OSDN Git Service

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