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