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