OSDN Git Service

74b4e230a7cb137df621c65f49ee48a864d69036
[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 int drmCrtcGetSequence(int fd, uint32_t crtcId, uint64_t *sequence, uint64_t *ns)
1699 {
1700     struct drm_crtc_get_sequence get_seq;
1701     int ret;
1702
1703     memclear(get_seq);
1704     get_seq.crtc_id = crtcId;
1705     ret = drmIoctl(fd, DRM_IOCTL_CRTC_GET_SEQUENCE, &get_seq);
1706     if (ret)
1707         return ret;
1708
1709     if (sequence)
1710         *sequence = get_seq.sequence;
1711     if (ns)
1712         *ns = get_seq.sequence_ns;
1713     return 0;
1714 }
1715
1716 int drmCrtcQueueSequence(int fd, uint32_t crtcId, uint32_t flags, uint64_t sequence,
1717                          uint64_t *sequence_queued, uint64_t user_data)
1718 {
1719     struct drm_crtc_queue_sequence queue_seq;
1720     int ret;
1721
1722     memclear(queue_seq);
1723     queue_seq.crtc_id = crtcId;
1724     queue_seq.flags = flags;
1725     queue_seq.sequence = sequence;
1726     queue_seq.user_data = user_data;
1727
1728     ret = drmIoctl(fd, DRM_IOCTL_CRTC_QUEUE_SEQUENCE, &queue_seq);
1729     if (ret == 0 && sequence_queued)
1730         *sequence_queued = queue_seq.sequence;
1731
1732     return ret;
1733 }
1734
1735 /**
1736  * Acquire the AGP device.
1737  *
1738  * Must be called before any of the other AGP related calls.
1739  *
1740  * \param fd file descriptor.
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_ACQUIRE ioctl.
1746  */
1747 int drmAgpAcquire(int fd)
1748 {
1749     if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
1750         return -errno;
1751     return 0;
1752 }
1753
1754
1755 /**
1756  * Release the AGP device.
1757  *
1758  * \param fd file descriptor.
1759  *
1760  * \return zero on success, or a negative value on failure.
1761  *
1762  * \internal
1763  * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
1764  */
1765 int drmAgpRelease(int fd)
1766 {
1767     if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
1768         return -errno;
1769     return 0;
1770 }
1771
1772
1773 /**
1774  * Set the AGP mode.
1775  *
1776  * \param fd file descriptor.
1777  * \param mode AGP mode.
1778  *
1779  * \return zero on success, or a negative value on failure.
1780  *
1781  * \internal
1782  * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
1783  * argument in a drm_agp_mode structure.
1784  */
1785 int drmAgpEnable(int fd, unsigned long mode)
1786 {
1787     drm_agp_mode_t m;
1788
1789     memclear(m);
1790     m.mode = mode;
1791     if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
1792         return -errno;
1793     return 0;
1794 }
1795
1796
1797 /**
1798  * Allocate a chunk of AGP memory.
1799  *
1800  * \param fd file descriptor.
1801  * \param size requested memory size in bytes. Will be rounded to page boundary.
1802  * \param type type of memory to allocate.
1803  * \param address if not zero, will be set to the physical address of the
1804  * allocated memory.
1805  * \param handle on success will be set to a handle of the allocated memory.
1806  *
1807  * \return zero on success, or a negative value on failure.
1808  *
1809  * \internal
1810  * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
1811  * arguments in a drm_agp_buffer structure.
1812  */
1813 int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
1814                 unsigned long *address, drm_handle_t *handle)
1815 {
1816     drm_agp_buffer_t b;
1817
1818     memclear(b);
1819     *handle = DRM_AGP_NO_HANDLE;
1820     b.size   = size;
1821     b.type   = type;
1822     if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
1823         return -errno;
1824     if (address != 0UL)
1825         *address = b.physical;
1826     *handle = b.handle;
1827     return 0;
1828 }
1829
1830
1831 /**
1832  * Free a chunk of AGP memory.
1833  *
1834  * \param fd file descriptor.
1835  * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1836  *
1837  * \return zero on success, or a negative value on failure.
1838  *
1839  * \internal
1840  * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
1841  * argument in a drm_agp_buffer structure.
1842  */
1843 int drmAgpFree(int fd, drm_handle_t handle)
1844 {
1845     drm_agp_buffer_t b;
1846
1847     memclear(b);
1848     b.handle = handle;
1849     if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
1850         return -errno;
1851     return 0;
1852 }
1853
1854
1855 /**
1856  * Bind a chunk of AGP memory.
1857  *
1858  * \param fd file descriptor.
1859  * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1860  * \param offset offset in bytes. It will round to page boundary.
1861  *
1862  * \return zero on success, or a negative value on failure.
1863  *
1864  * \internal
1865  * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
1866  * argument in a drm_agp_binding structure.
1867  */
1868 int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
1869 {
1870     drm_agp_binding_t b;
1871
1872     memclear(b);
1873     b.handle = handle;
1874     b.offset = offset;
1875     if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
1876         return -errno;
1877     return 0;
1878 }
1879
1880
1881 /**
1882  * Unbind a chunk of AGP memory.
1883  *
1884  * \param fd file descriptor.
1885  * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1886  *
1887  * \return zero on success, or a negative value on failure.
1888  *
1889  * \internal
1890  * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
1891  * the argument in a drm_agp_binding structure.
1892  */
1893 int drmAgpUnbind(int fd, drm_handle_t handle)
1894 {
1895     drm_agp_binding_t b;
1896
1897     memclear(b);
1898     b.handle = handle;
1899     if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
1900         return -errno;
1901     return 0;
1902 }
1903
1904
1905 /**
1906  * Get AGP driver major version number.
1907  *
1908  * \param fd file descriptor.
1909  *
1910  * \return major version number on success, or a negative value on failure..
1911  *
1912  * \internal
1913  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1914  * necessary information in a drm_agp_info structure.
1915  */
1916 int drmAgpVersionMajor(int fd)
1917 {
1918     drm_agp_info_t i;
1919
1920     memclear(i);
1921
1922     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1923         return -errno;
1924     return i.agp_version_major;
1925 }
1926
1927
1928 /**
1929  * Get AGP driver minor version number.
1930  *
1931  * \param fd file descriptor.
1932  *
1933  * \return minor version number on success, or a negative value on failure.
1934  *
1935  * \internal
1936  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1937  * necessary information in a drm_agp_info structure.
1938  */
1939 int drmAgpVersionMinor(int fd)
1940 {
1941     drm_agp_info_t i;
1942
1943     memclear(i);
1944
1945     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1946         return -errno;
1947     return i.agp_version_minor;
1948 }
1949
1950
1951 /**
1952  * Get AGP mode.
1953  *
1954  * \param fd file descriptor.
1955  *
1956  * \return mode on success, or zero on failure.
1957  *
1958  * \internal
1959  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1960  * necessary information in a drm_agp_info structure.
1961  */
1962 unsigned long drmAgpGetMode(int fd)
1963 {
1964     drm_agp_info_t i;
1965
1966     memclear(i);
1967
1968     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1969         return 0;
1970     return i.mode;
1971 }
1972
1973
1974 /**
1975  * Get AGP aperture base.
1976  *
1977  * \param fd file descriptor.
1978  *
1979  * \return aperture base on success, zero on failure.
1980  *
1981  * \internal
1982  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1983  * necessary information in a drm_agp_info structure.
1984  */
1985 unsigned long drmAgpBase(int fd)
1986 {
1987     drm_agp_info_t i;
1988
1989     memclear(i);
1990
1991     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1992         return 0;
1993     return i.aperture_base;
1994 }
1995
1996
1997 /**
1998  * Get AGP aperture size.
1999  *
2000  * \param fd file descriptor.
2001  *
2002  * \return aperture size on success, zero on failure.
2003  *
2004  * \internal
2005  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2006  * necessary information in a drm_agp_info structure.
2007  */
2008 unsigned long drmAgpSize(int fd)
2009 {
2010     drm_agp_info_t i;
2011
2012     memclear(i);
2013
2014     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2015         return 0;
2016     return i.aperture_size;
2017 }
2018
2019
2020 /**
2021  * Get used AGP memory.
2022  *
2023  * \param fd file descriptor.
2024  *
2025  * \return memory used on success, or zero on failure.
2026  *
2027  * \internal
2028  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2029  * necessary information in a drm_agp_info structure.
2030  */
2031 unsigned long drmAgpMemoryUsed(int fd)
2032 {
2033     drm_agp_info_t i;
2034
2035     memclear(i);
2036
2037     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2038         return 0;
2039     return i.memory_used;
2040 }
2041
2042
2043 /**
2044  * Get available AGP memory.
2045  *
2046  * \param fd file descriptor.
2047  *
2048  * \return memory available on success, or zero on failure.
2049  *
2050  * \internal
2051  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2052  * necessary information in a drm_agp_info structure.
2053  */
2054 unsigned long drmAgpMemoryAvail(int fd)
2055 {
2056     drm_agp_info_t i;
2057
2058     memclear(i);
2059
2060     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2061         return 0;
2062     return i.memory_allowed;
2063 }
2064
2065
2066 /**
2067  * Get hardware vendor ID.
2068  *
2069  * \param fd file descriptor.
2070  *
2071  * \return vendor ID on success, or zero on failure.
2072  *
2073  * \internal
2074  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2075  * necessary information in a drm_agp_info structure.
2076  */
2077 unsigned int drmAgpVendorId(int fd)
2078 {
2079     drm_agp_info_t i;
2080
2081     memclear(i);
2082
2083     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2084         return 0;
2085     return i.id_vendor;
2086 }
2087
2088
2089 /**
2090  * Get hardware device ID.
2091  *
2092  * \param fd file descriptor.
2093  *
2094  * \return zero on success, or zero on failure.
2095  *
2096  * \internal
2097  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2098  * necessary information in a drm_agp_info structure.
2099  */
2100 unsigned int drmAgpDeviceId(int fd)
2101 {
2102     drm_agp_info_t i;
2103
2104     memclear(i);
2105
2106     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2107         return 0;
2108     return i.id_device;
2109 }
2110
2111 int drmScatterGatherAlloc(int fd, unsigned long size, drm_handle_t *handle)
2112 {
2113     drm_scatter_gather_t sg;
2114
2115     memclear(sg);
2116
2117     *handle = 0;
2118     sg.size   = size;
2119     if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
2120         return -errno;
2121     *handle = sg.handle;
2122     return 0;
2123 }
2124
2125 int drmScatterGatherFree(int fd, drm_handle_t handle)
2126 {
2127     drm_scatter_gather_t sg;
2128
2129     memclear(sg);
2130     sg.handle = handle;
2131     if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
2132         return -errno;
2133     return 0;
2134 }
2135
2136 /**
2137  * Wait for VBLANK.
2138  *
2139  * \param fd file descriptor.
2140  * \param vbl pointer to a drmVBlank structure.
2141  *
2142  * \return zero on success, or a negative value on failure.
2143  *
2144  * \internal
2145  * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
2146  */
2147 int drmWaitVBlank(int fd, drmVBlankPtr vbl)
2148 {
2149     struct timespec timeout, cur;
2150     int ret;
2151
2152     ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2153     if (ret < 0) {
2154         fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
2155         goto out;
2156     }
2157     timeout.tv_sec++;
2158
2159     do {
2160        ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
2161        vbl->request.type &= ~DRM_VBLANK_RELATIVE;
2162        if (ret && errno == EINTR) {
2163            clock_gettime(CLOCK_MONOTONIC, &cur);
2164            /* Timeout after 1s */
2165            if (cur.tv_sec > timeout.tv_sec + 1 ||
2166                (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
2167                 timeout.tv_nsec)) {
2168                    errno = EBUSY;
2169                    ret = -1;
2170                    break;
2171            }
2172        }
2173     } while (ret && errno == EINTR);
2174
2175 out:
2176     return ret;
2177 }
2178
2179 int drmError(int err, const char *label)
2180 {
2181     switch (err) {
2182     case DRM_ERR_NO_DEVICE:
2183         fprintf(stderr, "%s: no device\n", label);
2184         break;
2185     case DRM_ERR_NO_ACCESS:
2186         fprintf(stderr, "%s: no access\n", label);
2187         break;
2188     case DRM_ERR_NOT_ROOT:
2189         fprintf(stderr, "%s: not root\n", label);
2190         break;
2191     case DRM_ERR_INVALID:
2192         fprintf(stderr, "%s: invalid args\n", label);
2193         break;
2194     default:
2195         if (err < 0)
2196             err = -err;
2197         fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2198         break;
2199     }
2200
2201     return 1;
2202 }
2203
2204 /**
2205  * Install IRQ handler.
2206  *
2207  * \param fd file descriptor.
2208  * \param irq IRQ number.
2209  *
2210  * \return zero on success, or a negative value on failure.
2211  *
2212  * \internal
2213  * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2214  * argument in a drm_control structure.
2215  */
2216 int drmCtlInstHandler(int fd, int irq)
2217 {
2218     drm_control_t ctl;
2219
2220     memclear(ctl);
2221     ctl.func  = DRM_INST_HANDLER;
2222     ctl.irq   = irq;
2223     if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2224         return -errno;
2225     return 0;
2226 }
2227
2228
2229 /**
2230  * Uninstall IRQ handler.
2231  *
2232  * \param fd file descriptor.
2233  *
2234  * \return zero on success, or a negative value on failure.
2235  *
2236  * \internal
2237  * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2238  * argument in a drm_control structure.
2239  */
2240 int drmCtlUninstHandler(int fd)
2241 {
2242     drm_control_t ctl;
2243
2244     memclear(ctl);
2245     ctl.func  = DRM_UNINST_HANDLER;
2246     ctl.irq   = 0;
2247     if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2248         return -errno;
2249     return 0;
2250 }
2251
2252 int drmFinish(int fd, int context, drmLockFlags flags)
2253 {
2254     drm_lock_t lock;
2255
2256     memclear(lock);
2257     lock.context = context;
2258     if (flags & DRM_LOCK_READY)      lock.flags |= _DRM_LOCK_READY;
2259     if (flags & DRM_LOCK_QUIESCENT)  lock.flags |= _DRM_LOCK_QUIESCENT;
2260     if (flags & DRM_LOCK_FLUSH)      lock.flags |= _DRM_LOCK_FLUSH;
2261     if (flags & DRM_LOCK_FLUSH_ALL)  lock.flags |= _DRM_LOCK_FLUSH_ALL;
2262     if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2263     if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2264     if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2265         return -errno;
2266     return 0;
2267 }
2268
2269 /**
2270  * Get IRQ from bus ID.
2271  *
2272  * \param fd file descriptor.
2273  * \param busnum bus number.
2274  * \param devnum device number.
2275  * \param funcnum function number.
2276  *
2277  * \return IRQ number on success, or a negative value on failure.
2278  *
2279  * \internal
2280  * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2281  * arguments in a drm_irq_busid structure.
2282  */
2283 int drmGetInterruptFromBusID(int fd, int busnum, int devnum, int funcnum)
2284 {
2285     drm_irq_busid_t p;
2286
2287     memclear(p);
2288     p.busnum  = busnum;
2289     p.devnum  = devnum;
2290     p.funcnum = funcnum;
2291     if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2292         return -errno;
2293     return p.irq;
2294 }
2295
2296 int drmAddContextTag(int fd, drm_context_t context, void *tag)
2297 {
2298     drmHashEntry  *entry = drmGetEntry(fd);
2299
2300     if (drmHashInsert(entry->tagTable, context, tag)) {
2301         drmHashDelete(entry->tagTable, context);
2302         drmHashInsert(entry->tagTable, context, tag);
2303     }
2304     return 0;
2305 }
2306
2307 int drmDelContextTag(int fd, drm_context_t context)
2308 {
2309     drmHashEntry  *entry = drmGetEntry(fd);
2310
2311     return drmHashDelete(entry->tagTable, context);
2312 }
2313
2314 void *drmGetContextTag(int fd, drm_context_t context)
2315 {
2316     drmHashEntry  *entry = drmGetEntry(fd);
2317     void          *value;
2318
2319     if (drmHashLookup(entry->tagTable, context, &value))
2320         return NULL;
2321
2322     return value;
2323 }
2324
2325 int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2326                                 drm_handle_t handle)
2327 {
2328     drm_ctx_priv_map_t map;
2329
2330     memclear(map);
2331     map.ctx_id = ctx_id;
2332     map.handle = (void *)(uintptr_t)handle;
2333
2334     if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2335         return -errno;
2336     return 0;
2337 }
2338
2339 int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2340                                 drm_handle_t *handle)
2341 {
2342     drm_ctx_priv_map_t map;
2343
2344     memclear(map);
2345     map.ctx_id = ctx_id;
2346
2347     if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2348         return -errno;
2349     if (handle)
2350         *handle = (drm_handle_t)(uintptr_t)map.handle;
2351
2352     return 0;
2353 }
2354
2355 int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2356               drmMapType *type, drmMapFlags *flags, drm_handle_t *handle,
2357               int *mtrr)
2358 {
2359     drm_map_t map;
2360
2361     memclear(map);
2362     map.offset = idx;
2363     if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2364         return -errno;
2365     *offset = map.offset;
2366     *size   = map.size;
2367     *type   = map.type;
2368     *flags  = map.flags;
2369     *handle = (unsigned long)map.handle;
2370     *mtrr   = map.mtrr;
2371     return 0;
2372 }
2373
2374 int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2375                  unsigned long *magic, unsigned long *iocs)
2376 {
2377     drm_client_t client;
2378
2379     memclear(client);
2380     client.idx = idx;
2381     if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2382         return -errno;
2383     *auth      = client.auth;
2384     *pid       = client.pid;
2385     *uid       = client.uid;
2386     *magic     = client.magic;
2387     *iocs      = client.iocs;
2388     return 0;
2389 }
2390
2391 int drmGetStats(int fd, drmStatsT *stats)
2392 {
2393     drm_stats_t s;
2394     unsigned    i;
2395
2396     memclear(s);
2397     if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2398         return -errno;
2399
2400     stats->count = 0;
2401     memset(stats, 0, sizeof(*stats));
2402     if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2403         return -1;
2404
2405 #define SET_VALUE                              \
2406     stats->data[i].long_format = "%-20.20s";   \
2407     stats->data[i].rate_format = "%8.8s";      \
2408     stats->data[i].isvalue     = 1;            \
2409     stats->data[i].verbose     = 0
2410
2411 #define SET_COUNT                              \
2412     stats->data[i].long_format = "%-20.20s";   \
2413     stats->data[i].rate_format = "%5.5s";      \
2414     stats->data[i].isvalue     = 0;            \
2415     stats->data[i].mult_names  = "kgm";        \
2416     stats->data[i].mult        = 1000;         \
2417     stats->data[i].verbose     = 0
2418
2419 #define SET_BYTE                               \
2420     stats->data[i].long_format = "%-20.20s";   \
2421     stats->data[i].rate_format = "%5.5s";      \
2422     stats->data[i].isvalue     = 0;            \
2423     stats->data[i].mult_names  = "KGM";        \
2424     stats->data[i].mult        = 1024;         \
2425     stats->data[i].verbose     = 0
2426
2427
2428     stats->count = s.count;
2429     for (i = 0; i < s.count; i++) {
2430         stats->data[i].value = s.data[i].value;
2431         switch (s.data[i].type) {
2432         case _DRM_STAT_LOCK:
2433             stats->data[i].long_name = "Lock";
2434             stats->data[i].rate_name = "Lock";
2435             SET_VALUE;
2436             break;
2437         case _DRM_STAT_OPENS:
2438             stats->data[i].long_name = "Opens";
2439             stats->data[i].rate_name = "O";
2440             SET_COUNT;
2441             stats->data[i].verbose   = 1;
2442             break;
2443         case _DRM_STAT_CLOSES:
2444             stats->data[i].long_name = "Closes";
2445             stats->data[i].rate_name = "Lock";
2446             SET_COUNT;
2447             stats->data[i].verbose   = 1;
2448             break;
2449         case _DRM_STAT_IOCTLS:
2450             stats->data[i].long_name = "Ioctls";
2451             stats->data[i].rate_name = "Ioc/s";
2452             SET_COUNT;
2453             break;
2454         case _DRM_STAT_LOCKS:
2455             stats->data[i].long_name = "Locks";
2456             stats->data[i].rate_name = "Lck/s";
2457             SET_COUNT;
2458             break;
2459         case _DRM_STAT_UNLOCKS:
2460             stats->data[i].long_name = "Unlocks";
2461             stats->data[i].rate_name = "Unl/s";
2462             SET_COUNT;
2463             break;
2464         case _DRM_STAT_IRQ:
2465             stats->data[i].long_name = "IRQs";
2466             stats->data[i].rate_name = "IRQ/s";
2467             SET_COUNT;
2468             break;
2469         case _DRM_STAT_PRIMARY:
2470             stats->data[i].long_name = "Primary Bytes";
2471             stats->data[i].rate_name = "PB/s";
2472             SET_BYTE;
2473             break;
2474         case _DRM_STAT_SECONDARY:
2475             stats->data[i].long_name = "Secondary Bytes";
2476             stats->data[i].rate_name = "SB/s";
2477             SET_BYTE;
2478             break;
2479         case _DRM_STAT_DMA:
2480             stats->data[i].long_name = "DMA";
2481             stats->data[i].rate_name = "DMA/s";
2482             SET_COUNT;
2483             break;
2484         case _DRM_STAT_SPECIAL:
2485             stats->data[i].long_name = "Special DMA";
2486             stats->data[i].rate_name = "dma/s";
2487             SET_COUNT;
2488             break;
2489         case _DRM_STAT_MISSED:
2490             stats->data[i].long_name = "Miss";
2491             stats->data[i].rate_name = "Ms/s";
2492             SET_COUNT;
2493             break;
2494         case _DRM_STAT_VALUE:
2495             stats->data[i].long_name = "Value";
2496             stats->data[i].rate_name = "Value";
2497             SET_VALUE;
2498             break;
2499         case _DRM_STAT_BYTE:
2500             stats->data[i].long_name = "Bytes";
2501             stats->data[i].rate_name = "B/s";
2502             SET_BYTE;
2503             break;
2504         case _DRM_STAT_COUNT:
2505         default:
2506             stats->data[i].long_name = "Count";
2507             stats->data[i].rate_name = "Cnt/s";
2508             SET_COUNT;
2509             break;
2510         }
2511     }
2512     return 0;
2513 }
2514
2515 /**
2516  * Issue a set-version ioctl.
2517  *
2518  * \param fd file descriptor.
2519  * \param drmCommandIndex command index
2520  * \param data source pointer of the data to be read and written.
2521  * \param size size of the data to be read and written.
2522  *
2523  * \return zero on success, or a negative value on failure.
2524  *
2525  * \internal
2526  * It issues a read-write ioctl given by
2527  * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2528  */
2529 int drmSetInterfaceVersion(int fd, drmSetVersion *version)
2530 {
2531     int retcode = 0;
2532     drm_set_version_t sv;
2533
2534     memclear(sv);
2535     sv.drm_di_major = version->drm_di_major;
2536     sv.drm_di_minor = version->drm_di_minor;
2537     sv.drm_dd_major = version->drm_dd_major;
2538     sv.drm_dd_minor = version->drm_dd_minor;
2539
2540     if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
2541         retcode = -errno;
2542     }
2543
2544     version->drm_di_major = sv.drm_di_major;
2545     version->drm_di_minor = sv.drm_di_minor;
2546     version->drm_dd_major = sv.drm_dd_major;
2547     version->drm_dd_minor = sv.drm_dd_minor;
2548
2549     return retcode;
2550 }
2551
2552 /**
2553  * Send a device-specific command.
2554  *
2555  * \param fd file descriptor.
2556  * \param drmCommandIndex command index
2557  *
2558  * \return zero on success, or a negative value on failure.
2559  *
2560  * \internal
2561  * It issues a ioctl given by
2562  * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2563  */
2564 int drmCommandNone(int fd, unsigned long drmCommandIndex)
2565 {
2566     unsigned long request;
2567
2568     request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
2569
2570     if (drmIoctl(fd, request, NULL)) {
2571         return -errno;
2572     }
2573     return 0;
2574 }
2575
2576
2577 /**
2578  * Send a device-specific read command.
2579  *
2580  * \param fd file descriptor.
2581  * \param drmCommandIndex command index
2582  * \param data destination pointer of the data to be read.
2583  * \param size size of the data to be read.
2584  *
2585  * \return zero on success, or a negative value on failure.
2586  *
2587  * \internal
2588  * It issues a read ioctl given by
2589  * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2590  */
2591 int drmCommandRead(int fd, unsigned long drmCommandIndex, void *data,
2592                    unsigned long size)
2593 {
2594     unsigned long request;
2595
2596     request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
2597         DRM_COMMAND_BASE + drmCommandIndex, size);
2598
2599     if (drmIoctl(fd, request, data)) {
2600         return -errno;
2601     }
2602     return 0;
2603 }
2604
2605
2606 /**
2607  * Send a device-specific write command.
2608  *
2609  * \param fd file descriptor.
2610  * \param drmCommandIndex command index
2611  * \param data source pointer of the data to be written.
2612  * \param size size of the data to be written.
2613  *
2614  * \return zero on success, or a negative value on failure.
2615  *
2616  * \internal
2617  * It issues a write ioctl given by
2618  * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2619  */
2620 int drmCommandWrite(int fd, unsigned long drmCommandIndex, void *data,
2621                     unsigned long size)
2622 {
2623     unsigned long request;
2624
2625     request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
2626         DRM_COMMAND_BASE + drmCommandIndex, size);
2627
2628     if (drmIoctl(fd, request, data)) {
2629         return -errno;
2630     }
2631     return 0;
2632 }
2633
2634
2635 /**
2636  * Send a device-specific read-write command.
2637  *
2638  * \param fd file descriptor.
2639  * \param drmCommandIndex command index
2640  * \param data source pointer of the data to be read and written.
2641  * \param size size of the data to be read and written.
2642  *
2643  * \return zero on success, or a negative value on failure.
2644  *
2645  * \internal
2646  * It issues a read-write ioctl given by
2647  * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2648  */
2649 int drmCommandWriteRead(int fd, unsigned long drmCommandIndex, void *data,
2650                         unsigned long size)
2651 {
2652     unsigned long request;
2653
2654     request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
2655         DRM_COMMAND_BASE + drmCommandIndex, size);
2656
2657     if (drmIoctl(fd, request, data))
2658         return -errno;
2659     return 0;
2660 }
2661
2662 #define DRM_MAX_FDS 16
2663 static struct {
2664     char *BusID;
2665     int fd;
2666     int refcount;
2667     int type;
2668 } connection[DRM_MAX_FDS];
2669
2670 static int nr_fds = 0;
2671
2672 int drmOpenOnce(void *unused,
2673                 const char *BusID,
2674                 int *newlyopened)
2675 {
2676     return drmOpenOnceWithType(BusID, newlyopened, DRM_NODE_PRIMARY);
2677 }
2678
2679 int drmOpenOnceWithType(const char *BusID, int *newlyopened, int type)
2680 {
2681     int i;
2682     int fd;
2683
2684     for (i = 0; i < nr_fds; i++)
2685         if ((strcmp(BusID, connection[i].BusID) == 0) &&
2686             (connection[i].type == type)) {
2687             connection[i].refcount++;
2688             *newlyopened = 0;
2689             return connection[i].fd;
2690         }
2691
2692     fd = drmOpenWithType(NULL, BusID, type);
2693     if (fd < 0 || nr_fds == DRM_MAX_FDS)
2694         return fd;
2695
2696     connection[nr_fds].BusID = strdup(BusID);
2697     connection[nr_fds].fd = fd;
2698     connection[nr_fds].refcount = 1;
2699     connection[nr_fds].type = type;
2700     *newlyopened = 1;
2701
2702     if (0)
2703         fprintf(stderr, "saved connection %d for %s %d\n",
2704                 nr_fds, connection[nr_fds].BusID,
2705                 strcmp(BusID, connection[nr_fds].BusID));
2706
2707     nr_fds++;
2708
2709     return fd;
2710 }
2711
2712 void drmCloseOnce(int fd)
2713 {
2714     int i;
2715
2716     for (i = 0; i < nr_fds; i++) {
2717         if (fd == connection[i].fd) {
2718             if (--connection[i].refcount == 0) {
2719                 drmClose(connection[i].fd);
2720                 free(connection[i].BusID);
2721
2722                 if (i < --nr_fds)
2723                     connection[i] = connection[nr_fds];
2724
2725                 return;
2726             }
2727         }
2728     }
2729 }
2730
2731 int drmSetMaster(int fd)
2732 {
2733         return drmIoctl(fd, DRM_IOCTL_SET_MASTER, NULL);
2734 }
2735
2736 int drmDropMaster(int fd)
2737 {
2738         return drmIoctl(fd, DRM_IOCTL_DROP_MASTER, NULL);
2739 }
2740
2741 char *drmGetDeviceNameFromFd(int fd)
2742 {
2743     char name[128];
2744     struct stat sbuf;
2745     dev_t d;
2746     int i;
2747
2748     /* The whole drmOpen thing is a fiasco and we need to find a way
2749      * back to just using open(2).  For now, however, lets just make
2750      * things worse with even more ad hoc directory walking code to
2751      * discover the device file name. */
2752
2753     fstat(fd, &sbuf);
2754     d = sbuf.st_rdev;
2755
2756     for (i = 0; i < DRM_MAX_MINOR; i++) {
2757         snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
2758         if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
2759             break;
2760     }
2761     if (i == DRM_MAX_MINOR)
2762         return NULL;
2763
2764     return strdup(name);
2765 }
2766
2767 int drmGetNodeTypeFromFd(int fd)
2768 {
2769     struct stat sbuf;
2770     int maj, min, type;
2771
2772     if (fstat(fd, &sbuf))
2773         return -1;
2774
2775     maj = major(sbuf.st_rdev);
2776     min = minor(sbuf.st_rdev);
2777
2778     if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode)) {
2779         errno = EINVAL;
2780         return -1;
2781     }
2782
2783     type = drmGetMinorType(min);
2784     if (type == -1)
2785         errno = ENODEV;
2786     return type;
2787 }
2788
2789 int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags, int *prime_fd)
2790 {
2791     struct drm_prime_handle args;
2792     int ret;
2793
2794     memclear(args);
2795     args.fd = -1;
2796     args.handle = handle;
2797     args.flags = flags;
2798     ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
2799     if (ret)
2800         return ret;
2801
2802     *prime_fd = args.fd;
2803     return 0;
2804 }
2805
2806 int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
2807 {
2808     struct drm_prime_handle args;
2809     int ret;
2810
2811     memclear(args);
2812     args.fd = prime_fd;
2813     ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
2814     if (ret)
2815         return ret;
2816
2817     *handle = args.handle;
2818     return 0;
2819 }
2820
2821 static char *drmGetMinorNameForFD(int fd, int type)
2822 {
2823 #ifdef __linux__
2824     DIR *sysdir;
2825     struct dirent *pent, *ent;
2826     struct stat sbuf;
2827     const char *name = drmGetMinorName(type);
2828     int len;
2829     char dev_name[64], buf[64];
2830     long name_max;
2831     int maj, min;
2832
2833     if (!name)
2834         return NULL;
2835
2836     len = strlen(name);
2837
2838     if (fstat(fd, &sbuf))
2839         return NULL;
2840
2841     maj = major(sbuf.st_rdev);
2842     min = minor(sbuf.st_rdev);
2843
2844     if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
2845         return NULL;
2846
2847     snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
2848
2849     sysdir = opendir(buf);
2850     if (!sysdir)
2851         return NULL;
2852
2853     name_max = fpathconf(dirfd(sysdir), _PC_NAME_MAX);
2854     if (name_max == -1)
2855         goto out_close_dir;
2856
2857     pent = malloc(offsetof(struct dirent, d_name) + name_max + 1);
2858     if (pent == NULL)
2859          goto out_close_dir;
2860
2861     while (readdir_r(sysdir, pent, &ent) == 0 && ent != NULL) {
2862         if (strncmp(ent->d_name, name, len) == 0) {
2863             snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
2864                  ent->d_name);
2865
2866             free(pent);
2867             closedir(sysdir);
2868
2869             return strdup(dev_name);
2870         }
2871     }
2872
2873     free(pent);
2874
2875 out_close_dir:
2876     closedir(sysdir);
2877 #else
2878     struct stat sbuf;
2879     char buf[PATH_MAX + 1];
2880     const char *dev_name;
2881     unsigned int maj, min;
2882     int n, base;
2883
2884     if (fstat(fd, &sbuf))
2885         return NULL;
2886
2887     maj = major(sbuf.st_rdev);
2888     min = minor(sbuf.st_rdev);
2889
2890     if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
2891         return NULL;
2892
2893     switch (type) {
2894     case DRM_NODE_PRIMARY:
2895         dev_name = DRM_DEV_NAME;
2896         break;
2897     case DRM_NODE_CONTROL:
2898         dev_name = DRM_CONTROL_DEV_NAME;
2899         break;
2900     case DRM_NODE_RENDER:
2901         dev_name = DRM_RENDER_DEV_NAME;
2902         break;
2903     default:
2904         return NULL;
2905     };
2906
2907     base = drmGetMinorBase(type);
2908     if (base < 0)
2909         return NULL;
2910
2911     n = snprintf(buf, sizeof(buf), dev_name, DRM_DIR_NAME, min - base);
2912     if (n == -1 || n >= sizeof(buf))
2913         return NULL;
2914
2915     return strdup(buf);
2916 #endif
2917     return NULL;
2918 }
2919
2920 char *drmGetPrimaryDeviceNameFromFd(int fd)
2921 {
2922     return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
2923 }
2924
2925 char *drmGetRenderDeviceNameFromFd(int fd)
2926 {
2927     return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
2928 }
2929
2930 #ifdef __linux__
2931 static char * DRM_PRINTFLIKE(2, 3)
2932 sysfs_uevent_get(const char *path, const char *fmt, ...)
2933 {
2934     char filename[PATH_MAX + 1], *key, *line = NULL, *value = NULL;
2935     size_t size = 0, len;
2936     ssize_t num;
2937     va_list ap;
2938     FILE *fp;
2939
2940     va_start(ap, fmt);
2941     num = vasprintf(&key, fmt, ap);
2942     va_end(ap);
2943     len = num;
2944
2945     snprintf(filename, sizeof(filename), "%s/uevent", path);
2946
2947     fp = fopen(filename, "r");
2948     if (!fp) {
2949         free(key);
2950         return NULL;
2951     }
2952
2953     while ((num = getline(&line, &size, fp)) >= 0) {
2954         if ((strncmp(line, key, len) == 0) && (line[len] == '=')) {
2955             char *start = line + len + 1, *end = line + num - 1;
2956
2957             if (*end != '\n')
2958                 end++;
2959
2960             value = strndup(start, end - start);
2961             break;
2962         }
2963     }
2964
2965     free(line);
2966     fclose(fp);
2967
2968     free(key);
2969
2970     return value;
2971 }
2972 #endif
2973
2974 static int drmParseSubsystemType(int maj, int min)
2975 {
2976 #ifdef __linux__
2977     char path[PATH_MAX + 1];
2978     char link[PATH_MAX + 1] = "";
2979     char *name;
2980
2981     snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/subsystem",
2982              maj, min);
2983
2984     if (readlink(path, link, PATH_MAX) < 0)
2985         return -errno;
2986
2987     name = strrchr(link, '/');
2988     if (!name)
2989         return -EINVAL;
2990
2991     if (strncmp(name, "/pci", 4) == 0)
2992         return DRM_BUS_PCI;
2993
2994     if (strncmp(name, "/usb", 4) == 0)
2995         return DRM_BUS_USB;
2996
2997     if (strncmp(name, "/platform", 9) == 0)
2998         return DRM_BUS_PLATFORM;
2999
3000     if (strncmp(name, "/host1x", 7) == 0)
3001         return DRM_BUS_HOST1X;
3002
3003     return -EINVAL;
3004 #elif defined(__OpenBSD__)
3005     return DRM_BUS_PCI;
3006 #else
3007 #warning "Missing implementation of drmParseSubsystemType"
3008     return -EINVAL;
3009 #endif
3010 }
3011
3012 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
3013 {
3014 #ifdef __linux__
3015     unsigned int domain, bus, dev, func;
3016     char path[PATH_MAX + 1], *value;
3017     int num;
3018
3019     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3020
3021     value = sysfs_uevent_get(path, "PCI_SLOT_NAME");
3022     if (!value)
3023         return -ENOENT;
3024
3025     num = sscanf(value, "%04x:%02x:%02x.%1u", &domain, &bus, &dev, &func);
3026     free(value);
3027
3028     if (num != 4)
3029         return -EINVAL;
3030
3031     info->domain = domain;
3032     info->bus = bus;
3033     info->dev = dev;
3034     info->func = func;
3035
3036     return 0;
3037 #elif defined(__OpenBSD__)
3038     struct drm_pciinfo pinfo;
3039     int fd, type;
3040
3041     type = drmGetMinorType(min);
3042     if (type == -1)
3043         return -ENODEV;
3044
3045     fd = drmOpenMinor(min, 0, type);
3046     if (fd < 0)
3047         return -errno;
3048
3049     if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3050         close(fd);
3051         return -errno;
3052     }
3053     close(fd);
3054
3055     info->domain = pinfo.domain;
3056     info->bus = pinfo.bus;
3057     info->dev = pinfo.dev;
3058     info->func = pinfo.func;
3059
3060     return 0;
3061 #else
3062 #warning "Missing implementation of drmParsePciBusInfo"
3063     return -EINVAL;
3064 #endif
3065 }
3066
3067 int drmDevicesEqual(drmDevicePtr a, drmDevicePtr b)
3068 {
3069     if (a == NULL || b == NULL)
3070         return 0;
3071
3072     if (a->bustype != b->bustype)
3073         return 0;
3074
3075     switch (a->bustype) {
3076     case DRM_BUS_PCI:
3077         return memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo)) == 0;
3078
3079     case DRM_BUS_USB:
3080         return memcmp(a->businfo.usb, b->businfo.usb, sizeof(drmUsbBusInfo)) == 0;
3081
3082     case DRM_BUS_PLATFORM:
3083         return memcmp(a->businfo.platform, b->businfo.platform, sizeof(drmPlatformBusInfo)) == 0;
3084
3085     case DRM_BUS_HOST1X:
3086         return memcmp(a->businfo.host1x, b->businfo.host1x, sizeof(drmHost1xBusInfo)) == 0;
3087
3088     default:
3089         break;
3090     }
3091
3092     return 0;
3093 }
3094
3095 static int drmGetNodeType(const char *name)
3096 {
3097     if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
3098         sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
3099         return DRM_NODE_PRIMARY;
3100
3101     if (strncmp(name, DRM_CONTROL_MINOR_NAME,
3102         sizeof(DRM_CONTROL_MINOR_NAME ) - 1) == 0)
3103         return DRM_NODE_CONTROL;
3104
3105     if (strncmp(name, DRM_RENDER_MINOR_NAME,
3106         sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
3107         return DRM_NODE_RENDER;
3108
3109     return -EINVAL;
3110 }
3111
3112 static int drmGetMaxNodeName(void)
3113 {
3114     return sizeof(DRM_DIR_NAME) +
3115            MAX3(sizeof(DRM_PRIMARY_MINOR_NAME),
3116                 sizeof(DRM_CONTROL_MINOR_NAME),
3117                 sizeof(DRM_RENDER_MINOR_NAME)) +
3118            3 /* length of the node number */;
3119 }
3120
3121 #ifdef __linux__
3122 static int parse_separate_sysfs_files(int maj, int min,
3123                                       drmPciDeviceInfoPtr device,
3124                                       bool ignore_revision)
3125 {
3126 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3127     static const char *attrs[] = {
3128       "revision", /* Older kernels are missing the file, so check for it first */
3129       "vendor",
3130       "device",
3131       "subsystem_vendor",
3132       "subsystem_device",
3133     };
3134     char path[PATH_MAX + 1];
3135     unsigned int data[ARRAY_SIZE(attrs)];
3136     FILE *fp;
3137     int ret;
3138
3139     for (unsigned i = ignore_revision ? 1 : 0; i < ARRAY_SIZE(attrs); i++) {
3140         snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/%s", maj, min,
3141                  attrs[i]);
3142         fp = fopen(path, "r");
3143         if (!fp)
3144             return -errno;
3145
3146         ret = fscanf(fp, "%x", &data[i]);
3147         fclose(fp);
3148         if (ret != 1)
3149             return -errno;
3150
3151     }
3152
3153     device->revision_id = ignore_revision ? 0xff : data[0] & 0xff;
3154     device->vendor_id = data[1] & 0xffff;
3155     device->device_id = data[2] & 0xffff;
3156     device->subvendor_id = data[3] & 0xffff;
3157     device->subdevice_id = data[4] & 0xffff;
3158
3159     return 0;
3160 }
3161
3162 static int parse_config_sysfs_file(int maj, int min,
3163                                    drmPciDeviceInfoPtr device)
3164 {
3165     char path[PATH_MAX + 1];
3166     unsigned char config[64];
3167     int fd, ret;
3168
3169     snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/config", maj, min);
3170     fd = open(path, O_RDONLY);
3171     if (fd < 0)
3172         return -errno;
3173
3174     ret = read(fd, config, sizeof(config));
3175     close(fd);
3176     if (ret < 0)
3177         return -errno;
3178
3179     device->vendor_id = config[0] | (config[1] << 8);
3180     device->device_id = config[2] | (config[3] << 8);
3181     device->revision_id = config[8];
3182     device->subvendor_id = config[44] | (config[45] << 8);
3183     device->subdevice_id = config[46] | (config[47] << 8);
3184
3185     return 0;
3186 }
3187 #endif
3188
3189 static int drmParsePciDeviceInfo(int maj, int min,
3190                                  drmPciDeviceInfoPtr device,
3191                                  uint32_t flags)
3192 {
3193 #ifdef __linux__
3194     if (!(flags & DRM_DEVICE_GET_PCI_REVISION))
3195         return parse_separate_sysfs_files(maj, min, device, true);
3196
3197     if (parse_separate_sysfs_files(maj, min, device, false))
3198         return parse_config_sysfs_file(maj, min, device);
3199
3200     return 0;
3201 #elif defined(__OpenBSD__)
3202     struct drm_pciinfo pinfo;
3203     int fd, type;
3204
3205     type = drmGetMinorType(min);
3206     if (type == -1)
3207         return -ENODEV;
3208
3209     fd = drmOpenMinor(min, 0, type);
3210     if (fd < 0)
3211         return -errno;
3212
3213     if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3214         close(fd);
3215         return -errno;
3216     }
3217     close(fd);
3218
3219     device->vendor_id = pinfo.vendor_id;
3220     device->device_id = pinfo.device_id;
3221     device->revision_id = pinfo.revision_id;
3222     device->subvendor_id = pinfo.subvendor_id;
3223     device->subdevice_id = pinfo.subdevice_id;
3224
3225     return 0;
3226 #else
3227 #warning "Missing implementation of drmParsePciDeviceInfo"
3228     return -EINVAL;
3229 #endif
3230 }
3231
3232 static void drmFreePlatformDevice(drmDevicePtr device)
3233 {
3234     if (device->deviceinfo.platform) {
3235         if (device->deviceinfo.platform->compatible) {
3236             char **compatible = device->deviceinfo.platform->compatible;
3237
3238             while (*compatible) {
3239                 free(*compatible);
3240                 compatible++;
3241             }
3242
3243             free(device->deviceinfo.platform->compatible);
3244         }
3245     }
3246 }
3247
3248 static void drmFreeHost1xDevice(drmDevicePtr device)
3249 {
3250     if (device->deviceinfo.host1x) {
3251         if (device->deviceinfo.host1x->compatible) {
3252             char **compatible = device->deviceinfo.host1x->compatible;
3253
3254             while (*compatible) {
3255                 free(*compatible);
3256                 compatible++;
3257             }
3258
3259             free(device->deviceinfo.host1x->compatible);
3260         }
3261     }
3262 }
3263
3264 void drmFreeDevice(drmDevicePtr *device)
3265 {
3266     if (device == NULL)
3267         return;
3268
3269     if (*device) {
3270         switch ((*device)->bustype) {
3271         case DRM_BUS_PLATFORM:
3272             drmFreePlatformDevice(*device);
3273             break;
3274
3275         case DRM_BUS_HOST1X:
3276             drmFreeHost1xDevice(*device);
3277             break;
3278         }
3279     }
3280
3281     free(*device);
3282     *device = NULL;
3283 }
3284
3285 void drmFreeDevices(drmDevicePtr devices[], int count)
3286 {
3287     int i;
3288
3289     if (devices == NULL)
3290         return;
3291
3292     for (i = 0; i < count; i++)
3293         if (devices[i])
3294             drmFreeDevice(&devices[i]);
3295 }
3296
3297 static drmDevicePtr drmDeviceAlloc(unsigned int type, const char *node,
3298                                    size_t bus_size, size_t device_size,
3299                                    char **ptrp)
3300 {
3301     size_t max_node_length, extra, size;
3302     drmDevicePtr device;
3303     unsigned int i;
3304     char *ptr;
3305
3306     max_node_length = ALIGN(drmGetMaxNodeName(), sizeof(void *));
3307     extra = DRM_NODE_MAX * (sizeof(void *) + max_node_length);
3308
3309     size = sizeof(*device) + extra + bus_size + device_size;
3310
3311     device = calloc(1, size);
3312     if (!device)
3313         return NULL;
3314
3315     device->available_nodes = 1 << type;
3316
3317     ptr = (char *)device + sizeof(*device);
3318     device->nodes = (char **)ptr;
3319
3320     ptr += DRM_NODE_MAX * sizeof(void *);
3321
3322     for (i = 0; i < DRM_NODE_MAX; i++) {
3323         device->nodes[i] = ptr;
3324         ptr += max_node_length;
3325     }
3326
3327     memcpy(device->nodes[type], node, max_node_length);
3328
3329     *ptrp = ptr;
3330
3331     return device;
3332 }
3333
3334 static int drmProcessPciDevice(drmDevicePtr *device,
3335                                const char *node, int node_type,
3336                                int maj, int min, bool fetch_deviceinfo,
3337                                uint32_t flags)
3338 {
3339     drmDevicePtr dev;
3340     char *addr;
3341     int ret;
3342
3343     dev = drmDeviceAlloc(node_type, node, sizeof(drmPciBusInfo),
3344                          sizeof(drmPciDeviceInfo), &addr);
3345     if (!dev)
3346         return -ENOMEM;
3347
3348     dev->bustype = DRM_BUS_PCI;
3349
3350     dev->businfo.pci = (drmPciBusInfoPtr)addr;
3351
3352     ret = drmParsePciBusInfo(maj, min, dev->businfo.pci);
3353     if (ret)
3354         goto free_device;
3355
3356     // Fetch the device info if the user has requested it
3357     if (fetch_deviceinfo) {
3358         addr += sizeof(drmPciBusInfo);
3359         dev->deviceinfo.pci = (drmPciDeviceInfoPtr)addr;
3360
3361         ret = drmParsePciDeviceInfo(maj, min, dev->deviceinfo.pci, flags);
3362         if (ret)
3363             goto free_device;
3364     }
3365
3366     *device = dev;
3367
3368     return 0;
3369
3370 free_device:
3371     free(dev);
3372     return ret;
3373 }
3374
3375 static int drmParseUsbBusInfo(int maj, int min, drmUsbBusInfoPtr info)
3376 {
3377 #ifdef __linux__
3378     char path[PATH_MAX + 1], *value;
3379     unsigned int bus, dev;
3380     int ret;
3381
3382     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3383
3384     value = sysfs_uevent_get(path, "BUSNUM");
3385     if (!value)
3386         return -ENOENT;
3387
3388     ret = sscanf(value, "%03u", &bus);
3389     free(value);
3390
3391     if (ret <= 0)
3392         return -errno;
3393
3394     value = sysfs_uevent_get(path, "DEVNUM");
3395     if (!value)
3396         return -ENOENT;
3397
3398     ret = sscanf(value, "%03u", &dev);
3399     free(value);
3400
3401     if (ret <= 0)
3402         return -errno;
3403
3404     info->bus = bus;
3405     info->dev = dev;
3406
3407     return 0;
3408 #else
3409 #warning "Missing implementation of drmParseUsbBusInfo"
3410     return -EINVAL;
3411 #endif
3412 }
3413
3414 static int drmParseUsbDeviceInfo(int maj, int min, drmUsbDeviceInfoPtr info)
3415 {
3416 #ifdef __linux__
3417     char path[PATH_MAX + 1], *value;
3418     unsigned int vendor, product;
3419     int ret;
3420
3421     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3422
3423     value = sysfs_uevent_get(path, "PRODUCT");
3424     if (!value)
3425         return -ENOENT;
3426
3427     ret = sscanf(value, "%x/%x", &vendor, &product);
3428     free(value);
3429
3430     if (ret <= 0)
3431         return -errno;
3432
3433     info->vendor = vendor;
3434     info->product = product;
3435
3436     return 0;
3437 #else
3438 #warning "Missing implementation of drmParseUsbDeviceInfo"
3439     return -EINVAL;
3440 #endif
3441 }
3442
3443 static int drmProcessUsbDevice(drmDevicePtr *device, const char *node,
3444                                int node_type, int maj, int min,
3445                                bool fetch_deviceinfo, uint32_t flags)
3446 {
3447     drmDevicePtr dev;
3448     char *ptr;
3449     int ret;
3450
3451     dev = drmDeviceAlloc(node_type, node, sizeof(drmUsbBusInfo),
3452                          sizeof(drmUsbDeviceInfo), &ptr);
3453     if (!dev)
3454         return -ENOMEM;
3455
3456     dev->bustype = DRM_BUS_USB;
3457
3458     dev->businfo.usb = (drmUsbBusInfoPtr)ptr;
3459
3460     ret = drmParseUsbBusInfo(maj, min, dev->businfo.usb);
3461     if (ret < 0)
3462         goto free_device;
3463
3464     if (fetch_deviceinfo) {
3465         ptr += sizeof(drmUsbBusInfo);
3466         dev->deviceinfo.usb = (drmUsbDeviceInfoPtr)ptr;
3467
3468         ret = drmParseUsbDeviceInfo(maj, min, dev->deviceinfo.usb);
3469         if (ret < 0)
3470             goto free_device;
3471     }
3472
3473     *device = dev;
3474
3475     return 0;
3476
3477 free_device:
3478     free(dev);
3479     return ret;
3480 }
3481
3482 static int drmParsePlatformBusInfo(int maj, int min, drmPlatformBusInfoPtr info)
3483 {
3484 #ifdef __linux__
3485     char path[PATH_MAX + 1], *name;
3486
3487     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3488
3489     name = sysfs_uevent_get(path, "OF_FULLNAME");
3490     if (!name)
3491         return -ENOENT;
3492
3493     strncpy(info->fullname, name, DRM_PLATFORM_DEVICE_NAME_LEN);
3494     info->fullname[DRM_PLATFORM_DEVICE_NAME_LEN - 1] = '\0';
3495     free(name);
3496
3497     return 0;
3498 #else
3499 #warning "Missing implementation of drmParsePlatformBusInfo"
3500     return -EINVAL;
3501 #endif
3502 }
3503
3504 static int drmParsePlatformDeviceInfo(int maj, int min,
3505                                       drmPlatformDeviceInfoPtr info)
3506 {
3507 #ifdef __linux__
3508     char path[PATH_MAX + 1], *value;
3509     unsigned int count, i;
3510     int err;
3511
3512     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3513
3514     value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
3515     if (!value)
3516         return -ENOENT;
3517
3518     sscanf(value, "%u", &count);
3519     free(value);
3520
3521     info->compatible = calloc(count + 1, sizeof(*info->compatible));
3522     if (!info->compatible)
3523         return -ENOMEM;
3524
3525     for (i = 0; i < count; i++) {
3526         value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
3527         if (!value) {
3528             err = -ENOENT;
3529             goto free;
3530         }
3531
3532         info->compatible[i] = value;
3533     }
3534
3535     return 0;
3536
3537 free:
3538     while (i--)
3539         free(info->compatible[i]);
3540
3541     free(info->compatible);
3542     return err;
3543 #else
3544 #warning "Missing implementation of drmParsePlatformDeviceInfo"
3545     return -EINVAL;
3546 #endif
3547 }
3548
3549 static int drmProcessPlatformDevice(drmDevicePtr *device,
3550                                     const char *node, int node_type,
3551                                     int maj, int min, bool fetch_deviceinfo,
3552                                     uint32_t flags)
3553 {
3554     drmDevicePtr dev;
3555     char *ptr;
3556     int ret;
3557
3558     dev = drmDeviceAlloc(node_type, node, sizeof(drmPlatformBusInfo),
3559                          sizeof(drmPlatformDeviceInfo), &ptr);
3560     if (!dev)
3561         return -ENOMEM;
3562
3563     dev->bustype = DRM_BUS_PLATFORM;
3564
3565     dev->businfo.platform = (drmPlatformBusInfoPtr)ptr;
3566
3567     ret = drmParsePlatformBusInfo(maj, min, dev->businfo.platform);
3568     if (ret < 0)
3569         goto free_device;
3570
3571     if (fetch_deviceinfo) {
3572         ptr += sizeof(drmPlatformBusInfo);
3573         dev->deviceinfo.platform = (drmPlatformDeviceInfoPtr)ptr;
3574
3575         ret = drmParsePlatformDeviceInfo(maj, min, dev->deviceinfo.platform);
3576         if (ret < 0)
3577             goto free_device;
3578     }
3579
3580     *device = dev;
3581
3582     return 0;
3583
3584 free_device:
3585     free(dev);
3586     return ret;
3587 }
3588
3589 static int drmParseHost1xBusInfo(int maj, int min, drmHost1xBusInfoPtr info)
3590 {
3591 #ifdef __linux__
3592     char path[PATH_MAX + 1], *name;
3593
3594     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3595
3596     name = sysfs_uevent_get(path, "OF_FULLNAME");
3597     if (!name)
3598         return -ENOENT;
3599
3600     strncpy(info->fullname, name, DRM_HOST1X_DEVICE_NAME_LEN);
3601     info->fullname[DRM_HOST1X_DEVICE_NAME_LEN - 1] = '\0';
3602     free(name);
3603
3604     return 0;
3605 #else
3606 #warning "Missing implementation of drmParseHost1xBusInfo"
3607     return -EINVAL;
3608 #endif
3609 }
3610
3611 static int drmParseHost1xDeviceInfo(int maj, int min,
3612                                     drmHost1xDeviceInfoPtr info)
3613 {
3614 #ifdef __linux__
3615     char path[PATH_MAX + 1], *value;
3616     unsigned int count, i;
3617     int err;
3618
3619     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3620
3621     value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
3622     if (!value)
3623         return -ENOENT;
3624
3625     sscanf(value, "%u", &count);
3626     free(value);
3627
3628     info->compatible = calloc(count + 1, sizeof(*info->compatible));
3629     if (!info->compatible)
3630         return -ENOMEM;
3631
3632     for (i = 0; i < count; i++) {
3633         value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
3634         if (!value) {
3635             err = -ENOENT;
3636             goto free;
3637         }
3638
3639         info->compatible[i] = value;
3640     }
3641
3642     return 0;
3643
3644 free:
3645     while (i--)
3646         free(info->compatible[i]);
3647
3648     free(info->compatible);
3649     return err;
3650 #else
3651 #warning "Missing implementation of drmParseHost1xDeviceInfo"
3652     return -EINVAL;
3653 #endif
3654 }
3655
3656 static int drmProcessHost1xDevice(drmDevicePtr *device,
3657                                   const char *node, int node_type,
3658                                   int maj, int min, bool fetch_deviceinfo,
3659                                   uint32_t flags)
3660 {
3661     drmDevicePtr dev;
3662     char *ptr;
3663     int ret;
3664
3665     dev = drmDeviceAlloc(node_type, node, sizeof(drmHost1xBusInfo),
3666                          sizeof(drmHost1xDeviceInfo), &ptr);
3667     if (!dev)
3668         return -ENOMEM;
3669
3670     dev->bustype = DRM_BUS_HOST1X;
3671
3672     dev->businfo.host1x = (drmHost1xBusInfoPtr)ptr;
3673
3674     ret = drmParseHost1xBusInfo(maj, min, dev->businfo.host1x);
3675     if (ret < 0)
3676         goto free_device;
3677
3678     if (fetch_deviceinfo) {
3679         ptr += sizeof(drmHost1xBusInfo);
3680         dev->deviceinfo.host1x = (drmHost1xDeviceInfoPtr)ptr;
3681
3682         ret = drmParseHost1xDeviceInfo(maj, min, dev->deviceinfo.host1x);
3683         if (ret < 0)
3684             goto free_device;
3685     }
3686
3687     *device = dev;
3688
3689     return 0;
3690
3691 free_device:
3692     free(dev);
3693     return ret;
3694 }
3695
3696 /* Consider devices located on the same bus as duplicate and fold the respective
3697  * entries into a single one.
3698  *
3699  * Note: this leaves "gaps" in the array, while preserving the length.
3700  */
3701 static void drmFoldDuplicatedDevices(drmDevicePtr local_devices[], int count)
3702 {
3703     int node_type, i, j;
3704
3705     for (i = 0; i < count; i++) {
3706         for (j = i + 1; j < count; j++) {
3707             if (drmDevicesEqual(local_devices[i], local_devices[j])) {
3708                 local_devices[i]->available_nodes |= local_devices[j]->available_nodes;
3709                 node_type = log2(local_devices[j]->available_nodes);
3710                 memcpy(local_devices[i]->nodes[node_type],
3711                        local_devices[j]->nodes[node_type], drmGetMaxNodeName());
3712                 drmFreeDevice(&local_devices[j]);
3713             }
3714         }
3715     }
3716 }
3717
3718 /* Check that the given flags are valid returning 0 on success */
3719 static int
3720 drm_device_validate_flags(uint32_t flags)
3721 {
3722         return (flags & ~DRM_DEVICE_GET_PCI_REVISION);
3723 }
3724
3725 /**
3726  * Get information about the opened drm device
3727  *
3728  * \param fd file descriptor of the drm device
3729  * \param flags feature/behaviour bitmask
3730  * \param device the address of a drmDevicePtr where the information
3731  *               will be allocated in stored
3732  *
3733  * \return zero on success, negative error code otherwise.
3734  *
3735  * \note Unlike drmGetDevice it does not retrieve the pci device revision field
3736  * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
3737  */
3738 int drmGetDevice2(int fd, uint32_t flags, drmDevicePtr *device)
3739 {
3740 #ifdef __OpenBSD__
3741     /*
3742      * DRI device nodes on OpenBSD are not in their own directory, they reside
3743      * in /dev along with a large number of statically generated /dev nodes.
3744      * Avoid stat'ing all of /dev needlessly by implementing this custom path.
3745      */
3746     drmDevicePtr     d;
3747     struct stat      sbuf;
3748     char             node[PATH_MAX + 1];
3749     const char      *dev_name;
3750     int              node_type, subsystem_type;
3751     int              maj, min, n, ret, base;
3752
3753     if (fd == -1 || device == NULL)
3754         return -EINVAL;
3755
3756     if (fstat(fd, &sbuf))
3757         return -errno;
3758
3759     maj = major(sbuf.st_rdev);
3760     min = minor(sbuf.st_rdev);
3761
3762     if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3763         return -EINVAL;
3764
3765     node_type = drmGetMinorType(min);
3766     if (node_type == -1)
3767         return -ENODEV;
3768
3769     switch (node_type) {
3770     case DRM_NODE_PRIMARY:
3771         dev_name = DRM_DEV_NAME;
3772         break;
3773     case DRM_NODE_CONTROL:
3774         dev_name = DRM_CONTROL_DEV_NAME;
3775         break;
3776     case DRM_NODE_RENDER:
3777         dev_name = DRM_RENDER_DEV_NAME;
3778         break;
3779     default:
3780         return -EINVAL;
3781     };
3782
3783     base = drmGetMinorBase(node_type);
3784     if (base < 0)
3785         return -EINVAL;
3786
3787     n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min - base);
3788     if (n == -1 || n >= PATH_MAX)
3789       return -errno;
3790     if (stat(node, &sbuf))
3791         return -EINVAL;
3792
3793     subsystem_type = drmParseSubsystemType(maj, min);
3794     if (subsystem_type != DRM_BUS_PCI)
3795         return -ENODEV;
3796
3797     ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
3798     if (ret)
3799         return ret;
3800
3801     *device = d;
3802
3803     return 0;
3804 #else
3805     drmDevicePtr *local_devices;
3806     drmDevicePtr d;
3807     DIR *sysdir;
3808     struct dirent *dent;
3809     struct stat sbuf;
3810     char node[PATH_MAX + 1];
3811     int node_type, subsystem_type;
3812     int maj, min;
3813     int ret, i, node_count;
3814     int max_count = 16;
3815     dev_t find_rdev;
3816
3817     if (drm_device_validate_flags(flags))
3818         return -EINVAL;
3819
3820     if (fd == -1 || device == NULL)
3821         return -EINVAL;
3822
3823     if (fstat(fd, &sbuf))
3824         return -errno;
3825
3826     find_rdev = sbuf.st_rdev;
3827     maj = major(sbuf.st_rdev);
3828     min = minor(sbuf.st_rdev);
3829
3830     if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3831         return -EINVAL;
3832
3833     subsystem_type = drmParseSubsystemType(maj, min);
3834
3835     local_devices = calloc(max_count, sizeof(drmDevicePtr));
3836     if (local_devices == NULL)
3837         return -ENOMEM;
3838
3839     sysdir = opendir(DRM_DIR_NAME);
3840     if (!sysdir) {
3841         ret = -errno;
3842         goto free_locals;
3843     }
3844
3845     i = 0;
3846     while ((dent = readdir(sysdir))) {
3847         node_type = drmGetNodeType(dent->d_name);
3848         if (node_type < 0)
3849             continue;
3850
3851         snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, dent->d_name);
3852         if (stat(node, &sbuf))
3853             continue;
3854
3855         maj = major(sbuf.st_rdev);
3856         min = minor(sbuf.st_rdev);
3857
3858         if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3859             continue;
3860
3861         if (drmParseSubsystemType(maj, min) != subsystem_type)
3862             continue;
3863
3864         switch (subsystem_type) {
3865         case DRM_BUS_PCI:
3866             ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
3867             if (ret)
3868                 continue;
3869
3870             break;
3871
3872         case DRM_BUS_USB:
3873             ret = drmProcessUsbDevice(&d, node, node_type, maj, min, true, flags);
3874             if (ret)
3875                 continue;
3876
3877             break;
3878
3879         case DRM_BUS_PLATFORM:
3880             ret = drmProcessPlatformDevice(&d, node, node_type, maj, min, true, flags);
3881             if (ret)
3882                 continue;
3883
3884             break;
3885
3886         case DRM_BUS_HOST1X:
3887             ret = drmProcessHost1xDevice(&d, node, node_type, maj, min, true, flags);
3888             if (ret)
3889                 continue;
3890
3891             break;
3892
3893         default:
3894             continue;
3895         }
3896
3897         if (i >= max_count) {
3898             drmDevicePtr *temp;
3899
3900             max_count += 16;
3901             temp = realloc(local_devices, max_count * sizeof(drmDevicePtr));
3902             if (!temp)
3903                 goto free_devices;
3904             local_devices = temp;
3905         }
3906
3907         /* store target at local_devices[0] for ease to use below */
3908         if (find_rdev == sbuf.st_rdev && i) {
3909             local_devices[i] = local_devices[0];
3910             local_devices[0] = d;
3911         }
3912         else
3913             local_devices[i] = d;
3914         i++;
3915     }
3916     node_count = i;
3917
3918     drmFoldDuplicatedDevices(local_devices, node_count);
3919
3920     *device = local_devices[0];
3921     drmFreeDevices(&local_devices[1], node_count - 1);
3922
3923     closedir(sysdir);
3924     free(local_devices);
3925     if (*device == NULL)
3926         return -ENODEV;
3927     return 0;
3928
3929 free_devices:
3930     drmFreeDevices(local_devices, i);
3931     closedir(sysdir);
3932
3933 free_locals:
3934     free(local_devices);
3935     return ret;
3936 #endif
3937 }
3938
3939 /**
3940  * Get information about the opened drm device
3941  *
3942  * \param fd file descriptor of the drm device
3943  * \param device the address of a drmDevicePtr where the information
3944  *               will be allocated in stored
3945  *
3946  * \return zero on success, negative error code otherwise.
3947  */
3948 int drmGetDevice(int fd, drmDevicePtr *device)
3949 {
3950     return drmGetDevice2(fd, DRM_DEVICE_GET_PCI_REVISION, device);
3951 }
3952
3953 /**
3954  * Get drm devices on the system
3955  *
3956  * \param flags feature/behaviour bitmask
3957  * \param devices the array of devices with drmDevicePtr elements
3958  *                can be NULL to get the device number first
3959  * \param max_devices the maximum number of devices for the array
3960  *
3961  * \return on error - negative error code,
3962  *         if devices is NULL - total number of devices available on the system,
3963  *         alternatively the number of devices stored in devices[], which is
3964  *         capped by the max_devices.
3965  *
3966  * \note Unlike drmGetDevices it does not retrieve the pci device revision field
3967  * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
3968  */
3969 int drmGetDevices2(uint32_t flags, drmDevicePtr devices[], int max_devices)
3970 {
3971     drmDevicePtr *local_devices;
3972     drmDevicePtr device;
3973     DIR *sysdir;
3974     struct dirent *dent;
3975     struct stat sbuf;
3976     char node[PATH_MAX + 1];
3977     int node_type, subsystem_type;
3978     int maj, min;
3979     int ret, i, node_count, device_count;
3980     int max_count = 16;
3981
3982     if (drm_device_validate_flags(flags))
3983         return -EINVAL;
3984
3985     local_devices = calloc(max_count, sizeof(drmDevicePtr));
3986     if (local_devices == NULL)
3987         return -ENOMEM;
3988
3989     sysdir = opendir(DRM_DIR_NAME);
3990     if (!sysdir) {
3991         ret = -errno;
3992         goto free_locals;
3993     }
3994
3995     i = 0;
3996     while ((dent = readdir(sysdir))) {
3997         node_type = drmGetNodeType(dent->d_name);
3998         if (node_type < 0)
3999             continue;
4000
4001         snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, dent->d_name);
4002         if (stat(node, &sbuf))
4003             continue;
4004
4005         maj = major(sbuf.st_rdev);
4006         min = minor(sbuf.st_rdev);
4007
4008         if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
4009             continue;
4010
4011         subsystem_type = drmParseSubsystemType(maj, min);
4012
4013         if (subsystem_type < 0)
4014             continue;
4015
4016         switch (subsystem_type) {
4017         case DRM_BUS_PCI:
4018             ret = drmProcessPciDevice(&device, node, node_type,
4019                                       maj, min, devices != NULL, flags);
4020             if (ret)
4021                 continue;
4022
4023             break;
4024
4025         case DRM_BUS_USB:
4026             ret = drmProcessUsbDevice(&device, node, node_type, maj, min,
4027                                       devices != NULL, flags);
4028             if (ret)
4029                 continue;
4030
4031             break;
4032
4033         case DRM_BUS_PLATFORM:
4034             ret = drmProcessPlatformDevice(&device, node, node_type, maj, min,
4035                                            devices != NULL, flags);
4036             if (ret)
4037                 continue;
4038
4039             break;
4040
4041         case DRM_BUS_HOST1X:
4042             ret = drmProcessHost1xDevice(&device, node, node_type, maj, min,
4043                                          devices != NULL, flags);
4044             if (ret)
4045                 continue;
4046
4047             break;
4048
4049         default:
4050             continue;
4051         }
4052
4053         if (i >= max_count) {
4054             drmDevicePtr *temp;
4055
4056             max_count += 16;
4057             temp = realloc(local_devices, max_count * sizeof(drmDevicePtr));
4058             if (!temp)
4059                 goto free_devices;
4060             local_devices = temp;
4061         }
4062
4063         local_devices[i] = device;
4064         i++;
4065     }
4066     node_count = i;
4067
4068     drmFoldDuplicatedDevices(local_devices, node_count);
4069
4070     device_count = 0;
4071     for (i = 0; i < node_count; i++) {
4072         if (!local_devices[i])
4073             continue;
4074
4075         if ((devices != NULL) && (device_count < max_devices))
4076             devices[device_count] = local_devices[i];
4077         else
4078             drmFreeDevice(&local_devices[i]);
4079
4080         device_count++;
4081     }
4082
4083     closedir(sysdir);
4084     free(local_devices);
4085     return device_count;
4086
4087 free_devices:
4088     drmFreeDevices(local_devices, i);
4089     closedir(sysdir);
4090
4091 free_locals:
4092     free(local_devices);
4093     return ret;
4094 }
4095
4096 /**
4097  * Get drm devices on the system
4098  *
4099  * \param devices the array of devices with drmDevicePtr elements
4100  *                can be NULL to get the device number first
4101  * \param max_devices the maximum number of devices for the array
4102  *
4103  * \return on error - negative error code,
4104  *         if devices is NULL - total number of devices available on the system,
4105  *         alternatively the number of devices stored in devices[], which is
4106  *         capped by the max_devices.
4107  */
4108 int drmGetDevices(drmDevicePtr devices[], int max_devices)
4109 {
4110     return drmGetDevices2(DRM_DEVICE_GET_PCI_REVISION, devices, max_devices);
4111 }
4112
4113 char *drmGetDeviceNameFromFd2(int fd)
4114 {
4115 #ifdef __linux__
4116     struct stat sbuf;
4117     char path[PATH_MAX + 1], *value;
4118     unsigned int maj, min;
4119
4120     if (fstat(fd, &sbuf))
4121         return NULL;
4122
4123     maj = major(sbuf.st_rdev);
4124     min = minor(sbuf.st_rdev);
4125
4126     if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
4127         return NULL;
4128
4129     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d", maj, min);
4130
4131     value = sysfs_uevent_get(path, "DEVNAME");
4132     if (!value)
4133         return NULL;
4134
4135     snprintf(path, sizeof(path), "/dev/%s", value);
4136     free(value);
4137
4138     return strdup(path);
4139 #else
4140     struct stat      sbuf;
4141     char             node[PATH_MAX + 1];
4142     const char      *dev_name;
4143     int              node_type;
4144     int              maj, min, n, base;
4145
4146     if (fstat(fd, &sbuf))
4147         return NULL;
4148
4149     maj = major(sbuf.st_rdev);
4150     min = minor(sbuf.st_rdev);
4151
4152     if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
4153         return NULL;
4154
4155     node_type = drmGetMinorType(min);
4156     if (node_type == -1)
4157         return NULL;
4158
4159     switch (node_type) {
4160     case DRM_NODE_PRIMARY:
4161         dev_name = DRM_DEV_NAME;
4162         break;
4163     case DRM_NODE_CONTROL:
4164         dev_name = DRM_CONTROL_DEV_NAME;
4165         break;
4166     case DRM_NODE_RENDER:
4167         dev_name = DRM_RENDER_DEV_NAME;
4168         break;
4169     default:
4170         return NULL;
4171     };
4172
4173     base = drmGetMinorBase(node_type);
4174     if (base < 0)
4175         return NULL;
4176
4177     n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min - base);
4178     if (n == -1 || n >= PATH_MAX)
4179       return NULL;
4180
4181     return strdup(node);
4182 #endif
4183 }
4184
4185 int drmSyncobjCreate(int fd, uint32_t flags, uint32_t *handle)
4186 {
4187     struct drm_syncobj_create args;
4188     int ret;
4189
4190     memclear(args);
4191     args.flags = flags;
4192     args.handle = 0;
4193     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_CREATE, &args);
4194     if (ret)
4195         return ret;
4196     *handle = args.handle;
4197     return 0;
4198 }
4199
4200 int drmSyncobjDestroy(int fd, uint32_t handle)
4201 {
4202     struct drm_syncobj_destroy args;
4203
4204     memclear(args);
4205     args.handle = handle;
4206     return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_DESTROY, &args);
4207 }
4208
4209 int drmSyncobjHandleToFD(int fd, uint32_t handle, int *obj_fd)
4210 {
4211     struct drm_syncobj_handle args;
4212     int ret;
4213
4214     memclear(args);
4215     args.fd = -1;
4216     args.handle = handle;
4217     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4218     if (ret)
4219         return ret;
4220     *obj_fd = args.fd;
4221     return 0;
4222 }
4223
4224 int drmSyncobjFDToHandle(int fd, int obj_fd, uint32_t *handle)
4225 {
4226     struct drm_syncobj_handle args;
4227     int ret;
4228
4229     memclear(args);
4230     args.fd = obj_fd;
4231     args.handle = 0;
4232     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4233     if (ret)
4234         return ret;
4235     *handle = args.handle;
4236     return 0;
4237 }
4238
4239 int drmSyncobjImportSyncFile(int fd, uint32_t handle, int sync_file_fd)
4240 {
4241     struct drm_syncobj_handle args;
4242
4243     memclear(args);
4244     args.fd = sync_file_fd;
4245     args.handle = handle;
4246     args.flags = DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE;
4247     return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4248 }
4249
4250 int drmSyncobjExportSyncFile(int fd, uint32_t handle, int *sync_file_fd)
4251 {
4252     struct drm_syncobj_handle args;
4253     int ret;
4254
4255     memclear(args);
4256     args.fd = -1;
4257     args.handle = handle;
4258     args.flags = DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE;
4259     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4260     if (ret)
4261         return ret;
4262     *sync_file_fd = args.fd;
4263     return 0;
4264 }
4265
4266 int drmSyncobjWait(int fd, uint32_t *handles, unsigned num_handles,
4267                    int64_t timeout_nsec, unsigned flags,
4268                    uint32_t *first_signaled)
4269 {
4270     struct drm_syncobj_wait args;
4271     int ret;
4272
4273     memclear(args);
4274     args.handles = (intptr_t)handles;
4275     args.timeout_nsec = timeout_nsec;
4276     args.count_handles = num_handles;
4277     args.flags = flags;
4278
4279     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_WAIT, &args);
4280     if (ret < 0)
4281         return ret;
4282
4283     if (first_signaled)
4284         *first_signaled = args.first_signaled;
4285     return ret;
4286 }
4287
4288 int drmSyncobjReset(int fd, const uint32_t *handles, uint32_t handle_count)
4289 {
4290     struct drm_syncobj_array args;
4291     int ret;
4292
4293     memclear(args);
4294     args.handles = (uintptr_t)handles;
4295     args.count_handles = handle_count;
4296
4297     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_RESET, &args);
4298     return ret;
4299 }
4300
4301 int drmSyncobjSignal(int fd, const uint32_t *handles, uint32_t handle_count)
4302 {
4303     struct drm_syncobj_array args;
4304     int ret;
4305
4306     memclear(args);
4307     args.handles = (uintptr_t)handles;
4308     args.count_handles = handle_count;
4309
4310     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_SIGNAL, &args);
4311     return ret;
4312 }