3 * User-level interface to DRM device
5 * \author Rickard E. (Rik) Faith <faith@valinux.com>
6 * \author Kevin E. Martin <martin@valinux.com>
10 * Copyright 1999 Precision Insight, Inc., Cedar Park, Texas.
11 * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California.
12 * All Rights Reserved.
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:
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
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.
49 #include <sys/types.h>
51 #define stat_t struct stat
52 #include <sys/ioctl.h>
55 #ifdef HAVE_SYS_MKDEV_H
56 # include <sys/mkdev.h> /* defines major(), minor(), and makedev() on Solaris */
60 /* Not all systems have MAP_FAILED defined */
62 #define MAP_FAILED ((void *)-1)
66 #include "libdrm_macros.h"
68 #include "util_math.h"
71 #define DRM_PRIMARY_MINOR_NAME "drm"
72 #define DRM_CONTROL_MINOR_NAME "drmC"
73 #define DRM_RENDER_MINOR_NAME "drmR"
75 #define DRM_PRIMARY_MINOR_NAME "card"
76 #define DRM_CONTROL_MINOR_NAME "controlD"
77 #define DRM_RENDER_MINOR_NAME "renderD"
80 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
94 #endif /* __OpenBSD__ */
97 #define DRM_MAJOR 226 /* Linux */
101 * This definition needs to be changed on some systems if dev_t is a structure.
102 * If there is a header file we can get it from, there would be best.
105 #define makedev(x,y) ((dev_t)(((x) << 8) | (y)))
108 #define DRM_MSG_VERBOSITY 3
110 #define memclear(s) memset(&s, 0, sizeof(s))
112 static drmServerInfoPtr drm_server_info;
114 void drmSetServerInfo(drmServerInfoPtr info)
116 drm_server_info = info;
120 * Output a message to stderr.
122 * \param format printf() like format string.
125 * This function is a wrapper around vfprintf().
128 static int DRM_PRINTFLIKE(1, 0)
129 drmDebugPrint(const char *format, va_list ap)
131 return vfprintf(stderr, format, ap);
135 drmMsg(const char *format, ...)
139 if (((env = getenv("LIBGL_DEBUG")) && strstr(env, "verbose")) ||
140 (drm_server_info && drm_server_info->debug_print))
142 va_start(ap, format);
143 if (drm_server_info) {
144 drm_server_info->debug_print(format,ap);
146 drmDebugPrint(format, ap);
152 static void *drmHashTable = NULL; /* Context switch callbacks */
154 void *drmGetHashTable(void)
159 void *drmMalloc(int size)
161 return calloc(1, size);
164 void drmFree(void *pt)
170 * Call ioctl, restarting if it is interupted
173 drmIoctl(int fd, unsigned long request, void *arg)
178 ret = ioctl(fd, request, arg);
179 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
183 static unsigned long drmGetKeyFromFd(int fd)
192 drmHashEntry *drmGetEntry(int fd)
194 unsigned long key = drmGetKeyFromFd(fd);
199 drmHashTable = drmHashCreate();
201 if (drmHashLookup(drmHashTable, key, &value)) {
202 entry = drmMalloc(sizeof(*entry));
205 entry->tagTable = drmHashCreate();
206 drmHashInsert(drmHashTable, key, entry);
214 * Compare two busid strings
219 * \return 1 if matched.
222 * This function compares two bus ID strings. It understands the older
223 * PCI:b:d:f format and the newer pci:oooo:bb:dd.f format. In the format, o is
224 * domain, b is bus, d is device, f is function.
226 static int drmMatchBusID(const char *id1, const char *id2, int pci_domain_ok)
228 /* First, check if the IDs are exactly the same */
229 if (strcasecmp(id1, id2) == 0)
232 /* Try to match old/new-style PCI bus IDs. */
233 if (strncasecmp(id1, "pci", 3) == 0) {
234 unsigned int o1, b1, d1, f1;
235 unsigned int o2, b2, d2, f2;
238 ret = sscanf(id1, "pci:%04x:%02x:%02x.%u", &o1, &b1, &d1, &f1);
241 ret = sscanf(id1, "PCI:%u:%u:%u", &b1, &d1, &f1);
246 ret = sscanf(id2, "pci:%04x:%02x:%02x.%u", &o2, &b2, &d2, &f2);
249 ret = sscanf(id2, "PCI:%u:%u:%u", &b2, &d2, &f2);
254 /* If domains aren't properly supported by the kernel interface,
255 * just ignore them, which sucks less than picking a totally random
256 * card with "open by name"
261 if ((o1 != o2) || (b1 != b2) || (d1 != d2) || (f1 != f2))
270 * Handles error checking for chown call.
272 * \param path to file.
273 * \param id of the new owner.
274 * \param id of the new group.
276 * \return zero if success or -1 if failure.
279 * Checks for failure. If failure was caused by signal call chown again.
280 * If any other failure happened then it will output error mesage using
284 static int chown_check_return(const char *path, uid_t owner, gid_t group)
289 rv = chown(path, owner, group);
290 } while (rv != 0 && errno == EINTR);
295 drmMsg("Failed to change owner or group for file %s! %d: %s\n",
296 path, errno, strerror(errno));
302 * Open the DRM device, creating it if necessary.
304 * \param dev major and minor numbers of the device.
305 * \param minor minor number of the device.
307 * \return a file descriptor on success, or a negative value on error.
310 * Assembles the device name from \p minor and opens it, creating the device
311 * special file node with the major and minor numbers specified by \p dev and
312 * parent directory if necessary and was called by root.
314 static int drmOpenDevice(dev_t dev, int minor, int type)
317 const char *dev_name;
320 mode_t devmode = DRM_DEV_MODE, serv_mode;
323 int isroot = !geteuid();
324 uid_t user = DRM_DEV_UID;
325 gid_t group = DRM_DEV_GID;
329 case DRM_NODE_PRIMARY:
330 dev_name = DRM_DEV_NAME;
332 case DRM_NODE_CONTROL:
333 dev_name = DRM_CONTROL_DEV_NAME;
335 case DRM_NODE_RENDER:
336 dev_name = DRM_RENDER_DEV_NAME;
342 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
343 drmMsg("drmOpenDevice: node name is %s\n", buf);
345 if (drm_server_info && drm_server_info->get_perms) {
346 drm_server_info->get_perms(&serv_group, &serv_mode);
347 devmode = serv_mode ? serv_mode : DRM_DEV_MODE;
348 devmode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
352 if (stat(DRM_DIR_NAME, &st)) {
354 return DRM_ERR_NOT_ROOT;
355 mkdir(DRM_DIR_NAME, DRM_DEV_DIRMODE);
356 chown_check_return(DRM_DIR_NAME, 0, 0); /* root:root */
357 chmod(DRM_DIR_NAME, DRM_DEV_DIRMODE);
360 /* Check if the device node exists and create it if necessary. */
361 if (stat(buf, &st)) {
363 return DRM_ERR_NOT_ROOT;
365 mknod(buf, S_IFCHR | devmode, dev);
368 if (drm_server_info && drm_server_info->get_perms) {
369 group = ((int)serv_group >= 0) ? serv_group : DRM_DEV_GID;
370 chown_check_return(buf, user, group);
374 /* if we modprobed then wait for udev */
378 if (stat(DRM_DIR_NAME, &st)) {
382 if (udev_count == 50)
387 if (stat(buf, &st)) {
391 if (udev_count == 50)
398 fd = open(buf, O_RDWR, 0);
399 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
400 fd, fd < 0 ? strerror(errno) : "OK");
405 /* Check if the device node is not what we expect it to be, and recreate it
406 * and try again if so.
408 if (st.st_rdev != dev) {
410 return DRM_ERR_NOT_ROOT;
412 mknod(buf, S_IFCHR | devmode, dev);
413 if (drm_server_info && drm_server_info->get_perms) {
414 chown_check_return(buf, user, group);
418 fd = open(buf, O_RDWR, 0);
419 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
420 fd, fd < 0 ? strerror(errno) : "OK");
424 drmMsg("drmOpenDevice: Open failed\n");
432 * Open the DRM device
434 * \param minor device minor number.
435 * \param create allow to create the device if set.
437 * \return a file descriptor on success, or a negative value on error.
440 * Calls drmOpenDevice() if \p create is set, otherwise assembles the device
441 * name from \p minor and opens it.
443 static int drmOpenMinor(int minor, int create, int type)
447 const char *dev_name;
450 return drmOpenDevice(makedev(DRM_MAJOR, minor), minor, type);
453 case DRM_NODE_PRIMARY:
454 dev_name = DRM_DEV_NAME;
456 case DRM_NODE_CONTROL:
457 dev_name = DRM_CONTROL_DEV_NAME;
459 case DRM_NODE_RENDER:
460 dev_name = DRM_RENDER_DEV_NAME;
466 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
467 if ((fd = open(buf, O_RDWR, 0)) >= 0)
474 * Determine whether the DRM kernel driver has been loaded.
476 * \return 1 if the DRM driver is loaded, 0 otherwise.
479 * Determine the presence of the kernel driver by attempting to open the 0
480 * minor and get version information. For backward compatibility with older
481 * Linux implementations, /proc/dri is also checked.
483 int drmAvailable(void)
485 drmVersionPtr version;
489 if ((fd = drmOpenMinor(0, 1, DRM_NODE_PRIMARY)) < 0) {
491 /* Try proc for backward Linux compatibility */
492 if (!access("/proc/dri/0", R_OK))
498 if ((version = drmGetVersion(fd))) {
500 drmFreeVersion(version);
507 static int drmGetMinorBase(int type)
510 case DRM_NODE_PRIMARY:
512 case DRM_NODE_CONTROL:
514 case DRM_NODE_RENDER:
521 static int drmGetMinorType(int minor)
523 int type = minor >> 6;
529 case DRM_NODE_PRIMARY:
530 case DRM_NODE_CONTROL:
531 case DRM_NODE_RENDER:
538 static const char *drmGetMinorName(int type)
541 case DRM_NODE_PRIMARY:
542 return DRM_PRIMARY_MINOR_NAME;
543 case DRM_NODE_CONTROL:
544 return DRM_CONTROL_MINOR_NAME;
545 case DRM_NODE_RENDER:
546 return DRM_RENDER_MINOR_NAME;
553 * Open the device by bus ID.
555 * \param busid bus ID.
556 * \param type device node type.
558 * \return a file descriptor on success, or a negative value on error.
561 * This function attempts to open every possible minor (up to DRM_MAX_MINOR),
562 * comparing the device bus ID with the one supplied.
564 * \sa drmOpenMinor() and drmGetBusid().
566 static int drmOpenByBusid(const char *busid, int type)
568 int i, pci_domain_ok = 1;
572 int base = drmGetMinorBase(type);
577 drmMsg("drmOpenByBusid: Searching for BusID %s\n", busid);
578 for (i = base; i < base + DRM_MAX_MINOR; i++) {
579 fd = drmOpenMinor(i, 1, type);
580 drmMsg("drmOpenByBusid: drmOpenMinor returns %d\n", fd);
582 /* We need to try for 1.4 first for proper PCI domain support
583 * and if that fails, we know the kernel is busted
587 sv.drm_dd_major = -1; /* Don't care */
588 sv.drm_dd_minor = -1; /* Don't care */
589 if (drmSetInterfaceVersion(fd, &sv)) {
595 sv.drm_dd_major = -1; /* Don't care */
596 sv.drm_dd_minor = -1; /* Don't care */
597 drmMsg("drmOpenByBusid: Interface 1.4 failed, trying 1.1\n");
598 drmSetInterfaceVersion(fd, &sv);
600 buf = drmGetBusid(fd);
601 drmMsg("drmOpenByBusid: drmGetBusid reports %s\n", buf);
602 if (buf && drmMatchBusID(buf, busid, pci_domain_ok)) {
616 * Open the device by name.
618 * \param name driver name.
619 * \param type the device node type.
621 * \return a file descriptor on success, or a negative value on error.
624 * This function opens the first minor number that matches the driver name and
625 * isn't already in use. If it's in use it then it will already have a bus ID
628 * \sa drmOpenMinor(), drmGetVersion() and drmGetBusid().
630 static int drmOpenByName(const char *name, int type)
634 drmVersionPtr version;
636 int base = drmGetMinorBase(type);
642 * Open the first minor number that matches the driver name and isn't
643 * already in use. If it's in use it will have a busid assigned already.
645 for (i = base; i < base + DRM_MAX_MINOR; i++) {
646 if ((fd = drmOpenMinor(i, 1, type)) >= 0) {
647 if ((version = drmGetVersion(fd))) {
648 if (!strcmp(version->name, name)) {
649 drmFreeVersion(version);
650 id = drmGetBusid(fd);
651 drmMsg("drmGetBusid returned '%s'\n", id ? id : "NULL");
660 drmFreeVersion(version);
668 /* Backward-compatibility /proc support */
669 for (i = 0; i < 8; i++) {
670 char proc_name[64], buf[512];
671 char *driver, *pt, *devstring;
674 sprintf(proc_name, "/proc/dri/%d/name", i);
675 if ((fd = open(proc_name, 0, 0)) >= 0) {
676 retcode = read(fd, buf, sizeof(buf)-1);
679 buf[retcode-1] = '\0';
680 for (driver = pt = buf; *pt && *pt != ' '; ++pt)
682 if (*pt) { /* Device is next */
684 if (!strcmp(driver, name)) { /* Match */
685 for (devstring = ++pt; *pt && *pt != ' '; ++pt)
687 if (*pt) { /* Found busid */
688 return drmOpenByBusid(++pt, type);
689 } else { /* No busid */
690 return drmOpenDevice(strtol(devstring, NULL, 0),i, type);
704 * Open the DRM device.
706 * Looks up the specified name and bus ID, and opens the device found. The
707 * entry in /dev/dri is created if necessary and if called by root.
709 * \param name driver name. Not referenced if bus ID is supplied.
710 * \param busid bus ID. Zero if not known.
712 * \return a file descriptor on success, or a negative value on error.
715 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
718 int drmOpen(const char *name, const char *busid)
720 return drmOpenWithType(name, busid, DRM_NODE_PRIMARY);
724 * Open the DRM device with specified type.
726 * Looks up the specified name and bus ID, and opens the device found. The
727 * entry in /dev/dri is created if necessary and if called by root.
729 * \param name driver name. Not referenced if bus ID is supplied.
730 * \param busid bus ID. Zero if not known.
731 * \param type the device node type to open, PRIMARY, CONTROL or RENDER
733 * \return a file descriptor on success, or a negative value on error.
736 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
739 int drmOpenWithType(const char *name, const char *busid, int type)
741 if (!drmAvailable() && name != NULL && drm_server_info &&
742 drm_server_info->load_module) {
743 /* try to load the kernel module */
744 if (!drm_server_info->load_module(name)) {
745 drmMsg("[drm] failed to load kernel module \"%s\"\n", name);
751 int fd = drmOpenByBusid(busid, type);
757 return drmOpenByName(name, type);
762 int drmOpenControl(int minor)
764 return drmOpenMinor(minor, 0, DRM_NODE_CONTROL);
767 int drmOpenRender(int minor)
769 return drmOpenMinor(minor, 0, DRM_NODE_RENDER);
773 * Free the version information returned by drmGetVersion().
775 * \param v pointer to the version information.
778 * It frees the memory pointed by \p %v as well as all the non-null strings
781 void drmFreeVersion(drmVersionPtr v)
793 * Free the non-public version information returned by the kernel.
795 * \param v pointer to the version information.
798 * Used by drmGetVersion() to free the memory pointed by \p %v as well as all
799 * the non-null strings pointers in it.
801 static void drmFreeKernelVersion(drm_version_t *v)
813 * Copy version information.
815 * \param d destination pointer.
816 * \param s source pointer.
819 * Used by drmGetVersion() to translate the information returned by the ioctl
820 * interface in a private structure into the public structure counterpart.
822 static void drmCopyVersion(drmVersionPtr d, const drm_version_t *s)
824 d->version_major = s->version_major;
825 d->version_minor = s->version_minor;
826 d->version_patchlevel = s->version_patchlevel;
827 d->name_len = s->name_len;
828 d->name = strdup(s->name);
829 d->date_len = s->date_len;
830 d->date = strdup(s->date);
831 d->desc_len = s->desc_len;
832 d->desc = strdup(s->desc);
837 * Query the driver version information.
839 * \param fd file descriptor.
841 * \return pointer to a drmVersion structure which should be freed with
844 * \note Similar information is available via /proc/dri.
847 * It gets the version information via successive DRM_IOCTL_VERSION ioctls,
848 * first with zeros to get the string lengths, and then the actually strings.
849 * It also null-terminates them since they might not be already.
851 drmVersionPtr drmGetVersion(int fd)
853 drmVersionPtr retval;
854 drm_version_t *version = drmMalloc(sizeof(*version));
858 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
859 drmFreeKernelVersion(version);
863 if (version->name_len)
864 version->name = drmMalloc(version->name_len + 1);
865 if (version->date_len)
866 version->date = drmMalloc(version->date_len + 1);
867 if (version->desc_len)
868 version->desc = drmMalloc(version->desc_len + 1);
870 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
871 drmMsg("DRM_IOCTL_VERSION: %s\n", strerror(errno));
872 drmFreeKernelVersion(version);
876 /* The results might not be null-terminated strings, so terminate them. */
877 if (version->name_len) version->name[version->name_len] = '\0';
878 if (version->date_len) version->date[version->date_len] = '\0';
879 if (version->desc_len) version->desc[version->desc_len] = '\0';
881 retval = drmMalloc(sizeof(*retval));
882 drmCopyVersion(retval, version);
883 drmFreeKernelVersion(version);
889 * Get version information for the DRM user space library.
891 * This version number is driver independent.
893 * \param fd file descriptor.
895 * \return version information.
898 * This function allocates and fills a drm_version structure with a hard coded
901 drmVersionPtr drmGetLibVersion(int fd)
903 drm_version_t *version = drmMalloc(sizeof(*version));
906 * NOTE THIS MUST NOT GO ABOVE VERSION 1.X due to drivers needing it
907 * revision 1.0.x = original DRM interface with no drmGetLibVersion
908 * entry point and many drm<Device> extensions
909 * revision 1.1.x = added drmCommand entry points for device extensions
910 * added drmGetLibVersion to identify libdrm.a version
911 * revision 1.2.x = added drmSetInterfaceVersion
912 * modified drmOpen to handle both busid and name
913 * revision 1.3.x = added server + memory manager
915 version->version_major = 1;
916 version->version_minor = 3;
917 version->version_patchlevel = 0;
919 return (drmVersionPtr)version;
922 int drmGetCap(int fd, uint64_t capability, uint64_t *value)
924 struct drm_get_cap cap;
928 cap.capability = capability;
930 ret = drmIoctl(fd, DRM_IOCTL_GET_CAP, &cap);
938 int drmSetClientCap(int fd, uint64_t capability, uint64_t value)
940 struct drm_set_client_cap cap;
943 cap.capability = capability;
946 return drmIoctl(fd, DRM_IOCTL_SET_CLIENT_CAP, &cap);
950 * Free the bus ID information.
952 * \param busid bus ID information string as given by drmGetBusid().
955 * This function is just frees the memory pointed by \p busid.
957 void drmFreeBusid(const char *busid)
959 drmFree((void *)busid);
964 * Get the bus ID of the device.
966 * \param fd file descriptor.
968 * \return bus ID string.
971 * This function gets the bus ID via successive DRM_IOCTL_GET_UNIQUE ioctls to
972 * get the string length and data, passing the arguments in a drm_unique
975 char *drmGetBusid(int fd)
981 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
983 u.unique = drmMalloc(u.unique_len + 1);
984 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
986 u.unique[u.unique_len] = '\0';
993 * Set the bus ID of the device.
995 * \param fd file descriptor.
996 * \param busid bus ID string.
998 * \return zero on success, negative on failure.
1001 * This function is a wrapper around the DRM_IOCTL_SET_UNIQUE ioctl, passing
1002 * the arguments in a drm_unique structure.
1004 int drmSetBusid(int fd, const char *busid)
1009 u.unique = (char *)busid;
1010 u.unique_len = strlen(busid);
1012 if (drmIoctl(fd, DRM_IOCTL_SET_UNIQUE, &u)) {
1018 int drmGetMagic(int fd, drm_magic_t * magic)
1025 if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
1027 *magic = auth.magic;
1031 int drmAuthMagic(int fd, drm_magic_t magic)
1037 if (drmIoctl(fd, DRM_IOCTL_AUTH_MAGIC, &auth))
1043 * Specifies a range of memory that is available for mapping by a
1046 * \param fd file descriptor.
1047 * \param offset usually the physical address. The actual meaning depends of
1048 * the \p type parameter. See below.
1049 * \param size of the memory in bytes.
1050 * \param type type of the memory to be mapped.
1051 * \param flags combination of several flags to modify the function actions.
1052 * \param handle will be set to a value that may be used as the offset
1053 * parameter for mmap().
1055 * \return zero on success or a negative value on error.
1057 * \par Mapping the frame buffer
1058 * For the frame buffer
1059 * - \p offset will be the physical address of the start of the frame buffer,
1060 * - \p size will be the size of the frame buffer in bytes, and
1061 * - \p type will be DRM_FRAME_BUFFER.
1064 * The area mapped will be uncached. If MTRR support is available in the
1065 * kernel, the frame buffer area will be set to write combining.
1067 * \par Mapping the MMIO register area
1068 * For the MMIO register area,
1069 * - \p offset will be the physical address of the start of the register area,
1070 * - \p size will be the size of the register area bytes, and
1071 * - \p type will be DRM_REGISTERS.
1073 * The area mapped will be uncached.
1075 * \par Mapping the SAREA
1077 * - \p offset will be ignored and should be set to zero,
1078 * - \p size will be the desired size of the SAREA in bytes,
1079 * - \p type will be DRM_SHM.
1082 * A shared memory area of the requested size will be created and locked in
1083 * kernel memory. This area may be mapped into client-space by using the handle
1086 * \note May only be called by root.
1089 * This function is a wrapper around the DRM_IOCTL_ADD_MAP ioctl, passing
1090 * the arguments in a drm_map structure.
1092 int drmAddMap(int fd, drm_handle_t offset, drmSize size, drmMapType type,
1093 drmMapFlags flags, drm_handle_t *handle)
1098 map.offset = offset;
1102 if (drmIoctl(fd, DRM_IOCTL_ADD_MAP, &map))
1105 *handle = (drm_handle_t)(uintptr_t)map.handle;
1109 int drmRmMap(int fd, drm_handle_t handle)
1114 map.handle = (void *)(uintptr_t)handle;
1116 if(drmIoctl(fd, DRM_IOCTL_RM_MAP, &map))
1122 * Make buffers available for DMA transfers.
1124 * \param fd file descriptor.
1125 * \param count number of buffers.
1126 * \param size size of each buffer.
1127 * \param flags buffer allocation flags.
1128 * \param agp_offset offset in the AGP aperture
1130 * \return number of buffers allocated, negative on error.
1133 * This function is a wrapper around DRM_IOCTL_ADD_BUFS ioctl.
1137 int drmAddBufs(int fd, int count, int size, drmBufDescFlags flags,
1140 drm_buf_desc_t request;
1143 request.count = count;
1144 request.size = size;
1145 request.flags = flags;
1146 request.agp_start = agp_offset;
1148 if (drmIoctl(fd, DRM_IOCTL_ADD_BUFS, &request))
1150 return request.count;
1153 int drmMarkBufs(int fd, double low, double high)
1155 drm_buf_info_t info;
1160 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1166 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1169 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1170 int retval = -errno;
1175 for (i = 0; i < info.count; i++) {
1176 info.list[i].low_mark = low * info.list[i].count;
1177 info.list[i].high_mark = high * info.list[i].count;
1178 if (drmIoctl(fd, DRM_IOCTL_MARK_BUFS, &info.list[i])) {
1179 int retval = -errno;
1192 * \param fd file descriptor.
1193 * \param count number of buffers to free.
1194 * \param list list of buffers to be freed.
1196 * \return zero on success, or a negative value on failure.
1198 * \note This function is primarily used for debugging.
1201 * This function is a wrapper around the DRM_IOCTL_FREE_BUFS ioctl, passing
1202 * the arguments in a drm_buf_free structure.
1204 int drmFreeBufs(int fd, int count, int *list)
1206 drm_buf_free_t request;
1209 request.count = count;
1210 request.list = list;
1211 if (drmIoctl(fd, DRM_IOCTL_FREE_BUFS, &request))
1220 * \param fd file descriptor.
1223 * This function closes the file descriptor.
1225 int drmClose(int fd)
1227 unsigned long key = drmGetKeyFromFd(fd);
1228 drmHashEntry *entry = drmGetEntry(fd);
1230 drmHashDestroy(entry->tagTable);
1233 entry->tagTable = NULL;
1235 drmHashDelete(drmHashTable, key);
1243 * Map a region of memory.
1245 * \param fd file descriptor.
1246 * \param handle handle returned by drmAddMap().
1247 * \param size size in bytes. Must match the size used by drmAddMap().
1248 * \param address will contain the user-space virtual address where the mapping
1251 * \return zero on success, or a negative value on failure.
1254 * This function is a wrapper for mmap().
1256 int drmMap(int fd, drm_handle_t handle, drmSize size, drmAddressPtr address)
1258 static unsigned long pagesize_mask = 0;
1264 pagesize_mask = getpagesize() - 1;
1266 size = (size + pagesize_mask) & ~pagesize_mask;
1268 *address = drm_mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1269 if (*address == MAP_FAILED)
1276 * Unmap mappings obtained with drmMap().
1278 * \param address address as given by drmMap().
1279 * \param size size in bytes. Must match the size used by drmMap().
1281 * \return zero on success, or a negative value on failure.
1284 * This function is a wrapper for munmap().
1286 int drmUnmap(drmAddress address, drmSize size)
1288 return drm_munmap(address, size);
1291 drmBufInfoPtr drmGetBufInfo(int fd)
1293 drm_buf_info_t info;
1294 drmBufInfoPtr retval;
1299 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1303 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1306 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1311 retval = drmMalloc(sizeof(*retval));
1312 retval->count = info.count;
1313 retval->list = drmMalloc(info.count * sizeof(*retval->list));
1314 for (i = 0; i < info.count; i++) {
1315 retval->list[i].count = info.list[i].count;
1316 retval->list[i].size = info.list[i].size;
1317 retval->list[i].low_mark = info.list[i].low_mark;
1318 retval->list[i].high_mark = info.list[i].high_mark;
1327 * Map all DMA buffers into client-virtual space.
1329 * \param fd file descriptor.
1331 * \return a pointer to a ::drmBufMap structure.
1333 * \note The client may not use these buffers until obtaining buffer indices
1337 * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1338 * information about the buffers in a drm_buf_map structure into the
1339 * client-visible data structures.
1341 drmBufMapPtr drmMapBufs(int fd)
1344 drmBufMapPtr retval;
1348 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1354 if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1357 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1362 retval = drmMalloc(sizeof(*retval));
1363 retval->count = bufs.count;
1364 retval->list = drmMalloc(bufs.count * sizeof(*retval->list));
1365 for (i = 0; i < bufs.count; i++) {
1366 retval->list[i].idx = bufs.list[i].idx;
1367 retval->list[i].total = bufs.list[i].total;
1368 retval->list[i].used = 0;
1369 retval->list[i].address = bufs.list[i].address;
1379 * Unmap buffers allocated with drmMapBufs().
1381 * \return zero on success, or negative value on failure.
1384 * Calls munmap() for every buffer stored in \p bufs and frees the
1385 * memory allocated by drmMapBufs().
1387 int drmUnmapBufs(drmBufMapPtr bufs)
1391 for (i = 0; i < bufs->count; i++) {
1392 drm_munmap(bufs->list[i].address, bufs->list[i].total);
1395 drmFree(bufs->list);
1402 #define DRM_DMA_RETRY 16
1405 * Reserve DMA buffers.
1407 * \param fd file descriptor.
1410 * \return zero on success, or a negative value on failure.
1413 * Assemble the arguments into a drm_dma structure and keeps issuing the
1414 * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1416 int drmDMA(int fd, drmDMAReqPtr request)
1421 dma.context = request->context;
1422 dma.send_count = request->send_count;
1423 dma.send_indices = request->send_list;
1424 dma.send_sizes = request->send_sizes;
1425 dma.flags = request->flags;
1426 dma.request_count = request->request_count;
1427 dma.request_size = request->request_size;
1428 dma.request_indices = request->request_list;
1429 dma.request_sizes = request->request_sizes;
1430 dma.granted_count = 0;
1433 ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1434 } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1437 request->granted_count = dma.granted_count;
1446 * Obtain heavyweight hardware lock.
1448 * \param fd file descriptor.
1449 * \param context context.
1450 * \param flags flags that determine the sate of the hardware when the function
1453 * \return always zero.
1456 * This function translates the arguments into a drm_lock structure and issue
1457 * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1459 int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
1464 lock.context = context;
1466 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
1467 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
1468 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
1469 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
1470 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
1471 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
1473 while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
1479 * Release the hardware lock.
1481 * \param fd file descriptor.
1482 * \param context context.
1484 * \return zero on success, or a negative value on failure.
1487 * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
1488 * argument in a drm_lock structure.
1490 int drmUnlock(int fd, drm_context_t context)
1495 lock.context = context;
1496 return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
1499 drm_context_t *drmGetReservedContextList(int fd, int *count)
1503 drm_context_t * retval;
1507 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1513 if (!(list = drmMalloc(res.count * sizeof(*list))))
1515 if (!(retval = drmMalloc(res.count * sizeof(*retval)))) {
1520 res.contexts = list;
1521 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1524 for (i = 0; i < res.count; i++)
1525 retval[i] = list[i].handle;
1532 void drmFreeReservedContextList(drm_context_t *pt)
1540 * Used by the X server during GLXContext initialization. This causes
1541 * per-context kernel-level resources to be allocated.
1543 * \param fd file descriptor.
1544 * \param handle is set on success. To be used by the client when requesting DMA
1545 * dispatch with drmDMA().
1547 * \return zero on success, or a negative value on failure.
1549 * \note May only be called by root.
1552 * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
1553 * argument in a drm_ctx structure.
1555 int drmCreateContext(int fd, drm_context_t *handle)
1560 if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
1562 *handle = ctx.handle;
1566 int drmSwitchToContext(int fd, drm_context_t context)
1571 ctx.handle = context;
1572 if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
1577 int drmSetContextFlags(int fd, drm_context_t context, drm_context_tFlags flags)
1582 * Context preserving means that no context switches are done between DMA
1583 * buffers from one context and the next. This is suitable for use in the
1584 * X server (which promises to maintain hardware context), or in the
1585 * client-side library when buffers are swapped on behalf of two threads.
1588 ctx.handle = context;
1589 if (flags & DRM_CONTEXT_PRESERVED)
1590 ctx.flags |= _DRM_CONTEXT_PRESERVED;
1591 if (flags & DRM_CONTEXT_2DONLY)
1592 ctx.flags |= _DRM_CONTEXT_2DONLY;
1593 if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
1598 int drmGetContextFlags(int fd, drm_context_t context,
1599 drm_context_tFlagsPtr flags)
1604 ctx.handle = context;
1605 if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
1608 if (ctx.flags & _DRM_CONTEXT_PRESERVED)
1609 *flags |= DRM_CONTEXT_PRESERVED;
1610 if (ctx.flags & _DRM_CONTEXT_2DONLY)
1611 *flags |= DRM_CONTEXT_2DONLY;
1618 * Free any kernel-level resources allocated with drmCreateContext() associated
1621 * \param fd file descriptor.
1622 * \param handle handle given by drmCreateContext().
1624 * \return zero on success, or a negative value on failure.
1626 * \note May only be called by root.
1629 * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
1630 * argument in a drm_ctx structure.
1632 int drmDestroyContext(int fd, drm_context_t handle)
1637 ctx.handle = handle;
1638 if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
1643 int drmCreateDrawable(int fd, drm_drawable_t *handle)
1648 if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
1650 *handle = draw.handle;
1654 int drmDestroyDrawable(int fd, drm_drawable_t handle)
1659 draw.handle = handle;
1660 if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
1665 int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
1666 drm_drawable_info_type_t type, unsigned int num,
1669 drm_update_draw_t update;
1672 update.handle = handle;
1675 update.data = (unsigned long long)(unsigned long)data;
1677 if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
1684 * Acquire the AGP device.
1686 * Must be called before any of the other AGP related calls.
1688 * \param fd file descriptor.
1690 * \return zero on success, or a negative value on failure.
1693 * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
1695 int drmAgpAcquire(int fd)
1697 if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
1704 * Release the AGP device.
1706 * \param fd file descriptor.
1708 * \return zero on success, or a negative value on failure.
1711 * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
1713 int drmAgpRelease(int fd)
1715 if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
1724 * \param fd file descriptor.
1725 * \param mode AGP mode.
1727 * \return zero on success, or a negative value on failure.
1730 * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
1731 * argument in a drm_agp_mode structure.
1733 int drmAgpEnable(int fd, unsigned long mode)
1739 if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
1746 * Allocate a chunk of AGP memory.
1748 * \param fd file descriptor.
1749 * \param size requested memory size in bytes. Will be rounded to page boundary.
1750 * \param type type of memory to allocate.
1751 * \param address if not zero, will be set to the physical address of the
1753 * \param handle on success will be set to a handle of the allocated memory.
1755 * \return zero on success, or a negative value on failure.
1758 * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
1759 * arguments in a drm_agp_buffer structure.
1761 int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
1762 unsigned long *address, drm_handle_t *handle)
1767 *handle = DRM_AGP_NO_HANDLE;
1770 if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
1773 *address = b.physical;
1780 * Free a chunk of AGP memory.
1782 * \param fd file descriptor.
1783 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1785 * \return zero on success, or a negative value on failure.
1788 * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
1789 * argument in a drm_agp_buffer structure.
1791 int drmAgpFree(int fd, drm_handle_t handle)
1797 if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
1804 * Bind a chunk of AGP memory.
1806 * \param fd file descriptor.
1807 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1808 * \param offset offset in bytes. It will round to page boundary.
1810 * \return zero on success, or a negative value on failure.
1813 * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
1814 * argument in a drm_agp_binding structure.
1816 int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
1818 drm_agp_binding_t b;
1823 if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
1830 * Unbind a chunk of AGP memory.
1832 * \param fd file descriptor.
1833 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1835 * \return zero on success, or a negative value on failure.
1838 * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
1839 * the argument in a drm_agp_binding structure.
1841 int drmAgpUnbind(int fd, drm_handle_t handle)
1843 drm_agp_binding_t b;
1847 if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
1854 * Get AGP driver major version number.
1856 * \param fd file descriptor.
1858 * \return major version number on success, or a negative value on failure..
1861 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1862 * necessary information in a drm_agp_info structure.
1864 int drmAgpVersionMajor(int fd)
1870 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1872 return i.agp_version_major;
1877 * Get AGP driver minor version number.
1879 * \param fd file descriptor.
1881 * \return minor version number on success, or a negative value on failure.
1884 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1885 * necessary information in a drm_agp_info structure.
1887 int drmAgpVersionMinor(int fd)
1893 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1895 return i.agp_version_minor;
1902 * \param fd file descriptor.
1904 * \return mode on success, or zero on failure.
1907 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1908 * necessary information in a drm_agp_info structure.
1910 unsigned long drmAgpGetMode(int fd)
1916 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1923 * Get AGP aperture base.
1925 * \param fd file descriptor.
1927 * \return aperture base on success, zero on failure.
1930 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1931 * necessary information in a drm_agp_info structure.
1933 unsigned long drmAgpBase(int fd)
1939 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1941 return i.aperture_base;
1946 * Get AGP aperture size.
1948 * \param fd file descriptor.
1950 * \return aperture size on success, zero on failure.
1953 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1954 * necessary information in a drm_agp_info structure.
1956 unsigned long drmAgpSize(int fd)
1962 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1964 return i.aperture_size;
1969 * Get used AGP memory.
1971 * \param fd file descriptor.
1973 * \return memory used on success, or zero on failure.
1976 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1977 * necessary information in a drm_agp_info structure.
1979 unsigned long drmAgpMemoryUsed(int fd)
1985 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1987 return i.memory_used;
1992 * Get available AGP memory.
1994 * \param fd file descriptor.
1996 * \return memory available on success, or zero on failure.
1999 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2000 * necessary information in a drm_agp_info structure.
2002 unsigned long drmAgpMemoryAvail(int fd)
2008 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2010 return i.memory_allowed;
2015 * Get hardware vendor ID.
2017 * \param fd file descriptor.
2019 * \return vendor ID on success, or zero on failure.
2022 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2023 * necessary information in a drm_agp_info structure.
2025 unsigned int drmAgpVendorId(int fd)
2031 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2038 * Get hardware device ID.
2040 * \param fd file descriptor.
2042 * \return zero on success, or zero on failure.
2045 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2046 * necessary information in a drm_agp_info structure.
2048 unsigned int drmAgpDeviceId(int fd)
2054 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2059 int drmScatterGatherAlloc(int fd, unsigned long size, drm_handle_t *handle)
2061 drm_scatter_gather_t sg;
2067 if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
2069 *handle = sg.handle;
2073 int drmScatterGatherFree(int fd, drm_handle_t handle)
2075 drm_scatter_gather_t sg;
2079 if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
2087 * \param fd file descriptor.
2088 * \param vbl pointer to a drmVBlank structure.
2090 * \return zero on success, or a negative value on failure.
2093 * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
2095 int drmWaitVBlank(int fd, drmVBlankPtr vbl)
2097 struct timespec timeout, cur;
2100 ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2102 fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
2108 ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
2109 vbl->request.type &= ~DRM_VBLANK_RELATIVE;
2110 if (ret && errno == EINTR) {
2111 clock_gettime(CLOCK_MONOTONIC, &cur);
2112 /* Timeout after 1s */
2113 if (cur.tv_sec > timeout.tv_sec + 1 ||
2114 (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
2121 } while (ret && errno == EINTR);
2127 int drmError(int err, const char *label)
2130 case DRM_ERR_NO_DEVICE:
2131 fprintf(stderr, "%s: no device\n", label);
2133 case DRM_ERR_NO_ACCESS:
2134 fprintf(stderr, "%s: no access\n", label);
2136 case DRM_ERR_NOT_ROOT:
2137 fprintf(stderr, "%s: not root\n", label);
2139 case DRM_ERR_INVALID:
2140 fprintf(stderr, "%s: invalid args\n", label);
2145 fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2153 * Install IRQ handler.
2155 * \param fd file descriptor.
2156 * \param irq IRQ number.
2158 * \return zero on success, or a negative value on failure.
2161 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2162 * argument in a drm_control structure.
2164 int drmCtlInstHandler(int fd, int irq)
2169 ctl.func = DRM_INST_HANDLER;
2171 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2178 * Uninstall IRQ handler.
2180 * \param fd file descriptor.
2182 * \return zero on success, or a negative value on failure.
2185 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2186 * argument in a drm_control structure.
2188 int drmCtlUninstHandler(int fd)
2193 ctl.func = DRM_UNINST_HANDLER;
2195 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2200 int drmFinish(int fd, int context, drmLockFlags flags)
2205 lock.context = context;
2206 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
2207 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
2208 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
2209 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
2210 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2211 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2212 if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2218 * Get IRQ from bus ID.
2220 * \param fd file descriptor.
2221 * \param busnum bus number.
2222 * \param devnum device number.
2223 * \param funcnum function number.
2225 * \return IRQ number on success, or a negative value on failure.
2228 * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2229 * arguments in a drm_irq_busid structure.
2231 int drmGetInterruptFromBusID(int fd, int busnum, int devnum, int funcnum)
2238 p.funcnum = funcnum;
2239 if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2244 int drmAddContextTag(int fd, drm_context_t context, void *tag)
2246 drmHashEntry *entry = drmGetEntry(fd);
2248 if (drmHashInsert(entry->tagTable, context, tag)) {
2249 drmHashDelete(entry->tagTable, context);
2250 drmHashInsert(entry->tagTable, context, tag);
2255 int drmDelContextTag(int fd, drm_context_t context)
2257 drmHashEntry *entry = drmGetEntry(fd);
2259 return drmHashDelete(entry->tagTable, context);
2262 void *drmGetContextTag(int fd, drm_context_t context)
2264 drmHashEntry *entry = drmGetEntry(fd);
2267 if (drmHashLookup(entry->tagTable, context, &value))
2273 int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2274 drm_handle_t handle)
2276 drm_ctx_priv_map_t map;
2279 map.ctx_id = ctx_id;
2280 map.handle = (void *)(uintptr_t)handle;
2282 if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2287 int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2288 drm_handle_t *handle)
2290 drm_ctx_priv_map_t map;
2293 map.ctx_id = ctx_id;
2295 if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2298 *handle = (drm_handle_t)(uintptr_t)map.handle;
2303 int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2304 drmMapType *type, drmMapFlags *flags, drm_handle_t *handle,
2311 if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2313 *offset = map.offset;
2317 *handle = (unsigned long)map.handle;
2322 int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2323 unsigned long *magic, unsigned long *iocs)
2325 drm_client_t client;
2329 if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2331 *auth = client.auth;
2334 *magic = client.magic;
2335 *iocs = client.iocs;
2339 int drmGetStats(int fd, drmStatsT *stats)
2345 if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2349 memset(stats, 0, sizeof(*stats));
2350 if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2354 stats->data[i].long_format = "%-20.20s"; \
2355 stats->data[i].rate_format = "%8.8s"; \
2356 stats->data[i].isvalue = 1; \
2357 stats->data[i].verbose = 0
2360 stats->data[i].long_format = "%-20.20s"; \
2361 stats->data[i].rate_format = "%5.5s"; \
2362 stats->data[i].isvalue = 0; \
2363 stats->data[i].mult_names = "kgm"; \
2364 stats->data[i].mult = 1000; \
2365 stats->data[i].verbose = 0
2368 stats->data[i].long_format = "%-20.20s"; \
2369 stats->data[i].rate_format = "%5.5s"; \
2370 stats->data[i].isvalue = 0; \
2371 stats->data[i].mult_names = "KGM"; \
2372 stats->data[i].mult = 1024; \
2373 stats->data[i].verbose = 0
2376 stats->count = s.count;
2377 for (i = 0; i < s.count; i++) {
2378 stats->data[i].value = s.data[i].value;
2379 switch (s.data[i].type) {
2380 case _DRM_STAT_LOCK:
2381 stats->data[i].long_name = "Lock";
2382 stats->data[i].rate_name = "Lock";
2385 case _DRM_STAT_OPENS:
2386 stats->data[i].long_name = "Opens";
2387 stats->data[i].rate_name = "O";
2389 stats->data[i].verbose = 1;
2391 case _DRM_STAT_CLOSES:
2392 stats->data[i].long_name = "Closes";
2393 stats->data[i].rate_name = "Lock";
2395 stats->data[i].verbose = 1;
2397 case _DRM_STAT_IOCTLS:
2398 stats->data[i].long_name = "Ioctls";
2399 stats->data[i].rate_name = "Ioc/s";
2402 case _DRM_STAT_LOCKS:
2403 stats->data[i].long_name = "Locks";
2404 stats->data[i].rate_name = "Lck/s";
2407 case _DRM_STAT_UNLOCKS:
2408 stats->data[i].long_name = "Unlocks";
2409 stats->data[i].rate_name = "Unl/s";
2413 stats->data[i].long_name = "IRQs";
2414 stats->data[i].rate_name = "IRQ/s";
2417 case _DRM_STAT_PRIMARY:
2418 stats->data[i].long_name = "Primary Bytes";
2419 stats->data[i].rate_name = "PB/s";
2422 case _DRM_STAT_SECONDARY:
2423 stats->data[i].long_name = "Secondary Bytes";
2424 stats->data[i].rate_name = "SB/s";
2428 stats->data[i].long_name = "DMA";
2429 stats->data[i].rate_name = "DMA/s";
2432 case _DRM_STAT_SPECIAL:
2433 stats->data[i].long_name = "Special DMA";
2434 stats->data[i].rate_name = "dma/s";
2437 case _DRM_STAT_MISSED:
2438 stats->data[i].long_name = "Miss";
2439 stats->data[i].rate_name = "Ms/s";
2442 case _DRM_STAT_VALUE:
2443 stats->data[i].long_name = "Value";
2444 stats->data[i].rate_name = "Value";
2447 case _DRM_STAT_BYTE:
2448 stats->data[i].long_name = "Bytes";
2449 stats->data[i].rate_name = "B/s";
2452 case _DRM_STAT_COUNT:
2454 stats->data[i].long_name = "Count";
2455 stats->data[i].rate_name = "Cnt/s";
2464 * Issue a set-version ioctl.
2466 * \param fd file descriptor.
2467 * \param drmCommandIndex command index
2468 * \param data source pointer of the data to be read and written.
2469 * \param size size of the data to be read and written.
2471 * \return zero on success, or a negative value on failure.
2474 * It issues a read-write ioctl given by
2475 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2477 int drmSetInterfaceVersion(int fd, drmSetVersion *version)
2480 drm_set_version_t sv;
2483 sv.drm_di_major = version->drm_di_major;
2484 sv.drm_di_minor = version->drm_di_minor;
2485 sv.drm_dd_major = version->drm_dd_major;
2486 sv.drm_dd_minor = version->drm_dd_minor;
2488 if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
2492 version->drm_di_major = sv.drm_di_major;
2493 version->drm_di_minor = sv.drm_di_minor;
2494 version->drm_dd_major = sv.drm_dd_major;
2495 version->drm_dd_minor = sv.drm_dd_minor;
2501 * Send a device-specific command.
2503 * \param fd file descriptor.
2504 * \param drmCommandIndex command index
2506 * \return zero on success, or a negative value on failure.
2509 * It issues a ioctl given by
2510 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2512 int drmCommandNone(int fd, unsigned long drmCommandIndex)
2514 unsigned long request;
2516 request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
2518 if (drmIoctl(fd, request, NULL)) {
2526 * Send a device-specific read command.
2528 * \param fd file descriptor.
2529 * \param drmCommandIndex command index
2530 * \param data destination pointer of the data to be read.
2531 * \param size size of the data to be read.
2533 * \return zero on success, or a negative value on failure.
2536 * It issues a read ioctl given by
2537 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2539 int drmCommandRead(int fd, unsigned long drmCommandIndex, void *data,
2542 unsigned long request;
2544 request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
2545 DRM_COMMAND_BASE + drmCommandIndex, size);
2547 if (drmIoctl(fd, request, data)) {
2555 * Send a device-specific write command.
2557 * \param fd file descriptor.
2558 * \param drmCommandIndex command index
2559 * \param data source pointer of the data to be written.
2560 * \param size size of the data to be written.
2562 * \return zero on success, or a negative value on failure.
2565 * It issues a write ioctl given by
2566 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2568 int drmCommandWrite(int fd, unsigned long drmCommandIndex, void *data,
2571 unsigned long request;
2573 request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
2574 DRM_COMMAND_BASE + drmCommandIndex, size);
2576 if (drmIoctl(fd, request, data)) {
2584 * Send a device-specific read-write command.
2586 * \param fd file descriptor.
2587 * \param drmCommandIndex command index
2588 * \param data source pointer of the data to be read and written.
2589 * \param size size of the data to be read and written.
2591 * \return zero on success, or a negative value on failure.
2594 * It issues a read-write ioctl given by
2595 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2597 int drmCommandWriteRead(int fd, unsigned long drmCommandIndex, void *data,
2600 unsigned long request;
2602 request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
2603 DRM_COMMAND_BASE + drmCommandIndex, size);
2605 if (drmIoctl(fd, request, data))
2610 #define DRM_MAX_FDS 16
2616 } connection[DRM_MAX_FDS];
2618 static int nr_fds = 0;
2620 int drmOpenOnce(void *unused,
2624 return drmOpenOnceWithType(BusID, newlyopened, DRM_NODE_PRIMARY);
2627 int drmOpenOnceWithType(const char *BusID, int *newlyopened, int type)
2632 for (i = 0; i < nr_fds; i++)
2633 if ((strcmp(BusID, connection[i].BusID) == 0) &&
2634 (connection[i].type == type)) {
2635 connection[i].refcount++;
2637 return connection[i].fd;
2640 fd = drmOpenWithType(NULL, BusID, type);
2641 if (fd < 0 || nr_fds == DRM_MAX_FDS)
2644 connection[nr_fds].BusID = strdup(BusID);
2645 connection[nr_fds].fd = fd;
2646 connection[nr_fds].refcount = 1;
2647 connection[nr_fds].type = type;
2651 fprintf(stderr, "saved connection %d for %s %d\n",
2652 nr_fds, connection[nr_fds].BusID,
2653 strcmp(BusID, connection[nr_fds].BusID));
2660 void drmCloseOnce(int fd)
2664 for (i = 0; i < nr_fds; i++) {
2665 if (fd == connection[i].fd) {
2666 if (--connection[i].refcount == 0) {
2667 drmClose(connection[i].fd);
2668 free(connection[i].BusID);
2671 connection[i] = connection[nr_fds];
2679 int drmSetMaster(int fd)
2681 return drmIoctl(fd, DRM_IOCTL_SET_MASTER, NULL);
2684 int drmDropMaster(int fd)
2686 return drmIoctl(fd, DRM_IOCTL_DROP_MASTER, NULL);
2689 char *drmGetDeviceNameFromFd(int fd)
2696 /* The whole drmOpen thing is a fiasco and we need to find a way
2697 * back to just using open(2). For now, however, lets just make
2698 * things worse with even more ad hoc directory walking code to
2699 * discover the device file name. */
2704 for (i = 0; i < DRM_MAX_MINOR; i++) {
2705 snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
2706 if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
2709 if (i == DRM_MAX_MINOR)
2712 return strdup(name);
2715 int drmGetNodeTypeFromFd(int fd)
2720 if (fstat(fd, &sbuf))
2723 maj = major(sbuf.st_rdev);
2724 min = minor(sbuf.st_rdev);
2726 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode)) {
2731 type = drmGetMinorType(min);
2737 int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags, int *prime_fd)
2739 struct drm_prime_handle args;
2744 args.handle = handle;
2746 ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
2750 *prime_fd = args.fd;
2754 int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
2756 struct drm_prime_handle args;
2761 ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
2765 *handle = args.handle;
2769 static char *drmGetMinorNameForFD(int fd, int type)
2773 struct dirent *pent, *ent;
2775 const char *name = drmGetMinorName(type);
2777 char dev_name[64], buf[64];
2786 if (fstat(fd, &sbuf))
2789 maj = major(sbuf.st_rdev);
2790 min = minor(sbuf.st_rdev);
2792 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
2795 snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
2797 sysdir = opendir(buf);
2801 name_max = fpathconf(dirfd(sysdir), _PC_NAME_MAX);
2805 pent = malloc(offsetof(struct dirent, d_name) + name_max + 1);
2809 while (readdir_r(sysdir, pent, &ent) == 0 && ent != NULL) {
2810 if (strncmp(ent->d_name, name, len) == 0) {
2811 snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
2817 return strdup(dev_name);
2829 char *drmGetPrimaryDeviceNameFromFd(int fd)
2831 return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
2834 char *drmGetRenderDeviceNameFromFd(int fd)
2836 return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
2839 static int drmParseSubsystemType(int maj, int min)
2842 char path[PATH_MAX + 1];
2843 char link[PATH_MAX + 1] = "";
2846 snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/subsystem",
2849 if (readlink(path, link, PATH_MAX) < 0)
2852 name = strrchr(link, '/');
2856 if (strncmp(name, "/pci", 4) == 0)
2861 #warning "Missing implementation of drmParseSubsystemType"
2866 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
2869 char path[PATH_MAX + 1];
2872 int domain, bus, dev, func;
2875 snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/uevent", maj, min);
2876 fd = open(path, O_RDONLY);
2880 ret = read(fd, data, sizeof(data));
2885 #define TAG "PCI_SLOT_NAME="
2886 str = strstr(data, TAG);
2890 if (sscanf(str, TAG "%04x:%02x:%02x.%1u",
2891 &domain, &bus, &dev, &func) != 4)
2895 info->domain = domain;
2902 #warning "Missing implementation of drmParsePciBusInfo"
2907 static int drmCompareBusInfo(drmDevicePtr a, drmDevicePtr b)
2909 if (a == NULL || b == NULL)
2912 if (a->bustype != b->bustype)
2915 switch (a->bustype) {
2917 return memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo));
2925 static int drmGetNodeType(const char *name)
2927 if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
2928 sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
2929 return DRM_NODE_PRIMARY;
2931 if (strncmp(name, DRM_CONTROL_MINOR_NAME,
2932 sizeof(DRM_CONTROL_MINOR_NAME ) - 1) == 0)
2933 return DRM_NODE_CONTROL;
2935 if (strncmp(name, DRM_RENDER_MINOR_NAME,
2936 sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
2937 return DRM_NODE_RENDER;
2942 static int drmGetMaxNodeName(void)
2944 return sizeof(DRM_DIR_NAME) +
2945 MAX3(sizeof(DRM_PRIMARY_MINOR_NAME),
2946 sizeof(DRM_CONTROL_MINOR_NAME),
2947 sizeof(DRM_RENDER_MINOR_NAME)) +
2948 3 /* lenght of the node number */;
2951 static int drmParsePciDeviceInfo(const char *d_name,
2952 drmPciDeviceInfoPtr device)
2955 char path[PATH_MAX + 1];
2956 unsigned char config[64];
2959 snprintf(path, PATH_MAX, "/sys/class/drm/%s/device/config", d_name);
2960 fd = open(path, O_RDONLY);
2964 ret = read(fd, config, sizeof(config));
2969 device->vendor_id = config[0] | (config[1] << 8);
2970 device->device_id = config[2] | (config[3] << 8);
2971 device->revision_id = config[8];
2972 device->subvendor_id = config[44] | (config[45] << 8);
2973 device->subdevice_id = config[46] | (config[47] << 8);
2977 #warning "Missing implementation of drmParsePciDeviceInfo"
2982 static void drmFreeDevice(drmDevicePtr *device)
2991 void drmFreeDevices(drmDevicePtr devices[], int count)
2995 if (devices == NULL)
2998 for (i = 0; i < count && devices[i] != NULL; i++)
2999 drmFreeDevice(&devices[i]);
3003 * Get drm devices on the system
3005 * \param devices the array of devices with drmDevicePtr elements
3006 * can be NULL to get the device number first
3007 * \param max_devices the maximum number of devices for the array
3009 * \return on error - negative error code,
3010 * if devices is NULL - total number of devices available on the system,
3011 * alternatively the number of devices stored in devices[], which is
3012 * capped by the max_devices.
3014 int drmGetDevices(drmDevicePtr devices[], int max_devices)
3016 drmDevicePtr *local_devices;
3017 drmDevicePtr device;
3019 struct dirent *dent;
3021 char node[PATH_MAX + 1];
3022 const int max_node_str = drmGetMaxNodeName();
3023 int node_type, subsystem_type;
3025 int ret, i, j, node_count, device_count;
3029 local_devices = calloc(max_count, sizeof(drmDevicePtr));
3030 if (local_devices == NULL)
3033 sysdir = opendir(DRM_DIR_NAME);
3040 while ((dent = readdir(sysdir))) {
3041 node_type = drmGetNodeType(dent->d_name);
3045 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, dent->d_name);
3046 if (stat(node, &sbuf))
3049 maj = major(sbuf.st_rdev);
3050 min = minor(sbuf.st_rdev);
3052 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3055 subsystem_type = drmParseSubsystemType(maj, min);
3057 if (subsystem_type < 0)
3060 switch (subsystem_type) {
3062 addr = device = calloc(1, sizeof(drmDevice) +
3064 (sizeof(void *) + max_node_str)) +
3065 sizeof(drmPciBusInfo) +
3066 sizeof(drmPciDeviceInfo));
3070 device->bustype = subsystem_type;
3071 device->available_nodes = 1 << node_type;
3073 addr += sizeof(drmDevice);
3074 device->nodes = addr;
3076 addr += DRM_NODE_MAX * sizeof(void *);
3077 for (j = 0; j < DRM_NODE_MAX; j++) {
3078 device->nodes[j] = addr;
3079 addr += max_node_str;
3081 memcpy(device->nodes[node_type], node, max_node_str);
3083 device->businfo.pci = addr;
3085 ret = drmParsePciBusInfo(maj, min, device->businfo.pci);
3089 // Fetch the device info if the user has requested it
3090 if (devices != NULL) {
3091 addr += sizeof(drmPciBusInfo);
3092 device->deviceinfo.pci = addr;
3094 ret = drmParsePciDeviceInfo(dent->d_name,
3095 device->deviceinfo.pci);
3102 fprintf(stderr, "The subsystem type is not supported yet\n");
3106 if (i >= max_count) {
3110 temp = realloc(local_devices, max_count * sizeof(drmDevicePtr));
3113 local_devices = temp;
3116 local_devices[i] = device;
3121 /* Fold nodes into a single device if they share the same bus info */
3122 for (i = 0; i < node_count; i++) {
3123 for (j = i + 1; j < node_count; j++) {
3124 if (drmCompareBusInfo(local_devices[i], local_devices[j]) == 0) {
3125 local_devices[i]->available_nodes |= local_devices[j]->available_nodes;
3126 node_type = log2(local_devices[j]->available_nodes);
3127 memcpy(local_devices[i]->nodes[node_type],
3128 local_devices[j]->nodes[node_type], max_node_str);
3129 drmFreeDevice(&local_devices[j]);
3135 for (i = 0; i < node_count && local_devices[i]; i++) {
3136 if ((devices != NULL) && (device_count < max_devices))
3137 devices[device_count] = local_devices[i];
3139 drmFreeDevice(&local_devices[i]);
3144 free(local_devices);
3146 return device_count;
3149 drmFreeDevices(local_devices, i);
3150 free(local_devices);