OSDN Git Service

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