1 /*
2 * Copyright (C) 2013 Rob Clark <robclark@freedesktop.org>
3 * Copyright (C) 2014-2016 Emil Velikov <emil.l.velikov@gmail.com>
4 * Copyright (C) 2016 Intel Corporation
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice (including the next
14 * paragraph) shall be included in all copies or substantial portions of the
15 * Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 * SOFTWARE.
24 *
25 * Authors:
26 * Rob Clark <robclark@freedesktop.org>
27 */
28
29 #include <dlfcn.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <sys/stat.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <stdbool.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <stdlib.h>
39 #include <limits.h>
40 #include <sys/param.h>
41 #ifdef MAJOR_IN_MKDEV
42 #include <sys/mkdev.h>
43 #endif
44 #ifdef MAJOR_IN_SYSMACROS
45 #include <sys/sysmacros.h>
46 #endif
47 #include <GL/gl.h>
48 #include <GL/internal/dri_interface.h>
49 #include <GL/internal/mesa_interface.h>
50 #include "loader.h"
51 #include "util/libdrm.h"
52 #include "util/os_file.h"
53 #include "util/os_misc.h"
54 #include "util/u_debug.h"
55 #include "git_sha1.h"
56
57 #include "drm-uapi/nouveau_drm.h"
58
59 #define MAX_DRM_DEVICES 64
60
61 #ifdef USE_DRICONF
62 #include "util/xmlconfig.h"
63 #include "util/driconf.h"
64 #endif
65
66 #include "util/macros.h"
67
68 #define __IS_LOADER
69 #include "pci_id_driver_map.h"
70
71 /* For systems like Hurd */
72 #ifndef PATH_MAX
73 #define PATH_MAX 4096
74 #endif
75
default_logger(int level,const char * fmt,...)76 static void default_logger(int level, const char *fmt, ...)
77 {
78 if (level <= _LOADER_WARNING) {
79 va_list args;
80 va_start(args, fmt);
81 vfprintf(stderr, fmt, args);
82 va_end(args);
83 }
84 }
85
86 static loader_logger *log_ = default_logger;
87
88 int
loader_open_device(const char * device_name)89 loader_open_device(const char *device_name)
90 {
91 int fd;
92 #ifdef O_CLOEXEC
93 fd = open(device_name, O_RDWR | O_CLOEXEC);
94 if (fd == -1 && errno == EINVAL)
95 #endif
96 {
97 fd = open(device_name, O_RDWR);
98 if (fd != -1)
99 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
100 }
101 if (fd == -1 && errno == EACCES) {
102 log_(_LOADER_WARNING, "failed to open %s: %s\n",
103 device_name, strerror(errno));
104 }
105 return fd;
106 }
107
108 char *
loader_get_kernel_driver_name(int fd)109 loader_get_kernel_driver_name(int fd)
110 {
111 char *driver;
112 drmVersionPtr version = drmGetVersion(fd);
113
114 if (!version) {
115 log_(_LOADER_WARNING, "failed to get driver name for fd %d\n", fd);
116 return NULL;
117 }
118
119 driver = strndup(version->name, version->name_len);
120 log_(driver ? _LOADER_DEBUG : _LOADER_WARNING, "using driver %s for %d\n",
121 driver, fd);
122
123 drmFreeVersion(version);
124 return driver;
125 }
126
127 bool
iris_predicate(int fd,const char * driver)128 iris_predicate(int fd, const char *driver)
129 {
130 char *kernel_driver = loader_get_kernel_driver_name(fd);
131 bool ret = kernel_driver && (strcmp(kernel_driver, "i915") == 0 ||
132 strcmp(kernel_driver, "xe") == 0);
133
134 free(kernel_driver);
135 return ret;
136 }
137
138 /* choose zink or nouveau GL */
139 bool
nouveau_zink_predicate(int fd,const char * driver)140 nouveau_zink_predicate(int fd, const char *driver)
141 {
142 #if !defined(HAVE_NVK) || !defined(HAVE_ZINK)
143 if (!strcmp(driver, "zink"))
144 return false;
145 return true;
146 #else
147
148 bool prefer_zink = false;
149
150 /* enable this once zink is up to speed.
151 * struct drm_nouveau_getparam r = { .param = NOUVEAU_GETPARAM_CHIPSET_ID };
152 * int ret = drmCommandWriteRead(fd, DRM_NOUVEAU_GETPARAM, &r, sizeof(r));
153 * if (ret == 0 && (r.value & ~0xf) >= 0x160)
154 * prefer_zink = true;
155 */
156
157 prefer_zink = debug_get_bool_option("NOUVEAU_USE_ZINK", prefer_zink);
158
159 if (prefer_zink && !strcmp(driver, "zink"))
160 return true;
161
162 if (!prefer_zink && !strcmp(driver, "nouveau"))
163 return true;
164 return false;
165 #endif
166 }
167
168
169 /**
170 * Goes through all the platform devices whose driver is on the given list and
171 * try to open their render node. It returns the fd of the first device that
172 * it can open.
173 */
174 int
loader_open_render_node_platform_device(const char * const drivers[],unsigned int n_drivers)175 loader_open_render_node_platform_device(const char * const drivers[],
176 unsigned int n_drivers)
177 {
178 drmDevicePtr devices[MAX_DRM_DEVICES], device;
179 int num_devices, fd = -1;
180 int i, j;
181 bool found = false;
182
183 num_devices = drmGetDevices2(0, devices, MAX_DRM_DEVICES);
184 if (num_devices <= 0)
185 return -ENOENT;
186
187 for (i = 0; i < num_devices; i++) {
188 device = devices[i];
189
190 if ((device->available_nodes & (1 << DRM_NODE_RENDER)) &&
191 (device->bustype == DRM_BUS_PLATFORM)) {
192 drmVersionPtr version;
193
194 fd = loader_open_device(device->nodes[DRM_NODE_RENDER]);
195 if (fd < 0)
196 continue;
197
198 version = drmGetVersion(fd);
199 if (!version) {
200 close(fd);
201 continue;
202 }
203
204 for (j = 0; j < n_drivers; j++) {
205 if (strcmp(version->name, drivers[j]) == 0) {
206 found = true;
207 break;
208 }
209 }
210 if (!found) {
211 drmFreeVersion(version);
212 close(fd);
213 continue;
214 }
215
216 drmFreeVersion(version);
217 break;
218 }
219 }
220 drmFreeDevices(devices, num_devices);
221
222 if (i == num_devices)
223 return -ENOENT;
224
225 return fd;
226 }
227
228 bool
loader_is_device_render_capable(int fd)229 loader_is_device_render_capable(int fd)
230 {
231 drmDevicePtr dev_ptr;
232 bool ret;
233
234 if (drmGetDevice2(fd, 0, &dev_ptr) != 0)
235 return false;
236
237 ret = (dev_ptr->available_nodes & (1 << DRM_NODE_RENDER));
238
239 drmFreeDevice(&dev_ptr);
240
241 return ret;
242 }
243
244 char *
loader_get_render_node(dev_t device)245 loader_get_render_node(dev_t device)
246 {
247 char *render_node = NULL;
248 drmDevicePtr dev_ptr;
249
250 if (drmGetDeviceFromDevId(device, 0, &dev_ptr) < 0)
251 return NULL;
252
253 if (dev_ptr->available_nodes & (1 << DRM_NODE_RENDER)) {
254 render_node = strdup(dev_ptr->nodes[DRM_NODE_RENDER]);
255 if (!render_node)
256 log_(_LOADER_DEBUG, "MESA-LOADER: failed to allocate memory for render node\n");
257 }
258
259 drmFreeDevice(&dev_ptr);
260
261 return render_node;
262 }
263
264 #ifdef USE_DRICONF
265 static const driOptionDescription __driConfigOptionsLoader[] = {
266 DRI_CONF_SECTION_INITIALIZATION
267 DRI_CONF_DEVICE_ID_PATH_TAG()
268 DRI_CONF_DRI_DRIVER()
269 DRI_CONF_SECTION_END
270 };
271
loader_get_dri_config_driver(int fd)272 static char *loader_get_dri_config_driver(int fd)
273 {
274 driOptionCache defaultInitOptions;
275 driOptionCache userInitOptions;
276 char *dri_driver = NULL;
277 char *kernel_driver = loader_get_kernel_driver_name(fd);
278
279 driParseOptionInfo(&defaultInitOptions, __driConfigOptionsLoader,
280 ARRAY_SIZE(__driConfigOptionsLoader));
281 driParseConfigFiles(&userInitOptions, &defaultInitOptions, 0,
282 "loader", kernel_driver, NULL, NULL, 0, NULL, 0);
283 if (driCheckOption(&userInitOptions, "dri_driver", DRI_STRING)) {
284 char *opt = driQueryOptionstr(&userInitOptions, "dri_driver");
285 /* not an empty string */
286 if (*opt)
287 dri_driver = strdup(opt);
288 }
289 driDestroyOptionCache(&userInitOptions);
290 driDestroyOptionInfo(&defaultInitOptions);
291
292 free(kernel_driver);
293 return dri_driver;
294 }
295
loader_get_dri_config_device_id(void)296 static char *loader_get_dri_config_device_id(void)
297 {
298 driOptionCache defaultInitOptions;
299 driOptionCache userInitOptions;
300 char *prime = NULL;
301
302 driParseOptionInfo(&defaultInitOptions, __driConfigOptionsLoader,
303 ARRAY_SIZE(__driConfigOptionsLoader));
304 driParseConfigFiles(&userInitOptions, &defaultInitOptions, 0,
305 "loader", NULL, NULL, NULL, 0, NULL, 0);
306 if (driCheckOption(&userInitOptions, "device_id", DRI_STRING)) {
307 char *opt = driQueryOptionstr(&userInitOptions, "device_id");
308 if (*opt)
309 prime = strdup(opt);
310 }
311 driDestroyOptionCache(&userInitOptions);
312 driDestroyOptionInfo(&defaultInitOptions);
313
314 return prime;
315 }
316 #endif
317
drm_construct_id_path_tag(drmDevicePtr device)318 static char *drm_construct_id_path_tag(drmDevicePtr device)
319 {
320 char *tag = NULL;
321
322 if (device->bustype == DRM_BUS_PCI) {
323 if (asprintf(&tag, "pci-%04x_%02x_%02x_%1u",
324 device->businfo.pci->domain,
325 device->businfo.pci->bus,
326 device->businfo.pci->dev,
327 device->businfo.pci->func) < 0) {
328 return NULL;
329 }
330 } else if (device->bustype == DRM_BUS_PLATFORM ||
331 device->bustype == DRM_BUS_HOST1X) {
332 char *fullname, *name, *address;
333
334 if (device->bustype == DRM_BUS_PLATFORM)
335 fullname = device->businfo.platform->fullname;
336 else
337 fullname = device->businfo.host1x->fullname;
338
339 name = strrchr(fullname, '/');
340 if (!name)
341 name = strdup(fullname);
342 else
343 name = strdup(name + 1);
344
345 address = strchr(name, '@');
346 if (address) {
347 *address++ = '\0';
348
349 if (asprintf(&tag, "platform-%s_%s", address, name) < 0)
350 tag = NULL;
351 } else {
352 if (asprintf(&tag, "platform-%s", name) < 0)
353 tag = NULL;
354 }
355
356 free(name);
357 }
358 return tag;
359 }
360
drm_device_matches_tag(drmDevicePtr device,const char * prime_tag)361 static bool drm_device_matches_tag(drmDevicePtr device, const char *prime_tag)
362 {
363 char *tag = drm_construct_id_path_tag(device);
364 int ret;
365
366 if (tag == NULL)
367 return false;
368
369 ret = strcmp(tag, prime_tag);
370
371 free(tag);
372 return ret == 0;
373 }
374
drm_get_id_path_tag_for_fd(int fd)375 static char *drm_get_id_path_tag_for_fd(int fd)
376 {
377 drmDevicePtr device;
378 char *tag;
379
380 if (drmGetDevice2(fd, 0, &device) != 0)
381 return NULL;
382
383 tag = drm_construct_id_path_tag(device);
384 drmFreeDevice(&device);
385 return tag;
386 }
387
loader_get_user_preferred_fd(int * fd_render_gpu,int * original_fd)388 bool loader_get_user_preferred_fd(int *fd_render_gpu, int *original_fd)
389 {
390 const char *dri_prime = getenv("DRI_PRIME");
391 bool debug = debug_get_bool_option("DRI_PRIME_DEBUG", false);
392 char *default_tag = NULL;
393 drmDevicePtr devices[MAX_DRM_DEVICES];
394 int i, num_devices, fd = -1;
395 struct {
396 enum {
397 PRIME_IS_INTEGER,
398 PRIME_IS_VID_DID,
399 PRIME_IS_PCI_TAG
400 } semantics;
401 union {
402 int as_integer;
403 struct {
404 uint16_t v, d;
405 } as_vendor_device_ids;
406 } v;
407 char *str;
408 } prime = {};
409 prime.str = NULL;
410
411 if (dri_prime)
412 prime.str = strdup(dri_prime);
413 #ifdef USE_DRICONF
414 else
415 prime.str = loader_get_dri_config_device_id();
416 #endif
417
418 if (prime.str == NULL) {
419 goto no_prime_gpu_offloading;
420 } else {
421 uint16_t vendor_id, device_id;
422 if (sscanf(prime.str, "%hx:%hx", &vendor_id, &device_id) == 2) {
423 prime.semantics = PRIME_IS_VID_DID;
424 prime.v.as_vendor_device_ids.v = vendor_id;
425 prime.v.as_vendor_device_ids.d = device_id;
426 } else {
427 int i = atoi(prime.str);
428 if (i < 0 || strcmp(prime.str, "0") == 0) {
429 printf("Invalid value (%d) for DRI_PRIME. Should be > 0\n", i);
430 goto err;
431 } else if (i == 0) {
432 prime.semantics = PRIME_IS_PCI_TAG;
433 } else {
434 prime.semantics = PRIME_IS_INTEGER;
435 prime.v.as_integer = i;
436 }
437 }
438 }
439
440 default_tag = drm_get_id_path_tag_for_fd(*fd_render_gpu);
441 if (default_tag == NULL)
442 goto err;
443
444 num_devices = drmGetDevices2(0, devices, MAX_DRM_DEVICES);
445 if (num_devices <= 0)
446 goto err;
447
448 if (debug) {
449 log_(_LOADER_WARNING, "DRI_PRIME: %d devices\n", num_devices);
450 for (i = 0; i < num_devices; i++) {
451 log_(_LOADER_WARNING, " %d:", i);
452 if (!(devices[i]->available_nodes & 1 << DRM_NODE_RENDER)) {
453 log_(_LOADER_WARNING, "not a render node -> not usable\n");
454 continue;
455 }
456 char *tag = drm_construct_id_path_tag(devices[i]);
457 if (tag) {
458 log_(_LOADER_WARNING, " %s", tag);
459 free(tag);
460 }
461 if (devices[i]->bustype == DRM_BUS_PCI) {
462 log_(_LOADER_WARNING, " %4x:%4x",
463 devices[i]->deviceinfo.pci->vendor_id,
464 devices[i]->deviceinfo.pci->device_id);
465 }
466 log_(_LOADER_WARNING, " %s", devices[i]->nodes[DRM_NODE_RENDER]);
467
468 if (drm_device_matches_tag(devices[i], default_tag)) {
469 log_(_LOADER_WARNING, " [default]");
470 }
471 log_(_LOADER_WARNING, "\n");
472 }
473 }
474
475 if (prime.semantics == PRIME_IS_INTEGER &&
476 prime.v.as_integer >= num_devices) {
477 printf("Inconsistent value (%d) for DRI_PRIME. Should be < %d "
478 "(GPU devices count). Using: %d\n",
479 prime.v.as_integer, num_devices, num_devices - 1);
480 prime.v.as_integer = num_devices - 1;
481 }
482
483 for (i = 0; i < num_devices; i++) {
484 if (!(devices[i]->available_nodes & 1 << DRM_NODE_RENDER))
485 continue;
486
487 log_(debug ? _LOADER_WARNING : _LOADER_INFO, "DRI_PRIME: device %d ", i);
488
489 /* three formats of DRI_PRIME are supported:
490 * "N": a >= 1 integer value. Select the Nth GPU, skipping the
491 * default one.
492 * id_path_tag: (for example "pci-0000_02_00_0") choose the card
493 * with this id_path_tag.
494 * vendor_id:device_id
495 */
496 switch (prime.semantics) {
497 case PRIME_IS_INTEGER: {
498 /* Skip the default device */
499 if (drm_device_matches_tag(devices[i], default_tag)) {
500 log_(debug ? _LOADER_WARNING : _LOADER_INFO,
501 "skipped (default device)\n");
502 continue;
503 }
504 prime.v.as_integer--;
505
506 /* Skip more GPUs? */
507 if (prime.v.as_integer) {
508 log_(debug ? _LOADER_WARNING : _LOADER_INFO,
509 "skipped (%d more to skip)\n", prime.v.as_integer - 1);
510 continue;
511 }
512 log_(debug ? _LOADER_WARNING : _LOADER_INFO, " -> ");
513 break;
514 }
515 case PRIME_IS_VID_DID: {
516 if (devices[i]->bustype == DRM_BUS_PCI &&
517 devices[i]->deviceinfo.pci->vendor_id == prime.v.as_vendor_device_ids.v &&
518 devices[i]->deviceinfo.pci->device_id == prime.v.as_vendor_device_ids.d) {
519 /* Update prime for the "different_device"
520 * determination below. */
521 free(prime.str);
522 prime.str = drm_construct_id_path_tag(devices[i]);
523 log_(debug ? _LOADER_WARNING : _LOADER_INFO,
524 " - vid:did match -> ");
525 break;
526 } else {
527 log_(debug ? _LOADER_WARNING : _LOADER_INFO,
528 "skipped (vid:did didn't match)\n");
529 }
530 continue;
531 }
532 case PRIME_IS_PCI_TAG: {
533 if (!drm_device_matches_tag(devices[i], prime.str)) {
534 log_(debug ? _LOADER_WARNING : _LOADER_INFO,
535 "skipped (pci id tag didn't match)\n");
536 continue;
537 }
538 log_(debug ? _LOADER_WARNING : _LOADER_INFO, " - pci tag match -> ");
539 break;
540 }
541 }
542
543 log_(debug ? _LOADER_WARNING : _LOADER_INFO,
544 "selected (%s)\n", devices[i]->nodes[DRM_NODE_RENDER]);
545 fd = loader_open_device(devices[i]->nodes[DRM_NODE_RENDER]);
546 break;
547 }
548 drmFreeDevices(devices, num_devices);
549
550 if (i == num_devices)
551 goto err;
552
553 if (fd < 0) {
554 log_(debug ? _LOADER_WARNING : _LOADER_INFO,
555 "DRI_PRIME: failed to open '%s'\n",
556 devices[i]->nodes[DRM_NODE_RENDER]);
557
558 goto err;
559 }
560
561 bool is_render_and_display_gpu_diff = !!strcmp(default_tag, prime.str);
562 if (original_fd) {
563 if (is_render_and_display_gpu_diff) {
564 *original_fd = *fd_render_gpu;
565 *fd_render_gpu = fd;
566 } else {
567 *original_fd = *fd_render_gpu;
568 close(fd);
569 }
570 } else {
571 close(*fd_render_gpu);
572 *fd_render_gpu = fd;
573 }
574
575 free(default_tag);
576 free(prime.str);
577 return is_render_and_display_gpu_diff;
578 err:
579 log_(debug ? _LOADER_WARNING : _LOADER_INFO,
580 "DRI_PRIME: error. Using the default GPU\n");
581 free(default_tag);
582 free(prime.str);
583 no_prime_gpu_offloading:
584 if (original_fd)
585 *original_fd = *fd_render_gpu;
586 return false;
587 }
588
589 static bool
drm_get_pci_id_for_fd(int fd,int * vendor_id,int * chip_id)590 drm_get_pci_id_for_fd(int fd, int *vendor_id, int *chip_id)
591 {
592 drmDevicePtr device;
593
594 if (drmGetDevice2(fd, 0, &device) != 0) {
595 log_(_LOADER_WARNING, "MESA-LOADER: failed to retrieve device information\n");
596 return false;
597 }
598
599 if (device->bustype != DRM_BUS_PCI) {
600 drmFreeDevice(&device);
601 log_(_LOADER_DEBUG, "MESA-LOADER: device is not located on the PCI bus\n");
602 return false;
603 }
604
605 *vendor_id = device->deviceinfo.pci->vendor_id;
606 *chip_id = device->deviceinfo.pci->device_id;
607 drmFreeDevice(&device);
608 return true;
609 }
610
611 #ifdef __linux__
loader_get_linux_pci_field(int maj,int min,const char * field)612 static int loader_get_linux_pci_field(int maj, int min, const char *field)
613 {
614 char path[PATH_MAX + 1];
615 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device/%s", maj, min, field);
616
617 char *field_str = os_read_file(path, NULL);
618 if (!field_str) {
619 /* Probably non-PCI device. */
620 return 0;
621 }
622
623 int value = (int)strtoll(field_str, NULL, 16);
624 free(field_str);
625
626 return value;
627 }
628
629 static bool
loader_get_linux_pci_id_for_fd(int fd,int * vendor_id,int * chip_id)630 loader_get_linux_pci_id_for_fd(int fd, int *vendor_id, int *chip_id)
631 {
632 struct stat sbuf;
633 if (fstat(fd, &sbuf) != 0) {
634 log_(_LOADER_DEBUG, "MESA-LOADER: failed to fstat fd\n");
635 return false;
636 }
637
638 int maj = major(sbuf.st_rdev);
639 int min = minor(sbuf.st_rdev);
640
641 *vendor_id = loader_get_linux_pci_field(maj, min, "vendor");
642 *chip_id = loader_get_linux_pci_field(maj, min, "device");
643
644 return *vendor_id && *chip_id;
645 }
646 #endif /* __linux__ */
647
648 bool
loader_get_pci_id_for_fd(int fd,int * vendor_id,int * chip_id)649 loader_get_pci_id_for_fd(int fd, int *vendor_id, int *chip_id)
650 {
651 #ifdef __linux__
652 /* Implementation without causing full enumeration of DRM devices. */
653 if (loader_get_linux_pci_id_for_fd(fd, vendor_id, chip_id))
654 return true;
655 #endif
656
657 return drm_get_pci_id_for_fd(fd, vendor_id, chip_id);
658 }
659
660 char *
loader_get_device_name_for_fd(int fd)661 loader_get_device_name_for_fd(int fd)
662 {
663 return drmGetDeviceNameFromFd2(fd);
664 }
665
666 static char *
loader_get_pci_driver(int fd)667 loader_get_pci_driver(int fd)
668 {
669 int vendor_id, chip_id, i, j;
670 char *driver = NULL;
671
672 if (!loader_get_pci_id_for_fd(fd, &vendor_id, &chip_id))
673 return NULL;
674
675 for (i = 0; i < ARRAY_SIZE(driver_map); i++) {
676 if (vendor_id != driver_map[i].vendor_id)
677 continue;
678
679 if (driver_map[i].predicate && !driver_map[i].predicate(fd, driver_map[i].driver))
680 continue;
681
682 if (driver_map[i].num_chips_ids == -1) {
683 driver = strdup(driver_map[i].driver);
684 goto out;
685 }
686
687 for (j = 0; j < driver_map[i].num_chips_ids; j++)
688 if (driver_map[i].chip_ids[j] == chip_id) {
689 driver = strdup(driver_map[i].driver);
690 goto out;
691 }
692 }
693
694 out:
695 log_(driver ? _LOADER_DEBUG : _LOADER_WARNING,
696 "pci id for fd %d: %04x:%04x, driver %s\n",
697 fd, vendor_id, chip_id, driver);
698 return driver;
699 }
700
701 char *
loader_get_driver_for_fd(int fd)702 loader_get_driver_for_fd(int fd)
703 {
704 char *driver;
705
706 /* Allow an environment variable to force choosing a different driver
707 * binary. If that driver binary can't survive on this FD, that's the
708 * user's problem, but this allows vc4 simulator to run on an i965 host,
709 * and may be useful for some touch testing of i915 on an i965 host.
710 */
711 if (__normal_user()) {
712 const char *override = os_get_option("MESA_LOADER_DRIVER_OVERRIDE");
713 if (override)
714 return strdup(override);
715 }
716
717 #if defined(USE_DRICONF)
718 driver = loader_get_dri_config_driver(fd);
719 if (driver)
720 return driver;
721 #endif
722
723 driver = loader_get_pci_driver(fd);
724 if (!driver)
725 driver = loader_get_kernel_driver_name(fd);
726
727 return driver;
728 }
729
730 void
loader_set_logger(loader_logger * logger)731 loader_set_logger(loader_logger *logger)
732 {
733 log_ = logger;
734 }
735
736 char *
loader_get_extensions_name(const char * driver_name)737 loader_get_extensions_name(const char *driver_name)
738 {
739 char *name = NULL;
740
741 if (asprintf(&name, "%s_%s", __DRI_DRIVER_GET_EXTENSIONS, driver_name) < 0)
742 return NULL;
743
744 const size_t len = strlen(name);
745 for (size_t i = 0; i < len; i++) {
746 if (name[i] == '-')
747 name[i] = '_';
748 }
749
750 return name;
751 }
752
753 bool
loader_bind_extensions(void * data,const struct dri_extension_match * matches,size_t num_matches,const __DRIextension ** extensions)754 loader_bind_extensions(void *data,
755 const struct dri_extension_match *matches, size_t num_matches,
756 const __DRIextension **extensions)
757 {
758 bool ret = true;
759
760 for (size_t j = 0; j < num_matches; j++) {
761 const struct dri_extension_match *match = &matches[j];
762 const __DRIextension **field = (const __DRIextension **)((char *)data + matches[j].offset);
763 for (size_t i = 0; extensions[i]; i++) {
764 if (strcmp(extensions[i]->name, match->name) == 0 &&
765 extensions[i]->version >= match->version) {
766 *field = extensions[i];
767 break;
768 }
769 }
770
771 if (!*field) {
772 log_(match->optional ? _LOADER_DEBUG : _LOADER_FATAL, "did not find extension %s version %d\n",
773 match->name, match->version);
774 if (!match->optional)
775 ret = false;
776 continue;
777 }
778
779 /* The loaders rely on the loaded DRI drivers being from the same Mesa
780 * build so that we can reference the same structs on both sides.
781 */
782 if (strcmp(match->name, __DRI_MESA) == 0) {
783 const __DRImesaCoreExtension *mesa = (const __DRImesaCoreExtension *)*field;
784 if (strcmp(mesa->version_string, MESA_INTERFACE_VERSION_STRING) != 0) {
785 log_(_LOADER_FATAL, "DRI driver not from this Mesa build ('%s' vs '%s')\n",
786 mesa->version_string, MESA_INTERFACE_VERSION_STRING);
787 ret = false;
788 }
789 }
790 }
791
792 return ret;
793 }
794 /**
795 * Opens a driver or backend using its name, returning the library handle.
796 *
797 * \param driverName - a name like "i965", "radeon", "nouveau", etc.
798 * \param lib_suffix - a suffix to append to the driver name to generate the
799 * full library name.
800 * \param search_path_vars - NULL-terminated list of env vars that can be used
801 * \param default_search_path - a colon-separted list of directories used if
802 * search_path_vars is NULL or none of the vars are set in the environment.
803 * \param warn_on_fail - Log a warning if the driver is not found.
804 */
805 void *
loader_open_driver_lib(const char * driver_name,const char * lib_suffix,const char ** search_path_vars,const char * default_search_path,bool warn_on_fail)806 loader_open_driver_lib(const char *driver_name,
807 const char *lib_suffix,
808 const char **search_path_vars,
809 const char *default_search_path,
810 bool warn_on_fail)
811 {
812 char path[PATH_MAX];
813 const char *search_paths, *next, *end;
814
815 search_paths = NULL;
816 if (__normal_user() && search_path_vars) {
817 for (int i = 0; search_path_vars[i] != NULL; i++) {
818 search_paths = getenv(search_path_vars[i]);
819 if (search_paths)
820 break;
821 }
822 }
823 if (search_paths == NULL)
824 search_paths = default_search_path;
825
826 void *driver = NULL;
827 const char *dl_error = NULL;
828 end = search_paths + strlen(search_paths);
829 for (const char *p = search_paths; p < end; p = next + 1) {
830 int len;
831 next = strchr(p, ':');
832 if (next == NULL)
833 next = end;
834
835 len = next - p;
836 snprintf(path, sizeof(path), "%.*s/tls/%s%s.so", len,
837 p, driver_name, lib_suffix);
838 driver = dlopen(path, RTLD_NOW | RTLD_GLOBAL);
839 if (driver == NULL) {
840 snprintf(path, sizeof(path), "%.*s/%s%s.so", len,
841 p, driver_name, lib_suffix);
842 driver = dlopen(path, RTLD_NOW | RTLD_GLOBAL);
843 if (driver == NULL) {
844 dl_error = dlerror();
845 log_(_LOADER_DEBUG, "MESA-LOADER: failed to open %s: %s\n",
846 path, dl_error);
847 }
848 }
849 /* not need continue to loop all paths once the driver is found */
850 if (driver != NULL)
851 break;
852 }
853
854 if (driver == NULL) {
855 if (warn_on_fail) {
856 log_(_LOADER_WARNING,
857 "MESA-LOADER: failed to open %s: %s (search paths %s, suffix %s)\n",
858 driver_name, dl_error, search_paths, lib_suffix);
859 }
860 return NULL;
861 }
862
863 log_(_LOADER_DEBUG, "MESA-LOADER: dlopen(%s)\n", path);
864
865 return driver;
866 }
867
868 /**
869 * Opens a DRI driver using its driver name, returning the __DRIextension
870 * entrypoints.
871 *
872 * \param driverName - a name like "i965", "radeon", "nouveau", etc.
873 * \param out_driver - Address where the dlopen() return value will be stored.
874 * \param search_path_vars - NULL-terminated list of env vars that can be used
875 * to override the DEFAULT_DRIVER_DIR search path.
876 */
877 const struct __DRIextensionRec **
loader_open_driver(const char * driver_name,void ** out_driver_handle,const char ** search_path_vars)878 loader_open_driver(const char *driver_name,
879 void **out_driver_handle,
880 const char **search_path_vars)
881 {
882 char *get_extensions_name;
883 const struct __DRIextensionRec **extensions = NULL;
884 const struct __DRIextensionRec **(*get_extensions)(void);
885 void *driver = loader_open_driver_lib(driver_name, "_dri", search_path_vars,
886 DEFAULT_DRIVER_DIR, true);
887
888 if (!driver)
889 goto failed;
890
891 get_extensions_name = loader_get_extensions_name(driver_name);
892 if (get_extensions_name) {
893 get_extensions = dlsym(driver, get_extensions_name);
894 if (get_extensions) {
895 extensions = get_extensions();
896 } else {
897 log_(_LOADER_DEBUG, "MESA-LOADER: driver does not expose %s(): %s\n",
898 get_extensions_name, dlerror());
899 }
900 free(get_extensions_name);
901 }
902
903 if (extensions == NULL) {
904 log_(_LOADER_WARNING,
905 "MESA-LOADER: driver exports no extensions (%s)\n", dlerror());
906 dlclose(driver);
907 driver = NULL;
908 }
909
910 failed:
911 *out_driver_handle = driver;
912 return extensions;
913 }
914