OSDN Git Service

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