OSDN Git Service

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