OSDN Git Service

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