[Xquartz-changes] xserver: Branch 'master' - 278 commits

Jeremy Huddleston jeremyhu at freedesktop.org
Sun Sep 15 08:11:01 PDT 2013


 .dir-locals.el                             |    1 
 COPYING                                    |    1 
 Makefile.am                                |    2 
 Xext/panoramiX.c                           |   14 
 Xext/saver.c                               |    8 
 Xext/sync.c                                |   13 
 Xext/xvdisp.c                              |    8 
 Xext/xvmain.c                              |    4 
 Xi/chgdctl.c                               |    6 
 Xi/devbell.c                               |    3 
 Xi/exevents.c                              |  225 ++++++------
 Xi/extinit.c                               |   38 +-
 Xi/grabdev.c                               |    5 
 Xi/setdval.c                               |    3 
 Xi/setmode.c                               |    4 
 Xi/ungrdevb.c                              |    2 
 Xi/ungrdevk.c                              |    2 
 Xi/xiallowev.c                             |    2 
 Xi/xibarriers.c                            |   21 +
 Xi/xibarriers.h                            |    4 
 Xi/xigrabdev.c                             |   15 
 Xi/xipassivegrab.c                         |    2 
 Xi/xiqueryversion.c                        |   53 ++
 composite/compext.c                        |    7 
 config/10-quirks.conf                      |   54 +++
 config/Makefile.am                         |    4 
 config/non-seat0.conf.multi-seat           |   18 +
 configure.ac                               |   40 +-
 dix/Makefile.am                            |    3 
 dix/cursor.c                               |   29 +
 dix/devices.c                              |   59 ++-
 dix/dispatch.c                             |   27 -
 dix/dixutils.c                             |    8 
 dix/eventconvert.c                         |   23 -
 dix/events.c                               |  129 ++++---
 dix/getevents.c                            |   63 ++-
 dix/grabs.c                                |   21 -
 dix/main.c                                 |   15 
 dix/pixmap.c                               |    2 
 dix/ptrveloc.c                             |    5 
 dix/registry.c                             |   25 -
 dix/stubmain.c                             |   35 +
 dix/touch.c                                |  124 +++++-
 dix/window.c                               |   20 -
 exa/Makefile.am                            |    2 
 fb/fbpict.c                                |    8 
 fb/fbpixmap.c                              |    1 
 fb/wfbrename.h                             |    1 
 glx/Makefile.am                            |    4 
 glx/extension_string.c                     |    2 
 glx/extension_string.h                     |    5 
 glx/glxcmds.c                              |   26 +
 glx/glxdri.c                               |   12 
 glx/glxdri2.c                              |   15 
 glx/glxdricommon.c                         |    4 
 glx/glxscreens.h                           |    3 
 hw/dmx/config/dmxcompat.c                  |    4 
 hw/dmx/dmx_glxvisuals.c                    |   25 -
 hw/dmx/glxProxy/glxcmds.c                  |   16 
 hw/dmx/glxProxy/glxscreens.c               |    9 
 hw/dmx/glxProxy/glxsingle.c                |    6 
 hw/dmx/glxProxy/glxvendor.c                |    4 
 hw/kdrive/ephyr/Makefile.am                |    2 
 hw/kdrive/ephyr/XF86dri.c                  |   23 -
 hw/kdrive/ephyr/ephyr.c                    |    7 
 hw/kdrive/ephyr/ephyrdri.c                 |    5 
 hw/kdrive/ephyr/ephyrdri.h                 |    2 
 hw/kdrive/ephyr/ephyrdriext.c              |   23 -
 hw/kdrive/ephyr/ephyrhostglx.c             |   49 +-
 hw/kdrive/ephyr/ephyrhostvideo.c           |   40 +-
 hw/kdrive/ephyr/ephyrinit.c                |   10 
 hw/kdrive/ephyr/ephyrvideo.c               |   24 -
 hw/kdrive/ephyr/hostx.c                    |   45 +-
 hw/kdrive/ephyr/hostx.h                    |    5 
 hw/kdrive/ephyr/man/Xephyr.man             |    6 
 hw/kdrive/ephyr/os.c                       |    2 
 hw/kdrive/fake/Makefile.am                 |    2 
 hw/kdrive/fbdev/Makefile.am                |    2 
 hw/kdrive/fbdev/fbdev.c                    |  167 +++++++--
 hw/kdrive/fbdev/fbdev.h                    |    2 
 hw/kdrive/linux/Makefile.am                |    2 
 hw/kdrive/linux/evdev.c                    |    2 
 hw/kdrive/linux/linux.c                    |    2 
 hw/kdrive/linux/mouse.c                    |   12 
 hw/kdrive/linux/ps2.c                      |    2 
 hw/kdrive/src/Makefile.am                  |    2 
 hw/kdrive/src/kdrive.c                     |    9 
 hw/kdrive/src/kdrive.h                     |   13 
 hw/kdrive/src/kinput.c                     |   21 -
 hw/kdrive/src/kxv.c                        |    2 
 hw/xfree86/Makefile.am                     |    4 
 hw/xfree86/common/Makefile.am              |    2 
 hw/xfree86/common/xf86.h                   |   26 -
 hw/xfree86/common/xf86Config.c             |    1 
 hw/xfree86/common/xf86DPMS.c               |   45 +-
 hw/xfree86/common/xf86Events.c             |   18 -
 hw/xfree86/common/xf86Init.c               |    2 
 hw/xfree86/common/xf86Mode.c               |   17 
 hw/xfree86/common/xf86Module.h             |    2 
 hw/xfree86/common/xf86Option.c             |    2 
 hw/xfree86/common/xf86Xinput.c             |    2 
 hw/xfree86/common/xf86fbman.c              |   12 
 hw/xfree86/common/xf86platformBus.c        |   37 +-
 hw/xfree86/common/xf86platformBus.h        |    4 
 hw/xfree86/common/xf86sbusBus.c            |    6 
 hw/xfree86/common/xf86xvmc.c               |    4 
 hw/xfree86/ddc/Makefile.am                 |    2 
 hw/xfree86/ddc/ddc.c                       |    7 
 hw/xfree86/ddc/xf86DDC.h                   |    2 
 hw/xfree86/dixmods/Makefile.am             |    2 
 hw/xfree86/dri2/dri2.c                     |   19 -
 hw/xfree86/exa/Makefile.am                 |    2 
 hw/xfree86/fbdevhw/Makefile.am             |    2 
 hw/xfree86/fbdevhw/fbdevhw.c               |    1 
 hw/xfree86/i2c/Makefile.am                 |    2 
 hw/xfree86/int10/Makefile.am               |    6 
 hw/xfree86/loader/Makefile.am              |    2 
 hw/xfree86/man/xorg.conf.man               |   18 -
 hw/xfree86/modes/Makefile.am               |    6 
 hw/xfree86/modes/xf86Crtc.c                |  146 ++++++--
 hw/xfree86/modes/xf86Crtc.h                |    3 
 hw/xfree86/modes/xf86Cursors.c             |    4 
 hw/xfree86/modes/xf86DisplayIDModes.c      |    1 
 hw/xfree86/modes/xf86Modes.h               |    6 
 hw/xfree86/modes/xf86RandR12.c             |   42 ++
 hw/xfree86/modes/xf86RandR12.h             |    3 
 hw/xfree86/modes/xf86Rename.h              |   94 -----
 hw/xfree86/os-support/bsd/Makefile.am      |    2 
 hw/xfree86/os-support/bus/Makefile.am      |    2 
 hw/xfree86/os-support/bus/Sbus.c           |    8 
 hw/xfree86/os-support/hurd/Makefile.am     |    2 
 hw/xfree86/os-support/linux/Makefile.am    |    2 
 hw/xfree86/os-support/linux/lnx_platform.c |   62 ++-
 hw/xfree86/os-support/misc/Makefile.am     |    2 
 hw/xfree86/os-support/shared/posix_tty.c   |    3 
 hw/xfree86/os-support/solaris/Makefile.am  |    2 
 hw/xfree86/os-support/solaris/sun_init.c   |    2 
 hw/xfree86/os-support/stub/Makefile.am     |    2 
 hw/xfree86/os-support/xf86_OSlib.h         |    5 
 hw/xfree86/os-support/xf86_OSproc.h        |    3 
 hw/xfree86/parser/Makefile.am              |    2 
 hw/xfree86/parser/write.c                  |    3 
 hw/xfree86/ramdac/Makefile.am              |    2 
 hw/xfree86/ramdac/xf86Cursor.c             |   29 -
 hw/xfree86/shadowfb/Makefile.am            |    2 
 hw/xfree86/utils/cvt/Makefile.am           |    3 
 hw/xfree86/utils/cvt/cvt.c                 |    1 
 hw/xfree86/vbe/Makefile.am                 |    3 
 hw/xfree86/vbe/vbe.c                       |    1 
 hw/xfree86/vgahw/Makefile.am               |    2 
 hw/xfree86/x86emu/Makefile.am              |    2 
 hw/xnest/Args.h                            |    2 
 hw/xquartz/GL/visualConfigs.c              |    3 
 hw/xquartz/Makefile.am                     |    5 
 hw/xquartz/pbproxy/x-selection.m           |    3 
 hw/xquartz/pseudoramiX.c                   |  516 -----------------------------
 hw/xquartz/pseudoramiX.h                   |   10 
 hw/xquartz/xpr/Makefile.am                 |    1 
 hw/xwin/InitInput.c                        |    1 
 hw/xwin/InitOutput.c                       |   40 ++
 hw/xwin/Makefile.am                        |    8 
 hw/xwin/XWin.exe.manifest                  |    2 
 hw/xwin/glx/Makefile.am                    |    6 
 hw/xwin/glx/indirect.c                     |    2 
 hw/xwin/win.h                              |   29 -
 hw/xwin/winauth.c                          |    7 
 hw/xwin/winclipboard.h                     |    4 
 hw/xwin/winclipboardthread.c               |   16 
 hw/xwin/winclipboardwndproc.c              |   11 
 hw/xwin/winclipboardwrappers.c             |    2 
 hw/xwin/wincursor.c                        |   43 +-
 hw/xwin/windialogs.c                       |   74 +---
 hw/xwin/winfillsp.c                        |    2 
 hw/xwin/winglobals.c                       |    2 
 hw/xwin/winglobals.h                       |    5 
 hw/xwin/winkeybd.c                         |   64 ++-
 hw/xwin/winmessages.h                      |    2 
 hw/xwin/winmouse.c                         |   50 +-
 hw/xwin/winmsgwindow.c                     |  180 ++++++++++
 hw/xwin/winmultiwindowclass.c              |   31 +
 hw/xwin/winmultiwindowclass.h              |    2 
 hw/xwin/winmultiwindowicons.c              |    6 
 hw/xwin/winmultiwindowwindow.c             |   15 
 hw/xwin/winmultiwindowwm.c                 |   56 +--
 hw/xwin/winmultiwindowwndproc.c            |   30 +
 hw/xwin/winpfbdd.c                         |   13 
 hw/xwin/winprefs.c                         |   29 -
 hw/xwin/winprefs.h                         |   10 
 hw/xwin/winscrinit.c                       |    6 
 hw/xwin/winsetsp.c                         |   52 +-
 hw/xwin/wintrayicon.c                      |    2 
 hw/xwin/winwin32rootless.c                 |   44 +-
 hw/xwin/winwin32rootlesswindow.c           |    8 
 hw/xwin/winwin32rootlesswndproc.c          |   27 +
 hw/xwin/winwindow.c                        |    4 
 hw/xwin/winwindow.h                        |    1 
 hw/xwin/winwindowswm.c                     |   21 -
 hw/xwin/winwndproc.c                       |   27 +
 include/callback.h                         |    1 
 include/cursor.h                           |    4 
 include/dix-config.h.in                    |    3 
 include/dixgrabs.h                         |    2 
 include/dixstruct.h                        |    2 
 include/eventstr.h                         |    2 
 include/hotplug.h                          |    1 
 include/input.h                            |    7 
 include/inputstr.h                         |    6 
 include/list.h                             |    2 
 include/registry.h                         |    2 
 include/xkbsrv.h                           |    3 
 include/xorg-config.h.in                   |    3 
 mi/miinitext.c                             |    2 
 miext/damage/Makefile.am                   |    2 
 miext/shadow/Makefile.am                   |    4 
 miext/shadow/c2p_core.h                    |  187 ++++++++++
 miext/shadow/shadow.h                      |   12 
 miext/shadow/shafb4.c                      |  139 +++++++
 miext/shadow/shafb8.c                      |  143 ++++++++
 miext/shadow/shiplan2p4.c                  |  136 +++++++
 miext/shadow/shiplan2p8.c                  |  137 +++++++
 miext/shadow/shpacked.c                    |    1 
 miext/sync/Makefile.am                     |    2 
 os/Makefile.am                             |    5 
 os/backtrace.c                             |   75 ++++
 os/io.c                                    |    1 
 os/log.c                                   |  121 ++++++
 pseudoramiX/Makefile.am                    |    7 
 pseudoramiX/pseudoramiX.c                  |  516 +++++++++++++++++++++++++++++
 pseudoramiX/pseudoramiX.h                  |   10 
 randr/randr.c                              |   24 +
 randr/randrstr.h                           |   10 
 randr/rrcrtc.c                             |   11 
 randr/rrinfo.c                             |    2 
 randr/rroutput.c                           |    2 
 randr/rrprovider.c                         |    2 
 randr/rrscreen.c                           |    2 
 render/animcur.c                           |    3 
 test/Makefile.am                           |    4 
 test/hashtabletest.c                       |    4 
 test/input.c                               |    2 
 test/signal-logging.c                      |  106 +++++
 test/xi2/Makefile.am                       |    2 
 test/xi2/protocol-xiqueryversion.c         |   60 +--
 xfixes/cursor.c                            |   16 
 xfixes/xfixesint.h                         |    2 
 xkb/xkb.c                                  |    3 
 xkb/xkbActions.c                           |  149 ++++----
 xkb/xkbInit.c                              |   29 +
 248 files changed, 3966 insertions(+), 1957 deletions(-)

New commits:
commit 97f3023b2598cd3e7e46d6c316e0e72807dcab79
Author: Jeremy Huddleston Sequoia <jeremyhu at apple.com>
Date:   Sun Sep 15 08:10:33 2013 -0700

    XQuartz: pbproxy: Fix build with -DDEBUG
    
    Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu at apple.com>

diff --git a/hw/xquartz/pbproxy/x-selection.m b/hw/xquartz/pbproxy/x-selection.m
index 57ddb74..f4f4de8 100644
--- a/hw/xquartz/pbproxy/x-selection.m
+++ b/hw/xquartz/pbproxy/x-selection.m
@@ -85,8 +85,7 @@ static struct propdata null_propdata = {
 static void
 dump_prefs()
 {
-    ErrorF(fp,
-           "pbproxy preferences:\n"
+    ErrorF("pbproxy preferences:\n"
            "\tactive %u\n"
            "\tprimary_on_grab %u\n"
            "\tclipboard_to_pasteboard %u\n"
commit f68527acf4d6504bd7d2c1fbc7eb67f9c2d8337a
Author: Jeremy Huddleston Sequoia <jeremyhu at apple.com>
Date:   Sun Sep 15 08:07:44 2013 -0700

    XQuartz: Fix build with moved pseudoramiX
    
    Regression from: e716baedc4d8e52a60f43ef21aba771b340d8c8b
    
    Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu at apple.com>
    CC: Jon TURNEY <jon.turney at dronecode.org.uk>

diff --git a/hw/xquartz/Makefile.am b/hw/xquartz/Makefile.am
index 2e894d7..2ca953c 100644
--- a/hw/xquartz/Makefile.am
+++ b/hw/xquartz/Makefile.am
@@ -8,6 +8,7 @@ AM_CPPFLAGS = \
 	-DUSE_NEW_CLUT \
 	-DXFree86Server \
 	-I$(top_srcdir)/miext/rootless \
+	-I$(top_builddir)/pseudoramiX \
 	-DX11LIBDIR=\"$(libdir)\"
 
 if GLX
diff --git a/hw/xquartz/xpr/Makefile.am b/hw/xquartz/xpr/Makefile.am
index 763a7cd..c654ee5 100644
--- a/hw/xquartz/xpr/Makefile.am
+++ b/hw/xquartz/xpr/Makefile.am
@@ -3,6 +3,7 @@ noinst_LTLIBRARIES = libXquartzXpr.la
 AM_CFLAGS =  $(DIX_CFLAGS)
 AM_CPPFLAGS = \
 	-I$(srcdir) -I$(srcdir)/.. \
+	-I$(top_builddir)/pseudoramiX \
 	-I$(top_srcdir)/miext \
 	-I$(top_srcdir)/miext/rootless
 
commit 47ff382d1fce25a8b097d45b79489e891f1f1228
Merge: 6f89ae3 3752a81
Author: Keith Packard <keithp at keithp.com>
Date:   Mon Sep 9 15:13:42 2013 -0700

    Merge remote-tracking branch 'jturney/master'

commit 6f89ae3e64c4dfeea508813e546c10ba1da3ea8e
Author: Thomas Klausner <wiz at NetBSD.org>
Date:   Wed Sep 4 20:06:07 2013 +0200

    Fix typo in configure warning.
    
    Signed-off-by: Thomas Klausner <wiz at NetBSD.org>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/configure.ac b/configure.ac
index d27ca23..5159420 100644
--- a/configure.ac
+++ b/configure.ac
@@ -47,7 +47,7 @@ XORG_WITH_XSLTPROC
 XORG_ENABLE_UNIT_TESTS
 XORG_LD_WRAP([optional])
 
-m4_ifndef([XORG_FONT_MACROS_VERSION], [m4_fatal([must install fontutil 1.1 or later before running autoconf/autogen])])
+m4_ifndef([XORG_FONT_MACROS_VERSION], [m4_fatal([must install font-util 1.1 or later before running autoconf/autogen])])
 XORG_FONT_MACROS_VERSION(1.1)
 
 dnl this gets generated by autoheader, and thus contains all the defines.  we
commit 47218a6e09549781fd61dbf5e0d3d5c81da64323
Author: Thomas Klausner <wiz at NetBSD.org>
Date:   Wed Sep 4 20:05:51 2013 +0200

    Fix bug in cursor handling.
    
    CreateCursor (Xlib call XCreatePixmapCursor) with a non-bitmap
    source pixmap and a None mask is supposed to error out with BadMatch,
    but didn't.
    
    From der Mouse <mouse at Rodents-Montreal.ORG>, changed following
    comments by Alan Coopersmith <alan.coopersmith at oracle.com>.
    
    Signed-off-by: Thomas Klausner <wiz at NetBSD.org>
    Reviewed-by: Jasper St. Pierre <jstpierre at mecheye.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/dispatch.c b/dix/dispatch.c
index 51d0de2..71fda48 100644
--- a/dix/dispatch.c
+++ b/dix/dispatch.c
@@ -2864,18 +2864,25 @@ ProcCreateCursor(ClientPtr client)
         return rc;
     }
 
-    rc = dixLookupResourceByType((pointer *) &msk, stuff->mask, RT_PIXMAP,
-                                 client, DixReadAccess);
-    if (rc != Success) {
-        if (stuff->mask != None) {
+    if (src->drawable.depth != 1)
+        return (BadMatch);
+
+    /* Find and validate cursor mask pixmap, if one is provided */
+    if (stuff->mask != None) {
+        rc = dixLookupResourceByType((pointer *) &msk, stuff->mask, RT_PIXMAP,
+                                     client, DixReadAccess);
+        if (rc != Success) {
             client->errorValue = stuff->mask;
             return rc;
         }
+
+        if (src->drawable.width != msk->drawable.width
+            || src->drawable.height != msk->drawable.height
+            || src->drawable.depth != 1 || msk->drawable.depth != 1)
+            return BadMatch;
     }
-    else if (src->drawable.width != msk->drawable.width
-             || src->drawable.height != msk->drawable.height
-             || src->drawable.depth != 1 || msk->drawable.depth != 1)
-        return BadMatch;
+    else
+        msk = NULL;
 
     width = src->drawable.width;
     height = src->drawable.height;
commit 1110b71e360195aab040d835b54540ab558638c5
Author: Chris Clayton <chris2553 at googlemail.com>
Date:   Wed Sep 4 15:42:04 2013 +1000

    kdrive: fix build error on gcc 4.8 for out-of-bounds array access
    
    I'm getting a error building xorg-server-1.14.1.902 with thelatest snapshot
    of gcc-4.8:
    
    input.c:225:43: error: array subscript is above array bounds
    [-Werror=array-bounds]
    
    This is because kdNumInputFds can become equal to KD_MAX_INPUT_FDS in
    KdRegisterFd(). This means that in KdUnregisterFd(), kdInputFds[j + 1] can
    be beyond the end of the array.
    
    Signed-off-by: Chris Clayton <chris2553 at googlemail.com>
    Reviewed-by: Keith Packard <keithp at keithp.com>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/kdrive/src/kinput.c b/hw/kdrive/src/kinput.c
index f93830e..527c7a2 100644
--- a/hw/kdrive/src/kinput.c
+++ b/hw/kdrive/src/kinput.c
@@ -221,7 +221,7 @@ KdUnregisterFd(void *closure, int fd, Bool do_close)
             if (do_close)
                 close(kdInputFds[i].fd);
             kdNumInputFds--;
-            for (j = i; j < kdNumInputFds; j++)
+            for (j = i; j < (kdNumInputFds - 1); j++)
                 kdInputFds[j] = kdInputFds[j + 1];
             break;
         }
commit 3752a815800626ae93f64a856f5889aa6636344e
Author: Marc Haesen <marha at users.sourceforge.net>
Date:   Sat Aug 10 17:38:38 2013 +0100

    hw/xwin: Remove unnecessary and incorrect HWND casts
    
    Signed-off-by: Marc Haesen <marha at users.sourceforge.net>
    Reviewed-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/winmultiwindowwm.c b/hw/xwin/winmultiwindowwm.c
index 6851368..1dd8ba5 100644
--- a/hw/xwin/winmultiwindowwm.c
+++ b/hw/xwin/winmultiwindowwm.c
@@ -1061,15 +1061,13 @@ winMultiWindowXMsgProc(void *pArg)
                 (pProcArg->pDisplay, pProcArg->dwScreen, TRUE)) {
                 if (!g_fAnotherWMRunning) {
                     g_fAnotherWMRunning = TRUE;
-                    SendMessage(*(HWND *) pProcArg->hwndScreen, WM_UNMANAGE, 0,
-                                0);
+                    SendMessage(pProcArg->hwndScreen, WM_UNMANAGE, 0, 0);
                 }
             }
             else {
                 if (g_fAnotherWMRunning) {
                     g_fAnotherWMRunning = FALSE;
-                    SendMessage(*(HWND *) pProcArg->hwndScreen, WM_MANAGE, 0,
-                                0);
+                    SendMessage(pProcArg->hwndScreen, WM_MANAGE, 0, 0);
                 }
             }
             Sleep(500);
diff --git a/hw/xwin/winmultiwindowwndproc.c b/hw/xwin/winmultiwindowwndproc.c
index a888f08..abb87ee 100644
--- a/hw/xwin/winmultiwindowwndproc.c
+++ b/hw/xwin/winmultiwindowwndproc.c
@@ -825,7 +825,7 @@ winTopLevelWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
         }
         /* Prevent the mouse wheel from stalling when another window is minimized */
         if (HIWORD(wParam) == 0 && LOWORD(wParam) == WA_ACTIVE &&
-            (HWND) lParam != NULL && (HWND) lParam != (HWND) GetParent(hwnd))
+            (HWND) lParam != NULL && (HWND) lParam != GetParent(hwnd))
             SetFocus(hwnd);
         return 0;
 
commit 34932cef6cc800fbdf2f375506057ed8cd1e07f6
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Mon Apr 1 13:43:00 2013 +0100

    hw/xwin: Fix compilation of winauth.c with -Werror=implicit-function-declaration
    
    /jhbuild/checkout/xorg/xserver/hw/xwin/winauth.c: In function ‘MitGenerateCookie’:
    /jhbuild/checkout/xorg/xserver/hw/xwin/winauth.c:87:5: error: implicit declaration of function ‘MitAddCookie’ [-Werror=implicit-function-declaration]
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>
    Reviewed-by: Marc Haesen <marha at users.sourceforge.net>

diff --git a/hw/xwin/winauth.c b/hw/xwin/winauth.c
index 25d1fbd..a6a7366 100644
--- a/hw/xwin/winauth.c
+++ b/hw/xwin/winauth.c
@@ -36,6 +36,7 @@
 
 /* Includes for authorization */
 #include "securitysrv.h"
+#include "os/osdep.h"
 
 /*
  * Constants
@@ -56,8 +57,7 @@ static char *g_pAuthData = NULL;
  */
 
 #ifndef XCSECURITY
-static
-    void
+void
 GenerateRandomData(int len, char *buf)
 {
     int fd;
@@ -70,9 +70,8 @@ GenerateRandomData(int len, char *buf)
 static char cookie[16];         /* 128 bits */
 
 XID
-    static
 MitGenerateCookie(unsigned data_length,
-                  char *data,
+                  const char *data,
                   XID id, unsigned *data_length_return, char **data_return)
 {
     int i = 0;
commit 2a08554a0bf80b862c15676c31ecd463b616518c
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Mon Jun 17 23:54:01 2013 +0100

    hw/xwin: Remove unused extern g_fUseUnicode from winclipboardwndproc.c
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>
    Reviewed-by: Marc Haesen <marha at users.sourceforge.net>

diff --git a/hw/xwin/winclipboardwndproc.c b/hw/xwin/winclipboardwndproc.c
index 32712aa..90dc9e0 100644
--- a/hw/xwin/winclipboardwndproc.c
+++ b/hw/xwin/winclipboardwndproc.c
@@ -48,7 +48,6 @@
  * References to external symbols
  */
 
-extern Bool g_fUseUnicode;
 extern void *g_pClipboardDisplay;
 extern Window g_iClipboardWindow;
 extern Atom g_atomLastOwnedSelection;
commit 69401f38a697c941ea58351028f4cd4b810f9188
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Mon Jun 17 18:37:26 2013 +0100

    hw/xwin: Remove unneeded forward declaration of winProcessXEventsTimeout()
    
    Remove unneeded forward declaration of winProcessXEventsTimeout(), the actual
    definition immediately follows.
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>
    Reviewed-by: Marc Haesen <marha at users.sourceforge.net>

diff --git a/hw/xwin/winclipboardwndproc.c b/hw/xwin/winclipboardwndproc.c
index e19f678..32712aa 100644
--- a/hw/xwin/winclipboardwndproc.c
+++ b/hw/xwin/winclipboardwndproc.c
@@ -53,16 +53,6 @@ extern void *g_pClipboardDisplay;
 extern Window g_iClipboardWindow;
 extern Atom g_atomLastOwnedSelection;
 
-/* 
- * Local function prototypes
- */
-
-static int
-
-
-winProcessXEventsTimeout(HWND hwnd, int iWindow, Display * pDisplay,
-                         Bool fUseUnicode, int iTimeoutSec);
-
 /*
  * Process X events up to specified timeout
  */
commit 9c45a1ad44f12ac25e1c3b7a18a3bceb85a2cf38
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Mon Jun 17 16:58:47 2013 +0100

    hw/xwin: Remove prototype for non-existent winDeinitClipboard()
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>
    Reviewed-by: Marc Haesen <marha at users.sourceforge.net>

diff --git a/hw/xwin/winclipboard.h b/hw/xwin/winclipboard.h
index aa7fd44..cb77695 100644
--- a/hw/xwin/winclipboard.h
+++ b/hw/xwin/winclipboard.h
@@ -106,9 +106,6 @@ void
 
 void *winClipboardProc(void *);
 
-void
- winDeinitClipboard(void);
-
 /*
  * winclipboardwndproc.c
  */
commit acc46fc217352b94f77a6b5b14808ea89875a2a1
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Mon Jun 17 00:40:13 2013 +0100

    hw/xwin: Remove unused externs from winclipboardwrappers.c
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>
    Reviewed-by: Marc Haesen <marha at users.sourceforge.net>

diff --git a/hw/xwin/winclipboardwrappers.c b/hw/xwin/winclipboardwrappers.c
index 008088b..bfd6bff 100644
--- a/hw/xwin/winclipboardwrappers.c
+++ b/hw/xwin/winclipboardwrappers.c
@@ -56,8 +56,6 @@ DISPATCH_PROC(winProcSetSelectionOwner);
  * References to external symbols
  */
 
-extern unsigned int g_uiAuthDataLen;
-extern char *g_pAuthData;
 extern Bool g_fClipboardLaunched;
 extern Bool g_fClipboardStarted;
 extern Bool g_fClipboard;
commit fcc7767f8cd6c318861b1060ef6a3936750a0dd2
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Mon Jun 10 17:31:12 2013 +0100

    hw/xwin: Remove unused winProcQueryTreeOrig variable
    
    Unused since 47c7b6d3e626497747ae2780f259a15b8e6c846f "Remove no-longer needed
    tricks used to prevent the clipboard client from being killed"
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>
    Reviewed-by: Marc Haesen <marha at users.sourceforge.net>

diff --git a/hw/xwin/InitInput.c b/hw/xwin/InitInput.c
index 395b533..36346b7 100644
--- a/hw/xwin/InitInput.c
+++ b/hw/xwin/InitInput.c
@@ -39,7 +39,6 @@
 
 #ifdef XWIN_CLIPBOARD
 int winProcEstablishConnection(ClientPtr /* client */ );
-int winProcQueryTree(ClientPtr /* client */ );
 int winProcSetSelectionOwner(ClientPtr /* client */ );
 #endif
 
diff --git a/hw/xwin/winglobals.c b/hw/xwin/winglobals.c
index b3ca295..d281322 100644
--- a/hw/xwin/winglobals.c
+++ b/hw/xwin/winglobals.c
@@ -85,7 +85,6 @@ pthread_mutex_t g_pmTerminating = PTHREAD_MUTEX_INITIALIZER;
  * Wrapped DIX functions
  */
 winDispatchProcPtr winProcEstablishConnectionOrig = NULL;
-winDispatchProcPtr winProcQueryTreeOrig = NULL;
 winDispatchProcPtr winProcSetSelectionOwnerOrig = NULL;
 
 /*
diff --git a/hw/xwin/winglobals.h b/hw/xwin/winglobals.h
index 4faba9e..58a919c 100644
--- a/hw/xwin/winglobals.h
+++ b/hw/xwin/winglobals.h
@@ -71,7 +71,6 @@ typedef int (*winDispatchProcPtr) (ClientPtr);
  * Wrapped DIX functions
  */
 extern winDispatchProcPtr winProcEstablishConnectionOrig;
-extern winDispatchProcPtr winProcQueryTreeOrig;
 extern winDispatchProcPtr winProcSetSelectionOwnerOrig;
 #endif
 
commit 8fa882a980abea6f05b4b59447a187aea2c793a1
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Sat Aug 10 12:41:07 2013 +0100

    hw/xwin: Fix ARGB cursor conversion on x86_64
    
    Fix erroneous use of unsigned long * for lpBits in winXCursorToHCURSOR() which
    leads to ARGB cursors being vertically streched on x86_64 by interleaving blank
    rows of pixels.
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>
    Reviewed-by: Marc Haesen <marha at users.sourceforge.net>

diff --git a/hw/xwin/wincursor.c b/hw/xwin/wincursor.c
index 285e1bc..a35336a 100644
--- a/hw/xwin/wincursor.c
+++ b/hw/xwin/wincursor.c
@@ -162,7 +162,7 @@ winLoadCursor(ScreenPtr pScreen, CursorPtr pCursor, int screen)
     HDC hDC;
     BITMAPV4HEADER bi;
     BITMAPINFO *pbmi;
-    unsigned long *lpBits;
+    uint32_t *lpBits;
 
     WIN_DEBUG_MSG("winLoadCursor: Win32: %dx%d X11: %dx%d hotspot: %d,%d\n",
                   pScreenPriv->cursor.sm_cx, pScreenPriv->cursor.sm_cy,
@@ -256,15 +256,14 @@ winLoadCursor(ScreenPtr pScreen, CursorPtr pCursor, int screen)
         bi.bV4AlphaMask = 0xFF000000;
 
         lpBits =
-            (unsigned long *) calloc(pScreenPriv->cursor.sm_cx *
-                                     pScreenPriv->cursor.sm_cy,
-                                     sizeof(unsigned long));
+            (uint32_t *) calloc(pScreenPriv->cursor.sm_cx *
+                                pScreenPriv->cursor.sm_cy,
+                                sizeof(uint32_t));
 
         if (lpBits) {
             int y;
             for (y = 0; y < nCY; y++) {
-                unsigned long *src, *dst;
-
+                void *src, *dst;
                 src = &(pCursor->bits->argb[y * pCursor->bits->width]);
                 dst = &(lpBits[y * pScreenPriv->cursor.sm_cx]);
                 memcpy(dst, src, 4 * nCX);
@@ -304,8 +303,8 @@ winLoadCursor(ScreenPtr pScreen, CursorPtr pCursor, int screen)
         pbmiColors[2].rgbReserved = 0;
 
         lpBits =
-            (unsigned long *) calloc(pScreenPriv->cursor.sm_cx *
-                                     pScreenPriv->cursor.sm_cy, sizeof(char));
+            (uint32_t *) calloc(pScreenPriv->cursor.sm_cx *
+                                pScreenPriv->cursor.sm_cy, sizeof(char));
 
         pCur = (unsigned char *) lpBits;
         if (lpBits) {
commit 4bfb2dce5eea4923eaf86eca33b96087b28235f5
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Sun Apr 7 23:59:44 2013 +0100

    hw/xwin: Fix an issue in winSetSpansNativeGDI() identifed by -Warray-bounds
    
    The BITMAPINFO local only has room for a single RBGQUAD in bmiColors, but we
    access two (black and white for a mono-color DIB).  Fix by changing to a dynamic
    allocation big enough for a BITMAPINFO and a RGBQUAD.
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>
    Reviewed-by: Marc Haesen <marha at users.sourceforge.net>

diff --git a/hw/xwin/winsetsp.c b/hw/xwin/winsetsp.c
index f102f9f..11108cb 100644
--- a/hw/xwin/winsetsp.c
+++ b/hw/xwin/winsetsp.c
@@ -46,7 +46,7 @@ winSetSpansNativeGDI(DrawablePtr pDrawable,
     PixmapPtr pPixmap = NULL;
     winPrivPixmapPtr pPixmapPriv = NULL;
     HBITMAP hbmpOrig = NULL;
-    BITMAPINFO bmi;
+    BITMAPINFO *pbmi;
     HRGN hrgn = NULL, combined = NULL;
     int nbox;
     BoxPtr pbox;
@@ -57,6 +57,8 @@ winSetSpansNativeGDI(DrawablePtr pDrawable,
     if (!nbox)
         return;
 
+    pbmi = malloc(sizeof(BITMAPINFO) + sizeof(RGBQUAD));
+
     combined = CreateRectRgn(pbox->x1, pbox->y1, pbox->x2, pbox->y2);
     nbox--;
     pbox++;
@@ -86,19 +88,20 @@ winSetSpansNativeGDI(DrawablePtr pDrawable,
                        "failed on pPixmapPriv->hBitmap\n");
 
         while (iSpans--) {
-            ZeroMemory(&bmi, sizeof(BITMAPINFO));
-            bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
-            bmi.bmiHeader.biWidth = *piWidths;
-            bmi.bmiHeader.biHeight = 1;
-            bmi.bmiHeader.biPlanes = 1;
-            bmi.bmiHeader.biBitCount = pDrawable->depth;
-            bmi.bmiHeader.biCompression = BI_RGB;
+            ZeroMemory(pbmi, sizeof(BITMAPINFO));
+            pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
+            pbmi->bmiHeader.biWidth = *piWidths;
+            pbmi->bmiHeader.biHeight = 1;
+            pbmi->bmiHeader.biPlanes = 1;
+            pbmi->bmiHeader.biBitCount = pDrawable->depth;
+            pbmi->bmiHeader.biCompression = BI_RGB;
 
             /* Setup color table for mono DIBs */
             if (pDrawable->depth == 1) {
-                bmi.bmiColors[1].rgbBlue = 255;
-                bmi.bmiColors[1].rgbGreen = 255;
-                bmi.bmiColors[1].rgbRed = 255;
+                RGBQUAD *bmiColors = &(pbmi->bmiColors[0]);
+                bmiColors[1].rgbBlue = 255;
+                bmiColors[1].rgbGreen = 255;
+                bmiColors[1].rgbRed = 255;
             }
 
             StretchDIBits(pGCPriv->hdcMem,
@@ -107,7 +110,7 @@ winSetSpansNativeGDI(DrawablePtr pDrawable,
                           0, 0,
                           *piWidths, 1,
                           pSrcs,
-                          (BITMAPINFO *) &bmi,
+                          (BITMAPINFO *) pbmi,
                           DIB_RGB_COLORS, g_copyROP[pGC->alu]);
 
             pSrcs += PixmapBytePad(*piWidths, pDrawable->depth);
@@ -129,19 +132,20 @@ winSetSpansNativeGDI(DrawablePtr pDrawable,
         combined = NULL;
 
         while (iSpans--) {
-            ZeroMemory(&bmi, sizeof(BITMAPINFO));
-            bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
-            bmi.bmiHeader.biWidth = *piWidths;
-            bmi.bmiHeader.biHeight = 1;
-            bmi.bmiHeader.biPlanes = 1;
-            bmi.bmiHeader.biBitCount = pDrawable->depth;
-            bmi.bmiHeader.biCompression = BI_RGB;
+            ZeroMemory(pbmi, sizeof(BITMAPINFO));
+            pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
+            pbmi->bmiHeader.biWidth = *piWidths;
+            pbmi->bmiHeader.biHeight = 1;
+            pbmi->bmiHeader.biPlanes = 1;
+            pbmi->bmiHeader.biBitCount = pDrawable->depth;
+            pbmi->bmiHeader.biCompression = BI_RGB;
 
             /* Setup color table for mono DIBs */
             if (pDrawable->depth == 1) {
-                bmi.bmiColors[1].rgbBlue = 255;
-                bmi.bmiColors[1].rgbGreen = 255;
-                bmi.bmiColors[1].rgbRed = 255;
+                RGBQUAD *bmiColors = &(pbmi->bmiColors[0]);
+                bmiColors[1].rgbBlue = 255;
+                bmiColors[1].rgbGreen = 255;
+                bmiColors[1].rgbRed = 255;
             }
 
             StretchDIBits(pGCPriv->hdc,
@@ -150,7 +154,7 @@ winSetSpansNativeGDI(DrawablePtr pDrawable,
                           0, 0,
                           *piWidths, 1,
                           pSrcs,
-                          (BITMAPINFO *) &bmi,
+                          (BITMAPINFO *) pbmi,
                           DIB_RGB_COLORS, g_copyROP[pGC->alu]);
 
             pSrcs += PixmapBytePad(*piWidths, pDrawable->depth);
@@ -166,4 +170,6 @@ winSetSpansNativeGDI(DrawablePtr pDrawable,
         FatalError("\nwinSetSpansNativeGDI - Unknown drawable type\n\n");
         break;
     }
+
+    free(pbmi);
 }
commit 784c006adb22c6693ad30dd0b1b05369cfaa7b5e
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Sat Aug 10 11:55:23 2013 +0100

    hw/xwin: Fix -Warray-bounds warning in winXCursorToHCURSOR()
    
    Rewrite winXCursorToHCURSOR() so access to BITMAPINFO bmiColors member doesn't
    trigger an -Warray-bounds warning.
    
    Note that the underlying storage is allocated as a BITMAPV4HEADER, so has
    sufficent room for the extra RGBQUADs bmiColors after the BITMAPINFO bmiHeader.
    
    wincursor.c: In function 'winSetCursor':
    wincursor.c:293:24: error: array subscript is above array bounds [-Werror=array-bounds]
    wincursor.c:294:24: error: array subscript is above array bounds [-Werror=array-bounds]
    wincursor.c:295:24: error: array subscript is above array bounds [-Werror=array-bounds]
    wincursor.c:296:24: error: array subscript is above array bounds [-Werror=array-bounds]
    wincursor.c:297:24: error: array subscript is above array bounds [-Werror=array-bounds]
    wincursor.c:298:24: error: array subscript is above array bounds [-Werror=array-bounds]
    wincursor.c:299:24: error: array subscript is above array bounds [-Werror=array-bounds]
    wincursor.c:300:24: error: array subscript is above array bounds [-Werror=array-bounds]
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>
    Reviewed-by: Marc Haesen <marha at users.sourceforge.net>

diff --git a/hw/xwin/wincursor.c b/hw/xwin/wincursor.c
index 2962d06..285e1bc 100644
--- a/hw/xwin/wincursor.c
+++ b/hw/xwin/wincursor.c
@@ -273,9 +273,12 @@ winLoadCursor(ScreenPtr pScreen, CursorPtr pCursor, int screen)
     }                           /* End if-truecolor-icon */
 
     if (!lpBits) {
+        RGBQUAD *pbmiColors;
         /* Bicolor, use a palettized DIB */
         WIN_DEBUG_MSG("winLoadCursor: Trying two color cursor\n");
         pbmi = (BITMAPINFO *) &bi;
+        pbmiColors = &(pbmi->bmiColors[0]);
+
         memset(pbmi, 0, sizeof(BITMAPINFOHEADER));
         pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
         pbmi->bmiHeader.biWidth = pScreenPriv->cursor.sm_cx;
@@ -286,18 +289,19 @@ winLoadCursor(ScreenPtr pScreen, CursorPtr pCursor, int screen)
         pbmi->bmiHeader.biSizeImage = 0;
         pbmi->bmiHeader.biClrUsed = 3;
         pbmi->bmiHeader.biClrImportant = 3;
-        pbmi->bmiColors[0].rgbRed = 0;  /* Empty */
-        pbmi->bmiColors[0].rgbGreen = 0;
-        pbmi->bmiColors[0].rgbBlue = 0;
-        pbmi->bmiColors[0].rgbReserved = 0;
-        pbmi->bmiColors[1].rgbRed = pCursor->backRed >> 8;      /* Background */
-        pbmi->bmiColors[1].rgbGreen = pCursor->backGreen >> 8;
-        pbmi->bmiColors[1].rgbBlue = pCursor->backBlue >> 8;
-        pbmi->bmiColors[1].rgbReserved = 0;
-        pbmi->bmiColors[2].rgbRed = pCursor->foreRed >> 8;      /* Foreground */
-        pbmi->bmiColors[2].rgbGreen = pCursor->foreGreen >> 8;
-        pbmi->bmiColors[2].rgbBlue = pCursor->foreBlue >> 8;
-        pbmi->bmiColors[2].rgbReserved = 0;
+
+        pbmiColors[0].rgbRed = 0;  /* Empty */
+        pbmiColors[0].rgbGreen = 0;
+        pbmiColors[0].rgbBlue = 0;
+        pbmiColors[0].rgbReserved = 0;
+        pbmiColors[1].rgbRed = pCursor->backRed >> 8;      /* Background */
+        pbmiColors[1].rgbGreen = pCursor->backGreen >> 8;
+        pbmiColors[1].rgbBlue = pCursor->backBlue >> 8;
+        pbmiColors[1].rgbReserved = 0;
+        pbmiColors[2].rgbRed = pCursor->foreRed >> 8;      /* Foreground */
+        pbmiColors[2].rgbGreen = pCursor->foreGreen >> 8;
+        pbmiColors[2].rgbBlue = pCursor->foreBlue >> 8;
+        pbmiColors[2].rgbReserved = 0;
 
         lpBits =
             (unsigned long *) calloc(pScreenPriv->cursor.sm_cx *
commit 41d03c9ccce665b919b180bbb819b78c750aa325
Author: Marc Haesen <marha at users.sourceforge.net>
Date:   Fri Aug 2 18:19:22 2013 +0100

    hw/xwin: Correct size of _WINDOWSWM_NATIVE_HWND property on x86_64
    
    Use the correct size of a HWND on x86_64 in XChangeProperty() and
    XGetWindowProperty() calls for the _WINDOWSWM_NATIVE_HWND property.
    
    Signed-off-by: Marc Haesen <marha at users.sourceforge.net>
    Reviewed-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/winmultiwindowwm.c b/hw/xwin/winmultiwindowwm.c
index 3c44f05..6851368 100644
--- a/hw/xwin/winmultiwindowwm.c
+++ b/hw/xwin/winmultiwindowwm.c
@@ -488,7 +488,7 @@ getHwnd(WMInfoPtr pWMInfo, Window iWindow)
                            iWindow,
                            pWMInfo->atmPrivMap,
                            0,
-                           1,
+                           sizeof(HWND)/4,
                            False,
                            XA_INTEGER,
                            &atmType,
@@ -747,10 +747,10 @@ winMultiWindowWMProc(void *pArg)
             ErrorF("\tWM_WM_MAP\n");
 #endif
             /* Put a note as to the HWND associated with this Window */
-            XChangeProperty(pWMInfo->pDisplay, pNode->msg.iWindow, pWMInfo->atmPrivMap, XA_INTEGER,     //pWMInfo->atmPrivMap,
+            XChangeProperty(pWMInfo->pDisplay, pNode->msg.iWindow, pWMInfo->atmPrivMap, XA_INTEGER,
                             32,
                             PropModeReplace,
-                            (unsigned char *) &(pNode->msg.hwndWindow), 1);
+                            (unsigned char *) &(pNode->msg.hwndWindow), sizeof(HWND)/4);
             UpdateName(pWMInfo, pNode->msg.iWindow);
             UpdateIcon(pWMInfo, pNode->msg.iWindow);
             break;
@@ -759,10 +759,10 @@ winMultiWindowWMProc(void *pArg)
 #if CYGMULTIWINDOW_DEBUG
             ErrorF("\tWM_WM_MAP2\n");
 #endif
-            XChangeProperty(pWMInfo->pDisplay, pNode->msg.iWindow, pWMInfo->atmPrivMap, XA_INTEGER,     //pWMInfo->atmPrivMap,
+            XChangeProperty(pWMInfo->pDisplay, pNode->msg.iWindow, pWMInfo->atmPrivMap, XA_INTEGER,
                             32,
                             PropModeReplace,
-                            (unsigned char *) &(pNode->msg.hwndWindow), 1);
+                            (unsigned char *) &(pNode->msg.hwndWindow), sizeof(HWND)/4);
             break;
 
         case WM_WM_MAP3:
@@ -770,10 +770,10 @@ winMultiWindowWMProc(void *pArg)
             ErrorF("\tWM_WM_MAP3\n");
 #endif
             /* Put a note as to the HWND associated with this Window */
-            XChangeProperty(pWMInfo->pDisplay, pNode->msg.iWindow, pWMInfo->atmPrivMap, XA_INTEGER,     //pWMInfo->atmPrivMap,
+            XChangeProperty(pWMInfo->pDisplay, pNode->msg.iWindow, pWMInfo->atmPrivMap, XA_INTEGER,
                             32,
                             PropModeReplace,
-                            (unsigned char *) &(pNode->msg.hwndWindow), 1);
+                            (unsigned char *) &(pNode->msg.hwndWindow), sizeof(HWND)/4);
             UpdateName(pWMInfo, pNode->msg.iWindow);
             UpdateIcon(pWMInfo, pNode->msg.iWindow);
             UpdateStyle(pWMInfo, pNode->msg.iWindow);
commit 390cfec10ef7d52391f890c7593ac82a7d77d856
Author: Colin Harrison <colin.harrison at virgin.net>
Date:   Fri Aug 9 16:48:12 2013 +0100

    hw/xwin: Correct winprefs.c function signatures for x64.
    
    Correct SetupRootMenu(), SetupSysMenu(), HandleCustomWM_INITMENU() and
    HandleCustomWM_COMMAND() function signatures which use unsigned long parameters,
    where just a specific HWND or HMENU handle type should have been used.
    
    Signed-off-by: Colin Harrison <colin.harrison at virgin.net>
    Reviewed-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Marc Haesen <marha at users.sourceforge.net>

diff --git a/hw/xwin/winmultiwindowwndproc.c b/hw/xwin/winmultiwindowwndproc.c
index 9292e73..a888f08 100644
--- a/hw/xwin/winmultiwindowwndproc.c
+++ b/hw/xwin/winmultiwindowwndproc.c
@@ -420,14 +420,14 @@ winTopLevelWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
         /*
          * Add whatever the setup file wants to for this window
          */
-        SetupSysMenu((unsigned long) hwnd);
+        SetupSysMenu(hwnd);
         return 0;
 
     case WM_SYSCOMMAND:
         /*
          * Any window menu items go through here
          */
-        if (HandleCustomWM_COMMAND((unsigned long) hwnd, LOWORD(wParam))) {
+        if (HandleCustomWM_COMMAND(hwnd, LOWORD(wParam))) {
             /* Don't pass customized menus to DefWindowProc */
             return 0;
         }
@@ -443,7 +443,7 @@ winTopLevelWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
 
     case WM_INITMENU:
         /* Checks/Unchecks any menu items before they are displayed */
-        HandleCustomWM_INITMENU((unsigned long) hwnd, wParam);
+        HandleCustomWM_INITMENU(hwnd, (HMENU)wParam);
         break;
 
     case WM_ERASEBKGND:
diff --git a/hw/xwin/winprefs.c b/hw/xwin/winprefs.c
index 8936aae..f386fac 100644
--- a/hw/xwin/winprefs.c
+++ b/hw/xwin/winprefs.c
@@ -188,7 +188,7 @@ ReloadEnumWindowsProc(HWND hwnd, LPARAM lParam)
         }
 
         /* Update the system menu for this window */
-        SetupSysMenu((unsigned long) hwnd);
+        SetupSysMenu(hwnd);
 
         /* That was easy... */
     }
@@ -275,15 +275,11 @@ ReloadPrefs(void)
  * Check/uncheck the ALWAYSONTOP items in this menu
  */
 void
-HandleCustomWM_INITMENU(unsigned long hwndIn, unsigned long hmenuIn)
+HandleCustomWM_INITMENU(HWND hwnd, HMENU hmenu)
 {
-    HWND hwnd;
-    HMENU hmenu;
     DWORD dwExStyle;
     int i, j;
 
-    hwnd = (HWND) hwndIn;
-    hmenu = (HMENU) hmenuIn;
     if (!hwnd || !hmenu)
         return;
 
@@ -305,15 +301,12 @@ HandleCustomWM_INITMENU(unsigned long hwndIn, unsigned long hmenuIn)
  * Return TRUE if command is proccessed, FALSE otherwise.
  */
 Bool
-HandleCustomWM_COMMAND(unsigned long hwndIn, int command)
+HandleCustomWM_COMMAND(HWND hwnd, int command)
 {
-    HWND hwnd;
     int i, j;
     MENUPARSED *m;
     DWORD dwExStyle;
 
-    hwnd = (HWND) hwndIn;
-
     if (!command)
         return FALSE;
 
@@ -412,15 +405,13 @@ HandleCustomWM_COMMAND(unsigned long hwndIn, int command)
  * Add the default or a custom menu depending on the class match
  */
 void
-SetupSysMenu(unsigned long hwndIn)
+SetupSysMenu(HWND hwnd)
 {
-    HWND hwnd;
     HMENU sys;
     int i;
     WindowPtr pWin;
     char *res_name, *res_class;
 
-    hwnd = (HWND) hwndIn;
     if (!hwnd)
         return;
 
@@ -465,11 +456,8 @@ SetupSysMenu(unsigned long hwndIn)
  * Possibly add a menu to the toolbar icon
  */
 void
-SetupRootMenu(unsigned long hmenuRoot)
+SetupRootMenu(HMENU root)
 {
-    HMENU root;
-
-    root = (HMENU) hmenuRoot;
     if (!root)
         return;
 
diff --git a/hw/xwin/winprefs.h b/hw/xwin/winprefs.h
index a4a6e7e..8f4eb08 100644
--- a/hw/xwin/winprefs.h
+++ b/hw/xwin/winprefs.h
@@ -150,16 +150,16 @@ void
  LoadPreferences(void);
 
 void
- SetupRootMenu(unsigned long hmenuRoot);
+ SetupRootMenu(HMENU root);
 
 void
- SetupSysMenu(unsigned long hwndIn);
+ SetupSysMenu(HWND hwnd);
 
 void
- HandleCustomWM_INITMENU(unsigned long hwndIn, unsigned long hmenuIn);
+ HandleCustomWM_INITMENU(HWND hwnd, HMENU hmenu);
 
 Bool
- HandleCustomWM_COMMAND(unsigned long hwndIn, int command);
+ HandleCustomWM_COMMAND(HWND hwnd, int command);
 
 int
  winIconIsOverride(HICON hicon);
diff --git a/hw/xwin/wintrayicon.c b/hw/xwin/wintrayicon.c
index f168b88..e0aa7e5 100644
--- a/hw/xwin/wintrayicon.c
+++ b/hw/xwin/wintrayicon.c
@@ -170,7 +170,7 @@ winHandleIconMessage(HWND hwnd, UINT message,
             RemoveMenu(hmenuTray, ID_APP_HIDE_ROOT, MF_BYCOMMAND);
         }
 
-        SetupRootMenu((unsigned long) hmenuTray);
+        SetupRootMenu(hmenuTray);
 
         /*
          * NOTE: This three-step procedure is required for
commit e716baedc4d8e52a60f43ef21aba771b340d8c8b
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Sat Mar 31 14:42:45 2012 +0100

    Move pseudoramiX code where it can be shared between Xwin and Xquartz
    
    Move pseudoramiX code to a separate top-level directory.  Link Xwin and Xquartz
    with libPseudoramiX
    
    I'm not sure moving this to a top-level directory is appropriate, but I'm not
    sure where else it fits.
    
    Future work: pseudoramiX can probably be consolidated with the rrxinerama code
    (which I think provides fake xinerama data when real XINERAMA is disabled and we
    only have one screen)
    
    v2: fix distcheck
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>
    Reviewed-by: Marc Haesen <marha at users.sourceforge.net>

diff --git a/Makefile.am b/Makefile.am
index 9a62853..7be4271 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -27,6 +27,7 @@ SUBDIRS = \
 	Xext \
 	miext \
 	os \
+	pseudoramiX \
 	randr \
 	render  \
 	Xi \
@@ -77,6 +78,7 @@ DIST_SUBDIRS = \
 	Xext \
 	miext \
 	os \
+	pseudoramiX \
 	randr \
 	render  \
 	Xi \
diff --git a/configure.ac b/configure.ac
index d27ca23..225b70f 100644
--- a/configure.ac
+++ b/configure.ac
@@ -2256,6 +2256,7 @@ miext/damage/Makefile
 miext/shadow/Makefile
 miext/rootless/Makefile
 os/Makefile
+pseudoramiX/Makefile
 randr/Makefile
 render/Makefile
 xkb/Makefile
diff --git a/hw/xquartz/Makefile.am b/hw/xquartz/Makefile.am
index a7cc012..2e894d7 100644
--- a/hw/xquartz/Makefile.am
+++ b/hw/xquartz/Makefile.am
@@ -28,7 +28,6 @@ libXquartz_la_SOURCES = \
 	darwinEvents.c \
 	darwinXinput.c \
 	keysym2ucs.c \
-	pseudoramiX.c \
 	quartz.c \
 	quartzCocoa.m \
 	quartzKeyboard.c \
@@ -36,6 +35,8 @@ libXquartz_la_SOURCES = \
 	quartzRandR.c \
 	console_redirect.c
 
+libXquartz_la_LIBADD = $(top_builddir)/pseudoramiX/libPseudoramiX.la
+
 EXTRA_DIST = \
 	X11Application.h \
 	X11Controller.h \
@@ -44,7 +45,6 @@ EXTRA_DIST = \
 	darwinfb.h \
 	darwinEvents.h \
 	keysym2ucs.h \
-	pseudoramiX.h \
 	quartz.h \
 	quartzCommon.h \
 	quartzKeyboard.h \
diff --git a/hw/xquartz/pseudoramiX.c b/hw/xquartz/pseudoramiX.c
deleted file mode 100644
index 23dbc73..0000000
--- a/hw/xquartz/pseudoramiX.c
+++ /dev/null
@@ -1,516 +0,0 @@
-/*
- * Minimal implementation of PanoramiX/Xinerama
- *
- * This is used in rootless mode where the underlying window server
- * already provides an abstracted view of multiple screens as one
- * large screen area.
- *
- * This code is largely based on panoramiX.c, which contains the
- * following copyright notice:
- */
-/*****************************************************************
-   Copyright (c) 1991, 1997 Digital Equipment Corporation, Maynard, Massachusetts.
-   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.
-
-   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
-   DIGITAL EQUIPMENT CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES, INCLUDING,
-   BUT NOT LIMITED TO CONSEQUENTIAL OR INCIDENTAL 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.
-
-   Except as contained in this notice, the name of Digital Equipment Corporation
-   shall not be used in advertising or otherwise to promote the sale, use or other
-   dealings in this Software without prior written authorization from Digital
-   Equipment Corporation.
- ******************************************************************/
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include "pseudoramiX.h"
-#include "extnsionst.h"
-#include "extinit.h"
-#include "dixstruct.h"
-#include "window.h"
-#include <X11/extensions/panoramiXproto.h>
-#include "globals.h"
-
-#define TRACE PseudoramiXTrace("TRACE " __FILE__ ":%s",__FUNCTION__)
-#define DEBUG_LOG PseudoramiXDebug
-
-Bool noPseudoramiXExtension = FALSE;
-
-extern int
-ProcPanoramiXQueryVersion(ClientPtr client);
-
-static void
-PseudoramiXResetProc(ExtensionEntry *extEntry);
-
-static int
-ProcPseudoramiXQueryVersion(ClientPtr client);
-static int
-ProcPseudoramiXGetState(ClientPtr client);
-static int
-ProcPseudoramiXGetScreenCount(ClientPtr client);
-static int
-ProcPseudoramiXGetScreenSize(ClientPtr client);
-static int
-ProcPseudoramiXIsActive(ClientPtr client);
-static int
-ProcPseudoramiXQueryScreens(ClientPtr client);
-static int
-ProcPseudoramiXDispatch(ClientPtr client);
-
-static int
-SProcPseudoramiXQueryVersion(ClientPtr client);
-static int
-SProcPseudoramiXGetState(ClientPtr client);
-static int
-SProcPseudoramiXGetScreenCount(ClientPtr client);
-static int
-SProcPseudoramiXGetScreenSize(ClientPtr client);
-static int
-SProcPseudoramiXIsActive(ClientPtr client);
-static int
-SProcPseudoramiXQueryScreens(ClientPtr client);
-static int
-SProcPseudoramiXDispatch(ClientPtr client);
-
-typedef struct {
-    int x;
-    int y;
-    int w;
-    int h;
-} PseudoramiXScreenRec;
-
-static PseudoramiXScreenRec *pseudoramiXScreens = NULL;
-static int pseudoramiXScreensAllocated = 0;
-static int pseudoramiXNumScreens = 0;
-static unsigned long pseudoramiXGeneration = 0;
-
-static void
-PseudoramiXTrace(const char *format, ...)
-{
-    va_list ap;
-
-    va_start(ap, format);
-    LogVMessageVerb(X_NONE, 10, format, ap);
-    va_end(ap);
-}
-
-static void
-PseudoramiXDebug(const char *format, ...)
-{
-    va_list ap;
-
-    va_start(ap, format);
-    LogVMessageVerb(X_NONE, 3, format, ap);
-    va_end(ap);
-}
-
-// Add a PseudoramiX screen.
-// The rest of the X server will know nothing about this screen.
-// Can be called before or after extension init.
-// Screens must be re-added once per generation.
-void
-PseudoramiXAddScreen(int x, int y, int w, int h)
-{
-    PseudoramiXScreenRec *s;
-
-    if (noPseudoramiXExtension) return;
-
-    if (pseudoramiXNumScreens == pseudoramiXScreensAllocated) {
-        pseudoramiXScreensAllocated += pseudoramiXScreensAllocated + 1;
-        pseudoramiXScreens = realloc(pseudoramiXScreens,
-                                     pseudoramiXScreensAllocated *
-                                     sizeof(PseudoramiXScreenRec));
-    }
-
-    DEBUG_LOG("x: %d, y: %d, w: %d, h: %d\n", x, y, w, h);
-
-    s = &pseudoramiXScreens[pseudoramiXNumScreens++];
-    s->x = x;
-    s->y = y;
-    s->w = w;
-    s->h = h;
-}
-
-// Initialize PseudoramiX.
-// Copied from PanoramiXExtensionInit
-void
-PseudoramiXExtensionInit(void)
-{
-    Bool success = FALSE;
-    ExtensionEntry      *extEntry;
-
-    if (noPseudoramiXExtension) return;
-
-    TRACE;
-
-    /* Even with only one screen we need to enable PseudoramiX to allow
-       dynamic screen configuration changes. */
-#if 0
-    if (pseudoramiXNumScreens == 1) {
-        // Only one screen - disable Xinerama extension.
-        noPseudoramiXExtension = TRUE;
-        return;
-    }
-#endif
-
-    if (pseudoramiXGeneration != serverGeneration) {
-        extEntry = AddExtension(PANORAMIX_PROTOCOL_NAME, 0, 0,
-                                ProcPseudoramiXDispatch,
-                                SProcPseudoramiXDispatch,
-                                PseudoramiXResetProc,
-                                StandardMinorOpcode);
-        if (!extEntry) {
-            ErrorF("PseudoramiXExtensionInit(): AddExtension failed\n");
-        }
-        else {
-            pseudoramiXGeneration = serverGeneration;
-            success = TRUE;
-        }
-    }
-
-    if (!success) {
-        ErrorF("%s Extension (PseudoramiX) failed to initialize\n",
-               PANORAMIX_PROTOCOL_NAME);
-        return;
-    }
-}
-
-void
-PseudoramiXResetScreens(void)
-{
-    TRACE;
-
-    pseudoramiXNumScreens = 0;
-}
-
-static void
-PseudoramiXResetProc(ExtensionEntry *extEntry)
-{
-    TRACE;
-
-    PseudoramiXResetScreens();
-}
-
-// was PanoramiX
-static int
-ProcPseudoramiXQueryVersion(ClientPtr client)
-{
-    TRACE;
-
-    return ProcPanoramiXQueryVersion(client);
-}
-
-// was PanoramiX
-static int
-ProcPseudoramiXGetState(ClientPtr client)
-{
-    REQUEST(xPanoramiXGetStateReq);
-    WindowPtr pWin;
-    xPanoramiXGetStateReply rep;
-    register int rc;
-
-    TRACE;
-
-    REQUEST_SIZE_MATCH(xPanoramiXGetStateReq);
-    rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess);
-    if (rc != Success)
-        return rc;
-
-    rep.type = X_Reply;
-    rep.length = 0;
-    rep.sequenceNumber = client->sequence;
-    rep.state = !noPseudoramiXExtension;
-    rep.window = stuff->window;
-    if (client->swapped) {
-        swaps(&rep.sequenceNumber);
-        swapl(&rep.length);
-        swapl(&rep.window);
-    }
-    WriteToClient(client, sizeof(xPanoramiXGetStateReply),&rep);
-    return Success;
-}
-
-// was PanoramiX
-static int
-ProcPseudoramiXGetScreenCount(ClientPtr client)
-{
-    REQUEST(xPanoramiXGetScreenCountReq);
-    WindowPtr pWin;
-    xPanoramiXGetScreenCountReply rep;
-    register int rc;
-
-    TRACE;
-
-    REQUEST_SIZE_MATCH(xPanoramiXGetScreenCountReq);
-    rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess);
-    if (rc != Success)
-        return rc;
-
-    rep.type = X_Reply;
-    rep.length = 0;
-    rep.sequenceNumber = client->sequence;
-    rep.ScreenCount = pseudoramiXNumScreens;
-    rep.window = stuff->window;
-    if (client->swapped) {
-        swaps(&rep.sequenceNumber);
-        swapl(&rep.length);
-        swapl(&rep.window);
-    }
-    WriteToClient(client, sizeof(xPanoramiXGetScreenCountReply),&rep);
-    return Success;
-}
-
-// was PanoramiX
-static int
-ProcPseudoramiXGetScreenSize(ClientPtr client)
-{
-    REQUEST(xPanoramiXGetScreenSizeReq);
-    WindowPtr pWin;
-    xPanoramiXGetScreenSizeReply rep;
-    register int rc;
-
-    TRACE;
-
-    if (stuff->screen >= pseudoramiXNumScreens)
-      return BadMatch;
-
-    REQUEST_SIZE_MATCH(xPanoramiXGetScreenSizeReq);
-    rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess);
-    if (rc != Success)
-        return rc;
-
-    rep.type = X_Reply;
-    rep.length = 0;
-    rep.sequenceNumber = client->sequence;
-    /* screen dimensions */
-    rep.width = pseudoramiXScreens[stuff->screen].w;
-    // was screenInfo.screens[stuff->screen]->width;
-    rep.height = pseudoramiXScreens[stuff->screen].h;
-    // was screenInfo.screens[stuff->screen]->height;
-    rep.window = stuff->window;
-    rep.screen = stuff->screen;
-    if (client->swapped) {
-        swaps(&rep.sequenceNumber);
-        swapl(&rep.length);
-        swapl(&rep.width);
-        swapl(&rep.height);
-        swapl(&rep.window);
-        swapl(&rep.screen);
-    }
-    WriteToClient(client, sizeof(xPanoramiXGetScreenSizeReply),&rep);
-    return Success;
-}
-
-// was Xinerama
-static int
-ProcPseudoramiXIsActive(ClientPtr client)
-{
-    /* REQUEST(xXineramaIsActiveReq); */
-    xXineramaIsActiveReply rep;
-
-    TRACE;
-
-    REQUEST_SIZE_MATCH(xXineramaIsActiveReq);
-
-    rep.type = X_Reply;
-    rep.length = 0;
-    rep.sequenceNumber = client->sequence;
-    rep.state = !noPseudoramiXExtension;
-    if (client->swapped) {
-        swaps(&rep.sequenceNumber);
-        swapl(&rep.length);
-        swapl(&rep.state);
-    }
-    WriteToClient(client, sizeof(xXineramaIsActiveReply),&rep);
-    return Success;
-}
-
-// was Xinerama
-static int
-ProcPseudoramiXQueryScreens(ClientPtr client)
-{
-    /* REQUEST(xXineramaQueryScreensReq); */
-    xXineramaQueryScreensReply rep;
-
-    DEBUG_LOG("noPseudoramiXExtension=%d, pseudoramiXNumScreens=%d\n",
-              noPseudoramiXExtension,
-              pseudoramiXNumScreens);
-
-    REQUEST_SIZE_MATCH(xXineramaQueryScreensReq);
-
-    rep.type = X_Reply;
-    rep.sequenceNumber = client->sequence;
-    rep.number = noPseudoramiXExtension ? 0 : pseudoramiXNumScreens;
-    rep.length = bytes_to_int32(rep.number * sz_XineramaScreenInfo);
-    if (client->swapped) {
-        swaps(&rep.sequenceNumber);
-        swapl(&rep.length);
-        swapl(&rep.number);
-    }
-    WriteToClient(client, sizeof(xXineramaQueryScreensReply),&rep);
-
-    if (!noPseudoramiXExtension) {
-        xXineramaScreenInfo scratch;
-        int i;
-
-        for (i = 0; i < pseudoramiXNumScreens; i++) {
-            scratch.x_org = pseudoramiXScreens[i].x;
-            scratch.y_org = pseudoramiXScreens[i].y;
-            scratch.width = pseudoramiXScreens[i].w;
-            scratch.height = pseudoramiXScreens[i].h;
-
-            if (client->swapped) {
-                swaps(&scratch.x_org);
-                swaps(&scratch.y_org);
-                swaps(&scratch.width);
-                swaps(&scratch.height);
-            }
-            WriteToClient(client, sz_XineramaScreenInfo,&scratch);
-        }
-    }
-
-    return Success;
-}
-
-// was PanoramiX
-static int
-ProcPseudoramiXDispatch(ClientPtr client)
-{
-    REQUEST(xReq);
-    TRACE;
-    switch (stuff->data) {
-    case X_PanoramiXQueryVersion:
-        return ProcPseudoramiXQueryVersion(client);
-
-    case X_PanoramiXGetState:
-        return ProcPseudoramiXGetState(client);
-
-    case X_PanoramiXGetScreenCount:
-        return ProcPseudoramiXGetScreenCount(client);
-
-    case X_PanoramiXGetScreenSize:
-        return ProcPseudoramiXGetScreenSize(client);
-
-    case X_XineramaIsActive:
-        return ProcPseudoramiXIsActive(client);
-
-    case X_XineramaQueryScreens:
-        return ProcPseudoramiXQueryScreens(client);
-    }
-    return BadRequest;
-}
-
-static int
-SProcPseudoramiXQueryVersion(ClientPtr client)
-{
-    REQUEST(xPanoramiXQueryVersionReq);
-
-    TRACE;
-
-    swaps(&stuff->length);
-    REQUEST_SIZE_MATCH(xPanoramiXQueryVersionReq);
-    return ProcPseudoramiXQueryVersion(client);
-}
-
-static int
-SProcPseudoramiXGetState(ClientPtr client)
-{
-    REQUEST(xPanoramiXGetStateReq);
-
-    TRACE;
-
-    swaps(&stuff->length);
-    REQUEST_SIZE_MATCH(xPanoramiXGetStateReq);
-    return ProcPseudoramiXGetState(client);
-}
-
-static int
-SProcPseudoramiXGetScreenCount(ClientPtr client)
-{
-    REQUEST(xPanoramiXGetScreenCountReq);
-
-    TRACE;
-
-    swaps(&stuff->length);
-    REQUEST_SIZE_MATCH(xPanoramiXGetScreenCountReq);
-    return ProcPseudoramiXGetScreenCount(client);
-}
-
-static int
-SProcPseudoramiXGetScreenSize(ClientPtr client)
-{
-    REQUEST(xPanoramiXGetScreenSizeReq);
-
-    TRACE;
-
-    swaps(&stuff->length);
-    REQUEST_SIZE_MATCH(xPanoramiXGetScreenSizeReq);
-    return ProcPseudoramiXGetScreenSize(client);
-}
-
-static int
-SProcPseudoramiXIsActive(ClientPtr client)
-{
-    REQUEST(xXineramaIsActiveReq);
-
-    TRACE;
-
-    swaps(&stuff->length);
-    REQUEST_SIZE_MATCH(xXineramaIsActiveReq);
-    return ProcPseudoramiXIsActive(client);
-}
-
-static int
-SProcPseudoramiXQueryScreens(ClientPtr client)
-{
-    REQUEST(xXineramaQueryScreensReq);
-
-    TRACE;
-
-    swaps(&stuff->length);
-    REQUEST_SIZE_MATCH(xXineramaQueryScreensReq);
-    return ProcPseudoramiXQueryScreens(client);
-}
-
-static int
-SProcPseudoramiXDispatch(ClientPtr client)
-{
-    REQUEST(xReq);
-
-    TRACE;
-
-    switch (stuff->data) {
-    case X_PanoramiXQueryVersion:
-        return SProcPseudoramiXQueryVersion(client);
-
-    case X_PanoramiXGetState:
-        return SProcPseudoramiXGetState(client);
-
-    case X_PanoramiXGetScreenCount:
-        return SProcPseudoramiXGetScreenCount(client);
-
-    case X_PanoramiXGetScreenSize:
-        return SProcPseudoramiXGetScreenSize(client);
-
-    case X_XineramaIsActive:
-        return SProcPseudoramiXIsActive(client);
-
-    case X_XineramaQueryScreens:
-        return SProcPseudoramiXQueryScreens(client);
-    }
-    return BadRequest;
-}
diff --git a/hw/xquartz/pseudoramiX.h b/hw/xquartz/pseudoramiX.h
deleted file mode 100644
index f063919..0000000
--- a/hw/xquartz/pseudoramiX.h
+++ /dev/null
@@ -1,10 +0,0 @@
-/*
- * Minimal implementation of PanoramiX/Xinerama
- */
-
-extern int noPseudoramiXExtension;
-
-void
-PseudoramiXAddScreen(int x, int y, int w, int h);
-void
-PseudoramiXResetScreens(void);
diff --git a/hw/xwin/Makefile.am b/hw/xwin/Makefile.am
index 831e7dc..c700695 100644
--- a/hw/xwin/Makefile.am
+++ b/hw/xwin/Makefile.am
@@ -153,6 +153,7 @@ XWin_SOURCES = $(SRCS)
 AM_CPPFLAGS = -I$(top_srcdir)/miext/rootless
 
 XWIN_SYS_LIBS += -ldxguid
+XWIN_LIBS += 	$(top_builddir)/pseudoramiX/libPseudoramiX.la
 
 XWin_DEPENDENCIES = $(MULTIWINDOWEXTWM_LIBS) $(XWIN_GLX_LIBS) $(XWIN_LIBS) $(XSERVER_LIBS)
 XWin_LDADD = $(MULTIWINDOW_LIBS) $(MULTIWINDOWEXTWM_LIBS) $(XWIN_GLX_LIBS) $(XWIN_GLX_LINK_FLAGS) $(XWIN_LIBS) $(MAIN_LIB) $(XSERVER_LIBS) $(XSERVER_SYS_LIBS) $(XWIN_SYS_LIBS)
diff --git a/pseudoramiX/Makefile.am b/pseudoramiX/Makefile.am
new file mode 100644
index 0000000..17b664b
--- /dev/null
+++ b/pseudoramiX/Makefile.am
@@ -0,0 +1,7 @@
+# Fake Xinerama extension
+
+AM_CFLAGS = $(DIX_CFLAGS)
+
+noinst_LTLIBRARIES = libPseudoramiX.la
+
+libPseudoramiX_la_SOURCES = pseudoramiX.c pseudoramiX.h
diff --git a/pseudoramiX/pseudoramiX.c b/pseudoramiX/pseudoramiX.c
new file mode 100644
index 0000000..23dbc73
--- /dev/null
+++ b/pseudoramiX/pseudoramiX.c
@@ -0,0 +1,516 @@
+/*
+ * Minimal implementation of PanoramiX/Xinerama
+ *
+ * This is used in rootless mode where the underlying window server
+ * already provides an abstracted view of multiple screens as one
+ * large screen area.
+ *
+ * This code is largely based on panoramiX.c, which contains the
+ * following copyright notice:
+ */
+/*****************************************************************
+   Copyright (c) 1991, 1997 Digital Equipment Corporation, Maynard, Massachusetts.
+   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.
+
+   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
+   DIGITAL EQUIPMENT CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES, INCLUDING,
+   BUT NOT LIMITED TO CONSEQUENTIAL OR INCIDENTAL 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.
+
+   Except as contained in this notice, the name of Digital Equipment Corporation
+   shall not be used in advertising or otherwise to promote the sale, use or other
+   dealings in this Software without prior written authorization from Digital
+   Equipment Corporation.
+ ******************************************************************/
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include "pseudoramiX.h"
+#include "extnsionst.h"
+#include "extinit.h"
+#include "dixstruct.h"
+#include "window.h"
+#include <X11/extensions/panoramiXproto.h>
+#include "globals.h"
+
+#define TRACE PseudoramiXTrace("TRACE " __FILE__ ":%s",__FUNCTION__)
+#define DEBUG_LOG PseudoramiXDebug
+
+Bool noPseudoramiXExtension = FALSE;
+
+extern int
+ProcPanoramiXQueryVersion(ClientPtr client);
+
+static void
+PseudoramiXResetProc(ExtensionEntry *extEntry);
+
+static int
+ProcPseudoramiXQueryVersion(ClientPtr client);
+static int
+ProcPseudoramiXGetState(ClientPtr client);
+static int
+ProcPseudoramiXGetScreenCount(ClientPtr client);
+static int
+ProcPseudoramiXGetScreenSize(ClientPtr client);
+static int
+ProcPseudoramiXIsActive(ClientPtr client);
+static int
+ProcPseudoramiXQueryScreens(ClientPtr client);
+static int
+ProcPseudoramiXDispatch(ClientPtr client);
+
+static int
+SProcPseudoramiXQueryVersion(ClientPtr client);
+static int
+SProcPseudoramiXGetState(ClientPtr client);
+static int
+SProcPseudoramiXGetScreenCount(ClientPtr client);
+static int
+SProcPseudoramiXGetScreenSize(ClientPtr client);
+static int
+SProcPseudoramiXIsActive(ClientPtr client);
+static int
+SProcPseudoramiXQueryScreens(ClientPtr client);
+static int
+SProcPseudoramiXDispatch(ClientPtr client);
+
+typedef struct {
+    int x;
+    int y;
+    int w;
+    int h;
+} PseudoramiXScreenRec;
+
+static PseudoramiXScreenRec *pseudoramiXScreens = NULL;
+static int pseudoramiXScreensAllocated = 0;
+static int pseudoramiXNumScreens = 0;
+static unsigned long pseudoramiXGeneration = 0;
+
+static void
+PseudoramiXTrace(const char *format, ...)
+{
+    va_list ap;
+
+    va_start(ap, format);
+    LogVMessageVerb(X_NONE, 10, format, ap);
+    va_end(ap);
+}
+
+static void
+PseudoramiXDebug(const char *format, ...)
+{
+    va_list ap;
+
+    va_start(ap, format);
+    LogVMessageVerb(X_NONE, 3, format, ap);
+    va_end(ap);
+}
+
+// Add a PseudoramiX screen.
+// The rest of the X server will know nothing about this screen.
+// Can be called before or after extension init.
+// Screens must be re-added once per generation.
+void
+PseudoramiXAddScreen(int x, int y, int w, int h)
+{
+    PseudoramiXScreenRec *s;
+
+    if (noPseudoramiXExtension) return;
+
+    if (pseudoramiXNumScreens == pseudoramiXScreensAllocated) {
+        pseudoramiXScreensAllocated += pseudoramiXScreensAllocated + 1;
+        pseudoramiXScreens = realloc(pseudoramiXScreens,
+                                     pseudoramiXScreensAllocated *
+                                     sizeof(PseudoramiXScreenRec));
+    }
+
+    DEBUG_LOG("x: %d, y: %d, w: %d, h: %d\n", x, y, w, h);
+
+    s = &pseudoramiXScreens[pseudoramiXNumScreens++];
+    s->x = x;
+    s->y = y;
+    s->w = w;
+    s->h = h;
+}
+
+// Initialize PseudoramiX.
+// Copied from PanoramiXExtensionInit
+void
+PseudoramiXExtensionInit(void)
+{
+    Bool success = FALSE;
+    ExtensionEntry      *extEntry;
+
+    if (noPseudoramiXExtension) return;
+
+    TRACE;
+
+    /* Even with only one screen we need to enable PseudoramiX to allow
+       dynamic screen configuration changes. */
+#if 0
+    if (pseudoramiXNumScreens == 1) {
+        // Only one screen - disable Xinerama extension.
+        noPseudoramiXExtension = TRUE;
+        return;
+    }
+#endif
+
+    if (pseudoramiXGeneration != serverGeneration) {
+        extEntry = AddExtension(PANORAMIX_PROTOCOL_NAME, 0, 0,
+                                ProcPseudoramiXDispatch,
+                                SProcPseudoramiXDispatch,
+                                PseudoramiXResetProc,
+                                StandardMinorOpcode);
+        if (!extEntry) {
+            ErrorF("PseudoramiXExtensionInit(): AddExtension failed\n");
+        }
+        else {
+            pseudoramiXGeneration = serverGeneration;
+            success = TRUE;
+        }
+    }
+
+    if (!success) {
+        ErrorF("%s Extension (PseudoramiX) failed to initialize\n",
+               PANORAMIX_PROTOCOL_NAME);
+        return;
+    }
+}
+
+void
+PseudoramiXResetScreens(void)
+{
+    TRACE;
+
+    pseudoramiXNumScreens = 0;
+}
+
+static void
+PseudoramiXResetProc(ExtensionEntry *extEntry)
+{
+    TRACE;
+
+    PseudoramiXResetScreens();
+}
+
+// was PanoramiX
+static int
+ProcPseudoramiXQueryVersion(ClientPtr client)
+{
+    TRACE;
+
+    return ProcPanoramiXQueryVersion(client);
+}
+
+// was PanoramiX
+static int
+ProcPseudoramiXGetState(ClientPtr client)
+{
+    REQUEST(xPanoramiXGetStateReq);
+    WindowPtr pWin;
+    xPanoramiXGetStateReply rep;
+    register int rc;
+
+    TRACE;
+
+    REQUEST_SIZE_MATCH(xPanoramiXGetStateReq);
+    rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess);
+    if (rc != Success)
+        return rc;
+
+    rep.type = X_Reply;
+    rep.length = 0;
+    rep.sequenceNumber = client->sequence;
+    rep.state = !noPseudoramiXExtension;
+    rep.window = stuff->window;
+    if (client->swapped) {
+        swaps(&rep.sequenceNumber);
+        swapl(&rep.length);
+        swapl(&rep.window);
+    }
+    WriteToClient(client, sizeof(xPanoramiXGetStateReply),&rep);
+    return Success;
+}
+
+// was PanoramiX
+static int
+ProcPseudoramiXGetScreenCount(ClientPtr client)
+{
+    REQUEST(xPanoramiXGetScreenCountReq);
+    WindowPtr pWin;
+    xPanoramiXGetScreenCountReply rep;
+    register int rc;
+
+    TRACE;
+
+    REQUEST_SIZE_MATCH(xPanoramiXGetScreenCountReq);
+    rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess);
+    if (rc != Success)
+        return rc;
+
+    rep.type = X_Reply;
+    rep.length = 0;
+    rep.sequenceNumber = client->sequence;
+    rep.ScreenCount = pseudoramiXNumScreens;
+    rep.window = stuff->window;
+    if (client->swapped) {
+        swaps(&rep.sequenceNumber);
+        swapl(&rep.length);
+        swapl(&rep.window);
+    }
+    WriteToClient(client, sizeof(xPanoramiXGetScreenCountReply),&rep);
+    return Success;
+}
+
+// was PanoramiX
+static int
+ProcPseudoramiXGetScreenSize(ClientPtr client)
+{
+    REQUEST(xPanoramiXGetScreenSizeReq);
+    WindowPtr pWin;
+    xPanoramiXGetScreenSizeReply rep;
+    register int rc;
+
+    TRACE;
+
+    if (stuff->screen >= pseudoramiXNumScreens)
+      return BadMatch;
+
+    REQUEST_SIZE_MATCH(xPanoramiXGetScreenSizeReq);
+    rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess);
+    if (rc != Success)
+        return rc;
+
+    rep.type = X_Reply;
+    rep.length = 0;
+    rep.sequenceNumber = client->sequence;
+    /* screen dimensions */
+    rep.width = pseudoramiXScreens[stuff->screen].w;
+    // was screenInfo.screens[stuff->screen]->width;
+    rep.height = pseudoramiXScreens[stuff->screen].h;
+    // was screenInfo.screens[stuff->screen]->height;
+    rep.window = stuff->window;
+    rep.screen = stuff->screen;
+    if (client->swapped) {
+        swaps(&rep.sequenceNumber);
+        swapl(&rep.length);
+        swapl(&rep.width);
+        swapl(&rep.height);
+        swapl(&rep.window);
+        swapl(&rep.screen);
+    }
+    WriteToClient(client, sizeof(xPanoramiXGetScreenSizeReply),&rep);
+    return Success;
+}
+
+// was Xinerama
+static int
+ProcPseudoramiXIsActive(ClientPtr client)
+{
+    /* REQUEST(xXineramaIsActiveReq); */
+    xXineramaIsActiveReply rep;
+
+    TRACE;
+
+    REQUEST_SIZE_MATCH(xXineramaIsActiveReq);
+
+    rep.type = X_Reply;
+    rep.length = 0;
+    rep.sequenceNumber = client->sequence;
+    rep.state = !noPseudoramiXExtension;
+    if (client->swapped) {
+        swaps(&rep.sequenceNumber);
+        swapl(&rep.length);
+        swapl(&rep.state);
+    }
+    WriteToClient(client, sizeof(xXineramaIsActiveReply),&rep);
+    return Success;
+}
+
+// was Xinerama
+static int
+ProcPseudoramiXQueryScreens(ClientPtr client)
+{
+    /* REQUEST(xXineramaQueryScreensReq); */
+    xXineramaQueryScreensReply rep;
+
+    DEBUG_LOG("noPseudoramiXExtension=%d, pseudoramiXNumScreens=%d\n",
+              noPseudoramiXExtension,
+              pseudoramiXNumScreens);
+
+    REQUEST_SIZE_MATCH(xXineramaQueryScreensReq);
+
+    rep.type = X_Reply;
+    rep.sequenceNumber = client->sequence;
+    rep.number = noPseudoramiXExtension ? 0 : pseudoramiXNumScreens;
+    rep.length = bytes_to_int32(rep.number * sz_XineramaScreenInfo);
+    if (client->swapped) {
+        swaps(&rep.sequenceNumber);
+        swapl(&rep.length);
+        swapl(&rep.number);
+    }
+    WriteToClient(client, sizeof(xXineramaQueryScreensReply),&rep);
+
+    if (!noPseudoramiXExtension) {
+        xXineramaScreenInfo scratch;
+        int i;
+
+        for (i = 0; i < pseudoramiXNumScreens; i++) {
+            scratch.x_org = pseudoramiXScreens[i].x;
+            scratch.y_org = pseudoramiXScreens[i].y;
+            scratch.width = pseudoramiXScreens[i].w;
+            scratch.height = pseudoramiXScreens[i].h;
+
+            if (client->swapped) {
+                swaps(&scratch.x_org);
+                swaps(&scratch.y_org);
+                swaps(&scratch.width);
+                swaps(&scratch.height);
+            }
+            WriteToClient(client, sz_XineramaScreenInfo,&scratch);
+        }
+    }
+
+    return Success;
+}
+
+// was PanoramiX
+static int
+ProcPseudoramiXDispatch(ClientPtr client)
+{
+    REQUEST(xReq);
+    TRACE;
+    switch (stuff->data) {
+    case X_PanoramiXQueryVersion:
+        return ProcPseudoramiXQueryVersion(client);
+
+    case X_PanoramiXGetState:
+        return ProcPseudoramiXGetState(client);
+
+    case X_PanoramiXGetScreenCount:
+        return ProcPseudoramiXGetScreenCount(client);
+
+    case X_PanoramiXGetScreenSize:
+        return ProcPseudoramiXGetScreenSize(client);
+
+    case X_XineramaIsActive:
+        return ProcPseudoramiXIsActive(client);
+
+    case X_XineramaQueryScreens:
+        return ProcPseudoramiXQueryScreens(client);
+    }
+    return BadRequest;
+}
+
+static int
+SProcPseudoramiXQueryVersion(ClientPtr client)
+{
+    REQUEST(xPanoramiXQueryVersionReq);
+
+    TRACE;
+
+    swaps(&stuff->length);
+    REQUEST_SIZE_MATCH(xPanoramiXQueryVersionReq);
+    return ProcPseudoramiXQueryVersion(client);
+}
+
+static int
+SProcPseudoramiXGetState(ClientPtr client)
+{
+    REQUEST(xPanoramiXGetStateReq);
+
+    TRACE;
+
+    swaps(&stuff->length);
+    REQUEST_SIZE_MATCH(xPanoramiXGetStateReq);
+    return ProcPseudoramiXGetState(client);
+}
+
+static int
+SProcPseudoramiXGetScreenCount(ClientPtr client)
+{
+    REQUEST(xPanoramiXGetScreenCountReq);
+
+    TRACE;
+
+    swaps(&stuff->length);
+    REQUEST_SIZE_MATCH(xPanoramiXGetScreenCountReq);
+    return ProcPseudoramiXGetScreenCount(client);
+}
+
+static int
+SProcPseudoramiXGetScreenSize(ClientPtr client)
+{
+    REQUEST(xPanoramiXGetScreenSizeReq);
+
+    TRACE;
+
+    swaps(&stuff->length);
+    REQUEST_SIZE_MATCH(xPanoramiXGetScreenSizeReq);
+    return ProcPseudoramiXGetScreenSize(client);
+}
+
+static int
+SProcPseudoramiXIsActive(ClientPtr client)
+{
+    REQUEST(xXineramaIsActiveReq);
+
+    TRACE;
+
+    swaps(&stuff->length);
+    REQUEST_SIZE_MATCH(xXineramaIsActiveReq);
+    return ProcPseudoramiXIsActive(client);
+}
+
+static int
+SProcPseudoramiXQueryScreens(ClientPtr client)
+{
+    REQUEST(xXineramaQueryScreensReq);
+
+    TRACE;
+
+    swaps(&stuff->length);
+    REQUEST_SIZE_MATCH(xXineramaQueryScreensReq);
+    return ProcPseudoramiXQueryScreens(client);
+}
+
+static int
+SProcPseudoramiXDispatch(ClientPtr client)
+{
+    REQUEST(xReq);
+
+    TRACE;
+
+    switch (stuff->data) {
+    case X_PanoramiXQueryVersion:
+        return SProcPseudoramiXQueryVersion(client);
+
+    case X_PanoramiXGetState:
+        return SProcPseudoramiXGetState(client);
+
+    case X_PanoramiXGetScreenCount:
+        return SProcPseudoramiXGetScreenCount(client);
+
+    case X_PanoramiXGetScreenSize:
+        return SProcPseudoramiXGetScreenSize(client);
+
+    case X_XineramaIsActive:
+        return SProcPseudoramiXIsActive(client);
+
+    case X_XineramaQueryScreens:
+        return SProcPseudoramiXQueryScreens(client);
+    }
+    return BadRequest;
+}
diff --git a/pseudoramiX/pseudoramiX.h b/pseudoramiX/pseudoramiX.h
new file mode 100644
index 0000000..f063919
--- /dev/null
+++ b/pseudoramiX/pseudoramiX.h
@@ -0,0 +1,10 @@
+/*
+ * Minimal implementation of PanoramiX/Xinerama
+ */
+
+extern int noPseudoramiXExtension;
+
+void
+PseudoramiXAddScreen(int x, int y, int w, int h);
+void
+PseudoramiXResetScreens(void);
commit ce0217b98261dcf8b20cfb743831965dda1950ec
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Sat Aug 10 12:35:55 2013 +0100

    hw/xwin: Fix winglobals.h for MinGW64 build
    
    Include pthread.h in winglobals.h to fix build with latest MinGW64 headers
    
    In file included from
    winmultiwindowicons.c:47:0:
    winglobals.h:92:1: error: unknown type name ‘pthread_mutex_t’
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>
    Reviewed-by: Marc Haesen <marha at users.sourceforge.net>

diff --git a/hw/xwin/winglobals.h b/hw/xwin/winglobals.h
index e7e2f7e..4faba9e 100644
--- a/hw/xwin/winglobals.h
+++ b/hw/xwin/winglobals.h
@@ -30,6 +30,8 @@
 #include <xwin-config.h>
 #endif
 
+#include <pthread.h>
+
 /*
  * References to external symbols
  */
commit b27756dbe6a1be4633ec47a8fe92a4c217f68f93
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Sun Aug 11 12:15:11 2013 +0100

    hw/xwin: Fix inclusion of shlobj.h in MinGW64 build
    
    Fix build with latest MinGW64 headers by wrapping Status type in shlobj.h as well
    
    In file included from InitOutput.c:51:0:
    /usr/i686-w64-mingw32/sys-root/mingw/include/shlobj.h:1231:44: error: expected identifier or ‘(’ before ‘int’
    /usr/i686-w64-mingw32/sys-root/mingw/include/shlobj.h:1248:44: error: expected identifier or ‘(’ before ‘int’
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>
    Reviewed-by: Marc Haesen <marha at users.sourceforge.net>

diff --git a/hw/xwin/InitOutput.c b/hw/xwin/InitOutput.c
index d6b5e4f..b05ca27 100644
--- a/hw/xwin/InitOutput.c
+++ b/hw/xwin/InitOutput.c
@@ -48,7 +48,11 @@ from The Open Group.
 #include "xkbsrv.h"
 #endif
 #ifdef RELOCATE_PROJECTROOT
+#pragma push_macro("Status")
+#undef Status
+#define Status wStatus
 #include <shlobj.h>
+#pragma pop_macro("Status")
 typedef WINAPI HRESULT(*SHGETFOLDERPATHPROC) (HWND hwndOwner,
                                               int nFolder,
                                               HANDLE hToken,
commit 94d4e29aedc69431fa9b299ca1b67947173d7a24
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Aug 26 15:51:46 2013 +1000

    Xi: allow for XIAllowEvent requests larger than XI < 2.2 size (#68554)
    
    XIAllowEvents changed length in XI 2.2 (for the touchid). A bug in libXi
    causes libXi to always use the new request length if the server supports
    2.2, regardless of the client's XIQueryVersion request.
    
    The server takes the client's XIQueryVersion request into account though,
    resulting in a BadLength error if a 2.[0,1] client calls XIAllowEvents on a
    XI 2.2+ server.
    
    Can't fix this in libXi, so work around this in the server.
    
    X.Org Bug 68554 <http://bugs.freedesktop.org/show_bug.cgi?id=68554>
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Adam Jackson <ajax at redhat.com>

diff --git a/Xi/xiallowev.c b/Xi/xiallowev.c
index 62a0727..ebef233 100644
--- a/Xi/xiallowev.c
+++ b/Xi/xiallowev.c
@@ -81,7 +81,7 @@ ProcXIAllowEvents(ClientPtr client)
         have_xi22 = TRUE;
     }
     else {
-        REQUEST_SIZE_MATCH(xXIAllowEventsReq);
+        REQUEST_AT_LEAST_SIZE(xXIAllowEventsReq);
     }
 
     ret = dixLookupDevice(&dev, stuff->deviceid, client, DixGetAttrAccess);
commit 82939e02392cbb880313fe92957091ff89ce2f2b
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Aug 16 15:30:59 2013 +1000

    dix: check for grab type before checking XI2 mask
    
    if the grab type isn't XI2, grab->xi2mask is random. That random data may
    have the enter/leave mask set, leading to events sent to the client that the
    client can't handler.
    
    Source of these errors:
      _xgeWireToEvent: Unknown extension 131, this should never happen.
    
    Simplest reproducer:
       Start Xephyr, press button inside window, move out. As the pointer leaves
       the Xephyr window, the errors appear.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Adam Jackson <ajax at redhat.com>

diff --git a/dix/events.c b/dix/events.c
index 4e6a175..086601a 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -4653,7 +4653,7 @@ DeviceEnterLeaveEvent(DeviceIntPtr mouse,
 
     filter = GetEventFilter(mouse, (xEvent *) event);
 
-    if (grab) {
+    if (grab && grab->type == XI2) {
         Mask mask;
 
         mask = xi2mask_isset(grab->xi2mask, mouse, type);
commit 16894df1ffb6fe21bf723dd954578e8d934799ca
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Aug 16 10:55:09 2013 +1000

    Xi: replace loop with memset
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Adam Jackson <ajax at redhat.com>

diff --git a/Xi/grabdev.c b/Xi/grabdev.c
index 443ef56..9c6c429 100644
--- a/Xi/grabdev.c
+++ b/Xi/grabdev.c
@@ -175,10 +175,7 @@ CreateMaskFromList(ClientPtr client, XEventClass * list, int count,
     int device;
     DeviceIntPtr tdev;
 
-    for (i = 0; i < EMASKSIZE; i++) {
-        mask[i].mask = 0;
-        mask[i].dev = NULL;
-    }
+    memset(mask, 0, EMASKSIZE * sizeof(struct tmask));
 
     for (i = 0; i < count; i++, list++) {
         device = *list >> 8;
commit 8f2292b683f591052da2fe94fb3831a3c9a5aa61
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Aug 16 11:05:49 2013 +1000

    include: wrap EMASKSIZE in parentheses
    
    Otherwise things like EMASKSIZE * foo will yield interesting results.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Adam Jackson <ajax at redhat.com>

diff --git a/include/inputstr.h b/include/inputstr.h
index 2da72c1..dc36c5d 100644
--- a/include/inputstr.h
+++ b/include/inputstr.h
@@ -65,7 +65,7 @@ extern _X_EXPORT int CountBits(const uint8_t * mask, int len);
 #define SameClient(obj,client) \
 	(CLIENT_BITS((obj)->resource) == (client)->clientAsMask)
 
-#define EMASKSIZE	MAXDEVICES + 2
+#define EMASKSIZE	(MAXDEVICES + 2)
 
 /* This is the last XI2 event supported by the server. If you add
  * events to the protocol, the server will not support these events until
commit d803f296c616ccf55711cf0af9e7d3eae2edda16
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Aug 23 09:04:01 2013 +1000

    test: fix the gcc diagnostics pragma
    
    pop without push restores the commandline options. The proper way is to
    push, then ignore, then pop.
    
    And while we're at it, change the pop argument to a comment - pop ignores
    the argument, but be proper about it.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/test/signal-logging.c b/test/signal-logging.c
index f6bc85c..a03c5ac 100644
--- a/test/signal-logging.c
+++ b/test/signal-logging.c
@@ -150,6 +150,7 @@ number_formatting(void)
         assert(check_float_format_test(float_tests[i]));
 }
 
+#pragma GCC diagnostic push
 #pragma GCC diagnostic ignored "-Wformat-security"
 static void logging_format(void)
 {
@@ -378,7 +379,7 @@ static void logging_format(void)
 
 #undef read_log_msg
 }
-#pragma GCC diagnostic pop "-Wformat-security"
+#pragma GCC diagnostic pop /* "-Wformat-security" */
 
 int
 main(int argc, char **argv)
commit 05ea6307fa4f0bee3d3bf536396059f3906791a0
Author: Egbert Eich <eich at freedesktop.org>
Date:   Fri Aug 16 19:52:16 2013 +0200

    DIX/Xi: Pass correct client to CheckDeviceGrabAndHintWindow()
    
    If we have a client which has registered for a DeviceButton grab
    be sure to pass this to CheckDeviceGrabAndHintWindow(). Since the
    order of clients is arbitrary there is no guarantee that the last
    client in the list is the one that belongs to this class.
    
    Signed-off-by: Egbert Eich <eich at freedesktop.org>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/events.c b/dix/events.c
index ed3138d..4e6a175 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -2105,6 +2105,7 @@ DeliverEventToInputClients(DeviceIntPtr dev, InputClients * inputclients,
 {
     int attempt;
     enum EventDeliveryState rc = EVENT_NOT_DELIVERED;
+    Bool have_device_button_grab_class_client = FALSE;
 
     for (; inputclients; inputclients = inputclients->next) {
         Mask mask;
@@ -2124,13 +2125,21 @@ DeliverEventToInputClients(DeviceIntPtr dev, InputClients * inputclients,
                                             events, count,
                                             mask, filter, grab))) {
             if (attempt > 0) {
-                rc = EVENT_DELIVERED;
-                *client_return = client;
-                *mask_return = mask;
-                /* Success overrides non-success, so if we've been
-                 * successful on one client, return that */
-            }
-            else if (rc == EVENT_NOT_DELIVERED)
+                /*
+                 * The order of clients is arbitrary therefore if one
+                 * client belongs to DeviceButtonGrabClass make sure to
+                 * catch it.
+                 */
+                if (!have_device_button_grab_class_client) {
+                    rc = EVENT_DELIVERED;
+                    *client_return = client;
+                    *mask_return = mask;
+                    /* Success overrides non-success, so if we've been
+                     * successful on one client, return that */
+                    if (mask & DeviceButtonGrabMask)
+                        have_device_button_grab_class_client = TRUE;
+                }
+            } else if (rc == EVENT_NOT_DELIVERED)
                 rc = EVENT_REJECTED;
         }
     }
commit e01a3f65d3e6d92f92ef2992b338cc9625bde082
Author: Eric Anholt <eric at anholt.net>
Date:   Sat Aug 17 14:50:37 2013 +0200

    ephyr: Fix warning about XID vs unsigned long * by changing function args
    
    There's no reason to pass the data back out to the caller, since the
    caller was dropping it on the floor.  The original data is a CARD32,
    so no need to mess with weird unsigned longs.
    
    Signed-off-by: Eric Anholt <eric at anholt.net>
    Reviewed-by: Julien Cristau <jcristau at debian.org>

diff --git a/hw/kdrive/ephyr/ephyrdri.c b/hw/kdrive/ephyr/ephyrdri.c
index 5055436..3a4a063 100644
--- a/hw/kdrive/ephyr/ephyrdri.c
+++ b/hw/kdrive/ephyr/ephyrdri.c
@@ -137,18 +137,19 @@ ephyrDRIGetClientDriverName(int a_screen,
 Bool
 ephyrDRICreateContext(int a_screen,
                       int a_visual_id,
-                      XID *a_returned_ctxt_id, drm_context_t * a_hw_ctxt)
+                      CARD32 ctxt_id, drm_context_t * a_hw_ctxt)
 {
     Display *dpy = hostx_get_display();
     Bool is_ok = FALSE;
     Visual v;
+    XID returned_ctxt_id = ctxt_id;
 
     EPHYR_LOG("enter. screen:%d, visual:%d\n", a_screen, a_visual_id);
     memset(&v, 0, sizeof(v));
     v.visualid = a_visual_id;
     is_ok = XF86DRICreateContext(dpy,
                                  DefaultScreen(dpy),
-                                 &v, a_returned_ctxt_id, a_hw_ctxt);
+                                 &v, &returned_ctxt_id, a_hw_ctxt);
     EPHYR_LOG("leave:%d\n", is_ok);
     return is_ok;
 }
diff --git a/hw/kdrive/ephyr/ephyrdri.h b/hw/kdrive/ephyr/ephyrdri.h
index d28910f..8f2d302 100644
--- a/hw/kdrive/ephyr/ephyrdri.h
+++ b/hw/kdrive/ephyr/ephyrdri.h
@@ -43,7 +43,7 @@ Bool ephyrDRIGetClientDriverName(int a_screen,
                                  char **a_client_driver_name);
 Bool ephyrDRICreateContext(int a_screen,
                            int a_visual_id,
-                           XID *a_returned_ctx_id, drm_context_t * a_hw_ctx);
+                           CARD32 ctx_id, drm_context_t * a_hw_ctx);
 Bool ephyrDRIDestroyContext(int a_screen, int a_context_id);
 Bool ephyrDRICreateDrawable(int a_screen,
                             int a_drawable, drm_drawable_t * a_hw_drawable);
diff --git a/hw/kdrive/ephyr/ephyrdriext.c b/hw/kdrive/ephyr/ephyrdriext.c
index 4db40e3..617ffb1 100644
--- a/hw/kdrive/ephyr/ephyrdriext.c
+++ b/hw/kdrive/ephyr/ephyrdriext.c
@@ -716,7 +716,6 @@ ProcXF86DRICreateContext(register ClientPtr client)
     ScreenPtr pScreen;
     VisualPtr visual;
     int i = 0;
-    unsigned long context_id = 0;
 
     REQUEST(xXF86DRICreateContextReq);
     REQUEST_SIZE_MATCH(xXF86DRICreateContextReq);
@@ -739,10 +738,9 @@ ProcXF86DRICreateContext(register ClientPtr client)
         return BadValue;
     }
 
-    context_id = stuff->context;
     if (!ephyrDRICreateContext(stuff->screen,
                                stuff->visual,
-                               &context_id,
+                               stuff->context,
                                (drm_context_t *) &rep.hHWContext)) {
         return BadValue;
     }
commit f1cefe020bd21c07dfcc9f204e79939499abbd35
Author: Eric Anholt <eric at anholt.net>
Date:   Sat Aug 17 14:38:08 2013 +0200

    ephyr: Drop is_ok logging.
    
    The only cases that lead to !is_ok are already EPHYR_LOG_ERROR, and it
    fixes set-but-unused compiler warnings.
    
    Signed-off-by: Eric Anholt <eric at anholt.net>
    Reviewed-by: Julien Cristau <jcristau at debian.org>

diff --git a/hw/kdrive/ephyr/ephyrdriext.c b/hw/kdrive/ephyr/ephyrdriext.c
index 144c6e1..4db40e3 100644
--- a/hw/kdrive/ephyr/ephyrdriext.c
+++ b/hw/kdrive/ephyr/ephyrdriext.c
@@ -189,7 +189,6 @@ static void
 ephyrDRIMoveWindow(WindowPtr a_win,
                    int a_x, int a_y, WindowPtr a_siblings, VTKind a_kind)
 {
-    Bool is_ok = FALSE;
     ScreenPtr screen = NULL;
     EphyrDRIScreenPrivPtr screen_priv = NULL;
     EphyrDRIWindowPrivPtr win_priv = NULL;
@@ -214,18 +213,16 @@ ephyrDRIMoveWindow(WindowPtr a_win,
     EPHYR_LOG("window: %p\n", a_win);
     if (!a_win->parent) {
         EPHYR_LOG("cannot move root window\n");
-        is_ok = TRUE;
-        goto out;
+        return;
     }
     win_priv = GET_EPHYR_DRI_WINDOW_PRIV(a_win);
     if (!win_priv) {
         EPHYR_LOG("not a DRI peered window\n");
-        is_ok = TRUE;
-        goto out;
+        return;
     }
     if (!findWindowPairFromLocal(a_win, &pair) || !pair) {
         EPHYR_LOG_ERROR("failed to get window pair\n");
-        goto out;
+        return;
     }
     /*compute position relative to parent window */
     x = a_win->drawable.x - a_win->parent->drawable.x;
@@ -237,11 +234,6 @@ ephyrDRIMoveWindow(WindowPtr a_win,
     geo.width = a_win->drawable.width;
     geo.height = a_win->drawable.height;
     hostx_set_window_geometry(pair->remote, &geo);
-    is_ok = TRUE;
-
- out:
-    EPHYR_LOG("leave. is_ok:%d\n", is_ok);
-    /*do cleanup here */
 }
 
 static Bool
@@ -297,7 +289,6 @@ ephyrDRIPositionWindow(WindowPtr a_win, int a_x, int a_y)
 static void
 ephyrDRIClipNotify(WindowPtr a_win, int a_x, int a_y)
 {
-    Bool is_ok = FALSE;
     ScreenPtr screen = NULL;
     EphyrDRIScreenPrivPtr screen_priv = NULL;
     EphyrDRIWindowPrivPtr win_priv = NULL;
@@ -323,7 +314,6 @@ ephyrDRIClipNotify(WindowPtr a_win, int a_x, int a_y)
     win_priv = GET_EPHYR_DRI_WINDOW_PRIV(a_win);
     if (!win_priv) {
         EPHYR_LOG("not a DRI peered window\n");
-        is_ok = TRUE;
         goto out;
     }
     if (!findWindowPairFromLocal(a_win, &pair) || !pair) {
@@ -343,9 +333,8 @@ ephyrDRIClipNotify(WindowPtr a_win, int a_x, int a_y)
      * push the clipping region of this window
      * to the peer window in the host
      */
-    is_ok = hostx_set_window_bounding_rectangles
+    hostx_set_window_bounding_rectangles
         (pair->remote, rects, RegionNumRects(&a_win->clipList));
-    is_ok = TRUE;
 
  out:
     free(rects);
commit 77c7a2014e3942b55c0b78308edf02eab33f2e60
Author: Eric Anholt <eric at anholt.net>
Date:   Sat Aug 17 14:36:09 2013 +0200

    kdrive: Fix const cast warnings in arguments processing.
    
    Signed-off-by: Eric Anholt <eric at anholt.net>
    Reviewed-by: Julien Cristau <jcristau at debian.org>

diff --git a/hw/kdrive/ephyr/ephyrinit.c b/hw/kdrive/ephyr/ephyrinit.c
index adacac9..9a1dd7d 100644
--- a/hw/kdrive/ephyr/ephyrinit.c
+++ b/hw/kdrive/ephyr/ephyrinit.c
@@ -45,7 +45,7 @@ extern KdPointerDriver LinuxEvdevMouseDriver;
 extern KdKeyboardDriver LinuxEvdevKeyboardDriver;
 #endif
 
-void processScreenArg(char *screen_size, char *parent_id);
+void processScreenArg(const char *screen_size, char *parent_id);
 
 void
 InitCard(char *name)
@@ -134,7 +134,7 @@ ddxUseMsg(void)
 }
 
 void
-processScreenArg(char *screen_size, char *parent_id)
+processScreenArg(const char *screen_size, char *parent_id)
 {
     KdCardInfo *card;
 
diff --git a/hw/kdrive/ephyr/os.c b/hw/kdrive/ephyr/os.c
index a2a705d..56b52d1 100644
--- a/hw/kdrive/ephyr/os.c
+++ b/hw/kdrive/ephyr/os.c
@@ -28,7 +28,7 @@
 #endif
 #include "ephyr.h"
 
-extern void processScreenArg(char *screen_size, char *parent_id);
+extern void processScreenArg(const char *screen_size, char *parent_id);
 
 static int
 EphyrInit(void)
diff --git a/hw/kdrive/src/kdrive.c b/hw/kdrive/src/kdrive.c
index 1899a27..f8949be 100644
--- a/hw/kdrive/src/kdrive.c
+++ b/hw/kdrive/src/kdrive.c
@@ -246,8 +246,8 @@ ddxGiveUp(enum ExitCode error)
 Bool kdDumbDriver;
 Bool kdSoftCursor;
 
-char *
-KdParseFindNext(char *cur, const char *delim, char *save, char *last)
+const char *
+KdParseFindNext(const char *cur, const char *delim, char *save, char *last)
 {
     while (*cur && !strchr(delim, *cur)) {
         *save++ = *cur++;
@@ -282,7 +282,7 @@ KdSubRotation(Rotation a, Rotation b)
 }
 
 void
-KdParseScreen(KdScreenInfo * screen, char *arg)
+KdParseScreen(KdScreenInfo * screen, const char *arg)
 {
     char delim;
     char save[1024];
diff --git a/hw/kdrive/src/kdrive.h b/hw/kdrive/src/kdrive.h
index 96787b6..d5d0799 100644
--- a/hw/kdrive/src/kdrive.h
+++ b/hw/kdrive/src/kdrive.h
@@ -411,13 +411,14 @@ Rotation KdAddRotation(Rotation a, Rotation b);
 Rotation KdSubRotation(Rotation a, Rotation b);
 
 void
- KdParseScreen(KdScreenInfo * screen, char *arg);
+ KdParseScreen(KdScreenInfo * screen, const char *arg);
 
-KdPointerInfo *KdParsePointer(char *arg);
+KdPointerInfo *KdParsePointer(const char *arg);
 
-KdKeyboardInfo *KdParseKeyboard(char *arg);
+KdKeyboardInfo *KdParseKeyboard(const char *arg);
 
-char *KdParseFindNext(char *cur, const char *delim, char *save, char *last);
+const char *
+KdParseFindNext(const char *cur, const char *delim, char *save, char *last);
 
 void
  KdParseRgba(char *rgba);
diff --git a/hw/kdrive/src/kinput.c b/hw/kdrive/src/kinput.c
index 3aad87a..f93830e 100644
--- a/hw/kdrive/src/kinput.c
+++ b/hw/kdrive/src/kinput.c
@@ -1086,7 +1086,7 @@ KdParseKbdOptions(KdKeyboardInfo * ki)
 }
 
 KdKeyboardInfo *
-KdParseKeyboard(char *arg)
+KdParseKeyboard(const char *arg)
 {
     char save[1024];
     char delim;
@@ -1178,7 +1178,7 @@ KdParsePointerOptions(KdPointerInfo * pi)
 }
 
 KdPointerInfo *
-KdParsePointer(char *arg)
+KdParsePointer(const char *arg)
 {
     char save[1024];
     char delim;
commit 7107937e473a3557c37d719cb100b2e9b09075dd
Author: Eric Anholt <eric at anholt.net>
Date:   Sat Aug 17 13:11:17 2013 +0200

    kdrive: Fix const cast warnings in driver name handling.
    
    Signed-off-by: Eric Anholt <eric at anholt.net>
    Reviewed-by: Julien Cristau <jcristau at debian.org>

diff --git a/hw/kdrive/linux/mouse.c b/hw/kdrive/linux/mouse.c
index aaab0cd..2bfe7f2 100644
--- a/hw/kdrive/linux/mouse.c
+++ b/hw/kdrive/linux/mouse.c
@@ -193,7 +193,7 @@ MouseWriteBytes(int fd, unsigned char *c, int n, int timeout)
 #define MAX_VALID   4           /* number of valid packets before accepting */
 
 typedef struct _kmouseProt {
-    char *name;
+    const char *name;
     Bool (*Complete) (KdPointerInfo * pi, unsigned char *ev, int ne);
     int (*Valid) (KdPointerInfo * pi, unsigned char *ev, int ne);
     Bool (*Parse) (KdPointerInfo * pi, unsigned char *ev, int ne);
diff --git a/hw/kdrive/src/kdrive.h b/hw/kdrive/src/kdrive.h
index 4829e1a..96787b6 100644
--- a/hw/kdrive/src/kdrive.h
+++ b/hw/kdrive/src/kdrive.h
@@ -174,7 +174,7 @@ typedef enum _kdPointerState {
 typedef struct _KdPointerInfo KdPointerInfo;
 
 typedef struct _KdPointerDriver {
-    char *name;
+    const char *name;
      Status(*Init) (KdPointerInfo *);
      Status(*Enable) (KdPointerInfo *);
     void (*Disable) (KdPointerInfo *);
@@ -243,7 +243,7 @@ typedef struct {
 typedef struct _KdKeyboardInfo KdKeyboardInfo;
 
 typedef struct _KdKeyboardDriver {
-    char *name;
+    const char *name;
     Bool (*Init) (KdKeyboardInfo *);
     Bool (*Enable) (KdKeyboardInfo *);
     void (*Leds) (KdKeyboardInfo *, int);
commit 56c405d46a86853771a0b808da4c8a9ef626960c
Author: Eric Anholt <eric at anholt.net>
Date:   Sat Aug 17 13:07:23 2013 +0200

    kdrive: Fix a few easy cast warnings.
    
    Signed-off-by: Eric Anholt <eric at anholt.net>
    Reviewed-by: Julien Cristau <jcristau at debian.org>

diff --git a/hw/kdrive/linux/evdev.c b/hw/kdrive/linux/evdev.c
index 9982fad..63e8409 100644
--- a/hw/kdrive/linux/evdev.c
+++ b/hw/kdrive/linux/evdev.c
@@ -186,7 +186,7 @@ EvdevPtrRead(int evdevPort, void *closure)
     }
 }
 
-char *kdefaultEvdev[] = {
+const char *kdefaultEvdev[] = {
     "/dev/input/event0",
     "/dev/input/event1",
     "/dev/input/event2",
diff --git a/hw/kdrive/linux/linux.c b/hw/kdrive/linux/linux.c
index 498c239..00de2ae 100644
--- a/hw/kdrive/linux/linux.c
+++ b/hw/kdrive/linux/linux.c
@@ -63,7 +63,7 @@ LinuxVTRequest(int sig)
 
 /* Check before chowning -- this avoids touching the file system */
 static void
-LinuxCheckChown(char *file)
+LinuxCheckChown(const char *file)
 {
     struct stat st;
     __uid_t u;
diff --git a/hw/kdrive/linux/mouse.c b/hw/kdrive/linux/mouse.c
index f442447..aaab0cd 100644
--- a/hw/kdrive/linux/mouse.c
+++ b/hw/kdrive/linux/mouse.c
@@ -738,7 +738,7 @@ MouseInitProtocol(Kmouse * km)
 }
 
 static void
-MouseFirstProtocol(Kmouse * km, char *prot)
+MouseFirstProtocol(Kmouse * km, const char *prot)
 {
     if (prot) {
         for (km->i_prot = 0; km->i_prot < NUM_PROT; km->i_prot++)
@@ -887,7 +887,7 @@ MouseRead(int mousePort, void *closure)
 
 int MouseInputType;
 
-char *kdefaultMouse[] = {
+const char *kdefaultMouse[] = {
     "/dev/input/mice",
     "/dev/mouse",
     "/dev/psaux",
diff --git a/hw/kdrive/linux/ps2.c b/hw/kdrive/linux/ps2.c
index d1522a2..e5417a5 100644
--- a/hw/kdrive/linux/ps2.c
+++ b/hw/kdrive/linux/ps2.c
@@ -58,7 +58,7 @@ Ps2ReadBytes(int fd, char *buf, int len, int min)
     return tot;
 }
 
-char *Ps2Names[] = {
+const char *Ps2Names[] = {
     "/dev/psaux",
 /*    "/dev/mouse", */
     "/dev/input/mice",
commit a9c48a07eea50468fa47ab178cdd91edb0b5727f
Author: Eric Anholt <eric at anholt.net>
Date:   Sat Aug 17 13:06:23 2013 +0200

    kdrive: Drop dead code.
    
    This is unused as of the introduction of a helper in
    e7150db5350bc2113ff4126019b489847a4dc217
    
    Signed-off-by: Eric Anholt <eric at anholt.net>
    Reviewed-by: Julien Cristau <jcristau at debian.org>

diff --git a/hw/kdrive/src/kinput.c b/hw/kdrive/src/kinput.c
index c30f170..3aad87a 100644
--- a/hw/kdrive/src/kinput.c
+++ b/hw/kdrive/src/kinput.c
@@ -1675,13 +1675,6 @@ char *kdActionNames[] = {
 };
 #endif                          /* DEBUG */
 
-static void
-KdQueueEvent(DeviceIntPtr pDev, InternalEvent *ev)
-{
-    KdAssertSigioBlocked("KdQueueEvent");
-    mieqEnqueue(pDev, ev);
-}
-
 /* We return true if we're stealing the event. */
 static Bool
 KdRunMouseMachine(KdPointerInfo * pi, KdInputClass c, int type, int x, int y,
commit 873ae962bdb7559c952b5955ba262285701982a8
Author: Eric Anholt <eric at anholt.net>
Date:   Sat Aug 17 13:01:57 2013 +0200

    ephyr: Fix dead code warning.
    
    Signed-off-by: Eric Anholt <eric at anholt.net>
    Reviewed-by: Julien Cristau <jcristau at debian.org>

diff --git a/hw/kdrive/ephyr/ephyrhostglx.c b/hw/kdrive/ephyr/ephyrhostglx.c
index 6a4392f..5ecb02d 100644
--- a/hw/kdrive/ephyr/ephyrhostglx.c
+++ b/hw/kdrive/ephyr/ephyrhostglx.c
@@ -274,7 +274,6 @@ ephyrHostGLXGetVisualConfigsInternal(enum VisualConfRequestType a_type,
     xGLXGetVisualConfigsReply reply;
     char *server_glx_version = NULL, *server_glx_extensions = NULL;
     int j = 0,
-        screens = 0,
         major_opcode = 0,
         num_props = 0,
         num_visuals = 0, props_buf_size = 0, props_per_visual_size = 0;
@@ -282,7 +281,6 @@ ephyrHostGLXGetVisualConfigsInternal(enum VisualConfRequestType a_type,
 
     EPHYR_RETURN_VAL_IF_FAIL(dpy, FALSE);
 
-    screens = ScreenCount(dpy);
     if (!ephyrHostGLXGetMajorOpcode(&major_opcode)) {
         EPHYR_LOG_ERROR("failed to get opcode\n");
         goto out;
commit 34af2eebe19e2f8afe35a5614d4d44fa4fd89d6b
Author: Eric Anholt <eric at anholt.net>
Date:   Sat Aug 17 13:01:32 2013 +0200

    ephyr: Fix const-cast warnings for setting window title.
    
    Signed-off-by: Eric Anholt <eric at anholt.net>
    Reviewed-by: Julien Cristau <jcristau at debian.org>

diff --git a/hw/kdrive/ephyr/hostx.c b/hw/kdrive/ephyr/hostx.c
index f2b458d..5071289 100644
--- a/hw/kdrive/ephyr/hostx.c
+++ b/hw/kdrive/ephyr/hostx.c
@@ -215,7 +215,7 @@ hostx_set_screen_number(EphyrScreenInfo screen, int number)
 }
 
 void
-hostx_set_win_title(EphyrScreenInfo screen, char *extra_text)
+hostx_set_win_title(EphyrScreenInfo screen, const char *extra_text)
 {
     struct EphyrHostScreen *host_screen = host_screen_from_screen_info(screen);
 
diff --git a/hw/kdrive/ephyr/hostx.h b/hw/kdrive/ephyr/hostx.h
index 38b7b37..f47297c 100644
--- a/hw/kdrive/ephyr/hostx.h
+++ b/hw/kdrive/ephyr/hostx.h
@@ -171,7 +171,7 @@ void
  hostx_set_screen_number(EphyrScreenInfo screen, int number);
 
 void
- hostx_set_win_title(EphyrScreenInfo screen, char *extra_text);
+ hostx_set_win_title(EphyrScreenInfo screen, const char *extra_text);
 
 int
  hostx_get_depth(void);
commit 7edf5066db48434739ac64e0576fbb4fdf0f37f9
Author: Eric Anholt <eric at anholt.net>
Date:   Sat Aug 17 12:54:33 2013 +0200

    ephyr: Fix const cast warnings in ephyrhostvideo.
    
    Signed-off-by: Eric Anholt <eric at anholt.net>
    Reviewed-by: Julien Cristau <jcristau at debian.org>

diff --git a/hw/kdrive/ephyr/ephyrhostvideo.c b/hw/kdrive/ephyr/ephyrhostvideo.c
index 05e9ad9..99f0f50 100644
--- a/hw/kdrive/ephyr/ephyrhostvideo.c
+++ b/hw/kdrive/ephyr/ephyrhostvideo.c
@@ -58,7 +58,7 @@
 #endif /*FALSE*/
 static XExtensionInfo _xv_info_data;
 static XExtensionInfo *xv_info = &_xv_info_data;
-static char *xv_extension_name = XvName;
+static const char *xv_extension_name = XvName;
 static char *xv_error_string(Display * dpy, int code, XExtCodes * codes,
                              char *buf, int n);
 static int xv_close_display(Display * dpy, XExtCodes * codes);
@@ -78,7 +78,7 @@ static XExtensionHooks xv_extension_hooks = {
     xv_error_string             /* error_string */
 };
 
-static char *xv_error_list[] = {
+static const char *xv_error_list[] = {
     "BadPort",                  /* XvBadPort     */
     "BadEncoding",              /* XvBadEncoding */
     "BadControl"                /* XvBadControl  */
@@ -311,7 +311,7 @@ char
 ephyrHostXVAdaptorGetType(const EphyrHostXVAdaptor * a_this)
 {
     EPHYR_RETURN_VAL_IF_FAIL(a_this, -1);
-    return ((XvAdaptorInfo *) a_this)->type;
+    return ((const XvAdaptorInfo *) a_this)->type;
 }
 
 const char *
@@ -319,7 +319,7 @@ ephyrHostXVAdaptorGetName(const EphyrHostXVAdaptor * a_this)
 {
     EPHYR_RETURN_VAL_IF_FAIL(a_this, NULL);
 
-    return ((XvAdaptorInfo *) a_this)->name;
+    return ((const XvAdaptorInfo *) a_this)->name;
 }
 
 EphyrHostVideoFormat *
@@ -333,16 +333,16 @@ ephyrHostXVAdaptorGetVideoFormats(const EphyrHostXVAdaptor * a_this,
 
     EPHYR_RETURN_VAL_IF_FAIL(a_this, NULL);
 
-    nb_formats = ((XvAdaptorInfo *) a_this)->num_formats;
+    nb_formats = ((const XvAdaptorInfo *) a_this)->num_formats;
     formats = calloc(nb_formats, sizeof(EphyrHostVideoFormat));
     for (i = 0; i < nb_formats; i++) {
         memset(&visual_info_template, 0, sizeof(visual_info_template));
         visual_info_template.visualid =
-            ((XvAdaptorInfo *) a_this)->formats[i].visual_id;
+            ((const XvAdaptorInfo *) a_this)->formats[i].visual_id;
         visual_info = XGetVisualInfo(hostx_get_display(),
                                      VisualIDMask,
                                      &visual_info_template, &nb_visual_info);
-        formats[i].depth = ((XvAdaptorInfo *) a_this)->formats[i].depth;
+        formats[i].depth = ((const XvAdaptorInfo *) a_this)->formats[i].depth;
         formats[i].visual_class = visual_info->class;
         XFree(visual_info);
     }
@@ -356,7 +356,7 @@ ephyrHostXVAdaptorGetNbPorts(const EphyrHostXVAdaptor * a_this)
 {
     EPHYR_RETURN_VAL_IF_FAIL(a_this, -1);
 
-    return ((XvAdaptorInfo *) a_this)->num_ports;
+    return ((const XvAdaptorInfo *) a_this)->num_ports;
 }
 
 int
@@ -364,7 +364,7 @@ ephyrHostXVAdaptorGetFirstPortID(const EphyrHostXVAdaptor * a_this)
 {
     EPHYR_RETURN_VAL_IF_FAIL(a_this, -1);
 
-    return ((XvAdaptorInfo *) a_this)->base_id;
+    return ((const XvAdaptorInfo *) a_this)->base_id;
 }
 
 Bool
@@ -372,8 +372,8 @@ ephyrHostXVAdaptorHasPutVideo(const EphyrHostXVAdaptor * a_this, Bool *a_result)
 {
     EPHYR_RETURN_VAL_IF_FAIL(a_this && a_result, FALSE);
 
-    if ((((XvAdaptorInfo *) a_this)->type & (XvVideoMask | XvInputMask)) ==
-        (XvVideoMask | XvInputMask))
+    if ((((const XvAdaptorInfo *) a_this)->type &
+         (XvVideoMask | XvInputMask)) == (XvVideoMask | XvInputMask))
         *a_result = TRUE;
     else
         *a_result = FALSE;
@@ -383,8 +383,8 @@ ephyrHostXVAdaptorHasPutVideo(const EphyrHostXVAdaptor * a_this, Bool *a_result)
 Bool
 ephyrHostXVAdaptorHasGetVideo(const EphyrHostXVAdaptor * a_this, Bool *a_result)
 {
-    if ((((XvAdaptorInfo *) a_this)->type & (XvVideoMask | XvOutputMask)) ==
-        (XvVideoMask | XvOutputMask))
+    if ((((const XvAdaptorInfo *) a_this)->type &
+         (XvVideoMask | XvOutputMask)) == (XvVideoMask | XvOutputMask))
         *a_result = TRUE;
     else
         *a_result = FALSE;
@@ -396,8 +396,8 @@ ephyrHostXVAdaptorHasPutStill(const EphyrHostXVAdaptor * a_this, Bool *a_result)
 {
     EPHYR_RETURN_VAL_IF_FAIL(a_this && a_result, FALSE);
 
-    if ((((XvAdaptorInfo *) a_this)->type & (XvStillMask | XvInputMask)) ==
-        (XvStillMask | XvInputMask))
+    if ((((const XvAdaptorInfo *) a_this)->type &
+         (XvStillMask | XvInputMask)) == (XvStillMask | XvInputMask))
         *a_result = TRUE;
     else
         *a_result = FALSE;
@@ -409,8 +409,8 @@ ephyrHostXVAdaptorHasGetStill(const EphyrHostXVAdaptor * a_this, Bool *a_result)
 {
     EPHYR_RETURN_VAL_IF_FAIL(a_this && a_result, FALSE);
 
-    if ((((XvAdaptorInfo *) a_this)->type & (XvStillMask | XvOutputMask)) ==
-        (XvStillMask | XvOutputMask))
+    if ((((const XvAdaptorInfo *) a_this)->type &
+         (XvStillMask | XvOutputMask)) == (XvStillMask | XvOutputMask))
         *a_result = TRUE;
     else
         *a_result = FALSE;
@@ -422,8 +422,8 @@ ephyrHostXVAdaptorHasPutImage(const EphyrHostXVAdaptor * a_this, Bool *a_result)
 {
     EPHYR_RETURN_VAL_IF_FAIL(a_this && a_result, FALSE);
 
-    if ((((XvAdaptorInfo *) a_this)->type & (XvImageMask | XvInputMask)) ==
-        (XvImageMask | XvInputMask))
+    if ((((const XvAdaptorInfo *) a_this)->type &
+         (XvImageMask | XvInputMask)) == (XvImageMask | XvInputMask))
         *a_result = TRUE;
     else
         *a_result = FALSE;
commit fe7463b8ce0de301c2f82b108c93963424f77219
Author: Julien Cristau <jcristau at debian.org>
Date:   Sat Jul 27 12:09:07 2013 +0200

    dix: add missing include for DeleteWindowFromAnySelections
    
    Fixes build error with XACE disabled:
    window.c:886:5: error: implicit declaration of function 'DeleteWindowFromAnySelections' [-Werror=implicit-function-declaration]
         DeleteWindowFromAnySelections(pWin);
         ^
    
    Debian bug#701372
    
    Reported-by: Matthias Klose <doko at debian.org>
    Signed-off-by: Julien Cristau <jcristau at debian.org>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/dix/window.c b/dix/window.c
index 8950f97..9fa51c2 100644
--- a/dix/window.c
+++ b/dix/window.c
@@ -126,6 +126,7 @@ Equipment Corporation.
 #ifdef COMPOSITE
 #include "compint.h"
 #endif
+#include "selection.h"
 
 #include "privates.h"
 #include "xace.h"
commit 6a49f8836a649322d38a364d9ae084be40fb2305
Author: Keith Packard <keithp at keithp.com>
Date:   Sat Aug 17 12:17:36 2013 +0200

    Add .dir-locals.el
    
    Enforce X.org style with an emacs configuration file
    
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/.dir-locals.el b/.dir-locals.el
new file mode 100644
index 0000000..6aceae3
--- /dev/null
+++ b/.dir-locals.el
@@ -0,0 +1 @@
+((c-mode . ((c-basic-offset . 4) (indent-tabs-mode . nil))))
\ No newline at end of file
commit f67d022523c59a27f3bf8791aa9ca6624318b1fd
Merge: 5a36cdd 9680f6a
Author: Keith Packard <keithp at keithp.com>
Date:   Tue Aug 6 07:12:12 2013 +0200

    Merge commit '9680f6a12d642c2e4bfa09bf459d678214059d74'

commit 5a36cdd91530d27627e39159a89b53f9fbb75280
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Aug 5 20:46:45 2013 -0700

    Allow disabling XFree86-DGA, DRI, VidModeExtension extensions
    
    Code to recognize these in extension enable/disable options was wrapped
    in #ifdef XorgLoader, but that's not defined when building miinitext.c
    since the great module merge of 1.13.  Change to an #ifdef that is defined.
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Robert Hooker <robert.hooker at canonical.com>
    Reviewed-by: Daniel Stone <daniel at fooishbar.org>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/mi/miinitext.c b/mi/miinitext.c
index 81c663a..dbca9f7 100644
--- a/mi/miinitext.c
+++ b/mi/miinitext.c
@@ -157,7 +157,7 @@ static ExtensionToggle ExtensionToggleList[] = {
 #ifdef XF86BIGFONT
     {"XFree86-Bigfont", &noXFree86BigfontExtension},
 #endif
-#ifdef XorgLoader
+#ifdef XORGSERVER
 #ifdef XFreeXDGA
     {"XFree86-DGA", &noXFree86DGAExtension},
 #endif
commit 9680f6a12d642c2e4bfa09bf459d678214059d74
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Tue Aug 6 13:14:56 2013 +1000

    xfree86: de-duplicate some AM_CPPFLAGS
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>

diff --git a/hw/xfree86/int10/Makefile.am b/hw/xfree86/int10/Makefile.am
index 383846c..66cb14d 100644
--- a/hw/xfree86/int10/Makefile.am
+++ b/hw/xfree86/int10/Makefile.am
@@ -17,9 +17,10 @@ if I386_VIDEO
 I386_VIDEO_CFLAGS = -D_PC
 endif
 
+AM_CPPFLAGS = $(XORG_INCS)
+
 if INT10_VM86
 AM_CFLAGS = $(I386_VIDEO_CFLAGS) -D_VM86_LINUX $(DIX_CFLAGS) $(XORG_CFLAGS) $(EXTRA_CFLAGS)
-AM_CPPFLAGS = $(XORG_INCS)
 libint10_la_SOURCES = \
 	$(COMMON_SOURCES) \
 	$(srcdir)/../os-support/linux/int10/vm86/linux_vm86.c \
@@ -29,7 +30,7 @@ endif
 if INT10_X86EMU
 AM_CFLAGS = $(I386_VIDEO_CFLAGS) -D_X86EMU -DNO_SYS_HEADERS \
            $(XORG_CFLAGS) $(EXTRA_CFLAGS) $(DIX_CFLAGS)
-AM_CPPFLAGS = $(XORG_INCS) -I$(srcdir)/../x86emu
+AM_CPPFLAGS += -I$(srcdir)/../x86emu
 libint10_la_SOURCES = \
 	$(COMMON_SOURCES) \
 	xf86x86emu.c \
@@ -39,7 +40,6 @@ endif
 
 if INT10_STUB
 AM_CFLAGS = $(I386_VIDEO_CFLAGS) -D_VM86_LINUX $(DIX_CFLAGS) $(XORG_CFLAGS) $(EXTRA_CFLAGS)
-AM_CPPFLAGS = $(XORG_INCS)
 libint10_la_SOURCES = stub.c xf86int10module.c
 endif
 
commit bbef8e46f2fed8f823ee4b97e96c3fcee28f3b75
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Tue Aug 6 13:08:13 2013 +1000

    Replace INCLUDES with AM_CPPFLAGS
    
    newer automake gets quite noisy about this.
    hw/xfree86/ddc/Makefile.am:7: warning:
    'INCLUDES' is the old name for 'AM_CPPFLAGS' (or '*_CPPFLAGS')
    and many more of these.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>

diff --git a/exa/Makefile.am b/exa/Makefile.am
index 8b759cd..c1f1e86 100644
--- a/exa/Makefile.am
+++ b/exa/Makefile.am
@@ -8,7 +8,7 @@ if XORG
 sdk_HEADERS = exa.h
 endif
 
-INCLUDES = \
+AM_CPPFLAGS = \
 	$(XORG_INCS) \
 	-I$(srcdir)/../miext/cw
 
diff --git a/glx/Makefile.am b/glx/Makefile.am
index 591c4ac..d1c203d 100644
--- a/glx/Makefile.am
+++ b/glx/Makefile.am
@@ -15,7 +15,7 @@ AM_CFLAGS = \
 # none yet
 #sdk_HEADERS =
 
-INCLUDES = \
+AM_CPPFLAGS = \
 	-I$(top_srcdir)/hw/xfree86/os-support \
 	-I$(top_srcdir)/hw/xfree86/os-support/bus \
 	-I$(top_srcdir)/hw/xfree86/common \
@@ -23,7 +23,7 @@ INCLUDES = \
 	-I$(top_srcdir)/mi
 
 if DRI2_AIGLX
-INCLUDES += -I$(top_srcdir)/hw/xfree86/dri2
+AM_CPPFLAGS += -I$(top_srcdir)/hw/xfree86/dri2
 endif
 
 glapi_sources =					\
diff --git a/hw/kdrive/ephyr/Makefile.am b/hw/kdrive/ephyr/Makefile.am
index 2e0613a..ab02437 100644
--- a/hw/kdrive/ephyr/Makefile.am
+++ b/hw/kdrive/ephyr/Makefile.am
@@ -1,6 +1,6 @@
 SUBDIRS = man
 
-INCLUDES = 			\
+AM_CPPFLAGS = 			\
 	@KDRIVE_INCS@		\
 	@KDRIVE_CFLAGS@		\
 	@XEPHYR_INCS@		\
diff --git a/hw/kdrive/fake/Makefile.am b/hw/kdrive/fake/Makefile.am
index 6d3ed05..14c99c3 100644
--- a/hw/kdrive/fake/Makefile.am
+++ b/hw/kdrive/fake/Makefile.am
@@ -1,4 +1,4 @@
-INCLUDES = 					\
+AM_CPPFLAGS = 					\
 	@KDRIVE_INCS@				\
 	@KDRIVE_CFLAGS@
 
diff --git a/hw/kdrive/fbdev/Makefile.am b/hw/kdrive/fbdev/Makefile.am
index ec9df95..7e8ba02 100644
--- a/hw/kdrive/fbdev/Makefile.am
+++ b/hw/kdrive/fbdev/Makefile.am
@@ -1,4 +1,4 @@
-INCLUDES = 					\
+AM_CPPFLAGS = 					\
 	@KDRIVE_INCS@				\
 	@KDRIVE_CFLAGS@
 
diff --git a/hw/kdrive/linux/Makefile.am b/hw/kdrive/linux/Makefile.am
index 93e5d2f..1362cd9 100644
--- a/hw/kdrive/linux/Makefile.am
+++ b/hw/kdrive/linux/Makefile.am
@@ -1,4 +1,4 @@
-INCLUDES = 					\
+AM_CPPFLAGS = 					\
 	@KDRIVE_INCS@				\
 	@KDRIVE_CFLAGS@
 
diff --git a/hw/kdrive/src/Makefile.am b/hw/kdrive/src/Makefile.am
index 51375b9..5799ddb 100644
--- a/hw/kdrive/src/Makefile.am
+++ b/hw/kdrive/src/Makefile.am
@@ -1,4 +1,4 @@
-INCLUDES = 					\
+AM_CPPFLAGS = 					\
 	@KDRIVE_INCS@				\
 	@KDRIVE_CFLAGS@
 
diff --git a/hw/xfree86/Makefile.am b/hw/xfree86/Makefile.am
index c3899b5..d568e0d 100644
--- a/hw/xfree86/Makefile.am
+++ b/hw/xfree86/Makefile.am
@@ -39,7 +39,7 @@ bin_PROGRAMS = Xorg
 nodist_Xorg_SOURCES = sdksyms.c
 
 AM_CFLAGS = $(DIX_CFLAGS) @XORG_CFLAGS@
-INCLUDES = $(XORG_INCS) -I$(srcdir)/parser -I$(top_srcdir)/miext/cw \
+AM_CPPFLAGS = $(XORG_INCS) -I$(srcdir)/parser -I$(top_srcdir)/miext/cw \
 	-I$(srcdir)/ddc -I$(srcdir)/i2c -I$(srcdir)/modes -I$(srcdir)/ramdac \
 	-I$(srcdir)/dri -I$(srcdir)/dri2
 
@@ -115,7 +115,7 @@ CLEANFILES = sdksyms.c sdksyms.dep
 EXTRA_DIST += sdksyms.sh
 
 sdksyms.dep sdksyms.c: sdksyms.sh
-	$(AM_V_GEN)CPP='$(CPP)' AWK='$(AWK)' $(SHELL) $(srcdir)/sdksyms.sh $(top_srcdir) $(CFLAGS) $(AM_CFLAGS) $(INCLUDES)
+	$(AM_V_GEN)CPP='$(CPP)' AWK='$(AWK)' $(SHELL) $(srcdir)/sdksyms.sh $(top_srcdir) $(CFLAGS) $(AM_CFLAGS) $(AM_CPPFLAGS)
 
 SDKSYMS_DEP = sdksyms.dep
 include $(SDKSYMS_DEP)
diff --git a/hw/xfree86/common/Makefile.am b/hw/xfree86/common/Makefile.am
index 532d87b..7a2b4bc 100644
--- a/hw/xfree86/common/Makefile.am
+++ b/hw/xfree86/common/Makefile.am
@@ -53,7 +53,7 @@ libcommon_la_SOURCES = xf86Configure.c xf86Bus.c xf86Config.c \
 nodist_libcommon_la_SOURCES = xf86DefModeSet.c xf86Build.h
 libcommon_la_LIBADD = $(top_builddir)/config/libconfig.la
 
-INCLUDES = $(XORG_INCS) -I$(srcdir)/../ddc -I$(srcdir)/../i2c \
+AM_CPPFLAGS = $(XORG_INCS) -I$(srcdir)/../ddc -I$(srcdir)/../i2c \
 	   -I$(srcdir)/../loader -I$(srcdir)/../parser \
            -I$(srcdir)/../vbe -I$(srcdir)/../int10 \
 	   -I$(srcdir)/../vgahw -I$(srcdir)/../dixmods/extmod \
diff --git a/hw/xfree86/ddc/Makefile.am b/hw/xfree86/ddc/Makefile.am
index 93ea4a2..a7b84ad 100644
--- a/hw/xfree86/ddc/Makefile.am
+++ b/hw/xfree86/ddc/Makefile.am
@@ -4,7 +4,7 @@ noinst_LTLIBRARIES = libddc.la
 
 libddc_la_SOURCES = ddc.c interpret_edid.c print_edid.c ddcProperty.c
 
-INCLUDES = $(XORG_INCS) -I$(srcdir)/../i2c
+AM_CPPFLAGS = $(XORG_INCS) -I$(srcdir)/../i2c
 
 AM_CFLAGS = $(DIX_CFLAGS) $(XORG_CFLAGS)
 
diff --git a/hw/xfree86/dixmods/Makefile.am b/hw/xfree86/dixmods/Makefile.am
index f161db6..9933bc8 100644
--- a/hw/xfree86/dixmods/Makefile.am
+++ b/hw/xfree86/dixmods/Makefile.am
@@ -12,7 +12,7 @@ extsmoduledir = $(moduledir)/extensions
 extsmodule_LTLIBRARIES = $(GLXMODS)
 
 AM_CFLAGS = @XORG_CFLAGS@ @DIX_CFLAGS@
-INCLUDES = @XORG_INCS@ \
+AM_CPPFLAGS = @XORG_INCS@ \
            -I$(top_srcdir)/hw/xfree86/loader \
            -I$(top_srcdir)/miext/shadow \
            -I$(top_srcdir)/glx
diff --git a/hw/xfree86/exa/Makefile.am b/hw/xfree86/exa/Makefile.am
index 4339084..1e42cda 100644
--- a/hw/xfree86/exa/Makefile.am
+++ b/hw/xfree86/exa/Makefile.am
@@ -4,7 +4,7 @@ module_LTLIBRARIES = libexa.la
 
 libexa_la_LDFLAGS = -module -avoid-version $(LD_NO_UNDEFINED_FLAG)
 
-INCLUDES = \
+AM_CPPFLAGS = \
 	$(XORG_INCS) \
 	-I$(srcdir)/../../../exa \
 	-I$(srcdir)/../../../miext/cw
diff --git a/hw/xfree86/fbdevhw/Makefile.am b/hw/xfree86/fbdevhw/Makefile.am
index ee5577a..37cd88c 100644
--- a/hw/xfree86/fbdevhw/Makefile.am
+++ b/hw/xfree86/fbdevhw/Makefile.am
@@ -10,7 +10,7 @@ else
 libfbdevhw_la_SOURCES = fbdevhwstub.c
 endif
 
-INCLUDES = $(XORG_INCS) -I$(srcdir)/../i2c -I$(srcdir)/../modes -I$(srcdir)/../ddc -I$(srcdir)/../parser
+AM_CPPFLAGS = $(XORG_INCS) -I$(srcdir)/../i2c -I$(srcdir)/../modes -I$(srcdir)/../ddc -I$(srcdir)/../parser
 
 AM_CFLAGS = $(DIX_CFLAGS) $(XORG_CFLAGS)
 
diff --git a/hw/xfree86/i2c/Makefile.am b/hw/xfree86/i2c/Makefile.am
index cb18db1..c311591 100644
--- a/hw/xfree86/i2c/Makefile.am
+++ b/hw/xfree86/i2c/Makefile.am
@@ -12,7 +12,7 @@ multimedia_LTLIBRARIES =	\
 
 libi2c_la_SOURCES = xf86i2c.c
 
-INCLUDES = $(XORG_INCS)
+AM_CPPFLAGS = $(XORG_INCS)
 
 AM_CFLAGS = $(DIX_CFLAGS) $(XORG_CFLAGS)
 
diff --git a/hw/xfree86/int10/Makefile.am b/hw/xfree86/int10/Makefile.am
index f5ece69..383846c 100644
--- a/hw/xfree86/int10/Makefile.am
+++ b/hw/xfree86/int10/Makefile.am
@@ -19,7 +19,7 @@ endif
 
 if INT10_VM86
 AM_CFLAGS = $(I386_VIDEO_CFLAGS) -D_VM86_LINUX $(DIX_CFLAGS) $(XORG_CFLAGS) $(EXTRA_CFLAGS)
-INCLUDES = $(XORG_INCS)
+AM_CPPFLAGS = $(XORG_INCS)
 libint10_la_SOURCES = \
 	$(COMMON_SOURCES) \
 	$(srcdir)/../os-support/linux/int10/vm86/linux_vm86.c \
@@ -29,7 +29,7 @@ endif
 if INT10_X86EMU
 AM_CFLAGS = $(I386_VIDEO_CFLAGS) -D_X86EMU -DNO_SYS_HEADERS \
            $(XORG_CFLAGS) $(EXTRA_CFLAGS) $(DIX_CFLAGS)
-INCLUDES = $(XORG_INCS) -I$(srcdir)/../x86emu
+AM_CPPFLAGS = $(XORG_INCS) -I$(srcdir)/../x86emu
 libint10_la_SOURCES = \
 	$(COMMON_SOURCES) \
 	xf86x86emu.c \
@@ -39,7 +39,7 @@ endif
 
 if INT10_STUB
 AM_CFLAGS = $(I386_VIDEO_CFLAGS) -D_VM86_LINUX $(DIX_CFLAGS) $(XORG_CFLAGS) $(EXTRA_CFLAGS)
-INCLUDES = $(XORG_INCS)
+AM_CPPFLAGS = $(XORG_INCS)
 libint10_la_SOURCES = stub.c xf86int10module.c
 endif
 
diff --git a/hw/xfree86/loader/Makefile.am b/hw/xfree86/loader/Makefile.am
index bd47a63..a658ca5 100644
--- a/hw/xfree86/loader/Makefile.am
+++ b/hw/xfree86/loader/Makefile.am
@@ -1,6 +1,6 @@
 noinst_LTLIBRARIES = libloader.la
 
-INCLUDES = $(XORG_INCS) -I$(srcdir)/../parser -I$(top_srcdir)/miext/cw \
+AM_CPPFLAGS = $(XORG_INCS) -I$(srcdir)/../parser -I$(top_srcdir)/miext/cw \
 	   -I$(srcdir)/../ddc -I$(srcdir)/../i2c -I$(srcdir)/../modes \
 	   -I$(srcdir)/../ramdac -I$(srcdir)/../dri -I$(srcdir)/../dri2
 
diff --git a/hw/xfree86/modes/Makefile.am b/hw/xfree86/modes/Makefile.am
index 7e33ebb..220643f 100644
--- a/hw/xfree86/modes/Makefile.am
+++ b/hw/xfree86/modes/Makefile.am
@@ -19,7 +19,7 @@ libxf86modes_la_SOURCES = \
 	xf86Rotate.c \
         $(DGA_SRCS)
 
-INCLUDES = $(XORG_INCS) -I$(srcdir)/../ddc -I$(srcdir)/../i2c \
+AM_CPPFLAGS = $(XORG_INCS) -I$(srcdir)/../ddc -I$(srcdir)/../i2c \
 	   -I$(srcdir)/../loader -I$(srcdir)/../rac -I$(srcdir)/../parser \
 	   -I$(srcdir)/../vbe -I$(srcdir)/../int10 \
 	   -I$(srcdir)/../vgahw -I$(srcdir)/../ramdac \
diff --git a/hw/xfree86/os-support/bsd/Makefile.am b/hw/xfree86/os-support/bsd/Makefile.am
index b6ecdf1..7133c0f 100644
--- a/hw/xfree86/os-support/bsd/Makefile.am
+++ b/hw/xfree86/os-support/bsd/Makefile.am
@@ -54,7 +54,7 @@ endif
 # FIXME: NetBSD Aperture defines (configure.ac)
 AM_CFLAGS = -DUSESTDRES $(XORG_CFLAGS) $(DIX_CFLAGS)
 
-INCLUDES = $(XORG_INCS)
+AM_CPPFLAGS = $(XORG_INCS)
 
 libbsd_la_SOURCES = \
 	$(srcdir)/../shared/posix_tty.c \
diff --git a/hw/xfree86/os-support/bus/Makefile.am b/hw/xfree86/os-support/bus/Makefile.am
index e09d4d2..eebb3ae 100644
--- a/hw/xfree86/os-support/bus/Makefile.am
+++ b/hw/xfree86/os-support/bus/Makefile.am
@@ -17,7 +17,7 @@ endif
 
 libbus_la_SOURCES = $(PCI_SOURCES) $(PLATFORM_SOURCES) nobus.c
 
-INCLUDES = $(XORG_INCS)
+AM_CPPFLAGS = $(XORG_INCS)
 
 AM_CFLAGS = $(XORG_CFLAGS) $(DIX_CFLAGS)
 
diff --git a/hw/xfree86/os-support/hurd/Makefile.am b/hw/xfree86/os-support/hurd/Makefile.am
index 3e82247..f228c1c 100644
--- a/hw/xfree86/os-support/hurd/Makefile.am
+++ b/hw/xfree86/os-support/hurd/Makefile.am
@@ -12,4 +12,4 @@ libhurd_la_SOURCES = hurd_bell.c hurd_init.c hurd_mmap.c \
 
 AM_CFLAGS = -DUSESTDRES -DHAVE_SYSV_IPC $(XORG_CFLAGS) $(DIX_CFLAGS)
 
-INCLUDES = $(XORG_INCS)
+AM_CPPFLAGS = $(XORG_INCS)
diff --git a/hw/xfree86/os-support/linux/Makefile.am b/hw/xfree86/os-support/linux/Makefile.am
index 61175b3..83e7e00 100644
--- a/hw/xfree86/os-support/linux/Makefile.am
+++ b/hw/xfree86/os-support/linux/Makefile.am
@@ -34,7 +34,7 @@ liblinux_la_SOURCES = lnx_init.c lnx_video.c \
 
 AM_CFLAGS = -DUSESTDRES -DHAVE_SYSV_IPC $(DIX_CFLAGS) $(XORG_CFLAGS) $(PLATFORM_DEFINES)
 
-INCLUDES = $(XORG_INCS) $(PLATFORM_INCLUDES) $(LIBDRM_CFLAGS)
+AM_CPPFLAGS = $(XORG_INCS) $(PLATFORM_INCLUDES) $(LIBDRM_CFLAGS)
 
 EXTRA_DIST = \
 	$(srcdir)/../shared/xf86Axp.h
diff --git a/hw/xfree86/os-support/misc/Makefile.am b/hw/xfree86/os-support/misc/Makefile.am
index 4bd3fc3..0265aec 100644
--- a/hw/xfree86/os-support/misc/Makefile.am
+++ b/hw/xfree86/os-support/misc/Makefile.am
@@ -5,7 +5,7 @@ libmisc_la_SOURCES = SlowBcopy.c
 
 #AM_LDFLAGS = -r
 
-INCLUDES = $(XORG_INCS)
+AM_CPPFLAGS = $(XORG_INCS)
 
 AM_CFLAGS = $(XORG_CFLAGS) $(DIX_CFLAGS)
 
diff --git a/hw/xfree86/os-support/solaris/Makefile.am b/hw/xfree86/os-support/solaris/Makefile.am
index 5163f44..6cda4b3 100644
--- a/hw/xfree86/os-support/solaris/Makefile.am
+++ b/hw/xfree86/os-support/solaris/Makefile.am
@@ -31,7 +31,7 @@ nodist_sdk_HEADERS = solaris- at SOLARIS_INOUT_ARCH@.il
 
 AM_CFLAGS = -DUSESTDRES -DHAVE_SYSV_IPC $(XORG_CFLAGS) $(DIX_CFLAGS)
 
-INCLUDES = $(XORG_INCS) 
+AM_CPPFLAGS = $(XORG_INCS) 
 
 EXTRA_DIST = solaris-amd64.S solaris-ia32.S solaris-sparcv8plus.S \
 	apSolaris.shar sun_inout.s
diff --git a/hw/xfree86/os-support/stub/Makefile.am b/hw/xfree86/os-support/stub/Makefile.am
index a1156ef..a39e17d 100644
--- a/hw/xfree86/os-support/stub/Makefile.am
+++ b/hw/xfree86/os-support/stub/Makefile.am
@@ -2,7 +2,7 @@ noinst_LTLIBRARIES = libstub.la
 
 AM_CFLAGS = $(XORG_CFLAGS) $(DIX_CFLAGS)
 
-INCLUDES = $(XORG_INCS)
+AM_CPPFLAGS = $(XORG_INCS)
 
 libstub_la_SOURCES = \
 	$(srcdir)/../shared/VTsw_noop.c \
diff --git a/hw/xfree86/parser/Makefile.am b/hw/xfree86/parser/Makefile.am
index 002cfbf..3bf62e8 100644
--- a/hw/xfree86/parser/Makefile.am
+++ b/hw/xfree86/parser/Makefile.am
@@ -51,4 +51,4 @@ sdk_HEADERS = \
 	xf86Parser.h \
 	xf86Optrec.h
 
-INCLUDES = -I$(srcdir)/../common
+AM_CPPFLAGS = -I$(srcdir)/../common
diff --git a/hw/xfree86/ramdac/Makefile.am b/hw/xfree86/ramdac/Makefile.am
index 346af4c..a3d7762 100644
--- a/hw/xfree86/ramdac/Makefile.am
+++ b/hw/xfree86/ramdac/Makefile.am
@@ -9,4 +9,4 @@ EXTRA_DIST = BTPriv.h IBMPriv.h TIPriv.h xf86CursorPriv.h xf86RamDacPriv.h \
 	CURSOR.NOTES
 
 AM_CFLAGS = $(DIX_CFLAGS) $(XORG_CFLAGS)
-INCLUDES = $(XORG_INCS)
+AM_CPPFLAGS = $(XORG_INCS)
diff --git a/hw/xfree86/shadowfb/Makefile.am b/hw/xfree86/shadowfb/Makefile.am
index 5756fca..22f7ada 100644
--- a/hw/xfree86/shadowfb/Makefile.am
+++ b/hw/xfree86/shadowfb/Makefile.am
@@ -5,6 +5,6 @@ libshadowfb_la_LIBADD = $(PIXMAN_LIBS)
 
 sdk_HEADERS = shadowfb.h
 
-INCLUDES = $(XORG_INCS)
+AM_CPPFLAGS = $(XORG_INCS)
 
 AM_CFLAGS = $(DIX_CFLAGS) $(XORG_CFLAGS)
diff --git a/hw/xfree86/utils/cvt/Makefile.am b/hw/xfree86/utils/cvt/Makefile.am
index 754606e..26abeb4 100644
--- a/hw/xfree86/utils/cvt/Makefile.am
+++ b/hw/xfree86/utils/cvt/Makefile.am
@@ -22,7 +22,7 @@
 
 bin_PROGRAMS = cvt
 
-INCLUDES = $(XORG_INCS) \
+AM_CPPFLAGS = $(XORG_INCS) \
 	   -I$(top_srcdir)/hw/xfree86/ddc \
 	   -I$(top_srcdir)/hw/xfree86/modes \
 	   -I$(top_srcdir)/hw/xfree86/parser
diff --git a/hw/xfree86/vbe/Makefile.am b/hw/xfree86/vbe/Makefile.am
index 1720eb9..041b47a 100644
--- a/hw/xfree86/vbe/Makefile.am
+++ b/hw/xfree86/vbe/Makefile.am
@@ -9,6 +9,6 @@ sdk_HEADERS = vbe.h vbeModes.h
 
 AM_CFLAGS = $(DIX_CFLAGS) $(XORG_CFLAGS)
 
-INCLUDES = $(XORG_INCS) -I$(srcdir)/../ddc -I$(srcdir)/../i2c \
+AM_CPPFLAGS = $(XORG_INCS) -I$(srcdir)/../ddc -I$(srcdir)/../i2c \
            -I$(srcdir)/../modes -I$(srcdir)/../parser \
            -I$(srcdir)/../int10
diff --git a/hw/xfree86/vgahw/Makefile.am b/hw/xfree86/vgahw/Makefile.am
index f48e46a..f0b6574 100644
--- a/hw/xfree86/vgahw/Makefile.am
+++ b/hw/xfree86/vgahw/Makefile.am
@@ -1,7 +1,7 @@
 module_LTLIBRARIES = libvgahw.la
 libvgahw_la_LDFLAGS = -avoid-version
 libvgahw_la_SOURCES = vgaHW.c vgaHWmodule.c
-INCLUDES = $(XORG_INCS) -I$(srcdir)/../ddc -I$(srcdir)/../i2c
+AM_CPPFLAGS = $(XORG_INCS) -I$(srcdir)/../ddc -I$(srcdir)/../i2c
 AM_CFLAGS = $(DIX_CFLAGS) $(XORG_CFLAGS)
 
 sdk_HEADERS = vgaHW.h
diff --git a/hw/xfree86/x86emu/Makefile.am b/hw/xfree86/x86emu/Makefile.am
index df96977..2a55d63 100644
--- a/hw/xfree86/x86emu/Makefile.am
+++ b/hw/xfree86/x86emu/Makefile.am
@@ -11,7 +11,7 @@ libx86emu_la_SOURCES = debug.c \
                       sys.c \
                       x86emu.h
 
-INCLUDES = 
+AM_CPPFLAGS = 
 
 AM_CFLAGS = $(DIX_CFLAGS) $(XORG_CFLAGS)
 
diff --git a/hw/xwin/Makefile.am b/hw/xwin/Makefile.am
index 74a4243..831e7dc 100644
--- a/hw/xwin/Makefile.am
+++ b/hw/xwin/Makefile.am
@@ -150,7 +150,7 @@ SRCS =	InitInput.c \
 
 XWin_SOURCES = $(SRCS)
 
-INCLUDES = -I$(top_srcdir)/miext/rootless
+AM_CPPFLAGS = -I$(top_srcdir)/miext/rootless
 
 XWIN_SYS_LIBS += -ldxguid
 
diff --git a/hw/xwin/glx/Makefile.am b/hw/xwin/glx/Makefile.am
index f969af2..067ee5b 100644
--- a/hw/xwin/glx/Makefile.am
+++ b/hw/xwin/glx/Makefile.am
@@ -23,7 +23,7 @@ endif
 
 DEFS =  $(DEFS_MULTIWINDOW) $(DEFS_MULTIWINDOWEXTWM) $(DEFS_GLX_WINDOWS)
 
-INCLUDES = -I$(top_srcdir)/miext/rootless
+AM_CPPFLAGS = -I$(top_srcdir)/miext/rootless
 
 AM_CFLAGS = -DHAVE_XWIN_CONFIG_H $(DIX_CFLAGS) \
             $(XWINMODULES_CFLAGS) \
diff --git a/miext/damage/Makefile.am b/miext/damage/Makefile.am
index 767a65a..a7f432a 100644
--- a/miext/damage/Makefile.am
+++ b/miext/damage/Makefile.am
@@ -2,7 +2,7 @@ noinst_LTLIBRARIES = libdamage.la
 
 AM_CFLAGS = $(DIX_CFLAGS)
 
-INCLUDES = -I$(srcdir)/../cw
+AM_CPPFLAGS = -I$(srcdir)/../cw
 
 if XORG
 sdk_HEADERS = damage.h damagestr.h
diff --git a/miext/sync/Makefile.am b/miext/sync/Makefile.am
index 36b2816..9aa1ba5 100644
--- a/miext/sync/Makefile.am
+++ b/miext/sync/Makefile.am
@@ -2,7 +2,7 @@ noinst_LTLIBRARIES = libsync.la
 
 AM_CFLAGS = $(DIX_CFLAGS)
 
-INCLUDES = 
+AM_CPPFLAGS = 
 
 if XORG
 sdk_HEADERS = misync.h misyncstr.h
diff --git a/test/Makefile.am b/test/Makefile.am
index 34f53fc..eff0c9d 100644
--- a/test/Makefile.am
+++ b/test/Makefile.am
@@ -13,9 +13,9 @@ TESTS=$(noinst_PROGRAMS)
 TESTS_ENVIRONMENT = $(XORG_MALLOC_DEBUG_ENV)
 
 AM_CFLAGS = $(DIX_CFLAGS) @XORG_CFLAGS@
-INCLUDES = $(XORG_INCS) -I$(top_srcdir)/miext/cw
+AM_CPPFLAGS = $(XORG_INCS) -I$(top_srcdir)/miext/cw
 if XORG
-INCLUDES += -I$(top_srcdir)/hw/xfree86/parser \
+AM_CPPFLAGS += -I$(top_srcdir)/hw/xfree86/parser \
 	-I$(top_srcdir)/hw/xfree86/ddc \
 	-I$(top_srcdir)/hw/xfree86/i2c -I$(top_srcdir)/hw/xfree86/modes \
 	-I$(top_srcdir)/hw/xfree86/ramdac -I$(top_srcdir)/hw/xfree86/dri \
diff --git a/test/xi2/Makefile.am b/test/xi2/Makefile.am
index 9de7abf..bfddfef 100644
--- a/test/xi2/Makefile.am
+++ b/test/xi2/Makefile.am
@@ -17,7 +17,7 @@ TESTS=$(noinst_PROGRAMS)
 TESTS_ENVIRONMENT = $(XORG_MALLOC_DEBUG_ENV)
 
 AM_CFLAGS = $(DIX_CFLAGS) @XORG_CFLAGS@
-INCLUDES = @XORG_INCS@
+AM_CPPFLAGS = @XORG_INCS@
 TEST_LDADD=../libxservertest.la $(XORG_SYS_LIBS) $(XSERVER_SYS_LIBS) $(GLX_SYS_LIBS)
 COMMON_SOURCES=protocol-common.h protocol-common.c
 
commit c218ba8423a73a7a643cb17789db8a1dd0901ca6
Author: Julien Cristau <jcristau at debian.org>
Date:   Fri Aug 2 20:07:36 2013 +0200

    xfree86: improve check for posix saved ids
    
    Replace hardcoded SVR4 || linux || CSRG_BASED with an autoconf check and
    the _POSIX_SAVED_IDS macro.
    
    Suggested-by: Mark Kettenis <mark.kettenis at xs4all.nl>
    Signed-off-by: Julien Cristau <jcristau at debian.org>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Mark Kettenis <kettenis at openbsd.org>.
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/configure.ac b/configure.ac
index c6ecba4..d27ca23 100644
--- a/configure.ac
+++ b/configure.ac
@@ -215,7 +215,7 @@ AC_SUBST(DLOPEN_LIBS)
 dnl Checks for library functions.
 AC_CHECK_FUNCS([backtrace ffs geteuid getuid issetugid getresuid \
 	getdtablesize getifaddrs getpeereid getpeerucred getzoneid \
-	mmap shmctl64 strncasecmp vasprintf vsnprintf walkcontext])
+	mmap seteuid shmctl64 strncasecmp vasprintf vsnprintf walkcontext])
 AC_REPLACE_FUNCS([strcasecmp strcasestr strlcat strlcpy strndup])
 
 dnl Find the math libary, then check for cbrt function in it.
diff --git a/hw/xfree86/parser/write.c b/hw/xfree86/parser/write.c
index 9c706a0..26739b9 100644
--- a/hw/xfree86/parser/write.c
+++ b/hw/xfree86/parser/write.c
@@ -55,6 +55,7 @@
 #include <xorg-config.h>
 #endif
 
+#include "os.h"
 #include "xf86Parser.h"
 #include "xf86tokens.h"
 #include "Configint.h"
@@ -65,7 +66,7 @@
 #include <signal.h>
 #include <errno.h>
 
-#if defined(SVR4) || defined(__linux__) || defined(CSRG_BASED)
+#if defined(HAVE_SETEUID) && defined(_POSIX_SAVED_IDS) && _POSIX_SAVED_IDS > 0
 #define HAS_SAVED_IDS_AND_SETEUID
 #endif
 #if defined(WIN32)
diff --git a/include/xorg-config.h.in b/include/xorg-config.h.in
index a71b25d..0df31ae 100644
--- a/include/xorg-config.h.in
+++ b/include/xorg-config.h.in
@@ -139,4 +139,7 @@
 /* Have X server platform bus support */
 #undef XSERVER_PLATFORM_BUS
 
+/* Define to 1 if you have the `seteuid' function. */
+#undef HAVE_SETEUID
+
 #endif /* _XORG_CONFIG_H_ */
commit 930c6ff15d437dfb0f897e8cb4253abba70819cc
Author: Julien Cristau <jcristau at debian.org>
Date:   Fri Aug 2 23:46:00 2013 +0200

    test: include dix-config.h in hashtabletest.c
    
    Missing _XSERVER64 define caused inconsistent sizeof(XID) between the
    test and hashtable code, leading to test failures on 64bit big endian
    archs like s390x or ppc64.
    
    Signed-off-by: Julien Cristau <jcristau at debian.org>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/test/hashtabletest.c b/test/hashtabletest.c
index 64c7091..6af14a8 100644
--- a/test/hashtabletest.c
+++ b/test/hashtabletest.c
@@ -1,3 +1,7 @@
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
 #include <misc.h>
 #include <stdlib.h>
 #include <stdio.h>
commit b6e5c4669e0db391966deb397e8c975ec7f0124d
Author: Maarten Lankhorst <maarten.lankhorst at canonical.com>
Date:   Tue Jul 30 15:31:24 2013 +0200

    test/xi2: fix protocol-xiqueryversion test
    
    The old code was broken and allowed setting client version >= XIVersion,
    this was fixed in the previous patch, but updating the value for XIVersion
    broke the tests, so fix the tests too.
    
    Signed-off-by: Maarten Lankhorst <maarten.lankhorst at canonical.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/test/xi2/protocol-xiqueryversion.c b/test/xi2/protocol-xiqueryversion.c
index aff0237..ed75c89 100644
--- a/test/xi2/protocol-xiqueryversion.c
+++ b/test/xi2/protocol-xiqueryversion.c
@@ -44,8 +44,8 @@
 #include "extinit.h"            /* for XInputExtensionInit */
 #include "scrnintstr.h"
 #include "xiqueryversion.h"
-
 #include "protocol-common.h"
+#include "exglobals.h"
 
 extern XExtensionVersion XIVersion;
 
@@ -54,8 +54,8 @@ struct test_data {
     int minor_client;
     int major_server;
     int minor_server;
-    int major_cached;
-    int minor_cached;
+    int major_expected;
+    int minor_expected;
 };
 
 static void
@@ -93,13 +93,8 @@ reply_XIQueryVersion_multiple(ClientPtr client, int len, char *data, void *closu
     reply_check_defaults(rep, len, XIQueryVersion);
     assert(rep->length == 0);
 
-    if (versions->major_cached == -1) {
-        versions->major_cached = rep->major_version;
-        versions->minor_cached = rep->minor_version;
-    }
-
-    assert(versions->major_cached == rep->major_version);
-    assert(versions->minor_cached == rep->minor_version);
+    assert(versions->major_expected == rep->major_version);
+    assert(versions->minor_expected == rep->minor_version);
 }
 
 /**
@@ -199,6 +194,7 @@ test_XIQueryVersion_multiple(void)
 {
     xXIQueryVersionReq request;
     ClientRec client;
+    XIClientPtr pXIClient;
     struct test_data versions;
     int rc;
 
@@ -213,28 +209,26 @@ test_XIQueryVersion_multiple(void)
     userdata = (void *) &versions;
 
     /* run 1 */
-    versions.major_cached = -1;
-    versions.minor_cached = -1;
 
-    /* client is lower than server, noncached */
-    request.major_version = 2;
-    request.minor_version = 1;
+    /* client is lower than server, nonexpected */
+    versions.major_expected = request.major_version = 2;
+    versions.minor_expected = request.minor_version = 1;
     rc = ProcXIQueryVersion(&client);
     assert(rc == Success);
 
-    /* client is higher than server, cached */
+    /* client is higher than server, no change */
     request.major_version = 2;
     request.minor_version = 3;
     rc = ProcXIQueryVersion(&client);
     assert(rc == Success);
 
-    /* client is equal, cached */
+    /* client tries to set higher version, stays same */
     request.major_version = 2;
     request.minor_version = 2;
     rc = ProcXIQueryVersion(&client);
     assert(rc == Success);
 
-    /* client is low than cached */
+    /* client tries to set lower version, no change */
     request.major_version = 2;
     request.minor_version = 0;
     rc = ProcXIQueryVersion(&client);
@@ -243,20 +237,24 @@ test_XIQueryVersion_multiple(void)
     /* run 2 */
     client = init_client(request.length, &request);
     XIVersion.major_version = 2;
-    XIVersion.minor_version = 2;
-    versions.major_cached = -1;
-    versions.minor_cached = -1;
+    XIVersion.minor_version = 3;
 
-    request.major_version = 2;
-    request.minor_version = 2;
+    versions.major_expected = request.major_version = 2;
+    versions.minor_expected = request.minor_version = 2;
     rc = ProcXIQueryVersion(&client);
     assert(rc == Success);
 
+    /* client bumps version from 2.2 to 2.3 */
     request.major_version = 2;
-    request.minor_version = 3;
+    versions.minor_expected = request.minor_version = 3;
     rc = ProcXIQueryVersion(&client);
     assert(rc == Success);
 
+    /* real version is changed, too! */
+    pXIClient = dixLookupPrivate(&client.devPrivates, XIClientPrivateKey);
+    assert(pXIClient->minor_version == 3);
+
+    /* client tries to set lower version, no change */
     request.major_version = 2;
     request.minor_version = 1;
     rc = ProcXIQueryVersion(&client);
@@ -265,20 +263,22 @@ test_XIQueryVersion_multiple(void)
     /* run 3 */
     client = init_client(request.length, &request);
     XIVersion.major_version = 2;
-    XIVersion.minor_version = 2;
-    versions.major_cached = -1;
-    versions.minor_cached = -1;
+    XIVersion.minor_version = 3;
 
-    request.major_version = 2;
-    request.minor_version = 3;
+    versions.major_expected = request.major_version = 2;
+    versions.minor_expected = request.minor_version = 3;
     rc = ProcXIQueryVersion(&client);
     assert(rc == Success);
 
     request.major_version = 2;
-    request.minor_version = 2;
+    versions.minor_expected = request.minor_version = 2;
     rc = ProcXIQueryVersion(&client);
     assert(rc == Success);
 
+    /* but real client version must not be lowered */
+    pXIClient = dixLookupPrivate(&client.devPrivates, XIClientPrivateKey);
+    assert(pXIClient->minor_version == 3);
+
     request.major_version = 2;
     request.minor_version = 1;
     rc = ProcXIQueryVersion(&client);
commit 500e844a24962c9e70abb3d614f1973013b2de73
Author: Maarten Lankhorst <maarten.lankhorst at canonical.com>
Date:   Tue Jul 30 14:45:21 2013 +0200

    Xi: Clamp XIClient maximal version to XIVersion
    
    Do not allow setting client version to an arbitrary value >= XIVersion.
    Fixes a test error with test/xi2/protocol-xiqueryversion.c, introduced by
    commit 4360514d1c "Xi: Allow clients to ask for 2.3 and then 2.2 without failing"
    
    Signed-off-by: Maarten Lankhorst <maarten.lankhorst at canonical.com>
    Reviewed-by: Keith Packard <keithp at keithp.com>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xi/xiqueryversion.c b/Xi/xiqueryversion.c
index 6c7b9c0..c705f78 100644
--- a/Xi/xiqueryversion.c
+++ b/Xi/xiqueryversion.c
@@ -70,12 +70,21 @@ ProcXIQueryVersion(ClientPtr client)
 
     pXIClient = dixLookupPrivate(&client->devPrivates, XIClientPrivateKey);
 
+    if (version_compare(XIVersion.major_version, XIVersion.minor_version,
+                stuff->major_version, stuff->minor_version) > 0) {
+        major = stuff->major_version;
+        minor = stuff->minor_version;
+    } else {
+        major = XIVersion.major_version;
+        minor = XIVersion.minor_version;
+    }
+
     if (pXIClient->major_version) {
 
         /* Check to see if the client has only ever asked
          * for version 2.2 or higher
          */
-        if (version_compare(stuff->major_version, stuff->minor_version, 2, 2) >= 0 &&
+        if (version_compare(major, minor, 2, 2) >= 0 &&
             version_compare(pXIClient->major_version, pXIClient->minor_version, 2, 2) >= 0)
         {
 
@@ -84,16 +93,14 @@ ProcXIQueryVersion(ClientPtr client)
              * version to the client but leave the server internal
              * version set to the highest requested value
              */
-            major = stuff->major_version;
-            minor = stuff->minor_version;
-            if (version_compare(stuff->major_version, stuff->minor_version,
+            if (version_compare(major, minor,
                                 pXIClient->major_version, pXIClient->minor_version) > 0)
             {
-                pXIClient->major_version = stuff->major_version;
-                pXIClient->minor_version = stuff->minor_version;
+                pXIClient->major_version = major;
+                pXIClient->minor_version = minor;
             }
         } else {
-            if (version_compare(stuff->major_version, stuff->minor_version,
+            if (version_compare(major, minor,
                                 pXIClient->major_version, pXIClient->minor_version) < 0) {
 
                 client->errorValue = stuff->major_version;
@@ -103,16 +110,6 @@ ProcXIQueryVersion(ClientPtr client)
             minor = pXIClient->minor_version;
         }
     } else {
-        if (version_compare(XIVersion.major_version, XIVersion.minor_version,
-                    stuff->major_version, stuff->minor_version) > 0) {
-            major = stuff->major_version;
-            minor = stuff->minor_version;
-        }
-        else {
-            major = XIVersion.major_version;
-            minor = XIVersion.minor_version;
-        }
-
         pXIClient->major_version = major;
         pXIClient->minor_version = minor;
     }
commit e1ab8f239bdc6af17ef6cd0e9c6187c4e2e2f5bc
Author: Dave Airlie <airlied at redhat.com>
Date:   Wed Jul 31 11:35:44 2013 +1000

    xfree86/man: document AutoAddGPU
    
    This at least mentions AutoAddGPU and hints at when you might
    want to disable it.
    
    Signed-off-by: Dave Airlie <airlied at redhat.com>
    Reviewed-by: Alex Deucher <alexander.deucher at amd.com>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/xfree86/man/xorg.conf.man b/hw/xfree86/man/xorg.conf.man
index fa5b5fe..85f9f2e 100644
--- a/hw/xfree86/man/xorg.conf.man
+++ b/hw/xfree86/man/xorg.conf.man
@@ -668,6 +668,10 @@ DevicePresenceNotify event sent), but not enabled, thus leaving policy up
 to the client.
 Enabled by default.
 .TP 7
+.BI "Option \*qAutoAddGPU\*q \*q" boolean \*q
+If this option is disabled, then no GPU devices will be added from the udev
+backend. Enabled by default. (May need to be disabled to setup Xinerama).
+.TP 7
 .BI "Option \*qLog\*q \*q" string \*q
 This option controls whether the log is flushed and/or synced to disk after
 each message.
commit ff38bbe81ace85bf675bbaa0a9ca5f3b32ede449
Merge: bdd1e22 4360514
Author: Keith Packard <keithp at keithp.com>
Date:   Thu Jul 25 22:50:27 2013 -0700

    Merge remote-tracking branch 'whot/for-keith'

commit 4360514d1cc8e3132f93f56172d291074e8c770f
Author: Keith Packard <keithp at keithp.com>
Date:   Wed Jul 10 22:42:55 2013 -0700

    Xi: Allow clients to ask for 2.3 and then 2.2 without failing
    
    This allows different sub-systems within the same application to
    request different Xi versions without either getting old behaviour
    everywhere or simply failing with a BadValue.
    
    Signed-off-by: Keith Packard <keithp at keithp.com>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xi/xiqueryversion.c b/Xi/xiqueryversion.c
index b807a53..6c7b9c0 100644
--- a/Xi/xiqueryversion.c
+++ b/Xi/xiqueryversion.c
@@ -71,13 +71,37 @@ ProcXIQueryVersion(ClientPtr client)
     pXIClient = dixLookupPrivate(&client->devPrivates, XIClientPrivateKey);
 
     if (pXIClient->major_version) {
-        if (version_compare(stuff->major_version, stuff->minor_version,
-                            pXIClient->major_version, pXIClient->minor_version) < 0) {
-            client->errorValue = stuff->major_version;
-            return BadValue;
+
+        /* Check to see if the client has only ever asked
+         * for version 2.2 or higher
+         */
+        if (version_compare(stuff->major_version, stuff->minor_version, 2, 2) >= 0 &&
+            version_compare(pXIClient->major_version, pXIClient->minor_version, 2, 2) >= 0)
+        {
+
+            /* As of version 2.2, Peter promises to never again break
+             * backward compatibility, so we'll return the requested
+             * version to the client but leave the server internal
+             * version set to the highest requested value
+             */
+            major = stuff->major_version;
+            minor = stuff->minor_version;
+            if (version_compare(stuff->major_version, stuff->minor_version,
+                                pXIClient->major_version, pXIClient->minor_version) > 0)
+            {
+                pXIClient->major_version = stuff->major_version;
+                pXIClient->minor_version = stuff->minor_version;
+            }
+        } else {
+            if (version_compare(stuff->major_version, stuff->minor_version,
+                                pXIClient->major_version, pXIClient->minor_version) < 0) {
+
+                client->errorValue = stuff->major_version;
+                return BadValue;
+            }
+            major = pXIClient->major_version;
+            minor = pXIClient->minor_version;
         }
-        major = pXIClient->major_version;
-        minor = pXIClient->minor_version;
     } else {
         if (version_compare(XIVersion.major_version, XIVersion.minor_version,
                     stuff->major_version, stuff->minor_version) > 0) {
commit bdd1e22cbde9ea2324e4e1991c9e152f22f88151
Author: Aaron Plattner <aplattner at nvidia.com>
Date:   Tue Apr 30 14:14:23 2013 -0700

    xfree86: detach scanout pixmaps when detaching output GPUs
    
    Commit 8f4640bdb9d3988148e09a08d2c7e3bab1d538d6 fixed a bit of a
    chicken-and-egg problem by detaching GPU screens when their providers
    are destroyed, which happens before CloseScreen is called.  However,
    this created a new problem: the GPU screen tears down its RandR crtc
    objects during CloseScreen and if one of them is active, it tries to
    detach the scanout pixmap then.  This crashes because
    RRCrtcDetachScanoutPixmap tries to get the master screen's screen
    pixmap, but crtc->pScreen->current_master is already NULL at that
    point.
    
    It doesn't make sense for an unbound GPU screen to still be scanning
    out its former master screen's pixmap, so detach them first when the
    provider is destroyed.
    
    Signed-off-by: Aaron Plattner <aplattner at nvidia.com>
    Reviewed-by: Dave Airlie <airlied at redhat.com>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/xfree86/modes/xf86RandR12.c b/hw/xfree86/modes/xf86RandR12.c
index 2817aaa..76614de 100644
--- a/hw/xfree86/modes/xf86RandR12.c
+++ b/hw/xfree86/modes/xf86RandR12.c
@@ -1771,6 +1771,19 @@ xf86RandR12EnterVT(ScrnInfoPtr pScrn)
     return RRGetInfo(pScreen, TRUE);    /* force a re-probe of outputs and notify clients about changes */
 }
 
+static void
+xf86DetachOutputGPU(ScreenPtr pScreen)
+{
+    rrScrPrivPtr rp = rrGetScrPriv(pScreen);
+    int i;
+
+    /* make sure there are no attached shared scanout pixmaps first */
+    for (i = 0; i < rp->numCrtcs; i++)
+        RRCrtcDetachScanoutPixmap(rp->crtcs[i]);
+
+    DetachOutputGPU(pScreen);
+}
+
 static Bool
 xf86RandR14ProviderSetOutputSource(ScreenPtr pScreen,
                                    RRProviderPtr provider,
@@ -1780,7 +1793,7 @@ xf86RandR14ProviderSetOutputSource(ScreenPtr pScreen,
         if (provider->output_source) {
             ScreenPtr cmScreen = pScreen->current_master;
 
-            DetachOutputGPU(pScreen);
+            xf86DetachOutputGPU(pScreen);
             AttachUnboundGPU(cmScreen, pScreen);
         }
         provider->output_source = NULL;
@@ -1808,7 +1821,7 @@ xf86RandR14ProviderSetOffloadSink(ScreenPtr pScreen,
     if (!sink_provider) {
         if (provider->offload_sink) {
             ScreenPtr cmScreen = pScreen->current_master;
-            DetachOutputGPU(pScreen);
+            xf86DetachOutputGPU(pScreen);
             AttachUnboundGPU(cmScreen, pScreen);
         }
 
@@ -1899,7 +1912,7 @@ xf86RandR14ProviderDestroy(ScreenPtr screen, RRProviderPtr provider)
             RRSetChanged(screen);
         }
         else if (config->randr_provider->output_source) {
-            DetachOutputGPU(screen);
+            xf86DetachOutputGPU(screen);
             config->randr_provider->output_source = NULL;
             RRSetChanged(screen);
         }
commit 3d8756631070c440cefa31b35fea3d407f187810
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Jul 22 13:43:07 2013 +1000

    dix: set the valuator mask to ensure XI 1.x events have data
    
    XI 1.x only allows for first + num valuators, so if a device sends data for
    valuators 0 and 2+ only (i.e. valuator 1 is missing) we still need to get
    the data for that from somewhere.
    XI 1.x uses the hack of an unset valuator mask to get the right coordinates,
    i.e. we set the value but don't set the mask for it so XI2 events have the
    right mask.
    
    For an absolute device in relative mode, this broke in b28a1af55cf, the
    value was now always 0. This wasn't visible on the cursor, only in an XI 1.x
    client. The GIMP e.g. sees jumps to x/0 every few events.
    
    Drop the condition introduced in b28a1af55cf, data in valuators is always
    absolute, regardless of the mode.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/getevents.c b/dix/getevents.c
index f5ab8c4..14b65ca 100644
--- a/dix/getevents.c
+++ b/dix/getevents.c
@@ -239,7 +239,7 @@ set_valuators(DeviceIntPtr dev, DeviceEvent *event, ValuatorMask *mask)
                 SetBit(event->valuators.mode, i);
             event->valuators.data[i] = valuator_mask_get_double(mask, i);
         }
-        else if (valuator_get_mode(dev, i) == Absolute)
+        else
             event->valuators.data[i] = dev->valuator->axisVal[i];
     }
 }
commit 4fb686d6a6777950f0e0d55b848cd2af4cbad372
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Jul 24 11:50:00 2013 +1000

    dix: check the xi2mask, not the grab type for touch listeners
    
    grab->type is only non-zero for passive grabs. We're checking an active grab
    here, so we need to check if the touch mask is set on the grab.
    
    Test case: grab the device, then start two simultaneous touches. The
    grabbing client won't see the second touchpoints because grab->type is 0
    and the second touch is not an emulating pointer.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/touch.c b/dix/touch.c
index a4b6d7e..a7ea213 100644
--- a/dix/touch.c
+++ b/dix/touch.c
@@ -895,8 +895,7 @@ TouchAddActiveGrabListener(DeviceIntPtr dev, TouchPointInfoPtr ti,
 
     if (!ti->emulate_pointer &&
         grab->grabtype == XI2 &&
-        (grab->type != XI_TouchBegin && grab->type != XI_TouchEnd &&
-         grab->type != XI_TouchUpdate))
+        !xi2mask_isset(grab->xi2mask, dev, XI_TouchBegin))
         return;
 
     TouchAddGrabListener(dev, ti, ev, grab);
diff --git a/include/inputstr.h b/include/inputstr.h
index 85be885..2da72c1 100644
--- a/include/inputstr.h
+++ b/include/inputstr.h
@@ -195,7 +195,7 @@ typedef struct _GrabRec {
     unsigned keyboardMode:1;
     unsigned pointerMode:1;
     enum InputLevel grabtype;
-    CARD8 type;                 /* event type */
+    CARD8 type;                 /* event type for passive grabs, 0 for active grabs */
     DetailRec modifiersDetail;
     DeviceIntPtr modifierDevice;
     DetailRec detail;           /* key or button */
commit 43ac0491e36cdbb716b5c9d39c97d0aba3bebd75
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Mon Apr 8 01:28:36 2013 +0100

    hw/xwin: Fix numerous 64-bit format/type cast issues with debug printing of pointers
    
    Numerous pieces of debug output cast a pointer to an int and then use a "%08x"
    printf format.
    
    Use "%p" format for 64-bit portability.
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/winfillsp.c b/hw/xwin/winfillsp.c
index f2432ed..bd0a15e 100644
--- a/hw/xwin/winfillsp.c
+++ b/hw/xwin/winfillsp.c
@@ -118,7 +118,7 @@ winFillSpansNativeGDI(DrawablePtr pDrawable,
         if (hbmpOrig == NULL)
             FatalError("winFillSpans - DRAWABLE_PIXMAP - "
                        "SelectObject () failed on\n\tpPixmapPriv->hBitmap: "
-                       "%08x\n", (unsigned int) pPixmapPriv->hBitmap);
+                       "%p\n", pPixmapPriv->hBitmap);
 
         /* Branch on the fill type */
         switch (pGC->fillStyle) {
diff --git a/hw/xwin/winscrinit.c b/hw/xwin/winscrinit.c
index 5623b88..23152cb 100644
--- a/hw/xwin/winscrinit.c
+++ b/hw/xwin/winscrinit.c
@@ -703,7 +703,7 @@ winFinishScreenInitNativeGDI(int i,
     pScreenPriv->fEnabled = TRUE;
 
     ErrorF("winFinishScreenInitNativeGDI - Successful addition of "
-           "screen %08x\n", (unsigned int) pScreen);
+           "screen %p\n", pScreen);
 
     return TRUE;
 }
diff --git a/hw/xwin/winwin32rootless.c b/hw/xwin/winwin32rootless.c
index 210fea3..724976a 100644
--- a/hw/xwin/winwin32rootless.c
+++ b/hw/xwin/winwin32rootless.c
@@ -312,8 +312,8 @@ winMWExtWMCreateFrame(RootlessWindowPtr pFrame, ScreenPtr pScreen,
     }
 
 #if CYGMULTIWINDOW_DEBUG
-    winDebug("winMWExtWMCreateFrame - (%08x) %08x\n",
-             (int) pFrame->wid, (int) pRLWinPriv->hWnd);
+    winDebug("winMWExtWMCreateFrame - (%p) %p\n",
+             pFrame->wid, pRLWinPriv->hWnd);
 #if 0
     {
         WindowPtr pWin2 = NULL;
@@ -350,8 +350,8 @@ winMWExtWMDestroyFrame(RootlessFrameID wid)
     char pszClass[CLASS_NAME_LENGTH];
 
 #if CYGMULTIWINDOW_DEBUG
-    winDebug("winMWExtWMDestroyFrame (%08x) %08x\n",
-             (int) pRLWinPriv, (int) pRLWinPriv->hWnd);
+    winDebug("winMWExtWMDestroyFrame (%p) %p\n",
+             pRLWinPriv, pRLWinPriv->hWnd);
 #if 0
     {
         WindowPtr pWin2 = NULL;
@@ -416,7 +416,7 @@ winMWExtWMMoveFrame(RootlessFrameID wid, ScreenPtr pScreen, int iNewX,
     int iX, iY, iWidth, iHeight;
 
 #if CYGMULTIWINDOW_DEBUG
-    winDebug("winMWExtWMMoveFrame (%08x) (%d %d)\n", (int) pRLWinPriv, iNewX,
+    winDebug("winMWExtWMMoveFrame (%p) (%d %d)\n", pRLWinPriv, iNewX,
              iNewY);
 #endif
 
@@ -456,7 +456,7 @@ winMWExtWMMoveFrame(RootlessFrameID wid, ScreenPtr pScreen, int iNewX,
                  SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER);
     g_fNoConfigureWindow = FALSE;
 #if CYGMULTIWINDOW_DEBUG
-    winDebug("winMWExtWMMoveFrame (%08x) done\n", (int) pRLWinPriv);
+    winDebug("winMWExtWMMoveFrame (%p) done\n", pRLWinPriv);
 #endif
 }
 
@@ -474,8 +474,8 @@ winMWExtWMResizeFrame(RootlessFrameID wid, ScreenPtr pScreen,
     int iX, iY;
 
 #if CYGMULTIWINDOW_DEBUG
-    winDebug("winMWExtWMResizeFrame (%08x) (%d %d)-(%d %d)\n",
-             (int) pRLWinPriv, iNewX, iNewY, uiNewWidth, uiNewHeight);
+    winDebug("winMWExtWMResizeFrame (%p) (%d %d)-(%d %d)\n",
+             pRLWinPriv, iNewX, iNewY, uiNewWidth, uiNewHeight);
 #endif
 
     pRLWinPriv->fResized = TRUE;
@@ -526,7 +526,7 @@ winMWExtWMRestackFrame(RootlessFrameID wid, RootlessFrameID nextWid)
     Bool fNeedRestack = TRUE;
 
 #if CYGMULTIWINDOW_DEBUG
-    winDebug("winMWExtWMRestackFrame (%08x)\n", (int) pRLWinPriv);
+    winDebug("winMWExtWMRestackFrame (%p)\n", pRLWinPriv);
 #endif
 
     if (pScreenPriv && pScreenPriv->fRestacking)
@@ -612,7 +612,7 @@ winMWExtWMRestackFrame(RootlessFrameID wid, RootlessFrameID nextWid)
                      0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
     }
 #if CYGMULTIWINDOW_DEBUG
-    winDebug("winMWExtWMRestackFrame - done (%08x)\n", (int) pRLWinPriv);
+    winDebug("winMWExtWMRestackFrame - done (%p)\n", pRLWinPriv);
 #endif
 
     pRLWinPriv->fRestackingNow = FALSE;
@@ -626,7 +626,7 @@ winMWExtWMReshapeFrame(RootlessFrameID wid, RegionPtr pShape)
     RECT rcWindow, rcClient;
 
 #if CYGMULTIWINDOW_DEBUG
-    winDebug("winMWExtWMReshapeFrame (%08x)\n", (int) pRLWinPriv);
+    winDebug("winMWExtWMReshapeFrame (%p)\n", pRLWinPriv);
 #endif
 
     hRgn = winMWExtWMCreateRgnFromRegion(pShape);
@@ -655,7 +655,7 @@ winMWExtWMUnmapFrame(RootlessFrameID wid)
     win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) wid;
 
 #if CYGMULTIWINDOW_DEBUG
-    winDebug("winMWExtWMUnmapFrame (%08x)\n", (int) pRLWinPriv);
+    winDebug("winMWExtWMUnmapFrame (%p)\n", pRLWinPriv);
 #endif
 
     g_fNoConfigureWindow = TRUE;
@@ -680,7 +680,7 @@ winMWExtWMStartDrawing(RootlessFrameID wid, char **pixelData, int *bytesPerRow)
     HBITMAP hbmpNew;
 
 #if CYGMULTIWINDOW_DEBUG
-    winDebug("winMWExtWMStartDrawing (%08x) %08x\n", (int) pRLWinPriv,
+    winDebug("winMWExtWMStartDrawing (%p) %08x\n", pRLWinPriv,
              pRLWinPriv->fDestroyed);
 #endif
 
@@ -692,8 +692,8 @@ winMWExtWMStartDrawing(RootlessFrameID wid, char **pixelData, int *bytesPerRow)
             pScreenInfo = pScreenPriv->pScreenInfo;
 
 #if CYGMULTIWINDOW_DEBUG
-        winDebug("\tpScreenPriv %08X\n", (int) pScreenPriv);
-        winDebug("\tpScreenInfo %08X\n", (int) pScreenInfo);
+        winDebug("\tpScreenPriv %p\n", pScreenPriv);
+        winDebug("\tpScreenInfo %p\n", pScreenInfo);
         winDebug("\t(%d, %d)\n", (int) pRLWinPriv->pFrame->width,
                  (int) pRLWinPriv->pFrame->height);
 #endif
@@ -808,9 +808,9 @@ winMWExtWMStartDrawing(RootlessFrameID wid, char **pixelData, int *bytesPerRow)
         ErrorF("winMWExtWMStartDrawing - Already window was destroyed \n");
     }
 #if CYGMULTIWINDOW_DEBUG
-    winDebug("winMWExtWMStartDrawing - done (0x%08x) 0x%08x %d\n",
-             (int) pRLWinPriv,
-             (unsigned int) pRLWinPriv->pfb,
+    winDebug("winMWExtWMStartDrawing - done (%p) %p %d\n",
+             pRLWinPriv,
+             pRLWinPriv->pfb,
              (unsigned int) pRLWinPriv->dwWidthBytes);
 #endif
     *pixelData = pRLWinPriv->pfb;
@@ -924,8 +924,8 @@ winMWExtWMRootlessSwitchWindow(RootlessWindowPtr pFrame, WindowPtr oldWin)
     win32RootlessWindowPtr pRLWinPriv = (win32RootlessWindowPtr) pFrame->wid;
 
 #if CYGMULTIWINDOW_DEBUG
-    winDebug("winMWExtWMRootlessSwitchWindow (%08x) %08x\n",
-             (int) pRLWinPriv, (int) pRLWinPriv->hWnd);
+    winDebug("winMWExtWMRootlessSwitchWindow (%p) %p\n",
+             pRLWinPriv, pRLWinPriv->hWnd);
 #endif
     pRLWinPriv->pFrame = pFrame;
     pRLWinPriv->fResized = TRUE;
@@ -979,8 +979,8 @@ winMWExtWMCopyWindow(RootlessFrameID wid, int nDstRects,
     RECT rcDmg;
 
 #if CYGMULTIWINDOW_DEBUG
-    winDebug("winMWExtWMCopyWindow (%08x, %d, %08x, %d, %d)\n",
-             (int) pRLWinPriv, nDstRects, (int) pDstRects, nDx, nDy);
+    winDebug("winMWExtWMCopyWindow (%p, %d, %p, %d, %d)\n",
+             pRLWinPriv, nDstRects, pDstRects, nDx, nDy);
 #endif
 
     for (pEnd = pDstRects + nDstRects; pDstRects < pEnd; pDstRects++) {
diff --git a/hw/xwin/winwin32rootlesswindow.c b/hw/xwin/winwin32rootlesswindow.c
index ce615e6..1faa531 100644
--- a/hw/xwin/winwin32rootlesswindow.c
+++ b/hw/xwin/winwin32rootlesswindow.c
@@ -213,8 +213,8 @@ winMWExtWMUpdateWindowDecoration(win32RootlessWindowPtr pRLWinPriv,
 
     showCmd |= SWP_NOMOVE | SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOZORDER;
 
-    winDebug("winMWExtWMUpdateWindowDecoration %08x %s\n",
-             (int) pRLWinPriv, fDecorate ? "Decorate" : "Bare");
+    winDebug("winMWExtWMUpdateWindowDecoration %p %s\n",
+             pRLWinPriv, fDecorate ? "Decorate" : "Bare");
 
     /* Get the extended window style information */
     dwExStyle = GetWindowLongPtr(pRLWinPriv->hWnd, GWL_EXSTYLE);
diff --git a/hw/xwin/winwin32rootlesswndproc.c b/hw/xwin/winwin32rootlesswndproc.c
index be29583..001d0d2 100644
--- a/hw/xwin/winwin32rootlesswndproc.c
+++ b/hw/xwin/winwin32rootlesswndproc.c
@@ -832,24 +832,24 @@ winMWExtWMWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
         if (!(pWinPos->flags & SWP_NOZORDER)) {
             if (pRLWinPriv->fRestackingNow || pScreenPriv->fRestacking) {
 #if CYGMULTIWINDOW_DEBUG
-                winDebug("Win %08x is now restacking.\n",
-                         (unsigned int) pRLWinPriv);
+                winDebug("Win %p is now restacking.\n",
+                         pRLWinPriv);
 #endif
                 break;
             }
 
             if (winIsInternalWMRunning(pScreenInfo) || IsRaiseOnClick(pWin)) {
 #if CYGMULTIWINDOW_DEBUG
-                winDebug("Win %08x has WINDOWSWM_RAISE_ON_CLICK.\n",
-                         (unsigned int) pRLWinPriv);
+                winDebug("Win %p has WINDOWSWM_RAISE_ON_CLICK.\n",
+                         pRLWinPriv);
 #endif
                 break;
             }
 
 #if CYGMULTIWINDOW_DEBUG
-            winDebug("Win %08x forbid to change z order (%08x).\n",
-                     (unsigned int) pRLWinPriv,
-                     (unsigned int) pWinPos->hwndInsertAfter);
+            winDebug("Win %p forbid to change z order (%p).\n",
+                     pRLWinPriv,
+                     pWinPos->hwndInsertAfter);
 #endif
             pWinPos->flags |= SWP_NOZORDER;
         }
diff --git a/hw/xwin/winwindowswm.c b/hw/xwin/winwindowswm.c
index 6e9d63c..be43265 100644
--- a/hw/xwin/winwindowswm.c
+++ b/hw/xwin/winwindowswm.c
@@ -246,7 +246,7 @@ winWindowsWMSendEvent(int type, unsigned int mask, int which, int arg,
     for (pEvent = *pHead; pEvent; pEvent = pEvent->next) {
         client = pEvent->client;
 #if CYGMULTIWINDOW_DEBUG
-        ErrorF("winWindowsWMSendEvent - x%08x\n", (int) client);
+        ErrorF("winWindowsWMSendEvent - %p\n", client);
 #endif
         if ((pEvent->mask & mask) == 0) {
             continue;
@@ -381,8 +381,8 @@ ProcWindowsWMFrameDraw(ClientPtr client)
         return BadWindow;
 
 #if CYGMULTIWINDOW_DEBUG
-    ErrorF("ProcWindowsWMFrameDraw - HWND 0x%08x 0x%08x 0x%08x\n",
-           (int) pRLWinPriv->hWnd, (int) stuff->frame_style,
+    ErrorF("ProcWindowsWMFrameDraw - HWND %p 0x%08x 0x%08x\n",
+           pRLWinPriv->hWnd, (int) stuff->frame_style,
            (int) stuff->frame_style_ex);
     ErrorF("ProcWindowsWMFrameDraw - %d %d %d %d\n",
            stuff->ix, stuff->iy, stuff->iw, stuff->ih);
commit e95bb97073ca77193e4c51bd1504403fbe245533
Author: Colin Harrison <colin.harrison at virgin.net>
Date:   Tue Jun 25 21:34:43 2013 +0100

    hw/xwin: Fix possible crash in winMultiWindowGetClassHint
    
    Fix a possible crash in winMultiWindowGetClassHint() when an application doesn't
    null terminate the WM_CLASS property class name (which is an ICCCM conformance
    bug in the application)
    
    (Reported for running the contiki cooja simulator in multiwindow mode, although
    it seems that many Java clients may have this problem, see [1])
    
    Based on a patch by Marc Haesen.
    
    v2: Avoid using strnlen() which is missing on MinGW
    v3: Align with Xming patch
    
    [1] http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6961123
    
    Signed-off-by: Colin Harrison <colin.harrison at virgin.net>
    Reviewed-by: Yaakov Selkowitz <yselkowitz at users.sourceforge.net>
    Reviewed-by: Jon TURNEY <jon.turney at dronecode.org.uk>

diff --git a/hw/xwin/winmultiwindowclass.c b/hw/xwin/winmultiwindowclass.c
index ced8f45..6787332 100644
--- a/hw/xwin/winmultiwindowclass.c
+++ b/hw/xwin/winmultiwindowclass.c
@@ -68,7 +68,12 @@ winMultiWindowGetClassHint(WindowPtr pWin, char **res_name, char **res_class)
     while (prop) {
         if (prop->propertyName == XA_WM_CLASS
             && prop->type == XA_STRING && prop->format == 8 && prop->data) {
+            /*
+              WM_CLASS property should consist of 2 null terminated strings, but we
+              must handle the cases when one or both is absent or not null terminated
+            */
             len_name = strlen((char *) prop->data);
+            if (len_name > prop->size) len_name = prop->size;
 
             (*res_name) = malloc(len_name + 1);
 
@@ -77,13 +82,13 @@ winMultiWindowGetClassHint(WindowPtr pWin, char **res_name, char **res_class)
                 return 0;
             }
 
-            /* Add one to len_name to allow copying of trailing 0 */
-            strncpy((*res_name), prop->data, len_name + 1);
+            /* Copy name and ensure null terminated */
+            strncpy((*res_name), prop->data, len_name);
+            (*res_name)[len_name] = '\0';
 
-            if (len_name == prop->size)
-                len_name--;
-
-            len_class = strlen(((char *) prop->data) + 1 + len_name);
+            /* Compute length of class name, it could be that it is absent or not null terminated */
+            len_class = (len_name >= prop->size) ? 0 : (strlen(((char *) prop->data) + 1 + len_name));
+            if (len_class > prop->size - 1 - len_name) len_class = prop->size - 1 - len_name;
 
             (*res_class) = malloc(len_class + 1);
 
@@ -95,7 +100,9 @@ winMultiWindowGetClassHint(WindowPtr pWin, char **res_name, char **res_class)
                 return 0;
             }
 
-            strcpy((*res_class), ((char *) prop->data) + 1 + len_name);
+            /* Copy class name and ensure null terminated */
+            strncpy((*res_class), ((char *) prop->data) + 1 + len_name, len_class);
+            (*res_class)[len_class] = '\0';
 
             return 1;
         }
commit 4bc375aa2f08bd092f60d3e358d345fc9a0d3637
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Tue Jun 18 19:21:02 2013 +0100

    hw/xwin: Remove obsolete WIN_XEVENTS_SHUTDOWN
    
    Remove obsolete WIN_XEVENTS_SHUTDOWN.  This event is never generated.
    
    (I think the idea was to listen for WM_DELETE_WINDOW, but that's not a very
    useful thing to do for a hidden window.)
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/winclipboard.h b/hw/xwin/winclipboard.h
index 2cd775d..aa7fd44 100644
--- a/hw/xwin/winclipboard.h
+++ b/hw/xwin/winclipboard.h
@@ -66,7 +66,6 @@
 #define WIN_JMP_ERROR_IO			2
 #define WIN_LOCAL_PROPERTY			"CYGX_CUT_BUFFER"
 #define WIN_XEVENTS_SUCCESS			0
-#define WIN_XEVENTS_SHUTDOWN			1
 #define WIN_XEVENTS_CONVERT			2
 #define WIN_XEVENTS_NOTIFY			3
 #define WIN_CLIPBOARD_RETRIES			40
diff --git a/hw/xwin/winclipboardthread.c b/hw/xwin/winclipboardthread.c
index 69c654d..33595be 100644
--- a/hw/xwin/winclipboardthread.c
+++ b/hw/xwin/winclipboardthread.c
@@ -325,14 +325,7 @@ winClipboardProc(void *pvNotUsed)
         /* Branch on which descriptor became active */
         if (FD_ISSET(iConnectionNumber, &fdsRead)) {
             /* Process X events */
-            /* Exit when we see that server is shutting down */
-            iReturn = winClipboardFlushXEvents(hwnd,
-                                               iWindow, pDisplay, fUseUnicode);
-            if (WIN_XEVENTS_SHUTDOWN == iReturn) {
-                ErrorF("winClipboardProc - winClipboardFlushXEvents "
-                       "trapped shutdown event, exiting main loop.\n");
-                break;
-            }
+            winClipboardFlushXEvents(hwnd, iWindow, pDisplay, fUseUnicode);
         }
 
 #ifdef HAS_DEVWINDOWS
commit 2663203cd6994166e107e796c4724a4ed3b59370
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Tue Jun 18 18:03:05 2013 +0100

    configure.ac: Check for python at configure time when building XWin with AIGLX
    
    Check for python at configure time when building XWin with AIGLX, it's used to
    generate the wrapper code for native GL functions.
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/configure.ac b/configure.ac
index d0d0fd7..c6ecba4 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1944,6 +1944,10 @@ if test "x$XWIN" = xyes; then
 
 dnl XWin with AIGLX requires OpenGL spec files in order to generate wrapper code for native GL functions
 	if [test "x$XWIN" = xyes && test "x$AIGLX" = xyes] ; then
+           AC_CHECK_PROG(PYTHON, python, python)
+           if test -z "$PYTHON"; then
+                AC_MSG_ERROR([python not found])
+           fi
            if test "x$KHRONOS_SPEC_DIR" = "xauto" ; then
 		PKG_CHECK_MODULES([KHRONOS_OPENGL_REGISTRY], [khronos-opengl-registry])
 		KHRONOS_SPEC_DIR=`pkg-config khronos-opengl-registry --variable=specdir`
diff --git a/hw/xwin/glx/Makefile.am b/hw/xwin/glx/Makefile.am
index 59f6879..f969af2 100644
--- a/hw/xwin/glx/Makefile.am
+++ b/hw/xwin/glx/Makefile.am
@@ -33,10 +33,10 @@ AM_CFLAGS = -DHAVE_XWIN_CONFIG_H $(DIX_CFLAGS) \
 if XWIN_GLX_WINDOWS
 
 generated_gl_wrappers.c: gen_gl_wrappers.py $(KHRONOS_SPEC_DIR)/gl.spec $(KHRONOS_SPEC_DIR)/gl.tm
-	$(AM_V_GEN)$(srcdir)/gen_gl_wrappers.py --spec=$(KHRONOS_SPEC_DIR)/gl.spec --typemap=$(KHRONOS_SPEC_DIR)/gl.tm --dispatch-header=$(top_srcdir)/glx/dispatch.h --staticwrappers >generated_gl_wrappers.c
+	$(AM_V_GEN)$(PYTHON) $(srcdir)/gen_gl_wrappers.py --spec=$(KHRONOS_SPEC_DIR)/gl.spec --typemap=$(KHRONOS_SPEC_DIR)/gl.tm --dispatch-header=$(top_srcdir)/glx/dispatch.h --staticwrappers >generated_gl_wrappers.c
 
 generated_wgl_wrappers.c: gen_gl_wrappers.py $(KHRONOS_SPEC_DIR)/wglext.spec $(KHRONOS_SPEC_DIR)/wgl.tm
-	$(AM_V_GEN)$(srcdir)/gen_gl_wrappers.py --spec=$(KHRONOS_SPEC_DIR)/wglext.spec --typemap=$(KHRONOS_SPEC_DIR)/wgl.tm --prefix=wgl --preresolve >generated_wgl_wrappers.c
+	$(AM_V_GEN)$(PYTHON) $(srcdir)/gen_gl_wrappers.py --spec=$(KHRONOS_SPEC_DIR)/wglext.spec --typemap=$(KHRONOS_SPEC_DIR)/wgl.tm --prefix=wgl --preresolve >generated_wgl_wrappers.c
 endif
 
 BUILT_SOURCES = generated_gl_wrappers.c generated_wgl_wrappers.c
commit 9fe360bf2be5c959fb21835955ef550098ccbbf0
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Sun Jun 16 00:07:57 2013 +0100

    hw/xwin: Avoid a null dereference if CreateDIBSection() fails in NetWMToWinIconAlpha()
    
    Avoid a null dereference of DIB_pixels if CreateDIBSection() fails in
    NetWMToWinIconAlpha()
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/winmultiwindowicons.c b/hw/xwin/winmultiwindowicons.c
index bcc5688..0531ad6 100644
--- a/hw/xwin/winmultiwindowicons.c
+++ b/hw/xwin/winmultiwindowicons.c
@@ -257,6 +257,10 @@ NetWMToWinIconAlpha(uint32_t * icon)
                                    DIB_RGB_COLORS, (void **) &DIB_pixels, NULL,
                                    0);
     ReleaseDC(NULL, hdc);
+
+    if (!ii.hbmColor)
+      return NULL;
+
     ii.hbmMask = CreateBitmap(width, height, 1, 1, NULL);
     memcpy(DIB_pixels, pixels, height * width * 4);
 
commit 71b5f56302bbd8be62f63f0dd62cbcd33aab3ac5
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Thu Feb 21 17:12:17 2013 +0000

    hw/xwin: Handle WM_MOUSEHWHEEL
    
    Handle WM_MOUSEHWHEEL tilt wheel messages, similarly to WM_MOUSEWHEEL scroll
    wheel messages, to generate X button 6 and 7 presses and releases.
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/win.h b/hw/xwin/win.h
index 182e96b..ce89348 100644
--- a/hw/xwin/win.h
+++ b/hw/xwin/win.h
@@ -42,6 +42,11 @@
 #define YES					1
 #endif
 
+/* We can handle WM_MOUSEHWHEEL even though _WIN32_WINNT < 0x0600 */
+#ifndef WM_MOUSEHWHEEL
+#define WM_MOUSEHWHEEL 0x020E
+#endif
+
 /* Turn debug messages on or off */
 #ifndef CYGDEBUG
 #define CYGDEBUG				NO
@@ -449,6 +454,7 @@ typedef struct _winPrivScreenRec {
     Bool fBadDepth;
 
     int iDeltaZ;
+    int iDeltaV;
 
     int iConnectedClients;
 
@@ -975,7 +981,7 @@ int
  winMouseProc(DeviceIntPtr pDeviceInt, int iState);
 
 int
- winMouseWheel(ScreenPtr pScreen, int iDeltaZ);
+ winMouseWheel(int *iTotalDeltaZ, int iDeltaZ, int iButtonUp, int iButtonDown);
 
 void
  winMouseButtonsSendEvent(int iEventType, int iButton);
diff --git a/hw/xwin/winmessages.h b/hw/xwin/winmessages.h
index 3d3fab2..8282f8b 100644
--- a/hw/xwin/winmessages.h
+++ b/hw/xwin/winmessages.h
@@ -529,7 +529,7 @@ static const char *MESSAGE_NAMES[1024] = {
     "WM_XBUTTONDOWN",
     "WM_XBUTTONUP",
     "WM_XBUTTONDBLCLK",
-    "526",
+    "WM_MOUSEHWHEEL",
     "527",
     "WM_PARENTNOTIFY",
     "WM_ENTERMENULOOP",
diff --git a/hw/xwin/winmouse.c b/hw/xwin/winmouse.c
index da067cd..bbe21cb 100644
--- a/hw/xwin/winmouse.c
+++ b/hw/xwin/winmouse.c
@@ -145,20 +145,16 @@ winMouseProc(DeviceIntPtr pDeviceInt, int iState)
 
 /* Handle the mouse wheel */
 int
-winMouseWheel(ScreenPtr pScreen, int iDeltaZ)
+winMouseWheel(int *iTotalDeltaZ, int iDeltaZ, int iButtonUp, int iButtonDown)
 {
-    winScreenPriv(pScreen);
-    int button;                 /* Button4 or Button5 */
-
-    /* Button4 = WheelUp */
-    /* Button5 = WheelDown */
+    int button;
 
     /* Do we have any previous delta stored? */
-    if ((pScreenPriv->iDeltaZ > 0 && iDeltaZ > 0)
-        || (pScreenPriv->iDeltaZ < 0 && iDeltaZ < 0)) {
+    if ((*iTotalDeltaZ > 0 && iDeltaZ > 0)
+        || (*iTotalDeltaZ < 0 && iDeltaZ < 0)) {
         /* Previous delta and of same sign as current delta */
-        iDeltaZ += pScreenPriv->iDeltaZ;
-        pScreenPriv->iDeltaZ = 0;
+        iDeltaZ += *iTotalDeltaZ;
+        *iTotalDeltaZ = 0;
     }
     else {
         /*
@@ -167,7 +163,7 @@ winMouseWheel(ScreenPtr pScreen, int iDeltaZ)
          * as blindly setting takes just as much time
          * as checking, then setting if necessary :)
          */
-        pScreenPriv->iDeltaZ = 0;
+        *iTotalDeltaZ = 0;
     }
 
     /*
@@ -175,7 +171,7 @@ winMouseWheel(ScreenPtr pScreen, int iDeltaZ)
      * WHEEL_DELTA
      */
     if (iDeltaZ >= WHEEL_DELTA || (-1 * iDeltaZ) >= WHEEL_DELTA) {
-        pScreenPriv->iDeltaZ = 0;
+        *iTotalDeltaZ = 0;
 
         /* Figure out how many whole deltas of the wheel we have */
         iDeltaZ /= WHEEL_DELTA;
@@ -186,16 +182,16 @@ winMouseWheel(ScreenPtr pScreen, int iDeltaZ)
          * we will store the wheel delta until the threshold
          * has been reached.
          */
-        pScreenPriv->iDeltaZ = iDeltaZ;
+        *iTotalDeltaZ = iDeltaZ;
         return 0;
     }
 
     /* Set the button to indicate up or down wheel delta */
     if (iDeltaZ > 0) {
-        button = Button4;
+        button = iButtonUp;
     }
     else {
-        button = Button5;
+        button = iButtonDown;
     }
 
     /*
diff --git a/hw/xwin/winmultiwindowwndproc.c b/hw/xwin/winmultiwindowwndproc.c
index da7914a..9292e73 100644
--- a/hw/xwin/winmultiwindowwndproc.c
+++ b/hw/xwin/winmultiwindowwndproc.c
@@ -684,6 +684,18 @@ winTopLevelWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
         else
             break;
 
+    case WM_MOUSEHWHEEL:
+        if (SendMessage
+            (hwnd, WM_NCHITTEST, 0,
+             MAKELONG(GET_X_LPARAM(lParam),
+                      GET_Y_LPARAM(lParam))) == HTCLIENT) {
+            /* Pass the message to the root window */
+            SendMessage(hwndScreen, message, wParam, lParam);
+            return 0;
+        }
+        else
+            break;
+
     case WM_SETFOCUS:
         if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
             break;
diff --git a/hw/xwin/winwin32rootlesswndproc.c b/hw/xwin/winwin32rootlesswndproc.c
index 9c282ec..be29583 100644
--- a/hw/xwin/winwin32rootlesswndproc.c
+++ b/hw/xwin/winwin32rootlesswndproc.c
@@ -667,6 +667,15 @@ winMWExtWMWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
         SendMessage(hwndScreen, message, wParam, lParam);
         return 0;
 
+    case WM_MOUSEHWHEEL:
+#if CYGMULTIWINDOW_DEBUG
+        winDebug("winMWExtWMWindowProc - WM_MOUSEHWHEEL\n");
+#endif
+
+        /* Pass the message to the root window */
+        SendMessage(hwndScreen, message, wParam, lParam);
+        return 0;
+
     case WM_MOUSEACTIVATE:
 #if CYGMULTIWINDOW_DEBUG
         winDebug("winMWExtWMWindowProc - WM_MOUSEACTIVATE\n");
diff --git a/hw/xwin/winwndproc.c b/hw/xwin/winwndproc.c
index 7af222c..c73a75c 100644
--- a/hw/xwin/winwndproc.c
+++ b/hw/xwin/winwndproc.c
@@ -976,7 +976,20 @@ winWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
 #if CYGDEBUG
         winDebug("winWindowProc - WM_MOUSEWHEEL\n");
 #endif
-        winMouseWheel(s_pScreen, GET_WHEEL_DELTA_WPARAM(wParam));
+        /* Button4 = WheelUp */
+        /* Button5 = WheelDown */
+        winMouseWheel(&(s_pScreenPriv->iDeltaZ), GET_WHEEL_DELTA_WPARAM(wParam), Button4, Button5);
+        break;
+
+    case WM_MOUSEHWHEEL:
+        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
+            break;
+#if CYGDEBUG
+        winDebug("winWindowProc - WM_MOUSEHWHEEL\n");
+#endif
+        /* Button7 = TiltRight */
+        /* Button6 = TiltLeft */
+        winMouseWheel(&(s_pScreenPriv->iDeltaV), GET_WHEEL_DELTA_WPARAM(wParam), 7, 6);
         break;
 
     case WM_SETFOCUS:
@@ -1147,6 +1160,7 @@ winWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
 
         /* Clear any lingering wheel delta */
         s_pScreenPriv->iDeltaZ = 0;
+        s_pScreenPriv->iDeltaV = 0;
 
         /* Reshow the Windows mouse cursor if we are being deactivated */
         if (g_fSoftwareCursor && LOWORD(wParam) == WA_INACTIVE && !g_fCursor) {
commit cf9c777ee094d660e0c95559373fd23ee910362e
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Thu Feb 21 17:10:45 2013 +0000

    hw/xwin: Map extra mouse buttons 1 and 2 to X buttons 8 and 9
    
    Map extra mouse buttons 1 and 2 to X buttons 8 and 9, as conventional, leaving X
    buttons 6 and 7 for tilt wheel.
    
    Also add button labels for buttons 6, 7, 8 and 9 and change btn_labels in from a
    dynamic allocation to a fixed one of the required size for all the labels we
    use.
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/winmouse.c b/hw/xwin/winmouse.c
index 9d896c9..da067cd 100644
--- a/hw/xwin/winmouse.c
+++ b/hw/xwin/winmouse.c
@@ -65,10 +65,10 @@ int
 winMouseProc(DeviceIntPtr pDeviceInt, int iState)
 {
     int lngMouseButtons, i;
-    int lngWheelEvents = 2;
+    int lngWheelEvents = 4;
     CARD8 *map;
     DevicePtr pDevice = (DevicePtr) pDeviceInt;
-    Atom *btn_labels;
+    Atom btn_labels[9];
     Atom axes_labels[2];
 
     switch (iState) {
@@ -80,15 +80,23 @@ winMouseProc(DeviceIntPtr pDeviceInt, int iState)
         /* Mapping of windows events to X events:
          * LEFT:1 MIDDLE:2 RIGHT:3
          * SCROLL_UP:4 SCROLL_DOWN:5
-         * XBUTTON 1:6 XBUTTON 2:7 ...
+         * TILT_LEFT:6 TILT_RIGHT:7
+         * XBUTTON 1:8 XBUTTON 2:9 (most commonly 'back' and 'forward')
+         * ...
          *
+         * The current Windows API only defines 2 extra buttons, so we don't
+         * expect more than 5 buttons to be reported, but more than that
+         * should be handled correctly
+         */
+
+        /*
          * To map scroll wheel correctly we need at least the 3 normal buttons
          */
         if (lngMouseButtons < 3)
             lngMouseButtons = 3;
 
-        /* allocate memory: 
-         * number of buttons + 2x mouse wheel event + 1 extra (offset for map) 
+        /* allocate memory:
+         * number of buttons + 4 x mouse wheel event + 1 extra (offset for map)
          */
         map = malloc(sizeof(CARD8) * (lngMouseButtons + lngWheelEvents + 1));
 
@@ -97,12 +105,15 @@ winMouseProc(DeviceIntPtr pDeviceInt, int iState)
         for (i = 1; i <= lngMouseButtons + lngWheelEvents; i++)
             map[i] = i;
 
-        btn_labels = calloc((lngMouseButtons + lngWheelEvents), sizeof(Atom));
         btn_labels[0] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_LEFT);
         btn_labels[1] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_MIDDLE);
         btn_labels[2] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_RIGHT);
         btn_labels[3] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_WHEEL_UP);
         btn_labels[4] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_WHEEL_DOWN);
+        btn_labels[5] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_HWHEEL_LEFT);
+        btn_labels[6] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_HWHEEL_RIGHT);
+        btn_labels[7] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_BACK);
+        btn_labels[8] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_FORWARD);
 
         axes_labels[0] = XIGetKnownProperty(AXIS_LABEL_PROP_REL_X);
         axes_labels[1] = XIGetKnownProperty(AXIS_LABEL_PROP_REL_Y);
@@ -114,7 +125,6 @@ winMouseProc(DeviceIntPtr pDeviceInt, int iState)
                                 winMouseCtrl,
                                 GetMotionHistorySize(), 2, axes_labels);
         free(map);
-        free(btn_labels);
 
         g_winMouseButtonMap = pDeviceInt->button->map;
         break;
diff --git a/hw/xwin/winmultiwindowwndproc.c b/hw/xwin/winmultiwindowwndproc.c
index 3818187..da7914a 100644
--- a/hw/xwin/winmultiwindowwndproc.c
+++ b/hw/xwin/winmultiwindowwndproc.c
@@ -661,7 +661,7 @@ winTopLevelWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
         if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
             break;
         SetCapture(hwnd);
-        return winMouseButtonsHandle(s_pScreen, ButtonPress, HIWORD(wParam) + 5,
+        return winMouseButtonsHandle(s_pScreen, ButtonPress, HIWORD(wParam) + 7,
                                      wParam);
 
     case WM_XBUTTONUP:
@@ -670,7 +670,7 @@ winTopLevelWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
         ReleaseCapture();
         winStartMousePolling(s_pScreenPriv);
         return winMouseButtonsHandle(s_pScreen, ButtonRelease,
-                                     HIWORD(wParam) + 5, wParam);
+                                     HIWORD(wParam) + 7, wParam);
 
     case WM_MOUSEWHEEL:
         if (SendMessage
diff --git a/hw/xwin/winwin32rootlesswndproc.c b/hw/xwin/winwin32rootlesswndproc.c
index 13df186..9c282ec 100644
--- a/hw/xwin/winwin32rootlesswndproc.c
+++ b/hw/xwin/winwin32rootlesswndproc.c
@@ -649,13 +649,13 @@ winMWExtWMWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
         if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
             break;
         SetCapture(hwnd);
-        return winMouseButtonsHandle(pScreen, ButtonPress, HIWORD(wParam) + 5,
+        return winMouseButtonsHandle(pScreen, ButtonPress, HIWORD(wParam) + 7,
                                      wParam);
     case WM_XBUTTONUP:
         if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
             break;
         ReleaseCapture();
-        return winMouseButtonsHandle(pScreen, ButtonRelease, HIWORD(wParam) + 5,
+        return winMouseButtonsHandle(pScreen, ButtonRelease, HIWORD(wParam) + 7,
                                      wParam);
 
     case WM_MOUSEWHEEL:
diff --git a/hw/xwin/winwndproc.c b/hw/xwin/winwndproc.c
index f99afb5..7af222c 100644
--- a/hw/xwin/winwndproc.c
+++ b/hw/xwin/winwndproc.c
@@ -894,7 +894,7 @@ winWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
 #endif
             )
             SetCapture(hwnd);
-        return winMouseButtonsHandle(s_pScreen, ButtonPress, HIWORD(wParam) + 5,
+        return winMouseButtonsHandle(s_pScreen, ButtonPress, HIWORD(wParam) + 7,
                                      wParam);
     case WM_XBUTTONUP:
         if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
@@ -906,7 +906,7 @@ winWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
             )
             ReleaseCapture();
         return winMouseButtonsHandle(s_pScreen, ButtonRelease,
-                                     HIWORD(wParam) + 5, wParam);
+                                     HIWORD(wParam) + 7, wParam);
 
     case WM_TIMER:
         if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
commit c9d7b9516f4a04cb9012c6c1e9466491a468aa07
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Tue Feb 19 14:38:40 2013 +0000

    hw/xwin: Remove unneeded WM_XBUTTON message defines
    
    Remove unneeded WM_XBUTTON message defines, they have been provided by w32api
    for a long time now.
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/win.h b/hw/xwin/win.h
index a663088..182e96b 100644
--- a/hw/xwin/win.h
+++ b/hw/xwin/win.h
@@ -47,17 +47,6 @@
 #define CYGDEBUG				NO
 #endif
 
-/* WM_XBUTTON Messages. They should go into w32api. */
-#ifndef WM_XBUTTONDOWN
-#define WM_XBUTTONDOWN 523
-#endif
-#ifndef WM_XBUTTONUP
-#define WM_XBUTTONUP 524
-#endif
-#ifndef WM_XBUTTONDBLCLK
-#define WM_XBUTTONDBLCLK 525
-#endif
-
 #define WIN_DEFAULT_BPP				0
 #define WIN_DEFAULT_WHITEPIXEL			255
 #define WIN_DEFAULT_BLACKPIXEL			0
commit 5dccfc63f9c7056e7cd30884e1d3ccea86a2f419
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Mon Dec 17 22:38:00 2012 +0000

    hw/xwin: Change winTranslateKey() to return it's result as it's return value
    
    Change winTranslateKey() to return it's result as it's return value, and change
    it's uses as well.
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/win.h b/hw/xwin/win.h
index dd6ed02..a663088 100644
--- a/hw/xwin/win.h
+++ b/hw/xwin/win.h
@@ -921,8 +921,8 @@ void
  * winkeybd.c
  */
 
-void
- winTranslateKey(WPARAM wParam, LPARAM lParam, int *piScanCode);
+int
+ winTranslateKey(WPARAM wParam, LPARAM lParam);
 
 int
  winKeybdProc(DeviceIntPtr pDeviceInt, int iState);
diff --git a/hw/xwin/winkeybd.c b/hw/xwin/winkeybd.c
index 27432e1..9c5d4e9 100644
--- a/hw/xwin/winkeybd.c
+++ b/hw/xwin/winkeybd.c
@@ -65,13 +65,14 @@ static void
  * like AltGr on European keyboards.
  */
 
-void
-winTranslateKey(WPARAM wParam, LPARAM lParam, int *piScanCode)
+int
+winTranslateKey(WPARAM wParam, LPARAM lParam)
 {
     int iKeyFixup = g_iKeyMap[wParam * WIN_KEYMAP_COLS + 1];
     int iKeyFixupEx = g_iKeyMap[wParam * WIN_KEYMAP_COLS + 2];
     int iParam = HIWORD(lParam);
     int iParamScanCode = LOBYTE(iParam);
+    int iScanCode;
 
     winDebug("winTranslateKey: wParam %08x lParam %08x\n", wParam, lParam);
 
@@ -96,23 +97,25 @@ winTranslateKey(WPARAM wParam, LPARAM lParam, int *piScanCode)
 
     /* Branch on special extended, special non-extended, or normal key */
     if ((iParam & KF_EXTENDED) && iKeyFixupEx)
-        *piScanCode = iKeyFixupEx;
+        iScanCode = iKeyFixupEx;
     else if (iKeyFixup)
-        *piScanCode = iKeyFixup;
+        iScanCode = iKeyFixup;
     else if (wParam == 0 && iParamScanCode == 0x70)
-        *piScanCode = KEY_HKTG;
+        iScanCode = KEY_HKTG;
     else
         switch (iParamScanCode) {
         case 0x70:
-            *piScanCode = KEY_HKTG;
+            iScanCode = KEY_HKTG;
             break;
         case 0x73:
-            *piScanCode = KEY_BSlash2;
+            iScanCode = KEY_BSlash2;
             break;
         default:
-            *piScanCode = iParamScanCode;
+            iScanCode = iParamScanCode;
             break;
         }
+
+    return iScanCode;
 }
 
 /* Ring the keyboard bell (system speaker on PCs) */
diff --git a/hw/xwin/winwndproc.c b/hw/xwin/winwndproc.c
index f93072c..f99afb5 100644
--- a/hw/xwin/winwndproc.c
+++ b/hw/xwin/winwndproc.c
@@ -1064,7 +1064,7 @@ winWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
         }
 
         /* Translate Windows key code to X scan code */
-        winTranslateKey(wParam, lParam, &iScanCode);
+        iScanCode = winTranslateKey(wParam, lParam);
 
         /* Ignore repeats for CapsLock */
         if (wParam == VK_CAPITAL)
@@ -1093,7 +1093,7 @@ winWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
             return 0;
 
         /* Enqueue a keyup event */
-        winTranslateKey(wParam, lParam, &iScanCode);
+        iScanCode = winTranslateKey(wParam, lParam);
         winSendKeyEvent(iScanCode, FALSE);
 
         /* Release all pressed shift keys */
commit 9b4cec76f1d7792d4bf64fa069ea6b64bc42da0d
Author: Oliver Schmidt <oschmidt-mailinglists at gmx.de>
Date:   Mon Nov 5 15:05:32 2012 +0000

    hw/xwin: Consider left and right modifier keys independently on gaining focus
    
    Handle left and right ctrl and shift keys independently
    
    Assume that all modifiers are cleared when all keys are released on focus lost,
    as internalKeyState doesn't record which modifier key was pressed.
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/winkeybd.c b/hw/xwin/winkeybd.c
index e412f23..27432e1 100644
--- a/hw/xwin/winkeybd.c
+++ b/hw/xwin/winkeybd.c
@@ -264,25 +264,38 @@ winRestoreModeKeyStates(void)
 
     /* Check if modifier keys are pressed, and if so, fake a press */
     {
-        BOOL ctrl = (GetAsyncKeyState(VK_CONTROL) < 0);
-        BOOL shift = (GetAsyncKeyState(VK_SHIFT) < 0);
+
+        BOOL lctrl = (GetAsyncKeyState(VK_LCONTROL) < 0);
+        BOOL rctrl = (GetAsyncKeyState(VK_RCONTROL) < 0);
+        BOOL lshift = (GetAsyncKeyState(VK_LSHIFT) < 0);
+        BOOL rshift = (GetAsyncKeyState(VK_RSHIFT) < 0);
         BOOL alt = (GetAsyncKeyState(VK_LMENU) < 0);
         BOOL altgr = (GetAsyncKeyState(VK_RMENU) < 0);
 
-        if (ctrl && altgr)
-            ctrl = FALSE;
+        /*
+           If AltGr and CtrlL appear to be pressed, assume the
+           CtrL is a fake one
+         */
+        if (lctrl && altgr)
+            lctrl = FALSE;
+
+        if (lctrl)
+            winSendKeyEvent(KEY_LCtrl, TRUE);
+
+        if (rctrl)
+            winSendKeyEvent(KEY_RCtrl, TRUE);
 
-        if (LOGICAL_XOR(internalKeyStates & ControlMask, ctrl))
-            winSendKeyEvent(KEY_LCtrl, ctrl);
+        if (lshift)
+            winSendKeyEvent(KEY_ShiftL, TRUE);
 
-        if (LOGICAL_XOR(internalKeyStates & ShiftMask, shift))
-            winSendKeyEvent(KEY_ShiftL, shift);
+        if (rshift)
+            winSendKeyEvent(KEY_ShiftL, TRUE);
 
-        if (LOGICAL_XOR(internalKeyStates & Mod1Mask, alt))
-            winSendKeyEvent(KEY_Alt, alt);
+        if (alt)
+            winSendKeyEvent(KEY_Alt, TRUE);
 
-        if (LOGICAL_XOR(internalKeyStates & Mod5Mask, altgr))
-            winSendKeyEvent(KEY_AltLang, altgr);
+        if (altgr)
+            winSendKeyEvent(KEY_AltLang, TRUE);
     }
 
     /*
@@ -313,6 +326,12 @@ winRestoreModeKeyStates(void)
         winSendKeyEvent(KEY_HKTG, TRUE);
         winSendKeyEvent(KEY_HKTG, FALSE);
     }
+
+    /*
+       For strict correctness, we should also press any non-modifier keys
+       which are already down when we gain focus, but nobody has complained
+       yet :-)
+     */
 }
 
 /*
commit 235149d0b4af9097e47b3af0ba56d4eb0179518c
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Mon Apr 5 14:22:39 2010 +0100

    hw/xwin: Remove an extra '\n' from some log messages
    
    Remove an extra '\n' from internal client IOError log messages
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/winclipboardthread.c b/hw/xwin/winclipboardthread.c
index 6da9f3b..69c654d 100644
--- a/hw/xwin/winclipboardthread.c
+++ b/hw/xwin/winclipboardthread.c
@@ -460,7 +460,7 @@ winClipboardErrorHandler(Display * pDisplay, XErrorEvent * pErr)
 static int
 winClipboardIOErrorHandler(Display * pDisplay)
 {
-    ErrorF("winClipboardIOErrorHandler!\n\n");
+    ErrorF("winClipboardIOErrorHandler!\n");
 
     if (pthread_equal(pthread_self(), g_winClipboardProcThread)) {
         /* Restart at the main entry point */
diff --git a/hw/xwin/winmultiwindowwm.c b/hw/xwin/winmultiwindowwm.c
index 7671bda..3c44f05 100644
--- a/hw/xwin/winmultiwindowwm.c
+++ b/hw/xwin/winmultiwindowwm.c
@@ -1470,7 +1470,7 @@ winMultiWindowWMErrorHandler(Display * pDisplay, XErrorEvent * pErr)
 static int
 winMultiWindowWMIOErrorHandler(Display * pDisplay)
 {
-    ErrorF("winMultiWindowWMIOErrorHandler!\n\n");
+    ErrorF("winMultiWindowWMIOErrorHandler!\n");
 
     if (pthread_equal(pthread_self(), g_winMultiWindowWMThread)) {
         if (g_shutdown)
@@ -1510,7 +1510,7 @@ winMultiWindowXMsgProcErrorHandler(Display * pDisplay, XErrorEvent * pErr)
 static int
 winMultiWindowXMsgProcIOErrorHandler(Display * pDisplay)
 {
-    ErrorF("winMultiWindowXMsgProcIOErrorHandler!\n\n");
+    ErrorF("winMultiWindowXMsgProcIOErrorHandler!\n");
 
     if (pthread_equal(pthread_self(), g_winMultiWindowXMsgProcThread)) {
         /* Restart at the main entry point */
commit c7aa9f7578e721b0c9e565e7a085b6aeb30bf2ac
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Sat Feb 4 17:04:11 2012 +0000

    hw/xwin: _NET_WM_STATE is ATOM[] not ATOM
    
    _NET_WM_STATE is ATOM[] not ATOM, a list of window state hints, so check all of
    the atoms, not just the first one
    
    See EWMH specifcation, section "Application Window Properties"
    
    v2: Actually use [] on the returned atom data
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/winmultiwindowwm.c b/hw/xwin/winmultiwindowwm.c
index 4f6dec7..7671bda 100644
--- a/hw/xwin/winmultiwindowwm.c
+++ b/hw/xwin/winmultiwindowwm.c
@@ -1626,23 +1626,27 @@ winApplyHints(Display * pDisplay, Window iWindow, HWND hWnd, HWND * zstyle)
     }
 
     if (XGetWindowProperty(pDisplay, iWindow, windowState, 0L,
-                           1L, False, XA_ATOM, &type, &format,
+                           MAXINT, False, XA_ATOM, &type, &format,
                            &nitems, &left,
                            (unsigned char **) &pAtom) == Success) {
-        if (pAtom && nitems == 1) {
-            if (*pAtom == skiptaskbarState)
-                hint |= HINT_SKIPTASKBAR;
-            if (*pAtom == hiddenState)
-                maxmin |= HINT_MIN;
-            else if (*pAtom == fullscreenState)
-                maxmin |= HINT_MAX;
-            if (*pAtom == belowState)
-                *zstyle = HWND_BOTTOM;
-            else if (*pAtom == aboveState)
-                *zstyle = HWND_TOPMOST;
-        }
-        if (pAtom)
+        if (pAtom ) {
+            unsigned long i;
+
+            for (i = 0; i < nitems; i++) {
+                if (pAtom[i] == skiptaskbarState)
+                    hint |= HINT_SKIPTASKBAR;
+                if (pAtom[i] == hiddenState)
+                    maxmin |= HINT_MIN;
+                else if (pAtom[i] == fullscreenState)
+                    maxmin |= HINT_MAX;
+                if (pAtom[i] == belowState)
+                    *zstyle = HWND_BOTTOM;
+                else if (pAtom[i] == aboveState)
+                    *zstyle = HWND_TOPMOST;
+            }
+
             XFree(pAtom);
+        }
     }
 
     nitems = left = 0;
commit 682ccac90b18f293520f77db5b163fcb40328e2b
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Wed Aug 31 21:35:14 2011 +0100

    hw/xwin: Improve WM_ENDSESSION handling using separate messaging window thread
    
    Currently, WM_ENDSESSION just calls GiveUp() to set the DE_TERMINATE flag. But
    for the X server to exit cleanly, we also need the X server dispatch loop to be
    unblocked so it can notice that DE_TERMINATE has been set and exit, removing
    it's lock file and any unix domain socket.
    
    It appears that the system will terminate the process when the last UI thread in
    that process returns from processing WM_ENDSESSION for the last top-level
    window.
    
    Since WM_ENDSESSION appears to sent by the system via SendMessage()
    (synchronously) and the wndproc is called to process it in the message thread
    for that window (the X server thread), we can't easily terminate the X server
    dispatch loop from inside the WM_ENDSESSION message processing.
    
    So, create a messaging window, a hidden, top-level window, with a separate
    thread to catch this message, and process it by calling GiveUp() and then
    blocking on a mutex until the X server dispatch loop exits.
    
    Also, notice when this is a shutdown cancel WM_ENDSESSION message and take no
    action.
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/InitOutput.c b/hw/xwin/InitOutput.c
index 04c17b7..d6b5e4f 100644
--- a/hw/xwin/InitOutput.c
+++ b/hw/xwin/InitOutput.c
@@ -186,6 +186,25 @@ ddxBeforeReset(void)
 }
 #endif
 
+int
+main(int argc, char *argv[], char *envp[])
+{
+    int iReturn;
+
+    /* Create & acquire the termination mutex */
+    iReturn = pthread_mutex_init(&g_pmTerminating, NULL);
+    if (iReturn != 0) {
+        ErrorF("ddxMain - pthread_mutex_init () failed: %d\n", iReturn);
+    }
+
+    iReturn = pthread_mutex_lock(&g_pmTerminating);
+    if (iReturn != 0) {
+        ErrorF("ddxMain - pthread_mutex_lock () failed: %d\n", iReturn);
+    }
+
+    return dix_main(argc, argv, envp);
+}
+
 /* See Porting Layer Definition - p. 57 */
 void
 ddxGiveUp(enum ExitCode error)
@@ -243,6 +262,19 @@ ddxGiveUp(enum ExitCode error)
 
     /* Tell Windows that we want to end the app */
     PostQuitMessage(0);
+
+    {
+        winDebug("ddxGiveUp - Releasing termination mutex\n");
+
+        int iReturn = pthread_mutex_unlock(&g_pmTerminating);
+
+        if (iReturn != 0) {
+            ErrorF("winMsgWindowProc - pthread_mutex_unlock () failed: %d\n",
+                   iReturn);
+        }
+    }
+
+    winDebug("ddxGiveUp - End\n");
 }
 
 /* See Porting Layer Definition - p. 57 */
@@ -962,6 +994,10 @@ InitOutput(ScreenInfo * pScreenInfo, int argc, char *argv[])
     /* Store the instance handle */
     g_hInstance = GetModuleHandle(NULL);
 
+    /* Create the messaging window */
+    if (serverGeneration == 1)
+        winCreateMsgWindowThread();
+
     /* Initialize each screen */
     for (i = 0; i < g_iNumScreens; ++i) {
         /* Initialize the screen */
diff --git a/hw/xwin/Makefile.am b/hw/xwin/Makefile.am
index 90812ab..74a4243 100644
--- a/hw/xwin/Makefile.am
+++ b/hw/xwin/Makefile.am
@@ -92,6 +92,7 @@ SRCS =	InitInput.c \
 	winmonitors.c \
 	winmouse.c \
 	winmsg.c \
+	winmsgwindow.c \
 	winmultiwindowclass.c \
 	winmultiwindowicons.c \
 	winprefs.c \
diff --git a/hw/xwin/win.h b/hw/xwin/win.h
index fa774bc..dd6ed02 100644
--- a/hw/xwin/win.h
+++ b/hw/xwin/win.h
@@ -1403,6 +1403,12 @@ winDoRandRScreenSetSize(ScreenPtr pScreen,
                         CARD16 height, CARD32 mmWidth, CARD32 mmHeight);
 
 /*
+ * winmsgwindow.c
+ */
+Bool
+winCreateMsgWindowThread(void);
+
+/*
  * END DDX and DIX Function Prototypes
  */
 
diff --git a/hw/xwin/winglobals.c b/hw/xwin/winglobals.c
index b34d1a7..b3ca295 100644
--- a/hw/xwin/winglobals.c
+++ b/hw/xwin/winglobals.c
@@ -78,6 +78,7 @@ Bool g_fNoHelpMessageBox = FALSE;
 Bool g_fSoftwareCursor = FALSE;
 Bool g_fSilentDupError = FALSE;
 Bool g_fNativeGl = TRUE;
+pthread_mutex_t g_pmTerminating = PTHREAD_MUTEX_INITIALIZER;
 
 #ifdef XWIN_CLIPBOARD
 /*
diff --git a/hw/xwin/winglobals.h b/hw/xwin/winglobals.h
index d2e2ba2..e7e2f7e 100644
--- a/hw/xwin/winglobals.h
+++ b/hw/xwin/winglobals.h
@@ -90,4 +90,6 @@ extern Bool g_fButton[3];
 extern Bool g_fNoConfigureWindow;
 #endif
 
+extern pthread_mutex_t g_pmTerminating;
+
 #endif                          /* WINGLOBALS_H */
diff --git a/hw/xwin/winmsgwindow.c b/hw/xwin/winmsgwindow.c
new file mode 100644
index 0000000..8067c69
--- /dev/null
+++ b/hw/xwin/winmsgwindow.c
@@ -0,0 +1,180 @@
+/*
+ * Copyright (C) Jon TURNEY 2011
+ *
+ * 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 (including the next
+ * paragraph) 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 "win.h"
+
+/*
+ * This is the messaging window, a hidden top-level window. We never do anything
+ * with it, but other programs may send messages to it.
+ */
+
+/*
+ * winMsgWindowProc - Window procedure for msg window
+ */
+
+static
+LRESULT CALLBACK
+winMsgWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
+{
+#if CYGDEBUG
+    winDebugWin32Message("winMsgWindowProc", hwnd, message, wParam, lParam);
+#endif
+
+    switch (message) {
+    case WM_ENDSESSION:
+        if (!wParam)
+            return 0;           /* shutdown is being cancelled */
+
+        /*
+           Send a WM_GIVEUP message to the X server thread so it wakes up if
+           blocked in select(), performs GiveUp(), and then notices that GiveUp()
+           has set the DE_TERMINATE flag so exits the msg dispatch loop.
+         */
+        {
+            ScreenPtr pScreen = screenInfo.screens[0];
+
+            winScreenPriv(pScreen);
+            PostMessage(pScreenPriv->hwndScreen, WM_GIVEUP, 0, 0);
+        }
+
+        /*
+           This process will be terminated by the system almost immediately
+           after the last thread with a message queue returns from processing
+           WM_ENDSESSION, so we cannot rely on any code executing after this
+           message is processed and need to wait here until ddxGiveUp() is called
+           and releases the termination mutex to guarantee that the lock file and
+           unix domain sockets have been removed
+
+           ofc, Microsoft doesn't document this under WM_ENDSESSION, you are supposed
+           to read the source of CRSS to find out how it works :-)
+
+           http://blogs.msdn.com/b/michen/archive/2008/04/04/application-termination-when-user-logs-off.aspx
+         */
+        {
+            int iReturn = pthread_mutex_lock(&g_pmTerminating);
+
+            if (iReturn != 0) {
+                ErrorF("winMsgWindowProc - pthread_mutex_lock () failed: %d\n",
+                       iReturn);
+            }
+            winDebug
+                ("winMsgWindowProc - WM_ENDSESSION termination lock acquired\n");
+        }
+
+        return 0;
+    }
+
+    return DefWindowProc(hwnd, message, wParam, lParam);
+}
+
+static HWND
+winCreateMsgWindow(void)
+{
+    HWND hwndMsg;
+    wATOM winClass;
+
+    // register window class
+    {
+        WNDCLASSEX wcx;
+
+        wcx.cbSize = sizeof(WNDCLASSEX);
+        wcx.style = CS_HREDRAW | CS_VREDRAW;
+        wcx.lpfnWndProc = winMsgWindowProc;
+        wcx.cbClsExtra = 0;
+        wcx.cbWndExtra = 0;
+        wcx.hInstance = g_hInstance;
+        wcx.hIcon = NULL;
+        wcx.hCursor = 0;
+        wcx.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
+        wcx.lpszMenuName = NULL;
+        wcx.lpszClassName = WINDOW_CLASS_X_MSG;
+        wcx.hIconSm = NULL;
+        winClass = RegisterClassEx(&wcx);
+    }
+
+    // Create the msg window.
+    hwndMsg = CreateWindowEx(0, // no extended styles
+                             WINDOW_CLASS_X_MSG,        // class name
+                             "XWin Msg Window", // window name
+                             WS_OVERLAPPEDWINDOW,       // overlapped window
+                             CW_USEDEFAULT,     // default horizontal position
+                             CW_USEDEFAULT,     // default vertical position
+                             CW_USEDEFAULT,     // default width
+                             CW_USEDEFAULT,     // default height
+                             (HWND) NULL,       // no parent or owner window
+                             (HMENU) NULL,      // class menu used
+                             GetModuleHandle(NULL),     // instance handle
+                             NULL);     // no window creation data
+
+    if (!hwndMsg) {
+        ErrorF("winCreateMsgWindow - Create msg window failed\n");
+        return NULL;
+    }
+
+    winDebug("winCreateMsgWindow - Created msg window hwnd 0x%x\n", hwndMsg);
+
+    return hwndMsg;
+}
+
+static void *
+winMsgWindowThreadProc(void *arg)
+{
+    HWND hwndMsg;
+
+    winDebug("winMsgWindowThreadProc - Hello\n");
+
+    hwndMsg = winCreateMsgWindow();
+    if (hwndMsg) {
+        MSG msg;
+
+        /* Pump the msg window message queue */
+        while (GetMessage(&msg, hwndMsg, 0, 0) > 0) {
+#if CYGDEBUG
+            winDebugWin32Message("winMsgWindowThread", msg.hwnd, msg.message,
+                                 msg.wParam, msg.lParam);
+#endif
+            DispatchMessage(&msg);
+        }
+    }
+
+    winDebug("winMsgWindowThreadProc - Exit\n");
+
+    return NULL;
+}
+
+Bool
+winCreateMsgWindowThread(void)
+{
+    pthread_t ptMsgWindowThreadProc;
+
+    /* Spawn a thread for the msg window  */
+    if (pthread_create(&ptMsgWindowThreadProc,
+                       NULL, winMsgWindowThreadProc, NULL)) {
+        /* Bail if thread creation failed */
+        ErrorF("winCreateMsgWindow - pthread_create failed.\n");
+        return FALSE;
+    }
+
+    return TRUE;
+}
diff --git a/hw/xwin/winwindow.h b/hw/xwin/winwindow.h
index 25826ec..7e6bd56 100644
--- a/hw/xwin/winwindow.h
+++ b/hw/xwin/winwindow.h
@@ -49,6 +49,7 @@
 #define WINDOW_TITLE_XDMCP	"%s:%s.%d"
 #define WIN_SCR_PROP		"cyg_screen_prop rl"
 #define WINDOW_CLASS_X		"cygwin/x X rl"
+#define WINDOW_CLASS_X_MSG      "cygwin/x X msg"
 #define WINDOW_TITLE_X		PROJECT_NAME " X"
 #define WIN_WINDOW_PROP		"cyg_window_prop_rl"
 #ifdef HAS_DEVWINDOWS
diff --git a/hw/xwin/winwndproc.c b/hw/xwin/winwndproc.c
index c7509ea..f93072c 100644
--- a/hw/xwin/winwndproc.c
+++ b/hw/xwin/winwndproc.c
@@ -1221,7 +1221,6 @@ winWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
         }
         break;
 
-    case WM_ENDSESSION:
     case WM_GIVEUP:
         /* Tell X that we are giving up */
 #ifdef XWIN_MULTIWINDOW
commit 15febb05d77cc7e7185c942f35459838f75cfdc0
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Mon Sep 3 15:19:43 2012 +0100

    Allow DDX to provide a main()
    
    XQuartz already conditionally renames main() as dix_main() so it can provide
    it's own main().  This isn't the ideal way of doing this, as it prevents libdix
    built this way from being useful with any other DDX.
    
    So instead, always name that function dix_main(), and also provide a stub main()
    which just calls dix_main(), which can be overriden in the DDX.
    
    Add a main() to XWin (XQuartz already has one, of course).
    
    It's no longer neccessary to link XWin and XQuartz with libmain.
    
    v2: Remove unneeded stub main hw/xwin/InitOutput.c
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Julien Cristau <jcristau at debian.org>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/configure.ac b/configure.ac
index 75281f0..d0d0fd7 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1967,7 +1967,7 @@ if test "x$XQUARTZ" = xyes; then
 	AC_DEFINE(XQUARTZ,1,[Have Quartz])
 	AC_DEFINE(ROOTLESS,1,[Build Rootless code])
 
-	XQUARTZ_LIBS="$MAIN_LIB $FB_LIB $FIXES_LIB $XEXT_LIB $DBE_LIB $RECORD_LIB $RANDR_LIB $RENDER_LIB $DAMAGE_LIB $MIEXT_SYNC_LIB $MIEXT_DAMAGE_LIB $MIEXT_SHADOW_LIB $XI_LIB $XKB_LIB $XKB_STUB_LIB $XPSTUBS_LIB"
+	XQUARTZ_LIBS="$FB_LIB $FIXES_LIB $XEXT_LIB $DBE_LIB $RECORD_LIB $RANDR_LIB $RENDER_LIB $DAMAGE_LIB $MIEXT_SYNC_LIB $MIEXT_DAMAGE_LIB $MIEXT_SHADOW_LIB $XI_LIB $XKB_LIB $XKB_STUB_LIB $XPSTUBS_LIB"
 	AC_SUBST([XQUARTZ_LIBS])
 
 	AC_CHECK_LIB([Xplugin],[xp_init],[:])
diff --git a/dix/Makefile.am b/dix/Makefile.am
index b7358aa..e7ca236 100644
--- a/dix/Makefile.am
+++ b/dix/Makefile.am
@@ -4,7 +4,7 @@ AM_CPPFLAGS = -I$(top_srcdir)/include
 AM_CFLAGS = $(DIX_CFLAGS)
 
 libmain_la_SOURCES =    \
-	main.c
+	stubmain.c
 
 libdix_la_SOURCES = 	\
 	atom.c		\
@@ -14,6 +14,7 @@ libdix_la_SOURCES = 	\
 	dispatch.c	\
 	dispatch.h	\
 	dixfonts.c	\
+	main.c		\
 	dixutils.c	\
 	enterleave.c	\
 	enterleave.h	\
diff --git a/dix/main.c b/dix/main.c
index e69cd93..05dcbed 100644
--- a/dix/main.c
+++ b/dix/main.c
@@ -125,14 +125,10 @@ BOOL serverRunning = FALSE;
 pthread_mutex_t serverRunningMutex = PTHREAD_MUTEX_INITIALIZER;
 pthread_cond_t serverRunningCond = PTHREAD_COND_INITIALIZER;
 
-int dix_main(int argc, char *argv[], char *envp[]);
+#endif
 
 int
 dix_main(int argc, char *argv[], char *envp[])
-#else
-int
-main(int argc, char *argv[], char *envp[])
-#endif
 {
     int i;
     HWEventQueueType alwaysCheckForInput[2];
diff --git a/dix/stubmain.c b/dix/stubmain.c
new file mode 100644
index 0000000..7efb4b8
--- /dev/null
+++ b/dix/stubmain.c
@@ -0,0 +1,35 @@
+/***********************************************************
+
+Copyright 2012 Jon TURNEY
+
+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 (including the next
+paragraph) 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.
+
+******************************************************************/
+
+int dix_main(int argc, char *argv[], char *envp[]);
+
+/*
+  A default implementation of main, which can be overridden by the DDX
+ */
+int
+main(int argc, char *argv[], char *envp[])
+{
+    return dix_main(argc, argv, envp);
+}
diff --git a/hw/xwin/Makefile.am b/hw/xwin/Makefile.am
index f131975..90812ab 100644
--- a/hw/xwin/Makefile.am
+++ b/hw/xwin/Makefile.am
@@ -153,7 +153,7 @@ INCLUDES = -I$(top_srcdir)/miext/rootless
 
 XWIN_SYS_LIBS += -ldxguid
 
-XWin_DEPENDENCIES = $(MULTIWINDOWEXTWM_LIBS) $(XWIN_GLX_LIBS) $(XWIN_LIBS) $(MAIN_LIB) $(XSERVER_LIBS)
+XWin_DEPENDENCIES = $(MULTIWINDOWEXTWM_LIBS) $(XWIN_GLX_LIBS) $(XWIN_LIBS) $(XSERVER_LIBS)
 XWin_LDADD = $(MULTIWINDOW_LIBS) $(MULTIWINDOWEXTWM_LIBS) $(XWIN_GLX_LIBS) $(XWIN_GLX_LINK_FLAGS) $(XWIN_LIBS) $(MAIN_LIB) $(XSERVER_LIBS) $(XSERVER_SYS_LIBS) $(XWIN_SYS_LIBS)
 XWin_LDFLAGS = -mwindows -static
 
commit d5ebe20f9ba9569351c4a41449866679fd60ba45
Merge: 21ea7eb 33f7e60
Author: Keith Packard <keithp at keithp.com>
Date:   Mon Jul 22 20:34:41 2013 -0700

    Merge remote-tracking branch 'alanc/master'

commit 21ea7ebb6a1ad56f3060747af0df235ca6ff27fa
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Jul 19 08:56:38 2013 +1000

    dix: scale y back instead of x up when pre-scaling coordinates
    
    The peculiar way we handle coordinates results in relative coordinates on
    absolute devices being added to the last value, then that value is mapped to
    the screen (taking the device dimensions into account). From that mapped
    value we get the final coordinates, both screen and device coordinates.
    
    To avoid uneven scaling on relative coordinates, they are pre-scaled by
    screen ratio:resolution:device ratio factor before being mapped. This
    ensures that a circle drawn on the device is a circle on the screen.
    
    Previously, we used the ratio to scale x up. Synaptics already does its own
    scaling based on the resolution and that is done by scaling y down by the
    ratio. So we can remove the code from the driver and get approximately the
    same behaviour here.
    
    Minor ABI bump, so we can remove this from synaptics.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Tested-by: Emmanuel Benisty <benisty.e at gmail.com>

diff --git a/dix/getevents.c b/dix/getevents.c
index 51d4fd4..f5ab8c4 100644
--- a/dix/getevents.c
+++ b/dix/getevents.c
@@ -773,7 +773,7 @@ add_to_scroll_valuator(DeviceIntPtr dev, ValuatorMask *mask, int valuator, doubl
 static void
 scale_for_device_resolution(DeviceIntPtr dev, ValuatorMask *mask)
 {
-    double x;
+    double y;
     ValuatorClassPtr v = dev->valuator;
     int xrange = v->axes[0].max_value - v->axes[0].min_value + 1;
     int yrange = v->axes[1].max_value - v->axes[1].min_value + 1;
@@ -783,14 +783,14 @@ scale_for_device_resolution(DeviceIntPtr dev, ValuatorMask *mask)
     double resolution_ratio = 1.0;
     double ratio;
 
-    if (!valuator_mask_fetch_double(mask, 0, &x))
+    if (!valuator_mask_fetch_double(mask, 1, &y))
         return;
 
     if (v->axes[0].resolution != 0 && v->axes[1].resolution != 0)
         resolution_ratio = 1.0 * v->axes[0].resolution/v->axes[1].resolution;
 
     ratio = device_ratio/resolution_ratio/screen_ratio;
-    valuator_mask_set_double(mask, 0, x * ratio);
+    valuator_mask_set_double(mask, 1, y / ratio);
 }
 
 /**
diff --git a/hw/xfree86/common/xf86Module.h b/hw/xfree86/common/xf86Module.h
index 1393427..e0cec05 100644
--- a/hw/xfree86/common/xf86Module.h
+++ b/hw/xfree86/common/xf86Module.h
@@ -81,7 +81,7 @@ typedef enum {
  */
 #define ABI_ANSIC_VERSION	SET_ABI_VERSION(0, 4)
 #define ABI_VIDEODRV_VERSION	SET_ABI_VERSION(14, 1)
-#define ABI_XINPUT_VERSION	SET_ABI_VERSION(19, 1)
+#define ABI_XINPUT_VERSION	SET_ABI_VERSION(19, 2)
 #define ABI_EXTENSION_VERSION	SET_ABI_VERSION(7, 0)
 #define ABI_FONT_VERSION	SET_ABI_VERSION(0, 6)
 
commit 33f7e60785f12770ce10558c2ca7ce1323eefc59
Author: Thomas Klausner <wiz at NetBSD.org>
Date:   Fri Jul 12 08:21:19 2013 +0200

    Fix typo in header guard.
    
    Signed-off-by: Thomas Klausner <wiz at NetBSD.org>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>

diff --git a/hw/xnest/Args.h b/hw/xnest/Args.h
index 514a395..225418d 100644
--- a/hw/xnest/Args.h
+++ b/hw/xnest/Args.h
@@ -12,7 +12,7 @@ is" without express or implied warranty.
 
 */
 
-#ifndef XNESTARGC_H
+#ifndef XNESTARGS_H
 #define XNESTARGS_H
 
 extern char *xnestDisplayName;
commit ddc52b9cbae017f04c7a232af4e8b16c9f96823d
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Fri Jul 5 22:43:17 2013 -0700

    Xephyr: Use _XEatDataWords (from Xlib 1.6) instead of _XEatData
    
    Simplifies code and reduces risk of overflow from converting length
    field in X replies from words to bytes.
    
    One call to _XEatData is left in ephyrHostGLXGetStringFromServer where
    it's already been checked for overflow, and other values have been
    subtracted from it to reduce the size of data remaining to be eaten.
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>

diff --git a/configure.ac b/configure.ac
index 206b9c4..75281f0 100644
--- a/configure.ac
+++ b/configure.ac
@@ -2112,7 +2112,7 @@ if test "$KDRIVE" = yes; then
        AC_DEFINE(KDRIVE_MOUSE, 1, [Enable KDrive mouse driver])
     fi
 
-    XEPHYR_REQUIRED_LIBS="x11 $LIBXEXT xau xdmcp"
+    XEPHYR_REQUIRED_LIBS="x11 >= 1.6 $LIBXEXT xau xdmcp"
     if test "x$XV" = xyes; then
         XEPHYR_REQUIRED_LIBS="$XEPHYR_REQUIRED_LIBS xv"
     fi
diff --git a/hw/kdrive/ephyr/XF86dri.c b/hw/kdrive/ephyr/XF86dri.c
index 9f230fc..15b6219 100644
--- a/hw/kdrive/ephyr/XF86dri.c
+++ b/hw/kdrive/ephyr/XF86dri.c
@@ -231,7 +231,7 @@ XF86DRIOpenConnection(Display * dpy, int screen,
         else
             *busIdString = NULL;
         if (*busIdString == NULL) {
-            _XEatData(dpy, ((rep.busIdStringLength + 3) & ~3));
+            _XEatDataWords(dpy, rep.length);
             UnlockDisplay(dpy);
             SyncHandle();
             TRACE("OpenConnection... return False");
@@ -333,7 +333,7 @@ XF86DRIGetClientDriverName(Display * dpy, int screen,
         else
             *clientDriverName = NULL;
         if (*clientDriverName == NULL) {
-            _XEatData(dpy, ((rep.clientDriverNameLength + 3) & ~3));
+            _XEatDataWords(dpy, rep.length);
             UnlockDisplay(dpy);
             SyncHandle();
             TRACE("GetClientDriverName... return False");
@@ -539,7 +539,7 @@ XF86DRIGetDrawableInfo(Display * dpy, int screen, Drawable drawable,
                           SIZEOF(xGenericReply) +
                           total_rects * sizeof(drm_clip_rect_t)) +
                          3) & ~3) >> 2)) {
-        _XEatData(dpy, rep.length);
+        _XEatDataWords(dpy, rep.length);
         UnlockDisplay(dpy);
         SyncHandle();
         TRACE("GetDrawableInfo... return False");
@@ -613,7 +613,7 @@ XF86DRIGetDeviceInfo(Display * dpy, int screen, drm_handle_t * hFrameBuffer,
 
     if (rep.length) {
         if (!(*pDevPrivate = (void *) calloc(rep.devPrivateSize, 1))) {
-            _XEatData(dpy, ((rep.devPrivateSize + 3) & ~3));
+            _XEatDataWords(dpy, rep.length);
             UnlockDisplay(dpy);
             SyncHandle();
             TRACE("GetDeviceInfo... return False");
diff --git a/hw/kdrive/ephyr/ephyrhostglx.c b/hw/kdrive/ephyr/ephyrhostglx.c
index 90f450c..6a4392f 100644
--- a/hw/kdrive/ephyr/ephyrhostglx.c
+++ b/hw/kdrive/ephyr/ephyrhostglx.c
@@ -211,8 +211,10 @@ ephyrHostGLXGetStringFromServer(int a_screen_number,
     _XReply(dpy, (xReply *) &reply, 0, False);
 
 #if UINT32_MAX >= (ULONG_MAX / 4)
-    if (reply.length >= (ULONG_MAX / 4))
+    if (reply.length >= (ULONG_MAX / 4)) {
+        _XEatDataWords(dpy, reply.length);
         goto eat_out;
+    }
 #endif
     if (reply.length > 0) {
         length = (unsigned long) reply.length * 4;
diff --git a/hw/kdrive/ephyr/ephyrhostvideo.c b/hw/kdrive/ephyr/ephyrhostvideo.c
index 362aa05..05e9ad9 100644
--- a/hw/kdrive/ephyr/ephyrhostvideo.c
+++ b/hw/kdrive/ephyr/ephyrhostvideo.c
@@ -677,7 +677,7 @@ ephyrHostXVQueryImageAttributes(int a_port_id,
         _XRead(dpy, (char *) a_offsets, rep.num_planes << 2);
     }
     else {
-        _XEatData(dpy, rep.length << 2);
+        _XEatDataWords(dpy, rep.length);
     }
     *a_width = rep.width;
     *a_height = rep.height;
commit a3d43edf71847f4b486f971405d2b457f81b73d1
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Fri Jul 5 22:35:32 2013 -0700

    glxproxy: Use _XEatDataWords (from Xlib 1.6) instead of _XEatData
    
    Reduces risk of overflow from converting length field in X replies
    from words to bytes.   (Also seems to be what several calls were
    already incorrectly passing to _XEatData.)
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>

diff --git a/configure.ac b/configure.ac
index 89a7a9d..206b9c4 100644
--- a/configure.ac
+++ b/configure.ac
@@ -2003,7 +2003,7 @@ AM_CONDITIONAL(STANDALONE_XPBPROXY, [test "x$STANDALONE_XPBPROXY" = xyes])
 dnl DMX DDX
 PKG_CHECK_MODULES(
 	[DMXMODULES],
-	[xmuu $LIBXEXT x11 xrender xfixes $LIBXI $DMXPROTO xau $XDMCP_MODULES],
+	[xmuu $LIBXEXT x11 >= 1.6 xrender xfixes $LIBXI $DMXPROTO xau $XDMCP_MODULES],
 	[PKG_CHECK_MODULES(
 		[XDMXCONFIG_DEP],
 		[xaw7 xmu xt xpm x11],
diff --git a/hw/dmx/glxProxy/glxcmds.c b/hw/dmx/glxProxy/glxcmds.c
index 0e817ca..8cdb25e 100644
--- a/hw/dmx/glxProxy/glxcmds.c
+++ b/hw/dmx/glxProxy/glxcmds.c
@@ -2610,7 +2610,7 @@ __glXQueryExtensionsString(__GLXclientState * cl, GLbyte * pc)
     be_buf = (char *) malloc(numbytes);
     if (!be_buf) {
         /* Throw data on the floor */
-        _XEatData(dpy, len);
+        _XEatDataWords(dpy, len);
     }
     else {
         _XReadPad(dpy, (char *) be_buf, numbytes);
@@ -2691,7 +2691,7 @@ __glXQueryServerString(__GLXclientState * cl, GLbyte * pc)
     be_buf = (char *) malloc(numbytes);
     if (!be_buf) {
         /* Throw data on the floor */
-        _XEatData(dpy, len);
+        _XEatDataWords(dpy, len);
     }
     else {
         _XReadPad(dpy, (char *) be_buf, numbytes);
diff --git a/hw/dmx/glxProxy/glxscreens.c b/hw/dmx/glxProxy/glxscreens.c
index 746d94e..138afed 100644
--- a/hw/dmx/glxProxy/glxscreens.c
+++ b/hw/dmx/glxProxy/glxscreens.c
@@ -154,7 +154,7 @@ CalcServerVersionAndExtensions(void)
         be_extensions[s] = (char *) malloc(numbytes);
         if (!be_extensions[s]) {
             /* Throw data on the floor */
-            _XEatData(dpy, length);
+            _XEatDataWords(dpy, length);
         }
         else {
             _XReadPad(dpy, (char *) be_extensions[s], numbytes);
diff --git a/hw/dmx/glxProxy/glxsingle.c b/hw/dmx/glxProxy/glxsingle.c
index e60cfeb..abfb880 100644
--- a/hw/dmx/glxProxy/glxsingle.c
+++ b/hw/dmx/glxProxy/glxsingle.c
@@ -258,7 +258,7 @@ __glXForwardPipe0WithReply(__GLXclientState * cl, GLbyte * pc)
         }
         else {
             /* Throw data on the floor */
-            _XEatData(dpy, be_buf_size);
+            _XEatDataWords(dpy, be_reply.length);
             return BadAlloc;
         }
     }
@@ -357,7 +357,7 @@ __glXForwardAllWithReply(__GLXclientState * cl, GLbyte * pc)
             }
             else {
                 /* Throw data on the floor */
-                _XEatData(dpy, be_buf_size);
+                _XEatDataWords(dpy, be_reply.length);
                 return BadAlloc;
             }
         }
@@ -993,7 +993,7 @@ __glXDisp_ReadPixels(__GLXclientState * cl, GLbyte * pc)
                     }
                     else {
                         /* Throw data on the floor */
-                        _XEatData(dpy, be_buf_size);
+                        _XEatDataWords(dpy, be_reply.length);
                         free(buf);
                         return BadAlloc;
                     }
diff --git a/hw/dmx/glxProxy/glxvendor.c b/hw/dmx/glxProxy/glxvendor.c
index 5777c6a..50d505c 100644
--- a/hw/dmx/glxProxy/glxvendor.c
+++ b/hw/dmx/glxProxy/glxvendor.c
@@ -246,7 +246,7 @@ __glXVForwardPipe0WithReply(__GLXclientState * cl, GLbyte * pc)
         }
         else {
             /* Throw data on the floor */
-            _XEatData(dpy, be_buf_size);
+            _XEatDataWords(dpy, be_reply.length);
             return BadAlloc;
         }
     }
@@ -340,7 +340,7 @@ __glXVForwardAllWithReply(__GLXclientState * cl, GLbyte * pc)
             }
             else {
                 /* Throw data on the floor */
-                _XEatData(dpy, be_buf_size);
+                _XEatDataWords(dpy, be_reply.length);
                 return BadAlloc;
             }
         }
commit 87b0cabc145a9b5f6faffdfb544ce1c647b8ab72
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Fri Jul 5 22:32:10 2013 -0700

    glxproxy: Use _XReadPad instead of _XEatData to clean up the slop
    
    Xlib already provides a function to eat padding bytes after the
    data read, so use it instead of calculating it ourselves.
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>

diff --git a/hw/dmx/glxProxy/glxcmds.c b/hw/dmx/glxProxy/glxcmds.c
index 4538274..0e817ca 100644
--- a/hw/dmx/glxProxy/glxcmds.c
+++ b/hw/dmx/glxProxy/glxcmds.c
@@ -2582,7 +2582,6 @@ __glXQueryExtensionsString(__GLXclientState * cl, GLbyte * pc)
     xGLXQueryExtensionsStringReply be_reply;
     DMXScreenInfo *dmxScreen;
     Display *dpy;
-    int slop;
 #endif
 
     screen = req->screen;
@@ -2608,16 +2607,13 @@ __glXQueryExtensionsString(__GLXclientState * cl, GLbyte * pc)
     _XReply(dpy, (xReply *) &be_reply, 0, False);
     len = (int) be_reply.length;
     numbytes = (int) be_reply.n;
-    slop = numbytes * __GLX_SIZE_INT8 & 3;
     be_buf = (char *) malloc(numbytes);
     if (!be_buf) {
         /* Throw data on the floor */
         _XEatData(dpy, len);
     }
     else {
-        _XRead(dpy, (char *) be_buf, numbytes);
-        if (slop)
-            _XEatData(dpy, 4 - slop);
+        _XReadPad(dpy, (char *) be_buf, numbytes);
     }
     UnlockDisplay(dpy);
     SyncHandle();
@@ -2666,7 +2662,6 @@ __glXQueryServerString(__GLXclientState * cl, GLbyte * pc)
     xGLXQueryServerStringReply be_reply;
     DMXScreenInfo *dmxScreen;
     Display *dpy;
-    int slop;
 #endif
 
     name = req->name;
@@ -2693,16 +2688,13 @@ __glXQueryServerString(__GLXclientState * cl, GLbyte * pc)
     _XReply(dpy, (xReply *) &be_reply, 0, False);
     len = (int) be_reply.length;
     numbytes = (int) be_reply.n;
-    slop = numbytes * __GLX_SIZE_INT8 & 3;
     be_buf = (char *) malloc(numbytes);
     if (!be_buf) {
         /* Throw data on the floor */
         _XEatData(dpy, len);
     }
     else {
-        _XRead(dpy, (char *) be_buf, numbytes);
-        if (slop)
-            _XEatData(dpy, 4 - slop);
+        _XReadPad(dpy, (char *) be_buf, numbytes);
     }
     UnlockDisplay(dpy);
     SyncHandle();
diff --git a/hw/dmx/glxProxy/glxscreens.c b/hw/dmx/glxProxy/glxscreens.c
index 2a19092..746d94e 100644
--- a/hw/dmx/glxProxy/glxscreens.c
+++ b/hw/dmx/glxProxy/glxscreens.c
@@ -138,7 +138,7 @@ CalcServerVersionAndExtensions(void)
         Display *dpy = dmxScreen->beDisplay;
         xGLXQueryServerStringReq *req;
         xGLXQueryServerStringReply reply;
-        int length, numbytes, slop;
+        int length, numbytes;
 
         /* Send the glXQueryServerString request */
         LockDisplay(dpy);
@@ -151,16 +151,13 @@ CalcServerVersionAndExtensions(void)
 
         length = (int) reply.length;
         numbytes = (int) reply.n;
-        slop = numbytes * __GLX_SIZE_INT8 & 3;
         be_extensions[s] = (char *) malloc(numbytes);
         if (!be_extensions[s]) {
             /* Throw data on the floor */
             _XEatData(dpy, length);
         }
         else {
-            _XRead(dpy, (char *) be_extensions[s], numbytes);
-            if (slop)
-                _XEatData(dpy, 4 - slop);
+            _XReadPad(dpy, (char *) be_extensions[s], numbytes);
         }
         UnlockDisplay(dpy);
         SyncHandle();
commit 1cb182cbdc11fc1c97507c57875f1d2453f27328
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Apr 15 08:41:14 2013 -0700

    Xephyr: integer overflow in XF86DRIGetClientDriverName()
    
    clientDriverNameLength is a CARD32 and needs to be bounds checked before
    adding one to it to come up with the total size to allocate, to avoid
    integer overflow leading to underallocation and writing data from the
    network past the end of the allocated buffer.
    
    Reported-by: Ilja Van Sprundel <ivansprundel at ioactive.com>
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Julien Cristau <jcristau at debian.org>

diff --git a/hw/kdrive/ephyr/XF86dri.c b/hw/kdrive/ephyr/XF86dri.c
index 7074bc3..9f230fc 100644
--- a/hw/kdrive/ephyr/XF86dri.c
+++ b/hw/kdrive/ephyr/XF86dri.c
@@ -328,9 +328,11 @@ XF86DRIGetClientDriverName(Display * dpy, int screen,
     *ddxDriverPatchVersion = rep.ddxDriverPatchVersion;
 
     if (rep.length) {
-        if (!
-            (*clientDriverName =
-             (char *) calloc(rep.clientDriverNameLength + 1, 1))) {
+        if (rep.clientDriverNameLength < INT_MAX)
+            *clientDriverName = calloc(rep.clientDriverNameLength + 1, 1);
+        else
+            *clientDriverName = NULL;
+        if (*clientDriverName == NULL) {
             _XEatData(dpy, ((rep.clientDriverNameLength + 3) & ~3));
             UnlockDisplay(dpy);
             SyncHandle();
commit 20644e53b385c54d73242c86a7d3f981d18a3843
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Mon Apr 15 08:39:03 2013 -0700

    Xephyr: integer overflow in XF86DRIOpenConnection()
    
    busIdStringLength is a CARD32 and needs to be bounds checked before adding
    one to it to come up with the total size to allocate, to avoid integer
    overflow leading to underallocation and writing data from the network past
    the end of the allocated buffer.
    
    Reported-by: Ilja Van Sprundel <ivansprundel at ioactive.com>
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Julien Cristau <jcristau at debian.org>

diff --git a/hw/kdrive/ephyr/XF86dri.c b/hw/kdrive/ephyr/XF86dri.c
index 9d742f3..7074bc3 100644
--- a/hw/kdrive/ephyr/XF86dri.c
+++ b/hw/kdrive/ephyr/XF86dri.c
@@ -64,6 +64,7 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 #include <GL/glx.h>
 #include "xf86dri.h"
 #include <X11/dri/xf86driproto.h>
+#include <limits.h>
 
 static XExtensionInfo _xf86dri_info_data;
 static XExtensionInfo *xf86dri_info = &_xf86dri_info_data;
@@ -225,7 +226,11 @@ XF86DRIOpenConnection(Display * dpy, int screen,
     }
 
     if (rep.length) {
-        if (!(*busIdString = (char *) calloc(rep.busIdStringLength + 1, 1))) {
+        if (rep.busIdStringLength < INT_MAX)
+            *busIdString = calloc(rep.busIdStringLength + 1, 1);
+        else
+            *busIdString = NULL;
+        if (*busIdString == NULL) {
             _XEatData(dpy, ((rep.busIdStringLength + 3) & ~3));
             UnlockDisplay(dpy);
             SyncHandle();
commit c37ceda76bf9ec6f5166122e864663e10f106546
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Sun Apr 14 10:50:50 2013 -0700

    Xephyr: integer overflow in ephyrHostGLXGetStringFromServer()
    
    reply.length & reply.size are CARD32s and need to be bounds checked before
    multiplying or adding to come up with the total size to allocate, to avoid
    integer overflow leading to underallocation and writing data from the
    network past the end of the allocated buffer.
    
    Reported-by: Ilja Van Sprundel <ivansprundel at ioactive.com>
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>

diff --git a/hw/kdrive/ephyr/ephyrhostglx.c b/hw/kdrive/ephyr/ephyrhostglx.c
index 5c6c40f..90f450c 100644
--- a/hw/kdrive/ephyr/ephyrhostglx.c
+++ b/hw/kdrive/ephyr/ephyrhostglx.c
@@ -137,7 +137,7 @@ ephyrHostGLXQueryVersion(int *a_major, int *a_minor)
 }
 
 /**
- * GLX protocol structure for the ficticious "GXLGenericGetString" request.
+ * GLX protocol structure for the ficticious "GLXGenericGetString" request.
  * 
  * This is a non-existant protocol packet.  It just so happens that all of
  * the real protocol packets used to request a string from the server have
@@ -169,7 +169,8 @@ ephyrHostGLXGetStringFromServer(int a_screen_number,
     int default_screen = DefaultScreen(dpy);
     xGLXGenericGetStringReq *req = NULL;
     xGLXSingleReply reply;
-    int length = 0, numbytes = 0, major_opcode = 0, get_string_op = 0;
+    unsigned long length = 0, numbytes = 0;
+    int major_opcode = 0, get_string_op = 0;
 
     EPHYR_RETURN_VAL_IF_FAIL(dpy && a_string, FALSE);
 
@@ -209,36 +210,46 @@ ephyrHostGLXGetStringFromServer(int a_screen_number,
 
     _XReply(dpy, (xReply *) &reply, 0, False);
 
-    length = reply.length * 4;
-    if (!length) {
-        numbytes = 0;
-    }
-    else {
+#if UINT32_MAX >= (ULONG_MAX / 4)
+    if (reply.length >= (ULONG_MAX / 4))
+        goto eat_out;
+#endif
+    if (reply.length > 0) {
+        length = (unsigned long) reply.length * 4;
         numbytes = reply.size;
+        if (numbytes > length) {
+            EPHYR_LOG_ERROR("string length %d longer than reply length %d\n",
+                            numbytes, length);
+            goto eat_out;
+        }
     }
     EPHYR_LOG("going to get a string of size:%d\n", numbytes);
 
-    *a_string = (char *) Xmalloc(numbytes + 1);
-    if (!a_string) {
+    if (numbytes < INT_MAX)
+        *a_string = Xcalloc(numbytes + 1, 1);
+    else
+        *a_string = NULL;
+    if (*a_string == NULL) {
         EPHYR_LOG_ERROR("allocation failed\n");
-        goto out;
+        goto eat_out;
     }
 
-    memset(*a_string, 0, numbytes + 1);
     if (_XRead(dpy, *a_string, numbytes)) {
-        UnlockDisplay(dpy);
-        SyncHandle();
         EPHYR_LOG_ERROR("read failed\n");
-        goto out;
+        length = 0; /* if read failed, no idea how much to eat */
+    }
+    else {
+        length -= numbytes;
+        EPHYR_LOG("strname:%#x, strvalue:'%s', strlen:%d\n",
+                  a_string_name, *a_string, numbytes);
+        is_ok = TRUE;
     }
-    length -= numbytes;
+
+ eat_out:
     _XEatData(dpy, length);
     UnlockDisplay(dpy);
     SyncHandle();
-    EPHYR_LOG("strname:%#x, strvalue:'%s', strlen:%d\n",
-              a_string_name, *a_string, numbytes);
 
-    is_ok = TRUE;
  out:
     EPHYR_LOG("leave\n");
     return is_ok;
commit 5fbd8c45b46ab93522e417240aa770466c30b735
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Sun Apr 14 09:45:26 2013 -0700

    Xdmx: integer overflow in GetGLXFBConfigs()
    
    numFBConfigs & numAttribs are CARD32s and need to be bounds checked before
    multiplying by structure sizes to come up with the total size to allocate,
    to avoid integer overflow leading to underallocation and writing data from
    the network past the end of the allocated buffer.
    
    Reported-by: Ilja Van Sprundel <ivansprundel at ioactive.com>
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>

diff --git a/hw/dmx/dmx_glxvisuals.c b/hw/dmx/dmx_glxvisuals.c
index 027557a..56bd67b 100644
--- a/hw/dmx/dmx_glxvisuals.c
+++ b/hw/dmx/dmx_glxvisuals.c
@@ -279,7 +279,10 @@ GetGLXFBConfigs(Display * dpy, int glxMajorOpcode, int *nconfigs)
         return NULL;
     }
 
-    attrs = (INT32 *) Xmalloc(2 * numAttribs * __GLX_SIZE_CARD32);
+    if (numAttribs < (INT_MAX / (2 * __GLX_SIZE_CARD32)))
+        attrs = Xmalloc(2 * numAttribs * __GLX_SIZE_CARD32);
+    else
+        attrs = NULL;
     if (!attrs) {
         UnlockDisplay(dpy);
         SyncHandle();
@@ -287,15 +290,16 @@ GetGLXFBConfigs(Display * dpy, int glxMajorOpcode, int *nconfigs)
     }
 
     /* Allocate memory for our config structure */
-    config = (__GLXFBConfig *)
-        Xmalloc(numFBConfigs * sizeof(__GLXFBConfig));
+    if (numFBConfigs < (INT_MAX / sizeof(__GLXFBConfig)))
+        config = Xcalloc(numFBConfigs, sizeof(__GLXFBConfig));
+    else
+        config = NULL;
     if (!config) {
         free(attrs);
         UnlockDisplay(dpy);
         SyncHandle();
         return NULL;
     }
-    memset(config, 0, numFBConfigs * sizeof(__GLXFBConfig));
     fbconfigs = config;
 
     /* Convert attribute list into our format */
commit c89bcd12f4fc7233830a8dbe7863c312f657da3c
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Sun Apr 14 09:33:57 2013 -0700

    Xdmx: integer overflow in GetGLXVisualConfigs()
    
    numVisuals & numProps are both CARD32 and need to be bounds checked before
    multiplying by structure sizes to come up with the total size to allocate,
    to avoid integer overflow leading to underallocation and writing data from
    the network past the end of the allocated buffer.
    
    Reported-by: Ilja Van Sprundel <ivansprundel at ioactive.com>
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>

diff --git a/hw/dmx/dmx_glxvisuals.c b/hw/dmx/dmx_glxvisuals.c
index f903b74..027557a 100644
--- a/hw/dmx/dmx_glxvisuals.c
+++ b/hw/dmx/dmx_glxvisuals.c
@@ -37,6 +37,7 @@
 #include <GL/glxproto.h>
 #include <X11/extensions/Xext.h>
 #include <X11/extensions/extutil.h>
+#include <limits.h>
 
 #include "dmx_glxvisuals.h"
 
@@ -84,7 +85,10 @@ GetGLXVisualConfigs(Display * dpy, int screen, int *nconfigs)
         SyncHandle();
         return NULL;
     }
-    props = (INT32 *) Xmalloc(nprops * __GLX_SIZE_CARD32);
+    if (nprops < (INT_MAX / __GLX_SIZE_CARD32))
+        props = Xmalloc(nprops * __GLX_SIZE_CARD32);
+    else
+        props = NULL;
     if (!props) {
         UnlockDisplay(dpy);
         SyncHandle();
@@ -92,15 +96,16 @@ GetGLXVisualConfigs(Display * dpy, int screen, int *nconfigs)
     }
 
     /* Allocate memory for our config structure */
-    config = (__GLXvisualConfig *)
-        Xmalloc(nvisuals * sizeof(__GLXvisualConfig));
+    if (nvisuals < (INT_MAX / sizeof(__GLXvisualConfig)))
+        config = Xcalloc(nvisuals, sizeof(__GLXvisualConfig));
+    else
+        config = NULL;
     if (!config) {
         free(props);
         UnlockDisplay(dpy);
         SyncHandle();
         return NULL;
     }
-    memset(config, 0, nvisuals * sizeof(__GLXvisualConfig));
     configs = config;
     num_good_visuals = 0;
 
commit 74469895e39fa38337f59edd64c4031ab9bb51d8
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Jul 15 13:06:28 2013 +1000

    dix: allow a ConstantDeceleration between 0 and 1 (#66134)
    
    A constant deceleration of x simply means (delta * 1/x). We limited that to
    values >= 1.0f for obvious reasons, but can also allow values from 0-1.
    That means that ConstantDeceleration is actually a ConstantAcceleration, but
    hey, if someone needs it...
    
    X.Org Bug 66134 <http://bugs.freedesktop.org/show_bug.cgi?id=66134>
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/dix/ptrveloc.c b/dix/ptrveloc.c
index d6fef9c..e75300a 100644
--- a/dix/ptrveloc.c
+++ b/dix/ptrveloc.c
@@ -245,11 +245,10 @@ AccelSetDecelProperty(DeviceIntPtr dev, Atom atom,
     if (checkOnly) {
         if (rc)
             return rc;
-        return (v >= 1.0f) ? Success : BadValue;
+        return (v > 0) ? Success : BadValue;
     }
 
-    if (v >= 1.0f)
-        vel->const_acceleration = 1 / v;
+    vel->const_acceleration = 1 / v;
 
     return Success;
 }
diff --git a/hw/xfree86/man/xorg.conf.man b/hw/xfree86/man/xorg.conf.man
index 67d8594..fa5b5fe 100644
--- a/hw/xfree86/man/xorg.conf.man
+++ b/hw/xfree86/man/xorg.conf.man
@@ -972,7 +972,8 @@ is constructed. This is mainly a matter of personal preference.
 .BI "Option \*qConstantDeceleration\*q  \*q" real \*q
 Makes the pointer go
 .B deceleration
-times slower than normal. Most useful for high-resolution devices.
+times slower than normal. Most useful for high-resolution devices. A value
+between 0 and 1 will speed up the pointer.
 .TP 7
 .BI "Option \*qAdaptiveDeceleration\*q  \*q" real \*q
 Allows to actually decelerate the pointer when going slow. At most, it will be
commit 0e3be0b25fcfeff386bad132526352c2e45f1932
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Jul 12 14:10:10 2013 +1000

    dix: UpdateTouchesForGrab must only free the listener grab if it is non-NULL
    
    If a client calls XIGrabDevice in response to a ButtonPress event (regular
    event selection), the device will have a grab, but listener->grab is NULL.
    
    Check for that, to avoid logspam.
    
    [ 26293.863] (EE) BUG: triggered 'if (!pGrab)'
    [ 26293.863] (EE) BUG: grabs.c:256 in FreeGrab()
    [ 26293.863] (EE)
    [ 26293.863] (EE) Backtrace:
    [ 26293.864] (EE) 0: /usr/bin/Xorg (FreeGrab+0x54) [0x45d3fc]
    [ 26293.864] (EE) 1: /usr/bin/Xorg (UpdateTouchesForGrab+0x135) [0x447d4e]
    [ 26293.864] (EE) 2: /usr/bin/Xorg (ActivatePointerGrab+0x1ba) [0x447f3d]
    [ 26293.864] (EE) 3: /usr/bin/Xorg (GrabDevice+0x3e6) [0x4503bc]
    [ 26293.864] (EE) 4: /usr/bin/Xorg (ProcXIGrabDevice+0x1f9) [0x5981b1]
    [ 26293.865] (EE) 5: /usr/bin/Xorg (ProcIDispatch+0x78) [0x58aa17]
    [ 26293.865] (EE) 6: /usr/bin/Xorg (Dispatch+0x30d) [0x43347e]
    [ 26293.865] (EE) 7: /usr/bin/Xorg (main+0x61d) [0x498175]
    [ 26293.865] (EE) 8: /lib64/libc.so.6 (__libc_start_main+0xf5) [0x3df5621b75]
    [ 26293.865] (EE) 9: /usr/bin/Xorg (_start+0x29) [0x423a19]
    [ 26293.866] (EE) 10: ? (?+0x29) [0x29]
    [ 26293.866] (EE)
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/dix/events.c b/dix/events.c
index 03b2d2e..ed3138d 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -1441,7 +1441,8 @@ UpdateTouchesForGrab(DeviceIntPtr mouse)
                 listener->type = LISTENER_POINTER_GRAB;
             else
                 listener->type = LISTENER_GRAB;
-            FreeGrab(listener->grab);
+            if (listener->grab)
+                FreeGrab(listener->grab);
             listener->grab = AllocGrab(grab);
         }
     }
commit 24cbb47ca80cd7a47749ece0ff3a98657ddf3ae3
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Jul 12 12:17:47 2013 +1000

    config: provide example configuration for multi-seat setups
    
    Seats other than seat0 need custom configuration. Provide that with a
    default configuration file so we can share it across distros.
    
    This file intentionally does not end in .conf so it won't get picked up by
    the server after a normal installation. gdm, or whatever starts up the
    servers will have to explicitly specifiy this config file.
    
    This file replaces the one currently written by systemd's multi-seat-x
    binary:
    http://cgit.freedesktop.org/systemd/systemd/tree/src/login/multi-seat-x.c
    
    CC: Lennart Poettering <lennart at poettering.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Dan Nicholson <dbn.lists at gmail.com>

diff --git a/config/Makefile.am b/config/Makefile.am
index da81d77..327d07e 100644
--- a/config/Makefile.am
+++ b/config/Makefile.am
@@ -44,4 +44,4 @@ endif # CONFIG_NEED_DBUS
 
 endif # !CONFIG_UDEV
 
-EXTRA_DIST = xorg-server.conf x11-input.fdi 10-evdev.conf fdi2iclass.py 10-quirks.conf
+EXTRA_DIST = xorg-server.conf x11-input.fdi 10-evdev.conf non-seat0.conf.multi-seat fdi2iclass.py 10-quirks.conf
diff --git a/config/non-seat0.conf.multi-seat b/config/non-seat0.conf.multi-seat
new file mode 100644
index 0000000..34008ce
--- /dev/null
+++ b/config/non-seat0.conf.multi-seat
@@ -0,0 +1,18 @@
+# This is the default configuration for servers on seat-1 and above.
+#
+# Start the server with -config non-seat0.conf.multi-seat, or alternatively
+# rename the file to end in .conf and put it in the standard config
+# directory (though it will apply to _all_ seats!).
+#
+# * Disable VT switching with Ctrl-Alt-F1
+# * Force a grab on all input devices to detach them from the VT subsystem
+#   to avoid event leakage.
+
+Section "ServerFlags"
+        Option "DontVTSwitch" "on"
+EndSection
+
+Section "InputClass"
+        Identifier "Force input devices to seat"
+        Option "GrabDevice" "on"
+EndSection
commit 791121e00692e12cb4c38c8d018bd72eb5081eb7
Author: François Tigeot <ftigeot at wolfpond.org>
Date:   Mon Jul 15 21:54:26 2013 +0200

    Fix mouse header include on DragonFly and FreeBSD
    
    *  __FreeBSD_kernel_version doesn't exist anymore
    
    * The removed check was for FreeBSD versions from before September 2000
      which are no longer supported anyway
    
    * Fixes: https://bugs.freedesktop.org/show_bug.cgi?id=66045
    
    Signed-off-by: François Tigeot <ftigeot at wolfpond.org>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/xfree86/os-support/xf86_OSlib.h b/hw/xfree86/os-support/xf86_OSlib.h
index e931b09..eb0a338 100644
--- a/hw/xfree86/os-support/xf86_OSlib.h
+++ b/hw/xfree86/os-support/xf86_OSlib.h
@@ -277,12 +277,7 @@ struct pcvtid {
 #include <dev/wscons/wsdisplay_usl_io.h>
 #endif                          /* WSCONS_SUPPORT */
 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
-#if defined(__FreeBSD_kernel_version) && (__FreeBSD_kernel_version >= 500013)
 #include <sys/mouse.h>
-#else
-#undef MOUSE_GETINFO
-#include <machine/mouse.h>
-#endif
 #endif
     /* Include these definitions in case ioctl_pc.h didn't get included */
 #ifndef CONSOLE_X_MODE_ON
commit 59a6d3f1eb03010ab831b32b03706a1d6143c732
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Thu Nov 8 13:41:13 2012 +0000

    os: Remove any old logfile before trying to write to it
    
    If we are not backing up logfiles, remove the old logfile before trying to write
    a new logfile, as otherwise the operation may fail if the previous logfile was
    created by a different user.
    
    This change is useful when:
    - The DDX doesn't use the logfile backup mechanism (i.e. not Xorg)
    - The DDX is run by a non-root user, and then by a different non-root user
    - The logfile directory doesn't have the restricted-deletion flag set
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Acked-by: Yaakov Selkowitz <yselkowitz at users.sourceforge.net>
    Reviewed-by: Yaakov Selkowitz <yselkowitz at users.sourceforge.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/os/log.c b/os/log.c
index f19faf5..53b3586 100644
--- a/os/log.c
+++ b/os/log.c
@@ -216,6 +216,9 @@ LogInit(const char *fname, const char *backup)
                 free(oldLog);
             }
         }
+        else {
+            unlink(logFileName);
+        }
         if ((logFile = fopen(logFileName, "w")) == NULL)
             FatalError("Cannot open log file \"%s\"\n", logFileName);
         setvbuf(logFile, NULL, _IONBF, 0);
commit 8eeaa74bc241acb41f1d3ed64971e0b01e794776
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Tue Jul 9 13:27:19 2013 +1000

    dix: when ungrabbing an active grab, accept pointer grabs (#66720)
    
    Ungrabbing a device during an active touch grab rejects the grab. Ungrabbing
    a device during an active pointer grab accepts the grab.
    
    Rejection is not really an option for a pointer-emulated grab, if a client
    has a button mask on the window it would get a ButtonPress emulated after
    UngrabDevice. That is against the core grab behaviour.
    
    X.Org Bug 66720 <http://bugs.freedesktop.org/show_bug.cgi?id=66720>
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Jasper St. Pierre <jstpierre at mecheye.net>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 2bbc6f0..fd4b80c 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1223,9 +1223,13 @@ ProcessTouchOwnershipEvent(TouchOwnershipEvent *ev,
     else if (ev->reason == XIAcceptTouch) {
         int i;
 
-        /* Go through the motions of ending the touch if the listener has
+
+        /* For pointer-emulated listeners that ungrabbed the active grab,
+         * the state was forced to LISTENER_HAS_END. Still go
+         * through the motions of ending the touch if the listener has
          * already seen the end. This ensures that the touch record is ended in
-         * the server. */
+         * the server.
+         */
         if (ti->listeners[0].state == LISTENER_HAS_END)
             TouchEmitTouchEnd(dev, ti, TOUCH_ACCEPT, ti->listeners[0].listener);
 
@@ -1883,16 +1887,23 @@ DeliverTouchEndEvent(DeviceIntPtr dev, TouchPointInfoPtr ti, InternalEvent *ev,
 
     if (listener->type == LISTENER_POINTER_REGULAR ||
         listener->type == LISTENER_POINTER_GRAB) {
-        rc = DeliverTouchEmulatedEvent(dev, ti, ev, listener, client, win,
-                                       grab, xi2mask);
-
-         /* Once we send a TouchEnd to a legacy listener, we're already well
-          * past the accepting/rejecting stage (can only happen on
-          * GrabModeSync + replay. This listener now gets the end event,
-          * and we can continue.
-          */
-        if (rc == Success)
-            listener->state = LISTENER_HAS_END;
+        /* Note: If the active grab was ungrabbed, we already changed the
+         * state to LISTENER_HAS_END but still get here. So we mustn't
+         * actually send the event.
+         * This is part two of the hack in DeactivatePointerGrab
+         */
+        if (listener->state != LISTENER_HAS_END) {
+            rc = DeliverTouchEmulatedEvent(dev, ti, ev, listener, client, win,
+                                           grab, xi2mask);
+
+             /* Once we send a TouchEnd to a legacy listener, we're already well
+              * past the accepting/rejecting stage (can only happen on
+              * GrabModeSync + replay. This listener now gets the end event,
+              * and we can continue.
+              */
+            if (rc == Success)
+                listener->state = LISTENER_HAS_END;
+        }
         goto out;
     }
 
diff --git a/dix/events.c b/dix/events.c
index e5db348..03b2d2e 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -1522,13 +1522,20 @@ DeactivatePointerGrab(DeviceIntPtr mouse)
     for (i = 0; !wasPassive && mouse->touch && i < mouse->touch->num_touches; i++) {
         TouchPointInfoPtr ti = mouse->touch->touches + i;
         if (ti->active && TouchResourceIsOwner(ti, grab_resource)) {
+            int mode = XIRejectTouch;
             /* Rejecting will generate a TouchEnd, but we must not
                emulate a ButtonRelease here. So pretend the listener
                already has the end event */
             if (grab->grabtype == CORE || grab->grabtype == XI ||
-                    !xi2mask_isset(mouse->deviceGrab.grab->xi2mask, mouse, XI_TouchBegin))
+                    !xi2mask_isset(mouse->deviceGrab.grab->xi2mask, mouse, XI_TouchBegin)) {
+                mode = XIAcceptTouch;
+                /* NOTE: we set the state here, but
+                 * ProcessTouchOwnershipEvent() will still call
+                 * TouchEmitTouchEnd for this listener. The other half of
+                 * this hack is in DeliverTouchEndEvent */
                 ti->listeners[0].state = LISTENER_HAS_END;
-            TouchListenerAcceptReject(mouse, ti, 0, XIRejectTouch);
+            }
+            TouchListenerAcceptReject(mouse, ti, 0, mode);
         }
     }
 
commit a2d6932ad48f2cbfcc4c5fb8272e47106d08ac78
Author: Julien Cristau <jcristau at debian.org>
Date:   Mon Jul 1 19:39:30 2013 +0200

    xkb: don't call atoi(NULL) when parsing argv
    
    If the -ardelay or -arinterval options have no argument, there's no
    point trying to read it.
    
    See
    http://www.forallsecure.com/bug-reports/feb3db57fc206d8df22ca53a6907f74973876272/
    
    Reported-by: Alexandre Rebert <alexandre at cmu.edu>
    Signed-off-by: Julien Cristau <jcristau at debian.org>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/xkb/xkbInit.c b/xkb/xkbInit.c
index 5308a29..f72655f 100644
--- a/xkb/xkbInit.c
+++ b/xkb/xkbInit.c
@@ -759,13 +759,15 @@ XkbProcessArguments(int argc, char *argv[], int i)
     if ((strcmp(argv[i], "-ardelay") == 0) || (strcmp(argv[i], "-ar1") == 0)) { /* -ardelay int */
         if (++i >= argc)
             UseMsg();
-        XkbDfltRepeatDelay = (long) atoi(argv[i]);
+        else
+            XkbDfltRepeatDelay = (long) atoi(argv[i]);
         return 2;
     }
     if ((strcmp(argv[i], "-arinterval") == 0) || (strcmp(argv[i], "-ar2") == 0)) {      /* -arinterval int */
         if (++i >= argc)
             UseMsg();
-        XkbDfltRepeatInterval = (long) atoi(argv[i]);
+        else
+            XkbDfltRepeatInterval = (long) atoi(argv[i]);
         return 2;
     }
     return 0;
commit 77e51d5bbb97eb5c9d9dbff9a7c44d7e53620e68
Author: Eric Anholt <eric at anholt.net>
Date:   Mon Jun 17 15:51:19 2013 -0700

    Revert "DRI2: re-allocate DRI2 drawable if pixmap serial changes"
    
    This reverts commit 3209b094a3b1466b579e8020e12a4f3fa78a5f3f.  After a
    long debug session by Paul Berry, it appears that this was the commit
    that has been producing sporadic failures in piglit front buffer
    rendering tests for the last several years.
    
    GetBuffers may return fresh buffers with invalid contents at a couple
    reasonable times:
    
    - When first asked for a non-fake-front buffer.
    - When the drawable size is changed, an Invalidate has been sent, and
      obviously the app needs to redraw the whole buffer.
    - After a glXSwapBuffers(), GL allows the backbuffer to be undefined,
      and an Invalidate was sent to tell the GL that it should grab these
      appropriate new buffers to avoid stalling.
    
    But with the patch being reverted, GetBuffers would also return fresh
    invalid buffers when the drawable serial number changed, which is
    approximately "whenever, for any reason".  The app is not expecting
    invalid buffer contents "whenever", nor is it valid.  Because the GL
    usually only GetBuffers after an Invalidate is sent, and the new
    buffer allocation only happened during a GetBuffers, most apps saw no
    problems.  But apps that do (fake-)frontbuffer rendering do frequently
    ask the server for the front buffer (since we drop the fake front
    allocation when we're not doing front buffer rendering), and if the
    drawable serial got bumped midway through a draw, the server would
    pointlessly ditch the front *and* backbuffer full of important
    drawing, resulting in bad rendering.
    
    The patch was originally to fix bugzilla:
    https://bugs.freedesktop.org/show_bug.cgi?id=28365
    Specifically:
    
        To reproduce, start with a large-ish display (i.e. 1680x1050 on my
        laptop), use the patched glxgears from bug 28252 to add the
        -override option.  Then run glxgears -override -geometry 640x480
        to create a 640x480 window in the top left corner, which will work
        fine.  Next, run xrandr -s 640x480 and watch the fireworks.
    
    I've tested with an override-redirect glxgears, both with vblank sync
    enabled and disabled, both with gnome-shell and no window manager at
    all, before and after this patch.  The only problem observed was that
    before and after the revert, sometimes when alt-tabbing to kill my
    gears after completing the test gnome-shell would get confused about
    override-redirectness of the glxgears window (according to a log
    message) and apparently not bother doing any further compositing.
    
    Signed-off-by: Eric Anholt <eric at anholt.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>
    Reviewed-by: Chris Wilson <chris at chris-wilson.co.uk>
    Tested-by: Chris Wilson <chris at chris-wilson.co.uk>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/xfree86/dri2/dri2.c b/hw/xfree86/dri2/dri2.c
index 40963c3..0b047f0 100644
--- a/hw/xfree86/dri2/dri2.c
+++ b/hw/xfree86/dri2/dri2.c
@@ -99,7 +99,6 @@ typedef struct _DRI2Drawable {
     CARD64 last_swap_msc;       /* msc at completion of most recent swap */
     CARD64 last_swap_ust;       /* ust at completion of most recent swap */
     int swap_limit;             /* for N-buffering */
-    unsigned long serialNumber;
     Bool needInvalidate;
     int prime_id;
     PixmapPtr prime_slave_pixmap;
@@ -189,19 +188,6 @@ DRI2GetDrawable(DrawablePtr pDraw)
     }
 }
 
-static unsigned long
-DRI2DrawableSerial(DrawablePtr pDraw)
-{
-    ScreenPtr pScreen = pDraw->pScreen;
-    PixmapPtr pPix;
-
-    if (pDraw->type != DRAWABLE_WINDOW)
-        return pDraw->serialNumber;
-
-    pPix = pScreen->GetWindowPixmap((WindowPtr) pDraw);
-    return pPix->drawable.serialNumber;
-}
-
 static DRI2DrawablePtr
 DRI2AllocateDrawable(DrawablePtr pDraw)
 {
@@ -235,7 +221,6 @@ DRI2AllocateDrawable(DrawablePtr pDraw)
     pPriv->last_swap_msc = 0;
     pPriv->last_swap_ust = 0;
     xorg_list_init(&pPriv->reference_list);
-    pPriv->serialNumber = DRI2DrawableSerial(pDraw);
     pPriv->needInvalidate = FALSE;
     pPriv->redirectpixmap = NULL;
     pPriv->prime_slave_pixmap = NULL;
@@ -493,7 +478,6 @@ allocate_or_reuse_buffer(DrawablePtr pDraw, DRI2ScreenPtr ds,
         || attachment == DRI2BufferFrontLeft
         || !dimensions_match || (pPriv->buffers[old_buf]->format != format)) {
         *buffer = create_buffer (pDraw, attachment, format);
-        pPriv->serialNumber = DRI2DrawableSerial(pDraw);
         return TRUE;
 
     }
@@ -559,8 +543,7 @@ do_get_buffers(DrawablePtr pDraw, int *width, int *height,
     ds = DRI2GetScreen(pDraw->pScreen);
 
     dimensions_match = (pDraw->width == pPriv->width)
-        && (pDraw->height == pPriv->height)
-        && (pPriv->serialNumber == DRI2DrawableSerial(pDraw));
+        && (pDraw->height == pPriv->height);
 
     buffers = calloc((count + 1), sizeof(buffers[0]));
     if (!buffers)
commit 227015d6544115258b74c31b700f9bd163540e24
Merge: d9005d5 80054fc
Author: Keith Packard <keithp at keithp.com>
Date:   Tue Jun 18 10:53:08 2013 -0700

    Merge remote-tracking branch 'jturney/master'

commit 80054fcafb095aff76f6df00d348c7fd85e8ddbc
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Sat Mar 30 19:44:14 2013 +0000

    hw/xwin: Update manifest to target all architectures, not just x86
    
    Update manifest to target all architectures, not just x86
    
    Also: Write explicit dependencies for Xwin.rc.  XWin.exe.manifest and X.ico are
    included the resource compiler output, so add a dependency on them to cause it
    to be recompiled if they change.
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/Makefile.am b/hw/xwin/Makefile.am
index 93ce570..f131975 100644
--- a/hw/xwin/Makefile.am
+++ b/hw/xwin/Makefile.am
@@ -160,6 +160,8 @@ XWin_LDFLAGS = -mwindows -static
 .rc.o:
 	$(AM_V_GEN)$(WINDRES) --use-temp-file -i $< --input-format=rc -o $@ -O coff -I $(top_builddir)/include
 
+XWin.o: XWin.rc XWin.exe.manifest X.ico
+
 winprefsyacc.h: winprefsyacc.c
 winprefslex.c: winprefslex.l winprefsyacc.c winprefsyacc.h
 
diff --git a/hw/xwin/XWin.exe.manifest b/hw/xwin/XWin.exe.manifest
index a0d4d7d..477334f 100755
--- a/hw/xwin/XWin.exe.manifest
+++ b/hw/xwin/XWin.exe.manifest
@@ -7,7 +7,7 @@
 	       type="win32"
 	       name="Microsoft.Windows.Common-Controls"
 	       version="6.0.0.0"
-	       processorArchitecture="X86"
+	       processorArchitecture="*"
 	       publicKeyToken="6595b64144ccf1df"
 	       language="*"
 	     />
commit 689e7ad9b0fccd582cd63796cc90a999f141f589
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Sun Mar 31 18:36:37 2013 +0100

    hw/xwin: Win32 Windows properties are of pointer type HANDLE, not an integer type
    
    Win32 Windows properties are of pointer type HANDLE, not an integer type, but we
    use the Windows property WINDOW_WID_PROP to store the X window XID.
    
    Add appropriate casts to show it doesn't matter that an XID is smaller than a
    pointer on 64-bit build.
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/winmultiwindowwindow.c b/hw/xwin/winmultiwindowwindow.c
index dcbfaff..44ad193 100644
--- a/hw/xwin/winmultiwindowwindow.c
+++ b/hw/xwin/winmultiwindowwindow.c
@@ -519,7 +519,7 @@ winCreateWindowsWindow(WindowPtr pWin)
     if (winMultiWindowGetTransientFor(pWin, &daddyId)) {
         if (daddyId) {
             hFore = GetForegroundWindow();
-            if (hFore && (daddyId != (Window) GetProp(hFore, WIN_WID_PROP)))
+            if (hFore && (daddyId != (Window) (INT_PTR) GetProp(hFore, WIN_WID_PROP)))
                 hFore = NULL;
         }
     }
@@ -593,7 +593,7 @@ winCreateWindowsWindow(WindowPtr pWin)
     /* Cause any .XWinrc menus to be added in main WNDPROC */
     PostMessage(hWnd, WM_INIT_SYS_MENU, 0, 0);
 
-    SetProp(hWnd, WIN_WID_PROP, (HANDLE) winGetWindowID(pWin));
+    SetProp(hWnd, WIN_WID_PROP, (HANDLE) (INT_PTR) winGetWindowID(pWin));
 
     /* Flag that this Windows window handles its own activation */
     SetProp(hWnd, WIN_NEEDMANAGE_PROP, (HANDLE) 0);
diff --git a/hw/xwin/winmultiwindowwndproc.c b/hw/xwin/winmultiwindowwndproc.c
index 0e46ea7..3818187 100644
--- a/hw/xwin/winmultiwindowwndproc.c
+++ b/hw/xwin/winmultiwindowwndproc.c
@@ -343,7 +343,7 @@ winTopLevelWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
         /* */
         wmMsg.msg = 0;
         wmMsg.hwndWindow = hwnd;
-        wmMsg.iWindow = (Window) GetProp(hwnd, WIN_WID_PROP);
+        wmMsg.iWindow = (Window) (INT_PTR) GetProp(hwnd, WIN_WID_PROP);
 
         wmMsg.iX = pDraw->x;
         wmMsg.iY = pDraw->y;
@@ -391,8 +391,8 @@ winTopLevelWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
         /* */
         SetProp(hwnd,
                 WIN_WID_PROP,
-                (HANDLE) winGetWindowID(((LPCREATESTRUCT) lParam)->
-                                        lpCreateParams));
+                (HANDLE) (INT_PTR) winGetWindowID(((LPCREATESTRUCT) lParam)->
+                                                  lpCreateParams));
 
         /*
          * Make X windows' Z orders sync with Windows windows because
diff --git a/hw/xwin/winprefs.c b/hw/xwin/winprefs.c
index 05d8c87..8936aae 100644
--- a/hw/xwin/winprefs.c
+++ b/hw/xwin/winprefs.c
@@ -181,7 +181,7 @@ ReloadEnumWindowsProc(HWND hwnd, LPARAM lParam)
 
                 wmMsg.msg = WM_WM_ICON_EVENT;
                 wmMsg.hwndWindow = hwnd;
-                wmMsg.iWindow = (Window) GetProp(hwnd, WIN_WID_PROP);
+                wmMsg.iWindow = (Window) (INT_PTR) GetProp(hwnd, WIN_WID_PROP);
 
                 winSendMessageToWM(s_pScreenPriv->pWMInfo, &wmMsg);
             }
commit e1a0945e8d4a3858838a14e64022524efd73c905
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Sun Mar 31 18:35:35 2013 +0100

    hw/xwin: winMultiWindowGetTransientFor() returns an XID not a WindowPtr
    
    winMultiWindowGetTransientFor() accesses the WM_TRANSIENT_FOR property, which is
    an X window XID (which we compare with WINDOW_WID_PROP) and not a WindowPtr.
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/winmultiwindowclass.c b/hw/xwin/winmultiwindowclass.c
index 1af104d..ced8f45 100644
--- a/hw/xwin/winmultiwindowclass.c
+++ b/hw/xwin/winmultiwindowclass.c
@@ -213,7 +213,7 @@ winMultiWindowGetWMNormalHints(WindowPtr pWin, WinXSizeHints * hints)
 }
 
 int
-winMultiWindowGetTransientFor(WindowPtr pWin, WindowPtr *ppDaddy)
+winMultiWindowGetTransientFor(WindowPtr pWin, Window *pDaddyId)
 {
     struct _Window *pwin;
     struct _Property *prop;
@@ -230,13 +230,13 @@ winMultiWindowGetTransientFor(WindowPtr pWin, WindowPtr *ppDaddy)
     else
         prop = NULL;
 
-    if (ppDaddy)
-        *ppDaddy = NULL;
+    if (pDaddyId)
+        *pDaddyId = 0;
 
     while (prop) {
         if (prop->propertyName == XA_WM_TRANSIENT_FOR) {
-            if (ppDaddy)
-                memcpy(ppDaddy, prop->data, sizeof(WindowPtr));
+            if (pDaddyId)
+                memcpy(pDaddyId, prop->data, sizeof(Window));
             return 1;
         }
         else
diff --git a/hw/xwin/winmultiwindowclass.h b/hw/xwin/winmultiwindowclass.h
index 0e3465c..3244f78 100644
--- a/hw/xwin/winmultiwindowclass.h
+++ b/hw/xwin/winmultiwindowclass.h
@@ -118,6 +118,6 @@ int
  winMultiWindowGetWMName(WindowPtr pWin, char **wmName);
 
 int
- winMultiWindowGetTransientFor(WindowPtr pWin, WindowPtr *ppDaddy);
+ winMultiWindowGetTransientFor(WindowPtr pWin, Window *ppDaddy);
 
 #endif
diff --git a/hw/xwin/winmultiwindowwindow.c b/hw/xwin/winmultiwindowwindow.c
index 0948156..dcbfaff 100644
--- a/hw/xwin/winmultiwindowwindow.c
+++ b/hw/xwin/winmultiwindowwindow.c
@@ -486,7 +486,7 @@ winCreateWindowsWindow(WindowPtr pWin)
     winWindowPriv(pWin);
     winPrivScreenPtr pScreenPriv = pWinPriv->pScreenPriv;
     WinXSizeHints hints;
-    WindowPtr pDaddy;
+    Window daddyId;
     DWORD dwStyle, dwExStyle;
     RECT rc;
 
@@ -516,10 +516,10 @@ winCreateWindowsWindow(WindowPtr pWin)
     winDebug("winCreateWindowsWindow - %dx%d @ %dx%d\n", iWidth, iHeight, iX,
              iY);
 
-    if (winMultiWindowGetTransientFor(pWin, &pDaddy)) {
-        if (pDaddy) {
+    if (winMultiWindowGetTransientFor(pWin, &daddyId)) {
+        if (daddyId) {
             hFore = GetForegroundWindow();
-            if (hFore && (pDaddy != (WindowPtr) GetProp(hFore, WIN_WID_PROP)))
+            if (hFore && (daddyId != (Window) GetProp(hFore, WIN_WID_PROP)))
                 hFore = NULL;
         }
     }
commit be201ac257687355bf0916d7c525d598ed9b1282
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Sat Mar 30 19:47:16 2013 +0000

    hw/xwin: Change winIconIsOverride() to take a HICON parameter
    
    Change winIconIsOverride() to take a HICON parameter, so some unneccessary
    casts, which weren't portable to 64-bit Cygwin, can be removed.
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/winmultiwindowicons.c b/hw/xwin/winmultiwindowicons.c
index 0322d98..bcc5688 100644
--- a/hw/xwin/winmultiwindowicons.c
+++ b/hw/xwin/winmultiwindowicons.c
@@ -624,7 +624,7 @@ winDestroyIcon(HICON hIcon)
     /* Delete the icon if its not one of the application defaults or an override */
     if (hIcon &&
         hIcon != g_hIconX &&
-        hIcon != g_hSmallIconX && !winIconIsOverride((unsigned long) hIcon))
+        hIcon != g_hSmallIconX && !winIconIsOverride(hIcon))
         DestroyIcon(hIcon);
 }
 #endif
diff --git a/hw/xwin/winprefs.c b/hw/xwin/winprefs.c
index 6cbd7ad..05d8c87 100644
--- a/hw/xwin/winprefs.c
+++ b/hw/xwin/winprefs.c
@@ -617,13 +617,10 @@ winOverrideIcon(char *res_name, char *res_class, char *wmName)
  * ICONS{} overrides)?
  */
 int
-winIconIsOverride(unsigned hiconIn)
+winIconIsOverride(HICON hicon)
 {
-    HICON hicon;
     int i;
 
-    hicon = (HICON) hiconIn;
-
     if (!hicon)
         return 0;
 
diff --git a/hw/xwin/winprefs.h b/hw/xwin/winprefs.h
index 5de5719..a4a6e7e 100644
--- a/hw/xwin/winprefs.h
+++ b/hw/xwin/winprefs.h
@@ -162,7 +162,7 @@ Bool
  HandleCustomWM_COMMAND(unsigned long hwndIn, int command);
 
 int
- winIconIsOverride(unsigned hiconIn);
+ winIconIsOverride(HICON hicon);
 
 HICON winOverrideIcon(char *res_name, char *res_class, char *wmName);
 
commit fc40f9a92cf5981bccc45bbc0b959cc06c5accc2
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Sat Mar 30 19:41:06 2013 +0000

    hw/xwin: Fix uses of CreateDialogParam() for 64-bit builds
    
    Fix uses of CreateDialogParam() to be more strictly correct, for 64-bit builds
    
    dwInitParam parameter is LPARAM, not int
    Return type of DLGPROC is INT_PTR, not WINBOOL
    
    Also: Reporting the value of g_hDlgDepthChange is completely uninteresting, we
    are just interested in GetLastError() if it is NULL
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/windialogs.c b/hw/xwin/windialogs.c
index 16f7ba0..054ee95 100644
--- a/hw/xwin/windialogs.c
+++ b/hw/xwin/windialogs.c
@@ -47,13 +47,13 @@ extern Bool g_fClipboardStarted;
  * Local function prototypes
  */
 
-static wBOOL CALLBACK
+static INT_PTR CALLBACK
 winExitDlgProc(HWND hDialog, UINT message, WPARAM wParam, LPARAM lParam);
 
-static wBOOL CALLBACK
+static INT_PTR CALLBACK
 winChangeDepthDlgProc(HWND hDialog, UINT message, WPARAM wParam, LPARAM lParam);
 
-static wBOOL CALLBACK
+static INT_PTR CALLBACK
 winAboutDlgProc(HWND hDialog, UINT message, WPARAM wParam, LPARAM lParam);
 
 static void
@@ -285,7 +285,7 @@ winDisplayExitDialog(winPrivScreenPtr pScreenPriv)
     g_hDlgExit = CreateDialogParam(g_hInstance,
                                    "EXIT_DIALOG",
                                    pScreenPriv->hwndScreen,
-                                   winExitDlgProc, (int) pScreenPriv);
+                                   winExitDlgProc, (LPARAM) pScreenPriv);
 
     /* Show the dialog box */
     ShowWindow(g_hDlgExit, SW_SHOW);
@@ -304,7 +304,7 @@ winDisplayExitDialog(winPrivScreenPtr pScreenPriv)
  * Exit dialog window procedure
  */
 
-static wBOOL CALLBACK
+static INT_PTR CALLBACK
 winExitDlgProc(HWND hDialog, UINT message, WPARAM wParam, LPARAM lParam)
 {
     static winPrivScreenPtr s_pScreenPriv = NULL;
@@ -404,14 +404,13 @@ winDisplayDepthChangeDialog(winPrivScreenPtr pScreenPriv)
                                           "DEPTH_CHANGE_BOX",
                                           pScreenPriv->hwndScreen,
                                           winChangeDepthDlgProc,
-                                          (int) pScreenPriv);
+                                          (LPARAM) pScreenPriv);
     /* Show the dialog box */
     ShowWindow(g_hDlgDepthChange, SW_SHOW);
 
-    ErrorF("winDisplayDepthChangeDialog - DialogBox returned: %d\n",
-           (int) g_hDlgDepthChange);
-    ErrorF("winDisplayDepthChangeDialog - GetLastError: %d\n",
-           (int) GetLastError());
+    if (!g_hDlgDepthChange)
+        ErrorF("winDisplayDepthChangeDialog - GetLastError: %d\n",
+                (int) GetLastError());
 
     /* Minimize the display window */
     ShowWindow(pScreenPriv->hwndScreen, SW_MINIMIZE);
@@ -422,7 +421,7 @@ winDisplayDepthChangeDialog(winPrivScreenPtr pScreenPriv)
  * disruptive screen depth changes. 
  */
 
-static wBOOL CALLBACK
+static INT_PTR CALLBACK
 winChangeDepthDlgProc(HWND hwndDialog, UINT message,
                       WPARAM wParam, LPARAM lParam)
 {
@@ -536,7 +535,7 @@ winDisplayAboutDialog(winPrivScreenPtr pScreenPriv)
     g_hDlgAbout = CreateDialogParam(g_hInstance,
                                     "ABOUT_BOX",
                                     pScreenPriv->hwndScreen,
-                                    winAboutDlgProc, (int) pScreenPriv);
+                                    winAboutDlgProc, (LPARAM) pScreenPriv);
 
     /* Show the dialog box */
     ShowWindow(g_hDlgAbout, SW_SHOW);
@@ -553,7 +552,7 @@ winDisplayAboutDialog(winPrivScreenPtr pScreenPriv)
  * Process messages for the about dialog.
  */
 
-static wBOOL CALLBACK
+static INT_PTR CALLBACK
 winAboutDlgProc(HWND hwndDialog, UINT message, WPARAM wParam, LPARAM lParam)
 {
     static winPrivScreenPtr s_pScreenPriv = NULL;
commit b542976846eb5d4c82910272af32ec8298da4177
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Sat Mar 30 19:40:31 2013 +0000

    hw/xwin: deprecated interface cygwin_conv_to_win32_path() doesn't exist in 64-bit cygwin
    
    The deprecated interface cygwin_conv_to_win32_path() doesn't exist in 64-bit
    cygwin, but both the ID_ABOUT_CHANGELOG control and the referenced file who's
    path we are converting haven't existed for a while, so just remove this unused,
    cygwin-specific code.
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/windialogs.c b/hw/xwin/windialogs.c
index 3ceaf4e..16f7ba0 100644
--- a/hw/xwin/windialogs.c
+++ b/hw/xwin/windialogs.c
@@ -33,9 +33,6 @@
 #include <xwin-config.h>
 #endif
 #include "win.h"
-#ifdef __CYGWIN__
-#include <sys/cygwin.h>
-#endif
 #include <shellapi.h>
 #include "winprefs.h"
 
@@ -623,17 +620,8 @@ winAboutDlgProc(HWND hwndDialog, UINT message, WPARAM wParam, LPARAM lParam)
         {
             INT_PTR iReturn;
 
-#ifdef __CYGWIN__
-            const char *pszCygPath = "/usr/X11R6/share/doc/"
-                "xorg-x11-xwin/changelog.html";
-            char pszWinPath[MAX_PATH + 1];
-
-            /* Convert the POSIX path to a Win32 path */
-            cygwin_conv_to_win32_path(pszCygPath, pszWinPath);
-#else
             const char *pszWinPath = "http://x.cygwin.com/"
                 "devel/server/changelog.html";
-#endif
 
             iReturn = (INT_PTR) ShellExecute(NULL,
                                          "open",
commit 5a47c6420cfe298143310938f08cc36a503e8d3d
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Mon Apr 8 01:27:26 2013 +0100

    hw/xwin: Fix a 64-bit portability issue with casting HINSTANCE result of ShellExecute() to an integer
    
    Fix a 64-bit portability issue with casting HINSTANCE result of ShellExecute()
    to an integer: Since HINSTANCE is a pointer type, use INT_PTR rather than int.
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/windialogs.c b/hw/xwin/windialogs.c
index 86f332a..3ceaf4e 100644
--- a/hw/xwin/windialogs.c
+++ b/hw/xwin/windialogs.c
@@ -621,7 +621,7 @@ winAboutDlgProc(HWND hwndDialog, UINT message, WPARAM wParam, LPARAM lParam)
 
         case ID_ABOUT_CHANGELOG:
         {
-            int iReturn;
+            INT_PTR iReturn;
 
 #ifdef __CYGWIN__
             const char *pszCygPath = "/usr/X11R6/share/doc/"
@@ -635,12 +635,12 @@ winAboutDlgProc(HWND hwndDialog, UINT message, WPARAM wParam, LPARAM lParam)
                 "devel/server/changelog.html";
 #endif
 
-            iReturn = (int) ShellExecute(NULL,
+            iReturn = (INT_PTR) ShellExecute(NULL,
                                          "open",
                                          pszWinPath, NULL, NULL, SW_MAXIMIZE);
             if (iReturn < 32) {
                 ErrorF("winAboutDlgProc - WM_COMMAND - ID_ABOUT_CHANGELOG - "
-                       "ShellExecute failed: %d\n", iReturn);
+                       "ShellExecute failed: %d\n", (int)iReturn);
             }
         }
             return TRUE;
@@ -648,14 +648,15 @@ winAboutDlgProc(HWND hwndDialog, UINT message, WPARAM wParam, LPARAM lParam)
         case ID_ABOUT_WEBSITE:
         {
             const char *pszPath = __VENDORDWEBSUPPORT__;
-            int iReturn;
+            INT_PTR iReturn;
 
-            iReturn = (int) ShellExecute(NULL,
+            iReturn = (INT_PTR) ShellExecute(NULL,
                                          "open",
                                          pszPath, NULL, NULL, SW_MAXIMIZE);
             if (iReturn < 32) {
                 ErrorF("winAboutDlgProc - WM_COMMAND - ID_ABOUT_WEBSITE - "
-                       "ShellExecute failed: %d\n", iReturn);
+                       "ShellExecute failed: %d\n", (int)iReturn);
+
             }
         }
             return TRUE;
@@ -663,14 +664,14 @@ winAboutDlgProc(HWND hwndDialog, UINT message, WPARAM wParam, LPARAM lParam)
         case ID_ABOUT_UG:
         {
             const char *pszPath = "http://x.cygwin.com/docs/ug/";
-            int iReturn;
+            INT_PTR iReturn;
 
-            iReturn = (int) ShellExecute(NULL,
+            iReturn = (INT_PTR) ShellExecute(NULL,
                                          "open",
                                          pszPath, NULL, NULL, SW_MAXIMIZE);
             if (iReturn < 32) {
                 ErrorF("winAboutDlgProc - WM_COMMAND - ID_ABOUT_UG - "
-                       "ShellExecute failed: %d\n", iReturn);
+                       "ShellExecute failed: %d\n", (int)iReturn);
             }
         }
             return TRUE;
@@ -678,14 +679,14 @@ winAboutDlgProc(HWND hwndDialog, UINT message, WPARAM wParam, LPARAM lParam)
         case ID_ABOUT_FAQ:
         {
             const char *pszPath = "http://x.cygwin.com/docs/faq/";
-            int iReturn;
+            INT_PTR iReturn;
 
-            iReturn = (int) ShellExecute(NULL,
+            iReturn = (INT_PTR) ShellExecute(NULL,
                                          "open",
                                          pszPath, NULL, NULL, SW_MAXIMIZE);
             if (iReturn < 32) {
                 ErrorF("winAboutDlgProc - WM_COMMAND - ID_ABOUT_FAQ - "
-                       "ShellExecute failed: %d\n", iReturn);
+                       "ShellExecute failed: %d\n", (int)iReturn);
             }
         }
             return TRUE;
commit d9005d58c0413dcc3a99150c13d05163881cf782
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Tue Jun 4 14:39:33 2013 +1000

    config: add a quirks file for devices needing special configuration
    
    This is the fedora quirks file configuring the special handling some devices
    need. Rather than keeping this distro-specific add it to the tree so we can
    share these quirks.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>

diff --git a/config/10-quirks.conf b/config/10-quirks.conf
new file mode 100644
index 0000000..c9b823c
--- /dev/null
+++ b/config/10-quirks.conf
@@ -0,0 +1,54 @@
+# Collection of quirks and blacklist/whitelists for specific devices.
+
+
+# Accelerometer device, posts data through ABS_X/ABS_Y, making X unusable
+# http://bugs.freedesktop.org/show_bug.cgi?id=22442 
+Section "InputClass"
+        Identifier "ThinkPad HDAPS accelerometer blacklist"
+        MatchProduct "ThinkPad HDAPS accelerometer data"
+        Option "Ignore" "on"
+EndSection
+
+# https://bugzilla.redhat.com/show_bug.cgi?id=523914
+# Mouse does not move in PV Xen guest
+# Explicitly tell evdev to not ignore the absolute axes.
+Section "InputClass"
+        Identifier "Xen Virtual Pointer axis blacklist"
+        MatchProduct "Xen Virtual Pointer"
+        Option "IgnoreAbsoluteAxes" "off"
+        Option "IgnoreRelativeAxes" "off"
+EndSection
+
+# https://bugzilla.redhat.com/show_bug.cgi?id=612140
+# please make Evoluent VerticalMouse 3 work out of the box
+# Button mapping on this mouse is quirky
+Section "InputClass"
+	Identifier "Evoluent VerticalMouse 3"
+        MatchProduct "Evoluent VerticalMouse 3"
+        # Sets following configuration:
+        # top button:    left
+        # middle button: middle
+        # bottom button: right
+        # wheel click:   middle
+        # thumb button:  8 (back)
+	Option "ButtonMapping" "1 2 2 4 5 6 7 3 8"
+EndSection
+
+
+# https://bugs.freedesktop.org/show_bug.cgi?id=55867
+# Bug 55867 - Doesn't know how to tag XI_TRACKBALL
+Section "InputClass"
+        Identifier "Tag trackballs as XI_TRACKBALL"
+        MatchProduct "trackball"
+        MatchDriver "evdev"
+        Option "TypeName" "TRACKBALL"
+EndSection
+
+# https://bugs.freedesktop.org/show_bug.cgi?id=62831
+# Bug 62831 - Mionix Naos 5000 mouse detected incorrectly
+Section "InputClass"
+        Identifier "Tag Mionix Naos 5000 mouse XI_MOUSE"
+        MatchProduct "La-VIEW Technology Naos 5000 Mouse"
+        MatchDriver "evdev"
+        Option "TypeName" "MOUSE"
+EndSection
diff --git a/config/Makefile.am b/config/Makefile.am
index 69bdcf7..da81d77 100644
--- a/config/Makefile.am
+++ b/config/Makefile.am
@@ -11,7 +11,7 @@ libconfig_la_LIBADD = $(UDEV_LIBS)
 
 if XORG
 xorgconfddir = $(datadir)/X11/$(XF86CONFIGDIR)
-xorgconfd_DATA = 10-evdev.conf
+xorgconfd_DATA = 10-evdev.conf 10-quirks.conf
 endif
 
 else
@@ -44,4 +44,4 @@ endif # CONFIG_NEED_DBUS
 
 endif # !CONFIG_UDEV
 
-EXTRA_DIST = xorg-server.conf x11-input.fdi 10-evdev.conf fdi2iclass.py
+EXTRA_DIST = xorg-server.conf x11-input.fdi 10-evdev.conf fdi2iclass.py 10-quirks.conf
commit 04ce6f6f6c880281e42c9ebf21d6f980ddae79b4
Author: Maarten Lankhorst <maarten.lankhorst at canonical.com>
Date:   Thu May 30 11:23:07 2013 +0200

    dix: add missing dixFreeRegistry define
    
    Fixes a build failure on debian's udeb builds.
    
    Signed-off-by: Maarten Lankhorst <maarten.lankhorst at canonical.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/include/registry.h b/include/registry.h
index e298ab6..96be87a 100644
--- a/include/registry.h
+++ b/include/registry.h
@@ -60,6 +60,7 @@ extern _X_EXPORT void dixFreeRegistry(void);
 #define LookupResourceName(a) XREGISTRY_UNKNOWN
 
 #define dixResetRegistry() { ; }
+#define dixFreeRegistry() { ; }
 
 #endif                          /* XREGISTRY */
 #endif                          /* DIX_REGISTRY_H */
commit c21344add2fc589df83b29be5831c36a372201bd
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon May 27 13:46:49 2013 +1000

    dix: remove logspam in RefCursor()
    
    This shouldn't have been in the patch
    
    Reported-by: Colin Harrison <colin.harrison at virgin.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/dix/cursor.c b/dix/cursor.c
index 0820b18..cd8305c 100644
--- a/dix/cursor.c
+++ b/dix/cursor.c
@@ -134,12 +134,8 @@ FreeCursor(pointer value, XID cid)
 CursorPtr
 RefCursor(CursorPtr cursor)
 {
-    ErrorF("%s ::::: cursor is %p", __func__, cursor);
-    if (cursor) {
-        xorg_backtrace();
+    if (cursor)
         cursor->refcnt++;
-    }
-    ErrorF("\n");
     return cursor;
 }
 
commit cb3018d8a15add48efb3335e1f79b66378166008
Merge: c76a1b3 6589f3b
Author: Keith Packard <keithp at keithp.com>
Date:   Thu May 23 19:58:46 2013 -0600

    Merge remote-tracking branch 'whot/unreviewed'

commit c76a1b343d6a56aa9529e87f0eda8d61355d562b
Merge: 891123c 9a5ad65
Author: Keith Packard <keithp at keithp.com>
Date:   Thu May 23 19:58:36 2013 -0600

    Merge remote-tracking branch 'whot/touch-grab-race-condition-56578-v3'

commit 891123ce9dac5e52685b9a921b33d8279ba52956
Merge: 7e97166 49521ed
Author: Keith Packard <keithp at keithp.com>
Date:   Thu May 23 10:30:15 2013 -0600

    Merge remote-tracking branch 'whot/for-keith'

commit 6589f3b55e335eef6c658c8ba1fe15a062f7e31c
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Tue May 14 08:31:19 2013 +1000

    dix: devices must have valuators before touch is initialized
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/devices.c b/dix/devices.c
index 291b767..527eea0 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -1647,6 +1647,7 @@ InitTouchClassDeviceStruct(DeviceIntPtr device, unsigned int max_touches,
 
     BUG_RETURN_VAL(device == NULL, FALSE);
     BUG_RETURN_VAL(device->touch != NULL, FALSE);
+    BUG_RETURN_VAL(device->valuator == NULL, FALSE);
 
     /* Check the mode is valid, and at least X and Y axes. */
     BUG_RETURN_VAL(mode != XIDirectTouch && mode != XIDependentTouch, FALSE);
commit 756ab88d93542f0589c9bf46f40ccc57df64f0fd
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Apr 26 15:10:08 2013 +1000

    dix: fix device scaling to use a [min,max[ range.
    
    defmin/defmax are screen coords and thus use a min-inclusive, max-exclusive
    range. device axes ranges are inclusive, so bump the max up by one to get the
    scaling right.
    
    This fixes off-by-one coordinate errors if the coordinate matrix is used to
    bind the device to a fraction of the screen. It introduces an off-by-one
    scaling error in the device coordinate range, but since most devices have a
    higher resolution than the screen (e.g. a Wacom I4 has 5080 dpi) the effect
    of this should be limited.
    
    This error manifests when we have numScreens > 1, as the scaling from
    desktop size back to screen size drops one device unit.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/devices.c b/dix/devices.c
index 9b6faee..291b767 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -112,8 +112,8 @@ DeviceSetTransform(DeviceIntPtr dev, float *transform_data)
      *  Transform is the user supplied (affine) transform
      *  InvScale scales coordinates back up into their native range
      */
-    sx = dev->valuator->axes[0].max_value - dev->valuator->axes[0].min_value;
-    sy = dev->valuator->axes[1].max_value - dev->valuator->axes[1].min_value;
+    sx = dev->valuator->axes[0].max_value - dev->valuator->axes[0].min_value + 1;
+    sy = dev->valuator->axes[1].max_value - dev->valuator->axes[1].min_value + 1;
 
     /* invscale */
     pixman_f_transform_init_scale(&scale, sx, sy);
diff --git a/dix/getevents.c b/dix/getevents.c
index ac0ccb2..51d4fd4 100644
--- a/dix/getevents.c
+++ b/dix/getevents.c
@@ -298,11 +298,11 @@ rescaleValuatorAxis(double coord, AxisInfoPtr from, AxisInfoPtr to,
 
     if (from && from->min_value < from->max_value) {
         fmin = from->min_value;
-        fmax = from->max_value;
+        fmax = from->max_value + 1;
     }
     if (to && to->min_value < to->max_value) {
         tmin = to->min_value;
-        tmax = to->max_value;
+        tmax = to->max_value + 1;
     }
 
     if (fmin == tmin && fmax == tmax)
@@ -924,9 +924,9 @@ scale_to_desktop(DeviceIntPtr dev, ValuatorMask *mask,
 
     /* scale x&y to desktop coordinates */
     *screenx = rescaleValuatorAxis(x, dev->valuator->axes + 0, NULL,
-                                   screenInfo.x, screenInfo.width - 1);
+                                   screenInfo.x, screenInfo.width);
     *screeny = rescaleValuatorAxis(y, dev->valuator->axes + 1, NULL,
-                                   screenInfo.y, screenInfo.height - 1);
+                                   screenInfo.y, screenInfo.height);
 
     *devx = x;
     *devy = y;
@@ -1366,6 +1366,12 @@ QueuePointerEvents(DeviceIntPtr device, int type,
  * is the last coordinate on the first screen and must be rescaled for the
  * event to be m. XI2 clients that do their own coordinate mapping would
  * otherwise interpret the position of the device elsewere to the cursor.
+ * However, this scaling leads to losses:
+ * if we have two ScreenRecs we scale from e.g. [0..44704]  (Wacom I4) to
+ * [0..2048[. that gives us 2047.954 as desktop coord, or the per-screen
+ * coordinate 1023.954. Scaling that back into the device coordinate range
+ * gives us 44703. So off by one device unit. It's a bug, but we'll have to
+ * live with it because with all this scaling, we just cannot win.
  *
  * @return the number of events written into events.
  */
commit 5cc2c96f824dbb28b9f8da61efc41596f8bd0561
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Sat Mar 9 20:43:51 2013 +1000

    dix: pre-scale x by the screen:device:resolution ratio
    
    commit 61a99aff9d33728a0b67920254d2d4d79f80cf39
        dix: pre-scale relative events from abs devices to desktop ratio (#31636)
    
    added pre-scaling of relative coordinates coming from absolute devices to
    undo uneven scaling based on the screen dimensions.
    
    Devices have their own device width/height ratio as well (in a specific
    resolution) and this must be applied for relative devices as well to avoid
    scaling of the relative events into the device's ratio.
    
    e.g. a Wacom Intuos4 6x9 is in 16:10 format with equal horiz/vert
    resolution (dpi). A movement by 1000/1000 coordinates is a perfect diagonal
    on the tablet and must be reflected as such on the screen.
    
    However, we map the relative device-coordinate events to absolute screen
    coordinates based on the axis ranges. This results in an effective scaling
    of 1000/(1000 * 1.6) and thus an uneven x/y axis movement - the y
    axis is always faster.
    
    So we need to pre-scale not only by the desktop dimenstions but also by the
    device width/height ratio _and_ the resolution ratio.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/getevents.c b/dix/getevents.c
index 241c7ec..ac0ccb2 100644
--- a/dix/getevents.c
+++ b/dix/getevents.c
@@ -770,6 +770,29 @@ add_to_scroll_valuator(DeviceIntPtr dev, ValuatorMask *mask, int valuator, doubl
 }
 
 
+static void
+scale_for_device_resolution(DeviceIntPtr dev, ValuatorMask *mask)
+{
+    double x;
+    ValuatorClassPtr v = dev->valuator;
+    int xrange = v->axes[0].max_value - v->axes[0].min_value + 1;
+    int yrange = v->axes[1].max_value - v->axes[1].min_value + 1;
+
+    double screen_ratio = 1.0 * screenInfo.width/screenInfo.height;
+    double device_ratio = 1.0 * xrange/yrange;
+    double resolution_ratio = 1.0;
+    double ratio;
+
+    if (!valuator_mask_fetch_double(mask, 0, &x))
+        return;
+
+    if (v->axes[0].resolution != 0 && v->axes[1].resolution != 0)
+        resolution_ratio = 1.0 * v->axes[0].resolution/v->axes[1].resolution;
+
+    ratio = device_ratio/resolution_ratio/screen_ratio;
+    valuator_mask_set_double(mask, 0, x * ratio);
+}
+
 /**
  * Move the device's pointer by the values given in @valuators.
  *
@@ -781,27 +804,14 @@ moveRelative(DeviceIntPtr dev, int flags, ValuatorMask *mask)
 {
     int i;
     Bool clip_xy = IsMaster(dev) || !IsFloating(dev);
+    ValuatorClassPtr v = dev->valuator;
 
     /* for abs devices in relative mode, we've just scaled wrong, since we
        mapped the device's shape into the screen shape. Undo this. */
-    if ((flags & POINTER_ABSOLUTE) == 0 && dev->valuator &&
-        dev->valuator->axes[0].min_value < dev->valuator->axes[0].max_value) {
-
-        double ratio = 1.0 * screenInfo.width/screenInfo.height;
-
-        if (ratio > 1.0) {
-            double y;
-            if (valuator_mask_fetch_double(mask, 1, &y)) {
-                y *= ratio;
-                valuator_mask_set_double(mask, 1, y);
-            }
-        } else {
-            double x;
-            if (valuator_mask_fetch_double(mask, 0, &x)) {
-                x *= ratio;
-                valuator_mask_set_double(mask, 0, x);
-            }
-        }
+    if ((flags & POINTER_ABSOLUTE) == 0 && v && v->numAxes > 1 &&
+        v->axes[0].min_value < v->axes[0].max_value &&
+        v->axes[1].min_value < v->axes[1].max_value) {
+        scale_for_device_resolution(dev, mask);
     }
 
     /* calc other axes, clip, drop back into valuators */
commit 9a5ad65330693b3273972b63d10f2907d9ab954a
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed May 15 19:01:11 2013 +1000

    Abstract cursor refcounting
    
    Too many callers relied on the refcnt being handled correctly. Use a simple
    wrapper to handle that case.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xext/saver.c b/Xext/saver.c
index 8de043f..fe81bc4 100644
--- a/Xext/saver.c
+++ b/Xext/saver.c
@@ -531,15 +531,16 @@ CreateSaverWindow(ScreenPtr pScreen)
         mask |= CWBorderPixmap;
     }
     if (pAttr->pCursor) {
+        CursorPtr cursor;
         if (!pWin->optional)
             if (!MakeWindowOptional(pWin)) {
                 FreeResource(pWin->drawable.id, RT_NONE);
                 return FALSE;
             }
-        pAttr->pCursor->refcnt++;
+        cursor = RefCursor(pAttr->pCursor);
         if (pWin->optional->cursor)
             FreeCursor(pWin->optional->cursor, (Cursor) 0);
-        pWin->optional->cursor = pAttr->pCursor;
+        pWin->optional->cursor = cursor;
         pWin->cursorIsNone = FALSE;
         CheckWindowOptionalNeed(pWin);
         mask |= CWCursor;
@@ -1065,8 +1066,7 @@ ScreenSaverSetAttributes(ClientPtr client)
                     client->errorValue = cursorID;
                     goto PatchUp;
                 }
-                pCursor->refcnt++;
-                pAttr->pCursor = pCursor;
+                pAttr->pCursor = RefCursor(pCursor);
                 pAttr->mask &= ~CWCursor;
             }
             break;
diff --git a/dix/cursor.c b/dix/cursor.c
index 1ee127a..0820b18 100644
--- a/dix/cursor.c
+++ b/dix/cursor.c
@@ -114,9 +114,13 @@ FreeCursor(pointer value, XID cid)
     ScreenPtr pscr;
     DeviceIntPtr pDev = NULL;   /* unused anyway */
 
-    if (--pCurs->refcnt != 0)
+
+    UnrefCursor(pCurs);
+    if (CursorRefCount(pCurs) != 0)
         return Success;
 
+    BUG_WARN(CursorRefCount(pCurs) < 0);
+
     for (nscr = 0; nscr < screenInfo.numScreens; nscr++) {
         pscr = screenInfo.screens[nscr];
         (void) (*pscr->UnrealizeCursor) (pDev, pscr, pCurs);
@@ -127,6 +131,33 @@ FreeCursor(pointer value, XID cid)
     return Success;
 }
 
+CursorPtr
+RefCursor(CursorPtr cursor)
+{
+    ErrorF("%s ::::: cursor is %p", __func__, cursor);
+    if (cursor) {
+        xorg_backtrace();
+        cursor->refcnt++;
+    }
+    ErrorF("\n");
+    return cursor;
+}
+
+CursorPtr
+UnrefCursor(CursorPtr cursor)
+{
+    if (cursor)
+        cursor->refcnt--;
+    return cursor;
+}
+
+int
+CursorRefCount(const CursorPtr cursor)
+{
+    return cursor ? cursor->refcnt : 0;
+}
+
+
 /*
  * We check for empty cursors so that we won't have to display them
  */
diff --git a/dix/events.c b/dix/events.c
index 8124ca9..e5db348 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -931,8 +931,7 @@ ChangeToCursor(DeviceIntPtr pDev, CursorPtr cursor)
 
         (*pScreen->DisplayCursor) (pDev, pScreen, cursor);
         FreeCursor(pSprite->current, (Cursor) 0);
-        pSprite->current = cursor;
-        pSprite->current->refcnt++;
+        pSprite->current = RefCursor(cursor);
     }
 }
 
@@ -3210,11 +3209,10 @@ InitializeSprite(DeviceIntPtr pDev, WindowPtr pWin)
         pSprite->pEnqueueScreen = screenInfo.screens[0];
         pSprite->pDequeueScreen = pSprite->pEnqueueScreen;
     }
-    if (pCursor)
-        pCursor->refcnt++;
+    pCursor = RefCursor(pCursor);
     if (pSprite->current)
         FreeCursor(pSprite->current, None);
-    pSprite->current = pCursor;
+    pSprite->current = RefCursor(pCursor);
 
     if (pScreen) {
         (*pScreen->RealizeCursor) (pDev, pScreen, pSprite->current);
@@ -3293,9 +3291,7 @@ UpdateSpriteForScreen(DeviceIntPtr pDev, ScreenPtr pScreen)
     pSprite->hotLimits.x2 = pScreen->width;
     pSprite->hotLimits.y2 = pScreen->height;
     pSprite->win = win;
-    pCursor = wCursor(win);
-    if (pCursor)
-        pCursor->refcnt++;
+    pCursor = RefCursor(wCursor(win));
     if (pSprite->current)
         FreeCursor(pSprite->current, 0);
     pSprite->current = pCursor;
@@ -4945,9 +4941,7 @@ ProcChangeActivePointerGrab(ClientPtr client)
         (CompareTimeStamps(time, device->deviceGrab.grabTime) == EARLIER))
         return Success;
     oldCursor = grab->cursor;
-    grab->cursor = newCursor;
-    if (newCursor)
-        newCursor->refcnt++;
+    grab->cursor = RefCursor(newCursor);
     PostNewCursor(device);
     if (oldCursor)
         FreeCursor(oldCursor, (Cursor) 0);
@@ -5092,9 +5086,7 @@ GrabDevice(ClientPtr client, DeviceIntPtr dev,
         else
             xi2mask_merge(tempGrab->xi2mask, mask->xi2mask);
         tempGrab->device = dev;
-        tempGrab->cursor = cursor;
-        if (cursor)
-            tempGrab->cursor->refcnt++;
+        tempGrab->cursor = RefCursor(cursor);
         tempGrab->confineTo = confineTo;
         tempGrab->grabtype = grabtype;
         (*grabInfo->ActivateGrab) (dev, tempGrab, time, FALSE);
diff --git a/dix/grabs.c b/dix/grabs.c
index b254ddc..a03897a 100644
--- a/dix/grabs.c
+++ b/dix/grabs.c
@@ -241,13 +241,11 @@ CreateGrab(int client, DeviceIntPtr device, DeviceIntPtr modDevice,
     grab->detail.exact = keybut;
     grab->detail.pMask = NULL;
     grab->confineTo = confineTo;
-    grab->cursor = cursor;
+    grab->cursor = RefCursor(cursor);
     grab->next = NULL;
 
     if (grabtype == XI2)
         xi2mask_merge(grab->xi2mask, mask->xi2mask);
-    if (cursor)
-        cursor->refcnt++;
     return grab;
 
 }
@@ -274,9 +272,6 @@ CopyGrab(GrabPtr dst, const GrabPtr src)
     Mask *details_mask = NULL;
     XI2Mask *xi2mask;
 
-    if (src->cursor)
-        src->cursor->refcnt++;
-
     if (src->modifiersDetail.pMask) {
         int len = MasksPerDetailMask * sizeof(Mask);
 
@@ -314,6 +309,7 @@ CopyGrab(GrabPtr dst, const GrabPtr src)
     dst->modifiersDetail.pMask = mdetails_mask;
     dst->detail.pMask = details_mask;
     dst->xi2mask = xi2mask;
+    dst->cursor = RefCursor(src->cursor);
 
     xi2mask_merge(dst->xi2mask, src->xi2mask);
 
diff --git a/dix/window.c b/dix/window.c
index a9297f3..8950f97 100644
--- a/dix/window.c
+++ b/dix/window.c
@@ -547,8 +547,7 @@ InitRootWindow(WindowPtr pWin)
     (*pScreen->PositionWindow) (pWin, 0, 0);
 
     pWin->cursorIsNone = FALSE;
-    pWin->optional->cursor = rootCursor;
-    rootCursor->refcnt++;
+    pWin->optional->cursor = RefCursor(rootCursor);
 
     if (party_like_its_1989) {
         MakeRootTile(pWin);
@@ -1416,8 +1415,7 @@ ChangeWindowAttributes(WindowPtr pWin, Mask vmask, XID *vlist, ClientPtr client)
                     else if (pWin->parent && pCursor == wCursor(pWin->parent))
                         checkOptional = TRUE;
                     pOldCursor = pWin->optional->cursor;
-                    pWin->optional->cursor = pCursor;
-                    pCursor->refcnt++;
+                    pWin->optional->cursor = RefCursor(pCursor);
                     pWin->cursorIsNone = FALSE;
                     /*
                      * check on any children now matching the new cursor
@@ -3323,8 +3321,7 @@ MakeWindowOptional(WindowPtr pWin)
     parentOptional = FindWindowWithOptional(pWin)->optional;
     optional->visual = parentOptional->visual;
     if (!pWin->cursorIsNone) {
-        optional->cursor = parentOptional->cursor;
-        optional->cursor->refcnt++;
+        optional->cursor = RefCursor(parentOptional->cursor);
     }
     else {
         optional->cursor = None;
@@ -3412,8 +3409,7 @@ ChangeWindowDeviceCursor(WindowPtr pWin, DeviceIntPtr pDev, CursorPtr pCursor)
     if (pCursor && WindowParentHasDeviceCursor(pWin, pDev, pCursor))
         pNode->cursor = None;
     else {
-        pNode->cursor = pCursor;
-        pCursor->refcnt++;
+        pNode->cursor = RefCursor(pCursor);
     }
 
     pNode = pPrev = NULL;
@@ -3421,8 +3417,7 @@ ChangeWindowDeviceCursor(WindowPtr pWin, DeviceIntPtr pDev, CursorPtr pCursor)
     for (pChild = pWin->firstChild; pChild; pChild = pChild->nextSib) {
         if (WindowSeekDeviceCursor(pChild, pDev, &pNode, &pPrev)) {
             if (pNode->cursor == None) {        /* inherited from parent */
-                pNode->cursor = pOldCursor;
-                pOldCursor->refcnt++;
+                pNode->cursor = RefCursor(pOldCursor);
             }
             else if (pNode->cursor == pCursor) {
                 pNode->cursor = None;
diff --git a/hw/xfree86/modes/xf86Cursors.c b/hw/xfree86/modes/xf86Cursors.c
index 634ee3f..2b0db34 100644
--- a/hw/xfree86/modes/xf86Cursors.c
+++ b/hw/xfree86/modes/xf86Cursors.c
@@ -481,7 +481,7 @@ xf86_use_hw_cursor(ScreenPtr screen, CursorPtr cursor)
     xf86CrtcConfigPtr xf86_config = XF86_CRTC_CONFIG_PTR(scrn);
     xf86CursorInfoPtr cursor_info = xf86_config->cursor_info;
 
-    ++cursor->refcnt;
+    cursor = RefCursor(cursor);
     if (xf86_config->cursor)
         FreeCursor(xf86_config->cursor, None);
     xf86_config->cursor = cursor;
@@ -500,7 +500,7 @@ xf86_use_hw_cursor_argb(ScreenPtr screen, CursorPtr cursor)
     xf86CrtcConfigPtr xf86_config = XF86_CRTC_CONFIG_PTR(scrn);
     xf86CursorInfoPtr cursor_info = xf86_config->cursor_info;
 
-    ++cursor->refcnt;
+    cursor = RefCursor(cursor);
     if (xf86_config->cursor)
         FreeCursor(xf86_config->cursor, None);
     xf86_config->cursor = cursor;
diff --git a/hw/xfree86/ramdac/xf86Cursor.c b/hw/xfree86/ramdac/xf86Cursor.c
index d32aac1..860704e 100644
--- a/hw/xfree86/ramdac/xf86Cursor.c
+++ b/hw/xfree86/ramdac/xf86Cursor.c
@@ -271,7 +271,7 @@ xf86CursorRealizeCursor(DeviceIntPtr pDev, ScreenPtr pScreen, CursorPtr pCurs)
         (xf86CursorScreenPtr) dixLookupPrivate(&pScreen->devPrivates,
                                                xf86CursorScreenKey);
 
-    if (pCurs->refcnt <= 1)
+    if (CursorRefCount(pCurs) <= 1)
         dixSetScreenPrivate(&pCurs->devPrivates, CursorScreenKey, pScreen,
                             NULL);
 
@@ -285,7 +285,7 @@ xf86CursorUnrealizeCursor(DeviceIntPtr pDev, ScreenPtr pScreen, CursorPtr pCurs)
         (xf86CursorScreenPtr) dixLookupPrivate(&pScreen->devPrivates,
                                                xf86CursorScreenKey);
 
-    if (pCurs->refcnt <= 1) {
+    if (CursorRefCount(pCurs) <= 1) {
         free(dixLookupScreenPrivate
              (&pCurs->devPrivates, CursorScreenKey, pScreen));
         dixSetScreenPrivate(&pCurs->devPrivates, CursorScreenKey, pScreen,
@@ -322,37 +322,37 @@ xf86CursorSetCursor(DeviceIntPtr pDev, ScreenPtr pScreen, CursorPtr pCurs,
     /* only update for VCP, otherwise we get cursor jumps when removing a
        sprite. The second cursor is never HW rendered anyway. */
     if (GetMaster(pDev, MASTER_POINTER) == inputInfo.pointer) {
-        pCurs->refcnt++;
+        CursorPtr cursor = RefCursor(pCurs);
         if (ScreenPriv->CurrentCursor)
             FreeCursor(ScreenPriv->CurrentCursor, None);
-        ScreenPriv->CurrentCursor = pCurs;
+        ScreenPriv->CurrentCursor = cursor;
         ScreenPriv->x = x;
         ScreenPriv->y = y;
         ScreenPriv->CursorToRestore = NULL;
-        ScreenPriv->HotX = pCurs->bits->xhot;
-        ScreenPriv->HotY = pCurs->bits->yhot;
+        ScreenPriv->HotX = cursor->bits->xhot;
+        ScreenPriv->HotY = cursor->bits->yhot;
 
         if (!infoPtr->pScrn->vtSema)
-            ScreenPriv->SavedCursor = pCurs;
+            ScreenPriv->SavedCursor = cursor;
 
         if (infoPtr->pScrn->vtSema && xorg_list_is_empty(&pScreen->pixmap_dirty_list) &&
             (ScreenPriv->ForceHWCursorCount ||
              ((
 #ifdef ARGB_CURSOR
-               pCurs->bits->argb &&
+               cursor->bits->argb &&
                infoPtr->UseHWCursorARGB &&
-               (*infoPtr->UseHWCursorARGB)(pScreen, pCurs)) ||
-              (pCurs->bits->argb == 0 &&
+               (*infoPtr->UseHWCursorARGB)(pScreen, cursor)) ||
+              (cursor->bits->argb == 0 &&
 #endif
-               (pCurs->bits->height <= infoPtr->MaxHeight) &&
-               (pCurs->bits->width <= infoPtr->MaxWidth) &&
-               (!infoPtr->UseHWCursor || (*infoPtr->UseHWCursor) (pScreen, pCurs)))))) {
+               (cursor->bits->height <= infoPtr->MaxHeight) &&
+               (cursor->bits->width <= infoPtr->MaxWidth) &&
+               (!infoPtr->UseHWCursor || (*infoPtr->UseHWCursor) (pScreen, cursor)))))) {
             
             if (ScreenPriv->SWCursor)   /* remove the SW cursor */
                 (*ScreenPriv->spriteFuncs->SetCursor) (pDev, pScreen,
                                                        NullCursor, x, y);
 
-            xf86SetCursor(pScreen, pCurs, x, y);
+            xf86SetCursor(pScreen, cursor, x, y);
             ScreenPriv->SWCursor = FALSE;
             ScreenPriv->isUp = TRUE;
 
diff --git a/include/cursor.h b/include/cursor.h
index 0823251..89a650f 100644
--- a/include/cursor.h
+++ b/include/cursor.h
@@ -71,6 +71,10 @@ extern _X_EXPORT CursorPtr rootCursor;
 extern _X_EXPORT int FreeCursor(pointer /*pCurs */ ,
                                 XID /*cid */ );
 
+extern _X_EXPORT CursorPtr RefCursor(CursorPtr /* cursor */);
+extern _X_EXPORT CursorPtr UnrefCursor(CursorPtr /* cursor */);
+extern _X_EXPORT int CursorRefCount(const CursorPtr /* cursor */);
+
 extern _X_EXPORT int AllocARGBCursor(unsigned char * /*psrcbits */ ,
                                      unsigned char * /*pmaskbits */ ,
                                      CARD32 * /*argb */ ,
diff --git a/render/animcur.c b/render/animcur.c
index 9cbba83..038c5b9 100644
--- a/render/animcur.c
+++ b/render/animcur.c
@@ -383,8 +383,7 @@ AnimCursorCreate(CursorPtr *cursors, CARD32 *deltas, int ncursor,
     ac->elts = (AnimCurElt *) (ac + 1);
 
     for (i = 0; i < ncursor; i++) {
-        cursors[i]->refcnt++;
-        ac->elts[i].pCursor = cursors[i];
+        ac->elts[i].pCursor = RefCursor(cursors[i]);
         ac->elts[i].delay = deltas[i];
     }
 
diff --git a/xfixes/cursor.c b/xfixes/cursor.c
index 90a026b..753d5f7 100644
--- a/xfixes/cursor.c
+++ b/xfixes/cursor.c
@@ -613,12 +613,12 @@ ReplaceCursorLookup(pointer value, XID id, pointer closure)
     }
     if (pCursor && pCursor != rcl->pNew) {
         if ((*rcl->testCursor) (pCursor, rcl->closure)) {
-            rcl->pNew->refcnt++;
+            CursorPtr curs = RefCursor(rcl->pNew);
             /* either redirect reference or update resource database */
             if (pCursorRef)
-                *pCursorRef = rcl->pNew;
+                *pCursorRef = curs;
             else
-                ChangeResourceValue(id, RT_CURSOR, rcl->pNew);
+                ChangeResourceValue(id, RT_CURSOR, curs);
             FreeCursor(pCursor, cursor);
         }
     }
commit 35c2e263db01b2b61354298e5e85aa3cae8ac317
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Tue May 14 14:51:31 2013 +1000

    dix: call UpdateDeviceState() for emulated TouchEndEvents
    
    ProcessTouchEvents() calls UDS for all touch events, but if the event type
    was switched to TouchUpdate(pending end) UDS is a noop.
    
    Daniel Drake found this can cause stuck buttons if a touch grab is
    activated, rejected and the touch event is passed to a regular listener.
    This sequence causes the TouchEnd to be changed to TouchUpdate(pending end).
    
    The actual TouchEnd event is later generated by the server once it is passed
    to the next listener. UDS is never called for this event, thus the button
    remains logically down.
    
    A previous patch suggested for UDS to handle TouchUpdate events [1], however
    this would release the button when the first TouchEvent is processed, not
    when the last grab has been released (as is the case for sync pointer
    grabs). A client may thus have the grab on the device, receive a ButtonPress
    but see the button logically up in an XQueryPointer request.
    
    This patch adds a call to UDS to TouchEmitTouchEnd(). The device state must
    be updated once a TouchEnd event was sent to the last grabbing listener and
    the number of grabs on the touchpoint is 0.
    
    [1] http://patchwork.freedesktop.org/patch/13464/
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/touch.c b/dix/touch.c
index 110b1cc..a4b6d7e 100644
--- a/dix/touch.c
+++ b/dix/touch.c
@@ -1122,6 +1122,8 @@ TouchEmitTouchEnd(DeviceIntPtr dev, TouchPointInfoPtr ti, int flags, XID resourc
     TouchDeliverDeviceClassesChangedEvent(ti, GetTimeInMillis(), resource);
     GetDixTouchEnd(&event, dev, ti, flags);
     DeliverTouchEvents(dev, ti, &event, resource);
+    if (ti->num_grabs == 0)
+        UpdateDeviceState(dev, &event.device_event);
 }
 
 void
commit 8b9dc2628115dcb3f3601ad19b1ae157df21b9ee
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Tue May 14 07:46:25 2013 +1000

    dix: devices must have valuators before touch is initialized
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/devices.c b/dix/devices.c
index c514d77..c514cfe 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -1647,6 +1647,7 @@ InitTouchClassDeviceStruct(DeviceIntPtr device, unsigned int max_touches,
 
     BUG_RETURN_VAL(device == NULL, FALSE);
     BUG_RETURN_VAL(device->touch != NULL, FALSE);
+    BUG_RETURN_VAL(device->valuator == NULL, FALSE);
 
     /* Check the mode is valid, and at least X and Y axes. */
     BUG_RETURN_VAL(mode != XIDirectTouch && mode != XIDependentTouch, FALSE);
commit fd5ea0237db6d725a48f76b706135df9d3246b82
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon May 13 15:22:12 2013 +1000

    Xi: fix warning - remove unused 'rc'
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index a99821f..2bbc6f0 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1036,7 +1036,6 @@ DeliverOneTouchEvent(ClientPtr client, DeviceIntPtr dev, TouchPointInfoPtr ti,
 static void
 ActivateEarlyAccept(DeviceIntPtr dev, TouchPointInfoPtr ti)
 {
-    int rc;
     ClientPtr client;
     XID error;
     GrabPtr grab = ti->listeners[0].grab;
commit 481702101b86fff003430e952dc65fb41eb56400
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri May 3 15:07:58 2013 +1000

    dix: fix cursor refcounting
    
    The cursor is referenced during CopyGrab(), thus doesn't need to be handled
    manually anymore. It does need to be refcounted for temp grabs though.
    
    The oldGrab handling in ProcGrabPointer is a leftover from the cursor in the
    grab being refcounted, but the grab itself being a static struct in the
    DeviceIntRec. Now that all grabs are copied, this lead to a double-free of
    the cursor (Reproduced in Thunderbird, dragging an email twice (or more
    often) causes a crash).
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/events.c b/dix/events.c
index 7464db5..8124ca9 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -1491,9 +1491,6 @@ ActivatePointerGrab(DeviceIntPtr mouse, GrabPtr grab,
         grabinfo->grabTime = syncEvents.time;
     else
         grabinfo->grabTime = time;
-    if (grab->cursor)
-        grab->cursor->refcnt++;
-    BUG_WARN(grabinfo->grab != NULL);
     grabinfo->grab = AllocGrab(grab);
     grabinfo->fromPassiveGrab = isPassive;
     grabinfo->implicitGrab = autoGrab & ImplicitGrabMask;
@@ -1552,8 +1549,6 @@ DeactivatePointerGrab(DeviceIntPtr mouse)
     if (grab->confineTo)
         ConfineCursorToWindow(mouse, GetCurrentRootWindow(mouse), FALSE, FALSE);
     PostNewCursor(mouse);
-    if (grab->cursor)
-        FreeCursor(grab->cursor, (Cursor) 0);
 
     if (!wasImplicit && grab->grabtype == XI2)
         ReattachToOldMaster(mouse);
@@ -4860,7 +4855,6 @@ ProcGrabPointer(ClientPtr client)
     GrabPtr grab;
     GrabMask mask;
     WindowPtr confineTo;
-    CursorPtr oldCursor;
     BYTE status;
 
     REQUEST(xGrabPointerReq);
@@ -4883,15 +4877,10 @@ ProcGrabPointer(ClientPtr client)
             return rc;
     }
 
-    oldCursor = NullCursor;
     grab = device->deviceGrab.grab;
 
-    if (grab) {
-        if (grab->confineTo && !confineTo)
-            ConfineCursorToWindow(device, GetCurrentRootWindow(device), FALSE,
-                                  FALSE);
-        oldCursor = grab->cursor;
-    }
+    if (grab && grab->confineTo && !confineTo)
+        ConfineCursorToWindow(device, GetCurrentRootWindow(device), FALSE, FALSE);
 
     mask.core = stuff->eventMask;
 
@@ -4901,9 +4890,6 @@ ProcGrabPointer(ClientPtr client)
     if (rc != Success)
         return rc;
 
-    if (oldCursor && status == GrabSuccess)
-        FreeCursor(oldCursor, (Cursor) 0);
-
     rep = (xGrabPointerReply) {
         .type = X_Reply,
         .status = status,
@@ -5107,6 +5093,8 @@ GrabDevice(ClientPtr client, DeviceIntPtr dev,
             xi2mask_merge(tempGrab->xi2mask, mask->xi2mask);
         tempGrab->device = dev;
         tempGrab->cursor = cursor;
+        if (cursor)
+            tempGrab->cursor->refcnt++;
         tempGrab->confineTo = confineTo;
         tempGrab->grabtype = grabtype;
         (*grabInfo->ActivateGrab) (dev, tempGrab, time, FALSE);
commit 49521edaf8930b335afac2185209e26e7000820b
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed May 15 08:51:51 2013 +1000

    ephyr: add -resizeable to the man page
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>

diff --git a/hw/kdrive/ephyr/man/Xephyr.man b/hw/kdrive/ephyr/man/Xephyr.man
index 792511b..f14f6c8 100644
--- a/hw/kdrive/ephyr/man/Xephyr.man
+++ b/hw/kdrive/ephyr/man/Xephyr.man
@@ -59,6 +59,10 @@ set 'cursor acceleration':
 The host's cursor is reused. This is only really there to aid
 debugging by avoiding server paints for the cursor. Performance
 improvement is negligible.
+.TP 8
+.B -resizeable
+Allow the Xephyr window to be resized, even if not embedded into a parent
+window. By default, the Xephyr window has a fixed size.
 .SH "SIGNALS"
 Send a SIGUSR1 to the server (e.g. pkill -USR1 Xephyr) to
 toggle the debugging mode.
commit 7a4bbfd9f2ce7aad23148ba01bb3f1071da606a3
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed May 15 08:46:38 2013 +1000

    ephyr: fix typo in man page
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>

diff --git a/hw/kdrive/ephyr/man/Xephyr.man b/hw/kdrive/ephyr/man/Xephyr.man
index ca88ab2..792511b 100644
--- a/hw/kdrive/ephyr/man/Xephyr.man
+++ b/hw/kdrive/ephyr/man/Xephyr.man
@@ -46,7 +46,7 @@ and the following additional options:
 sets the screen size.
 .TP 8
 .BI -parent " id"
-uses exiting window
+uses existing window
 .I id .
 If a
 .BI -screen
commit 7e97166c4fc38076b6224e4dbdd632b43444149f
Author: Geert Uytterhoeven <geert at linux-m68k.org>
Date:   Tue May 14 13:04:53 2013 +0200

    Shadow: Switch the Amiga/Atari bitplane code to the canonical X.Org license
    
    Also add my name to the list of authors in COPYING
    
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Signed-off-by: Geert Uytterhoeven <geert at linux-m68k.org>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/COPYING b/COPYING
index 7aa0df0..cc52a32 100644
--- a/COPYING
+++ b/COPYING
@@ -20,6 +20,7 @@ Copyright © 1999 Keith Packard
 Copyright © 2007-2009 Red Hat, Inc.
 Copyright © 2005-2008 Daniel Stone
 Copyright © 2006-2009 Simon Thum
+Copyright © 2003-2008, 2013 Geert Uytterhoeven
 Copyright © 2006 Luc Verhaegen
 
 Permission is hereby granted, free of charge, to any person obtaining a
diff --git a/miext/shadow/c2p_core.h b/miext/shadow/c2p_core.h
index a48e223..5b9ea06 100644
--- a/miext/shadow/c2p_core.h
+++ b/miext/shadow/c2p_core.h
@@ -1,29 +1,30 @@
 /*
  *  Fast C2P (Chunky-to-Planar) Conversion
  *
- *  Copyright (C) 2003-2008 Geert Uytterhoeven
- *
  *  NOTES:
  *    - This code was inspired by Scout's C2P tutorial
  *    - It assumes to run on a big endian system
  *
- *  Permission to use, copy, modify, distribute, and sell this software and its
- *  documentation for any purpose is hereby granted without fee, provided that
- *  the above copyright notice appear in all copies and that both that
- *  copyright notice and this permission notice appear in supporting
- *  documentation, and that the name of Geert Uytterhoeven not be used in
- *  advertising or publicity pertaining to distribution of the software without
- *  specific, written prior permission.  Geert Uytterhoeven makes no
- *  representations about the suitability of this software for any purpose.  It
- *  is provided "as is" without express or implied warranty.
+ *  Copyright © 2003-2008 Geert Uytterhoeven
+ *
+ *  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 (including the next
+ *  paragraph) shall be included in all copies or substantial portions of the
+ *  Software.
  *
- *  GEERT UYTTERHOEVEN DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
- *  INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
- *  EVENT SHALL GEERT UYTTERHOEVEN BE LIABLE FOR ANY SPECIAL, INDIRECT OR
- *  CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
- *  DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
- *  TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- *  PERFORMANCE OF THIS 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.
  */
 
 
diff --git a/miext/shadow/shafb4.c b/miext/shadow/shafb4.c
index 0724932..d88ae1c 100644
--- a/miext/shadow/shafb4.c
+++ b/miext/shadow/shafb4.c
@@ -1,26 +1,26 @@
 /*
+ *  Copyright © 2013 Geert Uytterhoeven
  *
- * Copyright © 2013 Geert Uytterhoeven
+ *  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:
  *
- * Permission to use, copy, modify, distribute, and sell this software and its
- * documentation for any purpose is hereby granted without fee, provided that
- * the above copyright notice appear in all copies and that both that
- * copyright notice and this permission notice appear in supporting
- * documentation, and that the name of Geert Uytterhoeven not be used in
- * advertising or publicity pertaining to distribution of the software without
- * specific, written prior permission.  Geert Uytterhoeven makes no
- * representations about the suitability of this software for any purpose.  It
- * is provided "as is" without express or implied warranty.
+ *  The above copyright notice and this permission notice (including the next
+ *  paragraph) shall be included in all copies or substantial portions of the
+ *  Software.
  *
- * GEERT UYTTERHOEVEN DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
- * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
- * EVENT SHALL GEERT UYTTERHOEVEN BE LIABLE FOR ANY SPECIAL, INDIRECT OR
- * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
- * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
- * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- * PERFORMANCE OF THIS 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.
  *
- * Based on shpacked.c, which is Copyright © 2000 Keith Packard
+ *  Based on shpacked.c, which is Copyright © 2000 Keith Packard
  */
 
 #ifdef HAVE_DIX_CONFIG_H
diff --git a/miext/shadow/shafb8.c b/miext/shadow/shafb8.c
index 0835e16..8d84bfa 100644
--- a/miext/shadow/shafb8.c
+++ b/miext/shadow/shafb8.c
@@ -1,26 +1,26 @@
 /*
+ *  Copyright © 2013 Geert Uytterhoeven
  *
- * Copyright © 2013 Geert Uytterhoeven
+ *  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:
  *
- * Permission to use, copy, modify, distribute, and sell this software and its
- * documentation for any purpose is hereby granted without fee, provided that
- * the above copyright notice appear in all copies and that both that
- * copyright notice and this permission notice appear in supporting
- * documentation, and that the name of Geert Uytterhoeven not be used in
- * advertising or publicity pertaining to distribution of the software without
- * specific, written prior permission.  Geert Uytterhoeven makes no
- * representations about the suitability of this software for any purpose.  It
- * is provided "as is" without express or implied warranty.
+ *  The above copyright notice and this permission notice (including the next
+ *  paragraph) shall be included in all copies or substantial portions of the
+ *  Software.
  *
- * GEERT UYTTERHOEVEN DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
- * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
- * EVENT SHALL GEERT UYTTERHOEVEN BE LIABLE FOR ANY SPECIAL, INDIRECT OR
- * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
- * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
- * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- * PERFORMANCE OF THIS 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.
  *
- * Based on shpacked.c, which is Copyright © 2000 Keith Packard
+ *  Based on shpacked.c, which is Copyright © 2000 Keith Packard
  */
 
 #ifdef HAVE_DIX_CONFIG_H
diff --git a/miext/shadow/shiplan2p4.c b/miext/shadow/shiplan2p4.c
index 79ada99..0e46bae 100644
--- a/miext/shadow/shiplan2p4.c
+++ b/miext/shadow/shiplan2p4.c
@@ -1,26 +1,26 @@
 /*
+ *  Copyright © 2013 Geert Uytterhoeven
  *
- * Copyright © 2013 Geert Uytterhoeven
+ *  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:
  *
- * Permission to use, copy, modify, distribute, and sell this software and its
- * documentation for any purpose is hereby granted without fee, provided that
- * the above copyright notice appear in all copies and that both that
- * copyright notice and this permission notice appear in supporting
- * documentation, and that the name of Geert Uytterhoeven not be used in
- * advertising or publicity pertaining to distribution of the software without
- * specific, written prior permission.  Geert Uytterhoeven makes no
- * representations about the suitability of this software for any purpose.  It
- * is provided "as is" without express or implied warranty.
+ *  The above copyright notice and this permission notice (including the next
+ *  paragraph) shall be included in all copies or substantial portions of the
+ *  Software.
  *
- * GEERT UYTTERHOEVEN DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
- * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
- * EVENT SHALL GEERT UYTTERHOEVEN BE LIABLE FOR ANY SPECIAL, INDIRECT OR
- * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
- * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
- * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- * PERFORMANCE OF THIS 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.
  *
- * Based on shpacked.c, which is Copyright © 2000 Keith Packard
+ *  Based on shpacked.c, which is Copyright © 2000 Keith Packard
  */
 
 #ifdef HAVE_DIX_CONFIG_H
diff --git a/miext/shadow/shiplan2p8.c b/miext/shadow/shiplan2p8.c
index 55762f6..17d6a13 100644
--- a/miext/shadow/shiplan2p8.c
+++ b/miext/shadow/shiplan2p8.c
@@ -1,26 +1,26 @@
 /*
+ *  Copyright © 2013 Geert Uytterhoeven
  *
- * Copyright © 2013 Geert Uytterhoeven
+ *  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:
  *
- * Permission to use, copy, modify, distribute, and sell this software and its
- * documentation for any purpose is hereby granted without fee, provided that
- * the above copyright notice appear in all copies and that both that
- * copyright notice and this permission notice appear in supporting
- * documentation, and that the name of Geert Uytterhoeven not be used in
- * advertising or publicity pertaining to distribution of the software without
- * specific, written prior permission.  Geert Uytterhoeven makes no
- * representations about the suitability of this software for any purpose.  It
- * is provided "as is" without express or implied warranty.
+ *  The above copyright notice and this permission notice (including the next
+ *  paragraph) shall be included in all copies or substantial portions of the
+ *  Software.
  *
- * GEERT UYTTERHOEVEN DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
- * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
- * EVENT SHALL GEERT UYTTERHOEVEN BE LIABLE FOR ANY SPECIAL, INDIRECT OR
- * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
- * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
- * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- * PERFORMANCE OF THIS 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.
  *
- * Based on shpacked.c, which is Copyright © 2000 Keith Packard
+ *  Based on shpacked.c, which is Copyright © 2000 Keith Packard
  */
 
 #ifdef HAVE_DIX_CONFIG_H
commit 3093f78d17e48a506aab170a9089cd10e21af299
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri May 3 15:02:05 2013 +1000

    dix: free the old grab when activating a new grab
    
    A client may call XIGrabDevice twice, overwriting the existing grab. Thus,
    make sure we free the old copy after we copied it. Free it last, to make
    sure our refcounts don't run to 0 and inadvertantly free something on the
    way.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/events.c b/dix/events.c
index 76bc555..7464db5 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -1468,6 +1468,7 @@ ActivatePointerGrab(DeviceIntPtr mouse, GrabPtr grab,
                     TimeStamp time, Bool autoGrab)
 {
     GrabInfoPtr grabinfo = &mouse->deviceGrab;
+    GrabPtr oldgrab = grabinfo->grab;
     WindowPtr oldWin = (grabinfo->grab) ?
         grabinfo->grab->window : mouse->spriteInfo->sprite->win;
     Bool isPassive = autoGrab & ~ImplicitGrabMask;
@@ -1500,6 +1501,8 @@ ActivatePointerGrab(DeviceIntPtr mouse, GrabPtr grab,
     UpdateTouchesForGrab(mouse);
     CheckGrabForSyncs(mouse, (Bool) grab->pointerMode,
                       (Bool) grab->keyboardMode);
+    if (oldgrab)
+        FreeGrab(oldgrab);
 }
 
 /**
@@ -1570,6 +1573,7 @@ ActivateKeyboardGrab(DeviceIntPtr keybd, GrabPtr grab, TimeStamp time,
                      Bool passive)
 {
     GrabInfoPtr grabinfo = &keybd->deviceGrab;
+    GrabPtr oldgrab = grabinfo->grab;
     WindowPtr oldWin;
 
     /* slave devices need to float for the duration of the grab. */
@@ -1595,12 +1599,13 @@ ActivateKeyboardGrab(DeviceIntPtr keybd, GrabPtr grab, TimeStamp time,
         grabinfo->grabTime = syncEvents.time;
     else
         grabinfo->grabTime = time;
-    BUG_WARN(grabinfo->grab != NULL);
     grabinfo->grab = AllocGrab(grab);
     grabinfo->fromPassiveGrab = passive;
     grabinfo->implicitGrab = passive & ImplicitGrabMask;
     CheckGrabForSyncs(keybd, (Bool) grab->keyboardMode,
                       (Bool) grab->pointerMode);
+    if (oldgrab)
+        FreeGrab(oldgrab);
 }
 
 /**
commit 2566bdd8bc996cccde77b846819808c6239a89d2
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Apr 24 14:46:06 2013 +1000

    Xi: check for HAS_ACCEPTED only for grab listeners
    
    If we have one listener left but it's not a grab, it cannot be in
    LISTENER_HAS_ACCEPTED state.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index ae2e5ae..a99821f 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1919,7 +1919,7 @@ DeliverTouchEndEvent(DeviceIntPtr dev, TouchPointInfoPtr ti, InternalEvent *ev,
             rc = DeliverOneTouchEvent(client, dev, ti, grab, win, ev);
 
         if ((ti->num_listeners > 1 ||
-             listener->state != LISTENER_HAS_ACCEPTED) &&
+             (ti->num_grabs > 0 && listener->state != LISTENER_HAS_ACCEPTED)) &&
             (ev->device_event.flags & (TOUCH_ACCEPT | TOUCH_REJECT)) == 0) {
             ev->any.type = ET_TouchUpdate;
             ev->device_event.flags |= TOUCH_PENDING_END;
commit 5b00fc52270e9cfdfe7ac1838a21defe50fc3d31
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Apr 24 14:40:31 2013 +1000

    Move TouchListenerGone call to CloseDownClient
    
    TouchListenerGone cleans up if a client disappears. Having this in
    FreeGrab() triggers cyclic removal of grabs, emitting wrong events. In
    particular, it would clean up a passive grab record while that grab is
    active.
    
    Move it to CloseDownClient() instead, cleaning up before we go.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/dispatch.c b/dix/dispatch.c
index 1363f22..51d0de2 100644
--- a/dix/dispatch.c
+++ b/dix/dispatch.c
@@ -3399,6 +3399,7 @@ CloseDownClient(ClientPtr client)
             clientinfo.setup = (xConnSetup *) NULL;
             CallCallbacks((&ClientStateCallback), (pointer) &clientinfo);
         }
+        TouchListenerGone(client->clientAsMask);
         FreeClientResources(client);
         /* Disable client ID tracking. This must be done after
          * ClientStateCallback. */
diff --git a/dix/grabs.c b/dix/grabs.c
index f46a6b2..b254ddc 100644
--- a/dix/grabs.c
+++ b/dix/grabs.c
@@ -257,9 +257,6 @@ FreeGrab(GrabPtr pGrab)
 {
     BUG_RETURN(!pGrab);
 
-    if (pGrab->grabtype == XI2 && pGrab->type == XI_TouchBegin)
-        TouchListenerGone(pGrab->resource);
-
     free(pGrab->modifiersDetail.pMask);
     free(pGrab->detail.pMask);
 
diff --git a/dix/touch.c b/dix/touch.c
index 0099914..110b1cc 100644
--- a/dix/touch.c
+++ b/dix/touch.c
@@ -989,11 +989,11 @@ TouchListenerGone(XID resource)
                 continue;
 
             for (j = 0; j < ti->num_listeners; j++) {
-                if (ti->listeners[j].listener != resource)
+                if (CLIENT_BITS(ti->listeners[j].listener) != resource)
                     continue;
 
                 nev = GetTouchOwnershipEvents(events, dev, ti, XIRejectTouch,
-                                              resource, 0);
+                                              ti->listeners[j].listener, 0);
                 for (k = 0; k < nev; k++)
                     mieqProcessDeviceEvent(dev, events + k, NULL);
 
commit 34c9b39d9937c2e19c2dffc9748605f90d40f965
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Apr 24 12:53:52 2013 +1000

    dix: remove all listeners when freeing a touch
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/touch.c b/dix/touch.c
index fb218d4..0099914 100644
--- a/dix/touch.c
+++ b/dix/touch.c
@@ -263,6 +263,7 @@ void
 TouchFreeTouchPoint(DeviceIntPtr device, int index)
 {
     TouchPointInfoPtr ti;
+    int i;
 
     if (!device->touch || index >= device->touch->num_touches)
         return;
@@ -271,6 +272,9 @@ TouchFreeTouchPoint(DeviceIntPtr device, int index)
     if (ti->active)
         TouchEndTouch(device, ti);
 
+    for (i = 0; i < ti->num_listeners; i++)
+        TouchRemoveListener(ti, ti->listeners[0].listener);
+
     valuator_mask_free(&ti->valuators);
     free(ti->sprite.spriteTrace);
     ti->sprite.spriteTrace = NULL;
commit 395124bd2782823de37e5c5b2f15dba49cff05f6
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Apr 17 20:15:35 2013 +1000

    dix: always copy grabs, don't reference them
    
    Introduced in xorg-server-1.13.99.901-2-g9ad0fdb. Storing the grab pointer
    in the listener turns out to be a bad idea. If the grab is not an active
    grab or an implicit grab, the pointer stored is the one to the grab attached
    on the window. This grab may be removed if the client calls UngrabButton or
    similar while the touch is still active, leaving a dangling pointer.
    
    To avoid this, copy the grab wherever we need to reference it later. This
    is also what we do for pointer/keyboard grabs, where we copy the grab as
    soon as it becomes active.
    
    Reported-by: Maarten Lankhorst <maarten.lankhorst at canonical.com>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 2feddd3..ae2e5ae 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1429,8 +1429,11 @@ DeliverTouchEmulatedEvent(DeviceIntPtr dev, TouchPointInfoPtr ti,
          */
         if (!devgrab && dev->deviceGrab.grab && dev->deviceGrab.implicitGrab) {
             TouchListener *l;
+            GrabPtr g;
 
             devgrab = dev->deviceGrab.grab;
+            g = AllocGrab(devgrab);
+            BUG_WARN(!g);
 
             *dev->deviceGrab.sync.event = ev->device_event;
 
@@ -1439,8 +1442,8 @@ DeliverTouchEmulatedEvent(DeviceIntPtr dev, TouchPointInfoPtr ti,
              * event selection. Thus, we update the last listener in the array.
              */
             l = &ti->listeners[ti->num_listeners - 1];
-            l->listener = devgrab->resource;
-            l->grab = devgrab;
+            l->listener = g->resource;
+            l->grab = g;
             //l->resource_type = RT_NONE;
 
             if (devgrab->grabtype != XI2 || devgrab->type != XI_TouchBegin)
diff --git a/dix/events.c b/dix/events.c
index cd2d939..76bc555 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -1442,7 +1442,8 @@ UpdateTouchesForGrab(DeviceIntPtr mouse)
                 listener->type = LISTENER_POINTER_GRAB;
             else
                 listener->type = LISTENER_GRAB;
-            listener->grab = grab;
+            FreeGrab(listener->grab);
+            listener->grab = AllocGrab(grab);
         }
     }
 }
diff --git a/dix/touch.c b/dix/touch.c
index 01a554e..fb218d4 100644
--- a/dix/touch.c
+++ b/dix/touch.c
@@ -365,6 +365,8 @@ TouchBeginTouch(DeviceIntPtr dev, int sourceid, uint32_t touchid,
 void
 TouchEndTouch(DeviceIntPtr dev, TouchPointInfoPtr ti)
 {
+    int i;
+
     if (ti->emulate_pointer) {
         GrabPtr grab;
 
@@ -376,6 +378,9 @@ TouchEndTouch(DeviceIntPtr dev, TouchPointInfoPtr ti)
         }
     }
 
+    for (i = 0; i < ti->num_listeners; i++)
+        TouchRemoveListener(ti, ti->listeners[0].listener);
+
     ti->active = FALSE;
     ti->pending_finish = FALSE;
     ti->sprite.spriteTraceGood = 0;
@@ -692,15 +697,23 @@ void
 TouchAddListener(TouchPointInfoPtr ti, XID resource, int resource_type,
                  enum InputLevel level, enum TouchListenerType type,
                  enum TouchListenerState state, WindowPtr window,
-                 GrabPtr grab)
+                 const GrabPtr grab)
 {
+    GrabPtr g = NULL;
+
+    /* We need a copy of the grab, not the grab itself since that may be
+     * deleted by a UngrabButton request and leaves us with a dangling
+     * pointer */
+    if (grab)
+        g = AllocGrab(grab);
+
     ti->listeners[ti->num_listeners].listener = resource;
     ti->listeners[ti->num_listeners].resource_type = resource_type;
     ti->listeners[ti->num_listeners].level = level;
     ti->listeners[ti->num_listeners].state = state;
     ti->listeners[ti->num_listeners].type = type;
     ti->listeners[ti->num_listeners].window = window;
-    ti->listeners[ti->num_listeners].grab = grab;
+    ti->listeners[ti->num_listeners].grab = g;
     if (grab)
         ti->num_grabs++;
     ti->num_listeners++;
@@ -725,6 +738,7 @@ TouchRemoveListener(TouchPointInfoPtr ti, XID resource)
             continue;
 
         if (listener->grab) {
+            FreeGrab(listener->grab);
             listener->grab = NULL;
             ti->num_grabs--;
         }
@@ -734,6 +748,7 @@ TouchRemoveListener(TouchPointInfoPtr ti, XID resource)
         ti->num_listeners--;
         ti->listeners[ti->num_listeners].listener = 0;
         ti->listeners[ti->num_listeners].state = LISTENER_AWAITING_BEGIN;
+
         return TRUE;
     }
     return FALSE;
commit 925e35122ebad877395bcf13676e9dbeb254bdfa
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Tue Apr 23 15:52:18 2013 +1000

    dix: AllocGrab can copy if an argument is passed in
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 2495ade..2feddd3 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -2844,7 +2844,7 @@ CheckDeviceGrabAndHintWindow(WindowPtr pWin, int type,
              (deliveryMask & DeviceButtonGrabMask)) {
         GrabPtr tempGrab;
 
-        tempGrab = AllocGrab();
+        tempGrab = AllocGrab(NULL);
         if (!tempGrab)
             return;
 
diff --git a/Xi/ungrdevb.c b/Xi/ungrdevb.c
index c4632fa..b02510e 100644
--- a/Xi/ungrdevb.c
+++ b/Xi/ungrdevb.c
@@ -127,7 +127,7 @@ ProcXUngrabDeviceButton(ClientPtr client)
         (stuff->modifiers & ~AllModifiersMask))
         return BadValue;
 
-    temporaryGrab = AllocGrab();
+    temporaryGrab = AllocGrab(NULL);
     if (!temporaryGrab)
         return BadAlloc;
 
diff --git a/Xi/ungrdevk.c b/Xi/ungrdevk.c
index 3273878..f981171 100644
--- a/Xi/ungrdevk.c
+++ b/Xi/ungrdevk.c
@@ -134,7 +134,7 @@ ProcXUngrabDeviceKey(ClientPtr client)
         (stuff->modifiers & ~AllModifiersMask))
         return BadValue;
 
-    temporaryGrab = AllocGrab();
+    temporaryGrab = AllocGrab(NULL);
     if (!temporaryGrab)
         return BadAlloc;
 
diff --git a/Xi/xipassivegrab.c b/Xi/xipassivegrab.c
index 62a3a46..eccec0a 100644
--- a/Xi/xipassivegrab.c
+++ b/Xi/xipassivegrab.c
@@ -307,7 +307,7 @@ ProcXIPassiveUngrabDevice(ClientPtr client)
 
     mod_dev = (IsFloating(dev)) ? dev : GetMaster(dev, MASTER_KEYBOARD);
 
-    tempGrab = AllocGrab();
+    tempGrab = AllocGrab(NULL);
     if (!tempGrab)
         return BadAlloc;
 
diff --git a/dix/events.c b/dix/events.c
index dc50311..cd2d939 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -1492,8 +1492,7 @@ ActivatePointerGrab(DeviceIntPtr mouse, GrabPtr grab,
     if (grab->cursor)
         grab->cursor->refcnt++;
     BUG_WARN(grabinfo->grab != NULL);
-    grabinfo->grab = AllocGrab();
-    CopyGrab(grabinfo->grab, grab);
+    grabinfo->grab = AllocGrab(grab);
     grabinfo->fromPassiveGrab = isPassive;
     grabinfo->implicitGrab = autoGrab & ImplicitGrabMask;
     PostNewCursor(mouse);
@@ -1596,8 +1595,7 @@ ActivateKeyboardGrab(DeviceIntPtr keybd, GrabPtr grab, TimeStamp time,
     else
         grabinfo->grabTime = time;
     BUG_WARN(grabinfo->grab != NULL);
-    grabinfo->grab = AllocGrab();
-    CopyGrab(grabinfo->grab, grab);
+    grabinfo->grab = AllocGrab(grab);
     grabinfo->fromPassiveGrab = passive;
     grabinfo->implicitGrab = passive & ImplicitGrabMask;
     CheckGrabForSyncs(keybd, (Bool) grab->keyboardMode,
@@ -1991,7 +1989,7 @@ ActivateImplicitGrab(DeviceIntPtr dev, ClientPtr client, WindowPtr win,
     else
         return FALSE;
 
-    tempGrab = AllocGrab();
+    tempGrab = AllocGrab(NULL);
     if (!tempGrab)
         return FALSE;
     tempGrab->next = NULL;
@@ -3898,7 +3896,7 @@ CheckPassiveGrabsOnWindow(WindowPtr pWin,
     if (!grab)
         return NULL;
 
-    tempGrab = AllocGrab();
+    tempGrab = AllocGrab(NULL);
 
     /* Fill out the grab details, but leave the type for later before
      * comparing */
@@ -5087,7 +5085,7 @@ GrabDevice(ClientPtr client, DeviceIntPtr dev,
     else {
         GrabPtr tempGrab;
 
-        tempGrab = AllocGrab();
+        tempGrab = AllocGrab(NULL);
 
         tempGrab->next = NULL;
         tempGrab->window = pWin;
@@ -5443,7 +5441,7 @@ ProcUngrabKey(ClientPtr client)
         client->errorValue = stuff->modifiers;
         return BadValue;
     }
-    tempGrab = AllocGrab();
+    tempGrab = AllocGrab(NULL);
     if (!tempGrab)
         return BadAlloc;
     tempGrab->resource = client->clientAsMask;
@@ -5637,7 +5635,7 @@ ProcUngrabButton(ClientPtr client)
 
     ptr = PickPointer(client);
 
-    tempGrab = AllocGrab();
+    tempGrab = AllocGrab(NULL);
     if (!tempGrab)
         return BadAlloc;
     tempGrab->resource = client->clientAsMask;
diff --git a/dix/grabs.c b/dix/grabs.c
index 0a2111d..f46a6b2 100644
--- a/dix/grabs.c
+++ b/dix/grabs.c
@@ -189,7 +189,7 @@ UngrabAllDevices(Bool kill_client)
 }
 
 GrabPtr
-AllocGrab(void)
+AllocGrab(const GrabPtr src)
 {
     GrabPtr grab = calloc(1, sizeof(GrabRec));
 
@@ -201,6 +201,12 @@ AllocGrab(void)
         }
     }
 
+    if (src && !CopyGrab(grab, src)) {
+        free(grab->xi2mask);
+        free(grab);
+        grab = NULL;
+    }
+
     return grab;
 }
 
@@ -213,7 +219,7 @@ CreateGrab(int client, DeviceIntPtr device, DeviceIntPtr modDevice,
 {
     GrabPtr grab;
 
-    grab = AllocGrab();
+    grab = AllocGrab(NULL);
     if (!grab)
         return (GrabPtr) NULL;
     grab->resource = FakeClientID(client);
diff --git a/include/dixgrabs.h b/include/dixgrabs.h
index eccec77..ca3c95b 100644
--- a/include/dixgrabs.h
+++ b/include/dixgrabs.h
@@ -31,7 +31,7 @@ struct _GrabParameters;
 extern void PrintDeviceGrabInfo(DeviceIntPtr dev);
 extern void UngrabAllDevices(Bool kill_client);
 
-extern GrabPtr AllocGrab(void);
+extern GrabPtr AllocGrab(const GrabPtr src);
 extern void FreeGrab(GrabPtr grab);
 extern Bool CopyGrab(GrabPtr dst, const GrabPtr src);
 
commit 4980bcef9973ba1f90f53028f061669ee5d2661b
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Tue Apr 23 15:46:04 2013 +1000

    dix: freeing a null grab is a bug, complain if doing so
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/grabs.c b/dix/grabs.c
index 3b02352..0a2111d 100644
--- a/dix/grabs.c
+++ b/dix/grabs.c
@@ -249,6 +249,8 @@ CreateGrab(int client, DeviceIntPtr device, DeviceIntPtr modDevice,
 void
 FreeGrab(GrabPtr pGrab)
 {
+    BUG_RETURN(!pGrab);
+
     if (pGrab->grabtype == XI2 && pGrab->type == XI_TouchBegin)
         TouchListenerGone(pGrab->resource);
 
commit ccfa0f2d5de557546815a5e4f59552e2af46b578
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Tue Apr 23 15:39:32 2013 +1000

    dix: use a temporary variable for listeners[0]
    
    no functional changes
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/events.c b/dix/events.c
index e2e94a5..dc50311 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -1427,21 +1427,22 @@ UpdateTouchesForGrab(DeviceIntPtr mouse)
 
     for (i = 0; i < mouse->touch->num_touches; i++) {
         TouchPointInfoPtr ti = mouse->touch->touches + i;
+        TouchListener *listener = &ti->listeners[0];
         GrabPtr grab = mouse->deviceGrab.grab;
 
         if (ti->active &&
-            CLIENT_BITS(ti->listeners[0].listener) == grab->resource) {
-            ti->listeners[0].listener = grab->resource;
-            ti->listeners[0].level = grab->grabtype;
-            ti->listeners[0].state = LISTENER_IS_OWNER;
-            ti->listeners[0].window = grab->window;
+            CLIENT_BITS(listener->listener) == grab->resource) {
+            listener->listener = grab->resource;
+            listener->level = grab->grabtype;
+            listener->state = LISTENER_IS_OWNER;
+            listener->window = grab->window;
 
             if (grab->grabtype == CORE || grab->grabtype == XI ||
                 !xi2mask_isset(grab->xi2mask, mouse, XI_TouchBegin))
-                ti->listeners[0].type = LISTENER_POINTER_GRAB;
+                listener->type = LISTENER_POINTER_GRAB;
             else
-                ti->listeners[0].type = LISTENER_GRAB;
-            ti->listeners[0].grab = grab;
+                listener->type = LISTENER_GRAB;
+            listener->grab = grab;
         }
     }
 }
commit 5363433a5cc64e2f83859aa1c32a89e5e1ddf9e4
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Apr 18 10:32:11 2013 +1000

    dix: drop DeviceIntRec's activeGrab struct
    
    Obsolete since 4bc2761ad5ec2d0668aec639780ffb136605fbc8. This struct
    existed so copying a passive grab could be simply done by
      activeGrab = *grab
    
    and thus have a copy of the GrabPtr we'd get from various sources but still
    be able to check device->grab for NULL.
    
    Since 4bc2761 activeGrab is a pointer itself and points to the same memory
    as grabinfo->grab, leaving us with the potential of dangling pointers if
    either calls FreeGrab() and doesn't reset the other one.
    
    There is no reader of activeGrab anyway, so simply removing it is
    sufficient.
    
    Note: field is merely renamed to keep the ABI. Should be removed in the
    future.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/devices.c b/dix/devices.c
index 9b6faee..c514d77 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -281,7 +281,6 @@ AddInputDevice(ClientPtr client, DeviceProc deviceProc, Bool autoStart)
     dev->deviceGrab.grabTime = currentTime;
     dev->deviceGrab.ActivateGrab = ActivateKeyboardGrab;
     dev->deviceGrab.DeactivateGrab = DeactivateKeyboardGrab;
-    dev->deviceGrab.activeGrab = AllocGrab();
     dev->deviceGrab.sync.event = calloc(1, sizeof(DeviceEvent));
 
     XkbSetExtension(dev, ProcessKeyboardEvent);
@@ -977,7 +976,8 @@ CloseDevice(DeviceIntPtr dev)
         }
     }
 
-    FreeGrab(dev->deviceGrab.activeGrab);
+    if (dev->deviceGrab.grab)
+        FreeGrab(dev->deviceGrab.grab);
     free(dev->deviceGrab.sync.event);
     free(dev->config_info);     /* Allocated in xf86ActivateDevice. */
     free(dev->last.scroll);
diff --git a/dix/events.c b/dix/events.c
index da9bd38..e2e94a5 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -1490,8 +1490,9 @@ ActivatePointerGrab(DeviceIntPtr mouse, GrabPtr grab,
         grabinfo->grabTime = time;
     if (grab->cursor)
         grab->cursor->refcnt++;
-    CopyGrab(grabinfo->activeGrab, grab);
-    grabinfo->grab = grabinfo->activeGrab;
+    BUG_WARN(grabinfo->grab != NULL);
+    grabinfo->grab = AllocGrab();
+    CopyGrab(grabinfo->grab, grab);
     grabinfo->fromPassiveGrab = isPassive;
     grabinfo->implicitGrab = autoGrab & ImplicitGrabMask;
     PostNewCursor(mouse);
@@ -1554,6 +1555,8 @@ DeactivatePointerGrab(DeviceIntPtr mouse)
         ReattachToOldMaster(mouse);
 
     ComputeFreezes();
+
+    FreeGrab(grab);
 }
 
 /**
@@ -1591,8 +1594,9 @@ ActivateKeyboardGrab(DeviceIntPtr keybd, GrabPtr grab, TimeStamp time,
         grabinfo->grabTime = syncEvents.time;
     else
         grabinfo->grabTime = time;
-    CopyGrab(grabinfo->activeGrab, grab);
-    grabinfo->grab = grabinfo->activeGrab;
+    BUG_WARN(grabinfo->grab != NULL);
+    grabinfo->grab = AllocGrab();
+    CopyGrab(grabinfo->grab, grab);
     grabinfo->fromPassiveGrab = passive;
     grabinfo->implicitGrab = passive & ImplicitGrabMask;
     CheckGrabForSyncs(keybd, (Bool) grab->keyboardMode,
@@ -1638,6 +1642,8 @@ DeactivateKeyboardGrab(DeviceIntPtr keybd)
         ReattachToOldMaster(keybd);
 
     ComputeFreezes();
+
+    FreeGrab(grab);
 }
 
 void
diff --git a/include/inputstr.h b/include/inputstr.h
index de96fae..85be885 100644
--- a/include/inputstr.h
+++ b/include/inputstr.h
@@ -485,7 +485,7 @@ typedef struct _GrabInfoRec {
     TimeStamp grabTime;
     Bool fromPassiveGrab;       /* true if from passive grab */
     Bool implicitGrab;          /* implicit from ButtonPress */
-    GrabPtr activeGrab;
+    GrabPtr unused;             /* Kept for ABI stability, remove soon */
     GrabPtr grab;
     CARD8 activatingKey;
     void (*ActivateGrab) (DeviceIntPtr /*device */ ,
commit 7dbf61817d3bd4b1fc71710677e56c5d8cfcdb4e
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Apr 17 20:14:56 2013 +1000

    dix: use a tmp variable for the to-be-removed touch listener
    
    No functional changes.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/touch.c b/dix/touch.c
index be4a7de..01a554e 100644
--- a/dix/touch.c
+++ b/dix/touch.c
@@ -719,12 +719,13 @@ TouchRemoveListener(TouchPointInfoPtr ti, XID resource)
 
     for (i = 0; i < ti->num_listeners; i++) {
         int j;
+        TouchListener *listener = &ti->listeners[i];
 
-        if (ti->listeners[i].listener != resource)
+        if (listener->listener != resource)
             continue;
 
-        if (ti->listeners[i].grab) {
-            ti->listeners[i].grab = NULL;
+        if (listener->grab) {
+            listener->grab = NULL;
             ti->num_grabs--;
         }
 
commit a71a283934406d870bcd8dc376eb1c9ce1c8bbb4
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Apr 17 20:13:34 2013 +1000

    dix: invert a loop condition
    
    Change the single if condition in the loop body to a
        if (!foo) continue;
    and re-indent the rest.
    
    No functional changes.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/touch.c b/dix/touch.c
index 0cbc2eb..be4a7de 100644
--- a/dix/touch.c
+++ b/dix/touch.c
@@ -718,21 +718,22 @@ TouchRemoveListener(TouchPointInfoPtr ti, XID resource)
     int i;
 
     for (i = 0; i < ti->num_listeners; i++) {
-        if (ti->listeners[i].listener == resource) {
-            int j;
+        int j;
 
-            if (ti->listeners[i].grab) {
-                ti->listeners[i].grab = NULL;
-                ti->num_grabs--;
-            }
+        if (ti->listeners[i].listener != resource)
+            continue;
 
-            for (j = i; j < ti->num_listeners - 1; j++)
-                ti->listeners[j] = ti->listeners[j + 1];
-            ti->num_listeners--;
-            ti->listeners[ti->num_listeners].listener = 0;
-            ti->listeners[ti->num_listeners].state = LISTENER_AWAITING_BEGIN;
-            return TRUE;
+        if (ti->listeners[i].grab) {
+            ti->listeners[i].grab = NULL;
+            ti->num_grabs--;
         }
+
+        for (j = i; j < ti->num_listeners - 1; j++)
+            ti->listeners[j] = ti->listeners[j + 1];
+        ti->num_listeners--;
+        ti->listeners[ti->num_listeners].listener = 0;
+        ti->listeners[ti->num_listeners].state = LISTENER_AWAITING_BEGIN;
+        return TRUE;
     }
     return FALSE;
 }
commit 5174b1f98204beee79eba74c4cda5f2be0a60a8f
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Feb 28 11:02:40 2013 +1000

    dix: XAllowEvents() on a touch event means accepting it
    
    A sync grab is the owner once it gets events. If it doesn't replay the
    event it will get all events from this touch, equivalent to accepting it.
    
    If the touch has ended before XAllowEvents() is called, we also now need to
    send the TouchEnd event and clean-up since we won't see anything more from
    this touch.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/events.c b/dix/events.c
index 0512052..da9bd38 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -1742,6 +1742,16 @@ AllowSome(ClientPtr client, TimeStamp time, DeviceIntPtr thisDev, int newState)
         }
         break;
     }
+
+    /* We've unfrozen the grab. If the grab was a touch grab, we're now the
+     * owner and expected to accept/reject it. Reject == ReplayPointer which
+     * we've handled in ComputeFreezes() (during DeactivateGrab) above,
+     * anything else is accept.
+     */
+    if (newState != NOT_GRABBED /* Replay */ &&
+        IsTouchEvent((InternalEvent*)grabinfo->sync.event)) {
+        TouchAcceptAndEnd(thisDev, grabinfo->sync.event->touchid);
+    }
 }
 
 /**
diff --git a/dix/touch.c b/dix/touch.c
index f7112fc..0cbc2eb 100644
--- a/dix/touch.c
+++ b/dix/touch.c
@@ -1102,3 +1102,17 @@ TouchEmitTouchEnd(DeviceIntPtr dev, TouchPointInfoPtr ti, int flags, XID resourc
     GetDixTouchEnd(&event, dev, ti, flags);
     DeliverTouchEvents(dev, ti, &event, resource);
 }
+
+void
+TouchAcceptAndEnd(DeviceIntPtr dev, int touchid)
+{
+    TouchPointInfoPtr ti = TouchFindByClientID(dev, touchid);
+    if (!ti)
+        return;
+
+    TouchListenerAcceptReject(dev, ti, 0, XIAcceptTouch);
+    if (ti->pending_finish)
+        TouchEmitTouchEnd(dev, ti, 0, 0);
+    if (ti->num_listeners <= 1)
+        TouchEndTouch(dev, ti);
+}
diff --git a/include/input.h b/include/input.h
index ef8191b..1745e9a 100644
--- a/include/input.h
+++ b/include/input.h
@@ -591,6 +591,7 @@ extern void TouchEndPhysicallyActiveTouches(DeviceIntPtr dev);
 extern void TouchDeliverDeviceClassesChangedEvent(TouchPointInfoPtr ti,
                                                   Time time, XID resource);
 extern void TouchEmitTouchEnd(DeviceIntPtr dev, TouchPointInfoPtr ti, int flags, XID resource);
+extern void TouchAcceptAndEnd(DeviceIntPtr dev, int touchid);
 
 /* misc event helpers */
 extern Mask GetEventMask(DeviceIntPtr dev, xEvent *ev, InputClientsPtr clients);
commit e7f79c48b0faea910dc881034c00eb807fcd6210
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Mar 1 12:52:35 2013 +1000

    dix: move EmitTouchEnd to touch.c
    
    No functional changes, this just enables it to be re-used easier.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index f500669..2495ade 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1053,33 +1053,6 @@ ActivateEarlyAccept(DeviceIntPtr dev, TouchPointInfoPtr ti)
 }
 
 /**
- * Generate and deliver a TouchEnd event.
- *
- * @param dev The device to deliver the event for.
- * @param ti The touch point record to deliver the event for.
- * @param flags Internal event flags. The called does not need to provide
- *        TOUCH_CLIENT_ID and TOUCH_POINTER_EMULATED, this function will ensure
- *        they are set appropriately.
- * @param resource The client resource to deliver to, or 0 for all clients.
- */
-static void
-EmitTouchEnd(DeviceIntPtr dev, TouchPointInfoPtr ti, int flags, XID resource)
-{
-    InternalEvent event;
-
-    /* We're not processing a touch end for a frozen device */
-    if (dev->deviceGrab.sync.frozen)
-        return;
-
-    flags |= TOUCH_CLIENT_ID;
-    if (ti->emulate_pointer)
-        flags |= TOUCH_POINTER_EMULATED;
-    TouchDeliverDeviceClassesChangedEvent(ti, GetTimeInMillis(), resource);
-    GetDixTouchEnd(&event, dev, ti, flags);
-    DeliverTouchEvents(dev, ti, &event, resource);
-}
-
-/**
  * Find the oldest touch that still has a pointer emulation client.
  *
  * Pointer emulation can only be performed for the oldest touch. Otherwise, the
@@ -1150,7 +1123,7 @@ TouchPuntToNextOwner(DeviceIntPtr dev, TouchPointInfoPtr ti,
     /* New owner has Begin/Update but not end. If touch is pending_finish,
      * emulate the TouchEnd now */
     if (ti->pending_finish) {
-        EmitTouchEnd(dev, ti, 0, 0);
+        TouchEmitTouchEnd(dev, ti, 0, 0);
 
         /* If the last owner is not a touch grab, finalise the touch, we
            won't get more correspondence on this.
@@ -1208,7 +1181,7 @@ TouchRejected(DeviceIntPtr sourcedev, TouchPointInfoPtr ti, XID resource,
     for (i = 0; i < ti->num_listeners; i++) {
         if (ti->listeners[i].listener == resource) {
             if (ti->listeners[i].state != LISTENER_HAS_END)
-                EmitTouchEnd(sourcedev, ti, TOUCH_REJECT, resource);
+                TouchEmitTouchEnd(sourcedev, ti, TOUCH_REJECT, resource);
             break;
         }
     }
@@ -1255,12 +1228,12 @@ ProcessTouchOwnershipEvent(TouchOwnershipEvent *ev,
          * already seen the end. This ensures that the touch record is ended in
          * the server. */
         if (ti->listeners[0].state == LISTENER_HAS_END)
-            EmitTouchEnd(dev, ti, TOUCH_ACCEPT, ti->listeners[0].listener);
+            TouchEmitTouchEnd(dev, ti, TOUCH_ACCEPT, ti->listeners[0].listener);
 
         /* The touch owner has accepted the touch.  Send TouchEnd events to
          * everyone else, and truncate the list of listeners. */
         for (i = 1; i < ti->num_listeners; i++)
-            EmitTouchEnd(dev, ti, TOUCH_ACCEPT, ti->listeners[i].listener);
+            TouchEmitTouchEnd(dev, ti, TOUCH_ACCEPT, ti->listeners[i].listener);
 
         while (ti->num_listeners > 1)
             TouchRemoveListener(ti, ti->listeners[1].listener);
diff --git a/dix/touch.c b/dix/touch.c
index 76592e7..f7112fc 100644
--- a/dix/touch.c
+++ b/dix/touch.c
@@ -1075,3 +1075,30 @@ TouchEndPhysicallyActiveTouches(DeviceIntPtr dev)
 
     FreeEventList(eventlist, GetMaximumEventsNum());
 }
+
+/**
+ * Generate and deliver a TouchEnd event.
+ *
+ * @param dev The device to deliver the event for.
+ * @param ti The touch point record to deliver the event for.
+ * @param flags Internal event flags. The called does not need to provide
+ *        TOUCH_CLIENT_ID and TOUCH_POINTER_EMULATED, this function will ensure
+ *        they are set appropriately.
+ * @param resource The client resource to deliver to, or 0 for all clients.
+ */
+void
+TouchEmitTouchEnd(DeviceIntPtr dev, TouchPointInfoPtr ti, int flags, XID resource)
+{
+    InternalEvent event;
+
+    /* We're not processing a touch end for a frozen device */
+    if (dev->deviceGrab.sync.frozen)
+        return;
+
+    flags |= TOUCH_CLIENT_ID;
+    if (ti->emulate_pointer)
+        flags |= TOUCH_POINTER_EMULATED;
+    TouchDeliverDeviceClassesChangedEvent(ti, GetTimeInMillis(), resource);
+    GetDixTouchEnd(&event, dev, ti, flags);
+    DeliverTouchEvents(dev, ti, &event, resource);
+}
diff --git a/include/input.h b/include/input.h
index 304895f..ef8191b 100644
--- a/include/input.h
+++ b/include/input.h
@@ -590,6 +590,7 @@ extern int TouchAcceptReject(ClientPtr client, DeviceIntPtr dev, int mode,
 extern void TouchEndPhysicallyActiveTouches(DeviceIntPtr dev);
 extern void TouchDeliverDeviceClassesChangedEvent(TouchPointInfoPtr ti,
                                                   Time time, XID resource);
+extern void TouchEmitTouchEnd(DeviceIntPtr dev, TouchPointInfoPtr ti, int flags, XID resource);
 
 /* misc event helpers */
 extern Mask GetEventMask(DeviceIntPtr dev, xEvent *ev, InputClientsPtr clients);
commit 0eb9390f6048049136347d5a5834d88bfc67cc09
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Mar 1 10:41:01 2013 +1000

    Xi: Don't emit a TouchEnd event to a frozen device
    
    EmitTouchEnd calls DeliverTouchEvents directly instead of through
    public.processInputProc. If a device is frozen, the TouchEnd is
    processed while the device is waiting for a XAllowEvents and thus ends the
    touch point (and the grab) before the client decided what to do with it. In
    the case of ReplayPointer, this loses the event.
    
    This is a hack, but making EmitTouchEnd use processInputProc breaks
    approximately everything, especially the touch point is cleaned up during
    ProcessTouchEvents. Working around that is a bigger hack than this.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index f480473..f500669 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1067,6 +1067,10 @@ EmitTouchEnd(DeviceIntPtr dev, TouchPointInfoPtr ti, int flags, XID resource)
 {
     InternalEvent event;
 
+    /* We're not processing a touch end for a frozen device */
+    if (dev->deviceGrab.sync.frozen)
+        return;
+
     flags |= TOUCH_CLIENT_ID;
     if (ti->emulate_pointer)
         flags |= TOUCH_POINTER_EMULATED;
commit a7d989d335f903ffd8b168cd2beeb82c78d30c21
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Feb 28 13:07:26 2013 +1000

    Xi: use public.processInputProc to replay the touch history
    
    If a device is frozen in results to a grab, we need to enqueue the events.
    
    This makes things complicated, and hard to follow since touch events are now
    replayed in the history, pushed into EnqueueEvent, then replayed later
    during PlayReleasedEvents in response to an XAllowEvents.
    
    While the device is frozen, no touch events are processed, so if there is a
    touch client with ownership mask _below_ the grab this will delay the
    delivery and potentially screw gesture recognition. However, this is the
    behaviour we have already anyway if the top-most client is a sync pgrab or
    there is a sync grab active on the device when the TouchBegin was generated.
    
    (also note, such a client would only reliably work in case of ReplayPointer
    anyway)
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 9d999de..f480473 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1554,7 +1554,7 @@ ProcessTouchEvent(InternalEvent *ev, DeviceIntPtr dev)
 
     touchid = ev->device_event.touchid;
 
-    if (type == ET_TouchBegin) {
+    if (type == ET_TouchBegin && !(ev->device_event.flags & TOUCH_REPLAYING)) {
         ti = TouchBeginTouch(dev, ev->device_event.sourceid, touchid,
                              emulate_pointer);
     }
@@ -1621,7 +1621,9 @@ ProcessTouchEvent(InternalEvent *ev, DeviceIntPtr dev)
      * called after event type mutation. Touch end events are always processed
      * in order to end touch records. */
     /* FIXME: check this */
-    if ((type == ET_TouchBegin && !TouchBuildSprite(dev, ti, ev)) ||
+    if ((type == ET_TouchBegin &&
+         !(ev->device_event.flags & TOUCH_REPLAYING) &&
+         !TouchBuildSprite(dev, ti, ev)) ||
         (type != ET_TouchEnd && ti->sprite.spriteTraceGood == 0))
         return;
 
@@ -1629,7 +1631,7 @@ ProcessTouchEvent(InternalEvent *ev, DeviceIntPtr dev)
     /* WARNING: the event type may change to TouchUpdate in
      * DeliverTouchEvents if a TouchEnd was delivered to a grabbing
      * owner */
-    DeliverTouchEvents(dev, ti, (InternalEvent *) ev, 0);
+    DeliverTouchEvents(dev, ti, ev, ev->device_event.resource);
     if (ev->any.type == ET_TouchEnd)
         TouchEndTouch(dev, ti);
 
diff --git a/dix/touch.c b/dix/touch.c
index 5d6e2a7..76592e7 100644
--- a/dix/touch.c
+++ b/dix/touch.c
@@ -474,7 +474,21 @@ TouchEventHistoryReplay(TouchPointInfoPtr ti, DeviceIntPtr dev, XID resource)
         DeviceEvent *ev = &ti->history[i];
 
         ev->flags |= TOUCH_REPLAYING;
-        DeliverTouchEvents(dev, ti, (InternalEvent *) ev, resource);
+        ev->resource = resource;
+        /* FIXME:
+           We're replaying ti->history which contains the TouchBegin +
+           all TouchUpdates for ti. This needs to be passed on to the next
+           listener. If that is a touch listener, everything is dandy.
+           If the TouchBegin however triggers a sync passive grab, the
+           TouchUpdate events must be sent to EnqueueEvent so the events end
+           up in syncEvents.pending to be forwarded correctly in a
+           subsequent ComputeFreeze().
+
+           However, if we just send them to EnqueueEvent the sync'ing device
+           prevents handling of touch events for ownership listeners who
+           want the events right here, right now.
+         */
+        dev->public.processInputProc((InternalEvent*)ev, dev);
     }
 }
 
diff --git a/include/eventstr.h b/include/eventstr.h
index 5c1adc4..3950584 100644
--- a/include/eventstr.h
+++ b/include/eventstr.h
@@ -123,6 +123,7 @@ struct _DeviceEvent {
     int corestate;    /**< Core key/button state BEFORE the event */
     int key_repeat;   /**< Internally-generated key repeat event */
     uint32_t flags;   /**< Flags to be copied into the generated event */
+    uint32_t resource; /**< Touch event resource, only for TOUCH_REPLAYING */
 };
 
 /**
commit 214d11d3fcdac51fc7afbf3770516ec14f9e13c1
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Feb 27 15:05:54 2013 +1000

    Xi: when punting to a new owner, always create TouchEnd events
    
    If a touch is pending_finish and we just punted it to the next owner, that
    client must receive a TouchEnd event.
    
    If we just punted to the last owner and that owner not a touch grab, we need
    to end the touch since this is the last event to be sent, and the client
    cannot accept/reject this.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 97fec35..9d999de 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1143,12 +1143,21 @@ TouchPuntToNextOwner(DeviceIntPtr dev, TouchPointInfoPtr ti,
         TouchEventHistoryReplay(ti, dev, listener->listener);
     }
 
-    /* If we've just removed the last grab and the touch has physically
-     * ended, send a TouchEnd event too and finalise the touch. */
-    if (ti->num_listeners == 1 && ti->num_grabs == 0 && ti->pending_finish) {
+    /* New owner has Begin/Update but not end. If touch is pending_finish,
+     * emulate the TouchEnd now */
+    if (ti->pending_finish) {
         EmitTouchEnd(dev, ti, 0, 0);
-        TouchEndTouch(dev, ti);
-        return;
+
+        /* If the last owner is not a touch grab, finalise the touch, we
+           won't get more correspondence on this.
+         */
+        if (ti->num_listeners == 1 &&
+            (ti->num_grabs == 0 ||
+             listener->grab->grabtype != XI2 ||
+             !xi2mask_isset(listener->grab->xi2mask, dev, XI_TouchBegin))) {
+            TouchEndTouch(dev, ti);
+            return;
+        }
     }
 
     if (accepted_early)
commit 026627fe19aad007544eccf209f0dea05e67a7a7
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Mar 1 09:15:37 2013 +1000

    Xi: save state for early acceptance
    
    Delivering an event changes the state to LISTENER_IS_OWNER and we thus lose
    the information of early acceptance.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 0f37d6b..97fec35 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1126,10 +1126,10 @@ TouchPuntToNextOwner(DeviceIntPtr dev, TouchPointInfoPtr ti,
                      TouchOwnershipEvent *ev)
 {
     TouchListener *listener = &ti->listeners[0]; /* new owner */
+    int accepted_early = listener->state == LISTENER_EARLY_ACCEPT;
 
     /* Deliver the ownership */
-    if (listener->state == LISTENER_AWAITING_OWNER ||
-        listener->state == LISTENER_EARLY_ACCEPT)
+    if (listener->state == LISTENER_AWAITING_OWNER || accepted_early)
         DeliverTouchEvents(dev, ti, (InternalEvent *) ev,
                            listener->listener);
     else if (listener->state == LISTENER_AWAITING_BEGIN) {
@@ -1151,7 +1151,7 @@ TouchPuntToNextOwner(DeviceIntPtr dev, TouchPointInfoPtr ti,
         return;
     }
 
-    if (listener->state == LISTENER_EARLY_ACCEPT)
+    if (accepted_early)
         ActivateEarlyAccept(dev, ti);
 }
 
commit d905348134c80f19793eefb761731b00559ddf3a
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Feb 28 15:28:46 2013 +1000

    Xi: if a passive async grab is activated from an emulated touch, accept
    
    Async grabs cannot replay events, they cannot reject, so we can do an early
    accept here.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index b1df0cb..0f37d6b 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1848,8 +1848,14 @@ DeliverTouchBeginEvent(DeviceIntPtr dev, TouchPointInfoPtr ti,
         listener->type == LISTENER_POINTER_GRAB) {
         rc = DeliverTouchEmulatedEvent(dev, ti, ev, listener, client, win,
                                        grab, xi2mask);
-        if (rc == Success)
+        if (rc == Success) {
             listener->state = LISTENER_IS_OWNER;
+            /* async grabs cannot replay, so automatically accept this touch */
+            if (dev->deviceGrab.grab &&
+                dev->deviceGrab.fromPassiveGrab &&
+                dev->deviceGrab.grab->pointerMode == GrabModeAsync)
+                ActivateEarlyAccept(dev, ti);
+        }
         goto out;
     }
 
commit 8b0d21044956f3810199d5e2f38ce33069e97be7
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Feb 28 13:04:36 2013 +1000

    Xi: fix lookup in ActivateEarlyAccept
    
    ActivateEarlyAccept() can only be called from a grabbing client, so we can
    ignore the rest. And it's easy enough to get the client from that since
    9ad0fdb135a1c336771aee1f6eab75a6ad874aff.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 27551dd..b1df0cb 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1039,17 +1039,16 @@ ActivateEarlyAccept(DeviceIntPtr dev, TouchPointInfoPtr ti)
     int rc;
     ClientPtr client;
     XID error;
+    GrabPtr grab = ti->listeners[0].grab;
 
-    rc = dixLookupClient(&client, ti->listeners[0].listener, serverClient,
-                         DixSendAccess);
-    if (rc != Success) {
-        ErrorF("[Xi] Failed to lookup early accepting client.\n");
-        return;
-    }
+    BUG_RETURN(ti->listeners[0].type != LISTENER_GRAB &&
+               ti->listeners[0].type != LISTENER_POINTER_GRAB);
+    BUG_RETURN(!grab);
+
+    client = rClient(grab);
 
     if (TouchAcceptReject(client, dev, XIAcceptTouch, ti->client_id,
-                          ti->listeners[0].window->drawable.id, &error) !=
-        Success)
+                          ti->listeners[0].window->drawable.id, &error) != Success)
         ErrorF("[Xi] Failed to accept touch grab after early acceptance.\n");
 }
 
commit d08bae297f9d7651edb1923d6b0d6b14b3d674fc
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Feb 28 13:08:27 2013 +1000

    Xi: update the core listener state if we delivered the touch event
    
    If a TouchBegin is sent to a core client, that client is now the owner.
    
    By the time the TouchEnd is being processed, the client cannot replay
    anymore, so we can assume that this is the final touch end and we can clean
    up the touch record.
    
    Note: DeliverTouchEmulatedEvent is called for all listeners and immediately
    bails out if the client is not the owner and thus shouldn't yet get the
    event. Thus, check the return code.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 0cadf43..27551dd 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1849,6 +1849,8 @@ DeliverTouchBeginEvent(DeviceIntPtr dev, TouchPointInfoPtr ti,
         listener->type == LISTENER_POINTER_GRAB) {
         rc = DeliverTouchEmulatedEvent(dev, ti, ev, listener, client, win,
                                        grab, xi2mask);
+        if (rc == Success)
+            listener->state = LISTENER_IS_OWNER;
         goto out;
     }
 
@@ -1889,13 +1891,13 @@ DeliverTouchEndEvent(DeviceIntPtr dev, TouchPointInfoPtr ti, InternalEvent *ev,
         rc = DeliverTouchEmulatedEvent(dev, ti, ev, listener, client, win,
                                        grab, xi2mask);
 
-        if (ti->num_listeners > 1) {
-            ev->any.type = ET_TouchUpdate;
-            ev->device_event.flags |= TOUCH_PENDING_END;
-            if (!(ev->device_event.flags & TOUCH_CLIENT_ID))
-                ti->pending_finish = TRUE;
-        }
-
+         /* Once we send a TouchEnd to a legacy listener, we're already well
+          * past the accepting/rejecting stage (can only happen on
+          * GrabModeSync + replay. This listener now gets the end event,
+          * and we can continue.
+          */
+        if (rc == Success)
+            listener->state = LISTENER_HAS_END;
         goto out;
     }
 
commit 81554d274f04951c55ea7f2e38d0455e2025e08d
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Feb 25 11:21:07 2013 +1000

    Xi: if we delivered a TouchEnd to a passive grab, end it
    
    ef64b5ee97099618cf2e2cbbd3e471095695ae24 (which introduced the
    TOUCH_CLIENT_ID check) has a wrong assumption that generated touch events
    (TOUCH_CLIENT_ID) should not terminate passive grabs.
    This is untrue, a TouchEnd may be generated in response to a TouchReject
    higher up. If we _deliver_ an event to a client, terminate the passive grab.
    
    This requires us to count the actually delivered events too (first hunk).
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index fae747c..0cadf43 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1417,7 +1417,7 @@ DeliverTouchEmulatedEvent(DeviceIntPtr dev, TouchPointInfoPtr ti,
             }
 
             if (!deliveries)
-                DeliverOneGrabbedEvent(ptrev, dev, grab->grabtype);
+                deliveries = DeliverOneGrabbedEvent(ptrev, dev, grab->grabtype);
 
             /* We must accept the touch sequence once a pointer listener has
              * received one event past ButtonPress. */
@@ -1425,8 +1425,7 @@ DeliverTouchEmulatedEvent(DeviceIntPtr dev, TouchPointInfoPtr ti,
                 !(ev->device_event.flags & TOUCH_CLIENT_ID))
                 TouchListenerAcceptReject(dev, ti, 0, XIAcceptTouch);
 
-            if (ev->any.type == ET_TouchEnd &&
-                !(ev->device_event.flags & TOUCH_CLIENT_ID) &&
+            if (deliveries && ev->any.type == ET_TouchEnd &&
                 !dev->button->buttonsDown &&
                 dev->deviceGrab.fromPassiveGrab && GrabIsPointerGrab(grab)) {
                 (*dev->deviceGrab.DeactivateGrab) (dev);
commit 363b6387da6e669099a2da3861c73a29808295a6
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Feb 13 11:26:11 2013 +1000

    dix: don't prepend an activated passive grab to the listeners
    
    If the device is currently grabbed as the result of a passive grab
    activating, do not prepend that grab to the listeners (unlike active grabs).
    Otherwise, a client with a passive pointer grab will prevent touch grabs
    from activating higher up in the window stack.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/touch.c b/dix/touch.c
index 3027bbb..5d6e2a7 100644
--- a/dix/touch.c
+++ b/dix/touch.c
@@ -874,7 +874,7 @@ TouchSetupListeners(DeviceIntPtr dev, TouchPointInfoPtr ti, InternalEvent *ev)
     SpritePtr sprite = &ti->sprite;
     WindowPtr win;
 
-    if (dev->deviceGrab.grab)
+    if (dev->deviceGrab.grab && !dev->deviceGrab.fromPassiveGrab)
         TouchAddActiveGrabListener(dev, ti, ev, dev->deviceGrab.grab);
 
     /* We set up an active touch listener for existing touches, but not any
commit 9cc45c18ad1511adf3fb163dd4cefbef106edb23
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Feb 13 10:49:23 2013 +1000

    Xi: not having an ownership mask does not mean automatic acceptance
    
    If we only have a single touch-grabbing client, setting the client as owner
    would clean up the touch once the TouchEnd was processed. If the client then
    calls XIAllowTouches() it will receive a BadValue for the touch ID (since
    the internal record is already cleaned up).
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 3088257..fae747c 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1867,7 +1867,7 @@ DeliverTouchBeginEvent(DeviceIntPtr dev, TouchPointInfoPtr ti,
         if (has_ownershipmask)
             TouchSendOwnershipEvent(dev, ti, 0, listener->listener);
 
-        if (!has_ownershipmask || listener->type == LISTENER_REGULAR)
+        if (listener->type == LISTENER_REGULAR)
             state = LISTENER_HAS_ACCEPTED;
         else
             state = LISTENER_IS_OWNER;
commit 2f1aedcaed8fd99b823d451bf1fb02330c078f67
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu May 9 14:30:50 2013 +1000

    input: print warnings if drivers don't initialize properly
    
    If drivers supply incorrect values don't just quietly return False, spew to
    the log so we can detect what's going on. All these cases are driver bugs
    and should be fixed immediately.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Dave Airlie <airlied at redhat.com>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 7eb71ee..3088257 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -2023,6 +2023,9 @@ InitProximityClassDeviceStruct(DeviceIntPtr dev)
 {
     ProximityClassPtr proxc;
 
+    BUG_RETURN_VAL(dev == NULL, FALSE);
+    BUG_RETURN_VAL(dev->proximity != NULL, FALSE);
+
     proxc = (ProximityClassPtr) malloc(sizeof(ProximityClassRec));
     if (!proxc)
         return FALSE;
@@ -2048,10 +2051,10 @@ InitValuatorAxisStruct(DeviceIntPtr dev, int axnum, Atom label, int minval,
 {
     AxisInfoPtr ax;
 
-    if (!dev || !dev->valuator || (minval > maxval && mode == Absolute))
-        return FALSE;
-    if (axnum >= dev->valuator->numAxes)
-        return FALSE;
+    BUG_RETURN_VAL(dev == NULL, FALSE);
+    BUG_RETURN_VAL(dev->valuator == NULL, FALSE);
+    BUG_RETURN_VAL(axnum >= dev->valuator->numAxes, FALSE);
+    BUG_RETURN_VAL(minval > maxval && mode == Absolute, FALSE);
 
     ax = dev->valuator->axes + axnum;
 
@@ -2081,8 +2084,9 @@ SetScrollValuator(DeviceIntPtr dev, int axnum, enum ScrollType type,
     InternalEvent dce;
     DeviceIntPtr master;
 
-    if (!dev || !dev->valuator || axnum >= dev->valuator->numAxes)
-        return FALSE;
+    BUG_RETURN_VAL(dev == NULL, FALSE);
+    BUG_RETURN_VAL(dev->valuator == NULL, FALSE);
+    BUG_RETURN_VAL(axnum >= dev->valuator->numAxes, FALSE);
 
     switch (type) {
     case SCROLL_TYPE_VERTICAL:
diff --git a/dix/devices.c b/dix/devices.c
index 767b5c7..9b6faee 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -1277,6 +1277,9 @@ InitButtonClassDeviceStruct(DeviceIntPtr dev, int numButtons, Atom *labels,
     ButtonClassPtr butc;
     int i;
 
+    BUG_RETURN_VAL(dev == NULL, FALSE);
+    BUG_RETURN_VAL(dev->button != NULL, FALSE);
+
     butc = calloc(1, sizeof(ButtonClassRec));
     if (!butc)
         return FALSE;
@@ -1337,8 +1340,7 @@ InitValuatorClassDeviceStruct(DeviceIntPtr dev, int numAxes, Atom *labels,
     int i;
     ValuatorClassPtr valc;
 
-    if (!dev)
-        return FALSE;
+    BUG_RETURN_VAL(dev == NULL, FALSE);
 
     if (numAxes > MAX_VALUATORS) {
         LogMessage(X_WARNING,
@@ -1447,6 +1449,9 @@ InitFocusClassDeviceStruct(DeviceIntPtr dev)
 {
     FocusClassPtr focc;
 
+    BUG_RETURN_VAL(dev == NULL, FALSE);
+    BUG_RETURN_VAL(dev->focus != NULL, FALSE);
+
     focc = malloc(sizeof(FocusClassRec));
     if (!focc)
         return FALSE;
@@ -1466,6 +1471,9 @@ InitPtrFeedbackClassDeviceStruct(DeviceIntPtr dev, PtrCtrlProcPtr controlProc)
 {
     PtrFeedbackPtr feedc;
 
+    BUG_RETURN_VAL(dev == NULL, FALSE);
+    BUG_RETURN_VAL(dev->ptrfeed != NULL, FALSE);
+
     feedc = malloc(sizeof(PtrFeedbackClassRec));
     if (!feedc)
         return FALSE;
@@ -1507,6 +1515,9 @@ InitStringFeedbackClassDeviceStruct(DeviceIntPtr dev,
     int i;
     StringFeedbackPtr feedc;
 
+    BUG_RETURN_VAL(dev == NULL, FALSE);
+    BUG_RETURN_VAL(dev->stringfeed != NULL, FALSE);
+
     feedc = malloc(sizeof(StringFeedbackClassRec));
     if (!feedc)
         return FALSE;
@@ -1541,6 +1552,9 @@ InitBellFeedbackClassDeviceStruct(DeviceIntPtr dev, BellProcPtr bellProc,
 {
     BellFeedbackPtr feedc;
 
+    BUG_RETURN_VAL(dev == NULL, FALSE);
+    BUG_RETURN_VAL(dev->bell != NULL, FALSE);
+
     feedc = malloc(sizeof(BellFeedbackClassRec));
     if (!feedc)
         return FALSE;
@@ -1560,6 +1574,9 @@ InitLedFeedbackClassDeviceStruct(DeviceIntPtr dev, LedCtrlProcPtr controlProc)
 {
     LedFeedbackPtr feedc;
 
+    BUG_RETURN_VAL(dev == NULL, FALSE);
+    BUG_RETURN_VAL(dev->leds != NULL, FALSE);
+
     feedc = malloc(sizeof(LedFeedbackClassRec));
     if (!feedc)
         return FALSE;
@@ -1580,6 +1597,9 @@ InitIntegerFeedbackClassDeviceStruct(DeviceIntPtr dev,
 {
     IntegerFeedbackPtr feedc;
 
+    BUG_RETURN_VAL(dev == NULL, FALSE);
+    BUG_RETURN_VAL(dev->intfeed != NULL, FALSE);
+
     feedc = malloc(sizeof(IntegerFeedbackClassRec));
     if (!feedc)
         return FALSE;
@@ -1600,6 +1620,11 @@ InitPointerDeviceStruct(DevicePtr device, CARD8 *map, int numButtons,
 {
     DeviceIntPtr dev = (DeviceIntPtr) device;
 
+    BUG_RETURN_VAL(dev == NULL, FALSE);
+    BUG_RETURN_VAL(dev->button != NULL, FALSE);
+    BUG_RETURN_VAL(dev->valuator != NULL, FALSE);
+    BUG_RETURN_VAL(dev->ptrfeed != NULL, FALSE);
+
     return (InitButtonClassDeviceStruct(dev, numButtons, btn_labels, map) &&
             InitValuatorClassDeviceStruct(dev, numAxes, axes_labels,
                                           numMotionEvents, Relative) &&
@@ -1620,14 +1645,12 @@ InitTouchClassDeviceStruct(DeviceIntPtr device, unsigned int max_touches,
     TouchClassPtr touch;
     int i;
 
-    if (device->touch || !device->valuator)
-        return FALSE;
+    BUG_RETURN_VAL(device == NULL, FALSE);
+    BUG_RETURN_VAL(device->touch != NULL, FALSE);
 
     /* Check the mode is valid, and at least X and Y axes. */
-    if (mode != XIDirectTouch && mode != XIDependentTouch)
-        return FALSE;
-    if (num_axes < 2)
-        return FALSE;
+    BUG_RETURN_VAL(mode != XIDirectTouch && mode != XIDependentTouch, FALSE);
+    BUG_RETURN_VAL(num_axes < 2, FALSE);
 
     if (num_axes > MAX_VALUATORS) {
         LogMessage(X_WARNING,
diff --git a/xkb/xkbInit.c b/xkb/xkbInit.c
index 573c4ff..5308a29 100644
--- a/xkb/xkbInit.c
+++ b/xkb/xkbInit.c
@@ -503,8 +503,9 @@ InitKeyboardDeviceStruct(DeviceIntPtr dev, XkbRMLVOSet * rmlvo,
     XkbEventCauseRec cause;
     XkbRMLVOSet rmlvo_dflts = { NULL };
 
-    if (dev->key || dev->kbdfeed)
-        return FALSE;
+    BUG_RETURN_VAL(dev == NULL, FALSE);
+    BUG_RETURN_VAL(dev->key != NULL, FALSE);
+    BUG_RETURN_VAL(dev->kbdfeed != NULL, FALSE);
 
     if (!rmlvo) {
         rmlvo = &rmlvo_dflts;
commit 8a88b0ab52ba375ae84463a90503db88af10e368
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu May 9 14:30:49 2013 +1000

    dix: don't overwrite proximity/focus classes
    
    InitPointerClassDeviceStruct/InitKeyboardDeviceStruct allocate a
    proximity/focus class, respectively. If a driver calls
    InitFocusClassDeviceStruct or InitProximityClassDeviceStruct beforehand,
    the previously allocated class is overwritten, leaking the memory.
    
    Neither takes a parameter other than the device, so we can simply skip
    initialising it if we already have one.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Dave Airlie <airlied at redhat.com>

diff --git a/dix/devices.c b/dix/devices.c
index 0c718d2..767b5c7 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -1367,7 +1367,7 @@ InitValuatorClassDeviceStruct(DeviceIntPtr dev, int numAxes, Atom *labels,
     valc->numMotionEvents = numMotionEvents;
     valc->motionHintWindow = NullWindow;
 
-    if (mode & OutOfProximity)
+    if ((mode & OutOfProximity) && !dev->proximity)
         InitProximityClassDeviceStruct(dev);
 
     dev->valuator = valc;
diff --git a/xkb/xkbInit.c b/xkb/xkbInit.c
index 244c353..573c4ff 100644
--- a/xkb/xkbInit.c
+++ b/xkb/xkbInit.c
@@ -589,7 +589,8 @@ InitKeyboardDeviceStruct(DeviceIntPtr dev, XkbRMLVOSet * rmlvo,
     XkbUpdateActions(dev, xkb->min_key_code, XkbNumKeys(xkb), &changes,
                      &check, &cause);
 
-    InitFocusClassDeviceStruct(dev);
+    if (!dev->focus)
+        InitFocusClassDeviceStruct(dev);
 
     xkbi->kbdProc = ctrl_func;
     dev->kbdfeed->BellProc = bell_func;
commit 34b0d07ebf4a7874fe7fd336bef5bbdd8debda1c
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri May 10 09:44:29 2013 +1000

    dix: reset the OsBuffers after killing all clients
    
    ==21860== 24 bytes in 1 blocks are still reachable in loss record 85 of 397
    ==21860==    at 0x4C2B3F8: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==21860==    by 0x61ED93: AllocateOutputBuffer (io.c:1037)
    ==21860==    by 0x61E15A: WriteToClient (io.c:764)
    ==21860==    by 0x457B30: ProcQueryExtension (extension.c:275)
    ==21860==    by 0x43596B: Dispatch (dispatch.c:432)
    ==21860==    by 0x425DAB: main (main.c:295)
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Dave Airlie <airlied at redhat.com>

diff --git a/dix/dispatch.c b/dix/dispatch.c
index 90b6c7c..1363f22 100644
--- a/dix/dispatch.c
+++ b/dix/dispatch.c
@@ -465,6 +465,7 @@ Dispatch(void)
     free(clientReady);
     dispatchException &= ~DE_RESET;
     SmartScheduleLatencyLimited = 0;
+    ResetOsBuffers();
 }
 
 static int VendorRelease = VENDOR_RELEASE;
commit 67c66606c760c263d7a4c2d1bba43ed6225a4e7c
Author: Robert Morell <rmorell at nvidia.com>
Date:   Thu May 9 13:09:02 2013 -0700

    os: Reset input buffer's 'ignoreBytes' field
    
    If a client sends a request larger than maxBigRequestSize, the server is
    supposed to ignore it.
    
    Before commit cf88363d, the server would simply disconnect the client.  After
    that commit, it attempts to gracefully ignore the request by remembering how
    long the client specified the request to be, and ignoring that many bytes.
    However, if a client sends a BigReq header with a large size and disconnects
    before actually sending the rest of the specified request, the server will
    reuse the ConnectionInput buffer without resetting the ignoreBytes field.  This
    makes the server ignore new X clients' requests.
    
    This fixes that behavior by resetting the ignoreBytes field when putting the
    ConnectionInput buffer back on the FreeInputs list.
    
    Signed-off-by: Robert Morell <rmorell at nvidia.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/os/io.c b/os/io.c
index 2f091c4..0d980ab 100644
--- a/os/io.c
+++ b/os/io.c
@@ -1063,6 +1063,7 @@ FreeOsBuffers(OsCommPtr oc)
             oci->bufptr = oci->buffer;
             oci->bufcnt = 0;
             oci->lenLastReq = 0;
+            oci->ignoreBytes = 0;
         }
     }
     if ((oco = oc->output)) {
commit ddc11397a56c745b5d1fb377e9d9b1fcc73802c8
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Feb 27 18:36:39 2012 +1000

    dix: delete all callbacks before reset
    
    DeleteCallbackManager() introduced for better symmetry in the caller, they
    do the same thing.
    
    ==20085== 24 bytes in 1 blocks are still reachable in loss record 11 of 103
    ==20085==    at 0x4C2A4CD: malloc (vg_replace_malloc.c:236)
    ==20085==    by 0x43A097: CreateCallbackList (dixutils.c:837)
    ==20085==    by 0x43A1D3: AddCallback (dixutils.c:869)
    ==20085==    by 0x4B1736: GEExtensionInit (geext.c:209)
    ==20085==    by 0x41C8A8: InitExtensions (miinitext.c:389)
    ==20085==    by 0x5AC918: main (main.c:208)
    
    ==2042== 8 bytes in 1 blocks are still reachable in loss record 2 of 97
    ==2042==    at 0x4C2A4CD: malloc (vg_replace_malloc.c:236)
    ==2042==    by 0x4C2A657: realloc (vg_replace_malloc.c:525)
    ==2042==    by 0x4802F5: XNFrealloc (utils.c:1095)
    ==2042==    by 0x43A17A: CreateCallbackList (dixutils.c:855)
    ==2042==    by 0x43A1EF: AddCallback (dixutils.c:870)
    ==2042==    by 0x4B1752: GEExtensionInit (geext.c:209)
    ==2042==    by 0x41C8A8: InitExtensions (miinitext.c:389)
    ==2042==    by 0x5AC9E4: main (main.c:208)
    ==2042==
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/dix/dixutils.c b/dix/dixutils.c
index 3f24629..c250bb1 100644
--- a/dix/dixutils.c
+++ b/dix/dixutils.c
@@ -849,7 +849,7 @@ DeleteCallbackList(CallbackListPtr *pcbl)
 }
 
 void
-InitCallbackManager(void)
+DeleteCallbackManager(void)
 {
     int i;
 
@@ -861,3 +861,9 @@ InitCallbackManager(void)
     numCallbackListsToCleanup = 0;
     listsToCleanup = NULL;
 }
+
+void
+InitCallbackManager(void)
+{
+    DeleteCallbackManager();
+}
diff --git a/dix/main.c b/dix/main.c
index 1fa0504..e69cd93 100644
--- a/dix/main.c
+++ b/dix/main.c
@@ -366,6 +366,8 @@ main(int argc, char *argv[], char *envp[])
 
         FreeAuditTimer();
 
+        DeleteCallbackManager();
+
         if (dispatchException & DE_TERMINATE) {
             CloseWellKnownConnections();
         }
diff --git a/include/callback.h b/include/callback.h
index ed6b678..b427089 100644
--- a/include/callback.h
+++ b/include/callback.h
@@ -86,5 +86,6 @@ CallCallbacks(CallbackListPtr *pcbl, pointer call_data)
 extern _X_EXPORT void DeleteCallbackList(CallbackListPtr * /*pcbl */ );
 
 extern _X_EXPORT void InitCallbackManager(void);
+extern _X_EXPORT void DeleteCallbackManager(void);
 
 #endif                          /* CALLBACK_H */
commit 6993f8b459e25b1a7a0a03e209688a28ce6c2c56
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Apr 24 14:59:11 2013 +1000

    Xi: free barrier code at reset time
    
    ==29423== 16 bytes in 1 blocks are definitely lost in loss record 73 of 328
    ==29423==    at 0x4A06B6F: calloc (vg_replace_malloc.c:593)
    ==29423==    by 0x5987C0: XIBarrierInit (xibarriers.c:908)
    ==29423==    by 0x58F370: XInputExtensionInit (extinit.c:1300)
    ==29423==    by 0x4F33C3: InitExtensions (miinitext.c:337)
    ==29423==    by 0x4997DB: main (main.c:208)
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/Xi/extinit.c b/Xi/extinit.c
index 02fffe5..a49a421 100644
--- a/Xi/extinit.c
+++ b/Xi/extinit.c
@@ -1171,6 +1171,8 @@ IResetProc(ExtensionEntry * unused)
 
     free(xi_all_devices.name);
     free(xi_all_master_devices.name);
+
+    XIBarrierReset();
 }
 
 /***********************************************************************
diff --git a/Xi/xibarriers.c b/Xi/xibarriers.c
index fccab86..6732ce9 100644
--- a/Xi/xibarriers.c
+++ b/Xi/xibarriers.c
@@ -917,3 +917,15 @@ XIBarrierInit(void)
 
     return PointerBarrierType;
 }
+
+void
+XIBarrierReset(void)
+{
+    int i;
+    for (i = 0; i < screenInfo.numScreens; i++) {
+        ScreenPtr pScreen = screenInfo.screens[i];
+        BarrierScreenPtr cs = GetBarrierScreen(pScreen);
+        free(cs);
+        SetBarrierScreen(pScreen, NULL);
+    }
+}
diff --git a/Xi/xibarriers.h b/Xi/xibarriers.h
index 11e84ec..f61b482 100644
--- a/Xi/xibarriers.h
+++ b/Xi/xibarriers.h
@@ -36,8 +36,8 @@ int
 XIDestroyPointerBarrier(ClientPtr client,
                         xXFixesDestroyPointerBarrierReq * stuff);
 
-Bool
-XIBarrierInit(void);
+Bool XIBarrierInit(void);
+void XIBarrierReset(void);
 
 int SProcXIBarrierReleasePointer(ClientPtr client);
 int ProcXIBarrierReleasePointer(ClientPtr client);
commit 042c6d861f7bb7038ddcdd6b59766fd9094d0e52
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Tue Apr 30 15:44:37 2013 +1000

    os: Use ErrorFSigSafe from FatalError and it's friends
    
    Backtrace logging etc. is already sigsafe, but the actual FatalError message
    in response is not yet, leading to amusing logs like this:
    
        (EE) Segmentation fault at address 0x0
        (EE) BUG: triggered 'if (inSignalContext)'
        (EE) BUG: log.c:499 in LogVMessageVerb()
        (EE) Warning: attempting to log data in a signal unsafe manner while in
        signal context.
        Please update to check inSignalContext and/or use LogMessageVerbSigSafe() or
        ErrorFSigSafe().
        The offending log format message is:
    
        Fatal server error:
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/glx/glxdri.c b/glx/glxdri.c
index 1964d2e..1ac6839 100644
--- a/glx/glxdri.c
+++ b/glx/glxdri.c
@@ -889,7 +889,7 @@ glxDRILeaveVT(ScrnInfoPtr scrn)
     __GLXDRIscreen *screen = (__GLXDRIscreen *)
         glxGetScreen(xf86ScrnToScreen(scrn));
 
-    LogMessage(X_INFO, "AIGLX: Suspending AIGLX clients for VT switch\n");
+    LogMessageVerbSigSafe(X_INFO, -1, "AIGLX: Suspending AIGLX clients for VT switch\n");
 
     glxSuspendClients();
 
diff --git a/glx/glxdri2.c b/glx/glxdri2.c
index 6548579..8a1fa41 100644
--- a/glx/glxdri2.c
+++ b/glx/glxdri2.c
@@ -835,7 +835,7 @@ glxDRILeaveVT(ScrnInfoPtr scrn)
     __GLXDRIscreen *screen = (__GLXDRIscreen *)
         glxGetScreen(xf86ScrnToScreen(scrn));
 
-    LogMessage(X_INFO, "AIGLX: Suspending AIGLX clients for VT switch\n");
+    LogMessageVerbSigSafe(X_INFO, -1, "AIGLX: Suspending AIGLX clients for VT switch\n");
 
     glxSuspendClients();
 
diff --git a/os/log.c b/os/log.c
index 3dc675f..f19faf5 100644
--- a/os/log.c
+++ b/os/log.c
@@ -250,7 +250,7 @@ void
 LogClose(enum ExitCode error)
 {
     if (logFile) {
-        ErrorF("Server terminated %s (%d). Closing log file.\n",
+        ErrorFSigSafe("Server terminated %s (%d). Closing log file.\n",
                (error == EXIT_NO_ERROR) ? "successfully" : "with error", error);
         fclose(logFile);
         logFile = NULL;
@@ -878,9 +878,9 @@ FatalError(const char *f, ...)
     static Bool beenhere = FALSE;
 
     if (beenhere)
-        ErrorF("\nFatalError re-entered, aborting\n");
+        ErrorFSigSafe("\nFatalError re-entered, aborting\n");
     else
-        ErrorF("\nFatal server error:\n");
+        ErrorFSigSafe("\nFatal server error:\n");
 
     va_start(args, f);
 
@@ -897,9 +897,9 @@ FatalError(const char *f, ...)
         va_end(apple_args);
     }
 #endif
-    VErrorF(f, args);
+    VErrorFSigSafe(f, args);
     va_end(args);
-    ErrorF("\n");
+    ErrorFSigSafe("\n");
     if (!beenhere)
         OsVendorFatalError(f, args2);
     va_end(args2);
commit d9848fb4b182ca21bacf28ed7410d1a502cb000e
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Feb 14 16:24:53 2013 +1000

    os: complain about unsupported pnprintf directives
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/os/log.c b/os/log.c
index 9f95743..3dc675f 100644
--- a/os/log.c
+++ b/os/log.c
@@ -461,6 +461,7 @@ pnprintf(char *string, size_t size, const char *f, va_list args)
             string[s_idx++] = '%';
             break;
         default:
+            BUG_WARN_MSG(f[f_idx], "Unsupported printf directive '%c'\n", f[f_idx]);
             va_arg(args, char*);
             string[s_idx++] = '%';
             if (s_idx < size - 1)
diff --git a/test/signal-logging.c b/test/signal-logging.c
index b45d8d4..f6bc85c 100644
--- a/test/signal-logging.c
+++ b/test/signal-logging.c
@@ -206,6 +206,13 @@ static void logging_format(void)
     read_log_msg(logmsg);
     assert(strcmp(logmsg, "(EE) test a\n") == 0);
 
+    /* something unsupported % */
+    LogMessageVerbSigSafe(X_ERROR, -1, "test %Q\n");
+    read_log_msg(logmsg);
+    assert(strstr(logmsg, "BUG") != NULL);
+    LogMessageVerbSigSafe(X_ERROR, -1, "\n");
+    fseek(f, 0, SEEK_END);
+
     /* string substitution */
     LogMessageVerbSigSafe(X_ERROR, -1, "%s\n", "substituted string");
     read_log_msg(logmsg);
commit d903d17d7f006fa333265b8476063b189c20d082
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Feb 14 16:19:34 2013 +1000

    os: support %c in pnprintf
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/os/log.c b/os/log.c
index e4e9e8b..9f95743 100644
--- a/os/log.c
+++ b/os/log.c
@@ -450,6 +450,13 @@ pnprintf(char *string, size_t size, const char *f, va_list args)
                     string[s_idx++] = number[i];
             }
             break;
+        case 'c':
+            {
+                char c = va_arg(args, int);
+                if (s_idx < size - 1)
+                    string[s_idx++] = c;
+            }
+            break;
         case '%':
             string[s_idx++] = '%';
             break;
diff --git a/test/signal-logging.c b/test/signal-logging.c
index 65baa45..b45d8d4 100644
--- a/test/signal-logging.c
+++ b/test/signal-logging.c
@@ -201,6 +201,11 @@ static void logging_format(void)
     read_log_msg(logmsg);
     assert(strcmp(logmsg, "(EE) test %\n") == 0);
 
+    /* character */
+    LogMessageVerbSigSafe(X_ERROR, -1, "test %c\n", 'a');
+    read_log_msg(logmsg);
+    assert(strcmp(logmsg, "(EE) test a\n") == 0);
+
     /* string substitution */
     LogMessageVerbSigSafe(X_ERROR, -1, "%s\n", "substituted string");
     read_log_msg(logmsg);
commit 58ef34ee6d0f68aa28f6f1a26e56f49ec85ed9bf
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Feb 14 16:13:22 2013 +1000

    os: support %% in pnprintf
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/os/log.c b/os/log.c
index df025fb..e4e9e8b 100644
--- a/os/log.c
+++ b/os/log.c
@@ -450,6 +450,9 @@ pnprintf(char *string, size_t size, const char *f, va_list args)
                     string[s_idx++] = number[i];
             }
             break;
+        case '%':
+            string[s_idx++] = '%';
+            break;
         default:
             va_arg(args, char*);
             string[s_idx++] = '%';
diff --git a/test/signal-logging.c b/test/signal-logging.c
index 9038cf8..65baa45 100644
--- a/test/signal-logging.c
+++ b/test/signal-logging.c
@@ -196,6 +196,11 @@ static void logging_format(void)
     read_log_msg(logmsg);
     assert(strcmp(logmsg, "(EE) %s %d %u %% %p %i\n") == 0);
 
+    /* literal % */
+    LogMessageVerbSigSafe(X_ERROR, -1, "test %%\n");
+    read_log_msg(logmsg);
+    assert(strcmp(logmsg, "(EE) test %\n") == 0);
+
     /* string substitution */
     LogMessageVerbSigSafe(X_ERROR, -1, "%s\n", "substituted string");
     read_log_msg(logmsg);
commit 5ea21560dd071ea4ab87430000d087fd5fe1f092
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Feb 14 15:34:32 2013 +1000

    os: support pnprintf length modifiers for integers
    
    Mainly for %ld, smaller than int is propagated anyway, and %lld isn't really
    used.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/os/log.c b/os/log.c
index dc6e288..df025fb 100644
--- a/os/log.c
+++ b/os/log.c
@@ -279,6 +279,55 @@ LogSetParameter(LogParameter param, int value)
     }
 }
 
+enum {
+    LMOD_LONG     = 0x1,
+    LMOD_LONGLONG = 0x2,
+    LMOD_SHORT    = 0x4,
+    LMOD_SIZET    = 0x8,
+};
+
+/**
+ * Parse non-digit length modifiers and set the corresponding flag in
+ * flags_return.
+ *
+ * @return the number of bytes parsed
+ */
+static int parse_length_modifier(const char *format, size_t len, int *flags_return)
+{
+    int idx = 0;
+    int length_modifier = 0;
+
+    while (idx < len) {
+        switch (format[idx]) {
+            case 'l':
+                BUG_RETURN_VAL(length_modifier & LMOD_SHORT, 0);
+
+                if (length_modifier & LMOD_LONG)
+                    length_modifier |= LMOD_LONGLONG;
+                else
+                    length_modifier |= LMOD_LONG;
+                break;
+            case 'h':
+                BUG_RETURN_VAL(length_modifier & (LMOD_LONG|LMOD_LONGLONG), 0);
+                length_modifier |= LMOD_SHORT;
+                /* gcc says 'short int' is promoted to 'int' when
+                 * passed through '...', so ignored during
+                 * processing */
+                break;
+            case 'z':
+                length_modifier |= LMOD_SIZET;
+                break;
+            default:
+                goto out;
+        }
+        idx++;
+    }
+
+out:
+    *flags_return = length_modifier;
+    return idx;
+}
+
 /**
  * Signal-safe snprintf, with some limitations over snprintf. Be careful
  * which directives you use.
@@ -297,6 +346,7 @@ pnprintf(char *string, size_t size, const char *f, va_list args)
     int64_t si;
 
     for (; f_idx < f_len && s_idx < size - 1; f_idx++) {
+        int length_modifier = 0;
         if (f[f_idx] != '%') {
             string[s_idx++] = f[f_idx];
             continue;
@@ -304,10 +354,18 @@ pnprintf(char *string, size_t size, const char *f, va_list args)
 
         f_idx++;
 
-        /* silently swallow length modifiers */
+        /* silently swallow digit length modifiers */
         while (f_idx < f_len && ((f[f_idx] >= '0' && f[f_idx] <= '9') || f[f_idx] == '.'))
             f_idx++;
 
+        /* non-digit length modifiers */
+        if (f_idx < f_len) {
+            int parsed_bytes = parse_length_modifier(&f[f_idx], f_len - f_idx, &length_modifier);
+            if (parsed_bytes < 0)
+                return 0;
+            f_idx += parsed_bytes;
+        }
+
         if (f_idx >= f_len)
             break;
 
@@ -321,7 +379,15 @@ pnprintf(char *string, size_t size, const char *f, va_list args)
             break;
 
         case 'u':
-            ui = va_arg(args, unsigned);
+            if (length_modifier & LMOD_LONGLONG)
+                ui = va_arg(args, unsigned long long);
+            else if (length_modifier & LMOD_LONG)
+                ui = va_arg(args, unsigned long);
+            else if (length_modifier & LMOD_SIZET)
+                ui = va_arg(args, size_t);
+            else
+                ui = va_arg(args, unsigned);
+
             FormatUInt64(ui, number);
             p_len = strlen_sigsafe(number);
 
@@ -330,7 +396,15 @@ pnprintf(char *string, size_t size, const char *f, va_list args)
             break;
         case 'i':
         case 'd':
-            si = va_arg(args, int);
+            if (length_modifier & LMOD_LONGLONG)
+                si = va_arg(args, long long);
+            else if (length_modifier & LMOD_LONG)
+                si = va_arg(args, long);
+            else if (length_modifier & LMOD_SIZET)
+                si = va_arg(args, ssize_t);
+            else
+                si = va_arg(args, int);
+
             FormatInt64(si, number);
             p_len = strlen_sigsafe(number);
 
@@ -351,7 +425,15 @@ pnprintf(char *string, size_t size, const char *f, va_list args)
             break;
 
         case 'x':
-            ui = va_arg(args, unsigned);
+            if (length_modifier & LMOD_LONGLONG)
+                ui = va_arg(args, unsigned long long);
+            else if (length_modifier & LMOD_LONG)
+                ui = va_arg(args, unsigned long);
+            else if (length_modifier & LMOD_SIZET)
+                ui = va_arg(args, size_t);
+            else
+                ui = va_arg(args, unsigned);
+
             FormatUInt64Hex(ui, number);
             p_len = strlen_sigsafe(number);
 
diff --git a/test/signal-logging.c b/test/signal-logging.c
index e0eb810..9038cf8 100644
--- a/test/signal-logging.c
+++ b/test/signal-logging.c
@@ -158,6 +158,8 @@ static void logging_format(void)
     char buf[1024];
     int i;
     unsigned int ui;
+    long li;
+    unsigned long lui;
     FILE *f;
     char read_buf[2048];
     char *logmsg;
@@ -207,6 +209,14 @@ static void logging_format(void)
     LogMessageVerbSigSafe(X_ERROR, -1, "\n");
     fseek(f, 0, SEEK_END);
 
+#warning Ignore compiler warning below "unknown conversion type character".  This is intentional.
+    /* %hld is bogus */
+    LogMessageVerbSigSafe(X_ERROR, -1, "%hld\n", 4);
+    read_log_msg(logmsg);
+    assert(strstr(logmsg, "BUG") != NULL);
+    LogMessageVerbSigSafe(X_ERROR, -1, "\n");
+    fseek(f, 0, SEEK_END);
+
     /* number substitution */
     ui = 0;
     do {
@@ -215,12 +225,47 @@ static void logging_format(void)
         LogMessageVerbSigSafe(X_ERROR, -1, "%u\n", ui);
         read_log_msg(logmsg);
         assert(strcmp(logmsg, expected) == 0);
+
+        sprintf(expected, "(EE) %x\n", ui);
+        LogMessageVerbSigSafe(X_ERROR, -1, "%x\n", ui);
+        read_log_msg(logmsg);
+        assert(strcmp(logmsg, expected) == 0);
+
         if (ui == 0)
             ui = 1;
         else
             ui <<= 1;
     } while(ui);
 
+    lui = 0;
+    do {
+        char expected[30];
+        sprintf(expected, "(EE) %lu\n", lui);
+        LogMessageVerbSigSafe(X_ERROR, -1, "%lu\n", lui);
+        read_log_msg(logmsg);
+
+        sprintf(expected, "(EE) %lld\n", (unsigned long long)ui);
+        LogMessageVerbSigSafe(X_ERROR, -1, "%lld\n", (unsigned long long)ui);
+        read_log_msg(logmsg);
+        assert(strcmp(logmsg, expected) == 0);
+
+        sprintf(expected, "(EE) %lx\n", lui);
+        printf("%s\n", expected);
+        LogMessageVerbSigSafe(X_ERROR, -1, "%lx\n", lui);
+        read_log_msg(logmsg);
+        assert(strcmp(logmsg, expected) == 0);
+
+        sprintf(expected, "(EE) %llx\n", (unsigned long long)ui);
+        LogMessageVerbSigSafe(X_ERROR, -1, "%llx\n", (unsigned long long)ui);
+        read_log_msg(logmsg);
+        assert(strcmp(logmsg, expected) == 0);
+
+        if (lui == 0)
+            lui = 1;
+        else
+            lui <<= 1;
+    } while(lui);
+
     /* signed number substitution */
     i = 0;
     do {
@@ -230,7 +275,6 @@ static void logging_format(void)
         read_log_msg(logmsg);
         assert(strcmp(logmsg, expected) == 0);
 
-
         sprintf(expected, "(EE) %d\n", i | INT_MIN);
         LogMessageVerbSigSafe(X_ERROR, -1, "%d\n", i | INT_MIN);
         read_log_msg(logmsg);
@@ -242,19 +286,35 @@ static void logging_format(void)
             i <<= 1;
     } while(i > INT_MIN);
 
-    /* hex number substitution */
-    ui = 0;
+    li = 0;
     do {
         char expected[30];
-        sprintf(expected, "(EE) %x\n", ui);
-        LogMessageVerbSigSafe(X_ERROR, -1, "%x\n", ui);
+        sprintf(expected, "(EE) %ld\n", li);
+        LogMessageVerbSigSafe(X_ERROR, -1, "%ld\n", li);
         read_log_msg(logmsg);
         assert(strcmp(logmsg, expected) == 0);
-        if (ui == 0)
-            ui = 1;
+
+        sprintf(expected, "(EE) %ld\n", li | LONG_MIN);
+        LogMessageVerbSigSafe(X_ERROR, -1, "%ld\n", li | LONG_MIN);
+        read_log_msg(logmsg);
+        assert(strcmp(logmsg, expected) == 0);
+
+        sprintf(expected, "(EE) %lld\n", (long long)li);
+        LogMessageVerbSigSafe(X_ERROR, -1, "%lld\n", (long long)li);
+        read_log_msg(logmsg);
+        assert(strcmp(logmsg, expected) == 0);
+
+        sprintf(expected, "(EE) %lld\n", (long long)(li | LONG_MIN));
+        LogMessageVerbSigSafe(X_ERROR, -1, "%lld\n", (long long)(li | LONG_MIN));
+        read_log_msg(logmsg);
+        assert(strcmp(logmsg, expected) == 0);
+
+        if (li == 0)
+            li = 1;
         else
-            ui <<= 1;
-    } while(ui);
+            li <<= 1;
+    } while(li > LONG_MIN);
+
 
     /* pointer substitution */
     /* we print a null-pointer differently to printf */
commit d3d4af5f9e505d444b6c82c6ea238206433fd24b
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Feb 27 18:59:45 2012 +1000

    dix: reset the registry before quitting
    
    Heaps of these:
    ==2042== 15,360 bytes in 120 blocks are still reachable in loss record 94 of
    97
    ==2042==    at 0x4C2A4CD: malloc (vg_replace_malloc.c:236)
    ==2042==    by 0x4C2A657: realloc (vg_replace_malloc.c:525)
    ==2042==    by 0x45FB91: double_size (registry.c:65)
    ==2042==    by 0x45FC97: RegisterRequestName (registry.c:85)
    ==2042==    by 0x460095: RegisterExtensionNames (registry.c:179)
    ==2042==    by 0x460729: dixResetRegistry (registry.c:334)
    ==2042==    by 0x5AC992: main (main.c:201)
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/dix/main.c b/dix/main.c
index c46e40a..1fa0504 100644
--- a/dix/main.c
+++ b/dix/main.c
@@ -358,6 +358,8 @@ main(int argc, char *argv[], char *envp[])
         dixFreePrivates(serverClient->devPrivates, PRIVATE_CLIENT);
         serverClient->devPrivates = NULL;
 
+	dixFreeRegistry();
+
         FreeFonts();
 
         FreeAllAtoms();
diff --git a/dix/registry.c b/dix/registry.c
index 5bad0fd..82a3340 100644
--- a/dix/registry.c
+++ b/dix/registry.c
@@ -280,14 +280,9 @@ LookupResourceName(RESTYPE resource)
     return resources[resource] ? resources[resource] : XREGISTRY_UNKNOWN;
 }
 
-/*
- * Setup and teardown
- */
 void
-dixResetRegistry(void)
+dixFreeRegistry(void)
 {
-    ExtensionEntry extEntry = { .name = CORE };
-
     /* Free all memory */
     while (nmajor--) {
         while (nminor[nmajor])
@@ -315,9 +310,23 @@ dixResetRegistry(void)
 
     nmajor = nevent = nerror = nresource = 0;
 
+    if (fh) {
+	fclose(fh);
+        fh = NULL;
+    }
+}
+
+/*
+ * Setup and teardown
+ */
+void
+dixResetRegistry(void)
+{
+    ExtensionEntry extEntry = { .name = CORE };
+
+    dixFreeRegistry();
+
     /* Open the protocol file */
-    if (fh)
-        fclose(fh);
     fh = fopen(FILENAME, "r");
     if (!fh)
         LogMessage(X_WARNING,
diff --git a/include/registry.h b/include/registry.h
index f471b89..e298ab6 100644
--- a/include/registry.h
+++ b/include/registry.h
@@ -44,6 +44,7 @@ extern _X_EXPORT const char *LookupResourceName(RESTYPE rtype);
  * Setup and teardown
  */
 extern _X_EXPORT void dixResetRegistry(void);
+extern _X_EXPORT void dixFreeRegistry(void);
 
 #else                           /* XREGISTRY */
 
commit 6f44d672aa34d343f63f0ea81ad58154a66b57ec
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Feb 27 17:17:41 2012 +1000

    xkb: free XkbRulesUsed and XkbRulesDflt on extension cleanup
    
    ==2547== 1 bytes in 1 blocks are still reachable in loss record 1 of 111
    ==2547==    at 0x4C2A4CD: malloc (vg_replace_malloc.c:236)
    ==2547==    by 0x64D1551: strdup (strdup.c:43)
    ==2547==    by 0x4802FB: Xstrdup (utils.c:1113)
    ==2547==    by 0x585B6C: XkbSetRulesUsed (xkbInit.c:219)
    ==2547==    by 0x58700F: InitKeyboardDeviceStruct (xkbInit.c:595)
    ==2547==    by 0x419FA3: vfbKeybdProc (InitInput.c:74)
    ==2547==    by 0x425A3D: ActivateDevice (devices.c:540)
    ==2547==    by 0x425F65: InitAndStartDevices (devices.c:713)
    ==2547==    by 0x5ACA57: main (main.c:259)
    
    and a few more of the above.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/dix/devices.c b/dix/devices.c
index fa94a94..0c718d2 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -1052,6 +1052,7 @@ CloseDownDevices(void)
     inputInfo.pointer = NULL;
 
     XkbDeleteRulesDflts();
+    XkbDeleteRulesUsed();
 
     OsReleaseSignals();
 }
diff --git a/include/xkbsrv.h b/include/xkbsrv.h
index 45e2e8c..346ebcc 100644
--- a/include/xkbsrv.h
+++ b/include/xkbsrv.h
@@ -751,6 +751,9 @@ extern _X_EXPORT void XkbSetRulesDflts(XkbRMLVOSet *    /* rmlvo */
 extern _X_EXPORT void XkbDeleteRulesDflts(void
     );
 
+extern _X_EXPORT void XkbDeleteRulesUsed(void
+    );
+
 extern _X_EXPORT int SProcXkbDispatch(ClientPtr /* client */
     );
 
diff --git a/xkb/xkbInit.c b/xkb/xkbInit.c
index 4e8e267..244c353 100644
--- a/xkb/xkbInit.c
+++ b/xkb/xkbInit.c
@@ -251,6 +251,21 @@ XkbSetRulesDflts(XkbRMLVOSet * rmlvo)
 }
 
 void
+XkbDeleteRulesUsed(void)
+{
+    free(XkbRulesUsed);
+    XkbRulesUsed = NULL;
+    free(XkbModelUsed);
+    XkbModelUsed = NULL;
+    free(XkbLayoutUsed);
+    XkbLayoutUsed = NULL;
+    free(XkbVariantUsed);
+    XkbVariantUsed = NULL;
+    free(XkbOptionsUsed);
+    XkbOptionsUsed = NULL;
+}
+
+void
 XkbDeleteRulesDflts(void)
 {
     free(XkbRulesDflt);
commit 623981ddaeb8836f3b0939e527c0e943f9c4e974
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Feb 1 09:06:20 2013 +1000

    If neither HAL nor udev backends are enabled, warn the user
    
    If both are missing,  input device hotplugging will not work out of the box.
    While we still have a DBus-API or the user may want to set AAD off all the
    time, the most likely source of this is misconfiguration (i.e. lack of the
    udev/hal devel packages).
    
    Message printed last to make it more obvious to the user.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/configure.ac b/configure.ac
index 0b72860..89a7a9d 100644
--- a/configure.ac
+++ b/configure.ac
@@ -2223,6 +2223,14 @@ AC_SUBST([prefix])
 
 AC_CONFIG_COMMANDS([sdksyms], [touch hw/xfree86/sdksyms.dep])
 
+if test "x$CONFIG_HAL" = xno && test "x$CONFIG_UDEV" = xno; then
+    AC_WARN([
+             ***********************************************
+             Neither HAL nor udev backend will be enabled.
+             Input device hotplugging will not be available!
+             ***********************************************])
+fi
+
 AC_OUTPUT([
 Makefile
 glx/Makefile
commit dce40e2266200421647044ec7e856656d2ef952d
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Tue Feb 26 12:34:21 2013 +1000

    Xi: always return BadMatch for XTest devices ChangeDeviceControl requests
    
    The only controls that still do something are DEVICE_RESOLUTION and
    DEVICE_ENABLE.
    
    XTest devices have no resolution to change, and they cannot be disabled. So
    skip the lot, and prevent a crash in the DDX when it's trying to
    de-reference pInfo->control_proc on device with no pInfo struct.
    
    Likewise, don't allow setting device mode or the valuators.
    XTest pointers are always relative, they don't have a mode.
    
    Test cases:
    xts5/XI/ChangeDeviceControl (1/10)
    xts5/XI/SetDeviceValuators (1/6)
    and a few others
    
    Reported-by: Knut Petersen <Knut_Petersen at t-online.de>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/Xi/chgdctl.c b/Xi/chgdctl.c
index 31d3a57..d078aa2 100644
--- a/Xi/chgdctl.c
+++ b/Xi/chgdctl.c
@@ -122,6 +122,12 @@ ProcXChangeDeviceControl(ClientPtr client)
     if (ret != Success)
         goto out;
 
+    /* XTest devices are special, none of the below apply to them anyway */
+    if (IsXTestDevice(dev, NULL)) {
+        ret = BadMatch;
+        goto out;
+    }
+
     rep = (xChangeDeviceControlReply) {
         .repType = X_Reply,
         .RepType = X_ChangeDeviceControl,
diff --git a/Xi/setdval.c b/Xi/setdval.c
index 4c9c99f..463e4f3 100644
--- a/Xi/setdval.c
+++ b/Xi/setdval.c
@@ -110,6 +110,9 @@ ProcXSetDeviceValuators(ClientPtr client)
     if (dev->valuator == NULL)
         return BadMatch;
 
+    if (IsXTestDevice(dev, NULL))
+        return BadMatch;
+
     if (stuff->first_valuator + stuff->num_valuators > dev->valuator->numAxes)
         return BadValue;
 
diff --git a/Xi/setmode.c b/Xi/setmode.c
index 5356552..5ed0913 100644
--- a/Xi/setmode.c
+++ b/Xi/setmode.c
@@ -104,6 +104,10 @@ ProcXSetDeviceMode(ClientPtr client)
         return rc;
     if (dev->valuator == NULL)
         return BadMatch;
+
+    if (IsXTestDevice(dev, NULL))
+        return BadMatch;
+
     if ((dev->deviceGrab.grab) && !SameClient(dev->deviceGrab.grab, client))
         rep.status = AlreadyGrabbed;
     else
commit 23d1bc69f305edd5a6e2cfec3dfc84befda0881c
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Mar 14 11:07:57 2013 +1000

    dix: send the current axis value in DeviceChangedEvents (#62321)
    
    X.Org Bug 62321 <http://bugs.freedesktop.org/show_bug.cgi?id=62321>
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/dix/eventconvert.c b/dix/eventconvert.c
index ebc52c3..f7ecdba 100644
--- a/dix/eventconvert.c
+++ b/dix/eventconvert.c
@@ -501,9 +501,7 @@ appendValuatorInfo(DeviceChangedEvent *dce, xXIValuatorInfo * info,
     info->min.frac = 0;
     info->max.integral = dce->valuators[axisnumber].max;
     info->max.frac = 0;
-    /* FIXME: value */
-    info->value.integral = 0;
-    info->value.frac = 0;
+    info->value = double_to_fp3232(dce->valuators[axisnumber].value);
     info->resolution = dce->valuators[axisnumber].resolution;
     info->number = axisnumber;
     info->mode = dce->valuators[axisnumber].mode;
diff --git a/dix/getevents.c b/dix/getevents.c
index a4f192c..241c7ec 100644
--- a/dix/getevents.c
+++ b/dix/getevents.c
@@ -277,6 +277,7 @@ CreateClassesChangedEvent(InternalEvent *event,
             dce->valuators[i].mode = slave->valuator->axes[i].mode;
             dce->valuators[i].name = slave->valuator->axes[i].label;
             dce->valuators[i].scroll = slave->valuator->axes[i].scroll;
+            dce->valuators[i].value = slave->valuator->axisVal[i];
         }
     }
     if (slave->key) {
diff --git a/include/eventstr.h b/include/eventstr.h
index 38fab4f..5c1adc4 100644
--- a/include/eventstr.h
+++ b/include/eventstr.h
@@ -175,6 +175,7 @@ struct _DeviceChangedEvent {
     struct {
         uint32_t min;           /**< Minimum value */
         uint32_t max;           /**< Maximum value */
+        double value;           /**< Current value */;
         /* FIXME: frac parts of min/max */
         uint32_t resolution;    /**< Resolution counts/m */
         uint8_t mode;           /**< Relative or Absolute */
commit 27b11f5c19d67e2f6784d86cb7df86bbab3b58bb
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Feb 15 11:19:10 2013 +1000

    Xi: fix comment - XI2 grabs aren't keysym grabs
    
    Comment dates back to a pre-release version of XI2 that supported keysym
    grabs. That never made it into a release, it was ditched before.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 576f0fe..7eb71ee 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -2222,8 +2222,7 @@ GrabButton(ClientPtr client, DeviceIntPtr dev, DeviceIntPtr modifier_device,
 }
 
 /**
- * Grab the given key. If grabtype is XI, the key is a keycode. If
- * grabtype is XI2, the key is a keysym.
+ * Grab the given key.
  */
 int
 GrabKey(ClientPtr client, DeviceIntPtr dev, DeviceIntPtr modifier_device,
commit 2746c681639f9512e6e45fb8d0151b996b6aff7f
Merge: 1e6cf8e 9878e09
Author: Keith Packard <keithp at keithp.com>
Date:   Mon May 6 10:52:40 2013 -0700

    Merge remote-tracking branch 'alanc/master'

commit 1e6cf8ec20d07b73a11116564aba71b4e4291dcd
Merge: dbfeaf7 5860408a
Author: Keith Packard <keithp at keithp.com>
Date:   Mon May 6 10:20:21 2013 -0700

    Merge remote-tracking branch 'jturney/unused-but-set-variable-warning-fix'

commit dbfeaf70623a83e1a3f3255c94d52e0e04702837
Author: Aaron Plattner <aplattner at nvidia.com>
Date:   Tue Apr 30 14:30:18 2013 -0700

    xfree86: don't enable anything in xf86InitialConfiguration for GPU screens
    
    There's no point in turning on outputs connected to GPU screens during initial
    configuration.  Not only does this cause them to just display black, it also
    confuses clients when these screens are attached to a master screen and RandR
    reports that the outputs are already on.
    
    Also, don't print the warning about no outputs being found on GPU screens,
    since that's expected.
    
    Signed-off-by: Aaron Plattner <aplattner at nvidia.com>
    Reviewed-by: Dave Airlie <airlied at gmail.com>

diff --git a/hw/xfree86/modes/xf86Crtc.c b/hw/xfree86/modes/xf86Crtc.c
index 4a490c6..35845e8 100644
--- a/hw/xfree86/modes/xf86Crtc.c
+++ b/hw/xfree86/modes/xf86Crtc.c
@@ -1997,6 +1997,14 @@ xf86CollectEnabledOutputs(ScrnInfoPtr scrn, xf86CrtcConfigPtr config,
     Bool any_enabled = FALSE;
     int o;
 
+    /*
+     * Don't bother enabling outputs on GPU screens: a client needs to attach
+     * it to a source provider before setting a mode that scans out a shared
+     * pixmap.
+     */
+    if (scrn->is_gpu)
+        return FALSE;
+
     for (o = 0; o < config->num_output; o++)
         any_enabled |= enabled[o] = xf86OutputEnabled(config->output[o], TRUE);
 
@@ -2466,9 +2474,11 @@ xf86InitialConfiguration(ScrnInfoPtr scrn, Bool canGrow)
 
     ret = xf86CollectEnabledOutputs(scrn, config, enabled);
     if (ret == FALSE && canGrow) {
-        xf86DrvMsg(i, X_WARNING,
-                   "Unable to find connected outputs - setting %dx%d initial framebuffer\n",
-                   NO_OUTPUT_DEFAULT_WIDTH, NO_OUTPUT_DEFAULT_HEIGHT);
+        if (!scrn->is_gpu)
+            xf86DrvMsg(i, X_WARNING,
+		       "Unable to find connected outputs - setting %dx%d "
+                       "initial framebuffer\n",
+                       NO_OUTPUT_DEFAULT_WIDTH, NO_OUTPUT_DEFAULT_HEIGHT);
         have_outputs = FALSE;
     }
     else {
commit 5860408a19d956f8cebb7ae39cfdbfcebd5e6360
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Wed Apr 3 18:43:26 2013 +0100

    hw/xwin: Fix unused-but-set-variable warning in ProcWindowsWMFrameGetRect()
    
    /jhbuild/checkout/xorg/xserver/hw/xwin/winwindowswm.c: In function ‘ProcWindowsWMFrameGetRect’:
    /jhbuild/checkout/xorg/xserver/hw/xwin/winwindowswm.c:322:12: error: variable ‘ir’ set but not used [-Werror=unused-but-set-variable]
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/winwindowswm.c b/hw/xwin/winwindowswm.c
index fbd41aa..6e9d63c 100644
--- a/hw/xwin/winwindowswm.c
+++ b/hw/xwin/winwindowswm.c
@@ -66,18 +66,6 @@ typedef struct _WMEvent {
     unsigned int mask;
 } WMEventRec;
 
-static inline BoxRec
-make_box(int x, int y, int w, int h)
-{
-    BoxRec r;
-
-    r.x1 = x;
-    r.y1 = y;
-    r.x2 = x + w;
-    r.y2 = y + h;
-    return r;
-}
-
 static int
 ProcWindowsWMQueryVersion(ClientPtr client)
 {
@@ -319,7 +307,6 @@ static int
 ProcWindowsWMFrameGetRect(ClientPtr client)
 {
     xWindowsWMFrameGetRectReply rep;
-    BoxRec ir;
     RECT rcNew;
 
     REQUEST(xWindowsWMFrameGetRectReq);
@@ -334,8 +321,6 @@ ProcWindowsWMFrameGetRect(ClientPtr client)
     rep.length = 0;
     rep.sequenceNumber = client->sequence;
 
-    ir = make_box(stuff->ix, stuff->iy, stuff->iw, stuff->ih);
-
     if (stuff->frame_rect != 0) {
         ErrorF("ProcWindowsWMFrameGetRect - stuff->frame_rect != 0\n");
         return BadValue;
commit bcfd523c150b34e9304d174ba812160c611f270d
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Wed Apr 3 18:34:38 2013 +0100

    hw/xwin: Fix unused-but-set-variable warning in winMWExtWMUpdateWindowDecoration()
    
    /jhbuild/checkout/xorg/xserver/hw/xwin/winwin32rootlesswindow.c: In function ‘winMWExtWMUpdateWindowDecoration’:
    /jhbuild/checkout/xorg/xserver/hw/xwin/winwin32rootlesswindow.c:189:11: error: variable ‘dwStyle’ set but not used [-Werror=unused-but-set-variable]
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/winwin32rootlesswindow.c b/hw/xwin/winwin32rootlesswindow.c
index f2d68cb..ce615e6 100644
--- a/hw/xwin/winwin32rootlesswindow.c
+++ b/hw/xwin/winwin32rootlesswindow.c
@@ -186,7 +186,6 @@ winMWExtWMUpdateWindowDecoration(win32RootlessWindowPtr pRLWinPriv,
 {
     Bool fDecorate = FALSE;
     DWORD dwExStyle = 0;
-    DWORD dwStyle = 0;
     WINDOWPLACEMENT wndPlace;
     UINT showCmd = 0;
 
@@ -217,9 +216,8 @@ winMWExtWMUpdateWindowDecoration(win32RootlessWindowPtr pRLWinPriv,
     winDebug("winMWExtWMUpdateWindowDecoration %08x %s\n",
              (int) pRLWinPriv, fDecorate ? "Decorate" : "Bare");
 
-    /* Get the standard and extended window style information */
+    /* Get the extended window style information */
     dwExStyle = GetWindowLongPtr(pRLWinPriv->hWnd, GWL_EXSTYLE);
-    dwStyle = GetWindowLongPtr(pRLWinPriv->hWnd, GWL_STYLE);
 
     if (fDecorate) {
         RECT rcNew;
commit fbf819c24dc080f166cff29bf46b0feb604c6b8c
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Wed Apr 3 16:40:35 2013 +0100

    hw/xwin: Fix unused-but-set-variable warning in winHotKeyAltTabPrimaryDD()
    
    /jhbuild/checkout/xorg/xserver/hw/xwin/winpfbdd.c: In function ‘winHotKeyAltTabPrimaryDD’:
    /jhbuild/checkout/xorg/xserver/hw/xwin/winpfbdd.c:518:20: error: variable ‘rcSrc’ set but not used [-Werror=unused-but-set-variable]
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/winpfbdd.c b/hw/xwin/winpfbdd.c
index ee6ea72..f870007 100644
--- a/hw/xwin/winpfbdd.c
+++ b/hw/xwin/winpfbdd.c
@@ -514,8 +514,6 @@ static Bool
 winHotKeyAltTabPrimaryDD(ScreenPtr pScreen)
 {
     winScreenPriv(pScreen);
-    winScreenInfo *pScreenInfo = pScreenPriv->pScreenInfo;
-    RECT rcClient, rcSrc;
     HRESULT ddrval = DD_OK;
 
     ErrorF("\nwinHotKeyAltTabPrimaryDD\n\n");
@@ -527,11 +525,6 @@ winHotKeyAltTabPrimaryDD(ScreenPtr pScreen)
     if (pScreenPriv->pddsPrimary == NULL || pScreenPriv->pddsOffscreen == NULL)
         return FALSE;
 
-    /* Get client area in screen coords */
-    GetClientRect(pScreenPriv->hwndScreen, &rcClient);
-    MapWindowPoints(pScreenPriv->hwndScreen,
-                    HWND_DESKTOP, (LPPOINT) &rcClient, 2);
-
     /* Did we loose the primary surface? */
     ddrval = IDirectDrawSurface2_IsLost(pScreenPriv->pddsPrimary);
     if (ddrval == DD_OK) {
@@ -541,12 +534,6 @@ winHotKeyAltTabPrimaryDD(ScreenPtr pScreen)
                        "surface\n");
     }
 
-    /* Setup a source rectangle */
-    rcSrc.left = 0;
-    rcSrc.top = 0;
-    rcSrc.right = pScreenInfo->dwWidth;
-    rcSrc.bottom = pScreenInfo->dwHeight;
-
     /* Blit the primary surface to the offscreen surface */
     ddrval = IDirectDrawSurface2_Blt(pScreenPriv->pddsOffscreen, NULL,  /* should be rcDest */
                                      pScreenPriv->pddsPrimary,
commit 7dae1e59ce6077f475c04a41fa00096a74114064
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Wed Apr 3 16:33:39 2013 +0100

    hw/xwin: Fix unused-but-set-variable warning in winMinimizeWindow() when built !XWIN_MULTIWINDOWEXTWM
    
    /jhbuild/checkout/xorg/xserver/hw/xwin/winmultiwindowwindow.c: In function ‘winMinimizeWindow’:
    /jhbuild/checkout/xorg/xserver/hw/xwin/winmultiwindowwindow.c:813:20: error: variable ‘pScreenInfo’ set but not used [-Werror=unused-but-set-variable]
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/winmultiwindowwindow.c b/hw/xwin/winmultiwindowwindow.c
index c0c7db2..0948156 100644
--- a/hw/xwin/winmultiwindowwindow.c
+++ b/hw/xwin/winmultiwindowwindow.c
@@ -808,7 +808,6 @@ winMinimizeWindow(Window id)
     HWND hWnd;
     ScreenPtr pScreen = NULL;
     winPrivScreenPtr pScreenPriv = NULL;
-    winScreenInfo *pScreenInfo = NULL;
 
 #if CYGWINDOWING_DEBUG
     ErrorF("winMinimizeWindow\n");
@@ -824,11 +823,9 @@ winMinimizeWindow(Window id)
     pScreen = pWin->drawable.pScreen;
     if (pScreen)
         pScreenPriv = winGetScreenPriv(pScreen);
-    if (pScreenPriv)
-        pScreenInfo = pScreenPriv->pScreenInfo;
 
 #ifdef XWIN_MULTIWINDOWEXTWM
-    if (pScreenPriv && pScreenInfo->fInternalWM) {
+    if (pScreenPriv && pScreenPriv->pScreenInfo->fInternalWM) {
         pRLWinPriv =
             (win32RootlessWindowPtr) RootlessFrameForWindow(pWin, FALSE);
         hWnd = pRLWinPriv->hWnd;
commit b284666f09b77f9c2f048fee22015a353152a57f
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Wed Apr 3 16:27:45 2013 +0100

    hw/xwin: Fix unused-but-set-variable warning in winClipboardProc()
    
    /jhbuild/checkout/xorg/xserver/hw/xwin/winclipboardthread.c: In function ‘winClipboardProc’:
    /jhbuild/checkout/xorg/xserver/hw/xwin/winclipboardthread.c:88:25: error: variable ‘atomClipboardManager’ set but not used [-Werror=unused-but-set-variable]
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/winclipboardthread.c b/hw/xwin/winclipboardthread.c
index c8508a9..6da9f3b 100644
--- a/hw/xwin/winclipboardthread.c
+++ b/hw/xwin/winclipboardthread.c
@@ -83,7 +83,7 @@ static int
 void *
 winClipboardProc(void *pvNotUsed)
 {
-    Atom atomClipboard, atomClipboardManager;
+    Atom atomClipboard;
     int iReturn;
     HWND hwnd = NULL;
     int iConnectionNumber = 0;
@@ -206,9 +206,8 @@ winClipboardProc(void *pvNotUsed)
     iMaxDescriptor = iConnectionNumber + 1;
 #endif
 
-    /* Create atoms */
+    /* Create atom */
     atomClipboard = XInternAtom(pDisplay, "CLIPBOARD", False);
-    atomClipboardManager = XInternAtom(pDisplay, "CLIPBOARD_MANAGER", False);
 
     /* Create a messaging window */
     iWindow = XCreateSimpleWindow(pDisplay,
commit d414a09bb7f8d4440b36cbc6f0b4ca0eaefe5cbf
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Wed Apr 3 16:25:54 2013 +0100

    hw/xwin: Fix unused-but-set-variable warning in winWindowProc()
    
    /jhbuild/checkout/xorg/xserver/hw/xwin/winwndproc.c: In function ‘winWindowProc’:
    /jhbuild/checkout/xorg/xserver/hw/xwin/winwndproc.c:65:22: error: variable ‘s_hInstance’ set but not used [-Werror=unused-but-set-variable]
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/winwndproc.c b/hw/xwin/winwndproc.c
index 7ba0280..c7509ea 100644
--- a/hw/xwin/winwndproc.c
+++ b/hw/xwin/winwndproc.c
@@ -62,7 +62,6 @@ winWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
     static winScreenInfo *s_pScreenInfo = NULL;
     static ScreenPtr s_pScreen = NULL;
     static HWND s_hwndLastPrivates = NULL;
-    static HINSTANCE s_hInstance;
     static Bool s_fTracking = FALSE;
     static unsigned long s_ulServerGeneration = 0;
     static UINT s_uTaskbarRestart = 0;
@@ -117,7 +116,6 @@ winWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
          * areas of our display window.
          */
         s_pScreenPriv = ((LPCREATESTRUCT) lParam)->lpCreateParams;
-        s_hInstance = ((LPCREATESTRUCT) lParam)->hInstance;
         s_pScreenInfo = s_pScreenPriv->pScreenInfo;
         s_pScreen = s_pScreenInfo->pScreen;
         s_hwndLastPrivates = hwnd;
commit 7726102671690eb28138d032c8398ac903b97606
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Wed Apr 3 16:24:08 2013 +0100

    hw/xwin: Fix unused-but-set-variable warning in winCopyWindowNativeGDI()
    
    /jhbuild/checkout/xorg/xserver/hw/xwin/winwindow.c: In function ‘winCopyWindowNativeGDI’:
    /jhbuild/checkout/xorg/xserver/hw/xwin/winwindow.c:131:15: error: variable ‘pwinRoot’ set but not used [-Werror=unused-but-set-variable]
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/winwindow.c b/hw/xwin/winwindow.c
index ab6d8de..029bd85 100644
--- a/hw/xwin/winwindow.c
+++ b/hw/xwin/winwindow.c
@@ -128,7 +128,6 @@ winCopyWindowNativeGDI(WindowPtr pWin, DDXPointRec ptOldOrg, RegionPtr prgnSrc)
     BoxPtr pBox;
     int dx, dy;
     int i, nbox;
-    WindowPtr pwinRoot;
     BoxPtr pBoxDst;
     ScreenPtr pScreen = pWin->drawable.pScreen;
 
@@ -138,9 +137,6 @@ winCopyWindowNativeGDI(WindowPtr pWin, DDXPointRec ptOldOrg, RegionPtr prgnSrc)
     ErrorF("winCopyWindow\n");
 #endif
 
-    /* Get a pointer to the root window */
-    pwinRoot = pWin->drawable.pScreen->root;
-
     /* Create a region for the destination */
     prgnDst = RegionCreate(NULL, 1);
 
commit b9a2566a6e2f56a0335cd4a089b2066c06a67455
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Wed Apr 3 16:50:38 2013 +0100

    hw/xwin: Fix unused-but-set-variable warning in winFinishScreenInitFB()
    
    /jhbuild/checkout/xorg/xserver/hw/xwin/winscrinit.c:264:11: error: variable ‘pbits’ set but not used [-Werror=unused-but-set-variable]
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/winscrinit.c b/hw/xwin/winscrinit.c
index e776bdb..5623b88 100644
--- a/hw/xwin/winscrinit.c
+++ b/hw/xwin/winscrinit.c
@@ -259,7 +259,6 @@ winFinishScreenInitFB(int i, ScreenPtr pScreen, int argc, char **argv)
     winScreenPriv(pScreen);
     winScreenInfo *pScreenInfo = pScreenPriv->pScreenInfo;
     VisualPtr pVisual = NULL;
-    char *pbits = NULL;
 
 #if defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW)
     int iReturn;
@@ -293,9 +292,6 @@ winFinishScreenInitFB(int i, ScreenPtr pScreen, int argc, char **argv)
         return FALSE;
     }
 
-    /* Setup a local variable to point to the framebuffer */
-    pbits = pScreenInfo->pfb;
-
     /* Apparently we need this for the render extension */
     miSetPixmapDepths();
 
commit c97fbd39adbc0a8cb8537f40b12c091aee29221a
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Wed Apr 3 16:18:27 2013 +0100

    hw/xwin: Fix unused-but-set-variable warning in winIsFakeCtrl_L()
    
    /jhbuild/checkout/xorg/xserver/hw/xwin/winkeybd.c:331:17: error: variable ‘lastMessage’ set but not used [-Werror=unused-but-set-variable]
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/winkeybd.c b/hw/xwin/winkeybd.c
index 27c114c..e412f23 100644
--- a/hw/xwin/winkeybd.c
+++ b/hw/xwin/winkeybd.c
@@ -328,7 +328,6 @@ winIsFakeCtrl_L(UINT message, WPARAM wParam, LPARAM lParam)
     Bool fReturn;
 
     static Bool lastWasControlL = FALSE;
-    static UINT lastMessage;
     static LONG lastTime;
 
     /*
@@ -352,7 +351,6 @@ winIsFakeCtrl_L(UINT message, WPARAM wParam, LPARAM lParam)
 
         if (!fReturn) {
             lastWasControlL = TRUE;
-            lastMessage = message;
             lastTime = lTime;
         }
         else {
commit cdb74fe17dcb3b5a9c61951f897deaf07f86775f
Author: Jon TURNEY <jon.turney at dronecode.org.uk>
Date:   Wed Apr 3 16:16:06 2013 +0100

    hw/xwin: Fix unused-but-set-variable warnings in windialog.c
    
    /jhbuild/checkout/xorg/xserver/hw/xwin/windialogs.c: In function ‘winChangeDepthDlgProc’:
    /jhbuild/checkout/xorg/xserver/hw/xwin/windialogs.c:432:22: error: variable ‘s_pScreen’ set but not used [-Werror=unused-but-set-variable]
    /jhbuild/checkout/xorg/xserver/hw/xwin/windialogs.c: In function ‘winAboutDlgProc’:
    /jhbuild/checkout/xorg/xserver/hw/xwin/windialogs.c:564:22: error: variable ‘s_pScreen’ set but not used [-Werror=unused-but-set-variable]
    
    Signed-off-by: Jon TURNEY <jon.turney at dronecode.org.uk>
    Reviewed-by: Colin Harrison <colin.harrison at virgin.net>

diff --git a/hw/xwin/windialogs.c b/hw/xwin/windialogs.c
index a02146e..86f332a 100644
--- a/hw/xwin/windialogs.c
+++ b/hw/xwin/windialogs.c
@@ -431,7 +431,6 @@ winChangeDepthDlgProc(HWND hwndDialog, UINT message,
 {
     static winPrivScreenPtr s_pScreenPriv = NULL;
     static winScreenInfo *s_pScreenInfo = NULL;
-    static ScreenPtr s_pScreen = NULL;
 
 #if CYGDEBUG
     winDebug("winChangeDepthDlgProc\n");
@@ -447,12 +446,11 @@ winChangeDepthDlgProc(HWND hwndDialog, UINT message,
         /* Store pointers to private structures for future use */
         s_pScreenPriv = (winPrivScreenPtr) lParam;
         s_pScreenInfo = s_pScreenPriv->pScreenInfo;
-        s_pScreen = s_pScreenInfo->pScreen;
 
 #if CYGDEBUG
         winDebug("winChangeDepthDlgProc - WM_INITDIALOG - s_pScreenPriv: %08x, "
-                 "s_pScreenInfo: %08x, s_pScreen: %08x\n",
-                 s_pScreenPriv, s_pScreenInfo, s_pScreen);
+                 "s_pScreenInfo: %08x\n",
+                 s_pScreenPriv, s_pScreenInfo);
 #endif
 
 #if CYGDEBUG
@@ -562,8 +560,6 @@ static wBOOL CALLBACK
 winAboutDlgProc(HWND hwndDialog, UINT message, WPARAM wParam, LPARAM lParam)
 {
     static winPrivScreenPtr s_pScreenPriv = NULL;
-    static winScreenInfo *s_pScreenInfo = NULL;
-    static ScreenPtr s_pScreen = NULL;
 
 #if CYGDEBUG
     winDebug("winAboutDlgProc\n");
@@ -576,10 +572,8 @@ winAboutDlgProc(HWND hwndDialog, UINT message, WPARAM wParam, LPARAM lParam)
         winDebug("winAboutDlgProc - WM_INITDIALOG\n");
 #endif
 
-        /* Store pointers to private structures for future use */
+        /* Store pointer to private structure for future use */
         s_pScreenPriv = (winPrivScreenPtr) lParam;
-        s_pScreenInfo = s_pScreenPriv->pScreenInfo;
-        s_pScreen = s_pScreenInfo->pScreen;
 
         winInitDialog(hwndDialog);
 
commit f2fd8ec3725a61abbc831f0a9ec28fa2b7020c47
Author: Dave Airlie <airlied at redhat.com>
Date:   Wed Jan 9 12:52:13 2013 +1000

    gpu: call CreateScreenResources for GPU screens
    
    I didn't think we needed this before, but after doing some more
    work with reverse optimus it seems like it should be called.
    
    Reviewed-by: Keith Packard <keithp at keithp.com>
    Signed-off-by: Dave Airlie <airlied at redhat.com>

diff --git a/dix/main.c b/dix/main.c
index bea1a8d..c46e40a 100644
--- a/dix/main.c
+++ b/dix/main.c
@@ -211,6 +211,9 @@ main(int argc, char *argv[], char *envp[])
             ScreenPtr pScreen = screenInfo.gpuscreens[i];
             if (!CreateScratchPixmapsForScreen(pScreen))
                 FatalError("failed to create scratch pixmaps");
+            if (pScreen->CreateScreenResources &&
+                !(*pScreen->CreateScreenResources) (pScreen))
+                FatalError("failed to create screen resources");
         }
 
         for (i = 0; i < screenInfo.numScreens; i++) {
diff --git a/hw/xfree86/common/xf86platformBus.c b/hw/xfree86/common/xf86platformBus.c
index bcb65ff..e368dee 100644
--- a/hw/xfree86/common/xf86platformBus.c
+++ b/hw/xfree86/common/xf86platformBus.c
@@ -455,6 +455,14 @@ xf86platformAddDevice(int index)
 
    CreateScratchPixmapsForScreen(xf86GPUScreens[i]->pScreen);
 
+   if (xf86GPUScreens[i]->pScreen->CreateScreenResources &&
+       !(*xf86GPUScreens[i]->pScreen->CreateScreenResources) (xf86GPUScreens[i]->pScreen)) {
+       RemoveGPUScreen(xf86GPUScreens[i]->pScreen);
+       xf86DeleteScreen(xf86GPUScreens[i]);
+       xf86UnclaimPlatformSlot(&xf86_platform_devices[index], NULL);
+       xf86NumGPUScreens = old_screens;
+       return -1;
+   }
    /* attach unbound to 0 protocol screen */
    AttachUnboundGPU(xf86Screens[0]->pScreen, xf86GPUScreens[i]->pScreen);
 
commit 8fcb9d91b69abc72ddef31b9f2e8585580c6cad2
Author: Dave Airlie <airlied at redhat.com>
Date:   Wed Jan 9 12:52:08 2013 +1000

    dix: allow pixmap dirty helper to be used for non-shared pixmaps
    
    this allows the pixmap dirty helper to be used for reverse optimus,
    where the GPU wants to copy from the shared pixmap to its VRAM copy.
    
    [airlied: slave_dst is wrong name now but pointless ABI churn at this point]
    Reviewed-by: Keith Packard <keithp at keithp.com>
    Signed-off-by: Dave Airlie <airlied at redhat.com>

diff --git a/dix/pixmap.c b/dix/pixmap.c
index 2418812..fe92147 100644
--- a/dix/pixmap.c
+++ b/dix/pixmap.c
@@ -243,6 +243,8 @@ Bool PixmapSyncDirtyHelper(PixmapDirtyUpdatePtr dirty, RegionPtr dirty_region)
     }
 
     dst = dirty->slave_dst->master_pixmap;
+    if (!dst)
+        dst = dirty->slave_dst;
 
     RegionTranslate(dirty_region, -dirty->x, -dirty->y);
     n = RegionNumRects(dirty_region);
diff --git a/fb/fbpixmap.c b/fb/fbpixmap.c
index fbcdca9..0824b64 100644
--- a/fb/fbpixmap.c
+++ b/fb/fbpixmap.c
@@ -67,6 +67,7 @@ fbCreatePixmapBpp(ScreenPtr pScreen, int width, int height, int depth, int bpp,
     pPixmap->devKind = paddedWidth;
     pPixmap->refcnt = 1;
     pPixmap->devPrivate.ptr = (pointer) ((char *) pPixmap + base + adjust);
+    pPixmap->master_pixmap = NULL;
 
 #ifdef FB_DEBUG
     pPixmap->devPrivate.ptr =
commit 16077b81c502e04d77f81f683e0c213b9fe75393
Author: Dave Airlie <airlied at redhat.com>
Date:   Wed Jan 9 12:52:03 2013 +1000

    xf86crtc: don't use scrn->display for gpu screens
    
    scrn->display is a property of the main screen really, and we don't
    want to have the GPU screens use it for anything when picking modes
    or a front buffer size.
    
    This fixes a bug where when you plugged a display link device, it
    would try and allocate a screen the same size as the current running
    one (3360x1050 in this case), which was too big for the device. Avoid
    doing this and just pick sizes based on whats plugged into this device.
    
    Reviewed-by: Keith Packard <keithp at keithp.com>
    Signed-off-by: Dave Airlie <airlied at redhat.com>

diff --git a/hw/xfree86/modes/xf86Crtc.c b/hw/xfree86/modes/xf86Crtc.c
index d64f6bd..4a490c6 100644
--- a/hw/xfree86/modes/xf86Crtc.c
+++ b/hw/xfree86/modes/xf86Crtc.c
@@ -2449,11 +2449,11 @@ xf86InitialConfiguration(ScrnInfoPtr scrn, Bool canGrow)
     config->debug_modes = xf86ReturnOptValBool(config->options,
                                                OPTION_MODEDEBUG, FALSE);
 
-    if (scrn->display->virtualX)
+    if (scrn->display->virtualX && !scrn->is_gpu)
         width = scrn->display->virtualX;
     else
         width = config->maxWidth;
-    if (scrn->display->virtualY)
+    if (scrn->display->virtualY && !scrn->is_gpu)
         height = scrn->display->virtualY;
     else
         height = config->maxHeight;
@@ -2517,8 +2517,10 @@ xf86InitialConfiguration(ScrnInfoPtr scrn, Bool canGrow)
 
     /* XXX override xf86 common frame computation code */
 
-    scrn->display->frameX0 = 0;
-    scrn->display->frameY0 = 0;
+    if (!scrn->is_gpu) {
+        scrn->display->frameX0 = 0;
+        scrn->display->frameY0 = 0;
+    }
 
     for (c = 0; c < config->num_crtc; c++) {
         xf86CrtcPtr crtc = config->crtc[c];
@@ -2566,7 +2568,7 @@ xf86InitialConfiguration(ScrnInfoPtr scrn, Bool canGrow)
         }
     }
 
-    if (scrn->display->virtualX == 0) {
+    if (scrn->display->virtualX == 0 || scrn->is_gpu) {
         /*
          * Expand virtual size to cover the current config and potential mode
          * switches, if the driver can't enlarge the screen later.
@@ -2581,8 +2583,10 @@ xf86InitialConfiguration(ScrnInfoPtr scrn, Bool canGrow)
             }
         }
 
-        scrn->display->virtualX = width;
-        scrn->display->virtualY = height;
+	if (!scrn->is_gpu) {
+            scrn->display->virtualX = width;
+            scrn->display->virtualY = height;
+	}
     }
 
     if (width > scrn->virtualX)
commit f0d0d75bfe62553dde353f89e46ff13dd863fbe8
Author: Dave Airlie <airlied at redhat.com>
Date:   Wed Jan 9 12:51:55 2013 +1000

    dix/gpu: remove asserts for output/offload from same slave
    
    We should have no problem allowing output/offload from the same slave,
    I asserted here, but in order to implement reverse optimus this makes
    perfect sense. (reverse optimus is intel outputting to nvidia).
    
    Reviewed-by: Keith Packard <keithp at keithp.com>
    Signed-off-by: Dave Airlie <airlied at redhat.com>

diff --git a/dix/dispatch.c b/dix/dispatch.c
index 8d61735..90b6c7c 100644
--- a/dix/dispatch.c
+++ b/dix/dispatch.c
@@ -3942,7 +3942,6 @@ void
 AttachOutputGPU(ScreenPtr pScreen, ScreenPtr new)
 {
     assert(new->isGPU);
-    assert(!new->current_master);
     xorg_list_add(&new->output_head, &pScreen->output_slave_list);
     new->current_master = pScreen;
 }
@@ -3959,7 +3958,6 @@ void
 AttachOffloadGPU(ScreenPtr pScreen, ScreenPtr new)
 {
     assert(new->isGPU);
-    assert(!new->current_master);
     xorg_list_add(&new->offload_head, &pScreen->offload_slave_list);
     new->current_master = pScreen;
 }
commit 9d26e8eaf5a2d7c3e65670ac20254c60f665c463
Author: Dave Airlie <airlied at redhat.com>
Date:   Wed Jan 9 14:26:35 2013 +1000

    randr: report changes when we disconnect a GPU slave
    
    When we disconnect an output/offload slave set the changed bits,
    so a later TellChanged can do something.
    
    Then when we remove a GPU slave device, sent change notification
    to the protocol screen.
    
    This allows hot unplugged USB devices to disappear in clients.
    
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Dave Airlie <airlied at redhat.com>

diff --git a/hw/xfree86/common/xf86platformBus.c b/hw/xfree86/common/xf86platformBus.c
index 9034dad..bcb65ff 100644
--- a/hw/xfree86/common/xf86platformBus.c
+++ b/hw/xfree86/common/xf86platformBus.c
@@ -47,6 +47,7 @@
 #include "Pci.h"
 #include "xf86platformBus.h"
 
+#include "randrstr.h"
 int platformSlotClaimed;
 
 int xf86_num_platform_devices;
@@ -499,7 +500,7 @@ xf86platformRemoveDevice(int index)
     xf86UnclaimPlatformSlot(&xf86_platform_devices[index], NULL);
 
     xf86_remove_platform_device(index);
-
+    RRTellChanged(xf86Screens[0]->pScreen);
  out:
     return;
 }
diff --git a/hw/xfree86/modes/xf86RandR12.c b/hw/xfree86/modes/xf86RandR12.c
index 25beee6..2817aaa 100644
--- a/hw/xfree86/modes/xf86RandR12.c
+++ b/hw/xfree86/modes/xf86RandR12.c
@@ -1896,10 +1896,12 @@ xf86RandR14ProviderDestroy(ScreenPtr screen, RRProviderPtr provider)
         if (config->randr_provider->offload_sink) {
             DetachOffloadGPU(screen);
             config->randr_provider->offload_sink = NULL;
+            RRSetChanged(screen);
         }
         else if (config->randr_provider->output_source) {
             DetachOutputGPU(screen);
             config->randr_provider->output_source = NULL;
+            RRSetChanged(screen);
         }
         else if (screen->current_master)
             DetachUnboundGPU(screen);
commit b724324252d13ff95f62eebd12d125b194d2ccc2
Author: Dave Airlie <airlied at redhat.com>
Date:   Wed Jan 9 14:25:43 2013 +1000

    randr: only respected changed on the protocol screen
    
    We don't want to know about changes on the non-protocol screen,
    we will fix up setchanged to make sure non-protocol screens update
    the protocol screens when they have a change.
    
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Dave Airlie <airlied at redhat.com>

diff --git a/randr/randr.c b/randr/randr.c
index fb0895d..cb6fce7 100644
--- a/randr/randr.c
+++ b/randr/randr.c
@@ -506,7 +506,7 @@ RRTellChanged(ScreenPtr pScreen)
         mastersp = pScrPriv;
     }
 
-    if (pScrPriv->changed) {
+    if (mastersp->changed) {
         UpdateCurrentTimeIf();
         if (mastersp->configChanged) {
             mastersp->lastConfigTime = currentTime;
commit b3f70f38edebac87afe9351538365292f1aaaff3
Author: Dave Airlie <airlied at redhat.com>
Date:   Wed Jan 9 14:29:47 2013 +1000

    randr: make SetChanged modify the main protocol screen not the gpu screen
    
    When SetChanged is called we now modify the main protocol screen,
    not the the gpu screen. Since changed stuff should work at the protocol level.
    
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Dave Airlie <airlied at redhat.com>

diff --git a/randr/randr.c b/randr/randr.c
index 11f88b2..fb0895d 100644
--- a/randr/randr.c
+++ b/randr/randr.c
@@ -467,9 +467,23 @@ TellChanged(WindowPtr pWin, pointer value)
 void
 RRSetChanged(ScreenPtr pScreen)
 {
+    /* set changed bits on the master screen only */
+    ScreenPtr master;
     rrScrPriv(pScreen);
+    rrScrPrivPtr mastersp;
+
+    if (pScreen->isGPU) {
+        master = pScreen->current_master;
+        if (!master)
+            return;
+        mastersp = rrGetScrPriv(master);
+    }
+    else {
+        master = pScreen;
+        mastersp = pScrPriv;
+    }
 
-    pScrPriv->changed = TRUE;
+    mastersp->changed = TRUE;
 }
 
 /*
commit f9c8248b8326ad01f33f31531c6b2479baf80f02
Author: Dave Airlie <airlied at redhat.com>
Date:   Wed Jan 9 14:23:57 2013 +1000

    randr: don't directly set changed bits in randr screen
    
    Introduce a wrapper interface so we can fix things up for multi-gpu
    situations later.
    
    This just introduces the API for now.
    
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Dave Airlie <airlied at redhat.com>

diff --git a/randr/randr.c b/randr/randr.c
index f0decfc..11f88b2 100644
--- a/randr/randr.c
+++ b/randr/randr.c
@@ -464,6 +464,14 @@ TellChanged(WindowPtr pWin, pointer value)
     return WT_WALKCHILDREN;
 }
 
+void
+RRSetChanged(ScreenPtr pScreen)
+{
+    rrScrPriv(pScreen);
+
+    pScrPriv->changed = TRUE;
+}
+
 /*
  * Something changed; send events and adjust pointer position
  */
diff --git a/randr/randrstr.h b/randr/randrstr.h
index 2517479..2babfed 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -486,6 +486,10 @@ extern _X_EXPORT void
  RRDeliverScreenEvent(ClientPtr client, WindowPtr pWin, ScreenPtr pScreen);
 
 /* randr.c */
+/* set a screen change on the primary screen */
+extern _X_EXPORT void
+RRSetChanged(ScreenPtr pScreen);
+
 /*
  * Send all pending events
  */
diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index 721b05a..2f76b62 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -39,7 +39,7 @@ RRCrtcChanged(RRCrtcPtr crtc, Bool layoutChanged)
     if (pScreen) {
         rrScrPriv(pScreen);
 
-        pScrPriv->changed = TRUE;
+        RRSetChanged(pScreen);
         /*
          * Send ConfigureNotify on any layout change
          */
diff --git a/randr/rrinfo.c b/randr/rrinfo.c
index 1408d6f..fc57bd4 100644
--- a/randr/rrinfo.c
+++ b/randr/rrinfo.c
@@ -225,7 +225,7 @@ RRScreenSetSizeRange(ScreenPtr pScreen,
     pScrPriv->minHeight = minHeight;
     pScrPriv->maxWidth = maxWidth;
     pScrPriv->maxHeight = maxHeight;
-    pScrPriv->changed = TRUE;
+    RRSetChanged(pScreen);
     pScrPriv->configChanged = TRUE;
 }
 
diff --git a/randr/rroutput.c b/randr/rroutput.c
index 88781ba..922d61f 100644
--- a/randr/rroutput.c
+++ b/randr/rroutput.c
@@ -36,7 +36,7 @@ RROutputChanged(RROutputPtr output, Bool configChanged)
     output->changed = TRUE;
     if (pScreen) {
         rrScrPriv(pScreen);
-        pScrPriv->changed = TRUE;
+        RRSetChanged(pScreen);
         if (configChanged)
             pScrPriv->configChanged = TRUE;
     }
diff --git a/randr/rrscreen.c b/randr/rrscreen.c
index 39340cc..36179ae 100644
--- a/randr/rrscreen.c
+++ b/randr/rrscreen.c
@@ -143,7 +143,7 @@ RRScreenSizeNotify(ScreenPtr pScreen)
     pScrPriv->height = pScreen->height;
     pScrPriv->mmWidth = pScreen->mmWidth;
     pScrPriv->mmHeight = pScreen->mmHeight;
-    pScrPriv->changed = TRUE;
+    RRSetChanged(pScreen);
 /*    pScrPriv->sizeChanged = TRUE; */
 
     RRTellChanged(pScreen);
commit 451ba4bd41b82acd4aec6236ba121e00cfeb311b
Author: Chris Wilson <chris at chris-wilson.co.uk>
Date:   Thu Jan 10 03:26:33 2013 +0000

    hw/xfree86: Only report SetDesiredModes() failed if at least one modeset fails
    
    commit 6703a7c7cf1a349c137e247a0c8eb462ff7b07be
    Author: Keith Packard <keithp at keithp.com>
    Date:   Tue Jan 8 20:24:32 2013 -0800
    
        hw/xfree86: Require only one working CRTC to start the server.
    
    changed the logic to try to set the mode on all connected outputs rather
    than abort upon the first failure. The return error code was then
    tweaked such that it reported success if it set a mode on any crtc.
    However, this confuses the headless case where we never enable any crtcs
    and also, importantly, never fail to set a crtc.
    
    Bugzilla: https://bugs.freedesktop.org/show_bug.cgi?id=59190
    
    Signed-off-by: Chris Wilson <chris at chris-wilson.co.uk>
    Also-written-by: Maarten Lankhorst <maarten.lankhorst at canonical.com>
    Reviewed-by: Keith Packard <keithp at keithp.com>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/xfree86/modes/xf86Crtc.c b/hw/xfree86/modes/xf86Crtc.c
index e4b393c..d64f6bd 100644
--- a/hw/xfree86/modes/xf86Crtc.c
+++ b/hw/xfree86/modes/xf86Crtc.c
@@ -2687,8 +2687,8 @@ xf86SetDesiredModes(ScrnInfoPtr scrn)
 {
     xf86CrtcConfigPtr config = XF86_CRTC_CONFIG_PTR(scrn);
     xf86CrtcPtr crtc = config->crtc[0];
+    int enabled = 0, failed = 0;
     int c;
-    int enabled = 0;
 
     /* A driver with this hook will take care of this */
     if (!crtc->funcs->set_mode_major) {
@@ -2748,11 +2748,12 @@ xf86SetDesiredModes(ScrnInfoPtr scrn)
                 if (config->output[o]->crtc == crtc)
                     config->output[o]->crtc = NULL;
             crtc->enabled = FALSE;
+            ++failed;
 	}
     }
 
     xf86DisableUnusedFunctions(scrn);
-    return enabled != 0;
+    return enabled != 0 || failed == 0;
 }
 
 /**
commit 9878e097a7de2f86eff0dcfd9fe5d83b162197ec
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Wed Apr 24 15:24:31 2013 -0700

    Only call xf86platformVTProbe() when it's defined
    
    Fixes build on non-udev systems, since XSERVER_PLATFORM_BUS is only
    defined in configure.ac if $CONFIG_UDEV_KMS is true.
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Dave Airlie <airlied at redhat.com>

diff --git a/hw/xfree86/common/xf86Events.c b/hw/xfree86/common/xf86Events.c
index ea18420..7a949fd 100644
--- a/hw/xfree86/common/xf86Events.c
+++ b/hw/xfree86/common/xf86Events.c
@@ -561,8 +561,10 @@ xf86VTSwitch(void)
         for (ih = InputHandlers; ih; ih = ih->next)
             xf86EnableInputHandler(ih);
 
+#ifdef XSERVER_PLATFORM_BUS
         /* check for any new output devices */
         xf86platformVTProbe();
+#endif
 
         OsReleaseSIGIO();
     }
commit e779402d531625ba4ed5d628d06c6b1e06b2ec7b
Author: Keith Packard <keithp at keithp.com>
Date:   Thu Apr 25 09:02:31 2013 -0700

    shadow: Define c2p_unsupported
    
    Just make this call BUG_WARN(1) to indicate that something unexpected
    happened
    
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/miext/shadow/c2p_core.h b/miext/shadow/c2p_core.h
index 252f93e..a48e223 100644
--- a/miext/shadow/c2p_core.h
+++ b/miext/shadow/c2p_core.h
@@ -41,7 +41,9 @@ static inline void _transp(CARD32 d[], unsigned int i1, unsigned int i2,
 }
 
 
-extern void c2p_unsupported(void);
+static inline void c2p_unsupported(void) {
+    BUG_WARN(1);
+}
 
 static inline CARD32 get_mask(unsigned int n)
 {
commit 2b361fbda536f0125e4b87a6d455acc58f4e8690
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Sun Feb 10 10:24:59 2013 -0800

    sparcPromPathname2Node: free name when returning error, instead of leaking it
    
    Reported with other leaks found by cppcheck in bugzilla #50281
    https://bugs.freedesktop.org/show_bug.cgi?id=50281
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/xfree86/os-support/bus/Sbus.c b/hw/xfree86/os-support/bus/Sbus.c
index 8260007..14e6d4b 100644
--- a/hw/xfree86/os-support/bus/Sbus.c
+++ b/hw/xfree86/os-support/bus/Sbus.c
@@ -617,8 +617,10 @@ sparcPromPathname2Node(const char *pathName)
         return 0;
     strcpy(name, pathName);
     name[i + 1] = 0;
-    if (name[0] != '/')
+    if (name[0] != '/') {
+        free(name);
         return 0;
+    }
     p = strchr(name + 1, '/');
     if (p)
         *p = 0;
@@ -629,8 +631,10 @@ sparcPromPathname2Node(const char *pathName)
         *regstr++ = 0;
     else
         regstr = p;
-    if (name + 1 == regstr)
+    if (name + 1 == regstr) {
+        free(name);
         return 0;
+    }
     promGetSibling(0);
     i = promWalkPathname2Node(name + 1, regstr, promRootNode, 0);
     free(name);
commit 174ccd84931ece5a92a09c4a1d6a47e0958ebf7e
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Sun Feb 10 10:24:59 2013 -0800

    xf86SbusCmapLoadPalette: Delay malloc until needed, avoiding leak on error
    
    Reported with other leaks found by cppcheck in bugzilla #50281
    https://bugs.freedesktop.org/show_bug.cgi?id=50281
    
    V2: check for malloc failure
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>

diff --git a/hw/xfree86/common/xf86sbusBus.c b/hw/xfree86/common/xf86sbusBus.c
index b6a6b94..07eb71e 100644
--- a/hw/xfree86/common/xf86sbusBus.c
+++ b/hw/xfree86/common/xf86sbusBus.c
@@ -641,14 +641,16 @@ xf86SbusCmapLoadPalette(ScrnInfoPtr pScrn, int numColors, int *indices,
     int i, index;
     sbusCmapPtr cmap;
     struct fbcmap fbcmap;
-    unsigned char *data = malloc(numColors * 3);
+    unsigned char *data;
 
     cmap = SBUSCMAPPTR(pScrn->pScreen);
     if (!cmap)
         return;
     fbcmap.count = 0;
     fbcmap.index = indices[0];
-    fbcmap.red = data;
+    fbcmap.red = data = malloc(numColors * 3);
+    if (!data)
+        return;
     fbcmap.green = data + numColors;
     fbcmap.blue = fbcmap.green + numColors;
     for (i = 0; i < numColors; i++) {
commit 6bca0184d167388cd417d113031317990489987d
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Sun Feb 10 10:18:02 2013 -0800

    dmxVDLRead: if we opened a file, close it instead of leaking it
    
    Reported with other leaks found by cppcheck in bugzilla #50281
    https://bugs.freedesktop.org/show_bug.cgi?id=50281
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/dmx/config/dmxcompat.c b/hw/dmx/config/dmxcompat.c
index bd9f127..107991a 100644
--- a/hw/dmx/config/dmxcompat.c
+++ b/hw/dmx/config/dmxcompat.c
@@ -228,5 +228,9 @@ dmxVDLRead(const char *filename)
             break;
         }
     }
+
+    if (str != stdin)
+        fclose(str);
+
     return entry;
 }
commit 8c5ff2e93f73b24adff741b25fc1e31b2f5dd0ac
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Sun Feb 10 10:24:59 2013 -0800

    __glXDRIscreenProbe: free screen when DRI2Connect fails, instead of leaking it
    
    Reported with other leaks found by cppcheck in bugzilla #50281
    https://bugs.freedesktop.org/show_bug.cgi?id=50281
    
    V2: goto existing error handler, instead of replicating more of it here
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/glx/glxdri2.c b/glx/glxdri2.c
index e07cb56..6548579 100644
--- a/glx/glxdri2.c
+++ b/glx/glxdri2.c
@@ -946,7 +946,7 @@ __glXDRIscreenProbe(ScreenPtr pScreen)
                      &screen->fd, &driverName, &deviceName)) {
         LogMessage(X_INFO,
                    "AIGLX: Screen %d is not DRI2 capable\n", pScreen->myNum);
-        return NULL;
+        goto handle_error;
     }
 
     screen->base.destroy = __glXDRIscreenDestroy;
commit 9567fa9a7269765bc59ac71b931e16df261d794d
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Sun Feb 10 10:24:59 2013 -0800

    __glXDRIscreenCreateContext: free context on failure, instead of leaking it
    
    Reported with other leaks found by cppcheck in bugzilla #50281
    https://bugs.freedesktop.org/show_bug.cgi?id=50281
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Ian Romanick <ian.d.romanick at intel.com>

diff --git a/glx/glxdri.c b/glx/glxdri.c
index a997e2f..1964d2e 100644
--- a/glx/glxdri.c
+++ b/glx/glxdri.c
@@ -645,8 +645,10 @@ __glXDRIscreenCreateContext(__GLXscreen * baseScreen,
     for (i = 0; i < pScreen->numVisuals; i++, visual++)
         if (visual->vid == glxConfig->visualID)
             break;
-    if (i == pScreen->numVisuals)
+    if (i == pScreen->numVisuals) {
+        free(context);
         return NULL;
+    }
 
     context->hwContextID = FakeClientID(0);
 
@@ -655,8 +657,10 @@ __glXDRIscreenCreateContext(__GLXscreen * baseScreen,
                               context->hwContextID, &hwContext);
     __glXleaveServer(GL_FALSE);
 
-    if (!retval)
+    if (!retval) {
+        free(context);
         return NULL;
+    }
 
     context->driContext = screen->legacy->createNewContext(screen->driScreen, config->driConfig, 0,     /* render type */
                                                            driShare,
commit 7ab98bafc9a3426fd40f8ae693430491333ba4fc
Merge: 53da26a 5ab2603
Author: Keith Packard <keithp at keithp.com>
Date:   Wed Apr 24 14:14:45 2013 -0700

    Merge remote-tracking branch 'geertu/master'

commit 53da26afb76bcce70b91c5df23d25e7e85c010cf
Merge: 5ece86e d8d3c78
Author: Keith Packard <keithp at keithp.com>
Date:   Wed Apr 24 10:27:19 2013 -0700

    Merge remote-tracking branch 'whot/for-keith'

diff --cc hw/xfree86/os-support/linux/lnx_platform.c
index 2a04f34,bd060c9..1865b31
--- a/hw/xfree86/os-support/linux/lnx_platform.c
+++ b/hw/xfree86/os-support/linux/lnx_platform.c
@@@ -161,18 -122,9 +143,17 @@@ xf86PlatformDeviceProbe(struct OdevAttr
      if (i != xf86_num_platform_devices)
          goto out_free;
  
-     LogMessage(X_INFO, "config/udev: Adding drm device (%s)\n",
-                path);
+     LogMessage(X_INFO, "xfree86: Adding drm device (%s)\n", path);
  
 -    ret = get_drm_info(attribs, path);
 +    if (!xf86VTOwner()) {
 +            /* if we don't currently own the VT then don't probe the device,
 +               just mark it as unowned for later use */
 +            attribs->unowned = TRUE;
 +            xf86_add_platform_device(attribs);
 +            return;
 +    }
 +
 +    ret = get_drm_info(attribs, path, -1);
      if (ret == FALSE)
          goto out_free;
  
commit 5ece86e921a1df457a9baab6a2357ccda4ad6957
Merge: ef0a726 22cab8a
Author: Keith Packard <keithp at keithp.com>
Date:   Wed Apr 24 10:23:51 2013 -0700

    Merge remote-tracking branch 'airlied/for-keithp-gpu-vt-owner'

commit ef0a726bc8d5c415244cb4f86d664938b0127a5d
Author: Jeremy White <jwhite at codeweavers.com>
Date:   Thu Mar 21 10:58:42 2013 -0500

    Eliminate the use of xf86Rename.h
    
    Signed-off-by: Jeremy White <jwhite at codeweavers.com>
    Reviewed-by: Keith Packard <keithp at keithp.com>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/xfree86/modes/Makefile.am b/hw/xfree86/modes/Makefile.am
index 9236426..7e33ebb 100644
--- a/hw/xfree86/modes/Makefile.am
+++ b/hw/xfree86/modes/Makefile.am
@@ -16,7 +16,6 @@ libxf86modes_la_SOURCES = \
 	xf86Modes.h \
 	xf86RandR12.c \
 	xf86RandR12.h \
-	xf86Rename.h \
 	xf86Rotate.c \
         $(DGA_SRCS)
 
@@ -29,7 +28,6 @@ INCLUDES = $(XORG_INCS) -I$(srcdir)/../ddc -I$(srcdir)/../i2c \
 sdk_HEADERS = \
 	xf86Crtc.h \
 	xf86Modes.h \
-	xf86RandR12.h \
-	xf86Rename.h
+	xf86RandR12.h
 
 AM_CFLAGS = $(DIX_CFLAGS) $(XORG_CFLAGS)
diff --git a/hw/xfree86/modes/xf86Crtc.h b/hw/xfree86/modes/xf86Crtc.h
index 802303f..c127d78 100644
--- a/hw/xfree86/modes/xf86Crtc.h
+++ b/hw/xfree86/modes/xf86Crtc.h
@@ -25,9 +25,6 @@
 
 #include <edid.h>
 #include "randrstr.h"
-#if XF86_MODES_RENAME
-#include "xf86Rename.h"
-#endif
 #include "xf86Modes.h"
 #include "xf86Cursor.h"
 #include "xf86i2c.h"
diff --git a/hw/xfree86/modes/xf86Modes.h b/hw/xfree86/modes/xf86Modes.h
index d3abee5..5458918 100644
--- a/hw/xfree86/modes/xf86Modes.h
+++ b/hw/xfree86/modes/xf86Modes.h
@@ -36,9 +36,6 @@
 #include "xorgVersion.h"
 #include "edid.h"
 #include "xf86Parser.h"
-#if XF86_MODES_RENAME
-#include "xf86Rename.h"
-#endif
 
 extern _X_EXPORT double xf86ModeHSync(const DisplayModeRec * mode);
 extern _X_EXPORT double xf86ModeVRefresh(const DisplayModeRec * mode);
diff --git a/hw/xfree86/modes/xf86RandR12.h b/hw/xfree86/modes/xf86RandR12.h
index 9ad695c..e603799 100644
--- a/hw/xfree86/modes/xf86RandR12.h
+++ b/hw/xfree86/modes/xf86RandR12.h
@@ -24,9 +24,6 @@
 #define _XF86_RANDR_H_
 #include <randrstr.h>
 #include <X11/extensions/render.h>
-#if XF86_MODES_RENAME
-#include "xf86Rename.h"
-#endif
 
 extern _X_EXPORT Bool xf86RandR12CreateScreenResources(ScreenPtr pScreen);
 extern _X_EXPORT Bool xf86RandR12Init(ScreenPtr pScreen);
diff --git a/hw/xfree86/modes/xf86Rename.h b/hw/xfree86/modes/xf86Rename.h
deleted file mode 100644
index 46690a8..0000000
--- a/hw/xfree86/modes/xf86Rename.h
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright © 2006 Keith Packard
- *
- * Permission to use, copy, modify, distribute, and sell this software and its
- * documentation for any purpose is hereby granted without fee, provided that
- * the above copyright notice appear in all copies and that both that copyright
- * notice and this permission notice appear in supporting documentation, and
- * that the name of the copyright holders not be used in advertising or
- * publicity pertaining to distribution of the software without specific,
- * written prior permission.  The copyright holders make no representations
- * about the suitability of this software for any purpose.  It is provided "as
- * is" without express or implied warranty.
- *
- * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
- * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
- * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
- * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
- * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
- * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
- * OF THIS SOFTWARE.
- */
-
-#ifndef _XF86RENAME_H_
-#define _XF86RENAME_H_
-
-#include "local_xf86Rename.h"
-
-#define xf86_cursors_fini XF86NAME(xf86_cursors_fini)
-#define xf86_cursors_init XF86NAME(xf86_cursors_init)
-#define xf86_hide_cursors XF86NAME(xf86_hide_cursors)
-#define xf86_reload_cursors XF86NAME(xf86_reload_cursors)
-#define xf86_show_cursors XF86NAME(xf86_show_cursors)
-#define xf86ConnectorGetName XF86NAME(xf86ConnectorGetName)
-#define xf86CrtcConfigInit XF86NAME(xf86CrtcConfigInit)
-#define xf86CrtcConfigPrivateIndex XF86NAME(xf86CrtcConfigPrivateIndex)
-#define xf86CrtcCreate XF86NAME(xf86CrtcCreate)
-#define xf86CrtcDestroy XF86NAME(xf86CrtcDestroy)
-#define xf86CrtcInUse XF86NAME(xf86CrtcInUse)
-#define xf86CrtcRotate XF86NAME(xf86CrtcRotate)
-#define xf86CrtcScreenInit XF86NAME(xf86CrtcScreenInit)
-#define xf86CrtcSetModeTransform XF86NAME(xf86CrtcSetModeTransform)
-#define xf86CrtcSetMode XF86NAME(xf86CrtcSetMode)
-#define xf86CrtcSetSizeRange XF86NAME(xf86CrtcSetSizeRange)
-#define xf86CVTMode XF86NAME(xf86CVTMode)
-#define xf86DDCMonitorSet XF86NAME(xf86DDCMonitorSet)
-#define xf86DisableUnusedFunctions XF86NAME(xf86DisableUnusedFunctions)
-#define xf86DPMSSet XF86NAME(xf86DPMSSet)
-#define xf86DuplicateMode XF86NAME(xf86DuplicateMode)
-#define xf86DuplicateModes XF86NAME(xf86DuplicateModes)
-#define xf86GetDefaultModes XF86NAME(xf86GetDefaultModes)
-#define xf86GetMonitorModes XF86NAME(xf86GetMonitorModes)
-#define xf86InitialConfiguration XF86NAME(xf86InitialConfiguration)
-#define xf86ModeHSync XF86NAME(xf86ModeHSync)
-#define xf86ModesAdd XF86NAME(xf86ModesAdd)
-#define xf86ModesEqual XF86NAME(xf86ModesEqual)
-#define xf86ModeVRefresh XF86NAME(xf86ModeVRefresh)
-#define xf86OutputCreate XF86NAME(xf86OutputCreate)
-#define xf86OutputDestroy XF86NAME(xf86OutputDestroy)
-#define xf86OutputGetEDID XF86NAME(xf86OutputGetEDID)
-#define xf86OutputGetEDIDModes XF86NAME(xf86OutputGetEDIDModes)
-#define xf86OutputRename XF86NAME(xf86OutputRename)
-#define xf86OutputSetEDID XF86NAME(xf86OutputSetEDID)
-#define xf86OutputUseScreenMonitor XF86NAME(xf86OutputUseScreenMonitor)
-#define xf86PrintModeline XF86NAME(xf86PrintModeline)
-#define xf86ProbeOutputModes XF86NAME(xf86ProbeOutputModes)
-#define xf86PruneInvalidModes XF86NAME(xf86PruneInvalidModes)
-#define xf86RotateCloseScreen XF86NAME(xf86RotateCloseScreen)
-#define xf86SetModeCrtc XF86NAME(xf86SetModeCrtc)
-#define xf86SetModeDefaultName XF86NAME(xf86SetModeDefaultName)
-#define xf86SetScrnInfoModes XF86NAME(xf86SetScrnInfoModes)
-#define xf86ValidateModesClocks XF86NAME(xf86ValidateModesClocks)
-#define xf86ValidateModesFlags XF86NAME(xf86ValidateModesFlags)
-#define xf86ValidateModesSize XF86NAME(xf86ValidateModesSize)
-#define xf86ValidateModesSync XF86NAME(xf86ValidateModesSync)
-#define xf86ValidateModesUserConfig XF86NAME(xf86ValidateModesUserConfig)
-#define xf86DiDGAInit XF86NAME(xf86DiDGAInit)
-#define xf86DiDGAReInit XF86NAME(xf86DiDGAReInit)
-#define xf86DDCGetModes XF86NAME(xf86DDCGetModes)
-#define xf86RandR12CreateScreenResources XF86NAME(xf86RandR12CreateScreenResources)
-#define xf86RandR12GetOriginalVirtualSize XF86NAME(xf86RandR12GetOriginalVirtualSize)
-#define xf86RandR12GetRotation XF86NAME(xf86RandR12GetRotation)
-#define xf86RandR12Init XF86NAME(xf86RandR12Init)
-#define xf86RandR12PreInit XF86NAME(xf86RandR12PreInit)
-#define xf86RandR12SetConfig XF86NAME(xf86RandR12SetConfig)
-#define xf86RandR12SetRotations XF86NAME(xf86RandR12SetRotations)
-#define xf86SaveScreen XF86NAME(xf86SaveScreen)
-#define xf86CrtcSetScreenSubpixelOrder XF86NAME(xf86CrtcSetScreenSubpixelOrder)
-#define xf86ModeWidth XF86NAME(xf86ModeWidth)
-#define xf86ModeHeight XF86NAME(xf86ModeHeight)
-#define xf86OutputFindClosestMode XF86NAME(xf86OutputFindClosestMode)
-#define xf86SetSingleMode XF86NAME(xf86SetSingleMode)
-#define xf86SetDesiredModes XF86NAME(xf86SetDesiredModes)
-
-#endif                          /* _XF86RENAME_H_ */
commit 2b539239e465faa9e8c6d96f1c6f00e593d46c18
Author: Keith Packard <keithp at keithp.com>
Date:   Wed Apr 24 10:11:03 2013 -0700

    Bump to 1.14.99.1
    
    Snapshot with fix for CVE-2013-1940.
    
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/configure.ac b/configure.ac
index e0750bb..0b72860 100644
--- a/configure.ac
+++ b/configure.ac
@@ -26,9 +26,9 @@ dnl
 dnl Process this file with autoconf to create configure.
 
 AC_PREREQ(2.60)
-AC_INIT([xorg-server], 1.14.99.0, [https://bugs.freedesktop.org/enter_bug.cgi?product=xorg], xorg-server)
-RELEASE_DATE="2013-03-18"
-RELEASE_NAME="Pok Pok Meyer Lemon"
+AC_INIT([xorg-server], 1.14.99.1, [https://bugs.freedesktop.org/enter_bug.cgi?product=xorg], xorg-server)
+RELEASE_DATE="2013-04-24"
+RELEASE_NAME="Sweet Tea"
 AC_CONFIG_SRCDIR([Makefile.am])
 AM_INIT_AUTOMAKE([foreign dist-bzip2])
 
commit d8d3c78b6ebdf63836951d2dbd2d3d621ff26da2
Author: Andreas Müller <schnitzeltony at googlemail.com>
Date:   Tue Apr 16 14:30:43 2013 +0200

    dixstruct.h: fix segfaults - char is unsigned for ARM and PowerPC architectures
    
    see ARM related bug reports [1-3]
    
    [1] https://github.com/archlinuxarm/PKGBUILDs/issues/446I
    [2] http://www.raspberrypi.org/phpBB3/viewtopic.php?t=38568&p=321673
    [3] http://lists.linuxtogo.org/pipermail/openembedded-core/2013-April/037805.html
    
    Signed-off-by: Andreas Müller <schnitzeltony at googlemail.com>
    Reviewed-by: Mark Kettenis <kettenis at openbsd.org>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/include/dixstruct.h b/include/dixstruct.h
index 6784819..aef822c 100644
--- a/include/dixstruct.h
+++ b/include/dixstruct.h
@@ -96,7 +96,7 @@ typedef struct _Client {
     unsigned int clientGone:1;
     unsigned int closeDownMode:2;
     unsigned int clientState:2;
-    char smart_priority;
+    signed char smart_priority;
     short noClientException;      /* this client died or needs to be killed */
     int priority;
     ReplySwapPtr pSwapReplyFunc;
commit 7d722796c678532e8c5897c673c43184da353f44
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Wed Apr 17 19:47:42 2013 +1000

    dix: plug memory leak in freeing TouchClass
    
    ==15562== 1,800 bytes in 1 blocks are definitely lost in loss record 298 of 330
    ==15562==    at 0x4A06B6F: calloc (vg_replace_malloc.c:593)
    ==15562==    by 0x4312C7: InitTouchClassDeviceStruct (devices.c:1644)
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>

diff --git a/dix/devices.c b/dix/devices.c
index 5f98afc..fa94a94 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -795,6 +795,7 @@ FreeDeviceClass(int type, pointer *class)
             free((*t)->touches[i].valuators);
         }
 
+        free((*t)->touches);
         free((*t));
         break;
     }
commit 5ab260317ad3b2aafff31a97df21620db52eacd1
Author: Geert Uytterhoeven <geert at linux-m68k.org>
Date:   Sun Mar 10 21:04:19 2013 +0100

    Xfbdev: Wire up Amiga afb4 and afb8 support
    
    Add support for Amiga-style bitplanes, with 4 or 8 bits per pixel.
    
    Signed-off-by: Geert Uytterhoeven <geert at linux-m68k.org>
    Acked-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/kdrive/fbdev/fbdev.c b/hw/kdrive/fbdev/fbdev.c
index 40747fe..95f64cb 100644
--- a/hw/kdrive/fbdev/fbdev.c
+++ b/hw/kdrive/fbdev/fbdev.c
@@ -319,6 +319,21 @@ fbdevWindowLinear(ScreenPtr pScreen,
     return (CARD8 *) priv->fb + row * priv->fix.line_length + offset;
 }
 
+static void *
+fbdevWindowAfb(ScreenPtr pScreen,
+               CARD32 row,
+               CARD32 offset, int mode, CARD32 *size, void *closure)
+{
+    KdScreenPriv(pScreen);
+    FbdevPriv *priv = pScreenPriv->card->driver;
+
+    if (!pScreenPriv->enabled)
+        return 0;
+    /* offset to next plane */
+    *size = priv->var.yres_virtual * priv->fix.line_length;
+    return (CARD8 *) priv->fb + row * priv->fix.line_length + offset;
+}
+
 Bool
 fbdevMapFramebuffer(KdScreenInfo * screen)
 {
@@ -435,7 +450,20 @@ fbdevSetShadow(ScreenPtr pScreen)
         break;
 
     case FB_TYPE_PLANES:
-        FatalError("Bitplanes are not yet supported\n");
+        window = fbdevWindowAfb;
+        switch (priv->var.bits_per_pixel) {
+        case 4:
+            update = shadowUpdateAfb4;
+            break;
+
+        case 8:
+            update = shadowUpdateAfb8;
+            break;
+
+        default:
+            FatalError("Bitplanes with bpp %u are not yet supported\n",
+                       priv->var.bits_per_pixel);
+        }
         break;
 
     case FB_TYPE_INTERLEAVED_PLANES:
commit 672bc5bb38918304cf68114a1112cd48651a5e83
Author: Geert Uytterhoeven <geert at linux-m68k.org>
Date:   Sun Mar 10 17:17:26 2013 +0100

    Xfbdev: Wire up Atari iplan2p4 and iplan2p8 support
    
    Add support for Atari-style interleaved bitplanes, with 2 bytes interleave
    and 4 or 8 bits per pixel.
    
    Signed-off-by: Geert Uytterhoeven <geert at linux-m68k.org>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/kdrive/fbdev/fbdev.c b/hw/kdrive/fbdev/fbdev.c
index 52dfbf5..40747fe 100644
--- a/hw/kdrive/fbdev/fbdev.c
+++ b/hw/kdrive/fbdev/fbdev.c
@@ -439,7 +439,24 @@ fbdevSetShadow(ScreenPtr pScreen)
         break;
 
     case FB_TYPE_INTERLEAVED_PLANES:
-        FatalError("Interleaved bitplanes are not yet supported\n");
+        if (priv->fix.type_aux == 2) {
+            switch (priv->var.bits_per_pixel) {
+            case 4:
+                update = shadowUpdateIplan2p4;
+                break;
+
+            case 8:
+                update = shadowUpdateIplan2p8;
+                break;
+
+            default:
+                FatalError("Atari interleaved bitplanes with bpp %u are not yet supported\n",
+                           priv->var.bits_per_pixel);
+            }
+        } else {
+            FatalError("Interleaved bitplanes with interleave %u are not yet supported\n",
+                       priv->fix.type_aux);
+        }
         break;
 
     case FB_TYPE_TEXT:
commit 95a3c7536c1a4afe97aaf955980034cc69af9c2f
Author: Geert Uytterhoeven <geert at linux-m68k.org>
Date:   Sun Mar 10 17:17:26 2013 +0100

    Xfbdev: Force shadowfb for frame buffers with non-packed pixels
    
    Signed-off-by: Geert Uytterhoeven <geert at linux-m68k.org>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/kdrive/fbdev/fbdev.c b/hw/kdrive/fbdev/fbdev.c
index f31635d..52dfbf5 100644
--- a/hw/kdrive/fbdev/fbdev.c
+++ b/hw/kdrive/fbdev/fbdev.c
@@ -326,7 +326,8 @@ fbdevMapFramebuffer(KdScreenInfo * screen)
     KdPointerMatrix m;
     FbdevPriv *priv = screen->card->driver;
 
-    if (scrpriv->randr != RR_Rotate_0)
+    if (scrpriv->randr != RR_Rotate_0 ||
+        priv->fix.type != FB_TYPE_PACKED_PIXELS)
         scrpriv->shadow = TRUE;
     else
         scrpriv->shadow = FALSE;
commit 0e808110df216649e05503baecd06cd5a3e50421
Author: Geert Uytterhoeven <geert at linux-m68k.org>
Date:   Sun Mar 10 17:17:26 2013 +0100

    Xfbdev: Reject unsupported frame buffer types
    
    Signed-off-by: Geert Uytterhoeven <geert at linux-m68k.org>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/kdrive/fbdev/fbdev.c b/hw/kdrive/fbdev/fbdev.c
index ebbfeb9..f31635d 100644
--- a/hw/kdrive/fbdev/fbdev.c
+++ b/hw/kdrive/fbdev/fbdev.c
@@ -402,33 +402,58 @@ fbdevSetShadow(ScreenPtr pScreen)
 
     window = fbdevWindowLinear;
     update = 0;
-    if (scrpriv->randr)
-        if (priv->var.bits_per_pixel == 16) {
-            switch (scrpriv->randr) {
-            case RR_Rotate_90:
-                if (useYX)
-                    update = shadowUpdateRotate16_90YX;
-                else
-                    update = shadowUpdateRotate16_90;
-                break;
-            case RR_Rotate_180:
-                update = shadowUpdateRotate16_180;
-                break;
-            case RR_Rotate_270:
-                if (useYX)
-                    update = shadowUpdateRotate16_270YX;
-                else
-                    update = shadowUpdateRotate16_270;
-                break;
-            default:
-                update = shadowUpdateRotate16;
-                break;
+    switch (priv->fix.type) {
+    case FB_TYPE_PACKED_PIXELS:
+        if (scrpriv->randr)
+            if (priv->var.bits_per_pixel == 16) {
+                switch (scrpriv->randr) {
+                case RR_Rotate_90:
+                    if (useYX)
+                        update = shadowUpdateRotate16_90YX;
+                    else
+                        update = shadowUpdateRotate16_90;
+                    break;
+                case RR_Rotate_180:
+                    update = shadowUpdateRotate16_180;
+                    break;
+                case RR_Rotate_270:
+                    if (useYX)
+                        update = shadowUpdateRotate16_270YX;
+                    else
+                        update = shadowUpdateRotate16_270;
+                    break;
+                default:
+                    update = shadowUpdateRotate16;
+                    break;
+                }
             }
-        }
+            else
+                update = shadowUpdateRotatePacked;
         else
-            update = shadowUpdateRotatePacked;
-    else
-        update = shadowUpdatePacked;
+            update = shadowUpdatePacked;
+        break;
+
+    case FB_TYPE_PLANES:
+        FatalError("Bitplanes are not yet supported\n");
+        break;
+
+    case FB_TYPE_INTERLEAVED_PLANES:
+        FatalError("Interleaved bitplanes are not yet supported\n");
+        break;
+
+    case FB_TYPE_TEXT:
+        FatalError("Text frame buffers are not yet supported\n");
+        break;
+
+    case FB_TYPE_VGA_PLANES:
+        FatalError("VGA planes are not yet supported\n");
+        break;
+
+    default:
+        FatalError("Unsupported frame buffer type %u\n", priv->fix.type);
+        break;
+    }
+
     return KdShadowSet(pScreen, scrpriv->randr, update, window);
 }
 
commit cfd10576812c36f5844805eb95ed1f2d093d1691
Author: Geert Uytterhoeven <geert at linux-m68k.org>
Date:   Sun Mar 10 21:03:44 2013 +0100

    Shadow: Add support for Amiga afb8
    
    Add support for Amiga-style bitplanes, with 8 bits per pixel.
    
    Signed-off-by: Geert Uytterhoeven <geert at linux-m68k.org>
    Acked-by: Keith Packard <keithp at keithp.com>

diff --git a/miext/shadow/Makefile.am b/miext/shadow/Makefile.am
index d2142ad..1db8a26 100644
--- a/miext/shadow/Makefile.am
+++ b/miext/shadow/Makefile.am
@@ -10,6 +10,7 @@ libshadow_la_SOURCES =		\
 	shadow.c		\
 	shadow.h		\
 	shafb4.c		\
+	shafb8.c		\
 	shalloc.c		\
 	shiplan2p4.c		\
 	shiplan2p8.c		\
diff --git a/miext/shadow/shadow.h b/miext/shadow/shadow.h
index f9ea6c4..421ae96 100644
--- a/miext/shadow/shadow.h
+++ b/miext/shadow/shadow.h
@@ -99,6 +99,9 @@ extern _X_EXPORT void
  shadowUpdateAfb4(ScreenPtr pScreen, shadowBufPtr pBuf);
 
 extern _X_EXPORT void
+ shadowUpdateAfb8(ScreenPtr pScreen, shadowBufPtr pBuf);
+
+extern _X_EXPORT void
  shadowUpdateIplan2p4(ScreenPtr pScreen, shadowBufPtr pBuf);
 
 extern _X_EXPORT void
diff --git a/miext/shadow/shafb8.c b/miext/shadow/shafb8.c
new file mode 100644
index 0000000..0835e16
--- /dev/null
+++ b/miext/shadow/shafb8.c
@@ -0,0 +1,143 @@
+/*
+ *
+ * Copyright © 2013 Geert Uytterhoeven
+ *
+ * Permission to use, copy, modify, distribute, and sell this software and its
+ * documentation for any purpose is hereby granted without fee, provided that
+ * the above copyright notice appear in all copies and that both that
+ * copyright notice and this permission notice appear in supporting
+ * documentation, and that the name of Geert Uytterhoeven not be used in
+ * advertising or publicity pertaining to distribution of the software without
+ * specific, written prior permission.  Geert Uytterhoeven makes no
+ * representations about the suitability of this software for any purpose.  It
+ * is provided "as is" without express or implied warranty.
+ *
+ * GEERT UYTTERHOEVEN DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+ * EVENT SHALL GEERT UYTTERHOEVEN BE LIABLE FOR ANY SPECIAL, INDIRECT OR
+ * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
+ * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
+ * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ * PERFORMANCE OF THIS SOFTWARE.
+ *
+ * Based on shpacked.c, which is Copyright © 2000 Keith Packard
+ */
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include <stdlib.h>
+
+#include    <X11/X.h>
+#include    "scrnintstr.h"
+#include    "windowstr.h"
+#include    <X11/fonts/font.h>
+#include    "dixfontstr.h"
+#include    <X11/fonts/fontstruct.h>
+#include    "mi.h"
+#include    "regionstr.h"
+#include    "globals.h"
+#include    "gcstruct.h"
+#include    "shadow.h"
+#include    "fb.h"
+#include    "c2p_core.h"
+
+
+    /*
+     *  Perform a full C2P step on 32 8-bit pixels, stored in 8 32-bit words
+     *  containing
+     *    - 32 8-bit chunky pixels on input
+     *    - permutated planar data (1 plane per 32-bit word) on output
+     */
+
+static void c2p_32x8(CARD32 d[8])
+{
+    transp8(d, 16, 4);
+    transp8(d, 8, 2);
+    transp8(d, 4, 1);
+    transp8(d, 2, 4);
+    transp8(d, 1, 2);
+}
+
+
+    /*
+     *  Store a full block of permutated planar data after c2p conversion
+     */
+
+static inline void store_afb8(void *dst, unsigned int stride,
+                              const CARD32 d[8])
+{
+    CARD8 *p = dst;
+
+    *(CARD32 *)p = d[7]; p += stride;
+    *(CARD32 *)p = d[5]; p += stride;
+    *(CARD32 *)p = d[3]; p += stride;
+    *(CARD32 *)p = d[1]; p += stride;
+    *(CARD32 *)p = d[6]; p += stride;
+    *(CARD32 *)p = d[4]; p += stride;
+    *(CARD32 *)p = d[2]; p += stride;
+    *(CARD32 *)p = d[0]; p += stride;
+}
+
+
+void
+shadowUpdateAfb8(ScreenPtr pScreen, shadowBufPtr pBuf)
+{
+    RegionPtr damage = shadowDamage(pBuf);
+    PixmapPtr pShadow = pBuf->pPixmap;
+    int nbox = RegionNumRects(damage);
+    BoxPtr pbox = RegionRects(damage);
+    FbBits *shaBase;
+    CARD32 *shaLine, *sha;
+    FbStride shaStride;
+    int scrLine;
+    _X_UNUSED int shaBpp, shaXoff, shaYoff;
+    int x, y, w, h;
+    int i, n;
+    CARD32 *win;
+    CARD32 off, winStride;
+    union {
+        CARD8 bytes[32];
+        CARD32 words[8];
+    } d;
+
+    fbGetDrawable(&pShadow->drawable, shaBase, shaStride, shaBpp, shaXoff,
+                  shaYoff);
+    if (sizeof(FbBits) != sizeof(CARD32))
+        shaStride = shaStride * sizeof(FbBits) / sizeof(CARD32);
+
+    while (nbox--) {
+        x = pbox->x1;
+        y = pbox->y1;
+        w = pbox->x2 - pbox->x1;
+        h = pbox->y2 - pbox->y1;
+
+        scrLine = x & -32;
+        shaLine = (CARD32 *)shaBase + y * shaStride + scrLine / sizeof(CARD32);
+
+        off = scrLine / 8;              /* byte offset in bitplane scanline */
+        n = ((x & 31) + w + 31) / 32;   /* number of c2p units in scanline */
+
+        while (h--) {
+            sha = shaLine;
+            win = (CARD32 *) (*pBuf->window) (pScreen,
+                                              y,
+                                              off,
+                                              SHADOW_WINDOW_WRITE,
+                                              &winStride,
+                                              pBuf->closure);
+            if (!win)
+                return;
+            for (i = 0; i < n; i++) {
+                memcpy(d.bytes, sha, sizeof(d.bytes));
+                c2p_32x8(d.words);
+                store_afb8(win++, winStride, d.words);
+                sha += sizeof(d.bytes) / sizeof(*sha);
+            }
+            shaLine += shaStride;
+            y++;
+        }
+        pbox++;
+    }
+}
commit a1b8e7f1e6118b611ba9d332b8763ee2b44f550c
Author: Geert Uytterhoeven <geert at linux-m68k.org>
Date:   Wed Mar 27 09:37:02 2013 +0100

    Shadow: Add support for Amiga afb4
    
    Add support for Amiga-style bitplanes, with 4 bits per pixel.
    
    Signed-off-by: Geert Uytterhoeven <geert at linux-m68k.org>
    Acked-by: Keith Packard <keithp at keithp.com>

diff --git a/miext/shadow/Makefile.am b/miext/shadow/Makefile.am
index 882463e..d2142ad 100644
--- a/miext/shadow/Makefile.am
+++ b/miext/shadow/Makefile.am
@@ -9,6 +9,7 @@ endif
 libshadow_la_SOURCES =		\
 	shadow.c		\
 	shadow.h		\
+	shafb4.c		\
 	shalloc.c		\
 	shiplan2p4.c		\
 	shiplan2p8.c		\
diff --git a/miext/shadow/shadow.h b/miext/shadow/shadow.h
index e190cd4..f9ea6c4 100644
--- a/miext/shadow/shadow.h
+++ b/miext/shadow/shadow.h
@@ -96,6 +96,9 @@ shadowInit(ScreenPtr pScreen, ShadowUpdateProc update, ShadowWindowProc window);
 extern _X_EXPORT void *shadowAlloc(int width, int height, int bpp);
 
 extern _X_EXPORT void
+ shadowUpdateAfb4(ScreenPtr pScreen, shadowBufPtr pBuf);
+
+extern _X_EXPORT void
  shadowUpdateIplan2p4(ScreenPtr pScreen, shadowBufPtr pBuf);
 
 extern _X_EXPORT void
diff --git a/miext/shadow/shafb4.c b/miext/shadow/shafb4.c
new file mode 100644
index 0000000..0724932
--- /dev/null
+++ b/miext/shadow/shafb4.c
@@ -0,0 +1,139 @@
+/*
+ *
+ * Copyright © 2013 Geert Uytterhoeven
+ *
+ * Permission to use, copy, modify, distribute, and sell this software and its
+ * documentation for any purpose is hereby granted without fee, provided that
+ * the above copyright notice appear in all copies and that both that
+ * copyright notice and this permission notice appear in supporting
+ * documentation, and that the name of Geert Uytterhoeven not be used in
+ * advertising or publicity pertaining to distribution of the software without
+ * specific, written prior permission.  Geert Uytterhoeven makes no
+ * representations about the suitability of this software for any purpose.  It
+ * is provided "as is" without express or implied warranty.
+ *
+ * GEERT UYTTERHOEVEN DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+ * EVENT SHALL GEERT UYTTERHOEVEN BE LIABLE FOR ANY SPECIAL, INDIRECT OR
+ * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
+ * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
+ * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ * PERFORMANCE OF THIS SOFTWARE.
+ *
+ * Based on shpacked.c, which is Copyright © 2000 Keith Packard
+ */
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include <stdlib.h>
+
+#include    <X11/X.h>
+#include    "scrnintstr.h"
+#include    "windowstr.h"
+#include    <X11/fonts/font.h>
+#include    "dixfontstr.h"
+#include    <X11/fonts/fontstruct.h>
+#include    "mi.h"
+#include    "regionstr.h"
+#include    "globals.h"
+#include    "gcstruct.h"
+#include    "shadow.h"
+#include    "fb.h"
+#include    "c2p_core.h"
+
+
+    /*
+     *  Perform a full C2P step on 32 4-bit pixels, stored in 4 32-bit words
+     *  containing
+     *    - 32 4-bit chunky pixels on input
+     *    - permutated planar data (1 plane per 32-bit word) on output
+     */
+
+static void c2p_32x4(CARD32 d[4])
+{
+    transp4(d, 16, 2);
+    transp4(d, 8, 1);
+    transp4(d, 4, 2);
+    transp4(d, 2, 1);
+    transp4(d, 1, 2);
+}
+
+
+    /*
+     *  Store a full block of permutated planar data after c2p conversion
+     */
+
+static inline void store_afb4(void *dst, unsigned int stride,
+                              const CARD32 d[4])
+{
+    CARD8 *p = dst;
+
+    *(CARD32 *)p = d[3]; p += stride;
+    *(CARD32 *)p = d[1]; p += stride;
+    *(CARD32 *)p = d[2]; p += stride;
+    *(CARD32 *)p = d[0]; p += stride;
+}
+
+
+void
+shadowUpdateAfb4(ScreenPtr pScreen, shadowBufPtr pBuf)
+{
+    RegionPtr damage = shadowDamage(pBuf);
+    PixmapPtr pShadow = pBuf->pPixmap;
+    int nbox = RegionNumRects(damage);
+    BoxPtr pbox = RegionRects(damage);
+    FbBits *shaBase;
+    CARD32 *shaLine, *sha;
+    FbStride shaStride;
+    int scrLine;
+    _X_UNUSED int shaBpp, shaXoff, shaYoff;
+    int x, y, w, h;
+    int i, n;
+    CARD32 *win;
+    CARD32 off, winStride;
+    union {
+        CARD8 bytes[16];
+        CARD32 words[4];
+    } d;
+
+    fbGetDrawable(&pShadow->drawable, shaBase, shaStride, shaBpp, shaXoff,
+                  shaYoff);
+    if (sizeof(FbBits) != sizeof(CARD32))
+        shaStride = shaStride * sizeof(FbBits) / sizeof(CARD32);
+
+    while (nbox--) {
+        x = pbox->x1;
+        y = pbox->y1;
+        w = pbox->x2 - pbox->x1;
+        h = pbox->y2 - pbox->y1;
+
+        scrLine = (x & -32) / 2;
+        shaLine = (CARD32 *)shaBase + y * shaStride + scrLine / sizeof(CARD32);
+
+        off = scrLine / 4;              /* byte offset in bitplane scanline */
+        n = ((x & 31) + w + 31) / 32;   /* number of c2p units in scanline */
+
+        while (h--) {
+            sha = shaLine;
+            win = (CARD32 *) (*pBuf->window) (pScreen,
+                                             y,
+                                             off,
+                                             SHADOW_WINDOW_WRITE,
+                                             &winStride,
+                                             pBuf->closure);
+            if (!win)
+                return;
+            for (i = 0; i < n; i++) {
+                memcpy(d.bytes, sha, sizeof(d.bytes));
+                c2p_32x4(d.words);
+                store_afb4(win++, winStride, d.words);
+                sha += sizeof(d.bytes) / sizeof(*sha);
+            }
+            shaLine += shaStride;
+            y++;
+        }
+        pbox++;
+    }
+}
commit d7181e567d1629c387b834da7eecdf618d14718e
Author: Geert Uytterhoeven <geert at linux-m68k.org>
Date:   Sun Mar 10 17:16:17 2013 +0100

    Shadow: Add support for Atari iplan2p8
    
    Add support for Atari-style interleaved bitplanes, with 2 bytes interleave
    and 8 bits per pixel.
    
    Signed-off-by: Geert Uytterhoeven <geert at linux-m68k.org>
    Acked-by: Keith Packard <keithp at keithp.com>

diff --git a/miext/shadow/Makefile.am b/miext/shadow/Makefile.am
index adb10bf..882463e 100644
--- a/miext/shadow/Makefile.am
+++ b/miext/shadow/Makefile.am
@@ -11,6 +11,7 @@ libshadow_la_SOURCES =		\
 	shadow.h		\
 	shalloc.c		\
 	shiplan2p4.c		\
+	shiplan2p8.c		\
 	shpacked.c		\
 	shplanar8.c		\
 	shplanar.c		\
diff --git a/miext/shadow/shadow.h b/miext/shadow/shadow.h
index d62903c..e190cd4 100644
--- a/miext/shadow/shadow.h
+++ b/miext/shadow/shadow.h
@@ -99,6 +99,9 @@ extern _X_EXPORT void
  shadowUpdateIplan2p4(ScreenPtr pScreen, shadowBufPtr pBuf);
 
 extern _X_EXPORT void
+ shadowUpdateIplan2p8(ScreenPtr pScreen, shadowBufPtr pBuf);
+
+extern _X_EXPORT void
  shadowUpdatePacked(ScreenPtr pScreen, shadowBufPtr pBuf);
 
 extern _X_EXPORT void
diff --git a/miext/shadow/shiplan2p8.c b/miext/shadow/shiplan2p8.c
new file mode 100644
index 0000000..55762f6
--- /dev/null
+++ b/miext/shadow/shiplan2p8.c
@@ -0,0 +1,137 @@
+/*
+ *
+ * Copyright © 2013 Geert Uytterhoeven
+ *
+ * Permission to use, copy, modify, distribute, and sell this software and its
+ * documentation for any purpose is hereby granted without fee, provided that
+ * the above copyright notice appear in all copies and that both that
+ * copyright notice and this permission notice appear in supporting
+ * documentation, and that the name of Geert Uytterhoeven not be used in
+ * advertising or publicity pertaining to distribution of the software without
+ * specific, written prior permission.  Geert Uytterhoeven makes no
+ * representations about the suitability of this software for any purpose.  It
+ * is provided "as is" without express or implied warranty.
+ *
+ * GEERT UYTTERHOEVEN DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+ * EVENT SHALL GEERT UYTTERHOEVEN BE LIABLE FOR ANY SPECIAL, INDIRECT OR
+ * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
+ * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
+ * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ * PERFORMANCE OF THIS SOFTWARE.
+ *
+ * Based on shpacked.c, which is Copyright © 2000 Keith Packard
+ */
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include <stdlib.h>
+
+#include    <X11/X.h>
+#include    "scrnintstr.h"
+#include    "windowstr.h"
+#include    <X11/fonts/font.h>
+#include    "dixfontstr.h"
+#include    <X11/fonts/fontstruct.h>
+#include    "mi.h"
+#include    "regionstr.h"
+#include    "globals.h"
+#include    "gcstruct.h"
+#include    "shadow.h"
+#include    "fb.h"
+#include    "c2p_core.h"
+
+
+    /*
+     *  Perform a full C2P step on 16 8-bit pixels, stored in 4 32-bit words
+     *  containing
+     *    - 16 8-bit chunky pixels on input
+     *    - permutated planar data (2 planes per 32-bit word) on output
+     */
+
+static void c2p_16x8(CARD32 d[4])
+{
+    transp4(d, 8, 2);
+    transp4(d, 1, 2);
+    transp4x(d, 16, 2);
+    transp4x(d, 2, 2);
+    transp4(d, 4, 1);
+}
+
+
+    /*
+     *  Store a full block of permutated iplan2p8 data after c2p conversion
+     */
+
+static inline void store_iplan2p8(void *dst, const CARD32 d[4])
+{
+    CARD32 *p = dst;
+
+    *p++ = d[1];
+    *p++ = d[3];
+    *p++ = d[0];
+    *p++ = d[2];
+}
+
+
+void
+shadowUpdateIplan2p8(ScreenPtr pScreen, shadowBufPtr pBuf)
+{
+    RegionPtr damage = shadowDamage(pBuf);
+    PixmapPtr pShadow = pBuf->pPixmap;
+    int nbox = RegionNumRects(damage);
+    BoxPtr pbox = RegionRects(damage);
+    FbBits *shaBase;
+    CARD16 *shaLine, *sha;
+    FbStride shaStride;
+    int scrLine;
+    _X_UNUSED int shaBpp, shaXoff, shaYoff;
+    int x, y, w, h;
+    int i, n;
+    CARD16 *win;
+    _X_UNUSED CARD32 winSize;
+    union {
+        CARD8 bytes[16];
+        CARD32 words[4];
+    } d;
+
+    fbGetDrawable(&pShadow->drawable, shaBase, shaStride, shaBpp, shaXoff,
+                  shaYoff);
+    shaStride *= sizeof(FbBits) / sizeof(CARD16);
+
+    while (nbox--) {
+        x = pbox->x1;
+        y = pbox->y1;
+        w = pbox->x2 - pbox->x1;
+        h = pbox->y2 - pbox->y1;
+
+        scrLine = x & -16;
+        shaLine = (CARD16 *)shaBase + y * shaStride + scrLine / sizeof(CARD16);
+
+        n = ((x & 15) + w + 15) / 16;   /* number of c2p units in scanline */
+
+        while (h--) {
+            sha = shaLine;
+            win = (CARD16 *) (*pBuf->window) (pScreen,
+                                              y,
+                                              scrLine,
+                                              SHADOW_WINDOW_WRITE,
+                                              &winSize,
+                                              pBuf->closure);
+            if (!win)
+                return;
+            for (i = 0; i < n; i++) {
+                memcpy(d.bytes, sha, sizeof(d.bytes));
+                c2p_16x8(d.words);
+                store_iplan2p8(win, d.words);
+                sha += sizeof(d.bytes) / sizeof(*sha);
+                win += sizeof(d.bytes) / sizeof(*win);
+            }
+            shaLine += shaStride;
+            y++;
+        }
+        pbox++;
+    }
+}
commit 3f7506b0fca72b2462b85bc4f613de809ae95859
Author: Geert Uytterhoeven <geert at linux-m68k.org>
Date:   Sun Mar 10 21:01:02 2013 +0100

    Shadow: Add support for Atari iplan2p4
    
    Add support for Atari-style interleaved bitplanes, with 2 bytes interleave
    and 4 bits per pixel.
    
    Signed-off-by: Geert Uytterhoeven <geert at linux-m68k.org>
    Acked-by: Keith Packard <keithp at keithp.com>

diff --git a/miext/shadow/Makefile.am b/miext/shadow/Makefile.am
index 30f7bda..adb10bf 100644
--- a/miext/shadow/Makefile.am
+++ b/miext/shadow/Makefile.am
@@ -10,6 +10,7 @@ libshadow_la_SOURCES =		\
 	shadow.c		\
 	shadow.h		\
 	shalloc.c		\
+	shiplan2p4.c		\
 	shpacked.c		\
 	shplanar8.c		\
 	shplanar.c		\
diff --git a/miext/shadow/shadow.h b/miext/shadow/shadow.h
index 83de22c..d62903c 100644
--- a/miext/shadow/shadow.h
+++ b/miext/shadow/shadow.h
@@ -96,6 +96,9 @@ shadowInit(ScreenPtr pScreen, ShadowUpdateProc update, ShadowWindowProc window);
 extern _X_EXPORT void *shadowAlloc(int width, int height, int bpp);
 
 extern _X_EXPORT void
+ shadowUpdateIplan2p4(ScreenPtr pScreen, shadowBufPtr pBuf);
+
+extern _X_EXPORT void
  shadowUpdatePacked(ScreenPtr pScreen, shadowBufPtr pBuf);
 
 extern _X_EXPORT void
diff --git a/miext/shadow/shiplan2p4.c b/miext/shadow/shiplan2p4.c
new file mode 100644
index 0000000..79ada99
--- /dev/null
+++ b/miext/shadow/shiplan2p4.c
@@ -0,0 +1,136 @@
+/*
+ *
+ * Copyright © 2013 Geert Uytterhoeven
+ *
+ * Permission to use, copy, modify, distribute, and sell this software and its
+ * documentation for any purpose is hereby granted without fee, provided that
+ * the above copyright notice appear in all copies and that both that
+ * copyright notice and this permission notice appear in supporting
+ * documentation, and that the name of Geert Uytterhoeven not be used in
+ * advertising or publicity pertaining to distribution of the software without
+ * specific, written prior permission.  Geert Uytterhoeven makes no
+ * representations about the suitability of this software for any purpose.  It
+ * is provided "as is" without express or implied warranty.
+ *
+ * GEERT UYTTERHOEVEN DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+ * EVENT SHALL GEERT UYTTERHOEVEN BE LIABLE FOR ANY SPECIAL, INDIRECT OR
+ * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
+ * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
+ * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ * PERFORMANCE OF THIS SOFTWARE.
+ *
+ * Based on shpacked.c, which is Copyright © 2000 Keith Packard
+ */
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include <stdlib.h>
+
+#include    <X11/X.h>
+#include    "scrnintstr.h"
+#include    "windowstr.h"
+#include    <X11/fonts/font.h>
+#include    "dixfontstr.h"
+#include    <X11/fonts/fontstruct.h>
+#include    "mi.h"
+#include    "regionstr.h"
+#include    "globals.h"
+#include    "gcstruct.h"
+#include    "shadow.h"
+#include    "fb.h"
+#include    "c2p_core.h"
+
+
+    /*
+     *  Perform a full C2P step on 16 4-bit pixels, stored in 2 32-bit words
+     *  containing
+     *    - 16 4-bit chunky pixels on input
+     *    - permutated planar data (2 planes per 32-bit word) on output
+     */
+
+static void c2p_16x4(CARD32 d[2])
+{
+    transp2(d, 8);
+    transp2(d, 2);
+    transp2x(d, 1);
+    transp2(d, 16);
+    transp2(d, 4);
+    transp2(d, 1);
+}
+
+
+    /*
+     *  Store a full block of iplan2p4 data after c2p conversion
+     */
+
+static inline void store_iplan2p4(void *dst, const CARD32 d[2])
+{
+    CARD32 *p = dst;
+
+    *p++ = d[0];
+    *p++ = d[1];
+}
+
+
+void
+shadowUpdateIplan2p4(ScreenPtr pScreen, shadowBufPtr pBuf)
+{
+    RegionPtr damage = shadowDamage(pBuf);
+    PixmapPtr pShadow = pBuf->pPixmap;
+    int nbox = RegionNumRects(damage);
+    BoxPtr pbox = RegionRects(damage);
+    FbBits *shaBase;
+    CARD16 *shaLine, *sha;
+    FbStride shaStride;
+    int scrLine;
+    _X_UNUSED int shaBpp, shaXoff, shaYoff;
+    int x, y, w, h;
+    int i, n;
+    CARD16 *win;
+    _X_UNUSED CARD32 winSize;
+    union {
+        CARD8 bytes[8];
+        CARD32 words[2];
+    } d;
+
+    fbGetDrawable(&pShadow->drawable, shaBase, shaStride, shaBpp, shaXoff,
+                  shaYoff);
+    shaStride *= sizeof(FbBits) / sizeof(CARD16);
+
+    while (nbox--) {
+        x = pbox->x1;
+        y = pbox->y1;
+        w = pbox->x2 - pbox->x1;
+        h = pbox->y2 - pbox->y1;
+
+        scrLine = (x & -16) / 2;
+        shaLine = (CARD16 *)shaBase + y * shaStride + scrLine / sizeof(CARD16);
+
+        n = ((x & 15) + w + 15) / 16;   /* number of c2p units in scanline */
+
+        while (h--) {
+            sha = shaLine;
+            win = (CARD16 *) (*pBuf->window) (pScreen,
+                                              y,
+                                              scrLine,
+                                              SHADOW_WINDOW_WRITE,
+                                              &winSize,
+                                              pBuf->closure);
+            if (!win)
+                return;
+            for (i = 0; i < n; i++) {
+                memcpy(d.bytes, sha, sizeof(d.bytes));
+                c2p_16x4(d.words);
+                store_iplan2p4(win, d.words);
+                sha += sizeof(d.bytes) / sizeof(*sha);
+                win += sizeof(d.bytes) / sizeof(*win);
+            }
+            shaLine += shaStride;
+            y++;
+        }
+        pbox++;
+    }
+}
commit 87af9ab7d52578b0ea315fc4f8dfd906d19755fb
Author: Geert Uytterhoeven <geert at linux-m68k.org>
Date:   Sun Mar 10 17:15:05 2013 +0100

    Shadow: Add c2p core
    
    Add Chunky-to-Planar core functionality, to be used by the Atari and Amiga
    (interleaved) bitplanes code.
    
    Signed-off-by: Geert Uytterhoeven <geert at linux-m68k.org>
    Acked-by: Keith Packard <keithp at keithp.com>

diff --git a/miext/shadow/c2p_core.h b/miext/shadow/c2p_core.h
new file mode 100644
index 0000000..252f93e
--- /dev/null
+++ b/miext/shadow/c2p_core.h
@@ -0,0 +1,184 @@
+/*
+ *  Fast C2P (Chunky-to-Planar) Conversion
+ *
+ *  Copyright (C) 2003-2008 Geert Uytterhoeven
+ *
+ *  NOTES:
+ *    - This code was inspired by Scout's C2P tutorial
+ *    - It assumes to run on a big endian system
+ *
+ *  Permission to use, copy, modify, distribute, and sell this software and its
+ *  documentation for any purpose is hereby granted without fee, provided that
+ *  the above copyright notice appear in all copies and that both that
+ *  copyright notice and this permission notice appear in supporting
+ *  documentation, and that the name of Geert Uytterhoeven not be used in
+ *  advertising or publicity pertaining to distribution of the software without
+ *  specific, written prior permission.  Geert Uytterhoeven makes no
+ *  representations about the suitability of this software for any purpose.  It
+ *  is provided "as is" without express or implied warranty.
+ *
+ *  GEERT UYTTERHOEVEN DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+ *  INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+ *  EVENT SHALL GEERT UYTTERHOEVEN BE LIABLE FOR ANY SPECIAL, INDIRECT OR
+ *  CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
+ *  DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
+ *  TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ *  PERFORMANCE OF THIS SOFTWARE.
+ */
+
+
+    /*
+     *  Basic transpose step
+     */
+
+static inline void _transp(CARD32 d[], unsigned int i1, unsigned int i2,
+                           unsigned int shift, CARD32 mask)
+{
+    CARD32 t = (d[i1] ^ (d[i2] >> shift)) & mask;
+
+    d[i1] ^= t;
+    d[i2] ^= t << shift;
+}
+
+
+extern void c2p_unsupported(void);
+
+static inline CARD32 get_mask(unsigned int n)
+{
+    switch (n) {
+    case 1:
+        return 0x55555555;
+
+    case 2:
+        return 0x33333333;
+
+    case 4:
+        return 0x0f0f0f0f;
+
+    case 8:
+        return 0x00ff00ff;
+
+    case 16:
+        return 0x0000ffff;
+    }
+
+    c2p_unsupported();
+    return 0;
+}
+
+
+    /*
+     *  Transpose operations on 8 32-bit words
+     */
+
+static inline void transp8(CARD32 d[], unsigned int n, unsigned int m)
+{
+    CARD32 mask = get_mask(n);
+
+    switch (m) {
+    case 1:
+        /* First n x 1 block */
+        _transp(d, 0, 1, n, mask);
+        /* Second n x 1 block */
+        _transp(d, 2, 3, n, mask);
+        /* Third n x 1 block */
+        _transp(d, 4, 5, n, mask);
+        /* Fourth n x 1 block */
+        _transp(d, 6, 7, n, mask);
+        return;
+
+    case 2:
+        /* First n x 2 block */
+        _transp(d, 0, 2, n, mask);
+        _transp(d, 1, 3, n, mask);
+        /* Second n x 2 block */
+        _transp(d, 4, 6, n, mask);
+        _transp(d, 5, 7, n, mask);
+        return;
+
+    case 4:
+        /* Single n x 4 block */
+        _transp(d, 0, 4, n, mask);
+        _transp(d, 1, 5, n, mask);
+        _transp(d, 2, 6, n, mask);
+        _transp(d, 3, 7, n, mask);
+        return;
+    }
+
+    c2p_unsupported();
+}
+
+
+    /*
+     *  Transpose operations on 4 32-bit words
+     */
+
+static inline void transp4(CARD32 d[], unsigned int n, unsigned int m)
+{
+    CARD32 mask = get_mask(n);
+
+    switch (m) {
+    case 1:
+        /* First n x 1 block */
+        _transp(d, 0, 1, n, mask);
+        /* Second n x 1 block */
+        _transp(d, 2, 3, n, mask);
+        return;
+
+    case 2:
+        /* Single n x 2 block */
+        _transp(d, 0, 2, n, mask);
+        _transp(d, 1, 3, n, mask);
+        return;
+    }
+
+    c2p_unsupported();
+}
+
+
+    /*
+     *  Transpose operations on 4 32-bit words (reverse order)
+     */
+
+static inline void transp4x(CARD32 d[], unsigned int n, unsigned int m)
+{
+    CARD32 mask = get_mask(n);
+
+    switch (m) {
+    case 2:
+        /* Single n x 2 block */
+        _transp(d, 2, 0, n, mask);
+        _transp(d, 3, 1, n, mask);
+        return;
+    }
+
+    c2p_unsupported();
+}
+
+
+    /*
+     *  Transpose operations on 2 32-bit words
+     */
+
+static inline void transp2(CARD32 d[], unsigned int n)
+{
+    CARD32 mask = get_mask(n);
+
+    /* Single n x 1 block */
+    _transp(d, 0, 1, n, mask);
+    return;
+}
+
+
+    /*
+     *  Transpose operations on 2 32-bit words (reverse order)
+     */
+
+static inline void transp2x(CARD32 d[], unsigned int n)
+{
+    CARD32 mask = get_mask(n);
+
+    /* Single n x 1 block */
+    _transp(d, 1, 0, n, mask);
+    return;
+}
commit 4ee2566c3e420a717be36f79126a14e15edac30f
Author: Geert Uytterhoeven <geert at linux-m68k.org>
Date:   Tue Mar 12 18:10:40 2013 +0100

    Xfbdev: Treat 1 bpp pseudocolor as monochrome
    
    miCreateDefColormap() only preallocates black and white pixels if
    depth > 1.
    Hence override the visual, so fbdevCreateColormap() takes care of it.
    
    Signed-off-by: Geert Uytterhoeven <geert at linux-m68k.org>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/kdrive/fbdev/fbdev.c b/hw/kdrive/fbdev/fbdev.c
index 0082575..ebbfeb9 100644
--- a/hw/kdrive/fbdev/fbdev.c
+++ b/hw/kdrive/fbdev/fbdev.c
@@ -216,11 +216,13 @@ fbdevScreenInitialize(KdScreenInfo * screen, FbdevScrPriv * scrpriv)
         screen->fb.visuals = (1 << StaticGray);
         break;
     case FB_VISUAL_PSEUDOCOLOR:
-        if (gray) {
-            screen->fb.visuals = (1 << StaticGray);
+        screen->fb.visuals = (1 << StaticGray);
+        if (priv->var.bits_per_pixel == 1) {
+            /* Override to monochrome, to have preallocated black/white */
+            priv->fix.visual = FB_VISUAL_MONO01;
+        } else if (gray) {
             /* could also support GrayScale, but what's the point? */
-        }
-        else {
+        } else {
             screen->fb.visuals = ((1 << StaticGray) |
                                   (1 << GrayScale) |
                                   (1 << StaticColor) |
commit 6dfb94a891ed445f47832ba1364fcbf1de018f4a
Author: Geert Uytterhoeven <geert at linux-m68k.org>
Date:   Tue Mar 12 14:16:10 2013 +0100

    Xfbdev: Add support for monochrome visuals
    
    Monochrome supports StaticGray, with hardcoded black and white pixels.
    
    Signed-off-by: Geert Uytterhoeven <geert at linux-m68k.org>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/kdrive/fbdev/fbdev.c b/hw/kdrive/fbdev/fbdev.c
index 7b29f42..0082575 100644
--- a/hw/kdrive/fbdev/fbdev.c
+++ b/hw/kdrive/fbdev/fbdev.c
@@ -211,6 +211,10 @@ fbdevScreenInitialize(KdScreenInfo * screen, FbdevScrPriv * scrpriv)
         priv->fix.line_length = (priv->var.xres_virtual * depth + 7) / 8;
 
     switch (priv->fix.visual) {
+    case FB_VISUAL_MONO01:
+    case FB_VISUAL_MONO10:
+        screen->fb.visuals = (1 << StaticGray);
+        break;
     case FB_VISUAL_PSEUDOCOLOR:
         if (gray) {
             screen->fb.visuals = (1 << StaticGray);
@@ -577,6 +581,26 @@ fbdevCreateColormap(ColormapPtr pmap)
     xColorItem *pdefs;
 
     switch (priv->fix.visual) {
+    case FB_VISUAL_MONO01:
+        pScreen->whitePixel = 0;
+        pScreen->blackPixel = 1;
+        pmap->red[0].co.local.red = 65535;
+        pmap->red[0].co.local.green = 65535;
+        pmap->red[0].co.local.blue = 65535;
+        pmap->red[1].co.local.red = 0;
+        pmap->red[1].co.local.green = 0;
+        pmap->red[1].co.local.blue = 0;
+        return TRUE;
+    case FB_VISUAL_MONO10:
+        pScreen->blackPixel = 0;
+        pScreen->whitePixel = 1;
+        pmap->red[0].co.local.red = 0;
+        pmap->red[0].co.local.green = 0;
+        pmap->red[0].co.local.blue = 0;
+        pmap->red[1].co.local.red = 65535;
+        pmap->red[1].co.local.green = 65535;
+        pmap->red[1].co.local.blue = 65535;
+        return TRUE;
     case FB_VISUAL_STATIC_PSEUDOCOLOR:
         pVisual = pmap->pVisual;
         nent = pVisual->ColormapEntries;
commit 1049b32166760bdc00106625e213d31a8fc60bad
Author: Geert Uytterhoeven <geert at linux-m68k.org>
Date:   Tue Mar 12 14:19:25 2013 +0100

    Xfbdev: Handle unset fix.line_length
    
    Older frame buffer devices may not fill in fix.line_length, in which
    case it must be calculated by the application.
    
    Signed-off-by: Geert Uytterhoeven <geert at linux-m68k.org>

diff --git a/hw/kdrive/fbdev/fbdev.c b/hw/kdrive/fbdev/fbdev.c
index a8d36c6..7b29f42 100644
--- a/hw/kdrive/fbdev/fbdev.c
+++ b/hw/kdrive/fbdev/fbdev.c
@@ -206,6 +206,10 @@ fbdevScreenInitialize(KdScreenInfo * screen, FbdevScrPriv * scrpriv)
     depth = priv->var.bits_per_pixel;
     gray = priv->var.grayscale;
 
+    /* Calculate fix.line_length if it's zero */
+    if (!priv->fix.line_length)
+        priv->fix.line_length = (priv->var.xres_virtual * depth + 7) / 8;
+
     switch (priv->fix.visual) {
     case FB_VISUAL_PSEUDOCOLOR:
         if (gray) {
commit 5c509c360d97bea78ef461596ab4b7bde69020ac
Author: Geert Uytterhoeven <geert at linux-m68k.org>
Date:   Fri Feb 22 13:21:28 2013 +0100

    Xfbdev: Make char *fbdevDevicePath const
    
    This fixes:
    
    hw/kdrive/fbdev/fbdev.c: In function 'fbdevInitialize':
    hw/kdrive/fbdev/fbdev.c:41:25: warning: assignment discards 'const' qualifier from pointer target type [enabled by default]
    
    Signed-off-by: Geert Uytterhoeven <geert at linux-m68k.org>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/kdrive/fbdev/fbdev.c b/hw/kdrive/fbdev/fbdev.c
index d6fcf1a..a8d36c6 100644
--- a/hw/kdrive/fbdev/fbdev.c
+++ b/hw/kdrive/fbdev/fbdev.c
@@ -30,7 +30,7 @@
 
 extern int KdTsPhyScreen;
 
-char *fbdevDevicePath = NULL;
+const char *fbdevDevicePath = NULL;
 
 static Bool
 fbdevInitialize(KdCardInfo * card, FbdevPriv * priv)
diff --git a/hw/kdrive/fbdev/fbdev.h b/hw/kdrive/fbdev/fbdev.h
index 0706f4e..f3f7aec 100644
--- a/hw/kdrive/fbdev/fbdev.h
+++ b/hw/kdrive/fbdev/fbdev.h
@@ -49,7 +49,7 @@ typedef struct _fbdevScrPriv {
 } FbdevScrPriv;
 
 extern KdCardFuncs fbdevFuncs;
-extern char *fbdevDevicePath;
+extern const char *fbdevDevicePath;
 
 Bool
  fbdevCardInit(KdCardInfo * card);
commit b08afbc53c1d583c3913b92e67db44823077b112
Author: Geert Uytterhoeven <geert at linux-m68k.org>
Date:   Tue Mar 12 15:20:00 2013 +0100

    KDrive: Bail out if screen initialization failed
    
    Else we may get a segmentation fault later.
    
    Signed-off-by: Geert Uytterhoeven <geert at linux-m68k.org>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/kdrive/src/kdrive.c b/hw/kdrive/src/kdrive.c
index 7d9bf9d..1899a27 100644
--- a/hw/kdrive/src/kdrive.c
+++ b/hw/kdrive/src/kdrive.c
@@ -943,7 +943,8 @@ KdInitScreen(ScreenInfo * pScreenInfo,
 {
     KdCardInfo *card = screen->card;
 
-    (*card->cfuncs->scrinit) (screen);
+    if (!(*card->cfuncs->scrinit) (screen))
+        FatalError("Screen initialization failed!\n");
 
     if (!card->cfuncs->initAccel)
         screen->dumb = TRUE;
commit e7045c9dd208a1afe36526ab21ef15f8b01c8bd2
Author: Geert Uytterhoeven <geert at linux-m68k.org>
Date:   Sat Feb 23 20:09:22 2013 +0100

    test/input: Fix double-aligned test in dix_valuator_alloc() on m68k
    
    On m68k, doubles are not 64-bit aligned, just like on i386 and sh.
    
    Signed-off-by: Geert Uytterhoeven <geert at linux-m68k.org>

diff --git a/test/input.c b/test/input.c
index be988a4..df20f82 100644
--- a/test/input.c
+++ b/test/input.c
@@ -1384,7 +1384,7 @@ dix_valuator_alloc(void)
 
         assert(v);
         assert(v->numAxes == num_axes);
-#if !defined(__i386__) && !defined(__sh__)
+#if !defined(__i386__) && !defined(__m68k__) && !defined(__sh__)
         /* must be double-aligned on 64 bit */
         assert(((void *) v->axisVal - (void *) v) % sizeof(double) == 0);
         assert(((void *) v->axes - (void *) v) % sizeof(double) == 0);
commit 8bb0616cc2799c2c34448da6337ea8cb9438cda7
Author: Geert Uytterhoeven <geert at linux-m68k.org>
Date:   Fri Feb 22 21:10:07 2013 +0100

    miext/shadow/shpacked.c: Remove unused PickBit() define
    
    Signed-off-by: Geert Uytterhoeven <geert at linux-m68k.org>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/miext/shadow/shpacked.c b/miext/shadow/shpacked.c
index d2b2e5e..5ef18f8 100644
--- a/miext/shadow/shpacked.c
+++ b/miext/shadow/shpacked.c
@@ -98,7 +98,6 @@ shadowUpdatePacked(ScreenPtr pScreen, shadowBufPtr pBuf)
                     i = width;
                 width -= i;
                 scr += i;
-#define PickBit(a,i)	(((a) >> (i)) & 1)
                 memcpy(win, sha, i * sizeof(FbBits));
                 sha += i;
             }
commit 6ca03b9161d33b1d2b55a3a1a913cf88deb2343f
Author: Dave Airlie <airlied at gmail.com>
Date:   Wed Apr 10 16:09:01 2013 +1000

    xf86: fix flush input to work with Linux evdev devices.
    
    So when we VT switch back and attempt to flush the input devices,
    we don't succeed because evdev won't return part of an event,
    since we were only asking for 4 bytes, we'd only get -EINVAL back.
    
    This could later cause events to be flushed that we shouldn't have
    gotten.
    
    This is a fix for CVE-2013-1940.
    
    Signed-off-by: Dave Airlie <airlied at redhat.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/xfree86/os-support/shared/posix_tty.c b/hw/xfree86/os-support/shared/posix_tty.c
index ab3757a..4d08c1e 100644
--- a/hw/xfree86/os-support/shared/posix_tty.c
+++ b/hw/xfree86/os-support/shared/posix_tty.c
@@ -421,7 +421,8 @@ xf86FlushInput(int fd)
 {
     fd_set fds;
     struct timeval timeout;
-    char c[4];
+    /* this needs to be big enough to flush an evdev event. */
+    char c[256];
 
     DebugF("FlushingSerial\n");
     if (tcflush(fd, TCIFLUSH) == 0)
commit ddc149beaf708e84fb5573c4322d4f859c517917
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Feb 27 18:50:46 2012 +1000

    Stop the shouting
    
    Meanwhile, here in the future lowercase letters have been invented.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/Xext/xvmain.c b/Xext/xvmain.c
index c2860b8..0c5dc9b 100644
--- a/Xext/xvmain.c
+++ b/Xext/xvmain.c
@@ -156,8 +156,8 @@ XvExtensionInit(void)
     if (!dixRegisterPrivateKey(&XvScreenKeyRec, PRIVATE_SCREEN, 0))
         return;
 
-    /* LOOK TO SEE IF ANY SCREENS WERE INITIALIZED; IF NOT THEN
-       INIT GLOBAL VARIABLES SO THE EXTENSION CAN FUNCTION */
+    /* Look to see if any screens were initialized; if not then
+       init global variables so the extension can function */
     if (XvScreenGeneration != serverGeneration) {
         if (!CreateResourceTypes()) {
             ErrorF("XvExtensionInit: Unable to allocate resource types\n");
commit 27356a45b4f6bad4d0bbf356e6d976d0c8dd257b
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Feb 27 17:22:16 2012 +1000

    dix: only allocate unused classes for master devices
    
    Slave devices don't need these and the matching code in CloseDevice() has a
    IsMaster() condition on freeing these, causing a leak.
    
    ==16111== 384 bytes in 4 blocks are definitely lost in loss record 72 of 105
    ==16111==    at 0x4C28BB4: calloc (vg_replace_malloc.c:467)
    ==16111==    by 0x42AEE2: AllocDevicePair (devices.c:2707)
    ==16111==    by 0x4BAA27: AllocXTestDevice (xtest.c:617)
    ==16111==    by 0x4BA89A: InitXTestDevices (xtest.c:570)
    ==16111==    by 0x425F5E: InitCoreDevices (devices.c:690)
    ==16111==    by 0x5ACB2D: main (main.c:257)
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/devices.c b/dix/devices.c
index be236dd..5f98afc 100644
--- a/dix/devices.c
+++ b/dix/devices.c
@@ -2766,9 +2766,10 @@ AllocDevicePair(ClientPtr client, const char *name,
     keyboard->type = (master) ? MASTER_KEYBOARD : SLAVE;
 
     /* The ClassesRec stores the device classes currently not used. */
-    pointer->unused_classes = calloc(1, sizeof(ClassesRec));
-
-    keyboard->unused_classes = calloc(1, sizeof(ClassesRec));
+    if (IsMaster(pointer)) {
+        pointer->unused_classes = calloc(1, sizeof(ClassesRec));
+        keyboard->unused_classes = calloc(1, sizeof(ClassesRec));
+    }
 
     *ptr = pointer;
 
commit 98b94c36d6b1d286bbd4cb414e54b4b95a1484b0
Author: Maarten Lankhorst <maarten.lankhorst at canonical.com>
Date:   Mon Apr 15 16:53:48 2013 +0200

    dix: copy event in TouchConvertToPointerEvent correctly
    
    Fixes reading random memory read beyond the end of original event.
    
    sizeof device_event: 424
    sizeof internal_event: 2800
    
    Signed-off-by: Maarten Lankhorst <maarten.lankhorst at canonical.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/touch.c b/dix/touch.c
index 891cc78..3027bbb 100644
--- a/dix/touch.c
+++ b/dix/touch.c
@@ -620,14 +620,14 @@ TouchConvertToPointerEvent(const InternalEvent *event,
     BUG_WARN_MSG(!(event->device_event.flags & TOUCH_POINTER_EMULATED),
                  "Non-emulating touch event\n");
 
-    *motion_event = *event;
+    motion_event->device_event = event->device_event;
     motion_event->any.type = ET_Motion;
     motion_event->device_event.detail.button = 0;
     motion_event->device_event.flags = XIPointerEmulated;
 
     if (nevents > 1) {
         BUG_RETURN_VAL(!button_event, 0);
-        *button_event = *event;
+        button_event->device_event = event->device_event;
         button_event->any.type = ptrtype;
         button_event->device_event.flags = XIPointerEmulated;
         /* detail is already correct */
commit 4bff442ec5aa4b93a3f5c11782d4b7b9d1ae13ac
Author: Knut Petersen <Knut_Petersen at t-online.de>
Date:   Tue Feb 26 07:52:59 2013 +0100

    Never try to execute BellProcPtr NULL.
    
    This prevents xts XI/XDeviceBell-2 test
    from segfaulting the server.
    
    Signed-off-by: Knut Petersen <Knut_Petersen at t-online.de>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xi/devbell.c b/Xi/devbell.c
index c75b94d..202c8de 100644
--- a/Xi/devbell.c
+++ b/Xi/devbell.c
@@ -142,7 +142,8 @@ ProcXDeviceBell(ClientPtr client)
         newpercent = base + newpercent;
     else
         newpercent = base - newpercent + stuff->percent;
+    if (proc == NULL)
+        return BadValue;
     (*proc) (newpercent, dev, ctrl, class);
-
     return Success;
 }
commit 9003399708936481083424b4ff8f18a16b88b7b3
Author: Rui Matos <tiagomatos at gmail.com>
Date:   Sat Apr 13 04:22:54 2013 +0200

    Xi: fix swapped grab mode args for keyboard devices in XIGrabDevice
    
    The protocol says that the grab_mode argument applies to the device
    being grabbed and paired_device_mode to the paired master
    device. GrabDevice() however takes in a pointer mode and a keyboard
    mode and so we have to swap the values according the type of device
    being grabbed.
    
    Signed-off-by: Rui Matos <tiagomatos at gmail.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xi/xigrabdev.c b/Xi/xigrabdev.c
index 09186e8..63d95bc 100644
--- a/Xi/xigrabdev.c
+++ b/Xi/xigrabdev.c
@@ -67,6 +67,8 @@ ProcXIGrabDevice(ClientPtr client)
     uint8_t status;
     GrabMask mask = { 0 };
     int mask_len;
+    unsigned int keyboard_mode;
+    unsigned int pointer_mode;
 
     REQUEST(xXIGrabDeviceReq);
     REQUEST_AT_LEAST_SIZE(xXIGrabDeviceReq);
@@ -78,6 +80,15 @@ ProcXIGrabDevice(ClientPtr client)
     if (!IsMaster(dev))
         stuff->paired_device_mode = GrabModeAsync;
 
+    if (IsKeyboardDevice(dev)) {
+        keyboard_mode = stuff->grab_mode;
+        pointer_mode = stuff->paired_device_mode;
+    }
+    else {
+        keyboard_mode = stuff->paired_device_mode;
+        pointer_mode = stuff->grab_mode;
+    }
+
     if (XICheckInvalidMaskBits(client, (unsigned char *) &stuff[1],
                                stuff->mask_len * 4) != Success)
         return BadValue;
@@ -91,8 +102,8 @@ ProcXIGrabDevice(ClientPtr client)
     xi2mask_set_one_mask(mask.xi2mask, dev->id, (unsigned char *) &stuff[1],
                          mask_len);
 
-    ret = GrabDevice(client, dev, stuff->grab_mode,
-                     stuff->paired_device_mode,
+    ret = GrabDevice(client, dev, pointer_mode,
+                     keyboard_mode,
                      stuff->grab_window,
                      stuff->owner_events,
                      stuff->time,
commit d16284687ddeffde32a561b8c67b2e2e3d66aeaa
Author: Bryce Harrington <bryce at canonical.com>
Date:   Wed Apr 10 23:05:40 2013 -0700

    xfree86: Revert workaround for drm race condition.
    
    Revert 70739e817b2d64bc020ea491f23a3574bdb6155e and mostly revert
    c31eac647a9ecf0fb20dc98266cadf0ba923ba14.
    
    Further investigation shows the encountered race condition is between
    lightdm and plymouth-splash, as implemented in the Ubuntu distribution
    within the limitations of upstart's job coordination logic, and can (and
    should) be fixed within those limiations.  Not in xserver itself.
    
    This leaves some of the diagnostic improvements from the recent patch
    series, in case others run into a similar situation.
    
    Signed-off-by: Bryce Harrington <bryce at canonical.com>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/xfree86/os-support/linux/lnx_platform.c b/hw/xfree86/os-support/linux/lnx_platform.c
index 9b92d0c..bd060c9 100644
--- a/hw/xfree86/os-support/linux/lnx_platform.c
+++ b/hw/xfree86/os-support/linux/lnx_platform.c
@@ -26,35 +26,17 @@ get_drm_info(struct OdevAttributes *attribs, char *path)
     char *buf;
     int fd;
     int err = 0;
-    int tries = 0;
 
     fd = open(path, O_RDWR, O_CLOEXEC);
     if (fd == -1)
         return FALSE;
 
-    while (tries++ < 200) {
-	sv.drm_di_major = 1;
-	sv.drm_di_minor = 4;
-	sv.drm_dd_major = -1;       /* Don't care */
-	sv.drm_dd_minor = -1;       /* Don't care */
-
-	err = drmSetInterfaceVersion(fd, &sv);
-	if (!err) {
-	    if (tries > 1)
-		LogMessage(X_INFO, "setversion 1.4 succeeded on try #%d\n", tries);
-	    break;
-	} if (err == -EACCES) {
-	    if (tries % 500 == 0)
-		LogMessage(X_INFO, "waiting on drm device...\n");
-	} else {
-	    break;
-	}
-
-	usleep(10000);
-
-	if (!drmSetMaster(fd))
-	    LogMessage(X_INFO, "drmSetMaster succeeded\n");
-    }
+    sv.drm_di_major = 1;
+    sv.drm_di_minor = 4;
+    sv.drm_dd_major = -1;       /* Don't care */
+    sv.drm_dd_minor = -1;       /* Don't care */
+
+    err = drmSetInterfaceVersion(fd, &sv);
     if (err) {
         ErrorF("setversion 1.4 failed: %s\n", strerror(-err));
 	goto out;
commit 131f883f85b9b734e5e5652f16ba1d3b5f4de12f
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Apr 12 09:14:53 2013 +1000

    xfree86: change a log message
    
    This path is technically executed through config/udev, but having two
    messages in the form "config/udev: Adding drm device" makes it appear as if
    the udev filters are wrong and it's trying to add the same device twice. In
    fact, it's only one device, only added once, but a duplicate log message.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Dave Airlie <airlied at redhat.com>

diff --git a/hw/xfree86/os-support/linux/lnx_platform.c b/hw/xfree86/os-support/linux/lnx_platform.c
index 444f8f5..9b92d0c 100644
--- a/hw/xfree86/os-support/linux/lnx_platform.c
+++ b/hw/xfree86/os-support/linux/lnx_platform.c
@@ -140,8 +140,7 @@ xf86PlatformDeviceProbe(struct OdevAttributes *attribs)
     if (i != xf86_num_platform_devices)
         goto out_free;
 
-    LogMessage(X_INFO, "config/udev: Adding drm device (%s)\n",
-               path);
+    LogMessage(X_INFO, "xfree86: Adding drm device (%s)\n", path);
 
     ret = get_drm_info(attribs, path);
     if (ret == FALSE)
commit 22cab8a28a433d03a4e6ba97f9a160271d73cb52
Author: Dave Airlie <airlied at gmail.com>
Date:   Wed Apr 10 16:32:15 2013 +1000

    xf86: don't hotplug output devices while VT switched.
    
    We don't want to hotplug output devices while we are VT switched,
    as we get races between multiple X servers on the device open, and
    drm device master status. This just queues device opens until we return
    from VT switch.
    
    Reviewed-by: Chris Wilson <chris at chris-wilson.co.uk>
    Signed-off-by: Dave Airlie <airlied at redhat.com>

diff --git a/hw/xfree86/common/xf86Events.c b/hw/xfree86/common/xf86Events.c
index 4c59adb..ea18420 100644
--- a/hw/xfree86/common/xf86Events.c
+++ b/hw/xfree86/common/xf86Events.c
@@ -84,6 +84,7 @@
 #include "dpmsproc.h"
 #endif
 
+#include "xf86platformBus.h"
 /*
  * This is a toggling variable:
  *  FALSE = No VT switching keys have been pressed last time around
@@ -560,6 +561,9 @@ xf86VTSwitch(void)
         for (ih = InputHandlers; ih; ih = ih->next)
             xf86EnableInputHandler(ih);
 
+        /* check for any new output devices */
+        xf86platformVTProbe();
+
         OsReleaseSIGIO();
     }
 }
diff --git a/hw/xfree86/common/xf86platformBus.c b/hw/xfree86/common/xf86platformBus.c
index 5866333..9034dad 100644
--- a/hw/xfree86/common/xf86platformBus.c
+++ b/hw/xfree86/common/xf86platformBus.c
@@ -113,6 +113,11 @@ xf86_get_platform_device_attrib(struct xf86_platform_device *device, int attrib_
     return NULL;
 }
 
+Bool
+xf86_get_platform_device_unowned(int index)
+{
+    return xf86_platform_devices[index].attribs->unowned;
+}
 
 /*
  * xf86IsPrimaryPlatform() -- return TRUE if primary device
@@ -498,4 +503,18 @@ xf86platformRemoveDevice(int index)
  out:
     return;
 }
+
+/* called on return from VT switch to find any new devices */
+void xf86platformVTProbe(void)
+{
+    int i;
+
+    for (i = 0; i < xf86_num_platform_devices; i++) {
+        if (xf86_platform_devices[i].attribs->unowned == FALSE)
+            continue;
+
+        xf86_platform_devices[i].attribs->unowned = FALSE;
+        xf86PlatformReprobeDevice(i, xf86_platform_devices[i].attribs);
+    }
+}
 #endif
diff --git a/hw/xfree86/common/xf86platformBus.h b/hw/xfree86/common/xf86platformBus.h
index 49afc24..4e17578 100644
--- a/hw/xfree86/common/xf86platformBus.h
+++ b/hw/xfree86/common/xf86platformBus.h
@@ -46,6 +46,8 @@ extern int
 xf86_remove_platform_device(int dev_index);
 extern Bool
 xf86_add_platform_device_attrib(int index, int attrib_id, char *attrib_str);
+extern Bool
+xf86_get_platform_device_unowned(int index);
 
 extern int
 xf86platformAddDevice(int index);
@@ -59,6 +61,8 @@ xf86PlatformDeviceCheckBusID(struct xf86_platform_device *device, const char *bu
 
 extern _X_EXPORT int
 xf86PlatformMatchDriver(char *matches[], int nmatches);
+
+extern void xf86platformVTProbe(void);
 #endif
 
 #endif
diff --git a/hw/xfree86/os-support/linux/lnx_platform.c b/hw/xfree86/os-support/linux/lnx_platform.c
index 444f8f5..2a04f34 100644
--- a/hw/xfree86/os-support/linux/lnx_platform.c
+++ b/hw/xfree86/os-support/linux/lnx_platform.c
@@ -20,7 +20,7 @@
 #include "hotplug.h"
 
 static Bool
-get_drm_info(struct OdevAttributes *attribs, char *path)
+get_drm_info(struct OdevAttributes *attribs, char *path, int delayed_index)
 {
     drmSetVersion sv;
     char *buf;
@@ -60,10 +60,14 @@ get_drm_info(struct OdevAttributes *attribs, char *path)
 	goto out;
     }
 
-    xf86_add_platform_device(attribs);
+    /* for a delayed probe we've already added the device */
+    if (delayed_index == -1) {
+            xf86_add_platform_device(attribs);
+            delayed_index = xf86_num_platform_devices - 1;
+    }
 
     buf = drmGetBusid(fd);
-    xf86_add_platform_device_attrib(xf86_num_platform_devices - 1,
+    xf86_add_platform_device_attrib(delayed_index,
                                     ODEV_ATTRIB_BUSID, buf);
     drmFreeBusid(buf);
 out:
@@ -113,6 +117,23 @@ xf86PlatformDeviceCheckBusID(struct xf86_platform_device *device, const char *bu
 }
 
 void
+xf86PlatformReprobeDevice(int index, struct OdevAttributes *attribs)
+{
+    Bool ret;
+    char *dpath;
+    dpath = xf86_get_platform_attrib(index, ODEV_ATTRIB_PATH);
+
+    ret = get_drm_info(attribs, dpath, index);
+    if (ret == FALSE) {
+        xf86_remove_platform_device(index);
+        return;
+    }
+    ret = xf86platformAddDevice(index);
+    if (ret == -1)
+        xf86_remove_platform_device(index);
+}
+
+void
 xf86PlatformDeviceProbe(struct OdevAttributes *attribs)
 {
     struct OdevAttribute *attrib;
@@ -143,7 +164,15 @@ xf86PlatformDeviceProbe(struct OdevAttributes *attribs)
     LogMessage(X_INFO, "config/udev: Adding drm device (%s)\n",
                path);
 
-    ret = get_drm_info(attribs, path);
+    if (!xf86VTOwner()) {
+            /* if we don't currently own the VT then don't probe the device,
+               just mark it as unowned for later use */
+            attribs->unowned = TRUE;
+            xf86_add_platform_device(attribs);
+            return;
+    }
+
+    ret = get_drm_info(attribs, path, -1);
     if (ret == FALSE)
         goto out_free;
 
@@ -162,6 +191,9 @@ void NewGPUDeviceRequest(struct OdevAttributes *attribs)
     if (old_num == xf86_num_platform_devices)
         return;
 
+    if (xf86_get_platform_device_unowned(xf86_num_platform_devices - 1) == TRUE)
+        return;
+
     ret = xf86platformAddDevice(xf86_num_platform_devices-1);
     if (ret == -1)
         xf86_remove_platform_device(xf86_num_platform_devices-1);
@@ -195,7 +227,10 @@ void DeleteGPUDeviceRequest(struct OdevAttributes *attribs)
 
     ErrorF("xf86: remove device %d %s\n", index, syspath);
 
-    xf86platformRemoveDevice(index);
+    if (xf86_get_platform_device_unowned(index) == TRUE)
+            xf86_remove_platform_device(index);
+    else
+            xf86platformRemoveDevice(index);
 out:
     config_odev_free_attribute_list(attribs);
 }
diff --git a/hw/xfree86/os-support/xf86_OSproc.h b/hw/xfree86/os-support/xf86_OSproc.h
index ea2b16e..6be5946 100644
--- a/hw/xfree86/os-support/xf86_OSproc.h
+++ b/hw/xfree86/os-support/xf86_OSproc.h
@@ -223,6 +223,9 @@ extern _X_EXPORT void xf86InitVidMem(void);
 #include "hotplug.h"
 void
 xf86PlatformDeviceProbe(struct OdevAttributes *attribs);
+
+void
+xf86PlatformReprobeDevice(int index, struct OdevAttributes *attribs);
 #endif
 
 _XFUNCPROTOEND
diff --git a/include/hotplug.h b/include/hotplug.h
index 2a95b45..29a22c4 100644
--- a/include/hotplug.h
+++ b/include/hotplug.h
@@ -40,6 +40,7 @@ struct OdevAttribute {
 
 struct OdevAttributes {
     struct xorg_list list;
+    Bool unowned;
 };
 
 struct OdevAttributes *
commit 5b359cf6135ca173d8f65cb92926332f07f91efe
Author: Dave Airlie <airlied at gmail.com>
Date:   Wed Apr 10 16:32:11 2013 +1000

    xf86: use new xf86VTOwner interface in a few places
    
    This replaces some previous uses of direct xf86Screens[0] accesses.
    
    Reviewed-by: Chris Wilson <chris at chris-wilson.co.uk>
    Signed-off-by: Dave Airlie <airlied at gmail.com>

diff --git a/hw/xfree86/common/xf86Events.c b/hw/xfree86/common/xf86Events.c
index 980f38d..4c59adb 100644
--- a/hw/xfree86/common/xf86Events.c
+++ b/hw/xfree86/common/xf86Events.c
@@ -427,7 +427,7 @@ xf86VTSwitch(void)
      * Since all screens are currently all in the same state it is sufficient
      * check the first.  This might change in future.
      */
-    if (xf86Screens[0]->vtSema) {
+    if (xf86VTOwner()) {
 
         DebugF("xf86VTSwitch: Leaving, xf86Exiting is %s\n",
                BOOLTOSTRING((dispatchException & DE_TERMINATE) ? TRUE : FALSE));
diff --git a/hw/xfree86/common/xf86Init.c b/hw/xfree86/common/xf86Init.c
index 1695dbf..91ec4c8 100644
--- a/hw/xfree86/common/xf86Init.c
+++ b/hw/xfree86/common/xf86Init.c
@@ -819,7 +819,7 @@ InitOutput(ScreenInfo * pScreenInfo, int argc, char **argv)
     if (serverGeneration != 1) {
         xf86Resetting = TRUE;
         /* All screens are in the same state, so just check the first */
-        if (!xf86Screens[0]->vtSema) {
+        if (!xf86VTOwner()) {
 #ifdef HAS_USL_VTS
             ioctl(xf86Info.consoleFd, VT_RELDISP, VT_ACKACQ);
 #endif
diff --git a/hw/xfree86/common/xf86Xinput.c b/hw/xfree86/common/xf86Xinput.c
index bee407b..26c03c6 100644
--- a/hw/xfree86/common/xf86Xinput.c
+++ b/hw/xfree86/common/xf86Xinput.c
@@ -870,7 +870,7 @@ xf86NewInputDevice(InputInfoPtr pInfo, DeviceIntPtr *pdev, BOOL enable)
     }
 
     /* Enable it if it's properly initialised and we're currently in the VT */
-    if (enable && dev->inited && dev->startup && xf86Screens[0]->vtSema) {
+    if (enable && dev->inited && dev->startup && xf86VTOwner()) {
         OsBlockSignals();
         EnableDevice(dev, TRUE);
         if (!dev->enabled) {
diff --git a/hw/xfree86/os-support/solaris/sun_init.c b/hw/xfree86/os-support/solaris/sun_init.c
index 4b75a98..68527a5 100644
--- a/hw/xfree86/os-support/solaris/sun_init.c
+++ b/hw/xfree86/os-support/solaris/sun_init.c
@@ -274,7 +274,7 @@ xf86OpenConsole(void)
              * this is to make sure we don't continue until the activate
              * signal is received.
              */
-            if (!xf86Screens[0]->vtSema)
+            if (!xf86VTOwner())
                 sleep(5);
         }
 #endif                          /* HAS_USL_VTS */
commit d61ea1f64db45201c1a2b39c39293c5768d98092
Author: Dave Airlie <airlied at gmail.com>
Date:   Wed Apr 10 16:32:02 2013 +1000

    xfree86: add VT owner interface
    
    This is just a simple interface to avoid accessing x86Screens[0]
    directly.
    
    Reviewed-by: Chris Wilson <chris at chris-wilson.co.uk>
    Signed-off-by: Dave Airlie <airlied at gmail.com>

diff --git a/hw/xfree86/common/xf86.h b/hw/xfree86/common/xf86.h
index 1a20026..eada01c 100644
--- a/hw/xfree86/common/xf86.h
+++ b/hw/xfree86/common/xf86.h
@@ -238,6 +238,7 @@ extern _X_EXPORT void xf86InterceptSigIll(void (*sigillhandler) (void));
 extern _X_EXPORT Bool xf86EnableVTSwitch(Bool new);
 extern _X_EXPORT void xf86ProcessActionEvent(ActionEvent action, void *arg);
 extern _X_EXPORT void xf86PrintBacktrace(void);
+extern _X_EXPORT Bool xf86VTOwner(void);
 
 /* xf86Helper.c */
 
diff --git a/hw/xfree86/common/xf86Events.c b/hw/xfree86/common/xf86Events.c
index 0552233..980f38d 100644
--- a/hw/xfree86/common/xf86Events.c
+++ b/hw/xfree86/common/xf86Events.c
@@ -768,3 +768,12 @@ DDXRingBell(int volume, int pitch, int duration)
 {
     xf86OSRingBell(volume, pitch, duration);
 }
+
+Bool
+xf86VTOwner(void)
+{
+    /* at system startup xf86Screens[0] won't be set - but we will own the VT */
+    if (xf86NumScreens == 0)
+	return TRUE;
+    return xf86Screens[0]->vtSema;
+}
commit 7347f39f94d8cebbf73ce1a2f94d1abdaf7ff383
Author: Maarten Lankhorst <maarten.lankhorst at canonical.com>
Date:   Tue Apr 9 11:19:07 2013 +0200

    Xi: Do not handle ET_TouchOwnership in ProcessTouchEvent
    
    The event struct is different, causing memory corruption on 1.13 and 1.14,
    
    as can be witnessed in https://bugs.freedesktop.org/show_bug.cgi?id=56578
    
    Signed-off-by: Maarten Lankhorst <maarten.lankhorst at canonical.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 6779139..576f0fe 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1223,9 +1223,16 @@ TouchRejected(DeviceIntPtr sourcedev, TouchPointInfoPtr ti, XID resource,
  * touchpoint if it is pending finish.
  */
 static void
-ProcessTouchOwnershipEvent(DeviceIntPtr dev, TouchPointInfoPtr ti,
-                           TouchOwnershipEvent *ev)
+ProcessTouchOwnershipEvent(TouchOwnershipEvent *ev,
+                           DeviceIntPtr dev)
 {
+    TouchPointInfoPtr ti = TouchFindByClientID(dev, ev->touchid);
+
+    if (!ti) {
+        DebugF("[Xi] %s: Failed to get event %d for touchpoint %d\n",
+               dev->name, ev->type, ev->touchid);
+        return;
+    }
 
     if (ev->reason == XIRejectTouch)
         TouchRejected(dev, ti, ev->resource, ev);
@@ -1538,10 +1545,7 @@ ProcessTouchEvent(InternalEvent *ev, DeviceIntPtr dev)
     if (!t)
         return;
 
-    if (ev->any.type == ET_TouchOwnership)
-        touchid = ev->touch_ownership_event.touchid;
-    else
-        touchid = ev->device_event.touchid;
+    touchid = ev->device_event.touchid;
 
     if (type == ET_TouchBegin) {
         ti = TouchBeginTouch(dev, ev->device_event.sourceid, touchid,
@@ -1614,19 +1618,13 @@ ProcessTouchEvent(InternalEvent *ev, DeviceIntPtr dev)
         (type != ET_TouchEnd && ti->sprite.spriteTraceGood == 0))
         return;
 
-    /* TouchOwnership events are handled separately from the rest, as they
-     * have more complex semantics. */
-    if (ev->any.type == ET_TouchOwnership)
-        ProcessTouchOwnershipEvent(dev, ti, &ev->touch_ownership_event);
-    else {
-        TouchCopyValuatorData(&ev->device_event, ti);
-        /* WARNING: the event type may change to TouchUpdate in
-         * DeliverTouchEvents if a TouchEnd was delivered to a grabbing
-         * owner */
-        DeliverTouchEvents(dev, ti, (InternalEvent *) ev, 0);
-        if (ev->any.type == ET_TouchEnd)
-            TouchEndTouch(dev, ti);
-    }
+    TouchCopyValuatorData(&ev->device_event, ti);
+    /* WARNING: the event type may change to TouchUpdate in
+     * DeliverTouchEvents if a TouchEnd was delivered to a grabbing
+     * owner */
+    DeliverTouchEvents(dev, ti, (InternalEvent *) ev, 0);
+    if (ev->any.type == ET_TouchEnd)
+        TouchEndTouch(dev, ti);
 
     if (emulate_pointer)
         UpdateDeviceState(dev, &ev->device_event);
@@ -1820,10 +1818,14 @@ ProcessOtherEvent(InternalEvent *ev, DeviceIntPtr device)
         break;
     case ET_TouchBegin:
     case ET_TouchUpdate:
-    case ET_TouchOwnership:
     case ET_TouchEnd:
         ProcessTouchEvent(ev, device);
         break;
+    case ET_TouchOwnership:
+        /* TouchOwnership events are handled separately from the rest, as they
+         * have more complex semantics. */
+        ProcessTouchOwnershipEvent(&ev->touch_ownership_event, device);
+        break;
     case ET_BarrierHit:
     case ET_BarrierLeave:
         ProcessBarrierEvent(ev, device);
commit dbba50a1280cbda9ecff6f37884b4c5756c30bab
Author: Keith Packard <keithp at keithp.com>
Date:   Tue Apr 9 16:23:19 2013 -0700

    Xi: Use correct destination when swapping barrier events
    
    Write the swapped values to the destination rather than the source.
    
    Signed-off-by: Keith Packard <keithp at keithp.com>
    Reviewed-by: Jasper St. Pierre <jstpierre at mecheye.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xi/extinit.c b/Xi/extinit.c
index 619d0e4..02fffe5 100644
--- a/Xi/extinit.c
+++ b/Xi/extinit.c
@@ -848,24 +848,24 @@ SBarrierEvent(xXIBarrierEvent * from,
 
     *to = *from;
 
-    swaps(&from->sequenceNumber);
-    swapl(&from->length);
-    swaps(&from->evtype);
-    swapl(&from->time);
-    swaps(&from->deviceid);
-    swaps(&from->sourceid);
-    swapl(&from->event);
-    swapl(&from->root);
-    swapl(&from->root_x);
-    swapl(&from->root_y);
-
-    swapl(&from->dx.integral);
-    swapl(&from->dx.frac);
-    swapl(&from->dy.integral);
-    swapl(&from->dy.frac);
-    swapl(&from->dtime);
-    swapl(&from->barrier);
-    swapl(&from->eventid);
+    swaps(&to->sequenceNumber);
+    swapl(&to->length);
+    swaps(&to->evtype);
+    swapl(&to->time);
+    swaps(&to->deviceid);
+    swaps(&to->sourceid);
+    swapl(&to->event);
+    swapl(&to->root);
+    swapl(&to->root_x);
+    swapl(&to->root_y);
+
+    swapl(&to->dx.integral);
+    swapl(&to->dx.frac);
+    swapl(&to->dy.integral);
+    swapl(&to->dy.frac);
+    swapl(&to->dtime);
+    swapl(&to->barrier);
+    swapl(&to->eventid);
 }
 
 /** Event swapping function for XI2 events. */
commit b86b3d10bb2fee1a922b8831e8bb415c339f3d99
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Mar 4 07:58:41 2013 +1000

    dix: don't set non-exisiting flags on touch events
    
    Unlike pointer/keyboard events, the flags field for ET_Touch* is a set of
    server-internal defines that we need to convert to XI protocol defines.
    Currently only two of those defines actually translate to the protocol, so
    make sure we don't send internal garbage down the wire.
    
    No effect to current clients since they shouldn't look at undefined bits
    anyway.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/dix/eventconvert.c b/dix/eventconvert.c
index 2c411cf..ebc52c3 100644
--- a/dix/eventconvert.c
+++ b/dix/eventconvert.c
@@ -684,17 +684,18 @@ eventToDeviceEvent(DeviceEvent *ev, xEvent **xi)
     xde->root_x = double_to_fp1616(ev->root_x + ev->root_x_frac);
     xde->root_y = double_to_fp1616(ev->root_y + ev->root_y_frac);
 
-    if (ev->type == ET_TouchUpdate)
-        xde->flags |= (ev->flags & TOUCH_PENDING_END) ? XITouchPendingEnd : 0;
-    else
-        xde->flags = ev->flags;
+    if (IsTouchEvent((InternalEvent *)ev)) {
+        if (ev->type == ET_TouchUpdate)
+            xde->flags |= (ev->flags & TOUCH_PENDING_END) ? XITouchPendingEnd : 0;
 
-    if (IsTouchEvent((InternalEvent *) ev) &&
-        ev->flags & TOUCH_POINTER_EMULATED)
-        xde->flags |= XITouchEmulatingPointer;
+        if (ev->flags & TOUCH_POINTER_EMULATED)
+            xde->flags |= XITouchEmulatingPointer;
+    } else {
+        xde->flags = ev->flags;
 
-    if (ev->key_repeat)
-        xde->flags |= XIKeyRepeat;
+        if (ev->key_repeat)
+            xde->flags |= XIKeyRepeat;
+    }
 
     xde->mods.base_mods = ev->mods.base;
     xde->mods.latched_mods = ev->mods.latched;
commit ecf62755086fd65898998d5a509aee5f29a9583d
Author: Jeremy White <jwhite at codeweavers.com>
Date:   Thu Mar 21 10:58:57 2013 -0500

    Define prototypes for hw/xfree86/modes/xf86Modes.c only in xf86Modes.h.
    
    This removes a large number of redundant declaration warnings.
    
    Signed-off-by: Jeremy White <jwhite at codeweavers.com>
    Reviewed-by: Robert Morell <rmorell at nvidia.com>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/xfree86/common/xf86.h b/hw/xfree86/common/xf86.h
index 1514c26..1a20026 100644
--- a/hw/xfree86/common/xf86.h
+++ b/hw/xfree86/common/xf86.h
@@ -198,11 +198,6 @@ extern _X_EXPORT void *xf86GetPointerScreenFuncs(void);
 extern _X_EXPORT void xf86InitOrigins(void);
 extern _X_EXPORT void xf86ReconfigureLayout(void);
 
-/* xf86cvt.c */
-extern _X_EXPORT DisplayModePtr xf86CVTMode(int HDisplay, int VDisplay,
-                                            float VRefresh, Bool Reduced,
-                                            Bool Interlaced);
-
 /* xf86DPMS.c */
 
 extern _X_EXPORT Bool xf86DPMSInit(ScreenPtr pScreen, DPMSSetProcPtr set,
@@ -413,26 +408,6 @@ extern _X_EXPORT void
 xf86PrintModes(ScrnInfoPtr scrp);
 extern _X_EXPORT void
 xf86ShowClockRanges(ScrnInfoPtr scrp, ClockRangePtr clockRanges);
-extern _X_EXPORT double
-xf86ModeHSync(const DisplayModeRec * mode);
-extern _X_EXPORT double
-xf86ModeVRefresh(const DisplayModeRec * mode);
-extern _X_EXPORT void
-xf86SetModeDefaultName(DisplayModePtr mode);
-extern _X_EXPORT void
-xf86SetModeCrtc(DisplayModePtr p, int adjustFlags);
-extern _X_EXPORT DisplayModePtr
-xf86DuplicateMode(const DisplayModeRec * pMode);
-extern _X_EXPORT void
-xf86SaveModeContents(DisplayModePtr intern, const DisplayModeRec * pMode);
-extern _X_EXPORT DisplayModePtr
-xf86DuplicateModes(ScrnInfoPtr pScrn, DisplayModePtr modeList);
-extern _X_EXPORT Bool
-xf86ModesEqual(const DisplayModeRec * pMode1, const DisplayModeRec * pMode2);
-extern _X_EXPORT void
-xf86PrintModeline(int scrnIndex, DisplayModePtr mode);
-extern _X_EXPORT DisplayModePtr
-xf86ModesAdd(DisplayModePtr modes, DisplayModePtr new);
 
 /* xf86Option.c */
 
diff --git a/hw/xfree86/common/xf86Config.c b/hw/xfree86/common/xf86Config.c
index 486752b..74d5ed3 100644
--- a/hw/xfree86/common/xf86Config.c
+++ b/hw/xfree86/common/xf86Config.c
@@ -52,6 +52,7 @@
 #endif
 
 #include "xf86.h"
+#include "xf86Modes.h"
 #include "xf86Parser.h"
 #include "xf86tokens.h"
 #include "xf86Config.h"
diff --git a/hw/xfree86/ddc/xf86DDC.h b/hw/xfree86/ddc/xf86DDC.h
index c63da8b..bdc7648 100644
--- a/hw/xfree86/ddc/xf86DDC.h
+++ b/hw/xfree86/ddc/xf86DDC.h
@@ -45,8 +45,6 @@ extern _X_EXPORT void
 
 extern _X_EXPORT Bool xf86SetDDCproperties(ScrnInfoPtr pScreen, xf86MonPtr DDC);
 
-extern _X_EXPORT DisplayModePtr xf86DDCGetModes(int scrnIndex, xf86MonPtr DDC);
-
 extern _X_EXPORT Bool
  xf86MonitorIsHDMI(xf86MonPtr mon);
 
diff --git a/hw/xfree86/fbdevhw/Makefile.am b/hw/xfree86/fbdevhw/Makefile.am
index 1fa9321..ee5577a 100644
--- a/hw/xfree86/fbdevhw/Makefile.am
+++ b/hw/xfree86/fbdevhw/Makefile.am
@@ -10,7 +10,7 @@ else
 libfbdevhw_la_SOURCES = fbdevhwstub.c
 endif
 
-INCLUDES = $(XORG_INCS) -I$(srcdir)/../i2c
+INCLUDES = $(XORG_INCS) -I$(srcdir)/../i2c -I$(srcdir)/../modes -I$(srcdir)/../ddc -I$(srcdir)/../parser
 
 AM_CFLAGS = $(DIX_CFLAGS) $(XORG_CFLAGS)
 
diff --git a/hw/xfree86/fbdevhw/fbdevhw.c b/hw/xfree86/fbdevhw/fbdevhw.c
index d4b5558..cbb4093 100644
--- a/hw/xfree86/fbdevhw/fbdevhw.c
+++ b/hw/xfree86/fbdevhw/fbdevhw.c
@@ -6,6 +6,7 @@
 #include <string.h>
 
 #include "xf86.h"
+#include "xf86Modes.h"
 #include "xf86_OSproc.h"
 
 /* pci stuff */
diff --git a/hw/xfree86/modes/xf86DisplayIDModes.c b/hw/xfree86/modes/xf86DisplayIDModes.c
index bead126..c2e7718 100644
--- a/hw/xfree86/modes/xf86DisplayIDModes.c
+++ b/hw/xfree86/modes/xf86DisplayIDModes.c
@@ -25,6 +25,7 @@
 
 #include "xorg-config.h"
 #include "xf86.h"
+#include "xf86Modes.h"
 #include "xf86str.h"
 #include "edid.h"
 #include "xf86DDC.h"
diff --git a/hw/xfree86/modes/xf86Modes.h b/hw/xfree86/modes/xf86Modes.h
index aec7688..d3abee5 100644
--- a/hw/xfree86/modes/xf86Modes.h
+++ b/hw/xfree86/modes/xf86Modes.h
@@ -112,6 +112,9 @@ xf86GetMonitorModes(ScrnInfoPtr pScrn, XF86ConfMonitorPtr conf_monitor);
 extern _X_EXPORT DisplayModePtr xf86GetDefaultModes(void);
 
 extern _X_EXPORT void
+xf86SaveModeContents(DisplayModePtr intern, const DisplayModeRec *mode);
+
+extern _X_EXPORT void
  xf86DDCApplyQuirks(int scrnIndex, xf86MonPtr DDC);
 
 #endif                          /* _XF86MODES_H_ */
diff --git a/hw/xfree86/modes/xf86RandR12.c b/hw/xfree86/modes/xf86RandR12.c
index 01fc9c5..25beee6 100644
--- a/hw/xfree86/modes/xf86RandR12.c
+++ b/hw/xfree86/modes/xf86RandR12.c
@@ -31,6 +31,7 @@
 #include "xf86.h"
 #include "os.h"
 #include "globals.h"
+#include "xf86Modes.h"
 #include "xf86Priv.h"
 #include "xf86DDC.h"
 #include "mipointer.h"
diff --git a/hw/xfree86/utils/cvt/Makefile.am b/hw/xfree86/utils/cvt/Makefile.am
index 4ebcedf..754606e 100644
--- a/hw/xfree86/utils/cvt/Makefile.am
+++ b/hw/xfree86/utils/cvt/Makefile.am
@@ -24,6 +24,7 @@ bin_PROGRAMS = cvt
 
 INCLUDES = $(XORG_INCS) \
 	   -I$(top_srcdir)/hw/xfree86/ddc \
+	   -I$(top_srcdir)/hw/xfree86/modes \
 	   -I$(top_srcdir)/hw/xfree86/parser
 
 # gah
diff --git a/hw/xfree86/utils/cvt/cvt.c b/hw/xfree86/utils/cvt/cvt.c
index 9483964..5e2888e 100644
--- a/hw/xfree86/utils/cvt/cvt.c
+++ b/hw/xfree86/utils/cvt/cvt.c
@@ -24,6 +24,7 @@
 /* Standalone VESA CVT standard timing modelines generator. */
 
 #include "xf86.h"
+#include "xf86Modes.h"
 
 /* FatalError implementation used by the server code we built in */
 void
diff --git a/hw/xfree86/vbe/Makefile.am b/hw/xfree86/vbe/Makefile.am
index 0b24faf..1720eb9 100644
--- a/hw/xfree86/vbe/Makefile.am
+++ b/hw/xfree86/vbe/Makefile.am
@@ -10,4 +10,5 @@ sdk_HEADERS = vbe.h vbeModes.h
 AM_CFLAGS = $(DIX_CFLAGS) $(XORG_CFLAGS)
 
 INCLUDES = $(XORG_INCS) -I$(srcdir)/../ddc -I$(srcdir)/../i2c \
+           -I$(srcdir)/../modes -I$(srcdir)/../parser \
            -I$(srcdir)/../int10
diff --git a/hw/xfree86/vbe/vbe.c b/hw/xfree86/vbe/vbe.c
index 97a9bcf..f0344af 100644
--- a/hw/xfree86/vbe/vbe.c
+++ b/hw/xfree86/vbe/vbe.c
@@ -16,6 +16,7 @@
 #include <string.h>
 
 #include "xf86.h"
+#include "xf86Modes.h"
 #include "vbe.h"
 #include <X11/extensions/dpmsconst.h>
 
commit e13f29984251dbbe6076264ed710c2922312eed1
Author: Bryce Harrington <bryce at canonical.com>
Date:   Tue Mar 19 12:12:46 2013 -0700

    xfree86: Be verbose if waiting on opening the drm device
    
    Signed-off-by: Bryce Harrington <bryce at canonical.com>
    Reviewed-by: Chris Wilson <chris at chris-wilson.co.uk>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/xfree86/os-support/linux/lnx_platform.c b/hw/xfree86/os-support/linux/lnx_platform.c
index 977d590..444f8f5 100644
--- a/hw/xfree86/os-support/linux/lnx_platform.c
+++ b/hw/xfree86/os-support/linux/lnx_platform.c
@@ -43,7 +43,10 @@ get_drm_info(struct OdevAttributes *attribs, char *path)
 	    if (tries > 1)
 		LogMessage(X_INFO, "setversion 1.4 succeeded on try #%d\n", tries);
 	    break;
-	} else if (err != -EACCES) {
+	} if (err == -EACCES) {
+	    if (tries % 500 == 0)
+		LogMessage(X_INFO, "waiting on drm device...\n");
+	} else {
 	    break;
 	}
 
commit 70739e817b2d64bc020ea491f23a3574bdb6155e
Author: Bryce Harrington <bryce at canonical.com>
Date:   Tue Mar 19 12:12:45 2013 -0700

    xfree86: Fix race condition failure opening drm.
    
    If other processes have had drm open previously, xserver may attempt to
    open the device too early and fail, with xserver error exit "Cannot
    run in framebuffer mode" or Xorg.0.log messages about "setversion 1.4
    failed".
    
    In this situation, we're receiving back -EACCES from libdrm.  To address
    this we need to re-set ourselves as the drm master, and keep trying to
    set the interface until it works (or until we give up).
    
    See https://bugs.launchpad.net/ubuntu/+source/libdrm/+bug/982889
    
    Signed-off-by: Bryce Harrington <bryce at canonical.com>
    Reviewed-by: Chris Wilson <chris at chris-wilson.co.uk>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/xfree86/os-support/linux/lnx_platform.c b/hw/xfree86/os-support/linux/lnx_platform.c
index 10c8ecf..977d590 100644
--- a/hw/xfree86/os-support/linux/lnx_platform.c
+++ b/hw/xfree86/os-support/linux/lnx_platform.c
@@ -43,8 +43,14 @@ get_drm_info(struct OdevAttributes *attribs, char *path)
 	    if (tries > 1)
 		LogMessage(X_INFO, "setversion 1.4 succeeded on try #%d\n", tries);
 	    break;
+	} else if (err != -EACCES) {
+	    break;
 	}
+
 	usleep(10000);
+
+	if (!drmSetMaster(fd))
+	    LogMessage(X_INFO, "drmSetMaster succeeded\n");
     }
     if (err) {
         ErrorF("setversion 1.4 failed: %s\n", strerror(-err));
commit c31eac647a9ecf0fb20dc98266cadf0ba923ba14
Author: Bryce Harrington <bryce at canonical.com>
Date:   Tue Mar 19 12:12:44 2013 -0700

    xfree86: Keep trying to set interface on drm for 2 seconds.
    
    And if we've had to delay booting due to not being able to set the
    interface, fess up.
    
    Signed-off-by: Bryce Harrington <bryce at canonical.com>
    Reviewed-by: Chris Wilson <chris at chris-wilson.co.uk>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/xfree86/os-support/linux/lnx_platform.c b/hw/xfree86/os-support/linux/lnx_platform.c
index 3ae2db1..10c8ecf 100644
--- a/hw/xfree86/os-support/linux/lnx_platform.c
+++ b/hw/xfree86/os-support/linux/lnx_platform.c
@@ -26,16 +26,26 @@ get_drm_info(struct OdevAttributes *attribs, char *path)
     char *buf;
     int fd;
     int err = 0;
+    int tries = 0;
 
     fd = open(path, O_RDWR, O_CLOEXEC);
     if (fd == -1)
         return FALSE;
 
-    sv.drm_di_major = 1;
-    sv.drm_di_minor = 4;
-    sv.drm_dd_major = -1;       /* Don't care */
-    sv.drm_dd_minor = -1;       /* Don't care */
-    err = drmSetInterfaceVersion(fd, &sv);
+    while (tries++ < 200) {
+	sv.drm_di_major = 1;
+	sv.drm_di_minor = 4;
+	sv.drm_dd_major = -1;       /* Don't care */
+	sv.drm_dd_minor = -1;       /* Don't care */
+
+	err = drmSetInterfaceVersion(fd, &sv);
+	if (!err) {
+	    if (tries > 1)
+		LogMessage(X_INFO, "setversion 1.4 succeeded on try #%d\n", tries);
+	    break;
+	}
+	usleep(10000);
+    }
     if (err) {
         ErrorF("setversion 1.4 failed: %s\n", strerror(-err));
 	goto out;
commit d1cc210de8c13f2db9f6f284ecc652305c28801e
Author: Bryce Harrington <bryce at canonical.com>
Date:   Tue Mar 19 12:12:43 2013 -0700

    xfree86: Provide more details on failure
    
    Signed-off-by: Bryce Harrington <bryce at canonical.com>
    Reviewed-by: Chris Wilson <chris at chris-wilson.co.uk>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/xfree86/os-support/linux/lnx_platform.c b/hw/xfree86/os-support/linux/lnx_platform.c
index 6ee219a..3ae2db1 100644
--- a/hw/xfree86/os-support/linux/lnx_platform.c
+++ b/hw/xfree86/os-support/linux/lnx_platform.c
@@ -7,6 +7,8 @@
 #include <xf86drm.h>
 #include <fcntl.h>
 #include <unistd.h>
+#include <errno.h>
+#include <string.h>
 
 /* Linux platform device support */
 #include "xf86_OSproc.h"
@@ -35,7 +37,7 @@ get_drm_info(struct OdevAttributes *attribs, char *path)
     sv.drm_dd_minor = -1;       /* Don't care */
     err = drmSetInterfaceVersion(fd, &sv);
     if (err) {
-        ErrorF("setversion 1.4 failed\n");
+        ErrorF("setversion 1.4 failed: %s\n", strerror(-err));
 	goto out;
     }
 
commit f059d0dabc553a5f748d86de9115da00be5997d5
Author: Bryce Harrington <bryce at canonical.com>
Date:   Tue Mar 19 12:12:42 2013 -0700

    xfree86: Track error code and add label for error handling.
    
    Signed-off-by: Bryce Harrington <bryce at canonical.com>
    Reviewed-by: Chris Wilson <chris at chris-wilson.co.uk>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/xfree86/os-support/linux/lnx_platform.c b/hw/xfree86/os-support/linux/lnx_platform.c
index 69a5b8c..6ee219a 100644
--- a/hw/xfree86/os-support/linux/lnx_platform.c
+++ b/hw/xfree86/os-support/linux/lnx_platform.c
@@ -23,6 +23,7 @@ get_drm_info(struct OdevAttributes *attribs, char *path)
     drmSetVersion sv;
     char *buf;
     int fd;
+    int err = 0;
 
     fd = open(path, O_RDWR, O_CLOEXEC);
     if (fd == -1)
@@ -32,10 +33,10 @@ get_drm_info(struct OdevAttributes *attribs, char *path)
     sv.drm_di_minor = 4;
     sv.drm_dd_major = -1;       /* Don't care */
     sv.drm_dd_minor = -1;       /* Don't care */
-    if (drmSetInterfaceVersion(fd, &sv)) {
+    err = drmSetInterfaceVersion(fd, &sv);
+    if (err) {
         ErrorF("setversion 1.4 failed\n");
-	close(fd);
-        return FALSE;
+	goto out;
     }
 
     xf86_add_platform_device(attribs);
@@ -44,8 +45,9 @@ get_drm_info(struct OdevAttributes *attribs, char *path)
     xf86_add_platform_device_attrib(xf86_num_platform_devices - 1,
                                     ODEV_ATTRIB_BUSID, buf);
     drmFreeBusid(buf);
+out:
     close(fd);
-    return TRUE;
+    return (err == 0);
 }
 
 Bool
commit 4d7052bd7bbf49b573dc4d34ad14e7f058a0d884
Author: Bryce Harrington <bryce at canonical.com>
Date:   Tue Mar 19 12:12:41 2013 -0700

    xfree86: (Cleanup) Close fd if drm interface 1.4 could not be set.
    
    Signed-off-by: Bryce Harrington <bryce at canonical.com>
    Reviewed-by: Chris Wilson <chris at chris-wilson.co.uk>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/xfree86/os-support/linux/lnx_platform.c b/hw/xfree86/os-support/linux/lnx_platform.c
index 76f5583..69a5b8c 100644
--- a/hw/xfree86/os-support/linux/lnx_platform.c
+++ b/hw/xfree86/os-support/linux/lnx_platform.c
@@ -34,6 +34,7 @@ get_drm_info(struct OdevAttributes *attribs, char *path)
     sv.drm_dd_minor = -1;       /* Don't care */
     if (drmSetInterfaceVersion(fd, &sv)) {
         ErrorF("setversion 1.4 failed\n");
+	close(fd);
         return FALSE;
     }
 
commit 8928f8fa0bb154ce437af703ff702016f0dcf127
Author: Geert Uytterhoeven <geert at linux-m68k.org>
Date:   Mon Mar 18 21:38:10 2013 +0100

    kdrive/fbdev: revive randr new screen size logic
    
    hw/kdrive/fbdev/fbdev.c: In function 'fbdevRandRSetConfig':
    hw/kdrive/fbdev/fbdev.c:470:19: warning: variable 'newheight' set but not used [-Wunused-but-set-variable]
    hw/kdrive/fbdev/fbdev.c:470:9: warning: variable 'newwidth' set but not used [-Wunused-but-set-variable]
    
    Signed-off-by: Geert Uytterhoeven <geert at linux-m68k.org>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/kdrive/fbdev/fbdev.c b/hw/kdrive/fbdev/fbdev.c
index fd14afa..d6fcf1a 100644
--- a/hw/kdrive/fbdev/fbdev.c
+++ b/hw/kdrive/fbdev/fbdev.c
@@ -465,15 +465,19 @@ fbdevRandRSetConfig(ScreenPtr pScreen,
     int oldheight;
     int oldmmwidth;
     int oldmmheight;
-    int newwidth, newheight;
+    int newwidth, newheight, newmmwidth, newmmheight;
 
     if (screen->randr & (RR_Rotate_0 | RR_Rotate_180)) {
         newwidth = pSize->width;
         newheight = pSize->height;
+        newmmwidth = pSize->mmWidth;
+        newmmheight = pSize->mmHeight;
     }
     else {
         newwidth = pSize->height;
         newheight = pSize->width;
+        newmmwidth = pSize->mmHeight;
+        newmmheight = pSize->mmWidth;
     }
 
     if (wasEnabled)
@@ -491,6 +495,10 @@ fbdevRandRSetConfig(ScreenPtr pScreen,
      */
 
     scrpriv->randr = KdAddRotation(screen->randr, randr);
+    pScreen->width = newwidth;
+    pScreen->height = newheight;
+    pScreen->mmWidth = newmmwidth;
+    pScreen->mmHeight = newmmheight;
 
     fbdevUnmapFramebuffer(screen);
 
commit 808c87bff710263f5a7b3c12a7e7fec54672fecd
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Mar 25 14:51:58 2013 +1000

    Revert "kdrive: fix "set but not used" warnings"
    
    Partial revert of commit 4149ee8ec0193acbf3812c7ee2627b93b9a89997, better
    fix coming up.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/kdrive/fbdev/fbdev.c b/hw/kdrive/fbdev/fbdev.c
index fb6e3a2..fd14afa 100644
--- a/hw/kdrive/fbdev/fbdev.c
+++ b/hw/kdrive/fbdev/fbdev.c
@@ -465,6 +465,16 @@ fbdevRandRSetConfig(ScreenPtr pScreen,
     int oldheight;
     int oldmmwidth;
     int oldmmheight;
+    int newwidth, newheight;
+
+    if (screen->randr & (RR_Rotate_0 | RR_Rotate_180)) {
+        newwidth = pSize->width;
+        newheight = pSize->height;
+    }
+    else {
+        newwidth = pSize->height;
+        newheight = pSize->width;
+    }
 
     if (wasEnabled)
         KdDisableScreen(pScreen);
commit ac4c2abe985ce6816a3389c41eb23462c6ac2486
Author: vdb at picaros.org <vdb at picaros.org>
Date:   Thu Mar 7 16:07:31 2013 +0100

    xserver: add monitor Option "ZoomModes" [v2]
    
    Section "Monitor"
      Identifier "a21inch"
      Option "PreferredMode" "1600x1200"
      Option "ZoomModes" "1600x1200 1280x1024 1280x1024 640x480"
    EndSection
    
    The option's effect is to search for and mark once each named mode in
    the output modes list.  So the specification order is free and the zoom
    modes sequence follows the order of the output modes list.  All marked
    modes are available via the Ctrl+Alt+Keypad-{Plus,Minus} key
    combination.
    
    See also http://bugs.freedesktop.org/show_bug.cgi?id=17954.
    
    This option has its use for combined monitor and television setups.
    It allows for easy switching between 60 Hz and 50 Hz modes even when a
    monitor refuses to display the input signal.
    
    (Includes a few minor changes suggested by Aaron for v2)
    
    Signed-off-by: Servaas Vandenberghe <vdb at picaros.org>
    Reviewed-by: Aaron Plattner <aplattner at nvidia.com>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/xfree86/man/xorg.conf.man b/hw/xfree86/man/xorg.conf.man
index 9361ce9..67d8594 100644
--- a/hw/xfree86/man/xorg.conf.man
+++ b/hw/xfree86/man/xorg.conf.man
@@ -1676,6 +1676,17 @@ This optional entry specifies a mode to be marked as the preferred initial mode
 of the monitor.
 (RandR 1.2-supporting drivers only)
 .TP 7
+.BI "Option \*qZoomModes\*q \*q" name " " name " " ... \*q
+This optional entry specifies modes to be marked as zoom modes.
+It is possible to switch to the next and previous mode via
+.BR Ctrl+Alt+Keypad\-Plus " and " Ctrl+Alt+Keypad\-Minus .
+All these keypad available modes are selected from the screen mode list.
+This list is a copy of the compatibility output monitor mode list.
+Since this output is the output connected to the lowest
+dot-area monitor, as determined from its largest size mode, that
+monitor defines the available zoom modes.
+(RandR 1.2-supporting drivers only)
+.TP 7
 .BI "Option \*qPosition\*q \*q" x " " y \*q
 This optional entry specifies the position of the monitor within the X
 screen.
diff --git a/hw/xfree86/modes/xf86Crtc.c b/hw/xfree86/modes/xf86Crtc.c
index f9ae465..e4b393c 100644
--- a/hw/xfree86/modes/xf86Crtc.c
+++ b/hw/xfree86/modes/xf86Crtc.c
@@ -428,6 +428,7 @@ extern XF86ConfigPtr xf86configptr;
 
 typedef enum {
     OPTION_PREFERRED_MODE,
+    OPTION_ZOOM_MODES,
     OPTION_POSITION,
     OPTION_BELOW,
     OPTION_RIGHT_OF,
@@ -446,6 +447,7 @@ typedef enum {
 
 static OptionInfoRec xf86OutputOptions[] = {
     {OPTION_PREFERRED_MODE, "PreferredMode", OPTV_STRING, {0}, FALSE},
+    {OPTION_ZOOM_MODES, "ZoomModes", OPTV_STRING, {0}, FALSE },
     {OPTION_POSITION, "Position", OPTV_STRING, {0}, FALSE},
     {OPTION_BELOW, "Below", OPTV_STRING, {0}, FALSE},
     {OPTION_RIGHT_OF, "RightOf", OPTV_STRING, {0}, FALSE},
@@ -1418,6 +1420,90 @@ preferredMode(ScrnInfoPtr pScrn, xf86OutputPtr output)
     return preferred_mode;
 }
 
+/** identify a token
+ * args
+ *   *src     a string with zero or more tokens, e.g. "tok0 tok1",
+ *   **token  stores a pointer to the first token character,
+ *   *len     stores the token length.
+ * return
+ *   a pointer into src[] at the token terminating character, or
+ *   NULL if no token is found.
+ */
+static const char *
+gettoken(const char *src, const char **token, int *len)
+{
+    const char *delim = " \t";
+    int skip;
+
+    if (!src)
+        return NULL;
+
+    skip = strspn(src, delim);
+    *token = &src[skip];
+
+    *len = strcspn(*token, delim);
+    /* Support for backslash escaped delimiters could be implemented
+     * here.
+     */
+
+    /* (*token)[0] != '\0'  <==>  *len > 0 */
+    if (*len > 0)
+        return &(*token)[*len];
+    else
+        return NULL;
+}
+
+/** Check for a user configured zoom mode list, Option "ZoomModes":
+ *
+ * Section "Monitor"
+ *   Identifier "a21inch"
+ *   Option "ZoomModes" "1600x1200 1280x1024 1280x1024 640x480"
+ * EndSection
+ *
+ * Each user mode name is searched for independently so the list
+ * specification order is free.  An output mode is matched at most
+ * once, a mode with an already set M_T_USERDEF type bit is skipped.
+ * Thus a repeat mode name specification matches the next output mode
+ * with the same name.
+ *
+ * Ctrl+Alt+Keypad-{Plus,Minus} zooms {in,out} by selecting the
+ * {next,previous} M_T_USERDEF mode in the screen modes list, itself
+ * sorted toward lower dot area or lower dot clock frequency, see
+ *   modes/xf86Crtc.c: xf86SortModes() xf86SetScrnInfoModes(), and
+ *   common/xf86Cursor.c: xf86ZoomViewport().
+ */
+static int
+processZoomModes(xf86OutputPtr output)
+{
+    const char *zoom_modes;
+    int count = 0;
+
+    zoom_modes = xf86GetOptValString(output->options, OPTION_ZOOM_MODES);
+
+    if (zoom_modes) {
+        const char *token, *next;
+        int len;
+
+        next = gettoken(zoom_modes, &token, &len);
+        while (next) {
+            DisplayModePtr mode;
+
+            for (mode = output->probed_modes; mode; mode = mode->next)
+                if (!strncmp(token, mode->name, len)  /* prefix match */
+                    && mode->name[len] == '\0'        /* equal length */
+                    && !(mode->type & M_T_USERDEF)) { /* no rematch */
+                    mode->type |= M_T_USERDEF;
+                    break;
+                }
+
+            count++;
+            next = gettoken(next, &token, &len);
+        }
+    }
+
+    return count;
+}
+
 static void
 GuessRangeFromModes(MonPtr mon, DisplayModePtr mode)
 {
@@ -1713,6 +1799,9 @@ xf86ProbeOutputModes(ScrnInfoPtr scrn, int maxX, int maxY)
             }
         }
 
+        /* Ctrl+Alt+Keypad-{Plus,Minus} zoom mode: M_T_USERDEF mode type */
+        processZoomModes(output);
+
         output->initial_rotation = xf86OutputInitialRotation(output);
 
         if (debug_modes) {
commit 2967391c6d35f03121afa8003e0fb94b62495129
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Feb 28 10:43:05 2013 +1000

    Xi: add a comment to make a condition a bit clearer
    
    The commit message to 676447190190d8546165e21be242cf16dd69f5ae explains it,
    but that doesn't stop the WTF moment when reading the code.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 05685a2..6779139 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1898,6 +1898,7 @@ DeliverTouchEndEvent(DeviceIntPtr dev, TouchPointInfoPtr ti, InternalEvent *ev,
         goto out;
     }
 
+    /* A client is waiting for the begin, don't give it a TouchEnd */
     if (listener->state == LISTENER_AWAITING_BEGIN) {
         listener->state = LISTENER_HAS_END;
         goto out;
commit 2fdde2c40d83695438b6f5615f98bd7ae801b43d
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Feb 25 15:21:32 2013 +1000

    dix: update coords for touch events in PlayReleasedEvents
    
    Note: this is only hit for #ifdef PANORAMIX
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/dix/events.c b/dix/events.c
index 2682ecd..0512052 100644
--- a/dix/events.c
+++ b/dix/events.c
@@ -1200,6 +1200,9 @@ PlayReleasedEvents(void)
                 case ET_KeyRelease:
                 case ET_ProximityIn:
                 case ET_ProximityOut:
+                case ET_TouchBegin:
+                case ET_TouchUpdate:
+                case ET_TouchEnd:
                     ev->root_x += screenInfo.screens[0]->x -
                         pDev->spriteInfo->sprite->screen->x;
                     ev->root_y += screenInfo.screens[0]->y -
commit 697071ab2b7f8910e01ed74618138538291cd1e8
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Feb 28 10:30:15 2013 +1000

    Xi: compress two if statements with the same body
    
    We do the same thing here, compress them into one body.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 6fcca9a..05685a2 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1904,7 +1904,9 @@ DeliverTouchEndEvent(DeviceIntPtr dev, TouchPointInfoPtr ti, InternalEvent *ev,
     }
 
     /* Event in response to reject */
-    if (ev->device_event.flags & TOUCH_REJECT) {
+    if (ev->device_event.flags & TOUCH_REJECT ||
+        (ev->device_event.flags & TOUCH_ACCEPT && !TouchResourceIsOwner(ti, listener->listener))) {
+        /* Touch has been rejected, or accepted by its owner which is not this listener */
         if (listener->state != LISTENER_HAS_END)
             rc = DeliverOneTouchEvent(client, dev, ti, grab, win, ev);
         listener->state = LISTENER_HAS_END;
@@ -1927,12 +1929,6 @@ DeliverTouchEndEvent(DeviceIntPtr dev, TouchPointInfoPtr ti, InternalEvent *ev,
         if (normal_end)
             listener->state = LISTENER_HAS_END;
     }
-    else if (ev->device_event.flags & TOUCH_ACCEPT) {
-        /* Touch has been accepted by its owner, which is not this listener */
-        if (listener->state != LISTENER_HAS_END)
-            rc = DeliverOneTouchEvent(client, dev, ti, grab, win, ev);
-        listener->state = LISTENER_HAS_END;
-    }
 
  out:
     return rc;
commit 11bead1fa205a1353e6a33c6024c7e8ace80be7c
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Feb 25 11:13:52 2013 +1000

    dix: fix a comment
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/dix/touch.c b/dix/touch.c
index 0db842c..891cc78 100644
--- a/dix/touch.c
+++ b/dix/touch.c
@@ -902,7 +902,8 @@ TouchSetupListeners(DeviceIntPtr dev, TouchPointInfoPtr ti, InternalEvent *ev)
 }
 
 /**
- * Remove the touch pointer grab from the device. Called from AllowSome()
+ * Remove the touch pointer grab from the device. Called from
+ * DeactivatePointerGrab()
  */
 void
 TouchRemovePointerGrab(DeviceIntPtr dev)
commit fc504a44d12d537d4e07f659f1863f200a0272ad
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Mar 1 08:26:06 2013 +1000

    Xi: use a temp variable for the new listener
    
    Instead of accessing ti->listener[0] all the time.
    
    No functional changes.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index f2268dd..6fcca9a 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1126,20 +1126,22 @@ static void
 TouchPuntToNextOwner(DeviceIntPtr dev, TouchPointInfoPtr ti,
                      TouchOwnershipEvent *ev)
 {
+    TouchListener *listener = &ti->listeners[0]; /* new owner */
+
     /* Deliver the ownership */
-    if (ti->listeners[0].state == LISTENER_AWAITING_OWNER ||
-        ti->listeners[0].state == LISTENER_EARLY_ACCEPT)
+    if (listener->state == LISTENER_AWAITING_OWNER ||
+        listener->state == LISTENER_EARLY_ACCEPT)
         DeliverTouchEvents(dev, ti, (InternalEvent *) ev,
-                           ti->listeners[0].listener);
-    else if (ti->listeners[0].state == LISTENER_AWAITING_BEGIN) {
+                           listener->listener);
+    else if (listener->state == LISTENER_AWAITING_BEGIN) {
         /* We can't punt to a pointer listener unless all older pointer
          * emulated touches have been seen already. */
-        if ((ti->listeners[0].type == LISTENER_POINTER_GRAB ||
-             ti->listeners[0].type == LISTENER_POINTER_REGULAR) &&
+        if ((listener->type == LISTENER_POINTER_GRAB ||
+             listener->type == LISTENER_POINTER_REGULAR) &&
             ti != FindOldestPointerEmulatedTouch(dev))
             return;
 
-        TouchEventHistoryReplay(ti, dev, ti->listeners[0].listener);
+        TouchEventHistoryReplay(ti, dev, listener->listener);
     }
 
     /* If we've just removed the last grab and the touch has physically
@@ -1150,7 +1152,7 @@ TouchPuntToNextOwner(DeviceIntPtr dev, TouchPointInfoPtr ti,
         return;
     }
 
-    if (ti->listeners[0].state == LISTENER_EARLY_ACCEPT)
+    if (listener->state == LISTENER_EARLY_ACCEPT)
         ActivateEarlyAccept(dev, ti);
 }
 
commit 9978b57b8d94f061d72a67b99a02b0ba16a11429
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Mar 1 08:43:58 2013 +1000

    Xi: return !Success from DeliverTouchEmulatedEvent if we didn't deliver
    
    All callers currently ignore the new value, so this patch has no effect.
    Inverse call graph:
    
    DeliverTouchEmulatedEvent
            DeliverEmulatedMotionEvent              Ignores value
            DeliverTouchBeginEvent
                    DeliverTouchEvent
                            DeliverTouchEvents      Ignores value
            DeliverTouchEndEvent
                    DeliverTouchEvent
                            DeliverTouchEvents      Ignores value
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>

diff --git a/Xi/exevents.c b/Xi/exevents.c
index 609b126..f2268dd 100644
--- a/Xi/exevents.c
+++ b/Xi/exevents.c
@@ -1376,7 +1376,7 @@ DeliverTouchEmulatedEvent(DeviceIntPtr dev, TouchPointInfoPtr ti,
 
     /* We don't deliver pointer events to non-owners */
     if (!TouchResourceIsOwner(ti, listener->listener))
-        return Success;
+        return !Success;
 
     nevents = TouchConvertToPointerEvent(ev, &motion, &button);
     BUG_RETURN_VAL(nevents == 0, BadValue);
@@ -1398,7 +1398,7 @@ DeliverTouchEmulatedEvent(DeviceIntPtr dev, TouchPointInfoPtr ti,
             /* 'grab' is the passive grab, but if the grab isn't active,
              * don't deliver */
             if (!dev->deviceGrab.grab)
-                return Success;
+                return !Success;
 
             if (grab->ownerEvents) {
                 WindowPtr focus = NullWindow;
commit cc3d1a5a6120e721a46c67446ba68f5596055633
Author: Piotr Dziwinski <piotrdz at gmail.com>
Date:   Sat Feb 23 13:14:45 2013 +0100

    glx: fix uninitialized var in __glXDRIscreenProbe
    
    Fixes: https://bugs.freedesktop.org/show_bug.cgi?id=59825
    
    Signed-off-by: Piotr Dziwinski <piotrdz at gmail.com>
    Reviewed-by: Keith Packard <keithp at keithp.com>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/glx/glxdri.c b/glx/glxdri.c
index da46468..a997e2f 100644
--- a/glx/glxdri.c
+++ b/glx/glxdri.c
@@ -971,6 +971,8 @@ __glXDRIscreenProbe(ScreenPtr pScreen)
     size_t buffer_size;
     ScrnInfoPtr pScrn = xf86ScreenToScrn(pScreen);
 
+    framebuffer.base = NULL;
+
     if (!xf86LoaderCheckSymbol("DRIQueryDirectRenderingCapable") ||
         !DRIQueryDirectRenderingCapable(pScreen, &isCapable) || !isCapable) {
         LogMessage(X_INFO,
commit c2ede8f92f0d6f15b1b2a04889cb54cd1728780b
Merge: 190b032 7050aae
Author: Keith Packard <keithp at keithp.com>
Date:   Mon Mar 18 11:26:24 2013 -0700

    Merge remote-tracking branch 'whot/for-keith'

commit 190b0321510b99d4738915f540cea5c0c51e07e2
Author: Zack Rusin <zackr at vmware.com>
Date:   Thu Feb 14 15:06:57 2013 -0800

    GLX/DRI2: Do not expose INTEL_swap_event without swap control
    
    Swap events depent on the implementation of ScheduleSwap. By
    unconditionally enabling GLX_INTEL_swap_event we're breaking
    the system with drivers that don't support it because the apps
    are forever stuck waiting for an event that will never be
    delivered. So lets enable the extension only if the hooks it
    depends on are actually there.
    
    Signed-off-by: Zack Rusin <zackr at vmware.com>
    Reviewed-by: Ian Romanick <ian.d.romanick at intel.com>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/glx/glxdri2.c b/glx/glxdri2.c
index 8fba6a8..e07cb56 100644
--- a/glx/glxdri2.c
+++ b/glx/glxdri2.c
@@ -857,8 +857,6 @@ initializeExtensions(__GLXDRIscreen * screen)
     __glXEnableExtension(screen->glx_enable_bits, "GLX_MESA_copy_sub_buffer");
     LogMessage(X_INFO, "AIGLX: enabled GLX_MESA_copy_sub_buffer\n");
 
-    __glXEnableExtension(screen->glx_enable_bits, "GLX_INTEL_swap_event");
-    LogMessage(X_INFO, "AIGLX: enabled GLX_INTEL_swap_event\n");
 
 #if __DRI_DRI2_VERSION >= 3
     if (screen->dri2->base.version >= 3) {
@@ -876,8 +874,10 @@ initializeExtensions(__GLXDRIscreen * screen)
 #endif
 
     if (DRI2HasSwapControl(pScreen)) {
+        __glXEnableExtension(screen->glx_enable_bits, "GLX_INTEL_swap_event");
         __glXEnableExtension(screen->glx_enable_bits, "GLX_SGI_swap_control");
         __glXEnableExtension(screen->glx_enable_bits, "GLX_MESA_swap_control");
+        LogMessage(X_INFO, "AIGLX: enabled GLX_INTEL_swap_event\n");
         LogMessage(X_INFO,
                    "AIGLX: enabled GLX_SGI_swap_control and GLX_MESA_swap_control\n");
     }
commit 116f020102fd6c2a603069a639b113dfa31b48b7
Merge: cf89aa5 0f537da
Author: Keith Packard <keithp at keithp.com>
Date:   Mon Mar 18 11:18:58 2013 -0700

    Merge remote-tracking branch 'whot/next'

commit cf89aa53748b964f9d9eceaa12a7d6f1a076d1ee
Author: Tomasz Lis <tomasz.lis at intel.com>
Date:   Mon Mar 11 10:21:28 2013 +0100

    Full support of sRGB capable fbconfigs.
    
    Changes to correctly initialize the sRGB capability attribute and
    transfer it between XServer and the client. Modifications include
    extension string, transferring visual config attribs and fbconfig
    attribs. Also, attribute is initialized in the modules which do not
    really use it (xquartz and xwin).
    This version advertises both ARB and EXT strings, and initializes
    the capability to default value of FALSE. It has corrected required
    GLX version and does not influence swrast. The sRGB capable attribute
    is attached only to those configs which do have this capability.
    Both ARB and EXT versions share the same GLX extension enabling bit.
    
    Signed-off-by: Tomasz Lis <tomasz.lis at intel.com>
    Reviewed-by: Ian Romanick <ian.d.romanick at intel.com>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/glx/extension_string.c b/glx/extension_string.c
index 544ca1f..58f930f 100644
--- a/glx/extension_string.c
+++ b/glx/extension_string.c
@@ -71,9 +71,11 @@ static const struct extension_info known_glx_extensions[] = {
     { GLX(ARB_create_context),          VER(0,0), N, },
     { GLX(ARB_create_context_profile),  VER(0,0), N, },
     { GLX(ARB_create_context_robustness), VER(0,0), N, },
+    { GLX(ARB_framebuffer_sRGB),        VER(0,0), N, },
     { GLX(ARB_multisample),             VER(1,4), Y, },
 
     { GLX(EXT_create_context_es2_profile), VER(0,0), N, },
+    { GLX(EXT_framebuffer_sRGB),        VER(0,0), N, },
     { GLX(EXT_import_context),          VER(0,0), Y, },
     { GLX(EXT_texture_from_pixmap),     VER(0,0), Y, },
     { GLX(EXT_visual_info),             VER(0,0), Y, },
diff --git a/glx/extension_string.h b/glx/extension_string.h
index 7a4a8b1..81b7de3 100644
--- a/glx/extension_string.h
+++ b/glx/extension_string.h
@@ -39,6 +39,7 @@ enum {
     ARB_create_context_bit = 0,
     ARB_create_context_profile_bit,
     ARB_create_context_robustness_bit,
+    ARB_framebuffer_sRGB_bit,
     ARB_multisample_bit,
     EXT_create_context_es2_profile_bit,
     EXT_import_context_bit,
@@ -58,6 +59,10 @@ enum {
     __NUM_GLX_EXTS,
 };
 
+/* For extensions which have identical ARB and EXT implementation
+ * in GLX area, use one enabling bit for both. */
+#define EXT_framebuffer_sRGB_bit ARB_framebuffer_sRGB_bit
+
 #define __GLX_EXT_BYTES ((__NUM_GLX_EXTS + 7) / 8)
 
 extern int __glXGetExtensionString(const unsigned char *enable_bits,
diff --git a/glx/glxcmds.c b/glx/glxcmds.c
index c1f4e22..5b7a628 100644
--- a/glx/glxcmds.c
+++ b/glx/glxcmds.c
@@ -913,7 +913,7 @@ __glXDisp_CopyContext(__GLXclientState * cl, GLbyte * pc)
 
 enum {
     GLX_VIS_CONFIG_UNPAIRED = 18,
-    GLX_VIS_CONFIG_PAIRED = 20
+    GLX_VIS_CONFIG_PAIRED = 22
 };
 
 enum {
@@ -1005,8 +1005,17 @@ __glXDisp_GetVisualConfigs(__GLXclientState * cl, GLbyte * pc)
         buf[p++] = modes->samples;
         buf[p++] = GLX_SAMPLE_BUFFERS_SGIS;
         buf[p++] = modes->sampleBuffers;
-        buf[p++] = 0;           /* copy over visualSelectGroup (GLX_VISUAL_SELECT_GROUP_SGIX)? */
-        buf[p++] = 0;
+        /* Add attribute only if its value is not default. */
+        if (modes->sRGBCapable != GL_FALSE) {
+            buf[p++] = GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT;
+            buf[p++] = modes->sRGBCapable;
+        }
+        /* Don't add visualSelectGroup (GLX_VISUAL_SELECT_GROUP_SGIX)?
+         * Pad the remaining place with zeroes, so that attributes count is constant. */
+        while (p < GLX_VIS_CONFIG_TOTAL) {
+            buf[p++] = 0;
+            buf[p++] = 0;
+        }
 
         assert(p == GLX_VIS_CONFIG_TOTAL);
         if (client->swapped) {
@@ -1017,7 +1026,7 @@ __glXDisp_GetVisualConfigs(__GLXclientState * cl, GLbyte * pc)
     return Success;
 }
 
-#define __GLX_TOTAL_FBCONFIG_ATTRIBS (36)
+#define __GLX_TOTAL_FBCONFIG_ATTRIBS (37)
 #define __GLX_FBCONFIG_ATTRIBS_LENGTH (__GLX_TOTAL_FBCONFIG_ATTRIBS * 2)
 /**
  * Send the set of GLXFBConfigs to the client.  There is not currently
@@ -1109,6 +1118,15 @@ DoGetFBConfigs(__GLXclientState * cl, unsigned screen)
         WRITE_PAIR(GLX_BIND_TO_MIPMAP_TEXTURE_EXT, modes->bindToMipmapTexture);
         WRITE_PAIR(GLX_BIND_TO_TEXTURE_TARGETS_EXT,
                    modes->bindToTextureTargets);
+        /* Add attribute only if its value is not default. */
+        if (modes->sRGBCapable != GL_FALSE) {
+            WRITE_PAIR(GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT, modes->sRGBCapable);
+        }
+        /* Pad the remaining place with zeroes, so that attributes count is constant. */
+        while (p < __GLX_FBCONFIG_ATTRIBS_LENGTH) {
+            WRITE_PAIR(0, 0);
+        }
+        assert(p == __GLX_FBCONFIG_ATTRIBS_LENGTH);
 
         if (client->swapped) {
             __GLX_SWAP_INT_ARRAY(buf, __GLX_FBCONFIG_ATTRIBS_LENGTH);
diff --git a/glx/glxdri2.c b/glx/glxdri2.c
index b26e501..8fba6a8 100644
--- a/glx/glxdri2.c
+++ b/glx/glxdri2.c
@@ -882,6 +882,13 @@ initializeExtensions(__GLXDRIscreen * screen)
                    "AIGLX: enabled GLX_SGI_swap_control and GLX_MESA_swap_control\n");
     }
 
+    /* enable EXT_framebuffer_sRGB extension (even if there are no sRGB capable fbconfigs) */
+    {
+        __glXEnableExtension(screen->glx_enable_bits,
+                 "GLX_EXT_framebuffer_sRGB");
+        LogMessage(X_INFO, "AIGLX: enabled GLX_EXT_framebuffer_sRGB\n");
+    }
+
     for (i = 0; extensions[i]; i++) {
 #ifdef __DRI_READ_DRAWABLE
         if (strcmp(extensions[i]->name, __DRI_READ_DRAWABLE) == 0) {
diff --git a/glx/glxdricommon.c b/glx/glxdricommon.c
index c90f380..b027f24 100644
--- a/glx/glxdricommon.c
+++ b/glx/glxdricommon.c
@@ -105,7 +105,9 @@ __ATTRIB(__DRI_ATTRIB_BUFFER_SIZE, rgbBits),
         __ATTRIB(__DRI_ATTRIB_BIND_TO_TEXTURE_RGB, bindToTextureRgb),
         __ATTRIB(__DRI_ATTRIB_BIND_TO_TEXTURE_RGBA, bindToTextureRgba),
         __ATTRIB(__DRI_ATTRIB_BIND_TO_MIPMAP_TEXTURE, bindToMipmapTexture),
-        __ATTRIB(__DRI_ATTRIB_YINVERTED, yInverted),};
+        __ATTRIB(__DRI_ATTRIB_YINVERTED, yInverted),
+        __ATTRIB(__DRI_ATTRIB_FRAMEBUFFER_SRGB_CAPABLE, sRGBCapable),
+        };
 
 static void
 setScalar(__GLXconfig * config, unsigned int attrib, unsigned int value)
diff --git a/glx/glxscreens.h b/glx/glxscreens.h
index b29df58..0a7b604 100644
--- a/glx/glxscreens.h
+++ b/glx/glxscreens.h
@@ -102,6 +102,9 @@ struct __GLXconfig {
     GLint bindToMipmapTexture;
     GLint bindToTextureTargets;
     GLint yInverted;
+
+    /* ARB_framebuffer_sRGB */
+    GLint sRGBCapable;
 };
 
 GLint glxConvertToXVisualType(int visualType);
diff --git a/hw/xquartz/GL/visualConfigs.c b/hw/xquartz/GL/visualConfigs.c
index 03486cd..a00abf2 100644
--- a/hw/xquartz/GL/visualConfigs.c
+++ b/hw/xquartz/GL/visualConfigs.c
@@ -262,6 +262,9 @@ __GLXconfig *__glXAquaCreateVisualConfigs(int *numConfigsPtr, int screenNumber)
                                         c->bindToTextureTargets = 0;
                                         c->yInverted = 0;
 
+                                        /* EXT_framebuffer_sRGB */
+                                        c->sRGBCapable = GL_FALSE;
+
                                         c = c->next;
                                     }
                                 }
diff --git a/hw/xwin/glx/indirect.c b/hw/xwin/glx/indirect.c
index 00cef36..14a4711 100644
--- a/hw/xwin/glx/indirect.c
+++ b/hw/xwin/glx/indirect.c
@@ -2025,6 +2025,7 @@ glxWinCreateConfigs(HDC hdc, glxWinScreen * screen)
         c->base.bindToMipmapTexture = -1;
         c->base.bindToTextureTargets = -1;
         c->base.yInverted = -1;
+        c->base.sRGBCapable = 0;
 
         n++;
 
@@ -2419,6 +2420,7 @@ glxWinCreateConfigsExt(HDC hdc, glxWinScreen * screen)
             GLX_TEXTURE_1D_BIT_EXT | GLX_TEXTURE_2D_BIT_EXT |
             GLX_TEXTURE_RECTANGLE_BIT_EXT;
         c->base.yInverted = -1;
+        c->base.sRGBCapable = 0;
 
         n++;
 
commit 679ccecd8bc6d797e99f3b707f8041b727ca7a49
Author: Keith Packard <keithp at keithp.com>
Date:   Mon Mar 18 10:01:20 2013 -0700

    Bump release to 1.14.99.0
    
    Get us off the release number so that we don't conflict with the
    stable branch.
    
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/configure.ac b/configure.ac
index 6e1ff65..d221de7 100644
--- a/configure.ac
+++ b/configure.ac
@@ -26,9 +26,9 @@ dnl
 dnl Process this file with autoconf to create configure.
 
 AC_PREREQ(2.60)
-AC_INIT([xorg-server], 1.14.0, [https://bugs.freedesktop.org/enter_bug.cgi?product=xorg], xorg-server)
-RELEASE_DATE="2013-03-05"
-RELEASE_NAME="Keemun Mao Feng"
+AC_INIT([xorg-server], 1.14.99.0, [https://bugs.freedesktop.org/enter_bug.cgi?product=xorg], xorg-server)
+RELEASE_DATE="2013-03-18"
+RELEASE_NAME="Pok Pok Meyer Lemon"
 AC_CONFIG_SRCDIR([Makefile.am])
 AM_INIT_AUTOMAKE([foreign dist-bzip2])
 
commit 7050aae69c2a55dfdbb5c6af7882307e90ba4275
Author: Robert Morell <rmorell at nvidia.com>
Date:   Tue Mar 12 09:40:16 2013 -0700

    list.h: Make xorg_list_init inline
    
    Otherwise this file is emitted in every unit that includes it.
    
    Signed-off-by: Robert Morell <rmorell at nvidia.com>
    Reviewed-by: Jamey Sharp <jamey at minilop.net>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/include/list.h b/include/list.h
index 067c679..11de7c5 100644
--- a/include/list.h
+++ b/include/list.h
@@ -119,7 +119,7 @@ struct xorg_list {
  *
  * @param The list to initialized.
  */
-static void
+static inline void
 xorg_list_init(struct xorg_list *list)
 {
     list->next = list->prev = list;
commit 31595b528645a7e4903eb81da0fc332d78407f25
Author: Robert Morell <rmorell at nvidia.com>
Date:   Tue Mar 12 09:37:43 2013 -0700

    configure.ac: Require inputproto 2.3
    
    This picks up support for Xi pointer barriers in the protocol.
    
    Signed-off-by: Robert Morell <rmorell at nvidia.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/configure.ac b/configure.ac
index 6e1ff65..44982b3 100644
--- a/configure.ac
+++ b/configure.ac
@@ -788,7 +788,7 @@ XPROTO="xproto >= 7.0.22"
 RANDRPROTO="randrproto >= 1.4.0"
 RENDERPROTO="renderproto >= 0.11"
 XEXTPROTO="xextproto >= 7.1.99"
-INPUTPROTO="inputproto >= 2.2.99.1"
+INPUTPROTO="inputproto >= 2.3"
 KBPROTO="kbproto >= 1.0.3"
 FONTSPROTO="fontsproto"
 FIXESPROTO="fixesproto >= 5.0"
commit 3ac2e61705432951f9e1b96b42b4214e7f748f94
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Sat Mar 9 17:12:53 2013 +1000

    xfixes: ifdef PanoramiXFixes* (#62015)
    
    Fixes build failure with --disable-xinerama introduced by
    482e0cb cursor: Move pointer barrier code over to XI
    
    Reason is new include order: sdksyms.sh includes xfixes.h, which previously
    did not include xfixesint.h.
    
    As of 482e0cb xfixes.h includes xibarriers.h which includes xfixesint.h
    
    X.Org Bug 62015 <http://bugs.freedesktop.org/show_bug.cgi?id=62015>
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Tested-by: Daniel Martin <consume.noise at gmail.com>

diff --git a/xfixes/xfixesint.h b/xfixes/xfixesint.h
index 334c71f..44e8890 100644
--- a/xfixes/xfixesint.h
+++ b/xfixes/xfixesint.h
@@ -291,8 +291,10 @@ int
  SProcXFixesDestroyPointerBarrier(ClientPtr client);
 
 /* Xinerama */
+#ifdef PANORAMIX
 extern int (*PanoramiXSaveXFixesVector[XFixesNumberRequests]) (ClientPtr);
 void PanoramiXFixesInit(void);
 void PanoramiXFixesReset(void);
+#endif
 
 #endif                          /* _XFIXESINT_H_ */
commit 5047810a4c20fab444b8c6eb146c55dcdb0d4219
Author: Aaron Plattner <aplattner at nvidia.com>
Date:   Wed Mar 6 09:40:28 2013 -0800

    fb: Rename wfbDestroyGlyphCache
    
    Renaming this function was missed in commit
    9cbcb5bd6a5360a128d15b77a02d8d3351f74366, so both libfb.so and libwfb.so define
    functions named fbDestroyGlyphCache.
    
    Signed-off-by: Aaron Plattner <aplattner at nvidia.com>
    Reviewed-by: Søren Sandmann <ssp at redhat.com>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/fb/wfbrename.h b/fb/wfbrename.h
index 588440c..54d00d0 100644
--- a/fb/wfbrename.h
+++ b/fb/wfbrename.h
@@ -52,6 +52,7 @@
 #define fbCreatePixmap wfbCreatePixmap
 #define fbCreatePixmapBpp wfbCreatePixmapBpp
 #define fbCreateWindow wfbCreateWindow
+#define fbDestroyGlyphCache wfbDestroyGlyphCache
 #define fbDestroyPixmap wfbDestroyPixmap
 #define fbDestroyWindow wfbDestroyWindow
 #define fbDoCopy wfbDoCopy
commit 103b77c59e3638a45179bf6d7908f5c738d2d872
Author: Keith Packard <keithp at keithp.com>
Date:   Tue Mar 5 22:31:17 2013 -0800

    Version bumped to 1.14
    
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/configure.ac b/configure.ac
index 53335b1..6e1ff65 100644
--- a/configure.ac
+++ b/configure.ac
@@ -26,9 +26,9 @@ dnl
 dnl Process this file with autoconf to create configure.
 
 AC_PREREQ(2.60)
-AC_INIT([xorg-server], 1.13.99.902, [https://bugs.freedesktop.org/enter_bug.cgi?product=xorg], xorg-server)
-RELEASE_DATE="2013-02-12"
-RELEASE_NAME="Ginger Beer"
+AC_INIT([xorg-server], 1.14.0, [https://bugs.freedesktop.org/enter_bug.cgi?product=xorg], xorg-server)
+RELEASE_DATE="2013-03-05"
+RELEASE_NAME="Keemun Mao Feng"
 AC_CONFIG_SRCDIR([Makefile.am])
 AM_INIT_AUTOMAKE([foreign dist-bzip2])
 
commit 0f537da72d414ed84e3cd14e3bb7e08565136bd7
Author: Andreas Wettstein <wettstein509 at solnet.ch>
Date:   Sun Mar 3 20:25:44 2013 +0100

    xkb: Fixes to LatchMods/LatchGroup
    
    The main problem this patch addresses is that if a latch is put on
    multi-level key with a Latch/Lock/Set, it is possible that after all
    keys are released, still base modifiers are set, which typically will
    make the keyboard unusable.  To see how it happens (without the patch),
    assume that key AltGr sets Mod5 when pressed by itself, and latches Mod3
    when pressed together with Shift.  Now press Shift, then AltGr and
    release both keys in reverse order.  Mod3 is now latched, and the
    LatchMods filter remains active as the second filter.  Now press AltGr;
    Mod5 base modifier gets set, and the SetMods filter will become active
    as the first filter.  Release AltGr: First, the SetMods filter will set
    clearMods to Mod5, then the LatchMods filter will overwrite clearMods
    with Mod3.  Result: the Mod5 base modifier will remain set.  This
    example becomes practically relevant for the revised German standard
    layout (DIN 2137-1:2012-06).
    
    Other changes implement the latch behaviour more accurately according to
    the specification.  For example, releasing a modifier latching key can
    at the same time clear a locked modifier, promote another modifier that
    is latched to locked, and latch a third modifier.  Overall, what the
    code does should be straightforward to compare what the XKB protocol
    specification demands, see the table in section 6.3.
    
    Finally, releasing a key no longer cancels a latch that has not become
    pending yet.  In my opinion, the specification is not clear; it speaks
    of "operating" a key, which the patch effectivly interprets as "press"
    rather than "press or release".  From my experience, using the latter
    interpretation makes latches on higher levels practically unusable.  In
    the example given above, one would have to release AltGr always before
    Shift to get the Mod3-Latch.  The practical relevance of latches on
    higher levels is once more given by the revised German standard layout.
    
    Signed-off-by: Andreas Wettstein <wettstein509 at solnet.ch>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/xkb/xkbActions.c b/xkb/xkbActions.c
index 416de92..e32005c 100644
--- a/xkb/xkbActions.c
+++ b/xkb/xkbActions.c
@@ -222,7 +222,6 @@ _XkbFilterSetState(XkbSrvInfoPtr xkbi,
 
 #define	LATCH_KEY_DOWN	1
 #define	LATCH_PENDING	2
-#define	NO_LATCH	3
 
 static int
 _XkbFilterLatchState(XkbSrvInfoPtr xkbi,
@@ -230,6 +229,7 @@ _XkbFilterLatchState(XkbSrvInfoPtr xkbi,
 {
 
     if (filter->keycode == 0) { /* initial press */
+        AccessXCancelRepeatKey(xkbi,keycode);
         filter->keycode = keycode;
         filter->active = 1;
         filter->filterOthers = 1;
@@ -250,91 +250,102 @@ _XkbFilterLatchState(XkbSrvInfoPtr xkbi,
     else if (pAction && (filter->priv == LATCH_PENDING)) {
         if (((1 << pAction->type) & XkbSA_BreakLatch) != 0) {
             filter->active = 0;
-            if (filter->upAction.type == XkbSA_LatchMods)
-                xkbi->state.latched_mods &= ~filter->upAction.mods.mask;
-            else
-                xkbi->state.latched_group -=
-                    XkbSAGroup(&filter->upAction.group);
-        }
-        else if ((pAction->type == filter->upAction.type) &&
-                 (pAction->mods.flags == filter->upAction.mods.flags) &&
-                 (pAction->mods.mask == filter->upAction.mods.mask)) {
-            if (filter->upAction.mods.flags & XkbSA_LatchToLock) {
-                XkbControlsPtr ctrls = xkbi->desc->ctrls;
-
-                if (filter->upAction.type == XkbSA_LatchMods)
-                    pAction->mods.type = XkbSA_LockMods;
-                else
-                    pAction->group.type = XkbSA_LockGroup;
-                if (XkbAX_NeedFeedback(ctrls, XkbAX_StickyKeysFBMask) &&
-                    (ctrls->enabled_ctrls & XkbStickyKeysMask)) {
-                    XkbDDXAccessXBeep(xkbi->device, _BEEP_STICKY_LOCK,
-                                      XkbStickyKeysMask);
-                }
-            }
-            else {
-                if (filter->upAction.type == XkbSA_LatchMods)
-                    pAction->mods.type = XkbSA_SetMods;
-                else
-                    pAction->group.type = XkbSA_SetGroup;
-            }
-            if (filter->upAction.type == XkbSA_LatchMods)
-                xkbi->state.latched_mods &= ~filter->upAction.mods.mask;
-            else
-                xkbi->state.latched_group -=
-                    XkbSAGroup(&filter->upAction.group);
-            filter->active = 0;
+            /* If one latch is broken, all latches are broken, so it's no use
+               to find out which particular latch this filter tracks. */
+            xkbi->state.latched_mods = 0;
+            xkbi->state.latched_group = 0;
         }
     }
-    else if (filter->keycode == keycode) {      /* release */
+    else if (filter->keycode == keycode && filter->priv != LATCH_PENDING){
+        /* The test above for LATCH_PENDING skips subsequent releases of the
+           key after it has been released first time and the latch became
+           pending. */
         XkbControlsPtr ctrls = xkbi->desc->ctrls;
-        int needBeep;
-        int beepType = _BEEP_NONE;
+        int needBeep = ((ctrls->enabled_ctrls & XkbStickyKeysMask) &&
+                        XkbAX_NeedFeedback(ctrls, XkbAX_StickyKeysFBMask));
 
-        needBeep = ((ctrls->enabled_ctrls & XkbStickyKeysMask) &&
-                    XkbAX_NeedFeedback(ctrls, XkbAX_StickyKeysFBMask));
         if (filter->upAction.type == XkbSA_LatchMods) {
-            xkbi->clearMods = filter->upAction.mods.mask;
-            if ((filter->upAction.mods.flags & XkbSA_ClearLocks) &&
-                (xkbi->clearMods & xkbi->state.locked_mods) ==
-                xkbi->clearMods) {
-                xkbi->state.locked_mods &= ~xkbi->clearMods;
-                filter->priv = NO_LATCH;
-                beepType = _BEEP_STICKY_UNLOCK;
+            unsigned char mask = filter->upAction.mods.mask;
+            unsigned char common;
+
+            xkbi->clearMods = mask;
+
+            /* ClearLocks */
+            common = mask & xkbi->state.locked_mods;
+            if ((filter->upAction.mods.flags & XkbSA_ClearLocks) && common) {
+                mask &= ~common;
+                xkbi->state.locked_mods &= ~common;
+                if (needBeep)
+                    XkbDDXAccessXBeep(xkbi->device, _BEEP_STICKY_UNLOCK,
+                                      XkbStickyKeysMask);
+            }
+            /* LatchToLock */
+            common = mask & xkbi->state.latched_mods;
+            if ((filter->upAction.mods.flags & XkbSA_LatchToLock) && common) {
+                unsigned char newlocked;
+
+                mask &= ~common;
+                newlocked = common & ~xkbi->state.locked_mods;
+                if(newlocked){
+                    xkbi->state.locked_mods |= newlocked;
+                    if (needBeep)
+                        XkbDDXAccessXBeep(xkbi->device, _BEEP_STICKY_LOCK,
+                                          XkbStickyKeysMask);
+
+                }
+                xkbi->state.latched_mods &= ~common;
+            }
+            /* Latch remaining modifiers, if any. */
+            if (mask) {
+                xkbi->state.latched_mods |= mask;
+                filter->priv = LATCH_PENDING;
+                if (needBeep)
+                    XkbDDXAccessXBeep(xkbi->device, _BEEP_STICKY_LATCH,
+                                      XkbStickyKeysMask);
             }
         }
         else {
             xkbi->groupChange = -XkbSAGroup(&filter->upAction.group);
+            /* ClearLocks */
             if ((filter->upAction.group.flags & XkbSA_ClearLocks) &&
                 (xkbi->state.locked_group)) {
                 xkbi->state.locked_group = 0;
-                filter->priv = NO_LATCH;
-                beepType = _BEEP_STICKY_UNLOCK;
+                if (needBeep)
+                    XkbDDXAccessXBeep(xkbi->device, _BEEP_STICKY_UNLOCK,
+                                      XkbStickyKeysMask);
             }
-        }
-        if (filter->priv == NO_LATCH) {
-            filter->active = 0;
-        }
-        else {
-            filter->priv = LATCH_PENDING;
-            if (filter->upAction.type == XkbSA_LatchMods) {
-                xkbi->state.latched_mods |= filter->upAction.mods.mask;
-                needBeep = xkbi->state.latched_mods ? needBeep : 0;
-                xkbi->state.latched_mods |= filter->upAction.mods.mask;
+            /* LatchToLock */
+            else if ((filter->upAction.group.flags & XkbSA_LatchToLock)
+                     && (xkbi->state.latched_group)) {
+                xkbi->state.locked_group  += XkbSAGroup(&filter->upAction.group);
+                xkbi->state.latched_group -= XkbSAGroup(&filter->upAction.group);
+                if(XkbSAGroup(&filter->upAction.group) && needBeep)
+                    XkbDDXAccessXBeep(xkbi->device, _BEEP_STICKY_LOCK,
+                                      XkbStickyKeysMask);
             }
-            else {
-                xkbi->state.latched_group +=
-                    XkbSAGroup(&filter->upAction.group);
+            /* Latch group */
+            else if(XkbSAGroup(&filter->upAction.group)){
+                xkbi->state.latched_group += XkbSAGroup(&filter->upAction.group);
+                filter->priv = LATCH_PENDING;
+                if (needBeep)
+                    XkbDDXAccessXBeep(xkbi->device, _BEEP_STICKY_LATCH,
+                                      XkbStickyKeysMask);
             }
-            if (needBeep && (beepType == _BEEP_NONE))
-                beepType = _BEEP_STICKY_LATCH;
         }
-        if (needBeep && (beepType != _BEEP_NONE))
-            XkbDDXAccessXBeep(xkbi->device, beepType, XkbStickyKeysMask);
+
+        if (filter->priv != LATCH_PENDING)
+            filter->active = 0;
     }
-    else if (filter->priv == LATCH_KEY_DOWN) {
-        filter->priv = NO_LATCH;
-        filter->filterOthers = 0;
+    else if (pAction && (filter->priv == LATCH_KEY_DOWN)) {
+        /* Latch was broken before it became pending: degrade to a
+           SetMods/SetGroup. */
+        if (filter->upAction.type == XkbSA_LatchMods)
+            filter->upAction.type = XkbSA_SetMods;
+        else
+            filter->upAction.type = XkbSA_SetGroup;
+        filter->filter = _XkbFilterSetState;
+        filter->priv = 0;
+        return filter->filter(xkbi, filter, keycode, pAction);
     }
     return 1;
 }
commit eadda231091aa6feb68207ee22f6bc3a390d4556
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Feb 15 11:19:09 2013 +1000

    xephyr: fix "set but not used warnings"
    
    ephyrvideo.c: In function 'ephyrPutVideo':
    ephyrvideo.c:1009:42: warning: variable 'drw_h' set but not used
    ephyrvideo.c:1009:31: warning: variable 'drw_w' set but not used
    ephyrvideo.c:1009:20: warning: variable 'drw_y' set but not used
    ephyrvideo.c:1009:9: warning: variable 'drw_x' set but not used
    ephyrvideo.c: In function 'ephyrGetVideo':
    ephyrvideo.c:1058:42: warning: variable 'drw_h' set but not used
    ephyrvideo.c:1058:31: warning: variable 'drw_w' set but not used
    ephyrvideo.c:1058:20: warning: variable 'drw_y' set but not used
    ephyrvideo.c:1058:9: warning: variable 'drw_x' set but not used
    ephyrvideo.c: In function 'ephyrPutStill':
    ephyrvideo.c:1107:42: warning: variable 'drw_h' set but not used
    ephyrvideo.c:1107:31: warning: variable 'drw_w' set but not used
    ephyrvideo.c:1107:20: warning: variable 'drw_y' set but not used
    ephyrvideo.c:1107:9: warning: variable 'drw_x' set but not used
    ephyrvideo.c: In function 'ephyrGetStill':
    ephyrvideo.c:1156:42: warning: variable 'drw_h' set but not used
    ephyrvideo.c:1156:31: warning: variable 'drw_w' set but not used
    ephyrvideo.c:1156:20: warning: variable 'drw_y' set but not used
    ephyrvideo.c:1156:9: warning: variable 'drw_x' set but not used
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Robert Morell <rmorell at nvidia.com>

diff --git a/hw/kdrive/ephyr/ephyrvideo.c b/hw/kdrive/ephyr/ephyrvideo.c
index 55dbd2e..dfc29f5 100644
--- a/hw/kdrive/ephyr/ephyrvideo.c
+++ b/hw/kdrive/ephyr/ephyrvideo.c
@@ -1006,7 +1006,6 @@ ephyrPutVideo(KdScreenInfo * a_info,
     EphyrPortPriv *port_priv = a_port_priv;
     BoxRec clipped_area, dst_box;
     int result = BadImplementation;
-    int drw_x = 0, drw_y = 0, drw_w = 0, drw_h = 0;
 
     EPHYR_RETURN_VAL_IF_FAIL(a_info->pScreen, BadValue);
     EPHYR_RETURN_VAL_IF_FAIL(a_drawable && port_priv, BadValue);
@@ -1024,11 +1023,6 @@ ephyrPutVideo(KdScreenInfo * a_info,
         goto out;
     }
 
-    drw_x = clipped_area.x1;
-    drw_y = clipped_area.y1;
-    drw_w = clipped_area.x2 - clipped_area.x1;
-    drw_h = clipped_area.y2 - clipped_area.y1;
-
     if (!ephyrHostXVPutVideo(a_info->pScreen->myNum,
                              port_priv->port_number,
                              a_vid_x, a_vid_y, a_vid_w, a_vid_h,
@@ -1055,7 +1049,6 @@ ephyrGetVideo(KdScreenInfo * a_info,
     EphyrPortPriv *port_priv = a_port_priv;
     BoxRec clipped_area, dst_box;
     int result = BadImplementation;
-    int drw_x = 0, drw_y = 0, drw_w = 0, drw_h = 0;
 
     EPHYR_RETURN_VAL_IF_FAIL(a_info && a_info->pScreen, BadValue);
     EPHYR_RETURN_VAL_IF_FAIL(a_drawable && port_priv, BadValue);
@@ -1073,11 +1066,6 @@ ephyrGetVideo(KdScreenInfo * a_info,
         goto out;
     }
 
-    drw_x = clipped_area.x1;
-    drw_y = clipped_area.y1;
-    drw_w = clipped_area.x2 - clipped_area.x1;
-    drw_h = clipped_area.y2 - clipped_area.y1;
-
     if (!ephyrHostXVGetVideo(a_info->pScreen->myNum,
                              port_priv->port_number,
                              a_vid_x, a_vid_y, a_vid_w, a_vid_h,
@@ -1104,7 +1092,6 @@ ephyrPutStill(KdScreenInfo * a_info,
     EphyrPortPriv *port_priv = a_port_priv;
     BoxRec clipped_area, dst_box;
     int result = BadImplementation;
-    int drw_x = 0, drw_y = 0, drw_w = 0, drw_h = 0;
 
     EPHYR_RETURN_VAL_IF_FAIL(a_info && a_info->pScreen, BadValue);
     EPHYR_RETURN_VAL_IF_FAIL(a_drawable && port_priv, BadValue);
@@ -1122,11 +1109,6 @@ ephyrPutStill(KdScreenInfo * a_info,
         goto out;
     }
 
-    drw_x = clipped_area.x1;
-    drw_y = clipped_area.y1;
-    drw_w = clipped_area.x2 - clipped_area.x1;
-    drw_h = clipped_area.y2 - clipped_area.y1;
-
     if (!ephyrHostXVPutStill(a_info->pScreen->myNum,
                              port_priv->port_number,
                              a_vid_x, a_vid_y, a_vid_w, a_vid_h,
@@ -1153,7 +1135,6 @@ ephyrGetStill(KdScreenInfo * a_info,
     EphyrPortPriv *port_priv = a_port_priv;
     BoxRec clipped_area, dst_box;
     int result = BadImplementation;
-    int drw_x = 0, drw_y = 0, drw_w = 0, drw_h = 0;
 
     EPHYR_RETURN_VAL_IF_FAIL(a_info && a_info->pScreen, BadValue);
     EPHYR_RETURN_VAL_IF_FAIL(a_drawable && port_priv, BadValue);
@@ -1171,11 +1152,6 @@ ephyrGetStill(KdScreenInfo * a_info,
         goto out;
     }
 
-    drw_x = clipped_area.x1;
-    drw_y = clipped_area.y1;
-    drw_w = clipped_area.x2 - clipped_area.x1;
-    drw_h = clipped_area.y2 - clipped_area.y1;
-
     if (!ephyrHostXVGetStill(a_info->pScreen->myNum,
                              port_priv->port_number,
                              a_vid_x, a_vid_y, a_vid_w, a_vid_h,
commit 4149ee8ec0193acbf3812c7ee2627b93b9a89997
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Feb 15 11:19:08 2013 +1000

    kdrive: fix "set but not used" warnings
    
    kinput.c: In function 'KdEnqueueKeyboardEvent':
    kinput.c:1845:16: warning: variable 'ctrl' set but not used
    kinput.c:1844:17: warning: variable 'keyc' set but not used
    
    kinput.c: In function 'KdEnqueuePointerEvent':
    kinput.c:1887:12: warning: variable 'ms' set but not used
    
    kxv.c: In function 'KdXVDisable':
    kxv.c:1181:19: warning: variable 'ScreenPriv' set but not used
    
    mouse.c: In function 'ps2SkipInit':
    mouse.c:444:9: warning: variable 'skipping' set but not used
    mouse.c: In function 'ps2Init':
    mouse.c:473:10: warning: variable 'waiting' set but not used
    mouse.c:472:9: warning: variable 'skipping' set but not used
    
    fbdev.c: In function 'fbdevRandRSetConfig':
    fbdev.c:468:19: warning: variable 'newheight' set but not used
    fbdev.c:468:9: warning: variable 'newwidth' set but not used
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Robert Morell <rmorell at nvidia.com>

diff --git a/hw/kdrive/fbdev/fbdev.c b/hw/kdrive/fbdev/fbdev.c
index fd14afa..fb6e3a2 100644
--- a/hw/kdrive/fbdev/fbdev.c
+++ b/hw/kdrive/fbdev/fbdev.c
@@ -465,16 +465,6 @@ fbdevRandRSetConfig(ScreenPtr pScreen,
     int oldheight;
     int oldmmwidth;
     int oldmmheight;
-    int newwidth, newheight;
-
-    if (screen->randr & (RR_Rotate_0 | RR_Rotate_180)) {
-        newwidth = pSize->width;
-        newheight = pSize->height;
-    }
-    else {
-        newwidth = pSize->height;
-        newheight = pSize->width;
-    }
 
     if (wasEnabled)
         KdDisableScreen(pScreen);
diff --git a/hw/kdrive/linux/mouse.c b/hw/kdrive/linux/mouse.c
index c875077..f442447 100644
--- a/hw/kdrive/linux/mouse.c
+++ b/hw/kdrive/linux/mouse.c
@@ -441,10 +441,8 @@ ps2SkipInit(KdPointerInfo * pi, int ninit, Bool ret_next)
 {
     Kmouse *km = pi->driverPrivate;
     int c = -1;
-    int skipping;
     Bool waiting;
 
-    skipping = 0;
     waiting = FALSE;
     while (ninit || ret_next) {
         c = MouseReadByte(&km->iob, MOUSE_TIMEOUT);
@@ -469,8 +467,6 @@ static Bool
 ps2Init(KdPointerInfo * pi)
 {
     Kmouse *km = pi->driverPrivate;
-    int skipping;
-    Bool waiting;
     int id;
     unsigned char *init;
     int ninit;
@@ -483,8 +479,6 @@ ps2Init(KdPointerInfo * pi)
      */
     if (!MouseWriteByte(km->iob.fd, PSMC_SEND_DEV_ID, 100))
         return FALSE;
-    skipping = 0;
-    waiting = FALSE;
     id = ps2SkipInit(pi, 0, TRUE);
     switch (id) {
     case 3:
diff --git a/hw/kdrive/src/kinput.c b/hw/kdrive/src/kinput.c
index b1068bb..c30f170 100644
--- a/hw/kdrive/src/kinput.c
+++ b/hw/kdrive/src/kinput.c
@@ -1821,16 +1821,11 @@ KdEnqueueKeyboardEvent(KdKeyboardInfo * ki,
                        unsigned char scan_code, unsigned char is_up)
 {
     unsigned char key_code;
-    KeyClassPtr keyc = NULL;
-    KeybdCtrl *ctrl = NULL;
     int type;
 
     if (!ki || !ki->dixdev || !ki->dixdev->kbdfeed || !ki->dixdev->key)
         return;
 
-    keyc = ki->dixdev->key;
-    ctrl = &ki->dixdev->kbdfeed->ctrl;
-
     if (scan_code >= ki->minScanCode && scan_code <= ki->maxScanCode) {
         key_code = scan_code + KD_MIN_KEYCODE - ki->minScanCode;
 
@@ -1864,7 +1859,6 @@ void
 KdEnqueuePointerEvent(KdPointerInfo * pi, unsigned long flags, int rx, int ry,
                       int rz)
 {
-    CARD32 ms;
     unsigned char buttons;
     int x, y, z;
     int (*matrix)[3] = kdPointerMatrix.matrix;
@@ -1875,8 +1869,6 @@ KdEnqueuePointerEvent(KdPointerInfo * pi, unsigned long flags, int rx, int ry,
     if (!pi)
         return;
 
-    ms = GetTimeInMillis();
-
     /* we don't need to transform z, so we don't. */
     if (flags & KD_MOUSE_DELTA) {
         if (pi->transformCoordinates) {
diff --git a/hw/kdrive/src/kxv.c b/hw/kdrive/src/kxv.c
index cf65636..2263972 100644
--- a/hw/kdrive/src/kxv.c
+++ b/hw/kdrive/src/kxv.c
@@ -1174,7 +1174,6 @@ void
 KdXVDisable(ScreenPtr pScreen)
 {
     XvScreenPtr pxvs;
-    KdXVScreenPtr ScreenPriv;
     XvAdaptorPtr pAdaptor;
     XvPortPtr pPort;
     XvPortRecPrivatePtr pPriv;
@@ -1184,7 +1183,6 @@ KdXVDisable(ScreenPtr pScreen)
         return;
 
     pxvs = GET_XV_SCREEN(pScreen);
-    ScreenPriv = GET_KDXV_SCREEN(pScreen);
 
     for (i = 0; i < pxvs->nAdaptors; i++) {
         pAdaptor = &pxvs->pAdaptors[i];
commit 44fc062f85df7288c17d2d64b73aa4957b91fd6d
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Feb 18 14:57:58 2013 +1000

    os: document pnprintf as sigsafe snprintf
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/os/log.c b/os/log.c
index 95bd8cc..dc6e288 100644
--- a/os/log.c
+++ b/os/log.c
@@ -279,6 +279,10 @@ LogSetParameter(LogParameter param, int value)
     }
 }
 
+/**
+ * Signal-safe snprintf, with some limitations over snprintf. Be careful
+ * which directives you use.
+ */
 static int
 pnprintf(char *string, size_t size, const char *f, va_list args)
 {
commit c100211034ab69ce453a1644fb61c6808d7e3eda
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Tue Dec 18 14:12:40 2012 +1000

    dix: only show the cursor if a window defines one (#58398)
    
    e02f864fdf "Suppress cursor display until the first XDefineCursor() request"
    disabled cursor display a priori unless -retro is given.
    
    On a plain server, caling XFixesHideCursor() and XFixesShowCursor() would
    show the default root cursor, despite no client actually defining a cursor.
    
    Change the logic, disable CursorVisible by default and only enable it from
    the window's CWCursor logic. If no window ever defines a cursor, said cursor
    stays invisible.
    
    X.Org Bug 58398 <http://bugs.freedesktop.org/show_bug.cgi?id=58398>
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Tested-by: Bastien Nocera <hadess at hadess.net>
    Reviewed-by: Daniel Martin <consume.noise at gmail.com>

diff --git a/dix/window.c b/dix/window.c
index a5b28a6..a9297f3 100644
--- a/dix/window.c
+++ b/dix/window.c
@@ -1431,6 +1431,8 @@ ChangeWindowAttributes(WindowPtr pWin, Mask vmask, XID *vlist, ClientPtr client)
                     }
                 }
 
+                CursorVisible = TRUE;
+
                 if (pWin->realized)
                     WindowHasNewCursor(pWin);
 
@@ -3430,6 +3432,8 @@ ChangeWindowDeviceCursor(WindowPtr pWin, DeviceIntPtr pDev, CursorPtr pCursor)
     }
 
  out:
+    CursorVisible = TRUE;
+
     if (pWin->realized)
         WindowHasNewCursor(pWin);
 
diff --git a/include/input.h b/include/input.h
index 5c65597..304895f 100644
--- a/include/input.h
+++ b/include/input.h
@@ -638,6 +638,11 @@ extern _X_HIDDEN void valuator_set_mode(DeviceIntPtr dev, int axis, int mode);
    xfixes/cursor.c uses it to determine if the cursor is enabled */
 extern Bool EnableCursor;
 
+/* Set to FALSE by default - ChangeWindowAttributes sets it to TRUE on
+ * CWCursor, xfixes/cursor.c uses it to determine if the cursor is enabled
+ */
+extern Bool CursorVisible;
+
 extern _X_EXPORT ValuatorMask *valuator_mask_new(int num_valuators);
 extern _X_EXPORT void valuator_mask_free(ValuatorMask **mask);
 extern _X_EXPORT void valuator_mask_set_range(ValuatorMask *mask,
diff --git a/xfixes/cursor.c b/xfixes/cursor.c
index 568e717..90a026b 100644
--- a/xfixes/cursor.c
+++ b/xfixes/cursor.c
@@ -129,8 +129,7 @@ typedef struct _CursorScreen {
 #define Unwrap(as,s,elt,backup)	(((backup) = (s)->elt), (s)->elt = (as)->elt)
 
 /* The cursor doesn't show up until the first XDefineCursor() */
-static Bool CursorVisible = FALSE;
-
+Bool CursorVisible = FALSE;
 Bool EnableCursor = TRUE;
 
 static Bool
@@ -142,12 +141,7 @@ CursorDisplayCursor(DeviceIntPtr pDev, ScreenPtr pScreen, CursorPtr pCursor)
 
     Unwrap(cs, pScreen, DisplayCursor, backupProc);
 
-    /*
-     * Have to check ConnectionInfo to distinguish client requests from
-     * initial root window setup.  Not a great way to do it, I admit.
-     */
-    if (ConnectionInfo)
-        CursorVisible = EnableCursor;
+    CursorVisible = CursorVisible && EnableCursor;
 
     if (cs->pCursorHideCounts != NULL || !CursorVisible) {
         ret = (*pScreen->DisplayCursor) (pDev, pScreen, NullCursor);
commit 6238bd68bd71323f8b4f1808f34dabe2ae447fe3
Author: Aaron Plattner <aplattner at nvidia.com>
Date:   Tue Mar 5 13:04:46 2013 -0800

    DPMS: include GPU screens in DPMS code
    
    Otherwise, displays driven by GPU screens remain on all the time.
    
    Signed-off-by: Aaron Plattner <aplattner at nvidia.com>
    Reviewed-by: Alex Deucher <alexander.deucher at amd.com>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/hw/xfree86/common/xf86DPMS.c b/hw/xfree86/common/xf86DPMS.c
index ef4a2c1..3f1e142 100644
--- a/hw/xfree86/common/xf86DPMS.c
+++ b/hw/xfree86/common/xf86DPMS.c
@@ -130,6 +130,19 @@ DPMSClose(ScreenPtr pScreen)
     return pScreen->CloseScreen(pScreen);
 }
 
+static void
+DPMSSetScreen(ScrnInfoPtr pScrn, int level)
+{
+    ScreenPtr pScreen = xf86ScrnToScreen(pScrn);
+    DPMSPtr pDPMS = dixLookupPrivate(&pScreen->devPrivates, DPMSKey);
+
+    if (pDPMS && pScrn->DPMSSet && pDPMS->Enabled && pScrn->vtSema) {
+        xf86VGAarbiterLock(pScrn);
+        pScrn->DPMSSet(pScrn, level, 0);
+        xf86VGAarbiterUnlock(pScrn);
+    }
+}
+
 /*
  * DPMSSet --
  *	Device dependent DPMS mode setting hook.  This is called whenever
@@ -139,8 +152,6 @@ int
 DPMSSet(ClientPtr client, int level)
 {
     int rc, i;
-    DPMSPtr pDPMS;
-    ScrnInfoPtr pScrn;
 
     DPMSPowerLevel = level;
 
@@ -155,17 +166,23 @@ DPMSSet(ClientPtr client, int level)
 
     /* For each screen, set the DPMS level */
     for (i = 0; i < xf86NumScreens; i++) {
-        pScrn = xf86Screens[i];
-        pDPMS = dixLookupPrivate(&screenInfo.screens[i]->devPrivates, DPMSKey);
-        if (pDPMS && pScrn->DPMSSet && pDPMS->Enabled && pScrn->vtSema) {
-            xf86VGAarbiterLock(pScrn);
-            pScrn->DPMSSet(pScrn, level, 0);
-            xf86VGAarbiterUnlock(pScrn);
-        }
+        DPMSSetScreen(xf86Screens[i], level);
+    }
+    for (i = 0; i < xf86NumGPUScreens; i++) {
+        DPMSSetScreen(xf86GPUScreens[i], level);
     }
     return Success;
 }
 
+static Bool
+DPMSSupportedOnScreen(ScrnInfoPtr pScrn)
+{
+    ScreenPtr pScreen = xf86ScrnToScreen(pScrn);
+    DPMSPtr pDPMS = dixLookupPrivate(&pScreen->devPrivates, DPMSKey);
+
+    return pDPMS && pScrn->DPMSSet;
+}
+
 /*
  * DPMSSupported --
  *	Return TRUE if any screen supports DPMS.
@@ -174,8 +191,6 @@ Bool
 DPMSSupported(void)
 {
     int i;
-    DPMSPtr pDPMS;
-    ScrnInfoPtr pScrn;
 
     if (DPMSKey == NULL) {
         return FALSE;
@@ -183,9 +198,11 @@ DPMSSupported(void)
 
     /* For each screen, check if DPMS is supported */
     for (i = 0; i < xf86NumScreens; i++) {
-        pScrn = xf86Screens[i];
-        pDPMS = dixLookupPrivate(&screenInfo.screens[i]->devPrivates, DPMSKey);
-        if (pDPMS && pScrn->DPMSSet)
+        if (DPMSSupportedOnScreen(xf86Screens[i]))
+            return TRUE;
+    }
+    for (i = 0; i < xf86NumGPUScreens; i++) {
+        if (DPMSSupportedOnScreen(xf86GPUScreens[i]))
             return TRUE;
     }
     return FALSE;
commit dd4ab8b572956f9457616869d6e383c8ed964c73
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Tue Mar 5 10:14:29 2013 +1000

    Xi: force dtime to 0 on the first BarrierHit
    
    dtime to the previous event is 0 on the first BarrierHit event.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Jasper St. Pierre <jstpierre at mecheye.net>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/Xi/xibarriers.c b/Xi/xibarriers.c
index a225cbc..fccab86 100644
--- a/Xi/xibarriers.c
+++ b/Xi/xibarriers.c
@@ -435,6 +435,7 @@ input_constrain_cursor(DeviceIntPtr dev, ScreenPtr screen,
     dir = barrier_get_direction(current_x, current_y, x, y);
 
     while (dir != 0) {
+        int new_sequence;
         struct PointerBarrierDevice *pbd;
 
         c = barrier_find_nearest(cs, master, dir, current_x, current_y, x, y);
@@ -444,6 +445,8 @@ input_constrain_cursor(DeviceIntPtr dev, ScreenPtr screen,
         nearest = &c->barrier;
 
         pbd = GetBarrierDevice(c, master->id);
+        new_sequence = !pbd->hit;
+
         pbd->seen = TRUE;
         pbd->hit = TRUE;
 
@@ -466,7 +469,7 @@ input_constrain_cursor(DeviceIntPtr dev, ScreenPtr screen,
         ev.event_id = pbd->barrier_event_id;
         ev.barrierid = c->id;
 
-        ev.dt = ms - pbd->last_timestamp;
+        ev.dt = new_sequence ? 0 : ms - pbd->last_timestamp;
         ev.window = c->window;
         pbd->last_timestamp = ms;
 
commit 604169af8b67afc74a292cdb9070a3a1f2d7c536
Merge: 8f4640b 6ea59dc
Author: Keith Packard <keithp at keithp.com>
Date:   Mon Mar 4 21:09:59 2013 -0800

    Merge commit '6ea59dc2d8887102bfd8d7c838d2e7ab17645aec'

commit 6ea59dc2d8887102bfd8d7c838d2e7ab17645aec
Author: Jasper St. Pierre <jstpierre at mecheye.net>
Date:   Sun Mar 3 04:50:55 2013 -0500

    xibarriers: Remove accidental use of the comma operator
    
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xi/xibarriers.c b/Xi/xibarriers.c
index 7b7b83f..a225cbc 100644
--- a/Xi/xibarriers.c
+++ b/Xi/xibarriers.c
@@ -676,8 +676,8 @@ BarrierFreeBarrier(void *data, XID id)
             continue;
 
         ev.deviceid = dev->id;
-        ev.event_id = pbd->barrier_event_id,
-        ev.dt = ms - pbd->last_timestamp,
+        ev.event_id = pbd->barrier_event_id;
+        ev.dt = ms - pbd->last_timestamp;
 
         GetSpritePosition(dev, &root_x, &root_y);
         ev.root_x = root_x;
commit bd58ebe4cf3b0ce60f87fb26a3715f774dabd349
Author: Daniel Martin <consume.noise at gmail.com>
Date:   Thu Dec 20 13:50:17 2012 +0100

    ephyr: Fix crash on 24bpp host framebuffer
    
    Use bytes_per_line and bits_per_pixel from the created XImage to fix
        https://bugzilla.redhat.com/show_bug.cgi?id=518960
    
    Signed-off-by: Daniel Martin <consume.noise at gmail.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/kdrive/ephyr/ephyr.c b/hw/kdrive/ephyr/ephyr.c
index f32e432..02d4970 100644
--- a/hw/kdrive/ephyr/ephyr.c
+++ b/hw/kdrive/ephyr/ephyr.c
@@ -238,13 +238,11 @@ ephyrMapFramebuffer(KdScreenInfo * screen)
     KdComputePointerMatrix(&m, ephyrRandr, screen->width, screen->height);
     KdSetPointerMatrix(&m);
 
-    priv->bytes_per_line =
-        ((screen->width * screen->fb.bitsPerPixel + 31) >> 5) << 2;
-
     buffer_height = ephyrBufferHeight(screen);
 
     priv->base =
-        hostx_screen_init(screen, screen->width, screen->height, buffer_height);
+        hostx_screen_init(screen, screen->width, screen->height, buffer_height,
+                          &priv->bytes_per_line, &screen->fb.bitsPerPixel);
 
     if ((scrpriv->randr & RR_Rotate_0) && !(scrpriv->randr & RR_Reflect_All)) {
         scrpriv->shadow = FALSE;
diff --git a/hw/kdrive/ephyr/hostx.c b/hw/kdrive/ephyr/hostx.c
index c8642cb..f2b458d 100644
--- a/hw/kdrive/ephyr/hostx.c
+++ b/hw/kdrive/ephyr/hostx.c
@@ -619,7 +619,8 @@ hostx_set_cmap_entry(unsigned char idx,
  */
 void *
 hostx_screen_init(EphyrScreenInfo screen,
-                  int width, int height, int buffer_height)
+                  int width, int height, int buffer_height,
+                  int *bytes_per_line, int *bits_per_pixel)
 {
     int bitmap_pad;
     Bool shm_success = False;
@@ -696,6 +697,9 @@ hostx_screen_init(EphyrScreenInfo screen,
             malloc(host_screen->ximg->bytes_per_line * buffer_height);
     }
 
+    *bytes_per_line = host_screen->ximg->bytes_per_line;
+    *bits_per_pixel = host_screen->ximg->bits_per_pixel;
+
     XResizeWindow(HostX.dpy, host_screen->win, width, height);
 
     /* Ask the WM to keep our size static */
diff --git a/hw/kdrive/ephyr/hostx.h b/hw/kdrive/ephyr/hostx.h
index 31c4053..38b7b37 100644
--- a/hw/kdrive/ephyr/hostx.h
+++ b/hw/kdrive/ephyr/hostx.h
@@ -193,7 +193,8 @@ hostx_set_cmap_entry(unsigned char idx,
                      unsigned char r, unsigned char g, unsigned char b);
 
 void *hostx_screen_init(EphyrScreenInfo screen,
-                        int width, int height, int buffer_height);
+                        int width, int height, int buffer_height,
+                        int *bytes_per_line, int *bits_per_pixel);
 
 void
 
commit 8f4640bdb9d3988148e09a08d2c7e3bab1d538d6
Author: Dave Airlie <airlied at redhat.com>
Date:   Wed Jan 9 12:58:28 2013 +1000

    randr: cleanup provider properly
    
    So in the cold plug server shutdown case, we reap the resources
    before we call CloseScreen handlers, so the config->randr_provider
    is a dangling pointer when the xf86CrtcCloseScreen handler is called,
    
    however in the hot screen unplug case, we can't rely on automatically
    reaped resources, so we need to clean up the provider in the xf86CrtcCloseScreen
    case.
    
    This patch provides a cleanup callback from the randr provider removal
    into the DDX so it can cleanup properly, this then gets called by the automatic
    code for cold plug, or if hot unplug it gets called explicitly.
    
    Fixes a number of random server crashes on shutdown
    Bugzilla: https://bugs.freedesktop.org/show_bug.cgi?id=58174
    Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=891140
    
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Dave Airlie <airlied at redhat.com>

diff --git a/hw/xfree86/modes/xf86Crtc.c b/hw/xfree86/modes/xf86Crtc.c
index b52b6ef..f9ae465 100644
--- a/hw/xfree86/modes/xf86Crtc.c
+++ b/hw/xfree86/modes/xf86Crtc.c
@@ -743,16 +743,8 @@ xf86CrtcCloseScreen(ScreenPtr screen)
     }
     /* detach any providers */
     if (config->randr_provider) {
-        if (config->randr_provider->offload_sink) {
-            DetachOffloadGPU(screen);
-            config->randr_provider->offload_sink = NULL;
-        }
-        else if (config->randr_provider->output_source) {
-            DetachOutputGPU(screen);
-            config->randr_provider->output_source = NULL;
-        }
-        else if (screen->current_master)
-            DetachUnboundGPU(screen);
+        RRProviderDestroy(config->randr_provider);
+        config->randr_provider = NULL;
     }
     return TRUE;
 }
diff --git a/hw/xfree86/modes/xf86RandR12.c b/hw/xfree86/modes/xf86RandR12.c
index 3530abf..01fc9c5 100644
--- a/hw/xfree86/modes/xf86RandR12.c
+++ b/hw/xfree86/modes/xf86RandR12.c
@@ -1885,6 +1885,27 @@ xf86RandR13ConstrainCursorHarder(DeviceIntPtr dev, ScreenPtr screen, int mode, i
     }
 }
 
+static void
+xf86RandR14ProviderDestroy(ScreenPtr screen, RRProviderPtr provider)
+{
+    ScrnInfoPtr scrn = xf86ScreenToScrn(screen);
+    xf86CrtcConfigPtr config = XF86_CRTC_CONFIG_PTR(scrn);
+    
+    if (config->randr_provider == provider) {
+        if (config->randr_provider->offload_sink) {
+            DetachOffloadGPU(screen);
+            config->randr_provider->offload_sink = NULL;
+        }
+        else if (config->randr_provider->output_source) {
+            DetachOutputGPU(screen);
+            config->randr_provider->output_source = NULL;
+        }
+        else if (screen->current_master)
+            DetachUnboundGPU(screen);
+    }
+    config->randr_provider = NULL;
+}
+
 static Bool
 xf86RandR12Init12(ScreenPtr pScreen)
 {
@@ -1914,6 +1935,7 @@ xf86RandR12Init12(ScreenPtr pScreen)
     rp->rrProviderSetProperty = xf86RandR14ProviderSetProperty;
     rp->rrProviderGetProperty = xf86RandR14ProviderGetProperty;
     rp->rrCrtcSetScanoutPixmap = xf86CrtcSetScanoutPixmap;
+    rp->rrProviderDestroy = xf86RandR14ProviderDestroy;
 
     pScrn->PointerMoved = xf86RandR12PointerMoved;
     pScrn->ChangeGamma = xf86RandR12ChangeGamma;
diff --git a/randr/randrstr.h b/randr/randrstr.h
index f52d0f2..2517479 100644
--- a/randr/randrstr.h
+++ b/randr/randrstr.h
@@ -232,6 +232,9 @@ typedef Bool (*RRProviderSetOffloadSinkProcPtr)(ScreenPtr pScreen,
                                          RRProviderPtr offload_sink);
 
 
+typedef void (*RRProviderDestroyProcPtr)(ScreenPtr pScreen,
+                                         RRProviderPtr provider);
+
 /* These are for 1.0 compatibility */
 
 typedef struct _rrRefresh {
@@ -330,6 +333,9 @@ typedef struct _rrScrPriv {
     Bool discontiguous;
 
     RRProviderPtr provider;
+
+    RRProviderDestroyProcPtr rrProviderDestroy;
+
 } rrScrPrivRec, *rrScrPrivPtr;
 
 extern _X_EXPORT DevPrivateKeyRec rrPrivKeyRec;
diff --git a/randr/rrprovider.c b/randr/rrprovider.c
index c4ed515..b321e62 100644
--- a/randr/rrprovider.c
+++ b/randr/rrprovider.c
@@ -389,6 +389,8 @@ RRProviderDestroyResource (pointer value, XID pid)
     {
         rrScrPriv(pScreen);
 
+        if (pScrPriv->rrProviderDestroy)
+            (*pScrPriv->rrProviderDestroy)(pScreen, provider);
         pScrPriv->provider = NULL;
     }
     free(provider);
commit 3ec35c45ca17f5ed6fd02c50fc49ae7b8d128dcb
Author: Dave Airlie <airlied at redhat.com>
Date:   Wed Jan 9 12:53:14 2013 +1000

    xf86: actually set the compat output in the failure case
    
    The previous fix for the previous fix, didn't fully work,
    
    If we don't set compat_output we end up doing derferences
    of arrays with -1, leading to valgrind warnings.
    
    Reviewed-by: Chris Wilson <chris at chris-wilson.co.uk>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Dave Airlie <airlied at redhat.com>

diff --git a/hw/xfree86/modes/xf86Crtc.c b/hw/xfree86/modes/xf86Crtc.c
index b3ded5a..b52b6ef 100644
--- a/hw/xfree86/modes/xf86Crtc.c
+++ b/hw/xfree86/modes/xf86Crtc.c
@@ -1848,8 +1848,10 @@ SetCompatOutput(xf86CrtcConfigPtr config)
     }
 
     /* All outputs are disconnected, select one to fake */
-    if (!output && config->num_output)
-        output = config->output[0];
+    if (!output && config->num_output) {
+        config->compat_output = 0;
+        output = config->output[config->compat_output];
+    }
 
     return output;
 }
commit da8ee26023fc2868fe970471195a5f3c86fb574b
Author: Dave Airlie <airlied at redhat.com>
Date:   Wed Jan 9 12:51:45 2013 +1000

    xfree86/hotplug: cleanup properly if the screen fails to initialise
    
    Due to another bug, the modesetting/udl driver would fail to init properly
    on hotplug, when it did the code didn't clean up properly, and on removing
    the device the server could crash.
    
    Found in F18 testing.
    
    Signed-off-by: Dave Airlie <airlied at redhat.com>
    Reviewed-by: Aaron Plattner <aplattner at nvidia.com>

diff --git a/hw/xfree86/common/xf86platformBus.c b/hw/xfree86/common/xf86platformBus.c
index 0525e39..5866333 100644
--- a/hw/xfree86/common/xf86platformBus.c
+++ b/hw/xfree86/common/xf86platformBus.c
@@ -438,7 +438,12 @@ xf86platformAddDevice(int index)
     }
 
    scr_index = AddGPUScreen(xf86GPUScreens[i]->ScreenInit, 0, NULL);
-
+   if (scr_index == -1) {
+       xf86DeleteScreen(xf86GPUScreens[i]);
+       xf86UnclaimPlatformSlot(&xf86_platform_devices[index], NULL);
+       xf86NumGPUScreens = old_screens;
+       return -1;
+   }
    dixSetPrivate(&xf86GPUScreens[i]->pScreen->devPrivates,
                  xf86ScreenKey, xf86GPUScreens[i]);
 
commit e21e183059df5975e7086850d1931edb2c1bbd06
Author: Marcin Slusarz <marcin.slusarz at gmail.com>
Date:   Thu Feb 21 09:02:44 2013 +1000

    os: use libunwind to generate backtraces
    
    Libunwind generates backtraces much more reliably than glibc's "backtrace".
    
    Before:
    0: /opt/xserver/bin/X (0x400000+0x18ce36) [0x58ce36]
    1: /opt/xserver/bin/X (xorg_backtrace+0x9) [0x58d119]
    2: /opt/xserver/bin/X (0x400000+0x190d69) [0x590d69]
    3: /lib64/libpthread.so.0 (0x7fb904268000+0x10a90) [0x7fb904278a90]
    4: /lib64/libc.so.6 (ioctl+0x7) [0x7fb902fbf987]
    5: /usr/lib64/libdrm.so.2 (drmIoctl+0x28) [0x7fb90405ffa8]
    6: /usr/lib64/libdrm.so.2 (drmCommandWrite+0x1b) [0x7fb90406235b]
    7: /usr/lib64/libdrm_nouveau.so.2 (nouveau_bo_wait+0x89) [0x7fb902009719]
    8: /opt/xserver/lib/xorg/modules/drivers/nouveau_drv.so (0x7fb90220e000+0x76f3) [0x7fb9022156f3]
    9: /opt/xserver/lib/xorg/modules/libexa.so (0x7fb9019c7000+0xbae0) [0x7fb9019d2ae0]
    10: /opt/xserver/bin/X (0x400000+0x17d2b3) [0x57d2b3]
    11: /opt/xserver/bin/X (0x400000+0xc9930) [0x4c9930]
    12: /opt/xserver/bin/X (0x400000+0x3a81a) [0x43a81a]
    13: /opt/xserver/bin/X (0x400000+0x3d6a1) [0x43d6a1]
    14: /opt/xserver/bin/X (0x400000+0x2c2ca) [0x42c2ca]
    15: /lib64/libc.so.6 (__libc_start_main+0xf5) [0x7fb902f019b5]
    16: /opt/xserver/bin/X (0x400000+0x2c60d) [0x42c60d]
    17: ?? [0x0]
    
    After:
    0: /opt/xserver/bin/X (OsSigHandler+0x39) [0x590d69]
    1: /lib64/libpthread.so.0 (__restore_rt+0x0) [0x7fb904278a8f]
    2: /lib64/libc.so.6 (ioctl+0x7) [0x7fb902fbf987]
    3: /usr/lib64/libdrm.so.2 (drmIoctl+0x28) [0x7fb90405ffa8]
    4: /usr/lib64/libdrm.so.2 (drmCommandWrite+0x1b) [0x7fb90406235b]
    5: /usr/lib64/libdrm_nouveau.so.2 (nouveau_bo_wait+0x89) [0x7fb902009719]
    6: /opt/xserver/lib/xorg/modules/drivers/nouveau_drv.so (nouveau_exa_download_from_screen+0x1a3) [0x7fb9022156f3]
    7: /opt/xserver/lib/xorg/modules/libexa.so (exaGetImage+0x1f0) [0x7fb9019d2ae0]
    8: /opt/xserver/bin/X (miSpriteGetImage+0x173) [0x57d2b3]
    9: /opt/xserver/bin/X (compGetImage+0xb0) [0x4c9930]
    10: /opt/xserver/bin/X (ProcGetImage+0x55a) [0x43a81a]
    11: /opt/xserver/bin/X (Dispatch+0x341) [0x43d6a1]
    12: /opt/xserver/bin/X (main+0x3ba) [0x42c2ca]
    13: /lib64/libc.so.6 (__libc_start_main+0xf5) [0x7fb902f019b5]
    14: /opt/xserver/bin/X (_start+0x29) [0x42c60d]
    15: ? (?+0x29) [0x29]
    
    Signed-off-by: Marcin Slusarz <marcin.slusarz at gmail.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Tested-by: Knut Petersen <knut.petersen at t-online.de>

diff --git a/configure.ac b/configure.ac
index 53335b1..8b9cbc9 100644
--- a/configure.ac
+++ b/configure.ac
@@ -308,6 +308,13 @@ AC_CHECK_HEADER([execinfo.h],[
     ])]
 )
 
+PKG_CHECK_MODULES(LIBUNWIND, libunwind, [HAVE_LIBUNWIND=yes], [HAVE_LIBUNWIND=no])
+if test "x$HAVE_LIBUNWIND" = xyes; then
+	AC_DEFINE(HAVE_LIBUNWIND, 1, [Have libunwind support])
+fi
+AM_CONDITIONAL(HAVE_LIBUNWIND, [test "x$HAVE_LIBUNWIND" = xyes])
+
+
 dnl ---------------------------------------------------------------------------
 dnl Bus options and CPU capabilities.  Replaces logic in
 dnl hw/xfree86/os-support/bus/Makefile.am, among others.
@@ -1336,7 +1343,7 @@ AC_DEFINE(BIGREQS, 1, [Support BigRequests extension])
 
 if test "x$SPECIAL_DTRACE_OBJECTS" = "xyes" ; then
   DIX_LIB='$(top_builddir)/dix/dix.O'
-  OS_LIB='$(top_builddir)/os/os.O $(SHA1_LIBS) $(DLOPEN_LIBS)'
+  OS_LIB='$(top_builddir)/os/os.O $(SHA1_LIBS) $(DLOPEN_LIBS) $(LIBUNWIND_LIBS)'
 else
   DIX_LIB='$(top_builddir)/dix/libdix.la'
   OS_LIB='$(top_builddir)/os/libos.la'
diff --git a/include/dix-config.h.in b/include/dix-config.h.in
index e1cb9eb..a643dfc 100644
--- a/include/dix-config.h.in
+++ b/include/dix-config.h.in
@@ -60,6 +60,9 @@
 /* Has backtrace support */
 #undef HAVE_BACKTRACE
 
+/* Has libunwind support */
+#undef HAVE_LIBUNWIND
+
 /* Define to 1 if you have the <byteswap.h> header file. */
 #undef HAVE_BYTESWAP_H
 
diff --git a/os/Makefile.am b/os/Makefile.am
index 8891485..364b6da 100644
--- a/os/Makefile.am
+++ b/os/Makefile.am
@@ -34,6 +34,11 @@ if XDMCP
 libos_la_SOURCES += $(XDMCP_SRCS)
 endif
 
+if HAVE_LIBUNWIND
+AM_CFLAGS += $(LIBUNWIND_CFLAGS)
+libos_la_LIBADD += $(LIBUNWIND_LIBS)
+endif
+
 EXTRA_DIST = $(SECURERPC_SRCS) $(XDMCP_SRCS)
 
 if SPECIAL_DTRACE_OBJECTS
diff --git a/os/backtrace.c b/os/backtrace.c
index daac60c..426f9b1 100644
--- a/os/backtrace.c
+++ b/os/backtrace.c
@@ -30,6 +30,80 @@
 #include <errno.h>
 #include <string.h>
 
+#ifdef HAVE_LIBUNWIND
+
+#define UNW_LOCAL_ONLY
+#include <libunwind.h>
+
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+#include <dlfcn.h>
+
+void
+xorg_backtrace(void)
+{
+    unw_cursor_t cursor;
+    unw_context_t context;
+    unw_word_t off;
+    unw_proc_info_t pip;
+    int ret, i = 0;
+    char procname[256];
+    const char *filename;
+    Dl_info dlinfo;
+
+    pip.unwind_info = NULL;
+    ret = unw_getcontext(&context);
+    if (ret) {
+        ErrorFSigSafe("unw_getcontext failed: %s [%d]\n", unw_strerror(ret),
+                ret);
+        return;
+    }
+
+    ret = unw_init_local(&cursor, &context);
+    if (ret) {
+        ErrorFSigSafe("unw_init_local failed: %s [%d]\n", unw_strerror(ret),
+                ret);
+        return;
+    }
+
+    ErrorFSigSafe("\n");
+    ErrorFSigSafe("Backtrace:\n");
+    ret = unw_step(&cursor);
+    while (ret > 0) {
+        ret = unw_get_proc_info(&cursor, &pip);
+        if (ret) {
+            ErrorFSigSafe("unw_get_proc_info failed: %s [%d]\n",
+                    unw_strerror(ret), ret);
+            break;
+        }
+
+        ret = unw_get_proc_name(&cursor, procname, 256, &off);
+        if (ret && ret != -UNW_ENOMEM) {
+            if (ret != -UNW_EUNSPEC)
+                ErrorFSigSafe("unw_get_proc_name failed: %s [%d]\n",
+                        unw_strerror(ret), ret);
+            procname[0] = '?';
+            procname[1] = 0;
+        }
+
+        if (dladdr((void *)(pip.start_ip + off), &dlinfo) && dlinfo.dli_fname &&
+                *dlinfo.dli_fname)
+            filename = dlinfo.dli_fname;
+        else
+            filename = "?";
+
+        ErrorFSigSafe("%u: %s (%s%s+0x%x) [%p]\n", i++, filename, procname,
+            ret == -UNW_ENOMEM ? "..." : "", (int)off,
+            (void *)(pip.start_ip + off));
+
+        ret = unw_step(&cursor);
+        if (ret < 0)
+            ErrorFSigSafe("unw_step failed: %s [%d]\n", unw_strerror(ret), ret);
+    }
+    ErrorFSigSafe("\n");
+}
+#else /* HAVE_LIBUNWIND */
 #ifdef HAVE_BACKTRACE
 #ifndef _GNU_SOURCE
 #define _GNU_SOURCE
@@ -246,3 +320,4 @@ xorg_backtrace(void)
 
 #endif
 #endif
+#endif
commit e27b2e61632b220ddc36d0d0387581a9f4774f21
Author: Peter Harris <pharris at opentext.com>
Date:   Tue Feb 19 16:08:52 2013 -0500

    xkb: Set nIndicators in XkbGetIndicatorMap
    
    Xlib doesn't use this value (it computes it from the reply length
    instead) which is why nobody has noticed yet. But the spec
    http://www.x.org/releases/X11R7.7/doc/kbproto/xkbproto.html
    says that it should be set.
    
    Signed-off-by: Peter Harris <pharris at opentext.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/xkb/xkb.c b/xkb/xkb.c
index f2bcaee..c78aceb 100644
--- a/xkb/xkb.c
+++ b/xkb/xkb.c
@@ -3073,6 +3073,7 @@ XkbComputeGetIndicatorMapReplySize(XkbIndicatorPtr indicators,
             nIndicators++;
     }
     rep->length = (nIndicators * SIZEOF(xkbIndicatorMapWireDesc)) / 4;
+    rep->nIndicators = nIndicators;
     return Success;
 }
 
commit 3aac7a59dc6ef2d8bbf46ba5d37acdf6013e9450
Author: Daniel Martin <daniel.martin at secunet.com>
Date:   Tue Dec 11 17:23:55 2012 +0100

    ephyr: Add -resizeable option
    
    With this option passed, ephyr windows can be resized like normal
    windows on the fly, without the need of an explicit parent window.
    
    Signed-off-by: Daniel Martin <daniel.martin at secunet.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/kdrive/ephyr/ephyr.c b/hw/kdrive/ephyr/ephyr.c
index e6520d0..f32e432 100644
--- a/hw/kdrive/ephyr/ephyr.c
+++ b/hw/kdrive/ephyr/ephyr.c
@@ -56,6 +56,7 @@ typedef struct _EphyrInputPrivate {
 } EphyrKbdPrivate, EphyrPointerPrivate;
 
 Bool EphyrWantGrayScale = 0;
+Bool EphyrWantResize = 0;
 
 Bool
 ephyrInitialize(KdCardInfo * card, EphyrPriv * priv)
diff --git a/hw/kdrive/ephyr/ephyrinit.c b/hw/kdrive/ephyr/ephyrinit.c
index 5e2eb67..adacac9 100644
--- a/hw/kdrive/ephyr/ephyrinit.c
+++ b/hw/kdrive/ephyr/ephyrinit.c
@@ -31,6 +31,7 @@
 
 extern Window EphyrPreExistingHostWin;
 extern Bool EphyrWantGrayScale;
+extern Bool EphyrWantResize;
 extern Bool kdHasPointer;
 extern Bool kdHasKbd;
 
@@ -116,6 +117,7 @@ ddxUseMsg(void)
     ErrorF("-host-cursor         Re-use exisiting X host server cursor\n");
     ErrorF("-fullscreen          Attempt to run Xephyr fullscreen\n");
     ErrorF("-grayscale           Simulate 8bit grayscale\n");
+    ErrorF("-resizeable          Make Xephyr windows resizeable\n");
     ErrorF
         ("-fakexa              Simulate acceleration using software rendering\n");
     ErrorF("-verbosity <level>   Set log verbosity level\n");
@@ -210,6 +212,10 @@ ddxProcessArgument(int argc, char **argv, int i)
         EphyrWantGrayScale = 1;
         return 1;
     }
+    else if (!strcmp(argv[i], "-resizeable")) {
+        EphyrWantResize = 1;
+        return 1;
+    }
     else if (!strcmp(argv[i], "-fakexa")) {
         ephyrFuncs.initAccel = ephyrDrawInit;
         ephyrFuncs.enableAccel = ephyrDrawEnable;
diff --git a/hw/kdrive/ephyr/hostx.c b/hw/kdrive/ephyr/hostx.c
index aed0285..c8642cb 100644
--- a/hw/kdrive/ephyr/hostx.c
+++ b/hw/kdrive/ephyr/hostx.c
@@ -117,6 +117,8 @@ extern EphyrKeySyms ephyrKeySyms;
 
 extern int monitorResolution;
 
+extern Bool EphyrWantResize;
+
 char *ephyrResName = NULL;
 int ephyrResNameFromCmd = 0;
 char *ephyrTitle = NULL;
@@ -697,7 +699,7 @@ hostx_screen_init(EphyrScreenInfo screen,
     XResizeWindow(HostX.dpy, host_screen->win, width, height);
 
     /* Ask the WM to keep our size static */
-    if (host_screen->win_pre_existing == None) {
+    if (host_screen->win_pre_existing == None && !EphyrWantResize) {
         size_hints = XAllocSizeHints();
         size_hints->max_width = size_hints->min_width = width;
         size_hints->max_height = size_hints->min_height = height;
@@ -1012,19 +1014,27 @@ hostx_get_event(EphyrHostXEvent * ev)
 
         case ConfigureNotify:
         {
-            struct EphyrHostScreen *host_screen =
-                host_screen_from_window(xev.xconfigure.window);
-
-            if (host_screen && host_screen->win_pre_existing != None) {
-                ev->type = EPHYR_EV_CONFIGURE;
-                ev->data.configure.width = xev.xconfigure.width;
-                ev->data.configure.height = xev.xconfigure.height;
-                ev->data.configure.window = xev.xconfigure.window;
-                ev->data.configure.screen = host_screen->mynum;
-                return 1;
+            struct EphyrHostScreen *host_screen;
+
+            /* event compression as for Expose events, cause
+             * we don't want to resize the framebuffer for
+             * every single change */
+            while (XCheckTypedWindowEvent(HostX.dpy, xev.xconfigure.window,
+                                          ConfigureNotify, &xev));
+            host_screen = host_screen_from_window(xev.xconfigure.window);
+
+            if (!host_screen ||
+                (host_screen->win_pre_existing == None && !EphyrWantResize)) {
+                return 0;
             }
 
-            return 0;
+            ev->type = EPHYR_EV_CONFIGURE;
+            ev->data.configure.width = xev.xconfigure.width;
+            ev->data.configure.height = xev.xconfigure.height;
+            ev->data.configure.window = xev.xconfigure.window;
+            ev->data.configure.screen = host_screen->mynum;
+
+            return 1;
         }
         default:
             break;
commit f9198e278becec158b570204cf9fc1de822ac76b
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Mon Feb 27 16:43:10 2012 +1000

    dix: FreeAllAtoms() on reset
    
    ==5712== 6 bytes in 1 blocks are still reachable in loss record 17 of 585
    ==5712==    at 0x4A074CD: malloc (vg_replace_malloc.c:236)
    ==5712==    by 0x3D1DE885B1: strndup (strndup.c:46)
    ==5712==    by 0x41CB71: MakeAtom (atom.c:121)
    ==5712==    by 0x55AE3E: XIGetKnownProperty (xiproperty.c:401)
    ==5712==    by 0x4251C9: AddInputDevice (devices.c:312)
    ==5712==    by 0x42AC0C: AllocDevicePair (devices.c:2657)
    ==5712==    by 0x425E6E: InitCoreDevices (devices.c:677)
    ==5712==    by 0x5ACA05: main (main.c:257)
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Chase Douglas <chase.douglas at canonical.com>

diff --git a/dix/main.c b/dix/main.c
index fb935c9..bea1a8d 100644
--- a/dix/main.c
+++ b/dix/main.c
@@ -357,6 +357,8 @@ main(int argc, char *argv[], char *envp[])
 
         FreeFonts();
 
+        FreeAllAtoms();
+
         FreeAuditTimer();
 
         if (dispatchException & DE_TERMINATE) {
commit 88517ced1fa2e621be2d05a319b522b3111da516
Merge: 82425c6 73974dd
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Fri Feb 15 11:58:52 2013 +1000

    Merge branch 'master' of git+ssh://people.freedesktop.org/~alanc/xserver into next

commit 82425c66e7a8c436b5be7ad44880dd4be6c1f06a
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Feb 14 10:21:47 2013 +1000

    xfree86: remove redundant declaration of inputInfo
    
    xf86Cursor.c:19:18: warning: redundant redeclaration of 'inputInfo'
    [-Wredundant-decls]
    In file included from xf86Cursor.c:18:0:
    ../../../include/inputstr.h:614:57: note: previous declaration of
    'inputInfo' was here
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Mark Kettenis <kettenis at openbsd.org>

diff --git a/hw/xfree86/ramdac/xf86Cursor.c b/hw/xfree86/ramdac/xf86Cursor.c
index 8d48a75..d32aac1 100644
--- a/hw/xfree86/ramdac/xf86Cursor.c
+++ b/hw/xfree86/ramdac/xf86Cursor.c
@@ -16,7 +16,6 @@
  * Externing inputInfo is not the nice way to do it but it works.
  */
 #include "inputstr.h"
-extern InputInfo inputInfo;
 
 DevPrivateKeyRec xf86CursorScreenKeyRec;
 
commit 6133c417595a9c8fc158b0d68fd4a7a2c58fdc47
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Feb 14 10:15:33 2013 +1000

    xkb: remove unused variable 'names'
    
    xkb.c: In function '_XkbSetNamesCheck':
    xkb.c:3987:18: warning: variable 'names' set but not used
    [-Wunused-but-set-variable]
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Mark Kettenis <kettenis at openbsd.org>

diff --git a/xkb/xkb.c b/xkb/xkb.c
index 7e51e40..f2bcaee 100644
--- a/xkb/xkb.c
+++ b/xkb/xkb.c
@@ -3984,13 +3984,11 @@ _XkbSetNamesCheck(ClientPtr client, DeviceIntPtr dev,
                   xkbSetNamesReq * stuff, CARD32 *data)
 {
     XkbDescRec *xkb;
-    XkbNamesRec *names;
     CARD32 *tmp;
     Atom bad;
 
     tmp = data;
     xkb = dev->key->xkbInfo->desc;
-    names = xkb->names;
 
     if (stuff->which & XkbKeyTypeNamesMask) {
         int i;
commit 63d00c6b146d7f5fb80f20f19066088059042a5e
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Feb 14 10:13:53 2013 +1000

    Xext: rename two shadowing variables
    
    panoramiX.c: In function 'PanoramiXCreateConnectionBlock':
    panoramiX.c:599:10: warning: declaration of 'disableBackingStore' shadows a
    global declaration [-Wshadow]
    In file included from ../include/windowstr.h:60:0,
                     from panoramiX.c:47:
    ../include/opaque.h:56:52: warning: shadowed declaration is here [-Wshadow]
    
    panoramiX.c: In function 'PanoramiXConsolidate':
    panoramiX.c:834:19: warning: declaration of 'pScreen' shadows a previous
    local [-Wshadow]
    panoramiX.c:813:15: warning: shadowed declaration is here [-Wshadow]
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Mark Kettenis <kettenis at openbsd.org>

diff --git a/Xext/panoramiX.c b/Xext/panoramiX.c
index be475f7..7f888e3 100644
--- a/Xext/panoramiX.c
+++ b/Xext/panoramiX.c
@@ -596,7 +596,7 @@ Bool
 PanoramiXCreateConnectionBlock(void)
 {
     int i, j, length;
-    Bool disableBackingStore = FALSE;
+    Bool disable_backing_store = FALSE;
     int old_width, old_height;
     float width_mult, height_mult;
     xWindowRoot *root;
@@ -622,10 +622,10 @@ PanoramiXCreateConnectionBlock(void)
         }
         if (pScreen->backingStoreSupport !=
             screenInfo.screens[0]->backingStoreSupport)
-            disableBackingStore = TRUE;
+            disable_backing_store = TRUE;
     }
 
-    if (disableBackingStore) {
+    if (disable_backing_store) {
         for (i = 0; i < screenInfo.numScreens; i++) {
             pScreen = screenInfo.screens[i];
             pScreen->backingStoreSupport = NotUseful;
@@ -831,15 +831,15 @@ PanoramiXConsolidate(void)
     saver->type = XRT_WINDOW;
 
     FOR_NSCREENS(i) {
-        ScreenPtr pScreen = screenInfo.screens[i];
+        ScreenPtr scr = screenInfo.screens[i];
 
-        root->info[i].id = pScreen->root->drawable.id;
+        root->info[i].id = scr->root->drawable.id;
         root->u.win.class = InputOutput;
         root->u.win.root = TRUE;
-        saver->info[i].id = pScreen->screensaver.wid;
+        saver->info[i].id = scr->screensaver.wid;
         saver->u.win.class = InputOutput;
         saver->u.win.root = TRUE;
-        defmap->info[i].id = pScreen->defColormap;
+        defmap->info[i].id = scr->defColormap;
     }
 
     AddResource(root->info[0].id, XRT_WINDOW, root);
commit 8bbea9f48f43e54c55c8b60ea36bda3134a86af2
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Feb 14 10:09:53 2013 +1000

    Xext: renaming shadowing variable
    
    xvdisp.c: In function 'ProcXvStopVideo':
    xvdisp.c:712:11: warning: declaration of 'rc' shadows a previous local
    [-Wshadow]
    xvdisp.c:705:17: warning: shadowed declaration is here [-Wshadow]
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Mark Kettenis <kettenis at openbsd.org>

diff --git a/Xext/xvdisp.c b/Xext/xvdisp.c
index 31b7783..7877293 100644
--- a/Xext/xvdisp.c
+++ b/Xext/xvdisp.c
@@ -702,7 +702,7 @@ ProcXvUngrabPort(ClientPtr client)
 static int
 ProcXvStopVideo(ClientPtr client)
 {
-    int status, rc;
+    int status, ret;
     DrawablePtr pDraw;
     XvPortPtr pPort;
 
@@ -716,9 +716,9 @@ ProcXvStopVideo(ClientPtr client)
         return status;
     }
 
-    rc = dixLookupDrawable(&pDraw, stuff->drawable, client, 0, DixWriteAccess);
-    if (rc != Success)
-        return rc;
+    ret = dixLookupDrawable(&pDraw, stuff->drawable, client, 0, DixWriteAccess);
+    if (ret != Success)
+        return ret;
 
     return XvdiStopVideo(client, pPort, pDraw);
 }
commit 7b79a2e4a11b5c5f0ebaa495828725e235d2b08e
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Feb 14 10:06:55 2013 +1000

    fb: drop two unneeded shadowing variables
    
    fbpict.c: In function 'fbGlyphs':
    fbpict.c:188:6: warning: declaration of 'x' shadows a previous local
    [-Wshadow]
    fbpict.c:111:9: warning: shadowed declaration is here [-Wshadow]
    fbpict.c:188:9: warning: declaration of 'y' shadows a previous local
    [-Wshadow]
    fbpict.c:111:12: warning: shadowed declaration is here [-Wshadow]
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Soren Sandmann <ssp at redhat.com>
    Reviewed-by: Mark Kettenis <kettenis at openbsd.org>

diff --git a/fb/fbpict.c b/fb/fbpict.c
index 2804ff4..b503858 100644
--- a/fb/fbpict.c
+++ b/fb/fbpict.c
@@ -185,19 +185,15 @@ fbGlyphs(CARD8 op,
     if (maskFormat) {
 	pixman_format_code_t format;
 	pixman_box32_t extents;
-	int x, y;
 
 	format = maskFormat->format | (maskFormat->depth << 24);
 
 	pixman_glyph_get_extents(glyphCache, n_glyphs, pglyphs, &extents);
 
-	x = extents.x1;
-	y = extents.y1;
-
 	pixman_composite_glyphs(op, srcImage, dstImage, format,
 				xSrc + srcXoff + xDst, ySrc + srcYoff + yDst,
-				x, y,
-				x + dstXoff, y + dstYoff,
+				extents.x1, extents.y1,
+				extents.x1 + dstXoff, extents.y1 + dstYoff,
 				extents.x2 - extents.x1,
 				extents.y2 - extents.y1,
 				glyphCache, n_glyphs, pglyphs);
commit 858d8b19b3a5bb59e5c5f9a9e68adce2495b5e31
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Feb 14 10:04:06 2013 +1000

    xfree86: drop unused prevSIGIO
    
    Unused as of 5d309af2ed93e91c7d72f548a11052051efbb40f
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Mark Kettenis <kettenis at openbsd.org>

diff --git a/hw/xfree86/common/xf86Events.c b/hw/xfree86/common/xf86Events.c
index d92174e..0552233 100644
--- a/hw/xfree86/common/xf86Events.c
+++ b/hw/xfree86/common/xf86Events.c
@@ -413,7 +413,6 @@ static void
 xf86VTSwitch(void)
 {
     int i;
-    static int prevSIGIO;
     InputInfoPtr pInfo;
     IHPtr ih;
 
commit 592d35aef0a8089a344543cf5a425e0537c0431b
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Feb 14 10:02:02 2013 +1000

    randr: fix "set but unused" warnings
    
    rrcrtc.c: In function 'RRCrtcDetachScanoutPixmap':
    rrcrtc.c:366:9: warning: variable 'ret' set but not used
    [-Wunused-but-set-variable]
    rrcrtc.c: In function 'rrCheckPixmapBounding':
    rrcrtc.c:505:13: warning: variable 'ret' set but not used
    [-Wunused-but-set-variable]
    rrcrtc.c:445:9: warning: unused variable 'i' [-Wunused-variable]
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Mark Kettenis <kettenis at openbsd.org>

diff --git a/randr/rrcrtc.c b/randr/rrcrtc.c
index 6e2eca5..721b05a 100644
--- a/randr/rrcrtc.c
+++ b/randr/rrcrtc.c
@@ -363,13 +363,12 @@ void
 RRCrtcDetachScanoutPixmap(RRCrtcPtr crtc)
 {
     ScreenPtr master = crtc->pScreen->current_master;
-    int ret;
     PixmapPtr mscreenpix;
     rrScrPriv(crtc->pScreen);
 
     mscreenpix = master->GetScreenPixmap(master);
 
-    ret = pScrPriv->rrCrtcSetScanoutPixmap(crtc, NULL);
+    pScrPriv->rrCrtcSetScanoutPixmap(crtc, NULL);
     if (crtc->scanout_pixmap) {
         master->StopPixmapTracking(mscreenpix, crtc->scanout_pixmap);
         /*
@@ -442,7 +441,7 @@ rrCheckPixmapBounding(ScreenPtr pScreen,
                       RRCrtcPtr rr_crtc, int x, int y, int w, int h)
 {
     RegionRec root_pixmap_region, total_region, new_crtc_region;
-    int i, c;
+    int c;
     BoxRec newbox;
     BoxPtr newsize;
     ScreenPtr slave;
@@ -502,10 +501,8 @@ rrCheckPixmapBounding(ScreenPtr pScreen,
         new_height == screen_pixmap->drawable.height) {
         ErrorF("adjust shatters %d %d\n", newsize->x1, newsize->x2);
     } else {
-        int ret;
         rrScrPriv(pScreen);
-        ret = pScrPriv->rrScreenSetSize(pScreen,
-                                           new_width, new_height, 0, 0);
+        pScrPriv->rrScreenSetSize(pScreen, new_width, new_height, 0, 0);
     }
 
     /* set shatters TODO */
commit 90642948cc78834d95f7a3bddaac7ff77b68ed7e
Merge: 9a35d42 eda7dbf
Author: Keith Packard <keithp at keithp.com>
Date:   Thu Feb 14 11:05:48 2013 -0800

    Merge remote-tracking branch 'jeremyhu/master'

commit 9a35d4240e2aa91ac104f0f9f86f83ff9a2d3d04
Author: Peter Hutterer <peter.hutterer at who-t.net>
Date:   Thu Feb 14 16:31:13 2013 +1000

    os: fix pnprintf OOB buffer read for unterminated length modifiers
    
    Format strings with length modifiers but missing format specifier like "%0"
    will read one byte past the array size.
    
    Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
    Reviewed-by: Keith Packard <keithp at keithp.com>
    Signed-off-by: Keith Packard <keithp at keithp.com>

diff --git a/os/log.c b/os/log.c
index 2697ace..95bd8cc 100644
--- a/os/log.c
+++ b/os/log.c
@@ -304,6 +304,9 @@ pnprintf(char *string, size_t size, const char *f, va_list args)
         while (f_idx < f_len && ((f[f_idx] >= '0' && f[f_idx] <= '9') || f[f_idx] == '.'))
             f_idx++;
 
+        if (f_idx >= f_len)
+            break;
+
         switch (f[f_idx]) {
         case 's':
             string_arg = va_arg(args, char*);
diff --git a/test/signal-logging.c b/test/signal-logging.c
index 1ef17af..e0eb810 100644
--- a/test/signal-logging.c
+++ b/test/signal-logging.c
@@ -199,6 +199,14 @@ static void logging_format(void)
     read_log_msg(logmsg);
     assert(strcmp(logmsg, "(EE) substituted string\n") == 0);
 
+    /* Invalid format */
+#warning Ignore compiler warning below "lacks type at end of format".  This is intentional.
+    LogMessageVerbSigSafe(X_ERROR, -1, "%4", 4);
+    read_log_msg(logmsg);
+    assert(strcmp(logmsg, "(EE) ") == 0);
+    LogMessageVerbSigSafe(X_ERROR, -1, "\n");
+    fseek(f, 0, SEEK_END);
+
     /* number substitution */
     ui = 0;
     do {
commit 73974dd7ea9ca4d4cdd5464cb813088a6ee9770b
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Sun Jan 27 15:42:02 2013 -0800

    Avoid memory leak in ddc resort() if find_header() fails
    
    Call find_header first, returning on failure before calling malloc.
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/xfree86/ddc/ddc.c b/hw/xfree86/ddc/ddc.c
index 28c9696..44c1d53 100644
--- a/hw/xfree86/ddc/ddc.c
+++ b/hw/xfree86/ddc/ddc.c
@@ -91,15 +91,16 @@ resort(unsigned char *s_block)
     unsigned char *d_new, *d_ptr, *d_end, *s_ptr, *s_end;
     unsigned char tmp;
 
+    s_ptr = find_header(s_block);
+    if (!s_ptr)
+        return NULL;
     s_end = s_block + EDID1_LEN;
+
     d_new = malloc(EDID1_LEN);
     if (!d_new)
         return NULL;
     d_end = d_new + EDID1_LEN;
 
-    s_ptr = find_header(s_block);
-    if (!s_ptr)
-        return NULL;
     for (d_ptr = d_new; d_ptr < d_end; d_ptr++) {
         tmp = *(s_ptr++);
         *d_ptr = tmp;
commit b1129a1f1771c9d1653cc15aae94a614f081638a
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Sun Jan 27 14:00:54 2013 -0800

    xf86XvMCScreenInit: Avoid leak if dixRegisterPrivateKey fails
    
    Found by parfait 1.1 memory analyser:
       Memory leak of pointer 'pAdapt' allocated with malloc((88 * num_adaptors))
            at line 162 of hw/xfree86/common/xf86xvmc.c in function 'xf86XvMCScreenInit'.
              'pAdapt' allocated at line 158 with malloc((88 * num_adaptors)).
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/xfree86/common/xf86xvmc.c b/hw/xfree86/common/xf86xvmc.c
index 78a32bf..3169c05 100644
--- a/hw/xfree86/common/xf86xvmc.c
+++ b/hw/xfree86/common/xf86xvmc.c
@@ -158,8 +158,10 @@ xf86XvMCScreenInit(ScreenPtr pScreen,
     if (!(pAdapt = malloc(sizeof(XvMCAdaptorRec) * num_adaptors)))
         return FALSE;
 
-    if (!dixRegisterPrivateKey(&XF86XvMCScreenKeyRec, PRIVATE_SCREEN, 0))
+    if (!dixRegisterPrivateKey(&XF86XvMCScreenKeyRec, PRIVATE_SCREEN, 0)) {
+        free(pAdapt);
         return FALSE;
+    }
 
     if (!(pScreenPriv = malloc(sizeof(xf86XvMCScreenRec)))) {
         free(pAdapt);
commit 563db909bcf965b6103c1807bf9f00ede957077d
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Sun Jan 27 13:55:50 2013 -0800

    Avoid memory leak on realloc failure in localRegisterFreeBoxCallback
    
    Also avoids leaving invalid pointers in structures if realloc had to
    move them elsewhere to make them larger.
    
    Found by parfait 1.1 code analyzer:
       Memory leak of pointer 'newCallbacks' allocated with realloc(((char*)offman->FreeBoxesUpdateCallback), (8 * (offman->NumCallbacks + 1)))
            at line 328 of hw/xfree86/common/xf86fbman.c in function 'localRegisterFreeBoxCallback'.
              'newCallbacks' allocated at line 320 with realloc(((char*)offman->FreeBoxesUpdateCallback), (8 * (offman->NumCallbacks + 1))).
              newCallbacks leaks when newCallbacks != NULL at line 327.
       Memory leak of pointer 'newPrivates' allocated with realloc(((char*)offman->devPrivates), (8 * (offman->NumCallbacks + 1)))
            at line 328 of hw/xfree86/common/xf86fbman.c in function 'localRegisterFreeBoxCallback'.
              'newPrivates' allocated at line 324 with realloc(((char*)offman->devPrivates), (8 * (offman->NumCallbacks + 1))).
              newPrivates leaks when newCallbacks == NULL at line 327.
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/xfree86/common/xf86fbman.c b/hw/xfree86/common/xf86fbman.c
index c2e7bab..4da6af2 100644
--- a/hw/xfree86/common/xf86fbman.c
+++ b/hw/xfree86/common/xf86fbman.c
@@ -320,15 +320,17 @@ localRegisterFreeBoxCallback(ScreenPtr pScreen,
     newCallbacks = realloc(offman->FreeBoxesUpdateCallback,
                            sizeof(FreeBoxCallbackProcPtr) *
                            (offman->NumCallbacks + 1));
+    if (!newCallbacks)
+        return FALSE;
+    else
+        offman->FreeBoxesUpdateCallback = newCallbacks;
 
     newPrivates = realloc(offman->devPrivates,
                           sizeof(DevUnion) * (offman->NumCallbacks + 1));
-
-    if (!newCallbacks || !newPrivates)
+    if (!newPrivates)
         return FALSE;
-
-    offman->FreeBoxesUpdateCallback = newCallbacks;
-    offman->devPrivates = newPrivates;
+    else
+        offman->devPrivates = newPrivates;
 
     offman->FreeBoxesUpdateCallback[offman->NumCallbacks] = FreeBoxCallback;
     offman->devPrivates[offman->NumCallbacks].ptr = devPriv;
commit 08f75d3a9661c6c32800e1b4f150626200b889d9
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Sun Jan 27 13:50:30 2013 -0800

    Avoid NULL pointer dereference in xf86TokenToOptinfo if token not found
    
    Reported by parfait 1.1 code analyzer:
    
    Error: Null pointer dereference (CWE 476)
       Read from null pointer 'p'
            at line 746 of hw/xfree86/common/xf86Option.c in function 'xf86TokenToOptName'.
              Function 'xf86TokenToOptinfo' may return constant 'NULL' at line 721, called at line 745.
              Null pointer introduced at line 721 in function 'xf86TokenToOptinfo'.
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/xfree86/common/xf86Option.c b/hw/xfree86/common/xf86Option.c
index 40c9d15..607c333 100644
--- a/hw/xfree86/common/xf86Option.c
+++ b/hw/xfree86/common/xf86Option.c
@@ -743,7 +743,7 @@ xf86TokenToOptName(const OptionInfoRec * table, int token)
     const OptionInfoRec *p;
 
     p = xf86TokenToOptinfo(table, token);
-    return p->name;
+    return p ? p->name : NULL;
 }
 
 Bool
commit c1c01e350834a23161b33bd34b2fa9c01d02a65b
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Sun Jan 27 13:10:08 2013 -0800

    Make xf86ValidateModes actually copy clock range list to screen pointer
    
    Our in-house parfait 1.1 code analysis tool complained that every exit
    path from xf86ValidateModes() in hw/xfree86/common/xf86Mode.c leaks the
    storeClockRanges allocation made at line 1501 with XNFalloc.
    
    Investigating, it seems that this code to copy the clock range list to
    the clockRanges list in the screen pointer is just plain insane, and
    according to git, has been since we first imported it from XFree86.
    
    We start at line 1495 by walking the linked list from scrp->clockRanges
    until we find the end.  But that was just a diversion, since we've found
    the end and immediately forgotten it, and thus at 1499 we know that
    storeClockRanges is NULL, but that's not a problem since we're going to
    immediately overwrite that value as the first thing in the loop.
    
    So we move on through this loop at 1499, which takes us through the
    linked list from the clockRanges variable, and for every entry in
    that list allocates a new structure and copies cp to it.  If we've
    not filled in the screen's clockRanges pointer yet, we set it to
    the first storeClockRanges we copied from cp.   Otherwise, as best
    I can tell, we just drop it into memory and let it leak away, as
    parfait warned.
    
    And then we hit the loop action, which if we haven't hit the end of
    the cp list, advances cp to the next item in the list, and then just
    for the fun of it, also sets storeClockRanges to the ->next pointer it
    has just copied from cp as well, even though it's going to overwrite
    it as the very first instruction in the loop body.
    
    v2: rewritten using nt_list_* macros from Xorg's list.h header
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/xfree86/common/xf86Mode.c b/hw/xfree86/common/xf86Mode.c
index d80dec8..706ab64 100644
--- a/hw/xfree86/common/xf86Mode.c
+++ b/hw/xfree86/common/xf86Mode.c
@@ -1370,7 +1370,6 @@ xf86ValidateModes(ScrnInfoPtr scrp, DisplayModePtr availModes,
     int saveType;
     PixmapFormatRec *BankFormat;
     ClockRangePtr cp;
-    ClockRangePtr storeClockRanges;
     int numTimings = 0;
     range hsync[MAX_HSYNC];
     range vrefresh[MAX_VREFRESH];
@@ -1492,16 +1491,14 @@ xf86ValidateModes(ScrnInfoPtr scrp, DisplayModePtr availModes,
     /*
      * Store the clockRanges for later use by the VidMode extension.
      */
-    storeClockRanges = scrp->clockRanges;
-    while (storeClockRanges != NULL) {
-        storeClockRanges = storeClockRanges->next;
-    }
-    for (cp = clockRanges; cp != NULL; cp = cp->next,
-         storeClockRanges = storeClockRanges->next) {
-        storeClockRanges = xnfalloc(sizeof(ClockRange));
+    nt_list_for_each_entry(cp, clockRanges, next) {
+        ClockRangePtr newCR = xnfalloc(sizeof(ClockRange));
+        memcpy(newCR, cp, sizeof(ClockRange));
+        newCR->next = NULL;
         if (scrp->clockRanges == NULL)
-            scrp->clockRanges = storeClockRanges;
-        memcpy(storeClockRanges, cp, sizeof(ClockRange));
+            scrp->clockRanges = newCR;
+        else
+            nt_list_append(newCR, scrp->clockRanges, ClockRange, next);
     }
 
     /* Determine which pixmap format to pass to scanLineWidth() */
commit 89badba082c81d20fe35cb064c16e131ff288ca3
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Sun Jan 27 12:08:47 2013 -0800

    Free keymap on error in Xephyr's hostx_load_keymap
    
    Found by parfait 1.1 code analyser:
       Memory leak of pointer 'keymap' allocated with XGetKeyboardMapping(HostX.dpy, min_keycode, ((max_keycode - min_keycode) + 1), &host_width)
            at line 861 of hw/kdrive/ephyr/hostx.c in function 'hostx_load_keymap'.
              'keymap' allocated at line 845 with XGetKeyboardMapping(HostX.dpy, min_keycode, ((max_keycode - min_keycode) + 1), &host_width).
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/hw/kdrive/ephyr/hostx.c b/hw/kdrive/ephyr/hostx.c
index 157ac36..aed0285 100644
--- a/hw/kdrive/ephyr/hostx.c
+++ b/hw/kdrive/ephyr/hostx.c
@@ -858,7 +858,7 @@ hostx_load_keymap(void)
                                          (max_keycode - min_keycode + 1) *
                                          width);
     if (!ephyrKeySyms.map)
-        return;
+        goto out;
 
     for (i = 0; i < (max_keycode - min_keycode + 1); i++)
         for (j = 0; j < width; j++)
@@ -871,6 +871,7 @@ hostx_load_keymap(void)
     ephyrKeySyms.maxKeyCode = max_keycode;
     ephyrKeySyms.mapWidth = width;
 
+ out:
     XFree(keymap);
 }
 
commit 48b94651205b175760904e448f94111d1ab85e13
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Sun Jan 27 11:20:45 2013 -0800

    Stop leaking overlayWin in PanoramiXCompositeGetOverlayWindow error paths
    
    Found by parfait 1.1 code analyzer:
    
    Error: Memory leak (CWE 401)
       Memory leak of pointer 'overlayWin' allocated with malloc(72)
            at line 806 of composite/compext.c in function 'PanoramiXCompositeGetOverlayWindow'.
              pointer allocated at line 794 with malloc(72).
              <unknown> leaks when rc != 0 at line 804.
            at line 816 of composite/compext.c in function 'PanoramiXCompositeGetOverlayWindow'.
              pointer allocated at line 794 with malloc(72).
              <unknown> leaks when pOc == NULL at line 815.
            at line 825 of composite/compext.c in function 'PanoramiXCompositeGetOverlayWindow'.
              pointer allocated at line 794 with malloc(72).
              <unknown> leaks when cs->pOverlayWin == NULL at line 822
                  and compCreateOverlayWindow(pScreen) == 0 at line 823.
            at line 834 of composite/compext.c in function 'PanoramiXCompositeGetOverlayWindow'.
              pointer allocated at line 794 with malloc(72).
              <unknown> leaks when rc != 0 at line 832.
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/composite/compext.c b/composite/compext.c
index 8641eff..e4821c5 100644
--- a/composite/compext.c
+++ b/composite/compext.c
@@ -803,6 +803,7 @@ PanoramiXCompositeGetOverlayWindow(ClientPtr client)
                                      RT_WINDOW, client, DixGetAttrAccess);
         if (rc != Success) {
             client->errorValue = stuff->window;
+            free(overlayWin);
             return rc;
         }
         pScreen = pWin->drawable.pScreen;
@@ -812,8 +813,10 @@ PanoramiXCompositeGetOverlayWindow(ClientPtr client)
          * interest in the overlay window
          */
         pOc = compCreateOverlayClient(pScreen, client);
-        if (pOc == NULL)
+        if (pOc == NULL) {
+            free(overlayWin);
             return BadAlloc;
+        }
 
         /*
          * Make sure the overlay window exists
@@ -822,6 +825,7 @@ PanoramiXCompositeGetOverlayWindow(ClientPtr client)
         if (cs->pOverlayWin == NULL)
             if (!compCreateOverlayWindow(pScreen)) {
                 FreeResource(pOc->resource, RT_NONE);
+                free(overlayWin);
                 return BadAlloc;
             }
 
@@ -831,6 +835,7 @@ PanoramiXCompositeGetOverlayWindow(ClientPtr client)
                       DixGetAttrAccess);
         if (rc != Success) {
             FreeResource(pOc->resource, RT_NONE);
+            free(overlayWin);
             return rc;
         }
     }
commit f4a9332ad149ed15353a9c482563bdd042d0b403
Author: Alan Coopersmith <alan.coopersmith at oracle.com>
Date:   Sun Jan 27 10:06:42 2013 -0800

    Handle failure to create counter in init_system_idle_counter
    
    Check for NULL pointer (which can be returned for multiple reasons)
    before trying to dereference it to add privates.   To avoid memory leak
    in error path, delay malloc of privates until we're ready to add them.
    
    In case we do return NULL up through SyncInitDeviceIdleTime, handle the
    possibility of getting NULL passed back down to SyncRemoveDeviceIdleTime.
    
    As reported by parfait 1.1:
    Error: Null pointer dereference (CWE 476)
       Read from null pointer 'idle_time_counter'
            at line 2764 of xserver/Xext/sync.c in function 'init_system_idle_counter'.
              Function 'SyncCreateSystemCounter' may return constant 'NULL' at line 952, called at line 2756.
              Null pointer introduced at line 952 in function 'SyncCreateSystemCounter'.
    
    Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
    Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net>

diff --git a/Xext/sync.c b/Xext/sync.c
index 4d11992..9ae5b39 100644
--- a/Xext/sync.c
+++ b/Xext/sync.c
@@ -2747,7 +2747,6 @@ init_system_idle_counter(const char *name, int deviceid)
 {
     CARD64 resolution;
     XSyncValue idle;
-    IdleCounterPriv *priv = malloc(sizeof(IdleCounterPriv));
     SyncCounter *idle_time_counter;
 
     IdleTimeQueryValue(NULL, &idle);
@@ -2758,10 +2757,14 @@ init_system_idle_counter(const char *name, int deviceid)
                                                 IdleTimeQueryValue,
                                                 IdleTimeBracketValues);
 
-    priv->deviceid = deviceid;
-    priv->value_less = priv->value_greater = NULL;
+    if (idle_time_counter != NULL) {
+        IdleCounterPriv *priv = malloc(sizeof(IdleCounterPriv));
 
-    idle_time_counter->pSysCounterInfo->private = priv;
+        priv->value_less = priv->value_greater = NULL;
+        priv->deviceid = deviceid;
+
+        idle_time_counter->pSysCounterInfo->private = priv;
+    }
 
     return idle_time_counter;
 }
@@ -2786,6 +2789,6 @@ void SyncRemoveDeviceIdleTime(SyncCounter *counter)
     /* FreeAllResources() frees all system counters before the devices are
        shut down, check if there are any left before freeing the device's
        counter */
-    if (!xorg_list_is_empty(&SysCounterList))
+    if (counter && !xorg_list_is_empty(&SysCounterList))
         xorg_list_del(&counter->pSysCounterInfo->entry);
 }


More information about the Xquartz-changes mailing list