OSDN Git Service

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