OSDN Git Service

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