OSDN Git Service

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