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