OSDN Git Service

etnaviv: fix etna_bo_from_name
[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     if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
870         drmFreeKernelVersion(version);
871         return NULL;
872     }
873
874     if (version->name_len)
875         version->name    = drmMalloc(version->name_len + 1);
876     if (version->date_len)
877         version->date    = drmMalloc(version->date_len + 1);
878     if (version->desc_len)
879         version->desc    = drmMalloc(version->desc_len + 1);
880
881     if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
882         drmMsg("DRM_IOCTL_VERSION: %s\n", strerror(errno));
883         drmFreeKernelVersion(version);
884         return NULL;
885     }
886
887     /* The results might not be null-terminated strings, so terminate them. */
888     if (version->name_len) version->name[version->name_len] = '\0';
889     if (version->date_len) version->date[version->date_len] = '\0';
890     if (version->desc_len) version->desc[version->desc_len] = '\0';
891
892     retval = drmMalloc(sizeof(*retval));
893     drmCopyVersion(retval, version);
894     drmFreeKernelVersion(version);
895     return retval;
896 }
897
898
899 /**
900  * Get version information for the DRM user space library.
901  *
902  * This version number is driver independent.
903  *
904  * \param fd file descriptor.
905  *
906  * \return version information.
907  *
908  * \internal
909  * This function allocates and fills a drm_version structure with a hard coded
910  * version number.
911  */
912 drmVersionPtr drmGetLibVersion(int fd)
913 {
914     drm_version_t *version = drmMalloc(sizeof(*version));
915
916     /* Version history:
917      *   NOTE THIS MUST NOT GO ABOVE VERSION 1.X due to drivers needing it
918      *   revision 1.0.x = original DRM interface with no drmGetLibVersion
919      *                    entry point and many drm<Device> extensions
920      *   revision 1.1.x = added drmCommand entry points for device extensions
921      *                    added drmGetLibVersion to identify libdrm.a version
922      *   revision 1.2.x = added drmSetInterfaceVersion
923      *                    modified drmOpen to handle both busid and name
924      *   revision 1.3.x = added server + memory manager
925      */
926     version->version_major      = 1;
927     version->version_minor      = 3;
928     version->version_patchlevel = 0;
929
930     return (drmVersionPtr)version;
931 }
932
933 int drmGetCap(int fd, uint64_t capability, uint64_t *value)
934 {
935     struct drm_get_cap cap;
936     int ret;
937
938     memclear(cap);
939     cap.capability = capability;
940
941     ret = drmIoctl(fd, DRM_IOCTL_GET_CAP, &cap);
942     if (ret)
943         return ret;
944
945     *value = cap.value;
946     return 0;
947 }
948
949 int drmSetClientCap(int fd, uint64_t capability, uint64_t value)
950 {
951     struct drm_set_client_cap cap;
952
953     memclear(cap);
954     cap.capability = capability;
955     cap.value = value;
956
957     return drmIoctl(fd, DRM_IOCTL_SET_CLIENT_CAP, &cap);
958 }
959
960 /**
961  * Free the bus ID information.
962  *
963  * \param busid bus ID information string as given by drmGetBusid().
964  *
965  * \internal
966  * This function is just frees the memory pointed by \p busid.
967  */
968 void drmFreeBusid(const char *busid)
969 {
970     drmFree((void *)busid);
971 }
972
973
974 /**
975  * Get the bus ID of the device.
976  *
977  * \param fd file descriptor.
978  *
979  * \return bus ID string.
980  *
981  * \internal
982  * This function gets the bus ID via successive DRM_IOCTL_GET_UNIQUE ioctls to
983  * get the string length and data, passing the arguments in a drm_unique
984  * structure.
985  */
986 char *drmGetBusid(int fd)
987 {
988     drm_unique_t u;
989
990     memclear(u);
991
992     if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
993         return NULL;
994     u.unique = drmMalloc(u.unique_len + 1);
995     if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u)) {
996         drmFree(u.unique);
997         return NULL;
998     }
999     u.unique[u.unique_len] = '\0';
1000
1001     return u.unique;
1002 }
1003
1004
1005 /**
1006  * Set the bus ID of the device.
1007  *
1008  * \param fd file descriptor.
1009  * \param busid bus ID string.
1010  *
1011  * \return zero on success, negative on failure.
1012  *
1013  * \internal
1014  * This function is a wrapper around the DRM_IOCTL_SET_UNIQUE ioctl, passing
1015  * the arguments in a drm_unique structure.
1016  */
1017 int drmSetBusid(int fd, const char *busid)
1018 {
1019     drm_unique_t u;
1020
1021     memclear(u);
1022     u.unique     = (char *)busid;
1023     u.unique_len = strlen(busid);
1024
1025     if (drmIoctl(fd, DRM_IOCTL_SET_UNIQUE, &u)) {
1026         return -errno;
1027     }
1028     return 0;
1029 }
1030
1031 int drmGetMagic(int fd, drm_magic_t * magic)
1032 {
1033     drm_auth_t auth;
1034
1035     memclear(auth);
1036
1037     *magic = 0;
1038     if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
1039         return -errno;
1040     *magic = auth.magic;
1041     return 0;
1042 }
1043
1044 int drmAuthMagic(int fd, drm_magic_t magic)
1045 {
1046     drm_auth_t auth;
1047
1048     memclear(auth);
1049     auth.magic = magic;
1050     if (drmIoctl(fd, DRM_IOCTL_AUTH_MAGIC, &auth))
1051         return -errno;
1052     return 0;
1053 }
1054
1055 /**
1056  * Specifies a range of memory that is available for mapping by a
1057  * non-root process.
1058  *
1059  * \param fd file descriptor.
1060  * \param offset usually the physical address. The actual meaning depends of
1061  * the \p type parameter. See below.
1062  * \param size of the memory in bytes.
1063  * \param type type of the memory to be mapped.
1064  * \param flags combination of several flags to modify the function actions.
1065  * \param handle will be set to a value that may be used as the offset
1066  * parameter for mmap().
1067  *
1068  * \return zero on success or a negative value on error.
1069  *
1070  * \par Mapping the frame buffer
1071  * For the frame buffer
1072  * - \p offset will be the physical address of the start of the frame buffer,
1073  * - \p size will be the size of the frame buffer in bytes, and
1074  * - \p type will be DRM_FRAME_BUFFER.
1075  *
1076  * \par
1077  * The area mapped will be uncached. If MTRR support is available in the
1078  * kernel, the frame buffer area will be set to write combining.
1079  *
1080  * \par Mapping the MMIO register area
1081  * For the MMIO register area,
1082  * - \p offset will be the physical address of the start of the register area,
1083  * - \p size will be the size of the register area bytes, and
1084  * - \p type will be DRM_REGISTERS.
1085  * \par
1086  * The area mapped will be uncached.
1087  *
1088  * \par Mapping the SAREA
1089  * For the SAREA,
1090  * - \p offset will be ignored and should be set to zero,
1091  * - \p size will be the desired size of the SAREA in bytes,
1092  * - \p type will be DRM_SHM.
1093  *
1094  * \par
1095  * A shared memory area of the requested size will be created and locked in
1096  * kernel memory. This area may be mapped into client-space by using the handle
1097  * returned.
1098  *
1099  * \note May only be called by root.
1100  *
1101  * \internal
1102  * This function is a wrapper around the DRM_IOCTL_ADD_MAP ioctl, passing
1103  * the arguments in a drm_map structure.
1104  */
1105 int drmAddMap(int fd, drm_handle_t offset, drmSize size, drmMapType type,
1106               drmMapFlags flags, drm_handle_t *handle)
1107 {
1108     drm_map_t map;
1109
1110     memclear(map);
1111     map.offset  = offset;
1112     map.size    = size;
1113     map.type    = type;
1114     map.flags   = flags;
1115     if (drmIoctl(fd, DRM_IOCTL_ADD_MAP, &map))
1116         return -errno;
1117     if (handle)
1118         *handle = (drm_handle_t)(uintptr_t)map.handle;
1119     return 0;
1120 }
1121
1122 int drmRmMap(int fd, drm_handle_t handle)
1123 {
1124     drm_map_t map;
1125
1126     memclear(map);
1127     map.handle = (void *)(uintptr_t)handle;
1128
1129     if(drmIoctl(fd, DRM_IOCTL_RM_MAP, &map))
1130         return -errno;
1131     return 0;
1132 }
1133
1134 /**
1135  * Make buffers available for DMA transfers.
1136  *
1137  * \param fd file descriptor.
1138  * \param count number of buffers.
1139  * \param size size of each buffer.
1140  * \param flags buffer allocation flags.
1141  * \param agp_offset offset in the AGP aperture
1142  *
1143  * \return number of buffers allocated, negative on error.
1144  *
1145  * \internal
1146  * This function is a wrapper around DRM_IOCTL_ADD_BUFS ioctl.
1147  *
1148  * \sa drm_buf_desc.
1149  */
1150 int drmAddBufs(int fd, int count, int size, drmBufDescFlags flags,
1151                int agp_offset)
1152 {
1153     drm_buf_desc_t request;
1154
1155     memclear(request);
1156     request.count     = count;
1157     request.size      = size;
1158     request.flags     = flags;
1159     request.agp_start = agp_offset;
1160
1161     if (drmIoctl(fd, DRM_IOCTL_ADD_BUFS, &request))
1162         return -errno;
1163     return request.count;
1164 }
1165
1166 int drmMarkBufs(int fd, double low, double high)
1167 {
1168     drm_buf_info_t info;
1169     int            i;
1170
1171     memclear(info);
1172
1173     if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1174         return -EINVAL;
1175
1176     if (!info.count)
1177         return -EINVAL;
1178
1179     if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1180         return -ENOMEM;
1181
1182     if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1183         int retval = -errno;
1184         drmFree(info.list);
1185         return retval;
1186     }
1187
1188     for (i = 0; i < info.count; i++) {
1189         info.list[i].low_mark  = low  * info.list[i].count;
1190         info.list[i].high_mark = high * info.list[i].count;
1191         if (drmIoctl(fd, DRM_IOCTL_MARK_BUFS, &info.list[i])) {
1192             int retval = -errno;
1193             drmFree(info.list);
1194             return retval;
1195         }
1196     }
1197     drmFree(info.list);
1198
1199     return 0;
1200 }
1201
1202 /**
1203  * Free buffers.
1204  *
1205  * \param fd file descriptor.
1206  * \param count number of buffers to free.
1207  * \param list list of buffers to be freed.
1208  *
1209  * \return zero on success, or a negative value on failure.
1210  *
1211  * \note This function is primarily used for debugging.
1212  *
1213  * \internal
1214  * This function is a wrapper around the DRM_IOCTL_FREE_BUFS ioctl, passing
1215  * the arguments in a drm_buf_free structure.
1216  */
1217 int drmFreeBufs(int fd, int count, int *list)
1218 {
1219     drm_buf_free_t request;
1220
1221     memclear(request);
1222     request.count = count;
1223     request.list  = list;
1224     if (drmIoctl(fd, DRM_IOCTL_FREE_BUFS, &request))
1225         return -errno;
1226     return 0;
1227 }
1228
1229
1230 /**
1231  * Close the device.
1232  *
1233  * \param fd file descriptor.
1234  *
1235  * \internal
1236  * This function closes the file descriptor.
1237  */
1238 int drmClose(int fd)
1239 {
1240     unsigned long key    = drmGetKeyFromFd(fd);
1241     drmHashEntry  *entry = drmGetEntry(fd);
1242
1243     drmHashDestroy(entry->tagTable);
1244     entry->fd       = 0;
1245     entry->f        = NULL;
1246     entry->tagTable = NULL;
1247
1248     drmHashDelete(drmHashTable, key);
1249     drmFree(entry);
1250
1251     return close(fd);
1252 }
1253
1254
1255 /**
1256  * Map a region of memory.
1257  *
1258  * \param fd file descriptor.
1259  * \param handle handle returned by drmAddMap().
1260  * \param size size in bytes. Must match the size used by drmAddMap().
1261  * \param address will contain the user-space virtual address where the mapping
1262  * begins.
1263  *
1264  * \return zero on success, or a negative value on failure.
1265  *
1266  * \internal
1267  * This function is a wrapper for mmap().
1268  */
1269 int drmMap(int fd, drm_handle_t handle, drmSize size, drmAddressPtr address)
1270 {
1271     static unsigned long pagesize_mask = 0;
1272
1273     if (fd < 0)
1274         return -EINVAL;
1275
1276     if (!pagesize_mask)
1277         pagesize_mask = getpagesize() - 1;
1278
1279     size = (size + pagesize_mask) & ~pagesize_mask;
1280
1281     *address = drm_mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1282     if (*address == MAP_FAILED)
1283         return -errno;
1284     return 0;
1285 }
1286
1287
1288 /**
1289  * Unmap mappings obtained with drmMap().
1290  *
1291  * \param address address as given by drmMap().
1292  * \param size size in bytes. Must match the size used by drmMap().
1293  *
1294  * \return zero on success, or a negative value on failure.
1295  *
1296  * \internal
1297  * This function is a wrapper for munmap().
1298  */
1299 int drmUnmap(drmAddress address, drmSize size)
1300 {
1301     return drm_munmap(address, size);
1302 }
1303
1304 drmBufInfoPtr drmGetBufInfo(int fd)
1305 {
1306     drm_buf_info_t info;
1307     drmBufInfoPtr  retval;
1308     int            i;
1309
1310     memclear(info);
1311
1312     if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1313         return NULL;
1314
1315     if (info.count) {
1316         if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1317             return NULL;
1318
1319         if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1320             drmFree(info.list);
1321             return NULL;
1322         }
1323
1324         retval = drmMalloc(sizeof(*retval));
1325         retval->count = info.count;
1326         retval->list  = drmMalloc(info.count * sizeof(*retval->list));
1327         for (i = 0; i < info.count; i++) {
1328             retval->list[i].count     = info.list[i].count;
1329             retval->list[i].size      = info.list[i].size;
1330             retval->list[i].low_mark  = info.list[i].low_mark;
1331             retval->list[i].high_mark = info.list[i].high_mark;
1332         }
1333         drmFree(info.list);
1334         return retval;
1335     }
1336     return NULL;
1337 }
1338
1339 /**
1340  * Map all DMA buffers into client-virtual space.
1341  *
1342  * \param fd file descriptor.
1343  *
1344  * \return a pointer to a ::drmBufMap structure.
1345  *
1346  * \note The client may not use these buffers until obtaining buffer indices
1347  * with drmDMA().
1348  *
1349  * \internal
1350  * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1351  * information about the buffers in a drm_buf_map structure into the
1352  * client-visible data structures.
1353  */
1354 drmBufMapPtr drmMapBufs(int fd)
1355 {
1356     drm_buf_map_t bufs;
1357     drmBufMapPtr  retval;
1358     int           i;
1359
1360     memclear(bufs);
1361     if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1362         return NULL;
1363
1364     if (!bufs.count)
1365         return NULL;
1366
1367     if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1368         return NULL;
1369
1370     if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1371         drmFree(bufs.list);
1372         return NULL;
1373     }
1374
1375     retval = drmMalloc(sizeof(*retval));
1376     retval->count = bufs.count;
1377     retval->list  = drmMalloc(bufs.count * sizeof(*retval->list));
1378     for (i = 0; i < bufs.count; i++) {
1379         retval->list[i].idx     = bufs.list[i].idx;
1380         retval->list[i].total   = bufs.list[i].total;
1381         retval->list[i].used    = 0;
1382         retval->list[i].address = bufs.list[i].address;
1383     }
1384
1385     drmFree(bufs.list);
1386     return retval;
1387 }
1388
1389
1390 /**
1391  * Unmap buffers allocated with drmMapBufs().
1392  *
1393  * \return zero on success, or negative value on failure.
1394  *
1395  * \internal
1396  * Calls munmap() for every buffer stored in \p bufs and frees the
1397  * memory allocated by drmMapBufs().
1398  */
1399 int drmUnmapBufs(drmBufMapPtr bufs)
1400 {
1401     int i;
1402
1403     for (i = 0; i < bufs->count; i++) {
1404         drm_munmap(bufs->list[i].address, bufs->list[i].total);
1405     }
1406
1407     drmFree(bufs->list);
1408     drmFree(bufs);
1409     return 0;
1410 }
1411
1412
1413 #define DRM_DMA_RETRY  16
1414
1415 /**
1416  * Reserve DMA buffers.
1417  *
1418  * \param fd file descriptor.
1419  * \param request
1420  *
1421  * \return zero on success, or a negative value on failure.
1422  *
1423  * \internal
1424  * Assemble the arguments into a drm_dma structure and keeps issuing the
1425  * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1426  */
1427 int drmDMA(int fd, drmDMAReqPtr request)
1428 {
1429     drm_dma_t dma;
1430     int ret, i = 0;
1431
1432     dma.context         = request->context;
1433     dma.send_count      = request->send_count;
1434     dma.send_indices    = request->send_list;
1435     dma.send_sizes      = request->send_sizes;
1436     dma.flags           = request->flags;
1437     dma.request_count   = request->request_count;
1438     dma.request_size    = request->request_size;
1439     dma.request_indices = request->request_list;
1440     dma.request_sizes   = request->request_sizes;
1441     dma.granted_count   = 0;
1442
1443     do {
1444         ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1445     } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1446
1447     if ( ret == 0 ) {
1448         request->granted_count = dma.granted_count;
1449         return 0;
1450     } else {
1451         return -errno;
1452     }
1453 }
1454
1455
1456 /**
1457  * Obtain heavyweight hardware lock.
1458  *
1459  * \param fd file descriptor.
1460  * \param context context.
1461  * \param flags flags that determine the sate of the hardware when the function
1462  * returns.
1463  *
1464  * \return always zero.
1465  *
1466  * \internal
1467  * This function translates the arguments into a drm_lock structure and issue
1468  * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1469  */
1470 int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
1471 {
1472     drm_lock_t lock;
1473
1474     memclear(lock);
1475     lock.context = context;
1476     lock.flags   = 0;
1477     if (flags & DRM_LOCK_READY)      lock.flags |= _DRM_LOCK_READY;
1478     if (flags & DRM_LOCK_QUIESCENT)  lock.flags |= _DRM_LOCK_QUIESCENT;
1479     if (flags & DRM_LOCK_FLUSH)      lock.flags |= _DRM_LOCK_FLUSH;
1480     if (flags & DRM_LOCK_FLUSH_ALL)  lock.flags |= _DRM_LOCK_FLUSH_ALL;
1481     if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
1482     if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
1483
1484     while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
1485         ;
1486     return 0;
1487 }
1488
1489 /**
1490  * Release the hardware lock.
1491  *
1492  * \param fd file descriptor.
1493  * \param context context.
1494  *
1495  * \return zero on success, or a negative value on failure.
1496  *
1497  * \internal
1498  * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
1499  * argument in a drm_lock structure.
1500  */
1501 int drmUnlock(int fd, drm_context_t context)
1502 {
1503     drm_lock_t lock;
1504
1505     memclear(lock);
1506     lock.context = context;
1507     return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
1508 }
1509
1510 drm_context_t *drmGetReservedContextList(int fd, int *count)
1511 {
1512     drm_ctx_res_t res;
1513     drm_ctx_t     *list;
1514     drm_context_t * retval;
1515     int           i;
1516
1517     memclear(res);
1518     if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1519         return NULL;
1520
1521     if (!res.count)
1522         return NULL;
1523
1524     if (!(list   = drmMalloc(res.count * sizeof(*list))))
1525         return NULL;
1526     if (!(retval = drmMalloc(res.count * sizeof(*retval))))
1527         goto err_free_list;
1528
1529     res.contexts = list;
1530     if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1531         goto err_free_context;
1532
1533     for (i = 0; i < res.count; i++)
1534         retval[i] = list[i].handle;
1535     drmFree(list);
1536
1537     *count = res.count;
1538     return retval;
1539
1540 err_free_list:
1541     drmFree(list);
1542 err_free_context:
1543     drmFree(retval);
1544     return NULL;
1545 }
1546
1547 void drmFreeReservedContextList(drm_context_t *pt)
1548 {
1549     drmFree(pt);
1550 }
1551
1552 /**
1553  * Create context.
1554  *
1555  * Used by the X server during GLXContext initialization. This causes
1556  * per-context kernel-level resources to be allocated.
1557  *
1558  * \param fd file descriptor.
1559  * \param handle is set on success. To be used by the client when requesting DMA
1560  * dispatch with drmDMA().
1561  *
1562  * \return zero on success, or a negative value on failure.
1563  *
1564  * \note May only be called by root.
1565  *
1566  * \internal
1567  * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
1568  * argument in a drm_ctx structure.
1569  */
1570 int drmCreateContext(int fd, drm_context_t *handle)
1571 {
1572     drm_ctx_t ctx;
1573
1574     memclear(ctx);
1575     if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
1576         return -errno;
1577     *handle = ctx.handle;
1578     return 0;
1579 }
1580
1581 int drmSwitchToContext(int fd, drm_context_t context)
1582 {
1583     drm_ctx_t ctx;
1584
1585     memclear(ctx);
1586     ctx.handle = context;
1587     if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
1588         return -errno;
1589     return 0;
1590 }
1591
1592 int drmSetContextFlags(int fd, drm_context_t context, drm_context_tFlags flags)
1593 {
1594     drm_ctx_t ctx;
1595
1596     /*
1597      * Context preserving means that no context switches are done between DMA
1598      * buffers from one context and the next.  This is suitable for use in the
1599      * X server (which promises to maintain hardware context), or in the
1600      * client-side library when buffers are swapped on behalf of two threads.
1601      */
1602     memclear(ctx);
1603     ctx.handle = context;
1604     if (flags & DRM_CONTEXT_PRESERVED)
1605         ctx.flags |= _DRM_CONTEXT_PRESERVED;
1606     if (flags & DRM_CONTEXT_2DONLY)
1607         ctx.flags |= _DRM_CONTEXT_2DONLY;
1608     if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
1609         return -errno;
1610     return 0;
1611 }
1612
1613 int drmGetContextFlags(int fd, drm_context_t context,
1614                        drm_context_tFlagsPtr flags)
1615 {
1616     drm_ctx_t ctx;
1617
1618     memclear(ctx);
1619     ctx.handle = context;
1620     if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
1621         return -errno;
1622     *flags = 0;
1623     if (ctx.flags & _DRM_CONTEXT_PRESERVED)
1624         *flags |= DRM_CONTEXT_PRESERVED;
1625     if (ctx.flags & _DRM_CONTEXT_2DONLY)
1626         *flags |= DRM_CONTEXT_2DONLY;
1627     return 0;
1628 }
1629
1630 /**
1631  * Destroy context.
1632  *
1633  * Free any kernel-level resources allocated with drmCreateContext() associated
1634  * with the context.
1635  *
1636  * \param fd file descriptor.
1637  * \param handle handle given by drmCreateContext().
1638  *
1639  * \return zero on success, or a negative value on failure.
1640  *
1641  * \note May only be called by root.
1642  *
1643  * \internal
1644  * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
1645  * argument in a drm_ctx structure.
1646  */
1647 int drmDestroyContext(int fd, drm_context_t handle)
1648 {
1649     drm_ctx_t ctx;
1650
1651     memclear(ctx);
1652     ctx.handle = handle;
1653     if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
1654         return -errno;
1655     return 0;
1656 }
1657
1658 int drmCreateDrawable(int fd, drm_drawable_t *handle)
1659 {
1660     drm_draw_t draw;
1661
1662     memclear(draw);
1663     if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
1664         return -errno;
1665     *handle = draw.handle;
1666     return 0;
1667 }
1668
1669 int drmDestroyDrawable(int fd, drm_drawable_t handle)
1670 {
1671     drm_draw_t draw;
1672
1673     memclear(draw);
1674     draw.handle = handle;
1675     if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
1676         return -errno;
1677     return 0;
1678 }
1679
1680 int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
1681                           drm_drawable_info_type_t type, unsigned int num,
1682                           void *data)
1683 {
1684     drm_update_draw_t update;
1685
1686     memclear(update);
1687     update.handle = handle;
1688     update.type = type;
1689     update.num = num;
1690     update.data = (unsigned long long)(unsigned long)data;
1691
1692     if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
1693         return -errno;
1694
1695     return 0;
1696 }
1697
1698 /**
1699  * Acquire the AGP device.
1700  *
1701  * Must be called before any of the other AGP related calls.
1702  *
1703  * \param fd file descriptor.
1704  *
1705  * \return zero on success, or a negative value on failure.
1706  *
1707  * \internal
1708  * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
1709  */
1710 int drmAgpAcquire(int fd)
1711 {
1712     if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
1713         return -errno;
1714     return 0;
1715 }
1716
1717
1718 /**
1719  * Release the AGP device.
1720  *
1721  * \param fd file descriptor.
1722  *
1723  * \return zero on success, or a negative value on failure.
1724  *
1725  * \internal
1726  * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
1727  */
1728 int drmAgpRelease(int fd)
1729 {
1730     if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
1731         return -errno;
1732     return 0;
1733 }
1734
1735
1736 /**
1737  * Set the AGP mode.
1738  *
1739  * \param fd file descriptor.
1740  * \param mode AGP mode.
1741  *
1742  * \return zero on success, or a negative value on failure.
1743  *
1744  * \internal
1745  * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
1746  * argument in a drm_agp_mode structure.
1747  */
1748 int drmAgpEnable(int fd, unsigned long mode)
1749 {
1750     drm_agp_mode_t m;
1751
1752     memclear(m);
1753     m.mode = mode;
1754     if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
1755         return -errno;
1756     return 0;
1757 }
1758
1759
1760 /**
1761  * Allocate a chunk of AGP memory.
1762  *
1763  * \param fd file descriptor.
1764  * \param size requested memory size in bytes. Will be rounded to page boundary.
1765  * \param type type of memory to allocate.
1766  * \param address if not zero, will be set to the physical address of the
1767  * allocated memory.
1768  * \param handle on success will be set to a handle of the allocated memory.
1769  *
1770  * \return zero on success, or a negative value on failure.
1771  *
1772  * \internal
1773  * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
1774  * arguments in a drm_agp_buffer structure.
1775  */
1776 int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
1777                 unsigned long *address, drm_handle_t *handle)
1778 {
1779     drm_agp_buffer_t b;
1780
1781     memclear(b);
1782     *handle = DRM_AGP_NO_HANDLE;
1783     b.size   = size;
1784     b.type   = type;
1785     if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
1786         return -errno;
1787     if (address != 0UL)
1788         *address = b.physical;
1789     *handle = b.handle;
1790     return 0;
1791 }
1792
1793
1794 /**
1795  * Free a chunk of AGP memory.
1796  *
1797  * \param fd file descriptor.
1798  * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1799  *
1800  * \return zero on success, or a negative value on failure.
1801  *
1802  * \internal
1803  * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
1804  * argument in a drm_agp_buffer structure.
1805  */
1806 int drmAgpFree(int fd, drm_handle_t handle)
1807 {
1808     drm_agp_buffer_t b;
1809
1810     memclear(b);
1811     b.handle = handle;
1812     if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
1813         return -errno;
1814     return 0;
1815 }
1816
1817
1818 /**
1819  * Bind a chunk of AGP memory.
1820  *
1821  * \param fd file descriptor.
1822  * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1823  * \param offset offset in bytes. It will round to page boundary.
1824  *
1825  * \return zero on success, or a negative value on failure.
1826  *
1827  * \internal
1828  * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
1829  * argument in a drm_agp_binding structure.
1830  */
1831 int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
1832 {
1833     drm_agp_binding_t b;
1834
1835     memclear(b);
1836     b.handle = handle;
1837     b.offset = offset;
1838     if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
1839         return -errno;
1840     return 0;
1841 }
1842
1843
1844 /**
1845  * Unbind a chunk of AGP memory.
1846  *
1847  * \param fd file descriptor.
1848  * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1849  *
1850  * \return zero on success, or a negative value on failure.
1851  *
1852  * \internal
1853  * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
1854  * the argument in a drm_agp_binding structure.
1855  */
1856 int drmAgpUnbind(int fd, drm_handle_t handle)
1857 {
1858     drm_agp_binding_t b;
1859
1860     memclear(b);
1861     b.handle = handle;
1862     if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
1863         return -errno;
1864     return 0;
1865 }
1866
1867
1868 /**
1869  * Get AGP driver major version number.
1870  *
1871  * \param fd file descriptor.
1872  *
1873  * \return major version number on success, or a negative value on failure..
1874  *
1875  * \internal
1876  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1877  * necessary information in a drm_agp_info structure.
1878  */
1879 int drmAgpVersionMajor(int fd)
1880 {
1881     drm_agp_info_t i;
1882
1883     memclear(i);
1884
1885     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1886         return -errno;
1887     return i.agp_version_major;
1888 }
1889
1890
1891 /**
1892  * Get AGP driver minor version number.
1893  *
1894  * \param fd file descriptor.
1895  *
1896  * \return minor version number on success, or a negative value on failure.
1897  *
1898  * \internal
1899  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1900  * necessary information in a drm_agp_info structure.
1901  */
1902 int drmAgpVersionMinor(int fd)
1903 {
1904     drm_agp_info_t i;
1905
1906     memclear(i);
1907
1908     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1909         return -errno;
1910     return i.agp_version_minor;
1911 }
1912
1913
1914 /**
1915  * Get AGP mode.
1916  *
1917  * \param fd file descriptor.
1918  *
1919  * \return mode on success, or zero on failure.
1920  *
1921  * \internal
1922  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1923  * necessary information in a drm_agp_info structure.
1924  */
1925 unsigned long drmAgpGetMode(int fd)
1926 {
1927     drm_agp_info_t i;
1928
1929     memclear(i);
1930
1931     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1932         return 0;
1933     return i.mode;
1934 }
1935
1936
1937 /**
1938  * Get AGP aperture base.
1939  *
1940  * \param fd file descriptor.
1941  *
1942  * \return aperture base on success, zero on failure.
1943  *
1944  * \internal
1945  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1946  * necessary information in a drm_agp_info structure.
1947  */
1948 unsigned long drmAgpBase(int fd)
1949 {
1950     drm_agp_info_t i;
1951
1952     memclear(i);
1953
1954     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1955         return 0;
1956     return i.aperture_base;
1957 }
1958
1959
1960 /**
1961  * Get AGP aperture size.
1962  *
1963  * \param fd file descriptor.
1964  *
1965  * \return aperture size on success, zero on failure.
1966  *
1967  * \internal
1968  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1969  * necessary information in a drm_agp_info structure.
1970  */
1971 unsigned long drmAgpSize(int fd)
1972 {
1973     drm_agp_info_t i;
1974
1975     memclear(i);
1976
1977     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1978         return 0;
1979     return i.aperture_size;
1980 }
1981
1982
1983 /**
1984  * Get used AGP memory.
1985  *
1986  * \param fd file descriptor.
1987  *
1988  * \return memory used on success, or zero on failure.
1989  *
1990  * \internal
1991  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1992  * necessary information in a drm_agp_info structure.
1993  */
1994 unsigned long drmAgpMemoryUsed(int fd)
1995 {
1996     drm_agp_info_t i;
1997
1998     memclear(i);
1999
2000     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2001         return 0;
2002     return i.memory_used;
2003 }
2004
2005
2006 /**
2007  * Get available AGP memory.
2008  *
2009  * \param fd file descriptor.
2010  *
2011  * \return memory available on success, or zero on failure.
2012  *
2013  * \internal
2014  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2015  * necessary information in a drm_agp_info structure.
2016  */
2017 unsigned long drmAgpMemoryAvail(int fd)
2018 {
2019     drm_agp_info_t i;
2020
2021     memclear(i);
2022
2023     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2024         return 0;
2025     return i.memory_allowed;
2026 }
2027
2028
2029 /**
2030  * Get hardware vendor ID.
2031  *
2032  * \param fd file descriptor.
2033  *
2034  * \return vendor ID on success, or zero on failure.
2035  *
2036  * \internal
2037  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2038  * necessary information in a drm_agp_info structure.
2039  */
2040 unsigned int drmAgpVendorId(int fd)
2041 {
2042     drm_agp_info_t i;
2043
2044     memclear(i);
2045
2046     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2047         return 0;
2048     return i.id_vendor;
2049 }
2050
2051
2052 /**
2053  * Get hardware device ID.
2054  *
2055  * \param fd file descriptor.
2056  *
2057  * \return zero on success, or zero on failure.
2058  *
2059  * \internal
2060  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2061  * necessary information in a drm_agp_info structure.
2062  */
2063 unsigned int drmAgpDeviceId(int fd)
2064 {
2065     drm_agp_info_t i;
2066
2067     memclear(i);
2068
2069     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2070         return 0;
2071     return i.id_device;
2072 }
2073
2074 int drmScatterGatherAlloc(int fd, unsigned long size, drm_handle_t *handle)
2075 {
2076     drm_scatter_gather_t sg;
2077
2078     memclear(sg);
2079
2080     *handle = 0;
2081     sg.size   = size;
2082     if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
2083         return -errno;
2084     *handle = sg.handle;
2085     return 0;
2086 }
2087
2088 int drmScatterGatherFree(int fd, drm_handle_t handle)
2089 {
2090     drm_scatter_gather_t sg;
2091
2092     memclear(sg);
2093     sg.handle = handle;
2094     if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
2095         return -errno;
2096     return 0;
2097 }
2098
2099 /**
2100  * Wait for VBLANK.
2101  *
2102  * \param fd file descriptor.
2103  * \param vbl pointer to a drmVBlank structure.
2104  *
2105  * \return zero on success, or a negative value on failure.
2106  *
2107  * \internal
2108  * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
2109  */
2110 int drmWaitVBlank(int fd, drmVBlankPtr vbl)
2111 {
2112     struct timespec timeout, cur;
2113     int ret;
2114
2115     ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2116     if (ret < 0) {
2117         fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
2118         goto out;
2119     }
2120     timeout.tv_sec++;
2121
2122     do {
2123        ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
2124        vbl->request.type &= ~DRM_VBLANK_RELATIVE;
2125        if (ret && errno == EINTR) {
2126            clock_gettime(CLOCK_MONOTONIC, &cur);
2127            /* Timeout after 1s */
2128            if (cur.tv_sec > timeout.tv_sec + 1 ||
2129                (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
2130                 timeout.tv_nsec)) {
2131                    errno = EBUSY;
2132                    ret = -1;
2133                    break;
2134            }
2135        }
2136     } while (ret && errno == EINTR);
2137
2138 out:
2139     return ret;
2140 }
2141
2142 int drmError(int err, const char *label)
2143 {
2144     switch (err) {
2145     case DRM_ERR_NO_DEVICE:
2146         fprintf(stderr, "%s: no device\n", label);
2147         break;
2148     case DRM_ERR_NO_ACCESS:
2149         fprintf(stderr, "%s: no access\n", label);
2150         break;
2151     case DRM_ERR_NOT_ROOT:
2152         fprintf(stderr, "%s: not root\n", label);
2153         break;
2154     case DRM_ERR_INVALID:
2155         fprintf(stderr, "%s: invalid args\n", label);
2156         break;
2157     default:
2158         if (err < 0)
2159             err = -err;
2160         fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2161         break;
2162     }
2163
2164     return 1;
2165 }
2166
2167 /**
2168  * Install IRQ handler.
2169  *
2170  * \param fd file descriptor.
2171  * \param irq IRQ number.
2172  *
2173  * \return zero on success, or a negative value on failure.
2174  *
2175  * \internal
2176  * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2177  * argument in a drm_control structure.
2178  */
2179 int drmCtlInstHandler(int fd, int irq)
2180 {
2181     drm_control_t ctl;
2182
2183     memclear(ctl);
2184     ctl.func  = DRM_INST_HANDLER;
2185     ctl.irq   = irq;
2186     if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2187         return -errno;
2188     return 0;
2189 }
2190
2191
2192 /**
2193  * Uninstall IRQ handler.
2194  *
2195  * \param fd file descriptor.
2196  *
2197  * \return zero on success, or a negative value on failure.
2198  *
2199  * \internal
2200  * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2201  * argument in a drm_control structure.
2202  */
2203 int drmCtlUninstHandler(int fd)
2204 {
2205     drm_control_t ctl;
2206
2207     memclear(ctl);
2208     ctl.func  = DRM_UNINST_HANDLER;
2209     ctl.irq   = 0;
2210     if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2211         return -errno;
2212     return 0;
2213 }
2214
2215 int drmFinish(int fd, int context, drmLockFlags flags)
2216 {
2217     drm_lock_t lock;
2218
2219     memclear(lock);
2220     lock.context = context;
2221     if (flags & DRM_LOCK_READY)      lock.flags |= _DRM_LOCK_READY;
2222     if (flags & DRM_LOCK_QUIESCENT)  lock.flags |= _DRM_LOCK_QUIESCENT;
2223     if (flags & DRM_LOCK_FLUSH)      lock.flags |= _DRM_LOCK_FLUSH;
2224     if (flags & DRM_LOCK_FLUSH_ALL)  lock.flags |= _DRM_LOCK_FLUSH_ALL;
2225     if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2226     if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2227     if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2228         return -errno;
2229     return 0;
2230 }
2231
2232 /**
2233  * Get IRQ from bus ID.
2234  *
2235  * \param fd file descriptor.
2236  * \param busnum bus number.
2237  * \param devnum device number.
2238  * \param funcnum function number.
2239  *
2240  * \return IRQ number on success, or a negative value on failure.
2241  *
2242  * \internal
2243  * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2244  * arguments in a drm_irq_busid structure.
2245  */
2246 int drmGetInterruptFromBusID(int fd, int busnum, int devnum, int funcnum)
2247 {
2248     drm_irq_busid_t p;
2249
2250     memclear(p);
2251     p.busnum  = busnum;
2252     p.devnum  = devnum;
2253     p.funcnum = funcnum;
2254     if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2255         return -errno;
2256     return p.irq;
2257 }
2258
2259 int drmAddContextTag(int fd, drm_context_t context, void *tag)
2260 {
2261     drmHashEntry  *entry = drmGetEntry(fd);
2262
2263     if (drmHashInsert(entry->tagTable, context, tag)) {
2264         drmHashDelete(entry->tagTable, context);
2265         drmHashInsert(entry->tagTable, context, tag);
2266     }
2267     return 0;
2268 }
2269
2270 int drmDelContextTag(int fd, drm_context_t context)
2271 {
2272     drmHashEntry  *entry = drmGetEntry(fd);
2273
2274     return drmHashDelete(entry->tagTable, context);
2275 }
2276
2277 void *drmGetContextTag(int fd, drm_context_t context)
2278 {
2279     drmHashEntry  *entry = drmGetEntry(fd);
2280     void          *value;
2281
2282     if (drmHashLookup(entry->tagTable, context, &value))
2283         return NULL;
2284
2285     return value;
2286 }
2287
2288 int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2289                                 drm_handle_t handle)
2290 {
2291     drm_ctx_priv_map_t map;
2292
2293     memclear(map);
2294     map.ctx_id = ctx_id;
2295     map.handle = (void *)(uintptr_t)handle;
2296
2297     if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2298         return -errno;
2299     return 0;
2300 }
2301
2302 int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2303                                 drm_handle_t *handle)
2304 {
2305     drm_ctx_priv_map_t map;
2306
2307     memclear(map);
2308     map.ctx_id = ctx_id;
2309
2310     if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2311         return -errno;
2312     if (handle)
2313         *handle = (drm_handle_t)(uintptr_t)map.handle;
2314
2315     return 0;
2316 }
2317
2318 int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2319               drmMapType *type, drmMapFlags *flags, drm_handle_t *handle,
2320               int *mtrr)
2321 {
2322     drm_map_t map;
2323
2324     memclear(map);
2325     map.offset = idx;
2326     if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2327         return -errno;
2328     *offset = map.offset;
2329     *size   = map.size;
2330     *type   = map.type;
2331     *flags  = map.flags;
2332     *handle = (unsigned long)map.handle;
2333     *mtrr   = map.mtrr;
2334     return 0;
2335 }
2336
2337 int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2338                  unsigned long *magic, unsigned long *iocs)
2339 {
2340     drm_client_t client;
2341
2342     memclear(client);
2343     client.idx = idx;
2344     if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2345         return -errno;
2346     *auth      = client.auth;
2347     *pid       = client.pid;
2348     *uid       = client.uid;
2349     *magic     = client.magic;
2350     *iocs      = client.iocs;
2351     return 0;
2352 }
2353
2354 int drmGetStats(int fd, drmStatsT *stats)
2355 {
2356     drm_stats_t s;
2357     unsigned    i;
2358
2359     memclear(s);
2360     if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2361         return -errno;
2362
2363     stats->count = 0;
2364     memset(stats, 0, sizeof(*stats));
2365     if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2366         return -1;
2367
2368 #define SET_VALUE                              \
2369     stats->data[i].long_format = "%-20.20s";   \
2370     stats->data[i].rate_format = "%8.8s";      \
2371     stats->data[i].isvalue     = 1;            \
2372     stats->data[i].verbose     = 0
2373
2374 #define SET_COUNT                              \
2375     stats->data[i].long_format = "%-20.20s";   \
2376     stats->data[i].rate_format = "%5.5s";      \
2377     stats->data[i].isvalue     = 0;            \
2378     stats->data[i].mult_names  = "kgm";        \
2379     stats->data[i].mult        = 1000;         \
2380     stats->data[i].verbose     = 0
2381
2382 #define SET_BYTE                               \
2383     stats->data[i].long_format = "%-20.20s";   \
2384     stats->data[i].rate_format = "%5.5s";      \
2385     stats->data[i].isvalue     = 0;            \
2386     stats->data[i].mult_names  = "KGM";        \
2387     stats->data[i].mult        = 1024;         \
2388     stats->data[i].verbose     = 0
2389
2390
2391     stats->count = s.count;
2392     for (i = 0; i < s.count; i++) {
2393         stats->data[i].value = s.data[i].value;
2394         switch (s.data[i].type) {
2395         case _DRM_STAT_LOCK:
2396             stats->data[i].long_name = "Lock";
2397             stats->data[i].rate_name = "Lock";
2398             SET_VALUE;
2399             break;
2400         case _DRM_STAT_OPENS:
2401             stats->data[i].long_name = "Opens";
2402             stats->data[i].rate_name = "O";
2403             SET_COUNT;
2404             stats->data[i].verbose   = 1;
2405             break;
2406         case _DRM_STAT_CLOSES:
2407             stats->data[i].long_name = "Closes";
2408             stats->data[i].rate_name = "Lock";
2409             SET_COUNT;
2410             stats->data[i].verbose   = 1;
2411             break;
2412         case _DRM_STAT_IOCTLS:
2413             stats->data[i].long_name = "Ioctls";
2414             stats->data[i].rate_name = "Ioc/s";
2415             SET_COUNT;
2416             break;
2417         case _DRM_STAT_LOCKS:
2418             stats->data[i].long_name = "Locks";
2419             stats->data[i].rate_name = "Lck/s";
2420             SET_COUNT;
2421             break;
2422         case _DRM_STAT_UNLOCKS:
2423             stats->data[i].long_name = "Unlocks";
2424             stats->data[i].rate_name = "Unl/s";
2425             SET_COUNT;
2426             break;
2427         case _DRM_STAT_IRQ:
2428             stats->data[i].long_name = "IRQs";
2429             stats->data[i].rate_name = "IRQ/s";
2430             SET_COUNT;
2431             break;
2432         case _DRM_STAT_PRIMARY:
2433             stats->data[i].long_name = "Primary Bytes";
2434             stats->data[i].rate_name = "PB/s";
2435             SET_BYTE;
2436             break;
2437         case _DRM_STAT_SECONDARY:
2438             stats->data[i].long_name = "Secondary Bytes";
2439             stats->data[i].rate_name = "SB/s";
2440             SET_BYTE;
2441             break;
2442         case _DRM_STAT_DMA:
2443             stats->data[i].long_name = "DMA";
2444             stats->data[i].rate_name = "DMA/s";
2445             SET_COUNT;
2446             break;
2447         case _DRM_STAT_SPECIAL:
2448             stats->data[i].long_name = "Special DMA";
2449             stats->data[i].rate_name = "dma/s";
2450             SET_COUNT;
2451             break;
2452         case _DRM_STAT_MISSED:
2453             stats->data[i].long_name = "Miss";
2454             stats->data[i].rate_name = "Ms/s";
2455             SET_COUNT;
2456             break;
2457         case _DRM_STAT_VALUE:
2458             stats->data[i].long_name = "Value";
2459             stats->data[i].rate_name = "Value";
2460             SET_VALUE;
2461             break;
2462         case _DRM_STAT_BYTE:
2463             stats->data[i].long_name = "Bytes";
2464             stats->data[i].rate_name = "B/s";
2465             SET_BYTE;
2466             break;
2467         case _DRM_STAT_COUNT:
2468         default:
2469             stats->data[i].long_name = "Count";
2470             stats->data[i].rate_name = "Cnt/s";
2471             SET_COUNT;
2472             break;
2473         }
2474     }
2475     return 0;
2476 }
2477
2478 /**
2479  * Issue a set-version ioctl.
2480  *
2481  * \param fd file descriptor.
2482  * \param drmCommandIndex command index
2483  * \param data source pointer of the data to be read and written.
2484  * \param size size of the data to be read and written.
2485  *
2486  * \return zero on success, or a negative value on failure.
2487  *
2488  * \internal
2489  * It issues a read-write ioctl given by
2490  * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2491  */
2492 int drmSetInterfaceVersion(int fd, drmSetVersion *version)
2493 {
2494     int retcode = 0;
2495     drm_set_version_t sv;
2496
2497     memclear(sv);
2498     sv.drm_di_major = version->drm_di_major;
2499     sv.drm_di_minor = version->drm_di_minor;
2500     sv.drm_dd_major = version->drm_dd_major;
2501     sv.drm_dd_minor = version->drm_dd_minor;
2502
2503     if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
2504         retcode = -errno;
2505     }
2506
2507     version->drm_di_major = sv.drm_di_major;
2508     version->drm_di_minor = sv.drm_di_minor;
2509     version->drm_dd_major = sv.drm_dd_major;
2510     version->drm_dd_minor = sv.drm_dd_minor;
2511
2512     return retcode;
2513 }
2514
2515 /**
2516  * Send a device-specific command.
2517  *
2518  * \param fd file descriptor.
2519  * \param drmCommandIndex command index
2520  *
2521  * \return zero on success, or a negative value on failure.
2522  *
2523  * \internal
2524  * It issues a ioctl given by
2525  * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2526  */
2527 int drmCommandNone(int fd, unsigned long drmCommandIndex)
2528 {
2529     unsigned long request;
2530
2531     request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
2532
2533     if (drmIoctl(fd, request, NULL)) {
2534         return -errno;
2535     }
2536     return 0;
2537 }
2538
2539
2540 /**
2541  * Send a device-specific read command.
2542  *
2543  * \param fd file descriptor.
2544  * \param drmCommandIndex command index
2545  * \param data destination pointer of the data to be read.
2546  * \param size size of the data to be read.
2547  *
2548  * \return zero on success, or a negative value on failure.
2549  *
2550  * \internal
2551  * It issues a read ioctl given by
2552  * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2553  */
2554 int drmCommandRead(int fd, unsigned long drmCommandIndex, void *data,
2555                    unsigned long size)
2556 {
2557     unsigned long request;
2558
2559     request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
2560         DRM_COMMAND_BASE + drmCommandIndex, size);
2561
2562     if (drmIoctl(fd, request, data)) {
2563         return -errno;
2564     }
2565     return 0;
2566 }
2567
2568
2569 /**
2570  * Send a device-specific write command.
2571  *
2572  * \param fd file descriptor.
2573  * \param drmCommandIndex command index
2574  * \param data source pointer of the data to be written.
2575  * \param size size of the data to be written.
2576  *
2577  * \return zero on success, or a negative value on failure.
2578  *
2579  * \internal
2580  * It issues a write ioctl given by
2581  * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2582  */
2583 int drmCommandWrite(int fd, unsigned long drmCommandIndex, void *data,
2584                     unsigned long size)
2585 {
2586     unsigned long request;
2587
2588     request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
2589         DRM_COMMAND_BASE + drmCommandIndex, size);
2590
2591     if (drmIoctl(fd, request, data)) {
2592         return -errno;
2593     }
2594     return 0;
2595 }
2596
2597
2598 /**
2599  * Send a device-specific read-write command.
2600  *
2601  * \param fd file descriptor.
2602  * \param drmCommandIndex command index
2603  * \param data source pointer of the data to be read and written.
2604  * \param size size of the data to be read and written.
2605  *
2606  * \return zero on success, or a negative value on failure.
2607  *
2608  * \internal
2609  * It issues a read-write ioctl given by
2610  * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2611  */
2612 int drmCommandWriteRead(int fd, unsigned long drmCommandIndex, void *data,
2613                         unsigned long size)
2614 {
2615     unsigned long request;
2616
2617     request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
2618         DRM_COMMAND_BASE + drmCommandIndex, size);
2619
2620     if (drmIoctl(fd, request, data))
2621         return -errno;
2622     return 0;
2623 }
2624
2625 #define DRM_MAX_FDS 16
2626 static struct {
2627     char *BusID;
2628     int fd;
2629     int refcount;
2630     int type;
2631 } connection[DRM_MAX_FDS];
2632
2633 static int nr_fds = 0;
2634
2635 int drmOpenOnce(void *unused,
2636                 const char *BusID,
2637                 int *newlyopened)
2638 {
2639     return drmOpenOnceWithType(BusID, newlyopened, DRM_NODE_PRIMARY);
2640 }
2641
2642 int drmOpenOnceWithType(const char *BusID, int *newlyopened, int type)
2643 {
2644     int i;
2645     int fd;
2646
2647     for (i = 0; i < nr_fds; i++)
2648         if ((strcmp(BusID, connection[i].BusID) == 0) &&
2649             (connection[i].type == type)) {
2650             connection[i].refcount++;
2651             *newlyopened = 0;
2652             return connection[i].fd;
2653         }
2654
2655     fd = drmOpenWithType(NULL, BusID, type);
2656     if (fd < 0 || nr_fds == DRM_MAX_FDS)
2657         return fd;
2658
2659     connection[nr_fds].BusID = strdup(BusID);
2660     connection[nr_fds].fd = fd;
2661     connection[nr_fds].refcount = 1;
2662     connection[nr_fds].type = type;
2663     *newlyopened = 1;
2664
2665     if (0)
2666         fprintf(stderr, "saved connection %d for %s %d\n",
2667                 nr_fds, connection[nr_fds].BusID,
2668                 strcmp(BusID, connection[nr_fds].BusID));
2669
2670     nr_fds++;
2671
2672     return fd;
2673 }
2674
2675 void drmCloseOnce(int fd)
2676 {
2677     int i;
2678
2679     for (i = 0; i < nr_fds; i++) {
2680         if (fd == connection[i].fd) {
2681             if (--connection[i].refcount == 0) {
2682                 drmClose(connection[i].fd);
2683                 free(connection[i].BusID);
2684
2685                 if (i < --nr_fds)
2686                     connection[i] = connection[nr_fds];
2687
2688                 return;
2689             }
2690         }
2691     }
2692 }
2693
2694 int drmSetMaster(int fd)
2695 {
2696         return drmIoctl(fd, DRM_IOCTL_SET_MASTER, NULL);
2697 }
2698
2699 int drmDropMaster(int fd)
2700 {
2701         return drmIoctl(fd, DRM_IOCTL_DROP_MASTER, NULL);
2702 }
2703
2704 char *drmGetDeviceNameFromFd(int fd)
2705 {
2706     char name[128];
2707     struct stat sbuf;
2708     dev_t d;
2709     int i;
2710
2711     /* The whole drmOpen thing is a fiasco and we need to find a way
2712      * back to just using open(2).  For now, however, lets just make
2713      * things worse with even more ad hoc directory walking code to
2714      * discover the device file name. */
2715
2716     fstat(fd, &sbuf);
2717     d = sbuf.st_rdev;
2718
2719     for (i = 0; i < DRM_MAX_MINOR; i++) {
2720         snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
2721         if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
2722             break;
2723     }
2724     if (i == DRM_MAX_MINOR)
2725         return NULL;
2726
2727     return strdup(name);
2728 }
2729
2730 int drmGetNodeTypeFromFd(int fd)
2731 {
2732     struct stat sbuf;
2733     int maj, min, type;
2734
2735     if (fstat(fd, &sbuf))
2736         return -1;
2737
2738     maj = major(sbuf.st_rdev);
2739     min = minor(sbuf.st_rdev);
2740
2741     if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode)) {
2742         errno = EINVAL;
2743         return -1;
2744     }
2745
2746     type = drmGetMinorType(min);
2747     if (type == -1)
2748         errno = ENODEV;
2749     return type;
2750 }
2751
2752 int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags, int *prime_fd)
2753 {
2754     struct drm_prime_handle args;
2755     int ret;
2756
2757     memclear(args);
2758     args.fd = -1;
2759     args.handle = handle;
2760     args.flags = flags;
2761     ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
2762     if (ret)
2763         return ret;
2764
2765     *prime_fd = args.fd;
2766     return 0;
2767 }
2768
2769 int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
2770 {
2771     struct drm_prime_handle args;
2772     int ret;
2773
2774     memclear(args);
2775     args.fd = prime_fd;
2776     ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
2777     if (ret)
2778         return ret;
2779
2780     *handle = args.handle;
2781     return 0;
2782 }
2783
2784 static char *drmGetMinorNameForFD(int fd, int type)
2785 {
2786 #ifdef __linux__
2787     DIR *sysdir;
2788     struct dirent *pent, *ent;
2789     struct stat sbuf;
2790     const char *name = drmGetMinorName(type);
2791     int len;
2792     char dev_name[64], buf[64];
2793     long name_max;
2794     int maj, min;
2795
2796     if (!name)
2797         return NULL;
2798
2799     len = strlen(name);
2800
2801     if (fstat(fd, &sbuf))
2802         return NULL;
2803
2804     maj = major(sbuf.st_rdev);
2805     min = minor(sbuf.st_rdev);
2806
2807     if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
2808         return NULL;
2809
2810     snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
2811
2812     sysdir = opendir(buf);
2813     if (!sysdir)
2814         return NULL;
2815
2816     name_max = fpathconf(dirfd(sysdir), _PC_NAME_MAX);
2817     if (name_max == -1)
2818         goto out_close_dir;
2819
2820     pent = malloc(offsetof(struct dirent, d_name) + name_max + 1);
2821     if (pent == NULL)
2822          goto out_close_dir;
2823
2824     while (readdir_r(sysdir, pent, &ent) == 0 && ent != NULL) {
2825         if (strncmp(ent->d_name, name, len) == 0) {
2826             snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
2827                  ent->d_name);
2828
2829             free(pent);
2830             closedir(sysdir);
2831
2832             return strdup(dev_name);
2833         }
2834     }
2835
2836     free(pent);
2837
2838 out_close_dir:
2839     closedir(sysdir);
2840 #else
2841     struct stat sbuf;
2842     char buf[PATH_MAX + 1];
2843     const char *dev_name;
2844     unsigned int maj, min;
2845     int n, base;
2846
2847     if (fstat(fd, &sbuf))
2848         return NULL;
2849
2850     maj = major(sbuf.st_rdev);
2851     min = minor(sbuf.st_rdev);
2852
2853     if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
2854         return NULL;
2855
2856     switch (type) {
2857     case DRM_NODE_PRIMARY:
2858         dev_name = DRM_DEV_NAME;
2859         break;
2860     case DRM_NODE_CONTROL:
2861         dev_name = DRM_CONTROL_DEV_NAME;
2862         break;
2863     case DRM_NODE_RENDER:
2864         dev_name = DRM_RENDER_DEV_NAME;
2865         break;
2866     default:
2867         return NULL;
2868     };
2869
2870     base = drmGetMinorBase(type);
2871     if (base < 0)
2872         return NULL;
2873
2874     n = snprintf(buf, sizeof(buf), dev_name, DRM_DIR_NAME, min - base);
2875     if (n == -1 || n >= sizeof(buf))
2876         return NULL;
2877
2878     return strdup(buf);
2879 #endif
2880     return NULL;
2881 }
2882
2883 char *drmGetPrimaryDeviceNameFromFd(int fd)
2884 {
2885     return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
2886 }
2887
2888 char *drmGetRenderDeviceNameFromFd(int fd)
2889 {
2890     return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
2891 }
2892
2893 #ifdef __linux__
2894 static char * DRM_PRINTFLIKE(2, 3)
2895 sysfs_uevent_get(const char *path, const char *fmt, ...)
2896 {
2897     char filename[PATH_MAX + 1], *key, *line = NULL, *value = NULL;
2898     size_t size = 0, len;
2899     ssize_t num;
2900     va_list ap;
2901     FILE *fp;
2902
2903     va_start(ap, fmt);
2904     num = vasprintf(&key, fmt, ap);
2905     va_end(ap);
2906     len = num;
2907
2908     snprintf(filename, sizeof(filename), "%s/uevent", path);
2909
2910     fp = fopen(filename, "r");
2911     if (!fp) {
2912         free(key);
2913         return NULL;
2914     }
2915
2916     while ((num = getline(&line, &size, fp)) >= 0) {
2917         if ((strncmp(line, key, len) == 0) && (line[len] == '=')) {
2918             char *start = line + len + 1, *end = line + num - 1;
2919
2920             if (*end != '\n')
2921                 end++;
2922
2923             value = strndup(start, end - start);
2924             break;
2925         }
2926     }
2927
2928     free(line);
2929     fclose(fp);
2930
2931     free(key);
2932
2933     return value;
2934 }
2935 #endif
2936
2937 static int drmParseSubsystemType(int maj, int min)
2938 {
2939 #ifdef __linux__
2940     char path[PATH_MAX + 1];
2941     char link[PATH_MAX + 1] = "";
2942     char *name;
2943
2944     snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/subsystem",
2945              maj, min);
2946
2947     if (readlink(path, link, PATH_MAX) < 0)
2948         return -errno;
2949
2950     name = strrchr(link, '/');
2951     if (!name)
2952         return -EINVAL;
2953
2954     if (strncmp(name, "/pci", 4) == 0)
2955         return DRM_BUS_PCI;
2956
2957     if (strncmp(name, "/usb", 4) == 0)
2958         return DRM_BUS_USB;
2959
2960     if (strncmp(name, "/platform", 9) == 0)
2961         return DRM_BUS_PLATFORM;
2962
2963     if (strncmp(name, "/host1x", 7) == 0)
2964         return DRM_BUS_HOST1X;
2965
2966     return -EINVAL;
2967 #elif defined(__OpenBSD__)
2968     return DRM_BUS_PCI;
2969 #else
2970 #warning "Missing implementation of drmParseSubsystemType"
2971     return -EINVAL;
2972 #endif
2973 }
2974
2975 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
2976 {
2977 #ifdef __linux__
2978     unsigned int domain, bus, dev, func;
2979     char path[PATH_MAX + 1], *value;
2980     int num;
2981
2982     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
2983
2984     value = sysfs_uevent_get(path, "PCI_SLOT_NAME");
2985     if (!value)
2986         return -ENOENT;
2987
2988     num = sscanf(value, "%04x:%02x:%02x.%1u", &domain, &bus, &dev, &func);
2989     free(value);
2990
2991     if (num != 4)
2992         return -EINVAL;
2993
2994     info->domain = domain;
2995     info->bus = bus;
2996     info->dev = dev;
2997     info->func = func;
2998
2999     return 0;
3000 #elif defined(__OpenBSD__)
3001     struct drm_pciinfo pinfo;
3002     int fd, type;
3003
3004     type = drmGetMinorType(min);
3005     if (type == -1)
3006         return -ENODEV;
3007
3008     fd = drmOpenMinor(min, 0, type);
3009     if (fd < 0)
3010         return -errno;
3011
3012     if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3013         close(fd);
3014         return -errno;
3015     }
3016     close(fd);
3017
3018     info->domain = pinfo.domain;
3019     info->bus = pinfo.bus;
3020     info->dev = pinfo.dev;
3021     info->func = pinfo.func;
3022
3023     return 0;
3024 #else
3025 #warning "Missing implementation of drmParsePciBusInfo"
3026     return -EINVAL;
3027 #endif
3028 }
3029
3030 int drmDevicesEqual(drmDevicePtr a, drmDevicePtr b)
3031 {
3032     if (a == NULL || b == NULL)
3033         return 0;
3034
3035     if (a->bustype != b->bustype)
3036         return 0;
3037
3038     switch (a->bustype) {
3039     case DRM_BUS_PCI:
3040         return memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo)) == 0;
3041
3042     case DRM_BUS_USB:
3043         return memcmp(a->businfo.usb, b->businfo.usb, sizeof(drmUsbBusInfo)) == 0;
3044
3045     case DRM_BUS_PLATFORM:
3046         return memcmp(a->businfo.platform, b->businfo.platform, sizeof(drmPlatformBusInfo)) == 0;
3047
3048     case DRM_BUS_HOST1X:
3049         return memcmp(a->businfo.host1x, b->businfo.host1x, sizeof(drmHost1xBusInfo)) == 0;
3050
3051     default:
3052         break;
3053     }
3054
3055     return 0;
3056 }
3057
3058 static int drmGetNodeType(const char *name)
3059 {
3060     if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
3061         sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
3062         return DRM_NODE_PRIMARY;
3063
3064     if (strncmp(name, DRM_CONTROL_MINOR_NAME,
3065         sizeof(DRM_CONTROL_MINOR_NAME ) - 1) == 0)
3066         return DRM_NODE_CONTROL;
3067
3068     if (strncmp(name, DRM_RENDER_MINOR_NAME,
3069         sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
3070         return DRM_NODE_RENDER;
3071
3072     return -EINVAL;
3073 }
3074
3075 static int drmGetMaxNodeName(void)
3076 {
3077     return sizeof(DRM_DIR_NAME) +
3078            MAX3(sizeof(DRM_PRIMARY_MINOR_NAME),
3079                 sizeof(DRM_CONTROL_MINOR_NAME),
3080                 sizeof(DRM_RENDER_MINOR_NAME)) +
3081            3 /* length of the node number */;
3082 }
3083
3084 #ifdef __linux__
3085 static int parse_separate_sysfs_files(int maj, int min,
3086                                       drmPciDeviceInfoPtr device,
3087                                       bool ignore_revision)
3088 {
3089 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3090     static const char *attrs[] = {
3091       "revision", /* Older kernels are missing the file, so check for it first */
3092       "vendor",
3093       "device",
3094       "subsystem_vendor",
3095       "subsystem_device",
3096     };
3097     char path[PATH_MAX + 1];
3098     unsigned int data[ARRAY_SIZE(attrs)];
3099     FILE *fp;
3100     int ret;
3101
3102     for (unsigned i = ignore_revision ? 1 : 0; i < ARRAY_SIZE(attrs); i++) {
3103         snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/%s", maj, min,
3104                  attrs[i]);
3105         fp = fopen(path, "r");
3106         if (!fp)
3107             return -errno;
3108
3109         ret = fscanf(fp, "%x", &data[i]);
3110         fclose(fp);
3111         if (ret != 1)
3112             return -errno;
3113
3114     }
3115
3116     device->revision_id = ignore_revision ? 0xff : data[0] & 0xff;
3117     device->vendor_id = data[1] & 0xffff;
3118     device->device_id = data[2] & 0xffff;
3119     device->subvendor_id = data[3] & 0xffff;
3120     device->subdevice_id = data[4] & 0xffff;
3121
3122     return 0;
3123 }
3124
3125 static int parse_config_sysfs_file(int maj, int min,
3126                                    drmPciDeviceInfoPtr device)
3127 {
3128     char path[PATH_MAX + 1];
3129     unsigned char config[64];
3130     int fd, ret;
3131
3132     snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/config", maj, min);
3133     fd = open(path, O_RDONLY);
3134     if (fd < 0)
3135         return -errno;
3136
3137     ret = read(fd, config, sizeof(config));
3138     close(fd);
3139     if (ret < 0)
3140         return -errno;
3141
3142     device->vendor_id = config[0] | (config[1] << 8);
3143     device->device_id = config[2] | (config[3] << 8);
3144     device->revision_id = config[8];
3145     device->subvendor_id = config[44] | (config[45] << 8);
3146     device->subdevice_id = config[46] | (config[47] << 8);
3147
3148     return 0;
3149 }
3150 #endif
3151
3152 static int drmParsePciDeviceInfo(int maj, int min,
3153                                  drmPciDeviceInfoPtr device,
3154                                  uint32_t flags)
3155 {
3156 #ifdef __linux__
3157     if (!(flags & DRM_DEVICE_GET_PCI_REVISION))
3158         return parse_separate_sysfs_files(maj, min, device, true);
3159
3160     if (parse_separate_sysfs_files(maj, min, device, false))
3161         return parse_config_sysfs_file(maj, min, device);
3162
3163     return 0;
3164 #elif defined(__OpenBSD__)
3165     struct drm_pciinfo pinfo;
3166     int fd, type;
3167
3168     type = drmGetMinorType(min);
3169     if (type == -1)
3170         return -ENODEV;
3171
3172     fd = drmOpenMinor(min, 0, type);
3173     if (fd < 0)
3174         return -errno;
3175
3176     if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3177         close(fd);
3178         return -errno;
3179     }
3180     close(fd);
3181
3182     device->vendor_id = pinfo.vendor_id;
3183     device->device_id = pinfo.device_id;
3184     device->revision_id = pinfo.revision_id;
3185     device->subvendor_id = pinfo.subvendor_id;
3186     device->subdevice_id = pinfo.subdevice_id;
3187
3188     return 0;
3189 #else
3190 #warning "Missing implementation of drmParsePciDeviceInfo"
3191     return -EINVAL;
3192 #endif
3193 }
3194
3195 static void drmFreePlatformDevice(drmDevicePtr device)
3196 {
3197     if (device->deviceinfo.platform) {
3198         if (device->deviceinfo.platform->compatible) {
3199             char **compatible = device->deviceinfo.platform->compatible;
3200
3201             while (*compatible) {
3202                 free(*compatible);
3203                 compatible++;
3204             }
3205
3206             free(device->deviceinfo.platform->compatible);
3207         }
3208     }
3209 }
3210
3211 static void drmFreeHost1xDevice(drmDevicePtr device)
3212 {
3213     if (device->deviceinfo.host1x) {
3214         if (device->deviceinfo.host1x->compatible) {
3215             char **compatible = device->deviceinfo.host1x->compatible;
3216
3217             while (*compatible) {
3218                 free(*compatible);
3219                 compatible++;
3220             }
3221
3222             free(device->deviceinfo.host1x->compatible);
3223         }
3224     }
3225 }
3226
3227 void drmFreeDevice(drmDevicePtr *device)
3228 {
3229     if (device == NULL)
3230         return;
3231
3232     if (*device) {
3233         switch ((*device)->bustype) {
3234         case DRM_BUS_PLATFORM:
3235             drmFreePlatformDevice(*device);
3236             break;
3237
3238         case DRM_BUS_HOST1X:
3239             drmFreeHost1xDevice(*device);
3240             break;
3241         }
3242     }
3243
3244     free(*device);
3245     *device = NULL;
3246 }
3247
3248 void drmFreeDevices(drmDevicePtr devices[], int count)
3249 {
3250     int i;
3251
3252     if (devices == NULL)
3253         return;
3254
3255     for (i = 0; i < count; i++)
3256         if (devices[i])
3257             drmFreeDevice(&devices[i]);
3258 }
3259
3260 static drmDevicePtr drmDeviceAlloc(unsigned int type, const char *node,
3261                                    size_t bus_size, size_t device_size,
3262                                    char **ptrp)
3263 {
3264     size_t max_node_length, extra, size;
3265     drmDevicePtr device;
3266     unsigned int i;
3267     char *ptr;
3268
3269     max_node_length = ALIGN(drmGetMaxNodeName(), sizeof(void *));
3270     extra = DRM_NODE_MAX * (sizeof(void *) + max_node_length);
3271
3272     size = sizeof(*device) + extra + bus_size + device_size;
3273
3274     device = calloc(1, size);
3275     if (!device)
3276         return NULL;
3277
3278     device->available_nodes = 1 << type;
3279
3280     ptr = (char *)device + sizeof(*device);
3281     device->nodes = (char **)ptr;
3282
3283     ptr += DRM_NODE_MAX * sizeof(void *);
3284
3285     for (i = 0; i < DRM_NODE_MAX; i++) {
3286         device->nodes[i] = ptr;
3287         ptr += max_node_length;
3288     }
3289
3290     memcpy(device->nodes[type], node, max_node_length);
3291
3292     *ptrp = ptr;
3293
3294     return device;
3295 }
3296
3297 static int drmProcessPciDevice(drmDevicePtr *device,
3298                                const char *node, int node_type,
3299                                int maj, int min, bool fetch_deviceinfo,
3300                                uint32_t flags)
3301 {
3302     drmDevicePtr dev;
3303     char *addr;
3304     int ret;
3305
3306     dev = drmDeviceAlloc(node_type, node, sizeof(drmPciBusInfo),
3307                          sizeof(drmPciDeviceInfo), &addr);
3308     if (!dev)
3309         return -ENOMEM;
3310
3311     dev->bustype = DRM_BUS_PCI;
3312
3313     dev->businfo.pci = (drmPciBusInfoPtr)addr;
3314
3315     ret = drmParsePciBusInfo(maj, min, dev->businfo.pci);
3316     if (ret)
3317         goto free_device;
3318
3319     // Fetch the device info if the user has requested it
3320     if (fetch_deviceinfo) {
3321         addr += sizeof(drmPciBusInfo);
3322         dev->deviceinfo.pci = (drmPciDeviceInfoPtr)addr;
3323
3324         ret = drmParsePciDeviceInfo(maj, min, dev->deviceinfo.pci, flags);
3325         if (ret)
3326             goto free_device;
3327     }
3328
3329     *device = dev;
3330
3331     return 0;
3332
3333 free_device:
3334     free(dev);
3335     return ret;
3336 }
3337
3338 static int drmParseUsbBusInfo(int maj, int min, drmUsbBusInfoPtr info)
3339 {
3340 #ifdef __linux__
3341     char path[PATH_MAX + 1], *value;
3342     unsigned int bus, dev;
3343     int ret;
3344
3345     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3346
3347     value = sysfs_uevent_get(path, "BUSNUM");
3348     if (!value)
3349         return -ENOENT;
3350
3351     ret = sscanf(value, "%03u", &bus);
3352     free(value);
3353
3354     if (ret <= 0)
3355         return -errno;
3356
3357     value = sysfs_uevent_get(path, "DEVNUM");
3358     if (!value)
3359         return -ENOENT;
3360
3361     ret = sscanf(value, "%03u", &dev);
3362     free(value);
3363
3364     if (ret <= 0)
3365         return -errno;
3366
3367     info->bus = bus;
3368     info->dev = dev;
3369
3370     return 0;
3371 #else
3372 #warning "Missing implementation of drmParseUsbBusInfo"
3373     return -EINVAL;
3374 #endif
3375 }
3376
3377 static int drmParseUsbDeviceInfo(int maj, int min, drmUsbDeviceInfoPtr info)
3378 {
3379 #ifdef __linux__
3380     char path[PATH_MAX + 1], *value;
3381     unsigned int vendor, product;
3382     int ret;
3383
3384     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3385
3386     value = sysfs_uevent_get(path, "PRODUCT");
3387     if (!value)
3388         return -ENOENT;
3389
3390     ret = sscanf(value, "%x/%x", &vendor, &product);
3391     free(value);
3392
3393     if (ret <= 0)
3394         return -errno;
3395
3396     info->vendor = vendor;
3397     info->product = product;
3398
3399     return 0;
3400 #else
3401 #warning "Missing implementation of drmParseUsbDeviceInfo"
3402     return -EINVAL;
3403 #endif
3404 }
3405
3406 static int drmProcessUsbDevice(drmDevicePtr *device, const char *node,
3407                                int node_type, int maj, int min,
3408                                bool fetch_deviceinfo, uint32_t flags)
3409 {
3410     drmDevicePtr dev;
3411     char *ptr;
3412     int ret;
3413
3414     dev = drmDeviceAlloc(node_type, node, sizeof(drmUsbBusInfo),
3415                          sizeof(drmUsbDeviceInfo), &ptr);
3416     if (!dev)
3417         return -ENOMEM;
3418
3419     dev->bustype = DRM_BUS_USB;
3420
3421     dev->businfo.usb = (drmUsbBusInfoPtr)ptr;
3422
3423     ret = drmParseUsbBusInfo(maj, min, dev->businfo.usb);
3424     if (ret < 0)
3425         goto free_device;
3426
3427     if (fetch_deviceinfo) {
3428         ptr += sizeof(drmUsbBusInfo);
3429         dev->deviceinfo.usb = (drmUsbDeviceInfoPtr)ptr;
3430
3431         ret = drmParseUsbDeviceInfo(maj, min, dev->deviceinfo.usb);
3432         if (ret < 0)
3433             goto free_device;
3434     }
3435
3436     *device = dev;
3437
3438     return 0;
3439
3440 free_device:
3441     free(dev);
3442     return ret;
3443 }
3444
3445 static int drmParsePlatformBusInfo(int maj, int min, drmPlatformBusInfoPtr info)
3446 {
3447 #ifdef __linux__
3448     char path[PATH_MAX + 1], *name;
3449
3450     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3451
3452     name = sysfs_uevent_get(path, "OF_FULLNAME");
3453     if (!name)
3454         return -ENOENT;
3455
3456     strncpy(info->fullname, name, DRM_PLATFORM_DEVICE_NAME_LEN);
3457     info->fullname[DRM_PLATFORM_DEVICE_NAME_LEN - 1] = '\0';
3458     free(name);
3459
3460     return 0;
3461 #else
3462 #warning "Missing implementation of drmParsePlatformBusInfo"
3463     return -EINVAL;
3464 #endif
3465 }
3466
3467 static int drmParsePlatformDeviceInfo(int maj, int min,
3468                                       drmPlatformDeviceInfoPtr info)
3469 {
3470 #ifdef __linux__
3471     char path[PATH_MAX + 1], *value;
3472     unsigned int count, i;
3473     int err;
3474
3475     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3476
3477     value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
3478     if (!value)
3479         return -ENOENT;
3480
3481     sscanf(value, "%u", &count);
3482     free(value);
3483
3484     info->compatible = calloc(count + 1, sizeof(*info->compatible));
3485     if (!info->compatible)
3486         return -ENOMEM;
3487
3488     for (i = 0; i < count; i++) {
3489         value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
3490         if (!value) {
3491             err = -ENOENT;
3492             goto free;
3493         }
3494
3495         info->compatible[i] = value;
3496     }
3497
3498     return 0;
3499
3500 free:
3501     while (i--)
3502         free(info->compatible[i]);
3503
3504     free(info->compatible);
3505     return err;
3506 #else
3507 #warning "Missing implementation of drmParsePlatformDeviceInfo"
3508     return -EINVAL;
3509 #endif
3510 }
3511
3512 static int drmProcessPlatformDevice(drmDevicePtr *device,
3513                                     const char *node, int node_type,
3514                                     int maj, int min, bool fetch_deviceinfo,
3515                                     uint32_t flags)
3516 {
3517     drmDevicePtr dev;
3518     char *ptr;
3519     int ret;
3520
3521     dev = drmDeviceAlloc(node_type, node, sizeof(drmPlatformBusInfo),
3522                          sizeof(drmPlatformDeviceInfo), &ptr);
3523     if (!dev)
3524         return -ENOMEM;
3525
3526     dev->bustype = DRM_BUS_PLATFORM;
3527
3528     dev->businfo.platform = (drmPlatformBusInfoPtr)ptr;
3529
3530     ret = drmParsePlatformBusInfo(maj, min, dev->businfo.platform);
3531     if (ret < 0)
3532         goto free_device;
3533
3534     if (fetch_deviceinfo) {
3535         ptr += sizeof(drmPlatformBusInfo);
3536         dev->deviceinfo.platform = (drmPlatformDeviceInfoPtr)ptr;
3537
3538         ret = drmParsePlatformDeviceInfo(maj, min, dev->deviceinfo.platform);
3539         if (ret < 0)
3540             goto free_device;
3541     }
3542
3543     *device = dev;
3544
3545     return 0;
3546
3547 free_device:
3548     free(dev);
3549     return ret;
3550 }
3551
3552 static int drmParseHost1xBusInfo(int maj, int min, drmHost1xBusInfoPtr info)
3553 {
3554 #ifdef __linux__
3555     char path[PATH_MAX + 1], *name;
3556
3557     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3558
3559     name = sysfs_uevent_get(path, "OF_FULLNAME");
3560     if (!name)
3561         return -ENOENT;
3562
3563     strncpy(info->fullname, name, DRM_HOST1X_DEVICE_NAME_LEN);
3564     info->fullname[DRM_HOST1X_DEVICE_NAME_LEN - 1] = '\0';
3565     free(name);
3566
3567     return 0;
3568 #else
3569 #warning "Missing implementation of drmParseHost1xBusInfo"
3570     return -EINVAL;
3571 #endif
3572 }
3573
3574 static int drmParseHost1xDeviceInfo(int maj, int min,
3575                                     drmHost1xDeviceInfoPtr info)
3576 {
3577 #ifdef __linux__
3578     char path[PATH_MAX + 1], *value;
3579     unsigned int count, i;
3580     int err;
3581
3582     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3583
3584     value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
3585     if (!value)
3586         return -ENOENT;
3587
3588     sscanf(value, "%u", &count);
3589     free(value);
3590
3591     info->compatible = calloc(count + 1, sizeof(*info->compatible));
3592     if (!info->compatible)
3593         return -ENOMEM;
3594
3595     for (i = 0; i < count; i++) {
3596         value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
3597         if (!value) {
3598             err = -ENOENT;
3599             goto free;
3600         }
3601
3602         info->compatible[i] = value;
3603     }
3604
3605     return 0;
3606
3607 free:
3608     while (i--)
3609         free(info->compatible[i]);
3610
3611     free(info->compatible);
3612     return err;
3613 #else
3614 #warning "Missing implementation of drmParseHost1xDeviceInfo"
3615     return -EINVAL;
3616 #endif
3617 }
3618
3619 static int drmProcessHost1xDevice(drmDevicePtr *device,
3620                                   const char *node, int node_type,
3621                                   int maj, int min, bool fetch_deviceinfo,
3622                                   uint32_t flags)
3623 {
3624     drmDevicePtr dev;
3625     char *ptr;
3626     int ret;
3627
3628     dev = drmDeviceAlloc(node_type, node, sizeof(drmHost1xBusInfo),
3629                          sizeof(drmHost1xDeviceInfo), &ptr);
3630     if (!dev)
3631         return -ENOMEM;
3632
3633     dev->bustype = DRM_BUS_HOST1X;
3634
3635     dev->businfo.host1x = (drmHost1xBusInfoPtr)ptr;
3636
3637     ret = drmParseHost1xBusInfo(maj, min, dev->businfo.host1x);
3638     if (ret < 0)
3639         goto free_device;
3640
3641     if (fetch_deviceinfo) {
3642         ptr += sizeof(drmHost1xBusInfo);
3643         dev->deviceinfo.host1x = (drmHost1xDeviceInfoPtr)ptr;
3644
3645         ret = drmParseHost1xDeviceInfo(maj, min, dev->deviceinfo.host1x);
3646         if (ret < 0)
3647             goto free_device;
3648     }
3649
3650     *device = dev;
3651
3652     return 0;
3653
3654 free_device:
3655     free(dev);
3656     return ret;
3657 }
3658
3659 /* Consider devices located on the same bus as duplicate and fold the respective
3660  * entries into a single one.
3661  *
3662  * Note: this leaves "gaps" in the array, while preserving the length.
3663  */
3664 static void drmFoldDuplicatedDevices(drmDevicePtr local_devices[], int count)
3665 {
3666     int node_type, i, j;
3667
3668     for (i = 0; i < count; i++) {
3669         for (j = i + 1; j < count; j++) {
3670             if (drmDevicesEqual(local_devices[i], local_devices[j])) {
3671                 local_devices[i]->available_nodes |= local_devices[j]->available_nodes;
3672                 node_type = log2(local_devices[j]->available_nodes);
3673                 memcpy(local_devices[i]->nodes[node_type],
3674                        local_devices[j]->nodes[node_type], drmGetMaxNodeName());
3675                 drmFreeDevice(&local_devices[j]);
3676             }
3677         }
3678     }
3679 }
3680
3681 /* Check that the given flags are valid returning 0 on success */
3682 static int
3683 drm_device_validate_flags(uint32_t flags)
3684 {
3685         return (flags & ~DRM_DEVICE_GET_PCI_REVISION);
3686 }
3687
3688 /**
3689  * Get information about the opened drm device
3690  *
3691  * \param fd file descriptor of the drm device
3692  * \param flags feature/behaviour bitmask
3693  * \param device the address of a drmDevicePtr where the information
3694  *               will be allocated in stored
3695  *
3696  * \return zero on success, negative error code otherwise.
3697  *
3698  * \note Unlike drmGetDevice it does not retrieve the pci device revision field
3699  * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
3700  */
3701 int drmGetDevice2(int fd, uint32_t flags, drmDevicePtr *device)
3702 {
3703 #ifdef __OpenBSD__
3704     /*
3705      * DRI device nodes on OpenBSD are not in their own directory, they reside
3706      * in /dev along with a large number of statically generated /dev nodes.
3707      * Avoid stat'ing all of /dev needlessly by implementing this custom path.
3708      */
3709     drmDevicePtr     d;
3710     struct stat      sbuf;
3711     char             node[PATH_MAX + 1];
3712     const char      *dev_name;
3713     int              node_type, subsystem_type;
3714     int              maj, min, n, ret, base;
3715
3716     if (fd == -1 || device == NULL)
3717         return -EINVAL;
3718
3719     if (fstat(fd, &sbuf))
3720         return -errno;
3721
3722     maj = major(sbuf.st_rdev);
3723     min = minor(sbuf.st_rdev);
3724
3725     if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3726         return -EINVAL;
3727
3728     node_type = drmGetMinorType(min);
3729     if (node_type == -1)
3730         return -ENODEV;
3731
3732     switch (node_type) {
3733     case DRM_NODE_PRIMARY:
3734         dev_name = DRM_DEV_NAME;
3735         break;
3736     case DRM_NODE_CONTROL:
3737         dev_name = DRM_CONTROL_DEV_NAME;
3738         break;
3739     case DRM_NODE_RENDER:
3740         dev_name = DRM_RENDER_DEV_NAME;
3741         break;
3742     default:
3743         return -EINVAL;
3744     };
3745
3746     base = drmGetMinorBase(node_type);
3747     if (base < 0)
3748         return -EINVAL;
3749
3750     n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min - base);
3751     if (n == -1 || n >= PATH_MAX)
3752       return -errno;
3753     if (stat(node, &sbuf))
3754         return -EINVAL;
3755
3756     subsystem_type = drmParseSubsystemType(maj, min);
3757     if (subsystem_type != DRM_BUS_PCI)
3758         return -ENODEV;
3759
3760     ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
3761     if (ret)
3762         return ret;
3763
3764     *device = d;
3765
3766     return 0;
3767 #else
3768     drmDevicePtr *local_devices;
3769     drmDevicePtr d;
3770     DIR *sysdir;
3771     struct dirent *dent;
3772     struct stat sbuf;
3773     char node[PATH_MAX + 1];
3774     int node_type, subsystem_type;
3775     int maj, min;
3776     int ret, i, node_count;
3777     int max_count = 16;
3778     dev_t find_rdev;
3779
3780     if (drm_device_validate_flags(flags))
3781         return -EINVAL;
3782
3783     if (fd == -1 || device == NULL)
3784         return -EINVAL;
3785
3786     if (fstat(fd, &sbuf))
3787         return -errno;
3788
3789     find_rdev = sbuf.st_rdev;
3790     maj = major(sbuf.st_rdev);
3791     min = minor(sbuf.st_rdev);
3792
3793     if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3794         return -EINVAL;
3795
3796     subsystem_type = drmParseSubsystemType(maj, min);
3797
3798     local_devices = calloc(max_count, sizeof(drmDevicePtr));
3799     if (local_devices == NULL)
3800         return -ENOMEM;
3801
3802     sysdir = opendir(DRM_DIR_NAME);
3803     if (!sysdir) {
3804         ret = -errno;
3805         goto free_locals;
3806     }
3807
3808     i = 0;
3809     while ((dent = readdir(sysdir))) {
3810         node_type = drmGetNodeType(dent->d_name);
3811         if (node_type < 0)
3812             continue;
3813
3814         snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, dent->d_name);
3815         if (stat(node, &sbuf))
3816             continue;
3817
3818         maj = major(sbuf.st_rdev);
3819         min = minor(sbuf.st_rdev);
3820
3821         if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3822             continue;
3823
3824         if (drmParseSubsystemType(maj, min) != subsystem_type)
3825             continue;
3826
3827         switch (subsystem_type) {
3828         case DRM_BUS_PCI:
3829             ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
3830             if (ret)
3831                 continue;
3832
3833             break;
3834
3835         case DRM_BUS_USB:
3836             ret = drmProcessUsbDevice(&d, node, node_type, maj, min, true, flags);
3837             if (ret)
3838                 continue;
3839
3840             break;
3841
3842         case DRM_BUS_PLATFORM:
3843             ret = drmProcessPlatformDevice(&d, node, node_type, maj, min, true, flags);
3844             if (ret)
3845                 continue;
3846
3847             break;
3848
3849         case DRM_BUS_HOST1X:
3850             ret = drmProcessHost1xDevice(&d, node, node_type, maj, min, true, flags);
3851             if (ret)
3852                 continue;
3853
3854             break;
3855
3856         default:
3857             continue;
3858         }
3859
3860         if (i >= max_count) {
3861             drmDevicePtr *temp;
3862
3863             max_count += 16;
3864             temp = realloc(local_devices, max_count * sizeof(drmDevicePtr));
3865             if (!temp)
3866                 goto free_devices;
3867             local_devices = temp;
3868         }
3869
3870         /* store target at local_devices[0] for ease to use below */
3871         if (find_rdev == sbuf.st_rdev && i) {
3872             local_devices[i] = local_devices[0];
3873             local_devices[0] = d;
3874         }
3875         else
3876             local_devices[i] = d;
3877         i++;
3878     }
3879     node_count = i;
3880
3881     drmFoldDuplicatedDevices(local_devices, node_count);
3882
3883     *device = local_devices[0];
3884     drmFreeDevices(&local_devices[1], node_count - 1);
3885
3886     closedir(sysdir);
3887     free(local_devices);
3888     if (*device == NULL)
3889         return -ENODEV;
3890     return 0;
3891
3892 free_devices:
3893     drmFreeDevices(local_devices, i);
3894     closedir(sysdir);
3895
3896 free_locals:
3897     free(local_devices);
3898     return ret;
3899 #endif
3900 }
3901
3902 /**
3903  * Get information about the opened drm device
3904  *
3905  * \param fd file descriptor of the drm device
3906  * \param device the address of a drmDevicePtr where the information
3907  *               will be allocated in stored
3908  *
3909  * \return zero on success, negative error code otherwise.
3910  */
3911 int drmGetDevice(int fd, drmDevicePtr *device)
3912 {
3913     return drmGetDevice2(fd, DRM_DEVICE_GET_PCI_REVISION, device);
3914 }
3915
3916 /**
3917  * Get drm devices on the system
3918  *
3919  * \param flags feature/behaviour bitmask
3920  * \param devices the array of devices with drmDevicePtr elements
3921  *                can be NULL to get the device number first
3922  * \param max_devices the maximum number of devices for the array
3923  *
3924  * \return on error - negative error code,
3925  *         if devices is NULL - total number of devices available on the system,
3926  *         alternatively the number of devices stored in devices[], which is
3927  *         capped by the max_devices.
3928  *
3929  * \note Unlike drmGetDevices it does not retrieve the pci device revision field
3930  * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
3931  */
3932 int drmGetDevices2(uint32_t flags, drmDevicePtr devices[], int max_devices)
3933 {
3934     drmDevicePtr *local_devices;
3935     drmDevicePtr device;
3936     DIR *sysdir;
3937     struct dirent *dent;
3938     struct stat sbuf;
3939     char node[PATH_MAX + 1];
3940     int node_type, subsystem_type;
3941     int maj, min;
3942     int ret, i, node_count, device_count;
3943     int max_count = 16;
3944
3945     if (drm_device_validate_flags(flags))
3946         return -EINVAL;
3947
3948     local_devices = calloc(max_count, sizeof(drmDevicePtr));
3949     if (local_devices == NULL)
3950         return -ENOMEM;
3951
3952     sysdir = opendir(DRM_DIR_NAME);
3953     if (!sysdir) {
3954         ret = -errno;
3955         goto free_locals;
3956     }
3957
3958     i = 0;
3959     while ((dent = readdir(sysdir))) {
3960         node_type = drmGetNodeType(dent->d_name);
3961         if (node_type < 0)
3962             continue;
3963
3964         snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, dent->d_name);
3965         if (stat(node, &sbuf))
3966             continue;
3967
3968         maj = major(sbuf.st_rdev);
3969         min = minor(sbuf.st_rdev);
3970
3971         if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3972             continue;
3973
3974         subsystem_type = drmParseSubsystemType(maj, min);
3975
3976         if (subsystem_type < 0)
3977             continue;
3978
3979         switch (subsystem_type) {
3980         case DRM_BUS_PCI:
3981             ret = drmProcessPciDevice(&device, node, node_type,
3982                                       maj, min, devices != NULL, flags);
3983             if (ret)
3984                 continue;
3985
3986             break;
3987
3988         case DRM_BUS_USB:
3989             ret = drmProcessUsbDevice(&device, node, node_type, maj, min,
3990                                       devices != NULL, flags);
3991             if (ret)
3992                 continue;
3993
3994             break;
3995
3996         case DRM_BUS_PLATFORM:
3997             ret = drmProcessPlatformDevice(&device, node, node_type, maj, min,
3998                                            devices != NULL, flags);
3999             if (ret)
4000                 continue;
4001
4002             break;
4003
4004         case DRM_BUS_HOST1X:
4005             ret = drmProcessHost1xDevice(&device, node, node_type, maj, min,
4006                                          devices != NULL, flags);
4007             if (ret)
4008                 continue;
4009
4010             break;
4011
4012         default:
4013             continue;
4014         }
4015
4016         if (i >= max_count) {
4017             drmDevicePtr *temp;
4018
4019             max_count += 16;
4020             temp = realloc(local_devices, max_count * sizeof(drmDevicePtr));
4021             if (!temp)
4022                 goto free_devices;
4023             local_devices = temp;
4024         }
4025
4026         local_devices[i] = device;
4027         i++;
4028     }
4029     node_count = i;
4030
4031     drmFoldDuplicatedDevices(local_devices, node_count);
4032
4033     device_count = 0;
4034     for (i = 0; i < node_count; i++) {
4035         if (!local_devices[i])
4036             continue;
4037
4038         if ((devices != NULL) && (device_count < max_devices))
4039             devices[device_count] = local_devices[i];
4040         else
4041             drmFreeDevice(&local_devices[i]);
4042
4043         device_count++;
4044     }
4045
4046     closedir(sysdir);
4047     free(local_devices);
4048     return device_count;
4049
4050 free_devices:
4051     drmFreeDevices(local_devices, i);
4052     closedir(sysdir);
4053
4054 free_locals:
4055     free(local_devices);
4056     return ret;
4057 }
4058
4059 /**
4060  * Get drm devices on the system
4061  *
4062  * \param devices the array of devices with drmDevicePtr elements
4063  *                can be NULL to get the device number first
4064  * \param max_devices the maximum number of devices for the array
4065  *
4066  * \return on error - negative error code,
4067  *         if devices is NULL - total number of devices available on the system,
4068  *         alternatively the number of devices stored in devices[], which is
4069  *         capped by the max_devices.
4070  */
4071 int drmGetDevices(drmDevicePtr devices[], int max_devices)
4072 {
4073     return drmGetDevices2(DRM_DEVICE_GET_PCI_REVISION, devices, max_devices);
4074 }
4075
4076 char *drmGetDeviceNameFromFd2(int fd)
4077 {
4078 #ifdef __linux__
4079     struct stat sbuf;
4080     char path[PATH_MAX + 1], *value;
4081     unsigned int maj, min;
4082
4083     if (fstat(fd, &sbuf))
4084         return NULL;
4085
4086     maj = major(sbuf.st_rdev);
4087     min = minor(sbuf.st_rdev);
4088
4089     if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
4090         return NULL;
4091
4092     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d", maj, min);
4093
4094     value = sysfs_uevent_get(path, "DEVNAME");
4095     if (!value)
4096         return NULL;
4097
4098     snprintf(path, sizeof(path), "/dev/%s", value);
4099     free(value);
4100
4101     return strdup(path);
4102 #else
4103     struct stat      sbuf;
4104     char             node[PATH_MAX + 1];
4105     const char      *dev_name;
4106     int              node_type;
4107     int              maj, min, n, base;
4108
4109     if (fstat(fd, &sbuf))
4110         return NULL;
4111
4112     maj = major(sbuf.st_rdev);
4113     min = minor(sbuf.st_rdev);
4114
4115     if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
4116         return NULL;
4117
4118     node_type = drmGetMinorType(min);
4119     if (node_type == -1)
4120         return NULL;
4121
4122     switch (node_type) {
4123     case DRM_NODE_PRIMARY:
4124         dev_name = DRM_DEV_NAME;
4125         break;
4126     case DRM_NODE_CONTROL:
4127         dev_name = DRM_CONTROL_DEV_NAME;
4128         break;
4129     case DRM_NODE_RENDER:
4130         dev_name = DRM_RENDER_DEV_NAME;
4131         break;
4132     default:
4133         return NULL;
4134     };
4135
4136     base = drmGetMinorBase(node_type);
4137     if (base < 0)
4138         return NULL;
4139
4140     n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min - base);
4141     if (n == -1 || n >= PATH_MAX)
4142       return NULL;
4143
4144     return strdup(node);
4145 #endif
4146 }
4147
4148 int drmSyncobjCreate(int fd, uint32_t flags, uint32_t *handle)
4149 {
4150     struct drm_syncobj_create args;
4151     int ret;
4152
4153     memclear(args);
4154     args.flags = flags;
4155     args.handle = 0;
4156     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_CREATE, &args);
4157     if (ret)
4158         return ret;
4159     *handle = args.handle;
4160     return 0;
4161 }
4162
4163 int drmSyncobjDestroy(int fd, uint32_t handle)
4164 {
4165     struct drm_syncobj_destroy args;
4166
4167     memclear(args);
4168     args.handle = handle;
4169     return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_DESTROY, &args);
4170 }
4171
4172 int drmSyncobjHandleToFD(int fd, uint32_t handle, int *obj_fd)
4173 {
4174     struct drm_syncobj_handle args;
4175     int ret;
4176
4177     memclear(args);
4178     args.fd = -1;
4179     args.handle = handle;
4180     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4181     if (ret)
4182         return ret;
4183     *obj_fd = args.fd;
4184     return 0;
4185 }
4186
4187 int drmSyncobjFDToHandle(int fd, int obj_fd, uint32_t *handle)
4188 {
4189     struct drm_syncobj_handle args;
4190     int ret;
4191
4192     memclear(args);
4193     args.fd = obj_fd;
4194     args.handle = 0;
4195     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4196     if (ret)
4197         return ret;
4198     *handle = args.handle;
4199     return 0;
4200 }
4201
4202 int drmSyncobjImportSyncFile(int fd, uint32_t handle, int sync_file_fd)
4203 {
4204     struct drm_syncobj_handle args;
4205
4206     memclear(args);
4207     args.fd = sync_file_fd;
4208     args.handle = handle;
4209     args.flags = DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE;
4210     return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4211 }
4212
4213 int drmSyncobjExportSyncFile(int fd, uint32_t handle, int *sync_file_fd)
4214 {
4215     struct drm_syncobj_handle args;
4216     int ret;
4217
4218     memclear(args);
4219     args.fd = -1;
4220     args.handle = handle;
4221     args.flags = DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE;
4222     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4223     if (ret)
4224         return ret;
4225     *sync_file_fd = args.fd;
4226     return 0;
4227 }