OSDN Git Service

drm: fix the usage after free
[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 <unistd.h>
40 #include <string.h>
41 #include <strings.h>
42 #include <ctype.h>
43 #include <dirent.h>
44 #include <stddef.h>
45 #include <fcntl.h>
46 #include <errno.h>
47 #include <signal.h>
48 #include <time.h>
49 #include <sys/types.h>
50 #include <sys/stat.h>
51 #define stat_t struct stat
52 #include <sys/ioctl.h>
53 #include <sys/time.h>
54 #include <stdarg.h>
55 #ifdef HAVE_SYS_MKDEV_H
56 # include <sys/mkdev.h> /* defines major(), minor(), and makedev() on Solaris */
57 #endif
58
59 /* Not all systems have MAP_FAILED defined */
60 #ifndef MAP_FAILED
61 #define MAP_FAILED ((void *)-1)
62 #endif
63
64 #include "xf86drm.h"
65 #include "libdrm_macros.h"
66
67 #ifdef __OpenBSD__
68 #define DRM_PRIMARY_MINOR_NAME  "drm"
69 #define DRM_CONTROL_MINOR_NAME  "drmC"
70 #define DRM_RENDER_MINOR_NAME   "drmR"
71 #else
72 #define DRM_PRIMARY_MINOR_NAME  "card"
73 #define DRM_CONTROL_MINOR_NAME  "controlD"
74 #define DRM_RENDER_MINOR_NAME   "renderD"
75 #endif
76
77 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
78 #define DRM_MAJOR 145
79 #endif
80
81 #ifdef __NetBSD__
82 #define DRM_MAJOR 34
83 #endif
84
85 #ifdef __OpenBSD__
86 #ifdef __i386__
87 #define DRM_MAJOR 88
88 #else
89 #define DRM_MAJOR 87
90 #endif
91 #endif /* __OpenBSD__ */
92
93 #ifndef DRM_MAJOR
94 #define DRM_MAJOR 226           /* Linux */
95 #endif
96
97 /*
98  * This definition needs to be changed on some systems if dev_t is a structure.
99  * If there is a header file we can get it from, there would be best.
100  */
101 #ifndef makedev
102 #define makedev(x,y)    ((dev_t)(((x) << 8) | (y)))
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")) || drm_server_info)
137     {
138         va_start(ap, format);
139         if (drm_server_info) {
140           drm_server_info->debug_print(format,ap);
141         } else {
142           drmDebugPrint(format, ap);
143         }
144         va_end(ap);
145     }
146 }
147
148 static void *drmHashTable = NULL; /* Context switch callbacks */
149
150 void *drmGetHashTable(void)
151 {
152     return drmHashTable;
153 }
154
155 void *drmMalloc(int size)
156 {
157     return calloc(1, size);
158 }
159
160 void drmFree(void *pt)
161 {
162     free(pt);
163 }
164
165 /**
166  * Call ioctl, restarting if it is interupted
167  */
168 int
169 drmIoctl(int fd, unsigned long request, void *arg)
170 {
171     int ret;
172
173     do {
174         ret = ioctl(fd, request, arg);
175     } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
176     return ret;
177 }
178
179 static unsigned long drmGetKeyFromFd(int fd)
180 {
181     stat_t     st;
182
183     st.st_rdev = 0;
184     fstat(fd, &st);
185     return st.st_rdev;
186 }
187
188 drmHashEntry *drmGetEntry(int fd)
189 {
190     unsigned long key = drmGetKeyFromFd(fd);
191     void          *value;
192     drmHashEntry  *entry;
193
194     if (!drmHashTable)
195         drmHashTable = drmHashCreate();
196
197     if (drmHashLookup(drmHashTable, key, &value)) {
198         entry           = drmMalloc(sizeof(*entry));
199         entry->fd       = fd;
200         entry->f        = NULL;
201         entry->tagTable = drmHashCreate();
202         drmHashInsert(drmHashTable, key, entry);
203     } else {
204         entry = value;
205     }
206     return entry;
207 }
208
209 /**
210  * Compare two busid strings
211  *
212  * \param first
213  * \param second
214  *
215  * \return 1 if matched.
216  *
217  * \internal
218  * This function compares two bus ID strings.  It understands the older
219  * PCI:b:d:f format and the newer pci:oooo:bb:dd.f format.  In the format, o is
220  * domain, b is bus, d is device, f is function.
221  */
222 static int drmMatchBusID(const char *id1, const char *id2, int pci_domain_ok)
223 {
224     /* First, check if the IDs are exactly the same */
225     if (strcasecmp(id1, id2) == 0)
226         return 1;
227
228     /* Try to match old/new-style PCI bus IDs. */
229     if (strncasecmp(id1, "pci", 3) == 0) {
230         unsigned int o1, b1, d1, f1;
231         unsigned int o2, b2, d2, f2;
232         int ret;
233
234         ret = sscanf(id1, "pci:%04x:%02x:%02x.%u", &o1, &b1, &d1, &f1);
235         if (ret != 4) {
236             o1 = 0;
237             ret = sscanf(id1, "PCI:%u:%u:%u", &b1, &d1, &f1);
238             if (ret != 3)
239                 return 0;
240         }
241
242         ret = sscanf(id2, "pci:%04x:%02x:%02x.%u", &o2, &b2, &d2, &f2);
243         if (ret != 4) {
244             o2 = 0;
245             ret = sscanf(id2, "PCI:%u:%u:%u", &b2, &d2, &f2);
246             if (ret != 3)
247                 return 0;
248         }
249
250         /* If domains aren't properly supported by the kernel interface,
251          * just ignore them, which sucks less than picking a totally random
252          * card with "open by name"
253          */
254         if (!pci_domain_ok)
255                 o1 = o2 = 0;
256
257         if ((o1 != o2) || (b1 != b2) || (d1 != d2) || (f1 != f2))
258             return 0;
259         else
260             return 1;
261     }
262     return 0;
263 }
264
265 /**
266  * Handles error checking for chown call.
267  *
268  * \param path to file.
269  * \param id of the new owner.
270  * \param id of the new group.
271  *
272  * \return zero if success or -1 if failure.
273  *
274  * \internal
275  * Checks for failure. If failure was caused by signal call chown again.
276  * If any other failure happened then it will output error mesage using
277  * drmMsg() call.
278  */
279 #if !defined(UDEV)
280 static int chown_check_return(const char *path, uid_t owner, gid_t group)
281 {
282         int rv;
283
284         do {
285                 rv = chown(path, owner, group);
286         } while (rv != 0 && errno == EINTR);
287
288         if (rv == 0)
289                 return 0;
290
291         drmMsg("Failed to change owner or group for file %s! %d: %s\n",
292                         path, errno, strerror(errno));
293         return -1;
294 }
295 #endif
296
297 /**
298  * Open the DRM device, creating it if necessary.
299  *
300  * \param dev major and minor numbers of the device.
301  * \param minor minor number of the device.
302  * 
303  * \return a file descriptor on success, or a negative value on error.
304  *
305  * \internal
306  * Assembles the device name from \p minor and opens it, creating the device
307  * special file node with the major and minor numbers specified by \p dev and
308  * parent directory if necessary and was called by root.
309  */
310 static int drmOpenDevice(dev_t dev, int minor, int type)
311 {
312     stat_t          st;
313     const char      *dev_name;
314     char            buf[64];
315     int             fd;
316     mode_t          devmode = DRM_DEV_MODE, serv_mode;
317     gid_t           serv_group;
318 #if !defined(UDEV)
319     int             isroot  = !geteuid();
320     uid_t           user    = DRM_DEV_UID;
321     gid_t           group   = DRM_DEV_GID;
322 #endif
323
324     switch (type) {
325     case DRM_NODE_PRIMARY:
326             dev_name = DRM_DEV_NAME;
327             break;
328     case DRM_NODE_CONTROL:
329             dev_name = DRM_CONTROL_DEV_NAME;
330             break;
331     case DRM_NODE_RENDER:
332             dev_name = DRM_RENDER_DEV_NAME;
333             break;
334     default:
335             return -EINVAL;
336     };
337
338     sprintf(buf, dev_name, DRM_DIR_NAME, minor);
339     drmMsg("drmOpenDevice: node name is %s\n", buf);
340
341     if (drm_server_info) {
342         drm_server_info->get_perms(&serv_group, &serv_mode);
343         devmode  = serv_mode ? serv_mode : DRM_DEV_MODE;
344         devmode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
345     }
346
347 #if !defined(UDEV)
348     if (stat(DRM_DIR_NAME, &st)) {
349         if (!isroot)
350             return DRM_ERR_NOT_ROOT;
351         mkdir(DRM_DIR_NAME, DRM_DEV_DIRMODE);
352         chown_check_return(DRM_DIR_NAME, 0, 0); /* root:root */
353         chmod(DRM_DIR_NAME, DRM_DEV_DIRMODE);
354     }
355
356     /* Check if the device node exists and create it if necessary. */
357     if (stat(buf, &st)) {
358         if (!isroot)
359             return DRM_ERR_NOT_ROOT;
360         remove(buf);
361         mknod(buf, S_IFCHR | devmode, dev);
362     }
363
364     if (drm_server_info) {
365         group = ((int)serv_group >= 0) ? serv_group : DRM_DEV_GID;
366         chown_check_return(buf, user, group);
367         chmod(buf, devmode);
368     }
369 #else
370     /* if we modprobed then wait for udev */
371     {
372         int udev_count = 0;
373 wait_for_udev:
374         if (stat(DRM_DIR_NAME, &st)) {
375                 usleep(20);
376                 udev_count++;
377
378                 if (udev_count == 50)
379                         return -1;
380                 goto wait_for_udev;
381         }
382
383         if (stat(buf, &st)) {
384                 usleep(20);
385                 udev_count++;
386
387                 if (udev_count == 50)
388                         return -1;
389                 goto wait_for_udev;
390         }
391     }
392 #endif
393
394     fd = open(buf, O_RDWR, 0);
395     drmMsg("drmOpenDevice: open result is %d, (%s)\n",
396                 fd, fd < 0 ? strerror(errno) : "OK");
397     if (fd >= 0)
398         return fd;
399
400 #if !defined(UDEV)
401     /* Check if the device node is not what we expect it to be, and recreate it
402      * and try again if so.
403      */
404     if (st.st_rdev != dev) {
405         if (!isroot)
406             return DRM_ERR_NOT_ROOT;
407         remove(buf);
408         mknod(buf, S_IFCHR | devmode, dev);
409         if (drm_server_info) {
410             chown_check_return(buf, user, group);
411             chmod(buf, devmode);
412         }
413     }
414     fd = open(buf, O_RDWR, 0);
415     drmMsg("drmOpenDevice: open result is %d, (%s)\n",
416                 fd, fd < 0 ? strerror(errno) : "OK");
417     if (fd >= 0)
418         return fd;
419
420     drmMsg("drmOpenDevice: Open failed\n");
421     remove(buf);
422 #endif
423     return -errno;
424 }
425
426
427 /**
428  * Open the DRM device
429  *
430  * \param minor device minor number.
431  * \param create allow to create the device if set.
432  *
433  * \return a file descriptor on success, or a negative value on error.
434  * 
435  * \internal
436  * Calls drmOpenDevice() if \p create is set, otherwise assembles the device
437  * name from \p minor and opens it.
438  */
439 static int drmOpenMinor(int minor, int create, int type)
440 {
441     int  fd;
442     char buf[64];
443     const char *dev_name;
444     
445     if (create)
446         return drmOpenDevice(makedev(DRM_MAJOR, minor), minor, type);
447     
448     switch (type) {
449     case DRM_NODE_PRIMARY:
450             dev_name = DRM_DEV_NAME;
451             break;
452     case DRM_NODE_CONTROL:
453             dev_name = DRM_CONTROL_DEV_NAME;
454             break;
455     case DRM_NODE_RENDER:
456             dev_name = DRM_RENDER_DEV_NAME;
457             break;
458     default:
459             return -EINVAL;
460     };
461
462     sprintf(buf, dev_name, DRM_DIR_NAME, minor);
463     if ((fd = open(buf, O_RDWR, 0)) >= 0)
464         return fd;
465     return -errno;
466 }
467
468
469 /**
470  * Determine whether the DRM kernel driver has been loaded.
471  * 
472  * \return 1 if the DRM driver is loaded, 0 otherwise.
473  *
474  * \internal 
475  * Determine the presence of the kernel driver by attempting to open the 0
476  * minor and get version information.  For backward compatibility with older
477  * Linux implementations, /proc/dri is also checked.
478  */
479 int drmAvailable(void)
480 {
481     drmVersionPtr version;
482     int           retval = 0;
483     int           fd;
484
485     if ((fd = drmOpenMinor(0, 1, DRM_NODE_PRIMARY)) < 0) {
486 #ifdef __linux__
487         /* Try proc for backward Linux compatibility */
488         if (!access("/proc/dri/0", R_OK))
489             return 1;
490 #endif
491         return 0;
492     }
493     
494     if ((version = drmGetVersion(fd))) {
495         retval = 1;
496         drmFreeVersion(version);
497     }
498     close(fd);
499
500     return retval;
501 }
502
503 static int drmGetMinorBase(int type)
504 {
505     switch (type) {
506     case DRM_NODE_PRIMARY:
507         return 0;
508     case DRM_NODE_CONTROL:
509         return 64;
510     case DRM_NODE_RENDER:
511         return 128;
512     default:
513         return -1;
514     };
515 }
516
517 static int drmGetMinorType(int minor)
518 {
519     int type = minor >> 6;
520
521     if (minor < 0)
522         return -1;
523
524     switch (type) {
525     case DRM_NODE_PRIMARY:
526     case DRM_NODE_CONTROL:
527     case DRM_NODE_RENDER:
528         return type;
529     default:
530         return -1;
531     }
532 }
533
534 static const char *drmGetMinorName(int type)
535 {
536     switch (type) {
537     case DRM_NODE_PRIMARY:
538         return DRM_PRIMARY_MINOR_NAME;
539     case DRM_NODE_CONTROL:
540         return DRM_CONTROL_MINOR_NAME;
541     case DRM_NODE_RENDER:
542         return DRM_RENDER_MINOR_NAME;
543     default:
544         return NULL;
545     }
546 }
547
548 /**
549  * Open the device by bus ID.
550  *
551  * \param busid bus ID.
552  * \param type device node type.
553  *
554  * \return a file descriptor on success, or a negative value on error.
555  *
556  * \internal
557  * This function attempts to open every possible minor (up to DRM_MAX_MINOR),
558  * comparing the device bus ID with the one supplied.
559  *
560  * \sa drmOpenMinor() and drmGetBusid().
561  */
562 static int drmOpenByBusid(const char *busid, int type)
563 {
564     int        i, pci_domain_ok = 1;
565     int        fd;
566     const char *buf;
567     drmSetVersion sv;
568     int        base = drmGetMinorBase(type);
569
570     if (base < 0)
571         return -1;
572
573     drmMsg("drmOpenByBusid: Searching for BusID %s\n", busid);
574     for (i = base; i < base + DRM_MAX_MINOR; i++) {
575         fd = drmOpenMinor(i, 1, type);
576         drmMsg("drmOpenByBusid: drmOpenMinor returns %d\n", fd);
577         if (fd >= 0) {
578             /* We need to try for 1.4 first for proper PCI domain support
579              * and if that fails, we know the kernel is busted
580              */
581             sv.drm_di_major = 1;
582             sv.drm_di_minor = 4;
583             sv.drm_dd_major = -1;       /* Don't care */
584             sv.drm_dd_minor = -1;       /* Don't care */
585             if (drmSetInterfaceVersion(fd, &sv)) {
586 #ifndef __alpha__
587                 pci_domain_ok = 0;
588 #endif
589                 sv.drm_di_major = 1;
590                 sv.drm_di_minor = 1;
591                 sv.drm_dd_major = -1;       /* Don't care */
592                 sv.drm_dd_minor = -1;       /* Don't care */
593                 drmMsg("drmOpenByBusid: Interface 1.4 failed, trying 1.1\n");
594                 drmSetInterfaceVersion(fd, &sv);
595             }
596             buf = drmGetBusid(fd);
597             drmMsg("drmOpenByBusid: drmGetBusid reports %s\n", buf);
598             if (buf && drmMatchBusID(buf, busid, pci_domain_ok)) {
599                 drmFreeBusid(buf);
600                 return fd;
601             }
602             if (buf)
603                 drmFreeBusid(buf);
604             close(fd);
605         }
606     }
607     return -1;
608 }
609
610
611 /**
612  * Open the device by name.
613  *
614  * \param name driver name.
615  * \param type the device node type.
616  * 
617  * \return a file descriptor on success, or a negative value on error.
618  * 
619  * \internal
620  * This function opens the first minor number that matches the driver name and
621  * isn't already in use.  If it's in use it then it will already have a bus ID
622  * assigned.
623  * 
624  * \sa drmOpenMinor(), drmGetVersion() and drmGetBusid().
625  */
626 static int drmOpenByName(const char *name, int type)
627 {
628     int           i;
629     int           fd;
630     drmVersionPtr version;
631     char *        id;
632     int           base = drmGetMinorBase(type);
633
634     if (base < 0)
635         return -1;
636
637     /*
638      * Open the first minor number that matches the driver name and isn't
639      * already in use.  If it's in use it will have a busid assigned already.
640      */
641     for (i = base; i < base + DRM_MAX_MINOR; i++) {
642         if ((fd = drmOpenMinor(i, 1, type)) >= 0) {
643             if ((version = drmGetVersion(fd))) {
644                 if (!strcmp(version->name, name)) {
645                     drmFreeVersion(version);
646                     id = drmGetBusid(fd);
647                     drmMsg("drmGetBusid returned '%s'\n", id ? id : "NULL");
648                     if (!id || !*id) {
649                         if (id)
650                             drmFreeBusid(id);
651                         return fd;
652                     } else {
653                         drmFreeBusid(id);
654                     }
655                 } else {
656                     drmFreeVersion(version);
657                 }
658             }
659             close(fd);
660         }
661     }
662
663 #ifdef __linux__
664     /* Backward-compatibility /proc support */
665     for (i = 0; i < 8; i++) {
666         char proc_name[64], buf[512];
667         char *driver, *pt, *devstring;
668         int  retcode;
669         
670         sprintf(proc_name, "/proc/dri/%d/name", i);
671         if ((fd = open(proc_name, 0, 0)) >= 0) {
672             retcode = read(fd, buf, sizeof(buf)-1);
673             close(fd);
674             if (retcode) {
675                 buf[retcode-1] = '\0';
676                 for (driver = pt = buf; *pt && *pt != ' '; ++pt)
677                     ;
678                 if (*pt) { /* Device is next */
679                     *pt = '\0';
680                     if (!strcmp(driver, name)) { /* Match */
681                         for (devstring = ++pt; *pt && *pt != ' '; ++pt)
682                             ;
683                         if (*pt) { /* Found busid */
684                             return drmOpenByBusid(++pt, type);
685                         } else { /* No busid */
686                             return drmOpenDevice(strtol(devstring, NULL, 0),i, type);
687                         }
688                     }
689                 }
690             }
691         }
692     }
693 #endif
694
695     return -1;
696 }
697
698
699 /**
700  * Open the DRM device.
701  *
702  * Looks up the specified name and bus ID, and opens the device found.  The
703  * entry in /dev/dri is created if necessary and if called by root.
704  *
705  * \param name driver name. Not referenced if bus ID is supplied.
706  * \param busid bus ID. Zero if not known.
707  * 
708  * \return a file descriptor on success, or a negative value on error.
709  * 
710  * \internal
711  * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
712  * otherwise.
713  */
714 int drmOpen(const char *name, const char *busid)
715 {
716     return drmOpenWithType(name, busid, DRM_NODE_PRIMARY);
717 }
718
719 /**
720  * Open the DRM device with specified type.
721  *
722  * Looks up the specified name and bus ID, and opens the device found.  The
723  * entry in /dev/dri is created if necessary and if called by root.
724  *
725  * \param name driver name. Not referenced if bus ID is supplied.
726  * \param busid bus ID. Zero if not known.
727  * \param type the device node type to open, PRIMARY, CONTROL or RENDER
728  *
729  * \return a file descriptor on success, or a negative value on error.
730  *
731  * \internal
732  * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
733  * otherwise.
734  */
735 int drmOpenWithType(const char *name, const char *busid, int type)
736 {
737     if (!drmAvailable() && name != NULL && drm_server_info) {
738         /* try to load the kernel module */
739         if (!drm_server_info->load_module(name)) {
740             drmMsg("[drm] failed to load kernel module \"%s\"\n", name);
741             return -1;
742         }
743     }
744
745     if (busid) {
746         int fd = drmOpenByBusid(busid, type);
747         if (fd >= 0)
748             return fd;
749     }
750     
751     if (name)
752         return drmOpenByName(name, type);
753
754     return -1;
755 }
756
757 int drmOpenControl(int minor)
758 {
759     return drmOpenMinor(minor, 0, DRM_NODE_CONTROL);
760 }
761
762 int drmOpenRender(int minor)
763 {
764     return drmOpenMinor(minor, 0, DRM_NODE_RENDER);
765 }
766
767 /**
768  * Free the version information returned by drmGetVersion().
769  *
770  * \param v pointer to the version information.
771  *
772  * \internal
773  * It frees the memory pointed by \p %v as well as all the non-null strings
774  * pointers in it.
775  */
776 void drmFreeVersion(drmVersionPtr v)
777 {
778     if (!v)
779         return;
780     drmFree(v->name);
781     drmFree(v->date);
782     drmFree(v->desc);
783     drmFree(v);
784 }
785
786
787 /**
788  * Free the non-public version information returned by the kernel.
789  *
790  * \param v pointer to the version information.
791  *
792  * \internal
793  * Used by drmGetVersion() to free the memory pointed by \p %v as well as all
794  * the non-null strings pointers in it.
795  */
796 static void drmFreeKernelVersion(drm_version_t *v)
797 {
798     if (!v)
799         return;
800     drmFree(v->name);
801     drmFree(v->date);
802     drmFree(v->desc);
803     drmFree(v);
804 }
805
806
807 /**
808  * Copy version information.
809  * 
810  * \param d destination pointer.
811  * \param s source pointer.
812  * 
813  * \internal
814  * Used by drmGetVersion() to translate the information returned by the ioctl
815  * interface in a private structure into the public structure counterpart.
816  */
817 static void drmCopyVersion(drmVersionPtr d, const drm_version_t *s)
818 {
819     d->version_major      = s->version_major;
820     d->version_minor      = s->version_minor;
821     d->version_patchlevel = s->version_patchlevel;
822     d->name_len           = s->name_len;
823     d->name               = strdup(s->name);
824     d->date_len           = s->date_len;
825     d->date               = strdup(s->date);
826     d->desc_len           = s->desc_len;
827     d->desc               = strdup(s->desc);
828 }
829
830
831 /**
832  * Query the driver version information.
833  *
834  * \param fd file descriptor.
835  * 
836  * \return pointer to a drmVersion structure which should be freed with
837  * drmFreeVersion().
838  * 
839  * \note Similar information is available via /proc/dri.
840  * 
841  * \internal
842  * It gets the version information via successive DRM_IOCTL_VERSION ioctls,
843  * first with zeros to get the string lengths, and then the actually strings.
844  * It also null-terminates them since they might not be already.
845  */
846 drmVersionPtr drmGetVersion(int fd)
847 {
848     drmVersionPtr retval;
849     drm_version_t *version = drmMalloc(sizeof(*version));
850
851     memclear(*version);
852
853     if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
854         drmFreeKernelVersion(version);
855         return NULL;
856     }
857
858     if (version->name_len)
859         version->name    = drmMalloc(version->name_len + 1);
860     if (version->date_len)
861         version->date    = drmMalloc(version->date_len + 1);
862     if (version->desc_len)
863         version->desc    = drmMalloc(version->desc_len + 1);
864
865     if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
866         drmMsg("DRM_IOCTL_VERSION: %s\n", strerror(errno));
867         drmFreeKernelVersion(version);
868         return NULL;
869     }
870
871     /* The results might not be null-terminated strings, so terminate them. */
872     if (version->name_len) version->name[version->name_len] = '\0';
873     if (version->date_len) version->date[version->date_len] = '\0';
874     if (version->desc_len) version->desc[version->desc_len] = '\0';
875
876     retval = drmMalloc(sizeof(*retval));
877     drmCopyVersion(retval, version);
878     drmFreeKernelVersion(version);
879     return retval;
880 }
881
882
883 /**
884  * Get version information for the DRM user space library.
885  * 
886  * This version number is driver independent.
887  * 
888  * \param fd file descriptor.
889  *
890  * \return version information.
891  * 
892  * \internal
893  * This function allocates and fills a drm_version structure with a hard coded
894  * version number.
895  */
896 drmVersionPtr drmGetLibVersion(int fd)
897 {
898     drm_version_t *version = drmMalloc(sizeof(*version));
899
900     /* Version history:
901      *   NOTE THIS MUST NOT GO ABOVE VERSION 1.X due to drivers needing it
902      *   revision 1.0.x = original DRM interface with no drmGetLibVersion
903      *                    entry point and many drm<Device> extensions
904      *   revision 1.1.x = added drmCommand entry points for device extensions
905      *                    added drmGetLibVersion to identify libdrm.a version
906      *   revision 1.2.x = added drmSetInterfaceVersion
907      *                    modified drmOpen to handle both busid and name
908      *   revision 1.3.x = added server + memory manager
909      */
910     version->version_major      = 1;
911     version->version_minor      = 3;
912     version->version_patchlevel = 0;
913
914     return (drmVersionPtr)version;
915 }
916
917 int drmGetCap(int fd, uint64_t capability, uint64_t *value)
918 {
919         struct drm_get_cap cap;
920         int ret;
921
922         memclear(cap);
923         cap.capability = capability;
924
925         ret = drmIoctl(fd, DRM_IOCTL_GET_CAP, &cap);
926         if (ret)
927                 return ret;
928
929         *value = cap.value;
930         return 0;
931 }
932
933 int drmSetClientCap(int fd, uint64_t capability, uint64_t value)
934 {
935         struct drm_set_client_cap cap;
936
937         memclear(cap);
938         cap.capability = capability;
939         cap.value = value;
940
941         return drmIoctl(fd, DRM_IOCTL_SET_CLIENT_CAP, &cap);
942 }
943
944 /**
945  * Free the bus ID information.
946  *
947  * \param busid bus ID information string as given by drmGetBusid().
948  *
949  * \internal
950  * This function is just frees the memory pointed by \p busid.
951  */
952 void drmFreeBusid(const char *busid)
953 {
954     drmFree((void *)busid);
955 }
956
957
958 /**
959  * Get the bus ID of the device.
960  *
961  * \param fd file descriptor.
962  *
963  * \return bus ID string.
964  *
965  * \internal
966  * This function gets the bus ID via successive DRM_IOCTL_GET_UNIQUE ioctls to
967  * get the string length and data, passing the arguments in a drm_unique
968  * structure.
969  */
970 char *drmGetBusid(int fd)
971 {
972     drm_unique_t u;
973
974     memclear(u);
975
976     if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
977         return NULL;
978     u.unique = drmMalloc(u.unique_len + 1);
979     if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
980         return NULL;
981     u.unique[u.unique_len] = '\0';
982
983     return u.unique;
984 }
985
986
987 /**
988  * Set the bus ID of the device.
989  *
990  * \param fd file descriptor.
991  * \param busid bus ID string.
992  *
993  * \return zero on success, negative on failure.
994  *
995  * \internal
996  * This function is a wrapper around the DRM_IOCTL_SET_UNIQUE ioctl, passing
997  * the arguments in a drm_unique structure.
998  */
999 int drmSetBusid(int fd, const char *busid)
1000 {
1001     drm_unique_t u;
1002
1003     memclear(u);
1004     u.unique     = (char *)busid;
1005     u.unique_len = strlen(busid);
1006
1007     if (drmIoctl(fd, DRM_IOCTL_SET_UNIQUE, &u)) {
1008         return -errno;
1009     }
1010     return 0;
1011 }
1012
1013 int drmGetMagic(int fd, drm_magic_t * magic)
1014 {
1015     drm_auth_t auth;
1016
1017     memclear(auth);
1018
1019     *magic = 0;
1020     if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
1021         return -errno;
1022     *magic = auth.magic;
1023     return 0;
1024 }
1025
1026 int drmAuthMagic(int fd, drm_magic_t magic)
1027 {
1028     drm_auth_t auth;
1029
1030     memclear(auth);
1031     auth.magic = magic;
1032     if (drmIoctl(fd, DRM_IOCTL_AUTH_MAGIC, &auth))
1033         return -errno;
1034     return 0;
1035 }
1036
1037 /**
1038  * Specifies a range of memory that is available for mapping by a
1039  * non-root process.
1040  *
1041  * \param fd file descriptor.
1042  * \param offset usually the physical address. The actual meaning depends of
1043  * the \p type parameter. See below.
1044  * \param size of the memory in bytes.
1045  * \param type type of the memory to be mapped.
1046  * \param flags combination of several flags to modify the function actions.
1047  * \param handle will be set to a value that may be used as the offset
1048  * parameter for mmap().
1049  * 
1050  * \return zero on success or a negative value on error.
1051  *
1052  * \par Mapping the frame buffer
1053  * For the frame buffer
1054  * - \p offset will be the physical address of the start of the frame buffer,
1055  * - \p size will be the size of the frame buffer in bytes, and
1056  * - \p type will be DRM_FRAME_BUFFER.
1057  *
1058  * \par
1059  * The area mapped will be uncached. If MTRR support is available in the
1060  * kernel, the frame buffer area will be set to write combining. 
1061  *
1062  * \par Mapping the MMIO register area
1063  * For the MMIO register area,
1064  * - \p offset will be the physical address of the start of the register area,
1065  * - \p size will be the size of the register area bytes, and
1066  * - \p type will be DRM_REGISTERS.
1067  * \par
1068  * The area mapped will be uncached. 
1069  * 
1070  * \par Mapping the SAREA
1071  * For the SAREA,
1072  * - \p offset will be ignored and should be set to zero,
1073  * - \p size will be the desired size of the SAREA in bytes,
1074  * - \p type will be DRM_SHM.
1075  * 
1076  * \par
1077  * A shared memory area of the requested size will be created and locked in
1078  * kernel memory. This area may be mapped into client-space by using the handle
1079  * returned. 
1080  * 
1081  * \note May only be called by root.
1082  *
1083  * \internal
1084  * This function is a wrapper around the DRM_IOCTL_ADD_MAP ioctl, passing
1085  * the arguments in a drm_map structure.
1086  */
1087 int drmAddMap(int fd, drm_handle_t offset, drmSize size, drmMapType type,
1088               drmMapFlags flags, drm_handle_t *handle)
1089 {
1090     drm_map_t map;
1091
1092     memclear(map);
1093     map.offset  = offset;
1094     map.size    = size;
1095     map.type    = type;
1096     map.flags   = flags;
1097     if (drmIoctl(fd, DRM_IOCTL_ADD_MAP, &map))
1098         return -errno;
1099     if (handle)
1100         *handle = (drm_handle_t)(uintptr_t)map.handle;
1101     return 0;
1102 }
1103
1104 int drmRmMap(int fd, drm_handle_t handle)
1105 {
1106     drm_map_t map;
1107
1108     memclear(map);
1109     map.handle = (void *)(uintptr_t)handle;
1110
1111     if(drmIoctl(fd, DRM_IOCTL_RM_MAP, &map))
1112         return -errno;
1113     return 0;
1114 }
1115
1116 /**
1117  * Make buffers available for DMA transfers.
1118  * 
1119  * \param fd file descriptor.
1120  * \param count number of buffers.
1121  * \param size size of each buffer.
1122  * \param flags buffer allocation flags.
1123  * \param agp_offset offset in the AGP aperture 
1124  *
1125  * \return number of buffers allocated, negative on error.
1126  *
1127  * \internal
1128  * This function is a wrapper around DRM_IOCTL_ADD_BUFS ioctl.
1129  *
1130  * \sa drm_buf_desc.
1131  */
1132 int drmAddBufs(int fd, int count, int size, drmBufDescFlags flags,
1133                int agp_offset)
1134 {
1135     drm_buf_desc_t request;
1136
1137     memclear(request);
1138     request.count     = count;
1139     request.size      = size;
1140     request.flags     = flags;
1141     request.agp_start = agp_offset;
1142
1143     if (drmIoctl(fd, DRM_IOCTL_ADD_BUFS, &request))
1144         return -errno;
1145     return request.count;
1146 }
1147
1148 int drmMarkBufs(int fd, double low, double high)
1149 {
1150     drm_buf_info_t info;
1151     int            i;
1152
1153     memclear(info);
1154
1155     if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1156         return -EINVAL;
1157
1158     if (!info.count)
1159         return -EINVAL;
1160
1161     if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1162         return -ENOMEM;
1163
1164     if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1165         int retval = -errno;
1166         drmFree(info.list);
1167         return retval;
1168     }
1169
1170     for (i = 0; i < info.count; i++) {
1171         info.list[i].low_mark  = low  * info.list[i].count;
1172         info.list[i].high_mark = high * info.list[i].count;
1173         if (drmIoctl(fd, DRM_IOCTL_MARK_BUFS, &info.list[i])) {
1174             int retval = -errno;
1175             drmFree(info.list);
1176             return retval;
1177         }
1178     }
1179     drmFree(info.list);
1180
1181     return 0;
1182 }
1183
1184 /**
1185  * Free buffers.
1186  *
1187  * \param fd file descriptor.
1188  * \param count number of buffers to free.
1189  * \param list list of buffers to be freed.
1190  *
1191  * \return zero on success, or a negative value on failure.
1192  * 
1193  * \note This function is primarily used for debugging.
1194  * 
1195  * \internal
1196  * This function is a wrapper around the DRM_IOCTL_FREE_BUFS ioctl, passing
1197  * the arguments in a drm_buf_free structure.
1198  */
1199 int drmFreeBufs(int fd, int count, int *list)
1200 {
1201     drm_buf_free_t request;
1202
1203     memclear(request);
1204     request.count = count;
1205     request.list  = list;
1206     if (drmIoctl(fd, DRM_IOCTL_FREE_BUFS, &request))
1207         return -errno;
1208     return 0;
1209 }
1210
1211
1212 /**
1213  * Close the device.
1214  *
1215  * \param fd file descriptor.
1216  *
1217  * \internal
1218  * This function closes the file descriptor.
1219  */
1220 int drmClose(int fd)
1221 {
1222     unsigned long key    = drmGetKeyFromFd(fd);
1223     drmHashEntry  *entry = drmGetEntry(fd);
1224
1225     drmHashDestroy(entry->tagTable);
1226     entry->fd       = 0;
1227     entry->f        = NULL;
1228     entry->tagTable = NULL;
1229
1230     drmHashDelete(drmHashTable, key);
1231     drmFree(entry);
1232
1233     return close(fd);
1234 }
1235
1236
1237 /**
1238  * Map a region of memory.
1239  *
1240  * \param fd file descriptor.
1241  * \param handle handle returned by drmAddMap().
1242  * \param size size in bytes. Must match the size used by drmAddMap().
1243  * \param address will contain the user-space virtual address where the mapping
1244  * begins.
1245  *
1246  * \return zero on success, or a negative value on failure.
1247  * 
1248  * \internal
1249  * This function is a wrapper for mmap().
1250  */
1251 int drmMap(int fd, drm_handle_t handle, drmSize size, drmAddressPtr address)
1252 {
1253     static unsigned long pagesize_mask = 0;
1254
1255     if (fd < 0)
1256         return -EINVAL;
1257
1258     if (!pagesize_mask)
1259         pagesize_mask = getpagesize() - 1;
1260
1261     size = (size + pagesize_mask) & ~pagesize_mask;
1262
1263     *address = drm_mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1264     if (*address == MAP_FAILED)
1265         return -errno;
1266     return 0;
1267 }
1268
1269
1270 /**
1271  * Unmap mappings obtained with drmMap().
1272  *
1273  * \param address address as given by drmMap().
1274  * \param size size in bytes. Must match the size used by drmMap().
1275  * 
1276  * \return zero on success, or a negative value on failure.
1277  *
1278  * \internal
1279  * This function is a wrapper for munmap().
1280  */
1281 int drmUnmap(drmAddress address, drmSize size)
1282 {
1283     return drm_munmap(address, size);
1284 }
1285
1286 drmBufInfoPtr drmGetBufInfo(int fd)
1287 {
1288     drm_buf_info_t info;
1289     drmBufInfoPtr  retval;
1290     int            i;
1291
1292     memclear(info);
1293
1294     if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1295         return NULL;
1296
1297     if (info.count) {
1298         if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1299             return NULL;
1300
1301         if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1302             drmFree(info.list);
1303             return NULL;
1304         }
1305
1306         retval = drmMalloc(sizeof(*retval));
1307         retval->count = info.count;
1308         retval->list  = drmMalloc(info.count * sizeof(*retval->list));
1309         for (i = 0; i < info.count; i++) {
1310             retval->list[i].count     = info.list[i].count;
1311             retval->list[i].size      = info.list[i].size;
1312             retval->list[i].low_mark  = info.list[i].low_mark;
1313             retval->list[i].high_mark = info.list[i].high_mark;
1314         }
1315         drmFree(info.list);
1316         return retval;
1317     }
1318     return NULL;
1319 }
1320
1321 /**
1322  * Map all DMA buffers into client-virtual space.
1323  *
1324  * \param fd file descriptor.
1325  *
1326  * \return a pointer to a ::drmBufMap structure.
1327  *
1328  * \note The client may not use these buffers until obtaining buffer indices
1329  * with drmDMA().
1330  * 
1331  * \internal
1332  * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1333  * information about the buffers in a drm_buf_map structure into the
1334  * client-visible data structures.
1335  */ 
1336 drmBufMapPtr drmMapBufs(int fd)
1337 {
1338     drm_buf_map_t bufs;
1339     drmBufMapPtr  retval;
1340     int           i;
1341
1342     memclear(bufs);
1343     if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1344         return NULL;
1345
1346     if (!bufs.count)
1347         return NULL;
1348
1349         if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1350             return NULL;
1351
1352         if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1353             drmFree(bufs.list);
1354             return NULL;
1355         }
1356
1357         retval = drmMalloc(sizeof(*retval));
1358         retval->count = bufs.count;
1359         retval->list  = drmMalloc(bufs.count * sizeof(*retval->list));
1360         for (i = 0; i < bufs.count; i++) {
1361             retval->list[i].idx     = bufs.list[i].idx;
1362             retval->list[i].total   = bufs.list[i].total;
1363             retval->list[i].used    = 0;
1364             retval->list[i].address = bufs.list[i].address;
1365         }
1366
1367         drmFree(bufs.list);
1368         
1369         return retval;
1370 }
1371
1372
1373 /**
1374  * Unmap buffers allocated with drmMapBufs().
1375  *
1376  * \return zero on success, or negative value on failure.
1377  *
1378  * \internal
1379  * Calls munmap() for every buffer stored in \p bufs and frees the
1380  * memory allocated by drmMapBufs().
1381  */
1382 int drmUnmapBufs(drmBufMapPtr bufs)
1383 {
1384     int i;
1385
1386     for (i = 0; i < bufs->count; i++) {
1387         drm_munmap(bufs->list[i].address, bufs->list[i].total);
1388     }
1389
1390     drmFree(bufs->list);
1391     drmFree(bufs);
1392         
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 #endif
2821         return NULL;
2822 }
2823
2824 char *drmGetPrimaryDeviceNameFromFd(int fd)
2825 {
2826         return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
2827 }
2828
2829 char *drmGetRenderDeviceNameFromFd(int fd)
2830 {
2831         return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
2832 }