• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2008 Red Hat, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Soft-
6  * ware"), to deal in the Software without restriction, including without
7  * limitation the rights to use, copy, modify, merge, publish, distribute,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, provided that the above copyright
10  * notice(s) and this permission notice appear in all copies of the Soft-
11  * ware and that both the above copyright notice(s) and this permission
12  * notice appear in supporting documentation.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
16  * ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY
17  * RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN
18  * THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSE-
19  * QUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
20  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
21  * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFOR-
22  * MANCE OF THIS SOFTWARE.
23  *
24  * Except as contained in this notice, the name of a copyright holder shall
25  * not be used in advertising or otherwise to promote the sale, use or
26  * other dealings in this Software without prior written authorization of
27  * the copyright holder.
28  *
29  * Authors:
30  *   Kristian Høgsberg (krh@redhat.com)
31  */
32 
33 #if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
34 
35 #include <X11/Xlib.h>
36 #include <X11/extensions/Xfixes.h>
37 #include <X11/Xlib-xcb.h>
38 #include <xcb/xcb.h>
39 #include <xcb/dri2.h>
40 #include "glxclient.h"
41 #include <X11/extensions/dri2proto.h>
42 #include <dlfcn.h>
43 #include <fcntl.h>
44 #include <unistd.h>
45 #include <sys/types.h>
46 #include <sys/mman.h>
47 #include <sys/time.h>
48 #include "dri2.h"
49 #include "dri_common.h"
50 #include "dri2_priv.h"
51 #include "loader.h"
52 
53 /* From driconf.h, user exposed so should be stable */
54 #define DRI_CONF_VBLANK_NEVER 0
55 #define DRI_CONF_VBLANK_DEF_INTERVAL_0 1
56 #define DRI_CONF_VBLANK_DEF_INTERVAL_1 2
57 #define DRI_CONF_VBLANK_ALWAYS_SYNC 3
58 
59 #undef DRI2_MINOR
60 #define DRI2_MINOR 1
61 
62 struct dri2_display
63 {
64    __GLXDRIdisplay base;
65 
66    /*
67     ** XFree86-DRI version information
68     */
69    int driMajor;
70    int driMinor;
71    int driPatch;
72    int swapAvailable;
73    int invalidateAvailable;
74 
75    __glxHashTable *dri2Hash;
76 
77    const __DRIextension *loader_extensions[5];
78 };
79 
80 struct dri2_drawable
81 {
82    __GLXDRIdrawable base;
83    __DRIdrawable *driDrawable;
84    __DRIbuffer buffers[5];
85    int bufferCount;
86    int width, height;
87    int have_back;
88    int have_fake_front;
89    int swap_interval;
90 
91    uint64_t previous_time;
92    unsigned frames;
93 };
94 
95 static const struct glx_context_vtable dri2_context_vtable;
96 
97 /* For XCB's handling of ust/msc/sbc counters, we have to hand it the high and
98  * low halves separately.  This helps you split them.
99  */
100 static void
split_counter(uint64_t counter,uint32_t * hi,uint32_t * lo)101 split_counter(uint64_t counter, uint32_t *hi, uint32_t *lo)
102 {
103    *hi = (counter >> 32);
104    *lo = counter & 0xffffffff;
105 }
106 
107 static uint64_t
merge_counter(uint32_t hi,uint32_t lo)108 merge_counter(uint32_t hi, uint32_t lo)
109 {
110    return ((uint64_t)hi << 32) | lo;
111 }
112 
113 static void
dri2_destroy_context(struct glx_context * context)114 dri2_destroy_context(struct glx_context *context)
115 {
116    struct dri2_context *pcp = (struct dri2_context *) context;
117    struct dri2_screen *psc = (struct dri2_screen *) context->psc;
118 
119    driReleaseDrawables(&pcp->base);
120 
121    free((char *) context->extensions);
122 
123    (*psc->core->destroyContext) (pcp->driContext);
124 
125    free(pcp);
126 }
127 
128 static Bool
dri2_bind_context(struct glx_context * context,struct glx_context * old,GLXDrawable draw,GLXDrawable read)129 dri2_bind_context(struct glx_context *context, struct glx_context *old,
130 		  GLXDrawable draw, GLXDrawable read)
131 {
132    struct dri2_context *pcp = (struct dri2_context *) context;
133    struct dri2_screen *psc = (struct dri2_screen *) pcp->base.psc;
134    struct dri2_drawable *pdraw, *pread;
135    __DRIdrawable *dri_draw = NULL, *dri_read = NULL;
136    struct glx_display *dpyPriv = psc->base.display;
137    struct dri2_display *pdp;
138 
139    pdraw = (struct dri2_drawable *) driFetchDrawable(context, draw);
140    pread = (struct dri2_drawable *) driFetchDrawable(context, read);
141 
142    driReleaseDrawables(&pcp->base);
143 
144    if (pdraw)
145       dri_draw = pdraw->driDrawable;
146    else if (draw != None)
147       return GLXBadDrawable;
148 
149    if (pread)
150       dri_read = pread->driDrawable;
151    else if (read != None)
152       return GLXBadDrawable;
153 
154    if (!(*psc->core->bindContext) (pcp->driContext, dri_draw, dri_read))
155       return GLXBadContext;
156 
157    /* If the server doesn't send invalidate events, we may miss a
158     * resize before the rendering starts.  Invalidate the buffers now
159     * so the driver will recheck before rendering starts. */
160    pdp = (struct dri2_display *) dpyPriv->dri2Display;
161    if (!pdp->invalidateAvailable && pdraw) {
162       dri2InvalidateBuffers(psc->base.dpy, pdraw->base.xDrawable);
163       if (pread != pdraw && pread)
164 	 dri2InvalidateBuffers(psc->base.dpy, pread->base.xDrawable);
165    }
166 
167    return Success;
168 }
169 
170 static void
dri2_unbind_context(struct glx_context * context,struct glx_context * new)171 dri2_unbind_context(struct glx_context *context, struct glx_context *new)
172 {
173    struct dri2_context *pcp = (struct dri2_context *) context;
174    struct dri2_screen *psc = (struct dri2_screen *) pcp->base.psc;
175 
176    (*psc->core->unbindContext) (pcp->driContext);
177 }
178 
179 static struct glx_context *
dri2_create_context(struct glx_screen * base,struct glx_config * config_base,struct glx_context * shareList,int renderType)180 dri2_create_context(struct glx_screen *base,
181 		    struct glx_config *config_base,
182 		    struct glx_context *shareList, int renderType)
183 {
184    struct dri2_context *pcp, *pcp_shared;
185    struct dri2_screen *psc = (struct dri2_screen *) base;
186    __GLXDRIconfigPrivate *config = (__GLXDRIconfigPrivate *) config_base;
187    __DRIcontext *shared = NULL;
188 
189    /* Check the renderType value */
190    if (!validate_renderType_against_config(config_base, renderType))
191        return NULL;
192 
193    if (shareList) {
194       /* If the shareList context is not a DRI2 context, we cannot possibly
195        * create a DRI2 context that shares it.
196        */
197       if (shareList->vtable->destroy != dri2_destroy_context) {
198 	 return NULL;
199       }
200 
201       pcp_shared = (struct dri2_context *) shareList;
202       shared = pcp_shared->driContext;
203    }
204 
205    pcp = calloc(1, sizeof *pcp);
206    if (pcp == NULL)
207       return NULL;
208 
209    if (!glx_context_init(&pcp->base, &psc->base, &config->base)) {
210       free(pcp);
211       return NULL;
212    }
213 
214    pcp->base.renderType = renderType;
215 
216    pcp->driContext =
217       (*psc->dri2->createNewContext) (psc->driScreen,
218                                       config->driConfig, shared, pcp);
219 
220    if (pcp->driContext == NULL) {
221       free(pcp);
222       return NULL;
223    }
224 
225    pcp->base.vtable = &dri2_context_vtable;
226 
227    return &pcp->base;
228 }
229 
230 static struct glx_context *
dri2_create_context_attribs(struct glx_screen * base,struct glx_config * config_base,struct glx_context * shareList,unsigned num_attribs,const uint32_t * attribs,unsigned * error)231 dri2_create_context_attribs(struct glx_screen *base,
232 			    struct glx_config *config_base,
233 			    struct glx_context *shareList,
234 			    unsigned num_attribs,
235 			    const uint32_t *attribs,
236 			    unsigned *error)
237 {
238    struct dri2_context *pcp = NULL;
239    struct dri2_context *pcp_shared = NULL;
240    struct dri2_screen *psc = (struct dri2_screen *) base;
241    __GLXDRIconfigPrivate *config = (__GLXDRIconfigPrivate *) config_base;
242    __DRIcontext *shared = NULL;
243 
244    uint32_t minor_ver;
245    uint32_t major_ver;
246    uint32_t renderType;
247    uint32_t flags;
248    unsigned api;
249    int reset;
250    int release;
251    uint32_t ctx_attribs[2 * 6];
252    unsigned num_ctx_attribs = 0;
253 
254    if (psc->dri2->base.version < 3) {
255       *error = __DRI_CTX_ERROR_NO_MEMORY;
256       goto error_exit;
257    }
258 
259    /* Remap the GLX tokens to DRI2 tokens.
260     */
261    if (!dri2_convert_glx_attribs(num_attribs, attribs,
262                                  &major_ver, &minor_ver, &renderType, &flags,
263                                  &api, &reset, &release, error))
264       goto error_exit;
265 
266    if (!dri2_check_no_error(flags, shareList, major_ver, error)) {
267       goto error_exit;
268    }
269 
270    /* Check the renderType value */
271    if (!validate_renderType_against_config(config_base, renderType))
272        goto error_exit;
273 
274    if (shareList) {
275       pcp_shared = (struct dri2_context *) shareList;
276       shared = pcp_shared->driContext;
277    }
278 
279    pcp = calloc(1, sizeof *pcp);
280    if (pcp == NULL) {
281       *error = __DRI_CTX_ERROR_NO_MEMORY;
282       goto error_exit;
283    }
284 
285    if (!glx_context_init(&pcp->base, &psc->base, config_base))
286       goto error_exit;
287 
288    ctx_attribs[num_ctx_attribs++] = __DRI_CTX_ATTRIB_MAJOR_VERSION;
289    ctx_attribs[num_ctx_attribs++] = major_ver;
290    ctx_attribs[num_ctx_attribs++] = __DRI_CTX_ATTRIB_MINOR_VERSION;
291    ctx_attribs[num_ctx_attribs++] = minor_ver;
292 
293    /* Only send a value when the non-default value is requested.  By doing
294     * this we don't have to check the driver's DRI2 version before sending the
295     * default value.
296     */
297    if (reset != __DRI_CTX_RESET_NO_NOTIFICATION) {
298       ctx_attribs[num_ctx_attribs++] = __DRI_CTX_ATTRIB_RESET_STRATEGY;
299       ctx_attribs[num_ctx_attribs++] = reset;
300    }
301 
302    if (release != __DRI_CTX_RELEASE_BEHAVIOR_FLUSH) {
303       ctx_attribs[num_ctx_attribs++] = __DRI_CTX_ATTRIB_RELEASE_BEHAVIOR;
304       ctx_attribs[num_ctx_attribs++] = release;
305    }
306 
307    if (flags != 0) {
308       ctx_attribs[num_ctx_attribs++] = __DRI_CTX_ATTRIB_FLAGS;
309 
310       /* The current __DRI_CTX_FLAG_* values are identical to the
311        * GLX_CONTEXT_*_BIT values.
312        */
313       ctx_attribs[num_ctx_attribs++] = flags;
314    }
315 
316    /* The renderType is retrieved from attribs, or set to default
317     *  of GLX_RGBA_TYPE.
318     */
319    pcp->base.renderType = renderType;
320 
321    if (flags & __DRI_CTX_FLAG_NO_ERROR)
322       pcp->base.noError = GL_TRUE;
323 
324    pcp->driContext =
325       (*psc->dri2->createContextAttribs) (psc->driScreen,
326 					  api,
327 					  config ? config->driConfig : NULL,
328 					  shared,
329 					  num_ctx_attribs / 2,
330 					  ctx_attribs,
331 					  error,
332 					  pcp);
333 
334    if (pcp->driContext == NULL)
335       goto error_exit;
336 
337    pcp->base.vtable = &dri2_context_vtable;
338 
339    return &pcp->base;
340 
341 error_exit:
342    free(pcp);
343 
344    return NULL;
345 }
346 
347 static void
dri2DestroyDrawable(__GLXDRIdrawable * base)348 dri2DestroyDrawable(__GLXDRIdrawable *base)
349 {
350    struct dri2_screen *psc = (struct dri2_screen *) base->psc;
351    struct dri2_drawable *pdraw = (struct dri2_drawable *) base;
352    struct glx_display *dpyPriv = psc->base.display;
353    struct dri2_display *pdp = (struct dri2_display *)dpyPriv->dri2Display;
354 
355    __glxHashDelete(pdp->dri2Hash, pdraw->base.xDrawable);
356    (*psc->core->destroyDrawable) (pdraw->driDrawable);
357 
358    /* If it's a GLX 1.3 drawables, we can destroy the DRI2 drawable
359     * now, as the application explicitly asked to destroy the GLX
360     * drawable.  Otherwise, for legacy drawables, we let the DRI2
361     * drawable linger on the server, since there's no good way of
362     * knowing when the application is done with it.  The server will
363     * destroy the DRI2 drawable when it destroys the X drawable or the
364     * client exits anyway. */
365    if (pdraw->base.xDrawable != pdraw->base.drawable)
366       DRI2DestroyDrawable(psc->base.dpy, pdraw->base.xDrawable);
367 
368    free(pdraw);
369 }
370 
371 static __GLXDRIdrawable *
dri2CreateDrawable(struct glx_screen * base,XID xDrawable,GLXDrawable drawable,struct glx_config * config_base)372 dri2CreateDrawable(struct glx_screen *base, XID xDrawable,
373 		   GLXDrawable drawable, struct glx_config *config_base)
374 {
375    struct dri2_drawable *pdraw;
376    struct dri2_screen *psc = (struct dri2_screen *) base;
377    __GLXDRIconfigPrivate *config = (__GLXDRIconfigPrivate *) config_base;
378    struct glx_display *dpyPriv;
379    struct dri2_display *pdp;
380    GLint vblank_mode = DRI_CONF_VBLANK_DEF_INTERVAL_1;
381 
382    dpyPriv = __glXInitialize(psc->base.dpy);
383    if (dpyPriv == NULL)
384       return NULL;
385 
386    pdraw = calloc(1, sizeof(*pdraw));
387    if (!pdraw)
388       return NULL;
389 
390    pdraw->base.destroyDrawable = dri2DestroyDrawable;
391    pdraw->base.xDrawable = xDrawable;
392    pdraw->base.drawable = drawable;
393    pdraw->base.psc = &psc->base;
394    pdraw->bufferCount = 0;
395    pdraw->swap_interval = 1; /* default may be overridden below */
396    pdraw->have_back = 0;
397 
398    if (psc->config)
399       psc->config->configQueryi(psc->driScreen,
400 				"vblank_mode", &vblank_mode);
401 
402    switch (vblank_mode) {
403    case DRI_CONF_VBLANK_NEVER:
404    case DRI_CONF_VBLANK_DEF_INTERVAL_0:
405       pdraw->swap_interval = 0;
406       break;
407    case DRI_CONF_VBLANK_DEF_INTERVAL_1:
408    case DRI_CONF_VBLANK_ALWAYS_SYNC:
409    default:
410       pdraw->swap_interval = 1;
411       break;
412    }
413 
414    DRI2CreateDrawable(psc->base.dpy, xDrawable);
415    pdp = (struct dri2_display *)dpyPriv->dri2Display;
416    /* Create a new drawable */
417    pdraw->driDrawable =
418       (*psc->dri2->createNewDrawable) (psc->driScreen,
419                                        config->driConfig, pdraw);
420 
421    if (!pdraw->driDrawable) {
422       DRI2DestroyDrawable(psc->base.dpy, xDrawable);
423       free(pdraw);
424       return NULL;
425    }
426 
427    if (__glxHashInsert(pdp->dri2Hash, xDrawable, pdraw)) {
428       (*psc->core->destroyDrawable) (pdraw->driDrawable);
429       DRI2DestroyDrawable(psc->base.dpy, xDrawable);
430       free(pdraw);
431       return None;
432    }
433 
434    /*
435     * Make sure server has the same swap interval we do for the new
436     * drawable.
437     */
438    if (psc->vtable.setSwapInterval)
439       psc->vtable.setSwapInterval(&pdraw->base, pdraw->swap_interval);
440 
441    return &pdraw->base;
442 }
443 
444 static int
dri2DrawableGetMSC(struct glx_screen * psc,__GLXDRIdrawable * pdraw,int64_t * ust,int64_t * msc,int64_t * sbc)445 dri2DrawableGetMSC(struct glx_screen *psc, __GLXDRIdrawable *pdraw,
446 		   int64_t *ust, int64_t *msc, int64_t *sbc)
447 {
448    xcb_connection_t *c = XGetXCBConnection(pdraw->psc->dpy);
449    xcb_dri2_get_msc_cookie_t get_msc_cookie;
450    xcb_dri2_get_msc_reply_t *get_msc_reply;
451 
452    get_msc_cookie = xcb_dri2_get_msc_unchecked(c, pdraw->xDrawable);
453    get_msc_reply = xcb_dri2_get_msc_reply(c, get_msc_cookie, NULL);
454 
455    if (!get_msc_reply)
456       return 0;
457 
458    *ust = merge_counter(get_msc_reply->ust_hi, get_msc_reply->ust_lo);
459    *msc = merge_counter(get_msc_reply->msc_hi, get_msc_reply->msc_lo);
460    *sbc = merge_counter(get_msc_reply->sbc_hi, get_msc_reply->sbc_lo);
461    free(get_msc_reply);
462 
463    return 1;
464 }
465 
466 static int
dri2WaitForMSC(__GLXDRIdrawable * pdraw,int64_t target_msc,int64_t divisor,int64_t remainder,int64_t * ust,int64_t * msc,int64_t * sbc)467 dri2WaitForMSC(__GLXDRIdrawable *pdraw, int64_t target_msc, int64_t divisor,
468 	       int64_t remainder, int64_t *ust, int64_t *msc, int64_t *sbc)
469 {
470    xcb_connection_t *c = XGetXCBConnection(pdraw->psc->dpy);
471    xcb_dri2_wait_msc_cookie_t wait_msc_cookie;
472    xcb_dri2_wait_msc_reply_t *wait_msc_reply;
473    uint32_t target_msc_hi, target_msc_lo;
474    uint32_t divisor_hi, divisor_lo;
475    uint32_t remainder_hi, remainder_lo;
476 
477    split_counter(target_msc, &target_msc_hi, &target_msc_lo);
478    split_counter(divisor, &divisor_hi, &divisor_lo);
479    split_counter(remainder, &remainder_hi, &remainder_lo);
480 
481    wait_msc_cookie = xcb_dri2_wait_msc_unchecked(c, pdraw->xDrawable,
482                                                  target_msc_hi, target_msc_lo,
483                                                  divisor_hi, divisor_lo,
484                                                  remainder_hi, remainder_lo);
485    wait_msc_reply = xcb_dri2_wait_msc_reply(c, wait_msc_cookie, NULL);
486 
487    if (!wait_msc_reply)
488       return 0;
489 
490    *ust = merge_counter(wait_msc_reply->ust_hi, wait_msc_reply->ust_lo);
491    *msc = merge_counter(wait_msc_reply->msc_hi, wait_msc_reply->msc_lo);
492    *sbc = merge_counter(wait_msc_reply->sbc_hi, wait_msc_reply->sbc_lo);
493    free(wait_msc_reply);
494 
495    return 1;
496 }
497 
498 static int
dri2WaitForSBC(__GLXDRIdrawable * pdraw,int64_t target_sbc,int64_t * ust,int64_t * msc,int64_t * sbc)499 dri2WaitForSBC(__GLXDRIdrawable *pdraw, int64_t target_sbc, int64_t *ust,
500 	       int64_t *msc, int64_t *sbc)
501 {
502    xcb_connection_t *c = XGetXCBConnection(pdraw->psc->dpy);
503    xcb_dri2_wait_sbc_cookie_t wait_sbc_cookie;
504    xcb_dri2_wait_sbc_reply_t *wait_sbc_reply;
505    uint32_t target_sbc_hi, target_sbc_lo;
506 
507    split_counter(target_sbc, &target_sbc_hi, &target_sbc_lo);
508 
509    wait_sbc_cookie = xcb_dri2_wait_sbc_unchecked(c, pdraw->xDrawable,
510                                                  target_sbc_hi, target_sbc_lo);
511    wait_sbc_reply = xcb_dri2_wait_sbc_reply(c, wait_sbc_cookie, NULL);
512 
513    if (!wait_sbc_reply)
514       return 0;
515 
516    *ust = merge_counter(wait_sbc_reply->ust_hi, wait_sbc_reply->ust_lo);
517    *msc = merge_counter(wait_sbc_reply->msc_hi, wait_sbc_reply->msc_lo);
518    *sbc = merge_counter(wait_sbc_reply->sbc_hi, wait_sbc_reply->sbc_lo);
519    free(wait_sbc_reply);
520 
521    return 1;
522 }
523 
524 static __DRIcontext *
dri2GetCurrentContext()525 dri2GetCurrentContext()
526 {
527    struct glx_context *gc = __glXGetCurrentContext();
528    struct dri2_context *dri2Ctx = (struct dri2_context *)gc;
529 
530    return (gc != &dummyContext) ? dri2Ctx->driContext : NULL;
531 }
532 
533 /**
534  * dri2Throttle - Request driver throttling
535  *
536  * This function uses the DRI2 throttle extension to give the
537  * driver the opportunity to throttle on flush front, copysubbuffer
538  * and swapbuffers.
539  */
540 static void
dri2Throttle(struct dri2_screen * psc,struct dri2_drawable * draw,enum __DRI2throttleReason reason)541 dri2Throttle(struct dri2_screen *psc,
542 	     struct dri2_drawable *draw,
543 	     enum __DRI2throttleReason reason)
544 {
545    if (psc->throttle) {
546       __DRIcontext *ctx = dri2GetCurrentContext();
547 
548       psc->throttle->throttle(ctx, draw->driDrawable, reason);
549    }
550 }
551 
552 /**
553  * Asks the driver to flush any queued work necessary for serializing with the
554  * X command stream, and optionally the slightly more strict requirement of
555  * glFlush() equivalence (which would require flushing even if nothing had
556  * been drawn to a window system framebuffer, for example).
557  */
558 static void
dri2Flush(struct dri2_screen * psc,__DRIcontext * ctx,struct dri2_drawable * draw,unsigned flags,enum __DRI2throttleReason throttle_reason)559 dri2Flush(struct dri2_screen *psc,
560           __DRIcontext *ctx,
561           struct dri2_drawable *draw,
562           unsigned flags,
563           enum __DRI2throttleReason throttle_reason)
564 {
565    if (ctx && psc->f && psc->f->base.version >= 4) {
566       psc->f->flush_with_flags(ctx, draw->driDrawable, flags, throttle_reason);
567    } else {
568       if (flags & __DRI2_FLUSH_CONTEXT)
569          glFlush();
570 
571       if (psc->f)
572          psc->f->flush(draw->driDrawable);
573 
574       dri2Throttle(psc, draw, throttle_reason);
575    }
576 }
577 
578 static void
__dri2CopySubBuffer(__GLXDRIdrawable * pdraw,int x,int y,int width,int height,enum __DRI2throttleReason reason,Bool flush)579 __dri2CopySubBuffer(__GLXDRIdrawable *pdraw, int x, int y,
580 		    int width, int height,
581 		    enum __DRI2throttleReason reason, Bool flush)
582 {
583    struct dri2_drawable *priv = (struct dri2_drawable *) pdraw;
584    struct dri2_screen *psc = (struct dri2_screen *) pdraw->psc;
585    XRectangle xrect;
586    XserverRegion region;
587    __DRIcontext *ctx = dri2GetCurrentContext();
588    unsigned flags;
589 
590    /* Check we have the right attachments */
591    if (!priv->have_back)
592       return;
593 
594    xrect.x = x;
595    xrect.y = priv->height - y - height;
596    xrect.width = width;
597    xrect.height = height;
598 
599    flags = __DRI2_FLUSH_DRAWABLE;
600    if (flush)
601       flags |= __DRI2_FLUSH_CONTEXT;
602    dri2Flush(psc, ctx, priv, flags, __DRI2_THROTTLE_COPYSUBBUFFER);
603 
604    region = XFixesCreateRegion(psc->base.dpy, &xrect, 1);
605    DRI2CopyRegion(psc->base.dpy, pdraw->xDrawable, region,
606                   DRI2BufferFrontLeft, DRI2BufferBackLeft);
607 
608    /* Refresh the fake front (if present) after we just damaged the real
609     * front.
610     */
611    if (priv->have_fake_front)
612       DRI2CopyRegion(psc->base.dpy, pdraw->xDrawable, region,
613 		     DRI2BufferFakeFrontLeft, DRI2BufferFrontLeft);
614 
615    XFixesDestroyRegion(psc->base.dpy, region);
616 }
617 
618 static void
dri2CopySubBuffer(__GLXDRIdrawable * pdraw,int x,int y,int width,int height,Bool flush)619 dri2CopySubBuffer(__GLXDRIdrawable *pdraw, int x, int y,
620 		  int width, int height, Bool flush)
621 {
622    __dri2CopySubBuffer(pdraw, x, y, width, height,
623 		       __DRI2_THROTTLE_COPYSUBBUFFER, flush);
624 }
625 
626 
627 static void
dri2_copy_drawable(struct dri2_drawable * priv,int dest,int src)628 dri2_copy_drawable(struct dri2_drawable *priv, int dest, int src)
629 {
630    XRectangle xrect;
631    XserverRegion region;
632    struct dri2_screen *psc = (struct dri2_screen *) priv->base.psc;
633 
634    xrect.x = 0;
635    xrect.y = 0;
636    xrect.width = priv->width;
637    xrect.height = priv->height;
638 
639    if (psc->f)
640       (*psc->f->flush) (priv->driDrawable);
641 
642    region = XFixesCreateRegion(psc->base.dpy, &xrect, 1);
643    DRI2CopyRegion(psc->base.dpy, priv->base.xDrawable, region, dest, src);
644    XFixesDestroyRegion(psc->base.dpy, region);
645 
646 }
647 
648 static void
dri2_wait_x(struct glx_context * gc)649 dri2_wait_x(struct glx_context *gc)
650 {
651    struct dri2_drawable *priv = (struct dri2_drawable *)
652       GetGLXDRIDrawable(gc->currentDpy, gc->currentDrawable);
653 
654    if (priv == NULL || !priv->have_fake_front)
655       return;
656 
657    dri2_copy_drawable(priv, DRI2BufferFakeFrontLeft, DRI2BufferFrontLeft);
658 }
659 
660 static void
dri2_wait_gl(struct glx_context * gc)661 dri2_wait_gl(struct glx_context *gc)
662 {
663    struct dri2_drawable *priv = (struct dri2_drawable *)
664       GetGLXDRIDrawable(gc->currentDpy, gc->currentDrawable);
665 
666    if (priv == NULL || !priv->have_fake_front)
667       return;
668 
669    dri2_copy_drawable(priv, DRI2BufferFrontLeft, DRI2BufferFakeFrontLeft);
670 }
671 
672 /**
673  * Called by the driver when it needs to update the real front buffer with the
674  * contents of its fake front buffer.
675  */
676 static void
dri2FlushFrontBuffer(__DRIdrawable * driDrawable,void * loaderPrivate)677 dri2FlushFrontBuffer(__DRIdrawable *driDrawable, void *loaderPrivate)
678 {
679    struct glx_display *priv;
680    struct dri2_display *pdp;
681    struct glx_context *gc;
682    struct dri2_drawable *pdraw = loaderPrivate;
683    struct dri2_screen *psc;
684 
685    if (!pdraw)
686       return;
687 
688    if (!pdraw->base.psc)
689       return;
690 
691    psc = (struct dri2_screen *) pdraw->base.psc;
692 
693    priv = __glXInitialize(psc->base.dpy);
694 
695    if (priv == NULL)
696        return;
697 
698    pdp = (struct dri2_display *) priv->dri2Display;
699    gc = __glXGetCurrentContext();
700 
701    dri2Throttle(psc, pdraw, __DRI2_THROTTLE_FLUSHFRONT);
702 
703    /* Old servers don't send invalidate events */
704    if (!pdp->invalidateAvailable)
705        dri2InvalidateBuffers(priv->dpy, pdraw->base.xDrawable);
706 
707    dri2_wait_gl(gc);
708 }
709 
710 
711 static void
dri2DestroyScreen(struct glx_screen * base)712 dri2DestroyScreen(struct glx_screen *base)
713 {
714    struct dri2_screen *psc = (struct dri2_screen *) base;
715 
716    /* Free the direct rendering per screen data */
717    (*psc->core->destroyScreen) (psc->driScreen);
718    driDestroyConfigs(psc->driver_configs);
719    free(psc->driverName);
720    close(psc->fd);
721    free(psc);
722 }
723 
724 /**
725  * Process list of buffer received from the server
726  *
727  * Processes the list of buffers received in a reply from the server to either
728  * \c DRI2GetBuffers or \c DRI2GetBuffersWithFormat.
729  */
730 static void
process_buffers(struct dri2_drawable * pdraw,DRI2Buffer * buffers,unsigned count)731 process_buffers(struct dri2_drawable * pdraw, DRI2Buffer * buffers,
732                 unsigned count)
733 {
734    int i;
735 
736    pdraw->bufferCount = count;
737    pdraw->have_fake_front = 0;
738    pdraw->have_back = 0;
739 
740    /* This assumes the DRI2 buffer attachment tokens matches the
741     * __DRIbuffer tokens. */
742    for (i = 0; i < count; i++) {
743       pdraw->buffers[i].attachment = buffers[i].attachment;
744       pdraw->buffers[i].name = buffers[i].name;
745       pdraw->buffers[i].pitch = buffers[i].pitch;
746       pdraw->buffers[i].cpp = buffers[i].cpp;
747       pdraw->buffers[i].flags = buffers[i].flags;
748       if (pdraw->buffers[i].attachment == __DRI_BUFFER_FAKE_FRONT_LEFT)
749          pdraw->have_fake_front = 1;
750       if (pdraw->buffers[i].attachment == __DRI_BUFFER_BACK_LEFT)
751          pdraw->have_back = 1;
752    }
753 
754 }
755 
dri2GetSwapEventType(Display * dpy,XID drawable)756 unsigned dri2GetSwapEventType(Display* dpy, XID drawable)
757 {
758       struct glx_display *glx_dpy = __glXInitialize(dpy);
759       __GLXDRIdrawable *pdraw;
760       pdraw = dri2GetGlxDrawableFromXDrawableId(dpy, drawable);
761       if (!pdraw || !(pdraw->eventMask & GLX_BUFFER_SWAP_COMPLETE_INTEL_MASK))
762          return 0;
763       return glx_dpy->codes->first_event + GLX_BufferSwapComplete;
764 }
765 
show_fps(struct dri2_drawable * draw)766 static void show_fps(struct dri2_drawable *draw)
767 {
768    const int interval =
769       ((struct dri2_screen *) draw->base.psc)->show_fps_interval;
770    struct timeval tv;
771    uint64_t current_time;
772 
773    gettimeofday(&tv, 0);
774    current_time = (uint64_t)tv.tv_sec*1000000 + (uint64_t)tv.tv_usec;
775 
776    draw->frames++;
777 
778    if (draw->previous_time + interval * 1000000 <= current_time) {
779       if (draw->previous_time) {
780          fprintf(stderr, "libGL: FPS = %.2f\n",
781                  ((uint64_t)draw->frames * 1000000) /
782                  (double)(current_time - draw->previous_time));
783       }
784       draw->frames = 0;
785       draw->previous_time = current_time;
786    }
787 }
788 
789 static int64_t
dri2XcbSwapBuffers(Display * dpy,__GLXDRIdrawable * pdraw,int64_t target_msc,int64_t divisor,int64_t remainder)790 dri2XcbSwapBuffers(Display *dpy,
791                   __GLXDRIdrawable *pdraw,
792                   int64_t target_msc,
793                   int64_t divisor,
794                   int64_t remainder)
795 {
796    xcb_dri2_swap_buffers_cookie_t swap_buffers_cookie;
797    xcb_dri2_swap_buffers_reply_t *swap_buffers_reply;
798    uint32_t target_msc_hi, target_msc_lo;
799    uint32_t divisor_hi, divisor_lo;
800    uint32_t remainder_hi, remainder_lo;
801    int64_t ret = 0;
802    xcb_connection_t *c = XGetXCBConnection(dpy);
803 
804    split_counter(target_msc, &target_msc_hi, &target_msc_lo);
805    split_counter(divisor, &divisor_hi, &divisor_lo);
806    split_counter(remainder, &remainder_hi, &remainder_lo);
807 
808    swap_buffers_cookie =
809       xcb_dri2_swap_buffers_unchecked(c, pdraw->xDrawable,
810                                       target_msc_hi, target_msc_lo,
811                                       divisor_hi, divisor_lo,
812                                       remainder_hi, remainder_lo);
813 
814    /* Immediately wait on the swapbuffers reply.  If we didn't, we'd have
815     * to do so some time before reusing a (non-pageflipped) backbuffer.
816     * Otherwise, the new rendering could get ahead of the X Server's
817     * dispatch of the swapbuffer and you'd display garbage.
818     *
819     * We use XSync() first to reap the invalidate events through the event
820     * filter, to ensure that the next drawing doesn't use an invalidated
821     * buffer.
822     */
823    XSync(dpy, False);
824 
825    swap_buffers_reply =
826       xcb_dri2_swap_buffers_reply(c, swap_buffers_cookie, NULL);
827    if (swap_buffers_reply) {
828       ret = merge_counter(swap_buffers_reply->swap_hi,
829                           swap_buffers_reply->swap_lo);
830       free(swap_buffers_reply);
831    }
832    return ret;
833 }
834 
835 static int64_t
dri2SwapBuffers(__GLXDRIdrawable * pdraw,int64_t target_msc,int64_t divisor,int64_t remainder,Bool flush)836 dri2SwapBuffers(__GLXDRIdrawable *pdraw, int64_t target_msc, int64_t divisor,
837 		int64_t remainder, Bool flush)
838 {
839     struct dri2_drawable *priv = (struct dri2_drawable *) pdraw;
840     struct glx_display *dpyPriv = __glXInitialize(priv->base.psc->dpy);
841     struct dri2_screen *psc = (struct dri2_screen *) priv->base.psc;
842     struct dri2_display *pdp =
843 	(struct dri2_display *)dpyPriv->dri2Display;
844     int64_t ret = 0;
845 
846     /* Check we have the right attachments */
847     if (!priv->have_back)
848 	return ret;
849 
850     /* Old servers can't handle swapbuffers */
851     if (!pdp->swapAvailable) {
852        __dri2CopySubBuffer(pdraw, 0, 0, priv->width, priv->height,
853 			   __DRI2_THROTTLE_SWAPBUFFER, flush);
854     } else {
855        __DRIcontext *ctx = dri2GetCurrentContext();
856        unsigned flags = __DRI2_FLUSH_DRAWABLE;
857        if (flush)
858           flags |= __DRI2_FLUSH_CONTEXT;
859        dri2Flush(psc, ctx, priv, flags, __DRI2_THROTTLE_SWAPBUFFER);
860 
861        ret = dri2XcbSwapBuffers(pdraw->psc->dpy, pdraw,
862                                 target_msc, divisor, remainder);
863     }
864 
865     if (psc->show_fps_interval) {
866        show_fps(priv);
867     }
868 
869     /* Old servers don't send invalidate events */
870     if (!pdp->invalidateAvailable)
871        dri2InvalidateBuffers(dpyPriv->dpy, pdraw->xDrawable);
872 
873     return ret;
874 }
875 
876 static __DRIbuffer *
dri2GetBuffers(__DRIdrawable * driDrawable,int * width,int * height,unsigned int * attachments,int count,int * out_count,void * loaderPrivate)877 dri2GetBuffers(__DRIdrawable * driDrawable,
878                int *width, int *height,
879                unsigned int *attachments, int count,
880                int *out_count, void *loaderPrivate)
881 {
882    struct dri2_drawable *pdraw = loaderPrivate;
883    DRI2Buffer *buffers;
884 
885    buffers = DRI2GetBuffers(pdraw->base.psc->dpy, pdraw->base.xDrawable,
886                             width, height, attachments, count, out_count);
887    if (buffers == NULL)
888       return NULL;
889 
890    pdraw->width = *width;
891    pdraw->height = *height;
892    process_buffers(pdraw, buffers, *out_count);
893 
894    free(buffers);
895 
896    return pdraw->buffers;
897 }
898 
899 static __DRIbuffer *
dri2GetBuffersWithFormat(__DRIdrawable * driDrawable,int * width,int * height,unsigned int * attachments,int count,int * out_count,void * loaderPrivate)900 dri2GetBuffersWithFormat(__DRIdrawable * driDrawable,
901                          int *width, int *height,
902                          unsigned int *attachments, int count,
903                          int *out_count, void *loaderPrivate)
904 {
905    struct dri2_drawable *pdraw = loaderPrivate;
906    DRI2Buffer *buffers;
907 
908    buffers = DRI2GetBuffersWithFormat(pdraw->base.psc->dpy,
909                                       pdraw->base.xDrawable,
910                                       width, height, attachments,
911                                       count, out_count);
912    if (buffers == NULL)
913       return NULL;
914 
915    pdraw->width = *width;
916    pdraw->height = *height;
917    process_buffers(pdraw, buffers, *out_count);
918 
919    free(buffers);
920 
921    return pdraw->buffers;
922 }
923 
924 static int
dri2SetSwapInterval(__GLXDRIdrawable * pdraw,int interval)925 dri2SetSwapInterval(__GLXDRIdrawable *pdraw, int interval)
926 {
927    xcb_connection_t *c = XGetXCBConnection(pdraw->psc->dpy);
928    struct dri2_drawable *priv =  (struct dri2_drawable *) pdraw;
929    GLint vblank_mode = DRI_CONF_VBLANK_DEF_INTERVAL_1;
930    struct dri2_screen *psc = (struct dri2_screen *) priv->base.psc;
931 
932    if (psc->config)
933       psc->config->configQueryi(psc->driScreen,
934 				"vblank_mode", &vblank_mode);
935 
936    switch (vblank_mode) {
937    case DRI_CONF_VBLANK_NEVER:
938       if (interval != 0)
939          return GLX_BAD_VALUE;
940       break;
941    case DRI_CONF_VBLANK_ALWAYS_SYNC:
942       if (interval <= 0)
943 	 return GLX_BAD_VALUE;
944       break;
945    default:
946       break;
947    }
948 
949    xcb_dri2_swap_interval(c, priv->base.xDrawable, interval);
950    priv->swap_interval = interval;
951 
952    return 0;
953 }
954 
955 static int
dri2GetSwapInterval(__GLXDRIdrawable * pdraw)956 dri2GetSwapInterval(__GLXDRIdrawable *pdraw)
957 {
958    struct dri2_drawable *priv =  (struct dri2_drawable *) pdraw;
959 
960   return priv->swap_interval;
961 }
962 
963 static void
driSetBackgroundContext(void * loaderPrivate)964 driSetBackgroundContext(void *loaderPrivate)
965 {
966    struct dri2_context *pcp = (struct dri2_context *) loaderPrivate;
967    __glXSetCurrentContext(&pcp->base);
968 }
969 
970 static GLboolean
driIsThreadSafe(void * loaderPrivate)971 driIsThreadSafe(void *loaderPrivate)
972 {
973    struct dri2_context *pcp = (struct dri2_context *) loaderPrivate;
974    /* Check Xlib is running in thread safe mode
975     *
976     * 'lock_fns' is the XLockDisplay function pointer of the X11 display 'dpy'.
977     * It wll be NULL if XInitThreads wasn't called.
978     */
979    return pcp->base.psc->dpy->lock_fns != NULL;
980 }
981 
982 static const __DRIdri2LoaderExtension dri2LoaderExtension = {
983    .base = { __DRI_DRI2_LOADER, 3 },
984 
985    .getBuffers              = dri2GetBuffers,
986    .flushFrontBuffer        = dri2FlushFrontBuffer,
987    .getBuffersWithFormat    = dri2GetBuffersWithFormat,
988 };
989 
990 static const __DRIdri2LoaderExtension dri2LoaderExtension_old = {
991    .base = { __DRI_DRI2_LOADER, 3 },
992 
993    .getBuffers              = dri2GetBuffers,
994    .flushFrontBuffer        = dri2FlushFrontBuffer,
995    .getBuffersWithFormat    = NULL,
996 };
997 
998 static const __DRIuseInvalidateExtension dri2UseInvalidate = {
999    .base = { __DRI_USE_INVALIDATE, 1 }
1000 };
1001 
1002 static const __DRIbackgroundCallableExtension driBackgroundCallable = {
1003    .base = { __DRI_BACKGROUND_CALLABLE, 2 },
1004 
1005    .setBackgroundContext    = driSetBackgroundContext,
1006    .isThreadSafe            = driIsThreadSafe,
1007 };
1008 
1009 _X_HIDDEN void
dri2InvalidateBuffers(Display * dpy,XID drawable)1010 dri2InvalidateBuffers(Display *dpy, XID drawable)
1011 {
1012    __GLXDRIdrawable *pdraw =
1013       dri2GetGlxDrawableFromXDrawableId(dpy, drawable);
1014    struct dri2_screen *psc;
1015    struct dri2_drawable *pdp = (struct dri2_drawable *) pdraw;
1016 
1017    if (!pdraw)
1018       return;
1019 
1020    psc = (struct dri2_screen *) pdraw->psc;
1021 
1022    if (psc->f && psc->f->base.version >= 3 && psc->f->invalidate)
1023        psc->f->invalidate(pdp->driDrawable);
1024 }
1025 
1026 static void
dri2_bind_tex_image(Display * dpy,GLXDrawable drawable,int buffer,const int * attrib_list)1027 dri2_bind_tex_image(Display * dpy,
1028 		    GLXDrawable drawable,
1029 		    int buffer, const int *attrib_list)
1030 {
1031    struct glx_context *gc = __glXGetCurrentContext();
1032    struct dri2_context *pcp = (struct dri2_context *) gc;
1033    __GLXDRIdrawable *base = GetGLXDRIDrawable(dpy, drawable);
1034    struct glx_display *dpyPriv = __glXInitialize(dpy);
1035    struct dri2_drawable *pdraw = (struct dri2_drawable *) base;
1036    struct dri2_display *pdp;
1037    struct dri2_screen *psc;
1038 
1039    if (dpyPriv == NULL)
1040        return;
1041 
1042    pdp = (struct dri2_display *) dpyPriv->dri2Display;
1043 
1044    if (pdraw != NULL) {
1045       psc = (struct dri2_screen *) base->psc;
1046 
1047       if (!pdp->invalidateAvailable && psc->f &&
1048            psc->f->base.version >= 3 && psc->f->invalidate)
1049 	 psc->f->invalidate(pdraw->driDrawable);
1050 
1051       if (psc->texBuffer->base.version >= 2 &&
1052 	  psc->texBuffer->setTexBuffer2 != NULL) {
1053 	 (*psc->texBuffer->setTexBuffer2) (pcp->driContext,
1054 					   pdraw->base.textureTarget,
1055 					   pdraw->base.textureFormat,
1056 					   pdraw->driDrawable);
1057       }
1058       else {
1059 	 (*psc->texBuffer->setTexBuffer) (pcp->driContext,
1060 					  pdraw->base.textureTarget,
1061 					  pdraw->driDrawable);
1062       }
1063    }
1064 }
1065 
1066 static void
dri2_release_tex_image(Display * dpy,GLXDrawable drawable,int buffer)1067 dri2_release_tex_image(Display * dpy, GLXDrawable drawable, int buffer)
1068 {
1069    struct glx_context *gc = __glXGetCurrentContext();
1070    struct dri2_context *pcp = (struct dri2_context *) gc;
1071    __GLXDRIdrawable *base = GetGLXDRIDrawable(dpy, drawable);
1072    struct glx_display *dpyPriv = __glXInitialize(dpy);
1073    struct dri2_drawable *pdraw = (struct dri2_drawable *) base;
1074    struct dri2_screen *psc;
1075 
1076    if (dpyPriv != NULL && pdraw != NULL) {
1077       psc = (struct dri2_screen *) base->psc;
1078 
1079       if (psc->texBuffer->base.version >= 3 &&
1080           psc->texBuffer->releaseTexBuffer != NULL) {
1081          (*psc->texBuffer->releaseTexBuffer) (pcp->driContext,
1082                                            pdraw->base.textureTarget,
1083                                            pdraw->driDrawable);
1084       }
1085    }
1086 }
1087 
1088 static const struct glx_context_vtable dri2_context_vtable = {
1089    .destroy             = dri2_destroy_context,
1090    .bind                = dri2_bind_context,
1091    .unbind              = dri2_unbind_context,
1092    .wait_gl             = dri2_wait_gl,
1093    .wait_x              = dri2_wait_x,
1094    .use_x_font          = DRI_glXUseXFont,
1095    .bind_tex_image      = dri2_bind_tex_image,
1096    .release_tex_image   = dri2_release_tex_image,
1097    .get_proc_address    = NULL,
1098    .interop_query_device_info = dri2_interop_query_device_info,
1099    .interop_export_object = dri2_interop_export_object
1100 };
1101 
1102 static void
dri2BindExtensions(struct dri2_screen * psc,struct glx_display * priv,const char * driverName)1103 dri2BindExtensions(struct dri2_screen *psc, struct glx_display * priv,
1104                    const char *driverName)
1105 {
1106    const struct dri2_display *const pdp = (struct dri2_display *)
1107       priv->dri2Display;
1108    const __DRIextension **extensions;
1109    int i;
1110 
1111    extensions = psc->core->getExtensions(psc->driScreen);
1112 
1113    __glXEnableDirectExtension(&psc->base, "GLX_EXT_swap_control");
1114    __glXEnableDirectExtension(&psc->base, "GLX_SGI_swap_control");
1115    __glXEnableDirectExtension(&psc->base, "GLX_MESA_swap_control");
1116    __glXEnableDirectExtension(&psc->base, "GLX_SGI_make_current_read");
1117 
1118    /*
1119     * GLX_INTEL_swap_event is broken on the server side, where it's
1120     * currently unconditionally enabled. This completely breaks
1121     * systems running on drivers which don't support that extension.
1122     * There's no way to test for its presence on this side, so instead
1123     * of disabling it unconditionally, just disable it for drivers
1124     * which are known to not support it, or for DDX drivers supporting
1125     * only an older (pre-ScheduleSwap) version of DRI2.
1126     *
1127     * This is a hack which is required until:
1128     * http://lists.x.org/archives/xorg-devel/2013-February/035449.html
1129     * is merged and updated xserver makes it's way into distros:
1130     */
1131    if (pdp->swapAvailable && strcmp(driverName, "vmwgfx") != 0) {
1132       __glXEnableDirectExtension(&psc->base, "GLX_INTEL_swap_event");
1133    }
1134 
1135    if (psc->dri2->base.version >= 3) {
1136       const unsigned mask = psc->dri2->getAPIMask(psc->driScreen);
1137 
1138       __glXEnableDirectExtension(&psc->base, "GLX_ARB_create_context");
1139       __glXEnableDirectExtension(&psc->base, "GLX_ARB_create_context_profile");
1140 
1141       if ((mask & ((1 << __DRI_API_GLES) |
1142                    (1 << __DRI_API_GLES2) |
1143                    (1 << __DRI_API_GLES3))) != 0) {
1144          __glXEnableDirectExtension(&psc->base,
1145                                     "GLX_EXT_create_context_es_profile");
1146          __glXEnableDirectExtension(&psc->base,
1147                                     "GLX_EXT_create_context_es2_profile");
1148       }
1149    }
1150 
1151    for (i = 0; extensions[i]; i++) {
1152       if ((strcmp(extensions[i]->name, __DRI_TEX_BUFFER) == 0)) {
1153 	 psc->texBuffer = (__DRItexBufferExtension *) extensions[i];
1154 	 __glXEnableDirectExtension(&psc->base, "GLX_EXT_texture_from_pixmap");
1155       }
1156 
1157       if ((strcmp(extensions[i]->name, __DRI2_FLUSH) == 0)) {
1158 	 psc->f = (__DRI2flushExtension *) extensions[i];
1159 	 /* internal driver extension, no GL extension exposed */
1160       }
1161 
1162       if ((strcmp(extensions[i]->name, __DRI2_CONFIG_QUERY) == 0))
1163 	 psc->config = (__DRI2configQueryExtension *) extensions[i];
1164 
1165       if (((strcmp(extensions[i]->name, __DRI2_THROTTLE) == 0)))
1166 	 psc->throttle = (__DRI2throttleExtension *) extensions[i];
1167 
1168       /* DRI2 version 3 is also required because
1169        * GLX_ARB_create_context_robustness requires GLX_ARB_create_context.
1170        */
1171       if (psc->dri2->base.version >= 3
1172           && strcmp(extensions[i]->name, __DRI2_ROBUSTNESS) == 0)
1173          __glXEnableDirectExtension(&psc->base,
1174                                     "GLX_ARB_create_context_robustness");
1175 
1176       /* DRI2 version 3 is also required because
1177        * GLX_ARB_create_context_no_error requires GLX_ARB_create_context.
1178        */
1179       if (psc->dri2->base.version >= 3
1180           && strcmp(extensions[i]->name, __DRI2_NO_ERROR) == 0)
1181          __glXEnableDirectExtension(&psc->base,
1182                                     "GLX_ARB_create_context_no_error");
1183 
1184       /* DRI2 version 3 is also required because GLX_MESA_query_renderer
1185        * requires GLX_ARB_create_context_profile.
1186        */
1187       if (psc->dri2->base.version >= 3
1188           && strcmp(extensions[i]->name, __DRI2_RENDERER_QUERY) == 0) {
1189          psc->rendererQuery = (__DRI2rendererQueryExtension *) extensions[i];
1190          __glXEnableDirectExtension(&psc->base, "GLX_MESA_query_renderer");
1191       }
1192 
1193       if (strcmp(extensions[i]->name, __DRI2_INTEROP) == 0)
1194 	 psc->interop = (__DRI2interopExtension*)extensions[i];
1195 
1196       /* DRI2 version 3 is also required because
1197        * GLX_ARB_control_flush_control requires GLX_ARB_create_context.
1198        */
1199       if (psc->dri2->base.version >= 3
1200           && strcmp(extensions[i]->name, __DRI2_FLUSH_CONTROL) == 0)
1201          __glXEnableDirectExtension(&psc->base,
1202                                     "GLX_ARB_context_flush_control");
1203    }
1204 }
1205 
1206 static char *
dri2_get_driver_name(struct glx_screen * glx_screen)1207 dri2_get_driver_name(struct glx_screen *glx_screen)
1208 {
1209     struct dri2_screen *psc = (struct dri2_screen *)glx_screen;
1210 
1211     return psc->driverName;
1212 }
1213 
1214 static const struct glx_screen_vtable dri2_screen_vtable = {
1215    .create_context         = dri2_create_context,
1216    .create_context_attribs = dri2_create_context_attribs,
1217    .query_renderer_integer = dri2_query_renderer_integer,
1218    .query_renderer_string  = dri2_query_renderer_string,
1219    .get_driver_name        = dri2_get_driver_name,
1220 };
1221 
1222 static struct glx_screen *
dri2CreateScreen(int screen,struct glx_display * priv)1223 dri2CreateScreen(int screen, struct glx_display * priv)
1224 {
1225    const __DRIconfig **driver_configs;
1226    const __DRIextension **extensions;
1227    const struct dri2_display *const pdp = (struct dri2_display *)
1228       priv->dri2Display;
1229    struct dri2_screen *psc;
1230    __GLXDRIscreen *psp;
1231    struct glx_config *configs = NULL, *visuals = NULL;
1232    char *driverName = NULL, *loader_driverName, *deviceName, *tmp;
1233    drm_magic_t magic;
1234    int i;
1235    unsigned char disable;
1236 
1237    psc = calloc(1, sizeof *psc);
1238    if (psc == NULL)
1239       return NULL;
1240 
1241    psc->fd = -1;
1242 
1243    if (!glx_screen_init(&psc->base, screen, priv)) {
1244       free(psc);
1245       return NULL;
1246    }
1247 
1248    if (!DRI2Connect(priv->dpy, RootWindow(priv->dpy, screen),
1249 		    &driverName, &deviceName)) {
1250       glx_screen_cleanup(&psc->base);
1251       free(psc);
1252       InfoMessageF("screen %d does not appear to be DRI2 capable\n", screen);
1253       return NULL;
1254    }
1255 
1256    psc->fd = loader_open_device(deviceName);
1257    if (psc->fd < 0) {
1258       ErrorMessageF("failed to open %s: %s\n", deviceName, strerror(errno));
1259       goto handle_error;
1260    }
1261 
1262    if (drmGetMagic(psc->fd, &magic)) {
1263       ErrorMessageF("failed to get magic\n");
1264       goto handle_error;
1265    }
1266 
1267    if (!DRI2Authenticate(priv->dpy, RootWindow(priv->dpy, screen), magic)) {
1268       ErrorMessageF("failed to authenticate magic %d\n", magic);
1269       goto handle_error;
1270    }
1271 
1272    /* If Mesa knows about the appropriate driver for this fd, then trust it.
1273     * Otherwise, default to the server's value.
1274     */
1275    loader_driverName = loader_get_driver_for_fd(psc->fd);
1276    if (loader_driverName) {
1277       free(driverName);
1278       driverName = loader_driverName;
1279    }
1280    psc->driverName = driverName;
1281 
1282    extensions = driOpenDriver(driverName, &psc->driver);
1283    if (extensions == NULL)
1284       goto handle_error;
1285 
1286    for (i = 0; extensions[i]; i++) {
1287       if (strcmp(extensions[i]->name, __DRI_CORE) == 0)
1288 	 psc->core = (__DRIcoreExtension *) extensions[i];
1289       if (strcmp(extensions[i]->name, __DRI_DRI2) == 0)
1290 	 psc->dri2 = (__DRIdri2Extension *) extensions[i];
1291    }
1292 
1293    if (psc->core == NULL || psc->dri2 == NULL) {
1294       ErrorMessageF("core dri or dri2 extension not found\n");
1295       goto handle_error;
1296    }
1297 
1298    if (psc->dri2->base.version >= 4) {
1299       psc->driScreen =
1300          psc->dri2->createNewScreen2(screen, psc->fd,
1301                                      (const __DRIextension **)
1302                                      &pdp->loader_extensions[0],
1303                                      extensions,
1304                                      &driver_configs, psc);
1305    } else {
1306       psc->driScreen =
1307          psc->dri2->createNewScreen(screen, psc->fd,
1308                                     (const __DRIextension **)
1309                                     &pdp->loader_extensions[0],
1310                                     &driver_configs, psc);
1311    }
1312 
1313    if (psc->driScreen == NULL) {
1314       ErrorMessageF("failed to create dri screen\n");
1315       goto handle_error;
1316    }
1317 
1318    dri2BindExtensions(psc, priv, driverName);
1319 
1320    configs = driConvertConfigs(psc->core, psc->base.configs, driver_configs);
1321    visuals = driConvertConfigs(psc->core, psc->base.visuals, driver_configs);
1322 
1323    if (!configs || !visuals) {
1324        ErrorMessageF("No matching fbConfigs or visuals found\n");
1325        goto handle_error;
1326    }
1327 
1328    glx_config_destroy_list(psc->base.configs);
1329    psc->base.configs = configs;
1330    glx_config_destroy_list(psc->base.visuals);
1331    psc->base.visuals = visuals;
1332 
1333    psc->driver_configs = driver_configs;
1334 
1335    psc->base.vtable = &dri2_screen_vtable;
1336    psp = &psc->vtable;
1337    psc->base.driScreen = psp;
1338    psp->destroyScreen = dri2DestroyScreen;
1339    psp->createDrawable = dri2CreateDrawable;
1340    psp->swapBuffers = dri2SwapBuffers;
1341    psp->getDrawableMSC = NULL;
1342    psp->waitForMSC = NULL;
1343    psp->waitForSBC = NULL;
1344    psp->setSwapInterval = NULL;
1345    psp->getSwapInterval = NULL;
1346    psp->getBufferAge = NULL;
1347 
1348    if (pdp->driMinor >= 2) {
1349       psp->getDrawableMSC = dri2DrawableGetMSC;
1350       psp->waitForMSC = dri2WaitForMSC;
1351       psp->waitForSBC = dri2WaitForSBC;
1352       psp->setSwapInterval = dri2SetSwapInterval;
1353       psp->getSwapInterval = dri2GetSwapInterval;
1354       if (psc->config->configQueryb(psc->driScreen,
1355                                     "glx_disable_oml_sync_control",
1356                                     &disable) || !disable)
1357          __glXEnableDirectExtension(&psc->base, "GLX_OML_sync_control");
1358    }
1359 
1360    if (psc->config->configQueryb(psc->driScreen,
1361                                  "glx_disable_sgi_video_sync",
1362                                  &disable) || !disable)
1363       __glXEnableDirectExtension(&psc->base, "GLX_SGI_video_sync");
1364 
1365    if (psc->config->base.version > 1 &&
1366           psc->config->configQuerys(psc->driScreen, "glx_extension_override",
1367                                     &tmp) == 0)
1368       __glXParseExtensionOverride(&psc->base, tmp);
1369 
1370    if (psc->config->base.version > 1 &&
1371           psc->config->configQuerys(psc->driScreen,
1372                                     "indirect_gl_extension_override",
1373                                     &tmp) == 0)
1374       __IndirectGlParseExtensionOverride(&psc->base, tmp);
1375 
1376    /* DRI2 supports SubBuffer through DRI2CopyRegion, so it's always
1377     * available.*/
1378    psp->copySubBuffer = dri2CopySubBuffer;
1379    __glXEnableDirectExtension(&psc->base, "GLX_MESA_copy_sub_buffer");
1380 
1381    free(deviceName);
1382 
1383    tmp = getenv("LIBGL_SHOW_FPS");
1384    psc->show_fps_interval = (tmp) ? atoi(tmp) : 0;
1385    if (psc->show_fps_interval < 0)
1386       psc->show_fps_interval = 0;
1387 
1388    InfoMessageF("Using DRI2 for screen %d\n", screen);
1389 
1390    return &psc->base;
1391 
1392 handle_error:
1393    CriticalErrorMessageF("failed to load driver: %s\n", driverName);
1394 
1395    if (configs)
1396        glx_config_destroy_list(configs);
1397    if (visuals)
1398        glx_config_destroy_list(visuals);
1399    if (psc->driScreen)
1400        psc->core->destroyScreen(psc->driScreen);
1401    psc->driScreen = NULL;
1402    if (psc->fd >= 0)
1403       close(psc->fd);
1404    if (psc->driver)
1405       dlclose(psc->driver);
1406 
1407    free(deviceName);
1408    glx_screen_cleanup(&psc->base);
1409    free(psc);
1410 
1411    return NULL;
1412 }
1413 
1414 /* Called from __glXFreeDisplayPrivate.
1415  */
1416 static void
dri2DestroyDisplay(__GLXDRIdisplay * dpy)1417 dri2DestroyDisplay(__GLXDRIdisplay * dpy)
1418 {
1419    struct dri2_display *pdp = (struct dri2_display *) dpy;
1420 
1421    __glxHashDestroy(pdp->dri2Hash);
1422    free(dpy);
1423 }
1424 
1425 _X_HIDDEN __GLXDRIdrawable *
dri2GetGlxDrawableFromXDrawableId(Display * dpy,XID id)1426 dri2GetGlxDrawableFromXDrawableId(Display *dpy, XID id)
1427 {
1428    struct glx_display *d = __glXInitialize(dpy);
1429    struct dri2_display *pdp = (struct dri2_display *) d->dri2Display;
1430    __GLXDRIdrawable *pdraw;
1431 
1432    if (__glxHashLookup(pdp->dri2Hash, id, (void *) &pdraw) == 0)
1433       return pdraw;
1434 
1435    return NULL;
1436 }
1437 
1438 /*
1439  * Allocate, initialize and return a __DRIdisplayPrivate object.
1440  * This is called from __glXInitialize() when we are given a new
1441  * display pointer.
1442  */
1443 _X_HIDDEN __GLXDRIdisplay *
dri2CreateDisplay(Display * dpy)1444 dri2CreateDisplay(Display * dpy)
1445 {
1446    struct dri2_display *pdp;
1447    int eventBase, errorBase, i;
1448 
1449    if (!DRI2QueryExtension(dpy, &eventBase, &errorBase))
1450       return NULL;
1451 
1452    pdp = malloc(sizeof *pdp);
1453    if (pdp == NULL)
1454       return NULL;
1455 
1456    if (!DRI2QueryVersion(dpy, &pdp->driMajor, &pdp->driMinor)) {
1457       free(pdp);
1458       return NULL;
1459    }
1460 
1461    pdp->driPatch = 0;
1462    pdp->swapAvailable = (pdp->driMinor >= 2);
1463    pdp->invalidateAvailable = (pdp->driMinor >= 3);
1464 
1465    pdp->base.destroyDisplay = dri2DestroyDisplay;
1466    pdp->base.createScreen = dri2CreateScreen;
1467 
1468    i = 0;
1469    if (pdp->driMinor < 1)
1470       pdp->loader_extensions[i++] = &dri2LoaderExtension_old.base;
1471    else
1472       pdp->loader_extensions[i++] = &dri2LoaderExtension.base;
1473 
1474    pdp->loader_extensions[i++] = &dri2UseInvalidate.base;
1475 
1476    pdp->loader_extensions[i++] = &driBackgroundCallable.base;
1477 
1478    pdp->loader_extensions[i++] = NULL;
1479 
1480    pdp->dri2Hash = __glxHashCreate();
1481    if (pdp->dri2Hash == NULL) {
1482       free(pdp);
1483       return NULL;
1484    }
1485 
1486    return &pdp->base;
1487 }
1488 
1489 #endif /* GLX_DIRECT_RENDERING */
1490