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