OSDN Git Service

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