OSDN Git Service

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