Merge branch 'gallium-msaa'
[mesa.git] / src / egl / main / egldriver.c
1 /**
2 * Functions for choosing and opening/loading device drivers.
3 */
4
5
6 #include <assert.h>
7 #include <string.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include "eglconfig.h"
11 #include "eglcontext.h"
12 #include "egldefines.h"
13 #include "egldisplay.h"
14 #include "egldriver.h"
15 #include "eglglobals.h"
16 #include "egllog.h"
17 #include "eglmisc.h"
18 #include "eglmode.h"
19 #include "eglscreen.h"
20 #include "eglstring.h"
21 #include "eglsurface.h"
22 #include "eglimage.h"
23
24 #if defined(_EGL_PLATFORM_POSIX)
25 #include <dlfcn.h>
26 #include <sys/types.h>
27 #include <dirent.h>
28 #include <unistd.h>
29 #endif
30
31
32 /**
33 * Wrappers for dlopen/dlclose()
34 */
35 #if defined(_EGL_PLATFORM_WINDOWS)
36
37
38 /* XXX Need to decide how to do dynamic name lookup on Windows */
39 static const char DefaultDriverNames[] = {
40 "TBD",
41 };
42
43 typedef HMODULE lib_handle;
44
45 static HMODULE
46 open_library(const char *filename)
47 {
48 return LoadLibrary(filename);
49 }
50
51 static void
52 close_library(HMODULE lib)
53 {
54 FreeLibrary(lib);
55 }
56
57
58 static const char *
59 library_suffix(void)
60 {
61 return ".dll";
62 }
63
64
65 #elif defined(_EGL_PLATFORM_POSIX)
66
67
68 static const char *DefaultDriverNames[] = {
69 "egl_dri2",
70 "egl_glx"
71 };
72
73 typedef void * lib_handle;
74
75 static void *
76 open_library(const char *filename)
77 {
78 return dlopen(filename, RTLD_LAZY);
79 }
80
81 static void
82 close_library(void *lib)
83 {
84 dlclose(lib);
85 }
86
87
88 static const char *
89 library_suffix(void)
90 {
91 return ".so";
92 }
93
94
95 #endif
96
97
98 #define NUM_PROBE_CACHE_SLOTS 8
99 static struct {
100 EGLint keys[NUM_PROBE_CACHE_SLOTS];
101 const void *values[NUM_PROBE_CACHE_SLOTS];
102 } _eglProbeCache;
103
104
105 /**
106 * Open the named driver and find its bootstrap function: _eglMain().
107 */
108 static _EGLMain_t
109 _eglOpenLibrary(const char *driverPath, lib_handle *handle)
110 {
111 lib_handle lib;
112 _EGLMain_t mainFunc = NULL;
113 const char *error = "unknown error";
114
115 assert(driverPath);
116
117 _eglLog(_EGL_DEBUG, "dlopen(%s)", driverPath);
118 lib = open_library(driverPath);
119
120 #if defined(_EGL_PLATFORM_WINDOWS)
121 /* XXX untested */
122 if (lib)
123 mainFunc = (_EGLMain_t) GetProcAddress(lib, "_eglMain");
124 #elif defined(_EGL_PLATFORM_POSIX)
125 if (lib) {
126 union {
127 _EGLMain_t func;
128 void *ptr;
129 } tmp = { NULL };
130 /* direct cast gives a warning when compiled with -pedantic */
131 tmp.ptr = dlsym(lib, "_eglMain");
132 mainFunc = tmp.func;
133 if (!mainFunc)
134 error = dlerror();
135 }
136 else {
137 error = dlerror();
138 }
139 #endif
140
141 if (!lib) {
142 _eglLog(_EGL_WARNING, "Could not open driver %s (%s)",
143 driverPath, error);
144 if (!getenv("EGL_DRIVER"))
145 _eglLog(_EGL_WARNING,
146 "The driver can be overridden by setting EGL_DRIVER");
147 return NULL;
148 }
149
150 if (!mainFunc) {
151 _eglLog(_EGL_WARNING, "_eglMain not found in %s (%s)",
152 driverPath, error);
153 if (lib)
154 close_library(lib);
155 return NULL;
156 }
157
158 *handle = lib;
159 return mainFunc;
160 }
161
162
163 /**
164 * Load the named driver.
165 */
166 static _EGLDriver *
167 _eglLoadDriver(const char *path, const char *args)
168 {
169 _EGLMain_t mainFunc;
170 lib_handle lib;
171 _EGLDriver *drv = NULL;
172
173 mainFunc = _eglOpenLibrary(path, &lib);
174 if (!mainFunc)
175 return NULL;
176
177 drv = mainFunc(args);
178 if (!drv) {
179 if (lib)
180 close_library(lib);
181 return NULL;
182 }
183
184 if (!drv->Name) {
185 _eglLog(_EGL_WARNING, "Driver loaded from %s has no name", path);
186 drv->Name = "UNNAMED";
187 }
188
189 drv->Path = _eglstrdup(path);
190 drv->Args = (args) ? _eglstrdup(args) : NULL;
191 if (!drv->Path || (args && !drv->Args)) {
192 if (drv->Path)
193 free((char *) drv->Path);
194 if (drv->Args)
195 free((char *) drv->Args);
196 drv->Unload(drv);
197 if (lib)
198 close_library(lib);
199 return NULL;
200 }
201
202 drv->LibHandle = lib;
203
204 return drv;
205 }
206
207
208 /**
209 * Match a display to a preloaded driver.
210 *
211 * The matching is done by finding the driver with the highest score.
212 */
213 _EGLDriver *
214 _eglMatchDriver(_EGLDisplay *dpy)
215 {
216 _EGLDriver *best_drv = NULL;
217 EGLint best_score = -1, i;
218
219 /*
220 * this function is called after preloading and the drivers never change
221 * after preloading.
222 */
223 for (i = 0; i < _eglGlobal.NumDrivers; i++) {
224 _EGLDriver *drv = _eglGlobal.Drivers[i];
225 EGLint score;
226
227 score = (drv->Probe) ? drv->Probe(drv, dpy) : 0;
228 if (score > best_score) {
229 if (best_drv) {
230 _eglLog(_EGL_DEBUG, "driver %s has higher score than %s",
231 drv->Name, best_drv->Name);
232 }
233
234 best_drv = drv;
235 best_score = score;
236 /* perfect match */
237 if (score >= 100)
238 break;
239 }
240 }
241
242 return best_drv;
243 }
244
245
246 /**
247 * A loader function for use with _eglPreloadForEach. The loader data is the
248 * filename of the driver. This function stops on the first valid driver.
249 */
250 static EGLBoolean
251 _eglLoaderFile(const char *dir, size_t len, void *loader_data)
252 {
253 _EGLDriver *drv;
254 char path[1024];
255 const char *filename = (const char *) loader_data;
256 size_t flen = strlen(filename);
257
258 /* make a full path */
259 if (len + flen + 2 > sizeof(path))
260 return EGL_TRUE;
261 if (len) {
262 memcpy(path, dir, len);
263 path[len++] = '/';
264 }
265 memcpy(path + len, filename, flen);
266 len += flen;
267 path[len] = '\0';
268
269 if (library_suffix() == NULL || strstr(path, library_suffix()))
270 drv = _eglLoadDriver(path, NULL);
271 else {
272 const char *suffix = library_suffix();
273 size_t slen = strlen(suffix);
274 const char *p;
275 EGLBoolean need_suffix;
276
277 p = filename + flen - slen;
278 need_suffix = (p < filename || strcmp(p, suffix) != 0);
279 if (need_suffix && len + slen + 1 <= sizeof(path)) {
280 strcpy(path + len, suffix);
281 drv = _eglLoadDriver(path, NULL);
282 } else {
283 drv = NULL;
284 }
285 }
286 if (!drv)
287 return EGL_TRUE;
288
289 /* remember the driver and stop */
290 _eglGlobal.Drivers[_eglGlobal.NumDrivers++] = drv;
291 return EGL_FALSE;
292 }
293
294
295 /**
296 * A loader function for use with _eglPreloadForEach. The loader data is the
297 * pattern (prefix) of the files to look for.
298 */
299 static EGLBoolean
300 _eglLoaderPattern(const char *dir, size_t len, void *loader_data)
301 {
302 #if defined(_EGL_PLATFORM_POSIX)
303 const char *prefix, *suffix;
304 size_t prefix_len, suffix_len;
305 DIR *dirp;
306 struct dirent *dirent;
307 char path[1024];
308
309 if (len + 2 > sizeof(path))
310 return EGL_TRUE;
311 if (len) {
312 memcpy(path, dir, len);
313 path[len++] = '/';
314 }
315 path[len] = '\0';
316
317 dirp = opendir(path);
318 if (!dirp)
319 return EGL_TRUE;
320
321 prefix = (const char *) loader_data;
322 prefix_len = strlen(prefix);
323 suffix = library_suffix();
324 suffix_len = (suffix) ? strlen(suffix) : 0;
325
326 while ((dirent = readdir(dirp))) {
327 _EGLDriver *drv;
328 size_t dirent_len = strlen(dirent->d_name);
329 const char *p;
330
331 /* match the prefix */
332 if (strncmp(dirent->d_name, prefix, prefix_len) != 0)
333 continue;
334 /* match the suffix */
335 if (suffix) {
336 p = dirent->d_name + dirent_len - suffix_len;
337 if (p < dirent->d_name || strcmp(p, suffix) != 0)
338 continue;
339 }
340
341 /* make a full path and load the driver */
342 if (len + dirent_len + 1 <= sizeof(path)) {
343 strcpy(path + len, dirent->d_name);
344 drv = _eglLoadDriver(path, NULL);
345 if (drv)
346 _eglGlobal.Drivers[_eglGlobal.NumDrivers++] = drv;
347 }
348 }
349
350 closedir(dirp);
351
352 return EGL_TRUE;
353 #else /* _EGL_PLATFORM_POSIX */
354 /* stop immediately */
355 return EGL_FALSE;
356 #endif
357 }
358
359
360 /**
361 * Run the preload function on each driver directory and return the number of
362 * drivers loaded.
363 *
364 * The process may end prematurely if the callback function returns false.
365 */
366 static EGLint
367 _eglPreloadForEach(const char *search_path,
368 EGLBoolean (*loader)(const char *, size_t, void *),
369 void *loader_data)
370 {
371 const char *cur, *next;
372 size_t len;
373 EGLint num_drivers = _eglGlobal.NumDrivers;
374
375 cur = search_path;
376 while (cur) {
377 next = strchr(cur, ':');
378 len = (next) ? next - cur : strlen(cur);
379
380 if (!loader(cur, len, loader_data))
381 break;
382
383 cur = (next) ? next + 1 : NULL;
384 }
385
386 return (_eglGlobal.NumDrivers - num_drivers);
387 }
388
389
390 /**
391 * Return a list of colon-separated driver directories.
392 */
393 static const char *
394 _eglGetSearchPath(void)
395 {
396 static const char *search_path;
397
398 #if defined(_EGL_PLATFORM_POSIX) || defined(_EGL_PLATFORM_WINDOWS)
399 if (!search_path) {
400 static char buffer[1024];
401 const char *p;
402 int ret;
403
404 p = getenv("EGL_DRIVERS_PATH");
405 #if defined(_EGL_PLATFORM_POSIX)
406 if (p && (geteuid() != getuid() || getegid() != getgid())) {
407 _eglLog(_EGL_DEBUG,
408 "ignore EGL_DRIVERS_PATH for setuid/setgid binaries");
409 p = NULL;
410 }
411 #endif /* _EGL_PLATFORM_POSIX */
412
413 if (p) {
414 ret = snprintf(buffer, sizeof(buffer),
415 "%s:%s", p, _EGL_DRIVER_SEARCH_DIR);
416 if (ret > 0 && ret < sizeof(buffer))
417 search_path = buffer;
418 }
419 }
420 if (!search_path)
421 search_path = _EGL_DRIVER_SEARCH_DIR;
422 #else
423 search_path = "";
424 #endif
425
426 return search_path;
427 }
428
429
430 /**
431 * Preload a user driver.
432 *
433 * A user driver can be specified by EGL_DRIVER.
434 */
435 static EGLBoolean
436 _eglPreloadUserDriver(void)
437 {
438 const char *search_path = _eglGetSearchPath();
439 char *env;
440
441 env = getenv("EGL_DRIVER");
442 #if defined(_EGL_PLATFORM_POSIX)
443 if (env && strchr(env, '/')) {
444 search_path = "";
445 if ((geteuid() != getuid() || getegid() != getgid())) {
446 _eglLog(_EGL_DEBUG,
447 "ignore EGL_DRIVER for setuid/setgid binaries");
448 env = NULL;
449 }
450 }
451 #endif /* _EGL_PLATFORM_POSIX */
452 if (!env)
453 return EGL_FALSE;
454
455 if (!_eglPreloadForEach(search_path, _eglLoaderFile, (void *) env)) {
456 _eglLog(_EGL_WARNING, "EGL_DRIVER is set to an invalid driver");
457 return EGL_FALSE;
458 }
459
460 return EGL_TRUE;
461 }
462
463
464 /**
465 * Preload display drivers.
466 *
467 * Display drivers are a set of drivers that support a certain display system.
468 * The display system may be specified by EGL_DISPLAY.
469 *
470 * FIXME This makes libEGL a memory hog if an user driver is not specified and
471 * there are many display drivers.
472 */
473 static EGLBoolean
474 _eglPreloadDisplayDrivers(void)
475 {
476 const char *dpy;
477 char prefix[32];
478 int ret;
479
480 dpy = getenv("EGL_DISPLAY");
481 if (!dpy || !dpy[0])
482 dpy = _EGL_DEFAULT_DISPLAY;
483 if (!dpy || !dpy[0])
484 return EGL_FALSE;
485
486 ret = snprintf(prefix, sizeof(prefix), "egl_%s_", dpy);
487 if (ret < 0 || ret >= sizeof(prefix))
488 return EGL_FALSE;
489
490 return (_eglPreloadForEach(_eglGetSearchPath(),
491 _eglLoaderPattern, (void *) prefix) > 0);
492 }
493
494
495 /**
496 * Preload drivers.
497 *
498 * This function loads the driver modules and creates the corresponding
499 * _EGLDriver objects.
500 */
501 EGLBoolean
502 _eglPreloadDrivers(void)
503 {
504 EGLBoolean loaded;
505
506 /* protect the preloading process */
507 _eglLockMutex(_eglGlobal.Mutex);
508
509 /* already preloaded */
510 if (_eglGlobal.NumDrivers) {
511 _eglUnlockMutex(_eglGlobal.Mutex);
512 return EGL_TRUE;
513 }
514
515 loaded = (_eglPreloadUserDriver() ||
516 _eglPreloadDisplayDrivers());
517
518 _eglUnlockMutex(_eglGlobal.Mutex);
519
520 return loaded;
521 }
522
523 /**
524 * Unload preloaded drivers.
525 */
526 void
527 _eglUnloadDrivers(void)
528 {
529 EGLint i;
530
531 /* this is called at atexit time */
532 for (i = 0; i < _eglGlobal.NumDrivers; i++) {
533 _EGLDriver *drv = _eglGlobal.Drivers[i];
534 lib_handle handle = drv->LibHandle;
535
536 if (drv->Path)
537 free((char *) drv->Path);
538 if (drv->Args)
539 free((char *) drv->Args);
540
541 /* destroy driver */
542 if (drv->Unload)
543 drv->Unload(drv);
544
545 if (handle)
546 close_library(handle);
547 _eglGlobal.Drivers[i] = NULL;
548 }
549
550 _eglGlobal.NumDrivers = 0;
551 }
552
553 _EGLDriver *
554 _eglLoadDefaultDriver(EGLDisplay dpy, EGLint *major, EGLint *minor)
555 {
556 _EGLDriver *drv = NULL;
557 int i;
558
559 _eglLockMutex(_eglGlobal.Mutex);
560
561 for (i = 0; i < ARRAY_SIZE(DefaultDriverNames); i++) {
562 _eglPreloadForEach(_eglGetSearchPath(),
563 _eglLoaderFile, (void *) DefaultDriverNames[i]);
564 if (_eglGlobal.NumDrivers == 0)
565 continue;
566 drv = _eglGlobal.Drivers[0];
567 if (drv->API.Initialize(drv, dpy, major, minor))
568 break;
569 _eglUnloadDrivers();
570 }
571
572 _eglUnlockMutex(_eglGlobal.Mutex);
573
574 return drv;
575 }
576
577
578 /**
579 * Plug all the available fallback routines into the given driver's
580 * dispatch table.
581 */
582 void
583 _eglInitDriverFallbacks(_EGLDriver *drv)
584 {
585 /* If a pointer is set to NULL, then the device driver _really_ has
586 * to implement it.
587 */
588 drv->API.Initialize = NULL;
589 drv->API.Terminate = NULL;
590
591 drv->API.GetConfigs = _eglGetConfigs;
592 drv->API.ChooseConfig = _eglChooseConfig;
593 drv->API.GetConfigAttrib = _eglGetConfigAttrib;
594
595 drv->API.CreateContext = _eglCreateContext;
596 drv->API.DestroyContext = _eglDestroyContext;
597 drv->API.MakeCurrent = _eglMakeCurrent;
598 drv->API.QueryContext = _eglQueryContext;
599
600 drv->API.CreateWindowSurface = _eglCreateWindowSurface;
601 drv->API.CreatePixmapSurface = _eglCreatePixmapSurface;
602 drv->API.CreatePbufferSurface = _eglCreatePbufferSurface;
603 drv->API.DestroySurface = _eglDestroySurface;
604 drv->API.QuerySurface = _eglQuerySurface;
605 drv->API.SurfaceAttrib = _eglSurfaceAttrib;
606 drv->API.BindTexImage = _eglBindTexImage;
607 drv->API.ReleaseTexImage = _eglReleaseTexImage;
608 drv->API.SwapInterval = _eglSwapInterval;
609 drv->API.SwapBuffers = _eglSwapBuffers;
610 drv->API.CopyBuffers = _eglCopyBuffers;
611
612 drv->API.QueryString = _eglQueryString;
613 drv->API.WaitClient = _eglWaitClient;
614 drv->API.WaitNative = _eglWaitNative;
615
616 #ifdef EGL_MESA_screen_surface
617 drv->API.ChooseModeMESA = _eglChooseModeMESA;
618 drv->API.GetModesMESA = _eglGetModesMESA;
619 drv->API.GetModeAttribMESA = _eglGetModeAttribMESA;
620 drv->API.GetScreensMESA = _eglGetScreensMESA;
621 drv->API.CreateScreenSurfaceMESA = _eglCreateScreenSurfaceMESA;
622 drv->API.ShowScreenSurfaceMESA = _eglShowScreenSurfaceMESA;
623 drv->API.ScreenPositionMESA = _eglScreenPositionMESA;
624 drv->API.QueryScreenMESA = _eglQueryScreenMESA;
625 drv->API.QueryScreenSurfaceMESA = _eglQueryScreenSurfaceMESA;
626 drv->API.QueryScreenModeMESA = _eglQueryScreenModeMESA;
627 drv->API.QueryModeStringMESA = _eglQueryModeStringMESA;
628 #endif /* EGL_MESA_screen_surface */
629
630 #ifdef EGL_VERSION_1_2
631 drv->API.CreatePbufferFromClientBuffer = _eglCreatePbufferFromClientBuffer;
632 #endif /* EGL_VERSION_1_2 */
633
634 #ifdef EGL_KHR_image_base
635 drv->API.CreateImageKHR = _eglCreateImageKHR;
636 drv->API.DestroyImageKHR = _eglDestroyImageKHR;
637 #endif /* EGL_KHR_image_base */
638 }
639
640
641 /**
642 * Invoke a callback function on each EGL search path.
643 *
644 * The first argument of the callback function is the name of the search path.
645 * The second argument is the length of the name.
646 */
647 void
648 _eglSearchPathForEach(EGLBoolean (*callback)(const char *, size_t, void *),
649 void *callback_data)
650 {
651 const char *search_path = _eglGetSearchPath();
652 _eglPreloadForEach(search_path, callback, callback_data);
653 }
654
655
656 /**
657 * Set the probe cache at the given key.
658 *
659 * A key, instead of a _EGLDriver, is used to allow the probe cache to be share
660 * by multiple drivers.
661 */
662 void
663 _eglSetProbeCache(EGLint key, const void *val)
664 {
665 EGLint idx;
666
667 for (idx = 0; idx < NUM_PROBE_CACHE_SLOTS; idx++) {
668 if (!_eglProbeCache.keys[idx] || _eglProbeCache.keys[idx] == key)
669 break;
670 }
671 assert(key > 0);
672 assert(idx < NUM_PROBE_CACHE_SLOTS);
673
674 _eglProbeCache.keys[idx] = key;
675 _eglProbeCache.values[idx] = val;
676 }
677
678
679 /**
680 * Return the probe cache at the given key.
681 */
682 const void *
683 _eglGetProbeCache(EGLint key)
684 {
685 EGLint idx;
686
687 for (idx = 0; idx < NUM_PROBE_CACHE_SLOTS; idx++) {
688 if (!_eglProbeCache.keys[idx] || _eglProbeCache.keys[idx] == key)
689 break;
690 }
691
692 return (idx < NUM_PROBE_CACHE_SLOTS && _eglProbeCache.keys[idx] == key) ?
693 _eglProbeCache.values[idx] : NULL;
694 }