ffaa9f92bb6bc1ac8a42cc7bed6d2e43917318b6
[profile/ivi/mesa.git] / src / mesa / drivers / dri / common / dri_util.c
1 /**
2  * \file dri_util.c
3  * DRI utility functions.
4  *
5  * This module acts as glue between GLX and the actual hardware driver.  A DRI
6  * driver doesn't really \e have to use any of this - it's optional.  But, some
7  * useful stuff is done here that otherwise would have to be duplicated in most
8  * drivers.
9  * 
10  * Basically, these utility functions take care of some of the dirty details of
11  * screen initialization, context creation, context binding, DRM setup, etc.
12  *
13  * These functions are compiled into each DRI driver so libGL.so knows nothing
14  * about them.
15  */
16
17
18 #include <assert.h>
19 #include <stdarg.h>
20 #include <unistd.h>
21 #include <sys/mman.h>
22 #include <stdio.h>
23
24 #ifndef MAP_FAILED
25 #define MAP_FAILED ((void *)-1)
26 #endif
27
28 #include "main/imports.h"
29 #define None 0
30
31 #include "dri_util.h"
32 #include "drm_sarea.h"
33 #include "utils.h"
34 #include "xmlpool.h"
35 #include "../glsl/glsl_parser_extras.h"
36
37 PUBLIC const char __dri2ConfigOptions[] =
38    DRI_CONF_BEGIN
39       DRI_CONF_SECTION_PERFORMANCE
40          DRI_CONF_VBLANK_MODE(DRI_CONF_VBLANK_DEF_INTERVAL_1)
41       DRI_CONF_SECTION_END
42    DRI_CONF_END;
43
44 static const uint __dri2NConfigOptions = 1;
45
46 #ifndef GLX_OML_sync_control
47 typedef GLboolean ( * PFNGLXGETMSCRATEOMLPROC) (__DRIdrawable *drawable, int32_t *numerator, int32_t *denominator);
48 #endif
49
50 static void dri_get_drawable(__DRIdrawable *pdp);
51 static void dri_put_drawable(__DRIdrawable *pdp);
52
53 /**
54  * This is just a token extension used to signal that the driver
55  * supports setting a read drawable.
56  */
57 const __DRIextension driReadDrawableExtension = {
58     __DRI_READ_DRAWABLE, __DRI_READ_DRAWABLE_VERSION
59 };
60
61 GLint
62 driIntersectArea( drm_clip_rect_t rect1, drm_clip_rect_t rect2 )
63 {
64    if (rect2.x1 > rect1.x1) rect1.x1 = rect2.x1;
65    if (rect2.x2 < rect1.x2) rect1.x2 = rect2.x2;
66    if (rect2.y1 > rect1.y1) rect1.y1 = rect2.y1;
67    if (rect2.y2 < rect1.y2) rect1.y2 = rect2.y2;
68
69    if (rect1.x1 > rect1.x2 || rect1.y1 > rect1.y2) return 0;
70
71    return (rect1.x2 - rect1.x1) * (rect1.y2 - rect1.y1);
72 }
73
74 /*****************************************************************/
75 /** \name Context (un)binding functions                          */
76 /*****************************************************************/
77 /*@{*/
78
79 /**
80  * Unbind context.
81  * 
82  * \param scrn the screen.
83  * \param gc context.
84  *
85  * \return \c GL_TRUE on success, or \c GL_FALSE on failure.
86  * 
87  * \internal
88  * This function calls __DriverAPIRec::UnbindContext, and then decrements
89  * __DRIdrawableRec::refcount which must be non-zero for a successful
90  * return.
91  * 
92  * While casting the opaque private pointers associated with the parameters
93  * into their respective real types it also assures they are not \c NULL. 
94  */
95 static int driUnbindContext(__DRIcontext *pcp)
96 {
97     __DRIscreen *psp;
98     __DRIdrawable *pdp;
99     __DRIdrawable *prp;
100
101     /*
102     ** Assume error checking is done properly in glXMakeCurrent before
103     ** calling driUnbindContext.
104     */
105
106     if (pcp == NULL)
107         return GL_FALSE;
108
109     psp = pcp->driScreenPriv;
110     pdp = pcp->driDrawablePriv;
111     prp = pcp->driReadablePriv;
112
113     /* already unbound */
114     if (!pdp && !prp)
115       return GL_TRUE;
116     /* Let driver unbind drawable from context */
117     (*psp->DriverAPI.UnbindContext)(pcp);
118
119     assert(pdp);
120     if (pdp->refcount == 0) {
121         /* ERROR!!! */
122         return GL_FALSE;
123     }
124
125     dri_put_drawable(pdp);
126
127     if (prp != pdp) {
128         if (prp->refcount == 0) {
129             /* ERROR!!! */
130             return GL_FALSE;
131         }
132
133         dri_put_drawable(prp);
134     }
135
136
137     /* XXX this is disabled so that if we call SwapBuffers on an unbound
138      * window we can determine the last context bound to the window and
139      * use that context's lock. (BrianP, 2-Dec-2000)
140      */
141     pcp->driDrawablePriv = pcp->driReadablePriv = NULL;
142
143     return GL_TRUE;
144 }
145
146 /**
147  * This function takes both a read buffer and a draw buffer.  This is needed
148  * for \c glXMakeCurrentReadSGI or GLX 1.3's \c glXMakeContextCurrent
149  * function.
150  */
151 static int driBindContext(__DRIcontext *pcp,
152                           __DRIdrawable *pdp,
153                           __DRIdrawable *prp)
154 {
155     __DRIscreen *psp = NULL;
156
157     /*
158     ** Assume error checking is done properly in glXMakeCurrent before
159     ** calling driUnbindContext.
160     */
161
162     if (!pcp)
163         return GL_FALSE;
164
165     /* Bind the drawable to the context */
166     psp = pcp->driScreenPriv;
167     pcp->driDrawablePriv = pdp;
168     pcp->driReadablePriv = prp;
169     if (pdp) {
170         pdp->driContextPriv = pcp;
171         dri_get_drawable(pdp);
172     }
173     if (prp && pdp != prp) {
174         dri_get_drawable(prp);
175     }
176
177     /*
178     ** Now that we have a context associated with this drawable, we can
179     ** initialize the drawable information if has not been done before.
180     */
181
182     if (!psp->dri2.enabled) {
183         if (pdp && !pdp->pStamp) {
184             DRM_SPINLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID);
185             __driUtilUpdateDrawableInfo(pdp);
186             DRM_SPINUNLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID);
187         }
188         if (prp && pdp != prp && !prp->pStamp) {
189             DRM_SPINLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID);
190             __driUtilUpdateDrawableInfo(prp);
191             DRM_SPINUNLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID);
192         }
193     }
194
195     /* Call device-specific MakeCurrent */
196     return (*psp->DriverAPI.MakeCurrent)(pcp, pdp, prp);
197 }
198
199 /*@}*/
200
201
202 /*****************************************************************/
203 /** \name Drawable handling functions                            */
204 /*****************************************************************/
205 /*@{*/
206
207 /**
208  * Update private drawable information.
209  *
210  * \param pdp pointer to the private drawable information to update.
211  * 
212  * This function basically updates the __DRIdrawable struct's
213  * cliprect information by calling \c __DRIinterfaceMethods::getDrawableInfo.
214  * This is usually called by the DRI_VALIDATE_DRAWABLE_INFO macro which
215  * compares the __DRIdrwablePrivate pStamp and lastStamp values.  If
216  * the values are different that means we have to update the clipping
217  * info.
218  */
219 void
220 __driUtilUpdateDrawableInfo(__DRIdrawable *pdp)
221 {
222     __DRIscreen *psp = pdp->driScreenPriv;
223     __DRIcontext *pcp = pdp->driContextPriv;
224     
225     if (!pcp 
226         || ((pdp != pcp->driDrawablePriv) && (pdp != pcp->driReadablePriv))) {
227         /* ERROR!!! 
228          * ...but we must ignore it. There can be many contexts bound to a
229          * drawable.
230          */
231     }
232
233     if (pdp->pClipRects) {
234         free(pdp->pClipRects); 
235         pdp->pClipRects = NULL;
236     }
237
238     if (pdp->pBackClipRects) {
239         free(pdp->pBackClipRects); 
240         pdp->pBackClipRects = NULL;
241     }
242
243     DRM_SPINUNLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID);
244
245     if (! (*psp->getDrawableInfo->getDrawableInfo)(pdp,
246                           &pdp->index, &pdp->lastStamp,
247                           &pdp->x, &pdp->y, &pdp->w, &pdp->h,
248                           &pdp->numClipRects, &pdp->pClipRects,
249                           &pdp->backX,
250                           &pdp->backY,
251                           &pdp->numBackClipRects,
252                           &pdp->pBackClipRects,
253                           pdp->loaderPrivate)) {
254         /* Error -- eg the window may have been destroyed.  Keep going
255          * with no cliprects.
256          */
257         pdp->pStamp = &pdp->lastStamp; /* prevent endless loop */
258         pdp->numClipRects = 0;
259         pdp->pClipRects = NULL;
260         pdp->numBackClipRects = 0;
261         pdp->pBackClipRects = NULL;
262     }
263     else
264        pdp->pStamp = &(psp->pSAREA->drawableTable[pdp->index].stamp);
265
266     DRM_SPINLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID);
267 }
268
269 /*@}*/
270
271 /*****************************************************************/
272 /** \name GLX callbacks                                          */
273 /*****************************************************************/
274 /*@{*/
275
276 static void driReportDamage(__DRIdrawable *pdp,
277                             struct drm_clip_rect *pClipRects, int numClipRects)
278 {
279     __DRIscreen *psp = pdp->driScreenPriv;
280
281     /* Check that we actually have the new damage report method */
282     if (psp->damage) {
283         /* Report the damage.  Currently, all our drivers draw
284          * directly to the front buffer, so we report the damage there
285          * rather than to the backing storein (if any).
286          */
287         (*psp->damage->reportDamage)(pdp,
288                                      pdp->x, pdp->y,
289                                      pClipRects, numClipRects,
290                                      GL_TRUE, pdp->loaderPrivate);
291     }
292 }
293
294
295 /**
296  * Swap buffers.
297  *
298  * \param drawablePrivate opaque pointer to the per-drawable private info.
299  * 
300  * \internal
301  * This function calls __DRIdrawable::swapBuffers.
302  * 
303  * Is called directly from glXSwapBuffers().
304  */
305 static void driSwapBuffers(__DRIdrawable *dPriv)
306 {
307     __DRIscreen *psp = dPriv->driScreenPriv;
308     drm_clip_rect_t *rects;
309     int i;
310
311     psp->DriverAPI.SwapBuffers(dPriv);
312
313     if (!dPriv->numClipRects)
314         return;
315
316     rects = malloc(sizeof(*rects) * dPriv->numClipRects);
317
318     if (!rects)
319         return;
320
321     for (i = 0; i < dPriv->numClipRects; i++) {
322         rects[i].x1 = dPriv->pClipRects[i].x1 - dPriv->x;
323         rects[i].y1 = dPriv->pClipRects[i].y1 - dPriv->y;
324         rects[i].x2 = dPriv->pClipRects[i].x2 - dPriv->x;
325         rects[i].y2 = dPriv->pClipRects[i].y2 - dPriv->y;
326     }
327
328     driReportDamage(dPriv, rects, dPriv->numClipRects);
329     free(rects);
330 }
331
332 static int driDrawableGetMSC( __DRIscreen *sPriv, __DRIdrawable *dPriv,
333                               int64_t *msc )
334 {
335     return sPriv->DriverAPI.GetDrawableMSC(sPriv, dPriv, msc);
336 }
337
338
339 static int driWaitForMSC(__DRIdrawable *dPriv, int64_t target_msc,
340                          int64_t divisor, int64_t remainder,
341                          int64_t * msc, int64_t * sbc)
342 {
343     __DRIswapInfo  sInfo;
344     int  status;
345
346     status = dPriv->driScreenPriv->DriverAPI.WaitForMSC( dPriv, target_msc,
347                                                          divisor, remainder,
348                                                          msc );
349
350     /* GetSwapInfo() may not be provided by the driver if GLX_SGI_video_sync
351      * is supported but GLX_OML_sync_control is not.  Therefore, don't return
352      * an error value if GetSwapInfo() is not implemented.
353     */
354     if ( status == 0
355          && dPriv->driScreenPriv->DriverAPI.GetSwapInfo ) {
356         status = dPriv->driScreenPriv->DriverAPI.GetSwapInfo( dPriv, & sInfo );
357         *sbc = sInfo.swap_count;
358     }
359
360     return status;
361 }
362
363
364 const __DRImediaStreamCounterExtension driMediaStreamCounterExtension = {
365     { __DRI_MEDIA_STREAM_COUNTER, __DRI_MEDIA_STREAM_COUNTER_VERSION },
366     driWaitForMSC,
367     driDrawableGetMSC,
368 };
369
370
371 static void driCopySubBuffer(__DRIdrawable *dPriv,
372                               int x, int y, int w, int h)
373 {
374     drm_clip_rect_t rect;
375
376     rect.x1 = x;
377     rect.y1 = dPriv->h - y - h;
378     rect.x2 = x + w;
379     rect.y2 = rect.y1 + h;
380     driReportDamage(dPriv, &rect, 1);
381
382     dPriv->driScreenPriv->DriverAPI.CopySubBuffer(dPriv, x, y, w, h);
383 }
384
385 const __DRIcopySubBufferExtension driCopySubBufferExtension = {
386     { __DRI_COPY_SUB_BUFFER, __DRI_COPY_SUB_BUFFER_VERSION },
387     driCopySubBuffer
388 };
389
390 static void driSetSwapInterval(__DRIdrawable *dPriv, unsigned int interval)
391 {
392     dPriv->swap_interval = interval;
393 }
394
395 static unsigned int driGetSwapInterval(__DRIdrawable *dPriv)
396 {
397     return dPriv->swap_interval;
398 }
399
400 const __DRIswapControlExtension driSwapControlExtension = {
401     { __DRI_SWAP_CONTROL, __DRI_SWAP_CONTROL_VERSION },
402     driSetSwapInterval,
403     driGetSwapInterval
404 };
405
406
407 /**
408  * This is called via __DRIscreenRec's createNewDrawable pointer.
409  */
410 static __DRIdrawable *
411 driCreateNewDrawable(__DRIscreen *psp, const __DRIconfig *config,
412                      drm_drawable_t hwDrawable, int renderType,
413                      const int *attrs, void *data)
414 {
415     __DRIdrawable *pdp;
416
417     /* Since pbuffers are not yet supported, no drawable attributes are
418      * supported either.
419      */
420     (void) attrs;
421     (void) renderType;
422
423     pdp = malloc(sizeof *pdp);
424     if (!pdp) {
425         return NULL;
426     }
427
428     pdp->driContextPriv = NULL;
429     pdp->loaderPrivate = data;
430     pdp->hHWDrawable = hwDrawable;
431     pdp->refcount = 1;
432     pdp->pStamp = NULL;
433     pdp->lastStamp = 0;
434     pdp->index = 0;
435     pdp->x = 0;
436     pdp->y = 0;
437     pdp->w = 0;
438     pdp->h = 0;
439     pdp->numClipRects = 0;
440     pdp->numBackClipRects = 0;
441     pdp->pClipRects = NULL;
442     pdp->pBackClipRects = NULL;
443     pdp->vblSeq = 0;
444     pdp->vblFlags = 0;
445
446     pdp->driScreenPriv = psp;
447
448     if (!(*psp->DriverAPI.CreateBuffer)(psp, pdp, &config->modes, 0)) {
449        free(pdp);
450        return NULL;
451     }
452
453     pdp->msc_base = 0;
454
455     /* This special default value is replaced with the configured
456      * default value when the drawable is first bound to a direct
457      * rendering context. 
458      */
459     pdp->swap_interval = (unsigned)-1;
460
461     return pdp;
462 }
463
464
465 static __DRIdrawable *
466 dri2CreateNewDrawable(__DRIscreen *screen,
467                       const __DRIconfig *config,
468                       void *loaderPrivate)
469 {
470     __DRIdrawable *pdraw;
471
472     pdraw = driCreateNewDrawable(screen, config, 0, 0, NULL, loaderPrivate);
473     if (!pdraw)
474         return NULL;
475
476     pdraw->pClipRects = &pdraw->dri2.clipRect;
477     pdraw->pBackClipRects = &pdraw->dri2.clipRect;
478
479     pdraw->pStamp = &pdraw->dri2.stamp;
480     *pdraw->pStamp = pdraw->lastStamp + 1;
481
482     return pdraw;
483 }
484
485 static __DRIbuffer *
486 dri2AllocateBuffer(__DRIscreen *screen,
487                    unsigned int attachment, unsigned int format,
488                    int width, int height)
489 {
490     return (*screen->DriverAPI.AllocateBuffer)(screen, attachment, format,
491                                                width, height);
492 }
493
494 static void
495 dri2ReleaseBuffer(__DRIscreen *screen, __DRIbuffer *buffer)
496 {
497    (*screen->DriverAPI.ReleaseBuffer)(screen, buffer);
498 }
499
500
501 static int
502 dri2ConfigQueryb(__DRIscreen *screen, const char *var, GLboolean *val)
503 {
504    if (!driCheckOption(&screen->optionCache, var, DRI_BOOL))
505       return -1;
506
507    *val = driQueryOptionb(&screen->optionCache, var);
508
509    return 0;
510 }
511
512 static int
513 dri2ConfigQueryi(__DRIscreen *screen, const char *var, GLint *val)
514 {
515    if (!driCheckOption(&screen->optionCache, var, DRI_INT) &&
516        !driCheckOption(&screen->optionCache, var, DRI_ENUM))
517       return -1;
518
519     *val = driQueryOptioni(&screen->optionCache, var);
520
521     return 0;
522 }
523
524 static int
525 dri2ConfigQueryf(__DRIscreen *screen, const char *var, GLfloat *val)
526 {
527    if (!driCheckOption(&screen->optionCache, var, DRI_FLOAT))
528       return -1;
529
530     *val = driQueryOptionf(&screen->optionCache, var);
531
532     return 0;
533 }
534
535
536 static void dri_get_drawable(__DRIdrawable *pdp)
537 {
538     pdp->refcount++;
539 }
540         
541 static void dri_put_drawable(__DRIdrawable *pdp)
542 {
543     __DRIscreen *psp;
544
545     if (pdp) {
546         pdp->refcount--;
547         if (pdp->refcount)
548             return;
549
550         psp = pdp->driScreenPriv;
551         (*psp->DriverAPI.DestroyBuffer)(pdp);
552         if (pdp->pClipRects && pdp->pClipRects != &pdp->dri2.clipRect) {
553             free(pdp->pClipRects);
554             pdp->pClipRects = NULL;
555         }
556         if (pdp->pBackClipRects && pdp->pClipRects != &pdp->dri2.clipRect) {
557             free(pdp->pBackClipRects);
558             pdp->pBackClipRects = NULL;
559         }
560         free(pdp);
561     }
562 }
563
564 static void
565 driDestroyDrawable(__DRIdrawable *pdp)
566 {
567     dri_put_drawable(pdp);
568 }
569
570 /*@}*/
571
572
573 /*****************************************************************/
574 /** \name Context handling functions                             */
575 /*****************************************************************/
576 /*@{*/
577
578 /**
579  * Destroy the per-context private information.
580  * 
581  * \internal
582  * This function calls __DriverAPIRec::DestroyContext on \p contextPrivate, calls
583  * drmDestroyContext(), and finally frees \p contextPrivate.
584  */
585 static void
586 driDestroyContext(__DRIcontext *pcp)
587 {
588     if (pcp) {
589         (*pcp->driScreenPriv->DriverAPI.DestroyContext)(pcp);
590         free(pcp);
591     }
592 }
593
594
595 /**
596  * Create the per-drawable private driver information.
597  * 
598  * \param render_type   Type of rendering target.  \c GLX_RGBA_TYPE is the only
599  *                      type likely to ever be supported for direct-rendering.
600  *                      However, \c GLX_RGBA_FLOAT_TYPE_ARB may eventually be
601  *                      supported by some drivers.
602  * \param shared        Context with which to share textures, etc. or NULL
603  *
604  * \returns An opaque pointer to the per-context private information on
605  *          success, or \c NULL on failure.
606  * 
607  * \internal
608  * This function allocates and fills a __DRIcontextRec structure.  It
609  * performs some device independent initialization and passes all the
610  * relevent information to __DriverAPIRec::CreateContext to create the
611  * context.
612  *
613  */
614 static __DRIcontext *
615 driCreateNewContext(__DRIscreen *psp, const __DRIconfig *config,
616                     int render_type, __DRIcontext *shared, 
617                     drm_context_t hwContext, void *data)
618 {
619     __DRIcontext *pcp;
620     void * const shareCtx = (shared != NULL) ? shared->driverPrivate : NULL;
621
622     (void) render_type;
623
624     pcp = malloc(sizeof *pcp);
625     if (!pcp)
626         return NULL;
627
628     pcp->driScreenPriv = psp;
629     pcp->driDrawablePriv = NULL;
630     pcp->loaderPrivate = data;
631     
632     pcp->dri2.draw_stamp = 0;
633     pcp->dri2.read_stamp = 0;
634
635     pcp->hHWContext = hwContext;
636
637     if ( !(*psp->DriverAPI.CreateContext)(API_OPENGL,
638                                           &config->modes, pcp, shareCtx) ) {
639         free(pcp);
640         return NULL;
641     }
642
643     return pcp;
644 }
645
646 static unsigned int
647 dri2GetAPIMask(__DRIscreen *screen)
648 {
649     return screen->api_mask;
650 }
651
652 static __DRIcontext *
653 dri2CreateNewContextForAPI(__DRIscreen *screen, int api,
654                            const __DRIconfig *config,
655                            __DRIcontext *shared, void *data)
656 {
657     __DRIcontext *context;
658     const struct gl_config *modes = (config != NULL) ? &config->modes : NULL;
659     void *shareCtx = (shared != NULL) ? shared->driverPrivate : NULL;
660     gl_api mesa_api;
661
662     if (!(screen->api_mask & (1 << api)))
663         return NULL;
664
665     switch (api) {
666     case __DRI_API_OPENGL:
667             mesa_api = API_OPENGL;
668             break;
669     case __DRI_API_GLES:
670             mesa_api = API_OPENGLES;
671             break;
672     case __DRI_API_GLES2:
673             mesa_api = API_OPENGLES2;
674             break;
675     default:
676             return NULL;
677     }
678
679     context = malloc(sizeof *context);
680     if (!context)
681         return NULL;
682
683     context->driScreenPriv = screen;
684     context->driDrawablePriv = NULL;
685     context->loaderPrivate = data;
686     
687     if (!(*screen->DriverAPI.CreateContext)(mesa_api, modes,
688                                             context, shareCtx) ) {
689         free(context);
690         return NULL;
691     }
692
693     return context;
694 }
695
696
697 static __DRIcontext *
698 dri2CreateNewContext(__DRIscreen *screen, const __DRIconfig *config,
699                       __DRIcontext *shared, void *data)
700 {
701    return dri2CreateNewContextForAPI(screen, __DRI_API_OPENGL,
702                                      config, shared, data);
703 }
704
705 static int
706 driCopyContext(__DRIcontext *dest, __DRIcontext *src, unsigned long mask)
707 {
708     (void) dest;
709     (void) src;
710     (void) mask;
711     return GL_FALSE;
712 }
713
714 /*@}*/
715
716
717 /*****************************************************************/
718 /** \name Screen handling functions                              */
719 /*****************************************************************/
720 /*@{*/
721
722 /**
723  * Destroy the per-screen private information.
724  * 
725  * \internal
726  * This function calls __DriverAPIRec::DestroyScreen on \p screenPrivate, calls
727  * drmClose(), and finally frees \p screenPrivate.
728  */
729 static void driDestroyScreen(__DRIscreen *psp)
730 {
731     if (psp) {
732         /* No interaction with the X-server is possible at this point.  This
733          * routine is called after XCloseDisplay, so there is no protocol
734          * stream open to the X-server anymore.
735          */
736
737        _mesa_destroy_shader_compiler();
738
739         if (psp->DriverAPI.DestroyScreen)
740             (*psp->DriverAPI.DestroyScreen)(psp);
741
742         if (!psp->dri2.enabled) {
743            (void)drmUnmap((drmAddress)psp->pSAREA, SAREA_MAX);
744            (void)drmUnmap((drmAddress)psp->pFB, psp->fbSize);
745            (void)drmCloseOnce(psp->fd);
746         } else {
747            driDestroyOptionCache(&psp->optionCache);
748            driDestroyOptionInfo(&psp->optionInfo);
749         }
750
751         free(psp);
752     }
753 }
754
755 static void
756 setupLoaderExtensions(__DRIscreen *psp,
757                       const __DRIextension **extensions)
758 {
759     int i;
760
761     for (i = 0; extensions[i]; i++) {
762         if (strcmp(extensions[i]->name, __DRI_GET_DRAWABLE_INFO) == 0)
763             psp->getDrawableInfo = (__DRIgetDrawableInfoExtension *) extensions[i];
764         if (strcmp(extensions[i]->name, __DRI_DAMAGE) == 0)
765             psp->damage = (__DRIdamageExtension *) extensions[i];
766         if (strcmp(extensions[i]->name, __DRI_SYSTEM_TIME) == 0)
767             psp->systemTime = (__DRIsystemTimeExtension *) extensions[i];
768         if (strcmp(extensions[i]->name, __DRI_DRI2_LOADER) == 0)
769             psp->dri2.loader = (__DRIdri2LoaderExtension *) extensions[i];
770         if (strcmp(extensions[i]->name, __DRI_IMAGE_LOOKUP) == 0)
771             psp->dri2.image = (__DRIimageLookupExtension *) extensions[i];
772         if (strcmp(extensions[i]->name, __DRI_USE_INVALIDATE) == 0)
773             psp->dri2.useInvalidate = (__DRIuseInvalidateExtension *) extensions[i];
774     }
775 }
776
777 /**
778  * This is the bootstrap function for the driver.  libGL supplies all of the
779  * requisite information about the system, and the driver initializes itself.
780  * This routine also fills in the linked list pointed to by \c driver_modes
781  * with the \c struct gl_config that the driver can support for windows or
782  * pbuffers.
783  *
784  * For legacy DRI.
785  * 
786  * \param scrn  Index of the screen
787  * \param ddx_version Version of the 2D DDX.  This may not be meaningful for
788  *                    all drivers.
789  * \param dri_version Version of the "server-side" DRI.
790  * \param drm_version Version of the kernel DRM.
791  * \param frame_buffer Data describing the location and layout of the
792  *                     framebuffer.
793  * \param pSAREA       Pointer to the SAREA.
794  * \param fd           Device handle for the DRM.
795  * \param extensions   ??
796  * \param driver_modes  Returns modes suppoted by the driver
797  * \param loaderPrivate  ??
798  * 
799  * \note There is no need to check the minimum API version in this
800  * function.  Since the name of this function is versioned, it is
801  * impossible for a loader that is too old to even load this driver.
802  */
803 static __DRIscreen *
804 driCreateNewScreen(int scrn,
805                    const __DRIversion *ddx_version,
806                    const __DRIversion *dri_version,
807                    const __DRIversion *drm_version,
808                    const __DRIframebuffer *frame_buffer,
809                    drmAddress pSAREA, int fd, 
810                    const __DRIextension **extensions,
811                    const __DRIconfig ***driver_modes,
812                    void *loaderPrivate)
813 {
814     static const __DRIextension *emptyExtensionList[] = { NULL };
815     __DRIscreen *psp;
816
817     (void) loaderPrivate;
818
819     if (driDriverAPI.InitScreen == NULL) {
820         __driUtilMessage("driver does not support DRI1");
821         return NULL;
822     }
823
824     psp = calloc(1, sizeof *psp);
825     if (!psp)
826         return NULL;
827
828     setupLoaderExtensions(psp, extensions);
829
830     /*
831     ** NOT_DONE: This is used by the X server to detect when the client
832     ** has died while holding the drawable lock.  The client sets the
833     ** drawable lock to this value.
834     */
835     psp->drawLockID = 1;
836
837     psp->drm_version = *drm_version;
838     psp->ddx_version = *ddx_version;
839     psp->dri_version = *dri_version;
840
841     psp->pSAREA = pSAREA;
842     psp->lock = (drmLock *) &psp->pSAREA->lock;
843
844     psp->pFB = frame_buffer->base;
845     psp->fbSize = frame_buffer->size;
846     psp->fbStride = frame_buffer->stride;
847     psp->fbWidth = frame_buffer->width;
848     psp->fbHeight = frame_buffer->height;
849     psp->devPrivSize = frame_buffer->dev_priv_size;
850     psp->pDevPriv = frame_buffer->dev_priv;
851     psp->fbBPP = psp->fbStride * 8 / frame_buffer->width;
852
853     psp->extensions = emptyExtensionList;
854     psp->fd = fd;
855     psp->myNum = scrn;
856     psp->dri2.enabled = GL_FALSE;
857
858     psp->DriverAPI = driDriverAPI;
859     psp->api_mask = (1 << __DRI_API_OPENGL);
860
861     *driver_modes = driDriverAPI.InitScreen(psp);
862     if (*driver_modes == NULL) {
863         free(psp);
864         return NULL;
865     }
866
867     return psp;
868 }
869
870 /**
871  * DRI2
872  */
873 static __DRIscreen *
874 dri2CreateNewScreen(int scrn, int fd,
875                     const __DRIextension **extensions,
876                     const __DRIconfig ***driver_configs, void *data)
877 {
878     static const __DRIextension *emptyExtensionList[] = { NULL };
879     __DRIscreen *psp;
880     drmVersionPtr version;
881
882     if (driDriverAPI.InitScreen2 == NULL)
883         return NULL;
884
885     psp = calloc(1, sizeof(*psp));
886     if (!psp)
887         return NULL;
888
889     setupLoaderExtensions(psp, extensions);
890
891     version = drmGetVersion(fd);
892     if (version) {
893         psp->drm_version.major = version->version_major;
894         psp->drm_version.minor = version->version_minor;
895         psp->drm_version.patch = version->version_patchlevel;
896         drmFreeVersion(version);
897     }
898
899     psp->extensions = emptyExtensionList;
900     psp->fd = fd;
901     psp->myNum = scrn;
902     psp->dri2.enabled = GL_TRUE;
903
904     psp->DriverAPI = driDriverAPI;
905     psp->api_mask = (1 << __DRI_API_OPENGL);
906     *driver_configs = driDriverAPI.InitScreen2(psp);
907     if (*driver_configs == NULL) {
908         free(psp);
909         return NULL;
910     }
911
912     psp->DriverAPI = driDriverAPI;
913     psp->loaderPrivate = data;
914
915     driParseOptionInfo(&psp->optionInfo, __dri2ConfigOptions,
916                        __dri2NConfigOptions);
917     driParseConfigFiles(&psp->optionCache, &psp->optionInfo, psp->myNum,
918                         "dri2");
919
920     return psp;
921 }
922
923 static const __DRIextension **driGetExtensions(__DRIscreen *psp)
924 {
925     return psp->extensions;
926 }
927
928 /** Core interface */
929 const __DRIcoreExtension driCoreExtension = {
930     { __DRI_CORE, __DRI_CORE_VERSION },
931     NULL,
932     driDestroyScreen,
933     driGetExtensions,
934     driGetConfigAttrib,
935     driIndexConfigAttrib,
936     NULL,
937     driDestroyDrawable,
938     driSwapBuffers,
939     NULL,
940     driCopyContext,
941     driDestroyContext,
942     driBindContext,
943     driUnbindContext
944 };
945
946 /** DRI2 interface */
947 const __DRIdri2Extension driDRI2Extension = {
948     { __DRI_DRI2, __DRI_DRI2_VERSION },
949     dri2CreateNewScreen,
950     dri2CreateNewDrawable,
951     dri2CreateNewContext,
952     dri2GetAPIMask,
953     dri2CreateNewContextForAPI,
954     dri2AllocateBuffer,
955     dri2ReleaseBuffer
956 };
957
958 const __DRI2configQueryExtension dri2ConfigQueryExtension = {
959    { __DRI2_CONFIG_QUERY, __DRI2_CONFIG_QUERY_VERSION },
960    dri2ConfigQueryb,
961    dri2ConfigQueryi,
962    dri2ConfigQueryf,
963 };
964
965 /**
966  * Calculate amount of swap interval used between GLX buffer swaps.
967  * 
968  * The usage value, on the range [0,max], is the fraction of total swap
969  * interval time used between GLX buffer swaps is calculated.
970  *
971  *            \f$p = t_d / (i * t_r)\f$
972  * 
973  * Where \f$t_d\f$ is the time since the last GLX buffer swap, \f$i\f$ is the
974  * swap interval (as set by \c glXSwapIntervalSGI), and \f$t_r\f$ time
975  * required for a single vertical refresh period (as returned by \c
976  * glXGetMscRateOML).
977  * 
978  * See the documentation for the GLX_MESA_swap_frame_usage extension for more
979  * details.
980  *
981  * \param   dPriv  Pointer to the private drawable structure.
982  * \return  If less than a single swap interval time period was required
983  *          between GLX buffer swaps, a number greater than 0 and less than
984  *          1.0 is returned.  If exactly one swap interval time period is
985  *          required, 1.0 is returned, and if more than one is required then
986  *          a number greater than 1.0 will be returned.
987  *
988  * \sa glXSwapIntervalSGI glXGetMscRateOML
989  * 
990  * \todo Instead of caching the \c glXGetMscRateOML function pointer, would it
991  *       be possible to cache the sync rate?
992  */
993 float
994 driCalculateSwapUsage( __DRIdrawable *dPriv, int64_t last_swap_ust,
995                        int64_t current_ust )
996 {
997    int32_t   n;
998    int32_t   d;
999    int       interval;
1000    float     usage = 1.0;
1001    __DRIscreen *psp = dPriv->driScreenPriv;
1002
1003    if ( (*psp->systemTime->getMSCRate)(dPriv, &n, &d, dPriv->loaderPrivate) ) {
1004       interval = (dPriv->swap_interval != 0) ? dPriv->swap_interval : 1;
1005
1006
1007       /* We want to calculate
1008        * (current_UST - last_swap_UST) / (interval * us_per_refresh).  We get
1009        * current_UST by calling __glXGetUST.  last_swap_UST is stored in
1010        * dPriv->swap_ust.  interval has already been calculated.
1011        *
1012        * The only tricky part is us_per_refresh.  us_per_refresh is
1013        * 1000000 / MSC_rate.  We know the MSC_rate is n / d.  We can flip it
1014        * around and say us_per_refresh = 1000000 * d / n.  Since this goes in
1015        * the denominator of the final calculation, we calculate
1016        * (interval * 1000000 * d) and move n into the numerator.
1017        */
1018
1019       usage = (current_ust - last_swap_ust);
1020       usage *= n;
1021       usage /= (interval * d);
1022       usage /= 1000000.0;
1023    }
1024    
1025    return usage;
1026 }
1027
1028 void
1029 dri2InvalidateDrawable(__DRIdrawable *drawable)
1030 {
1031     drawable->dri2.stamp++;
1032 }
1033
1034 /*@}*/