OSDN Git Service

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