OSDN Git Service

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