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.
50 #include <sys/types.h>
52 #define stat_t struct stat
53 #include <sys/ioctl.h>
56 #ifdef HAVE_SYS_MKDEV_H
57 # include <sys/mkdev.h> /* defines major(), minor(), and makedev() on Solaris */
61 /* Not all systems have MAP_FAILED defined */
63 #define MAP_FAILED ((void *)-1)
67 #include "libdrm_macros.h"
69 #include "util_math.h"
72 #define DRM_PRIMARY_MINOR_NAME "drm"
73 #define DRM_CONTROL_MINOR_NAME "drmC"
74 #define DRM_RENDER_MINOR_NAME "drmR"
76 #define DRM_PRIMARY_MINOR_NAME "card"
77 #define DRM_CONTROL_MINOR_NAME "controlD"
78 #define DRM_RENDER_MINOR_NAME "renderD"
81 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
95 #endif /* __OpenBSD__ */
98 #define DRM_MAJOR 226 /* Linux */
102 * This definition needs to be changed on some systems if dev_t is a structure.
103 * If there is a header file we can get it from, there would be best.
106 #define makedev(x,y) ((dev_t)(((x) << 8) | (y)))
109 #define DRM_MSG_VERBOSITY 3
111 #define memclear(s) memset(&s, 0, sizeof(s))
113 static drmServerInfoPtr drm_server_info;
115 void drmSetServerInfo(drmServerInfoPtr info)
117 drm_server_info = info;
121 * Output a message to stderr.
123 * \param format printf() like format string.
126 * This function is a wrapper around vfprintf().
129 static int DRM_PRINTFLIKE(1, 0)
130 drmDebugPrint(const char *format, va_list ap)
132 return vfprintf(stderr, format, ap);
136 drmMsg(const char *format, ...)
140 if (((env = getenv("LIBGL_DEBUG")) && strstr(env, "verbose")) ||
141 (drm_server_info && drm_server_info->debug_print))
143 va_start(ap, format);
144 if (drm_server_info) {
145 drm_server_info->debug_print(format,ap);
147 drmDebugPrint(format, ap);
153 static void *drmHashTable = NULL; /* Context switch callbacks */
155 void *drmGetHashTable(void)
160 void *drmMalloc(int size)
162 return calloc(1, size);
165 void drmFree(void *pt)
171 * Call ioctl, restarting if it is interupted
174 drmIoctl(int fd, unsigned long request, void *arg)
179 ret = ioctl(fd, request, arg);
180 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
184 static unsigned long drmGetKeyFromFd(int fd)
193 drmHashEntry *drmGetEntry(int fd)
195 unsigned long key = drmGetKeyFromFd(fd);
200 drmHashTable = drmHashCreate();
202 if (drmHashLookup(drmHashTable, key, &value)) {
203 entry = drmMalloc(sizeof(*entry));
206 entry->tagTable = drmHashCreate();
207 drmHashInsert(drmHashTable, key, entry);
215 * Compare two busid strings
220 * \return 1 if matched.
223 * This function compares two bus ID strings. It understands the older
224 * PCI:b:d:f format and the newer pci:oooo:bb:dd.f format. In the format, o is
225 * domain, b is bus, d is device, f is function.
227 static int drmMatchBusID(const char *id1, const char *id2, int pci_domain_ok)
229 /* First, check if the IDs are exactly the same */
230 if (strcasecmp(id1, id2) == 0)
233 /* Try to match old/new-style PCI bus IDs. */
234 if (strncasecmp(id1, "pci", 3) == 0) {
235 unsigned int o1, b1, d1, f1;
236 unsigned int o2, b2, d2, f2;
239 ret = sscanf(id1, "pci:%04x:%02x:%02x.%u", &o1, &b1, &d1, &f1);
242 ret = sscanf(id1, "PCI:%u:%u:%u", &b1, &d1, &f1);
247 ret = sscanf(id2, "pci:%04x:%02x:%02x.%u", &o2, &b2, &d2, &f2);
250 ret = sscanf(id2, "PCI:%u:%u:%u", &b2, &d2, &f2);
255 /* If domains aren't properly supported by the kernel interface,
256 * just ignore them, which sucks less than picking a totally random
257 * card with "open by name"
262 if ((o1 != o2) || (b1 != b2) || (d1 != d2) || (f1 != f2))
271 * Handles error checking for chown call.
273 * \param path to file.
274 * \param id of the new owner.
275 * \param id of the new group.
277 * \return zero if success or -1 if failure.
280 * Checks for failure. If failure was caused by signal call chown again.
281 * If any other failure happened then it will output error mesage using
285 static int chown_check_return(const char *path, uid_t owner, gid_t group)
290 rv = chown(path, owner, group);
291 } while (rv != 0 && errno == EINTR);
296 drmMsg("Failed to change owner or group for file %s! %d: %s\n",
297 path, errno, strerror(errno));
303 * Open the DRM device, creating it if necessary.
305 * \param dev major and minor numbers of the device.
306 * \param minor minor number of the device.
308 * \return a file descriptor on success, or a negative value on error.
311 * Assembles the device name from \p minor and opens it, creating the device
312 * special file node with the major and minor numbers specified by \p dev and
313 * parent directory if necessary and was called by root.
315 static int drmOpenDevice(dev_t dev, int minor, int type)
318 const char *dev_name;
321 mode_t devmode = DRM_DEV_MODE, serv_mode;
324 int isroot = !geteuid();
325 uid_t user = DRM_DEV_UID;
326 gid_t group = DRM_DEV_GID;
330 case DRM_NODE_PRIMARY:
331 dev_name = DRM_DEV_NAME;
333 case DRM_NODE_CONTROL:
334 dev_name = DRM_CONTROL_DEV_NAME;
336 case DRM_NODE_RENDER:
337 dev_name = DRM_RENDER_DEV_NAME;
343 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
344 drmMsg("drmOpenDevice: node name is %s\n", buf);
346 if (drm_server_info && drm_server_info->get_perms) {
347 drm_server_info->get_perms(&serv_group, &serv_mode);
348 devmode = serv_mode ? serv_mode : DRM_DEV_MODE;
349 devmode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
353 if (stat(DRM_DIR_NAME, &st)) {
355 return DRM_ERR_NOT_ROOT;
356 mkdir(DRM_DIR_NAME, DRM_DEV_DIRMODE);
357 chown_check_return(DRM_DIR_NAME, 0, 0); /* root:root */
358 chmod(DRM_DIR_NAME, DRM_DEV_DIRMODE);
361 /* Check if the device node exists and create it if necessary. */
362 if (stat(buf, &st)) {
364 return DRM_ERR_NOT_ROOT;
366 mknod(buf, S_IFCHR | devmode, dev);
369 if (drm_server_info && drm_server_info->get_perms) {
370 group = ((int)serv_group >= 0) ? serv_group : DRM_DEV_GID;
371 chown_check_return(buf, user, group);
375 /* if we modprobed then wait for udev */
379 if (stat(DRM_DIR_NAME, &st)) {
383 if (udev_count == 50)
388 if (stat(buf, &st)) {
392 if (udev_count == 50)
399 fd = open(buf, O_RDWR, 0);
400 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
401 fd, fd < 0 ? strerror(errno) : "OK");
406 /* Check if the device node is not what we expect it to be, and recreate it
407 * and try again if so.
409 if (st.st_rdev != dev) {
411 return DRM_ERR_NOT_ROOT;
413 mknod(buf, S_IFCHR | devmode, dev);
414 if (drm_server_info && drm_server_info->get_perms) {
415 chown_check_return(buf, user, group);
419 fd = open(buf, O_RDWR, 0);
420 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
421 fd, fd < 0 ? strerror(errno) : "OK");
425 drmMsg("drmOpenDevice: Open failed\n");
433 * Open the DRM device
435 * \param minor device minor number.
436 * \param create allow to create the device if set.
438 * \return a file descriptor on success, or a negative value on error.
441 * Calls drmOpenDevice() if \p create is set, otherwise assembles the device
442 * name from \p minor and opens it.
444 static int drmOpenMinor(int minor, int create, int type)
448 const char *dev_name;
451 return drmOpenDevice(makedev(DRM_MAJOR, minor), minor, type);
454 case DRM_NODE_PRIMARY:
455 dev_name = DRM_DEV_NAME;
457 case DRM_NODE_CONTROL:
458 dev_name = DRM_CONTROL_DEV_NAME;
460 case DRM_NODE_RENDER:
461 dev_name = DRM_RENDER_DEV_NAME;
467 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
468 if ((fd = open(buf, O_RDWR, 0)) >= 0)
475 * Determine whether the DRM kernel driver has been loaded.
477 * \return 1 if the DRM driver is loaded, 0 otherwise.
480 * Determine the presence of the kernel driver by attempting to open the 0
481 * minor and get version information. For backward compatibility with older
482 * Linux implementations, /proc/dri is also checked.
484 int drmAvailable(void)
486 drmVersionPtr version;
490 if ((fd = drmOpenMinor(0, 1, DRM_NODE_PRIMARY)) < 0) {
492 /* Try proc for backward Linux compatibility */
493 if (!access("/proc/dri/0", R_OK))
499 if ((version = drmGetVersion(fd))) {
501 drmFreeVersion(version);
508 static int drmGetMinorBase(int type)
511 case DRM_NODE_PRIMARY:
513 case DRM_NODE_CONTROL:
515 case DRM_NODE_RENDER:
522 static int drmGetMinorType(int minor)
524 int type = minor >> 6;
530 case DRM_NODE_PRIMARY:
531 case DRM_NODE_CONTROL:
532 case DRM_NODE_RENDER:
539 static const char *drmGetMinorName(int type)
542 case DRM_NODE_PRIMARY:
543 return DRM_PRIMARY_MINOR_NAME;
544 case DRM_NODE_CONTROL:
545 return DRM_CONTROL_MINOR_NAME;
546 case DRM_NODE_RENDER:
547 return DRM_RENDER_MINOR_NAME;
554 * Open the device by bus ID.
556 * \param busid bus ID.
557 * \param type device node type.
559 * \return a file descriptor on success, or a negative value on error.
562 * This function attempts to open every possible minor (up to DRM_MAX_MINOR),
563 * comparing the device bus ID with the one supplied.
565 * \sa drmOpenMinor() and drmGetBusid().
567 static int drmOpenByBusid(const char *busid, int type)
569 int i, pci_domain_ok = 1;
573 int base = drmGetMinorBase(type);
578 drmMsg("drmOpenByBusid: Searching for BusID %s\n", busid);
579 for (i = base; i < base + DRM_MAX_MINOR; i++) {
580 fd = drmOpenMinor(i, 1, type);
581 drmMsg("drmOpenByBusid: drmOpenMinor returns %d\n", fd);
583 /* We need to try for 1.4 first for proper PCI domain support
584 * and if that fails, we know the kernel is busted
588 sv.drm_dd_major = -1; /* Don't care */
589 sv.drm_dd_minor = -1; /* Don't care */
590 if (drmSetInterfaceVersion(fd, &sv)) {
596 sv.drm_dd_major = -1; /* Don't care */
597 sv.drm_dd_minor = -1; /* Don't care */
598 drmMsg("drmOpenByBusid: Interface 1.4 failed, trying 1.1\n");
599 drmSetInterfaceVersion(fd, &sv);
601 buf = drmGetBusid(fd);
602 drmMsg("drmOpenByBusid: drmGetBusid reports %s\n", buf);
603 if (buf && drmMatchBusID(buf, busid, pci_domain_ok)) {
617 * Open the device by name.
619 * \param name driver name.
620 * \param type the device node type.
622 * \return a file descriptor on success, or a negative value on error.
625 * This function opens the first minor number that matches the driver name and
626 * isn't already in use. If it's in use it then it will already have a bus ID
629 * \sa drmOpenMinor(), drmGetVersion() and drmGetBusid().
631 static int drmOpenByName(const char *name, int type)
635 drmVersionPtr version;
637 int base = drmGetMinorBase(type);
643 * Open the first minor number that matches the driver name and isn't
644 * already in use. If it's in use it will have a busid assigned already.
646 for (i = base; i < base + DRM_MAX_MINOR; i++) {
647 if ((fd = drmOpenMinor(i, 1, type)) >= 0) {
648 if ((version = drmGetVersion(fd))) {
649 if (!strcmp(version->name, name)) {
650 drmFreeVersion(version);
651 id = drmGetBusid(fd);
652 drmMsg("drmGetBusid returned '%s'\n", id ? id : "NULL");
661 drmFreeVersion(version);
669 /* Backward-compatibility /proc support */
670 for (i = 0; i < 8; i++) {
671 char proc_name[64], buf[512];
672 char *driver, *pt, *devstring;
675 sprintf(proc_name, "/proc/dri/%d/name", i);
676 if ((fd = open(proc_name, 0, 0)) >= 0) {
677 retcode = read(fd, buf, sizeof(buf)-1);
680 buf[retcode-1] = '\0';
681 for (driver = pt = buf; *pt && *pt != ' '; ++pt)
683 if (*pt) { /* Device is next */
685 if (!strcmp(driver, name)) { /* Match */
686 for (devstring = ++pt; *pt && *pt != ' '; ++pt)
688 if (*pt) { /* Found busid */
689 return drmOpenByBusid(++pt, type);
690 } else { /* No busid */
691 return drmOpenDevice(strtol(devstring, NULL, 0),i, type);
705 * Open the DRM device.
707 * Looks up the specified name and bus ID, and opens the device found. The
708 * entry in /dev/dri is created if necessary and if called by root.
710 * \param name driver name. Not referenced if bus ID is supplied.
711 * \param busid bus ID. Zero if not known.
713 * \return a file descriptor on success, or a negative value on error.
716 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
719 int drmOpen(const char *name, const char *busid)
721 return drmOpenWithType(name, busid, DRM_NODE_PRIMARY);
725 * Open the DRM device with specified type.
727 * Looks up the specified name and bus ID, and opens the device found. The
728 * entry in /dev/dri is created if necessary and if called by root.
730 * \param name driver name. Not referenced if bus ID is supplied.
731 * \param busid bus ID. Zero if not known.
732 * \param type the device node type to open, PRIMARY, CONTROL or RENDER
734 * \return a file descriptor on success, or a negative value on error.
737 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
740 int drmOpenWithType(const char *name, const char *busid, int type)
742 if (!drmAvailable() && name != NULL && drm_server_info &&
743 drm_server_info->load_module) {
744 /* try to load the kernel module */
745 if (!drm_server_info->load_module(name)) {
746 drmMsg("[drm] failed to load kernel module \"%s\"\n", name);
752 int fd = drmOpenByBusid(busid, type);
758 return drmOpenByName(name, type);
763 int drmOpenControl(int minor)
765 return drmOpenMinor(minor, 0, DRM_NODE_CONTROL);
768 int drmOpenRender(int minor)
770 return drmOpenMinor(minor, 0, DRM_NODE_RENDER);
774 * Free the version information returned by drmGetVersion().
776 * \param v pointer to the version information.
779 * It frees the memory pointed by \p %v as well as all the non-null strings
782 void drmFreeVersion(drmVersionPtr v)
794 * Free the non-public version information returned by the kernel.
796 * \param v pointer to the version information.
799 * Used by drmGetVersion() to free the memory pointed by \p %v as well as all
800 * the non-null strings pointers in it.
802 static void drmFreeKernelVersion(drm_version_t *v)
814 * Copy version information.
816 * \param d destination pointer.
817 * \param s source pointer.
820 * Used by drmGetVersion() to translate the information returned by the ioctl
821 * interface in a private structure into the public structure counterpart.
823 static void drmCopyVersion(drmVersionPtr d, const drm_version_t *s)
825 d->version_major = s->version_major;
826 d->version_minor = s->version_minor;
827 d->version_patchlevel = s->version_patchlevel;
828 d->name_len = s->name_len;
829 d->name = strdup(s->name);
830 d->date_len = s->date_len;
831 d->date = strdup(s->date);
832 d->desc_len = s->desc_len;
833 d->desc = strdup(s->desc);
838 * Query the driver version information.
840 * \param fd file descriptor.
842 * \return pointer to a drmVersion structure which should be freed with
845 * \note Similar information is available via /proc/dri.
848 * It gets the version information via successive DRM_IOCTL_VERSION ioctls,
849 * first with zeros to get the string lengths, and then the actually strings.
850 * It also null-terminates them since they might not be already.
852 drmVersionPtr drmGetVersion(int fd)
854 drmVersionPtr retval;
855 drm_version_t *version = drmMalloc(sizeof(*version));
859 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
860 drmFreeKernelVersion(version);
864 if (version->name_len)
865 version->name = drmMalloc(version->name_len + 1);
866 if (version->date_len)
867 version->date = drmMalloc(version->date_len + 1);
868 if (version->desc_len)
869 version->desc = drmMalloc(version->desc_len + 1);
871 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
872 drmMsg("DRM_IOCTL_VERSION: %s\n", strerror(errno));
873 drmFreeKernelVersion(version);
877 /* The results might not be null-terminated strings, so terminate them. */
878 if (version->name_len) version->name[version->name_len] = '\0';
879 if (version->date_len) version->date[version->date_len] = '\0';
880 if (version->desc_len) version->desc[version->desc_len] = '\0';
882 retval = drmMalloc(sizeof(*retval));
883 drmCopyVersion(retval, version);
884 drmFreeKernelVersion(version);
890 * Get version information for the DRM user space library.
892 * This version number is driver independent.
894 * \param fd file descriptor.
896 * \return version information.
899 * This function allocates and fills a drm_version structure with a hard coded
902 drmVersionPtr drmGetLibVersion(int fd)
904 drm_version_t *version = drmMalloc(sizeof(*version));
907 * NOTE THIS MUST NOT GO ABOVE VERSION 1.X due to drivers needing it
908 * revision 1.0.x = original DRM interface with no drmGetLibVersion
909 * entry point and many drm<Device> extensions
910 * revision 1.1.x = added drmCommand entry points for device extensions
911 * added drmGetLibVersion to identify libdrm.a version
912 * revision 1.2.x = added drmSetInterfaceVersion
913 * modified drmOpen to handle both busid and name
914 * revision 1.3.x = added server + memory manager
916 version->version_major = 1;
917 version->version_minor = 3;
918 version->version_patchlevel = 0;
920 return (drmVersionPtr)version;
923 int drmGetCap(int fd, uint64_t capability, uint64_t *value)
925 struct drm_get_cap cap;
929 cap.capability = capability;
931 ret = drmIoctl(fd, DRM_IOCTL_GET_CAP, &cap);
939 int drmSetClientCap(int fd, uint64_t capability, uint64_t value)
941 struct drm_set_client_cap cap;
944 cap.capability = capability;
947 return drmIoctl(fd, DRM_IOCTL_SET_CLIENT_CAP, &cap);
951 * Free the bus ID information.
953 * \param busid bus ID information string as given by drmGetBusid().
956 * This function is just frees the memory pointed by \p busid.
958 void drmFreeBusid(const char *busid)
960 drmFree((void *)busid);
965 * Get the bus ID of the device.
967 * \param fd file descriptor.
969 * \return bus ID string.
972 * This function gets the bus ID via successive DRM_IOCTL_GET_UNIQUE ioctls to
973 * get the string length and data, passing the arguments in a drm_unique
976 char *drmGetBusid(int fd)
982 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
984 u.unique = drmMalloc(u.unique_len + 1);
985 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
987 u.unique[u.unique_len] = '\0';
994 * Set the bus ID of the device.
996 * \param fd file descriptor.
997 * \param busid bus ID string.
999 * \return zero on success, negative on failure.
1002 * This function is a wrapper around the DRM_IOCTL_SET_UNIQUE ioctl, passing
1003 * the arguments in a drm_unique structure.
1005 int drmSetBusid(int fd, const char *busid)
1010 u.unique = (char *)busid;
1011 u.unique_len = strlen(busid);
1013 if (drmIoctl(fd, DRM_IOCTL_SET_UNIQUE, &u)) {
1019 int drmGetMagic(int fd, drm_magic_t * magic)
1026 if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
1028 *magic = auth.magic;
1032 int drmAuthMagic(int fd, drm_magic_t magic)
1038 if (drmIoctl(fd, DRM_IOCTL_AUTH_MAGIC, &auth))
1044 * Specifies a range of memory that is available for mapping by a
1047 * \param fd file descriptor.
1048 * \param offset usually the physical address. The actual meaning depends of
1049 * the \p type parameter. See below.
1050 * \param size of the memory in bytes.
1051 * \param type type of the memory to be mapped.
1052 * \param flags combination of several flags to modify the function actions.
1053 * \param handle will be set to a value that may be used as the offset
1054 * parameter for mmap().
1056 * \return zero on success or a negative value on error.
1058 * \par Mapping the frame buffer
1059 * For the frame buffer
1060 * - \p offset will be the physical address of the start of the frame buffer,
1061 * - \p size will be the size of the frame buffer in bytes, and
1062 * - \p type will be DRM_FRAME_BUFFER.
1065 * The area mapped will be uncached. If MTRR support is available in the
1066 * kernel, the frame buffer area will be set to write combining.
1068 * \par Mapping the MMIO register area
1069 * For the MMIO register area,
1070 * - \p offset will be the physical address of the start of the register area,
1071 * - \p size will be the size of the register area bytes, and
1072 * - \p type will be DRM_REGISTERS.
1074 * The area mapped will be uncached.
1076 * \par Mapping the SAREA
1078 * - \p offset will be ignored and should be set to zero,
1079 * - \p size will be the desired size of the SAREA in bytes,
1080 * - \p type will be DRM_SHM.
1083 * A shared memory area of the requested size will be created and locked in
1084 * kernel memory. This area may be mapped into client-space by using the handle
1087 * \note May only be called by root.
1090 * This function is a wrapper around the DRM_IOCTL_ADD_MAP ioctl, passing
1091 * the arguments in a drm_map structure.
1093 int drmAddMap(int fd, drm_handle_t offset, drmSize size, drmMapType type,
1094 drmMapFlags flags, drm_handle_t *handle)
1099 map.offset = offset;
1103 if (drmIoctl(fd, DRM_IOCTL_ADD_MAP, &map))
1106 *handle = (drm_handle_t)(uintptr_t)map.handle;
1110 int drmRmMap(int fd, drm_handle_t handle)
1115 map.handle = (void *)(uintptr_t)handle;
1117 if(drmIoctl(fd, DRM_IOCTL_RM_MAP, &map))
1123 * Make buffers available for DMA transfers.
1125 * \param fd file descriptor.
1126 * \param count number of buffers.
1127 * \param size size of each buffer.
1128 * \param flags buffer allocation flags.
1129 * \param agp_offset offset in the AGP aperture
1131 * \return number of buffers allocated, negative on error.
1134 * This function is a wrapper around DRM_IOCTL_ADD_BUFS ioctl.
1138 int drmAddBufs(int fd, int count, int size, drmBufDescFlags flags,
1141 drm_buf_desc_t request;
1144 request.count = count;
1145 request.size = size;
1146 request.flags = flags;
1147 request.agp_start = agp_offset;
1149 if (drmIoctl(fd, DRM_IOCTL_ADD_BUFS, &request))
1151 return request.count;
1154 int drmMarkBufs(int fd, double low, double high)
1156 drm_buf_info_t info;
1161 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1167 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1170 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1171 int retval = -errno;
1176 for (i = 0; i < info.count; i++) {
1177 info.list[i].low_mark = low * info.list[i].count;
1178 info.list[i].high_mark = high * info.list[i].count;
1179 if (drmIoctl(fd, DRM_IOCTL_MARK_BUFS, &info.list[i])) {
1180 int retval = -errno;
1193 * \param fd file descriptor.
1194 * \param count number of buffers to free.
1195 * \param list list of buffers to be freed.
1197 * \return zero on success, or a negative value on failure.
1199 * \note This function is primarily used for debugging.
1202 * This function is a wrapper around the DRM_IOCTL_FREE_BUFS ioctl, passing
1203 * the arguments in a drm_buf_free structure.
1205 int drmFreeBufs(int fd, int count, int *list)
1207 drm_buf_free_t request;
1210 request.count = count;
1211 request.list = list;
1212 if (drmIoctl(fd, DRM_IOCTL_FREE_BUFS, &request))
1221 * \param fd file descriptor.
1224 * This function closes the file descriptor.
1226 int drmClose(int fd)
1228 unsigned long key = drmGetKeyFromFd(fd);
1229 drmHashEntry *entry = drmGetEntry(fd);
1231 drmHashDestroy(entry->tagTable);
1234 entry->tagTable = NULL;
1236 drmHashDelete(drmHashTable, key);
1244 * Map a region of memory.
1246 * \param fd file descriptor.
1247 * \param handle handle returned by drmAddMap().
1248 * \param size size in bytes. Must match the size used by drmAddMap().
1249 * \param address will contain the user-space virtual address where the mapping
1252 * \return zero on success, or a negative value on failure.
1255 * This function is a wrapper for mmap().
1257 int drmMap(int fd, drm_handle_t handle, drmSize size, drmAddressPtr address)
1259 static unsigned long pagesize_mask = 0;
1265 pagesize_mask = getpagesize() - 1;
1267 size = (size + pagesize_mask) & ~pagesize_mask;
1269 *address = drm_mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1270 if (*address == MAP_FAILED)
1277 * Unmap mappings obtained with drmMap().
1279 * \param address address as given by drmMap().
1280 * \param size size in bytes. Must match the size used by drmMap().
1282 * \return zero on success, or a negative value on failure.
1285 * This function is a wrapper for munmap().
1287 int drmUnmap(drmAddress address, drmSize size)
1289 return drm_munmap(address, size);
1292 drmBufInfoPtr drmGetBufInfo(int fd)
1294 drm_buf_info_t info;
1295 drmBufInfoPtr retval;
1300 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1304 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1307 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1312 retval = drmMalloc(sizeof(*retval));
1313 retval->count = info.count;
1314 retval->list = drmMalloc(info.count * sizeof(*retval->list));
1315 for (i = 0; i < info.count; i++) {
1316 retval->list[i].count = info.list[i].count;
1317 retval->list[i].size = info.list[i].size;
1318 retval->list[i].low_mark = info.list[i].low_mark;
1319 retval->list[i].high_mark = info.list[i].high_mark;
1328 * Map all DMA buffers into client-virtual space.
1330 * \param fd file descriptor.
1332 * \return a pointer to a ::drmBufMap structure.
1334 * \note The client may not use these buffers until obtaining buffer indices
1338 * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1339 * information about the buffers in a drm_buf_map structure into the
1340 * client-visible data structures.
1342 drmBufMapPtr drmMapBufs(int fd)
1345 drmBufMapPtr retval;
1349 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1355 if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1358 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1363 retval = drmMalloc(sizeof(*retval));
1364 retval->count = bufs.count;
1365 retval->list = drmMalloc(bufs.count * sizeof(*retval->list));
1366 for (i = 0; i < bufs.count; i++) {
1367 retval->list[i].idx = bufs.list[i].idx;
1368 retval->list[i].total = bufs.list[i].total;
1369 retval->list[i].used = 0;
1370 retval->list[i].address = bufs.list[i].address;
1380 * Unmap buffers allocated with drmMapBufs().
1382 * \return zero on success, or negative value on failure.
1385 * Calls munmap() for every buffer stored in \p bufs and frees the
1386 * memory allocated by drmMapBufs().
1388 int drmUnmapBufs(drmBufMapPtr bufs)
1392 for (i = 0; i < bufs->count; i++) {
1393 drm_munmap(bufs->list[i].address, bufs->list[i].total);
1396 drmFree(bufs->list);
1403 #define DRM_DMA_RETRY 16
1406 * Reserve DMA buffers.
1408 * \param fd file descriptor.
1411 * \return zero on success, or a negative value on failure.
1414 * Assemble the arguments into a drm_dma structure and keeps issuing the
1415 * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1417 int drmDMA(int fd, drmDMAReqPtr request)
1422 dma.context = request->context;
1423 dma.send_count = request->send_count;
1424 dma.send_indices = request->send_list;
1425 dma.send_sizes = request->send_sizes;
1426 dma.flags = request->flags;
1427 dma.request_count = request->request_count;
1428 dma.request_size = request->request_size;
1429 dma.request_indices = request->request_list;
1430 dma.request_sizes = request->request_sizes;
1431 dma.granted_count = 0;
1434 ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1435 } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1438 request->granted_count = dma.granted_count;
1447 * Obtain heavyweight hardware lock.
1449 * \param fd file descriptor.
1450 * \param context context.
1451 * \param flags flags that determine the sate of the hardware when the function
1454 * \return always zero.
1457 * This function translates the arguments into a drm_lock structure and issue
1458 * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1460 int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
1465 lock.context = context;
1467 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
1468 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
1469 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
1470 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
1471 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
1472 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
1474 while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
1480 * Release the hardware lock.
1482 * \param fd file descriptor.
1483 * \param context context.
1485 * \return zero on success, or a negative value on failure.
1488 * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
1489 * argument in a drm_lock structure.
1491 int drmUnlock(int fd, drm_context_t context)
1496 lock.context = context;
1497 return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
1500 drm_context_t *drmGetReservedContextList(int fd, int *count)
1504 drm_context_t * retval;
1508 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1514 if (!(list = drmMalloc(res.count * sizeof(*list))))
1516 if (!(retval = drmMalloc(res.count * sizeof(*retval)))) {
1521 res.contexts = list;
1522 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1525 for (i = 0; i < res.count; i++)
1526 retval[i] = list[i].handle;
1533 void drmFreeReservedContextList(drm_context_t *pt)
1541 * Used by the X server during GLXContext initialization. This causes
1542 * per-context kernel-level resources to be allocated.
1544 * \param fd file descriptor.
1545 * \param handle is set on success. To be used by the client when requesting DMA
1546 * dispatch with drmDMA().
1548 * \return zero on success, or a negative value on failure.
1550 * \note May only be called by root.
1553 * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
1554 * argument in a drm_ctx structure.
1556 int drmCreateContext(int fd, drm_context_t *handle)
1561 if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
1563 *handle = ctx.handle;
1567 int drmSwitchToContext(int fd, drm_context_t context)
1572 ctx.handle = context;
1573 if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
1578 int drmSetContextFlags(int fd, drm_context_t context, drm_context_tFlags flags)
1583 * Context preserving means that no context switches are done between DMA
1584 * buffers from one context and the next. This is suitable for use in the
1585 * X server (which promises to maintain hardware context), or in the
1586 * client-side library when buffers are swapped on behalf of two threads.
1589 ctx.handle = context;
1590 if (flags & DRM_CONTEXT_PRESERVED)
1591 ctx.flags |= _DRM_CONTEXT_PRESERVED;
1592 if (flags & DRM_CONTEXT_2DONLY)
1593 ctx.flags |= _DRM_CONTEXT_2DONLY;
1594 if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
1599 int drmGetContextFlags(int fd, drm_context_t context,
1600 drm_context_tFlagsPtr flags)
1605 ctx.handle = context;
1606 if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
1609 if (ctx.flags & _DRM_CONTEXT_PRESERVED)
1610 *flags |= DRM_CONTEXT_PRESERVED;
1611 if (ctx.flags & _DRM_CONTEXT_2DONLY)
1612 *flags |= DRM_CONTEXT_2DONLY;
1619 * Free any kernel-level resources allocated with drmCreateContext() associated
1622 * \param fd file descriptor.
1623 * \param handle handle given by drmCreateContext().
1625 * \return zero on success, or a negative value on failure.
1627 * \note May only be called by root.
1630 * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
1631 * argument in a drm_ctx structure.
1633 int drmDestroyContext(int fd, drm_context_t handle)
1638 ctx.handle = handle;
1639 if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
1644 int drmCreateDrawable(int fd, drm_drawable_t *handle)
1649 if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
1651 *handle = draw.handle;
1655 int drmDestroyDrawable(int fd, drm_drawable_t handle)
1660 draw.handle = handle;
1661 if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
1666 int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
1667 drm_drawable_info_type_t type, unsigned int num,
1670 drm_update_draw_t update;
1673 update.handle = handle;
1676 update.data = (unsigned long long)(unsigned long)data;
1678 if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
1685 * Acquire the AGP device.
1687 * Must be called before any of the other AGP related calls.
1689 * \param fd file descriptor.
1691 * \return zero on success, or a negative value on failure.
1694 * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
1696 int drmAgpAcquire(int fd)
1698 if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
1705 * Release the AGP device.
1707 * \param fd file descriptor.
1709 * \return zero on success, or a negative value on failure.
1712 * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
1714 int drmAgpRelease(int fd)
1716 if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
1725 * \param fd file descriptor.
1726 * \param mode AGP mode.
1728 * \return zero on success, or a negative value on failure.
1731 * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
1732 * argument in a drm_agp_mode structure.
1734 int drmAgpEnable(int fd, unsigned long mode)
1740 if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
1747 * Allocate a chunk of AGP memory.
1749 * \param fd file descriptor.
1750 * \param size requested memory size in bytes. Will be rounded to page boundary.
1751 * \param type type of memory to allocate.
1752 * \param address if not zero, will be set to the physical address of the
1754 * \param handle on success will be set to a handle of the allocated memory.
1756 * \return zero on success, or a negative value on failure.
1759 * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
1760 * arguments in a drm_agp_buffer structure.
1762 int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
1763 unsigned long *address, drm_handle_t *handle)
1768 *handle = DRM_AGP_NO_HANDLE;
1771 if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
1774 *address = b.physical;
1781 * Free a chunk of AGP memory.
1783 * \param fd file descriptor.
1784 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1786 * \return zero on success, or a negative value on failure.
1789 * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
1790 * argument in a drm_agp_buffer structure.
1792 int drmAgpFree(int fd, drm_handle_t handle)
1798 if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
1805 * Bind a chunk of AGP memory.
1807 * \param fd file descriptor.
1808 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1809 * \param offset offset in bytes. It will round to page boundary.
1811 * \return zero on success, or a negative value on failure.
1814 * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
1815 * argument in a drm_agp_binding structure.
1817 int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
1819 drm_agp_binding_t b;
1824 if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
1831 * Unbind a chunk of AGP memory.
1833 * \param fd file descriptor.
1834 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1836 * \return zero on success, or a negative value on failure.
1839 * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
1840 * the argument in a drm_agp_binding structure.
1842 int drmAgpUnbind(int fd, drm_handle_t handle)
1844 drm_agp_binding_t b;
1848 if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
1855 * Get AGP driver major version number.
1857 * \param fd file descriptor.
1859 * \return major version number on success, or a negative value on failure..
1862 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1863 * necessary information in a drm_agp_info structure.
1865 int drmAgpVersionMajor(int fd)
1871 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1873 return i.agp_version_major;
1878 * Get AGP driver minor version number.
1880 * \param fd file descriptor.
1882 * \return minor version number on success, or a negative value on failure.
1885 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1886 * necessary information in a drm_agp_info structure.
1888 int drmAgpVersionMinor(int fd)
1894 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1896 return i.agp_version_minor;
1903 * \param fd file descriptor.
1905 * \return mode on success, or zero on failure.
1908 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1909 * necessary information in a drm_agp_info structure.
1911 unsigned long drmAgpGetMode(int fd)
1917 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1924 * Get AGP aperture base.
1926 * \param fd file descriptor.
1928 * \return aperture base on success, zero on failure.
1931 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1932 * necessary information in a drm_agp_info structure.
1934 unsigned long drmAgpBase(int fd)
1940 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1942 return i.aperture_base;
1947 * Get AGP aperture size.
1949 * \param fd file descriptor.
1951 * \return aperture size on success, zero on failure.
1954 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1955 * necessary information in a drm_agp_info structure.
1957 unsigned long drmAgpSize(int fd)
1963 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1965 return i.aperture_size;
1970 * Get used AGP memory.
1972 * \param fd file descriptor.
1974 * \return memory used on success, or zero on failure.
1977 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1978 * necessary information in a drm_agp_info structure.
1980 unsigned long drmAgpMemoryUsed(int fd)
1986 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1988 return i.memory_used;
1993 * Get available AGP memory.
1995 * \param fd file descriptor.
1997 * \return memory available on success, or zero on failure.
2000 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2001 * necessary information in a drm_agp_info structure.
2003 unsigned long drmAgpMemoryAvail(int fd)
2009 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2011 return i.memory_allowed;
2016 * Get hardware vendor ID.
2018 * \param fd file descriptor.
2020 * \return vendor ID on success, or zero on failure.
2023 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2024 * necessary information in a drm_agp_info structure.
2026 unsigned int drmAgpVendorId(int fd)
2032 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2039 * Get hardware device ID.
2041 * \param fd file descriptor.
2043 * \return zero on success, or zero on failure.
2046 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2047 * necessary information in a drm_agp_info structure.
2049 unsigned int drmAgpDeviceId(int fd)
2055 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2060 int drmScatterGatherAlloc(int fd, unsigned long size, drm_handle_t *handle)
2062 drm_scatter_gather_t sg;
2068 if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
2070 *handle = sg.handle;
2074 int drmScatterGatherFree(int fd, drm_handle_t handle)
2076 drm_scatter_gather_t sg;
2080 if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
2088 * \param fd file descriptor.
2089 * \param vbl pointer to a drmVBlank structure.
2091 * \return zero on success, or a negative value on failure.
2094 * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
2096 int drmWaitVBlank(int fd, drmVBlankPtr vbl)
2098 struct timespec timeout, cur;
2101 ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2103 fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
2109 ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
2110 vbl->request.type &= ~DRM_VBLANK_RELATIVE;
2111 if (ret && errno == EINTR) {
2112 clock_gettime(CLOCK_MONOTONIC, &cur);
2113 /* Timeout after 1s */
2114 if (cur.tv_sec > timeout.tv_sec + 1 ||
2115 (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
2122 } while (ret && errno == EINTR);
2128 int drmError(int err, const char *label)
2131 case DRM_ERR_NO_DEVICE:
2132 fprintf(stderr, "%s: no device\n", label);
2134 case DRM_ERR_NO_ACCESS:
2135 fprintf(stderr, "%s: no access\n", label);
2137 case DRM_ERR_NOT_ROOT:
2138 fprintf(stderr, "%s: not root\n", label);
2140 case DRM_ERR_INVALID:
2141 fprintf(stderr, "%s: invalid args\n", label);
2146 fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2154 * Install IRQ handler.
2156 * \param fd file descriptor.
2157 * \param irq IRQ number.
2159 * \return zero on success, or a negative value on failure.
2162 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2163 * argument in a drm_control structure.
2165 int drmCtlInstHandler(int fd, int irq)
2170 ctl.func = DRM_INST_HANDLER;
2172 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2179 * Uninstall IRQ handler.
2181 * \param fd file descriptor.
2183 * \return zero on success, or a negative value on failure.
2186 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2187 * argument in a drm_control structure.
2189 int drmCtlUninstHandler(int fd)
2194 ctl.func = DRM_UNINST_HANDLER;
2196 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2201 int drmFinish(int fd, int context, drmLockFlags flags)
2206 lock.context = context;
2207 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
2208 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
2209 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
2210 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
2211 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2212 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2213 if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2219 * Get IRQ from bus ID.
2221 * \param fd file descriptor.
2222 * \param busnum bus number.
2223 * \param devnum device number.
2224 * \param funcnum function number.
2226 * \return IRQ number on success, or a negative value on failure.
2229 * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2230 * arguments in a drm_irq_busid structure.
2232 int drmGetInterruptFromBusID(int fd, int busnum, int devnum, int funcnum)
2239 p.funcnum = funcnum;
2240 if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2245 int drmAddContextTag(int fd, drm_context_t context, void *tag)
2247 drmHashEntry *entry = drmGetEntry(fd);
2249 if (drmHashInsert(entry->tagTable, context, tag)) {
2250 drmHashDelete(entry->tagTable, context);
2251 drmHashInsert(entry->tagTable, context, tag);
2256 int drmDelContextTag(int fd, drm_context_t context)
2258 drmHashEntry *entry = drmGetEntry(fd);
2260 return drmHashDelete(entry->tagTable, context);
2263 void *drmGetContextTag(int fd, drm_context_t context)
2265 drmHashEntry *entry = drmGetEntry(fd);
2268 if (drmHashLookup(entry->tagTable, context, &value))
2274 int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2275 drm_handle_t handle)
2277 drm_ctx_priv_map_t map;
2280 map.ctx_id = ctx_id;
2281 map.handle = (void *)(uintptr_t)handle;
2283 if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2288 int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2289 drm_handle_t *handle)
2291 drm_ctx_priv_map_t map;
2294 map.ctx_id = ctx_id;
2296 if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2299 *handle = (drm_handle_t)(uintptr_t)map.handle;
2304 int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2305 drmMapType *type, drmMapFlags *flags, drm_handle_t *handle,
2312 if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2314 *offset = map.offset;
2318 *handle = (unsigned long)map.handle;
2323 int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2324 unsigned long *magic, unsigned long *iocs)
2326 drm_client_t client;
2330 if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2332 *auth = client.auth;
2335 *magic = client.magic;
2336 *iocs = client.iocs;
2340 int drmGetStats(int fd, drmStatsT *stats)
2346 if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2350 memset(stats, 0, sizeof(*stats));
2351 if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2355 stats->data[i].long_format = "%-20.20s"; \
2356 stats->data[i].rate_format = "%8.8s"; \
2357 stats->data[i].isvalue = 1; \
2358 stats->data[i].verbose = 0
2361 stats->data[i].long_format = "%-20.20s"; \
2362 stats->data[i].rate_format = "%5.5s"; \
2363 stats->data[i].isvalue = 0; \
2364 stats->data[i].mult_names = "kgm"; \
2365 stats->data[i].mult = 1000; \
2366 stats->data[i].verbose = 0
2369 stats->data[i].long_format = "%-20.20s"; \
2370 stats->data[i].rate_format = "%5.5s"; \
2371 stats->data[i].isvalue = 0; \
2372 stats->data[i].mult_names = "KGM"; \
2373 stats->data[i].mult = 1024; \
2374 stats->data[i].verbose = 0
2377 stats->count = s.count;
2378 for (i = 0; i < s.count; i++) {
2379 stats->data[i].value = s.data[i].value;
2380 switch (s.data[i].type) {
2381 case _DRM_STAT_LOCK:
2382 stats->data[i].long_name = "Lock";
2383 stats->data[i].rate_name = "Lock";
2386 case _DRM_STAT_OPENS:
2387 stats->data[i].long_name = "Opens";
2388 stats->data[i].rate_name = "O";
2390 stats->data[i].verbose = 1;
2392 case _DRM_STAT_CLOSES:
2393 stats->data[i].long_name = "Closes";
2394 stats->data[i].rate_name = "Lock";
2396 stats->data[i].verbose = 1;
2398 case _DRM_STAT_IOCTLS:
2399 stats->data[i].long_name = "Ioctls";
2400 stats->data[i].rate_name = "Ioc/s";
2403 case _DRM_STAT_LOCKS:
2404 stats->data[i].long_name = "Locks";
2405 stats->data[i].rate_name = "Lck/s";
2408 case _DRM_STAT_UNLOCKS:
2409 stats->data[i].long_name = "Unlocks";
2410 stats->data[i].rate_name = "Unl/s";
2414 stats->data[i].long_name = "IRQs";
2415 stats->data[i].rate_name = "IRQ/s";
2418 case _DRM_STAT_PRIMARY:
2419 stats->data[i].long_name = "Primary Bytes";
2420 stats->data[i].rate_name = "PB/s";
2423 case _DRM_STAT_SECONDARY:
2424 stats->data[i].long_name = "Secondary Bytes";
2425 stats->data[i].rate_name = "SB/s";
2429 stats->data[i].long_name = "DMA";
2430 stats->data[i].rate_name = "DMA/s";
2433 case _DRM_STAT_SPECIAL:
2434 stats->data[i].long_name = "Special DMA";
2435 stats->data[i].rate_name = "dma/s";
2438 case _DRM_STAT_MISSED:
2439 stats->data[i].long_name = "Miss";
2440 stats->data[i].rate_name = "Ms/s";
2443 case _DRM_STAT_VALUE:
2444 stats->data[i].long_name = "Value";
2445 stats->data[i].rate_name = "Value";
2448 case _DRM_STAT_BYTE:
2449 stats->data[i].long_name = "Bytes";
2450 stats->data[i].rate_name = "B/s";
2453 case _DRM_STAT_COUNT:
2455 stats->data[i].long_name = "Count";
2456 stats->data[i].rate_name = "Cnt/s";
2465 * Issue a set-version ioctl.
2467 * \param fd file descriptor.
2468 * \param drmCommandIndex command index
2469 * \param data source pointer of the data to be read and written.
2470 * \param size size of the data to be read and written.
2472 * \return zero on success, or a negative value on failure.
2475 * It issues a read-write ioctl given by
2476 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2478 int drmSetInterfaceVersion(int fd, drmSetVersion *version)
2481 drm_set_version_t sv;
2484 sv.drm_di_major = version->drm_di_major;
2485 sv.drm_di_minor = version->drm_di_minor;
2486 sv.drm_dd_major = version->drm_dd_major;
2487 sv.drm_dd_minor = version->drm_dd_minor;
2489 if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
2493 version->drm_di_major = sv.drm_di_major;
2494 version->drm_di_minor = sv.drm_di_minor;
2495 version->drm_dd_major = sv.drm_dd_major;
2496 version->drm_dd_minor = sv.drm_dd_minor;
2502 * Send a device-specific command.
2504 * \param fd file descriptor.
2505 * \param drmCommandIndex command index
2507 * \return zero on success, or a negative value on failure.
2510 * It issues a ioctl given by
2511 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2513 int drmCommandNone(int fd, unsigned long drmCommandIndex)
2515 unsigned long request;
2517 request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
2519 if (drmIoctl(fd, request, NULL)) {
2527 * Send a device-specific read command.
2529 * \param fd file descriptor.
2530 * \param drmCommandIndex command index
2531 * \param data destination pointer of the data to be read.
2532 * \param size size of the data to be read.
2534 * \return zero on success, or a negative value on failure.
2537 * It issues a read ioctl given by
2538 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2540 int drmCommandRead(int fd, unsigned long drmCommandIndex, void *data,
2543 unsigned long request;
2545 request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
2546 DRM_COMMAND_BASE + drmCommandIndex, size);
2548 if (drmIoctl(fd, request, data)) {
2556 * Send a device-specific write command.
2558 * \param fd file descriptor.
2559 * \param drmCommandIndex command index
2560 * \param data source pointer of the data to be written.
2561 * \param size size of the data to be written.
2563 * \return zero on success, or a negative value on failure.
2566 * It issues a write ioctl given by
2567 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2569 int drmCommandWrite(int fd, unsigned long drmCommandIndex, void *data,
2572 unsigned long request;
2574 request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
2575 DRM_COMMAND_BASE + drmCommandIndex, size);
2577 if (drmIoctl(fd, request, data)) {
2585 * Send a device-specific read-write command.
2587 * \param fd file descriptor.
2588 * \param drmCommandIndex command index
2589 * \param data source pointer of the data to be read and written.
2590 * \param size size of the data to be read and written.
2592 * \return zero on success, or a negative value on failure.
2595 * It issues a read-write ioctl given by
2596 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2598 int drmCommandWriteRead(int fd, unsigned long drmCommandIndex, void *data,
2601 unsigned long request;
2603 request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
2604 DRM_COMMAND_BASE + drmCommandIndex, size);
2606 if (drmIoctl(fd, request, data))
2611 #define DRM_MAX_FDS 16
2617 } connection[DRM_MAX_FDS];
2619 static int nr_fds = 0;
2621 int drmOpenOnce(void *unused,
2625 return drmOpenOnceWithType(BusID, newlyopened, DRM_NODE_PRIMARY);
2628 int drmOpenOnceWithType(const char *BusID, int *newlyopened, int type)
2633 for (i = 0; i < nr_fds; i++)
2634 if ((strcmp(BusID, connection[i].BusID) == 0) &&
2635 (connection[i].type == type)) {
2636 connection[i].refcount++;
2638 return connection[i].fd;
2641 fd = drmOpenWithType(NULL, BusID, type);
2642 if (fd < 0 || nr_fds == DRM_MAX_FDS)
2645 connection[nr_fds].BusID = strdup(BusID);
2646 connection[nr_fds].fd = fd;
2647 connection[nr_fds].refcount = 1;
2648 connection[nr_fds].type = type;
2652 fprintf(stderr, "saved connection %d for %s %d\n",
2653 nr_fds, connection[nr_fds].BusID,
2654 strcmp(BusID, connection[nr_fds].BusID));
2661 void drmCloseOnce(int fd)
2665 for (i = 0; i < nr_fds; i++) {
2666 if (fd == connection[i].fd) {
2667 if (--connection[i].refcount == 0) {
2668 drmClose(connection[i].fd);
2669 free(connection[i].BusID);
2672 connection[i] = connection[nr_fds];
2680 int drmSetMaster(int fd)
2682 return drmIoctl(fd, DRM_IOCTL_SET_MASTER, NULL);
2685 int drmDropMaster(int fd)
2687 return drmIoctl(fd, DRM_IOCTL_DROP_MASTER, NULL);
2690 char *drmGetDeviceNameFromFd(int fd)
2697 /* The whole drmOpen thing is a fiasco and we need to find a way
2698 * back to just using open(2). For now, however, lets just make
2699 * things worse with even more ad hoc directory walking code to
2700 * discover the device file name. */
2705 for (i = 0; i < DRM_MAX_MINOR; i++) {
2706 snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
2707 if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
2710 if (i == DRM_MAX_MINOR)
2713 return strdup(name);
2716 int drmGetNodeTypeFromFd(int fd)
2721 if (fstat(fd, &sbuf))
2724 maj = major(sbuf.st_rdev);
2725 min = minor(sbuf.st_rdev);
2727 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode)) {
2732 type = drmGetMinorType(min);
2738 int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags, int *prime_fd)
2740 struct drm_prime_handle args;
2745 args.handle = handle;
2747 ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
2751 *prime_fd = args.fd;
2755 int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
2757 struct drm_prime_handle args;
2762 ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
2766 *handle = args.handle;
2770 static char *drmGetMinorNameForFD(int fd, int type)
2774 struct dirent *pent, *ent;
2776 const char *name = drmGetMinorName(type);
2778 char dev_name[64], buf[64];
2787 if (fstat(fd, &sbuf))
2790 maj = major(sbuf.st_rdev);
2791 min = minor(sbuf.st_rdev);
2793 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
2796 snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
2798 sysdir = opendir(buf);
2802 name_max = fpathconf(dirfd(sysdir), _PC_NAME_MAX);
2806 pent = malloc(offsetof(struct dirent, d_name) + name_max + 1);
2810 while (readdir_r(sysdir, pent, &ent) == 0 && ent != NULL) {
2811 if (strncmp(ent->d_name, name, len) == 0) {
2812 snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
2818 return strdup(dev_name);
2827 #warning "Missing implementation of drmGetMinorNameForFD"
2832 char *drmGetPrimaryDeviceNameFromFd(int fd)
2834 return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
2837 char *drmGetRenderDeviceNameFromFd(int fd)
2839 return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
2842 static int drmParseSubsystemType(int maj, int min)
2845 char path[PATH_MAX + 1];
2846 char link[PATH_MAX + 1] = "";
2849 snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/subsystem",
2852 if (readlink(path, link, PATH_MAX) < 0)
2855 name = strrchr(link, '/');
2859 if (strncmp(name, "/pci", 4) == 0)
2864 #warning "Missing implementation of drmParseSubsystemType"
2869 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
2872 char path[PATH_MAX + 1];
2875 int domain, bus, dev, func;
2878 snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/uevent", maj, min);
2879 fd = open(path, O_RDONLY);
2883 ret = read(fd, data, sizeof(data));
2888 #define TAG "PCI_SLOT_NAME="
2889 str = strstr(data, TAG);
2893 if (sscanf(str, TAG "%04x:%02x:%02x.%1u",
2894 &domain, &bus, &dev, &func) != 4)
2898 info->domain = domain;
2905 #warning "Missing implementation of drmParsePciBusInfo"
2910 static int drmCompareBusInfo(drmDevicePtr a, drmDevicePtr b)
2912 if (a == NULL || b == NULL)
2915 if (a->bustype != b->bustype)
2918 switch (a->bustype) {
2920 return memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo));
2928 static int drmGetNodeType(const char *name)
2930 if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
2931 sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
2932 return DRM_NODE_PRIMARY;
2934 if (strncmp(name, DRM_CONTROL_MINOR_NAME,
2935 sizeof(DRM_CONTROL_MINOR_NAME ) - 1) == 0)
2936 return DRM_NODE_CONTROL;
2938 if (strncmp(name, DRM_RENDER_MINOR_NAME,
2939 sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
2940 return DRM_NODE_RENDER;
2945 static int drmGetMaxNodeName(void)
2947 return sizeof(DRM_DIR_NAME) +
2948 MAX3(sizeof(DRM_PRIMARY_MINOR_NAME),
2949 sizeof(DRM_CONTROL_MINOR_NAME),
2950 sizeof(DRM_RENDER_MINOR_NAME)) +
2951 3 /* lenght of the node number */;
2954 static int drmParsePciDeviceInfo(const char *d_name,
2955 drmPciDeviceInfoPtr device)
2958 char path[PATH_MAX + 1];
2959 unsigned char config[64];
2962 snprintf(path, PATH_MAX, "/sys/class/drm/%s/device/config", d_name);
2963 fd = open(path, O_RDONLY);
2967 ret = read(fd, config, sizeof(config));
2972 device->vendor_id = config[0] | (config[1] << 8);
2973 device->device_id = config[2] | (config[3] << 8);
2974 device->revision_id = config[8];
2975 device->subvendor_id = config[44] | (config[45] << 8);
2976 device->subdevice_id = config[46] | (config[47] << 8);
2980 #warning "Missing implementation of drmParsePciDeviceInfo"
2985 void drmFreeDevice(drmDevicePtr *device)
2994 void drmFreeDevices(drmDevicePtr devices[], int count)
2998 if (devices == NULL)
3001 for (i = 0; i < count && devices[i] != NULL; i++)
3002 drmFreeDevice(&devices[i]);
3005 static int drmProcessPciDevice(drmDevicePtr *device, const char *d_name,
3006 const char *node, int node_type,
3007 int maj, int min, bool fetch_deviceinfo)
3009 const int max_node_str = drmGetMaxNodeName();
3013 addr = *device = calloc(1, sizeof(drmDevice) +
3015 (sizeof(void *) + max_node_str)) +
3016 sizeof(drmPciBusInfo) +
3017 sizeof(drmPciDeviceInfo));
3021 (*device)->bustype = DRM_BUS_PCI;
3022 (*device)->available_nodes = 1 << node_type;
3024 addr += sizeof(drmDevice);
3025 (*device)->nodes = addr;
3027 addr += DRM_NODE_MAX * sizeof(void *);
3028 for (i = 0; i < DRM_NODE_MAX; i++) {
3029 (*device)->nodes[i] = addr;
3030 addr += max_node_str;
3032 memcpy((*device)->nodes[node_type], node, max_node_str);
3034 (*device)->businfo.pci = addr;
3036 ret = drmParsePciBusInfo(maj, min, (*device)->businfo.pci);
3040 // Fetch the device info if the user has requested it
3041 if (fetch_deviceinfo) {
3042 addr += sizeof(drmPciBusInfo);
3043 (*device)->deviceinfo.pci = addr;
3045 ret = drmParsePciDeviceInfo(d_name, (*device)->deviceinfo.pci);
3057 static void drmFoldDuplicatedDevices(drmDevicePtr local_devices[], int count)
3059 int node_type, i, j;
3061 for (i = 0; i < count; i++) {
3062 for (j = i + 1; j < count; j++) {
3063 if (drmCompareBusInfo(local_devices[i], local_devices[j]) == 0) {
3064 local_devices[i]->available_nodes |= local_devices[j]->available_nodes;
3065 node_type = log2(local_devices[j]->available_nodes);
3066 memcpy(local_devices[i]->nodes[node_type],
3067 local_devices[j]->nodes[node_type], drmGetMaxNodeName());
3068 drmFreeDevice(&local_devices[j]);
3075 * Get information about the opened drm device
3077 * \param fd file descriptor of the drm device
3078 * \param device the address of a drmDevicePtr where the information
3079 * will be allocated in stored
3081 * \return zero on success, negative error code otherwise.
3083 int drmGetDevice(int fd, drmDevicePtr *device)
3085 drmDevicePtr *local_devices;
3088 struct dirent *dent;
3090 char node[PATH_MAX + 1];
3091 int node_type, subsystem_type;
3093 int ret, i, node_count;
3096 if (fd == -1 || device == NULL)
3099 if (fstat(fd, &sbuf))
3102 maj = major(sbuf.st_rdev);
3103 min = minor(sbuf.st_rdev);
3105 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3108 subsystem_type = drmParseSubsystemType(maj, min);
3110 local_devices = calloc(max_count, sizeof(drmDevicePtr));
3111 if (local_devices == NULL)
3114 sysdir = opendir(DRM_DIR_NAME);
3121 while ((dent = readdir(sysdir))) {
3122 node_type = drmGetNodeType(dent->d_name);
3126 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, dent->d_name);
3127 if (stat(node, &sbuf))
3130 maj = major(sbuf.st_rdev);
3131 min = minor(sbuf.st_rdev);
3133 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3136 if (drmParseSubsystemType(maj, min) != subsystem_type)
3139 switch (subsystem_type) {
3141 ret = drmProcessPciDevice(&d, dent->d_name, node, node_type,
3148 fprintf(stderr, "The subsystem type is not supported yet\n");
3152 if (i >= max_count) {
3156 temp = realloc(local_devices, max_count * sizeof(drmDevicePtr));
3159 local_devices = temp;
3162 local_devices[i] = d;
3167 /* Fold nodes into a single device if they share the same bus info */
3168 drmFoldDuplicatedDevices(local_devices, node_count);
3170 *device = local_devices[0];
3171 for (i = 1; i < node_count && local_devices[i]; i++)
3172 drmFreeDevice(&local_devices[i]);
3174 free(local_devices);
3179 drmFreeDevices(local_devices, i);
3180 free(local_devices);
3188 * Get drm devices on the system
3190 * \param devices the array of devices with drmDevicePtr elements
3191 * can be NULL to get the device number first
3192 * \param max_devices the maximum number of devices for the array
3194 * \return on error - negative error code,
3195 * if devices is NULL - total number of devices available on the system,
3196 * alternatively the number of devices stored in devices[], which is
3197 * capped by the max_devices.
3199 int drmGetDevices(drmDevicePtr devices[], int max_devices)
3201 drmDevicePtr *local_devices;
3202 drmDevicePtr device;
3204 struct dirent *dent;
3206 char node[PATH_MAX + 1];
3207 int node_type, subsystem_type;
3209 int ret, i, node_count, device_count;
3212 local_devices = calloc(max_count, sizeof(drmDevicePtr));
3213 if (local_devices == NULL)
3216 sysdir = opendir(DRM_DIR_NAME);
3223 while ((dent = readdir(sysdir))) {
3224 node_type = drmGetNodeType(dent->d_name);
3228 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, dent->d_name);
3229 if (stat(node, &sbuf))
3232 maj = major(sbuf.st_rdev);
3233 min = minor(sbuf.st_rdev);
3235 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3238 subsystem_type = drmParseSubsystemType(maj, min);
3240 if (subsystem_type < 0)
3243 switch (subsystem_type) {
3245 ret = drmProcessPciDevice(&device, dent->d_name, node, node_type,
3246 maj, min, devices != NULL);
3252 fprintf(stderr, "The subsystem type is not supported yet\n");
3256 if (i >= max_count) {
3260 temp = realloc(local_devices, max_count * sizeof(drmDevicePtr));
3263 local_devices = temp;
3266 local_devices[i] = device;
3271 /* Fold nodes into a single device if they share the same bus info */
3272 drmFoldDuplicatedDevices(local_devices, node_count);
3275 for (i = 0; i < node_count && local_devices[i]; i++) {
3276 if ((devices != NULL) && (device_count < max_devices))
3277 devices[device_count] = local_devices[i];
3279 drmFreeDevice(&local_devices[i]);
3284 free(local_devices);
3286 return device_count;
3289 drmFreeDevices(local_devices, i);
3290 free(local_devices);