OSDN Git Service

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