1 /**
2 * \file xf86drm.c
3 * User-level interface to DRM device
4 *
5 * \author Rickard E. (Rik) Faith <faith@valinux.com>
6 * \author Kevin E. Martin <martin@valinux.com>
7 */
8
9 /*
10 * Copyright 1999 Precision Insight, Inc., Cedar Park, Texas.
11 * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California.
12 * All Rights Reserved.
13 *
14 * Permission is hereby granted, free of charge, to any person obtaining a
15 * copy of this software and associated documentation files (the "Software"),
16 * to deal in the Software without restriction, including without limitation
17 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
18 * and/or sell copies of the Software, and to permit persons to whom the
19 * Software is furnished to do so, subject to the following conditions:
20 *
21 * The above copyright notice and this permission notice (including the next
22 * paragraph) shall be included in all copies or substantial portions of the
23 * Software.
24 *
25 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
28 * PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
29 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
30 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
31 * DEALINGS IN THE SOFTWARE.
32 */
33
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <stdbool.h>
37 #include <unistd.h>
38 #include <string.h>
39 #include <strings.h>
40 #include <ctype.h>
41 #include <dirent.h>
42 #include <stddef.h>
43 #include <fcntl.h>
44 #include <errno.h>
45 #include <limits.h>
46 #include <signal.h>
47 #include <time.h>
48 #include <sys/types.h>
49 #include <sys/stat.h>
50 #define stat_t struct stat
51 #include <sys/ioctl.h>
52 #include <sys/time.h>
53 #include <stdarg.h>
54 #ifdef MAJOR_IN_MKDEV
55 #include <sys/mkdev.h>
56 #endif
57 #ifdef MAJOR_IN_SYSMACROS
58 #include <sys/sysmacros.h>
59 #endif
60 #if HAVE_SYS_SYSCTL_H
61 #include <sys/sysctl.h>
62 #endif
63 #include <math.h>
64
65 #if defined(__FreeBSD__)
66 #include <sys/param.h>
67 #include <sys/pciio.h>
68 #endif
69
70 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
71
72 /* Not all systems have MAP_FAILED defined */
73 #ifndef MAP_FAILED
74 #define MAP_FAILED ((void *)-1)
75 #endif
76
77 #include "xf86drm.h"
78 #include "libdrm_macros.h"
79
80 #include "util_math.h"
81
82 #ifdef __DragonFly__
83 #define DRM_MAJOR 145
84 #endif
85
86 #ifdef __NetBSD__
87 #define DRM_MAJOR 34
88 #endif
89
90 #ifdef __OpenBSD__
91 #ifdef __i386__
92 #define DRM_MAJOR 88
93 #else
94 #define DRM_MAJOR 87
95 #endif
96 #endif /* __OpenBSD__ */
97
98 #ifndef DRM_MAJOR
99 #define DRM_MAJOR 226 /* Linux */
100 #endif
101
102 #if defined(__OpenBSD__) || defined(__DragonFly__)
103 struct drm_pciinfo {
104 uint16_t domain;
105 uint8_t bus;
106 uint8_t dev;
107 uint8_t func;
108 uint16_t vendor_id;
109 uint16_t device_id;
110 uint16_t subvendor_id;
111 uint16_t subdevice_id;
112 uint8_t revision_id;
113 };
114
115 #define DRM_IOCTL_GET_PCIINFO DRM_IOR(0x15, struct drm_pciinfo)
116 #endif
117
118 #define DRM_MSG_VERBOSITY 3
119
120 #define memclear(s) memset(&s, 0, sizeof(s))
121
122 static drmServerInfoPtr drm_server_info;
123
124 static bool drmNodeIsDRM(int maj, int min);
125 static char *drmGetMinorNameForFD(int fd, int type);
126
drmSetServerInfo(drmServerInfoPtr info)127 drm_public void drmSetServerInfo(drmServerInfoPtr info)
128 {
129 drm_server_info = info;
130 }
131
132 /**
133 * Output a message to stderr.
134 *
135 * \param format printf() like format string.
136 *
137 * \internal
138 * This function is a wrapper around vfprintf().
139 */
140
141 static int DRM_PRINTFLIKE(1, 0)
drmDebugPrint(const char * format,va_list ap)142 drmDebugPrint(const char *format, va_list ap)
143 {
144 return vfprintf(stderr, format, ap);
145 }
146
147 drm_public void
drmMsg(const char * format,...)148 drmMsg(const char *format, ...)
149 {
150 va_list ap;
151 const char *env;
152 if (((env = getenv("LIBGL_DEBUG")) && strstr(env, "verbose")) ||
153 (drm_server_info && drm_server_info->debug_print))
154 {
155 va_start(ap, format);
156 if (drm_server_info) {
157 drm_server_info->debug_print(format,ap);
158 } else {
159 drmDebugPrint(format, ap);
160 }
161 va_end(ap);
162 }
163 }
164
165 static void *drmHashTable = NULL; /* Context switch callbacks */
166
drmGetHashTable(void)167 drm_public void *drmGetHashTable(void)
168 {
169 return drmHashTable;
170 }
171
drmMalloc(int size)172 drm_public void *drmMalloc(int size)
173 {
174 return calloc(1, size);
175 }
176
drmFree(void * pt)177 drm_public void drmFree(void *pt)
178 {
179 free(pt);
180 }
181
182 /**
183 * Call ioctl, restarting if it is interrupted
184 */
185 drm_public int
drmIoctl(int fd,unsigned long request,void * arg)186 drmIoctl(int fd, unsigned long request, void *arg)
187 {
188 int ret;
189
190 do {
191 ret = ioctl(fd, request, arg);
192 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
193 return ret;
194 }
195
drmGetKeyFromFd(int fd)196 static unsigned long drmGetKeyFromFd(int fd)
197 {
198 stat_t st;
199
200 st.st_rdev = 0;
201 fstat(fd, &st);
202 return st.st_rdev;
203 }
204
drmGetEntry(int fd)205 drm_public drmHashEntry *drmGetEntry(int fd)
206 {
207 unsigned long key = drmGetKeyFromFd(fd);
208 void *value;
209 drmHashEntry *entry;
210
211 if (!drmHashTable)
212 drmHashTable = drmHashCreate();
213
214 if (drmHashLookup(drmHashTable, key, &value)) {
215 entry = drmMalloc(sizeof(*entry));
216 entry->fd = fd;
217 entry->f = NULL;
218 entry->tagTable = drmHashCreate();
219 drmHashInsert(drmHashTable, key, entry);
220 } else {
221 entry = value;
222 }
223 return entry;
224 }
225
226 /**
227 * Compare two busid strings
228 *
229 * \param first
230 * \param second
231 *
232 * \return 1 if matched.
233 *
234 * \internal
235 * This function compares two bus ID strings. It understands the older
236 * PCI:b:d:f format and the newer pci:oooo:bb:dd.f format. In the format, o is
237 * domain, b is bus, d is device, f is function.
238 */
drmMatchBusID(const char * id1,const char * id2,int pci_domain_ok)239 static int drmMatchBusID(const char *id1, const char *id2, int pci_domain_ok)
240 {
241 /* First, check if the IDs are exactly the same */
242 if (strcasecmp(id1, id2) == 0)
243 return 1;
244
245 /* Try to match old/new-style PCI bus IDs. */
246 if (strncasecmp(id1, "pci", 3) == 0) {
247 unsigned int o1, b1, d1, f1;
248 unsigned int o2, b2, d2, f2;
249 int ret;
250
251 ret = sscanf(id1, "pci:%04x:%02x:%02x.%u", &o1, &b1, &d1, &f1);
252 if (ret != 4) {
253 o1 = 0;
254 ret = sscanf(id1, "PCI:%u:%u:%u", &b1, &d1, &f1);
255 if (ret != 3)
256 return 0;
257 }
258
259 ret = sscanf(id2, "pci:%04x:%02x:%02x.%u", &o2, &b2, &d2, &f2);
260 if (ret != 4) {
261 o2 = 0;
262 ret = sscanf(id2, "PCI:%u:%u:%u", &b2, &d2, &f2);
263 if (ret != 3)
264 return 0;
265 }
266
267 /* If domains aren't properly supported by the kernel interface,
268 * just ignore them, which sucks less than picking a totally random
269 * card with "open by name"
270 */
271 if (!pci_domain_ok)
272 o1 = o2 = 0;
273
274 if ((o1 != o2) || (b1 != b2) || (d1 != d2) || (f1 != f2))
275 return 0;
276 else
277 return 1;
278 }
279 return 0;
280 }
281
282 /**
283 * Handles error checking for chown call.
284 *
285 * \param path to file.
286 * \param id of the new owner.
287 * \param id of the new group.
288 *
289 * \return zero if success or -1 if failure.
290 *
291 * \internal
292 * Checks for failure. If failure was caused by signal call chown again.
293 * If any other failure happened then it will output error message using
294 * drmMsg() call.
295 */
296 #if !UDEV
chown_check_return(const char * path,uid_t owner,gid_t group)297 static int chown_check_return(const char *path, uid_t owner, gid_t group)
298 {
299 int rv;
300
301 do {
302 rv = chown(path, owner, group);
303 } while (rv != 0 && errno == EINTR);
304
305 if (rv == 0)
306 return 0;
307
308 drmMsg("Failed to change owner or group for file %s! %d: %s\n",
309 path, errno, strerror(errno));
310 return -1;
311 }
312 #endif
313
drmGetDeviceName(int type)314 static const char *drmGetDeviceName(int type)
315 {
316 switch (type) {
317 case DRM_NODE_PRIMARY:
318 return DRM_DEV_NAME;
319 case DRM_NODE_CONTROL:
320 return DRM_CONTROL_DEV_NAME;
321 case DRM_NODE_RENDER:
322 return DRM_RENDER_DEV_NAME;
323 }
324 return NULL;
325 }
326
327 /**
328 * Open the DRM device, creating it if necessary.
329 *
330 * \param dev major and minor numbers of the device.
331 * \param minor minor number of the device.
332 *
333 * \return a file descriptor on success, or a negative value on error.
334 *
335 * \internal
336 * Assembles the device name from \p minor and opens it, creating the device
337 * special file node with the major and minor numbers specified by \p dev and
338 * parent directory if necessary and was called by root.
339 */
drmOpenDevice(dev_t dev,int minor,int type)340 static int drmOpenDevice(dev_t dev, int minor, int type)
341 {
342 stat_t st;
343 const char *dev_name = drmGetDeviceName(type);
344 char buf[DRM_NODE_NAME_MAX];
345 int fd;
346 mode_t devmode = DRM_DEV_MODE, serv_mode;
347 gid_t serv_group;
348 #if !UDEV
349 int isroot = !geteuid();
350 uid_t user = DRM_DEV_UID;
351 gid_t group = DRM_DEV_GID;
352 #endif
353
354 if (!dev_name)
355 return -EINVAL;
356
357 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
358 drmMsg("drmOpenDevice: node name is %s\n", buf);
359
360 if (drm_server_info && drm_server_info->get_perms) {
361 drm_server_info->get_perms(&serv_group, &serv_mode);
362 devmode = serv_mode ? serv_mode : DRM_DEV_MODE;
363 devmode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
364 }
365
366 #if !UDEV
367 if (stat(DRM_DIR_NAME, &st)) {
368 if (!isroot)
369 return DRM_ERR_NOT_ROOT;
370 mkdir(DRM_DIR_NAME, DRM_DEV_DIRMODE);
371 chown_check_return(DRM_DIR_NAME, 0, 0); /* root:root */
372 chmod(DRM_DIR_NAME, DRM_DEV_DIRMODE);
373 }
374
375 /* Check if the device node exists and create it if necessary. */
376 if (stat(buf, &st)) {
377 if (!isroot)
378 return DRM_ERR_NOT_ROOT;
379 remove(buf);
380 mknod(buf, S_IFCHR | devmode, dev);
381 }
382
383 if (drm_server_info && drm_server_info->get_perms) {
384 group = ((int)serv_group >= 0) ? serv_group : DRM_DEV_GID;
385 chown_check_return(buf, user, group);
386 chmod(buf, devmode);
387 }
388 #else
389 /* if we modprobed then wait for udev */
390 {
391 int udev_count = 0;
392 wait_for_udev:
393 if (stat(DRM_DIR_NAME, &st)) {
394 usleep(20);
395 udev_count++;
396
397 if (udev_count == 50)
398 return -1;
399 goto wait_for_udev;
400 }
401
402 if (stat(buf, &st)) {
403 usleep(20);
404 udev_count++;
405
406 if (udev_count == 50)
407 return -1;
408 goto wait_for_udev;
409 }
410 }
411 #endif
412
413 fd = open(buf, O_RDWR | O_CLOEXEC, 0);
414 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
415 fd, fd < 0 ? strerror(errno) : "OK");
416 if (fd >= 0)
417 return fd;
418
419 #if !UDEV
420 /* Check if the device node is not what we expect it to be, and recreate it
421 * and try again if so.
422 */
423 if (st.st_rdev != dev) {
424 if (!isroot)
425 return DRM_ERR_NOT_ROOT;
426 remove(buf);
427 mknod(buf, S_IFCHR | devmode, dev);
428 if (drm_server_info && drm_server_info->get_perms) {
429 chown_check_return(buf, user, group);
430 chmod(buf, devmode);
431 }
432 }
433 fd = open(buf, O_RDWR | O_CLOEXEC, 0);
434 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
435 fd, fd < 0 ? strerror(errno) : "OK");
436 if (fd >= 0)
437 return fd;
438
439 drmMsg("drmOpenDevice: Open failed\n");
440 remove(buf);
441 #endif
442 return -errno;
443 }
444
445
446 /**
447 * Open the DRM device
448 *
449 * \param minor device minor number.
450 * \param create allow to create the device if set.
451 *
452 * \return a file descriptor on success, or a negative value on error.
453 *
454 * \internal
455 * Calls drmOpenDevice() if \p create is set, otherwise assembles the device
456 * name from \p minor and opens it.
457 */
drmOpenMinor(int minor,int create,int type)458 static int drmOpenMinor(int minor, int create, int type)
459 {
460 int fd;
461 char buf[DRM_NODE_NAME_MAX];
462 const char *dev_name = drmGetDeviceName(type);
463
464 if (create)
465 return drmOpenDevice(makedev(DRM_MAJOR, minor), minor, type);
466
467 if (!dev_name)
468 return -EINVAL;
469
470 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
471 if ((fd = open(buf, O_RDWR | O_CLOEXEC, 0)) >= 0)
472 return fd;
473 return -errno;
474 }
475
476
477 /**
478 * Determine whether the DRM kernel driver has been loaded.
479 *
480 * \return 1 if the DRM driver is loaded, 0 otherwise.
481 *
482 * \internal
483 * Determine the presence of the kernel driver by attempting to open the 0
484 * minor and get version information. For backward compatibility with older
485 * Linux implementations, /proc/dri is also checked.
486 */
drmAvailable(void)487 drm_public int drmAvailable(void)
488 {
489 drmVersionPtr version;
490 int retval = 0;
491 int fd;
492
493 if ((fd = drmOpenMinor(0, 1, DRM_NODE_PRIMARY)) < 0) {
494 #ifdef __linux__
495 /* Try proc for backward Linux compatibility */
496 if (!access("/proc/dri/0", R_OK))
497 return 1;
498 #endif
499 return 0;
500 }
501
502 if ((version = drmGetVersion(fd))) {
503 retval = 1;
504 drmFreeVersion(version);
505 }
506 close(fd);
507
508 return retval;
509 }
510
drmGetMinorBase(int type)511 static int drmGetMinorBase(int type)
512 {
513 switch (type) {
514 case DRM_NODE_PRIMARY:
515 return 0;
516 case DRM_NODE_CONTROL:
517 return 64;
518 case DRM_NODE_RENDER:
519 return 128;
520 default:
521 return -1;
522 };
523 }
524
drmGetMinorType(int major,int minor)525 static int drmGetMinorType(int major, int minor)
526 {
527 #ifdef __FreeBSD__
528 char name[SPECNAMELEN];
529 int id;
530
531 if (!devname_r(makedev(major, minor), S_IFCHR, name, sizeof(name)))
532 return -1;
533
534 if (sscanf(name, "drm/%d", &id) != 1) {
535 // If not in /dev/drm/ we have the type in the name
536 if (sscanf(name, "dri/card%d\n", &id) >= 1)
537 return DRM_NODE_PRIMARY;
538 else if (sscanf(name, "dri/control%d\n", &id) >= 1)
539 return DRM_NODE_CONTROL;
540 else if (sscanf(name, "dri/renderD%d\n", &id) >= 1)
541 return DRM_NODE_RENDER;
542 return -1;
543 }
544
545 minor = id;
546 #endif
547 int type = minor >> 6;
548
549 if (minor < 0)
550 return -1;
551
552 switch (type) {
553 case DRM_NODE_PRIMARY:
554 case DRM_NODE_CONTROL:
555 case DRM_NODE_RENDER:
556 return type;
557 default:
558 return -1;
559 }
560 }
561
drmGetMinorName(int type)562 static const char *drmGetMinorName(int type)
563 {
564 switch (type) {
565 case DRM_NODE_PRIMARY:
566 return DRM_PRIMARY_MINOR_NAME;
567 case DRM_NODE_CONTROL:
568 return DRM_CONTROL_MINOR_NAME;
569 case DRM_NODE_RENDER:
570 return DRM_RENDER_MINOR_NAME;
571 default:
572 return NULL;
573 }
574 }
575
576 /**
577 * Open the device by bus ID.
578 *
579 * \param busid bus ID.
580 * \param type device node type.
581 *
582 * \return a file descriptor on success, or a negative value on error.
583 *
584 * \internal
585 * This function attempts to open every possible minor (up to DRM_MAX_MINOR),
586 * comparing the device bus ID with the one supplied.
587 *
588 * \sa drmOpenMinor() and drmGetBusid().
589 */
drmOpenByBusid(const char * busid,int type)590 static int drmOpenByBusid(const char *busid, int type)
591 {
592 int i, pci_domain_ok = 1;
593 int fd;
594 const char *buf;
595 drmSetVersion sv;
596 int base = drmGetMinorBase(type);
597
598 if (base < 0)
599 return -1;
600
601 drmMsg("drmOpenByBusid: Searching for BusID %s\n", busid);
602 for (i = base; i < base + DRM_MAX_MINOR; i++) {
603 fd = drmOpenMinor(i, 1, type);
604 drmMsg("drmOpenByBusid: drmOpenMinor returns %d\n", fd);
605 if (fd >= 0) {
606 /* We need to try for 1.4 first for proper PCI domain support
607 * and if that fails, we know the kernel is busted
608 */
609 sv.drm_di_major = 1;
610 sv.drm_di_minor = 4;
611 sv.drm_dd_major = -1; /* Don't care */
612 sv.drm_dd_minor = -1; /* Don't care */
613 if (drmSetInterfaceVersion(fd, &sv)) {
614 #ifndef __alpha__
615 pci_domain_ok = 0;
616 #endif
617 sv.drm_di_major = 1;
618 sv.drm_di_minor = 1;
619 sv.drm_dd_major = -1; /* Don't care */
620 sv.drm_dd_minor = -1; /* Don't care */
621 drmMsg("drmOpenByBusid: Interface 1.4 failed, trying 1.1\n");
622 drmSetInterfaceVersion(fd, &sv);
623 }
624 buf = drmGetBusid(fd);
625 drmMsg("drmOpenByBusid: drmGetBusid reports %s\n", buf);
626 if (buf && drmMatchBusID(buf, busid, pci_domain_ok)) {
627 drmFreeBusid(buf);
628 return fd;
629 }
630 if (buf)
631 drmFreeBusid(buf);
632 close(fd);
633 }
634 }
635 return -1;
636 }
637
638
639 /**
640 * Open the device by name.
641 *
642 * \param name driver name.
643 * \param type the device node type.
644 *
645 * \return a file descriptor on success, or a negative value on error.
646 *
647 * \internal
648 * This function opens the first minor number that matches the driver name and
649 * isn't already in use. If it's in use it then it will already have a bus ID
650 * assigned.
651 *
652 * \sa drmOpenMinor(), drmGetVersion() and drmGetBusid().
653 */
drmOpenByName(const char * name,int type)654 static int drmOpenByName(const char *name, int type)
655 {
656 int i;
657 int fd;
658 drmVersionPtr version;
659 char * id;
660 int base = drmGetMinorBase(type);
661
662 if (base < 0)
663 return -1;
664
665 /*
666 * Open the first minor number that matches the driver name and isn't
667 * already in use. If it's in use it will have a busid assigned already.
668 */
669 for (i = base; i < base + DRM_MAX_MINOR; i++) {
670 if ((fd = drmOpenMinor(i, 1, type)) >= 0) {
671 if ((version = drmGetVersion(fd))) {
672 if (!strcmp(version->name, name)) {
673 drmFreeVersion(version);
674 id = drmGetBusid(fd);
675 drmMsg("drmGetBusid returned '%s'\n", id ? id : "NULL");
676 if (!id || !*id) {
677 if (id)
678 drmFreeBusid(id);
679 return fd;
680 } else {
681 drmFreeBusid(id);
682 }
683 } else {
684 drmFreeVersion(version);
685 }
686 }
687 close(fd);
688 }
689 }
690
691 #ifdef __linux__
692 /* Backward-compatibility /proc support */
693 for (i = 0; i < 8; i++) {
694 char proc_name[64], buf[512];
695 char *driver, *pt, *devstring;
696 int retcode;
697
698 sprintf(proc_name, "/proc/dri/%d/name", i);
699 if ((fd = open(proc_name, 0, 0)) >= 0) {
700 retcode = read(fd, buf, sizeof(buf)-1);
701 close(fd);
702 if (retcode) {
703 buf[retcode-1] = '\0';
704 for (driver = pt = buf; *pt && *pt != ' '; ++pt)
705 ;
706 if (*pt) { /* Device is next */
707 *pt = '\0';
708 if (!strcmp(driver, name)) { /* Match */
709 for (devstring = ++pt; *pt && *pt != ' '; ++pt)
710 ;
711 if (*pt) { /* Found busid */
712 return drmOpenByBusid(++pt, type);
713 } else { /* No busid */
714 return drmOpenDevice(strtol(devstring, NULL, 0),i, type);
715 }
716 }
717 }
718 }
719 }
720 }
721 #endif
722
723 return -1;
724 }
725
726
727 /**
728 * Open the DRM device.
729 *
730 * Looks up the specified name and bus ID, and opens the device found. The
731 * entry in /dev/dri is created if necessary and if called by root.
732 *
733 * \param name driver name. Not referenced if bus ID is supplied.
734 * \param busid bus ID. Zero if not known.
735 *
736 * \return a file descriptor on success, or a negative value on error.
737 *
738 * \internal
739 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
740 * otherwise.
741 */
drmOpen(const char * name,const char * busid)742 drm_public int drmOpen(const char *name, const char *busid)
743 {
744 return drmOpenWithType(name, busid, DRM_NODE_PRIMARY);
745 }
746
747 /**
748 * Open the DRM device with specified type.
749 *
750 * Looks up the specified name and bus ID, and opens the device found. The
751 * entry in /dev/dri is created if necessary and if called by root.
752 *
753 * \param name driver name. Not referenced if bus ID is supplied.
754 * \param busid bus ID. Zero if not known.
755 * \param type the device node type to open, PRIMARY, CONTROL or RENDER
756 *
757 * \return a file descriptor on success, or a negative value on error.
758 *
759 * \internal
760 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
761 * otherwise.
762 */
drmOpenWithType(const char * name,const char * busid,int type)763 drm_public int drmOpenWithType(const char *name, const char *busid, int type)
764 {
765 if (name != NULL && drm_server_info &&
766 drm_server_info->load_module && !drmAvailable()) {
767 /* try to load the kernel module */
768 if (!drm_server_info->load_module(name)) {
769 drmMsg("[drm] failed to load kernel module \"%s\"\n", name);
770 return -1;
771 }
772 }
773
774 if (busid) {
775 int fd = drmOpenByBusid(busid, type);
776 if (fd >= 0)
777 return fd;
778 }
779
780 if (name)
781 return drmOpenByName(name, type);
782
783 return -1;
784 }
785
drmOpenControl(int minor)786 drm_public int drmOpenControl(int minor)
787 {
788 return drmOpenMinor(minor, 0, DRM_NODE_CONTROL);
789 }
790
drmOpenRender(int minor)791 drm_public int drmOpenRender(int minor)
792 {
793 return drmOpenMinor(minor, 0, DRM_NODE_RENDER);
794 }
795
796 /**
797 * Free the version information returned by drmGetVersion().
798 *
799 * \param v pointer to the version information.
800 *
801 * \internal
802 * It frees the memory pointed by \p %v as well as all the non-null strings
803 * pointers in it.
804 */
drmFreeVersion(drmVersionPtr v)805 drm_public void drmFreeVersion(drmVersionPtr v)
806 {
807 if (!v)
808 return;
809 drmFree(v->name);
810 drmFree(v->date);
811 drmFree(v->desc);
812 drmFree(v);
813 }
814
815
816 /**
817 * Free the non-public version information returned by the kernel.
818 *
819 * \param v pointer to the version information.
820 *
821 * \internal
822 * Used by drmGetVersion() to free the memory pointed by \p %v as well as all
823 * the non-null strings pointers in it.
824 */
drmFreeKernelVersion(drm_version_t * v)825 static void drmFreeKernelVersion(drm_version_t *v)
826 {
827 if (!v)
828 return;
829 drmFree(v->name);
830 drmFree(v->date);
831 drmFree(v->desc);
832 drmFree(v);
833 }
834
835
836 /**
837 * Copy version information.
838 *
839 * \param d destination pointer.
840 * \param s source pointer.
841 *
842 * \internal
843 * Used by drmGetVersion() to translate the information returned by the ioctl
844 * interface in a private structure into the public structure counterpart.
845 */
drmCopyVersion(drmVersionPtr d,const drm_version_t * s)846 static void drmCopyVersion(drmVersionPtr d, const drm_version_t *s)
847 {
848 d->version_major = s->version_major;
849 d->version_minor = s->version_minor;
850 d->version_patchlevel = s->version_patchlevel;
851 d->name_len = s->name_len;
852 d->name = strdup(s->name);
853 d->date_len = s->date_len;
854 d->date = strdup(s->date);
855 d->desc_len = s->desc_len;
856 d->desc = strdup(s->desc);
857 }
858
859
860 /**
861 * Query the driver version information.
862 *
863 * \param fd file descriptor.
864 *
865 * \return pointer to a drmVersion structure which should be freed with
866 * drmFreeVersion().
867 *
868 * \note Similar information is available via /proc/dri.
869 *
870 * \internal
871 * It gets the version information via successive DRM_IOCTL_VERSION ioctls,
872 * first with zeros to get the string lengths, and then the actually strings.
873 * It also null-terminates them since they might not be already.
874 */
drmGetVersion(int fd)875 drm_public drmVersionPtr drmGetVersion(int fd)
876 {
877 drmVersionPtr retval;
878 drm_version_t *version = drmMalloc(sizeof(*version));
879
880 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
881 drmFreeKernelVersion(version);
882 return NULL;
883 }
884
885 if (version->name_len)
886 version->name = drmMalloc(version->name_len + 1);
887 if (version->date_len)
888 version->date = drmMalloc(version->date_len + 1);
889 if (version->desc_len)
890 version->desc = drmMalloc(version->desc_len + 1);
891
892 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
893 drmMsg("DRM_IOCTL_VERSION: %s\n", strerror(errno));
894 drmFreeKernelVersion(version);
895 return NULL;
896 }
897
898 /* The results might not be null-terminated strings, so terminate them. */
899 if (version->name_len) version->name[version->name_len] = '\0';
900 if (version->date_len) version->date[version->date_len] = '\0';
901 if (version->desc_len) version->desc[version->desc_len] = '\0';
902
903 retval = drmMalloc(sizeof(*retval));
904 drmCopyVersion(retval, version);
905 drmFreeKernelVersion(version);
906 return retval;
907 }
908
909
910 /**
911 * Get version information for the DRM user space library.
912 *
913 * This version number is driver independent.
914 *
915 * \param fd file descriptor.
916 *
917 * \return version information.
918 *
919 * \internal
920 * This function allocates and fills a drm_version structure with a hard coded
921 * version number.
922 */
drmGetLibVersion(int fd)923 drm_public drmVersionPtr drmGetLibVersion(int fd)
924 {
925 drm_version_t *version = drmMalloc(sizeof(*version));
926
927 /* Version history:
928 * NOTE THIS MUST NOT GO ABOVE VERSION 1.X due to drivers needing it
929 * revision 1.0.x = original DRM interface with no drmGetLibVersion
930 * entry point and many drm<Device> extensions
931 * revision 1.1.x = added drmCommand entry points for device extensions
932 * added drmGetLibVersion to identify libdrm.a version
933 * revision 1.2.x = added drmSetInterfaceVersion
934 * modified drmOpen to handle both busid and name
935 * revision 1.3.x = added server + memory manager
936 */
937 version->version_major = 1;
938 version->version_minor = 3;
939 version->version_patchlevel = 0;
940
941 return (drmVersionPtr)version;
942 }
943
drmGetCap(int fd,uint64_t capability,uint64_t * value)944 drm_public int drmGetCap(int fd, uint64_t capability, uint64_t *value)
945 {
946 struct drm_get_cap cap;
947 int ret;
948
949 memclear(cap);
950 cap.capability = capability;
951
952 ret = drmIoctl(fd, DRM_IOCTL_GET_CAP, &cap);
953 if (ret)
954 return ret;
955
956 *value = cap.value;
957 return 0;
958 }
959
drmSetClientCap(int fd,uint64_t capability,uint64_t value)960 drm_public int drmSetClientCap(int fd, uint64_t capability, uint64_t value)
961 {
962 struct drm_set_client_cap cap;
963
964 memclear(cap);
965 cap.capability = capability;
966 cap.value = value;
967
968 return drmIoctl(fd, DRM_IOCTL_SET_CLIENT_CAP, &cap);
969 }
970
971 /**
972 * Free the bus ID information.
973 *
974 * \param busid bus ID information string as given by drmGetBusid().
975 *
976 * \internal
977 * This function is just frees the memory pointed by \p busid.
978 */
drmFreeBusid(const char * busid)979 drm_public void drmFreeBusid(const char *busid)
980 {
981 drmFree((void *)busid);
982 }
983
984
985 /**
986 * Get the bus ID of the device.
987 *
988 * \param fd file descriptor.
989 *
990 * \return bus ID string.
991 *
992 * \internal
993 * This function gets the bus ID via successive DRM_IOCTL_GET_UNIQUE ioctls to
994 * get the string length and data, passing the arguments in a drm_unique
995 * structure.
996 */
drmGetBusid(int fd)997 drm_public char *drmGetBusid(int fd)
998 {
999 drm_unique_t u;
1000
1001 memclear(u);
1002
1003 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
1004 return NULL;
1005 u.unique = drmMalloc(u.unique_len + 1);
1006 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u)) {
1007 drmFree(u.unique);
1008 return NULL;
1009 }
1010 u.unique[u.unique_len] = '\0';
1011
1012 return u.unique;
1013 }
1014
1015
1016 /**
1017 * Set the bus ID of the device.
1018 *
1019 * \param fd file descriptor.
1020 * \param busid bus ID string.
1021 *
1022 * \return zero on success, negative on failure.
1023 *
1024 * \internal
1025 * This function is a wrapper around the DRM_IOCTL_SET_UNIQUE ioctl, passing
1026 * the arguments in a drm_unique structure.
1027 */
drmSetBusid(int fd,const char * busid)1028 drm_public int drmSetBusid(int fd, const char *busid)
1029 {
1030 drm_unique_t u;
1031
1032 memclear(u);
1033 u.unique = (char *)busid;
1034 u.unique_len = strlen(busid);
1035
1036 if (drmIoctl(fd, DRM_IOCTL_SET_UNIQUE, &u)) {
1037 return -errno;
1038 }
1039 return 0;
1040 }
1041
drmGetMagic(int fd,drm_magic_t * magic)1042 drm_public int drmGetMagic(int fd, drm_magic_t * magic)
1043 {
1044 drm_auth_t auth;
1045
1046 memclear(auth);
1047
1048 *magic = 0;
1049 if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
1050 return -errno;
1051 *magic = auth.magic;
1052 return 0;
1053 }
1054
drmAuthMagic(int fd,drm_magic_t magic)1055 drm_public int drmAuthMagic(int fd, drm_magic_t magic)
1056 {
1057 drm_auth_t auth;
1058
1059 memclear(auth);
1060 auth.magic = magic;
1061 if (drmIoctl(fd, DRM_IOCTL_AUTH_MAGIC, &auth))
1062 return -errno;
1063 return 0;
1064 }
1065
1066 /**
1067 * Specifies a range of memory that is available for mapping by a
1068 * non-root process.
1069 *
1070 * \param fd file descriptor.
1071 * \param offset usually the physical address. The actual meaning depends of
1072 * the \p type parameter. See below.
1073 * \param size of the memory in bytes.
1074 * \param type type of the memory to be mapped.
1075 * \param flags combination of several flags to modify the function actions.
1076 * \param handle will be set to a value that may be used as the offset
1077 * parameter for mmap().
1078 *
1079 * \return zero on success or a negative value on error.
1080 *
1081 * \par Mapping the frame buffer
1082 * For the frame buffer
1083 * - \p offset will be the physical address of the start of the frame buffer,
1084 * - \p size will be the size of the frame buffer in bytes, and
1085 * - \p type will be DRM_FRAME_BUFFER.
1086 *
1087 * \par
1088 * The area mapped will be uncached. If MTRR support is available in the
1089 * kernel, the frame buffer area will be set to write combining.
1090 *
1091 * \par Mapping the MMIO register area
1092 * For the MMIO register area,
1093 * - \p offset will be the physical address of the start of the register area,
1094 * - \p size will be the size of the register area bytes, and
1095 * - \p type will be DRM_REGISTERS.
1096 * \par
1097 * The area mapped will be uncached.
1098 *
1099 * \par Mapping the SAREA
1100 * For the SAREA,
1101 * - \p offset will be ignored and should be set to zero,
1102 * - \p size will be the desired size of the SAREA in bytes,
1103 * - \p type will be DRM_SHM.
1104 *
1105 * \par
1106 * A shared memory area of the requested size will be created and locked in
1107 * kernel memory. This area may be mapped into client-space by using the handle
1108 * returned.
1109 *
1110 * \note May only be called by root.
1111 *
1112 * \internal
1113 * This function is a wrapper around the DRM_IOCTL_ADD_MAP ioctl, passing
1114 * the arguments in a drm_map structure.
1115 */
drmAddMap(int fd,drm_handle_t offset,drmSize size,drmMapType type,drmMapFlags flags,drm_handle_t * handle)1116 drm_public int drmAddMap(int fd, drm_handle_t offset, drmSize size, drmMapType type,
1117 drmMapFlags flags, drm_handle_t *handle)
1118 {
1119 drm_map_t map;
1120
1121 memclear(map);
1122 map.offset = offset;
1123 map.size = size;
1124 map.type = type;
1125 map.flags = flags;
1126 if (drmIoctl(fd, DRM_IOCTL_ADD_MAP, &map))
1127 return -errno;
1128 if (handle)
1129 *handle = (drm_handle_t)(uintptr_t)map.handle;
1130 return 0;
1131 }
1132
drmRmMap(int fd,drm_handle_t handle)1133 drm_public int drmRmMap(int fd, drm_handle_t handle)
1134 {
1135 drm_map_t map;
1136
1137 memclear(map);
1138 map.handle = (void *)(uintptr_t)handle;
1139
1140 if(drmIoctl(fd, DRM_IOCTL_RM_MAP, &map))
1141 return -errno;
1142 return 0;
1143 }
1144
1145 /**
1146 * Make buffers available for DMA transfers.
1147 *
1148 * \param fd file descriptor.
1149 * \param count number of buffers.
1150 * \param size size of each buffer.
1151 * \param flags buffer allocation flags.
1152 * \param agp_offset offset in the AGP aperture
1153 *
1154 * \return number of buffers allocated, negative on error.
1155 *
1156 * \internal
1157 * This function is a wrapper around DRM_IOCTL_ADD_BUFS ioctl.
1158 *
1159 * \sa drm_buf_desc.
1160 */
drmAddBufs(int fd,int count,int size,drmBufDescFlags flags,int agp_offset)1161 drm_public int drmAddBufs(int fd, int count, int size, drmBufDescFlags flags,
1162 int agp_offset)
1163 {
1164 drm_buf_desc_t request;
1165
1166 memclear(request);
1167 request.count = count;
1168 request.size = size;
1169 request.flags = flags;
1170 request.agp_start = agp_offset;
1171
1172 if (drmIoctl(fd, DRM_IOCTL_ADD_BUFS, &request))
1173 return -errno;
1174 return request.count;
1175 }
1176
drmMarkBufs(int fd,double low,double high)1177 drm_public int drmMarkBufs(int fd, double low, double high)
1178 {
1179 drm_buf_info_t info;
1180 int i;
1181
1182 memclear(info);
1183
1184 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1185 return -EINVAL;
1186
1187 if (!info.count)
1188 return -EINVAL;
1189
1190 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1191 return -ENOMEM;
1192
1193 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1194 int retval = -errno;
1195 drmFree(info.list);
1196 return retval;
1197 }
1198
1199 for (i = 0; i < info.count; i++) {
1200 info.list[i].low_mark = low * info.list[i].count;
1201 info.list[i].high_mark = high * info.list[i].count;
1202 if (drmIoctl(fd, DRM_IOCTL_MARK_BUFS, &info.list[i])) {
1203 int retval = -errno;
1204 drmFree(info.list);
1205 return retval;
1206 }
1207 }
1208 drmFree(info.list);
1209
1210 return 0;
1211 }
1212
1213 /**
1214 * Free buffers.
1215 *
1216 * \param fd file descriptor.
1217 * \param count number of buffers to free.
1218 * \param list list of buffers to be freed.
1219 *
1220 * \return zero on success, or a negative value on failure.
1221 *
1222 * \note This function is primarily used for debugging.
1223 *
1224 * \internal
1225 * This function is a wrapper around the DRM_IOCTL_FREE_BUFS ioctl, passing
1226 * the arguments in a drm_buf_free structure.
1227 */
drmFreeBufs(int fd,int count,int * list)1228 drm_public int drmFreeBufs(int fd, int count, int *list)
1229 {
1230 drm_buf_free_t request;
1231
1232 memclear(request);
1233 request.count = count;
1234 request.list = list;
1235 if (drmIoctl(fd, DRM_IOCTL_FREE_BUFS, &request))
1236 return -errno;
1237 return 0;
1238 }
1239
1240
1241 /**
1242 * Close the device.
1243 *
1244 * \param fd file descriptor.
1245 *
1246 * \internal
1247 * This function closes the file descriptor.
1248 */
drmClose(int fd)1249 drm_public int drmClose(int fd)
1250 {
1251 unsigned long key = drmGetKeyFromFd(fd);
1252 drmHashEntry *entry = drmGetEntry(fd);
1253
1254 drmHashDestroy(entry->tagTable);
1255 entry->fd = 0;
1256 entry->f = NULL;
1257 entry->tagTable = NULL;
1258
1259 drmHashDelete(drmHashTable, key);
1260 drmFree(entry);
1261
1262 return close(fd);
1263 }
1264
1265
1266 /**
1267 * Map a region of memory.
1268 *
1269 * \param fd file descriptor.
1270 * \param handle handle returned by drmAddMap().
1271 * \param size size in bytes. Must match the size used by drmAddMap().
1272 * \param address will contain the user-space virtual address where the mapping
1273 * begins.
1274 *
1275 * \return zero on success, or a negative value on failure.
1276 *
1277 * \internal
1278 * This function is a wrapper for mmap().
1279 */
drmMap(int fd,drm_handle_t handle,drmSize size,drmAddressPtr address)1280 drm_public int drmMap(int fd, drm_handle_t handle, drmSize size,
1281 drmAddressPtr address)
1282 {
1283 static unsigned long pagesize_mask = 0;
1284
1285 if (fd < 0)
1286 return -EINVAL;
1287
1288 if (!pagesize_mask)
1289 pagesize_mask = getpagesize() - 1;
1290
1291 size = (size + pagesize_mask) & ~pagesize_mask;
1292
1293 *address = drm_mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1294 if (*address == MAP_FAILED)
1295 return -errno;
1296 return 0;
1297 }
1298
1299
1300 /**
1301 * Unmap mappings obtained with drmMap().
1302 *
1303 * \param address address as given by drmMap().
1304 * \param size size in bytes. Must match the size used by drmMap().
1305 *
1306 * \return zero on success, or a negative value on failure.
1307 *
1308 * \internal
1309 * This function is a wrapper for munmap().
1310 */
drmUnmap(drmAddress address,drmSize size)1311 drm_public int drmUnmap(drmAddress address, drmSize size)
1312 {
1313 return drm_munmap(address, size);
1314 }
1315
drmGetBufInfo(int fd)1316 drm_public drmBufInfoPtr drmGetBufInfo(int fd)
1317 {
1318 drm_buf_info_t info;
1319 drmBufInfoPtr retval;
1320 int i;
1321
1322 memclear(info);
1323
1324 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1325 return NULL;
1326
1327 if (info.count) {
1328 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1329 return NULL;
1330
1331 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1332 drmFree(info.list);
1333 return NULL;
1334 }
1335
1336 retval = drmMalloc(sizeof(*retval));
1337 retval->count = info.count;
1338 retval->list = drmMalloc(info.count * sizeof(*retval->list));
1339 for (i = 0; i < info.count; i++) {
1340 retval->list[i].count = info.list[i].count;
1341 retval->list[i].size = info.list[i].size;
1342 retval->list[i].low_mark = info.list[i].low_mark;
1343 retval->list[i].high_mark = info.list[i].high_mark;
1344 }
1345 drmFree(info.list);
1346 return retval;
1347 }
1348 return NULL;
1349 }
1350
1351 /**
1352 * Map all DMA buffers into client-virtual space.
1353 *
1354 * \param fd file descriptor.
1355 *
1356 * \return a pointer to a ::drmBufMap structure.
1357 *
1358 * \note The client may not use these buffers until obtaining buffer indices
1359 * with drmDMA().
1360 *
1361 * \internal
1362 * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1363 * information about the buffers in a drm_buf_map structure into the
1364 * client-visible data structures.
1365 */
drmMapBufs(int fd)1366 drm_public drmBufMapPtr drmMapBufs(int fd)
1367 {
1368 drm_buf_map_t bufs;
1369 drmBufMapPtr retval;
1370 int i;
1371
1372 memclear(bufs);
1373 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1374 return NULL;
1375
1376 if (!bufs.count)
1377 return NULL;
1378
1379 if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1380 return NULL;
1381
1382 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1383 drmFree(bufs.list);
1384 return NULL;
1385 }
1386
1387 retval = drmMalloc(sizeof(*retval));
1388 retval->count = bufs.count;
1389 retval->list = drmMalloc(bufs.count * sizeof(*retval->list));
1390 for (i = 0; i < bufs.count; i++) {
1391 retval->list[i].idx = bufs.list[i].idx;
1392 retval->list[i].total = bufs.list[i].total;
1393 retval->list[i].used = 0;
1394 retval->list[i].address = bufs.list[i].address;
1395 }
1396
1397 drmFree(bufs.list);
1398 return retval;
1399 }
1400
1401
1402 /**
1403 * Unmap buffers allocated with drmMapBufs().
1404 *
1405 * \return zero on success, or negative value on failure.
1406 *
1407 * \internal
1408 * Calls munmap() for every buffer stored in \p bufs and frees the
1409 * memory allocated by drmMapBufs().
1410 */
drmUnmapBufs(drmBufMapPtr bufs)1411 drm_public int drmUnmapBufs(drmBufMapPtr bufs)
1412 {
1413 int i;
1414
1415 for (i = 0; i < bufs->count; i++) {
1416 drm_munmap(bufs->list[i].address, bufs->list[i].total);
1417 }
1418
1419 drmFree(bufs->list);
1420 drmFree(bufs);
1421 return 0;
1422 }
1423
1424
1425 #define DRM_DMA_RETRY 16
1426
1427 /**
1428 * Reserve DMA buffers.
1429 *
1430 * \param fd file descriptor.
1431 * \param request
1432 *
1433 * \return zero on success, or a negative value on failure.
1434 *
1435 * \internal
1436 * Assemble the arguments into a drm_dma structure and keeps issuing the
1437 * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1438 */
drmDMA(int fd,drmDMAReqPtr request)1439 drm_public int drmDMA(int fd, drmDMAReqPtr request)
1440 {
1441 drm_dma_t dma;
1442 int ret, i = 0;
1443
1444 dma.context = request->context;
1445 dma.send_count = request->send_count;
1446 dma.send_indices = request->send_list;
1447 dma.send_sizes = request->send_sizes;
1448 dma.flags = request->flags;
1449 dma.request_count = request->request_count;
1450 dma.request_size = request->request_size;
1451 dma.request_indices = request->request_list;
1452 dma.request_sizes = request->request_sizes;
1453 dma.granted_count = 0;
1454
1455 do {
1456 ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1457 } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1458
1459 if ( ret == 0 ) {
1460 request->granted_count = dma.granted_count;
1461 return 0;
1462 } else {
1463 return -errno;
1464 }
1465 }
1466
1467
1468 /**
1469 * Obtain heavyweight hardware lock.
1470 *
1471 * \param fd file descriptor.
1472 * \param context context.
1473 * \param flags flags that determine the state of the hardware when the function
1474 * returns.
1475 *
1476 * \return always zero.
1477 *
1478 * \internal
1479 * This function translates the arguments into a drm_lock structure and issue
1480 * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1481 */
drmGetLock(int fd,drm_context_t context,drmLockFlags flags)1482 drm_public int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
1483 {
1484 drm_lock_t lock;
1485
1486 memclear(lock);
1487 lock.context = context;
1488 lock.flags = 0;
1489 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
1490 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
1491 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
1492 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
1493 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
1494 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
1495
1496 while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
1497 ;
1498 return 0;
1499 }
1500
1501 /**
1502 * Release the hardware lock.
1503 *
1504 * \param fd file descriptor.
1505 * \param context context.
1506 *
1507 * \return zero on success, or a negative value on failure.
1508 *
1509 * \internal
1510 * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
1511 * argument in a drm_lock structure.
1512 */
drmUnlock(int fd,drm_context_t context)1513 drm_public int drmUnlock(int fd, drm_context_t context)
1514 {
1515 drm_lock_t lock;
1516
1517 memclear(lock);
1518 lock.context = context;
1519 return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
1520 }
1521
drmGetReservedContextList(int fd,int * count)1522 drm_public drm_context_t *drmGetReservedContextList(int fd, int *count)
1523 {
1524 drm_ctx_res_t res;
1525 drm_ctx_t *list;
1526 drm_context_t * retval;
1527 int i;
1528
1529 memclear(res);
1530 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1531 return NULL;
1532
1533 if (!res.count)
1534 return NULL;
1535
1536 if (!(list = drmMalloc(res.count * sizeof(*list))))
1537 return NULL;
1538 if (!(retval = drmMalloc(res.count * sizeof(*retval))))
1539 goto err_free_list;
1540
1541 res.contexts = list;
1542 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1543 goto err_free_context;
1544
1545 for (i = 0; i < res.count; i++)
1546 retval[i] = list[i].handle;
1547 drmFree(list);
1548
1549 *count = res.count;
1550 return retval;
1551
1552 err_free_list:
1553 drmFree(list);
1554 err_free_context:
1555 drmFree(retval);
1556 return NULL;
1557 }
1558
drmFreeReservedContextList(drm_context_t * pt)1559 drm_public void drmFreeReservedContextList(drm_context_t *pt)
1560 {
1561 drmFree(pt);
1562 }
1563
1564 /**
1565 * Create context.
1566 *
1567 * Used by the X server during GLXContext initialization. This causes
1568 * per-context kernel-level resources to be allocated.
1569 *
1570 * \param fd file descriptor.
1571 * \param handle is set on success. To be used by the client when requesting DMA
1572 * dispatch with drmDMA().
1573 *
1574 * \return zero on success, or a negative value on failure.
1575 *
1576 * \note May only be called by root.
1577 *
1578 * \internal
1579 * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
1580 * argument in a drm_ctx structure.
1581 */
drmCreateContext(int fd,drm_context_t * handle)1582 drm_public int drmCreateContext(int fd, drm_context_t *handle)
1583 {
1584 drm_ctx_t ctx;
1585
1586 memclear(ctx);
1587 if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
1588 return -errno;
1589 *handle = ctx.handle;
1590 return 0;
1591 }
1592
drmSwitchToContext(int fd,drm_context_t context)1593 drm_public int drmSwitchToContext(int fd, drm_context_t context)
1594 {
1595 drm_ctx_t ctx;
1596
1597 memclear(ctx);
1598 ctx.handle = context;
1599 if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
1600 return -errno;
1601 return 0;
1602 }
1603
drmSetContextFlags(int fd,drm_context_t context,drm_context_tFlags flags)1604 drm_public int drmSetContextFlags(int fd, drm_context_t context,
1605 drm_context_tFlags flags)
1606 {
1607 drm_ctx_t ctx;
1608
1609 /*
1610 * Context preserving means that no context switches are done between DMA
1611 * buffers from one context and the next. This is suitable for use in the
1612 * X server (which promises to maintain hardware context), or in the
1613 * client-side library when buffers are swapped on behalf of two threads.
1614 */
1615 memclear(ctx);
1616 ctx.handle = context;
1617 if (flags & DRM_CONTEXT_PRESERVED)
1618 ctx.flags |= _DRM_CONTEXT_PRESERVED;
1619 if (flags & DRM_CONTEXT_2DONLY)
1620 ctx.flags |= _DRM_CONTEXT_2DONLY;
1621 if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
1622 return -errno;
1623 return 0;
1624 }
1625
drmGetContextFlags(int fd,drm_context_t context,drm_context_tFlagsPtr flags)1626 drm_public int drmGetContextFlags(int fd, drm_context_t context,
1627 drm_context_tFlagsPtr flags)
1628 {
1629 drm_ctx_t ctx;
1630
1631 memclear(ctx);
1632 ctx.handle = context;
1633 if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
1634 return -errno;
1635 *flags = 0;
1636 if (ctx.flags & _DRM_CONTEXT_PRESERVED)
1637 *flags |= DRM_CONTEXT_PRESERVED;
1638 if (ctx.flags & _DRM_CONTEXT_2DONLY)
1639 *flags |= DRM_CONTEXT_2DONLY;
1640 return 0;
1641 }
1642
1643 /**
1644 * Destroy context.
1645 *
1646 * Free any kernel-level resources allocated with drmCreateContext() associated
1647 * with the context.
1648 *
1649 * \param fd file descriptor.
1650 * \param handle handle given by drmCreateContext().
1651 *
1652 * \return zero on success, or a negative value on failure.
1653 *
1654 * \note May only be called by root.
1655 *
1656 * \internal
1657 * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
1658 * argument in a drm_ctx structure.
1659 */
drmDestroyContext(int fd,drm_context_t handle)1660 drm_public int drmDestroyContext(int fd, drm_context_t handle)
1661 {
1662 drm_ctx_t ctx;
1663
1664 memclear(ctx);
1665 ctx.handle = handle;
1666 if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
1667 return -errno;
1668 return 0;
1669 }
1670
drmCreateDrawable(int fd,drm_drawable_t * handle)1671 drm_public int drmCreateDrawable(int fd, drm_drawable_t *handle)
1672 {
1673 drm_draw_t draw;
1674
1675 memclear(draw);
1676 if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
1677 return -errno;
1678 *handle = draw.handle;
1679 return 0;
1680 }
1681
drmDestroyDrawable(int fd,drm_drawable_t handle)1682 drm_public int drmDestroyDrawable(int fd, drm_drawable_t handle)
1683 {
1684 drm_draw_t draw;
1685
1686 memclear(draw);
1687 draw.handle = handle;
1688 if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
1689 return -errno;
1690 return 0;
1691 }
1692
drmUpdateDrawableInfo(int fd,drm_drawable_t handle,drm_drawable_info_type_t type,unsigned int num,void * data)1693 drm_public int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
1694 drm_drawable_info_type_t type,
1695 unsigned int num, void *data)
1696 {
1697 drm_update_draw_t update;
1698
1699 memclear(update);
1700 update.handle = handle;
1701 update.type = type;
1702 update.num = num;
1703 update.data = (unsigned long long)(unsigned long)data;
1704
1705 if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
1706 return -errno;
1707
1708 return 0;
1709 }
1710
drmCrtcGetSequence(int fd,uint32_t crtcId,uint64_t * sequence,uint64_t * ns)1711 drm_public int drmCrtcGetSequence(int fd, uint32_t crtcId, uint64_t *sequence,
1712 uint64_t *ns)
1713 {
1714 struct drm_crtc_get_sequence get_seq;
1715 int ret;
1716
1717 memclear(get_seq);
1718 get_seq.crtc_id = crtcId;
1719 ret = drmIoctl(fd, DRM_IOCTL_CRTC_GET_SEQUENCE, &get_seq);
1720 if (ret)
1721 return ret;
1722
1723 if (sequence)
1724 *sequence = get_seq.sequence;
1725 if (ns)
1726 *ns = get_seq.sequence_ns;
1727 return 0;
1728 }
1729
drmCrtcQueueSequence(int fd,uint32_t crtcId,uint32_t flags,uint64_t sequence,uint64_t * sequence_queued,uint64_t user_data)1730 drm_public int drmCrtcQueueSequence(int fd, uint32_t crtcId, uint32_t flags,
1731 uint64_t sequence,
1732 uint64_t *sequence_queued,
1733 uint64_t user_data)
1734 {
1735 struct drm_crtc_queue_sequence queue_seq;
1736 int ret;
1737
1738 memclear(queue_seq);
1739 queue_seq.crtc_id = crtcId;
1740 queue_seq.flags = flags;
1741 queue_seq.sequence = sequence;
1742 queue_seq.user_data = user_data;
1743
1744 ret = drmIoctl(fd, DRM_IOCTL_CRTC_QUEUE_SEQUENCE, &queue_seq);
1745 if (ret == 0 && sequence_queued)
1746 *sequence_queued = queue_seq.sequence;
1747
1748 return ret;
1749 }
1750
1751 /**
1752 * Acquire the AGP device.
1753 *
1754 * Must be called before any of the other AGP related calls.
1755 *
1756 * \param fd file descriptor.
1757 *
1758 * \return zero on success, or a negative value on failure.
1759 *
1760 * \internal
1761 * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
1762 */
drmAgpAcquire(int fd)1763 drm_public int drmAgpAcquire(int fd)
1764 {
1765 if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
1766 return -errno;
1767 return 0;
1768 }
1769
1770
1771 /**
1772 * Release the AGP device.
1773 *
1774 * \param fd file descriptor.
1775 *
1776 * \return zero on success, or a negative value on failure.
1777 *
1778 * \internal
1779 * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
1780 */
drmAgpRelease(int fd)1781 drm_public int drmAgpRelease(int fd)
1782 {
1783 if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
1784 return -errno;
1785 return 0;
1786 }
1787
1788
1789 /**
1790 * Set the AGP mode.
1791 *
1792 * \param fd file descriptor.
1793 * \param mode AGP mode.
1794 *
1795 * \return zero on success, or a negative value on failure.
1796 *
1797 * \internal
1798 * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
1799 * argument in a drm_agp_mode structure.
1800 */
drmAgpEnable(int fd,unsigned long mode)1801 drm_public int drmAgpEnable(int fd, unsigned long mode)
1802 {
1803 drm_agp_mode_t m;
1804
1805 memclear(m);
1806 m.mode = mode;
1807 if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
1808 return -errno;
1809 return 0;
1810 }
1811
1812
1813 /**
1814 * Allocate a chunk of AGP memory.
1815 *
1816 * \param fd file descriptor.
1817 * \param size requested memory size in bytes. Will be rounded to page boundary.
1818 * \param type type of memory to allocate.
1819 * \param address if not zero, will be set to the physical address of the
1820 * allocated memory.
1821 * \param handle on success will be set to a handle of the allocated memory.
1822 *
1823 * \return zero on success, or a negative value on failure.
1824 *
1825 * \internal
1826 * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
1827 * arguments in a drm_agp_buffer structure.
1828 */
drmAgpAlloc(int fd,unsigned long size,unsigned long type,unsigned long * address,drm_handle_t * handle)1829 drm_public int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
1830 unsigned long *address, drm_handle_t *handle)
1831 {
1832 drm_agp_buffer_t b;
1833
1834 memclear(b);
1835 *handle = DRM_AGP_NO_HANDLE;
1836 b.size = size;
1837 b.type = type;
1838 if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
1839 return -errno;
1840 if (address != 0UL)
1841 *address = b.physical;
1842 *handle = b.handle;
1843 return 0;
1844 }
1845
1846
1847 /**
1848 * Free a chunk of AGP memory.
1849 *
1850 * \param fd file descriptor.
1851 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1852 *
1853 * \return zero on success, or a negative value on failure.
1854 *
1855 * \internal
1856 * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
1857 * argument in a drm_agp_buffer structure.
1858 */
drmAgpFree(int fd,drm_handle_t handle)1859 drm_public int drmAgpFree(int fd, drm_handle_t handle)
1860 {
1861 drm_agp_buffer_t b;
1862
1863 memclear(b);
1864 b.handle = handle;
1865 if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
1866 return -errno;
1867 return 0;
1868 }
1869
1870
1871 /**
1872 * Bind a chunk of AGP memory.
1873 *
1874 * \param fd file descriptor.
1875 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1876 * \param offset offset in bytes. It will round to page boundary.
1877 *
1878 * \return zero on success, or a negative value on failure.
1879 *
1880 * \internal
1881 * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
1882 * argument in a drm_agp_binding structure.
1883 */
drmAgpBind(int fd,drm_handle_t handle,unsigned long offset)1884 drm_public int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
1885 {
1886 drm_agp_binding_t b;
1887
1888 memclear(b);
1889 b.handle = handle;
1890 b.offset = offset;
1891 if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
1892 return -errno;
1893 return 0;
1894 }
1895
1896
1897 /**
1898 * Unbind a chunk of AGP memory.
1899 *
1900 * \param fd file descriptor.
1901 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1902 *
1903 * \return zero on success, or a negative value on failure.
1904 *
1905 * \internal
1906 * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
1907 * the argument in a drm_agp_binding structure.
1908 */
drmAgpUnbind(int fd,drm_handle_t handle)1909 drm_public int drmAgpUnbind(int fd, drm_handle_t handle)
1910 {
1911 drm_agp_binding_t b;
1912
1913 memclear(b);
1914 b.handle = handle;
1915 if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
1916 return -errno;
1917 return 0;
1918 }
1919
1920
1921 /**
1922 * Get AGP driver major version number.
1923 *
1924 * \param fd file descriptor.
1925 *
1926 * \return major version number on success, or a negative value on failure..
1927 *
1928 * \internal
1929 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1930 * necessary information in a drm_agp_info structure.
1931 */
drmAgpVersionMajor(int fd)1932 drm_public int drmAgpVersionMajor(int fd)
1933 {
1934 drm_agp_info_t i;
1935
1936 memclear(i);
1937
1938 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1939 return -errno;
1940 return i.agp_version_major;
1941 }
1942
1943
1944 /**
1945 * Get AGP driver minor version number.
1946 *
1947 * \param fd file descriptor.
1948 *
1949 * \return minor version number on success, or a negative value on failure.
1950 *
1951 * \internal
1952 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1953 * necessary information in a drm_agp_info structure.
1954 */
drmAgpVersionMinor(int fd)1955 drm_public int drmAgpVersionMinor(int fd)
1956 {
1957 drm_agp_info_t i;
1958
1959 memclear(i);
1960
1961 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1962 return -errno;
1963 return i.agp_version_minor;
1964 }
1965
1966
1967 /**
1968 * Get AGP mode.
1969 *
1970 * \param fd file descriptor.
1971 *
1972 * \return mode on success, or zero on failure.
1973 *
1974 * \internal
1975 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1976 * necessary information in a drm_agp_info structure.
1977 */
drmAgpGetMode(int fd)1978 drm_public unsigned long drmAgpGetMode(int fd)
1979 {
1980 drm_agp_info_t i;
1981
1982 memclear(i);
1983
1984 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1985 return 0;
1986 return i.mode;
1987 }
1988
1989
1990 /**
1991 * Get AGP aperture base.
1992 *
1993 * \param fd file descriptor.
1994 *
1995 * \return aperture base on success, zero on failure.
1996 *
1997 * \internal
1998 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1999 * necessary information in a drm_agp_info structure.
2000 */
drmAgpBase(int fd)2001 drm_public unsigned long drmAgpBase(int fd)
2002 {
2003 drm_agp_info_t i;
2004
2005 memclear(i);
2006
2007 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2008 return 0;
2009 return i.aperture_base;
2010 }
2011
2012
2013 /**
2014 * Get AGP aperture size.
2015 *
2016 * \param fd file descriptor.
2017 *
2018 * \return aperture size on success, zero on failure.
2019 *
2020 * \internal
2021 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2022 * necessary information in a drm_agp_info structure.
2023 */
drmAgpSize(int fd)2024 drm_public unsigned long drmAgpSize(int fd)
2025 {
2026 drm_agp_info_t i;
2027
2028 memclear(i);
2029
2030 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2031 return 0;
2032 return i.aperture_size;
2033 }
2034
2035
2036 /**
2037 * Get used AGP memory.
2038 *
2039 * \param fd file descriptor.
2040 *
2041 * \return memory used on success, or zero on failure.
2042 *
2043 * \internal
2044 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2045 * necessary information in a drm_agp_info structure.
2046 */
drmAgpMemoryUsed(int fd)2047 drm_public unsigned long drmAgpMemoryUsed(int fd)
2048 {
2049 drm_agp_info_t i;
2050
2051 memclear(i);
2052
2053 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2054 return 0;
2055 return i.memory_used;
2056 }
2057
2058
2059 /**
2060 * Get available AGP memory.
2061 *
2062 * \param fd file descriptor.
2063 *
2064 * \return memory available on success, or zero on failure.
2065 *
2066 * \internal
2067 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2068 * necessary information in a drm_agp_info structure.
2069 */
drmAgpMemoryAvail(int fd)2070 drm_public unsigned long drmAgpMemoryAvail(int fd)
2071 {
2072 drm_agp_info_t i;
2073
2074 memclear(i);
2075
2076 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2077 return 0;
2078 return i.memory_allowed;
2079 }
2080
2081
2082 /**
2083 * Get hardware vendor ID.
2084 *
2085 * \param fd file descriptor.
2086 *
2087 * \return vendor ID on success, or zero on failure.
2088 *
2089 * \internal
2090 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2091 * necessary information in a drm_agp_info structure.
2092 */
drmAgpVendorId(int fd)2093 drm_public unsigned int drmAgpVendorId(int fd)
2094 {
2095 drm_agp_info_t i;
2096
2097 memclear(i);
2098
2099 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2100 return 0;
2101 return i.id_vendor;
2102 }
2103
2104
2105 /**
2106 * Get hardware device ID.
2107 *
2108 * \param fd file descriptor.
2109 *
2110 * \return zero on success, or zero on failure.
2111 *
2112 * \internal
2113 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2114 * necessary information in a drm_agp_info structure.
2115 */
drmAgpDeviceId(int fd)2116 drm_public unsigned int drmAgpDeviceId(int fd)
2117 {
2118 drm_agp_info_t i;
2119
2120 memclear(i);
2121
2122 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2123 return 0;
2124 return i.id_device;
2125 }
2126
drmScatterGatherAlloc(int fd,unsigned long size,drm_handle_t * handle)2127 drm_public int drmScatterGatherAlloc(int fd, unsigned long size,
2128 drm_handle_t *handle)
2129 {
2130 drm_scatter_gather_t sg;
2131
2132 memclear(sg);
2133
2134 *handle = 0;
2135 sg.size = size;
2136 if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
2137 return -errno;
2138 *handle = sg.handle;
2139 return 0;
2140 }
2141
drmScatterGatherFree(int fd,drm_handle_t handle)2142 drm_public int drmScatterGatherFree(int fd, drm_handle_t handle)
2143 {
2144 drm_scatter_gather_t sg;
2145
2146 memclear(sg);
2147 sg.handle = handle;
2148 if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
2149 return -errno;
2150 return 0;
2151 }
2152
2153 /**
2154 * Wait for VBLANK.
2155 *
2156 * \param fd file descriptor.
2157 * \param vbl pointer to a drmVBlank structure.
2158 *
2159 * \return zero on success, or a negative value on failure.
2160 *
2161 * \internal
2162 * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
2163 */
drmWaitVBlank(int fd,drmVBlankPtr vbl)2164 drm_public int drmWaitVBlank(int fd, drmVBlankPtr vbl)
2165 {
2166 struct timespec timeout, cur;
2167 int ret;
2168
2169 ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2170 if (ret < 0) {
2171 fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
2172 goto out;
2173 }
2174 timeout.tv_sec++;
2175
2176 do {
2177 ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
2178 vbl->request.type &= ~DRM_VBLANK_RELATIVE;
2179 if (ret && errno == EINTR) {
2180 clock_gettime(CLOCK_MONOTONIC, &cur);
2181 /* Timeout after 1s */
2182 if (cur.tv_sec > timeout.tv_sec + 1 ||
2183 (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
2184 timeout.tv_nsec)) {
2185 errno = EBUSY;
2186 ret = -1;
2187 break;
2188 }
2189 }
2190 } while (ret && errno == EINTR);
2191
2192 out:
2193 return ret;
2194 }
2195
drmError(int err,const char * label)2196 drm_public int drmError(int err, const char *label)
2197 {
2198 switch (err) {
2199 case DRM_ERR_NO_DEVICE:
2200 fprintf(stderr, "%s: no device\n", label);
2201 break;
2202 case DRM_ERR_NO_ACCESS:
2203 fprintf(stderr, "%s: no access\n", label);
2204 break;
2205 case DRM_ERR_NOT_ROOT:
2206 fprintf(stderr, "%s: not root\n", label);
2207 break;
2208 case DRM_ERR_INVALID:
2209 fprintf(stderr, "%s: invalid args\n", label);
2210 break;
2211 default:
2212 if (err < 0)
2213 err = -err;
2214 fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2215 break;
2216 }
2217
2218 return 1;
2219 }
2220
2221 /**
2222 * Install IRQ handler.
2223 *
2224 * \param fd file descriptor.
2225 * \param irq IRQ number.
2226 *
2227 * \return zero on success, or a negative value on failure.
2228 *
2229 * \internal
2230 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2231 * argument in a drm_control structure.
2232 */
drmCtlInstHandler(int fd,int irq)2233 drm_public int drmCtlInstHandler(int fd, int irq)
2234 {
2235 drm_control_t ctl;
2236
2237 memclear(ctl);
2238 ctl.func = DRM_INST_HANDLER;
2239 ctl.irq = irq;
2240 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2241 return -errno;
2242 return 0;
2243 }
2244
2245
2246 /**
2247 * Uninstall IRQ handler.
2248 *
2249 * \param fd file descriptor.
2250 *
2251 * \return zero on success, or a negative value on failure.
2252 *
2253 * \internal
2254 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2255 * argument in a drm_control structure.
2256 */
drmCtlUninstHandler(int fd)2257 drm_public int drmCtlUninstHandler(int fd)
2258 {
2259 drm_control_t ctl;
2260
2261 memclear(ctl);
2262 ctl.func = DRM_UNINST_HANDLER;
2263 ctl.irq = 0;
2264 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2265 return -errno;
2266 return 0;
2267 }
2268
drmFinish(int fd,int context,drmLockFlags flags)2269 drm_public int drmFinish(int fd, int context, drmLockFlags flags)
2270 {
2271 drm_lock_t lock;
2272
2273 memclear(lock);
2274 lock.context = context;
2275 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
2276 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
2277 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
2278 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
2279 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2280 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2281 if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2282 return -errno;
2283 return 0;
2284 }
2285
2286 /**
2287 * Get IRQ from bus ID.
2288 *
2289 * \param fd file descriptor.
2290 * \param busnum bus number.
2291 * \param devnum device number.
2292 * \param funcnum function number.
2293 *
2294 * \return IRQ number on success, or a negative value on failure.
2295 *
2296 * \internal
2297 * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2298 * arguments in a drm_irq_busid structure.
2299 */
drmGetInterruptFromBusID(int fd,int busnum,int devnum,int funcnum)2300 drm_public int drmGetInterruptFromBusID(int fd, int busnum, int devnum,
2301 int funcnum)
2302 {
2303 drm_irq_busid_t p;
2304
2305 memclear(p);
2306 p.busnum = busnum;
2307 p.devnum = devnum;
2308 p.funcnum = funcnum;
2309 if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2310 return -errno;
2311 return p.irq;
2312 }
2313
drmAddContextTag(int fd,drm_context_t context,void * tag)2314 drm_public int drmAddContextTag(int fd, drm_context_t context, void *tag)
2315 {
2316 drmHashEntry *entry = drmGetEntry(fd);
2317
2318 if (drmHashInsert(entry->tagTable, context, tag)) {
2319 drmHashDelete(entry->tagTable, context);
2320 drmHashInsert(entry->tagTable, context, tag);
2321 }
2322 return 0;
2323 }
2324
drmDelContextTag(int fd,drm_context_t context)2325 drm_public int drmDelContextTag(int fd, drm_context_t context)
2326 {
2327 drmHashEntry *entry = drmGetEntry(fd);
2328
2329 return drmHashDelete(entry->tagTable, context);
2330 }
2331
drmGetContextTag(int fd,drm_context_t context)2332 drm_public void *drmGetContextTag(int fd, drm_context_t context)
2333 {
2334 drmHashEntry *entry = drmGetEntry(fd);
2335 void *value;
2336
2337 if (drmHashLookup(entry->tagTable, context, &value))
2338 return NULL;
2339
2340 return value;
2341 }
2342
drmAddContextPrivateMapping(int fd,drm_context_t ctx_id,drm_handle_t handle)2343 drm_public int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2344 drm_handle_t handle)
2345 {
2346 drm_ctx_priv_map_t map;
2347
2348 memclear(map);
2349 map.ctx_id = ctx_id;
2350 map.handle = (void *)(uintptr_t)handle;
2351
2352 if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2353 return -errno;
2354 return 0;
2355 }
2356
drmGetContextPrivateMapping(int fd,drm_context_t ctx_id,drm_handle_t * handle)2357 drm_public int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2358 drm_handle_t *handle)
2359 {
2360 drm_ctx_priv_map_t map;
2361
2362 memclear(map);
2363 map.ctx_id = ctx_id;
2364
2365 if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2366 return -errno;
2367 if (handle)
2368 *handle = (drm_handle_t)(uintptr_t)map.handle;
2369
2370 return 0;
2371 }
2372
drmGetMap(int fd,int idx,drm_handle_t * offset,drmSize * size,drmMapType * type,drmMapFlags * flags,drm_handle_t * handle,int * mtrr)2373 drm_public int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2374 drmMapType *type, drmMapFlags *flags,
2375 drm_handle_t *handle, int *mtrr)
2376 {
2377 drm_map_t map;
2378
2379 memclear(map);
2380 map.offset = idx;
2381 if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2382 return -errno;
2383 *offset = map.offset;
2384 *size = map.size;
2385 *type = map.type;
2386 *flags = map.flags;
2387 *handle = (unsigned long)map.handle;
2388 *mtrr = map.mtrr;
2389 return 0;
2390 }
2391
drmGetClient(int fd,int idx,int * auth,int * pid,int * uid,unsigned long * magic,unsigned long * iocs)2392 drm_public int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2393 unsigned long *magic, unsigned long *iocs)
2394 {
2395 drm_client_t client;
2396
2397 memclear(client);
2398 client.idx = idx;
2399 if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2400 return -errno;
2401 *auth = client.auth;
2402 *pid = client.pid;
2403 *uid = client.uid;
2404 *magic = client.magic;
2405 *iocs = client.iocs;
2406 return 0;
2407 }
2408
drmGetStats(int fd,drmStatsT * stats)2409 drm_public int drmGetStats(int fd, drmStatsT *stats)
2410 {
2411 drm_stats_t s;
2412 unsigned i;
2413
2414 memclear(s);
2415 if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2416 return -errno;
2417
2418 stats->count = 0;
2419 memset(stats, 0, sizeof(*stats));
2420 if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2421 return -1;
2422
2423 #define SET_VALUE \
2424 stats->data[i].long_format = "%-20.20s"; \
2425 stats->data[i].rate_format = "%8.8s"; \
2426 stats->data[i].isvalue = 1; \
2427 stats->data[i].verbose = 0
2428
2429 #define SET_COUNT \
2430 stats->data[i].long_format = "%-20.20s"; \
2431 stats->data[i].rate_format = "%5.5s"; \
2432 stats->data[i].isvalue = 0; \
2433 stats->data[i].mult_names = "kgm"; \
2434 stats->data[i].mult = 1000; \
2435 stats->data[i].verbose = 0
2436
2437 #define SET_BYTE \
2438 stats->data[i].long_format = "%-20.20s"; \
2439 stats->data[i].rate_format = "%5.5s"; \
2440 stats->data[i].isvalue = 0; \
2441 stats->data[i].mult_names = "KGM"; \
2442 stats->data[i].mult = 1024; \
2443 stats->data[i].verbose = 0
2444
2445
2446 stats->count = s.count;
2447 for (i = 0; i < s.count; i++) {
2448 stats->data[i].value = s.data[i].value;
2449 switch (s.data[i].type) {
2450 case _DRM_STAT_LOCK:
2451 stats->data[i].long_name = "Lock";
2452 stats->data[i].rate_name = "Lock";
2453 SET_VALUE;
2454 break;
2455 case _DRM_STAT_OPENS:
2456 stats->data[i].long_name = "Opens";
2457 stats->data[i].rate_name = "O";
2458 SET_COUNT;
2459 stats->data[i].verbose = 1;
2460 break;
2461 case _DRM_STAT_CLOSES:
2462 stats->data[i].long_name = "Closes";
2463 stats->data[i].rate_name = "Lock";
2464 SET_COUNT;
2465 stats->data[i].verbose = 1;
2466 break;
2467 case _DRM_STAT_IOCTLS:
2468 stats->data[i].long_name = "Ioctls";
2469 stats->data[i].rate_name = "Ioc/s";
2470 SET_COUNT;
2471 break;
2472 case _DRM_STAT_LOCKS:
2473 stats->data[i].long_name = "Locks";
2474 stats->data[i].rate_name = "Lck/s";
2475 SET_COUNT;
2476 break;
2477 case _DRM_STAT_UNLOCKS:
2478 stats->data[i].long_name = "Unlocks";
2479 stats->data[i].rate_name = "Unl/s";
2480 SET_COUNT;
2481 break;
2482 case _DRM_STAT_IRQ:
2483 stats->data[i].long_name = "IRQs";
2484 stats->data[i].rate_name = "IRQ/s";
2485 SET_COUNT;
2486 break;
2487 case _DRM_STAT_PRIMARY:
2488 stats->data[i].long_name = "Primary Bytes";
2489 stats->data[i].rate_name = "PB/s";
2490 SET_BYTE;
2491 break;
2492 case _DRM_STAT_SECONDARY:
2493 stats->data[i].long_name = "Secondary Bytes";
2494 stats->data[i].rate_name = "SB/s";
2495 SET_BYTE;
2496 break;
2497 case _DRM_STAT_DMA:
2498 stats->data[i].long_name = "DMA";
2499 stats->data[i].rate_name = "DMA/s";
2500 SET_COUNT;
2501 break;
2502 case _DRM_STAT_SPECIAL:
2503 stats->data[i].long_name = "Special DMA";
2504 stats->data[i].rate_name = "dma/s";
2505 SET_COUNT;
2506 break;
2507 case _DRM_STAT_MISSED:
2508 stats->data[i].long_name = "Miss";
2509 stats->data[i].rate_name = "Ms/s";
2510 SET_COUNT;
2511 break;
2512 case _DRM_STAT_VALUE:
2513 stats->data[i].long_name = "Value";
2514 stats->data[i].rate_name = "Value";
2515 SET_VALUE;
2516 break;
2517 case _DRM_STAT_BYTE:
2518 stats->data[i].long_name = "Bytes";
2519 stats->data[i].rate_name = "B/s";
2520 SET_BYTE;
2521 break;
2522 case _DRM_STAT_COUNT:
2523 default:
2524 stats->data[i].long_name = "Count";
2525 stats->data[i].rate_name = "Cnt/s";
2526 SET_COUNT;
2527 break;
2528 }
2529 }
2530 return 0;
2531 }
2532
2533 /**
2534 * Issue a set-version ioctl.
2535 *
2536 * \param fd file descriptor.
2537 * \param drmCommandIndex command index
2538 * \param data source pointer of the data to be read and written.
2539 * \param size size of the data to be read and written.
2540 *
2541 * \return zero on success, or a negative value on failure.
2542 *
2543 * \internal
2544 * It issues a read-write ioctl given by
2545 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2546 */
drmSetInterfaceVersion(int fd,drmSetVersion * version)2547 drm_public int drmSetInterfaceVersion(int fd, drmSetVersion *version)
2548 {
2549 int retcode = 0;
2550 drm_set_version_t sv;
2551
2552 memclear(sv);
2553 sv.drm_di_major = version->drm_di_major;
2554 sv.drm_di_minor = version->drm_di_minor;
2555 sv.drm_dd_major = version->drm_dd_major;
2556 sv.drm_dd_minor = version->drm_dd_minor;
2557
2558 if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
2559 retcode = -errno;
2560 }
2561
2562 version->drm_di_major = sv.drm_di_major;
2563 version->drm_di_minor = sv.drm_di_minor;
2564 version->drm_dd_major = sv.drm_dd_major;
2565 version->drm_dd_minor = sv.drm_dd_minor;
2566
2567 return retcode;
2568 }
2569
2570 /**
2571 * Send a device-specific command.
2572 *
2573 * \param fd file descriptor.
2574 * \param drmCommandIndex command index
2575 *
2576 * \return zero on success, or a negative value on failure.
2577 *
2578 * \internal
2579 * It issues a ioctl given by
2580 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2581 */
drmCommandNone(int fd,unsigned long drmCommandIndex)2582 drm_public int drmCommandNone(int fd, unsigned long drmCommandIndex)
2583 {
2584 unsigned long request;
2585
2586 request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
2587
2588 if (drmIoctl(fd, request, NULL)) {
2589 return -errno;
2590 }
2591 return 0;
2592 }
2593
2594
2595 /**
2596 * Send a device-specific read command.
2597 *
2598 * \param fd file descriptor.
2599 * \param drmCommandIndex command index
2600 * \param data destination pointer of the data to be read.
2601 * \param size size of the data to be read.
2602 *
2603 * \return zero on success, or a negative value on failure.
2604 *
2605 * \internal
2606 * It issues a read ioctl given by
2607 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2608 */
drmCommandRead(int fd,unsigned long drmCommandIndex,void * data,unsigned long size)2609 drm_public int drmCommandRead(int fd, unsigned long drmCommandIndex,
2610 void *data, unsigned long size)
2611 {
2612 unsigned long request;
2613
2614 request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
2615 DRM_COMMAND_BASE + drmCommandIndex, size);
2616
2617 if (drmIoctl(fd, request, data)) {
2618 return -errno;
2619 }
2620 return 0;
2621 }
2622
2623
2624 /**
2625 * Send a device-specific write command.
2626 *
2627 * \param fd file descriptor.
2628 * \param drmCommandIndex command index
2629 * \param data source pointer of the data to be written.
2630 * \param size size of the data to be written.
2631 *
2632 * \return zero on success, or a negative value on failure.
2633 *
2634 * \internal
2635 * It issues a write ioctl given by
2636 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2637 */
drmCommandWrite(int fd,unsigned long drmCommandIndex,void * data,unsigned long size)2638 drm_public int drmCommandWrite(int fd, unsigned long drmCommandIndex,
2639 void *data, unsigned long size)
2640 {
2641 unsigned long request;
2642
2643 request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
2644 DRM_COMMAND_BASE + drmCommandIndex, size);
2645
2646 if (drmIoctl(fd, request, data)) {
2647 return -errno;
2648 }
2649 return 0;
2650 }
2651
2652
2653 /**
2654 * Send a device-specific read-write command.
2655 *
2656 * \param fd file descriptor.
2657 * \param drmCommandIndex command index
2658 * \param data source pointer of the data to be read and written.
2659 * \param size size of the data to be read and written.
2660 *
2661 * \return zero on success, or a negative value on failure.
2662 *
2663 * \internal
2664 * It issues a read-write ioctl given by
2665 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2666 */
drmCommandWriteRead(int fd,unsigned long drmCommandIndex,void * data,unsigned long size)2667 drm_public int drmCommandWriteRead(int fd, unsigned long drmCommandIndex,
2668 void *data, unsigned long size)
2669 {
2670 unsigned long request;
2671
2672 request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
2673 DRM_COMMAND_BASE + drmCommandIndex, size);
2674
2675 if (drmIoctl(fd, request, data))
2676 return -errno;
2677 return 0;
2678 }
2679
2680 #define DRM_MAX_FDS 16
2681 static struct {
2682 char *BusID;
2683 int fd;
2684 int refcount;
2685 int type;
2686 } connection[DRM_MAX_FDS];
2687
2688 static int nr_fds = 0;
2689
drmOpenOnce(void * unused,const char * BusID,int * newlyopened)2690 drm_public int drmOpenOnce(void *unused, const char *BusID, int *newlyopened)
2691 {
2692 return drmOpenOnceWithType(BusID, newlyopened, DRM_NODE_PRIMARY);
2693 }
2694
drmOpenOnceWithType(const char * BusID,int * newlyopened,int type)2695 drm_public int drmOpenOnceWithType(const char *BusID, int *newlyopened,
2696 int type)
2697 {
2698 int i;
2699 int fd;
2700
2701 for (i = 0; i < nr_fds; i++)
2702 if ((strcmp(BusID, connection[i].BusID) == 0) &&
2703 (connection[i].type == type)) {
2704 connection[i].refcount++;
2705 *newlyopened = 0;
2706 return connection[i].fd;
2707 }
2708
2709 fd = drmOpenWithType(NULL, BusID, type);
2710 if (fd < 0 || nr_fds == DRM_MAX_FDS)
2711 return fd;
2712
2713 connection[nr_fds].BusID = strdup(BusID);
2714 connection[nr_fds].fd = fd;
2715 connection[nr_fds].refcount = 1;
2716 connection[nr_fds].type = type;
2717 *newlyopened = 1;
2718
2719 if (0)
2720 fprintf(stderr, "saved connection %d for %s %d\n",
2721 nr_fds, connection[nr_fds].BusID,
2722 strcmp(BusID, connection[nr_fds].BusID));
2723
2724 nr_fds++;
2725
2726 return fd;
2727 }
2728
drmCloseOnce(int fd)2729 drm_public void drmCloseOnce(int fd)
2730 {
2731 int i;
2732
2733 for (i = 0; i < nr_fds; i++) {
2734 if (fd == connection[i].fd) {
2735 if (--connection[i].refcount == 0) {
2736 drmClose(connection[i].fd);
2737 free(connection[i].BusID);
2738
2739 if (i < --nr_fds)
2740 connection[i] = connection[nr_fds];
2741
2742 return;
2743 }
2744 }
2745 }
2746 }
2747
drmSetMaster(int fd)2748 drm_public int drmSetMaster(int fd)
2749 {
2750 return drmIoctl(fd, DRM_IOCTL_SET_MASTER, NULL);
2751 }
2752
drmDropMaster(int fd)2753 drm_public int drmDropMaster(int fd)
2754 {
2755 return drmIoctl(fd, DRM_IOCTL_DROP_MASTER, NULL);
2756 }
2757
drmIsMaster(int fd)2758 drm_public int drmIsMaster(int fd)
2759 {
2760 /* Detect master by attempting something that requires master.
2761 *
2762 * Authenticating magic tokens requires master and 0 is an
2763 * internal kernel detail which we could use. Attempting this on
2764 * a master fd would fail therefore fail with EINVAL because 0
2765 * is invalid.
2766 *
2767 * A non-master fd will fail with EACCES, as the kernel checks
2768 * for master before attempting to do anything else.
2769 *
2770 * Since we don't want to leak implementation details, use
2771 * EACCES.
2772 */
2773 return drmAuthMagic(fd, 0) != -EACCES;
2774 }
2775
drmGetDeviceNameFromFd(int fd)2776 drm_public char *drmGetDeviceNameFromFd(int fd)
2777 {
2778 #ifdef __FreeBSD__
2779 struct stat sbuf;
2780 int maj, min;
2781 int nodetype;
2782
2783 if (fstat(fd, &sbuf))
2784 return NULL;
2785
2786 maj = major(sbuf.st_rdev);
2787 min = minor(sbuf.st_rdev);
2788 nodetype = drmGetMinorType(maj, min);
2789 return drmGetMinorNameForFD(fd, nodetype);
2790 #else
2791 char name[128];
2792 struct stat sbuf;
2793 dev_t d;
2794 int i;
2795
2796 /* The whole drmOpen thing is a fiasco and we need to find a way
2797 * back to just using open(2). For now, however, lets just make
2798 * things worse with even more ad hoc directory walking code to
2799 * discover the device file name. */
2800
2801 fstat(fd, &sbuf);
2802 d = sbuf.st_rdev;
2803
2804 for (i = 0; i < DRM_MAX_MINOR; i++) {
2805 snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
2806 if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
2807 break;
2808 }
2809 if (i == DRM_MAX_MINOR)
2810 return NULL;
2811
2812 return strdup(name);
2813 #endif
2814 }
2815
drmNodeIsDRM(int maj,int min)2816 static bool drmNodeIsDRM(int maj, int min)
2817 {
2818 #ifdef __linux__
2819 char path[64];
2820 struct stat sbuf;
2821
2822 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device/drm",
2823 maj, min);
2824 return stat(path, &sbuf) == 0;
2825 #elif __FreeBSD__
2826 char name[SPECNAMELEN];
2827
2828 if (!devname_r(makedev(maj, min), S_IFCHR, name, sizeof(name)))
2829 return 0;
2830 /* Handle drm/ and dri/ as both are present in different FreeBSD version
2831 * FreeBSD on amd64/i386/powerpc external kernel modules create node in
2832 * in /dev/drm/ and links in /dev/dri while a WIP in kernel driver creates
2833 * only device nodes in /dev/dri/ */
2834 return (!strncmp(name, "drm/", 4) || !strncmp(name, "dri/", 4));
2835 #else
2836 return maj == DRM_MAJOR;
2837 #endif
2838 }
2839
drmGetNodeTypeFromFd(int fd)2840 drm_public int drmGetNodeTypeFromFd(int fd)
2841 {
2842 struct stat sbuf;
2843 int maj, min, type;
2844
2845 if (fstat(fd, &sbuf))
2846 return -1;
2847
2848 maj = major(sbuf.st_rdev);
2849 min = minor(sbuf.st_rdev);
2850
2851 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode)) {
2852 errno = EINVAL;
2853 return -1;
2854 }
2855
2856 type = drmGetMinorType(maj, min);
2857 if (type == -1)
2858 errno = ENODEV;
2859 return type;
2860 }
2861
drmPrimeHandleToFD(int fd,uint32_t handle,uint32_t flags,int * prime_fd)2862 drm_public int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags,
2863 int *prime_fd)
2864 {
2865 struct drm_prime_handle args;
2866 int ret;
2867
2868 memclear(args);
2869 args.fd = -1;
2870 args.handle = handle;
2871 args.flags = flags;
2872 ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
2873 if (ret)
2874 return ret;
2875
2876 *prime_fd = args.fd;
2877 return 0;
2878 }
2879
drmPrimeFDToHandle(int fd,int prime_fd,uint32_t * handle)2880 drm_public int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
2881 {
2882 struct drm_prime_handle args;
2883 int ret;
2884
2885 memclear(args);
2886 args.fd = prime_fd;
2887 ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
2888 if (ret)
2889 return ret;
2890
2891 *handle = args.handle;
2892 return 0;
2893 }
2894
drmGetMinorNameForFD(int fd,int type)2895 static char *drmGetMinorNameForFD(int fd, int type)
2896 {
2897 #ifdef __linux__
2898 DIR *sysdir;
2899 struct dirent *ent;
2900 struct stat sbuf;
2901 const char *name = drmGetMinorName(type);
2902 int len;
2903 char dev_name[64], buf[64];
2904 int maj, min;
2905
2906 if (!name)
2907 return NULL;
2908
2909 len = strlen(name);
2910
2911 if (fstat(fd, &sbuf))
2912 return NULL;
2913
2914 maj = major(sbuf.st_rdev);
2915 min = minor(sbuf.st_rdev);
2916
2917 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
2918 return NULL;
2919
2920 snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
2921
2922 sysdir = opendir(buf);
2923 if (!sysdir)
2924 return NULL;
2925
2926 while ((ent = readdir(sysdir))) {
2927 if (strncmp(ent->d_name, name, len) == 0) {
2928 snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
2929 ent->d_name);
2930
2931 closedir(sysdir);
2932 return strdup(dev_name);
2933 }
2934 }
2935
2936 closedir(sysdir);
2937 return NULL;
2938 #elif __FreeBSD__
2939 struct stat sbuf;
2940 char dname[SPECNAMELEN];
2941 const char *mname;
2942 char name[SPECNAMELEN];
2943 int id, maj, min, nodetype, i;
2944
2945 if (fstat(fd, &sbuf))
2946 return NULL;
2947
2948 maj = major(sbuf.st_rdev);
2949 min = minor(sbuf.st_rdev);
2950
2951 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
2952 return NULL;
2953
2954 if (!devname_r(sbuf.st_rdev, S_IFCHR, dname, sizeof(dname)))
2955 return NULL;
2956
2957 /* Handle both /dev/drm and /dev/dri
2958 * FreeBSD on amd64/i386/powerpc external kernel modules create node in
2959 * in /dev/drm/ and links in /dev/dri while a WIP in kernel driver creates
2960 * only device nodes in /dev/dri/ */
2961
2962 /* Get the node type represented by fd so we can deduce the target name */
2963 nodetype = drmGetMinorType(maj, min);
2964 if (nodetype == -1)
2965 return (NULL);
2966 mname = drmGetMinorName(type);
2967
2968 for (i = 0; i < SPECNAMELEN; i++) {
2969 if (isalpha(dname[i]) == 0 && dname[i] != '/')
2970 break;
2971 }
2972 if (dname[i] == '\0')
2973 return (NULL);
2974
2975 id = (int)strtol(&dname[i], NULL, 10);
2976 id -= drmGetMinorBase(nodetype);
2977 snprintf(name, sizeof(name), DRM_DIR_NAME "/%s%d", mname,
2978 id + drmGetMinorBase(type));
2979
2980 return strdup(name);
2981 #else
2982 struct stat sbuf;
2983 char buf[PATH_MAX + 1];
2984 const char *dev_name = drmGetDeviceName(type);
2985 unsigned int maj, min;
2986 int n;
2987
2988 if (fstat(fd, &sbuf))
2989 return NULL;
2990
2991 maj = major(sbuf.st_rdev);
2992 min = minor(sbuf.st_rdev);
2993
2994 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
2995 return NULL;
2996
2997 if (!dev_name)
2998 return NULL;
2999
3000 n = snprintf(buf, sizeof(buf), dev_name, DRM_DIR_NAME, min);
3001 if (n == -1 || n >= sizeof(buf))
3002 return NULL;
3003
3004 return strdup(buf);
3005 #endif
3006 }
3007
drmGetPrimaryDeviceNameFromFd(int fd)3008 drm_public char *drmGetPrimaryDeviceNameFromFd(int fd)
3009 {
3010 return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
3011 }
3012
drmGetRenderDeviceNameFromFd(int fd)3013 drm_public char *drmGetRenderDeviceNameFromFd(int fd)
3014 {
3015 return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
3016 }
3017
3018 #ifdef __linux__
3019 static char * DRM_PRINTFLIKE(2, 3)
sysfs_uevent_get(const char * path,const char * fmt,...)3020 sysfs_uevent_get(const char *path, const char *fmt, ...)
3021 {
3022 char filename[PATH_MAX + 1], *key, *line = NULL, *value = NULL;
3023 size_t size = 0, len;
3024 ssize_t num;
3025 va_list ap;
3026 FILE *fp;
3027
3028 va_start(ap, fmt);
3029 num = vasprintf(&key, fmt, ap);
3030 va_end(ap);
3031 len = num;
3032
3033 snprintf(filename, sizeof(filename), "%s/uevent", path);
3034
3035 fp = fopen(filename, "r");
3036 if (!fp) {
3037 free(key);
3038 return NULL;
3039 }
3040
3041 while ((num = getline(&line, &size, fp)) >= 0) {
3042 if ((strncmp(line, key, len) == 0) && (line[len] == '=')) {
3043 char *start = line + len + 1, *end = line + num - 1;
3044
3045 if (*end != '\n')
3046 end++;
3047
3048 value = strndup(start, end - start);
3049 break;
3050 }
3051 }
3052
3053 free(line);
3054 fclose(fp);
3055
3056 free(key);
3057
3058 return value;
3059 }
3060 #endif
3061
3062 /* Little white lie to avoid major rework of the existing code */
3063 #define DRM_BUS_VIRTIO 0x10
3064
3065 #ifdef __linux__
get_subsystem_type(const char * device_path)3066 static int get_subsystem_type(const char *device_path)
3067 {
3068 char path[PATH_MAX + 1] = "";
3069 char link[PATH_MAX + 1] = "";
3070 char *name;
3071 struct {
3072 const char *name;
3073 int bus_type;
3074 } bus_types[] = {
3075 { "/pci", DRM_BUS_PCI },
3076 { "/usb", DRM_BUS_USB },
3077 { "/platform", DRM_BUS_PLATFORM },
3078 { "/spi", DRM_BUS_PLATFORM },
3079 { "/host1x", DRM_BUS_HOST1X },
3080 { "/virtio", DRM_BUS_VIRTIO },
3081 };
3082
3083 strncpy(path, device_path, PATH_MAX);
3084 strncat(path, "/subsystem", PATH_MAX);
3085
3086 if (readlink(path, link, PATH_MAX) < 0)
3087 return -errno;
3088
3089 name = strrchr(link, '/');
3090 if (!name)
3091 return -EINVAL;
3092
3093 for (unsigned i = 0; i < ARRAY_SIZE(bus_types); i++) {
3094 if (strncmp(name, bus_types[i].name, strlen(bus_types[i].name)) == 0)
3095 return bus_types[i].bus_type;
3096 }
3097
3098 return -EINVAL;
3099 }
3100 #endif
3101
drmParseSubsystemType(int maj,int min)3102 static int drmParseSubsystemType(int maj, int min)
3103 {
3104 #ifdef __linux__
3105 char path[PATH_MAX + 1] = "";
3106 char real_path[PATH_MAX + 1] = "";
3107 int subsystem_type;
3108
3109 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3110
3111 subsystem_type = get_subsystem_type(path);
3112 /* Try to get the parent (underlying) device type */
3113 if (subsystem_type == DRM_BUS_VIRTIO) {
3114 /* Assume virtio-pci on error */
3115 if (!realpath(path, real_path))
3116 return DRM_BUS_VIRTIO;
3117 strncat(path, "/..", PATH_MAX);
3118 subsystem_type = get_subsystem_type(path);
3119 if (subsystem_type < 0)
3120 return DRM_BUS_VIRTIO;
3121 }
3122 return subsystem_type;
3123 #elif defined(__OpenBSD__) || defined(__DragonFly__) || defined(__FreeBSD__)
3124 return DRM_BUS_PCI;
3125 #else
3126 #warning "Missing implementation of drmParseSubsystemType"
3127 return -EINVAL;
3128 #endif
3129 }
3130
3131 #ifdef __linux__
3132 static void
get_pci_path(int maj,int min,char * pci_path)3133 get_pci_path(int maj, int min, char *pci_path)
3134 {
3135 char path[PATH_MAX + 1], *term;
3136
3137 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3138 if (!realpath(path, pci_path)) {
3139 strcpy(pci_path, path);
3140 return;
3141 }
3142
3143 term = strrchr(pci_path, '/');
3144 if (term && strncmp(term, "/virtio", 7) == 0)
3145 *term = 0;
3146 }
3147 #endif
3148
3149 #ifdef __FreeBSD__
get_sysctl_pci_bus_info(int maj,int min,drmPciBusInfoPtr info)3150 static int get_sysctl_pci_bus_info(int maj, int min, drmPciBusInfoPtr info)
3151 {
3152 char dname[SPECNAMELEN];
3153 char sysctl_name[16];
3154 char sysctl_val[256];
3155 size_t sysctl_len;
3156 int id, type, nelem;
3157 unsigned int rdev, majmin, domain, bus, dev, func;
3158
3159 rdev = makedev(maj, min);
3160 if (!devname_r(rdev, S_IFCHR, dname, sizeof(dname)))
3161 return -EINVAL;
3162
3163 if (sscanf(dname, "drm/%d\n", &id) != 1)
3164 return -EINVAL;
3165 type = drmGetMinorType(maj, min);
3166 if (type == -1)
3167 return -EINVAL;
3168
3169 /* BUG: This above section is iffy, since it mandates that a driver will
3170 * create both card and render node.
3171 * If it does not, the next DRM device will create card#X and
3172 * renderD#(128+X)-1.
3173 * This is a possibility in FreeBSD but for now there is no good way for
3174 * obtaining the info.
3175 */
3176 switch (type) {
3177 case DRM_NODE_PRIMARY:
3178 break;
3179 case DRM_NODE_CONTROL:
3180 id -= 64;
3181 break;
3182 case DRM_NODE_RENDER:
3183 id -= 128;
3184 break;
3185 }
3186 if (id < 0)
3187 return -EINVAL;
3188
3189 if (snprintf(sysctl_name, sizeof(sysctl_name), "hw.dri.%d.busid", id) <= 0)
3190 return -EINVAL;
3191 sysctl_len = sizeof(sysctl_val);
3192 if (sysctlbyname(sysctl_name, sysctl_val, &sysctl_len, NULL, 0))
3193 return -EINVAL;
3194
3195 #define bus_fmt "pci:%04x:%02x:%02x.%u"
3196
3197 nelem = sscanf(sysctl_val, bus_fmt, &domain, &bus, &dev, &func);
3198 if (nelem != 4)
3199 return -EINVAL;
3200 info->domain = domain;
3201 info->bus = bus;
3202 info->dev = dev;
3203 info->func = func;
3204
3205 return 0;
3206 }
3207 #endif
3208
drmParsePciBusInfo(int maj,int min,drmPciBusInfoPtr info)3209 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
3210 {
3211 #ifdef __linux__
3212 unsigned int domain, bus, dev, func;
3213 char pci_path[PATH_MAX + 1], *value;
3214 int num;
3215
3216 get_pci_path(maj, min, pci_path);
3217
3218 value = sysfs_uevent_get(pci_path, "PCI_SLOT_NAME");
3219 if (!value)
3220 return -ENOENT;
3221
3222 num = sscanf(value, "%04x:%02x:%02x.%1u", &domain, &bus, &dev, &func);
3223 free(value);
3224
3225 if (num != 4)
3226 return -EINVAL;
3227
3228 info->domain = domain;
3229 info->bus = bus;
3230 info->dev = dev;
3231 info->func = func;
3232
3233 return 0;
3234 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3235 struct drm_pciinfo pinfo;
3236 int fd, type;
3237
3238 type = drmGetMinorType(maj, min);
3239 if (type == -1)
3240 return -ENODEV;
3241
3242 fd = drmOpenMinor(min, 0, type);
3243 if (fd < 0)
3244 return -errno;
3245
3246 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3247 close(fd);
3248 return -errno;
3249 }
3250 close(fd);
3251
3252 info->domain = pinfo.domain;
3253 info->bus = pinfo.bus;
3254 info->dev = pinfo.dev;
3255 info->func = pinfo.func;
3256
3257 return 0;
3258 #elif __FreeBSD__
3259 return get_sysctl_pci_bus_info(maj, min, info);
3260 #else
3261 #warning "Missing implementation of drmParsePciBusInfo"
3262 return -EINVAL;
3263 #endif
3264 }
3265
drmDevicesEqual(drmDevicePtr a,drmDevicePtr b)3266 drm_public int drmDevicesEqual(drmDevicePtr a, drmDevicePtr b)
3267 {
3268 if (a == NULL || b == NULL)
3269 return 0;
3270
3271 if (a->bustype != b->bustype)
3272 return 0;
3273
3274 switch (a->bustype) {
3275 case DRM_BUS_PCI:
3276 return memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo)) == 0;
3277
3278 case DRM_BUS_USB:
3279 return memcmp(a->businfo.usb, b->businfo.usb, sizeof(drmUsbBusInfo)) == 0;
3280
3281 case DRM_BUS_PLATFORM:
3282 return memcmp(a->businfo.platform, b->businfo.platform, sizeof(drmPlatformBusInfo)) == 0;
3283
3284 case DRM_BUS_HOST1X:
3285 return memcmp(a->businfo.host1x, b->businfo.host1x, sizeof(drmHost1xBusInfo)) == 0;
3286
3287 default:
3288 break;
3289 }
3290
3291 return 0;
3292 }
3293
drmGetNodeType(const char * name)3294 static int drmGetNodeType(const char *name)
3295 {
3296 if (strncmp(name, DRM_CONTROL_MINOR_NAME,
3297 sizeof(DRM_CONTROL_MINOR_NAME ) - 1) == 0)
3298 return DRM_NODE_CONTROL;
3299
3300 if (strncmp(name, DRM_RENDER_MINOR_NAME,
3301 sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
3302 return DRM_NODE_RENDER;
3303
3304 if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
3305 sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
3306 return DRM_NODE_PRIMARY;
3307
3308 return -EINVAL;
3309 }
3310
drmGetMaxNodeName(void)3311 static int drmGetMaxNodeName(void)
3312 {
3313 return sizeof(DRM_DIR_NAME) +
3314 MAX3(sizeof(DRM_PRIMARY_MINOR_NAME),
3315 sizeof(DRM_CONTROL_MINOR_NAME),
3316 sizeof(DRM_RENDER_MINOR_NAME)) +
3317 3 /* length of the node number */;
3318 }
3319
3320 #ifdef __linux__
parse_separate_sysfs_files(int maj,int min,drmPciDeviceInfoPtr device,bool ignore_revision)3321 static int parse_separate_sysfs_files(int maj, int min,
3322 drmPciDeviceInfoPtr device,
3323 bool ignore_revision)
3324 {
3325 static const char *attrs[] = {
3326 "revision", /* Older kernels are missing the file, so check for it first */
3327 "vendor",
3328 "device",
3329 "subsystem_vendor",
3330 "subsystem_device",
3331 };
3332 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3333 unsigned int data[ARRAY_SIZE(attrs)];
3334 FILE *fp;
3335 int ret;
3336
3337 get_pci_path(maj, min, pci_path);
3338
3339 for (unsigned i = ignore_revision ? 1 : 0; i < ARRAY_SIZE(attrs); i++) {
3340 snprintf(path, PATH_MAX, "%s/%s", pci_path, attrs[i]);
3341 fp = fopen(path, "r");
3342 if (!fp)
3343 return -errno;
3344
3345 ret = fscanf(fp, "%x", &data[i]);
3346 fclose(fp);
3347 if (ret != 1)
3348 return -errno;
3349
3350 }
3351
3352 device->revision_id = ignore_revision ? 0xff : data[0] & 0xff;
3353 device->vendor_id = data[1] & 0xffff;
3354 device->device_id = data[2] & 0xffff;
3355 device->subvendor_id = data[3] & 0xffff;
3356 device->subdevice_id = data[4] & 0xffff;
3357
3358 return 0;
3359 }
3360
parse_config_sysfs_file(int maj,int min,drmPciDeviceInfoPtr device)3361 static int parse_config_sysfs_file(int maj, int min,
3362 drmPciDeviceInfoPtr device)
3363 {
3364 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3365 unsigned char config[64];
3366 int fd, ret;
3367
3368 get_pci_path(maj, min, pci_path);
3369
3370 snprintf(path, PATH_MAX, "%s/config", pci_path);
3371 fd = open(path, O_RDONLY);
3372 if (fd < 0)
3373 return -errno;
3374
3375 ret = read(fd, config, sizeof(config));
3376 close(fd);
3377 if (ret < 0)
3378 return -errno;
3379
3380 device->vendor_id = config[0] | (config[1] << 8);
3381 device->device_id = config[2] | (config[3] << 8);
3382 device->revision_id = config[8];
3383 device->subvendor_id = config[44] | (config[45] << 8);
3384 device->subdevice_id = config[46] | (config[47] << 8);
3385
3386 return 0;
3387 }
3388 #endif
3389
drmParsePciDeviceInfo(int maj,int min,drmPciDeviceInfoPtr device,uint32_t flags)3390 static int drmParsePciDeviceInfo(int maj, int min,
3391 drmPciDeviceInfoPtr device,
3392 uint32_t flags)
3393 {
3394 #ifdef __linux__
3395 if (!(flags & DRM_DEVICE_GET_PCI_REVISION))
3396 return parse_separate_sysfs_files(maj, min, device, true);
3397
3398 if (parse_separate_sysfs_files(maj, min, device, false))
3399 return parse_config_sysfs_file(maj, min, device);
3400
3401 return 0;
3402 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3403 struct drm_pciinfo pinfo;
3404 int fd, type;
3405
3406 type = drmGetMinorType(maj, min);
3407 if (type == -1)
3408 return -ENODEV;
3409
3410 fd = drmOpenMinor(min, 0, type);
3411 if (fd < 0)
3412 return -errno;
3413
3414 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3415 close(fd);
3416 return -errno;
3417 }
3418 close(fd);
3419
3420 device->vendor_id = pinfo.vendor_id;
3421 device->device_id = pinfo.device_id;
3422 device->revision_id = pinfo.revision_id;
3423 device->subvendor_id = pinfo.subvendor_id;
3424 device->subdevice_id = pinfo.subdevice_id;
3425
3426 return 0;
3427 #elif __FreeBSD__
3428 drmPciBusInfo info;
3429 struct pci_conf_io pc;
3430 struct pci_match_conf patterns[1];
3431 struct pci_conf results[1];
3432 int fd, error;
3433
3434 if (get_sysctl_pci_bus_info(maj, min, &info) != 0)
3435 return -EINVAL;
3436
3437 fd = open("/dev/pci", O_RDONLY, 0);
3438 if (fd < 0)
3439 return -errno;
3440
3441 bzero(&patterns, sizeof(patterns));
3442 patterns[0].pc_sel.pc_domain = info.domain;
3443 patterns[0].pc_sel.pc_bus = info.bus;
3444 patterns[0].pc_sel.pc_dev = info.dev;
3445 patterns[0].pc_sel.pc_func = info.func;
3446 patterns[0].flags = PCI_GETCONF_MATCH_DOMAIN | PCI_GETCONF_MATCH_BUS
3447 | PCI_GETCONF_MATCH_DEV | PCI_GETCONF_MATCH_FUNC;
3448 bzero(&pc, sizeof(struct pci_conf_io));
3449 pc.num_patterns = 1;
3450 pc.pat_buf_len = sizeof(patterns);
3451 pc.patterns = patterns;
3452 pc.match_buf_len = sizeof(results);
3453 pc.matches = results;
3454
3455 if (ioctl(fd, PCIOCGETCONF, &pc) || pc.status == PCI_GETCONF_ERROR) {
3456 error = errno;
3457 close(fd);
3458 return -error;
3459 }
3460 close(fd);
3461
3462 device->vendor_id = results[0].pc_vendor;
3463 device->device_id = results[0].pc_device;
3464 device->subvendor_id = results[0].pc_subvendor;
3465 device->subdevice_id = results[0].pc_subdevice;
3466 device->revision_id = results[0].pc_revid;
3467
3468 return 0;
3469 #else
3470 #warning "Missing implementation of drmParsePciDeviceInfo"
3471 return -EINVAL;
3472 #endif
3473 }
3474
drmFreePlatformDevice(drmDevicePtr device)3475 static void drmFreePlatformDevice(drmDevicePtr device)
3476 {
3477 if (device->deviceinfo.platform) {
3478 if (device->deviceinfo.platform->compatible) {
3479 char **compatible = device->deviceinfo.platform->compatible;
3480
3481 while (*compatible) {
3482 free(*compatible);
3483 compatible++;
3484 }
3485
3486 free(device->deviceinfo.platform->compatible);
3487 }
3488 }
3489 }
3490
drmFreeHost1xDevice(drmDevicePtr device)3491 static void drmFreeHost1xDevice(drmDevicePtr device)
3492 {
3493 if (device->deviceinfo.host1x) {
3494 if (device->deviceinfo.host1x->compatible) {
3495 char **compatible = device->deviceinfo.host1x->compatible;
3496
3497 while (*compatible) {
3498 free(*compatible);
3499 compatible++;
3500 }
3501
3502 free(device->deviceinfo.host1x->compatible);
3503 }
3504 }
3505 }
3506
drmFreeDevice(drmDevicePtr * device)3507 drm_public void drmFreeDevice(drmDevicePtr *device)
3508 {
3509 if (device == NULL)
3510 return;
3511
3512 if (*device) {
3513 switch ((*device)->bustype) {
3514 case DRM_BUS_PLATFORM:
3515 drmFreePlatformDevice(*device);
3516 break;
3517
3518 case DRM_BUS_HOST1X:
3519 drmFreeHost1xDevice(*device);
3520 break;
3521 }
3522 }
3523
3524 free(*device);
3525 *device = NULL;
3526 }
3527
drmFreeDevices(drmDevicePtr devices[],int count)3528 drm_public void drmFreeDevices(drmDevicePtr devices[], int count)
3529 {
3530 int i;
3531
3532 if (devices == NULL)
3533 return;
3534
3535 for (i = 0; i < count; i++)
3536 if (devices[i])
3537 drmFreeDevice(&devices[i]);
3538 }
3539
drmDeviceAlloc(unsigned int type,const char * node,size_t bus_size,size_t device_size,char ** ptrp)3540 static drmDevicePtr drmDeviceAlloc(unsigned int type, const char *node,
3541 size_t bus_size, size_t device_size,
3542 char **ptrp)
3543 {
3544 size_t max_node_length, extra, size;
3545 drmDevicePtr device;
3546 unsigned int i;
3547 char *ptr;
3548
3549 max_node_length = ALIGN(drmGetMaxNodeName(), sizeof(void *));
3550 extra = DRM_NODE_MAX * (sizeof(void *) + max_node_length);
3551
3552 size = sizeof(*device) + extra + bus_size + device_size;
3553
3554 device = calloc(1, size);
3555 if (!device)
3556 return NULL;
3557
3558 device->available_nodes = 1 << type;
3559
3560 ptr = (char *)device + sizeof(*device);
3561 device->nodes = (char **)ptr;
3562
3563 ptr += DRM_NODE_MAX * sizeof(void *);
3564
3565 for (i = 0; i < DRM_NODE_MAX; i++) {
3566 device->nodes[i] = ptr;
3567 ptr += max_node_length;
3568 }
3569
3570 memcpy(device->nodes[type], node, max_node_length);
3571
3572 *ptrp = ptr;
3573
3574 return device;
3575 }
3576
drmProcessPciDevice(drmDevicePtr * device,const char * node,int node_type,int maj,int min,bool fetch_deviceinfo,uint32_t flags)3577 static int drmProcessPciDevice(drmDevicePtr *device,
3578 const char *node, int node_type,
3579 int maj, int min, bool fetch_deviceinfo,
3580 uint32_t flags)
3581 {
3582 drmDevicePtr dev;
3583 char *addr;
3584 int ret;
3585
3586 dev = drmDeviceAlloc(node_type, node, sizeof(drmPciBusInfo),
3587 sizeof(drmPciDeviceInfo), &addr);
3588 if (!dev)
3589 return -ENOMEM;
3590
3591 dev->bustype = DRM_BUS_PCI;
3592
3593 dev->businfo.pci = (drmPciBusInfoPtr)addr;
3594
3595 ret = drmParsePciBusInfo(maj, min, dev->businfo.pci);
3596 if (ret)
3597 goto free_device;
3598
3599 // Fetch the device info if the user has requested it
3600 if (fetch_deviceinfo) {
3601 addr += sizeof(drmPciBusInfo);
3602 dev->deviceinfo.pci = (drmPciDeviceInfoPtr)addr;
3603
3604 ret = drmParsePciDeviceInfo(maj, min, dev->deviceinfo.pci, flags);
3605 if (ret)
3606 goto free_device;
3607 }
3608
3609 *device = dev;
3610
3611 return 0;
3612
3613 free_device:
3614 free(dev);
3615 return ret;
3616 }
3617
3618 #ifdef __linux__
drm_usb_dev_path(int maj,int min,char * path,size_t len)3619 static int drm_usb_dev_path(int maj, int min, char *path, size_t len)
3620 {
3621 char *value, *tmp_path, *slash;
3622
3623 snprintf(path, len, "/sys/dev/char/%d:%d/device", maj, min);
3624
3625 value = sysfs_uevent_get(path, "DEVTYPE");
3626 if (!value)
3627 return -ENOENT;
3628
3629 if (strcmp(value, "usb_device") == 0)
3630 return 0;
3631 if (strcmp(value, "usb_interface") != 0)
3632 return -ENOTSUP;
3633
3634 /* The parent of a usb_interface is a usb_device */
3635
3636 tmp_path = realpath(path, NULL);
3637 if (!tmp_path)
3638 return -errno;
3639
3640 slash = strrchr(tmp_path, '/');
3641 if (!slash) {
3642 free(tmp_path);
3643 return -EINVAL;
3644 }
3645
3646 *slash = '\0';
3647
3648 if (snprintf(path, len, "%s", tmp_path) >= (int)len) {
3649 free(tmp_path);
3650 return -EINVAL;
3651 }
3652
3653 free(tmp_path);
3654 return 0;
3655 }
3656 #endif
3657
drmParseUsbBusInfo(int maj,int min,drmUsbBusInfoPtr info)3658 static int drmParseUsbBusInfo(int maj, int min, drmUsbBusInfoPtr info)
3659 {
3660 #ifdef __linux__
3661 char path[PATH_MAX + 1], *value;
3662 unsigned int bus, dev;
3663 int ret;
3664
3665 ret = drm_usb_dev_path(maj, min, path, sizeof(path));
3666 if (ret < 0)
3667 return ret;
3668
3669 value = sysfs_uevent_get(path, "BUSNUM");
3670 if (!value)
3671 return -ENOENT;
3672
3673 ret = sscanf(value, "%03u", &bus);
3674 free(value);
3675
3676 if (ret <= 0)
3677 return -errno;
3678
3679 value = sysfs_uevent_get(path, "DEVNUM");
3680 if (!value)
3681 return -ENOENT;
3682
3683 ret = sscanf(value, "%03u", &dev);
3684 free(value);
3685
3686 if (ret <= 0)
3687 return -errno;
3688
3689 info->bus = bus;
3690 info->dev = dev;
3691
3692 return 0;
3693 #else
3694 #warning "Missing implementation of drmParseUsbBusInfo"
3695 return -EINVAL;
3696 #endif
3697 }
3698
drmParseUsbDeviceInfo(int maj,int min,drmUsbDeviceInfoPtr info)3699 static int drmParseUsbDeviceInfo(int maj, int min, drmUsbDeviceInfoPtr info)
3700 {
3701 #ifdef __linux__
3702 char path[PATH_MAX + 1], *value;
3703 unsigned int vendor, product;
3704 int ret;
3705
3706 ret = drm_usb_dev_path(maj, min, path, sizeof(path));
3707 if (ret < 0)
3708 return ret;
3709
3710 value = sysfs_uevent_get(path, "PRODUCT");
3711 if (!value)
3712 return -ENOENT;
3713
3714 ret = sscanf(value, "%x/%x", &vendor, &product);
3715 free(value);
3716
3717 if (ret <= 0)
3718 return -errno;
3719
3720 info->vendor = vendor;
3721 info->product = product;
3722
3723 return 0;
3724 #else
3725 #warning "Missing implementation of drmParseUsbDeviceInfo"
3726 return -EINVAL;
3727 #endif
3728 }
3729
drmProcessUsbDevice(drmDevicePtr * device,const char * node,int node_type,int maj,int min,bool fetch_deviceinfo,uint32_t flags)3730 static int drmProcessUsbDevice(drmDevicePtr *device, const char *node,
3731 int node_type, int maj, int min,
3732 bool fetch_deviceinfo, uint32_t flags)
3733 {
3734 drmDevicePtr dev;
3735 char *ptr;
3736 int ret;
3737
3738 dev = drmDeviceAlloc(node_type, node, sizeof(drmUsbBusInfo),
3739 sizeof(drmUsbDeviceInfo), &ptr);
3740 if (!dev)
3741 return -ENOMEM;
3742
3743 dev->bustype = DRM_BUS_USB;
3744
3745 dev->businfo.usb = (drmUsbBusInfoPtr)ptr;
3746
3747 ret = drmParseUsbBusInfo(maj, min, dev->businfo.usb);
3748 if (ret < 0)
3749 goto free_device;
3750
3751 if (fetch_deviceinfo) {
3752 ptr += sizeof(drmUsbBusInfo);
3753 dev->deviceinfo.usb = (drmUsbDeviceInfoPtr)ptr;
3754
3755 ret = drmParseUsbDeviceInfo(maj, min, dev->deviceinfo.usb);
3756 if (ret < 0)
3757 goto free_device;
3758 }
3759
3760 *device = dev;
3761
3762 return 0;
3763
3764 free_device:
3765 free(dev);
3766 return ret;
3767 }
3768
drmParseOFBusInfo(int maj,int min,char * fullname)3769 static int drmParseOFBusInfo(int maj, int min, char *fullname)
3770 {
3771 #ifdef __linux__
3772 char path[PATH_MAX + 1], *name, *tmp_name;
3773
3774 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3775
3776 name = sysfs_uevent_get(path, "OF_FULLNAME");
3777 tmp_name = name;
3778 if (!name) {
3779 /* If the device lacks OF data, pick the MODALIAS info */
3780 name = sysfs_uevent_get(path, "MODALIAS");
3781 if (!name)
3782 return -ENOENT;
3783
3784 /* .. and strip the MODALIAS=[platform,usb...]: part. */
3785 tmp_name = strrchr(name, ':');
3786 if (!tmp_name) {
3787 free(name);
3788 return -ENOENT;
3789 }
3790 tmp_name++;
3791 }
3792
3793 strncpy(fullname, tmp_name, DRM_PLATFORM_DEVICE_NAME_LEN);
3794 fullname[DRM_PLATFORM_DEVICE_NAME_LEN - 1] = '\0';
3795 free(name);
3796
3797 return 0;
3798 #else
3799 #warning "Missing implementation of drmParseOFBusInfo"
3800 return -EINVAL;
3801 #endif
3802 }
3803
drmParseOFDeviceInfo(int maj,int min,char *** compatible)3804 static int drmParseOFDeviceInfo(int maj, int min, char ***compatible)
3805 {
3806 #ifdef __linux__
3807 char path[PATH_MAX + 1], *value, *tmp_name;
3808 unsigned int count, i;
3809 int err;
3810
3811 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3812
3813 value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
3814 if (value) {
3815 sscanf(value, "%u", &count);
3816 free(value);
3817 } else {
3818 /* Assume one entry if the device lack OF data */
3819 count = 1;
3820 }
3821
3822 *compatible = calloc(count + 1, sizeof(char *));
3823 if (!*compatible)
3824 return -ENOMEM;
3825
3826 for (i = 0; i < count; i++) {
3827 value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
3828 tmp_name = value;
3829 if (!value) {
3830 /* If the device lacks OF data, pick the MODALIAS info */
3831 value = sysfs_uevent_get(path, "MODALIAS");
3832 if (!value) {
3833 err = -ENOENT;
3834 goto free;
3835 }
3836
3837 /* .. and strip the MODALIAS=[platform,usb...]: part. */
3838 tmp_name = strrchr(value, ':');
3839 if (!tmp_name) {
3840 free(value);
3841 return -ENOENT;
3842 }
3843 tmp_name = strdup(tmp_name + 1);
3844 free(value);
3845 }
3846
3847 (*compatible)[i] = tmp_name;
3848 }
3849
3850 return 0;
3851
3852 free:
3853 while (i--)
3854 free((*compatible)[i]);
3855
3856 free(*compatible);
3857 return err;
3858 #else
3859 #warning "Missing implementation of drmParseOFDeviceInfo"
3860 return -EINVAL;
3861 #endif
3862 }
3863
drmProcessPlatformDevice(drmDevicePtr * device,const char * node,int node_type,int maj,int min,bool fetch_deviceinfo,uint32_t flags)3864 static int drmProcessPlatformDevice(drmDevicePtr *device,
3865 const char *node, int node_type,
3866 int maj, int min, bool fetch_deviceinfo,
3867 uint32_t flags)
3868 {
3869 drmDevicePtr dev;
3870 char *ptr;
3871 int ret;
3872
3873 dev = drmDeviceAlloc(node_type, node, sizeof(drmPlatformBusInfo),
3874 sizeof(drmPlatformDeviceInfo), &ptr);
3875 if (!dev)
3876 return -ENOMEM;
3877
3878 dev->bustype = DRM_BUS_PLATFORM;
3879
3880 dev->businfo.platform = (drmPlatformBusInfoPtr)ptr;
3881
3882 ret = drmParseOFBusInfo(maj, min, dev->businfo.platform->fullname);
3883 if (ret < 0)
3884 goto free_device;
3885
3886 if (fetch_deviceinfo) {
3887 ptr += sizeof(drmPlatformBusInfo);
3888 dev->deviceinfo.platform = (drmPlatformDeviceInfoPtr)ptr;
3889
3890 ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.platform->compatible);
3891 if (ret < 0)
3892 goto free_device;
3893 }
3894
3895 *device = dev;
3896
3897 return 0;
3898
3899 free_device:
3900 free(dev);
3901 return ret;
3902 }
3903
drmProcessHost1xDevice(drmDevicePtr * device,const char * node,int node_type,int maj,int min,bool fetch_deviceinfo,uint32_t flags)3904 static int drmProcessHost1xDevice(drmDevicePtr *device,
3905 const char *node, int node_type,
3906 int maj, int min, bool fetch_deviceinfo,
3907 uint32_t flags)
3908 {
3909 drmDevicePtr dev;
3910 char *ptr;
3911 int ret;
3912
3913 dev = drmDeviceAlloc(node_type, node, sizeof(drmHost1xBusInfo),
3914 sizeof(drmHost1xDeviceInfo), &ptr);
3915 if (!dev)
3916 return -ENOMEM;
3917
3918 dev->bustype = DRM_BUS_HOST1X;
3919
3920 dev->businfo.host1x = (drmHost1xBusInfoPtr)ptr;
3921
3922 ret = drmParseOFBusInfo(maj, min, dev->businfo.host1x->fullname);
3923 if (ret < 0)
3924 goto free_device;
3925
3926 if (fetch_deviceinfo) {
3927 ptr += sizeof(drmHost1xBusInfo);
3928 dev->deviceinfo.host1x = (drmHost1xDeviceInfoPtr)ptr;
3929
3930 ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.host1x->compatible);
3931 if (ret < 0)
3932 goto free_device;
3933 }
3934
3935 *device = dev;
3936
3937 return 0;
3938
3939 free_device:
3940 free(dev);
3941 return ret;
3942 }
3943
3944 static int
process_device(drmDevicePtr * device,const char * d_name,int req_subsystem_type,bool fetch_deviceinfo,uint32_t flags)3945 process_device(drmDevicePtr *device, const char *d_name,
3946 int req_subsystem_type,
3947 bool fetch_deviceinfo, uint32_t flags)
3948 {
3949 struct stat sbuf;
3950 char node[PATH_MAX + 1];
3951 int node_type, subsystem_type;
3952 unsigned int maj, min;
3953
3954 node_type = drmGetNodeType(d_name);
3955 if (node_type < 0)
3956 return -1;
3957
3958 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, d_name);
3959 if (stat(node, &sbuf))
3960 return -1;
3961
3962 maj = major(sbuf.st_rdev);
3963 min = minor(sbuf.st_rdev);
3964
3965 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3966 return -1;
3967
3968 subsystem_type = drmParseSubsystemType(maj, min);
3969 if (req_subsystem_type != -1 && req_subsystem_type != subsystem_type)
3970 return -1;
3971
3972 switch (subsystem_type) {
3973 case DRM_BUS_PCI:
3974 case DRM_BUS_VIRTIO:
3975 return drmProcessPciDevice(device, node, node_type, maj, min,
3976 fetch_deviceinfo, flags);
3977 case DRM_BUS_USB:
3978 return drmProcessUsbDevice(device, node, node_type, maj, min,
3979 fetch_deviceinfo, flags);
3980 case DRM_BUS_PLATFORM:
3981 return drmProcessPlatformDevice(device, node, node_type, maj, min,
3982 fetch_deviceinfo, flags);
3983 case DRM_BUS_HOST1X:
3984 return drmProcessHost1xDevice(device, node, node_type, maj, min,
3985 fetch_deviceinfo, flags);
3986 default:
3987 return -1;
3988 }
3989 }
3990
3991 /* Consider devices located on the same bus as duplicate and fold the respective
3992 * entries into a single one.
3993 *
3994 * Note: this leaves "gaps" in the array, while preserving the length.
3995 */
drmFoldDuplicatedDevices(drmDevicePtr local_devices[],int count)3996 static void drmFoldDuplicatedDevices(drmDevicePtr local_devices[], int count)
3997 {
3998 int node_type, i, j;
3999
4000 for (i = 0; i < count; i++) {
4001 for (j = i + 1; j < count; j++) {
4002 if (drmDevicesEqual(local_devices[i], local_devices[j])) {
4003 local_devices[i]->available_nodes |= local_devices[j]->available_nodes;
4004 node_type = log2(local_devices[j]->available_nodes);
4005 memcpy(local_devices[i]->nodes[node_type],
4006 local_devices[j]->nodes[node_type], drmGetMaxNodeName());
4007 drmFreeDevice(&local_devices[j]);
4008 }
4009 }
4010 }
4011 }
4012
4013 /* Check that the given flags are valid returning 0 on success */
4014 static int
drm_device_validate_flags(uint32_t flags)4015 drm_device_validate_flags(uint32_t flags)
4016 {
4017 return (flags & ~DRM_DEVICE_GET_PCI_REVISION);
4018 }
4019
4020 static bool
drm_device_has_rdev(drmDevicePtr device,dev_t find_rdev)4021 drm_device_has_rdev(drmDevicePtr device, dev_t find_rdev)
4022 {
4023 struct stat sbuf;
4024
4025 for (int i = 0; i < DRM_NODE_MAX; i++) {
4026 if (device->available_nodes & 1 << i) {
4027 if (stat(device->nodes[i], &sbuf) == 0 &&
4028 sbuf.st_rdev == find_rdev)
4029 return true;
4030 }
4031 }
4032 return false;
4033 }
4034
4035 /*
4036 * The kernel drm core has a number of places that assume maximum of
4037 * 3x64 devices nodes. That's 64 for each of primary, control and
4038 * render nodes. Rounded it up to 256 for simplicity.
4039 */
4040 #define MAX_DRM_NODES 256
4041
4042 /**
4043 * Get information about the opened drm device
4044 *
4045 * \param fd file descriptor of the drm device
4046 * \param flags feature/behaviour bitmask
4047 * \param device the address of a drmDevicePtr where the information
4048 * will be allocated in stored
4049 *
4050 * \return zero on success, negative error code otherwise.
4051 *
4052 * \note Unlike drmGetDevice it does not retrieve the pci device revision field
4053 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
4054 */
drmGetDevice2(int fd,uint32_t flags,drmDevicePtr * device)4055 drm_public int drmGetDevice2(int fd, uint32_t flags, drmDevicePtr *device)
4056 {
4057 #ifdef __OpenBSD__
4058 /*
4059 * DRI device nodes on OpenBSD are not in their own directory, they reside
4060 * in /dev along with a large number of statically generated /dev nodes.
4061 * Avoid stat'ing all of /dev needlessly by implementing this custom path.
4062 */
4063 drmDevicePtr d;
4064 struct stat sbuf;
4065 char node[PATH_MAX + 1];
4066 const char *dev_name;
4067 int node_type, subsystem_type;
4068 int maj, min, n, ret;
4069
4070 if (fd == -1 || device == NULL)
4071 return -EINVAL;
4072
4073 if (fstat(fd, &sbuf))
4074 return -errno;
4075
4076 maj = major(sbuf.st_rdev);
4077 min = minor(sbuf.st_rdev);
4078
4079 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4080 return -EINVAL;
4081
4082 node_type = drmGetMinorType(maj, min);
4083 if (node_type == -1)
4084 return -ENODEV;
4085
4086 dev_name = drmGetDeviceName(node_type);
4087 if (!dev_name)
4088 return -EINVAL;
4089
4090 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min);
4091 if (n == -1 || n >= PATH_MAX)
4092 return -errno;
4093 if (stat(node, &sbuf))
4094 return -EINVAL;
4095
4096 subsystem_type = drmParseSubsystemType(maj, min);
4097 if (subsystem_type != DRM_BUS_PCI)
4098 return -ENODEV;
4099
4100 ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
4101 if (ret)
4102 return ret;
4103
4104 *device = d;
4105
4106 return 0;
4107 #else
4108 drmDevicePtr local_devices[MAX_DRM_NODES];
4109 drmDevicePtr d;
4110 DIR *sysdir;
4111 struct dirent *dent;
4112 struct stat sbuf;
4113 int subsystem_type;
4114 int maj, min;
4115 int ret, i, node_count;
4116 dev_t find_rdev;
4117
4118 if (drm_device_validate_flags(flags))
4119 return -EINVAL;
4120
4121 if (fd == -1 || device == NULL)
4122 return -EINVAL;
4123
4124 if (fstat(fd, &sbuf))
4125 return -errno;
4126
4127 find_rdev = sbuf.st_rdev;
4128 maj = major(sbuf.st_rdev);
4129 min = minor(sbuf.st_rdev);
4130
4131 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4132 return -EINVAL;
4133
4134 subsystem_type = drmParseSubsystemType(maj, min);
4135 if (subsystem_type < 0)
4136 return subsystem_type;
4137
4138 sysdir = opendir(DRM_DIR_NAME);
4139 if (!sysdir)
4140 return -errno;
4141
4142 i = 0;
4143 while ((dent = readdir(sysdir))) {
4144 ret = process_device(&d, dent->d_name, subsystem_type, true, flags);
4145 if (ret)
4146 continue;
4147
4148 if (i >= MAX_DRM_NODES) {
4149 fprintf(stderr, "More than %d drm nodes detected. "
4150 "Please report a bug - that should not happen.\n"
4151 "Skipping extra nodes\n", MAX_DRM_NODES);
4152 break;
4153 }
4154 local_devices[i] = d;
4155 i++;
4156 }
4157 node_count = i;
4158
4159 drmFoldDuplicatedDevices(local_devices, node_count);
4160
4161 *device = NULL;
4162
4163 for (i = 0; i < node_count; i++) {
4164 if (!local_devices[i])
4165 continue;
4166
4167 if (drm_device_has_rdev(local_devices[i], find_rdev))
4168 *device = local_devices[i];
4169 else
4170 drmFreeDevice(&local_devices[i]);
4171 }
4172
4173 closedir(sysdir);
4174 if (*device == NULL)
4175 return -ENODEV;
4176 return 0;
4177 #endif
4178 }
4179
4180 /**
4181 * Get information about the opened drm device
4182 *
4183 * \param fd file descriptor of the drm device
4184 * \param device the address of a drmDevicePtr where the information
4185 * will be allocated in stored
4186 *
4187 * \return zero on success, negative error code otherwise.
4188 */
drmGetDevice(int fd,drmDevicePtr * device)4189 drm_public int drmGetDevice(int fd, drmDevicePtr *device)
4190 {
4191 return drmGetDevice2(fd, DRM_DEVICE_GET_PCI_REVISION, device);
4192 }
4193
4194 /**
4195 * Get drm devices on the system
4196 *
4197 * \param flags feature/behaviour bitmask
4198 * \param devices the array of devices with drmDevicePtr elements
4199 * can be NULL to get the device number first
4200 * \param max_devices the maximum number of devices for the array
4201 *
4202 * \return on error - negative error code,
4203 * if devices is NULL - total number of devices available on the system,
4204 * alternatively the number of devices stored in devices[], which is
4205 * capped by the max_devices.
4206 *
4207 * \note Unlike drmGetDevices it does not retrieve the pci device revision field
4208 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
4209 */
drmGetDevices2(uint32_t flags,drmDevicePtr devices[],int max_devices)4210 drm_public int drmGetDevices2(uint32_t flags, drmDevicePtr devices[],
4211 int max_devices)
4212 {
4213 drmDevicePtr local_devices[MAX_DRM_NODES];
4214 drmDevicePtr device;
4215 DIR *sysdir;
4216 struct dirent *dent;
4217 int ret, i, node_count, device_count;
4218
4219 if (drm_device_validate_flags(flags))
4220 return -EINVAL;
4221
4222 sysdir = opendir(DRM_DIR_NAME);
4223 if (!sysdir)
4224 return -errno;
4225
4226 i = 0;
4227 while ((dent = readdir(sysdir))) {
4228 ret = process_device(&device, dent->d_name, -1, devices != NULL, flags);
4229 if (ret)
4230 continue;
4231
4232 if (i >= MAX_DRM_NODES) {
4233 fprintf(stderr, "More than %d drm nodes detected. "
4234 "Please report a bug - that should not happen.\n"
4235 "Skipping extra nodes\n", MAX_DRM_NODES);
4236 break;
4237 }
4238 local_devices[i] = device;
4239 i++;
4240 }
4241 node_count = i;
4242
4243 drmFoldDuplicatedDevices(local_devices, node_count);
4244
4245 device_count = 0;
4246 for (i = 0; i < node_count; i++) {
4247 if (!local_devices[i])
4248 continue;
4249
4250 if ((devices != NULL) && (device_count < max_devices))
4251 devices[device_count] = local_devices[i];
4252 else
4253 drmFreeDevice(&local_devices[i]);
4254
4255 device_count++;
4256 }
4257
4258 closedir(sysdir);
4259 return device_count;
4260 }
4261
4262 /**
4263 * Get drm devices on the system
4264 *
4265 * \param devices the array of devices with drmDevicePtr elements
4266 * can be NULL to get the device number first
4267 * \param max_devices the maximum number of devices for the array
4268 *
4269 * \return on error - negative error code,
4270 * if devices is NULL - total number of devices available on the system,
4271 * alternatively the number of devices stored in devices[], which is
4272 * capped by the max_devices.
4273 */
drmGetDevices(drmDevicePtr devices[],int max_devices)4274 drm_public int drmGetDevices(drmDevicePtr devices[], int max_devices)
4275 {
4276 return drmGetDevices2(DRM_DEVICE_GET_PCI_REVISION, devices, max_devices);
4277 }
4278
drmGetDeviceNameFromFd2(int fd)4279 drm_public char *drmGetDeviceNameFromFd2(int fd)
4280 {
4281 #ifdef __linux__
4282 struct stat sbuf;
4283 char path[PATH_MAX + 1], *value;
4284 unsigned int maj, min;
4285
4286 if (fstat(fd, &sbuf))
4287 return NULL;
4288
4289 maj = major(sbuf.st_rdev);
4290 min = minor(sbuf.st_rdev);
4291
4292 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4293 return NULL;
4294
4295 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d", maj, min);
4296
4297 value = sysfs_uevent_get(path, "DEVNAME");
4298 if (!value)
4299 return NULL;
4300
4301 snprintf(path, sizeof(path), "/dev/%s", value);
4302 free(value);
4303
4304 return strdup(path);
4305 #elif __FreeBSD__
4306 return drmGetDeviceNameFromFd(fd);
4307 #else
4308 struct stat sbuf;
4309 char node[PATH_MAX + 1];
4310 const char *dev_name;
4311 int node_type;
4312 int maj, min, n;
4313
4314 if (fstat(fd, &sbuf))
4315 return NULL;
4316
4317 maj = major(sbuf.st_rdev);
4318 min = minor(sbuf.st_rdev);
4319
4320 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4321 return NULL;
4322
4323 node_type = drmGetMinorType(maj, min);
4324 if (node_type == -1)
4325 return NULL;
4326
4327 dev_name = drmGetDeviceName(node_type);
4328 if (!dev_name)
4329 return NULL;
4330
4331 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min);
4332 if (n == -1 || n >= PATH_MAX)
4333 return NULL;
4334
4335 return strdup(node);
4336 #endif
4337 }
4338
drmSyncobjCreate(int fd,uint32_t flags,uint32_t * handle)4339 drm_public int drmSyncobjCreate(int fd, uint32_t flags, uint32_t *handle)
4340 {
4341 struct drm_syncobj_create args;
4342 int ret;
4343
4344 memclear(args);
4345 args.flags = flags;
4346 args.handle = 0;
4347 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_CREATE, &args);
4348 if (ret)
4349 return ret;
4350 *handle = args.handle;
4351 return 0;
4352 }
4353
drmSyncobjDestroy(int fd,uint32_t handle)4354 drm_public int drmSyncobjDestroy(int fd, uint32_t handle)
4355 {
4356 struct drm_syncobj_destroy args;
4357
4358 memclear(args);
4359 args.handle = handle;
4360 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_DESTROY, &args);
4361 }
4362
drmSyncobjHandleToFD(int fd,uint32_t handle,int * obj_fd)4363 drm_public int drmSyncobjHandleToFD(int fd, uint32_t handle, int *obj_fd)
4364 {
4365 struct drm_syncobj_handle args;
4366 int ret;
4367
4368 memclear(args);
4369 args.fd = -1;
4370 args.handle = handle;
4371 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4372 if (ret)
4373 return ret;
4374 *obj_fd = args.fd;
4375 return 0;
4376 }
4377
drmSyncobjFDToHandle(int fd,int obj_fd,uint32_t * handle)4378 drm_public int drmSyncobjFDToHandle(int fd, int obj_fd, uint32_t *handle)
4379 {
4380 struct drm_syncobj_handle args;
4381 int ret;
4382
4383 memclear(args);
4384 args.fd = obj_fd;
4385 args.handle = 0;
4386 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4387 if (ret)
4388 return ret;
4389 *handle = args.handle;
4390 return 0;
4391 }
4392
drmSyncobjImportSyncFile(int fd,uint32_t handle,int sync_file_fd)4393 drm_public int drmSyncobjImportSyncFile(int fd, uint32_t handle,
4394 int sync_file_fd)
4395 {
4396 struct drm_syncobj_handle args;
4397
4398 memclear(args);
4399 args.fd = sync_file_fd;
4400 args.handle = handle;
4401 args.flags = DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE;
4402 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4403 }
4404
drmSyncobjExportSyncFile(int fd,uint32_t handle,int * sync_file_fd)4405 drm_public int drmSyncobjExportSyncFile(int fd, uint32_t handle,
4406 int *sync_file_fd)
4407 {
4408 struct drm_syncobj_handle args;
4409 int ret;
4410
4411 memclear(args);
4412 args.fd = -1;
4413 args.handle = handle;
4414 args.flags = DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE;
4415 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4416 if (ret)
4417 return ret;
4418 *sync_file_fd = args.fd;
4419 return 0;
4420 }
4421
drmSyncobjWait(int fd,uint32_t * handles,unsigned num_handles,int64_t timeout_nsec,unsigned flags,uint32_t * first_signaled)4422 drm_public int drmSyncobjWait(int fd, uint32_t *handles, unsigned num_handles,
4423 int64_t timeout_nsec, unsigned flags,
4424 uint32_t *first_signaled)
4425 {
4426 struct drm_syncobj_wait args;
4427 int ret;
4428
4429 memclear(args);
4430 args.handles = (uintptr_t)handles;
4431 args.timeout_nsec = timeout_nsec;
4432 args.count_handles = num_handles;
4433 args.flags = flags;
4434
4435 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_WAIT, &args);
4436 if (ret < 0)
4437 return -errno;
4438
4439 if (first_signaled)
4440 *first_signaled = args.first_signaled;
4441 return ret;
4442 }
4443
drmSyncobjReset(int fd,const uint32_t * handles,uint32_t handle_count)4444 drm_public int drmSyncobjReset(int fd, const uint32_t *handles,
4445 uint32_t handle_count)
4446 {
4447 struct drm_syncobj_array args;
4448 int ret;
4449
4450 memclear(args);
4451 args.handles = (uintptr_t)handles;
4452 args.count_handles = handle_count;
4453
4454 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_RESET, &args);
4455 return ret;
4456 }
4457
drmSyncobjSignal(int fd,const uint32_t * handles,uint32_t handle_count)4458 drm_public int drmSyncobjSignal(int fd, const uint32_t *handles,
4459 uint32_t handle_count)
4460 {
4461 struct drm_syncobj_array args;
4462 int ret;
4463
4464 memclear(args);
4465 args.handles = (uintptr_t)handles;
4466 args.count_handles = handle_count;
4467
4468 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_SIGNAL, &args);
4469 return ret;
4470 }
4471
drmSyncobjTimelineSignal(int fd,const uint32_t * handles,uint64_t * points,uint32_t handle_count)4472 drm_public int drmSyncobjTimelineSignal(int fd, const uint32_t *handles,
4473 uint64_t *points, uint32_t handle_count)
4474 {
4475 struct drm_syncobj_timeline_array args;
4476 int ret;
4477
4478 memclear(args);
4479 args.handles = (uintptr_t)handles;
4480 args.points = (uintptr_t)points;
4481 args.count_handles = handle_count;
4482
4483 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TIMELINE_SIGNAL, &args);
4484 return ret;
4485 }
4486
drmSyncobjTimelineWait(int fd,uint32_t * handles,uint64_t * points,unsigned num_handles,int64_t timeout_nsec,unsigned flags,uint32_t * first_signaled)4487 drm_public int drmSyncobjTimelineWait(int fd, uint32_t *handles, uint64_t *points,
4488 unsigned num_handles,
4489 int64_t timeout_nsec, unsigned flags,
4490 uint32_t *first_signaled)
4491 {
4492 struct drm_syncobj_timeline_wait args;
4493 int ret;
4494
4495 memclear(args);
4496 args.handles = (uintptr_t)handles;
4497 args.points = (uintptr_t)points;
4498 args.timeout_nsec = timeout_nsec;
4499 args.count_handles = num_handles;
4500 args.flags = flags;
4501
4502 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TIMELINE_WAIT, &args);
4503 if (ret < 0)
4504 return -errno;
4505
4506 if (first_signaled)
4507 *first_signaled = args.first_signaled;
4508 return ret;
4509 }
4510
4511
drmSyncobjQuery(int fd,uint32_t * handles,uint64_t * points,uint32_t handle_count)4512 drm_public int drmSyncobjQuery(int fd, uint32_t *handles, uint64_t *points,
4513 uint32_t handle_count)
4514 {
4515 struct drm_syncobj_timeline_array args;
4516 int ret;
4517
4518 memclear(args);
4519 args.handles = (uintptr_t)handles;
4520 args.points = (uintptr_t)points;
4521 args.count_handles = handle_count;
4522
4523 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_QUERY, &args);
4524 if (ret)
4525 return ret;
4526 return 0;
4527 }
4528
drmSyncobjQuery2(int fd,uint32_t * handles,uint64_t * points,uint32_t handle_count,uint32_t flags)4529 drm_public int drmSyncobjQuery2(int fd, uint32_t *handles, uint64_t *points,
4530 uint32_t handle_count, uint32_t flags)
4531 {
4532 struct drm_syncobj_timeline_array args;
4533
4534 memclear(args);
4535 args.handles = (uintptr_t)handles;
4536 args.points = (uintptr_t)points;
4537 args.count_handles = handle_count;
4538 args.flags = flags;
4539
4540 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_QUERY, &args);
4541 }
4542
4543
drmSyncobjTransfer(int fd,uint32_t dst_handle,uint64_t dst_point,uint32_t src_handle,uint64_t src_point,uint32_t flags)4544 drm_public int drmSyncobjTransfer(int fd,
4545 uint32_t dst_handle, uint64_t dst_point,
4546 uint32_t src_handle, uint64_t src_point,
4547 uint32_t flags)
4548 {
4549 struct drm_syncobj_transfer args;
4550 int ret;
4551
4552 memclear(args);
4553 args.src_handle = src_handle;
4554 args.dst_handle = dst_handle;
4555 args.src_point = src_point;
4556 args.dst_point = dst_point;
4557 args.flags = flags;
4558
4559 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TRANSFER, &args);
4560
4561 return ret;
4562 }
4563