summary refs log tree commit diff stats
diff options
context:
space:
mode:
-rw-r--r--audio/audio.h3
-rw-r--r--audio/audio_int.h3
-rw-r--r--audio/audio_pt_int.h2
-rw-r--r--audio/mixeng.h3
-rw-r--r--backends/msmouse.c122
-rw-r--r--block.c4
-rw-r--r--block/backup.c13
-rw-r--r--block/blkdebug.c4
-rwxr-xr-xblock/blkreplay.c2
-rw-r--r--block/block-backend.c9
-rw-r--r--block/commit.c30
-rw-r--r--block/gluster.c2
-rw-r--r--block/io.c45
-rw-r--r--block/iscsi.c5
-rw-r--r--block/linux-aio.c2
-rw-r--r--block/mirror.c32
-rw-r--r--block/nbd-client.c6
-rw-r--r--block/nfs.c2
-rw-r--r--block/qcow.c4
-rw-r--r--block/qcow2-cluster.c19
-rw-r--r--block/qcow2.c4
-rw-r--r--block/qed.c4
-rw-r--r--block/raw-posix.c10
-rw-r--r--block/sheepdog.c14
-rw-r--r--block/ssh.c2
-rw-r--r--block/stream.c28
-rw-r--r--block/vmdk.c18
-rw-r--r--block/vvfat.c3
-rw-r--r--blockdev.c119
-rw-r--r--blockjob.c42
-rw-r--r--bsd-user/i386/target_syscall.h2
-rw-r--r--bsd-user/sparc/target_syscall.h2
-rw-r--r--bsd-user/sparc64/target_syscall.h2
-rw-r--r--bsd-user/x86_64/target_syscall.h2
-rw-r--r--contrib/ivshmem-client/ivshmem-client.h6
-rw-r--r--contrib/ivshmem-server/ivshmem-server.h6
-rw-r--r--cputlb.c29
-rw-r--r--crypto/block-luks.h6
-rw-r--r--crypto/block-qcow.h6
-rw-r--r--crypto/blockpriv.h6
-rw-r--r--crypto/hash-gcrypt.c2
-rw-r--r--crypto/ivgenpriv.h6
-rw-r--r--crypto/pbkdf-gcrypt.c2
-rw-r--r--crypto/pbkdf-nettle.c2
-rw-r--r--crypto/tlscredspriv.h7
-rw-r--r--docs/qmp-events.txt12
-rw-r--r--docs/usb-storage.txt12
-rw-r--r--exec.c2
-rw-r--r--fsdev/9p-iov-marshal.c18
-rw-r--r--fsdev/9p-iov-marshal.h4
-rw-r--r--fsdev/9p-marshal.h4
-rw-r--r--fsdev/file-op-9p.h6
-rw-r--r--hmp.c6
-rw-r--r--hw/9pfs/9p-proxy.h5
-rw-r--r--hw/9pfs/9p-synth.h4
-rw-r--r--hw/9pfs/9p-xattr.h5
-rw-r--r--hw/9pfs/9p.c4
-rw-r--r--hw/9pfs/9p.h4
-rw-r--r--hw/9pfs/coth.c4
-rw-r--r--hw/9pfs/coth.h4
-rw-r--r--hw/9pfs/virtio-9p.h4
-rw-r--r--hw/alpha/alpha_sys.h4
-rw-r--r--hw/arm/strongarm.h4
-rw-r--r--hw/audio/fmopl.h4
-rw-r--r--hw/audio/gusemu.h2
-rw-r--r--hw/audio/gustate.h2
-rw-r--r--hw/audio/lm4549.h2
-rw-r--r--hw/audio/pl041.h2
-rw-r--r--hw/block/block.c28
-rw-r--r--hw/block/nvme.c9
-rw-r--r--hw/block/virtio-blk.c2
-rw-r--r--hw/block/xen_blkif.h6
-rw-r--r--hw/bt/hci.c10
-rw-r--r--hw/bt/l2cap.c12
-rw-r--r--hw/char/sclpconsole.c2
-rw-r--r--hw/core/qdev-properties-system.c39
-rw-r--r--hw/core/qdev-properties.c13
-rw-r--r--hw/core/uboot_image.h6
-rw-r--r--hw/cris/boot.h4
-rw-r--r--hw/display/qxl.h2
-rw-r--r--hw/display/vga.h6
-rw-r--r--hw/display/vga_int.h5
-rw-r--r--hw/display/virtio-gpu-3d.c2
-rw-r--r--hw/display/virtio-gpu.c2
-rw-r--r--hw/i386/kvm/i8254.c3
-rw-r--r--hw/i386/kvm/pci-assign.c3
-rw-r--r--hw/ide/ahci.c14
-rw-r--r--hw/ide/cmd646.c10
-rw-r--r--hw/ide/core.c10
-rw-r--r--hw/ide/ich.c14
-rw-r--r--hw/ide/isa.c8
-rw-r--r--hw/ide/macio.c2
-rw-r--r--hw/ide/microdrive.c8
-rw-r--r--hw/ide/mmio.c2
-rw-r--r--hw/ide/pci.c10
-rw-r--r--hw/ide/piix.c10
-rw-r--r--hw/ide/qdev.c6
-rw-r--r--hw/ide/via.c10
-rw-r--r--hw/input/hid.c3
-rw-r--r--hw/input/trace-events6
-rw-r--r--hw/input/virtio-input.c3
-rw-r--r--hw/intc/Makefile.objs1
-rw-r--r--hw/intc/gic_internal.h2
-rw-r--r--hw/intc/gicv3_internal.h2
-rw-r--r--hw/intc/mips_gic.c460
-rw-r--r--hw/lm32/lm32.h2
-rw-r--r--hw/lm32/milkymist-hw.h6
-rw-r--r--hw/microblaze/boot.h6
-rw-r--r--hw/mips/cps.c25
-rw-r--r--hw/mips/mips_malta.c4
-rw-r--r--hw/misc/hyperv_testdev.c2
-rw-r--r--hw/misc/mips_cmgcr.c87
-rw-r--r--hw/misc/mips_cpc.c5
-rw-r--r--hw/net/e1000_regs.h7
-rw-r--r--hw/net/fsl_etsec/etsec.h7
-rw-r--r--hw/net/fsl_etsec/registers.h6
-rw-r--r--hw/net/ne2000.h2
-rw-r--r--hw/net/pcnet.h2
-rw-r--r--hw/net/rocker/rocker.h6
-rw-r--r--hw/net/rocker/rocker_desc.h5
-rw-r--r--hw/net/rocker/rocker_fp.h6
-rw-r--r--hw/net/rocker/rocker_hw.h6
-rw-r--r--hw/net/rocker/rocker_of_dpa.h6
-rw-r--r--hw/net/rocker/rocker_tlv.h4
-rw-r--r--hw/net/rocker/rocker_world.h6
-rw-r--r--hw/net/vmxnet3.h4
-rw-r--r--hw/net/vmxnet_debug.h6
-rw-r--r--hw/pci-bridge/dec.h4
-rw-r--r--hw/pci-bridge/ioh3420.c9
-rw-r--r--hw/pci-bridge/xio3130_downstream.c9
-rw-r--r--hw/pci-bridge/xio3130_upstream.c10
-rw-r--r--hw/pci-bridge/xio3130_upstream.h2
-rw-r--r--hw/ppc/mac.h7
-rw-r--r--hw/ppc/ppc405.h6
-rw-r--r--hw/ppc/spapr_cpu_core.c4
-rw-r--r--hw/ppc/spapr_pci_vfio.c2
-rw-r--r--hw/s390x/Makefile.objs2
-rw-r--r--hw/s390x/ccw-device.c27
-rw-r--r--hw/s390x/ccw-device.h43
-rw-r--r--hw/s390x/css-bridge.c124
-rw-r--r--hw/s390x/css.c145
-rw-r--r--hw/s390x/ipl.c37
-rw-r--r--hw/s390x/ipl.h15
-rw-r--r--hw/s390x/s390-pci-bus.c585
-rw-r--r--hw/s390x/s390-pci-bus.h81
-rw-r--r--hw/s390x/s390-pci-inst.c270
-rw-r--r--hw/s390x/s390-pci-inst.h9
-rw-r--r--hw/s390x/s390-virtio-ccw.c3
-rw-r--r--hw/s390x/s390-virtio.h2
-rw-r--r--hw/s390x/sclpquiesce.c2
-rw-r--r--hw/s390x/virtio-ccw.c271
-rw-r--r--hw/s390x/virtio-ccw.h40
-rw-r--r--hw/scsi/mfi.h6
-rw-r--r--hw/scsi/scsi-disk.c2
-rw-r--r--hw/scsi/vhost-scsi.c4
-rw-r--r--hw/scsi/virtio-scsi-dataplane.c6
-rw-r--r--hw/scsi/virtio-scsi.c6
-rw-r--r--hw/scsi/vmw_pvscsi.c2
-rw-r--r--hw/sh4/sh7750_regnames.h6
-rw-r--r--hw/sh4/sh7750_regs.h4
-rw-r--r--hw/timer/Makefile.objs1
-rw-r--r--hw/timer/mips_gictimer.c142
-rw-r--r--hw/tpm/tpm_util.h7
-rw-r--r--hw/usb/dev-storage.c6
-rw-r--r--hw/usb/hcd-ehci.h5
-rw-r--r--hw/usb/hcd-xhci.c3
-rw-r--r--hw/usb/xen-usb.c5
-rw-r--r--hw/vfio/common.c6
-rw-r--r--hw/virtio/vhost-backend.c5
-rw-r--r--hw/xen/xen-host-pci-device.h2
-rw-r--r--hw/xen/xen_pt.h2
-rw-r--r--hw/xenpv/xen_domainbuild.h2
-rw-r--r--hw/xtensa/bootparam.h4
-rw-r--r--include/block/block_int.h47
-rw-r--r--include/block/blockjob.h26
-rw-r--r--include/block/scsi.h5
-rw-r--r--include/block/thread-pool.h2
-rw-r--r--include/crypto/afsplit.h6
-rw-r--r--include/crypto/block.h6
-rw-r--r--include/crypto/cipher.h6
-rw-r--r--include/crypto/desrfb.h5
-rw-r--r--include/crypto/hash.h6
-rw-r--r--include/crypto/init.h6
-rw-r--r--include/crypto/ivgen.h6
-rw-r--r--include/crypto/pbkdf.h6
-rw-r--r--include/crypto/random.h6
-rw-r--r--include/crypto/secret.h6
-rw-r--r--include/crypto/tlscreds.h7
-rw-r--r--include/crypto/tlscredsanon.h7
-rw-r--r--include/crypto/tlscredsx509.h7
-rw-r--r--include/crypto/tlssession.h6
-rw-r--r--include/crypto/xts.h7
-rw-r--r--include/disas/bfd.h6
-rw-r--r--include/disas/disas.h6
-rw-r--r--include/elf.h7
-rw-r--r--include/exec/address-spaces.h4
-rw-r--r--include/exec/cpu-common.h10
-rw-r--r--include/exec/exec-all.h8
-rw-r--r--include/exec/gen-icount.h2
-rw-r--r--include/exec/helper-gen.h4
-rw-r--r--include/exec/helper-head.h7
-rw-r--r--include/exec/helper-proto.h4
-rw-r--r--include/exec/helper-tcg.h4
-rw-r--r--include/exec/softmmu-semi.h3
-rw-r--r--include/exec/tb-context.h4
-rw-r--r--include/exec/tb-hash-xx.h9
-rw-r--r--include/exec/tb-hash.h4
-rw-r--r--include/exec/user/abitypes.h5
-rw-r--r--include/fpu/softfloat.h2
-rw-r--r--include/hw/acpi/acpi.h3
-rw-r--r--include/hw/acpi/aml-build.h4
-rw-r--r--include/hw/acpi/cpu_hotplug.h5
-rw-r--r--include/hw/arm/arm.h6
-rw-r--r--include/hw/arm/exynos4210.h7
-rw-r--r--include/hw/arm/pxa.h5
-rw-r--r--include/hw/arm/soc_dma.h3
-rw-r--r--include/hw/arm/stm32f205_soc.h4
-rw-r--r--include/hw/audio/audio.h4
-rw-r--r--include/hw/audio/pcspk.h2
-rw-r--r--include/hw/block/block.h17
-rw-r--r--include/hw/block/flash.h2
-rw-r--r--include/hw/bt.h2
-rw-r--r--include/hw/char/escc.h2
-rw-r--r--include/hw/char/lm32_juart.h2
-rw-r--r--include/hw/char/pl011.h4
-rw-r--r--include/hw/char/serial.h3
-rw-r--r--include/hw/cris/etraxfs.h4
-rw-r--r--include/hw/cris/etraxfs_dma.h2
-rw-r--r--include/hw/display/dpcd.h2
-rw-r--r--include/hw/dma/xlnx_dpdma.h2
-rw-r--r--include/hw/empty_slot.h2
-rw-r--r--include/hw/fw-path-provider.h2
-rw-r--r--include/hw/gpio/imx_gpio.h8
-rw-r--r--include/hw/i2c/i2c-ddc.h6
-rw-r--r--include/hw/i2c/imx_i2c.h8
-rw-r--r--include/hw/i2c/pm_smbus.h2
-rw-r--r--include/hw/i386/apic_internal.h3
-rw-r--r--include/hw/i386/ioapic.h2
-rw-r--r--include/hw/i386/ioapic_internal.h2
-rw-r--r--include/hw/ide/ahci.h2
-rw-r--r--include/hw/ide/internal.h4
-rw-r--r--include/hw/ide/pci.h2
-rw-r--r--include/hw/input/adb.h6
-rw-r--r--include/hw/input/ps2.h2
-rw-r--r--include/hw/intc/allwinner-a10-pic.h4
-rw-r--r--include/hw/intc/mips_gic.h216
-rw-r--r--include/hw/isa/i8257.h1
-rw-r--r--include/hw/isa/i8259_internal.h2
-rw-r--r--include/hw/mips/cps.h2
-rw-r--r--include/hw/misc/arm_integrator_debug.h5
-rw-r--r--include/hw/misc/auxbus.h6
-rw-r--r--include/hw/misc/mips_cmgcr.h33
-rw-r--r--include/hw/misc/tmp105_regs.h5
-rw-r--r--include/hw/net/allwinner_emac.h5
-rw-r--r--include/hw/nmi.h2
-rw-r--r--include/hw/nvram/openbios_firmware_abi.h6
-rw-r--r--include/hw/pci-host/apb.h4
-rw-r--r--include/hw/pci-host/ppce500.h4
-rw-r--r--include/hw/pci-host/spapr.h10
-rw-r--r--include/hw/pci/pci_bridge.h2
-rw-r--r--include/hw/pci/pci_ids.h3
-rw-r--r--include/hw/pcmcia.h2
-rw-r--r--include/hw/platform-bus.h4
-rw-r--r--include/hw/ppc/mac_dbdma.h3
-rw-r--r--include/hw/ppc/openpic.h6
-rw-r--r--include/hw/ppc/ppc.h2
-rw-r--r--include/hw/ppc/ppc4xx.h6
-rw-r--r--include/hw/ppc/spapr.h6
-rw-r--r--include/hw/ppc/spapr_drc.h9
-rw-r--r--include/hw/ppc/spapr_vio.h7
-rw-r--r--include/hw/ppc/xics.h7
-rw-r--r--include/hw/qdev-properties.h4
-rw-r--r--include/hw/s390x/css-bridge.h31
-rw-r--r--include/hw/s390x/css.h18
-rw-r--r--include/hw/s390x/ebcdic.h6
-rw-r--r--include/hw/s390x/event-facility.h2
-rw-r--r--include/hw/s390x/ioinst.h4
-rw-r--r--include/hw/s390x/s390_flic.h6
-rw-r--r--include/hw/s390x/sclp.h5
-rw-r--r--include/hw/s390x/storage-keys.h8
-rw-r--r--include/hw/sd/sd.h7
-rw-r--r--include/hw/sh4/sh_intc.h6
-rw-r--r--include/hw/smbios/smbios.h3
-rw-r--r--include/hw/sparc/grlib.h6
-rw-r--r--include/hw/ssi/xilinx_spips.h6
-rw-r--r--include/hw/stream.h2
-rw-r--r--include/hw/sysbus.h4
-rw-r--r--include/hw/timer/a9gtimer.h6
-rw-r--r--include/hw/timer/allwinner-a10-pit.h4
-rw-r--r--include/hw/timer/hpet.h5
-rw-r--r--include/hw/timer/i8254.h2
-rw-r--r--include/hw/timer/i8254_internal.h2
-rw-r--r--include/hw/timer/m48t59.h6
-rw-r--r--include/hw/timer/mc146818rtc.h2
-rw-r--r--include/hw/timer/mc146818rtc_regs.h5
-rw-r--r--include/hw/timer/mips_gictimer.h46
-rw-r--r--include/hw/tricore/tricore.h4
-rw-r--r--include/hw/unicore32/puv3.h3
-rw-r--r--include/hw/usb/ehci-regs.h2
-rw-r--r--include/hw/usb/uhci-regs.h2
-rw-r--r--include/hw/vfio/vfio-common.h3
-rw-r--r--include/hw/vfio/vfio-platform.h2
-rw-r--r--include/hw/vfio/vfio.h4
-rw-r--r--include/hw/virtio/vhost-backend.h7
-rw-r--r--include/hw/virtio/virtio-access.h8
-rw-r--r--include/hw/virtio/virtio-balloon.h4
-rw-r--r--include/hw/virtio/virtio-blk.h4
-rw-r--r--include/hw/virtio/virtio-gpu.h4
-rw-r--r--include/hw/virtio/virtio-input.h6
-rw-r--r--include/hw/virtio/virtio-net.h4
-rw-r--r--include/hw/virtio/virtio-rng.h4
-rw-r--r--include/hw/virtio/virtio-scsi.h6
-rw-r--r--include/hw/virtio/virtio-serial.h5
-rw-r--r--include/hw/virtio/virtio.h4
-rw-r--r--include/hw/watchdog/wdt_diag288.h2
-rw-r--r--include/hw/xen/xen.h3
-rw-r--r--include/hw/xen/xen_backend.h2
-rw-r--r--include/hw/xen/xen_common.h4
-rw-r--r--include/io/channel-buffer.h6
-rw-r--r--include/io/channel-command.h6
-rw-r--r--include/io/channel-file.h6
-rw-r--r--include/io/channel-socket.h6
-rw-r--r--include/io/channel-tls.h6
-rw-r--r--include/io/channel-util.h6
-rw-r--r--include/io/channel-watch.h6
-rw-r--r--include/io/channel-websock.h6
-rw-r--r--include/io/channel.h6
-rw-r--r--include/io/task.h6
-rw-r--r--include/libdecnumber/decContext.h5
-rw-r--r--include/libdecnumber/decNumber.h9
-rw-r--r--include/libdecnumber/decNumberLocal.h7
-rw-r--r--include/libdecnumber/dpd/decimal128.h9
-rw-r--r--include/libdecnumber/dpd/decimal32.h9
-rw-r--r--include/libdecnumber/dpd/decimal64.h9
-rw-r--r--include/migration/block.h6
-rw-r--r--include/migration/qemu-file.h4
-rw-r--r--include/migration/vmstate.h5
-rw-r--r--include/monitor/hmp-target.h7
-rw-r--r--include/monitor/monitor.h2
-rw-r--r--include/monitor/qdev.h4
-rw-r--r--include/net/vhost-user.h6
-rw-r--r--include/qapi/qmp/dispatch.h5
-rw-r--r--include/qapi/qmp/qerror.h3
-rw-r--r--include/qapi/qmp/types.h6
-rw-r--r--include/qapi/visitor.h5
-rw-r--r--include/qemu/acl.h14
-rw-r--r--include/qemu/atomic.h8
-rw-r--r--include/qemu/base64.h6
-rw-r--r--include/qemu/bcd.h2
-rw-r--r--include/qemu/bswap.h70
-rw-r--r--include/qemu/buffer.h6
-rw-r--r--include/qemu/config-file.h6
-rw-r--r--include/qemu/coroutine.h10
-rw-r--r--include/qemu/coroutine_int.h4
-rw-r--r--include/qemu/cutils.h2
-rw-r--r--include/qemu/error-report.h5
-rw-r--r--include/qemu/fifo8.h6
-rw-r--r--include/qemu/fprintf-fn.h3
-rw-r--r--include/qemu/hbitmap.h2
-rw-r--r--include/qemu/help_option.h2
-rw-r--r--include/qemu/host-utils.h3
-rw-r--r--include/qemu/id.h2
-rw-r--r--include/qemu/main-loop.h6
-rw-r--r--include/qemu/mmap-alloc.h4
-rw-r--r--include/qemu/option.h4
-rw-r--r--include/qemu/option_int.h4
-rw-r--r--include/qemu/osdep.h3
-rw-r--r--include/qemu/path.h2
-rw-r--r--include/qemu/queue.h6
-rw-r--r--include/qemu/ratelimit.h45
-rw-r--r--include/qemu/rcu_queue.h2
-rw-r--r--include/qemu/readline.h2
-rw-r--r--include/qemu/seqlock.h7
-rw-r--r--include/qemu/sockets.h8
-rw-r--r--include/qemu/thread-posix.h7
-rw-r--r--include/qemu/thread-win32.h7
-rw-r--r--include/qemu/thread.h4
-rw-r--r--include/qemu/unicode.h2
-rw-r--r--include/qom/cpu.h15
-rw-r--r--include/sysemu/balloon.h4
-rw-r--r--include/sysemu/bt.h4
-rw-r--r--include/sysemu/device_tree.h6
-rw-r--r--include/sysemu/hostmem.h5
-rw-r--r--include/sysemu/tpm_backend.h4
-rw-r--r--include/sysemu/tpm_backend_int.h7
-rw-r--r--include/sysemu/xen-mapcache.h3
-rw-r--r--include/trace-tcg.h2
-rw-r--r--include/trace.h2
-rw-r--r--io/channel.c2
-rw-r--r--linux-user/aarch64/target_cpu.h4
-rw-r--r--linux-user/aarch64/target_signal.h6
-rw-r--r--linux-user/aarch64/target_structs.h4
-rw-r--r--linux-user/aarch64/target_syscall.h6
-rw-r--r--linux-user/alpha/target_cpu.h4
-rw-r--r--linux-user/alpha/target_signal.h6
-rw-r--r--linux-user/alpha/target_structs.h4
-rw-r--r--linux-user/alpha/target_syscall.h6
-rw-r--r--linux-user/arm/nwfpe/fpa11.h7
-rw-r--r--linux-user/arm/nwfpe/fpopcode.h4
-rw-r--r--linux-user/arm/nwfpe/fpsr.h4
-rw-r--r--linux-user/arm/target_cpu.h4
-rw-r--r--linux-user/arm/target_signal.h6
-rw-r--r--linux-user/arm/target_structs.h4
-rw-r--r--linux-user/arm/target_syscall.h6
-rw-r--r--linux-user/cris/target_cpu.h4
-rw-r--r--linux-user/cris/target_signal.h6
-rw-r--r--linux-user/cris/target_structs.h4
-rw-r--r--linux-user/cris/target_syscall.h4
-rw-r--r--linux-user/flatload.c2
-rw-r--r--linux-user/host/aarch64/hostdep.h4
-rw-r--r--linux-user/host/arm/hostdep.h4
-rw-r--r--linux-user/host/i386/hostdep.h4
-rw-r--r--linux-user/host/ia64/hostdep.h4
-rw-r--r--linux-user/host/mips/hostdep.h4
-rw-r--r--linux-user/host/ppc/hostdep.h4
-rw-r--r--linux-user/host/ppc64/hostdep.h4
-rw-r--r--linux-user/host/s390/hostdep.h4
-rw-r--r--linux-user/host/s390x/hostdep.h4
-rw-r--r--linux-user/host/sparc/hostdep.h4
-rw-r--r--linux-user/host/sparc64/hostdep.h4
-rw-r--r--linux-user/host/x32/hostdep.h4
-rw-r--r--linux-user/host/x86_64/hostdep.h4
-rw-r--r--linux-user/i386/target_cpu.h6
-rw-r--r--linux-user/i386/target_signal.h6
-rw-r--r--linux-user/i386/target_structs.h4
-rw-r--r--linux-user/i386/target_syscall.h6
-rw-r--r--linux-user/linux_loop.h5
-rw-r--r--linux-user/m68k/target_cpu.h4
-rw-r--r--linux-user/m68k/target_signal.h6
-rw-r--r--linux-user/m68k/target_structs.h4
-rw-r--r--linux-user/m68k/target_syscall.h6
-rw-r--r--linux-user/microblaze/target_cpu.h4
-rw-r--r--linux-user/microblaze/target_signal.h6
-rw-r--r--linux-user/microblaze/target_structs.h4
-rw-r--r--linux-user/microblaze/target_syscall.h4
-rw-r--r--linux-user/mips/target_cpu.h4
-rw-r--r--linux-user/mips/target_signal.h6
-rw-r--r--linux-user/mips/target_structs.h4
-rw-r--r--linux-user/mips/target_syscall.h6
-rw-r--r--linux-user/mips64/target_signal.h6
-rw-r--r--linux-user/mips64/target_syscall.h6
-rw-r--r--linux-user/openrisc/target_cpu.h4
-rw-r--r--linux-user/openrisc/target_signal.h6
-rw-r--r--linux-user/openrisc/target_structs.h4
-rw-r--r--linux-user/openrisc/target_syscall.h6
-rw-r--r--linux-user/ppc/target_cpu.h4
-rw-r--r--linux-user/ppc/target_signal.h6
-rw-r--r--linux-user/ppc/target_structs.h4
-rw-r--r--linux-user/ppc/target_syscall.h6
-rw-r--r--linux-user/s390x/target_cpu.h4
-rw-r--r--linux-user/s390x/target_signal.h6
-rw-r--r--linux-user/s390x/target_structs.h4
-rw-r--r--linux-user/s390x/target_syscall.h6
-rw-r--r--linux-user/sh4/target_cpu.h4
-rw-r--r--linux-user/sh4/target_signal.h6
-rw-r--r--linux-user/sh4/target_structs.h4
-rw-r--r--linux-user/sh4/target_syscall.h6
-rw-r--r--linux-user/sparc/target_cpu.h4
-rw-r--r--linux-user/sparc/target_signal.h6
-rw-r--r--linux-user/sparc/target_structs.h4
-rw-r--r--linux-user/sparc/target_syscall.h6
-rw-r--r--linux-user/sparc64/target_signal.h6
-rw-r--r--linux-user/sparc64/target_structs.h4
-rw-r--r--linux-user/sparc64/target_syscall.h6
-rw-r--r--linux-user/syscall_defs.h7
-rw-r--r--linux-user/tilegx/syscall_nr.h4
-rw-r--r--linux-user/tilegx/target_cpu.h4
-rw-r--r--linux-user/tilegx/target_signal.h6
-rw-r--r--linux-user/tilegx/target_structs.h4
-rw-r--r--linux-user/tilegx/target_syscall.h4
-rw-r--r--linux-user/uname.h4
-rw-r--r--linux-user/unicore32/target_cpu.h4
-rw-r--r--linux-user/unicore32/target_signal.h6
-rw-r--r--linux-user/unicore32/target_structs.h4
-rw-r--r--linux-user/unicore32/target_syscall.h8
-rw-r--r--linux-user/x86_64/target_signal.h6
-rw-r--r--linux-user/x86_64/target_structs.h4
-rw-r--r--linux-user/x86_64/target_syscall.h6
-rw-r--r--migration/migration.c4
-rw-r--r--migration/savevm.c103
-rw-r--r--monitor.c11
-rw-r--r--nbd/server.c12
-rw-r--r--net/tap-linux.h2
-rw-r--r--net/tap_int.h6
-rw-r--r--pc-bios/s390-ccw.imgbin26424 -> 26440 bytes
-rw-r--r--pc-bios/s390-ccw/iplb.h12
-rw-r--r--pc-bios/s390-ccw/main.c12
-rw-r--r--pc-bios/s390-ccw/virtio-scsi.c11
-rw-r--r--pc-bios/s390-ccw/virtio.h2
-rw-r--r--qapi/block-core.json94
-rw-r--r--qemu-img.c4
-rw-r--r--qemu-io-cmds.c18
-rw-r--r--qemu-options.h4
-rw-r--r--qga/service-win32.h5
-rw-r--r--qga/vss-win32/install.cpp3
-rw-r--r--qga/vss-win32/provider.cpp4
-rw-r--r--qga/vss-win32/requester.cpp4
-rw-r--r--qga/vss-win32/vss-common.h6
-rw-r--r--qmp-commands.hx28
m---------roms/openbios0
-rwxr-xr-xscripts/clean-header-guards.pl213
-rw-r--r--slirp/bootp.c2
-rw-r--r--slirp/bootp.h3
-rw-r--r--slirp/cksum.c2
-rw-r--r--slirp/if.c2
-rw-r--r--slirp/if.h4
-rw-r--r--slirp/ip.h4
-rw-r--r--slirp/ip6.h4
-rw-r--r--slirp/ip6_icmp.h4
-rw-r--r--slirp/ip_icmp.h4
-rw-r--r--slirp/ip_input.c2
-rw-r--r--slirp/ip_output.c2
-rw-r--r--slirp/libslirp.h4
-rw-r--r--slirp/main.h3
-rw-r--r--slirp/mbuf.c2
-rw-r--r--slirp/mbuf.h4
-rw-r--r--slirp/misc.c5
-rw-r--r--slirp/misc.h4
-rw-r--r--slirp/sbuf.c4
-rw-r--r--slirp/sbuf.h4
-rw-r--r--slirp/slirp.h4
-rw-r--r--slirp/socket.c2
-rw-r--r--slirp/socket.h6
-rw-r--r--slirp/tcp.h4
-rw-r--r--slirp/tcp_input.c2
-rw-r--r--slirp/tcp_output.c2
-rw-r--r--slirp/tcp_subr.c2
-rw-r--r--slirp/tcp_timer.c2
-rw-r--r--slirp/tcp_timer.h4
-rw-r--r--slirp/tcp_var.h4
-rw-r--r--slirp/tcpip.h4
-rw-r--r--slirp/tftp.c2
-rw-r--r--slirp/tftp.h3
-rw-r--r--slirp/udp.c2
-rw-r--r--slirp/udp.h4
-rw-r--r--softmmu_template.h79
-rw-r--r--target-alpha/cpu.h9
-rw-r--r--target-alpha/mem_helper.c7
-rw-r--r--target-arm/arm-powerctl.c4
-rw-r--r--target-arm/cpu.h4
-rw-r--r--target-arm/internals.h5
-rw-r--r--target-arm/op_helper.c30
-rw-r--r--target-arm/psci.c8
-rw-r--r--target-cris/cpu.h5
-rw-r--r--target-cris/crisv32-decode.h3
-rw-r--r--target-cris/op_helper.c6
-rw-r--r--target-i386/cpu.h7
-rw-r--r--target-i386/hyperv.h4
-rw-r--r--target-i386/mem_helper.c6
-rw-r--r--target-i386/svm.h4
-rw-r--r--target-lm32/cpu.h4
-rw-r--r--target-lm32/op_helper.c6
-rw-r--r--target-m68k/cpu.h5
-rw-r--r--target-m68k/op_helper.c6
-rw-r--r--target-microblaze/cpu.h5
-rw-r--r--target-microblaze/op_helper.c6
-rw-r--r--target-mips/cpu.h16
-rw-r--r--target-mips/helper.c16
-rw-r--r--target-mips/kvm_mips.h6
-rw-r--r--target-mips/machine.c10
-rw-r--r--target-mips/mips-defs.h6
-rw-r--r--target-mips/op_helper.c43
-rw-r--r--target-mips/translate.c11
-rw-r--r--target-mips/translate_init.c22
-rw-r--r--target-moxie/cpu.h7
-rw-r--r--target-moxie/helper.c6
-rw-r--r--target-openrisc/cpu.h6
-rw-r--r--target-openrisc/exception.h6
-rw-r--r--target-openrisc/mmu_helper.c4
-rw-r--r--target-ppc/cpu.h7
-rw-r--r--target-ppc/helper_regs.h6
-rw-r--r--target-ppc/kvm_ppc.h6
-rw-r--r--target-ppc/mmu-hash32.h6
-rw-r--r--target-ppc/mmu-hash64.h6
-rw-r--r--target-ppc/mmu_helper.c8
-rw-r--r--target-ppc/translate_init.c2
-rw-r--r--target-s390x/cpu.h7
-rw-r--r--target-s390x/kvm.c4
-rw-r--r--target-s390x/mem_helper.c6
-rw-r--r--target-sh4/cpu.h7
-rw-r--r--target-sh4/op_helper.c6
-rw-r--r--target-sparc/asi.h311
-rw-r--r--target-sparc/cpu.h39
-rw-r--r--target-sparc/fop_helper.c230
-rw-r--r--target-sparc/helper.h168
-rw-r--r--target-sparc/ldst_helper.c709
-rw-r--r--target-sparc/translate.c1273
-rw-r--r--target-tilegx/cpu.h5
-rw-r--r--target-tilegx/opcode_tilegx.h6
-rw-r--r--target-tricore/cpu-qom.h2
-rw-r--r--target-tricore/cpu.h7
-rw-r--r--target-tricore/op_helper.c6
-rw-r--r--target-tricore/tricore-defs.h6
-rw-r--r--target-unicore32/cpu.h7
-rw-r--r--target-unicore32/op_helper.c4
-rw-r--r--target-unicore32/softmmu.c2
-rw-r--r--target-xtensa/core-dc232b/core-isa.h7
-rw-r--r--target-xtensa/core-dc233c/core-isa.h7
-rw-r--r--target-xtensa/core-fsf/core-isa.h7
-rw-r--r--target-xtensa/cpu.h7
-rw-r--r--target-xtensa/op_helper.c11
-rw-r--r--tcg/aarch64/tcg-target.h6
-rw-r--r--tcg/arm/tcg-target.h5
-rw-r--r--tcg/i386/tcg-target.h5
-rw-r--r--tcg/ia64/tcg-target.h5
-rw-r--r--tcg/mips/tcg-target.h5
-rw-r--r--tcg/ppc/tcg-target.h5
-rw-r--r--tcg/s390/tcg-target.h5
-rw-r--r--tcg/sparc/tcg-target.h5
-rw-r--r--tcg/tci/tcg-target.h3
-rw-r--r--tests/boot-sector.h6
-rw-r--r--tests/libqos/ahci.h4
-rw-r--r--tests/libqos/libqos-pc.h4
-rw-r--r--tests/libqos/libqos.h4
-rw-r--r--tests/postcopy-test.c3
-rwxr-xr-xtests/qemu-iotests/09398
-rw-r--r--tests/qemu-iotests/093.out4
-rwxr-xr-xtests/qemu-iotests/15789
-rw-r--r--tests/qemu-iotests/157.out22
-rw-r--r--tests/qemu-iotests/group1
-rw-r--r--tests/tcg/xtensa/linker.ld.S2
-rw-r--r--tests/test-blockjob-txn.c11
-rw-r--r--tests/test-coroutine.c65
-rw-r--r--tests/test-thread-pool.c4
-rw-r--r--tests/vhost-user-bridge.c2
-rw-r--r--tests/vhost-user-test.c2
-rw-r--r--thread-pool.c2
-rw-r--r--trace/control-internal.h4
-rw-r--r--trace/control.h2
-rw-r--r--trace/event-internal.h2
-rw-r--r--trace/ftrace.h4
-rw-r--r--trace/mem-internal.h2
-rw-r--r--trace/mem.h2
-rw-r--r--translate-all.c10
-rw-r--r--ui/curses_keys.h2
-rw-r--r--ui/input-linux.c269
-rw-r--r--ui/keymaps.h6
-rw-r--r--ui/sdl_zoom.h6
-rw-r--r--ui/vnc-auth-sasl.h9
-rw-r--r--ui/vnc-auth-vencrypt.h7
-rw-r--r--ui/vnc-enc-tight.c23
-rw-r--r--ui/vnc-enc-tight.h6
-rw-r--r--ui/vnc-enc-zrle.h4
-rw-r--r--ui/vnc-enc-zywrle.h4
-rw-r--r--ui/vnc-ws.h6
-rw-r--r--ui/vnc.c15
-rw-r--r--ui/vnc.h6
-rw-r--r--util/acl.c9
-rw-r--r--util/mmap-alloc.c3
-rw-r--r--util/osdep.c23
-rw-r--r--util/oslib-posix.c2
-rw-r--r--util/qemu-coroutine-io.c2
-rw-r--r--util/qemu-coroutine-lock.c26
-rw-r--r--util/qemu-coroutine-sleep.c2
-rw-r--r--util/qemu-coroutine.c10
655 files changed, 6782 insertions, 3569 deletions
diff --git a/audio/audio.h b/audio/audio.h
index b41a97053d..11e56c9d17 100644
--- a/audio/audio.h
+++ b/audio/audio.h
@@ -21,6 +21,7 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
+
 #ifndef QEMU_AUDIO_H
 #define QEMU_AUDIO_H
 
@@ -162,4 +163,4 @@ static inline void *advance (void *p, int incr)
 int wav_start_capture (CaptureState *s, const char *path, int freq,
                        int bits, int nchannels);
 
-#endif  /* audio.h */
+#endif /* QEMU_AUDIO_H */
diff --git a/audio/audio_int.h b/audio/audio_int.h
index 566df5edf4..5bcb1c60e1 100644
--- a/audio/audio_int.h
+++ b/audio/audio_int.h
@@ -21,6 +21,7 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
+
 #ifndef QEMU_AUDIO_INT_H
 #define QEMU_AUDIO_INT_H
 
@@ -257,4 +258,4 @@ static inline int audio_ring_dist (int dst, int src, int len)
 #define AUDIO_FUNC __FILE__ ":" AUDIO_STRINGIFY (__LINE__)
 #endif
 
-#endif /* audio_int.h */
+#endif /* QEMU_AUDIO_INT_H */
diff --git a/audio/audio_pt_int.h b/audio/audio_pt_int.h
index 0dfff76aa3..4c0c15b9af 100644
--- a/audio/audio_pt_int.h
+++ b/audio/audio_pt_int.h
@@ -19,4 +19,4 @@ int audio_pt_wait (struct audio_pt *, const char *);
 int audio_pt_unlock_and_signal (struct audio_pt *, const char *);
 int audio_pt_join (struct audio_pt *, void **, const char *);
 
-#endif /* audio_pt_int.h */
+#endif /* QEMU_AUDIO_PT_INT_H */
diff --git a/audio/mixeng.h b/audio/mixeng.h
index 9de443b01d..b53a5ef99a 100644
--- a/audio/mixeng.h
+++ b/audio/mixeng.h
@@ -21,6 +21,7 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
+
 #ifndef QEMU_MIXENG_H
 #define QEMU_MIXENG_H
 
@@ -48,4 +49,4 @@ void st_rate_stop (void *opaque);
 void mixeng_clear (struct st_sample *buf, int len);
 void mixeng_volume (struct st_sample *buf, int len, struct mixeng_volume *vol);
 
-#endif  /* mixeng.h */
+#endif /* QEMU_MIXENG_H */
diff --git a/backends/msmouse.c b/backends/msmouse.c
index 8dea5a130f..aeb905562d 100644
--- a/backends/msmouse.c
+++ b/backends/msmouse.c
@@ -25,16 +25,51 @@
 #include "qemu-common.h"
 #include "sysemu/char.h"
 #include "ui/console.h"
+#include "ui/input.h"
 
 #define MSMOUSE_LO6(n) ((n) & 0x3f)
 #define MSMOUSE_HI2(n) (((n) & 0xc0) >> 6)
 
-static void msmouse_event(void *opaque,
-                          int dx, int dy, int dz, int buttons_state)
+typedef struct {
+    CharDriverState *chr;
+    QemuInputHandlerState *hs;
+    int axis[INPUT_AXIS__MAX];
+    bool btns[INPUT_BUTTON__MAX];
+    bool btnc[INPUT_BUTTON__MAX];
+    uint8_t outbuf[32];
+    int outlen;
+} MouseState;
+
+static void msmouse_chr_accept_input(CharDriverState *chr)
 {
-    CharDriverState *chr = (CharDriverState *)opaque;
+    MouseState *mouse = chr->opaque;
+    int len;
+
+    len = qemu_chr_be_can_write(chr);
+    if (len > mouse->outlen) {
+        len = mouse->outlen;
+    }
+    if (!len) {
+        return;
+    }
+
+    qemu_chr_be_write(chr, mouse->outbuf, len);
+    mouse->outlen -= len;
+    if (mouse->outlen) {
+        memmove(mouse->outbuf, mouse->outbuf + len, mouse->outlen);
+    }
+}
 
+static void msmouse_queue_event(MouseState *mouse)
+{
     unsigned char bytes[4] = { 0x40, 0x00, 0x00, 0x00 };
+    int dx, dy, count = 3;
+
+    dx = mouse->axis[INPUT_AXIS_X];
+    mouse->axis[INPUT_AXIS_X] = 0;
+
+    dy = mouse->axis[INPUT_AXIS_Y];
+    mouse->axis[INPUT_AXIS_Y] = 0;
 
     /* Movement deltas */
     bytes[0] |= (MSMOUSE_HI2(dy) << 2) | MSMOUSE_HI2(dx);
@@ -42,14 +77,54 @@ static void msmouse_event(void *opaque,
     bytes[2] |= MSMOUSE_LO6(dy);
 
     /* Buttons */
-    bytes[0] |= (buttons_state & 0x01 ? 0x20 : 0x00);
-    bytes[0] |= (buttons_state & 0x02 ? 0x10 : 0x00);
-    bytes[3] |= (buttons_state & 0x04 ? 0x20 : 0x00);
-
-    /* We always send the packet of, so that we do not have to keep track
-       of previous state of the middle button. This can potentially confuse
-       some very old drivers for two button mice though. */
-    qemu_chr_be_write(chr, bytes, 4);
+    bytes[0] |= (mouse->btns[INPUT_BUTTON_LEFT]   ? 0x20 : 0x00);
+    bytes[0] |= (mouse->btns[INPUT_BUTTON_RIGHT]  ? 0x10 : 0x00);
+    if (mouse->btns[INPUT_BUTTON_MIDDLE] ||
+        mouse->btnc[INPUT_BUTTON_MIDDLE]) {
+        bytes[3] |= (mouse->btns[INPUT_BUTTON_MIDDLE] ? 0x20 : 0x00);
+        mouse->btnc[INPUT_BUTTON_MIDDLE] = false;
+        count = 4;
+    }
+
+    if (mouse->outlen <= sizeof(mouse->outbuf) - count) {
+        memcpy(mouse->outbuf + mouse->outlen, bytes, count);
+        mouse->outlen += count;
+    } else {
+        /* queue full -> drop event */
+    }
+}
+
+static void msmouse_input_event(DeviceState *dev, QemuConsole *src,
+                                InputEvent *evt)
+{
+    MouseState *mouse = (MouseState *)dev;
+    InputMoveEvent *move;
+    InputBtnEvent *btn;
+
+    switch (evt->type) {
+    case INPUT_EVENT_KIND_REL:
+        move = evt->u.rel.data;
+        mouse->axis[move->axis] += move->value;
+        break;
+
+    case INPUT_EVENT_KIND_BTN:
+        btn = evt->u.btn.data;
+        mouse->btns[btn->button] = btn->down;
+        mouse->btnc[btn->button] = true;
+        break;
+
+    default:
+        /* keep gcc happy */
+        break;
+    }
+}
+
+static void msmouse_input_sync(DeviceState *dev)
+{
+    MouseState *mouse = (MouseState *)dev;
+
+    msmouse_queue_event(mouse);
+    msmouse_chr_accept_input(mouse->chr);
 }
 
 static int msmouse_chr_write (struct CharDriverState *s, const uint8_t *buf, int len)
@@ -60,26 +135,41 @@ static int msmouse_chr_write (struct CharDriverState *s, const uint8_t *buf, int
 
 static void msmouse_chr_close (struct CharDriverState *chr)
 {
-    g_free (chr);
+    MouseState *mouse = chr->opaque;
+
+    qemu_input_handler_unregister(mouse->hs);
+    g_free(mouse);
+    g_free(chr);
 }
 
+static QemuInputHandler msmouse_handler = {
+    .name  = "QEMU Microsoft Mouse",
+    .mask  = INPUT_EVENT_MASK_BTN | INPUT_EVENT_MASK_REL,
+    .event = msmouse_input_event,
+    .sync  = msmouse_input_sync,
+};
+
 static CharDriverState *qemu_chr_open_msmouse(const char *id,
                                               ChardevBackend *backend,
                                               ChardevReturn *ret,
                                               Error **errp)
 {
     ChardevCommon *common = backend->u.msmouse.data;
+    MouseState *mouse;
     CharDriverState *chr;
 
     chr = qemu_chr_alloc(common, errp);
-    if (!chr) {
-        return NULL;
-    }
     chr->chr_write = msmouse_chr_write;
     chr->chr_close = msmouse_chr_close;
+    chr->chr_accept_input = msmouse_chr_accept_input;
     chr->explicit_be_open = true;
 
-    qemu_add_mouse_event_handler(msmouse_event, chr, 0, "QEMU Microsoft Mouse");
+    mouse = g_new0(MouseState, 1);
+    mouse->hs = qemu_input_handler_register((DeviceState *)mouse,
+                                            &msmouse_handler);
+
+    mouse->chr = chr;
+    chr->opaque = mouse;
 
     return chr;
 }
diff --git a/block.c b/block.c
index 823ff1d7ab..67894e0719 100644
--- a/block.c
+++ b/block.c
@@ -329,8 +329,8 @@ int bdrv_create(BlockDriver *drv, const char* filename,
         /* Fast-path if already in coroutine context */
         bdrv_create_co_entry(&cco);
     } else {
-        co = qemu_coroutine_create(bdrv_create_co_entry);
-        qemu_coroutine_enter(co, &cco);
+        co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
+        qemu_coroutine_enter(co);
         while (cco.ret == NOT_DONE) {
             aio_poll(qemu_get_aio_context(), true);
         }
diff --git a/block/backup.c b/block/backup.c
index f87f8d539b..2c0532314f 100644
--- a/block/backup.c
+++ b/block/backup.c
@@ -474,9 +474,9 @@ static void coroutine_fn backup_run(void *opaque)
     block_job_defer_to_main_loop(&job->common, backup_complete, data);
 }
 
-void backup_start(BlockDriverState *bs, BlockDriverState *target,
-                  int64_t speed, MirrorSyncMode sync_mode,
-                  BdrvDirtyBitmap *sync_bitmap,
+void backup_start(const char *job_id, BlockDriverState *bs,
+                  BlockDriverState *target, int64_t speed,
+                  MirrorSyncMode sync_mode, BdrvDirtyBitmap *sync_bitmap,
                   BlockdevOnError on_source_error,
                   BlockdevOnError on_target_error,
                   BlockCompletionFunc *cb, void *opaque,
@@ -541,7 +541,8 @@ void backup_start(BlockDriverState *bs, BlockDriverState *target,
         goto error;
     }
 
-    job = block_job_create(&backup_job_driver, bs, speed, cb, opaque, errp);
+    job = block_job_create(job_id, &backup_job_driver, bs, speed,
+                           cb, opaque, errp);
     if (!job) {
         goto error;
     }
@@ -575,9 +576,9 @@ void backup_start(BlockDriverState *bs, BlockDriverState *target,
 
     bdrv_op_block_all(target, job->common.blocker);
     job->common.len = len;
-    job->common.co = qemu_coroutine_create(backup_run);
+    job->common.co = qemu_coroutine_create(backup_run, job);
     block_job_txn_add_job(txn, &job->common);
-    qemu_coroutine_enter(job->common.co, job);
+    qemu_coroutine_enter(job->common.co);
     return;
 
  error:
diff --git a/block/blkdebug.c b/block/blkdebug.c
index bbaa33fdd8..fb29283f80 100644
--- a/block/blkdebug.c
+++ b/block/blkdebug.c
@@ -621,7 +621,7 @@ static int blkdebug_debug_resume(BlockDriverState *bs, const char *tag)
 
     QLIST_FOREACH_SAFE(r, &s->suspended_reqs, next, next) {
         if (!strcmp(r->tag, tag)) {
-            qemu_coroutine_enter(r->co, NULL);
+            qemu_coroutine_enter(r->co);
             return 0;
         }
     }
@@ -647,7 +647,7 @@ static int blkdebug_debug_remove_breakpoint(BlockDriverState *bs,
     }
     QLIST_FOREACH_SAFE(r, &s->suspended_reqs, next, r_next) {
         if (!strcmp(r->tag, tag)) {
-            qemu_coroutine_enter(r->co, NULL);
+            qemu_coroutine_enter(r->co);
             ret = 0;
         }
     }
diff --git a/block/blkreplay.c b/block/blkreplay.c
index 70650e4be1..3368c8c98d 100755
--- a/block/blkreplay.c
+++ b/block/blkreplay.c
@@ -65,7 +65,7 @@ static int64_t blkreplay_getlength(BlockDriverState *bs)
 static void blkreplay_bh_cb(void *opaque)
 {
     Request *req = opaque;
-    qemu_coroutine_enter(req->co, NULL);
+    qemu_coroutine_enter(req->co);
     qemu_bh_delete(req->bh);
     g_free(req);
 }
diff --git a/block/block-backend.c b/block/block-backend.c
index a862f6577b..f9cea1b304 100644
--- a/block/block-backend.c
+++ b/block/block-backend.c
@@ -836,8 +836,8 @@ static int blk_prw(BlockBackend *blk, int64_t offset, uint8_t *buf,
         .ret    = NOT_DONE,
     };
 
-    co = qemu_coroutine_create(co_entry);
-    qemu_coroutine_enter(co, &rwco);
+    co = qemu_coroutine_create(co_entry, &rwco);
+    qemu_coroutine_enter(co);
 
     aio_context = blk_get_aio_context(blk);
     while (rwco.ret == NOT_DONE) {
@@ -950,8 +950,8 @@ static BlockAIOCB *blk_aio_prwv(BlockBackend *blk, int64_t offset, int bytes,
     acb->bh = NULL;
     acb->has_returned = false;
 
-    co = qemu_coroutine_create(co_entry);
-    qemu_coroutine_enter(co, acb);
+    co = qemu_coroutine_create(co_entry, acb);
+    qemu_coroutine_enter(co);
 
     acb->has_returned = true;
     if (acb->rwco.ret != NOT_DONE) {
@@ -1173,6 +1173,7 @@ BlockErrorAction blk_get_error_action(BlockBackend *blk, bool is_read,
         return BLOCK_ERROR_ACTION_REPORT;
     case BLOCKDEV_ON_ERROR_IGNORE:
         return BLOCK_ERROR_ACTION_IGNORE;
+    case BLOCKDEV_ON_ERROR_AUTO:
     default:
         abort();
     }
diff --git a/block/commit.c b/block/commit.c
index 379efb7c92..553e18da52 100644
--- a/block/commit.c
+++ b/block/commit.c
@@ -113,6 +113,7 @@ static void coroutine_fn commit_run(void *opaque)
     CommitBlockJob *s = opaque;
     CommitCompleteData *data;
     int64_t sector_num, end;
+    uint64_t delay_ns = 0;
     int ret = 0;
     int n = 0;
     void *buf = NULL;
@@ -142,10 +143,8 @@ static void coroutine_fn commit_run(void *opaque)
     buf = blk_blockalign(s->top, COMMIT_BUFFER_SIZE);
 
     for (sector_num = 0; sector_num < end; sector_num += n) {
-        uint64_t delay_ns = 0;
         bool copy;
 
-wait:
         /* Note that even when no rate limit is applied we need to yield
          * with no pending I/O here so that bdrv_drain_all() returns.
          */
@@ -161,19 +160,13 @@ wait:
         copy = (ret == 1);
         trace_commit_one_iteration(s, sector_num, n, ret);
         if (copy) {
-            if (s->common.speed) {
-                delay_ns = ratelimit_calculate_delay(&s->limit, n);
-                if (delay_ns > 0) {
-                    goto wait;
-                }
-            }
             ret = commit_populate(s->top, s->base, sector_num, n, buf);
             bytes_written += n * BDRV_SECTOR_SIZE;
         }
         if (ret < 0) {
-            if (s->on_error == BLOCKDEV_ON_ERROR_STOP ||
-                s->on_error == BLOCKDEV_ON_ERROR_REPORT||
-                (s->on_error == BLOCKDEV_ON_ERROR_ENOSPC && ret == -ENOSPC)) {
+            BlockErrorAction action =
+                block_job_error_action(&s->common, false, s->on_error, -ret);
+            if (action == BLOCK_ERROR_ACTION_REPORT) {
                 goto out;
             } else {
                 n = 0;
@@ -182,6 +175,10 @@ wait:
         }
         /* Publish progress */
         s->common.offset += n * BDRV_SECTOR_SIZE;
+
+        if (copy && s->common.speed) {
+            delay_ns = ratelimit_calculate_delay(&s->limit, n);
+        }
     }
 
     ret = 0;
@@ -211,8 +208,8 @@ static const BlockJobDriver commit_job_driver = {
     .set_speed     = commit_set_speed,
 };
 
-void commit_start(BlockDriverState *bs, BlockDriverState *base,
-                  BlockDriverState *top, int64_t speed,
+void commit_start(const char *job_id, BlockDriverState *bs,
+                  BlockDriverState *base, BlockDriverState *top, int64_t speed,
                   BlockdevOnError on_error, BlockCompletionFunc *cb,
                   void *opaque, const char *backing_file_str, Error **errp)
 {
@@ -236,7 +233,8 @@ void commit_start(BlockDriverState *bs, BlockDriverState *base,
         return;
     }
 
-    s = block_job_create(&commit_job_driver, bs, speed, cb, opaque, errp);
+    s = block_job_create(job_id, &commit_job_driver, bs, speed,
+                         cb, opaque, errp);
     if (!s) {
         return;
     }
@@ -277,10 +275,10 @@ void commit_start(BlockDriverState *bs, BlockDriverState *base,
     s->backing_file_str = g_strdup(backing_file_str);
 
     s->on_error = on_error;
-    s->common.co = qemu_coroutine_create(commit_run);
+    s->common.co = qemu_coroutine_create(commit_run, s);
 
     trace_commit_start(bs, base, top, s, s->common.co, opaque);
-    qemu_coroutine_enter(s->common.co, s);
+    qemu_coroutine_enter(s->common.co);
 }
 
 
diff --git a/block/gluster.c b/block/gluster.c
index 16f7778a50..406c1e6357 100644
--- a/block/gluster.c
+++ b/block/gluster.c
@@ -233,7 +233,7 @@ static void qemu_gluster_complete_aio(void *opaque)
 
     qemu_bh_delete(acb->bh);
     acb->bh = NULL;
-    qemu_coroutine_enter(acb->coroutine, NULL);
+    qemu_coroutine_enter(acb->coroutine);
 }
 
 /*
diff --git a/block/io.c b/block/io.c
index 708690898f..2887394633 100644
--- a/block/io.c
+++ b/block/io.c
@@ -195,7 +195,7 @@ static void bdrv_co_drain_bh_cb(void *opaque)
     qemu_bh_delete(data->bh);
     bdrv_drain_poll(data->bs);
     data->done = true;
-    qemu_coroutine_enter(co, NULL);
+    qemu_coroutine_enter(co);
 }
 
 static void coroutine_fn bdrv_co_yield_to_drain(BlockDriverState *bs)
@@ -599,8 +599,8 @@ static int bdrv_prwv_co(BdrvChild *child, int64_t offset,
     } else {
         AioContext *aio_context = bdrv_get_aio_context(child->bs);
 
-        co = qemu_coroutine_create(bdrv_rw_co_entry);
-        qemu_coroutine_enter(co, &rwco);
+        co = qemu_coroutine_create(bdrv_rw_co_entry, &rwco);
+        qemu_coroutine_enter(co);
         while (rwco.ret == NOT_DONE) {
             aio_poll(aio_context, true);
         }
@@ -799,7 +799,7 @@ static void bdrv_co_io_em_complete(void *opaque, int ret)
     CoroutineIOCompletion *co = opaque;
 
     co->ret = ret;
-    qemu_coroutine_enter(co->coroutine, NULL);
+    qemu_coroutine_enter(co->coroutine);
 }
 
 static int coroutine_fn bdrv_driver_preadv(BlockDriverState *bs,
@@ -1752,8 +1752,9 @@ int64_t bdrv_get_block_status_above(BlockDriverState *bs,
     } else {
         AioContext *aio_context = bdrv_get_aio_context(bs);
 
-        co = qemu_coroutine_create(bdrv_get_block_status_above_co_entry);
-        qemu_coroutine_enter(co, &data);
+        co = qemu_coroutine_create(bdrv_get_block_status_above_co_entry,
+                                   &data);
+        qemu_coroutine_enter(co);
         while (!data.done) {
             aio_poll(aio_context, true);
         }
@@ -1901,9 +1902,9 @@ bdrv_rw_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos,
             .is_read    = is_read,
             .ret        = -EINPROGRESS,
         };
-        Coroutine *co = qemu_coroutine_create(bdrv_co_rw_vmstate_entry);
+        Coroutine *co = qemu_coroutine_create(bdrv_co_rw_vmstate_entry, &data);
 
-        qemu_coroutine_enter(co, &data);
+        qemu_coroutine_enter(co);
         while (data.ret == -EINPROGRESS) {
             aio_poll(bdrv_get_aio_context(bs), true);
         }
@@ -2113,8 +2114,8 @@ static BlockAIOCB *bdrv_co_aio_rw_vector(BdrvChild *child,
     acb->req.flags = flags;
     acb->is_write = is_write;
 
-    co = qemu_coroutine_create(bdrv_co_do_rw);
-    qemu_coroutine_enter(co, acb);
+    co = qemu_coroutine_create(bdrv_co_do_rw, acb);
+    qemu_coroutine_enter(co);
 
     bdrv_co_maybe_schedule_bh(acb);
     return &acb->common;
@@ -2141,8 +2142,8 @@ BlockAIOCB *bdrv_aio_flush(BlockDriverState *bs,
     acb->need_bh = true;
     acb->req.error = -EINPROGRESS;
 
-    co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
-    qemu_coroutine_enter(co, acb);
+    co = qemu_coroutine_create(bdrv_aio_flush_co_entry, acb);
+    qemu_coroutine_enter(co);
 
     bdrv_co_maybe_schedule_bh(acb);
     return &acb->common;
@@ -2171,8 +2172,8 @@ BlockAIOCB *bdrv_aio_discard(BlockDriverState *bs,
     acb->req.error = -EINPROGRESS;
     acb->req.sector = sector_num;
     acb->req.nb_sectors = nb_sectors;
-    co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
-    qemu_coroutine_enter(co, acb);
+    co = qemu_coroutine_create(bdrv_aio_discard_co_entry, acb);
+    qemu_coroutine_enter(co);
 
     bdrv_co_maybe_schedule_bh(acb);
     return &acb->common;
@@ -2313,8 +2314,8 @@ int bdrv_flush(BlockDriverState *bs)
     } else {
         AioContext *aio_context = bdrv_get_aio_context(bs);
 
-        co = qemu_coroutine_create(bdrv_flush_co_entry);
-        qemu_coroutine_enter(co, &flush_co);
+        co = qemu_coroutine_create(bdrv_flush_co_entry, &flush_co);
+        qemu_coroutine_enter(co);
         while (flush_co.ret == NOT_DONE) {
             aio_poll(aio_context, true);
         }
@@ -2442,8 +2443,8 @@ int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
     } else {
         AioContext *aio_context = bdrv_get_aio_context(bs);
 
-        co = qemu_coroutine_create(bdrv_discard_co_entry);
-        qemu_coroutine_enter(co, &rwco);
+        co = qemu_coroutine_create(bdrv_discard_co_entry, &rwco);
+        qemu_coroutine_enter(co);
         while (rwco.ret == NOT_DONE) {
             aio_poll(aio_context, true);
         }
@@ -2505,9 +2506,9 @@ int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
         /* Fast-path if already in coroutine context */
         bdrv_co_ioctl_entry(&data);
     } else {
-        Coroutine *co = qemu_coroutine_create(bdrv_co_ioctl_entry);
+        Coroutine *co = qemu_coroutine_create(bdrv_co_ioctl_entry, &data);
 
-        qemu_coroutine_enter(co, &data);
+        qemu_coroutine_enter(co);
         while (data.ret == -EINPROGRESS) {
             aio_poll(bdrv_get_aio_context(bs), true);
         }
@@ -2535,8 +2536,8 @@ BlockAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
     acb->req.error = -EINPROGRESS;
     acb->req.req = req;
     acb->req.buf = buf;
-    co = qemu_coroutine_create(bdrv_co_aio_ioctl_entry);
-    qemu_coroutine_enter(co, acb);
+    co = qemu_coroutine_create(bdrv_co_aio_ioctl_entry, acb);
+    qemu_coroutine_enter(co);
 
     bdrv_co_maybe_schedule_bh(acb);
     return &acb->common;
diff --git a/block/iscsi.c b/block/iscsi.c
index 24f78a7755..cf1e9e7f66 100644
--- a/block/iscsi.c
+++ b/block/iscsi.c
@@ -46,7 +46,6 @@
 
 #ifdef __linux__
 #include <scsi/sg.h>
-#include <block/scsi.h>
 #endif
 
 typedef struct IscsiLun {
@@ -153,7 +152,7 @@ static void iscsi_co_generic_bh_cb(void *opaque)
     struct IscsiTask *iTask = opaque;
     iTask->complete = 1;
     qemu_bh_delete(iTask->bh);
-    qemu_coroutine_enter(iTask->co, NULL);
+    qemu_coroutine_enter(iTask->co);
 }
 
 static void iscsi_retry_timer_expired(void *opaque)
@@ -161,7 +160,7 @@ static void iscsi_retry_timer_expired(void *opaque)
     struct IscsiTask *iTask = opaque;
     iTask->complete = 1;
     if (iTask->co) {
-        qemu_coroutine_enter(iTask->co, NULL);
+        qemu_coroutine_enter(iTask->co);
     }
 }
 
diff --git a/block/linux-aio.c b/block/linux-aio.c
index 7df8651581..5c104bd3cd 100644
--- a/block/linux-aio.c
+++ b/block/linux-aio.c
@@ -94,7 +94,7 @@ static void qemu_laio_process_completion(struct qemu_laiocb *laiocb)
 
     laiocb->ret = ret;
     if (laiocb->co) {
-        qemu_coroutine_enter(laiocb->co, NULL);
+        qemu_coroutine_enter(laiocb->co);
     } else {
         laiocb->common.cb(laiocb->common.opaque, ret);
         qemu_aio_unref(laiocb);
diff --git a/block/mirror.c b/block/mirror.c
index 8d96049555..b1e633ecad 100644
--- a/block/mirror.c
+++ b/block/mirror.c
@@ -121,7 +121,7 @@ static void mirror_iteration_done(MirrorOp *op, int ret)
     g_free(op);
 
     if (s->waiting_for_io) {
-        qemu_coroutine_enter(s->common.co, NULL);
+        qemu_coroutine_enter(s->common.co);
     }
 }
 
@@ -422,7 +422,9 @@ static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)
         assert(io_sectors);
         sector_num += io_sectors;
         nb_chunks -= DIV_ROUND_UP(io_sectors, sectors_per_chunk);
-        delay_ns += ratelimit_calculate_delay(&s->limit, io_sectors);
+        if (s->common.speed) {
+            delay_ns = ratelimit_calculate_delay(&s->limit, io_sectors);
+        }
     }
     return delay_ns;
 }
@@ -761,7 +763,8 @@ static void mirror_complete(BlockJob *job, Error **errp)
     target = blk_bs(s->target);
 
     if (!s->synced) {
-        error_setg(errp, QERR_BLOCK_JOB_NOT_READY, job->id);
+        error_setg(errp, "The active block job '%s' cannot be completed",
+                   job->id);
         return;
     }
 
@@ -842,8 +845,8 @@ static const BlockJobDriver commit_active_job_driver = {
     .attached_aio_context   = mirror_attached_aio_context,
 };
 
-static void mirror_start_job(BlockDriverState *bs, BlockDriverState *target,
-                             const char *replaces,
+static void mirror_start_job(const char *job_id, BlockDriverState *bs,
+                             BlockDriverState *target, const char *replaces,
                              int64_t speed, uint32_t granularity,
                              int64_t buf_size,
                              BlockMirrorBackingMode backing_mode,
@@ -872,7 +875,7 @@ static void mirror_start_job(BlockDriverState *bs, BlockDriverState *target,
         buf_size = DEFAULT_MIRROR_BUF_SIZE;
     }
 
-    s = block_job_create(driver, bs, speed, cb, opaque, errp);
+    s = block_job_create(job_id, driver, bs, speed, cb, opaque, errp);
     if (!s) {
         return;
     }
@@ -900,13 +903,13 @@ static void mirror_start_job(BlockDriverState *bs, BlockDriverState *target,
 
     bdrv_op_block_all(target, s->common.blocker);
 
-    s->common.co = qemu_coroutine_create(mirror_run);
+    s->common.co = qemu_coroutine_create(mirror_run, s);
     trace_mirror_start(bs, s, s->common.co, opaque);
-    qemu_coroutine_enter(s->common.co, s);
+    qemu_coroutine_enter(s->common.co);
 }
 
-void mirror_start(BlockDriverState *bs, BlockDriverState *target,
-                  const char *replaces,
+void mirror_start(const char *job_id, BlockDriverState *bs,
+                  BlockDriverState *target, const char *replaces,
                   int64_t speed, uint32_t granularity, int64_t buf_size,
                   MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
                   BlockdevOnError on_source_error,
@@ -924,14 +927,14 @@ void mirror_start(BlockDriverState *bs, BlockDriverState *target,
     }
     is_none_mode = mode == MIRROR_SYNC_MODE_NONE;
     base = mode == MIRROR_SYNC_MODE_TOP ? backing_bs(bs) : NULL;
-    mirror_start_job(bs, target, replaces,
+    mirror_start_job(job_id, bs, target, replaces,
                      speed, granularity, buf_size, backing_mode,
                      on_source_error, on_target_error, unmap, cb, opaque, errp,
                      &mirror_job_driver, is_none_mode, base);
 }
 
-void commit_active_start(BlockDriverState *bs, BlockDriverState *base,
-                         int64_t speed,
+void commit_active_start(const char *job_id, BlockDriverState *bs,
+                         BlockDriverState *base, int64_t speed,
                          BlockdevOnError on_error,
                          BlockCompletionFunc *cb,
                          void *opaque, Error **errp)
@@ -972,7 +975,8 @@ void commit_active_start(BlockDriverState *bs, BlockDriverState *base,
         }
     }
 
-    mirror_start_job(bs, base, NULL, speed, 0, 0, MIRROR_LEAVE_BACKING_CHAIN,
+    mirror_start_job(job_id, bs, base, NULL, speed, 0, 0,
+                     MIRROR_LEAVE_BACKING_CHAIN,
                      on_error, on_error, false, cb, opaque, &local_err,
                      &commit_active_job_driver, false, base);
     if (local_err) {
diff --git a/block/nbd-client.c b/block/nbd-client.c
index 420bce89f3..4cc408d206 100644
--- a/block/nbd-client.c
+++ b/block/nbd-client.c
@@ -38,7 +38,7 @@ static void nbd_recv_coroutines_enter_all(NbdClientSession *s)
 
     for (i = 0; i < MAX_NBD_REQUESTS; i++) {
         if (s->recv_coroutine[i]) {
-            qemu_coroutine_enter(s->recv_coroutine[i], NULL);
+            qemu_coroutine_enter(s->recv_coroutine[i]);
         }
     }
 }
@@ -99,7 +99,7 @@ static void nbd_reply_ready(void *opaque)
     }
 
     if (s->recv_coroutine[i]) {
-        qemu_coroutine_enter(s->recv_coroutine[i], NULL);
+        qemu_coroutine_enter(s->recv_coroutine[i]);
         return;
     }
 
@@ -111,7 +111,7 @@ static void nbd_restart_write(void *opaque)
 {
     BlockDriverState *bs = opaque;
 
-    qemu_coroutine_enter(nbd_get_client_session(bs)->send_coroutine, NULL);
+    qemu_coroutine_enter(nbd_get_client_session(bs)->send_coroutine);
 }
 
 static int nbd_co_send_request(BlockDriverState *bs,
diff --git a/block/nfs.c b/block/nfs.c
index 15d6832c4c..8602a44211 100644
--- a/block/nfs.c
+++ b/block/nfs.c
@@ -104,7 +104,7 @@ static void nfs_co_generic_bh_cb(void *opaque)
     NFSRPC *task = opaque;
     task->complete = 1;
     qemu_bh_delete(task->bh);
-    qemu_coroutine_enter(task->co, NULL);
+    qemu_coroutine_enter(task->co);
 }
 
 static void
diff --git a/block/qcow.c b/block/qcow.c
index ac849bd47c..0c7b75bc76 100644
--- a/block/qcow.c
+++ b/block/qcow.c
@@ -948,8 +948,8 @@ static int qcow_write(BlockDriverState *bs, int64_t sector_num,
         .nb_sectors = nb_sectors,
         .ret        = -EINPROGRESS,
     };
-    co = qemu_coroutine_create(qcow_write_co_entry);
-    qemu_coroutine_enter(co, &data);
+    co = qemu_coroutine_create(qcow_write_co_entry, &data);
+    qemu_coroutine_enter(co);
     while (data.ret == -EINPROGRESS) {
         aio_poll(aio_context, true);
     }
diff --git a/block/qcow2-cluster.c b/block/qcow2-cluster.c
index 6b92ce9429..f94183529c 100644
--- a/block/qcow2-cluster.c
+++ b/block/qcow2-cluster.c
@@ -65,7 +65,8 @@ int qcow2_grow_l1_table(BlockDriverState *bs, uint64_t min_size,
         }
     }
 
-    if (new_l1_size > INT_MAX / sizeof(uint64_t)) {
+    QEMU_BUILD_BUG_ON(QCOW_MAX_L1_SIZE > INT_MAX);
+    if (new_l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
         return -EFBIG;
     }
 
@@ -482,8 +483,8 @@ int qcow2_get_cluster_offset(BlockDriverState *bs, uint64_t offset,
     unsigned int l2_index;
     uint64_t l1_index, l2_offset, *l2_table;
     int l1_bits, c;
-    unsigned int offset_in_cluster, nb_clusters;
-    uint64_t bytes_available, bytes_needed;
+    unsigned int offset_in_cluster;
+    uint64_t bytes_available, bytes_needed, nb_clusters;
     int ret;
 
     offset_in_cluster = offset_into_cluster(s, offset);
@@ -499,7 +500,6 @@ int qcow2_get_cluster_offset(BlockDriverState *bs, uint64_t offset,
     if (bytes_needed > bytes_available) {
         bytes_needed = bytes_available;
     }
-    assert(bytes_needed <= INT_MAX);
 
     *cluster_offset = 0;
 
@@ -536,8 +536,11 @@ int qcow2_get_cluster_offset(BlockDriverState *bs, uint64_t offset,
     l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
     *cluster_offset = be64_to_cpu(l2_table[l2_index]);
 
-    /* nb_needed <= INT_MAX, thus nb_clusters <= INT_MAX, too */
     nb_clusters = size_to_clusters(s, bytes_needed);
+    /* bytes_needed <= *bytes + offset_in_cluster, both of which are unsigned
+     * integers; the minimum cluster size is 512, so this assertion is always
+     * true */
+    assert(nb_clusters <= INT_MAX);
 
     ret = qcow2_get_cluster_type(*cluster_offset);
     switch (ret) {
@@ -584,13 +587,17 @@ int qcow2_get_cluster_offset(BlockDriverState *bs, uint64_t offset,
 
     qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
 
-    bytes_available = (c * s->cluster_size);
+    bytes_available = (int64_t)c * s->cluster_size;
 
 out:
     if (bytes_available > bytes_needed) {
         bytes_available = bytes_needed;
     }
 
+    /* bytes_available <= bytes_needed <= *bytes + offset_in_cluster;
+     * subtracting offset_in_cluster will therefore definitely yield something
+     * not exceeding UINT_MAX */
+    assert(bytes_available - offset_in_cluster <= UINT_MAX);
     *bytes = bytes_available - offset_in_cluster;
 
     return ret;
diff --git a/block/qcow2.c b/block/qcow2.c
index a5ea19b0b6..a6bca735e5 100644
--- a/block/qcow2.c
+++ b/block/qcow2.c
@@ -2570,8 +2570,8 @@ static int qcow2_write(BlockDriverState *bs, int64_t sector_num,
         .nb_sectors = nb_sectors,
         .ret        = -EINPROGRESS,
     };
-    co = qemu_coroutine_create(qcow2_write_co_entry);
-    qemu_coroutine_enter(co, &data);
+    co = qemu_coroutine_create(qcow2_write_co_entry, &data);
+    qemu_coroutine_enter(co);
     while (data.ret == -EINPROGRESS) {
         aio_poll(aio_context, true);
     }
diff --git a/block/qed.c b/block/qed.c
index f619d82c6e..426f3cb447 100644
--- a/block/qed.c
+++ b/block/qed.c
@@ -708,7 +708,7 @@ static void qed_is_allocated_cb(void *opaque, int ret, uint64_t offset, size_t l
     }
 
     if (cb->co) {
-        qemu_coroutine_enter(cb->co, NULL);
+        qemu_coroutine_enter(cb->co);
     }
 }
 
@@ -1425,7 +1425,7 @@ static void coroutine_fn qed_co_pwrite_zeroes_cb(void *opaque, int ret)
     cb->done = true;
     cb->ret = ret;
     if (cb->co) {
-        qemu_coroutine_enter(cb->co, NULL);
+        qemu_coroutine_enter(cb->co);
     }
 }
 
diff --git a/block/raw-posix.c b/block/raw-posix.c
index c979ac3fd1..d1c3bd8e47 100644
--- a/block/raw-posix.c
+++ b/block/raw-posix.c
@@ -639,15 +639,7 @@ static int raw_reopen_prepare(BDRVReopenState *state,
 
     if ((raw_s->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
         /* dup the original fd */
-        /* TODO: use qemu fcntl wrapper */
-#ifdef F_DUPFD_CLOEXEC
-        raw_s->fd = fcntl(s->fd, F_DUPFD_CLOEXEC, 0);
-#else
-        raw_s->fd = dup(s->fd);
-        if (raw_s->fd != -1) {
-            qemu_set_cloexec(raw_s->fd);
-        }
-#endif
+        raw_s->fd = qemu_dup(s->fd);
         if (raw_s->fd >= 0) {
             ret = fcntl_setfl(raw_s->fd, raw_s->open_flags);
             if (ret) {
diff --git a/block/sheepdog.c b/block/sheepdog.c
index ef5d044ab9..e739c56f08 100644
--- a/block/sheepdog.c
+++ b/block/sheepdog.c
@@ -495,7 +495,7 @@ static inline void free_aio_req(BDRVSheepdogState *s, AIOReq *aio_req)
 
 static void coroutine_fn sd_finish_aiocb(SheepdogAIOCB *acb)
 {
-    qemu_coroutine_enter(acb->coroutine, NULL);
+    qemu_coroutine_enter(acb->coroutine);
     qemu_aio_unref(acb);
 }
 
@@ -636,7 +636,7 @@ static void restart_co_req(void *opaque)
 {
     Coroutine *co = opaque;
 
-    qemu_coroutine_enter(co, NULL);
+    qemu_coroutine_enter(co);
 }
 
 typedef struct SheepdogReqCo {
@@ -726,8 +726,8 @@ static int do_req(int sockfd, AioContext *aio_context, SheepdogReq *hdr,
     if (qemu_in_coroutine()) {
         do_co_req(&srco);
     } else {
-        co = qemu_coroutine_create(do_co_req);
-        qemu_coroutine_enter(co, &srco);
+        co = qemu_coroutine_create(do_co_req, &srco);
+        qemu_coroutine_enter(co);
         while (!srco.finished) {
             aio_poll(aio_context, true);
         }
@@ -925,17 +925,17 @@ static void co_read_response(void *opaque)
     BDRVSheepdogState *s = opaque;
 
     if (!s->co_recv) {
-        s->co_recv = qemu_coroutine_create(aio_read_response);
+        s->co_recv = qemu_coroutine_create(aio_read_response, opaque);
     }
 
-    qemu_coroutine_enter(s->co_recv, opaque);
+    qemu_coroutine_enter(s->co_recv);
 }
 
 static void co_write_request(void *opaque)
 {
     BDRVSheepdogState *s = opaque;
 
-    qemu_coroutine_enter(s->co_send, NULL);
+    qemu_coroutine_enter(s->co_send);
 }
 
 /*
diff --git a/block/ssh.c b/block/ssh.c
index 06928ed939..bcbb0e4223 100644
--- a/block/ssh.c
+++ b/block/ssh.c
@@ -777,7 +777,7 @@ static void restart_coroutine(void *opaque)
 
     DPRINTF("co=%p", co);
 
-    qemu_coroutine_enter(co, NULL);
+    qemu_coroutine_enter(co);
 }
 
 static coroutine_fn void set_fd_handler(BDRVSSHState *s, BlockDriverState *bs)
diff --git a/block/stream.c b/block/stream.c
index c0efbda34e..31874817c2 100644
--- a/block/stream.c
+++ b/block/stream.c
@@ -95,6 +95,7 @@ static void coroutine_fn stream_run(void *opaque)
     BlockDriverState *base = s->base;
     int64_t sector_num = 0;
     int64_t end = -1;
+    uint64_t delay_ns = 0;
     int error = 0;
     int ret = 0;
     int n = 0;
@@ -123,10 +124,8 @@ static void coroutine_fn stream_run(void *opaque)
     }
 
     for (sector_num = 0; sector_num < end; sector_num += n) {
-        uint64_t delay_ns = 0;
         bool copy;
 
-wait:
         /* Note that even when no rate limit is applied we need to yield
          * with no pending I/O here so that bdrv_drain_all() returns.
          */
@@ -156,12 +155,6 @@ wait:
         }
         trace_stream_one_iteration(s, sector_num, n, ret);
         if (copy) {
-            if (s->common.speed) {
-                delay_ns = ratelimit_calculate_delay(&s->limit, n);
-                if (delay_ns > 0) {
-                    goto wait;
-                }
-            }
             ret = stream_populate(blk, sector_num, n, buf);
         }
         if (ret < 0) {
@@ -182,6 +175,9 @@ wait:
 
         /* Publish progress */
         s->common.offset += n * BDRV_SECTOR_SIZE;
+        if (copy && s->common.speed) {
+            delay_ns = ratelimit_calculate_delay(&s->limit, n);
+        }
     }
 
     if (!base) {
@@ -218,15 +214,15 @@ static const BlockJobDriver stream_job_driver = {
     .set_speed     = stream_set_speed,
 };
 
-void stream_start(BlockDriverState *bs, BlockDriverState *base,
-                  const char *backing_file_str, int64_t speed,
-                  BlockdevOnError on_error,
-                  BlockCompletionFunc *cb,
-                  void *opaque, Error **errp)
+void stream_start(const char *job_id, BlockDriverState *bs,
+                  BlockDriverState *base, const char *backing_file_str,
+                  int64_t speed, BlockdevOnError on_error,
+                  BlockCompletionFunc *cb, void *opaque, Error **errp)
 {
     StreamBlockJob *s;
 
-    s = block_job_create(&stream_job_driver, bs, speed, cb, opaque, errp);
+    s = block_job_create(job_id, &stream_job_driver, bs, speed,
+                         cb, opaque, errp);
     if (!s) {
         return;
     }
@@ -235,7 +231,7 @@ void stream_start(BlockDriverState *bs, BlockDriverState *base,
     s->backing_file_str = g_strdup(backing_file_str);
 
     s->on_error = on_error;
-    s->common.co = qemu_coroutine_create(stream_run);
+    s->common.co = qemu_coroutine_create(stream_run, s);
     trace_stream_start(bs, base, s, s->common.co, opaque);
-    qemu_coroutine_enter(s->common.co, s);
+    qemu_coroutine_enter(s->common.co);
 }
diff --git a/block/vmdk.c b/block/vmdk.c
index d73f4314ba..46d474e442 100644
--- a/block/vmdk.c
+++ b/block/vmdk.c
@@ -1202,13 +1202,6 @@ static int get_cluster_offset(BlockDriverState *bs,
     l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size;
     cluster_sector = le32_to_cpu(l2_table[l2_index]);
 
-    if (m_data) {
-        m_data->valid = 1;
-        m_data->l1_index = l1_index;
-        m_data->l2_index = l2_index;
-        m_data->l2_offset = l2_offset;
-        m_data->l2_cache_entry = &l2_table[l2_index];
-    }
     if (extent->has_zero_grain && cluster_sector == VMDK_GTE_ZEROED) {
         zeroed = true;
     }
@@ -1231,6 +1224,13 @@ static int get_cluster_offset(BlockDriverState *bs,
         if (ret) {
             return ret;
         }
+        if (m_data) {
+            m_data->valid = 1;
+            m_data->l1_index = l1_index;
+            m_data->l2_index = l2_index;
+            m_data->l2_offset = l2_offset;
+            m_data->l2_cache_entry = &l2_table[l2_index];
+        }
     }
     *cluster_offset = cluster_sector << BDRV_SECTOR_BITS;
     return VMDK_OK;
@@ -1686,8 +1686,8 @@ static int vmdk_write_compressed(BlockDriverState *bs,
             .nb_sectors = nb_sectors,
             .ret        = -EINPROGRESS,
         };
-        co = qemu_coroutine_create(vmdk_co_write_compressed);
-        qemu_coroutine_enter(co, &data);
+        co = qemu_coroutine_create(vmdk_co_write_compressed, &data);
+        qemu_coroutine_enter(co);
         while (data.ret == -EINPROGRESS) {
             aio_poll(aio_context, true);
         }
diff --git a/block/vvfat.c b/block/vvfat.c
index c3f24c6eb0..ba2620f3c2 100644
--- a/block/vvfat.c
+++ b/block/vvfat.c
@@ -3018,9 +3018,10 @@ static int enable_write_target(BlockDriverState *bs, Error **errp)
     }
 
     options = qdict_new();
-    qdict_put(options, "driver", qstring_from_str("qcow"));
+    qdict_put(options, "write-target.driver", qstring_from_str("qcow"));
     s->qcow = bdrv_open_child(s->qcow_filename, options, "write-target", bs,
                               &child_vvfat_qcow, false, errp);
+    QDECREF(options);
     if (!s->qcow) {
         ret = -EINVAL;
         goto err;
diff --git a/blockdev.c b/blockdev.c
index 0f8065c4a5..384ad3bba6 100644
--- a/blockdev.c
+++ b/blockdev.c
@@ -512,6 +512,8 @@ static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
 
     writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
 
+    id = qemu_opts_id(opts);
+
     qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
     qdict_array_split(interval_dict, &interval_list);
 
@@ -616,7 +618,7 @@ static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
     /* disk I/O throttling */
     if (throttle_enabled(&cfg)) {
         if (!throttling_group) {
-            throttling_group = blk_name(blk);
+            throttling_group = id;
         }
         blk_io_limits_enable(blk, throttling_group);
         blk_set_io_limits(blk, &cfg);
@@ -625,7 +627,7 @@ static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
     blk_set_enable_write_cache(blk, !writethrough);
     blk_set_on_error(blk, on_read_error, on_write_error);
 
-    if (!monitor_add_blk(blk, qemu_opts_id(opts), errp)) {
+    if (!monitor_add_blk(blk, id, errp)) {
         blk_unref(blk);
         blk = NULL;
         goto err_no_bs_opts;
@@ -1836,9 +1838,9 @@ typedef struct DriveBackupState {
     BlockJob *job;
 } DriveBackupState;
 
-static void do_drive_backup(const char *device, const char *target,
-                            bool has_format, const char *format,
-                            enum MirrorSyncMode sync,
+static void do_drive_backup(const char *job_id, const char *device,
+                            const char *target, bool has_format,
+                            const char *format, enum MirrorSyncMode sync,
                             bool has_mode, enum NewImageMode mode,
                             bool has_speed, int64_t speed,
                             bool has_bitmap, const char *bitmap,
@@ -1876,7 +1878,8 @@ static void drive_backup_prepare(BlkActionState *common, Error **errp)
     bdrv_drained_begin(blk_bs(blk));
     state->bs = blk_bs(blk);
 
-    do_drive_backup(backup->device, backup->target,
+    do_drive_backup(backup->has_job_id ? backup->job_id : NULL,
+                    backup->device, backup->target,
                     backup->has_format, backup->format,
                     backup->sync,
                     backup->has_mode, backup->mode,
@@ -1921,8 +1924,8 @@ typedef struct BlockdevBackupState {
     AioContext *aio_context;
 } BlockdevBackupState;
 
-static void do_blockdev_backup(const char *device, const char *target,
-                               enum MirrorSyncMode sync,
+static void do_blockdev_backup(const char *job_id, const char *device,
+                               const char *target, enum MirrorSyncMode sync,
                                bool has_speed, int64_t speed,
                                bool has_on_source_error,
                                BlockdevOnError on_source_error,
@@ -1968,8 +1971,8 @@ static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
     state->bs = blk_bs(blk);
     bdrv_drained_begin(state->bs);
 
-    do_blockdev_backup(backup->device, backup->target,
-                       backup->sync,
+    do_blockdev_backup(backup->has_job_id ? backup->job_id : NULL,
+                       backup->device, backup->target, backup->sync,
                        backup->has_speed, backup->speed,
                        backup->has_on_source_error, backup->on_source_error,
                        backup->has_on_target_error, backup->on_target_error,
@@ -3004,7 +3007,7 @@ static void block_job_cb(void *opaque, int ret)
     }
 }
 
-void qmp_block_stream(const char *device,
+void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
                       bool has_base, const char *base,
                       bool has_backing_file, const char *backing_file,
                       bool has_speed, int64_t speed,
@@ -3063,8 +3066,8 @@ void qmp_block_stream(const char *device,
     /* backing_file string overrides base bs filename */
     base_name = has_backing_file ? backing_file : base_name;
 
-    stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
-                 on_error, block_job_cb, bs, &local_err);
+    stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
+                 has_speed ? speed : 0, on_error, block_job_cb, bs, &local_err);
     if (local_err) {
         error_propagate(errp, local_err);
         goto out;
@@ -3076,7 +3079,7 @@ out:
     aio_context_release(aio_context);
 }
 
-void qmp_block_commit(const char *device,
+void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
                       bool has_base, const char *base,
                       bool has_top, const char *top,
                       bool has_backing_file, const char *backing_file,
@@ -3167,10 +3170,11 @@ void qmp_block_commit(const char *device,
                              " but 'top' is the active layer");
             goto out;
         }
-        commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
-                            bs, &local_err);
+        commit_active_start(has_job_id ? job_id : NULL, bs, base_bs, speed,
+                            on_error, block_job_cb, bs, &local_err);
     } else {
-        commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
+        commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, speed,
+                     on_error, block_job_cb, bs,
                      has_backing_file ? backing_file : NULL, &local_err);
     }
     if (local_err != NULL) {
@@ -3182,9 +3186,9 @@ out:
     aio_context_release(aio_context);
 }
 
-static void do_drive_backup(const char *device, const char *target,
-                            bool has_format, const char *format,
-                            enum MirrorSyncMode sync,
+static void do_drive_backup(const char *job_id, const char *device,
+                            const char *target, bool has_format,
+                            const char *format, enum MirrorSyncMode sync,
                             bool has_mode, enum NewImageMode mode,
                             bool has_speed, int64_t speed,
                             bool has_bitmap, const char *bitmap,
@@ -3303,7 +3307,7 @@ static void do_drive_backup(const char *device, const char *target,
         }
     }
 
-    backup_start(bs, target_bs, speed, sync, bmap,
+    backup_start(job_id, bs, target_bs, speed, sync, bmap,
                  on_source_error, on_target_error,
                  block_job_cb, bs, txn, &local_err);
     bdrv_unref(target_bs);
@@ -3316,7 +3320,8 @@ out:
     aio_context_release(aio_context);
 }
 
-void qmp_drive_backup(const char *device, const char *target,
+void qmp_drive_backup(bool has_job_id, const char *job_id,
+                      const char *device, const char *target,
                       bool has_format, const char *format,
                       enum MirrorSyncMode sync,
                       bool has_mode, enum NewImageMode mode,
@@ -3326,7 +3331,8 @@ void qmp_drive_backup(const char *device, const char *target,
                       bool has_on_target_error, BlockdevOnError on_target_error,
                       Error **errp)
 {
-    return do_drive_backup(device, target, has_format, format, sync,
+    return do_drive_backup(has_job_id ? job_id : NULL, device, target,
+                           has_format, format, sync,
                            has_mode, mode, has_speed, speed,
                            has_bitmap, bitmap,
                            has_on_source_error, on_source_error,
@@ -3339,8 +3345,8 @@ BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
     return bdrv_named_nodes_list(errp);
 }
 
-void do_blockdev_backup(const char *device, const char *target,
-                         enum MirrorSyncMode sync,
+void do_blockdev_backup(const char *job_id, const char *device,
+                        const char *target, enum MirrorSyncMode sync,
                          bool has_speed, int64_t speed,
                          bool has_on_source_error,
                          BlockdevOnError on_source_error,
@@ -3395,7 +3401,7 @@ void do_blockdev_backup(const char *device, const char *target,
             goto out;
         }
     }
-    backup_start(bs, target_bs, speed, sync, NULL, on_source_error,
+    backup_start(job_id, bs, target_bs, speed, sync, NULL, on_source_error,
                  on_target_error, block_job_cb, bs, txn, &local_err);
     if (local_err != NULL) {
         error_propagate(errp, local_err);
@@ -3404,7 +3410,8 @@ out:
     aio_context_release(aio_context);
 }
 
-void qmp_blockdev_backup(const char *device, const char *target,
+void qmp_blockdev_backup(bool has_job_id, const char *job_id,
+                         const char *device, const char *target,
                          enum MirrorSyncMode sync,
                          bool has_speed, int64_t speed,
                          bool has_on_source_error,
@@ -3413,7 +3420,8 @@ void qmp_blockdev_backup(const char *device, const char *target,
                          BlockdevOnError on_target_error,
                          Error **errp)
 {
-    do_blockdev_backup(device, target, sync, has_speed, speed,
+    do_blockdev_backup(has_job_id ? job_id : NULL, device, target,
+                       sync, has_speed, speed,
                        has_on_source_error, on_source_error,
                        has_on_target_error, on_target_error,
                        NULL, errp);
@@ -3422,7 +3430,7 @@ void qmp_blockdev_backup(const char *device, const char *target,
 /* Parameter check and block job starting for drive mirroring.
  * Caller should hold @device and @target's aio context (must be the same).
  **/
-static void blockdev_mirror_common(BlockDriverState *bs,
+static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
                                    BlockDriverState *target,
                                    bool has_replaces, const char *replaces,
                                    enum MirrorSyncMode sync,
@@ -3482,15 +3490,15 @@ static void blockdev_mirror_common(BlockDriverState *bs,
     /* pass the node name to replace to mirror start since it's loose coupling
      * and will allow to check whether the node still exist at mirror completion
      */
-    mirror_start(bs, target,
+    mirror_start(job_id, bs, target,
                  has_replaces ? replaces : NULL,
                  speed, granularity, buf_size, sync, backing_mode,
                  on_source_error, on_target_error, unmap,
                  block_job_cb, bs, errp);
 }
 
-void qmp_drive_mirror(const char *device, const char *target,
-                      bool has_format, const char *format,
+void qmp_drive_mirror(bool has_job_id, const char *job_id, const char *device,
+                      const char *target, bool has_format, const char *format,
                       bool has_node_name, const char *node_name,
                       bool has_replaces, const char *replaces,
                       enum MirrorSyncMode sync,
@@ -3634,7 +3642,7 @@ void qmp_drive_mirror(const char *device, const char *target,
 
     bdrv_set_aio_context(target_bs, aio_context);
 
-    blockdev_mirror_common(bs, target_bs,
+    blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
                            has_replaces, replaces, sync, backing_mode,
                            has_speed, speed,
                            has_granularity, granularity,
@@ -3649,7 +3657,8 @@ out:
     aio_context_release(aio_context);
 }
 
-void qmp_blockdev_mirror(const char *device, const char *target,
+void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
+                         const char *device, const char *target,
                          bool has_replaces, const char *replaces,
                          MirrorSyncMode sync,
                          bool has_speed, int64_t speed,
@@ -3690,7 +3699,7 @@ void qmp_blockdev_mirror(const char *device, const char *target,
 
     bdrv_set_aio_context(target_bs, aio_context);
 
-    blockdev_mirror_common(bs, target_bs,
+    blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
                            has_replaces, replaces, sync, backing_mode,
                            has_speed, speed,
                            has_granularity, granularity,
@@ -3704,42 +3713,28 @@ void qmp_blockdev_mirror(const char *device, const char *target,
     aio_context_release(aio_context);
 }
 
-/* Get the block job for a given device name and acquire its AioContext */
-static BlockJob *find_block_job(const char *device, AioContext **aio_context,
+/* Get a block job using its ID and acquire its AioContext */
+static BlockJob *find_block_job(const char *id, AioContext **aio_context,
                                 Error **errp)
 {
-    BlockBackend *blk;
-    BlockDriverState *bs;
-
-    *aio_context = NULL;
+    BlockJob *job;
 
-    blk = blk_by_name(device);
-    if (!blk) {
-        goto notfound;
-    }
+    assert(id != NULL);
 
-    *aio_context = blk_get_aio_context(blk);
-    aio_context_acquire(*aio_context);
+    *aio_context = NULL;
 
-    if (!blk_is_available(blk)) {
-        goto notfound;
-    }
-    bs = blk_bs(blk);
+    job = block_job_get(id);
 
-    if (!bs->job) {
-        goto notfound;
+    if (!job) {
+        error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
+                  "Block job '%s' not found", id);
+        return NULL;
     }
 
-    return bs->job;
+    *aio_context = blk_get_aio_context(job->blk);
+    aio_context_acquire(*aio_context);
 
-notfound:
-    error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
-              "No active block job on device '%s'", device);
-    if (*aio_context) {
-        aio_context_release(*aio_context);
-        *aio_context = NULL;
-    }
-    return NULL;
+    return job;
 }
 
 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
diff --git a/blockjob.c b/blockjob.c
index 205da9df4e..a5ba3bee52 100644
--- a/blockjob.c
+++ b/blockjob.c
@@ -33,6 +33,7 @@
 #include "qapi/qmp/qerror.h"
 #include "qapi/qmp/qjson.h"
 #include "qemu/coroutine.h"
+#include "qemu/id.h"
 #include "qmp-commands.h"
 #include "qemu/timer.h"
 #include "qapi-event.h"
@@ -60,6 +61,19 @@ BlockJob *block_job_next(BlockJob *job)
     return QLIST_NEXT(job, job_list);
 }
 
+BlockJob *block_job_get(const char *id)
+{
+    BlockJob *job;
+
+    QLIST_FOREACH(job, &block_jobs, job_list) {
+        if (!strcmp(id, job->id)) {
+            return job;
+        }
+    }
+
+    return NULL;
+}
+
 /* Normally the job runs in its BlockBackend's AioContext.  The exception is
  * block_job_defer_to_main_loop() where it runs in the QEMU main loop.  Code
  * that supports both cases uses this helper function.
@@ -103,9 +117,9 @@ static void block_job_detach_aio_context(void *opaque)
     block_job_unref(job);
 }
 
-void *block_job_create(const BlockJobDriver *driver, BlockDriverState *bs,
-                       int64_t speed, BlockCompletionFunc *cb,
-                       void *opaque, Error **errp)
+void *block_job_create(const char *job_id, const BlockJobDriver *driver,
+                       BlockDriverState *bs, int64_t speed,
+                       BlockCompletionFunc *cb, void *opaque, Error **errp)
 {
     BlockBackend *blk;
     BlockJob *job;
@@ -116,6 +130,20 @@ void *block_job_create(const BlockJobDriver *driver, BlockDriverState *bs,
         return NULL;
     }
 
+    if (job_id == NULL) {
+        job_id = bdrv_get_device_name(bs);
+    }
+
+    if (!id_wellformed(job_id)) {
+        error_setg(errp, "Invalid job ID '%s'", job_id);
+        return NULL;
+    }
+
+    if (block_job_get(job_id)) {
+        error_setg(errp, "Job ID '%s' already in use", job_id);
+        return NULL;
+    }
+
     blk = blk_new();
     blk_insert_bs(blk, bs);
 
@@ -126,7 +154,7 @@ void *block_job_create(const BlockJobDriver *driver, BlockDriverState *bs,
     bdrv_op_unblock(bs, BLOCK_OP_TYPE_DATAPLANE, job->blocker);
 
     job->driver        = driver;
-    job->id            = g_strdup(bdrv_get_device_name(bs));
+    job->id            = g_strdup(job_id);
     job->blk           = blk;
     job->cb            = cb;
     job->opaque        = opaque;
@@ -290,7 +318,8 @@ void block_job_set_speed(BlockJob *job, int64_t speed, Error **errp)
 void block_job_complete(BlockJob *job, Error **errp)
 {
     if (job->pause_count || job->cancelled || !job->driver->complete) {
-        error_setg(errp, QERR_BLOCK_JOB_NOT_READY, job->id);
+        error_setg(errp, "The active block job '%s' cannot be completed",
+                   job->id);
         return;
     }
 
@@ -346,7 +375,7 @@ void block_job_resume(BlockJob *job)
 void block_job_enter(BlockJob *job)
 {
     if (job->co && !job->busy) {
-        qemu_coroutine_enter(job->co, NULL);
+        qemu_coroutine_enter(job->co);
     }
 }
 
@@ -524,6 +553,7 @@ BlockErrorAction block_job_error_action(BlockJob *job, BlockdevOnError on_err,
 
     switch (on_err) {
     case BLOCKDEV_ON_ERROR_ENOSPC:
+    case BLOCKDEV_ON_ERROR_AUTO:
         action = (error == ENOSPC) ?
                  BLOCK_ERROR_ACTION_STOP : BLOCK_ERROR_ACTION_REPORT;
         break;
diff --git a/bsd-user/i386/target_syscall.h b/bsd-user/i386/target_syscall.h
index 82d1c58ca5..8f201386af 100644
--- a/bsd-user/i386/target_syscall.h
+++ b/bsd-user/i386/target_syscall.h
@@ -162,4 +162,4 @@ struct target_vm86plus_struct {
 
 #define UNAME_MACHINE "i386"
 
-#endif  /* TARGET_SYSCALL_H */
+#endif /* TARGET_SYSCALL_H */
diff --git a/bsd-user/sparc/target_syscall.h b/bsd-user/sparc/target_syscall.h
index c7eec6ba60..dfdf9f82f5 100644
--- a/bsd-user/sparc/target_syscall.h
+++ b/bsd-user/sparc/target_syscall.h
@@ -11,4 +11,4 @@ struct target_pt_regs {
 
 #define UNAME_MACHINE "sun4"
 
-#endif  /* TARGET_SYSCALL_H */
+#endif /* TARGET_SYSCALL_H */
diff --git a/bsd-user/sparc64/target_syscall.h b/bsd-user/sparc64/target_syscall.h
index 2f06100ae5..3a9f4c2ef9 100644
--- a/bsd-user/sparc64/target_syscall.h
+++ b/bsd-user/sparc64/target_syscall.h
@@ -12,4 +12,4 @@ struct target_pt_regs {
 
 #define UNAME_MACHINE "sun4u"
 
-#endif  /* TARGET_SYSCALL_H */
+#endif /* TARGET_SYSCALL_H */
diff --git a/bsd-user/x86_64/target_syscall.h b/bsd-user/x86_64/target_syscall.h
index 85a9766970..211ce29e90 100644
--- a/bsd-user/x86_64/target_syscall.h
+++ b/bsd-user/x86_64/target_syscall.h
@@ -118,4 +118,4 @@ struct target_msqid64_ds {
 #define TARGET_ARCH_GET_FS 0x1003
 #define TARGET_ARCH_GET_GS 0x1004
 
-#endif  /* TARGET_SYSCALL_H */
+#endif /* TARGET_SYSCALL_H */
diff --git a/contrib/ivshmem-client/ivshmem-client.h b/contrib/ivshmem-client/ivshmem-client.h
index 54cde17d93..5ee942262b 100644
--- a/contrib/ivshmem-client/ivshmem-client.h
+++ b/contrib/ivshmem-client/ivshmem-client.h
@@ -6,8 +6,8 @@
  * top-level directory.
  */
 
-#ifndef _IVSHMEM_CLIENT_H_
-#define _IVSHMEM_CLIENT_H_
+#ifndef IVSHMEM_CLIENT_H
+#define IVSHMEM_CLIENT_H
 
 /**
  * This file provides helper to implement an ivshmem client. It is used
@@ -209,4 +209,4 @@ ivshmem_client_search_peer(IvshmemClient *client, int64_t peer_id);
  */
 void ivshmem_client_dump(const IvshmemClient *client);
 
-#endif /* _IVSHMEM_CLIENT_H_ */
+#endif /* IVSHMEM_CLIENT_H */
diff --git a/contrib/ivshmem-server/ivshmem-server.h b/contrib/ivshmem-server/ivshmem-server.h
index d37ca85265..4af08e1bb7 100644
--- a/contrib/ivshmem-server/ivshmem-server.h
+++ b/contrib/ivshmem-server/ivshmem-server.h
@@ -6,8 +6,8 @@
  * top-level directory.
  */
 
-#ifndef _IVSHMEM_SERVER_H_
-#define _IVSHMEM_SERVER_H_
+#ifndef IVSHMEM_SERVER_H
+#define IVSHMEM_SERVER_H
 
 /**
  * The ivshmem server is a daemon that creates a unix socket in listen
@@ -163,4 +163,4 @@ ivshmem_server_search_peer(IvshmemServer *server, int64_t peer_id);
  */
 void ivshmem_server_dump(const IvshmemServer *server);
 
-#endif /* _IVSHMEM_SERVER_H_ */
+#endif /* IVSHMEM_SERVER_H */
diff --git a/cputlb.c b/cputlb.c
index 079e4979ca..d068ee597e 100644
--- a/cputlb.c
+++ b/cputlb.c
@@ -498,6 +498,35 @@ tb_page_addr_t get_page_addr_code(CPUArchState *env1, target_ulong addr)
     return qemu_ram_addr_from_host_nofail(p);
 }
 
+/* Return true if ADDR is present in the victim tlb, and has been copied
+   back to the main tlb.  */
+static bool victim_tlb_hit(CPUArchState *env, size_t mmu_idx, size_t index,
+                           size_t elt_ofs, target_ulong page)
+{
+    size_t vidx;
+    for (vidx = 0; vidx < CPU_VTLB_SIZE; ++vidx) {
+        CPUTLBEntry *vtlb = &env->tlb_v_table[mmu_idx][vidx];
+        target_ulong cmp = *(target_ulong *)((uintptr_t)vtlb + elt_ofs);
+
+        if (cmp == page) {
+            /* Found entry in victim tlb, swap tlb and iotlb.  */
+            CPUTLBEntry tmptlb, *tlb = &env->tlb_table[mmu_idx][index];
+            CPUIOTLBEntry tmpio, *io = &env->iotlb[mmu_idx][index];
+            CPUIOTLBEntry *vio = &env->iotlb_v[mmu_idx][vidx];
+
+            tmptlb = *tlb; *tlb = *vtlb; *vtlb = tmptlb;
+            tmpio = *io; *io = *vio; *vio = tmpio;
+            return true;
+        }
+    }
+    return false;
+}
+
+/* Macro to call the above, with local variables from the use context.  */
+#define VICTIM_TLB_HIT(TY, ADDR) \
+  victim_tlb_hit(env, mmu_idx, index, offsetof(CPUTLBEntry, TY), \
+                 (ADDR) & TARGET_PAGE_MASK)
+
 #define MMUSUFFIX _mmu
 
 #define SHIFT 0
diff --git a/crypto/block-luks.h b/crypto/block-luks.h
index 0934138aaa..b2d8a35c1b 100644
--- a/crypto/block-luks.h
+++ b/crypto/block-luks.h
@@ -18,11 +18,11 @@
  *
  */
 
-#ifndef QCRYPTO_BLOCK_LUKS_H__
-#define QCRYPTO_BLOCK_LUKS_H__
+#ifndef QCRYPTO_BLOCK_LUKS_H
+#define QCRYPTO_BLOCK_LUKS_H
 
 #include "crypto/blockpriv.h"
 
 extern const QCryptoBlockDriver qcrypto_block_driver_luks;
 
-#endif /* QCRYPTO_BLOCK_LUKS_H__ */
+#endif /* QCRYPTO_BLOCK_LUKS_H */
diff --git a/crypto/block-qcow.h b/crypto/block-qcow.h
index 569f836100..3e2c0a851a 100644
--- a/crypto/block-qcow.h
+++ b/crypto/block-qcow.h
@@ -18,11 +18,11 @@
  *
  */
 
-#ifndef QCRYPTO_BLOCK_QCOW_H__
-#define QCRYPTO_BLOCK_QCOW_H__
+#ifndef QCRYPTO_BLOCK_QCOW_H
+#define QCRYPTO_BLOCK_QCOW_H
 
 #include "crypto/blockpriv.h"
 
 extern const QCryptoBlockDriver qcrypto_block_driver_qcow;
 
-#endif /* QCRYPTO_BLOCK_QCOW_H__ */
+#endif /* QCRYPTO_BLOCK_QCOW_H */
diff --git a/crypto/blockpriv.h b/crypto/blockpriv.h
index 62970859d0..15b547d952 100644
--- a/crypto/blockpriv.h
+++ b/crypto/blockpriv.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QCRYPTO_BLOCK_PRIV_H__
-#define QCRYPTO_BLOCK_PRIV_H__
+#ifndef QCRYPTO_BLOCKPRIV_H
+#define QCRYPTO_BLOCKPRIV_H
 
 #include "crypto/block.h"
 
@@ -89,4 +89,4 @@ int qcrypto_block_encrypt_helper(QCryptoCipher *cipher,
                                  size_t len,
                                  Error **errp);
 
-#endif /* QCRYPTO_BLOCK_PRIV_H__ */
+#endif /* QCRYPTO_BLOCKPRIV_H */
diff --git a/crypto/hash-gcrypt.c b/crypto/hash-gcrypt.c
index 8ea5aff4ee..ed6f842461 100644
--- a/crypto/hash-gcrypt.c
+++ b/crypto/hash-gcrypt.c
@@ -19,9 +19,9 @@
  */
 
 #include "qemu/osdep.h"
+#include <gcrypt.h>
 #include "qapi/error.h"
 #include "crypto/hash.h"
-#include "gcrypt.h"
 
 
 static int qcrypto_hash_alg_map[QCRYPTO_HASH_ALG__MAX] = {
diff --git a/crypto/ivgenpriv.h b/crypto/ivgenpriv.h
index 7b87e02ea7..28e5c67383 100644
--- a/crypto/ivgenpriv.h
+++ b/crypto/ivgenpriv.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QCRYPTO_IVGEN_PRIV_H__
-#define QCRYPTO_IVGEN_PRIV_H__
+#ifndef QCRYPTO_IVGENPRIV_H
+#define QCRYPTO_IVGENPRIV_H
 
 #include "crypto/ivgen.h"
 
@@ -46,4 +46,4 @@ struct QCryptoIVGen {
 };
 
 
-#endif /* QCRYPTO_IVGEN_PRIV_H__ */
+#endif /* QCRYPTO_IVGENPRIV_H */
diff --git a/crypto/pbkdf-gcrypt.c b/crypto/pbkdf-gcrypt.c
index 997b311d84..34af3a97e9 100644
--- a/crypto/pbkdf-gcrypt.c
+++ b/crypto/pbkdf-gcrypt.c
@@ -19,9 +19,9 @@
  */
 
 #include "qemu/osdep.h"
+#include <gcrypt.h>
 #include "qapi/error.h"
 #include "crypto/pbkdf.h"
-#include "gcrypt.h"
 
 bool qcrypto_pbkdf2_supports(QCryptoHashAlgorithm hash)
 {
diff --git a/crypto/pbkdf-nettle.c b/crypto/pbkdf-nettle.c
index db9fc15780..d681a606f9 100644
--- a/crypto/pbkdf-nettle.c
+++ b/crypto/pbkdf-nettle.c
@@ -19,9 +19,9 @@
  */
 
 #include "qemu/osdep.h"
+#include <nettle/pbkdf2.h>
 #include "qapi/error.h"
 #include "crypto/pbkdf.h"
-#include "nettle/pbkdf2.h"
 
 
 bool qcrypto_pbkdf2_supports(QCryptoHashAlgorithm hash)
diff --git a/crypto/tlscredspriv.h b/crypto/tlscredspriv.h
index 9222be4a9e..13e9b6c0b2 100644
--- a/crypto/tlscredspriv.h
+++ b/crypto/tlscredspriv.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QCRYPTO_TLSCRED_PRIV_H__
-#define QCRYPTO_TLSCRED_PRIV_H__
+#ifndef QCRYPTO_TLSCREDSPRIV_H
+#define QCRYPTO_TLSCREDSPRIV_H
 
 #include "crypto/tlscreds.h"
 
@@ -38,5 +38,4 @@ int qcrypto_tls_creds_get_dh_params_file(QCryptoTLSCreds *creds,
 
 #endif
 
-#endif /* QCRYPTO_TLSCRED_PRIV_H__ */
-
+#endif /* QCRYPTO_TLSCREDSPRIV_H */
diff --git a/docs/qmp-events.txt b/docs/qmp-events.txt
index fa7574d671..7967ec4c5a 100644
--- a/docs/qmp-events.txt
+++ b/docs/qmp-events.txt
@@ -92,7 +92,8 @@ Data:
 
 - "type":     Job type (json-string; "stream" for image streaming
                                      "commit" for block commit)
-- "device":   Device name (json-string)
+- "device":   Job identifier. Originally the device name but other
+              values are allowed since QEMU 2.7 (json-string)
 - "len":      Maximum progress value (json-int)
 - "offset":   Current progress value (json-int)
               On success this is equal to len.
@@ -116,7 +117,8 @@ Data:
 
 - "type":     Job type (json-string; "stream" for image streaming
                                      "commit" for block commit)
-- "device":   Device name (json-string)
+- "device":   Job identifier. Originally the device name but other
+              values are allowed since QEMU 2.7 (json-string)
 - "len":      Maximum progress value (json-int)
 - "offset":   Current progress value (json-int)
               On success this is equal to len.
@@ -143,7 +145,8 @@ Emitted when a block job encounters an error.
 
 Data:
 
-- "device": device name (json-string)
+- "device": Job identifier. Originally the device name but other
+            values are allowed since QEMU 2.7 (json-string)
 - "operation": I/O operation (json-string, "read" or "write")
 - "action": action that has been taken, it's one of the following (json-string):
     "ignore": error has been ignored, the job may fail later
@@ -167,7 +170,8 @@ Data:
 
 - "type":     Job type (json-string; "stream" for image streaming
                                      "commit" for block commit)
-- "device":   Device name (json-string)
+- "device":   Job identifier. Originally the device name but other
+              values are allowed since QEMU 2.7 (json-string)
 - "len":      Maximum progress value (json-int)
 - "offset":   Current progress value (json-int)
               On success this is equal to len.
diff --git a/docs/usb-storage.txt b/docs/usb-storage.txt
index c5a3866eeb..fbc1f2edd8 100644
--- a/docs/usb-storage.txt
+++ b/docs/usb-storage.txt
@@ -40,6 +40,18 @@ numbers must be continuous, i.e. for three devices you must use 0+1+2.
 The 0+1+5 numbering from the "usb-uas" example isn't going to work
 with "usb-bot".
 
+Starting with qemu version 2.7 usb-bot and usb-uas devices can be
+hotplugged.  In the hotplug case they are added with "attached =
+false" so the guest will not see the device until the "attached"
+property is explicitly set to true.  That allows to attach one or more
+scsi devices before making the device visible to the guest, i.e. the
+workflow looks like this:
+
+   (1) device-add usb-bot,id=foo
+   (2) device-add scsi-{hd,cd},bus=foo.0,lun=0
+   (2b) optionally add more devices (luns 1 ... 15).
+   (3) scripts/qmp/qom-set foo.attached = true
+
 enjoy,
   Gerd
 
diff --git a/exec.c b/exec.c
index 0122ef76de..011babd584 100644
--- a/exec.c
+++ b/exec.c
@@ -36,7 +36,7 @@
 #include "qemu/config-file.h"
 #include "qemu/error-report.h"
 #if defined(CONFIG_USER_ONLY)
-#include <qemu.h>
+#include "qemu.h"
 #else /* !CONFIG_USER_ONLY */
 #include "hw/hw.h"
 #include "exec/memory.h"
diff --git a/fsdev/9p-iov-marshal.c b/fsdev/9p-iov-marshal.c
index 584082b5d6..663cad5429 100644
--- a/fsdev/9p-iov-marshal.c
+++ b/fsdev/9p-iov-marshal.c
@@ -207,31 +207,25 @@ ssize_t v9fs_iov_vmarshal(struct iovec *in_sg, int in_num, size_t offset,
             break;
         }
         case 'w': {
-            uint16_t val;
+            uint16_t val = va_arg(ap, int);
             if (bswap) {
-                cpu_to_le16w(&val, va_arg(ap, int));
-            } else {
-                val =  va_arg(ap, int);
+                val = cpu_to_le16(val);
             }
             copied = v9fs_pack(in_sg, in_num, offset, &val, sizeof(val));
             break;
         }
         case 'd': {
-            uint32_t val;
+            uint32_t val = va_arg(ap, uint32_t);
             if (bswap) {
-                cpu_to_le32w(&val, va_arg(ap, uint32_t));
-            } else {
-                val =  va_arg(ap, uint32_t);
+                val = cpu_to_le32(val);
             }
             copied = v9fs_pack(in_sg, in_num, offset, &val, sizeof(val));
             break;
         }
         case 'q': {
-            uint64_t val;
+            uint64_t val = va_arg(ap, uint64_t);
             if (bswap) {
-                cpu_to_le64w(&val, va_arg(ap, uint64_t));
-            } else {
-                val =  va_arg(ap, uint64_t);
+                val = cpu_to_le64(val);
             }
             copied = v9fs_pack(in_sg, in_num, offset, &val, sizeof(val));
             break;
diff --git a/fsdev/9p-iov-marshal.h b/fsdev/9p-iov-marshal.h
index 6bccbfb41a..1fb5016853 100644
--- a/fsdev/9p-iov-marshal.h
+++ b/fsdev/9p-iov-marshal.h
@@ -1,5 +1,5 @@
-#ifndef _QEMU_9P_IOV_MARSHAL_H
-#define _QEMU_9P_IOV_MARSHAL_H
+#ifndef QEMU_9P_IOV_MARSHAL_H
+#define QEMU_9P_IOV_MARSHAL_H
 
 #include "9p-marshal.h"
 
diff --git a/fsdev/9p-marshal.h b/fsdev/9p-marshal.h
index e91b24e9ca..140db6d99f 100644
--- a/fsdev/9p-marshal.h
+++ b/fsdev/9p-marshal.h
@@ -1,5 +1,5 @@
-#ifndef _QEMU_9P_MARSHAL_H
-#define _QEMU_9P_MARSHAL_H
+#ifndef QEMU_9P_MARSHAL_H
+#define QEMU_9P_MARSHAL_H
 
 typedef struct V9fsString
 {
diff --git a/fsdev/file-op-9p.h b/fsdev/file-op-9p.h
index b1338ba06c..6db9feac8f 100644
--- a/fsdev/file-op-9p.h
+++ b/fsdev/file-op-9p.h
@@ -10,8 +10,10 @@
  * the COPYING file in the top-level directory.
  *
  */
-#ifndef _FILEOP_H
-#define _FILEOP_H
+
+#ifndef FILE_OP_9P_H
+#define FILE_OP_9P_H
+
 #include <dirent.h>
 #include <utime.h>
 #include <sys/vfs.h>
diff --git a/hmp.c b/hmp.c
index 0cf5baa069..3ca79c3ea3 100644
--- a/hmp.c
+++ b/hmp.c
@@ -1097,7 +1097,7 @@ void hmp_drive_mirror(Monitor *mon, const QDict *qdict)
         mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
     }
 
-    qmp_drive_mirror(device, filename, !!format, format,
+    qmp_drive_mirror(false, NULL, device, filename, !!format, format,
                      false, NULL, false, NULL,
                      full ? MIRROR_SYNC_MODE_FULL : MIRROR_SYNC_MODE_TOP,
                      true, mode, false, 0, false, 0, false, 0,
@@ -1127,7 +1127,7 @@ void hmp_drive_backup(Monitor *mon, const QDict *qdict)
         mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
     }
 
-    qmp_drive_backup(device, filename, !!format, format,
+    qmp_drive_backup(false, NULL, device, filename, !!format, format,
                      full ? MIRROR_SYNC_MODE_FULL : MIRROR_SYNC_MODE_TOP,
                      true, mode, false, 0, false, NULL,
                      false, 0, false, 0, &err);
@@ -1485,7 +1485,7 @@ void hmp_block_stream(Monitor *mon, const QDict *qdict)
     const char *base = qdict_get_try_str(qdict, "base");
     int64_t speed = qdict_get_try_int(qdict, "speed", 0);
 
-    qmp_block_stream(device, base != NULL, base, false, NULL,
+    qmp_block_stream(false, NULL, device, base != NULL, base, false, NULL,
                      qdict_haskey(qdict, "speed"), speed,
                      true, BLOCKDEV_ON_ERROR_REPORT, &error);
 
diff --git a/hw/9pfs/9p-proxy.h b/hw/9pfs/9p-proxy.h
index ba9ca203de..b84301d001 100644
--- a/hw/9pfs/9p-proxy.h
+++ b/hw/9pfs/9p-proxy.h
@@ -9,8 +9,9 @@
  * This work is licensed under the terms of the GNU GPL, version 2.  See
  * the COPYING file in the top-level directory.
  */
-#ifndef _QEMU_9P_PROXY_H
-#define _QEMU_9P_PROXY_H
+
+#ifndef QEMU_9P_PROXY_H
+#define QEMU_9P_PROXY_H
 
 #define PROXY_MAX_IO_SZ (64 * 1024)
 #define V9FS_FD_VALID INT_MAX
diff --git a/hw/9pfs/9p-synth.h b/hw/9pfs/9p-synth.h
index 7c8441bd6c..6bcb44ace2 100644
--- a/hw/9pfs/9p-synth.h
+++ b/hw/9pfs/9p-synth.h
@@ -10,9 +10,9 @@
  * the COPYING file in the top-level directory.
  *
  */
-#ifndef HW_9PFS_SYNTH_H
-#define HW_9PFS_SYNTH_H 1
 
+#ifndef QEMU_9P_SYNTH_H
+#define QEMU_9P_SYNTH_H
 
 typedef struct V9fsSynthNode V9fsSynthNode;
 typedef ssize_t (*v9fs_synth_read)(void *buf, int len, off_t offset,
diff --git a/hw/9pfs/9p-xattr.h b/hw/9pfs/9p-xattr.h
index 4d39a20262..a853ea641c 100644
--- a/hw/9pfs/9p-xattr.h
+++ b/hw/9pfs/9p-xattr.h
@@ -10,8 +10,9 @@
  * the COPYING file in the top-level directory.
  *
  */
-#ifndef _QEMU_9P_XATTR_H
-#define _QEMU_9P_XATTR_H
+
+#ifndef QEMU_9P_XATTR_H
+#define QEMU_9P_XATTR_H
 
 #include "qemu/xattr.h"
 
diff --git a/hw/9pfs/9p.c b/hw/9pfs/9p.c
index 9acff9293c..b6b02b46a9 100644
--- a/hw/9pfs/9p.c
+++ b/hw/9pfs/9p.c
@@ -3278,8 +3278,8 @@ void pdu_submit(V9fsPDU *pdu)
     if (is_ro_export(&s->ctx) && !is_read_only_op(pdu)) {
         handler = v9fs_fs_ro;
     }
-    co = qemu_coroutine_create(handler);
-    qemu_coroutine_enter(co, pdu);
+    co = qemu_coroutine_create(handler, pdu);
+    qemu_coroutine_enter(co);
 }
 
 /* Returns 0 on success, 1 on failure. */
diff --git a/hw/9pfs/9p.h b/hw/9pfs/9p.h
index d2030fdf56..b4f757ab54 100644
--- a/hw/9pfs/9p.h
+++ b/hw/9pfs/9p.h
@@ -1,5 +1,5 @@
-#ifndef _QEMU_9P_H
-#define _QEMU_9P_H
+#ifndef QEMU_9P_H
+#define QEMU_9P_H
 
 #include <dirent.h>
 #include <utime.h>
diff --git a/hw/9pfs/coth.c b/hw/9pfs/coth.c
index 9b1151b60e..89018de6bf 100644
--- a/hw/9pfs/coth.c
+++ b/hw/9pfs/coth.c
@@ -22,14 +22,14 @@
 static void coroutine_enter_cb(void *opaque, int ret)
 {
     Coroutine *co = opaque;
-    qemu_coroutine_enter(co, NULL);
+    qemu_coroutine_enter(co);
 }
 
 /* Called from worker thread.  */
 static int coroutine_enter_func(void *arg)
 {
     Coroutine *co = arg;
-    qemu_coroutine_enter(co, NULL);
+    qemu_coroutine_enter(co);
     return 0;
 }
 
diff --git a/hw/9pfs/coth.h b/hw/9pfs/coth.h
index 5b02a63ad9..3c7424e423 100644
--- a/hw/9pfs/coth.h
+++ b/hw/9pfs/coth.h
@@ -12,8 +12,8 @@
  *
  */
 
-#ifndef _QEMU_9P_COTH_H
-#define _QEMU_9P_COTH_H
+#ifndef QEMU_9P_COTH_H
+#define QEMU_9P_COTH_H
 
 #include "qemu/thread.h"
 #include "qemu/coroutine.h"
diff --git a/hw/9pfs/virtio-9p.h b/hw/9pfs/virtio-9p.h
index 7f6d885539..7586b792d6 100644
--- a/hw/9pfs/virtio-9p.h
+++ b/hw/9pfs/virtio-9p.h
@@ -1,5 +1,5 @@
-#ifndef _QEMU_VIRTIO_9P_H
-#define _QEMU_VIRTIO_9P_H
+#ifndef QEMU_VIRTIO_9P_H
+#define QEMU_VIRTIO_9P_H
 
 #include "standard-headers/linux/virtio_9p.h"
 #include "hw/virtio/virtio.h"
diff --git a/hw/alpha/alpha_sys.h b/hw/alpha/alpha_sys.h
index fcaeb2b7aa..ed911f22a1 100644
--- a/hw/alpha/alpha_sys.h
+++ b/hw/alpha/alpha_sys.h
@@ -1,7 +1,7 @@
 /* Alpha cores and system support chips.  */
 
-#ifndef HW_ALPHA_H
-#define HW_ALPHA_H 1
+#ifndef HW_ALPHA_SYS_H
+#define HW_ALPHA_SYS_H
 
 #include "target-alpha/cpu-qom.h"
 #include "hw/pci/pci.h"
diff --git a/hw/arm/strongarm.h b/hw/arm/strongarm.h
index cd32bbdb0e..1470eac4f5 100644
--- a/hw/arm/strongarm.h
+++ b/hw/arm/strongarm.h
@@ -1,5 +1,5 @@
-#ifndef _STRONGARM_H
-#define _STRONGARM_H
+#ifndef STRONGARM_H
+#define STRONGARM_H
 
 #include "exec/memory.h"
 #include "target-arm/cpu-qom.h"
diff --git a/hw/audio/fmopl.h b/hw/audio/fmopl.h
index 24ba5f4802..fdda7f9f51 100644
--- a/hw/audio/fmopl.h
+++ b/hw/audio/fmopl.h
@@ -1,5 +1,5 @@
-#ifndef __FMOPL_H_
-#define __FMOPL_H_
+#ifndef FMOPL_H
+#define FMOPL_H
 
 /* --- select emulation chips --- */
 #define BUILD_YM3812 (HAS_YM3812)
diff --git a/hw/audio/gusemu.h b/hw/audio/gusemu.h
index b7f0751268..9aec7bf8e7 100644
--- a/hw/audio/gusemu.h
+++ b/hw/audio/gusemu.h
@@ -101,4 +101,4 @@ void gus_irqgen(GUSEmuState *state, unsigned int elapsed_time);
 /* lower values won´t provide any benefit at all, higher values can cause audible timing delays */
 /* note: masked timers are also calculated by this function, thus it might be needed even without any IRQs in use! */
 
-#endif  /* gusemu.h */
+#endif /* GUSEMU_H */
diff --git a/hw/audio/gustate.h b/hw/audio/gustate.h
index ece903abb9..d16297110d 100644
--- a/hw/audio/gustate.h
+++ b/hw/audio/gustate.h
@@ -129,4 +129,4 @@
 
 #define gusdataend (VSRegsEnd+4)
 
-#endif  /* gustate.h */
+#endif /* GUSTATE_H */
diff --git a/hw/audio/lm4549.h b/hw/audio/lm4549.h
index 812a7a4440..74c3ee8934 100644
--- a/hw/audio/lm4549.h
+++ b/hw/audio/lm4549.h
@@ -40,4 +40,4 @@ uint32_t lm4549_read(lm4549_state *s, hwaddr offset);
 void lm4549_write(lm4549_state *s, hwaddr offset, uint32_t value);
 uint32_t lm4549_write_samples(lm4549_state *s, uint32_t left, uint32_t right);
 
-#endif /* #ifndef HW_LM4549_H */
+#endif /* HW_LM4549_H */
diff --git a/hw/audio/pl041.h b/hw/audio/pl041.h
index 427ab6d6f8..515db4756b 100644
--- a/hw/audio/pl041.h
+++ b/hw/audio/pl041.h
@@ -132,4 +132,4 @@ enum {
 #define RXTOFEC3     (1 << 11)
 #define RXTOFEC4     (1 << 12)
 
-#endif /* #ifndef HW_PL041_H */
+#endif /* HW_PL041_H */
diff --git a/hw/block/block.c b/hw/block/block.c
index 97a59d4fa2..8dc9d84a39 100644
--- a/hw/block/block.c
+++ b/hw/block/block.c
@@ -51,6 +51,34 @@ void blkconf_blocksizes(BlockConf *conf)
     }
 }
 
+void blkconf_apply_backend_options(BlockConf *conf)
+{
+    BlockBackend *blk = conf->blk;
+    BlockdevOnError rerror, werror;
+    bool wce;
+
+    switch (conf->wce) {
+    case ON_OFF_AUTO_ON:    wce = true; break;
+    case ON_OFF_AUTO_OFF:   wce = false; break;
+    case ON_OFF_AUTO_AUTO:  wce = blk_enable_write_cache(blk); break;
+    default:
+        abort();
+    }
+
+    rerror = conf->rerror;
+    if (rerror == BLOCKDEV_ON_ERROR_AUTO) {
+        rerror = blk_get_on_error(blk, true);
+    }
+
+    werror = conf->werror;
+    if (werror == BLOCKDEV_ON_ERROR_AUTO) {
+        werror = blk_get_on_error(blk, false);
+    }
+
+    blk_set_enable_write_cache(blk, wce);
+    blk_set_on_error(blk, rerror, werror);
+}
+
 void blkconf_geometry(BlockConf *conf, int *ptrans,
                       unsigned cyls_max, unsigned heads_max, unsigned secs_max,
                       Error **errp)
diff --git a/hw/block/nvme.c b/hw/block/nvme.c
index 9faad29fad..2ded2475ee 100644
--- a/hw/block/nvme.c
+++ b/hw/block/nvme.c
@@ -21,10 +21,10 @@
  */
 
 #include "qemu/osdep.h"
-#include <hw/block/block.h>
-#include <hw/hw.h>
-#include <hw/pci/msix.h>
-#include <hw/pci/pci.h>
+#include "hw/block/block.h"
+#include "hw/hw.h"
+#include "hw/pci/msix.h"
+#include "hw/pci/pci.h"
 #include "sysemu/sysemu.h"
 #include "qapi/error.h"
 #include "qapi/visitor.h"
@@ -803,6 +803,7 @@ static int nvme_init(PCIDevice *pci_dev)
         return -1;
     }
     blkconf_blocksizes(&n->conf);
+    blkconf_apply_backend_options(&n->conf);
 
     pci_conf = pci_dev->config;
     pci_conf[PCI_INTERRUPT_PIN] = 1;
diff --git a/hw/block/virtio-blk.c b/hw/block/virtio-blk.c
index ae86e944ea..357ff9081e 100644
--- a/hw/block/virtio-blk.c
+++ b/hw/block/virtio-blk.c
@@ -897,6 +897,7 @@ static void virtio_blk_device_realize(DeviceState *dev, Error **errp)
     }
 
     blkconf_serial(&conf->conf, &conf->serial);
+    blkconf_apply_backend_options(&conf->conf);
     s->original_wce = blk_enable_write_cache(conf->conf.blk);
     blkconf_geometry(&conf->conf, NULL, 65535, 255, 255, &err);
     if (err) {
@@ -959,6 +960,7 @@ static void virtio_blk_instance_init(Object *obj)
 
 static Property virtio_blk_properties[] = {
     DEFINE_BLOCK_PROPERTIES(VirtIOBlock, conf.conf),
+    DEFINE_BLOCK_ERROR_PROPERTIES(VirtIOBlock, conf.conf),
     DEFINE_BLOCK_CHS_PROPERTIES(VirtIOBlock, conf.conf),
     DEFINE_PROP_STRING("serial", VirtIOBlock, conf.serial),
     DEFINE_PROP_BIT("config-wce", VirtIOBlock, conf.config_wce, 0, true),
diff --git a/hw/block/xen_blkif.h b/hw/block/xen_blkif.h
index 0738684410..3300b6fc0a 100644
--- a/hw/block/xen_blkif.h
+++ b/hw/block/xen_blkif.h
@@ -1,5 +1,5 @@
-#ifndef __XEN_BLKIF_H__
-#define __XEN_BLKIF_H__
+#ifndef XEN_BLKIF_H
+#define XEN_BLKIF_H
 
 #include <xen/io/ring.h>
 #include <xen/io/blkif.h>
@@ -143,4 +143,4 @@ static inline void blkif_get_x86_64_req(blkif_request_t *dst,
     }
 }
 
-#endif /* __XEN_BLKIF_H__ */
+#endif /* XEN_BLKIF_H */
diff --git a/hw/bt/hci.c b/hw/bt/hci.c
index 7d52205093..351123fab7 100644
--- a/hw/bt/hci.c
+++ b/hw/bt/hci.c
@@ -426,11 +426,7 @@ static void bt_submit_raw_acl(struct bt_piconet_s *net, int length, uint8_t *dat
  * be continuously allocated.  We do it though, to preserve similar
  * behaviour between hosts.  Some things, like the BD_ADDR cannot be
  * preserved though (for example if a real hci is used).  */
-#ifdef HOST_WORDS_BIGENDIAN
-# define HNDL(raw)	bswap16(raw)
-#else
-# define HNDL(raw)	(raw)
-#endif
+#define HNDL(raw) cpu_to_le16(raw)
 
 static const uint8_t bt_event_reserved_mask[8] = {
     0xff, 0x9f, 0xfb, 0xff, 0x07, 0x18, 0x00, 0x00,
@@ -1504,8 +1500,8 @@ static void bt_submit_hci(struct HCIInfo *info,
         return;
 
 #define PARAM(cmd, param)	(((cmd##_cp *) data)->param)
-#define PARAM16(cmd, param)	le16_to_cpup(&PARAM(cmd, param))
-#define PARAMHANDLE(cmd)	HNDL(PARAM(cmd, handle))
+#define PARAM16(cmd, param) lduw_le_p(&PARAM(cmd, param))
+#define PARAMHANDLE(cmd) PARAM16(cmd, handle)
 #define LENGTH_CHECK(cmd)	if (length < sizeof(cmd##_cp)) goto short_hci
     /* Note: the supported commands bitmask in bt_hci_read_local_commands_rp
      * needs to be updated every time a command is implemented here!  */
diff --git a/hw/bt/l2cap.c b/hw/bt/l2cap.c
index dfc95ed048..e342045140 100644
--- a/hw/bt/l2cap.c
+++ b/hw/bt/l2cap.c
@@ -526,9 +526,9 @@ static int l2cap_channel_config(struct l2cap_instance_s *l2cap,
             }
 
             /* MTU */
-            val = le16_to_cpup((void *) opt->val);
+            val = lduw_le_p(opt->val);
             if (val < ch->min_mtu) {
-                cpu_to_le16w((void *) opt->val, ch->min_mtu);
+                stw_le_p(opt->val, ch->min_mtu);
                 result = L2CAP_CONF_UNACCEPT;
                 break;
             }
@@ -543,7 +543,7 @@ static int l2cap_channel_config(struct l2cap_instance_s *l2cap,
             }
 
             /* Flush Timeout */
-            val = le16_to_cpup((void *) opt->val);
+            val = lduw_le_p(opt->val);
             if (val < 0x0001) {
                 opt->val[0] = 0xff;
                 opt->val[1] = 0xff;
@@ -987,7 +987,7 @@ static void l2cap_bframe_in(struct l2cap_chan_s *ch, uint16_t cid,
 static void l2cap_iframe_in(struct l2cap_chan_s *ch, uint16_t cid,
                 const l2cap_hdr *hdr, int len)
 {
-    uint16_t fcs = le16_to_cpup((void *) (hdr->data + len - 2));
+    uint16_t fcs = lduw_le_p(hdr->data + len - 2);
 
     if (len < 4)
         goto len_error;
@@ -1002,7 +1002,7 @@ static void l2cap_iframe_in(struct l2cap_chan_s *ch, uint16_t cid,
             /* TODO: Signal an error? */
             return;
         }
-        l2cap_sframe_in(ch, le16_to_cpup((void *) hdr->data));
+        l2cap_sframe_in(ch, lduw_le_p(hdr->data));
         return;
     }
 
@@ -1022,7 +1022,7 @@ static void l2cap_iframe_in(struct l2cap_chan_s *ch, uint16_t cid,
         if (len - 6 > ch->mps)
             goto len_error;
 
-        ch->len_total = le16_to_cpup((void *) (hdr->data + 2));
+        ch->len_total = lduw_le_p(hdr->data + 2);
         if (len >= 6 + ch->len_total)
             goto seg_error;
 
diff --git a/hw/char/sclpconsole.c b/hw/char/sclpconsole.c
index 15a5b2b2b5..d22464826b 100644
--- a/hw/char/sclpconsole.c
+++ b/hw/char/sclpconsole.c
@@ -13,7 +13,7 @@
  */
 
 #include "qemu/osdep.h"
-#include <hw/qdev.h>
+#include "hw/qdev.h"
 #include "qemu/thread.h"
 #include "qemu/error-report.h"
 
diff --git a/hw/core/qdev-properties-system.c b/hw/core/qdev-properties-system.c
index 65d9fa9f53..ab1bc5e945 100644
--- a/hw/core/qdev-properties-system.c
+++ b/hw/core/qdev-properties-system.c
@@ -72,12 +72,21 @@ static void parse_drive(DeviceState *dev, const char *str, void **ptr,
                         const char *propname, Error **errp)
 {
     BlockBackend *blk;
+    bool blk_created = false;
 
     blk = blk_by_name(str);
     if (!blk) {
+        BlockDriverState *bs = bdrv_lookup_bs(NULL, str, NULL);
+        if (bs) {
+            blk = blk_new();
+            blk_insert_bs(blk, bs);
+            blk_created = true;
+        }
+    }
+    if (!blk) {
         error_setg(errp, "Property '%s.%s' can't find value '%s'",
                    object_get_typename(OBJECT(dev)), propname, str);
-        return;
+        goto fail;
     }
     if (blk_attach_dev(blk, dev) < 0) {
         DriveInfo *dinfo = blk_legacy_dinfo(blk);
@@ -91,9 +100,16 @@ static void parse_drive(DeviceState *dev, const char *str, void **ptr,
             error_setg(errp, "Drive '%s' is already in use by another device",
                        str);
         }
-        return;
+        goto fail;
     }
+
     *ptr = blk;
+
+fail:
+    if (blk_created) {
+        /* If we need to keep a reference, blk_attach_dev() took it */
+        blk_unref(blk);
+    }
 }
 
 static void release_drive(Object *obj, const char *name, void *opaque)
@@ -103,8 +119,8 @@ static void release_drive(Object *obj, const char *name, void *opaque)
     BlockBackend **ptr = qdev_get_prop_ptr(dev, prop);
 
     if (*ptr) {
-        blk_detach_dev(*ptr, dev);
         blockdev_auto_del(*ptr);
+        blk_detach_dev(*ptr, dev);
     }
 }
 
@@ -127,7 +143,7 @@ static void set_drive(Object *obj, Visitor *v, const char *name, void *opaque,
 
 PropertyInfo qdev_prop_drive = {
     .name  = "str",
-    .description = "ID of a drive to use as a backend",
+    .description = "Node name or ID of a block device to use as a backend",
     .get   = get_drive,
     .set   = set_drive,
     .release = release_drive,
@@ -362,8 +378,19 @@ PropertyInfo qdev_prop_vlan = {
 void qdev_prop_set_drive(DeviceState *dev, const char *name,
                          BlockBackend *value, Error **errp)
 {
-    object_property_set_str(OBJECT(dev), value ? blk_name(value) : "",
-                            name, errp);
+    const char *ref = "";
+
+    if (value) {
+        ref = blk_name(value);
+        if (!*ref) {
+            BlockDriverState *bs = blk_bs(value);
+            if (bs) {
+                ref = bdrv_get_node_name(bs);
+            }
+        }
+    }
+
+    object_property_set_str(OBJECT(dev), ref, name, errp);
 }
 
 void qdev_prop_set_chr(DeviceState *dev, const char *name,
diff --git a/hw/core/qdev-properties.c b/hw/core/qdev-properties.c
index 3c20c8e4b2..14e544ab17 100644
--- a/hw/core/qdev-properties.c
+++ b/hw/core/qdev-properties.c
@@ -539,6 +539,19 @@ PropertyInfo qdev_prop_losttickpolicy = {
     .set   = set_enum,
 };
 
+/* --- Block device error handling policy --- */
+
+QEMU_BUILD_BUG_ON(sizeof(BlockdevOnError) != sizeof(int));
+
+PropertyInfo qdev_prop_blockdev_on_error = {
+    .name = "BlockdevOnError",
+    .description = "Error handling policy, "
+                   "report/ignore/enospc/stop/auto",
+    .enum_table = BlockdevOnError_lookup,
+    .get = get_enum,
+    .set = set_enum,
+};
+
 /* --- BIOS CHS translation */
 
 QEMU_BUILD_BUG_ON(sizeof(BiosAtaTranslation) != sizeof(int));
diff --git a/hw/core/uboot_image.h b/hw/core/uboot_image.h
index 9fc2760b53..34c11a70a6 100644
--- a/hw/core/uboot_image.h
+++ b/hw/core/uboot_image.h
@@ -26,8 +26,8 @@
  ********************************************************************
  */
 
-#ifndef __UBOOT_IMAGE_H__
-#define __UBOOT_IMAGE_H__
+#ifndef UBOOT_IMAGE_H
+#define UBOOT_IMAGE_H
 
 /*
  * Operating System Codes
@@ -155,4 +155,4 @@ typedef struct uboot_image_header {
 } uboot_image_header_t;
 
 
-#endif	/* __IMAGE_H__ */
+#endif /* UBOOT_IMAGE_H */
diff --git a/hw/cris/boot.h b/hw/cris/boot.h
index c4d3fa6f6f..218854e5d1 100644
--- a/hw/cris/boot.h
+++ b/hw/cris/boot.h
@@ -1,5 +1,5 @@
-#ifndef _CRIS_BOOT_H
-#define HW_CRIS_BOOT_H 1
+#ifndef HW_CRIS_BOOT_H
+#define HW_CRIS_BOOT_H
 
 struct cris_load_info
 {
diff --git a/hw/display/qxl.h b/hw/display/qxl.h
index fdb619d4a7..d2d49dd933 100644
--- a/hw/display/qxl.h
+++ b/hw/display/qxl.h
@@ -1,5 +1,5 @@
 #ifndef HW_QXL_H
-#define HW_QXL_H 1
+#define HW_QXL_H
 
 #include "qemu-common.h"
 
diff --git a/hw/display/vga.h b/hw/display/vga.h
index d917046da6..16886f5eed 100644
--- a/hw/display/vga.h
+++ b/hw/display/vga.h
@@ -14,8 +14,8 @@
  *
  */
 
-#ifndef __linux_video_vga_h__
-#define __linux_video_vga_h__
+#ifndef LINUX_VIDEO_VGA_H
+#define LINUX_VIDEO_VGA_H
 
 /* Some of the code below is taken from SVGAlib.  The original,
    unmodified copyright notice for that code is below. */
@@ -156,4 +156,4 @@
 /* VGA graphics controller bit masks */
 #define VGA_GR06_GRAPHICS_MODE  0x01
 
-#endif /* __linux_video_vga_h__ */
+#endif /* LINUX_VIDEO_VGA_H */
diff --git a/hw/display/vga_int.h b/hw/display/vga_int.h
index 3ce5544efd..dd6c958da3 100644
--- a/hw/display/vga_int.h
+++ b/hw/display/vga_int.h
@@ -21,10 +21,11 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
+
 #ifndef HW_VGA_INT_H
-#define HW_VGA_INT_H 1
+#define HW_VGA_INT_H
 
-#include <hw/hw.h>
+#include "hw/hw.h"
 #include "exec/memory.h"
 
 #define ST01_V_RETRACE      0x08
diff --git a/hw/display/virtio-gpu-3d.c b/hw/display/virtio-gpu-3d.c
index d6c8c6e2dc..758d33a09d 100644
--- a/hw/display/virtio-gpu-3d.c
+++ b/hw/display/virtio-gpu-3d.c
@@ -21,7 +21,7 @@
 
 #ifdef CONFIG_VIRGL
 
-#include "virglrenderer.h"
+#include <virglrenderer.h>
 
 static struct virgl_renderer_callbacks virtio_gpu_3d_cbs;
 
diff --git a/hw/display/virtio-gpu.c b/hw/display/virtio-gpu.c
index f8b0274752..929c3c8b8a 100644
--- a/hw/display/virtio-gpu.c
+++ b/hw/display/virtio-gpu.c
@@ -28,7 +28,7 @@ static struct virtio_gpu_simple_resource*
 virtio_gpu_find_resource(VirtIOGPU *g, uint32_t resource_id);
 
 #ifdef CONFIG_VIRGL
-#include "virglrenderer.h"
+#include <virglrenderer.h>
 #define VIRGL(_g, _virgl, _simple, ...)                     \
     do {                                                    \
         if (_g->use_virgl_renderer) {                       \
diff --git a/hw/i386/kvm/i8254.c b/hw/i386/kvm/i8254.c
index 734992ead0..521a58498a 100644
--- a/hw/i386/kvm/i8254.c
+++ b/hw/i386/kvm/i8254.c
@@ -22,14 +22,15 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
+
 #include "qemu/osdep.h"
+#include <linux/kvm.h>
 #include "qapi/error.h"
 #include "qemu/timer.h"
 #include "sysemu/sysemu.h"
 #include "hw/timer/i8254.h"
 #include "hw/timer/i8254_internal.h"
 #include "sysemu/kvm.h"
-#include "linux/kvm.h"
 
 #define KVM_PIT_REINJECT_BIT 0
 
diff --git a/hw/i386/kvm/pci-assign.c b/hw/i386/kvm/pci-assign.c
index 3623aa1965..1a429e5402 100644
--- a/hw/i386/kvm/pci-assign.c
+++ b/hw/i386/kvm/pci-assign.c
@@ -20,7 +20,9 @@
  *  Copyright (C) 2008, Red Hat, Amit Shah (amit.shah@redhat.com)
  *  Copyright (C) 2008, IBM, Muli Ben-Yehuda (muli@il.ibm.com)
  */
+
 #include "qemu/osdep.h"
+#include <linux/kvm.h>
 #include "qapi/error.h"
 #include "hw/hw.h"
 #include "hw/i386/pc.h"
@@ -32,7 +34,6 @@
 #include "sysemu/sysemu.h"
 #include "hw/pci/pci.h"
 #include "hw/pci/msi.h"
-#include "linux/kvm.h"
 #include "kvm_i386.h"
 #include "hw/pci/pci-assign.h"
 
diff --git a/hw/ide/ahci.c b/hw/ide/ahci.c
index b1a7b65a7b..bcb9ff9e1b 100644
--- a/hw/ide/ahci.c
+++ b/hw/ide/ahci.c
@@ -22,17 +22,17 @@
  */
 
 #include "qemu/osdep.h"
-#include <hw/hw.h>
-#include <hw/pci/msi.h>
-#include <hw/i386/pc.h>
-#include <hw/pci/pci.h>
+#include "hw/hw.h"
+#include "hw/pci/msi.h"
+#include "hw/i386/pc.h"
+#include "hw/pci/pci.h"
 
 #include "qemu/error-report.h"
 #include "sysemu/block-backend.h"
 #include "sysemu/dma.h"
-#include <hw/ide/internal.h>
-#include <hw/ide/pci.h>
-#include <hw/ide/ahci.h>
+#include "hw/ide/internal.h"
+#include "hw/ide/pci.h"
+#include "hw/ide/ahci.h"
 
 #define DEBUG_AHCI 0
 
diff --git a/hw/ide/cmd646.c b/hw/ide/cmd646.c
index 49294a5314..9ebb8d4fb2 100644
--- a/hw/ide/cmd646.c
+++ b/hw/ide/cmd646.c
@@ -23,15 +23,15 @@
  * THE SOFTWARE.
  */
 #include "qemu/osdep.h"
-#include <hw/hw.h>
-#include <hw/i386/pc.h>
-#include <hw/pci/pci.h>
-#include <hw/isa/isa.h>
+#include "hw/hw.h"
+#include "hw/i386/pc.h"
+#include "hw/pci/pci.h"
+#include "hw/isa/isa.h"
 #include "sysemu/block-backend.h"
 #include "sysemu/sysemu.h"
 #include "sysemu/dma.h"
 
-#include <hw/ide/pci.h>
+#include "hw/ide/pci.h"
 
 /* CMD646 specific */
 #define CFR		0x50
diff --git a/hw/ide/core.c b/hw/ide/core.c
index 029f6b9b12..f2d131b0d3 100644
--- a/hw/ide/core.c
+++ b/hw/ide/core.c
@@ -23,10 +23,10 @@
  * THE SOFTWARE.
  */
 #include "qemu/osdep.h"
-#include <hw/hw.h>
-#include <hw/i386/pc.h>
-#include <hw/pci/pci.h>
-#include <hw/isa/isa.h>
+#include "hw/hw.h"
+#include "hw/i386/pc.h"
+#include "hw/pci/pci.h"
+#include "hw/isa/isa.h"
 #include "qemu/error-report.h"
 #include "qemu/timer.h"
 #include "sysemu/sysemu.h"
@@ -35,7 +35,7 @@
 #include "sysemu/block-backend.h"
 #include "qemu/cutils.h"
 
-#include <hw/ide/internal.h>
+#include "hw/ide/internal.h"
 
 /* These values were based on a Seagate ST3500418AS but have been modified
    to make more sense in QEMU */
diff --git a/hw/ide/ich.c b/hw/ide/ich.c
index 920ec276ed..459916977e 100644
--- a/hw/ide/ich.c
+++ b/hw/ide/ich.c
@@ -61,15 +61,15 @@
  */
 
 #include "qemu/osdep.h"
-#include <hw/hw.h>
-#include <hw/pci/msi.h>
-#include <hw/i386/pc.h>
-#include <hw/pci/pci.h>
-#include <hw/isa/isa.h>
+#include "hw/hw.h"
+#include "hw/pci/msi.h"
+#include "hw/i386/pc.h"
+#include "hw/pci/pci.h"
+#include "hw/isa/isa.h"
 #include "sysemu/block-backend.h"
 #include "sysemu/dma.h"
-#include <hw/ide/pci.h>
-#include <hw/ide/ahci.h>
+#include "hw/ide/pci.h"
+#include "hw/ide/ahci.h"
 
 #define ICH9_MSI_CAP_OFFSET     0x80
 #define ICH9_SATA_CAP_OFFSET    0xA8
diff --git a/hw/ide/isa.c b/hw/ide/isa.c
index eba567c877..40213d662c 100644
--- a/hw/ide/isa.c
+++ b/hw/ide/isa.c
@@ -23,13 +23,13 @@
  * THE SOFTWARE.
  */
 #include "qemu/osdep.h"
-#include <hw/hw.h>
-#include <hw/i386/pc.h>
-#include <hw/isa/isa.h>
+#include "hw/hw.h"
+#include "hw/i386/pc.h"
+#include "hw/isa/isa.h"
 #include "sysemu/block-backend.h"
 #include "sysemu/dma.h"
 
-#include <hw/ide/internal.h>
+#include "hw/ide/internal.h"
 
 /***********************************************************/
 /* ISA IDE definitions */
diff --git a/hw/ide/macio.c b/hw/ide/macio.c
index 56cc50661f..5a326afd96 100644
--- a/hw/ide/macio.c
+++ b/hw/ide/macio.c
@@ -29,7 +29,7 @@
 #include "sysemu/block-backend.h"
 #include "sysemu/dma.h"
 
-#include <hw/ide/internal.h>
+#include "hw/ide/internal.h"
 
 /* debug MACIO */
 // #define DEBUG_MACIO
diff --git a/hw/ide/microdrive.c b/hw/ide/microdrive.c
index 5c9db8047d..e3fd30e457 100644
--- a/hw/ide/microdrive.c
+++ b/hw/ide/microdrive.c
@@ -23,13 +23,13 @@
  * THE SOFTWARE.
  */
 #include "qemu/osdep.h"
-#include <hw/hw.h>
-#include <hw/i386/pc.h>
-#include <hw/pcmcia.h>
+#include "hw/hw.h"
+#include "hw/i386/pc.h"
+#include "hw/pcmcia.h"
 #include "sysemu/block-backend.h"
 #include "sysemu/dma.h"
 
-#include <hw/ide/internal.h>
+#include "hw/ide/internal.h"
 
 #define TYPE_MICRODRIVE "microdrive"
 #define MICRODRIVE(obj) OBJECT_CHECK(MicroDriveState, (obj), TYPE_MICRODRIVE)
diff --git a/hw/ide/mmio.c b/hw/ide/mmio.c
index 493f65a1d0..6f12f456ed 100644
--- a/hw/ide/mmio.c
+++ b/hw/ide/mmio.c
@@ -28,7 +28,7 @@
 #include "sysemu/block-backend.h"
 #include "sysemu/dma.h"
 
-#include <hw/ide/internal.h>
+#include "hw/ide/internal.h"
 
 /***********************************************************/
 /* MMIO based ide port
diff --git a/hw/ide/pci.c b/hw/ide/pci.c
index 8d56a00b1b..3cfb510afe 100644
--- a/hw/ide/pci.c
+++ b/hw/ide/pci.c
@@ -23,14 +23,14 @@
  * THE SOFTWARE.
  */
 #include "qemu/osdep.h"
-#include <hw/hw.h>
-#include <hw/i386/pc.h>
-#include <hw/pci/pci.h>
-#include <hw/isa/isa.h>
+#include "hw/hw.h"
+#include "hw/i386/pc.h"
+#include "hw/pci/pci.h"
+#include "hw/isa/isa.h"
 #include "sysemu/block-backend.h"
 #include "sysemu/dma.h"
 #include "qemu/error-report.h"
-#include <hw/ide/pci.h>
+#include "hw/ide/pci.h"
 
 #define BMDMA_PAGE_SIZE 4096
 
diff --git a/hw/ide/piix.c b/hw/ide/piix.c
index 6d76ce980b..c190fcaa3c 100644
--- a/hw/ide/piix.c
+++ b/hw/ide/piix.c
@@ -24,15 +24,15 @@
  */
 
 #include "qemu/osdep.h"
-#include <hw/hw.h>
-#include <hw/i386/pc.h>
-#include <hw/pci/pci.h>
-#include <hw/isa/isa.h>
+#include "hw/hw.h"
+#include "hw/i386/pc.h"
+#include "hw/pci/pci.h"
+#include "hw/isa/isa.h"
 #include "sysemu/block-backend.h"
 #include "sysemu/sysemu.h"
 #include "sysemu/dma.h"
 
-#include <hw/ide/pci.h>
+#include "hw/ide/pci.h"
 
 static uint64_t bmdma_read(void *opaque, hwaddr addr, unsigned size)
 {
diff --git a/hw/ide/qdev.c b/hw/ide/qdev.c
index 6842a5596a..67c76bfcd6 100644
--- a/hw/ide/qdev.c
+++ b/hw/ide/qdev.c
@@ -17,11 +17,11 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 #include "qemu/osdep.h"
-#include <hw/hw.h>
+#include "hw/hw.h"
 #include "sysemu/dma.h"
 #include "qapi/error.h"
 #include "qemu/error-report.h"
-#include <hw/ide/internal.h>
+#include "hw/ide/internal.h"
 #include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/block/block.h"
@@ -180,6 +180,7 @@ static int ide_dev_initfn(IDEDevice *dev, IDEDriveKind kind)
             return -1;
         }
     }
+    blkconf_apply_backend_options(&dev->conf);
 
     if (ide_init_drive(s, dev->conf.blk, kind,
                        dev->version, dev->serial, dev->model, dev->wwn,
@@ -263,6 +264,7 @@ static int ide_drive_initfn(IDEDevice *dev)
 
 #define DEFINE_IDE_DEV_PROPERTIES()                     \
     DEFINE_BLOCK_PROPERTIES(IDEDrive, dev.conf),        \
+    DEFINE_BLOCK_ERROR_PROPERTIES(IDEDrive, dev.conf),  \
     DEFINE_PROP_STRING("ver",  IDEDrive, dev.version),  \
     DEFINE_PROP_UINT64("wwn",  IDEDrive, dev.wwn, 0),    \
     DEFINE_PROP_STRING("serial",  IDEDrive, dev.serial),\
diff --git a/hw/ide/via.c b/hw/ide/via.c
index d3f72267a1..5b32ecb386 100644
--- a/hw/ide/via.c
+++ b/hw/ide/via.c
@@ -24,15 +24,15 @@
  * THE SOFTWARE.
  */
 #include "qemu/osdep.h"
-#include <hw/hw.h>
-#include <hw/i386/pc.h>
-#include <hw/pci/pci.h>
-#include <hw/isa/isa.h>
+#include "hw/hw.h"
+#include "hw/i386/pc.h"
+#include "hw/pci/pci.h"
+#include "hw/isa/isa.h"
 #include "sysemu/block-backend.h"
 #include "sysemu/sysemu.h"
 #include "sysemu/dma.h"
 
-#include <hw/ide/pci.h>
+#include "hw/ide/pci.h"
 
 static uint64_t bmdma_read(void *opaque, hwaddr addr,
                            unsigned size)
diff --git a/hw/input/hid.c b/hw/input/hid.c
index d92c7463ba..5e2850e655 100644
--- a/hw/input/hid.c
+++ b/hw/input/hid.c
@@ -27,6 +27,7 @@
 #include "ui/console.h"
 #include "qemu/timer.h"
 #include "hw/input/hid.h"
+#include "trace.h"
 
 #define HID_USAGE_ERROR_ROLLOVER        0x01
 #define HID_USAGE_POSTFAIL              0x02
@@ -234,7 +235,7 @@ static void hid_keyboard_event(DeviceState *dev, QemuConsole *src,
                                              key->down,
                                              scancodes);
     if (hs->n + count > QUEUE_LENGTH) {
-        fprintf(stderr, "usb-kbd: warning: key event queue full\n");
+        trace_hid_kbd_queue_full();
         return;
     }
     for (i = 0; i < count; i++) {
diff --git a/hw/input/trace-events b/hw/input/trace-events
index 00fcec12b9..f24dff2f8b 100644
--- a/hw/input/trace-events
+++ b/hw/input/trace-events
@@ -23,3 +23,9 @@ milkymist_softusb_memory_write(uint32_t addr, uint32_t value) "addr %08x value %
 milkymist_softusb_mevt(uint8_t m) "m %d"
 milkymist_softusb_kevt(uint8_t m) "m %d"
 milkymist_softusb_pulse_irq(void) "Pulse IRQ"
+
+# hw/input/hid.c
+hid_kbd_queue_full(void) "queue full"
+
+# hw/input/virtio
+virtio_input_queue_full(void) "queue full"
diff --git a/hw/input/virtio-input.c b/hw/input/virtio-input.c
index f59749a943..edf69903a6 100644
--- a/hw/input/virtio-input.c
+++ b/hw/input/virtio-input.c
@@ -7,6 +7,7 @@
 #include "qemu/osdep.h"
 #include "qapi/error.h"
 #include "qemu/iov.h"
+#include "trace.h"
 
 #include "hw/qdev.h"
 #include "hw/virtio/virtio.h"
@@ -47,7 +48,7 @@ void virtio_input_send(VirtIOInput *vinput, virtio_input_event *event)
     virtqueue_get_avail_bytes(vinput->evt, &have, NULL, need, 0);
     if (have < need) {
         vinput->qindex = 0;
-        fprintf(stderr, "%s: ENOSPC in vq, dropping events\n", __func__);
+        trace_virtio_input_queue_full();
         return;
     }
 
diff --git a/hw/intc/Makefile.objs b/hw/intc/Makefile.objs
index 530df2eba6..05ec21b21e 100644
--- a/hw/intc/Makefile.objs
+++ b/hw/intc/Makefile.objs
@@ -37,3 +37,4 @@ obj-$(CONFIG_S390_FLIC) += s390_flic.o
 obj-$(CONFIG_S390_FLIC_KVM) += s390_flic_kvm.o
 obj-$(CONFIG_ASPEED_SOC) += aspeed_vic.o
 obj-$(CONFIG_ARM_GIC) += arm_gicv3_cpuif.o
+obj-$(CONFIG_MIPS_CPS) += mips_gic.o
diff --git a/hw/intc/gic_internal.h b/hw/intc/gic_internal.h
index 20c1e8a242..3f311740da 100644
--- a/hw/intc/gic_internal.h
+++ b/hw/intc/gic_internal.h
@@ -100,4 +100,4 @@ static inline bool gic_test_pending(GICState *s, int irq, int cm)
     }
 }
 
-#endif /* !QEMU_ARM_GIC_INTERNAL_H */
+#endif /* QEMU_ARM_GIC_INTERNAL_H */
diff --git a/hw/intc/gicv3_internal.h b/hw/intc/gicv3_internal.h
index 6ce5d49bde..8f3567edaa 100644
--- a/hw/intc/gicv3_internal.h
+++ b/hw/intc/gicv3_internal.h
@@ -328,4 +328,4 @@ static inline void gicv3_cache_all_target_cpustates(GICv3State *s)
     }
 }
 
-#endif /* !QEMU_ARM_GIC_INTERNAL_H */
+#endif /* QEMU_ARM_GICV3_INTERNAL_H */
diff --git a/hw/intc/mips_gic.c b/hw/intc/mips_gic.c
new file mode 100644
index 0000000000..6e257730f8
--- /dev/null
+++ b/hw/intc/mips_gic.c
@@ -0,0 +1,460 @@
+/*
+ * This file is subject to the terms and conditions of the GNU General Public
+ * License.  See the file "COPYING" in the main directory of this archive
+ * for more details.
+ *
+ * Copyright (C) 2012  MIPS Technologies, Inc.  All rights reserved.
+ * Authors: Sanjay Lal <sanjayl@kymasys.com>
+ *
+ * Copyright (C) 2016 Imagination Technologies
+ */
+
+#include "qemu/osdep.h"
+#include "qemu/log.h"
+#include "qapi/error.h"
+#include "hw/hw.h"
+#include "hw/sysbus.h"
+#include "exec/memory.h"
+#include "sysemu/sysemu.h"
+#include "sysemu/kvm.h"
+#include "kvm_mips.h"
+#include "hw/intc/mips_gic.h"
+
+static void mips_gic_set_vp_irq(MIPSGICState *gic, int vp, int pin, int level)
+{
+    int ored_level = level;
+    int i;
+
+    /* ORing pending registers sharing same pin */
+    if (!ored_level) {
+        for (i = 0; i < gic->num_irq; i++) {
+            if ((gic->irq_state[i].map_pin & GIC_MAP_MSK) == pin &&
+                    gic->irq_state[i].map_vp == vp &&
+                    gic->irq_state[i].enabled) {
+                ored_level |= gic->irq_state[i].pending;
+            }
+            if (ored_level) {
+                /* no need to iterate all interrupts */
+                break;
+            }
+        }
+        if (((gic->vps[vp].compare_map & GIC_MAP_MSK) == pin) &&
+                (gic->vps[vp].mask & GIC_VP_MASK_CMP_MSK)) {
+            /* ORing with local pending register (count/compare) */
+            ored_level |= (gic->vps[vp].pend & GIC_VP_MASK_CMP_MSK) >>
+                          GIC_VP_MASK_CMP_SHF;
+        }
+    }
+    if (kvm_enabled())  {
+        kvm_mips_set_ipi_interrupt(mips_env_get_cpu(gic->vps[vp].env),
+                                   pin + GIC_CPU_PIN_OFFSET,
+                                   ored_level);
+    } else {
+        qemu_set_irq(gic->vps[vp].env->irq[pin + GIC_CPU_PIN_OFFSET],
+                     ored_level);
+    }
+}
+
+static void gic_set_irq(void *opaque, int n_IRQ, int level)
+{
+    MIPSGICState *gic = (MIPSGICState *) opaque;
+    int vp = gic->irq_state[n_IRQ].map_vp;
+    int pin = gic->irq_state[n_IRQ].map_pin & GIC_MAP_MSK;
+
+    gic->irq_state[n_IRQ].pending = (uint8_t) level;
+    if (!gic->irq_state[n_IRQ].enabled) {
+        /* GIC interrupt source disabled */
+        return;
+    }
+    if (vp < 0 || vp >= gic->num_vps) {
+        return;
+    }
+    mips_gic_set_vp_irq(gic, vp, pin, level);
+}
+
+#define OFFSET_CHECK(c)                         \
+    do {                                        \
+        if (!(c)) {                             \
+            goto bad_offset;                    \
+        }                                       \
+    } while (0)
+
+/* GIC Read VP Local/Other Registers */
+static uint64_t gic_read_vp(MIPSGICState *gic, uint32_t vp_index, hwaddr addr,
+                            unsigned size)
+{
+    switch (addr) {
+    case GIC_VP_CTL_OFS:
+        return gic->vps[vp_index].ctl;
+    case GIC_VP_PEND_OFS:
+        mips_gictimer_get_sh_count(gic->gic_timer);
+        return gic->vps[vp_index].pend;
+    case GIC_VP_MASK_OFS:
+        return gic->vps[vp_index].mask;
+    case GIC_VP_COMPARE_MAP_OFS:
+        return gic->vps[vp_index].compare_map;
+    case GIC_VP_OTHER_ADDR_OFS:
+        return gic->vps[vp_index].other_addr;
+    case GIC_VP_IDENT_OFS:
+        return vp_index;
+    case GIC_VP_COMPARE_LO_OFS:
+        return mips_gictimer_get_vp_compare(gic->gic_timer, vp_index);
+    case GIC_VP_COMPARE_HI_OFS:
+        return 0;
+    default:
+        qemu_log_mask(LOG_UNIMP, "Read %d bytes at GIC offset LOCAL/OTHER 0x%"
+                      PRIx64 "\n", size, addr);
+        break;
+    }
+    return 0;
+}
+
+static uint64_t gic_read(void *opaque, hwaddr addr, unsigned size)
+{
+    MIPSGICState *gic = (MIPSGICState *) opaque;
+    uint32_t vp_index = current_cpu->cpu_index;
+    uint64_t ret = 0;
+    int i, base, irq_src;
+    uint32_t other_index;
+
+    switch (addr) {
+    case GIC_SH_CONFIG_OFS:
+        ret = gic->sh_config | (mips_gictimer_get_countstop(gic->gic_timer) <<
+                               GIC_SH_CONFIG_COUNTSTOP_SHF);
+        break;
+    case GIC_SH_COUNTERLO_OFS:
+        ret = mips_gictimer_get_sh_count(gic->gic_timer);
+        break;
+    case GIC_SH_COUNTERHI_OFS:
+        ret = 0;
+        break;
+    case GIC_SH_PEND_OFS ... GIC_SH_PEND_LAST_OFS:
+        /* each bit represents pending status for an interrupt pin */
+        base = (addr - GIC_SH_PEND_OFS) * 8;
+        OFFSET_CHECK((base + size * 8) <= gic->num_irq);
+        for (i = 0; i < size * 8; i++) {
+            ret |= (uint64_t) (gic->irq_state[base + i].pending) << i;
+        }
+        break;
+    case GIC_SH_MASK_OFS ... GIC_SH_MASK_LAST_OFS:
+        /* each bit represents status for an interrupt pin */
+        base = (addr - GIC_SH_MASK_OFS) * 8;
+        OFFSET_CHECK((base + size * 8) <= gic->num_irq);
+        for (i = 0; i < size * 8; i++) {
+            ret |= (uint64_t) (gic->irq_state[base + i].enabled) << i;
+        }
+        break;
+    case GIC_SH_MAP0_PIN_OFS ... GIC_SH_MAP255_PIN_OFS:
+        /* 32 bits per a pin */
+        irq_src = (addr - GIC_SH_MAP0_PIN_OFS) / 4;
+        OFFSET_CHECK(irq_src < gic->num_irq);
+        ret = gic->irq_state[irq_src].map_pin;
+        break;
+    case GIC_SH_MAP0_VP_OFS ... GIC_SH_MAP255_VP_LAST_OFS:
+        /* up to 32 bytes per a pin */
+        irq_src = (addr - GIC_SH_MAP0_VP_OFS) / 32;
+        OFFSET_CHECK(irq_src < gic->num_irq);
+        if ((gic->irq_state[irq_src].map_vp) >= 0) {
+            ret = (uint64_t) 1 << (gic->irq_state[irq_src].map_vp);
+        } else {
+            ret = 0;
+        }
+        break;
+    /* VP-Local Register */
+    case VP_LOCAL_SECTION_OFS ... (VP_LOCAL_SECTION_OFS + GIC_VL_BRK_GROUP):
+        ret = gic_read_vp(gic, vp_index, addr - VP_LOCAL_SECTION_OFS, size);
+        break;
+    /* VP-Other Register */
+    case VP_OTHER_SECTION_OFS ... (VP_OTHER_SECTION_OFS + GIC_VL_BRK_GROUP):
+        other_index = gic->vps[vp_index].other_addr;
+        ret = gic_read_vp(gic, other_index, addr - VP_OTHER_SECTION_OFS, size);
+        break;
+    /* User-Mode Visible section */
+    case USM_VISIBLE_SECTION_OFS + GIC_USER_MODE_COUNTERLO:
+        ret = mips_gictimer_get_sh_count(gic->gic_timer);
+        break;
+    case USM_VISIBLE_SECTION_OFS + GIC_USER_MODE_COUNTERHI:
+        ret = 0;
+        break;
+    default:
+        qemu_log_mask(LOG_UNIMP, "Read %d bytes at GIC offset 0x%" PRIx64 "\n",
+                      size, addr);
+        break;
+    }
+    return ret;
+bad_offset:
+    qemu_log_mask(LOG_GUEST_ERROR, "Wrong GIC offset at 0x%" PRIx64 "\n", addr);
+    return 0;
+}
+
+static void gic_timer_expire_cb(void *opaque, uint32_t vp_index)
+{
+    MIPSGICState *gic = opaque;
+
+    gic->vps[vp_index].pend |= (1 << GIC_LOCAL_INT_COMPARE);
+    if (gic->vps[vp_index].pend &
+            (gic->vps[vp_index].mask & GIC_VP_MASK_CMP_MSK)) {
+        if (gic->vps[vp_index].compare_map & GIC_MAP_TO_PIN_MSK) {
+            /* it is safe to set the irq high regardless of other GIC IRQs */
+            uint32_t pin = (gic->vps[vp_index].compare_map & GIC_MAP_MSK);
+            qemu_irq_raise(gic->vps[vp_index].env->irq
+                           [pin + GIC_CPU_PIN_OFFSET]);
+        }
+    }
+}
+
+static void gic_timer_store_vp_compare(MIPSGICState *gic, uint32_t vp_index,
+                                       uint64_t compare)
+{
+    gic->vps[vp_index].pend &= ~(1 << GIC_LOCAL_INT_COMPARE);
+    if (gic->vps[vp_index].compare_map & GIC_MAP_TO_PIN_MSK) {
+        uint32_t pin = (gic->vps[vp_index].compare_map & GIC_MAP_MSK);
+        mips_gic_set_vp_irq(gic, vp_index, pin, 0);
+    }
+    mips_gictimer_store_vp_compare(gic->gic_timer, vp_index, compare);
+}
+
+/* GIC Write VP Local/Other Registers */
+static void gic_write_vp(MIPSGICState *gic, uint32_t vp_index, hwaddr addr,
+                              uint64_t data, unsigned size)
+{
+    switch (addr) {
+    case GIC_VP_CTL_OFS:
+        /* EIC isn't supported */
+        break;
+    case GIC_VP_RMASK_OFS:
+        gic->vps[vp_index].mask &= ~(data & GIC_VP_SET_RESET_MSK) &
+                                   GIC_VP_SET_RESET_MSK;
+        break;
+    case GIC_VP_SMASK_OFS:
+        gic->vps[vp_index].mask |= data & GIC_VP_SET_RESET_MSK;
+        break;
+    case GIC_VP_COMPARE_MAP_OFS:
+        /* EIC isn't supported */
+        OFFSET_CHECK((data & GIC_MAP_MSK) <= GIC_CPU_INT_MAX);
+        gic->vps[vp_index].compare_map = data & GIC_MAP_TO_PIN_REG_MSK;
+        break;
+    case GIC_VP_OTHER_ADDR_OFS:
+        OFFSET_CHECK(data < gic->num_vps);
+        gic->vps[vp_index].other_addr = data;
+        break;
+    case GIC_VP_COMPARE_LO_OFS:
+        gic_timer_store_vp_compare(gic, vp_index, data);
+        break;
+    default:
+        qemu_log_mask(LOG_UNIMP, "Write %d bytes at GIC offset LOCAL/OTHER "
+                      "0x%" PRIx64" 0x%08" PRIx64 "\n", size, addr, data);
+        break;
+    }
+    return;
+bad_offset:
+    qemu_log_mask(LOG_GUEST_ERROR, "Wrong GIC offset at 0x%" PRIx64 "\n", addr);
+    return;
+}
+
+static void gic_write(void *opaque, hwaddr addr, uint64_t data, unsigned size)
+{
+    int intr;
+    MIPSGICState *gic = (MIPSGICState *) opaque;
+    uint32_t vp_index = current_cpu->cpu_index;
+    int i, base, irq_src;
+    uint32_t other_index;
+
+    switch (addr) {
+    case GIC_SH_CONFIG_OFS:
+        {
+            uint32_t pre_cntstop = mips_gictimer_get_countstop(gic->gic_timer);
+            uint32_t new_cntstop = (data & GIC_SH_CONFIG_COUNTSTOP_MSK) >>
+                                   GIC_SH_CONFIG_COUNTSTOP_SHF;
+            if (pre_cntstop != new_cntstop) {
+                if (new_cntstop == 1) {
+                    mips_gictimer_stop_count(gic->gic_timer);
+                } else {
+                    mips_gictimer_start_count(gic->gic_timer);
+                }
+            }
+        }
+        break;
+    case GIC_SH_COUNTERLO_OFS:
+        if (mips_gictimer_get_countstop(gic->gic_timer)) {
+            mips_gictimer_store_sh_count(gic->gic_timer, data);
+        }
+        break;
+    case GIC_SH_RMASK_OFS ... GIC_SH_RMASK_LAST_OFS:
+        /* up to 64 bits per a pin */
+        base = (addr - GIC_SH_RMASK_OFS) * 8;
+        OFFSET_CHECK((base + size * 8) <= gic->num_irq);
+        for (i = 0; i < size * 8; i++) {
+            gic->irq_state[base + i].enabled &= !((data >> i) & 1);
+        }
+        break;
+    case GIC_SH_WEDGE_OFS:
+        /* Figure out which VP/HW Interrupt this maps to */
+        intr = data & ~GIC_SH_WEDGE_RW_MSK;
+        /* Mask/Enabled Checks */
+        OFFSET_CHECK(intr < gic->num_irq);
+        if (data & GIC_SH_WEDGE_RW_MSK) {
+            gic_set_irq(gic, intr, 1);
+        } else {
+            gic_set_irq(gic, intr, 0);
+        }
+        break;
+    case GIC_SH_SMASK_OFS ... GIC_SH_SMASK_LAST_OFS:
+        /* up to 64 bits per a pin */
+        base = (addr - GIC_SH_SMASK_OFS) * 8;
+        OFFSET_CHECK((base + size * 8) <= gic->num_irq);
+        for (i = 0; i < size * 8; i++) {
+            gic->irq_state[base + i].enabled |= (data >> i) & 1;
+        }
+        break;
+    case GIC_SH_MAP0_PIN_OFS ... GIC_SH_MAP255_PIN_OFS:
+        /* 32 bits per a pin */
+        irq_src = (addr - GIC_SH_MAP0_PIN_OFS) / 4;
+        OFFSET_CHECK(irq_src < gic->num_irq);
+        /* EIC isn't supported */
+        OFFSET_CHECK((data & GIC_MAP_MSK) <= GIC_CPU_INT_MAX);
+        gic->irq_state[irq_src].map_pin = data & GIC_MAP_TO_PIN_REG_MSK;
+        break;
+    case GIC_SH_MAP0_VP_OFS ... GIC_SH_MAP255_VP_LAST_OFS:
+        /* up to 32 bytes per a pin */
+        irq_src = (addr - GIC_SH_MAP0_VP_OFS) / 32;
+        OFFSET_CHECK(irq_src < gic->num_irq);
+        data = data ? ctz64(data) : -1;
+        OFFSET_CHECK(data < gic->num_vps);
+        gic->irq_state[irq_src].map_vp = data;
+        break;
+    case VP_LOCAL_SECTION_OFS ... (VP_LOCAL_SECTION_OFS + GIC_VL_BRK_GROUP):
+        gic_write_vp(gic, vp_index, addr - VP_LOCAL_SECTION_OFS, data, size);
+        break;
+    case VP_OTHER_SECTION_OFS ... (VP_OTHER_SECTION_OFS + GIC_VL_BRK_GROUP):
+        other_index = gic->vps[vp_index].other_addr;
+        gic_write_vp(gic, other_index, addr - VP_OTHER_SECTION_OFS, data, size);
+        break;
+    case USM_VISIBLE_SECTION_OFS + GIC_USER_MODE_COUNTERLO:
+    case USM_VISIBLE_SECTION_OFS + GIC_USER_MODE_COUNTERHI:
+        /* do nothing. Read-only section */
+        break;
+    default:
+        qemu_log_mask(LOG_UNIMP, "Write %d bytes at GIC offset 0x%" PRIx64
+                      " 0x%08" PRIx64 "\n", size, addr, data);
+        break;
+    }
+    return;
+bad_offset:
+    qemu_log_mask(LOG_GUEST_ERROR, "Wrong GIC offset at 0x%" PRIx64 "\n", addr);
+}
+
+static void gic_reset(void *opaque)
+{
+    int i;
+    MIPSGICState *gic = (MIPSGICState *) opaque;
+    int numintrs = (gic->num_irq / 8) - 1;
+
+    gic->sh_config = /* COUNTSTOP = 0 it is accessible via MIPSGICTimer*/
+                     /* CounterHi not implemented */
+                     (0            << GIC_SH_CONFIG_COUNTBITS_SHF) |
+                     (numintrs     << GIC_SH_CONFIG_NUMINTRS_SHF)  |
+                     (gic->num_vps << GIC_SH_CONFIG_PVPS_SHF);
+    for (i = 0; i < gic->num_vps; i++) {
+        gic->vps[i].ctl         = 0x0;
+        gic->vps[i].pend        = 0x0;
+        /* PERFCNT, TIMER and WD not implemented */
+        gic->vps[i].mask        = 0x32;
+        gic->vps[i].compare_map = GIC_MAP_TO_PIN_MSK;
+        mips_gictimer_store_vp_compare(gic->gic_timer, i, 0xffffffff);
+        gic->vps[i].other_addr  = 0x0;
+    }
+    for (i = 0; i < gic->num_irq; i++) {
+        gic->irq_state[i].enabled = 0;
+        gic->irq_state[i].pending = 0;
+        gic->irq_state[i].map_pin = GIC_MAP_TO_PIN_MSK;
+        gic->irq_state[i].map_vp  = -1;
+    }
+    mips_gictimer_store_sh_count(gic->gic_timer, 0);
+    /* COUNTSTOP = 0 */
+    mips_gictimer_start_count(gic->gic_timer);
+}
+
+static const MemoryRegionOps gic_ops = {
+    .read = gic_read,
+    .write = gic_write,
+    .endianness = DEVICE_NATIVE_ENDIAN,
+    .impl = {
+        .max_access_size = 8,
+    },
+};
+
+static void mips_gic_init(Object *obj)
+{
+    SysBusDevice *sbd = SYS_BUS_DEVICE(obj);
+    MIPSGICState *s = MIPS_GIC(obj);
+
+    memory_region_init_io(&s->mr, OBJECT(s), &gic_ops, s,
+                          "mips-gic", GIC_ADDRSPACE_SZ);
+    sysbus_init_mmio(sbd, &s->mr);
+    qemu_register_reset(gic_reset, s);
+}
+
+static void mips_gic_realize(DeviceState *dev, Error **errp)
+{
+    MIPSGICState *s = MIPS_GIC(dev);
+    CPUState *cs = first_cpu;
+    int i;
+
+    if (s->num_vps > GIC_MAX_VPS) {
+        error_setg(errp, "Exceeded maximum CPUs %d", s->num_vps);
+        return;
+    }
+    if ((s->num_irq > GIC_MAX_INTRS) || (s->num_irq % 8) || (s->num_irq <= 0)) {
+        error_setg(errp, "GIC supports up to %d external interrupts in "
+                   "multiples of 8 : %d", GIC_MAX_INTRS, s->num_irq);
+        return;
+    }
+    s->vps = g_new(MIPSGICVPState, s->num_vps);
+    s->irq_state = g_new(MIPSGICIRQState, s->num_irq);
+    /* Register the env for all VPs with the GIC */
+    for (i = 0; i < s->num_vps; i++) {
+        if (cs != NULL) {
+            s->vps[i].env = cs->env_ptr;
+            cs = CPU_NEXT(cs);
+        } else {
+            error_setg(errp,
+               "Unable to initialize GIC, CPUState for CPU#%d not valid.", i);
+            return;
+        }
+    }
+    s->gic_timer = mips_gictimer_init(s, s->num_vps, gic_timer_expire_cb);
+    qdev_init_gpio_in(dev, gic_set_irq, s->num_irq);
+    for (i = 0; i < s->num_irq; i++) {
+        s->irq_state[i].irq = qdev_get_gpio_in(dev, i);
+    }
+}
+
+static Property mips_gic_properties[] = {
+    DEFINE_PROP_INT32("num-vp", MIPSGICState, num_vps, 1),
+    DEFINE_PROP_INT32("num-irq", MIPSGICState, num_irq, 256),
+    DEFINE_PROP_END_OF_LIST(),
+};
+
+static void mips_gic_class_init(ObjectClass *klass, void *data)
+{
+    DeviceClass *dc = DEVICE_CLASS(klass);
+
+    dc->props = mips_gic_properties;
+    dc->realize = mips_gic_realize;
+}
+
+static const TypeInfo mips_gic_info = {
+    .name          = TYPE_MIPS_GIC,
+    .parent        = TYPE_SYS_BUS_DEVICE,
+    .instance_size = sizeof(MIPSGICState),
+    .instance_init = mips_gic_init,
+    .class_init    = mips_gic_class_init,
+};
+
+static void mips_gic_register_types(void)
+{
+    type_register_static(&mips_gic_info);
+}
+
+type_init(mips_gic_register_types)
diff --git a/hw/lm32/lm32.h b/hw/lm32/lm32.h
index e338bfeae5..db9eb29ea4 100644
--- a/hw/lm32/lm32.h
+++ b/hw/lm32/lm32.h
@@ -1,5 +1,5 @@
 #ifndef HW_LM32_H
-#define HW_LM32_H 1
+#define HW_LM32_H
 
 #include "hw/char/lm32_juart.h"
 
diff --git a/hw/lm32/milkymist-hw.h b/hw/lm32/milkymist-hw.h
index eb6a3a2559..4418b44ca9 100644
--- a/hw/lm32/milkymist-hw.h
+++ b/hw/lm32/milkymist-hw.h
@@ -1,5 +1,5 @@
-#ifndef QEMU_HW_MILKYMIST_H
-#define QEMU_HW_MILKYMIST_H
+#ifndef QEMU_HW_MILKYMIST_HW_H
+#define QEMU_HW_MILKYMIST_HW_H
 
 #include "hw/qdev.h"
 #include "net/net.h"
@@ -203,4 +203,4 @@ static inline DeviceState *milkymist_softusb_create(hwaddr base,
     return dev;
 }
 
-#endif /* QEMU_HW_MILKYMIST_H */
+#endif /* QEMU_HW_MILKYMIST_HW_H */
diff --git a/hw/microblaze/boot.h b/hw/microblaze/boot.h
index 0eb7f8e4f6..dd1090d8b5 100644
--- a/hw/microblaze/boot.h
+++ b/hw/microblaze/boot.h
@@ -1,5 +1,5 @@
-#ifndef __MICROBLAZE_BOOT__
-#define __MICROBLAZE_BOOT__
+#ifndef MICROBLAZE_BOOT_H
+#define MICROBLAZE_BOOT_H
 
 #include "hw/hw.h"
 
@@ -9,4 +9,4 @@ void microblaze_load_kernel(MicroBlazeCPU *cpu, hwaddr ddr_base,
                             const char *dtb_filename,
                             void (*machine_cpu_reset)(MicroBlazeCPU *));
 
-#endif /* __MICROBLAZE_BOOT __ */
+#endif /* MICROBLAZE_BOOT_H */
diff --git a/hw/mips/cps.c b/hw/mips/cps.c
index 61208f8c69..77c621797a 100644
--- a/hw/mips/cps.c
+++ b/hw/mips/cps.c
@@ -26,13 +26,8 @@
 
 qemu_irq get_cps_irq(MIPSCPSState *s, int pin_number)
 {
-    MIPSCPU *cpu = MIPS_CPU(first_cpu);
-    CPUMIPSState *env = &cpu->env;
-
     assert(pin_number < s->num_irq);
-
-    /* TODO: return GIC pins once implemented */
-    return env->irq[pin_number];
+    return s->gic.irq_state[pin_number].irq;
 }
 
 static void mips_cps_init(Object *obj)
@@ -130,6 +125,21 @@ static void mips_cps_realize(DeviceState *dev, Error **errp)
     memory_region_add_subregion(&s->container, 0,
                             sysbus_mmio_get_region(SYS_BUS_DEVICE(&s->cpc), 0));
 
+    /* Global Interrupt Controller */
+    object_initialize(&s->gic, sizeof(s->gic), TYPE_MIPS_GIC);
+    qdev_set_parent_bus(DEVICE(&s->gic), sysbus_get_default());
+
+    object_property_set_int(OBJECT(&s->gic), s->num_vp, "num-vp", &err);
+    object_property_set_int(OBJECT(&s->gic), 128, "num-irq", &err);
+    object_property_set_bool(OBJECT(&s->gic), true, "realized", &err);
+    if (err != NULL) {
+        error_propagate(errp, err);
+        return;
+    }
+
+    memory_region_add_subregion(&s->container, 0,
+                            sysbus_mmio_get_region(SYS_BUS_DEVICE(&s->gic), 0));
+
     /* Global Configuration Registers */
     gcr_base = env->CP0_CMGCRBase << 4;
 
@@ -139,6 +149,7 @@ static void mips_cps_realize(DeviceState *dev, Error **errp)
     object_property_set_int(OBJECT(&s->gcr), s->num_vp, "num-vp", &err);
     object_property_set_int(OBJECT(&s->gcr), 0x800, "gcr-rev", &err);
     object_property_set_int(OBJECT(&s->gcr), gcr_base, "gcr-base", &err);
+    object_property_set_link(OBJECT(&s->gcr), OBJECT(&s->gic.mr), "gic", &err);
     object_property_set_link(OBJECT(&s->gcr), OBJECT(&s->cpc.mr), "cpc", &err);
     object_property_set_bool(OBJECT(&s->gcr), true, "realized", &err);
     if (err != NULL) {
@@ -152,7 +163,7 @@ static void mips_cps_realize(DeviceState *dev, Error **errp)
 
 static Property mips_cps_properties[] = {
     DEFINE_PROP_UINT32("num-vp", MIPSCPSState, num_vp, 1),
-    DEFINE_PROP_UINT32("num-irq", MIPSCPSState, num_irq, 8),
+    DEFINE_PROP_UINT32("num-irq", MIPSCPSState, num_irq, 256),
     DEFINE_PROP_STRING("cpu-model", MIPSCPSState, cpu_model),
     DEFINE_PROP_END_OF_LIST()
 };
diff --git a/hw/mips/mips_malta.c b/hw/mips/mips_malta.c
index 5c8ba44c62..34d41ef44a 100644
--- a/hw/mips/mips_malta.c
+++ b/hw/mips/mips_malta.c
@@ -955,9 +955,7 @@ static void create_cps(MaltaState *s, const char *cpu_model,
 
     sysbus_mmio_map_overlap(SYS_BUS_DEVICE(s->cps), 0, 0, 1);
 
-    /* FIXME: When GIC is present then we should use GIC's IRQ 3.
-       Until then CPS exposes CPU's IRQs thus use the default IRQ 2. */
-    *i8259_irq = get_cps_irq(s->cps, 2);
+    *i8259_irq = get_cps_irq(s->cps, 3);
     *cbus_irq = NULL;
 }
 
diff --git a/hw/misc/hyperv_testdev.c b/hw/misc/hyperv_testdev.c
index 1883fd7f20..6cae9e9010 100644
--- a/hw/misc/hyperv_testdev.c
+++ b/hw/misc/hyperv_testdev.c
@@ -12,11 +12,11 @@
  */
 
 #include "qemu/osdep.h"
+#include <linux/kvm.h>
 #include "hw/hw.h"
 #include "hw/qdev.h"
 #include "hw/isa/isa.h"
 #include "sysemu/kvm.h"
-#include "linux/kvm.h"
 #include "target-i386/hyperv.h"
 #include "kvm_i386.h"
 
diff --git a/hw/misc/mips_cmgcr.c b/hw/misc/mips_cmgcr.c
index 40f34643e3..b3ba16694e 100644
--- a/hw/misc/mips_cmgcr.c
+++ b/hw/misc/mips_cmgcr.c
@@ -17,12 +17,18 @@
 #include "sysemu/sysemu.h"
 #include "hw/misc/mips_cmgcr.h"
 #include "hw/misc/mips_cpc.h"
+#include "hw/intc/mips_gic.h"
 
 static inline bool is_cpc_connected(MIPSGCRState *s)
 {
     return s->cpc_mr != NULL;
 }
 
+static inline bool is_gic_connected(MIPSGCRState *s)
+{
+    return s->gic_mr != NULL;
+}
+
 static inline void update_cpc_base(MIPSGCRState *gcr, uint64_t val)
 {
     if (is_cpc_connected(gcr)) {
@@ -36,10 +42,25 @@ static inline void update_cpc_base(MIPSGCRState *gcr, uint64_t val)
     }
 }
 
+static inline void update_gic_base(MIPSGCRState *gcr, uint64_t val)
+{
+    if (is_gic_connected(gcr)) {
+        gcr->gic_base = val & GCR_GIC_BASE_MSK;
+        memory_region_transaction_begin();
+        memory_region_set_address(gcr->gic_mr,
+                                  gcr->gic_base & GCR_GIC_BASE_GICBASE_MSK);
+        memory_region_set_enabled(gcr->gic_mr,
+                                  gcr->gic_base & GCR_GIC_BASE_GICEN_MSK);
+        memory_region_transaction_commit();
+    }
+}
+
 /* Read GCR registers */
 static uint64_t gcr_read(void *opaque, hwaddr addr, unsigned size)
 {
     MIPSGCRState *gcr = (MIPSGCRState *) opaque;
+    MIPSGCRVPState *current_vps = &gcr->vps[current_cpu->cpu_index];
+    MIPSGCRVPState *other_vps = &gcr->vps[current_vps->other];
 
     switch (addr) {
     /* Global Control Block Register */
@@ -50,8 +71,12 @@ static uint64_t gcr_read(void *opaque, hwaddr addr, unsigned size)
         return gcr->gcr_base;
     case GCR_REV_OFS:
         return gcr->gcr_rev;
+    case GCR_GIC_BASE_OFS:
+        return gcr->gic_base;
     case GCR_CPC_BASE_OFS:
         return gcr->cpc_base;
+    case GCR_GIC_STATUS_OFS:
+        return is_gic_connected(gcr);
     case GCR_CPC_STATUS_OFS:
         return is_cpc_connected(gcr);
     case GCR_L2_CONFIG_OFS:
@@ -62,8 +87,14 @@ static uint64_t gcr_read(void *opaque, hwaddr addr, unsigned size)
     case MIPS_COCB_OFS + GCR_CL_CONFIG_OFS:
         /* Set PVP to # of VPs - 1 */
         return gcr->num_vps - 1;
+    case MIPS_CLCB_OFS + GCR_CL_RESETBASE_OFS:
+        return current_vps->reset_base;
+    case MIPS_COCB_OFS + GCR_CL_RESETBASE_OFS:
+        return other_vps->reset_base;
     case MIPS_CLCB_OFS + GCR_CL_OTHER_OFS:
-        return 0;
+        return current_vps->other;
+    case MIPS_COCB_OFS + GCR_CL_OTHER_OFS:
+        return other_vps->other;
     default:
         qemu_log_mask(LOG_UNIMP, "Read %d bytes at GCR offset 0x%" HWADDR_PRIx
                       "\n", size, addr);
@@ -72,15 +103,46 @@ static uint64_t gcr_read(void *opaque, hwaddr addr, unsigned size)
     return 0;
 }
 
+static inline target_ulong get_exception_base(MIPSGCRVPState *vps)
+{
+    /* TODO: BEV_BASE and SELECT_BEV */
+    return (int32_t)(vps->reset_base & GCR_CL_RESET_BASE_RESETBASE_MSK);
+}
+
 /* Write GCR registers */
 static void gcr_write(void *opaque, hwaddr addr, uint64_t data, unsigned size)
 {
     MIPSGCRState *gcr = (MIPSGCRState *)opaque;
+    MIPSGCRVPState *current_vps = &gcr->vps[current_cpu->cpu_index];
+    MIPSGCRVPState *other_vps = &gcr->vps[current_vps->other];
 
     switch (addr) {
+    case GCR_GIC_BASE_OFS:
+        update_gic_base(gcr, data);
+        break;
     case GCR_CPC_BASE_OFS:
         update_cpc_base(gcr, data);
         break;
+    case MIPS_CLCB_OFS + GCR_CL_RESETBASE_OFS:
+        current_vps->reset_base = data & GCR_CL_RESET_BASE_MSK;
+        cpu_set_exception_base(current_cpu->cpu_index,
+                               get_exception_base(current_vps));
+        break;
+    case MIPS_COCB_OFS + GCR_CL_RESETBASE_OFS:
+        other_vps->reset_base = data & GCR_CL_RESET_BASE_MSK;
+        cpu_set_exception_base(current_vps->other,
+                               get_exception_base(other_vps));
+        break;
+    case MIPS_CLCB_OFS + GCR_CL_OTHER_OFS:
+        if ((data & GCR_CL_OTHER_MSK) < gcr->num_vps) {
+            current_vps->other = data & GCR_CL_OTHER_MSK;
+        }
+        break;
+    case MIPS_COCB_OFS + GCR_CL_OTHER_OFS:
+        if ((data & GCR_CL_OTHER_MSK) < gcr->num_vps) {
+            other_vps->other = data & GCR_CL_OTHER_MSK;
+        }
+        break;
     default:
         qemu_log_mask(LOG_UNIMP, "Write %d bytes at GCR offset 0x%" HWADDR_PRIx
                       " 0x%" PRIx64 "\n", size, addr, data);
@@ -102,6 +164,12 @@ static void mips_gcr_init(Object *obj)
     SysBusDevice *sbd = SYS_BUS_DEVICE(obj);
     MIPSGCRState *s = MIPS_GCR(obj);
 
+    object_property_add_link(obj, "gic", TYPE_MEMORY_REGION,
+                             (Object **)&s->gic_mr,
+                             qdev_prop_allow_set_link_before_realize,
+                             OBJ_PROP_LINK_UNREF_ON_RELEASE,
+                             &error_abort);
+
     object_property_add_link(obj, "cpc", TYPE_MEMORY_REGION,
                              (Object **)&s->cpc_mr,
                              qdev_prop_allow_set_link_before_realize,
@@ -116,8 +184,16 @@ static void mips_gcr_init(Object *obj)
 static void mips_gcr_reset(DeviceState *dev)
 {
     MIPSGCRState *s = MIPS_GCR(dev);
+    int i;
 
+    update_gic_base(s, 0);
     update_cpc_base(s, 0);
+
+    for (i = 0; i < s->num_vps; i++) {
+        s->vps[i].other = 0;
+        s->vps[i].reset_base = 0xBFC00000 & GCR_CL_RESET_BASE_MSK;
+        cpu_set_exception_base(i, get_exception_base(&s->vps[i]));
+    }
 }
 
 static const VMStateDescription vmstate_mips_gcr = {
@@ -137,12 +213,21 @@ static Property mips_gcr_properties[] = {
     DEFINE_PROP_END_OF_LIST(),
 };
 
+static void mips_gcr_realize(DeviceState *dev, Error **errp)
+{
+    MIPSGCRState *s = MIPS_GCR(dev);
+
+    /* Create local set of registers for each VP */
+    s->vps = g_new(MIPSGCRVPState, s->num_vps);
+}
+
 static void mips_gcr_class_init(ObjectClass *klass, void *data)
 {
     DeviceClass *dc = DEVICE_CLASS(klass);
     dc->props = mips_gcr_properties;
     dc->vmsd = &vmstate_mips_gcr;
     dc->reset = mips_gcr_reset;
+    dc->realize = mips_gcr_realize;
 }
 
 static const TypeInfo mips_gcr_info = {
diff --git a/hw/misc/mips_cpc.c b/hw/misc/mips_cpc.c
index e6a35dd6a0..6d345745f6 100644
--- a/hw/misc/mips_cpc.c
+++ b/hw/misc/mips_cpc.c
@@ -37,7 +37,7 @@ static void cpc_run_vp(MIPSCPCState *cpc, uint64_t vp_run)
     CPU_FOREACH(cs) {
         uint64_t i = 1ULL << cs->cpu_index;
         if (i & vp_run & ~cpc->vp_running) {
-            cpu_interrupt(cs, CPU_INTERRUPT_WAKE);
+            cpu_reset(cs);
             cpc->vp_running |= i;
         }
     }
@@ -50,8 +50,7 @@ static void cpc_stop_vp(MIPSCPCState *cpc, uint64_t vp_stop)
     CPU_FOREACH(cs) {
         uint64_t i = 1ULL << cs->cpu_index;
         if (i & vp_stop & cpc->vp_running) {
-            cs->halted = 1;
-            cpu_reset_interrupt(cs, CPU_INTERRUPT_WAKE);
+            cpu_interrupt(cs, CPU_INTERRUPT_HALT);
             cpc->vp_running &= ~i;
         }
     }
diff --git a/hw/net/e1000_regs.h b/hw/net/e1000_regs.h
index c1acd458f2..23eed50b9c 100644
--- a/hw/net/e1000_regs.h
+++ b/hw/net/e1000_regs.h
@@ -29,9 +29,8 @@
  * Structures, enums, and macros for the MAC
  */
 
-#ifndef _E1000_HW_H_
-#define _E1000_HW_H_
-
+#ifndef HW_E1000_REGS_H
+#define HW_E1000_REGS_H
 
 /* PCI Device IDs */
 #define E1000_DEV_ID_82542               0x1000
@@ -1248,4 +1247,4 @@ struct e1000_data_desc {
 #define E1000_IOADDR 0x00
 #define E1000_IODATA 0x04
 
-#endif /* _E1000_HW_H_ */
+#endif /* HW_E1000_REGS_H */
diff --git a/hw/net/fsl_etsec/etsec.h b/hw/net/fsl_etsec/etsec.h
index e7dc0a4b90..30c828e241 100644
--- a/hw/net/fsl_etsec/etsec.h
+++ b/hw/net/fsl_etsec/etsec.h
@@ -21,8 +21,9 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
-#ifndef _ETSEC_H_
-#define _ETSEC_H_
+
+#ifndef ETSEC_H
+#define ETSEC_H
 
 #include "hw/qdev.h"
 #include "hw/sysbus.h"
@@ -173,4 +174,4 @@ void etsec_write_miim(eTSEC          *etsec,
 
 void etsec_miim_link_status(eTSEC *etsec, NetClientState *nc);
 
-#endif /* ! _ETSEC_H_ */
+#endif /* ETSEC_H */
diff --git a/hw/net/fsl_etsec/registers.h b/hw/net/fsl_etsec/registers.h
index 6fb96842b8..c4ed2b9d62 100644
--- a/hw/net/fsl_etsec/registers.h
+++ b/hw/net/fsl_etsec/registers.h
@@ -21,9 +21,9 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
-#ifndef _ETSEC_REGISTERS_H_
-#define _ETSEC_REGISTERS_H_
 
+#ifndef ETSEC_REGISTERS_H
+#define ETSEC_REGISTERS_H
 
 enum eTSEC_Register_Access_Type {
     ACC_RW      = 1,            /* Read/Write */
@@ -316,4 +316,4 @@ extern const eTSEC_Register_Definition eTSEC_registers_def[];
 #define TMR_ETTS2_H  (0xEA8 / 4)
 #define TMR_ETTS2_L  (0xEAC / 4)
 
-#endif /* ! _ETSEC_REGISTERS_H_ */
+#endif /* ETSEC_REGISTERS_H */
diff --git a/hw/net/ne2000.h b/hw/net/ne2000.h
index d022b28fc2..d213dccae3 100644
--- a/hw/net/ne2000.h
+++ b/hw/net/ne2000.h
@@ -1,5 +1,5 @@
 #ifndef HW_NE2000_H
-#define HW_NE2000_H 1
+#define HW_NE2000_H
 
 #define NE2000_PMEM_SIZE    (32*1024)
 #define NE2000_PMEM_START   (16*1024)
diff --git a/hw/net/pcnet.h b/hw/net/pcnet.h
index dec8de834c..40831a7845 100644
--- a/hw/net/pcnet.h
+++ b/hw/net/pcnet.h
@@ -1,5 +1,5 @@
 #ifndef HW_PCNET_H
-#define HW_PCNET_H 1
+#define HW_PCNET_H
 
 #define PCNET_IOPORT_SIZE       0x20
 #define PCNET_PNPMMIO_SIZE      0x20
diff --git a/hw/net/rocker/rocker.h b/hw/net/rocker/rocker.h
index f9c80f8013..7ae0495d9e 100644
--- a/hw/net/rocker/rocker.h
+++ b/hw/net/rocker/rocker.h
@@ -16,8 +16,8 @@
  * GNU General Public License for more details.
  */
 
-#ifndef _ROCKER_H_
-#define _ROCKER_H_
+#ifndef ROCKER_H
+#define ROCKER_H
 
 #include "qemu/sockets.h"
 
@@ -81,4 +81,4 @@ int rx_produce(World *world, uint32_t pport,
 int rocker_port_eg(Rocker *r, uint32_t pport,
                    const struct iovec *iov, int iovcnt);
 
-#endif /* _ROCKER_H_ */
+#endif /* ROCKER_H */
diff --git a/hw/net/rocker/rocker_desc.h b/hw/net/rocker/rocker_desc.h
index d4041f5c4c..1dec335614 100644
--- a/hw/net/rocker/rocker_desc.h
+++ b/hw/net/rocker/rocker_desc.h
@@ -14,9 +14,8 @@
  * GNU General Public License for more details.
  */
 
-
-#ifndef _ROCKER_DESC_H_
-#define _ROCKER_DESC_H_
+#ifndef ROCKER_DESC_H
+#define ROCKER_DESC_H
 
 #include "rocker_hw.h"
 
diff --git a/hw/net/rocker/rocker_fp.h b/hw/net/rocker/rocker_fp.h
index 04592bbfd2..dbe1dd329a 100644
--- a/hw/net/rocker/rocker_fp.h
+++ b/hw/net/rocker/rocker_fp.h
@@ -14,8 +14,8 @@
  * GNU General Public License for more details.
  */
 
-#ifndef _ROCKER_FP_H_
-#define _ROCKER_FP_H_
+#ifndef ROCKER_FP_H
+#define ROCKER_FP_H
 
 #include "net/net.h"
 #include "qemu/iov.h"
@@ -51,4 +51,4 @@ FpPort *fp_port_alloc(Rocker *r, char *sw_name,
 void fp_port_free(FpPort *port);
 void fp_port_reset(FpPort *port);
 
-#endif /* _ROCKER_FP_H_ */
+#endif /* ROCKER_FP_H */
diff --git a/hw/net/rocker/rocker_hw.h b/hw/net/rocker/rocker_hw.h
index 8c50830325..1786323fa4 100644
--- a/hw/net/rocker/rocker_hw.h
+++ b/hw/net/rocker/rocker_hw.h
@@ -6,8 +6,8 @@
  *
  */
 
-#ifndef _ROCKER_HW_
-#define _ROCKER_HW_
+#ifndef ROCKER_HW_H
+#define ROCKER_HW_H
 
 #define __le16 uint16_t
 #define __le32 uint32_t
@@ -490,4 +490,4 @@ enum rocker_of_dpa_overlay_type {
  */
 #define ROCKER_CONTROL_RESET            (1 << 0)
 
-#endif /* _ROCKER_HW_ */
+#endif /* ROCKER_HW_H */
diff --git a/hw/net/rocker/rocker_of_dpa.h b/hw/net/rocker/rocker_of_dpa.h
index f3f6d77807..01c7a97d0d 100644
--- a/hw/net/rocker/rocker_of_dpa.h
+++ b/hw/net/rocker/rocker_of_dpa.h
@@ -14,9 +14,9 @@
  * GNU General Public License for more details.
  */
 
-#ifndef _ROCKER_OF_DPA_H_
-#define _ROCKER_OF_DPA_H_
+#ifndef ROCKER_OF_DPA_H
+#define ROCKER_OF_DPA_H
 
 World *of_dpa_world_alloc(Rocker *r);
 
-#endif /* _ROCKER_OF_DPA_H_ */
+#endif /* ROCKER_OF_DPA_H */
diff --git a/hw/net/rocker/rocker_tlv.h b/hw/net/rocker/rocker_tlv.h
index 88561648f0..dd28d08443 100644
--- a/hw/net/rocker/rocker_tlv.h
+++ b/hw/net/rocker/rocker_tlv.h
@@ -14,8 +14,8 @@
  * GNU General Public License for more details.
  */
 
-#ifndef _ROCKER_TLV_H_
-#define _ROCKER_TLV_H_
+#ifndef ROCKER_TLV_H
+#define ROCKER_TLV_H
 
 #define ROCKER_TLV_ALIGNTO 8U
 #define ROCKER_TLV_ALIGN(len) \
diff --git a/hw/net/rocker/rocker_world.h b/hw/net/rocker/rocker_world.h
index 58ade47335..44f1fe3e19 100644
--- a/hw/net/rocker/rocker_world.h
+++ b/hw/net/rocker/rocker_world.h
@@ -14,8 +14,8 @@
  * GNU General Public License for more details.
  */
 
-#ifndef _ROCKER_WORLD_H_
-#define _ROCKER_WORLD_H_
+#ifndef ROCKER_WORLD_H
+#define ROCKER_WORLD_H
 
 #include "rocker_hw.h"
 
@@ -58,4 +58,4 @@ const char *world_name(World *world);
 
 World *rocker_get_world(Rocker *r, enum rocker_world_type type);
 
-#endif /* _ROCKER_WORLD_H_ */
+#endif /* ROCKER_WORLD_H */
diff --git a/hw/net/vmxnet3.h b/hw/net/vmxnet3.h
index f7006afe96..f9352c4a27 100644
--- a/hw/net/vmxnet3.h
+++ b/hw/net/vmxnet3.h
@@ -15,8 +15,8 @@
  *
  */
 
-#ifndef _QEMU_VMXNET3_H
-#define _QEMU_VMXNET3_H
+#ifndef QEMU_VMXNET3_H
+#define QEMU_VMXNET3_H
 
 #define VMXNET3_DEVICE_MAX_TX_QUEUES 8
 #define VMXNET3_DEVICE_MAX_RX_QUEUES 8   /* Keep this value as a power of 2 */
diff --git a/hw/net/vmxnet_debug.h b/hw/net/vmxnet_debug.h
index 5aab00b050..cb50aa95db 100644
--- a/hw/net/vmxnet_debug.h
+++ b/hw/net/vmxnet_debug.h
@@ -15,8 +15,8 @@
  *
  */
 
-#ifndef _QEMU_VMXNET_DEBUG_H
-#define _QEMU_VMXNET_DEBUG_H
+#ifndef QEMU_VMXNET_DEBUG_H
+#define QEMU_VMXNET_DEBUG_H
 
 #define VMXNET_DEVICE_NAME "vmxnet3"
 
@@ -142,4 +142,4 @@
         }                                                                     \
     } while (0)
 
-#endif /* _QEMU_VMXNET3_DEBUG_H  */
+#endif /* QEMU_VMXNET_DEBUG_H */
diff --git a/hw/pci-bridge/dec.h b/hw/pci-bridge/dec.h
index 17dc0c2b0a..ae17ca7362 100644
--- a/hw/pci-bridge/dec.h
+++ b/hw/pci-bridge/dec.h
@@ -1,5 +1,5 @@
-#ifndef DEC_PCI_H
-#define DEC_PCI_H
+#ifndef HW_PCI_BRIDGE_DEC_H
+#define HW_PCI_BRIDGE_DEC_H
 
 #include "qemu-common.h"
 
diff --git a/hw/pci-bridge/ioh3420.c b/hw/pci-bridge/ioh3420.c
index 93c6f0b7a2..0444b596c6 100644
--- a/hw/pci-bridge/ioh3420.c
+++ b/hw/pci-bridge/ioh3420.c
@@ -216,12 +216,3 @@ static void ioh3420_register_types(void)
 }
 
 type_init(ioh3420_register_types)
-
-/*
- * Local variables:
- *  c-indent-level: 4
- *  c-basic-offset: 4
- *  tab-width: 8
- *  indent-tab-mode: nil
- * End:
- */
diff --git a/hw/pci-bridge/xio3130_downstream.c b/hw/pci-bridge/xio3130_downstream.c
index f6149a302d..cef6e1325e 100644
--- a/hw/pci-bridge/xio3130_downstream.c
+++ b/hw/pci-bridge/xio3130_downstream.c
@@ -203,12 +203,3 @@ static void xio3130_downstream_register_types(void)
 }
 
 type_init(xio3130_downstream_register_types)
-
-/*
- * Local variables:
- *  c-indent-level: 4
- *  c-basic-offset: 4
- *  tab-width: 8
- *  indent-tab-mode: nil
- * End:
- */
diff --git a/hw/pci-bridge/xio3130_upstream.c b/hw/pci-bridge/xio3130_upstream.c
index 487edacc1d..4ad0440aa1 100644
--- a/hw/pci-bridge/xio3130_upstream.c
+++ b/hw/pci-bridge/xio3130_upstream.c
@@ -174,13 +174,3 @@ static void xio3130_upstream_register_types(void)
 }
 
 type_init(xio3130_upstream_register_types)
-
-
-/*
- * Local variables:
- *  c-indent-level: 4
- *  c-basic-offset: 4
- *  tab-width: 8
- *  indent-tab-mode: nil
- * End:
- */
diff --git a/hw/pci-bridge/xio3130_upstream.h b/hw/pci-bridge/xio3130_upstream.h
index 08c1d5f75b..d0ab7577e2 100644
--- a/hw/pci-bridge/xio3130_upstream.h
+++ b/hw/pci-bridge/xio3130_upstream.h
@@ -7,4 +7,4 @@ PCIEPort *xio3130_upstream_init(PCIBus *bus, int devfn, bool multifunction,
                                 const char *bus_name, pci_map_irq_fn map_irq,
                                 uint8_t port);
 
-#endif /* QEMU_XIO3130_H */
+#endif /* QEMU_XIO3130_UPSTREAM_H */
diff --git a/hw/ppc/mac.h b/hw/ppc/mac.h
index 5764b86c28..20cbddb4e4 100644
--- a/hw/ppc/mac.h
+++ b/hw/ppc/mac.h
@@ -22,8 +22,9 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
-#if !defined(__PPC_MAC_H__)
-#define __PPC_MAC_H__
+
+#ifndef PPC_MAC_H
+#define PPC_MAC_H
 
 #include "exec/memory.h"
 #include "hw/sysbus.h"
@@ -184,4 +185,4 @@ typedef struct MacIONVRAMState {
 } MacIONVRAMState;
 
 void pmac_format_nvram_partition (MacIONVRAMState *nvr, int len);
-#endif /* !defined(__PPC_MAC_H__) */
+#endif /* PPC_MAC_H */
diff --git a/hw/ppc/ppc405.h b/hw/ppc/ppc405.h
index 1c5f04fae1..c67febca2f 100644
--- a/hw/ppc/ppc405.h
+++ b/hw/ppc/ppc405.h
@@ -22,8 +22,8 @@
  * THE SOFTWARE.
  */
 
-#if !defined(PPC_405_H)
-#define PPC_405_H
+#ifndef PPC405_H
+#define PPC405_H
 
 #include "hw/ppc/ppc4xx.h"
 
@@ -78,4 +78,4 @@ CPUPPCState *ppc_stb025_init (MemoryRegion ram_memories[2],
                            uint32_t sysclk, qemu_irq **picp,
                            ram_addr_t *offsetp);
 
-#endif /* !defined(PPC_405_H) */
+#endif /* PPC405_H */
diff --git a/hw/ppc/spapr_cpu_core.c b/hw/ppc/spapr_cpu_core.c
index 70b6b0b5ee..9347f0741e 100644
--- a/hw/ppc/spapr_cpu_core.c
+++ b/hw/ppc/spapr_cpu_core.c
@@ -12,11 +12,11 @@
 #include "hw/ppc/spapr.h"
 #include "hw/boards.h"
 #include "qapi/error.h"
-#include <sysemu/cpus.h>
+#include "sysemu/cpus.h"
 #include "target-ppc/kvm_ppc.h"
 #include "hw/ppc/ppc.h"
 #include "target-ppc/mmu-hash64.h"
-#include <sysemu/numa.h>
+#include "sysemu/numa.h"
 
 static void spapr_cpu_reset(void *opaque)
 {
diff --git a/hw/ppc/spapr_pci_vfio.c b/hw/ppc/spapr_pci_vfio.c
index f3cb141763..8448e0b024 100644
--- a/hw/ppc/spapr_pci_vfio.c
+++ b/hw/ppc/spapr_pci_vfio.c
@@ -18,13 +18,13 @@
  */
 
 #include "qemu/osdep.h"
+#include <linux/vfio.h>
 #include "qapi/error.h"
 #include "qemu-common.h"
 #include "cpu.h"
 #include "hw/ppc/spapr.h"
 #include "hw/pci-host/spapr.h"
 #include "hw/pci/msix.h"
-#include "linux/vfio.h"
 #include "hw/vfio/vfio.h"
 #include "qemu/error-report.h"
 #include "sysemu/qtest.h"
diff --git a/hw/s390x/Makefile.objs b/hw/s390x/Makefile.objs
index 220361782d..41ac4ec325 100644
--- a/hw/s390x/Makefile.objs
+++ b/hw/s390x/Makefile.objs
@@ -8,6 +8,8 @@ obj-y += ipl.o
 obj-y += css.o
 obj-y += s390-virtio-ccw.o
 obj-y += virtio-ccw.o
+obj-y += css-bridge.o
+obj-y += ccw-device.o
 obj-y += s390-pci-bus.o s390-pci-inst.o
 obj-y += s390-skeys.o
 obj-$(CONFIG_KVM) += s390-skeys-kvm.o
diff --git a/hw/s390x/ccw-device.c b/hw/s390x/ccw-device.c
new file mode 100644
index 0000000000..28ea20440e
--- /dev/null
+++ b/hw/s390x/ccw-device.c
@@ -0,0 +1,27 @@
+/*
+ * Common device infrastructure for devices in the virtual css
+ *
+ * Copyright 2016 IBM Corp.
+ * Author(s): Jing Liu <liujbjl@linux.vnet.ibm.com>
+ *
+ * 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 "qemu/osdep.h"
+#include "ccw-device.h"
+
+static const TypeInfo ccw_device_info = {
+    .name = TYPE_CCW_DEVICE,
+    .parent = TYPE_DEVICE,
+    .instance_size = sizeof(CcwDevice),
+    .class_size = sizeof(CCWDeviceClass),
+    .abstract = true,
+};
+
+static void ccw_device_register(void)
+{
+    type_register_static(&ccw_device_info);
+}
+
+type_init(ccw_device_register)
diff --git a/hw/s390x/ccw-device.h b/hw/s390x/ccw-device.h
new file mode 100644
index 0000000000..59ba01b6c5
--- /dev/null
+++ b/hw/s390x/ccw-device.h
@@ -0,0 +1,43 @@
+/*
+ * Common device infrastructure for devices in the virtual css
+ *
+ * Copyright 2016 IBM Corp.
+ * Author(s): Jing Liu <liujbjl@linux.vnet.ibm.com>
+ *
+ * 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.
+ */
+
+#ifndef HW_S390X_CCW_DEVICE_H
+#define HW_S390X_CCW_DEVICE_H
+#include "qom/object.h"
+#include "hw/qdev-core.h"
+#include "hw/s390x/css.h"
+
+typedef struct CcwDevice {
+    DeviceState parent_obj;
+    SubchDev *sch;
+    /* <cssid>.<ssid>.<device number> */
+    CssDevId bus_id;
+} CcwDevice;
+
+typedef struct CCWDeviceClass {
+    DeviceClass parent_class;
+    void (*unplug)(HotplugHandler *, DeviceState *, Error **);
+} CCWDeviceClass;
+
+static inline CcwDevice *to_ccw_dev_fast(DeviceState *d)
+{
+    return container_of(d, CcwDevice, parent_obj);
+}
+
+#define TYPE_CCW_DEVICE "ccw-device"
+
+#define CCW_DEVICE(obj) OBJECT_CHECK(CcwDevice, (obj), TYPE_CCW_DEVICE)
+#define CCW_DEVICE_GET_CLASS(obj) \
+    OBJECT_GET_CLASS(CCWDeviceClass, (obj), TYPE_CCW_DEVICE)
+#define CCW_DEVICE_CLASS(klass) \
+    OBJECT_CLASS_CHECK(CCWDeviceClass, (klass), TYPE_CCW_DEVICE)
+
+#endif
diff --git a/hw/s390x/css-bridge.c b/hw/s390x/css-bridge.c
new file mode 100644
index 0000000000..e4c24e21f3
--- /dev/null
+++ b/hw/s390x/css-bridge.c
@@ -0,0 +1,124 @@
+/*
+ * css bridge implementation
+ *
+ * Copyright 2012,2016 IBM Corp.
+ * Author(s): Cornelia Huck <cornelia.huck@de.ibm.com>
+ *            Pierre Morel <pmorel@linux.vnet.ibm.com>
+ *
+ * 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 "qemu/osdep.h"
+#include "qapi/error.h"
+#include "hw/hotplug.h"
+#include "hw/sysbus.h"
+#include "qemu/bitops.h"
+#include "hw/s390x/css.h"
+#include "ccw-device.h"
+#include "hw/s390x/css-bridge.h"
+
+/*
+ * Invoke device-specific unplug handler, disable the subchannel
+ * (including sending a channel report to the guest) and remove the
+ * device from the virtual css bus.
+ */
+static void ccw_device_unplug(HotplugHandler *hotplug_dev,
+                              DeviceState *dev, Error **errp)
+{
+    CcwDevice *ccw_dev = CCW_DEVICE(dev);
+    CCWDeviceClass *k = CCW_DEVICE_GET_CLASS(ccw_dev);
+    SubchDev *sch = ccw_dev->sch;
+    Error *err = NULL;
+
+    if (k->unplug) {
+        k->unplug(hotplug_dev, dev, &err);
+        if (err) {
+            error_propagate(errp, err);
+            return;
+        }
+    }
+
+    /*
+     * We should arrive here only for device_del, since we don't support
+     * direct hot(un)plug of channels.
+     */
+    assert(sch != NULL);
+    /* Subchannel is now disabled and no longer valid. */
+    sch->curr_status.pmcw.flags &= ~(PMCW_FLAGS_MASK_ENA |
+                                     PMCW_FLAGS_MASK_DNV);
+
+    css_generate_sch_crws(sch->cssid, sch->ssid, sch->schid, 1, 0);
+
+    object_unparent(OBJECT(dev));
+}
+
+static void virtual_css_bus_reset(BusState *qbus)
+{
+    /* This should actually be modelled via the generic css */
+    css_reset();
+}
+
+static void virtual_css_bus_class_init(ObjectClass *klass, void *data)
+{
+    BusClass *k = BUS_CLASS(klass);
+
+    k->reset = virtual_css_bus_reset;
+}
+
+static const TypeInfo virtual_css_bus_info = {
+    .name = TYPE_VIRTUAL_CSS_BUS,
+    .parent = TYPE_BUS,
+    .instance_size = sizeof(VirtualCssBus),
+    .class_init = virtual_css_bus_class_init,
+};
+
+VirtualCssBus *virtual_css_bus_init(void)
+{
+    VirtualCssBus *cbus;
+    BusState *bus;
+    DeviceState *dev;
+
+    /* Create bridge device */
+    dev = qdev_create(NULL, TYPE_VIRTUAL_CSS_BRIDGE);
+    qdev_init_nofail(dev);
+
+    /* Create bus on bridge device */
+    bus = qbus_create(TYPE_VIRTUAL_CSS_BUS, dev, "virtual-css");
+    cbus = VIRTUAL_CSS_BUS(bus);
+
+    /* Enable hotplugging */
+    qbus_set_hotplug_handler(bus, dev, &error_abort);
+
+    return cbus;
+ }
+
+/***************** Virtual-css Bus Bridge Device ********************/
+
+static void virtual_css_bridge_class_init(ObjectClass *klass, void *data)
+{
+    HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(klass);
+    DeviceClass *dc = DEVICE_CLASS(klass);
+
+    hc->unplug = ccw_device_unplug;
+    set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories);
+}
+
+static const TypeInfo virtual_css_bridge_info = {
+    .name          = TYPE_VIRTUAL_CSS_BRIDGE,
+    .parent        = TYPE_SYS_BUS_DEVICE,
+    .instance_size = sizeof(SysBusDevice),
+    .class_init    = virtual_css_bridge_class_init,
+    .interfaces = (InterfaceInfo[]) {
+        { TYPE_HOTPLUG_HANDLER },
+        { }
+    }
+};
+
+static void virtual_css_register(void)
+{
+    type_register_static(&virtual_css_bridge_info);
+    type_register_static(&virtual_css_bus_info);
+}
+
+type_init(virtual_css_register)
diff --git a/hw/s390x/css.c b/hw/s390x/css.c
index 76668814da..aa61773885 100644
--- a/hw/s390x/css.c
+++ b/hw/s390x/css.c
@@ -12,7 +12,7 @@
 #include "qemu/osdep.h"
 #include "qapi/error.h"
 #include "qapi/visitor.h"
-#include <hw/qdev.h>
+#include "hw/qdev.h"
 #include "qemu/bitops.h"
 #include "exec/address-spaces.h"
 #include "cpu.h"
@@ -1340,6 +1340,116 @@ SubchDev *css_find_subch(uint8_t m, uint8_t cssid, uint8_t ssid, uint16_t schid)
     return channel_subsys.css[real_cssid]->sch_set[ssid]->sch[schid];
 }
 
+/**
+ * Return free device number in subchannel set.
+ *
+ * Return index of the first free device number in the subchannel set
+ * identified by @p cssid and @p ssid, beginning the search at @p
+ * start and wrapping around at MAX_DEVNO. Return a value exceeding
+ * MAX_SCHID if there are no free device numbers in the subchannel
+ * set.
+ */
+static uint32_t css_find_free_devno(uint8_t cssid, uint8_t ssid,
+                                    uint16_t start)
+{
+    uint32_t round;
+
+    for (round = 0; round <= MAX_DEVNO; round++) {
+        uint16_t devno = (start + round) % MAX_DEVNO;
+
+        if (!css_devno_used(cssid, ssid, devno)) {
+            return devno;
+        }
+    }
+    return MAX_DEVNO + 1;
+}
+
+/**
+ * Return first free subchannel (id) in subchannel set.
+ *
+ * Return index of the first free subchannel in the subchannel set
+ * identified by @p cssid and @p ssid, if there is any. Return a value
+ * exceeding MAX_SCHID if there are no free subchannels in the
+ * subchannel set.
+ */
+static uint32_t css_find_free_subch(uint8_t cssid, uint8_t ssid)
+{
+    uint32_t schid;
+
+    for (schid = 0; schid <= MAX_SCHID; schid++) {
+        if (!css_find_subch(1, cssid, ssid, schid)) {
+            return schid;
+        }
+    }
+    return MAX_SCHID + 1;
+}
+
+/**
+ * Return first free subchannel (id) in subchannel set for a device number
+ *
+ * Verify the device number @p devno is not used yet in the subchannel
+ * set identified by @p cssid and @p ssid. Set @p schid to the index
+ * of the first free subchannel in the subchannel set, if there is
+ * any. Return true if everything succeeded and false otherwise.
+ */
+static bool css_find_free_subch_for_devno(uint8_t cssid, uint8_t ssid,
+                                          uint16_t devno, uint16_t *schid,
+                                          Error **errp)
+{
+    uint32_t free_schid;
+
+    assert(schid);
+    if (css_devno_used(cssid, ssid, devno)) {
+        error_setg(errp, "Device %x.%x.%04x already exists",
+                   cssid, ssid, devno);
+        return false;
+    }
+    free_schid = css_find_free_subch(cssid, ssid);
+    if (free_schid > MAX_SCHID) {
+        error_setg(errp, "No free subchannel found for %x.%x.%04x",
+                   cssid, ssid, devno);
+        return false;
+    }
+    *schid = free_schid;
+    return true;
+}
+
+/**
+ * Return first free subchannel (id) and device number
+ *
+ * Locate the first free subchannel and first free device number in
+ * any of the subchannel sets of the channel subsystem identified by
+ * @p cssid. Return false if no free subchannel / device number could
+ * be found. Otherwise set @p ssid, @p devno and @p schid to identify
+ * the available subchannel and device number and return true.
+ *
+ * May modify @p ssid, @p devno and / or @p schid even if no free
+ * subchannel / device number could be found.
+ */
+static bool css_find_free_subch_and_devno(uint8_t cssid, uint8_t *ssid,
+                                          uint16_t *devno, uint16_t *schid,
+                                          Error **errp)
+{
+    uint32_t free_schid, free_devno;
+
+    assert(ssid && devno && schid);
+    for (*ssid = 0; *ssid <= MAX_SSID; (*ssid)++) {
+        free_schid = css_find_free_subch(cssid, *ssid);
+        if (free_schid > MAX_SCHID) {
+            continue;
+        }
+        free_devno = css_find_free_devno(cssid, *ssid, free_schid);
+        if (free_devno > MAX_DEVNO) {
+            continue;
+        }
+        *schid = free_schid;
+        *devno = free_devno;
+        return true;
+    }
+    error_setg(errp, "Virtual channel subsystem is full!");
+    return false;
+}
+
 bool css_subch_visible(SubchDev *sch)
 {
     if (sch->ssid > channel_subsys.max_ssid) {
@@ -1762,3 +1872,36 @@ PropertyInfo css_devid_propinfo = {
     .get = get_css_devid,
     .set = set_css_devid,
 };
+
+SubchDev *css_create_virtual_sch(CssDevId bus_id, Error **errp)
+{
+    uint16_t schid = 0;
+    SubchDev *sch;
+
+    if (bus_id.valid) {
+        /* Enforce use of virtual cssid. */
+        if (bus_id.cssid != VIRTUAL_CSSID) {
+            error_setg(errp, "cssid %hhx not valid for virtual devices",
+                       bus_id.cssid);
+            return NULL;
+        }
+        if (!css_find_free_subch_for_devno(bus_id.cssid, bus_id.ssid,
+                                           bus_id.devid, &schid, errp)) {
+            return NULL;
+        }
+    } else {
+        bus_id.cssid = VIRTUAL_CSSID;
+        if (!css_find_free_subch_and_devno(bus_id.cssid, &bus_id.ssid,
+                                           &bus_id.devid, &schid, errp)) {
+            return NULL;
+        }
+    }
+
+    sch = g_malloc0(sizeof(*sch));
+    sch->cssid = bus_id.cssid;
+    sch->ssid = bus_id.ssid;
+    sch->devno = bus_id.devid;
+    sch->schid = schid;
+    css_subch_assign(sch->cssid, sch->ssid, schid, sch->devno, sch);
+    return sch;
+}
diff --git a/hw/s390x/ipl.c b/hw/s390x/ipl.c
index e6bf7cf7c0..2e2664f22e 100644
--- a/hw/s390x/ipl.c
+++ b/hw/s390x/ipl.c
@@ -69,8 +69,8 @@ static const VMStateDescription vmstate_ipl = {
     .version_id = 0,
     .minimum_version_id = 0,
     .fields = (VMStateField[]) {
-        VMSTATE_UINT64(start_addr, S390IPLState),
-        VMSTATE_UINT64(bios_start_addr, S390IPLState),
+        VMSTATE_UINT64(compat_start_addr, S390IPLState),
+        VMSTATE_UINT64(compat_bios_start_addr, S390IPLState),
         VMSTATE_STRUCT(iplb, S390IPLState, 0, vmstate_iplb, IplParameterBlock),
         VMSTATE_BOOL(iplb_valid, S390IPLState),
         VMSTATE_UINT8(cssid, S390IPLState),
@@ -192,6 +192,13 @@ static void s390_ipl_realize(DeviceState *dev, Error **errp)
             stq_p(rom_ptr(INITRD_PARM_SIZE), initrd_size);
         }
     }
+    /*
+     * Don't ever use the migrated values, they could come from a different
+     * BIOS and therefore don't work. But still migrate the values, so
+     * QEMUs relying on it don't break.
+     */
+    ipl->compat_start_addr = ipl->start_addr;
+    ipl->compat_bios_start_addr = ipl->bios_start_addr;
     qemu_register_reset(qdev_reset_all_fn, dev);
 error:
     error_propagate(errp, err);
@@ -214,10 +221,14 @@ static bool s390_gen_initial_iplb(S390IPLState *ipl)
 
     dev_st = get_boot_device(0);
     if (dev_st) {
-        VirtioCcwDevice *ccw_dev = (VirtioCcwDevice *) object_dynamic_cast(
-            OBJECT(qdev_get_parent_bus(dev_st)->parent),
+        VirtioCcwDevice *virtio_ccw_dev = (VirtioCcwDevice *)
+            object_dynamic_cast(OBJECT(qdev_get_parent_bus(dev_st)->parent),
                 TYPE_VIRTIO_CCW_DEVICE);
-        if (ccw_dev) {
+        SCSIDevice *sd = (SCSIDevice *) object_dynamic_cast(OBJECT(dev_st),
+                                                            TYPE_SCSI_DEVICE);
+        if (virtio_ccw_dev) {
+            CcwDevice *ccw_dev = CCW_DEVICE(virtio_ccw_dev);
+
             ipl->iplb.len = cpu_to_be32(S390_IPLB_MIN_CCW_LEN);
             ipl->iplb.blk0_len =
                 cpu_to_be32(S390_IPLB_MIN_CCW_LEN - S390_IPLB_HEADER_LEN);
@@ -225,6 +236,22 @@ static bool s390_gen_initial_iplb(S390IPLState *ipl)
             ipl->iplb.ccw.devno = cpu_to_be16(ccw_dev->sch->devno);
             ipl->iplb.ccw.ssid = ccw_dev->sch->ssid & 3;
             return true;
+        } else if (sd) {
+            SCSIBus *bus = scsi_bus_from_device(sd);
+            VirtIOSCSI *vdev = container_of(bus, VirtIOSCSI, bus);
+            VirtIOSCSICcw *scsi_ccw = container_of(vdev, VirtIOSCSICcw, vdev);
+            CcwDevice *ccw_dev = CCW_DEVICE(scsi_ccw);
+
+            ipl->iplb.len = cpu_to_be32(S390_IPLB_MIN_QEMU_SCSI_LEN);
+            ipl->iplb.blk0_len =
+                cpu_to_be32(S390_IPLB_MIN_QEMU_SCSI_LEN - S390_IPLB_HEADER_LEN);
+            ipl->iplb.pbt = S390_IPL_TYPE_QEMU_SCSI;
+            ipl->iplb.scsi.lun = cpu_to_be32(sd->lun);
+            ipl->iplb.scsi.target = cpu_to_be16(sd->id);
+            ipl->iplb.scsi.channel = cpu_to_be16(sd->channel);
+            ipl->iplb.scsi.devno = cpu_to_be16(ccw_dev->sch->devno);
+            ipl->iplb.scsi.ssid = ccw_dev->sch->ssid & 3;
+            return true;
         }
     }
 
diff --git a/hw/s390x/ipl.h b/hw/s390x/ipl.h
index 9aa4d942a7..c89109585a 100644
--- a/hw/s390x/ipl.h
+++ b/hw/s390x/ipl.h
@@ -46,6 +46,16 @@ struct IplBlockFcp {
 } QEMU_PACKED;
 typedef struct IplBlockFcp IplBlockFcp;
 
+struct IplBlockQemuScsi {
+    uint32_t lun;
+    uint16_t target;
+    uint16_t channel;
+    uint8_t  reserved0[77];
+    uint8_t  ssid;
+    uint16_t devno;
+} QEMU_PACKED;
+typedef struct IplBlockQemuScsi IplBlockQemuScsi;
+
 union IplParameterBlock {
     struct {
         uint32_t len;
@@ -59,6 +69,7 @@ union IplParameterBlock {
         union {
             IplBlockCcw ccw;
             IplBlockFcp fcp;
+            IplBlockQemuScsi scsi;
         };
     } QEMU_PACKED;
     struct {
@@ -82,7 +93,9 @@ struct S390IPLState {
     /*< private >*/
     DeviceState parent_obj;
     uint64_t start_addr;
+    uint64_t compat_start_addr;
     uint64_t bios_start_addr;
+    uint64_t compat_bios_start_addr;
     bool enforce_bios;
     IplParameterBlock iplb;
     bool iplb_valid;
@@ -102,10 +115,12 @@ typedef struct S390IPLState S390IPLState;
 
 #define S390_IPL_TYPE_FCP 0x00
 #define S390_IPL_TYPE_CCW 0x02
+#define S390_IPL_TYPE_QEMU_SCSI 0xff
 
 #define S390_IPLB_HEADER_LEN 8
 #define S390_IPLB_MIN_CCW_LEN 200
 #define S390_IPLB_MIN_FCP_LEN 384
+#define S390_IPLB_MIN_QEMU_SCSI_LEN 200
 
 static inline bool iplb_valid_len(IplParameterBlock *iplb)
 {
diff --git a/hw/s390x/s390-pci-bus.c b/hw/s390x/s390-pci-bus.c
index a77c10ce9e..47ca853bd2 100644
--- a/hw/s390x/s390-pci-bus.c
+++ b/hw/s390x/s390-pci-bus.c
@@ -12,13 +12,15 @@
  */
 
 #include "qemu/osdep.h"
+#include "qapi/error.h"
+#include "qapi/visitor.h"
 #include "qemu-common.h"
 #include "cpu.h"
 #include "s390-pci-bus.h"
 #include "s390-pci-inst.h"
-#include <hw/pci/pci_bus.h>
-#include <hw/pci/msi.h>
-#include <qemu/error-report.h>
+#include "hw/pci/pci_bus.h"
+#include "hw/pci/msi.h"
+#include "qemu/error-report.h"
 
 /* #define DEBUG_S390PCI_BUS */
 #ifdef DEBUG_S390PCI_BUS
@@ -29,6 +31,19 @@
     do { } while (0)
 #endif
 
+static S390pciState *s390_get_phb(void)
+{
+    static S390pciState *phb;
+
+    if (!phb) {
+        phb = S390_PCI_HOST_BRIDGE(
+            object_resolve_path(TYPE_S390_PCI_HOST_BRIDGE, NULL));
+        assert(phb != NULL);
+    }
+
+    return phb;
+}
+
 int chsc_sei_nt2_get_event(void *res)
 {
     ChscSeiNt2Res *nt2_res = (ChscSeiNt2Res *)res;
@@ -36,12 +51,7 @@ int chsc_sei_nt2_get_event(void *res)
     PciCcdfErr *eccdf;
     int rc = 1;
     SeiContainer *sei_cont;
-    S390pciState *s = S390_PCI_HOST_BRIDGE(
-        object_resolve_path(TYPE_S390_PCI_HOST_BRIDGE, NULL));
-
-    if (!s) {
-        return rc;
-    }
+    S390pciState *s = s390_get_phb();
 
     sei_cont = QTAILQ_FIRST(&s->pending_sei);
     if (sei_cont) {
@@ -76,30 +86,40 @@ int chsc_sei_nt2_get_event(void *res)
 
 int chsc_sei_nt2_have_event(void)
 {
-    S390pciState *s = S390_PCI_HOST_BRIDGE(
-        object_resolve_path(TYPE_S390_PCI_HOST_BRIDGE, NULL));
+    S390pciState *s = s390_get_phb();
 
-    if (!s) {
-        return 0;
+    return !QTAILQ_EMPTY(&s->pending_sei);
+}
+
+S390PCIBusDevice *s390_pci_find_next_avail_dev(S390PCIBusDevice *pbdev)
+{
+    int idx = 0;
+    S390PCIBusDevice *dev = NULL;
+    S390pciState *s = s390_get_phb();
+
+    if (pbdev) {
+        idx = (pbdev->fh & FH_MASK_INDEX) + 1;
     }
 
-    return !QTAILQ_EMPTY(&s->pending_sei);
+    for (; idx < PCI_SLOT_MAX; idx++) {
+        dev = s->pbdev[idx];
+        if (dev && dev->state != ZPCI_FS_RESERVED) {
+            return dev;
+        }
+    }
+
+    return NULL;
 }
 
 S390PCIBusDevice *s390_pci_find_dev_by_fid(uint32_t fid)
 {
     S390PCIBusDevice *pbdev;
     int i;
-    S390pciState *s = S390_PCI_HOST_BRIDGE(
-        object_resolve_path(TYPE_S390_PCI_HOST_BRIDGE, NULL));
-
-    if (!s) {
-        return NULL;
-    }
+    S390pciState *s = s390_get_phb();
 
     for (i = 0; i < PCI_SLOT_MAX; i++) {
-        pbdev = &s->pbdev[i];
-        if ((pbdev->fh != 0) && (pbdev->fid == fid)) {
+        pbdev = s->pbdev[i];
+        if (pbdev && pbdev->fid == fid) {
             return pbdev;
         }
     }
@@ -118,16 +138,22 @@ void s390_pci_sclp_configure(SCCB *sccb)
         goto out;
     }
 
-    if (pbdev) {
-        if (pbdev->configured) {
-            rc = SCLP_RC_NO_ACTION_REQUIRED;
-        } else {
-            pbdev->configured = true;
-            rc = SCLP_RC_NORMAL_COMPLETION;
-        }
-    } else {
+    if (!pbdev) {
         DPRINTF("sclp config no dev found\n");
         rc = SCLP_RC_ADAPTER_ID_NOT_RECOGNIZED;
+        goto out;
+    }
+
+    switch (pbdev->state) {
+    case ZPCI_FS_RESERVED:
+        rc = SCLP_RC_ADAPTER_IN_RESERVED_STATE;
+        break;
+    case ZPCI_FS_STANDBY:
+        pbdev->state = ZPCI_FS_DISABLED;
+        rc = SCLP_RC_NORMAL_COMPLETION;
+        break;
+    default:
+        rc = SCLP_RC_NO_ACTION_REQUIRED;
     }
 out:
     psccb->header.response_code = cpu_to_be16(rc);
@@ -144,81 +170,96 @@ void s390_pci_sclp_deconfigure(SCCB *sccb)
         goto out;
     }
 
-    if (pbdev) {
-        if (!pbdev->configured) {
-            rc = SCLP_RC_NO_ACTION_REQUIRED;
-        } else {
-            if (pbdev->summary_ind) {
-                pci_dereg_irqs(pbdev);
-            }
-            if (pbdev->iommu_enabled) {
-                pci_dereg_ioat(pbdev);
-            }
-            pbdev->configured = false;
-            rc = SCLP_RC_NORMAL_COMPLETION;
-        }
-    } else {
+    if (!pbdev) {
         DPRINTF("sclp deconfig no dev found\n");
         rc = SCLP_RC_ADAPTER_ID_NOT_RECOGNIZED;
+        goto out;
+    }
+
+    switch (pbdev->state) {
+    case ZPCI_FS_RESERVED:
+        rc = SCLP_RC_ADAPTER_IN_RESERVED_STATE;
+        break;
+    case ZPCI_FS_STANDBY:
+        rc = SCLP_RC_NO_ACTION_REQUIRED;
+        break;
+    default:
+        if (pbdev->summary_ind) {
+            pci_dereg_irqs(pbdev);
+        }
+        if (pbdev->iommu_enabled) {
+            pci_dereg_ioat(pbdev);
+        }
+        pbdev->state = ZPCI_FS_STANDBY;
+        rc = SCLP_RC_NORMAL_COMPLETION;
+
+        if (pbdev->release_timer) {
+            qdev_unplug(DEVICE(pbdev->pdev), NULL);
+        }
     }
 out:
     psccb->header.response_code = cpu_to_be16(rc);
 }
 
-static uint32_t s390_pci_get_pfid(PCIDevice *pdev)
+static S390PCIBusDevice *s390_pci_find_dev_by_uid(uint16_t uid)
 {
-    return PCI_SLOT(pdev->devfn);
-}
+    int i;
+    S390PCIBusDevice *pbdev;
+    S390pciState *s = s390_get_phb();
 
-static uint32_t s390_pci_get_pfh(PCIDevice *pdev)
-{
-    return PCI_SLOT(pdev->devfn) | FH_VIRT;
+    for (i = 0; i < PCI_SLOT_MAX; i++) {
+        pbdev = s->pbdev[i];
+        if (!pbdev) {
+            continue;
+        }
+
+        if (pbdev->uid == uid) {
+            return pbdev;
+        }
+    }
+
+    return NULL;
 }
 
-S390PCIBusDevice *s390_pci_find_dev_by_idx(uint32_t idx)
+static S390PCIBusDevice *s390_pci_find_dev_by_target(const char *target)
 {
-    S390PCIBusDevice *pbdev;
     int i;
-    int j = 0;
-    S390pciState *s = S390_PCI_HOST_BRIDGE(
-        object_resolve_path(TYPE_S390_PCI_HOST_BRIDGE, NULL));
+    S390PCIBusDevice *pbdev;
+    S390pciState *s = s390_get_phb();
 
-    if (!s) {
+    if (!target) {
         return NULL;
     }
 
     for (i = 0; i < PCI_SLOT_MAX; i++) {
-        pbdev = &s->pbdev[i];
-
-        if (pbdev->fh == 0) {
+        pbdev = s->pbdev[i];
+        if (!pbdev) {
             continue;
         }
 
-        if (j == idx) {
+        if (!strcmp(pbdev->target, target)) {
             return pbdev;
         }
-        j++;
     }
 
     return NULL;
 }
 
+S390PCIBusDevice *s390_pci_find_dev_by_idx(uint32_t idx)
+{
+    S390pciState *s = s390_get_phb();
+
+    return s->pbdev[idx & FH_MASK_INDEX];
+}
+
 S390PCIBusDevice *s390_pci_find_dev_by_fh(uint32_t fh)
 {
+    S390pciState *s = s390_get_phb();
     S390PCIBusDevice *pbdev;
-    int i;
-    S390pciState *s = S390_PCI_HOST_BRIDGE(
-        object_resolve_path(TYPE_S390_PCI_HOST_BRIDGE, NULL));
 
-    if (!s || !fh) {
-        return NULL;
-    }
-
-    for (i = 0; i < PCI_SLOT_MAX; i++) {
-        pbdev = &s->pbdev[i];
-        if (pbdev->fh == fh) {
-            return pbdev;
-        }
+    pbdev = s->pbdev[fh & FH_MASK_INDEX];
+    if (pbdev && pbdev->fh == fh) {
+        return pbdev;
     }
 
     return NULL;
@@ -228,12 +269,7 @@ static void s390_pci_generate_event(uint8_t cc, uint16_t pec, uint32_t fh,
                                     uint32_t fid, uint64_t faddr, uint32_t e)
 {
     SeiContainer *sei_cont;
-    S390pciState *s = S390_PCI_HOST_BRIDGE(
-        object_resolve_path(TYPE_S390_PCI_HOST_BRIDGE, NULL));
-
-    if (!s) {
-        return;
-    }
+    S390pciState *s = s390_get_phb();
 
     sei_cont = g_malloc0(sizeof(SeiContainer));
     sei_cont->fh = fh;
@@ -253,9 +289,8 @@ static void s390_pci_generate_plug_event(uint16_t pec, uint32_t fh,
     s390_pci_generate_event(2, pec, fh, fid, 0, 0);
 }
 
-static void s390_pci_generate_error_event(uint16_t pec, uint32_t fh,
-                                          uint32_t fid, uint64_t faddr,
-                                          uint32_t e)
+void s390_pci_generate_error_event(uint16_t pec, uint32_t fh, uint32_t fid,
+                                   uint64_t faddr, uint32_t e)
 {
     s390_pci_generate_event(1, pec, fh, fid, faddr, e);
 }
@@ -357,8 +392,14 @@ static IOMMUTLBEntry s390_translate_iommu(MemoryRegion *iommu, hwaddr addr,
         .perm = IOMMU_NONE,
     };
 
-    if (!pbdev->configured || !pbdev->pdev ||
-        !(pbdev->fh & FH_ENABLED) || !pbdev->iommu_enabled) {
+    switch (pbdev->state) {
+    case ZPCI_FS_ENABLED:
+    case ZPCI_FS_BLOCKED:
+        if (!pbdev->iommu_enabled) {
+            return ret;
+        }
+        break;
+    default:
         return ret;
     }
 
@@ -377,30 +418,13 @@ static IOMMUTLBEntry s390_translate_iommu(MemoryRegion *iommu, hwaddr addr,
         return ret;
     }
 
-    if (!pbdev->g_iota) {
-        pbdev->error_state = true;
-        pbdev->lgstg_blocked = true;
-        s390_pci_generate_error_event(ERR_EVENT_INVALAS, pbdev->fh, pbdev->fid,
-                                      addr, 0);
-        return ret;
-    }
-
     if (addr < pbdev->pba || addr > pbdev->pal) {
-        pbdev->error_state = true;
-        pbdev->lgstg_blocked = true;
-        s390_pci_generate_error_event(ERR_EVENT_OORANGE, pbdev->fh, pbdev->fid,
-                                      addr, 0);
         return ret;
     }
 
     pte = s390_guest_io_table_walk(s390_pci_get_table_origin(pbdev->g_iota),
                                    addr);
-
     if (!pte) {
-        pbdev->error_state = true;
-        pbdev->lgstg_blocked = true;
-        s390_pci_generate_error_event(ERR_EVENT_SERR, pbdev->fh, pbdev->fid,
-                                      addr, ERR_EVENT_Q_BIT);
         return ret;
     }
 
@@ -426,7 +450,7 @@ static AddressSpace *s390_pci_dma_iommu(PCIBus *bus, void *opaque, int devfn)
 {
     S390pciState *s = opaque;
 
-    return &s->pbdev[PCI_SLOT(devfn)].as;
+    return &s->iommu[PCI_SLOT(devfn)]->as;
 }
 
 static uint8_t set_ind_atomic(uint64_t ind_loc, uint8_t to_be_set)
@@ -454,22 +478,22 @@ static void s390_msi_ctrl_write(void *opaque, hwaddr addr, uint64_t data,
 {
     S390PCIBusDevice *pbdev;
     uint32_t io_int_word;
-    uint32_t fid = data >> ZPCI_MSI_VEC_BITS;
+    uint32_t idx = data >> ZPCI_MSI_VEC_BITS;
     uint32_t vec = data & ZPCI_MSI_VEC_MASK;
     uint64_t ind_bit;
     uint32_t sum_bit;
     uint32_t e = 0;
 
-    DPRINTF("write_msix data 0x%" PRIx64 " fid %d vec 0x%x\n", data, fid, vec);
+    DPRINTF("write_msix data 0x%" PRIx64 " idx %d vec 0x%x\n", data, idx, vec);
 
-    pbdev = s390_pci_find_dev_by_fid(fid);
+    pbdev = s390_pci_find_dev_by_idx(idx);
     if (!pbdev) {
         e |= (vec << ERR_EVENT_MVN_OFFSET);
-        s390_pci_generate_error_event(ERR_EVENT_NOMSI, 0, fid, addr, e);
+        s390_pci_generate_error_event(ERR_EVENT_NOMSI, idx, 0, addr, e);
         return;
     }
 
-    if (!(pbdev->fh & FH_ENABLED)) {
+    if (pbdev->state != ZPCI_FS_ENABLED) {
         return;
     }
 
@@ -498,17 +522,15 @@ static const MemoryRegionOps s390_msi_ctrl_ops = {
 
 void s390_pci_iommu_enable(S390PCIBusDevice *pbdev)
 {
-    uint64_t size = pbdev->pal - pbdev->pba + 1;
-
-    memory_region_init_iommu(&pbdev->iommu_mr, OBJECT(&pbdev->mr),
-                             &s390_iommu_ops, "iommu-s390", size);
-    memory_region_add_subregion(&pbdev->mr, pbdev->pba, &pbdev->iommu_mr);
+    memory_region_init_iommu(&pbdev->iommu_mr, OBJECT(&pbdev->iommu->mr),
+                             &s390_iommu_ops, "iommu-s390", pbdev->pal + 1);
+    memory_region_add_subregion(&pbdev->iommu->mr, 0, &pbdev->iommu_mr);
     pbdev->iommu_enabled = true;
 }
 
 void s390_pci_iommu_disable(S390PCIBusDevice *pbdev)
 {
-    memory_region_del_subregion(&pbdev->mr, &pbdev->iommu_mr);
+    memory_region_del_subregion(&pbdev->iommu->mr, &pbdev->iommu_mr);
     object_unparent(OBJECT(&pbdev->iommu_mr));
     pbdev->iommu_enabled = false;
 }
@@ -516,13 +538,15 @@ void s390_pci_iommu_disable(S390PCIBusDevice *pbdev)
 static void s390_pcihost_init_as(S390pciState *s)
 {
     int i;
-    S390PCIBusDevice *pbdev;
+    S390PCIIOMMU *iommu;
 
     for (i = 0; i < PCI_SLOT_MAX; i++) {
-        pbdev = &s->pbdev[i];
-        memory_region_init(&pbdev->mr, OBJECT(s),
+        iommu = g_malloc0(sizeof(S390PCIIOMMU));
+        memory_region_init(&iommu->mr, OBJECT(s),
                            "iommu-root-s390", UINT64_MAX);
-        address_space_init(&pbdev->as, &pbdev->mr, "iommu-pci");
+        address_space_init(&iommu->as, &iommu->mr, "iommu-pci");
+
+        s->iommu[i] = iommu;
     }
 
     memory_region_init_io(&s->msix_notify_mr, OBJECT(s),
@@ -549,6 +573,10 @@ static int s390_pcihost_init(SysBusDevice *dev)
     bus = BUS(b);
     qbus_set_hotplug_handler(bus, DEVICE(dev), NULL);
     phb->bus = b;
+
+    s->bus = S390_PCI_BUS(qbus_create(TYPE_S390_PCI_BUS, DEVICE(s), NULL));
+    qbus_set_hotplug_handler(BUS(s->bus), DEVICE(s), NULL);
+
     QTAILQ_INIT(&s->pending_sei);
     return 0;
 }
@@ -581,51 +609,155 @@ static int s390_pcihost_setup_msix(S390PCIBusDevice *pbdev)
     return 0;
 }
 
+static S390PCIBusDevice *s390_pci_device_new(const char *target)
+{
+    DeviceState *dev = NULL;
+    S390pciState *s = s390_get_phb();
+
+    dev = qdev_try_create(BUS(s->bus), TYPE_S390_PCI_DEVICE);
+    if (!dev) {
+        return NULL;
+    }
+
+    qdev_prop_set_string(dev, "target", target);
+    qdev_init_nofail(dev);
+
+    return S390_PCI_DEVICE(dev);
+}
+
 static void s390_pcihost_hot_plug(HotplugHandler *hotplug_dev,
                                   DeviceState *dev, Error **errp)
 {
-    PCIDevice *pci_dev = PCI_DEVICE(dev);
-    S390PCIBusDevice *pbdev;
-    S390pciState *s = S390_PCI_HOST_BRIDGE(pci_device_root_bus(pci_dev)
-                                           ->qbus.parent);
+    PCIDevice *pdev = NULL;
+    S390PCIBusDevice *pbdev = NULL;
+    S390pciState *s = s390_get_phb();
 
-    pbdev = &s->pbdev[PCI_SLOT(pci_dev->devfn)];
+    if (object_dynamic_cast(OBJECT(dev), TYPE_PCI_DEVICE)) {
+        pdev = PCI_DEVICE(dev);
 
-    pbdev->fid = s390_pci_get_pfid(pci_dev);
-    pbdev->pdev = pci_dev;
-    pbdev->configured = true;
-    pbdev->fh = s390_pci_get_pfh(pci_dev);
+        if (!dev->id) {
+            /* In the case the PCI device does not define an id */
+            /* we generate one based on the PCI address         */
+            dev->id = g_strdup_printf("auto_%02x:%02x.%01x",
+                                      pci_bus_num(pdev->bus),
+                                      PCI_SLOT(pdev->devfn),
+                                      PCI_FUNC(pdev->devfn));
+        }
 
-    s390_pcihost_setup_msix(pbdev);
+        pbdev = s390_pci_find_dev_by_target(dev->id);
+        if (!pbdev) {
+            pbdev = s390_pci_device_new(dev->id);
+            if (!pbdev) {
+                error_setg(errp, "create zpci device failed");
+            }
+        }
 
-    if (dev->hotplugged) {
-        s390_pci_generate_plug_event(HP_EVENT_RESERVED_TO_STANDBY,
-                                     pbdev->fh, pbdev->fid);
-        s390_pci_generate_plug_event(HP_EVENT_TO_CONFIGURED,
-                                     pbdev->fh, pbdev->fid);
+        if (object_dynamic_cast(OBJECT(dev), "vfio-pci")) {
+            pbdev->fh |= FH_SHM_VFIO;
+        } else {
+            pbdev->fh |= FH_SHM_EMUL;
+        }
+
+        pbdev->pdev = pdev;
+        pbdev->iommu = s->iommu[PCI_SLOT(pdev->devfn)];
+        pbdev->state = ZPCI_FS_STANDBY;
+        s390_pcihost_setup_msix(pbdev);
+
+        if (dev->hotplugged) {
+            s390_pci_generate_plug_event(HP_EVENT_RESERVED_TO_STANDBY,
+                                         pbdev->fh, pbdev->fid);
+        }
+    } else if (object_dynamic_cast(OBJECT(dev), TYPE_S390_PCI_DEVICE)) {
+        int idx;
+
+        pbdev = S390_PCI_DEVICE(dev);
+        for (idx = 0; idx < PCI_SLOT_MAX; idx++) {
+            if (!s->pbdev[idx]) {
+                s->pbdev[idx] = pbdev;
+                pbdev->fh = idx;
+                return;
+            }
+        }
+
+        error_setg(errp, "no slot for plugging zpci device");
     }
 }
 
+static void s390_pcihost_timer_cb(void *opaque)
+{
+    S390PCIBusDevice *pbdev = opaque;
+
+    if (pbdev->summary_ind) {
+        pci_dereg_irqs(pbdev);
+    }
+    if (pbdev->iommu_enabled) {
+        pci_dereg_ioat(pbdev);
+    }
+
+    pbdev->state = ZPCI_FS_STANDBY;
+    s390_pci_generate_plug_event(HP_EVENT_CONFIGURED_TO_STBRES,
+                                 pbdev->fh, pbdev->fid);
+    qdev_unplug(DEVICE(pbdev), NULL);
+}
+
 static void s390_pcihost_hot_unplug(HotplugHandler *hotplug_dev,
                                     DeviceState *dev, Error **errp)
 {
-    PCIDevice *pci_dev = PCI_DEVICE(dev);
-    S390pciState *s = S390_PCI_HOST_BRIDGE(pci_device_root_bus(pci_dev)
-                                           ->qbus.parent);
-    S390PCIBusDevice *pbdev = &s->pbdev[PCI_SLOT(pci_dev->devfn)];
+    int i;
+    PCIDevice *pci_dev = NULL;
+    S390PCIBusDevice *pbdev = NULL;
+    S390pciState *s = s390_get_phb();
+
+    if (object_dynamic_cast(OBJECT(dev), TYPE_PCI_DEVICE)) {
+        pci_dev = PCI_DEVICE(dev);
 
-    if (pbdev->configured) {
-        pbdev->configured = false;
-        s390_pci_generate_plug_event(HP_EVENT_CONFIGURED_TO_STBRES,
+        for (i = 0 ; i < PCI_SLOT_MAX; i++) {
+            if (s->pbdev[i]->pdev == pci_dev) {
+                pbdev = s->pbdev[i];
+                break;
+            }
+        }
+
+        if (!pbdev) {
+            object_unparent(OBJECT(pci_dev));
+            return;
+        }
+    } else if (object_dynamic_cast(OBJECT(dev), TYPE_S390_PCI_DEVICE)) {
+        pbdev = S390_PCI_DEVICE(dev);
+        pci_dev = pbdev->pdev;
+    }
+
+    switch (pbdev->state) {
+    case ZPCI_FS_RESERVED:
+        goto out;
+    case ZPCI_FS_STANDBY:
+        break;
+    default:
+        s390_pci_generate_plug_event(HP_EVENT_DECONFIGURE_REQUEST,
                                      pbdev->fh, pbdev->fid);
+        pbdev->release_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
+                                            s390_pcihost_timer_cb,
+                                            pbdev);
+        timer_mod(pbdev->release_timer,
+                  qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + HOT_UNPLUG_TIMEOUT);
+        return;
+    }
+
+    if (pbdev->release_timer && timer_pending(pbdev->release_timer)) {
+        timer_del(pbdev->release_timer);
+        timer_free(pbdev->release_timer);
+        pbdev->release_timer = NULL;
     }
 
     s390_pci_generate_plug_event(HP_EVENT_STANDBY_TO_RESERVED,
                                  pbdev->fh, pbdev->fid);
-    pbdev->fh = 0;
-    pbdev->fid = 0;
-    pbdev->pdev = NULL;
     object_unparent(OBJECT(pci_dev));
+    pbdev->pdev = NULL;
+    pbdev->state = ZPCI_FS_RESERVED;
+out:
+    pbdev->fid = 0;
+    s->pbdev[pbdev->fh & FH_MASK_INDEX] = NULL;
+    object_unparent(OBJECT(pbdev));
 }
 
 static void s390_pcihost_class_init(ObjectClass *klass, void *data)
@@ -652,9 +784,178 @@ static const TypeInfo s390_pcihost_info = {
     }
 };
 
+static const TypeInfo s390_pcibus_info = {
+    .name = TYPE_S390_PCI_BUS,
+    .parent = TYPE_BUS,
+    .instance_size = sizeof(S390PCIBus),
+};
+
+static uint16_t s390_pci_generate_uid(void)
+{
+    uint16_t uid = 0;
+
+    do {
+        uid++;
+        if (!s390_pci_find_dev_by_uid(uid)) {
+            return uid;
+        }
+    } while (uid < ZPCI_MAX_UID);
+
+    return UID_UNDEFINED;
+}
+
+static uint32_t s390_pci_generate_fid(Error **errp)
+{
+    uint32_t fid = 0;
+
+    while (fid <= ZPCI_MAX_FID) {
+        if (!s390_pci_find_dev_by_fid(fid)) {
+            return fid;
+        }
+
+        if (fid == ZPCI_MAX_FID) {
+            break;
+        }
+
+        fid++;
+    }
+
+    error_setg(errp, "no free fid could be found");
+    return 0;
+}
+
+static void s390_pci_device_realize(DeviceState *dev, Error **errp)
+{
+    S390PCIBusDevice *zpci = S390_PCI_DEVICE(dev);
+
+    if (!zpci->target) {
+        error_setg(errp, "target must be defined");
+        return;
+    }
+
+    if (s390_pci_find_dev_by_target(zpci->target)) {
+        error_setg(errp, "target %s already has an associated zpci device",
+                   zpci->target);
+        return;
+    }
+
+    if (zpci->uid == UID_UNDEFINED) {
+        zpci->uid = s390_pci_generate_uid();
+        if (!zpci->uid) {
+            error_setg(errp, "no free uid could be found");
+            return;
+        }
+    } else if (s390_pci_find_dev_by_uid(zpci->uid)) {
+        error_setg(errp, "uid %u already in use", zpci->uid);
+        return;
+    }
+
+    if (!zpci->fid_defined) {
+        Error *local_error = NULL;
+
+        zpci->fid = s390_pci_generate_fid(&local_error);
+        if (local_error) {
+            error_propagate(errp, local_error);
+            return;
+        }
+    } else if (s390_pci_find_dev_by_fid(zpci->fid)) {
+        error_setg(errp, "fid %u already in use", zpci->fid);
+        return;
+    }
+
+    zpci->state = ZPCI_FS_RESERVED;
+}
+
+static void s390_pci_device_reset(DeviceState *dev)
+{
+    S390PCIBusDevice *pbdev = S390_PCI_DEVICE(dev);
+
+    switch (pbdev->state) {
+    case ZPCI_FS_RESERVED:
+        return;
+    case ZPCI_FS_STANDBY:
+        break;
+    default:
+        pbdev->fh &= ~FH_MASK_ENABLE;
+        pbdev->state = ZPCI_FS_DISABLED;
+        break;
+    }
+
+    if (pbdev->summary_ind) {
+        pci_dereg_irqs(pbdev);
+    }
+    if (pbdev->iommu_enabled) {
+        pci_dereg_ioat(pbdev);
+    }
+
+    pbdev->fmb_addr = 0;
+}
+
+static void s390_pci_get_fid(Object *obj, Visitor *v, const char *name,
+                         void *opaque, Error **errp)
+{
+    Property *prop = opaque;
+    uint32_t *ptr = qdev_get_prop_ptr(DEVICE(obj), prop);
+
+    visit_type_uint32(v, name, ptr, errp);
+}
+
+static void s390_pci_set_fid(Object *obj, Visitor *v, const char *name,
+                         void *opaque, Error **errp)
+{
+    DeviceState *dev = DEVICE(obj);
+    S390PCIBusDevice *zpci = S390_PCI_DEVICE(obj);
+    Property *prop = opaque;
+    uint32_t *ptr = qdev_get_prop_ptr(dev, prop);
+
+    if (dev->realized) {
+        qdev_prop_set_after_realize(dev, name, errp);
+        return;
+    }
+
+    visit_type_uint32(v, name, ptr, errp);
+    zpci->fid_defined = true;
+}
+
+static PropertyInfo s390_pci_fid_propinfo = {
+    .name = "zpci_fid",
+    .get = s390_pci_get_fid,
+    .set = s390_pci_set_fid,
+};
+
+#define DEFINE_PROP_S390_PCI_FID(_n, _s, _f) \
+    DEFINE_PROP(_n, _s, _f, s390_pci_fid_propinfo, uint32_t)
+
+static Property s390_pci_device_properties[] = {
+    DEFINE_PROP_UINT16("uid", S390PCIBusDevice, uid, UID_UNDEFINED),
+    DEFINE_PROP_S390_PCI_FID("fid", S390PCIBusDevice, fid),
+    DEFINE_PROP_STRING("target", S390PCIBusDevice, target),
+    DEFINE_PROP_END_OF_LIST(),
+};
+
+static void s390_pci_device_class_init(ObjectClass *klass, void *data)
+{
+    DeviceClass *dc = DEVICE_CLASS(klass);
+
+    dc->desc = "zpci device";
+    dc->reset = s390_pci_device_reset;
+    dc->bus_type = TYPE_S390_PCI_BUS;
+    dc->realize = s390_pci_device_realize;
+    dc->props = s390_pci_device_properties;
+}
+
+static const TypeInfo s390_pci_device_info = {
+    .name = TYPE_S390_PCI_DEVICE,
+    .parent = TYPE_DEVICE,
+    .instance_size = sizeof(S390PCIBusDevice),
+    .class_init = s390_pci_device_class_init,
+};
+
 static void s390_pci_register_types(void)
 {
     type_register_static(&s390_pcihost_info);
+    type_register_static(&s390_pcibus_info);
+    type_register_static(&s390_pci_device_info);
 }
 
 type_init(s390_pci_register_types)
diff --git a/hw/s390x/s390-pci-bus.h b/hw/s390x/s390-pci-bus.h
index 2c852d47fa..4f564e02f2 100644
--- a/hw/s390x/s390-pci-bus.h
+++ b/hw/s390x/s390-pci-bus.h
@@ -14,23 +14,38 @@
 #ifndef HW_S390_PCI_BUS_H
 #define HW_S390_PCI_BUS_H
 
-#include <hw/pci/pci.h>
-#include <hw/pci/pci_host.h>
+#include "hw/pci/pci.h"
+#include "hw/pci/pci_host.h"
 #include "hw/s390x/sclp.h"
 #include "hw/s390x/s390_flic.h"
 #include "hw/s390x/css.h"
 
 #define TYPE_S390_PCI_HOST_BRIDGE "s390-pcihost"
-#define FH_VIRT 0x00ff0000
-#define ENABLE_BIT_OFFSET 31
-#define FH_ENABLED (1 << ENABLE_BIT_OFFSET)
+#define TYPE_S390_PCI_BUS "s390-pcibus"
+#define TYPE_S390_PCI_DEVICE "zpci"
+#define FH_MASK_ENABLE   0x80000000
+#define FH_MASK_INSTANCE 0x7f000000
+#define FH_MASK_SHM      0x00ff0000
+#define FH_MASK_INDEX    0x0000001f
+#define FH_SHM_VFIO      0x00010000
+#define FH_SHM_EMUL      0x00020000
 #define S390_PCIPT_ADAPTER 2
+#define ZPCI_MAX_FID 0xffffffff
+#define ZPCI_MAX_UID 0xffff
+#define UID_UNDEFINED 0
+#define UID_CHECKING_ENABLED 0x01
+#define HOT_UNPLUG_TIMEOUT (NANOSECONDS_PER_SECOND * 60 * 5)
 
 #define S390_PCI_HOST_BRIDGE(obj) \
     OBJECT_CHECK(S390pciState, (obj), TYPE_S390_PCI_HOST_BRIDGE)
+#define S390_PCI_BUS(obj) \
+    OBJECT_CHECK(S390PCIBus, (obj), TYPE_S390_PCI_BUS)
+#define S390_PCI_DEVICE(obj) \
+    OBJECT_CHECK(S390PCIBusDevice, (obj), TYPE_S390_PCI_DEVICE)
 
 #define HP_EVENT_TO_CONFIGURED        0x0301
 #define HP_EVENT_RESERVED_TO_STANDBY  0x0302
+#define HP_EVENT_DECONFIGURE_REQUEST  0x0303
 #define HP_EVENT_CONFIGURED_TO_STBRES 0x0304
 #define HP_EVENT_STANDBY_TO_RESERVED  0x0308
 
@@ -150,6 +165,34 @@ enum ZpciIoatDtype {
 #define ZPCI_TABLE_VALID_MASK           0x20
 #define ZPCI_TABLE_PROT_MASK            0x200
 
+/* PCI Function States
+ *
+ * reserved: default; device has just been plugged or is in progress of being
+ *           unplugged
+ * standby: device is present but not configured; transition from any
+ *          configured state/to this state via sclp configure/deconfigure
+ *
+ * The following states make up the "configured" meta-state:
+ * disabled: device is configured but not enabled; transition between this
+ *           state and enabled via clp enable/disable
+ * enbaled: device is ready for use; transition to disabled via clp disable;
+ *          may enter an error state
+ * blocked: ignore all DMA and interrupts; transition back to enabled or from
+ *          error state via mpcifc
+ * error: an error occured; transition back to enabled via mpcifc
+ * permanent error: an unrecoverable error occured; transition to standby via
+ *                  sclp deconfigure
+ */
+typedef enum {
+    ZPCI_FS_RESERVED,
+    ZPCI_FS_STANDBY,
+    ZPCI_FS_DISABLED,
+    ZPCI_FS_ENABLED,
+    ZPCI_FS_BLOCKED,
+    ZPCI_FS_ERROR,
+    ZPCI_FS_PERMANENT_ERROR,
+} ZpciState;
+
 typedef struct SeiContainer {
     QTAILQ_ENTRY(SeiContainer) link;
     uint32_t fid;
@@ -214,14 +257,21 @@ typedef struct S390MsixInfo {
     uint32_t pba_offset;
 } S390MsixInfo;
 
+typedef struct S390PCIIOMMU {
+    AddressSpace as;
+    MemoryRegion mr;
+} S390PCIIOMMU;
+
 typedef struct S390PCIBusDevice {
+    DeviceState qdev;
     PCIDevice *pdev;
-    bool configured;
-    bool error_state;
-    bool lgstg_blocked;
+    ZpciState state;
     bool iommu_enabled;
+    char *target;
+    uint16_t uid;
     uint32_t fh;
     uint32_t fid;
+    bool fid_defined;
     uint64_t g_iota;
     uint64_t pba;
     uint64_t pal;
@@ -231,16 +281,22 @@ typedef struct S390PCIBusDevice {
     uint8_t sum;
     S390MsixInfo msix;
     AdapterRoutes routes;
-    AddressSpace as;
-    MemoryRegion mr;
+    S390PCIIOMMU *iommu;
     MemoryRegion iommu_mr;
     IndAddr *summary_ind;
     IndAddr *indicator;
+    QEMUTimer *release_timer;
 } S390PCIBusDevice;
 
+typedef struct S390PCIBus {
+    BusState qbus;
+} S390PCIBus;
+
 typedef struct S390pciState {
     PCIHostState parent_obj;
-    S390PCIBusDevice pbdev[PCI_SLOT_MAX];
+    S390PCIBus *bus;
+    S390PCIBusDevice *pbdev[PCI_SLOT_MAX];
+    S390PCIIOMMU *iommu[PCI_SLOT_MAX];
     AddressSpace msix_notify_as;
     MemoryRegion msix_notify_mr;
     QTAILQ_HEAD(, SeiContainer) pending_sei;
@@ -252,8 +308,11 @@ void s390_pci_sclp_configure(SCCB *sccb);
 void s390_pci_sclp_deconfigure(SCCB *sccb);
 void s390_pci_iommu_enable(S390PCIBusDevice *pbdev);
 void s390_pci_iommu_disable(S390PCIBusDevice *pbdev);
+void s390_pci_generate_error_event(uint16_t pec, uint32_t fh, uint32_t fid,
+                                   uint64_t faddr, uint32_t e);
 S390PCIBusDevice *s390_pci_find_dev_by_idx(uint32_t idx);
 S390PCIBusDevice *s390_pci_find_dev_by_fh(uint32_t fh);
 S390PCIBusDevice *s390_pci_find_dev_by_fid(uint32_t fid);
+S390PCIBusDevice *s390_pci_find_next_avail_dev(S390PCIBusDevice *pbdev);
 
 #endif
diff --git a/hw/s390x/s390-pci-inst.c b/hw/s390x/s390-pci-inst.c
index 479375f65d..f069b110b4 100644
--- a/hw/s390x/s390-pci-inst.c
+++ b/hw/s390x/s390-pci-inst.c
@@ -16,8 +16,8 @@
 #include "cpu.h"
 #include "s390-pci-inst.h"
 #include "s390-pci-bus.h"
-#include <exec/memory-internal.h>
-#include <qemu/error-report.h>
+#include "exec/memory-internal.h"
+#include "qemu/error-report.h"
 
 /* #define DEBUG_S390PCI_INST */
 #ifdef DEBUG_S390PCI_INST
@@ -37,9 +37,9 @@ static void s390_set_status_code(CPUS390XState *env,
 
 static int list_pci(ClpReqRspListPci *rrb, uint8_t *cc)
 {
-    S390PCIBusDevice *pbdev;
-    uint32_t res_code, initial_l2, g_l2, finish;
-    int rc, idx;
+    S390PCIBusDevice *pbdev = NULL;
+    uint32_t res_code, initial_l2, g_l2;
+    int rc, i;
     uint64_t resume_token;
 
     rc = 0;
@@ -56,8 +56,7 @@ static int list_pci(ClpReqRspListPci *rrb, uint8_t *cc)
     }
 
     if ((ldl_p(&rrb->request.fmt) & ~CLP_MASK_FMT) != 0 ||
-        ldq_p(&rrb->request.reserved1) != 0 ||
-        ldq_p(&rrb->request.reserved2) != 0) {
+        ldq_p(&rrb->request.reserved1) != 0) {
         res_code = CLP_RC_RESNOT0;
         rc = -EINVAL;
         goto out;
@@ -72,6 +71,8 @@ static int list_pci(ClpReqRspListPci *rrb, uint8_t *cc)
             rc = -EINVAL;
             goto out;
         }
+    } else {
+        pbdev = s390_pci_find_next_avail_dev(NULL);
     }
 
     if (lduw_p(&rrb->response.hdr.len) < 48) {
@@ -91,43 +92,40 @@ static int list_pci(ClpReqRspListPci *rrb, uint8_t *cc)
 
     stl_p(&rrb->response.fmt, 0);
     stq_p(&rrb->response.reserved1, 0);
-    stq_p(&rrb->response.reserved2, 0);
-    stl_p(&rrb->response.mdd, FH_VIRT);
+    stl_p(&rrb->response.mdd, FH_MASK_SHM);
     stw_p(&rrb->response.max_fn, PCI_MAX_FUNCTIONS);
+    rrb->response.flags = UID_CHECKING_ENABLED;
     rrb->response.entry_size = sizeof(ClpFhListEntry);
-    finish = 0;
-    idx = resume_token;
+
+    i = 0;
     g_l2 = LIST_PCI_HDR_LEN;
-    do {
-        pbdev = s390_pci_find_dev_by_idx(idx);
-        if (!pbdev) {
-            finish = 1;
-            break;
-        }
-        stw_p(&rrb->response.fh_list[idx - resume_token].device_id,
+    while (g_l2 < initial_l2 && pbdev) {
+        stw_p(&rrb->response.fh_list[i].device_id,
             pci_get_word(pbdev->pdev->config + PCI_DEVICE_ID));
-        stw_p(&rrb->response.fh_list[idx - resume_token].vendor_id,
+        stw_p(&rrb->response.fh_list[i].vendor_id,
             pci_get_word(pbdev->pdev->config + PCI_VENDOR_ID));
-        stl_p(&rrb->response.fh_list[idx - resume_token].config,
-            pbdev->configured << 31);
-        stl_p(&rrb->response.fh_list[idx - resume_token].fid, pbdev->fid);
-        stl_p(&rrb->response.fh_list[idx - resume_token].fh, pbdev->fh);
+        /* Ignore RESERVED devices. */
+        stl_p(&rrb->response.fh_list[i].config,
+            pbdev->state == ZPCI_FS_STANDBY ? 0 : 1 << 31);
+        stl_p(&rrb->response.fh_list[i].fid, pbdev->fid);
+        stl_p(&rrb->response.fh_list[i].fh, pbdev->fh);
 
         g_l2 += sizeof(ClpFhListEntry);
         /* Add endian check for DPRINTF? */
         DPRINTF("g_l2 %d vendor id 0x%x device id 0x%x fid 0x%x fh 0x%x\n",
-            g_l2,
-            lduw_p(&rrb->response.fh_list[idx - resume_token].vendor_id),
-            lduw_p(&rrb->response.fh_list[idx - resume_token].device_id),
-            ldl_p(&rrb->response.fh_list[idx - resume_token].fid),
-            ldl_p(&rrb->response.fh_list[idx - resume_token].fh));
-        idx++;
-    } while (g_l2 < initial_l2);
-
-    if (finish == 1) {
+                g_l2,
+                lduw_p(&rrb->response.fh_list[i].vendor_id),
+                lduw_p(&rrb->response.fh_list[i].device_id),
+                ldl_p(&rrb->response.fh_list[i].fid),
+                ldl_p(&rrb->response.fh_list[i].fh));
+        pbdev = s390_pci_find_next_avail_dev(pbdev);
+        i++;
+    }
+
+    if (!pbdev) {
         resume_token = 0;
     } else {
-        resume_token = idx;
+        resume_token = pbdev->fh & FH_MASK_INDEX;
     }
     stq_p(&rrb->response.resume_token, resume_token);
     stw_p(&rrb->response.hdr.len, g_l2);
@@ -212,14 +210,35 @@ int clp_service_call(S390CPU *cpu, uint8_t r2)
 
         switch (reqsetpci->oc) {
         case CLP_SET_ENABLE_PCI_FN:
-            pbdev->fh = pbdev->fh | FH_ENABLED;
+            switch (reqsetpci->ndas) {
+            case 0:
+                stw_p(&ressetpci->hdr.rsp, CLP_RC_SETPCIFN_DMAAS);
+                goto out;
+            case 1:
+                break;
+            default:
+                stw_p(&ressetpci->hdr.rsp, CLP_RC_SETPCIFN_RES);
+                goto out;
+            }
+
+            if (pbdev->fh & FH_MASK_ENABLE) {
+                stw_p(&ressetpci->hdr.rsp, CLP_RC_SETPCIFN_FHOP);
+                goto out;
+            }
+
+            pbdev->fh |= FH_MASK_ENABLE;
+            pbdev->state = ZPCI_FS_ENABLED;
             stl_p(&ressetpci->fh, pbdev->fh);
             stw_p(&ressetpci->hdr.rsp, CLP_RC_OK);
             break;
         case CLP_SET_DISABLE_PCI_FN:
-            pbdev->fh = pbdev->fh & ~FH_ENABLED;
-            pbdev->error_state = false;
-            pbdev->lgstg_blocked = false;
+            if (!(pbdev->fh & FH_MASK_ENABLE)) {
+                stw_p(&ressetpci->hdr.rsp, CLP_RC_SETPCIFN_FHOP);
+                goto out;
+            }
+            device_reset(DEVICE(pbdev));
+            pbdev->fh &= ~FH_MASK_ENABLE;
+            pbdev->state = ZPCI_FS_DISABLED;
             stl_p(&ressetpci->fh, pbdev->fh);
             stw_p(&ressetpci->hdr.rsp, CLP_RC_OK);
             break;
@@ -256,9 +275,10 @@ int clp_service_call(S390CPU *cpu, uint8_t r2)
 
         stq_p(&resquery->sdma, ZPCI_SDMA_ADDR);
         stq_p(&resquery->edma, ZPCI_EDMA_ADDR);
+        stl_p(&resquery->fid, pbdev->fid);
         stw_p(&resquery->pchid, 0);
         stw_p(&resquery->ug, 1);
-        stl_p(&resquery->uid, pbdev->fid);
+        stl_p(&resquery->uid, pbdev->uid);
         stw_p(&resquery->hdr.rsp, CLP_RC_OK);
         break;
     }
@@ -317,16 +337,25 @@ int pcilg_service_call(S390CPU *cpu, uint8_t r1, uint8_t r2)
     offset = env->regs[r2 + 1];
 
     pbdev = s390_pci_find_dev_by_fh(fh);
-    if (!pbdev || !(pbdev->fh & FH_ENABLED)) {
+    if (!pbdev) {
         DPRINTF("pcilg no pci dev\n");
         setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
         return 0;
     }
 
-    if (pbdev->lgstg_blocked) {
+    switch (pbdev->state) {
+    case ZPCI_FS_RESERVED:
+    case ZPCI_FS_STANDBY:
+    case ZPCI_FS_DISABLED:
+    case ZPCI_FS_PERMANENT_ERROR:
+        setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
+        return 0;
+    case ZPCI_FS_ERROR:
         setcc(cpu, ZPCI_PCI_LS_ERR);
         s390_set_status_code(env, r2, ZPCI_PCI_ST_BLOCKED);
         return 0;
+    default:
+        break;
     }
 
     if (pcias < 6) {
@@ -390,7 +419,8 @@ static void update_msix_table_msg_data(S390PCIBusDevice *pbdev, uint64_t offset,
 
     msg_data = (uint8_t *)data - offset % PCI_MSIX_ENTRY_SIZE +
                PCI_MSIX_ENTRY_VECTOR_CTRL;
-    val = pci_get_long(msg_data) | (pbdev->fid << ZPCI_MSI_VEC_BITS);
+    val = pci_get_long(msg_data) |
+        ((pbdev->fh & FH_MASK_INDEX) << ZPCI_MSI_VEC_BITS);
     pci_set_long(msg_data, val);
     DPRINTF("update msix msg_data to 0x%" PRIx64 "\n", *data);
 }
@@ -434,16 +464,25 @@ int pcistg_service_call(S390CPU *cpu, uint8_t r1, uint8_t r2)
     offset = env->regs[r2 + 1];
 
     pbdev = s390_pci_find_dev_by_fh(fh);
-    if (!pbdev || !(pbdev->fh & FH_ENABLED)) {
+    if (!pbdev) {
         DPRINTF("pcistg no pci dev\n");
         setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
         return 0;
     }
 
-    if (pbdev->lgstg_blocked) {
+    switch (pbdev->state) {
+    case ZPCI_FS_RESERVED:
+    case ZPCI_FS_STANDBY:
+    case ZPCI_FS_DISABLED:
+    case ZPCI_FS_PERMANENT_ERROR:
+        setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
+        return 0;
+    case ZPCI_FS_ERROR:
         setcc(cpu, ZPCI_PCI_LS_ERR);
         s390_set_status_code(env, r2, ZPCI_PCI_ST_BLOCKED);
         return 0;
+    default:
+        break;
     }
 
     data = env->regs[r1];
@@ -525,18 +564,55 @@ int rpcit_service_call(S390CPU *cpu, uint8_t r1, uint8_t r2)
     end = start + env->regs[r2 + 1];
 
     pbdev = s390_pci_find_dev_by_fh(fh);
-    if (!pbdev || !(pbdev->fh & FH_ENABLED)) {
+    if (!pbdev) {
         DPRINTF("rpcit no pci dev\n");
         setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
         goto out;
     }
 
+    switch (pbdev->state) {
+    case ZPCI_FS_RESERVED:
+    case ZPCI_FS_STANDBY:
+    case ZPCI_FS_DISABLED:
+    case ZPCI_FS_PERMANENT_ERROR:
+        setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
+        return 0;
+    case ZPCI_FS_ERROR:
+        setcc(cpu, ZPCI_PCI_LS_ERR);
+        s390_set_status_code(env, r1, ZPCI_MOD_ST_ERROR_RECOVER);
+        return 0;
+    default:
+        break;
+    }
+
+    if (!pbdev->g_iota) {
+        pbdev->state = ZPCI_FS_ERROR;
+        setcc(cpu, ZPCI_PCI_LS_ERR);
+        s390_set_status_code(env, r1, ZPCI_PCI_ST_INSUF_RES);
+        s390_pci_generate_error_event(ERR_EVENT_INVALAS, pbdev->fh, pbdev->fid,
+                                      start, 0);
+        goto out;
+    }
+
+    if (end < pbdev->pba || start > pbdev->pal) {
+        pbdev->state = ZPCI_FS_ERROR;
+        setcc(cpu, ZPCI_PCI_LS_ERR);
+        s390_set_status_code(env, r1, ZPCI_PCI_ST_INSUF_RES);
+        s390_pci_generate_error_event(ERR_EVENT_OORANGE, pbdev->fh, pbdev->fid,
+                                      start, 0);
+        goto out;
+    }
+
     mr = &pbdev->iommu_mr;
     while (start < end) {
         entry = mr->iommu_ops->translate(mr, start, 0);
 
         if (!entry.translated_addr) {
+            pbdev->state = ZPCI_FS_ERROR;
             setcc(cpu, ZPCI_PCI_LS_ERR);
+            s390_set_status_code(env, r1, ZPCI_PCI_ST_INSUF_RES);
+            s390_pci_generate_error_event(ERR_EVENT_SERR, pbdev->fh, pbdev->fid,
+                                          start, ERR_EVENT_Q_BIT);
             goto out;
         }
 
@@ -589,16 +665,25 @@ int pcistb_service_call(S390CPU *cpu, uint8_t r1, uint8_t r3, uint64_t gaddr,
     }
 
     pbdev = s390_pci_find_dev_by_fh(fh);
-    if (!pbdev || !(pbdev->fh & FH_ENABLED)) {
+    if (!pbdev) {
         DPRINTF("pcistb no pci dev fh 0x%x\n", fh);
         setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
         return 0;
     }
 
-    if (pbdev->lgstg_blocked) {
+    switch (pbdev->state) {
+    case ZPCI_FS_RESERVED:
+    case ZPCI_FS_STANDBY:
+    case ZPCI_FS_DISABLED:
+    case ZPCI_FS_PERMANENT_ERROR:
+        setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
+        return 0;
+    case ZPCI_FS_ERROR:
         setcc(cpu, ZPCI_PCI_LS_ERR);
         s390_set_status_code(env, r1, ZPCI_PCI_ST_BLOCKED);
         return 0;
+    default:
+        break;
     }
 
     mr = pbdev->pdev->io_regions[pcias].memory;
@@ -742,12 +827,23 @@ int mpcifc_service_call(S390CPU *cpu, uint8_t r1, uint64_t fiba, uint8_t ar)
     }
 
     pbdev = s390_pci_find_dev_by_fh(fh);
-    if (!pbdev || !(pbdev->fh & FH_ENABLED)) {
+    if (!pbdev) {
         DPRINTF("mpcifc no pci dev fh 0x%x\n", fh);
         setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
         return 0;
     }
 
+    switch (pbdev->state) {
+    case ZPCI_FS_RESERVED:
+    case ZPCI_FS_STANDBY:
+    case ZPCI_FS_DISABLED:
+    case ZPCI_FS_PERMANENT_ERROR:
+        setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
+        return 0;
+    default:
+        break;
+    }
+
     if (s390_cpu_virt_mem_read(cpu, fiba, ar, (uint8_t *)&fib, sizeof(fib))) {
         return 0;
     }
@@ -814,11 +910,25 @@ int mpcifc_service_call(S390CPU *cpu, uint8_t r1, uint64_t fiba, uint8_t ar)
         }
         break;
     case ZPCI_MOD_FC_RESET_ERROR:
-        pbdev->error_state = false;
-        pbdev->lgstg_blocked = false;
+        switch (pbdev->state) {
+        case ZPCI_FS_BLOCKED:
+        case ZPCI_FS_ERROR:
+            pbdev->state = ZPCI_FS_ENABLED;
+            break;
+        default:
+            cc = ZPCI_PCI_LS_ERR;
+            s390_set_status_code(env, r1, ZPCI_MOD_ST_SEQUENCE);
+        }
         break;
     case ZPCI_MOD_FC_RESET_BLOCK:
-        pbdev->lgstg_blocked = false;
+        switch (pbdev->state) {
+        case ZPCI_FS_ERROR:
+            pbdev->state = ZPCI_FS_BLOCKED;
+            break;
+        default:
+            cc = ZPCI_PCI_LS_ERR;
+            s390_set_status_code(env, r1, ZPCI_MOD_ST_SEQUENCE);
+        }
         break;
     case ZPCI_MOD_FC_SET_MEASURE:
         pbdev->fmb_addr = ldq_p(&fib.fmb_addr);
@@ -835,6 +945,7 @@ int mpcifc_service_call(S390CPU *cpu, uint8_t r1, uint64_t fiba, uint8_t ar)
 int stpcifc_service_call(S390CPU *cpu, uint8_t r1, uint64_t fiba, uint8_t ar)
 {
     CPUS390XState *env = &cpu->env;
+    uint8_t dmaas;
     uint32_t fh;
     ZpciFib fib;
     S390PCIBusDevice *pbdev;
@@ -847,19 +958,59 @@ int stpcifc_service_call(S390CPU *cpu, uint8_t r1, uint64_t fiba, uint8_t ar)
     }
 
     fh = env->regs[r1] >> 32;
+    dmaas = (env->regs[r1] >> 16) & 0xff;
+
+    if (dmaas) {
+        setcc(cpu, ZPCI_PCI_LS_ERR);
+        s390_set_status_code(env, r1, ZPCI_STPCIFC_ST_INVAL_DMAAS);
+        return 0;
+    }
 
     if (fiba & 0x7) {
         program_interrupt(env, PGM_SPECIFICATION, 6);
         return 0;
     }
 
-    pbdev = s390_pci_find_dev_by_fh(fh);
+    pbdev = s390_pci_find_dev_by_idx(fh & FH_MASK_INDEX);
     if (!pbdev) {
         setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
         return 0;
     }
 
     memset(&fib, 0, sizeof(fib));
+
+    switch (pbdev->state) {
+    case ZPCI_FS_RESERVED:
+    case ZPCI_FS_STANDBY:
+        setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
+        return 0;
+    case ZPCI_FS_DISABLED:
+        if (fh & FH_MASK_ENABLE) {
+            setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);
+            return 0;
+        }
+        goto out;
+    /* BLOCKED bit is set to one coincident with the setting of ERROR bit.
+     * FH Enabled bit is set to one in states of ENABLED, BLOCKED or ERROR. */
+    case ZPCI_FS_ERROR:
+        fib.fc |= 0x20;
+    case ZPCI_FS_BLOCKED:
+        fib.fc |= 0x40;
+    case ZPCI_FS_ENABLED:
+        fib.fc |= 0x80;
+        if (pbdev->iommu_enabled) {
+            fib.fc |= 0x10;
+        }
+        if (!(fh & FH_MASK_ENABLE)) {
+            env->regs[r1] |= 1ULL << 63;
+        }
+        break;
+    case ZPCI_FS_PERMANENT_ERROR:
+        setcc(cpu, ZPCI_PCI_LS_ERR);
+        s390_set_status_code(env, r1, ZPCI_STPCIFC_ST_PERM_ERROR);
+        return 0;
+    }
+
     stq_p(&fib.pba, pbdev->pba);
     stq_p(&fib.pal, pbdev->pal);
     stq_p(&fib.iota, pbdev->g_iota);
@@ -872,22 +1023,7 @@ int stpcifc_service_call(S390CPU *cpu, uint8_t r1, uint64_t fiba, uint8_t ar)
            ((uint32_t)pbdev->sum << 7) | pbdev->routes.adapter.summary_offset;
     stl_p(&fib.data, data);
 
-    if (pbdev->fh & FH_ENABLED) {
-        fib.fc |= 0x80;
-    }
-
-    if (pbdev->error_state) {
-        fib.fc |= 0x40;
-    }
-
-    if (pbdev->lgstg_blocked) {
-        fib.fc |= 0x20;
-    }
-
-    if (pbdev->g_iota) {
-        fib.fc |= 0x10;
-    }
-
+out:
     if (s390_cpu_virt_mem_write(cpu, fiba, ar, (uint8_t *)&fib, sizeof(fib))) {
         return 0;
     }
diff --git a/hw/s390x/s390-pci-inst.h b/hw/s390x/s390-pci-inst.h
index b084f2346b..23f4bfa0ed 100644
--- a/hw/s390x/s390-pci-inst.h
+++ b/hw/s390x/s390-pci-inst.h
@@ -15,7 +15,7 @@
 #define HW_S390_PCI_INST_H
 
 #include "s390-pci-bus.h"
-#include <sysemu/dma.h>
+#include "sysemu/dma.h"
 
 /* CLP common request & response block size */
 #define CLP_BLK_SIZE 4096
@@ -104,7 +104,7 @@ typedef struct ClpRspListPci {
     uint64_t resume_token;
     uint32_t mdd;
     uint16_t max_fn;
-    uint8_t reserved2;
+    uint8_t flags;
     uint8_t entry_size;
     ClpFhListEntry fh_list[CLP_FH_LIST_NR_ENTRIES];
 } QEMU_PACKED ClpRspListPci;
@@ -249,6 +249,11 @@ typedef struct ClpReqRspQueryPciGrp {
 #define ZPCI_MOD_FC_RESET_BLOCK 9
 #define ZPCI_MOD_FC_SET_MEASURE 10
 
+/* Store PCI Function Controls status codes */
+#define ZPCI_STPCIFC_ST_PERM_ERROR    8
+#define ZPCI_STPCIFC_ST_INVAL_DMAAS   28
+#define ZPCI_STPCIFC_ST_ERROR_RECOVER 40
+
 /* FIB function controls */
 #define ZPCI_FIB_FC_ENABLED     0x80
 #define ZPCI_FIB_FC_ERROR       0x40
diff --git a/hw/s390x/s390-virtio-ccw.c b/hw/s390x/s390-virtio-ccw.c
index 52f079a884..caf0a682a7 100644
--- a/hw/s390x/s390-virtio-ccw.c
+++ b/hw/s390x/s390-virtio-ccw.c
@@ -27,9 +27,10 @@
 #include "hw/compat.h"
 #include "ipl.h"
 #include "hw/s390x/s390-virtio-ccw.h"
+#include "hw/s390x/css-bridge.h"
 
 static const char *const reset_dev_types[] = {
-    "virtual-css-bridge",
+    TYPE_VIRTUAL_CSS_BRIDGE,
     "s390-sclp-event-facility",
     "s390-flic",
     "diag288",
diff --git a/hw/s390x/s390-virtio.h b/hw/s390x/s390-virtio.h
index ffd014cb5b..f588b80a6e 100644
--- a/hw/s390x/s390-virtio.h
+++ b/hw/s390x/s390-virtio.h
@@ -10,7 +10,7 @@
  */
 
 #ifndef HW_S390_VIRTIO_H
-#define HW_S390_VIRTIO_H 1
+#define HW_S390_VIRTIO_H
 
 #include "hw/nmi.h"
 #include "standard-headers/asm-s390/kvm_virtio.h"
diff --git a/hw/s390x/sclpquiesce.c b/hw/s390x/sclpquiesce.c
index c0ecab9c3b..762cb184ac 100644
--- a/hw/s390x/sclpquiesce.c
+++ b/hw/s390x/sclpquiesce.c
@@ -12,7 +12,7 @@
  *
  */
 #include "qemu/osdep.h"
-#include <hw/qdev.h>
+#include "hw/qdev.h"
 #include "sysemu/sysemu.h"
 #include "hw/s390x/sclp.h"
 #include "hw/s390x/event-facility.h"
diff --git a/hw/s390x/virtio-ccw.c b/hw/s390x/virtio-ccw.c
index 8b709e362e..a554a24d06 100644
--- a/hw/s390x/virtio-ccw.c
+++ b/hw/s390x/virtio-ccw.c
@@ -33,31 +33,11 @@
 #include "hw/s390x/css.h"
 #include "virtio-ccw.h"
 #include "trace.h"
+#include "hw/s390x/css-bridge.h"
 
 static void virtio_ccw_bus_new(VirtioBusState *bus, size_t bus_size,
                                VirtioCcwDevice *dev);
 
-static void virtual_css_bus_reset(BusState *qbus)
-{
-    /* This should actually be modelled via the generic css */
-    css_reset();
-}
-
-
-static void virtual_css_bus_class_init(ObjectClass *klass, void *data)
-{
-    BusClass *k = BUS_CLASS(klass);
-
-    k->reset = virtual_css_bus_reset;
-}
-
-static const TypeInfo virtual_css_bus_info = {
-    .name = TYPE_VIRTUAL_CSS_BUS,
-    .parent = TYPE_BUS,
-    .instance_size = sizeof(VirtualCssBus),
-    .class_init = virtual_css_bus_class_init,
-};
-
 VirtIODevice *virtio_ccw_get_vdev(SubchDev *sch)
 {
     VirtIODevice *vdev = NULL;
@@ -117,32 +97,13 @@ static int virtio_ccw_ioeventfd_assign(DeviceState *d, EventNotifier *notifier,
                                        int n, bool assign)
 {
     VirtioCcwDevice *dev = VIRTIO_CCW_DEVICE(d);
-    SubchDev *sch = dev->sch;
+    CcwDevice *ccw_dev = CCW_DEVICE(dev);
+    SubchDev *sch = ccw_dev->sch;
     uint32_t sch_id = (css_build_subchannel_id(sch) << 16) | sch->schid;
 
     return s390_assign_subch_ioeventfd(notifier, sch_id, n, assign);
 }
 
-VirtualCssBus *virtual_css_bus_init(void)
-{
-    VirtualCssBus *cbus;
-    BusState *bus;
-    DeviceState *dev;
-
-    /* Create bridge device */
-    dev = qdev_create(NULL, "virtual-css-bridge");
-    qdev_init_nofail(dev);
-
-    /* Create bus on bridge device */
-    bus = qbus_create(TYPE_VIRTUAL_CSS_BUS, dev, "virtual-css");
-    cbus = VIRTUAL_CSS_BUS(bus);
-
-    /* Enable hotplugging */
-    qbus_set_hotplug_handler(bus, dev, &error_abort);
-
-    return cbus;
-}
-
 /* Communication blocks used by several channel commands. */
 typedef struct VqInfoBlockLegacy {
     uint64_t queue;
@@ -234,6 +195,8 @@ static int virtio_ccw_set_vqs(SubchDev *sch, VqInfoBlock *info,
 
 static void virtio_ccw_reset_virtio(VirtioCcwDevice *dev, VirtIODevice *vdev)
 {
+    CcwDevice *ccw_dev = CCW_DEVICE(dev);
+
     virtio_ccw_stop_ioeventfd(dev);
     virtio_reset(vdev);
     if (dev->indicators) {
@@ -248,7 +211,7 @@ static void virtio_ccw_reset_virtio(VirtioCcwDevice *dev, VirtIODevice *vdev)
         release_indicator(&dev->routes.adapter, dev->summary_indicator);
         dev->summary_indicator = NULL;
     }
-    dev->sch->thinint_active = false;
+    ccw_dev->sch->thinint_active = false;
 }
 
 static int virtio_ccw_handle_set_vq(SubchDev *sch, CCW1 ccw, bool check_len,
@@ -703,116 +666,28 @@ static void virtio_sch_disable_cb(SubchDev *sch)
 
 static void virtio_ccw_device_realize(VirtioCcwDevice *dev, Error **errp)
 {
-    unsigned int schid;
-    bool found = false;
-    SubchDev *sch;
-    Error *err = NULL;
     VirtIOCCWDeviceClass *k = VIRTIO_CCW_DEVICE_GET_CLASS(dev);
+    CcwDevice *ccw_dev = CCW_DEVICE(dev);
+    SubchDev *sch = css_create_virtual_sch(ccw_dev->bus_id, errp);
+    Error *err = NULL;
 
-    sch = g_malloc0(sizeof(SubchDev));
-
-    sch->driver_data = dev;
-    dev->sch = sch;
-
-    dev->indicators = NULL;
-
-    /* Initialize subchannel structure. */
-    sch->channel_prog = 0x0;
-    sch->last_cmd_valid = false;
-    sch->thinint_active = false;
-    /*
-     * Use a device number if provided. Otherwise, fall back to subchannel
-     * number.
-     */
-    if (dev->bus_id.valid) {
-        /* Enforce use of virtual cssid. */
-        if (dev->bus_id.cssid != VIRTUAL_CSSID) {
-            error_setg(errp, "cssid %x not valid for virtio devices",
-                       dev->bus_id.cssid);
-            goto out_err;
-        }
-        if (css_devno_used(dev->bus_id.cssid, dev->bus_id.ssid,
-                           dev->bus_id.devid)) {
-                error_setg(errp, "Device %x.%x.%04x already exists",
-                           dev->bus_id.cssid, dev->bus_id.ssid,
-                           dev->bus_id.devid);
-                goto out_err;
-        }
-        sch->cssid = dev->bus_id.cssid;
-        sch->ssid = dev->bus_id.ssid;
-        sch->devno = dev->bus_id.devid;
-
-        /* Find the next free id. */
-        for (schid = 0; schid <= MAX_SCHID; schid++) {
-            if (!css_find_subch(1, sch->cssid, sch->ssid, schid)) {
-                sch->schid = schid;
-                css_subch_assign(sch->cssid, sch->ssid, sch->schid,
-                                 sch->devno, sch);
-                found = true;
-                break;
-            }
-        }
-        if (!found) {
-            error_setg(errp, "No free subchannel found for %x.%x.%04x",
-                       sch->cssid, sch->ssid, sch->devno);
-            goto out_err;
-        }
-        trace_virtio_ccw_new_device(sch->cssid, sch->ssid, sch->schid,
-                                    sch->devno, "user-configured");
-    } else {
-        unsigned int cssid = VIRTUAL_CSSID, ssid, devno;
-
-        for (ssid = 0; ssid <= MAX_SSID; ssid++) {
-            for (schid = 0; schid <= MAX_SCHID; schid++) {
-                if (!css_find_subch(1, cssid, ssid, schid)) {
-                    sch->cssid = cssid;
-                    sch->ssid = ssid;
-                    sch->schid = schid;
-                    devno = schid;
-                    /*
-                     * If the devno is already taken, look further in this
-                     * subchannel set.
-                     */
-                    while (css_devno_used(cssid, ssid, devno)) {
-                        if (devno == MAX_SCHID) {
-                            devno = 0;
-                        } else if (devno == schid - 1) {
-                            error_setg(errp, "No free devno found");
-                            goto out_err;
-                        } else {
-                            devno++;
-                        }
-                    }
-                    sch->devno = devno;
-                    css_subch_assign(cssid, ssid, schid, devno, sch);
-                    found = true;
-                    break;
-                }
-            }
-            if (found) {
-                break;
-            }
-        }
-        if (!found) {
-            error_setg(errp, "Virtual channel subsystem is full!");
-            goto out_err;
-        }
-        trace_virtio_ccw_new_device(cssid, ssid, schid, devno,
-                                    "auto-configured");
+    if (!sch) {
+        return;
     }
 
-    /* Build initial schib. */
-    css_sch_build_virtual_schib(sch, 0, VIRTIO_CCW_CHPID_TYPE);
-
+    sch->driver_data = dev;
     sch->ccw_cb = virtio_ccw_cb;
     sch->disable_cb = virtio_sch_disable_cb;
-
-    /* Build senseid data. */
-    memset(&sch->id, 0, sizeof(SenseId));
     sch->id.reserved = 0xff;
     sch->id.cu_type = VIRTIO_CCW_CU_TYPE;
-
+    ccw_dev->sch = sch;
+    dev->indicators = NULL;
     dev->revision = -1;
+    css_sch_build_virtual_schib(sch, 0, VIRTIO_CCW_CHPID_TYPE);
+
+    trace_virtio_ccw_new_device(
+        sch->cssid, sch->ssid, sch->schid, sch->devno,
+        ccw_dev->bus_id.valid ? "user-configured" : "auto-configured");
 
     if (k->realize) {
         k->realize(dev, &err);
@@ -820,19 +695,15 @@ static void virtio_ccw_device_realize(VirtioCcwDevice *dev, Error **errp)
     if (err) {
         error_propagate(errp, err);
         css_subch_assign(sch->cssid, sch->ssid, sch->schid, sch->devno, NULL);
-        goto out_err;
+        ccw_dev->sch = NULL;
+        g_free(sch);
     }
-
-    return;
-
-out_err:
-    dev->sch = NULL;
-    g_free(sch);
 }
 
 static int virtio_ccw_exit(VirtioCcwDevice *dev)
 {
-    SubchDev *sch = dev->sch;
+    CcwDevice *ccw_dev = CCW_DEVICE(dev);
+    SubchDev *sch = ccw_dev->sch;
 
     if (sch) {
         css_subch_assign(sch->cssid, sch->ssid, sch->schid, sch->devno, NULL);
@@ -1013,7 +884,9 @@ static void virtio_ccw_rng_realize(VirtioCcwDevice *ccw_dev, Error **errp)
  */
 static inline VirtioCcwDevice *to_virtio_ccw_dev_fast(DeviceState *d)
 {
-    return container_of(d, VirtioCcwDevice, parent_obj);
+    CcwDevice *ccw_dev = to_ccw_dev_fast(d);
+
+    return container_of(ccw_dev, VirtioCcwDevice, parent_obj);
 }
 
 static uint8_t virtio_set_ind_atomic(SubchDev *sch, uint64_t ind_loc,
@@ -1042,7 +915,8 @@ static uint8_t virtio_set_ind_atomic(SubchDev *sch, uint64_t ind_loc,
 static void virtio_ccw_notify(DeviceState *d, uint16_t vector)
 {
     VirtioCcwDevice *dev = to_virtio_ccw_dev_fast(d);
-    SubchDev *sch = dev->sch;
+    CcwDevice *ccw_dev = to_ccw_dev_fast(d);
+    SubchDev *sch = ccw_dev->sch;
     uint64_t indicators;
 
     /* queue indicators + secondary indicators */
@@ -1100,9 +974,10 @@ static void virtio_ccw_reset(DeviceState *d)
 {
     VirtioCcwDevice *dev = VIRTIO_CCW_DEVICE(d);
     VirtIODevice *vdev = virtio_bus_get_device(&dev->bus);
+    CcwDevice *ccw_dev = CCW_DEVICE(d);
 
     virtio_ccw_reset_virtio(dev, vdev);
-    css_reset_sch(dev->sch);
+    css_reset_sch(ccw_dev->sch);
 }
 
 static void virtio_ccw_vmstate_change(DeviceState *d, bool running)
@@ -1118,7 +993,7 @@ static void virtio_ccw_vmstate_change(DeviceState *d, bool running)
 
 static bool virtio_ccw_query_guest_notifiers(DeviceState *d)
 {
-    VirtioCcwDevice *dev = VIRTIO_CCW_DEVICE(d);
+    CcwDevice *dev = CCW_DEVICE(d);
 
     return !!(dev->sch->curr_status.pmcw.flags & PMCW_FLAGS_MASK_ENA);
 }
@@ -1126,8 +1001,9 @@ static bool virtio_ccw_query_guest_notifiers(DeviceState *d)
 static int virtio_ccw_get_mappings(VirtioCcwDevice *dev)
 {
     int r;
+    CcwDevice *ccw_dev = CCW_DEVICE(dev);
 
-    if (!dev->sch->thinint_active) {
+    if (!ccw_dev->sch->thinint_active) {
         return -EINVAL;
     }
 
@@ -1249,7 +1125,8 @@ static int virtio_ccw_set_guest_notifiers(DeviceState *d, int nvqs,
 {
     VirtioCcwDevice *dev = VIRTIO_CCW_DEVICE(d);
     VirtIODevice *vdev = virtio_bus_get_device(&dev->bus);
-    bool with_irqfd = dev->sch->thinint_active && kvm_irqfds_enabled();
+    CcwDevice *ccw_dev = CCW_DEVICE(d);
+    bool with_irqfd = ccw_dev->sch->thinint_active && kvm_irqfds_enabled();
     int r, n;
 
     if (with_irqfd && assigned) {
@@ -1308,7 +1185,8 @@ static int virtio_ccw_load_queue(DeviceState *d, int n, QEMUFile *f)
 static void virtio_ccw_save_config(DeviceState *d, QEMUFile *f)
 {
     VirtioCcwDevice *dev = VIRTIO_CCW_DEVICE(d);
-    SubchDev *s = dev->sch;
+    CcwDevice *ccw_dev = CCW_DEVICE(d);
+    SubchDev *s = ccw_dev->sch;
     VirtIODevice *vdev = virtio_ccw_get_vdev(s);
 
     subch_device_save(s, f);
@@ -1342,7 +1220,8 @@ static void virtio_ccw_save_config(DeviceState *d, QEMUFile *f)
 static int virtio_ccw_load_config(DeviceState *d, QEMUFile *f)
 {
     VirtioCcwDevice *dev = VIRTIO_CCW_DEVICE(d);
-    SubchDev *s = dev->sch;
+    CcwDevice *ccw_dev = CCW_DEVICE(d);
+    SubchDev *s = ccw_dev->sch;
     VirtIODevice *vdev = virtio_ccw_get_vdev(s);
     int len;
 
@@ -1387,7 +1266,8 @@ static void virtio_ccw_device_plugged(DeviceState *d, Error **errp)
 {
     VirtioCcwDevice *dev = VIRTIO_CCW_DEVICE(d);
     VirtIODevice *vdev = virtio_bus_get_device(&dev->bus);
-    SubchDev *sch = dev->sch;
+    CcwDevice *ccw_dev = CCW_DEVICE(d);
+    SubchDev *sch = ccw_dev->sch;
     int n = virtio_get_num_queues(vdev);
 
     if (virtio_get_num_queues(vdev) > VIRTIO_CCW_QUEUE_MAX) {
@@ -1431,7 +1311,7 @@ static void virtio_ccw_device_unplugged(DeviceState *d)
 /**************** Virtio-ccw Bus Device Descriptions *******************/
 
 static Property virtio_ccw_net_properties[] = {
-    DEFINE_PROP_CSS_DEV_ID("devno", VirtioCcwDevice, bus_id),
+    DEFINE_PROP_CSS_DEV_ID("devno", VirtioCcwDevice, parent_obj.bus_id),
     DEFINE_PROP_BIT("ioeventfd", VirtioCcwDevice, flags,
                     VIRTIO_CCW_FLAG_USE_IOEVENTFD_BIT, true),
     DEFINE_PROP_UINT32("max_revision", VirtioCcwDevice, max_rev,
@@ -1460,7 +1340,7 @@ static const TypeInfo virtio_ccw_net = {
 };
 
 static Property virtio_ccw_blk_properties[] = {
-    DEFINE_PROP_CSS_DEV_ID("devno", VirtioCcwDevice, bus_id),
+    DEFINE_PROP_CSS_DEV_ID("devno", VirtioCcwDevice, parent_obj.bus_id),
     DEFINE_PROP_BIT("ioeventfd", VirtioCcwDevice, flags,
                     VIRTIO_CCW_FLAG_USE_IOEVENTFD_BIT, true),
     DEFINE_PROP_UINT32("max_revision", VirtioCcwDevice, max_rev,
@@ -1489,7 +1369,7 @@ static const TypeInfo virtio_ccw_blk = {
 };
 
 static Property virtio_ccw_serial_properties[] = {
-    DEFINE_PROP_CSS_DEV_ID("devno", VirtioCcwDevice, bus_id),
+    DEFINE_PROP_CSS_DEV_ID("devno", VirtioCcwDevice, parent_obj.bus_id),
     DEFINE_PROP_BIT("ioeventfd", VirtioCcwDevice, flags,
                     VIRTIO_CCW_FLAG_USE_IOEVENTFD_BIT, true),
     DEFINE_PROP_UINT32("max_revision", VirtioCcwDevice, max_rev,
@@ -1518,7 +1398,7 @@ static const TypeInfo virtio_ccw_serial = {
 };
 
 static Property virtio_ccw_balloon_properties[] = {
-    DEFINE_PROP_CSS_DEV_ID("devno", VirtioCcwDevice, bus_id),
+    DEFINE_PROP_CSS_DEV_ID("devno", VirtioCcwDevice, parent_obj.bus_id),
     DEFINE_PROP_BIT("ioeventfd", VirtioCcwDevice, flags,
                     VIRTIO_CCW_FLAG_USE_IOEVENTFD_BIT, true),
     DEFINE_PROP_UINT32("max_revision", VirtioCcwDevice, max_rev,
@@ -1547,7 +1427,7 @@ static const TypeInfo virtio_ccw_balloon = {
 };
 
 static Property virtio_ccw_scsi_properties[] = {
-    DEFINE_PROP_CSS_DEV_ID("devno", VirtioCcwDevice, bus_id),
+    DEFINE_PROP_CSS_DEV_ID("devno", VirtioCcwDevice, parent_obj.bus_id),
     DEFINE_PROP_BIT("ioeventfd", VirtioCcwDevice, flags,
                     VIRTIO_CCW_FLAG_USE_IOEVENTFD_BIT, true),
     DEFINE_PROP_UINT32("max_revision", VirtioCcwDevice, max_rev,
@@ -1577,7 +1457,7 @@ static const TypeInfo virtio_ccw_scsi = {
 
 #ifdef CONFIG_VHOST_SCSI
 static Property vhost_ccw_scsi_properties[] = {
-    DEFINE_PROP_CSS_DEV_ID("devno", VirtioCcwDevice, bus_id),
+    DEFINE_PROP_CSS_DEV_ID("devno", VirtioCcwDevice, parent_obj.bus_id),
     DEFINE_PROP_UINT32("max_revision", VirtioCcwDevice, max_rev,
                        VIRTIO_CCW_MAX_REV),
     DEFINE_PROP_END_OF_LIST(),
@@ -1615,7 +1495,7 @@ static void virtio_ccw_rng_instance_init(Object *obj)
 }
 
 static Property virtio_ccw_rng_properties[] = {
-    DEFINE_PROP_CSS_DEV_ID("devno", VirtioCcwDevice, bus_id),
+    DEFINE_PROP_CSS_DEV_ID("devno", VirtioCcwDevice, parent_obj.bus_id),
     DEFINE_PROP_BIT("ioeventfd", VirtioCcwDevice, flags,
                     VIRTIO_CCW_FLAG_USE_IOEVENTFD_BIT, true),
     DEFINE_PROP_UINT32("max_revision", VirtioCcwDevice, max_rev,
@@ -1662,29 +1542,17 @@ static int virtio_ccw_busdev_exit(DeviceState *dev)
 static void virtio_ccw_busdev_unplug(HotplugHandler *hotplug_dev,
                                      DeviceState *dev, Error **errp)
 {
-    VirtioCcwDevice *_dev = (VirtioCcwDevice *)dev;
-    SubchDev *sch = _dev->sch;
+    VirtioCcwDevice *_dev = to_virtio_ccw_dev_fast(dev);
 
     virtio_ccw_stop_ioeventfd(_dev);
-
-    /*
-     * We should arrive here only for device_del, since we don't support
-     * direct hot(un)plug of channels, but only through virtio.
-     */
-    assert(sch != NULL);
-    /* Subchannel is now disabled and no longer valid. */
-    sch->curr_status.pmcw.flags &= ~(PMCW_FLAGS_MASK_ENA |
-                                     PMCW_FLAGS_MASK_DNV);
-
-    css_generate_sch_crws(sch->cssid, sch->ssid, sch->schid, 1, 0);
-
-    object_unparent(OBJECT(dev));
 }
 
 static void virtio_ccw_device_class_init(ObjectClass *klass, void *data)
 {
     DeviceClass *dc = DEVICE_CLASS(klass);
+    CCWDeviceClass *k = CCW_DEVICE_CLASS(dc);
 
+    k->unplug = virtio_ccw_busdev_unplug;
     dc->realize = virtio_ccw_busdev_realize;
     dc->exit = virtio_ccw_busdev_exit;
     dc->bus_type = TYPE_VIRTUAL_CSS_BUS;
@@ -1692,44 +1560,13 @@ static void virtio_ccw_device_class_init(ObjectClass *klass, void *data)
 
 static const TypeInfo virtio_ccw_device_info = {
     .name = TYPE_VIRTIO_CCW_DEVICE,
-    .parent = TYPE_DEVICE,
+    .parent = TYPE_CCW_DEVICE,
     .instance_size = sizeof(VirtioCcwDevice),
     .class_init = virtio_ccw_device_class_init,
     .class_size = sizeof(VirtIOCCWDeviceClass),
     .abstract = true,
 };
 
-/***************** Virtual-css Bus Bridge Device ********************/
-/* Only required to have the virtio bus as child in the system bus */
-
-static int virtual_css_bridge_init(SysBusDevice *dev)
-{
-    /* nothing */
-    return 0;
-}
-
-static void virtual_css_bridge_class_init(ObjectClass *klass, void *data)
-{
-    SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass);
-    HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(klass);
-    DeviceClass *dc = DEVICE_CLASS(klass);
-
-    k->init = virtual_css_bridge_init;
-    hc->unplug = virtio_ccw_busdev_unplug;
-    set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories);
-}
-
-static const TypeInfo virtual_css_bridge_info = {
-    .name          = "virtual-css-bridge",
-    .parent        = TYPE_SYS_BUS_DEVICE,
-    .instance_size = sizeof(SysBusDevice),
-    .class_init    = virtual_css_bridge_class_init,
-    .interfaces = (InterfaceInfo[]) {
-        { TYPE_HOTPLUG_HANDLER },
-        { }
-    }
-};
-
 /* virtio-ccw-bus */
 
 static void virtio_ccw_bus_new(VirtioBusState *bus, size_t bus_size,
@@ -1775,7 +1612,7 @@ static const TypeInfo virtio_ccw_bus_info = {
 
 #ifdef CONFIG_VIRTFS
 static Property virtio_ccw_9p_properties[] = {
-    DEFINE_PROP_CSS_DEV_ID("devno", VirtioCcwDevice, bus_id),
+    DEFINE_PROP_CSS_DEV_ID("devno", VirtioCcwDevice, parent_obj.bus_id),
     DEFINE_PROP_BIT("ioeventfd", VirtioCcwDevice, flags,
             VIRTIO_CCW_FLAG_USE_IOEVENTFD_BIT, true),
     DEFINE_PROP_UINT32("max_revision", VirtioCcwDevice, max_rev,
@@ -1824,7 +1661,6 @@ static const TypeInfo virtio_ccw_9p_info = {
 static void virtio_ccw_register(void)
 {
     type_register_static(&virtio_ccw_bus_info);
-    type_register_static(&virtual_css_bus_info);
     type_register_static(&virtio_ccw_device_info);
     type_register_static(&virtio_ccw_serial);
     type_register_static(&virtio_ccw_blk);
@@ -1835,7 +1671,6 @@ static void virtio_ccw_register(void)
     type_register_static(&vhost_ccw_scsi);
 #endif
     type_register_static(&virtio_ccw_rng);
-    type_register_static(&virtual_css_bridge_info);
 #ifdef CONFIG_VIRTFS
     type_register_static(&virtio_ccw_9p_info);
 #endif
diff --git a/hw/s390x/virtio-ccw.h b/hw/s390x/virtio-ccw.h
index 0bfb5d93c6..1c6bc86316 100644
--- a/hw/s390x/virtio-ccw.h
+++ b/hw/s390x/virtio-ccw.h
@@ -13,21 +13,21 @@
 #ifndef HW_S390X_VIRTIO_CCW_H
 #define HW_S390X_VIRTIO_CCW_H
 
-#include <hw/virtio/virtio-blk.h>
-#include <hw/virtio/virtio-net.h>
-#include <hw/virtio/virtio-serial.h>
-#include <hw/virtio/virtio-scsi.h>
+#include "hw/virtio/virtio-blk.h"
+#include "hw/virtio/virtio-net.h"
+#include "hw/virtio/virtio-serial.h"
+#include "hw/virtio/virtio-scsi.h"
 #ifdef CONFIG_VHOST_SCSI
-#include <hw/virtio/vhost-scsi.h>
+#include "hw/virtio/vhost-scsi.h"
 #endif
-#include <hw/virtio/virtio-balloon.h>
-#include <hw/virtio/virtio-rng.h>
-#include <hw/virtio/virtio-bus.h>
+#include "hw/virtio/virtio-balloon.h"
+#include "hw/virtio/virtio-rng.h"
+#include "hw/virtio/virtio-bus.h"
 
-#include <hw/s390x/s390_flic.h>
-#include <hw/s390x/css.h>
-
-#define VIRTUAL_CSSID 0xfe
+#include "hw/s390x/s390_flic.h"
+#include "hw/s390x/css.h"
+#include "ccw-device.h"
+#include "hw/s390x/css-bridge.h"
 
 #define VIRTIO_CCW_CU_TYPE 0x3832
 #define VIRTIO_CCW_CHPID_TYPE 0x32
@@ -67,7 +67,7 @@ typedef struct VirtioBusClass VirtioCcwBusClass;
 typedef struct VirtioCcwDevice VirtioCcwDevice;
 
 typedef struct VirtIOCCWDeviceClass {
-    DeviceClass parent_class;
+    CCWDeviceClass parent_class;
     void (*realize)(VirtioCcwDevice *dev, Error **errp);
     int (*exit)(VirtioCcwDevice *dev);
 } VirtIOCCWDeviceClass;
@@ -78,9 +78,7 @@ typedef struct VirtIOCCWDeviceClass {
 #define VIRTIO_CCW_FLAG_USE_IOEVENTFD   (1 << VIRTIO_CCW_FLAG_USE_IOEVENTFD_BIT)
 
 struct VirtioCcwDevice {
-    DeviceState parent_obj;
-    SubchDev *sch;
-    CssDevId bus_id;
+    CcwDevice parent_obj;
     int revision;
     uint32_t max_rev;
     VirtioBusState bus;
@@ -103,15 +101,6 @@ static inline int virtio_ccw_rev_max(VirtioCcwDevice *dev)
     return dev->max_rev;
 }
 
-/* virtual css bus type */
-typedef struct VirtualCssBus {
-    BusState parent_obj;
-} VirtualCssBus;
-
-#define TYPE_VIRTUAL_CSS_BUS "virtual-css-bus"
-#define VIRTUAL_CSS_BUS(obj) \
-     OBJECT_CHECK(VirtualCssBus, (obj), TYPE_VIRTUAL_CSS_BUS)
-
 /* virtio-scsi-ccw */
 
 #define TYPE_VIRTIO_SCSI_CCW "virtio-scsi-ccw"
@@ -191,7 +180,6 @@ typedef struct VirtIORNGCcw {
     VirtIORNG vdev;
 } VirtIORNGCcw;
 
-VirtualCssBus *virtual_css_bus_init(void);
 void virtio_ccw_device_update_status(SubchDev *sch);
 VirtIODevice *virtio_ccw_get_vdev(SubchDev *sch);
 
diff --git a/hw/scsi/mfi.h b/hw/scsi/mfi.h
index 29d41775d4..e67a5c0b47 100644
--- a/hw/scsi/mfi.h
+++ b/hw/scsi/mfi.h
@@ -30,8 +30,8 @@
  * SUCH DAMAGE.
  */
 
-#ifndef MFI_REG_H
-#define MFI_REG_H
+#ifndef SCSI_MFI_H
+#define SCSI_MFI_H
 
 /*
  * MegaRAID SAS MFI firmware definitions
@@ -1269,4 +1269,4 @@ struct mfi_config_data {
 #define MFI_SCSI_MAX_CMDS       8
 #define MFI_SCSI_MAX_CDB_LEN   16
 
-#endif /* MFI_REG_H */
+#endif /* SCSI_MFI_H */
diff --git a/hw/scsi/scsi-disk.c b/hw/scsi/scsi-disk.c
index 36f8a85a70..8dbfc10b78 100644
--- a/hw/scsi/scsi-disk.c
+++ b/hw/scsi/scsi-disk.c
@@ -2309,6 +2309,7 @@ static void scsi_realize(SCSIDevice *dev, Error **errp)
             return;
         }
     }
+    blkconf_apply_backend_options(&dev->conf);
 
     if (s->qdev.conf.discard_granularity == -1) {
         s->qdev.conf.discard_granularity =
@@ -2848,6 +2849,7 @@ static const TypeInfo scsi_disk_base_info = {
 
 #define DEFINE_SCSI_DISK_PROPERTIES()                                \
     DEFINE_BLOCK_PROPERTIES(SCSIDiskState, qdev.conf),               \
+    DEFINE_BLOCK_ERROR_PROPERTIES(SCSIDiskState, qdev.conf),         \
     DEFINE_PROP_STRING("ver", SCSIDiskState, version),               \
     DEFINE_PROP_STRING("serial", SCSIDiskState, serial),             \
     DEFINE_PROP_STRING("vendor", SCSIDiskState, vendor),             \
diff --git a/hw/scsi/vhost-scsi.c b/hw/scsi/vhost-scsi.c
index 2a00f2f3c8..5b2694615f 100644
--- a/hw/scsi/vhost-scsi.c
+++ b/hw/scsi/vhost-scsi.c
@@ -15,8 +15,9 @@
  */
 
 #include "qemu/osdep.h"
-#include "qapi/error.h"
+#include <linux/vhost.h>
 #include <sys/ioctl.h>
+#include "qapi/error.h"
 #include "qemu/error-report.h"
 #include "qemu/queue.h"
 #include "monitor/monitor.h"
@@ -27,7 +28,6 @@
 #include "hw/virtio/virtio-bus.h"
 #include "hw/virtio/virtio-access.h"
 #include "hw/fw-path-provider.h"
-#include "linux/vhost.h"
 #include "qemu/cutils.h"
 
 /* Features supported by host kernel. */
diff --git a/hw/scsi/virtio-scsi-dataplane.c b/hw/scsi/virtio-scsi-dataplane.c
index 18ced31493..b173b94949 100644
--- a/hw/scsi/virtio-scsi-dataplane.c
+++ b/hw/scsi/virtio-scsi-dataplane.c
@@ -15,9 +15,9 @@
 #include "hw/virtio/virtio-scsi.h"
 #include "qemu/error-report.h"
 #include "sysemu/block-backend.h"
-#include <hw/scsi/scsi.h>
-#include <block/scsi.h>
-#include <hw/virtio/virtio-bus.h>
+#include "hw/scsi/scsi.h"
+#include "block/scsi.h"
+#include "hw/virtio/virtio-bus.h"
 #include "hw/virtio/virtio-access.h"
 
 /* Context: QEMU global mutex held */
diff --git a/hw/scsi/virtio-scsi.c b/hw/scsi/virtio-scsi.c
index e8179d6616..722c93e5fc 100644
--- a/hw/scsi/virtio-scsi.c
+++ b/hw/scsi/virtio-scsi.c
@@ -20,9 +20,9 @@
 #include "qemu/error-report.h"
 #include "qemu/iov.h"
 #include "sysemu/block-backend.h"
-#include <hw/scsi/scsi.h>
-#include <block/scsi.h>
-#include <hw/virtio/virtio-bus.h>
+#include "hw/scsi/scsi.h"
+#include "block/scsi.h"
+#include "hw/virtio/virtio-bus.h"
 #include "hw/virtio/virtio-access.h"
 
 static inline int virtio_scsi_get_lun(uint8_t *lun)
diff --git a/hw/scsi/vmw_pvscsi.c b/hw/scsi/vmw_pvscsi.c
index da71c8c8a5..5116f4ad68 100644
--- a/hw/scsi/vmw_pvscsi.c
+++ b/hw/scsi/vmw_pvscsi.c
@@ -28,7 +28,7 @@
 #include "qemu/osdep.h"
 #include "qapi/error.h"
 #include "hw/scsi/scsi.h"
-#include <block/scsi.h>
+#include "block/scsi.h"
 #include "hw/pci/msi.h"
 #include "vmw_pvscsi.h"
 #include "trace.h"
diff --git a/hw/sh4/sh7750_regnames.h b/hw/sh4/sh7750_regnames.h
index 7463709b4c..e3ba88636f 100644
--- a/hw/sh4/sh7750_regnames.h
+++ b/hw/sh4/sh7750_regnames.h
@@ -1,6 +1,6 @@
-#ifndef _SH7750_REGNAMES_H
-#define _SH7750_REGNAMES_H
+#ifndef SH7750_REGNAMES_H
+#define SH7750_REGNAMES_H
 
 const char *regname(uint32_t addr);
 
-#endif				/* _SH7750_REGNAMES_H */
+#endif /* SH7750_REGNAMES_H */
diff --git a/hw/sh4/sh7750_regs.h b/hw/sh4/sh7750_regs.h
index 534aa48403..3e4554af31 100644
--- a/hw/sh4/sh7750_regs.h
+++ b/hw/sh4/sh7750_regs.h
@@ -16,8 +16,8 @@
  * @(#) sh7750_regs.h,v 1.2.4.1 2003/09/04 18:46:00 joel Exp
  */
 
-#ifndef __SH7750_REGS_H__
-#define __SH7750_REGS_H__
+#ifndef SH7750_REGS_H
+#define SH7750_REGS_H
 
 /*
  * All register has 2 addresses: in 0xff000000 - 0xffffffff (P4 address)  and
diff --git a/hw/timer/Makefile.objs b/hw/timer/Makefile.objs
index 003c14fa26..7ba8c23c75 100644
--- a/hw/timer/Makefile.objs
+++ b/hw/timer/Makefile.objs
@@ -26,6 +26,7 @@ obj-$(CONFIG_OMAP) += omap_synctimer.o
 obj-$(CONFIG_PXA2XX) += pxa2xx_timer.o
 obj-$(CONFIG_SH4) += sh_timer.o
 obj-$(CONFIG_DIGIC) += digic-timer.o
+obj-$(CONFIG_MIPS_CPS) += mips_gictimer.o
 
 obj-$(CONFIG_MC146818RTC) += mc146818rtc.o
 
diff --git a/hw/timer/mips_gictimer.c b/hw/timer/mips_gictimer.c
new file mode 100644
index 0000000000..3698889475
--- /dev/null
+++ b/hw/timer/mips_gictimer.c
@@ -0,0 +1,142 @@
+/*
+ * This file is subject to the terms and conditions of the GNU General Public
+ * License.  See the file "COPYING" in the main directory of this archive
+ * for more details.
+ *
+ * Copyright (C) 2016 Imagination Technologies
+ */
+
+#include "qemu/osdep.h"
+#include "hw/hw.h"
+#include "hw/sysbus.h"
+#include "qemu/timer.h"
+#include "hw/timer/mips_gictimer.h"
+
+#define TIMER_PERIOD 10 /* 10 ns period for 100 Mhz frequency */
+
+static void gic_vptimer_update(MIPSGICTimerState *gictimer,
+                                   uint32_t vp_index, uint64_t now)
+{
+    uint64_t next;
+    uint32_t wait;
+
+    wait = gictimer->vptimers[vp_index].comparelo - gictimer->sh_counterlo -
+           (uint32_t)(now / TIMER_PERIOD);
+    next = now + (uint64_t)wait * TIMER_PERIOD;
+
+    timer_mod(gictimer->vptimers[vp_index].qtimer, next);
+}
+
+static void gic_vptimer_expire(MIPSGICTimerState *gictimer, uint32_t vp_index,
+                               uint64_t now)
+{
+    if (gictimer->countstop) {
+        /* timer stopped */
+        return;
+    }
+    gictimer->cb(gictimer->opaque, vp_index);
+    gic_vptimer_update(gictimer, vp_index, now);
+}
+
+static void gic_vptimer_cb(void *opaque)
+{
+    MIPSGICTimerVPState *vptimer = opaque;
+    MIPSGICTimerState *gictimer = vptimer->gictimer;
+    gic_vptimer_expire(gictimer, vptimer->vp_index,
+                       qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL));
+}
+
+uint32_t mips_gictimer_get_sh_count(MIPSGICTimerState *gictimer)
+{
+    int i;
+    if (gictimer->countstop) {
+        return gictimer->sh_counterlo;
+    } else {
+        uint64_t now;
+        now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
+        for (i = 0; i < gictimer->num_vps; i++) {
+            if (timer_pending(gictimer->vptimers[i].qtimer)
+                && timer_expired(gictimer->vptimers[i].qtimer, now)) {
+                /* The timer has already expired.  */
+                gic_vptimer_expire(gictimer, i, now);
+            }
+        }
+        return gictimer->sh_counterlo + (uint32_t)(now / TIMER_PERIOD);
+    }
+}
+
+void mips_gictimer_store_sh_count(MIPSGICTimerState *gictimer, uint64_t count)
+{
+    int i;
+    uint64_t now;
+
+    if (gictimer->countstop || !gictimer->vptimers[0].qtimer) {
+        gictimer->sh_counterlo = count;
+    } else {
+        /* Store new count register */
+        now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
+        gictimer->sh_counterlo = count - (uint32_t)(now / TIMER_PERIOD);
+        /* Update timer timer */
+        for (i = 0; i < gictimer->num_vps; i++) {
+            gic_vptimer_update(gictimer, i, now);
+        }
+    }
+}
+
+uint32_t mips_gictimer_get_vp_compare(MIPSGICTimerState *gictimer,
+                                      uint32_t vp_index)
+{
+    return gictimer->vptimers[vp_index].comparelo;
+}
+
+void mips_gictimer_store_vp_compare(MIPSGICTimerState *gictimer,
+                                    uint32_t vp_index, uint64_t compare)
+{
+    gictimer->vptimers[vp_index].comparelo = (uint32_t) compare;
+    gic_vptimer_update(gictimer, vp_index,
+                       qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL));
+}
+
+uint8_t mips_gictimer_get_countstop(MIPSGICTimerState *gictimer)
+{
+    return gictimer->countstop;
+}
+
+void mips_gictimer_start_count(MIPSGICTimerState *gictimer)
+{
+    gictimer->countstop = 0;
+    mips_gictimer_store_sh_count(gictimer, gictimer->sh_counterlo);
+}
+
+void mips_gictimer_stop_count(MIPSGICTimerState *gictimer)
+{
+    int i;
+
+    gictimer->countstop = 1;
+    /* Store the current value */
+    gictimer->sh_counterlo +=
+        (uint32_t)(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / TIMER_PERIOD);
+    for (i = 0; i < gictimer->num_vps; i++) {
+        timer_del(gictimer->vptimers[i].qtimer);
+    }
+}
+
+MIPSGICTimerState *mips_gictimer_init(void *opaque, uint32_t nvps,
+                                      MIPSGICTimerCB *cb)
+{
+    int i;
+    MIPSGICTimerState *gictimer = g_new(MIPSGICTimerState, 1);
+    gictimer->vptimers = g_new(MIPSGICTimerVPState, nvps);
+    gictimer->countstop = 1;
+    gictimer->num_vps = nvps;
+    gictimer->opaque = opaque;
+    gictimer->cb = cb;
+    for (i = 0; i < nvps; i++) {
+        gictimer->vptimers[i].gictimer = gictimer;
+        gictimer->vptimers[i].vp_index = i;
+        gictimer->vptimers[i].qtimer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
+                                            &gic_vptimer_cb,
+                                            &gictimer->vptimers[i]);
+    }
+    return gictimer;
+}
diff --git a/hw/tpm/tpm_util.h b/hw/tpm/tpm_util.h
index e7f354a52d..df76245e6e 100644
--- a/hw/tpm/tpm_util.h
+++ b/hw/tpm/tpm_util.h
@@ -18,11 +18,12 @@
  * 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 TPM_TPM_UTILS_H
-#define TPM_TPM_UTILS_H
+
+#ifndef TPM_TPM_UTIL_H
+#define TPM_TPM_UTIL_H
 
 #include "sysemu/tpm_backend.h"
 
 int tpm_util_test_tpmdev(int tpm_fd, TPMVersion *tpm_version);
 
-#endif /* TPM_TPM_UTILS_H */
+#endif /* TPM_TPM_UTIL_H */
diff --git a/hw/usb/dev-storage.c b/hw/usb/dev-storage.c
index 4d605b8a6a..c607f7606d 100644
--- a/hw/usb/dev-storage.c
+++ b/hw/usb/dev-storage.c
@@ -603,16 +603,19 @@ static void usb_msd_realize_storage(USBDevice *dev, Error **errp)
 
     blkconf_serial(&s->conf, &dev->serial);
     blkconf_blocksizes(&s->conf);
+    blkconf_apply_backend_options(&s->conf);
 
     /*
      * 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
      * creates automatically.  But first it needs to detach from its
      * blockdev, or else scsi_bus_legacy_add_drive() dies when it
-     * attaches again.
+     * attaches again. We also need to take another reference so that
+     * blk_detach_dev() doesn't free blk while we still need it.
      *
      * The hack is probably a bad idea.
      */
+    blk_ref(blk);
     blk_detach_dev(blk, &s->dev.qdev);
     s->conf.blk = NULL;
 
@@ -623,6 +626,7 @@ static void usb_msd_realize_storage(USBDevice *dev, Error **errp)
     scsi_dev = scsi_bus_legacy_add_drive(&s->bus, blk, 0, !!s->removable,
                                          s->conf.bootindex, dev->serial,
                                          &err);
+    blk_unref(blk);
     if (!scsi_dev) {
         error_propagate(errp, err);
         return;
diff --git a/hw/usb/hcd-ehci.h b/hw/usb/hcd-ehci.h
index 30218423c8..3fd7038658 100644
--- a/hw/usb/hcd-ehci.h
+++ b/hw/usb/hcd-ehci.h
@@ -14,8 +14,9 @@
  * 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 HW_USB_EHCI_H
-#define HW_USB_EHCI_H 1
+
+#ifndef HW_USB_HCD_EHCI_H
+#define HW_USB_HCD_EHCI_H
 
 #include "hw/hw.h"
 #include "qemu/timer.h"
diff --git a/hw/usb/hcd-xhci.c b/hw/usb/hcd-xhci.c
index 1a3377f038..976bfb0659 100644
--- a/hw/usb/hcd-xhci.c
+++ b/hw/usb/hcd-xhci.c
@@ -2364,6 +2364,8 @@ static TRBCCode xhci_address_slot(XHCIState *xhci, unsigned int slotid,
     slot->uport = uport;
     slot->ctx = octx;
 
+    /* Make sure device is in USB_STATE_DEFAULT state */
+    usb_device_reset(dev);
     if (bsr) {
         slot_ctx[3] = SLOT_DEFAULT << SLOT_STATE_SHIFT;
     } else {
@@ -2371,7 +2373,6 @@ static TRBCCode xhci_address_slot(XHCIState *xhci, unsigned int slotid,
         uint8_t buf[1];
 
         slot_ctx[3] = (SLOT_ADDRESSED << SLOT_STATE_SHIFT) | slotid;
-        usb_device_reset(dev);
         memset(&p, 0, sizeof(p));
         usb_packet_addbuf(&p, buf, sizeof(buf));
         usb_packet_setup(&p, USB_TOKEN_OUT,
diff --git a/hw/usb/xen-usb.c b/hw/usb/xen-usb.c
index 0fd34c62c4..799245654a 100644
--- a/hw/usb/xen-usb.c
+++ b/hw/usb/xen-usb.c
@@ -21,6 +21,7 @@
 
 #include "qemu/osdep.h"
 #include <libusb.h>
+#include <sys/user.h>
 
 #include "qemu-common.h"
 #include "qemu/config-file.h"
@@ -31,7 +32,6 @@
 #include "qapi/qmp/qbool.h"
 #include "qapi/qmp/qint.h"
 #include "qapi/qmp/qstring.h"
-#include "sys/user.h"
 
 #include <xen/io/ring.h>
 #include <xen/io/usbif.h>
@@ -253,7 +253,8 @@ static int usbback_init_packet(struct usbback_req *usbback_req)
 
     case USBIF_PIPE_TYPE_CTRL:
         packet->parameter = *(uint64_t *)usbback_req->req.u.ctrl;
-        TR_REQ(xendev, "ctrl parameter: %lx, buflen: %x\n", packet->parameter,
+        TR_REQ(xendev, "ctrl parameter: %"PRIx64", buflen: %x\n",
+               packet->parameter,
                usbback_req->req.buffer_length);
         break;
 
diff --git a/hw/vfio/common.c b/hw/vfio/common.c
index f3c0522e7e..b313e7c2c6 100644
--- a/hw/vfio/common.c
+++ b/hw/vfio/common.c
@@ -20,6 +20,9 @@
 
 #include "qemu/osdep.h"
 #include <sys/ioctl.h>
+#ifdef CONFIG_KVM
+#include <linux/kvm.h>
+#endif
 #include <linux/vfio.h>
 
 #include "hw/vfio/vfio-common.h"
@@ -30,9 +33,6 @@
 #include "qemu/error-report.h"
 #include "qemu/range.h"
 #include "sysemu/kvm.h"
-#ifdef CONFIG_KVM
-#include "linux/kvm.h"
-#endif
 #include "trace.h"
 
 struct vfio_group_head vfio_group_list =
diff --git a/hw/virtio/vhost-backend.c b/hw/virtio/vhost-backend.c
index d62372e597..7681f152f3 100644
--- a/hw/virtio/vhost-backend.c
+++ b/hw/virtio/vhost-backend.c
@@ -9,12 +9,11 @@
  */
 
 #include "qemu/osdep.h"
+#include <linux/vhost.h>
+#include <sys/ioctl.h>
 #include "hw/virtio/vhost.h"
 #include "hw/virtio/vhost-backend.h"
 #include "qemu/error-report.h"
-#include "linux/vhost.h"
-
-#include <sys/ioctl.h>
 
 static int vhost_kernel_call(struct vhost_dev *dev, unsigned long int request,
                              void *arg)
diff --git a/hw/xen/xen-host-pci-device.h b/hw/xen/xen-host-pci-device.h
index 6acf36e13a..4d8d34ecb0 100644
--- a/hw/xen/xen-host-pci-device.h
+++ b/hw/xen/xen-host-pci-device.h
@@ -55,4 +55,4 @@ int xen_host_pci_set_block(XenHostPCIDevice *d, int pos, uint8_t *buf,
 
 int xen_host_pci_find_ext_cap_offset(XenHostPCIDevice *s, uint32_t cap);
 
-#endif /* !XEN_HOST_PCI_DEVICE_H_ */
+#endif /* XEN_HOST_PCI_DEVICE_H */
diff --git a/hw/xen/xen_pt.h b/hw/xen/xen_pt.h
index c2f8e1fc25..191d9caea1 100644
--- a/hw/xen/xen_pt.h
+++ b/hw/xen/xen_pt.h
@@ -332,4 +332,4 @@ int xen_pt_register_vga_regions(XenHostPCIDevice *dev);
 int xen_pt_unregister_vga_regions(XenHostPCIDevice *dev);
 void xen_pt_setup_vga(XenPCIPassthroughState *s, XenHostPCIDevice *dev,
                      Error **errp);
-#endif /* !XEN_PT_H */
+#endif /* XEN_PT_H */
diff --git a/hw/xenpv/xen_domainbuild.h b/hw/xenpv/xen_domainbuild.h
index 29a91ea7b1..652d9b410f 100644
--- a/hw/xenpv/xen_domainbuild.h
+++ b/hw/xenpv/xen_domainbuild.h
@@ -1,5 +1,5 @@
 #ifndef QEMU_HW_XEN_DOMAINBUILD_H
-#define QEMU_HW_XEN_DOMAINBUILD_H 1
+#define QEMU_HW_XEN_DOMAINBUILD_H
 
 #include "hw/xen/xen_common.h"
 
diff --git a/hw/xtensa/bootparam.h b/hw/xtensa/bootparam.h
index 955f4e86e3..ade7891ec5 100644
--- a/hw/xtensa/bootparam.h
+++ b/hw/xtensa/bootparam.h
@@ -1,5 +1,5 @@
-#ifndef HW_XTENSA_BOOTPARAM
-#define HW_XTENSA_BOOTPARAM
+#ifndef HW_XTENSA_BOOTPARAM_H
+#define HW_XTENSA_BOOTPARAM_H
 
 #define BP_TAG_COMMAND_LINE     0x1001  /* command line (0-terminated string)*/
 #define BP_TAG_INITRD           0x1002  /* ramdisk addr and size (bp_meminfo) */
diff --git a/include/block/block_int.h b/include/block/block_int.h
index 47b9aac71b..805414619d 100644
--- a/include/block/block_int.h
+++ b/include/block/block_int.h
@@ -639,11 +639,13 @@ int is_windows_drive(const char *filename);
 
 /**
  * stream_start:
+ * @job_id: The id of the newly-created job, or %NULL to use the
+ * device name of @bs.
  * @bs: Block device to operate on.
  * @base: Block device that will become the new base, or %NULL to
  * flatten the whole backing file chain onto @bs.
- * @base_id: The file name that will be written to @bs as the new
- * backing file if the job completes.  Ignored if @base is %NULL.
+ * @backing_file_str: The file name that will be written to @bs as the
+ * the new backing file if the job completes. Ignored if @base is %NULL.
  * @speed: The maximum speed, in bytes per second, or 0 for unlimited.
  * @on_error: The action to take upon error.
  * @cb: Completion function for the job.
@@ -654,15 +656,18 @@ int is_windows_drive(const char *filename);
  * in @bs, but allocated in any image between @base and @bs (both
  * exclusive) will be written to @bs.  At the end of a successful
  * streaming job, the backing file of @bs will be changed to
- * @base_id in the written image and to @base in the live BlockDriverState.
+ * @backing_file_str in the written image and to @base in the live
+ * BlockDriverState.
  */
-void stream_start(BlockDriverState *bs, BlockDriverState *base,
-                  const char *base_id, int64_t speed, BlockdevOnError on_error,
-                  BlockCompletionFunc *cb,
-                  void *opaque, Error **errp);
+void stream_start(const char *job_id, BlockDriverState *bs,
+                  BlockDriverState *base, const char *backing_file_str,
+                  int64_t speed, BlockdevOnError on_error,
+                  BlockCompletionFunc *cb, void *opaque, Error **errp);
 
 /**
  * commit_start:
+ * @job_id: The id of the newly-created job, or %NULL to use the
+ * device name of @bs.
  * @bs: Active block device.
  * @top: Top block device to be committed.
  * @base: Block device that will be written into, and become the new top.
@@ -674,12 +679,14 @@ void stream_start(BlockDriverState *bs, BlockDriverState *base,
  * @errp: Error object.
  *
  */
-void commit_start(BlockDriverState *bs, BlockDriverState *base,
-                 BlockDriverState *top, int64_t speed,
-                 BlockdevOnError on_error, BlockCompletionFunc *cb,
-                 void *opaque, const char *backing_file_str, Error **errp);
+void commit_start(const char *job_id, BlockDriverState *bs,
+                  BlockDriverState *base, BlockDriverState *top, int64_t speed,
+                  BlockdevOnError on_error, BlockCompletionFunc *cb,
+                  void *opaque, const char *backing_file_str, Error **errp);
 /**
  * commit_active_start:
+ * @job_id: The id of the newly-created job, or %NULL to use the
+ * device name of @bs.
  * @bs: Active block device to be committed.
  * @base: Block device that will be written into, and become the new top.
  * @speed: The maximum speed, in bytes per second, or 0 for unlimited.
@@ -689,13 +696,15 @@ void commit_start(BlockDriverState *bs, BlockDriverState *base,
  * @errp: Error object.
  *
  */
-void commit_active_start(BlockDriverState *bs, BlockDriverState *base,
-                         int64_t speed,
+void commit_active_start(const char *job_id, BlockDriverState *bs,
+                         BlockDriverState *base, int64_t speed,
                          BlockdevOnError on_error,
                          BlockCompletionFunc *cb,
                          void *opaque, Error **errp);
 /*
  * mirror_start:
+ * @job_id: The id of the newly-created job, or %NULL to use the
+ * device name of @bs.
  * @bs: Block device to operate on.
  * @target: Block device to write to.
  * @replaces: Block graph node name to replace once the mirror is done. Can
@@ -717,8 +726,8 @@ void commit_active_start(BlockDriverState *bs, BlockDriverState *base,
  * manually completed.  At the end of a successful mirroring job,
  * @bs will be switched to read from @target.
  */
-void mirror_start(BlockDriverState *bs, BlockDriverState *target,
-                  const char *replaces,
+void mirror_start(const char *job_id, BlockDriverState *bs,
+                  BlockDriverState *target, const char *replaces,
                   int64_t speed, uint32_t granularity, int64_t buf_size,
                   MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
                   BlockdevOnError on_source_error,
@@ -729,6 +738,8 @@ void mirror_start(BlockDriverState *bs, BlockDriverState *target,
 
 /*
  * backup_start:
+ * @job_id: The id of the newly-created job, or %NULL to use the
+ * device name of @bs.
  * @bs: Block device to operate on.
  * @target: Block device to write to.
  * @speed: The maximum speed, in bytes per second, or 0 for unlimited.
@@ -743,9 +754,9 @@ void mirror_start(BlockDriverState *bs, BlockDriverState *target,
  * Start a backup operation on @bs.  Clusters in @bs are written to @target
  * until the job is cancelled or manually completed.
  */
-void backup_start(BlockDriverState *bs, BlockDriverState *target,
-                  int64_t speed, MirrorSyncMode sync_mode,
-                  BdrvDirtyBitmap *sync_bitmap,
+void backup_start(const char *job_id, BlockDriverState *bs,
+                  BlockDriverState *target, int64_t speed,
+                  MirrorSyncMode sync_mode, BdrvDirtyBitmap *sync_bitmap,
                   BlockdevOnError on_source_error,
                   BlockdevOnError on_target_error,
                   BlockCompletionFunc *cb, void *opaque,
diff --git a/include/block/blockjob.h b/include/block/blockjob.h
index 7dc720c82b..4ddb4ae2e1 100644
--- a/include/block/blockjob.h
+++ b/include/block/blockjob.h
@@ -22,8 +22,9 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
+
 #ifndef BLOCKJOB_H
-#define BLOCKJOB_H 1
+#define BLOCKJOB_H
 
 #include "block/block.h"
 
@@ -106,10 +107,7 @@ struct BlockJob {
     BlockBackend *blk;
 
     /**
-     * The ID of the block job. Currently the BlockBackend name of the BDS
-     * owning the job at the time when the job is started.
-     *
-     * TODO Decouple block job IDs from BlockBackend names
+     * The ID of the block job.
      */
     char *id;
 
@@ -214,7 +212,19 @@ struct BlockJob {
 BlockJob *block_job_next(BlockJob *job);
 
 /**
+ * block_job_get:
+ * @id: The id of the block job.
+ *
+ * Get the block job identified by @id (which must not be %NULL).
+ *
+ * Returns the requested job, or %NULL if it doesn't exist.
+ */
+BlockJob *block_job_get(const char *id);
+
+/**
  * block_job_create:
+ * @job_id: The id of the newly-created job, or %NULL to have one
+ * generated automatically.
  * @job_type: The class object for the newly-created job.
  * @bs: The block
  * @speed: The maximum speed, in bytes per second, or 0 for unlimited.
@@ -231,9 +241,9 @@ BlockJob *block_job_next(BlockJob *job);
  * This function is not part of the public job interface; it should be
  * called from a wrapper that is specific to the job type.
  */
-void *block_job_create(const BlockJobDriver *driver, BlockDriverState *bs,
-                       int64_t speed, BlockCompletionFunc *cb,
-                       void *opaque, Error **errp);
+void *block_job_create(const char *job_id, const BlockJobDriver *driver,
+                       BlockDriverState *bs, int64_t speed,
+                       BlockCompletionFunc *cb, void *opaque, Error **errp);
 
 /**
  * block_job_sleep_ns:
diff --git a/include/block/scsi.h b/include/block/scsi.h
index 8b966d754c..cdf0a58a07 100644
--- a/include/block/scsi.h
+++ b/include/block/scsi.h
@@ -19,8 +19,9 @@
  * This header file contains public constants and structures used by
  * the scsi code for linux.
  */
-#ifndef HW_SCSI_DEFS_H
-#define HW_SCSI_DEFS_H 1
+
+#ifndef BLOCK_SCSI_H
+#define BLOCK_SCSI_H
 
 /*
  *      SCSI opcodes
diff --git a/include/block/thread-pool.h b/include/block/thread-pool.h
index 42eb5e8421..7dd7d730a0 100644
--- a/include/block/thread-pool.h
+++ b/include/block/thread-pool.h
@@ -16,7 +16,7 @@
  */
 
 #ifndef QEMU_THREAD_POOL_H
-#define QEMU_THREAD_POOL_H 1
+#define QEMU_THREAD_POOL_H
 
 #include "block/block.h"
 
diff --git a/include/crypto/afsplit.h b/include/crypto/afsplit.h
index 4cc4ca4b38..7dd21f0a67 100644
--- a/include/crypto/afsplit.h
+++ b/include/crypto/afsplit.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QCRYPTO_AFSPLIT_H__
-#define QCRYPTO_AFSPLIT_H__
+#ifndef QCRYPTO_AFSPLIT_H
+#define QCRYPTO_AFSPLIT_H
 
 #include "crypto/hash.h"
 
@@ -132,4 +132,4 @@ int qcrypto_afsplit_decode(QCryptoHashAlgorithm hash,
                            uint8_t *out,
                            Error **errp);
 
-#endif /* QCRYPTO_AFSPLIT_H__ */
+#endif /* QCRYPTO_AFSPLIT_H */
diff --git a/include/crypto/block.h b/include/crypto/block.h
index a21e11ff86..895521162c 100644
--- a/include/crypto/block.h
+++ b/include/crypto/block.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QCRYPTO_BLOCK_H__
-#define QCRYPTO_BLOCK_H__
+#ifndef QCRYPTO_BLOCK_H
+#define QCRYPTO_BLOCK_H
 
 #include "crypto/cipher.h"
 #include "crypto/ivgen.h"
@@ -229,4 +229,4 @@ uint64_t qcrypto_block_get_payload_offset(QCryptoBlock *block);
  */
 void qcrypto_block_free(QCryptoBlock *block);
 
-#endif /* QCRYPTO_BLOCK_H__ */
+#endif /* QCRYPTO_BLOCK_H */
diff --git a/include/crypto/cipher.h b/include/crypto/cipher.h
index d770c4835a..376654dcdd 100644
--- a/include/crypto/cipher.h
+++ b/include/crypto/cipher.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QCRYPTO_CIPHER_H__
-#define QCRYPTO_CIPHER_H__
+#ifndef QCRYPTO_CIPHER_H
+#define QCRYPTO_CIPHER_H
 
 #include "qapi-types.h"
 
@@ -230,4 +230,4 @@ int qcrypto_cipher_setiv(QCryptoCipher *cipher,
                          const uint8_t *iv, size_t niv,
                          Error **errp);
 
-#endif /* QCRYPTO_CIPHER_H__ */
+#endif /* QCRYPTO_CIPHER_H */
diff --git a/include/crypto/desrfb.h b/include/crypto/desrfb.h
index 773667ee79..7ca596c387 100644
--- a/include/crypto/desrfb.h
+++ b/include/crypto/desrfb.h
@@ -9,8 +9,9 @@
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  */
-#ifndef D3DES_H
-#define D3DES_H 1
+
+#ifndef QCRYPTO_DESRFB_H
+#define QCRYPTO_DESRFB_H
 
 /* d3des.h -
  *
diff --git a/include/crypto/hash.h b/include/crypto/hash.h
index f38caed669..ca3267f3df 100644
--- a/include/crypto/hash.h
+++ b/include/crypto/hash.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QCRYPTO_HASH_H__
-#define QCRYPTO_HASH_H__
+#ifndef QCRYPTO_HASH_H
+#define QCRYPTO_HASH_H
 
 #include "qapi-types.h"
 
@@ -189,4 +189,4 @@ int qcrypto_hash_base64(QCryptoHashAlgorithm alg,
                         char **base64,
                         Error **errp);
 
-#endif /* QCRYPTO_HASH_H__ */
+#endif /* QCRYPTO_HASH_H */
diff --git a/include/crypto/init.h b/include/crypto/init.h
index 2513ed0986..04c1edf770 100644
--- a/include/crypto/init.h
+++ b/include/crypto/init.h
@@ -18,9 +18,9 @@
  *
  */
 
-#ifndef QCRYPTO_INIT_H__
-#define QCRYPTO_INIT_H__
+#ifndef QCRYPTO_INIT_H
+#define QCRYPTO_INIT_H
 
 int qcrypto_init(Error **errp);
 
-#endif /* QCRYPTO_INIT_H__ */
+#endif /* QCRYPTO_INIT_H */
diff --git a/include/crypto/ivgen.h b/include/crypto/ivgen.h
index 09cdb6fcd9..0350cd2a93 100644
--- a/include/crypto/ivgen.h
+++ b/include/crypto/ivgen.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QCRYPTO_IVGEN_H__
-#define QCRYPTO_IVGEN_H__
+#ifndef QCRYPTO_IVGEN_H
+#define QCRYPTO_IVGEN_H
 
 #include "crypto/cipher.h"
 #include "crypto/hash.h"
@@ -203,4 +203,4 @@ QCryptoHashAlgorithm qcrypto_ivgen_get_hash(QCryptoIVGen *ivgen);
  */
 void qcrypto_ivgen_free(QCryptoIVGen *ivgen);
 
-#endif /* QCRYPTO_IVGEN_H__ */
+#endif /* QCRYPTO_IVGEN_H */
diff --git a/include/crypto/pbkdf.h b/include/crypto/pbkdf.h
index 58a1fe62a1..e9e4ceca83 100644
--- a/include/crypto/pbkdf.h
+++ b/include/crypto/pbkdf.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QCRYPTO_PBKDF_H__
-#define QCRYPTO_PBKDF_H__
+#ifndef QCRYPTO_PBKDF_H
+#define QCRYPTO_PBKDF_H
 
 #include "crypto/hash.h"
 
@@ -149,4 +149,4 @@ int qcrypto_pbkdf2_count_iters(QCryptoHashAlgorithm hash,
                                const uint8_t *salt, size_t nsalt,
                                Error **errp);
 
-#endif /* QCRYPTO_PBKDF_H__ */
+#endif /* QCRYPTO_PBKDF_H */
diff --git a/include/crypto/random.h b/include/crypto/random.h
index f9308f4647..a101353202 100644
--- a/include/crypto/random.h
+++ b/include/crypto/random.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QCRYPTO_RANDOM_H__
-#define QCRYPTO_RANDOM_H__
+#ifndef QCRYPTO_RANDOM_H
+#define QCRYPTO_RANDOM_H
 
 #include "qemu-common.h"
 #include "qapi/error.h"
@@ -41,4 +41,4 @@ int qcrypto_random_bytes(uint8_t *buf,
                          Error **errp);
 
 
-#endif /* QCRYPTO_RANDOM_H__ */
+#endif /* QCRYPTO_RANDOM_H */
diff --git a/include/crypto/secret.h b/include/crypto/secret.h
index b7392c6ba0..07a963e794 100644
--- a/include/crypto/secret.h
+++ b/include/crypto/secret.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QCRYPTO_SECRET_H__
-#define QCRYPTO_SECRET_H__
+#ifndef QCRYPTO_SECRET_H
+#define QCRYPTO_SECRET_H
 
 #include "qom/object.h"
 
@@ -143,4 +143,4 @@ extern char *qcrypto_secret_lookup_as_utf8(const char *secretid,
 extern char *qcrypto_secret_lookup_as_base64(const char *secretid,
                                              Error **errp);
 
-#endif /* QCRYPTO_SECRET_H__ */
+#endif /* QCRYPTO_SECRET_H */
diff --git a/include/crypto/tlscreds.h b/include/crypto/tlscreds.h
index 59e91875c1..ad47d88be7 100644
--- a/include/crypto/tlscreds.h
+++ b/include/crypto/tlscreds.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QCRYPTO_TLSCRED_H__
-#define QCRYPTO_TLSCRED_H__
+#ifndef QCRYPTO_TLSCREDS_H
+#define QCRYPTO_TLSCREDS_H
 
 #include "qom/object.h"
 
@@ -63,5 +63,4 @@ struct QCryptoTLSCredsClass {
 };
 
 
-#endif /* QCRYPTO_TLSCRED_H__ */
-
+#endif /* QCRYPTO_TLSCREDS_H */
diff --git a/include/crypto/tlscredsanon.h b/include/crypto/tlscredsanon.h
index d3976b84b9..4d6b7e4d29 100644
--- a/include/crypto/tlscredsanon.h
+++ b/include/crypto/tlscredsanon.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QCRYPTO_TLSCRED_ANON_H__
-#define QCRYPTO_TLSCRED_ANON_H__
+#ifndef QCRYPTO_TLSCREDSANON_H
+#define QCRYPTO_TLSCREDSANON_H
 
 #include "crypto/tlscreds.h"
 
@@ -108,5 +108,4 @@ struct QCryptoTLSCredsAnonClass {
 };
 
 
-#endif /* QCRYPTO_TLSCRED_H__ */
-
+#endif /* QCRYPTO_TLSCREDSANON_H */
diff --git a/include/crypto/tlscredsx509.h b/include/crypto/tlscredsx509.h
index 25796d7de4..66ad6a7486 100644
--- a/include/crypto/tlscredsx509.h
+++ b/include/crypto/tlscredsx509.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QCRYPTO_TLSCRED_X509_H__
-#define QCRYPTO_TLSCRED_X509_H__
+#ifndef QCRYPTO_TLSCREDSX509_H
+#define QCRYPTO_TLSCREDSX509_H
 
 #include "crypto/tlscreds.h"
 
@@ -110,5 +110,4 @@ struct QCryptoTLSCredsX509Class {
 };
 
 
-#endif /* QCRYPTO_TLSCRED_X509_H__ */
-
+#endif /* QCRYPTO_TLSCREDSX509_H */
diff --git a/include/crypto/tlssession.h b/include/crypto/tlssession.h
index c1bad9e4f0..1c7414e4ff 100644
--- a/include/crypto/tlssession.h
+++ b/include/crypto/tlssession.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QCRYPTO_TLS_SESSION_H__
-#define QCRYPTO_TLS_SESSION_H__
+#ifndef QCRYPTO_TLSSESSION_H
+#define QCRYPTO_TLSSESSION_H
 
 #include "crypto/tlscreds.h"
 
@@ -319,4 +319,4 @@ int qcrypto_tls_session_get_key_size(QCryptoTLSSession *sess,
  */
 char *qcrypto_tls_session_get_peer_name(QCryptoTLSSession *sess);
 
-#endif /* QCRYPTO_TLS_SESSION_H__ */
+#endif /* QCRYPTO_TLSSESSION_H */
diff --git a/include/crypto/xts.h b/include/crypto/xts.h
index c2924d8ba0..da32ab82b6 100644
--- a/include/crypto/xts.h
+++ b/include/crypto/xts.h
@@ -23,9 +23,8 @@
  *
  */
 
-
-#ifndef QCRYPTO_XTS_H_
-#define QCRYPTO_XTS_H_
+#ifndef QCRYPTO_XTS_H
+#define QCRYPTO_XTS_H
 
 #include "qemu-common.h"
 #include "qapi/error.h"
@@ -83,4 +82,4 @@ void xts_encrypt(const void *datactx,
                  const uint8_t *src);
 
 
-#endif /* QCRYPTO_XTS_H_ */
+#endif /* QCRYPTO_XTS_H */
diff --git a/include/disas/bfd.h b/include/disas/bfd.h
index a87b8a1eb9..64c9544ed7 100644
--- a/include/disas/bfd.h
+++ b/include/disas/bfd.h
@@ -6,8 +6,8 @@
    interface, for making instruction-processing programs more independent
    of the instruction set being processed.  */
 
-#ifndef DIS_ASM_H
-#define DIS_ASM_H
+#ifndef DISAS_BFD_H
+#define DISAS_BFD_H
 
 #include "qemu/fprintf-fn.h"
 
@@ -489,4 +489,4 @@ bfd_vma bfd_getl16 (const bfd_byte *addr);
 bfd_vma bfd_getb16 (const bfd_byte *addr);
 typedef bool bfd_boolean;
 
-#endif /* ! defined (DIS_ASM_H) */
+#endif /* DISAS_BFD_H */
diff --git a/include/disas/disas.h b/include/disas/disas.h
index 4930d78ac4..e549ca24a1 100644
--- a/include/disas/disas.h
+++ b/include/disas/disas.h
@@ -1,5 +1,5 @@
-#ifndef _QEMU_DISAS_H
-#define _QEMU_DISAS_H
+#ifndef QEMU_DISAS_H
+#define QEMU_DISAS_H
 
 #include "qemu-common.h"
 
@@ -42,4 +42,4 @@ struct syminfo {
 /* Filled in by elfload.c.  Simplistic, but will do for now. */
 extern struct syminfo *syminfos;
 
-#endif /* _QEMU_DISAS_H */
+#endif /* QEMU_DISAS_H */
diff --git a/include/elf.h b/include/elf.h
index 745739ab8c..1c2975dc82 100644
--- a/include/elf.h
+++ b/include/elf.h
@@ -1,6 +1,5 @@
-#ifndef _QEMU_ELF_H
-#define _QEMU_ELF_H
-
+#ifndef QEMU_ELF_H
+#define QEMU_ELF_H
 
 /* 32-bit ELF base types. */
 typedef uint32_t Elf32_Addr;
@@ -1573,4 +1572,4 @@ struct elf32_fdpic_loadmap {
 #endif /* ELF_CLASS */
 
 
-#endif /* _QEMU_ELF_H */
+#endif /* QEMU_ELF_H */
diff --git a/include/exec/address-spaces.h b/include/exec/address-spaces.h
index 3d12cddeec..db8bfa9a92 100644
--- a/include/exec/address-spaces.h
+++ b/include/exec/address-spaces.h
@@ -11,8 +11,8 @@
  *
  */
 
-#ifndef EXEC_MEMORY_H
-#define EXEC_MEMORY_H
+#ifndef EXEC_ADDRESS_SPACES_H
+#define EXEC_ADDRESS_SPACES_H
 
 /*
  * Internal interfaces between memory.c/exec.c/vl.c.  Do not #include unless
diff --git a/include/exec/cpu-common.h b/include/exec/cpu-common.h
index aaee995634..952bcfeb4c 100644
--- a/include/exec/cpu-common.h
+++ b/include/exec/cpu-common.h
@@ -1,5 +1,5 @@
 #ifndef CPU_COMMON_H
-#define CPU_COMMON_H 1
+#define CPU_COMMON_H
 
 /* CPU interfaces that are target independent.  */
 
@@ -23,12 +23,6 @@ typedef struct CPUListState {
     FILE *file;
 } CPUListState;
 
-typedef enum MMUAccessType {
-    MMU_DATA_LOAD  = 0,
-    MMU_DATA_STORE = 1,
-    MMU_INST_FETCH = 2
-} MMUAccessType;
-
 #if !defined(CONFIG_USER_ONLY)
 
 enum device_endian {
@@ -123,4 +117,4 @@ int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque);
 
 #endif
 
-#endif /* !CPU_COMMON_H */
+#endif /* CPU_COMMON_H */
diff --git a/include/exec/exec-all.h b/include/exec/exec-all.h
index c1f59fa59d..acda7b613d 100644
--- a/include/exec/exec-all.h
+++ b/include/exec/exec-all.h
@@ -17,8 +17,8 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 
-#ifndef _EXEC_ALL_H_
-#define _EXEC_ALL_H_
+#ifndef EXEC_ALL_H
+#define EXEC_ALL_H
 
 #include "qemu-common.h"
 #include "exec/tb-context.h"
@@ -361,8 +361,8 @@ extern uintptr_t tci_tb_ptr;
 struct MemoryRegion *iotlb_to_region(CPUState *cpu,
                                      hwaddr index, MemTxAttrs attrs);
 
-void tlb_fill(CPUState *cpu, target_ulong addr, int is_write, int mmu_idx,
-              uintptr_t retaddr);
+void tlb_fill(CPUState *cpu, target_ulong addr, MMUAccessType access_type,
+              int mmu_idx, uintptr_t retaddr);
 
 #endif
 
diff --git a/include/exec/gen-icount.h b/include/exec/gen-icount.h
index a011324b92..1af03d8f23 100644
--- a/include/exec/gen-icount.h
+++ b/include/exec/gen-icount.h
@@ -1,5 +1,5 @@
 #ifndef GEN_ICOUNT_H
-#define GEN_ICOUNT_H 1
+#define GEN_ICOUNT_H
 
 #include "qemu/timer.h"
 
diff --git a/include/exec/helper-gen.h b/include/exec/helper-gen.h
index 0d0da3aeb3..8239ffc77c 100644
--- a/include/exec/helper-gen.h
+++ b/include/exec/helper-gen.h
@@ -2,9 +2,9 @@
    This one expands generation functions for tcg opcodes.  */
 
 #ifndef HELPER_GEN_H
-#define HELPER_GEN_H 1
+#define HELPER_GEN_H
 
-#include <exec/helper-head.h>
+#include "exec/helper-head.h"
 
 #define DEF_HELPER_FLAGS_0(name, flags, ret)                            \
 static inline void glue(gen_helper_, name)(dh_retvar_decl0(ret))        \
diff --git a/include/exec/helper-head.h b/include/exec/helper-head.h
index 74f8f039d8..1cfc43b9ff 100644
--- a/include/exec/helper-head.h
+++ b/include/exec/helper-head.h
@@ -15,9 +15,8 @@
     GEN_HELPER 2 to do runtime registration helper functions.
  */
 
-#ifndef DEF_HELPER_H
-#define DEF_HELPER_H 1
-
+#ifndef EXEC_HELPER_HEAD_H
+#define EXEC_HELPER_HEAD_H
 
 #define HELPER(name) glue(helper_, name)
 
@@ -133,4 +132,4 @@
 
 /* MAX_OPC_PARAM_IARGS must be set to n if last entry is DEF_HELPER_FLAGS_n. */
 
-#endif /* DEF_HELPER_H */
+#endif /* EXEC_HELPER_HEAD_H */
diff --git a/include/exec/helper-proto.h b/include/exec/helper-proto.h
index effdd4383a..954bef85ce 100644
--- a/include/exec/helper-proto.h
+++ b/include/exec/helper-proto.h
@@ -2,9 +2,9 @@
    This one expands prototypes for the helper functions.  */
 
 #ifndef HELPER_PROTO_H
-#define HELPER_PROTO_H 1
+#define HELPER_PROTO_H
 
-#include <exec/helper-head.h>
+#include "exec/helper-head.h"
 
 #define DEF_HELPER_FLAGS_0(name, flags, ret) \
 dh_ctype(ret) HELPER(name) (void);
diff --git a/include/exec/helper-tcg.h b/include/exec/helper-tcg.h
index 79fa3c8c81..bb9287727c 100644
--- a/include/exec/helper-tcg.h
+++ b/include/exec/helper-tcg.h
@@ -2,9 +2,9 @@
    This one defines data structures private to tcg.c.  */
 
 #ifndef HELPER_TCG_H
-#define HELPER_TCG_H 1
+#define HELPER_TCG_H
 
-#include <exec/helper-head.h>
+#include "exec/helper-head.h"
 
 #define DEF_HELPER_FLAGS_0(NAME, FLAGS, ret) \
   { .func = HELPER(NAME), .name = #NAME, .flags = FLAGS, \
diff --git a/include/exec/softmmu-semi.h b/include/exec/softmmu-semi.h
index 3a58c3f087..7eefad8f39 100644
--- a/include/exec/softmmu-semi.h
+++ b/include/exec/softmmu-semi.h
@@ -6,8 +6,9 @@
  *
  * This code is licensed under the GPL
  */
+
 #ifndef SOFTMMU_SEMI_H
-#define SOFTMMU_SEMI_H 1
+#define SOFTMMU_SEMI_H
 
 static inline uint64_t softmmu_tget64(CPUArchState *env, target_ulong addr)
 {
diff --git a/include/exec/tb-context.h b/include/exec/tb-context.h
index e209c1c28c..dce95d92d6 100644
--- a/include/exec/tb-context.h
+++ b/include/exec/tb-context.h
@@ -17,8 +17,8 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 
-#ifndef QEMU_TB_CONTEXT_H_
-#define QEMU_TB_CONTEXT_H_
+#ifndef QEMU_TB_CONTEXT_H
+#define QEMU_TB_CONTEXT_H
 
 #include "qemu/thread.h"
 #include "qemu/qht.h"
diff --git a/include/exec/tb-hash-xx.h b/include/exec/tb-hash-xx.h
index 9f3fc05636..2c40b5c466 100644
--- a/include/exec/tb-hash-xx.h
+++ b/include/exec/tb-hash-xx.h
@@ -30,10 +30,11 @@
  * You can contact the author at :
  * - xxHash source repository : https://github.com/Cyan4973/xxHash
  */
-#ifndef EXEC_TB_HASH_XX
-#define EXEC_TB_HASH_XX
 
-#include <qemu/bitops.h>
+#ifndef EXEC_TB_HASH_XX_H
+#define EXEC_TB_HASH_XX_H
+
+#include "qemu/bitops.h"
 
 #define PRIME32_1   2654435761U
 #define PRIME32_2   2246822519U
@@ -91,4 +92,4 @@ uint32_t tb_hash_func5(uint64_t a0, uint64_t b0, uint32_t e)
     return h32;
 }
 
-#endif /* EXEC_TB_HASH_XX */
+#endif /* EXEC_TB_HASH_XX_H */
diff --git a/include/exec/tb-hash.h b/include/exec/tb-hash.h
index 1d0200bc91..2c27490cb8 100644
--- a/include/exec/tb-hash.h
+++ b/include/exec/tb-hash.h
@@ -17,8 +17,8 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 
-#ifndef EXEC_TB_HASH
-#define EXEC_TB_HASH
+#ifndef EXEC_TB_HASH_H
+#define EXEC_TB_HASH_H
 
 #include "exec/tb-hash-xx.h"
 
diff --git a/include/exec/user/abitypes.h b/include/exec/user/abitypes.h
index 80eedaccff..a09d6c64ff 100644
--- a/include/exec/user/abitypes.h
+++ b/include/exec/user/abitypes.h
@@ -1,5 +1,6 @@
-#ifndef QEMU_TYPES_H
-#define QEMU_TYPES_H
+#ifndef EXEC_USER_ABITYPES_H
+#define EXEC_USER_ABITYPES_H
+
 #include "cpu.h"
 
 #ifdef TARGET_ABI32
diff --git a/include/fpu/softfloat.h b/include/fpu/softfloat.h
index 95a11032d1..0e57ee53c0 100644
--- a/include/fpu/softfloat.h
+++ b/include/fpu/softfloat.h
@@ -751,4 +751,4 @@ static inline int float128_is_any_nan(float128 a)
 *----------------------------------------------------------------------------*/
 float128 float128_default_nan(float_status *status);
 
-#endif /* !SOFTFLOAT_H */
+#endif /* SOFTFLOAT_H */
diff --git a/include/hw/acpi/acpi.h b/include/hw/acpi/acpi.h
index c717f157fe..7b3d93cf0d 100644
--- a/include/hw/acpi/acpi.h
+++ b/include/hw/acpi/acpi.h
@@ -1,5 +1,6 @@
 #ifndef QEMU_HW_ACPI_H
 #define QEMU_HW_ACPI_H
+
 /*
  *  Copyright (c) 2009 Isaku Yamahata <yamahata at valinux co jp>
  *                     VA Linux Systems Japan K.K.
@@ -188,4 +189,4 @@ struct AcpiSlicOem {
 };
 int acpi_get_slic_oem(AcpiSlicOem *oem);
 
-#endif /* !QEMU_HW_ACPI_H */
+#endif /* QEMU_HW_ACPI_H */
diff --git a/include/hw/acpi/aml-build.h b/include/hw/acpi/aml-build.h
index e7a1a4cefd..e5f087803f 100644
--- a/include/hw/acpi/aml-build.h
+++ b/include/hw/acpi/aml-build.h
@@ -1,5 +1,5 @@
-#ifndef HW_ACPI_GEN_UTILS_H
-#define HW_ACPI_GEN_UTILS_H
+#ifndef HW_ACPI_AML_BUILD_H
+#define HW_ACPI_AML_BUILD_H
 
 #include "hw/acpi/acpi-defs.h"
 #include "hw/acpi/bios-linker-loader.h"
diff --git a/include/hw/acpi/cpu_hotplug.h b/include/hw/acpi/cpu_hotplug.h
index b995ef2ebd..3b932abbbb 100644
--- a/include/hw/acpi/cpu_hotplug.h
+++ b/include/hw/acpi/cpu_hotplug.h
@@ -9,8 +9,9 @@
  * 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 ACPI_HOTPLUG_H
-#define ACPI_HOTPLUG_H
+
+#ifndef HW_ACPI_CPU_HOTPLUG_H
+#define HW_ACPI_CPU_HOTPLUG_H
 
 #include "hw/acpi/acpi.h"
 #include "hw/acpi/pc-hotplug.h"
diff --git a/include/hw/arm/arm.h b/include/hw/arm/arm.h
index 8b49a9833f..aeeebfed90 100644
--- a/include/hw/arm/arm.h
+++ b/include/hw/arm/arm.h
@@ -8,8 +8,8 @@
  *
  */
 
-#ifndef ARM_MISC_H
-#define ARM_MISC_H 1
+#ifndef HW_ARM_H
+#define HW_ARM_H
 
 #include "exec/memory.h"
 #include "target-arm/cpu-qom.h"
@@ -140,4 +140,4 @@ void arm_write_secure_board_setup_dummy_smc(ARMCPU *cpu,
    ticks.  */
 extern int system_clock_scale;
 
-#endif /* !ARM_MISC_H */
+#endif /* HW_ARM_H */
diff --git a/include/hw/arm/exynos4210.h b/include/hw/arm/exynos4210.h
index b6d929ddb7..29fef8bfa1 100644
--- a/include/hw/arm/exynos4210.h
+++ b/include/hw/arm/exynos4210.h
@@ -22,9 +22,8 @@
  *
  */
 
-
-#ifndef EXYNOS4210_H_
-#define EXYNOS4210_H_
+#ifndef EXYNOS4210_H
+#define EXYNOS4210_H
 
 #include "qemu-common.h"
 #include "exec/memory.h"
@@ -135,4 +134,4 @@ DeviceState *exynos4210_uart_create(hwaddr addr,
                                     CharDriverState *chr,
                                     qemu_irq irq);
 
-#endif /* EXYNOS4210_H_ */
+#endif /* EXYNOS4210_H */
diff --git a/include/hw/arm/pxa.h b/include/hw/arm/pxa.h
index 074feacd03..dd1a48b0c1 100644
--- a/include/hw/arm/pxa.h
+++ b/include/hw/arm/pxa.h
@@ -6,8 +6,9 @@
  *
  * This code is licensed under the GNU GPL v2.
  */
+
 #ifndef PXA_H
-# define PXA_H			"pxa.h"
+#define PXA_H
 
 #include "exec/memory.h"
 #include "target-arm/cpu-qom.h"
@@ -189,4 +190,4 @@ PXA2xxState *pxa270_init(MemoryRegion *address_space, unsigned int sdram_size,
                          const char *revision);
 PXA2xxState *pxa255_init(MemoryRegion *address_space, unsigned int sdram_size);
 
-#endif	/* PXA_H */
+#endif /* PXA_H */
diff --git a/include/hw/arm/soc_dma.h b/include/hw/arm/soc_dma.h
index 7379731afd..fae322997e 100644
--- a/include/hw/arm/soc_dma.h
+++ b/include/hw/arm/soc_dma.h
@@ -19,8 +19,7 @@
  */
 
 #ifndef HW_SOC_DMA_H
-#define HW_SOC_DMA_H 1
-
+#define HW_SOC_DMA_H
 
 #include "exec/memory.h"
 #include "hw/irq.h"
diff --git a/include/hw/arm/stm32f205_soc.h b/include/hw/arm/stm32f205_soc.h
index 0390eff807..779b5da2dc 100644
--- a/include/hw/arm/stm32f205_soc.h
+++ b/include/hw/arm/stm32f205_soc.h
@@ -22,8 +22,8 @@
  * THE SOFTWARE.
  */
 
-#ifndef HW_ARM_STM32F205SOC_H
-#define HW_ARM_STM32F205SOC_H
+#ifndef HW_ARM_STM32F205_SOC_H
+#define HW_ARM_STM32F205_SOC_H
 
 #include "hw/misc/stm32f2xx_syscfg.h"
 #include "hw/timer/stm32f2xx_timer.h"
diff --git a/include/hw/audio/audio.h b/include/hw/audio/audio.h
index b28abdd3f7..55d40f71bf 100644
--- a/include/hw/audio/audio.h
+++ b/include/hw/audio/audio.h
@@ -1,5 +1,5 @@
-#ifndef HW_AUDIODEV_H
-#define HW_AUDIODEV_H 1
+#ifndef HW_AUDIO_H
+#define HW_AUDIO_H
 
 void isa_register_soundhw(const char *name, const char *descr,
                           int (*init_isa)(ISABus *bus));
diff --git a/include/hw/audio/pcspk.h b/include/hw/audio/pcspk.h
index 33e46a53d0..172afbf146 100644
--- a/include/hw/audio/pcspk.h
+++ b/include/hw/audio/pcspk.h
@@ -44,4 +44,4 @@ static inline ISADevice *pcspk_init(ISABus *bus, ISADevice *pit)
     return isadev;
 }
 
-#endif /* !HW_PCSPK_H */
+#endif /* HW_PCSPK_H */
diff --git a/include/hw/block/block.h b/include/hw/block/block.h
index 984660efd6..df9d207d81 100644
--- a/include/hw/block/block.h
+++ b/include/hw/block/block.h
@@ -8,8 +8,8 @@
  * later.  See the COPYING file in the top-level directory.
  */
 
-#ifndef HW_BLOCK_COMMON_H
-#define HW_BLOCK_COMMON_H
+#ifndef HW_BLOCK_H
+#define HW_BLOCK_H
 
 #include "qemu-common.h"
 
@@ -25,6 +25,9 @@ typedef struct BlockConf {
     uint32_t discard_granularity;
     /* geometry, not all devices use this */
     uint32_t cyls, heads, secs;
+    OnOffAuto wce;
+    BlockdevOnError rerror;
+    BlockdevOnError werror;
 } BlockConf;
 
 static inline unsigned int get_physical_block_exp(BlockConf *conf)
@@ -49,13 +52,20 @@ static inline unsigned int get_physical_block_exp(BlockConf *conf)
     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_UINT32("discard_granularity", _state, \
-                       _conf.discard_granularity, -1)
+                       _conf.discard_granularity, -1), \
+    DEFINE_PROP_ON_OFF_AUTO("write-cache", _state, _conf.wce, ON_OFF_AUTO_AUTO)
 
 #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)
 
+#define DEFINE_BLOCK_ERROR_PROPERTIES(_state, _conf)                    \
+    DEFINE_PROP_BLOCKDEV_ON_ERROR("rerror", _state, _conf.rerror,       \
+                                  BLOCKDEV_ON_ERROR_AUTO),              \
+    DEFINE_PROP_BLOCKDEV_ON_ERROR("werror", _state, _conf.werror,       \
+                                  BLOCKDEV_ON_ERROR_AUTO)
+
 /* Configuration helpers */
 
 void blkconf_serial(BlockConf *conf, char **serial);
@@ -63,6 +73,7 @@ void blkconf_geometry(BlockConf *conf, int *trans,
                       unsigned cyls_max, unsigned heads_max, unsigned secs_max,
                       Error **errp);
 void blkconf_blocksizes(BlockConf *conf);
+void blkconf_apply_backend_options(BlockConf *conf);
 
 /* Hard disk geometry */
 
diff --git a/include/hw/block/flash.h b/include/hw/block/flash.h
index a088baa4e4..67c3aa329e 100644
--- a/include/hw/block/flash.h
+++ b/include/hw/block/flash.h
@@ -1,5 +1,5 @@
 #ifndef HW_FLASH_H
-#define HW_FLASH_H 1
+#define HW_FLASH_H
 
 /* NOR flash devices */
 
diff --git a/include/hw/bt.h b/include/hw/bt.h
index c7c7909a37..185e79df2b 100644
--- a/include/hw/bt.h
+++ b/include/hw/bt.h
@@ -24,7 +24,7 @@
  */
 
 #ifndef HW_BT_H
-#define HW_BT_H 1
+#define HW_BT_H
 
 #include "hw/irq.h"
 
diff --git a/include/hw/char/escc.h b/include/hw/char/escc.h
index 2742d70ea0..297e2ebcda 100644
--- a/include/hw/char/escc.h
+++ b/include/hw/char/escc.h
@@ -1,5 +1,5 @@
 #ifndef HW_ESCC_H
-#define HW_ESCC_H 1
+#define HW_ESCC_H
 
 /* escc.c */
 #define TYPE_ESCC "escc"
diff --git a/include/hw/char/lm32_juart.h b/include/hw/char/lm32_juart.h
index 70dc416e9f..e7c6fb5a3b 100644
--- a/include/hw/char/lm32_juart.h
+++ b/include/hw/char/lm32_juart.h
@@ -10,4 +10,4 @@ uint32_t lm32_juart_get_jrx(DeviceState *d);
 void lm32_juart_set_jtx(DeviceState *d, uint32_t jtx);
 void lm32_juart_set_jrx(DeviceState *d, uint32_t jrx);
 
-#endif /* QEMU_HW_LM32_JUART_H */
+#endif /* QEMU_HW_CHAR_LM32_JUART_H */
diff --git a/include/hw/char/pl011.h b/include/hw/char/pl011.h
index 93bd7ee83e..0ca7c19410 100644
--- a/include/hw/char/pl011.h
+++ b/include/hw/char/pl011.h
@@ -12,8 +12,8 @@
  * this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-#ifndef PL011_UART_H
-#define PL011_UART_H
+#ifndef HW_PL011_H
+#define HW_PL011_H
 
 static inline DeviceState *pl011_create(hwaddr addr,
                                         qemu_irq irq,
diff --git a/include/hw/char/serial.h b/include/hw/char/serial.h
index 9feddc613c..a4fd3d559c 100644
--- a/include/hw/char/serial.h
+++ b/include/hw/char/serial.h
@@ -22,8 +22,9 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
+
 #ifndef HW_SERIAL_H
-#define HW_SERIAL_H 1
+#define HW_SERIAL_H
 
 #include "hw/hw.h"
 #include "sysemu/sysemu.h"
diff --git a/include/hw/cris/etraxfs.h b/include/hw/cris/etraxfs.h
index eb664181e7..723a2753c8 100644
--- a/include/hw/cris/etraxfs.h
+++ b/include/hw/cris/etraxfs.h
@@ -22,8 +22,8 @@
  * THE SOFTWARE.
  */
 
-#ifndef HW_EXTRAXFS_H
-#define HW_EXTRAXFS_H 1
+#ifndef HW_ETRAXFS_H
+#define HW_ETRAXFS_H
 
 #include "net/net.h"
 #include "hw/cris/etraxfs_dma.h"
diff --git a/include/hw/cris/etraxfs_dma.h b/include/hw/cris/etraxfs_dma.h
index 38104a67b5..f6f33e0980 100644
--- a/include/hw/cris/etraxfs_dma.h
+++ b/include/hw/cris/etraxfs_dma.h
@@ -1,5 +1,5 @@
 #ifndef HW_ETRAXFS_DMA_H
-#define HW_ETRAXFS_DMA_H 1
+#define HW_ETRAXFS_DMA_H
 
 struct dma_context_metadata {
 	/* data descriptor md */
diff --git a/include/hw/display/dpcd.h b/include/hw/display/dpcd.h
index 274dc2e42d..6880ee36a3 100644
--- a/include/hw/display/dpcd.h
+++ b/include/hw/display/dpcd.h
@@ -102,4 +102,4 @@ typedef struct DPCDState DPCDState;
 #define DPCD_SINK_STATUS                        0x205
 #define DPCD_RECEIVE_PORT_0_STATUS              0x01
 
-#endif /* !DPCD_H */
+#endif /* DPCD_H */
diff --git a/include/hw/dma/xlnx_dpdma.h b/include/hw/dma/xlnx_dpdma.h
index ae571a0b2f..664df28ae6 100644
--- a/include/hw/dma/xlnx_dpdma.h
+++ b/include/hw/dma/xlnx_dpdma.h
@@ -82,4 +82,4 @@ void xlnx_dpdma_set_host_data_location(XlnxDPDMAState *s, uint8_t channel,
  */
 void xlnx_dpdma_trigger_vsync_irq(XlnxDPDMAState *s);
 
-#endif /* !XLNX_DPDMA_H */
+#endif /* XLNX_DPDMA_H */
diff --git a/include/hw/empty_slot.h b/include/hw/empty_slot.h
index 6079602cdf..123a9f8989 100644
--- a/include/hw/empty_slot.h
+++ b/include/hw/empty_slot.h
@@ -1,5 +1,5 @@
 #ifndef HW_EMPTY_SLOT_H
-#define HW_EMPTY_SLOT_H 1
+#define HW_EMPTY_SLOT_H
 
 /* empty_slot.c */
 void empty_slot_init(hwaddr addr, uint64_t slot_size);
diff --git a/include/hw/fw-path-provider.h b/include/hw/fw-path-provider.h
index 7afaec0b1d..050cb05d92 100644
--- a/include/hw/fw-path-provider.h
+++ b/include/hw/fw-path-provider.h
@@ -16,7 +16,7 @@
  */
 
 #ifndef FW_PATH_PROVIDER_H
-#define FW_PATH_PROVIDER_H 1
+#define FW_PATH_PROVIDER_H
 
 #include "qemu-common.h"
 #include "qom/object.h"
diff --git a/include/hw/gpio/imx_gpio.h b/include/hw/gpio/imx_gpio.h
index b15a09fbca..ffab437f23 100644
--- a/include/hw/gpio/imx_gpio.h
+++ b/include/hw/gpio/imx_gpio.h
@@ -17,10 +17,10 @@
  * with this program; if not, see <http://www.gnu.org/licenses/>.
  */
 
-#ifndef __IMX_GPIO_H_
-#define __IMX_GPIO_H_
+#ifndef IMX_GPIO_H
+#define IMX_GPIO_H
 
-#include <hw/sysbus.h>
+#include "hw/sysbus.h"
 
 #define TYPE_IMX_GPIO "imx.gpio"
 #define IMX_GPIO(obj) OBJECT_CHECK(IMXGPIOState, (obj), TYPE_IMX_GPIO)
@@ -60,4 +60,4 @@ typedef struct IMXGPIOState {
     qemu_irq output[IMX_GPIO_PIN_COUNT];
 } IMXGPIOState;
 
-#endif /* __IMX_GPIO_H_ */
+#endif /* IMX_GPIO_H */
diff --git a/include/hw/i2c/i2c-ddc.h b/include/hw/i2c/i2c-ddc.h
index cb8e62d622..d9b5f33f58 100644
--- a/include/hw/i2c/i2c-ddc.h
+++ b/include/hw/i2c/i2c-ddc.h
@@ -16,8 +16,8 @@
  *  with this program; if not, see <http://www.gnu.org/licenses/>.
  */
 
-#ifndef I2C_DDC
-#define I2C_DDC
+#ifndef I2C_DDC_H
+#define I2C_DDC_H
 
 /* A simple I2C slave which just returns the contents of its EDID blob. */
 
@@ -35,4 +35,4 @@ typedef struct I2CDDCState I2CDDCState;
 #define TYPE_I2CDDC "i2c-ddc"
 #define I2CDDC(obj) OBJECT_CHECK(I2CDDCState, (obj), TYPE_I2CDDC)
 
-#endif /* !I2C_DDC */
+#endif /* I2C_DDC_H */
diff --git a/include/hw/i2c/imx_i2c.h b/include/hw/i2c/imx_i2c.h
index e2ee8eaee8..7c73a1fa28 100644
--- a/include/hw/i2c/imx_i2c.h
+++ b/include/hw/i2c/imx_i2c.h
@@ -18,10 +18,10 @@
  *
  */
 
-#ifndef __IMX_I2C_H_
-#define __IMX_I2C_H_
+#ifndef IMX_I2C_H
+#define IMX_I2C_H
 
-#include <hw/sysbus.h>
+#include "hw/sysbus.h"
 
 #define TYPE_IMX_I2C "imx.i2c"
 #define IMX_I2C(obj) OBJECT_CHECK(IMXI2CState, (obj), TYPE_IMX_I2C)
@@ -84,4 +84,4 @@ typedef struct IMXI2CState {
     uint16_t i2dr_write;
 } IMXI2CState;
 
-#endif /* __IMX_I2C_H_ */
+#endif /* IMX_I2C_H */
diff --git a/include/hw/i2c/pm_smbus.h b/include/hw/i2c/pm_smbus.h
index 926603fdff..2a837afdcb 100644
--- a/include/hw/i2c/pm_smbus.h
+++ b/include/hw/i2c/pm_smbus.h
@@ -17,4 +17,4 @@ typedef struct PMSMBus {
 
 void pm_smbus_init(DeviceState *parent, PMSMBus *smb);
 
-#endif /* !PM_SMBUS_H */
+#endif /* PM_SMBUS_H */
diff --git a/include/hw/i386/apic_internal.h b/include/hw/i386/apic_internal.h
index 74fe935e8e..73ce71674f 100644
--- a/include/hw/i386/apic_internal.h
+++ b/include/hw/i386/apic_internal.h
@@ -17,6 +17,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/>
  */
+
 #ifndef QEMU_APIC_INTERNAL_H
 #define QEMU_APIC_INTERNAL_H
 
@@ -222,4 +223,4 @@ static inline int apic_get_bit(uint32_t *tab, int index)
     return !!(tab[i] & mask);
 }
 
-#endif /* !QEMU_APIC_INTERNAL_H */
+#endif /* QEMU_APIC_INTERNAL_H */
diff --git a/include/hw/i386/ioapic.h b/include/hw/i386/ioapic.h
index 6245388c5d..9c8816f11f 100644
--- a/include/hw/i386/ioapic.h
+++ b/include/hw/i386/ioapic.h
@@ -25,4 +25,4 @@
 
 void ioapic_eoi_broadcast(int vector);
 
-#endif /* !HW_IOAPIC_H */
+#endif /* HW_IOAPIC_H */
diff --git a/include/hw/i386/ioapic_internal.h b/include/hw/i386/ioapic_internal.h
index cab9e67ee7..0542aa1131 100644
--- a/include/hw/i386/ioapic_internal.h
+++ b/include/hw/i386/ioapic_internal.h
@@ -112,4 +112,4 @@ void ioapic_reset_common(DeviceState *dev);
 
 void ioapic_print_redtbl(Monitor *mon, IOAPICCommonState *s);
 
-#endif /* !QEMU_IOAPIC_INTERNAL_H */
+#endif /* QEMU_IOAPIC_INTERNAL_H */
diff --git a/include/hw/ide/ahci.h b/include/hw/ide/ahci.h
index bc777ed5c2..0ca7c65820 100644
--- a/include/hw/ide/ahci.h
+++ b/include/hw/ide/ahci.h
@@ -24,7 +24,7 @@
 #ifndef HW_IDE_AHCI_H
 #define HW_IDE_AHCI_H
 
-#include <hw/sysbus.h>
+#include "hw/sysbus.h"
 
 #define AHCI_MEM_BAR_SIZE         0x1000
 #define AHCI_MAX_PORTS            32
diff --git a/include/hw/ide/internal.h b/include/hw/ide/internal.h
index 773928af77..7824bc34ce 100644
--- a/include/hw/ide/internal.h
+++ b/include/hw/ide/internal.h
@@ -6,8 +6,8 @@
  * only files in hw/ide/ are supposed to include this file.
  * non-internal declarations are in hw/ide.h
  */
-#include <hw/ide.h>
-#include <hw/isa/isa.h>
+#include "hw/ide.h"
+#include "hw/isa/isa.h"
 #include "sysemu/dma.h"
 #include "sysemu/sysemu.h"
 #include "hw/block/block.h"
diff --git a/include/hw/ide/pci.h b/include/hw/ide/pci.h
index 0f2d4b91a7..dbc6a0383d 100644
--- a/include/hw/ide/pci.h
+++ b/include/hw/ide/pci.h
@@ -1,7 +1,7 @@
 #ifndef HW_IDE_PCI_H
 #define HW_IDE_PCI_H
 
-#include <hw/ide/internal.h>
+#include "hw/ide/internal.h"
 
 #define BM_STATUS_DMAING 0x01
 #define BM_STATUS_ERROR  0x02
diff --git a/include/hw/input/adb.h b/include/hw/input/adb.h
index db51d03804..3ae8445e95 100644
--- a/include/hw/input/adb.h
+++ b/include/hw/input/adb.h
@@ -23,8 +23,8 @@
  * THE SOFTWARE.
  */
 
-#if !defined(__ADB_H__)
-#define __ADB_H__
+#ifndef ADB_H
+#define ADB_H
 
 #include "hw/qdev.h"
 
@@ -84,4 +84,4 @@ int adb_poll(ADBBusState *s, uint8_t *buf_out, uint16_t poll_mask);
 #define TYPE_ADB_KEYBOARD "adb-keyboard"
 #define TYPE_ADB_MOUSE "adb-mouse"
 
-#endif /* !defined(__ADB_H__) */
+#endif /* ADB_H */
diff --git a/include/hw/input/ps2.h b/include/hw/input/ps2.h
index 7c45ce7ced..b9ceee4154 100644
--- a/include/hw/input/ps2.h
+++ b/include/hw/input/ps2.h
@@ -35,4 +35,4 @@ void ps2_queue(void *, int b);
 void ps2_keyboard_set_translation(void *opaque, int mode);
 void ps2_mouse_fake_event(void *opaque);
 
-#endif /* !HW_PS2_H */
+#endif /* HW_PS2_H */
diff --git a/include/hw/intc/allwinner-a10-pic.h b/include/hw/intc/allwinner-a10-pic.h
index 5721b2e6b6..1d314a70d9 100644
--- a/include/hw/intc/allwinner-a10-pic.h
+++ b/include/hw/intc/allwinner-a10-pic.h
@@ -1,5 +1,5 @@
-#ifndef AW_A10_PIC_H
-#define AW_A10_PIC_H
+#ifndef ALLWINNER_A10_PIC_H
+#define ALLWINNER_A10_PIC_H
 
 #define TYPE_AW_A10_PIC  "allwinner-a10-pic"
 #define AW_A10_PIC(obj) OBJECT_CHECK(AwA10PICState, (obj), TYPE_AW_A10_PIC)
diff --git a/include/hw/intc/mips_gic.h b/include/hw/intc/mips_gic.h
new file mode 100644
index 0000000000..b98d50094a
--- /dev/null
+++ b/include/hw/intc/mips_gic.h
@@ -0,0 +1,216 @@
+/*
+ * This file is subject to the terms and conditions of the GNU General Public
+ * License.  See the file "COPYING" in the main directory of this archive
+ * for more details.
+ *
+ * Copyright (C) 2000, 07 MIPS Technologies, Inc.
+ * Copyright (C) 2016 Imagination Technologies
+ *
+ */
+
+#ifndef MIPS_GIC_H
+#define MIPS_GIC_H
+
+#include "hw/timer/mips_gictimer.h"
+#include "cpu.h"
+/*
+ * GIC Specific definitions
+ */
+
+/* The MIPS default location */
+#define GIC_BASE_ADDR           0x1bdc0000ULL
+#define GIC_ADDRSPACE_SZ        (128 * 1024)
+
+/* Constants */
+#define GIC_POL_POS     1
+#define GIC_POL_NEG     0
+#define GIC_TRIG_EDGE   1
+#define GIC_TRIG_LEVEL  0
+
+#define MSK(n)              ((1ULL << (n)) - 1)
+
+/* GIC Address Space */
+#define SHARED_SECTION_OFS          0x0000
+#define SHARED_SECTION_SIZE         0x8000
+#define VP_LOCAL_SECTION_OFS        0x8000
+#define VP_LOCAL_SECTION_SIZE       0x4000
+#define VP_OTHER_SECTION_OFS        0xc000
+#define VP_OTHER_SECTION_SIZE       0x4000
+#define USM_VISIBLE_SECTION_OFS     0x10000
+#define USM_VISIBLE_SECTION_SIZE    0x10000
+
+/* Register Map for Shared Section */
+
+#define GIC_SH_CONFIG_OFS           0x0000
+
+/* Shared Global Counter */
+#define GIC_SH_COUNTERLO_OFS        0x0010
+#define GIC_SH_COUNTERHI_OFS        0x0014
+#define GIC_SH_REVISIONID_OFS       0x0020
+
+/* Set/Clear corresponding bit in Edge Detect Register */
+#define GIC_SH_WEDGE_OFS            0x0280
+
+/* Reset Mask - Disables Interrupt */
+#define GIC_SH_RMASK_OFS            0x0300
+#define GIC_SH_RMASK_LAST_OFS       0x031c
+
+/* Set Mask (WO) - Enables Interrupt */
+#define GIC_SH_SMASK_OFS            0x0380
+#define GIC_SH_SMASK_LAST_OFS       0x039c
+
+/* Global Interrupt Mask Register (RO) - Bit Set == Interrupt enabled */
+#define GIC_SH_MASK_OFS             0x0400
+#define GIC_SH_MASK_LAST_OFS        0x041c
+
+/* Pending Global Interrupts (RO) */
+#define GIC_SH_PEND_OFS             0x0480
+#define GIC_SH_PEND_LAST_OFS        0x049c
+
+#define GIC_SH_MAP0_PIN_OFS         0x0500
+#define GIC_SH_MAP255_PIN_OFS       0x08fc
+
+#define GIC_SH_MAP0_VP_OFS          0x2000
+#define GIC_SH_MAP255_VP_LAST_OFS   0x3fe4
+
+/* Register Map for Local Section */
+#define GIC_VP_CTL_OFS              0x0000
+#define GIC_VP_PEND_OFS             0x0004
+#define GIC_VP_MASK_OFS             0x0008
+#define GIC_VP_RMASK_OFS            0x000c
+#define GIC_VP_SMASK_OFS            0x0010
+#define GIC_VP_WD_MAP_OFS           0x0040
+#define GIC_VP_COMPARE_MAP_OFS      0x0044
+#define GIC_VP_TIMER_MAP_OFS        0x0048
+#define GIC_VP_FDC_MAP_OFS          0x004c
+#define GIC_VP_PERFCTR_MAP_OFS      0x0050
+#define GIC_VP_SWINT0_MAP_OFS       0x0054
+#define GIC_VP_SWINT1_MAP_OFS       0x0058
+#define GIC_VP_OTHER_ADDR_OFS       0x0080
+#define GIC_VP_IDENT_OFS            0x0088
+#define GIC_VP_WD_CONFIG0_OFS       0x0090
+#define GIC_VP_WD_COUNT0_OFS        0x0094
+#define GIC_VP_WD_INITIAL0_OFS      0x0098
+#define GIC_VP_COMPARE_LO_OFS       0x00a0
+#define GIC_VP_COMPARE_HI_OFS       0x00a4
+#define GIC_VL_BRK_GROUP            0x3080
+
+/* User-Mode Visible Section Register */
+/* Read-only alias for GIC Shared CounterLo */
+#define GIC_USER_MODE_COUNTERLO     0x0000
+/* Read-only alias for GIC Shared CounterHi */
+#define GIC_USER_MODE_COUNTERHI     0x0004
+
+/* Masks */
+#define GIC_SH_CONFIG_COUNTSTOP_SHF     28
+#define GIC_SH_CONFIG_COUNTSTOP_MSK     (MSK(1) << GIC_SH_CONFIG_COUNTSTOP_SHF)
+#define GIC_SH_CONFIG_COUNTBITS_SHF     24
+#define GIC_SH_CONFIG_COUNTBITS_MSK     (MSK(4) << GIC_SH_CONFIG_COUNTBITS_SHF)
+#define GIC_SH_CONFIG_NUMINTRS_SHF      16
+#define GIC_SH_CONFIG_NUMINTRS_MSK      (MSK(8) << GIC_SH_CONFIG_NUMINTRS_SHF)
+#define GIC_SH_CONFIG_PVPS_SHF          0
+#define GIC_SH_CONFIG_PVPS_MSK          (MSK(8) << GIC_SH_CONFIG_NUMVPS_SHF)
+
+#define GIC_SH_WEDGE_RW_SHF             31
+#define GIC_SH_WEDGE_RW_MSK             (MSK(1) << GIC_SH_WEDGE_RW_SHF)
+
+#define GIC_MAP_TO_PIN_SHF              31
+#define GIC_MAP_TO_PIN_MSK              (MSK(1) << GIC_MAP_TO_PIN_SHF)
+#define GIC_MAP_TO_NMI_SHF              30
+#define GIC_MAP_TO_NMI_MSK              (MSK(1) << GIC_MAP_TO_NMI_SHF)
+#define GIC_MAP_TO_YQ_SHF               29
+#define GIC_MAP_TO_YQ_MSK               (MSK(1) << GIC_MAP_TO_YQ_SHF)
+#define GIC_MAP_SHF                     0
+#define GIC_MAP_MSK                     (MSK(6) << GIC_MAP_SHF)
+#define GIC_MAP_TO_PIN_REG_MSK          \
+    (GIC_MAP_TO_PIN_MSK | GIC_MAP_TO_NMI_MSK | GIC_MAP_TO_YQ_MSK | GIC_MAP_MSK)
+
+/* GIC_VP_CTL Masks */
+#define GIC_VP_CTL_FDC_RTBL_SHF         4
+#define GIC_VP_CTL_FDC_RTBL_MSK         (MSK(1) << GIC_VP_CTL_FDC_RTBL_SHF)
+#define GIC_VP_CTL_SWINT_RTBL_SHF       3
+#define GIC_VP_CTL_SWINT_RTBL_MSK       (MSK(1) << GIC_VP_CTL_SWINT_RTBL_SHF)
+#define GIC_VP_CTL_PERFCNT_RTBL_SHF     2
+#define GIC_VP_CTL_PERFCNT_RTBL_MSK     (MSK(1) << GIC_VP_CTL_PERFCNT_RTBL_SHF)
+#define GIC_VP_CTL_TIMER_RTBL_SHF       1
+#define GIC_VP_CTL_TIMER_RTBL_MSK       (MSK(1) << GIC_VP_CTL_TIMER_RTBL_SHF)
+#define GIC_VP_CTL_EIC_MODE_SHF         0
+#define GIC_VP_CTL_EIC_MODE_MSK         (MSK(1) << GIC_VP_CTL_EIC_MODE_SHF)
+
+/* GIC_VP_MASK Masks */
+#define GIC_VP_MASK_FDC_SHF         6
+#define GIC_VP_MASK_FDC_MSK         (MSK(1) << GIC_VP_MASK_FDC_SHF)
+#define GIC_VP_MASK_SWINT1_SHF      5
+#define GIC_VP_MASK_SWINT1_MSK      (MSK(1) << GIC_VP_MASK_SWINT1_SHF)
+#define GIC_VP_MASK_SWINT0_SHF      4
+#define GIC_VP_MASK_SWINT0_MSK      (MSK(1) << GIC_VP_MASK_SWINT0_SHF)
+#define GIC_VP_MASK_PERFCNT_SHF     3
+#define GIC_VP_MASK_PERFCNT_MSK     (MSK(1) << GIC_VP_MASK_PERFCNT_SHF)
+#define GIC_VP_MASK_TIMER_SHF       2
+#define GIC_VP_MASK_TIMER_MSK       (MSK(1) << GIC_VP_MASK_TIMER_SHF)
+#define GIC_VP_MASK_CMP_SHF         1
+#define GIC_VP_MASK_CMP_MSK         (MSK(1) << GIC_VP_MASK_CMP_SHF)
+#define GIC_VP_MASK_WD_SHF          0
+#define GIC_VP_MASK_WD_MSK          (MSK(1) << GIC_VP_MASK_WD_SHF)
+#define GIC_VP_SET_RESET_MSK        (MSK(7) << GIC_VP_MASK_WD_SHF)
+
+#define GIC_CPU_INT_MAX             5 /* Core Interrupt 7 */
+#define GIC_CPU_PIN_OFFSET          2
+
+/* Local GIC interrupts. */
+#define GIC_NUM_LOCAL_INTRS     7
+#define GIC_LOCAL_INT_FDC       6 /* CPU fast debug channel */
+#define GIC_LOCAL_INT_SWINT1    5 /* CPU software interrupt 1 */
+#define GIC_LOCAL_INT_SWINT0    4 /* CPU software interrupt 0 */
+#define GIC_LOCAL_INT_PERFCTR   3 /* CPU performance counter */
+#define GIC_LOCAL_INT_TIMER     2 /* CPU timer interrupt */
+#define GIC_LOCAL_INT_COMPARE   1 /* GIC count and compare timer */
+#define GIC_LOCAL_INT_WD        0 /* GIC watchdog */
+
+#define TYPE_MIPS_GIC "mips-gic"
+#define MIPS_GIC(obj) OBJECT_CHECK(MIPSGICState, (obj), TYPE_MIPS_GIC)
+
+/* Support up to 32 VPs and 256 IRQs */
+#define GIC_MAX_VPS             32
+#define GIC_MAX_INTRS           256
+
+typedef struct MIPSGICState MIPSGICState;
+typedef struct MIPSGICIRQState MIPSGICIRQState;
+typedef struct MIPSGICVPState MIPSGICVPState;
+
+struct MIPSGICIRQState {
+    uint8_t enabled;
+    uint8_t pending;
+    uint32_t map_pin;
+    int32_t map_vp;
+    qemu_irq irq;
+};
+
+struct MIPSGICVPState {
+    uint32_t ctl;
+    uint32_t pend;
+    uint32_t mask;
+    uint32_t compare_map;
+    uint32_t other_addr;
+    CPUMIPSState *env;
+};
+
+struct MIPSGICState {
+    SysBusDevice parent_obj;
+    MemoryRegion mr;
+
+    /* Shared Section Registers */
+    uint32_t sh_config;
+    MIPSGICIRQState *irq_state;
+
+    /* VP Local/Other Section Registers */
+    MIPSGICVPState *vps;
+
+    /* GIC VP Timer */
+    MIPSGICTimerState *gic_timer;
+
+    int32_t num_vps;
+    int32_t num_irq;
+};
+
+#endif /* MIPS_GIC_H */
diff --git a/include/hw/isa/i8257.h b/include/hw/isa/i8257.h
index 8c44d36282..aa211c0df7 100644
--- a/include/hw/isa/i8257.h
+++ b/include/hw/isa/i8257.h
@@ -39,4 +39,3 @@ typedef struct I8257State {
 } I8257State;
 
 #endif
-
diff --git a/include/hw/isa/i8259_internal.h b/include/hw/isa/i8259_internal.h
index cded509636..6954b6ec5f 100644
--- a/include/hw/isa/i8259_internal.h
+++ b/include/hw/isa/i8259_internal.h
@@ -80,4 +80,4 @@ void pic_reset_common(PICCommonState *s);
 ISADevice *i8259_init_chip(const char *name, ISABus *bus, bool master);
 
 
-#endif /* !QEMU_I8259_INTERNAL_H */
+#endif /* QEMU_I8259_INTERNAL_H */
diff --git a/include/hw/mips/cps.h b/include/hw/mips/cps.h
index 4dbae9c8c9..526b8d0b11 100644
--- a/include/hw/mips/cps.h
+++ b/include/hw/mips/cps.h
@@ -22,6 +22,7 @@
 
 #include "hw/sysbus.h"
 #include "hw/misc/mips_cmgcr.h"
+#include "hw/intc/mips_gic.h"
 #include "hw/misc/mips_cpc.h"
 #include "hw/misc/mips_itu.h"
 
@@ -37,6 +38,7 @@ typedef struct MIPSCPSState {
 
     MemoryRegion container;
     MIPSGCRState gcr;
+    MIPSGICState gic;
     MIPSCPCState cpc;
     MIPSITUState itu;
 } MIPSCPSState;
diff --git a/include/hw/misc/arm_integrator_debug.h b/include/hw/misc/arm_integrator_debug.h
index 37789b69d9..0077dacb44 100644
--- a/include/hw/misc/arm_integrator_debug.h
+++ b/include/hw/misc/arm_integrator_debug.h
@@ -10,8 +10,9 @@
  * 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_INTEGRATOR_DEBUG_H
-#define QEMU_INTEGRATOR_DEBUG_H
+
+#ifndef ARM_INTEGRATOR_DEBUG_H
+#define ARM_INTEGRATOR_DEBUG_H
 
 #define TYPE_INTEGRATOR_DEBUG "integrator_debug"
 
diff --git a/include/hw/misc/auxbus.h b/include/hw/misc/auxbus.h
index af39db7d79..68ade8a90f 100644
--- a/include/hw/misc/auxbus.h
+++ b/include/hw/misc/auxbus.h
@@ -22,8 +22,8 @@
  *
  */
 
-#ifndef QEMU_AUX_H
-#define QEMU_AUX_H
+#ifndef HW_MISC_AUXBUS_H
+#define HW_MISC_AUXBUS_H
 
 #include "hw/qdev.h"
 
@@ -125,4 +125,4 @@ void aux_init_mmio(AUXSlave *aux_slave, MemoryRegion *mmio);
 
 DeviceState *aux_create_slave(AUXBus *bus, const char *name, uint32_t addr);
 
-#endif /* !QEMU_AUX_H */
+#endif /* HW_MISC_AUXBUS_H */
diff --git a/include/hw/misc/mips_cmgcr.h b/include/hw/misc/mips_cmgcr.h
index cc60eefa53..a209d91ded 100644
--- a/include/hw/misc/mips_cmgcr.h
+++ b/include/hw/misc/mips_cmgcr.h
@@ -7,8 +7,8 @@
  *
  */
 
-#ifndef _MIPS_GCR_H
-#define _MIPS_GCR_H
+#ifndef MIPS_CMGCR_H
+#define MIPS_CMGCR_H
 
 #define TYPE_MIPS_GCR "mips-gcr"
 #define MIPS_GCR(obj) OBJECT_CHECK(MIPSGCRState, (obj), TYPE_MIPS_GCR)
@@ -26,23 +26,45 @@
 #define GCR_CONFIG_OFS      0x0000
 #define GCR_BASE_OFS        0x0008
 #define GCR_REV_OFS         0x0030
+#define GCR_GIC_BASE_OFS    0x0080
 #define GCR_CPC_BASE_OFS    0x0088
+#define GCR_GIC_STATUS_OFS  0x00D0
 #define GCR_CPC_STATUS_OFS  0x00F0
 #define GCR_L2_CONFIG_OFS   0x0130
 
 /* Core Local and Core Other Block Register Map */
 #define GCR_CL_CONFIG_OFS   0x0010
 #define GCR_CL_OTHER_OFS    0x0018
+#define GCR_CL_RESETBASE_OFS 0x0020
 
 /* GCR_L2_CONFIG register fields */
 #define GCR_L2_CONFIG_BYPASS_SHF    20
 #define GCR_L2_CONFIG_BYPASS_MSK    ((0x1ULL) << GCR_L2_CONFIG_BYPASS_SHF)
 
+/* GCR_GIC_BASE register fields */
+#define GCR_GIC_BASE_GICEN_MSK   1
+#define GCR_GIC_BASE_GICBASE_MSK 0xFFFFFFFE0000ULL
+#define GCR_GIC_BASE_MSK (GCR_GIC_BASE_GICEN_MSK | GCR_GIC_BASE_GICBASE_MSK)
+
 /* GCR_CPC_BASE register fields */
 #define GCR_CPC_BASE_CPCEN_MSK   1
 #define GCR_CPC_BASE_CPCBASE_MSK 0xFFFFFFFF8000ULL
 #define GCR_CPC_BASE_MSK (GCR_CPC_BASE_CPCEN_MSK | GCR_CPC_BASE_CPCBASE_MSK)
 
+/* GCR_CL_OTHER_OFS register fields */
+#define GCR_CL_OTHER_VPOTHER_MSK 0x7
+#define GCR_CL_OTHER_MSK GCR_CL_OTHER_VPOTHER_MSK
+
+/* GCR_CL_RESETBASE_OFS register fields */
+#define GCR_CL_RESET_BASE_RESETBASE_MSK 0xFFFFF000U
+#define GCR_CL_RESET_BASE_MSK GCR_CL_RESET_BASE_RESETBASE_MSK
+
+typedef struct MIPSGCRVPState MIPSGCRVPState;
+struct MIPSGCRVPState {
+    uint32_t other;
+    uint64_t reset_base;
+};
+
 typedef struct MIPSGCRState MIPSGCRState;
 struct MIPSGCRState {
     SysBusDevice parent_obj;
@@ -52,8 +74,13 @@ struct MIPSGCRState {
     hwaddr gcr_base;
     MemoryRegion iomem;
     MemoryRegion *cpc_mr;
+    MemoryRegion *gic_mr;
 
     uint64_t cpc_base;
+    uint64_t gic_base;
+
+    /* VP Local/Other Registers */
+    MIPSGCRVPState *vps;
 };
 
-#endif /* _MIPS_GCR_H */
+#endif /* MIPS_CMGCR_H */
diff --git a/include/hw/misc/tmp105_regs.h b/include/hw/misc/tmp105_regs.h
index 9b55abaf90..ef015ee5cf 100644
--- a/include/hw/misc/tmp105_regs.h
+++ b/include/hw/misc/tmp105_regs.h
@@ -11,8 +11,9 @@
  * 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_TMP105_MSGS_H
-#define QEMU_TMP105_MSGS_H
+
+#ifndef TMP105_REGS_H
+#define TMP105_REGS_H
 
 /**
  * TMP105Reg:
diff --git a/include/hw/net/allwinner_emac.h b/include/hw/net/allwinner_emac.h
index 9f21aa7e45..4cc8aab7ec 100644
--- a/include/hw/net/allwinner_emac.h
+++ b/include/hw/net/allwinner_emac.h
@@ -19,8 +19,9 @@
  * GNU General Public License for more details.
  *
  */
-#ifndef AW_EMAC_H
-#define AW_EMAC_H
+
+#ifndef ALLWINNER_EMAC_H
+#define ALLWINNER_EMAC_H
 
 #include "net/net.h"
 #include "qemu/fifo8.h"
diff --git a/include/hw/nmi.h b/include/hw/nmi.h
index b541772e1d..d092c684a1 100644
--- a/include/hw/nmi.h
+++ b/include/hw/nmi.h
@@ -20,7 +20,7 @@
  */
 
 #ifndef NMI_H
-#define NMI_H 1
+#define NMI_H
 
 #include "qemu-common.h"
 #include "qom/object.h"
diff --git a/include/hw/nvram/openbios_firmware_abi.h b/include/hw/nvram/openbios_firmware_abi.h
index c66ee22685..74cfd56180 100644
--- a/include/hw/nvram/openbios_firmware_abi.h
+++ b/include/hw/nvram/openbios_firmware_abi.h
@@ -1,5 +1,5 @@
-#ifndef FIRMWARE_ABI_H
-#define FIRMWARE_ABI_H
+#ifndef OPENBIOS_FIRMWARE_ABI_H
+#define OPENBIOS_FIRMWARE_ABI_H
 
 /* OpenBIOS NVRAM partition */
 struct OpenBIOS_nvpart_v1 {
@@ -72,4 +72,4 @@ Sun_init_header(struct Sun_nvram *header, const uint8_t *macaddr, int machine_id
 
     header->checksum = tmp;
 }
-#endif /* FIRMWARE_ABI_H */
+#endif /* OPENBIOS_FIRMWARE_ABI_H */
diff --git a/include/hw/pci-host/apb.h b/include/hw/pci-host/apb.h
index 736db6118e..b19bd55c40 100644
--- a/include/hw/pci-host/apb.h
+++ b/include/hw/pci-host/apb.h
@@ -1,5 +1,5 @@
-#ifndef APB_PCI_H
-#define APB_PCI_H
+#ifndef PCI_HOST_APB_H
+#define PCI_HOST_APB_H
 
 #include "qemu-common.h"
 
diff --git a/include/hw/pci-host/ppce500.h b/include/hw/pci-host/ppce500.h
index 61f773ef30..e3a374230b 100644
--- a/include/hw/pci-host/ppce500.h
+++ b/include/hw/pci-host/ppce500.h
@@ -1,5 +1,5 @@
-#ifndef PPCE500_PCI_H
-#define PPCE500_PCI_H
+#ifndef PCI_HOST_PPCE500_H
+#define PCI_HOST_PPCE500_H
 
 static inline int ppce500_pci_map_irq_slot(int devno, int irq_num)
 {
diff --git a/include/hw/pci-host/spapr.h b/include/hw/pci-host/spapr.h
index 193631d2dc..5adc603d47 100644
--- a/include/hw/pci-host/spapr.h
+++ b/include/hw/pci-host/spapr.h
@@ -16,13 +16,11 @@
  * 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/>.
  */
-#if !defined(__HW_SPAPR_H__)
-#error Please include spapr.h before this file!
-#endif
 
-#if !defined(__HW_SPAPR_PCI_H__)
-#define __HW_SPAPR_PCI_H__
+#ifndef PCI_HOST_SPAPR_H
+#define PCI_HOST_SPAPR_H
 
+#include "hw/ppc/spapr.h"
 #include "hw/pci/pci.h"
 #include "hw/pci/pci_host.h"
 #include "hw/ppc/xics.h"
@@ -155,4 +153,4 @@ static inline void spapr_phb_vfio_reset(DeviceState *qdev)
 
 void spapr_phb_dma_reset(sPAPRPHBState *sphb);
 
-#endif /* __HW_SPAPR_PCI_H__ */
+#endif /* PCI_HOST_SPAPR_H */
diff --git a/include/hw/pci/pci_bridge.h b/include/hw/pci/pci_bridge.h
index ed4aff6cd2..847fd7db33 100644
--- a/include/hw/pci/pci_bridge.h
+++ b/include/hw/pci/pci_bridge.h
@@ -67,4 +67,4 @@ void pci_bridge_map_irq(PCIBridge *br, const char* bus_name,
 #define  PCI_BRIDGE_CTL_DISCARD_STATUS	0x400	/* Discard timer status */
 #define  PCI_BRIDGE_CTL_DISCARD_SERR	0x800	/* Discard timer SERR# enable */
 
-#endif  /* QEMU_PCI_BRIDGE_H */
+#endif /* QEMU_PCI_BRIDGE_H */
diff --git a/include/hw/pci/pci_ids.h b/include/hw/pci/pci_ids.h
index db85afa03e..d77ca60a0e 100644
--- a/include/hw/pci/pci_ids.h
+++ b/include/hw/pci/pci_ids.h
@@ -7,8 +7,9 @@
  *
  *      QEMU-specific definitions belong in pci.h
  */
+
 #ifndef HW_PCI_IDS_H
-#define HW_PCI_IDS_H 1
+#define HW_PCI_IDS_H
 
 /* Device classes and subclasses */
 
diff --git a/include/hw/pcmcia.h b/include/hw/pcmcia.h
index 98406ffbc9..79cac9c761 100644
--- a/include/hw/pcmcia.h
+++ b/include/hw/pcmcia.h
@@ -1,5 +1,5 @@
 #ifndef HW_PCMCIA_H
-#define HW_PCMCIA_H 1
+#define HW_PCMCIA_H
 
 /* PCMCIA/Cardbus */
 
diff --git a/include/hw/platform-bus.h b/include/hw/platform-bus.h
index bd42b83809..a00775cba6 100644
--- a/include/hw/platform-bus.h
+++ b/include/hw/platform-bus.h
@@ -1,5 +1,5 @@
 #ifndef HW_PLATFORM_BUS_H
-#define HW_PLATFORM_BUS_H 1
+#define HW_PLATFORM_BUS_H
 
 /*
  *  Platform Bus device to support dynamic Sysbus devices
@@ -54,4 +54,4 @@ int platform_bus_get_irqn(PlatformBusDevice *platform_bus, SysBusDevice *sbdev,
 hwaddr platform_bus_get_mmio_addr(PlatformBusDevice *pbus, SysBusDevice *sbdev,
                                   int n);
 
-#endif /* !HW_PLATFORM_BUS_H */
+#endif /* HW_PLATFORM_BUS_H */
diff --git a/include/hw/ppc/mac_dbdma.h b/include/hw/ppc/mac_dbdma.h
index d15a6ccf3e..a8603877d7 100644
--- a/include/hw/ppc/mac_dbdma.h
+++ b/include/hw/ppc/mac_dbdma.h
@@ -19,8 +19,9 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
+
 #ifndef HW_MAC_DBDMA_H
-#define HW_MAC_DBDMA_H 1
+#define HW_MAC_DBDMA_H
 
 #include "exec/memory.h"
 #include "qemu/iov.h"
diff --git a/include/hw/ppc/openpic.h b/include/hw/ppc/openpic.h
index afe950b409..6137e2d7a2 100644
--- a/include/hw/ppc/openpic.h
+++ b/include/hw/ppc/openpic.h
@@ -1,5 +1,5 @@
-#if !defined(__OPENPIC_H__)
-#define __OPENPIC_H__
+#ifndef OPENPIC_H
+#define OPENPIC_H
 
 #include "qemu-common.h"
 #include "hw/qdev-core.h"
@@ -30,4 +30,4 @@ enum {
 #define TYPE_KVM_OPENPIC "kvm-openpic"
 int kvm_openpic_connect_vcpu(DeviceState *d, CPUState *cs);
 
-#endif /* __OPENPIC_H__ */
+#endif /* OPENPIC_H */
diff --git a/include/hw/ppc/ppc.h b/include/hw/ppc/ppc.h
index 5617dc4a2c..520c72a08d 100644
--- a/include/hw/ppc/ppc.h
+++ b/include/hw/ppc/ppc.h
@@ -1,5 +1,5 @@
 #ifndef HW_PPC_H
-#define HW_PPC_H 1
+#define HW_PPC_H
 
 #include "target-ppc/cpu-qom.h"
 
diff --git a/include/hw/ppc/ppc4xx.h b/include/hw/ppc/ppc4xx.h
index 91d84bad63..3b01ae8314 100644
--- a/include/hw/ppc/ppc4xx.h
+++ b/include/hw/ppc/ppc4xx.h
@@ -22,8 +22,8 @@
  * THE SOFTWARE.
  */
 
-#if !defined(PPC_4XX_H)
-#define PPC_4XX_H
+#ifndef PPC4XX_H
+#define PPC4XX_H
 
 #include "hw/pci/pci.h"
 
@@ -61,4 +61,4 @@ PCIBus *ppc4xx_pci_init(CPUPPCState *env, qemu_irq pci_irqs[4],
                         hwaddr special_cycle,
                         hwaddr registers);
 
-#endif /* !defined(PPC_4XX_H) */
+#endif /* PPC4XX_H */
diff --git a/include/hw/ppc/spapr.h b/include/hw/ppc/spapr.h
index 2e2dd14c30..bd8ac28160 100644
--- a/include/hw/ppc/spapr.h
+++ b/include/hw/ppc/spapr.h
@@ -1,5 +1,5 @@
-#if !defined(__HW_SPAPR_H__)
-#define __HW_SPAPR_H__
+#ifndef HW_SPAPR_H
+#define HW_SPAPR_H
 
 #include "sysemu/dma.h"
 #include "hw/boards.h"
@@ -648,4 +648,4 @@ int spapr_rng_populate_dt(void *fdt);
 #define SPAPR_LMB_FLAGS_DRC_INVALID 0x00000020
 #define SPAPR_LMB_FLAGS_RESERVED 0x00000080
 
-#endif /* !defined (__HW_SPAPR_H__) */
+#endif /* HW_SPAPR_H */
diff --git a/include/hw/ppc/spapr_drc.h b/include/hw/ppc/spapr_drc.h
index 08e8411463..fa531d5c26 100644
--- a/include/hw/ppc/spapr_drc.h
+++ b/include/hw/ppc/spapr_drc.h
@@ -9,12 +9,13 @@
  * This work is licensed under the terms of the GNU GPL, version 2 or later.
  * See the COPYING file in the top-level directory.
  */
-#if !defined(__HW_SPAPR_DRC_H__)
-#define __HW_SPAPR_DRC_H__
 
+#ifndef HW_SPAPR_DRC_H
+#define HW_SPAPR_DRC_H
+
+#include <libfdt.h>
 #include "qom/object.h"
 #include "hw/qdev.h"
-#include "libfdt.h"
 
 #define TYPE_SPAPR_DR_CONNECTOR "spapr-dr-connector"
 #define SPAPR_DR_CONNECTOR_GET_CLASS(obj) \
@@ -202,4 +203,4 @@ sPAPRDRConnector *spapr_dr_connector_by_id(sPAPRDRConnectorType type,
 int spapr_drc_populate_dt(void *fdt, int fdt_offset, Object *owner,
                           uint32_t drc_type_mask);
 
-#endif /* __HW_SPAPR_DRC_H__ */
+#endif /* HW_SPAPR_DRC_H */
diff --git a/include/hw/ppc/spapr_vio.h b/include/hw/ppc/spapr_vio.h
index bdb5d2f308..d4a1e2c8af 100644
--- a/include/hw/ppc/spapr_vio.h
+++ b/include/hw/ppc/spapr_vio.h
@@ -1,5 +1,6 @@
-#ifndef _HW_SPAPR_VIO_H
-#define _HW_SPAPR_VIO_H
+#ifndef HW_SPAPR_VIO_H
+#define HW_SPAPR_VIO_H
+
 /*
  * QEMU sPAPR VIO bus definitions
  *
@@ -145,4 +146,4 @@ extern const VMStateDescription vmstate_spapr_vio;
 
 void spapr_vio_set_bypass(VIOsPAPRDevice *dev, bool bypass);
 
-#endif /* _HW_SPAPR_VIO_H */
+#endif /* HW_SPAPR_VIO_H */
diff --git a/include/hw/ppc/xics.h b/include/hw/ppc/xics.h
index 6189a3bff7..2db9f938d3 100644
--- a/include/hw/ppc/xics.h
+++ b/include/hw/ppc/xics.h
@@ -24,8 +24,9 @@
  * THE SOFTWARE.
  *
  */
-#if !defined(__XICS_H__)
-#define __XICS_H__
+
+#ifndef XICS_H
+#define XICS_H
 
 #include "hw/sysbus.h"
 
@@ -196,4 +197,4 @@ void ics_set_irq_type(ICSState *ics, int srcno, bool lsi);
 
 int xics_find_source(XICSState *icp, int irq);
 
-#endif /* __XICS_H__ */
+#endif /* XICS_H */
diff --git a/include/hw/qdev-properties.h b/include/hw/qdev-properties.h
index 034b75acc5..2a9d2f90e6 100644
--- a/include/hw/qdev-properties.h
+++ b/include/hw/qdev-properties.h
@@ -20,6 +20,7 @@ extern PropertyInfo qdev_prop_ptr;
 extern PropertyInfo qdev_prop_macaddr;
 extern PropertyInfo qdev_prop_on_off_auto;
 extern PropertyInfo qdev_prop_losttickpolicy;
+extern PropertyInfo qdev_prop_blockdev_on_error;
 extern PropertyInfo qdev_prop_bios_chs_trans;
 extern PropertyInfo qdev_prop_fdc_drive_type;
 extern PropertyInfo qdev_prop_drive;
@@ -161,6 +162,9 @@ extern PropertyInfo qdev_prop_arraylen;
 #define DEFINE_PROP_LOSTTICKPOLICY(_n, _s, _f, _d) \
     DEFINE_PROP_DEFAULT(_n, _s, _f, _d, qdev_prop_losttickpolicy, \
                         LostTickPolicy)
+#define DEFINE_PROP_BLOCKDEV_ON_ERROR(_n, _s, _f, _d) \
+    DEFINE_PROP_DEFAULT(_n, _s, _f, _d, qdev_prop_blockdev_on_error, \
+                        BlockdevOnError)
 #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) \
diff --git a/include/hw/s390x/css-bridge.h b/include/hw/s390x/css-bridge.h
new file mode 100644
index 0000000000..ad73c1faf6
--- /dev/null
+++ b/include/hw/s390x/css-bridge.h
@@ -0,0 +1,31 @@
+/*
+ * virtual css bridge definition
+ *
+ * Copyright 2012,2016 IBM Corp.
+ * Author(s): Cornelia Huck <cornelia.huck@de.ibm.com>
+ *            Pierre Morel <pmorel@linux.vnet.ibm.com>
+ *
+ * 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.
+ */
+
+#ifndef HW_S390X_CSS_BRIDGE_H
+#define HW_S390X_CSS_BRIDGE_H
+#include "qom/object.h"
+#include "hw/qdev-core.h"
+
+/* virtual css bridge */
+#define TYPE_VIRTUAL_CSS_BRIDGE "virtual-css-bridge"
+
+/* virtual css bus type */
+typedef struct VirtualCssBus {
+    BusState parent_obj;
+} VirtualCssBus;
+
+#define TYPE_VIRTUAL_CSS_BUS "virtual-css-bus"
+#define VIRTUAL_CSS_BUS(obj) \
+     OBJECT_CHECK(VirtualCssBus, (obj), TYPE_VIRTUAL_CSS_BUS)
+VirtualCssBus *virtual_css_bus_init(void);
+
+#endif
diff --git a/include/hw/s390x/css.h b/include/hw/s390x/css.h
index 38f4d77779..1da63e361d 100644
--- a/include/hw/s390x/css.h
+++ b/include/hw/s390x/css.h
@@ -17,6 +17,7 @@
 #include "hw/s390x/ioinst.h"
 
 /* Channel subsystem constants. */
+#define MAX_DEVNO 65535
 #define MAX_SCHID 65535
 #define MAX_SSID 3
 #define MAX_CSSID 254 /* 255 is reserved */
@@ -24,6 +25,8 @@
 
 #define MAX_CIWS 62
 
+#define VIRTUAL_CSSID 0xfe
+
 typedef struct CIW {
     uint8_t type;
     uint8_t command;
@@ -169,4 +172,19 @@ extern PropertyInfo css_devid_propinfo;
 #define DEFINE_PROP_CSS_DEV_ID(_n, _s, _f) \
     DEFINE_PROP(_n, _s, _f, css_devid_propinfo, CssDevId)
 
+/**
+ * Create a subchannel for the given bus id.
+ *
+ * If @p bus_id is valid, verify that it uses the virtual channel
+ * subsystem id and is not already in use, and find a free subchannel
+ * id for it. If @p bus_id is not valid, find a free subchannel id and
+ * device number across all subchannel sets. If either of the former
+ * actions succeed, allocate a subchannel structure, initialise it
+ * with the bus id, subchannel id and device number, register it with
+ * the CSS and return it. Otherwise return NULL.
+ *
+ * The caller becomes owner of the returned subchannel structure and
+ * is responsible for unregistering and freeing it.
+ */
+SubchDev *css_create_virtual_sch(CssDevId bus_id, Error **errp);
 #endif
diff --git a/include/hw/s390x/ebcdic.h b/include/hw/s390x/ebcdic.h
index 1d6fde9c12..69a04cab62 100644
--- a/include/hw/s390x/ebcdic.h
+++ b/include/hw/s390x/ebcdic.h
@@ -9,8 +9,8 @@
  *
  */
 
-#ifndef EBCDIC_H_
-#define EBCDIC_H_
+#ifndef EBCDIC_H
+#define EBCDIC_H
 
 /* EBCDIC handling */
 static const uint8_t ebcdic2ascii[] = {
@@ -101,4 +101,4 @@ static inline void ascii_put(uint8_t *p, const char *ebcdic, int len)
     }
 }
 
-#endif /* EBCDIC_H_ */
+#endif /* EBCDIC_H */
diff --git a/include/hw/s390x/event-facility.h b/include/hw/s390x/event-facility.h
index dd8881838c..def1bb0c03 100644
--- a/include/hw/s390x/event-facility.h
+++ b/include/hw/s390x/event-facility.h
@@ -15,7 +15,7 @@
 #ifndef HW_S390_SCLP_EVENT_FACILITY_H
 #define HW_S390_SCLP_EVENT_FACILITY_H
 
-#include <hw/qdev.h>
+#include "hw/qdev.h"
 #include "qemu/thread.h"
 #include "hw/s390x/sclp.h"
 
diff --git a/include/hw/s390x/ioinst.h b/include/hw/s390x/ioinst.h
index 12d44c8a02..c559f53426 100644
--- a/include/hw/s390x/ioinst.h
+++ b/include/hw/s390x/ioinst.h
@@ -9,8 +9,8 @@
  * directory.
 */
 
-#ifndef IOINST_S390X_H
-#define IOINST_S390X_H
+#ifndef S390X_IOINST_H
+#define S390X_IOINST_H
 
 /*
  * Channel I/O related definitions, as defined in the Principles
diff --git a/include/hw/s390x/s390_flic.h b/include/hw/s390x/s390_flic.h
index 1dac2ee48d..9094edadf5 100644
--- a/include/hw/s390x/s390_flic.h
+++ b/include/hw/s390x/s390_flic.h
@@ -10,8 +10,8 @@
  * directory.
  */
 
-#ifndef __HW_S390_FLIC_H
-#define __HW_S390_FLIC_H
+#ifndef HW_S390_FLIC_H
+#define HW_S390_FLIC_H
 
 #include "hw/sysbus.h"
 #include "hw/s390x/adapter.h"
@@ -78,4 +78,4 @@ static inline DeviceState *s390_flic_kvm_create(void)
 }
 #endif
 
-#endif /* __HW_S390_FLIC_H */
+#endif /* HW_S390_FLIC_H */
diff --git a/include/hw/s390x/sclp.h b/include/hw/s390x/sclp.h
index b0c71b5550..ba28d1dd0e 100644
--- a/include/hw/s390x/sclp.h
+++ b/include/hw/s390x/sclp.h
@@ -14,8 +14,8 @@
 #ifndef HW_S390_SCLP_H
 #define HW_S390_SCLP_H
 
-#include <hw/sysbus.h>
-#include <hw/qdev.h>
+#include "hw/sysbus.h"
+#include "hw/qdev.h"
 
 #define SCLP_CMD_CODE_MASK                      0xffff00ff
 
@@ -58,6 +58,7 @@
 #define SCLP_RC_CONTAINED_EQUIPMENT_CHECK       0x0340
 #define SCLP_RC_INSUFFICIENT_SCCB_LENGTH        0x0300
 #define SCLP_RC_STANDBY_READ_COMPLETION         0x0410
+#define SCLP_RC_ADAPTER_IN_RESERVED_STATE       0x05f0
 #define SCLP_RC_ADAPTER_ID_NOT_RECOGNIZED       0x09f0
 #define SCLP_RC_INVALID_FUNCTION                0x40f0
 #define SCLP_RC_NO_EVENT_BUFFERS_STORED         0x60f0
diff --git a/include/hw/s390x/storage-keys.h b/include/hw/s390x/storage-keys.h
index 72b850cb17..62df48ec06 100644
--- a/include/hw/s390x/storage-keys.h
+++ b/include/hw/s390x/storage-keys.h
@@ -9,10 +9,10 @@
  * directory.
  */
 
-#ifndef __S390_STORAGE_KEYS_H
-#define __S390_STORAGE_KEYS_H
+#ifndef S390_STORAGE_KEYS_H
+#define S390_STORAGE_KEYS_H
 
-#include <hw/qdev.h>
+#include "hw/qdev.h"
 #include "monitor/monitor.h"
 
 #define TYPE_S390_SKEYS "s390-skeys"
@@ -57,4 +57,4 @@ S390SKeysState *s390_get_skeys_device(void);
 void hmp_dump_skeys(Monitor *mon, const QDict *qdict);
 void hmp_info_skeys(Monitor *mon, const QDict *qdict);
 
-#endif /* __S390_STORAGE_KEYS_H */
+#endif /* S390_STORAGE_KEYS_H */
diff --git a/include/hw/sd/sd.h b/include/hw/sd/sd.h
index c8a4b98d5d..79909b2478 100644
--- a/include/hw/sd/sd.h
+++ b/include/hw/sd/sd.h
@@ -26,8 +26,9 @@
  * (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 __hw_sd_h
-#define __hw_sd_h		1
+
+#ifndef HW_SD_H
+#define HW_SD_H
 
 #include "hw/qdev.h"
 
@@ -144,4 +145,4 @@ bool sdbus_get_readonly(SDBus *sd);
 void sdbus_set_inserted(SDBus *sd, bool inserted);
 void sdbus_set_readonly(SDBus *sd, bool inserted);
 
-#endif	/* __hw_sd_h */
+#endif /* HW_SD_H */
diff --git a/include/hw/sh4/sh_intc.h b/include/hw/sh4/sh_intc.h
index b7ddcb096a..7913bc48a2 100644
--- a/include/hw/sh4/sh_intc.h
+++ b/include/hw/sh4/sh_intc.h
@@ -1,5 +1,5 @@
-#ifndef __SH_INTC_H__
-#define __SH_INTC_H__
+#ifndef SH_INTC_H
+#define SH_INTC_H
 
 #include "qemu-common.h"
 #include "hw/irq.h"
@@ -80,4 +80,4 @@ int sh_intc_init(MemoryRegion *sysmem,
 
 void sh_intc_set_irl(void *opaque, int n, int level);
 
-#endif /* __SH_INTC_H__ */
+#endif /* SH_INTC_H */
diff --git a/include/hw/smbios/smbios.h b/include/hw/smbios/smbios.h
index ba3674609e..1cd53cc58c 100644
--- a/include/hw/smbios/smbios.h
+++ b/include/hw/smbios/smbios.h
@@ -1,5 +1,6 @@
 #ifndef QEMU_SMBIOS_H
 #define QEMU_SMBIOS_H
+
 /*
  * SMBIOS Support
  *
@@ -266,4 +267,4 @@ void smbios_get_tables(const struct smbios_phys_mem_area *mem_array,
                        const unsigned int mem_array_size,
                        uint8_t **tables, size_t *tables_len,
                        uint8_t **anchor, size_t *anchor_len);
-#endif /*QEMU_SMBIOS_H */
+#endif /* QEMU_SMBIOS_H */
diff --git a/include/hw/sparc/grlib.h b/include/hw/sparc/grlib.h
index 9a0db7b47b..afbb9bc07c 100644
--- a/include/hw/sparc/grlib.h
+++ b/include/hw/sparc/grlib.h
@@ -22,8 +22,8 @@
  * THE SOFTWARE.
  */
 
-#ifndef _GRLIB_H_
-#define _GRLIB_H_
+#ifndef GRLIB_H
+#define GRLIB_H
 
 #include "hw/qdev.h"
 #include "hw/sysbus.h"
@@ -117,4 +117,4 @@ DeviceState *grlib_apbuart_create(hwaddr  base,
     return dev;
 }
 
-#endif /* ! _GRLIB_H_ */
+#endif /* GRLIB_H */
diff --git a/include/hw/ssi/xilinx_spips.h b/include/hw/ssi/xilinx_spips.h
index dbb9eefbaa..06aa09629d 100644
--- a/include/hw/ssi/xilinx_spips.h
+++ b/include/hw/ssi/xilinx_spips.h
@@ -22,8 +22,8 @@
  * THE SOFTWARE.
  */
 
-#ifndef XLNX_SPIPS_H
-#define XLNX_SPIPS_H
+#ifndef XILINX_SPIPS_H
+#define XILINX_SPIPS_H
 
 #include "hw/ssi/ssi.h"
 #include "qemu/fifo8.h"
@@ -69,4 +69,4 @@ struct XilinxSPIPS {
 #define XILINX_QSPIPS(obj) \
      OBJECT_CHECK(XilinxQSPIPS, (obj), TYPE_XILINX_QSPIPS)
 
-#endif /* XLNX_SPIPS_H */
+#endif /* XILINX_SPIPS_H */
diff --git a/include/hw/stream.h b/include/hw/stream.h
index 30ccc56203..c370ba0c66 100644
--- a/include/hw/stream.h
+++ b/include/hw/stream.h
@@ -1,5 +1,5 @@
 #ifndef STREAM_H
-#define STREAM_H 1
+#define STREAM_H
 
 #include "qemu-common.h"
 #include "qom/object.h"
diff --git a/include/hw/sysbus.h b/include/hw/sysbus.h
index a4959378d4..e73a5b21ac 100644
--- a/include/hw/sysbus.h
+++ b/include/hw/sysbus.h
@@ -1,5 +1,5 @@
 #ifndef HW_SYSBUS_H
-#define HW_SYSBUS_H 1
+#define HW_SYSBUS_H
 
 /* Devices attached directly to the main system bus.  */
 
@@ -118,4 +118,4 @@ static inline DeviceState *sysbus_try_create_simple(const char *name,
     return sysbus_try_create_varargs(name, addr, irq, NULL);
 }
 
-#endif /* !HW_SYSBUS_H */
+#endif /* HW_SYSBUS_H */
diff --git a/include/hw/timer/a9gtimer.h b/include/hw/timer/a9gtimer.h
index 98d8e0ae53..81c4388784 100644
--- a/include/hw/timer/a9gtimer.h
+++ b/include/hw/timer/a9gtimer.h
@@ -20,8 +20,8 @@
  * with this program; if not, see <http://www.gnu.org/licenses/>.
  */
 
-#ifndef HW_TIMER_A9_GTIMER_H_H
-#define HW_TIMER_A9_GTIMER_H_H
+#ifndef A9GTIMER_H
+#define A9GTIMER_H
 
 #include "hw/sysbus.h"
 
@@ -94,4 +94,4 @@ typedef struct A9GTimerUpdate {
     uint64_t new;
 } A9GTimerUpdate;
 
-#endif /* #ifdef HW_TIMER_A9_GTIMER_H_H */
+#endif /* A9GTIMER_H */
diff --git a/include/hw/timer/allwinner-a10-pit.h b/include/hw/timer/allwinner-a10-pit.h
index 770bdc03c1..c0cc3e2169 100644
--- a/include/hw/timer/allwinner-a10-pit.h
+++ b/include/hw/timer/allwinner-a10-pit.h
@@ -1,5 +1,5 @@
-#ifndef AW_A10_PIT_H
-#define AW_A10_PIT_H
+#ifndef ALLWINNER_A10_PIT_H
+#define ALLWINNER_A10_PIT_H
 
 #include "hw/ptimer.h"
 
diff --git a/include/hw/timer/hpet.h b/include/hw/timer/hpet.h
index f38bcfecd6..f04c4d3238 100644
--- a/include/hw/timer/hpet.h
+++ b/include/hw/timer/hpet.h
@@ -10,8 +10,9 @@
  * the COPYING file in the top-level directory.
  *
  */
-#ifndef QEMU_HPET_EMUL_H
-#define QEMU_HPET_EMUL_H
+
+#ifndef HW_HPET_H
+#define HW_HPET_H
 
 #include "qom/object.h"
 
diff --git a/include/hw/timer/i8254.h b/include/hw/timer/i8254.h
index 27a0fb6c51..5adae9fa44 100644
--- a/include/hw/timer/i8254.h
+++ b/include/hw/timer/i8254.h
@@ -80,4 +80,4 @@ static inline ISADevice *kvm_pit_init(ISABus *bus, int base)
 void pit_set_gate(ISADevice *dev, int channel, int val);
 void pit_get_channel_info(ISADevice *dev, int channel, PITChannelInfo *info);
 
-#endif /* !HW_I8254_H */
+#endif /* HW_I8254_H */
diff --git a/include/hw/timer/i8254_internal.h b/include/hw/timer/i8254_internal.h
index e7cb7573ca..dc09cc0467 100644
--- a/include/hw/timer/i8254_internal.h
+++ b/include/hw/timer/i8254_internal.h
@@ -73,4 +73,4 @@ void pit_get_channel_info_common(PITCommonState *s, PITChannelState *sc,
                                  PITChannelInfo *info);
 void pit_reset_common(PITCommonState *s);
 
-#endif /* !QEMU_I8254_INTERNAL_H */
+#endif /* QEMU_I8254_INTERNAL_H */
diff --git a/include/hw/timer/m48t59.h b/include/hw/timer/m48t59.h
index 3367923639..db5e43a8da 100644
--- a/include/hw/timer/m48t59.h
+++ b/include/hw/timer/m48t59.h
@@ -1,5 +1,5 @@
-#ifndef NVRAM_H
-#define NVRAM_H
+#ifndef HW_M48T59_H
+#define HW_M48T59_H
 
 #include "qemu-common.h"
 #include "qom/object.h"
@@ -31,4 +31,4 @@ Nvram *m48t59_init(qemu_irq IRQ, hwaddr mem_base,
                    uint32_t io_base, uint16_t size, int base_year,
                    int type);
 
-#endif /* !NVRAM_H */
+#endif /* HW_M48T59_H */
diff --git a/include/hw/timer/mc146818rtc.h b/include/hw/timer/mc146818rtc.h
index eaf649767f..7c8e64b203 100644
--- a/include/hw/timer/mc146818rtc.h
+++ b/include/hw/timer/mc146818rtc.h
@@ -10,4 +10,4 @@ ISADevice *rtc_init(ISABus *bus, int base_year, qemu_irq intercept_irq);
 void rtc_set_memory(ISADevice *dev, int addr, int val);
 int rtc_get_memory(ISADevice *dev, int addr);
 
-#endif /* !MC146818RTC_H */
+#endif /* MC146818RTC_H */
diff --git a/include/hw/timer/mc146818rtc_regs.h b/include/hw/timer/mc146818rtc_regs.h
index ccdee42b3c..6ede6c832e 100644
--- a/include/hw/timer/mc146818rtc_regs.h
+++ b/include/hw/timer/mc146818rtc_regs.h
@@ -21,8 +21,9 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
-#ifndef RTC_REGS_H
-#define RTC_REGS_H
+
+#ifndef MC146818RTC_REGS_H
+#define MC146818RTC_REGS_H
 
 #define RTC_ISA_IRQ 8
 
diff --git a/include/hw/timer/mips_gictimer.h b/include/hw/timer/mips_gictimer.h
new file mode 100644
index 0000000000..c8bc5d2541
--- /dev/null
+++ b/include/hw/timer/mips_gictimer.h
@@ -0,0 +1,46 @@
+/*
+ * This file is subject to the terms and conditions of the GNU General Public
+ * License.  See the file "COPYING" in the main directory of this archive
+ * for more details.
+ *
+ * Copyright (C) 2016 Imagination Technologies
+ *
+ */
+
+#ifndef MIPS_GICTIMER_H
+#define MIPS_GICTIMER_H
+
+typedef struct MIPSGICTimerVPState MIPSGICTimerVPState;
+typedef struct MIPSGICTimerState MIPSGICTimerState;
+
+typedef void MIPSGICTimerCB(void *opaque, uint32_t vp_index);
+
+struct MIPSGICTimerVPState {
+    QEMUTimer *qtimer;
+    uint32_t vp_index;
+    uint32_t comparelo;
+    MIPSGICTimerState *gictimer;
+};
+
+struct MIPSGICTimerState {
+    void *opaque;
+    uint8_t countstop;
+    uint32_t sh_counterlo;
+    int32_t num_vps;
+    MIPSGICTimerVPState *vptimers;
+    MIPSGICTimerCB *cb;
+};
+
+uint32_t mips_gictimer_get_sh_count(MIPSGICTimerState *gic);
+void mips_gictimer_store_sh_count(MIPSGICTimerState *gic, uint64_t count);
+uint32_t mips_gictimer_get_vp_compare(MIPSGICTimerState *gictimer,
+                                      uint32_t vp_index);
+void mips_gictimer_store_vp_compare(MIPSGICTimerState *gic, uint32_t vp_index,
+                                    uint64_t compare);
+uint8_t mips_gictimer_get_countstop(MIPSGICTimerState *gic);
+void mips_gictimer_start_count(MIPSGICTimerState *gic);
+void mips_gictimer_stop_count(MIPSGICTimerState *gic);
+MIPSGICTimerState *mips_gictimer_init(void *opaque, uint32_t nvps,
+                                      MIPSGICTimerCB *cb);
+
+#endif /* MIPS_GICTIMER_H */
diff --git a/include/hw/tricore/tricore.h b/include/hw/tricore/tricore.h
index 5f13252788..89ef922c67 100644
--- a/include/hw/tricore/tricore.h
+++ b/include/hw/tricore/tricore.h
@@ -1,5 +1,5 @@
-#ifndef TRICORE_MISC_H
-#define TRICORE_MISC_H 1
+#ifndef HW_TRICORE_H
+#define HW_TRICORE_H
 
 #include "exec/memory.h"
 #include "hw/irq.h"
diff --git a/include/hw/unicore32/puv3.h b/include/hw/unicore32/puv3.h
index f37adcb665..5a4839f8df 100644
--- a/include/hw/unicore32/puv3.h
+++ b/include/hw/unicore32/puv3.h
@@ -8,6 +8,7 @@
  * 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
 
@@ -46,4 +47,4 @@
 #define DPRINTF(fmt, ...) do {} while (0)
 #endif
 
-#endif /* !QEMU_HW_PUV3_H */
+#endif /* QEMU_HW_PUV3_H */
diff --git a/include/hw/usb/ehci-regs.h b/include/hw/usb/ehci-regs.h
index 616f1b88cc..3e91b8e610 100644
--- a/include/hw/usb/ehci-regs.h
+++ b/include/hw/usb/ehci-regs.h
@@ -1,5 +1,5 @@
 #ifndef HW_USB_EHCI_REGS_H
-#define HW_USB_EHCI_REGS_H 1
+#define HW_USB_EHCI_REGS_H
 
 /* Capability Registers Base Address - section 2.2 */
 #define CAPLENGTH        0x0000  /* 1-byte, 0x0001 reserved */
diff --git a/include/hw/usb/uhci-regs.h b/include/hw/usb/uhci-regs.h
index c7315c5e1f..fd45d29db0 100644
--- a/include/hw/usb/uhci-regs.h
+++ b/include/hw/usb/uhci-regs.h
@@ -1,5 +1,5 @@
 #ifndef HW_USB_UHCI_REGS_H
-#define HW_USB_UHCI_REGS_H 1
+#define HW_USB_UHCI_REGS_H
 
 #define UHCI_CMD_FGR      (1 << 4)
 #define UHCI_CMD_EGSM     (1 << 3)
diff --git a/include/hw/vfio/vfio-common.h b/include/hw/vfio/vfio-common.h
index 07f7188df4..94dfae387a 100644
--- a/include/hw/vfio/vfio-common.h
+++ b/include/hw/vfio/vfio-common.h
@@ -17,6 +17,7 @@
  *  Copyright (C) 2008, Red Hat, Amit Shah (amit.shah@redhat.com)
  *  Copyright (C) 2008, IBM, Muli Ben-Yehuda (muli@il.ibm.com)
  */
+
 #ifndef HW_VFIO_VFIO_COMMON_H
 #define HW_VFIO_VFIO_COMMON_H
 
@@ -174,4 +175,4 @@ int vfio_spapr_create_window(VFIOContainer *container,
 int vfio_spapr_remove_window(VFIOContainer *container,
                              hwaddr offset_within_address_space);
 
-#endif /* !HW_VFIO_VFIO_COMMON_H */
+#endif /* HW_VFIO_VFIO_COMMON_H */
diff --git a/include/hw/vfio/vfio-platform.h b/include/hw/vfio/vfio-platform.h
index b468f80b1e..9baaa2db09 100644
--- a/include/hw/vfio/vfio-platform.h
+++ b/include/hw/vfio/vfio-platform.h
@@ -74,4 +74,4 @@ typedef struct VFIOPlatformDeviceClass {
 #define VFIO_PLATFORM_DEVICE_GET_CLASS(obj) \
      OBJECT_GET_CLASS(VFIOPlatformDeviceClass, (obj), TYPE_VFIO_PLATFORM)
 
-#endif /*HW_VFIO_VFIO_PLATFORM_H*/
+#endif /* HW_VFIO_VFIO_PLATFORM_H */
diff --git a/include/hw/vfio/vfio.h b/include/hw/vfio/vfio.h
index f27d599220..86248f5436 100644
--- a/include/hw/vfio/vfio.h
+++ b/include/hw/vfio/vfio.h
@@ -1,5 +1,5 @@
-#ifndef VFIO_API_H
-#define VFIO_API_H
+#ifndef HW_VFIO_H
+#define HW_VFIO_H
 
 bool vfio_eeh_as_ok(AddressSpace *as);
 int vfio_eeh_as_op(AddressSpace *as, uint32_t op);
diff --git a/include/hw/virtio/vhost-backend.h b/include/hw/virtio/vhost-backend.h
index 84e1cb79ff..cf7f0b5a69 100644
--- a/include/hw/virtio/vhost-backend.h
+++ b/include/hw/virtio/vhost-backend.h
@@ -8,9 +8,8 @@
  *
  */
 
-#ifndef VHOST_BACKEND_H_
-#define VHOST_BACKEND_H_
-
+#ifndef VHOST_BACKEND_H
+#define VHOST_BACKEND_H
 
 typedef enum VhostBackendType {
     VHOST_BACKEND_TYPE_NONE = 0,
@@ -110,4 +109,4 @@ extern const VhostOps user_ops;
 int vhost_set_backend_type(struct vhost_dev *dev,
                            VhostBackendType backend_type);
 
-#endif /* VHOST_BACKEND_H_ */
+#endif /* VHOST_BACKEND_H */
diff --git a/include/hw/virtio/virtio-access.h b/include/hw/virtio/virtio-access.h
index 4b28038146..440b4555ea 100644
--- a/include/hw/virtio/virtio-access.h
+++ b/include/hw/virtio/virtio-access.h
@@ -12,8 +12,10 @@
  * (at your option) any later version.
  *
  */
-#ifndef _QEMU_VIRTIO_ACCESS_H
-#define _QEMU_VIRTIO_ACCESS_H
+
+#ifndef QEMU_VIRTIO_ACCESS_H
+#define QEMU_VIRTIO_ACCESS_H
+
 #include "hw/virtio/virtio.h"
 #include "exec/address-spaces.h"
 
@@ -175,4 +177,4 @@ static inline void virtio_tswap64s(VirtIODevice *vdev, uint64_t *s)
 {
     *s = virtio_tswap64(vdev, *s);
 }
-#endif /* _QEMU_VIRTIO_ACCESS_H */
+#endif /* QEMU_VIRTIO_ACCESS_H */
diff --git a/include/hw/virtio/virtio-balloon.h b/include/hw/virtio/virtio-balloon.h
index 35f62ac119..1ea13bd6a4 100644
--- a/include/hw/virtio/virtio-balloon.h
+++ b/include/hw/virtio/virtio-balloon.h
@@ -12,8 +12,8 @@
  *
  */
 
-#ifndef _QEMU_VIRTIO_BALLOON_H
-#define _QEMU_VIRTIO_BALLOON_H
+#ifndef QEMU_VIRTIO_BALLOON_H
+#define QEMU_VIRTIO_BALLOON_H
 
 #include "standard-headers/linux/virtio_balloon.h"
 #include "hw/virtio/virtio.h"
diff --git a/include/hw/virtio/virtio-blk.h b/include/hw/virtio/virtio-blk.h
index e9bf463f53..180bd8db5d 100644
--- a/include/hw/virtio/virtio-blk.h
+++ b/include/hw/virtio/virtio-blk.h
@@ -11,8 +11,8 @@
  *
  */
 
-#ifndef _QEMU_VIRTIO_BLK_H
-#define _QEMU_VIRTIO_BLK_H
+#ifndef QEMU_VIRTIO_BLK_H
+#define QEMU_VIRTIO_BLK_H
 
 #include "standard-headers/linux/virtio_blk.h"
 #include "hw/virtio/virtio.h"
diff --git a/include/hw/virtio/virtio-gpu.h b/include/hw/virtio/virtio-gpu.h
index 3dff0c9a76..325354f9f3 100644
--- a/include/hw/virtio/virtio-gpu.h
+++ b/include/hw/virtio/virtio-gpu.h
@@ -11,8 +11,8 @@
  * See the COPYING file in the top-level directory.
  */
 
-#ifndef _QEMU_VIRTIO_VGA_H
-#define _QEMU_VIRTIO_VGA_H
+#ifndef HW_VIRTIO_GPU_H
+#define HW_VIRTIO_GPU_H
 
 #include "qemu/queue.h"
 #include "ui/qemu-pixman.h"
diff --git a/include/hw/virtio/virtio-input.h b/include/hw/virtio/virtio-input.h
index bddbd4b287..55db31087a 100644
--- a/include/hw/virtio/virtio-input.h
+++ b/include/hw/virtio/virtio-input.h
@@ -1,5 +1,5 @@
-#ifndef _QEMU_VIRTIO_INPUT_H
-#define _QEMU_VIRTIO_INPUT_H
+#ifndef QEMU_VIRTIO_INPUT_H
+#define QEMU_VIRTIO_INPUT_H
 
 #include "ui/input.h"
 
@@ -105,4 +105,4 @@ void virtio_input_add_config(VirtIOInput *vinput,
 void virtio_input_idstr_config(VirtIOInput *vinput,
                                uint8_t select, const char *string);
 
-#endif /* _QEMU_VIRTIO_INPUT_H */
+#endif /* QEMU_VIRTIO_INPUT_H */
diff --git a/include/hw/virtio/virtio-net.h b/include/hw/virtio/virtio-net.h
index 0cabdb6822..91ed97cfcd 100644
--- a/include/hw/virtio/virtio-net.h
+++ b/include/hw/virtio/virtio-net.h
@@ -11,8 +11,8 @@
  *
  */
 
-#ifndef _QEMU_VIRTIO_NET_H
-#define _QEMU_VIRTIO_NET_H
+#ifndef QEMU_VIRTIO_NET_H
+#define QEMU_VIRTIO_NET_H
 
 #include "standard-headers/linux/virtio_net.h"
 #include "hw/virtio/virtio.h"
diff --git a/include/hw/virtio/virtio-rng.h b/include/hw/virtio/virtio-rng.h
index 2bc1ee5b50..2d40abdbdb 100644
--- a/include/hw/virtio/virtio-rng.h
+++ b/include/hw/virtio/virtio-rng.h
@@ -9,8 +9,8 @@
  * top-level directory.
  */
 
-#ifndef _QEMU_VIRTIO_RNG_H
-#define _QEMU_VIRTIO_RNG_H
+#ifndef QEMU_VIRTIO_RNG_H
+#define QEMU_VIRTIO_RNG_H
 
 #include "sysemu/rng.h"
 #include "sysemu/rng-random.h"
diff --git a/include/hw/virtio/virtio-scsi.h b/include/hw/virtio/virtio-scsi.h
index b5156694e5..5e3f088f9a 100644
--- a/include/hw/virtio/virtio-scsi.h
+++ b/include/hw/virtio/virtio-scsi.h
@@ -11,8 +11,8 @@
  *
  */
 
-#ifndef _QEMU_VIRTIO_SCSI_H
-#define _QEMU_VIRTIO_SCSI_H
+#ifndef QEMU_VIRTIO_SCSI_H
+#define QEMU_VIRTIO_SCSI_H
 
 /* Override CDB/sense data size: they are dynamic (guest controlled) in QEMU */
 #define VIRTIO_SCSI_CDB_SIZE 0
@@ -141,4 +141,4 @@ void virtio_scsi_dataplane_start(VirtIOSCSI *s);
 void virtio_scsi_dataplane_stop(VirtIOSCSI *s);
 void virtio_scsi_dataplane_notify(VirtIODevice *vdev, VirtIOSCSIReq *req);
 
-#endif /* _QEMU_VIRTIO_SCSI_H */
+#endif /* QEMU_VIRTIO_SCSI_H */
diff --git a/include/hw/virtio/virtio-serial.h b/include/hw/virtio/virtio-serial.h
index 12a55a19e9..730c88d2a7 100644
--- a/include/hw/virtio/virtio-serial.h
+++ b/include/hw/virtio/virtio-serial.h
@@ -12,8 +12,9 @@
  * the COPYING file in the top-level directory.
  *
  */
-#ifndef _QEMU_VIRTIO_SERIAL_H
-#define _QEMU_VIRTIO_SERIAL_H
+
+#ifndef QEMU_VIRTIO_SERIAL_H
+#define QEMU_VIRTIO_SERIAL_H
 
 #include "standard-headers/linux/virtio_console.h"
 #include "hw/qdev.h"
diff --git a/include/hw/virtio/virtio.h b/include/hw/virtio/virtio.h
index 96b581dc91..8a681f56f1 100644
--- a/include/hw/virtio/virtio.h
+++ b/include/hw/virtio/virtio.h
@@ -11,8 +11,8 @@
  *
  */
 
-#ifndef _QEMU_VIRTIO_H
-#define _QEMU_VIRTIO_H
+#ifndef QEMU_VIRTIO_H
+#define QEMU_VIRTIO_H
 
 #include "hw/hw.h"
 #include "net/net.h"
diff --git a/include/hw/watchdog/wdt_diag288.h b/include/hw/watchdog/wdt_diag288.h
index 7f3fd450dc..706d96b753 100644
--- a/include/hw/watchdog/wdt_diag288.h
+++ b/include/hw/watchdog/wdt_diag288.h
@@ -33,4 +33,4 @@ typedef struct DIAG288Class {
                         uint64_t func, uint64_t timeout);
 } DIAG288Class;
 
-#endif  /* WDT_DIAG288_H */
+#endif /* WDT_DIAG288_H */
diff --git a/include/hw/xen/xen.h b/include/hw/xen/xen.h
index b2cd992430..a8f3afb03b 100644
--- a/include/hw/xen/xen.h
+++ b/include/hw/xen/xen.h
@@ -1,5 +1,6 @@
 #ifndef QEMU_HW_XEN_H
-#define QEMU_HW_XEN_H 1
+#define QEMU_HW_XEN_H
+
 /*
  * public xen header
  *   stuff needed outside xen-*.c, i.e. interfaces to qemu.
diff --git a/include/hw/xen/xen_backend.h b/include/hw/xen/xen_backend.h
index 6e18a46a97..754c0a4ee6 100644
--- a/include/hw/xen/xen_backend.h
+++ b/include/hw/xen/xen_backend.h
@@ -1,5 +1,5 @@
 #ifndef QEMU_HW_XEN_BACKEND_H
-#define QEMU_HW_XEN_BACKEND_H 1
+#define QEMU_HW_XEN_BACKEND_H
 
 #include "hw/xen/xen_common.h"
 #include "sysemu/sysemu.h"
diff --git a/include/hw/xen/xen_common.h b/include/hw/xen/xen_common.h
index 5eabf37328..640c31e2c1 100644
--- a/include/hw/xen/xen_common.h
+++ b/include/hw/xen/xen_common.h
@@ -1,7 +1,5 @@
 #ifndef QEMU_HW_XEN_COMMON_H
-#define QEMU_HW_XEN_COMMON_H 1
-
-
+#define QEMU_HW_XEN_COMMON_H
 
 /*
  * If we have new enough libxenctrl then we do not want/need these compat
diff --git a/include/io/channel-buffer.h b/include/io/channel-buffer.h
index 65c498b2c2..3f4b3f29e1 100644
--- a/include/io/channel-buffer.h
+++ b/include/io/channel-buffer.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QIO_CHANNEL_BUFFER_H__
-#define QIO_CHANNEL_BUFFER_H__
+#ifndef QIO_CHANNEL_BUFFER_H
+#define QIO_CHANNEL_BUFFER_H
 
 #include "io/channel.h"
 
@@ -57,4 +57,4 @@ struct QIOChannelBuffer {
 QIOChannelBuffer *
 qio_channel_buffer_new(size_t capacity);
 
-#endif /* QIO_CHANNEL_BUFFER_H__ */
+#endif /* QIO_CHANNEL_BUFFER_H */
diff --git a/include/io/channel-command.h b/include/io/channel-command.h
index cfc177e786..336d47fa5c 100644
--- a/include/io/channel-command.h
+++ b/include/io/channel-command.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QIO_CHANNEL_COMMAND_H__
-#define QIO_CHANNEL_COMMAND_H__
+#ifndef QIO_CHANNEL_COMMAND_H
+#define QIO_CHANNEL_COMMAND_H
 
 #include "io/channel.h"
 
@@ -88,4 +88,4 @@ qio_channel_command_new_spawn(const char *const argv[],
                               Error **errp);
 
 
-#endif /* QIO_CHANNEL_COMMAND_H__ */
+#endif /* QIO_CHANNEL_COMMAND_H */
diff --git a/include/io/channel-file.h b/include/io/channel-file.h
index 308e6d44d6..d2462c2ed7 100644
--- a/include/io/channel-file.h
+++ b/include/io/channel-file.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QIO_CHANNEL_FILE_H__
-#define QIO_CHANNEL_FILE_H__
+#ifndef QIO_CHANNEL_FILE_H
+#define QIO_CHANNEL_FILE_H
 
 #include "io/channel.h"
 
@@ -90,4 +90,4 @@ qio_channel_file_new_path(const char *path,
                           mode_t mode,
                           Error **errp);
 
-#endif /* QIO_CHANNEL_FILE_H__ */
+#endif /* QIO_CHANNEL_FILE_H */
diff --git a/include/io/channel-socket.h b/include/io/channel-socket.h
index 70d06b40d9..711f8bf7ce 100644
--- a/include/io/channel-socket.h
+++ b/include/io/channel-socket.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QIO_CHANNEL_SOCKET_H__
-#define QIO_CHANNEL_SOCKET_H__
+#ifndef QIO_CHANNEL_SOCKET_H
+#define QIO_CHANNEL_SOCKET_H
 
 #include "io/channel.h"
 #include "io/task.h"
@@ -248,4 +248,4 @@ qio_channel_socket_accept(QIOChannelSocket *ioc,
                           Error **errp);
 
 
-#endif /* QIO_CHANNEL_SOCKET_H__ */
+#endif /* QIO_CHANNEL_SOCKET_H */
diff --git a/include/io/channel-tls.h b/include/io/channel-tls.h
index 322eccbaae..d157eb10e8 100644
--- a/include/io/channel-tls.h
+++ b/include/io/channel-tls.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QIO_CHANNEL_TLS_H__
-#define QIO_CHANNEL_TLS_H__
+#ifndef QIO_CHANNEL_TLS_H
+#define QIO_CHANNEL_TLS_H
 
 #include "io/channel.h"
 #include "io/task.h"
@@ -139,4 +139,4 @@ void qio_channel_tls_handshake(QIOChannelTLS *ioc,
 QCryptoTLSSession *
 qio_channel_tls_get_session(QIOChannelTLS *ioc);
 
-#endif /* QIO_CHANNEL_TLS_H__ */
+#endif /* QIO_CHANNEL_TLS_H */
diff --git a/include/io/channel-util.h b/include/io/channel-util.h
index c93af82884..c0b79cf603 100644
--- a/include/io/channel-util.h
+++ b/include/io/channel-util.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QIO_CHANNEL_UTIL_H__
-#define QIO_CHANNEL_UTIL_H__
+#ifndef QIO_CHANNEL_UTIL_H
+#define QIO_CHANNEL_UTIL_H
 
 #include "io/channel.h"
 
@@ -49,4 +49,4 @@
 QIOChannel *qio_channel_new_fd(int fd,
                                Error **errp);
 
-#endif /* QIO_CHANNEL_UTIL_H__ */
+#endif /* QIO_CHANNEL_UTIL_H */
diff --git a/include/io/channel-watch.h b/include/io/channel-watch.h
index 76d764223e..63bc4ae2d9 100644
--- a/include/io/channel-watch.h
+++ b/include/io/channel-watch.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QIO_CHANNEL_WATCH_H__
-#define QIO_CHANNEL_WATCH_H__
+#ifndef QIO_CHANNEL_WATCH_H
+#define QIO_CHANNEL_WATCH_H
 
 #include "io/channel.h"
 
@@ -87,4 +87,4 @@ GSource *qio_channel_create_fd_pair_watch(QIOChannel *ioc,
                                           int fdwrite,
                                           GIOCondition condition);
 
-#endif /* QIO_CHANNEL_WATCH_H__ */
+#endif /* QIO_CHANNEL_WATCH_H */
diff --git a/include/io/channel-websock.h b/include/io/channel-websock.h
index 0dc21cc56d..3c9ff84727 100644
--- a/include/io/channel-websock.h
+++ b/include/io/channel-websock.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QIO_CHANNEL_WEBSOCK_H__
-#define QIO_CHANNEL_WEBSOCK_H__
+#ifndef QIO_CHANNEL_WEBSOCK_H
+#define QIO_CHANNEL_WEBSOCK_H
 
 #include "io/channel.h"
 #include "qemu/buffer.h"
@@ -105,4 +105,4 @@ void qio_channel_websock_handshake(QIOChannelWebsock *ioc,
                                    gpointer opaque,
                                    GDestroyNotify destroy);
 
-#endif /* QIO_CHANNEL_WEBSOCK_H__ */
+#endif /* QIO_CHANNEL_WEBSOCK_H */
diff --git a/include/io/channel.h b/include/io/channel.h
index e52f059310..752e89f4dc 100644
--- a/include/io/channel.h
+++ b/include/io/channel.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QIO_CHANNEL_H__
-#define QIO_CHANNEL_H__
+#ifndef QIO_CHANNEL_H
+#define QIO_CHANNEL_H
 
 #include "qemu-common.h"
 #include "qom/object.h"
@@ -502,4 +502,4 @@ void qio_channel_yield(QIOChannel *ioc,
 void qio_channel_wait(QIOChannel *ioc,
                       GIOCondition condition);
 
-#endif /* QIO_CHANNEL_H__ */
+#endif /* QIO_CHANNEL_H */
diff --git a/include/io/task.h b/include/io/task.h
index df9499aa3a..42028cb424 100644
--- a/include/io/task.h
+++ b/include/io/task.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QIO_TASK_H__
-#define QIO_TASK_H__
+#ifndef QIO_TASK_H
+#define QIO_TASK_H
 
 #include "qemu-common.h"
 #include "qom/object.h"
@@ -252,4 +252,4 @@ void qio_task_abort(QIOTask *task,
  */
 Object *qio_task_get_source(QIOTask *task);
 
-#endif /* QIO_TASK_H__ */
+#endif /* QIO_TASK_H */
diff --git a/include/libdecnumber/decContext.h b/include/libdecnumber/decContext.h
index 01365e2313..cea6e4279e 100644
--- a/include/libdecnumber/decContext.h
+++ b/include/libdecnumber/decContext.h
@@ -50,8 +50,9 @@
 /*								      */
 /* ------------------------------------------------------------------ */
 
-#if !defined(DECCONTEXT)
-  #define DECCONTEXT
+#ifndef DECCONTEXT_H
+#define DECCONTEXT_H
+
   #define DECCNAME     "decContext"			/* Short name */
   #define DECCFULLNAME "Decimal Context Descriptor"   /* Verbose name */
   #define DECCAUTHOR   "Mike Cowlishaw"		      /* Who to blame */
diff --git a/include/libdecnumber/decNumber.h b/include/libdecnumber/decNumber.h
index 9fa4e6a0c9..aa115fed07 100644
--- a/include/libdecnumber/decNumber.h
+++ b/include/libdecnumber/decNumber.h
@@ -32,15 +32,14 @@
 /* Decimal Number arithmetic module header			      */
 /* ------------------------------------------------------------------ */
 
-#if !defined(DECNUMBER)
-  #define DECNUMBER
+#ifndef DECNUMBER_H
+#define DECNUMBER_H
+
   #define DECNAME     "decNumber"			/* Short name */
   #define DECFULLNAME "Decimal Number Module"	      /* Verbose name */
   #define DECAUTHOR   "Mike Cowlishaw"		      /* Who to blame */
 
-  #if !defined(DECCONTEXT)
-    #include "libdecnumber/decContext.h"
-  #endif
+  #include "libdecnumber/decContext.h"
 
   /* Bit settings for decNumber.bits				      */
   #define DECNEG    0x80      /* Sign; 1=negative, 0=positive or zero */
diff --git a/include/libdecnumber/decNumberLocal.h b/include/libdecnumber/decNumberLocal.h
index 94fb512923..12cf1d8b6f 100644
--- a/include/libdecnumber/decNumberLocal.h
+++ b/include/libdecnumber/decNumberLocal.h
@@ -37,8 +37,9 @@
 /* decNumber.h or one of decDouble (etc.) must be included first.     */
 /* ------------------------------------------------------------------ */
 
-#if !defined(DECNUMBERLOC)
-  #define DECNUMBERLOC
+#ifndef DECNUMBERLOCAL_H
+#define DECNUMBERLOCAL_H
+
   #define DECVERSION	"decNumber 3.53" /* Package Version [16 max.] */
   #define DECNLAUTHOR	"Mike Cowlishaw"	      /* Who to blame */
 
@@ -658,6 +659,4 @@
   /* [end of format-dependent macros and constants]		      */
   #endif
 
-#else
-  #error decNumberLocal included more than once
 #endif
diff --git a/include/libdecnumber/dpd/decimal128.h b/include/libdecnumber/dpd/decimal128.h
index 7d9ee24f85..aff261e556 100644
--- a/include/libdecnumber/dpd/decimal128.h
+++ b/include/libdecnumber/dpd/decimal128.h
@@ -32,8 +32,9 @@
 /* Decimal 128-bit format module header				      */
 /* ------------------------------------------------------------------ */
 
-#if !defined(DECIMAL128)
-  #define DECIMAL128
+#ifndef DECIMAL128_H
+#define DECIMAL128_H
+
   #define DEC128NAME	 "decimal128"		      /* Short name   */
   #define DEC128FULLNAME "Decimal 128-bit Number"     /* Verbose name */
   #define DEC128AUTHOR	 "Mike Cowlishaw"	      /* Who to blame */
@@ -59,9 +60,7 @@
   #ifndef DECNUMDIGITS
     #define DECNUMDIGITS DECIMAL128_Pmax /* size if not already defined*/
   #endif
-  #ifndef DECNUMBER
-    #include "libdecnumber/decNumber.h"
-  #endif
+  #include "libdecnumber/decNumber.h"
 
   /* Decimal 128-bit type, accessible by bytes			      */
   typedef struct {
diff --git a/include/libdecnumber/dpd/decimal32.h b/include/libdecnumber/dpd/decimal32.h
index de313e0024..6cb9e43620 100644
--- a/include/libdecnumber/dpd/decimal32.h
+++ b/include/libdecnumber/dpd/decimal32.h
@@ -32,8 +32,9 @@
 /* Decimal 32-bit format module header				      */
 /* ------------------------------------------------------------------ */
 
-#if !defined(DECIMAL32)
-  #define DECIMAL32
+#ifndef DECIMAL32_H
+#define DECIMAL32_H
+
   #define DEC32NAME	"decimal32"		      /* Short name   */
   #define DEC32FULLNAME "Decimal 32-bit Number"	      /* Verbose name */
   #define DEC32AUTHOR	"Mike Cowlishaw"	      /* Who to blame */
@@ -59,9 +60,7 @@
   #ifndef DECNUMDIGITS
     #define DECNUMDIGITS DECIMAL32_Pmax /* size if not already defined*/
   #endif
-  #ifndef DECNUMBER
-    #include "libdecnumber/decNumber.h"
-  #endif
+  #include "libdecnumber/decNumber.h"
 
   /* Decimal 32-bit type, accessible by bytes */
   typedef struct {
diff --git a/include/libdecnumber/dpd/decimal64.h b/include/libdecnumber/dpd/decimal64.h
index 2f6c049402..f29e57064d 100644
--- a/include/libdecnumber/dpd/decimal64.h
+++ b/include/libdecnumber/dpd/decimal64.h
@@ -32,8 +32,9 @@
 /* Decimal 64-bit format module header				      */
 /* ------------------------------------------------------------------ */
 
-#if !defined(DECIMAL64)
-  #define DECIMAL64
+#ifndef DECIMAL64_H
+#define DECIMAL64_H
+
   #define DEC64NAME	"decimal64"		      /* Short name   */
   #define DEC64FULLNAME "Decimal 64-bit Number"	      /* Verbose name */
   #define DEC64AUTHOR	"Mike Cowlishaw"	      /* Who to blame */
@@ -61,9 +62,7 @@
   #ifndef DECNUMDIGITS
     #define DECNUMDIGITS DECIMAL64_Pmax /* size if not already defined*/
   #endif
-  #ifndef DECNUMBER
-    #include "libdecnumber/decNumber.h"
-  #endif
+  #include "libdecnumber/decNumber.h"
 
   /* Decimal 64-bit type, accessible by bytes			      */
   typedef struct {
diff --git a/include/migration/block.h b/include/migration/block.h
index ffa8ac0bdd..41a1ac8f79 100644
--- a/include/migration/block.h
+++ b/include/migration/block.h
@@ -11,8 +11,8 @@
  *
  */
 
-#ifndef BLOCK_MIGRATION_H
-#define BLOCK_MIGRATION_H
+#ifndef MIGRATION_BLOCK_H
+#define MIGRATION_BLOCK_H
 
 void blk_mig_init(void);
 int blk_mig_active(void);
@@ -20,4 +20,4 @@ uint64_t blk_mig_bytes_transferred(void);
 uint64_t blk_mig_bytes_remaining(void);
 uint64_t blk_mig_bytes_total(void);
 
-#endif /* BLOCK_MIGRATION_H */
+#endif /* MIGRATION_BLOCK_H */
diff --git a/include/migration/qemu-file.h b/include/migration/qemu-file.h
index 2409a98967..abedd466c9 100644
--- a/include/migration/qemu-file.h
+++ b/include/migration/qemu-file.h
@@ -21,8 +21,10 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
+
 #ifndef QEMU_FILE_H
-#define QEMU_FILE_H 1
+#define QEMU_FILE_H
+
 #include "qemu-common.h"
 #include "exec/cpu-common.h"
 #include "io/channel.h"
diff --git a/include/migration/vmstate.h b/include/migration/vmstate.h
index 15ea7679bd..1638ee57f7 100644
--- a/include/migration/vmstate.h
+++ b/include/migration/vmstate.h
@@ -23,11 +23,12 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
+
 #ifndef QEMU_VMSTATE_H
-#define QEMU_VMSTATE_H 1
+#define QEMU_VMSTATE_H
 
 #ifndef CONFIG_USER_ONLY
-#include <migration/qemu-file.h>
+#include "migration/qemu-file.h"
 #endif
 #include "migration/qjson.h"
 
diff --git a/include/monitor/hmp-target.h b/include/monitor/hmp-target.h
index bc2c9c04d0..454e8ed155 100644
--- a/include/monitor/hmp-target.h
+++ b/include/monitor/hmp-target.h
@@ -21,8 +21,9 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
-#ifndef MONITOR_COMMON_H
-#define MONITOR_COMMON_H
+
+#ifndef MONITOR_HMP_TARGET_H
+#define MONITOR_HMP_TARGET_H
 
 #define MD_TLONG 0
 #define MD_I32   1
@@ -46,4 +47,4 @@ void hmp_mce(Monitor *mon, const QDict *qdict);
 void hmp_info_local_apic(Monitor *mon, const QDict *qdict);
 void hmp_info_io_apic(Monitor *mon, const QDict *qdict);
 
-#endif /* MONITOR_COMMON */
+#endif /* MONITOR_HMP_TARGET_H */
diff --git a/include/monitor/monitor.h b/include/monitor/monitor.h
index aa0f37320c..c5c9ea292f 100644
--- a/include/monitor/monitor.h
+++ b/include/monitor/monitor.h
@@ -51,4 +51,4 @@ int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd);
 void monitor_fdset_dup_fd_remove(int dup_fd);
 int monitor_fdset_dup_fd_find(int dup_fd);
 
-#endif /* !MONITOR_H */
+#endif /* MONITOR_H */
diff --git a/include/monitor/qdev.h b/include/monitor/qdev.h
index c4b8a05146..8e504bc66b 100644
--- a/include/monitor/qdev.h
+++ b/include/monitor/qdev.h
@@ -1,5 +1,5 @@
-#ifndef QEMU_QDEV_MONITOR_H
-#define QEMU_QDEV_MONITOR_H
+#ifndef MONITOR_QDEV_H
+#define MONITOR_QDEV_H
 
 #include "hw/qdev-core.h"
 
diff --git a/include/net/vhost-user.h b/include/net/vhost-user.h
index efae35d57e..5bcd8a6285 100644
--- a/include/net/vhost-user.h
+++ b/include/net/vhost-user.h
@@ -8,11 +8,11 @@
  *
  */
 
-#ifndef VHOST_USER_H_
-#define VHOST_USER_H_
+#ifndef VHOST_USER_H
+#define VHOST_USER_H
 
 struct vhost_net;
 struct vhost_net *vhost_user_get_vhost_net(NetClientState *nc);
 uint64_t vhost_user_get_acked_features(NetClientState *nc);
 
-#endif /* VHOST_USER_H_ */
+#endif /* VHOST_USER_H */
diff --git a/include/qapi/qmp/dispatch.h b/include/qapi/qmp/dispatch.h
index 5609946a16..48c11b66d1 100644
--- a/include/qapi/qmp/dispatch.h
+++ b/include/qapi/qmp/dispatch.h
@@ -11,8 +11,8 @@
  *
  */
 
-#ifndef QMP_CORE_H
-#define QMP_CORE_H
+#ifndef QAPI_QMP_DISPATCH_H
+#define QAPI_QMP_DISPATCH_H
 
 #include "qapi/qmp/qobject.h"
 #include "qapi/qmp/qdict.h"
@@ -48,4 +48,3 @@ typedef void (*qmp_cmd_callback_fn)(QmpCommand *cmd, void *opaque);
 void qmp_for_each_command(qmp_cmd_callback_fn fn, void *opaque);
 
 #endif
-
diff --git a/include/qapi/qmp/qerror.h b/include/qapi/qmp/qerror.h
index d08652aaa5..6586c9fa62 100644
--- a/include/qapi/qmp/qerror.h
+++ b/include/qapi/qmp/qerror.h
@@ -19,9 +19,6 @@
 #define QERR_BASE_NOT_FOUND \
     "Base '%s' not found"
 
-#define QERR_BLOCK_JOB_NOT_READY \
-    "The active block job for device '%s' cannot be completed"
-
 #define QERR_BUS_NO_HOTPLUG \
     "Bus '%s' does not support hotplugging"
 
diff --git a/include/qapi/qmp/types.h b/include/qapi/qmp/types.h
index f21ecf48fe..27cfbd84e5 100644
--- a/include/qapi/qmp/types.h
+++ b/include/qapi/qmp/types.h
@@ -10,8 +10,8 @@
  * See the COPYING.LIB file in the top-level directory.
  */
 
-#ifndef QEMU_OBJECTS_H
-#define QEMU_OBJECTS_H
+#ifndef QAPI_QMP_TYPES_H
+#define QAPI_QMP_TYPES_H
 
 #include "qapi/qmp/qobject.h"
 #include "qapi/qmp/qint.h"
@@ -21,4 +21,4 @@
 #include "qapi/qmp/qdict.h"
 #include "qapi/qmp/qlist.h"
 
-#endif /* QEMU_OBJECTS_H */
+#endif /* QAPI_QMP_TYPES_H */
diff --git a/include/qapi/visitor.h b/include/qapi/visitor.h
index fb8f4eb6ec..6c77a913db 100644
--- a/include/qapi/visitor.h
+++ b/include/qapi/visitor.h
@@ -11,8 +11,9 @@
  * See the COPYING.LIB file in the top-level directory.
  *
  */
-#ifndef QAPI_VISITOR_CORE_H
-#define QAPI_VISITOR_CORE_H
+
+#ifndef QAPI_VISITOR_H
+#define QAPI_VISITOR_H
 
 #include "qapi/qmp/qobject.h"
 
diff --git a/include/qemu/acl.h b/include/qemu/acl.h
index 116487e282..7c44119a47 100644
--- a/include/qemu/acl.h
+++ b/include/qemu/acl.h
@@ -22,8 +22,8 @@
  * THE SOFTWARE.
  */
 
-#ifndef __QEMU_ACL_H__
-#define __QEMU_ACL_H__
+#ifndef QEMU_ACL_H
+#define QEMU_ACL_H
 
 #include "qemu/queue.h"
 
@@ -63,12 +63,4 @@ int qemu_acl_insert(qemu_acl *acl,
 int qemu_acl_remove(qemu_acl *acl,
 		    const char *match);
 
-#endif /* __QEMU_ACL_H__ */
-
-/*
- * Local variables:
- *  c-indent-level: 4
- *  c-basic-offset: 4
- *  tab-width: 8
- * End:
- */
+#endif /* QEMU_ACL_H */
diff --git a/include/qemu/atomic.h b/include/qemu/atomic.h
index 7a590969b5..7e13fca351 100644
--- a/include/qemu/atomic.h
+++ b/include/qemu/atomic.h
@@ -12,10 +12,8 @@
  * atomic primitive is meant to provide.
  */
 
-#ifndef __QEMU_ATOMIC_H
-#define __QEMU_ATOMIC_H 1
-
-
+#ifndef QEMU_ATOMIC_H
+#define QEMU_ATOMIC_H
 
 /* Compiler barrier */
 #define barrier()   ({ asm volatile("" ::: "memory"); (void)0; })
@@ -366,4 +364,4 @@
 #define atomic_or(ptr, n)      ((void) __sync_fetch_and_or(ptr, n))
 
 #endif /* __ATOMIC_RELAXED */
-#endif /* __QEMU_ATOMIC_H */
+#endif /* QEMU_ATOMIC_H */
diff --git a/include/qemu/base64.h b/include/qemu/base64.h
index 793708dc3a..815d85267d 100644
--- a/include/qemu/base64.h
+++ b/include/qemu/base64.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QEMU_BASE64_H__
-#define QEMU_BASE64_H__
+#ifndef QEMU_BASE64_H
+#define QEMU_BASE64_H
 
 #include "qemu-common.h"
 
@@ -55,4 +55,4 @@ uint8_t *qbase64_decode(const char *input,
                         Error **errp);
 
 
-#endif /* QEMU_BUFFER_H__ */
+#endif /* QEMU_BASE64_H */
diff --git a/include/qemu/bcd.h b/include/qemu/bcd.h
index b4c9b64b8f..dfebacf1fc 100644
--- a/include/qemu/bcd.h
+++ b/include/qemu/bcd.h
@@ -1,5 +1,5 @@
 #ifndef QEMU_BCD_H
-#define QEMU_BCD_H 1
+#define QEMU_BCD_H
 
 /* Convert a byte between binary and BCD.  */
 static inline uint8_t to_bcd(uint8_t val)
diff --git a/include/qemu/bswap.h b/include/qemu/bswap.h
index ce3c42e4d9..09c78fd28a 100644
--- a/include/qemu/bswap.h
+++ b/include/qemu/bswap.h
@@ -80,6 +80,64 @@ static inline void bswap64s(uint64_t *s)
 #define be_bswaps(p, size) do { *p = glue(bswap, size)(*p); } while(0)
 #endif
 
+/**
+ * Endianness conversion functions between host cpu and specified endianness.
+ * (We list the complete set of prototypes produced by the macros below
+ * to assist people who search the headers to find their definitions.)
+ *
+ * uint16_t le16_to_cpu(uint16_t v);
+ * uint32_t le32_to_cpu(uint32_t v);
+ * uint64_t le64_to_cpu(uint64_t v);
+ * uint16_t be16_to_cpu(uint16_t v);
+ * uint32_t be32_to_cpu(uint32_t v);
+ * uint64_t be64_to_cpu(uint64_t v);
+ *
+ * Convert the value @v from the specified format to the native
+ * endianness of the host CPU by byteswapping if necessary, and
+ * return the converted value.
+ *
+ * uint16_t cpu_to_le16(uint16_t v);
+ * uint32_t cpu_to_le32(uint32_t v);
+ * uint64_t cpu_to_le64(uint64_t v);
+ * uint16_t cpu_to_be16(uint16_t v);
+ * uint32_t cpu_to_be32(uint32_t v);
+ * uint64_t cpu_to_be64(uint64_t v);
+ *
+ * Convert the value @v from the native endianness of the host CPU to
+ * the specified format by byteswapping if necessary, and return
+ * the converted value.
+ *
+ * void le16_to_cpus(uint16_t *v);
+ * void le32_to_cpus(uint32_t *v);
+ * void le64_to_cpus(uint64_t *v);
+ * void be16_to_cpus(uint16_t *v);
+ * void be32_to_cpus(uint32_t *v);
+ * void be64_to_cpus(uint64_t *v);
+ *
+ * Do an in-place conversion of the value pointed to by @v from the
+ * specified format to the native endianness of the host CPU.
+ *
+ * void cpu_to_le16s(uint16_t *v);
+ * void cpu_to_le32s(uint32_t *v);
+ * void cpu_to_le64s(uint64_t *v);
+ * void cpu_to_be16s(uint16_t *v);
+ * void cpu_to_be32s(uint32_t *v);
+ * void cpu_to_be64s(uint64_t *v);
+ *
+ * Do an in-place conversion of the value pointed to by @v from the
+ * native endianness of the host CPU to the specified format.
+ *
+ * Both X_to_cpu() and cpu_to_X() perform the same operation; you
+ * should use whichever one is better documenting of the function your
+ * code is performing.
+ *
+ * Do not use these functions for conversion of values which are in guest
+ * memory, since the data may not be sufficiently aligned for the host CPU's
+ * load and store instructions. Instead you should use the ld*_p() and
+ * st*_p() functions, which perform loads and stores of data of any
+ * required size and endianness and handle possible misalignment.
+ */
+
 #define CPU_CONVERT(endian, size, type)\
 static inline type endian ## size ## _to_cpu(type v)\
 {\
@@ -99,16 +157,6 @@ static inline void endian ## size ## _to_cpus(type *p)\
 static inline void cpu_to_ ## endian ## size ## s(type *p)\
 {\
     glue(endian, _bswaps)(p, size);\
-}\
-\
-static inline type endian ## size ## _to_cpup(const type *p)\
-{\
-    return glue(glue(endian, size), _to_cpu)(*p);\
-}\
-\
-static inline void cpu_to_ ## endian ## size ## w(type *p, type v)\
-{\
-    *p = glue(glue(cpu_to_, endian), size)(v);\
 }
 
 CPU_CONVERT(be, 16, uint16_t)
@@ -126,7 +174,7 @@ static inline uint32_t qemu_bswap_len(uint32_t value, int len)
 }
 
 /*
- * Same as cpu_to_le{16,23}, except that gcc will figure the result is
+ * Same as cpu_to_le{16,32}, except that gcc will figure the result is
  * a compile-time constant if you pass in a constant.  So this can be
  * used to initialize static variables.
  */
diff --git a/include/qemu/buffer.h b/include/qemu/buffer.h
index dead9b77e1..b2ead1f051 100644
--- a/include/qemu/buffer.h
+++ b/include/qemu/buffer.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef QEMU_BUFFER_H__
-#define QEMU_BUFFER_H__
+#ifndef QEMU_BUFFER_H
+#define QEMU_BUFFER_H
 
 #include "qemu-common.h"
 
@@ -158,4 +158,4 @@ void buffer_move_empty(Buffer *to, Buffer *from);
  */
 void buffer_move(Buffer *to, Buffer *from);
 
-#endif /* QEMU_BUFFER_H__ */
+#endif /* QEMU_BUFFER_H */
diff --git a/include/qemu/config-file.h b/include/qemu/config-file.h
index 8603e86395..8d4b2b6d94 100644
--- a/include/qemu/config-file.h
+++ b/include/qemu/config-file.h
@@ -1,5 +1,5 @@
-#ifndef QEMU_CONFIG_H
-#define QEMU_CONFIG_H
+#ifndef QEMU_CONFIG_FILE_H
+#define QEMU_CONFIG_FILE_H
 
 #include "qemu/option.h"
 #include "qapi/qmp/qdict.h"
@@ -27,4 +27,4 @@ void qemu_config_parse_qdict(QDict *options, QemuOptsList **lists,
  */
 int qemu_read_default_config_files(bool userconfig);
 
-#endif /* QEMU_CONFIG_H */
+#endif /* QEMU_CONFIG_FILE_H */
diff --git a/include/qemu/coroutine.h b/include/qemu/coroutine.h
index 305fe76c29..ac8d4c9cc8 100644
--- a/include/qemu/coroutine.h
+++ b/include/qemu/coroutine.h
@@ -61,16 +61,14 @@ typedef void coroutine_fn CoroutineEntry(void *opaque);
  * Create a new coroutine
  *
  * Use qemu_coroutine_enter() to actually transfer control to the coroutine.
+ * The opaque argument is passed as the argument to the entry point.
  */
-Coroutine *qemu_coroutine_create(CoroutineEntry *entry);
+Coroutine *qemu_coroutine_create(CoroutineEntry *entry, void *opaque);
 
 /**
  * Transfer control to a coroutine
- *
- * The opaque argument is passed as the argument to the entry point when
- * entering the coroutine for the first time.  It is subsequently ignored.
  */
-void qemu_coroutine_enter(Coroutine *coroutine, void *opaque);
+void qemu_coroutine_enter(Coroutine *coroutine);
 
 /**
  * Transfer control back to a coroutine's caller
@@ -102,7 +100,7 @@ bool qemu_in_coroutine(void);
  * are built.
  */
 typedef struct CoQueue {
-    QTAILQ_HEAD(, Coroutine) entries;
+    QSIMPLEQ_HEAD(, Coroutine) entries;
 } CoQueue;
 
 /**
diff --git a/include/qemu/coroutine_int.h b/include/qemu/coroutine_int.h
index 42d6838401..581a7f5140 100644
--- a/include/qemu/coroutine_int.h
+++ b/include/qemu/coroutine_int.h
@@ -41,8 +41,8 @@ struct Coroutine {
     QSLIST_ENTRY(Coroutine) pool_next;
 
     /* Coroutines that should be woken up when we yield or terminate */
-    QTAILQ_HEAD(, Coroutine) co_queue_wakeup;
-    QTAILQ_ENTRY(Coroutine) co_queue_next;
+    QSIMPLEQ_HEAD(, Coroutine) co_queue_wakeup;
+    QSIMPLEQ_ENTRY(Coroutine) co_queue_next;
 };
 
 Coroutine *qemu_coroutine_new(void);
diff --git a/include/qemu/cutils.h b/include/qemu/cutils.h
index db7adadcf9..3e4ea236f0 100644
--- a/include/qemu/cutils.h
+++ b/include/qemu/cutils.h
@@ -1,5 +1,5 @@
 #ifndef QEMU_CUTILS_H
-#define QEMU_CUTILS_H 1
+#define QEMU_CUTILS_H
 
 #include "qemu/fprintf-fn.h"
 
diff --git a/include/qemu/error-report.h b/include/qemu/error-report.h
index 7a2a363fb3..499ec8b12a 100644
--- a/include/qemu/error-report.h
+++ b/include/qemu/error-report.h
@@ -10,9 +10,8 @@
  * See the COPYING file in the top-level directory.
  */
 
-#ifndef QEMU_ERROR_H
-#define QEMU_ERROR_H
-
+#ifndef QEMU_ERROR_REPORT_H
+#define QEMU_ERROR_REPORT_H
 
 typedef struct Location {
     /* all members are private to qemu-error.c */
diff --git a/include/qemu/fifo8.h b/include/qemu/fifo8.h
index 8820780669..24b364462d 100644
--- a/include/qemu/fifo8.h
+++ b/include/qemu/fifo8.h
@@ -1,5 +1,5 @@
-#ifndef FIFO_H
-#define FIFO_H
+#ifndef QEMU_FIFO8_H
+#define QEMU_FIFO8_H
 
 #include "migration/vmstate.h"
 
@@ -157,4 +157,4 @@ extern const VMStateDescription vmstate_fifo8;
     .offset     = vmstate_offset_value(_state, _field, Fifo8),       \
 }
 
-#endif /* FIFO_H */
+#endif /* QEMU_FIFO8_H */
diff --git a/include/qemu/fprintf-fn.h b/include/qemu/fprintf-fn.h
index b6bad35b1b..9068a960b3 100644
--- a/include/qemu/fprintf-fn.h
+++ b/include/qemu/fprintf-fn.h
@@ -6,8 +6,7 @@
  */
 
 #ifndef QEMU_FPRINTF_FN_H
-#define QEMU_FPRINTF_FN_H 1
-
+#define QEMU_FPRINTF_FN_H
 
 typedef int (*fprintf_function)(FILE *f, const char *fmt, ...)
     GCC_FMT_ATTR(2, 3);
diff --git a/include/qemu/hbitmap.h b/include/qemu/hbitmap.h
index e29188c0ad..8ab721e5aa 100644
--- a/include/qemu/hbitmap.h
+++ b/include/qemu/hbitmap.h
@@ -10,7 +10,7 @@
  */
 
 #ifndef HBITMAP_H
-#define HBITMAP_H 1
+#define HBITMAP_H
 
 #include "bitops.h"
 #include "host-utils.h"
diff --git a/include/qemu/help_option.h b/include/qemu/help_option.h
index e39a66e77b..328d2a89fd 100644
--- a/include/qemu/help_option.h
+++ b/include/qemu/help_option.h
@@ -1,5 +1,5 @@
 #ifndef QEMU_HELP_OPTION_H
-#define QEMU_HELP_OPTION_H 1
+#define QEMU_HELP_OPTION_H
 
 /**
  * is_help_option:
diff --git a/include/qemu/host-utils.h b/include/qemu/host-utils.h
index 3de7d4ec55..46187bbc7e 100644
--- a/include/qemu/host-utils.h
+++ b/include/qemu/host-utils.h
@@ -22,8 +22,9 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
+
 #ifndef HOST_UTILS_H
-#define HOST_UTILS_H 1
+#define HOST_UTILS_H
 
 #include "qemu/bswap.h"
 
diff --git a/include/qemu/id.h b/include/qemu/id.h
index 7d90335afb..40c70103e4 100644
--- a/include/qemu/id.h
+++ b/include/qemu/id.h
@@ -1,5 +1,5 @@
 #ifndef QEMU_ID_H
-#define QEMU_ID_H 1
+#define QEMU_ID_H
 
 typedef enum IdSubSystems {
     ID_QDEV,
diff --git a/include/qemu/main-loop.h b/include/qemu/main-loop.h
index 19b5de3dd5..470f600bbc 100644
--- a/include/qemu/main-loop.h
+++ b/include/qemu/main-loop.h
@@ -23,7 +23,7 @@
  */
 
 #ifndef QEMU_MAIN_LOOP_H
-#define QEMU_MAIN_LOOP_H 1
+#define QEMU_MAIN_LOOP_H
 
 #include "block/aio.h"
 
@@ -64,11 +64,11 @@ int qemu_init_main_loop(Error **errp);
  *
  *     void enter_co_bh(void *opaque) {
  *         QEMUCoroutine *co = opaque;
- *         qemu_coroutine_enter(co, NULL);
+ *         qemu_coroutine_enter(co);
  *     }
  *
  *     ...
- *     QEMUCoroutine *co = qemu_coroutine_create(coroutine_entry);
+ *     QEMUCoroutine *co = qemu_coroutine_create(coroutine_entry, NULL);
  *     QEMUBH *start_bh = qemu_bh_new(enter_co_bh, co);
  *     qemu_bh_schedule(start_bh);
  *     while (...) {
diff --git a/include/qemu/mmap-alloc.h b/include/qemu/mmap-alloc.h
index 0899b2f01e..933c024ac5 100644
--- a/include/qemu/mmap-alloc.h
+++ b/include/qemu/mmap-alloc.h
@@ -1,5 +1,5 @@
-#ifndef QEMU_MMAP_ALLOC
-#define QEMU_MMAP_ALLOC
+#ifndef QEMU_MMAP_ALLOC_H
+#define QEMU_MMAP_ALLOC_H
 
 #include "qemu-common.h"
 
diff --git a/include/qemu/option.h b/include/qemu/option.h
index 8542d2dfd6..1f9e3f939d 100644
--- a/include/qemu/option.h
+++ b/include/qemu/option.h
@@ -23,8 +23,8 @@
  * THE SOFTWARE.
  */
 
-#ifndef QEMU_OPTIONS_H
-#define QEMU_OPTIONS_H
+#ifndef QEMU_OPTION_H
+#define QEMU_OPTION_H
 
 #include "qemu/queue.h"
 #include "qapi/qmp/qdict.h"
diff --git a/include/qemu/option_int.h b/include/qemu/option_int.h
index 6432c1a8c9..26b1d9e4d6 100644
--- a/include/qemu/option_int.h
+++ b/include/qemu/option_int.h
@@ -23,8 +23,8 @@
  * THE SOFTWARE.
  */
 
-#ifndef QEMU_OPTIONS_INTERNAL_H
-#define QEMU_OPTIONS_INTERNAL_H
+#ifndef QEMU_OPTION_INT_H
+#define QEMU_OPTION_INT_H
 
 #include "qemu/option.h"
 #include "qemu/error-report.h"
diff --git a/include/qemu/osdep.h b/include/qemu/osdep.h
index e4c6ae6b38..fbb875959f 100644
--- a/include/qemu/osdep.h
+++ b/include/qemu/osdep.h
@@ -279,6 +279,9 @@ int qemu_madvise(void *addr, size_t len, int advice);
 
 int qemu_open(const char *name, int flags, ...);
 int qemu_close(int fd);
+#ifndef _WIN32
+int qemu_dup(int fd);
+#endif
 
 #if defined(__HAIKU__) && defined(__i386__)
 #define FMT_pid "%ld"
diff --git a/include/qemu/path.h b/include/qemu/path.h
index ed5fee086f..c6292a9709 100644
--- a/include/qemu/path.h
+++ b/include/qemu/path.h
@@ -1,5 +1,5 @@
 #ifndef QEMU_PATH_H
-#define QEMU_PATH_H 1
+#define QEMU_PATH_H
 
 void init_paths(const char *prefix);
 const char *path(const char *pathname);
diff --git a/include/qemu/queue.h b/include/qemu/queue.h
index f781aa20a8..c2b6c8149d 100644
--- a/include/qemu/queue.h
+++ b/include/qemu/queue.h
@@ -37,8 +37,8 @@
  *      @(#)queue.h     8.5 (Berkeley) 8/20/94
  */
 
-#ifndef QEMU_SYS_QUEUE_H_
-#define QEMU_SYS_QUEUE_H_
+#ifndef QEMU_SYS_QUEUE_H
+#define QEMU_SYS_QUEUE_H
 
 /*
  * This file defines four types of data structures: singly-linked lists,
@@ -436,4 +436,4 @@ struct {                                                                \
 #define QTAILQ_PREV(elm, headname, field) \
         (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last))
 
-#endif  /* !QEMU_SYS_QUEUE_H_ */
+#endif /* QEMU_SYS_QUEUE_H */
diff --git a/include/qemu/ratelimit.h b/include/qemu/ratelimit.h
index d413a4a696..8da1232574 100644
--- a/include/qemu/ratelimit.h
+++ b/include/qemu/ratelimit.h
@@ -12,37 +12,62 @@
  */
 
 #ifndef QEMU_RATELIMIT_H
-#define QEMU_RATELIMIT_H 1
+#define QEMU_RATELIMIT_H
 
 typedef struct {
-    int64_t next_slice_time;
+    int64_t slice_start_time;
+    int64_t slice_end_time;
     uint64_t slice_quota;
     uint64_t slice_ns;
     uint64_t dispatched;
 } RateLimit;
 
+/** Calculate and return delay for next request in ns
+ *
+ * Record that we sent @p n data units. If we may send more data units
+ * in the current time slice, return 0 (i.e. no delay). Otherwise
+ * return the amount of time (in ns) until the start of the next time
+ * slice that will permit sending the next chunk of data.
+ *
+ * Recording sent data units even after exceeding the quota is
+ * permitted; the time slice will be extended accordingly.
+ */
 static inline int64_t ratelimit_calculate_delay(RateLimit *limit, uint64_t n)
 {
     int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
+    uint64_t delay_slices;
 
-    if (limit->next_slice_time < now) {
-        limit->next_slice_time = now + limit->slice_ns;
+    assert(limit->slice_quota && limit->slice_ns);
+
+    if (limit->slice_end_time < now) {
+        /* Previous, possibly extended, time slice finished; reset the
+         * accounting. */
+        limit->slice_start_time = now;
+        limit->slice_end_time = now + limit->slice_ns;
         limit->dispatched = 0;
     }
-    if (limit->dispatched == 0 || limit->dispatched + n <= limit->slice_quota) {
-        limit->dispatched += n;
+
+    limit->dispatched += n;
+    if (limit->dispatched < limit->slice_quota) {
+        /* We may send further data within the current time slice, no
+         * need to delay the next request. */
         return 0;
-    } else {
-        limit->dispatched = n;
-        return limit->next_slice_time - now;
     }
+
+    /* Quota exceeded. Calculate the next time slice we may start
+     * sending data again. */
+    delay_slices = (limit->dispatched + limit->slice_quota - 1) /
+        limit->slice_quota;
+    limit->slice_end_time = limit->slice_start_time +
+        delay_slices * limit->slice_ns;
+    return limit->slice_end_time - now;
 }
 
 static inline void ratelimit_set_speed(RateLimit *limit, uint64_t speed,
                                        uint64_t slice_ns)
 {
     limit->slice_ns = slice_ns;
-    limit->slice_quota = ((double)speed * slice_ns)/1000000000ULL;
+    limit->slice_quota = MAX(((double)speed * slice_ns) / 1000000000ULL, 1);
 }
 
 #endif
diff --git a/include/qemu/rcu_queue.h b/include/qemu/rcu_queue.h
index 3aca7a57e3..01be77407b 100644
--- a/include/qemu/rcu_queue.h
+++ b/include/qemu/rcu_queue.h
@@ -131,4 +131,4 @@ extern "C" {
 #ifdef __cplusplus
 }
 #endif
-#endif /* QEMU_RCU_QUEUE.H */
+#endif /* QEMU_RCU_QUEUE_H */
diff --git a/include/qemu/readline.h b/include/qemu/readline.h
index 49efe4e39b..c08cf7400e 100644
--- a/include/qemu/readline.h
+++ b/include/qemu/readline.h
@@ -60,4 +60,4 @@ ReadLineState *readline_init(ReadLinePrintfFunc *printf_func,
                              void *opaque,
                              ReadLineCompletionFunc *completion_finder);
 
-#endif /* !READLINE_H */
+#endif /* READLINE_H */
diff --git a/include/qemu/seqlock.h b/include/qemu/seqlock.h
index 4dfc055353..2e2be4c4f0 100644
--- a/include/qemu/seqlock.h
+++ b/include/qemu/seqlock.h
@@ -10,11 +10,12 @@
  * See the COPYING file in the top-level directory.
  *
  */
+
 #ifndef QEMU_SEQLOCK_H
-#define QEMU_SEQLOCK_H 1
+#define QEMU_SEQLOCK_H
 
-#include <qemu/atomic.h>
-#include <qemu/thread.h>
+#include "qemu/atomic.h"
+#include "qemu/thread.h"
 
 typedef struct QemuSeqLock QemuSeqLock;
 
diff --git a/include/qemu/sockets.h b/include/qemu/sockets.h
index 2f3763f781..5fe01fbc6c 100644
--- a/include/qemu/sockets.h
+++ b/include/qemu/sockets.h
@@ -1,6 +1,7 @@
 /* headers to use the BSD sockets */
-#ifndef QEMU_SOCKET_H
-#define QEMU_SOCKET_H
+
+#ifndef QEMU_SOCKETS_H
+#define QEMU_SOCKETS_H
 
 #ifdef _WIN32
 
@@ -121,4 +122,5 @@ SocketAddress *socket_remote_address(int fd, Error **errp);
  * Returns: the socket address in string format, or NULL on error
  */
 char *socket_address_to_string(struct SocketAddress *addr, Error **errp);
-#endif /* QEMU_SOCKET_H */
+
+#endif /* QEMU_SOCKETS_H */
diff --git a/include/qemu/thread-posix.h b/include/qemu/thread-posix.h
index eb5c7a1da1..aa03567e5e 100644
--- a/include/qemu/thread-posix.h
+++ b/include/qemu/thread-posix.h
@@ -1,6 +1,7 @@
-#ifndef __QEMU_THREAD_POSIX_H
-#define __QEMU_THREAD_POSIX_H 1
-#include "pthread.h"
+#ifndef QEMU_THREAD_POSIX_H
+#define QEMU_THREAD_POSIX_H
+
+#include <pthread.h>
 #include <semaphore.h>
 
 struct QemuMutex {
diff --git a/include/qemu/thread-win32.h b/include/qemu/thread-win32.h
index 385ff5f76a..c7ce8dcd45 100644
--- a/include/qemu/thread-win32.h
+++ b/include/qemu/thread-win32.h
@@ -1,6 +1,7 @@
-#ifndef __QEMU_THREAD_WIN32_H
-#define __QEMU_THREAD_WIN32_H 1
-#include "windows.h"
+#ifndef QEMU_THREAD_WIN32_H
+#define QEMU_THREAD_WIN32_H
+
+#include <windows.h>
 
 struct QemuMutex {
     CRITICAL_SECTION lock;
diff --git a/include/qemu/thread.h b/include/qemu/thread.h
index c5d71cf8fc..31237e93ee 100644
--- a/include/qemu/thread.h
+++ b/include/qemu/thread.h
@@ -1,5 +1,5 @@
-#ifndef __QEMU_THREAD_H
-#define __QEMU_THREAD_H 1
+#ifndef QEMU_THREAD_H
+#define QEMU_THREAD_H
 
 #include "qemu/processor.h"
 #include "qemu/atomic.h"
diff --git a/include/qemu/unicode.h b/include/qemu/unicode.h
index d8731652d2..71c72db461 100644
--- a/include/qemu/unicode.h
+++ b/include/qemu/unicode.h
@@ -1,5 +1,5 @@
 #ifndef QEMU_UNICODE_H
-#define QEMU_UNICODE_H 1
+#define QEMU_UNICODE_H
 
 int mod_utf8_codepoint(const char *s, size_t n, char **end);
 
diff --git a/include/qom/cpu.h b/include/qom/cpu.h
index cacb100f7b..a6c6ed8b57 100644
--- a/include/qom/cpu.h
+++ b/include/qom/cpu.h
@@ -60,6 +60,12 @@ typedef uint64_t vaddr;
 #define CPU_CLASS(class) OBJECT_CLASS_CHECK(CPUClass, (class), TYPE_CPU)
 #define CPU_GET_CLASS(obj) OBJECT_GET_CLASS(CPUClass, (obj), TYPE_CPU)
 
+typedef enum MMUAccessType {
+    MMU_DATA_LOAD  = 0,
+    MMU_DATA_STORE = 1,
+    MMU_INST_FETCH = 2
+} MMUAccessType;
+
 typedef struct CPUWatchpoint CPUWatchpoint;
 
 typedef void (*CPUUnassignedAccess)(CPUState *cpu, hwaddr addr,
@@ -142,7 +148,8 @@ typedef struct CPUClass {
     void (*do_interrupt)(CPUState *cpu);
     CPUUnassignedAccess do_unassigned_access;
     void (*do_unaligned_access)(CPUState *cpu, vaddr addr,
-                                int is_write, int is_user, uintptr_t retaddr);
+                                MMUAccessType access_type,
+                                int mmu_idx, uintptr_t retaddr);
     bool (*virtio_is_big_endian)(CPUState *cpu);
     int (*memory_rw_debug)(CPUState *cpu, vaddr addr,
                            uint8_t *buf, int len, bool is_write);
@@ -716,12 +723,12 @@ static inline void cpu_unassigned_access(CPUState *cpu, hwaddr addr,
 }
 
 static inline void cpu_unaligned_access(CPUState *cpu, vaddr addr,
-                                        int is_write, int is_user,
-                                        uintptr_t retaddr)
+                                        MMUAccessType access_type,
+                                        int mmu_idx, uintptr_t retaddr)
 {
     CPUClass *cc = CPU_GET_CLASS(cpu);
 
-    cc->do_unaligned_access(cpu, addr, is_write, is_user, retaddr);
+    cc->do_unaligned_access(cpu, addr, access_type, mmu_idx, retaddr);
 }
 #endif
 
diff --git a/include/sysemu/balloon.h b/include/sysemu/balloon.h
index 3f976b49e7..af49e19c78 100644
--- a/include/sysemu/balloon.h
+++ b/include/sysemu/balloon.h
@@ -11,8 +11,8 @@
  *
  */
 
-#ifndef _QEMU_BALLOON_H
-#define _QEMU_BALLOON_H
+#ifndef QEMU_BALLOON_H
+#define QEMU_BALLOON_H
 
 #include "qapi-types.h"
 
diff --git a/include/sysemu/bt.h b/include/sysemu/bt.h
index 2bc6d53cca..ddb05cd109 100644
--- a/include/sysemu/bt.h
+++ b/include/sysemu/bt.h
@@ -1,5 +1,5 @@
-#ifndef BT_HOST_H
-#define BT_HOST_H
+#ifndef SYSEMU_BT_H
+#define SYSEMU_BT_H
 
 /* BT HCI info */
 
diff --git a/include/sysemu/device_tree.h b/include/sysemu/device_tree.h
index 705650aad4..e22e5bec9c 100644
--- a/include/sysemu/device_tree.h
+++ b/include/sysemu/device_tree.h
@@ -11,8 +11,8 @@
  *
  */
 
-#ifndef __DEVICE_TREE_H__
-#define __DEVICE_TREE_H__
+#ifndef DEVICE_TREE_H
+#define DEVICE_TREE_H
 
 void *create_device_tree(int *sizep);
 void *load_device_tree(const char *filename_path, int *sizep);
@@ -168,4 +168,4 @@ int qemu_fdt_setprop_sized_cells_from_array(void *fdt,
 #define FDT_PCI_RANGE_IOPORT               0x01000000
 #define FDT_PCI_RANGE_CONFIG               0x00000000
 
-#endif /* __DEVICE_TREE_H__ */
+#endif /* DEVICE_TREE_H */
diff --git a/include/sysemu/hostmem.h b/include/sysemu/hostmem.h
index c903404308..678232af40 100644
--- a/include/sysemu/hostmem.h
+++ b/include/sysemu/hostmem.h
@@ -9,8 +9,9 @@
  * 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_RAM_H
-#define QEMU_RAM_H
+
+#ifndef SYSEMU_HOSTMEM_H
+#define SYSEMU_HOSTMEM_H
 
 #include "sysemu/sysemu.h" /* for MAX_NODES */
 #include "qom/object.h"
diff --git a/include/sysemu/tpm_backend.h b/include/sysemu/tpm_backend.h
index e3ec80020f..b58f52d39f 100644
--- a/include/sysemu/tpm_backend.h
+++ b/include/sysemu/tpm_backend.h
@@ -10,8 +10,8 @@
  * See the COPYING file in the top-level directory.
  */
 
-#ifndef _QEMU_TPM_H
-#define _QEMU_TPM_H
+#ifndef TPM_BACKEND_H
+#define TPM_BACKEND_H
 
 #include "qom/object.h"
 #include "qemu-common.h"
diff --git a/include/sysemu/tpm_backend_int.h b/include/sysemu/tpm_backend_int.h
index cc0dcb3fd2..00639dd7de 100644
--- a/include/sysemu/tpm_backend_int.h
+++ b/include/sysemu/tpm_backend_int.h
@@ -19,9 +19,8 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>
  */
 
-#ifndef TPM_TPM_BACKEND_H
-#define TPM_TPM_BACKEND_H
-
+#ifndef TPM_BACKEND_INT_H
+#define TPM_BACKEND_INT_H
 
 typedef struct TPMBackendThread {
     GThreadPool *pool;
@@ -39,4 +38,4 @@ typedef enum TPMBackendCmd {
     TPM_BACKEND_CMD_TPM_RESET,
 } TPMBackendCmd;
 
-#endif /* TPM_TPM_BACKEND_H */
+#endif /* TPM_BACKEND_INT_H */
diff --git a/include/sysemu/xen-mapcache.h b/include/sysemu/xen-mapcache.h
index c849489fb2..b8c93b9bce 100644
--- a/include/sysemu/xen-mapcache.h
+++ b/include/sysemu/xen-mapcache.h
@@ -9,7 +9,6 @@
 #ifndef XEN_MAPCACHE_H
 #define XEN_MAPCACHE_H
 
-
 typedef hwaddr (*phys_offset_to_gaddr_t)(hwaddr start_addr,
                                                      ram_addr_t size,
                                                      void *opaque);
@@ -52,4 +51,4 @@ static inline void xen_invalidate_map_cache(void)
 
 #endif
 
-#endif /* !XEN_MAPCACHE_H */
+#endif /* XEN_MAPCACHE_H */
diff --git a/include/trace-tcg.h b/include/trace-tcg.h
index 6f6bdbb44a..edab4b159c 100644
--- a/include/trace-tcg.h
+++ b/include/trace-tcg.h
@@ -4,4 +4,4 @@
 #include "trace/generated-tcg-tracers.h"
 #include "trace/generated-events.h"
 
-#endif  /* TRACE_TCG_H */
+#endif /* TRACE_TCG_H */
diff --git a/include/trace.h b/include/trace.h
index 44a1f1f8c7..9a01e4454b 100644
--- a/include/trace.h
+++ b/include/trace.h
@@ -4,4 +4,4 @@
 #include "trace/generated-tracers.h"
 #include "trace/generated-events.h"
 
-#endif  /* TRACE_H */
+#endif /* TRACE_H */
diff --git a/io/channel.c b/io/channel.c
index 692eb179b3..923c4651ca 100644
--- a/io/channel.c
+++ b/io/channel.c
@@ -218,7 +218,7 @@ static gboolean qio_channel_yield_enter(QIOChannel *ioc,
                                         gpointer opaque)
 {
     QIOChannelYieldData *data = opaque;
-    qemu_coroutine_enter(data->co, NULL);
+    qemu_coroutine_enter(data->co);
     return FALSE;
 }
 
diff --git a/linux-user/aarch64/target_cpu.h b/linux-user/aarch64/target_cpu.h
index b5593dc5ad..777ce29f16 100644
--- a/linux-user/aarch64/target_cpu.h
+++ b/linux-user/aarch64/target_cpu.h
@@ -16,8 +16,8 @@
  * 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 TARGET_CPU_H
-#define TARGET_CPU_H
+#ifndef AARCH64_TARGET_CPU_H
+#define AARCH64_TARGET_CPU_H
 
 static inline void cpu_clone_regs(CPUARMState *env, target_ulong newsp)
 {
diff --git a/linux-user/aarch64/target_signal.h b/linux-user/aarch64/target_signal.h
index e8c677de11..e66367cac1 100644
--- a/linux-user/aarch64/target_signal.h
+++ b/linux-user/aarch64/target_signal.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SIGNAL_H
-#define TARGET_SIGNAL_H
+#ifndef AARCH64_TARGET_SIGNAL_H
+#define AARCH64_TARGET_SIGNAL_H
 
 #include "cpu.h"
 
@@ -26,4 +26,4 @@ static inline abi_ulong get_sp_from_cpustate(CPUARMState *state)
    return state->xregs[31];
 }
 
-#endif /* TARGET_SIGNAL_H */
+#endif /* AARCH64_TARGET_SIGNAL_H */
diff --git a/linux-user/aarch64/target_structs.h b/linux-user/aarch64/target_structs.h
index 21c1f2c074..a4998a7491 100644
--- a/linux-user/aarch64/target_structs.h
+++ b/linux-user/aarch64/target_structs.h
@@ -16,8 +16,8 @@
  * 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 TARGET_STRUCTS_H
-#define TARGET_STRUCTS_H
+#ifndef AARCH64_TARGET_STRUCTS_H
+#define AARCH64_TARGET_STRUCTS_H
 
 struct target_ipc_perm {
     abi_int __key;                      /* Key.  */
diff --git a/linux-user/aarch64/target_syscall.h b/linux-user/aarch64/target_syscall.h
index f458018048..1b62953eeb 100644
--- a/linux-user/aarch64/target_syscall.h
+++ b/linux-user/aarch64/target_syscall.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SYSCALL_H
-#define TARGET_SYSCALL_H
+#ifndef AARCH64_TARGET_SYSCALL_H
+#define AARCH64_TARGET_SYSCALL_H
 
 struct target_pt_regs {
     uint64_t        regs[31];
@@ -15,4 +15,4 @@ struct target_pt_regs {
 #define TARGET_MLOCKALL_MCL_CURRENT 1
 #define TARGET_MLOCKALL_MCL_FUTURE  2
 
-#endif  /* TARGET_SYSCALL_H */
+#endif /* AARCH64_TARGET_SYSCALL_H */
diff --git a/linux-user/alpha/target_cpu.h b/linux-user/alpha/target_cpu.h
index 42562452b2..ad124da7c0 100644
--- a/linux-user/alpha/target_cpu.h
+++ b/linux-user/alpha/target_cpu.h
@@ -16,8 +16,8 @@
  * 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 TARGET_CPU_H
-#define TARGET_CPU_H
+#ifndef ALPHA_TARGET_CPU_H
+#define ALPHA_TARGET_CPU_H
 
 static inline void cpu_clone_regs(CPUAlphaState *env, target_ulong newsp)
 {
diff --git a/linux-user/alpha/target_signal.h b/linux-user/alpha/target_signal.h
index 4c78319145..f1ed00d50e 100644
--- a/linux-user/alpha/target_signal.h
+++ b/linux-user/alpha/target_signal.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SIGNAL_H
-#define TARGET_SIGNAL_H
+#ifndef ALPHA_TARGET_SIGNAL_H
+#define ALPHA_TARGET_SIGNAL_H
 
 #include "cpu.h"
 
@@ -55,4 +55,4 @@ static inline abi_ulong get_sp_from_cpustate(CPUAlphaState *state)
 #define TARGET_GEN_SUBRNG6     -24
 #define TARGET_GEN_SUBRNG7     -25
 
-#endif /* TARGET_SIGNAL_H */
+#endif /* ALPHA_TARGET_SIGNAL_H */
diff --git a/linux-user/alpha/target_structs.h b/linux-user/alpha/target_structs.h
index 50e7708ffd..db2bfe2876 100644
--- a/linux-user/alpha/target_structs.h
+++ b/linux-user/alpha/target_structs.h
@@ -16,8 +16,8 @@
  * 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 TARGET_STRUCTS_H
-#define TARGET_STRUCTS_H
+#ifndef ALPHA_TARGET_STRUCTS_H
+#define ALPHA_TARGET_STRUCTS_H
 
 struct target_ipc_perm {
     abi_int __key;                      /* Key.  */
diff --git a/linux-user/alpha/target_syscall.h b/linux-user/alpha/target_syscall.h
index 3db4b16f6b..b580fc5b37 100644
--- a/linux-user/alpha/target_syscall.h
+++ b/linux-user/alpha/target_syscall.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SYSCALL_H
-#define TARGET_SYSCALL_H
+#ifndef ALPHA_TARGET_SYSCALL_H
+#define ALPHA_TARGET_SYSCALL_H
 
 /* default linux values for the selectors */
 #define __USER_DS	(1)
@@ -259,4 +259,4 @@ struct target_pt_regs {
 #define TARGET_MLOCKALL_MCL_CURRENT     0x2000
 #define TARGET_MLOCKALL_MCL_FUTURE      0x4000
 
-#endif  /* TARGET_SYSCALL_H */
+#endif /* ALPHA_TARGET_SYSCALL_H */
diff --git a/linux-user/arm/nwfpe/fpa11.h b/linux-user/arm/nwfpe/fpa11.h
index 0b072843da..d459c5da02 100644
--- a/linux-user/arm/nwfpe/fpa11.h
+++ b/linux-user/arm/nwfpe/fpa11.h
@@ -18,11 +18,10 @@
     along with this program; if not, see <http://www.gnu.org/licenses/>.
 */
 
-#ifndef __FPA11_H__
-#define __FPA11_H__
+#ifndef FPA11_H
+#define FPA11_H
 
-
-#include <cpu.h>
+#include "cpu.h"
 
 #define GET_FPA11() (qemufpa)
 
diff --git a/linux-user/arm/nwfpe/fpopcode.h b/linux-user/arm/nwfpe/fpopcode.h
index 1b1137f3c8..06cd909850 100644
--- a/linux-user/arm/nwfpe/fpopcode.h
+++ b/linux-user/arm/nwfpe/fpopcode.h
@@ -18,8 +18,8 @@
     along with this program; if not, see <http://www.gnu.org/licenses/>.
 */
 
-#ifndef __FPOPCODE_H__
-#define __FPOPCODE_H__
+#ifndef FPOPCODE_H
+#define FPOPCODE_H
 
 /*
 ARM Floating Point Instruction Classes
diff --git a/linux-user/arm/nwfpe/fpsr.h b/linux-user/arm/nwfpe/fpsr.h
index 859dcd5898..8c978f0b8f 100644
--- a/linux-user/arm/nwfpe/fpsr.h
+++ b/linux-user/arm/nwfpe/fpsr.h
@@ -18,8 +18,8 @@
     along with this program; if not, see <http://www.gnu.org/licenses/>.
 */
 
-#ifndef __FPSR_H__
-#define __FPSR_H__
+#ifndef FPSR_H
+#define FPSR_H
 
 /*
 The FPSR is a 32 bit register consisting of 4 parts, each exactly
diff --git a/linux-user/arm/target_cpu.h b/linux-user/arm/target_cpu.h
index 6832262e39..d888219150 100644
--- a/linux-user/arm/target_cpu.h
+++ b/linux-user/arm/target_cpu.h
@@ -16,8 +16,8 @@
  * 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 TARGET_CPU_H
-#define TARGET_CPU_H
+#ifndef ARM_TARGET_CPU_H
+#define ARM_TARGET_CPU_H
 
 static inline void cpu_clone_regs(CPUARMState *env, target_ulong newsp)
 {
diff --git a/linux-user/arm/target_signal.h b/linux-user/arm/target_signal.h
index fb31f4c5ec..cbbeb09f4d 100644
--- a/linux-user/arm/target_signal.h
+++ b/linux-user/arm/target_signal.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SIGNAL_H
-#define TARGET_SIGNAL_H
+#ifndef ARM_TARGET_SIGNAL_H
+#define ARM_TARGET_SIGNAL_H
 
 #include "cpu.h"
 
@@ -27,4 +27,4 @@ static inline abi_ulong get_sp_from_cpustate(CPUARMState *state)
 }
 
 
-#endif /* TARGET_SIGNAL_H */
+#endif /* ARM_TARGET_SIGNAL_H */
diff --git a/linux-user/arm/target_structs.h b/linux-user/arm/target_structs.h
index f3c85d4e1f..0bf034cc25 100644
--- a/linux-user/arm/target_structs.h
+++ b/linux-user/arm/target_structs.h
@@ -16,8 +16,8 @@
  * 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 TARGET_STRUCTS_H
-#define TARGET_STRUCTS_H
+#ifndef ARM_TARGET_STRUCTS_H
+#define ARM_TARGET_STRUCTS_H
 
 struct target_ipc_perm {
     abi_int __key;                      /* Key.  */
diff --git a/linux-user/arm/target_syscall.h b/linux-user/arm/target_syscall.h
index 11077b761b..cd021ff598 100644
--- a/linux-user/arm/target_syscall.h
+++ b/linux-user/arm/target_syscall.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SYSCALL_H
-#define TARGET_SYSCALL_H
+#ifndef ARM_TARGET_SYSCALL_H
+#define ARM_TARGET_SYSCALL_H
 
 /* this struct defines the way the registers are stored on the
    stack during a system call. */
@@ -33,4 +33,4 @@ struct target_pt_regs {
 #define TARGET_MLOCKALL_MCL_CURRENT 1
 #define TARGET_MLOCKALL_MCL_FUTURE  2
 
-#endif  /* TARGET_SYSCALL_H */
+#endif /* ARM_TARGET_SYSCALL_H */
diff --git a/linux-user/cris/target_cpu.h b/linux-user/cris/target_cpu.h
index 4d787e5ff3..c43aac62f9 100644
--- a/linux-user/cris/target_cpu.h
+++ b/linux-user/cris/target_cpu.h
@@ -17,8 +17,8 @@
  * 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 TARGET_CPU_H
-#define TARGET_CPU_H
+#ifndef CRIS_TARGET_CPU_H
+#define CRIS_TARGET_CPU_H
 
 static inline void cpu_clone_regs(CPUCRISState *env, target_ulong newsp)
 {
diff --git a/linux-user/cris/target_signal.h b/linux-user/cris/target_signal.h
index e0f1382815..664621bbcd 100644
--- a/linux-user/cris/target_signal.h
+++ b/linux-user/cris/target_signal.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SIGNAL_H
-#define TARGET_SIGNAL_H
+#ifndef CRIS_TARGET_SIGNAL_H
+#define CRIS_TARGET_SIGNAL_H
 
 #include "cpu.h"
 
@@ -27,4 +27,4 @@ static inline abi_ulong get_sp_from_cpustate(CPUCRISState *state)
 }
 
 
-#endif /* TARGET_SIGNAL_H */
+#endif /* CRIS_TARGET_SIGNAL_H */
diff --git a/linux-user/cris/target_structs.h b/linux-user/cris/target_structs.h
index e4a1ffb3c1..76f965325c 100644
--- a/linux-user/cris/target_structs.h
+++ b/linux-user/cris/target_structs.h
@@ -16,8 +16,8 @@
  * 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 TARGET_STRUCTS_H
-#define TARGET_STRUCTS_H
+#ifndef CRIS_TARGET_STRUCTS_H
+#define CRIS_TARGET_STRUCTS_H
 
 struct target_ipc_perm {
     abi_int __key;                      /* Key.  */
diff --git a/linux-user/cris/target_syscall.h b/linux-user/cris/target_syscall.h
index 2957b0d6ae..29d69009ff 100644
--- a/linux-user/cris/target_syscall.h
+++ b/linux-user/cris/target_syscall.h
@@ -1,5 +1,5 @@
-#ifndef CRIS_SYSCALL_H
-#define CRIS_SYSCALL_H 1
+#ifndef CRIS_TARGET_SYSCALL_H
+#define CRIS_TARGET_SYSCALL_H
 
 #define UNAME_MACHINE "cris"
 #define UNAME_MINIMUM_RELEASE "2.6.32"
diff --git a/linux-user/flatload.c b/linux-user/flatload.c
index 48ad1c5e9e..42d1079a24 100644
--- a/linux-user/flatload.c
+++ b/linux-user/flatload.c
@@ -37,7 +37,7 @@
 
 #include "qemu.h"
 #include "flat.h"
-#include <target_flat.h>
+#include "target_flat.h"
 
 //#define DEBUG
 
diff --git a/linux-user/host/aarch64/hostdep.h b/linux-user/host/aarch64/hostdep.h
index b79eaf1811..64f75cef49 100644
--- a/linux-user/host/aarch64/hostdep.h
+++ b/linux-user/host/aarch64/hostdep.h
@@ -9,8 +9,8 @@
  * See the COPYING file in the top-level directory.
  */
 
-#ifndef QEMU_HOSTDEP_H
-#define QEMU_HOSTDEP_H
+#ifndef AARCH64_HOSTDEP_H
+#define AARCH64_HOSTDEP_H
 
 /* We have a safe-syscall.inc.S */
 #define HAVE_SAFE_SYSCALL
diff --git a/linux-user/host/arm/hostdep.h b/linux-user/host/arm/hostdep.h
index 8e1ff2ffc5..5c1ae60120 100644
--- a/linux-user/host/arm/hostdep.h
+++ b/linux-user/host/arm/hostdep.h
@@ -9,8 +9,8 @@
  * See the COPYING file in the top-level directory.
  */
 
-#ifndef QEMU_HOSTDEP_H
-#define QEMU_HOSTDEP_H
+#ifndef ARM_HOSTDEP_H
+#define ARM_HOSTDEP_H
 
 /* We have a safe-syscall.inc.S */
 #define HAVE_SAFE_SYSCALL
diff --git a/linux-user/host/i386/hostdep.h b/linux-user/host/i386/hostdep.h
index 5a12f4adce..d834bd80ea 100644
--- a/linux-user/host/i386/hostdep.h
+++ b/linux-user/host/i386/hostdep.h
@@ -9,8 +9,8 @@
  * See the COPYING file in the top-level directory.
  */
 
-#ifndef QEMU_HOSTDEP_H
-#define QEMU_HOSTDEP_H
+#ifndef I386_HOSTDEP_H
+#define I386_HOSTDEP_H
 
 /* We have a safe-syscall.inc.S */
 #define HAVE_SAFE_SYSCALL
diff --git a/linux-user/host/ia64/hostdep.h b/linux-user/host/ia64/hostdep.h
index 7609bf5cd7..263bf7658e 100644
--- a/linux-user/host/ia64/hostdep.h
+++ b/linux-user/host/ia64/hostdep.h
@@ -9,7 +9,7 @@
  * See the COPYING file in the top-level directory.
  */
 
-#ifndef QEMU_HOSTDEP_H
-#define QEMU_HOSTDEP_H
+#ifndef IA64_HOSTDEP_H
+#define IA64_HOSTDEP_H
 
 #endif
diff --git a/linux-user/host/mips/hostdep.h b/linux-user/host/mips/hostdep.h
index 7609bf5cd7..ba111d75c3 100644
--- a/linux-user/host/mips/hostdep.h
+++ b/linux-user/host/mips/hostdep.h
@@ -9,7 +9,7 @@
  * See the COPYING file in the top-level directory.
  */
 
-#ifndef QEMU_HOSTDEP_H
-#define QEMU_HOSTDEP_H
+#ifndef MIPS_HOSTDEP_H
+#define MIPS_HOSTDEP_H
 
 #endif
diff --git a/linux-user/host/ppc/hostdep.h b/linux-user/host/ppc/hostdep.h
index 7609bf5cd7..23d8bd9d47 100644
--- a/linux-user/host/ppc/hostdep.h
+++ b/linux-user/host/ppc/hostdep.h
@@ -9,7 +9,7 @@
  * See the COPYING file in the top-level directory.
  */
 
-#ifndef QEMU_HOSTDEP_H
-#define QEMU_HOSTDEP_H
+#ifndef PPC_HOSTDEP_H
+#define PPC_HOSTDEP_H
 
 #endif
diff --git a/linux-user/host/ppc64/hostdep.h b/linux-user/host/ppc64/hostdep.h
index 310e7d1b73..0b0f5f7821 100644
--- a/linux-user/host/ppc64/hostdep.h
+++ b/linux-user/host/ppc64/hostdep.h
@@ -9,8 +9,8 @@
  * See the COPYING file in the top-level directory.
  */
 
-#ifndef QEMU_HOSTDEP_H
-#define QEMU_HOSTDEP_H
+#ifndef PPC64_HOSTDEP_H
+#define PPC64_HOSTDEP_H
 
 /* We have a safe-syscall.inc.S */
 #define HAVE_SAFE_SYSCALL
diff --git a/linux-user/host/s390/hostdep.h b/linux-user/host/s390/hostdep.h
index 7609bf5cd7..afcba5a16a 100644
--- a/linux-user/host/s390/hostdep.h
+++ b/linux-user/host/s390/hostdep.h
@@ -9,7 +9,7 @@
  * See the COPYING file in the top-level directory.
  */
 
-#ifndef QEMU_HOSTDEP_H
-#define QEMU_HOSTDEP_H
+#ifndef S390_HOSTDEP_H
+#define S390_HOSTDEP_H
 
 #endif
diff --git a/linux-user/host/s390x/hostdep.h b/linux-user/host/s390x/hostdep.h
index e95871c46a..6f9da9c608 100644
--- a/linux-user/host/s390x/hostdep.h
+++ b/linux-user/host/s390x/hostdep.h
@@ -9,8 +9,8 @@
  * See the COPYING file in the top-level directory.
  */
 
-#ifndef QEMU_HOSTDEP_H
-#define QEMU_HOSTDEP_H
+#ifndef S390X_HOSTDEP_H
+#define S390X_HOSTDEP_H
 
 /* We have a safe-syscall.inc.S */
 #define HAVE_SAFE_SYSCALL
diff --git a/linux-user/host/sparc/hostdep.h b/linux-user/host/sparc/hostdep.h
index 7609bf5cd7..391ad923cf 100644
--- a/linux-user/host/sparc/hostdep.h
+++ b/linux-user/host/sparc/hostdep.h
@@ -9,7 +9,7 @@
  * See the COPYING file in the top-level directory.
  */
 
-#ifndef QEMU_HOSTDEP_H
-#define QEMU_HOSTDEP_H
+#ifndef SPARC_HOSTDEP_H
+#define SPARC_HOSTDEP_H
 
 #endif
diff --git a/linux-user/host/sparc64/hostdep.h b/linux-user/host/sparc64/hostdep.h
index 7609bf5cd7..ce3968fca0 100644
--- a/linux-user/host/sparc64/hostdep.h
+++ b/linux-user/host/sparc64/hostdep.h
@@ -9,7 +9,7 @@
  * See the COPYING file in the top-level directory.
  */
 
-#ifndef QEMU_HOSTDEP_H
-#define QEMU_HOSTDEP_H
+#ifndef SPARC64_HOSTDEP_H
+#define SPARC64_HOSTDEP_H
 
 #endif
diff --git a/linux-user/host/x32/hostdep.h b/linux-user/host/x32/hostdep.h
index 7609bf5cd7..2c2d6d37da 100644
--- a/linux-user/host/x32/hostdep.h
+++ b/linux-user/host/x32/hostdep.h
@@ -9,7 +9,7 @@
  * See the COPYING file in the top-level directory.
  */
 
-#ifndef QEMU_HOSTDEP_H
-#define QEMU_HOSTDEP_H
+#ifndef X32_HOSTDEP_H
+#define X32_HOSTDEP_H
 
 #endif
diff --git a/linux-user/host/x86_64/hostdep.h b/linux-user/host/x86_64/hostdep.h
index 9dfbf3ae6a..3b4259633e 100644
--- a/linux-user/host/x86_64/hostdep.h
+++ b/linux-user/host/x86_64/hostdep.h
@@ -9,8 +9,8 @@
  * See the COPYING file in the top-level directory.
  */
 
-#ifndef QEMU_HOSTDEP_H
-#define QEMU_HOSTDEP_H
+#ifndef X86_64_HOSTDEP_H
+#define X86_64_HOSTDEP_H
 
 /* We have a safe-syscall.inc.S */
 #define HAVE_SAFE_SYSCALL
diff --git a/linux-user/i386/target_cpu.h b/linux-user/i386/target_cpu.h
index 58f86454d6..7fbcf9bb57 100644
--- a/linux-user/i386/target_cpu.h
+++ b/linux-user/i386/target_cpu.h
@@ -17,8 +17,8 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 
-#ifndef TARGET_CPU_H
-#define TARGET_CPU_H
+#ifndef I386_TARGET_CPU_H
+#define I386_TARGET_CPU_H
 
 static inline void cpu_clone_regs(CPUX86State *env, target_ulong newsp)
 {
@@ -45,4 +45,4 @@ static inline void cpu_set_tls(CPUX86State *env, target_ulong newtls)
 }
 #endif /* defined(TARGET_ABI32) */
 
-#endif /* !defined(TARGET_CPU_H) */
+#endif /* I386_TARGET_CPU_H */
diff --git a/linux-user/i386/target_signal.h b/linux-user/i386/target_signal.h
index 9baf7fbeb5..837e90fc4c 100644
--- a/linux-user/i386/target_signal.h
+++ b/linux-user/i386/target_signal.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SIGNAL_H
-#define TARGET_SIGNAL_H
+#ifndef I386_TARGET_SIGNAL_H
+#define I386_TARGET_SIGNAL_H
 
 #include "cpu.h"
 
@@ -26,4 +26,4 @@ static inline abi_ulong get_sp_from_cpustate(CPUX86State *state)
     return state->regs[R_ESP];
 }
 
-#endif /* TARGET_SIGNAL_H */
+#endif /* I386_TARGET_SIGNAL_H */
diff --git a/linux-user/i386/target_structs.h b/linux-user/i386/target_structs.h
index 65f535e16b..25388a7fd2 100644
--- a/linux-user/i386/target_structs.h
+++ b/linux-user/i386/target_structs.h
@@ -16,8 +16,8 @@
  * 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 TARGET_STRUCTS_H
-#define TARGET_STRUCTS_H
+#ifndef I386_TARGET_STRUCTS_H
+#define I386_TARGET_STRUCTS_H
 
 struct target_ipc_perm {
     abi_int __key;                      /* Key.  */
diff --git a/linux-user/i386/target_syscall.h b/linux-user/i386/target_syscall.h
index 0ac84dc02f..b4e895fd9c 100644
--- a/linux-user/i386/target_syscall.h
+++ b/linux-user/i386/target_syscall.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SYSCALL_H
-#define TARGET_SYSCALL_H
+#ifndef I386_TARGET_SYSCALL_H
+#define I386_TARGET_SYSCALL_H
 
 /* default linux values for the selectors */
 #define __USER_CS	(0x23)
@@ -154,4 +154,4 @@ struct target_vm86plus_struct {
 #define TARGET_MLOCKALL_MCL_CURRENT 1
 #define TARGET_MLOCKALL_MCL_FUTURE  2
 
-#endif  /* TARGET_SYSCALL_H */
+#endif /* I386_TARGET_SYSCALL_H */
diff --git a/linux-user/linux_loop.h b/linux-user/linux_loop.h
index 8974caa9d0..1f52403814 100644
--- a/linux-user/linux_loop.h
+++ b/linux-user/linux_loop.h
@@ -1,6 +1,7 @@
 /* Copied from 2.6.25 kernel headers to avoid problems on older hosts.  */
-#ifndef _LINUX_LOOP_H
-#define _LINUX_LOOP_H
+
+#ifndef LINUX_LOOP_H
+#define LINUX_LOOP_H
 
 /*
  * include/linux/loop.h
diff --git a/linux-user/m68k/target_cpu.h b/linux-user/m68k/target_cpu.h
index bb4d3fabe1..cc0bfc298e 100644
--- a/linux-user/m68k/target_cpu.h
+++ b/linux-user/m68k/target_cpu.h
@@ -18,8 +18,8 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 
-#ifndef TARGET_CPU_H
-#define TARGET_CPU_H
+#ifndef M68K_TARGET_CPU_H
+#define M68K_TARGET_CPU_H
 
 static inline void cpu_clone_regs(CPUM68KState *env, target_ulong newsp)
 {
diff --git a/linux-user/m68k/target_signal.h b/linux-user/m68k/target_signal.h
index 9deaa89c80..9d2d7343f8 100644
--- a/linux-user/m68k/target_signal.h
+++ b/linux-user/m68k/target_signal.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SIGNAL_H
-#define TARGET_SIGNAL_H
+#ifndef M68K_TARGET_SIGNAL_H
+#define M68K_TARGET_SIGNAL_H
 
 #include "cpu.h"
 
@@ -27,4 +27,4 @@ static inline abi_ulong get_sp_from_cpustate(CPUM68KState *state)
 }
 
 
-#endif /* TARGET_SIGNAL_H */
+#endif /* M68K_TARGET_SIGNAL_H */
diff --git a/linux-user/m68k/target_structs.h b/linux-user/m68k/target_structs.h
index de257c97de..a003676548 100644
--- a/linux-user/m68k/target_structs.h
+++ b/linux-user/m68k/target_structs.h
@@ -16,8 +16,8 @@
  * 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 TARGET_STRUCTS_H
-#define TARGET_STRUCTS_H
+#ifndef M68K_TARGET_STRUCTS_H
+#define M68K_TARGET_STRUCTS_H
 
 struct target_ipc_perm {
     abi_int __key;                      /* Key.  */
diff --git a/linux-user/m68k/target_syscall.h b/linux-user/m68k/target_syscall.h
index 97a4cc0cbd..db2be4f101 100644
--- a/linux-user/m68k/target_syscall.h
+++ b/linux-user/m68k/target_syscall.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SYSCALL_H
-#define TARGET_SYSCALL_H
+#ifndef M68K_TARGET_SYSCALL_H
+#define M68K_TARGET_SYSCALL_H
 
 /* this struct defines the way the registers are stored on the
    stack during a system call. */
@@ -26,4 +26,4 @@ struct target_pt_regs {
 
 void do_m68k_simcall(CPUM68KState *, int);
 
-#endif  /* TARGET_SYSCALL_H */
+#endif /* M68K_TARGET_SYSCALL_H */
diff --git a/linux-user/microblaze/target_cpu.h b/linux-user/microblaze/target_cpu.h
index c6386ea9e4..7dd979f960 100644
--- a/linux-user/microblaze/target_cpu.h
+++ b/linux-user/microblaze/target_cpu.h
@@ -16,8 +16,8 @@
  * 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 TARGET_CPU_H
-#define TARGET_CPU_H
+#ifndef MICROBLAZE_TARGET_CPU_H
+#define MICROBLAZE_TARGET_CPU_H
 
 static inline void cpu_clone_regs(CPUMBState *env, target_ulong newsp)
 {
diff --git a/linux-user/microblaze/target_signal.h b/linux-user/microblaze/target_signal.h
index acdf3b5acd..de2b0f49d5 100644
--- a/linux-user/microblaze/target_signal.h
+++ b/linux-user/microblaze/target_signal.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SIGNAL_H
-#define TARGET_SIGNAL_H
+#ifndef MICROBLAZE_TARGET_SIGNAL_H
+#define MICROBLAZE_TARGET_SIGNAL_H
 
 #include "cpu.h"
 
@@ -27,4 +27,4 @@ static inline abi_ulong get_sp_from_cpustate(CPUMBState *state)
 }
 
 
-#endif /* TARGET_SIGNAL_H */
+#endif /* MICROBLAZE_TARGET_SIGNAL_H */
diff --git a/linux-user/microblaze/target_structs.h b/linux-user/microblaze/target_structs.h
index 325e2f6d4d..70dbdb6101 100644
--- a/linux-user/microblaze/target_structs.h
+++ b/linux-user/microblaze/target_structs.h
@@ -16,8 +16,8 @@
  * 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 TARGET_STRUCTS_H
-#define TARGET_STRUCTS_H
+#ifndef MICROBLAZE_TARGET_STRUCTS_H
+#define MICROBLAZE_TARGET_STRUCTS_H
 
 struct target_ipc_perm {
     abi_int __key;                      /* Key.  */
diff --git a/linux-user/microblaze/target_syscall.h b/linux-user/microblaze/target_syscall.h
index 3c1ed27c04..0b6980c899 100644
--- a/linux-user/microblaze/target_syscall.h
+++ b/linux-user/microblaze/target_syscall.h
@@ -1,5 +1,5 @@
-#ifndef MICROBLAZE_SYSCALLS_H
-#define MICROBLAZE_SYSCALLS_H 1
+#ifndef MICROBLAZE_TARGET_SYSCALL_H
+#define MICROBLAZE_TARGET_SYSCALL_H
 
 #define UNAME_MACHINE "microblaze"
 #define UNAME_MINIMUM_RELEASE "2.6.32"
diff --git a/linux-user/mips/target_cpu.h b/linux-user/mips/target_cpu.h
index 19b8855000..2002920312 100644
--- a/linux-user/mips/target_cpu.h
+++ b/linux-user/mips/target_cpu.h
@@ -16,8 +16,8 @@
  * 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 TARGET_CPU_H
-#define TARGET_CPU_H
+#ifndef MIPS_TARGET_CPU_H
+#define MIPS_TARGET_CPU_H
 
 static inline void cpu_clone_regs(CPUMIPSState *env, target_ulong newsp)
 {
diff --git a/linux-user/mips/target_signal.h b/linux-user/mips/target_signal.h
index 460cc9ffef..8dd27cef35 100644
--- a/linux-user/mips/target_signal.h
+++ b/linux-user/mips/target_signal.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SIGNAL_H
-#define TARGET_SIGNAL_H
+#ifndef MIPS_TARGET_SIGNAL_H
+#define MIPS_TARGET_SIGNAL_H
 
 #include "cpu.h"
 
@@ -27,4 +27,4 @@ static inline abi_ulong get_sp_from_cpustate(CPUMIPSState *state)
 }
 
 
-#endif /* TARGET_SIGNAL_H */
+#endif /* MIPS_TARGET_SIGNAL_H */
diff --git a/linux-user/mips/target_structs.h b/linux-user/mips/target_structs.h
index 16021e8a94..fbd995581e 100644
--- a/linux-user/mips/target_structs.h
+++ b/linux-user/mips/target_structs.h
@@ -16,8 +16,8 @@
  * 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 TARGET_STRUCTS_H
-#define TARGET_STRUCTS_H
+#ifndef MIPS_TARGET_STRUCTS_H
+#define MIPS_TARGET_STRUCTS_H
 
 struct target_ipc_perm {
     abi_int __key;                      /* Key.  */
diff --git a/linux-user/mips/target_syscall.h b/linux-user/mips/target_syscall.h
index e8e305cc9c..2b4f390729 100644
--- a/linux-user/mips/target_syscall.h
+++ b/linux-user/mips/target_syscall.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SYSCALL_H
-#define TARGET_SYSCALL_H
+#ifndef MIPS_TARGET_SYSCALL_H
+#define MIPS_TARGET_SYSCALL_H
 
 /* this struct defines the way the registers are stored on the
    stack during a system call. */
@@ -230,4 +230,4 @@ struct target_pt_regs {
 #define TARGET_MLOCKALL_MCL_CURRENT 1
 #define TARGET_MLOCKALL_MCL_FUTURE  2
 
-#endif  /* TARGET_SYSCALL_H */
+#endif /* MIPS_TARGET_SYSCALL_H */
diff --git a/linux-user/mips64/target_signal.h b/linux-user/mips64/target_signal.h
index a2dc514e3e..67ef5a18f4 100644
--- a/linux-user/mips64/target_signal.h
+++ b/linux-user/mips64/target_signal.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SIGNAL_H
-#define TARGET_SIGNAL_H
+#ifndef MIPS64_TARGET_SIGNAL_H
+#define MIPS64_TARGET_SIGNAL_H
 
 #include "cpu.h"
 
@@ -27,4 +27,4 @@ static inline abi_ulong get_sp_from_cpustate(CPUMIPSState *state)
 }
 
 
-#endif /* TARGET_SIGNAL_H */
+#endif /* MIPS64_TARGET_SIGNAL_H */
diff --git a/linux-user/mips64/target_syscall.h b/linux-user/mips64/target_syscall.h
index 5789e86150..8da9c1f9cc 100644
--- a/linux-user/mips64/target_syscall.h
+++ b/linux-user/mips64/target_syscall.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SYSCALL_H
-#define TARGET_SYSCALL_H
+#ifndef MIPS64_TARGET_SYSCALL_H
+#define MIPS64_TARGET_SYSCALL_H
 
 /* this struct defines the way the registers are stored on the
    stack during a system call. */
@@ -227,4 +227,4 @@ struct target_pt_regs {
 #define TARGET_MLOCKALL_MCL_CURRENT 1
 #define TARGET_MLOCKALL_MCL_FUTURE  2
 
-#endif  /* TARGET_SYSCALL_H */
+#endif /* MIPS64_TARGET_SYSCALL_H */
diff --git a/linux-user/openrisc/target_cpu.h b/linux-user/openrisc/target_cpu.h
index 32a46ac840..a21ed1aff8 100644
--- a/linux-user/openrisc/target_cpu.h
+++ b/linux-user/openrisc/target_cpu.h
@@ -17,8 +17,8 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 
-#ifndef TARGET_CPU_H
-#define TARGET_CPU_H
+#ifndef OPENRISC_TARGET_CPU_H
+#define OPENRISC_TARGET_CPU_H
 
 static inline void cpu_clone_regs(CPUOpenRISCState *env, target_ulong newsp)
 {
diff --git a/linux-user/openrisc/target_signal.h b/linux-user/openrisc/target_signal.h
index f600501f6f..9f2c493f79 100644
--- a/linux-user/openrisc/target_signal.h
+++ b/linux-user/openrisc/target_signal.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SIGNAL_H
-#define TARGET_SIGNAL_H
+#ifndef OPENRISC_TARGET_SIGNAL_H
+#define OPENRISC_TARGET_SIGNAL_H
 
 #include "cpu.h"
 
@@ -24,4 +24,4 @@ static inline abi_ulong get_sp_from_cpustate(CPUOpenRISCState *state)
 }
 
 
-#endif /* TARGET_SIGNAL_H */
+#endif /* OPENRISC_TARGET_SIGNAL_H */
diff --git a/linux-user/openrisc/target_structs.h b/linux-user/openrisc/target_structs.h
index f4d560f575..afbb7ad108 100644
--- a/linux-user/openrisc/target_structs.h
+++ b/linux-user/openrisc/target_structs.h
@@ -16,8 +16,8 @@
  * 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 TARGET_STRUCTS_H
-#define TARGET_STRUCTS_H
+#ifndef OPENRISC_TARGET_STRUCTS_H
+#define OPENRISC_TARGET_STRUCTS_H
 
 struct target_ipc_perm {
     abi_int __key;                      /* Key.  */
diff --git a/linux-user/openrisc/target_syscall.h b/linux-user/openrisc/target_syscall.h
index 19aeffc95d..9d3380f9a8 100644
--- a/linux-user/openrisc/target_syscall.h
+++ b/linux-user/openrisc/target_syscall.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SYSCALL_H
-#define TARGET_SYSCALL_H
+#ifndef OPENRISC_TARGET_SYSCALL_H
+#define OPENRISC_TARGET_SYSCALL_H
 
 struct target_pt_regs {
     union {
@@ -31,4 +31,4 @@ struct target_pt_regs {
 #define TARGET_MLOCKALL_MCL_CURRENT 1
 #define TARGET_MLOCKALL_MCL_FUTURE  2
 
-#endif  /* TARGET_SYSCALL_H */
+#endif /* OPENRISC_TARGET_SYSCALL_H */
diff --git a/linux-user/ppc/target_cpu.h b/linux-user/ppc/target_cpu.h
index 26f4ba297f..3aab3d185d 100644
--- a/linux-user/ppc/target_cpu.h
+++ b/linux-user/ppc/target_cpu.h
@@ -16,8 +16,8 @@
  * 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 TARGET_CPU_H
-#define TARGET_CPU_H
+#ifndef PPC_TARGET_CPU_H
+#define PPC_TARGET_CPU_H
 
 static inline void cpu_clone_regs(CPUPPCState *env, target_ulong newsp)
 {
diff --git a/linux-user/ppc/target_signal.h b/linux-user/ppc/target_signal.h
index 4f01dd4ea8..865c52f3e8 100644
--- a/linux-user/ppc/target_signal.h
+++ b/linux-user/ppc/target_signal.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SIGNAL_H
-#define TARGET_SIGNAL_H
+#ifndef PPC_TARGET_SIGNAL_H
+#define PPC_TARGET_SIGNAL_H
 
 #include "cpu.h"
 
@@ -27,4 +27,4 @@ static inline abi_ulong get_sp_from_cpustate(CPUPPCState *state)
 }
 
 
-#endif /* TARGET_SIGNAL_H */
+#endif /* PPC_TARGET_SIGNAL_H */
diff --git a/linux-user/ppc/target_structs.h b/linux-user/ppc/target_structs.h
index 2b87613104..6b1f5791a9 100644
--- a/linux-user/ppc/target_structs.h
+++ b/linux-user/ppc/target_structs.h
@@ -16,8 +16,8 @@
  * 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 TARGET_STRUCTS_H
-#define TARGET_STRUCTS_H
+#ifndef PPC_TARGET_STRUCTS_H
+#define PPC_TARGET_STRUCTS_H
 
 struct target_ipc_perm {
     abi_int __key;                      /* Key.  */
diff --git a/linux-user/ppc/target_syscall.h b/linux-user/ppc/target_syscall.h
index 7ca83c2280..a8662f4856 100644
--- a/linux-user/ppc/target_syscall.h
+++ b/linux-user/ppc/target_syscall.h
@@ -17,8 +17,8 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 
-#ifndef TARGET_SYSCALL_H
-#define TARGET_SYSCALL_H
+#ifndef PPC_TARGET_SYSCALL_H
+#define PPC_TARGET_SYSCALL_H
 
 /* XXX: ABSOLUTELY BUGGY:
  * for now, this is quite just a cut-and-paste from i386 target...
@@ -75,4 +75,4 @@ struct target_revectored_struct {
 #define TARGET_MLOCKALL_MCL_CURRENT 0x2000
 #define TARGET_MLOCKALL_MCL_FUTURE  0x4000
 
-#endif  /* TARGET_SYSCALL_H */
+#endif /* PPC_TARGET_SYSCALL_H */
diff --git a/linux-user/s390x/target_cpu.h b/linux-user/s390x/target_cpu.h
index f10abe8e54..87ea4d2d9b 100644
--- a/linux-user/s390x/target_cpu.h
+++ b/linux-user/s390x/target_cpu.h
@@ -19,8 +19,8 @@
  * 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 TARGET_CPU_H
-#define TARGET_CPU_H
+#ifndef S390X_TARGET_CPU_H
+#define S390X_TARGET_CPU_H
 
 static inline void cpu_clone_regs(CPUS390XState *env, target_ulong newsp)
 {
diff --git a/linux-user/s390x/target_signal.h b/linux-user/s390x/target_signal.h
index a6fb2873a3..6f7b6abafe 100644
--- a/linux-user/s390x/target_signal.h
+++ b/linux-user/s390x/target_signal.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SIGNAL_H
-#define TARGET_SIGNAL_H
+#ifndef S390X_TARGET_SIGNAL_H
+#define S390X_TARGET_SIGNAL_H
 
 #include "cpu.h"
 
@@ -24,4 +24,4 @@ static inline abi_ulong get_sp_from_cpustate(CPUS390XState *state)
 }
 
 
-#endif /* TARGET_SIGNAL_H */
+#endif /* S390X_TARGET_SIGNAL_H */
diff --git a/linux-user/s390x/target_structs.h b/linux-user/s390x/target_structs.h
index 6b6f5b5212..cadff6db3d 100644
--- a/linux-user/s390x/target_structs.h
+++ b/linux-user/s390x/target_structs.h
@@ -16,8 +16,8 @@
  * 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 TARGET_STRUCTS_H
-#define TARGET_STRUCTS_H
+#ifndef S390X_TARGET_STRUCTS_H
+#define S390X_TARGET_STRUCTS_H
 
 
 struct target_ipc_perm {
diff --git a/linux-user/s390x/target_syscall.h b/linux-user/s390x/target_syscall.h
index 02061efc78..8d4f609eaa 100644
--- a/linux-user/s390x/target_syscall.h
+++ b/linux-user/s390x/target_syscall.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SYSCALL_H
-#define TARGET_SYSCALL_H
+#ifndef S390X_TARGET_SYSCALL_H
+#define S390X_TARGET_SYSCALL_H
 
 /* this typedef defines how a Program Status Word looks like */
 typedef struct {
@@ -31,4 +31,4 @@ struct target_pt_regs {
 #define TARGET_MLOCKALL_MCL_CURRENT 1
 #define TARGET_MLOCKALL_MCL_FUTURE  2
 
-#endif  /* TARGET_SYSCALL_H */
+#endif /* S390X_TARGET_SYSCALL_H */
diff --git a/linux-user/sh4/target_cpu.h b/linux-user/sh4/target_cpu.h
index 141856f845..9d305d2833 100644
--- a/linux-user/sh4/target_cpu.h
+++ b/linux-user/sh4/target_cpu.h
@@ -16,8 +16,8 @@
  * 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 TARGET_CPU_H
-#define TARGET_CPU_H
+#ifndef SH4_TARGET_CPU_H
+#define SH4_TARGET_CPU_H
 
 static inline void cpu_clone_regs(CPUSH4State *env, target_ulong newsp)
 {
diff --git a/linux-user/sh4/target_signal.h b/linux-user/sh4/target_signal.h
index f9911aa7f2..cbf23b6a31 100644
--- a/linux-user/sh4/target_signal.h
+++ b/linux-user/sh4/target_signal.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SIGNAL_H
-#define TARGET_SIGNAL_H
+#ifndef SH4_TARGET_SIGNAL_H
+#define SH4_TARGET_SIGNAL_H
 
 #include "cpu.h"
 
@@ -27,4 +27,4 @@ static inline abi_ulong get_sp_from_cpustate(CPUSH4State *state)
 }
 
 
-#endif /* TARGET_SIGNAL_H */
+#endif /* SH4_TARGET_SIGNAL_H */
diff --git a/linux-user/sh4/target_structs.h b/linux-user/sh4/target_structs.h
index 32b235e0b3..3e832bf69a 100644
--- a/linux-user/sh4/target_structs.h
+++ b/linux-user/sh4/target_structs.h
@@ -16,8 +16,8 @@
  * 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 TARGET_STRUCTS_H
-#define TARGET_STRUCTS_H
+#ifndef SH4_TARGET_STRUCTS_H
+#define SH4_TARGET_STRUCTS_H
 
 struct target_ipc_perm {
     abi_int __key;                      /* Key.  */
diff --git a/linux-user/sh4/target_syscall.h b/linux-user/sh4/target_syscall.h
index 9f3381bc9b..78d5557124 100644
--- a/linux-user/sh4/target_syscall.h
+++ b/linux-user/sh4/target_syscall.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SYSCALL_H
-#define TARGET_SYSCALL_H
+#ifndef SH4_TARGET_SYSCALL_H
+#define SH4_TARGET_SYSCALL_H
 
 struct target_pt_regs {
         unsigned long regs[16];
@@ -19,4 +19,4 @@ struct target_pt_regs {
 #define TARGET_MLOCKALL_MCL_CURRENT 1
 #define TARGET_MLOCKALL_MCL_FUTURE  2
 
-#endif  /* TARGET_SYSCALL_H */
+#endif /* SH4_TARGET_SYSCALL_H */
diff --git a/linux-user/sparc/target_cpu.h b/linux-user/sparc/target_cpu.h
index 4944d465a2..f2fe526204 100644
--- a/linux-user/sparc/target_cpu.h
+++ b/linux-user/sparc/target_cpu.h
@@ -17,8 +17,8 @@
  * 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 TARGET_CPU_H
-#define TARGET_CPU_H
+#ifndef SPARC_TARGET_CPU_H
+#define SPARC_TARGET_CPU_H
 
 static inline void cpu_clone_regs(CPUSPARCState *env, target_ulong newsp)
 {
diff --git a/linux-user/sparc/target_signal.h b/linux-user/sparc/target_signal.h
index 2df38c805f..e445e2b463 100644
--- a/linux-user/sparc/target_signal.h
+++ b/linux-user/sparc/target_signal.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SIGNAL_H
-#define TARGET_SIGNAL_H
+#ifndef SPARC_TARGET_SIGNAL_H
+#define SPARC_TARGET_SIGNAL_H
 
 #include "cpu.h"
 
@@ -34,4 +34,4 @@ static inline abi_ulong get_sp_from_cpustate(CPUSPARCState *state)
 }
 
 
-#endif /* TARGET_SIGNAL_H */
+#endif /* SPARC_TARGET_SIGNAL_H */
diff --git a/linux-user/sparc/target_structs.h b/linux-user/sparc/target_structs.h
index c139e09a61..ee24c3b5fc 100644
--- a/linux-user/sparc/target_structs.h
+++ b/linux-user/sparc/target_structs.h
@@ -16,8 +16,8 @@
  * 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 TARGET_STRUCTS_H
-#define TARGET_STRUCTS_H
+#ifndef SPARC_TARGET_STRUCTS_H
+#define SPARC_TARGET_STRUCTS_H
 
 struct target_ipc_perm {
     abi_int __key;                      /* Key.  */
diff --git a/linux-user/sparc/target_syscall.h b/linux-user/sparc/target_syscall.h
index a73fa6dae1..326f674b4e 100644
--- a/linux-user/sparc/target_syscall.h
+++ b/linux-user/sparc/target_syscall.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SYSCALL_H
-#define TARGET_SYSCALL_H
+#ifndef SPARC_TARGET_SYSCALL_H
+#define SPARC_TARGET_SYSCALL_H
 
 struct target_pt_regs {
 	abi_ulong psr;
@@ -22,4 +22,4 @@ struct target_pt_regs {
 #define TARGET_MLOCKALL_MCL_CURRENT 0x2000
 #define TARGET_MLOCKALL_MCL_FUTURE  0x4000
 
-#endif  /* TARGET_SYSCALL_H */
+#endif /* SPARC_TARGET_SYSCALL_H */
diff --git a/linux-user/sparc64/target_signal.h b/linux-user/sparc64/target_signal.h
index 2df38c805f..4449457baf 100644
--- a/linux-user/sparc64/target_signal.h
+++ b/linux-user/sparc64/target_signal.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SIGNAL_H
-#define TARGET_SIGNAL_H
+#ifndef SPARC64_TARGET_SIGNAL_H
+#define SPARC64_TARGET_SIGNAL_H
 
 #include "cpu.h"
 
@@ -34,4 +34,4 @@ static inline abi_ulong get_sp_from_cpustate(CPUSPARCState *state)
 }
 
 
-#endif /* TARGET_SIGNAL_H */
+#endif /* SPARC64_TARGET_SIGNAL_H */
diff --git a/linux-user/sparc64/target_structs.h b/linux-user/sparc64/target_structs.h
index fc1729007d..1808132b18 100644
--- a/linux-user/sparc64/target_structs.h
+++ b/linux-user/sparc64/target_structs.h
@@ -16,8 +16,8 @@
  * 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 TARGET_STRUCTS_H
-#define TARGET_STRUCTS_H
+#ifndef SPARC64_TARGET_STRUCTS_H
+#define SPARC64_TARGET_STRUCTS_H
 
 struct target_ipc_perm {
     abi_int __key;                      /* Key.  */
diff --git a/linux-user/sparc64/target_syscall.h b/linux-user/sparc64/target_syscall.h
index eb827fcac1..b7e3bf82fb 100644
--- a/linux-user/sparc64/target_syscall.h
+++ b/linux-user/sparc64/target_syscall.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SYSCALL_H
-#define TARGET_SYSCALL_H
+#ifndef SPARC64_TARGET_SYSCALL_H
+#define SPARC64_TARGET_SYSCALL_H
 
 struct target_pt_regs {
 	abi_ulong u_regs[16];
@@ -23,4 +23,4 @@ struct target_pt_regs {
 #define TARGET_MLOCKALL_MCL_CURRENT 0x2000
 #define TARGET_MLOCKALL_MCL_FUTURE  0x4000
 
-#endif  /* TARGET_SYSCALL_H */
+#endif /* SPARC64_TARGET_SYSCALL_H */
diff --git a/linux-user/syscall_defs.h b/linux-user/syscall_defs.h
index dce1bcc91d..b43966ece0 100644
--- a/linux-user/syscall_defs.h
+++ b/linux-user/syscall_defs.h
@@ -5,8 +5,7 @@
    necessary */
 
 #ifndef SYSCALL_DEFS_H
-#define SYSCALL_DEFS_H 1
-
+#define SYSCALL_DEFS_H
 
 #include "syscall_nr.h"
 
@@ -2577,8 +2576,6 @@ struct target_ucred {
     uint32_t gid;
 };
 
-#endif
-
 typedef int32_t target_timer_t;
 
 #define TARGET_SIGEV_MAX_SIZE 64
@@ -2620,3 +2617,5 @@ struct target_user_cap_data {
     uint32_t permitted;
     uint32_t inheritable;
 };
+
+#endif
diff --git a/linux-user/tilegx/syscall_nr.h b/linux-user/tilegx/syscall_nr.h
index 87fb72c554..8e30cd1ae9 100644
--- a/linux-user/tilegx/syscall_nr.h
+++ b/linux-user/tilegx/syscall_nr.h
@@ -1,5 +1,5 @@
-#ifndef TILEGX_SYSCALL_NR
-#define TILEGX_SYSCALL_NR
+#ifndef TILEGX_SYSCALL_NR_H
+#define TILEGX_SYSCALL_NR_H
 
 /*
  * Copy from linux kernel asm-generic/unistd.h, which tilegx uses.
diff --git a/linux-user/tilegx/target_cpu.h b/linux-user/tilegx/target_cpu.h
index c96e81d05e..4878e01b03 100644
--- a/linux-user/tilegx/target_cpu.h
+++ b/linux-user/tilegx/target_cpu.h
@@ -16,8 +16,8 @@
  * 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 TARGET_CPU_H
-#define TARGET_CPU_H
+#ifndef TILEGX_TARGET_CPU_H
+#define TILEGX_TARGET_CPU_H
 
 static inline void cpu_clone_regs(CPUTLGState *env, target_ulong newsp)
 {
diff --git a/linux-user/tilegx/target_signal.h b/linux-user/tilegx/target_signal.h
index fcf10405c4..f64551a8cf 100644
--- a/linux-user/tilegx/target_signal.h
+++ b/linux-user/tilegx/target_signal.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SIGNAL_H
-#define TARGET_SIGNAL_H
+#ifndef TILEGX_TARGET_SIGNAL_H
+#define TILEGX_TARGET_SIGNAL_H
 
 #include "cpu.h"
 
@@ -26,4 +26,4 @@ static inline abi_ulong get_sp_from_cpustate(CPUTLGState *state)
 }
 
 
-#endif /* TARGET_SIGNAL_H */
+#endif /* TILEGX_TARGET_SIGNAL_H */
diff --git a/linux-user/tilegx/target_structs.h b/linux-user/tilegx/target_structs.h
index 7d3ff782fd..de8b1f2f45 100644
--- a/linux-user/tilegx/target_structs.h
+++ b/linux-user/tilegx/target_structs.h
@@ -16,8 +16,8 @@
  * 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 TARGET_STRUCTS_H
-#define TARGET_STRUCTS_H
+#ifndef TILEGX_TARGET_STRUCTS_H
+#define TILEGX_TARGET_STRUCTS_H
 
 struct target_ipc_perm {
     abi_int __key;                      /* Key.  */
diff --git a/linux-user/tilegx/target_syscall.h b/linux-user/tilegx/target_syscall.h
index a938d4e90c..d731acdafa 100644
--- a/linux-user/tilegx/target_syscall.h
+++ b/linux-user/tilegx/target_syscall.h
@@ -1,5 +1,5 @@
-#ifndef TILEGX_SYSCALLS_H
-#define TILEGX_SYSCALLS_H
+#ifndef TILEGX_TARGET_SYSCALL_H
+#define TILEGX_TARGET_SYSCALL_H
 
 #define UNAME_MACHINE "tilegx"
 #define UNAME_MINIMUM_RELEASE "3.19"
diff --git a/linux-user/uname.h b/linux-user/uname.h
index cc62e76cc1..4503094211 100644
--- a/linux-user/uname.h
+++ b/linux-user/uname.h
@@ -1,5 +1,5 @@
 #ifndef UNAME_H
-#define UNAME_H 1
+#define UNAME_H
 
 #include <sys/utsname.h>
 #include <linux/utsname.h>
@@ -7,4 +7,4 @@
 const char *cpu_to_uname_machine(void *cpu_env);
 int sys_uname(struct new_utsname *buf);
 
-#endif /* UNAME _H */
+#endif /* UNAME_H */
diff --git a/linux-user/unicore32/target_cpu.h b/linux-user/unicore32/target_cpu.h
index fb7908719f..d7d2e7b083 100644
--- a/linux-user/unicore32/target_cpu.h
+++ b/linux-user/unicore32/target_cpu.h
@@ -8,8 +8,8 @@
  * published by the Free Software Foundation, or (at your option) any
  * later version. See the COPYING file in the top-level directory.
  */
-#ifndef TARGET_CPU_H
-#define TARGET_CPU_H
+#ifndef UNICORE32_TARGET_CPU_H
+#define UNICORE32_TARGET_CPU_H
 
 static inline void cpu_clone_regs(CPUUniCore32State *env, target_ulong newsp)
 {
diff --git a/linux-user/unicore32/target_signal.h b/linux-user/unicore32/target_signal.h
index 7c442381ab..c6496fb9ea 100644
--- a/linux-user/unicore32/target_signal.h
+++ b/linux-user/unicore32/target_signal.h
@@ -5,8 +5,8 @@
  * it under the terms of the GNU General Public License version 2 as
  * published by the Free Software Foundation.
  */
-#ifndef TARGET_SIGNAL_H
-#define TARGET_SIGNAL_H
+#ifndef UNICORE32_TARGET_SIGNAL_H
+#define UNICORE32_TARGET_SIGNAL_H
 
 /* this struct defines a stack used during syscall handling */
 typedef struct target_sigaltstack {
@@ -27,4 +27,4 @@ static inline abi_ulong get_sp_from_cpustate(CPUUniCore32State *state)
 }
 
 
-#endif /* TARGET_SIGNAL_H */
+#endif /* UNICORE32_TARGET_SIGNAL_H */
diff --git a/linux-user/unicore32/target_structs.h b/linux-user/unicore32/target_structs.h
index 789369503b..fbd4fa3f53 100644
--- a/linux-user/unicore32/target_structs.h
+++ b/linux-user/unicore32/target_structs.h
@@ -16,8 +16,8 @@
  * 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 TARGET_STRUCTS_H
-#define TARGET_STRUCTS_H
+#ifndef UNICORE32_TARGET_STRUCTS_H
+#define UNICORE32_TARGET_STRUCTS_H
 
 struct target_ipc_perm {
     abi_int __key;                      /* Key.  */
diff --git a/linux-user/unicore32/target_syscall.h b/linux-user/unicore32/target_syscall.h
index 385a97562d..346b207700 100644
--- a/linux-user/unicore32/target_syscall.h
+++ b/linux-user/unicore32/target_syscall.h
@@ -5,8 +5,10 @@
  * it under the terms of the GNU General Public License version 2 as
  * published by the Free Software Foundation.
  */
-#ifndef __UC32_SYSCALL_H__
-#define __UC32_SYSCALL_H__
+
+#ifndef UNICORE32_TARGET_SYSCALL_H
+#define UNICORE32_TARGET_SYSCALL_H
+
 struct target_pt_regs {
     abi_ulong uregs[34];
 };
@@ -57,4 +59,4 @@ struct target_pt_regs {
 #define TARGET_MLOCKALL_MCL_CURRENT 1
 #define TARGET_MLOCKALL_MCL_FUTURE  2
 
-#endif /* __UC32_SYSCALL_H__ */
+#endif /* UNICORE32_TARGET_SYSCALL_H */
diff --git a/linux-user/x86_64/target_signal.h b/linux-user/x86_64/target_signal.h
index 9baf7fbeb5..1e95f4a684 100644
--- a/linux-user/x86_64/target_signal.h
+++ b/linux-user/x86_64/target_signal.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SIGNAL_H
-#define TARGET_SIGNAL_H
+#ifndef X86_64_TARGET_SIGNAL_H
+#define X86_64_TARGET_SIGNAL_H
 
 #include "cpu.h"
 
@@ -26,4 +26,4 @@ static inline abi_ulong get_sp_from_cpustate(CPUX86State *state)
     return state->regs[R_ESP];
 }
 
-#endif /* TARGET_SIGNAL_H */
+#endif /* X86_64_TARGET_SIGNAL_H */
diff --git a/linux-user/x86_64/target_structs.h b/linux-user/x86_64/target_structs.h
index d934056149..348982703e 100644
--- a/linux-user/x86_64/target_structs.h
+++ b/linux-user/x86_64/target_structs.h
@@ -16,8 +16,8 @@
  * 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 TARGET_STRUCTS_H
-#define TARGET_STRUCTS_H
+#ifndef X86_64_TARGET_STRUCTS_H
+#define X86_64_TARGET_STRUCTS_H
 
 struct target_ipc_perm {
     abi_int __key;                      /* Key.  */
diff --git a/linux-user/x86_64/target_syscall.h b/linux-user/x86_64/target_syscall.h
index feecd32d50..983fb23d9b 100644
--- a/linux-user/x86_64/target_syscall.h
+++ b/linux-user/x86_64/target_syscall.h
@@ -1,5 +1,5 @@
-#ifndef TARGET_SYSCALL_H
-#define TARGET_SYSCALL_H
+#ifndef X86_64_TARGET_SYSCALL_H
+#define X86_64_TARGET_SYSCALL_H
 
 #define __USER_CS	(0x33)
 #define __USER_DS	(0x2B)
@@ -104,4 +104,4 @@ struct target_msqid64_ds {
 #define TARGET_MLOCKALL_MCL_CURRENT 1
 #define TARGET_MLOCKALL_MCL_FUTURE  2
 
-#endif  /* TARGET_SYSCALL_H */
+#endif /* X86_64_TARGET_SYSCALL_H */
diff --git a/migration/migration.c b/migration/migration.c
index a56013662d..c4e019305c 100644
--- a/migration/migration.c
+++ b/migration/migration.c
@@ -418,11 +418,11 @@ static void process_incoming_migration_co(void *opaque)
 
 void migration_fd_process_incoming(QEMUFile *f)
 {
-    Coroutine *co = qemu_coroutine_create(process_incoming_migration_co);
+    Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, f);
 
     migrate_decompress_threads_create();
     qemu_file_set_blocking(f, false);
-    qemu_coroutine_enter(co, f);
+    qemu_coroutine_enter(co);
 }
 
 
diff --git a/migration/savevm.c b/migration/savevm.c
index 38b85ee77b..33a2911ec2 100644
--- a/migration/savevm.c
+++ b/migration/savevm.c
@@ -2200,12 +2200,31 @@ void hmp_delvm(Monitor *mon, const QDict *qdict)
 void hmp_info_snapshots(Monitor *mon, const QDict *qdict)
 {
     BlockDriverState *bs, *bs1;
+    BdrvNextIterator it1;
     QEMUSnapshotInfo *sn_tab, *sn;
+    bool no_snapshot = true;
     int nb_sns, i;
     int total;
-    int *available_snapshots;
+    int *global_snapshots;
     AioContext *aio_context;
 
+    typedef struct SnapshotEntry {
+        QEMUSnapshotInfo sn;
+        QTAILQ_ENTRY(SnapshotEntry) next;
+    } SnapshotEntry;
+
+    typedef struct ImageEntry {
+        const char *imagename;
+        QTAILQ_ENTRY(ImageEntry) next;
+        QTAILQ_HEAD(, SnapshotEntry) snapshots;
+    } ImageEntry;
+
+    QTAILQ_HEAD(, ImageEntry) image_list =
+        QTAILQ_HEAD_INITIALIZER(image_list);
+
+    ImageEntry *image_entry, *next_ie;
+    SnapshotEntry *snapshot_entry;
+
     bs = bdrv_all_find_vmstate_bs();
     if (!bs) {
         monitor_printf(mon, "No available block device supports snapshots\n");
@@ -2222,34 +2241,102 @@ void hmp_info_snapshots(Monitor *mon, const QDict *qdict)
         return;
     }
 
-    if (nb_sns == 0) {
+    for (bs1 = bdrv_first(&it1); bs1; bs1 = bdrv_next(&it1)) {
+        int bs1_nb_sns = 0;
+        ImageEntry *ie;
+        SnapshotEntry *se;
+        AioContext *ctx = bdrv_get_aio_context(bs1);
+
+        aio_context_acquire(ctx);
+        if (bdrv_can_snapshot(bs1)) {
+            sn = NULL;
+            bs1_nb_sns = bdrv_snapshot_list(bs1, &sn);
+            if (bs1_nb_sns > 0) {
+                no_snapshot = false;
+                ie = g_new0(ImageEntry, 1);
+                ie->imagename = bdrv_get_device_name(bs1);
+                QTAILQ_INIT(&ie->snapshots);
+                QTAILQ_INSERT_TAIL(&image_list, ie, next);
+                for (i = 0; i < bs1_nb_sns; i++) {
+                    se = g_new0(SnapshotEntry, 1);
+                    se->sn = sn[i];
+                    QTAILQ_INSERT_TAIL(&ie->snapshots, se, next);
+                }
+            }
+            g_free(sn);
+        }
+        aio_context_release(ctx);
+    }
+
+    if (no_snapshot) {
         monitor_printf(mon, "There is no snapshot available.\n");
         return;
     }
 
-    available_snapshots = g_new0(int, nb_sns);
+    global_snapshots = g_new0(int, nb_sns);
     total = 0;
     for (i = 0; i < nb_sns; i++) {
-        if (bdrv_all_find_snapshot(sn_tab[i].id_str, &bs1) == 0) {
-            available_snapshots[total] = i;
+        SnapshotEntry *next_sn;
+        if (bdrv_all_find_snapshot(sn_tab[i].name, &bs1) == 0) {
+            global_snapshots[total] = i;
             total++;
+            QTAILQ_FOREACH(image_entry, &image_list, next) {
+                QTAILQ_FOREACH_SAFE(snapshot_entry, &image_entry->snapshots,
+                                    next, next_sn) {
+                    if (!strcmp(sn_tab[i].name, snapshot_entry->sn.name)) {
+                        QTAILQ_REMOVE(&image_entry->snapshots, snapshot_entry,
+                                      next);
+                        g_free(snapshot_entry);
+                    }
+                }
+            }
         }
     }
 
+    monitor_printf(mon, "List of snapshots present on all disks:\n");
+
     if (total > 0) {
         bdrv_snapshot_dump((fprintf_function)monitor_printf, mon, NULL);
         monitor_printf(mon, "\n");
         for (i = 0; i < total; i++) {
-            sn = &sn_tab[available_snapshots[i]];
+            sn = &sn_tab[global_snapshots[i]];
+            /* The ID is not guaranteed to be the same on all images, so
+             * overwrite it.
+             */
+            pstrcpy(sn->id_str, sizeof(sn->id_str), "--");
             bdrv_snapshot_dump((fprintf_function)monitor_printf, mon, sn);
             monitor_printf(mon, "\n");
         }
     } else {
-        monitor_printf(mon, "There is no suitable snapshot available\n");
+        monitor_printf(mon, "None\n");
     }
 
+    QTAILQ_FOREACH(image_entry, &image_list, next) {
+        if (QTAILQ_EMPTY(&image_entry->snapshots)) {
+            continue;
+        }
+        monitor_printf(mon,
+                       "\nList of partial (non-loadable) snapshots on '%s':\n",
+                       image_entry->imagename);
+        bdrv_snapshot_dump((fprintf_function)monitor_printf, mon, NULL);
+        monitor_printf(mon, "\n");
+        QTAILQ_FOREACH(snapshot_entry, &image_entry->snapshots, next) {
+            bdrv_snapshot_dump((fprintf_function)monitor_printf, mon,
+                               &snapshot_entry->sn);
+            monitor_printf(mon, "\n");
+        }
+    }
+
+    QTAILQ_FOREACH_SAFE(image_entry, &image_list, next, next_ie) {
+        SnapshotEntry *next_sn;
+        QTAILQ_FOREACH_SAFE(snapshot_entry, &image_entry->snapshots, next,
+                            next_sn) {
+            g_free(snapshot_entry);
+        }
+        g_free(image_entry);
+    }
     g_free(sn_tab);
-    g_free(available_snapshots);
+    g_free(global_snapshots);
 
 }
 
diff --git a/monitor.c b/monitor.c
index ed09cdc261..d0ff246a16 100644
--- a/monitor.c
+++ b/monitor.c
@@ -58,7 +58,7 @@
 #include "qapi/qmp/qjson.h"
 #include "qapi/qmp/json-streamer.h"
 #include "qapi/qmp/json-parser.h"
-#include <qom/object_interfaces.h>
+#include "qom/object_interfaces.h"
 #include "cpu.h"
 #include "trace.h"
 #include "trace/control.h"
@@ -4093,15 +4093,6 @@ static void sortcmdlist(void)
     qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
 }
 
-
-/*
- * Local variables:
- *  c-indent-level: 4
- *  c-basic-offset: 4
- *  tab-width: 8
- * End:
- */
-
 /* These functions just adapt the readline interface in a typesafe way.  We
  * could cast function pointers but that discards compiler checks.
  */
diff --git a/nbd/server.c b/nbd/server.c
index a677e266ff..fbc82de932 100644
--- a/nbd/server.c
+++ b/nbd/server.c
@@ -106,7 +106,7 @@ static gboolean nbd_negotiate_continue(QIOChannel *ioc,
                                        GIOCondition condition,
                                        void *opaque)
 {
-    qemu_coroutine_enter(opaque, NULL);
+    qemu_coroutine_enter(opaque);
     return TRUE;
 }
 
@@ -1230,9 +1230,9 @@ static void nbd_read(void *opaque)
     NBDClient *client = opaque;
 
     if (client->recv_coroutine) {
-        qemu_coroutine_enter(client->recv_coroutine, NULL);
+        qemu_coroutine_enter(client->recv_coroutine);
     } else {
-        qemu_coroutine_enter(qemu_coroutine_create(nbd_trip), client);
+        qemu_coroutine_enter(qemu_coroutine_create(nbd_trip, client));
     }
 }
 
@@ -1240,7 +1240,7 @@ static void nbd_restart_write(void *opaque)
 {
     NBDClient *client = opaque;
 
-    qemu_coroutine_enter(client->send_coroutine, NULL);
+    qemu_coroutine_enter(client->send_coroutine);
 }
 
 static void nbd_set_handlers(NBDClient *client)
@@ -1324,6 +1324,6 @@ void nbd_client_new(NBDExport *exp,
     client->close = close_fn;
 
     data->client = client;
-    data->co = qemu_coroutine_create(nbd_co_client_start);
-    qemu_coroutine_enter(data->co, data);
+    data->co = qemu_coroutine_create(nbd_co_client_start, data);
+    qemu_coroutine_enter(data->co);
 }
diff --git a/net/tap-linux.h b/net/tap-linux.h
index 1dc3a9f279..2f36d100fc 100644
--- a/net/tap-linux.h
+++ b/net/tap-linux.h
@@ -50,4 +50,4 @@
 #define TUN_F_TSO_ECN	0x08	/* I can handle TSO with ECN bits. */
 #define TUN_F_UFO	0x10	/* I can handle UFO packets */
 
-#endif /* QEMU_TAP_H */
+#endif /* QEMU_TAP_LINUX_H */
diff --git a/net/tap_int.h b/net/tap_int.h
index 2378021c45..ae6888f74a 100644
--- a/net/tap_int.h
+++ b/net/tap_int.h
@@ -23,8 +23,8 @@
  * THE SOFTWARE.
  */
 
-#ifndef QEMU_TAP_H
-#define QEMU_TAP_H
+#ifndef NET_TAP_INT_H
+#define NET_TAP_INT_H
 
 #include "qemu-common.h"
 #include "qapi-types.h"
@@ -46,4 +46,4 @@ int tap_fd_enable(int fd);
 int tap_fd_disable(int fd);
 int tap_fd_get_ifname(int fd, char *ifname);
 
-#endif /* QEMU_TAP_H */
+#endif /* NET_TAP_INT_H */
diff --git a/pc-bios/s390-ccw.img b/pc-bios/s390-ccw.img
index ea5fd9a479..089f6ba5e9 100644
--- a/pc-bios/s390-ccw.img
+++ b/pc-bios/s390-ccw.img
Binary files differdiff --git a/pc-bios/s390-ccw/iplb.h b/pc-bios/s390-ccw/iplb.h
index 1cf509f497..86abc56a90 100644
--- a/pc-bios/s390-ccw/iplb.h
+++ b/pc-bios/s390-ccw/iplb.h
@@ -43,6 +43,16 @@ struct IplBlockFcp {
 } __attribute__ ((packed));
 typedef struct IplBlockFcp IplBlockFcp;
 
+struct IplBlockQemuScsi {
+    uint32_t lun;
+    uint16_t target;
+    uint16_t channel;
+    uint8_t  reserved0[77];
+    uint8_t  ssid;
+    uint16_t devno;
+} __attribute__ ((packed));
+typedef struct IplBlockQemuScsi IplBlockQemuScsi;
+
 struct IplParameterBlock {
     uint32_t len;
     uint8_t  reserved0[3];
@@ -55,6 +65,7 @@ struct IplParameterBlock {
     union {
         IplBlockCcw ccw;
         IplBlockFcp fcp;
+        IplBlockQemuScsi scsi;
     };
 } __attribute__ ((packed));
 typedef struct IplParameterBlock IplParameterBlock;
@@ -63,6 +74,7 @@ extern IplParameterBlock iplb __attribute__((__aligned__(PAGE_SIZE)));
 
 #define S390_IPL_TYPE_FCP 0x00
 #define S390_IPL_TYPE_CCW 0x02
+#define S390_IPL_TYPE_QEMU_SCSI 0xff
 
 static inline bool store_iplb(IplParameterBlock *iplb)
 {
diff --git a/pc-bios/s390-ccw/main.c b/pc-bios/s390-ccw/main.c
index 9446ecc235..345b848752 100644
--- a/pc-bios/s390-ccw/main.c
+++ b/pc-bios/s390-ccw/main.c
@@ -84,6 +84,18 @@ static void virtio_setup(void)
             debug_print_int("ssid ", blk_schid.ssid);
             found = find_dev(&schib, dev_no);
             break;
+        case S390_IPL_TYPE_QEMU_SCSI:
+        {
+            VDev *vdev = virtio_get_device();
+
+            vdev->scsi_device_selected = true;
+            vdev->selected_scsi_device.channel = iplb.scsi.channel;
+            vdev->selected_scsi_device.target = iplb.scsi.target;
+            vdev->selected_scsi_device.lun = iplb.scsi.lun;
+            blk_schid.ssid = iplb.scsi.ssid & 0x3;
+            found = find_dev(&schib, iplb.scsi.devno);
+            break;
+        }
         default:
             panic("List-directed IPL not supported yet!\n");
         }
diff --git a/pc-bios/s390-ccw/virtio-scsi.c b/pc-bios/s390-ccw/virtio-scsi.c
index 3bb48e917e..d850a8deed 100644
--- a/pc-bios/s390-ccw/virtio-scsi.c
+++ b/pc-bios/s390-ccw/virtio-scsi.c
@@ -204,6 +204,17 @@ static void virtio_scsi_locate_device(VDev *vdev)
     debug_print_int("config.scsi.max_target ", vdev->config.scsi.max_target);
     debug_print_int("config.scsi.max_lun    ", vdev->config.scsi.max_lun);
 
+    if (vdev->scsi_device_selected) {
+        sdev->channel = vdev->selected_scsi_device.channel;
+        sdev->target = vdev->selected_scsi_device.target;
+        sdev->lun = vdev->selected_scsi_device.lun;
+
+        IPL_check(sdev->channel == 0, "non-zero channel requested");
+        IPL_check(sdev->target <= vdev->config.scsi.max_target, "target# high");
+        IPL_check(sdev->lun <= vdev->config.scsi.max_lun, "LUN# high");
+        return;
+    }
+
     for (target = 0; target <= vdev->config.scsi.max_target; target++) {
         sdev->channel = channel;
         sdev->target = target; /* sdev->lun will be 0 here */
diff --git a/pc-bios/s390-ccw/virtio.h b/pc-bios/s390-ccw/virtio.h
index 3c6e91510e..eb35ea5faf 100644
--- a/pc-bios/s390-ccw/virtio.h
+++ b/pc-bios/s390-ccw/virtio.h
@@ -274,6 +274,8 @@ struct VDev {
     uint64_t scsi_last_block;
     uint32_t scsi_dev_cyls;
     uint8_t scsi_dev_heads;
+    bool scsi_device_selected;
+    ScsiDevice selected_scsi_device;
 };
 typedef struct VDev VDev;
 
diff --git a/qapi/block-core.json b/qapi/block-core.json
index ac8f5f61d4..3444a9bc3e 100644
--- a/qapi/block-core.json
+++ b/qapi/block-core.json
@@ -664,10 +664,12 @@
 # @stop: for guest operations, stop the virtual machine;
 #        for jobs, pause the job
 #
+# @auto: inherit the error handling policy of the backend (since: 2.7)
+#
 # Since: 1.3
 ##
 { 'enum': 'BlockdevOnError',
-  'data': ['report', 'ignore', 'enospc', 'stop'] }
+  'data': ['report', 'ignore', 'enospc', 'stop', 'auto'] }
 
 ##
 # @MirrorSyncMode:
@@ -713,7 +715,8 @@
 #
 # @type: the job type ('stream' for image streaming)
 #
-# @device: the block device name
+# @device: The job identifier. Originally the device name but other
+#          values are allowed since QEMU 2.7
 #
 # @len: the maximum progress value
 #
@@ -866,6 +869,9 @@
 ##
 # @DriveBackup
 #
+# @job-id: #optional identifier for the newly-created block job. If
+#          omitted, the device name will be used. (Since 2.7)
+#
 # @device: the name of the device which should be copied.
 #
 # @target: the target of the new image. If the file exists, or if it
@@ -903,8 +909,8 @@
 # Since: 1.6
 ##
 { 'struct': 'DriveBackup',
-  'data': { 'device': 'str', 'target': 'str', '*format': 'str',
-            'sync': 'MirrorSyncMode', '*mode': 'NewImageMode',
+  'data': { '*job-id': 'str', 'device': 'str', 'target': 'str',
+            '*format': 'str', 'sync': 'MirrorSyncMode', '*mode': 'NewImageMode',
             '*speed': 'int', '*bitmap': 'str',
             '*on-source-error': 'BlockdevOnError',
             '*on-target-error': 'BlockdevOnError' } }
@@ -912,6 +918,9 @@
 ##
 # @BlockdevBackup
 #
+# @job-id: #optional identifier for the newly-created block job. If
+#          omitted, the device name will be used. (Since 2.7)
+#
 # @device: the name of the device which should be copied.
 #
 # @target: the name of the backup target device.
@@ -938,7 +947,7 @@
 # Since: 2.3
 ##
 { 'struct': 'BlockdevBackup',
-  'data': { 'device': 'str', 'target': 'str',
+  'data': { '*job-id': 'str', 'device': 'str', 'target': 'str',
             'sync': 'MirrorSyncMode',
             '*speed': 'int',
             '*on-source-error': 'BlockdevOnError',
@@ -1004,6 +1013,9 @@
 # Live commit of data from overlay image nodes into backing nodes - i.e.,
 # writes data between 'top' and 'base' into 'base'.
 #
+# @job-id: #optional identifier for the newly-created block job. If
+#          omitted, the device name will be used. (Since 2.7)
+#
 # @device:  the name of the device
 #
 # @base:   #optional The file name of the backing image to write data into.
@@ -1055,7 +1067,7 @@
 #
 ##
 { 'command': 'block-commit',
-  'data': { 'device': 'str', '*base': 'str', '*top': 'str',
+  'data': { '*job-id': 'str', 'device': 'str', '*base': 'str', '*top': 'str',
             '*backing-file': 'str', '*speed': 'int' } }
 
 ##
@@ -1108,6 +1120,9 @@
 #
 # Start mirroring a block device's writes to a new destination.
 #
+# @job-id: #optional identifier for the newly-created block job. If
+#          omitted, the device name will be used. (Since 2.7)
+#
 # @device:  the name of the device whose writes should be mirrored.
 #
 # @target: the target of the new image. If the file exists, or if it
@@ -1160,8 +1175,8 @@
 # Since 1.3
 ##
 { 'command': 'drive-mirror',
-  'data': { 'device': 'str', 'target': 'str', '*format': 'str',
-            '*node-name': 'str', '*replaces': 'str',
+  'data': { '*job-id': 'str', 'device': 'str', 'target': 'str',
+            '*format': 'str', '*node-name': 'str', '*replaces': 'str',
             'sync': 'MirrorSyncMode', '*mode': 'NewImageMode',
             '*speed': 'int', '*granularity': 'uint32',
             '*buf-size': 'int', '*on-source-error': 'BlockdevOnError',
@@ -1243,6 +1258,9 @@
 #
 # Start mirroring a block device's writes to a new destination.
 #
+# @job-id: #optional identifier for the newly-created block job. If
+#          omitted, the device name will be used. (Since 2.7)
+#
 # @device: the name of the device whose writes should be mirrored.
 #
 # @target: the id or node-name of the block device to mirror to. This mustn't be
@@ -1279,7 +1297,7 @@
 # Since 2.6
 ##
 { 'command': 'blockdev-mirror',
-  'data': { 'device': 'str', 'target': 'str',
+  'data': { '*job-id': 'str', 'device': 'str', 'target': 'str',
             '*replaces': 'str',
             'sync': 'MirrorSyncMode',
             '*speed': 'int', '*granularity': 'uint32',
@@ -1413,6 +1431,9 @@
 # On successful completion the image file is updated to drop the backing file
 # and the BLOCK_JOB_COMPLETED event is emitted.
 #
+# @job-id: #optional identifier for the newly-created block job. If
+#          omitted, the device name will be used. (Since 2.7)
+#
 # @device: the device name
 #
 # @base:   #optional the common backing file name
@@ -1444,8 +1465,9 @@
 # Since: 1.1
 ##
 { 'command': 'block-stream',
-  'data': { 'device': 'str', '*base': 'str', '*backing-file': 'str',
-            '*speed': 'int', '*on-error': 'BlockdevOnError' } }
+  'data': { '*job-id': 'str', 'device': 'str', '*base': 'str',
+            '*backing-file': 'str', '*speed': 'int',
+            '*on-error': 'BlockdevOnError' } }
 
 ##
 # @block-job-set-speed:
@@ -1456,7 +1478,9 @@
 #
 # Throttling can be disabled by setting the speed to 0.
 #
-# @device: the device name
+# @device: The job identifier. This used to be a device name (hence
+#          the name of the parameter), but since QEMU 2.7 it can have
+#          other values.
 #
 # @speed:  the maximum speed, in bytes per second, or 0 for unlimited.
 #          Defaults to 0.
@@ -1487,7 +1511,9 @@
 # operation can be started at a later time to finish copying all data from the
 # backing file.
 #
-# @device: the device name
+# @device: The job identifier. This used to be a device name (hence
+#          the name of the parameter), but since QEMU 2.7 it can have
+#          other values.
 #
 # @force: #optional whether to allow cancellation of a paused job (default
 #         false).  Since 1.3.
@@ -1513,7 +1539,9 @@
 # the operation is actually paused.  Cancelling a paused job automatically
 # resumes it.
 #
-# @device: the device name
+# @device: The job identifier. This used to be a device name (hence
+#          the name of the parameter), but since QEMU 2.7 it can have
+#          other values.
 #
 # Returns: Nothing on success
 #          If no background operation is active on this device, DeviceNotActive
@@ -1533,7 +1561,9 @@
 #
 # This command also clears the error status of the job.
 #
-# @device: the device name
+# @device: The job identifier. This used to be a device name (hence
+#          the name of the parameter), but since QEMU 2.7 it can have
+#          other values.
 #
 # Returns: Nothing on success
 #          If no background operation is active on this device, DeviceNotActive
@@ -1559,7 +1589,9 @@
 #
 # A cancelled or paused job cannot be completed.
 #
-# @device: the device name
+# @device: The job identifier. This used to be a device name (hence
+#          the name of the parameter), but since QEMU 2.7 it can have
+#          other values.
 #
 # Returns: Nothing on success
 #          If no background operation is active on this device, DeviceNotActive
@@ -2049,20 +2081,8 @@
 # @discard:       #optional discard-related options (default: ignore)
 # @cache:         #optional cache-related options
 # @aio:           #optional AIO backend (default: threads)
-# @rerror:        #optional how to handle read errors on the device
-#                 (default: report)
-# @werror:        #optional how to handle write errors on the device
-#                 (default: enospc)
 # @read-only:     #optional whether the block device should be read-only
 #                 (default: false)
-# @stats-account-invalid: #optional whether to include invalid
-#                         operations when computing last access statistics
-#                         (default: true) (Since 2.5)
-# @stats-account-failed: #optional whether to include failed
-#                         operations when computing latency and last
-#                         access statistics (default: true) (Since 2.5)
-# @stats-intervals: #optional list of intervals for collecting I/O
-#                   statistics, in seconds (default: none) (Since 2.5)
 # @detect-zeroes: #optional detect and optimize zero writes (Since 2.1)
 #                 (default: off)
 #
@@ -2072,17 +2092,13 @@
 ##
 { 'union': 'BlockdevOptions',
   'base': { 'driver': 'BlockdevDriver',
+# TODO 'id' is a BB-level option, remove it
             '*id': 'str',
             '*node-name': 'str',
             '*discard': 'BlockdevDiscardOptions',
             '*cache': 'BlockdevCacheOptions',
             '*aio': 'BlockdevAioOptions',
-            '*rerror': 'BlockdevOnError',
-            '*werror': 'BlockdevOnError',
             '*read-only': 'bool',
-            '*stats-account-invalid': 'bool',
-            '*stats-account-failed': 'bool',
-            '*stats-intervals': ['int'],
             '*detect-zeroes': 'BlockdevDetectZeroesOptions' },
   'discriminator': 'driver',
   'data': {
@@ -2405,7 +2421,8 @@
 #
 # @type: job type
 #
-# @device: device name
+# @device: The job identifier. Originally the device name but other
+#          values are allowed since QEMU 2.7
 #
 # @len: maximum progress value
 #
@@ -2436,7 +2453,8 @@
 #
 # @type: job type
 #
-# @device: device name
+# @device: The job identifier. Originally the device name but other
+#          values are allowed since QEMU 2.7
 #
 # @len: maximum progress value
 #
@@ -2459,7 +2477,8 @@
 #
 # Emitted when a block job encounters an error
 #
-# @device: device name
+# @device: The job identifier. Originally the device name but other
+#          values are allowed since QEMU 2.7
 #
 # @operation: I/O operation
 #
@@ -2479,7 +2498,8 @@
 #
 # @type: job type
 #
-# @device: device name
+# @device: The job identifier. Originally the device name but other
+#          values are allowed since QEMU 2.7
 #
 # @len: maximum progress value
 #
diff --git a/qemu-img.c b/qemu-img.c
index ea5970bdd3..2e40e1fc84 100644
--- a/qemu-img.c
+++ b/qemu-img.c
@@ -920,7 +920,7 @@ static int img_commit(int argc, char **argv)
         .bs   = bs,
     };
 
-    commit_active_start(bs, base_bs, 0, BLOCKDEV_ON_ERROR_REPORT,
+    commit_active_start("commit", bs, base_bs, 0, BLOCKDEV_ON_ERROR_REPORT,
                         common_block_job_cb, &cbi, &local_err);
     if (local_err) {
         goto done;
@@ -3283,7 +3283,7 @@ static int img_resize(int argc, char **argv)
         error_report("Image is read-only");
         break;
     default:
-        error_report("Error resizing image (%d)", -ret);
+        error_report("Error resizing image: %s", strerror(-ret));
         break;
     }
 out:
diff --git a/qemu-io-cmds.c b/qemu-io-cmds.c
index 09e879f872..6e29edb1fd 100644
--- a/qemu-io-cmds.c
+++ b/qemu-io-cmds.c
@@ -389,9 +389,9 @@ create_iovec(BlockBackend *blk, QEMUIOVector *qiov, char **argv, int nr_iov,
             goto fail;
         }
 
-        /* should be SIZE_T_MAX, but that doesn't exist */
-        if (len > INT_MAX) {
-            printf("Argument '%s' exceeds maximum size %d\n", arg, INT_MAX);
+        if (len > SIZE_MAX) {
+            printf("Argument '%s' exceeds maximum size %llu\n", arg,
+                   (unsigned long long)SIZE_MAX);
             goto fail;
         }
 
@@ -479,12 +479,12 @@ static int do_co_pwrite_zeroes(BlockBackend *blk, int64_t offset,
         .done   = false,
     };
 
-    if (count >> BDRV_SECTOR_BITS > INT_MAX) {
+    if (count > INT_MAX) {
         return -ERANGE;
     }
 
-    co = qemu_coroutine_create(co_pwrite_zeroes_entry);
-    qemu_coroutine_enter(co, &data);
+    co = qemu_coroutine_create(co_pwrite_zeroes_entry, &data);
+    qemu_coroutine_enter(co);
     while (!data.done) {
         aio_poll(blk_get_aio_context(blk), true);
     }
@@ -500,7 +500,7 @@ static int do_write_compressed(BlockBackend *blk, char *buf, int64_t offset,
 {
     int ret;
 
-    if (count >> 9 > INT_MAX) {
+    if (count >> 9 > BDRV_REQUEST_MAX_SECTORS) {
         return -ERANGE;
     }
 
@@ -1688,9 +1688,9 @@ static int discard_f(BlockBackend *blk, int argc, char **argv)
     if (count < 0) {
         print_cvtnum_err(count, argv[optind]);
         return 0;
-    } else if (count >> BDRV_SECTOR_BITS > INT_MAX) {
+    } else if (count >> BDRV_SECTOR_BITS > BDRV_REQUEST_MAX_SECTORS) {
         printf("length cannot exceed %"PRIu64", given %s\n",
-               (uint64_t)INT_MAX << BDRV_SECTOR_BITS,
+               (uint64_t)BDRV_REQUEST_MAX_SECTORS << BDRV_SECTOR_BITS,
                argv[optind]);
         return 0;
     }
diff --git a/qemu-options.h b/qemu-options.h
index 89a009ee96..b4ee63cd60 100644
--- a/qemu-options.h
+++ b/qemu-options.h
@@ -25,8 +25,8 @@
  * THE SOFTWARE.
  */
 
-#ifndef _QEMU_OPTIONS_H_
-#define _QEMU_OPTIONS_H_
+#ifndef QEMU_OPTIONS_H
+#define QEMU_OPTIONS_H
 
 enum {
 #define QEMU_OPTIONS_GENERATE_ENUM
diff --git a/qga/service-win32.h b/qga/service-win32.h
index 3b9e87024b..89e99dfede 100644
--- a/qga/service-win32.h
+++ b/qga/service-win32.h
@@ -10,8 +10,9 @@
  * 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 QGA_SERVICE_H
-#define QGA_SERVICE_H
+
+#ifndef QGA_SERVICE_WIN32_H
+#define QGA_SERVICE_WIN32_H
 
 #include <windows.h>
 
diff --git a/qga/vss-win32/install.cpp b/qga/vss-win32/install.cpp
index cd9cdb4a24..f4160a3a86 100644
--- a/qga/vss-win32/install.cpp
+++ b/qga/vss-win32/install.cpp
@@ -13,8 +13,7 @@
 #include "qemu/osdep.h"
 
 #include "vss-common.h"
-#include "inc/win2003/vscoordint.h"
-
+#include <inc/win2003/vscoordint.h>
 #include <comadmin.h>
 #include <wbemidl.h>
 #include <comdef.h>
diff --git a/qga/vss-win32/provider.cpp b/qga/vss-win32/provider.cpp
index d977393e33..ef9466909a 100644
--- a/qga/vss-win32/provider.cpp
+++ b/qga/vss-win32/provider.cpp
@@ -12,8 +12,8 @@
 
 #include "qemu/osdep.h"
 #include "vss-common.h"
-#include "inc/win2003/vscoordint.h"
-#include "inc/win2003/vsprov.h"
+#include <inc/win2003/vscoordint.h>
+#include <inc/win2003/vsprov.h>
 
 #define VSS_TIMEOUT_MSEC (60*1000)
 
diff --git a/qga/vss-win32/requester.cpp b/qga/vss-win32/requester.cpp
index 889052dedd..0cd2f0ee7f 100644
--- a/qga/vss-win32/requester.cpp
+++ b/qga/vss-win32/requester.cpp
@@ -13,8 +13,8 @@
 #include "qemu/osdep.h"
 #include "vss-common.h"
 #include "requester.h"
-#include "inc/win2003/vswriter.h"
-#include "inc/win2003/vsbackup.h"
+#include <inc/win2003/vswriter.h>
+#include <inc/win2003/vsbackup.h>
 
 /* Max wait time for frozen event (VSS can only hold writes for 10 seconds) */
 #define VSS_TIMEOUT_FREEZE_MSEC 10000
diff --git a/qga/vss-win32/vss-common.h b/qga/vss-win32/vss-common.h
index 91dae0c38d..c81a8564b2 100644
--- a/qga/vss-win32/vss-common.h
+++ b/qga/vss-win32/vss-common.h
@@ -10,8 +10,8 @@
  * See the COPYING file in the top-level directory.
  */
 
-#ifndef VSS_WIN32_H
-#define VSS_WIN32_H
+#ifndef VSS_COMMON_H
+#define VSS_COMMON_H
 
 #define __MIDL_user_allocate_free_DEFINED__
 #include <windows.h>
@@ -50,7 +50,7 @@
  * VSS headers must be installed from Microsoft VSS SDK 7.2 available at:
  * http://www.microsoft.com/en-us/download/details.aspx?id=23490
  */
-#include "inc/win2003/vss.h"
+#include <inc/win2003/vss.h>
 
 /* Macros to convert char definitions to wchar */
 #define _L(a) L##a
diff --git a/qmp-commands.hx b/qmp-commands.hx
index 6937e83cbd..c46c65ce2d 100644
--- a/qmp-commands.hx
+++ b/qmp-commands.hx
@@ -1106,7 +1106,7 @@ EQMP
 
     {
         .name       = "block-stream",
-        .args_type  = "device:B,base:s?,speed:o?,backing-file:s?,on-error:s?",
+        .args_type  = "job-id:s?,device:B,base:s?,speed:o?,backing-file:s?,on-error:s?",
         .mhandler.cmd_new = qmp_marshal_block_stream,
     },
 
@@ -1118,6 +1118,8 @@ Copy data from a backing file into a block device.
 
 Arguments:
 
+- "job-id": Identifier for the newly-created block job. If omitted,
+            the device name will be used. (json-string, optional)
 - "device": The device's ID, must be unique (json-string)
 - "base": The file name of the backing image above which copying starts
           (json-string, optional)
@@ -1149,7 +1151,7 @@ EQMP
 
     {
         .name       = "block-commit",
-        .args_type  = "device:B,base:s?,top:s?,backing-file:s?,speed:o?",
+        .args_type  = "job-id:s?,device:B,base:s?,top:s?,backing-file:s?,speed:o?",
         .mhandler.cmd_new = qmp_marshal_block_commit,
     },
 
@@ -1162,6 +1164,8 @@ data between 'top' and 'base' into 'base'.
 
 Arguments:
 
+- "job-id": Identifier for the newly-created block job. If omitted,
+            the device name will be used. (json-string, optional)
 - "device": The device's ID, must be unique (json-string)
 - "base": The file name of the backing image to write data into.
           If not specified, this is the deepest backing image
@@ -1212,8 +1216,8 @@ EQMP
 
     {
         .name       = "drive-backup",
-        .args_type  = "sync:s,device:B,target:s,speed:i?,mode:s?,format:s?,"
-                      "bitmap:s?,on-source-error:s?,on-target-error:s?",
+        .args_type  = "job-id:s?,sync:s,device:B,target:s,speed:i?,mode:s?,"
+                      "format:s?,bitmap:s?,on-source-error:s?,on-target-error:s?",
         .mhandler.cmd_new = qmp_marshal_drive_backup,
     },
 
@@ -1229,6 +1233,8 @@ block-job-cancel command.
 
 Arguments:
 
+- "job-id": Identifier for the newly-created block job. If omitted,
+            the device name will be used. (json-string, optional)
 - "device": the name of the device which should be copied.
             (json-string)
 - "target": the target of the new image. If the file exists, or if it is a
@@ -1266,7 +1272,7 @@ EQMP
 
     {
         .name       = "blockdev-backup",
-        .args_type  = "sync:s,device:B,target:B,speed:i?,"
+        .args_type  = "job-id:s?,sync:s,device:B,target:B,speed:i?,"
                       "on-source-error:s?,on-target-error:s?",
         .mhandler.cmd_new = qmp_marshal_blockdev_backup,
     },
@@ -1280,6 +1286,8 @@ as backup target.
 
 Arguments:
 
+- "job-id": Identifier for the newly-created block job. If omitted,
+            the device name will be used. (json-string, optional)
 - "device": the name of the device which should be copied.
             (json-string)
 - "target": the name of the backup target device. (json-string)
@@ -1656,8 +1664,8 @@ EQMP
 
     {
         .name       = "drive-mirror",
-        .args_type  = "sync:s,device:B,target:s,speed:i?,mode:s?,format:s?,"
-                      "node-name:s?,replaces:s?,"
+        .args_type  = "job-id:s?,sync:s,device:B,target:s,speed:i?,mode:s?,"
+                      "format:s?,node-name:s?,replaces:s?,"
                       "on-source-error:s?,on-target-error:s?,"
                       "unmap:b?,"
                       "granularity:i?,buf-size:i?",
@@ -1677,6 +1685,8 @@ of the source.
 
 Arguments:
 
+- "job-id": Identifier for the newly-created block job. If omitted,
+            the device name will be used. (json-string, optional)
 - "device": device name to operate on (json-string)
 - "target": name of new image file (json-string)
 - "format": format of new image (json-string, optional)
@@ -1720,7 +1730,7 @@ EQMP
 
     {
         .name       = "blockdev-mirror",
-        .args_type  = "sync:s,device:B,target:B,replaces:s?,speed:i?,"
+        .args_type  = "job-id:s?,sync:s,device:B,target:B,replaces:s?,speed:i?,"
                       "on-source-error:s?,on-target-error:s?,"
                       "granularity:i?,buf-size:i?",
         .mhandler.cmd_new = qmp_marshal_blockdev_mirror,
@@ -1735,6 +1745,8 @@ specifies the target of mirror operation.
 
 Arguments:
 
+- "job-id": Identifier for the newly-created block job. If omitted,
+            the device name will be used. (json-string, optional)
 - "device": device name to operate on (json-string)
 - "target": device name to mirror to (json-string)
 - "replaces": the block driver node name to replace when finished
diff --git a/roms/openbios b/roms/openbios
-Subproject 422b916649aa0db8c5edadccb22387b3e807e3b
+Subproject 36785d7b59726beca320a0b99cfa0a903782c6f
diff --git a/scripts/clean-header-guards.pl b/scripts/clean-header-guards.pl
new file mode 100755
index 0000000000..54ab99ae29
--- /dev/null
+++ b/scripts/clean-header-guards.pl
@@ -0,0 +1,213 @@
+#!/usr/bin/perl -w
+#
+# Clean up include guards in headers
+#
+# Copyright (C) 2016 Red Hat, Inc.
+#
+# Authors:
+#  Markus Armbruster <armbru@redhat.com>
+#
+# 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.
+#
+# Usage: scripts/clean-header-guards.pl [OPTION]... [FILE]...
+#     -c CC     Use a compiler other than cc
+#     -n        Suppress actual cleanup
+#     -v        Show which files are cleaned up, and which are skipped
+#
+# Does the following:
+# - Header files without a recognizable header guard are skipped.
+# - Clean up any untidy header guards in-place.  Warn if the cleanup
+#   renames guard symbols, and explain how to find occurences of these
+#   symbols that may have to be updated manually.
+# - Warn about duplicate header guard symbols.  To make full use of
+#   this warning, you should clean up *all* headers in one run.
+# - Warn when preprocessing a header with its guard symbol defined
+#   produces anything but whitespace.  The preprocessor is run like
+#   "cc -E -DGUARD_H -c -P -", and fed the test program on stdin.
+
+use strict;
+use Getopt::Std;
+
+# Stuff we don't want to clean because we import it into our tree:
+my $exclude = qr,^(disas/libvixl/|include/standard-headers/
+    |linux-headers/|pc-bios/|tests/tcg/|tests/multiboot/),x;
+# Stuff that is expected to fail the preprocessing test:
+my $exclude_cpp = qr,^include/libdecnumber/decNumberLocal.h,;
+
+my %guarded = ();
+my %old_guard = ();
+
+our $opt_c = "cc";
+our $opt_n = 0;
+our $opt_v = 0;
+getopts("c:nv");
+
+sub skipping {
+    my ($fname, $msg, $line1, $line2) = @_;
+
+    return if !$opt_v or $fname =~ $exclude;
+    print "$fname skipped: $msg\n";
+    print "    $line1" if defined $line1;
+    print "    $line2" if defined $line2;
+}
+
+sub gripe {
+    my ($fname, $msg) = @_;
+    return if $fname =~ $exclude;
+    print STDERR "$fname: warning: $msg\n";
+}
+
+sub slurp {
+    my ($fname) = @_;
+    local $/;                   # slurp
+    open(my $in, "<", $fname)
+        or die "can't open $fname for reading: $!";
+    return <$in>;
+}
+
+sub unslurp {
+    my ($fname, $contents) = @_;
+    open (my $out, ">", $fname)
+        or die "can't open $fname for writing: $!";
+    print $out $contents
+        or die "error writing $fname: $!";
+    close $out
+        or die "error writing $fname: $!";
+}
+
+sub fname2guard {
+    my ($fname) = @_;
+    $fname =~ tr/a-z/A-Z/;
+    $fname =~ tr/A-Z0-9/_/cs;
+    return $fname;
+}
+
+sub preprocess {
+    my ($fname, $guard) = @_;
+
+    open(my $pipe, "-|", "$opt_c -E -D$guard -c -P - <$fname")
+        or die "can't run $opt_c: $!";
+    while (<$pipe>) {
+        if ($_ =~ /\S/) {
+            gripe($fname, "not blank after preprocessing");
+            last;
+        }
+    }
+    close $pipe
+        or gripe($fname, "preprocessing failed ($opt_c exit status $?)");
+}
+
+for my $fname (@ARGV) {
+    my $text = slurp($fname);
+
+    $text =~ m,\A(\s*\n|\s*//\N*\n|\s*/\*.*?\*/\s*\n)*|,msg;
+    my $pre = $&;
+    unless ($text =~ /\G(.*\n)/g) {
+        $text =~ /\G.*/;
+        skipping($fname, "no recognizable header guard", "$&\n");
+        next;
+    }
+    my $line1 = $1;
+    unless ($text =~ /\G(.*\n)/g) {
+        $text =~ /\G.*/;
+        skipping($fname, "no recognizable header guard", "$&\n");
+        next;
+    }
+    my $line2 = $1;
+    my $body = substr($text, pos($text));
+
+    unless ($line1 =~ /^\s*\#\s*(if\s*\!\s*defined(\s*\()?|ifndef)\s*
+                       ([A-Za-z0-9_]+)/x) {
+        skipping($fname, "no recognizable header guard", $line1, $line2);
+        next;
+    }
+    my $guard = $3;
+    unless ($line2 =~ /^\s*\#\s*define\s+([A-Za-z0-9_]+)/) {
+        skipping($fname, "no recognizable header guard", $line1, $line2);
+        next;
+    }
+    my $guard2 = $1;
+    unless ($guard2 eq $guard) {
+        skipping($fname, "mismatched header guard ($guard vs. $guard2) ",
+                 $line1, $line2);
+        next;
+    }
+
+    unless ($body =~ m,\A((.*\n)*)
+                       (\s*\#\s*endif\s*(/\*\s*.*\s*\*/\s*)?\n?)
+                       (\n|\s)*\Z,x) {
+        skipping($fname, "can't find end of header guard");
+        next;
+    }
+    $body = $1;
+    my $line3 = $3;
+    my $endif_comment = $4;
+
+    my $oldg = $guard;
+
+    unless ($fname =~ $exclude) {
+        my @issues = ();
+        $guard =~ tr/a-z/A-Z/
+            and push @issues, "contains lowercase letters";
+        $guard =~ s/^_+//
+            and push @issues, "is a reserved identifier";
+        $guard =~ s/(_H)?_*$/_H/
+            and $& ne "_H" and push @issues, "doesn't end with _H";
+        unless ($guard =~ /^[A-Z][A-Z0-9_]*_H/) {
+            skipping($fname, "can't clean up odd guard symbol $oldg\n",
+                     $line1, $line2);
+            next;
+        }
+
+        my $exp = fname2guard($fname =~ s,.*/,,r);
+        unless ($guard =~ /\Q$exp\E\Z/) {
+            $guard = fname2guard($fname =~ s,^include/,,r);
+            push @issues, "doesn't match the file name";
+        }
+        if (@issues and $opt_v) {
+            print "$fname guard $oldg needs cleanup:\n    ",
+                join(", ", @issues), "\n";
+        }
+    }
+
+    $old_guard{$guard} = $oldg
+        if $guard ne $oldg;
+
+    if (exists $guarded{$guard}) {
+        gripe($fname, "guard $guard also used by $guarded{$guard}");
+    } else {
+        $guarded{$guard} = $fname;
+    }
+
+    unless ($fname =~ $exclude) {
+        my $newl1 = "#ifndef $guard\n";
+        my $newl2 = "#define $guard\n";
+        my $newl3 = "#endif\n";
+        $newl3 =~ s,\Z, /* $guard */, if defined $endif_comment;
+        if ($line1 ne $newl1 or $line2 ne $newl2 or $line3 ne $newl3) {
+            $pre =~ s/\n*\Z/\n\n/ if $pre =~ /\N/;
+            $body =~ s/\A\n*/\n/;
+            if ($opt_n) {
+                print "$fname would be cleaned up\n" if $opt_v;
+            } else {
+                unslurp($fname, "$pre$newl1$newl2$body$newl3");
+                print "$fname cleaned up\n" if $opt_v;
+            }
+        }
+    }
+
+    preprocess($fname, $opt_n ? $oldg : $guard)
+        unless $fname =~ $exclude or $fname =~ $exclude_cpp;
+}
+
+if (%old_guard) {
+    print STDERR "warning: guard symbol renaming may break things\n";
+    for my $guard (sort keys %old_guard) {
+        print STDERR "    $old_guard{$guard} -> $guard\n";
+    }
+    print STDERR "To find uses that may have to be updated try:\n";
+    print STDERR "    git grep -Ew '", join("|", sort values %old_guard),
+        "'\n";
+}
diff --git a/slirp/bootp.c b/slirp/bootp.c
index 7b3232bdc4..5a4646c182 100644
--- a/slirp/bootp.c
+++ b/slirp/bootp.c
@@ -22,7 +22,7 @@
  * THE SOFTWARE.
  */
 #include "qemu/osdep.h"
-#include <slirp.h>
+#include "slirp.h"
 
 #if defined(_WIN32)
 /* Windows ntohl() returns an u_long value.
diff --git a/slirp/bootp.h b/slirp/bootp.h
index ec3b68704c..394525733e 100644
--- a/slirp/bootp.h
+++ b/slirp/bootp.h
@@ -1,6 +1,7 @@
 /* bootp/dhcp defines */
+
 #ifndef SLIRP_BOOTP_H
-#define SLIRP_BOOTP_H 1
+#define SLIRP_BOOTP_H
 
 #define BOOTP_SERVER	67
 #define BOOTP_CLIENT	68
diff --git a/slirp/cksum.c b/slirp/cksum.c
index 2ad0e6540d..6d73abf4a0 100644
--- a/slirp/cksum.c
+++ b/slirp/cksum.c
@@ -31,7 +31,7 @@
  */
 
 #include "qemu/osdep.h"
-#include <slirp.h>
+#include "slirp.h"
 
 /*
  * Checksum routine for Internet Protocol family headers (Portable Version).
diff --git a/slirp/if.c b/slirp/if.c
index 9b02180db0..51ae0d0e9a 100644
--- a/slirp/if.c
+++ b/slirp/if.c
@@ -6,7 +6,7 @@
  */
 
 #include "qemu/osdep.h"
-#include <slirp.h>
+#include "slirp.h"
 #include "qemu/timer.h"
 
 static void
diff --git a/slirp/if.h b/slirp/if.h
index c7a5c5724d..69569c10df 100644
--- a/slirp/if.h
+++ b/slirp/if.h
@@ -5,8 +5,8 @@
  * terms and conditions of the copyright.
  */
 
-#ifndef _IF_H_
-#define _IF_H_
+#ifndef IF_H
+#define IF_H
 
 #define IF_COMPRESS	0x01	/* We want compression */
 #define IF_NOCOMPRESS	0x02	/* Do not do compression */
diff --git a/slirp/ip.h b/slirp/ip.h
index e2ee5e304c..1df6723357 100644
--- a/slirp/ip.h
+++ b/slirp/ip.h
@@ -30,8 +30,8 @@
  * ip.h,v 1.3 1994/08/21 05:27:30 paul Exp
  */
 
-#ifndef _IP_H_
-#define _IP_H_
+#ifndef IP_H
+#define IP_H
 
 #ifdef HOST_WORDS_BIGENDIAN
 # undef NTOHL
diff --git a/slirp/ip6.h b/slirp/ip6.h
index da23de66f1..0908855f0f 100644
--- a/slirp/ip6.h
+++ b/slirp/ip6.h
@@ -3,8 +3,8 @@
  * Guillaume Subiron, Yann Bordenave, Serigne Modou Wagne.
  */
 
-#ifndef SLIRP_IP6_H_
-#define SLIRP_IP6_H_
+#ifndef SLIRP_IP6_H
+#define SLIRP_IP6_H
 
 #include "net/eth.h"
 
diff --git a/slirp/ip6_icmp.h b/slirp/ip6_icmp.h
index 2282d29076..b3378b17b5 100644
--- a/slirp/ip6_icmp.h
+++ b/slirp/ip6_icmp.h
@@ -3,8 +3,8 @@
  * Guillaume Subiron, Yann Bordenave, Serigne Modou Wagne.
  */
 
-#ifndef SLIRP_NETINET_ICMP6_H_
-#define SLIRP_NETINET_ICMP6_H_
+#ifndef SLIRP_IP6_ICMP_H
+#define SLIRP_IP6_ICMP_H
 
 /*
  * Interface Control Message Protocol version 6 Definitions.
diff --git a/slirp/ip_icmp.h b/slirp/ip_icmp.h
index 846761d08e..d88ab34c1b 100644
--- a/slirp/ip_icmp.h
+++ b/slirp/ip_icmp.h
@@ -30,8 +30,8 @@
  * ip_icmp.h,v 1.4 1995/05/30 08:09:43 rgrimes Exp
  */
 
-#ifndef _NETINET_IP_ICMP_H_
-#define _NETINET_IP_ICMP_H_
+#ifndef NETINET_IP_ICMP_H
+#define NETINET_IP_ICMP_H
 
 /*
  * Interface Control Message Protocol Definitions.
diff --git a/slirp/ip_input.c b/slirp/ip_input.c
index 34fba2b7dd..348e1dca5a 100644
--- a/slirp/ip_input.c
+++ b/slirp/ip_input.c
@@ -39,7 +39,7 @@
  */
 
 #include "qemu/osdep.h"
-#include <slirp.h>
+#include "slirp.h"
 #include "ip_icmp.h"
 
 static struct ip *ip_reass(Slirp *slirp, struct ip *ip, struct ipq *fp);
diff --git a/slirp/ip_output.c b/slirp/ip_output.c
index 0d6b3b8312..db403f04c1 100644
--- a/slirp/ip_output.c
+++ b/slirp/ip_output.c
@@ -39,7 +39,7 @@
  */
 
 #include "qemu/osdep.h"
-#include <slirp.h>
+#include "slirp.h"
 
 /* Number of packets queued before we start sending
  * (to prevent allocing too many mbufs) */
diff --git a/slirp/libslirp.h b/slirp/libslirp.h
index b6fc584219..f90f0f524c 100644
--- a/slirp/libslirp.h
+++ b/slirp/libslirp.h
@@ -1,5 +1,5 @@
-#ifndef _LIBSLIRP_H
-#define _LIBSLIRP_H
+#ifndef LIBSLIRP_H
+#define LIBSLIRP_H
 
 #include "qemu-common.h"
 
diff --git a/slirp/main.h b/slirp/main.h
index f2e58cfe2d..90053ce5ec 100644
--- a/slirp/main.h
+++ b/slirp/main.h
@@ -4,8 +4,9 @@
  * Please read the file COPYRIGHT for the
  * terms and conditions of the copyright.
  */
+
 #ifndef SLIRP_MAIN_H
-#define SLIRP_MAIN_H 1
+#define SLIRP_MAIN_H
 
 #ifdef HAVE_SYS_SELECT_H
 #include <sys/select.h>
diff --git a/slirp/mbuf.c b/slirp/mbuf.c
index d136988397..7eddc217e4 100644
--- a/slirp/mbuf.c
+++ b/slirp/mbuf.c
@@ -16,7 +16,7 @@
  */
 
 #include "qemu/osdep.h"
-#include <slirp.h>
+#include "slirp.h"
 
 #define MBUF_THRESH 30
 
diff --git a/slirp/mbuf.h b/slirp/mbuf.h
index 36fb814097..893601ff9d 100644
--- a/slirp/mbuf.h
+++ b/slirp/mbuf.h
@@ -30,8 +30,8 @@
  * mbuf.h,v 1.9 1994/11/14 13:54:20 bde Exp
  */
 
-#ifndef _MBUF_H_
-#define _MBUF_H_
+#ifndef MBUF_H
+#define MBUF_H
 
 #define MINCSIZE 4096	/* Amount to increase mbuf if too small */
 
diff --git a/slirp/misc.c b/slirp/misc.c
index 1a0ea1be4e..88e9d94197 100644
--- a/slirp/misc.c
+++ b/slirp/misc.c
@@ -6,9 +6,8 @@
  */
 
 #include "qemu/osdep.h"
-#include <slirp.h>
-#include <libslirp.h>
-
+#include "slirp.h"
+#include "libslirp.h"
 #include "monitor/monitor.h"
 #include "qemu/error-report.h"
 #include "qemu/main-loop.h"
diff --git a/slirp/misc.h b/slirp/misc.h
index 0d0c059e6b..5211bbd30a 100644
--- a/slirp/misc.h
+++ b/slirp/misc.h
@@ -5,8 +5,8 @@
  * terms and conditions of the copyright.
  */
 
-#ifndef _MISC_H_
-#define _MISC_H_
+#ifndef MISC_H
+#define MISC_H
 
 struct ex_list {
 	int ex_pty;			/* Do we want a pty? */
diff --git a/slirp/sbuf.c b/slirp/sbuf.c
index dd4cb8c139..10119d3ad5 100644
--- a/slirp/sbuf.c
+++ b/slirp/sbuf.c
@@ -6,8 +6,8 @@
  */
 
 #include "qemu/osdep.h"
-#include <slirp.h>
-#include <qemu/main-loop.h>
+#include "slirp.h"
+#include "qemu/main-loop.h"
 
 static void sbappendsb(struct sbuf *sb, struct mbuf *m);
 
diff --git a/slirp/sbuf.h b/slirp/sbuf.h
index 4f22e7c388..efcec39a6b 100644
--- a/slirp/sbuf.h
+++ b/slirp/sbuf.h
@@ -5,8 +5,8 @@
  * terms and conditions of the copyright.
  */
 
-#ifndef _SBUF_H_
-#define _SBUF_H_
+#ifndef SBUF_H
+#define SBUF_H
 
 #define sbflush(sb) sbdrop((sb),(sb)->sb_cc)
 #define sbspace(sb) ((sb)->sb_datalen - (sb)->sb_cc)
diff --git a/slirp/slirp.h b/slirp/slirp.h
index e3641f9eba..624a850906 100644
--- a/slirp/slirp.h
+++ b/slirp/slirp.h
@@ -1,5 +1,5 @@
-#ifndef __COMMON_H__
-#define __COMMON_H__
+#ifndef SLIRP_H
+#define SLIRP_H
 
 #include "qemu/host-utils.h"
 #include "slirp_config.h"
diff --git a/slirp/socket.c b/slirp/socket.c
index 02e89ce1f2..280050a21f 100644
--- a/slirp/socket.c
+++ b/slirp/socket.c
@@ -7,7 +7,7 @@
 
 #include "qemu/osdep.h"
 #include "qemu-common.h"
-#include <slirp.h>
+#include "slirp.h"
 #include "ip_icmp.h"
 #ifdef __sun__
 #include <sys/filio.h>
diff --git a/slirp/socket.h b/slirp/socket.h
index b602e69b95..8feed2aea4 100644
--- a/slirp/socket.h
+++ b/slirp/socket.h
@@ -5,8 +5,8 @@
  * terms and conditions of the copyright.
  */
 
-#ifndef _SLIRP_SOCKET_H_
-#define _SLIRP_SOCKET_H_
+#ifndef SLIRP_SOCKET_H
+#define SLIRP_SOCKET_H
 
 #define SO_EXPIRE 240000
 #define SO_EXPIREFAST 10000
@@ -158,4 +158,4 @@ void sotranslate_in(struct socket *, struct sockaddr_storage *);
 void sotranslate_accept(struct socket *);
 
 
-#endif /* _SOCKET_H_ */
+#endif /* SLIRP_SOCKET_H */
diff --git a/slirp/tcp.h b/slirp/tcp.h
index 61befcde57..174d3d960c 100644
--- a/slirp/tcp.h
+++ b/slirp/tcp.h
@@ -30,8 +30,8 @@
  * tcp.h,v 1.3 1994/08/21 05:27:34 paul Exp
  */
 
-#ifndef _TCP_H_
-#define _TCP_H_
+#ifndef TCP_H
+#define TCP_H
 
 typedef	uint32_t tcp_seq;
 
diff --git a/slirp/tcp_input.c b/slirp/tcp_input.c
index e2b5d4ebbb..c5063a918d 100644
--- a/slirp/tcp_input.c
+++ b/slirp/tcp_input.c
@@ -39,7 +39,7 @@
  */
 
 #include "qemu/osdep.h"
-#include <slirp.h>
+#include "slirp.h"
 #include "ip_icmp.h"
 
 #define	TCPREXMTTHRESH 3
diff --git a/slirp/tcp_output.c b/slirp/tcp_output.c
index 99b0a9b1cb..819db27348 100644
--- a/slirp/tcp_output.c
+++ b/slirp/tcp_output.c
@@ -39,7 +39,7 @@
  */
 
 #include "qemu/osdep.h"
-#include <slirp.h>
+#include "slirp.h"
 
 static const u_char  tcp_outflags[TCP_NSTATES] = {
 	TH_RST|TH_ACK, 0,      TH_SYN,        TH_SYN|TH_ACK,
diff --git a/slirp/tcp_subr.c b/slirp/tcp_subr.c
index 6b9fef2008..ed16e1807f 100644
--- a/slirp/tcp_subr.c
+++ b/slirp/tcp_subr.c
@@ -39,7 +39,7 @@
  */
 
 #include "qemu/osdep.h"
-#include <slirp.h>
+#include "slirp.h"
 
 /* patchable/settable parameters for tcp */
 /* Don't do rfc1323 performance enhancements */
diff --git a/slirp/tcp_timer.c b/slirp/tcp_timer.c
index 8f5dd772ad..f9060c7bf8 100644
--- a/slirp/tcp_timer.c
+++ b/slirp/tcp_timer.c
@@ -31,7 +31,7 @@
  */
 
 #include "qemu/osdep.h"
-#include <slirp.h>
+#include "slirp.h"
 
 static struct tcpcb *tcp_timers(register struct tcpcb *tp, int timer);
 
diff --git a/slirp/tcp_timer.h b/slirp/tcp_timer.h
index ff17914f41..b25b3911d7 100644
--- a/slirp/tcp_timer.h
+++ b/slirp/tcp_timer.h
@@ -30,8 +30,8 @@
  * tcp_timer.h,v 1.4 1994/08/21 05:27:38 paul Exp
  */
 
-#ifndef _TCP_TIMER_H_
-#define _TCP_TIMER_H_
+#ifndef TCP_TIMER_H
+#define TCP_TIMER_H
 
 /*
  * Definitions of the TCP timers.  These timers are counted
diff --git a/slirp/tcp_var.h b/slirp/tcp_var.h
index 004193fb6d..0f8f187c5c 100644
--- a/slirp/tcp_var.h
+++ b/slirp/tcp_var.h
@@ -30,8 +30,8 @@
  * tcp_var.h,v 1.3 1994/08/21 05:27:39 paul Exp
  */
 
-#ifndef _TCP_VAR_H_
-#define _TCP_VAR_H_
+#ifndef TCP_VAR_H
+#define TCP_VAR_H
 
 #include "tcpip.h"
 #include "tcp_timer.h"
diff --git a/slirp/tcpip.h b/slirp/tcpip.h
index 124b4a9f62..7bdb971c5d 100644
--- a/slirp/tcpip.h
+++ b/slirp/tcpip.h
@@ -30,8 +30,8 @@
  * tcpip.h,v 1.3 1994/08/21 05:27:40 paul Exp
  */
 
-#ifndef _TCPIP_H_
-#define _TCPIP_H_
+#ifndef TCPIP_H
+#define TCPIP_H
 
 /*
  * Tcp+ip header, after ip options removed.
diff --git a/slirp/tftp.c b/slirp/tftp.c
index 367340222d..c1859066cc 100644
--- a/slirp/tftp.c
+++ b/slirp/tftp.c
@@ -23,7 +23,7 @@
  */
 
 #include "qemu/osdep.h"
-#include <slirp.h>
+#include "slirp.h"
 #include "qemu-common.h"
 #include "qemu/cutils.h"
 
diff --git a/slirp/tftp.h b/slirp/tftp.h
index 1cb1adf591..2cd276dec6 100644
--- a/slirp/tftp.h
+++ b/slirp/tftp.h
@@ -1,6 +1,7 @@
 /* tftp defines */
+
 #ifndef SLIRP_TFTP_H
-#define SLIRP_TFTP_H 1
+#define SLIRP_TFTP_H
 
 #define TFTP_SESSIONS_MAX 20
 
diff --git a/slirp/udp.c b/slirp/udp.c
index 247024fd86..93d7224792 100644
--- a/slirp/udp.c
+++ b/slirp/udp.c
@@ -39,7 +39,7 @@
  */
 
 #include "qemu/osdep.h"
-#include <slirp.h>
+#include "slirp.h"
 #include "ip_icmp.h"
 
 static uint8_t udp_tos(struct socket *so);
diff --git a/slirp/udp.h b/slirp/udp.h
index 10cc7809b1..be657cf922 100644
--- a/slirp/udp.h
+++ b/slirp/udp.h
@@ -30,8 +30,8 @@
  * udp.h,v 1.3 1994/08/21 05:27:41 paul Exp
  */
 
-#ifndef _UDP_H_
-#define _UDP_H_
+#ifndef UDP_H
+#define UDP_H
 
 #define UDP_TTL 0x60
 #define UDP_UDPDATALEN 16192
diff --git a/softmmu_template.h b/softmmu_template.h
index 4d378ca630..284ab2c7b2 100644
--- a/softmmu_template.h
+++ b/softmmu_template.h
@@ -116,31 +116,6 @@
 # define helper_te_st_name  helper_le_st_name
 #endif
 
-/* macro to check the victim tlb */
-#define VICTIM_TLB_HIT(ty)                                                    \
-({                                                                            \
-    /* we are about to do a page table walk. our last hope is the             \
-     * victim tlb. try to refill from the victim tlb before walking the       \
-     * page table. */                                                         \
-    int vidx;                                                                 \
-    CPUIOTLBEntry tmpiotlb;                                                   \
-    CPUTLBEntry tmptlb;                                                       \
-    for (vidx = CPU_VTLB_SIZE-1; vidx >= 0; --vidx) {                         \
-        if (env->tlb_v_table[mmu_idx][vidx].ty == (addr & TARGET_PAGE_MASK)) {\
-            /* found entry in victim tlb, swap tlb and iotlb */               \
-            tmptlb = env->tlb_table[mmu_idx][index];                          \
-            env->tlb_table[mmu_idx][index] = env->tlb_v_table[mmu_idx][vidx]; \
-            env->tlb_v_table[mmu_idx][vidx] = tmptlb;                         \
-            tmpiotlb = env->iotlb[mmu_idx][index];                            \
-            env->iotlb[mmu_idx][index] = env->iotlb_v[mmu_idx][vidx];         \
-            env->iotlb_v[mmu_idx][vidx] = tmpiotlb;                           \
-            break;                                                            \
-        }                                                                     \
-    }                                                                         \
-    /* return true when there is a vtlb hit, i.e. vidx >=0 */                 \
-    vidx >= 0;                                                                \
-})
-
 #ifndef SOFTMMU_CODE_ACCESS
 static inline DATA_TYPE glue(io_read, SUFFIX)(CPUArchState *env,
                                               CPUIOTLBEntry *iotlbentry,
@@ -186,7 +161,7 @@ WORD_TYPE helper_le_ld_name(CPUArchState *env, target_ulong addr,
     /* If the TLB entry is for a different page, reload and try again.  */
     if ((addr & TARGET_PAGE_MASK)
          != (tlb_addr & (TARGET_PAGE_MASK | TLB_INVALID_MASK))) {
-        if (!VICTIM_TLB_HIT(ADDR_READ)) {
+        if (!VICTIM_TLB_HIT(ADDR_READ, addr)) {
             tlb_fill(ENV_GET_CPU(env), addr, READ_ACCESS_TYPE,
                      mmu_idx, retaddr);
         }
@@ -260,7 +235,7 @@ WORD_TYPE helper_be_ld_name(CPUArchState *env, target_ulong addr,
     /* If the TLB entry is for a different page, reload and try again.  */
     if ((addr & TARGET_PAGE_MASK)
          != (tlb_addr & (TARGET_PAGE_MASK | TLB_INVALID_MASK))) {
-        if (!VICTIM_TLB_HIT(ADDR_READ)) {
+        if (!VICTIM_TLB_HIT(ADDR_READ, addr)) {
             tlb_fill(ENV_GET_CPU(env), addr, READ_ACCESS_TYPE,
                      mmu_idx, retaddr);
         }
@@ -370,7 +345,7 @@ void helper_le_st_name(CPUArchState *env, target_ulong addr, DATA_TYPE val,
     /* If the TLB entry is for a different page, reload and try again.  */
     if ((addr & TARGET_PAGE_MASK)
         != (tlb_addr & (TARGET_PAGE_MASK | TLB_INVALID_MASK))) {
-        if (!VICTIM_TLB_HIT(addr_write)) {
+        if (!VICTIM_TLB_HIT(addr_write, addr)) {
             tlb_fill(ENV_GET_CPU(env), addr, MMU_DATA_STORE, mmu_idx, retaddr);
         }
         tlb_addr = env->tlb_table[mmu_idx][index].addr_write;
@@ -395,12 +370,25 @@ void helper_le_st_name(CPUArchState *env, target_ulong addr, DATA_TYPE val,
     if (DATA_SIZE > 1
         && unlikely((addr & ~TARGET_PAGE_MASK) + DATA_SIZE - 1
                      >= TARGET_PAGE_SIZE)) {
-        int i;
+        int i, index2;
+        target_ulong page2, tlb_addr2;
     do_unaligned_access:
-        /* XXX: not efficient, but simple */
-        /* Note: relies on the fact that tlb_fill() does not remove the
-         * previous page from the TLB cache.  */
-        for (i = DATA_SIZE - 1; i >= 0; i--) {
+        /* Ensure the second page is in the TLB.  Note that the first page
+           is already guaranteed to be filled, and that the second page
+           cannot evict the first.  */
+        page2 = (addr + DATA_SIZE) & TARGET_PAGE_MASK;
+        index2 = (page2 >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1);
+        tlb_addr2 = env->tlb_table[mmu_idx][index2].addr_write;
+        if (page2 != (tlb_addr2 & (TARGET_PAGE_MASK | TLB_INVALID_MASK))
+            && !VICTIM_TLB_HIT(addr_write, page2)) {
+            tlb_fill(ENV_GET_CPU(env), page2, MMU_DATA_STORE,
+                     mmu_idx, retaddr);
+        }
+
+        /* XXX: not efficient, but simple.  */
+        /* This loop must go in the forward direction to avoid issues
+           with self-modifying code in Windows 64-bit.  */
+        for (i = 0; i < DATA_SIZE; ++i) {
             /* Little-endian extract.  */
             uint8_t val8 = val >> (i * 8);
             /* Note the adjustment at the beginning of the function.
@@ -440,7 +428,7 @@ void helper_be_st_name(CPUArchState *env, target_ulong addr, DATA_TYPE val,
     /* If the TLB entry is for a different page, reload and try again.  */
     if ((addr & TARGET_PAGE_MASK)
         != (tlb_addr & (TARGET_PAGE_MASK | TLB_INVALID_MASK))) {
-        if (!VICTIM_TLB_HIT(addr_write)) {
+        if (!VICTIM_TLB_HIT(addr_write, addr)) {
             tlb_fill(ENV_GET_CPU(env), addr, MMU_DATA_STORE, mmu_idx, retaddr);
         }
         tlb_addr = env->tlb_table[mmu_idx][index].addr_write;
@@ -465,12 +453,25 @@ void helper_be_st_name(CPUArchState *env, target_ulong addr, DATA_TYPE val,
     if (DATA_SIZE > 1
         && unlikely((addr & ~TARGET_PAGE_MASK) + DATA_SIZE - 1
                      >= TARGET_PAGE_SIZE)) {
-        int i;
+        int i, index2;
+        target_ulong page2, tlb_addr2;
     do_unaligned_access:
+        /* Ensure the second page is in the TLB.  Note that the first page
+           is already guaranteed to be filled, and that the second page
+           cannot evict the first.  */
+        page2 = (addr + DATA_SIZE) & TARGET_PAGE_MASK;
+        index2 = (page2 >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1);
+        tlb_addr2 = env->tlb_table[mmu_idx][index2].addr_write;
+        if (page2 != (tlb_addr2 & (TARGET_PAGE_MASK | TLB_INVALID_MASK))
+            && !VICTIM_TLB_HIT(addr_write, page2)) {
+            tlb_fill(ENV_GET_CPU(env), page2, MMU_DATA_STORE,
+                     mmu_idx, retaddr);
+        }
+
         /* XXX: not efficient, but simple */
-        /* Note: relies on the fact that tlb_fill() does not remove the
-         * previous page from the TLB cache.  */
-        for (i = DATA_SIZE - 1; i >= 0; i--) {
+        /* This loop must go in the forward direction to avoid issues
+           with self-modifying code.  */
+        for (i = 0; i < DATA_SIZE; ++i) {
             /* Big-endian extract.  */
             uint8_t val8 = val >> (((DATA_SIZE - 1) * 8) - (i * 8));
             /* Note the adjustment at the beginning of the function.
@@ -502,7 +503,7 @@ void probe_write(CPUArchState *env, target_ulong addr, int mmu_idx,
     if ((addr & TARGET_PAGE_MASK)
         != (tlb_addr & (TARGET_PAGE_MASK | TLB_INVALID_MASK))) {
         /* TLB entry is for a different page */
-        if (!VICTIM_TLB_HIT(addr_write)) {
+        if (!VICTIM_TLB_HIT(addr_write, addr)) {
             tlb_fill(ENV_GET_CPU(env), addr, MMU_DATA_STORE, mmu_idx, retaddr);
         }
     }
diff --git a/target-alpha/cpu.h b/target-alpha/cpu.h
index ce8d2965b2..ac5e801fb4 100644
--- a/target-alpha/cpu.h
+++ b/target-alpha/cpu.h
@@ -17,8 +17,8 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 
-#if !defined (__CPU_ALPHA_H__)
-#define __CPU_ALPHA_H__
+#ifndef ALPHA_CPU_H
+#define ALPHA_CPU_H
 
 #include "qemu-common.h"
 #include "cpu-qom.h"
@@ -323,7 +323,8 @@ hwaddr alpha_cpu_get_phys_page_debug(CPUState *cpu, vaddr addr);
 int alpha_cpu_gdb_read_register(CPUState *cpu, uint8_t *buf, int reg);
 int alpha_cpu_gdb_write_register(CPUState *cpu, uint8_t *buf, int reg);
 void alpha_cpu_do_unaligned_access(CPUState *cpu, vaddr addr,
-                                   int is_write, int is_user, uintptr_t retaddr);
+                                   MMUAccessType access_type,
+                                   int mmu_idx, uintptr_t retaddr);
 
 #define cpu_list alpha_cpu_list
 #define cpu_signal_handler cpu_alpha_signal_handler
@@ -523,4 +524,4 @@ static inline void cpu_get_tb_cpu_state(CPUAlphaState *env, target_ulong *pc,
     *pflags = flags;
 }
 
-#endif /* !defined (__CPU_ALPHA_H__) */
+#endif /* ALPHA_CPU_H */
diff --git a/target-alpha/mem_helper.c b/target-alpha/mem_helper.c
index 7f4d15fef2..1b2be50be7 100644
--- a/target-alpha/mem_helper.c
+++ b/target-alpha/mem_helper.c
@@ -99,7 +99,8 @@ uint64_t helper_stq_c_phys(CPUAlphaState *env, uint64_t p, uint64_t v)
 }
 
 void alpha_cpu_do_unaligned_access(CPUState *cs, vaddr addr,
-                                   int is_write, int is_user, uintptr_t retaddr)
+                                   MMUAccessType access_type,
+                                   int mmu_idx, uintptr_t retaddr)
 {
     AlphaCPU *cpu = ALPHA_CPU(cs);
     CPUAlphaState *env = &cpu->env;
@@ -144,12 +145,12 @@ void alpha_cpu_unassigned_access(CPUState *cs, hwaddr addr,
    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(CPUState *cs, target_ulong addr, int is_write,
+void tlb_fill(CPUState *cs, target_ulong addr, MMUAccessType access_type,
               int mmu_idx, uintptr_t retaddr)
 {
     int ret;
 
-    ret = alpha_cpu_handle_mmu_fault(cs, addr, is_write, mmu_idx);
+    ret = alpha_cpu_handle_mmu_fault(cs, addr, access_type, mmu_idx);
     if (unlikely(ret != 0)) {
         if (retaddr) {
             cpu_restore_state(cs, retaddr);
diff --git a/target-arm/arm-powerctl.c b/target-arm/arm-powerctl.c
index d452230515..6519d52cae 100644
--- a/target-arm/arm-powerctl.c
+++ b/target-arm/arm-powerctl.c
@@ -9,8 +9,8 @@
  */
 
 #include "qemu/osdep.h"
-#include <cpu.h>
-#include <cpu-qom.h>
+#include "cpu.h"
+#include "cpu-qom.h"
 #include "internals.h"
 #include "arm-powerctl.h"
 #include "qemu/log.h"
diff --git a/target-arm/cpu.h b/target-arm/cpu.h
index e2fac46909..76d824d315 100644
--- a/target-arm/cpu.h
+++ b/target-arm/cpu.h
@@ -16,9 +16,9 @@
  * 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_ARM_H
-#define CPU_ARM_H
 
+#ifndef ARM_CPU_H
+#define ARM_CPU_H
 
 #include "kvm-consts.h"
 
diff --git a/target-arm/internals.h b/target-arm/internals.h
index 466be0bdad..cd574017c6 100644
--- a/target-arm/internals.h
+++ b/target-arm/internals.h
@@ -476,8 +476,9 @@ bool arm_tlb_fill(CPUState *cpu, vaddr address, int rw, int mmu_idx,
 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx);
 
 /* Raise a data fault alignment exception for the specified virtual address */
-void arm_cpu_do_unaligned_access(CPUState *cs, vaddr vaddr, int is_write,
-                                 int is_user, uintptr_t retaddr);
+void arm_cpu_do_unaligned_access(CPUState *cs, vaddr vaddr,
+                                 MMUAccessType access_type,
+                                 int mmu_idx, uintptr_t retaddr);
 
 /* Call the EL change hook if one has been registered */
 static inline void arm_call_el_change_hook(ARMCPU *cpu)
diff --git a/target-arm/op_helper.c b/target-arm/op_helper.c
index 73da759206..3e8588ee6a 100644
--- a/target-arm/op_helper.c
+++ b/target-arm/op_helper.c
@@ -79,7 +79,7 @@ uint32_t HELPER(neon_tbl)(CPUARMState *env, uint32_t ireg, uint32_t def,
 static inline uint32_t merge_syn_data_abort(uint32_t template_syn,
                                             unsigned int target_el,
                                             bool same_el,
-                                            bool s1ptw, int is_write,
+                                            bool s1ptw, bool is_write,
                                             int fsc)
 {
     uint32_t syn;
@@ -97,7 +97,7 @@ static inline uint32_t merge_syn_data_abort(uint32_t template_syn,
      */
     if (!(template_syn & ARM_EL_ISV) || target_el != 2 || s1ptw) {
         syn = syn_data_abort_no_iss(same_el,
-                                    0, 0, s1ptw, is_write == 1, fsc);
+                                    0, 0, s1ptw, is_write, fsc);
     } else {
         /* Fields: IL, ISV, SAS, SSE, SRT, SF and AR come from the template
          * syndrome created at translation time.
@@ -105,7 +105,7 @@ static inline uint32_t merge_syn_data_abort(uint32_t template_syn,
          */
         syn = syn_data_abort_with_iss(same_el,
                                       0, 0, 0, 0, 0,
-                                      0, 0, s1ptw, is_write == 1, fsc,
+                                      0, 0, s1ptw, is_write, fsc,
                                       false);
         /* Merge the runtime syndrome with the template syndrome.  */
         syn |= template_syn;
@@ -117,14 +117,14 @@ static inline uint32_t merge_syn_data_abort(uint32_t template_syn,
  * NULL, it means that the function was called in C code (i.e. not
  * from generated code or from helper.c)
  */
-void tlb_fill(CPUState *cs, target_ulong addr, int is_write, int mmu_idx,
-              uintptr_t retaddr)
+void tlb_fill(CPUState *cs, target_ulong addr, MMUAccessType access_type,
+              int mmu_idx, uintptr_t retaddr)
 {
     bool ret;
     uint32_t fsr = 0;
     ARMMMUFaultInfo fi = {};
 
-    ret = arm_tlb_fill(cs, addr, is_write, mmu_idx, &fsr, &fi);
+    ret = arm_tlb_fill(cs, addr, access_type, mmu_idx, &fsr, &fi);
     if (unlikely(ret)) {
         ARMCPU *cpu = ARM_CPU(cs);
         CPUARMState *env = &cpu->env;
@@ -149,13 +149,15 @@ void tlb_fill(CPUState *cs, target_ulong addr, int is_write, int mmu_idx,
         /* For insn and data aborts we assume there is no instruction syndrome
          * information; this is always true for exceptions reported to EL1.
          */
-        if (is_write == 2) {
+        if (access_type == MMU_INST_FETCH) {
             syn = syn_insn_abort(same_el, 0, fi.s1ptw, syn);
             exc = EXCP_PREFETCH_ABORT;
         } else {
             syn = merge_syn_data_abort(env->exception.syndrome, target_el,
-                                       same_el, fi.s1ptw, is_write, syn);
-            if (is_write == 1 && arm_feature(env, ARM_FEATURE_V6)) {
+                                       same_el, fi.s1ptw,
+                                       access_type == MMU_DATA_STORE, syn);
+            if (access_type == MMU_DATA_STORE
+                && arm_feature(env, ARM_FEATURE_V6)) {
                 fsr |= (1 << 11);
             }
             exc = EXCP_DATA_ABORT;
@@ -168,8 +170,9 @@ void tlb_fill(CPUState *cs, target_ulong addr, int is_write, int mmu_idx,
 }
 
 /* Raise a data fault alignment exception for the specified virtual address */
-void arm_cpu_do_unaligned_access(CPUState *cs, vaddr vaddr, int is_write,
-                                 int is_user, uintptr_t retaddr)
+void arm_cpu_do_unaligned_access(CPUState *cs, vaddr vaddr,
+                                 MMUAccessType access_type,
+                                 int mmu_idx, uintptr_t retaddr)
 {
     ARMCPU *cpu = ARM_CPU(cs);
     CPUARMState *env = &cpu->env;
@@ -196,12 +199,13 @@ void arm_cpu_do_unaligned_access(CPUState *cs, vaddr vaddr, int is_write,
         env->exception.fsr = 0x1;
     }
 
-    if (is_write == 1 && arm_feature(env, ARM_FEATURE_V6)) {
+    if (access_type == MMU_DATA_STORE && arm_feature(env, ARM_FEATURE_V6)) {
         env->exception.fsr |= (1 << 11);
     }
 
     syn = merge_syn_data_abort(env->exception.syndrome, target_el,
-                               same_el, 0, is_write, 0x21);
+                               same_el, 0, access_type == MMU_DATA_STORE,
+                               0x21);
     raise_exception(env, EXCP_DATA_ABORT, syn, target_el);
 }
 
diff --git a/target-arm/psci.c b/target-arm/psci.c
index 4db9b8ce24..14316eb0ae 100644
--- a/target-arm/psci.c
+++ b/target-arm/psci.c
@@ -16,10 +16,10 @@
  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
  */
 #include "qemu/osdep.h"
-#include <cpu.h>
-#include <exec/helper-proto.h>
-#include <kvm-consts.h>
-#include <sysemu/sysemu.h>
+#include "cpu.h"
+#include "exec/helper-proto.h"
+#include "kvm-consts.h"
+#include "sysemu/sysemu.h"
 #include "internals.h"
 #include "arm-powerctl.h"
 #include "exec/exec-all.h"
diff --git a/target-cris/cpu.h b/target-cris/cpu.h
index e6046d20ca..7d7fe6eb1c 100644
--- a/target-cris/cpu.h
+++ b/target-cris/cpu.h
@@ -17,8 +17,9 @@
  * 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_CRIS_H
-#define CPU_CRIS_H
+
+#ifndef CRIS_CPU_H
+#define CRIS_CPU_H
 
 #include "qemu-common.h"
 #include "cpu-qom.h"
diff --git a/target-cris/crisv32-decode.h b/target-cris/crisv32-decode.h
index cdba377817..cdc2f8cbe6 100644
--- a/target-cris/crisv32-decode.h
+++ b/target-cris/crisv32-decode.h
@@ -17,8 +17,9 @@
  * 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 CRISV32_DECODE_H
-#define CRISV32_DECODE_H 1
+#define CRISV32_DECODE_H
 
 /* Convenient binary macros.  */
 #define HEX__(n) 0x##n##LU
diff --git a/target-cris/op_helper.c b/target-cris/op_helper.c
index 675ab86d44..504303913c 100644
--- a/target-cris/op_helper.c
+++ b/target-cris/op_helper.c
@@ -41,8 +41,8 @@
 /* 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) */
-void tlb_fill(CPUState *cs, target_ulong addr, int is_write, int mmu_idx,
-              uintptr_t retaddr)
+void tlb_fill(CPUState *cs, target_ulong addr, MMUAccessType access_type,
+              int mmu_idx, uintptr_t retaddr)
 {
     CRISCPU *cpu = CRIS_CPU(cs);
     CPUCRISState *env = &cpu->env;
@@ -50,7 +50,7 @@ void tlb_fill(CPUState *cs, target_ulong addr, int is_write, int mmu_idx,
 
     D_LOG("%s pc=%x tpc=%x ra=%p\n", __func__,
           env->pc, env->pregs[PR_EDA], (void *)retaddr);
-    ret = cris_cpu_handle_mmu_fault(cs, addr, is_write, mmu_idx);
+    ret = cris_cpu_handle_mmu_fault(cs, addr, access_type, mmu_idx);
     if (unlikely(ret)) {
         if (retaddr) {
             /* now we have a real cpu fault */
diff --git a/target-i386/cpu.h b/target-i386/cpu.h
index 5c7a2791f3..776efe630e 100644
--- a/target-i386/cpu.h
+++ b/target-i386/cpu.h
@@ -16,8 +16,9 @@
  * 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_I386_H
-#define CPU_I386_H
+
+#ifndef I386_CPU_H
+#define I386_CPU_H
 
 #include "qemu-common.h"
 #include "cpu-qom.h"
@@ -1607,4 +1608,4 @@ void x86_cpu_dump_local_apic_state(CPUState *cs, FILE *f,
 /* cpu.c */
 bool cpu_is_bsp(X86CPU *cpu);
 
-#endif /* CPU_I386_H */
+#endif /* I386_CPU_H */
diff --git a/target-i386/hyperv.h b/target-i386/hyperv.h
index b26201f8b9..0c3b562018 100644
--- a/target-i386/hyperv.h
+++ b/target-i386/hyperv.h
@@ -11,8 +11,8 @@
  *
  */
 
-#ifndef HYPERV_I386_H
-#define HYPERV_I386_H
+#ifndef TARGET_I386_HYPERV_H
+#define TARGET_I386_HYPERV_H
 
 #include "cpu.h"
 #include "sysemu/kvm.h"
diff --git a/target-i386/mem_helper.c b/target-i386/mem_helper.c
index c2f4769d4b..5bc0594dfa 100644
--- a/target-i386/mem_helper.c
+++ b/target-i386/mem_helper.c
@@ -140,12 +140,12 @@ void helper_boundl(CPUX86State *env, target_ulong a0, int v)
  * from generated code or from helper.c)
  */
 /* XXX: fix it to restore all registers */
-void tlb_fill(CPUState *cs, target_ulong addr, int is_write, int mmu_idx,
-              uintptr_t retaddr)
+void tlb_fill(CPUState *cs, target_ulong addr, MMUAccessType access_type,
+              int mmu_idx, uintptr_t retaddr)
 {
     int ret;
 
-    ret = x86_cpu_handle_mmu_fault(cs, addr, is_write, mmu_idx);
+    ret = x86_cpu_handle_mmu_fault(cs, addr, access_type, mmu_idx);
     if (ret) {
         X86CPU *cpu = X86_CPU(cs);
         CPUX86State *env = &cpu->env;
diff --git a/target-i386/svm.h b/target-i386/svm.h
index 04193ed60f..922c8fd39c 100644
--- a/target-i386/svm.h
+++ b/target-i386/svm.h
@@ -1,5 +1,5 @@
-#ifndef __SVM_H
-#define __SVM_H
+#ifndef SVM_H
+#define SVM_H
 
 #define TLB_CONTROL_DO_NOTHING 0
 #define TLB_CONTROL_FLUSH_ALL_ASID 1
diff --git a/target-lm32/cpu.h b/target-lm32/cpu.h
index 4efe98d828..d8a3515244 100644
--- a/target-lm32/cpu.h
+++ b/target-lm32/cpu.h
@@ -17,8 +17,8 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 
-#ifndef CPU_LM32_H
-#define CPU_LM32_H
+#ifndef LM32_CPU_H
+#define LM32_CPU_H
 
 #define TARGET_LONG_BITS 32
 
diff --git a/target-lm32/op_helper.c b/target-lm32/op_helper.c
index 7a550d1c0c..2177c8ad12 100644
--- a/target-lm32/op_helper.c
+++ b/target-lm32/op_helper.c
@@ -144,12 +144,12 @@ uint32_t HELPER(rcsr_jrx)(CPULM32State *env)
  * NULL, it means that the function was called in C code (i.e. not
  * from generated code or from helper.c)
  */
-void tlb_fill(CPUState *cs, target_ulong addr, int is_write, int mmu_idx,
-              uintptr_t retaddr)
+void tlb_fill(CPUState *cs, target_ulong addr, MMUAccessType access_type,
+              int mmu_idx, uintptr_t retaddr)
 {
     int ret;
 
-    ret = lm32_cpu_handle_mmu_fault(cs, addr, is_write, mmu_idx);
+    ret = lm32_cpu_handle_mmu_fault(cs, addr, access_type, mmu_idx);
     if (unlikely(ret)) {
         if (retaddr) {
             /* now we have a real cpu fault */
diff --git a/target-m68k/cpu.h b/target-m68k/cpu.h
index 9087769997..b2faa6b605 100644
--- a/target-m68k/cpu.h
+++ b/target-m68k/cpu.h
@@ -17,8 +17,9 @@
  * 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_M68K_H
-#define CPU_M68K_H
+
+#ifndef M68K_CPU_H
+#define M68K_CPU_H
 
 #define TARGET_LONG_BITS 32
 
diff --git a/target-m68k/op_helper.c b/target-m68k/op_helper.c
index ff32e35461..e41ae46498 100644
--- a/target-m68k/op_helper.c
+++ b/target-m68k/op_helper.c
@@ -39,12 +39,12 @@ static inline void do_interrupt_m68k_hardirq(CPUM68KState *env)
 /* 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) */
-void tlb_fill(CPUState *cs, target_ulong addr, int is_write, int mmu_idx,
-              uintptr_t retaddr)
+void tlb_fill(CPUState *cs, target_ulong addr, MMUAccessType access_type,
+              int mmu_idx, uintptr_t retaddr)
 {
     int ret;
 
-    ret = m68k_cpu_handle_mmu_fault(cs, addr, is_write, mmu_idx);
+    ret = m68k_cpu_handle_mmu_fault(cs, addr, access_type, mmu_idx);
     if (unlikely(ret)) {
         if (retaddr) {
             /* now we have a real cpu fault */
diff --git a/target-microblaze/cpu.h b/target-microblaze/cpu.h
index 16815dfc6a..beb75ffd26 100644
--- a/target-microblaze/cpu.h
+++ b/target-microblaze/cpu.h
@@ -16,8 +16,9 @@
  * 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_MICROBLAZE_H
-#define CPU_MICROBLAZE_H
+
+#ifndef MICROBLAZE_CPU_H
+#define MICROBLAZE_CPU_H
 
 #include "qemu-common.h"
 #include "cpu-qom.h"
diff --git a/target-microblaze/op_helper.c b/target-microblaze/op_helper.c
index 74a043c2ac..4a856e6204 100644
--- a/target-microblaze/op_helper.c
+++ b/target-microblaze/op_helper.c
@@ -33,12 +33,12 @@
  * NULL, it means that the function was called in C code (i.e. not
  * from generated code or from helper.c)
  */
-void tlb_fill(CPUState *cs, target_ulong addr, int is_write, int mmu_idx,
-              uintptr_t retaddr)
+void tlb_fill(CPUState *cs, target_ulong addr, MMUAccessType access_type,
+              int mmu_idx, uintptr_t retaddr)
 {
     int ret;
 
-    ret = mb_cpu_handle_mmu_fault(cs, addr, is_write, mmu_idx);
+    ret = mb_cpu_handle_mmu_fault(cs, addr, access_type, mmu_idx);
     if (unlikely(ret)) {
         if (retaddr) {
             /* now we have a real cpu fault */
diff --git a/target-mips/cpu.h b/target-mips/cpu.h
index 1037f9b7eb..5182dc74ff 100644
--- a/target-mips/cpu.h
+++ b/target-mips/cpu.h
@@ -1,5 +1,5 @@
-#if !defined (__MIPS_CPU_H__)
-#define __MIPS_CPU_H__
+#ifndef MIPS_CPU_H
+#define MIPS_CPU_H
 
 //#define DEBUG_OP
 
@@ -19,7 +19,7 @@ typedef struct r4k_tlb_t r4k_tlb_t;
 struct r4k_tlb_t {
     target_ulong VPN;
     uint32_t PageMask;
-    uint8_t ASID;
+    uint16_t ASID;
     unsigned int G:1;
     unsigned int C0:3;
     unsigned int C1:3;
@@ -343,6 +343,7 @@ struct CPUMIPSState {
     int32_t CP0_Count;
     target_ulong CP0_EntryHi;
 #define CP0EnHi_EHINV 10
+    target_ulong CP0_EntryHi_ASID_mask;
     int32_t CP0_Compare;
     int32_t CP0_Status;
 #define CP0St_CU3   31
@@ -467,6 +468,7 @@ struct CPUMIPSState {
     int32_t CP0_Config4_rw_bitmask;
 #define CP0C4_M    31
 #define CP0C4_IE   29
+#define CP0C4_AE   28
 #define CP0C4_KScrExist 16
 #define CP0C4_MMUExtDef 14
 #define CP0C4_FTLBPageSize 8
@@ -503,6 +505,7 @@ struct CPUMIPSState {
     int CP0_LLAddr_shift;
     target_ulong CP0_WatchLo[8];
     int32_t CP0_WatchHi[8];
+#define CP0WH_ASID 16
     target_ulong CP0_XContext;
     int32_t CP0_Framemask;
     int32_t CP0_Debug;
@@ -616,6 +619,7 @@ struct CPUMIPSState {
     void *irq[8];
     QEMUTimer *timer; /* Internal timer */
     MemoryRegion *itc_tag; /* ITC Configuration Tags */
+    target_ulong exception_base; /* ExceptionBase input to the core */
 };
 
 /**
@@ -653,7 +657,8 @@ hwaddr mips_cpu_get_phys_page_debug(CPUState *cpu, vaddr addr);
 int mips_cpu_gdb_read_register(CPUState *cpu, uint8_t *buf, int reg);
 int mips_cpu_gdb_write_register(CPUState *cpu, uint8_t *buf, int reg);
 void mips_cpu_do_unaligned_access(CPUState *cpu, vaddr addr,
-                                  int is_write, int is_user, uintptr_t retaddr);
+                                  MMUAccessType access_type,
+                                  int mmu_idx, uintptr_t retaddr);
 
 #if !defined(CONFIG_USER_ONLY)
 int no_mmu_map_address (CPUMIPSState *env, hwaddr *physical, int *prot,
@@ -807,6 +812,7 @@ int cpu_mips_signal_handler(int host_signum, void *pinfo, void *puc);
 
 #define cpu_init(cpu_model) CPU(cpu_mips_init(cpu_model))
 bool cpu_supports_cps_smp(const char *cpu_model);
+void cpu_set_exception_base(int vp_index, target_ulong address);
 
 /* TODO QOM'ify CPU reset and remove */
 void cpu_state_reset(CPUMIPSState *s);
@@ -1060,4 +1066,4 @@ static inline void QEMU_NORETURN do_raise_exception(CPUMIPSState *env,
     do_raise_exception_err(env, exception, 0, pc);
 }
 
-#endif /* !defined (__MIPS_CPU_H__) */
+#endif /* MIPS_CPU_H */
diff --git a/target-mips/helper.c b/target-mips/helper.c
index 65fbef0050..9fbca26d41 100644
--- a/target-mips/helper.c
+++ b/target-mips/helper.c
@@ -67,7 +67,7 @@ int fixed_mmu_map_address (CPUMIPSState *env, hwaddr *physical, int *prot,
 int r4k_map_address (CPUMIPSState *env, hwaddr *physical, int *prot,
                      target_ulong address, int rw, int access_type)
 {
-    uint8_t ASID = env->CP0_EntryHi & 0xFF;
+    uint16_t ASID = env->CP0_EntryHi & env->CP0_EntryHi_ASID_mask;
     int i;
 
     for (i = 0; i < env->tlb->tlb_in_use; i++) {
@@ -249,7 +249,7 @@ void sync_c0_status(CPUMIPSState *env, CPUMIPSState *cpu, int tc)
     cu = (v >> CP0St_CU0) & 0xf;
     mx = (v >> CP0St_MX) & 0x1;
     ksu = (v >> CP0St_KSU) & 0x3;
-    asid = env->CP0_EntryHi & 0xff;
+    asid = env->CP0_EntryHi & env->CP0_EntryHi_ASID_mask;
 
     tcstatus = cu << CP0TCSt_TCU0;
     tcstatus |= mx << CP0TCSt_TMX;
@@ -395,8 +395,8 @@ static void raise_mmu_exception(CPUMIPSState *env, target_ulong address,
     env->CP0_BadVAddr = address;
     env->CP0_Context = (env->CP0_Context & ~0x007fffff) |
                        ((address >> 9) & 0x007ffff0);
-    env->CP0_EntryHi =
-        (env->CP0_EntryHi & 0xFF) | (address & (TARGET_PAGE_MASK << 1));
+    env->CP0_EntryHi = (env->CP0_EntryHi & env->CP0_EntryHi_ASID_mask) |
+                       (address & (TARGET_PAGE_MASK << 1));
 #if defined(TARGET_MIPS64)
     env->CP0_EntryHi &= env->SEGMask;
     env->CP0_XContext =
@@ -640,7 +640,7 @@ void mips_cpu_do_interrupt(CPUState *cs)
         /* EJTAG probe trap enable is not implemented... */
         if (!(env->CP0_Status & (1 << CP0St_EXL)))
             env->CP0_Cause &= ~(1U << CP0Ca_BD);
-        env->active_tc.PC = (int32_t)0xBFC00480;
+        env->active_tc.PC = env->exception_base + 0x480;
         set_hflags_for_handler(env);
         break;
     case EXCP_RESET:
@@ -667,7 +667,7 @@ void mips_cpu_do_interrupt(CPUState *cs)
         env->hflags &= ~(MIPS_HFLAG_KSU);
         if (!(env->CP0_Status & (1 << CP0St_EXL)))
             env->CP0_Cause &= ~(1U << CP0Ca_BD);
-        env->active_tc.PC = (int32_t)0xBFC00000;
+        env->active_tc.PC = env->exception_base;
         set_hflags_for_handler(env);
         break;
     case EXCP_EXT_INTERRUPT:
@@ -849,7 +849,7 @@ void mips_cpu_do_interrupt(CPUState *cs)
         }
         env->hflags &= ~MIPS_HFLAG_BMASK;
         if (env->CP0_Status & (1 << CP0St_BEV)) {
-            env->active_tc.PC = (int32_t)0xBFC00200;
+            env->active_tc.PC = env->exception_base + 0x200;
         } else {
             env->active_tc.PC = (int32_t)(env->CP0_EBase & ~0x3ff);
         }
@@ -898,7 +898,7 @@ void r4k_invalidate_tlb (CPUMIPSState *env, int idx, int use_extra)
     r4k_tlb_t *tlb;
     target_ulong addr;
     target_ulong end;
-    uint8_t ASID = env->CP0_EntryHi & 0xFF;
+    uint16_t ASID = env->CP0_EntryHi & env->CP0_EntryHi_ASID_mask;
     target_ulong mask;
 
     tlb = &env->tlb->mmu.r4k.tlb[idx];
diff --git a/target-mips/kvm_mips.h b/target-mips/kvm_mips.h
index 54f59656ef..ae957f37f0 100644
--- a/target-mips/kvm_mips.h
+++ b/target-mips/kvm_mips.h
@@ -9,8 +9,8 @@
  * Authors: Sanjay Lal <sanjayl@kymasys.com>
 */
 
-#ifndef __KVM_MIPS_H__
-#define __KVM_MIPS_H__
+#ifndef KVM_MIPS_H
+#define KVM_MIPS_H
 
 /**
  * kvm_mips_reset_vcpu:
@@ -23,4 +23,4 @@ void kvm_mips_reset_vcpu(MIPSCPU *cpu);
 int kvm_mips_set_interrupt(MIPSCPU *cpu, int irq, int level);
 int kvm_mips_set_ipi_interrupt(MIPSCPU *cpu, int irq, int level);
 
-#endif /* __KVM_MIPS_H__ */
+#endif /* KVM_MIPS_H */
diff --git a/target-mips/machine.c b/target-mips/machine.c
index 7314cfe8c7..a27f2f156d 100644
--- a/target-mips/machine.c
+++ b/target-mips/machine.c
@@ -132,7 +132,7 @@ static int get_tlb(QEMUFile *f, void *pv, size_t size)
 
     qemu_get_betls(f, &v->VPN);
     qemu_get_be32s(f, &v->PageMask);
-    qemu_get_8s(f, &v->ASID);
+    qemu_get_be16s(f, &v->ASID);
     qemu_get_be16s(f, &flags);
     v->G = (flags >> 10) & 1;
     v->C0 = (flags >> 7) & 3;
@@ -156,7 +156,7 @@ static void put_tlb(QEMUFile *f, void *pv, size_t size)
 {
     r4k_tlb_t *v = pv;
 
-    uint8_t asid = v->ASID;
+    uint16_t asid = v->ASID;
     uint16_t flags = ((v->EHINV << 15) |
                       (v->RI1 << 14) |
                       (v->RI0 << 13) |
@@ -172,7 +172,7 @@ static void put_tlb(QEMUFile *f, void *pv, size_t size)
 
     qemu_put_betls(f, &v->VPN);
     qemu_put_be32s(f, &v->PageMask);
-    qemu_put_8s(f, &asid);
+    qemu_put_be16s(f, &asid);
     qemu_put_be16s(f, &flags);
     qemu_put_be64s(f, &v->PFN[0]);
     qemu_put_be64s(f, &v->PFN[1]);
@@ -192,8 +192,8 @@ const VMStateInfo vmstate_info_tlb = {
 
 const VMStateDescription vmstate_tlb = {
     .name = "cpu/tlb",
-    .version_id = 1,
-    .minimum_version_id = 1,
+    .version_id = 2,
+    .minimum_version_id = 2,
     .fields = (VMStateField[]) {
         VMSTATE_UINT32(nb_tlb, CPUMIPSTLBContext),
         VMSTATE_UINT32(tlb_in_use, CPUMIPSTLBContext),
diff --git a/target-mips/mips-defs.h b/target-mips/mips-defs.h
index 53b185ebd3..047554ee45 100644
--- a/target-mips/mips-defs.h
+++ b/target-mips/mips-defs.h
@@ -1,5 +1,5 @@
-#if !defined (__QEMU_MIPS_DEFS_H__)
-#define __QEMU_MIPS_DEFS_H__
+#ifndef QEMU_MIPS_DEFS_H
+#define QEMU_MIPS_DEFS_H
 
 /* If we want to use host float regs... */
 //#define USE_HOST_FLOAT_REGS
@@ -88,4 +88,4 @@
    Note that we still maintain Count/Compare to match the host clock. */
 //#define MIPS_STRICT_STANDARD 1
 
-#endif /* !defined (__QEMU_MIPS_DEFS_H__) */
+#endif /* QEMU_MIPS_DEFS_H */
diff --git a/target-mips/op_helper.c b/target-mips/op_helper.c
index 69daade24e..ea2f2abe19 100644
--- a/target-mips/op_helper.c
+++ b/target-mips/op_helper.c
@@ -679,7 +679,7 @@ static void sync_c0_tcstatus(CPUMIPSState *cpu, int tc,
 
     tcu = (v >> CP0TCSt_TCU0) & 0xf;
     tmx = (v >> CP0TCSt_TMX) & 0x1;
-    tasid = v & 0xff;
+    tasid = v & cpu->CP0_EntryHi_ASID_mask;
     tksu = (v >> CP0TCSt_TKSU) & 0x3;
 
     status = tcu << CP0St_CU0;
@@ -690,7 +690,7 @@ static void sync_c0_tcstatus(CPUMIPSState *cpu, int tc,
     cpu->CP0_Status |= status;
 
     /* Sync the TASID with EntryHi.  */
-    cpu->CP0_EntryHi &= ~0xff;
+    cpu->CP0_EntryHi &= ~cpu->CP0_EntryHi_ASID_mask;
     cpu->CP0_EntryHi |= tasid;
 
     compute_hflags(cpu);
@@ -702,7 +702,7 @@ static void sync_c0_entryhi(CPUMIPSState *cpu, int tc)
     int32_t *tcst;
     uint32_t asid, v = cpu->CP0_EntryHi;
 
-    asid = v & 0xff;
+    asid = v & cpu->CP0_EntryHi_ASID_mask;
 
     if (tc == cpu->current_tc) {
         tcst = &cpu->active_tc.CP0_TCStatus;
@@ -710,7 +710,7 @@ static void sync_c0_entryhi(CPUMIPSState *cpu, int tc)
         tcst = &cpu->tcs[tc].CP0_TCStatus;
     }
 
-    *tcst &= ~0xff;
+    *tcst &= ~cpu->CP0_EntryHi_ASID_mask;
     *tcst |= asid;
 }
 
@@ -1403,7 +1403,7 @@ void helper_mtc0_count(CPUMIPSState *env, target_ulong arg1)
 void helper_mtc0_entryhi(CPUMIPSState *env, target_ulong arg1)
 {
     target_ulong old, val, mask;
-    mask = (TARGET_PAGE_MASK << 1) | 0xFF;
+    mask = (TARGET_PAGE_MASK << 1) | env->CP0_EntryHi_ASID_mask;
     if (((env->CP0_Config4 >> CP0C4_IE) & 0x3) >= 2) {
         mask |= 1 << CP0EnHi_EHINV;
     }
@@ -1429,8 +1429,10 @@ void helper_mtc0_entryhi(CPUMIPSState *env, target_ulong arg1)
         sync_c0_entryhi(env, env->current_tc);
     }
     /* If the ASID changes, flush qemu's TLB.  */
-    if ((old & 0xFF) != (val & 0xFF))
+    if ((old & env->CP0_EntryHi_ASID_mask) !=
+        (val & env->CP0_EntryHi_ASID_mask)) {
         cpu_mips_tlb_flush(env, 1);
+    }
 }
 
 void helper_mttc0_entryhi(CPUMIPSState *env, target_ulong arg1)
@@ -1631,7 +1633,8 @@ void helper_mtc0_watchlo(CPUMIPSState *env, target_ulong arg1, uint32_t sel)
 
 void helper_mtc0_watchhi(CPUMIPSState *env, target_ulong arg1, uint32_t sel)
 {
-    env->CP0_WatchHi[sel] = (arg1 & 0x40FF0FF8);
+    int mask = 0x40000FF8 | (env->CP0_EntryHi_ASID_mask << CP0WH_ASID);
+    env->CP0_WatchHi[sel] = arg1 & mask;
     env->CP0_WatchHi[sel] &= ~(env->CP0_WatchHi[sel] & arg1 & 0x7);
 }
 
@@ -1989,7 +1992,7 @@ static void r4k_fill_tlb(CPUMIPSState *env, int idx)
 #if defined(TARGET_MIPS64)
     tlb->VPN &= env->SEGMask;
 #endif
-    tlb->ASID = env->CP0_EntryHi & 0xFF;
+    tlb->ASID = env->CP0_EntryHi & env->CP0_EntryHi_ASID_mask;
     tlb->PageMask = env->CP0_PageMask;
     tlb->G = env->CP0_EntryLo0 & env->CP0_EntryLo1 & 1;
     tlb->V0 = (env->CP0_EntryLo0 & 2) != 0;
@@ -2010,7 +2013,7 @@ void r4k_helper_tlbinv(CPUMIPSState *env)
 {
     int idx;
     r4k_tlb_t *tlb;
-    uint8_t ASID = env->CP0_EntryHi & 0xFF;
+    uint16_t ASID = env->CP0_EntryHi & env->CP0_EntryHi_ASID_mask;
 
     for (idx = 0; idx < env->tlb->nb_tlb; idx++) {
         tlb = &env->tlb->mmu.r4k.tlb[idx];
@@ -2036,7 +2039,7 @@ void r4k_helper_tlbwi(CPUMIPSState *env)
     r4k_tlb_t *tlb;
     int idx;
     target_ulong VPN;
-    uint8_t ASID;
+    uint16_t ASID;
     bool G, V0, D0, V1, D1;
 
     idx = (env->CP0_Index & ~0x80000000) % env->tlb->nb_tlb;
@@ -2045,7 +2048,7 @@ void r4k_helper_tlbwi(CPUMIPSState *env)
 #if defined(TARGET_MIPS64)
     VPN &= env->SEGMask;
 #endif
-    ASID = env->CP0_EntryHi & 0xff;
+    ASID = env->CP0_EntryHi & env->CP0_EntryHi_ASID_mask;
     G = env->CP0_EntryLo0 & env->CP0_EntryLo1 & 1;
     V0 = (env->CP0_EntryLo0 & 2) != 0;
     D0 = (env->CP0_EntryLo0 & 4) != 0;
@@ -2078,10 +2081,10 @@ void r4k_helper_tlbp(CPUMIPSState *env)
     target_ulong mask;
     target_ulong tag;
     target_ulong VPN;
-    uint8_t ASID;
+    uint16_t ASID;
     int i;
 
-    ASID = env->CP0_EntryHi & 0xFF;
+    ASID = env->CP0_EntryHi & env->CP0_EntryHi_ASID_mask;
     for (i = 0; i < env->tlb->nb_tlb; i++) {
         tlb = &env->tlb->mmu.r4k.tlb[i];
         /* 1k pages are not supported. */
@@ -2133,10 +2136,10 @@ static inline uint64_t get_entrylo_pfn_from_tlb(uint64_t tlb_pfn)
 void r4k_helper_tlbr(CPUMIPSState *env)
 {
     r4k_tlb_t *tlb;
-    uint8_t ASID;
+    uint16_t ASID;
     int idx;
 
-    ASID = env->CP0_EntryHi & 0xFF;
+    ASID = env->CP0_EntryHi & env->CP0_EntryHi_ASID_mask;
     idx = (env->CP0_Index & ~0x80000000) % env->tlb->nb_tlb;
     tlb = &env->tlb->mmu.r4k.tlb[idx];
 
@@ -2381,8 +2384,8 @@ void helper_wait(CPUMIPSState *env)
 #if !defined(CONFIG_USER_ONLY)
 
 void mips_cpu_do_unaligned_access(CPUState *cs, vaddr addr,
-                                  int access_type, int is_user,
-                                  uintptr_t retaddr)
+                                  MMUAccessType access_type,
+                                  int mmu_idx, uintptr_t retaddr)
 {
     MIPSCPU *cpu = MIPS_CPU(cs);
     CPUMIPSState *env = &cpu->env;
@@ -2403,12 +2406,12 @@ void mips_cpu_do_unaligned_access(CPUState *cs, vaddr addr,
     do_raise_exception_err(env, excp, error_code, retaddr);
 }
 
-void tlb_fill(CPUState *cs, target_ulong addr, int is_write, int mmu_idx,
-              uintptr_t retaddr)
+void tlb_fill(CPUState *cs, target_ulong addr, MMUAccessType access_type,
+              int mmu_idx, uintptr_t retaddr)
 {
     int ret;
 
-    ret = mips_cpu_handle_mmu_fault(cs, addr, is_write, mmu_idx);
+    ret = mips_cpu_handle_mmu_fault(cs, addr, access_type, mmu_idx);
     if (ret) {
         MIPSCPU *cpu = MIPS_CPU(cs);
         CPUMIPSState *env = &cpu->env;
diff --git a/target-mips/translate.c b/target-mips/translate.c
index cc321e9cce..bab52cb254 100644
--- a/target-mips/translate.c
+++ b/target-mips/translate.c
@@ -20169,6 +20169,7 @@ MIPSCPU *cpu_mips_init(const char *cpu_model)
     cpu = MIPS_CPU(object_new(TYPE_MIPS_CPU));
     env = &cpu->env;
     env->cpu_model = def;
+    env->exception_base = (int32_t)0xBFC00000;
 
 #ifndef CONFIG_USER_ONLY
     mmu_init(env, def);
@@ -20191,6 +20192,12 @@ bool cpu_supports_cps_smp(const char *cpu_model)
     return (def->CP0_Config3 & (1 << CP0C3_CMGCR)) != 0;
 }
 
+void cpu_set_exception_base(int vp_index, target_ulong address)
+{
+    MIPSCPU *vp = MIPS_CPU(qemu_get_cpu(vp_index));
+    vp->env.exception_base = address;
+}
+
 void cpu_state_reset(CPUMIPSState *env)
 {
     MIPSCPU *cpu = mips_env_get_cpu(env);
@@ -20281,7 +20288,7 @@ void cpu_state_reset(CPUMIPSState *env)
     } else {
         env->CP0_ErrorEPC = env->active_tc.PC;
     }
-    env->active_tc.PC = (int32_t)0xBFC00000;
+    env->active_tc.PC = env->exception_base;
     env->CP0_Random = env->tlb->nb_tlb - 1;
     env->tlb->tlb_in_use = env->tlb->nb_tlb;
     env->CP0_Wired = 0;
@@ -20295,6 +20302,8 @@ void cpu_state_reset(CPUMIPSState *env)
     if (env->CP0_Config3 & (1 << CP0C3_CMGCR)) {
         env->CP0_CMGCRBase = 0x1fbf8000 >> 4;
     }
+    env->CP0_EntryHi_ASID_mask = (env->CP0_Config4 & (1 << CP0C4_AE)) ?
+                                 0x3ff : 0xff;
     env->CP0_Status = (1 << CP0St_BEV) | (1 << CP0St_ERL);
     /* vectored interrupts not implemented, timer on int 7,
        no performance counters. */
diff --git a/target-mips/translate_init.c b/target-mips/translate_init.c
index b10284cc5d..39ed5c4c1b 100644
--- a/target-mips/translate_init.c
+++ b/target-mips/translate_init.c
@@ -671,26 +671,23 @@ static const mips_def_t mips_defs[] =
         .mmu_type = MMU_TYPE_R4000,
     },
     {
-        /* A generic CPU supporting MIPS64 Release 6 ISA.
-           FIXME: Support IEEE 754-2008 FP.
-                  Eventually this should be replaced by a real CPU model. */
-        .name = "MIPS64R6-generic",
-        .CP0_PRid = 0x00010000,
+        .name = "I6400",
+        .CP0_PRid = 0x1A900,
         .CP0_Config0 = MIPS_CONFIG0 | (0x2 << CP0C0_AR) | (0x2 << CP0C0_AT) |
                        (MMU_TYPE_R4000 << CP0C0_MT),
-        .CP0_Config1 = MIPS_CONFIG1 | (1 << CP0C1_FP) | (63 << CP0C1_MMU) |
-                       (2 << CP0C1_IS) | (4 << CP0C1_IL) | (3 << CP0C1_IA) |
-                       (2 << CP0C1_DS) | (4 << CP0C1_DL) | (3 << CP0C1_DA) |
+        .CP0_Config1 = MIPS_CONFIG1 | (1 << CP0C1_FP) | (15 << CP0C1_MMU) |
+                       (2 << CP0C1_IS) | (5 << CP0C1_IL) | (3 << CP0C1_IA) |
+                       (2 << CP0C1_DS) | (5 << CP0C1_DL) | (3 << CP0C1_DA) |
                        (0 << CP0C1_PC) | (1 << CP0C1_WR) | (1 << CP0C1_EP),
         .CP0_Config2 = MIPS_CONFIG2,
         .CP0_Config3 = MIPS_CONFIG3 | (1U << CP0C3_M) |
                        (1 << CP0C3_CMGCR) | (1 << CP0C3_MSAP) |
                        (1 << CP0C3_BP) | (1 << CP0C3_BI) | (1 << CP0C3_ULRI) |
-                       (1 << CP0C3_RXI) | (1 << CP0C3_LPA),
+                       (1 << CP0C3_RXI) | (1 << CP0C3_LPA) | (1 << CP0C3_VInt),
         .CP0_Config4 = MIPS_CONFIG4 | (1U << CP0C4_M) | (3 << CP0C4_IE) |
-                       (0xfc << CP0C4_KScrExist),
+                       (1 << CP0C4_AE) | (0xfc << CP0C4_KScrExist),
         .CP0_Config5 = MIPS_CONFIG5 | (1 << CP0C5_XNP) | (1 << CP0C5_VP) |
-                       (1 << CP0C5_LLB),
+                       (1 << CP0C5_LLB) | (1 << CP0C5_MRP),
         .CP0_Config5_rw_bitmask = (1 << CP0C5_MSAEn) | (1 << CP0C5_SBRI) |
                                   (1 << CP0C5_FRE) | (1 << CP0C5_UFE),
         .CP0_LLAddr_rw_bitmask = 0,
@@ -703,9 +700,10 @@ static const mips_def_t mips_defs[] =
         .CP0_PageGrain_rw_bitmask = (1 << CP0PG_ELPA),
         .CP1_fcr0 = (1 << FCR0_FREP) | (1 << FCR0_HAS2008) | (1 << FCR0_F64) |
                     (1 << FCR0_L) | (1 << FCR0_W) | (1 << FCR0_D) |
-                    (1 << FCR0_S) | (0x00 << FCR0_PRID) | (0x0 << FCR0_REV),
+                    (1 << FCR0_S) | (0x03 << FCR0_PRID) | (0x0 << FCR0_REV),
         .CP1_fcr31 = (1 << FCR31_ABS2008) | (1 << FCR31_NAN2008),
         .CP1_fcr31_rw_bitmask = 0x0103FFFF,
+        .MSAIR = 0x03 << MSAIR_ProcID,
         .SEGBITS = 48,
         .PABITS = 48,
         .insn_flags = CPU_MIPS64R6 | ASE_MSA,
diff --git a/target-moxie/cpu.h b/target-moxie/cpu.h
index 63d5cafc55..3e880facf4 100644
--- a/target-moxie/cpu.h
+++ b/target-moxie/cpu.h
@@ -16,8 +16,9 @@
  * 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 _CPU_MOXIE_H
-#define _CPU_MOXIE_H
+
+#ifndef MOXIE_CPU_H
+#define MOXIE_CPU_H
 
 #include "qemu-common.h"
 
@@ -139,4 +140,4 @@ static inline void cpu_get_tb_cpu_state(CPUMoxieState *env, target_ulong *pc,
 int moxie_cpu_handle_mmu_fault(CPUState *cpu, vaddr address,
                                int rw, int mmu_idx);
 
-#endif /* _CPU_MOXIE_H */
+#endif /* MOXIE_CPU_H */
diff --git a/target-moxie/helper.c b/target-moxie/helper.c
index d51e9b9cc4..330299f5a7 100644
--- a/target-moxie/helper.c
+++ b/target-moxie/helper.c
@@ -29,12 +29,12 @@
 /* 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) */
-void tlb_fill(CPUState *cs, target_ulong addr, int is_write, int mmu_idx,
-              uintptr_t retaddr)
+void tlb_fill(CPUState *cs, target_ulong addr, MMUAccessType access_type,
+              int mmu_idx, uintptr_t retaddr)
 {
     int ret;
 
-    ret = moxie_cpu_handle_mmu_fault(cs, addr, is_write, mmu_idx);
+    ret = moxie_cpu_handle_mmu_fault(cs, addr, access_type, mmu_idx);
     if (unlikely(ret)) {
         if (retaddr) {
             cpu_restore_state(cs, retaddr);
diff --git a/target-openrisc/cpu.h b/target-openrisc/cpu.h
index 9451a7cca6..aaf153579a 100644
--- a/target-openrisc/cpu.h
+++ b/target-openrisc/cpu.h
@@ -17,8 +17,8 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 
-#ifndef CPU_OPENRISC_H
-#define CPU_OPENRISC_H
+#ifndef OPENRISC_CPU_H
+#define OPENRISC_CPU_H
 
 #define TARGET_LONG_BITS 32
 
@@ -408,4 +408,4 @@ static inline int cpu_mmu_index(CPUOpenRISCState *env, bool ifetch)
 
 #define CPU_INTERRUPT_TIMER   CPU_INTERRUPT_TGT_INT_0
 
-#endif /* CPU_OPENRISC_H */
+#endif /* OPENRISC_CPU_H */
diff --git a/target-openrisc/exception.h b/target-openrisc/exception.h
index 4b64430df1..4ec56b4653 100644
--- a/target-openrisc/exception.h
+++ b/target-openrisc/exception.h
@@ -17,12 +17,12 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 
-#ifndef QEMU_OPENRISC_EXCP_H
-#define QEMU_OPENRISC_EXCP_H
+#ifndef TARGET_OPENRISC_EXCEPTION_H
+#define TARGET_OPENRISC_EXCEPTION_H
 
 #include "cpu.h"
 #include "qemu-common.h"
 
 void QEMU_NORETURN raise_exception(OpenRISCCPU *cpu, uint32_t excp);
 
-#endif /* QEMU_OPENRISC_EXCP_H */
+#endif /* TARGET_OPENRISC_EXCEPTION_H */
diff --git a/target-openrisc/mmu_helper.c b/target-openrisc/mmu_helper.c
index c0658c3868..a44d0aa51a 100644
--- a/target-openrisc/mmu_helper.c
+++ b/target-openrisc/mmu_helper.c
@@ -25,12 +25,12 @@
 
 #ifndef CONFIG_USER_ONLY
 
-void tlb_fill(CPUState *cs, target_ulong addr, int is_write,
+void tlb_fill(CPUState *cs, target_ulong addr, MMUAccessType access_type,
               int mmu_idx, uintptr_t retaddr)
 {
     int ret;
 
-    ret = openrisc_cpu_handle_mmu_fault(cs, addr, is_write, mmu_idx);
+    ret = openrisc_cpu_handle_mmu_fault(cs, addr, access_type, mmu_idx);
 
     if (ret) {
         if (retaddr) {
diff --git a/target-ppc/cpu.h b/target-ppc/cpu.h
index 2666a3f80d..5fce1ffa25 100644
--- a/target-ppc/cpu.h
+++ b/target-ppc/cpu.h
@@ -16,8 +16,9 @@
  * 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/>.
  */
-#if !defined (__CPU_PPC_H__)
-#define __CPU_PPC_H__
+
+#ifndef PPC_CPU_H
+#define PPC_CPU_H
 
 #include "qemu-common.h"
 
@@ -2432,4 +2433,4 @@ int ppc_get_vcpu_dt_id(PowerPCCPU *cpu);
 PowerPCCPU *ppc_get_vcpu_by_dt_id(int cpu_dt_id);
 
 void ppc_maybe_bswap_register(CPUPPCState *env, uint8_t *mem_buf, int len);
-#endif /* !defined (__CPU_PPC_H__) */
+#endif /* PPC_CPU_H */
diff --git a/target-ppc/helper_regs.h b/target-ppc/helper_regs.h
index 8fdfa5c7e6..8d38828936 100644
--- a/target-ppc/helper_regs.h
+++ b/target-ppc/helper_regs.h
@@ -17,8 +17,8 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 
-#if !defined(__HELPER_REGS_H__)
-#define __HELPER_REGS_H__
+#ifndef HELPER_REGS_H
+#define HELPER_REGS_H
 
 /* Swap temporary saved registers with GPRs */
 static inline void hreg_swap_gpr_tgpr(CPUPPCState *env)
@@ -168,4 +168,4 @@ static inline void check_tlb_flush(CPUPPCState *env)
 static inline void check_tlb_flush(CPUPPCState *env) { }
 #endif
 
-#endif /* !defined(__HELPER_REGS_H__) */
+#endif /* HELPER_REGS_H */
diff --git a/target-ppc/kvm_ppc.h b/target-ppc/kvm_ppc.h
index 20bfb59b1a..5461d1082c 100644
--- a/target-ppc/kvm_ppc.h
+++ b/target-ppc/kvm_ppc.h
@@ -6,8 +6,8 @@
  *
  */
 
-#ifndef __KVM_PPC_H__
-#define __KVM_PPC_H__
+#ifndef KVM_PPC_H
+#define KVM_PPC_H
 
 #define TYPE_HOST_POWERPC_CPU "host-" TYPE_POWERPC_CPU
 
@@ -316,4 +316,4 @@ static inline void kvmppc_icbi_range(PowerPCCPU *cpu, uint8_t *addr, int len)
 #define KVM_INTERRUPT_SET_LEVEL -3
 #endif
 
-#endif /* __KVM_PPC_H__ */
+#endif /* KVM_PPC_H */
diff --git a/target-ppc/mmu-hash32.h b/target-ppc/mmu-hash32.h
index aaceacd4d7..5b9fb08d1a 100644
--- a/target-ppc/mmu-hash32.h
+++ b/target-ppc/mmu-hash32.h
@@ -1,5 +1,5 @@
-#if !defined (__MMU_HASH32_H__)
-#define __MMU_HASH32_H__
+#ifndef MMU_HASH32_H
+#define MMU_HASH32_H
 
 #ifndef CONFIG_USER_ONLY
 
@@ -109,4 +109,4 @@ typedef struct {
 
 #endif /* CONFIG_USER_ONLY */
 
-#endif /* __MMU_HASH32_H__ */
+#endif /* MMU_HASH32_H */
diff --git a/target-ppc/mmu-hash64.h b/target-ppc/mmu-hash64.h
index 3a7476b30a..db265e30b2 100644
--- a/target-ppc/mmu-hash64.h
+++ b/target-ppc/mmu-hash64.h
@@ -1,5 +1,5 @@
-#if !defined (__MMU_HASH64_H__)
-#define __MMU_HASH64_H__
+#ifndef MMU_HASH64_H
+#define MMU_HASH64_H
 
 #ifndef CONFIG_USER_ONLY
 
@@ -134,4 +134,4 @@ typedef struct {
 
 #endif /* CONFIG_USER_ONLY */
 
-#endif /* !defined (__MMU_HASH64_H__) */
+#endif /* MMU_HASH64_H */
diff --git a/target-ppc/mmu_helper.c b/target-ppc/mmu_helper.c
index 485d5b8fde..3eb3cd78e2 100644
--- a/target-ppc/mmu_helper.c
+++ b/target-ppc/mmu_helper.c
@@ -2878,8 +2878,8 @@ void helper_check_tlb_flush(CPUPPCState *env)
    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(CPUState *cs, target_ulong addr, int is_write, int mmu_idx,
-              uintptr_t retaddr)
+void tlb_fill(CPUState *cs, target_ulong addr, MMUAccessType access_type,
+              int mmu_idx, uintptr_t retaddr)
 {
     PowerPCCPU *cpu = POWERPC_CPU(cs);
     PowerPCCPUClass *pcc = POWERPC_CPU_GET_CLASS(cs);
@@ -2887,9 +2887,9 @@ void tlb_fill(CPUState *cs, target_ulong addr, int is_write, int mmu_idx,
     int ret;
 
     if (pcc->handle_mmu_fault) {
-        ret = pcc->handle_mmu_fault(cpu, addr, is_write, mmu_idx);
+        ret = pcc->handle_mmu_fault(cpu, addr, access_type, mmu_idx);
     } else {
-        ret = cpu_ppc_handle_mmu_fault(env, addr, is_write, mmu_idx);
+        ret = cpu_ppc_handle_mmu_fault(env, addr, access_type, mmu_idx);
     }
     if (unlikely(ret != 0)) {
         if (likely(retaddr)) {
diff --git a/target-ppc/translate_init.c b/target-ppc/translate_init.c
index 8f257fb74a..7cb784262c 100644
--- a/target-ppc/translate_init.c
+++ b/target-ppc/translate_init.c
@@ -21,7 +21,7 @@
 #include "qemu/osdep.h"
 #include "disas/bfd.h"
 #include "exec/gdbstub.h"
-#include <sysemu/kvm.h>
+#include "sysemu/kvm.h"
 #include "kvm_ppc.h"
 #include "sysemu/arch_init.h"
 #include "sysemu/cpus.h"
diff --git a/target-s390x/cpu.h b/target-s390x/cpu.h
index 8bcb0f75f3..c216bdacef 100644
--- a/target-s390x/cpu.h
+++ b/target-s390x/cpu.h
@@ -19,8 +19,9 @@
  * 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_S390X_H
-#define CPU_S390X_H
+
+#ifndef S390X_CPU_H
+#define S390X_CPU_H
 
 #include "qemu-common.h"
 #include "cpu-qom.h"
@@ -219,7 +220,7 @@ int s390_cpu_gdb_write_register(CPUState *cpu, uint8_t *buf, int reg);
 void s390_cpu_gdb_init(CPUState *cs);
 void s390x_cpu_debug_excp_handler(CPUState *cs);
 
-#include <sysemu/kvm.h>
+#include "sysemu/kvm.h"
 
 /* distinguish between 24 bit and 31 bit addressing */
 #define HIGH_ORDER_BIT 0x80000000
diff --git a/target-s390x/kvm.c b/target-s390x/kvm.c
index 45e94ca48a..2991bff6a4 100644
--- a/target-s390x/kvm.c
+++ b/target-s390x/kvm.c
@@ -2246,10 +2246,10 @@ int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
                              uint64_t address, uint32_t data, PCIDevice *dev)
 {
     S390PCIBusDevice *pbdev;
-    uint32_t fid = data >> ZPCI_MSI_VEC_BITS;
+    uint32_t idx = data >> ZPCI_MSI_VEC_BITS;
     uint32_t vec = data & ZPCI_MSI_VEC_MASK;
 
-    pbdev = s390_pci_find_dev_by_fid(fid);
+    pbdev = s390_pci_find_dev_by_idx(idx);
     if (!pbdev) {
         DPRINTF("add_msi_route no dev\n");
         return -ENODEV;
diff --git a/target-s390x/mem_helper.c b/target-s390x/mem_helper.c
index ec8059a264..99bc5e2834 100644
--- a/target-s390x/mem_helper.c
+++ b/target-s390x/mem_helper.c
@@ -36,12 +36,12 @@
    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(CPUState *cs, target_ulong addr, int is_write, int mmu_idx,
-              uintptr_t retaddr)
+void tlb_fill(CPUState *cs, target_ulong addr, MMUAccessType access_type,
+              int mmu_idx, uintptr_t retaddr)
 {
     int ret;
 
-    ret = s390_cpu_handle_mmu_fault(cs, addr, is_write, mmu_idx);
+    ret = s390_cpu_handle_mmu_fault(cs, addr, access_type, mmu_idx);
     if (unlikely(ret != 0)) {
         if (likely(retaddr)) {
             /* now we have a real cpu fault */
diff --git a/target-sh4/cpu.h b/target-sh4/cpu.h
index 3f9dae2d1f..478ab55868 100644
--- a/target-sh4/cpu.h
+++ b/target-sh4/cpu.h
@@ -16,8 +16,9 @@
  * 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_SH4_H
-#define _CPU_SH4_H
+
+#ifndef SH4_CPU_H
+#define SH4_CPU_H
 
 #include "qemu-common.h"
 #include "cpu-qom.h"
@@ -387,4 +388,4 @@ static inline void cpu_get_tb_cpu_state(CPUSH4State *env, target_ulong *pc,
             | (env->movcal_backup ? TB_FLAG_PENDING_MOVCA : 0); /* Bit 4 */
 }
 
-#endif				/* _CPU_SH4_H */
+#endif /* SH4_CPU_H */
diff --git a/target-sh4/op_helper.c b/target-sh4/op_helper.c
index 303e83e7e5..0204b0338f 100644
--- a/target-sh4/op_helper.c
+++ b/target-sh4/op_helper.c
@@ -24,12 +24,12 @@
 
 #ifndef CONFIG_USER_ONLY
 
-void tlb_fill(CPUState *cs, target_ulong addr, int is_write, int mmu_idx,
-              uintptr_t retaddr)
+void tlb_fill(CPUState *cs, target_ulong addr, MMUAccessType access_type,
+              int mmu_idx, uintptr_t retaddr)
 {
     int ret;
 
-    ret = superh_cpu_handle_mmu_fault(cs, addr, is_write, mmu_idx);
+    ret = superh_cpu_handle_mmu_fault(cs, addr, access_type, mmu_idx);
     if (ret) {
         /* now we have a real cpu fault */
         if (retaddr) {
diff --git a/target-sparc/asi.h b/target-sparc/asi.h
new file mode 100644
index 0000000000..c9a1849600
--- /dev/null
+++ b/target-sparc/asi.h
@@ -0,0 +1,311 @@
+#ifndef _SPARC_ASI_H
+#define _SPARC_ASI_H
+
+/* asi.h:  Address Space Identifier values for the sparc.
+ *
+ * Copyright (C) 1995,1996 David S. Miller (davem@caip.rutgers.edu)
+ *
+ * Pioneer work for sun4m: Paul Hatchman (paul@sfe.com.au)
+ * Joint edition for sun4c+sun4m: Pete A. Zaitcev <zaitcev@ipmce.su>
+ */
+
+/* The first batch are for the sun4c. */
+
+#define ASI_NULL1           0x00
+#define ASI_NULL2           0x01
+
+/* sun4c and sun4 control registers and mmu/vac ops */
+#define ASI_CONTROL         0x02
+#define ASI_SEGMAP          0x03
+#define ASI_PTE             0x04
+#define ASI_HWFLUSHSEG      0x05
+#define ASI_HWFLUSHPAGE     0x06
+#define ASI_REGMAP          0x06
+#define ASI_HWFLUSHCONTEXT  0x07
+
+#define ASI_USERTXT         0x08
+#define ASI_KERNELTXT       0x09
+#define ASI_USERDATA        0x0a
+#define ASI_KERNELDATA      0x0b
+
+/* VAC Cache flushing on sun4c and sun4 */
+#define ASI_FLUSHSEG        0x0c
+#define ASI_FLUSHPG         0x0d
+#define ASI_FLUSHCTX        0x0e
+
+/* SPARCstation-5: only 6 bits are decoded. */
+/* wo = Write Only, rw = Read Write;        */
+/* ss = Single Size, as = All Sizes;        */
+#define ASI_M_RES00         0x00   /* Don't touch... */
+#define ASI_M_UNA01         0x01   /* Same here... */
+#define ASI_M_MXCC          0x02   /* Access to TI VIKING MXCC registers */
+#define ASI_M_FLUSH_PROBE   0x03   /* Reference MMU Flush/Probe; rw, ss */
+#define ASI_M_MMUREGS       0x04   /* MMU Registers; rw, ss */
+#define ASI_M_TLBDIAG       0x05   /* MMU TLB only Diagnostics */
+#define ASI_M_DIAGS         0x06   /* Reference MMU Diagnostics */
+#define ASI_M_IODIAG        0x07   /* MMU I/O TLB only Diagnostics */
+#define ASI_M_USERTXT       0x08   /* Same as ASI_USERTXT; rw, as */
+#define ASI_M_KERNELTXT     0x09   /* Same as ASI_KERNELTXT; rw, as */
+#define ASI_M_USERDATA      0x0A   /* Same as ASI_USERDATA; rw, as */
+#define ASI_M_KERNELDATA    0x0B   /* Same as ASI_KERNELDATA; rw, as */
+#define ASI_M_TXTC_TAG      0x0C   /* Instruction Cache Tag; rw, ss */
+#define ASI_M_TXTC_DATA     0x0D   /* Instruction Cache Data; rw, ss */
+#define ASI_M_DATAC_TAG     0x0E   /* Data Cache Tag; rw, ss */
+#define ASI_M_DATAC_DATA    0x0F   /* Data Cache Data; rw, ss */
+
+/* The following cache flushing ASIs work only with the 'sta'
+ * instruction. Results are unpredictable for 'swap' and 'ldstuba',
+ * so don't do it.
+ */
+
+/* These ASI flushes affect external caches too. */
+#define ASI_M_FLUSH_PAGE    0x10   /* Flush I&D Cache Line (page); wo, ss */
+#define ASI_M_FLUSH_SEG     0x11   /* Flush I&D Cache Line (seg); wo, ss */
+#define ASI_M_FLUSH_REGION  0x12   /* Flush I&D Cache Line (region); wo, ss */
+#define ASI_M_FLUSH_CTX     0x13   /* Flush I&D Cache Line (context); wo, ss */
+#define ASI_M_FLUSH_USER    0x14   /* Flush I&D Cache Line (user); wo, ss */
+
+/* Block-copy operations are available only on certain V8 cpus. */
+#define ASI_M_BCOPY         0x17   /* Block copy */
+
+/* These affect only the ICACHE and are Ross HyperSparc and TurboSparc specific. */
+#define ASI_M_IFLUSH_PAGE   0x18   /* Flush I Cache Line (page); wo, ss */
+#define ASI_M_IFLUSH_SEG    0x19   /* Flush I Cache Line (seg); wo, ss */
+#define ASI_M_IFLUSH_REGION 0x1A   /* Flush I Cache Line (region); wo, ss */
+#define ASI_M_IFLUSH_CTX    0x1B   /* Flush I Cache Line (context); wo, ss */
+#define ASI_M_IFLUSH_USER   0x1C   /* Flush I Cache Line (user); wo, ss */
+
+/* Block-fill operations are available on certain V8 cpus */
+#define ASI_M_BFILL         0x1F
+
+/* This allows direct access to main memory, actually 0x20 to 0x2f are
+ * the available ASI's for physical ram pass-through, but I don't have
+ * any idea what the other ones do....
+ */
+
+#define ASI_M_BYPASS       0x20   /* Reference MMU bypass; rw, as */
+#define ASI_M_FBMEM        0x29   /* Graphics card frame buffer access */
+#define ASI_M_VMEUS        0x2A   /* VME user 16-bit access */
+#define ASI_M_VMEPS        0x2B   /* VME priv 16-bit access */
+#define ASI_M_VMEUT        0x2C   /* VME user 32-bit access */
+#define ASI_M_VMEPT        0x2D   /* VME priv 32-bit access */
+#define ASI_M_SBUS         0x2E   /* Direct SBus access */
+#define ASI_M_CTL          0x2F   /* Control Space (ECC and MXCC are here) */
+
+
+/* This is ROSS HyperSparc only. */
+#define ASI_M_FLUSH_IWHOLE 0x31   /* Flush entire ICACHE; wo, ss */
+
+/* Tsunami/Viking/TurboSparc i/d cache flash clear. */
+#define ASI_M_IC_FLCLEAR   0x36
+#define ASI_M_DC_FLCLEAR   0x37
+
+#define ASI_M_DCDR         0x39   /* Data Cache Diagnostics Register rw, ss */
+
+#define ASI_M_VIKING_TMP1  0x40	  /* Emulation temporary 1 on Viking */
+/* only available on SuperSparc I */
+/* #define ASI_M_VIKING_TMP2  0x41 */  /* Emulation temporary 2 on Viking */
+
+#define ASI_M_ACTION       0x4c   /* Breakpoint Action Register (GNU/Viking) */
+
+/* LEON ASI */
+#define ASI_LEON_NOCACHE        0x01
+
+#define ASI_LEON_DCACHE_MISS    0x01
+
+#define ASI_LEON_CACHEREGS      0x02
+#define ASI_LEON_IFLUSH         0x10
+#define ASI_LEON_DFLUSH         0x11
+
+#define ASI_LEON_MMUFLUSH       0x18
+#define ASI_LEON_MMUREGS        0x19
+#define ASI_LEON_BYPASS         0x1c
+#define ASI_LEON_FLUSH_PAGE     0x10
+
+/* V9 Architecture mandary ASIs. */
+#define ASI_N			0x04 /* Nucleus				*/
+#define ASI_NL			0x0c /* Nucleus, little endian		*/
+#define ASI_AIUP		0x10 /* Primary, user			*/
+#define ASI_AIUS		0x11 /* Secondary, user			*/
+#define ASI_AIUPL		0x18 /* Primary, user, little endian	*/
+#define ASI_AIUSL		0x19 /* Secondary, user, little endian	*/
+#define ASI_P			0x80 /* Primary, implicit		*/
+#define ASI_S			0x81 /* Secondary, implicit		*/
+#define ASI_PNF			0x82 /* Primary, no fault		*/
+#define ASI_SNF			0x83 /* Secondary, no fault		*/
+#define ASI_PL			0x88 /* Primary, implicit, l-endian	*/
+#define ASI_SL			0x89 /* Secondary, implicit, l-endian	*/
+#define ASI_PNFL		0x8a /* Primary, no fault, l-endian	*/
+#define ASI_SNFL		0x8b /* Secondary, no fault, l-endian	*/
+
+/* SpitFire and later extended ASIs.  The "(III)" marker designates
+ * UltraSparc-III and later specific ASIs.  The "(CMT)" marker designates
+ * Chip Multi Threading specific ASIs.  "(NG)" designates Niagara specific
+ * ASIs, "(4V)" designates SUN4V specific ASIs.  "(NG4)" designates SPARC-T4
+ * and later ASIs.
+ */
+#define ASI_REAL                0x14 /* Real address, cachable          */
+#define ASI_PHYS_USE_EC		0x14 /* PADDR, E-cachable		*/
+#define ASI_REAL_IO             0x15 /* Real address, non-cachable      */
+#define ASI_PHYS_BYPASS_EC_E	0x15 /* PADDR, E-bit			*/
+#define ASI_BLK_AIUP_4V		0x16 /* (4V) Prim, user, block ld/st	*/
+#define ASI_BLK_AIUS_4V		0x17 /* (4V) Sec, user, block ld/st	*/
+#define ASI_REAL_L              0x1c /* Real address, cachable, LE      */
+#define ASI_PHYS_USE_EC_L	0x1c /* PADDR, E-cachable, little endian*/
+#define ASI_REAL_IO_L           0x1d /* Real address, non-cachable, LE  */
+#define ASI_PHYS_BYPASS_EC_E_L	0x1d /* PADDR, E-bit, little endian	*/
+#define ASI_BLK_AIUP_L_4V	0x1e /* (4V) Prim, user, block, l-endian*/
+#define ASI_BLK_AIUS_L_4V	0x1f /* (4V) Sec, user, block, l-endian	*/
+#define ASI_SCRATCHPAD		0x20 /* (4V) Scratch Pad Registers	*/
+#define ASI_MMU			0x21 /* (4V) MMU Context Registers	*/
+#define ASI_TWINX_AIUP          0x22 /* twin load, primary user         */
+#define ASI_TWINX_AIUS          0x23 /* twin load, secondary user       */
+#define ASI_BLK_INIT_QUAD_LDD_AIUS 0x23 /* (NG) init-store, twin load,
+					 * secondary, user
+					 */
+#define ASI_NUCLEUS_QUAD_LDD	0x24 /* Cachable, qword load		*/
+#define ASI_QUEUE		0x25 /* (4V) Interrupt Queue Registers	*/
+#define ASI_TWINX_REAL          0x26 /* twin load, real, cachable       */
+#define ASI_QUAD_LDD_PHYS_4V	0x26 /* (4V) Physical, qword load	*/
+#define ASI_TWINX_N             0x27 /* twin load, nucleus              */
+#define ASI_TWINX_AIUP_L        0x2a /* twin load, primary user, LE     */
+#define ASI_TWINX_AIUS_L        0x2b /* twin load, secondary user, LE   */
+#define ASI_NUCLEUS_QUAD_LDD_L	0x2c /* Cachable, qword load, l-endian 	*/
+#define ASI_TWINX_REAL_L        0x2e /* twin load, real, cachable, LE   */
+#define ASI_QUAD_LDD_PHYS_L_4V	0x2e /* (4V) Phys, qword load, l-endian	*/
+#define ASI_TWINX_NL            0x2f /* twin load, nucleus, LE          */
+#define ASI_PCACHE_DATA_STATUS	0x30 /* (III) PCache data stat RAM diag	*/
+#define ASI_PCACHE_DATA		0x31 /* (III) PCache data RAM diag	*/
+#define ASI_PCACHE_TAG		0x32 /* (III) PCache tag RAM diag	*/
+#define ASI_PCACHE_SNOOP_TAG	0x33 /* (III) PCache snoop tag RAM diag	*/
+#define ASI_QUAD_LDD_PHYS	0x34 /* (III+) PADDR, qword load	*/
+#define ASI_WCACHE_VALID_BITS	0x38 /* (III) WCache Valid Bits diag	*/
+#define ASI_WCACHE_DATA		0x39 /* (III) WCache data RAM diag	*/
+#define ASI_WCACHE_TAG		0x3a /* (III) WCache tag RAM diag	*/
+#define ASI_WCACHE_SNOOP_TAG	0x3b /* (III) WCache snoop tag RAM diag	*/
+#define ASI_QUAD_LDD_PHYS_L	0x3c /* (III+) PADDR, qw-load, l-endian	*/
+#define ASI_SRAM_FAST_INIT	0x40 /* (III+) Fast SRAM init		*/
+#define ASI_CORE_AVAILABLE	0x41 /* (CMT) LP Available		*/
+#define ASI_CORE_ENABLE_STAT	0x41 /* (CMT) LP Enable Status		*/
+#define ASI_CORE_ENABLE		0x41 /* (CMT) LP Enable RW		*/
+#define ASI_XIR_STEERING	0x41 /* (CMT) XIR Steering RW		*/
+#define ASI_CORE_RUNNING_RW	0x41 /* (CMT) LP Running RW		*/
+#define ASI_CORE_RUNNING_W1S	0x41 /* (CMT) LP Running Write-One Set	*/
+#define ASI_CORE_RUNNING_W1C	0x41 /* (CMT) LP Running Write-One Clr	*/
+#define ASI_CORE_RUNNING_STAT	0x41 /* (CMT) LP Running Status		*/
+#define ASI_CMT_ERROR_STEERING	0x41 /* (CMT) Error Steering RW		*/
+#define ASI_DCACHE_INVALIDATE	0x42 /* (III) DCache Invalidate diag	*/
+#define ASI_DCACHE_UTAG		0x43 /* (III) DCache uTag diag		*/
+#define ASI_DCACHE_SNOOP_TAG	0x44 /* (III) DCache snoop tag RAM diag	*/
+#define ASI_LSU_CONTROL		0x45 /* Load-store control unit		*/
+#define ASI_DCU_CONTROL_REG	0x45 /* (III) DCache Unit Control reg	*/
+#define ASI_DCACHE_DATA		0x46 /* DCache data-ram diag access	*/
+#define ASI_DCACHE_TAG		0x47 /* Dcache tag/valid ram diag access*/
+#define ASI_INTR_DISPATCH_STAT	0x48 /* IRQ vector dispatch status	*/
+#define ASI_INTR_RECEIVE	0x49 /* IRQ vector receive status	*/
+#define ASI_UPA_CONFIG		0x4a /* UPA config space		*/
+#define ASI_JBUS_CONFIG		0x4a /* (IIIi) JBUS Config Register	*/
+#define ASI_SAFARI_CONFIG	0x4a /* (III) Safari Config Register	*/
+#define ASI_SAFARI_ADDRESS	0x4a /* (III) Safari Address Register	*/
+#define ASI_ESTATE_ERROR_EN	0x4b /* E-cache error enable space	*/
+#define ASI_AFSR		0x4c /* Async fault status register	*/
+#define ASI_AFAR		0x4d /* Async fault address register	*/
+#define ASI_EC_TAG_DATA		0x4e /* E-cache tag/valid ram diag acc	*/
+#define ASI_IMMU		0x50 /* Insn-MMU main register space	*/
+#define ASI_IMMU_TSB_8KB_PTR	0x51 /* Insn-MMU 8KB TSB pointer reg	*/
+#define ASI_IMMU_TSB_64KB_PTR	0x52 /* Insn-MMU 64KB TSB pointer reg	*/
+#define ASI_ITLB_DATA_IN	0x54 /* Insn-MMU TLB data in reg	*/
+#define ASI_ITLB_DATA_ACCESS	0x55 /* Insn-MMU TLB data access reg	*/
+#define ASI_ITLB_TAG_READ	0x56 /* Insn-MMU TLB tag read reg	*/
+#define ASI_IMMU_DEMAP		0x57 /* Insn-MMU TLB demap		*/
+#define ASI_DMMU		0x58 /* Data-MMU main register space	*/
+#define ASI_DMMU_TSB_8KB_PTR	0x59 /* Data-MMU 8KB TSB pointer reg	*/
+#define ASI_DMMU_TSB_64KB_PTR	0x5a /* Data-MMU 16KB TSB pointer reg	*/
+#define ASI_DMMU_TSB_DIRECT_PTR	0x5b /* Data-MMU TSB direct pointer reg	*/
+#define ASI_DTLB_DATA_IN	0x5c /* Data-MMU TLB data in reg	*/
+#define ASI_DTLB_DATA_ACCESS	0x5d /* Data-MMU TLB data access reg	*/
+#define ASI_DTLB_TAG_READ	0x5e /* Data-MMU TLB tag read reg	*/
+#define ASI_DMMU_DEMAP		0x5f /* Data-MMU TLB demap		*/
+#define ASI_IIU_INST_TRAP	0x60 /* (III) Instruction Breakpoint	*/
+#define ASI_INTR_ID		0x63 /* (CMT) Interrupt ID register	*/
+#define ASI_CORE_ID		0x63 /* (CMT) LP ID register		*/
+#define ASI_CESR_ID		0x63 /* (CMT) CESR ID register		*/
+#define ASI_IC_INSTR		0x66 /* Insn cache instrucion ram diag	*/
+#define ASI_IC_TAG		0x67 /* Insn cache tag/valid ram diag 	*/
+#define ASI_IC_STAG		0x68 /* (III) Insn cache snoop tag ram	*/
+#define ASI_IC_PRE_DECODE	0x6e /* Insn cache pre-decode ram diag	*/
+#define ASI_IC_NEXT_FIELD	0x6f /* Insn cache next-field ram diag	*/
+#define ASI_BRPRED_ARRAY	0x6f /* (III) Branch Prediction RAM diag*/
+#define ASI_BLK_AIUP		0x70 /* Primary, user, block load/store	*/
+#define ASI_BLK_AIUS		0x71 /* Secondary, user, block ld/st	*/
+#define ASI_MCU_CTRL_REG	0x72 /* (III) Memory controller regs	*/
+#define ASI_EC_DATA		0x74 /* (III) E-cache data staging reg	*/
+#define ASI_EC_CTRL		0x75 /* (III) E-cache control reg	*/
+#define ASI_EC_W		0x76 /* E-cache diag write access	*/
+#define ASI_UDB_ERROR_W		0x77 /* External UDB error regs W	*/
+#define ASI_UDB_CONTROL_W	0x77 /* External UDB control regs W	*/
+#define ASI_INTR_W		0x77 /* IRQ vector dispatch write	*/
+#define ASI_INTR_DATAN_W	0x77 /* (III) Out irq vector data reg N	*/
+#define ASI_INTR_DISPATCH_W	0x77 /* (III) Interrupt vector dispatch	*/
+#define ASI_BLK_AIUPL		0x78 /* Primary, user, little, blk ld/st*/
+#define ASI_BLK_AIUSL		0x79 /* Secondary, user, little, blk ld/st*/
+#define ASI_EC_R		0x7e /* E-cache diag read access	*/
+#define ASI_UDBH_ERROR_R	0x7f /* External UDB error regs rd hi	*/
+#define ASI_UDBL_ERROR_R	0x7f /* External UDB error regs rd low	*/
+#define ASI_UDBH_CONTROL_R	0x7f /* External UDB control regs rd hi	*/
+#define ASI_UDBL_CONTROL_R	0x7f /* External UDB control regs rd low*/
+#define ASI_INTR_R		0x7f /* IRQ vector dispatch read	*/
+#define ASI_INTR_DATAN_R	0x7f /* (III) In irq vector data reg N	*/
+#define ASI_PIC			0xb0 /* (NG4) PIC registers		*/
+#define ASI_PST8_P		0xc0 /* Primary, 8 8-bit, partial	*/
+#define ASI_PST8_S		0xc1 /* Secondary, 8 8-bit, partial	*/
+#define ASI_PST16_P		0xc2 /* Primary, 4 16-bit, partial	*/
+#define ASI_PST16_S		0xc3 /* Secondary, 4 16-bit, partial	*/
+#define ASI_PST32_P		0xc4 /* Primary, 2 32-bit, partial	*/
+#define ASI_PST32_S		0xc5 /* Secondary, 2 32-bit, partial	*/
+#define ASI_PST8_PL		0xc8 /* Primary, 8 8-bit, partial, L	*/
+#define ASI_PST8_SL		0xc9 /* Secondary, 8 8-bit, partial, L	*/
+#define ASI_PST16_PL		0xca /* Primary, 4 16-bit, partial, L	*/
+#define ASI_PST16_SL		0xcb /* Secondary, 4 16-bit, partial, L	*/
+#define ASI_PST32_PL		0xcc /* Primary, 2 32-bit, partial, L	*/
+#define ASI_PST32_SL		0xcd /* Secondary, 2 32-bit, partial, L	*/
+#define ASI_FL8_P		0xd0 /* Primary, 1 8-bit, fpu ld/st	*/
+#define ASI_FL8_S		0xd1 /* Secondary, 1 8-bit, fpu ld/st	*/
+#define ASI_FL16_P		0xd2 /* Primary, 1 16-bit, fpu ld/st	*/
+#define ASI_FL16_S		0xd3 /* Secondary, 1 16-bit, fpu ld/st	*/
+#define ASI_FL8_PL		0xd8 /* Primary, 1 8-bit, fpu ld/st, L	*/
+#define ASI_FL8_SL		0xd9 /* Secondary, 1 8-bit, fpu ld/st, L*/
+#define ASI_FL16_PL		0xda /* Primary, 1 16-bit, fpu ld/st, L	*/
+#define ASI_FL16_SL		0xdb /* Secondary, 1 16-bit, fpu ld/st,L*/
+#define ASI_BLK_COMMIT_P	0xe0 /* Primary, blk store commit	*/
+#define ASI_BLK_COMMIT_S	0xe1 /* Secondary, blk store commit	*/
+#define ASI_TWINX_P             0xe2 /* twin load, primary implicit     */
+#define ASI_BLK_INIT_QUAD_LDD_P	0xe2 /* (NG) init-store, twin load,
+				      * primary, implicit */
+#define ASI_TWINX_S             0xe3 /* twin load, secondary implicit   */
+#define ASI_BLK_INIT_QUAD_LDD_S	0xe3 /* (NG) init-store, twin load,
+				      * secondary, implicit */
+#define ASI_TWINX_PL            0xea /* twin load, primary implicit, LE */
+#define ASI_TWINX_SL            0xeb /* twin load, secondary implicit, LE */
+#define ASI_BLK_P		0xf0 /* Primary, blk ld/st		*/
+#define ASI_BLK_S		0xf1 /* Secondary, blk ld/st		*/
+#define ASI_ST_BLKINIT_MRU_P	0xf2 /* (NG4) init-store, twin load,
+				      * Most-Recently-Used, primary,
+				      * implicit
+				      */
+#define ASI_ST_BLKINIT_MRU_S	0xf2 /* (NG4) init-store, twin load,
+				      * Most-Recently-Used, secondary,
+				      * implicit
+				      */
+#define ASI_BLK_PL		0xf8 /* Primary, blk ld/st, little	*/
+#define ASI_BLK_SL		0xf9 /* Secondary, blk ld/st, little	*/
+#define ASI_ST_BLKINIT_MRU_PL	0xfa /* (NG4) init-store, twin load,
+				      * Most-Recently-Used, primary,
+				      * implicit, little-endian
+				      */
+#define ASI_ST_BLKINIT_MRU_SL	0xfb /* (NG4) init-store, twin load,
+				      * Most-Recently-Used, secondary,
+				      * implicit, little-endian
+				      */
+
+#endif /* _SPARC_ASI_H */
diff --git a/target-sparc/cpu.h b/target-sparc/cpu.h
index f78fabfe7b..a3d64a4e52 100644
--- a/target-sparc/cpu.h
+++ b/target-sparc/cpu.h
@@ -1,5 +1,5 @@
-#ifndef CPU_SPARC_H
-#define CPU_SPARC_H
+#ifndef SPARC_CPU_H
+#define SPARC_CPU_H
 
 #include "qemu-common.h"
 #include "qemu/bswap.h"
@@ -540,9 +540,10 @@ void sparc_cpu_dump_state(CPUState *cpu, FILE *f,
 hwaddr sparc_cpu_get_phys_page_debug(CPUState *cpu, vaddr addr);
 int sparc_cpu_gdb_read_register(CPUState *cpu, uint8_t *buf, int reg);
 int sparc_cpu_gdb_write_register(CPUState *cpu, uint8_t *buf, int reg);
-void QEMU_NORETURN sparc_cpu_do_unaligned_access(CPUState *cpu,
-                                                 vaddr addr, int is_write,
-                                                 int is_user, uintptr_t retaddr);
+void QEMU_NORETURN sparc_cpu_do_unaligned_access(CPUState *cpu, vaddr addr,
+                                                 MMUAccessType access_type,
+                                                 int mmu_idx,
+                                                 uintptr_t retaddr);
 
 #ifndef NO_CPU_IO_DEFS
 /* cpu_init.c */
@@ -718,34 +719,34 @@ void cpu_tick_set_limit(CPUTimer *timer, uint64_t limit);
 trap_state* cpu_tsptr(CPUSPARCState* env);
 #endif
 
-#define TB_FLAG_FPU_ENABLED (1 << 4)
-#define TB_FLAG_AM_ENABLED (1 << 5)
+#define TB_FLAG_MMU_MASK     7
+#define TB_FLAG_FPU_ENABLED  (1 << 4)
+#define TB_FLAG_AM_ENABLED   (1 << 5)
+#define TB_FLAG_ASI_SHIFT    24
 
 static inline void cpu_get_tb_cpu_state(CPUSPARCState *env, target_ulong *pc,
-                                        target_ulong *cs_base, uint32_t *flags)
+                                        target_ulong *cs_base, uint32_t *pflags)
 {
+    uint32_t flags;
     *pc = env->pc;
     *cs_base = env->npc;
+    flags = cpu_mmu_index(env, false);
 #ifdef TARGET_SPARC64
-    // AM . Combined FPU enable bits . PRIV . DMMU enabled . IMMU enabled
-    *flags = (env->pstate & PS_PRIV)               /* 2 */
-        | ((env->lsu & (DMMU_E | IMMU_E)) >> 2)    /* 1, 0 */
-        | ((env->tl & 0xff) << 8)
-        | (env->dmmu.mmu_primary_context << 16);   /* 16... */
     if (env->pstate & PS_AM) {
-        *flags |= TB_FLAG_AM_ENABLED;
+        flags |= TB_FLAG_AM_ENABLED;
     }
-    if ((env->def->features & CPU_FEATURE_FLOAT) && (env->pstate & PS_PEF)
+    if ((env->def->features & CPU_FEATURE_FLOAT)
+        && (env->pstate & PS_PEF)
         && (env->fprs & FPRS_FEF)) {
-        *flags |= TB_FLAG_FPU_ENABLED;
+        flags |= TB_FLAG_FPU_ENABLED;
     }
+    flags |= env->asi << TB_FLAG_ASI_SHIFT;
 #else
-    // FPU enable . Supervisor
-    *flags = env->psrs;
     if ((env->def->features & CPU_FEATURE_FLOAT) && env->psref) {
-        *flags |= TB_FLAG_FPU_ENABLED;
+        flags |= TB_FLAG_FPU_ENABLED;
     }
 #endif
+    *pflags = flags;
 }
 
 static inline bool tb_fpu_enabled(int tb_flags)
diff --git a/target-sparc/fop_helper.c b/target-sparc/fop_helper.c
index 08306436ac..c7fb176e4c 100644
--- a/target-sparc/fop_helper.c
+++ b/target-sparc/fop_helper.c
@@ -19,48 +19,60 @@
 
 #include "qemu/osdep.h"
 #include "cpu.h"
+#include "exec/exec-all.h"
 #include "exec/helper-proto.h"
 
 #define QT0 (env->qt0)
 #define QT1 (env->qt1)
 
-static void check_ieee_exceptions(CPUSPARCState *env)
+static target_ulong do_check_ieee_exceptions(CPUSPARCState *env, uintptr_t ra)
 {
-    target_ulong status;
+    target_ulong status = get_float_exception_flags(&env->fp_status);
+    target_ulong fsr = env->fsr;
+
+    if (unlikely(status)) {
+        /* Keep exception flags clear for next time.  */
+        set_float_exception_flags(0, &env->fp_status);
 
-    status = get_float_exception_flags(&env->fp_status);
-    if (status) {
         /* Copy IEEE 754 flags into FSR */
         if (status & float_flag_invalid) {
-            env->fsr |= FSR_NVC;
+            fsr |= FSR_NVC;
         }
         if (status & float_flag_overflow) {
-            env->fsr |= FSR_OFC;
+            fsr |= FSR_OFC;
         }
         if (status & float_flag_underflow) {
-            env->fsr |= FSR_UFC;
+            fsr |= FSR_UFC;
         }
         if (status & float_flag_divbyzero) {
-            env->fsr |= FSR_DZC;
+            fsr |= FSR_DZC;
         }
         if (status & float_flag_inexact) {
-            env->fsr |= FSR_NXC;
+            fsr |= FSR_NXC;
         }
 
-        if ((env->fsr & FSR_CEXC_MASK) & ((env->fsr & FSR_TEM_MASK) >> 23)) {
-            /* Unmasked exception, generate a trap */
-            env->fsr |= FSR_FTT_IEEE_EXCP;
-            helper_raise_exception(env, TT_FP_EXCP);
+        if ((fsr & FSR_CEXC_MASK) & ((fsr & FSR_TEM_MASK) >> 23)) {
+            CPUState *cs = CPU(sparc_env_get_cpu(env));
+
+            /* Unmasked exception, generate a trap.  Note that while
+               the helper is marked as NO_WG, we can get away with
+               writing to cpu state along the exception path, since
+               TCG generated code will never see the write.  */
+            env->fsr = fsr | FSR_FTT_IEEE_EXCP;
+            cs->exception_index = TT_FP_EXCP;
+            cpu_loop_exit_restore(cs, ra);
         } else {
             /* Accumulate exceptions */
-            env->fsr |= (env->fsr & FSR_CEXC_MASK) << 5;
+            fsr |= (fsr & FSR_CEXC_MASK) << 5;
         }
     }
+
+    return fsr;
 }
 
-static inline void clear_float_exceptions(CPUSPARCState *env)
+target_ulong helper_check_ieee_exceptions(CPUSPARCState *env)
 {
-    set_float_exception_flags(0, &env->fp_status);
+    return do_check_ieee_exceptions(env, GETPC());
 }
 
 #define F_HELPER(name, p) void helper_f##name##p(CPUSPARCState *env)
@@ -69,26 +81,16 @@ static inline void clear_float_exceptions(CPUSPARCState *env)
     float32 helper_f ## name ## s (CPUSPARCState *env, float32 src1, \
                                    float32 src2)                \
     {                                                           \
-        float32 ret;                                            \
-        clear_float_exceptions(env);                            \
-        ret = float32_ ## name (src1, src2, &env->fp_status);   \
-        check_ieee_exceptions(env);                             \
-        return ret;                                             \
+        return float32_ ## name (src1, src2, &env->fp_status);  \
     }                                                           \
     float64 helper_f ## name ## d (CPUSPARCState * env, float64 src1,\
                                    float64 src2)                \
     {                                                           \
-        float64 ret;                                            \
-        clear_float_exceptions(env);                            \
-        ret = float64_ ## name (src1, src2, &env->fp_status);   \
-        check_ieee_exceptions(env);                             \
-        return ret;                                             \
+        return float64_ ## name (src1, src2, &env->fp_status);  \
     }                                                           \
     F_HELPER(name, q)                                           \
     {                                                           \
-        clear_float_exceptions(env);                            \
         QT0 = float128_ ## name (QT0, QT1, &env->fp_status);    \
-        check_ieee_exceptions(env);                             \
     }
 
 F_BINOP(add);
@@ -99,22 +101,16 @@ F_BINOP(div);
 
 float64 helper_fsmuld(CPUSPARCState *env, float32 src1, float32 src2)
 {
-    float64 ret;
-    clear_float_exceptions(env);
-    ret = float64_mul(float32_to_float64(src1, &env->fp_status),
-                      float32_to_float64(src2, &env->fp_status),
-                      &env->fp_status);
-    check_ieee_exceptions(env);
-    return ret;
+    return float64_mul(float32_to_float64(src1, &env->fp_status),
+                       float32_to_float64(src2, &env->fp_status),
+                       &env->fp_status);
 }
 
 void helper_fdmulq(CPUSPARCState *env, float64 src1, float64 src2)
 {
-    clear_float_exceptions(env);
     QT0 = float128_mul(float64_to_float128(src1, &env->fp_status),
                        float64_to_float128(src2, &env->fp_status),
                        &env->fp_status);
-    check_ieee_exceptions(env);
 }
 
 float32 helper_fnegs(float32 src)
@@ -137,48 +133,32 @@ F_HELPER(neg, q)
 /* Integer to float conversion.  */
 float32 helper_fitos(CPUSPARCState *env, int32_t src)
 {
-    /* Inexact error possible converting int to float.  */
-    float32 ret;
-    clear_float_exceptions(env);
-    ret = int32_to_float32(src, &env->fp_status);
-    check_ieee_exceptions(env);
-    return ret;
+    return int32_to_float32(src, &env->fp_status);
 }
 
 float64 helper_fitod(CPUSPARCState *env, int32_t src)
 {
-    /* No possible exceptions converting int to double.  */
     return int32_to_float64(src, &env->fp_status);
 }
 
 void helper_fitoq(CPUSPARCState *env, int32_t src)
 {
-    /* No possible exceptions converting int to long double.  */
     QT0 = int32_to_float128(src, &env->fp_status);
 }
 
 #ifdef TARGET_SPARC64
 float32 helper_fxtos(CPUSPARCState *env, int64_t src)
 {
-    float32 ret;
-    clear_float_exceptions(env);
-    ret = int64_to_float32(src, &env->fp_status);
-    check_ieee_exceptions(env);
-    return ret;
+    return int64_to_float32(src, &env->fp_status);
 }
 
 float64 helper_fxtod(CPUSPARCState *env, int64_t src)
 {
-    float64 ret;
-    clear_float_exceptions(env);
-    ret = int64_to_float64(src, &env->fp_status);
-    check_ieee_exceptions(env);
-    return ret;
+    return int64_to_float64(src, &env->fp_status);
 }
 
 void helper_fxtoq(CPUSPARCState *env, int64_t src)
 {
-    /* No possible exceptions converting long long to long double.  */
     QT0 = int64_to_float128(src, &env->fp_status);
 }
 #endif
@@ -187,108 +167,64 @@ void helper_fxtoq(CPUSPARCState *env, int64_t src)
 /* floating point conversion */
 float32 helper_fdtos(CPUSPARCState *env, float64 src)
 {
-    float32 ret;
-    clear_float_exceptions(env);
-    ret = float64_to_float32(src, &env->fp_status);
-    check_ieee_exceptions(env);
-    return ret;
+    return float64_to_float32(src, &env->fp_status);
 }
 
 float64 helper_fstod(CPUSPARCState *env, float32 src)
 {
-    float64 ret;
-    clear_float_exceptions(env);
-    ret = float32_to_float64(src, &env->fp_status);
-    check_ieee_exceptions(env);
-    return ret;
+    return float32_to_float64(src, &env->fp_status);
 }
 
 float32 helper_fqtos(CPUSPARCState *env)
 {
-    float32 ret;
-    clear_float_exceptions(env);
-    ret = float128_to_float32(QT1, &env->fp_status);
-    check_ieee_exceptions(env);
-    return ret;
+    return float128_to_float32(QT1, &env->fp_status);
 }
 
 void helper_fstoq(CPUSPARCState *env, float32 src)
 {
-    clear_float_exceptions(env);
     QT0 = float32_to_float128(src, &env->fp_status);
-    check_ieee_exceptions(env);
 }
 
 float64 helper_fqtod(CPUSPARCState *env)
 {
-    float64 ret;
-    clear_float_exceptions(env);
-    ret = float128_to_float64(QT1, &env->fp_status);
-    check_ieee_exceptions(env);
-    return ret;
+    return float128_to_float64(QT1, &env->fp_status);
 }
 
 void helper_fdtoq(CPUSPARCState *env, float64 src)
 {
-    clear_float_exceptions(env);
     QT0 = float64_to_float128(src, &env->fp_status);
-    check_ieee_exceptions(env);
 }
 
 /* Float to integer conversion.  */
 int32_t helper_fstoi(CPUSPARCState *env, float32 src)
 {
-    int32_t ret;
-    clear_float_exceptions(env);
-    ret = float32_to_int32_round_to_zero(src, &env->fp_status);
-    check_ieee_exceptions(env);
-    return ret;
+    return float32_to_int32_round_to_zero(src, &env->fp_status);
 }
 
 int32_t helper_fdtoi(CPUSPARCState *env, float64 src)
 {
-    int32_t ret;
-    clear_float_exceptions(env);
-    ret = float64_to_int32_round_to_zero(src, &env->fp_status);
-    check_ieee_exceptions(env);
-    return ret;
+    return float64_to_int32_round_to_zero(src, &env->fp_status);
 }
 
 int32_t helper_fqtoi(CPUSPARCState *env)
 {
-    int32_t ret;
-    clear_float_exceptions(env);
-    ret = float128_to_int32_round_to_zero(QT1, &env->fp_status);
-    check_ieee_exceptions(env);
-    return ret;
+    return float128_to_int32_round_to_zero(QT1, &env->fp_status);
 }
 
 #ifdef TARGET_SPARC64
 int64_t helper_fstox(CPUSPARCState *env, float32 src)
 {
-    int64_t ret;
-    clear_float_exceptions(env);
-    ret = float32_to_int64_round_to_zero(src, &env->fp_status);
-    check_ieee_exceptions(env);
-    return ret;
+    return float32_to_int64_round_to_zero(src, &env->fp_status);
 }
 
 int64_t helper_fdtox(CPUSPARCState *env, float64 src)
 {
-    int64_t ret;
-    clear_float_exceptions(env);
-    ret = float64_to_int64_round_to_zero(src, &env->fp_status);
-    check_ieee_exceptions(env);
-    return ret;
+    return float64_to_int64_round_to_zero(src, &env->fp_status);
 }
 
 int64_t helper_fqtox(CPUSPARCState *env)
 {
-    int64_t ret;
-    clear_float_exceptions(env);
-    ret = float128_to_int64_round_to_zero(QT1, &env->fp_status);
-    check_ieee_exceptions(env);
-    return ret;
+    return float128_to_int64_round_to_zero(QT1, &env->fp_status);
 }
 #endif
 
@@ -311,87 +247,79 @@ void helper_fabsq(CPUSPARCState *env)
 
 float32 helper_fsqrts(CPUSPARCState *env, float32 src)
 {
-    float32 ret;
-    clear_float_exceptions(env);
-    ret = float32_sqrt(src, &env->fp_status);
-    check_ieee_exceptions(env);
-    return ret;
+    return float32_sqrt(src, &env->fp_status);
 }
 
 float64 helper_fsqrtd(CPUSPARCState *env, float64 src)
 {
-    float64 ret;
-    clear_float_exceptions(env);
-    ret = float64_sqrt(src, &env->fp_status);
-    check_ieee_exceptions(env);
-    return ret;
+    return float64_sqrt(src, &env->fp_status);
 }
 
 void helper_fsqrtq(CPUSPARCState *env)
 {
-    clear_float_exceptions(env);
     QT0 = float128_sqrt(QT1, &env->fp_status);
-    check_ieee_exceptions(env);
 }
 
 #define GEN_FCMP(name, size, reg1, reg2, FS, E)                         \
-    void glue(helper_, name) (CPUSPARCState *env)                       \
+    target_ulong glue(helper_, name) (CPUSPARCState *env)               \
     {                                                                   \
         int ret;                                                        \
-        clear_float_exceptions(env);                                    \
+        target_ulong fsr;                                               \
         if (E) {                                                        \
             ret = glue(size, _compare)(reg1, reg2, &env->fp_status);    \
         } else {                                                        \
             ret = glue(size, _compare_quiet)(reg1, reg2,                \
                                              &env->fp_status);          \
         }                                                               \
-        check_ieee_exceptions(env);                                     \
+        fsr = do_check_ieee_exceptions(env, GETPC());                   \
         switch (ret) {                                                  \
         case float_relation_unordered:                                  \
-            env->fsr |= (FSR_FCC1 | FSR_FCC0) << FS;                    \
-            env->fsr |= FSR_NVA;                                        \
+            fsr |= (FSR_FCC1 | FSR_FCC0) << FS;                         \
+            fsr |= FSR_NVA;                                             \
             break;                                                      \
         case float_relation_less:                                       \
-            env->fsr &= ~(FSR_FCC1) << FS;                              \
-            env->fsr |= FSR_FCC0 << FS;                                 \
+            fsr &= ~(FSR_FCC1) << FS;                                   \
+            fsr |= FSR_FCC0 << FS;                                      \
             break;                                                      \
         case float_relation_greater:                                    \
-            env->fsr &= ~(FSR_FCC0) << FS;                              \
-            env->fsr |= FSR_FCC1 << FS;                                 \
+            fsr &= ~(FSR_FCC0) << FS;                                   \
+            fsr |= FSR_FCC1 << FS;                                      \
             break;                                                      \
         default:                                                        \
-            env->fsr &= ~((FSR_FCC1 | FSR_FCC0) << FS);                 \
+            fsr &= ~((FSR_FCC1 | FSR_FCC0) << FS);                      \
             break;                                                      \
         }                                                               \
+        return fsr;                                                     \
     }
 #define GEN_FCMP_T(name, size, FS, E)                                   \
-    void glue(helper_, name)(CPUSPARCState *env, size src1, size src2)  \
+    target_ulong glue(helper_, name)(CPUSPARCState *env, size src1, size src2)\
     {                                                                   \
         int ret;                                                        \
-        clear_float_exceptions(env);                                    \
+        target_ulong fsr;                                               \
         if (E) {                                                        \
             ret = glue(size, _compare)(src1, src2, &env->fp_status);    \
         } else {                                                        \
             ret = glue(size, _compare_quiet)(src1, src2,                \
                                              &env->fp_status);          \
         }                                                               \
-        check_ieee_exceptions(env);                                     \
+        fsr = do_check_ieee_exceptions(env, GETPC());                   \
         switch (ret) {                                                  \
         case float_relation_unordered:                                  \
-            env->fsr |= (FSR_FCC1 | FSR_FCC0) << FS;                    \
+            fsr |= (FSR_FCC1 | FSR_FCC0) << FS;                         \
             break;                                                      \
         case float_relation_less:                                       \
-            env->fsr &= ~(FSR_FCC1 << FS);                              \
-            env->fsr |= FSR_FCC0 << FS;                                 \
+            fsr &= ~(FSR_FCC1 << FS);                                   \
+            fsr |= FSR_FCC0 << FS;                                      \
             break;                                                      \
         case float_relation_greater:                                    \
-            env->fsr &= ~(FSR_FCC0 << FS);                              \
-            env->fsr |= FSR_FCC1 << FS;                                 \
+            fsr &= ~(FSR_FCC0 << FS);                                   \
+            fsr |= FSR_FCC1 << FS;                                      \
             break;                                                      \
         default:                                                        \
-            env->fsr &= ~((FSR_FCC1 | FSR_FCC0) << FS);                 \
+            fsr &= ~((FSR_FCC1 | FSR_FCC0) << FS);                      \
             break;                                                      \
         }                                                               \
+        return fsr;                                                     \
     }
 
 GEN_FCMP_T(fcmps, float32, 0, 0);
@@ -431,11 +359,11 @@ GEN_FCMP(fcmpeq_fcc3, float128, QT0, QT1, 26, 1);
 #undef GEN_FCMP_T
 #undef GEN_FCMP
 
-static inline void set_fsr(CPUSPARCState *env)
+static void set_fsr(CPUSPARCState *env, target_ulong fsr)
 {
     int rnd_mode;
 
-    switch (env->fsr & FSR_RD_MASK) {
+    switch (fsr & FSR_RD_MASK) {
     case FSR_RD_NEAREST:
         rnd_mode = float_round_nearest_even;
         break;
@@ -453,16 +381,20 @@ static inline void set_fsr(CPUSPARCState *env)
     set_float_rounding_mode(rnd_mode, &env->fp_status);
 }
 
-void helper_ldfsr(CPUSPARCState *env, uint32_t new_fsr)
+target_ulong helper_ldfsr(CPUSPARCState *env, target_ulong old_fsr,
+                          uint32_t new_fsr)
 {
-    env->fsr = (new_fsr & FSR_LDFSR_MASK) | (env->fsr & FSR_LDFSR_OLDMASK);
-    set_fsr(env);
+    old_fsr = (new_fsr & FSR_LDFSR_MASK) | (old_fsr & FSR_LDFSR_OLDMASK);
+    set_fsr(env, old_fsr);
+    return old_fsr;
 }
 
 #ifdef TARGET_SPARC64
-void helper_ldxfsr(CPUSPARCState *env, uint64_t new_fsr)
+target_ulong helper_ldxfsr(CPUSPARCState *env, target_ulong old_fsr,
+                           uint64_t new_fsr)
 {
-    env->fsr = (new_fsr & FSR_LDXFSR_MASK) | (env->fsr & FSR_LDXFSR_OLDMASK);
-    set_fsr(env);
+    old_fsr = (new_fsr & FSR_LDXFSR_MASK) | (old_fsr & FSR_LDXFSR_OLDMASK);
+    set_fsr(env, old_fsr);
+    return old_fsr;
 }
 #endif
diff --git a/target-sparc/helper.h b/target-sparc/helper.h
index 4374f0dd23..caa2a895d0 100644
--- a/target-sparc/helper.h
+++ b/target-sparc/helper.h
@@ -4,34 +4,32 @@ DEF_HELPER_2(wrpsr, void, env, tl)
 DEF_HELPER_1(rdpsr, tl, env)
 DEF_HELPER_1(power_down, void, env)
 #else
-DEF_HELPER_2(wrpil, void, env, tl)
+DEF_HELPER_FLAGS_2(wrpil, TCG_CALL_NO_RWG, void, env, tl)
 DEF_HELPER_2(wrpstate, void, env, tl)
 DEF_HELPER_1(done, void, env)
 DEF_HELPER_1(retry, void, env)
-DEF_HELPER_1(flushw, void, env)
-DEF_HELPER_1(saved, void, env)
-DEF_HELPER_1(restored, void, env)
+DEF_HELPER_FLAGS_1(flushw, TCG_CALL_NO_WG, void, env)
+DEF_HELPER_FLAGS_1(saved, TCG_CALL_NO_RWG, void, env)
+DEF_HELPER_FLAGS_1(restored, TCG_CALL_NO_RWG, void, env)
 DEF_HELPER_1(rdccr, tl, env)
 DEF_HELPER_2(wrccr, void, env, tl)
 DEF_HELPER_1(rdcwp, tl, env)
 DEF_HELPER_2(wrcwp, void, env, tl)
 DEF_HELPER_FLAGS_2(array8, TCG_CALL_NO_RWG_SE, tl, tl, tl)
-DEF_HELPER_1(popc, tl, tl)
-DEF_HELPER_4(ldda_asi, void, env, tl, int, int)
-DEF_HELPER_5(ldf_asi, void, env, tl, int, int, int)
-DEF_HELPER_5(stf_asi, void, env, tl, int, int, int)
-DEF_HELPER_5(casx_asi, tl, env, tl, tl, tl, i32)
-DEF_HELPER_2(set_softint, void, env, i64)
-DEF_HELPER_2(clear_softint, void, env, i64)
-DEF_HELPER_2(write_softint, void, env, i64)
-DEF_HELPER_2(tick_set_count, void, ptr, i64)
-DEF_HELPER_3(tick_get_count, i64, env, ptr, int)
-DEF_HELPER_2(tick_set_limit, void, ptr, i64)
+DEF_HELPER_FLAGS_1(popc, TCG_CALL_NO_RWG_SE, tl, tl)
+DEF_HELPER_FLAGS_3(ldda_asi, TCG_CALL_NO_WG, void, env, tl, int)
+DEF_HELPER_FLAGS_5(casx_asi, TCG_CALL_NO_WG, tl, env, tl, tl, tl, i32)
+DEF_HELPER_FLAGS_2(set_softint, TCG_CALL_NO_RWG, void, env, i64)
+DEF_HELPER_FLAGS_2(clear_softint, TCG_CALL_NO_RWG, void, env, i64)
+DEF_HELPER_FLAGS_2(write_softint, TCG_CALL_NO_RWG, void, env, i64)
+DEF_HELPER_FLAGS_2(tick_set_count, TCG_CALL_NO_RWG, void, ptr, i64)
+DEF_HELPER_FLAGS_3(tick_get_count, TCG_CALL_NO_WG, i64, env, ptr, int)
+DEF_HELPER_FLAGS_2(tick_set_limit, TCG_CALL_NO_RWG, void, ptr, i64)
 #endif
 #if !defined(CONFIG_USER_ONLY) || defined(TARGET_SPARC64)
-DEF_HELPER_5(cas_asi, tl, env, tl, tl, tl, i32)
+DEF_HELPER_FLAGS_5(cas_asi, TCG_CALL_NO_WG, tl, env, tl, tl, tl, i32)
 #endif
-DEF_HELPER_3(check_align, void, env, tl, i32)
+DEF_HELPER_FLAGS_3(check_align, TCG_CALL_NO_WG, void, env, tl, i32)
 DEF_HELPER_1(debug, void, env)
 DEF_HELPER_1(save, void, env)
 DEF_HELPER_1(restore, void, env)
@@ -42,95 +40,97 @@ DEF_HELPER_3(sdiv_cc, tl, env, tl, tl)
 DEF_HELPER_3(taddcctv, tl, env, tl, tl)
 DEF_HELPER_3(tsubcctv, tl, env, tl, tl)
 #ifdef TARGET_SPARC64
-DEF_HELPER_3(sdivx, s64, env, s64, s64)
-DEF_HELPER_3(udivx, i64, env, i64, i64)
+DEF_HELPER_FLAGS_3(sdivx, TCG_CALL_NO_WG, s64, env, s64, s64)
+DEF_HELPER_FLAGS_3(udivx, TCG_CALL_NO_WG, i64, env, i64, i64)
 #endif
-DEF_HELPER_3(ldqf, void, env, tl, int)
-DEF_HELPER_3(stqf, void, env, tl, int)
+DEF_HELPER_FLAGS_3(ldqf, TCG_CALL_NO_WG, void, env, tl, int)
+DEF_HELPER_FLAGS_3(stqf, TCG_CALL_NO_WG, void, env, tl, int)
 #if !defined(CONFIG_USER_ONLY) || defined(TARGET_SPARC64)
-DEF_HELPER_5(ld_asi, i64, env, tl, int, int, int)
-DEF_HELPER_5(st_asi, void, env, tl, i64, int, int)
+DEF_HELPER_FLAGS_4(ld_asi, TCG_CALL_NO_WG, i64, env, tl, int, i32)
+DEF_HELPER_FLAGS_5(st_asi, TCG_CALL_NO_WG, void, env, tl, i64, int, i32)
 #endif
-DEF_HELPER_2(ldfsr, void, env, i32)
+DEF_HELPER_FLAGS_1(check_ieee_exceptions, TCG_CALL_NO_WG, tl, env)
+DEF_HELPER_FLAGS_3(ldfsr, TCG_CALL_NO_RWG, tl, env, tl, i32)
 DEF_HELPER_FLAGS_1(fabss, TCG_CALL_NO_RWG_SE, f32, f32)
-DEF_HELPER_2(fsqrts, f32, env, f32)
-DEF_HELPER_2(fsqrtd, f64, env, f64)
-DEF_HELPER_3(fcmps, void, env, f32, f32)
-DEF_HELPER_3(fcmpd, void, env, f64, f64)
-DEF_HELPER_3(fcmpes, void, env, f32, f32)
-DEF_HELPER_3(fcmped, void, env, f64, f64)
-DEF_HELPER_1(fsqrtq, void, env)
-DEF_HELPER_1(fcmpq, void, env)
-DEF_HELPER_1(fcmpeq, void, env)
+DEF_HELPER_FLAGS_2(fsqrts, TCG_CALL_NO_RWG, f32, env, f32)
+DEF_HELPER_FLAGS_2(fsqrtd, TCG_CALL_NO_RWG, f64, env, f64)
+DEF_HELPER_FLAGS_3(fcmps, TCG_CALL_NO_WG, tl, env, f32, f32)
+DEF_HELPER_FLAGS_3(fcmpd, TCG_CALL_NO_WG, tl, env, f64, f64)
+DEF_HELPER_FLAGS_3(fcmpes, TCG_CALL_NO_WG, tl, env, f32, f32)
+DEF_HELPER_FLAGS_3(fcmped, TCG_CALL_NO_WG, tl, env, f64, f64)
+DEF_HELPER_FLAGS_1(fsqrtq, TCG_CALL_NO_RWG, void, env)
+DEF_HELPER_FLAGS_1(fcmpq, TCG_CALL_NO_WG, tl, env)
+DEF_HELPER_FLAGS_1(fcmpeq, TCG_CALL_NO_WG, tl, env)
 #ifdef TARGET_SPARC64
-DEF_HELPER_2(ldxfsr, void, env, i64)
+DEF_HELPER_FLAGS_3(ldxfsr, TCG_CALL_NO_RWG, tl, env, tl, i64)
 DEF_HELPER_FLAGS_1(fabsd, TCG_CALL_NO_RWG_SE, f64, f64)
-DEF_HELPER_3(fcmps_fcc1, void, env, f32, f32)
-DEF_HELPER_3(fcmps_fcc2, void, env, f32, f32)
-DEF_HELPER_3(fcmps_fcc3, void, env, f32, f32)
-DEF_HELPER_3(fcmpd_fcc1, void, env, f64, f64)
-DEF_HELPER_3(fcmpd_fcc2, void, env, f64, f64)
-DEF_HELPER_3(fcmpd_fcc3, void, env, f64, f64)
-DEF_HELPER_3(fcmpes_fcc1, void, env, f32, f32)
-DEF_HELPER_3(fcmpes_fcc2, void, env, f32, f32)
-DEF_HELPER_3(fcmpes_fcc3, void, env, f32, f32)
-DEF_HELPER_3(fcmped_fcc1, void, env, f64, f64)
-DEF_HELPER_3(fcmped_fcc2, void, env, f64, f64)
-DEF_HELPER_3(fcmped_fcc3, void, env, f64, f64)
-DEF_HELPER_1(fabsq, void, env)
-DEF_HELPER_1(fcmpq_fcc1, void, env)
-DEF_HELPER_1(fcmpq_fcc2, void, env)
-DEF_HELPER_1(fcmpq_fcc3, void, env)
-DEF_HELPER_1(fcmpeq_fcc1, void, env)
-DEF_HELPER_1(fcmpeq_fcc2, void, env)
-DEF_HELPER_1(fcmpeq_fcc3, void, env)
+DEF_HELPER_FLAGS_3(fcmps_fcc1, TCG_CALL_NO_WG, tl, env, f32, f32)
+DEF_HELPER_FLAGS_3(fcmps_fcc2, TCG_CALL_NO_WG, tl, env, f32, f32)
+DEF_HELPER_FLAGS_3(fcmps_fcc3, TCG_CALL_NO_WG, tl, env, f32, f32)
+DEF_HELPER_FLAGS_3(fcmpd_fcc1, TCG_CALL_NO_WG, tl, env, f64, f64)
+DEF_HELPER_FLAGS_3(fcmpd_fcc2, TCG_CALL_NO_WG, tl, env, f64, f64)
+DEF_HELPER_FLAGS_3(fcmpd_fcc3, TCG_CALL_NO_WG, tl, env, f64, f64)
+DEF_HELPER_FLAGS_3(fcmpes_fcc1, TCG_CALL_NO_WG, tl, env, f32, f32)
+DEF_HELPER_FLAGS_3(fcmpes_fcc2, TCG_CALL_NO_WG, tl, env, f32, f32)
+DEF_HELPER_FLAGS_3(fcmpes_fcc3, TCG_CALL_NO_WG, tl, env, f32, f32)
+DEF_HELPER_FLAGS_3(fcmped_fcc1, TCG_CALL_NO_WG, tl, env, f64, f64)
+DEF_HELPER_FLAGS_3(fcmped_fcc2, TCG_CALL_NO_WG, tl, env, f64, f64)
+DEF_HELPER_FLAGS_3(fcmped_fcc3, TCG_CALL_NO_WG, tl, env, f64, f64)
+DEF_HELPER_FLAGS_1(fabsq, TCG_CALL_NO_RWG, void, env)
+DEF_HELPER_FLAGS_1(fcmpq_fcc1, TCG_CALL_NO_WG, tl, env)
+DEF_HELPER_FLAGS_1(fcmpq_fcc2, TCG_CALL_NO_WG, tl, env)
+DEF_HELPER_FLAGS_1(fcmpq_fcc3, TCG_CALL_NO_WG, tl, env)
+DEF_HELPER_FLAGS_1(fcmpeq_fcc1, TCG_CALL_NO_WG, tl, env)
+DEF_HELPER_FLAGS_1(fcmpeq_fcc2, TCG_CALL_NO_WG, tl, env)
+DEF_HELPER_FLAGS_1(fcmpeq_fcc3, TCG_CALL_NO_WG, tl, env)
 #endif
 DEF_HELPER_2(raise_exception, noreturn, env, int)
-#define F_HELPER_0_1(name) DEF_HELPER_1(f ## name, void, env)
+#define F_HELPER_0_1(name) \
+  DEF_HELPER_FLAGS_1(f ## name, TCG_CALL_NO_RWG, void, env)
 
-DEF_HELPER_3(faddd, f64, env, f64, f64)
-DEF_HELPER_3(fsubd, f64, env, f64, f64)
-DEF_HELPER_3(fmuld, f64, env, f64, f64)
-DEF_HELPER_3(fdivd, f64, env, f64, f64)
+DEF_HELPER_FLAGS_3(faddd, TCG_CALL_NO_RWG, f64, env, f64, f64)
+DEF_HELPER_FLAGS_3(fsubd, TCG_CALL_NO_RWG, f64, env, f64, f64)
+DEF_HELPER_FLAGS_3(fmuld, TCG_CALL_NO_RWG, f64, env, f64, f64)
+DEF_HELPER_FLAGS_3(fdivd, TCG_CALL_NO_RWG, f64, env, f64, f64)
 F_HELPER_0_1(addq)
 F_HELPER_0_1(subq)
 F_HELPER_0_1(mulq)
 F_HELPER_0_1(divq)
 
-DEF_HELPER_3(fadds, f32, env, f32, f32)
-DEF_HELPER_3(fsubs, f32, env, f32, f32)
-DEF_HELPER_3(fmuls, f32, env, f32, f32)
-DEF_HELPER_3(fdivs, f32, env, f32, f32)
+DEF_HELPER_FLAGS_3(fadds, TCG_CALL_NO_RWG, f32, env, f32, f32)
+DEF_HELPER_FLAGS_3(fsubs, TCG_CALL_NO_RWG, f32, env, f32, f32)
+DEF_HELPER_FLAGS_3(fmuls, TCG_CALL_NO_RWG, f32, env, f32, f32)
+DEF_HELPER_FLAGS_3(fdivs, TCG_CALL_NO_RWG, f32, env, f32, f32)
 
-DEF_HELPER_3(fsmuld, f64, env, f32, f32)
-DEF_HELPER_3(fdmulq, void, env, f64, f64)
+DEF_HELPER_FLAGS_3(fsmuld, TCG_CALL_NO_RWG, f64, env, f32, f32)
+DEF_HELPER_FLAGS_3(fdmulq, TCG_CALL_NO_RWG, void, env, f64, f64)
 
 DEF_HELPER_FLAGS_1(fnegs, TCG_CALL_NO_RWG_SE, f32, f32)
-DEF_HELPER_2(fitod, f64, env, s32)
-DEF_HELPER_2(fitoq, void, env, s32)
+DEF_HELPER_FLAGS_2(fitod, TCG_CALL_NO_RWG_SE, f64, env, s32)
+DEF_HELPER_FLAGS_2(fitoq, TCG_CALL_NO_RWG, void, env, s32)
 
-DEF_HELPER_2(fitos, f32, env, s32)
+DEF_HELPER_FLAGS_2(fitos, TCG_CALL_NO_RWG, f32, env, s32)
 
 #ifdef TARGET_SPARC64
 DEF_HELPER_FLAGS_1(fnegd, TCG_CALL_NO_RWG_SE, f64, f64)
-DEF_HELPER_1(fnegq, void, env)
-DEF_HELPER_2(fxtos, f32, env, s64)
-DEF_HELPER_2(fxtod, f64, env, s64)
-DEF_HELPER_2(fxtoq, void, env, s64)
+DEF_HELPER_FLAGS_1(fnegq, TCG_CALL_NO_RWG, void, env)
+DEF_HELPER_FLAGS_2(fxtos, TCG_CALL_NO_RWG, f32, env, s64)
+DEF_HELPER_FLAGS_2(fxtod, TCG_CALL_NO_RWG, f64, env, s64)
+DEF_HELPER_FLAGS_2(fxtoq, TCG_CALL_NO_RWG, void, env, s64)
 #endif
-DEF_HELPER_2(fdtos, f32, env, f64)
-DEF_HELPER_2(fstod, f64, env, f32)
-DEF_HELPER_1(fqtos, f32, env)
-DEF_HELPER_2(fstoq, void, env, f32)
-DEF_HELPER_1(fqtod, f64, env)
-DEF_HELPER_2(fdtoq, void, env, f64)
-DEF_HELPER_2(fstoi, s32, env, f32)
-DEF_HELPER_2(fdtoi, s32, env, f64)
-DEF_HELPER_1(fqtoi, s32, env)
+DEF_HELPER_FLAGS_2(fdtos, TCG_CALL_NO_RWG, f32, env, f64)
+DEF_HELPER_FLAGS_2(fstod, TCG_CALL_NO_RWG, f64, env, f32)
+DEF_HELPER_FLAGS_1(fqtos, TCG_CALL_NO_RWG, f32, env)
+DEF_HELPER_FLAGS_2(fstoq, TCG_CALL_NO_RWG, void, env, f32)
+DEF_HELPER_FLAGS_1(fqtod, TCG_CALL_NO_RWG, f64, env)
+DEF_HELPER_FLAGS_2(fdtoq, TCG_CALL_NO_RWG, void, env, f64)
+DEF_HELPER_FLAGS_2(fstoi, TCG_CALL_NO_RWG, s32, env, f32)
+DEF_HELPER_FLAGS_2(fdtoi, TCG_CALL_NO_RWG, s32, env, f64)
+DEF_HELPER_FLAGS_1(fqtoi, TCG_CALL_NO_RWG, s32, env)
 #ifdef TARGET_SPARC64
-DEF_HELPER_2(fstox, s64, env, f32)
-DEF_HELPER_2(fdtox, s64, env, f64)
-DEF_HELPER_1(fqtox, s64, env)
+DEF_HELPER_FLAGS_2(fstox, TCG_CALL_NO_RWG, s64, env, f32)
+DEF_HELPER_FLAGS_2(fdtox, TCG_CALL_NO_RWG, s64, env, f64)
+DEF_HELPER_FLAGS_1(fqtox, TCG_CALL_NO_RWG, s64, env)
 
 DEF_HELPER_FLAGS_2(fpmerge, TCG_CALL_NO_RWG_SE, i64, i64, i64)
 DEF_HELPER_FLAGS_2(fmul8x16, TCG_CALL_NO_RWG_SE, i64, i64, i64)
@@ -172,4 +172,4 @@ VIS_CMPHELPER(cmpne)
 #undef VIS_HELPER
 #undef VIS_CMPHELPER
 DEF_HELPER_1(compute_psr, void, env)
-DEF_HELPER_1(compute_C_icc, i32, env)
+DEF_HELPER_FLAGS_1(compute_C_icc, TCG_CALL_NO_WG_SE, i32, env)
diff --git a/target-sparc/ldst_helper.c b/target-sparc/ldst_helper.c
index f73cf6deaa..6ce5ccc37f 100644
--- a/target-sparc/ldst_helper.c
+++ b/target-sparc/ldst_helper.c
@@ -19,9 +19,11 @@
 
 #include "qemu/osdep.h"
 #include "cpu.h"
+#include "tcg.h"
 #include "exec/helper-proto.h"
 #include "exec/exec-all.h"
 #include "exec/cpu_ldst.h"
+#include "asi.h"
 
 //#define DEBUG_MMU
 //#define DEBUG_MXCC
@@ -427,9 +429,11 @@ static uint64_t leon3_cache_control_ld(CPUSPARCState *env, target_ulong addr,
     return ret;
 }
 
-uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
-                       int sign)
+uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr,
+                       int asi, uint32_t memop)
 {
+    int size = 1 << (memop & MO_SIZE);
+    int sign = memop & MO_SIGN;
     CPUState *cs = CPU(sparc_env_get_cpu(env));
     uint64_t ret = 0;
 #if defined(DEBUG_MXCC) || defined(DEBUG_ASI)
@@ -438,7 +442,8 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
 
     helper_check_align(env, addr, size - 1);
     switch (asi) {
-    case 2: /* SuperSparc MXCC registers and Leon3 cache control */
+    case ASI_M_MXCC: /* SuperSparc MXCC registers, or... */
+    /* case ASI_LEON_CACHEREGS:  Leon3 cache control */
         switch (addr) {
         case 0x00:          /* Leon3 Cache Control */
         case 0x08:          /* Leon3 Instruction Cache config */
@@ -497,8 +502,8 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
         dump_mxcc(env);
 #endif
         break;
-    case 3: /* MMU probe */
-    case 0x18: /* LEON3 MMU probe */
+    case ASI_M_FLUSH_PROBE: /* SuperSparc MMU probe */
+    case ASI_LEON_MMUFLUSH: /* LEON3 MMU probe */
         {
             int mmulev;
 
@@ -512,8 +517,8 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
                         addr, mmulev, ret);
         }
         break;
-    case 4: /* read MMU regs */
-    case 0x19: /* LEON3 read MMU regs */
+    case ASI_M_MMUREGS: /* SuperSparc MMU regs */
+    case ASI_LEON_MMUREGS: /* LEON3 MMU regs */
         {
             int reg = (addr >> 8) & 0x1f;
 
@@ -528,11 +533,11 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
             DPRINTF_MMU("mmu_read: reg[%d] = 0x%08" PRIx64 "\n", reg, ret);
         }
         break;
-    case 5: /* Turbosparc ITLB Diagnostic */
-    case 6: /* Turbosparc DTLB Diagnostic */
-    case 7: /* Turbosparc IOTLB Diagnostic */
+    case ASI_M_TLBDIAG: /* Turbosparc ITLB Diagnostic */
+    case ASI_M_DIAGS:   /* Turbosparc DTLB Diagnostic */
+    case ASI_M_IODIAG:  /* Turbosparc IOTLB Diagnostic */
         break;
-    case 9: /* Supervisor code access */
+    case ASI_KERNELTXT: /* Supervisor code access */
         switch (size) {
         case 1:
             ret = cpu_ldub_code(env, addr);
@@ -549,7 +554,7 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
             break;
         }
         break;
-    case 0xa: /* User data access */
+    case ASI_USERDATA: /* User data access */
         switch (size) {
         case 1:
             ret = cpu_ldub_user(env, addr);
@@ -566,8 +571,8 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
             break;
         }
         break;
-    case 0xb: /* Supervisor data access */
-    case 0x80:
+    case ASI_KERNELDATA: /* Supervisor data access */
+    case ASI_P: /* Implicit primary context data access (v9 only?) */
         switch (size) {
         case 1:
             ret = cpu_ldub_kernel(env, addr);
@@ -584,13 +589,13 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
             break;
         }
         break;
-    case 0xc: /* I-cache tag */
-    case 0xd: /* I-cache data */
-    case 0xe: /* D-cache tag */
-    case 0xf: /* D-cache data */
+    case ASI_M_TXTC_TAG:   /* SparcStation 5 I-cache tag */
+    case ASI_M_TXTC_DATA:  /* SparcStation 5 I-cache data */
+    case ASI_M_DATAC_TAG:  /* SparcStation 5 D-cache tag */
+    case ASI_M_DATAC_DATA: /* SparcStation 5 D-cache data */
         break;
-    case 0x20: /* MMU passthrough */
-    case 0x1c: /* LEON MMU passthrough */
+    case ASI_M_BYPASS:    /* MMU passthrough */
+    case ASI_LEON_BYPASS: /* LEON MMU passthrough */
         switch (size) {
         case 1:
             ret = ldub_phys(cs->as, addr);
@@ -669,7 +674,7 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
     case 0x4c: /* SuperSPARC MMU Breakpoint Action */
         ret = env->mmubpaction;
         break;
-    case 8: /* User code access, XXX */
+    case ASI_USERTXT: /* User code access, XXX */
     default:
         cpu_unassigned_access(cs, addr, false, false, asi, size);
         ret = 0;
@@ -696,15 +701,17 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
     return ret;
 }
 
-void helper_st_asi(CPUSPARCState *env, target_ulong addr, uint64_t val, int asi,
-                   int size)
+void helper_st_asi(CPUSPARCState *env, target_ulong addr, uint64_t val,
+                   int asi, uint32_t memop)
 {
+    int size = 1 << (memop & MO_SIZE);
     SPARCCPU *cpu = sparc_env_get_cpu(env);
     CPUState *cs = CPU(cpu);
 
     helper_check_align(env, addr, size - 1);
     switch (asi) {
-    case 2: /* SuperSparc MXCC registers and Leon3 cache control */
+    case ASI_M_MXCC: /* SuperSparc MXCC registers, or... */
+    /* case ASI_LEON_CACHEREGS:  Leon3 cache control */
         switch (addr) {
         case 0x00:          /* Leon3 Cache Control */
         case 0x08:          /* Leon3 Instruction Cache config */
@@ -838,8 +845,8 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, uint64_t val, int asi,
         dump_mxcc(env);
 #endif
         break;
-    case 3: /* MMU flush */
-    case 0x18: /* LEON3 MMU flush */
+    case ASI_M_FLUSH_PROBE: /* SuperSparc MMU flush */
+    case ASI_LEON_MMUFLUSH: /* LEON3 MMU flush */
         {
             int mmulev;
 
@@ -863,8 +870,8 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, uint64_t val, int asi,
 #endif
         }
         break;
-    case 4: /* write MMU regs */
-    case 0x19: /* LEON3 write MMU regs */
+    case ASI_M_MMUREGS: /* write MMU regs */
+    case ASI_LEON_MMUREGS: /* LEON3 write MMU regs */
         {
             int reg = (addr >> 8) & 0x1f;
             uint32_t oldreg;
@@ -918,11 +925,11 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, uint64_t val, int asi,
 #endif
         }
         break;
-    case 5: /* Turbosparc ITLB Diagnostic */
-    case 6: /* Turbosparc DTLB Diagnostic */
-    case 7: /* Turbosparc IOTLB Diagnostic */
+    case ASI_M_TLBDIAG: /* Turbosparc ITLB Diagnostic */
+    case ASI_M_DIAGS:   /* Turbosparc DTLB Diagnostic */
+    case ASI_M_IODIAG:  /* Turbosparc IOTLB Diagnostic */
         break;
-    case 0xa: /* User data access */
+    case ASI_USERDATA: /* User data access */
         switch (size) {
         case 1:
             cpu_stb_user(env, addr, val);
@@ -939,8 +946,8 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, uint64_t val, int asi,
             break;
         }
         break;
-    case 0xb: /* Supervisor data access */
-    case 0x80:
+    case ASI_KERNELDATA: /* Supervisor data access */
+    case ASI_P:
         switch (size) {
         case 1:
             cpu_stb_kernel(env, addr, val);
@@ -957,17 +964,17 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, uint64_t val, int asi,
             break;
         }
         break;
-    case 0xc: /* I-cache tag */
-    case 0xd: /* I-cache data */
-    case 0xe: /* D-cache tag */
-    case 0xf: /* D-cache data */
-    case 0x10: /* I/D-cache flush page */
-    case 0x11: /* I/D-cache flush segment */
-    case 0x12: /* I/D-cache flush region */
-    case 0x13: /* I/D-cache flush context */
-    case 0x14: /* I/D-cache flush user */
+    case ASI_M_TXTC_TAG:   /* I-cache tag */
+    case ASI_M_TXTC_DATA:  /* I-cache data */
+    case ASI_M_DATAC_TAG:  /* D-cache tag */
+    case ASI_M_DATAC_DATA: /* D-cache data */
+    case ASI_M_FLUSH_PAGE:   /* I/D-cache flush page */
+    case ASI_M_FLUSH_SEG:    /* I/D-cache flush segment */
+    case ASI_M_FLUSH_REGION: /* I/D-cache flush region */
+    case ASI_M_FLUSH_CTX:    /* I/D-cache flush context */
+    case ASI_M_FLUSH_USER:   /* I/D-cache flush user */
         break;
-    case 0x17: /* Block copy, sta access */
+    case ASI_M_BCOPY: /* Block copy, sta access */
         {
             /* val = src
                addr = dst
@@ -981,20 +988,20 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, uint64_t val, int asi,
             }
         }
         break;
-    case 0x1f: /* Block fill, stda access */
+    case ASI_M_BFILL: /* Block fill, stda access */
         {
             /* addr = dst
                fill 32 bytes with val */
             unsigned int i;
-            uint32_t dst = addr & 7;
+            uint32_t dst = addr & ~7;
 
             for (i = 0; i < 32; i += 8, dst += 8) {
                 cpu_stq_kernel(env, dst, val);
             }
         }
         break;
-    case 0x20: /* MMU passthrough */
-    case 0x1c: /* LEON MMU passthrough */
+    case ASI_M_BYPASS:    /* MMU passthrough */
+    case ASI_LEON_BYPASS: /* LEON MMU passthrough */
         {
             switch (size) {
             case 1:
@@ -1078,8 +1085,8 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, uint64_t val, int asi,
     case 0x4c: /* SuperSPARC MMU Breakpoint Action */
         env->mmubpaction = val & 0x1fff;
         break;
-    case 8: /* User code access, XXX */
-    case 9: /* Supervisor code access, XXX */
+    case ASI_USERTXT: /* User code access, XXX */
+    case ASI_KERNELTXT: /* Supervisor code access, XXX */
     default:
         cpu_unassigned_access(CPU(sparc_env_get_cpu(env)),
                               addr, true, false, asi, size);
@@ -1094,9 +1101,11 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, uint64_t val, int asi,
 #else /* TARGET_SPARC64 */
 
 #ifdef CONFIG_USER_ONLY
-uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
-                       int sign)
+uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr,
+                       int asi, uint32_t memop)
 {
+    int size = 1 << (memop & MO_SIZE);
+    int sign = memop & MO_SIGN;
     uint64_t ret = 0;
 #if defined(DEBUG_ASI)
     target_ulong last_addr = addr;
@@ -1110,8 +1119,8 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
     addr = asi_address_mask(env, asi, addr);
 
     switch (asi) {
-    case 0x82: /* Primary no-fault */
-    case 0x8a: /* Primary no-fault LE */
+    case ASI_PNF:  /* Primary no-fault */
+    case ASI_PNFL: /* Primary no-fault LE */
         if (page_check_range(addr, size, PAGE_READ) == -1) {
 #ifdef DEBUG_ASI
             dump_asi("read ", last_addr, asi, size, ret);
@@ -1119,8 +1128,8 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
             return 0;
         }
         /* Fall through */
-    case 0x80: /* Primary */
-    case 0x88: /* Primary LE */
+    case ASI_P: /* Primary */
+    case ASI_PL: /* Primary LE */
         {
             switch (size) {
             case 1:
@@ -1139,8 +1148,8 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
             }
         }
         break;
-    case 0x83: /* Secondary no-fault */
-    case 0x8b: /* Secondary no-fault LE */
+    case ASI_SNF:  /* Secondary no-fault */
+    case ASI_SNFL: /* Secondary no-fault LE */
         if (page_check_range(addr, size, PAGE_READ) == -1) {
 #ifdef DEBUG_ASI
             dump_asi("read ", last_addr, asi, size, ret);
@@ -1148,8 +1157,8 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
             return 0;
         }
         /* Fall through */
-    case 0x81: /* Secondary */
-    case 0x89: /* Secondary LE */
+    case ASI_S:  /* Secondary */
+    case ASI_SL: /* Secondary LE */
         /* XXX */
         break;
     default:
@@ -1158,10 +1167,10 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
 
     /* Convert from little endian */
     switch (asi) {
-    case 0x88: /* Primary LE */
-    case 0x89: /* Secondary LE */
-    case 0x8a: /* Primary no-fault LE */
-    case 0x8b: /* Secondary no-fault LE */
+    case ASI_PL:   /* Primary LE */
+    case ASI_SL:   /* Secondary LE */
+    case ASI_PNFL: /* Primary no-fault LE */
+    case ASI_SNFL: /* Secondary no-fault LE */
         switch (size) {
         case 2:
             ret = bswap16(ret);
@@ -1202,8 +1211,9 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
 }
 
 void helper_st_asi(CPUSPARCState *env, target_ulong addr, target_ulong val,
-                   int asi, int size)
+                   int asi, uint32_t memop)
 {
+    int size = 1 << (memop & MO_SIZE);
 #ifdef DEBUG_ASI
     dump_asi("write", addr, asi, size, val);
 #endif
@@ -1216,8 +1226,8 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, target_ulong val,
 
     /* Convert to little endian */
     switch (asi) {
-    case 0x88: /* Primary LE */
-    case 0x89: /* Secondary LE */
+    case ASI_PL: /* Primary LE */
+    case ASI_SL: /* Secondary LE */
         switch (size) {
         case 2:
             val = bswap16(val);
@@ -1236,8 +1246,8 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, target_ulong val,
     }
 
     switch (asi) {
-    case 0x80: /* Primary */
-    case 0x88: /* Primary LE */
+    case ASI_P:  /* Primary */
+    case ASI_PL: /* Primary LE */
         {
             switch (size) {
             case 1:
@@ -1256,15 +1266,15 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, target_ulong val,
             }
         }
         break;
-    case 0x81: /* Secondary */
-    case 0x89: /* Secondary LE */
+    case ASI_S:  /* Secondary */
+    case ASI_SL: /* Secondary LE */
         /* XXX */
         return;
 
-    case 0x82: /* Primary no-fault, RO */
-    case 0x83: /* Secondary no-fault, RO */
-    case 0x8a: /* Primary no-fault LE, RO */
-    case 0x8b: /* Secondary no-fault LE, RO */
+    case ASI_PNF:  /* Primary no-fault, RO */
+    case ASI_SNF:  /* Secondary no-fault, RO */
+    case ASI_PNFL: /* Primary no-fault LE, RO */
+    case ASI_SNFL: /* Secondary no-fault LE, RO */
     default:
         helper_raise_exception(env, TT_DATA_ACCESS);
         return;
@@ -1273,9 +1283,11 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, target_ulong val,
 
 #else /* CONFIG_USER_ONLY */
 
-uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
-                       int sign)
+uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr,
+                       int asi, uint32_t memop)
 {
+    int size = 1 << (memop & MO_SIZE);
+    int sign = memop & MO_SIGN;
     CPUState *cs = CPU(sparc_env_get_cpu(env));
     uint64_t ret = 0;
 #if defined(DEBUG_ASI)
@@ -1318,16 +1330,14 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
     }
 
     switch (asi) {
-    case 0x10: /* As if user primary */
-    case 0x11: /* As if user secondary */
-    case 0x18: /* As if user primary LE */
-    case 0x19: /* As if user secondary LE */
-    case 0x80: /* Primary */
-    case 0x81: /* Secondary */
-    case 0x88: /* Primary LE */
-    case 0x89: /* Secondary LE */
-    case 0xe2: /* UA2007 Primary block init */
-    case 0xe3: /* UA2007 Secondary block init */
+    case ASI_AIUP:  /* As if user primary */
+    case ASI_AIUS:  /* As if user secondary */
+    case ASI_AIUPL: /* As if user primary LE */
+    case ASI_AIUSL: /* As if user secondary LE */
+    case ASI_P:  /* Primary */
+    case ASI_S:  /* Secondary */
+    case ASI_PL: /* Primary LE */
+    case ASI_SL: /* Secondary LE */
         if ((asi & 0x80) && (env->pstate & PS_PRIV)) {
             if (cpu_hypervisor_mode(env)) {
                 switch (size) {
@@ -1418,10 +1428,10 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
             }
         }
         break;
-    case 0x14: /* Bypass */
-    case 0x15: /* Bypass, non-cacheable */
-    case 0x1c: /* Bypass LE */
-    case 0x1d: /* Bypass, non-cacheable LE */
+    case ASI_REAL:        /* Bypass */
+    case ASI_REAL_IO:   /* Bypass, non-cacheable */
+    case ASI_REAL_L:      /* Bypass LE */
+    case ASI_REAL_IO_L: /* Bypass, non-cacheable LE */
         {
             switch (size) {
             case 1:
@@ -1440,13 +1450,8 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
             }
             break;
         }
-    case 0x24: /* Nucleus quad LDD 128 bit atomic */
-    case 0x2c: /* Nucleus quad LDD 128 bit atomic LE
-                  Only ldda allowed */
-        helper_raise_exception(env, TT_ILL_INSN);
-        return 0;
-    case 0x04: /* Nucleus */
-    case 0x0c: /* Nucleus Little Endian (LE) */
+    case ASI_N:  /* Nucleus */
+    case ASI_NL: /* Nucleus Little Endian (LE) */
         {
             switch (size) {
             case 1:
@@ -1465,13 +1470,13 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
             }
             break;
         }
-    case 0x4a: /* UPA config */
+    case ASI_UPA_CONFIG: /* UPA config */
         /* XXX */
         break;
-    case 0x45: /* LSU */
+    case ASI_LSU_CONTROL: /* LSU */
         ret = env->lsu;
         break;
-    case 0x50: /* I-MMU regs */
+    case ASI_IMMU: /* I-MMU regs */
         {
             int reg = (addr >> 3) & 0xf;
 
@@ -1484,7 +1489,7 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
 
             break;
         }
-    case 0x51: /* I-MMU 8k TSB pointer */
+    case ASI_IMMU_TSB_8KB_PTR: /* I-MMU 8k TSB pointer */
         {
             /* env->immuregs[5] holds I-MMU TSB register value
                env->immuregs[6] holds I-MMU Tag Access register value */
@@ -1492,7 +1497,7 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
                                          8*1024);
             break;
         }
-    case 0x52: /* I-MMU 64k TSB pointer */
+    case ASI_IMMU_TSB_64KB_PTR: /* I-MMU 64k TSB pointer */
         {
             /* env->immuregs[5] holds I-MMU TSB register value
                env->immuregs[6] holds I-MMU Tag Access register value */
@@ -1500,21 +1505,21 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
                                          64*1024);
             break;
         }
-    case 0x55: /* I-MMU data access */
+    case ASI_ITLB_DATA_ACCESS: /* I-MMU data access */
         {
             int reg = (addr >> 3) & 0x3f;
 
             ret = env->itlb[reg].tte;
             break;
         }
-    case 0x56: /* I-MMU tag read */
+    case ASI_ITLB_TAG_READ: /* I-MMU tag read */
         {
             int reg = (addr >> 3) & 0x3f;
 
             ret = env->itlb[reg].tag;
             break;
         }
-    case 0x58: /* D-MMU regs */
+    case ASI_DMMU: /* D-MMU regs */
         {
             int reg = (addr >> 3) & 0xf;
 
@@ -1526,7 +1531,7 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
             }
             break;
         }
-    case 0x59: /* D-MMU 8k TSB pointer */
+    case ASI_DMMU_TSB_8KB_PTR: /* D-MMU 8k TSB pointer */
         {
             /* env->dmmuregs[5] holds D-MMU TSB register value
                env->dmmuregs[6] holds D-MMU Tag Access register value */
@@ -1534,7 +1539,7 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
                                          8*1024);
             break;
         }
-    case 0x5a: /* D-MMU 64k TSB pointer */
+    case ASI_DMMU_TSB_64KB_PTR: /* D-MMU 64k TSB pointer */
         {
             /* env->dmmuregs[5] holds D-MMU TSB register value
                env->dmmuregs[6] holds D-MMU Tag Access register value */
@@ -1542,26 +1547,26 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
                                          64*1024);
             break;
         }
-    case 0x5d: /* D-MMU data access */
+    case ASI_DTLB_DATA_ACCESS: /* D-MMU data access */
         {
             int reg = (addr >> 3) & 0x3f;
 
             ret = env->dtlb[reg].tte;
             break;
         }
-    case 0x5e: /* D-MMU tag read */
+    case ASI_DTLB_TAG_READ: /* D-MMU tag read */
         {
             int reg = (addr >> 3) & 0x3f;
 
             ret = env->dtlb[reg].tag;
             break;
         }
-    case 0x48: /* Interrupt dispatch, RO */
+    case ASI_INTR_DISPATCH_STAT: /* Interrupt dispatch, RO */
         break;
-    case 0x49: /* Interrupt data receive */
+    case ASI_INTR_RECEIVE: /* Interrupt data receive */
         ret = env->ivec_status;
         break;
-    case 0x7f: /* Incoming interrupt vector, RO */
+    case ASI_INTR_R: /* Incoming interrupt vector, RO */
         {
             int reg = (addr >> 4) & 0x3;
             if (reg < 3) {
@@ -1569,40 +1574,59 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
             }
             break;
         }
-    case 0x46: /* D-cache data */
-    case 0x47: /* D-cache tag access */
-    case 0x4b: /* E-cache error enable */
-    case 0x4c: /* E-cache asynchronous fault status */
-    case 0x4d: /* E-cache asynchronous fault address */
-    case 0x4e: /* E-cache tag data */
-    case 0x66: /* I-cache instruction access */
-    case 0x67: /* I-cache tag access */
-    case 0x6e: /* I-cache predecode */
-    case 0x6f: /* I-cache LRU etc. */
-    case 0x76: /* E-cache tag */
-    case 0x7e: /* E-cache tag */
-        break;
-    case 0x5b: /* D-MMU data pointer */
-    case 0x54: /* I-MMU data in, WO */
-    case 0x57: /* I-MMU demap, WO */
-    case 0x5c: /* D-MMU data in, WO */
-    case 0x5f: /* D-MMU demap, WO */
-    case 0x77: /* Interrupt vector, WO */
+    case ASI_DCACHE_DATA:     /* D-cache data */
+    case ASI_DCACHE_TAG:      /* D-cache tag access */
+    case ASI_ESTATE_ERROR_EN: /* E-cache error enable */
+    case ASI_AFSR:            /* E-cache asynchronous fault status */
+    case ASI_AFAR:            /* E-cache asynchronous fault address */
+    case ASI_EC_TAG_DATA:     /* E-cache tag data */
+    case ASI_IC_INSTR:        /* I-cache instruction access */
+    case ASI_IC_TAG:          /* I-cache tag access */
+    case ASI_IC_PRE_DECODE:   /* I-cache predecode */
+    case ASI_IC_NEXT_FIELD:   /* I-cache LRU etc. */
+    case ASI_EC_W:            /* E-cache tag */
+    case ASI_EC_R:            /* E-cache tag */
+        break;
+    case ASI_DMMU_TSB_DIRECT_PTR: /* D-MMU data pointer */
+    case ASI_ITLB_DATA_IN:        /* I-MMU data in, WO */
+    case ASI_IMMU_DEMAP:          /* I-MMU demap, WO */
+    case ASI_DTLB_DATA_IN:        /* D-MMU data in, WO */
+    case ASI_DMMU_DEMAP:          /* D-MMU demap, WO */
+    case ASI_INTR_W:              /* Interrupt vector, WO */
     default:
         cpu_unassigned_access(cs, addr, false, false, 1, size);
         ret = 0;
         break;
+
+    case ASI_NUCLEUS_QUAD_LDD:   /* Nucleus quad LDD 128 bit atomic */
+    case ASI_NUCLEUS_QUAD_LDD_L: /* Nucleus quad LDD 128 bit atomic LE */
+    case ASI_TWINX_AIUP:   /* As if user primary, twinx */
+    case ASI_TWINX_AIUS:   /* As if user secondary, twinx */
+    case ASI_TWINX_REAL:   /* Real address, twinx */
+    case ASI_TWINX_AIUP_L: /* As if user primary, twinx, LE */
+    case ASI_TWINX_AIUS_L: /* As if user secondary, twinx, LE */
+    case ASI_TWINX_REAL_L: /* Real address, twinx, LE */
+    case ASI_TWINX_N:  /* Nucleus, twinx */
+    case ASI_TWINX_NL: /* Nucleus, twinx, LE */
+    /* ??? From the UA2011 document; overlaps BLK_INIT_QUAD_LDD_* */
+    case ASI_TWINX_P:  /* Primary, twinx */
+    case ASI_TWINX_PL: /* Primary, twinx, LE */
+    case ASI_TWINX_S:  /* Secondary, twinx */
+    case ASI_TWINX_SL: /* Secondary, twinx, LE */
+        /* These are all 128-bit atomic; only ldda (now ldtxa) allowed */
+        helper_raise_exception(env, TT_ILL_INSN);
+        return 0;
     }
 
     /* Convert from little endian */
     switch (asi) {
-    case 0x0c: /* Nucleus Little Endian (LE) */
-    case 0x18: /* As if user primary LE */
-    case 0x19: /* As if user secondary LE */
-    case 0x1c: /* Bypass LE */
-    case 0x1d: /* Bypass, non-cacheable LE */
-    case 0x88: /* Primary LE */
-    case 0x89: /* Secondary LE */
+    case ASI_NL: /* Nucleus Little Endian (LE) */
+    case ASI_AIUPL: /* As if user primary LE */
+    case ASI_AIUSL: /* As if user secondary LE */
+    case ASI_REAL_L:      /* Bypass LE */
+    case ASI_REAL_IO_L: /* Bypass, non-cacheable LE */
+    case ASI_PL: /* Primary LE */
+    case ASI_SL: /* Secondary LE */
         switch(size) {
         case 2:
             ret = bswap16(ret);
@@ -1643,8 +1667,9 @@ uint64_t helper_ld_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
 }
 
 void helper_st_asi(CPUSPARCState *env, target_ulong addr, target_ulong val,
-                   int asi, int size)
+                   int asi, uint32_t memop)
 {
+    int size = 1 << (memop & MO_SIZE);
     SPARCCPU *cpu = sparc_env_get_cpu(env);
     CPUState *cs = CPU(cpu);
 
@@ -1666,13 +1691,13 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, target_ulong val,
 
     /* Convert to little endian */
     switch (asi) {
-    case 0x0c: /* Nucleus Little Endian (LE) */
-    case 0x18: /* As if user primary LE */
-    case 0x19: /* As if user secondary LE */
-    case 0x1c: /* Bypass LE */
-    case 0x1d: /* Bypass, non-cacheable LE */
-    case 0x88: /* Primary LE */
-    case 0x89: /* Secondary LE */
+    case ASI_NL: /* Nucleus Little Endian (LE) */
+    case ASI_AIUPL: /* As if user primary LE */
+    case ASI_AIUSL: /* As if user secondary LE */
+    case ASI_REAL_L: /* Bypass LE */
+    case ASI_REAL_IO_L: /* Bypass, non-cacheable LE */
+    case ASI_PL: /* Primary LE */
+    case ASI_SL: /* Secondary LE */
         switch (size) {
         case 2:
             val = bswap16(val);
@@ -1691,16 +1716,14 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, target_ulong val,
     }
 
     switch (asi) {
-    case 0x10: /* As if user primary */
-    case 0x11: /* As if user secondary */
-    case 0x18: /* As if user primary LE */
-    case 0x19: /* As if user secondary LE */
-    case 0x80: /* Primary */
-    case 0x81: /* Secondary */
-    case 0x88: /* Primary LE */
-    case 0x89: /* Secondary LE */
-    case 0xe2: /* UA2007 Primary block init */
-    case 0xe3: /* UA2007 Secondary block init */
+    case ASI_AIUP:  /* As if user primary */
+    case ASI_AIUS:  /* As if user secondary */
+    case ASI_AIUPL: /* As if user primary LE */
+    case ASI_AIUSL: /* As if user secondary LE */
+    case ASI_P:  /* Primary */
+    case ASI_S:  /* Secondary */
+    case ASI_PL: /* Primary LE */
+    case ASI_SL: /* Secondary LE */
         if ((asi & 0x80) && (env->pstate & PS_PRIV)) {
             if (cpu_hypervisor_mode(env)) {
                 switch (size) {
@@ -1791,10 +1814,10 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, target_ulong val,
             }
         }
         break;
-    case 0x14: /* Bypass */
-    case 0x15: /* Bypass, non-cacheable */
-    case 0x1c: /* Bypass LE */
-    case 0x1d: /* Bypass, non-cacheable LE */
+    case ASI_REAL:      /* Bypass */
+    case ASI_REAL_IO:   /* Bypass, non-cacheable */
+    case ASI_REAL_L:    /* Bypass LE */
+    case ASI_REAL_IO_L: /* Bypass, non-cacheable LE */
         {
             switch (size) {
             case 1:
@@ -1813,13 +1836,8 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, target_ulong val,
             }
         }
         return;
-    case 0x24: /* Nucleus quad LDD 128 bit atomic */
-    case 0x2c: /* Nucleus quad LDD 128 bit atomic LE
-                  Only ldda allowed */
-        helper_raise_exception(env, TT_ILL_INSN);
-        return;
-    case 0x04: /* Nucleus */
-    case 0x0c: /* Nucleus Little Endian (LE) */
+    case ASI_N:  /* Nucleus */
+    case ASI_NL: /* Nucleus Little Endian (LE) */
         {
             switch (size) {
             case 1:
@@ -1839,10 +1857,10 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, target_ulong val,
             break;
         }
 
-    case 0x4a: /* UPA config */
+    case ASI_UPA_CONFIG: /* UPA config */
         /* XXX */
         return;
-    case 0x45: /* LSU */
+    case ASI_LSU_CONTROL: /* LSU */
         {
             uint64_t oldreg;
 
@@ -1860,7 +1878,7 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, target_ulong val,
             }
             return;
         }
-    case 0x50: /* I-MMU regs */
+    case ASI_IMMU: /* I-MMU regs */
         {
             int reg = (addr >> 3) & 0xf;
             uint64_t oldreg;
@@ -1904,10 +1922,10 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, target_ulong val,
 #endif
             return;
         }
-    case 0x54: /* I-MMU data in */
+    case ASI_ITLB_DATA_IN: /* I-MMU data in */
         replace_tlb_1bit_lru(env->itlb, env->immu.tag_access, val, "immu", env);
         return;
-    case 0x55: /* I-MMU data access */
+    case ASI_ITLB_DATA_ACCESS: /* I-MMU data access */
         {
             /* TODO: auto demap */
 
@@ -1921,10 +1939,10 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, target_ulong val,
 #endif
             return;
         }
-    case 0x57: /* I-MMU demap */
+    case ASI_IMMU_DEMAP: /* I-MMU demap */
         demap_tlb(env->itlb, addr, "immu", env);
         return;
-    case 0x58: /* D-MMU regs */
+    case ASI_DMMU: /* D-MMU regs */
         {
             int reg = (addr >> 3) & 0xf;
             uint64_t oldreg;
@@ -1977,10 +1995,10 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, target_ulong val,
 #endif
             return;
         }
-    case 0x5c: /* D-MMU data in */
+    case ASI_DTLB_DATA_IN: /* D-MMU data in */
         replace_tlb_1bit_lru(env->dtlb, env->dmmu.tag_access, val, "dmmu", env);
         return;
-    case 0x5d: /* D-MMU data access */
+    case ASI_DTLB_DATA_ACCESS: /* D-MMU data access */
         {
             unsigned int i = (addr >> 3) & 0x3f;
 
@@ -1992,38 +2010,56 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, target_ulong val,
 #endif
             return;
         }
-    case 0x5f: /* D-MMU demap */
+    case ASI_DMMU_DEMAP: /* D-MMU demap */
         demap_tlb(env->dtlb, addr, "dmmu", env);
         return;
-    case 0x49: /* Interrupt data receive */
+    case ASI_INTR_RECEIVE: /* Interrupt data receive */
         env->ivec_status = val & 0x20;
         return;
-    case 0x46: /* D-cache data */
-    case 0x47: /* D-cache tag access */
-    case 0x4b: /* E-cache error enable */
-    case 0x4c: /* E-cache asynchronous fault status */
-    case 0x4d: /* E-cache asynchronous fault address */
-    case 0x4e: /* E-cache tag data */
-    case 0x66: /* I-cache instruction access */
-    case 0x67: /* I-cache tag access */
-    case 0x6e: /* I-cache predecode */
-    case 0x6f: /* I-cache LRU etc. */
-    case 0x76: /* E-cache tag */
-    case 0x7e: /* E-cache tag */
+    case ASI_NUCLEUS_QUAD_LDD:   /* Nucleus quad LDD 128 bit atomic */
+    case ASI_NUCLEUS_QUAD_LDD_L: /* Nucleus quad LDD 128 bit atomic LE */
+    case ASI_TWINX_AIUP:   /* As if user primary, twinx */
+    case ASI_TWINX_AIUS:   /* As if user secondary, twinx */
+    case ASI_TWINX_REAL:   /* Real address, twinx */
+    case ASI_TWINX_AIUP_L: /* As if user primary, twinx, LE */
+    case ASI_TWINX_AIUS_L: /* As if user secondary, twinx, LE */
+    case ASI_TWINX_REAL_L: /* Real address, twinx, LE */
+    case ASI_TWINX_N:  /* Nucleus, twinx */
+    case ASI_TWINX_NL: /* Nucleus, twinx, LE */
+    /* ??? From the UA2011 document; overlaps BLK_INIT_QUAD_LDD_* */
+    case ASI_TWINX_P:  /* Primary, twinx */
+    case ASI_TWINX_PL: /* Primary, twinx, LE */
+    case ASI_TWINX_S:  /* Secondary, twinx */
+    case ASI_TWINX_SL: /* Secondary, twinx, LE */
+        /* Only stda allowed */
+        helper_raise_exception(env, TT_ILL_INSN);
+        return;
+    case ASI_DCACHE_DATA: /* D-cache data */
+    case ASI_DCACHE_TAG: /* D-cache tag access */
+    case ASI_ESTATE_ERROR_EN: /* E-cache error enable */
+    case ASI_AFSR: /* E-cache asynchronous fault status */
+    case ASI_AFAR: /* E-cache asynchronous fault address */
+    case ASI_EC_TAG_DATA: /* E-cache tag data */
+    case ASI_IC_INSTR: /* I-cache instruction access */
+    case ASI_IC_TAG: /* I-cache tag access */
+    case ASI_IC_PRE_DECODE: /* I-cache predecode */
+    case ASI_IC_NEXT_FIELD: /* I-cache LRU etc. */
+    case ASI_EC_W: /* E-cache tag */
+    case ASI_EC_R: /* E-cache tag */
         return;
-    case 0x51: /* I-MMU 8k TSB pointer, RO */
-    case 0x52: /* I-MMU 64k TSB pointer, RO */
-    case 0x56: /* I-MMU tag read, RO */
-    case 0x59: /* D-MMU 8k TSB pointer, RO */
-    case 0x5a: /* D-MMU 64k TSB pointer, RO */
-    case 0x5b: /* D-MMU data pointer, RO */
-    case 0x5e: /* D-MMU tag read, RO */
-    case 0x48: /* Interrupt dispatch, RO */
-    case 0x7f: /* Incoming interrupt vector, RO */
-    case 0x82: /* Primary no-fault, RO */
-    case 0x83: /* Secondary no-fault, RO */
-    case 0x8a: /* Primary no-fault LE, RO */
-    case 0x8b: /* Secondary no-fault LE, RO */
+    case ASI_IMMU_TSB_8KB_PTR: /* I-MMU 8k TSB pointer, RO */
+    case ASI_IMMU_TSB_64KB_PTR: /* I-MMU 64k TSB pointer, RO */
+    case ASI_ITLB_TAG_READ: /* I-MMU tag read, RO */
+    case ASI_DMMU_TSB_8KB_PTR: /* D-MMU 8k TSB pointer, RO */
+    case ASI_DMMU_TSB_64KB_PTR: /* D-MMU 64k TSB pointer, RO */
+    case ASI_DMMU_TSB_DIRECT_PTR: /* D-MMU data pointer, RO */
+    case ASI_DTLB_TAG_READ: /* D-MMU tag read, RO */
+    case ASI_INTR_DISPATCH_STAT: /* Interrupt dispatch, RO */
+    case ASI_INTR_R: /* Incoming interrupt vector, RO */
+    case ASI_PNF: /* Primary no-fault, RO */
+    case ASI_SNF: /* Secondary no-fault, RO */
+    case ASI_PNFL: /* Primary no-fault LE, RO */
+    case ASI_SNFL: /* Secondary no-fault LE, RO */
     default:
         cpu_unassigned_access(cs, addr, true, false, 1, size);
         return;
@@ -2031,8 +2067,11 @@ void helper_st_asi(CPUSPARCState *env, target_ulong addr, target_ulong val,
 }
 #endif /* CONFIG_USER_ONLY */
 
-void helper_ldda_asi(CPUSPARCState *env, target_ulong addr, int asi, int rd)
+/* 128-bit LDDA; result returned in QT0.  */
+void helper_ldda_asi(CPUSPARCState *env, target_ulong addr, int asi)
 {
+    uint64_t h, l;
+
     if ((asi < 0x80 && (env->pstate & PS_PRIV) == 0)
         || (cpu_has_hypervisor(env)
             && asi >= 0x30 && asi < 0x80
@@ -2044,191 +2083,82 @@ void helper_ldda_asi(CPUSPARCState *env, target_ulong addr, int asi, int rd)
 
     switch (asi) {
 #if !defined(CONFIG_USER_ONLY)
-    case 0x24: /* Nucleus quad LDD 128 bit atomic */
-    case 0x2c: /* Nucleus quad LDD 128 bit atomic LE */
+    case ASI_TWINX_AIUP:   /* As if user primary, twinx */
+    case ASI_TWINX_AIUP_L: /* As if user primary, twinx, LE */
         helper_check_align(env, addr, 0xf);
-        if (rd == 0) {
-            env->gregs[1] = cpu_ldq_nucleus(env, addr + 8);
-            if (asi == 0x2c) {
-                bswap64s(&env->gregs[1]);
-            }
-        } else if (rd < 8) {
-            env->gregs[rd] = cpu_ldq_nucleus(env, addr);
-            env->gregs[rd + 1] = cpu_ldq_nucleus(env, addr + 8);
-            if (asi == 0x2c) {
-                bswap64s(&env->gregs[rd]);
-                bswap64s(&env->gregs[rd + 1]);
-            }
-        } else {
-            env->regwptr[rd - 8] = cpu_ldq_nucleus(env, addr);
-            env->regwptr[rd + 1 - 8] = cpu_ldq_nucleus(env, addr + 8);
-            if (asi == 0x2c) {
-                bswap64s(&env->regwptr[rd - 8]);
-                bswap64s(&env->regwptr[rd + 1 - 8]);
-            }
-        }
+        h = cpu_ldq_user(env, addr);
+        l = cpu_ldq_user(env, addr + 8);
         break;
-#endif
-    default:
-        helper_check_align(env, addr, 0x3);
-        if (rd == 0) {
-            env->gregs[1] = helper_ld_asi(env, addr + 4, asi, 4, 0);
-        } else if (rd < 8) {
-            env->gregs[rd] = helper_ld_asi(env, addr, asi, 4, 0);
-            env->gregs[rd + 1] = helper_ld_asi(env, addr + 4, asi, 4, 0);
-        } else {
-            env->regwptr[rd - 8] = helper_ld_asi(env, addr, asi, 4, 0);
-            env->regwptr[rd + 1 - 8] = helper_ld_asi(env, addr + 4, asi, 4, 0);
-        }
+    case ASI_TWINX_AIUS:   /* As if user secondary, twinx */
+    case ASI_TWINX_AIUS_L: /* As if user secondary, twinx, LE */
+        helper_check_align(env, addr, 0xf);
+        h = cpu_ldq_user_secondary(env, addr);
+        l = cpu_ldq_user_secondary(env, addr + 8);
         break;
-    }
-}
-
-void helper_ldf_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
-                    int rd)
-{
-    unsigned int i;
-    target_ulong val;
-
-    helper_check_align(env, addr, 3);
-    addr = asi_address_mask(env, asi, addr);
-
-    switch (asi) {
-    case 0xf0: /* UA2007/JPS1 Block load primary */
-    case 0xf1: /* UA2007/JPS1 Block load secondary */
-    case 0xf8: /* UA2007/JPS1 Block load primary LE */
-    case 0xf9: /* UA2007/JPS1 Block load secondary LE */
-        if (rd & 7) {
-            helper_raise_exception(env, TT_ILL_INSN);
-            return;
-        }
-        helper_check_align(env, addr, 0x3f);
-        for (i = 0; i < 8; i++, rd += 2, addr += 8) {
-            env->fpr[rd / 2].ll = helper_ld_asi(env, addr, asi & 0x8f, 8, 0);
-        }
-        return;
-
-    case 0x16: /* UA2007 Block load primary, user privilege */
-    case 0x17: /* UA2007 Block load secondary, user privilege */
-    case 0x1e: /* UA2007 Block load primary LE, user privilege */
-    case 0x1f: /* UA2007 Block load secondary LE, user privilege */
-    case 0x70: /* JPS1 Block load primary, user privilege */
-    case 0x71: /* JPS1 Block load secondary, user privilege */
-    case 0x78: /* JPS1 Block load primary LE, user privilege */
-    case 0x79: /* JPS1 Block load secondary LE, user privilege */
-        if (rd & 7) {
-            helper_raise_exception(env, TT_ILL_INSN);
-            return;
-        }
-        helper_check_align(env, addr, 0x3f);
-        for (i = 0; i < 8; i++, rd += 2, addr += 8) {
-            env->fpr[rd / 2].ll = helper_ld_asi(env, addr, asi & 0x19, 8, 0);
+    case ASI_TWINX_REAL:   /* Real address, twinx */
+    case ASI_TWINX_REAL_L: /* Real address, twinx, LE */
+        helper_check_align(env, addr, 0xf);
+        {
+            CPUState *cs = CPU(sparc_env_get_cpu(env));
+            h = ldq_phys(cs->as, addr);
+            l = ldq_phys(cs->as, addr + 8);
         }
-        return;
-
-    default:
         break;
-    }
-
-    switch (size) {
-    default:
-    case 4:
-        val = helper_ld_asi(env, addr, asi, size, 0);
-        if (rd & 1) {
-            env->fpr[rd / 2].l.lower = val;
-        } else {
-            env->fpr[rd / 2].l.upper = val;
+    case ASI_NUCLEUS_QUAD_LDD:
+    case ASI_NUCLEUS_QUAD_LDD_L:
+    case ASI_TWINX_N:  /* Nucleus, twinx */
+    case ASI_TWINX_NL: /* Nucleus, twinx, LE */
+        helper_check_align(env, addr, 0xf);
+        h = cpu_ldq_nucleus(env, addr);
+        l = cpu_ldq_nucleus(env, addr + 8);
+        break;
+    case ASI_TWINX_S: /* Secondary, twinx */
+    case ASI_TWINX_SL: /* Secondary, twinx, LE */
+        if (!cpu_hypervisor_mode(env)) {
+            helper_check_align(env, addr, 0xf);
+            if (env->pstate & PS_PRIV) {
+                h = cpu_ldq_kernel_secondary(env, addr);
+                l = cpu_ldq_kernel_secondary(env, addr + 8);
+            } else {
+                h = cpu_ldq_user_secondary(env, addr);
+                l = cpu_ldq_user_secondary(env, addr + 8);
+            }
+            break;
         }
+        /* fallthru */
+    case ASI_TWINX_P:  /* Primary, twinx */
+    case ASI_TWINX_PL: /* Primary, twinx, LE */
+        helper_check_align(env, addr, 0xf);
+        h = cpu_ldq_data(env, addr);
+        l = cpu_ldq_data(env, addr + 8);
         break;
-    case 8:
-        env->fpr[rd / 2].ll = helper_ld_asi(env, addr, asi, size, 0);
-        break;
-    case 16:
-        env->fpr[rd / 2].ll = helper_ld_asi(env, addr, asi, 8, 0);
-        env->fpr[rd / 2 + 1].ll = helper_ld_asi(env, addr + 8, asi, 8, 0);
-        break;
-    }
-}
-
-void helper_stf_asi(CPUSPARCState *env, target_ulong addr, int asi, int size,
-                    int rd)
-{
-    unsigned int i;
-    target_ulong val;
-
-    addr = asi_address_mask(env, asi, addr);
-
-    switch (asi) {
-    case 0xe0: /* UA2007/JPS1 Block commit store primary (cache flush) */
-    case 0xe1: /* UA2007/JPS1 Block commit store secondary (cache flush) */
-    case 0xf0: /* UA2007/JPS1 Block store primary */
-    case 0xf1: /* UA2007/JPS1 Block store secondary */
-    case 0xf8: /* UA2007/JPS1 Block store primary LE */
-    case 0xf9: /* UA2007/JPS1 Block store secondary LE */
-        if (rd & 7) {
-            helper_raise_exception(env, TT_ILL_INSN);
-            return;
-        }
-        helper_check_align(env, addr, 0x3f);
-        for (i = 0; i < 8; i++, rd += 2, addr += 8) {
-            helper_st_asi(env, addr, env->fpr[rd / 2].ll, asi & 0x8f, 8);
-        }
-
-        return;
-    case 0x16: /* UA2007 Block load primary, user privilege */
-    case 0x17: /* UA2007 Block load secondary, user privilege */
-    case 0x1e: /* UA2007 Block load primary LE, user privilege */
-    case 0x1f: /* UA2007 Block load secondary LE, user privilege */
-    case 0x70: /* JPS1 Block store primary, user privilege */
-    case 0x71: /* JPS1 Block store secondary, user privilege */
-    case 0x78: /* JPS1 Block load primary LE, user privilege */
-    case 0x79: /* JPS1 Block load secondary LE, user privilege */
-        if (rd & 7) {
-            helper_raise_exception(env, TT_ILL_INSN);
-            return;
-        }
-        helper_check_align(env, addr, 0x3f);
-        for (i = 0; i < 8; i++, rd += 2, addr += 8) {
-            helper_st_asi(env, addr, env->fpr[rd / 2].ll, asi & 0x19, 8);
-        }
-
-        return;
-    case 0xd2: /* 16-bit floating point load primary */
-    case 0xd3: /* 16-bit floating point load secondary */
-    case 0xda: /* 16-bit floating point load primary, LE */
-    case 0xdb: /* 16-bit floating point load secondary, LE */
-        helper_check_align(env, addr, 1);
-        /* Fall through */
-    case 0xd0: /* 8-bit floating point load primary */
-    case 0xd1: /* 8-bit floating point load secondary */
-    case 0xd8: /* 8-bit floating point load primary, LE */
-    case 0xd9: /* 8-bit floating point load secondary, LE */
-        val = env->fpr[rd / 2].l.lower;
-        helper_st_asi(env, addr, val, asi & 0x8d, ((asi & 2) >> 1) + 1);
-        return;
+#else
+    case ASI_TWINX_P:  /* Primary, twinx */
+    case ASI_TWINX_PL: /* Primary, twinx, LE */
+    case ASI_TWINX_S:  /* Primary, twinx */
+    case ASI_TWINX_SL: /* Primary, twinx, LE */
+        /* ??? Should be available, but we need to implement
+           an atomic 128-bit load.  */
+        helper_raise_exception(env, TT_PRIV_ACT);
+#endif
     default:
-        helper_check_align(env, addr, 3);
-        break;
+        /* Non-twinx asi, so this is the legacy ldda insn, which
+           performs two word sized operations.  */
+        /* ??? The UA2011 manual recommends emulating this with
+           a single 64-bit load.  However, LE asis *are* treated
+           as two 32-bit loads individually byte swapped.  */
+        helper_check_align(env, addr, 0x7);
+        QT0.high = (uint32_t)helper_ld_asi(env, addr, asi, MO_UL);
+        QT0.low = (uint32_t)helper_ld_asi(env, addr + 4, asi, MO_UL);
+        return;
     }
 
-    switch (size) {
-    default:
-    case 4:
-        if (rd & 1) {
-            val = env->fpr[rd / 2].l.lower;
-        } else {
-            val = env->fpr[rd / 2].l.upper;
-        }
-        helper_st_asi(env, addr, val, asi, size);
-        break;
-    case 8:
-        helper_st_asi(env, addr, env->fpr[rd / 2].ll, asi, size);
-        break;
-    case 16:
-        helper_st_asi(env, addr, env->fpr[rd / 2].ll, asi, 8);
-        helper_st_asi(env, addr + 8, env->fpr[rd / 2 + 1].ll, asi, 8);
-        break;
+    if (asi & 8) {
+        h = bswap64(h);
+        l = bswap64(l);
     }
+    QT0.high = h;
+    QT0.low = l;
 }
 
 target_ulong helper_casx_asi(CPUSPARCState *env, target_ulong addr,
@@ -2237,9 +2167,9 @@ target_ulong helper_casx_asi(CPUSPARCState *env, target_ulong addr,
 {
     target_ulong ret;
 
-    ret = helper_ld_asi(env, addr, asi, 8, 0);
+    ret = helper_ld_asi(env, addr, asi, MO_Q);
     if (val2 == ret) {
-        helper_st_asi(env, addr, val1, asi, 8);
+        helper_st_asi(env, addr, val1, asi, MO_Q);
     }
     return ret;
 }
@@ -2252,10 +2182,10 @@ target_ulong helper_cas_asi(CPUSPARCState *env, target_ulong addr,
     target_ulong ret;
 
     val2 &= 0xffffffffUL;
-    ret = helper_ld_asi(env, addr, asi, 4, 0);
+    ret = helper_ld_asi(env, addr, asi, MO_UL);
     ret &= 0xffffffffUL;
     if (val2 == ret) {
-        helper_st_asi(env, addr, val1 & 0xffffffffUL, asi, 4);
+        helper_st_asi(env, addr, val1 & 0xffffffffUL, asi, MO_UL);
     }
     return ret;
 }
@@ -2420,9 +2350,10 @@ void sparc_cpu_unassigned_access(CPUState *cs, hwaddr addr,
 #endif
 
 #if !defined(CONFIG_USER_ONLY)
-void QEMU_NORETURN sparc_cpu_do_unaligned_access(CPUState *cs,
-                                                 vaddr addr, int is_write,
-                                                 int is_user, uintptr_t retaddr)
+void QEMU_NORETURN sparc_cpu_do_unaligned_access(CPUState *cs, vaddr addr,
+                                                 MMUAccessType access_type,
+                                                 int mmu_idx,
+                                                 uintptr_t retaddr)
 {
     SPARCCPU *cpu = SPARC_CPU(cs);
     CPUSPARCState *env = &cpu->env;
@@ -2441,12 +2372,12 @@ void QEMU_NORETURN sparc_cpu_do_unaligned_access(CPUState *cs,
    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(CPUState *cs, target_ulong addr, int is_write, int mmu_idx,
-              uintptr_t retaddr)
+void tlb_fill(CPUState *cs, target_ulong addr, MMUAccessType access_type,
+              int mmu_idx, uintptr_t retaddr)
 {
     int ret;
 
-    ret = sparc_cpu_handle_mmu_fault(cs, addr, is_write, mmu_idx);
+    ret = sparc_cpu_handle_mmu_fault(cs, addr, access_type, mmu_idx);
     if (ret) {
         if (retaddr) {
             cpu_restore_state(cs, retaddr);
diff --git a/target-sparc/translate.c b/target-sparc/translate.c
index 0f4faf7062..e7691e4458 100644
--- a/target-sparc/translate.c
+++ b/target-sparc/translate.c
@@ -31,6 +31,7 @@
 
 #include "trace-tcg.h"
 #include "exec/log.h"
+#include "asi.h"
 
 
 #define DEBUG_DISAS
@@ -53,11 +54,10 @@ static TCGv cpu_tbr;
 #endif
 static TCGv cpu_cond;
 #ifdef TARGET_SPARC64
-static TCGv_i32 cpu_xcc, cpu_asi, cpu_fprs;
+static TCGv_i32 cpu_xcc, cpu_fprs;
 static TCGv cpu_gsr;
 static TCGv cpu_tick_cmpr, cpu_stick_cmpr, cpu_hstick_cmpr;
 static TCGv cpu_hintp, cpu_htba, cpu_hver, cpu_ssr, cpu_ver;
-static TCGv_i32 cpu_softint;
 #else
 static TCGv cpu_wim;
 #endif
@@ -82,6 +82,10 @@ typedef struct DisasContext {
     TCGv ttl[5];
     int n_t32;
     int n_ttl;
+#ifdef TARGET_SPARC64
+    int fprs_dirty;
+    int asi;
+#endif
 } DisasContext;
 
 typedef struct {
@@ -137,10 +141,16 @@ static inline TCGv get_temp_tl(DisasContext *dc)
     return t;
 }
 
-static inline void gen_update_fprs_dirty(int rd)
+static inline void gen_update_fprs_dirty(DisasContext *dc, int rd)
 {
 #if defined(TARGET_SPARC64)
-    tcg_gen_ori_i32(cpu_fprs, cpu_fprs, (rd < 32) ? 1 : 2);
+    int bit = (rd < 32) ? 1 : 2;
+    /* If we know we've already set this bit within the TB,
+       we can avoid setting it again.  */
+    if (!(dc->fprs_dirty & bit)) {
+        dc->fprs_dirty |= bit;
+        tcg_gen_ori_i32(cpu_fprs, cpu_fprs, bit);
+    }
 #endif
 }
 
@@ -182,7 +192,7 @@ static void gen_store_fpr_F(DisasContext *dc, unsigned int dst, TCGv_i32 v)
     tcg_gen_deposit_i64(cpu_fpr[dst / 2], cpu_fpr[dst / 2], t,
                         (dst & 1 ? 0 : 32), 32);
 #endif
-    gen_update_fprs_dirty(dst);
+    gen_update_fprs_dirty(dc, dst);
 }
 
 static TCGv_i32 gen_dest_fpr_F(DisasContext *dc)
@@ -200,7 +210,7 @@ static void gen_store_fpr_D(DisasContext *dc, unsigned int dst, TCGv_i64 v)
 {
     dst = DFPREG(dst);
     tcg_gen_mov_i64(cpu_fpr[dst / 2], v);
-    gen_update_fprs_dirty(dst);
+    gen_update_fprs_dirty(dc, dst);
 }
 
 static TCGv_i64 gen_dest_fpr_D(DisasContext *dc, unsigned int dst)
@@ -233,14 +243,14 @@ static void gen_op_store_QT0_fpr(unsigned int dst)
 }
 
 #ifdef TARGET_SPARC64
-static void gen_move_Q(unsigned int rd, unsigned int rs)
+static void gen_move_Q(DisasContext *dc, unsigned int rd, unsigned int rs)
 {
     rd = QFPREG(rd);
     rs = QFPREG(rs);
 
     tcg_gen_mov_i64(cpu_fpr[rd / 2], cpu_fpr[rs / 2]);
     tcg_gen_mov_i64(cpu_fpr[rd / 2 + 1], cpu_fpr[rs / 2 + 1]);
-    gen_update_fprs_dirty(rd);
+    gen_update_fprs_dirty(dc, rd);
 }
 #endif
 
@@ -1044,6 +1054,24 @@ static inline void save_state(DisasContext *dc)
     save_npc(dc);
 }
 
+static void gen_exception(DisasContext *dc, int which)
+{
+    TCGv_i32 t;
+
+    save_state(dc);
+    t = tcg_const_i32(which);
+    gen_helper_raise_exception(cpu_env, t);
+    tcg_temp_free_i32(t);
+    dc->is_br = 1;
+}
+
+static void gen_check_align(TCGv addr, int mask)
+{
+    TCGv_i32 r_mask = tcg_const_i32(mask);
+    gen_helper_check_align(cpu_env, addr, r_mask);
+    tcg_temp_free_i32(r_mask);
+}
+
 static inline void gen_mov_pc_npc(DisasContext *dc)
 {
     if (dc->npc == JUMP_PC) {
@@ -1497,16 +1525,16 @@ static inline void gen_op_fcmps(int fccno, TCGv_i32 r_rs1, TCGv_i32 r_rs2)
 {
     switch (fccno) {
     case 0:
-        gen_helper_fcmps(cpu_env, r_rs1, r_rs2);
+        gen_helper_fcmps(cpu_fsr, cpu_env, r_rs1, r_rs2);
         break;
     case 1:
-        gen_helper_fcmps_fcc1(cpu_env, r_rs1, r_rs2);
+        gen_helper_fcmps_fcc1(cpu_fsr, cpu_env, r_rs1, r_rs2);
         break;
     case 2:
-        gen_helper_fcmps_fcc2(cpu_env, r_rs1, r_rs2);
+        gen_helper_fcmps_fcc2(cpu_fsr, cpu_env, r_rs1, r_rs2);
         break;
     case 3:
-        gen_helper_fcmps_fcc3(cpu_env, r_rs1, r_rs2);
+        gen_helper_fcmps_fcc3(cpu_fsr, cpu_env, r_rs1, r_rs2);
         break;
     }
 }
@@ -1515,16 +1543,16 @@ static inline void gen_op_fcmpd(int fccno, TCGv_i64 r_rs1, TCGv_i64 r_rs2)
 {
     switch (fccno) {
     case 0:
-        gen_helper_fcmpd(cpu_env, r_rs1, r_rs2);
+        gen_helper_fcmpd(cpu_fsr, cpu_env, r_rs1, r_rs2);
         break;
     case 1:
-        gen_helper_fcmpd_fcc1(cpu_env, r_rs1, r_rs2);
+        gen_helper_fcmpd_fcc1(cpu_fsr, cpu_env, r_rs1, r_rs2);
         break;
     case 2:
-        gen_helper_fcmpd_fcc2(cpu_env, r_rs1, r_rs2);
+        gen_helper_fcmpd_fcc2(cpu_fsr, cpu_env, r_rs1, r_rs2);
         break;
     case 3:
-        gen_helper_fcmpd_fcc3(cpu_env, r_rs1, r_rs2);
+        gen_helper_fcmpd_fcc3(cpu_fsr, cpu_env, r_rs1, r_rs2);
         break;
     }
 }
@@ -1533,16 +1561,16 @@ static inline void gen_op_fcmpq(int fccno)
 {
     switch (fccno) {
     case 0:
-        gen_helper_fcmpq(cpu_env);
+        gen_helper_fcmpq(cpu_fsr, cpu_env);
         break;
     case 1:
-        gen_helper_fcmpq_fcc1(cpu_env);
+        gen_helper_fcmpq_fcc1(cpu_fsr, cpu_env);
         break;
     case 2:
-        gen_helper_fcmpq_fcc2(cpu_env);
+        gen_helper_fcmpq_fcc2(cpu_fsr, cpu_env);
         break;
     case 3:
-        gen_helper_fcmpq_fcc3(cpu_env);
+        gen_helper_fcmpq_fcc3(cpu_fsr, cpu_env);
         break;
     }
 }
@@ -1551,16 +1579,16 @@ static inline void gen_op_fcmpes(int fccno, TCGv_i32 r_rs1, TCGv_i32 r_rs2)
 {
     switch (fccno) {
     case 0:
-        gen_helper_fcmpes(cpu_env, r_rs1, r_rs2);
+        gen_helper_fcmpes(cpu_fsr, cpu_env, r_rs1, r_rs2);
         break;
     case 1:
-        gen_helper_fcmpes_fcc1(cpu_env, r_rs1, r_rs2);
+        gen_helper_fcmpes_fcc1(cpu_fsr, cpu_env, r_rs1, r_rs2);
         break;
     case 2:
-        gen_helper_fcmpes_fcc2(cpu_env, r_rs1, r_rs2);
+        gen_helper_fcmpes_fcc2(cpu_fsr, cpu_env, r_rs1, r_rs2);
         break;
     case 3:
-        gen_helper_fcmpes_fcc3(cpu_env, r_rs1, r_rs2);
+        gen_helper_fcmpes_fcc3(cpu_fsr, cpu_env, r_rs1, r_rs2);
         break;
     }
 }
@@ -1569,16 +1597,16 @@ static inline void gen_op_fcmped(int fccno, TCGv_i64 r_rs1, TCGv_i64 r_rs2)
 {
     switch (fccno) {
     case 0:
-        gen_helper_fcmped(cpu_env, r_rs1, r_rs2);
+        gen_helper_fcmped(cpu_fsr, cpu_env, r_rs1, r_rs2);
         break;
     case 1:
-        gen_helper_fcmped_fcc1(cpu_env, r_rs1, r_rs2);
+        gen_helper_fcmped_fcc1(cpu_fsr, cpu_env, r_rs1, r_rs2);
         break;
     case 2:
-        gen_helper_fcmped_fcc2(cpu_env, r_rs1, r_rs2);
+        gen_helper_fcmped_fcc2(cpu_fsr, cpu_env, r_rs1, r_rs2);
         break;
     case 3:
-        gen_helper_fcmped_fcc3(cpu_env, r_rs1, r_rs2);
+        gen_helper_fcmped_fcc3(cpu_fsr, cpu_env, r_rs1, r_rs2);
         break;
     }
 }
@@ -1587,16 +1615,16 @@ static inline void gen_op_fcmpeq(int fccno)
 {
     switch (fccno) {
     case 0:
-        gen_helper_fcmpeq(cpu_env);
+        gen_helper_fcmpeq(cpu_fsr, cpu_env);
         break;
     case 1:
-        gen_helper_fcmpeq_fcc1(cpu_env);
+        gen_helper_fcmpeq_fcc1(cpu_fsr, cpu_env);
         break;
     case 2:
-        gen_helper_fcmpeq_fcc2(cpu_env);
+        gen_helper_fcmpeq_fcc2(cpu_fsr, cpu_env);
         break;
     case 3:
-        gen_helper_fcmpeq_fcc3(cpu_env);
+        gen_helper_fcmpeq_fcc3(cpu_fsr, cpu_env);
         break;
     }
 }
@@ -1605,57 +1633,47 @@ static inline void gen_op_fcmpeq(int fccno)
 
 static inline void gen_op_fcmps(int fccno, TCGv r_rs1, TCGv r_rs2)
 {
-    gen_helper_fcmps(cpu_env, r_rs1, r_rs2);
+    gen_helper_fcmps(cpu_fsr, cpu_env, r_rs1, r_rs2);
 }
 
 static inline void gen_op_fcmpd(int fccno, TCGv_i64 r_rs1, TCGv_i64 r_rs2)
 {
-    gen_helper_fcmpd(cpu_env, r_rs1, r_rs2);
+    gen_helper_fcmpd(cpu_fsr, cpu_env, r_rs1, r_rs2);
 }
 
 static inline void gen_op_fcmpq(int fccno)
 {
-    gen_helper_fcmpq(cpu_env);
+    gen_helper_fcmpq(cpu_fsr, cpu_env);
 }
 
 static inline void gen_op_fcmpes(int fccno, TCGv r_rs1, TCGv r_rs2)
 {
-    gen_helper_fcmpes(cpu_env, r_rs1, r_rs2);
+    gen_helper_fcmpes(cpu_fsr, cpu_env, r_rs1, r_rs2);
 }
 
 static inline void gen_op_fcmped(int fccno, TCGv_i64 r_rs1, TCGv_i64 r_rs2)
 {
-    gen_helper_fcmped(cpu_env, r_rs1, r_rs2);
+    gen_helper_fcmped(cpu_fsr, cpu_env, r_rs1, r_rs2);
 }
 
 static inline void gen_op_fcmpeq(int fccno)
 {
-    gen_helper_fcmpeq(cpu_env);
+    gen_helper_fcmpeq(cpu_fsr, cpu_env);
 }
 #endif
 
-static inline void gen_op_fpexception_im(int fsr_flags)
+static void gen_op_fpexception_im(DisasContext *dc, int fsr_flags)
 {
-    TCGv_i32 r_const;
-
     tcg_gen_andi_tl(cpu_fsr, cpu_fsr, FSR_FTT_NMASK);
     tcg_gen_ori_tl(cpu_fsr, cpu_fsr, fsr_flags);
-    r_const = tcg_const_i32(TT_FP_EXCP);
-    gen_helper_raise_exception(cpu_env, r_const);
-    tcg_temp_free_i32(r_const);
+    gen_exception(dc, TT_FP_EXCP);
 }
 
 static int gen_trap_ifnofpu(DisasContext *dc)
 {
 #if !defined(CONFIG_USER_ONLY)
     if (!dc->fpu_enabled) {
-        TCGv_i32 r_const;
-
-        save_state(dc);
-        r_const = tcg_const_i32(TT_NFPU_INSN);
-        gen_helper_raise_exception(cpu_env, r_const);
-        tcg_temp_free_i32(r_const);
-        dc->is_br = 1;
+        gen_exception(dc, TT_NFPU_INSN);
         return 1;
     }
 #endif
@@ -1676,6 +1694,7 @@ static inline void gen_fop_FF(DisasContext *dc, int rd, int rs,
     dst = gen_dest_fpr_F(dc);
 
     gen(dst, cpu_env, src);
+    gen_helper_check_ieee_exceptions(cpu_fsr, cpu_env);
 
     gen_store_fpr_F(dc, rd, dst);
 }
@@ -1703,6 +1722,7 @@ static inline void gen_fop_FFF(DisasContext *dc, int rd, int rs1, int rs2,
     dst = gen_dest_fpr_F(dc);
 
     gen(dst, cpu_env, src1, src2);
+    gen_helper_check_ieee_exceptions(cpu_fsr, cpu_env);
 
     gen_store_fpr_F(dc, rd, dst);
 }
@@ -1732,6 +1752,7 @@ static inline void gen_fop_DD(DisasContext *dc, int rd, int rs,
     dst = gen_dest_fpr_D(dc, rd);
 
     gen(dst, cpu_env, src);
+    gen_helper_check_ieee_exceptions(cpu_fsr, cpu_env);
 
     gen_store_fpr_D(dc, rd, dst);
 }
@@ -1761,6 +1782,7 @@ static inline void gen_fop_DDD(DisasContext *dc, int rd, int rs1, int rs2,
     dst = gen_dest_fpr_D(dc, rd);
 
     gen(dst, cpu_env, src1, src2);
+    gen_helper_check_ieee_exceptions(cpu_fsr, cpu_env);
 
     gen_store_fpr_D(dc, rd, dst);
 }
@@ -1816,9 +1838,10 @@ static inline void gen_fop_QQ(DisasContext *dc, int rd, int rs,
     gen_op_load_fpr_QT1(QFPREG(rs));
 
     gen(cpu_env);
+    gen_helper_check_ieee_exceptions(cpu_fsr, cpu_env);
 
     gen_op_store_QT0_fpr(QFPREG(rd));
-    gen_update_fprs_dirty(QFPREG(rd));
+    gen_update_fprs_dirty(dc, QFPREG(rd));
 }
 
 #ifdef TARGET_SPARC64
@@ -1830,7 +1853,7 @@ static inline void gen_ne_fop_QQ(DisasContext *dc, int rd, int rs,
     gen(cpu_env);
 
     gen_op_store_QT0_fpr(QFPREG(rd));
-    gen_update_fprs_dirty(QFPREG(rd));
+    gen_update_fprs_dirty(dc, QFPREG(rd));
 }
 #endif
 
@@ -1841,9 +1864,10 @@ static inline void gen_fop_QQQ(DisasContext *dc, int rd, int rs1, int rs2,
     gen_op_load_fpr_QT1(QFPREG(rs2));
 
     gen(cpu_env);
+    gen_helper_check_ieee_exceptions(cpu_fsr, cpu_env);
 
     gen_op_store_QT0_fpr(QFPREG(rd));
-    gen_update_fprs_dirty(QFPREG(rd));
+    gen_update_fprs_dirty(dc, QFPREG(rd));
 }
 
 static inline void gen_fop_DFF(DisasContext *dc, int rd, int rs1, int rs2,
@@ -1857,6 +1881,7 @@ static inline void gen_fop_DFF(DisasContext *dc, int rd, int rs1, int rs2,
     dst = gen_dest_fpr_D(dc, rd);
 
     gen(dst, cpu_env, src1, src2);
+    gen_helper_check_ieee_exceptions(cpu_fsr, cpu_env);
 
     gen_store_fpr_D(dc, rd, dst);
 }
@@ -1870,9 +1895,10 @@ static inline void gen_fop_QDD(DisasContext *dc, int rd, int rs1, int rs2,
     src2 = gen_load_fpr_D(dc, rs2);
 
     gen(cpu_env, src1, src2);
+    gen_helper_check_ieee_exceptions(cpu_fsr, cpu_env);
 
     gen_op_store_QT0_fpr(QFPREG(rd));
-    gen_update_fprs_dirty(QFPREG(rd));
+    gen_update_fprs_dirty(dc, QFPREG(rd));
 }
 
 #ifdef TARGET_SPARC64
@@ -1886,6 +1912,7 @@ static inline void gen_fop_DF(DisasContext *dc, int rd, int rs,
     dst = gen_dest_fpr_D(dc, rd);
 
     gen(dst, cpu_env, src);
+    gen_helper_check_ieee_exceptions(cpu_fsr, cpu_env);
 
     gen_store_fpr_D(dc, rd, dst);
 }
@@ -1915,6 +1942,7 @@ static inline void gen_fop_FD(DisasContext *dc, int rd, int rs,
     dst = gen_dest_fpr_F(dc);
 
     gen(dst, cpu_env, src);
+    gen_helper_check_ieee_exceptions(cpu_fsr, cpu_env);
 
     gen_store_fpr_F(dc, rd, dst);
 }
@@ -1928,6 +1956,7 @@ static inline void gen_fop_FQ(DisasContext *dc, int rd, int rs,
     dst = gen_dest_fpr_F(dc);
 
     gen(dst, cpu_env);
+    gen_helper_check_ieee_exceptions(cpu_fsr, cpu_env);
 
     gen_store_fpr_F(dc, rd, dst);
 }
@@ -1941,6 +1970,7 @@ static inline void gen_fop_DQ(DisasContext *dc, int rd, int rs,
     dst = gen_dest_fpr_D(dc, rd);
 
     gen(dst, cpu_env);
+    gen_helper_check_ieee_exceptions(cpu_fsr, cpu_env);
 
     gen_store_fpr_D(dc, rd, dst);
 }
@@ -1955,7 +1985,7 @@ static inline void gen_ne_fop_QF(DisasContext *dc, int rd, int rs,
     gen(cpu_env, src);
 
     gen_op_store_QT0_fpr(QFPREG(rd));
-    gen_update_fprs_dirty(QFPREG(rd));
+    gen_update_fprs_dirty(dc, QFPREG(rd));
 }
 
 static inline void gen_ne_fop_QD(DisasContext *dc, int rd, int rs,
@@ -1968,266 +1998,734 @@ static inline void gen_ne_fop_QD(DisasContext *dc, int rd, int rs,
     gen(cpu_env, src);
 
     gen_op_store_QT0_fpr(QFPREG(rd));
-    gen_update_fprs_dirty(QFPREG(rd));
+    gen_update_fprs_dirty(dc, QFPREG(rd));
 }
 
 /* asi moves */
-#ifdef TARGET_SPARC64
-static inline TCGv_i32 gen_get_asi(int insn, TCGv r_addr)
-{
+#if !defined(CONFIG_USER_ONLY) || defined(TARGET_SPARC64)
+typedef enum {
+    GET_ASI_HELPER,
+    GET_ASI_EXCP,
+    GET_ASI_DIRECT,
+    GET_ASI_DTWINX,
+    GET_ASI_BLOCK,
+    GET_ASI_SHORT,
+} ASIType;
+
+typedef struct {
+    ASIType type;
     int asi;
-    TCGv_i32 r_asi;
+    int mem_idx;
+    TCGMemOp memop;
+} DisasASI;
+
+static DisasASI get_asi(DisasContext *dc, int insn, TCGMemOp memop)
+{
+    int asi = GET_FIELD(insn, 19, 26);
+    ASIType type = GET_ASI_HELPER;
+    int mem_idx = dc->mem_idx;
 
+#ifndef TARGET_SPARC64
+    /* Before v9, all asis are immediate and privileged.  */
     if (IS_IMM) {
-        r_asi = tcg_temp_new_i32();
-        tcg_gen_mov_i32(r_asi, cpu_asi);
+        gen_exception(dc, TT_ILL_INSN);
+        type = GET_ASI_EXCP;
+    } else if (supervisor(dc)
+               /* Note that LEON accepts ASI_USERDATA in user mode, for
+                  use with CASA.  Also note that previous versions of
+                  QEMU allowed (and old versions of gcc emitted) ASI_P
+                  for LEON, which is incorrect.  */
+               || (asi == ASI_USERDATA
+                   && (dc->def->features & CPU_FEATURE_CASA))) {
+        switch (asi) {
+        case ASI_USERDATA:   /* User data access */
+            mem_idx = MMU_USER_IDX;
+            type = GET_ASI_DIRECT;
+            break;
+        case ASI_KERNELDATA: /* Supervisor data access */
+            mem_idx = MMU_KERNEL_IDX;
+            type = GET_ASI_DIRECT;
+            break;
+        }
     } else {
-        asi = GET_FIELD(insn, 19, 26);
-        r_asi = tcg_const_i32(asi);
+        gen_exception(dc, TT_PRIV_INSN);
+        type = GET_ASI_EXCP;
+    }
+#else
+    if (IS_IMM) {
+        asi = dc->asi;
     }
-    return r_asi;
+    /* With v9, all asis below 0x80 are privileged.  */
+    /* ??? We ought to check cpu_has_hypervisor, but we didn't copy
+       down that bit into DisasContext.  For the moment that's ok,
+       since the direct implementations below doesn't have any ASIs
+       in the restricted [0x30, 0x7f] range, and the check will be
+       done properly in the helper.  */
+    if (!supervisor(dc) && asi < 0x80) {
+        gen_exception(dc, TT_PRIV_ACT);
+        type = GET_ASI_EXCP;
+    } else {
+        switch (asi) {
+        case ASI_N:  /* Nucleus */
+        case ASI_NL: /* Nucleus LE */
+        case ASI_TWINX_N:
+        case ASI_TWINX_NL:
+            mem_idx = MMU_NUCLEUS_IDX;
+            break;
+        case ASI_AIUP:  /* As if user primary */
+        case ASI_AIUPL: /* As if user primary LE */
+        case ASI_TWINX_AIUP:
+        case ASI_TWINX_AIUP_L:
+        case ASI_BLK_AIUP_4V:
+        case ASI_BLK_AIUP_L_4V:
+        case ASI_BLK_AIUP:
+        case ASI_BLK_AIUPL:
+            mem_idx = MMU_USER_IDX;
+            break;
+        case ASI_AIUS:  /* As if user secondary */
+        case ASI_AIUSL: /* As if user secondary LE */
+        case ASI_TWINX_AIUS:
+        case ASI_TWINX_AIUS_L:
+        case ASI_BLK_AIUS_4V:
+        case ASI_BLK_AIUS_L_4V:
+        case ASI_BLK_AIUS:
+        case ASI_BLK_AIUSL:
+            mem_idx = MMU_USER_SECONDARY_IDX;
+            break;
+        case ASI_S:  /* Secondary */
+        case ASI_SL: /* Secondary LE */
+        case ASI_TWINX_S:
+        case ASI_TWINX_SL:
+        case ASI_BLK_COMMIT_S:
+        case ASI_BLK_S:
+        case ASI_BLK_SL:
+        case ASI_FL8_S:
+        case ASI_FL8_SL:
+        case ASI_FL16_S:
+        case ASI_FL16_SL:
+            if (mem_idx == MMU_USER_IDX) {
+                mem_idx = MMU_USER_SECONDARY_IDX;
+            } else if (mem_idx == MMU_KERNEL_IDX) {
+                mem_idx = MMU_KERNEL_SECONDARY_IDX;
+            }
+            break;
+        case ASI_P:  /* Primary */
+        case ASI_PL: /* Primary LE */
+        case ASI_TWINX_P:
+        case ASI_TWINX_PL:
+        case ASI_BLK_COMMIT_P:
+        case ASI_BLK_P:
+        case ASI_BLK_PL:
+        case ASI_FL8_P:
+        case ASI_FL8_PL:
+        case ASI_FL16_P:
+        case ASI_FL16_PL:
+            break;
+        }
+        switch (asi) {
+        case ASI_N:
+        case ASI_NL:
+        case ASI_AIUP:
+        case ASI_AIUPL:
+        case ASI_AIUS:
+        case ASI_AIUSL:
+        case ASI_S:
+        case ASI_SL:
+        case ASI_P:
+        case ASI_PL:
+            type = GET_ASI_DIRECT;
+            break;
+        case ASI_TWINX_N:
+        case ASI_TWINX_NL:
+        case ASI_TWINX_AIUP:
+        case ASI_TWINX_AIUP_L:
+        case ASI_TWINX_AIUS:
+        case ASI_TWINX_AIUS_L:
+        case ASI_TWINX_P:
+        case ASI_TWINX_PL:
+        case ASI_TWINX_S:
+        case ASI_TWINX_SL:
+            type = GET_ASI_DTWINX;
+            break;
+        case ASI_BLK_COMMIT_P:
+        case ASI_BLK_COMMIT_S:
+        case ASI_BLK_AIUP_4V:
+        case ASI_BLK_AIUP_L_4V:
+        case ASI_BLK_AIUP:
+        case ASI_BLK_AIUPL:
+        case ASI_BLK_AIUS_4V:
+        case ASI_BLK_AIUS_L_4V:
+        case ASI_BLK_AIUS:
+        case ASI_BLK_AIUSL:
+        case ASI_BLK_S:
+        case ASI_BLK_SL:
+        case ASI_BLK_P:
+        case ASI_BLK_PL:
+            type = GET_ASI_BLOCK;
+            break;
+        case ASI_FL8_S:
+        case ASI_FL8_SL:
+        case ASI_FL8_P:
+        case ASI_FL8_PL:
+            memop = MO_UB;
+            type = GET_ASI_SHORT;
+            break;
+        case ASI_FL16_S:
+        case ASI_FL16_SL:
+        case ASI_FL16_P:
+        case ASI_FL16_PL:
+            memop = MO_TEUW;
+            type = GET_ASI_SHORT;
+            break;
+        }
+        /* The little-endian asis all have bit 3 set.  */
+        if (asi & 8) {
+            memop ^= MO_BSWAP;
+        }
+    }
+#endif
+
+    return (DisasASI){ type, asi, mem_idx, memop };
 }
 
-static inline void gen_ld_asi(TCGv dst, TCGv addr, int insn, int size,
-                              int sign)
+static void gen_ld_asi(DisasContext *dc, TCGv dst, TCGv addr,
+                       int insn, TCGMemOp memop)
 {
-    TCGv_i32 r_asi, r_size, r_sign;
+    DisasASI da = get_asi(dc, insn, memop);
 
-    r_asi = gen_get_asi(insn, addr);
-    r_size = tcg_const_i32(size);
-    r_sign = tcg_const_i32(sign);
-    gen_helper_ld_asi(dst, cpu_env, addr, r_asi, r_size, r_sign);
-    tcg_temp_free_i32(r_sign);
-    tcg_temp_free_i32(r_size);
-    tcg_temp_free_i32(r_asi);
+    switch (da.type) {
+    case GET_ASI_EXCP:
+        break;
+    case GET_ASI_DTWINX: /* Reserved for ldda.  */
+        gen_exception(dc, TT_ILL_INSN);
+        break;
+    case GET_ASI_DIRECT:
+        gen_address_mask(dc, addr);
+        tcg_gen_qemu_ld_tl(dst, addr, da.mem_idx, da.memop);
+        break;
+    default:
+        {
+            TCGv_i32 r_asi = tcg_const_i32(da.asi);
+            TCGv_i32 r_mop = tcg_const_i32(memop);
+
+            save_state(dc);
+#ifdef TARGET_SPARC64
+            gen_helper_ld_asi(dst, cpu_env, addr, r_asi, r_mop);
+#else
+            {
+                TCGv_i64 t64 = tcg_temp_new_i64();
+                gen_helper_ld_asi(t64, cpu_env, addr, r_asi, r_mop);
+                tcg_gen_trunc_i64_tl(dst, t64);
+                tcg_temp_free_i64(t64);
+            }
+#endif
+            tcg_temp_free_i32(r_mop);
+            tcg_temp_free_i32(r_asi);
+        }
+        break;
+    }
 }
 
-static inline void gen_st_asi(TCGv src, TCGv addr, int insn, int size)
+static void gen_st_asi(DisasContext *dc, TCGv src, TCGv addr,
+                       int insn, TCGMemOp memop)
 {
-    TCGv_i32 r_asi, r_size;
+    DisasASI da = get_asi(dc, insn, memop);
 
-    r_asi = gen_get_asi(insn, addr);
-    r_size = tcg_const_i32(size);
-    gen_helper_st_asi(cpu_env, addr, src, r_asi, r_size);
-    tcg_temp_free_i32(r_size);
-    tcg_temp_free_i32(r_asi);
+    switch (da.type) {
+    case GET_ASI_EXCP:
+        break;
+    case GET_ASI_DTWINX: /* Reserved for stda.  */
+        gen_exception(dc, TT_ILL_INSN);
+        break;
+    case GET_ASI_DIRECT:
+        gen_address_mask(dc, addr);
+        tcg_gen_qemu_st_tl(src, addr, da.mem_idx, da.memop);
+        break;
+    default:
+        {
+            TCGv_i32 r_asi = tcg_const_i32(da.asi);
+            TCGv_i32 r_mop = tcg_const_i32(memop & MO_SIZE);
+
+            save_state(dc);
+#ifdef TARGET_SPARC64
+            gen_helper_st_asi(cpu_env, addr, src, r_asi, r_mop);
+#else
+            {
+                TCGv_i64 t64 = tcg_temp_new_i64();
+                tcg_gen_extu_tl_i64(t64, src);
+                gen_helper_st_asi(cpu_env, addr, t64, r_asi, r_mop);
+                tcg_temp_free_i64(t64);
+            }
+#endif
+            tcg_temp_free_i32(r_mop);
+            tcg_temp_free_i32(r_asi);
+
+            /* A write to a TLB register may alter page maps.  End the TB. */
+            dc->npc = DYNAMIC_PC;
+        }
+        break;
+    }
 }
 
-static inline void gen_ldf_asi(TCGv addr, int insn, int size, int rd)
+static void gen_swap_asi(DisasContext *dc, TCGv dst, TCGv src,
+                         TCGv addr, int insn)
 {
-    TCGv_i32 r_asi, r_size, r_rd;
+    DisasASI da = get_asi(dc, insn, MO_TEUL);
 
-    r_asi = gen_get_asi(insn, addr);
-    r_size = tcg_const_i32(size);
-    r_rd = tcg_const_i32(rd);
-    gen_helper_ldf_asi(cpu_env, addr, r_asi, r_size, r_rd);
-    tcg_temp_free_i32(r_rd);
-    tcg_temp_free_i32(r_size);
-    tcg_temp_free_i32(r_asi);
+    switch (da.type) {
+    case GET_ASI_EXCP:
+        break;
+    default:
+        {
+            TCGv_i32 r_asi = tcg_const_i32(da.asi);
+            TCGv_i32 r_mop = tcg_const_i32(MO_UL);
+            TCGv_i64 s64, t64;
+
+            save_state(dc);
+            t64 = tcg_temp_new_i64();
+            gen_helper_ld_asi(t64, cpu_env, addr, r_asi, r_mop);
+
+            s64 = tcg_temp_new_i64();
+            tcg_gen_extu_tl_i64(s64, src);
+            gen_helper_st_asi(cpu_env, addr, s64, r_asi, r_mop);
+            tcg_temp_free_i64(s64);
+            tcg_temp_free_i32(r_mop);
+            tcg_temp_free_i32(r_asi);
+
+            tcg_gen_trunc_i64_tl(dst, t64);
+            tcg_temp_free_i64(t64);
+        }
+        break;
+    }
 }
 
-static inline void gen_stf_asi(TCGv addr, int insn, int size, int rd)
+static void gen_cas_asi(DisasContext *dc, TCGv addr, TCGv val2,
+                        int insn, int rd)
 {
-    TCGv_i32 r_asi, r_size, r_rd;
+    DisasASI da = get_asi(dc, insn, MO_TEUL);
+    TCGv val1, dst;
+    TCGv_i32 r_asi;
 
-    r_asi = gen_get_asi(insn, addr);
-    r_size = tcg_const_i32(size);
-    r_rd = tcg_const_i32(rd);
-    gen_helper_stf_asi(cpu_env, addr, r_asi, r_size, r_rd);
-    tcg_temp_free_i32(r_rd);
-    tcg_temp_free_i32(r_size);
+    if (da.type == GET_ASI_EXCP) {
+        return;
+    }
+
+    save_state(dc);
+    val1 = gen_load_gpr(dc, rd);
+    dst = gen_dest_gpr(dc, rd);
+    r_asi = tcg_const_i32(da.asi);
+    gen_helper_cas_asi(dst, cpu_env, addr, val1, val2, r_asi);
     tcg_temp_free_i32(r_asi);
+    gen_store_gpr(dc, rd, dst);
 }
 
-static inline void gen_swap_asi(TCGv dst, TCGv src, TCGv addr, int insn)
+static void gen_ldstub_asi(DisasContext *dc, TCGv dst, TCGv addr, int insn)
 {
-    TCGv_i32 r_asi, r_size, r_sign;
-    TCGv_i64 t64 = tcg_temp_new_i64();
+    DisasASI da = get_asi(dc, insn, MO_UB);
 
-    r_asi = gen_get_asi(insn, addr);
-    r_size = tcg_const_i32(4);
-    r_sign = tcg_const_i32(0);
-    gen_helper_ld_asi(t64, cpu_env, addr, r_asi, r_size, r_sign);
-    tcg_temp_free_i32(r_sign);
-    gen_helper_st_asi(cpu_env, addr, src, r_asi, r_size);
-    tcg_temp_free_i32(r_size);
-    tcg_temp_free_i32(r_asi);
-    tcg_gen_trunc_i64_tl(dst, t64);
-    tcg_temp_free_i64(t64);
+    switch (da.type) {
+    case GET_ASI_EXCP:
+        break;
+    default:
+        {
+            TCGv_i32 r_asi = tcg_const_i32(da.asi);
+            TCGv_i32 r_mop = tcg_const_i32(MO_UB);
+            TCGv_i64 s64, t64;
+
+            save_state(dc);
+            t64 = tcg_temp_new_i64();
+            gen_helper_ld_asi(t64, cpu_env, addr, r_asi, r_mop);
+
+            s64 = tcg_const_i64(0xff);
+            gen_helper_st_asi(cpu_env, addr, s64, r_asi, r_mop);
+            tcg_temp_free_i64(s64);
+            tcg_temp_free_i32(r_mop);
+            tcg_temp_free_i32(r_asi);
+
+            tcg_gen_trunc_i64_tl(dst, t64);
+            tcg_temp_free_i64(t64);
+        }
+        break;
+    }
 }
+#endif
 
-static inline void gen_ldda_asi(DisasContext *dc, TCGv hi, TCGv addr,
-                                int insn, int rd)
+#ifdef TARGET_SPARC64
+static void gen_ldf_asi(DisasContext *dc, TCGv addr,
+                        int insn, int size, int rd)
 {
-    TCGv_i32 r_asi, r_rd;
+    DisasASI da = get_asi(dc, insn, (size == 4 ? MO_TEUL : MO_TEQ));
+    TCGv_i32 d32;
 
-    r_asi = gen_get_asi(insn, addr);
-    r_rd = tcg_const_i32(rd);
-    gen_helper_ldda_asi(cpu_env, addr, r_asi, r_rd);
-    tcg_temp_free_i32(r_rd);
-    tcg_temp_free_i32(r_asi);
+    switch (da.type) {
+    case GET_ASI_EXCP:
+        break;
+
+    case GET_ASI_DIRECT:
+        gen_address_mask(dc, addr);
+        switch (size) {
+        case 4:
+            d32 = gen_dest_fpr_F(dc);
+            tcg_gen_qemu_ld_i32(d32, addr, da.mem_idx, da.memop);
+            gen_store_fpr_F(dc, rd, d32);
+            break;
+        case 8:
+            tcg_gen_qemu_ld_i64(cpu_fpr[rd / 2], addr, da.mem_idx, da.memop);
+            break;
+        case 16:
+            tcg_gen_qemu_ld_i64(cpu_fpr[rd / 2], addr, da.mem_idx, da.memop);
+            tcg_gen_addi_tl(addr, addr, 8);
+            tcg_gen_qemu_ld_i64(cpu_fpr[rd/2+1], addr, da.mem_idx, da.memop);
+            break;
+        default:
+            g_assert_not_reached();
+        }
+        break;
+
+    case GET_ASI_BLOCK:
+        /* Valid for lddfa on aligned registers only.  */
+        if (size == 8 && (rd & 7) == 0) {
+            TCGv eight;
+            int i;
+
+            gen_check_align(addr, 0x3f);
+            gen_address_mask(dc, addr);
+
+            eight = tcg_const_tl(8);
+            for (i = 0; ; ++i) {
+                tcg_gen_qemu_ld_i64(cpu_fpr[rd / 2 + i], addr,
+                                    da.mem_idx, da.memop);
+                if (i == 7) {
+                    break;
+                }
+                tcg_gen_add_tl(addr, addr, eight);
+            }
+            tcg_temp_free(eight);
+        } else {
+            gen_exception(dc, TT_ILL_INSN);
+        }
+        break;
+
+    case GET_ASI_SHORT:
+        /* Valid for lddfa only.  */
+        if (size == 8) {
+            gen_address_mask(dc, addr);
+            tcg_gen_qemu_ld_i64(cpu_fpr[rd / 2], addr, da.mem_idx, da.memop);
+        } else {
+            gen_exception(dc, TT_ILL_INSN);
+        }
+        break;
+
+    default:
+        {
+            TCGv_i32 r_asi = tcg_const_i32(da.asi);
+            TCGv_i32 r_mop = tcg_const_i32(da.memop);
+
+            save_state(dc);
+            /* According to the table in the UA2011 manual, the only
+               other asis that are valid for ldfa/lddfa/ldqfa are
+               the NO_FAULT asis.  We still need a helper for these,
+               but we can just use the integer asi helper for them.  */
+            switch (size) {
+            case 4:
+                {
+                    TCGv d64 = tcg_temp_new_i64();
+                    gen_helper_ld_asi(d64, cpu_env, addr, r_asi, r_mop);
+                    d32 = gen_dest_fpr_F(dc);
+                    tcg_gen_extrl_i64_i32(d32, d64);
+                    tcg_temp_free_i64(d64);
+                    gen_store_fpr_F(dc, rd, d32);
+                }
+                break;
+            case 8:
+                gen_helper_ld_asi(cpu_fpr[rd / 2], cpu_env, addr, r_asi, r_mop);
+                break;
+            case 16:
+                gen_helper_ld_asi(cpu_fpr[rd / 2], cpu_env, addr, r_asi, r_mop);
+                tcg_gen_addi_tl(addr, addr, 8);
+                gen_helper_ld_asi(cpu_fpr[rd/2+1], cpu_env, addr, r_asi, r_mop);
+                break;
+            default:
+                g_assert_not_reached();
+            }
+            tcg_temp_free_i32(r_mop);
+            tcg_temp_free_i32(r_asi);
+        }
+        break;
+    }
 }
 
-static inline void gen_stda_asi(DisasContext *dc, TCGv hi, TCGv addr,
-                                int insn, int rd)
+static void gen_stf_asi(DisasContext *dc, TCGv addr,
+                        int insn, int size, int rd)
 {
-    TCGv_i32 r_asi, r_size;
-    TCGv lo = gen_load_gpr(dc, rd + 1);
-    TCGv_i64 t64 = tcg_temp_new_i64();
+    DisasASI da = get_asi(dc, insn, (size == 4 ? MO_TEUL : MO_TEQ));
+    TCGv_i32 d32;
 
-    tcg_gen_concat_tl_i64(t64, lo, hi);
-    r_asi = gen_get_asi(insn, addr);
-    r_size = tcg_const_i32(8);
-    gen_helper_st_asi(cpu_env, addr, t64, r_asi, r_size);
-    tcg_temp_free_i32(r_size);
-    tcg_temp_free_i32(r_asi);
-    tcg_temp_free_i64(t64);
+    switch (da.type) {
+    case GET_ASI_EXCP:
+        break;
+
+    case GET_ASI_DIRECT:
+        gen_address_mask(dc, addr);
+        switch (size) {
+        case 4:
+            d32 = gen_load_fpr_F(dc, rd);
+            tcg_gen_qemu_st_i32(d32, addr, da.mem_idx, da.memop);
+            break;
+        case 8:
+            tcg_gen_qemu_st_i64(cpu_fpr[rd / 2], addr, da.mem_idx, da.memop);
+            break;
+        case 16:
+            tcg_gen_qemu_st_i64(cpu_fpr[rd / 2], addr, da.mem_idx, da.memop);
+            tcg_gen_addi_tl(addr, addr, 8);
+            tcg_gen_qemu_st_i64(cpu_fpr[rd/2+1], addr, da.mem_idx, da.memop);
+            break;
+        default:
+            g_assert_not_reached();
+        }
+        break;
+
+    case GET_ASI_BLOCK:
+        /* Valid for stdfa on aligned registers only.  */
+        if (size == 8 && (rd & 7) == 0) {
+            TCGv eight;
+            int i;
+
+            gen_check_align(addr, 0x3f);
+            gen_address_mask(dc, addr);
+
+            eight = tcg_const_tl(8);
+            for (i = 0; ; ++i) {
+                tcg_gen_qemu_st_i64(cpu_fpr[rd / 2 + i], addr,
+                                    da.mem_idx, da.memop);
+                if (i == 7) {
+                    break;
+                }
+                tcg_gen_add_tl(addr, addr, eight);
+            }
+            tcg_temp_free(eight);
+        } else {
+            gen_exception(dc, TT_ILL_INSN);
+        }
+        break;
+
+    case GET_ASI_SHORT:
+        /* Valid for stdfa only.  */
+        if (size == 8) {
+            gen_address_mask(dc, addr);
+            tcg_gen_qemu_st_i64(cpu_fpr[rd / 2], addr, da.mem_idx, da.memop);
+        } else {
+            gen_exception(dc, TT_ILL_INSN);
+        }
+        break;
+
+    default:
+        /* According to the table in the UA2011 manual, the only
+           other asis that are valid for ldfa/lddfa/ldqfa are
+           the PST* asis, which aren't currently handled.  */
+        gen_exception(dc, TT_ILL_INSN);
+        break;
+    }
 }
 
-static inline void gen_casx_asi(DisasContext *dc, TCGv addr,
-                                TCGv val2, int insn, int rd)
+static void gen_ldda_asi(DisasContext *dc, TCGv addr, int insn, int rd)
 {
-    TCGv val1 = gen_load_gpr(dc, rd);
-    TCGv dst = gen_dest_gpr(dc, rd);
-    TCGv_i32 r_asi = gen_get_asi(insn, addr);
+    DisasASI da = get_asi(dc, insn, MO_TEQ);
+    TCGv_i64 hi = gen_dest_gpr(dc, rd);
+    TCGv_i64 lo = gen_dest_gpr(dc, rd + 1);
 
-    gen_helper_casx_asi(dst, cpu_env, addr, val1, val2, r_asi);
-    tcg_temp_free_i32(r_asi);
-    gen_store_gpr(dc, rd, dst);
-}
+    switch (da.type) {
+    case GET_ASI_EXCP:
+        return;
 
-#elif !defined(CONFIG_USER_ONLY)
+    case GET_ASI_DTWINX:
+        gen_check_align(addr, 15);
+        gen_address_mask(dc, addr);
+        tcg_gen_qemu_ld_i64(hi, addr, da.mem_idx, da.memop);
+        tcg_gen_addi_tl(addr, addr, 8);
+        tcg_gen_qemu_ld_i64(lo, addr, da.mem_idx, da.memop);
+        break;
 
-static inline void gen_ld_asi(TCGv dst, TCGv addr, int insn, int size,
-                              int sign)
-{
-    TCGv_i32 r_asi, r_size, r_sign;
-    TCGv_i64 t64 = tcg_temp_new_i64();
+    case GET_ASI_DIRECT:
+        {
+            TCGv_i64 tmp = tcg_temp_new_i64();
 
-    r_asi = tcg_const_i32(GET_FIELD(insn, 19, 26));
-    r_size = tcg_const_i32(size);
-    r_sign = tcg_const_i32(sign);
-    gen_helper_ld_asi(t64, cpu_env, addr, r_asi, r_size, r_sign);
-    tcg_temp_free_i32(r_sign);
-    tcg_temp_free_i32(r_size);
-    tcg_temp_free_i32(r_asi);
-    tcg_gen_trunc_i64_tl(dst, t64);
-    tcg_temp_free_i64(t64);
+            gen_address_mask(dc, addr);
+            tcg_gen_qemu_ld_i64(tmp, addr, da.mem_idx, da.memop);
+
+            /* Note that LE ldda acts as if each 32-bit register
+               result is byte swapped.  Having just performed one
+               64-bit bswap, we need now to swap the writebacks.  */
+            if ((da.memop & MO_BSWAP) == MO_TE) {
+                tcg_gen_extr32_i64(lo, hi, tmp);
+            } else {
+                tcg_gen_extr32_i64(hi, lo, tmp);
+            }
+            tcg_temp_free_i64(tmp);
+        }
+        break;
+
+    default:
+        {
+            TCGv_i32 r_asi = tcg_const_i32(da.asi);
+
+            save_state(dc);
+            gen_helper_ldda_asi(cpu_env, addr, r_asi);
+            tcg_temp_free_i32(r_asi);
+
+            tcg_gen_ld_i64(hi, cpu_env, offsetof(CPUSPARCState, qt0.high));
+            tcg_gen_ld_i64(lo, cpu_env, offsetof(CPUSPARCState, qt0.low));
+        }
+        break;
+    }
+
+    gen_store_gpr(dc, rd, hi);
+    gen_store_gpr(dc, rd + 1, lo);
 }
 
-static inline void gen_st_asi(TCGv src, TCGv addr, int insn, int size)
+static void gen_stda_asi(DisasContext *dc, TCGv hi, TCGv addr,
+                         int insn, int rd)
 {
-    TCGv_i32 r_asi, r_size;
-    TCGv_i64 t64 = tcg_temp_new_i64();
+    DisasASI da = get_asi(dc, insn, MO_TEQ);
+    TCGv lo = gen_load_gpr(dc, rd + 1);
 
-    tcg_gen_extu_tl_i64(t64, src);
-    r_asi = tcg_const_i32(GET_FIELD(insn, 19, 26));
-    r_size = tcg_const_i32(size);
-    gen_helper_st_asi(cpu_env, addr, t64, r_asi, r_size);
-    tcg_temp_free_i32(r_size);
-    tcg_temp_free_i32(r_asi);
-    tcg_temp_free_i64(t64);
+    switch (da.type) {
+    case GET_ASI_EXCP:
+        break;
+
+    case GET_ASI_DTWINX:
+        gen_check_align(addr, 15);
+        gen_address_mask(dc, addr);
+        tcg_gen_qemu_st_i64(hi, addr, da.mem_idx, da.memop);
+        tcg_gen_addi_tl(addr, addr, 8);
+        tcg_gen_qemu_st_i64(lo, addr, da.mem_idx, da.memop);
+        break;
+
+    case GET_ASI_DIRECT:
+        {
+            TCGv_i64 t64 = tcg_temp_new_i64();
+
+            /* Note that LE stda acts as if each 32-bit register result is
+               byte swapped.  We will perform one 64-bit LE store, so now
+               we must swap the order of the construction.  */
+            if ((da.memop & MO_BSWAP) == MO_TE) {
+                tcg_gen_concat32_i64(t64, lo, hi);
+            } else {
+                tcg_gen_concat32_i64(t64, hi, lo);
+            }
+            gen_address_mask(dc, addr);
+            tcg_gen_qemu_st_i64(t64, addr, da.mem_idx, da.memop);
+            tcg_temp_free_i64(t64);
+        }
+        break;
+
+    default:
+        {
+            TCGv_i32 r_asi = tcg_const_i32(da.asi);
+            TCGv_i32 r_mop = tcg_const_i32(MO_Q);
+            TCGv_i64 t64;
+
+            save_state(dc);
+
+            t64 = tcg_temp_new_i64();
+            tcg_gen_concat_tl_i64(t64, lo, hi);
+            gen_helper_st_asi(cpu_env, addr, t64, r_asi, r_mop);
+            tcg_temp_free_i32(r_mop);
+            tcg_temp_free_i32(r_asi);
+            tcg_temp_free_i64(t64);
+        }
+        break;
+    }
 }
 
-static inline void gen_swap_asi(TCGv dst, TCGv src, TCGv addr, int insn)
+static void gen_casx_asi(DisasContext *dc, TCGv addr, TCGv val2,
+                         int insn, int rd)
 {
-    TCGv_i32 r_asi, r_size, r_sign;
-    TCGv_i64 r_val, t64;
+    DisasASI da = get_asi(dc, insn, MO_TEQ);
+    TCGv val1 = gen_load_gpr(dc, rd);
+    TCGv dst = gen_dest_gpr(dc, rd);
+    TCGv_i32 r_asi;
 
-    r_asi = tcg_const_i32(GET_FIELD(insn, 19, 26));
-    r_size = tcg_const_i32(4);
-    r_sign = tcg_const_i32(0);
-    t64 = tcg_temp_new_i64();
-    gen_helper_ld_asi(t64, cpu_env, addr, r_asi, r_size, r_sign);
-    tcg_temp_free(r_sign);
-    r_val = tcg_temp_new_i64();
-    tcg_gen_extu_tl_i64(r_val, src);
-    gen_helper_st_asi(cpu_env, addr, r_val, r_asi, r_size);
-    tcg_temp_free_i64(r_val);
-    tcg_temp_free_i32(r_size);
+    if (da.type == GET_ASI_EXCP) {
+        return;
+    }
+
+    save_state(dc);
+    r_asi = tcg_const_i32(da.asi);
+    gen_helper_casx_asi(dst, cpu_env, addr, val1, val2, r_asi);
     tcg_temp_free_i32(r_asi);
-    tcg_gen_trunc_i64_tl(dst, t64);
-    tcg_temp_free_i64(t64);
+    gen_store_gpr(dc, rd, dst);
 }
 
-static inline void gen_ldda_asi(DisasContext *dc, TCGv hi, TCGv addr,
-                                int insn, int rd)
+#elif !defined(CONFIG_USER_ONLY)
+static void gen_ldda_asi(DisasContext *dc, TCGv addr, int insn, int rd)
 {
-    TCGv_i32 r_asi, r_size, r_sign;
-    TCGv t;
-    TCGv_i64 t64;
-
-    r_asi = tcg_const_i32(GET_FIELD(insn, 19, 26));
-    r_size = tcg_const_i32(8);
-    r_sign = tcg_const_i32(0);
-    t64 = tcg_temp_new_i64();
-    gen_helper_ld_asi(t64, cpu_env, addr, r_asi, r_size, r_sign);
-    tcg_temp_free_i32(r_sign);
-    tcg_temp_free_i32(r_size);
-    tcg_temp_free_i32(r_asi);
-
     /* ??? Work around an apparent bug in Ubuntu gcc 4.8.2-10ubuntu2+12,
        whereby "rd + 1" elicits "error: array subscript is above array".
        Since we have already asserted that rd is even, the semantics
        are unchanged.  */
-    t = gen_dest_gpr(dc, rd | 1);
-    tcg_gen_trunc_i64_tl(t, t64);
-    gen_store_gpr(dc, rd | 1, t);
+    TCGv lo = gen_dest_gpr(dc, rd | 1);
+    TCGv hi = gen_dest_gpr(dc, rd);
+    TCGv_i64 t64 = tcg_temp_new_i64();
+    DisasASI da = get_asi(dc, insn, MO_TEQ);
+
+    switch (da.type) {
+    case GET_ASI_EXCP:
+        tcg_temp_free_i64(t64);
+        return;
+    case GET_ASI_DIRECT:
+        gen_address_mask(dc, addr);
+        tcg_gen_qemu_ld_i64(t64, addr, da.mem_idx, da.memop);
+        break;
+    default:
+        {
+            TCGv_i32 r_asi = tcg_const_i32(da.asi);
+            TCGv_i32 r_mop = tcg_const_i32(MO_Q);
+
+            save_state(dc);
+            gen_helper_ld_asi(t64, cpu_env, addr, r_asi, r_mop);
+            tcg_temp_free_i32(r_mop);
+            tcg_temp_free_i32(r_asi);
+        }
+        break;
+    }
 
-    tcg_gen_shri_i64(t64, t64, 32);
-    tcg_gen_trunc_i64_tl(hi, t64);
+    tcg_gen_extr_i64_i32(lo, hi, t64);
     tcg_temp_free_i64(t64);
+    gen_store_gpr(dc, rd | 1, lo);
     gen_store_gpr(dc, rd, hi);
 }
 
-static inline void gen_stda_asi(DisasContext *dc, TCGv hi, TCGv addr,
-                                int insn, int rd)
+static void gen_stda_asi(DisasContext *dc, TCGv hi, TCGv addr,
+                         int insn, int rd)
 {
-    TCGv_i32 r_asi, r_size;
+    DisasASI da = get_asi(dc, insn, MO_TEQ);
     TCGv lo = gen_load_gpr(dc, rd + 1);
     TCGv_i64 t64 = tcg_temp_new_i64();
 
     tcg_gen_concat_tl_i64(t64, lo, hi);
-    r_asi = tcg_const_i32(GET_FIELD(insn, 19, 26));
-    r_size = tcg_const_i32(8);
-    gen_helper_st_asi(cpu_env, addr, t64, r_asi, r_size);
-    tcg_temp_free_i32(r_size);
-    tcg_temp_free_i32(r_asi);
-    tcg_temp_free_i64(t64);
-}
-#endif
-
-#if !defined(CONFIG_USER_ONLY) || defined(TARGET_SPARC64)
-static inline void gen_cas_asi(DisasContext *dc, TCGv addr,
-                               TCGv val2, int insn, int rd)
-{
-    TCGv val1 = gen_load_gpr(dc, rd);
-    TCGv dst = gen_dest_gpr(dc, rd);
-#ifdef TARGET_SPARC64
-    TCGv_i32 r_asi = gen_get_asi(insn, addr);
-#else
-    TCGv_i32 r_asi = tcg_const_i32(GET_FIELD(insn, 19, 26));
-#endif
 
-    gen_helper_cas_asi(dst, cpu_env, addr, val1, val2, r_asi);
-    tcg_temp_free_i32(r_asi);
-    gen_store_gpr(dc, rd, dst);
-}
-
-static inline void gen_ldstub_asi(TCGv dst, TCGv addr, int insn)
-{
-    TCGv_i64 r_val;
-    TCGv_i32 r_asi, r_size;
+    switch (da.type) {
+    case GET_ASI_EXCP:
+        break;
+    case GET_ASI_DIRECT:
+        gen_address_mask(dc, addr);
+        tcg_gen_qemu_st_i64(t64, addr, da.mem_idx, da.memop);
+        break;
+    default:
+        {
+            TCGv_i32 r_asi = tcg_const_i32(da.asi);
+            TCGv_i32 r_mop = tcg_const_i32(MO_Q);
 
-    gen_ld_asi(dst, addr, insn, 1, 0);
+            save_state(dc);
+            gen_helper_st_asi(cpu_env, addr, t64, r_asi, r_mop);
+            tcg_temp_free_i32(r_mop);
+            tcg_temp_free_i32(r_asi);
+        }
+        break;
+    }
 
-    r_val = tcg_const_i64(0xffULL);
-    r_asi = tcg_const_i32(GET_FIELD(insn, 19, 26));
-    r_size = tcg_const_i32(1);
-    gen_helper_st_asi(cpu_env, addr, r_val, r_asi, r_size);
-    tcg_temp_free_i32(r_size);
-    tcg_temp_free_i32(r_asi);
-    tcg_temp_free_i64(r_val);
+    tcg_temp_free_i64(t64);
 }
 #endif
 
@@ -2299,7 +2797,7 @@ static void gen_fmovq(DisasContext *dc, DisasCompare *cmp, int rd, int rs)
     tcg_gen_movcond_i64(cmp->cond, cpu_fpr[qd / 2 + 1], cmp->c1, cmp->c2,
                         cpu_fpr[qs / 2 + 1], cpu_fpr[qd / 2 + 1]);
 
-    gen_update_fprs_dirty(qd);
+    gen_update_fprs_dirty(dc, qd);
 }
 
 #ifndef CONFIG_USER_ONLY
@@ -2711,7 +3209,7 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                     gen_store_gpr(dc, rd, cpu_dst);
                     break;
                 case 0x3: /* V9 rdasi */
-                    tcg_gen_ext_i32_tl(cpu_dst, cpu_asi);
+                    tcg_gen_movi_tl(cpu_dst, dc->asi);
                     gen_store_gpr(dc, rd, cpu_dst);
                     break;
                 case 0x4: /* V9 rdtick */
@@ -2754,7 +3252,8 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                     gen_store_gpr(dc, rd, cpu_gsr);
                     break;
                 case 0x16: /* Softint */
-                    tcg_gen_ext_i32_tl(cpu_dst, cpu_softint);
+                    tcg_gen_ld32s_tl(cpu_dst, cpu_env,
+                                     offsetof(CPUSPARCState, softint));
                     gen_store_gpr(dc, rd, cpu_dst);
                     break;
                 case 0x17: /* Tick compare */
@@ -2972,7 +3471,7 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                 rs1 = GET_FIELD(insn, 13, 17);
                 rs2 = GET_FIELD(insn, 27, 31);
                 xop = GET_FIELD(insn, 18, 26);
-                save_state(dc);
+
                 switch (xop) {
                 case 0x1: /* fmovs */
                     cpu_src1_32 = gen_load_fpr_F(dc, rs2);
@@ -3096,7 +3595,7 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                     break;
                 case 0x3: /* V9 fmovq */
                     CHECK_FPU_FEATURE(dc, FLOAT128);
-                    gen_move_Q(rd, rs2);
+                    gen_move_Q(dc, rd, rs2);
                     break;
                 case 0x6: /* V9 fnegd */
                     gen_ne_fop_DD(dc, rd, rs2, gen_helper_fnegd);
@@ -3147,7 +3646,6 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                 rs1 = GET_FIELD(insn, 13, 17);
                 rs2 = GET_FIELD(insn, 27, 31);
                 xop = GET_FIELD(insn, 18, 26);
-                save_state(dc);
 
 #ifdef TARGET_SPARC64
 #define FMOVR(sz)                                                  \
@@ -3636,11 +4134,18 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                             case 0x3: /* V9 wrasi */
                                 tcg_gen_xor_tl(cpu_tmp0, cpu_src1, cpu_src2);
                                 tcg_gen_andi_tl(cpu_tmp0, cpu_tmp0, 0xff);
-                                tcg_gen_trunc_tl_i32(cpu_asi, cpu_tmp0);
+                                tcg_gen_st32_tl(cpu_tmp0, cpu_env,
+                                                offsetof(CPUSPARCState, asi));
+                                /* End TB to notice changed ASI.  */
+                                save_state(dc);
+                                gen_op_next_insn();
+                                tcg_gen_exit_tb(0);
+                                dc->is_br = 1;
                                 break;
                             case 0x6: /* V9 wrfprs */
                                 tcg_gen_xor_tl(cpu_tmp0, cpu_src1, cpu_src2);
                                 tcg_gen_trunc_tl_i32(cpu_fprs, cpu_tmp0);
+                                dc->fprs_dirty = 0;
                                 save_state(dc);
                                 gen_op_next_insn();
                                 tcg_gen_exit_tb(0);
@@ -4483,8 +4988,6 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
 #endif
 #ifdef TARGET_SPARC64
             } else if (xop == 0x39) { /* V9 return */
-                TCGv_i32 r_const;
-
                 save_state(dc);
                 cpu_src1 = get_src1(dc, insn);
                 cpu_tmp0 = get_temp_tl(dc);
@@ -4502,9 +5005,7 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                 }
                 gen_helper_restore(cpu_env);
                 gen_mov_pc_npc(dc);
-                r_const = tcg_const_i32(3);
-                gen_helper_check_align(cpu_env, cpu_tmp0, r_const);
-                tcg_temp_free_i32(r_const);
+                gen_check_align(cpu_tmp0, 3);
                 tcg_gen_mov_tl(cpu_npc, cpu_tmp0);
                 dc->npc = DYNAMIC_PC;
                 goto jmp_insn;
@@ -4527,16 +5028,12 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                 switch (xop) {
                 case 0x38:      /* jmpl */
                     {
-                        TCGv t;
-                        TCGv_i32 r_const;
-
-                        t = gen_dest_gpr(dc, rd);
+                        TCGv t = gen_dest_gpr(dc, rd);
                         tcg_gen_movi_tl(t, dc->pc);
                         gen_store_gpr(dc, rd, t);
+
                         gen_mov_pc_npc(dc);
-                        r_const = tcg_const_i32(3);
-                        gen_helper_check_align(cpu_env, cpu_tmp0, r_const);
-                        tcg_temp_free_i32(r_const);
+                        gen_check_align(cpu_tmp0, 3);
                         gen_address_mask(dc, cpu_tmp0);
                         tcg_gen_mov_tl(cpu_npc, cpu_tmp0);
                         dc->npc = DYNAMIC_PC;
@@ -4545,14 +5042,10 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
 #if !defined(CONFIG_USER_ONLY) && !defined(TARGET_SPARC64)
                 case 0x39:      /* rett, V9 return */
                     {
-                        TCGv_i32 r_const;
-
                         if (!supervisor(dc))
                             goto priv_insn;
                         gen_mov_pc_npc(dc);
-                        r_const = tcg_const_i32(3);
-                        gen_helper_check_align(cpu_env, cpu_tmp0, r_const);
-                        tcg_temp_free_i32(r_const);
+                        gen_check_align(cpu_tmp0, 3);
                         tcg_gen_mov_tl(cpu_npc, cpu_tmp0);
                         dc->npc = DYNAMIC_PC;
                         gen_helper_rett(cpu_env);
@@ -4648,14 +5141,8 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                     if (rd & 1)
                         goto illegal_insn;
                     else {
-                        TCGv_i32 r_const;
                         TCGv_i64 t64;
 
-                        save_state(dc);
-                        r_const = tcg_const_i32(7);
-                        /* XXX remove alignment check */
-                        gen_helper_check_align(cpu_env, cpu_addr, r_const);
-                        tcg_temp_free_i32(r_const);
                         gen_address_mask(dc, cpu_addr);
                         t64 = tcg_temp_new_i64();
                         tcg_gen_qemu_ld64(t64, cpu_addr, dc->mem_idx);
@@ -4704,89 +5191,34 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                     break;
 #if !defined(CONFIG_USER_ONLY) || defined(TARGET_SPARC64)
                 case 0x10:      /* lda, V9 lduwa, load word alternate */
-#ifndef TARGET_SPARC64
-                    if (IS_IMM)
-                        goto illegal_insn;
-                    if (!supervisor(dc))
-                        goto priv_insn;
-#endif
-                    save_state(dc);
-                    gen_ld_asi(cpu_val, cpu_addr, insn, 4, 0);
+                    gen_ld_asi(dc, cpu_val, cpu_addr, insn, MO_TEUL);
                     break;
                 case 0x11:      /* lduba, load unsigned byte alternate */
-#ifndef TARGET_SPARC64
-                    if (IS_IMM)
-                        goto illegal_insn;
-                    if (!supervisor(dc))
-                        goto priv_insn;
-#endif
-                    save_state(dc);
-                    gen_ld_asi(cpu_val, cpu_addr, insn, 1, 0);
+                    gen_ld_asi(dc, cpu_val, cpu_addr, insn, MO_UB);
                     break;
                 case 0x12:      /* lduha, load unsigned halfword alternate */
-#ifndef TARGET_SPARC64
-                    if (IS_IMM)
-                        goto illegal_insn;
-                    if (!supervisor(dc))
-                        goto priv_insn;
-#endif
-                    save_state(dc);
-                    gen_ld_asi(cpu_val, cpu_addr, insn, 2, 0);
+                    gen_ld_asi(dc, cpu_val, cpu_addr, insn, MO_TEUW);
                     break;
                 case 0x13:      /* ldda, load double word alternate */
-#ifndef TARGET_SPARC64
-                    if (IS_IMM)
-                        goto illegal_insn;
-                    if (!supervisor(dc))
-                        goto priv_insn;
-#endif
-                    if (rd & 1)
+                    if (rd & 1) {
                         goto illegal_insn;
-                    save_state(dc);
-                    gen_ldda_asi(dc, cpu_val, cpu_addr, insn, rd);
+                    }
+                    gen_ldda_asi(dc, cpu_addr, insn, rd);
                     goto skip_move;
                 case 0x19:      /* ldsba, load signed byte alternate */
-#ifndef TARGET_SPARC64
-                    if (IS_IMM)
-                        goto illegal_insn;
-                    if (!supervisor(dc))
-                        goto priv_insn;
-#endif
-                    save_state(dc);
-                    gen_ld_asi(cpu_val, cpu_addr, insn, 1, 1);
+                    gen_ld_asi(dc, cpu_val, cpu_addr, insn, MO_SB);
                     break;
                 case 0x1a:      /* ldsha, load signed halfword alternate */
-#ifndef TARGET_SPARC64
-                    if (IS_IMM)
-                        goto illegal_insn;
-                    if (!supervisor(dc))
-                        goto priv_insn;
-#endif
-                    save_state(dc);
-                    gen_ld_asi(cpu_val, cpu_addr, insn, 2, 1);
+                    gen_ld_asi(dc, cpu_val, cpu_addr, insn, MO_TESW);
                     break;
                 case 0x1d:      /* ldstuba -- XXX: should be atomically */
-#ifndef TARGET_SPARC64
-                    if (IS_IMM)
-                        goto illegal_insn;
-                    if (!supervisor(dc))
-                        goto priv_insn;
-#endif
-                    save_state(dc);
-                    gen_ldstub_asi(cpu_val, cpu_addr, insn);
+                    gen_ldstub_asi(dc, cpu_val, cpu_addr, insn);
                     break;
                 case 0x1f:      /* swapa, swap reg with alt. memory. Also
                                    atomically */
                     CHECK_IU_FEATURE(dc, SWAP);
-#ifndef TARGET_SPARC64
-                    if (IS_IMM)
-                        goto illegal_insn;
-                    if (!supervisor(dc))
-                        goto priv_insn;
-#endif
-                    save_state(dc);
                     cpu_src1 = gen_load_gpr(dc, rd);
-                    gen_swap_asi(cpu_val, cpu_src1, cpu_addr, insn);
+                    gen_swap_asi(dc, cpu_val, cpu_src1, cpu_addr, insn);
                     break;
 
 #ifndef TARGET_SPARC64
@@ -4806,12 +5238,10 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                     tcg_gen_qemu_ld64(cpu_val, cpu_addr, dc->mem_idx);
                     break;
                 case 0x18: /* V9 ldswa */
-                    save_state(dc);
-                    gen_ld_asi(cpu_val, cpu_addr, insn, 4, 1);
+                    gen_ld_asi(dc, cpu_val, cpu_addr, insn, MO_TESL);
                     break;
                 case 0x1b: /* V9 ldxa */
-                    save_state(dc);
-                    gen_ld_asi(cpu_val, cpu_addr, insn, 8, 0);
+                    gen_ld_asi(dc, cpu_val, cpu_addr, insn, MO_TEQ);
                     break;
                 case 0x2d: /* V9 prefetch, no effect */
                     goto skip_move;
@@ -4819,17 +5249,15 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                     if (gen_trap_ifnofpu(dc)) {
                         goto jmp_insn;
                     }
-                    save_state(dc);
-                    gen_ldf_asi(cpu_addr, insn, 4, rd);
-                    gen_update_fprs_dirty(rd);
+                    gen_ldf_asi(dc, cpu_addr, insn, 4, rd);
+                    gen_update_fprs_dirty(dc, rd);
                     goto skip_move;
                 case 0x33: /* V9 lddfa */
                     if (gen_trap_ifnofpu(dc)) {
                         goto jmp_insn;
                     }
-                    save_state(dc);
-                    gen_ldf_asi(cpu_addr, insn, 8, DFPREG(rd));
-                    gen_update_fprs_dirty(DFPREG(rd));
+                    gen_ldf_asi(dc, cpu_addr, insn, 8, DFPREG(rd));
+                    gen_update_fprs_dirty(dc, DFPREG(rd));
                     goto skip_move;
                 case 0x3d: /* V9 prefetcha, no effect */
                     goto skip_move;
@@ -4838,9 +5266,8 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                     if (gen_trap_ifnofpu(dc)) {
                         goto jmp_insn;
                     }
-                    save_state(dc);
-                    gen_ldf_asi(cpu_addr, insn, 16, QFPREG(rd));
-                    gen_update_fprs_dirty(QFPREG(rd));
+                    gen_ldf_asi(dc, cpu_addr, insn, 16, QFPREG(rd));
+                    gen_update_fprs_dirty(dc, QFPREG(rd));
                     goto skip_move;
 #endif
                 default:
@@ -4856,7 +5283,6 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                 if (gen_trap_ifnofpu(dc)) {
                     goto jmp_insn;
                 }
-                save_state(dc);
                 switch (xop) {
                 case 0x20:      /* ldf, load fpreg */
                     gen_address_mask(dc, cpu_addr);
@@ -4872,7 +5298,7 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                     if (rd == 1) {
                         TCGv_i64 t64 = tcg_temp_new_i64();
                         tcg_gen_qemu_ld64(t64, cpu_addr, dc->mem_idx);
-                        gen_helper_ldxfsr(cpu_env, t64);
+                        gen_helper_ldxfsr(cpu_fsr, cpu_env, cpu_fsr, t64);
                         tcg_temp_free_i64(t64);
                         break;
                     }
@@ -4881,7 +5307,7 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                     t0 = get_temp_tl(dc);
                     tcg_gen_qemu_ld32u(t0, cpu_addr, dc->mem_idx);
                     tcg_gen_trunc_tl_i32(cpu_dst_32, t0);
-                    gen_helper_ldfsr(cpu_env, cpu_dst_32);
+                    gen_helper_ldfsr(cpu_fsr, cpu_env, cpu_fsr, cpu_dst_32);
                     break;
                 case 0x22:      /* ldqf, load quad fpreg */
                     {
@@ -4893,7 +5319,7 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                         gen_helper_ldqf(cpu_env, cpu_addr, r_const);
                         tcg_temp_free_i32(r_const);
                         gen_op_store_QT0_fpr(QFPREG(rd));
-                        gen_update_fprs_dirty(QFPREG(rd));
+                        gen_update_fprs_dirty(dc, QFPREG(rd));
                     }
                     break;
                 case 0x23:      /* lddf, load double fpreg */
@@ -4926,18 +5352,11 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                     if (rd & 1)
                         goto illegal_insn;
                     else {
-                        TCGv_i32 r_const;
                         TCGv_i64 t64;
                         TCGv lo;
 
-                        save_state(dc);
                         gen_address_mask(dc, cpu_addr);
-                        r_const = tcg_const_i32(7);
-                        /* XXX remove alignment check */
-                        gen_helper_check_align(cpu_env, cpu_addr, r_const);
-                        tcg_temp_free_i32(r_const);
                         lo = gen_load_gpr(dc, rd + 1);
-
                         t64 = tcg_temp_new_i64();
                         tcg_gen_concat_tl_i64(t64, lo, cpu_val);
                         tcg_gen_qemu_st64(t64, cpu_addr, dc->mem_idx);
@@ -4946,51 +5365,19 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                     break;
 #if !defined(CONFIG_USER_ONLY) || defined(TARGET_SPARC64)
                 case 0x14: /* sta, V9 stwa, store word alternate */
-#ifndef TARGET_SPARC64
-                    if (IS_IMM)
-                        goto illegal_insn;
-                    if (!supervisor(dc))
-                        goto priv_insn;
-#endif
-                    save_state(dc);
-                    gen_st_asi(cpu_val, cpu_addr, insn, 4);
-                    dc->npc = DYNAMIC_PC;
+                    gen_st_asi(dc, cpu_val, cpu_addr, insn, MO_TEUL);
                     break;
                 case 0x15: /* stba, store byte alternate */
-#ifndef TARGET_SPARC64
-                    if (IS_IMM)
-                        goto illegal_insn;
-                    if (!supervisor(dc))
-                        goto priv_insn;
-#endif
-                    save_state(dc);
-                    gen_st_asi(cpu_val, cpu_addr, insn, 1);
-                    dc->npc = DYNAMIC_PC;
+                    gen_st_asi(dc, cpu_val, cpu_addr, insn, MO_UB);
                     break;
                 case 0x16: /* stha, store halfword alternate */
-#ifndef TARGET_SPARC64
-                    if (IS_IMM)
-                        goto illegal_insn;
-                    if (!supervisor(dc))
-                        goto priv_insn;
-#endif
-                    save_state(dc);
-                    gen_st_asi(cpu_val, cpu_addr, insn, 2);
-                    dc->npc = DYNAMIC_PC;
+                    gen_st_asi(dc, cpu_val, cpu_addr, insn, MO_TEUW);
                     break;
                 case 0x17: /* stda, store double word alternate */
-#ifndef TARGET_SPARC64
-                    if (IS_IMM)
-                        goto illegal_insn;
-                    if (!supervisor(dc))
-                        goto priv_insn;
-#endif
-                    if (rd & 1)
+                    if (rd & 1) {
                         goto illegal_insn;
-                    else {
-                        save_state(dc);
-                        gen_stda_asi(dc, cpu_val, cpu_addr, insn, rd);
                     }
+                    gen_stda_asi(dc, cpu_val, cpu_addr, insn, rd);
                     break;
 #endif
 #ifdef TARGET_SPARC64
@@ -4999,9 +5386,7 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                     tcg_gen_qemu_st64(cpu_val, cpu_addr, dc->mem_idx);
                     break;
                 case 0x1e: /* V9 stxa */
-                    save_state(dc);
-                    gen_st_asi(cpu_val, cpu_addr, insn, 8);
-                    dc->npc = DYNAMIC_PC;
+                    gen_st_asi(dc, cpu_val, cpu_addr, insn, MO_TEQ);
                     break;
 #endif
                 default:
@@ -5011,7 +5396,6 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                 if (gen_trap_ifnofpu(dc)) {
                     goto jmp_insn;
                 }
-                save_state(dc);
                 switch (xop) {
                 case 0x24: /* stf, store fpreg */
                     {
@@ -5024,17 +5408,14 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                     break;
                 case 0x25: /* stfsr, V9 stxfsr */
                     {
-                        TCGv t = get_temp_tl(dc);
-
-                        tcg_gen_ld_tl(t, cpu_env, offsetof(CPUSPARCState, fsr));
 #ifdef TARGET_SPARC64
                         gen_address_mask(dc, cpu_addr);
                         if (rd == 1) {
-                            tcg_gen_qemu_st64(t, cpu_addr, dc->mem_idx);
+                            tcg_gen_qemu_st64(cpu_fsr, cpu_addr, dc->mem_idx);
                             break;
                         }
 #endif
-                        tcg_gen_qemu_st32(t, cpu_addr, dc->mem_idx);
+                        tcg_gen_qemu_st32(cpu_fsr, cpu_addr, dc->mem_idx);
                     }
                     break;
                 case 0x26:
@@ -5073,34 +5454,29 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                     goto illegal_insn;
                 }
             } else if (xop > 0x33 && xop < 0x3f) {
-                save_state(dc);
                 switch (xop) {
 #ifdef TARGET_SPARC64
                 case 0x34: /* V9 stfa */
                     if (gen_trap_ifnofpu(dc)) {
                         goto jmp_insn;
                     }
-                    gen_stf_asi(cpu_addr, insn, 4, rd);
+                    gen_stf_asi(dc, cpu_addr, insn, 4, rd);
                     break;
                 case 0x36: /* V9 stqfa */
                     {
-                        TCGv_i32 r_const;
-
                         CHECK_FPU_FEATURE(dc, FLOAT128);
                         if (gen_trap_ifnofpu(dc)) {
                             goto jmp_insn;
                         }
-                        r_const = tcg_const_i32(7);
-                        gen_helper_check_align(cpu_env, cpu_addr, r_const);
-                        tcg_temp_free_i32(r_const);
-                        gen_stf_asi(cpu_addr, insn, 16, QFPREG(rd));
+                        gen_check_align(cpu_addr, 7);
+                        gen_stf_asi(dc, cpu_addr, insn, 16, QFPREG(rd));
                     }
                     break;
                 case 0x37: /* V9 stdfa */
                     if (gen_trap_ifnofpu(dc)) {
                         goto jmp_insn;
                     }
-                    gen_stf_asi(cpu_addr, insn, 8, DFPREG(rd));
+                    gen_stf_asi(dc, cpu_addr, insn, 8, DFPREG(rd));
                     break;
                 case 0x3e: /* V9 casxa */
                     rs2 = GET_FIELD(insn, 27, 31);
@@ -5118,13 +5494,6 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
                 case 0x3c: /* V9 or LEON3 casa */
 #ifndef TARGET_SPARC64
                     CHECK_IU_FEATURE(dc, CASA);
-                    if (IS_IMM) {
-                        goto illegal_insn;
-                    }
-                    /* LEON3 allows CASA from user space with ASI 0xa */
-                    if ((GET_FIELD(insn, 19, 26) != 0xa) && !supervisor(dc)) {
-                        goto priv_insn;
-                    }
 #endif
                     rs2 = GET_FIELD(insn, 27, 31);
                     cpu_src2 = gen_load_gpr(dc, rs2);
@@ -5155,63 +5524,27 @@ static void disas_sparc_insn(DisasContext * dc, unsigned int insn)
  jmp_insn:
     goto egress;
  illegal_insn:
-    {
-        TCGv_i32 r_const;
-
-        save_state(dc);
-        r_const = tcg_const_i32(TT_ILL_INSN);
-        gen_helper_raise_exception(cpu_env, r_const);
-        tcg_temp_free_i32(r_const);
-        dc->is_br = 1;
-    }
+    gen_exception(dc, TT_ILL_INSN);
     goto egress;
  unimp_flush:
-    {
-        TCGv_i32 r_const;
-
-        save_state(dc);
-        r_const = tcg_const_i32(TT_UNIMP_FLUSH);
-        gen_helper_raise_exception(cpu_env, r_const);
-        tcg_temp_free_i32(r_const);
-        dc->is_br = 1;
-    }
+    gen_exception(dc, TT_UNIMP_FLUSH);
     goto egress;
 #if !defined(CONFIG_USER_ONLY)
  priv_insn:
-    {
-        TCGv_i32 r_const;
-
-        save_state(dc);
-        r_const = tcg_const_i32(TT_PRIV_INSN);
-        gen_helper_raise_exception(cpu_env, r_const);
-        tcg_temp_free_i32(r_const);
-        dc->is_br = 1;
-    }
+    gen_exception(dc, TT_PRIV_INSN);
     goto egress;
 #endif
  nfpu_insn:
-    save_state(dc);
-    gen_op_fpexception_im(FSR_FTT_UNIMPFPOP);
-    dc->is_br = 1;
+    gen_op_fpexception_im(dc, FSR_FTT_UNIMPFPOP);
     goto egress;
 #if !defined(CONFIG_USER_ONLY) && !defined(TARGET_SPARC64)
  nfq_insn:
-    save_state(dc);
-    gen_op_fpexception_im(FSR_FTT_SEQ_ERROR);
-    dc->is_br = 1;
+    gen_op_fpexception_im(dc, FSR_FTT_SEQ_ERROR);
     goto egress;
 #endif
 #ifndef TARGET_SPARC64
  ncp_insn:
-    {
-        TCGv r_const;
-
-        save_state(dc);
-        r_const = tcg_const_i32(TT_NCP_INSN);
-        gen_helper_raise_exception(cpu_env, r_const);
-        tcg_temp_free(r_const);
-        dc->is_br = 1;
-    }
+    gen_exception(dc, TT_NCP_INSN);
     goto egress;
 #endif
  egress:
@@ -5248,11 +5581,15 @@ void gen_intermediate_code(CPUSPARCState * env, TranslationBlock * tb)
     last_pc = dc->pc;
     dc->npc = (target_ulong) tb->cs_base;
     dc->cc_op = CC_OP_DYNAMIC;
-    dc->mem_idx = cpu_mmu_index(env, false);
+    dc->mem_idx = tb->flags & TB_FLAG_MMU_MASK;
     dc->def = env->def;
     dc->fpu_enabled = tb_fpu_enabled(tb->flags);
     dc->address_mask_32bit = tb_am_enabled(tb->flags);
     dc->singlestep = (cs->singlestep_enabled || singlestep);
+#ifdef TARGET_SPARC64
+    dc->fprs_dirty = 0;
+    dc->asi = (tb->flags >> TB_FLAG_ASI_SHIFT) & 0xff;
+#endif
 
     num_insns = 0;
     max_insns = tb->cflags & CF_COUNT_MASK;
@@ -5362,9 +5699,7 @@ void gen_intermediate_code_init(CPUSPARCState *env)
     static const struct { TCGv_i32 *ptr; int off; const char *name; } r32[] = {
 #ifdef TARGET_SPARC64
         { &cpu_xcc, offsetof(CPUSPARCState, xcc), "xcc" },
-        { &cpu_asi, offsetof(CPUSPARCState, asi), "asi" },
         { &cpu_fprs, offsetof(CPUSPARCState, fprs), "fprs" },
-        { &cpu_softint, offsetof(CPUSPARCState, softint), "softint" },
 #else
         { &cpu_wim, offsetof(CPUSPARCState, wim), "wim" },
 #endif
diff --git a/target-tilegx/cpu.h b/target-tilegx/cpu.h
index d74032925b..1735427233 100644
--- a/target-tilegx/cpu.h
+++ b/target-tilegx/cpu.h
@@ -16,8 +16,9 @@
  * 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_TILEGX_H
-#define CPU_TILEGX_H
+
+#ifndef TILEGX_CPU_H
+#define TILEGX_CPU_H
 
 #include "qemu-common.h"
 
diff --git a/target-tilegx/opcode_tilegx.h b/target-tilegx/opcode_tilegx.h
index 989436d2f8..55376be4cf 100644
--- a/target-tilegx/opcode_tilegx.h
+++ b/target-tilegx/opcode_tilegx.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef __ARCH_OPCODE_H__
-#define __ARCH_OPCODE_H__
+#ifndef OPCODE_TILEGX_H
+#define OPCODE_TILEGX_H
 
 #ifndef __ASSEMBLER__
 
@@ -1403,4 +1403,4 @@ enum
 
 #endif /* __ASSEMBLER__ */
 
-#endif /* __ARCH_OPCODE_H__ */
+#endif /* OPCODE_TILEGX_H */
diff --git a/target-tricore/cpu-qom.h b/target-tricore/cpu-qom.h
index 399c98f2d6..6a69756126 100644
--- a/target-tricore/cpu-qom.h
+++ b/target-tricore/cpu-qom.h
@@ -41,4 +41,4 @@ typedef struct TriCoreCPUClass {
 
 typedef struct TriCoreCPU TriCoreCPU;
 
-#endif /*QEMU_TRICORE_CPU_QOM_H */
+#endif /* QEMU_TRICORE_CPU_QOM_H */
diff --git a/target-tricore/cpu.h b/target-tricore/cpu.h
index a298d63eea..a3493a123c 100644
--- a/target-tricore/cpu.h
+++ b/target-tricore/cpu.h
@@ -16,8 +16,9 @@
  * 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/>.
  */
-#if !defined(__TRICORE_CPU_H__)
-#define __TRICORE_CPU_H__
+
+#ifndef TRICORE_CPU_H
+#define TRICORE_CPU_H
 
 #include "tricore-defs.h"
 #include "qemu-common.h"
@@ -420,4 +421,4 @@ int cpu_tricore_handle_mmu_fault(CPUState *cpu, target_ulong address,
                                  int rw, int mmu_idx);
 #define cpu_handle_mmu_fault cpu_tricore_handle_mmu_fault
 
-#endif /*__TRICORE_CPU_H__ */
+#endif /* TRICORE_CPU_H */
diff --git a/target-tricore/op_helper.c b/target-tricore/op_helper.c
index 3382a126bd..ac02e0a36b 100644
--- a/target-tricore/op_helper.c
+++ b/target-tricore/op_helper.c
@@ -2828,11 +2828,11 @@ static inline void QEMU_NORETURN do_raise_exception_err(CPUTriCoreState *env,
     cpu_loop_exit(cs);
 }
 
-void tlb_fill(CPUState *cs, target_ulong addr, int is_write, int mmu_idx,
-              uintptr_t retaddr)
+void tlb_fill(CPUState *cs, target_ulong addr, MMUAccessType access_type,
+              int mmu_idx, uintptr_t retaddr)
 {
     int ret;
-    ret = cpu_tricore_handle_mmu_fault(cs, addr, is_write, mmu_idx);
+    ret = cpu_tricore_handle_mmu_fault(cs, addr, access_type, mmu_idx);
     if (ret) {
         TriCoreCPU *cpu = TRICORE_CPU(cs);
         CPUTriCoreState *env = &cpu->env;
diff --git a/target-tricore/tricore-defs.h b/target-tricore/tricore-defs.h
index 4350b03044..40abfaac14 100644
--- a/target-tricore/tricore-defs.h
+++ b/target-tricore/tricore-defs.h
@@ -15,8 +15,8 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 
-#if !defined(__QEMU_TRICORE_DEFS_H__)
-#define __QEMU_TRICORE_DEFS_H__
+#ifndef QEMU_TRICORE_DEFS_H
+#define QEMU_TRICORE_DEFS_H
 
 #define TARGET_PAGE_BITS 14
 #define TARGET_LONG_BITS 32
@@ -25,4 +25,4 @@
 
 #define TRICORE_TLB_MAX 128
 
-#endif /* __QEMU_TRICORE_DEFS_H__ */
+#endif /* QEMU_TRICORE_DEFS_H */
diff --git a/target-unicore32/cpu.h b/target-unicore32/cpu.h
index 83f758496a..7b5b405e79 100644
--- a/target-unicore32/cpu.h
+++ b/target-unicore32/cpu.h
@@ -8,8 +8,9 @@
  * published by the Free Software Foundation, or (at your option) any
  * later version. See the COPYING file in the top-level directory.
  */
-#ifndef QEMU_UNICORE32_CPU_H
-#define QEMU_UNICORE32_CPU_H
+
+#ifndef UNICORE32_CPU_H
+#define UNICORE32_CPU_H
 
 #define TARGET_LONG_BITS                32
 #define TARGET_PAGE_BITS                12
@@ -184,4 +185,4 @@ int uc32_cpu_handle_mmu_fault(CPUState *cpu, vaddr address, int rw,
 void uc32_translate_init(void);
 void switch_mode(CPUUniCore32State *, int);
 
-#endif /* QEMU_UNICORE32_CPU_H */
+#endif /* UNICORE32_CPU_H */
diff --git a/target-unicore32/op_helper.c b/target-unicore32/op_helper.c
index a782d33843..0872c29faa 100644
--- a/target-unicore32/op_helper.c
+++ b/target-unicore32/op_helper.c
@@ -244,12 +244,12 @@ uint32_t HELPER(ror_cc)(CPUUniCore32State *env, uint32_t x, uint32_t i)
 }
 
 #ifndef CONFIG_USER_ONLY
-void tlb_fill(CPUState *cs, target_ulong addr, int is_write,
+void tlb_fill(CPUState *cs, target_ulong addr, MMUAccessType access_type,
               int mmu_idx, uintptr_t retaddr)
 {
     int ret;
 
-    ret = uc32_cpu_handle_mmu_fault(cs, addr, is_write, mmu_idx);
+    ret = uc32_cpu_handle_mmu_fault(cs, addr, access_type, mmu_idx);
     if (unlikely(ret)) {
         if (retaddr) {
             /* now we have a real cpu fault */
diff --git a/target-unicore32/softmmu.c b/target-unicore32/softmmu.c
index a34026a524..e7152e72e0 100644
--- a/target-unicore32/softmmu.c
+++ b/target-unicore32/softmmu.c
@@ -13,7 +13,7 @@
 #endif
 
 #include "qemu/osdep.h"
-#include <cpu.h>
+#include "cpu.h"
 #include "exec/exec-all.h"
 
 #undef DEBUG_UC32
diff --git a/target-xtensa/core-dc232b/core-isa.h b/target-xtensa/core-dc232b/core-isa.h
index 69f1065574..a9935b87af 100644
--- a/target-xtensa/core-dc232b/core-isa.h
+++ b/target-xtensa/core-dc232b/core-isa.h
@@ -8,9 +8,8 @@
  * Copyright (c) 1999-2007 Tensilica Inc.
  */
 
-#ifndef _XTENSA_CORE_CONFIGURATION_H
-#define _XTENSA_CORE_CONFIGURATION_H
-
+#ifndef XTENSA_DC232B_CORE_ISA_H
+#define XTENSA_DC232B_CORE_ISA_H
 
 /****************************************************************************
             Parameters Useful for Any Code, USER or PRIVILEGED
@@ -420,4 +419,4 @@
 #endif /* !XTENSA_HAL_NON_PRIVILEGED_ONLY */
 
 
-#endif /* _XTENSA_CORE_CONFIGURATION_H */
+#endif /* XTENSA_DC232B_CORE_ISA_H */
diff --git a/target-xtensa/core-dc233c/core-isa.h b/target-xtensa/core-dc233c/core-isa.h
index e82c3cbe48..ff92b7f3ed 100644
--- a/target-xtensa/core-dc233c/core-isa.h
+++ b/target-xtensa/core-dc233c/core-isa.h
@@ -28,9 +28,8 @@
    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.  */
 
-#ifndef _XTENSA_CORE_CONFIGURATION_H
-#define _XTENSA_CORE_CONFIGURATION_H
-
+#ifndef XTENSA_DC233C_CORE_ISA_H
+#define XTENSA_DC233C_CORE_ISA_H
 
 /****************************************************************************
             Parameters Useful for Any Code, USER or PRIVILEGED
@@ -471,4 +470,4 @@ usable for an MMU-based OS */
 #endif /* !XTENSA_HAL_NON_PRIVILEGED_ONLY */
 
 
-#endif /* _XTENSA_CORE_CONFIGURATION_H */
+#endif /* XTENSA_DC233C_CORE_ISA_H */
diff --git a/target-xtensa/core-fsf/core-isa.h b/target-xtensa/core-fsf/core-isa.h
index b519d6c741..fb2bb8f2cb 100644
--- a/target-xtensa/core-fsf/core-isa.h
+++ b/target-xtensa/core-fsf/core-isa.h
@@ -8,9 +8,8 @@
  * Copyright (C) 1999-2006 Tensilica Inc.
  */
 
-#ifndef _XTENSA_CORE_H
-#define _XTENSA_CORE_H
-
+#ifndef XTENSA_FSF_CORE_ISA_H
+#define XTENSA_FSF_CORE_ISA_H
 
 /****************************************************************************
             Parameters Useful for Any Code, USER or PRIVILEGED
@@ -358,4 +357,4 @@
 #endif /* !XTENSA_HAL_NON_PRIVILEGED_ONLY */
 
 
-#endif /* _XTENSA_CORE_CONFIGURATION_H */
+#endif /* XTENSA_FSF_CORE_ISA_H */
diff --git a/target-xtensa/cpu.h b/target-xtensa/cpu.h
index 8477ec963a..7fe82a37af 100644
--- a/target-xtensa/cpu.h
+++ b/target-xtensa/cpu.h
@@ -25,8 +25,8 @@
  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef CPU_XTENSA_H
-#define CPU_XTENSA_H
+#ifndef XTENSA_CPU_H
+#define XTENSA_CPU_H
 
 #define ALIGNED_ONLY
 #define TARGET_LONG_BITS 32
@@ -414,7 +414,8 @@ hwaddr xtensa_cpu_get_phys_page_debug(CPUState *cpu, vaddr addr);
 int xtensa_cpu_gdb_read_register(CPUState *cpu, uint8_t *buf, int reg);
 int xtensa_cpu_gdb_write_register(CPUState *cpu, uint8_t *buf, int reg);
 void xtensa_cpu_do_unaligned_access(CPUState *cpu, vaddr addr,
-                                    int is_write, int is_user, uintptr_t retaddr);
+                                    MMUAccessType access_type,
+                                    int mmu_idx, uintptr_t retaddr);
 
 #define cpu_signal_handler cpu_xtensa_signal_handler
 #define cpu_list xtensa_cpu_list
diff --git a/target-xtensa/op_helper.c b/target-xtensa/op_helper.c
index bc3667f0ab..0a4b2147bc 100644
--- a/target-xtensa/op_helper.c
+++ b/target-xtensa/op_helper.c
@@ -35,7 +35,8 @@
 #include "qemu/timer.h"
 
 void xtensa_cpu_do_unaligned_access(CPUState *cs,
-        vaddr addr, int is_write, int is_user, uintptr_t retaddr)
+        vaddr addr, MMUAccessType access_type,
+        int mmu_idx, uintptr_t retaddr)
 {
     XtensaCPU *cpu = XTENSA_CPU(cs);
     CPUXtensaState *env = &cpu->env;
@@ -48,19 +49,19 @@ void xtensa_cpu_do_unaligned_access(CPUState *cs,
     }
 }
 
-void tlb_fill(CPUState *cs,
-              target_ulong vaddr, int is_write, int mmu_idx, uintptr_t retaddr)
+void tlb_fill(CPUState *cs, target_ulong vaddr, MMUAccessType access_type,
+              int mmu_idx, uintptr_t retaddr)
 {
     XtensaCPU *cpu = XTENSA_CPU(cs);
     CPUXtensaState *env = &cpu->env;
     uint32_t paddr;
     uint32_t page_size;
     unsigned access;
-    int ret = xtensa_get_physical_addr(env, true, vaddr, is_write, mmu_idx,
+    int ret = xtensa_get_physical_addr(env, true, vaddr, access_type, mmu_idx,
             &paddr, &page_size, &access);
 
     qemu_log_mask(CPU_LOG_MMU, "%s(%08x, %d, %d) -> %08x, ret = %d\n",
-                  __func__, vaddr, is_write, mmu_idx, paddr, ret);
+                  __func__, vaddr, access_type, mmu_idx, paddr, ret);
 
     if (ret == 0) {
         tlb_set_page(cs,
diff --git a/tcg/aarch64/tcg-target.h b/tcg/aarch64/tcg-target.h
index 19a04a6e75..a1d101f891 100644
--- a/tcg/aarch64/tcg-target.h
+++ b/tcg/aarch64/tcg-target.h
@@ -10,8 +10,8 @@
  * See the COPYING file in the top-level directory for details.
  */
 
-#ifndef TCG_TARGET_AARCH64
-#define TCG_TARGET_AARCH64 1
+#ifndef AARCH64_TCG_TARGET_H
+#define AARCH64_TCG_TARGET_H
 
 #define TCG_TARGET_INSN_UNIT_SIZE  4
 #define TCG_TARGET_TLB_DISPLACEMENT_BITS 24
@@ -106,4 +106,4 @@ static inline void flush_icache_range(uintptr_t start, uintptr_t stop)
     __builtin___clear_cache((char *)start, (char *)stop);
 }
 
-#endif /* TCG_TARGET_AARCH64 */
+#endif /* AARCH64_TCG_TARGET_H */
diff --git a/tcg/arm/tcg-target.h b/tcg/arm/tcg-target.h
index 6559f80b71..a0e1acfa77 100644
--- a/tcg/arm/tcg-target.h
+++ b/tcg/arm/tcg-target.h
@@ -22,8 +22,9 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
-#ifndef TCG_TARGET_ARM 
-#define TCG_TARGET_ARM 1
+
+#ifndef ARM_TCG_TARGET_H
+#define ARM_TCG_TARGET_H
 
 #undef TCG_TARGET_STACK_GROWSUP
 #define TCG_TARGET_INSN_UNIT_SIZE 4
diff --git a/tcg/i386/tcg-target.h b/tcg/i386/tcg-target.h
index 92be341713..524cfc61fd 100644
--- a/tcg/i386/tcg-target.h
+++ b/tcg/i386/tcg-target.h
@@ -21,8 +21,9 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
-#ifndef TCG_TARGET_I386 
-#define TCG_TARGET_I386 1
+
+#ifndef I386_TCG_TARGET_H
+#define I386_TCG_TARGET_H
 
 #define TCG_TARGET_INSN_UNIT_SIZE  1
 #define TCG_TARGET_TLB_DISPLACEMENT_BITS 31
diff --git a/tcg/ia64/tcg-target.h b/tcg/ia64/tcg-target.h
index ae9b79f02f..6dddb7f772 100644
--- a/tcg/ia64/tcg-target.h
+++ b/tcg/ia64/tcg-target.h
@@ -22,8 +22,9 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
-#ifndef TCG_TARGET_IA64 
-#define TCG_TARGET_IA64 1
+
+#ifndef IA64_TCG_TARGET_H
+#define IA64_TCG_TARGET_H
 
 #define TCG_TARGET_INSN_UNIT_SIZE 16
 #define TCG_TARGET_TLB_DISPLACEMENT_BITS 21
diff --git a/tcg/mips/tcg-target.h b/tcg/mips/tcg-target.h
index b1cda37b66..3aeac87614 100644
--- a/tcg/mips/tcg-target.h
+++ b/tcg/mips/tcg-target.h
@@ -23,8 +23,9 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
-#ifndef TCG_TARGET_MIPS 
-#define TCG_TARGET_MIPS 1
+
+#ifndef MIPS_TCG_TARGET_H
+#define MIPS_TCG_TARGET_H
 
 #define TCG_TARGET_INSN_UNIT_SIZE 4
 #define TCG_TARGET_TLB_DISPLACEMENT_BITS 16
diff --git a/tcg/ppc/tcg-target.h b/tcg/ppc/tcg-target.h
index b4f0818762..dd032f286b 100644
--- a/tcg/ppc/tcg-target.h
+++ b/tcg/ppc/tcg-target.h
@@ -21,8 +21,9 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
-#ifndef TCG_TARGET_PPC64 
-#define TCG_TARGET_PPC64 1
+
+#ifndef PPC_TCG_TARGET_H
+#define PPC_TCG_TARGET_H
 
 #ifdef _ARCH_PPC64
 # define TCG_TARGET_REG_BITS  64
diff --git a/tcg/s390/tcg-target.h b/tcg/s390/tcg-target.h
index d9dc038733..0c1af244f3 100644
--- a/tcg/s390/tcg-target.h
+++ b/tcg/s390/tcg-target.h
@@ -21,8 +21,9 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
-#ifndef TCG_TARGET_S390 
-#define TCG_TARGET_S390 1
+
+#ifndef S390_TCG_TARGET_H
+#define S390_TCG_TARGET_H
 
 #define TCG_TARGET_INSN_UNIT_SIZE 2
 #define TCG_TARGET_TLB_DISPLACEMENT_BITS 19
diff --git a/tcg/sparc/tcg-target.h b/tcg/sparc/tcg-target.h
index 2cd72d2d41..88f9c90f5f 100644
--- a/tcg/sparc/tcg-target.h
+++ b/tcg/sparc/tcg-target.h
@@ -21,8 +21,9 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
-#ifndef TCG_TARGET_SPARC 
-#define TCG_TARGET_SPARC 1
+
+#ifndef SPARC_TCG_TARGET_H
+#define SPARC_TCG_TARGET_H
 
 #define TCG_TARGET_REG_BITS 64
 
diff --git a/tcg/tci/tcg-target.h b/tcg/tci/tcg-target.h
index 3942f9cccf..868228b2e7 100644
--- a/tcg/tci/tcg-target.h
+++ b/tcg/tci/tcg-target.h
@@ -37,10 +37,9 @@
  * Therefore, we need both 32 and 64 bit virtual machines (interpreter).
  */
 
-#if !defined(TCG_TARGET_H)
+#ifndef TCG_TARGET_H
 #define TCG_TARGET_H
 
-
 #define TCG_TARGET_INTERPRETER 1
 #define TCG_TARGET_INSN_UNIT_SIZE 1
 #define TCG_TARGET_TLB_DISPLACEMENT_BITS 32
diff --git a/tests/boot-sector.h b/tests/boot-sector.h
index 38be0290e3..f64b477aa3 100644
--- a/tests/boot-sector.h
+++ b/tests/boot-sector.h
@@ -11,8 +11,8 @@
  * See the COPYING file in the top-level directory.
  */
 
-#ifndef TEST_BOOT_SECTOR
-#define TEST_BOOT_SECTOR
+#ifndef TEST_BOOT_SECTOR_H
+#define TEST_BOOT_SECTOR_H
 
 /* Create boot disk file.  */
 int boot_sector_init(const char *fname);
@@ -23,4 +23,4 @@ void boot_sector_test(void);
 /* unlink boot disk file.  */
 void boot_sector_cleanup(const char *fname);
 
-#endif /* TEST_BOOT_SECTOR */
+#endif /* TEST_BOOT_SECTOR_H */
diff --git a/tests/libqos/ahci.h b/tests/libqos/ahci.h
index 71dd7a6e5a..c69fb5ae90 100644
--- a/tests/libqos/ahci.h
+++ b/tests/libqos/ahci.h
@@ -1,5 +1,5 @@
-#ifndef __libqos_ahci_h
-#define __libqos_ahci_h
+#ifndef LIBQOS_AHCI_H
+#define LIBQOS_AHCI_H
 
 /*
  * AHCI qtest library functions and definitions
diff --git a/tests/libqos/libqos-pc.h b/tests/libqos/libqos-pc.h
index b1820c5739..a0e4c45516 100644
--- a/tests/libqos/libqos-pc.h
+++ b/tests/libqos/libqos-pc.h
@@ -1,5 +1,5 @@
-#ifndef __libqos_pc_h
-#define __libqos_pc_h
+#ifndef LIBQOS_PC_H
+#define LIBQOS_PC_H
 
 #include "libqos/libqos.h"
 
diff --git a/tests/libqos/libqos.h b/tests/libqos/libqos.h
index ca14d2e9fe..604980d125 100644
--- a/tests/libqos/libqos.h
+++ b/tests/libqos/libqos.h
@@ -1,5 +1,5 @@
-#ifndef __libqos_h
-#define __libqos_h
+#ifndef LIBQOS_H
+#define LIBQOS_H
 
 #include "libqtest.h"
 #include "libqos/pci.h"
diff --git a/tests/postcopy-test.c b/tests/postcopy-test.c
index 35d5180173..16465ab57e 100644
--- a/tests/postcopy-test.c
+++ b/tests/postcopy-test.c
@@ -15,11 +15,10 @@
 #include "libqtest.h"
 #include "qemu/option.h"
 #include "qemu/range.h"
+#include "qemu/sockets.h"
 #include "sysemu/char.h"
 #include "sysemu/sysemu.h"
 
-#include <qemu/sockets.h>
-
 const unsigned start_address = 1024 * 1024;
 const unsigned end_address = 100 * 1024 * 1024;
 bool got_stop;
diff --git a/tests/qemu-iotests/093 b/tests/qemu-iotests/093
index ce8e13cb49..ffcb271b36 100755
--- a/tests/qemu-iotests/093
+++ b/tests/qemu-iotests/093
@@ -184,5 +184,103 @@ class ThrottleTestCase(iotests.QMPTestCase):
 class ThrottleTestCoroutine(ThrottleTestCase):
     test_img = "null-co://"
 
+class ThrottleTestGroupNames(iotests.QMPTestCase):
+    test_img = "null-aio://"
+    max_drives = 3
+
+    def setUp(self):
+        self.vm = iotests.VM()
+        for i in range(0, self.max_drives):
+            self.vm.add_drive(self.test_img, "throttling.iops-total=100")
+        self.vm.launch()
+
+    def tearDown(self):
+        self.vm.shutdown()
+
+    def set_io_throttle(self, device, params):
+        params["device"] = device
+        result = self.vm.qmp("block_set_io_throttle", conv_keys=False, **params)
+        self.assert_qmp(result, 'return', {})
+
+    def verify_name(self, device, name):
+        result = self.vm.qmp("query-block")
+        for r in result["return"]:
+            if r["device"] == device:
+                info = r["inserted"]
+                if name:
+                    self.assertEqual(info["group"], name)
+                else:
+                    self.assertFalse(info.has_key('group'))
+                return
+
+        raise Exception("No group information found for '%s'" % device)
+
+    def test_group_naming(self):
+        params = {"bps": 0,
+                  "bps_rd": 0,
+                  "bps_wr": 0,
+                  "iops": 0,
+                  "iops_rd": 0,
+                  "iops_wr": 0}
+
+        # Check the drives added using the command line.
+        # The default throttling group name is the device name.
+        for i in range(self.max_drives):
+            devname = "drive%d" % i
+            self.verify_name(devname, devname)
+
+        # Clear throttling settings => the group name is gone.
+        for i in range(self.max_drives):
+            devname = "drive%d" % i
+            self.set_io_throttle(devname, params)
+            self.verify_name(devname, None)
+
+        # Set throttling settings using block_set_io_throttle and
+        # check the default group names.
+        params["iops"] = 10
+        for i in range(self.max_drives):
+            devname = "drive%d" % i
+            self.set_io_throttle(devname, params)
+            self.verify_name(devname, devname)
+
+        # Set a custom group name for each device
+        for i in range(3):
+            devname = "drive%d" % i
+            groupname = "group%d" % i
+            params['group'] = groupname
+            self.set_io_throttle(devname, params)
+            self.verify_name(devname, groupname)
+
+        # Put drive0 in group1 and check that all other devices remain
+        # unchanged
+        params['group'] = 'group1'
+        self.set_io_throttle('drive0', params)
+        self.verify_name('drive0', 'group1')
+        for i in range(1, self.max_drives):
+            devname = "drive%d" % i
+            groupname = "group%d" % i
+            self.verify_name(devname, groupname)
+
+        # Put drive0 in group2 and check that all other devices remain
+        # unchanged
+        params['group'] = 'group2'
+        self.set_io_throttle('drive0', params)
+        self.verify_name('drive0', 'group2')
+        for i in range(1, self.max_drives):
+            devname = "drive%d" % i
+            groupname = "group%d" % i
+            self.verify_name(devname, groupname)
+
+        # Clear throttling settings from drive0 check that all other
+        # devices remain unchanged
+        params["iops"] = 0
+        self.set_io_throttle('drive0', params)
+        self.verify_name('drive0', None)
+        for i in range(1, self.max_drives):
+            devname = "drive%d" % i
+            groupname = "group%d" % i
+            self.verify_name(devname, groupname)
+
+
 if __name__ == '__main__':
     iotests.main(supported_fmts=["raw"])
diff --git a/tests/qemu-iotests/093.out b/tests/qemu-iotests/093.out
index 89968f35d7..914e3737bd 100644
--- a/tests/qemu-iotests/093.out
+++ b/tests/qemu-iotests/093.out
@@ -1,5 +1,5 @@
-....
+.....
 ----------------------------------------------------------------------
-Ran 4 tests
+Ran 5 tests
 
 OK
diff --git a/tests/qemu-iotests/157 b/tests/qemu-iotests/157
new file mode 100755
index 0000000000..8d939cb747
--- /dev/null
+++ b/tests/qemu-iotests/157
@@ -0,0 +1,89 @@
+#!/bin/bash
+#
+# Test command line configuration of block devices with qdev
+#
+# Copyright (C) 2016 Red Hat, 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.
+#
+# 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=kwolf@redhat.com
+
+seq="$(basename $0)"
+echo "QA output created by $seq"
+
+here="$PWD"
+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 generic
+_supported_proto file
+_supported_os Linux
+
+function do_run_qemu()
+{
+    echo Testing: "$@"
+    (
+        if ! test -t 0; then
+            while read cmd; do
+                echo $cmd
+            done
+        fi
+        echo quit
+    ) | $QEMU -nodefaults -nographic -monitor stdio -serial none "$@"
+    echo
+}
+
+function run_qemu()
+{
+    do_run_qemu "$@" 2>&1 | _filter_testdir | _filter_imgfmt \
+                          | _filter_qemu | _filter_generated_node_ids
+}
+
+
+size=128M
+drive="if=none,file=$TEST_IMG,driver=$IMGFMT"
+
+_make_test_img $size
+
+echo
+echo "=== Setting WCE with qdev and with manually created BB ==="
+echo
+
+# The qdev option takes precedence, but if it isn't given or 'auto', the BB
+# option is used instead.
+
+for cache in "writeback" "writethrough"; do
+    for wce in "" ",write-cache=auto" ",write-cache=on" ",write-cache=off"; do
+        echo "info block" \
+            | run_qemu -drive "$drive,cache=$cache" \
+                       -device "virtio-blk,drive=none0$wce" \
+            | grep -e "Testing" -e "Cache mode"
+    done
+done
+
+# success, all done
+echo "*** done"
+rm -f $seq.full
+status=0
diff --git a/tests/qemu-iotests/157.out b/tests/qemu-iotests/157.out
new file mode 100644
index 0000000000..77a9c03d2c
--- /dev/null
+++ b/tests/qemu-iotests/157.out
@@ -0,0 +1,22 @@
+QA output created by 157
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728
+
+=== Setting WCE with qdev and with manually created BB ===
+
+Testing: -drive if=none,file=TEST_DIR/t.IMGFMT,driver=IMGFMT,cache=writeback -device virtio-blk,drive=none0
+    Cache mode:       writeback
+Testing: -drive if=none,file=TEST_DIR/t.IMGFMT,driver=IMGFMT,cache=writeback -device virtio-blk,drive=none0,write-cache=auto
+    Cache mode:       writeback
+Testing: -drive if=none,file=TEST_DIR/t.IMGFMT,driver=IMGFMT,cache=writeback -device virtio-blk,drive=none0,write-cache=on
+    Cache mode:       writeback
+Testing: -drive if=none,file=TEST_DIR/t.IMGFMT,driver=IMGFMT,cache=writeback -device virtio-blk,drive=none0,write-cache=off
+    Cache mode:       writethrough
+Testing: -drive if=none,file=TEST_DIR/t.IMGFMT,driver=IMGFMT,cache=writethrough -device virtio-blk,drive=none0
+    Cache mode:       writethrough
+Testing: -drive if=none,file=TEST_DIR/t.IMGFMT,driver=IMGFMT,cache=writethrough -device virtio-blk,drive=none0,write-cache=auto
+    Cache mode:       writethrough
+Testing: -drive if=none,file=TEST_DIR/t.IMGFMT,driver=IMGFMT,cache=writethrough -device virtio-blk,drive=none0,write-cache=on
+    Cache mode:       writeback
+Testing: -drive if=none,file=TEST_DIR/t.IMGFMT,driver=IMGFMT,cache=writethrough -device virtio-blk,drive=none0,write-cache=off
+    Cache mode:       writethrough
+*** done
diff --git a/tests/qemu-iotests/group b/tests/qemu-iotests/group
index 1c6fcb6018..3a3973e963 100644
--- a/tests/qemu-iotests/group
+++ b/tests/qemu-iotests/group
@@ -156,3 +156,4 @@
 154 rw auto backing quick
 155 rw auto
 156 rw auto quick
+157 auto
diff --git a/tests/tcg/xtensa/linker.ld.S b/tests/tcg/xtensa/linker.ld.S
index f1e7fa9f8d..5902302cf8 100644
--- a/tests/tcg/xtensa/linker.ld.S
+++ b/tests/tcg/xtensa/linker.ld.S
@@ -1,4 +1,4 @@
-#include <core-isa.h>
+#include "core-isa.h"
 
 #if XTENSA_HAVE_BE
 OUTPUT_FORMAT("elf32-xtensa-be")
diff --git a/tests/test-blockjob-txn.c b/tests/test-blockjob-txn.c
index d3030f1566..d049cba8a3 100644
--- a/tests/test-blockjob-txn.c
+++ b/tests/test-blockjob-txn.c
@@ -91,19 +91,22 @@ static BlockJob *test_block_job_start(unsigned int iterations,
     BlockDriverState *bs;
     TestBlockJob *s;
     TestBlockJobCBData *data;
+    static unsigned counter;
+    char job_id[24];
 
     data = g_new0(TestBlockJobCBData, 1);
     bs = bdrv_new();
-    s = block_job_create(&test_block_job_driver, bs, 0, test_block_job_cb,
-                         data, &error_abort);
+    snprintf(job_id, sizeof(job_id), "job%u", counter++);
+    s = block_job_create(job_id, &test_block_job_driver, bs, 0,
+                         test_block_job_cb, data, &error_abort);
     s->iterations = iterations;
     s->use_timer = use_timer;
     s->rc = rc;
     s->result = result;
-    s->common.co = qemu_coroutine_create(test_block_job_run);
+    s->common.co = qemu_coroutine_create(test_block_job_run, s);
     data->job = s;
     data->result = result;
-    qemu_coroutine_enter(s->common.co, s);
+    qemu_coroutine_enter(s->common.co);
     return &s->common;
 }
 
diff --git a/tests/test-coroutine.c b/tests/test-coroutine.c
index 215b92e636..ee5e06d327 100644
--- a/tests/test-coroutine.c
+++ b/tests/test-coroutine.c
@@ -30,8 +30,8 @@ static void test_in_coroutine(void)
 
     g_assert(!qemu_in_coroutine());
 
-    coroutine = qemu_coroutine_create(verify_in_coroutine);
-    qemu_coroutine_enter(coroutine, NULL);
+    coroutine = qemu_coroutine_create(verify_in_coroutine, NULL);
+    qemu_coroutine_enter(coroutine);
 }
 
 /*
@@ -40,15 +40,16 @@ static void test_in_coroutine(void)
 
 static void coroutine_fn verify_self(void *opaque)
 {
-    g_assert(qemu_coroutine_self() == opaque);
+    Coroutine **p_co = opaque;
+    g_assert(qemu_coroutine_self() == *p_co);
 }
 
 static void test_self(void)
 {
     Coroutine *coroutine;
 
-    coroutine = qemu_coroutine_create(verify_self);
-    qemu_coroutine_enter(coroutine, coroutine);
+    coroutine = qemu_coroutine_create(verify_self, &coroutine);
+    qemu_coroutine_enter(coroutine);
 }
 
 /*
@@ -70,8 +71,8 @@ static void coroutine_fn nest(void *opaque)
     if (nd->n_enter < nd->max) {
         Coroutine *child;
 
-        child = qemu_coroutine_create(nest);
-        qemu_coroutine_enter(child, nd);
+        child = qemu_coroutine_create(nest, nd);
+        qemu_coroutine_enter(child);
     }
 
     nd->n_return++;
@@ -86,8 +87,8 @@ static void test_nesting(void)
         .max      = 128,
     };
 
-    root = qemu_coroutine_create(nest);
-    qemu_coroutine_enter(root, &nd);
+    root = qemu_coroutine_create(nest, &nd);
+    qemu_coroutine_enter(root);
 
     /* Must enter and return from max nesting level */
     g_assert_cmpint(nd.n_enter, ==, nd.max);
@@ -115,9 +116,9 @@ static void test_yield(void)
     bool done = false;
     int i = -1; /* one extra time to return from coroutine */
 
-    coroutine = qemu_coroutine_create(yield_5_times);
+    coroutine = qemu_coroutine_create(yield_5_times, &done);
     while (!done) {
-        qemu_coroutine_enter(coroutine, &done);
+        qemu_coroutine_enter(coroutine);
         i++;
     }
     g_assert_cmpint(i, ==, 5); /* coroutine must yield 5 times */
@@ -131,7 +132,7 @@ static void coroutine_fn c2_fn(void *opaque)
 static void coroutine_fn c1_fn(void *opaque)
 {
     Coroutine *c2 = opaque;
-    qemu_coroutine_enter(c2, NULL);
+    qemu_coroutine_enter(c2);
 }
 
 static void test_co_queue(void)
@@ -139,12 +140,12 @@ static void test_co_queue(void)
     Coroutine *c1;
     Coroutine *c2;
 
-    c1 = qemu_coroutine_create(c1_fn);
-    c2 = qemu_coroutine_create(c2_fn);
+    c2 = qemu_coroutine_create(c2_fn, NULL);
+    c1 = qemu_coroutine_create(c1_fn, c2);
 
-    qemu_coroutine_enter(c1, c2);
+    qemu_coroutine_enter(c1);
     memset(c1, 0xff, sizeof(Coroutine));
-    qemu_coroutine_enter(c2, NULL);
+    qemu_coroutine_enter(c2);
 }
 
 /*
@@ -164,14 +165,14 @@ static void test_lifecycle(void)
     bool done = false;
 
     /* Create, enter, and return from coroutine */
-    coroutine = qemu_coroutine_create(set_and_exit);
-    qemu_coroutine_enter(coroutine, &done);
+    coroutine = qemu_coroutine_create(set_and_exit, &done);
+    qemu_coroutine_enter(coroutine);
     g_assert(done); /* expect done to be true (first time) */
 
     /* Repeat to check that no state affects this test */
     done = false;
-    coroutine = qemu_coroutine_create(set_and_exit);
-    qemu_coroutine_enter(coroutine, &done);
+    coroutine = qemu_coroutine_create(set_and_exit, &done);
+    qemu_coroutine_enter(coroutine);
     g_assert(done); /* expect done to be true (second time) */
 }
 
@@ -205,12 +206,12 @@ static void do_order_test(void)
 {
     Coroutine *co;
 
-    co = qemu_coroutine_create(co_order_test);
+    co = qemu_coroutine_create(co_order_test, NULL);
     record_push(1, 1);
-    qemu_coroutine_enter(co, NULL);
+    qemu_coroutine_enter(co);
     record_push(1, 2);
     g_assert(!qemu_in_coroutine());
-    qemu_coroutine_enter(co, NULL);
+    qemu_coroutine_enter(co);
     record_push(1, 3);
     g_assert(!qemu_in_coroutine());
 }
@@ -247,8 +248,8 @@ static void perf_lifecycle(void)
 
     g_test_timer_start();
     for (i = 0; i < max; i++) {
-        coroutine = qemu_coroutine_create(empty_coroutine);
-        qemu_coroutine_enter(coroutine, NULL);
+        coroutine = qemu_coroutine_create(empty_coroutine, NULL);
+        qemu_coroutine_enter(coroutine);
     }
     duration = g_test_timer_elapsed();
 
@@ -271,8 +272,8 @@ static void perf_nesting(void)
             .n_return = 0,
             .max      = maxnesting,
         };
-        root = qemu_coroutine_create(nest);
-        qemu_coroutine_enter(root, &nd);
+        root = qemu_coroutine_create(nest, &nd);
+        qemu_coroutine_enter(root);
     }
     duration = g_test_timer_elapsed();
 
@@ -301,11 +302,11 @@ static void perf_yield(void)
 
     maxcycles = 100000000;
     i = maxcycles;
-    Coroutine *coroutine = qemu_coroutine_create(yield_loop);
+    Coroutine *coroutine = qemu_coroutine_create(yield_loop, &i);
 
     g_test_timer_start();
     while (i > 0) {
-        qemu_coroutine_enter(coroutine, &i);
+        qemu_coroutine_enter(coroutine);
     }
     duration = g_test_timer_elapsed();
 
@@ -351,9 +352,9 @@ static void perf_cost(void)
 
     g_test_timer_start();
     while (i++ < maxcycles) {
-        co = qemu_coroutine_create(perf_cost_func);
-        qemu_coroutine_enter(co, &i);
-        qemu_coroutine_enter(co, NULL);
+        co = qemu_coroutine_create(perf_cost_func, &i);
+        qemu_coroutine_enter(co);
+        qemu_coroutine_enter(co);
     }
     duration = g_test_timer_elapsed();
     ops = (long)(maxcycles / (duration * 1000));
diff --git a/tests/test-thread-pool.c b/tests/test-thread-pool.c
index b0e1f3290f..8dbf66a44a 100644
--- a/tests/test-thread-pool.c
+++ b/tests/test-thread-pool.c
@@ -91,9 +91,9 @@ static void co_test_cb(void *opaque)
 static void test_submit_co(void)
 {
     WorkerTestData data;
-    Coroutine *co = qemu_coroutine_create(co_test_cb);
+    Coroutine *co = qemu_coroutine_create(co_test_cb, &data);
 
-    qemu_coroutine_enter(co, &data);
+    qemu_coroutine_enter(co);
 
     /* Back here once the worker has started.  */
 
diff --git a/tests/vhost-user-bridge.c b/tests/vhost-user-bridge.c
index 45fa2b6148..775e031069 100644
--- a/tests/vhost-user-bridge.c
+++ b/tests/vhost-user-bridge.c
@@ -36,8 +36,6 @@
 #include <sys/eventfd.h>
 #include <arpa/inet.h>
 #include <netdb.h>
-#include <qemu/osdep.h>
-
 #include <linux/vhost.h>
 
 #include "qemu/atomic.h"
diff --git a/tests/vhost-user-test.c b/tests/vhost-user-test.c
index 421d432f44..46d05881b6 100644
--- a/tests/vhost-user-test.c
+++ b/tests/vhost-user-test.c
@@ -13,12 +13,12 @@
 #include "libqtest.h"
 #include "qemu/option.h"
 #include "qemu/range.h"
+#include "qemu/sockets.h"
 #include "sysemu/char.h"
 #include "sysemu/sysemu.h"
 
 #include <linux/vhost.h>
 #include <sys/vfs.h>
-#include <qemu/sockets.h>
 
 /* GLIB version compatibility flags */
 #if !GLIB_CHECK_VERSION(2, 26, 0)
diff --git a/thread-pool.c b/thread-pool.c
index 03ba0b02a4..6fba913529 100644
--- a/thread-pool.c
+++ b/thread-pool.c
@@ -267,7 +267,7 @@ static void thread_pool_co_cb(void *opaque, int ret)
     ThreadPoolCo *co = opaque;
 
     co->ret = ret;
-    qemu_coroutine_enter(co->co, NULL);
+    qemu_coroutine_enter(co->co);
 }
 
 int coroutine_fn thread_pool_submit_co(ThreadPool *pool, ThreadPoolFunc *func,
diff --git a/trace/control-internal.h b/trace/control-internal.h
index dcf67f505a..deacc8f894 100644
--- a/trace/control-internal.h
+++ b/trace/control-internal.h
@@ -10,8 +10,6 @@
 #ifndef TRACE__CONTROL_INTERNAL_H
 #define TRACE__CONTROL_INTERNAL_H
 
-
-
 extern TraceEvent trace_events[];
 extern bool trace_events_dstate[];
 extern int trace_events_enabled_count;
@@ -72,4 +70,4 @@ static inline void trace_event_set_state_dynamic(TraceEvent *ev, bool state)
     trace_events_dstate[id] = state;
 }
 
-#endif  /* TRACE__CONTROL_INTERNAL_H */
+#endif /* TRACE__CONTROL_INTERNAL_H */
diff --git a/trace/control.h b/trace/control.h
index a2dd3eaedf..452a800eb2 100644
--- a/trace/control.h
+++ b/trace/control.h
@@ -203,4 +203,4 @@ char *trace_opt_parse(const char *optarg);
 
 #include "trace/control-internal.h"
 
-#endif  /* TRACE__CONTROL_H */
+#endif /* TRACE__CONTROL_H */
diff --git a/trace/event-internal.h b/trace/event-internal.h
index 86f6a511be..e4ea2e78a9 100644
--- a/trace/event-internal.h
+++ b/trace/event-internal.h
@@ -28,4 +28,4 @@ typedef struct TraceEvent {
 } TraceEvent;
 
 
-#endif  /* TRACE__EVENT_INTERNAL_H */
+#endif /* TRACE__EVENT_INTERNAL_H */
diff --git a/trace/ftrace.h b/trace/ftrace.h
index 92372e3caa..cb5e35d217 100644
--- a/trace/ftrace.h
+++ b/trace/ftrace.h
@@ -1,8 +1,6 @@
 #ifndef TRACE_FTRACE_H
 #define TRACE_FTRACE_H
 
-
-
 #define MAX_TRACE_STRLEN 512
 #define _STR(x) #x
 #define STR(x) _STR(x)
@@ -11,4 +9,4 @@ extern int trace_marker_fd;
 
 bool ftrace_init(void);
 
-#endif /* ! TRACE_FTRACE_H */
+#endif /* TRACE_FTRACE_H */
diff --git a/trace/mem-internal.h b/trace/mem-internal.h
index a75e0ff732..ddda934253 100644
--- a/trace/mem-internal.h
+++ b/trace/mem-internal.h
@@ -43,4 +43,4 @@ static inline uint8_t trace_mem_build_info(
     return res;
 }
 
-#endif  /* TRACE__MEM_INTERNAL_H */
+#endif /* TRACE__MEM_INTERNAL_H */
diff --git a/trace/mem.h b/trace/mem.h
index c76a572689..9c88bcb4e6 100644
--- a/trace/mem.h
+++ b/trace/mem.h
@@ -31,4 +31,4 @@ static uint8_t trace_mem_build_info(TCGMemOp size, bool sign_extend,
 
 #include "trace/mem-internal.h"
 
-#endif  /* TRACE__MEM_H */
+#endif /* TRACE__MEM_H */
diff --git a/translate-all.c b/translate-all.c
index eaa95e4cd7..0d47c1c0cf 100644
--- a/translate-all.c
+++ b/translate-all.c
@@ -2000,6 +2000,7 @@ int page_check_range(target_ulong start, target_ulong len, int flags)
 int page_unprotect(target_ulong address, uintptr_t pc)
 {
     unsigned int prot;
+    bool current_tb_invalidated;
     PageDesc *p;
     target_ulong host_start, host_end, addr;
 
@@ -2021,6 +2022,7 @@ int page_unprotect(target_ulong address, uintptr_t pc)
         host_end = host_start + qemu_host_page_size;
 
         prot = 0;
+        current_tb_invalidated = false;
         for (addr = host_start ; addr < host_end ; addr += TARGET_PAGE_SIZE) {
             p = page_find(addr >> TARGET_PAGE_BITS);
             p->flags |= PAGE_WRITE;
@@ -2028,10 +2030,7 @@ int page_unprotect(target_ulong address, uintptr_t pc)
 
             /* and since the content will be modified, we must invalidate
                the corresponding translated code. */
-            if (tb_invalidate_phys_page(addr, pc)) {
-                mmap_unlock();
-                return 2;
-            }
+            current_tb_invalidated |= tb_invalidate_phys_page(addr, pc);
 #ifdef DEBUG_TB_CHECK
             tb_invalidate_check(addr);
 #endif
@@ -2040,7 +2039,8 @@ int page_unprotect(target_ulong address, uintptr_t pc)
                  prot & PAGE_BITS);
 
         mmap_unlock();
-        return 1;
+        /* If current TB was invalidated return to main loop */
+        return current_tb_invalidated ? 2 : 1;
     }
     mmap_unlock();
     return 0;
diff --git a/ui/curses_keys.h b/ui/curses_keys.h
index f7467449b9..e39ef9e718 100644
--- a/ui/curses_keys.h
+++ b/ui/curses_keys.h
@@ -23,7 +23,7 @@
  */
 
 #ifndef QEMU_CURSES_KEYS_H
-#define QEMU_CURSES_KEYS_H 1
+#define QEMU_CURSES_KEYS_H
 
 #include <curses.h>
 #include "keymaps.h"
diff --git a/ui/input-linux.c b/ui/input-linux.c
index 1d33b5c121..0e230ce699 100644
--- a/ui/input-linux.c
+++ b/ui/input-linux.c
@@ -129,6 +129,17 @@ static int qemu_input_linux_to_qcode(unsigned int lnx)
     return linux_to_qcode[lnx];
 }
 
+static bool linux_is_button(unsigned int lnx)
+{
+    if (lnx < 0x100) {
+        return false;
+    }
+    if (lnx >= 0x160 && lnx < 0x2c0) {
+        return false;
+    }
+    return true;
+}
+
 #define TYPE_INPUT_LINUX "input-linux"
 #define INPUT_LINUX(obj) \
     OBJECT_CHECK(InputLinux, (obj), TYPE_INPUT_LINUX)
@@ -153,6 +164,12 @@ struct InputLinux {
     int         keycount;
     int         wheel;
     bool        initialized;
+
+    bool        has_rel_x;
+    bool        has_abs_x;
+    int         num_keys;
+    int         num_btns;
+
     QTAILQ_ENTRY(InputLinux) next;
 };
 
@@ -188,71 +205,55 @@ static void input_linux_toggle_grab(InputLinux *il)
     }
 }
 
-static void input_linux_event_keyboard(void *opaque)
+static void input_linux_handle_keyboard(InputLinux *il,
+                                        struct input_event *event)
 {
-    InputLinux *il = opaque;
-    struct input_event event;
-    int rc;
-
-    for (;;) {
-        rc = read(il->fd, &event, sizeof(event));
-        if (rc != sizeof(event)) {
-            if (rc < 0 && errno != EAGAIN) {
-                fprintf(stderr, "%s: read: %s\n", __func__, strerror(errno));
-                qemu_set_fd_handler(il->fd, NULL, NULL, NULL);
-                close(il->fd);
-            }
-            break;
+    if (event->type == EV_KEY) {
+        if (event->value > 2 || (event->value > 1 && !il->repeat)) {
+            /*
+             * ignore autorepeat + unknown key events
+             * 0 == up, 1 == down, 2 == autorepeat, other == undefined
+             */
+            return;
+        }
+        if (event->code >= KEY_CNT) {
+            /*
+             * Should not happen.  But better safe than sorry,
+             * and we make Coverity happy too.
+             */
+            return;
         }
 
-        switch (event.type) {
-        case EV_KEY:
-            if (event.value > 2 || (event.value > 1 && !il->repeat)) {
-                /*
-                 * ignore autorepeat + unknown key events
-                 * 0 == up, 1 == down, 2 == autorepeat, other == undefined
-                 */
-                continue;
-            }
-            if (event.code >= KEY_CNT) {
-                /*
-                 * Should not happen.  But better safe than sorry,
-                 * and we make Coverity happy too.
-                 */
-                continue;
-            }
-            /* keep track of key state */
-            if (!il->keydown[event.code] && event.value) {
-                il->keydown[event.code] = true;
-                il->keycount++;
-            }
-            if (il->keydown[event.code] && !event.value) {
-                il->keydown[event.code] = false;
-                il->keycount--;
-            }
+        /* keep track of key state */
+        if (!il->keydown[event->code] && event->value) {
+            il->keydown[event->code] = true;
+            il->keycount++;
+        }
+        if (il->keydown[event->code] && !event->value) {
+            il->keydown[event->code] = false;
+            il->keycount--;
+        }
 
-            /* send event to guest when grab is active */
-            if (il->grab_active) {
-                int qcode = qemu_input_linux_to_qcode(event.code);
-                qemu_input_event_send_key_qcode(NULL, qcode, event.value);
-            }
+        /* send event to guest when grab is active */
+        if (il->grab_active) {
+            int qcode = qemu_input_linux_to_qcode(event->code);
+            qemu_input_event_send_key_qcode(NULL, qcode, event->value);
+        }
 
-            /* hotkey -> record switch request ... */
-            if (il->keydown[KEY_LEFTCTRL] &&
-                il->keydown[KEY_RIGHTCTRL]) {
-                il->grab_request = true;
-            }
+        /* hotkey -> record switch request ... */
+        if (il->keydown[KEY_LEFTCTRL] &&
+            il->keydown[KEY_RIGHTCTRL]) {
+            il->grab_request = true;
+        }
 
-            /*
-             * ... and do the switch when all keys are lifted, so we
-             * confuse neither guest nor host with keys which seem to
-             * be stuck due to missing key-up events.
-             */
-            if (il->grab_request && !il->keycount) {
-                il->grab_request = false;
-                input_linux_toggle_grab(il);
-            }
-            break;
+        /*
+         * ... and do the switch when all keys are lifted, so we
+         * confuse neither guest nor host with keys which seem to
+         * be stuck due to missing key-up events.
+         */
+        if (il->grab_request && !il->keycount) {
+            il->grab_request = false;
+            input_linux_toggle_grab(il);
         }
     }
 }
@@ -265,7 +266,59 @@ static void input_linux_event_mouse_button(int button)
     qemu_input_event_sync();
 }
 
-static void input_linux_event_mouse(void *opaque)
+static void input_linux_handle_mouse(InputLinux *il, struct input_event *event)
+{
+    if (!il->grab_active) {
+        return;
+    }
+
+    switch (event->type) {
+    case EV_KEY:
+        switch (event->code) {
+        case BTN_LEFT:
+            qemu_input_queue_btn(NULL, INPUT_BUTTON_LEFT, event->value);
+            break;
+        case BTN_RIGHT:
+            qemu_input_queue_btn(NULL, INPUT_BUTTON_RIGHT, event->value);
+            break;
+        case BTN_MIDDLE:
+            qemu_input_queue_btn(NULL, INPUT_BUTTON_MIDDLE, event->value);
+            break;
+        case BTN_GEAR_UP:
+            qemu_input_queue_btn(NULL, INPUT_BUTTON_WHEEL_UP, event->value);
+            break;
+        case BTN_GEAR_DOWN:
+            qemu_input_queue_btn(NULL, INPUT_BUTTON_WHEEL_DOWN,
+                                 event->value);
+            break;
+        };
+        break;
+    case EV_REL:
+        switch (event->code) {
+        case REL_X:
+            qemu_input_queue_rel(NULL, INPUT_AXIS_X, event->value);
+            break;
+        case REL_Y:
+            qemu_input_queue_rel(NULL, INPUT_AXIS_Y, event->value);
+            break;
+        case REL_WHEEL:
+            il->wheel = event->value;
+            break;
+        }
+        break;
+    case EV_SYN:
+        qemu_input_event_sync();
+        if (il->wheel != 0) {
+            input_linux_event_mouse_button((il->wheel > 0)
+                                           ? INPUT_BUTTON_WHEEL_UP
+                                           : INPUT_BUTTON_WHEEL_DOWN);
+            il->wheel = 0;
+        }
+        break;
+    }
+}
+
+static void input_linux_event(void *opaque)
 {
     InputLinux *il = opaque;
     struct input_event event;
@@ -282,54 +335,11 @@ static void input_linux_event_mouse(void *opaque)
             break;
         }
 
-        /* only send event to guest when grab is active */
-        if (!il->grab_active) {
-            continue;
+        if (il->num_keys) {
+            input_linux_handle_keyboard(il, &event);
         }
-
-        switch (event.type) {
-        case EV_KEY:
-            switch (event.code) {
-            case BTN_LEFT:
-                qemu_input_queue_btn(NULL, INPUT_BUTTON_LEFT, event.value);
-                break;
-            case BTN_RIGHT:
-                qemu_input_queue_btn(NULL, INPUT_BUTTON_RIGHT, event.value);
-                break;
-            case BTN_MIDDLE:
-                qemu_input_queue_btn(NULL, INPUT_BUTTON_MIDDLE, event.value);
-                break;
-            case BTN_GEAR_UP:
-                qemu_input_queue_btn(NULL, INPUT_BUTTON_WHEEL_UP, event.value);
-                break;
-            case BTN_GEAR_DOWN:
-                qemu_input_queue_btn(NULL, INPUT_BUTTON_WHEEL_DOWN,
-                                     event.value);
-                break;
-            };
-            break;
-        case EV_REL:
-            switch (event.code) {
-            case REL_X:
-                qemu_input_queue_rel(NULL, INPUT_AXIS_X, event.value);
-                break;
-            case REL_Y:
-                qemu_input_queue_rel(NULL, INPUT_AXIS_Y, event.value);
-                break;
-            case REL_WHEEL:
-                il->wheel = event.value;
-                break;
-            }
-            break;
-        case EV_SYN:
-            qemu_input_event_sync();
-            if (il->wheel != 0) {
-                input_linux_event_mouse_button((il->wheel > 0)
-                                               ? INPUT_BUTTON_WHEEL_UP
-                                               : INPUT_BUTTON_WHEEL_DOWN);
-                il->wheel = 0;
-            }
-            break;
+        if (il->has_rel_x && il->num_btns) {
+            input_linux_handle_mouse(il, &event);
         }
     }
 }
@@ -337,7 +347,8 @@ static void input_linux_event_mouse(void *opaque)
 static void input_linux_complete(UserCreatable *uc, Error **errp)
 {
     InputLinux *il = INPUT_LINUX(uc);
-    uint32_t evtmap, relmap, absmap;
+    uint8_t evtmap, relmap, absmap, keymap[KEY_CNT / 8];
+    unsigned int i;
     int rc, ver;
 
     if (!il->evdev) {
@@ -365,36 +376,36 @@ static void input_linux_complete(UserCreatable *uc, Error **errp)
     }
 
     if (evtmap & (1 << EV_REL)) {
+        relmap = 0;
         rc = ioctl(il->fd, EVIOCGBIT(EV_REL, sizeof(relmap)), &relmap);
-        if (rc < 0) {
-            relmap = 0;
+        if (relmap & (1 << REL_X)) {
+            il->has_rel_x = true;
         }
     }
 
     if (evtmap & (1 << EV_ABS)) {
-        ioctl(il->fd, EVIOCGBIT(EV_ABS, sizeof(absmap)), &absmap);
-        if (rc < 0) {
-            absmap = 0;
+        absmap = 0;
+        rc = ioctl(il->fd, EVIOCGBIT(EV_ABS, sizeof(absmap)), &absmap);
+        if (absmap & (1 << ABS_X)) {
+            il->has_abs_x = true;
         }
     }
 
-    if ((evtmap & (1 << EV_REL)) &&
-        (relmap & (1 << REL_X))) {
-        /* has relative x axis -> assume mouse */
-        qemu_set_fd_handler(il->fd, input_linux_event_mouse, NULL, il);
-    } else if ((evtmap & (1 << EV_ABS)) &&
-               (absmap & (1 << ABS_X))) {
-        /* has absolute x axis -> not supported */
-        error_setg(errp, "tablet/touchscreen not supported");
-        goto err_close;
-    } else if (evtmap & (1 << EV_KEY)) {
-        /* has keys/buttons (and no x axis) -> assume keyboard */
-        qemu_set_fd_handler(il->fd, input_linux_event_keyboard, NULL, il);
-    } else {
-        /* Huh? What is this? */
-        error_setg(errp, "unknown kind of input device");
-        goto err_close;
+    if (evtmap & (1 << EV_KEY)) {
+        memset(keymap, 0, sizeof(keymap));
+        rc = ioctl(il->fd, EVIOCGBIT(EV_KEY, sizeof(keymap)), keymap);
+        for (i = 0; i < KEY_CNT; i++) {
+            if (keymap[i / 8] & (1 << (i % 8))) {
+                if (linux_is_button(i)) {
+                    il->num_btns++;
+                } else {
+                    il->num_keys++;
+                }
+            }
+        }
     }
+
+    qemu_set_fd_handler(il->fd, input_linux_event, NULL, il);
     input_linux_toggle_grab(il);
     QTAILQ_INSERT_TAIL(&inputs, il, next);
     il->initialized = true;
diff --git a/ui/keymaps.h b/ui/keymaps.h
index a7600d5751..47d061343e 100644
--- a/ui/keymaps.h
+++ b/ui/keymaps.h
@@ -22,8 +22,8 @@
  * THE SOFTWARE.
  */
 
-#ifndef __QEMU_KEYMAPS_H__
-#define __QEMU_KEYMAPS_H__
+#ifndef QEMU_KEYMAPS_H
+#define QEMU_KEYMAPS_H
 
 #include "qemu-common.h"
 
@@ -74,4 +74,4 @@ int keysym2scancode(void *kbd_layout, int keysym);
 int keycode_is_keypad(void *kbd_layout, int keycode);
 int keysym_is_numlock(void *kbd_layout, int keysym);
 
-#endif /* __QEMU_KEYMAPS_H__ */
+#endif /* QEMU_KEYMAPS_H */
diff --git a/ui/sdl_zoom.h b/ui/sdl_zoom.h
index 74955bc944..39696ddb08 100644
--- a/ui/sdl_zoom.h
+++ b/ui/sdl_zoom.h
@@ -11,8 +11,8 @@
  *
  */
 
-#ifndef SDL_zoom_h
-#define SDL_zoom_h
+#ifndef SDL_ZOOM_H
+#define SDL_ZOOM_H
 
 #include <SDL.h>
 
@@ -22,4 +22,4 @@
 int sdl_zoom_blit(SDL_Surface *src_sfc, SDL_Surface *dst_sfc,
                   int smooth, SDL_Rect *src_rect);
 
-#endif /* SDL_zoom_h */
+#endif /* SDL_ZOOM_H */
diff --git a/ui/vnc-auth-sasl.h b/ui/vnc-auth-sasl.h
index 3f59da67eb..cb42745a6b 100644
--- a/ui/vnc-auth-sasl.h
+++ b/ui/vnc-auth-sasl.h
@@ -22,10 +22,8 @@
  * THE SOFTWARE.
  */
 
-
-#ifndef __QEMU_VNC_AUTH_SASL_H__
-#define __QEMU_VNC_AUTH_SASL_H__
-
+#ifndef QEMU_VNC_AUTH_SASL_H
+#define QEMU_VNC_AUTH_SASL_H
 
 #include <sasl/sasl.h>
 
@@ -71,5 +69,4 @@ long vnc_client_write_sasl(VncState *vs);
 
 void start_auth_sasl(VncState *vs);
 
-#endif /* __QEMU_VNC_AUTH_SASL_H__ */
-
+#endif /* QEMU_VNC_AUTH_SASL_H */
diff --git a/ui/vnc-auth-vencrypt.h b/ui/vnc-auth-vencrypt.h
index 9f674c5173..1e35406664 100644
--- a/ui/vnc-auth-vencrypt.h
+++ b/ui/vnc-auth-vencrypt.h
@@ -24,10 +24,9 @@
  * THE SOFTWARE.
  */
 
-
-#ifndef __QEMU_VNC_AUTH_VENCRYPT_H__
-#define __QEMU_VNC_AUTH_VENCRYPT_H__
+#ifndef QEMU_VNC_AUTH_VENCRYPT_H
+#define QEMU_VNC_AUTH_VENCRYPT_H
 
 void start_auth_vencrypt(VncState *vs);
 
-#endif /* __QEMU_VNC_AUTH_VENCRYPT_H__ */
+#endif /* QEMU_VNC_AUTH_VENCRYPT_H */
diff --git a/ui/vnc-enc-tight.c b/ui/vnc-enc-tight.c
index e5cba0e5a7..b8581dd2e9 100644
--- a/ui/vnc-enc-tight.c
+++ b/ui/vnc-enc-tight.c
@@ -349,7 +349,7 @@ tight_detect_smooth_image(VncState *vs, int w, int h)
     tight_fill_palette##bpp(VncState *vs, int x, int y,                 \
                             int max, size_t count,                      \
                             uint32_t *bg, uint32_t *fg,                 \
-                            VncPalette **palette) {                     \
+                            VncPalette *palette) {                      \
         uint##bpp##_t *data;                                            \
         uint##bpp##_t c0, c1, ci;                                       \
         int i, n0, n1;                                                  \
@@ -396,23 +396,23 @@ tight_detect_smooth_image(VncState *vs, int w, int h)
             return 0;                                                   \
         }                                                               \
                                                                         \
-        *palette = palette_new(max, bpp);                               \
-        palette_put(*palette, c0);                                      \
-        palette_put(*palette, c1);                                      \
-        palette_put(*palette, ci);                                      \
+        palette_init(palette, max, bpp);                                \
+        palette_put(palette, c0);                                       \
+        palette_put(palette, c1);                                       \
+        palette_put(palette, ci);                                       \
                                                                         \
         for (i++; i < count; i++) {                                     \
             if (data[i] == ci) {                                        \
                 continue;                                               \
             } else {                                                    \
                 ci = data[i];                                           \
-                if (!palette_put(*palette, (uint32_t)ci)) {             \
+                if (!palette_put(palette, (uint32_t)ci)) {              \
                     return 0;                                           \
                 }                                                       \
             }                                                           \
         }                                                               \
                                                                         \
-        return palette_size(*palette);                                  \
+        return palette_size(palette);                                   \
     }
 
 DEFINE_FILL_PALETTE_FUNCTION(8)
@@ -421,7 +421,7 @@ DEFINE_FILL_PALETTE_FUNCTION(32)
 
 static int tight_fill_palette(VncState *vs, int x, int y,
                               size_t count, uint32_t *bg, uint32_t *fg,
-                              VncPalette **palette)
+                              VncPalette *palette)
 {
     int max;
 
@@ -1457,9 +1457,11 @@ static int send_sub_rect_jpeg(VncState *vs, int x, int y, int w, int h,
 }
 #endif
 
+static __thread VncPalette color_count_palette;
+
 static int send_sub_rect(VncState *vs, int x, int y, int w, int h)
 {
-    VncPalette *palette = NULL;
+    VncPalette *palette = &color_count_palette;
     uint32_t bg = 0, fg = 0;
     int colors;
     int ret = 0;
@@ -1488,7 +1490,7 @@ static int send_sub_rect(VncState *vs, int x, int y, int w, int h)
     }
 #endif
 
-    colors = tight_fill_palette(vs, x, y, w * h, &bg, &fg, &palette);
+    colors = tight_fill_palette(vs, x, y, w * h, &bg, &fg, palette);
 
 #ifdef CONFIG_VNC_JPEG
     if (allow_jpeg && vs->tight.quality != (uint8_t)-1) {
@@ -1501,7 +1503,6 @@ static int send_sub_rect(VncState *vs, int x, int y, int w, int h)
     ret = send_sub_rect_nojpeg(vs, x, y, w, h, bg, fg, colors, palette);
 #endif
 
-    palette_destroy(palette);
     return ret;
 }
 
diff --git a/ui/vnc-enc-tight.h b/ui/vnc-enc-tight.h
index a3add788e2..95c3dac020 100644
--- a/ui/vnc-enc-tight.h
+++ b/ui/vnc-enc-tight.h
@@ -27,8 +27,8 @@
  * THE SOFTWARE.
  */
 
-#ifndef VNC_ENCODING_TIGHT_H
-#define VNC_ENCODING_TIGHT_H
+#ifndef VNC_ENC_TIGHT_H
+#define VNC_ENC_TIGHT_H
 
 /*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  * Tight Encoding.
@@ -180,4 +180,4 @@
 #define VNC_TIGHT_DETECT_MIN_WIDTH           8
 #define VNC_TIGHT_DETECT_MIN_HEIGHT          8
 
-#endif /* VNC_ENCODING_TIGHT_H */
+#endif /* VNC_ENC_TIGHT_H */
diff --git a/ui/vnc-enc-zrle.h b/ui/vnc-enc-zrle.h
index 6b182132a6..6535cb2aaf 100644
--- a/ui/vnc-enc-zrle.h
+++ b/ui/vnc-enc-zrle.h
@@ -26,8 +26,8 @@
  * THE SOFTWARE.
  */
 
-#ifndef VNC_ENCODING_ZRLE_H
-#define VNC_ENCODING_ZRLE_H
+#ifndef VNC_ENC_ZRLE_H
+#define VNC_ENC_ZRLE_H
 
 /*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  * ZRLE - encoding combining Zlib compression, tiling, palettisation and
diff --git a/ui/vnc-enc-zywrle.h b/ui/vnc-enc-zywrle.h
index d436d588fc..610bd79d1a 100644
--- a/ui/vnc-enc-zywrle.h
+++ b/ui/vnc-enc-zywrle.h
@@ -41,8 +41,8 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  ********************************************************************/
 
-#ifndef VNC_ENCODING_ZYWRLE_H
-#define VNC_ENCODING_ZYWRLE_H
+#ifndef VNC_ENC_ZYWRLE_H
+#define VNC_ENC_ZYWRLE_H
 
 /* Tables for Coefficients filtering. */
 #ifndef ZYWRLE_QUANTIZE
diff --git a/ui/vnc-ws.h b/ui/vnc-ws.h
index 652b6fc390..396cacfcb0 100644
--- a/ui/vnc-ws.h
+++ b/ui/vnc-ws.h
@@ -18,8 +18,8 @@
  * along with this software; if not, see <http://www.gnu.org/licenses/>.
  */
 
-#ifndef __QEMU_UI_VNC_WS_H
-#define __QEMU_UI_VNC_WS_H
+#ifndef QEMU_UI_VNC_WS_H
+#define QEMU_UI_VNC_WS_H
 
 gboolean vncws_tls_handshake_io(QIOChannel *ioc,
                                 GIOCondition condition,
@@ -28,4 +28,4 @@ gboolean vncws_handshake_io(QIOChannel *ioc,
                             GIOCondition condition,
                             void *opaque);
 
-#endif /* __QEMU_UI_VNC_WS_H */
+#endif /* QEMU_UI_VNC_WS_H */
diff --git a/ui/vnc.c b/ui/vnc.c
index 18c0b56c3a..e3f857cc90 100644
--- a/ui/vnc.c
+++ b/ui/vnc.c
@@ -1025,7 +1025,7 @@ static int find_and_clear_dirty_height(VncState *vs,
 static int vnc_update_client(VncState *vs, int has_dirty, bool sync)
 {
     vs->has_dirty += has_dirty;
-    if (vs->need_update && vs->ioc != NULL) {
+    if (vs->need_update && !vs->disconnecting) {
         VncDisplay *vd = vs->vd;
         VncJob *job;
         int y;
@@ -1436,8 +1436,9 @@ static void vnc_jobs_bh(void *opaque)
  * First function called whenever there is more data to be read from
  * the client socket. Will delegate actual work according to whether
  * SASL SSF layers are enabled (thus requiring decryption calls)
+ * Returns 0 on success, -1 if client disconnected
  */
-static void vnc_client_read(VncState *vs)
+static int vnc_client_read(VncState *vs)
 {
     ssize_t ret;
 
@@ -1450,8 +1451,9 @@ static void vnc_client_read(VncState *vs)
     if (!ret) {
         if (vs->disconnecting) {
             vnc_disconnect_finish(vs);
+            return -1;
         }
-        return;
+        return 0;
     }
 
     while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
@@ -1461,7 +1463,7 @@ static void vnc_client_read(VncState *vs)
         ret = vs->read_handler(vs, vs->input.buffer, len);
         if (vs->disconnecting) {
             vnc_disconnect_finish(vs);
-            return;
+            return -1;
         }
 
         if (!ret) {
@@ -1470,6 +1472,7 @@ static void vnc_client_read(VncState *vs)
             vs->read_handler_expect = ret;
         }
     }
+    return 0;
 }
 
 gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
@@ -1477,7 +1480,9 @@ gboolean vnc_client_io(QIOChannel *ioc G_GNUC_UNUSED,
 {
     VncState *vs = opaque;
     if (condition & G_IO_IN) {
-        vnc_client_read(vs);
+        if (vnc_client_read(vs) < 0) {
+            return TRUE;
+        }
     }
     if (condition & G_IO_OUT) {
         vnc_client_write(vs);
diff --git a/ui/vnc.h b/ui/vnc.h
index 6568bca520..ab5f244116 100644
--- a/ui/vnc.h
+++ b/ui/vnc.h
@@ -24,8 +24,8 @@
  * THE SOFTWARE.
  */
 
-#ifndef __QEMU_VNC_H
-#define __QEMU_VNC_H
+#ifndef QEMU_VNC_H
+#define QEMU_VNC_H
 
 #include "qemu-common.h"
 #include "qemu/queue.h"
@@ -577,4 +577,4 @@ int vnc_zrle_send_framebuffer_update(VncState *vs, int x, int y, int w, int h);
 int vnc_zywrle_send_framebuffer_update(VncState *vs, int x, int y, int w, int h);
 void vnc_zrle_clear(VncState *vs);
 
-#endif /* __QEMU_VNC_H */
+#endif /* QEMU_VNC_H */
diff --git a/util/acl.c b/util/acl.c
index 723b6a89b4..c105addadc 100644
--- a/util/acl.c
+++ b/util/acl.c
@@ -177,12 +177,3 @@ int qemu_acl_remove(qemu_acl *acl,
     }
     return -1;
 }
-
-
-/*
- * Local variables:
- *  c-indent-level: 4
- *  c-basic-offset: 4
- *  tab-width: 8
- * End:
- */
diff --git a/util/mmap-alloc.c b/util/mmap-alloc.c
index 629d97a362..5a85aa3c89 100644
--- a/util/mmap-alloc.c
+++ b/util/mmap-alloc.c
@@ -9,8 +9,9 @@
  * 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/osdep.h"
-#include <qemu/mmap-alloc.h>
+#include "qemu/mmap-alloc.h"
 
 #define HUGETLBFS_MAGIC       0x958458f6
 
diff --git a/util/osdep.c b/util/osdep.c
index ff004e8074..06fb1cfda6 100644
--- a/util/osdep.c
+++ b/util/osdep.c
@@ -83,14 +83,7 @@ static int qemu_dup_flags(int fd, int flags)
     int serrno;
     int dup_flags;
 
-#ifdef F_DUPFD_CLOEXEC
-    ret = fcntl(fd, F_DUPFD_CLOEXEC, 0);
-#else
-    ret = dup(fd);
-    if (ret != -1) {
-        qemu_set_cloexec(ret);
-    }
-#endif
+    ret = qemu_dup(fd);
     if (ret == -1) {
         goto fail;
     }
@@ -129,6 +122,20 @@ fail:
     return -1;
 }
 
+int qemu_dup(int fd)
+{
+    int ret;
+#ifdef F_DUPFD_CLOEXEC
+    ret = fcntl(fd, F_DUPFD_CLOEXEC, 0);
+#else
+    ret = dup(fd);
+    if (ret != -1) {
+        qemu_set_cloexec(ret);
+    }
+#endif
+    return ret;
+}
+
 static int qemu_parse_fdset(const char *param)
 {
     return qemu_parse_fd(param);
diff --git a/util/oslib-posix.c b/util/oslib-posix.c
index e2e1d4d39f..d8e5dcfede 100644
--- a/util/oslib-posix.c
+++ b/util/oslib-posix.c
@@ -48,7 +48,7 @@
 #include <sys/sysctl.h>
 #endif
 
-#include <qemu/mmap-alloc.h>
+#include "qemu/mmap-alloc.h"
 
 int qemu_get_thread_id(void)
 {
diff --git a/util/qemu-coroutine-io.c b/util/qemu-coroutine-io.c
index 91b9357d4a..44a8969a69 100644
--- a/util/qemu-coroutine-io.c
+++ b/util/qemu-coroutine-io.c
@@ -75,7 +75,7 @@ static void fd_coroutine_enter(void *opaque)
 {
     FDYieldUntilData *data = opaque;
     qemu_set_fd_handler(data->fd, NULL, NULL, NULL);
-    qemu_coroutine_enter(data->co, NULL);
+    qemu_coroutine_enter(data->co);
 }
 
 void coroutine_fn yield_until_fd_readable(int fd)
diff --git a/util/qemu-coroutine-lock.c b/util/qemu-coroutine-lock.c
index da37ca7f95..22aa9abb30 100644
--- a/util/qemu-coroutine-lock.c
+++ b/util/qemu-coroutine-lock.c
@@ -31,13 +31,13 @@
 
 void qemu_co_queue_init(CoQueue *queue)
 {
-    QTAILQ_INIT(&queue->entries);
+    QSIMPLEQ_INIT(&queue->entries);
 }
 
 void coroutine_fn qemu_co_queue_wait(CoQueue *queue)
 {
     Coroutine *self = qemu_coroutine_self();
-    QTAILQ_INSERT_TAIL(&queue->entries, self, co_queue_next);
+    QSIMPLEQ_INSERT_TAIL(&queue->entries, self, co_queue_next);
     qemu_coroutine_yield();
     assert(qemu_in_coroutine());
 }
@@ -55,9 +55,9 @@ void qemu_co_queue_run_restart(Coroutine *co)
     Coroutine *next;
 
     trace_qemu_co_queue_run_restart(co);
-    while ((next = QTAILQ_FIRST(&co->co_queue_wakeup))) {
-        QTAILQ_REMOVE(&co->co_queue_wakeup, next, co_queue_next);
-        qemu_coroutine_enter(next, NULL);
+    while ((next = QSIMPLEQ_FIRST(&co->co_queue_wakeup))) {
+        QSIMPLEQ_REMOVE_HEAD(&co->co_queue_wakeup, co_queue_next);
+        qemu_coroutine_enter(next);
     }
 }
 
@@ -66,13 +66,13 @@ static bool qemu_co_queue_do_restart(CoQueue *queue, bool single)
     Coroutine *self = qemu_coroutine_self();
     Coroutine *next;
 
-    if (QTAILQ_EMPTY(&queue->entries)) {
+    if (QSIMPLEQ_EMPTY(&queue->entries)) {
         return false;
     }
 
-    while ((next = QTAILQ_FIRST(&queue->entries)) != NULL) {
-        QTAILQ_REMOVE(&queue->entries, next, co_queue_next);
-        QTAILQ_INSERT_TAIL(&self->co_queue_wakeup, next, co_queue_next);
+    while ((next = QSIMPLEQ_FIRST(&queue->entries)) != NULL) {
+        QSIMPLEQ_REMOVE_HEAD(&queue->entries, co_queue_next);
+        QSIMPLEQ_INSERT_TAIL(&self->co_queue_wakeup, next, co_queue_next);
         trace_qemu_co_queue_next(next);
         if (single) {
             break;
@@ -97,19 +97,19 @@ bool qemu_co_enter_next(CoQueue *queue)
 {
     Coroutine *next;
 
-    next = QTAILQ_FIRST(&queue->entries);
+    next = QSIMPLEQ_FIRST(&queue->entries);
     if (!next) {
         return false;
     }
 
-    QTAILQ_REMOVE(&queue->entries, next, co_queue_next);
-    qemu_coroutine_enter(next, NULL);
+    QSIMPLEQ_REMOVE_HEAD(&queue->entries, co_queue_next);
+    qemu_coroutine_enter(next);
     return true;
 }
 
 bool qemu_co_queue_empty(CoQueue *queue)
 {
-    return QTAILQ_FIRST(&queue->entries) == NULL;
+    return QSIMPLEQ_FIRST(&queue->entries) == NULL;
 }
 
 void qemu_co_mutex_init(CoMutex *mutex)
diff --git a/util/qemu-coroutine-sleep.c b/util/qemu-coroutine-sleep.c
index 6966831d37..25de3ed3dd 100644
--- a/util/qemu-coroutine-sleep.c
+++ b/util/qemu-coroutine-sleep.c
@@ -25,7 +25,7 @@ static void co_sleep_cb(void *opaque)
 {
     CoSleepCB *sleep_cb = opaque;
 
-    qemu_coroutine_enter(sleep_cb->co, NULL);
+    qemu_coroutine_enter(sleep_cb->co);
 }
 
 void coroutine_fn co_aio_sleep_ns(AioContext *ctx, QEMUClockType type,
diff --git a/util/qemu-coroutine.c b/util/qemu-coroutine.c
index 5816702cc5..89f21a9cec 100644
--- a/util/qemu-coroutine.c
+++ b/util/qemu-coroutine.c
@@ -42,7 +42,7 @@ static void coroutine_pool_cleanup(Notifier *n, void *value)
     }
 }
 
-Coroutine *qemu_coroutine_create(CoroutineEntry *entry)
+Coroutine *qemu_coroutine_create(CoroutineEntry *entry, void *opaque)
 {
     Coroutine *co = NULL;
 
@@ -76,7 +76,8 @@ Coroutine *qemu_coroutine_create(CoroutineEntry *entry)
     }
 
     co->entry = entry;
-    QTAILQ_INIT(&co->co_queue_wakeup);
+    co->entry_arg = opaque;
+    QSIMPLEQ_INIT(&co->co_queue_wakeup);
     return co;
 }
 
@@ -100,12 +101,12 @@ static void coroutine_delete(Coroutine *co)
     qemu_coroutine_delete(co);
 }
 
-void qemu_coroutine_enter(Coroutine *co, void *opaque)
+void qemu_coroutine_enter(Coroutine *co)
 {
     Coroutine *self = qemu_coroutine_self();
     CoroutineAction ret;
 
-    trace_qemu_coroutine_enter(self, co, opaque);
+    trace_qemu_coroutine_enter(self, co, co->entry_arg);
 
     if (co->caller) {
         fprintf(stderr, "Co-routine re-entered recursively\n");
@@ -113,7 +114,6 @@ void qemu_coroutine_enter(Coroutine *co, void *opaque)
     }
 
     co->caller = self;
-    co->entry_arg = opaque;
     ret = qemu_coroutine_switch(self, co, COROUTINE_ENTER);
 
     qemu_co_queue_run_restart(co);