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.
48 #include <sys/types.h>
50 #define stat_t struct stat
51 #include <sys/ioctl.h>
55 #include <sys/mkdev.h>
57 #ifdef MAJOR_IN_SYSMACROS
58 #include <sys/sysmacros.h>
62 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
64 /* Not all systems have MAP_FAILED defined */
66 #define MAP_FAILED ((void *)-1)
70 #include "libdrm_macros.h"
72 #include "util_math.h"
75 #define DRM_PRIMARY_MINOR_NAME "drm"
76 #define DRM_CONTROL_MINOR_NAME "drmC"
77 #define DRM_RENDER_MINOR_NAME "drmR"
79 #define DRM_PRIMARY_MINOR_NAME "card"
80 #define DRM_CONTROL_MINOR_NAME "controlD"
81 #define DRM_RENDER_MINOR_NAME "renderD"
84 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
98 #endif /* __OpenBSD__ */
101 #define DRM_MAJOR 226 /* Linux */
104 #if defined(__OpenBSD__) || defined(__DragonFly__)
112 uint16_t subvendor_id;
113 uint16_t subdevice_id;
117 #define DRM_IOCTL_GET_PCIINFO DRM_IOR(0x15, struct drm_pciinfo)
120 #define DRM_MSG_VERBOSITY 3
122 #define memclear(s) memset(&s, 0, sizeof(s))
124 static drmServerInfoPtr drm_server_info;
126 drm_public void drmSetServerInfo(drmServerInfoPtr info)
128 drm_server_info = info;
132 * Output a message to stderr.
134 * \param format printf() like format string.
137 * This function is a wrapper around vfprintf().
140 static int DRM_PRINTFLIKE(1, 0)
141 drmDebugPrint(const char *format, va_list ap)
143 return vfprintf(stderr, format, ap);
147 drmMsg(const char *format, ...)
151 if (((env = getenv("LIBGL_DEBUG")) && strstr(env, "verbose")) ||
152 (drm_server_info && drm_server_info->debug_print))
154 va_start(ap, format);
155 if (drm_server_info) {
156 drm_server_info->debug_print(format,ap);
158 drmDebugPrint(format, ap);
164 static void *drmHashTable = NULL; /* Context switch callbacks */
166 drm_public void *drmGetHashTable(void)
171 drm_public void *drmMalloc(int size)
173 return calloc(1, size);
176 drm_public void drmFree(void *pt)
182 * Call ioctl, restarting if it is interrupted
185 drmIoctl(int fd, unsigned long request, void *arg)
190 ret = ioctl(fd, request, arg);
191 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
195 static unsigned long drmGetKeyFromFd(int fd)
204 drm_public drmHashEntry *drmGetEntry(int fd)
206 unsigned long key = drmGetKeyFromFd(fd);
211 drmHashTable = drmHashCreate();
213 if (drmHashLookup(drmHashTable, key, &value)) {
214 entry = drmMalloc(sizeof(*entry));
217 entry->tagTable = drmHashCreate();
218 drmHashInsert(drmHashTable, key, entry);
226 * Compare two busid strings
231 * \return 1 if matched.
234 * This function compares two bus ID strings. It understands the older
235 * PCI:b:d:f format and the newer pci:oooo:bb:dd.f format. In the format, o is
236 * domain, b is bus, d is device, f is function.
238 static int drmMatchBusID(const char *id1, const char *id2, int pci_domain_ok)
240 /* First, check if the IDs are exactly the same */
241 if (strcasecmp(id1, id2) == 0)
244 /* Try to match old/new-style PCI bus IDs. */
245 if (strncasecmp(id1, "pci", 3) == 0) {
246 unsigned int o1, b1, d1, f1;
247 unsigned int o2, b2, d2, f2;
250 ret = sscanf(id1, "pci:%04x:%02x:%02x.%u", &o1, &b1, &d1, &f1);
253 ret = sscanf(id1, "PCI:%u:%u:%u", &b1, &d1, &f1);
258 ret = sscanf(id2, "pci:%04x:%02x:%02x.%u", &o2, &b2, &d2, &f2);
261 ret = sscanf(id2, "PCI:%u:%u:%u", &b2, &d2, &f2);
266 /* If domains aren't properly supported by the kernel interface,
267 * just ignore them, which sucks less than picking a totally random
268 * card with "open by name"
273 if ((o1 != o2) || (b1 != b2) || (d1 != d2) || (f1 != f2))
282 * Handles error checking for chown call.
284 * \param path to file.
285 * \param id of the new owner.
286 * \param id of the new group.
288 * \return zero if success or -1 if failure.
291 * Checks for failure. If failure was caused by signal call chown again.
292 * If any other failure happened then it will output error message using
296 static int chown_check_return(const char *path, uid_t owner, gid_t group)
301 rv = chown(path, owner, group);
302 } while (rv != 0 && errno == EINTR);
307 drmMsg("Failed to change owner or group for file %s! %d: %s\n",
308 path, errno, strerror(errno));
314 * Open the DRM device, creating it if necessary.
316 * \param dev major and minor numbers of the device.
317 * \param minor minor number of the device.
319 * \return a file descriptor on success, or a negative value on error.
322 * Assembles the device name from \p minor and opens it, creating the device
323 * special file node with the major and minor numbers specified by \p dev and
324 * parent directory if necessary and was called by root.
326 static int drmOpenDevice(dev_t dev, int minor, int type)
329 const char *dev_name;
332 mode_t devmode = DRM_DEV_MODE, serv_mode;
335 int isroot = !geteuid();
336 uid_t user = DRM_DEV_UID;
337 gid_t group = DRM_DEV_GID;
341 case DRM_NODE_PRIMARY:
342 dev_name = DRM_DEV_NAME;
344 case DRM_NODE_CONTROL:
345 dev_name = DRM_CONTROL_DEV_NAME;
347 case DRM_NODE_RENDER:
348 dev_name = DRM_RENDER_DEV_NAME;
354 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
355 drmMsg("drmOpenDevice: node name is %s\n", buf);
357 if (drm_server_info && drm_server_info->get_perms) {
358 drm_server_info->get_perms(&serv_group, &serv_mode);
359 devmode = serv_mode ? serv_mode : DRM_DEV_MODE;
360 devmode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
364 if (stat(DRM_DIR_NAME, &st)) {
366 return DRM_ERR_NOT_ROOT;
367 mkdir(DRM_DIR_NAME, DRM_DEV_DIRMODE);
368 chown_check_return(DRM_DIR_NAME, 0, 0); /* root:root */
369 chmod(DRM_DIR_NAME, DRM_DEV_DIRMODE);
372 /* Check if the device node exists and create it if necessary. */
373 if (stat(buf, &st)) {
375 return DRM_ERR_NOT_ROOT;
377 mknod(buf, S_IFCHR | devmode, dev);
380 if (drm_server_info && drm_server_info->get_perms) {
381 group = ((int)serv_group >= 0) ? serv_group : DRM_DEV_GID;
382 chown_check_return(buf, user, group);
386 /* if we modprobed then wait for udev */
390 if (stat(DRM_DIR_NAME, &st)) {
394 if (udev_count == 50)
399 if (stat(buf, &st)) {
403 if (udev_count == 50)
410 fd = open(buf, O_RDWR | O_CLOEXEC, 0);
411 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
412 fd, fd < 0 ? strerror(errno) : "OK");
417 /* Check if the device node is not what we expect it to be, and recreate it
418 * and try again if so.
420 if (st.st_rdev != dev) {
422 return DRM_ERR_NOT_ROOT;
424 mknod(buf, S_IFCHR | devmode, dev);
425 if (drm_server_info && drm_server_info->get_perms) {
426 chown_check_return(buf, user, group);
430 fd = open(buf, O_RDWR | O_CLOEXEC, 0);
431 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
432 fd, fd < 0 ? strerror(errno) : "OK");
436 drmMsg("drmOpenDevice: Open failed\n");
444 * Open the DRM device
446 * \param minor device minor number.
447 * \param create allow to create the device if set.
449 * \return a file descriptor on success, or a negative value on error.
452 * Calls drmOpenDevice() if \p create is set, otherwise assembles the device
453 * name from \p minor and opens it.
455 static int drmOpenMinor(int minor, int create, int type)
459 const char *dev_name;
462 return drmOpenDevice(makedev(DRM_MAJOR, minor), minor, type);
465 case DRM_NODE_PRIMARY:
466 dev_name = DRM_DEV_NAME;
468 case DRM_NODE_CONTROL:
469 dev_name = DRM_CONTROL_DEV_NAME;
471 case DRM_NODE_RENDER:
472 dev_name = DRM_RENDER_DEV_NAME;
478 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
479 if ((fd = open(buf, O_RDWR | O_CLOEXEC, 0)) >= 0)
486 * Determine whether the DRM kernel driver has been loaded.
488 * \return 1 if the DRM driver is loaded, 0 otherwise.
491 * Determine the presence of the kernel driver by attempting to open the 0
492 * minor and get version information. For backward compatibility with older
493 * Linux implementations, /proc/dri is also checked.
495 drm_public int drmAvailable(void)
497 drmVersionPtr version;
501 if ((fd = drmOpenMinor(0, 1, DRM_NODE_PRIMARY)) < 0) {
503 /* Try proc for backward Linux compatibility */
504 if (!access("/proc/dri/0", R_OK))
510 if ((version = drmGetVersion(fd))) {
512 drmFreeVersion(version);
519 static int drmGetMinorBase(int type)
522 case DRM_NODE_PRIMARY:
524 case DRM_NODE_CONTROL:
526 case DRM_NODE_RENDER:
533 static int drmGetMinorType(int minor)
535 int type = minor >> 6;
541 case DRM_NODE_PRIMARY:
542 case DRM_NODE_CONTROL:
543 case DRM_NODE_RENDER:
550 static const char *drmGetMinorName(int type)
553 case DRM_NODE_PRIMARY:
554 return DRM_PRIMARY_MINOR_NAME;
555 case DRM_NODE_CONTROL:
556 return DRM_CONTROL_MINOR_NAME;
557 case DRM_NODE_RENDER:
558 return DRM_RENDER_MINOR_NAME;
565 * Open the device by bus ID.
567 * \param busid bus ID.
568 * \param type device node type.
570 * \return a file descriptor on success, or a negative value on error.
573 * This function attempts to open every possible minor (up to DRM_MAX_MINOR),
574 * comparing the device bus ID with the one supplied.
576 * \sa drmOpenMinor() and drmGetBusid().
578 static int drmOpenByBusid(const char *busid, int type)
580 int i, pci_domain_ok = 1;
584 int base = drmGetMinorBase(type);
589 drmMsg("drmOpenByBusid: Searching for BusID %s\n", busid);
590 for (i = base; i < base + DRM_MAX_MINOR; i++) {
591 fd = drmOpenMinor(i, 1, type);
592 drmMsg("drmOpenByBusid: drmOpenMinor returns %d\n", fd);
594 /* We need to try for 1.4 first for proper PCI domain support
595 * and if that fails, we know the kernel is busted
599 sv.drm_dd_major = -1; /* Don't care */
600 sv.drm_dd_minor = -1; /* Don't care */
601 if (drmSetInterfaceVersion(fd, &sv)) {
607 sv.drm_dd_major = -1; /* Don't care */
608 sv.drm_dd_minor = -1; /* Don't care */
609 drmMsg("drmOpenByBusid: Interface 1.4 failed, trying 1.1\n");
610 drmSetInterfaceVersion(fd, &sv);
612 buf = drmGetBusid(fd);
613 drmMsg("drmOpenByBusid: drmGetBusid reports %s\n", buf);
614 if (buf && drmMatchBusID(buf, busid, pci_domain_ok)) {
628 * Open the device by name.
630 * \param name driver name.
631 * \param type the device node type.
633 * \return a file descriptor on success, or a negative value on error.
636 * This function opens the first minor number that matches the driver name and
637 * isn't already in use. If it's in use it then it will already have a bus ID
640 * \sa drmOpenMinor(), drmGetVersion() and drmGetBusid().
642 static int drmOpenByName(const char *name, int type)
646 drmVersionPtr version;
648 int base = drmGetMinorBase(type);
654 * Open the first minor number that matches the driver name and isn't
655 * already in use. If it's in use it will have a busid assigned already.
657 for (i = base; i < base + DRM_MAX_MINOR; i++) {
658 if ((fd = drmOpenMinor(i, 1, type)) >= 0) {
659 if ((version = drmGetVersion(fd))) {
660 if (!strcmp(version->name, name)) {
661 drmFreeVersion(version);
662 id = drmGetBusid(fd);
663 drmMsg("drmGetBusid returned '%s'\n", id ? id : "NULL");
672 drmFreeVersion(version);
680 /* Backward-compatibility /proc support */
681 for (i = 0; i < 8; i++) {
682 char proc_name[64], buf[512];
683 char *driver, *pt, *devstring;
686 sprintf(proc_name, "/proc/dri/%d/name", i);
687 if ((fd = open(proc_name, 0, 0)) >= 0) {
688 retcode = read(fd, buf, sizeof(buf)-1);
691 buf[retcode-1] = '\0';
692 for (driver = pt = buf; *pt && *pt != ' '; ++pt)
694 if (*pt) { /* Device is next */
696 if (!strcmp(driver, name)) { /* Match */
697 for (devstring = ++pt; *pt && *pt != ' '; ++pt)
699 if (*pt) { /* Found busid */
700 return drmOpenByBusid(++pt, type);
701 } else { /* No busid */
702 return drmOpenDevice(strtol(devstring, NULL, 0),i, type);
716 * Open the DRM device.
718 * Looks up the specified name and bus ID, and opens the device found. The
719 * entry in /dev/dri is created if necessary and if called by root.
721 * \param name driver name. Not referenced if bus ID is supplied.
722 * \param busid bus ID. Zero if not known.
724 * \return a file descriptor on success, or a negative value on error.
727 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
730 drm_public int drmOpen(const char *name, const char *busid)
732 return drmOpenWithType(name, busid, DRM_NODE_PRIMARY);
736 * Open the DRM device with specified type.
738 * Looks up the specified name and bus ID, and opens the device found. The
739 * entry in /dev/dri is created if necessary and if called by root.
741 * \param name driver name. Not referenced if bus ID is supplied.
742 * \param busid bus ID. Zero if not known.
743 * \param type the device node type to open, PRIMARY, CONTROL or RENDER
745 * \return a file descriptor on success, or a negative value on error.
748 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
751 drm_public int drmOpenWithType(const char *name, const char *busid, int type)
753 if (name != NULL && drm_server_info &&
754 drm_server_info->load_module && !drmAvailable()) {
755 /* try to load the kernel module */
756 if (!drm_server_info->load_module(name)) {
757 drmMsg("[drm] failed to load kernel module \"%s\"\n", name);
763 int fd = drmOpenByBusid(busid, type);
769 return drmOpenByName(name, type);
774 drm_public int drmOpenControl(int minor)
776 return drmOpenMinor(minor, 0, DRM_NODE_CONTROL);
779 drm_public int drmOpenRender(int minor)
781 return drmOpenMinor(minor, 0, DRM_NODE_RENDER);
785 * Free the version information returned by drmGetVersion().
787 * \param v pointer to the version information.
790 * It frees the memory pointed by \p %v as well as all the non-null strings
793 drm_public void drmFreeVersion(drmVersionPtr v)
805 * Free the non-public version information returned by the kernel.
807 * \param v pointer to the version information.
810 * Used by drmGetVersion() to free the memory pointed by \p %v as well as all
811 * the non-null strings pointers in it.
813 static void drmFreeKernelVersion(drm_version_t *v)
825 * Copy version information.
827 * \param d destination pointer.
828 * \param s source pointer.
831 * Used by drmGetVersion() to translate the information returned by the ioctl
832 * interface in a private structure into the public structure counterpart.
834 static void drmCopyVersion(drmVersionPtr d, const drm_version_t *s)
836 d->version_major = s->version_major;
837 d->version_minor = s->version_minor;
838 d->version_patchlevel = s->version_patchlevel;
839 d->name_len = s->name_len;
840 d->name = strdup(s->name);
841 d->date_len = s->date_len;
842 d->date = strdup(s->date);
843 d->desc_len = s->desc_len;
844 d->desc = strdup(s->desc);
849 * Query the driver version information.
851 * \param fd file descriptor.
853 * \return pointer to a drmVersion structure which should be freed with
856 * \note Similar information is available via /proc/dri.
859 * It gets the version information via successive DRM_IOCTL_VERSION ioctls,
860 * first with zeros to get the string lengths, and then the actually strings.
861 * It also null-terminates them since they might not be already.
863 drm_public drmVersionPtr drmGetVersion(int fd)
865 drmVersionPtr retval;
866 drm_version_t *version = drmMalloc(sizeof(*version));
868 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
869 drmFreeKernelVersion(version);
873 if (version->name_len)
874 version->name = drmMalloc(version->name_len + 1);
875 if (version->date_len)
876 version->date = drmMalloc(version->date_len + 1);
877 if (version->desc_len)
878 version->desc = drmMalloc(version->desc_len + 1);
880 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
881 drmMsg("DRM_IOCTL_VERSION: %s\n", strerror(errno));
882 drmFreeKernelVersion(version);
886 /* The results might not be null-terminated strings, so terminate them. */
887 if (version->name_len) version->name[version->name_len] = '\0';
888 if (version->date_len) version->date[version->date_len] = '\0';
889 if (version->desc_len) version->desc[version->desc_len] = '\0';
891 retval = drmMalloc(sizeof(*retval));
892 drmCopyVersion(retval, version);
893 drmFreeKernelVersion(version);
899 * Get version information for the DRM user space library.
901 * This version number is driver independent.
903 * \param fd file descriptor.
905 * \return version information.
908 * This function allocates and fills a drm_version structure with a hard coded
911 drm_public drmVersionPtr drmGetLibVersion(int fd)
913 drm_version_t *version = drmMalloc(sizeof(*version));
916 * NOTE THIS MUST NOT GO ABOVE VERSION 1.X due to drivers needing it
917 * revision 1.0.x = original DRM interface with no drmGetLibVersion
918 * entry point and many drm<Device> extensions
919 * revision 1.1.x = added drmCommand entry points for device extensions
920 * added drmGetLibVersion to identify libdrm.a version
921 * revision 1.2.x = added drmSetInterfaceVersion
922 * modified drmOpen to handle both busid and name
923 * revision 1.3.x = added server + memory manager
925 version->version_major = 1;
926 version->version_minor = 3;
927 version->version_patchlevel = 0;
929 return (drmVersionPtr)version;
932 drm_public int drmGetCap(int fd, uint64_t capability, uint64_t *value)
934 struct drm_get_cap cap;
938 cap.capability = capability;
940 ret = drmIoctl(fd, DRM_IOCTL_GET_CAP, &cap);
948 drm_public int drmSetClientCap(int fd, uint64_t capability, uint64_t value)
950 struct drm_set_client_cap cap;
953 cap.capability = capability;
956 return drmIoctl(fd, DRM_IOCTL_SET_CLIENT_CAP, &cap);
960 * Free the bus ID information.
962 * \param busid bus ID information string as given by drmGetBusid().
965 * This function is just frees the memory pointed by \p busid.
967 drm_public void drmFreeBusid(const char *busid)
969 drmFree((void *)busid);
974 * Get the bus ID of the device.
976 * \param fd file descriptor.
978 * \return bus ID string.
981 * This function gets the bus ID via successive DRM_IOCTL_GET_UNIQUE ioctls to
982 * get the string length and data, passing the arguments in a drm_unique
985 drm_public char *drmGetBusid(int fd)
991 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
993 u.unique = drmMalloc(u.unique_len + 1);
994 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u)) {
998 u.unique[u.unique_len] = '\0';
1005 * Set the bus ID of the device.
1007 * \param fd file descriptor.
1008 * \param busid bus ID string.
1010 * \return zero on success, negative on failure.
1013 * This function is a wrapper around the DRM_IOCTL_SET_UNIQUE ioctl, passing
1014 * the arguments in a drm_unique structure.
1016 drm_public int drmSetBusid(int fd, const char *busid)
1021 u.unique = (char *)busid;
1022 u.unique_len = strlen(busid);
1024 if (drmIoctl(fd, DRM_IOCTL_SET_UNIQUE, &u)) {
1030 drm_public int drmGetMagic(int fd, drm_magic_t * magic)
1037 if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
1039 *magic = auth.magic;
1043 drm_public int drmAuthMagic(int fd, drm_magic_t magic)
1049 if (drmIoctl(fd, DRM_IOCTL_AUTH_MAGIC, &auth))
1055 * Specifies a range of memory that is available for mapping by a
1058 * \param fd file descriptor.
1059 * \param offset usually the physical address. The actual meaning depends of
1060 * the \p type parameter. See below.
1061 * \param size of the memory in bytes.
1062 * \param type type of the memory to be mapped.
1063 * \param flags combination of several flags to modify the function actions.
1064 * \param handle will be set to a value that may be used as the offset
1065 * parameter for mmap().
1067 * \return zero on success or a negative value on error.
1069 * \par Mapping the frame buffer
1070 * For the frame buffer
1071 * - \p offset will be the physical address of the start of the frame buffer,
1072 * - \p size will be the size of the frame buffer in bytes, and
1073 * - \p type will be DRM_FRAME_BUFFER.
1076 * The area mapped will be uncached. If MTRR support is available in the
1077 * kernel, the frame buffer area will be set to write combining.
1079 * \par Mapping the MMIO register area
1080 * For the MMIO register area,
1081 * - \p offset will be the physical address of the start of the register area,
1082 * - \p size will be the size of the register area bytes, and
1083 * - \p type will be DRM_REGISTERS.
1085 * The area mapped will be uncached.
1087 * \par Mapping the SAREA
1089 * - \p offset will be ignored and should be set to zero,
1090 * - \p size will be the desired size of the SAREA in bytes,
1091 * - \p type will be DRM_SHM.
1094 * A shared memory area of the requested size will be created and locked in
1095 * kernel memory. This area may be mapped into client-space by using the handle
1098 * \note May only be called by root.
1101 * This function is a wrapper around the DRM_IOCTL_ADD_MAP ioctl, passing
1102 * the arguments in a drm_map structure.
1104 drm_public int drmAddMap(int fd, drm_handle_t offset, drmSize size, drmMapType type,
1105 drmMapFlags flags, drm_handle_t *handle)
1110 map.offset = offset;
1114 if (drmIoctl(fd, DRM_IOCTL_ADD_MAP, &map))
1117 *handle = (drm_handle_t)(uintptr_t)map.handle;
1121 drm_public int drmRmMap(int fd, drm_handle_t handle)
1126 map.handle = (void *)(uintptr_t)handle;
1128 if(drmIoctl(fd, DRM_IOCTL_RM_MAP, &map))
1134 * Make buffers available for DMA transfers.
1136 * \param fd file descriptor.
1137 * \param count number of buffers.
1138 * \param size size of each buffer.
1139 * \param flags buffer allocation flags.
1140 * \param agp_offset offset in the AGP aperture
1142 * \return number of buffers allocated, negative on error.
1145 * This function is a wrapper around DRM_IOCTL_ADD_BUFS ioctl.
1149 drm_public int drmAddBufs(int fd, int count, int size, drmBufDescFlags flags,
1152 drm_buf_desc_t request;
1155 request.count = count;
1156 request.size = size;
1157 request.flags = flags;
1158 request.agp_start = agp_offset;
1160 if (drmIoctl(fd, DRM_IOCTL_ADD_BUFS, &request))
1162 return request.count;
1165 drm_public int drmMarkBufs(int fd, double low, double high)
1167 drm_buf_info_t info;
1172 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1178 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1181 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1182 int retval = -errno;
1187 for (i = 0; i < info.count; i++) {
1188 info.list[i].low_mark = low * info.list[i].count;
1189 info.list[i].high_mark = high * info.list[i].count;
1190 if (drmIoctl(fd, DRM_IOCTL_MARK_BUFS, &info.list[i])) {
1191 int retval = -errno;
1204 * \param fd file descriptor.
1205 * \param count number of buffers to free.
1206 * \param list list of buffers to be freed.
1208 * \return zero on success, or a negative value on failure.
1210 * \note This function is primarily used for debugging.
1213 * This function is a wrapper around the DRM_IOCTL_FREE_BUFS ioctl, passing
1214 * the arguments in a drm_buf_free structure.
1216 drm_public int drmFreeBufs(int fd, int count, int *list)
1218 drm_buf_free_t request;
1221 request.count = count;
1222 request.list = list;
1223 if (drmIoctl(fd, DRM_IOCTL_FREE_BUFS, &request))
1232 * \param fd file descriptor.
1235 * This function closes the file descriptor.
1237 drm_public int drmClose(int fd)
1239 unsigned long key = drmGetKeyFromFd(fd);
1240 drmHashEntry *entry = drmGetEntry(fd);
1242 drmHashDestroy(entry->tagTable);
1245 entry->tagTable = NULL;
1247 drmHashDelete(drmHashTable, key);
1255 * Map a region of memory.
1257 * \param fd file descriptor.
1258 * \param handle handle returned by drmAddMap().
1259 * \param size size in bytes. Must match the size used by drmAddMap().
1260 * \param address will contain the user-space virtual address where the mapping
1263 * \return zero on success, or a negative value on failure.
1266 * This function is a wrapper for mmap().
1268 drm_public int drmMap(int fd, drm_handle_t handle, drmSize size,
1269 drmAddressPtr address)
1271 static unsigned long pagesize_mask = 0;
1277 pagesize_mask = getpagesize() - 1;
1279 size = (size + pagesize_mask) & ~pagesize_mask;
1281 *address = drm_mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1282 if (*address == MAP_FAILED)
1289 * Unmap mappings obtained with drmMap().
1291 * \param address address as given by drmMap().
1292 * \param size size in bytes. Must match the size used by drmMap().
1294 * \return zero on success, or a negative value on failure.
1297 * This function is a wrapper for munmap().
1299 drm_public int drmUnmap(drmAddress address, drmSize size)
1301 return drm_munmap(address, size);
1304 drm_public drmBufInfoPtr drmGetBufInfo(int fd)
1306 drm_buf_info_t info;
1307 drmBufInfoPtr retval;
1312 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1316 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1319 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1324 retval = drmMalloc(sizeof(*retval));
1325 retval->count = info.count;
1326 retval->list = drmMalloc(info.count * sizeof(*retval->list));
1327 for (i = 0; i < info.count; i++) {
1328 retval->list[i].count = info.list[i].count;
1329 retval->list[i].size = info.list[i].size;
1330 retval->list[i].low_mark = info.list[i].low_mark;
1331 retval->list[i].high_mark = info.list[i].high_mark;
1340 * Map all DMA buffers into client-virtual space.
1342 * \param fd file descriptor.
1344 * \return a pointer to a ::drmBufMap structure.
1346 * \note The client may not use these buffers until obtaining buffer indices
1350 * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1351 * information about the buffers in a drm_buf_map structure into the
1352 * client-visible data structures.
1354 drm_public drmBufMapPtr drmMapBufs(int fd)
1357 drmBufMapPtr retval;
1361 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1367 if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1370 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1375 retval = drmMalloc(sizeof(*retval));
1376 retval->count = bufs.count;
1377 retval->list = drmMalloc(bufs.count * sizeof(*retval->list));
1378 for (i = 0; i < bufs.count; i++) {
1379 retval->list[i].idx = bufs.list[i].idx;
1380 retval->list[i].total = bufs.list[i].total;
1381 retval->list[i].used = 0;
1382 retval->list[i].address = bufs.list[i].address;
1391 * Unmap buffers allocated with drmMapBufs().
1393 * \return zero on success, or negative value on failure.
1396 * Calls munmap() for every buffer stored in \p bufs and frees the
1397 * memory allocated by drmMapBufs().
1399 drm_public int drmUnmapBufs(drmBufMapPtr bufs)
1403 for (i = 0; i < bufs->count; i++) {
1404 drm_munmap(bufs->list[i].address, bufs->list[i].total);
1407 drmFree(bufs->list);
1413 #define DRM_DMA_RETRY 16
1416 * Reserve DMA buffers.
1418 * \param fd file descriptor.
1421 * \return zero on success, or a negative value on failure.
1424 * Assemble the arguments into a drm_dma structure and keeps issuing the
1425 * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1427 drm_public int drmDMA(int fd, drmDMAReqPtr request)
1432 dma.context = request->context;
1433 dma.send_count = request->send_count;
1434 dma.send_indices = request->send_list;
1435 dma.send_sizes = request->send_sizes;
1436 dma.flags = request->flags;
1437 dma.request_count = request->request_count;
1438 dma.request_size = request->request_size;
1439 dma.request_indices = request->request_list;
1440 dma.request_sizes = request->request_sizes;
1441 dma.granted_count = 0;
1444 ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1445 } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1448 request->granted_count = dma.granted_count;
1457 * Obtain heavyweight hardware lock.
1459 * \param fd file descriptor.
1460 * \param context context.
1461 * \param flags flags that determine the state of the hardware when the function
1464 * \return always zero.
1467 * This function translates the arguments into a drm_lock structure and issue
1468 * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1470 drm_public int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
1475 lock.context = context;
1477 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
1478 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
1479 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
1480 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
1481 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
1482 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
1484 while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
1490 * Release the hardware lock.
1492 * \param fd file descriptor.
1493 * \param context context.
1495 * \return zero on success, or a negative value on failure.
1498 * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
1499 * argument in a drm_lock structure.
1501 drm_public int drmUnlock(int fd, drm_context_t context)
1506 lock.context = context;
1507 return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
1510 drm_public drm_context_t *drmGetReservedContextList(int fd, int *count)
1514 drm_context_t * retval;
1518 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1524 if (!(list = drmMalloc(res.count * sizeof(*list))))
1526 if (!(retval = drmMalloc(res.count * sizeof(*retval))))
1529 res.contexts = list;
1530 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1531 goto err_free_context;
1533 for (i = 0; i < res.count; i++)
1534 retval[i] = list[i].handle;
1547 drm_public void drmFreeReservedContextList(drm_context_t *pt)
1555 * Used by the X server during GLXContext initialization. This causes
1556 * per-context kernel-level resources to be allocated.
1558 * \param fd file descriptor.
1559 * \param handle is set on success. To be used by the client when requesting DMA
1560 * dispatch with drmDMA().
1562 * \return zero on success, or a negative value on failure.
1564 * \note May only be called by root.
1567 * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
1568 * argument in a drm_ctx structure.
1570 drm_public int drmCreateContext(int fd, drm_context_t *handle)
1575 if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
1577 *handle = ctx.handle;
1581 drm_public int drmSwitchToContext(int fd, drm_context_t context)
1586 ctx.handle = context;
1587 if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
1592 drm_public int drmSetContextFlags(int fd, drm_context_t context,
1593 drm_context_tFlags flags)
1598 * Context preserving means that no context switches are done between DMA
1599 * buffers from one context and the next. This is suitable for use in the
1600 * X server (which promises to maintain hardware context), or in the
1601 * client-side library when buffers are swapped on behalf of two threads.
1604 ctx.handle = context;
1605 if (flags & DRM_CONTEXT_PRESERVED)
1606 ctx.flags |= _DRM_CONTEXT_PRESERVED;
1607 if (flags & DRM_CONTEXT_2DONLY)
1608 ctx.flags |= _DRM_CONTEXT_2DONLY;
1609 if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
1614 drm_public int drmGetContextFlags(int fd, drm_context_t context,
1615 drm_context_tFlagsPtr flags)
1620 ctx.handle = context;
1621 if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
1624 if (ctx.flags & _DRM_CONTEXT_PRESERVED)
1625 *flags |= DRM_CONTEXT_PRESERVED;
1626 if (ctx.flags & _DRM_CONTEXT_2DONLY)
1627 *flags |= DRM_CONTEXT_2DONLY;
1634 * Free any kernel-level resources allocated with drmCreateContext() associated
1637 * \param fd file descriptor.
1638 * \param handle handle given by drmCreateContext().
1640 * \return zero on success, or a negative value on failure.
1642 * \note May only be called by root.
1645 * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
1646 * argument in a drm_ctx structure.
1648 drm_public int drmDestroyContext(int fd, drm_context_t handle)
1653 ctx.handle = handle;
1654 if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
1659 drm_public int drmCreateDrawable(int fd, drm_drawable_t *handle)
1664 if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
1666 *handle = draw.handle;
1670 drm_public int drmDestroyDrawable(int fd, drm_drawable_t handle)
1675 draw.handle = handle;
1676 if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
1681 drm_public int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
1682 drm_drawable_info_type_t type,
1683 unsigned int num, void *data)
1685 drm_update_draw_t update;
1688 update.handle = handle;
1691 update.data = (unsigned long long)(unsigned long)data;
1693 if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
1699 drm_public int drmCrtcGetSequence(int fd, uint32_t crtcId, uint64_t *sequence,
1702 struct drm_crtc_get_sequence get_seq;
1706 get_seq.crtc_id = crtcId;
1707 ret = drmIoctl(fd, DRM_IOCTL_CRTC_GET_SEQUENCE, &get_seq);
1712 *sequence = get_seq.sequence;
1714 *ns = get_seq.sequence_ns;
1718 drm_public int drmCrtcQueueSequence(int fd, uint32_t crtcId, uint32_t flags,
1720 uint64_t *sequence_queued,
1723 struct drm_crtc_queue_sequence queue_seq;
1726 memclear(queue_seq);
1727 queue_seq.crtc_id = crtcId;
1728 queue_seq.flags = flags;
1729 queue_seq.sequence = sequence;
1730 queue_seq.user_data = user_data;
1732 ret = drmIoctl(fd, DRM_IOCTL_CRTC_QUEUE_SEQUENCE, &queue_seq);
1733 if (ret == 0 && sequence_queued)
1734 *sequence_queued = queue_seq.sequence;
1740 * Acquire the AGP device.
1742 * Must be called before any of the other AGP related calls.
1744 * \param fd file descriptor.
1746 * \return zero on success, or a negative value on failure.
1749 * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
1751 drm_public int drmAgpAcquire(int fd)
1753 if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
1760 * Release the AGP device.
1762 * \param fd file descriptor.
1764 * \return zero on success, or a negative value on failure.
1767 * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
1769 drm_public int drmAgpRelease(int fd)
1771 if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
1780 * \param fd file descriptor.
1781 * \param mode AGP mode.
1783 * \return zero on success, or a negative value on failure.
1786 * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
1787 * argument in a drm_agp_mode structure.
1789 drm_public int drmAgpEnable(int fd, unsigned long mode)
1795 if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
1802 * Allocate a chunk of AGP memory.
1804 * \param fd file descriptor.
1805 * \param size requested memory size in bytes. Will be rounded to page boundary.
1806 * \param type type of memory to allocate.
1807 * \param address if not zero, will be set to the physical address of the
1809 * \param handle on success will be set to a handle of the allocated memory.
1811 * \return zero on success, or a negative value on failure.
1814 * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
1815 * arguments in a drm_agp_buffer structure.
1817 drm_public int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
1818 unsigned long *address, drm_handle_t *handle)
1823 *handle = DRM_AGP_NO_HANDLE;
1826 if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
1829 *address = b.physical;
1836 * Free a chunk of AGP memory.
1838 * \param fd file descriptor.
1839 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1841 * \return zero on success, or a negative value on failure.
1844 * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
1845 * argument in a drm_agp_buffer structure.
1847 drm_public int drmAgpFree(int fd, drm_handle_t handle)
1853 if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
1860 * Bind a chunk of AGP memory.
1862 * \param fd file descriptor.
1863 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1864 * \param offset offset in bytes. It will round to page boundary.
1866 * \return zero on success, or a negative value on failure.
1869 * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
1870 * argument in a drm_agp_binding structure.
1872 drm_public int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
1874 drm_agp_binding_t b;
1879 if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
1886 * Unbind a chunk of AGP memory.
1888 * \param fd file descriptor.
1889 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1891 * \return zero on success, or a negative value on failure.
1894 * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
1895 * the argument in a drm_agp_binding structure.
1897 drm_public int drmAgpUnbind(int fd, drm_handle_t handle)
1899 drm_agp_binding_t b;
1903 if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
1910 * Get AGP driver major version number.
1912 * \param fd file descriptor.
1914 * \return major version number on success, or a negative value on failure..
1917 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1918 * necessary information in a drm_agp_info structure.
1920 drm_public int drmAgpVersionMajor(int fd)
1926 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1928 return i.agp_version_major;
1933 * Get AGP driver minor version number.
1935 * \param fd file descriptor.
1937 * \return minor version number on success, or a negative value on failure.
1940 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1941 * necessary information in a drm_agp_info structure.
1943 drm_public int drmAgpVersionMinor(int fd)
1949 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1951 return i.agp_version_minor;
1958 * \param fd file descriptor.
1960 * \return mode on success, or zero on failure.
1963 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1964 * necessary information in a drm_agp_info structure.
1966 drm_public unsigned long drmAgpGetMode(int fd)
1972 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1979 * Get AGP aperture base.
1981 * \param fd file descriptor.
1983 * \return aperture base on success, zero on failure.
1986 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1987 * necessary information in a drm_agp_info structure.
1989 drm_public unsigned long drmAgpBase(int fd)
1995 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1997 return i.aperture_base;
2002 * Get AGP aperture size.
2004 * \param fd file descriptor.
2006 * \return aperture size on success, zero on failure.
2009 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2010 * necessary information in a drm_agp_info structure.
2012 drm_public unsigned long drmAgpSize(int fd)
2018 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2020 return i.aperture_size;
2025 * Get used AGP memory.
2027 * \param fd file descriptor.
2029 * \return memory used on success, or zero on failure.
2032 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2033 * necessary information in a drm_agp_info structure.
2035 drm_public unsigned long drmAgpMemoryUsed(int fd)
2041 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2043 return i.memory_used;
2048 * Get available AGP memory.
2050 * \param fd file descriptor.
2052 * \return memory available on success, or zero on failure.
2055 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2056 * necessary information in a drm_agp_info structure.
2058 drm_public unsigned long drmAgpMemoryAvail(int fd)
2064 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2066 return i.memory_allowed;
2071 * Get hardware vendor ID.
2073 * \param fd file descriptor.
2075 * \return vendor ID on success, or zero on failure.
2078 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2079 * necessary information in a drm_agp_info structure.
2081 drm_public unsigned int drmAgpVendorId(int fd)
2087 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2094 * Get hardware device ID.
2096 * \param fd file descriptor.
2098 * \return zero on success, or zero on failure.
2101 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2102 * necessary information in a drm_agp_info structure.
2104 drm_public unsigned int drmAgpDeviceId(int fd)
2110 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2115 drm_public int drmScatterGatherAlloc(int fd, unsigned long size,
2116 drm_handle_t *handle)
2118 drm_scatter_gather_t sg;
2124 if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
2126 *handle = sg.handle;
2130 drm_public int drmScatterGatherFree(int fd, drm_handle_t handle)
2132 drm_scatter_gather_t sg;
2136 if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
2144 * \param fd file descriptor.
2145 * \param vbl pointer to a drmVBlank structure.
2147 * \return zero on success, or a negative value on failure.
2150 * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
2152 drm_public int drmWaitVBlank(int fd, drmVBlankPtr vbl)
2154 struct timespec timeout, cur;
2157 ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2159 fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
2165 ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
2166 vbl->request.type &= ~DRM_VBLANK_RELATIVE;
2167 if (ret && errno == EINTR) {
2168 clock_gettime(CLOCK_MONOTONIC, &cur);
2169 /* Timeout after 1s */
2170 if (cur.tv_sec > timeout.tv_sec + 1 ||
2171 (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
2178 } while (ret && errno == EINTR);
2184 drm_public int drmError(int err, const char *label)
2187 case DRM_ERR_NO_DEVICE:
2188 fprintf(stderr, "%s: no device\n", label);
2190 case DRM_ERR_NO_ACCESS:
2191 fprintf(stderr, "%s: no access\n", label);
2193 case DRM_ERR_NOT_ROOT:
2194 fprintf(stderr, "%s: not root\n", label);
2196 case DRM_ERR_INVALID:
2197 fprintf(stderr, "%s: invalid args\n", label);
2202 fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2210 * Install IRQ handler.
2212 * \param fd file descriptor.
2213 * \param irq IRQ number.
2215 * \return zero on success, or a negative value on failure.
2218 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2219 * argument in a drm_control structure.
2221 drm_public int drmCtlInstHandler(int fd, int irq)
2226 ctl.func = DRM_INST_HANDLER;
2228 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2235 * Uninstall IRQ handler.
2237 * \param fd file descriptor.
2239 * \return zero on success, or a negative value on failure.
2242 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2243 * argument in a drm_control structure.
2245 drm_public int drmCtlUninstHandler(int fd)
2250 ctl.func = DRM_UNINST_HANDLER;
2252 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2257 drm_public int drmFinish(int fd, int context, drmLockFlags flags)
2262 lock.context = context;
2263 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
2264 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
2265 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
2266 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
2267 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2268 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2269 if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2275 * Get IRQ from bus ID.
2277 * \param fd file descriptor.
2278 * \param busnum bus number.
2279 * \param devnum device number.
2280 * \param funcnum function number.
2282 * \return IRQ number on success, or a negative value on failure.
2285 * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2286 * arguments in a drm_irq_busid structure.
2288 drm_public int drmGetInterruptFromBusID(int fd, int busnum, int devnum,
2296 p.funcnum = funcnum;
2297 if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2302 drm_public int drmAddContextTag(int fd, drm_context_t context, void *tag)
2304 drmHashEntry *entry = drmGetEntry(fd);
2306 if (drmHashInsert(entry->tagTable, context, tag)) {
2307 drmHashDelete(entry->tagTable, context);
2308 drmHashInsert(entry->tagTable, context, tag);
2313 drm_public int drmDelContextTag(int fd, drm_context_t context)
2315 drmHashEntry *entry = drmGetEntry(fd);
2317 return drmHashDelete(entry->tagTable, context);
2320 drm_public void *drmGetContextTag(int fd, drm_context_t context)
2322 drmHashEntry *entry = drmGetEntry(fd);
2325 if (drmHashLookup(entry->tagTable, context, &value))
2331 drm_public int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2332 drm_handle_t handle)
2334 drm_ctx_priv_map_t map;
2337 map.ctx_id = ctx_id;
2338 map.handle = (void *)(uintptr_t)handle;
2340 if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2345 drm_public int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2346 drm_handle_t *handle)
2348 drm_ctx_priv_map_t map;
2351 map.ctx_id = ctx_id;
2353 if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2356 *handle = (drm_handle_t)(uintptr_t)map.handle;
2361 drm_public int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2362 drmMapType *type, drmMapFlags *flags,
2363 drm_handle_t *handle, int *mtrr)
2369 if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2371 *offset = map.offset;
2375 *handle = (unsigned long)map.handle;
2380 drm_public int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2381 unsigned long *magic, unsigned long *iocs)
2383 drm_client_t client;
2387 if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2389 *auth = client.auth;
2392 *magic = client.magic;
2393 *iocs = client.iocs;
2397 drm_public int drmGetStats(int fd, drmStatsT *stats)
2403 if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2407 memset(stats, 0, sizeof(*stats));
2408 if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2412 stats->data[i].long_format = "%-20.20s"; \
2413 stats->data[i].rate_format = "%8.8s"; \
2414 stats->data[i].isvalue = 1; \
2415 stats->data[i].verbose = 0
2418 stats->data[i].long_format = "%-20.20s"; \
2419 stats->data[i].rate_format = "%5.5s"; \
2420 stats->data[i].isvalue = 0; \
2421 stats->data[i].mult_names = "kgm"; \
2422 stats->data[i].mult = 1000; \
2423 stats->data[i].verbose = 0
2426 stats->data[i].long_format = "%-20.20s"; \
2427 stats->data[i].rate_format = "%5.5s"; \
2428 stats->data[i].isvalue = 0; \
2429 stats->data[i].mult_names = "KGM"; \
2430 stats->data[i].mult = 1024; \
2431 stats->data[i].verbose = 0
2434 stats->count = s.count;
2435 for (i = 0; i < s.count; i++) {
2436 stats->data[i].value = s.data[i].value;
2437 switch (s.data[i].type) {
2438 case _DRM_STAT_LOCK:
2439 stats->data[i].long_name = "Lock";
2440 stats->data[i].rate_name = "Lock";
2443 case _DRM_STAT_OPENS:
2444 stats->data[i].long_name = "Opens";
2445 stats->data[i].rate_name = "O";
2447 stats->data[i].verbose = 1;
2449 case _DRM_STAT_CLOSES:
2450 stats->data[i].long_name = "Closes";
2451 stats->data[i].rate_name = "Lock";
2453 stats->data[i].verbose = 1;
2455 case _DRM_STAT_IOCTLS:
2456 stats->data[i].long_name = "Ioctls";
2457 stats->data[i].rate_name = "Ioc/s";
2460 case _DRM_STAT_LOCKS:
2461 stats->data[i].long_name = "Locks";
2462 stats->data[i].rate_name = "Lck/s";
2465 case _DRM_STAT_UNLOCKS:
2466 stats->data[i].long_name = "Unlocks";
2467 stats->data[i].rate_name = "Unl/s";
2471 stats->data[i].long_name = "IRQs";
2472 stats->data[i].rate_name = "IRQ/s";
2475 case _DRM_STAT_PRIMARY:
2476 stats->data[i].long_name = "Primary Bytes";
2477 stats->data[i].rate_name = "PB/s";
2480 case _DRM_STAT_SECONDARY:
2481 stats->data[i].long_name = "Secondary Bytes";
2482 stats->data[i].rate_name = "SB/s";
2486 stats->data[i].long_name = "DMA";
2487 stats->data[i].rate_name = "DMA/s";
2490 case _DRM_STAT_SPECIAL:
2491 stats->data[i].long_name = "Special DMA";
2492 stats->data[i].rate_name = "dma/s";
2495 case _DRM_STAT_MISSED:
2496 stats->data[i].long_name = "Miss";
2497 stats->data[i].rate_name = "Ms/s";
2500 case _DRM_STAT_VALUE:
2501 stats->data[i].long_name = "Value";
2502 stats->data[i].rate_name = "Value";
2505 case _DRM_STAT_BYTE:
2506 stats->data[i].long_name = "Bytes";
2507 stats->data[i].rate_name = "B/s";
2510 case _DRM_STAT_COUNT:
2512 stats->data[i].long_name = "Count";
2513 stats->data[i].rate_name = "Cnt/s";
2522 * Issue a set-version ioctl.
2524 * \param fd file descriptor.
2525 * \param drmCommandIndex command index
2526 * \param data source pointer of the data to be read and written.
2527 * \param size size of the data to be read and written.
2529 * \return zero on success, or a negative value on failure.
2532 * It issues a read-write ioctl given by
2533 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2535 drm_public int drmSetInterfaceVersion(int fd, drmSetVersion *version)
2538 drm_set_version_t sv;
2541 sv.drm_di_major = version->drm_di_major;
2542 sv.drm_di_minor = version->drm_di_minor;
2543 sv.drm_dd_major = version->drm_dd_major;
2544 sv.drm_dd_minor = version->drm_dd_minor;
2546 if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
2550 version->drm_di_major = sv.drm_di_major;
2551 version->drm_di_minor = sv.drm_di_minor;
2552 version->drm_dd_major = sv.drm_dd_major;
2553 version->drm_dd_minor = sv.drm_dd_minor;
2559 * Send a device-specific command.
2561 * \param fd file descriptor.
2562 * \param drmCommandIndex command index
2564 * \return zero on success, or a negative value on failure.
2567 * It issues a ioctl given by
2568 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2570 drm_public int drmCommandNone(int fd, unsigned long drmCommandIndex)
2572 unsigned long request;
2574 request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
2576 if (drmIoctl(fd, request, NULL)) {
2584 * Send a device-specific read command.
2586 * \param fd file descriptor.
2587 * \param drmCommandIndex command index
2588 * \param data destination pointer of the data to be read.
2589 * \param size size of the data to be read.
2591 * \return zero on success, or a negative value on failure.
2594 * It issues a read ioctl given by
2595 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2597 drm_public int drmCommandRead(int fd, unsigned long drmCommandIndex,
2598 void *data, unsigned long size)
2600 unsigned long request;
2602 request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
2603 DRM_COMMAND_BASE + drmCommandIndex, size);
2605 if (drmIoctl(fd, request, data)) {
2613 * Send a device-specific write command.
2615 * \param fd file descriptor.
2616 * \param drmCommandIndex command index
2617 * \param data source pointer of the data to be written.
2618 * \param size size of the data to be written.
2620 * \return zero on success, or a negative value on failure.
2623 * It issues a write ioctl given by
2624 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2626 drm_public int drmCommandWrite(int fd, unsigned long drmCommandIndex,
2627 void *data, unsigned long size)
2629 unsigned long request;
2631 request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
2632 DRM_COMMAND_BASE + drmCommandIndex, size);
2634 if (drmIoctl(fd, request, data)) {
2642 * Send a device-specific read-write command.
2644 * \param fd file descriptor.
2645 * \param drmCommandIndex command index
2646 * \param data source pointer of the data to be read and written.
2647 * \param size size of the data to be read and written.
2649 * \return zero on success, or a negative value on failure.
2652 * It issues a read-write ioctl given by
2653 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2655 drm_public int drmCommandWriteRead(int fd, unsigned long drmCommandIndex,
2656 void *data, unsigned long size)
2658 unsigned long request;
2660 request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
2661 DRM_COMMAND_BASE + drmCommandIndex, size);
2663 if (drmIoctl(fd, request, data))
2668 #define DRM_MAX_FDS 16
2674 } connection[DRM_MAX_FDS];
2676 static int nr_fds = 0;
2678 drm_public int drmOpenOnce(void *unused, const char *BusID, int *newlyopened)
2680 return drmOpenOnceWithType(BusID, newlyopened, DRM_NODE_PRIMARY);
2683 drm_public int drmOpenOnceWithType(const char *BusID, int *newlyopened,
2689 for (i = 0; i < nr_fds; i++)
2690 if ((strcmp(BusID, connection[i].BusID) == 0) &&
2691 (connection[i].type == type)) {
2692 connection[i].refcount++;
2694 return connection[i].fd;
2697 fd = drmOpenWithType(NULL, BusID, type);
2698 if (fd < 0 || nr_fds == DRM_MAX_FDS)
2701 connection[nr_fds].BusID = strdup(BusID);
2702 connection[nr_fds].fd = fd;
2703 connection[nr_fds].refcount = 1;
2704 connection[nr_fds].type = type;
2708 fprintf(stderr, "saved connection %d for %s %d\n",
2709 nr_fds, connection[nr_fds].BusID,
2710 strcmp(BusID, connection[nr_fds].BusID));
2717 drm_public void drmCloseOnce(int fd)
2721 for (i = 0; i < nr_fds; i++) {
2722 if (fd == connection[i].fd) {
2723 if (--connection[i].refcount == 0) {
2724 drmClose(connection[i].fd);
2725 free(connection[i].BusID);
2728 connection[i] = connection[nr_fds];
2736 drm_public int drmSetMaster(int fd)
2738 return drmIoctl(fd, DRM_IOCTL_SET_MASTER, NULL);
2741 drm_public int drmDropMaster(int fd)
2743 return drmIoctl(fd, DRM_IOCTL_DROP_MASTER, NULL);
2746 drm_public int drmIsMaster(int fd)
2748 /* Detect master by attempting something that requires master.
2750 * Authenticating magic tokens requires master and 0 is an
2751 * internal kernel detail which we could use. Attempting this on
2752 * a master fd would fail therefore fail with EINVAL because 0
2755 * A non-master fd will fail with EACCES, as the kernel checks
2756 * for master before attempting to do anything else.
2758 * Since we don't want to leak implementation details, use
2761 return drmAuthMagic(fd, 0) != -EACCES;
2764 drm_public char *drmGetDeviceNameFromFd(int fd)
2771 /* The whole drmOpen thing is a fiasco and we need to find a way
2772 * back to just using open(2). For now, however, lets just make
2773 * things worse with even more ad hoc directory walking code to
2774 * discover the device file name. */
2779 for (i = 0; i < DRM_MAX_MINOR; i++) {
2780 snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
2781 if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
2784 if (i == DRM_MAX_MINOR)
2787 return strdup(name);
2790 static bool drmNodeIsDRM(int maj, int min)
2796 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device/drm",
2798 return stat(path, &sbuf) == 0;
2800 return maj == DRM_MAJOR;
2804 drm_public int drmGetNodeTypeFromFd(int fd)
2809 if (fstat(fd, &sbuf))
2812 maj = major(sbuf.st_rdev);
2813 min = minor(sbuf.st_rdev);
2815 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode)) {
2820 type = drmGetMinorType(min);
2826 drm_public int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags,
2829 struct drm_prime_handle args;
2834 args.handle = handle;
2836 ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
2840 *prime_fd = args.fd;
2844 drm_public int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
2846 struct drm_prime_handle args;
2851 ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
2855 *handle = args.handle;
2859 static char *drmGetMinorNameForFD(int fd, int type)
2865 const char *name = drmGetMinorName(type);
2867 char dev_name[64], buf[64];
2875 if (fstat(fd, &sbuf))
2878 maj = major(sbuf.st_rdev);
2879 min = minor(sbuf.st_rdev);
2881 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
2884 snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
2886 sysdir = opendir(buf);
2890 while ((ent = readdir(sysdir))) {
2891 if (strncmp(ent->d_name, name, len) == 0) {
2892 snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
2896 return strdup(dev_name);
2904 char buf[PATH_MAX + 1];
2905 const char *dev_name;
2906 unsigned int maj, min;
2909 if (fstat(fd, &sbuf))
2912 maj = major(sbuf.st_rdev);
2913 min = minor(sbuf.st_rdev);
2915 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
2919 case DRM_NODE_PRIMARY:
2920 dev_name = DRM_DEV_NAME;
2922 case DRM_NODE_CONTROL:
2923 dev_name = DRM_CONTROL_DEV_NAME;
2925 case DRM_NODE_RENDER:
2926 dev_name = DRM_RENDER_DEV_NAME;
2932 base = drmGetMinorBase(type);
2936 n = snprintf(buf, sizeof(buf), dev_name, DRM_DIR_NAME, min - base);
2937 if (n == -1 || n >= sizeof(buf))
2944 drm_public char *drmGetPrimaryDeviceNameFromFd(int fd)
2946 return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
2949 drm_public char *drmGetRenderDeviceNameFromFd(int fd)
2951 return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
2955 static char * DRM_PRINTFLIKE(2, 3)
2956 sysfs_uevent_get(const char *path, const char *fmt, ...)
2958 char filename[PATH_MAX + 1], *key, *line = NULL, *value = NULL;
2959 size_t size = 0, len;
2965 num = vasprintf(&key, fmt, ap);
2969 snprintf(filename, sizeof(filename), "%s/uevent", path);
2971 fp = fopen(filename, "r");
2977 while ((num = getline(&line, &size, fp)) >= 0) {
2978 if ((strncmp(line, key, len) == 0) && (line[len] == '=')) {
2979 char *start = line + len + 1, *end = line + num - 1;
2984 value = strndup(start, end - start);
2998 /* Little white lie to avoid major rework of the existing code */
2999 #define DRM_BUS_VIRTIO 0x10
3001 static int drmParseSubsystemType(int maj, int min)
3004 char path[PATH_MAX + 1];
3005 char link[PATH_MAX + 1] = "";
3011 { "/pci", DRM_BUS_PCI },
3012 { "/usb", DRM_BUS_USB },
3013 { "/platform", DRM_BUS_PLATFORM },
3014 { "/spi", DRM_BUS_PLATFORM },
3015 { "/host1x", DRM_BUS_HOST1X },
3016 { "/virtio", DRM_BUS_VIRTIO },
3019 snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/subsystem",
3022 if (readlink(path, link, PATH_MAX) < 0)
3025 name = strrchr(link, '/');
3029 for (unsigned i = 0; i < ARRAY_SIZE(bus_types); i++) {
3030 if (strncmp(name, bus_types[i].name, strlen(bus_types[i].name)) == 0)
3031 return bus_types[i].bus_type;
3035 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3038 #warning "Missing implementation of drmParseSubsystemType"
3044 get_pci_path(int maj, int min, char *pci_path)
3046 char path[PATH_MAX + 1], *term;
3048 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3049 if (!realpath(path, pci_path)) {
3050 strcpy(pci_path, path);
3054 term = strrchr(pci_path, '/');
3055 if (term && strncmp(term, "/virtio", 7) == 0)
3059 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
3062 unsigned int domain, bus, dev, func;
3063 char pci_path[PATH_MAX + 1], *value;
3066 get_pci_path(maj, min, pci_path);
3068 value = sysfs_uevent_get(pci_path, "PCI_SLOT_NAME");
3072 num = sscanf(value, "%04x:%02x:%02x.%1u", &domain, &bus, &dev, &func);
3078 info->domain = domain;
3084 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3085 struct drm_pciinfo pinfo;
3088 type = drmGetMinorType(min);
3092 fd = drmOpenMinor(min, 0, type);
3096 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3102 info->domain = pinfo.domain;
3103 info->bus = pinfo.bus;
3104 info->dev = pinfo.dev;
3105 info->func = pinfo.func;
3109 #warning "Missing implementation of drmParsePciBusInfo"
3114 drm_public int drmDevicesEqual(drmDevicePtr a, drmDevicePtr b)
3116 if (a == NULL || b == NULL)
3119 if (a->bustype != b->bustype)
3122 switch (a->bustype) {
3124 return memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo)) == 0;
3127 return memcmp(a->businfo.usb, b->businfo.usb, sizeof(drmUsbBusInfo)) == 0;
3129 case DRM_BUS_PLATFORM:
3130 return memcmp(a->businfo.platform, b->businfo.platform, sizeof(drmPlatformBusInfo)) == 0;
3132 case DRM_BUS_HOST1X:
3133 return memcmp(a->businfo.host1x, b->businfo.host1x, sizeof(drmHost1xBusInfo)) == 0;
3142 static int drmGetNodeType(const char *name)
3144 if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
3145 sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
3146 return DRM_NODE_PRIMARY;
3148 if (strncmp(name, DRM_CONTROL_MINOR_NAME,
3149 sizeof(DRM_CONTROL_MINOR_NAME ) - 1) == 0)
3150 return DRM_NODE_CONTROL;
3152 if (strncmp(name, DRM_RENDER_MINOR_NAME,
3153 sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
3154 return DRM_NODE_RENDER;
3159 static int drmGetMaxNodeName(void)
3161 return sizeof(DRM_DIR_NAME) +
3162 MAX3(sizeof(DRM_PRIMARY_MINOR_NAME),
3163 sizeof(DRM_CONTROL_MINOR_NAME),
3164 sizeof(DRM_RENDER_MINOR_NAME)) +
3165 3 /* length of the node number */;
3169 static int parse_separate_sysfs_files(int maj, int min,
3170 drmPciDeviceInfoPtr device,
3171 bool ignore_revision)
3173 static const char *attrs[] = {
3174 "revision", /* Older kernels are missing the file, so check for it first */
3180 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3181 unsigned int data[ARRAY_SIZE(attrs)];
3185 get_pci_path(maj, min, pci_path);
3187 for (unsigned i = ignore_revision ? 1 : 0; i < ARRAY_SIZE(attrs); i++) {
3188 snprintf(path, PATH_MAX, "%s/%s", pci_path, attrs[i]);
3189 fp = fopen(path, "r");
3193 ret = fscanf(fp, "%x", &data[i]);
3200 device->revision_id = ignore_revision ? 0xff : data[0] & 0xff;
3201 device->vendor_id = data[1] & 0xffff;
3202 device->device_id = data[2] & 0xffff;
3203 device->subvendor_id = data[3] & 0xffff;
3204 device->subdevice_id = data[4] & 0xffff;
3209 static int parse_config_sysfs_file(int maj, int min,
3210 drmPciDeviceInfoPtr device)
3212 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3213 unsigned char config[64];
3216 get_pci_path(maj, min, pci_path);
3218 snprintf(path, PATH_MAX, "%s/config", pci_path);
3219 fd = open(path, O_RDONLY);
3223 ret = read(fd, config, sizeof(config));
3228 device->vendor_id = config[0] | (config[1] << 8);
3229 device->device_id = config[2] | (config[3] << 8);
3230 device->revision_id = config[8];
3231 device->subvendor_id = config[44] | (config[45] << 8);
3232 device->subdevice_id = config[46] | (config[47] << 8);
3238 static int drmParsePciDeviceInfo(int maj, int min,
3239 drmPciDeviceInfoPtr device,
3243 if (!(flags & DRM_DEVICE_GET_PCI_REVISION))
3244 return parse_separate_sysfs_files(maj, min, device, true);
3246 if (parse_separate_sysfs_files(maj, min, device, false))
3247 return parse_config_sysfs_file(maj, min, device);
3250 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3251 struct drm_pciinfo pinfo;
3254 type = drmGetMinorType(min);
3258 fd = drmOpenMinor(min, 0, type);
3262 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3268 device->vendor_id = pinfo.vendor_id;
3269 device->device_id = pinfo.device_id;
3270 device->revision_id = pinfo.revision_id;
3271 device->subvendor_id = pinfo.subvendor_id;
3272 device->subdevice_id = pinfo.subdevice_id;
3276 #warning "Missing implementation of drmParsePciDeviceInfo"
3281 static void drmFreePlatformDevice(drmDevicePtr device)
3283 if (device->deviceinfo.platform) {
3284 if (device->deviceinfo.platform->compatible) {
3285 char **compatible = device->deviceinfo.platform->compatible;
3287 while (*compatible) {
3292 free(device->deviceinfo.platform->compatible);
3297 static void drmFreeHost1xDevice(drmDevicePtr device)
3299 if (device->deviceinfo.host1x) {
3300 if (device->deviceinfo.host1x->compatible) {
3301 char **compatible = device->deviceinfo.host1x->compatible;
3303 while (*compatible) {
3308 free(device->deviceinfo.host1x->compatible);
3313 drm_public void drmFreeDevice(drmDevicePtr *device)
3319 switch ((*device)->bustype) {
3320 case DRM_BUS_PLATFORM:
3321 drmFreePlatformDevice(*device);
3324 case DRM_BUS_HOST1X:
3325 drmFreeHost1xDevice(*device);
3334 drm_public void drmFreeDevices(drmDevicePtr devices[], int count)
3338 if (devices == NULL)
3341 for (i = 0; i < count; i++)
3343 drmFreeDevice(&devices[i]);
3346 static drmDevicePtr drmDeviceAlloc(unsigned int type, const char *node,
3347 size_t bus_size, size_t device_size,
3350 size_t max_node_length, extra, size;
3351 drmDevicePtr device;
3355 max_node_length = ALIGN(drmGetMaxNodeName(), sizeof(void *));
3356 extra = DRM_NODE_MAX * (sizeof(void *) + max_node_length);
3358 size = sizeof(*device) + extra + bus_size + device_size;
3360 device = calloc(1, size);
3364 device->available_nodes = 1 << type;
3366 ptr = (char *)device + sizeof(*device);
3367 device->nodes = (char **)ptr;
3369 ptr += DRM_NODE_MAX * sizeof(void *);
3371 for (i = 0; i < DRM_NODE_MAX; i++) {
3372 device->nodes[i] = ptr;
3373 ptr += max_node_length;
3376 memcpy(device->nodes[type], node, max_node_length);
3383 static int drmProcessPciDevice(drmDevicePtr *device,
3384 const char *node, int node_type,
3385 int maj, int min, bool fetch_deviceinfo,
3392 dev = drmDeviceAlloc(node_type, node, sizeof(drmPciBusInfo),
3393 sizeof(drmPciDeviceInfo), &addr);
3397 dev->bustype = DRM_BUS_PCI;
3399 dev->businfo.pci = (drmPciBusInfoPtr)addr;
3401 ret = drmParsePciBusInfo(maj, min, dev->businfo.pci);
3405 // Fetch the device info if the user has requested it
3406 if (fetch_deviceinfo) {
3407 addr += sizeof(drmPciBusInfo);
3408 dev->deviceinfo.pci = (drmPciDeviceInfoPtr)addr;
3410 ret = drmParsePciDeviceInfo(maj, min, dev->deviceinfo.pci, flags);
3424 static int drmParseUsbBusInfo(int maj, int min, drmUsbBusInfoPtr info)
3427 char path[PATH_MAX + 1], *value;
3428 unsigned int bus, dev;
3431 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3433 value = sysfs_uevent_get(path, "BUSNUM");
3437 ret = sscanf(value, "%03u", &bus);
3443 value = sysfs_uevent_get(path, "DEVNUM");
3447 ret = sscanf(value, "%03u", &dev);
3458 #warning "Missing implementation of drmParseUsbBusInfo"
3463 static int drmParseUsbDeviceInfo(int maj, int min, drmUsbDeviceInfoPtr info)
3466 char path[PATH_MAX + 1], *value;
3467 unsigned int vendor, product;
3470 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3472 value = sysfs_uevent_get(path, "PRODUCT");
3476 ret = sscanf(value, "%x/%x", &vendor, &product);
3482 info->vendor = vendor;
3483 info->product = product;
3487 #warning "Missing implementation of drmParseUsbDeviceInfo"
3492 static int drmProcessUsbDevice(drmDevicePtr *device, const char *node,
3493 int node_type, int maj, int min,
3494 bool fetch_deviceinfo, uint32_t flags)
3500 dev = drmDeviceAlloc(node_type, node, sizeof(drmUsbBusInfo),
3501 sizeof(drmUsbDeviceInfo), &ptr);
3505 dev->bustype = DRM_BUS_USB;
3507 dev->businfo.usb = (drmUsbBusInfoPtr)ptr;
3509 ret = drmParseUsbBusInfo(maj, min, dev->businfo.usb);
3513 if (fetch_deviceinfo) {
3514 ptr += sizeof(drmUsbBusInfo);
3515 dev->deviceinfo.usb = (drmUsbDeviceInfoPtr)ptr;
3517 ret = drmParseUsbDeviceInfo(maj, min, dev->deviceinfo.usb);
3531 static int drmParseOFBusInfo(int maj, int min, char *fullname)
3534 char path[PATH_MAX + 1], *name, *tmp_name;
3536 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3538 name = sysfs_uevent_get(path, "OF_FULLNAME");
3541 /* If the device lacks OF data, pick the MODALIAS info */
3542 name = sysfs_uevent_get(path, "MODALIAS");
3546 /* .. and strip the MODALIAS=[platform,usb...]: part. */
3547 tmp_name = strrchr(name, ':');
3555 strncpy(fullname, tmp_name, DRM_PLATFORM_DEVICE_NAME_LEN);
3556 fullname[DRM_PLATFORM_DEVICE_NAME_LEN - 1] = '\0';
3561 #warning "Missing implementation of drmParseOFBusInfo"
3566 static int drmParseOFDeviceInfo(int maj, int min, char ***compatible)
3569 char path[PATH_MAX + 1], *value, *tmp_name;
3570 unsigned int count, i;
3573 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3575 value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
3577 sscanf(value, "%u", &count);
3580 /* Assume one entry if the device lack OF data */
3584 *compatible = calloc(count + 1, sizeof(char *));
3588 for (i = 0; i < count; i++) {
3589 value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
3592 /* If the device lacks OF data, pick the MODALIAS info */
3593 value = sysfs_uevent_get(path, "MODALIAS");
3599 /* .. and strip the MODALIAS=[platform,usb...]: part. */
3600 tmp_name = strrchr(value, ':');
3605 tmp_name = strdup(tmp_name + 1);
3609 (*compatible)[i] = tmp_name;
3616 free((*compatible)[i]);
3621 #warning "Missing implementation of drmParseOFDeviceInfo"
3626 static int drmProcessPlatformDevice(drmDevicePtr *device,
3627 const char *node, int node_type,
3628 int maj, int min, bool fetch_deviceinfo,
3635 dev = drmDeviceAlloc(node_type, node, sizeof(drmPlatformBusInfo),
3636 sizeof(drmPlatformDeviceInfo), &ptr);
3640 dev->bustype = DRM_BUS_PLATFORM;
3642 dev->businfo.platform = (drmPlatformBusInfoPtr)ptr;
3644 ret = drmParseOFBusInfo(maj, min, dev->businfo.platform->fullname);
3648 if (fetch_deviceinfo) {
3649 ptr += sizeof(drmPlatformBusInfo);
3650 dev->deviceinfo.platform = (drmPlatformDeviceInfoPtr)ptr;
3652 ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.platform->compatible);
3666 static int drmProcessHost1xDevice(drmDevicePtr *device,
3667 const char *node, int node_type,
3668 int maj, int min, bool fetch_deviceinfo,
3675 dev = drmDeviceAlloc(node_type, node, sizeof(drmHost1xBusInfo),
3676 sizeof(drmHost1xDeviceInfo), &ptr);
3680 dev->bustype = DRM_BUS_HOST1X;
3682 dev->businfo.host1x = (drmHost1xBusInfoPtr)ptr;
3684 ret = drmParseOFBusInfo(maj, min, dev->businfo.host1x->fullname);
3688 if (fetch_deviceinfo) {
3689 ptr += sizeof(drmHost1xBusInfo);
3690 dev->deviceinfo.host1x = (drmHost1xDeviceInfoPtr)ptr;
3692 ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.host1x->compatible);
3707 process_device(drmDevicePtr *device, const char *d_name,
3708 int req_subsystem_type,
3709 bool fetch_deviceinfo, uint32_t flags)
3712 char node[PATH_MAX + 1];
3713 int node_type, subsystem_type;
3714 unsigned int maj, min;
3716 node_type = drmGetNodeType(d_name);
3720 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, d_name);
3721 if (stat(node, &sbuf))
3724 maj = major(sbuf.st_rdev);
3725 min = minor(sbuf.st_rdev);
3727 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3730 subsystem_type = drmParseSubsystemType(maj, min);
3731 if (req_subsystem_type != -1 && req_subsystem_type != subsystem_type)
3734 switch (subsystem_type) {
3736 case DRM_BUS_VIRTIO:
3737 return drmProcessPciDevice(device, node, node_type, maj, min,
3738 fetch_deviceinfo, flags);
3740 return drmProcessUsbDevice(device, node, node_type, maj, min,
3741 fetch_deviceinfo, flags);
3742 case DRM_BUS_PLATFORM:
3743 return drmProcessPlatformDevice(device, node, node_type, maj, min,
3744 fetch_deviceinfo, flags);
3745 case DRM_BUS_HOST1X:
3746 return drmProcessHost1xDevice(device, node, node_type, maj, min,
3747 fetch_deviceinfo, flags);
3753 /* Consider devices located on the same bus as duplicate and fold the respective
3754 * entries into a single one.
3756 * Note: this leaves "gaps" in the array, while preserving the length.
3758 static void drmFoldDuplicatedDevices(drmDevicePtr local_devices[], int count)
3760 int node_type, i, j;
3762 for (i = 0; i < count; i++) {
3763 for (j = i + 1; j < count; j++) {
3764 if (drmDevicesEqual(local_devices[i], local_devices[j])) {
3765 local_devices[i]->available_nodes |= local_devices[j]->available_nodes;
3766 node_type = log2(local_devices[j]->available_nodes);
3767 memcpy(local_devices[i]->nodes[node_type],
3768 local_devices[j]->nodes[node_type], drmGetMaxNodeName());
3769 drmFreeDevice(&local_devices[j]);
3775 /* Check that the given flags are valid returning 0 on success */
3777 drm_device_validate_flags(uint32_t flags)
3779 return (flags & ~DRM_DEVICE_GET_PCI_REVISION);
3783 drm_device_has_rdev(drmDevicePtr device, dev_t find_rdev)
3787 for (int i = 0; i < DRM_NODE_MAX; i++) {
3788 if (device->available_nodes & 1 << i) {
3789 if (stat(device->nodes[i], &sbuf) == 0 &&
3790 sbuf.st_rdev == find_rdev)
3798 * The kernel drm core has a number of places that assume maximum of
3799 * 3x64 devices nodes. That's 64 for each of primary, control and
3800 * render nodes. Rounded it up to 256 for simplicity.
3802 #define MAX_DRM_NODES 256
3805 * Get information about the opened drm device
3807 * \param fd file descriptor of the drm device
3808 * \param flags feature/behaviour bitmask
3809 * \param device the address of a drmDevicePtr where the information
3810 * will be allocated in stored
3812 * \return zero on success, negative error code otherwise.
3814 * \note Unlike drmGetDevice it does not retrieve the pci device revision field
3815 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
3817 drm_public int drmGetDevice2(int fd, uint32_t flags, drmDevicePtr *device)
3821 * DRI device nodes on OpenBSD are not in their own directory, they reside
3822 * in /dev along with a large number of statically generated /dev nodes.
3823 * Avoid stat'ing all of /dev needlessly by implementing this custom path.
3827 char node[PATH_MAX + 1];
3828 const char *dev_name;
3829 int node_type, subsystem_type;
3830 int maj, min, n, ret, base;
3832 if (fd == -1 || device == NULL)
3835 if (fstat(fd, &sbuf))
3838 maj = major(sbuf.st_rdev);
3839 min = minor(sbuf.st_rdev);
3841 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3844 node_type = drmGetMinorType(min);
3845 if (node_type == -1)
3848 switch (node_type) {
3849 case DRM_NODE_PRIMARY:
3850 dev_name = DRM_DEV_NAME;
3852 case DRM_NODE_CONTROL:
3853 dev_name = DRM_CONTROL_DEV_NAME;
3855 case DRM_NODE_RENDER:
3856 dev_name = DRM_RENDER_DEV_NAME;
3862 base = drmGetMinorBase(node_type);
3866 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min - base);
3867 if (n == -1 || n >= PATH_MAX)
3869 if (stat(node, &sbuf))
3872 subsystem_type = drmParseSubsystemType(maj, min);
3873 if (subsystem_type != DRM_BUS_PCI)
3876 ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
3884 drmDevicePtr local_devices[MAX_DRM_NODES];
3887 struct dirent *dent;
3891 int ret, i, node_count;
3894 if (drm_device_validate_flags(flags))
3897 if (fd == -1 || device == NULL)
3900 if (fstat(fd, &sbuf))
3903 find_rdev = sbuf.st_rdev;
3904 maj = major(sbuf.st_rdev);
3905 min = minor(sbuf.st_rdev);
3907 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3910 subsystem_type = drmParseSubsystemType(maj, min);
3911 if (subsystem_type < 0)
3912 return subsystem_type;
3914 sysdir = opendir(DRM_DIR_NAME);
3919 while ((dent = readdir(sysdir))) {
3920 ret = process_device(&d, dent->d_name, subsystem_type, true, flags);
3924 if (i >= MAX_DRM_NODES) {
3925 fprintf(stderr, "More than %d drm nodes detected. "
3926 "Please report a bug - that should not happen.\n"
3927 "Skipping extra nodes\n", MAX_DRM_NODES);
3930 local_devices[i] = d;
3935 drmFoldDuplicatedDevices(local_devices, node_count);
3939 for (i = 0; i < node_count; i++) {
3940 if (!local_devices[i])
3943 if (drm_device_has_rdev(local_devices[i], find_rdev))
3944 *device = local_devices[i];
3946 drmFreeDevice(&local_devices[i]);
3950 if (*device == NULL)
3957 * Get information about the opened drm device
3959 * \param fd file descriptor of the drm device
3960 * \param device the address of a drmDevicePtr where the information
3961 * will be allocated in stored
3963 * \return zero on success, negative error code otherwise.
3965 drm_public int drmGetDevice(int fd, drmDevicePtr *device)
3967 return drmGetDevice2(fd, DRM_DEVICE_GET_PCI_REVISION, device);
3971 * Get drm devices on the system
3973 * \param flags feature/behaviour bitmask
3974 * \param devices the array of devices with drmDevicePtr elements
3975 * can be NULL to get the device number first
3976 * \param max_devices the maximum number of devices for the array
3978 * \return on error - negative error code,
3979 * if devices is NULL - total number of devices available on the system,
3980 * alternatively the number of devices stored in devices[], which is
3981 * capped by the max_devices.
3983 * \note Unlike drmGetDevices it does not retrieve the pci device revision field
3984 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
3986 drm_public int drmGetDevices2(uint32_t flags, drmDevicePtr devices[],
3989 drmDevicePtr local_devices[MAX_DRM_NODES];
3990 drmDevicePtr device;
3992 struct dirent *dent;
3993 int ret, i, node_count, device_count;
3995 if (drm_device_validate_flags(flags))
3998 sysdir = opendir(DRM_DIR_NAME);
4003 while ((dent = readdir(sysdir))) {
4004 ret = process_device(&device, dent->d_name, -1, devices != NULL, flags);
4008 if (i >= MAX_DRM_NODES) {
4009 fprintf(stderr, "More than %d drm nodes detected. "
4010 "Please report a bug - that should not happen.\n"
4011 "Skipping extra nodes\n", MAX_DRM_NODES);
4014 local_devices[i] = device;
4019 drmFoldDuplicatedDevices(local_devices, node_count);
4022 for (i = 0; i < node_count; i++) {
4023 if (!local_devices[i])
4026 if ((devices != NULL) && (device_count < max_devices))
4027 devices[device_count] = local_devices[i];
4029 drmFreeDevice(&local_devices[i]);
4035 return device_count;
4039 * Get drm devices on the system
4041 * \param devices the array of devices with drmDevicePtr elements
4042 * can be NULL to get the device number first
4043 * \param max_devices the maximum number of devices for the array
4045 * \return on error - negative error code,
4046 * if devices is NULL - total number of devices available on the system,
4047 * alternatively the number of devices stored in devices[], which is
4048 * capped by the max_devices.
4050 drm_public int drmGetDevices(drmDevicePtr devices[], int max_devices)
4052 return drmGetDevices2(DRM_DEVICE_GET_PCI_REVISION, devices, max_devices);
4055 drm_public char *drmGetDeviceNameFromFd2(int fd)
4059 char path[PATH_MAX + 1], *value;
4060 unsigned int maj, min;
4062 if (fstat(fd, &sbuf))
4065 maj = major(sbuf.st_rdev);
4066 min = minor(sbuf.st_rdev);
4068 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4071 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d", maj, min);
4073 value = sysfs_uevent_get(path, "DEVNAME");
4077 snprintf(path, sizeof(path), "/dev/%s", value);
4080 return strdup(path);
4083 char node[PATH_MAX + 1];
4084 const char *dev_name;
4086 int maj, min, n, base;
4088 if (fstat(fd, &sbuf))
4091 maj = major(sbuf.st_rdev);
4092 min = minor(sbuf.st_rdev);
4094 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4097 node_type = drmGetMinorType(min);
4098 if (node_type == -1)
4101 switch (node_type) {
4102 case DRM_NODE_PRIMARY:
4103 dev_name = DRM_DEV_NAME;
4105 case DRM_NODE_CONTROL:
4106 dev_name = DRM_CONTROL_DEV_NAME;
4108 case DRM_NODE_RENDER:
4109 dev_name = DRM_RENDER_DEV_NAME;
4115 base = drmGetMinorBase(node_type);
4119 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min - base);
4120 if (n == -1 || n >= PATH_MAX)
4123 return strdup(node);
4127 drm_public int drmSyncobjCreate(int fd, uint32_t flags, uint32_t *handle)
4129 struct drm_syncobj_create args;
4135 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_CREATE, &args);
4138 *handle = args.handle;
4142 drm_public int drmSyncobjDestroy(int fd, uint32_t handle)
4144 struct drm_syncobj_destroy args;
4147 args.handle = handle;
4148 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_DESTROY, &args);
4151 drm_public int drmSyncobjHandleToFD(int fd, uint32_t handle, int *obj_fd)
4153 struct drm_syncobj_handle args;
4158 args.handle = handle;
4159 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4166 drm_public int drmSyncobjFDToHandle(int fd, int obj_fd, uint32_t *handle)
4168 struct drm_syncobj_handle args;
4174 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4177 *handle = args.handle;
4181 drm_public int drmSyncobjImportSyncFile(int fd, uint32_t handle,
4184 struct drm_syncobj_handle args;
4187 args.fd = sync_file_fd;
4188 args.handle = handle;
4189 args.flags = DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE;
4190 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4193 drm_public int drmSyncobjExportSyncFile(int fd, uint32_t handle,
4196 struct drm_syncobj_handle args;
4201 args.handle = handle;
4202 args.flags = DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE;
4203 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4206 *sync_file_fd = args.fd;
4210 drm_public int drmSyncobjWait(int fd, uint32_t *handles, unsigned num_handles,
4211 int64_t timeout_nsec, unsigned flags,
4212 uint32_t *first_signaled)
4214 struct drm_syncobj_wait args;
4218 args.handles = (uintptr_t)handles;
4219 args.timeout_nsec = timeout_nsec;
4220 args.count_handles = num_handles;
4223 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_WAIT, &args);
4228 *first_signaled = args.first_signaled;
4232 drm_public int drmSyncobjReset(int fd, const uint32_t *handles,
4233 uint32_t handle_count)
4235 struct drm_syncobj_array args;
4239 args.handles = (uintptr_t)handles;
4240 args.count_handles = handle_count;
4242 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_RESET, &args);
4246 drm_public int drmSyncobjSignal(int fd, const uint32_t *handles,
4247 uint32_t handle_count)
4249 struct drm_syncobj_array args;
4253 args.handles = (uintptr_t)handles;
4254 args.count_handles = handle_count;
4256 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_SIGNAL, &args);