xf86drm.c revision 9ce4edcc
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
814
815/**
816 * Free the bus ID information.
817 *
818 * \param busid bus ID information string as given by drmGetBusid().
819 *
820 * \internal
821 * This function is just frees the memory pointed by \p busid.
822 */
823void drmFreeBusid(const char *busid)
824{
825    drmFree((void *)busid);
826}
827
828
829/**
830 * Get the bus ID of the device.
831 *
832 * \param fd file descriptor.
833 *
834 * \return bus ID string.
835 *
836 * \internal
837 * This function gets the bus ID via successive DRM_IOCTL_GET_UNIQUE ioctls to
838 * get the string length and data, passing the arguments in a drm_unique
839 * structure.
840 */
841char *drmGetBusid(int fd)
842{
843    drm_unique_t u;
844
845    u.unique_len = 0;
846    u.unique     = NULL;
847
848    if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
849	return NULL;
850    u.unique = drmMalloc(u.unique_len + 1);
851    if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
852	return NULL;
853    u.unique[u.unique_len] = '\0';
854
855    return u.unique;
856}
857
858
859/**
860 * Set the bus ID of the device.
861 *
862 * \param fd file descriptor.
863 * \param busid bus ID string.
864 *
865 * \return zero on success, negative on failure.
866 *
867 * \internal
868 * This function is a wrapper around the DRM_IOCTL_SET_UNIQUE ioctl, passing
869 * the arguments in a drm_unique structure.
870 */
871int drmSetBusid(int fd, const char *busid)
872{
873    drm_unique_t u;
874
875    u.unique     = (char *)busid;
876    u.unique_len = strlen(busid);
877
878    if (drmIoctl(fd, DRM_IOCTL_SET_UNIQUE, &u)) {
879	return -errno;
880    }
881    return 0;
882}
883
884int drmGetMagic(int fd, drm_magic_t * magic)
885{
886    drm_auth_t auth;
887
888    *magic = 0;
889    if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
890	return -errno;
891    *magic = auth.magic;
892    return 0;
893}
894
895int drmAuthMagic(int fd, drm_magic_t magic)
896{
897    drm_auth_t auth;
898
899    auth.magic = magic;
900    if (drmIoctl(fd, DRM_IOCTL_AUTH_MAGIC, &auth))
901	return -errno;
902    return 0;
903}
904
905/**
906 * Specifies a range of memory that is available for mapping by a
907 * non-root process.
908 *
909 * \param fd file descriptor.
910 * \param offset usually the physical address. The actual meaning depends of
911 * the \p type parameter. See below.
912 * \param size of the memory in bytes.
913 * \param type type of the memory to be mapped.
914 * \param flags combination of several flags to modify the function actions.
915 * \param handle will be set to a value that may be used as the offset
916 * parameter for mmap().
917 *
918 * \return zero on success or a negative value on error.
919 *
920 * \par Mapping the frame buffer
921 * For the frame buffer
922 * - \p offset will be the physical address of the start of the frame buffer,
923 * - \p size will be the size of the frame buffer in bytes, and
924 * - \p type will be DRM_FRAME_BUFFER.
925 *
926 * \par
927 * The area mapped will be uncached. If MTRR support is available in the
928 * kernel, the frame buffer area will be set to write combining.
929 *
930 * \par Mapping the MMIO register area
931 * For the MMIO register area,
932 * - \p offset will be the physical address of the start of the register area,
933 * - \p size will be the size of the register area bytes, and
934 * - \p type will be DRM_REGISTERS.
935 * \par
936 * The area mapped will be uncached.
937 *
938 * \par Mapping the SAREA
939 * For the SAREA,
940 * - \p offset will be ignored and should be set to zero,
941 * - \p size will be the desired size of the SAREA in bytes,
942 * - \p type will be DRM_SHM.
943 *
944 * \par
945 * A shared memory area of the requested size will be created and locked in
946 * kernel memory. This area may be mapped into client-space by using the handle
947 * returned.
948 *
949 * \note May only be called by root.
950 *
951 * \internal
952 * This function is a wrapper around the DRM_IOCTL_ADD_MAP ioctl, passing
953 * the arguments in a drm_map structure.
954 */
955int drmAddMap(int fd, drm_handle_t offset, drmSize size, drmMapType type,
956	      drmMapFlags flags, drm_handle_t *handle)
957{
958    drm_map_t map;
959
960    map.offset  = offset;
961    map.size    = size;
962    map.handle  = 0;
963    map.type    = type;
964    map.flags   = flags;
965    if (drmIoctl(fd, DRM_IOCTL_ADD_MAP, &map))
966	return -errno;
967    if (handle)
968	*handle = (drm_handle_t)map.handle;
969    return 0;
970}
971
972int drmRmMap(int fd, drm_handle_t handle)
973{
974    drm_map_t map;
975
976    map.handle = (void *)handle;
977
978    if(drmIoctl(fd, DRM_IOCTL_RM_MAP, &map))
979	return -errno;
980    return 0;
981}
982
983/**
984 * Make buffers available for DMA transfers.
985 *
986 * \param fd file descriptor.
987 * \param count number of buffers.
988 * \param size size of each buffer.
989 * \param flags buffer allocation flags.
990 * \param agp_offset offset in the AGP aperture
991 *
992 * \return number of buffers allocated, negative on error.
993 *
994 * \internal
995 * This function is a wrapper around DRM_IOCTL_ADD_BUFS ioctl.
996 *
997 * \sa drm_buf_desc.
998 */
999int drmAddBufs(int fd, int count, int size, drmBufDescFlags flags,
1000	       int agp_offset)
1001{
1002    drm_buf_desc_t request;
1003
1004    request.count     = count;
1005    request.size      = size;
1006    request.low_mark  = 0;
1007    request.high_mark = 0;
1008    request.flags     = flags;
1009    request.agp_start = agp_offset;
1010
1011    if (drmIoctl(fd, DRM_IOCTL_ADD_BUFS, &request))
1012	return -errno;
1013    return request.count;
1014}
1015
1016int drmMarkBufs(int fd, double low, double high)
1017{
1018    drm_buf_info_t info;
1019    int            i;
1020
1021    info.count = 0;
1022    info.list  = NULL;
1023
1024    if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1025	return -EINVAL;
1026
1027    if (!info.count)
1028	return -EINVAL;
1029
1030    if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1031	return -ENOMEM;
1032
1033    if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1034	int retval = -errno;
1035	drmFree(info.list);
1036	return retval;
1037    }
1038
1039    for (i = 0; i < info.count; i++) {
1040	info.list[i].low_mark  = low  * info.list[i].count;
1041	info.list[i].high_mark = high * info.list[i].count;
1042	if (drmIoctl(fd, DRM_IOCTL_MARK_BUFS, &info.list[i])) {
1043	    int retval = -errno;
1044	    drmFree(info.list);
1045	    return retval;
1046	}
1047    }
1048    drmFree(info.list);
1049
1050    return 0;
1051}
1052
1053/**
1054 * Free buffers.
1055 *
1056 * \param fd file descriptor.
1057 * \param count number of buffers to free.
1058 * \param list list of buffers to be freed.
1059 *
1060 * \return zero on success, or a negative value on failure.
1061 *
1062 * \note This function is primarily used for debugging.
1063 *
1064 * \internal
1065 * This function is a wrapper around the DRM_IOCTL_FREE_BUFS ioctl, passing
1066 * the arguments in a drm_buf_free structure.
1067 */
1068int drmFreeBufs(int fd, int count, int *list)
1069{
1070    drm_buf_free_t request;
1071
1072    request.count = count;
1073    request.list  = list;
1074    if (drmIoctl(fd, DRM_IOCTL_FREE_BUFS, &request))
1075	return -errno;
1076    return 0;
1077}
1078
1079
1080/**
1081 * Close the device.
1082 *
1083 * \param fd file descriptor.
1084 *
1085 * \internal
1086 * This function closes the file descriptor.
1087 */
1088int drmClose(int fd)
1089{
1090    unsigned long key    = drmGetKeyFromFd(fd);
1091    drmHashEntry  *entry = drmGetEntry(fd);
1092
1093    drmHashDestroy(entry->tagTable);
1094    entry->fd       = 0;
1095    entry->f        = NULL;
1096    entry->tagTable = NULL;
1097
1098    drmHashDelete(drmHashTable, key);
1099    drmFree(entry);
1100
1101    return close(fd);
1102}
1103
1104
1105/**
1106 * Map a region of memory.
1107 *
1108 * \param fd file descriptor.
1109 * \param handle handle returned by drmAddMap().
1110 * \param size size in bytes. Must match the size used by drmAddMap().
1111 * \param address will contain the user-space virtual address where the mapping
1112 * begins.
1113 *
1114 * \return zero on success, or a negative value on failure.
1115 *
1116 * \internal
1117 * This function is a wrapper for mmap().
1118 */
1119int drmMap(int fd, drm_handle_t handle, drmSize size, drmAddressPtr address)
1120{
1121    static unsigned long pagesize_mask = 0;
1122
1123    if (fd < 0)
1124	return -EINVAL;
1125
1126    if (!pagesize_mask)
1127	pagesize_mask = getpagesize() - 1;
1128
1129    size = (size + pagesize_mask) & ~pagesize_mask;
1130
1131    *address = mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1132    if (*address == MAP_FAILED)
1133	return -errno;
1134    return 0;
1135}
1136
1137
1138/**
1139 * Unmap mappings obtained with drmMap().
1140 *
1141 * \param address address as given by drmMap().
1142 * \param size size in bytes. Must match the size used by drmMap().
1143 *
1144 * \return zero on success, or a negative value on failure.
1145 *
1146 * \internal
1147 * This function is a wrapper for munmap().
1148 */
1149int drmUnmap(drmAddress address, drmSize size)
1150{
1151    return munmap(address, size);
1152}
1153
1154drmBufInfoPtr drmGetBufInfo(int fd)
1155{
1156    drm_buf_info_t info;
1157    drmBufInfoPtr  retval;
1158    int            i;
1159
1160    info.count = 0;
1161    info.list  = NULL;
1162
1163    if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1164	return NULL;
1165
1166    if (info.count) {
1167	if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1168	    return NULL;
1169
1170	if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1171	    drmFree(info.list);
1172	    return NULL;
1173	}
1174
1175	retval = drmMalloc(sizeof(*retval));
1176	retval->count = info.count;
1177	retval->list  = drmMalloc(info.count * sizeof(*retval->list));
1178	for (i = 0; i < info.count; i++) {
1179	    retval->list[i].count     = info.list[i].count;
1180	    retval->list[i].size      = info.list[i].size;
1181	    retval->list[i].low_mark  = info.list[i].low_mark;
1182	    retval->list[i].high_mark = info.list[i].high_mark;
1183	}
1184	drmFree(info.list);
1185	return retval;
1186    }
1187    return NULL;
1188}
1189
1190/**
1191 * Map all DMA buffers into client-virtual space.
1192 *
1193 * \param fd file descriptor.
1194 *
1195 * \return a pointer to a ::drmBufMap structure.
1196 *
1197 * \note The client may not use these buffers until obtaining buffer indices
1198 * with drmDMA().
1199 *
1200 * \internal
1201 * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1202 * information about the buffers in a drm_buf_map structure into the
1203 * client-visible data structures.
1204 */
1205drmBufMapPtr drmMapBufs(int fd)
1206{
1207    drm_buf_map_t bufs;
1208    drmBufMapPtr  retval;
1209    int           i;
1210
1211    bufs.count = 0;
1212    bufs.list  = NULL;
1213    bufs.virtual = NULL;
1214    if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1215	return NULL;
1216
1217    if (!bufs.count)
1218	return NULL;
1219
1220	if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1221	    return NULL;
1222
1223	if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1224	    drmFree(bufs.list);
1225	    return NULL;
1226	}
1227
1228	retval = drmMalloc(sizeof(*retval));
1229	retval->count = bufs.count;
1230	retval->list  = drmMalloc(bufs.count * sizeof(*retval->list));
1231	for (i = 0; i < bufs.count; i++) {
1232	    retval->list[i].idx     = bufs.list[i].idx;
1233	    retval->list[i].total   = bufs.list[i].total;
1234	    retval->list[i].used    = 0;
1235	    retval->list[i].address = bufs.list[i].address;
1236	}
1237
1238	drmFree(bufs.list);
1239
1240	return retval;
1241}
1242
1243
1244/**
1245 * Unmap buffers allocated with drmMapBufs().
1246 *
1247 * \return zero on success, or negative value on failure.
1248 *
1249 * \internal
1250 * Calls munmap() for every buffer stored in \p bufs and frees the
1251 * memory allocated by drmMapBufs().
1252 */
1253int drmUnmapBufs(drmBufMapPtr bufs)
1254{
1255    int i;
1256
1257    for (i = 0; i < bufs->count; i++) {
1258	munmap(bufs->list[i].address, bufs->list[i].total);
1259    }
1260
1261    drmFree(bufs->list);
1262    drmFree(bufs);
1263
1264    return 0;
1265}
1266
1267
1268#define DRM_DMA_RETRY		16
1269
1270/**
1271 * Reserve DMA buffers.
1272 *
1273 * \param fd file descriptor.
1274 * \param request
1275 *
1276 * \return zero on success, or a negative value on failure.
1277 *
1278 * \internal
1279 * Assemble the arguments into a drm_dma structure and keeps issuing the
1280 * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1281 */
1282int drmDMA(int fd, drmDMAReqPtr request)
1283{
1284    drm_dma_t dma;
1285    int ret, i = 0;
1286
1287    dma.context         = request->context;
1288    dma.send_count      = request->send_count;
1289    dma.send_indices    = request->send_list;
1290    dma.send_sizes      = request->send_sizes;
1291    dma.flags           = request->flags;
1292    dma.request_count   = request->request_count;
1293    dma.request_size    = request->request_size;
1294    dma.request_indices = request->request_list;
1295    dma.request_sizes   = request->request_sizes;
1296    dma.granted_count   = 0;
1297
1298    do {
1299	ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1300    } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1301
1302    if ( ret == 0 ) {
1303	request->granted_count = dma.granted_count;
1304	return 0;
1305    } else {
1306	return -errno;
1307    }
1308}
1309
1310
1311/**
1312 * Obtain heavyweight hardware lock.
1313 *
1314 * \param fd file descriptor.
1315 * \param context context.
1316 * \param flags flags that determine the sate of the hardware when the function
1317 * returns.
1318 *
1319 * \return always zero.
1320 *
1321 * \internal
1322 * This function translates the arguments into a drm_lock structure and issue
1323 * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1324 */
1325int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
1326{
1327    drm_lock_t lock;
1328
1329    lock.context = context;
1330    lock.flags   = 0;
1331    if (flags & DRM_LOCK_READY)      lock.flags |= _DRM_LOCK_READY;
1332    if (flags & DRM_LOCK_QUIESCENT)  lock.flags |= _DRM_LOCK_QUIESCENT;
1333    if (flags & DRM_LOCK_FLUSH)      lock.flags |= _DRM_LOCK_FLUSH;
1334    if (flags & DRM_LOCK_FLUSH_ALL)  lock.flags |= _DRM_LOCK_FLUSH_ALL;
1335    if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
1336    if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
1337
1338    while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
1339	;
1340    return 0;
1341}
1342
1343/**
1344 * Release the hardware lock.
1345 *
1346 * \param fd file descriptor.
1347 * \param context context.
1348 *
1349 * \return zero on success, or a negative value on failure.
1350 *
1351 * \internal
1352 * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
1353 * argument in a drm_lock structure.
1354 */
1355int drmUnlock(int fd, drm_context_t context)
1356{
1357    drm_lock_t lock;
1358
1359    lock.context = context;
1360    lock.flags   = 0;
1361    return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
1362}
1363
1364drm_context_t *drmGetReservedContextList(int fd, int *count)
1365{
1366    drm_ctx_res_t res;
1367    drm_ctx_t     *list;
1368    drm_context_t * retval;
1369    int           i;
1370
1371    res.count    = 0;
1372    res.contexts = NULL;
1373    if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1374	return NULL;
1375
1376    if (!res.count)
1377	return NULL;
1378
1379    if (!(list   = drmMalloc(res.count * sizeof(*list))))
1380	return NULL;
1381    if (!(retval = drmMalloc(res.count * sizeof(*retval)))) {
1382	drmFree(list);
1383	return NULL;
1384    }
1385
1386    res.contexts = list;
1387    if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1388	return NULL;
1389
1390    for (i = 0; i < res.count; i++)
1391	retval[i] = list[i].handle;
1392    drmFree(list);
1393
1394    *count = res.count;
1395    return retval;
1396}
1397
1398void drmFreeReservedContextList(drm_context_t *pt)
1399{
1400    drmFree(pt);
1401}
1402
1403/**
1404 * Create context.
1405 *
1406 * Used by the X server during GLXContext initialization. This causes
1407 * per-context kernel-level resources to be allocated.
1408 *
1409 * \param fd file descriptor.
1410 * \param handle is set on success. To be used by the client when requesting DMA
1411 * dispatch with drmDMA().
1412 *
1413 * \return zero on success, or a negative value on failure.
1414 *
1415 * \note May only be called by root.
1416 *
1417 * \internal
1418 * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
1419 * argument in a drm_ctx structure.
1420 */
1421int drmCreateContext(int fd, drm_context_t *handle)
1422{
1423    drm_ctx_t ctx;
1424
1425    ctx.flags = 0;	/* Modified with functions below */
1426    if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
1427	return -errno;
1428    *handle = ctx.handle;
1429    return 0;
1430}
1431
1432int drmSwitchToContext(int fd, drm_context_t context)
1433{
1434    drm_ctx_t ctx;
1435
1436    ctx.handle = context;
1437    if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
1438	return -errno;
1439    return 0;
1440}
1441
1442int drmSetContextFlags(int fd, drm_context_t context, drm_context_tFlags flags)
1443{
1444    drm_ctx_t ctx;
1445
1446    /*
1447     * Context preserving means that no context switches are done between DMA
1448     * buffers from one context and the next.  This is suitable for use in the
1449     * X server (which promises to maintain hardware context), or in the
1450     * client-side library when buffers are swapped on behalf of two threads.
1451     */
1452    ctx.handle = context;
1453    ctx.flags  = 0;
1454    if (flags & DRM_CONTEXT_PRESERVED)
1455	ctx.flags |= _DRM_CONTEXT_PRESERVED;
1456    if (flags & DRM_CONTEXT_2DONLY)
1457	ctx.flags |= _DRM_CONTEXT_2DONLY;
1458    if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
1459	return -errno;
1460    return 0;
1461}
1462
1463int drmGetContextFlags(int fd, drm_context_t context,
1464                       drm_context_tFlagsPtr flags)
1465{
1466    drm_ctx_t ctx;
1467
1468    ctx.handle = context;
1469    if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
1470	return -errno;
1471    *flags = 0;
1472    if (ctx.flags & _DRM_CONTEXT_PRESERVED)
1473	*flags |= DRM_CONTEXT_PRESERVED;
1474    if (ctx.flags & _DRM_CONTEXT_2DONLY)
1475	*flags |= DRM_CONTEXT_2DONLY;
1476    return 0;
1477}
1478
1479/**
1480 * Destroy context.
1481 *
1482 * Free any kernel-level resources allocated with drmCreateContext() associated
1483 * with the context.
1484 *
1485 * \param fd file descriptor.
1486 * \param handle handle given by drmCreateContext().
1487 *
1488 * \return zero on success, or a negative value on failure.
1489 *
1490 * \note May only be called by root.
1491 *
1492 * \internal
1493 * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
1494 * argument in a drm_ctx structure.
1495 */
1496int drmDestroyContext(int fd, drm_context_t handle)
1497{
1498    drm_ctx_t ctx;
1499    ctx.handle = handle;
1500    if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
1501	return -errno;
1502    return 0;
1503}
1504
1505int drmCreateDrawable(int fd, drm_drawable_t *handle)
1506{
1507    drm_draw_t draw;
1508    if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
1509	return -errno;
1510    *handle = draw.handle;
1511    return 0;
1512}
1513
1514int drmDestroyDrawable(int fd, drm_drawable_t handle)
1515{
1516    drm_draw_t draw;
1517    draw.handle = handle;
1518    if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
1519	return -errno;
1520    return 0;
1521}
1522
1523int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
1524			   drm_drawable_info_type_t type, unsigned int num,
1525			   void *data)
1526{
1527    drm_update_draw_t update;
1528
1529    update.handle = handle;
1530    update.type = type;
1531    update.num = num;
1532    update.data = (unsigned long long)(unsigned long)data;
1533
1534    if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
1535	return -errno;
1536
1537    return 0;
1538}
1539
1540/**
1541 * Acquire the AGP device.
1542 *
1543 * Must be called before any of the other AGP related calls.
1544 *
1545 * \param fd file descriptor.
1546 *
1547 * \return zero on success, or a negative value on failure.
1548 *
1549 * \internal
1550 * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
1551 */
1552int drmAgpAcquire(int fd)
1553{
1554    if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
1555	return -errno;
1556    return 0;
1557}
1558
1559
1560/**
1561 * Release the AGP device.
1562 *
1563 * \param fd file descriptor.
1564 *
1565 * \return zero on success, or a negative value on failure.
1566 *
1567 * \internal
1568 * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
1569 */
1570int drmAgpRelease(int fd)
1571{
1572    if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
1573	return -errno;
1574    return 0;
1575}
1576
1577
1578/**
1579 * Set the AGP mode.
1580 *
1581 * \param fd file descriptor.
1582 * \param mode AGP mode.
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_ENABLE ioctl, passing the
1588 * argument in a drm_agp_mode structure.
1589 */
1590int drmAgpEnable(int fd, unsigned long mode)
1591{
1592    drm_agp_mode_t m;
1593
1594    m.mode = mode;
1595    if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
1596	return -errno;
1597    return 0;
1598}
1599
1600
1601/**
1602 * Allocate a chunk of AGP memory.
1603 *
1604 * \param fd file descriptor.
1605 * \param size requested memory size in bytes. Will be rounded to page boundary.
1606 * \param type type of memory to allocate.
1607 * \param address if not zero, will be set to the physical address of the
1608 * allocated memory.
1609 * \param handle on success will be set to a handle of the allocated memory.
1610 *
1611 * \return zero on success, or a negative value on failure.
1612 *
1613 * \internal
1614 * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
1615 * arguments in a drm_agp_buffer structure.
1616 */
1617int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
1618		unsigned long *address, drm_handle_t *handle)
1619{
1620    drm_agp_buffer_t b;
1621
1622    *handle = DRM_AGP_NO_HANDLE;
1623    b.size   = size;
1624    b.handle = 0;
1625    b.type   = type;
1626    if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
1627	return -errno;
1628    if (address != 0UL)
1629	*address = b.physical;
1630    *handle = b.handle;
1631    return 0;
1632}
1633
1634
1635/**
1636 * Free a chunk of AGP memory.
1637 *
1638 * \param fd file descriptor.
1639 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1640 *
1641 * \return zero on success, or a negative value on failure.
1642 *
1643 * \internal
1644 * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
1645 * argument in a drm_agp_buffer structure.
1646 */
1647int drmAgpFree(int fd, drm_handle_t handle)
1648{
1649    drm_agp_buffer_t b;
1650
1651    b.size   = 0;
1652    b.handle = handle;
1653    if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
1654	return -errno;
1655    return 0;
1656}
1657
1658
1659/**
1660 * Bind a chunk of AGP memory.
1661 *
1662 * \param fd file descriptor.
1663 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1664 * \param offset offset in bytes. It will round to page boundary.
1665 *
1666 * \return zero on success, or a negative value on failure.
1667 *
1668 * \internal
1669 * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
1670 * argument in a drm_agp_binding structure.
1671 */
1672int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
1673{
1674    drm_agp_binding_t b;
1675
1676    b.handle = handle;
1677    b.offset = offset;
1678    if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
1679	return -errno;
1680    return 0;
1681}
1682
1683
1684/**
1685 * Unbind a chunk of AGP memory.
1686 *
1687 * \param fd file descriptor.
1688 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1689 *
1690 * \return zero on success, or a negative value on failure.
1691 *
1692 * \internal
1693 * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
1694 * the argument in a drm_agp_binding structure.
1695 */
1696int drmAgpUnbind(int fd, drm_handle_t handle)
1697{
1698    drm_agp_binding_t b;
1699
1700    b.handle = handle;
1701    b.offset = 0;
1702    if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
1703	return -errno;
1704    return 0;
1705}
1706
1707
1708/**
1709 * Get AGP driver major version number.
1710 *
1711 * \param fd file descriptor.
1712 *
1713 * \return major version number on success, or a negative value on failure..
1714 *
1715 * \internal
1716 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1717 * necessary information in a drm_agp_info structure.
1718 */
1719int drmAgpVersionMajor(int fd)
1720{
1721    drm_agp_info_t i;
1722
1723    if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1724	return -errno;
1725    return i.agp_version_major;
1726}
1727
1728
1729/**
1730 * Get AGP driver minor version number.
1731 *
1732 * \param fd file descriptor.
1733 *
1734 * \return minor version number on success, or a negative value on failure.
1735 *
1736 * \internal
1737 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1738 * necessary information in a drm_agp_info structure.
1739 */
1740int drmAgpVersionMinor(int fd)
1741{
1742    drm_agp_info_t i;
1743
1744    if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1745	return -errno;
1746    return i.agp_version_minor;
1747}
1748
1749
1750/**
1751 * Get AGP mode.
1752 *
1753 * \param fd file descriptor.
1754 *
1755 * \return mode on success, or zero on failure.
1756 *
1757 * \internal
1758 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1759 * necessary information in a drm_agp_info structure.
1760 */
1761unsigned long drmAgpGetMode(int fd)
1762{
1763    drm_agp_info_t i;
1764
1765    if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1766	return 0;
1767    return i.mode;
1768}
1769
1770
1771/**
1772 * Get AGP aperture base.
1773 *
1774 * \param fd file descriptor.
1775 *
1776 * \return aperture base on success, zero on failure.
1777 *
1778 * \internal
1779 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1780 * necessary information in a drm_agp_info structure.
1781 */
1782unsigned long drmAgpBase(int fd)
1783{
1784    drm_agp_info_t i;
1785
1786    if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1787	return 0;
1788    return i.aperture_base;
1789}
1790
1791
1792/**
1793 * Get AGP aperture size.
1794 *
1795 * \param fd file descriptor.
1796 *
1797 * \return aperture size on success, zero on failure.
1798 *
1799 * \internal
1800 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1801 * necessary information in a drm_agp_info structure.
1802 */
1803unsigned long drmAgpSize(int fd)
1804{
1805    drm_agp_info_t i;
1806
1807    if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1808	return 0;
1809    return i.aperture_size;
1810}
1811
1812
1813/**
1814 * Get used AGP memory.
1815 *
1816 * \param fd file descriptor.
1817 *
1818 * \return memory used on success, or zero on failure.
1819 *
1820 * \internal
1821 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1822 * necessary information in a drm_agp_info structure.
1823 */
1824unsigned long drmAgpMemoryUsed(int fd)
1825{
1826    drm_agp_info_t i;
1827
1828    if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1829	return 0;
1830    return i.memory_used;
1831}
1832
1833
1834/**
1835 * Get available AGP memory.
1836 *
1837 * \param fd file descriptor.
1838 *
1839 * \return memory available on success, or zero on failure.
1840 *
1841 * \internal
1842 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1843 * necessary information in a drm_agp_info structure.
1844 */
1845unsigned long drmAgpMemoryAvail(int fd)
1846{
1847    drm_agp_info_t i;
1848
1849    if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1850	return 0;
1851    return i.memory_allowed;
1852}
1853
1854
1855/**
1856 * Get hardware vendor ID.
1857 *
1858 * \param fd file descriptor.
1859 *
1860 * \return vendor ID on success, or zero on failure.
1861 *
1862 * \internal
1863 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1864 * necessary information in a drm_agp_info structure.
1865 */
1866unsigned int drmAgpVendorId(int fd)
1867{
1868    drm_agp_info_t i;
1869
1870    if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1871	return 0;
1872    return i.id_vendor;
1873}
1874
1875
1876/**
1877 * Get hardware device ID.
1878 *
1879 * \param fd file descriptor.
1880 *
1881 * \return zero on success, or zero on failure.
1882 *
1883 * \internal
1884 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1885 * necessary information in a drm_agp_info structure.
1886 */
1887unsigned int drmAgpDeviceId(int fd)
1888{
1889    drm_agp_info_t i;
1890
1891    if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1892	return 0;
1893    return i.id_device;
1894}
1895
1896int drmScatterGatherAlloc(int fd, unsigned long size, drm_handle_t *handle)
1897{
1898    drm_scatter_gather_t sg;
1899
1900    *handle = 0;
1901    sg.size   = size;
1902    sg.handle = 0;
1903    if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
1904	return -errno;
1905    *handle = sg.handle;
1906    return 0;
1907}
1908
1909int drmScatterGatherFree(int fd, drm_handle_t handle)
1910{
1911    drm_scatter_gather_t sg;
1912
1913    sg.size   = 0;
1914    sg.handle = handle;
1915    if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
1916	return -errno;
1917    return 0;
1918}
1919
1920/**
1921 * Wait for VBLANK.
1922 *
1923 * \param fd file descriptor.
1924 * \param vbl pointer to a drmVBlank structure.
1925 *
1926 * \return zero on success, or a negative value on failure.
1927 *
1928 * \internal
1929 * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
1930 */
1931int drmWaitVBlank(int fd, drmVBlankPtr vbl)
1932{
1933    struct timespec timeout, cur;
1934    int ret;
1935
1936    ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
1937    if (ret < 0) {
1938	fprintf(stderr, "clock_gettime failed: %s\n", strerror(ret));
1939	goto out;
1940    }
1941    timeout.tv_sec++;
1942
1943    do {
1944       ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
1945       vbl->request.type &= ~DRM_VBLANK_RELATIVE;
1946       if (ret && errno == EINTR) {
1947	       clock_gettime(CLOCK_MONOTONIC, &cur);
1948	       /* Timeout after 1s */
1949	       if (cur.tv_sec > timeout.tv_sec + 1 ||
1950		   (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
1951		    timeout.tv_nsec)) {
1952		       errno = EBUSY;
1953		       ret = -1;
1954		       break;
1955	       }
1956       }
1957    } while (ret && errno == EINTR);
1958
1959out:
1960    return ret;
1961}
1962
1963int drmError(int err, const char *label)
1964{
1965    switch (err) {
1966    case DRM_ERR_NO_DEVICE:
1967	fprintf(stderr, "%s: no device\n", label);
1968	break;
1969    case DRM_ERR_NO_ACCESS:
1970	fprintf(stderr, "%s: no access\n", label);
1971	break;
1972    case DRM_ERR_NOT_ROOT:
1973	fprintf(stderr, "%s: not root\n", label);
1974	break;
1975    case DRM_ERR_INVALID:
1976	fprintf(stderr, "%s: invalid args\n", label);
1977	break;
1978    default:
1979	if (err < 0)
1980	    err = -err;
1981	fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
1982	break;
1983    }
1984
1985    return 1;
1986}
1987
1988/**
1989 * Install IRQ handler.
1990 *
1991 * \param fd file descriptor.
1992 * \param irq IRQ number.
1993 *
1994 * \return zero on success, or a negative value on failure.
1995 *
1996 * \internal
1997 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
1998 * argument in a drm_control structure.
1999 */
2000int drmCtlInstHandler(int fd, int irq)
2001{
2002    drm_control_t ctl;
2003
2004    ctl.func  = DRM_INST_HANDLER;
2005    ctl.irq   = irq;
2006    if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2007	return -errno;
2008    return 0;
2009}
2010
2011
2012/**
2013 * Uninstall IRQ handler.
2014 *
2015 * \param fd file descriptor.
2016 *
2017 * \return zero on success, or a negative value on failure.
2018 *
2019 * \internal
2020 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2021 * argument in a drm_control structure.
2022 */
2023int drmCtlUninstHandler(int fd)
2024{
2025    drm_control_t ctl;
2026
2027    ctl.func  = DRM_UNINST_HANDLER;
2028    ctl.irq   = 0;
2029    if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2030	return -errno;
2031    return 0;
2032}
2033
2034int drmFinish(int fd, int context, drmLockFlags flags)
2035{
2036    drm_lock_t lock;
2037
2038    lock.context = context;
2039    lock.flags   = 0;
2040    if (flags & DRM_LOCK_READY)      lock.flags |= _DRM_LOCK_READY;
2041    if (flags & DRM_LOCK_QUIESCENT)  lock.flags |= _DRM_LOCK_QUIESCENT;
2042    if (flags & DRM_LOCK_FLUSH)      lock.flags |= _DRM_LOCK_FLUSH;
2043    if (flags & DRM_LOCK_FLUSH_ALL)  lock.flags |= _DRM_LOCK_FLUSH_ALL;
2044    if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2045    if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2046    if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2047	return -errno;
2048    return 0;
2049}
2050
2051/**
2052 * Get IRQ from bus ID.
2053 *
2054 * \param fd file descriptor.
2055 * \param busnum bus number.
2056 * \param devnum device number.
2057 * \param funcnum function number.
2058 *
2059 * \return IRQ number on success, or a negative value on failure.
2060 *
2061 * \internal
2062 * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2063 * arguments in a drm_irq_busid structure.
2064 */
2065int drmGetInterruptFromBusID(int fd, int busnum, int devnum, int funcnum)
2066{
2067    drm_irq_busid_t p;
2068
2069    p.busnum  = busnum;
2070    p.devnum  = devnum;
2071    p.funcnum = funcnum;
2072    if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2073	return -errno;
2074    return p.irq;
2075}
2076
2077int drmAddContextTag(int fd, drm_context_t context, void *tag)
2078{
2079    drmHashEntry  *entry = drmGetEntry(fd);
2080
2081    if (drmHashInsert(entry->tagTable, context, tag)) {
2082	drmHashDelete(entry->tagTable, context);
2083	drmHashInsert(entry->tagTable, context, tag);
2084    }
2085    return 0;
2086}
2087
2088int drmDelContextTag(int fd, drm_context_t context)
2089{
2090    drmHashEntry  *entry = drmGetEntry(fd);
2091
2092    return drmHashDelete(entry->tagTable, context);
2093}
2094
2095void *drmGetContextTag(int fd, drm_context_t context)
2096{
2097    drmHashEntry  *entry = drmGetEntry(fd);
2098    void          *value;
2099
2100    if (drmHashLookup(entry->tagTable, context, &value))
2101	return NULL;
2102
2103    return value;
2104}
2105
2106int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2107                                drm_handle_t handle)
2108{
2109    drm_ctx_priv_map_t map;
2110
2111    map.ctx_id = ctx_id;
2112    map.handle = (void *)handle;
2113
2114    if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2115	return -errno;
2116    return 0;
2117}
2118
2119int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2120                                drm_handle_t *handle)
2121{
2122    drm_ctx_priv_map_t map;
2123
2124    map.ctx_id = ctx_id;
2125
2126    if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2127	return -errno;
2128    if (handle)
2129	*handle = (drm_handle_t)map.handle;
2130
2131    return 0;
2132}
2133
2134int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2135	      drmMapType *type, drmMapFlags *flags, drm_handle_t *handle,
2136	      int *mtrr)
2137{
2138    drm_map_t map;
2139
2140    map.offset = idx;
2141    if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2142	return -errno;
2143    *offset = map.offset;
2144    *size   = map.size;
2145    *type   = map.type;
2146    *flags  = map.flags;
2147    *handle = (unsigned long)map.handle;
2148    *mtrr   = map.mtrr;
2149    return 0;
2150}
2151
2152int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2153		 unsigned long *magic, unsigned long *iocs)
2154{
2155    drm_client_t client;
2156
2157    client.idx = idx;
2158    if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2159	return -errno;
2160    *auth      = client.auth;
2161    *pid       = client.pid;
2162    *uid       = client.uid;
2163    *magic     = client.magic;
2164    *iocs      = client.iocs;
2165    return 0;
2166}
2167
2168int drmGetStats(int fd, drmStatsT *stats)
2169{
2170    drm_stats_t s;
2171    int         i;
2172
2173    if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2174	return -errno;
2175
2176    stats->count = 0;
2177    memset(stats, 0, sizeof(*stats));
2178    if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2179	return -1;
2180
2181#define SET_VALUE                              \
2182    stats->data[i].long_format = "%-20.20s";   \
2183    stats->data[i].rate_format = "%8.8s";      \
2184    stats->data[i].isvalue     = 1;            \
2185    stats->data[i].verbose     = 0
2186
2187#define SET_COUNT                              \
2188    stats->data[i].long_format = "%-20.20s";   \
2189    stats->data[i].rate_format = "%5.5s";      \
2190    stats->data[i].isvalue     = 0;            \
2191    stats->data[i].mult_names  = "kgm";        \
2192    stats->data[i].mult        = 1000;         \
2193    stats->data[i].verbose     = 0
2194
2195#define SET_BYTE                               \
2196    stats->data[i].long_format = "%-20.20s";   \
2197    stats->data[i].rate_format = "%5.5s";      \
2198    stats->data[i].isvalue     = 0;            \
2199    stats->data[i].mult_names  = "KGM";        \
2200    stats->data[i].mult        = 1024;         \
2201    stats->data[i].verbose     = 0
2202
2203
2204    stats->count = s.count;
2205    for (i = 0; i < s.count; i++) {
2206	stats->data[i].value = s.data[i].value;
2207	switch (s.data[i].type) {
2208	case _DRM_STAT_LOCK:
2209	    stats->data[i].long_name = "Lock";
2210	    stats->data[i].rate_name = "Lock";
2211	    SET_VALUE;
2212	    break;
2213	case _DRM_STAT_OPENS:
2214	    stats->data[i].long_name = "Opens";
2215	    stats->data[i].rate_name = "O";
2216	    SET_COUNT;
2217	    stats->data[i].verbose   = 1;
2218	    break;
2219	case _DRM_STAT_CLOSES:
2220	    stats->data[i].long_name = "Closes";
2221	    stats->data[i].rate_name = "Lock";
2222	    SET_COUNT;
2223	    stats->data[i].verbose   = 1;
2224	    break;
2225	case _DRM_STAT_IOCTLS:
2226	    stats->data[i].long_name = "Ioctls";
2227	    stats->data[i].rate_name = "Ioc/s";
2228	    SET_COUNT;
2229	    break;
2230	case _DRM_STAT_LOCKS:
2231	    stats->data[i].long_name = "Locks";
2232	    stats->data[i].rate_name = "Lck/s";
2233	    SET_COUNT;
2234	    break;
2235	case _DRM_STAT_UNLOCKS:
2236	    stats->data[i].long_name = "Unlocks";
2237	    stats->data[i].rate_name = "Unl/s";
2238	    SET_COUNT;
2239	    break;
2240	case _DRM_STAT_IRQ:
2241	    stats->data[i].long_name = "IRQs";
2242	    stats->data[i].rate_name = "IRQ/s";
2243	    SET_COUNT;
2244	    break;
2245	case _DRM_STAT_PRIMARY:
2246	    stats->data[i].long_name = "Primary Bytes";
2247	    stats->data[i].rate_name = "PB/s";
2248	    SET_BYTE;
2249	    break;
2250	case _DRM_STAT_SECONDARY:
2251	    stats->data[i].long_name = "Secondary Bytes";
2252	    stats->data[i].rate_name = "SB/s";
2253	    SET_BYTE;
2254	    break;
2255	case _DRM_STAT_DMA:
2256	    stats->data[i].long_name = "DMA";
2257	    stats->data[i].rate_name = "DMA/s";
2258	    SET_COUNT;
2259	    break;
2260	case _DRM_STAT_SPECIAL:
2261	    stats->data[i].long_name = "Special DMA";
2262	    stats->data[i].rate_name = "dma/s";
2263	    SET_COUNT;
2264	    break;
2265	case _DRM_STAT_MISSED:
2266	    stats->data[i].long_name = "Miss";
2267	    stats->data[i].rate_name = "Ms/s";
2268	    SET_COUNT;
2269	    break;
2270	case _DRM_STAT_VALUE:
2271	    stats->data[i].long_name = "Value";
2272	    stats->data[i].rate_name = "Value";
2273	    SET_VALUE;
2274	    break;
2275	case _DRM_STAT_BYTE:
2276	    stats->data[i].long_name = "Bytes";
2277	    stats->data[i].rate_name = "B/s";
2278	    SET_BYTE;
2279	    break;
2280	case _DRM_STAT_COUNT:
2281	default:
2282	    stats->data[i].long_name = "Count";
2283	    stats->data[i].rate_name = "Cnt/s";
2284	    SET_COUNT;
2285	    break;
2286	}
2287    }
2288    return 0;
2289}
2290
2291/**
2292 * Issue a set-version ioctl.
2293 *
2294 * \param fd file descriptor.
2295 * \param drmCommandIndex command index
2296 * \param data source pointer of the data to be read and written.
2297 * \param size size of the data to be read and written.
2298 *
2299 * \return zero on success, or a negative value on failure.
2300 *
2301 * \internal
2302 * It issues a read-write ioctl given by
2303 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2304 */
2305int drmSetInterfaceVersion(int fd, drmSetVersion *version)
2306{
2307    int retcode = 0;
2308    drm_set_version_t sv;
2309
2310    sv.drm_di_major = version->drm_di_major;
2311    sv.drm_di_minor = version->drm_di_minor;
2312    sv.drm_dd_major = version->drm_dd_major;
2313    sv.drm_dd_minor = version->drm_dd_minor;
2314
2315    if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
2316	retcode = -errno;
2317    }
2318
2319    version->drm_di_major = sv.drm_di_major;
2320    version->drm_di_minor = sv.drm_di_minor;
2321    version->drm_dd_major = sv.drm_dd_major;
2322    version->drm_dd_minor = sv.drm_dd_minor;
2323
2324    return retcode;
2325}
2326
2327/**
2328 * Send a device-specific command.
2329 *
2330 * \param fd file descriptor.
2331 * \param drmCommandIndex command index
2332 *
2333 * \return zero on success, or a negative value on failure.
2334 *
2335 * \internal
2336 * It issues a ioctl given by
2337 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2338 */
2339int drmCommandNone(int fd, unsigned long drmCommandIndex)
2340{
2341    void *data = NULL; /* dummy */
2342    unsigned long request;
2343
2344    request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
2345
2346    if (drmIoctl(fd, request, data)) {
2347	return -errno;
2348    }
2349    return 0;
2350}
2351
2352
2353/**
2354 * Send a device-specific read command.
2355 *
2356 * \param fd file descriptor.
2357 * \param drmCommandIndex command index
2358 * \param data destination pointer of the data to be read.
2359 * \param size size of the data to be read.
2360 *
2361 * \return zero on success, or a negative value on failure.
2362 *
2363 * \internal
2364 * It issues a read ioctl given by
2365 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2366 */
2367int drmCommandRead(int fd, unsigned long drmCommandIndex, void *data,
2368                   unsigned long size)
2369{
2370    unsigned long request;
2371
2372    request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
2373	DRM_COMMAND_BASE + drmCommandIndex, size);
2374
2375    if (drmIoctl(fd, request, data)) {
2376	return -errno;
2377    }
2378    return 0;
2379}
2380
2381
2382/**
2383 * Send a device-specific write command.
2384 *
2385 * \param fd file descriptor.
2386 * \param drmCommandIndex command index
2387 * \param data source pointer of the data to be written.
2388 * \param size size of the data to be written.
2389 *
2390 * \return zero on success, or a negative value on failure.
2391 *
2392 * \internal
2393 * It issues a write ioctl given by
2394 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2395 */
2396int drmCommandWrite(int fd, unsigned long drmCommandIndex, void *data,
2397                    unsigned long size)
2398{
2399    unsigned long request;
2400
2401    request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
2402	DRM_COMMAND_BASE + drmCommandIndex, size);
2403
2404    if (drmIoctl(fd, request, data)) {
2405	return -errno;
2406    }
2407    return 0;
2408}
2409
2410
2411/**
2412 * Send a device-specific read-write command.
2413 *
2414 * \param fd file descriptor.
2415 * \param drmCommandIndex command index
2416 * \param data source pointer of the data to be read and written.
2417 * \param size size of the data to be read and written.
2418 *
2419 * \return zero on success, or a negative value on failure.
2420 *
2421 * \internal
2422 * It issues a read-write ioctl given by
2423 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2424 */
2425int drmCommandWriteRead(int fd, unsigned long drmCommandIndex, void *data,
2426                        unsigned long size)
2427{
2428    unsigned long request;
2429
2430    request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
2431	DRM_COMMAND_BASE + drmCommandIndex, size);
2432
2433    if (drmIoctl(fd, request, data))
2434	return -errno;
2435    return 0;
2436}
2437
2438#define DRM_MAX_FDS 16
2439static struct {
2440    char *BusID;
2441    int fd;
2442    int refcount;
2443} connection[DRM_MAX_FDS];
2444
2445static int nr_fds = 0;
2446
2447int drmOpenOnce(void *unused,
2448		const char *BusID,
2449		int *newlyopened)
2450{
2451    int i;
2452    int fd;
2453
2454    for (i = 0; i < nr_fds; i++)
2455	if (strcmp(BusID, connection[i].BusID) == 0) {
2456	    connection[i].refcount++;
2457	    *newlyopened = 0;
2458	    return connection[i].fd;
2459	}
2460
2461    fd = drmOpen(unused, BusID);
2462    if (fd <= 0 || nr_fds == DRM_MAX_FDS)
2463	return fd;
2464
2465    connection[nr_fds].BusID = strdup(BusID);
2466    connection[nr_fds].fd = fd;
2467    connection[nr_fds].refcount = 1;
2468    *newlyopened = 1;
2469
2470    if (0)
2471	fprintf(stderr, "saved connection %d for %s %d\n",
2472		nr_fds, connection[nr_fds].BusID,
2473		strcmp(BusID, connection[nr_fds].BusID));
2474
2475    nr_fds++;
2476
2477    return fd;
2478}
2479
2480void drmCloseOnce(int fd)
2481{
2482    int i;
2483
2484    for (i = 0; i < nr_fds; i++) {
2485	if (fd == connection[i].fd) {
2486	    if (--connection[i].refcount == 0) {
2487		drmClose(connection[i].fd);
2488		free(connection[i].BusID);
2489
2490		if (i < --nr_fds)
2491		    connection[i] = connection[nr_fds];
2492
2493		return;
2494	    }
2495	}
2496    }
2497}
2498
2499int drmSetMaster(int fd)
2500{
2501	return ioctl(fd, DRM_IOCTL_SET_MASTER, 0);
2502}
2503
2504int drmDropMaster(int fd)
2505{
2506	return ioctl(fd, DRM_IOCTL_DROP_MASTER, 0);
2507}
2508
2509char *drmGetDeviceNameFromFd(int fd)
2510{
2511	char name[128];
2512	struct stat sbuf;
2513	dev_t d;
2514	int i;
2515
2516	/* The whole drmOpen thing is a fiasco and we need to find a way
2517	 * back to just using open(2).  For now, however, lets just make
2518	 * things worse with even more ad hoc directory walking code to
2519	 * discover the device file name. */
2520
2521	fstat(fd, &sbuf);
2522	d = sbuf.st_rdev;
2523
2524	for (i = 0; i < DRM_MAX_MINOR; i++) {
2525		snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
2526		if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
2527			break;
2528	}
2529	if (i == DRM_MAX_MINOR)
2530		return NULL;
2531
2532	return strdup(name);
2533}
2534