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