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