xf86drm.c revision 237f1da6
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#ifdef DRM_IOCTL_MMAP
1142    struct drm_mmap mmap_req = {0};
1143#endif
1144
1145    if (fd < 0)
1146	return -EINVAL;
1147
1148    if (!pagesize_mask)
1149	pagesize_mask = getpagesize() - 1;
1150
1151    size = (size + pagesize_mask) & ~pagesize_mask;
1152
1153#ifdef DRM_IOCTL_MMAP
1154    mmap_req.dnm_addr = NULL;
1155    mmap_req.dnm_size = size;
1156    mmap_req.dnm_prot = (PROT_READ | PROT_WRITE);
1157    mmap_req.dnm_flags = MAP_SHARED;
1158    mmap_req.dnm_offset = handle;
1159    if (drmIoctl(fd, DRM_IOCTL_MMAP, &mmap_req) == 0) {
1160	*address = mmap_req.dnm_addr;
1161	return 0;
1162    }
1163#endif
1164    *address = mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1165    if (*address == MAP_FAILED)
1166	return -errno;
1167    return 0;
1168}
1169
1170
1171/**
1172 * Unmap mappings obtained with drmMap().
1173 *
1174 * \param address address as given by drmMap().
1175 * \param size size in bytes. Must match the size used by drmMap().
1176 *
1177 * \return zero on success, or a negative value on failure.
1178 *
1179 * \internal
1180 * This function is a wrapper for munmap().
1181 */
1182int drmUnmap(drmAddress address, drmSize size)
1183{
1184    return munmap(address, size);
1185}
1186
1187drmBufInfoPtr drmGetBufInfo(int fd)
1188{
1189    drm_buf_info_t info;
1190    drmBufInfoPtr  retval;
1191    int            i;
1192
1193    info.count = 0;
1194    info.list  = NULL;
1195
1196    if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1197	return NULL;
1198
1199    if (info.count) {
1200	if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1201	    return NULL;
1202
1203	if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1204	    drmFree(info.list);
1205	    return NULL;
1206	}
1207
1208	retval = drmMalloc(sizeof(*retval));
1209	retval->count = info.count;
1210	retval->list  = drmMalloc(info.count * sizeof(*retval->list));
1211	for (i = 0; i < info.count; i++) {
1212	    retval->list[i].count     = info.list[i].count;
1213	    retval->list[i].size      = info.list[i].size;
1214	    retval->list[i].low_mark  = info.list[i].low_mark;
1215	    retval->list[i].high_mark = info.list[i].high_mark;
1216	}
1217	drmFree(info.list);
1218	return retval;
1219    }
1220    return NULL;
1221}
1222
1223/**
1224 * Map all DMA buffers into client-virtual space.
1225 *
1226 * \param fd file descriptor.
1227 *
1228 * \return a pointer to a ::drmBufMap structure.
1229 *
1230 * \note The client may not use these buffers until obtaining buffer indices
1231 * with drmDMA().
1232 *
1233 * \internal
1234 * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1235 * information about the buffers in a drm_buf_map structure into the
1236 * client-visible data structures.
1237 */
1238drmBufMapPtr drmMapBufs(int fd)
1239{
1240    drm_buf_map_t bufs;
1241    drmBufMapPtr  retval;
1242    int           i;
1243
1244    bufs.count = 0;
1245    bufs.list  = NULL;
1246    bufs.virtual = NULL;
1247    if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1248	return NULL;
1249
1250    if (!bufs.count)
1251	return NULL;
1252
1253	if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1254	    return NULL;
1255
1256	if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1257	    drmFree(bufs.list);
1258	    return NULL;
1259	}
1260
1261	retval = drmMalloc(sizeof(*retval));
1262	retval->count = bufs.count;
1263	retval->list  = drmMalloc(bufs.count * sizeof(*retval->list));
1264	for (i = 0; i < bufs.count; i++) {
1265	    retval->list[i].idx     = bufs.list[i].idx;
1266	    retval->list[i].total   = bufs.list[i].total;
1267	    retval->list[i].used    = 0;
1268	    retval->list[i].address = bufs.list[i].address;
1269	}
1270
1271	drmFree(bufs.list);
1272
1273	return retval;
1274}
1275
1276
1277/**
1278 * Unmap buffers allocated with drmMapBufs().
1279 *
1280 * \return zero on success, or negative value on failure.
1281 *
1282 * \internal
1283 * Calls munmap() for every buffer stored in \p bufs and frees the
1284 * memory allocated by drmMapBufs().
1285 */
1286int drmUnmapBufs(drmBufMapPtr bufs)
1287{
1288    int i;
1289
1290    for (i = 0; i < bufs->count; i++) {
1291	munmap(bufs->list[i].address, bufs->list[i].total);
1292    }
1293
1294    drmFree(bufs->list);
1295    drmFree(bufs);
1296
1297    return 0;
1298}
1299
1300
1301#define DRM_DMA_RETRY		16
1302
1303/**
1304 * Reserve DMA buffers.
1305 *
1306 * \param fd file descriptor.
1307 * \param request
1308 *
1309 * \return zero on success, or a negative value on failure.
1310 *
1311 * \internal
1312 * Assemble the arguments into a drm_dma structure and keeps issuing the
1313 * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1314 */
1315int drmDMA(int fd, drmDMAReqPtr request)
1316{
1317    drm_dma_t dma;
1318    int ret, i = 0;
1319
1320    dma.context         = request->context;
1321    dma.send_count      = request->send_count;
1322    dma.send_indices    = request->send_list;
1323    dma.send_sizes      = request->send_sizes;
1324    dma.flags           = request->flags;
1325    dma.request_count   = request->request_count;
1326    dma.request_size    = request->request_size;
1327    dma.request_indices = request->request_list;
1328    dma.request_sizes   = request->request_sizes;
1329    dma.granted_count   = 0;
1330
1331    do {
1332	ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1333    } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1334
1335    if ( ret == 0 ) {
1336	request->granted_count = dma.granted_count;
1337	return 0;
1338    } else {
1339	return -errno;
1340    }
1341}
1342
1343
1344/**
1345 * Obtain heavyweight hardware lock.
1346 *
1347 * \param fd file descriptor.
1348 * \param context context.
1349 * \param flags flags that determine the sate of the hardware when the function
1350 * returns.
1351 *
1352 * \return always zero.
1353 *
1354 * \internal
1355 * This function translates the arguments into a drm_lock structure and issue
1356 * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1357 */
1358int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
1359{
1360    drm_lock_t lock;
1361
1362    lock.context = context;
1363    lock.flags   = 0;
1364    if (flags & DRM_LOCK_READY)      lock.flags |= _DRM_LOCK_READY;
1365    if (flags & DRM_LOCK_QUIESCENT)  lock.flags |= _DRM_LOCK_QUIESCENT;
1366    if (flags & DRM_LOCK_FLUSH)      lock.flags |= _DRM_LOCK_FLUSH;
1367    if (flags & DRM_LOCK_FLUSH_ALL)  lock.flags |= _DRM_LOCK_FLUSH_ALL;
1368    if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
1369    if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
1370
1371    while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
1372	;
1373    return 0;
1374}
1375
1376/**
1377 * Release the hardware lock.
1378 *
1379 * \param fd file descriptor.
1380 * \param context context.
1381 *
1382 * \return zero on success, or a negative value on failure.
1383 *
1384 * \internal
1385 * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
1386 * argument in a drm_lock structure.
1387 */
1388int drmUnlock(int fd, drm_context_t context)
1389{
1390    drm_lock_t lock;
1391
1392    lock.context = context;
1393    lock.flags   = 0;
1394    return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
1395}
1396
1397drm_context_t *drmGetReservedContextList(int fd, int *count)
1398{
1399    drm_ctx_res_t res;
1400    drm_ctx_t     *list;
1401    drm_context_t * retval;
1402    int           i;
1403
1404    res.count    = 0;
1405    res.contexts = NULL;
1406    if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1407	return NULL;
1408
1409    if (!res.count)
1410	return NULL;
1411
1412    if (!(list   = drmMalloc(res.count * sizeof(*list))))
1413	return NULL;
1414    if (!(retval = drmMalloc(res.count * sizeof(*retval)))) {
1415	drmFree(list);
1416	return NULL;
1417    }
1418
1419    res.contexts = list;
1420    if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1421	return NULL;
1422
1423    for (i = 0; i < res.count; i++)
1424	retval[i] = list[i].handle;
1425    drmFree(list);
1426
1427    *count = res.count;
1428    return retval;
1429}
1430
1431void drmFreeReservedContextList(drm_context_t *pt)
1432{
1433    drmFree(pt);
1434}
1435
1436/**
1437 * Create context.
1438 *
1439 * Used by the X server during GLXContext initialization. This causes
1440 * per-context kernel-level resources to be allocated.
1441 *
1442 * \param fd file descriptor.
1443 * \param handle is set on success. To be used by the client when requesting DMA
1444 * dispatch with drmDMA().
1445 *
1446 * \return zero on success, or a negative value on failure.
1447 *
1448 * \note May only be called by root.
1449 *
1450 * \internal
1451 * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
1452 * argument in a drm_ctx structure.
1453 */
1454int drmCreateContext(int fd, drm_context_t *handle)
1455{
1456    drm_ctx_t ctx;
1457
1458    ctx.flags = 0;	/* Modified with functions below */
1459    if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
1460	return -errno;
1461    *handle = ctx.handle;
1462    return 0;
1463}
1464
1465int drmSwitchToContext(int fd, drm_context_t context)
1466{
1467    drm_ctx_t ctx;
1468
1469    ctx.handle = context;
1470    if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
1471	return -errno;
1472    return 0;
1473}
1474
1475int drmSetContextFlags(int fd, drm_context_t context, drm_context_tFlags flags)
1476{
1477    drm_ctx_t ctx;
1478
1479    /*
1480     * Context preserving means that no context switches are done between DMA
1481     * buffers from one context and the next.  This is suitable for use in the
1482     * X server (which promises to maintain hardware context), or in the
1483     * client-side library when buffers are swapped on behalf of two threads.
1484     */
1485    ctx.handle = context;
1486    ctx.flags  = 0;
1487    if (flags & DRM_CONTEXT_PRESERVED)
1488	ctx.flags |= _DRM_CONTEXT_PRESERVED;
1489    if (flags & DRM_CONTEXT_2DONLY)
1490	ctx.flags |= _DRM_CONTEXT_2DONLY;
1491    if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
1492	return -errno;
1493    return 0;
1494}
1495
1496int drmGetContextFlags(int fd, drm_context_t context,
1497                       drm_context_tFlagsPtr flags)
1498{
1499    drm_ctx_t ctx;
1500
1501    ctx.handle = context;
1502    if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
1503	return -errno;
1504    *flags = 0;
1505    if (ctx.flags & _DRM_CONTEXT_PRESERVED)
1506	*flags |= DRM_CONTEXT_PRESERVED;
1507    if (ctx.flags & _DRM_CONTEXT_2DONLY)
1508	*flags |= DRM_CONTEXT_2DONLY;
1509    return 0;
1510}
1511
1512/**
1513 * Destroy context.
1514 *
1515 * Free any kernel-level resources allocated with drmCreateContext() associated
1516 * with the context.
1517 *
1518 * \param fd file descriptor.
1519 * \param handle handle given by drmCreateContext().
1520 *
1521 * \return zero on success, or a negative value on failure.
1522 *
1523 * \note May only be called by root.
1524 *
1525 * \internal
1526 * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
1527 * argument in a drm_ctx structure.
1528 */
1529int drmDestroyContext(int fd, drm_context_t handle)
1530{
1531    drm_ctx_t ctx;
1532    ctx.handle = handle;
1533    if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
1534	return -errno;
1535    return 0;
1536}
1537
1538int drmCreateDrawable(int fd, drm_drawable_t *handle)
1539{
1540    drm_draw_t draw;
1541    if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
1542	return -errno;
1543    *handle = draw.handle;
1544    return 0;
1545}
1546
1547int drmDestroyDrawable(int fd, drm_drawable_t handle)
1548{
1549    drm_draw_t draw;
1550    draw.handle = handle;
1551    if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
1552	return -errno;
1553    return 0;
1554}
1555
1556int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
1557			   drm_drawable_info_type_t type, unsigned int num,
1558			   void *data)
1559{
1560    drm_update_draw_t update;
1561
1562    update.handle = handle;
1563    update.type = type;
1564    update.num = num;
1565    update.data = (unsigned long long)(unsigned long)data;
1566
1567    if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
1568	return -errno;
1569
1570    return 0;
1571}
1572
1573/**
1574 * Acquire the AGP device.
1575 *
1576 * Must be called before any of the other AGP related calls.
1577 *
1578 * \param fd file descriptor.
1579 *
1580 * \return zero on success, or a negative value on failure.
1581 *
1582 * \internal
1583 * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
1584 */
1585int drmAgpAcquire(int fd)
1586{
1587    if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
1588	return -errno;
1589    return 0;
1590}
1591
1592
1593/**
1594 * Release the AGP device.
1595 *
1596 * \param fd file descriptor.
1597 *
1598 * \return zero on success, or a negative value on failure.
1599 *
1600 * \internal
1601 * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
1602 */
1603int drmAgpRelease(int fd)
1604{
1605    if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
1606	return -errno;
1607    return 0;
1608}
1609
1610
1611/**
1612 * Set the AGP mode.
1613 *
1614 * \param fd file descriptor.
1615 * \param mode AGP mode.
1616 *
1617 * \return zero on success, or a negative value on failure.
1618 *
1619 * \internal
1620 * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
1621 * argument in a drm_agp_mode structure.
1622 */
1623int drmAgpEnable(int fd, unsigned long mode)
1624{
1625    drm_agp_mode_t m;
1626
1627    m.mode = mode;
1628    if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
1629	return -errno;
1630    return 0;
1631}
1632
1633
1634/**
1635 * Allocate a chunk of AGP memory.
1636 *
1637 * \param fd file descriptor.
1638 * \param size requested memory size in bytes. Will be rounded to page boundary.
1639 * \param type type of memory to allocate.
1640 * \param address if not zero, will be set to the physical address of the
1641 * allocated memory.
1642 * \param handle on success will be set to a handle of the allocated memory.
1643 *
1644 * \return zero on success, or a negative value on failure.
1645 *
1646 * \internal
1647 * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
1648 * arguments in a drm_agp_buffer structure.
1649 */
1650int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
1651		unsigned long *address, drm_handle_t *handle)
1652{
1653    drm_agp_buffer_t b;
1654
1655    *handle = DRM_AGP_NO_HANDLE;
1656    b.size   = size;
1657    b.handle = 0;
1658    b.type   = type;
1659    if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
1660	return -errno;
1661    if (address != 0UL)
1662	*address = b.physical;
1663    *handle = b.handle;
1664    return 0;
1665}
1666
1667
1668/**
1669 * Free a chunk of AGP memory.
1670 *
1671 * \param fd file descriptor.
1672 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1673 *
1674 * \return zero on success, or a negative value on failure.
1675 *
1676 * \internal
1677 * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
1678 * argument in a drm_agp_buffer structure.
1679 */
1680int drmAgpFree(int fd, drm_handle_t handle)
1681{
1682    drm_agp_buffer_t b;
1683
1684    b.size   = 0;
1685    b.handle = handle;
1686    if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
1687	return -errno;
1688    return 0;
1689}
1690
1691
1692/**
1693 * Bind a chunk of AGP memory.
1694 *
1695 * \param fd file descriptor.
1696 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1697 * \param offset offset in bytes. It will round to page boundary.
1698 *
1699 * \return zero on success, or a negative value on failure.
1700 *
1701 * \internal
1702 * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
1703 * argument in a drm_agp_binding structure.
1704 */
1705int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
1706{
1707    drm_agp_binding_t b;
1708
1709    b.handle = handle;
1710    b.offset = offset;
1711    if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
1712	return -errno;
1713    return 0;
1714}
1715
1716
1717/**
1718 * Unbind a chunk of AGP memory.
1719 *
1720 * \param fd file descriptor.
1721 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1722 *
1723 * \return zero on success, or a negative value on failure.
1724 *
1725 * \internal
1726 * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
1727 * the argument in a drm_agp_binding structure.
1728 */
1729int drmAgpUnbind(int fd, drm_handle_t handle)
1730{
1731    drm_agp_binding_t b;
1732
1733    b.handle = handle;
1734    b.offset = 0;
1735    if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
1736	return -errno;
1737    return 0;
1738}
1739
1740
1741/**
1742 * Get AGP driver major version number.
1743 *
1744 * \param fd file descriptor.
1745 *
1746 * \return major version number on success, or a negative value on failure..
1747 *
1748 * \internal
1749 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1750 * necessary information in a drm_agp_info structure.
1751 */
1752int drmAgpVersionMajor(int fd)
1753{
1754    drm_agp_info_t i;
1755
1756    if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1757	return -errno;
1758    return i.agp_version_major;
1759}
1760
1761
1762/**
1763 * Get AGP driver minor version number.
1764 *
1765 * \param fd file descriptor.
1766 *
1767 * \return minor version number on success, or a negative value on failure.
1768 *
1769 * \internal
1770 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1771 * necessary information in a drm_agp_info structure.
1772 */
1773int drmAgpVersionMinor(int fd)
1774{
1775    drm_agp_info_t i;
1776
1777    if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1778	return -errno;
1779    return i.agp_version_minor;
1780}
1781
1782
1783/**
1784 * Get AGP mode.
1785 *
1786 * \param fd file descriptor.
1787 *
1788 * \return mode on success, or zero on failure.
1789 *
1790 * \internal
1791 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1792 * necessary information in a drm_agp_info structure.
1793 */
1794unsigned long drmAgpGetMode(int fd)
1795{
1796    drm_agp_info_t i;
1797
1798    if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1799	return 0;
1800    return i.mode;
1801}
1802
1803
1804/**
1805 * Get AGP aperture base.
1806 *
1807 * \param fd file descriptor.
1808 *
1809 * \return aperture base on success, zero on failure.
1810 *
1811 * \internal
1812 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1813 * necessary information in a drm_agp_info structure.
1814 */
1815unsigned long drmAgpBase(int fd)
1816{
1817    drm_agp_info_t i;
1818
1819    if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1820	return 0;
1821    return i.aperture_base;
1822}
1823
1824
1825/**
1826 * Get AGP aperture size.
1827 *
1828 * \param fd file descriptor.
1829 *
1830 * \return aperture size on success, zero on failure.
1831 *
1832 * \internal
1833 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1834 * necessary information in a drm_agp_info structure.
1835 */
1836unsigned long drmAgpSize(int fd)
1837{
1838    drm_agp_info_t i;
1839
1840    if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1841	return 0;
1842    return i.aperture_size;
1843}
1844
1845
1846/**
1847 * Get used AGP memory.
1848 *
1849 * \param fd file descriptor.
1850 *
1851 * \return memory used on success, or zero on failure.
1852 *
1853 * \internal
1854 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1855 * necessary information in a drm_agp_info structure.
1856 */
1857unsigned long drmAgpMemoryUsed(int fd)
1858{
1859    drm_agp_info_t i;
1860
1861    if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1862	return 0;
1863    return i.memory_used;
1864}
1865
1866
1867/**
1868 * Get available AGP memory.
1869 *
1870 * \param fd file descriptor.
1871 *
1872 * \return memory available on success, or zero on failure.
1873 *
1874 * \internal
1875 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1876 * necessary information in a drm_agp_info structure.
1877 */
1878unsigned long drmAgpMemoryAvail(int fd)
1879{
1880    drm_agp_info_t i;
1881
1882    if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1883	return 0;
1884    return i.memory_allowed;
1885}
1886
1887
1888/**
1889 * Get hardware vendor ID.
1890 *
1891 * \param fd file descriptor.
1892 *
1893 * \return vendor ID on success, or zero on failure.
1894 *
1895 * \internal
1896 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1897 * necessary information in a drm_agp_info structure.
1898 */
1899unsigned int drmAgpVendorId(int fd)
1900{
1901    drm_agp_info_t i;
1902
1903    if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1904	return 0;
1905    return i.id_vendor;
1906}
1907
1908
1909/**
1910 * Get hardware device ID.
1911 *
1912 * \param fd file descriptor.
1913 *
1914 * \return zero on success, or zero on failure.
1915 *
1916 * \internal
1917 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1918 * necessary information in a drm_agp_info structure.
1919 */
1920unsigned int drmAgpDeviceId(int fd)
1921{
1922    drm_agp_info_t i;
1923
1924    if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1925	return 0;
1926    return i.id_device;
1927}
1928
1929int drmScatterGatherAlloc(int fd, unsigned long size, drm_handle_t *handle)
1930{
1931    drm_scatter_gather_t sg;
1932
1933    *handle = 0;
1934    sg.size   = size;
1935    sg.handle = 0;
1936    if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
1937	return -errno;
1938    *handle = sg.handle;
1939    return 0;
1940}
1941
1942int drmScatterGatherFree(int fd, drm_handle_t handle)
1943{
1944    drm_scatter_gather_t sg;
1945
1946    sg.size   = 0;
1947    sg.handle = handle;
1948    if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
1949	return -errno;
1950    return 0;
1951}
1952
1953/**
1954 * Wait for VBLANK.
1955 *
1956 * \param fd file descriptor.
1957 * \param vbl pointer to a drmVBlank structure.
1958 *
1959 * \return zero on success, or a negative value on failure.
1960 *
1961 * \internal
1962 * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
1963 */
1964int drmWaitVBlank(int fd, drmVBlankPtr vbl)
1965{
1966    struct timespec timeout, cur;
1967    int ret;
1968
1969    ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
1970    if (ret < 0) {
1971	fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
1972	goto out;
1973    }
1974    timeout.tv_sec++;
1975
1976    do {
1977       ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
1978       vbl->request.type &= ~DRM_VBLANK_RELATIVE;
1979       if (ret && errno == EINTR) {
1980	       clock_gettime(CLOCK_MONOTONIC, &cur);
1981	       /* Timeout after 1s */
1982	       if (cur.tv_sec > timeout.tv_sec + 1 ||
1983		   (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
1984		    timeout.tv_nsec)) {
1985		       errno = EBUSY;
1986		       ret = -1;
1987		       break;
1988	       }
1989       }
1990    } while (ret && errno == EINTR);
1991
1992out:
1993    return ret;
1994}
1995
1996int drmError(int err, const char *label)
1997{
1998    switch (err) {
1999    case DRM_ERR_NO_DEVICE:
2000	fprintf(stderr, "%s: no device\n", label);
2001	break;
2002    case DRM_ERR_NO_ACCESS:
2003	fprintf(stderr, "%s: no access\n", label);
2004	break;
2005    case DRM_ERR_NOT_ROOT:
2006	fprintf(stderr, "%s: not root\n", label);
2007	break;
2008    case DRM_ERR_INVALID:
2009	fprintf(stderr, "%s: invalid args\n", label);
2010	break;
2011    default:
2012	if (err < 0)
2013	    err = -err;
2014	fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2015	break;
2016    }
2017
2018    return 1;
2019}
2020
2021/**
2022 * Install IRQ handler.
2023 *
2024 * \param fd file descriptor.
2025 * \param irq IRQ number.
2026 *
2027 * \return zero on success, or a negative value on failure.
2028 *
2029 * \internal
2030 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2031 * argument in a drm_control structure.
2032 */
2033int drmCtlInstHandler(int fd, int irq)
2034{
2035    drm_control_t ctl;
2036
2037    ctl.func  = DRM_INST_HANDLER;
2038    ctl.irq   = irq;
2039    if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2040	return -errno;
2041    return 0;
2042}
2043
2044
2045/**
2046 * Uninstall IRQ handler.
2047 *
2048 * \param fd file descriptor.
2049 *
2050 * \return zero on success, or a negative value on failure.
2051 *
2052 * \internal
2053 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2054 * argument in a drm_control structure.
2055 */
2056int drmCtlUninstHandler(int fd)
2057{
2058    drm_control_t ctl;
2059
2060    ctl.func  = DRM_UNINST_HANDLER;
2061    ctl.irq   = 0;
2062    if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2063	return -errno;
2064    return 0;
2065}
2066
2067int drmFinish(int fd, int context, drmLockFlags flags)
2068{
2069    drm_lock_t lock;
2070
2071    lock.context = context;
2072    lock.flags   = 0;
2073    if (flags & DRM_LOCK_READY)      lock.flags |= _DRM_LOCK_READY;
2074    if (flags & DRM_LOCK_QUIESCENT)  lock.flags |= _DRM_LOCK_QUIESCENT;
2075    if (flags & DRM_LOCK_FLUSH)      lock.flags |= _DRM_LOCK_FLUSH;
2076    if (flags & DRM_LOCK_FLUSH_ALL)  lock.flags |= _DRM_LOCK_FLUSH_ALL;
2077    if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2078    if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2079    if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2080	return -errno;
2081    return 0;
2082}
2083
2084/**
2085 * Get IRQ from bus ID.
2086 *
2087 * \param fd file descriptor.
2088 * \param busnum bus number.
2089 * \param devnum device number.
2090 * \param funcnum function number.
2091 *
2092 * \return IRQ number on success, or a negative value on failure.
2093 *
2094 * \internal
2095 * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2096 * arguments in a drm_irq_busid structure.
2097 */
2098int drmGetInterruptFromBusID(int fd, int busnum, int devnum, int funcnum)
2099{
2100    drm_irq_busid_t p;
2101
2102    p.busnum  = busnum;
2103    p.devnum  = devnum;
2104    p.funcnum = funcnum;
2105    if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2106	return -errno;
2107    return p.irq;
2108}
2109
2110int drmAddContextTag(int fd, drm_context_t context, void *tag)
2111{
2112    drmHashEntry  *entry = drmGetEntry(fd);
2113
2114    if (drmHashInsert(entry->tagTable, context, tag)) {
2115	drmHashDelete(entry->tagTable, context);
2116	drmHashInsert(entry->tagTable, context, tag);
2117    }
2118    return 0;
2119}
2120
2121int drmDelContextTag(int fd, drm_context_t context)
2122{
2123    drmHashEntry  *entry = drmGetEntry(fd);
2124
2125    return drmHashDelete(entry->tagTable, context);
2126}
2127
2128void *drmGetContextTag(int fd, drm_context_t context)
2129{
2130    drmHashEntry  *entry = drmGetEntry(fd);
2131    void          *value;
2132
2133    if (drmHashLookup(entry->tagTable, context, &value))
2134	return NULL;
2135
2136    return value;
2137}
2138
2139int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2140                                drm_handle_t handle)
2141{
2142    drm_ctx_priv_map_t map;
2143
2144    map.ctx_id = ctx_id;
2145    map.handle = (void *)(uintptr_t)handle;
2146
2147    if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2148	return -errno;
2149    return 0;
2150}
2151
2152int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2153                                drm_handle_t *handle)
2154{
2155    drm_ctx_priv_map_t map;
2156
2157    map.ctx_id = ctx_id;
2158
2159    if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2160	return -errno;
2161    if (handle)
2162	*handle = (drm_handle_t)(uintptr_t)map.handle;
2163
2164    return 0;
2165}
2166
2167int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2168	      drmMapType *type, drmMapFlags *flags, drm_handle_t *handle,
2169	      int *mtrr)
2170{
2171    drm_map_t map;
2172
2173    map.offset = idx;
2174    if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2175	return -errno;
2176    *offset = map.offset;
2177    *size   = map.size;
2178    *type   = map.type;
2179    *flags  = map.flags;
2180    *handle = (unsigned long)map.handle;
2181    *mtrr   = map.mtrr;
2182    return 0;
2183}
2184
2185int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2186		 unsigned long *magic, unsigned long *iocs)
2187{
2188    drm_client_t client;
2189
2190    client.idx = idx;
2191    if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2192	return -errno;
2193    *auth      = client.auth;
2194    *pid       = client.pid;
2195    *uid       = client.uid;
2196    *magic     = client.magic;
2197    *iocs      = client.iocs;
2198    return 0;
2199}
2200
2201int drmGetStats(int fd, drmStatsT *stats)
2202{
2203    drm_stats_t s;
2204    int         i;
2205
2206    if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2207	return -errno;
2208
2209    stats->count = 0;
2210    memset(stats, 0, sizeof(*stats));
2211    if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2212	return -1;
2213
2214#define SET_VALUE                              \
2215    stats->data[i].long_format = "%-20.20s";   \
2216    stats->data[i].rate_format = "%8.8s";      \
2217    stats->data[i].isvalue     = 1;            \
2218    stats->data[i].verbose     = 0
2219
2220#define SET_COUNT                              \
2221    stats->data[i].long_format = "%-20.20s";   \
2222    stats->data[i].rate_format = "%5.5s";      \
2223    stats->data[i].isvalue     = 0;            \
2224    stats->data[i].mult_names  = "kgm";        \
2225    stats->data[i].mult        = 1000;         \
2226    stats->data[i].verbose     = 0
2227
2228#define SET_BYTE                               \
2229    stats->data[i].long_format = "%-20.20s";   \
2230    stats->data[i].rate_format = "%5.5s";      \
2231    stats->data[i].isvalue     = 0;            \
2232    stats->data[i].mult_names  = "KGM";        \
2233    stats->data[i].mult        = 1024;         \
2234    stats->data[i].verbose     = 0
2235
2236
2237    stats->count = s.count;
2238    for (i = 0; i < s.count; i++) {
2239	stats->data[i].value = s.data[i].value;
2240	switch (s.data[i].type) {
2241	case _DRM_STAT_LOCK:
2242	    stats->data[i].long_name = "Lock";
2243	    stats->data[i].rate_name = "Lock";
2244	    SET_VALUE;
2245	    break;
2246	case _DRM_STAT_OPENS:
2247	    stats->data[i].long_name = "Opens";
2248	    stats->data[i].rate_name = "O";
2249	    SET_COUNT;
2250	    stats->data[i].verbose   = 1;
2251	    break;
2252	case _DRM_STAT_CLOSES:
2253	    stats->data[i].long_name = "Closes";
2254	    stats->data[i].rate_name = "Lock";
2255	    SET_COUNT;
2256	    stats->data[i].verbose   = 1;
2257	    break;
2258	case _DRM_STAT_IOCTLS:
2259	    stats->data[i].long_name = "Ioctls";
2260	    stats->data[i].rate_name = "Ioc/s";
2261	    SET_COUNT;
2262	    break;
2263	case _DRM_STAT_LOCKS:
2264	    stats->data[i].long_name = "Locks";
2265	    stats->data[i].rate_name = "Lck/s";
2266	    SET_COUNT;
2267	    break;
2268	case _DRM_STAT_UNLOCKS:
2269	    stats->data[i].long_name = "Unlocks";
2270	    stats->data[i].rate_name = "Unl/s";
2271	    SET_COUNT;
2272	    break;
2273	case _DRM_STAT_IRQ:
2274	    stats->data[i].long_name = "IRQs";
2275	    stats->data[i].rate_name = "IRQ/s";
2276	    SET_COUNT;
2277	    break;
2278	case _DRM_STAT_PRIMARY:
2279	    stats->data[i].long_name = "Primary Bytes";
2280	    stats->data[i].rate_name = "PB/s";
2281	    SET_BYTE;
2282	    break;
2283	case _DRM_STAT_SECONDARY:
2284	    stats->data[i].long_name = "Secondary Bytes";
2285	    stats->data[i].rate_name = "SB/s";
2286	    SET_BYTE;
2287	    break;
2288	case _DRM_STAT_DMA:
2289	    stats->data[i].long_name = "DMA";
2290	    stats->data[i].rate_name = "DMA/s";
2291	    SET_COUNT;
2292	    break;
2293	case _DRM_STAT_SPECIAL:
2294	    stats->data[i].long_name = "Special DMA";
2295	    stats->data[i].rate_name = "dma/s";
2296	    SET_COUNT;
2297	    break;
2298	case _DRM_STAT_MISSED:
2299	    stats->data[i].long_name = "Miss";
2300	    stats->data[i].rate_name = "Ms/s";
2301	    SET_COUNT;
2302	    break;
2303	case _DRM_STAT_VALUE:
2304	    stats->data[i].long_name = "Value";
2305	    stats->data[i].rate_name = "Value";
2306	    SET_VALUE;
2307	    break;
2308	case _DRM_STAT_BYTE:
2309	    stats->data[i].long_name = "Bytes";
2310	    stats->data[i].rate_name = "B/s";
2311	    SET_BYTE;
2312	    break;
2313	case _DRM_STAT_COUNT:
2314	default:
2315	    stats->data[i].long_name = "Count";
2316	    stats->data[i].rate_name = "Cnt/s";
2317	    SET_COUNT;
2318	    break;
2319	}
2320    }
2321    return 0;
2322}
2323
2324/**
2325 * Issue a set-version ioctl.
2326 *
2327 * \param fd file descriptor.
2328 * \param drmCommandIndex command index
2329 * \param data source pointer of the data to be read and written.
2330 * \param size size of the data to be read and written.
2331 *
2332 * \return zero on success, or a negative value on failure.
2333 *
2334 * \internal
2335 * It issues a read-write ioctl given by
2336 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2337 */
2338int drmSetInterfaceVersion(int fd, drmSetVersion *version)
2339{
2340    int retcode = 0;
2341    drm_set_version_t sv;
2342
2343    sv.drm_di_major = version->drm_di_major;
2344    sv.drm_di_minor = version->drm_di_minor;
2345    sv.drm_dd_major = version->drm_dd_major;
2346    sv.drm_dd_minor = version->drm_dd_minor;
2347
2348    if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
2349	retcode = -errno;
2350    }
2351
2352    version->drm_di_major = sv.drm_di_major;
2353    version->drm_di_minor = sv.drm_di_minor;
2354    version->drm_dd_major = sv.drm_dd_major;
2355    version->drm_dd_minor = sv.drm_dd_minor;
2356
2357    return retcode;
2358}
2359
2360/**
2361 * Send a device-specific command.
2362 *
2363 * \param fd file descriptor.
2364 * \param drmCommandIndex command index
2365 *
2366 * \return zero on success, or a negative value on failure.
2367 *
2368 * \internal
2369 * It issues a ioctl given by
2370 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2371 */
2372int drmCommandNone(int fd, unsigned long drmCommandIndex)
2373{
2374    void *data = NULL; /* dummy */
2375    unsigned long request;
2376
2377    request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
2378
2379    if (drmIoctl(fd, request, data)) {
2380	return -errno;
2381    }
2382    return 0;
2383}
2384
2385
2386/**
2387 * Send a device-specific read command.
2388 *
2389 * \param fd file descriptor.
2390 * \param drmCommandIndex command index
2391 * \param data destination pointer of the data to be read.
2392 * \param size size of the data to be read.
2393 *
2394 * \return zero on success, or a negative value on failure.
2395 *
2396 * \internal
2397 * It issues a read ioctl given by
2398 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2399 */
2400int drmCommandRead(int fd, unsigned long drmCommandIndex, void *data,
2401                   unsigned long size)
2402{
2403    unsigned long request;
2404
2405    request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
2406	DRM_COMMAND_BASE + drmCommandIndex, size);
2407
2408    if (drmIoctl(fd, request, data)) {
2409	return -errno;
2410    }
2411    return 0;
2412}
2413
2414
2415/**
2416 * Send a device-specific write command.
2417 *
2418 * \param fd file descriptor.
2419 * \param drmCommandIndex command index
2420 * \param data source pointer of the data to be written.
2421 * \param size size of the data to be written.
2422 *
2423 * \return zero on success, or a negative value on failure.
2424 *
2425 * \internal
2426 * It issues a write ioctl given by
2427 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2428 */
2429int drmCommandWrite(int fd, unsigned long drmCommandIndex, void *data,
2430                    unsigned long size)
2431{
2432    unsigned long request;
2433
2434    request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
2435	DRM_COMMAND_BASE + drmCommandIndex, size);
2436
2437    if (drmIoctl(fd, request, data)) {
2438	return -errno;
2439    }
2440    return 0;
2441}
2442
2443
2444/**
2445 * Send a device-specific read-write command.
2446 *
2447 * \param fd file descriptor.
2448 * \param drmCommandIndex command index
2449 * \param data source pointer of the data to be read and written.
2450 * \param size size of the data to be read and written.
2451 *
2452 * \return zero on success, or a negative value on failure.
2453 *
2454 * \internal
2455 * It issues a read-write ioctl given by
2456 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2457 */
2458int drmCommandWriteRead(int fd, unsigned long drmCommandIndex, void *data,
2459                        unsigned long size)
2460{
2461    unsigned long request;
2462
2463    request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
2464	DRM_COMMAND_BASE + drmCommandIndex, size);
2465
2466    if (drmIoctl(fd, request, data))
2467	return -errno;
2468    return 0;
2469}
2470
2471#define DRM_MAX_FDS 16
2472static struct {
2473    char *BusID;
2474    int fd;
2475    int refcount;
2476} connection[DRM_MAX_FDS];
2477
2478static int nr_fds = 0;
2479
2480int drmOpenOnce(void *unused,
2481		const char *BusID,
2482		int *newlyopened)
2483{
2484    int i;
2485    int fd;
2486
2487    for (i = 0; i < nr_fds; i++)
2488	if (strcmp(BusID, connection[i].BusID) == 0) {
2489	    connection[i].refcount++;
2490	    *newlyopened = 0;
2491	    return connection[i].fd;
2492	}
2493
2494    fd = drmOpen(unused, BusID);
2495    if (fd <= 0 || nr_fds == DRM_MAX_FDS)
2496	return fd;
2497
2498    connection[nr_fds].BusID = strdup(BusID);
2499    connection[nr_fds].fd = fd;
2500    connection[nr_fds].refcount = 1;
2501    *newlyopened = 1;
2502
2503    if (0)
2504	fprintf(stderr, "saved connection %d for %s %d\n",
2505		nr_fds, connection[nr_fds].BusID,
2506		strcmp(BusID, connection[nr_fds].BusID));
2507
2508    nr_fds++;
2509
2510    return fd;
2511}
2512
2513void drmCloseOnce(int fd)
2514{
2515    int i;
2516
2517    for (i = 0; i < nr_fds; i++) {
2518	if (fd == connection[i].fd) {
2519	    if (--connection[i].refcount == 0) {
2520		drmClose(connection[i].fd);
2521		free(connection[i].BusID);
2522
2523		if (i < --nr_fds)
2524		    connection[i] = connection[nr_fds];
2525
2526		return;
2527	    }
2528	}
2529    }
2530}
2531
2532int drmSetMaster(int fd)
2533{
2534	return ioctl(fd, DRM_IOCTL_SET_MASTER, 0);
2535}
2536
2537int drmDropMaster(int fd)
2538{
2539	return ioctl(fd, DRM_IOCTL_DROP_MASTER, 0);
2540}
2541
2542char *drmGetDeviceNameFromFd(int fd)
2543{
2544	char name[128];
2545	struct stat sbuf;
2546	dev_t d;
2547	int i;
2548
2549	/* The whole drmOpen thing is a fiasco and we need to find a way
2550	 * back to just using open(2).  For now, however, lets just make
2551	 * things worse with even more ad hoc directory walking code to
2552	 * discover the device file name. */
2553
2554	fstat(fd, &sbuf);
2555	d = sbuf.st_rdev;
2556
2557	for (i = 0; i < DRM_MAX_MINOR; i++) {
2558		snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
2559		if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
2560			break;
2561	}
2562	if (i == DRM_MAX_MINOR)
2563		return NULL;
2564
2565	return strdup(name);
2566}
2567
2568int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags, int *prime_fd)
2569{
2570	struct drm_prime_handle args;
2571	int ret;
2572
2573	args.handle = handle;
2574	args.flags = flags;
2575	ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
2576	if (ret)
2577		return ret;
2578
2579	*prime_fd = args.fd;
2580	return 0;
2581}
2582
2583int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
2584{
2585	struct drm_prime_handle args;
2586	int ret;
2587
2588	args.fd = prime_fd;
2589	args.flags = 0;
2590	ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
2591	if (ret)
2592		return ret;
2593
2594	*handle = args.handle;
2595	return 0;
2596}
2597
2598