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