libGL: Consolidate DRI initialization in dri_glx.c
[mesa.git] / src / glx / x11 / glxext.c
index 66567b83138545ee50aab81f7da0910bd1cabe93..e07312214bec7002588c9cdc934c3d1c9b7dc0fc 100644 (file)
 
 #include "glxclient.h"
 #include <stdio.h>
-#include <Xext.h>
-#include <extutil.h>
+#include <X11/extensions/Xext.h>
+#include <X11/extensions/extutil.h>
+#include <X11/extensions/Xfixes.h>
+#include <X11/extensions/Xdamage.h>
 #include <assert.h>
 #include "indirect_init.h"
 #include "glapi.h"
-#ifdef XTHREADS
-# include "Xthreads.h"
-#elif defined(PTHREADS)
-# include <pthread.h>
-#endif
 #include "glxextensions.h"
 #include "glcontextmodes.h"
 #include "glheader.h"
 #include <inttypes.h>
 #include <sys/mman.h>
 #include "xf86dri.h"
+#include "xf86drm.h"
 #include "sarea.h"
 #include "dri_glx.h"
 #endif
 
 #ifdef USE_XCB
-#include <X11/xcl.h>
-#include <X11/XCB/xcb.h>
-#include <X11/XCB/glx.h>
+#include <X11/Xlib-xcb.h>
+#include <xcb/xcb.h>
+#include <xcb/glx.h>
 #endif
 
 #include <assert.h>
@@ -146,7 +144,7 @@ static __GLapi *IndirectAPI = NULL;
  * Current context management and locking
  */
 
-#if defined( XTHREADS )
+#if defined( USE_XTHREADS )
 
 /* thread safe */
 static GLboolean TSDinitialized = GL_FALSE;
@@ -290,6 +288,10 @@ static /* const */ char *error_list[] = {
     "GLXBadRenderRequest",
     "GLXBadLargeRequest",
     "GLXUnsupportedPrivateRequest",
+    "GLXBadFBConfig",
+    "GLXBadPbuffer",
+    "GLXBadCurrentDrawable",
+    "GLXBadWindow",
 };
 
 int __glXCloseDisplay(Display *dpy, XExtCodes *codes)
@@ -353,13 +355,15 @@ static void FreeScreenConfigs(__GLXdisplayPrivate *priv)
 
            psc->configs = NULL;        /* NOTE: just for paranoia */
        }
+       Xfree((char*) psc->serverGLXexts);
 
 #ifdef GLX_DIRECT_RENDERING
        /* Free the direct rendering per screen data */
        if (psc->driScreen.private)
-           (*psc->driScreen.destroyScreen)(priv->dpy, i,
-                                           psc->driScreen.private);
+           (*psc->driScreen.destroyScreen)(&psc->driScreen);
        psc->driScreen.private = NULL;
+       if (psc->drawHash)
+           __glxHashDestroy(psc->drawHash);
 #endif
     }
     XFree((char*) priv->screenConfigs);
@@ -384,12 +388,16 @@ static int __glXFreeDisplayPrivate(XExtData *extension)
        priv->serverGLXversion = 0x0; /* to protect against double free's */
     }
 
-#if 0 /* GLX_DIRECT_RENDERING */
+#ifdef GLX_DIRECT_RENDERING
     /* Free the direct rendering per display data */
     if (priv->driDisplay.private)
        (*priv->driDisplay.destroyDisplay)(priv->dpy,
                                           priv->driDisplay.private);
     priv->driDisplay.private = NULL;
+    if (priv->driDisplay.createNewScreen) {
+        Xfree(priv->driDisplay.createNewScreen); /* free array of ptrs */
+        priv->driDisplay.createNewScreen = NULL;
+    }
 #endif
 
     Xfree((char*) priv);
