libdrm: Add get_sysctl_pci_bus_info for FreeBSD
[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 static void
3124 get_pci_path(int maj, int min, char *pci_path)
3125 {
3126     char path[PATH_MAX + 1], *term;
3127
3128     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3129     if (!realpath(path, pci_path)) {
3130         strcpy(pci_path, path);
3131         return;
3132     }
3133
3134     term = strrchr(pci_path, '/');
3135     if (term && strncmp(term, "/virtio", 7) == 0)
3136         *term = 0;
3137 }
3138
3139 #ifdef __FreeBSD__
3140 static int get_sysctl_pci_bus_info(int maj, int min, drmPciBusInfoPtr info)
3141 {
3142     char dname[SPECNAMELEN];
3143     char sysctl_name[16];
3144     char sysctl_val[256];
3145     size_t sysctl_len;
3146     int id, type, nelem;
3147     unsigned int rdev, majmin, domain, bus, dev, func;
3148
3149     rdev = makedev(maj, min);
3150     if (!devname_r(rdev, S_IFCHR, dname, sizeof(dname)))
3151       return -EINVAL;
3152
3153     if (sscanf(dname, "drm/%d\n", &id) != 1)
3154         return -EINVAL;
3155     type = drmGetMinorType(maj, min);
3156     if (type == -1)
3157         return -EINVAL;
3158
3159     /* BUG: This above section is iffy, since it mandates that a driver will
3160      * create both card and render node.
3161      * If it does not, the next DRM device will create card#X and
3162      * renderD#(128+X)-1.
3163      * This is a possibility in FreeBSD but for now there is no good way for
3164      * obtaining the info.
3165      */
3166     switch (type) {
3167     case DRM_NODE_PRIMARY:
3168          break;
3169     case DRM_NODE_CONTROL:
3170          id -= 64;
3171          break;
3172     case DRM_NODE_RENDER:
3173          id -= 128;
3174           break;
3175     }
3176     if (id < 0)
3177         return -EINVAL;
3178
3179     if (snprintf(sysctl_name, sizeof(sysctl_name), "hw.dri.%d.busid", id) <= 0)
3180       return -EINVAL;
3181     sysctl_len = sizeof(sysctl_val);
3182     if (sysctlbyname(sysctl_name, sysctl_val, &sysctl_len, NULL, 0))
3183       return -EINVAL;
3184
3185     #define bus_fmt "pci:%04x:%02x:%02x.%u"
3186
3187     nelem = sscanf(sysctl_val, bus_fmt, &domain, &bus, &dev, &func);
3188     if (nelem != 4)
3189       return -EINVAL;
3190     info->domain = domain;
3191     info->bus = bus;
3192     info->dev = dev;
3193     info->func = func;
3194
3195     return 0;
3196 }
3197 #endif
3198
3199 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
3200 {
3201 #ifdef __linux__
3202     unsigned int domain, bus, dev, func;
3203     char pci_path[PATH_MAX + 1], *value;
3204     int num;
3205
3206     get_pci_path(maj, min, pci_path);
3207
3208     value = sysfs_uevent_get(pci_path, "PCI_SLOT_NAME");
3209     if (!value)
3210         return -ENOENT;
3211
3212     num = sscanf(value, "%04x:%02x:%02x.%1u", &domain, &bus, &dev, &func);
3213     free(value);
3214
3215     if (num != 4)
3216         return -EINVAL;
3217
3218     info->domain = domain;
3219     info->bus = bus;
3220     info->dev = dev;
3221     info->func = func;
3222
3223     return 0;
3224 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3225     struct drm_pciinfo pinfo;
3226     int fd, type;
3227
3228     type = drmGetMinorType(maj, min);
3229     if (type == -1)
3230         return -ENODEV;
3231
3232     fd = drmOpenMinor(min, 0, type);
3233     if (fd < 0)
3234         return -errno;
3235
3236     if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3237         close(fd);
3238         return -errno;
3239     }
3240     close(fd);
3241
3242     info->domain = pinfo.domain;
3243     info->bus = pinfo.bus;
3244     info->dev = pinfo.dev;
3245     info->func = pinfo.func;
3246
3247     return 0;
3248 #elif __FreeBSD__
3249     return get_sysctl_pci_bus_info(maj, min, info);
3250 #else
3251 #warning "Missing implementation of drmParsePciBusInfo"
3252     return -EINVAL;
3253 #endif
3254 }
3255
3256 drm_public int drmDevicesEqual(drmDevicePtr a, drmDevicePtr b)
3257 {
3258     if (a == NULL || b == NULL)
3259         return 0;
3260
3261     if (a->bustype != b->bustype)
3262         return 0;
3263
3264     switch (a->bustype) {
3265     case DRM_BUS_PCI:
3266         return memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo)) == 0;
3267
3268     case DRM_BUS_USB:
3269         return memcmp(a->businfo.usb, b->businfo.usb, sizeof(drmUsbBusInfo)) == 0;
3270
3271     case DRM_BUS_PLATFORM:
3272         return memcmp(a->businfo.platform, b->businfo.platform, sizeof(drmPlatformBusInfo)) == 0;
3273
3274     case DRM_BUS_HOST1X:
3275         return memcmp(a->businfo.host1x, b->businfo.host1x, sizeof(drmHost1xBusInfo)) == 0;
3276
3277     default:
3278         break;
3279     }
3280
3281     return 0;
3282 }
3283
3284 static int drmGetNodeType(const char *name)
3285 {
3286     if (strncmp(name, DRM_CONTROL_MINOR_NAME,
3287         sizeof(DRM_CONTROL_MINOR_NAME ) - 1) == 0)
3288         return DRM_NODE_CONTROL;
3289
3290     if (strncmp(name, DRM_RENDER_MINOR_NAME,
3291         sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
3292         return DRM_NODE_RENDER;
3293
3294     if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
3295         sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
3296         return DRM_NODE_PRIMARY;
3297
3298     return -EINVAL;
3299 }
3300
3301 static int drmGetMaxNodeName(void)
3302 {
3303     return sizeof(DRM_DIR_NAME) +
3304            MAX3(sizeof(DRM_PRIMARY_MINOR_NAME),
3305                 sizeof(DRM_CONTROL_MINOR_NAME),
3306                 sizeof(DRM_RENDER_MINOR_NAME)) +
3307            3 /* length of the node number */;
3308 }
3309
3310 #ifdef __linux__
3311 static int parse_separate_sysfs_files(int maj, int min,
3312                                       drmPciDeviceInfoPtr device,
3313                                       bool ignore_revision)
3314 {
3315     static const char *attrs[] = {
3316       "revision", /* Older kernels are missing the file, so check for it first */
3317       "vendor",
3318       "device",
3319       "subsystem_vendor",
3320       "subsystem_device",
3321     };
3322     char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3323     unsigned int data[ARRAY_SIZE(attrs)];
3324     FILE *fp;
3325     int ret;
3326
3327     get_pci_path(maj, min, pci_path);
3328
3329     for (unsigned i = ignore_revision ? 1 : 0; i < ARRAY_SIZE(attrs); i++) {
3330         snprintf(path, PATH_MAX, "%s/%s", pci_path, attrs[i]);
3331         fp = fopen(path, "r");
3332         if (!fp)
3333             return -errno;
3334
3335         ret = fscanf(fp, "%x", &data[i]);
3336         fclose(fp);
3337         if (ret != 1)
3338             return -errno;
3339
3340     }
3341
3342     device->revision_id = ignore_revision ? 0xff : data[0] & 0xff;
3343     device->vendor_id = data[1] & 0xffff;
3344     device->device_id = data[2] & 0xffff;
3345     device->subvendor_id = data[3] & 0xffff;
3346     device->subdevice_id = data[4] & 0xffff;
3347
3348     return 0;
3349 }
3350
3351 static int parse_config_sysfs_file(int maj, int min,
3352                                    drmPciDeviceInfoPtr device)
3353 {
3354     char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3355     unsigned char config[64];
3356     int fd, ret;
3357
3358     get_pci_path(maj, min, pci_path);
3359
3360     snprintf(path, PATH_MAX, "%s/config", pci_path);
3361     fd = open(path, O_RDONLY);
3362     if (fd < 0)
3363         return -errno;
3364
3365     ret = read(fd, config, sizeof(config));
3366     close(fd);
3367     if (ret < 0)
3368         return -errno;
3369
3370     device->vendor_id = config[0] | (config[1] << 8);
3371     device->device_id = config[2] | (config[3] << 8);
3372     device->revision_id = config[8];
3373     device->subvendor_id = config[44] | (config[45] << 8);
3374     device->subdevice_id = config[46] | (config[47] << 8);
3375
3376     return 0;
3377 }
3378 #endif
3379
3380 static int drmParsePciDeviceInfo(int maj, int min,
3381                                  drmPciDeviceInfoPtr device,
3382                                  uint32_t flags)
3383 {
3384 #ifdef __linux__
3385     if (!(flags & DRM_DEVICE_GET_PCI_REVISION))
3386         return parse_separate_sysfs_files(maj, min, device, true);
3387
3388     if (parse_separate_sysfs_files(maj, min, device, false))
3389         return parse_config_sysfs_file(maj, min, device);
3390
3391     return 0;
3392 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3393     struct drm_pciinfo pinfo;
3394     int fd, type;
3395
3396     type = drmGetMinorType(maj, min);
3397     if (type == -1)
3398         return -ENODEV;
3399
3400     fd = drmOpenMinor(min, 0, type);
3401     if (fd < 0)
3402         return -errno;
3403
3404     if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3405         close(fd);
3406         return -errno;
3407     }
3408     close(fd);
3409
3410     device->vendor_id = pinfo.vendor_id;
3411     device->device_id = pinfo.device_id;
3412     device->revision_id = pinfo.revision_id;
3413     device->subvendor_id = pinfo.subvendor_id;
3414     device->subdevice_id = pinfo.subdevice_id;
3415
3416     return 0;
3417 #else
3418 #warning "Missing implementation of drmParsePciDeviceInfo"
3419     return -EINVAL;
3420 #endif
3421 }
3422
3423 static void drmFreePlatformDevice(drmDevicePtr device)
3424 {
3425     if (device->deviceinfo.platform) {
3426         if (device->deviceinfo.platform->compatible) {
3427             char **compatible = device->deviceinfo.platform->compatible;
3428
3429             while (*compatible) {
3430                 free(*compatible);
3431                 compatible++;
3432             }
3433
3434             free(device->deviceinfo.platform->compatible);
3435         }
3436     }
3437 }
3438
3439 static void drmFreeHost1xDevice(drmDevicePtr device)
3440 {
3441     if (device->deviceinfo.host1x) {
3442         if (device->deviceinfo.host1x->compatible) {
3443             char **compatible = device->deviceinfo.host1x->compatible;
3444
3445             while (*compatible) {
3446                 free(*compatible);
3447                 compatible++;
3448             }
3449
3450             free(device->deviceinfo.host1x->compatible);
3451         }
3452     }
3453 }
3454
3455 drm_public void drmFreeDevice(drmDevicePtr *device)
3456 {
3457     if (device == NULL)
3458         return;
3459
3460     if (*device) {
3461         switch ((*device)->bustype) {
3462         case DRM_BUS_PLATFORM:
3463             drmFreePlatformDevice(*device);
3464             break;
3465
3466         case DRM_BUS_HOST1X:
3467             drmFreeHost1xDevice(*device);
3468             break;
3469         }
3470     }
3471
3472     free(*device);
3473     *device = NULL;
3474 }
3475
3476 drm_public void drmFreeDevices(drmDevicePtr devices[], int count)
3477 {
3478     int i;
3479
3480     if (devices == NULL)
3481         return;
3482
3483     for (i = 0; i < count; i++)
3484         if (devices[i])
3485             drmFreeDevice(&devices[i]);
3486 }
3487
3488 static drmDevicePtr drmDeviceAlloc(unsigned int type, const char *node,
3489                                    size_t bus_size, size_t device_size,
3490                                    char **ptrp)
3491 {
3492     size_t max_node_length, extra, size;
3493     drmDevicePtr device;
3494     unsigned int i;
3495     char *ptr;
3496
3497     max_node_length = ALIGN(drmGetMaxNodeName(), sizeof(void *));
3498     extra = DRM_NODE_MAX * (sizeof(void *) + max_node_length);
3499
3500     size = sizeof(*device) + extra + bus_size + device_size;
3501
3502     device = calloc(1, size);
3503     if (!device)
3504         return NULL;
3505
3506     device->available_nodes = 1 << type;
3507
3508     ptr = (char *)device + sizeof(*device);
3509     device->nodes = (char **)ptr;
3510
3511     ptr += DRM_NODE_MAX * sizeof(void *);
3512
3513     for (i = 0; i < DRM_NODE_MAX; i++) {
3514         device->nodes[i] = ptr;
3515         ptr += max_node_length;
3516     }
3517
3518     memcpy(device->nodes[type], node, max_node_length);
3519
3520     *ptrp = ptr;
3521
3522     return device;
3523 }
3524
3525 static int drmProcessPciDevice(drmDevicePtr *device,
3526                                const char *node, int node_type,
3527                                int maj, int min, bool fetch_deviceinfo,
3528                                uint32_t flags)
3529 {
3530     drmDevicePtr dev;
3531     char *addr;
3532     int ret;
3533
3534     dev = drmDeviceAlloc(node_type, node, sizeof(drmPciBusInfo),
3535                          sizeof(drmPciDeviceInfo), &addr);
3536     if (!dev)
3537         return -ENOMEM;
3538
3539     dev->bustype = DRM_BUS_PCI;
3540
3541     dev->businfo.pci = (drmPciBusInfoPtr)addr;
3542
3543     ret = drmParsePciBusInfo(maj, min, dev->businfo.pci);
3544     if (ret)
3545         goto free_device;
3546
3547     // Fetch the device info if the user has requested it
3548     if (fetch_deviceinfo) {
3549         addr += sizeof(drmPciBusInfo);
3550         dev->deviceinfo.pci = (drmPciDeviceInfoPtr)addr;
3551
3552         ret = drmParsePciDeviceInfo(maj, min, dev->deviceinfo.pci, flags);
3553         if (ret)
3554             goto free_device;
3555     }
3556
3557     *device = dev;
3558
3559     return 0;
3560
3561 free_device:
3562     free(dev);
3563     return ret;
3564 }
3565
3566 static int drmParseUsbBusInfo(int maj, int min, drmUsbBusInfoPtr info)
3567 {
3568 #ifdef __linux__
3569     char path[PATH_MAX + 1], *value;
3570     unsigned int bus, dev;
3571     int ret;
3572
3573     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3574
3575     value = sysfs_uevent_get(path, "BUSNUM");
3576     if (!value)
3577         return -ENOENT;
3578
3579     ret = sscanf(value, "%03u", &bus);
3580     free(value);
3581
3582     if (ret <= 0)
3583         return -errno;
3584
3585     value = sysfs_uevent_get(path, "DEVNUM");
3586     if (!value)
3587         return -ENOENT;
3588
3589     ret = sscanf(value, "%03u", &dev);
3590     free(value);
3591
3592     if (ret <= 0)
3593         return -errno;
3594
3595     info->bus = bus;
3596     info->dev = dev;
3597
3598     return 0;
3599 #else
3600 #warning "Missing implementation of drmParseUsbBusInfo"
3601     return -EINVAL;
3602 #endif
3603 }
3604
3605 static int drmParseUsbDeviceInfo(int maj, int min, drmUsbDeviceInfoPtr info)
3606 {
3607 #ifdef __linux__
3608     char path[PATH_MAX + 1], *value;
3609     unsigned int vendor, product;
3610     int ret;
3611
3612     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3613
3614     value = sysfs_uevent_get(path, "PRODUCT");
3615     if (!value)
3616         return -ENOENT;
3617
3618     ret = sscanf(value, "%x/%x", &vendor, &product);
3619     free(value);
3620
3621     if (ret <= 0)
3622         return -errno;
3623
3624     info->vendor = vendor;
3625     info->product = product;
3626
3627     return 0;
3628 #else
3629 #warning "Missing implementation of drmParseUsbDeviceInfo"
3630     return -EINVAL;
3631 #endif
3632 }
3633
3634 static int drmProcessUsbDevice(drmDevicePtr *device, const char *node,
3635                                int node_type, int maj, int min,
3636                                bool fetch_deviceinfo, uint32_t flags)
3637 {
3638     drmDevicePtr dev;
3639     char *ptr;
3640     int ret;
3641
3642     dev = drmDeviceAlloc(node_type, node, sizeof(drmUsbBusInfo),
3643                          sizeof(drmUsbDeviceInfo), &ptr);
3644     if (!dev)
3645         return -ENOMEM;
3646
3647     dev->bustype = DRM_BUS_USB;
3648
3649     dev->businfo.usb = (drmUsbBusInfoPtr)ptr;
3650
3651     ret = drmParseUsbBusInfo(maj, min, dev->businfo.usb);
3652     if (ret < 0)
3653         goto free_device;
3654
3655     if (fetch_deviceinfo) {
3656         ptr += sizeof(drmUsbBusInfo);
3657         dev->deviceinfo.usb = (drmUsbDeviceInfoPtr)ptr;
3658
3659         ret = drmParseUsbDeviceInfo(maj, min, dev->deviceinfo.usb);
3660         if (ret < 0)
3661             goto free_device;
3662     }
3663
3664     *device = dev;
3665
3666     return 0;
3667
3668 free_device:
3669     free(dev);
3670     return ret;
3671 }
3672
3673 static int drmParseOFBusInfo(int maj, int min, char *fullname)
3674 {
3675 #ifdef __linux__
3676     char path[PATH_MAX + 1], *name, *tmp_name;
3677
3678     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3679
3680     name = sysfs_uevent_get(path, "OF_FULLNAME");
3681     tmp_name = name;
3682     if (!name) {
3683         /* If the device lacks OF data, pick the MODALIAS info */
3684         name = sysfs_uevent_get(path, "MODALIAS");
3685         if (!name)
3686             return -ENOENT;
3687
3688         /* .. and strip the MODALIAS=[platform,usb...]: part. */
3689         tmp_name = strrchr(name, ':');
3690         if (!tmp_name) {
3691             free(name);
3692             return -ENOENT;
3693         }
3694         tmp_name++;
3695     }
3696
3697     strncpy(fullname, tmp_name, DRM_PLATFORM_DEVICE_NAME_LEN);
3698     fullname[DRM_PLATFORM_DEVICE_NAME_LEN - 1] = '\0';
3699     free(name);
3700
3701     return 0;
3702 #else
3703 #warning "Missing implementation of drmParseOFBusInfo"
3704     return -EINVAL;
3705 #endif
3706 }
3707
3708 static int drmParseOFDeviceInfo(int maj, int min, char ***compatible)
3709 {
3710 #ifdef __linux__
3711     char path[PATH_MAX + 1], *value, *tmp_name;
3712     unsigned int count, i;
3713     int err;
3714
3715     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3716
3717     value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
3718     if (value) {
3719         sscanf(value, "%u", &count);
3720         free(value);
3721     } else {
3722         /* Assume one entry if the device lack OF data */
3723         count = 1;
3724     }
3725
3726     *compatible = calloc(count + 1, sizeof(char *));
3727     if (!*compatible)
3728         return -ENOMEM;
3729
3730     for (i = 0; i < count; i++) {
3731         value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
3732         tmp_name = value;
3733         if (!value) {
3734             /* If the device lacks OF data, pick the MODALIAS info */
3735             value = sysfs_uevent_get(path, "MODALIAS");
3736             if (!value) {
3737                 err = -ENOENT;
3738                 goto free;
3739             }
3740
3741             /* .. and strip the MODALIAS=[platform,usb...]: part. */
3742             tmp_name = strrchr(value, ':');
3743             if (!tmp_name) {
3744                 free(value);
3745                 return -ENOENT;
3746             }
3747             tmp_name = strdup(tmp_name + 1);
3748             free(value);
3749         }
3750
3751         (*compatible)[i] = tmp_name;
3752     }
3753
3754     return 0;
3755
3756 free:
3757     while (i--)
3758         free((*compatible)[i]);
3759
3760     free(*compatible);
3761     return err;
3762 #else
3763 #warning "Missing implementation of drmParseOFDeviceInfo"
3764     return -EINVAL;
3765 #endif
3766 }
3767
3768 static int drmProcessPlatformDevice(drmDevicePtr *device,
3769                                     const char *node, int node_type,
3770                                     int maj, int min, bool fetch_deviceinfo,
3771                                     uint32_t flags)
3772 {
3773     drmDevicePtr dev;
3774     char *ptr;
3775     int ret;
3776
3777     dev = drmDeviceAlloc(node_type, node, sizeof(drmPlatformBusInfo),
3778                          sizeof(drmPlatformDeviceInfo), &ptr);
3779     if (!dev)
3780         return -ENOMEM;
3781
3782     dev->bustype = DRM_BUS_PLATFORM;
3783
3784     dev->businfo.platform = (drmPlatformBusInfoPtr)ptr;
3785
3786     ret = drmParseOFBusInfo(maj, min, dev->businfo.platform->fullname);
3787     if (ret < 0)
3788         goto free_device;
3789
3790     if (fetch_deviceinfo) {
3791         ptr += sizeof(drmPlatformBusInfo);
3792         dev->deviceinfo.platform = (drmPlatformDeviceInfoPtr)ptr;
3793
3794         ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.platform->compatible);
3795         if (ret < 0)
3796             goto free_device;
3797     }
3798
3799     *device = dev;
3800
3801     return 0;
3802
3803 free_device:
3804     free(dev);
3805     return ret;
3806 }
3807
3808 static int drmProcessHost1xDevice(drmDevicePtr *device,
3809                                   const char *node, int node_type,
3810                                   int maj, int min, bool fetch_deviceinfo,
3811                                   uint32_t flags)
3812 {
3813     drmDevicePtr dev;
3814     char *ptr;
3815     int ret;
3816
3817     dev = drmDeviceAlloc(node_type, node, sizeof(drmHost1xBusInfo),
3818                          sizeof(drmHost1xDeviceInfo), &ptr);
3819     if (!dev)
3820         return -ENOMEM;
3821
3822     dev->bustype = DRM_BUS_HOST1X;
3823
3824     dev->businfo.host1x = (drmHost1xBusInfoPtr)ptr;
3825
3826     ret = drmParseOFBusInfo(maj, min, dev->businfo.host1x->fullname);
3827     if (ret < 0)
3828         goto free_device;
3829
3830     if (fetch_deviceinfo) {
3831         ptr += sizeof(drmHost1xBusInfo);
3832         dev->deviceinfo.host1x = (drmHost1xDeviceInfoPtr)ptr;
3833
3834         ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.host1x->compatible);
3835         if (ret < 0)
3836             goto free_device;
3837     }
3838
3839     *device = dev;
3840
3841     return 0;
3842
3843 free_device:
3844     free(dev);
3845     return ret;
3846 }
3847
3848 static int
3849 process_device(drmDevicePtr *device, const char *d_name,
3850                int req_subsystem_type,
3851                bool fetch_deviceinfo, uint32_t flags)
3852 {
3853     struct stat sbuf;
3854     char node[PATH_MAX + 1];
3855     int node_type, subsystem_type;
3856     unsigned int maj, min;
3857
3858     node_type = drmGetNodeType(d_name);
3859     if (node_type < 0)
3860         return -1;
3861
3862     snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, d_name);
3863     if (stat(node, &sbuf))
3864         return -1;
3865
3866     maj = major(sbuf.st_rdev);
3867     min = minor(sbuf.st_rdev);
3868
3869     if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3870         return -1;
3871
3872     subsystem_type = drmParseSubsystemType(maj, min);
3873     if (req_subsystem_type != -1 && req_subsystem_type != subsystem_type)
3874         return -1;
3875
3876     switch (subsystem_type) {
3877     case DRM_BUS_PCI:
3878         return drmProcessPciDevice(device, node, node_type, maj, min,
3879                                    fetch_deviceinfo, flags);
3880     case DRM_BUS_USB:
3881         return drmProcessUsbDevice(device, node, node_type, maj, min,
3882                                    fetch_deviceinfo, flags);
3883     case DRM_BUS_PLATFORM:
3884         return drmProcessPlatformDevice(device, node, node_type, maj, min,
3885                                         fetch_deviceinfo, flags);
3886     case DRM_BUS_HOST1X:
3887         return drmProcessHost1xDevice(device, node, node_type, maj, min,
3888                                       fetch_deviceinfo, flags);
3889     default:
3890         return -1;
3891    }
3892 }
3893
3894 /* Consider devices located on the same bus as duplicate and fold the respective
3895  * entries into a single one.
3896  *
3897  * Note: this leaves "gaps" in the array, while preserving the length.
3898  */
3899 static void drmFoldDuplicatedDevices(drmDevicePtr local_devices[], int count)
3900 {
3901     int node_type, i, j;
3902
3903     for (i = 0; i < count; i++) {
3904         for (j = i + 1; j < count; j++) {
3905             if (drmDevicesEqual(local_devices[i], local_devices[j])) {
3906                 local_devices[i]->available_nodes |= local_devices[j]->available_nodes;
3907                 node_type = log2(local_devices[j]->available_nodes);
3908                 memcpy(local_devices[i]->nodes[node_type],
3909                        local_devices[j]->nodes[node_type], drmGetMaxNodeName());
3910                 drmFreeDevice(&local_devices[j]);
3911             }
3912         }
3913     }
3914 }
3915
3916 /* Check that the given flags are valid returning 0 on success */
3917 static int
3918 drm_device_validate_flags(uint32_t flags)
3919 {
3920         return (flags & ~DRM_DEVICE_GET_PCI_REVISION);
3921 }
3922
3923 static bool
3924 drm_device_has_rdev(drmDevicePtr device, dev_t find_rdev)
3925 {
3926     struct stat sbuf;
3927
3928     for (int i = 0; i < DRM_NODE_MAX; i++) {
3929         if (device->available_nodes & 1 << i) {
3930             if (stat(device->nodes[i], &sbuf) == 0 &&
3931                 sbuf.st_rdev == find_rdev)
3932                 return true;
3933         }
3934     }
3935     return false;
3936 }
3937
3938 /*
3939  * The kernel drm core has a number of places that assume maximum of
3940  * 3x64 devices nodes. That's 64 for each of primary, control and
3941  * render nodes. Rounded it up to 256 for simplicity.
3942  */
3943 #define MAX_DRM_NODES 256
3944
3945 /**
3946  * Get information about the opened drm device
3947  *
3948  * \param fd file descriptor of the drm device
3949  * \param flags feature/behaviour bitmask
3950  * \param device the address of a drmDevicePtr where the information
3951  *               will be allocated in stored
3952  *
3953  * \return zero on success, negative error code otherwise.
3954  *
3955  * \note Unlike drmGetDevice it does not retrieve the pci device revision field
3956  * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
3957  */
3958 drm_public int drmGetDevice2(int fd, uint32_t flags, drmDevicePtr *device)
3959 {
3960 #ifdef __OpenBSD__
3961     /*
3962      * DRI device nodes on OpenBSD are not in their own directory, they reside
3963      * in /dev along with a large number of statically generated /dev nodes.
3964      * Avoid stat'ing all of /dev needlessly by implementing this custom path.
3965      */
3966     drmDevicePtr     d;
3967     struct stat      sbuf;
3968     char             node[PATH_MAX + 1];
3969     const char      *dev_name;
3970     int              node_type, subsystem_type;
3971     int              maj, min, n, ret;
3972
3973     if (fd == -1 || device == NULL)
3974         return -EINVAL;
3975
3976     if (fstat(fd, &sbuf))
3977         return -errno;
3978
3979     maj = major(sbuf.st_rdev);
3980     min = minor(sbuf.st_rdev);
3981
3982     if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3983         return -EINVAL;
3984
3985     node_type = drmGetMinorType(maj, min);
3986     if (node_type == -1)
3987         return -ENODEV;
3988
3989     dev_name = drmGetDeviceName(node_type);
3990     if (!dev_name)
3991         return -EINVAL;
3992
3993     n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min);
3994     if (n == -1 || n >= PATH_MAX)
3995       return -errno;
3996     if (stat(node, &sbuf))
3997         return -EINVAL;
3998
3999     subsystem_type = drmParseSubsystemType(maj, min);
4000     if (subsystem_type != DRM_BUS_PCI)
4001         return -ENODEV;
4002
4003     ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
4004     if (ret)
4005         return ret;
4006
4007     *device = d;
4008
4009     return 0;
4010 #else
4011     drmDevicePtr local_devices[MAX_DRM_NODES];
4012     drmDevicePtr d;
4013     DIR *sysdir;
4014     struct dirent *dent;
4015     struct stat sbuf;
4016     int subsystem_type;
4017     int maj, min;
4018     int ret, i, node_count;
4019     dev_t find_rdev;
4020
4021     if (drm_device_validate_flags(flags))
4022         return -EINVAL;
4023
4024     if (fd == -1 || device == NULL)
4025         return -EINVAL;
4026
4027     if (fstat(fd, &sbuf))
4028         return -errno;
4029
4030     find_rdev = sbuf.st_rdev;
4031     maj = major(sbuf.st_rdev);
4032     min = minor(sbuf.st_rdev);
4033
4034     if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4035         return -EINVAL;
4036
4037     subsystem_type = drmParseSubsystemType(maj, min);
4038     if (subsystem_type < 0)
4039         return subsystem_type;
4040
4041     sysdir = opendir(DRM_DIR_NAME);
4042     if (!sysdir)
4043         return -errno;
4044
4045     i = 0;
4046     while ((dent = readdir(sysdir))) {
4047         ret = process_device(&d, dent->d_name, subsystem_type, true, flags);
4048         if (ret)
4049             continue;
4050
4051         if (i >= MAX_DRM_NODES) {
4052             fprintf(stderr, "More than %d drm nodes detected. "
4053                     "Please report a bug - that should not happen.\n"
4054                     "Skipping extra nodes\n", MAX_DRM_NODES);
4055             break;
4056         }
4057         local_devices[i] = d;
4058         i++;
4059     }
4060     node_count = i;
4061
4062     drmFoldDuplicatedDevices(local_devices, node_count);
4063
4064     *device = NULL;
4065
4066     for (i = 0; i < node_count; i++) {
4067         if (!local_devices[i])
4068             continue;
4069
4070         if (drm_device_has_rdev(local_devices[i], find_rdev))
4071             *device = local_devices[i];
4072         else
4073             drmFreeDevice(&local_devices[i]);
4074     }
4075
4076     closedir(sysdir);
4077     if (*device == NULL)
4078         return -ENODEV;
4079     return 0;
4080 #endif
4081 }
4082
4083 /**
4084  * Get information about the opened drm device
4085  *
4086  * \param fd file descriptor of the drm device
4087  * \param device the address of a drmDevicePtr where the information
4088  *               will be allocated in stored
4089  *
4090  * \return zero on success, negative error code otherwise.
4091  */
4092 drm_public int drmGetDevice(int fd, drmDevicePtr *device)
4093 {
4094     return drmGetDevice2(fd, DRM_DEVICE_GET_PCI_REVISION, device);
4095 }
4096
4097 /**
4098  * Get drm devices on the system
4099  *
4100  * \param flags feature/behaviour bitmask
4101  * \param devices the array of devices with drmDevicePtr elements
4102  *                can be NULL to get the device number first
4103  * \param max_devices the maximum number of devices for the array
4104  *
4105  * \return on error - negative error code,
4106  *         if devices is NULL - total number of devices available on the system,
4107  *         alternatively the number of devices stored in devices[], which is
4108  *         capped by the max_devices.
4109  *
4110  * \note Unlike drmGetDevices it does not retrieve the pci device revision field
4111  * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
4112  */
4113 drm_public int drmGetDevices2(uint32_t flags, drmDevicePtr devices[],
4114                               int max_devices)
4115 {
4116     drmDevicePtr local_devices[MAX_DRM_NODES];
4117     drmDevicePtr device;
4118     DIR *sysdir;
4119     struct dirent *dent;
4120     int ret, i, node_count, device_count;
4121
4122     if (drm_device_validate_flags(flags))
4123         return -EINVAL;
4124
4125     sysdir = opendir(DRM_DIR_NAME);
4126     if (!sysdir)
4127         return -errno;
4128
4129     i = 0;
4130     while ((dent = readdir(sysdir))) {
4131         ret = process_device(&device, dent->d_name, -1, devices != NULL, flags);
4132         if (ret)
4133             continue;
4134
4135         if (i >= MAX_DRM_NODES) {
4136             fprintf(stderr, "More than %d drm nodes detected. "
4137                     "Please report a bug - that should not happen.\n"
4138                     "Skipping extra nodes\n", MAX_DRM_NODES);
4139             break;
4140         }
4141         local_devices[i] = device;
4142         i++;
4143     }
4144     node_count = i;
4145
4146     drmFoldDuplicatedDevices(local_devices, node_count);
4147
4148     device_count = 0;
4149     for (i = 0; i < node_count; i++) {
4150         if (!local_devices[i])
4151             continue;
4152
4153         if ((devices != NULL) && (device_count < max_devices))
4154             devices[device_count] = local_devices[i];
4155         else
4156             drmFreeDevice(&local_devices[i]);
4157
4158         device_count++;
4159     }
4160
4161     closedir(sysdir);
4162     return device_count;
4163 }
4164
4165 /**
4166  * Get drm devices on the system
4167  *
4168  * \param devices the array of devices with drmDevicePtr elements
4169  *                can be NULL to get the device number first
4170  * \param max_devices the maximum number of devices for the array
4171  *
4172  * \return on error - negative error code,
4173  *         if devices is NULL - total number of devices available on the system,
4174  *         alternatively the number of devices stored in devices[], which is
4175  *         capped by the max_devices.
4176  */
4177 drm_public int drmGetDevices(drmDevicePtr devices[], int max_devices)
4178 {
4179     return drmGetDevices2(DRM_DEVICE_GET_PCI_REVISION, devices, max_devices);
4180 }
4181
4182 drm_public char *drmGetDeviceNameFromFd2(int fd)
4183 {
4184 #ifdef __linux__
4185     struct stat sbuf;
4186     char path[PATH_MAX + 1], *value;
4187     unsigned int maj, min;
4188
4189     if (fstat(fd, &sbuf))
4190         return NULL;
4191
4192     maj = major(sbuf.st_rdev);
4193     min = minor(sbuf.st_rdev);
4194
4195     if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4196         return NULL;
4197
4198     snprintf(path, sizeof(path), "/sys/dev/char/%d:%d", maj, min);
4199
4200     value = sysfs_uevent_get(path, "DEVNAME");
4201     if (!value)
4202         return NULL;
4203
4204     snprintf(path, sizeof(path), "/dev/%s", value);
4205     free(value);
4206
4207     return strdup(path);
4208 #elif __FreeBSD__
4209     return drmGetDeviceNameFromFd(fd);
4210 #else
4211     struct stat      sbuf;
4212     char             node[PATH_MAX + 1];
4213     const char      *dev_name;
4214     int              node_type;
4215     int              maj, min, n;
4216
4217     if (fstat(fd, &sbuf))
4218         return NULL;
4219
4220     maj = major(sbuf.st_rdev);
4221     min = minor(sbuf.st_rdev);
4222
4223     if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4224         return NULL;
4225
4226     node_type = drmGetMinorType(maj, min);
4227     if (node_type == -1)
4228         return NULL;
4229
4230     dev_name = drmGetDeviceName(node_type);
4231     if (!dev_name)
4232         return NULL;
4233
4234     n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min);
4235     if (n == -1 || n >= PATH_MAX)
4236       return NULL;
4237
4238     return strdup(node);
4239 #endif
4240 }
4241
4242 drm_public int drmSyncobjCreate(int fd, uint32_t flags, uint32_t *handle)
4243 {
4244     struct drm_syncobj_create args;
4245     int ret;
4246
4247     memclear(args);
4248     args.flags = flags;
4249     args.handle = 0;
4250     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_CREATE, &args);
4251     if (ret)
4252         return ret;
4253     *handle = args.handle;
4254     return 0;
4255 }
4256
4257 drm_public int drmSyncobjDestroy(int fd, uint32_t handle)
4258 {
4259     struct drm_syncobj_destroy args;
4260
4261     memclear(args);
4262     args.handle = handle;
4263     return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_DESTROY, &args);
4264 }
4265
4266 drm_public int drmSyncobjHandleToFD(int fd, uint32_t handle, int *obj_fd)
4267 {
4268     struct drm_syncobj_handle args;
4269     int ret;
4270
4271     memclear(args);
4272     args.fd = -1;
4273     args.handle = handle;
4274     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4275     if (ret)
4276         return ret;
4277     *obj_fd = args.fd;
4278     return 0;
4279 }
4280
4281 drm_public int drmSyncobjFDToHandle(int fd, int obj_fd, uint32_t *handle)
4282 {
4283     struct drm_syncobj_handle args;
4284     int ret;
4285
4286     memclear(args);
4287     args.fd = obj_fd;
4288     args.handle = 0;
4289     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4290     if (ret)
4291         return ret;
4292     *handle = args.handle;
4293     return 0;
4294 }
4295
4296 drm_public int drmSyncobjImportSyncFile(int fd, uint32_t handle,
4297                                         int sync_file_fd)
4298 {
4299     struct drm_syncobj_handle args;
4300
4301     memclear(args);
4302     args.fd = sync_file_fd;
4303     args.handle = handle;
4304     args.flags = DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE;
4305     return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4306 }
4307
4308 drm_public int drmSyncobjExportSyncFile(int fd, uint32_t handle,
4309                                         int *sync_file_fd)
4310 {
4311     struct drm_syncobj_handle args;
4312     int ret;
4313
4314     memclear(args);
4315     args.fd = -1;
4316     args.handle = handle;
4317     args.flags = DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE;
4318     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4319     if (ret)
4320         return ret;
4321     *sync_file_fd = args.fd;
4322     return 0;
4323 }
4324
4325 drm_public int drmSyncobjWait(int fd, uint32_t *handles, unsigned num_handles,
4326                               int64_t timeout_nsec, unsigned flags,
4327                               uint32_t *first_signaled)
4328 {
4329     struct drm_syncobj_wait args;
4330     int ret;
4331
4332     memclear(args);
4333     args.handles = (uintptr_t)handles;
4334     args.timeout_nsec = timeout_nsec;
4335     args.count_handles = num_handles;
4336     args.flags = flags;
4337
4338     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_WAIT, &args);
4339     if (ret < 0)
4340         return -errno;
4341
4342     if (first_signaled)
4343         *first_signaled = args.first_signaled;
4344     return ret;
4345 }
4346
4347 drm_public int drmSyncobjReset(int fd, const uint32_t *handles,
4348                                uint32_t handle_count)
4349 {
4350     struct drm_syncobj_array args;
4351     int ret;
4352
4353     memclear(args);
4354     args.handles = (uintptr_t)handles;
4355     args.count_handles = handle_count;
4356
4357     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_RESET, &args);
4358     return ret;
4359 }
4360
4361 drm_public int drmSyncobjSignal(int fd, const uint32_t *handles,
4362                                 uint32_t handle_count)
4363 {
4364     struct drm_syncobj_array args;
4365     int ret;
4366
4367     memclear(args);
4368     args.handles = (uintptr_t)handles;
4369     args.count_handles = handle_count;
4370
4371     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_SIGNAL, &args);
4372     return ret;
4373 }
4374
4375 drm_public int drmSyncobjTimelineSignal(int fd, const uint32_t *handles,
4376                                         uint64_t *points, uint32_t handle_count)
4377 {
4378     struct drm_syncobj_timeline_array args;
4379     int ret;
4380
4381     memclear(args);
4382     args.handles = (uintptr_t)handles;
4383     args.points = (uintptr_t)points;
4384     args.count_handles = handle_count;
4385
4386     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TIMELINE_SIGNAL, &args);
4387     return ret;
4388 }
4389
4390 drm_public int drmSyncobjTimelineWait(int fd, uint32_t *handles, uint64_t *points,
4391                                       unsigned num_handles,
4392                                       int64_t timeout_nsec, unsigned flags,
4393                                       uint32_t *first_signaled)
4394 {
4395     struct drm_syncobj_timeline_wait args;
4396     int ret;
4397
4398     memclear(args);
4399     args.handles = (uintptr_t)handles;
4400     args.points = (uintptr_t)points;
4401     args.timeout_nsec = timeout_nsec;
4402     args.count_handles = num_handles;
4403     args.flags = flags;
4404
4405     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TIMELINE_WAIT, &args);
4406     if (ret < 0)
4407         return -errno;
4408
4409     if (first_signaled)
4410         *first_signaled = args.first_signaled;
4411     return ret;
4412 }
4413
4414
4415 drm_public int drmSyncobjQuery(int fd, uint32_t *handles, uint64_t *points,
4416                                uint32_t handle_count)
4417 {
4418     struct drm_syncobj_timeline_array args;
4419     int ret;
4420
4421     memclear(args);
4422     args.handles = (uintptr_t)handles;
4423     args.points = (uintptr_t)points;
4424     args.count_handles = handle_count;
4425
4426     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_QUERY, &args);
4427     if (ret)
4428         return ret;
4429     return 0;
4430 }
4431
4432 drm_public int drmSyncobjQuery2(int fd, uint32_t *handles, uint64_t *points,
4433                                 uint32_t handle_count, uint32_t flags)
4434 {
4435     struct drm_syncobj_timeline_array args;
4436
4437     memclear(args);
4438     args.handles = (uintptr_t)handles;
4439     args.points = (uintptr_t)points;
4440     args.count_handles = handle_count;
4441     args.flags = flags;
4442
4443     return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_QUERY, &args);
4444 }
4445
4446
4447 drm_public int drmSyncobjTransfer(int fd,
4448                                   uint32_t dst_handle, uint64_t dst_point,
4449                                   uint32_t src_handle, uint64_t src_point,
4450                                   uint32_t flags)
4451 {
4452     struct drm_syncobj_transfer args;
4453     int ret;
4454
4455     memclear(args);
4456     args.src_handle = src_handle;
4457     args.dst_handle = dst_handle;
4458     args.src_point = src_point;
4459     args.dst_point = dst_point;
4460     args.flags = flags;
4461
4462     ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TRANSFER, &args);
4463
4464     return ret;
4465 }