Merge remote branch 'kwolf/for-anthony' into staging
diff --git a/Makefile b/Makefile
index 7986bf6..221fbd8 100644
--- a/Makefile
+++ b/Makefile
@@ -29,7 +29,7 @@
 LIBS+=-lz $(LIBS_TOOLS)
 
 ifdef BUILD_DOCS
-DOCS=qemu-doc.html qemu-tech.html qemu.1 qemu-img.1 qemu-nbd.8
+DOCS=qemu-doc.html qemu-tech.html qemu.1 qemu-img.1 qemu-nbd.8 QMP/qmp-commands.txt
 else
 DOCS=
 endif
@@ -120,9 +120,11 @@
 
 vnc-auth-sasl.o: vnc-auth-sasl.c vnc.h
 
-vnc-encoding-zlib.o: vnc.h
+vnc-encoding-zlib.o: vnc-encoding-zlib.c vnc.h
 
-vnc-encoding-hextile.o: vnc.h
+vnc-encoding-hextile.o: vnc-encoding-hextile.c vnc.h
+
+vnc-encoding-tight.o: vnc-encoding-tight.c vnc.h vnc-encoding-tight.h
 
 curses.o: curses.c keymaps.h curses_keys.h
 
@@ -144,6 +146,8 @@
 qemu-img-cmds.h: $(SRC_PATH)/qemu-img-cmds.hx
 	$(call quiet-command,sh $(SRC_PATH)/hxtool -h < $< > $@,"  GEN   $@")
 
+check-qint.o check-qstring.o check-qdict.o check-qlist.o check-qfloat.o check-qjson.o: $(GENERATED_HEADERS)
+
 check-qint: check-qint.o qint.o qemu-malloc.o
 check-qstring: check-qstring.o qstring.o qemu-malloc.o
 check-qdict: check-qdict.o qdict.o qfloat.o qint.o qstring.o qbool.o qemu-malloc.o qlist.o
@@ -259,6 +263,9 @@
 qemu-monitor.texi: $(SRC_PATH)/qemu-monitor.hx
 	$(call quiet-command,sh $(SRC_PATH)/hxtool -t < $< > $@,"  GEN   $@")
 
+QMP/qmp-commands.txt: $(SRC_PATH)/qemu-monitor.hx
+	$(call quiet-command,sh $(SRC_PATH)/hxtool -q < $< > $@,"  GEN   $@")
+
 qemu-img-cmds.texi: $(SRC_PATH)/qemu-img-cmds.hx
 	$(call quiet-command,sh $(SRC_PATH)/hxtool -t < $< > $@,"  GEN   $@")
 
diff --git a/Makefile.objs b/Makefile.objs
index 1a942e5..9796dcb 100644
--- a/Makefile.objs
+++ b/Makefile.objs
@@ -105,6 +105,7 @@
 common-obj-$(CONFIG_CURSES) += curses.o
 common-obj-y += vnc.o acl.o d3des.o
 common-obj-y += vnc-encoding-zlib.o vnc-encoding-hextile.o
+common-obj-y += vnc-encoding-tight.o
 common-obj-y += iov.o
 common-obj-$(CONFIG_VNC_TLS) += vnc-tls.o vnc-auth-vencrypt.o
 common-obj-$(CONFIG_VNC_SASL) += vnc-auth-sasl.o
diff --git a/Makefile.target b/Makefile.target
index fda5bf3..d06c679 100644
--- a/Makefile.target
+++ b/Makefile.target
@@ -85,7 +85,8 @@
 
 QEMU_CFLAGS+=-I$(SRC_PATH)/linux-user -I$(SRC_PATH)/linux-user/$(TARGET_ABI_DIR)
 obj-y = main.o syscall.o strace.o mmap.o signal.o thunk.o \
-      elfload.o linuxload.o uaccess.o gdbstub.o cpu-uname.o
+      elfload.o linuxload.o uaccess.o gdbstub.o cpu-uname.o \
+      qemu-malloc.o
 
 obj-$(TARGET_HAS_BFLT) += flatload.o
 
diff --git a/QMP/README b/QMP/README
index 9334c25..35a80c7 100644
--- a/QMP/README
+++ b/QMP/README
@@ -15,8 +15,9 @@
 
 For more information, please, refer to the following files:
 
-o qmp-spec.txt    QEMU Monitor Protocol current specification
-o qmp-events.txt  List of available asynchronous events
+o qmp-spec.txt      QEMU Monitor Protocol current specification
+o qmp-commands.txt  QMP supported commands
+o qmp-events.txt    List of available asynchronous events
 
 There are also two simple Python scripts available:
 
diff --git a/arch_init.c b/arch_init.c
index cfc03ea..8e849a8 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -108,7 +108,7 @@
     static ram_addr_t current_addr = 0;
     ram_addr_t saved_addr = current_addr;
     ram_addr_t addr = 0;
-    int found = 0;
+    int bytes_sent = 0;
 
     while (addr < last_ram_offset) {
         if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
@@ -123,19 +123,20 @@
             if (is_dup_page(p, *p)) {
                 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
                 qemu_put_byte(f, *p);
+                bytes_sent = 1;
             } else {
                 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
                 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
+                bytes_sent = TARGET_PAGE_SIZE;
             }
 
-            found = 1;
             break;
         }
         addr += TARGET_PAGE_SIZE;
         current_addr = (saved_addr + addr) % last_ram_offset;
     }
 
-    return found;
+    return bytes_sent;
 }
 
 static uint64_t bytes_transferred;