@@ -592,6 +600,21 @@ __glXInitializeVisualConfigFromTags( __GLcontextModes *config, int count,
          case GLX_SAMPLES_SGIS:
            config->samples = *bp++;
            break;
+       case GLX_BIND_TO_TEXTURE_RGB_EXT:
+           config->bindToTextureRgb = *bp++;
+           break;
+       case GLX_BIND_TO_TEXTURE_RGBA_EXT:
+           config->bindToTextureRgba = *bp++;
+           break;
+       case GLX_BIND_TO_MIPMAP_TEXTURE_EXT:
+           config->bindToMipmapTexture = *bp++;
+           break;
+       case GLX_BIND_TO_TEXTURE_TARGETS_EXT:
+           config->bindToTextureTargets = *bp++;
+           break;
+       case GLX_Y_INVERTED_EXT:
+           config->yInverted = *bp++;
+           break;
          case None:
            i = count;
            break;
@@ -610,301 +633,128 @@ __glXInitializeVisualConfigFromTags( __GLcontextModes *config, int count,
     config->haveStencilBuffer = (config->stencilBits > 0);
 }
 
-
-#ifdef GLX_DIRECT_RENDERING
-static unsigned
-filter_modes( __GLcontextModes ** server_modes,
-             const __GLcontextModes * driver_modes )
+static __GLcontextModes *
+createConfigsFromProperties(Display *dpy, int nvisuals, int nprops,
+                           int screen, GLboolean tagged_only)
 {
-    __GLcontextModes * m;
-    __GLcontextModes ** prev_next;
-    const __GLcontextModes * check;
-    unsigned modes_count = 0;
-
-    if ( driver_modes == NULL ) {
-       fprintf(stderr, "libGL warning: 3D driver returned no fbconfigs.\n");
-       return 0;
-    }
-
-    /* For each mode in server_modes, check to see if a matching mode exists
-     * in driver_modes.  If not, then the mode is not available.
-     */
-
-    prev_next = server_modes;
-    for ( m = *prev_next ; m != NULL ; m = *prev_next ) {
-       GLboolean do_delete = GL_TRUE;
+    INT32 buf[__GLX_TOTAL_CONFIG], *props;
+    unsigned prop_size;
+    __GLcontextModes *modes, *m;
+    int i;
 
-       for ( check = driver_modes ; check != NULL ; check = check->next ) {
-           if ( _gl_context_modes_are_same( m, check ) ) {
-               do_delete = GL_FALSE;
-               break;
-           }
-       }
+    if (nprops == 0)
+       return NULL;
 
-       /* The 3D has to support all the modes that match the GLX visuals
-        * sent from the X server.
-        */
-       if ( do_delete && (m->visualID != 0) ) {
-           do_delete = GL_FALSE;
+    /* FIXME: Is the __GLX_MIN_CONFIG_PROPS test correct for FBconfigs? */
 
-           fprintf(stderr, "libGL warning: 3D driver claims to not support "
-                   "visual 0x%02x\n", m->visualID);
-       }
+    /* Check number of properties */
+    if (nprops < __GLX_MIN_CONFIG_PROPS || nprops > __GLX_MAX_CONFIG_PROPS)
+       return NULL;
 
-       if ( do_delete ) {
-           *prev_next = m->next;
+    /* Allocate memory for our config structure */
+    modes = _gl_context_modes_create(nvisuals, sizeof(__GLcontextModes));
+    if (!modes)
+       return NULL;
 
-           m->next = NULL;
-           _gl_context_modes_destroy( m );
-       }
-       else {
-           modes_count++;
-           prev_next = & m->next;
-       }
+    prop_size = nprops * __GLX_SIZE_INT32;
+    if (prop_size <= sizeof(buf))
+       props = buf;
+    else
+       props = Xmalloc(prop_size);
+
+    /* Read each config structure and convert it into our format */
+    m = modes;
+    for (i = 0; i < nvisuals; i++) {
+       _XRead(dpy, (char *)props, prop_size);
+       /* Older X servers don't send this so we default it here. */
+       m->drawableType = GLX_WINDOW_BIT;
+       __glXInitializeVisualConfigFromTags(m, nprops, props,
+                                           tagged_only, GL_TRUE);
+       m->screen = screen;
+       m = m->next;
     }
 
-    return modes_count;
-}
-
+    if (props != buf)
+       Xfree(props);
 
-/**
- * Implement \c __DRIinterfaceMethods::getProcAddress.
- */
-static __DRIfuncPtr get_proc_address( const char * proc_name )
-{
-    if (strcmp( proc_name, "glxEnableExtension" ) == 0) {
-       return (__DRIfuncPtr) __glXScrEnableExtension;
-    }
-    
-    return NULL;
+    return modes;
 }
 
-
-/**
- * Table of functions exported by the loader to the driver.
- */
-static const __DRIinterfaceMethods interface_methods = {
-    get_proc_address,
-
-    _gl_context_modes_create,
-    _gl_context_modes_destroy,
-      
-    __glXFindDRIScreen,
-    __glXWindowExists,
-      
-    XF86DRICreateContextWithConfig,
-    XF86DRIDestroyContext,
-
-    XF86DRICreateDrawable,
-    XF86DRIDestroyDrawable,
-    XF86DRIGetDrawableInfo,
-
-    __glXGetUST,
-    glXGetMscRateOML,
-};
-
-
-/**
- * Perform the required libGL-side initialization and call the client-side
- * driver's \c __driCreateNewScreen function.
- * 
- * \param dpy    Display pointer.
- * \param scrn   Screen number on the display.
- * \param psc    DRI screen information.
- * \param driDpy DRI display information.
- * \param createNewScreen  Pointer to the client-side driver's
- *               \c __driCreateNewScreen function.
- * \returns A pointer to the \c __DRIscreenPrivate structure returned by
- *          the client-side driver on success, or \c NULL on failure.
- * 
- * \todo This function needs to be modified to remove context-modes from the
- *       list stored in the \c __GLXscreenConfigsRec to match the list
- *       returned by the client-side driver.
- */
-static void *
-CallCreateNewScreen(Display *dpy, int scrn, __DRIscreen *psc,
-                   __DRIdisplay * driDpy,
-                   PFNCREATENEWSCREENFUNC createNewScreen)
+static GLboolean
+getVisualConfigs(Display *dpy, __GLXdisplayPrivate *priv, int screen)
 {
-    __DRIscreenPrivate *psp = NULL;
-#ifndef GLX_USE_APPLEGL
-    drm_handle_t hSAREA;
-    drmAddress pSAREA;
-    char *BusID;
-    __DRIversion   ddx_version;
-    __DRIversion   dri_version;
-    __DRIversion   drm_version;
-    __DRIframebuffer  framebuffer;
-    int   fd = -1;
-    int   status;
-    const char * err_msg;
-    const char * err_extra;
-    int api_ver = __glXGetInternalVersion();
-
-
-    dri_version.major = driDpy->private->driMajor;
-    dri_version.minor = driDpy->private->driMinor;
-    dri_version.patch = driDpy->private->driPatch;
-
-
-    err_msg = "XF86DRIOpenConnection";
-    err_extra = NULL;
-
-    framebuffer.dev_priv = NULL;
-
-    if (XF86DRIOpenConnection(dpy, scrn, &hSAREA, &BusID)) {
-       fd = drmOpen(NULL,BusID);
-       Xfree(BusID); /* No longer needed */
-
-       err_msg = "open DRM";
-       err_extra = strerror( -fd );
-
-       if (fd >= 0) {
-           drm_magic_t magic;
-
-           err_msg = "drmGetMagic";
-           err_extra = NULL;
-
-           if (!drmGetMagic(fd, &magic)) {
-               drmVersionPtr version = drmGetVersion(fd);
-               if (version) {
-                   drm_version.major = version->version_major;
-                   drm_version.minor = version->version_minor;
-                   drm_version.patch = version->version_patchlevel;
-                   drmFreeVersion(version);
-               }
-               else {
-                   drm_version.major = -1;
-                   drm_version.minor = -1;
-                   drm_version.patch = -1;
-               }
-
-               err_msg = "XF86DRIAuthConnection";
-               if (XF86DRIAuthConnection(dpy, scrn, magic)) {
-                   char *driverName;
-
-                   /*
-                    * Get device name (like "tdfx") and the ddx version
-                    * numbers.  We'll check the version in each DRI driver's
-                    * "createNewScreen" function.
-                    */
-                   err_msg = "XF86DRIGetClientDriverName";
-                   if (XF86DRIGetClientDriverName(dpy, scrn,
-                                                  &ddx_version.major,
-                                                  &ddx_version.minor,
-                                                  &ddx_version.patch,
-                                                  &driverName)) {
-                       drm_handle_t  hFB;
-                       int        junk;
-
-                       /* No longer needed. */
-                       Xfree( driverName );
-
-
-                       /*
-                        * Get device-specific info.  pDevPriv will point to a struct
-                        * (such as DRIRADEONRec in xfree86/driver/ati/radeon_dri.h)
-                        * that has information about the screen size, depth, pitch,
-                        * ancilliary buffers, DRM mmap handles, etc.
-                        */
-                       err_msg = "XF86DRIGetDeviceInfo";
-                       if (XF86DRIGetDeviceInfo(dpy, scrn,
-                                                &hFB,
-                                                &junk,
-                                                &framebuffer.size,
-                                                &framebuffer.stride,
-                                                &framebuffer.dev_priv_size,
-                                                &framebuffer.dev_priv)) {
-                           framebuffer.width = DisplayWidth(dpy, scrn);
-                           framebuffer.height = DisplayHeight(dpy, scrn);
-
-                           /*
-                            * Map the framebuffer region.
-                            */
-                           status = drmMap(fd, hFB, framebuffer.size, 
-                                           (drmAddressPtr)&framebuffer.base);
-
-                           err_msg = "drmMap of framebuffer";
-                           err_extra = strerror( -status );
-
-                           if ( status == 0 ) {
-                               /*
-                                * Map the SAREA region.  Further mmap regions
-                                * may be setup in each DRI driver's
-                                * "createNewScreen" function.
-                                */
-                               status = drmMap(fd, hSAREA, SAREA_MAX, 
-                                               &pSAREA);
-
-                               err_msg = "drmMap of sarea";
-                               err_extra = strerror( -status );
-
-                               if ( status == 0 ) {
-                                   __GLcontextModes * driver_modes = NULL;
-                                   __GLXscreenConfigs *configs = psc->screenConfigs;
-
-                                   err_msg = "InitDriver";
-                                   err_extra = NULL;
-                                   psp = (*createNewScreen)(dpy, scrn,
-                                                            psc,
-                                                            configs->configs,
-                                                            & ddx_version,
-                                                            & dri_version,
-                                                            & drm_version,
-                                                            & framebuffer,
-                                                            pSAREA,
-                                                            fd,
-                                                            api_ver,
-                                                            & interface_methods,
-                                                            & driver_modes );
-
-                                   filter_modes( & configs->configs,
-                                                 driver_modes );
-                                   _gl_context_modes_destroy( driver_modes );
-                               }
-                           }
-                       }
-                   }
-               }
-           }
-       }
-    }
+    xGLXGetVisualConfigsReq *req;
+    __GLXscreenConfigs *psc;
+    xGLXGetVisualConfigsReply reply;
+    
+    LockDisplay(dpy);
 
-    if ( psp == NULL ) {
-       if ( pSAREA != MAP_FAILED ) {
-           (void)drmUnmap(pSAREA, SAREA_MAX);
-       }
+    psc = priv->screenConfigs + screen;
+    psc->visuals = NULL;
+    GetReq(GLXGetVisualConfigs, req);
+    req->reqType = priv->majorOpcode;
+    req->glxCode = X_GLXGetVisualConfigs;
+    req->screen = screen;
 
-       if ( framebuffer.base != MAP_FAILED ) {
-           (void)drmUnmap((drmAddress)framebuffer.base, framebuffer.size);
-       }
+    if (!_XReply(dpy, (xReply*) &reply, 0, False))
+       goto out;
 
-       if ( framebuffer.dev_priv != NULL ) {
-           Xfree(framebuffer.dev_priv);
-       }
+    psc->visuals = createConfigsFromProperties(dpy,
+                                              reply.numVisuals,
+                                              reply.numProps,
+                                              screen, GL_FALSE);
 
-       if ( fd >= 0 ) {
-           (void)drmClose(fd);
-       }
+ out:
+    UnlockDisplay(dpy);
+    return psc->visuals != NULL;
+}
 
-       (void)XF86DRICloseConnection(dpy, scrn);
+static GLboolean
+getFBConfigs(Display *dpy, __GLXdisplayPrivate *priv, int screen)
+{
+    xGLXGetFBConfigsReq *fb_req;
+    xGLXGetFBConfigsSGIXReq *sgi_req;
+    xGLXVendorPrivateWithReplyReq *vpreq;
+    xGLXGetFBConfigsReply reply;
+    __GLXscreenConfigs *psc;
 
-       if ( err_extra != NULL ) {
-           fprintf(stderr, "libGL error: %s failed (%s)\n", err_msg,
-                   err_extra);
-       }
-       else {
-           fprintf(stderr, "libGL error: %s failed\n", err_msg );
-       }
+    psc = priv->screenConfigs + screen;
+    psc->serverGLXexts = __glXGetStringFromServer(dpy, priv->majorOpcode,
+                                                 X_GLXQueryServerString,
+                                                 screen, GLX_EXTENSIONS);
 
-        fprintf(stderr, "libGL error: reverting to (slow) indirect rendering\n");
-    }
-#endif /* !GLX_USE_APPLEGL */
+    LockDisplay(dpy);
 
-    return psp;
+    psc->configs = NULL;
+    if (atof(priv->serverGLXversion) >= 1.3) {
+       GetReq(GLXGetFBConfigs, fb_req);
+       fb_req->reqType = priv->majorOpcode;
+       fb_req->glxCode = X_GLXGetFBConfigs;
+       fb_req->screen = screen;
+    } else if (strstr(psc->serverGLXexts, "GLX_SGIX_fbconfig") != NULL) {
+       GetReqExtra(GLXVendorPrivateWithReply,
+                   sz_xGLXGetFBConfigsSGIXReq +
+                   sz_xGLXVendorPrivateWithReplyReq, vpreq);
+       sgi_req = (xGLXGetFBConfigsSGIXReq *) vpreq;
+       sgi_req->reqType = priv->majorOpcode;
+       sgi_req->glxCode = X_GLXVendorPrivateWithReply;
+       sgi_req->vendorCode = X_GLXvop_GetFBConfigsSGIX;
+       sgi_req->screen = screen;
+    } else
+       goto out;
+
+    if (!_XReply(dpy, (xReply*) &reply, 0, False))
+       goto out;
+
+    psc->configs = createConfigsFromProperties(dpy,
+                                              reply.numFBConfigs,
+                                              reply.numAttribs * 2,
+                                              screen, GL_TRUE);
+
+ out:
+    UnlockDisplay(dpy);
+    return psc->configs != NULL;
 }
-#endif /* GLX_DIRECT_RENDERING */
-
 
 /*
 ** Allocate the memory for the per screen configs for each screen.
@@ -912,17 +762,8 @@ CallCreateNewScreen(Display *dpy, int scrn, __DRIscreen *psc,
 */
 static Bool AllocAndFetchScreenConfigs(Display *dpy, __GLXdisplayPrivate *priv)
 {
-    xGLXGetVisualConfigsReq *req;
-    xGLXGetFBConfigsReq *fb_req;
-    xGLXVendorPrivateWithReplyReq *vpreq;
-    xGLXGetFBConfigsSGIXReq *sgi_req;
-    xGLXGetVisualConfigsReply reply;
     __GLXscreenConfigs *psc;
-    __GLcontextModes *config;
-    GLint i, j, nprops, screens;
-    INT32 buf[__GLX_TOTAL_CONFIG], *props;
-    unsigned supported_request = 0;
-    unsigned prop_size;
+    GLint i, screens;
 
     /*
     ** First allocate memory for the array of per screen configs.
@@ -936,160 +777,21 @@ static Bool AllocAndFetchScreenConfigs(Display *dpy, __GLXdisplayPrivate *priv)
     priv->screenConfigs = psc;
     
     priv->serverGLXversion = __glXGetStringFromServer(dpy, priv->majorOpcode,
-                                        X_GLXQueryServerString,
-                                        0, GLX_VERSION);
+                                                     X_GLXQueryServerString,
+                                                     0, GLX_VERSION);
     if ( priv->serverGLXversion == NULL ) {
        FreeScreenConfigs(priv);
        return GL_FALSE;
     }
 
-    if ( atof( priv->serverGLXversion ) >= 1.3 ) {
-       supported_request = 1;
-    }
-
-    /*
-    ** Now fetch each screens configs structures.  If a screen supports
-    ** GL (by returning a numVisuals > 0) then allocate memory for our
-    ** config structure and then fill it in.
-    */
     for (i = 0; i < screens; i++, psc++) {
-       if ( supported_request != 1 ) {
-           psc->serverGLXexts = __glXGetStringFromServer(dpy, priv->majorOpcode,
-                                                         X_GLXQueryServerString,
-                                                         i, GLX_EXTENSIONS);
-           if ( strstr( psc->serverGLXexts, "GLX_SGIX_fbconfig" ) != NULL ) {
-               supported_request = 2;
-           }
-           else {
-               supported_request = 3;
-           }
-       }
-
-
-       LockDisplay(dpy);
-       switch( supported_request ) {
-           case 1:
-           GetReq(GLXGetFBConfigs,fb_req);
-           fb_req->reqType = priv->majorOpcode;
-           fb_req->glxCode = X_GLXGetFBConfigs;
-           fb_req->screen = i;
-           break;
-          
-           case 2:
-           GetReqExtra(GLXVendorPrivateWithReply,
-                       sz_xGLXGetFBConfigsSGIXReq-sz_xGLXVendorPrivateWithReplyReq,vpreq);
-           sgi_req = (xGLXGetFBConfigsSGIXReq *) vpreq;
-           sgi_req->reqType = priv->majorOpcode;
-           sgi_req->glxCode = X_GLXVendorPrivateWithReply;
-           sgi_req->vendorCode = X_GLXvop_GetFBConfigsSGIX;
-           sgi_req->screen = i;
-           break;
-
-           case 3:
-           GetReq(GLXGetVisualConfigs,req);
-           req->reqType = priv->majorOpcode;
-           req->glxCode = X_GLXGetVisualConfigs;
-           req->screen = i;
-           break;
-       }
-
-       if (!_XReply(dpy, (xReply*) &reply, 0, False)) {
-           /* Something is busted. Punt. */
-           UnlockDisplay(dpy);
-           FreeScreenConfigs(priv);
-           return GL_FALSE;
-       }
-
-       UnlockDisplay(dpy);
-       if (!reply.numVisuals) {
-           /* This screen does not support GL rendering */
-           UnlockDisplay(dpy);
-           continue;
-       }
-
-       /* FIXME: Is the __GLX_MIN_CONFIG_PROPS test correct for
-        * FIXME: FBconfigs? 
-        */
-       /* Check number of properties */
-       nprops = reply.numProps;
-       if ((nprops < __GLX_MIN_CONFIG_PROPS) ||
-           (nprops > __GLX_MAX_CONFIG_PROPS)) {
-           /* Huh?  Not in protocol defined limits.  Punt */
-           UnlockDisplay(dpy);
-           SyncHandle();
-           FreeScreenConfigs(priv);
-           return GL_FALSE;
-       }
-
-       /* Allocate memory for our config structure */
-       psc->configs = _gl_context_modes_create(reply.numVisuals,
-                                               sizeof(__GLcontextModes));
-       if (!psc->configs) {
-           UnlockDisplay(dpy);
-           SyncHandle();
-           FreeScreenConfigs(priv);
-           return GL_FALSE;
-       }
-
-       /* Allocate memory for the properties, if needed */
-       if ( supported_request != 3 ) {
-           nprops *= 2;
-       }
-
-       prop_size = nprops * __GLX_SIZE_INT32;
-
-       if (prop_size <= sizeof(buf)) {
-           props = buf;
-       } else {
-           props = (INT32 *) Xmalloc(prop_size);
-       } 
-
-       /* Read each config structure and convert it into our format */
-        config = psc->configs;
-       for (j = 0; j < reply.numVisuals; j++) {
-           assert( config != NULL );
-           _XRead(dpy, (char *)props, prop_size);
-
-           if ( supported_request != 3 ) {
-               config->rgbMode = GL_TRUE;
-               config->drawableType = GLX_WINDOW_BIT;
-           }
-           else {
-               config->drawableType = GLX_WINDOW_BIT | GLX_PIXMAP_BIT;
-           }
-
-           __glXInitializeVisualConfigFromTags( config, nprops, props,
-                                                (supported_request != 3),
-                                                GL_TRUE );
-           if ( config->fbconfigID == GLX_DONT_CARE ) {
-               config->fbconfigID = config->visualID;
-           }
-           config->screen = i;
-           config = config->next;
-       }
-       if (props != buf) {
-           Xfree((char *)props);
-       }
-       UnlockDisplay(dpy);
+       getVisualConfigs(dpy, priv, i);
+       getFBConfigs(dpy, priv, i);
 
+       psc->scr = i;
+       psc->dpy = dpy;
 #ifdef GLX_DIRECT_RENDERING
-        /* Initialize per screen dynamic client GLX extensions */
-       psc->ext_list_first_time = GL_TRUE;
-       /* Initialize the direct rendering per screen data and functions */
-       if (priv->driDisplay.private != NULL) {
-           /* FIXME: Should it be some sort of an error if createNewScreen[i]
-            * FIXME: is NULL?
-            */
-           if (priv->driDisplay.createNewScreen &&
-               priv->driDisplay.createNewScreen[i]) {
-
-               psc->driScreen.screenConfigs = (void *)psc;
-               psc->driScreen.private =
-                   CallCreateNewScreen(dpy, i, & psc->driScreen,
-                                       & priv->driDisplay,
-                                       priv->driDisplay.createNewScreen[i] );
-           }
-       }
+       driCreateScreen(psc, i, priv);
 #endif
     }
     SyncHandle();
@@ -1107,7 +809,7 @@ __GLXdisplayPrivate *__glXInitialize(Display* dpy)
     XEDataObject dataObj;
     int major, minor;
 
-#if defined(XTHREADS)
+#if defined(USE_XTHREADS)
     {
         static int firstCall = 1;
         if (firstCall) {
@@ -1153,7 +855,7 @@ __GLXdisplayPrivate *__glXInitialize(Display* dpy)
        __glXUnlock();
        return 0;
     }
-    dpyPriv = (__GLXdisplayPrivate *) Xmalloc(sizeof(__GLXdisplayPrivate));
+    dpyPriv = (__GLXdisplayPrivate *) Xcalloc(1, sizeof(__GLXdisplayPrivate));
     if (!dpyPriv) {
        __glXUnlock();
        Xfree((char*) private);
@@ -1178,12 +880,7 @@ __GLXdisplayPrivate *__glXInitialize(Display* dpy)
     ** Note: This _must_ be done before calling any other DRI routines
     ** (e.g., those called in AllocAndFetchScreenConfigs).
     */
-    if (getenv("LIBGL_ALWAYS_INDIRECT")) {
-        /* Assinging zero here assures we'll never go direct */
-        dpyPriv->driDisplay.private = 0;
-        dpyPriv->driDisplay.destroyDisplay = 0;
-    }
-    else {
+    if (getenv("LIBGL_ALWAYS_INDIRECT") == NULL) {
         dpyPriv->driDisplay.private =
             driCreateDisplay(dpy, &dpyPriv->driDisplay);
     }
@@ -1264,7 +961,7 @@ GLubyte *__glXFlushRenderBuffer(__GLXcontext *ctx, GLubyte *pc)
 {
     Display * const dpy = ctx->currentDpy;
 #ifdef USE_XCB
-    XCBConnection *c = XCBConnectionOfDisplay(dpy);
+    xcb_connection_t *c = XGetXCBConnection(dpy);
 #else
     xGLXRenderReq *req;
 #endif /* USE_XCB */
@@ -1272,7 +969,8 @@ GLubyte *__glXFlushRenderBuffer(__GLXcontext *ctx, GLubyte *pc)
 
     if ( (dpy != NULL) && (size > 0) ) {
 #ifdef USE_XCB
-       XCBGlxRender(c, ctx->currentContextTag, size, (char *)ctx->buf);
+       xcb_glx_render(c, ctx->currentContextTag, size,
+                      (const uint8_t *)ctx->buf);
 #else
        /* Send the entire buffer as an X request */
        LockDisplay(dpy);
@@ -1315,8 +1013,8 @@ void __glXSendLargeChunk(__GLXcontext *gc, GLint requestNumber,
 {
     Display *dpy = gc->currentDpy;
 #ifdef USE_XCB
-    XCBConnection *c = XCBConnectionOfDisplay(dpy);
-    XCBGlxRenderLarge(c, gc->currentContextTag, requestNumber, totalRequests, dataLen, data);
+    xcb_connection_t *c = XGetXCBConnection(dpy);
+    xcb_glx_render_large(c, gc->currentContextTag, requestNumber, totalRequests, dataLen, data);
 #else
     xGLXRenderLargeReq *req;
     
@@ -1395,7 +1093,7 @@ void __glXSendLargeCommand(__GLXcontext *ctx,
 
 /************************************************************************/
 
-GLXContext glXGetCurrentContext(void)
+PUBLIC GLXContext glXGetCurrentContext(void)
 {
     GLXContext cx = __glXGetCurrentContext();
     
@@ -1406,40 +1104,13 @@ GLXContext glXGetCurrentContext(void)
     }
 }
 
-GLXDrawable glXGetCurrentDrawable(void)
+PUBLIC GLXDrawable glXGetCurrentDrawable(void)
 {
     GLXContext gc = __glXGetCurrentContext();
     return gc->currentDrawable;
 }
 
 
-/************************************************************************/
-
-#ifdef GLX_DIRECT_RENDERING
-/* Return the DRI per screen structure */
-__DRIscreen *__glXFindDRIScreen(__DRInativeDisplay *dpy, int scrn)
-{
-    __DRIscreen *pDRIScreen = NULL;
-    XExtDisplayInfo *info = __glXFindDisplay(dpy);
-    XExtData **privList, *found;
-    __GLXdisplayPrivate *dpyPriv;
-    XEDataObject dataObj;
-
-    __glXLock();
-    dataObj.display = dpy;
-    privList = XEHeadOfExtensionList(dataObj);
-    found = XFindOnExtensionList(privList, info->codes->extension);
-    __glXUnlock();
-
-    if (found) {
-       dpyPriv = (__GLXdisplayPrivate *)found->private_data;
-       pDRIScreen = &dpyPriv->screenConfigs[scrn].driScreen;
-    }
-
-    return pDRIScreen;
-}
-#endif
-
 /************************************************************************/
 
 static Bool SendMakeCurrentRequest( Display *dpy, CARD8 opcode,
@@ -1460,12 +1131,17 @@ static Bool SendMakeCurrentRequest( Display *dpy, CARD8 opcode,
  * \warning
  * This function assumes that \c dpy is locked with \c LockDisplay on entry.
  */
-static Bool SendMakeCurrentRequest( Display *dpy, CARD8 opcode,
-                                   GLXContextID gc_id, GLXContextTag gc_tag,
-                                   GLXDrawable draw, GLXDrawable read,
-                                   xGLXMakeCurrentReply * reply )
+static Bool SendMakeCurrentRequest(Display *dpy, CARD8 opcode,
+                                  GLXContextID gc_id, GLXContextTag gc_tag,
+                                  GLXDrawable draw, GLXDrawable read,
+                                  xGLXMakeCurrentReply *reply)
 {
-    if ( draw == read ) {
+    Bool ret;
+
+
+    LockDisplay(dpy);
+
+    if (draw == read) {
        xGLXMakeCurrentReq *req;
 
        GetReq(GLXMakeCurrent,req);
@@ -1483,7 +1159,7 @@ static Bool SendMakeCurrentRequest( Display *dpy, CARD8 opcode,
         * not the SGI extension.
         */
 
-       if ( (priv->majorVersion > 1) || (priv->minorVersion >= 3) ) {
+       if ((priv->majorVersion > 1) || (priv->minorVersion >= 3)) {
            xGLXMakeContextCurrentReq *req;
 
            GetReq(GLXMakeContextCurrent,req);
@@ -1511,183 +1187,172 @@ static Bool SendMakeCurrentRequest( Display *dpy, CARD8 opcode,
        }
     }
 
-    return _XReply(dpy, (xReply*) reply, 0, False);
+    ret = _XReply(dpy, (xReply*) reply, 0, False);
+
+    UnlockDisplay(dpy);
+    SyncHandle();
+
+    return ret;
 }
 
 
 #ifdef GLX_DIRECT_RENDERING
+static __DRIdrawable *
+FetchDRIDrawable( Display *dpy, GLXDrawable drawable, GLXContext gc)
+{
+    __GLXdisplayPrivate * const priv = __glXInitialize(dpy);
+    __GLXdrawable *pdraw;
+    __GLXscreenConfigs *sc;
+    drm_drawable_t hwDrawable;
+    void *empty_attribute_list = NULL;
+
+    if (priv == NULL || priv->driDisplay.private == NULL)
+       return NULL;
+    
+    sc = &priv->screenConfigs[gc->screen];
+    if (__glxHashLookup(sc->drawHash, drawable, (void *) &pdraw) == 0)
+       return &pdraw->driDrawable;
+
+    /* Allocate a new drawable */
+    pdraw = Xmalloc(sizeof(*pdraw));
+    if (!pdraw)
+       return NULL;
+
+    pdraw->drawable = drawable;
+    pdraw->psc = sc;
+
+    if (!XF86DRICreateDrawable(dpy, sc->scr, drawable, &hwDrawable))
+       return NULL;
+
+    /* Create a new drawable */
+    pdraw->driDrawable.private =
+       (*sc->driScreen.createNewDrawable)(&sc->driScreen,
+                                          gc->mode,
+                                          &pdraw->driDrawable,
+                                          hwDrawable,
+                                          GLX_WINDOW_BIT,
+                                          empty_attribute_list);
+
+    if (!pdraw->driDrawable.private) {
+       XF86DRIDestroyDrawable(dpy, sc->scr, drawable);
+       Xfree(pdraw);
+       return NULL;
+    }
+
+    if (__glxHashInsert(sc->drawHash, drawable, pdraw)) {
+       (*pdraw->driDrawable.destroyDrawable)(&pdraw->driDrawable);
+       XF86DRIDestroyDrawable(dpy, sc->scr, drawable);
+       Xfree(pdraw);
+       return NULL;
+    }
+
+    return &pdraw->driDrawable;
+}
+
 static Bool BindContextWrapper( Display *dpy, GLXContext gc,
                                GLXDrawable draw, GLXDrawable read )
 {
-    return (*gc->driContext.bindContext)(dpy, gc->screen, draw, read,
-                                        & gc->driContext);
+    __DRIdrawable *pdraw = FetchDRIDrawable(dpy, draw, gc);
+    __DRIdrawable *pread = FetchDRIDrawable(dpy, read, gc);
+
+    return (*gc->driContext.bindContext)(&gc->driContext, pdraw, pread);
 }
 
 
 static Bool UnbindContextWrapper( GLXContext gc )
 {
-    return (*gc->driContext.unbindContext)(gc->currentDpy, gc->screen, 
-                                          gc->currentDrawable,
-                                          gc->currentReadable,
-                                          & gc->driContext );
+    return (*gc->driContext.unbindContext)(&gc->driContext);
 }
 #endif /* GLX_DIRECT_RENDERING */
 
 
-/*
-** Make a particular context current.
-** NOTE: this is in this file so that it can access dummyContext.
-*/
+/**
+ * Make a particular context current.
+ * 
+ * \note This is in this file so that it can access dummyContext.
+ */
 USED static Bool MakeContextCurrent(Display *dpy, GLXDrawable draw,
                                     GLXDrawable read, GLXContext gc)
 {
     xGLXMakeCurrentReply reply;
-    GLXContext oldGC;
-    CARD8 opcode, oldOpcode;
-    Bool sentRequestToOldDpy = False;
-    Bool bindReturnValue = True;
+    const GLXContext oldGC = __glXGetCurrentContext();
+    const CARD8 opcode = __glXSetupForCommand(dpy);
+    const CARD8 oldOpcode = ((gc == oldGC) || (oldGC == &dummyContext))
+      ? opcode : __glXSetupForCommand(oldGC->currentDpy);
+    Bool bindReturnValue;
+
 
-    opcode = __glXSetupForCommand(dpy);
-    if (!opcode) {
+    if (!opcode || !oldOpcode) {
        return GL_FALSE;
     }
 
-    /*
-    ** Make sure that the new context has a nonzero ID.  In the request,
-    ** a zero context ID is used only to mean that we bind to no current
-    ** context.
-    */
+    /* Make sure that the new context has a nonzero ID.  In the request,
+     * a zero context ID is used only to mean that we bind to no current
+     * context.
+     */
     if ((gc != NULL) && (gc->xid == None)) {
        return GL_FALSE;
     }
 
-    oldGC = __glXGetCurrentContext();
-    oldOpcode = (gc == oldGC) ? opcode : __glXSetupForCommand(dpy);
-    if (!oldOpcode) {
+#ifndef GLX_DIRECT_RENDERING
+    if (gc && gc->isDirect) {
        return GL_FALSE;
     }
+#endif
 
-    if ((dpy != oldGC->currentDpy || (gc && gc->isDirect)) &&
-       !oldGC->isDirect && oldGC != &dummyContext) {
-       /*
-       ** We are either switching from one dpy to another and have to
-       ** send a request to the previous dpy to unbind the previous
-       ** context, or we are switching away from a indirect context to
-       ** a direct context and have to send a request to the dpy to
-       ** unbind the previous context.
-       */
-       sentRequestToOldDpy = True;
-        LockDisplay(oldGC->currentDpy);
-       if ( ! SendMakeCurrentRequest( oldGC->currentDpy, oldOpcode, None,
-                                      oldGC->currentContextTag, None, None,
-                                      &reply ) ) {
-           /* The make current failed.  Just return GL_FALSE. */
-           UnlockDisplay(oldGC->currentDpy);
-           SyncHandle();
-           return GL_FALSE;
-       }
+    _glapi_check_multithread();
 
-       oldGC->currentContextTag = 0;
-    }
-    
 #ifdef GLX_DIRECT_RENDERING
-    /* Unbind the old direct rendering context */
-    if (oldGC->isDirect) {
-       if (oldGC->driContext.private) {
-           if (! UnbindContextWrapper( oldGC )) {
-               /* The make current failed.  Just return GL_FALSE. */
-               return GL_FALSE;
-           }
-       }
-       oldGC->currentContextTag = 0;
-    }
-
     /* Bind the direct rendering context to the drawable */
     if (gc && gc->isDirect) {
-       if (gc->driContext.private) {
-           bindReturnValue = BindContextWrapper( dpy, gc, draw, read );
-       }
-    } else {
+       bindReturnValue = (gc->driContext.private) 
+         ? BindContextWrapper(dpy, gc, draw, read)
+         : False;
+    } else
 #endif
-        _glapi_check_multithread();
+    {
        /* Send a glXMakeCurrent request to bind the new context. */
-       LockDisplay(dpy);
-
-       bindReturnValue = SendMakeCurrentRequest( dpy, opcode, 
-                                                 gc ? gc->xid : None,
-                                                 oldGC->currentContextTag,
-                                                 draw, read, &reply );
-       UnlockDisplay(dpy);
-#ifdef GLX_DIRECT_RENDERING
+       bindReturnValue = 
+         SendMakeCurrentRequest(dpy, opcode, gc ? gc->xid : None,
+                                ((dpy != oldGC->currentDpy) || oldGC->isDirect)
+                                ? None : oldGC->currentContextTag,
+                                draw, read, &reply);
     }
-#endif
 
 
     if (!bindReturnValue) {
-       /* The make current failed. */
-       if (gc && !gc->isDirect) {
-           SyncHandle();
-       }
+       return False;
+    }
 
+    if ((dpy != oldGC->currentDpy || (gc && gc->isDirect)) &&
+       !oldGC->isDirect && oldGC != &dummyContext) {
+       xGLXMakeCurrentReply dummy_reply;
+
+       /* We are either switching from one dpy to another and have to
+        * send a request to the previous dpy to unbind the previous
+        * context, or we are switching away from a indirect context to
+        * a direct context and have to send a request to the dpy to
+        * unbind the previous context.
+        */
+       (void) SendMakeCurrentRequest(oldGC->currentDpy, oldOpcode, None,
+                                     oldGC->currentContextTag, None, None,
+                                     & dummy_reply);
+    }
 #ifdef GLX_DIRECT_RENDERING
-       /* If the old context was direct rendering, then re-bind to it. */
-       if (oldGC->isDirect) {
-           if (oldGC->driContext.private) {
-               if (! BindContextWrapper( oldGC->currentDpy, oldGC,
-                                         oldGC->currentDrawable,
-                                         oldGC->currentReadable )) {
-                   /*
-                   ** The request failed; this cannot happen with the
-                   ** current API.  If in the future the API is
-                   ** extended to allow context sharing between
-                   ** clients, then this may fail (because another
-                   ** client may have grabbed the context); in that
-                   ** case, we cannot undo the previous request, and
-                   ** cannot adhere to the "no-op" behavior.
-                   */
-               }
-           }
-       } else
-#endif
-       /*
-       ** If we had just sent a request to a previous dpy, we have to
-       ** undo that request (because if a command fails, it should act
-       ** like a no-op) by making current to the previous context and
-       ** drawable.
-       */
-       if (sentRequestToOldDpy) {
-           if ( !SendMakeCurrentRequest( oldGC->currentDpy, oldOpcode,
-                                         oldGC->xid, 0, 
-                                         oldGC->currentDrawable,
-                                         oldGC->currentReadable, &reply ) ) {
-               UnlockDisplay(oldGC->currentDpy);
-               SyncHandle();
-               /*
-               ** The request failed; this cannot happen with the
-               ** current API.  If in the future the API is extended to
-               ** allow context sharing between clients, then this may
-               ** fail (because another client may have grabbed the
-               ** context); in that case, we cannot undo the previous
-               ** request, and cannot adhere to the "no-op" behavior.
-               */
-           }
-            else {
-               UnlockDisplay(oldGC->currentDpy);
-            }
-           oldGC->currentContextTag = reply.contextTag;
-       }
-       return GL_FALSE;
+    else if (oldGC->isDirect && oldGC->driContext.private) {
+       (void) UnbindContextWrapper(oldGC);
     }
+#endif
+
 
     /* Update our notion of what is current */
     __glXLock();
     if (gc == oldGC) {
-       /*
-       ** Even though the contexts are the same the drawable might have
-       ** changed.  Note that gc cannot be the dummy, and that oldGC
-       ** cannot be NULL, therefore if they are the same, gc is not
-       ** NULL and not the dummy.
-       */
+       /* Even though the contexts are the same the drawable might have
+        * changed.  Note that gc cannot be the dummy, and that oldGC
+        * cannot be NULL, therefore if they are the same, gc is not
+        * NULL and not the dummy.
+        */
        gc->currentDrawable = draw;
        gc->currentReadable = read;
     } else {
@@ -1699,17 +1364,19 @@ USED static Bool MakeContextCurrent(Display *dpy, GLXDrawable draw,
            oldGC->currentContextTag = 0;
 
            if (oldGC->xid == None) {
-               /* 
-               ** We are switching away from a context that was
-               ** previously destroyed, so we need to free the memory
-               ** for the old handle.
-               */
+               /* We are switching away from a context that was
+                * previously destroyed, so we need to free the memory
+                * for the old handle.
+                */
 #ifdef GLX_DIRECT_RENDERING
                /* Destroy the old direct rendering context */
                if (oldGC->isDirect) {
                    if (oldGC->driContext.private) {
                        (*oldGC->driContext.destroyContext)
-                           (dpy, oldGC->screen, oldGC->driContext.private);
+                           (&oldGC->driContext);
+                       XF86DRIDestroyContext(oldGC->createDpy,
+                                             oldGC->psc->scr,
+                                             gc->hwContextID);
                        oldGC->driContext.private = NULL;
                    }
                }
@@ -1719,35 +1386,30 @@ USED static Bool MakeContextCurrent(Display *dpy, GLXDrawable draw,
        }
        if (gc) {
            __glXSetCurrentContext(gc);
-#ifdef GLX_DIRECT_RENDERING
+
+           gc->currentDpy = dpy;
+           gc->currentDrawable = draw;
+           gc->currentReadable = read;
+
             if (!gc->isDirect) {
                if (!IndirectAPI)
                   IndirectAPI = __glXNewIndirectAPI();
                _glapi_set_dispatch(IndirectAPI);
-# ifdef GLX_USE_APPLEGL
+
+#ifdef GLX_USE_APPLEGL
                do {
                    extern void XAppleDRIUseIndirectDispatch(void);
                    XAppleDRIUseIndirectDispatch();
                } while (0);
-# endif
-            }
-#else
-            /* if not direct rendering, always need indirect dispatch */
-            if (!IndirectAPI)
-               IndirectAPI = __glXNewIndirectAPI();
-            _glapi_set_dispatch(IndirectAPI);
 #endif
-           gc->currentDpy = dpy;
-           gc->currentDrawable = draw;
-           gc->currentReadable = read;
 
-           if ( ! gc->isDirect ) {
-               __GLXattribute * state = (__GLXattribute *)(gc->client_state_private);
+               __GLXattribute *state = 
+                 (__GLXattribute *)(gc->client_state_private);
 
                gc->currentContextTag = reply.contextTag;
-               if ( state->array_state == NULL ) {
-                   (void) glGetString( GL_EXTENSIONS );
-                   (void) glGetString( GL_VERSION );
+               if (state->array_state == NULL) {
+                   (void) glGetString(GL_EXTENSIONS);
+                   (void) glGetString(GL_VERSION);
                    __glXInitVertexArrayState(gc);
                }
            }
@@ -1766,8 +1428,7 @@ USED static Bool MakeContextCurrent(Display *dpy, GLXDrawable draw,
 }
 
 
-PUBLIC Bool GLX_PREFIX(glXMakeCurrent)(Display *dpy, GLXDrawable draw,
-                                       GLXContext gc)
+PUBLIC Bool glXMakeCurrent(Display *dpy, GLXDrawable draw, GLXContext gc)
 {
     return MakeContextCurrent( dpy, draw, draw, gc );
 }