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