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