OSDN Git Service

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