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>
61 #include <sys/sysctl.h>
65 #if defined(__FreeBSD__)
66 #include <sys/param.h>
67 #include <sys/pciio.h>
70 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
72 /* Not all systems have MAP_FAILED defined */
74 #define MAP_FAILED ((void *)-1)
78 #include "libdrm_macros.h"
80 #include "util_math.h"
96 #endif /* __OpenBSD__ */
99 #define DRM_MAJOR 226 /* Linux */
102 #if defined(__OpenBSD__) || defined(__DragonFly__)
110 uint16_t subvendor_id;
111 uint16_t subdevice_id;
115 #define DRM_IOCTL_GET_PCIINFO DRM_IOR(0x15, struct drm_pciinfo)
118 #define DRM_MSG_VERBOSITY 3
120 #define memclear(s) memset(&s, 0, sizeof(s))
122 static drmServerInfoPtr drm_server_info;
124 static bool drmNodeIsDRM(int maj, int min);
125 static char *drmGetMinorNameForFD(int fd, int type);
127 drm_public void drmSetServerInfo(drmServerInfoPtr info)
129 drm_server_info = info;
133 * Output a message to stderr.
135 * \param format printf() like format string.
138 * This function is a wrapper around vfprintf().
141 static int DRM_PRINTFLIKE(1, 0)
142 drmDebugPrint(const char *format, va_list ap)
144 return vfprintf(stderr, format, ap);
148 drmMsg(const char *format, ...)
152 if (((env = getenv("LIBGL_DEBUG")) && strstr(env, "verbose")) ||
153 (drm_server_info && drm_server_info->debug_print))
155 va_start(ap, format);
156 if (drm_server_info) {
157 drm_server_info->debug_print(format,ap);
159 drmDebugPrint(format, ap);
165 static void *drmHashTable = NULL; /* Context switch callbacks */
167 drm_public void *drmGetHashTable(void)
172 drm_public void *drmMalloc(int size)
174 return calloc(1, size);
177 drm_public void drmFree(void *pt)
183 * Call ioctl, restarting if it is interrupted
186 drmIoctl(int fd, unsigned long request, void *arg)
191 ret = ioctl(fd, request, arg);
192 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
196 static unsigned long drmGetKeyFromFd(int fd)
205 drm_public drmHashEntry *drmGetEntry(int fd)
207 unsigned long key = drmGetKeyFromFd(fd);
212 drmHashTable = drmHashCreate();
214 if (drmHashLookup(drmHashTable, key, &value)) {
215 entry = drmMalloc(sizeof(*entry));
218 entry->tagTable = drmHashCreate();
219 drmHashInsert(drmHashTable, key, entry);
227 * Compare two busid strings
232 * \return 1 if matched.
235 * This function compares two bus ID strings. It understands the older
236 * PCI:b:d:f format and the newer pci:oooo:bb:dd.f format. In the format, o is
237 * domain, b is bus, d is device, f is function.
239 static int drmMatchBusID(const char *id1, const char *id2, int pci_domain_ok)
241 /* First, check if the IDs are exactly the same */
242 if (strcasecmp(id1, id2) == 0)
245 /* Try to match old/new-style PCI bus IDs. */
246 if (strncasecmp(id1, "pci", 3) == 0) {
247 unsigned int o1, b1, d1, f1;
248 unsigned int o2, b2, d2, f2;
251 ret = sscanf(id1, "pci:%04x:%02x:%02x.%u", &o1, &b1, &d1, &f1);
254 ret = sscanf(id1, "PCI:%u:%u:%u", &b1, &d1, &f1);
259 ret = sscanf(id2, "pci:%04x:%02x:%02x.%u", &o2, &b2, &d2, &f2);
262 ret = sscanf(id2, "PCI:%u:%u:%u", &b2, &d2, &f2);
267 /* If domains aren't properly supported by the kernel interface,
268 * just ignore them, which sucks less than picking a totally random
269 * card with "open by name"
274 if ((o1 != o2) || (b1 != b2) || (d1 != d2) || (f1 != f2))
283 * Handles error checking for chown call.
285 * \param path to file.
286 * \param id of the new owner.
287 * \param id of the new group.
289 * \return zero if success or -1 if failure.
292 * Checks for failure. If failure was caused by signal call chown again.
293 * If any other failure happened then it will output error message using
297 static int chown_check_return(const char *path, uid_t owner, gid_t group)
302 rv = chown(path, owner, group);
303 } while (rv != 0 && errno == EINTR);
308 drmMsg("Failed to change owner or group for file %s! %d: %s\n",
309 path, errno, strerror(errno));
314 static const char *drmGetDeviceName(int type)
317 case DRM_NODE_PRIMARY:
319 case DRM_NODE_CONTROL:
320 return DRM_CONTROL_DEV_NAME;
321 case DRM_NODE_RENDER:
322 return DRM_RENDER_DEV_NAME;
328 * Open the DRM device, creating it if necessary.
330 * \param dev major and minor numbers of the device.
331 * \param minor minor number of the device.
333 * \return a file descriptor on success, or a negative value on error.
336 * Assembles the device name from \p minor and opens it, creating the device
337 * special file node with the major and minor numbers specified by \p dev and
338 * parent directory if necessary and was called by root.
340 static int drmOpenDevice(dev_t dev, int minor, int type)
343 const char *dev_name = drmGetDeviceName(type);
344 char buf[DRM_NODE_NAME_MAX];
346 mode_t devmode = DRM_DEV_MODE, serv_mode;
349 int isroot = !geteuid();
350 uid_t user = DRM_DEV_UID;
351 gid_t group = DRM_DEV_GID;
357 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
358 drmMsg("drmOpenDevice: node name is %s\n", buf);
360 if (drm_server_info && drm_server_info->get_perms) {
361 drm_server_info->get_perms(&serv_group, &serv_mode);
362 devmode = serv_mode ? serv_mode : DRM_DEV_MODE;
363 devmode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
367 if (stat(DRM_DIR_NAME, &st)) {
369 return DRM_ERR_NOT_ROOT;
370 mkdir(DRM_DIR_NAME, DRM_DEV_DIRMODE);
371 chown_check_return(DRM_DIR_NAME, 0, 0); /* root:root */
372 chmod(DRM_DIR_NAME, DRM_DEV_DIRMODE);
375 /* Check if the device node exists and create it if necessary. */
376 if (stat(buf, &st)) {
378 return DRM_ERR_NOT_ROOT;
380 mknod(buf, S_IFCHR | devmode, dev);
383 if (drm_server_info && drm_server_info->get_perms) {
384 group = ((int)serv_group >= 0) ? serv_group : DRM_DEV_GID;
385 chown_check_return(buf, user, group);
389 /* if we modprobed then wait for udev */
393 if (stat(DRM_DIR_NAME, &st)) {
397 if (udev_count == 50)
402 if (stat(buf, &st)) {
406 if (udev_count == 50)
413 fd = open(buf, O_RDWR | O_CLOEXEC, 0);
414 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
415 fd, fd < 0 ? strerror(errno) : "OK");
420 /* Check if the device node is not what we expect it to be, and recreate it
421 * and try again if so.
423 if (st.st_rdev != dev) {
425 return DRM_ERR_NOT_ROOT;
427 mknod(buf, S_IFCHR | devmode, dev);
428 if (drm_server_info && drm_server_info->get_perms) {
429 chown_check_return(buf, user, group);
433 fd = open(buf, O_RDWR | O_CLOEXEC, 0);
434 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
435 fd, fd < 0 ? strerror(errno) : "OK");
439 drmMsg("drmOpenDevice: Open failed\n");
447 * Open the DRM device
449 * \param minor device minor number.
450 * \param create allow to create the device if set.
452 * \return a file descriptor on success, or a negative value on error.
455 * Calls drmOpenDevice() if \p create is set, otherwise assembles the device
456 * name from \p minor and opens it.
458 static int drmOpenMinor(int minor, int create, int type)
461 char buf[DRM_NODE_NAME_MAX];
462 const char *dev_name = drmGetDeviceName(type);
465 return drmOpenDevice(makedev(DRM_MAJOR, minor), minor, type);
470 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
471 if ((fd = open(buf, O_RDWR | O_CLOEXEC, 0)) >= 0)
478 * Determine whether the DRM kernel driver has been loaded.
480 * \return 1 if the DRM driver is loaded, 0 otherwise.
483 * Determine the presence of the kernel driver by attempting to open the 0
484 * minor and get version information. For backward compatibility with older
485 * Linux implementations, /proc/dri is also checked.
487 drm_public int drmAvailable(void)
489 drmVersionPtr version;
493 if ((fd = drmOpenMinor(0, 1, DRM_NODE_PRIMARY)) < 0) {
495 /* Try proc for backward Linux compatibility */
496 if (!access("/proc/dri/0", R_OK))
502 if ((version = drmGetVersion(fd))) {
504 drmFreeVersion(version);
511 static int drmGetMinorBase(int type)
514 case DRM_NODE_PRIMARY:
516 case DRM_NODE_CONTROL:
518 case DRM_NODE_RENDER:
525 static int drmGetMinorType(int major, int minor)
528 char name[SPECNAMELEN];
531 if (!devname_r(makedev(major, minor), S_IFCHR, name, sizeof(name)))
534 if (sscanf(name, "drm/%d", &id) != 1) {
535 // If not in /dev/drm/ we have the type in the name
536 if (sscanf(name, "dri/card%d\n", &id) >= 1)
537 return DRM_NODE_PRIMARY;
538 else if (sscanf(name, "dri/control%d\n", &id) >= 1)
539 return DRM_NODE_CONTROL;
540 else if (sscanf(name, "dri/renderD%d\n", &id) >= 1)
541 return DRM_NODE_RENDER;
547 int type = minor >> 6;
553 case DRM_NODE_PRIMARY:
554 case DRM_NODE_CONTROL:
555 case DRM_NODE_RENDER:
562 static const char *drmGetMinorName(int type)
565 case DRM_NODE_PRIMARY:
566 return DRM_PRIMARY_MINOR_NAME;
567 case DRM_NODE_CONTROL:
568 return DRM_CONTROL_MINOR_NAME;
569 case DRM_NODE_RENDER:
570 return DRM_RENDER_MINOR_NAME;
577 * Open the device by bus ID.
579 * \param busid bus ID.
580 * \param type device node type.
582 * \return a file descriptor on success, or a negative value on error.
585 * This function attempts to open every possible minor (up to DRM_MAX_MINOR),
586 * comparing the device bus ID with the one supplied.
588 * \sa drmOpenMinor() and drmGetBusid().
590 static int drmOpenByBusid(const char *busid, int type)
592 int i, pci_domain_ok = 1;
596 int base = drmGetMinorBase(type);
601 drmMsg("drmOpenByBusid: Searching for BusID %s\n", busid);
602 for (i = base; i < base + DRM_MAX_MINOR; i++) {
603 fd = drmOpenMinor(i, 1, type);
604 drmMsg("drmOpenByBusid: drmOpenMinor returns %d\n", fd);
606 /* We need to try for 1.4 first for proper PCI domain support
607 * and if that fails, we know the kernel is busted
611 sv.drm_dd_major = -1; /* Don't care */
612 sv.drm_dd_minor = -1; /* Don't care */
613 if (drmSetInterfaceVersion(fd, &sv)) {
619 sv.drm_dd_major = -1; /* Don't care */
620 sv.drm_dd_minor = -1; /* Don't care */
621 drmMsg("drmOpenByBusid: Interface 1.4 failed, trying 1.1\n");
622 drmSetInterfaceVersion(fd, &sv);
624 buf = drmGetBusid(fd);
625 drmMsg("drmOpenByBusid: drmGetBusid reports %s\n", buf);
626 if (buf && drmMatchBusID(buf, busid, pci_domain_ok)) {
640 * Open the device by name.
642 * \param name driver name.
643 * \param type the device node type.
645 * \return a file descriptor on success, or a negative value on error.
648 * This function opens the first minor number that matches the driver name and
649 * isn't already in use. If it's in use it then it will already have a bus ID
652 * \sa drmOpenMinor(), drmGetVersion() and drmGetBusid().
654 static int drmOpenByName(const char *name, int type)
658 drmVersionPtr version;
660 int base = drmGetMinorBase(type);
666 * Open the first minor number that matches the driver name and isn't
667 * already in use. If it's in use it will have a busid assigned already.
669 for (i = base; i < base + DRM_MAX_MINOR; i++) {
670 if ((fd = drmOpenMinor(i, 1, type)) >= 0) {
671 if ((version = drmGetVersion(fd))) {
672 if (!strcmp(version->name, name)) {
673 drmFreeVersion(version);
674 id = drmGetBusid(fd);
675 drmMsg("drmGetBusid returned '%s'\n", id ? id : "NULL");
684 drmFreeVersion(version);
692 /* Backward-compatibility /proc support */
693 for (i = 0; i < 8; i++) {
694 char proc_name[64], buf[512];
695 char *driver, *pt, *devstring;
698 sprintf(proc_name, "/proc/dri/%d/name", i);
699 if ((fd = open(proc_name, 0, 0)) >= 0) {
700 retcode = read(fd, buf, sizeof(buf)-1);
703 buf[retcode-1] = '\0';
704 for (driver = pt = buf; *pt && *pt != ' '; ++pt)
706 if (*pt) { /* Device is next */
708 if (!strcmp(driver, name)) { /* Match */
709 for (devstring = ++pt; *pt && *pt != ' '; ++pt)
711 if (*pt) { /* Found busid */
712 return drmOpenByBusid(++pt, type);
713 } else { /* No busid */
714 return drmOpenDevice(strtol(devstring, NULL, 0),i, type);
728 * Open the DRM device.
730 * Looks up the specified name and bus ID, and opens the device found. The
731 * entry in /dev/dri is created if necessary and if called by root.
733 * \param name driver name. Not referenced if bus ID is supplied.
734 * \param busid bus ID. Zero if not known.
736 * \return a file descriptor on success, or a negative value on error.
739 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
742 drm_public int drmOpen(const char *name, const char *busid)
744 return drmOpenWithType(name, busid, DRM_NODE_PRIMARY);
748 * Open the DRM device with specified type.
750 * Looks up the specified name and bus ID, and opens the device found. The
751 * entry in /dev/dri is created if necessary and if called by root.
753 * \param name driver name. Not referenced if bus ID is supplied.
754 * \param busid bus ID. Zero if not known.
755 * \param type the device node type to open, PRIMARY, CONTROL or RENDER
757 * \return a file descriptor on success, or a negative value on error.
760 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
763 drm_public int drmOpenWithType(const char *name, const char *busid, int type)
765 if (name != NULL && drm_server_info &&
766 drm_server_info->load_module && !drmAvailable()) {
767 /* try to load the kernel module */
768 if (!drm_server_info->load_module(name)) {
769 drmMsg("[drm] failed to load kernel module \"%s\"\n", name);
775 int fd = drmOpenByBusid(busid, type);
781 return drmOpenByName(name, type);
786 drm_public int drmOpenControl(int minor)
788 return drmOpenMinor(minor, 0, DRM_NODE_CONTROL);
791 drm_public int drmOpenRender(int minor)
793 return drmOpenMinor(minor, 0, DRM_NODE_RENDER);
797 * Free the version information returned by drmGetVersion().
799 * \param v pointer to the version information.
802 * It frees the memory pointed by \p %v as well as all the non-null strings
805 drm_public void drmFreeVersion(drmVersionPtr v)
817 * Free the non-public version information returned by the kernel.
819 * \param v pointer to the version information.
822 * Used by drmGetVersion() to free the memory pointed by \p %v as well as all
823 * the non-null strings pointers in it.
825 static void drmFreeKernelVersion(drm_version_t *v)
837 * Copy version information.
839 * \param d destination pointer.
840 * \param s source pointer.
843 * Used by drmGetVersion() to translate the information returned by the ioctl
844 * interface in a private structure into the public structure counterpart.
846 static void drmCopyVersion(drmVersionPtr d, const drm_version_t *s)
848 d->version_major = s->version_major;
849 d->version_minor = s->version_minor;
850 d->version_patchlevel = s->version_patchlevel;
851 d->name_len = s->name_len;
852 d->name = strdup(s->name);
853 d->date_len = s->date_len;
854 d->date = strdup(s->date);
855 d->desc_len = s->desc_len;
856 d->desc = strdup(s->desc);
861 * Query the driver version information.
863 * \param fd file descriptor.
865 * \return pointer to a drmVersion structure which should be freed with
868 * \note Similar information is available via /proc/dri.
871 * It gets the version information via successive DRM_IOCTL_VERSION ioctls,
872 * first with zeros to get the string lengths, and then the actually strings.
873 * It also null-terminates them since they might not be already.
875 drm_public drmVersionPtr drmGetVersion(int fd)
877 drmVersionPtr retval;
878 drm_version_t *version = drmMalloc(sizeof(*version));
880 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
881 drmFreeKernelVersion(version);
885 if (version->name_len)
886 version->name = drmMalloc(version->name_len + 1);
887 if (version->date_len)
888 version->date = drmMalloc(version->date_len + 1);
889 if (version->desc_len)
890 version->desc = drmMalloc(version->desc_len + 1);
892 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
893 drmMsg("DRM_IOCTL_VERSION: %s\n", strerror(errno));
894 drmFreeKernelVersion(version);
898 /* The results might not be null-terminated strings, so terminate them. */
899 if (version->name_len) version->name[version->name_len] = '\0';
900 if (version->date_len) version->date[version->date_len] = '\0';
901 if (version->desc_len) version->desc[version->desc_len] = '\0';
903 retval = drmMalloc(sizeof(*retval));
904 drmCopyVersion(retval, version);
905 drmFreeKernelVersion(version);
911 * Get version information for the DRM user space library.
913 * This version number is driver independent.
915 * \param fd file descriptor.
917 * \return version information.
920 * This function allocates and fills a drm_version structure with a hard coded
923 drm_public drmVersionPtr drmGetLibVersion(int fd)
925 drm_version_t *version = drmMalloc(sizeof(*version));
928 * NOTE THIS MUST NOT GO ABOVE VERSION 1.X due to drivers needing it
929 * revision 1.0.x = original DRM interface with no drmGetLibVersion
930 * entry point and many drm<Device> extensions
931 * revision 1.1.x = added drmCommand entry points for device extensions
932 * added drmGetLibVersion to identify libdrm.a version
933 * revision 1.2.x = added drmSetInterfaceVersion
934 * modified drmOpen to handle both busid and name
935 * revision 1.3.x = added server + memory manager
937 version->version_major = 1;
938 version->version_minor = 3;
939 version->version_patchlevel = 0;
941 return (drmVersionPtr)version;
944 drm_public int drmGetCap(int fd, uint64_t capability, uint64_t *value)
946 struct drm_get_cap cap;
950 cap.capability = capability;
952 ret = drmIoctl(fd, DRM_IOCTL_GET_CAP, &cap);
960 drm_public int drmSetClientCap(int fd, uint64_t capability, uint64_t value)
962 struct drm_set_client_cap cap;
965 cap.capability = capability;
968 return drmIoctl(fd, DRM_IOCTL_SET_CLIENT_CAP, &cap);
972 * Free the bus ID information.
974 * \param busid bus ID information string as given by drmGetBusid().
977 * This function is just frees the memory pointed by \p busid.
979 drm_public void drmFreeBusid(const char *busid)
981 drmFree((void *)busid);
986 * Get the bus ID of the device.
988 * \param fd file descriptor.
990 * \return bus ID string.
993 * This function gets the bus ID via successive DRM_IOCTL_GET_UNIQUE ioctls to
994 * get the string length and data, passing the arguments in a drm_unique
997 drm_public char *drmGetBusid(int fd)
1003 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
1005 u.unique = drmMalloc(u.unique_len + 1);
1006 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u)) {
1010 u.unique[u.unique_len] = '\0';
1017 * Set the bus ID of the device.
1019 * \param fd file descriptor.
1020 * \param busid bus ID string.
1022 * \return zero on success, negative on failure.
1025 * This function is a wrapper around the DRM_IOCTL_SET_UNIQUE ioctl, passing
1026 * the arguments in a drm_unique structure.
1028 drm_public int drmSetBusid(int fd, const char *busid)
1033 u.unique = (char *)busid;
1034 u.unique_len = strlen(busid);
1036 if (drmIoctl(fd, DRM_IOCTL_SET_UNIQUE, &u)) {
1042 drm_public int drmGetMagic(int fd, drm_magic_t * magic)
1049 if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
1051 *magic = auth.magic;
1055 drm_public int drmAuthMagic(int fd, drm_magic_t magic)
1061 if (drmIoctl(fd, DRM_IOCTL_AUTH_MAGIC, &auth))
1067 * Specifies a range of memory that is available for mapping by a
1070 * \param fd file descriptor.
1071 * \param offset usually the physical address. The actual meaning depends of
1072 * the \p type parameter. See below.
1073 * \param size of the memory in bytes.
1074 * \param type type of the memory to be mapped.
1075 * \param flags combination of several flags to modify the function actions.
1076 * \param handle will be set to a value that may be used as the offset
1077 * parameter for mmap().
1079 * \return zero on success or a negative value on error.
1081 * \par Mapping the frame buffer
1082 * For the frame buffer
1083 * - \p offset will be the physical address of the start of the frame buffer,
1084 * - \p size will be the size of the frame buffer in bytes, and
1085 * - \p type will be DRM_FRAME_BUFFER.
1088 * The area mapped will be uncached. If MTRR support is available in the
1089 * kernel, the frame buffer area will be set to write combining.
1091 * \par Mapping the MMIO register area
1092 * For the MMIO register area,
1093 * - \p offset will be the physical address of the start of the register area,
1094 * - \p size will be the size of the register area bytes, and
1095 * - \p type will be DRM_REGISTERS.
1097 * The area mapped will be uncached.
1099 * \par Mapping the SAREA
1101 * - \p offset will be ignored and should be set to zero,
1102 * - \p size will be the desired size of the SAREA in bytes,
1103 * - \p type will be DRM_SHM.
1106 * A shared memory area of the requested size will be created and locked in
1107 * kernel memory. This area may be mapped into client-space by using the handle
1110 * \note May only be called by root.
1113 * This function is a wrapper around the DRM_IOCTL_ADD_MAP ioctl, passing
1114 * the arguments in a drm_map structure.
1116 drm_public int drmAddMap(int fd, drm_handle_t offset, drmSize size, drmMapType type,
1117 drmMapFlags flags, drm_handle_t *handle)
1122 map.offset = offset;
1126 if (drmIoctl(fd, DRM_IOCTL_ADD_MAP, &map))
1129 *handle = (drm_handle_t)(uintptr_t)map.handle;
1133 drm_public int drmRmMap(int fd, drm_handle_t handle)
1138 map.handle = (void *)(uintptr_t)handle;
1140 if(drmIoctl(fd, DRM_IOCTL_RM_MAP, &map))
1146 * Make buffers available for DMA transfers.
1148 * \param fd file descriptor.
1149 * \param count number of buffers.
1150 * \param size size of each buffer.
1151 * \param flags buffer allocation flags.
1152 * \param agp_offset offset in the AGP aperture
1154 * \return number of buffers allocated, negative on error.
1157 * This function is a wrapper around DRM_IOCTL_ADD_BUFS ioctl.
1161 drm_public int drmAddBufs(int fd, int count, int size, drmBufDescFlags flags,
1164 drm_buf_desc_t request;
1167 request.count = count;
1168 request.size = size;
1169 request.flags = flags;
1170 request.agp_start = agp_offset;
1172 if (drmIoctl(fd, DRM_IOCTL_ADD_BUFS, &request))
1174 return request.count;
1177 drm_public int drmMarkBufs(int fd, double low, double high)
1179 drm_buf_info_t info;
1184 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1190 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1193 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1194 int retval = -errno;
1199 for (i = 0; i < info.count; i++) {
1200 info.list[i].low_mark = low * info.list[i].count;
1201 info.list[i].high_mark = high * info.list[i].count;
1202 if (drmIoctl(fd, DRM_IOCTL_MARK_BUFS, &info.list[i])) {
1203 int retval = -errno;
1216 * \param fd file descriptor.
1217 * \param count number of buffers to free.
1218 * \param list list of buffers to be freed.
1220 * \return zero on success, or a negative value on failure.
1222 * \note This function is primarily used for debugging.
1225 * This function is a wrapper around the DRM_IOCTL_FREE_BUFS ioctl, passing
1226 * the arguments in a drm_buf_free structure.
1228 drm_public int drmFreeBufs(int fd, int count, int *list)
1230 drm_buf_free_t request;
1233 request.count = count;
1234 request.list = list;
1235 if (drmIoctl(fd, DRM_IOCTL_FREE_BUFS, &request))
1244 * \param fd file descriptor.
1247 * This function closes the file descriptor.
1249 drm_public int drmClose(int fd)
1251 unsigned long key = drmGetKeyFromFd(fd);
1252 drmHashEntry *entry = drmGetEntry(fd);
1254 drmHashDestroy(entry->tagTable);
1257 entry->tagTable = NULL;
1259 drmHashDelete(drmHashTable, key);
1267 * Map a region of memory.
1269 * \param fd file descriptor.
1270 * \param handle handle returned by drmAddMap().
1271 * \param size size in bytes. Must match the size used by drmAddMap().
1272 * \param address will contain the user-space virtual address where the mapping
1275 * \return zero on success, or a negative value on failure.
1278 * This function is a wrapper for mmap().
1280 drm_public int drmMap(int fd, drm_handle_t handle, drmSize size,
1281 drmAddressPtr address)
1283 static unsigned long pagesize_mask = 0;
1289 pagesize_mask = getpagesize() - 1;
1291 size = (size + pagesize_mask) & ~pagesize_mask;
1293 *address = drm_mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1294 if (*address == MAP_FAILED)
1301 * Unmap mappings obtained with drmMap().
1303 * \param address address as given by drmMap().
1304 * \param size size in bytes. Must match the size used by drmMap().
1306 * \return zero on success, or a negative value on failure.
1309 * This function is a wrapper for munmap().
1311 drm_public int drmUnmap(drmAddress address, drmSize size)
1313 return drm_munmap(address, size);
1316 drm_public drmBufInfoPtr drmGetBufInfo(int fd)
1318 drm_buf_info_t info;
1319 drmBufInfoPtr retval;
1324 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1328 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1331 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1336 retval = drmMalloc(sizeof(*retval));
1337 retval->count = info.count;
1338 retval->list = drmMalloc(info.count * sizeof(*retval->list));
1339 for (i = 0; i < info.count; i++) {
1340 retval->list[i].count = info.list[i].count;
1341 retval->list[i].size = info.list[i].size;
1342 retval->list[i].low_mark = info.list[i].low_mark;
1343 retval->list[i].high_mark = info.list[i].high_mark;
1352 * Map all DMA buffers into client-virtual space.
1354 * \param fd file descriptor.
1356 * \return a pointer to a ::drmBufMap structure.
1358 * \note The client may not use these buffers until obtaining buffer indices
1362 * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1363 * information about the buffers in a drm_buf_map structure into the
1364 * client-visible data structures.
1366 drm_public drmBufMapPtr drmMapBufs(int fd)
1369 drmBufMapPtr retval;
1373 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1379 if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1382 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1387 retval = drmMalloc(sizeof(*retval));
1388 retval->count = bufs.count;
1389 retval->list = drmMalloc(bufs.count * sizeof(*retval->list));
1390 for (i = 0; i < bufs.count; i++) {
1391 retval->list[i].idx = bufs.list[i].idx;
1392 retval->list[i].total = bufs.list[i].total;
1393 retval->list[i].used = 0;
1394 retval->list[i].address = bufs.list[i].address;
1403 * Unmap buffers allocated with drmMapBufs().
1405 * \return zero on success, or negative value on failure.
1408 * Calls munmap() for every buffer stored in \p bufs and frees the
1409 * memory allocated by drmMapBufs().
1411 drm_public int drmUnmapBufs(drmBufMapPtr bufs)
1415 for (i = 0; i < bufs->count; i++) {
1416 drm_munmap(bufs->list[i].address, bufs->list[i].total);
1419 drmFree(bufs->list);
1425 #define DRM_DMA_RETRY 16
1428 * Reserve DMA buffers.
1430 * \param fd file descriptor.
1433 * \return zero on success, or a negative value on failure.
1436 * Assemble the arguments into a drm_dma structure and keeps issuing the
1437 * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1439 drm_public int drmDMA(int fd, drmDMAReqPtr request)
1444 dma.context = request->context;
1445 dma.send_count = request->send_count;
1446 dma.send_indices = request->send_list;
1447 dma.send_sizes = request->send_sizes;
1448 dma.flags = request->flags;
1449 dma.request_count = request->request_count;
1450 dma.request_size = request->request_size;
1451 dma.request_indices = request->request_list;
1452 dma.request_sizes = request->request_sizes;
1453 dma.granted_count = 0;
1456 ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1457 } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1460 request->granted_count = dma.granted_count;
1469 * Obtain heavyweight hardware lock.
1471 * \param fd file descriptor.
1472 * \param context context.
1473 * \param flags flags that determine the state of the hardware when the function
1476 * \return always zero.
1479 * This function translates the arguments into a drm_lock structure and issue
1480 * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1482 drm_public int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
1487 lock.context = context;
1489 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
1490 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
1491 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
1492 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
1493 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
1494 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
1496 while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
1502 * Release the hardware lock.
1504 * \param fd file descriptor.
1505 * \param context context.
1507 * \return zero on success, or a negative value on failure.
1510 * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
1511 * argument in a drm_lock structure.
1513 drm_public int drmUnlock(int fd, drm_context_t context)
1518 lock.context = context;
1519 return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
1522 drm_public drm_context_t *drmGetReservedContextList(int fd, int *count)
1526 drm_context_t * retval;
1530 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1536 if (!(list = drmMalloc(res.count * sizeof(*list))))
1538 if (!(retval = drmMalloc(res.count * sizeof(*retval))))
1541 res.contexts = list;
1542 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1543 goto err_free_context;
1545 for (i = 0; i < res.count; i++)
1546 retval[i] = list[i].handle;
1559 drm_public void drmFreeReservedContextList(drm_context_t *pt)
1567 * Used by the X server during GLXContext initialization. This causes
1568 * per-context kernel-level resources to be allocated.
1570 * \param fd file descriptor.
1571 * \param handle is set on success. To be used by the client when requesting DMA
1572 * dispatch with drmDMA().
1574 * \return zero on success, or a negative value on failure.
1576 * \note May only be called by root.
1579 * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
1580 * argument in a drm_ctx structure.
1582 drm_public int drmCreateContext(int fd, drm_context_t *handle)
1587 if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
1589 *handle = ctx.handle;
1593 drm_public int drmSwitchToContext(int fd, drm_context_t context)
1598 ctx.handle = context;
1599 if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
1604 drm_public int drmSetContextFlags(int fd, drm_context_t context,
1605 drm_context_tFlags flags)
1610 * Context preserving means that no context switches are done between DMA
1611 * buffers from one context and the next. This is suitable for use in the
1612 * X server (which promises to maintain hardware context), or in the
1613 * client-side library when buffers are swapped on behalf of two threads.
1616 ctx.handle = context;
1617 if (flags & DRM_CONTEXT_PRESERVED)
1618 ctx.flags |= _DRM_CONTEXT_PRESERVED;
1619 if (flags & DRM_CONTEXT_2DONLY)
1620 ctx.flags |= _DRM_CONTEXT_2DONLY;
1621 if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
1626 drm_public int drmGetContextFlags(int fd, drm_context_t context,
1627 drm_context_tFlagsPtr flags)
1632 ctx.handle = context;
1633 if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
1636 if (ctx.flags & _DRM_CONTEXT_PRESERVED)
1637 *flags |= DRM_CONTEXT_PRESERVED;
1638 if (ctx.flags & _DRM_CONTEXT_2DONLY)
1639 *flags |= DRM_CONTEXT_2DONLY;
1646 * Free any kernel-level resources allocated with drmCreateContext() associated
1649 * \param fd file descriptor.
1650 * \param handle handle given by drmCreateContext().
1652 * \return zero on success, or a negative value on failure.
1654 * \note May only be called by root.
1657 * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
1658 * argument in a drm_ctx structure.
1660 drm_public int drmDestroyContext(int fd, drm_context_t handle)
1665 ctx.handle = handle;
1666 if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
1671 drm_public int drmCreateDrawable(int fd, drm_drawable_t *handle)
1676 if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
1678 *handle = draw.handle;
1682 drm_public int drmDestroyDrawable(int fd, drm_drawable_t handle)
1687 draw.handle = handle;
1688 if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
1693 drm_public int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
1694 drm_drawable_info_type_t type,
1695 unsigned int num, void *data)
1697 drm_update_draw_t update;
1700 update.handle = handle;
1703 update.data = (unsigned long long)(unsigned long)data;
1705 if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
1711 drm_public int drmCrtcGetSequence(int fd, uint32_t crtcId, uint64_t *sequence,
1714 struct drm_crtc_get_sequence get_seq;
1718 get_seq.crtc_id = crtcId;
1719 ret = drmIoctl(fd, DRM_IOCTL_CRTC_GET_SEQUENCE, &get_seq);
1724 *sequence = get_seq.sequence;
1726 *ns = get_seq.sequence_ns;
1730 drm_public int drmCrtcQueueSequence(int fd, uint32_t crtcId, uint32_t flags,
1732 uint64_t *sequence_queued,
1735 struct drm_crtc_queue_sequence queue_seq;
1738 memclear(queue_seq);
1739 queue_seq.crtc_id = crtcId;
1740 queue_seq.flags = flags;
1741 queue_seq.sequence = sequence;
1742 queue_seq.user_data = user_data;
1744 ret = drmIoctl(fd, DRM_IOCTL_CRTC_QUEUE_SEQUENCE, &queue_seq);
1745 if (ret == 0 && sequence_queued)
1746 *sequence_queued = queue_seq.sequence;
1752 * Acquire the AGP device.
1754 * Must be called before any of the other AGP related calls.
1756 * \param fd file descriptor.
1758 * \return zero on success, or a negative value on failure.
1761 * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
1763 drm_public int drmAgpAcquire(int fd)
1765 if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
1772 * Release the AGP device.
1774 * \param fd file descriptor.
1776 * \return zero on success, or a negative value on failure.
1779 * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
1781 drm_public int drmAgpRelease(int fd)
1783 if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
1792 * \param fd file descriptor.
1793 * \param mode AGP mode.
1795 * \return zero on success, or a negative value on failure.
1798 * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
1799 * argument in a drm_agp_mode structure.
1801 drm_public int drmAgpEnable(int fd, unsigned long mode)
1807 if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
1814 * Allocate a chunk of AGP memory.
1816 * \param fd file descriptor.
1817 * \param size requested memory size in bytes. Will be rounded to page boundary.
1818 * \param type type of memory to allocate.
1819 * \param address if not zero, will be set to the physical address of the
1821 * \param handle on success will be set to a handle of the allocated memory.
1823 * \return zero on success, or a negative value on failure.
1826 * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
1827 * arguments in a drm_agp_buffer structure.
1829 drm_public int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
1830 unsigned long *address, drm_handle_t *handle)
1835 *handle = DRM_AGP_NO_HANDLE;
1838 if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
1841 *address = b.physical;
1848 * Free a chunk of AGP memory.
1850 * \param fd file descriptor.
1851 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1853 * \return zero on success, or a negative value on failure.
1856 * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
1857 * argument in a drm_agp_buffer structure.
1859 drm_public int drmAgpFree(int fd, drm_handle_t handle)
1865 if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
1872 * Bind a chunk of AGP memory.
1874 * \param fd file descriptor.
1875 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1876 * \param offset offset in bytes. It will round to page boundary.
1878 * \return zero on success, or a negative value on failure.
1881 * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
1882 * argument in a drm_agp_binding structure.
1884 drm_public int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
1886 drm_agp_binding_t b;
1891 if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
1898 * Unbind a chunk of AGP memory.
1900 * \param fd file descriptor.
1901 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1903 * \return zero on success, or a negative value on failure.
1906 * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
1907 * the argument in a drm_agp_binding structure.
1909 drm_public int drmAgpUnbind(int fd, drm_handle_t handle)
1911 drm_agp_binding_t b;
1915 if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
1922 * Get AGP driver major version number.
1924 * \param fd file descriptor.
1926 * \return major version number on success, or a negative value on failure..
1929 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1930 * necessary information in a drm_agp_info structure.
1932 drm_public int drmAgpVersionMajor(int fd)
1938 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1940 return i.agp_version_major;
1945 * Get AGP driver minor version number.
1947 * \param fd file descriptor.
1949 * \return minor version number on success, or a negative value on failure.
1952 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1953 * necessary information in a drm_agp_info structure.
1955 drm_public int drmAgpVersionMinor(int fd)
1961 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1963 return i.agp_version_minor;
1970 * \param fd file descriptor.
1972 * \return mode on success, or zero on failure.
1975 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1976 * necessary information in a drm_agp_info structure.
1978 drm_public unsigned long drmAgpGetMode(int fd)
1984 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1991 * Get AGP aperture base.
1993 * \param fd file descriptor.
1995 * \return aperture base on success, zero on failure.
1998 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1999 * necessary information in a drm_agp_info structure.
2001 drm_public unsigned long drmAgpBase(int fd)
2007 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2009 return i.aperture_base;
2014 * Get AGP aperture size.
2016 * \param fd file descriptor.
2018 * \return aperture size on success, zero on failure.
2021 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2022 * necessary information in a drm_agp_info structure.
2024 drm_public unsigned long drmAgpSize(int fd)
2030 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2032 return i.aperture_size;
2037 * Get used AGP memory.
2039 * \param fd file descriptor.
2041 * \return memory used on success, or zero on failure.
2044 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2045 * necessary information in a drm_agp_info structure.
2047 drm_public unsigned long drmAgpMemoryUsed(int fd)
2053 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2055 return i.memory_used;
2060 * Get available AGP memory.
2062 * \param fd file descriptor.
2064 * \return memory available on success, or zero on failure.
2067 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2068 * necessary information in a drm_agp_info structure.
2070 drm_public unsigned long drmAgpMemoryAvail(int fd)
2076 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2078 return i.memory_allowed;
2083 * Get hardware vendor ID.
2085 * \param fd file descriptor.
2087 * \return vendor ID on success, or zero on failure.
2090 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2091 * necessary information in a drm_agp_info structure.
2093 drm_public unsigned int drmAgpVendorId(int fd)
2099 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2106 * Get hardware device ID.
2108 * \param fd file descriptor.
2110 * \return zero on success, or zero on failure.
2113 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2114 * necessary information in a drm_agp_info structure.
2116 drm_public unsigned int drmAgpDeviceId(int fd)
2122 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2127 drm_public int drmScatterGatherAlloc(int fd, unsigned long size,
2128 drm_handle_t *handle)
2130 drm_scatter_gather_t sg;
2136 if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
2138 *handle = sg.handle;
2142 drm_public int drmScatterGatherFree(int fd, drm_handle_t handle)
2144 drm_scatter_gather_t sg;
2148 if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
2156 * \param fd file descriptor.
2157 * \param vbl pointer to a drmVBlank structure.
2159 * \return zero on success, or a negative value on failure.
2162 * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
2164 drm_public int drmWaitVBlank(int fd, drmVBlankPtr vbl)
2166 struct timespec timeout, cur;
2169 ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2171 fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
2177 ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
2178 vbl->request.type &= ~DRM_VBLANK_RELATIVE;
2179 if (ret && errno == EINTR) {
2180 clock_gettime(CLOCK_MONOTONIC, &cur);
2181 /* Timeout after 1s */
2182 if (cur.tv_sec > timeout.tv_sec + 1 ||
2183 (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
2190 } while (ret && errno == EINTR);
2196 drm_public int drmError(int err, const char *label)
2199 case DRM_ERR_NO_DEVICE:
2200 fprintf(stderr, "%s: no device\n", label);
2202 case DRM_ERR_NO_ACCESS:
2203 fprintf(stderr, "%s: no access\n", label);
2205 case DRM_ERR_NOT_ROOT:
2206 fprintf(stderr, "%s: not root\n", label);
2208 case DRM_ERR_INVALID:
2209 fprintf(stderr, "%s: invalid args\n", label);
2214 fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2222 * Install IRQ handler.
2224 * \param fd file descriptor.
2225 * \param irq IRQ number.
2227 * \return zero on success, or a negative value on failure.
2230 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2231 * argument in a drm_control structure.
2233 drm_public int drmCtlInstHandler(int fd, int irq)
2238 ctl.func = DRM_INST_HANDLER;
2240 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2247 * Uninstall IRQ handler.
2249 * \param fd file descriptor.
2251 * \return zero on success, or a negative value on failure.
2254 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2255 * argument in a drm_control structure.
2257 drm_public int drmCtlUninstHandler(int fd)
2262 ctl.func = DRM_UNINST_HANDLER;
2264 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2269 drm_public int drmFinish(int fd, int context, drmLockFlags flags)
2274 lock.context = context;
2275 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
2276 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
2277 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
2278 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
2279 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2280 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2281 if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2287 * Get IRQ from bus ID.
2289 * \param fd file descriptor.
2290 * \param busnum bus number.
2291 * \param devnum device number.
2292 * \param funcnum function number.
2294 * \return IRQ number on success, or a negative value on failure.
2297 * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2298 * arguments in a drm_irq_busid structure.
2300 drm_public int drmGetInterruptFromBusID(int fd, int busnum, int devnum,
2308 p.funcnum = funcnum;
2309 if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2314 drm_public int drmAddContextTag(int fd, drm_context_t context, void *tag)
2316 drmHashEntry *entry = drmGetEntry(fd);
2318 if (drmHashInsert(entry->tagTable, context, tag)) {
2319 drmHashDelete(entry->tagTable, context);
2320 drmHashInsert(entry->tagTable, context, tag);
2325 drm_public int drmDelContextTag(int fd, drm_context_t context)
2327 drmHashEntry *entry = drmGetEntry(fd);
2329 return drmHashDelete(entry->tagTable, context);
2332 drm_public void *drmGetContextTag(int fd, drm_context_t context)
2334 drmHashEntry *entry = drmGetEntry(fd);
2337 if (drmHashLookup(entry->tagTable, context, &value))
2343 drm_public int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2344 drm_handle_t handle)
2346 drm_ctx_priv_map_t map;
2349 map.ctx_id = ctx_id;
2350 map.handle = (void *)(uintptr_t)handle;
2352 if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2357 drm_public int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2358 drm_handle_t *handle)
2360 drm_ctx_priv_map_t map;
2363 map.ctx_id = ctx_id;
2365 if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2368 *handle = (drm_handle_t)(uintptr_t)map.handle;
2373 drm_public int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2374 drmMapType *type, drmMapFlags *flags,
2375 drm_handle_t *handle, int *mtrr)
2381 if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2383 *offset = map.offset;
2387 *handle = (unsigned long)map.handle;
2392 drm_public int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2393 unsigned long *magic, unsigned long *iocs)
2395 drm_client_t client;
2399 if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2401 *auth = client.auth;
2404 *magic = client.magic;
2405 *iocs = client.iocs;
2409 drm_public int drmGetStats(int fd, drmStatsT *stats)
2415 if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2419 memset(stats, 0, sizeof(*stats));
2420 if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2424 stats->data[i].long_format = "%-20.20s"; \
2425 stats->data[i].rate_format = "%8.8s"; \
2426 stats->data[i].isvalue = 1; \
2427 stats->data[i].verbose = 0
2430 stats->data[i].long_format = "%-20.20s"; \
2431 stats->data[i].rate_format = "%5.5s"; \
2432 stats->data[i].isvalue = 0; \
2433 stats->data[i].mult_names = "kgm"; \
2434 stats->data[i].mult = 1000; \
2435 stats->data[i].verbose = 0
2438 stats->data[i].long_format = "%-20.20s"; \
2439 stats->data[i].rate_format = "%5.5s"; \
2440 stats->data[i].isvalue = 0; \
2441 stats->data[i].mult_names = "KGM"; \
2442 stats->data[i].mult = 1024; \
2443 stats->data[i].verbose = 0
2446 stats->count = s.count;
2447 for (i = 0; i < s.count; i++) {
2448 stats->data[i].value = s.data[i].value;
2449 switch (s.data[i].type) {
2450 case _DRM_STAT_LOCK:
2451 stats->data[i].long_name = "Lock";
2452 stats->data[i].rate_name = "Lock";
2455 case _DRM_STAT_OPENS:
2456 stats->data[i].long_name = "Opens";
2457 stats->data[i].rate_name = "O";
2459 stats->data[i].verbose = 1;
2461 case _DRM_STAT_CLOSES:
2462 stats->data[i].long_name = "Closes";
2463 stats->data[i].rate_name = "Lock";
2465 stats->data[i].verbose = 1;
2467 case _DRM_STAT_IOCTLS:
2468 stats->data[i].long_name = "Ioctls";
2469 stats->data[i].rate_name = "Ioc/s";
2472 case _DRM_STAT_LOCKS:
2473 stats->data[i].long_name = "Locks";
2474 stats->data[i].rate_name = "Lck/s";
2477 case _DRM_STAT_UNLOCKS:
2478 stats->data[i].long_name = "Unlocks";
2479 stats->data[i].rate_name = "Unl/s";
2483 stats->data[i].long_name = "IRQs";
2484 stats->data[i].rate_name = "IRQ/s";
2487 case _DRM_STAT_PRIMARY:
2488 stats->data[i].long_name = "Primary Bytes";
2489 stats->data[i].rate_name = "PB/s";
2492 case _DRM_STAT_SECONDARY:
2493 stats->data[i].long_name = "Secondary Bytes";
2494 stats->data[i].rate_name = "SB/s";
2498 stats->data[i].long_name = "DMA";
2499 stats->data[i].rate_name = "DMA/s";
2502 case _DRM_STAT_SPECIAL:
2503 stats->data[i].long_name = "Special DMA";
2504 stats->data[i].rate_name = "dma/s";
2507 case _DRM_STAT_MISSED:
2508 stats->data[i].long_name = "Miss";
2509 stats->data[i].rate_name = "Ms/s";
2512 case _DRM_STAT_VALUE:
2513 stats->data[i].long_name = "Value";
2514 stats->data[i].rate_name = "Value";
2517 case _DRM_STAT_BYTE:
2518 stats->data[i].long_name = "Bytes";
2519 stats->data[i].rate_name = "B/s";
2522 case _DRM_STAT_COUNT:
2524 stats->data[i].long_name = "Count";
2525 stats->data[i].rate_name = "Cnt/s";
2534 * Issue a set-version ioctl.
2536 * \param fd file descriptor.
2537 * \param drmCommandIndex command index
2538 * \param data source pointer of the data to be read and written.
2539 * \param size size of the data to be read and written.
2541 * \return zero on success, or a negative value on failure.
2544 * It issues a read-write ioctl given by
2545 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2547 drm_public int drmSetInterfaceVersion(int fd, drmSetVersion *version)
2550 drm_set_version_t sv;
2553 sv.drm_di_major = version->drm_di_major;
2554 sv.drm_di_minor = version->drm_di_minor;
2555 sv.drm_dd_major = version->drm_dd_major;
2556 sv.drm_dd_minor = version->drm_dd_minor;
2558 if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
2562 version->drm_di_major = sv.drm_di_major;
2563 version->drm_di_minor = sv.drm_di_minor;
2564 version->drm_dd_major = sv.drm_dd_major;
2565 version->drm_dd_minor = sv.drm_dd_minor;
2571 * Send a device-specific command.
2573 * \param fd file descriptor.
2574 * \param drmCommandIndex command index
2576 * \return zero on success, or a negative value on failure.
2579 * It issues a ioctl given by
2580 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2582 drm_public int drmCommandNone(int fd, unsigned long drmCommandIndex)
2584 unsigned long request;
2586 request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
2588 if (drmIoctl(fd, request, NULL)) {
2596 * Send a device-specific read command.
2598 * \param fd file descriptor.
2599 * \param drmCommandIndex command index
2600 * \param data destination pointer of the data to be read.
2601 * \param size size of the data to be read.
2603 * \return zero on success, or a negative value on failure.
2606 * It issues a read ioctl given by
2607 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2609 drm_public int drmCommandRead(int fd, unsigned long drmCommandIndex,
2610 void *data, unsigned long size)
2612 unsigned long request;
2614 request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
2615 DRM_COMMAND_BASE + drmCommandIndex, size);
2617 if (drmIoctl(fd, request, data)) {
2625 * Send a device-specific write command.
2627 * \param fd file descriptor.
2628 * \param drmCommandIndex command index
2629 * \param data source pointer of the data to be written.
2630 * \param size size of the data to be written.
2632 * \return zero on success, or a negative value on failure.
2635 * It issues a write ioctl given by
2636 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2638 drm_public int drmCommandWrite(int fd, unsigned long drmCommandIndex,
2639 void *data, unsigned long size)
2641 unsigned long request;
2643 request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
2644 DRM_COMMAND_BASE + drmCommandIndex, size);
2646 if (drmIoctl(fd, request, data)) {
2654 * Send a device-specific read-write command.
2656 * \param fd file descriptor.
2657 * \param drmCommandIndex command index
2658 * \param data source pointer of the data to be read and written.
2659 * \param size size of the data to be read and written.
2661 * \return zero on success, or a negative value on failure.
2664 * It issues a read-write ioctl given by
2665 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2667 drm_public int drmCommandWriteRead(int fd, unsigned long drmCommandIndex,
2668 void *data, unsigned long size)
2670 unsigned long request;
2672 request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
2673 DRM_COMMAND_BASE + drmCommandIndex, size);
2675 if (drmIoctl(fd, request, data))
2680 #define DRM_MAX_FDS 16
2686 } connection[DRM_MAX_FDS];
2688 static int nr_fds = 0;
2690 drm_public int drmOpenOnce(void *unused, const char *BusID, int *newlyopened)
2692 return drmOpenOnceWithType(BusID, newlyopened, DRM_NODE_PRIMARY);
2695 drm_public int drmOpenOnceWithType(const char *BusID, int *newlyopened,
2701 for (i = 0; i < nr_fds; i++)
2702 if ((strcmp(BusID, connection[i].BusID) == 0) &&
2703 (connection[i].type == type)) {
2704 connection[i].refcount++;
2706 return connection[i].fd;
2709 fd = drmOpenWithType(NULL, BusID, type);
2710 if (fd < 0 || nr_fds == DRM_MAX_FDS)
2713 connection[nr_fds].BusID = strdup(BusID);
2714 connection[nr_fds].fd = fd;
2715 connection[nr_fds].refcount = 1;
2716 connection[nr_fds].type = type;
2720 fprintf(stderr, "saved connection %d for %s %d\n",
2721 nr_fds, connection[nr_fds].BusID,
2722 strcmp(BusID, connection[nr_fds].BusID));
2729 drm_public void drmCloseOnce(int fd)
2733 for (i = 0; i < nr_fds; i++) {
2734 if (fd == connection[i].fd) {
2735 if (--connection[i].refcount == 0) {
2736 drmClose(connection[i].fd);
2737 free(connection[i].BusID);
2740 connection[i] = connection[nr_fds];
2748 drm_public int drmSetMaster(int fd)
2750 return drmIoctl(fd, DRM_IOCTL_SET_MASTER, NULL);
2753 drm_public int drmDropMaster(int fd)
2755 return drmIoctl(fd, DRM_IOCTL_DROP_MASTER, NULL);
2758 drm_public int drmIsMaster(int fd)
2760 /* Detect master by attempting something that requires master.
2762 * Authenticating magic tokens requires master and 0 is an
2763 * internal kernel detail which we could use. Attempting this on
2764 * a master fd would fail therefore fail with EINVAL because 0
2767 * A non-master fd will fail with EACCES, as the kernel checks
2768 * for master before attempting to do anything else.
2770 * Since we don't want to leak implementation details, use
2773 return drmAuthMagic(fd, 0) != -EACCES;
2776 drm_public char *drmGetDeviceNameFromFd(int fd)
2783 if (fstat(fd, &sbuf))
2786 maj = major(sbuf.st_rdev);
2787 min = minor(sbuf.st_rdev);
2788 nodetype = drmGetMinorType(maj, min);
2789 return drmGetMinorNameForFD(fd, nodetype);
2796 /* The whole drmOpen thing is a fiasco and we need to find a way
2797 * back to just using open(2). For now, however, lets just make
2798 * things worse with even more ad hoc directory walking code to
2799 * discover the device file name. */
2804 for (i = 0; i < DRM_MAX_MINOR; i++) {
2805 snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
2806 if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
2809 if (i == DRM_MAX_MINOR)
2812 return strdup(name);
2816 static bool drmNodeIsDRM(int maj, int min)
2822 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device/drm",
2824 return stat(path, &sbuf) == 0;
2826 char name[SPECNAMELEN];
2828 if (!devname_r(makedev(maj, min), S_IFCHR, name, sizeof(name)))
2830 /* Handle drm/ and dri/ as both are present in different FreeBSD version
2831 * FreeBSD on amd64/i386/powerpc external kernel modules create node in
2832 * in /dev/drm/ and links in /dev/dri while a WIP in kernel driver creates
2833 * only device nodes in /dev/dri/ */
2834 return (!strncmp(name, "drm/", 4) || !strncmp(name, "dri/", 4));
2836 return maj == DRM_MAJOR;
2840 drm_public int drmGetNodeTypeFromFd(int fd)
2845 if (fstat(fd, &sbuf))
2848 maj = major(sbuf.st_rdev);
2849 min = minor(sbuf.st_rdev);
2851 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode)) {
2856 type = drmGetMinorType(maj, min);
2862 drm_public int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags,
2865 struct drm_prime_handle args;
2870 args.handle = handle;
2872 ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
2876 *prime_fd = args.fd;
2880 drm_public int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
2882 struct drm_prime_handle args;
2887 ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
2891 *handle = args.handle;
2895 static char *drmGetMinorNameForFD(int fd, int type)
2901 const char *name = drmGetMinorName(type);
2903 char dev_name[64], buf[64];
2911 if (fstat(fd, &sbuf))
2914 maj = major(sbuf.st_rdev);
2915 min = minor(sbuf.st_rdev);
2917 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
2920 snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
2922 sysdir = opendir(buf);
2926 while ((ent = readdir(sysdir))) {
2927 if (strncmp(ent->d_name, name, len) == 0) {
2928 snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
2932 return strdup(dev_name);
2940 char dname[SPECNAMELEN];
2942 char name[SPECNAMELEN];
2943 int id, maj, min, nodetype, i;
2945 if (fstat(fd, &sbuf))
2948 maj = major(sbuf.st_rdev);
2949 min = minor(sbuf.st_rdev);
2951 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
2954 if (!devname_r(sbuf.st_rdev, S_IFCHR, dname, sizeof(dname)))
2957 /* Handle both /dev/drm and /dev/dri
2958 * FreeBSD on amd64/i386/powerpc external kernel modules create node in
2959 * in /dev/drm/ and links in /dev/dri while a WIP in kernel driver creates
2960 * only device nodes in /dev/dri/ */
2962 /* Get the node type represented by fd so we can deduce the target name */
2963 nodetype = drmGetMinorType(maj, min);
2966 mname = drmGetMinorName(type);
2968 for (i = 0; i < SPECNAMELEN; i++) {
2969 if (isalpha(dname[i]) == 0 && dname[i] != '/')
2972 if (dname[i] == '\0')
2975 id = (int)strtol(&dname[i], NULL, 10);
2976 id -= drmGetMinorBase(nodetype);
2977 snprintf(name, sizeof(name), DRM_DIR_NAME "/%s%d", mname,
2978 id + drmGetMinorBase(type));
2980 return strdup(name);
2983 char buf[PATH_MAX + 1];
2984 const char *dev_name = drmGetDeviceName(type);
2985 unsigned int maj, min;
2988 if (fstat(fd, &sbuf))
2991 maj = major(sbuf.st_rdev);
2992 min = minor(sbuf.st_rdev);
2994 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3000 n = snprintf(buf, sizeof(buf), dev_name, DRM_DIR_NAME, min);
3001 if (n == -1 || n >= sizeof(buf))
3008 drm_public char *drmGetPrimaryDeviceNameFromFd(int fd)
3010 return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
3013 drm_public char *drmGetRenderDeviceNameFromFd(int fd)
3015 return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
3019 static char * DRM_PRINTFLIKE(2, 3)
3020 sysfs_uevent_get(const char *path, const char *fmt, ...)
3022 char filename[PATH_MAX + 1], *key, *line = NULL, *value = NULL;
3023 size_t size = 0, len;
3029 num = vasprintf(&key, fmt, ap);
3033 snprintf(filename, sizeof(filename), "%s/uevent", path);
3035 fp = fopen(filename, "r");
3041 while ((num = getline(&line, &size, fp)) >= 0) {
3042 if ((strncmp(line, key, len) == 0) && (line[len] == '=')) {
3043 char *start = line + len + 1, *end = line + num - 1;
3048 value = strndup(start, end - start);
3062 /* Little white lie to avoid major rework of the existing code */
3063 #define DRM_BUS_VIRTIO 0x10
3066 static int get_subsystem_type(const char *device_path)
3068 char path[PATH_MAX + 1] = "";
3069 char link[PATH_MAX + 1] = "";
3075 { "/pci", DRM_BUS_PCI },
3076 { "/usb", DRM_BUS_USB },
3077 { "/platform", DRM_BUS_PLATFORM },
3078 { "/spi", DRM_BUS_PLATFORM },
3079 { "/host1x", DRM_BUS_HOST1X },
3080 { "/virtio", DRM_BUS_VIRTIO },
3083 strncpy(path, device_path, PATH_MAX);
3084 strncat(path, "/subsystem", PATH_MAX);
3086 if (readlink(path, link, PATH_MAX) < 0)
3089 name = strrchr(link, '/');
3093 for (unsigned i = 0; i < ARRAY_SIZE(bus_types); i++) {
3094 if (strncmp(name, bus_types[i].name, strlen(bus_types[i].name)) == 0)
3095 return bus_types[i].bus_type;
3102 static int drmParseSubsystemType(int maj, int min)
3105 char path[PATH_MAX + 1] = "";
3106 char real_path[PATH_MAX + 1] = "";
3109 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3111 subsystem_type = get_subsystem_type(path);
3112 /* Try to get the parent (underlying) device type */
3113 if (subsystem_type == DRM_BUS_VIRTIO) {
3114 /* Assume virtio-pci on error */
3115 if (!realpath(path, real_path))
3116 return DRM_BUS_VIRTIO;
3117 strncat(path, "/..", PATH_MAX);
3118 subsystem_type = get_subsystem_type(path);
3119 if (subsystem_type < 0)
3120 return DRM_BUS_VIRTIO;
3122 return subsystem_type;
3123 #elif defined(__OpenBSD__) || defined(__DragonFly__) || defined(__FreeBSD__)
3126 #warning "Missing implementation of drmParseSubsystemType"
3133 get_pci_path(int maj, int min, char *pci_path)
3135 char path[PATH_MAX + 1], *term;
3137 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3138 if (!realpath(path, pci_path)) {
3139 strcpy(pci_path, path);
3143 term = strrchr(pci_path, '/');
3144 if (term && strncmp(term, "/virtio", 7) == 0)
3150 static int get_sysctl_pci_bus_info(int maj, int min, drmPciBusInfoPtr info)
3152 char dname[SPECNAMELEN];
3153 char sysctl_name[16];
3154 char sysctl_val[256];
3156 int id, type, nelem;
3157 unsigned int rdev, majmin, domain, bus, dev, func;
3159 rdev = makedev(maj, min);
3160 if (!devname_r(rdev, S_IFCHR, dname, sizeof(dname)))
3163 if (sscanf(dname, "drm/%d\n", &id) != 1)
3165 type = drmGetMinorType(maj, min);
3169 /* BUG: This above section is iffy, since it mandates that a driver will
3170 * create both card and render node.
3171 * If it does not, the next DRM device will create card#X and
3172 * renderD#(128+X)-1.
3173 * This is a possibility in FreeBSD but for now there is no good way for
3174 * obtaining the info.
3177 case DRM_NODE_PRIMARY:
3179 case DRM_NODE_CONTROL:
3182 case DRM_NODE_RENDER:
3189 if (snprintf(sysctl_name, sizeof(sysctl_name), "hw.dri.%d.busid", id) <= 0)
3191 sysctl_len = sizeof(sysctl_val);
3192 if (sysctlbyname(sysctl_name, sysctl_val, &sysctl_len, NULL, 0))
3195 #define bus_fmt "pci:%04x:%02x:%02x.%u"
3197 nelem = sscanf(sysctl_val, bus_fmt, &domain, &bus, &dev, &func);
3200 info->domain = domain;
3209 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
3212 unsigned int domain, bus, dev, func;
3213 char pci_path[PATH_MAX + 1], *value;
3216 get_pci_path(maj, min, pci_path);
3218 value = sysfs_uevent_get(pci_path, "PCI_SLOT_NAME");
3222 num = sscanf(value, "%04x:%02x:%02x.%1u", &domain, &bus, &dev, &func);
3228 info->domain = domain;
3234 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3235 struct drm_pciinfo pinfo;
3238 type = drmGetMinorType(maj, min);
3242 fd = drmOpenMinor(min, 0, type);
3246 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3252 info->domain = pinfo.domain;
3253 info->bus = pinfo.bus;
3254 info->dev = pinfo.dev;
3255 info->func = pinfo.func;
3259 return get_sysctl_pci_bus_info(maj, min, info);
3261 #warning "Missing implementation of drmParsePciBusInfo"
3266 drm_public int drmDevicesEqual(drmDevicePtr a, drmDevicePtr b)
3268 if (a == NULL || b == NULL)
3271 if (a->bustype != b->bustype)
3274 switch (a->bustype) {
3276 return memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo)) == 0;
3279 return memcmp(a->businfo.usb, b->businfo.usb, sizeof(drmUsbBusInfo)) == 0;
3281 case DRM_BUS_PLATFORM:
3282 return memcmp(a->businfo.platform, b->businfo.platform, sizeof(drmPlatformBusInfo)) == 0;
3284 case DRM_BUS_HOST1X:
3285 return memcmp(a->businfo.host1x, b->businfo.host1x, sizeof(drmHost1xBusInfo)) == 0;
3294 static int drmGetNodeType(const char *name)
3296 if (strncmp(name, DRM_CONTROL_MINOR_NAME,
3297 sizeof(DRM_CONTROL_MINOR_NAME ) - 1) == 0)
3298 return DRM_NODE_CONTROL;
3300 if (strncmp(name, DRM_RENDER_MINOR_NAME,
3301 sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
3302 return DRM_NODE_RENDER;
3304 if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
3305 sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
3306 return DRM_NODE_PRIMARY;
3311 static int drmGetMaxNodeName(void)
3313 return sizeof(DRM_DIR_NAME) +
3314 MAX3(sizeof(DRM_PRIMARY_MINOR_NAME),
3315 sizeof(DRM_CONTROL_MINOR_NAME),
3316 sizeof(DRM_RENDER_MINOR_NAME)) +
3317 3 /* length of the node number */;
3321 static int parse_separate_sysfs_files(int maj, int min,
3322 drmPciDeviceInfoPtr device,
3323 bool ignore_revision)
3325 static const char *attrs[] = {
3326 "revision", /* Older kernels are missing the file, so check for it first */
3332 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3333 unsigned int data[ARRAY_SIZE(attrs)];
3337 get_pci_path(maj, min, pci_path);
3339 for (unsigned i = ignore_revision ? 1 : 0; i < ARRAY_SIZE(attrs); i++) {
3340 snprintf(path, PATH_MAX, "%s/%s", pci_path, attrs[i]);
3341 fp = fopen(path, "r");
3345 ret = fscanf(fp, "%x", &data[i]);
3352 device->revision_id = ignore_revision ? 0xff : data[0] & 0xff;
3353 device->vendor_id = data[1] & 0xffff;
3354 device->device_id = data[2] & 0xffff;
3355 device->subvendor_id = data[3] & 0xffff;
3356 device->subdevice_id = data[4] & 0xffff;
3361 static int parse_config_sysfs_file(int maj, int min,
3362 drmPciDeviceInfoPtr device)
3364 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3365 unsigned char config[64];
3368 get_pci_path(maj, min, pci_path);
3370 snprintf(path, PATH_MAX, "%s/config", pci_path);
3371 fd = open(path, O_RDONLY);
3375 ret = read(fd, config, sizeof(config));
3380 device->vendor_id = config[0] | (config[1] << 8);
3381 device->device_id = config[2] | (config[3] << 8);
3382 device->revision_id = config[8];
3383 device->subvendor_id = config[44] | (config[45] << 8);
3384 device->subdevice_id = config[46] | (config[47] << 8);
3390 static int drmParsePciDeviceInfo(int maj, int min,
3391 drmPciDeviceInfoPtr device,
3395 if (!(flags & DRM_DEVICE_GET_PCI_REVISION))
3396 return parse_separate_sysfs_files(maj, min, device, true);
3398 if (parse_separate_sysfs_files(maj, min, device, false))
3399 return parse_config_sysfs_file(maj, min, device);
3402 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3403 struct drm_pciinfo pinfo;
3406 type = drmGetMinorType(maj, min);
3410 fd = drmOpenMinor(min, 0, type);
3414 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3420 device->vendor_id = pinfo.vendor_id;
3421 device->device_id = pinfo.device_id;
3422 device->revision_id = pinfo.revision_id;
3423 device->subvendor_id = pinfo.subvendor_id;
3424 device->subdevice_id = pinfo.subdevice_id;
3429 struct pci_conf_io pc;
3430 struct pci_match_conf patterns[1];
3431 struct pci_conf results[1];
3434 if (get_sysctl_pci_bus_info(maj, min, &info) != 0)
3437 fd = open("/dev/pci", O_RDONLY, 0);
3441 bzero(&patterns, sizeof(patterns));
3442 patterns[0].pc_sel.pc_domain = info.domain;
3443 patterns[0].pc_sel.pc_bus = info.bus;
3444 patterns[0].pc_sel.pc_dev = info.dev;
3445 patterns[0].pc_sel.pc_func = info.func;
3446 patterns[0].flags = PCI_GETCONF_MATCH_DOMAIN | PCI_GETCONF_MATCH_BUS
3447 | PCI_GETCONF_MATCH_DEV | PCI_GETCONF_MATCH_FUNC;
3448 bzero(&pc, sizeof(struct pci_conf_io));
3449 pc.num_patterns = 1;
3450 pc.pat_buf_len = sizeof(patterns);
3451 pc.patterns = patterns;
3452 pc.match_buf_len = sizeof(results);
3453 pc.matches = results;
3455 if (ioctl(fd, PCIOCGETCONF, &pc) || pc.status == PCI_GETCONF_ERROR) {
3462 device->vendor_id = results[0].pc_vendor;
3463 device->device_id = results[0].pc_device;
3464 device->subvendor_id = results[0].pc_subvendor;
3465 device->subdevice_id = results[0].pc_subdevice;
3466 device->revision_id = results[0].pc_revid;
3470 #warning "Missing implementation of drmParsePciDeviceInfo"
3475 static void drmFreePlatformDevice(drmDevicePtr device)
3477 if (device->deviceinfo.platform) {
3478 if (device->deviceinfo.platform->compatible) {
3479 char **compatible = device->deviceinfo.platform->compatible;
3481 while (*compatible) {
3486 free(device->deviceinfo.platform->compatible);
3491 static void drmFreeHost1xDevice(drmDevicePtr device)
3493 if (device->deviceinfo.host1x) {
3494 if (device->deviceinfo.host1x->compatible) {
3495 char **compatible = device->deviceinfo.host1x->compatible;
3497 while (*compatible) {
3502 free(device->deviceinfo.host1x->compatible);
3507 drm_public void drmFreeDevice(drmDevicePtr *device)
3513 switch ((*device)->bustype) {
3514 case DRM_BUS_PLATFORM:
3515 drmFreePlatformDevice(*device);
3518 case DRM_BUS_HOST1X:
3519 drmFreeHost1xDevice(*device);
3528 drm_public void drmFreeDevices(drmDevicePtr devices[], int count)
3532 if (devices == NULL)
3535 for (i = 0; i < count; i++)
3537 drmFreeDevice(&devices[i]);
3540 static drmDevicePtr drmDeviceAlloc(unsigned int type, const char *node,
3541 size_t bus_size, size_t device_size,
3544 size_t max_node_length, extra, size;
3545 drmDevicePtr device;
3549 max_node_length = ALIGN(drmGetMaxNodeName(), sizeof(void *));
3550 extra = DRM_NODE_MAX * (sizeof(void *) + max_node_length);
3552 size = sizeof(*device) + extra + bus_size + device_size;
3554 device = calloc(1, size);
3558 device->available_nodes = 1 << type;
3560 ptr = (char *)device + sizeof(*device);
3561 device->nodes = (char **)ptr;
3563 ptr += DRM_NODE_MAX * sizeof(void *);
3565 for (i = 0; i < DRM_NODE_MAX; i++) {
3566 device->nodes[i] = ptr;
3567 ptr += max_node_length;
3570 memcpy(device->nodes[type], node, max_node_length);
3577 static int drmProcessPciDevice(drmDevicePtr *device,
3578 const char *node, int node_type,
3579 int maj, int min, bool fetch_deviceinfo,
3586 dev = drmDeviceAlloc(node_type, node, sizeof(drmPciBusInfo),
3587 sizeof(drmPciDeviceInfo), &addr);
3591 dev->bustype = DRM_BUS_PCI;
3593 dev->businfo.pci = (drmPciBusInfoPtr)addr;
3595 ret = drmParsePciBusInfo(maj, min, dev->businfo.pci);
3599 // Fetch the device info if the user has requested it
3600 if (fetch_deviceinfo) {
3601 addr += sizeof(drmPciBusInfo);
3602 dev->deviceinfo.pci = (drmPciDeviceInfoPtr)addr;
3604 ret = drmParsePciDeviceInfo(maj, min, dev->deviceinfo.pci, flags);
3619 static int drm_usb_dev_path(int maj, int min, char *path, size_t len)
3621 char *value, *tmp_path, *slash;
3623 snprintf(path, len, "/sys/dev/char/%d:%d/device", maj, min);
3625 value = sysfs_uevent_get(path, "DEVTYPE");
3629 if (strcmp(value, "usb_device") == 0)
3631 if (strcmp(value, "usb_interface") != 0)
3634 /* The parent of a usb_interface is a usb_device */
3636 tmp_path = realpath(path, NULL);
3640 slash = strrchr(tmp_path, '/');
3648 if (snprintf(path, len, "%s", tmp_path) >= (int)len) {
3658 static int drmParseUsbBusInfo(int maj, int min, drmUsbBusInfoPtr info)
3661 char path[PATH_MAX + 1], *value;
3662 unsigned int bus, dev;
3665 ret = drm_usb_dev_path(maj, min, path, sizeof(path));
3669 value = sysfs_uevent_get(path, "BUSNUM");
3673 ret = sscanf(value, "%03u", &bus);
3679 value = sysfs_uevent_get(path, "DEVNUM");
3683 ret = sscanf(value, "%03u", &dev);
3694 #warning "Missing implementation of drmParseUsbBusInfo"
3699 static int drmParseUsbDeviceInfo(int maj, int min, drmUsbDeviceInfoPtr info)
3702 char path[PATH_MAX + 1], *value;
3703 unsigned int vendor, product;
3706 ret = drm_usb_dev_path(maj, min, path, sizeof(path));
3710 value = sysfs_uevent_get(path, "PRODUCT");
3714 ret = sscanf(value, "%x/%x", &vendor, &product);
3720 info->vendor = vendor;
3721 info->product = product;
3725 #warning "Missing implementation of drmParseUsbDeviceInfo"
3730 static int drmProcessUsbDevice(drmDevicePtr *device, const char *node,
3731 int node_type, int maj, int min,
3732 bool fetch_deviceinfo, uint32_t flags)
3738 dev = drmDeviceAlloc(node_type, node, sizeof(drmUsbBusInfo),
3739 sizeof(drmUsbDeviceInfo), &ptr);
3743 dev->bustype = DRM_BUS_USB;
3745 dev->businfo.usb = (drmUsbBusInfoPtr)ptr;
3747 ret = drmParseUsbBusInfo(maj, min, dev->businfo.usb);
3751 if (fetch_deviceinfo) {
3752 ptr += sizeof(drmUsbBusInfo);
3753 dev->deviceinfo.usb = (drmUsbDeviceInfoPtr)ptr;
3755 ret = drmParseUsbDeviceInfo(maj, min, dev->deviceinfo.usb);
3769 static int drmParseOFBusInfo(int maj, int min, char *fullname)
3772 char path[PATH_MAX + 1], *name, *tmp_name;
3774 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3776 name = sysfs_uevent_get(path, "OF_FULLNAME");
3779 /* If the device lacks OF data, pick the MODALIAS info */
3780 name = sysfs_uevent_get(path, "MODALIAS");
3784 /* .. and strip the MODALIAS=[platform,usb...]: part. */
3785 tmp_name = strrchr(name, ':');
3793 strncpy(fullname, tmp_name, DRM_PLATFORM_DEVICE_NAME_LEN);
3794 fullname[DRM_PLATFORM_DEVICE_NAME_LEN - 1] = '\0';
3799 #warning "Missing implementation of drmParseOFBusInfo"
3804 static int drmParseOFDeviceInfo(int maj, int min, char ***compatible)
3807 char path[PATH_MAX + 1], *value, *tmp_name;
3808 unsigned int count, i;
3811 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3813 value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
3815 sscanf(value, "%u", &count);
3818 /* Assume one entry if the device lack OF data */
3822 *compatible = calloc(count + 1, sizeof(char *));
3826 for (i = 0; i < count; i++) {
3827 value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
3830 /* If the device lacks OF data, pick the MODALIAS info */
3831 value = sysfs_uevent_get(path, "MODALIAS");
3837 /* .. and strip the MODALIAS=[platform,usb...]: part. */
3838 tmp_name = strrchr(value, ':');
3843 tmp_name = strdup(tmp_name + 1);
3847 (*compatible)[i] = tmp_name;
3854 free((*compatible)[i]);
3859 #warning "Missing implementation of drmParseOFDeviceInfo"
3864 static int drmProcessPlatformDevice(drmDevicePtr *device,
3865 const char *node, int node_type,
3866 int maj, int min, bool fetch_deviceinfo,
3873 dev = drmDeviceAlloc(node_type, node, sizeof(drmPlatformBusInfo),
3874 sizeof(drmPlatformDeviceInfo), &ptr);
3878 dev->bustype = DRM_BUS_PLATFORM;
3880 dev->businfo.platform = (drmPlatformBusInfoPtr)ptr;
3882 ret = drmParseOFBusInfo(maj, min, dev->businfo.platform->fullname);
3886 if (fetch_deviceinfo) {
3887 ptr += sizeof(drmPlatformBusInfo);
3888 dev->deviceinfo.platform = (drmPlatformDeviceInfoPtr)ptr;
3890 ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.platform->compatible);
3904 static int drmProcessHost1xDevice(drmDevicePtr *device,
3905 const char *node, int node_type,
3906 int maj, int min, bool fetch_deviceinfo,
3913 dev = drmDeviceAlloc(node_type, node, sizeof(drmHost1xBusInfo),
3914 sizeof(drmHost1xDeviceInfo), &ptr);
3918 dev->bustype = DRM_BUS_HOST1X;
3920 dev->businfo.host1x = (drmHost1xBusInfoPtr)ptr;
3922 ret = drmParseOFBusInfo(maj, min, dev->businfo.host1x->fullname);
3926 if (fetch_deviceinfo) {
3927 ptr += sizeof(drmHost1xBusInfo);
3928 dev->deviceinfo.host1x = (drmHost1xDeviceInfoPtr)ptr;
3930 ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.host1x->compatible);
3945 process_device(drmDevicePtr *device, const char *d_name,
3946 int req_subsystem_type,
3947 bool fetch_deviceinfo, uint32_t flags)
3950 char node[PATH_MAX + 1];
3951 int node_type, subsystem_type;
3952 unsigned int maj, min;
3954 node_type = drmGetNodeType(d_name);
3958 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, d_name);
3959 if (stat(node, &sbuf))
3962 maj = major(sbuf.st_rdev);
3963 min = minor(sbuf.st_rdev);
3965 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3968 subsystem_type = drmParseSubsystemType(maj, min);
3969 if (req_subsystem_type != -1 && req_subsystem_type != subsystem_type)
3972 switch (subsystem_type) {
3974 case DRM_BUS_VIRTIO:
3975 return drmProcessPciDevice(device, node, node_type, maj, min,
3976 fetch_deviceinfo, flags);
3978 return drmProcessUsbDevice(device, node, node_type, maj, min,
3979 fetch_deviceinfo, flags);
3980 case DRM_BUS_PLATFORM:
3981 return drmProcessPlatformDevice(device, node, node_type, maj, min,
3982 fetch_deviceinfo, flags);
3983 case DRM_BUS_HOST1X:
3984 return drmProcessHost1xDevice(device, node, node_type, maj, min,
3985 fetch_deviceinfo, flags);
3991 /* Consider devices located on the same bus as duplicate and fold the respective
3992 * entries into a single one.
3994 * Note: this leaves "gaps" in the array, while preserving the length.
3996 static void drmFoldDuplicatedDevices(drmDevicePtr local_devices[], int count)
3998 int node_type, i, j;
4000 for (i = 0; i < count; i++) {
4001 for (j = i + 1; j < count; j++) {
4002 if (drmDevicesEqual(local_devices[i], local_devices[j])) {
4003 local_devices[i]->available_nodes |= local_devices[j]->available_nodes;
4004 node_type = log2(local_devices[j]->available_nodes);
4005 memcpy(local_devices[i]->nodes[node_type],
4006 local_devices[j]->nodes[node_type], drmGetMaxNodeName());
4007 drmFreeDevice(&local_devices[j]);
4013 /* Check that the given flags are valid returning 0 on success */
4015 drm_device_validate_flags(uint32_t flags)
4017 return (flags & ~DRM_DEVICE_GET_PCI_REVISION);
4021 drm_device_has_rdev(drmDevicePtr device, dev_t find_rdev)
4025 for (int i = 0; i < DRM_NODE_MAX; i++) {
4026 if (device->available_nodes & 1 << i) {
4027 if (stat(device->nodes[i], &sbuf) == 0 &&
4028 sbuf.st_rdev == find_rdev)
4036 * The kernel drm core has a number of places that assume maximum of
4037 * 3x64 devices nodes. That's 64 for each of primary, control and
4038 * render nodes. Rounded it up to 256 for simplicity.
4040 #define MAX_DRM_NODES 256
4043 * Get information about the opened drm device
4045 * \param fd file descriptor of the drm device
4046 * \param flags feature/behaviour bitmask
4047 * \param device the address of a drmDevicePtr where the information
4048 * will be allocated in stored
4050 * \return zero on success, negative error code otherwise.
4052 * \note Unlike drmGetDevice it does not retrieve the pci device revision field
4053 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
4055 drm_public int drmGetDevice2(int fd, uint32_t flags, drmDevicePtr *device)
4059 * DRI device nodes on OpenBSD are not in their own directory, they reside
4060 * in /dev along with a large number of statically generated /dev nodes.
4061 * Avoid stat'ing all of /dev needlessly by implementing this custom path.
4065 char node[PATH_MAX + 1];
4066 const char *dev_name;
4067 int node_type, subsystem_type;
4068 int maj, min, n, ret;
4070 if (fd == -1 || device == NULL)
4073 if (fstat(fd, &sbuf))
4076 maj = major(sbuf.st_rdev);
4077 min = minor(sbuf.st_rdev);
4079 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4082 node_type = drmGetMinorType(maj, min);
4083 if (node_type == -1)
4086 dev_name = drmGetDeviceName(node_type);
4090 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min);
4091 if (n == -1 || n >= PATH_MAX)
4093 if (stat(node, &sbuf))
4096 subsystem_type = drmParseSubsystemType(maj, min);
4097 if (subsystem_type != DRM_BUS_PCI)
4100 ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
4108 drmDevicePtr local_devices[MAX_DRM_NODES];
4111 struct dirent *dent;
4115 int ret, i, node_count;
4118 if (drm_device_validate_flags(flags))
4121 if (fd == -1 || device == NULL)
4124 if (fstat(fd, &sbuf))
4127 find_rdev = sbuf.st_rdev;
4128 maj = major(sbuf.st_rdev);
4129 min = minor(sbuf.st_rdev);
4131 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4134 subsystem_type = drmParseSubsystemType(maj, min);
4135 if (subsystem_type < 0)
4136 return subsystem_type;
4138 sysdir = opendir(DRM_DIR_NAME);
4143 while ((dent = readdir(sysdir))) {
4144 ret = process_device(&d, dent->d_name, subsystem_type, true, flags);
4148 if (i >= MAX_DRM_NODES) {
4149 fprintf(stderr, "More than %d drm nodes detected. "
4150 "Please report a bug - that should not happen.\n"
4151 "Skipping extra nodes\n", MAX_DRM_NODES);
4154 local_devices[i] = d;
4159 drmFoldDuplicatedDevices(local_devices, node_count);
4163 for (i = 0; i < node_count; i++) {
4164 if (!local_devices[i])
4167 if (drm_device_has_rdev(local_devices[i], find_rdev))
4168 *device = local_devices[i];
4170 drmFreeDevice(&local_devices[i]);
4174 if (*device == NULL)
4181 * Get information about the opened drm device
4183 * \param fd file descriptor of the drm device
4184 * \param device the address of a drmDevicePtr where the information
4185 * will be allocated in stored
4187 * \return zero on success, negative error code otherwise.
4189 drm_public int drmGetDevice(int fd, drmDevicePtr *device)
4191 return drmGetDevice2(fd, DRM_DEVICE_GET_PCI_REVISION, device);
4195 * Get drm devices on the system
4197 * \param flags feature/behaviour bitmask
4198 * \param devices the array of devices with drmDevicePtr elements
4199 * can be NULL to get the device number first
4200 * \param max_devices the maximum number of devices for the array
4202 * \return on error - negative error code,
4203 * if devices is NULL - total number of devices available on the system,
4204 * alternatively the number of devices stored in devices[], which is
4205 * capped by the max_devices.
4207 * \note Unlike drmGetDevices it does not retrieve the pci device revision field
4208 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
4210 drm_public int drmGetDevices2(uint32_t flags, drmDevicePtr devices[],
4213 drmDevicePtr local_devices[MAX_DRM_NODES];
4214 drmDevicePtr device;
4216 struct dirent *dent;
4217 int ret, i, node_count, device_count;
4219 if (drm_device_validate_flags(flags))
4222 sysdir = opendir(DRM_DIR_NAME);
4227 while ((dent = readdir(sysdir))) {
4228 ret = process_device(&device, dent->d_name, -1, devices != NULL, flags);
4232 if (i >= MAX_DRM_NODES) {
4233 fprintf(stderr, "More than %d drm nodes detected. "
4234 "Please report a bug - that should not happen.\n"
4235 "Skipping extra nodes\n", MAX_DRM_NODES);
4238 local_devices[i] = device;
4243 drmFoldDuplicatedDevices(local_devices, node_count);
4246 for (i = 0; i < node_count; i++) {
4247 if (!local_devices[i])
4250 if ((devices != NULL) && (device_count < max_devices))
4251 devices[device_count] = local_devices[i];
4253 drmFreeDevice(&local_devices[i]);
4259 return device_count;
4263 * Get drm devices on the system
4265 * \param devices the array of devices with drmDevicePtr elements
4266 * can be NULL to get the device number first
4267 * \param max_devices the maximum number of devices for the array
4269 * \return on error - negative error code,
4270 * if devices is NULL - total number of devices available on the system,
4271 * alternatively the number of devices stored in devices[], which is
4272 * capped by the max_devices.
4274 drm_public int drmGetDevices(drmDevicePtr devices[], int max_devices)
4276 return drmGetDevices2(DRM_DEVICE_GET_PCI_REVISION, devices, max_devices);
4279 drm_public char *drmGetDeviceNameFromFd2(int fd)
4283 char path[PATH_MAX + 1], *value;
4284 unsigned int maj, min;
4286 if (fstat(fd, &sbuf))
4289 maj = major(sbuf.st_rdev);
4290 min = minor(sbuf.st_rdev);
4292 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4295 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d", maj, min);
4297 value = sysfs_uevent_get(path, "DEVNAME");
4301 snprintf(path, sizeof(path), "/dev/%s", value);
4304 return strdup(path);
4306 return drmGetDeviceNameFromFd(fd);
4309 char node[PATH_MAX + 1];
4310 const char *dev_name;
4314 if (fstat(fd, &sbuf))
4317 maj = major(sbuf.st_rdev);
4318 min = minor(sbuf.st_rdev);
4320 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4323 node_type = drmGetMinorType(maj, min);
4324 if (node_type == -1)
4327 dev_name = drmGetDeviceName(node_type);
4331 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min);
4332 if (n == -1 || n >= PATH_MAX)
4335 return strdup(node);
4339 drm_public int drmSyncobjCreate(int fd, uint32_t flags, uint32_t *handle)
4341 struct drm_syncobj_create args;
4347 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_CREATE, &args);
4350 *handle = args.handle;
4354 drm_public int drmSyncobjDestroy(int fd, uint32_t handle)
4356 struct drm_syncobj_destroy args;
4359 args.handle = handle;
4360 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_DESTROY, &args);
4363 drm_public int drmSyncobjHandleToFD(int fd, uint32_t handle, int *obj_fd)
4365 struct drm_syncobj_handle args;
4370 args.handle = handle;
4371 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4378 drm_public int drmSyncobjFDToHandle(int fd, int obj_fd, uint32_t *handle)
4380 struct drm_syncobj_handle args;
4386 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4389 *handle = args.handle;
4393 drm_public int drmSyncobjImportSyncFile(int fd, uint32_t handle,
4396 struct drm_syncobj_handle args;
4399 args.fd = sync_file_fd;
4400 args.handle = handle;
4401 args.flags = DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE;
4402 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4405 drm_public int drmSyncobjExportSyncFile(int fd, uint32_t handle,
4408 struct drm_syncobj_handle args;
4413 args.handle = handle;
4414 args.flags = DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE;
4415 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4418 *sync_file_fd = args.fd;
4422 drm_public int drmSyncobjWait(int fd, uint32_t *handles, unsigned num_handles,
4423 int64_t timeout_nsec, unsigned flags,
4424 uint32_t *first_signaled)
4426 struct drm_syncobj_wait args;
4430 args.handles = (uintptr_t)handles;
4431 args.timeout_nsec = timeout_nsec;
4432 args.count_handles = num_handles;
4435 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_WAIT, &args);
4440 *first_signaled = args.first_signaled;
4444 drm_public int drmSyncobjReset(int fd, const uint32_t *handles,
4445 uint32_t handle_count)
4447 struct drm_syncobj_array args;
4451 args.handles = (uintptr_t)handles;
4452 args.count_handles = handle_count;
4454 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_RESET, &args);
4458 drm_public int drmSyncobjSignal(int fd, const uint32_t *handles,
4459 uint32_t handle_count)
4461 struct drm_syncobj_array args;
4465 args.handles = (uintptr_t)handles;
4466 args.count_handles = handle_count;
4468 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_SIGNAL, &args);
4472 drm_public int drmSyncobjTimelineSignal(int fd, const uint32_t *handles,
4473 uint64_t *points, uint32_t handle_count)
4475 struct drm_syncobj_timeline_array args;
4479 args.handles = (uintptr_t)handles;
4480 args.points = (uintptr_t)points;
4481 args.count_handles = handle_count;
4483 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TIMELINE_SIGNAL, &args);
4487 drm_public int drmSyncobjTimelineWait(int fd, uint32_t *handles, uint64_t *points,
4488 unsigned num_handles,
4489 int64_t timeout_nsec, unsigned flags,
4490 uint32_t *first_signaled)
4492 struct drm_syncobj_timeline_wait args;
4496 args.handles = (uintptr_t)handles;
4497 args.points = (uintptr_t)points;
4498 args.timeout_nsec = timeout_nsec;
4499 args.count_handles = num_handles;
4502 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TIMELINE_WAIT, &args);
4507 *first_signaled = args.first_signaled;
4512 drm_public int drmSyncobjQuery(int fd, uint32_t *handles, uint64_t *points,
4513 uint32_t handle_count)
4515 struct drm_syncobj_timeline_array args;
4519 args.handles = (uintptr_t)handles;
4520 args.points = (uintptr_t)points;
4521 args.count_handles = handle_count;
4523 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_QUERY, &args);
4529 drm_public int drmSyncobjQuery2(int fd, uint32_t *handles, uint64_t *points,
4530 uint32_t handle_count, uint32_t flags)
4532 struct drm_syncobj_timeline_array args;
4535 args.handles = (uintptr_t)handles;
4536 args.points = (uintptr_t)points;
4537 args.count_handles = handle_count;
4540 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_QUERY, &args);
4544 drm_public int drmSyncobjTransfer(int fd,
4545 uint32_t dst_handle, uint64_t dst_point,
4546 uint32_t src_handle, uint64_t src_point,
4549 struct drm_syncobj_transfer args;
4553 args.src_handle = src_handle;
4554 args.dst_handle = dst_handle;
4555 args.src_point = src_point;
4556 args.dst_point = dst_point;
4559 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TRANSFER, &args);