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