@@ -206,11 +207,11 @@
     bwidth = qemu_get_clock_ns(rt_clock);
 
     while (!qemu_file_rate_limit(f)) {
-        int ret;
+        int bytes_sent;
 
-        ret = ram_save_block(f);
-        bytes_transferred += ret * TARGET_PAGE_SIZE;
-        if (ret == 0) { /* no more blocks */
+        bytes_sent = ram_save_block(f);
+        bytes_transferred += bytes_sent;
+        if (bytes_sent == 0) { /* no more blocks */
             break;
         }
     }
@@ -226,9 +227,11 @@
 
     /* try transferring iterative blocks of memory */
     if (stage == 3) {
+        int bytes_sent;
+
         /* flush all remaining blocks regardless of rate limiting */
-        while (ram_save_block(f) != 0) {
-            bytes_transferred += TARGET_PAGE_SIZE;
+        while ((bytes_sent = ram_save_block(f)) != 0) {
+            bytes_transferred += bytes_sent;
         }
         cpu_physical_memory_set_dirty_tracking(0);
     }
diff --git a/block.c b/block.c
index 296de89..39724c1 100644
--- a/block.c
+++ b/block.c
@@ -1445,33 +1445,6 @@
     qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
 }
 
-/**
- * bdrv_info(): Block devices information
- *
- * Each block device information is stored in a QDict and the
- * returned QObject is a QList of all devices.
- *
- * The QDict contains the following:
- *
- * - "device": device name
- * - "type": device type
- * - "removable": true if the device is removable, false otherwise
- * - "locked": true if the device is locked, false otherwise
- * - "inserted": only present if the device is inserted, it is a QDict
- *    containing the following:
- *          - "file": device file name
- *          - "ro": true if read-only, false otherwise
- *          - "drv": driver format name
- *          - "backing_file": backing file name if one is used
- *          - "encrypted": true if encrypted, false otherwise
- *
- * Example:
- *
- * [ { "device": "ide0-hd0", "type": "hd", "removable": false, "locked": false,
- *     "inserted": { "file": "/tmp/foobar", "ro": false, "drv": "qcow2" } },
- *   { "device": "floppy0", "type": "floppy", "removable": true,
- *     "locked": false } ]
- */
 void bdrv_info(Monitor *mon, QObject **ret_data)
 {
     QList *bs_list;
@@ -1577,48 +1550,6 @@
     return res;
 }
 
-/**
- * bdrv_info_stats(): show block device statistics
- *
- * Each device statistic information is stored in a QDict and
- * the returned QObject is a QList of all devices.
- *
- * The QDict contains the following:
- *
- * - "device": device name
- * - "stats": A QDict with the statistics information, it contains:
- *     - "rd_bytes": bytes read
- *     - "wr_bytes": bytes written
- *     - "rd_operations": read operations
- *     - "wr_operations": write operations
- *     - "wr_highest_offset": Highest offset of a sector written since the
- *       BlockDriverState has been opened
- * - "parent": A QDict recursively holding the statistics of the underlying
- *    protocol (e.g. the host file for a qcow2 image). If there is no
- *    underlying protocol, this field is omitted.
- *
- * Example:
- *
- * [ { "device": "ide0-hd0",
- *               "stats": { "rd_bytes": 512,
- *                          "wr_bytes": 0,
- *                          "rd_operations": 1,
- *                          "wr_operations": 0,
- *                          "wr_highest_offset": 0 },
- *               "parent": {
- *                      "stats": { "rd_bytes": 1024,
- *                                 "wr_bytes": 0,
- *                                 "rd_operations": 2,
- *                                 "wr_operations": 0,
- *                                 "wr_highest_offset": 0,
- *                      } } },
- *   { "device": "ide1-cd0",
- *               "stats": { "rd_bytes": 0,
- *                          "wr_bytes": 0,
- *                          "rd_operations": 0,
- *                          "wr_operations": 0,
- *                          "wr_highest_offset": 0 } },
- */
 void bdrv_info_stats(Monitor *mon, QObject **ret_data)
 {
     QObject *obj;
diff --git a/bswap.h b/bswap.h
index 956f3fa..20caae6 100644
--- a/bswap.h
+++ b/bswap.h
@@ -205,7 +205,7 @@
 
 #ifdef HOST_WORDS_BIGENDIAN
 #define cpu_to_32wu cpu_to_be32wu
-#define leul_to_cpu(v) le ## HOST_LONG_BITS ## _to_cpu(v)
+#define leul_to_cpu(v) glue(glue(le,HOST_LONG_BITS),_to_cpu)(v)
 #else
 #define cpu_to_32wu cpu_to_le32wu
 #define leul_to_cpu(v) (v)
diff --git a/configure b/configure
index 3cd2c5f..653c8d2 100755
--- a/configure
+++ b/configure
@@ -2817,3 +2817,7 @@
 if test "$static" = "no" -a "$user_pie" = "yes" ; then
   echo "QEMU_CFLAGS+=-fpie" > $d/config.mak
 fi
+
+if test "$docs" = "yes" ; then
+  mkdir -p QMP
+fi
diff --git a/console.c b/console.c
index 7070b1b..698bc10 100644
--- a/console.c
+++ b/console.c
@@ -167,7 +167,7 @@
 
 void vga_hw_invalidate(void)
 {
-    if (active_console->hw_invalidate)
+    if (active_console && active_console->hw_invalidate)
         active_console->hw_invalidate(active_console->hw);
 }
 
@@ -1621,6 +1621,22 @@
     pf.depth = bpp == 32 ? 24 : bpp;
 
     switch (bpp) {
+        case 15:
+            pf.bits_per_pixel = 16;
+            pf.bytes_per_pixel = 2;
+            pf.rmask = 0x00007c00;
+            pf.gmask = 0x000003E0;
+            pf.bmask = 0x0000001F;
+            pf.rmax = 31;
+            pf.gmax = 31;
+            pf.bmax = 31;
+            pf.rshift = 10;
+            pf.gshift = 5;
+            pf.bshift = 0;
+            pf.rbits = 5;
+            pf.gbits = 5;
+            pf.bbits = 5;
+            break;
         case 16:
             pf.rmask = 0x0000F800;
             pf.gmask = 0x000007E0;
diff --git a/cpu-all.h b/cpu-all.h
index 47a5722..77eaf85 100644
--- a/cpu-all.h
+++ b/cpu-all.h
@@ -627,6 +627,7 @@
 #if defined(CONFIG_USE_GUEST_BASE)
 extern unsigned long guest_base;
 extern int have_guest_base;
+extern unsigned long reserved_va;
 #define GUEST_BASE guest_base
 #else
 #define GUEST_BASE 0ul
diff --git a/hw/apic.c b/hw/apic.c
index 9029dad..7fbd79b 100644
--- a/hw/apic.c
+++ b/hw/apic.c
@@ -26,6 +26,21 @@
 #include "kvm.h"
 
 //#define DEBUG_APIC
+//#define DEBUG_COALESCING
+
+#ifdef DEBUG_APIC
+#define DPRINTF(fmt, ...)                                       \
+    do { printf("apic: " fmt , ## __VA_ARGS__); } while (0)
+#else
+#define DPRINTF(fmt, ...)
+#endif
+
+#ifdef DEBUG_COALESCING
+#define DPRINTF_C(fmt, ...)                                     \
+    do { printf("apic: " fmt , ## __VA_ARGS__); } while (0)
+#else
+#define DPRINTF_C(fmt, ...)
+#endif
 
 /* APIC Local Vector Table */
 #define APIC_LVT_TIMER   0
@@ -158,6 +173,8 @@
     uint32_t lvt = s->lvt[vector];
     int trigger_mode;
 
+    DPRINTF("%s: vector %d delivery mode %d\n", __func__, vector,
+            (lvt >> 8) & 7);
     if (lvt & APIC_LVT_MASKED)
         return;
 
@@ -287,6 +304,9 @@
 {
     uint32_t deliver_bitmask[MAX_APIC_WORDS];
 
+    DPRINTF("%s: dest %d dest_mode %d delivery_mode %d vector %d"
+            " polarity %d trigger_mode %d\n", __func__, dest, dest_mode,
+            delivery_mode, vector_num, polarity, trigger_mode);
     apic_get_delivery_bitmask(deliver_bitmask, dest, dest_mode);
     apic_bus_deliver(deliver_bitmask, delivery_mode, vector_num, polarity,
                      trigger_mode);
@@ -295,9 +315,8 @@
 void cpu_set_apic_base(CPUState *env, uint64_t val)
 {
     APICState *s = env->apic_state;
-#ifdef DEBUG_APIC
-    printf("cpu_set_apic_base: %016" PRIx64 "\n", val);
-#endif
+
+    DPRINTF("cpu_set_apic_base: %016" PRIx64 "\n", val);
     if (!s)
         return;
     s->apicbase = (val & 0xfffff000) |
@@ -313,10 +332,9 @@
 uint64_t cpu_get_apic_base(CPUState *env)
 {
     APICState *s = env->apic_state;
-#ifdef DEBUG_APIC
-    printf("cpu_get_apic_base: %016" PRIx64 "\n",
-           s ? (uint64_t)s->apicbase: 0);
-#endif
+
+    DPRINTF("cpu_get_apic_base: %016" PRIx64 "\n",
+            s ? (uint64_t)s->apicbase: 0);
     return s ? s->apicbase : 0;
 }
 
@@ -386,17 +404,20 @@
 
 void apic_reset_irq_delivered(void)
 {
+    DPRINTF_C("%s: old coalescing %d\n", __func__, apic_irq_delivered);
     apic_irq_delivered = 0;
 }
 
 int apic_get_irq_delivered(void)
 {
+    DPRINTF_C("%s: returning coalescing %d\n", __func__, apic_irq_delivered);
     return apic_irq_delivered;
 }
 
 static void apic_set_irq(APICState *s, int vector_num, int trigger_mode)
 {
     apic_irq_delivered += !get_bit(s->irr, vector_num);
+    DPRINTF_C("%s: coalescing %d\n", __func__, apic_irq_delivered);
 
     set_bit(s->irr, vector_num);
     if (trigger_mode)
@@ -755,9 +776,7 @@
         val = 0;
         break;
     }
-#ifdef DEBUG_APIC
-    printf("APIC read: %08x = %08x\n", (uint32_t)addr, val);
-#endif
+    DPRINTF("read: " TARGET_FMT_plx " = %08x\n", addr, val);
     return val;
 }
 
@@ -792,9 +811,7 @@
         return;
     s = env->apic_state;
 
-#ifdef DEBUG_APIC
-    printf("APIC write: %08x = %08x\n", (uint32_t)addr, val);
-#endif
+    DPRINTF("write: " TARGET_FMT_plx " = %08x\n", addr, val);
 
     switch(index) {
     case 0x02:
diff --git a/hw/arm_boot.c b/hw/arm_boot.c
index df031a5..620550b 100644
--- a/hw/arm_boot.c
+++ b/hw/arm_boot.c
@@ -187,6 +187,7 @@
             env->regs[15] = info->entry & 0xfffffffe;
             env->thumb = info->entry & 1;
         } else {
+            env->regs[15] = info->loader_start;
             if (old_param) {
                 set_kernel_args_old(info, info->initrd_size,
                                     info->loader_start);
diff --git a/hw/gt64xxx.c b/hw/gt64xxx.c
index 55971b9..7691e1d 100644
--- a/hw/gt64xxx.c
+++ b/hw/gt64xxx.c
@@ -276,7 +276,7 @@
     check_reserved_space(&start, &length);
     length = 0x1000;
     /* Map new address */
-    DPRINTF("ISD: %x@%x -> %x@%x, %x\n", s->ISD_length, s->ISD_start,
+    DPRINTF("ISD: "TARGET_FMT_plx"@"TARGET_FMT_plx" -> "TARGET_FMT_plx"@"TARGET_FMT_plx", %x\n", s->ISD_length, s->ISD_start,
             length, start, s->ISD_handle);
     s->ISD_start = start;
     s->ISD_length = length;
diff --git a/hw/gumstix.c b/hw/gumstix.c
index 3fd31f4..b64e04e 100644
--- a/hw/gumstix.c
+++ b/hw/gumstix.c
@@ -74,8 +74,6 @@
         exit(1);
     }
 
-    cpu->env->regs[15] = 0x00000000;
-
     /* Interrupt line of NIC is connected to GPIO line 36 */
     smc91c111_init(&nd_table[0], 0x04000300,
                     pxa2xx_gpio_in_get(cpu->gpio)[36]);
@@ -114,8 +112,6 @@
         exit(1);
     }
 
-    cpu->env->regs[15] = 0x00000000;
-
     /* Interrupt line of NIC is connected to GPIO line 99 */
     smc91c111_init(&nd_table[0], 0x04000300,
                     pxa2xx_gpio_in_get(cpu->gpio)[99]);
diff --git a/hw/i8259.c b/hw/i8259.c
index ea48e0e..a995280 100644
--- a/hw/i8259.c
+++ b/hw/i8259.c
@@ -30,6 +30,13 @@
 /* debug PIC */
 //#define DEBUG_PIC
 
+#ifdef DEBUG_PIC
+#define DPRINTF(fmt, ...)                                       \
+    do { printf("pic: " fmt , ## __VA_ARGS__); } while (0)
+#else
+#define DPRINTF(fmt, ...)
+#endif
+
 //#define DEBUG_IRQ_LATENCY
 //#define DEBUG_IRQ_COUNT
 
@@ -185,9 +192,7 @@
 
 #if defined(DEBUG_PIC) || defined(DEBUG_IRQ_COUNT)
     if (level != irq_level[irq]) {
-#if defined(DEBUG_PIC)
-        printf("i8259_set_irq: irq=%d level=%d\n", irq, level);
-#endif
+        DPRINTF("i8259_set_irq: irq=%d level=%d\n", irq, level);
         irq_level[irq] = level;
 #ifdef DEBUG_IRQ_COUNT
 	if (level == 1)
@@ -253,9 +258,7 @@
            (double)(qemu_get_clock(vm_clock) -
                     irq_time[irq]) * 1000000.0 / get_ticks_per_sec());
 #endif
-#if defined(DEBUG_PIC)
-    printf("pic_interrupt: irq=%d\n", irq);
-#endif
+    DPRINTF("pic_interrupt: irq=%d\n", irq);
     return intno;
 }
 
@@ -286,9 +289,7 @@
     PicState *s = opaque;
     int priority, cmd, irq;
 
-#ifdef DEBUG_PIC
-    printf("pic_write: addr=0x%02x val=0x%02x\n", addr, val);
-#endif
+    DPRINTF("write: addr=0x%02x val=0x%02x\n", addr, val);
     addr &= 1;
     if (addr == 0) {
         if (val & 0x10) {
@@ -416,9 +417,7 @@
             ret = s->imr;
         }
     }
-#ifdef DEBUG_PIC
-    printf("pic_read: addr=0x%02x val=0x%02x\n", addr1, ret);
-#endif
+    DPRINTF("read: addr=0x%02x val=0x%02x\n", addr1, ret);
     return ret;
 }
 
diff --git a/hw/ioapic.c b/hw/ioapic.c
index 7ad8018..335da6e 100644
--- a/hw/ioapic.c
+++ b/hw/ioapic.c
@@ -28,6 +28,13 @@
 
 //#define DEBUG_IOAPIC
 
+#ifdef DEBUG_IOAPIC
+#define DPRINTF(fmt, ...)                                       \
+    do { printf("ioapic: " fmt , ## __VA_ARGS__); } while (0)
+#else
+#define DPRINTF(fmt, ...)
+#endif
+
 #define IOAPIC_NUM_PINS			0x18
 #define IOAPIC_LVT_MASKED 		(1<<16)
 
@@ -95,6 +102,7 @@
      * to GSI 2.  GSI maps to ioapic 1-1.  This is not
      * the cleanest way of doing it but it should work. */
 
+    DPRINTF("%s: %s vec %x\n", __func__, level? "raise" : "lower", vector);
     if (vector == 0)
         vector = 2;
 
@@ -149,9 +157,7 @@
                         val = s->ioredtbl[index] & 0xffffffff;
                 }
         }
-#ifdef DEBUG_IOAPIC
-        printf("I/O APIC read: %08x = %08x\n", s->ioregsel, val);
-#endif
+        DPRINTF("read: %08x = %08x\n", s->ioregsel, val);
     }
     return val;
 }
@@ -166,9 +172,7 @@
         s->ioregsel = val;
         return;
     } else if (addr == 0x10) {
-#ifdef DEBUG_IOAPIC
-        printf("I/O APIC write: %08x = %08x\n", s->ioregsel, val);
-#endif
+        DPRINTF("write: %08x = %08x\n", s->ioregsel, val);
         switch (s->ioregsel) {
             case 0x00:
                 s->id = (val >> 24) & 0xff;
diff --git a/hw/mainstone.c b/hw/mainstone.c
index a4379e3..54bacfb 100644
--- a/hw/mainstone.c
+++ b/hw/mainstone.c
@@ -89,9 +89,6 @@
     cpu_register_physical_memory(0, MAINSTONE_ROM,
                     qemu_ram_alloc(MAINSTONE_ROM) | IO_MEM_ROM);
 
-    /* Setup initial (reset) machine state */
-    cpu->env->regs[15] = mainstone_binfo.loader_start;
-
 #ifdef TARGET_WORDS_BIGENDIAN
     be = 1;
 #else
diff --git a/hw/mc146818rtc.c b/hw/mc146818rtc.c
index 571c593..c3e6a70 100644
--- a/hw/mc146818rtc.c
+++ b/hw/mc146818rtc.c
@@ -31,6 +31,7 @@
 #include "mc146818rtc.h"
 
 //#define DEBUG_CMOS
+//#define DEBUG_COALESCED
 
 #ifdef DEBUG_CMOS
 # define CMOS_DPRINTF(format, ...)      printf(format, ## __VA_ARGS__)
@@ -38,6 +39,12 @@
 # define CMOS_DPRINTF(format, ...)      do { } while (0)
 #endif
 
+#ifdef DEBUG_COALESCED
+# define DPRINTF_C(format, ...)      printf(format, ## __VA_ARGS__)
+#else
+# define DPRINTF_C(format, ...)      do { } while (0)
+#endif
+
 #define RTC_REINJECT_ON_ACK_COUNT 20
 
 #define RTC_SECONDS             0
@@ -131,9 +138,12 @@
     if (s->irq_coalesced != 0) {
         apic_reset_irq_delivered();
         s->cmos_data[RTC_REG_C] |= 0xc0;
+        DPRINTF_C("cmos: injecting from timer\n");
         rtc_irq_raise(s->irq);
         if (apic_get_irq_delivered()) {
             s->irq_coalesced--;
+            DPRINTF_C("cmos: coalesced irqs decreased to %d\n",
+                      s->irq_coalesced);
         }
     }
 
@@ -164,8 +174,10 @@
         /* period in 32 Khz cycles */
         period = 1 << (period_code - 1);
 #ifdef TARGET_I386
-        if(period != s->period)
+        if (period != s->period) {
             s->irq_coalesced = (s->irq_coalesced * s->period) / period;
+            DPRINTF_C("cmos: coalesced irqs scaled to %d\n", s->irq_coalesced);
+        }
         s->period = period;
 #endif
         /* compute 32 khz clock */
@@ -198,6 +210,8 @@
             if (!apic_get_irq_delivered()) {
                 s->irq_coalesced++;
                 rtc_coalesced_timer_update(s);
+                DPRINTF_C("cmos: coalesced irqs increased to %d\n",
+                          s->irq_coalesced);
             }
         } else
 #endif
@@ -476,9 +490,13 @@
                     s->irq_reinject_on_ack_count < RTC_REINJECT_ON_ACK_COUNT) {
                 s->irq_reinject_on_ack_count++;
                 apic_reset_irq_delivered();
+                DPRINTF_C("cmos: injecting on ack\n");
                 qemu_irq_raise(s->irq);
-                if (apic_get_irq_delivered())
+                if (apic_get_irq_delivered()) {
                     s->irq_coalesced--;
+                    DPRINTF_C("cmos: coalesced irqs decreased to %d\n",
+                              s->irq_coalesced);
+                }
                 break;
             }
 #endif
diff --git a/hw/msix.c b/hw/msix.c
index 2ca0900..1613bb4 100644
--- a/hw/msix.c
+++ b/hw/msix.c
@@ -15,14 +15,6 @@
 #include "msix.h"
 #include "pci.h"
 
-/* Declaration from linux/pci_regs.h */
-#define  PCI_CAP_ID_MSIX 0x11 /* MSI-X */
-#define  PCI_MSIX_FLAGS 2     /* Table at lower 11 bits */
-#define  PCI_MSIX_FLAGS_QSIZE	0x7FF
-#define  PCI_MSIX_FLAGS_ENABLE	(1 << 15)
-#define  PCI_MSIX_FLAGS_MASKALL	(1 << 14)
-#define  PCI_MSIX_FLAGS_BIRMASK	(7 << 0)
-
 /* MSI-X capability structure */
 #define MSIX_TABLE_OFFSET 4
 #define MSIX_PBA_OFFSET 8
diff --git a/hw/musicpal.c b/hw/musicpal.c
index ebd933e..d44c5a0 100644
--- a/hw/musicpal.c
+++ b/hw/musicpal.c
@@ -1295,8 +1295,6 @@
                                        musicpal_gpio_writefn, s);
     sysbus_init_mmio(dev, MP_GPIO_SIZE, iomemtype);
 
-    musicpal_gpio_reset(&dev->qdev);
-
     qdev_init_gpio_out(&dev->qdev, s->out, ARRAY_SIZE(s->out));
 
     qdev_init_gpio_in(&dev->qdev, musicpal_gpio_pin_event, 32);
diff --git a/hw/nseries.c b/hw/nseries.c
index 0273eee..04a028d 100644
--- a/hw/nseries.c
+++ b/hw/nseries.c
@@ -1016,7 +1016,6 @@
     n800_dss_init(&s->blizzard);
 
     /* CPU setup */
-    s->cpu->env->regs[15] = s->cpu->env->boot_info->loader_start;
     s->cpu->env->GE = 0x5;
 
     /* If the machine has a slided keyboard, open it */
@@ -1317,11 +1316,6 @@
     if (usb_enabled)
         n8x0_usb_setup(s);
 
-    /* Setup initial (reset) machine state */
-
-    /* Start at the OneNAND bootloader.  */
-    s->cpu->env->regs[15] = 0;
-
     if (kernel_filename) {
         /* Or at the linux loader.  */
         binfo->kernel_filename = kernel_filename;
@@ -1330,7 +1324,6 @@
         arm_load_kernel(s->cpu->env, binfo);
 
         qemu_register_reset(n8x0_boot_init, s);
-        n8x0_boot_init(s);
     }
 
     if (option_rom[0] && (boot_device[0] == 'n' || !kernel_filename)) {
diff --git a/hw/omap_sx1.c b/hw/omap_sx1.c
index ca0a7d1..2e9879f 100644
--- a/hw/omap_sx1.c
+++ b/hw/omap_sx1.c
@@ -195,15 +195,10 @@
 
     /* Load the kernel.  */
     if (kernel_filename) {
-        /* Start at bootloader.  */
-        cpu->env->regs[15] = sx1_binfo.loader_start;
-
         sx1_binfo.kernel_filename = kernel_filename;
         sx1_binfo.kernel_cmdline = kernel_cmdline;
         sx1_binfo.initrd_filename = initrd_filename;
         arm_load_kernel(cpu->env, &sx1_binfo);
-    } else {
-        cpu->env->regs[15] = 0x00000000;
     }
 
     /* TODO: fix next line */
diff --git a/hw/palm.c b/hw/palm.c
index ba7c398..8db133d 100644
--- a/hw/palm.c
+++ b/hw/palm.c
@@ -243,7 +243,6 @@
             rom_size = load_image_targphys(option_rom[0], OMAP_CS0_BASE,
                                            flash_size);
             rom_loaded = 1;
-            cpu->env->regs[15] = 0x00000000;
         }
         if (rom_size < 0) {
             fprintf(stderr, "%s: error loading '%s'\n",
@@ -258,9 +257,6 @@
 
     /* Load the kernel.  */
     if (kernel_filename) {
-        /* Start at bootloader.  */
-        cpu->env->regs[15] = palmte_binfo.loader_start;
-
         palmte_binfo.kernel_filename = kernel_filename;
         palmte_binfo.kernel_cmdline = kernel_cmdline;
         palmte_binfo.initrd_filename = initrd_filename;
diff --git a/hw/pc.c b/hw/pc.c
index e7f31d3..9b85c42 100644
--- a/hw/pc.c
+++ b/hw/pc.c
@@ -39,6 +39,16 @@
 /* output Bochs bios info messages */
 //#define DEBUG_BIOS
 
+/* debug PC/ISA interrupts */
+//#define DEBUG_IRQ
+
+#ifdef DEBUG_IRQ
+#define DPRINTF(fmt, ...)                                       \
+    do { printf("CPUIRQ: " fmt , ## __VA_ARGS__); } while (0)
+#else
+#define DPRINTF(fmt, ...)
+#endif
+
 #define BIOS_FILENAME "bios.bin"
 
 #define PC_MAX_BIOS_SIZE (4 * 1024 * 1024)
@@ -70,6 +80,7 @@
 {
     IsaIrqState *isa = (IsaIrqState *)opaque;
 
+    DPRINTF("isa_irqs: %s irq %d\n", level? "raise" : "lower", n);
     if (n < 16) {
         qemu_set_irq(isa->i8259[n], level);
     }
@@ -150,6 +161,7 @@
 {
     CPUState *env = first_cpu;
 
+    DPRINTF("pic_irqs: %s irq %d\n", level? "raise" : "lower", irq);
     if (env->apic_state) {
         while (env) {
             if (apic_accept_pic_intr(env))
diff --git a/hw/pc.h b/hw/pc.h
index 73cccef..0e52933 100644
--- a/hw/pc.h
+++ b/hw/pc.h
@@ -135,7 +135,7 @@
 struct PCII440FXState;
 typedef struct PCII440FXState PCII440FXState;
 
-PCIBus *i440fx_init(PCII440FXState **pi440fx_state, int *piix_devfn, qemu_irq *pic, int ram_size);
+PCIBus *i440fx_init(PCII440FXState **pi440fx_state, int *piix_devfn, qemu_irq *pic, ram_addr_t ram_size);
 void i440fx_init_memory_mappings(PCII440FXState *d);
 
 /* piix4.c */
diff --git a/hw/pci-hotplug.c b/hw/pci-hotplug.c
index 37ac015..a8f3df1 100644
--- a/hw/pci-hotplug.c
+++ b/hw/pci-hotplug.c
@@ -124,7 +124,7 @@
         if (pci_read_devaddr(mon, pci_addr, &dom, &pci_bus, &slot)) {
             goto err;
         }
-        dev = pci_find_device(pci_find_root_bus(0), pci_bus, slot, 0);
+        dev = pci_find_device(pci_find_root_bus(dom), pci_bus, slot, 0);
         if (!dev) {
             monitor_printf(mon, "no pci device with address %s\n", pci_addr);
             goto err;
@@ -252,7 +252,8 @@
 
     if (dev) {
         monitor_printf(mon, "OK domain %d, bus %d, slot %d, function %d\n",
-                       0, pci_bus_num(dev->bus), PCI_SLOT(dev->devfn),
+                       pci_find_domain(dev->bus),
+                       pci_bus_num(dev->bus), PCI_SLOT(dev->devfn),
                        PCI_FUNC(dev->devfn));
     } else
         monitor_printf(mon, "failed to add %s\n", opts);
@@ -269,7 +270,7 @@
         return -1;
     }
 
-    d = pci_find_device(pci_find_root_bus(0), bus, slot, 0);
+    d = pci_find_device(pci_find_root_bus(dom), bus, slot, 0);
     if (!d) {
         monitor_printf(mon, "slot %d empty\n", slot);
         return -1;
diff --git a/hw/pci.c b/hw/pci.c
index 8d84651..cbbd1dd 100644
--- a/hw/pci.c
+++ b/hw/pci.c
@@ -200,6 +200,26 @@
     return NULL;
 }
 
+int pci_find_domain(const PCIBus *bus)
+{
+    PCIDevice *d;
+    struct PCIHostBus *host;
+
+    /* obtain root bus */
+    while ((d = bus->parent_dev) != NULL) {
+        bus = d->bus;
+    }
+
+    QLIST_FOREACH(host, &host_buses, next) {
+        if (host->bus == bus) {
+            return host->domain;
+        }
+    }
+
+    abort();    /* should not be reached */
+    return -1;
+}
+
 void pci_bus_new_inplace(PCIBus *bus, DeviceState *parent,
                          const char *name, int devfn_min)
 {
@@ -419,14 +439,12 @@
     return ret;
 }
 
-static int pci_set_default_subsystem_id(PCIDevice *pci_dev)
+static void pci_set_default_subsystem_id(PCIDevice *pci_dev)
 {
-    uint16_t *id;
-
-    id = (void*)(&pci_dev->config[PCI_SUBSYSTEM_VENDOR_ID]);
-    id[0] = cpu_to_le16(pci_default_sub_vendor_id);
-    id[1] = cpu_to_le16(pci_default_sub_device_id);
-    return 0;
+    pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
+                 pci_default_sub_vendor_id);
+    pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
+                 pci_default_sub_device_id);
 }
 
 /*
@@ -507,7 +525,7 @@
     }
 
     *devfnp = slot << 3;
-    return pci_find_bus(pci_find_root_bus(0), bus);
+    return pci_find_bus(pci_find_root_bus(dom), bus);
 }
 
 static void pci_init_cmask(PCIDevice *dev)
@@ -1362,67 +1380,6 @@
     return NULL;
 }
 
-/**
- * do_pci_info(): PCI buses and devices information
- *
- * The returned QObject is a QList of all buses. Each bus is
- * represented by a QDict, which has a key with a QList of all
- * PCI devices attached to it. Each device is represented by
- * a QDict.
- *
- * The bus QDict contains the following:
- *
- * - "bus": bus number
- * - "devices": a QList of QDicts, each QDict represents a PCI
- *   device
- *
- * The PCI device QDict contains the following:
- *
- * - "bus": identical to the parent's bus number
- * - "slot": slot number
- * - "function": function number
- * - "class_info": a QDict containing:
- *      - "desc": device class description (optional)
- *      - "class": device class number
- * - "id": a QDict containing:
- *      - "device": device ID
- *      - "vendor": vendor ID
- * - "irq": device's IRQ if assigned (optional)
- * - "qdev_id": qdev id string
- * - "pci_bridge": It's a QDict, only present if this device is a
- *   PCI bridge, contains:
- *      - "bus": bus number
- *      - "secondary": secondary bus number
- *      - "subordinate": subordinate bus number
- *      - "io_range": a QDict with memory range information
- *      - "memory_range": a QDict with memory range information
- *      - "prefetchable_range": a QDict with memory range information
- *      - "devices": a QList of PCI devices if there's any attached (optional)
- * - "regions": a QList of QDicts, each QDict represents a
- *   memory region of this device
- *
- * The memory range QDict contains the following:
- *
- * - "base": base memory address
- * - "limit": limit value
- *
- * The region QDict can be an I/O region or a memory region,
- * an I/O region QDict contains the following:
- *
- * - "type": "io"
- * - "bar": BAR number
- * - "address": memory address
- * - "size": memory size
- *
- * A memory region QDict contains the following:
- *
- * - "type": "memory"
- * - "bar": BAR number
- * - "address": memory address
- * - "size": memory size
- * - "mem_type_64": true or false
- * - "prefetch": true or false
- */
 void do_pci_info(Monitor *mon, QObject **ret_data)
 {
     QList *bus_list;
diff --git a/hw/pci.h b/hw/pci.h
index f6e6c5f..3a15bd4 100644
--- a/hw/pci.h
+++ b/hw/pci.h
@@ -97,17 +97,6 @@
 /* PCI HEADER_TYPE */
 #define  PCI_HEADER_TYPE_MULTI_FUNCTION 0x80
 
-#define PCI_STATUS_RESERVED_MASK_LO (PCI_STATUS_RESERVED1 | \
-                PCI_STATUS_INT_STATUS | PCI_STATUS_CAPABILITIES | \
-                PCI_STATUS_66MHZ | PCI_STATUS_RESERVED2 | PCI_STATUS_FAST_BACK)
-
-#define PCI_STATUS_RESERVED_MASK_HI (PCI_STATUS_DEVSEL >> 8)
-
-/* Bits in the PCI Command Register (PCI 2.3 spec) */
-#define PCI_COMMAND_RESERVED	0xf800
-
-#define PCI_COMMAND_RESERVED_MASK_HI (PCI_COMMAND_RESERVED >> 8)
-
 /* Size of the standard PCI config header */
 #define PCI_CONFIG_HEADER_SIZE 0x40
 /* Size of the standard PCI config space */
@@ -229,6 +218,7 @@
 int pci_bus_num(PCIBus *s);
 void pci_for_each_device(PCIBus *bus, int bus_num, void (*fn)(PCIBus *bus, PCIDevice *d));
 PCIBus *pci_find_root_bus(int domain);
+int pci_find_domain(const PCIBus *bus);
 PCIBus *pci_find_bus(PCIBus *bus, int bus_num);
 PCIDevice *pci_find_device(PCIBus *bus, int bus_num, int slot, int function);
 PCIBus *pci_get_bus_devfn(int *devfnp, const char *devaddr);
@@ -350,12 +340,12 @@
 PCIDevice *pci_create(PCIBus *bus, int devfn, const char *name);
 PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name);
 
-static inline int pci_is_express(PCIDevice *d)
+static inline int pci_is_express(const PCIDevice *d)
 {
     return d->cap_present & QEMU_PCI_CAP_EXPRESS;
 }
 
-static inline uint32_t pci_config_size(PCIDevice *d)
+static inline uint32_t pci_config_size(const PCIDevice *d)
 {
     return pci_is_express(d) ? PCIE_CONFIG_SPACE_SIZE : PCI_CONFIG_SPACE_SIZE;
 }
diff --git a/hw/piix_pci.c b/hw/piix_pci.c
index aff7f6d..d14d05e 100644
--- a/hw/piix_pci.c
+++ b/hw/piix_pci.c
@@ -216,7 +216,7 @@
     return 0;
 }
 
-PCIBus *i440fx_init(PCII440FXState **pi440fx_state, int *piix3_devfn, qemu_irq *pic, int ram_size)
+PCIBus *i440fx_init(PCII440FXState **pi440fx_state, int *piix3_devfn, qemu_irq *pic, ram_addr_t ram_size)
 {
     DeviceState *dev;
     PCIBus *b;
diff --git a/hw/qdev.c b/hw/qdev.c
index af17486..aa2ce01 100644
--- a/hw/qdev.c
+++ b/hw/qdev.c
@@ -779,19 +779,6 @@
     }
 }
 
-/**
- * do_device_add(): Add a device
- *
- * Argument qdict contains
- * - "driver": the name of the new device's driver
- * - "bus": the device's parent bus (device tree path)
- * - "id": the device's ID (must be unique)
- * - device properties
- *
- * Example:
- *
- * { "driver": "usb-net", "id": "eth1", "netdev": "netdev1" }
- */
 int do_device_add(Monitor *mon, const QDict *qdict, QObject **ret_data)
 {
     QemuOpts *opts;
diff --git a/hw/spitz.c b/hw/spitz.c
index c3b5cd8..4f82e24 100644
--- a/hw/spitz.c
+++ b/hw/spitz.c
@@ -993,9 +993,6 @@
         /* A 4.0 GB microdrive is permanently sitting in CF slot 0.  */
         spitz_microdrive_attach(cpu, 0);
 
-    /* Setup initial (reset) machine state */
-    cpu->env->regs[15] = spitz_binfo.loader_start;
-
     spitz_binfo.kernel_filename = kernel_filename;
     spitz_binfo.kernel_cmdline = kernel_cmdline;
     spitz_binfo.initrd_filename = initrd_filename;
diff --git a/hw/sun4m.c b/hw/sun4m.c
index 7ba0f76..e4ca8f3 100644
--- a/hw/sun4m.c
+++ b/hw/sun4m.c
@@ -93,7 +93,7 @@
 #define ESCC_CLOCK 4915200
 
 struct sun4m_hwdef {
-    target_phys_addr_t iommu_base, slavio_base;
+    target_phys_addr_t iommu_base, iommu_pad_base, iommu_pad_len, slavio_base;
     target_phys_addr_t intctl_base, counter_base, nvram_base, ms_kb_base;
     target_phys_addr_t serial_base, fd_base;
     target_phys_addr_t afx_base, idreg_base, dma_base, esp_base, le_base;
@@ -854,6 +854,14 @@
     iommu = iommu_init(hwdef->iommu_base, hwdef->iommu_version,
                        slavio_irq[30]);
 
+    if (hwdef->iommu_pad_base) {
+        /* On the real hardware (SS-5, LX) the MMU is not padded, but aliased.
+           Software shouldn't use aliased addresses, neither should it crash
+           when does. Using empty_slot instead of aliasing can help with
+           debugging such accesses */
+        empty_slot_init(hwdef->iommu_pad_base,hwdef->iommu_pad_len);
+    }
+
     espdma = sparc32_dma_init(hwdef->dma_base, slavio_irq[18],
                               iommu, &espdma_irq);
 
@@ -965,6 +973,8 @@
     /* SS-5 */
     {
         .iommu_base   = 0x10000000,
+        .iommu_pad_base = 0x10004000,
+        .iommu_pad_len  = 0x0fffb000,
         .tcx_base     = 0x50000000,
         .cs_base      = 0x6c000000,
         .slavio_base  = 0x70000000,
@@ -1091,6 +1101,8 @@
     /* LX */
     {
         .iommu_base   = 0x10000000,
+        .iommu_pad_base = 0x10004000,
+        .iommu_pad_len  = 0x0fffb000,
         .tcx_base     = 0x50000000,
         .slavio_base  = 0x70000000,
         .ms_kb_base   = 0x71000000,
diff --git a/hw/tosa.c b/hw/tosa.c
index bc6591f..fbe8d8c 100644
--- a/hw/tosa.c
+++ b/hw/tosa.c
@@ -229,9 +229,6 @@
 
     tosa_tg_init(cpu);
 
-    /* Setup initial (reset) machine state */
-    cpu->env->regs[15] = tosa_binfo.loader_start;
-
     tosa_binfo.kernel_filename = kernel_filename;
     tosa_binfo.kernel_cmdline = kernel_cmdline;
     tosa_binfo.initrd_filename = initrd_filename;
diff --git a/hw/virtio-serial-bus.c b/hw/virtio-serial-bus.c
index 3ce95e8..7f9d28f 100644
--- a/hw/virtio-serial-bus.c
+++ b/hw/virtio-serial-bus.c
@@ -774,7 +774,8 @@
     }
 
     vser->config.max_nr_ports = max_nr_ports;
-    vser->ports_map = qemu_mallocz((max_nr_ports + 31) / 32);
+    vser->ports_map = qemu_mallocz(((max_nr_ports + 31) / 32)
+        * sizeof(vser->ports_map[0]));
     /*
      * Reserve location 0 for a console port for backward compat
      * (old kernel, new qemu)
diff --git a/hxtool b/hxtool
index 8f65532..d499dc0 100644
--- a/hxtool
+++ b/hxtool
@@ -7,7 +7,7 @@
         case $str in
             HXCOMM*)
             ;;
-            STEXI*|ETEXI*) flag=$(($flag^1))
+            STEXI*|ETEXI*|SQMP*|EQMP*) flag=$(($flag^1))
             ;;
             *)
             test $flag -eq 1 && printf "%s\n" "$str"
@@ -38,6 +38,12 @@
             fi
             flag=0
             ;;
+            SQMP*|EQMP*)
+            if test $flag -eq 1 ; then
+                echo "line $line: syntax error: expected ETEXI, found $str" >&2
+                exit 1
+            fi
+            ;;
             DEFHEADING*)
             echo "$(expr "$str" : "DEFHEADING(\(.*\))")"
             ;;
@@ -49,9 +55,45 @@
     done
 }
 
+hxtoqmp()
+{
+    IFS=
+    flag=0
+    while read -r str; do
+        case "$str" in
+            HXCOMM*)
+            ;;
+            SQMP*)
+            if test $flag -eq 1 ; then
+                echo "line $line: syntax error: expected EQMP, found $str" >&2
+                exit 1
+            fi
+            flag=1
+            ;;
+            EQMP*)
+            if test $flag -ne 1 ; then
+                echo "line $line: syntax error: expected SQMP, found $str" >&2
+                exit 1
+            fi
+            flag=0
+            ;;
+            STEXI*|ETEXI*)
+            if test $flag -eq 1 ; then
+                echo "line $line: syntax error: expected EQMP, found $str" >&2
+                exit 1
+            fi
+            ;;
+            *)
+            test $flag -eq 1 && echo "$str"
+            ;;
+        esac
+    done
+}
+
 case "$1" in
 "-h") hxtoh ;;
 "-t") hxtotexi ;;
+"-q") hxtoqmp ;;
 *) exit 1 ;;
 esac
 
diff --git a/input.c b/input.c
index 8f0941e..651442d 100644
--- a/input.c
+++ b/input.c
@@ -214,24 +214,6 @@
     qlist_iter(mice_list, info_mice_iter, mon);
 }
 
-/**
- * do_info_mice(): Show VM mice information
- *
- * Each mouse is represented by a QDict, the returned QObject is a QList of
- * all mice.
- *
- * The mouse QDict contains the following:
- *
- * - "name": mouse's name
- * - "index": mouse's index
- * - "current": true if this mouse is receiving events, false otherwise
- * - "absolute": true if the mouse generates absolute input events
- *
- * Example:
- *
- * [ { "name": "QEMU Microsoft Mouse", "index": 0, "current": false, "absolute": false },
- *   { "name": "QEMU PS/2 Mouse", "index": 1, "current": true, "absolute": true } ]
- */
 void do_info_mice(Monitor *mon, QObject **ret_data)
 {
     QEMUPutMouseEntry *cursor;
diff --git a/linux-user/elfload.c b/linux-user/elfload.c
index 1f27918..2d920f2 100644
--- a/linux-user/elfload.c
+++ b/linux-user/elfload.c
@@ -1682,7 +1682,7 @@
      * In case where user has not explicitly set the guest_base, we
      * probe here that should we set it automatically.
      */
-    if (!have_guest_base) {
+    if (!(have_guest_base || reserved_va)) {
         /*
          * Go through ELF program header table and find the address
          * range used by loadable segments.  Check that this is available on
diff --git a/linux-user/flatload.c b/linux-user/flatload.c
index 6a2c3f9..914de1f 100644
--- a/linux-user/flatload.c
+++ b/linux-user/flatload.c
@@ -338,7 +338,7 @@
 static void old_reloc(struct lib_info *libinfo, uint32_t rl)
 {
 #ifdef DEBUG
-	char *segment[] = { "TEXT", "DATA", "BSS", "*UNKNOWN*" };
+	const char *segment[] = { "TEXT", "DATA", "BSS", "*UNKNOWN*" };
 #endif
 	uint32_t *ptr;
         uint32_t offset;
diff --git a/linux-user/main.c b/linux-user/main.c
index b240f29..0f23fc9 100644
--- a/linux-user/main.c
+++ b/linux-user/main.c
@@ -44,6 +44,7 @@
 #if defined(CONFIG_USE_GUEST_BASE)
 unsigned long guest_base;
 int have_guest_base;
+unsigned long reserved_va;
 #endif
 
 static const char *interp_prefix = CONFIG_QEMU_PREFIX;
@@ -2433,7 +2434,8 @@
             env->lock_addr = -1;
             info.si_signo = TARGET_SIGSEGV;
             info.si_errno = 0;
-            info.si_code = 0;  /* ??? SEGV_MAPERR vs SEGV_ACCERR.  */
+            info.si_code = (page_get_flags(env->ipr[IPR_EXC_ADDR]) & PAGE_VALID
+                            ? TARGET_SEGV_ACCERR : TARGET_SEGV_MAPERR);
             info._sifields._sigfault._addr = env->ipr[IPR_EXC_ADDR];
             queue_signal(env, info.si_signo, &info);
             break;
@@ -2609,6 +2611,7 @@
            "-0 argv0          forces target process argv[0] to be argv0\n"
 #if defined(CONFIG_USE_GUEST_BASE)
            "-B address        set guest_base address to address\n"
+           "-R size           reserve size bytes for guest virtual address space\n"
 #endif
            "\n"
            "Debug options:\n"
@@ -2804,6 +2807,39 @@
         } else if (!strcmp(r, "B")) {
            guest_base = strtol(argv[optind++], NULL, 0);
            have_guest_base = 1;
+        } else if (!strcmp(r, "R")) {
+            char *p;
+            int shift = 0;
+            reserved_va = strtoul(argv[optind++], &p, 0);
+            switch (*p) {
+            case 'k':
+            case 'K':
+                shift = 10;
+                break;
+            case 'M':
+                shift = 20;
+                break;
+            case 'G':
+                shift = 30;
+                break;
+            }
+            if (shift) {
+                unsigned long unshifted = reserved_va;
+                p++;
+                reserved_va <<= shift;
+                if (((reserved_va >> shift) != unshifted)
+#if HOST_LONG_BITS > TARGET_VIRT_ADDR_SPACE_BITS
+                    || (reserved_va > (1ul << TARGET_VIRT_ADDR_SPACE_BITS))
+#endif
+                    ) {
+                    fprintf(stderr, "Reserved virtual address too big\n");
+                    exit(1);
+                }
+            }
+            if (*p) {
+                fprintf(stderr, "Unrecognised -R size suffix '%s'\n", p);
+                exit(1);
+            }
 #endif
         } else if (!strcmp(r, "drop-ld-preload")) {
             (void) envlist_unsetenv(envlist, "LD_PRELOAD");
@@ -2892,6 +2928,34 @@
      * proper page alignment for guest_base.
      */
     guest_base = HOST_PAGE_ALIGN(guest_base);
+
+    if (reserved_va) {
+        void *p;
+        int flags;
+
+        flags = MAP_ANONYMOUS | MAP_PRIVATE | MAP_NORESERVE;
+        if (have_guest_base) {
+            flags |= MAP_FIXED;
+        }
+        p = mmap((void *)guest_base, reserved_va, PROT_NONE, flags, -1, 0);
+        if (p == MAP_FAILED) {
+            fprintf(stderr, "Unable to reserve guest address space\n");
+            exit(1);
+        }
+        guest_base = (unsigned long)p;
+        /* Make sure the address is properly aligned.  */
+        if (guest_base & ~qemu_host_page_mask) {
+            munmap(p, reserved_va);
+            p = mmap((void *)guest_base, reserved_va + qemu_host_page_size,
+                     PROT_NONE, flags, -1, 0);
+            if (p == MAP_FAILED) {
+                fprintf(stderr, "Unable to reserve guest address space\n");
+                exit(1);
+            }
+            guest_base = HOST_PAGE_ALIGN((unsigned long)p);
+        }
+        qemu_log("Reserved 0x%lx bytes of guest address space\n", reserved_va);
+    }
 #endif /* CONFIG_USE_GUEST_BASE */
 
     /*
diff --git a/linux-user/mmap.c b/linux-user/mmap.c
index 9c062e7..39da6df 100644
--- a/linux-user/mmap.c
+++ b/linux-user/mmap.c
@@ -77,58 +77,6 @@
 }
 #endif
 
-void *qemu_vmalloc(size_t size)
-{
-    void *p;
-
-    mmap_lock();
-    /* Use map and mark the pages as used.  */
-    p = mmap(NULL, size, PROT_READ | PROT_WRITE,
-             MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
-    mmap_unlock();
-    return p;
-}
-
-void *qemu_malloc(size_t size)
-{
-    char * p;
-    size += 16;
-    p = qemu_vmalloc(size);
-    *(size_t *)p = size;
-    return p + 16;
-}
-
-/* We use map, which is always zero initialized.  */
-void * qemu_mallocz(size_t size)
-{
-    return qemu_malloc(size);
-}
-
-void qemu_free(void *ptr)
-{
-    /* FIXME: We should unmark the reserved pages here.  However this gets
-       complicated when one target page spans multiple host pages, so we
-       don't bother.  */
-    size_t *p;
-    p = (size_t *)((char *)ptr - 16);
-    munmap(p, *p);
-}
-
-void *qemu_realloc(void *ptr, size_t size)
-{
-    size_t old_size, copy;
-    void *new_ptr;
-
-    if (!ptr)
-        return qemu_malloc(size);
-    old_size = *(size_t *)((char *)ptr - 16);
-    copy = old_size < size ? old_size : size;
-    new_ptr = qemu_malloc(size);
-    memcpy(new_ptr, ptr, copy);
-    qemu_free(ptr);
-    return new_ptr;
-}
-
 /* NOTE: all the constants are the HOST ones, but addresses are target. */
 int target_mprotect(abi_ulong start, abi_ulong len, int prot)
 {
@@ -268,6 +216,40 @@
 
 unsigned long last_brk;
 
+/* Subroutine of mmap_find_vma, used when we have pre-allocated a chunk
+   of guest address space.  */
+static abi_ulong mmap_find_vma_reserved(abi_ulong start, abi_ulong size)
+{
+    abi_ulong addr;
+    abi_ulong last_addr;
+    int prot;
+    int looped = 0;
+
+    if (size > reserved_va) {
+        return (abi_ulong)-1;
+    }
+
+    last_addr = start;
+    for (addr = start; last_addr + size != addr; addr += qemu_host_page_size) {
+        if (last_addr + size >= reserved_va
+            || (abi_ulong)(last_addr + size) < last_addr) {
+            if (looped) {
+                return (abi_ulong)-1;
+            }
+            last_addr = qemu_host_page_size;
+            addr = 0;
+            looped = 1;
+            continue;
+        }
+        prot = page_get_flags(addr);
+        if (prot) {
+            last_addr = addr + qemu_host_page_size;
+        }
+    }
+    mmap_next_start = addr;
+    return last_addr;
+}
+
 /*
  * Find and reserve a free memory area of size 'size'. The search
  * starts at 'start'.
@@ -289,6 +271,10 @@
 
     size = HOST_PAGE_ALIGN(size);
 
+    if (reserved_va) {
+        return mmap_find_vma_reserved(start, size);
+    }
+
     addr = start;
     wrapped = repeat = 0;
     prev = 0;
@@ -577,6 +563,47 @@
     return -1;
 }
 
+static void mmap_reserve(abi_ulong start, abi_ulong size)
+{
+    abi_ulong real_start;
+    abi_ulong real_end;
+    abi_ulong addr;
+    abi_ulong end;
+    int prot;
+
+    real_start = start & qemu_host_page_mask;
+    real_end = HOST_PAGE_ALIGN(start + size);
+    end = start + size;
+    if (start > real_start) {
+        /* handle host page containing start */
+        prot = 0;
+        for (addr = real_start; addr < start; addr += TARGET_PAGE_SIZE) {
+            prot |= page_get_flags(addr);
+        }
+        if (real_end == real_start + qemu_host_page_size) {
+            for (addr = end; addr < real_end; addr += TARGET_PAGE_SIZE) {
+                prot |= page_get_flags(addr);
+            }
+            end = real_end;
+        }
+        if (prot != 0)
+            real_start += qemu_host_page_size;
+    }
+    if (end < real_end) {
+        prot = 0;
+        for (addr = end; addr < real_end; addr += TARGET_PAGE_SIZE) {
+            prot |= page_get_flags(addr);
+        }
+        if (prot != 0)
+            real_end -= qemu_host_page_size;
+    }
+    if (real_start != real_end) {
+        mmap(g2h(real_start), real_end - real_start, PROT_NONE,
+                 MAP_FIXED | MAP_ANONYMOUS | MAP_PRIVATE | MAP_NORESERVE,
+                 -1, 0);
+    }
+}
+
 int target_munmap(abi_ulong start, abi_ulong len)
 {
     abi_ulong end, real_start, real_end, addr;
@@ -624,7 +651,11 @@
     ret = 0;
     /* unmap what we can */
     if (real_start < real_end) {
-        ret = munmap(g2h(real_start), real_end - real_start);
+        if (reserved_va) {
+            mmap_reserve(real_start, real_end - real_start);
+        } else {
+            ret = munmap(g2h(real_start), real_end - real_start);
+        }
     }
 
     if (ret == 0)
@@ -642,12 +673,18 @@
 
     mmap_lock();
 
-    if (flags & MREMAP_FIXED)
+    if (flags & MREMAP_FIXED) {
         host_addr = (void *) syscall(__NR_mremap, g2h(old_addr),
                                      old_size, new_size,
                                      flags,
-                                     new_addr);
-    else if (flags & MREMAP_MAYMOVE) {
+                                     g2h(new_addr));
+
+        if (reserved_va && host_addr != MAP_FAILED) {
+            /* If new and old addresses overlap then the above mremap will
+               already have failed with EINVAL.  */
+            mmap_reserve(old_addr, old_size);
+        }
+    } else if (flags & MREMAP_MAYMOVE) {
         abi_ulong mmap_start;
 
         mmap_start = mmap_find_vma(0, new_size);
@@ -655,13 +692,32 @@
         if (mmap_start == -1) {
             errno = ENOMEM;
             host_addr = MAP_FAILED;
-        } else
+        } else {
             host_addr = (void *) syscall(__NR_mremap, g2h(old_addr),
                                          old_size, new_size,
                                          flags | MREMAP_FIXED,
                                          g2h(mmap_start));
+            mmap_reserve(old_addr, old_size);
+        }
     } else {
-        host_addr = mremap(g2h(old_addr), old_size, new_size, flags);
+        int prot = 0;
+        if (reserved_va && old_size < new_size) {
+            abi_ulong addr;
+            for (addr = old_addr + old_size;
+                 addr < old_addr + new_size;
+                 addr++) {
+                prot |= page_get_flags(addr);
+            }
+        }
+        if (prot == 0) {
+            host_addr = mremap(g2h(old_addr), old_size, new_size, flags);
+            if (host_addr != MAP_FAILED && reserved_va && old_size > new_size) {
+                mmap_reserve(old_addr + old_size, new_size - old_size);
+            }
+        } else {
+            errno = ENOMEM;
+            host_addr = MAP_FAILED;
+        }
         /* Check if address fits target address space */
         if ((unsigned long)host_addr + new_size > (abi_ulong)-1) {
             /* Revert mremap() changes */
diff --git a/migration-exec.c b/migration-exec.c
index 5435827..93bde62 100644
--- a/migration-exec.c
+++ b/migration-exec.c
@@ -43,13 +43,21 @@
 
 static int exec_close(FdMigrationState *s)
 {
+    int ret = 0;
     DPRINTF("exec_close\n");
     if (s->opaque) {
-        qemu_fclose(s->opaque);
+        ret = qemu_fclose(s->opaque);
         s->opaque = NULL;
         s->fd = -1;
+        if (ret != -1 &&
+            WIFEXITED(ret)
+            && WEXITSTATUS(ret) == 0) {
+            ret = 0;
+        } else {
+            ret = -1;
+        }
     }
-    return 0;
+    return ret;
 }
 
 MigrationState *exec_start_outgoing_migration(Monitor *mon,
diff --git a/migration.c b/migration.c
index 05f6cc5..fbf2339 100644
--- a/migration.c
+++ b/migration.c
@@ -197,44 +197,6 @@
     qdict_put_obj(qdict, name, obj);
 }
 
-/**
- * do_info_migrate(): Migration status
- *
- * Return a QDict. If migration is active there will be another
- * QDict with RAM migration status and if block migration is active
- * another one with block migration status.
- *
- * The main QDict contains the following:
- *
- * - "status": migration status
- * - "ram": only present if "status" is "active", it is a QDict with the
- *   following RAM information (in bytes):
- *          - "transferred": amount transferred
- *          - "remaining": amount remaining
- *          - "total": total
- * - "disk": only present if "status" is "active" and it is a block migration,
- *   it is a QDict with the following disk information (in bytes):
- *          - "transferred": amount transferred
- *          - "remaining": amount remaining
- *          - "total": total
- *
- * Examples:
- *
- * 1. Migration is "completed":
- *
- * { "status": "completed" }
- *
- * 2. Migration is "active" and it is not a block migration:
- *
- * { "status": "active",
- *            "ram": { "transferred": 123, "remaining": 123, "total": 246 } }
- *
- * 3. Migration is "active" and it is a block migration:
- *
- * { "status": "active",
- *   "ram": { "total": 1057024, "remaining": 1053304, "transferred": 3720 },
- *   "disk": { "total": 20971520, "remaining": 20880384, "transferred": 91136 }}
- */
 void do_info_migrate(Monitor *mon, QObject **ret_data)
 {
     QDict *qdict;
@@ -290,13 +252,17 @@
     migrate_fd_cleanup(s);
 }
 
-void migrate_fd_cleanup(FdMigrationState *s)
+int migrate_fd_cleanup(FdMigrationState *s)
 {
+    int ret = 0;
+
     qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
 
     if (s->file) {
         DPRINTF("closing file\n");
-        qemu_fclose(s->file);
+        if (qemu_fclose(s->file) != 0) {
+            ret = -1;
+        }
         s->file = NULL;
     }
 
@@ -309,6 +275,8 @@
     }
 
     s->fd = -1;
+
+    return ret;
 }
 
 void migrate_fd_put_notify(void *opaque)
@@ -387,7 +355,12 @@
         } else {
             state = MIG_STATE_COMPLETED;
         }
-        migrate_fd_cleanup(s);
+        if (migrate_fd_cleanup(s) < 0) {
+            if (old_vm_running) {
+                vm_start();
+            }
+            state = MIG_STATE_ERROR;
+        }
         s->state = state;
     }
 }
diff --git a/migration.h b/migration.h
index 385423f..97eef4a 100644
--- a/migration.h
+++ b/migration.h
@@ -107,7 +107,7 @@
 
 void migrate_fd_error(FdMigrationState *s);
 
-void migrate_fd_cleanup(FdMigrationState *s);
+int migrate_fd_cleanup(FdMigrationState *s);
 
 void migrate_fd_put_notify(void *opaque);
 
diff --git a/monitor.c b/monitor.c
index ad50f12..15b53b9 100644
--- a/monitor.c
+++ b/monitor.c
@@ -677,18 +677,6 @@
                                   qdict_get_str(qdict, "package"));
 }
 
-/**
- * do_info_version(): Show QEMU version
- *
- * Return a QDict with the following information:
- *
- * - "qemu": QEMU's version
- * - "package": package's version
- *
- * Example:
- *
- * { "qemu": "0.11.50", "package": "" }
- */
 static void do_info_version(Monitor *mon, QObject **ret_data)
 {
     *ret_data = qobject_from_jsonf("{ 'qemu': %s, 'package': %s }",
@@ -707,17 +695,6 @@
     monitor_printf(mon, "%s\n", qdict_get_str(qdict, "name"));
 }
 
-/**
- * do_info_name(): Show VM name
- *
- * Return a QDict with the following information:
- *
- * - "name": VM's name (optional)
- *
- * Example:
- *
- * { "name": "qemu-name" }
- */
 static void do_info_name(Monitor *mon, QObject **ret_data)
 {
     *ret_data = qemu_name ? qobject_from_jsonf("{'name': %s }", qemu_name) :
@@ -739,20 +716,6 @@
     return qobject_from_jsonf("{ 'name': %s }", p);
 }
 
-/**
- * do_info_commands(): List QMP available commands
- *
- * Each command is represented by a QDict, the returned QObject is a QList
- * of all commands.
- *
- * The QDict contains:
- *
- * - "name": command's name
- *
- * Example:
- *
- * { [ { "name": "query-balloon" }, { "name": "system_powerdown" } ] }
- */
 static void do_info_commands(Monitor *mon, QObject **ret_data)
 {
     QList *cmd_list;
@@ -785,17 +748,6 @@
                    "enabled" : "disabled");
 }
 
-/**
- * do_info_hpet(): Show HPET state
- *
- * Return a QDict with the following information:
- *
- * - "enabled": true if hpet if enabled, false otherwise
- *
- * Example:
- *
- * { "enabled": true }
- */
 static void do_info_hpet(Monitor *mon, QObject **ret_data)
 {
     *ret_data = qobject_from_jsonf("{ 'enabled': %i }", !no_hpet);
@@ -807,17 +759,6 @@
     monitor_printf(mon, "%s\n", qdict_get_str(qobject_to_qdict(data), "UUID"));
 }
 
-/**
- * do_info_uuid(): Show VM UUID
- *
- * Return a QDict with the following information:
- *
- * - "UUID": Universally Unique Identifier
- *
- * Example:
- *
- * { "UUID": "550e8400-e29b-41d4-a716-446655440000" }
- */
 static void do_info_uuid(Monitor *mon, QObject **ret_data)
 {
     char uuid[64];
@@ -913,25 +854,6 @@
     qlist_iter(cpu_list, print_cpu_iter, mon);
 }
 
-/**
- * do_info_cpus(): Show CPU information
- *
- * Return a QList. Each CPU is represented by a QDict, which contains:
- *
- * - "cpu": CPU index
- * - "current": true if this is the current CPU, false otherwise
- * - "halted": true if the cpu is halted, false otherwise
- * - Current program counter. The key's name depends on the architecture:
- *      "pc": i386/x86)64
- *      "nip": PPC
- *      "pc" and "npc": sparc
- *      "PC": mips
- *
- * Example:
- *
- * [ { "CPU": 0, "current": true, "halted": false, "pc": 3227107138 },
- *   { "CPU": 1, "current": false, "halted": true, "pc": 7108165 } ]
- */
 static void do_info_cpus(Monitor *mon, QObject **ret_data)
 {
     CPUState *env;
@@ -2106,18 +2028,6 @@
     }
 }
 
-/**
- * do_info_kvm(): Show KVM information
- *
- * Return a QDict with the following information:
- *
- * - "enabled": true if KVM support is enabled, false otherwise
- * - "present": true if QEMU has KVM support, false otherwise
- *
- * Example:
- *
- * { "enabled": true, "present": true }
- */
 static void do_info_kvm(Monitor *mon, QObject **ret_data)
 {
 #ifdef CONFIG_KVM
@@ -2261,18 +2171,6 @@
     monitor_printf(mon, "\n");
 }
 
-/**
- * do_info_status(): VM status
- *
- * Return a QDict with the following information:
- *
- * - "running": true if the VM is running, or false if it is paused
- * - "singlestep": true if the VM is in single step mode, false otherwise
- *
- * Example:
- *
- * { "running": true, "singlestep": false }
- */
 static void do_info_status(Monitor *mon, QObject **ret_data)
 {
     *ret_data = qobject_from_jsonf("{ 'running': %i, 'singlestep': %i }",
diff --git a/net.c b/net.c
index 378edfc..efa8b3d 100644
--- a/net.c
+++ b/net.c
@@ -1194,18 +1194,6 @@
     qemu_del_vlan_client(vc);
 }
 
-/**
- * do_netdev_add(): Add a host network device
- *
- * Argument qdict contains
- * - "type": the device type, "tap", "user", ...
- * - "id": the device's ID (must be unique)
- * - device options
- *
- * Example:
- *
- * { "type": "user", "id": "netdev1", "hostname": "a-guest" }
- */
 int do_netdev_add(Monitor *mon, const QDict *qdict, QObject **ret_data)
 {
     QemuOpts *opts;
@@ -1220,16 +1208,6 @@
     return res;
 }
 
-/**
- * do_netdev_del(): Delete a host network device
- *
- * Argument qdict contains
- * - "id": the device's ID
- *
- * Example:
- *
- * { "id": "netdev1" }
- */
 int do_netdev_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
 {
     const char *id = qdict_get_str(qdict, "id");
diff --git a/qemu-char.c b/qemu-char.c
index ac65a1c..faaf624 100644
--- a/qemu-char.c
+++ b/qemu-char.c
@@ -2528,22 +2528,6 @@
     qlist_iter(qobject_to_qlist(ret_data), qemu_chr_qlist_iter, mon);
 }
 
-/**
- * qemu_chr_info(): Character devices information
- *
- * Each device is represented by a QDict. The returned QObject is a QList
- * of all devices.
- *
- * The QDict contains the following:
- *
- * - "label": device's label
- * - "filename": device's file
- *
- * Example:
- *
- * [ { "label": "monitor", "filename", "stdio" },
- *   { "label": "serial0", "filename": "vc" } ]
- */
 void qemu_chr_info(Monitor *mon, QObject **ret_data)
 {
     QList *chr_list;
diff --git a/qemu-doc.texi b/qemu-doc.texi
index 6647b7b..e2c8e56 100644
--- a/qemu-doc.texi
+++ b/qemu-doc.texi
@@ -2124,7 +2124,7 @@
 @subsection Command line options
 
 @example
-usage: qemu-i386 [-h] [-d] [-L path] [-s size] [-cpu model] [-g port] [-B offset] program [arguments...]
+usage: qemu-i386 [-h] [-d] [-L path] [-s size] [-cpu model] [-g port] [-B offset] [-R size] program [arguments...]
 @end example
 
 @table @option
@@ -2140,6 +2140,9 @@
 Offset guest address by the specified number of bytes.  This is useful when
 the address region rewuired by guest applications is reserved on the host.
 Ths option is currently only supported on some hosts.
+@item -R size
+Pre-allocate a guest virtual address space of the given size (in bytes).
+"G", "M", and "k" suffixes may be used when specifying the size.  
 @end table
 
 Debug options:
diff --git a/qemu-malloc.c b/qemu-malloc.c
index 6cdc5de..1b33e04 100644
--- a/qemu-malloc.c
+++ b/qemu-malloc.c
@@ -69,10 +69,10 @@
 
 void *qemu_mallocz(size_t size)
 {
-    void *ptr;
-    ptr = qemu_malloc(size);
-    memset(ptr, 0, size);
-    return ptr;
+    if (!size && !allow_zero_malloc()) {
+        abort();
+    }
+    return oom_check(calloc(1, size ? size : 1));
 }
 
 char *qemu_strdup(const char *str)
diff --git a/qemu-monitor.hx b/qemu-monitor.hx
index b6e3467..f6a94f2 100644
--- a/qemu-monitor.hx
+++ b/qemu-monitor.hx
@@ -1,10 +1,48 @@
 HXCOMM Use DEFHEADING() to define headings in both help text and texi
 HXCOMM Text between STEXI and ETEXI are copied to texi version and
 HXCOMM discarded from C version
+HXCOMM Text between SQMP and EQMP is copied to the QMP documention file and
+HXCOMM does not show up in the other formats.
 HXCOMM DEF(command, args, callback, arg_string, help) is used to construct
 HXCOMM monitor commands
 HXCOMM HXCOMM can be used for comments, discarded from both texi and C
 
+SQMP
+                        QMP Supported Commands
+                        ----------------------
+
+This document describes all commands currently supported by QMP.
+
+Most of the time their usage is exactly the same as in the user Monitor, this
+means that any other document which also describe commands (the manpage,
+QEMU's manual, etc) can and should be consulted.
+
+QMP has two types of commands: regular and query commands. Regular commands
+usually change the Virtual Machine's state someway, while query commands just
+return information. The sections below are divided accordingly.
+
+It's important to observe that all communication examples are formatted in
+a reader-friendly way, so that they're easier to understand. However, in real
+protocol usage, they're emitted as a single line.
+
+Also, the following notation is used to denote data flow:
+
+-> data issued by the Client
+<- Server data response
+
+Please, refer to the QMP specification (QMP/qmp-spec.txt) for detailed
+information on the Server command and response formats.
+
+NOTE: This document is temporary and will be replaced soon.
+
+1. Regular Commands
+===================
+
+Server's responses in the examples below are always a success response, please
+refer to the QMP specification for more details on error responses.
+
+EQMP
+
 STEXI
 @table @option
 ETEXI
@@ -38,86 +76,6 @@
 ETEXI
 
     {
-        .name       = "info",
-        .args_type  = "item:s?",
-        .params     = "[subcommand]",
-        .help       = "show various information about the system state",
-        .user_print = monitor_user_noop,
-        .mhandler.cmd_new = do_info,
-    },
-
-STEXI
-@item info @var{subcommand}
-@findex info
-Show various information about the system state.
-
-@table @option
-@item info version
-show the version of QEMU
-@item info network
-show the various VLANs and the associated devices
-@item info chardev
-show the character devices
-@item info block
-show the block devices
-@item info block
-show block device statistics
-@item info registers
-show the cpu registers
-@item info cpus
-show infos for each CPU
-@item info history
-show the command line history
-@item info irq
-show the interrupts statistics (if available)
-@item info pic
-show i8259 (PIC) state
-@item info pci
-show emulated PCI device info
-@item info tlb
-show virtual to physical memory mappings (i386 only)
-@item info mem
-show the active virtual memory mappings (i386 only)
-@item info hpet
-show state of HPET (i386 only)
-@item info kvm
-show KVM information
-@item info usb
-show USB devices plugged on the virtual USB hub
-@item info usbhost
-show all USB host devices
-@item info profile
-show profiling information
-@item info capture
-show information about active capturing
-@item info snapshots
-show list of VM snapshots
-@item info status
-show the current VM status (running|paused)
-@item info pcmcia
-show guest PCMCIA status
-@item info mice
-show which guest mouse is receiving events
-@item info vnc
-show the vnc server status
-@item info name
-show the current VM name
-@item info uuid
-show the current VM UUID
-@item info cpustats
-show CPU statistics
-@item info usernet
-show user network stack connection states
-@item info migrate
-show migration status
-@item info balloon
-show balloon information
-@item info qtree
-show device tree
-@end table
-ETEXI
-
-    {
         .name       = "q|quit",
         .args_type  = "",
         .params     = "",
@@ -131,6 +89,20 @@
 @findex quit
 Quit the emulator.
 ETEXI
+SQMP
+quit
+----
+
+Quit the emulator.
+
+Arguments: None.
+
+Example:
+
+-> { "execute": "quit" }
+<- { "return": {} }
+
+EQMP
 
     {
         .name       = "eject",
@@ -146,6 +118,25 @@
 @findex eject
 Eject a removable medium (use -f to force it).
 ETEXI
+SQMP
+eject
+-----
+
+Eject a removable medium.
+
+Arguments: 
+
+- force: force ejection (json-bool, optional)
+- device: device name (json-string)
+
+Example:
+
+-> { "execute": "eject", "arguments": { "device": "ide1-cd0" } }
+<- { "return": {} }
+
+Note: The "force" argument defaults to false.
+
+EQMP
 
     {
         .name       = "change",
@@ -193,6 +184,35 @@
 
 @end table
 ETEXI
+SQMP
+change
+------
+
+Change a removable medium or VNC configuration.
+
+Arguments:
+
+- "device": device name (json-string)
+- "target": filename or item (json-string)
+- "arg": additional argument (json-string, optional)
+
+Examples:
+
+1. Change a removable medium
+
+-> { "execute": "change",
+             "arguments": { "device": "ide1-cd0",
+                            "target": "/srv/images/Fedora-12-x86_64-DVD.iso" } }
+<- { "return": {} }
+
+2. Change VNC password
+
+-> { "execute": "change",
+             "arguments": { "device": "vnc", "target": "password",
+                            "arg": "foobar1" } }
+<- { "return": {} }
+
+EQMP
 
     {
         .name       = "screendump",
@@ -208,6 +228,22 @@
 @findex screendump
 Save screen into PPM image @var{filename}.
 ETEXI
+SQMP
+screendump
+----------
+
+Save screen into PPM image.
+
+Arguments:
+
+- "filename": file path (json-string)
+
+Example:
+
+-> { "execute": "screendump", "arguments": { "filename": "/tmp/image" } }
+<- { "return": {} }
+
+EQMP
 
     {
         .name       = "logfile",
@@ -312,6 +348,20 @@
 @findex stop
 Stop emulation.
 ETEXI
+SQMP
+stop
+----
+
+Stop the emulator.
+
+Arguments: None.
+
+Example:
+
+-> { "execute": "stop" }
+<- { "return": {} }
+
+EQMP
 
     {
         .name       = "c|cont",
@@ -327,6 +377,20 @@
 @findex cont
 Resume emulation.
 ETEXI
+SQMP
+cont
+----
+
+Resume emulation.
+
+Arguments: None.
+
+Example:
+
+-> { "execute": "cont" }
+<- { "return": {} }
+
+EQMP
 
     {
         .name       = "gdbserver",
@@ -501,6 +565,20 @@
 
 Reset the system.
 ETEXI
+SQMP
+system_reset
+------------
+
+Reset the system.
+
+Arguments: None.
+
+Example:
+
+-> { "execute": "system_reset" }
+<- { "return": {} }
+
+EQMP
 
     {
         .name       = "system_powerdown",
@@ -517,6 +595,20 @@
 
 Power down the system (if supported).
 ETEXI
+SQMP
+system_powerdown
+----------------
+
+Send system power down event.
+
+Arguments: None.
+
+Example:
+
+-> { "execute": "system_powerdown" }
+<- { "return": {} }
+
+EQMP
 
     {
         .name       = "sum",
@@ -581,6 +673,33 @@
 
 Add device.
 ETEXI
+SQMP
+device_add
+----------
+
+Add a device.
+
+Arguments:
+
+- "driver": the name of the new device's driver (json-string)
+- "bus": the device's parent bus (device tree path, json-string, optional)
+- "id": the device's ID, must be unique (json-string)
+- device properties
+
+Example:
+
+-> { "execute": "device_add", "arguments": { "driver": "e1000", "id": "net1" } }
+<- { "return": {} }
+
+Notes:
+
+(1) For detailed information about this command, please refer to the
+    'docs/qdev-device-use.txt' file.
+
+(2) It's possible to list device properties by running QEMU with the
+    "-device DEVICE,\?" command-line argument, where DEVICE is the device's name
+
+EQMP
 
     {
         .name       = "device_del",
@@ -597,6 +716,22 @@
 
 Remove device @var{id}.
 ETEXI
+SQMP
+device_del
+----------
+
+Remove a device.
+
+Arguments:
+
+- "id": the device's ID (json-string)
+
+Example:
+
+-> { "execute": "device_del", "arguments": { "id": "net1" } }
+<- { "return": {} }
+
+EQMP
 
     {
         .name       = "cpu",
@@ -612,6 +747,24 @@
 @findex cpu
 Set the default CPU.
 ETEXI
+SQMP
+cpu
+---
+
+Set the default CPU.
+
+Arguments:
+
+- "index": the CPU's index (json-int)
+
+Example:
+
+-> { "execute": "cpu", "arguments": { "index": 0 } }
+<- { "return": {} }
+
+Note: CPUs' indexes are obtained with the 'query-cpus' command.
+
+EQMP
 
     {
         .name       = "mouse_move",
@@ -715,6 +868,29 @@
 @findex memsave
 save to disk virtual memory dump starting at @var{addr} of size @var{size}.
 ETEXI
+SQMP
+memsave
+-------
+
+Save to disk virtual memory dump starting at 'val' of size 'size'.
+
+Arguments:
+
+- "val": the starting address (json-int)
+- "size": the memory size, in bytes (json-int)
+- "filename": file path (json-string)
+
+Example:
+
+-> { "execute": "memsave",
+             "arguments": { "val": 10,
+                            "size": 100,
+                            "filename": "/tmp/virtual-mem-dump" } }
+<- { "return": {} }
+
+Note: Depends on the current CPU.
+
+EQMP
 
     {
         .name       = "pmemsave",
@@ -730,6 +906,27 @@
 @findex pmemsave
 save to disk physical memory dump starting at @var{addr} of size @var{size}.
 ETEXI
+SQMP
+pmemsave
+--------
+
+Save to disk physical memory dump starting at 'val' of size 'size'.
+
+Arguments:
+
+- "val": the starting address (json-int)
+- "size": the memory size, in bytes (json-int)
+- "filename": file path (json-string)
+
+Example:
+
+-> { "execute": "pmemsave",
+             "arguments": { "val": 10,
+                            "size": 100,
+                            "filename": "/tmp/physical-mem-dump" } }
+<- { "return": {} }
+
+EQMP
 
     {
         .name       = "boot_set",
@@ -786,6 +983,32 @@
 	-b for migration with full copy of disk
 	-i for migration with incremental copy of disk (base image is shared)
 ETEXI
+SQMP
+migrate
+-------
+
+Migrate to URI.
+
+Arguments:
+
+- "blk": block migration, full disk copy (json-bool, optional)
+- "inc": incremental disk copy (json-bool, optional)
+- "uri": Destination URI (json-string)
+
+Example:
+
+-> { "execute": "migrate", "arguments": { "uri": "tcp:0:4446" } }
+<- { "return": {} }
+
+Notes:
+
+(1) The 'query-migrate' command should be used to check migration's progress
+    and final result (this information is provided by the 'status' member)
+(2) All boolean arguments default to false
+(3) The user Monitor's "detach" argument is invalid in QMP and should not
+    be used
+
+EQMP
 
     {
         .name       = "migrate_cancel",
@@ -801,6 +1024,20 @@
 @findex migrate_cancel
 Cancel the current VM migration.
 ETEXI
+SQMP
+migrate_cancel
+--------------
+
+Cancel the current migration.
+
+Arguments: None.
+
+Example:
+
+-> { "execute": "migrate_cancel" }
+<- { "return": {} }
+
+EQMP
 
     {
         .name       = "migrate_set_speed",
@@ -816,6 +1053,22 @@
 @findex migrate_set_speed
 Set maximum speed to @var{value} (in bytes) for migrations.
 ETEXI
+SQMP
+migrate_set_speed
+-----------------
+
+Set maximum speed for migrations.
+
+Arguments:
+
+- "value": maximum speed, in bytes per second (json-number)
+
+Example:
+
+-> { "execute": "migrate_set_speed", "arguments": { "value": 1024 } }
+<- { "return": {} }
+
+EQMP
 
     {
         .name       = "migrate_set_downtime",
@@ -831,6 +1084,22 @@
 @findex migrate_set_downtime
 Set maximum tolerated downtime (in seconds) for migration.
 ETEXI
+SQMP
+migrate_set_downtime
+--------------------
+
+Set maximum tolerated downtime (in seconds) for migrations.
+
+Arguments:
+
+- "value": maximum downtime (json-number)
+
+Example:
+
+-> { "execute": "migrate_set_downtime", "arguments": { "value": 0.1 } }
+<- { "return": {} }
+
+EQMP
 
 #if defined(TARGET_I386)
     {
@@ -926,6 +1195,28 @@
 @findex netdev_add
 Add host network device.
 ETEXI
+SQMP
+netdev_add
+----------
+
+Add host network device.
+
+Arguments:
+
+- "type": the device type, "tap", "user", ... (json-string)
+- "id": the device's ID, must be unique (json-string)
+- device options
+
+Example:
+
+-> { "execute": "netdev_add", "arguments": { "type": "user", "id": "netdev1" } }
+<- { "return": {} }
+
+Note: The supported device options are the same ones supported by the '-net'
+      command-line argument, which are listed in the '-help' output or QEMU's
+      manual
+
+EQMP
 
     {
         .name       = "netdev_del",
@@ -941,6 +1232,22 @@
 @findex netdev_del
 Remove host network device.
 ETEXI
+SQMP
+netdev_del
+----------
+
+Remove host network device.
+
+Arguments:
+
+- "id": the device's ID, must be unique (json-string)
+
+Example:
+
+-> { "execute": "netdev_del", "arguments": { "id": "netdev1" } }
+<- { "return": {} }
+
+EQMP
 
 #ifdef CONFIG_SLIRP
     {
@@ -977,7 +1284,7 @@
         .name       = "balloon",
         .args_type  = "value:M",
         .params     = "target",
-        .help       = "request VM to change it's memory allocation (in MB)",
+        .help       = "request VM to change its memory allocation (in MB)",
         .user_print = monitor_user_noop,
         .mhandler.cmd_async = do_balloon,
         .async      = 1,
@@ -988,6 +1295,22 @@
 @findex balloon
 Request VM to change its memory allocation to @var{value} (in MB).
 ETEXI
+SQMP
+balloon
+-------
+
+Request VM to change its memory allocation (in bytes).
+
+Arguments:
+
+- "value": New memory allocation (json-int)
+
+Example:
+
+-> { "execute": "balloon", "arguments": { "value": 536870912 } }
+<- { "return": {} }
+
+EQMP
 
     {
         .name       = "set_link",
@@ -1003,6 +1326,23 @@
 @findex set_link
 Switch link @var{name} on (i.e. up) or off (i.e. down).
 ETEXI
+SQMP
+set_link
+--------
+
+Change the link status of a network adapter.
+
+Arguments:
+
+- "name": network device name (json-string)
+- "up": status is up (json-bool)
+
+Example:
+
+-> { "execute": "set_link", "arguments": { "name": "e1000.0", "up": false } }
+<- { "return": {} }
+
+EQMP
 
     {
         .name       = "watchdog_action",
@@ -1132,6 +1472,22 @@
 mechanism on unix sockets, it is stored using the name @var{fdname} for
 later use by other monitor commands.
 ETEXI
+SQMP
+getfd
+-----
+
+Receive a file descriptor via SCM rights and assign it a name.
+
+Arguments:
+
+- "fdname": file descriptor name (json-string)
+
+Example:
+
+-> { "execute": "getfd", "arguments": { "fdname": "fd1" } }
+<- { "return": {} }
+
+EQMP
 
     {
         .name       = "closefd",
@@ -1149,6 +1505,22 @@
 @code{getfd} command. This is only needed if the file descriptor was never
 used by another monitor command.
 ETEXI
+SQMP
+closefd
+-------
+
+Close a file descriptor previously passed via SCM rights.
+
+Arguments:
+
+- "fdname": file descriptor name (json-string)
+
+Example:
+
+-> { "execute": "closefd", "arguments": { "fdname": "fd1" } }
+<- { "return": {} }
+
+EQMP
 
     {
         .name       = "block_passwd",
@@ -1164,6 +1536,24 @@
 @findex block_passwd
 Set the encrypted device @var{device} password to @var{password}
 ETEXI
+SQMP
+block_passwd
+------------
+
+Set the password of encrypted block devices.
+
+Arguments:
+
+- "device": device name (json-string)
+- "password": password (json-string)
+
+Example:
+
+-> { "execute": "block_passwd", "arguments": { "device": "ide0-hd0",
+                                               "password": "12345" } }
+<- { "return": {} }
+
+EQMP
 
     {
         .name       = "qmp_capabilities",
@@ -1179,6 +1569,954 @@
 @findex qmp_capabilities
 Enable the specified QMP capabilities
 ETEXI
+SQMP
+qmp_capabilities
+----------------
+
+Enable QMP capabilities.
+
+Arguments: None.
+
+Example:
+
+-> { "execute": "qmp_capabilities" }
+<- { "return": {} }
+
+Note: This command must be issued before issuing any other command.
+
+EQMP
+
+
+HXCOMM Keep the 'info' command at the end!
+HXCOMM This is required for the QMP documentation layout.
+
+SQMP
+
+2. Query Commands
+=================
+
+EQMP
+
+    {
+        .name       = "info",
+        .args_type  = "item:s?",
+        .params     = "[subcommand]",
+        .help       = "show various information about the system state",
+        .user_print = monitor_user_noop,
+        .mhandler.cmd_new = do_info,
+    },
+
+STEXI
+@item info @var{subcommand}
+@findex info
+Show various information about the system state.
+
+@table @option
+@item info version
+show the version of QEMU
+ETEXI
+SQMP
+query-version
+-------------
+
+Show QEMU version.
+
+Return a json-object with the following information:
+
+- "qemu": QEMU's version (json-string)
+- "package": package's version (json-string)
+
+Example:
+
+-> { "execute": "query-version" }
+<- { "return": { "qemu": "0.11.50", "package": "" } }
+
+EQMP
+
+STEXI
+@item info commands
+list QMP available commands
+ETEXI
+SQMP
+query-commands
+--------------
+
+List QMP available commands.
+
+Each command is represented by a json-object, the returned value is a json-array
+of all commands.
+
+Each json-object contain:
+
+- "name": command's name (json-string)
+
+Example:
+
+-> { "execute": "query-commands" }
+<- {
+      "return":[
+         {
+            "name":"query-balloon"
+         },
+         {
+            "name":"system_powerdown"
+         }
+      ]
+   }
+
+Note: This example has been shortened as the real response is too long.
+
+EQMP
+
+STEXI
+@item info network
+show the various VLANs and the associated devices
+ETEXI
+
+STEXI
+@item info chardev
+show the character devices
+ETEXI
+SQMP
+query-chardev
+-------------
+
+Each device is represented by a json-object. The returned value is a json-array
+of all devices.
+
+Each json-object contain the following:
+
+- "label": device's label (json-string)
+- "filename": device's file (json-string)
+
+Example:
+
+-> { "execute": "query-chardev" }
+<- {
+      "return":[
+         {
+            "label":"monitor",
+            "filename":"stdio"
+         },
+         {
+            "label":"serial0",
+            "filename":"vc"
+         }
+      ]
+   }
+
+EQMP
+
+STEXI
+@item info block
+show the block devices
+ETEXI
+SQMP
+query-block
+-----------
+
+Show the block devices.
+
+Each block device information is stored in a json-object and the returned value
+is a json-array of all devices.
+
+Each json-object contain the following:
+
+- "device": device name (json-string)
+- "type": device type (json-string)
+         - Possible values: "hd", "cdrom", "floppy", "unknown"
+- "removable": true if the device is removable, false otherwise (json-bool)
+- "locked": true if the device is locked, false otherwise (json-bool)
+- "inserted": only present if the device is inserted, it is a json-object
+   containing the following:
+         - "file": device file name (json-string)
+         - "ro": true if read-only, false otherwise (json-bool)
+         - "drv": driver format name (json-string)
+             - Possible values: "blkdebug", "bochs", "cloop", "cow", "dmg",
+                                "file", "file", "ftp", "ftps", "host_cdrom",
+                                "host_device", "host_floppy", "http", "https",
+                                "nbd", "parallels", "qcow", "qcow2", "raw",
+                                "tftp", "vdi", "vmdk", "vpc", "vvfat"
+         - "backing_file": backing file name (json-string, optional)
+         - "encrypted": true if encrypted, false otherwise (json-bool)
+
+Example:
+
+-> { "execute": "query-block" }
+<- {
+      "return":[
+         {
+            "device":"ide0-hd0",
+            "locked":false,
+            "removable":false,
+            "inserted":{
+               "ro":false,
+               "drv":"qcow2",
+               "encrypted":false,
+               "file":"disks/test.img"
+            },
+            "type":"hd"
+         },
+         {
+            "device":"ide1-cd0",
+            "locked":false,
+            "removable":true,
+            "type":"cdrom"
+         },
+         {
+            "device":"floppy0",
+            "locked":false,
+            "removable":true,
+            "type": "floppy"
+         },
+         {
+            "device":"sd0",
+            "locked":false,
+            "removable":true,
+            "type":"floppy"
+         }
+      ]
+   }
+
+EQMP
+
+STEXI
+@item info blockstats
+show block device statistics
+ETEXI
+SQMP
+query-blockstats
+----------------
+
+Show block device statistics.
+
+Each device statistic information is stored in a json-object and the returned
+value is a json-array of all devices.
+
+Each json-object contain the following:
+
+- "device": device name (json-string)
+- "stats": A json-object with the statistics information, it contains:
+    - "rd_bytes": bytes read (json-int)
+    - "wr_bytes": bytes written (json-int)
+    - "rd_operations": read operations (json-int)
+    - "wr_operations": write operations (json-int)
+    - "wr_highest_offset": Highest offset of a sector written since the
+                           BlockDriverState has been opened (json-int)
+- "parent": Contains recursively the statistics of the underlying
+            protocol (e.g. the host file for a qcow2 image). If there is
+            no underlying protocol, this field is omitted
+            (json-object, optional)
+
+Example:
+
+-> { "execute": "query-blockstats" }
+<- {
+      "return":[
+         {
+            "device":"ide0-hd0",
+            "parent":{
+               "stats":{
+                  "wr_highest_offset":3686448128,
+                  "wr_bytes":9786368,
+                  "wr_operations":751,
+                  "rd_bytes":122567168,
+                  "rd_operations":36772
+               }
+            },
+            "stats":{
+               "wr_highest_offset":2821110784,
+               "wr_bytes":9786368,
+               "wr_operations":692,
+               "rd_bytes":122739200,
+               "rd_operations":36604
+            }
+         },
+         {
+            "device":"ide1-cd0",
+            "stats":{
+               "wr_highest_offset":0,
+               "wr_bytes":0,
+               "wr_operations":0,
+               "rd_bytes":0,
+               "rd_operations":0
+            }
+         },
+         {
+            "device":"floppy0",
+            "stats":{
+               "wr_highest_offset":0,
+               "wr_bytes":0,
+               "wr_operations":0,
+               "rd_bytes":0,
+               "rd_operations":0
+            }
+         },
+         {
+            "device":"sd0",
+            "stats":{
+               "wr_highest_offset":0,
+               "wr_bytes":0,
+               "wr_operations":0,
+               "rd_bytes":0,
+               "rd_operations":0
+            }
+         }
+      ]
+   }
+
+EQMP
+
+STEXI
+@item info registers
+show the cpu registers
+@item info cpus
+show infos for each CPU
+ETEXI
+SQMP
+query-cpus
+----------
+
+Show CPU information.
+
+Return a json-array. Each CPU is represented by a json-object, which contains:
+
+- "CPU": CPU index (json-int)
+- "current": true if this is the current CPU, false otherwise (json-bool)
+- "halted": true if the cpu is halted, false otherwise (json-bool)
+- Current program counter. The key's name depends on the architecture:
+     "pc": i386/x86_64 (json-int)
+     "nip": PPC (json-int)
+     "pc" and "npc": sparc (json-int)
+     "PC": mips (json-int)
+
+Example:
+
+-> { "execute": "query-cpus" }
+<- {
+      "return":[
+         {
+            "CPU":0,
+            "current":true,
+            "halted":false,
+            "pc":3227107138
+         },
+         {
+            "CPU":1,
+            "current":false,
+            "halted":true,
+            "pc":7108165
+         }
+      ]
+   }
+
+EQMP
+
+STEXI
+@item info history
+show the command line history
+@item info irq
+show the interrupts statistics (if available)
+@item info pic
+show i8259 (PIC) state
+ETEXI
+
+STEXI
+@item info pci
+show emulated PCI device info
+ETEXI
+SQMP
+query-pci
+---------
+
+PCI buses and devices information.
+
+The returned value is a json-array of all buses. Each bus is represented by
+a json-object, which has a key with a json-array of all PCI devices attached
+to it. Each device is represented by a json-object.
+
+The bus json-object contains the following:
+
+- "bus": bus number (json-int)
+- "devices": a json-array of json-objects, each json-object represents a
+             PCI device
+
+The PCI device json-object contains the following:
+
+- "bus": identical to the parent's bus number (json-int)
+- "slot": slot number (json-int)
+- "function": function number (json-int)
+- "class_info": a json-object containing:
+     - "desc": device class description (json-string, optional)
+     - "class": device class number (json-int)
+- "id": a json-object containing:
+     - "device": device ID (json-int)
+     - "vendor": vendor ID (json-int)
+- "irq": device's IRQ if assigned (json-int, optional)
+- "qdev_id": qdev id string (json-string)
+- "pci_bridge": It's a json-object, only present if this device is a
+                PCI bridge, contains:
+     - "bus": bus number (json-int)
+     - "secondary": secondary bus number (json-int)
+     - "subordinate": subordinate bus number (json-int)
+     - "io_range": I/O memory range information, a json-object with the
+                   following members:
+                 - "base": base address, in bytes (json-int)
+                 - "limit": limit address, in bytes (json-int)
+     - "memory_range": memory range information, a json-object with the
+                       following members:
+                 - "base": base address, in bytes (json-int)
+                 - "limit": limit address, in bytes (json-int)
+     - "prefetchable_range": Prefetchable memory range information, a
+                             json-object with the following members:
+                 - "base": base address, in bytes (json-int)
+                 - "limit": limit address, in bytes (json-int)
+     - "devices": a json-array of PCI devices if there's any attached, each
+                  each element is represented by a json-object, which contains
+                  the same members of the 'PCI device json-object' described
+                  above (optional)
+- "regions": a json-array of json-objects, each json-object represents a
+             memory region of this device
+
+The memory range json-object contains the following:
+
+- "base": base memory address (json-int)
+- "limit": limit value (json-int)
+
+The region json-object can be an I/O region or a memory region, an I/O region
+json-object contains the following:
+
+- "type": "io" (json-string, fixed)
+- "bar": BAR number (json-int)
+- "address": memory address (json-int)
+- "size": memory size (json-int)
+
+A memory region json-object contains the following:
+
+- "type": "memory" (json-string, fixed)
+- "bar": BAR number (json-int)
+- "address": memory address (json-int)
+- "size": memory size (json-int)
+- "mem_type_64": true or false (json-bool)
+- "prefetch": true or false (json-bool)
+
+Example:
+
+-> { "execute": "query-pci" }
+<- {
+      "return":[
+         {
+            "bus":0,
+            "devices":[
+               {
+                  "bus":0,
+                  "qdev_id":"",
+                  "slot":0,
+                  "class_info":{
+                     "class":1536,
+                     "desc":"Host bridge"
+                  },
+                  "id":{
+                     "device":32902,
+                     "vendor":4663
+                  },
+                  "function":0,
+                  "regions":[
+   
+                  ]
+               },
+               {
+                  "bus":0,
+                  "qdev_id":"",
+                  "slot":1,
+                  "class_info":{
+                     "class":1537,
+                     "desc":"ISA bridge"
+                  },
+                  "id":{
+                     "device":32902,
+                     "vendor":28672
+                  },
+                  "function":0,
+                  "regions":[
+   
+                  ]
+               },
+               {
+                  "bus":0,
+                  "qdev_id":"",
+                  "slot":1,
+                  "class_info":{
+                     "class":257,
+                     "desc":"IDE controller"
+                  },
+                  "id":{
+                     "device":32902,
+                     "vendor":28688
+                  },
+                  "function":1,
+                  "regions":[
+                     {
+                        "bar":4,
+                        "size":16,
+                        "address":49152,
+                        "type":"io"
+                     }
+                  ]
+               },
+               {
+                  "bus":0,
+                  "qdev_id":"",
+                  "slot":2,
+                  "class_info":{
+                     "class":768,
+                     "desc":"VGA controller"
+                  },
+                  "id":{
+                     "device":4115,
+                     "vendor":184
+                  },
+                  "function":0,
+                  "regions":[
+                     {
+                        "prefetch":true,
+                        "mem_type_64":false,
+                        "bar":0,
+                        "size":33554432,
+                        "address":4026531840,
+                        "type":"memory"
+                     },
+                     {
+                        "prefetch":false,
+                        "mem_type_64":false,
+                        "bar":1,
+                        "size":4096,
+                        "address":4060086272,
+                        "type":"memory"
+                     },
+                     {
+                        "prefetch":false,
+                        "mem_type_64":false,
+                        "bar":6,
+                        "size":65536,
+                        "address":-1,
+                        "type":"memory"
+                     }
+                  ]
+               },
+               {
+                  "bus":0,
+                  "qdev_id":"",
+                  "irq":11,
+                  "slot":4,
+                  "class_info":{
+                     "class":1280,
+                     "desc":"RAM controller"
+                  },
+                  "id":{
+                     "device":6900,
+                     "vendor":4098
+                  },
+                  "function":0,
+                  "regions":[
+                     {
+                        "bar":0,
+                        "size":32,
+                        "address":49280,
+                        "type":"io"
+                     }
+                  ]
+               }
+            ]
+         }
+      ]
+   }
+
+Note: This example has been shortened as the real response is too long.
+
+EQMP
+
+STEXI
+@item info tlb
+show virtual to physical memory mappings (i386 only)
+@item info mem
+show the active virtual memory mappings (i386 only)
+ETEXI
+
+STEXI
+@item info hpet
+show state of HPET (i386 only)
+ETEXI
+SQMP
+query-hpet
+----------
+
+Show HPET state.
+
+Return a json-object with the following information:
+
+- "enabled": true if hpet if enabled, false otherwise (json-bool)
+
+Example:
+
+-> { "execute": "query-hpet" }
+<- { "return": { "enabled": true } }
+
+EQMP
+
+STEXI
+@item info jit
+show dynamic compiler info
+@item info kvm
+show KVM information
+@item info numa
+show NUMA information
+ETEXI
+
+STEXI
+@item info kvm
+show KVM information
+ETEXI
+SQMP
+query-kvm
+---------
+
+Show KVM information.
+
+Return a json-object with the following information:
+
+- "enabled": true if KVM support is enabled, false otherwise (json-bool)
+- "present": true if QEMU has KVM support, false otherwise (json-bool)
+
+Example:
+
+-> { "execute": "query-kvm" }
+<- { "return": { "enabled": true, "present": true } }
+
+EQMP
+
+STEXI
+@item info usb
+show USB devices plugged on the virtual USB hub
+@item info usbhost
+show all USB host devices
+@item info profile
+show profiling information
+@item info capture
+show information about active capturing
+@item info snapshots
+show list of VM snapshots
+ETEXI
+
+STEXI
+@item info status
+show the current VM status (running|paused)
+ETEXI
+SQMP
+query-status
+------------
+
+Return a json-object with the following information:
+
+- "running": true if the VM is running, or false if it is paused (json-bool)
+- "singlestep": true if the VM is in single step mode,
+                false otherwise (json-bool)
+
+Example:
+
+-> { "execute": "query-status" }
+<- { "return": { "running": true, "singlestep": false } }
+
+EQMP
+
+STEXI
+@item info pcmcia
+show guest PCMCIA status
+ETEXI
+
+STEXI
+@item info mice
+show which guest mouse is receiving events
+ETEXI
+SQMP
+query-mice
+----------
+
+Show VM mice information.
+
+Each mouse is represented by a json-object, the returned value is a json-array
+of all mice.
+
+The mouse json-object contains the following:
+
+- "name": mouse's name (json-string)
+- "index": mouse's index (json-int)
+- "current": true if this mouse is receiving events, false otherwise (json-bool)
+- "absolute": true if the mouse generates absolute input events (json-bool)
+
+Example:
+
+-> { "execute": "query-mice" }
+<- {
+      "return":[
+         {
+            "name":"QEMU Microsoft Mouse",
+            "index":0,
+            "current":false,
+            "absolute":false
+         },
+         {
+            "name":"QEMU PS/2 Mouse",
+            "index":1,
+            "current":true,
+            "absolute":true
+         }
+      ]
+   }
+
+EQMP
+
+STEXI
+@item info vnc
+show the vnc server status
+ETEXI
+SQMP
+query-vnc
+---------
+
+Show VNC server information.
+
+Return a json-object with server information. Connected clients are returned
+as a json-array of json-objects.
+
+The main json-object contains the following:
+
+- "enabled": true or false (json-bool)
+- "host": server's IP address (json-string)
+- "family": address family (json-string)
+         - Possible values: "ipv4", "ipv6", "unix", "unknown"
+- "service": server's port number (json-string)
+- "auth": authentication method (json-string)
+         - Possible values: "invalid", "none", "ra2", "ra2ne", "sasl", "tight",
+                            "tls", "ultra", "unknown", "vencrypt", "vencrypt",
+                            "vencrypt+plain", "vencrypt+tls+none",
+                            "vencrypt+tls+plain", "vencrypt+tls+sasl",
+                            "vencrypt+tls+vnc", "vencrypt+x509+none",
+                            "vencrypt+x509+plain", "vencrypt+x509+sasl",
+                            "vencrypt+x509+vnc", "vnc"
+- "clients": a json-array of all connected clients
+
+Clients are described by a json-object, each one contain the following:
+
+- "host": client's IP address (json-string)
+- "family": address family (json-string)
+         - Possible values: "ipv4", "ipv6", "unix", "unknown"
+- "service": client's port number (json-string)
+- "x509_dname": TLS dname (json-string, optional)
+- "sasl_username": SASL username (json-string, optional)
+
+Example:
+
+-> { "execute": "query-vnc" }
+<- {
+      "return":{
+         "enabled":true,
+         "host":"0.0.0.0",
+         "service":"50402",
+         "auth":"vnc",
+         "family":"ipv4",
+         "clients":[
+            {
+               "host":"127.0.0.1",
+               "service":"50401",
+               "family":"ipv4"
+            }
+         ]
+      }
+   }
+
+EQMP
+
+STEXI
+@item info name
+show the current VM name
+ETEXI
+SQMP
+query-name
+----------
+
+Show VM name.
+
+Return a json-object with the following information:
+
+- "name": VM's name (json-string, optional)
+
+Example:
+
+-> { "execute": "query-name" }
+<- { "return": { "name": "qemu-name" } }
+
+EQMP
+
+STEXI
+@item info uuid
+show the current VM UUID
+ETEXI
+SQMP
+query-uuid
+----------
+
+Show VM UUID.
+
+Return a json-object with the following information:
+
+- "UUID": Universally Unique Identifier (json-string)
+
+Example:
+
+-> { "execute": "query-uuid" }
+<- { "return": { "UUID": "550e8400-e29b-41d4-a716-446655440000" } }
+
+EQMP
+
+STEXI
+@item info cpustats
+show CPU statistics
+@item info usernet
+show user network stack connection states
+ETEXI
+
+STEXI
+@item info migrate
+show migration status
+ETEXI
+SQMP
+query-migrate
+-------------
+
+Migration status.
+
+Return a json-object. If migration is active there will be another json-object
+with RAM migration status and if block migration is active another one with
+block migration status.
+
+The main json-object contains the following:
+
+- "status": migration status (json-string)
+     - Possible values: "active", "completed", "failed", "cancelled"
+- "ram": only present if "status" is "active", it is a json-object with the
+  following RAM information (in bytes):
+         - "transferred": amount transferred (json-int)
+         - "remaining": amount remaining (json-int)
+         - "total": total (json-int)
+- "disk": only present if "status" is "active" and it is a block migration,
+  it is a json-object with the following disk information (in bytes):
+         - "transferred": amount transferred (json-int)
+         - "remaining": amount remaining (json-int)
+         - "total": total (json-int)
+
+Examples:
+
+1. Before the first migration
+
+-> { "execute": "query-migrate" }
+<- { "return": {} }
+
+2. Migration is done and has succeeded
+
+-> { "execute": "query-migrate" }
+<- { "return": { "status": "completed" } }
+
+3. Migration is done and has failed
+
+-> { "execute": "query-migrate" }
+<- { "return": { "status": "failed" } }
+
+4. Migration is being performed and is not a block migration:
+
+-> { "execute": "query-migrate" }
+<- {
+      "return":{
+         "status":"active",
+         "ram":{
+            "transferred":123,
+            "remaining":123,
+            "total":246
+         }
+      }
+   }
+
+5. Migration is being performed and is a block migration:
+
+-> { "execute": "query-migrate" }
+<- {
+      "return":{
+         "status":"active",
+         "ram":{
+            "total":1057024,
+            "remaining":1053304,
+            "transferred":3720
+         },
+         "disk":{
+            "total":20971520,
+            "remaining":20880384,
+            "transferred":91136
+         }
+      }
+   }
+
+EQMP
+
+STEXI
+@item info balloon
+show balloon information
+ETEXI
+SQMP
+query-balloon
+-------------
+
+Show balloon information.
+
+Make an asynchronous request for balloon info. When the request completes a
+json-object will be returned containing the following data:
+
+- "actual": current balloon value in bytes (json-int)
+- "mem_swapped_in": Amount of memory swapped in bytes (json-int, optional)
+- "mem_swapped_out": Amount of memory swapped out in bytes (json-int, optional)
+- "major_page_faults": Number of major faults (json-int, optional)
+- "minor_page_faults": Number of minor faults (json-int, optional)
+- "free_mem": Total amount of free and unused memory in
+              bytes (json-int, optional)
+- "total_mem": Total amount of available memory in bytes (json-int, optional)
+
+Example:
+
+-> { "execute": "query-balloon" }
+<- {
+      "return":{
+         "actual":1073741824,
+         "mem_swapped_in":0,
+         "mem_swapped_out":0,
+         "major_page_faults":142,
+         "minor_page_faults":239245,
+         "free_mem":1014185984,
+         "total_mem":1044668416
+      }
+   }
+
+EQMP
+
+STEXI
+@item info qtree
+show device tree
+@item info qdm
+show qdev device model list
+@item info roms
+show roms
+@end table
+ETEXI
+
+HXCOMM DO NOT add new commands after 'info', move your addition before it!
 
 STEXI
 @end table
diff --git a/savevm.c b/savevm.c
index dc20390..af92ba2 100644
--- a/savevm.c
+++ b/savevm.c
@@ -235,9 +235,10 @@
 static int stdio_pclose(void *opaque)
 {
     QEMUFileStdio *s = opaque;
-    pclose(s->stdio_file);
+    int ret;
+    ret = pclose(s->stdio_file);
     qemu_free(s);
-    return 0;
+    return ret;
 }
 
 static int stdio_fclose(void *opaque)
diff --git a/softmmu_header.h b/softmmu_header.h
index 6a36e01..2f95c33 100644
--- a/softmmu_header.h
+++ b/softmmu_header.h
@@ -60,7 +60,7 @@
 #if DATA_SIZE == 8
 #define RES_TYPE uint64_t
 #else
-#define RES_TYPE int
+#define RES_TYPE uint32_t
 #endif
 
 #if ACCESS_TYPE == (NB_MMU_MODES + 1)
diff --git a/target-arm/cpu.h b/target-arm/cpu.h
index 1e34541..f3d138d 100644
--- a/target-arm/cpu.h
+++ b/target-arm/cpu.h
@@ -148,13 +148,6 @@
         int pending_exception;
     } v7m;
 
-    /* Coprocessor IO used by peripherals */
-    struct {
-        ARMReadCPFunc *cp_read;
-        ARMWriteCPFunc *cp_write;
-        void *opaque;
-    } cp[15];
-
     /* Thumb-2 EE state.  */
     uint32_t teecr;
     uint32_t teehbr;
@@ -204,6 +197,13 @@
     CPU_COMMON
 
     /* These fields after the common ones so they are preserved on reset.  */
+
+    /* Coprocessor IO used by peripherals */
+    struct {
+        ARMReadCPFunc *cp_read;
+        ARMWriteCPFunc *cp_write;
+        void *opaque;
+    } cp[15];
     void *nvic;
     struct arm_boot_info *boot_info;
 } CPUARMState;
diff --git a/target-arm/helper.c b/target-arm/helper.c
index 99e0394..63e5dc7 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -207,7 +207,6 @@
 #else
     /* SVC mode with interrupts disabled.  */
     env->uncached_cpsr = ARM_CPU_MODE_SVC | CPSR_A | CPSR_F | CPSR_I;
-    env->regs[15] = 0;
     /* On ARMv7-M the CPSR_I is the value of the PRIMASK register, and is
        clear at reset.  Initial SP and PC are loaded from ROM.  */
     if (IS_M(env)) {
diff --git a/target-i386/cpuid.c b/target-i386/cpuid.c
index 56938e2..7a11215 100644
--- a/target-i386/cpuid.c
+++ b/target-i386/cpuid.c
@@ -364,6 +364,20 @@
         .model_id = "QEMU Virtual CPU version " QEMU_VERSION,
     },
     {
+        .name = "kvm32",
+        .level = 5,
+        .family = 15,
+        .model = 6,
+        .stepping = 1,
+        .features = PPRO_FEATURES |
+            CPUID_MTRR | CPUID_CLFLUSH | CPUID_MCA | CPUID_PSE36,
+        .ext_features = CPUID_EXT_SSE3,
+        .ext2_features = PPRO_FEATURES & EXT2_FEATURE_MASK,
+        .ext3_features = 0,
+        .xlevel = 0x80000008,
+        .model_id = "Common 32-bit KVM processor"
+    },
+    {
         .name = "coreduo",
         .level = 10,
         .family = 6,
diff --git a/target-ppc/helper.c b/target-ppc/helper.c
index a5479c4..d342b09 100644
--- a/target-ppc/helper.c
+++ b/target-ppc/helper.c
@@ -2080,7 +2080,6 @@
     srr1 = SPR_SRR1;
     asrr0 = -1;
     asrr1 = -1;
-    msr &= ~((target_ulong)0x783F0000);
     switch (excp) {
     case POWERPC_EXCP_NONE:
         /* Should never happen */
@@ -2594,7 +2593,6 @@
 #if 0 /* Fix this: not on all targets */
     new_msr &= ~((target_ulong)1 << MSR_PMM);
 #endif
-    new_msr &= ~((target_ulong)1 << MSR_LE);
     if (msr_ile)
         new_msr |= (target_ulong)1 << MSR_LE;
     else
diff --git a/target-ppc/op_helper.c b/target-ppc/op_helper.c
index 8f2ee98..3c3aa60 100644
--- a/target-ppc/op_helper.c
+++ b/target-ppc/op_helper.c
@@ -1646,20 +1646,20 @@
 void helper_rfi (void)
 {
     do_rfi(env->spr[SPR_SRR0], env->spr[SPR_SRR1],
-           ~((target_ulong)0x0), 1);
+           ~((target_ulong)0x783F0000), 1);
 }
 
 #if defined(TARGET_PPC64)
 void helper_rfid (void)
 {
     do_rfi(env->spr[SPR_SRR0], env->spr[SPR_SRR1],
-           ~((target_ulong)0x0), 0);
+           ~((target_ulong)0x783F0000), 0);
 }
 
 void helper_hrfid (void)
 {
     do_rfi(env->spr[SPR_HSRR0], env->spr[SPR_HSRR1],
-           ~((target_ulong)0x0), 0);
+           ~((target_ulong)0x783F0000), 0);
 }
 #endif
 #endif
diff --git a/target-sparc/helper.c b/target-sparc/helper.c
index 96a22f3..aa1fd63 100644
--- a/target-sparc/helper.c
+++ b/target-sparc/helper.c
@@ -495,6 +495,9 @@
             env->dmmu.sfsr |= (fault_type << 7);
 
             env->dmmu.sfar = address; /* Fault address register */
+
+            env->dmmu.tag_access = (address & ~0x1fffULL) | context;
+
             return 1;
         }
     }
@@ -544,6 +547,8 @@
                 env->immu.sfsr |= (is_user << 3) | 1;
                 env->exception_index = TT_TFAULT;
 
+                env->immu.tag_access = (address & ~0x1fffULL) | context;
+
                 DPRINTF_MMU("TFAULT at %" PRIx64 " context %" PRIx64 "\n",
                             address, context);
 
diff --git a/target-sparc/op_helper.c b/target-sparc/op_helper.c
index edeeb44..be3c1e0 100644
--- a/target-sparc/op_helper.c
+++ b/target-sparc/op_helper.c
@@ -247,6 +247,42 @@
     return addr;
 }
 
+/* returns true if access using this ASI is to have address translated by MMU
+   otherwise access is to raw physical address */
+static inline int is_translating_asi(int asi)
+{
+#ifdef TARGET_SPARC64
+    /* Ultrasparc IIi translating asi
+       - note this list is defined by cpu implementation
+     */
+    switch (asi) {
+    case 0x04 ... 0x11:
+    case 0x18 ... 0x19:
+    case 0x24 ... 0x2C:
+    case 0x70 ... 0x73:
+    case 0x78 ... 0x79:
+    case 0x80 ... 0xFF:
+        return 1;
+
+    default:
+        return 0;
+    }
+#else
+    /* TODO: check sparc32 bits */
+    return 0;
+#endif
+}
+
+static inline target_ulong asi_address_mask(CPUState *env1,
+                                            int asi, target_ulong addr)
+{
+    if (is_translating_asi(asi)) {
+        return address_mask(env, addr);
+    } else {
+        return addr;
+    }
+}
+
 static void raise_exception(int tt)
 {
     env->exception_index = tt;
@@ -1745,6 +1781,7 @@
     case 0x31: // Turbosparc RAM snoop
     case 0x32: // Turbosparc page table descriptor diagnostic
     case 0x39: /* data cache diagnostic register */
+    case 0x4c: /* SuperSPARC MMU Breakpoint Action register */
         ret = 0;
         break;
     case 0x38: /* SuperSPARC MMU Breakpoint Control Registers */
@@ -2150,7 +2187,7 @@
         raise_exception(TT_PRIV_ACT);
 
     helper_check_align(addr, size - 1);
-    addr = address_mask(env, addr);
+    addr = asi_address_mask(env, asi, addr);
 
     switch (asi) {
     case 0x82: // Primary no-fault
@@ -2253,7 +2290,7 @@
         raise_exception(TT_PRIV_ACT);
 
     helper_check_align(addr, size - 1);
-    addr = address_mask(env, addr);
+    addr = asi_address_mask(env, asi, addr);
 
     /* Convert to little endian */
     switch (asi) {
@@ -2330,6 +2367,8 @@
         raise_exception(TT_PRIV_ACT);
 
     helper_check_align(addr, size - 1);
+    addr = asi_address_mask(env, asi, addr);
+
     switch (asi) {
     case 0x82: // Primary no-fault
     case 0x8a: // Primary no-fault LE
@@ -2681,6 +2720,8 @@
         raise_exception(TT_PRIV_ACT);
 
     helper_check_align(addr, size - 1);
+    addr = asi_address_mask(env, asi, addr);
+
     /* Convert to little endian */
     switch (asi) {
     case 0x0c: // Nucleus Little Endian (LE)
@@ -3055,30 +3096,34 @@
             && !(env->hpstate & HS_PRIV)))
         raise_exception(TT_PRIV_ACT);
 
+    addr = asi_address_mask(env, asi, addr);
+
     switch (asi) {
+#if !defined(CONFIG_USER_ONLY)
     case 0x24: // Nucleus quad LDD 128 bit atomic
     case 0x2c: // Nucleus quad LDD 128 bit atomic LE
         helper_check_align(addr, 0xf);
         if (rd == 0) {
-            env->gregs[1] = ldq_kernel(addr + 8);
+            env->gregs[1] = ldq_nucleus(addr + 8);
             if (asi == 0x2c)
                 bswap64s(&env->gregs[1]);
         } else if (rd < 8) {
-            env->gregs[rd] = ldq_kernel(addr);
-            env->gregs[rd + 1] = ldq_kernel(addr + 8);
+            env->gregs[rd] = ldq_nucleus(addr);
+            env->gregs[rd + 1] = ldq_nucleus(addr + 8);
             if (asi == 0x2c) {
                 bswap64s(&env->gregs[rd]);
                 bswap64s(&env->gregs[rd + 1]);
             }
         } else {
-            env->regwptr[rd] = ldq_kernel(addr);
-            env->regwptr[rd + 1] = ldq_kernel(addr + 8);
+            env->regwptr[rd] = ldq_nucleus(addr);
+            env->regwptr[rd + 1] = ldq_nucleus(addr + 8);
             if (asi == 0x2c) {
                 bswap64s(&env->regwptr[rd]);
                 bswap64s(&env->regwptr[rd + 1]);
             }
         }
         break;
+#endif
     default:
         helper_check_align(addr, 0x3);
         if (rd == 0)
@@ -3100,6 +3145,8 @@
     target_ulong val;
 
     helper_check_align(addr, 3);
+    addr = asi_address_mask(env, asi, addr);
+
     switch (asi) {
     case 0xf0: // Block load primary
     case 0xf1: // Block load secondary
@@ -3117,6 +3164,20 @@
         }
 
         return;
+    case 0x70: // Block load primary, user privilege
+    case 0x71: // Block load secondary, user privilege
+        if (rd & 7) {
+            raise_exception(TT_ILL_INSN);
+            return;
+        }
+        helper_check_align(addr, 0x3f);
+        for (i = 0; i < 16; i++) {
+            *(uint32_t *)&env->fpr[rd++] = helper_ld_asi(addr, asi & 0x1f, 4,
+                                                         0);
+            addr += 4;
+        }
+
+        return;
     default:
         break;
     }
@@ -3142,6 +3203,8 @@
     target_ulong val = 0;
 
     helper_check_align(addr, 3);
+    addr = asi_address_mask(env, asi, addr);
+
     switch (asi) {
     case 0xe0: // UA2007 Block commit store primary (cache flush)
     case 0xe1: // UA2007 Block commit store secondary (cache flush)
@@ -3161,6 +3224,20 @@
         }
 
         return;
+    case 0x70: // Block store primary, user privilege
+    case 0x71: // Block store secondary, user privilege
+        if (rd & 7) {
+            raise_exception(TT_ILL_INSN);
+            return;
+        }
+        helper_check_align(addr, 0x3f);
+        for (i = 0; i < 16; i++) {
+            val = *(uint32_t *)&env->fpr[rd++];
+            helper_st_asi(addr, val, asi & 0x1f, 4);
+            addr += 4;
+        }
+
+        return;
     default:
         break;
     }
@@ -3229,7 +3306,7 @@
     uint32_t x1;
 
     x0 = (a & 0xffffffff) | ((int64_t) (env->y) << 32);
-    x1 = b;
+    x1 = (b & 0xffffffff);
 
     if (x1 == 0) {
         raise_exception(TT_DIV_ZERO);
@@ -3251,7 +3328,7 @@
     int32_t x1;
 
     x0 = (a & 0xffffffff) | ((int64_t) (env->y) << 32);
-    x1 = b;
+    x1 = (b & 0xffffffff);
 
     if (x1 == 0) {
         raise_exception(TT_DIV_ZERO);
@@ -3272,18 +3349,19 @@
     helper_check_align(addr, 7);
 #if !defined(CONFIG_USER_ONLY)
     switch (mem_idx) {
-    case 0:
+    case MMU_USER_IDX:
         stfq_user(addr, DT0);
         break;
-    case 1:
+    case MMU_KERNEL_IDX:
         stfq_kernel(addr, DT0);
         break;
 #ifdef TARGET_SPARC64
-    case 2:
+    case MMU_HYPV_IDX:
         stfq_hypv(addr, DT0);
         break;
 #endif
     default:
+        DPRINTF_MMU("helper_stdf: need to check MMU idx %d\n", mem_idx);
         break;
     }
 #else
@@ -3296,18 +3374,19 @@
     helper_check_align(addr, 7);
 #if !defined(CONFIG_USER_ONLY)
     switch (mem_idx) {
-    case 0:
+    case MMU_USER_IDX:
         DT0 = ldfq_user(addr);
         break;
-    case 1:
+    case MMU_KERNEL_IDX:
         DT0 = ldfq_kernel(addr);
         break;
 #ifdef TARGET_SPARC64
-    case 2:
+    case MMU_HYPV_IDX:
         DT0 = ldfq_hypv(addr);
         break;
 #endif
     default:
+        DPRINTF_MMU("helper_lddf: need to check MMU idx %d\n", mem_idx);
         break;
     }
 #else
@@ -3323,24 +3402,25 @@
     helper_check_align(addr, 7);
 #if !defined(CONFIG_USER_ONLY)
     switch (mem_idx) {
-    case 0:
+    case MMU_USER_IDX:
         u.ll.upper = ldq_user(addr);
         u.ll.lower = ldq_user(addr + 8);
         QT0 = u.q;
         break;
-    case 1:
+    case MMU_KERNEL_IDX:
         u.ll.upper = ldq_kernel(addr);
         u.ll.lower = ldq_kernel(addr + 8);
         QT0 = u.q;
         break;
 #ifdef TARGET_SPARC64
-    case 2:
+    case MMU_HYPV_IDX:
         u.ll.upper = ldq_hypv(addr);
         u.ll.lower = ldq_hypv(addr + 8);
         QT0 = u.q;
         break;
 #endif
     default:
+        DPRINTF_MMU("helper_ldqf: need to check MMU idx %d\n", mem_idx);
         break;
     }
 #else
@@ -3358,24 +3438,25 @@
     helper_check_align(addr, 7);
 #if !defined(CONFIG_USER_ONLY)
     switch (mem_idx) {
-    case 0:
+    case MMU_USER_IDX:
         u.q = QT0;
         stq_user(addr, u.ll.upper);
         stq_user(addr + 8, u.ll.lower);
         break;
-    case 1:
+    case MMU_KERNEL_IDX:
         u.q = QT0;
         stq_kernel(addr, u.ll.upper);
         stq_kernel(addr + 8, u.ll.lower);
         break;
 #ifdef TARGET_SPARC64
-    case 2:
+    case MMU_HYPV_IDX:
         u.q = QT0;
         stq_hypv(addr, u.ll.upper);
         stq_hypv(addr + 8, u.ll.lower);
         break;
 #endif
     default:
+        DPRINTF_MMU("helper_stqf: need to check MMU idx %d\n", mem_idx);
         break;
     }
 #else
diff --git a/target-sparc/translate.c b/target-sparc/translate.c
index 72ca0b4..23f9519 100644
--- a/target-sparc/translate.c
+++ b/target-sparc/translate.c
@@ -662,50 +662,53 @@
     tcg_gen_mov_tl(dst, cpu_cc_dst);
 }
 
-static inline void gen_op_umul(TCGv dst, TCGv src1, TCGv src2)
+static inline void gen_op_multiply(TCGv dst, TCGv src1, TCGv src2, int sign_ext)
 {
+    TCGv_i32 r_src1, r_src2;
     TCGv_i64 r_temp, r_temp2;
 
+    r_src1 = tcg_temp_new_i32();
+    r_src2 = tcg_temp_new_i32();
+
+    tcg_gen_trunc_tl_i32(r_src1, src1);
+    tcg_gen_trunc_tl_i32(r_src2, src2);
+
     r_temp = tcg_temp_new_i64();
     r_temp2 = tcg_temp_new_i64();
 
-    tcg_gen_extu_tl_i64(r_temp, src2);
-    tcg_gen_extu_tl_i64(r_temp2, src1);
+    if (sign_ext) {
+        tcg_gen_ext_i32_i64(r_temp, r_src2);
+        tcg_gen_ext_i32_i64(r_temp2, r_src1);
+    } else {
+        tcg_gen_extu_i32_i64(r_temp, r_src2);
+        tcg_gen_extu_i32_i64(r_temp2, r_src1);
+    }
+
     tcg_gen_mul_i64(r_temp2, r_temp, r_temp2);
 
     tcg_gen_shri_i64(r_temp, r_temp2, 32);
     tcg_gen_trunc_i64_tl(cpu_tmp0, r_temp);
     tcg_temp_free_i64(r_temp);
     tcg_gen_andi_tl(cpu_y, cpu_tmp0, 0xffffffff);
-#ifdef TARGET_SPARC64
-    tcg_gen_mov_i64(dst, r_temp2);
-#else
+
     tcg_gen_trunc_i64_tl(dst, r_temp2);
-#endif
+
     tcg_temp_free_i64(r_temp2);
+
+    tcg_temp_free_i32(r_src1);
+    tcg_temp_free_i32(r_src2);
+}
+
+static inline void gen_op_umul(TCGv dst, TCGv src1, TCGv src2)
+{
+    /* zero-extend truncated operands before multiplication */
+    gen_op_multiply(dst, src1, src2, 0);
 }
 
 static inline void gen_op_smul(TCGv dst, TCGv src1, TCGv src2)
 {
-    TCGv_i64 r_temp, r_temp2;
-
-    r_temp = tcg_temp_new_i64();
-    r_temp2 = tcg_temp_new_i64();
-
-    tcg_gen_ext_tl_i64(r_temp, src2);
-    tcg_gen_ext_tl_i64(r_temp2, src1);
-    tcg_gen_mul_i64(r_temp2, r_temp, r_temp2);
-
-    tcg_gen_shri_i64(r_temp, r_temp2, 32);
-    tcg_gen_trunc_i64_tl(cpu_tmp0, r_temp);
-    tcg_temp_free_i64(r_temp);
-    tcg_gen_andi_tl(cpu_y, cpu_tmp0, 0xffffffff);
-#ifdef TARGET_SPARC64
-    tcg_gen_mov_i64(dst, r_temp2);
-#else
-    tcg_gen_trunc_i64_tl(dst, r_temp2);
-#endif
-    tcg_temp_free_i64(r_temp2);
+    /* sign-extend truncated operands before multiplication */
+    gen_op_multiply(dst, src1, src2, 1);
 }
 
 #ifdef TARGET_SPARC64
@@ -4476,7 +4479,11 @@
                     if (rd == 1) {
                         tcg_gen_qemu_ld64(cpu_tmp64, cpu_addr, dc->mem_idx);
                         gen_helper_ldxfsr(cpu_tmp64);
-                    } else
+                    } else {
+                        tcg_gen_qemu_ld32u(cpu_tmp0, cpu_addr, dc->mem_idx);
+                        tcg_gen_trunc_tl_i32(cpu_tmp32, cpu_tmp0);
+                        gen_helper_ldfsr(cpu_tmp32);
+                    }
 #else
                     {
                         tcg_gen_qemu_ld32u(cpu_tmp32, cpu_addr, dc->mem_idx);
@@ -4490,6 +4497,7 @@
 
                         CHECK_FPU_FEATURE(dc, FLOAT128);
                         r_const = tcg_const_i32(dc->mem_idx);
+                        gen_address_mask(dc, cpu_addr);
                         gen_helper_ldqf(cpu_addr, r_const);
                         tcg_temp_free_i32(r_const);
                         gen_op_store_QT0_fpr(QFPREG(rd));
@@ -4500,6 +4508,7 @@
                         TCGv_i32 r_const;
 
                         r_const = tcg_const_i32(dc->mem_idx);
+                        gen_address_mask(dc, cpu_addr);
                         gen_helper_lddf(cpu_addr, r_const);
                         tcg_temp_free_i32(r_const);
                         gen_op_store_DT0_fpr(DFPREG(rd));
@@ -4635,6 +4644,7 @@
                         CHECK_FPU_FEATURE(dc, FLOAT128);
                         gen_op_load_fpr_QT0(QFPREG(rd));
                         r_const = tcg_const_i32(dc->mem_idx);
+                        gen_address_mask(dc, cpu_addr);
                         gen_helper_stqf(cpu_addr, r_const);
                         tcg_temp_free_i32(r_const);
                     }
@@ -4657,6 +4667,7 @@
 
                         gen_op_load_fpr_DT0(DFPREG(rd));
                         r_const = tcg_const_i32(dc->mem_idx);
+                        gen_address_mask(dc, cpu_addr);
                         gen_helper_stdf(cpu_addr, r_const);
                         tcg_temp_free_i32(r_const);
                     }
diff --git a/tcg/i386/tcg-target.c b/tcg/i386/tcg-target.c
index 396a2f1d..3600c35 100644
--- a/tcg/i386/tcg-target.c
+++ b/tcg/i386/tcg-target.c
@@ -156,7 +156,8 @@
         return 0;
 }
 
-#define P_EXT   0x100 /* 0x0f opcode prefix */
+#define P_EXT		0x100		/* 0x0f opcode prefix */
+#define P_DATA16	0x200		/* 0x66 opcode prefix */
 
 #define OPC_ARITH_EvIz	(0x81)
 #define OPC_ARITH_EvIb	(0x83)
@@ -262,8 +263,12 @@
 
 static inline void tcg_out_opc(TCGContext *s, int opc)
 {
-    if (opc & P_EXT)
+    if (opc & P_DATA16) {
+        tcg_out8(s, 0x66);
+    }
+    if (opc & P_EXT) {
         tcg_out8(s, 0x0f);
+    }
     tcg_out8(s, opc);
 }
 
@@ -396,10 +401,14 @@
 
 static void tcg_out_shifti(TCGContext *s, int subopc, int reg, int count)
 {
+    /* Propagate an opcode prefix, such as P_DATA16.  */
+    int ext = subopc & ~0x7;
+    subopc &= 0x7;
+
     if (count == 1) {
-        tcg_out_modrm(s, OPC_SHIFT_1, subopc, reg);
+        tcg_out_modrm(s, OPC_SHIFT_1 | ext, subopc, reg);
     } else {
-        tcg_out_modrm(s, OPC_SHIFT_Ib, subopc, reg);
+        tcg_out_modrm(s, OPC_SHIFT_Ib | ext, subopc, reg);
         tcg_out8(s, count);
     }
 }
@@ -411,8 +420,7 @@
 
 static inline void tcg_out_rolw_8(TCGContext *s, int reg)
 {
-    tcg_out8(s, 0x66);
-    tcg_out_shifti(s, SHIFT_ROL, reg, 8);
+    tcg_out_shifti(s, SHIFT_ROL | P_DATA16, reg, 8);
 }
 
 static inline void tcg_out_ext8u(TCGContext *s, int dest, int src)
@@ -694,47 +702,39 @@
     __stl_mmu,
     __stq_mmu,
 };
-#endif
 
-#ifndef CONFIG_USER_ONLY
-#define GUEST_BASE 0
-#endif
+/* Perform the TLB load and compare.
 
-/* XXX: qemu_ld and qemu_st could be modified to clobber only EDX and
-   EAX. It will be useful once fixed registers globals are less
-   common. */
-static void tcg_out_qemu_ld(TCGContext *s, const TCGArg *args,
-                            int opc)
+   Inputs:
+   ADDRLO_IDX contains the index into ARGS of the low part of the
+   address; the high part of the address is at ADDR_LOW_IDX+1.
+
+   MEM_INDEX and S_BITS are the memory context and log2 size of the load.
+
+   WHICH is the offset into the CPUTLBEntry structure of the slot to read.
+   This should be offsetof addr_read or addr_write.
+
+   Outputs:
+   LABEL_PTRS is filled with 1 (32-bit addresses) or 2 (64-bit addresses)
+   positions of the displacements of forward jumps to the TLB miss case.
+
+   EAX is loaded with the low part of the address.  In the TLB hit case,
+   it has been adjusted as indicated by the TLB and so is a host address.
+   In the TLB miss case, it continues to hold a guest address.
+
+   EDX is clobbered.  */
+
+static inline void tcg_out_tlb_load(TCGContext *s, int addrlo_idx,
+                                    int mem_index, int s_bits,
+                                    const TCGArg *args,
+                                    uint8_t **label_ptr, int which)
 {
-    int addr_reg, data_reg, data_reg2, r0, r1, mem_index, s_bits, bswap;
-#if defined(CONFIG_SOFTMMU)
-    uint8_t *label1_ptr, *label2_ptr;
-#endif
-#if TARGET_LONG_BITS == 64
-#if defined(CONFIG_SOFTMMU)
-    uint8_t *label3_ptr;
-#endif
-    int addr_reg2;
-#endif
+    const int addrlo = args[addrlo_idx];
+    const int r0 = TCG_REG_EAX;
+    const int r1 = TCG_REG_EDX;
 
-    data_reg = *args++;
-    if (opc == 3)
-        data_reg2 = *args++;
-    else
-        data_reg2 = 0;
-    addr_reg = *args++;
-#if TARGET_LONG_BITS == 64
-    addr_reg2 = *args++;
-#endif
-    mem_index = *args;
-    s_bits = opc & 3;
-
-    r0 = TCG_REG_EAX;
-    r1 = TCG_REG_EDX;
-
-#if defined(CONFIG_SOFTMMU)
-    tcg_out_mov(s, r1, addr_reg);
-    tcg_out_mov(s, r0, addr_reg);
+    tcg_out_mov(s, r1, addrlo);
+    tcg_out_mov(s, r0, addrlo);
 
     tcg_out_shifti(s, SHIFT_SHR, r1, TARGET_PAGE_BITS - CPU_TLB_ENTRY_BITS);
 
@@ -742,44 +742,150 @@
     tgen_arithi(s, ARITH_AND, r1, (CPU_TLB_SIZE - 1) << CPU_TLB_ENTRY_BITS, 0);
 
     tcg_out_modrm_sib_offset(s, OPC_LEA, r1, TCG_AREG0, r1, 0,
-                             offsetof(CPUState,
-                                      tlb_table[mem_index][0].addr_read));
+                             offsetof(CPUState, tlb_table[mem_index][0])
+                             + which);
 
     /* cmp 0(r1), r0 */
     tcg_out_modrm_offset(s, OPC_CMP_GvEv, r0, r1, 0);
 
-    tcg_out_mov(s, r0, addr_reg);
+    tcg_out_mov(s, r0, addrlo);
 
-#if TARGET_LONG_BITS == 32
-    /* je label1 */
-    tcg_out8(s, OPC_JCC_short + JCC_JE);
-    label1_ptr = s->code_ptr;
-    s->code_ptr++;
-#else
-    /* jne label3 */
+    /* jne label1 */
     tcg_out8(s, OPC_JCC_short + JCC_JNE);
-    label3_ptr = s->code_ptr;
+    label_ptr[0] = s->code_ptr;
     s->code_ptr++;
 
-    /* cmp 4(r1), addr_reg2 */
-    tcg_out_modrm_offset(s, OPC_CMP_GvEv, addr_reg2, r1, 4);
+    if (TARGET_LONG_BITS == 64) {
+        /* cmp 4(r1), addrhi */
+        tcg_out_modrm_offset(s, OPC_CMP_GvEv, args[addrlo_idx+1], r1, 4);
 
-    /* je label1 */
-    tcg_out8(s, OPC_JCC_short + JCC_JE);
-    label1_ptr = s->code_ptr;
-    s->code_ptr++;
+        /* jne label1 */
+        tcg_out8(s, OPC_JCC_short + JCC_JNE);
+        label_ptr[1] = s->code_ptr;
+        s->code_ptr++;
+    }
 
-    /* label3: */
-    *label3_ptr = s->code_ptr - label3_ptr - 1;
+    /* TLB Hit.  */
+
+    /* add addend(r1), r0 */
+    tcg_out_modrm_offset(s, OPC_ADD_GvEv, r0, r1,
+                         offsetof(CPUTLBEntry, addend) - which);
+}
 #endif
 
+static void tcg_out_qemu_ld_direct(TCGContext *s, int datalo, int datahi,
+                                   int base, tcg_target_long ofs, int sizeop)
+{
+#ifdef TARGET_WORDS_BIGENDIAN
+    const int bswap = 1;
+#else
+    const int bswap = 0;
+#endif
+    switch (sizeop) {
+    case 0:
+        /* movzbl */
+        tcg_out_modrm_offset(s, OPC_MOVZBL, datalo, base, ofs);
+        break;
+    case 0 | 4:
+        /* movsbl */
+        tcg_out_modrm_offset(s, OPC_MOVSBL, datalo, base, ofs);
+        break;
+    case 1:
+        /* movzwl */
+        tcg_out_modrm_offset(s, OPC_MOVZWL, datalo, base, ofs);
+        if (bswap) {
+            tcg_out_rolw_8(s, datalo);
+        }
+        break;
+    case 1 | 4:
+        /* movswl */
+        tcg_out_modrm_offset(s, OPC_MOVSWL, datalo, base, ofs);
+        if (bswap) {
+            tcg_out_rolw_8(s, datalo);
+            tcg_out_modrm(s, OPC_MOVSWL, datalo, datalo);
+        }
+        break;
+    case 2:
+        tcg_out_ld(s, TCG_TYPE_I32, datalo, base, ofs);
+        if (bswap) {
+            tcg_out_bswap32(s, datalo);
+        }
+        break;
+    case 3:
+        if (bswap) {
+            int t = datalo;
+            datalo = datahi;
+            datahi = t;
+        }
+        if (base != datalo) {
+            tcg_out_ld(s, TCG_TYPE_I32, datalo, base, ofs);
+            tcg_out_ld(s, TCG_TYPE_I32, datahi, base, ofs + 4);
+        } else {
+            tcg_out_ld(s, TCG_TYPE_I32, datahi, base, ofs + 4);
+            tcg_out_ld(s, TCG_TYPE_I32, datalo, base, ofs);
+        }
+        if (bswap) {
+            tcg_out_bswap32(s, datalo);
+            tcg_out_bswap32(s, datahi);
+        }
+        break;
+    default:
+        tcg_abort();
+    }
+}
+
+/* XXX: qemu_ld and qemu_st could be modified to clobber only EDX and
+   EAX. It will be useful once fixed registers globals are less
+   common. */
+static void tcg_out_qemu_ld(TCGContext *s, const TCGArg *args,
+                            int opc)
+{
+    int data_reg, data_reg2 = 0;
+    int addrlo_idx;
+#if defined(CONFIG_SOFTMMU)
+    int mem_index, s_bits, arg_idx;
+    uint8_t *label_ptr[3];
+#endif
+
+    data_reg = args[0];
+    addrlo_idx = 1;
+    if (opc == 3) {
+        data_reg2 = args[1];
+        addrlo_idx = 2;
+    }
+
+#if defined(CONFIG_SOFTMMU)
+    mem_index = args[addrlo_idx + (TARGET_LONG_BITS / 32)];
+    s_bits = opc & 3;
+
+    tcg_out_tlb_load(s, addrlo_idx, mem_index, s_bits, args,
+                     label_ptr, offsetof(CPUTLBEntry, addr_read));
+
+    /* TLB Hit.  */
+    tcg_out_qemu_ld_direct(s, data_reg, data_reg2, TCG_REG_EAX, 0, opc);
+
+    /* jmp label2 */
+    tcg_out8(s, OPC_JMP_short);
+    label_ptr[2] = s->code_ptr;
+    s->code_ptr++;
+
+    /* TLB Miss.  */
+
+    /* label1: */
+    *label_ptr[0] = s->code_ptr - label_ptr[0] - 1;
+    if (TARGET_LONG_BITS == 64) {
+        *label_ptr[1] = s->code_ptr - label_ptr[1] - 1;
+    }
+
     /* XXX: move that code at the end of the TB */
-#if TARGET_LONG_BITS == 32
-    tcg_out_movi(s, TCG_TYPE_I32, TCG_REG_EDX, mem_index);
-#else
-    tcg_out_mov(s, TCG_REG_EDX, addr_reg2);
-    tcg_out_movi(s, TCG_TYPE_I32, TCG_REG_ECX, mem_index);
-#endif
+    /* EAX is already loaded.  */
+    arg_idx = 1;
+    if (TARGET_LONG_BITS == 64) {
+        tcg_out_mov(s, tcg_target_call_iarg_regs[arg_idx++],
+                    args[addrlo_idx + 1]);
+    }
+    tcg_out_movi(s, TCG_TYPE_I32, tcg_target_call_iarg_regs[arg_idx],
+                 mem_index);
     tcg_out_calli(s, (tcg_target_long)qemu_ld_helpers[s_bits]);
 
     switch(opc) {
@@ -811,206 +917,144 @@
         break;
     }
 
-    /* jmp label2 */
-    tcg_out8(s, OPC_JMP_short);
-    label2_ptr = s->code_ptr;
-    s->code_ptr++;
-
-    /* label1: */
-    *label1_ptr = s->code_ptr - label1_ptr - 1;
-
-    /* add x(r1), r0 */
-    tcg_out_modrm_offset(s, OPC_ADD_GvEv, r0, r1,
-                         offsetof(CPUTLBEntry, addend) -
-                         offsetof(CPUTLBEntry, addr_read));
+    /* label2: */
+    *label_ptr[2] = s->code_ptr - label_ptr[2] - 1;
 #else
-    r0 = addr_reg;
+    tcg_out_qemu_ld_direct(s, data_reg, data_reg2,
+                           args[addrlo_idx], GUEST_BASE, opc);
 #endif
+}
 
+static void tcg_out_qemu_st_direct(TCGContext *s, int datalo, int datahi,
+                                   int base, tcg_target_long ofs, int sizeop)
+{
 #ifdef TARGET_WORDS_BIGENDIAN
-    bswap = 1;
+    const int bswap = 1;
 #else
-    bswap = 0;
+    const int bswap = 0;
 #endif
-    switch(opc) {
+    /* ??? Ideally we wouldn't need a scratch register.  For user-only,
+       we could perform the bswap twice to restore the original value
+       instead of moving to the scratch.  But as it is, the L constraint
+       means that EDX is definitely free here.  */
+    int scratch = TCG_REG_EDX;
+
+    switch (sizeop) {
     case 0:
-        /* movzbl */
-        tcg_out_modrm_offset(s, OPC_MOVZBL, data_reg, r0, GUEST_BASE);
-        break;
-    case 0 | 4:
-        /* movsbl */
-        tcg_out_modrm_offset(s, OPC_MOVSBL, data_reg, r0, GUEST_BASE);
+        tcg_out_modrm_offset(s, OPC_MOVB_EvGv, datalo, base, ofs);
         break;
     case 1:
-        /* movzwl */
-        tcg_out_modrm_offset(s, OPC_MOVZWL, data_reg, r0, GUEST_BASE);
         if (bswap) {
-            tcg_out_rolw_8(s, data_reg);
+            tcg_out_mov(s, scratch, datalo);
+            tcg_out_rolw_8(s, scratch);
+            datalo = scratch;
         }
-        break;
-    case 1 | 4:
-        /* movswl */
-        tcg_out_modrm_offset(s, OPC_MOVSWL, data_reg, r0, GUEST_BASE);
-        if (bswap) {
-            tcg_out_rolw_8(s, data_reg);
-
-            /* movswl data_reg, data_reg */
-            tcg_out_modrm(s, OPC_MOVSWL, data_reg, data_reg);
-        }
+        /* movw */
+        tcg_out_modrm_offset(s, OPC_MOVL_EvGv | P_DATA16,
+                             datalo, base, ofs);
         break;
     case 2:
-        tcg_out_ld(s, TCG_TYPE_I32, data_reg, r0, GUEST_BASE);
         if (bswap) {
-            tcg_out_bswap32(s, data_reg);
+            tcg_out_mov(s, scratch, datalo);
+            tcg_out_bswap32(s, scratch);
+            datalo = scratch;
         }
+        tcg_out_st(s, TCG_TYPE_I32, datalo, base, ofs);
         break;
     case 3:
         if (bswap) {
-            int t = data_reg;
-            data_reg = data_reg2;
-            data_reg2 = t;
-        }
-        if (r0 != data_reg) {
-            tcg_out_ld(s, TCG_TYPE_I32, data_reg, r0, GUEST_BASE);
-            tcg_out_ld(s, TCG_TYPE_I32, data_reg2, r0, GUEST_BASE + 4);
+            tcg_out_mov(s, scratch, datahi);
+            tcg_out_bswap32(s, scratch);
+            tcg_out_st(s, TCG_TYPE_I32, scratch, base, ofs);
+            tcg_out_mov(s, scratch, datalo);
+            tcg_out_bswap32(s, scratch);
+            tcg_out_st(s, TCG_TYPE_I32, scratch, base, ofs + 4);
         } else {
-            tcg_out_ld(s, TCG_TYPE_I32, data_reg2, r0, GUEST_BASE + 4);
-            tcg_out_ld(s, TCG_TYPE_I32, data_reg, r0, GUEST_BASE);
-        }
-        if (bswap) {
-            tcg_out_bswap32(s, data_reg);
-            tcg_out_bswap32(s, data_reg2);
+            tcg_out_st(s, TCG_TYPE_I32, datalo, base, ofs);
+            tcg_out_st(s, TCG_TYPE_I32, datahi, base, ofs + 4);
         }
         break;
     default:
         tcg_abort();
     }
-
-#if defined(CONFIG_SOFTMMU)
-    /* label2: */
-    *label2_ptr = s->code_ptr - label2_ptr - 1;
-#endif
 }
 
-
 static void tcg_out_qemu_st(TCGContext *s, const TCGArg *args,
                             int opc)
 {
-    int addr_reg, data_reg, data_reg2, r0, r1, mem_index, s_bits, bswap;
+    int data_reg, data_reg2 = 0;
+    int addrlo_idx;
 #if defined(CONFIG_SOFTMMU)
+    int mem_index, s_bits;
     int stack_adjust;
-    uint8_t *label1_ptr, *label2_ptr;
+    uint8_t *label_ptr[3];
 #endif
-#if TARGET_LONG_BITS == 64
+
+    data_reg = args[0];
+    addrlo_idx = 1;
+    if (opc == 3) {
+        data_reg2 = args[1];
+        addrlo_idx = 2;
+    }
+
 #if defined(CONFIG_SOFTMMU)
-    uint8_t *label3_ptr;
-#endif
-    int addr_reg2;
-#endif
-
-    data_reg = *args++;
-    if (opc == 3)
-        data_reg2 = *args++;
-    else
-        data_reg2 = 0;
-    addr_reg = *args++;
-#if TARGET_LONG_BITS == 64
-    addr_reg2 = *args++;
-#endif
-    mem_index = *args;
-
+    mem_index = args[addrlo_idx + (TARGET_LONG_BITS / 32)];
     s_bits = opc;
 
-    r0 = TCG_REG_EAX;
-    r1 = TCG_REG_EDX;
+    tcg_out_tlb_load(s, addrlo_idx, mem_index, s_bits, args,
+                     label_ptr, offsetof(CPUTLBEntry, addr_write));
 
-#if defined(CONFIG_SOFTMMU)
-    tcg_out_mov(s, r1, addr_reg);
-    tcg_out_mov(s, r0, addr_reg);
+    /* TLB Hit.  */
+    tcg_out_qemu_st_direct(s, data_reg, data_reg2, TCG_REG_EAX, 0, opc);
 
-    tcg_out_shifti(s, SHIFT_SHR, r1, TARGET_PAGE_BITS - CPU_TLB_ENTRY_BITS);
-
-    tgen_arithi(s, ARITH_AND, r0, TARGET_PAGE_MASK | ((1 << s_bits) - 1), 0);
-    tgen_arithi(s, ARITH_AND, r1, (CPU_TLB_SIZE - 1) << CPU_TLB_ENTRY_BITS, 0);
-
-    tcg_out_modrm_sib_offset(s, OPC_LEA, r1, TCG_AREG0, r1, 0,
-                             offsetof(CPUState,
-                                      tlb_table[mem_index][0].addr_write));
-
-    /* cmp 0(r1), r0 */
-    tcg_out_modrm_offset(s, OPC_CMP_GvEv, r0, r1, 0);
-
-    tcg_out_mov(s, r0, addr_reg);
-
-#if TARGET_LONG_BITS == 32
-    /* je label1 */
-    tcg_out8(s, OPC_JCC_short + JCC_JE);
-    label1_ptr = s->code_ptr;
-    s->code_ptr++;
-#else
-    /* jne label3 */
-    tcg_out8(s, OPC_JCC_short + JCC_JNE);
-    label3_ptr = s->code_ptr;
+    /* jmp label2 */
+    tcg_out8(s, OPC_JMP_short);
+    label_ptr[2] = s->code_ptr;
     s->code_ptr++;
 
-    /* cmp 4(r1), addr_reg2 */
-    tcg_out_modrm_offset(s, OPC_CMP_GvEv, addr_reg2, r1, 4);
+    /* TLB Miss.  */
 
-    /* je label1 */
-    tcg_out8(s, OPC_JCC_short + JCC_JE);
-    label1_ptr = s->code_ptr;
-    s->code_ptr++;
-
-    /* label3: */
-    *label3_ptr = s->code_ptr - label3_ptr - 1;
-#endif
+    /* label1: */
+    *label_ptr[0] = s->code_ptr - label_ptr[0] - 1;
+    if (TARGET_LONG_BITS == 64) {
+        *label_ptr[1] = s->code_ptr - label_ptr[1] - 1;
+    }
 
     /* XXX: move that code at the end of the TB */
-#if TARGET_LONG_BITS == 32
-    if (opc == 3) {
+    if (TARGET_LONG_BITS == 32) {
         tcg_out_mov(s, TCG_REG_EDX, data_reg);
-        tcg_out_mov(s, TCG_REG_ECX, data_reg2);
-        tcg_out_pushi(s, mem_index);
-        stack_adjust = 4;
-    } else {
-        switch(opc) {
-        case 0:
-            tcg_out_ext8u(s, TCG_REG_EDX, data_reg);
-            break;
-        case 1:
-            tcg_out_ext16u(s, TCG_REG_EDX, data_reg);
-            break;
-        case 2:
-            tcg_out_mov(s, TCG_REG_EDX, data_reg);
-            break;
+        if (opc == 3) {
+            tcg_out_mov(s, TCG_REG_ECX, data_reg2);
+            tcg_out_pushi(s, mem_index);
+            stack_adjust = 4;
+        } else {
+            tcg_out_movi(s, TCG_TYPE_I32, TCG_REG_ECX, mem_index);
+            stack_adjust = 0;
         }
-        tcg_out_movi(s, TCG_TYPE_I32, TCG_REG_ECX, mem_index);
-        stack_adjust = 0;
-    }
-#else
-    if (opc == 3) {
-        tcg_out_mov(s, TCG_REG_EDX, addr_reg2);
-        tcg_out_pushi(s, mem_index);
-        tcg_out_push(s, data_reg2);
-        tcg_out_push(s, data_reg);
-        stack_adjust = 12;
     } else {
-        tcg_out_mov(s, TCG_REG_EDX, addr_reg2);
-        switch(opc) {
-        case 0:
-            tcg_out_ext8u(s, TCG_REG_ECX, data_reg);
-            break;
-        case 1:
-            tcg_out_ext16u(s, TCG_REG_ECX, data_reg);
-            break;
-        case 2:
-            tcg_out_mov(s, TCG_REG_ECX, data_reg);
-            break;
+        if (opc == 3) {
+            tcg_out_mov(s, TCG_REG_EDX, args[addrlo_idx + 1]);
+            tcg_out_pushi(s, mem_index);
+            tcg_out_push(s, data_reg2);
+            tcg_out_push(s, data_reg);
+            stack_adjust = 12;
+        } else {
+            tcg_out_mov(s, TCG_REG_EDX, args[addrlo_idx + 1]);
+            switch(opc) {
+            case 0:
+                tcg_out_ext8u(s, TCG_REG_ECX, data_reg);
+                break;
+            case 1:
+                tcg_out_ext16u(s, TCG_REG_ECX, data_reg);
+                break;
+            case 2:
+                tcg_out_mov(s, TCG_REG_ECX, data_reg);
+                break;
+            }
+            tcg_out_pushi(s, mem_index);
+            stack_adjust = 4;
         }
-        tcg_out_pushi(s, mem_index);
-        stack_adjust = 4;
     }
-#endif
 
     tcg_out_calli(s, (tcg_target_long)qemu_st_helpers[s_bits]);
 
@@ -1021,69 +1065,11 @@
         tcg_out_addi(s, TCG_REG_ESP, stack_adjust);
     }
 
-    /* jmp label2 */
-    tcg_out8(s, OPC_JMP_short);
-    label2_ptr = s->code_ptr;
-    s->code_ptr++;
-
-    /* label1: */
-    *label1_ptr = s->code_ptr - label1_ptr - 1;
-
-    /* add x(r1), r0 */
-    tcg_out_modrm_offset(s, OPC_ADD_GvEv, r0, r1,
-                         offsetof(CPUTLBEntry, addend) -
-                         offsetof(CPUTLBEntry, addr_write));
-#else
-    r0 = addr_reg;
-#endif
-
-#ifdef TARGET_WORDS_BIGENDIAN
-    bswap = 1;
-#else
-    bswap = 0;
-#endif
-    switch(opc) {
-    case 0:
-        tcg_out_modrm_offset(s, OPC_MOVB_EvGv, data_reg, r0, GUEST_BASE);
-        break;
-    case 1:
-        if (bswap) {
-            tcg_out_mov(s, r1, data_reg);
-            tcg_out_rolw_8(s, r1);
-            data_reg = r1;
-        }
-        /* movw */
-        tcg_out8(s, 0x66);
-        tcg_out_modrm_offset(s, OPC_MOVL_EvGv, data_reg, r0, GUEST_BASE);
-        break;
-    case 2:
-        if (bswap) {
-            tcg_out_mov(s, r1, data_reg);
-            tcg_out_bswap32(s, r1);
-            data_reg = r1;
-        }
-        tcg_out_st(s, TCG_TYPE_I32, data_reg, r0, GUEST_BASE);
-        break;
-    case 3:
-        if (bswap) {
-            tcg_out_mov(s, r1, data_reg2);
-            tcg_out_bswap32(s, r1);
-            tcg_out_st(s, TCG_TYPE_I32, r1, r0, GUEST_BASE);
-            tcg_out_mov(s, r1, data_reg);
-            tcg_out_bswap32(s, r1);
-            tcg_out_st(s, TCG_TYPE_I32, r1, r0, GUEST_BASE + 4);
-        } else {
-            tcg_out_st(s, TCG_TYPE_I32, data_reg, r0, GUEST_BASE);
-            tcg_out_st(s, TCG_TYPE_I32, data_reg2, r0, GUEST_BASE + 4);
-        }
-        break;
-    default:
-        tcg_abort();
-    }
-
-#if defined(CONFIG_SOFTMMU)
     /* label2: */
-    *label2_ptr = s->code_ptr - label2_ptr - 1;
+    *label_ptr[2] = s->code_ptr - label_ptr[2] - 1;
+#else
+    tcg_out_qemu_st_direct(s, data_reg, data_reg2,
+                           args[addrlo_idx], GUEST_BASE, opc);
 #endif
 }
 
@@ -1159,8 +1145,8 @@
         break;
     case INDEX_op_st16_i32:
         /* movw */
-        tcg_out8(s, 0x66);
-        tcg_out_modrm_offset(s, OPC_MOVL_EvGv, args[0], args[1], args[2]);
+        tcg_out_modrm_offset(s, OPC_MOVL_EvGv | P_DATA16,
+                             args[0], args[1], args[2]);
         break;
     case INDEX_op_st_i32:
         tcg_out_st(s, TCG_TYPE_I32, args[0], args[1], args[2]);
diff --git a/tcg/tcg-op.h b/tcg/tcg-op.h
index bafac2b..aa436de 100644
--- a/tcg/tcg-op.h
+++ b/tcg/tcg-op.h
@@ -2172,12 +2172,20 @@
 
 static inline void tcg_gen_qemu_ld32u(TCGv ret, TCGv addr, int mem_index)
 {
+#if TARGET_LONG_BITS == 32
+    tcg_gen_qemu_ldst_op(INDEX_op_qemu_ld32, ret, addr, mem_index);
+#else
     tcg_gen_qemu_ldst_op(INDEX_op_qemu_ld32u, ret, addr, mem_index);
+#endif
 }
 
 static inline void tcg_gen_qemu_ld32s(TCGv ret, TCGv addr, int mem_index)
 {
+#if TARGET_LONG_BITS == 32
+    tcg_gen_qemu_ldst_op(INDEX_op_qemu_ld32, ret, addr, mem_index);
+#else
     tcg_gen_qemu_ldst_op(INDEX_op_qemu_ld32s, ret, addr, mem_index);
+#endif
 }
 
 static inline void tcg_gen_qemu_ld64(TCGv_i64 ret, TCGv addr, int mem_index)
diff --git a/vnc-encoding-hextile.c b/vnc-encoding-hextile.c
index a01c5e2..728f25e 100644
--- a/vnc-encoding-hextile.c
+++ b/vnc-encoding-hextile.c
@@ -62,8 +62,8 @@
 #undef BPP
 #undef GENERIC
 
-void vnc_hextile_send_framebuffer_update(VncState *vs, int x,
-                                         int y, int w, int h)
+int vnc_hextile_send_framebuffer_update(VncState *vs, int x,
+                                        int y, int w, int h)
 {
     int i, j;
     int has_fg, has_bg;
@@ -83,6 +83,7 @@
     free(last_fg);
     free(last_bg);
 
+    return 1;
 }
 
 void vnc_hextile_set_pixel_conversion(VncState *vs, int generic)
diff --git a/vnc-encoding-tight.c b/vnc-encoding-tight.c
new file mode 100644
index 0000000..e8604a8
--- /dev/null
+++ b/vnc-encoding-tight.c
@@ -0,0 +1,961 @@
+/*
+ * QEMU VNC display driver: tight encoding
+ *
+ * From libvncserver/libvncserver/tight.c
+ * Copyright (C) 2000, 2001 Const Kaplinsky.  All Rights Reserved.
+ * Copyright (C) 1999 AT&T Laboratories Cambridge.  All Rights Reserved.
+ *
+ * Copyright (C) 2010 Corentin Chary <corentin.chary@gmail.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include <stdbool.h>
+
+#include "qdict.h"
+#include "qint.h"
+#include "vnc.h"
+#include "vnc-encoding-tight.h"
+
+/* Compression level stuff. The following array contains various
+   encoder parameters for each of 10 compression levels (0..9).
+   Last three parameters correspond to JPEG quality levels (0..9). */
+
+static const struct {
+    int max_rect_size, max_rect_width;
+    int mono_min_rect_size, gradient_min_rect_size;
+    int idx_zlib_level, mono_zlib_level, raw_zlib_level, gradient_zlib_level;
+    int gradient_threshold, gradient_threshold24;
+    int idx_max_colors_divisor;
+    int jpeg_quality, jpeg_threshold, jpeg_threshold24;
+} tight_conf[] = {
+    {   512,   32,   6, 65536, 0, 0, 0, 0,   0,   0,   4,  5, 10000, 23000 },
+    {  2048,  128,   6, 65536, 1, 1, 1, 0,   0,   0,   8, 10,  8000, 18000 },
+    {  6144,  256,   8, 65536, 3, 3, 2, 0,   0,   0,  24, 15,  6500, 15000 },
+    { 10240, 1024,  12, 65536, 5, 5, 3, 0,   0,   0,  32, 25,  5000, 12000 },
+    { 16384, 2048,  12, 65536, 6, 6, 4, 0,   0,   0,  32, 37,  4000, 10000 },
+    { 32768, 2048,  12,  4096, 7, 7, 5, 4, 150, 380,  32, 50,  3000,  8000 },
+    { 65536, 2048,  16,  4096, 7, 7, 6, 4, 170, 420,  48, 60,  2000,  5000 },
+    { 65536, 2048,  16,  4096, 8, 8, 7, 5, 180, 450,  64, 70,  1000,  2500 },
+    { 65536, 2048,  32,  8192, 9, 9, 8, 6, 190, 475,  64, 75,   500,  1200 },
+    { 65536, 2048,  32,  8192, 9, 9, 9, 6, 200, 500,  96, 80,   200,   500 }
+};
+
+/*
+ * Code to determine how many different colors used in rectangle.
+ */
+
+static void tight_palette_rgb2buf(uint32_t rgb, int bpp, uint8_t buf[6])
+{
+    memset(buf, 0, 6);
+
+    if (bpp == 32) {
+        buf[0] = ((rgb >> 24) & 0xFF);
+        buf[1] = ((rgb >> 16) & 0xFF);
+        buf[2] = ((rgb >>  8) & 0xFF);
+        buf[3] = ((rgb >>  0) & 0xFF);
+        buf[4] = ((buf[0] & 1) == 0) << 3 | ((buf[1] & 1) == 0) << 2;
+        buf[4]|= ((buf[2] & 1) == 0) << 1 | ((buf[3] & 1) == 0) << 0;
+        buf[0] |= 1;
+        buf[1] |= 1;
+        buf[2] |= 1;
+        buf[3] |= 1;
+    }
+    if (bpp == 16) {
+        buf[0] = ((rgb >> 8) & 0xFF);
+        buf[1] = ((rgb >> 0) & 0xFF);
+        buf[2] = ((buf[0] & 1) == 0) << 1 | ((buf[1] & 1) == 0) << 0;
+        buf[0] |= 1;
+        buf[1] |= 1;
+    }
+}
+
+static uint32_t tight_palette_buf2rgb(int bpp, const uint8_t *buf)
+{
+    uint32_t rgb = 0;
+
+    if (bpp == 32) {
+        rgb |= ((buf[0] & ~1) | !((buf[4] >> 3) & 1)) << 24;
+        rgb |= ((buf[1] & ~1) | !((buf[4] >> 2) & 1)) << 16;
+        rgb |= ((buf[2] & ~1) | !((buf[4] >> 1) & 1)) <<  8;
+        rgb |= ((buf[3] & ~1) | !((buf[4] >> 0) & 1)) <<  0;
+    }
+    if (bpp == 16) {
+        rgb |= ((buf[0] & ~1) | !((buf[2] >> 1) & 1)) << 8;
+        rgb |= ((buf[1] & ~1) | !((buf[2] >> 0) & 1)) << 0;
+    }
+    return rgb;
+}
+
+
+static int tight_palette_insert(QDict *palette, uint32_t rgb, int bpp, int max)
+{
+    uint8_t key[6];
+    int idx = qdict_size(palette);
+    bool present;
+
+    tight_palette_rgb2buf(rgb, bpp, key);
+    present = qdict_haskey(palette, (char *)key);
+    if (idx >= max && !present) {
+        return 0;
+    }
+    if (!present) {
+        qdict_put(palette, (char *)key, qint_from_int(idx));
+    }
+    return qdict_size(palette);
+}
+
+#define DEFINE_FILL_PALETTE_FUNCTION(bpp)                               \
+                                                                        \
+    static int                                                          \
+    tight_fill_palette##bpp(VncState *vs, int x, int y,                 \
+                            int max, size_t count,                      \
+                            uint32_t *bg, uint32_t *fg,                 \
+                            struct QDict **palette) {                   \
+        uint##bpp##_t *data;                                            \
+        uint##bpp##_t c0, c1, ci;                                       \
+        int i, n0, n1;                                                  \
+                                                                        \
+        data = (uint##bpp##_t *)vs->tight.buffer;                       \
+                                                                        \
+        c0 = data[0];                                                   \
+        i = 1;                                                          \
+        while (i < count && data[i] == c0)                              \
+            i++;                                                        \
+        if (i >= count) {                                               \
+            *bg = *fg = c0;                                             \
+            return 1;                                                   \
+        }                                                               \
+                                                                        \
+        if (max < 2) {                                                  \
+            return 0;                                                   \
+        }                                                               \
+                                                                        \
+        n0 = i;                                                         \
+        c1 = data[i];                                                   \
+        n1 = 0;                                                         \
+        for (i++; i < count; i++) {                                     \
+            ci = data[i];                                               \
+            if (ci == c0) {                                             \
+                n0++;                                                   \
+            } else if (ci == c1) {                                      \
+                n1++;                                                   \
+            } else                                                      \
+                break;                                                  \
+        }                                                               \
+        if (i >= count) {                                               \
+            if (n0 > n1) {                                              \
+                *bg = (uint32_t)c0;                                     \
+                *fg = (uint32_t)c1;                                     \
+            } else {                                                    \
+                *bg = (uint32_t)c1;                                     \
+                *fg = (uint32_t)c0;                                     \
+            }                                                           \
+            return 2;                                                   \
+        }                                                               \
+                                                                        \
+        if (max == 2) {                                                 \
+            return 0;                                                   \
+        }                                                               \
+                                                                        \
+        *palette = qdict_new();                                         \
+        tight_palette_insert(*palette, c0, bpp, max);                   \
+        tight_palette_insert(*palette, c1, bpp, max);                   \
+        tight_palette_insert(*palette, ci, bpp, max);                   \
+                                                                        \
+        for (i++; i < count; i++) {                                     \
+            if (data[i] == ci) {                                        \
+                continue;                                               \
+            } else {                                                    \
+                if (!tight_palette_insert(*palette, (uint32_t)ci,       \
+                                          bpp, max)) {                  \
+                    return 0;                                           \
+                }                                                       \
+                ci = data[i];                                           \
+            }                                                           \
+        }                                                               \
+                                                                        \
+        return qdict_size(*palette);                                    \
+    }
+
+DEFINE_FILL_PALETTE_FUNCTION(8)
+DEFINE_FILL_PALETTE_FUNCTION(16)
+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,
+                              struct QDict **palette)
+{
+    int max;
+
+    max = count / tight_conf[vs->tight_compression].idx_max_colors_divisor;
+    if (max < 2 &&
+        count >= tight_conf[vs->tight_compression].mono_min_rect_size) {
+        max = 2;
+    }
+    if (max >= 256) {
+        max = 256;
+    }
+
+    switch(vs->clientds.pf.bytes_per_pixel) {
+    case 4:
+        return tight_fill_palette32(vs, x, y, max, count, bg, fg, palette);
+    case 2:
+        return tight_fill_palette16(vs, x, y, max, count, bg, fg, palette);
+    default:
+        max = 2;
+        return tight_fill_palette8(vs, x, y, max, count, bg, fg, palette);
+    }
+    return 0;
+}
+
+/* Callback to dump a palette with qdict_iter
+static void print_palette(const char *key, QObject *obj, void *opaque)
+{
+    uint8_t idx = qint_get_int(qobject_to_qint(obj));
+    uint32_t rgb = tight_palette_buf2rgb(32, (uint8_t *)key);
+
+    fprintf(stderr, "%.2x ", (unsigned char)*key);
+    while (*key++)
+        fprintf(stderr, "%.2x ", (unsigned char)*key);
+
+    fprintf(stderr, ": idx: %x rgb: %x\n", idx, rgb);
+}
+*/
+
+/*
+ * Converting truecolor samples into palette indices.
+ */
+#define DEFINE_IDX_ENCODE_FUNCTION(bpp)                                 \
+                                                                        \
+    static void                                                         \
+    tight_encode_indexed_rect##bpp(uint8_t *buf, int count,             \
+                                   struct QDict *palette) {             \
+        uint##bpp##_t *src;                                             \
+        uint##bpp##_t rgb;                                              \
+        uint8_t key[6];                                                 \
+        int i, rep;                                                     \
+        uint8_t idx;                                                    \
+                                                                        \
+        src = (uint##bpp##_t *) buf;                                    \
+                                                                        \
+        for (i = 0; i < count; i++) {                                   \
+            rgb = *src++;                                               \
+            rep = 0;                                                    \
+            while (i < count && *src == rgb) {                          \
+                rep++, src++, i++;                                      \
+            }                                                           \
+            tight_palette_rgb2buf(rgb, bpp, key);                       \
+            if (!qdict_haskey(palette, (char *)key)) {                  \
+                /*                                                      \
+                 * Should never happen, but don't break everything      \
+                 * if it does, use the first color instead              \
+                 */                                                     \
+                idx = 0;                                                \
+            } else {                                                    \
+                idx = qdict_get_int(palette, (char *)key);              \
+            }                                                           \
+            while (rep >= 0) {                                          \
+                *buf++ = idx;                                           \
+                rep--;                                                  \
+            }                                                           \
+        }                                                               \
+    }
+
+DEFINE_IDX_ENCODE_FUNCTION(16)
+DEFINE_IDX_ENCODE_FUNCTION(32)
+
+#define DEFINE_MONO_ENCODE_FUNCTION(bpp)                                \
+                                                                        \
+    static void                                                         \
+    tight_encode_mono_rect##bpp(uint8_t *buf, int w, int h,             \
+                                uint##bpp##_t bg, uint##bpp##_t fg) {   \
+        uint##bpp##_t *ptr;                                             \
+        unsigned int value, mask;                                       \
+        int aligned_width;                                              \
+        int x, y, bg_bits;                                              \
+                                                                        \
+        ptr = (uint##bpp##_t *) buf;                                    \
+        aligned_width = w - w % 8;                                      \
+                                                                        \
+        for (y = 0; y < h; y++) {                                       \
+            for (x = 0; x < aligned_width; x += 8) {                    \
+                for (bg_bits = 0; bg_bits < 8; bg_bits++) {             \
+                    if (*ptr++ != bg) {                                 \
+                        break;                                          \
+                    }                                                   \
+                }                                                       \
+                if (bg_bits == 8) {                                     \
+                    *buf++ = 0;                                         \
+                    continue;                                           \
+                }                                                       \
+                mask = 0x80 >> bg_bits;                                 \
+                value = mask;                                           \
+                for (bg_bits++; bg_bits < 8; bg_bits++) {               \
+                    mask >>= 1;                                         \
+                    if (*ptr++ != bg) {                                 \
+                        value |= mask;                                  \
+                    }                                                   \
+                }                                                       \
+                *buf++ = (uint8_t)value;                                \
+            }                                                           \
+                                                                        \
+            mask = 0x80;                                                \
+            value = 0;                                                  \
+            if (x >= w) {                                               \
+                continue;                                               \
+            }                                                           \
+                                                                        \
+            for (; x < w; x++) {                                        \
+                if (*ptr++ != bg) {                                     \
+                    value |= mask;                                      \
+                }                                                       \
+                mask >>= 1;                                             \
+            }                                                           \
+            *buf++ = (uint8_t)value;                                    \
+        }                                                               \
+    }
+
+DEFINE_MONO_ENCODE_FUNCTION(8)
+DEFINE_MONO_ENCODE_FUNCTION(16)
+DEFINE_MONO_ENCODE_FUNCTION(32)
+
+/*
+ * Check if a rectangle is all of the same color. If needSameColor is
+ * set to non-zero, then also check that its color equals to the
+ * *colorPtr value. The result is 1 if the test is successfull, and in
+ * that case new color will be stored in *colorPtr.
+ */
+
+#define DEFINE_CHECK_SOLID_FUNCTION(bpp)                                \
+                                                                        \
+    static bool                                                         \
+    check_solid_tile##bpp(VncState *vs, int x, int y, int w, int h,     \
+                          uint32_t* color, bool samecolor)              \
+    {                                                                   \
+        VncDisplay *vd = vs->vd;                                        \
+        uint##bpp##_t *fbptr;                                           \
+        uint##bpp##_t c;                                                \
+        int dx, dy;                                                     \
+                                                                        \
+        fbptr = (uint##bpp##_t *)                                       \
+            (vd->server->data + y * ds_get_linesize(vs->ds) +           \
+             x * ds_get_bytes_per_pixel(vs->ds));                       \
+                                                                        \
+        c = *fbptr;                                                     \
+        if (samecolor && (uint32_t)c != *color) {                       \
+            return false;                                               \
+        }                                                               \
+                                                                        \
+        for (dy = 0; dy < h; dy++) {                                    \
+            for (dx = 0; dx < w; dx++) {                                \
+                if (c != fbptr[dx]) {                                   \
+                    return false;                                       \
+                }                                                       \
+            }                                                           \
+            fbptr = (uint##bpp##_t *)                                   \
+                ((uint8_t *)fbptr + ds_get_linesize(vs->ds));           \
+        }                                                               \
+                                                                        \
+        *color = (uint32_t)c;                                           \
+        return true;                                                    \
+    }
+
+DEFINE_CHECK_SOLID_FUNCTION(32)
+DEFINE_CHECK_SOLID_FUNCTION(16)
+DEFINE_CHECK_SOLID_FUNCTION(8)
+
+static bool check_solid_tile(VncState *vs, int x, int y, int w, int h,
+                             uint32_t* color, bool samecolor)
+{
+    VncDisplay *vd = vs->vd;
+
+    switch(vd->server->pf.bytes_per_pixel) {
+    case 4:
+        return check_solid_tile32(vs, x, y, w, h, color, samecolor);
+    case 2:
+        return check_solid_tile16(vs, x, y, w, h, color, samecolor);
+    default:
+        return check_solid_tile8(vs, x, y, w, h, color, samecolor);
+    }
+}
+
+static void find_best_solid_area(VncState *vs, int x, int y, int w, int h,
+                                 uint32_t color, int *w_ptr, int *h_ptr)
+{
+    int dx, dy, dw, dh;
+    int w_prev;
+    int w_best = 0, h_best = 0;
+
+    w_prev = w;
+
+    for (dy = y; dy < y + h; dy += VNC_TIGHT_MAX_SPLIT_TILE_SIZE) {
+
+        dh = MIN(VNC_TIGHT_MAX_SPLIT_TILE_SIZE, y + h - dy);
+        dw = MIN(VNC_TIGHT_MAX_SPLIT_TILE_SIZE, w_prev);
+
+        if (!check_solid_tile(vs, x, dy, dw, dh, &color, true)) {
+            break;
+        }
+
+        for (dx = x + dw; dx < x + w_prev;) {
+            dw = MIN(VNC_TIGHT_MAX_SPLIT_TILE_SIZE, x + w_prev - dx);
+
+            if (!check_solid_tile(vs, dx, dy, dw, dh, &color, true)) {
+                break;
+            }
+            dx += dw;
+        }
+
+        w_prev = dx - x;
+        if (w_prev * (dy + dh - y) > w_best * h_best) {
+            w_best = w_prev;
+            h_best = dy + dh - y;
+        }
+    }
+
+    *w_ptr = w_best;
+    *h_ptr = h_best;
+}
+
+static void extend_solid_area(VncState *vs, int x, int y, int w, int h,
+                              uint32_t color, int *x_ptr, int *y_ptr,
+                              int *w_ptr, int *h_ptr)
+{
+    int cx, cy;
+
+    /* Try to extend the area upwards. */
+    for ( cy = *y_ptr - 1;
+          cy >= y && check_solid_tile(vs, *x_ptr, cy, *w_ptr, 1, &color, true);
+          cy-- );
+    *h_ptr += *y_ptr - (cy + 1);
+    *y_ptr = cy + 1;
+
+    /* ... downwards. */
+    for ( cy = *y_ptr + *h_ptr;
+          cy < y + h &&
+              check_solid_tile(vs, *x_ptr, cy, *w_ptr, 1, &color, true);
+          cy++ );
+    *h_ptr += cy - (*y_ptr + *h_ptr);
+
+    /* ... to the left. */
+    for ( cx = *x_ptr - 1;
+          cx >= x && check_solid_tile(vs, cx, *y_ptr, 1, *h_ptr, &color, true);
+          cx-- );
+    *w_ptr += *x_ptr - (cx + 1);
+    *x_ptr = cx + 1;
+
+    /* ... to the right. */
+    for ( cx = *x_ptr + *w_ptr;
+          cx < x + w &&
+              check_solid_tile(vs, cx, *y_ptr, 1, *h_ptr, &color, true);
+          cx++ );
+    *w_ptr += cx - (*x_ptr + *w_ptr);
+}
+
+static int tight_init_stream(VncState *vs, int stream_id,
+                             int level, int strategy)
+{
+    z_streamp zstream = &vs->tight_stream[stream_id];
+
+    if (zstream->opaque == NULL) {
+        int err;
+
+        VNC_DEBUG("VNC: TIGHT: initializing zlib stream %d\n", stream_id);
+        VNC_DEBUG("VNC: TIGHT: opaque = %p | vs = %p\n", zstream->opaque, vs);
+        zstream->zalloc = vnc_zlib_zalloc;
+        zstream->zfree = vnc_zlib_zfree;
+
+        err = deflateInit2(zstream, level, Z_DEFLATED, MAX_WBITS,
+                           MAX_MEM_LEVEL, strategy);
+
+        if (err != Z_OK) {
+            fprintf(stderr, "VNC: error initializing zlib\n");
+            return -1;
+        }
+
+        vs->tight_levels[stream_id] = level;
+        zstream->opaque = vs;
+    }
+
+    if (vs->tight_levels[stream_id] != level) {
+        if (deflateParams(zstream, level, strategy) != Z_OK) {
+            return -1;
+        }
+        vs->tight_levels[stream_id] = level;
+    }
+    return 0;
+}
+
+static void tight_send_compact_size(VncState *vs, size_t len)
+{
+    int lpc = 0;
+    int bytes = 0;
+    char buf[3] = {0, 0, 0};
+
+    buf[bytes++] = len & 0x7F;
+    if (len > 0x7F) {
+        buf[bytes-1] |= 0x80;
+        buf[bytes++] = (len >> 7) & 0x7F;
+        if (len > 0x3FFF) {
+            buf[bytes-1] |= 0x80;
+            buf[bytes++] = (len >> 14) & 0xFF;
+        }
+    }
+    for (lpc = 0; lpc < bytes; lpc++) {
+        vnc_write_u8(vs, buf[lpc]);
+    }
+}
+
+static int tight_compress_data(VncState *vs, int stream_id, size_t bytes,
+                               int level, int strategy)
+{
+    z_streamp zstream = &vs->tight_stream[stream_id];
+    int previous_out;
+
+    if (bytes < VNC_TIGHT_MIN_TO_COMPRESS) {
+        vnc_write(vs, vs->tight.buffer, vs->tight.offset);
+        return bytes;
+    }
+
+    if (tight_init_stream(vs, stream_id, level, strategy)) {
+        return -1;
+    }
+
+    /* reserve memory in output buffer */
+    buffer_reserve(&vs->tight_zlib, bytes + 64);
+
+    /* set pointers */
+    zstream->next_in = vs->tight.buffer;
+    zstream->avail_in = vs->tight.offset;
+    zstream->next_out = vs->tight_zlib.buffer + vs->tight_zlib.offset;
+    zstream->avail_out = vs->tight_zlib.capacity - vs->tight_zlib.offset;
+    zstream->data_type = Z_BINARY;
+    previous_out = zstream->total_out;
+
+    /* start encoding */
+    if (deflate(zstream, Z_SYNC_FLUSH) != Z_OK) {
+        fprintf(stderr, "VNC: error during tight compression\n");
+        return -1;
+    }
+
+    vs->tight_zlib.offset = vs->tight_zlib.capacity - zstream->avail_out;
+    bytes = zstream->total_out - previous_out;
+
+    tight_send_compact_size(vs, bytes);
+    vnc_write(vs, vs->tight_zlib.buffer, bytes);
+
+    buffer_reset(&vs->tight_zlib);
+
+    return bytes;
+}
+
+/*
+ * Subencoding implementations.
+ */
+static void tight_pack24(VncState *vs, uint8_t *buf, size_t count, size_t *ret)
+{
+    uint32_t *buf32;
+    uint32_t pix;
+    int rshift, gshift, bshift;
+
+    buf32 = (uint32_t *)buf;
+
+    if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==
+        (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG)) {
+        rshift = vs->clientds.pf.rshift;
+        gshift = vs->clientds.pf.gshift;
+        bshift = vs->clientds.pf.bshift;
+    } else {
+        rshift = 24 - vs->clientds.pf.rshift;
+        gshift = 24 - vs->clientds.pf.gshift;
+        bshift = 24 - vs->clientds.pf.bshift;
+    }
+
+    if (ret) {
+        *ret = count * 3;
+    }
+
+    while (count--) {
+        pix = *buf32++;
+        *buf++ = (char)(pix >> rshift);
+        *buf++ = (char)(pix >> gshift);
+        *buf++ = (char)(pix >> bshift);
+    }
+}
+
+static int send_full_color_rect(VncState *vs, int w, int h)
+{
+    int stream = 0;
+    size_t bytes;
+
+    vnc_write_u8(vs, stream << 4); /* no flushing, no filter */
+
+    if (vs->tight_pixel24) {
+        tight_pack24(vs, vs->tight.buffer, w * h, &vs->tight.offset);
+        bytes = 3;
+    } else {
+        bytes = vs->clientds.pf.bytes_per_pixel;
+    }
+
+    bytes = tight_compress_data(vs, stream, w * h * bytes,
+                                tight_conf[vs->tight_compression].raw_zlib_level,
+                                Z_DEFAULT_STRATEGY);
+
+    return (bytes >= 0);
+}
+
+static int send_solid_rect(VncState *vs)
+{
+    size_t bytes;
+
+    vnc_write_u8(vs, VNC_TIGHT_FILL << 4); /* no flushing, no filter */
+
+    if (vs->tight_pixel24) {
+        tight_pack24(vs, vs->tight.buffer, 1, &vs->tight.offset);
+        bytes = 3;
+    } else {
+        bytes = vs->clientds.pf.bytes_per_pixel;
+    }
+
+    vnc_write(vs, vs->tight.buffer, bytes);
+    return 1;
+}
+
+static int send_mono_rect(VncState *vs, int w, int h, uint32_t bg, uint32_t fg)
+{
+    size_t bytes;
+    int stream = 1;
+    int level = tight_conf[vs->tight_compression].mono_zlib_level;
+
+    bytes = ((w + 7) / 8) * h;
+
+    vnc_write_u8(vs, (stream | VNC_TIGHT_EXPLICIT_FILTER) << 4);
+    vnc_write_u8(vs, VNC_TIGHT_FILTER_PALETTE);
+    vnc_write_u8(vs, 1);
+
+    switch(vs->clientds.pf.bytes_per_pixel) {
+    case 4:
+    {
+        uint32_t buf[2] = {bg, fg};
+        size_t ret = sizeof (buf);
+
+        if (vs->tight_pixel24) {
+            tight_pack24(vs, (unsigned char*)buf, 2, &ret);
+        }
+        vnc_write(vs, buf, ret);
+
+        tight_encode_mono_rect32(vs->tight.buffer, w, h, bg, fg);
+        break;
+    }
+    case 2:
+        vnc_write(vs, &bg, 2);
+        vnc_write(vs, &fg, 2);
+        tight_encode_mono_rect16(vs->tight.buffer, w, h, bg, fg);
+        break;
+    default:
+        vnc_write_u8(vs, bg);
+        vnc_write_u8(vs, fg);
+        tight_encode_mono_rect8(vs->tight.buffer, w, h, bg, fg);
+        break;
+    }
+    vs->tight.offset = bytes;
+
+    bytes = tight_compress_data(vs, stream, bytes, level, Z_DEFAULT_STRATEGY);
+    return (bytes >= 0);
+}
+
+struct palette_cb_priv {
+    VncState *vs;
+    uint8_t *header;
+};
+
+static void write_palette(const char *key, QObject *obj, void *opaque)
+{
+    struct palette_cb_priv *priv = opaque;
+    VncState *vs = priv->vs;
+    uint32_t bytes = vs->clientds.pf.bytes_per_pixel;
+    uint8_t idx = qint_get_int(qobject_to_qint(obj));
+
+    if (bytes == 4) {
+        uint32_t color = tight_palette_buf2rgb(32, (uint8_t *)key);
+
+        ((uint32_t*)priv->header)[idx] = color;
+    } else {
+        uint16_t color = tight_palette_buf2rgb(16, (uint8_t *)key);
+
+        ((uint16_t*)priv->header)[idx] = color;
+    }
+}
+
+static int send_palette_rect(VncState *vs, int w, int h, struct QDict *palette)
+{
+    int stream = 2;
+    int level = tight_conf[vs->tight_compression].idx_zlib_level;
+    int colors;
+    size_t bytes;
+
+    colors = qdict_size(palette);
+
+    vnc_write_u8(vs, (stream | VNC_TIGHT_EXPLICIT_FILTER) << 4);
+    vnc_write_u8(vs, VNC_TIGHT_FILTER_PALETTE);
+    vnc_write_u8(vs, colors - 1);
+
+    switch(vs->clientds.pf.bytes_per_pixel) {
+    case 4:
+    {
+        size_t old_offset, offset;
+        uint32_t header[qdict_size(palette)];
+        struct palette_cb_priv priv = { vs, (uint8_t *)header };
+
+        old_offset = vs->output.offset;
+        qdict_iter(palette, write_palette, &priv);
+        vnc_write(vs, header, sizeof(header));
+
+        if (vs->tight_pixel24) {
+            tight_pack24(vs, vs->output.buffer + old_offset, colors, &offset);
+            vs->output.offset = old_offset + offset;
+        }
+
+        tight_encode_indexed_rect32(vs->tight.buffer, w * h, palette);
+        break;
+    }
+    case 2:
+    {
+        uint16_t header[qdict_size(palette)];
+        struct palette_cb_priv priv = { vs, (uint8_t *)header };
+
+        qdict_iter(palette, write_palette, &priv);
+        vnc_write(vs, header, sizeof(header));
+        tight_encode_indexed_rect16(vs->tight.buffer, w * h, palette);
+        break;
+    }
+    default:
+        return -1; /* No palette for 8bits colors */
+        break;
+    }
+    bytes = w * h;
+    vs->tight.offset = bytes;
+
+    bytes = tight_compress_data(vs, stream, bytes,
+                                level, Z_DEFAULT_STRATEGY);
+    return (bytes >= 0);
+}
+
+static void vnc_tight_start(VncState *vs)
+{
+    buffer_reset(&vs->tight);
+
+    // make the output buffer be the zlib buffer, so we can compress it later
+    vs->tight_tmp = vs->output;
+    vs->output = vs->tight;
+}
+
+static void vnc_tight_stop(VncState *vs)
+{
+    // switch back to normal output/zlib buffers
+    vs->tight = vs->output;
+    vs->output = vs->tight_tmp;
+}
+
+static int send_sub_rect(VncState *vs, int x, int y, int w, int h)
+{
+    struct QDict *palette = NULL;
+    uint32_t bg = 0, fg = 0;
+    int colors;
+    int ret = 0;
+
+    vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_TIGHT);
+
+    vnc_tight_start(vs);
+    vnc_raw_send_framebuffer_update(vs, x, y, w, h);
+    vnc_tight_stop(vs);
+
+    colors = tight_fill_palette(vs, x, y, w * h, &fg, &bg, &palette);
+
+    if (colors == 0) {
+        ret = send_full_color_rect(vs, w, h);
+    } else if (colors == 1) {
+        ret = send_solid_rect(vs);
+    } else if (colors == 2) {
+        ret = send_mono_rect(vs, w, h, bg, fg);
+    } else if (colors <= 256) {
+        ret = send_palette_rect(vs, w, h, palette);
+    }
+    QDECREF(palette);
+    return ret;
+}
+
+static int send_sub_rect_solid(VncState *vs, int x, int y, int w, int h)
+{
+    vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_TIGHT);
+
+    vnc_tight_start(vs);
+    vnc_raw_send_framebuffer_update(vs, x, y, w, h);
+    vnc_tight_stop(vs);
+
+    return send_solid_rect(vs);
+}
+
+static int send_rect_simple(VncState *vs, int x, int y, int w, int h)
+{
+    int max_size, max_width;
+    int max_sub_width, max_sub_height;
+    int dx, dy;
+    int rw, rh;
+    int n = 0;
+
+    max_size = tight_conf[vs->tight_compression].max_rect_size;
+    max_width = tight_conf[vs->tight_compression].max_rect_width;
+
+    if (w > max_width || w * h > max_size) {
+        max_sub_width = (w > max_width) ? max_width : w;
+        max_sub_height = max_size / max_sub_width;
+
+        for (dy = 0; dy < h; dy += max_sub_height) {
+            for (dx = 0; dx < w; dx += max_width) {
+                rw = MIN(max_sub_width, w - dx);
+                rh = MIN(max_sub_height, h - dy);
+                n += send_sub_rect(vs, x+dx, y+dy, rw, rh);
+            }
+        }
+    } else {
+        n += send_sub_rect(vs, x, y, w, h);
+    }
+
+    return n;
+}
+
+static int find_large_solid_color_rect(VncState *vs, int x, int y,
+                                       int w, int h, int max_rows)
+{
+    int dx, dy, dw, dh;
+    int n = 0;
+
+    /* Try to find large solid-color areas and send them separately. */
+
+    for (dy = y; dy < y + h; dy += VNC_TIGHT_MAX_SPLIT_TILE_SIZE) {
+
+        /* If a rectangle becomes too large, send its upper part now. */
+
+        if (dy - y >= max_rows) {
+            n += send_rect_simple(vs, x, y, w, max_rows);
+            y += max_rows;
+            h -= max_rows;
+        }
+
+        dh = MIN(VNC_TIGHT_MAX_SPLIT_TILE_SIZE, (y + h - dy));
+
+        for (dx = x; dx < x + w; dx += VNC_TIGHT_MAX_SPLIT_TILE_SIZE) {
+            uint32_t color_value;
+            int x_best, y_best, w_best, h_best;
+
+            dw = MIN(VNC_TIGHT_MAX_SPLIT_TILE_SIZE, (x + w - dx));
+
+            if (!check_solid_tile(vs, dx, dy, dw, dh, &color_value, false)) {
+                continue ;
+            }
+
+            /* Get dimensions of solid-color area. */
+
+            find_best_solid_area(vs, dx, dy, w - (dx - x), h - (dy - y),
+                                 color_value, &w_best, &h_best);
+
+            /* Make sure a solid rectangle is large enough
+               (or the whole rectangle is of the same color). */
+
+            if (w_best * h_best != w * h &&
+                w_best * h_best < VNC_TIGHT_MIN_SOLID_SUBRECT_SIZE) {
+                continue;
+            }
+
+            /* Try to extend solid rectangle to maximum size. */
+
+            x_best = dx; y_best = dy;
+            extend_solid_area(vs, x, y, w, h, color_value,
+                              &x_best, &y_best, &w_best, &h_best);
+
+            /* Send rectangles at top and left to solid-color area. */
+
+            if (y_best != y) {
+                n += send_rect_simple(vs, x, y, w, y_best-y);
+            }
+            if (x_best != x) {
+                n += vnc_tight_send_framebuffer_update(vs, x, y_best,
+                                                       x_best-x, h_best);
+            }
+
+            /* Send solid-color rectangle. */
+            n += send_sub_rect_solid(vs, x_best, y_best, w_best, h_best);
+
+            /* Send remaining rectangles (at right and bottom). */
+
+            if (x_best + w_best != x + w) {
+                n += vnc_tight_send_framebuffer_update(vs, x_best+w_best,
+                                                       y_best,
+                                                       w-(x_best-x)-w_best,
+                                                       h_best);
+            }
+            if (y_best + h_best != y + h) {
+                n += vnc_tight_send_framebuffer_update(vs, x, y_best+h_best,
+                                                       w, h-(y_best-y)-h_best);
+            }
+
+            /* Return after all recursive calls are done. */
+            return n;
+        }
+    }
+    return n + send_rect_simple(vs, x, y, w, h);
+}
+
+int vnc_tight_send_framebuffer_update(VncState *vs, int x, int y,
+                                      int w, int h)
+{
+    int max_rows;
+
+    if (vs->clientds.pf.bytes_per_pixel == 4 && vs->clientds.pf.rmax == 0xFF &&
+        vs->clientds.pf.bmax == 0xFF && vs->clientds.pf.gmax == 0xFF) {
+        vs->tight_pixel24 = true;
+    } else {
+        vs->tight_pixel24 = false;
+    }
+
+    if (w * h < VNC_TIGHT_MIN_SPLIT_RECT_SIZE)
+        return send_rect_simple(vs, x, y, w, h);
+
+    /* Calculate maximum number of rows in one non-solid rectangle. */
+
+    max_rows = tight_conf[vs->tight_compression].max_rect_size;
+    max_rows /= MIN(tight_conf[vs->tight_compression].max_rect_width, w);
+
+    return find_large_solid_color_rect(vs, x, y, w, h, max_rows);
+}
+
+void vnc_tight_clear(VncState *vs)
+{
+    int i;
+    for (i=0; i<ARRAY_SIZE(vs->tight_stream); i++) {
+        if (vs->tight_stream[i].opaque) {
+            deflateEnd(&vs->tight_stream[i]);
+        }
+    }
+
+    buffer_free(&vs->tight);
+    buffer_free(&vs->tight_zlib);
+}
diff --git a/vnc-encoding-tight.h b/vnc-encoding-tight.h
new file mode 100644
index 0000000..64d1062
--- /dev/null
+++ b/vnc-encoding-tight.h
@@ -0,0 +1,176 @@
+/*
+ * QEMU VNC display driver: tight encoding
+ *
+ * From libvncserver/rfb/rfbproto.h
+ * Copyright (C) 2005 Rohit Kumar, Johannes E. Schindelin
+ * Copyright (C) 2000-2002 Constantin Kaplinsky.  All Rights Reserved.
+ * Copyright (C) 2000 Tridia Corporation.  All Rights Reserved.
+ * Copyright (C) 1999 AT&T Laboratories Cambridge.  All Rights Reserved.
+ *
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#ifndef VNC_ENCODING_TIGHT_H
+#define VNC_ENCODING_TIGHT_H
+
+/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+ * Tight Encoding.
+ *
+ *-- The first byte of each Tight-encoded rectangle is a "compression control
+ *   byte". Its format is as follows (bit 0 is the least significant one):
+ *
+ *   bit 0:    if 1, then compression stream 0 should be reset;
+ *   bit 1:    if 1, then compression stream 1 should be reset;
+ *   bit 2:    if 1, then compression stream 2 should be reset;
+ *   bit 3:    if 1, then compression stream 3 should be reset;
+ *   bits 7-4: if 1000 (0x08), then the compression type is "fill",
+ *             if 1001 (0x09), then the compression type is "jpeg",
+ *             if 0xxx, then the compression type is "basic",
+ *             values greater than 1001 are not valid.
+ *
+ * If the compression type is "basic", then bits 6..4 of the
+ * compression control byte (those xxx in 0xxx) specify the following:
+ *
+ *   bits 5-4:  decimal representation is the index of a particular zlib
+ *              stream which should be used for decompressing the data;
+ *   bit 6:     if 1, then a "filter id" byte is following this byte.
+ *
+ *-- The data that follows after the compression control byte described
+ * above depends on the compression type ("fill", "jpeg" or "basic").
+ *
+ *-- If the compression type is "fill", then the only pixel value follows, in
+ * client pixel format (see NOTE 1). This value applies to all pixels of the
+ * rectangle.
+ *
+ *-- If the compression type is "jpeg", the following data stream looks like
+ * this:
+ *
+ *   1..3 bytes:  data size (N) in compact representation;
+ *   N bytes:     JPEG image.
+ *
+ * Data size is compactly represented in one, two or three bytes, according
+ * to the following scheme:
+ *
+ *  0xxxxxxx                    (for values 0..127)
+ *  1xxxxxxx 0yyyyyyy           (for values 128..16383)
+ *  1xxxxxxx 1yyyyyyy zzzzzzzz  (for values 16384..4194303)
+ *
+ * Here each character denotes one bit, xxxxxxx are the least significant 7
+ * bits of the value (bits 0-6), yyyyyyy are bits 7-13, and zzzzzzzz are the
+ * most significant 8 bits (bits 14-21). For example, decimal value 10000
+ * should be represented as two bytes: binary 10010000 01001110, or
+ * hexadecimal 90 4E.
+ *
+ *-- If the compression type is "basic" and bit 6 of the compression control
+ * byte was set to 1, then the next (second) byte specifies "filter id" which
+ * tells the decoder what filter type was used by the encoder to pre-process
+ * pixel data before the compression. The "filter id" byte can be one of the
+ * following:
+ *
+ *   0:  no filter ("copy" filter);
+ *   1:  "palette" filter;
+ *   2:  "gradient" filter.
+ *
+ *-- If bit 6 of the compression control byte is set to 0 (no "filter id"
+ * byte), or if the filter id is 0, then raw pixel values in the client
+ * format (see NOTE 1) will be compressed. See below details on the
+ * compression.
+ *
+ *-- The "gradient" filter pre-processes pixel data with a simple algorithm
+ * which converts each color component to a difference between a "predicted"
+ * intensity and the actual intensity. Such a technique does not affect
+ * uncompressed data size, but helps to compress photo-like images better.
+ * Pseudo-code for converting intensities to differences is the following:
+ *
+ *   P[i,j] := V[i-1,j] + V[i,j-1] - V[i-1,j-1];
+ *   if (P[i,j] < 0) then P[i,j] := 0;
+ *   if (P[i,j] > MAX) then P[i,j] := MAX;
+ *   D[i,j] := V[i,j] - P[i,j];
+ *
+ * Here V[i,j] is the intensity of a color component for a pixel at
+ * coordinates (i,j). MAX is the maximum value of intensity for a color
+ * component.
+ *
+ *-- The "palette" filter converts true-color pixel data to indexed colors
+ * and a palette which can consist of 2..256 colors. If the number of colors
+ * is 2, then each pixel is encoded in 1 bit, otherwise 8 bits is used to
+ * encode one pixel. 1-bit encoding is performed such way that the most
+ * significant bits correspond to the leftmost pixels, and each raw of pixels
+ * is aligned to the byte boundary. When "palette" filter is used, the
+ * palette is sent before the pixel data. The palette begins with an unsigned
+ * byte which value is the number of colors in the palette minus 1 (i.e. 1
+ * means 2 colors, 255 means 256 colors in the palette). Then follows the
+ * palette itself which consist of pixel values in client pixel format (see
+ * NOTE 1).
+ *
+ *-- The pixel data is compressed using the zlib library. But if the data
+ * size after applying the filter but before the compression is less then 12,
+ * then the data is sent as is, uncompressed. Four separate zlib streams
+ * (0..3) can be used and the decoder should read the actual stream id from
+ * the compression control byte (see NOTE 2).
+ *
+ * If the compression is not used, then the pixel data is sent as is,
+ * otherwise the data stream looks like this:
+ *
+ *   1..3 bytes:  data size (N) in compact representation;
+ *   N bytes:     zlib-compressed data.
+ *
+ * Data size is compactly represented in one, two or three bytes, just like
+ * in the "jpeg" compression method (see above).
+ *
+ *-- NOTE 1. If the color depth is 24, and all three color components are
+ * 8-bit wide, then one pixel in Tight encoding is always represented by
+ * three bytes, where the first byte is red component, the second byte is
+ * green component, and the third byte is blue component of the pixel color
+ * value. This applies to colors in palettes as well.
+ *
+ *-- NOTE 2. The decoder must reset compression streams' states before
+ * decoding the rectangle, if some of bits 0,1,2,3 in the compression control
+ * byte are set to 1. Note that the decoder must reset zlib streams even if
+ * the compression type is "fill" or "jpeg".
+ *
+ *-- NOTE 3. The "gradient" filter and "jpeg" compression may be used only
+ * when bits-per-pixel value is either 16 or 32, not 8.
+ *
+ *-- NOTE 4. The width of any Tight-encoded rectangle cannot exceed 2048
+ * pixels. If a rectangle is wider, it must be split into several rectangles
+ * and each one should be encoded separately.
+ *
+ */
+
+#define VNC_TIGHT_EXPLICIT_FILTER       0x04
+#define VNC_TIGHT_FILL                  0x08
+#define VNC_TIGHT_JPEG                  0x09
+#define VNC_TIGHT_MAX_SUBENCODING       0x09
+
+/* Filters to improve compression efficiency */
+#define VNC_TIGHT_FILTER_COPY             0x00
+#define VNC_TIGHT_FILTER_PALETTE          0x01
+#define VNC_TIGHT_FILTER_GRADIENT         0x02
+
+/* Note: The following constant should not be changed. */
+#define VNC_TIGHT_MIN_TO_COMPRESS 12
+
+/* The parameters below may be adjusted. */
+#define VNC_TIGHT_MIN_SPLIT_RECT_SIZE     4096
+#define VNC_TIGHT_MIN_SOLID_SUBRECT_SIZE  2048
+#define VNC_TIGHT_MAX_SPLIT_TILE_SIZE       16
+
+#endif /* VNC_ENCODING_TIGHT_H */
diff --git a/vnc-encoding-zlib.c b/vnc-encoding-zlib.c
index 4a495ad..a99bc38 100644
--- a/vnc-encoding-zlib.c
+++ b/vnc-encoding-zlib.c
@@ -28,7 +28,7 @@
 
 #define ZALLOC_ALIGNMENT 16
 
-static void *zalloc(void *x, unsigned items, unsigned size)
+void *vnc_zlib_zalloc(void *x, unsigned items, unsigned size)
 {
     void *p;
 
@@ -40,7 +40,7 @@
     return (p);
 }
 
-static void zfree(void *x, void *addr)
+void vnc_zlib_zfree(void *x, void *addr)
 {
     qemu_free(addr);
 }
@@ -54,9 +54,9 @@
     vs->output = vs->zlib;
 }
 
-static int vnc_zlib_stop(VncState *vs, int stream_id)
+static int vnc_zlib_stop(VncState *vs)
 {
-    z_streamp zstream = &vs->zlib_stream[stream_id];
+    z_streamp zstream = &vs->zlib_stream;
     int previous_out;
 
     // switch back to normal output/zlib buffers
@@ -70,10 +70,10 @@
     if (zstream->opaque != vs) {
         int err;
 
-        VNC_DEBUG("VNC: initializing zlib stream %d\n", stream_id);
+        VNC_DEBUG("VNC: initializing zlib stream\n");
         VNC_DEBUG("VNC: opaque = %p | vs = %p\n", zstream->opaque, vs);
-        zstream->zalloc = zalloc;
-        zstream->zfree = zfree;
+        zstream->zalloc = vnc_zlib_zalloc;
+        zstream->zfree = vnc_zlib_zfree;
 
         err = deflateInit2(zstream, vs->tight_compression, Z_DEFLATED, MAX_WBITS,
                            MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY);
@@ -83,10 +83,17 @@
             return -1;
         }
 
+        vs->zlib_level = vs->tight_compression;
         zstream->opaque = vs;
     }
 
-    // XXX what to do if tight_compression changed in between?
+    if (vs->tight_compression != vs->zlib_level) {
+        if (deflateParams(zstream, vs->tight_compression,
+                          Z_DEFAULT_STRATEGY) != Z_OK) {
+            return -1;
+        }
+        vs->zlib_level = vs->tight_compression;
+    }
 
     // reserve memory in output buffer
     buffer_reserve(&vs->output, vs->zlib.offset + 64);
@@ -109,7 +116,7 @@
     return zstream->total_out - previous_out;
 }
 
-void vnc_zlib_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
+int vnc_zlib_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
 {
     int old_offset, new_offset, bytes_written;
 
@@ -122,21 +129,24 @@
     // compress the stream
     vnc_zlib_start(vs);
     vnc_raw_send_framebuffer_update(vs, x, y, w, h);
-    bytes_written = vnc_zlib_stop(vs, 0);
+    bytes_written = vnc_zlib_stop(vs);
 
     if (bytes_written == -1)
-        return;
+        return 0;
 
     // hack in the size
     new_offset = vs->output.offset;
     vs->output.offset = old_offset;
     vnc_write_u32(vs, bytes_written);
     vs->output.offset = new_offset;
+
+    return 1;
 }
 
-void vnc_zlib_init(VncState *vs)
+void vnc_zlib_clear(VncState *vs)
 {
-    int i;
-    for (i=0; i<(sizeof(vs->zlib_stream) / sizeof(z_stream)); i++)
-        vs->zlib_stream[i].opaque = NULL;
+    if (vs->zlib_stream.opaque) {
+        deflateEnd(&vs->zlib_stream);
+    }
+    buffer_free(&vs->zlib);
 }
diff --git a/vnc.c b/vnc.c
index 11ae3e5..ed0e096 100644
--- a/vnc.c
+++ b/vnc.c
@@ -323,35 +323,6 @@
     }
 }
 
-/**
- * do_info_vnc(): Show VNC server information
- *
- * Return a QDict with server information. Connected clients are returned
- * as a QList of QDicts.
- *
- * The main QDict contains the following:
- *
- * - "enabled": true or false
- * - "host": server's IP address
- * - "family": address family ("ipv4" or "ipv6")
- * - "service": server's port number
- * - "auth": authentication method
- * - "clients": a QList of all connected clients
- *
- * Clients are described by a QDict, with the following information:
- *
- * - "host": client's IP address
- * - "family": address family ("ipv4" or "ipv6")
- * - "service": client's port number
- * - "x509_dname": TLS dname (optional)
- * - "sasl_username": SASL username (optional)
- *
- * Example:
- *
- * { "enabled": true, "host": "0.0.0.0", "service": "50402", "auth": "vnc",
- *   "family": "ipv4",
- *   "clients": [{ "host": "127.0.0.1", "service": "50401", "family": "ipv4" }]}
- */
 void do_info_vnc(Monitor *mon, QObject **ret_data)
 {
     if (vnc_display == NULL || vnc_display->display == NULL) {
@@ -508,15 +479,43 @@
         buffer->offset = 0;
 }
 
+void buffer_free(Buffer *buffer)
+{
+    qemu_free(buffer->buffer);
+    buffer->offset = 0;
+    buffer->capacity = 0;
+    buffer->buffer = NULL;
+}
+
 void buffer_append(Buffer *buffer, const void *data, size_t len)
 {
     memcpy(buffer->buffer + buffer->offset, data, len);
     buffer->offset += len;
 }
 
+static void vnc_desktop_resize(VncState *vs)
+{
+    DisplayState *ds = vs->ds;
+
+    if (vs->csock == -1 || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
+        return;
+    }
+    if (vs->client_width == ds_get_width(ds) &&
+        vs->client_height == ds_get_height(ds)) {
+        return;
+    }
+    vs->client_width = ds_get_width(ds);
+    vs->client_height = ds_get_height(ds);
+    vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
+    vnc_write_u8(vs, 0);
+    vnc_write_u16(vs, 1); /* number of rects */
+    vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
+                           VNC_ENCODING_DESKTOPRESIZE);
+    vnc_flush(vs);
+}
+
 static void vnc_dpy_resize(DisplayState *ds)
 {
-    int size_changed;
     VncDisplay *vd = ds->opaque;
     VncState *vs;
 
@@ -534,23 +533,12 @@
         vd->guest.ds = qemu_mallocz(sizeof(*vd->guest.ds));
     if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel)
         console_color_init(ds);
-    size_changed = ds_get_width(ds) != vd->guest.ds->width ||
-                   ds_get_height(ds) != vd->guest.ds->height;
     *(vd->guest.ds) = *(ds->surface);
     memset(vd->guest.dirty, 0xFF, sizeof(vd->guest.dirty));
 
     QTAILQ_FOREACH(vs, &vd->clients, next) {
         vnc_colordepth(vs);
-        if (size_changed) {
-            if (vs->csock != -1 && vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
-                vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
-                vnc_write_u8(vs, 0);
-                vnc_write_u16(vs, 1); /* number of rects */
-                vnc_framebuffer_update(vs, 0, 0, ds_get_width(ds), ds_get_height(ds),
-                        VNC_ENCODING_DESKTOPRESIZE);
-                vnc_flush(vs);
-            }
-        }
+        vnc_desktop_resize(vs);
         if (vs->vd->cursor) {
             vnc_cursor_define(vs);
         }
@@ -644,7 +632,7 @@
     }
 }
 
-void vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
+int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
 {
     int i;
     uint8_t *row;
@@ -655,23 +643,30 @@
         vs->write_pixels(vs, &vd->server->pf, row, w * ds_get_bytes_per_pixel(vs->ds));
         row += ds_get_linesize(vs->ds);
     }
+    return 1;
 }
 
-static void send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
+static int send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
 {
+    int n = 0;
+
     switch(vs->vnc_encoding) {
         case VNC_ENCODING_ZLIB:
-            vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
+            n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
             break;
         case VNC_ENCODING_HEXTILE:
             vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
-            vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
+            n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
+            break;
+        case VNC_ENCODING_TIGHT:
+            n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
             break;
         default:
             vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
-            vnc_raw_send_framebuffer_update(vs, x, y, w, h);
+            n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
             break;
     }
+    return n;
 }
 
 static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
@@ -826,6 +821,8 @@
         int y;
         int n_rectangles;
         int saved_offset;
+        int width, height;
+        int n;
 
         if (vs->output.offset && !vs->audio_cap && !vs->force_update)
             /* kernel send buffers are full -> drop frames to throttle */
@@ -846,10 +843,13 @@
         saved_offset = vs->output.offset;
         vnc_write_u16(vs, 0);
 
-        for (y = 0; y < vd->server->height; y++) {
+        width = MIN(vd->server->width, vs->client_width);
+        height = MIN(vd->server->height, vs->client_height);
+
+        for (y = 0; y < height; y++) {
             int x;
             int last_x = -1;
-            for (x = 0; x < vd->server->width / 16; x++) {
+            for (x = 0; x < width / 16; x++) {
                 if (vnc_get_bit(vs->dirty[y], x)) {
                     if (last_x == -1) {
                         last_x = x;
@@ -858,16 +858,18 @@
                 } else {
                     if (last_x != -1) {
                         int h = find_and_clear_dirty_height(vs, y, last_x, x);
-                        send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
-                        n_rectangles++;
+                        n = send_framebuffer_update(vs, last_x * 16, y,
+                                                    (x - last_x) * 16, h);
+                        n_rectangles += n;
                     }
                     last_x = -1;
                 }
             }
             if (last_x != -1) {
                 int h = find_and_clear_dirty_height(vs, y, last_x, x);
-                send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
-                n_rectangles++;
+                n = send_framebuffer_update(vs, last_x * 16, y,
+                                            (x - last_x) * 16, h);
+                n_rectangles += n;
             }
         }
         vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
@@ -961,17 +963,14 @@
 {
     vnc_qmp_event(vs, QEVENT_VNC_DISCONNECTED);
 
-    if (vs->input.buffer) {
-        qemu_free(vs->input.buffer);
-        vs->input.buffer = NULL;
-    }
-    if (vs->output.buffer) {
-        qemu_free(vs->output.buffer);
-        vs->output.buffer = NULL;
-    }
+    buffer_free(&vs->input);
+    buffer_free(&vs->output);
 
     qobject_decref(vs->info);
 
+    vnc_zlib_clear(vs);
+    vnc_tight_clear(vs);
+
 #ifdef CONFIG_VNC_TLS
     vnc_tls_client_cleanup(vs);
 #endif /* CONFIG_VNC_TLS */
@@ -1642,35 +1641,37 @@
     int i;
     unsigned int enc = 0;
 
-    vnc_zlib_init(vs);
     vs->features = 0;
-    vs->vnc_encoding = -1;
+    vs->vnc_encoding = 0;
     vs->tight_compression = 9;
     vs->tight_quality = 9;
     vs->absolute = -1;
 
+    /*
+     * Start from the end because the encodings are sent in order of preference.
+     * This way the prefered encoding (first encoding defined in the array)
+     * will be set at the end of the loop.
+     */
     for (i = n_encodings - 1; i >= 0; i--) {
         enc = encodings[i];
         switch (enc) {
         case VNC_ENCODING_RAW:
-            if (vs->vnc_encoding != -1) {
-                vs->vnc_encoding = enc;
-            }
+            vs->vnc_encoding = enc;
             break;
         case VNC_ENCODING_COPYRECT:
             vs->features |= VNC_FEATURE_COPYRECT_MASK;
             break;
         case VNC_ENCODING_HEXTILE:
             vs->features |= VNC_FEATURE_HEXTILE_MASK;
-            if (vs->vnc_encoding != -1) {
-                vs->vnc_encoding = enc;
-            }
+            vs->vnc_encoding = enc;
+            break;
+        case VNC_ENCODING_TIGHT:
+            vs->features |= VNC_FEATURE_TIGHT_MASK;
+            vs->vnc_encoding = enc;
             break;
         case VNC_ENCODING_ZLIB:
             vs->features |= VNC_FEATURE_ZLIB_MASK;
-            if (vs->vnc_encoding != -1) {
-                vs->vnc_encoding = enc;
-            }
+            vs->vnc_encoding = enc;
             break;
         case VNC_ENCODING_DESKTOPRESIZE:
             vs->features |= VNC_FEATURE_RESIZE_MASK;
@@ -1701,6 +1702,7 @@
             break;
         }
     }
+    vnc_desktop_resize(vs);
     check_pointer_type_change(&vs->mouse_mode_notifier);
 }
 
@@ -1949,8 +1951,10 @@
     char buf[1024];
     int size;
 
-    vnc_write_u16(vs, ds_get_width(vs->ds));
-    vnc_write_u16(vs, ds_get_height(vs->ds));
+    vs->client_width = ds_get_width(vs->ds);
+    vs->client_height = ds_get_height(vs->ds);
+    vnc_write_u16(vs, vs->client_width);
+    vnc_write_u16(vs, vs->client_height);
 
     pixel_format_message(vs);
 
diff --git a/vnc.h b/vnc.h
index 0d39897..7b64cf7 100644
--- a/vnc.h
+++ b/vnc.h
@@ -134,6 +134,8 @@
     int absolute;
     int last_x;
     int last_y;
+    int client_width;
+    int client_height;
 
     uint32_t vnc_encoding;
 
@@ -170,6 +172,12 @@
     /* Tight */
     uint8_t tight_quality;
     uint8_t tight_compression;
+    uint8_t tight_pixel24;
+    Buffer tight;
+    Buffer tight_tmp;
+    Buffer tight_zlib;
+    int tight_levels[4];
+    z_stream tight_stream[4];
 
     /* Hextile */
     VncSendHextileTile *send_hextile_tile;
@@ -177,7 +185,8 @@
     /* Zlib */
     Buffer zlib;
     Buffer zlib_tmp;
-    z_stream zlib_stream[4];
+    z_stream zlib_stream;
+    int zlib_level;
 
     Notifier mouse_mode_notifier;
 
@@ -381,6 +390,7 @@
 int buffer_empty(Buffer *buffer);
 uint8_t *buffer_end(Buffer *buffer);
 void buffer_reset(Buffer *buffer);
+void buffer_free(Buffer *buffer);
 void buffer_append(Buffer *buffer, const void *data, size_t len);
 
 
@@ -396,13 +406,19 @@
 void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v);
 
 /* Encodings */
-void vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h);
+int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h);
 
-void vnc_hextile_send_framebuffer_update(VncState *vs, int x,
+int vnc_hextile_send_framebuffer_update(VncState *vs, int x,
                                          int y, int w, int h);
 void vnc_hextile_set_pixel_conversion(VncState *vs, int generic);
 
-void vnc_zlib_init(VncState *vs);
-void vnc_zlib_send_framebuffer_update(VncState *vs, int x, int y, int w, int h);
+void *vnc_zlib_zalloc(void *x, unsigned items, unsigned size);
+void vnc_zlib_zfree(void *x, void *addr);
+int vnc_zlib_send_framebuffer_update(VncState *vs, int x, int y, int w, int h);
+void vnc_zlib_clear(VncState *vs);
+
+
+int vnc_tight_send_framebuffer_update(VncState *vs, int x, int y, int w, int h);
+void vnc_tight_clear(VncState *vs);
 
 #endif /* __QEMU_VNC_H */