1 /*
2  * Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
3  * Copyright © 2008 Red Hat, Inc.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Soft-
7  * ware"), to deal in the Software without restriction, including without
8  * limitation the rights to use, copy, modify, merge, publish, distribute,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, provided that the above copyright
11  * notice(s) and this permission notice appear in all copies of the Soft-
12  * ware and that both the above copyright notice(s) and this permission
13  * notice appear in supporting documentation.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
17  * ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY
18  * RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN
19  * THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSE-
20  * QUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
21  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
22  * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFOR-
23  * MANCE OF THIS SOFTWARE.
24  *
25  * Except as contained in this notice, the name of a copyright holder shall
26  * not be used in advertising or otherwise to promote the sale, use or
27  * other dealings in this Software without prior written authorization of
28  * the copyright holder.
29  *
30  * Authors:
31  *   Kevin E. Martin <kevin@precisioninsight.com>
32  *   Brian Paul <brian@precisioninsight.com>
33  *   Kristian Høgsberg (krh@redhat.com)
34  */
35 
36 #if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
37 
38 #include <unistd.h>
39 #include <dlfcn.h>
40 #include <stdarg.h>
41 #include "glxclient.h"
42 #include "dri_common.h"
43 #include "loader.h"
44 #include <X11/Xlib-xcb.h>
45 #include <xcb/xproto.h>
46 
47 #ifndef RTLD_NOW
48 #define RTLD_NOW 0
49 #endif
50 #ifndef RTLD_GLOBAL
51 #define RTLD_GLOBAL 0
52 #endif
53 
54 #ifndef GL_LIB_NAME
55 #define GL_LIB_NAME "libGL.so.1"
56 #endif
57 
58 /**
59  * Try to \c dlopen the named driver.
60  *
61  * This function adds the "_dri.so" suffix to the driver name and searches the
62  * directories specified by the \c LIBGL_DRIVERS_PATH environment variable in
63  * order to find the driver.
64  *
65  * \param driverName - a name like "i965", "radeon", "nouveau", etc.
66  * \param out_driver_handle - Address to return the resulting dlopen() handle.
67  *
68  * \returns
69  * The __DRIextension entrypoint table for the driver, or \c NULL if driver
70  * file not found.
71  */
72 _X_HIDDEN const __DRIextension **
driOpenDriver(const char * driverName,void ** out_driver_handle)73 driOpenDriver(const char *driverName, void **out_driver_handle)
74 {
75    void *glhandle;
76 
77    /* Attempt to make sure libGL symbols will be visible to the driver */
78    glhandle = dlopen(GL_LIB_NAME, RTLD_NOW | RTLD_GLOBAL);
79 
80    static const char *search_path_vars[] = {
81       "LIBGL_DRIVERS_PATH",
82       "LIBGL_DRIVERS_DIR", /* deprecated */
83       NULL
84    };
85 
86    const __DRIextension **extensions =
87       loader_open_driver(driverName, out_driver_handle, search_path_vars);
88 
89    if (glhandle)
90       dlclose(glhandle);
91 
92    return extensions;
93 }
94 
95 #define __ATTRIB(attrib, field) \
96     { attrib, offsetof(struct glx_config, field) }
97 
98 static const struct
99 {
100    unsigned int attrib, offset;
101 } attribMap[] = {
102    __ATTRIB(__DRI_ATTRIB_BUFFER_SIZE, rgbBits),
103       __ATTRIB(__DRI_ATTRIB_LEVEL, level),
104       __ATTRIB(__DRI_ATTRIB_RED_SIZE, redBits),
105       __ATTRIB(__DRI_ATTRIB_GREEN_SIZE, greenBits),
106       __ATTRIB(__DRI_ATTRIB_BLUE_SIZE, blueBits),
107       __ATTRIB(__DRI_ATTRIB_ALPHA_SIZE, alphaBits),
108       __ATTRIB(__DRI_ATTRIB_DEPTH_SIZE, depthBits),
109       __ATTRIB(__DRI_ATTRIB_STENCIL_SIZE, stencilBits),
110       __ATTRIB(__DRI_ATTRIB_ACCUM_RED_SIZE, accumRedBits),
111       __ATTRIB(__DRI_ATTRIB_ACCUM_GREEN_SIZE, accumGreenBits),
112       __ATTRIB(__DRI_ATTRIB_ACCUM_BLUE_SIZE, accumBlueBits),
113       __ATTRIB(__DRI_ATTRIB_ACCUM_ALPHA_SIZE, accumAlphaBits),
114       __ATTRIB(__DRI_ATTRIB_SAMPLE_BUFFERS, sampleBuffers),
115       __ATTRIB(__DRI_ATTRIB_SAMPLES, samples),
116       __ATTRIB(__DRI_ATTRIB_DOUBLE_BUFFER, doubleBufferMode),
117       __ATTRIB(__DRI_ATTRIB_STEREO, stereoMode),
118       __ATTRIB(__DRI_ATTRIB_AUX_BUFFERS, numAuxBuffers),
119       __ATTRIB(__DRI_ATTRIB_SWAP_METHOD, swapMethod),
120       __ATTRIB(__DRI_ATTRIB_BIND_TO_TEXTURE_RGB, bindToTextureRgb),
121       __ATTRIB(__DRI_ATTRIB_BIND_TO_TEXTURE_RGBA, bindToTextureRgba),
122       __ATTRIB(__DRI_ATTRIB_BIND_TO_MIPMAP_TEXTURE, bindToMipmapTexture),
123       __ATTRIB(__DRI_ATTRIB_YINVERTED, yInverted),
124       __ATTRIB(__DRI_ATTRIB_FRAMEBUFFER_SRGB_CAPABLE, sRGBCapable)
125 };
126 
127 static int
scalarEqual(struct glx_config * mode,unsigned int attrib,unsigned int value)128 scalarEqual(struct glx_config *mode, unsigned int attrib, unsigned int value)
129 {
130    unsigned glxValue, i;
131 
132    for (i = 0; i < ARRAY_SIZE(attribMap); i++)
133       if (attribMap[i].attrib == attrib) {
134          glxValue = *(unsigned int *) ((char *) mode + attribMap[i].offset);
135          return glxValue == GLX_DONT_CARE || glxValue == value;
136       }
137 
138    return GL_TRUE;              /* Is a non-existing attribute equal to value? */
139 }
140 
141 static int
driConfigEqual(const __DRIcoreExtension * core,struct glx_config * config,const __DRIconfig * driConfig)142 driConfigEqual(const __DRIcoreExtension *core,
143                struct glx_config *config, const __DRIconfig *driConfig)
144 {
145    unsigned int attrib, value, glxValue;
146    int i;
147 
148    i = 0;
149    while (core->indexConfigAttrib(driConfig, i++, &attrib, &value)) {
150       switch (attrib) {
151       case __DRI_ATTRIB_RENDER_TYPE:
152          glxValue = 0;
153          if (value & __DRI_ATTRIB_RGBA_BIT) {
154             glxValue |= GLX_RGBA_BIT;
155          }
156          if (value & __DRI_ATTRIB_COLOR_INDEX_BIT) {
157             glxValue |= GLX_COLOR_INDEX_BIT;
158          }
159          if (value & __DRI_ATTRIB_FLOAT_BIT) {
160             glxValue |= GLX_RGBA_FLOAT_BIT_ARB;
161          }
162          if (value & __DRI_ATTRIB_UNSIGNED_FLOAT_BIT) {
163             glxValue |= GLX_RGBA_UNSIGNED_FLOAT_BIT_EXT;
164          }
165          if (glxValue != config->renderType)
166             return GL_FALSE;
167          break;
168 
169       case __DRI_ATTRIB_BIND_TO_TEXTURE_TARGETS:
170          glxValue = 0;
171          if (value & __DRI_ATTRIB_TEXTURE_1D_BIT)
172             glxValue |= GLX_TEXTURE_1D_BIT_EXT;
173          if (value & __DRI_ATTRIB_TEXTURE_2D_BIT)
174             glxValue |= GLX_TEXTURE_2D_BIT_EXT;
175          if (value & __DRI_ATTRIB_TEXTURE_RECTANGLE_BIT)
176             glxValue |= GLX_TEXTURE_RECTANGLE_BIT_EXT;
177          if (config->bindToTextureTargets != GLX_DONT_CARE &&
178              glxValue != config->bindToTextureTargets)
179             return GL_FALSE;
180          break;
181 
182       case __DRI_ATTRIB_SWAP_METHOD:
183          if (value == __DRI_ATTRIB_SWAP_EXCHANGE)
184             glxValue = GLX_SWAP_EXCHANGE_OML;
185          else if (value == __DRI_ATTRIB_SWAP_COPY)
186             glxValue = GLX_SWAP_COPY_OML;
187          else
188             glxValue = GLX_SWAP_UNDEFINED_OML;
189 
190          if (!scalarEqual(config, attrib, glxValue))
191             return GL_FALSE;
192 
193          break;
194 
195       /* Nerf some attributes we can safely ignore if the server claims to
196        * support them but the driver does not.
197        */
198       case __DRI_ATTRIB_CONFIG_CAVEAT:
199          if (value & __DRI_ATTRIB_NON_CONFORMANT_CONFIG)
200             glxValue = GLX_NON_CONFORMANT_CONFIG;
201          else if (value & __DRI_ATTRIB_SLOW_BIT)
202             glxValue = GLX_SLOW_CONFIG;
203          else
204             glxValue = GLX_NONE;
205          if (glxValue != config->visualRating) {
206             if (config->visualRating == GLX_NONE) {
207                static int warned;
208                if (!warned) {
209                   DebugMessageF("Not downgrading visual rating\n");
210                   warned = 1;
211                }
212             } else {
213                return GL_FALSE;
214             }
215          }
216          break;
217 
218       case __DRI_ATTRIB_AUX_BUFFERS:
219          if (!scalarEqual(config, attrib, value)) {
220             static int warned;
221             if (!warned) {
222                DebugMessageF("Disabling server's aux buffer support\n");
223                warned = 1;
224             }
225             config->numAuxBuffers = 0;
226          }
227          break;
228 
229       case __DRI_ATTRIB_BIND_TO_MIPMAP_TEXTURE:
230          if (!scalarEqual(config, attrib, value)) {
231             static int warned;
232             if (!warned) {
233                DebugMessageF("Disabling server's tfp mipmap support\n");
234                warned = 1;
235             }
236             config->bindToMipmapTexture = 0;
237          }
238          break;
239 
240       default:
241          if (!scalarEqual(config, attrib, value))
242             return GL_FALSE;
243       }
244    }
245 
246    return GL_TRUE;
247 }
248 
249 static struct glx_config *
createDriMode(const __DRIcoreExtension * core,struct glx_config * config,const __DRIconfig ** driConfigs)250 createDriMode(const __DRIcoreExtension * core,
251 	      struct glx_config *config, const __DRIconfig **driConfigs)
252 {
253    __GLXDRIconfigPrivate *driConfig;
254    int i;
255 
256    for (i = 0; driConfigs[i]; i++) {
257       if (driConfigEqual(core, config, driConfigs[i]))
258          break;
259    }
260 
261    if (driConfigs[i] == NULL)
262       return NULL;
263 
264    driConfig = malloc(sizeof *driConfig);
265    if (driConfig == NULL)
266       return NULL;
267 
268    driConfig->base = *config;
269    driConfig->driConfig = driConfigs[i];
270 
271    return &driConfig->base;
272 }
273 
274 _X_HIDDEN struct glx_config *
driConvertConfigs(const __DRIcoreExtension * core,struct glx_config * configs,const __DRIconfig ** driConfigs)275 driConvertConfigs(const __DRIcoreExtension * core,
276                   struct glx_config *configs, const __DRIconfig **driConfigs)
277 {
278    struct glx_config head, *tail, *m;
279 
280    tail = &head;
281    head.next = NULL;
282    for (m = configs; m; m = m->next) {
283       tail->next = createDriMode(core, m, driConfigs);
284       if (tail->next == NULL) {
285          /* no matching dri config for m */
286          continue;
287       }
288 
289 
290       tail = tail->next;
291    }
292 
293    return head.next;
294 }
295 
296 _X_HIDDEN void
driDestroyConfigs(const __DRIconfig ** configs)297 driDestroyConfigs(const __DRIconfig **configs)
298 {
299    int i;
300 
301    for (i = 0; configs[i]; i++)
302       free((__DRIconfig *) configs[i]);
303    free(configs);
304 }
305 
306 static struct glx_config *
driInferDrawableConfig(struct glx_screen * psc,GLXDrawable draw)307 driInferDrawableConfig(struct glx_screen *psc, GLXDrawable draw)
308 {
309    unsigned int fbconfig = 0;
310    xcb_get_window_attributes_cookie_t cookie = { 0 };
311    xcb_get_window_attributes_reply_t *attr = NULL;
312    xcb_connection_t *conn = XGetXCBConnection(psc->dpy);
313 
314    /* In practice here, either the XID is a bare Window or it was created
315     * by some other client. First let's see if the X server can tell us
316     * the answer. Xorg first added GLX_EXT_no_config_context in 1.20, where
317     * this usually works except for bare Windows that haven't been made
318     * current yet.
319     */
320    if (__glXGetDrawableAttribute(psc->dpy, draw, GLX_FBCONFIG_ID, &fbconfig)) {
321       return glx_config_find_fbconfig(psc->configs, fbconfig);
322    }
323 
324    /* Well this had better be a Window then. Figure out its visual and
325     * then find the corresponding GLX visual.
326     */
327    cookie = xcb_get_window_attributes(conn, draw);
328    attr = xcb_get_window_attributes_reply(conn, cookie, NULL);
329 
330    if (attr) {
331       uint32_t vid = attr->visual;
332       free(attr);
333       return glx_config_find_visual(psc->visuals, vid);
334    }
335 
336    return NULL;
337 }
338 
339 _X_HIDDEN __GLXDRIdrawable *
driFetchDrawable(struct glx_context * gc,GLXDrawable glxDrawable)340 driFetchDrawable(struct glx_context *gc, GLXDrawable glxDrawable)
341 {
342    Display *dpy = gc->psc->dpy;
343    struct glx_display *const priv = __glXInitialize(dpy);
344    __GLXDRIdrawable *pdraw;
345    struct glx_screen *psc;
346    struct glx_config *config = gc->config;
347    unsigned int type;
348 
349    if (priv == NULL)
350       return NULL;
351 
352    if (glxDrawable == None)
353       return NULL;
354 
355    psc = priv->screens[gc->screen];
356    if (priv->drawHash == NULL)
357       return NULL;
358 
359    if (__glxHashLookup(priv->drawHash, glxDrawable, (void *) &pdraw) == 0) {
360       /* Resurrected, so remove from the alive-query-set if exist. */
361       _mesa_set_remove_key(priv->zombieGLXDrawable, pdraw);
362 
363       pdraw->refcount ++;
364       return pdraw;
365    }
366 
367    /* if this is a no-config context, infer the fbconfig from the drawable */
368    if (config == NULL)
369       config = driInferDrawableConfig(gc->psc, glxDrawable);
370    if (config == NULL)
371       return NULL;
372 
373    /* We can't find this GLX drawable above because it's either:
374     *
375     * 1. An X window ID instead of a GLX window ID. This could happend when
376     *    glXMakeCurrent() is passed an X window directly instead of creating
377     *    GLXWindow with glXCreateWindow() first.
378     *
379     * 2. A GLXPbuffer created on other display:
380     *
381     *    From the GLX spec:
382     *
383     *      Like other drawable types, GLXPbuffers are shared; any client which
384     *      knows the associated XID can use a GLXPbuffer.
385     *
386     *    So client other than the creator of this GLXPbuffer could use its
387     *    XID to do something like glXMakeCurrent(). I can't find explicite
388     *    statement in GLX spec that also allow GLXWindow and GLXPixmap.
389     *
390     *    But even GLXWindow and GLXPixmap is allowed, currently client other
391     *    than the GLX drawable creator has no way to find which X drawable
392     *    (window or pixmap) this GLX drawable uses, except the GLXPbuffer
393     *    case which use the same XID for both X pixmap and GLX drawable.
394     */
395 
396    /* Infer the GLX drawable type. */
397    if (__glXGetDrawableAttribute(dpy, glxDrawable, GLX_DRAWABLE_TYPE, &type)) {
398       /* Xserver may support query with raw X11 window. */
399       if (type == GLX_PIXMAP_BIT) {
400          ErrorMessageF("GLXPixmap drawable type is not supported\n");
401          return NULL;
402       }
403    } else {
404       /* Xserver may not implement GLX_DRAWABLE_TYPE query yet. */
405       type = GLX_PBUFFER_BIT | GLX_WINDOW_BIT;
406    }
407 
408    pdraw = psc->driScreen->createDrawable(psc, glxDrawable, glxDrawable,
409                                           type, config);
410 
411    if (pdraw == NULL) {
412       ErrorMessageF("failed to create drawable\n");
413       return NULL;
414    }
415 
416    if (__glxHashInsert(priv->drawHash, glxDrawable, pdraw)) {
417       (*pdraw->destroyDrawable) (pdraw);
418       return NULL;
419    }
420    pdraw->refcount = 1;
421 
422    return pdraw;
423 }
424 
425 static int
discardGLXBadDrawableHandler(Display * display,xError * err,XExtCodes * codes,int * ret_code)426 discardGLXBadDrawableHandler(Display *display, xError *err, XExtCodes *codes,
427                              int *ret_code)
428 {
429    int code = codes->first_error + GLXBadDrawable;
430 
431    /* Only discard error which is expected. */
432    if (err->majorCode == codes->major_opcode &&
433        err->minorCode == X_GLXGetDrawableAttributes &&
434        /* newer xserver use GLXBadDrawable, old one use BadDrawable */
435        (err->errorCode == code || err->errorCode == BadDrawable)) {
436       *ret_code = 1;
437       return 1;
438    }
439 
440    return 0;
441 }
442 
443 static void
checkServerGLXDrawableAlive(const struct glx_display * priv)444 checkServerGLXDrawableAlive(const struct glx_display *priv)
445 {
446    ErrorType old = XESetError(priv->dpy, priv->codes.extension,
447                               discardGLXBadDrawableHandler);
448 
449    set_foreach(priv->zombieGLXDrawable, entry) {
450       __GLXDRIdrawable *pdraw = (__GLXDRIdrawable *)entry->key;
451       GLXDrawable drawable = pdraw->drawable;
452       unsigned int dummy;
453 
454       /* Fail to query, so the window has been closed. Release the GLXDrawable. */
455       if (!__glXGetDrawableAttribute(priv->dpy, drawable, GLX_WIDTH, &dummy)) {
456          pdraw->destroyDrawable(pdraw);
457          __glxHashDelete(priv->drawHash, drawable);
458          _mesa_set_remove(priv->zombieGLXDrawable, entry);
459       }
460    }
461 
462    XESetError(priv->dpy, priv->codes.extension, old);
463 }
464 
465 static void
releaseDrawable(const struct glx_display * priv,GLXDrawable drawable)466 releaseDrawable(const struct glx_display *priv, GLXDrawable drawable)
467 {
468    __GLXDRIdrawable *pdraw;
469 
470    if (__glxHashLookup(priv->drawHash, drawable, (void *) &pdraw) == 0) {
471       /* Only native window and pbuffer have same GLX and X11 drawable ID. */
472       if (pdraw->drawable == pdraw->xDrawable) {
473          pdraw->refcount --;
474          /* If pbuffer's refcount reaches 0, it must be imported from other
475           * display. Because pbuffer created from this display will always
476           * hold the last refcount until destroy the GLXPbuffer object.
477           */
478          if (pdraw->refcount == 0) {
479             if (pdraw->psc->keep_native_window_glx_drawable) {
480                checkServerGLXDrawableAlive(priv);
481                _mesa_set_add(priv->zombieGLXDrawable, pdraw);
482             } else {
483                pdraw->destroyDrawable(pdraw);
484                __glxHashDelete(priv->drawHash, drawable);
485             }
486          }
487       }
488    }
489 }
490 
491 _X_HIDDEN void
driReleaseDrawables(struct glx_context * gc)492 driReleaseDrawables(struct glx_context *gc)
493 {
494    const struct glx_display *priv = gc->psc->display;
495 
496    if (priv == NULL)
497       return;
498 
499    releaseDrawable(priv, gc->currentDrawable);
500    releaseDrawable(priv, gc->currentReadable);
501 
502    gc->currentDrawable = None;
503    gc->currentReadable = None;
504 
505 }
506 
507 _X_HIDDEN int
dri_convert_glx_attribs(unsigned num_attribs,const uint32_t * attribs,struct dri_ctx_attribs * dca)508 dri_convert_glx_attribs(unsigned num_attribs, const uint32_t *attribs,
509                         struct dri_ctx_attribs *dca)
510 {
511    unsigned i;
512    uint32_t profile = GLX_CONTEXT_CORE_PROFILE_BIT_ARB;
513 
514    dca->major_ver = 1;
515    dca->minor_ver = 0;
516    dca->render_type = GLX_RGBA_TYPE;
517    dca->reset = __DRI_CTX_RESET_NO_NOTIFICATION;
518    dca->release = __DRI_CTX_RELEASE_BEHAVIOR_FLUSH;
519    dca->flags = 0;
520    dca->api = __DRI_API_OPENGL;
521    dca->no_error = 0;
522 
523    if (num_attribs == 0)
524       return __DRI_CTX_ERROR_SUCCESS;
525 
526    /* This is actually an internal error, but what the heck. */
527    if (attribs == NULL)
528       return __DRI_CTX_ERROR_UNKNOWN_ATTRIBUTE;
529 
530    for (i = 0; i < num_attribs; i++) {
531       switch (attribs[i * 2]) {
532       case GLX_CONTEXT_MAJOR_VERSION_ARB:
533 	 dca->major_ver = attribs[i * 2 + 1];
534 	 break;
535       case GLX_CONTEXT_MINOR_VERSION_ARB:
536 	 dca->minor_ver = attribs[i * 2 + 1];
537 	 break;
538       case GLX_CONTEXT_FLAGS_ARB:
539 	 dca->flags = attribs[i * 2 + 1];
540 	 break;
541       case GLX_CONTEXT_OPENGL_NO_ERROR_ARB:
542 	 dca->no_error = attribs[i * 2 + 1];
543 	 break;
544       case GLX_CONTEXT_PROFILE_MASK_ARB:
545 	 profile = attribs[i * 2 + 1];
546 	 break;
547       case GLX_RENDER_TYPE:
548          dca->render_type = attribs[i * 2 + 1];
549 	 break;
550       case GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB:
551          switch (attribs[i * 2 + 1]) {
552          case GLX_NO_RESET_NOTIFICATION_ARB:
553             dca->reset = __DRI_CTX_RESET_NO_NOTIFICATION;
554             break;
555          case GLX_LOSE_CONTEXT_ON_RESET_ARB:
556             dca->reset = __DRI_CTX_RESET_LOSE_CONTEXT;
557             break;
558          default:
559             return __DRI_CTX_ERROR_UNKNOWN_ATTRIBUTE;
560          }
561          break;
562       case GLX_CONTEXT_RELEASE_BEHAVIOR_ARB:
563          switch (attribs[i * 2 + 1]) {
564          case GLX_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB:
565             dca->release = __DRI_CTX_RELEASE_BEHAVIOR_NONE;
566             break;
567          case GLX_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB:
568             dca->release = __DRI_CTX_RELEASE_BEHAVIOR_FLUSH;
569             break;
570          default:
571             return __DRI_CTX_ERROR_UNKNOWN_ATTRIBUTE;
572          }
573          break;
574       case GLX_SCREEN:
575          /* Implies GLX_EXT_no_config_context */
576          dca->render_type = GLX_DONT_CARE;
577          break;
578       default:
579 	 /* If an unknown attribute is received, fail.
580 	  */
581 	 return __DRI_CTX_ERROR_UNKNOWN_ATTRIBUTE;
582       }
583    }
584 
585    switch (profile) {
586    case GLX_CONTEXT_CORE_PROFILE_BIT_ARB:
587       /* This is the default value, but there are no profiles before OpenGL
588        * 3.2. The GLX_ARB_create_context_profile spec says:
589        *
590        *     "If the requested OpenGL version is less than 3.2,
591        *     GLX_CONTEXT_PROFILE_MASK_ARB is ignored and the functionality
592        *     of the context is determined solely by the requested version."
593        */
594       dca->api = (dca->major_ver > 3 || (dca->major_ver == 3 && dca->minor_ver >= 2))
595          ? __DRI_API_OPENGL_CORE : __DRI_API_OPENGL;
596       break;
597    case GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB:
598       dca->api = __DRI_API_OPENGL;
599       break;
600    case GLX_CONTEXT_ES_PROFILE_BIT_EXT:
601       if (dca->major_ver >= 3)
602          dca->api = __DRI_API_GLES3;
603       else if (dca->major_ver == 2 && dca->minor_ver == 0)
604          dca->api = __DRI_API_GLES2;
605       else if (dca->major_ver == 1 && dca->minor_ver < 2)
606          dca->api = __DRI_API_GLES;
607       else {
608          return __DRI_CTX_ERROR_BAD_API;
609       }
610       break;
611    default:
612       return __DRI_CTX_ERROR_BAD_API;
613    }
614 
615    /* Unknown flag value */
616    if (dca->flags & ~(__DRI_CTX_FLAG_DEBUG |
617                       __DRI_CTX_FLAG_FORWARD_COMPATIBLE |
618                       __DRI_CTX_FLAG_ROBUST_BUFFER_ACCESS |
619                       __DRI_CTX_FLAG_RESET_ISOLATION))
620       return __DRI_CTX_ERROR_UNKNOWN_FLAG;
621 
622    /* There are no forward-compatible contexts before OpenGL 3.0.  The
623     * GLX_ARB_create_context spec says:
624     *
625     *     "Forward-compatible contexts are defined only for OpenGL versions
626     *     3.0 and later."
627     */
628    if (dca->major_ver < 3 && (dca->flags & __DRI_CTX_FLAG_FORWARD_COMPATIBLE) != 0)
629       return __DRI_CTX_ERROR_BAD_FLAG;
630 
631    if (dca->major_ver >= 3 && dca->render_type == GLX_COLOR_INDEX_TYPE)
632       return __DRI_CTX_ERROR_BAD_FLAG;
633 
634    /* The KHR_no_error specs say:
635     *
636     *    Requires OpenGL ES 2.0 or OpenGL 2.0.
637     */
638    if (dca->no_error && dca->major_ver < 2)
639       return __DRI_CTX_ERROR_UNKNOWN_ATTRIBUTE;
640 
641    /* The GLX_ARB_create_context_no_error specs say:
642     *
643     *    BadMatch is generated if the GLX_CONTEXT_OPENGL_NO_ERROR_ARB is TRUE at
644     *    the same time as a debug or robustness context is specified.
645     *
646     */
647    if (dca->no_error && ((dca->flags & __DRI_CTX_FLAG_DEBUG) ||
648                          (dca->flags & __DRI_CTX_FLAG_ROBUST_BUFFER_ACCESS)))
649       return __DRI_CTX_ERROR_BAD_FLAG;
650 
651    return __DRI_CTX_ERROR_SUCCESS;
652 }
653 
654 struct glx_context *
dri_common_create_context(struct glx_screen * base,struct glx_config * config_base,struct glx_context * shareList,int renderType)655 dri_common_create_context(struct glx_screen *base,
656                           struct glx_config *config_base,
657                           struct glx_context *shareList,
658                           int renderType)
659 {
660    unsigned int error;
661    uint32_t attribs[2] = { GLX_RENDER_TYPE, renderType };
662 
663    return base->vtable->create_context_attribs(base, config_base, shareList,
664                                                1, attribs, &error);
665 }
666 
667 
668 /*
669  * Given a display pointer and screen number, determine the name of
670  * the DRI driver for the screen (i.e., "i965", "radeon", "nouveau", etc).
671  * Return True for success, False for failure.
672  */
673 static Bool
driGetDriverName(Display * dpy,int scrNum,char ** driverName)674 driGetDriverName(Display * dpy, int scrNum, char **driverName)
675 {
676    struct glx_screen *glx_screen = GetGLXScreenConfigs(dpy, scrNum);
677 
678    if (!glx_screen || !glx_screen->vtable->get_driver_name)
679       return False;
680 
681    *driverName = glx_screen->vtable->get_driver_name(glx_screen);
682    return True;
683 }
684 
685 /*
686  * Exported function for querying the DRI driver for a given screen.
687  *
688  * The returned char pointer points to a static array that will be
689  * overwritten by subsequent calls.
690  */
691 _GLX_PUBLIC const char *
glXGetScreenDriver(Display * dpy,int scrNum)692 glXGetScreenDriver(Display * dpy, int scrNum)
693 {
694    static char ret[32];
695    char *driverName;
696 
697    if (driGetDriverName(dpy, scrNum, &driverName)) {
698       int len;
699       if (!driverName)
700          return NULL;
701       len = strlen(driverName);
702       if (len >= 31)
703          return NULL;
704       memcpy(ret, driverName, len + 1);
705       free(driverName);
706       return ret;
707    }
708    return NULL;
709 }
710 
711 /* glXGetDriverConfig must return a pointer with a static lifetime. To avoid
712  * keeping drivers loaded and other leaks, we keep a cache of results here that
713  * is cleared by an atexit handler.
714  */
715 struct driver_config_entry {
716    struct driver_config_entry *next;
717    char *driverName;
718    char *config;
719 };
720 
721 static pthread_mutex_t driver_config_mutex = PTHREAD_MUTEX_INITIALIZER;
722 static struct driver_config_entry *driver_config_cache = NULL;
723 
724 /* Called as an atexit function. Otherwise, this would have to be called with
725  * driver_config_mutex locked.
726  */
727 static void
clear_driver_config_cache()728 clear_driver_config_cache()
729 {
730    while (driver_config_cache) {
731       struct driver_config_entry *e = driver_config_cache;
732       driver_config_cache = e->next;
733 
734       free(e->driverName);
735       free(e->config);
736       free(e);
737    }
738 }
739 
740 static char *
get_driver_config(const char * driverName)741 get_driver_config(const char *driverName)
742 {
743    void *handle;
744    char *config = NULL;
745    const __DRIextension **extensions = driOpenDriver(driverName, &handle);
746    if (extensions) {
747       for (int i = 0; extensions[i]; i++) {
748          if (strcmp(extensions[i]->name, __DRI_CONFIG_OPTIONS) != 0)
749             continue;
750 
751          __DRIconfigOptionsExtension *ext =
752             (__DRIconfigOptionsExtension *)extensions[i];
753 
754          if (ext->base.version >= 2)
755             config = ext->getXml(driverName);
756          else
757             config = strdup(ext->xml);
758 
759          break;
760       }
761    }
762 
763    if (!config) {
764       /* Fall back to the old method */
765       config = dlsym(handle, "__driConfigOptions");
766       if (config)
767          config = strdup(config);
768    }
769 
770    dlclose(handle);
771 
772    return config;
773 }
774 
775 /*
776  * Exported function for obtaining a driver's option list (UTF-8 encoded XML).
777  *
778  * The returned char pointer points directly into the driver. Therefore
779  * it should be treated as a constant.
780  *
781  * If the driver was not found or does not support configuration NULL is
782  * returned.
783  */
784 _GLX_PUBLIC const char *
glXGetDriverConfig(const char * driverName)785 glXGetDriverConfig(const char *driverName)
786 {
787    struct driver_config_entry *e;
788 
789    pthread_mutex_lock(&driver_config_mutex);
790 
791    for (e = driver_config_cache; e; e = e->next) {
792       if (strcmp(e->driverName, driverName) == 0)
793          goto out;
794    }
795 
796    e = malloc(sizeof(*e));
797    if (!e)
798       goto out;
799 
800    e->config = get_driver_config(driverName);
801    e->driverName = strdup(driverName);
802    if (!e->config || !e->driverName) {
803       free(e->config);
804       free(e->driverName);
805       free(e);
806       e = NULL;
807       goto out;
808    }
809 
810    e->next = driver_config_cache;
811    driver_config_cache = e;
812 
813    if (!e->next)
814       atexit(clear_driver_config_cache);
815 
816 out:
817    pthread_mutex_unlock(&driver_config_mutex);
818 
819    return e ? e->config : NULL;
820 }
821 
822 #endif /* GLX_DIRECT_RENDERING */
823