OSDN Git Service

e99f2e2de18ce3b9c3035e7f8a8b90e3b0d897a6
[android-x86/external-libdrm.git] / xf86drm.c
1 /**
2  * \file xf86drm.c
3  * User-level interface to DRM device
4  *
5  * \author Rickard E. (Rik) Faith <faith@valinux.com>
6  * \author Kevin E. Martin <martin@valinux.com>
7  */
8
9 /*
10  * Copyright 1999 Precision Insight, Inc., Cedar Park, Texas.
11  * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California.
12  * All Rights Reserved.
13  *
14  * Permission is hereby granted, free of charge, to any person obtaining a
15  * copy of this software and associated documentation files (the "Software"),
16  * to deal in the Software without restriction, including without limitation
17  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
18  * and/or sell copies of the Software, and to permit persons to whom the
19  * Software is furnished to do so, subject to the following conditions:
20  *
21  * The above copyright notice and this permission notice (including the next
22  * paragraph) shall be included in all copies or substantial portions of the
23  * Software.
24  *
25  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
28  * PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
29  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
30  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
31  * DEALINGS IN THE SOFTWARE.
32  */
33
34 #ifdef HAVE_CONFIG_H
35 # include <config.h>
36 #endif
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <stdbool.h>
40 #include <unistd.h>
41 #include <string.h>
42 #include <strings.h>
43 #include <ctype.h>
44 #include <dirent.h>
45 #include <stddef.h>
46 #include <fcntl.h>
47 #include <errno.h>
48 #include <limits.h>
49 #include <signal.h>
50 #include <time.h>
51 #include <sys/types.h>
52 #include <sys/stat.h>
53 #define stat_t struct stat
54 #include <sys/ioctl.h>
55 #include <sys/time.h>
56 #include <stdarg.h>
57 #ifdef HAVE_SYS_MKDEV_H
58 # include <sys/mkdev.h> /* defines major(), minor(), and makedev() on Solaris */
59 #endif
60 #include <math.h>
61
62 /* Not all systems have MAP_FAILED defined */
63 #ifndef MAP_FAILED
64 #define MAP_FAILED ((void *)-1)
65 #endif
66
67 #include "xf86drm.h"
68 #include "libdrm_macros.h"
69
70 #include "util_math.h"
71
72 #ifdef __OpenBSD__
73 #define DRM_PRIMARY_MINOR_NAME  "drm"
74 #define DRM_CONTROL_MINOR_NAME  "drmC"
75 #define DRM_RENDER_MINOR_NAME   "drmR"
76 #else
77 #define DRM_PRIMARY_MINOR_NAME  "card"
78 #define DRM_CONTROL_MINOR_NAME  "controlD"
79 #define DRM_RENDER_MINOR_NAME   "renderD"
80 #endif
81
82 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
83 #define DRM_MAJOR 145
84 #endif
85
86 #ifdef __NetBSD__
87 #define DRM_MAJOR 34
88 #endif
89
90 #ifdef __OpenBSD__
91 #ifdef __i386__
92 #define DRM_MAJOR 88
93 #else
94 #define DRM_MAJOR 87
95 #endif
96 #endif /* __OpenBSD__ */
97
98 #ifndef DRM_MAJOR
99 #define DRM_MAJOR 226 /* Linux */
100 #endif
101
102 #define DRM_MSG_VERBOSITY 3
103
104 #define memclear(s) memset(&s, 0, sizeof(s))
105
106 static drmServerInfoPtr drm_server_info;
107
108 void drmSetServerInfo(drmServerInfoPtr info)
109 {
110     drm_server_info = info;
111 }
112
113 /**
114  * Output a message to stderr.
115  *
116  * \param format printf() like format string.
117  *
118  * \internal
119  * This function is a wrapper around vfprintf().
120  */
121
122 static int DRM_PRINTFLIKE(1, 0)
123 drmDebugPrint(const char *format, va_list ap)
124 {
125     return vfprintf(stderr, format, ap);
126 }
127
128 void
129 drmMsg(const char *format, ...)
130 {
131     va_list ap;
132     const char *env;
133     if (((env = getenv("LIBGL_DEBUG")) && strstr(env, "verbose")) ||
134         (drm_server_info && drm_server_info->debug_print))
135     {
136         va_start(ap, format);
137         if (drm_server_info) {
138             drm_server_info->debug_print(format,ap);
139         } else {
140             drmDebugPrint(format, ap);
141         }
142         va_end(ap);
143     }
144 }
145
146 static void *drmHashTable = NULL; /* Context switch callbacks */
147
148 void *drmGetHashTable(void)
149 {
150     return drmHashTable;
151 }
152
153 void *drmMalloc(int size)
154 {
155     return calloc(1, size);
156 }
157
158 void drmFree(void *pt)
159 {
160     free(pt);
161 }
162
163 /**
164  * Call ioctl, restarting if it is interupted
165  */
166 int
167 drmIoctl(int fd, unsigned long request, void *arg)
168 {
169     int ret;
170
171     do {
172         ret = ioctl(fd, request, arg);
173     } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
174     return ret;
175 }
176
177 static unsigned long drmGetKeyFromFd(int fd)
178 {
179     stat_t     st;
180
181     st.st_rdev = 0;
182     fstat(fd, &st);
183     return st.st_rdev;
184 }
185
186 drmHashEntry *drmGetEntry(int fd)
187 {
188     unsigned long key = drmGetKeyFromFd(fd);
189     void          *value;
190     drmHashEntry  *entry;
191
192     if (!drmHashTable)
193         drmHashTable = drmHashCreate();
194
195     if (drmHashLookup(drmHashTable, key, &value)) {
196         entry           = drmMalloc(sizeof(*entry));
197         entry->fd       = fd;
198         entry->f        = NULL;
199         entry->tagTable = drmHashCreate();
200         drmHashInsert(drmHashTable, key, entry);
201     } else {
202         entry = value;
203     }
204     return entry;
205 }
206
207 /**
208  * Compare two busid strings
209  *
210  * \param first
211  * \param second
212  *
213  * \return 1 if matched.
214  *
215  * \internal
216  * This function compares two bus ID strings.  It understands the older
217  * PCI:b:d:f format and the newer pci:oooo:bb:dd.f format.  In the format, o is
218  * domain, b is bus, d is device, f is function.
219  */
220 static int drmMatchBusID(const char *id1, const char *id2, int pci_domain_ok)
221 {
222     /* First, check if the IDs are exactly the same */
223     if (strcasecmp(id1, id2) == 0)
224         return 1;
225
226     /* Try to match old/new-style PCI bus IDs. */
227     if (strncasecmp(id1, "pci", 3) == 0) {
228         unsigned int o1, b1, d1, f1;
229         unsigned int o2, b2, d2, f2;
230         int ret;
231
232         ret = sscanf(id1, "pci:%04x:%02x:%02x.%u", &o1, &b1, &d1, &f1);
233         if (ret != 4) {
234             o1 = 0;
235             ret = sscanf(id1, "PCI:%u:%u:%u", &b1, &d1, &f1);
236             if (ret != 3)
237                 return 0;
238         }
239
240         ret = sscanf(id2, "pci:%04x:%02x:%02x.%u", &o2, &b2, &d2, &f2);
241         if (ret != 4) {
242             o2 = 0;
243             ret = sscanf(id2, "PCI:%u:%u:%u", &b2, &d2, &f2);
244             if (ret != 3)
245                 return 0;
246         }
247
248         /* If domains aren't properly supported by the kernel interface,
249          * just ignore them, which sucks less than picking a totally random
250          * card with "open by name"
251          */
252         if (!pci_domain_ok)
253             o1 = o2 = 0;
254
255         if ((o1 != o2) || (b1 != b2) || (d1 != d2) || (f1 != f2))
256             return 0;
257         else
258             return 1;
259     }
260     return 0;
261 }
262
263 /**
264  * Handles error checking for chown call.
265  *
266  * \param path to file.
267  * \param id of the new owner.
268  * \param id of the new group.
269  *
270  * \return zero if success or -1 if failure.
271  *
272  * \internal
273  * Checks for failure. If failure was caused by signal call chown again.
274  * If any other failure happened then it will output error mesage using
275  * drmMsg() call.
276  */
277 #if !defined(UDEV)
278 static int chown_check_return(const char *path, uid_t owner, gid_t group)
279 {
280         int rv;
281
282         do {
283             rv = chown(path, owner, group);
284         } while (rv != 0 && errno == EINTR);
285
286         if (rv == 0)
287             return 0;
288
289         drmMsg("Failed to change owner or group for file %s! %d: %s\n",
290                path, errno, strerror(errno));
291         return -1;
292 }
293 #endif
294
295 /**
296  * Open the DRM device, creating it if necessary.
297  *
298  * \param dev major and minor numbers of the device.
299  * \param minor minor number of the device.
300  *
301  * \return a file descriptor on success, or a negative value on error.
302  *
303  * \internal
304  * Assembles the device name from \p minor and opens it, creating the device
305  * special file node with the major and minor numbers specified by \p dev and
306  * parent directory if necessary and was called by root.
307  */
308 static int drmOpenDevice(dev_t dev, int minor, int type)
309 {
310     stat_t          st;
311     const char      *dev_name;
312     char            buf[64];
313     int             fd;
314     mode_t          devmode = DRM_DEV_MODE, serv_mode;
315     gid_t           serv_group;
316 #if !defined(UDEV)
317     int             isroot  = !geteuid();
318     uid_t           user    = DRM_DEV_UID;
319     gid_t           group   = DRM_DEV_GID;
320 #endif
321
322     switch (type) {
323     case DRM_NODE_PRIMARY:
324         dev_name = DRM_DEV_NAME;
325         break;
326     case DRM_NODE_CONTROL:
327         dev_name = DRM_CONTROL_DEV_NAME;
328         break;
329     case DRM_NODE_RENDER:
330         dev_name = DRM_RENDER_DEV_NAME;
331         break;
332     default:
333         return -EINVAL;
334     };
335
336     sprintf(buf, dev_name, DRM_DIR_NAME, minor);
337     drmMsg("drmOpenDevice: node name is %s\n", buf);
338
339     if (drm_server_info && drm_server_info->get_perms) {
340         drm_server_info->get_perms(&serv_group, &serv_mode);
341         devmode  = serv_mode ? serv_mode : DRM_DEV_MODE;
342         devmode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
343     }
344
345 #if !defined(UDEV)
346     if (stat(DRM_DIR_NAME, &st)) {
347         if (!isroot)
348             return DRM_ERR_NOT_ROOT;
349         mkdir(DRM_DIR_NAME, DRM_DEV_DIRMODE);
350         chown_check_return(DRM_DIR_NAME, 0, 0); /* root:root */
351         chmod(DRM_DIR_NAME, DRM_DEV_DIRMODE);
352     }
353
354     /* Check if the device node exists and create it if necessary. */
355     if (stat(buf, &st)) {
356         if (!isroot)
357             return DRM_ERR_NOT_ROOT;
358         remove(buf);
359         mknod(buf, S_IFCHR | devmode, dev);
360     }
361
362     if (drm_server_info && drm_server_info->get_perms) {
363         group = ((int)serv_group >= 0) ? serv_group : DRM_DEV_GID;
364         chown_check_return(buf, user, group);
365         chmod(buf, devmode);
366     }
367 #else
368     /* if we modprobed then wait for udev */
369     {
370         int udev_count = 0;
371 wait_for_udev:
372         if (stat(DRM_DIR_NAME, &st)) {
373             usleep(20);
374             udev_count++;
375
376             if (udev_count == 50)
377                 return -1;
378             goto wait_for_udev;
379         }
380
381         if (stat(buf, &st)) {
382             usleep(20);
383             udev_count++;
384
385             if (udev_count == 50)
386                 return -1;
387             goto wait_for_udev;
388         }
389     }
390 #endif
391
392     fd = open(buf, O_RDWR, 0);
393     drmMsg("drmOpenDevice: open result is %d, (%s)\n",
394            fd, fd < 0 ? strerror(errno) : "OK");
395     if (fd >= 0)
396         return fd;
397
398 #if !defined(UDEV)
399     /* Check if the device node is not what we expect it to be, and recreate it
400      * and try again if so.
401      */
402     if (st.st_rdev != dev) {
403         if (!isroot)
404             return DRM_ERR_NOT_ROOT;
405         remove(buf);
406         mknod(buf, S_IFCHR | devmode, dev);
407         if (drm_server_info && drm_server_info->get_perms) {
408             chown_check_return(buf, user, group);
409             chmod(buf, devmode);
410         }
411     }
412     fd = open(buf, O_RDWR, 0);
413     drmMsg("drmOpenDevice: open result is %d, (%s)\n",
414            fd, fd < 0 ? strerror(errno) : "OK");
415     if (fd >= 0)
416         return fd;
417
418     drmMsg("drmOpenDevice: Open failed\n");
419     remove(buf);
420 #endif
421     return -errno;
422 }
423
424
425 /**
426  * Open the DRM device
427  *
428  * \param minor device minor number.
429  * \param create allow to create the device if set.
430  *
431  * \return a file descriptor on success, or a negative value on error.
432  *
433  * \internal
434  * Calls drmOpenDevice() if \p create is set, otherwise assembles the device
435  * name from \p minor and opens it.
436  */
437 static int drmOpenMinor(int minor, int create, int type)
438 {
439     int  fd;
440     char buf[64];
441     const char *dev_name;
442
443     if (create)
444         return drmOpenDevice(makedev(DRM_MAJOR, minor), minor, type);
445
446     switch (type) {
447     case DRM_NODE_PRIMARY:
448         dev_name = DRM_DEV_NAME;
449         break;
450     case DRM_NODE_CONTROL:
451         dev_name = DRM_CONTROL_DEV_NAME;
452         break;
453     case DRM_NODE_RENDER:
454         dev_name = DRM_RENDER_DEV_NAME;
455         break;
456     default:
457         return -EINVAL;
458     };
459
460     sprintf(buf, dev_name, DRM_DIR_NAME, minor);
461     if ((fd = open(buf, O_RDWR, 0)) >= 0)
462         return fd;
463     return -errno;
464 }
465
466
467 /**
468  * Determine whether the DRM kernel driver has been loaded.
469  *
470  * \return 1 if the DRM driver is loaded, 0 otherwise.
471  *
472  * \internal
473  * Determine the presence of the kernel driver by attempting to open the 0
474  * minor and get version information.  For backward compatibility with older
475  * Linux implementations, /proc/dri is also checked.
476  */
477 int drmAvailable(void)
478 {
479     drmVersionPtr version;
480     int           retval = 0;
481     int           fd;
482
483     if ((fd = drmOpenMinor(0, 1, DRM_NODE_PRIMARY)) < 0) {
484 #ifdef __linux__
485         /* Try proc for backward Linux compatibility */
486         if (!access("/proc/dri/0", R_OK))
487             return 1;
488 #endif
489         return 0;
490     }
491
492     if ((version = drmGetVersion(fd))) {
493         retval = 1;
494         drmFreeVersion(version);
495     }
496     close(fd);
497
498     return retval;
499 }
500
501 static int drmGetMinorBase(int type)
502 {
503     switch (type) {
504     case DRM_NODE_PRIMARY:
505         return 0;
506     case DRM_NODE_CONTROL:
507         return 64;
508     case DRM_NODE_RENDER:
509         return 128;
510     default:
511         return -1;
512     };
513 }
514
515 static int drmGetMinorType(int minor)
516 {
517     int type = minor >> 6;
518
519     if (minor < 0)
520         return -1;
521
522     switch (type) {
523     case DRM_NODE_PRIMARY:
524     case DRM_NODE_CONTROL:
525     case DRM_NODE_RENDER:
526         return type;
527     default:
528         return -1;
529     }
530 }
531
532 static const char *drmGetMinorName(int type)
533 {
534     switch (type) {
535     case DRM_NODE_PRIMARY:
536         return DRM_PRIMARY_MINOR_NAME;
537     case DRM_NODE_CONTROL:
538         return DRM_CONTROL_MINOR_NAME;
539     case DRM_NODE_RENDER:
540         return DRM_RENDER_MINOR_NAME;
541     default:
542         return NULL;
543     }
544 }
545
546 /**
547  * Open the device by bus ID.
548  *
549  * \param busid bus ID.
550  * \param type device node type.
551  *
552  * \return a file descriptor on success, or a negative value on error.
553  *
554  * \internal
555  * This function attempts to open every possible minor (up to DRM_MAX_MINOR),
556  * comparing the device bus ID with the one supplied.
557  *
558  * \sa drmOpenMinor() and drmGetBusid().
559  */
560 static int drmOpenByBusid(const char *busid, int type)
561 {
562     int        i, pci_domain_ok = 1;
563     int        fd;
564     const char *buf;
565     drmSetVersion sv;
566     int        base = drmGetMinorBase(type);
567
568     if (base < 0)
569         return -1;
570
571     drmMsg("drmOpenByBusid: Searching for BusID %s\n", busid);
572     for (i = base; i < base + DRM_MAX_MINOR; i++) {
573         fd = drmOpenMinor(i, 1, type);
574         drmMsg("drmOpenByBusid: drmOpenMinor returns %d\n", fd);
575         if (fd >= 0) {
576             /* We need to try for 1.4 first for proper PCI domain support
577              * and if that fails, we know the kernel is busted
578              */
579             sv.drm_di_major = 1;
580             sv.drm_di_minor = 4;
581             sv.drm_dd_major = -1;        /* Don't care */
582             sv.drm_dd_minor = -1;        /* Don't care */
583             if (drmSetInterfaceVersion(fd, &sv)) {
584 #ifndef __alpha__
585                 pci_domain_ok = 0;
586 #endif
587                 sv.drm_di_major = 1;
588                 sv.drm_di_minor = 1;
589                 sv.drm_dd_major = -1;       /* Don't care */
590                 sv.drm_dd_minor = -1;       /* Don't care */
591                 drmMsg("drmOpenByBusid: Interface 1.4 failed, trying 1.1\n");
592                 drmSetInterfaceVersion(fd, &sv);
593             }
594             buf = drmGetBusid(fd);
595             drmMsg("drmOpenByBusid: drmGetBusid reports %s\n", buf);
596             if (buf && drmMatchBusID(buf, busid, pci_domain_ok)) {
597                 drmFreeBusid(buf);
598                 return fd;
599             }
600             if (buf)
601                 drmFreeBusid(buf);
602             close(fd);
603         }
604     }
605     return -1;
606 }
607
608
609 /**
610  * Open the device by name.
611  *
612  * \param name driver name.
613  * \param type the device node type.
614  *
615  * \return a file descriptor on success, or a negative value on error.
616  *
617  * \internal
618  * This function opens the first minor number that matches the driver name and
619  * isn't already in use.  If it's in use it then it will already have a bus ID
620  * assigned.
621  *
622  * \sa drmOpenMinor(), drmGetVersion() and drmGetBusid().
623  */
624 static int drmOpenByName(const char *name, int type)
625 {
626     int           i;
627     int           fd;
628     drmVersionPtr version;
629     char *        id;
630     int           base = drmGetMinorBase(type);
631
632     if (base < 0)
633         return -1;
634
635     /*
636      * Open the first minor number that matches the driver name and isn't
637      * already in use.  If it's in use it will have a busid assigned already.
638      */
639     for (i = base; i < base + DRM_MAX_MINOR; i++) {
640         if ((fd = drmOpenMinor(i, 1, type)) >= 0) {
641             if ((version = drmGetVersion(fd))) {
642                 if (!strcmp(version->name, name)) {
643                     drmFreeVersion(version);
644                     id = drmGetBusid(fd);
645                     drmMsg("drmGetBusid returned '%s'\n", id ? id : "NULL");
646                     if (!id || !*id) {
647                         if (id)
648                             drmFreeBusid(id);
649                         return fd;
650                     } else {
651                         drmFreeBusid(id);
652                     }
653                 } else {
654                     drmFreeVersion(version);
655                 }
656             }
657             close(fd);
658         }
659     }
660
661 #ifdef __linux__
662     /* Backward-compatibility /proc support */
663     for (i = 0; i < 8; i++) {
664         char proc_name[64], buf[512];
665         char *driver, *pt, *devstring;
666         int  retcode;
667
668         sprintf(proc_name, "/proc/dri/%d/name", i);
669         if ((fd = open(proc_name, 0, 0)) >= 0) {
670             retcode = read(fd, buf, sizeof(buf)-1);
671             close(fd);
672             if (retcode) {
673                 buf[retcode-1] = '\0';
674                 for (driver = pt = buf; *pt && *pt != ' '; ++pt)
675                     ;
676                 if (*pt) { /* Device is next */
677                     *pt = '\0';
678                     if (!strcmp(driver, name)) { /* Match */
679                         for (devstring = ++pt; *pt && *pt != ' '; ++pt)
680                             ;
681                         if (*pt) { /* Found busid */
682                             return drmOpenByBusid(++pt, type);
683                         } else { /* No busid */
684                             return drmOpenDevice(strtol(devstring, NULL, 0),i, type);
685                         }
686                     }
687                 }
688             }
689         }
690     }
691 #endif
692
693     return -1;
694 }
695
696
697 /**
698  * Open the DRM device.
699  *
700  * Looks up the specified name and bus ID, and opens the device found.  The
701  * entry in /dev/dri is created if necessary and if called by root.
702  *
703  * \param name driver name. Not referenced if bus ID is supplied.
704  * \param busid bus ID. Zero if not known.
705  *
706  * \return a file descriptor on success, or a negative value on error.
707  *
708  * \internal
709  * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
710  * otherwise.
711  */
712 int drmOpen(const char *name, const char *busid)
713 {
714     return drmOpenWithType(name, busid, DRM_NODE_PRIMARY);
715 }
716
717 /**
718  * Open the DRM device with specified type.
719  *
720  * Looks up the specified name and bus ID, and opens the device found.  The
721  * entry in /dev/dri is created if necessary and if called by root.
722  *
723  * \param name driver name. Not referenced if bus ID is supplied.
724  * \param busid bus ID. Zero if not known.
725  * \param type the device node type to open, PRIMARY, CONTROL or RENDER
726  *
727  * \return a file descriptor on success, or a negative value on error.
728  *
729  * \internal
730  * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
731  * otherwise.
732  */
733 int drmOpenWithType(const char *name, const char *busid, int type)
734 {
735     if (!drmAvailable() && name != NULL && drm_server_info &&
736         drm_server_info->load_module) {
737         /* try to load the kernel module */
738         if (!drm_server_info->load_module(name)) {
739             drmMsg("[drm] failed to load kernel module \"%s\"\n", name);
740             return -1;
741         }
742     }
743
744     if (busid) {
745         int fd = drmOpenByBusid(busid, type);
746         if (fd >= 0)
747             return fd;
748     }
749
750     if (name)
751         return drmOpenByName(name, type);
752
753     return -1;
754 }
755
756 int drmOpenControl(int minor)
757 {
758     return drmOpenMinor(minor, 0, DRM_NODE_CONTROL);
759 }
760
761 int drmOpenRender(int minor)
762 {
763     return drmOpenMinor(minor, 0, DRM_NODE_RENDER);
764 }
765
766 /**
767  * Free the version information returned by drmGetVersion().
768  *
769  * \param v pointer to the version information.
770  *
771  * \internal
772  * It frees the memory pointed by \p %v as well as all the non-null strings
773  * pointers in it.
774  */
775 void drmFreeVersion(drmVersionPtr v)
776 {
777     if (!v)
778         return;
779     drmFree(v->name);
780     drmFree(v->date);
781     drmFree(v->desc);
782     drmFree(v);
783 }
784
785
786 /**
787  * Free the non-public version information returned by the kernel.
788  *
789  * \param v pointer to the version information.
790  *
791  * \internal
792  * Used by drmGetVersion() to free the memory pointed by \p %v as well as all
793  * the non-null strings pointers in it.
794  */
795 static void drmFreeKernelVersion(drm_version_t *v)
796 {
797     if (!v)
798         return;
799     drmFree(v->name);
800     drmFree(v->date);
801     drmFree(v->desc);
802     drmFree(v);
803 }
804
805
806 /**
807  * Copy version information.
808  *
809  * \param d destination pointer.
810  * \param s source pointer.
811  *
812  * \internal
813  * Used by drmGetVersion() to translate the information returned by the ioctl
814  * interface in a private structure into the public structure counterpart.
815  */
816 static void drmCopyVersion(drmVersionPtr d, const drm_version_t *s)
817 {
818     d->version_major      = s->version_major;
819     d->version_minor      = s->version_minor;
820     d->version_patchlevel = s->version_patchlevel;
821     d->name_len           = s->name_len;
822     d->name               = strdup(s->name);
823     d->date_len           = s->date_len;
824     d->date               = strdup(s->date);
825     d->desc_len           = s->desc_len;
826     d->desc               = strdup(s->desc);
827 }
828
829
830 /**
831  * Query the driver version information.
832  *
833  * \param fd file descriptor.
834  *
835  * \return pointer to a drmVersion structure which should be freed with
836  * drmFreeVersion().
837  *
838  * \note Similar information is available via /proc/dri.
839  *
840  * \internal
841  * It gets the version information via successive DRM_IOCTL_VERSION ioctls,
842  * first with zeros to get the string lengths, and then the actually strings.
843  * It also null-terminates them since they might not be already.
844  */
845 drmVersionPtr drmGetVersion(int fd)
846 {
847     drmVersionPtr retval;
848     drm_version_t *version = drmMalloc(sizeof(*version));
849
850     memclear(*version);
851
852     if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
853         drmFreeKernelVersion(version);
854         return NULL;
855     }
856
857     if (version->name_len)
858         version->name    = drmMalloc(version->name_len + 1);
859     if (version->date_len)
860         version->date    = drmMalloc(version->date_len + 1);
861     if (version->desc_len)
862         version->desc    = drmMalloc(version->desc_len + 1);
863
864     if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
865         drmMsg("DRM_IOCTL_VERSION: %s\n", strerror(errno));
866         drmFreeKernelVersion(version);
867         return NULL;
868     }
869
870     /* The results might not be null-terminated strings, so terminate them. */
871     if (version->name_len) version->name[version->name_len] = '\0';
872     if (version->date_len) version->date[version->date_len] = '\0';
873     if (version->desc_len) version->desc[version->desc_len] = '\0';
874
875     retval = drmMalloc(sizeof(*retval));
876     drmCopyVersion(retval, version);
877     drmFreeKernelVersion(version);
878     return retval;
879 }
880
881
882 /**
883  * Get version information for the DRM user space library.
884  *
885  * This version number is driver independent.
886  *
887  * \param fd file descriptor.
888  *
889  * \return version information.
890  *
891  * \internal
892  * This function allocates and fills a drm_version structure with a hard coded
893  * version number.
894  */
895 drmVersionPtr drmGetLibVersion(int fd)
896 {
897     drm_version_t *version = drmMalloc(sizeof(*version));
898
899     /* Version history:
900      *   NOTE THIS MUST NOT GO ABOVE VERSION 1.X due to drivers needing it
901      *   revision 1.0.x = original DRM interface with no drmGetLibVersion
902      *                    entry point and many drm<Device> extensions
903      *   revision 1.1.x = added drmCommand entry points for device extensions
904      *                    added drmGetLibVersion to identify libdrm.a version
905      *   revision 1.2.x = added drmSetInterfaceVersion
906      *                    modified drmOpen to handle both busid and name
907      *   revision 1.3.x = added server + memory manager
908      */
909     version->version_major      = 1;
910     version->version_minor      = 3;
911     version->version_patchlevel = 0;
912
913     return (drmVersionPtr)version;
914 }
915
916 int drmGetCap(int fd, uint64_t capability, uint64_t *value)
917 {
918     struct drm_get_cap cap;
919     int ret;
920
921     memclear(cap);
922     cap.capability = capability;
923
924     ret = drmIoctl(fd, DRM_IOCTL_GET_CAP, &cap);
925     if (ret)
926         return ret;
927
928     *value = cap.value;
929     return 0;
930 }
931
932 int drmSetClientCap(int fd, uint64_t capability, uint64_t value)
933 {
934     struct drm_set_client_cap cap;
935
936     memclear(cap);
937     cap.capability = capability;
938     cap.value = value;
939
940     return drmIoctl(fd, DRM_IOCTL_SET_CLIENT_CAP, &cap);
941 }
942
943 /**
944  * Free the bus ID information.
945  *
946  * \param busid bus ID information string as given by drmGetBusid().
947  *
948  * \internal
949  * This function is just frees the memory pointed by \p busid.
950  */
951 void drmFreeBusid(const char *busid)
952 {
953     drmFree((void *)busid);
954 }
955
956
957 /**
958  * Get the bus ID of the device.
959  *
960  * \param fd file descriptor.
961  *
962  * \return bus ID string.
963  *
964  * \internal
965  * This function gets the bus ID via successive DRM_IOCTL_GET_UNIQUE ioctls to
966  * get the string length and data, passing the arguments in a drm_unique
967  * structure.
968  */
969 char *drmGetBusid(int fd)
970 {
971     drm_unique_t u;
972
973     memclear(u);
974
975     if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
976         return NULL;
977     u.unique = drmMalloc(u.unique_len + 1);
978     if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
979         return NULL;
980     u.unique[u.unique_len] = '\0';
981
982     return u.unique;
983 }
984
985
986 /**
987  * Set the bus ID of the device.
988  *
989  * \param fd file descriptor.
990  * \param busid bus ID string.
991  *
992  * \return zero on success, negative on failure.
993  *
994  * \internal
995  * This function is a wrapper around the DRM_IOCTL_SET_UNIQUE ioctl, passing
996  * the arguments in a drm_unique structure.
997  */
998 int drmSetBusid(int fd, const char *busid)
999 {
1000     drm_unique_t u;
1001
1002     memclear(u);
1003     u.unique     = (char *)busid;
1004     u.unique_len = strlen(busid);
1005
1006     if (drmIoctl(fd, DRM_IOCTL_SET_UNIQUE, &u)) {
1007         return -errno;
1008     }
1009     return 0;
1010 }
1011
1012 int drmGetMagic(int fd, drm_magic_t * magic)
1013 {
1014     drm_auth_t auth;
1015
1016     memclear(auth);
1017
1018     *magic = 0;
1019     if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
1020         return -errno;
1021     *magic = auth.magic;
1022     return 0;
1023 }
1024
1025 int drmAuthMagic(int fd, drm_magic_t magic)
1026 {
1027     drm_auth_t auth;
1028
1029     memclear(auth);
1030     auth.magic = magic;
1031     if (drmIoctl(fd, DRM_IOCTL_AUTH_MAGIC, &auth))
1032         return -errno;
1033     return 0;
1034 }
1035
1036 /**
1037  * Specifies a range of memory that is available for mapping by a
1038  * non-root process.
1039  *
1040  * \param fd file descriptor.
1041  * \param offset usually the physical address. The actual meaning depends of
1042  * the \p type parameter. See below.
1043  * \param size of the memory in bytes.
1044  * \param type type of the memory to be mapped.
1045  * \param flags combination of several flags to modify the function actions.
1046  * \param handle will be set to a value that may be used as the offset
1047  * parameter for mmap().
1048  *
1049  * \return zero on success or a negative value on error.
1050  *
1051  * \par Mapping the frame buffer
1052  * For the frame buffer
1053  * - \p offset will be the physical address of the start of the frame buffer,
1054  * - \p size will be the size of the frame buffer in bytes, and
1055  * - \p type will be DRM_FRAME_BUFFER.
1056  *
1057  * \par
1058  * The area mapped will be uncached. If MTRR support is available in the
1059  * kernel, the frame buffer area will be set to write combining.
1060  *
1061  * \par Mapping the MMIO register area
1062  * For the MMIO register area,
1063  * - \p offset will be the physical address of the start of the register area,
1064  * - \p size will be the size of the register area bytes, and
1065  * - \p type will be DRM_REGISTERS.
1066  * \par
1067  * The area mapped will be uncached.
1068  *
1069  * \par Mapping the SAREA
1070  * For the SAREA,
1071  * - \p offset will be ignored and should be set to zero,
1072  * - \p size will be the desired size of the SAREA in bytes,
1073  * - \p type will be DRM_SHM.
1074  *
1075  * \par
1076  * A shared memory area of the requested size will be created and locked in
1077  * kernel memory. This area may be mapped into client-space by using the handle
1078  * returned.
1079  *
1080  * \note May only be called by root.
1081  *
1082  * \internal
1083  * This function is a wrapper around the DRM_IOCTL_ADD_MAP ioctl, passing
1084  * the arguments in a drm_map structure.
1085  */
1086 int drmAddMap(int fd, drm_handle_t offset, drmSize size, drmMapType type,
1087               drmMapFlags flags, drm_handle_t *handle)
1088 {
1089     drm_map_t map;
1090
1091     memclear(map);
1092     map.offset  = offset;
1093     map.size    = size;
1094     map.type    = type;
1095     map.flags   = flags;
1096     if (drmIoctl(fd, DRM_IOCTL_ADD_MAP, &map))
1097         return -errno;
1098     if (handle)
1099         *handle = (drm_handle_t)(uintptr_t)map.handle;
1100     return 0;
1101 }
1102
1103 int drmRmMap(int fd, drm_handle_t handle)
1104 {
1105     drm_map_t map;
1106
1107     memclear(map);
1108     map.handle = (void *)(uintptr_t)handle;
1109
1110     if(drmIoctl(fd, DRM_IOCTL_RM_MAP, &map))
1111         return -errno;
1112     return 0;
1113 }
1114
1115 /**
1116  * Make buffers available for DMA transfers.
1117  *
1118  * \param fd file descriptor.
1119  * \param count number of buffers.
1120  * \param size size of each buffer.
1121  * \param flags buffer allocation flags.
1122  * \param agp_offset offset in the AGP aperture
1123  *
1124  * \return number of buffers allocated, negative on error.
1125  *
1126  * \internal
1127  * This function is a wrapper around DRM_IOCTL_ADD_BUFS ioctl.
1128  *
1129  * \sa drm_buf_desc.
1130  */
1131 int drmAddBufs(int fd, int count, int size, drmBufDescFlags flags,
1132                int agp_offset)
1133 {
1134     drm_buf_desc_t request;
1135
1136     memclear(request);
1137     request.count     = count;
1138     request.size      = size;
1139     request.flags     = flags;
1140     request.agp_start = agp_offset;
1141
1142     if (drmIoctl(fd, DRM_IOCTL_ADD_BUFS, &request))
1143         return -errno;
1144     return request.count;
1145 }
1146
1147 int drmMarkBufs(int fd, double low, double high)
1148 {
1149     drm_buf_info_t info;
1150     int            i;
1151
1152     memclear(info);
1153
1154     if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1155         return -EINVAL;
1156
1157     if (!info.count)
1158         return -EINVAL;
1159
1160     if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1161         return -ENOMEM;
1162
1163     if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1164         int retval = -errno;
1165         drmFree(info.list);
1166         return retval;
1167     }
1168
1169     for (i = 0; i < info.count; i++) {
1170         info.list[i].low_mark  = low  * info.list[i].count;
1171         info.list[i].high_mark = high * info.list[i].count;
1172         if (drmIoctl(fd, DRM_IOCTL_MARK_BUFS, &info.list[i])) {
1173             int retval = -errno;
1174             drmFree(info.list);
1175             return retval;
1176         }
1177     }
1178     drmFree(info.list);
1179
1180     return 0;
1181 }
1182
1183 /**
1184  * Free buffers.
1185  *
1186  * \param fd file descriptor.
1187  * \param count number of buffers to free.
1188  * \param list list of buffers to be freed.
1189  *
1190  * \return zero on success, or a negative value on failure.
1191  *
1192  * \note This function is primarily used for debugging.
1193  *
1194  * \internal
1195  * This function is a wrapper around the DRM_IOCTL_FREE_BUFS ioctl, passing
1196  * the arguments in a drm_buf_free structure.
1197  */
1198 int drmFreeBufs(int fd, int count, int *list)
1199 {
1200     drm_buf_free_t request;
1201
1202     memclear(request);
1203     request.count = count;
1204     request.list  = list;
1205     if (drmIoctl(fd, DRM_IOCTL_FREE_BUFS, &request))
1206         return -errno;
1207     return 0;
1208 }
1209
1210
1211 /**
1212  * Close the device.
1213  *
1214  * \param fd file descriptor.
1215  *
1216  * \internal
1217  * This function closes the file descriptor.
1218  */
1219 int drmClose(int fd)
1220 {
1221     unsigned long key    = drmGetKeyFromFd(fd);
1222     drmHashEntry  *entry = drmGetEntry(fd);
1223
1224     drmHashDestroy(entry->tagTable);
1225     entry->fd       = 0;
1226     entry->f        = NULL;
1227     entry->tagTable = NULL;
1228
1229     drmHashDelete(drmHashTable, key);
1230     drmFree(entry);
1231
1232     return close(fd);
1233 }
1234
1235
1236 /**
1237  * Map a region of memory.
1238  *
1239  * \param fd file descriptor.
1240  * \param handle handle returned by drmAddMap().
1241  * \param size size in bytes. Must match the size used by drmAddMap().
1242  * \param address will contain the user-space virtual address where the mapping
1243  * begins.
1244  *
1245  * \return zero on success, or a negative value on failure.
1246  *
1247  * \internal
1248  * This function is a wrapper for mmap().
1249  */
1250 int drmMap(int fd, drm_handle_t handle, drmSize size, drmAddressPtr address)
1251 {
1252     static unsigned long pagesize_mask = 0;
1253
1254     if (fd < 0)
1255         return -EINVAL;
1256
1257     if (!pagesize_mask)
1258         pagesize_mask = getpagesize() - 1;
1259
1260     size = (size + pagesize_mask) & ~pagesize_mask;
1261
1262     *address = drm_mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1263     if (*address == MAP_FAILED)
1264         return -errno;
1265     return 0;
1266 }
1267
1268
1269 /**
1270  * Unmap mappings obtained with drmMap().
1271  *
1272  * \param address address as given by drmMap().
1273  * \param size size in bytes. Must match the size used by drmMap().
1274  *
1275  * \return zero on success, or a negative value on failure.
1276  *
1277  * \internal
1278  * This function is a wrapper for munmap().
1279  */
1280 int drmUnmap(drmAddress address, drmSize size)
1281 {
1282     return drm_munmap(address, size);
1283 }
1284
1285 drmBufInfoPtr drmGetBufInfo(int fd)
1286 {
1287     drm_buf_info_t info;
1288     drmBufInfoPtr  retval;
1289     int            i;
1290
1291     memclear(info);
1292
1293     if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1294         return NULL;
1295
1296     if (info.count) {
1297         if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1298             return NULL;
1299
1300         if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1301             drmFree(info.list);
1302             return NULL;
1303         }
1304
1305         retval = drmMalloc(sizeof(*retval));
1306         retval->count = info.count;
1307         retval->list  = drmMalloc(info.count * sizeof(*retval->list));
1308         for (i = 0; i < info.count; i++) {
1309             retval->list[i].count     = info.list[i].count;
1310             retval->list[i].size      = info.list[i].size;
1311             retval->list[i].low_mark  = info.list[i].low_mark;
1312             retval->list[i].high_mark = info.list[i].high_mark;
1313         }
1314         drmFree(info.list);
1315         return retval;
1316     }
1317     return NULL;
1318 }
1319
1320 /**
1321  * Map all DMA buffers into client-virtual space.
1322  *
1323  * \param fd file descriptor.
1324  *
1325  * \return a pointer to a ::drmBufMap structure.
1326  *
1327  * \note The client may not use these buffers until obtaining buffer indices
1328  * with drmDMA().
1329  *
1330  * \internal
1331  * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1332  * information about the buffers in a drm_buf_map structure into the
1333  * client-visible data structures.
1334  */
1335 drmBufMapPtr drmMapBufs(int fd)
1336 {
1337     drm_buf_map_t bufs;
1338     drmBufMapPtr  retval;
1339     int           i;
1340
1341     memclear(bufs);
1342     if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1343         return NULL;
1344
1345     if (!bufs.count)
1346         return NULL;
1347
1348     if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1349         return NULL;
1350
1351     if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1352         drmFree(bufs.list);
1353         return NULL;
1354     }
1355
1356     retval = drmMalloc(sizeof(*retval));
1357     retval->count = bufs.count;
1358     retval->list  = drmMalloc(bufs.count * sizeof(*retval->list));
1359     for (i = 0; i < bufs.count; i++) {
1360         retval->list[i].idx     = bufs.list[i].idx;
1361         retval->list[i].total   = bufs.list[i].total;
1362         retval->list[i].used    = 0;
1363         retval->list[i].address = bufs.list[i].address;
1364     }
1365
1366     drmFree(bufs.list);
1367     return retval;
1368 }
1369
1370
1371 /**
1372  * Unmap buffers allocated with drmMapBufs().
1373  *
1374  * \return zero on success, or negative value on failure.
1375  *
1376  * \internal
1377  * Calls munmap() for every buffer stored in \p bufs and frees the
1378  * memory allocated by drmMapBufs().
1379  */
1380 int drmUnmapBufs(drmBufMapPtr bufs)
1381 {
1382     int i;
1383
1384     for (i = 0; i < bufs->count; i++) {
1385         drm_munmap(bufs->list[i].address, bufs->list[i].total);
1386     }
1387
1388     drmFree(bufs->list);
1389     drmFree(bufs);
1390     return 0;
1391 }
1392
1393
1394 #define DRM_DMA_RETRY  16
1395
1396 /**
1397  * Reserve DMA buffers.
1398  *
1399  * \param fd file descriptor.
1400  * \param request
1401  *
1402  * \return zero on success, or a negative value on failure.
1403  *
1404  * \internal
1405  * Assemble the arguments into a drm_dma structure and keeps issuing the
1406  * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1407  */
1408 int drmDMA(int fd, drmDMAReqPtr request)
1409 {
1410     drm_dma_t dma;
1411     int ret, i = 0;
1412
1413     dma.context         = request->context;
1414     dma.send_count      = request->send_count;
1415     dma.send_indices    = request->send_list;
1416     dma.send_sizes      = request->send_sizes;
1417     dma.flags           = request->flags;
1418     dma.request_count   = request->request_count;
1419     dma.request_size    = request->request_size;
1420     dma.request_indices = request->request_list;
1421     dma.request_sizes   = request->request_sizes;
1422     dma.granted_count   = 0;
1423
1424     do {
1425         ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1426     } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1427
1428     if ( ret == 0 ) {
1429         request->granted_count = dma.granted_count;
1430         return 0;
1431     } else {
1432         return -errno;
1433     }
1434 }
1435
1436
1437 /**
1438  * Obtain heavyweight hardware lock.
1439  *
1440  * \param fd file descriptor.
1441  * \param context context.
1442  * \param flags flags that determine the sate of the hardware when the function
1443  * returns.
1444  *
1445  * \return always zero.
1446  *
1447  * \internal
1448  * This function translates the arguments into a drm_lock structure and issue
1449  * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1450  */
1451 int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
1452 {
1453     drm_lock_t lock;
1454
1455     memclear(lock);
1456     lock.context = context;
1457     lock.flags   = 0;
1458     if (flags & DRM_LOCK_READY)      lock.flags |= _DRM_LOCK_READY;
1459     if (flags & DRM_LOCK_QUIESCENT)  lock.flags |= _DRM_LOCK_QUIESCENT;
1460     if (flags & DRM_LOCK_FLUSH)      lock.flags |= _DRM_LOCK_FLUSH;
1461     if (flags & DRM_LOCK_FLUSH_ALL)  lock.flags |= _DRM_LOCK_FLUSH_ALL;
1462     if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
1463     if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
1464
1465     while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
1466         ;
1467     return 0;
1468 }
1469
1470 /**
1471  * Release the hardware lock.
1472  *
1473  * \param fd file descriptor.
1474  * \param context context.
1475  *
1476  * \return zero on success, or a negative value on failure.
1477  *
1478  * \internal
1479  * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
1480  * argument in a drm_lock structure.
1481  */
1482 int drmUnlock(int fd, drm_context_t context)
1483 {
1484     drm_lock_t lock;
1485
1486     memclear(lock);
1487     lock.context = context;
1488     return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
1489 }
1490
1491 drm_context_t *drmGetReservedContextList(int fd, int *count)
1492 {
1493     drm_ctx_res_t res;
1494     drm_ctx_t     *list;
1495     drm_context_t * retval;
1496     int           i;
1497
1498     memclear(res);
1499     if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1500         return NULL;
1501
1502     if (!res.count)
1503         return NULL;
1504
1505     if (!(list   = drmMalloc(res.count * sizeof(*list))))
1506         return NULL;
1507     if (!(retval = drmMalloc(res.count * sizeof(*retval)))) {
1508         drmFree(list);
1509         return NULL;
1510     }
1511
1512     res.contexts = list;
1513     if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1514         return NULL;
1515
1516     for (i = 0; i < res.count; i++)
1517         retval[i] = list[i].handle;
1518     drmFree(list);
1519
1520     *count = res.count;
1521     return retval;
1522 }
1523
1524 void drmFreeReservedContextList(drm_context_t *pt)
1525 {
1526     drmFree(pt);
1527 }
1528
1529 /**
1530  * Create context.
1531  *
1532  * Used by the X server during GLXContext initialization. This causes
1533  * per-context kernel-level resources to be allocated.
1534  *
1535  * \param fd file descriptor.
1536  * \param handle is set on success. To be used by the client when requesting DMA
1537  * dispatch with drmDMA().
1538  *
1539  * \return zero on success, or a negative value on failure.
1540  *
1541  * \note May only be called by root.
1542  *
1543  * \internal
1544  * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
1545  * argument in a drm_ctx structure.
1546  */
1547 int drmCreateContext(int fd, drm_context_t *handle)
1548 {
1549     drm_ctx_t ctx;
1550
1551     memclear(ctx);
1552     if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
1553         return -errno;
1554     *handle = ctx.handle;
1555     return 0;
1556 }
1557
1558 int drmSwitchToContext(int fd, drm_context_t context)
1559 {
1560     drm_ctx_t ctx;
1561
1562     memclear(ctx);
1563     ctx.handle = context;
1564     if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
1565         return -errno;
1566     return 0;
1567 }
1568
1569 int drmSetContextFlags(int fd, drm_context_t context, drm_context_tFlags flags)
1570 {
1571     drm_ctx_t ctx;
1572
1573     /*
1574      * Context preserving means that no context switches are done between DMA
1575      * buffers from one context and the next.  This is suitable for use in the
1576      * X server (which promises to maintain hardware context), or in the
1577      * client-side library when buffers are swapped on behalf of two threads.
1578      */
1579     memclear(ctx);
1580     ctx.handle = context;
1581     if (flags & DRM_CONTEXT_PRESERVED)
1582         ctx.flags |= _DRM_CONTEXT_PRESERVED;
1583     if (flags & DRM_CONTEXT_2DONLY)
1584         ctx.flags |= _DRM_CONTEXT_2DONLY;
1585     if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
1586         return -errno;
1587     return 0;
1588 }
1589
1590 int drmGetContextFlags(int fd, drm_context_t context,
1591                        drm_context_tFlagsPtr flags)
1592 {
1593     drm_ctx_t ctx;
1594
1595     memclear(ctx);
1596     ctx.handle = context;
1597     if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
1598         return -errno;
1599     *flags = 0;
1600     if (ctx.flags & _DRM_CONTEXT_PRESERVED)
1601         *flags |= DRM_CONTEXT_PRESERVED;
1602     if (ctx.flags & _DRM_CONTEXT_2DONLY)
1603         *flags |= DRM_CONTEXT_2DONLY;
1604     return 0;
1605 }
1606
1607 /**
1608  * Destroy context.
1609  *
1610  * Free any kernel-level resources allocated with drmCreateContext() associated
1611  * with the context.
1612  *
1613  * \param fd file descriptor.
1614  * \param handle handle given by drmCreateContext().
1615  *
1616  * \return zero on success, or a negative value on failure.
1617  *
1618  * \note May only be called by root.
1619  *
1620  * \internal
1621  * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
1622  * argument in a drm_ctx structure.
1623  */
1624 int drmDestroyContext(int fd, drm_context_t handle)
1625 {
1626     drm_ctx_t ctx;
1627
1628     memclear(ctx);
1629     ctx.handle = handle;
1630     if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
1631         return -errno;
1632     return 0;
1633 }
1634
1635 int drmCreateDrawable(int fd, drm_drawable_t *handle)
1636 {
1637     drm_draw_t draw;
1638
1639     memclear(draw);
1640     if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
1641         return -errno;
1642     *handle = draw.handle;
1643     return 0;
1644 }
1645
1646 int drmDestroyDrawable(int fd, drm_drawable_t handle)
1647 {
1648     drm_draw_t draw;
1649
1650     memclear(draw);
1651     draw.handle = handle;
1652     if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
1653         return -errno;
1654     return 0;
1655 }
1656
1657 int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
1658                           drm_drawable_info_type_t type, unsigned int num,
1659                           void *data)
1660 {
1661     drm_update_draw_t update;
1662
1663     memclear(update);
1664     update.handle = handle;
1665     update.type = type;
1666     update.num = num;
1667     update.data = (unsigned long long)(unsigned long)data;
1668
1669     if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
1670         return -errno;
1671
1672     return 0;
1673 }
1674
1675 /**
1676  * Acquire the AGP device.
1677  *
1678  * Must be called before any of the other AGP related calls.
1679  *
1680  * \param fd file descriptor.
1681  *
1682  * \return zero on success, or a negative value on failure.
1683  *
1684  * \internal
1685  * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
1686  */
1687 int drmAgpAcquire(int fd)
1688 {
1689     if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
1690         return -errno;
1691     return 0;
1692 }
1693
1694
1695 /**
1696  * Release the AGP device.
1697  *
1698  * \param fd file descriptor.
1699  *
1700  * \return zero on success, or a negative value on failure.
1701  *
1702  * \internal
1703  * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
1704  */
1705 int drmAgpRelease(int fd)
1706 {
1707     if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
1708         return -errno;
1709     return 0;
1710 }
1711
1712
1713 /**
1714  * Set the AGP mode.
1715  *
1716  * \param fd file descriptor.
1717  * \param mode AGP mode.
1718  *
1719  * \return zero on success, or a negative value on failure.
1720  *
1721  * \internal
1722  * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
1723  * argument in a drm_agp_mode structure.
1724  */
1725 int drmAgpEnable(int fd, unsigned long mode)
1726 {
1727     drm_agp_mode_t m;
1728
1729     memclear(m);
1730     m.mode = mode;
1731     if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
1732         return -errno;
1733     return 0;
1734 }
1735
1736
1737 /**
1738  * Allocate a chunk of AGP memory.
1739  *
1740  * \param fd file descriptor.
1741  * \param size requested memory size in bytes. Will be rounded to page boundary.
1742  * \param type type of memory to allocate.
1743  * \param address if not zero, will be set to the physical address of the
1744  * allocated memory.
1745  * \param handle on success will be set to a handle of the allocated memory.
1746  *
1747  * \return zero on success, or a negative value on failure.
1748  *
1749  * \internal
1750  * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
1751  * arguments in a drm_agp_buffer structure.
1752  */
1753 int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
1754                 unsigned long *address, drm_handle_t *handle)
1755 {
1756     drm_agp_buffer_t b;
1757
1758     memclear(b);
1759     *handle = DRM_AGP_NO_HANDLE;
1760     b.size   = size;
1761     b.type   = type;
1762     if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
1763         return -errno;
1764     if (address != 0UL)
1765         *address = b.physical;
1766     *handle = b.handle;
1767     return 0;
1768 }
1769
1770
1771 /**
1772  * Free a chunk of AGP memory.
1773  *
1774  * \param fd file descriptor.
1775  * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1776  *
1777  * \return zero on success, or a negative value on failure.
1778  *
1779  * \internal
1780  * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
1781  * argument in a drm_agp_buffer structure.
1782  */
1783 int drmAgpFree(int fd, drm_handle_t handle)
1784 {
1785     drm_agp_buffer_t b;
1786
1787     memclear(b);
1788     b.handle = handle;
1789     if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
1790         return -errno;
1791     return 0;
1792 }
1793
1794
1795 /**
1796  * Bind a chunk of AGP memory.
1797  *
1798  * \param fd file descriptor.
1799  * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1800  * \param offset offset in bytes. It will round to page boundary.
1801  *
1802  * \return zero on success, or a negative value on failure.
1803  *
1804  * \internal
1805  * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
1806  * argument in a drm_agp_binding structure.
1807  */
1808 int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
1809 {
1810     drm_agp_binding_t b;
1811
1812     memclear(b);
1813     b.handle = handle;
1814     b.offset = offset;
1815     if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
1816         return -errno;
1817     return 0;
1818 }
1819
1820
1821 /**
1822  * Unbind a chunk of AGP memory.
1823  *
1824  * \param fd file descriptor.
1825  * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1826  *
1827  * \return zero on success, or a negative value on failure.
1828  *
1829  * \internal
1830  * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
1831  * the argument in a drm_agp_binding structure.
1832  */
1833 int drmAgpUnbind(int fd, drm_handle_t handle)
1834 {
1835     drm_agp_binding_t b;
1836
1837     memclear(b);
1838     b.handle = handle;
1839     if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
1840         return -errno;
1841     return 0;
1842 }
1843
1844
1845 /**
1846  * Get AGP driver major version number.
1847  *
1848  * \param fd file descriptor.
1849  *
1850  * \return major version number on success, or a negative value on failure..
1851  *
1852  * \internal
1853  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1854  * necessary information in a drm_agp_info structure.
1855  */
1856 int drmAgpVersionMajor(int fd)
1857 {
1858     drm_agp_info_t i;
1859
1860     memclear(i);
1861
1862     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1863         return -errno;
1864     return i.agp_version_major;
1865 }
1866
1867
1868 /**
1869  * Get AGP driver minor version number.
1870  *
1871  * \param fd file descriptor.
1872  *
1873  * \return minor version number on success, or a negative value on failure.
1874  *
1875  * \internal
1876  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1877  * necessary information in a drm_agp_info structure.
1878  */
1879 int drmAgpVersionMinor(int fd)
1880 {
1881     drm_agp_info_t i;
1882
1883     memclear(i);
1884
1885     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1886         return -errno;
1887     return i.agp_version_minor;
1888 }
1889
1890
1891 /**
1892  * Get AGP mode.
1893  *
1894  * \param fd file descriptor.
1895  *
1896  * \return mode on success, or zero on failure.
1897  *
1898  * \internal
1899  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1900  * necessary information in a drm_agp_info structure.
1901  */
1902 unsigned long drmAgpGetMode(int fd)
1903 {
1904     drm_agp_info_t i;
1905
1906     memclear(i);
1907
1908     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1909         return 0;
1910     return i.mode;
1911 }
1912
1913
1914 /**
1915  * Get AGP aperture base.
1916  *
1917  * \param fd file descriptor.
1918  *
1919  * \return aperture base on success, zero on failure.
1920  *
1921  * \internal
1922  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1923  * necessary information in a drm_agp_info structure.
1924  */
1925 unsigned long drmAgpBase(int fd)
1926 {
1927     drm_agp_info_t i;
1928
1929     memclear(i);
1930
1931     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1932         return 0;
1933     return i.aperture_base;
1934 }
1935
1936
1937 /**
1938  * Get AGP aperture size.
1939  *
1940  * \param fd file descriptor.
1941  *
1942  * \return aperture size on success, zero on failure.
1943  *
1944  * \internal
1945  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1946  * necessary information in a drm_agp_info structure.
1947  */
1948 unsigned long drmAgpSize(int fd)
1949 {
1950     drm_agp_info_t i;
1951
1952     memclear(i);
1953
1954     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1955         return 0;
1956     return i.aperture_size;
1957 }
1958
1959
1960 /**
1961  * Get used AGP memory.
1962  *
1963  * \param fd file descriptor.
1964  *
1965  * \return memory used on success, or zero on failure.
1966  *
1967  * \internal
1968  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1969  * necessary information in a drm_agp_info structure.
1970  */
1971 unsigned long drmAgpMemoryUsed(int fd)
1972 {
1973     drm_agp_info_t i;
1974
1975     memclear(i);
1976
1977     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1978         return 0;
1979     return i.memory_used;
1980 }
1981
1982
1983 /**
1984  * Get available AGP memory.
1985  *
1986  * \param fd file descriptor.
1987  *
1988  * \return memory available on success, or zero on failure.
1989  *
1990  * \internal
1991  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1992  * necessary information in a drm_agp_info structure.
1993  */
1994 unsigned long drmAgpMemoryAvail(int fd)
1995 {
1996     drm_agp_info_t i;
1997
1998     memclear(i);
1999
2000     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2001         return 0;
2002     return i.memory_allowed;
2003 }
2004
2005
2006 /**
2007  * Get hardware vendor ID.
2008  *
2009  * \param fd file descriptor.
2010  *
2011  * \return vendor ID on success, or zero on failure.
2012  *
2013  * \internal
2014  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2015  * necessary information in a drm_agp_info structure.
2016  */
2017 unsigned int drmAgpVendorId(int fd)
2018 {
2019     drm_agp_info_t i;
2020
2021     memclear(i);
2022
2023     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2024         return 0;
2025     return i.id_vendor;
2026 }
2027
2028
2029 /**
2030  * Get hardware device ID.
2031  *
2032  * \param fd file descriptor.
2033  *
2034  * \return zero on success, or zero on failure.
2035  *
2036  * \internal
2037  * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2038  * necessary information in a drm_agp_info structure.
2039  */
2040 unsigned int drmAgpDeviceId(int fd)
2041 {
2042     drm_agp_info_t i;
2043
2044     memclear(i);
2045
2046     if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2047         return 0;
2048     return i.id_device;
2049 }
2050
2051 int drmScatterGatherAlloc(int fd, unsigned long size, drm_handle_t *handle)
2052 {
2053     drm_scatter_gather_t sg;
2054
2055     memclear(sg);
2056
2057     *handle = 0;
2058     sg.size   = size;
2059     if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
2060         return -errno;
2061     *handle = sg.handle;
2062     return 0;
2063 }
2064
2065 int drmScatterGatherFree(int fd, drm_handle_t handle)
2066 {
2067     drm_scatter_gather_t sg;
2068
2069     memclear(sg);
2070     sg.handle = handle;
2071     if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
2072         return -errno;
2073     return 0;
2074 }
2075
2076 /**
2077  * Wait for VBLANK.
2078  *
2079  * \param fd file descriptor.
2080  * \param vbl pointer to a drmVBlank structure.
2081  *
2082  * \return zero on success, or a negative value on failure.
2083  *
2084  * \internal
2085  * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
2086  */
2087 int drmWaitVBlank(int fd, drmVBlankPtr vbl)
2088 {
2089     struct timespec timeout, cur;
2090     int ret;
2091
2092     ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2093     if (ret < 0) {
2094         fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
2095         goto out;
2096     }
2097     timeout.tv_sec++;
2098
2099     do {
2100        ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
2101        vbl->request.type &= ~DRM_VBLANK_RELATIVE;
2102        if (ret && errno == EINTR) {
2103            clock_gettime(CLOCK_MONOTONIC, &cur);
2104            /* Timeout after 1s */
2105            if (cur.tv_sec > timeout.tv_sec + 1 ||
2106                (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
2107                 timeout.tv_nsec)) {
2108                    errno = EBUSY;
2109                    ret = -1;
2110                    break;
2111            }
2112        }
2113     } while (ret && errno == EINTR);
2114
2115 out:
2116     return ret;
2117 }
2118
2119 int drmError(int err, const char *label)
2120 {
2121     switch (err) {
2122     case DRM_ERR_NO_DEVICE:
2123         fprintf(stderr, "%s: no device\n", label);
2124         break;
2125     case DRM_ERR_NO_ACCESS:
2126         fprintf(stderr, "%s: no access\n", label);
2127         break;
2128     case DRM_ERR_NOT_ROOT:
2129         fprintf(stderr, "%s: not root\n", label);
2130         break;
2131     case DRM_ERR_INVALID:
2132         fprintf(stderr, "%s: invalid args\n", label);
2133         break;
2134     default:
2135         if (err < 0)
2136             err = -err;
2137         fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2138         break;
2139     }
2140
2141     return 1;
2142 }
2143
2144 /**
2145  * Install IRQ handler.
2146  *
2147  * \param fd file descriptor.
2148  * \param irq IRQ number.
2149  *
2150  * \return zero on success, or a negative value on failure.
2151  *
2152  * \internal
2153  * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2154  * argument in a drm_control structure.
2155  */
2156 int drmCtlInstHandler(int fd, int irq)
2157 {
2158     drm_control_t ctl;
2159
2160     memclear(ctl);
2161     ctl.func  = DRM_INST_HANDLER;
2162     ctl.irq   = irq;
2163     if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2164         return -errno;
2165     return 0;
2166 }
2167
2168
2169 /**
2170  * Uninstall IRQ handler.
2171  *
2172  * \param fd file descriptor.
2173  *
2174  * \return zero on success, or a negative value on failure.
2175  *
2176  * \internal
2177  * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2178  * argument in a drm_control structure.
2179  */
2180 int drmCtlUninstHandler(int fd)
2181 {
2182     drm_control_t ctl;
2183
2184     memclear(ctl);
2185     ctl.func  = DRM_UNINST_HANDLER;
2186     ctl.irq   = 0;
2187     if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2188         return -errno;
2189     return 0;
2190 }
2191
2192 int drmFinish(int fd, int context, drmLockFlags flags)
2193 {
2194     drm_lock_t lock;
2195
2196     memclear(lock);
2197     lock.context = context;
2198     if (flags & DRM_LOCK_READY)      lock.flags |= _DRM_LOCK_READY;
2199     if (flags & DRM_LOCK_QUIESCENT)  lock.flags |= _DRM_LOCK_QUIESCENT;
2200     if (flags & DRM_LOCK_FLUSH)      lock.flags |= _DRM_LOCK_FLUSH;
2201     if (flags & DRM_LOCK_FLUSH_ALL)  lock.flags |= _DRM_LOCK_FLUSH_ALL;
2202     if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2203     if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2204     if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2205         return -errno;
2206     return 0;
2207 }
2208
2209 /**
2210  * Get IRQ from bus ID.
2211  *
2212  * \param fd file descriptor.
2213  * \param busnum bus number.
2214  * \param devnum device number.
2215  * \param funcnum function number.
2216  *
2217  * \return IRQ number on success, or a negative value on failure.
2218  *
2219  * \internal
2220  * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2221  * arguments in a drm_irq_busid structure.
2222  */
2223 int drmGetInterruptFromBusID(int fd, int busnum, int devnum, int funcnum)
2224 {
2225     drm_irq_busid_t p;
2226
2227     memclear(p);
2228     p.busnum  = busnum;
2229     p.devnum  = devnum;
2230     p.funcnum = funcnum;
2231     if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2232         return -errno;
2233     return p.irq;
2234 }
2235
2236 int drmAddContextTag(int fd, drm_context_t context, void *tag)
2237 {
2238     drmHashEntry  *entry = drmGetEntry(fd);
2239
2240     if (drmHashInsert(entry->tagTable, context, tag)) {
2241         drmHashDelete(entry->tagTable, context);
2242         drmHashInsert(entry->tagTable, context, tag);
2243     }
2244     return 0;
2245 }
2246
2247 int drmDelContextTag(int fd, drm_context_t context)
2248 {
2249     drmHashEntry  *entry = drmGetEntry(fd);
2250
2251     return drmHashDelete(entry->tagTable, context);
2252 }
2253
2254 void *drmGetContextTag(int fd, drm_context_t context)
2255 {
2256     drmHashEntry  *entry = drmGetEntry(fd);
2257     void          *value;
2258
2259     if (drmHashLookup(entry->tagTable, context, &value))
2260         return NULL;
2261
2262     return value;
2263 }
2264
2265 int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2266                                 drm_handle_t handle)
2267 {
2268     drm_ctx_priv_map_t map;
2269
2270     memclear(map);
2271     map.ctx_id = ctx_id;
2272     map.handle = (void *)(uintptr_t)handle;
2273
2274     if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2275         return -errno;
2276     return 0;
2277 }
2278
2279 int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2280                                 drm_handle_t *handle)
2281 {
2282     drm_ctx_priv_map_t map;
2283
2284     memclear(map);
2285     map.ctx_id = ctx_id;
2286
2287     if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2288         return -errno;
2289     if (handle)
2290         *handle = (drm_handle_t)(uintptr_t)map.handle;
2291
2292     return 0;
2293 }
2294
2295 int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2296               drmMapType *type, drmMapFlags *flags, drm_handle_t *handle,
2297               int *mtrr)
2298 {
2299     drm_map_t map;
2300
2301     memclear(map);
2302     map.offset = idx;
2303     if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2304         return -errno;
2305     *offset = map.offset;
2306     *size   = map.size;
2307     *type   = map.type;
2308     *flags  = map.flags;
2309     *handle = (unsigned long)map.handle;
2310     *mtrr   = map.mtrr;
2311     return 0;
2312 }
2313
2314 int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2315                  unsigned long *magic, unsigned long *iocs)
2316 {
2317     drm_client_t client;
2318
2319     memclear(client);
2320     client.idx = idx;
2321     if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2322         return -errno;
2323     *auth      = client.auth;
2324     *pid       = client.pid;
2325     *uid       = client.uid;
2326     *magic     = client.magic;
2327     *iocs      = client.iocs;
2328     return 0;
2329 }
2330
2331 int drmGetStats(int fd, drmStatsT *stats)
2332 {
2333     drm_stats_t s;
2334     unsigned    i;
2335
2336     memclear(s);
2337     if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2338         return -errno;
2339
2340     stats->count = 0;
2341     memset(stats, 0, sizeof(*stats));
2342     if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2343         return -1;
2344
2345 #define SET_VALUE                              \
2346     stats->data[i].long_format = "%-20.20s";   \
2347     stats->data[i].rate_format = "%8.8s";      \
2348     stats->data[i].isvalue     = 1;            \
2349     stats->data[i].verbose     = 0
2350
2351 #define SET_COUNT                              \
2352     stats->data[i].long_format = "%-20.20s";   \
2353     stats->data[i].rate_format = "%5.5s";      \
2354     stats->data[i].isvalue     = 0;            \
2355     stats->data[i].mult_names  = "kgm";        \
2356     stats->data[i].mult        = 1000;         \
2357     stats->data[i].verbose     = 0
2358
2359 #define SET_BYTE                               \
2360     stats->data[i].long_format = "%-20.20s";   \
2361     stats->data[i].rate_format = "%5.5s";      \
2362     stats->data[i].isvalue     = 0;            \
2363     stats->data[i].mult_names  = "KGM";        \
2364     stats->data[i].mult        = 1024;         \
2365     stats->data[i].verbose     = 0
2366
2367
2368     stats->count = s.count;
2369     for (i = 0; i < s.count; i++) {
2370         stats->data[i].value = s.data[i].value;
2371         switch (s.data[i].type) {
2372         case _DRM_STAT_LOCK:
2373             stats->data[i].long_name = "Lock";
2374             stats->data[i].rate_name = "Lock";
2375             SET_VALUE;
2376             break;
2377         case _DRM_STAT_OPENS:
2378             stats->data[i].long_name = "Opens";
2379             stats->data[i].rate_name = "O";
2380             SET_COUNT;
2381             stats->data[i].verbose   = 1;
2382             break;
2383         case _DRM_STAT_CLOSES:
2384             stats->data[i].long_name = "Closes";
2385             stats->data[i].rate_name = "Lock";
2386             SET_COUNT;
2387             stats->data[i].verbose   = 1;
2388             break;
2389         case _DRM_STAT_IOCTLS:
2390             stats->data[i].long_name = "Ioctls";
2391             stats->data[i].rate_name = "Ioc/s";
2392             SET_COUNT;
2393             break;
2394         case _DRM_STAT_LOCKS:
2395             stats->data[i].long_name = "Locks";
2396             stats->data[i].rate_name = "Lck/s";
2397             SET_COUNT;
2398             break;
2399         case _DRM_STAT_UNLOCKS:
2400             stats->data[i].long_name = "Unlocks";
2401             stats->data[i].rate_name = "Unl/s";
2402             SET_COUNT;
2403             break;
2404         case _DRM_STAT_IRQ:
2405             stats->data[i].long_name = "IRQs";
2406             stats->data[i].rate_name = "IRQ/s";
2407             SET_COUNT;
2408             break;
2409         case _DRM_STAT_PRIMARY:
2410             stats->data[i].long_name = "Primary Bytes";
2411             stats->data[i].rate_name = "PB/s";
2412             SET_BYTE;
2413             break;
2414         case _DRM_STAT_SECONDARY:
2415             stats->data[i].long_name = "Secondary Bytes";
2416             stats->data[i].rate_name = "SB/s";
2417             SET_BYTE;
2418             break;
2419         case _DRM_STAT_DMA:
2420             stats->data[i].long_name = "DMA";
2421             stats->data[i].rate_name = "DMA/s";
2422             SET_COUNT;
2423             break;
2424         case _DRM_STAT_SPECIAL:
2425             stats->data[i].long_name = "Special DMA";
2426             stats->data[i].rate_name = "dma/s";
2427             SET_COUNT;
2428             break;
2429         case _DRM_STAT_MISSED:
2430             stats->data[i].long_name = "Miss";
2431             stats->data[i].rate_name = "Ms/s";
2432             SET_COUNT;
2433             break;
2434         case _DRM_STAT_VALUE:
2435             stats->data[i].long_name = "Value";
2436             stats->data[i].rate_name = "Value";
2437             SET_VALUE;
2438             break;
2439         case _DRM_STAT_BYTE:
2440             stats->data[i].long_name = "Bytes";
2441             stats->data[i].rate_name = "B/s";
2442             SET_BYTE;
2443             break;
2444         case _DRM_STAT_COUNT:
2445         default:
2446             stats->data[i].long_name = "Count";
2447             stats->data[i].rate_name = "Cnt/s";
2448             SET_COUNT;
2449             break;
2450         }
2451     }
2452     return 0;
2453 }
2454
2455 /**
2456  * Issue a set-version ioctl.
2457  *
2458  * \param fd file descriptor.
2459  * \param drmCommandIndex command index
2460  * \param data source pointer of the data to be read and written.
2461  * \param size size of the data to be read and written.
2462  *
2463  * \return zero on success, or a negative value on failure.
2464  *
2465  * \internal
2466  * It issues a read-write ioctl given by
2467  * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2468  */
2469 int drmSetInterfaceVersion(int fd, drmSetVersion *version)
2470 {
2471     int retcode = 0;
2472     drm_set_version_t sv;
2473
2474     memclear(sv);
2475     sv.drm_di_major = version->drm_di_major;
2476     sv.drm_di_minor = version->drm_di_minor;
2477     sv.drm_dd_major = version->drm_dd_major;
2478     sv.drm_dd_minor = version->drm_dd_minor;
2479
2480     if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
2481         retcode = -errno;
2482     }
2483
2484     version->drm_di_major = sv.drm_di_major;
2485     version->drm_di_minor = sv.drm_di_minor;
2486     version->drm_dd_major = sv.drm_dd_major;
2487     version->drm_dd_minor = sv.drm_dd_minor;
2488
2489     return retcode;
2490 }
2491
2492 /**
2493  * Send a device-specific command.
2494  *
2495  * \param fd file descriptor.
2496  * \param drmCommandIndex command index
2497  *
2498  * \return zero on success, or a negative value on failure.
2499  *
2500  * \internal
2501  * It issues a ioctl given by
2502  * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2503  */
2504 int drmCommandNone(int fd, unsigned long drmCommandIndex)
2505 {
2506     unsigned long request;
2507
2508     request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
2509
2510     if (drmIoctl(fd, request, NULL)) {
2511         return -errno;
2512     }
2513     return 0;
2514 }
2515
2516
2517 /**
2518  * Send a device-specific read command.
2519  *
2520  * \param fd file descriptor.
2521  * \param drmCommandIndex command index
2522  * \param data destination pointer of the data to be read.
2523  * \param size size of the data to be read.
2524  *
2525  * \return zero on success, or a negative value on failure.
2526  *
2527  * \internal
2528  * It issues a read ioctl given by
2529  * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2530  */
2531 int drmCommandRead(int fd, unsigned long drmCommandIndex, void *data,
2532                    unsigned long size)
2533 {
2534     unsigned long request;
2535
2536     request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
2537         DRM_COMMAND_BASE + drmCommandIndex, size);
2538
2539     if (drmIoctl(fd, request, data)) {
2540         return -errno;
2541     }
2542     return 0;
2543 }
2544
2545
2546 /**
2547  * Send a device-specific write command.
2548  *
2549  * \param fd file descriptor.
2550  * \param drmCommandIndex command index
2551  * \param data source pointer of the data to be written.
2552  * \param size size of the data to be written.
2553  *
2554  * \return zero on success, or a negative value on failure.
2555  *
2556  * \internal
2557  * It issues a write ioctl given by
2558  * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2559  */
2560 int drmCommandWrite(int fd, unsigned long drmCommandIndex, void *data,
2561                     unsigned long size)
2562 {
2563     unsigned long request;
2564
2565     request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
2566         DRM_COMMAND_BASE + drmCommandIndex, size);
2567
2568     if (drmIoctl(fd, request, data)) {
2569         return -errno;
2570     }
2571     return 0;
2572 }
2573
2574
2575 /**
2576  * Send a device-specific read-write command.
2577  *
2578  * \param fd file descriptor.
2579  * \param drmCommandIndex command index
2580  * \param data source pointer of the data to be read and written.
2581  * \param size size of the data to be read and written.
2582  *
2583  * \return zero on success, or a negative value on failure.
2584  *
2585  * \internal
2586  * It issues a read-write ioctl given by
2587  * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2588  */
2589 int drmCommandWriteRead(int fd, unsigned long drmCommandIndex, void *data,
2590                         unsigned long size)
2591 {
2592     unsigned long request;
2593
2594     request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
2595         DRM_COMMAND_BASE + drmCommandIndex, size);
2596
2597     if (drmIoctl(fd, request, data))
2598         return -errno;
2599     return 0;
2600 }
2601
2602 #define DRM_MAX_FDS 16
2603 static struct {
2604     char *BusID;
2605     int fd;
2606     int refcount;
2607     int type;
2608 } connection[DRM_MAX_FDS];
2609
2610 static int nr_fds = 0;
2611
2612 int drmOpenOnce(void *unused,
2613                 const char *BusID,
2614                 int *newlyopened)
2615 {
2616     return drmOpenOnceWithType(BusID, newlyopened, DRM_NODE_PRIMARY);
2617 }
2618
2619 int drmOpenOnceWithType(const char *BusID, int *newlyopened, int type)
2620 {
2621     int i;
2622     int fd;
2623
2624     for (i = 0; i < nr_fds; i++)
2625         if ((strcmp(BusID, connection[i].BusID) == 0) &&
2626             (connection[i].type == type)) {
2627             connection[i].refcount++;
2628             *newlyopened = 0;
2629             return connection[i].fd;
2630         }
2631
2632     fd = drmOpenWithType(NULL, BusID, type);
2633     if (fd < 0 || nr_fds == DRM_MAX_FDS)
2634         return fd;
2635
2636     connection[nr_fds].BusID = strdup(BusID);
2637     connection[nr_fds].fd = fd;
2638     connection[nr_fds].refcount = 1;
2639     connection[nr_fds].type = type;
2640     *newlyopened = 1;
2641
2642     if (0)
2643         fprintf(stderr, "saved connection %d for %s %d\n",
2644                 nr_fds, connection[nr_fds].BusID,
2645                 strcmp(BusID, connection[nr_fds].BusID));
2646
2647     nr_fds++;
2648
2649     return fd;
2650 }
2651
2652 void drmCloseOnce(int fd)
2653 {
2654     int i;
2655
2656     for (i = 0; i < nr_fds; i++) {
2657         if (fd == connection[i].fd) {
2658             if (--connection[i].refcount == 0) {
2659                 drmClose(connection[i].fd);
2660                 free(connection[i].BusID);
2661
2662                 if (i < --nr_fds)
2663                     connection[i] = connection[nr_fds];
2664
2665                 return;
2666             }
2667         }
2668     }
2669 }
2670
2671 int drmSetMaster(int fd)
2672 {
2673         return drmIoctl(fd, DRM_IOCTL_SET_MASTER, NULL);
2674 }
2675
2676 int drmDropMaster(int fd)
2677 {
2678         return drmIoctl(fd, DRM_IOCTL_DROP_MASTER, NULL);
2679 }
2680
2681 char *drmGetDeviceNameFromFd(int fd)
2682 {
2683     char name[128];
2684     struct stat sbuf;
2685     dev_t d;
2686     int i;
2687
2688     /* The whole drmOpen thing is a fiasco and we need to find a way
2689      * back to just using open(2).  For now, however, lets just make
2690      * things worse with even more ad hoc directory walking code to
2691      * discover the device file name. */
2692
2693     fstat(fd, &sbuf);
2694     d = sbuf.st_rdev;
2695
2696     for (i = 0; i < DRM_MAX_MINOR; i++) {
2697         snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
2698         if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
2699             break;
2700     }
2701     if (i == DRM_MAX_MINOR)
2702         return NULL;
2703
2704     return strdup(name);
2705 }
2706
2707 int drmGetNodeTypeFromFd(int fd)
2708 {
2709     struct stat sbuf;
2710     int maj, min, type;
2711
2712     if (fstat(fd, &sbuf))
2713         return -1;
2714
2715     maj = major(sbuf.st_rdev);
2716     min = minor(sbuf.st_rdev);
2717
2718     if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode)) {
2719         errno = EINVAL;
2720         return -1;
2721     }
2722
2723     type = drmGetMinorType(min);
2724     if (type == -1)
2725         errno = ENODEV;
2726     return type;
2727 }
2728
2729 int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags, int *prime_fd)
2730 {
2731     struct drm_prime_handle args;
2732     int ret;
2733
2734     memclear(args);
2735     args.fd = -1;
2736     args.handle = handle;
2737     args.flags = flags;
2738     ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
2739     if (ret)
2740         return ret;
2741
2742     *prime_fd = args.fd;
2743     return 0;
2744 }
2745
2746 int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
2747 {
2748     struct drm_prime_handle args;
2749     int ret;
2750
2751     memclear(args);
2752     args.fd = prime_fd;
2753     ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
2754     if (ret)
2755         return ret;
2756
2757     *handle = args.handle;
2758     return 0;
2759 }
2760
2761 static char *drmGetMinorNameForFD(int fd, int type)
2762 {
2763 #ifdef __linux__
2764     DIR *sysdir;
2765     struct dirent *pent, *ent;
2766     struct stat sbuf;
2767     const char *name = drmGetMinorName(type);
2768     int len;
2769     char dev_name[64], buf[64];
2770     long name_max;
2771     int maj, min;
2772
2773     if (!name)
2774         return NULL;
2775
2776     len = strlen(name);
2777
2778     if (fstat(fd, &sbuf))
2779         return NULL;
2780
2781     maj = major(sbuf.st_rdev);
2782     min = minor(sbuf.st_rdev);
2783
2784     if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
2785         return NULL;
2786
2787     snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
2788
2789     sysdir = opendir(buf);
2790     if (!sysdir)
2791         return NULL;
2792
2793     name_max = fpathconf(dirfd(sysdir), _PC_NAME_MAX);
2794     if (name_max == -1)
2795         goto out_close_dir;
2796
2797     pent = malloc(offsetof(struct dirent, d_name) + name_max + 1);
2798     if (pent == NULL)
2799          goto out_close_dir;
2800
2801     while (readdir_r(sysdir, pent, &ent) == 0 && ent != NULL) {
2802         if (strncmp(ent->d_name, name, len) == 0) {
2803             snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
2804                  ent->d_name);
2805
2806             free(pent);
2807             closedir(sysdir);
2808
2809             return strdup(dev_name);
2810         }
2811     }
2812
2813     free(pent);
2814
2815 out_close_dir:
2816     closedir(sysdir);
2817 #else
2818 #warning "Missing implementation of drmGetMinorNameForFD"
2819 #endif
2820     return NULL;
2821 }
2822
2823 char *drmGetPrimaryDeviceNameFromFd(int fd)
2824 {
2825     return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
2826 }
2827
2828 char *drmGetRenderDeviceNameFromFd(int fd)
2829 {
2830     return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
2831 }
2832
2833 static int drmParseSubsystemType(int maj, int min)
2834 {
2835 #ifdef __linux__
2836     char path[PATH_MAX + 1];
2837     char link[PATH_MAX + 1] = "";
2838     char *name;
2839
2840     snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/subsystem",
2841              maj, min);
2842
2843     if (readlink(path, link, PATH_MAX) < 0)
2844         return -errno;
2845
2846     name = strrchr(link, '/');
2847     if (!name)
2848         return -EINVAL;
2849
2850     if (strncmp(name, "/pci", 4) == 0)
2851         return DRM_BUS_PCI;
2852
2853     return -EINVAL;
2854 #else
2855 #warning "Missing implementation of drmParseSubsystemType"
2856     return -EINVAL;
2857 #endif
2858 }
2859
2860 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
2861 {
2862 #ifdef __linux__
2863     char path[PATH_MAX + 1];
2864     char data[128 + 1];
2865     char *str;
2866     int domain, bus, dev, func;
2867     int fd, ret;
2868
2869     snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/uevent", maj, min);
2870     fd = open(path, O_RDONLY);
2871     if (fd < 0)
2872         return -errno;
2873
2874     ret = read(fd, data, sizeof(data));
2875     data[128] = '\0';
2876     close(fd);
2877     if (ret < 0)
2878         return -errno;
2879
2880 #define TAG "PCI_SLOT_NAME="
2881     str = strstr(data, TAG);
2882     if (str == NULL)
2883         return -EINVAL;
2884
2885     if (sscanf(str, TAG "%04x:%02x:%02x.%1u",
2886                &domain, &bus, &dev, &func) != 4)
2887         return -EINVAL;
2888 #undef TAG
2889
2890     info->domain = domain;
2891     info->bus = bus;
2892     info->dev = dev;
2893     info->func = func;
2894
2895     return 0;
2896 #else
2897 #warning "Missing implementation of drmParsePciBusInfo"
2898     return -EINVAL;
2899 #endif
2900 }
2901
2902 static int drmCompareBusInfo(drmDevicePtr a, drmDevicePtr b)
2903 {
2904     if (a == NULL || b == NULL)
2905         return -1;
2906
2907     if (a->bustype != b->bustype)
2908         return -1;
2909
2910     switch (a->bustype) {
2911     case DRM_BUS_PCI:
2912         return memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo));
2913     default:
2914         break;
2915     }
2916
2917     return -1;
2918 }
2919
2920 static int drmGetNodeType(const char *name)
2921 {
2922     if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
2923         sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
2924         return DRM_NODE_PRIMARY;
2925
2926     if (strncmp(name, DRM_CONTROL_MINOR_NAME,
2927         sizeof(DRM_CONTROL_MINOR_NAME ) - 1) == 0)
2928         return DRM_NODE_CONTROL;
2929
2930     if (strncmp(name, DRM_RENDER_MINOR_NAME,
2931         sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
2932         return DRM_NODE_RENDER;
2933
2934     return -EINVAL;
2935 }
2936
2937 static int drmGetMaxNodeName(void)
2938 {
2939     return sizeof(DRM_DIR_NAME) +
2940            MAX3(sizeof(DRM_PRIMARY_MINOR_NAME),
2941                 sizeof(DRM_CONTROL_MINOR_NAME),
2942                 sizeof(DRM_RENDER_MINOR_NAME)) +
2943            3 /* length of the node number */;
2944 }
2945
2946 static int drmParsePciDeviceInfo(const char *d_name,
2947                                  drmPciDeviceInfoPtr device)
2948 {
2949 #ifdef __linux__
2950     char path[PATH_MAX + 1];
2951     unsigned char config[64];
2952     int fd, ret;
2953
2954     snprintf(path, PATH_MAX, "/sys/class/drm/%s/device/config", d_name);
2955     fd = open(path, O_RDONLY);
2956     if (fd < 0)
2957         return -errno;
2958
2959     ret = read(fd, config, sizeof(config));
2960     close(fd);
2961     if (ret < 0)
2962         return -errno;
2963
2964     device->vendor_id = config[0] | (config[1] << 8);
2965     device->device_id = config[2] | (config[3] << 8);
2966     device->revision_id = config[8];
2967     device->subvendor_id = config[44] | (config[45] << 8);
2968     device->subdevice_id = config[46] | (config[47] << 8);
2969
2970     return 0;
2971 #else
2972 #warning "Missing implementation of drmParsePciDeviceInfo"
2973     return -EINVAL;
2974 #endif
2975 }
2976
2977 void drmFreeDevice(drmDevicePtr *device)
2978 {
2979     if (device == NULL)
2980         return;
2981
2982     free(*device);
2983     *device = NULL;
2984 }
2985
2986 void drmFreeDevices(drmDevicePtr devices[], int count)
2987 {
2988     int i;
2989
2990     if (devices == NULL)
2991         return;
2992
2993     for (i = 0; i < count && devices[i] != NULL; i++)
2994         drmFreeDevice(&devices[i]);
2995 }
2996
2997 static int drmProcessPciDevice(drmDevicePtr *device, const char *d_name,
2998                                const char *node, int node_type,
2999                                int maj, int min, bool fetch_deviceinfo)
3000 {
3001     const int max_node_str = ALIGN(drmGetMaxNodeName(), sizeof(void *));
3002     int ret, i;
3003     char *addr;
3004
3005     *device = calloc(1, sizeof(drmDevice) +
3006                      (DRM_NODE_MAX * (sizeof(void *) + max_node_str)) +
3007                      sizeof(drmPciBusInfo) +
3008                      sizeof(drmPciDeviceInfo));
3009     if (!*device)
3010         return -ENOMEM;
3011
3012     addr = (char*)*device;
3013
3014     (*device)->bustype = DRM_BUS_PCI;
3015     (*device)->available_nodes = 1 << node_type;
3016
3017     addr += sizeof(drmDevice);
3018     (*device)->nodes = (char**)addr;
3019
3020     addr += DRM_NODE_MAX * sizeof(void *);
3021     for (i = 0; i < DRM_NODE_MAX; i++) {
3022         (*device)->nodes[i] = addr;
3023         addr += max_node_str;
3024     }
3025     memcpy((*device)->nodes[node_type], node, max_node_str);
3026
3027     (*device)->businfo.pci = (drmPciBusInfoPtr)addr;
3028
3029     ret = drmParsePciBusInfo(maj, min, (*device)->businfo.pci);
3030     if (ret)
3031         goto free_device;
3032
3033     // Fetch the device info if the user has requested it
3034     if (fetch_deviceinfo) {
3035         addr += sizeof(drmPciBusInfo);
3036         (*device)->deviceinfo.pci = (drmPciDeviceInfoPtr)addr;
3037
3038         ret = drmParsePciDeviceInfo(d_name, (*device)->deviceinfo.pci);
3039         if (ret)
3040             goto free_device;
3041     }
3042     return 0;
3043
3044 free_device:
3045     free(*device);
3046     *device = NULL;
3047     return ret;
3048 }
3049
3050 static void drmFoldDuplicatedDevices(drmDevicePtr local_devices[], int count)
3051 {
3052     int node_type, i, j;
3053
3054     for (i = 0; i < count; i++) {
3055         for (j = i + 1; j < count; j++) {
3056             if (drmCompareBusInfo(local_devices[i], local_devices[j]) == 0) {
3057                 local_devices[i]->available_nodes |= local_devices[j]->available_nodes;
3058                 node_type = log2(local_devices[j]->available_nodes);
3059                 memcpy(local_devices[i]->nodes[node_type],
3060                        local_devices[j]->nodes[node_type], drmGetMaxNodeName());
3061                 drmFreeDevice(&local_devices[j]);
3062             }
3063         }
3064     }
3065 }
3066
3067 /**
3068  * Get information about the opened drm device
3069  *
3070  * \param fd file descriptor of the drm device
3071  * \param device the address of a drmDevicePtr where the information
3072  *               will be allocated in stored
3073  *
3074  * \return zero on success, negative error code otherwise.
3075  */
3076 int drmGetDevice(int fd, drmDevicePtr *device)
3077 {
3078     drmDevicePtr *local_devices;
3079     drmDevicePtr d;
3080     DIR *sysdir;
3081     struct dirent *dent;
3082     struct stat sbuf;
3083     char node[PATH_MAX + 1];
3084     int node_type, subsystem_type;
3085     int maj, min;
3086     int ret, i, node_count;
3087     int max_count = 16;
3088
3089     if (fd == -1 || device == NULL)
3090         return -EINVAL;
3091
3092     if (fstat(fd, &sbuf))
3093         return -errno;
3094
3095     maj = major(sbuf.st_rdev);
3096     min = minor(sbuf.st_rdev);
3097
3098     if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3099         return -EINVAL;
3100
3101     subsystem_type = drmParseSubsystemType(maj, min);
3102
3103     local_devices = calloc(max_count, sizeof(drmDevicePtr));
3104     if (local_devices == NULL)
3105         return -ENOMEM;
3106
3107     sysdir = opendir(DRM_DIR_NAME);
3108     if (!sysdir) {
3109         ret = -errno;
3110         goto free_locals;
3111     }
3112
3113     i = 0;
3114     while ((dent = readdir(sysdir))) {
3115         node_type = drmGetNodeType(dent->d_name);
3116         if (node_type < 0)
3117             continue;
3118
3119         snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, dent->d_name);
3120         if (stat(node, &sbuf))
3121             continue;
3122
3123         maj = major(sbuf.st_rdev);
3124         min = minor(sbuf.st_rdev);
3125
3126         if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3127             continue;
3128
3129         if (drmParseSubsystemType(maj, min) != subsystem_type)
3130             continue;
3131
3132         switch (subsystem_type) {
3133         case DRM_BUS_PCI:
3134             ret = drmProcessPciDevice(&d, dent->d_name, node, node_type,
3135                                       maj, min, true);
3136             if (ret)
3137                 goto free_devices;
3138
3139             break;
3140         default:
3141             fprintf(stderr, "The subsystem type is not supported yet\n");
3142             continue;
3143         }
3144
3145         if (i >= max_count) {
3146             drmDevicePtr *temp;
3147
3148             max_count += 16;
3149             temp = realloc(local_devices, max_count * sizeof(drmDevicePtr));
3150             if (!temp)
3151                 goto free_devices;
3152             local_devices = temp;
3153         }
3154
3155         local_devices[i] = d;
3156         i++;
3157     }
3158     node_count = i;
3159
3160     /* Fold nodes into a single device if they share the same bus info */
3161     drmFoldDuplicatedDevices(local_devices, node_count);
3162
3163     *device = local_devices[0];
3164     for (i = 1; i < node_count && local_devices[i]; i++)
3165             drmFreeDevice(&local_devices[i]);
3166
3167     closedir(sysdir);
3168     free(local_devices);
3169     return 0;
3170
3171 free_devices:
3172     drmFreeDevices(local_devices, i);
3173     closedir(sysdir);
3174
3175 free_locals:
3176     free(local_devices);
3177     return ret;
3178 }
3179
3180 /**
3181  * Get drm devices on the system
3182  *
3183  * \param devices the array of devices with drmDevicePtr elements
3184  *                can be NULL to get the device number first
3185  * \param max_devices the maximum number of devices for the array
3186  *
3187  * \return on error - negative error code,
3188  *         if devices is NULL - total number of devices available on the system,
3189  *         alternatively the number of devices stored in devices[], which is
3190  *         capped by the max_devices.
3191  */
3192 int drmGetDevices(drmDevicePtr devices[], int max_devices)
3193 {
3194     drmDevicePtr *local_devices;
3195     drmDevicePtr device;
3196     DIR *sysdir;
3197     struct dirent *dent;
3198     struct stat sbuf;
3199     char node[PATH_MAX + 1];
3200     int node_type, subsystem_type;
3201     int maj, min;
3202     int ret, i, node_count, device_count;
3203     int max_count = 16;
3204
3205     local_devices = calloc(max_count, sizeof(drmDevicePtr));
3206     if (local_devices == NULL)
3207         return -ENOMEM;
3208
3209     sysdir = opendir(DRM_DIR_NAME);
3210     if (!sysdir) {
3211         ret = -errno;
3212         goto free_locals;
3213     }
3214
3215     i = 0;
3216     while ((dent = readdir(sysdir))) {
3217         node_type = drmGetNodeType(dent->d_name);
3218         if (node_type < 0)
3219             continue;
3220
3221         snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, dent->d_name);
3222         if (stat(node, &sbuf))
3223             continue;
3224
3225         maj = major(sbuf.st_rdev);
3226         min = minor(sbuf.st_rdev);
3227
3228         if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3229             continue;
3230
3231         subsystem_type = drmParseSubsystemType(maj, min);
3232
3233         if (subsystem_type < 0)
3234             continue;
3235
3236         switch (subsystem_type) {
3237         case DRM_BUS_PCI:
3238             ret = drmProcessPciDevice(&device, dent->d_name, node, node_type,
3239                                       maj, min, devices != NULL);
3240             if (ret)
3241                 goto free_devices;
3242
3243             break;
3244         default:
3245             fprintf(stderr, "The subsystem type is not supported yet\n");
3246             continue;
3247         }
3248
3249         if (i >= max_count) {
3250             drmDevicePtr *temp;
3251
3252             max_count += 16;
3253             temp = realloc(local_devices, max_count * sizeof(drmDevicePtr));
3254             if (!temp)
3255                 goto free_devices;
3256             local_devices = temp;
3257         }
3258
3259         local_devices[i] = device;
3260         i++;
3261     }
3262     node_count = i;
3263
3264     /* Fold nodes into a single device if they share the same bus info */
3265     drmFoldDuplicatedDevices(local_devices, node_count);
3266
3267     device_count = 0;
3268     for (i = 0; i < node_count; i++) {
3269         if (!local_devices[i])
3270             continue;
3271
3272         if ((devices != NULL) && (device_count < max_devices))
3273             devices[device_count] = local_devices[i];
3274         else
3275             drmFreeDevice(&local_devices[i]);
3276
3277         device_count++;
3278     }
3279
3280     closedir(sysdir);
3281     free(local_devices);
3282     return device_count;
3283
3284 free_devices:
3285     drmFreeDevices(local_devices, i);
3286     closedir(sysdir);
3287
3288 free_locals:
3289     free(local_devices);
3290     return ret;
3291 }