OSDN Git Service

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