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);
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));
313 static const char *drmGetDeviceName(int type)
316 case DRM_NODE_PRIMARY:
318 case DRM_NODE_CONTROL:
319 return DRM_CONTROL_DEV_NAME;
320 case DRM_NODE_RENDER:
321 return DRM_RENDER_DEV_NAME;
327 * Open the DRM device, creating it if necessary.
329 * \param dev major and minor numbers of the device.
330 * \param minor minor number of the device.
332 * \return a file descriptor on success, or a negative value on error.
335 * Assembles the device name from \p minor and opens it, creating the device
336 * special file node with the major and minor numbers specified by \p dev and
337 * parent directory if necessary and was called by root.
339 static int drmOpenDevice(dev_t dev, int minor, int type)
342 const char *dev_name = drmGetDeviceName(type);
343 char buf[DRM_NODE_NAME_MAX];
345 mode_t devmode = DRM_DEV_MODE, serv_mode;
348 int isroot = !geteuid();
349 uid_t user = DRM_DEV_UID;
350 gid_t group = DRM_DEV_GID;
356 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
357 drmMsg("drmOpenDevice: node name is %s\n", buf);
359 if (drm_server_info && drm_server_info->get_perms) {
360 drm_server_info->get_perms(&serv_group, &serv_mode);
361 devmode = serv_mode ? serv_mode : DRM_DEV_MODE;
362 devmode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
366 if (stat(DRM_DIR_NAME, &st)) {
368 return DRM_ERR_NOT_ROOT;
369 mkdir(DRM_DIR_NAME, DRM_DEV_DIRMODE);
370 chown_check_return(DRM_DIR_NAME, 0, 0); /* root:root */
371 chmod(DRM_DIR_NAME, DRM_DEV_DIRMODE);
374 /* Check if the device node exists and create it if necessary. */
375 if (stat(buf, &st)) {
377 return DRM_ERR_NOT_ROOT;
379 mknod(buf, S_IFCHR | devmode, dev);
382 if (drm_server_info && drm_server_info->get_perms) {
383 group = ((int)serv_group >= 0) ? serv_group : DRM_DEV_GID;
384 chown_check_return(buf, user, group);
388 /* if we modprobed then wait for udev */
392 if (stat(DRM_DIR_NAME, &st)) {
396 if (udev_count == 50)
401 if (stat(buf, &st)) {
405 if (udev_count == 50)
412 fd = open(buf, O_RDWR | O_CLOEXEC, 0);
413 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
414 fd, fd < 0 ? strerror(errno) : "OK");
419 /* Check if the device node is not what we expect it to be, and recreate it
420 * and try again if so.
422 if (st.st_rdev != dev) {
424 return DRM_ERR_NOT_ROOT;
426 mknod(buf, S_IFCHR | devmode, dev);
427 if (drm_server_info && drm_server_info->get_perms) {
428 chown_check_return(buf, user, group);
432 fd = open(buf, O_RDWR | O_CLOEXEC, 0);
433 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
434 fd, fd < 0 ? strerror(errno) : "OK");
438 drmMsg("drmOpenDevice: Open failed\n");
446 * Open the DRM device
448 * \param minor device minor number.
449 * \param create allow to create the device if set.
451 * \return a file descriptor on success, or a negative value on error.
454 * Calls drmOpenDevice() if \p create is set, otherwise assembles the device
455 * name from \p minor and opens it.
457 static int drmOpenMinor(int minor, int create, int type)
460 char buf[DRM_NODE_NAME_MAX];
461 const char *dev_name = drmGetDeviceName(type);
464 return drmOpenDevice(makedev(DRM_MAJOR, minor), minor, type);
469 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
470 if ((fd = open(buf, O_RDWR | O_CLOEXEC, 0)) >= 0)
477 * Determine whether the DRM kernel driver has been loaded.
479 * \return 1 if the DRM driver is loaded, 0 otherwise.
482 * Determine the presence of the kernel driver by attempting to open the 0
483 * minor and get version information. For backward compatibility with older
484 * Linux implementations, /proc/dri is also checked.
486 drm_public int drmAvailable(void)
488 drmVersionPtr version;
492 if ((fd = drmOpenMinor(0, 1, DRM_NODE_PRIMARY)) < 0) {
494 /* Try proc for backward Linux compatibility */
495 if (!access("/proc/dri/0", R_OK))
501 if ((version = drmGetVersion(fd))) {
503 drmFreeVersion(version);
510 static int drmGetMinorBase(int type)
513 case DRM_NODE_PRIMARY:
515 case DRM_NODE_CONTROL:
517 case DRM_NODE_RENDER:
524 static int drmGetMinorType(int major, int minor)
527 char name[SPECNAMELEN];
530 if (!devname_r(makedev(major, minor), S_IFCHR, name, sizeof(name)))
533 if (sscanf(name, "drm/%d", &id) != 1) {
534 // If not in /dev/drm/ we have the type in the name
535 if (sscanf(name, "dri/card%d\n", &id) >= 1)
536 return DRM_NODE_PRIMARY;
537 else if (sscanf(name, "dri/control%d\n", &id) >= 1)
538 return DRM_NODE_CONTROL;
539 else if (sscanf(name, "dri/renderD%d\n", &id) >= 1)
540 return DRM_NODE_RENDER;
546 int type = minor >> 6;
552 case DRM_NODE_PRIMARY:
553 case DRM_NODE_CONTROL:
554 case DRM_NODE_RENDER:
561 static const char *drmGetMinorName(int type)
564 case DRM_NODE_PRIMARY:
565 return DRM_PRIMARY_MINOR_NAME;
566 case DRM_NODE_CONTROL:
567 return DRM_CONTROL_MINOR_NAME;
568 case DRM_NODE_RENDER:
569 return DRM_RENDER_MINOR_NAME;
576 * Open the device by bus ID.
578 * \param busid bus ID.
579 * \param type device node type.
581 * \return a file descriptor on success, or a negative value on error.
584 * This function attempts to open every possible minor (up to DRM_MAX_MINOR),
585 * comparing the device bus ID with the one supplied.
587 * \sa drmOpenMinor() and drmGetBusid().
589 static int drmOpenByBusid(const char *busid, int type)
591 int i, pci_domain_ok = 1;
595 int base = drmGetMinorBase(type);
600 drmMsg("drmOpenByBusid: Searching for BusID %s\n", busid);
601 for (i = base; i < base + DRM_MAX_MINOR; i++) {
602 fd = drmOpenMinor(i, 1, type);
603 drmMsg("drmOpenByBusid: drmOpenMinor returns %d\n", fd);
605 /* We need to try for 1.4 first for proper PCI domain support
606 * and if that fails, we know the kernel is busted
610 sv.drm_dd_major = -1; /* Don't care */
611 sv.drm_dd_minor = -1; /* Don't care */
612 if (drmSetInterfaceVersion(fd, &sv)) {
618 sv.drm_dd_major = -1; /* Don't care */
619 sv.drm_dd_minor = -1; /* Don't care */
620 drmMsg("drmOpenByBusid: Interface 1.4 failed, trying 1.1\n");
621 drmSetInterfaceVersion(fd, &sv);
623 buf = drmGetBusid(fd);
624 drmMsg("drmOpenByBusid: drmGetBusid reports %s\n", buf);
625 if (buf && drmMatchBusID(buf, busid, pci_domain_ok)) {
639 * Open the device by name.
641 * \param name driver name.
642 * \param type the device node type.
644 * \return a file descriptor on success, or a negative value on error.
647 * This function opens the first minor number that matches the driver name and
648 * isn't already in use. If it's in use it then it will already have a bus ID
651 * \sa drmOpenMinor(), drmGetVersion() and drmGetBusid().
653 static int drmOpenByName(const char *name, int type)
657 drmVersionPtr version;
659 int base = drmGetMinorBase(type);
665 * Open the first minor number that matches the driver name and isn't
666 * already in use. If it's in use it will have a busid assigned already.
668 for (i = base; i < base + DRM_MAX_MINOR; i++) {
669 if ((fd = drmOpenMinor(i, 1, type)) >= 0) {
670 if ((version = drmGetVersion(fd))) {
671 if (!strcmp(version->name, name)) {
672 drmFreeVersion(version);
673 id = drmGetBusid(fd);
674 drmMsg("drmGetBusid returned '%s'\n", id ? id : "NULL");
683 drmFreeVersion(version);
691 /* Backward-compatibility /proc support */
692 for (i = 0; i < 8; i++) {
693 char proc_name[64], buf[512];
694 char *driver, *pt, *devstring;
697 sprintf(proc_name, "/proc/dri/%d/name", i);
698 if ((fd = open(proc_name, 0, 0)) >= 0) {
699 retcode = read(fd, buf, sizeof(buf)-1);
702 buf[retcode-1] = '\0';
703 for (driver = pt = buf; *pt && *pt != ' '; ++pt)
705 if (*pt) { /* Device is next */
707 if (!strcmp(driver, name)) { /* Match */
708 for (devstring = ++pt; *pt && *pt != ' '; ++pt)
710 if (*pt) { /* Found busid */
711 return drmOpenByBusid(++pt, type);
712 } else { /* No busid */
713 return drmOpenDevice(strtol(devstring, NULL, 0),i, type);
727 * Open the DRM device.
729 * Looks up the specified name and bus ID, and opens the device found. The
730 * entry in /dev/dri is created if necessary and if called by root.
732 * \param name driver name. Not referenced if bus ID is supplied.
733 * \param busid bus ID. Zero if not known.
735 * \return a file descriptor on success, or a negative value on error.
738 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
741 drm_public int drmOpen(const char *name, const char *busid)
743 return drmOpenWithType(name, busid, DRM_NODE_PRIMARY);
747 * Open the DRM device with specified type.
749 * Looks up the specified name and bus ID, and opens the device found. The
750 * entry in /dev/dri is created if necessary and if called by root.
752 * \param name driver name. Not referenced if bus ID is supplied.
753 * \param busid bus ID. Zero if not known.
754 * \param type the device node type to open, PRIMARY, CONTROL or RENDER
756 * \return a file descriptor on success, or a negative value on error.
759 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
762 drm_public int drmOpenWithType(const char *name, const char *busid, int type)
764 if (name != NULL && drm_server_info &&
765 drm_server_info->load_module && !drmAvailable()) {
766 /* try to load the kernel module */
767 if (!drm_server_info->load_module(name)) {
768 drmMsg("[drm] failed to load kernel module \"%s\"\n", name);
774 int fd = drmOpenByBusid(busid, type);
780 return drmOpenByName(name, type);
785 drm_public int drmOpenControl(int minor)
787 return drmOpenMinor(minor, 0, DRM_NODE_CONTROL);
790 drm_public int drmOpenRender(int minor)
792 return drmOpenMinor(minor, 0, DRM_NODE_RENDER);
796 * Free the version information returned by drmGetVersion().
798 * \param v pointer to the version information.
801 * It frees the memory pointed by \p %v as well as all the non-null strings
804 drm_public void drmFreeVersion(drmVersionPtr v)
816 * Free the non-public version information returned by the kernel.
818 * \param v pointer to the version information.
821 * Used by drmGetVersion() to free the memory pointed by \p %v as well as all
822 * the non-null strings pointers in it.
824 static void drmFreeKernelVersion(drm_version_t *v)
836 * Copy version information.
838 * \param d destination pointer.
839 * \param s source pointer.
842 * Used by drmGetVersion() to translate the information returned by the ioctl
843 * interface in a private structure into the public structure counterpart.
845 static void drmCopyVersion(drmVersionPtr d, const drm_version_t *s)
847 d->version_major = s->version_major;
848 d->version_minor = s->version_minor;
849 d->version_patchlevel = s->version_patchlevel;
850 d->name_len = s->name_len;
851 d->name = strdup(s->name);
852 d->date_len = s->date_len;
853 d->date = strdup(s->date);
854 d->desc_len = s->desc_len;
855 d->desc = strdup(s->desc);
860 * Query the driver version information.
862 * \param fd file descriptor.
864 * \return pointer to a drmVersion structure which should be freed with
867 * \note Similar information is available via /proc/dri.
870 * It gets the version information via successive DRM_IOCTL_VERSION ioctls,
871 * first with zeros to get the string lengths, and then the actually strings.
872 * It also null-terminates them since they might not be already.
874 drm_public drmVersionPtr drmGetVersion(int fd)
876 drmVersionPtr retval;
877 drm_version_t *version = drmMalloc(sizeof(*version));
879 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
880 drmFreeKernelVersion(version);
884 if (version->name_len)
885 version->name = drmMalloc(version->name_len + 1);
886 if (version->date_len)
887 version->date = drmMalloc(version->date_len + 1);
888 if (version->desc_len)
889 version->desc = drmMalloc(version->desc_len + 1);
891 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
892 drmMsg("DRM_IOCTL_VERSION: %s\n", strerror(errno));
893 drmFreeKernelVersion(version);
897 /* The results might not be null-terminated strings, so terminate them. */
898 if (version->name_len) version->name[version->name_len] = '\0';
899 if (version->date_len) version->date[version->date_len] = '\0';
900 if (version->desc_len) version->desc[version->desc_len] = '\0';
902 retval = drmMalloc(sizeof(*retval));
903 drmCopyVersion(retval, version);
904 drmFreeKernelVersion(version);
910 * Get version information for the DRM user space library.
912 * This version number is driver independent.
914 * \param fd file descriptor.
916 * \return version information.
919 * This function allocates and fills a drm_version structure with a hard coded
922 drm_public drmVersionPtr drmGetLibVersion(int fd)
924 drm_version_t *version = drmMalloc(sizeof(*version));
927 * NOTE THIS MUST NOT GO ABOVE VERSION 1.X due to drivers needing it
928 * revision 1.0.x = original DRM interface with no drmGetLibVersion
929 * entry point and many drm<Device> extensions
930 * revision 1.1.x = added drmCommand entry points for device extensions
931 * added drmGetLibVersion to identify libdrm.a version
932 * revision 1.2.x = added drmSetInterfaceVersion
933 * modified drmOpen to handle both busid and name
934 * revision 1.3.x = added server + memory manager
936 version->version_major = 1;
937 version->version_minor = 3;
938 version->version_patchlevel = 0;
940 return (drmVersionPtr)version;
943 drm_public int drmGetCap(int fd, uint64_t capability, uint64_t *value)
945 struct drm_get_cap cap;
949 cap.capability = capability;
951 ret = drmIoctl(fd, DRM_IOCTL_GET_CAP, &cap);
959 drm_public int drmSetClientCap(int fd, uint64_t capability, uint64_t value)
961 struct drm_set_client_cap cap;
964 cap.capability = capability;
967 return drmIoctl(fd, DRM_IOCTL_SET_CLIENT_CAP, &cap);
971 * Free the bus ID information.
973 * \param busid bus ID information string as given by drmGetBusid().
976 * This function is just frees the memory pointed by \p busid.
978 drm_public void drmFreeBusid(const char *busid)
980 drmFree((void *)busid);
985 * Get the bus ID of the device.
987 * \param fd file descriptor.
989 * \return bus ID string.
992 * This function gets the bus ID via successive DRM_IOCTL_GET_UNIQUE ioctls to
993 * get the string length and data, passing the arguments in a drm_unique
996 drm_public char *drmGetBusid(int fd)
1002 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
1004 u.unique = drmMalloc(u.unique_len + 1);
1005 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u)) {
1009 u.unique[u.unique_len] = '\0';
1016 * Set the bus ID of the device.
1018 * \param fd file descriptor.
1019 * \param busid bus ID string.
1021 * \return zero on success, negative on failure.
1024 * This function is a wrapper around the DRM_IOCTL_SET_UNIQUE ioctl, passing
1025 * the arguments in a drm_unique structure.
1027 drm_public int drmSetBusid(int fd, const char *busid)
1032 u.unique = (char *)busid;
1033 u.unique_len = strlen(busid);
1035 if (drmIoctl(fd, DRM_IOCTL_SET_UNIQUE, &u)) {
1041 drm_public int drmGetMagic(int fd, drm_magic_t * magic)
1048 if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
1050 *magic = auth.magic;
1054 drm_public int drmAuthMagic(int fd, drm_magic_t magic)
1060 if (drmIoctl(fd, DRM_IOCTL_AUTH_MAGIC, &auth))
1066 * Specifies a range of memory that is available for mapping by a
1069 * \param fd file descriptor.
1070 * \param offset usually the physical address. The actual meaning depends of
1071 * the \p type parameter. See below.
1072 * \param size of the memory in bytes.
1073 * \param type type of the memory to be mapped.
1074 * \param flags combination of several flags to modify the function actions.
1075 * \param handle will be set to a value that may be used as the offset
1076 * parameter for mmap().
1078 * \return zero on success or a negative value on error.
1080 * \par Mapping the frame buffer
1081 * For the frame buffer
1082 * - \p offset will be the physical address of the start of the frame buffer,
1083 * - \p size will be the size of the frame buffer in bytes, and
1084 * - \p type will be DRM_FRAME_BUFFER.
1087 * The area mapped will be uncached. If MTRR support is available in the
1088 * kernel, the frame buffer area will be set to write combining.
1090 * \par Mapping the MMIO register area
1091 * For the MMIO register area,
1092 * - \p offset will be the physical address of the start of the register area,
1093 * - \p size will be the size of the register area bytes, and
1094 * - \p type will be DRM_REGISTERS.
1096 * The area mapped will be uncached.
1098 * \par Mapping the SAREA
1100 * - \p offset will be ignored and should be set to zero,
1101 * - \p size will be the desired size of the SAREA in bytes,
1102 * - \p type will be DRM_SHM.
1105 * A shared memory area of the requested size will be created and locked in
1106 * kernel memory. This area may be mapped into client-space by using the handle
1109 * \note May only be called by root.
1112 * This function is a wrapper around the DRM_IOCTL_ADD_MAP ioctl, passing
1113 * the arguments in a drm_map structure.
1115 drm_public int drmAddMap(int fd, drm_handle_t offset, drmSize size, drmMapType type,
1116 drmMapFlags flags, drm_handle_t *handle)
1121 map.offset = offset;
1125 if (drmIoctl(fd, DRM_IOCTL_ADD_MAP, &map))
1128 *handle = (drm_handle_t)(uintptr_t)map.handle;
1132 drm_public int drmRmMap(int fd, drm_handle_t handle)
1137 map.handle = (void *)(uintptr_t)handle;
1139 if(drmIoctl(fd, DRM_IOCTL_RM_MAP, &map))
1145 * Make buffers available for DMA transfers.
1147 * \param fd file descriptor.
1148 * \param count number of buffers.
1149 * \param size size of each buffer.
1150 * \param flags buffer allocation flags.
1151 * \param agp_offset offset in the AGP aperture
1153 * \return number of buffers allocated, negative on error.
1156 * This function is a wrapper around DRM_IOCTL_ADD_BUFS ioctl.
1160 drm_public int drmAddBufs(int fd, int count, int size, drmBufDescFlags flags,
1163 drm_buf_desc_t request;
1166 request.count = count;
1167 request.size = size;
1168 request.flags = flags;
1169 request.agp_start = agp_offset;
1171 if (drmIoctl(fd, DRM_IOCTL_ADD_BUFS, &request))
1173 return request.count;
1176 drm_public int drmMarkBufs(int fd, double low, double high)
1178 drm_buf_info_t info;
1183 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1189 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1192 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1193 int retval = -errno;
1198 for (i = 0; i < info.count; i++) {
1199 info.list[i].low_mark = low * info.list[i].count;
1200 info.list[i].high_mark = high * info.list[i].count;
1201 if (drmIoctl(fd, DRM_IOCTL_MARK_BUFS, &info.list[i])) {
1202 int retval = -errno;
1215 * \param fd file descriptor.
1216 * \param count number of buffers to free.
1217 * \param list list of buffers to be freed.
1219 * \return zero on success, or a negative value on failure.
1221 * \note This function is primarily used for debugging.
1224 * This function is a wrapper around the DRM_IOCTL_FREE_BUFS ioctl, passing
1225 * the arguments in a drm_buf_free structure.
1227 drm_public int drmFreeBufs(int fd, int count, int *list)
1229 drm_buf_free_t request;
1232 request.count = count;
1233 request.list = list;
1234 if (drmIoctl(fd, DRM_IOCTL_FREE_BUFS, &request))
1243 * \param fd file descriptor.
1246 * This function closes the file descriptor.
1248 drm_public int drmClose(int fd)
1250 unsigned long key = drmGetKeyFromFd(fd);
1251 drmHashEntry *entry = drmGetEntry(fd);
1253 drmHashDestroy(entry->tagTable);
1256 entry->tagTable = NULL;
1258 drmHashDelete(drmHashTable, key);
1266 * Map a region of memory.
1268 * \param fd file descriptor.
1269 * \param handle handle returned by drmAddMap().
1270 * \param size size in bytes. Must match the size used by drmAddMap().
1271 * \param address will contain the user-space virtual address where the mapping
1274 * \return zero on success, or a negative value on failure.
1277 * This function is a wrapper for mmap().
1279 drm_public int drmMap(int fd, drm_handle_t handle, drmSize size,
1280 drmAddressPtr address)
1282 static unsigned long pagesize_mask = 0;
1288 pagesize_mask = getpagesize() - 1;
1290 size = (size + pagesize_mask) & ~pagesize_mask;
1292 *address = drm_mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1293 if (*address == MAP_FAILED)
1300 * Unmap mappings obtained with drmMap().
1302 * \param address address as given by drmMap().
1303 * \param size size in bytes. Must match the size used by drmMap().
1305 * \return zero on success, or a negative value on failure.
1308 * This function is a wrapper for munmap().
1310 drm_public int drmUnmap(drmAddress address, drmSize size)
1312 return drm_munmap(address, size);
1315 drm_public drmBufInfoPtr drmGetBufInfo(int fd)
1317 drm_buf_info_t info;
1318 drmBufInfoPtr retval;
1323 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1327 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1330 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1335 retval = drmMalloc(sizeof(*retval));
1336 retval->count = info.count;
1337 retval->list = drmMalloc(info.count * sizeof(*retval->list));
1338 for (i = 0; i < info.count; i++) {
1339 retval->list[i].count = info.list[i].count;
1340 retval->list[i].size = info.list[i].size;
1341 retval->list[i].low_mark = info.list[i].low_mark;
1342 retval->list[i].high_mark = info.list[i].high_mark;
1351 * Map all DMA buffers into client-virtual space.
1353 * \param fd file descriptor.
1355 * \return a pointer to a ::drmBufMap structure.
1357 * \note The client may not use these buffers until obtaining buffer indices
1361 * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1362 * information about the buffers in a drm_buf_map structure into the
1363 * client-visible data structures.
1365 drm_public drmBufMapPtr drmMapBufs(int fd)
1368 drmBufMapPtr retval;
1372 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1378 if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1381 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1386 retval = drmMalloc(sizeof(*retval));
1387 retval->count = bufs.count;
1388 retval->list = drmMalloc(bufs.count * sizeof(*retval->list));
1389 for (i = 0; i < bufs.count; i++) {
1390 retval->list[i].idx = bufs.list[i].idx;
1391 retval->list[i].total = bufs.list[i].total;
1392 retval->list[i].used = 0;
1393 retval->list[i].address = bufs.list[i].address;
1402 * Unmap buffers allocated with drmMapBufs().
1404 * \return zero on success, or negative value on failure.
1407 * Calls munmap() for every buffer stored in \p bufs and frees the
1408 * memory allocated by drmMapBufs().
1410 drm_public int drmUnmapBufs(drmBufMapPtr bufs)
1414 for (i = 0; i < bufs->count; i++) {
1415 drm_munmap(bufs->list[i].address, bufs->list[i].total);
1418 drmFree(bufs->list);
1424 #define DRM_DMA_RETRY 16
1427 * Reserve DMA buffers.
1429 * \param fd file descriptor.
1432 * \return zero on success, or a negative value on failure.
1435 * Assemble the arguments into a drm_dma structure and keeps issuing the
1436 * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1438 drm_public int drmDMA(int fd, drmDMAReqPtr request)
1443 dma.context = request->context;
1444 dma.send_count = request->send_count;
1445 dma.send_indices = request->send_list;
1446 dma.send_sizes = request->send_sizes;
1447 dma.flags = request->flags;
1448 dma.request_count = request->request_count;
1449 dma.request_size = request->request_size;
1450 dma.request_indices = request->request_list;
1451 dma.request_sizes = request->request_sizes;
1452 dma.granted_count = 0;
1455 ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1456 } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1459 request->granted_count = dma.granted_count;
1468 * Obtain heavyweight hardware lock.
1470 * \param fd file descriptor.
1471 * \param context context.
1472 * \param flags flags that determine the state of the hardware when the function
1475 * \return always zero.
1478 * This function translates the arguments into a drm_lock structure and issue
1479 * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1481 drm_public int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
1486 lock.context = context;
1488 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
1489 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
1490 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
1491 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
1492 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
1493 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
1495 while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
1501 * Release the hardware lock.
1503 * \param fd file descriptor.
1504 * \param context context.
1506 * \return zero on success, or a negative value on failure.
1509 * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
1510 * argument in a drm_lock structure.
1512 drm_public int drmUnlock(int fd, drm_context_t context)
1517 lock.context = context;
1518 return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
1521 drm_public drm_context_t *drmGetReservedContextList(int fd, int *count)
1525 drm_context_t * retval;
1529 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1535 if (!(list = drmMalloc(res.count * sizeof(*list))))
1537 if (!(retval = drmMalloc(res.count * sizeof(*retval))))
1540 res.contexts = list;
1541 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1542 goto err_free_context;
1544 for (i = 0; i < res.count; i++)
1545 retval[i] = list[i].handle;
1558 drm_public void drmFreeReservedContextList(drm_context_t *pt)
1566 * Used by the X server during GLXContext initialization. This causes
1567 * per-context kernel-level resources to be allocated.
1569 * \param fd file descriptor.
1570 * \param handle is set on success. To be used by the client when requesting DMA
1571 * dispatch with drmDMA().
1573 * \return zero on success, or a negative value on failure.
1575 * \note May only be called by root.
1578 * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
1579 * argument in a drm_ctx structure.
1581 drm_public int drmCreateContext(int fd, drm_context_t *handle)
1586 if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
1588 *handle = ctx.handle;
1592 drm_public int drmSwitchToContext(int fd, drm_context_t context)
1597 ctx.handle = context;
1598 if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
1603 drm_public int drmSetContextFlags(int fd, drm_context_t context,
1604 drm_context_tFlags flags)
1609 * Context preserving means that no context switches are done between DMA
1610 * buffers from one context and the next. This is suitable for use in the
1611 * X server (which promises to maintain hardware context), or in the
1612 * client-side library when buffers are swapped on behalf of two threads.
1615 ctx.handle = context;
1616 if (flags & DRM_CONTEXT_PRESERVED)
1617 ctx.flags |= _DRM_CONTEXT_PRESERVED;
1618 if (flags & DRM_CONTEXT_2DONLY)
1619 ctx.flags |= _DRM_CONTEXT_2DONLY;
1620 if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
1625 drm_public int drmGetContextFlags(int fd, drm_context_t context,
1626 drm_context_tFlagsPtr flags)
1631 ctx.handle = context;
1632 if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
1635 if (ctx.flags & _DRM_CONTEXT_PRESERVED)
1636 *flags |= DRM_CONTEXT_PRESERVED;
1637 if (ctx.flags & _DRM_CONTEXT_2DONLY)
1638 *flags |= DRM_CONTEXT_2DONLY;
1645 * Free any kernel-level resources allocated with drmCreateContext() associated
1648 * \param fd file descriptor.
1649 * \param handle handle given by drmCreateContext().
1651 * \return zero on success, or a negative value on failure.
1653 * \note May only be called by root.
1656 * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
1657 * argument in a drm_ctx structure.
1659 drm_public int drmDestroyContext(int fd, drm_context_t handle)
1664 ctx.handle = handle;
1665 if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
1670 drm_public int drmCreateDrawable(int fd, drm_drawable_t *handle)
1675 if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
1677 *handle = draw.handle;
1681 drm_public int drmDestroyDrawable(int fd, drm_drawable_t handle)
1686 draw.handle = handle;
1687 if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
1692 drm_public int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
1693 drm_drawable_info_type_t type,
1694 unsigned int num, void *data)
1696 drm_update_draw_t update;
1699 update.handle = handle;
1702 update.data = (unsigned long long)(unsigned long)data;
1704 if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
1710 drm_public int drmCrtcGetSequence(int fd, uint32_t crtcId, uint64_t *sequence,
1713 struct drm_crtc_get_sequence get_seq;
1717 get_seq.crtc_id = crtcId;
1718 ret = drmIoctl(fd, DRM_IOCTL_CRTC_GET_SEQUENCE, &get_seq);
1723 *sequence = get_seq.sequence;
1725 *ns = get_seq.sequence_ns;
1729 drm_public int drmCrtcQueueSequence(int fd, uint32_t crtcId, uint32_t flags,
1731 uint64_t *sequence_queued,
1734 struct drm_crtc_queue_sequence queue_seq;
1737 memclear(queue_seq);
1738 queue_seq.crtc_id = crtcId;
1739 queue_seq.flags = flags;
1740 queue_seq.sequence = sequence;
1741 queue_seq.user_data = user_data;
1743 ret = drmIoctl(fd, DRM_IOCTL_CRTC_QUEUE_SEQUENCE, &queue_seq);
1744 if (ret == 0 && sequence_queued)
1745 *sequence_queued = queue_seq.sequence;
1751 * Acquire the AGP device.
1753 * Must be called before any of the other AGP related calls.
1755 * \param fd file descriptor.
1757 * \return zero on success, or a negative value on failure.
1760 * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
1762 drm_public int drmAgpAcquire(int fd)
1764 if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
1771 * Release the AGP device.
1773 * \param fd file descriptor.
1775 * \return zero on success, or a negative value on failure.
1778 * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
1780 drm_public int drmAgpRelease(int fd)
1782 if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
1791 * \param fd file descriptor.
1792 * \param mode AGP mode.
1794 * \return zero on success, or a negative value on failure.
1797 * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
1798 * argument in a drm_agp_mode structure.
1800 drm_public int drmAgpEnable(int fd, unsigned long mode)
1806 if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
1813 * Allocate a chunk of AGP memory.
1815 * \param fd file descriptor.
1816 * \param size requested memory size in bytes. Will be rounded to page boundary.
1817 * \param type type of memory to allocate.
1818 * \param address if not zero, will be set to the physical address of the
1820 * \param handle on success will be set to a handle of the allocated memory.
1822 * \return zero on success, or a negative value on failure.
1825 * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
1826 * arguments in a drm_agp_buffer structure.
1828 drm_public int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
1829 unsigned long *address, drm_handle_t *handle)
1834 *handle = DRM_AGP_NO_HANDLE;
1837 if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
1840 *address = b.physical;
1847 * Free a chunk of AGP memory.
1849 * \param fd file descriptor.
1850 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1852 * \return zero on success, or a negative value on failure.
1855 * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
1856 * argument in a drm_agp_buffer structure.
1858 drm_public int drmAgpFree(int fd, drm_handle_t handle)
1864 if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
1871 * Bind a chunk of AGP memory.
1873 * \param fd file descriptor.
1874 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1875 * \param offset offset in bytes. It will round to page boundary.
1877 * \return zero on success, or a negative value on failure.
1880 * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
1881 * argument in a drm_agp_binding structure.
1883 drm_public int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
1885 drm_agp_binding_t b;
1890 if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
1897 * Unbind a chunk of AGP memory.
1899 * \param fd file descriptor.
1900 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1902 * \return zero on success, or a negative value on failure.
1905 * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
1906 * the argument in a drm_agp_binding structure.
1908 drm_public int drmAgpUnbind(int fd, drm_handle_t handle)
1910 drm_agp_binding_t b;
1914 if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
1921 * Get AGP driver major version number.
1923 * \param fd file descriptor.
1925 * \return major version number on success, or a negative value on failure..
1928 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1929 * necessary information in a drm_agp_info structure.
1931 drm_public int drmAgpVersionMajor(int fd)
1937 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1939 return i.agp_version_major;
1944 * Get AGP driver minor version number.
1946 * \param fd file descriptor.
1948 * \return minor version number on success, or a negative value on failure.
1951 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1952 * necessary information in a drm_agp_info structure.
1954 drm_public int drmAgpVersionMinor(int fd)
1960 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1962 return i.agp_version_minor;
1969 * \param fd file descriptor.
1971 * \return mode on success, or zero on failure.
1974 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1975 * necessary information in a drm_agp_info structure.
1977 drm_public unsigned long drmAgpGetMode(int fd)
1983 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1990 * Get AGP aperture base.
1992 * \param fd file descriptor.
1994 * \return aperture base on success, zero on failure.
1997 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1998 * necessary information in a drm_agp_info structure.
2000 drm_public unsigned long drmAgpBase(int fd)
2006 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2008 return i.aperture_base;
2013 * Get AGP aperture size.
2015 * \param fd file descriptor.
2017 * \return aperture size on success, zero on failure.
2020 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2021 * necessary information in a drm_agp_info structure.
2023 drm_public unsigned long drmAgpSize(int fd)
2029 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2031 return i.aperture_size;
2036 * Get used AGP memory.
2038 * \param fd file descriptor.
2040 * \return memory used on success, or zero on failure.
2043 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2044 * necessary information in a drm_agp_info structure.
2046 drm_public unsigned long drmAgpMemoryUsed(int fd)
2052 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2054 return i.memory_used;
2059 * Get available AGP memory.
2061 * \param fd file descriptor.
2063 * \return memory available on success, or zero on failure.
2066 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2067 * necessary information in a drm_agp_info structure.
2069 drm_public unsigned long drmAgpMemoryAvail(int fd)
2075 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2077 return i.memory_allowed;
2082 * Get hardware vendor ID.
2084 * \param fd file descriptor.
2086 * \return vendor ID on success, or zero on failure.
2089 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2090 * necessary information in a drm_agp_info structure.
2092 drm_public unsigned int drmAgpVendorId(int fd)
2098 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2105 * Get hardware device ID.
2107 * \param fd file descriptor.
2109 * \return zero on success, or zero on failure.
2112 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2113 * necessary information in a drm_agp_info structure.
2115 drm_public unsigned int drmAgpDeviceId(int fd)
2121 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2126 drm_public int drmScatterGatherAlloc(int fd, unsigned long size,
2127 drm_handle_t *handle)
2129 drm_scatter_gather_t sg;
2135 if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
2137 *handle = sg.handle;
2141 drm_public int drmScatterGatherFree(int fd, drm_handle_t handle)
2143 drm_scatter_gather_t sg;
2147 if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
2155 * \param fd file descriptor.
2156 * \param vbl pointer to a drmVBlank structure.
2158 * \return zero on success, or a negative value on failure.
2161 * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
2163 drm_public int drmWaitVBlank(int fd, drmVBlankPtr vbl)
2165 struct timespec timeout, cur;
2168 ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2170 fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
2176 ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
2177 vbl->request.type &= ~DRM_VBLANK_RELATIVE;
2178 if (ret && errno == EINTR) {
2179 clock_gettime(CLOCK_MONOTONIC, &cur);
2180 /* Timeout after 1s */
2181 if (cur.tv_sec > timeout.tv_sec + 1 ||
2182 (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
2189 } while (ret && errno == EINTR);
2195 drm_public int drmError(int err, const char *label)
2198 case DRM_ERR_NO_DEVICE:
2199 fprintf(stderr, "%s: no device\n", label);
2201 case DRM_ERR_NO_ACCESS:
2202 fprintf(stderr, "%s: no access\n", label);
2204 case DRM_ERR_NOT_ROOT:
2205 fprintf(stderr, "%s: not root\n", label);
2207 case DRM_ERR_INVALID:
2208 fprintf(stderr, "%s: invalid args\n", label);
2213 fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2221 * Install IRQ handler.
2223 * \param fd file descriptor.
2224 * \param irq IRQ number.
2226 * \return zero on success, or a negative value on failure.
2229 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2230 * argument in a drm_control structure.
2232 drm_public int drmCtlInstHandler(int fd, int irq)
2237 ctl.func = DRM_INST_HANDLER;
2239 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2246 * Uninstall IRQ handler.
2248 * \param fd file descriptor.
2250 * \return zero on success, or a negative value on failure.
2253 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2254 * argument in a drm_control structure.
2256 drm_public int drmCtlUninstHandler(int fd)
2261 ctl.func = DRM_UNINST_HANDLER;
2263 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2268 drm_public int drmFinish(int fd, int context, drmLockFlags flags)
2273 lock.context = context;
2274 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
2275 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
2276 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
2277 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
2278 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2279 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2280 if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2286 * Get IRQ from bus ID.
2288 * \param fd file descriptor.
2289 * \param busnum bus number.
2290 * \param devnum device number.
2291 * \param funcnum function number.
2293 * \return IRQ number on success, or a negative value on failure.
2296 * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2297 * arguments in a drm_irq_busid structure.
2299 drm_public int drmGetInterruptFromBusID(int fd, int busnum, int devnum,
2307 p.funcnum = funcnum;
2308 if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2313 drm_public int drmAddContextTag(int fd, drm_context_t context, void *tag)
2315 drmHashEntry *entry = drmGetEntry(fd);
2317 if (drmHashInsert(entry->tagTable, context, tag)) {
2318 drmHashDelete(entry->tagTable, context);
2319 drmHashInsert(entry->tagTable, context, tag);
2324 drm_public int drmDelContextTag(int fd, drm_context_t context)
2326 drmHashEntry *entry = drmGetEntry(fd);
2328 return drmHashDelete(entry->tagTable, context);
2331 drm_public void *drmGetContextTag(int fd, drm_context_t context)
2333 drmHashEntry *entry = drmGetEntry(fd);
2336 if (drmHashLookup(entry->tagTable, context, &value))
2342 drm_public int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2343 drm_handle_t handle)
2345 drm_ctx_priv_map_t map;
2348 map.ctx_id = ctx_id;
2349 map.handle = (void *)(uintptr_t)handle;
2351 if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2356 drm_public int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2357 drm_handle_t *handle)
2359 drm_ctx_priv_map_t map;
2362 map.ctx_id = ctx_id;
2364 if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2367 *handle = (drm_handle_t)(uintptr_t)map.handle;
2372 drm_public int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2373 drmMapType *type, drmMapFlags *flags,
2374 drm_handle_t *handle, int *mtrr)
2380 if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2382 *offset = map.offset;
2386 *handle = (unsigned long)map.handle;
2391 drm_public int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2392 unsigned long *magic, unsigned long *iocs)
2394 drm_client_t client;
2398 if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2400 *auth = client.auth;
2403 *magic = client.magic;
2404 *iocs = client.iocs;
2408 drm_public int drmGetStats(int fd, drmStatsT *stats)
2414 if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2418 memset(stats, 0, sizeof(*stats));
2419 if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2423 stats->data[i].long_format = "%-20.20s"; \
2424 stats->data[i].rate_format = "%8.8s"; \
2425 stats->data[i].isvalue = 1; \
2426 stats->data[i].verbose = 0
2429 stats->data[i].long_format = "%-20.20s"; \
2430 stats->data[i].rate_format = "%5.5s"; \
2431 stats->data[i].isvalue = 0; \
2432 stats->data[i].mult_names = "kgm"; \
2433 stats->data[i].mult = 1000; \
2434 stats->data[i].verbose = 0
2437 stats->data[i].long_format = "%-20.20s"; \
2438 stats->data[i].rate_format = "%5.5s"; \
2439 stats->data[i].isvalue = 0; \
2440 stats->data[i].mult_names = "KGM"; \
2441 stats->data[i].mult = 1024; \
2442 stats->data[i].verbose = 0
2445 stats->count = s.count;
2446 for (i = 0; i < s.count; i++) {
2447 stats->data[i].value = s.data[i].value;
2448 switch (s.data[i].type) {
2449 case _DRM_STAT_LOCK:
2450 stats->data[i].long_name = "Lock";
2451 stats->data[i].rate_name = "Lock";
2454 case _DRM_STAT_OPENS:
2455 stats->data[i].long_name = "Opens";
2456 stats->data[i].rate_name = "O";
2458 stats->data[i].verbose = 1;
2460 case _DRM_STAT_CLOSES:
2461 stats->data[i].long_name = "Closes";
2462 stats->data[i].rate_name = "Lock";
2464 stats->data[i].verbose = 1;
2466 case _DRM_STAT_IOCTLS:
2467 stats->data[i].long_name = "Ioctls";
2468 stats->data[i].rate_name = "Ioc/s";
2471 case _DRM_STAT_LOCKS:
2472 stats->data[i].long_name = "Locks";
2473 stats->data[i].rate_name = "Lck/s";
2476 case _DRM_STAT_UNLOCKS:
2477 stats->data[i].long_name = "Unlocks";
2478 stats->data[i].rate_name = "Unl/s";
2482 stats->data[i].long_name = "IRQs";
2483 stats->data[i].rate_name = "IRQ/s";
2486 case _DRM_STAT_PRIMARY:
2487 stats->data[i].long_name = "Primary Bytes";
2488 stats->data[i].rate_name = "PB/s";
2491 case _DRM_STAT_SECONDARY:
2492 stats->data[i].long_name = "Secondary Bytes";
2493 stats->data[i].rate_name = "SB/s";
2497 stats->data[i].long_name = "DMA";
2498 stats->data[i].rate_name = "DMA/s";
2501 case _DRM_STAT_SPECIAL:
2502 stats->data[i].long_name = "Special DMA";
2503 stats->data[i].rate_name = "dma/s";
2506 case _DRM_STAT_MISSED:
2507 stats->data[i].long_name = "Miss";
2508 stats->data[i].rate_name = "Ms/s";
2511 case _DRM_STAT_VALUE:
2512 stats->data[i].long_name = "Value";
2513 stats->data[i].rate_name = "Value";
2516 case _DRM_STAT_BYTE:
2517 stats->data[i].long_name = "Bytes";
2518 stats->data[i].rate_name = "B/s";
2521 case _DRM_STAT_COUNT:
2523 stats->data[i].long_name = "Count";
2524 stats->data[i].rate_name = "Cnt/s";
2533 * Issue a set-version ioctl.
2535 * \param fd file descriptor.
2536 * \param drmCommandIndex command index
2537 * \param data source pointer of the data to be read and written.
2538 * \param size size of the data to be read and written.
2540 * \return zero on success, or a negative value on failure.
2543 * It issues a read-write ioctl given by
2544 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2546 drm_public int drmSetInterfaceVersion(int fd, drmSetVersion *version)
2549 drm_set_version_t sv;
2552 sv.drm_di_major = version->drm_di_major;
2553 sv.drm_di_minor = version->drm_di_minor;
2554 sv.drm_dd_major = version->drm_dd_major;
2555 sv.drm_dd_minor = version->drm_dd_minor;
2557 if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
2561 version->drm_di_major = sv.drm_di_major;
2562 version->drm_di_minor = sv.drm_di_minor;
2563 version->drm_dd_major = sv.drm_dd_major;
2564 version->drm_dd_minor = sv.drm_dd_minor;
2570 * Send a device-specific command.
2572 * \param fd file descriptor.
2573 * \param drmCommandIndex command index
2575 * \return zero on success, or a negative value on failure.
2578 * It issues a ioctl given by
2579 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2581 drm_public int drmCommandNone(int fd, unsigned long drmCommandIndex)
2583 unsigned long request;
2585 request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
2587 if (drmIoctl(fd, request, NULL)) {
2595 * Send a device-specific read command.
2597 * \param fd file descriptor.
2598 * \param drmCommandIndex command index
2599 * \param data destination pointer of the data to be read.
2600 * \param size size of the data to be read.
2602 * \return zero on success, or a negative value on failure.
2605 * It issues a read ioctl given by
2606 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2608 drm_public int drmCommandRead(int fd, unsigned long drmCommandIndex,
2609 void *data, unsigned long size)
2611 unsigned long request;
2613 request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
2614 DRM_COMMAND_BASE + drmCommandIndex, size);
2616 if (drmIoctl(fd, request, data)) {
2624 * Send a device-specific write command.
2626 * \param fd file descriptor.
2627 * \param drmCommandIndex command index
2628 * \param data source pointer of the data to be written.
2629 * \param size size of the data to be written.
2631 * \return zero on success, or a negative value on failure.
2634 * It issues a write ioctl given by
2635 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2637 drm_public int drmCommandWrite(int fd, unsigned long drmCommandIndex,
2638 void *data, unsigned long size)
2640 unsigned long request;
2642 request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
2643 DRM_COMMAND_BASE + drmCommandIndex, size);
2645 if (drmIoctl(fd, request, data)) {
2653 * Send a device-specific read-write command.
2655 * \param fd file descriptor.
2656 * \param drmCommandIndex command index
2657 * \param data source pointer of the data to be read and written.
2658 * \param size size of the data to be read and written.
2660 * \return zero on success, or a negative value on failure.
2663 * It issues a read-write ioctl given by
2664 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2666 drm_public int drmCommandWriteRead(int fd, unsigned long drmCommandIndex,
2667 void *data, unsigned long size)
2669 unsigned long request;
2671 request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
2672 DRM_COMMAND_BASE + drmCommandIndex, size);
2674 if (drmIoctl(fd, request, data))
2679 #define DRM_MAX_FDS 16
2685 } connection[DRM_MAX_FDS];
2687 static int nr_fds = 0;
2689 drm_public int drmOpenOnce(void *unused, const char *BusID, int *newlyopened)
2691 return drmOpenOnceWithType(BusID, newlyopened, DRM_NODE_PRIMARY);
2694 drm_public int drmOpenOnceWithType(const char *BusID, int *newlyopened,
2700 for (i = 0; i < nr_fds; i++)
2701 if ((strcmp(BusID, connection[i].BusID) == 0) &&
2702 (connection[i].type == type)) {
2703 connection[i].refcount++;
2705 return connection[i].fd;
2708 fd = drmOpenWithType(NULL, BusID, type);
2709 if (fd < 0 || nr_fds == DRM_MAX_FDS)
2712 connection[nr_fds].BusID = strdup(BusID);
2713 connection[nr_fds].fd = fd;
2714 connection[nr_fds].refcount = 1;
2715 connection[nr_fds].type = type;
2719 fprintf(stderr, "saved connection %d for %s %d\n",
2720 nr_fds, connection[nr_fds].BusID,
2721 strcmp(BusID, connection[nr_fds].BusID));
2728 drm_public void drmCloseOnce(int fd)
2732 for (i = 0; i < nr_fds; i++) {
2733 if (fd == connection[i].fd) {
2734 if (--connection[i].refcount == 0) {
2735 drmClose(connection[i].fd);
2736 free(connection[i].BusID);
2739 connection[i] = connection[nr_fds];
2747 drm_public int drmSetMaster(int fd)
2749 return drmIoctl(fd, DRM_IOCTL_SET_MASTER, NULL);
2752 drm_public int drmDropMaster(int fd)
2754 return drmIoctl(fd, DRM_IOCTL_DROP_MASTER, NULL);
2757 drm_public int drmIsMaster(int fd)
2759 /* Detect master by attempting something that requires master.
2761 * Authenticating magic tokens requires master and 0 is an
2762 * internal kernel detail which we could use. Attempting this on
2763 * a master fd would fail therefore fail with EINVAL because 0
2766 * A non-master fd will fail with EACCES, as the kernel checks
2767 * for master before attempting to do anything else.
2769 * Since we don't want to leak implementation details, use
2772 return drmAuthMagic(fd, 0) != -EACCES;
2775 drm_public char *drmGetDeviceNameFromFd(int fd)
2779 char dname[SPECNAMELEN];
2780 char name[SPECNAMELEN];
2783 if (fstat(fd, &sbuf))
2786 maj = major(sbuf.st_rdev);
2787 min = minor(sbuf.st_rdev);
2789 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
2792 if (!devname_r(sbuf.st_rdev, S_IFCHR, dname, sizeof(dname)))
2795 snprintf(name, sizeof(name), "/dev/%s", dname);
2796 return strdup(name);
2803 /* The whole drmOpen thing is a fiasco and we need to find a way
2804 * back to just using open(2). For now, however, lets just make
2805 * things worse with even more ad hoc directory walking code to
2806 * discover the device file name. */
2811 for (i = 0; i < DRM_MAX_MINOR; i++) {
2812 snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
2813 if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
2816 if (i == DRM_MAX_MINOR)
2819 return strdup(name);
2823 static bool drmNodeIsDRM(int maj, int min)
2829 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device/drm",
2831 return stat(path, &sbuf) == 0;
2833 char name[SPECNAMELEN];
2835 if (!devname_r(makedev(maj, min), S_IFCHR, name, sizeof(name)))
2837 /* Handle drm/ and dri/ as both are present in different FreeBSD version
2838 * FreeBSD on amd64/i386/powerpc external kernel modules create node in
2839 * in /dev/drm/ and links in /dev/dri while a WIP in kernel driver creates
2840 * only device nodes in /dev/dri/ */
2841 return (!strncmp(name, "drm/", 4) || !strncmp(name, "dri/", 4));
2843 return maj == DRM_MAJOR;
2847 drm_public int drmGetNodeTypeFromFd(int fd)
2852 if (fstat(fd, &sbuf))
2855 maj = major(sbuf.st_rdev);
2856 min = minor(sbuf.st_rdev);
2858 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode)) {
2863 type = drmGetMinorType(maj, min);
2869 drm_public int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags,
2872 struct drm_prime_handle args;
2877 args.handle = handle;
2879 ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
2883 *prime_fd = args.fd;
2887 drm_public int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
2889 struct drm_prime_handle args;
2894 ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
2898 *handle = args.handle;
2902 static char *drmGetMinorNameForFD(int fd, int type)
2908 const char *name = drmGetMinorName(type);
2910 char dev_name[64], buf[64];
2918 if (fstat(fd, &sbuf))
2921 maj = major(sbuf.st_rdev);
2922 min = minor(sbuf.st_rdev);
2924 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
2927 snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
2929 sysdir = opendir(buf);
2933 while ((ent = readdir(sysdir))) {
2934 if (strncmp(ent->d_name, name, len) == 0) {
2935 snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
2939 return strdup(dev_name);
2947 char dname[SPECNAMELEN];
2949 char name[SPECNAMELEN];
2952 if (fstat(fd, &sbuf))
2955 maj = major(sbuf.st_rdev);
2956 min = minor(sbuf.st_rdev);
2958 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
2961 if (!devname_r(sbuf.st_rdev, S_IFCHR, dname, sizeof(dname)))
2964 /* Handle both /dev/drm and /dev/dri
2965 * FreeBSD on amd64/i386/powerpc external kernel modules create node in
2966 * in /dev/drm/ and links in /dev/dri while a WIP in kernel driver creates
2967 * only device nodes in /dev/dri/ */
2968 mname = drmGetMinorName(type);
2969 if (sscanf(dname, "drm/%d", &id) != 1) {
2970 snprintf(name, sizeof(name), "dri/%s", mname);
2971 if (strncmp(name, dname, strlen(name)) != 0)
2973 snprintf(name, sizeof(name), "/dev/%s", dname);
2975 snprintf(name, sizeof(name), DRM_DIR_NAME "/%s%d", mname, id);
2976 return strdup(name);
2979 char buf[PATH_MAX + 1];
2980 const char *dev_name = drmGetDeviceName(type);
2981 unsigned int maj, min;
2984 if (fstat(fd, &sbuf))
2987 maj = major(sbuf.st_rdev);
2988 min = minor(sbuf.st_rdev);
2990 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
2996 n = snprintf(buf, sizeof(buf), dev_name, DRM_DIR_NAME, min);
2997 if (n == -1 || n >= sizeof(buf))
3004 drm_public char *drmGetPrimaryDeviceNameFromFd(int fd)
3006 return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
3009 drm_public char *drmGetRenderDeviceNameFromFd(int fd)
3011 return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
3015 static char * DRM_PRINTFLIKE(2, 3)
3016 sysfs_uevent_get(const char *path, const char *fmt, ...)
3018 char filename[PATH_MAX + 1], *key, *line = NULL, *value = NULL;
3019 size_t size = 0, len;
3025 num = vasprintf(&key, fmt, ap);
3029 snprintf(filename, sizeof(filename), "%s/uevent", path);
3031 fp = fopen(filename, "r");
3037 while ((num = getline(&line, &size, fp)) >= 0) {
3038 if ((strncmp(line, key, len) == 0) && (line[len] == '=')) {
3039 char *start = line + len + 1, *end = line + num - 1;
3044 value = strndup(start, end - start);
3058 /* Little white lie to avoid major rework of the existing code */
3059 #define DRM_BUS_VIRTIO 0x10
3062 static int get_subsystem_type(const char *device_path)
3064 char path[PATH_MAX + 1] = "";
3065 char link[PATH_MAX + 1] = "";
3071 { "/pci", DRM_BUS_PCI },
3072 { "/usb", DRM_BUS_USB },
3073 { "/platform", DRM_BUS_PLATFORM },
3074 { "/spi", DRM_BUS_PLATFORM },
3075 { "/host1x", DRM_BUS_HOST1X },
3076 { "/virtio", DRM_BUS_VIRTIO },
3079 strncpy(path, device_path, PATH_MAX);
3080 strncat(path, "/subsystem", PATH_MAX);
3082 if (readlink(path, link, PATH_MAX) < 0)
3085 name = strrchr(link, '/');
3089 for (unsigned i = 0; i < ARRAY_SIZE(bus_types); i++) {
3090 if (strncmp(name, bus_types[i].name, strlen(bus_types[i].name)) == 0)
3091 return bus_types[i].bus_type;
3098 static int drmParseSubsystemType(int maj, int min)
3101 char path[PATH_MAX + 1] = "";
3102 char real_path[PATH_MAX + 1] = "";
3105 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3106 if (!realpath(path, real_path))
3108 snprintf(path, sizeof(path), "%s", real_path);
3110 subsystem_type = get_subsystem_type(path);
3111 if (subsystem_type == DRM_BUS_VIRTIO) {
3112 strncat(path, "/..", PATH_MAX);
3113 subsystem_type = get_subsystem_type(path);
3115 return subsystem_type;
3116 #elif defined(__OpenBSD__) || defined(__DragonFly__) || defined(__FreeBSD__)
3119 #warning "Missing implementation of drmParseSubsystemType"
3126 get_pci_path(int maj, int min, char *pci_path)
3128 char path[PATH_MAX + 1], *term;
3130 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3131 if (!realpath(path, pci_path)) {
3132 strcpy(pci_path, path);
3136 term = strrchr(pci_path, '/');
3137 if (term && strncmp(term, "/virtio", 7) == 0)
3143 static int get_sysctl_pci_bus_info(int maj, int min, drmPciBusInfoPtr info)
3145 char dname[SPECNAMELEN];
3146 char sysctl_name[16];
3147 char sysctl_val[256];
3149 int id, type, nelem;
3150 unsigned int rdev, majmin, domain, bus, dev, func;
3152 rdev = makedev(maj, min);
3153 if (!devname_r(rdev, S_IFCHR, dname, sizeof(dname)))
3156 if (sscanf(dname, "drm/%d\n", &id) != 1)
3158 type = drmGetMinorType(maj, min);
3162 /* BUG: This above section is iffy, since it mandates that a driver will
3163 * create both card and render node.
3164 * If it does not, the next DRM device will create card#X and
3165 * renderD#(128+X)-1.
3166 * This is a possibility in FreeBSD but for now there is no good way for
3167 * obtaining the info.
3170 case DRM_NODE_PRIMARY:
3172 case DRM_NODE_CONTROL:
3175 case DRM_NODE_RENDER:
3182 if (snprintf(sysctl_name, sizeof(sysctl_name), "hw.dri.%d.busid", id) <= 0)
3184 sysctl_len = sizeof(sysctl_val);
3185 if (sysctlbyname(sysctl_name, sysctl_val, &sysctl_len, NULL, 0))
3188 #define bus_fmt "pci:%04x:%02x:%02x.%u"
3190 nelem = sscanf(sysctl_val, bus_fmt, &domain, &bus, &dev, &func);
3193 info->domain = domain;
3202 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
3205 unsigned int domain, bus, dev, func;
3206 char pci_path[PATH_MAX + 1], *value;
3209 get_pci_path(maj, min, pci_path);
3211 value = sysfs_uevent_get(pci_path, "PCI_SLOT_NAME");
3215 num = sscanf(value, "%04x:%02x:%02x.%1u", &domain, &bus, &dev, &func);
3221 info->domain = domain;
3227 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3228 struct drm_pciinfo pinfo;
3231 type = drmGetMinorType(maj, min);
3235 fd = drmOpenMinor(min, 0, type);
3239 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3245 info->domain = pinfo.domain;
3246 info->bus = pinfo.bus;
3247 info->dev = pinfo.dev;
3248 info->func = pinfo.func;
3252 return get_sysctl_pci_bus_info(maj, min, info);
3254 #warning "Missing implementation of drmParsePciBusInfo"
3259 drm_public int drmDevicesEqual(drmDevicePtr a, drmDevicePtr b)
3261 if (a == NULL || b == NULL)
3264 if (a->bustype != b->bustype)
3267 switch (a->bustype) {
3269 return memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo)) == 0;
3272 return memcmp(a->businfo.usb, b->businfo.usb, sizeof(drmUsbBusInfo)) == 0;
3274 case DRM_BUS_PLATFORM:
3275 return memcmp(a->businfo.platform, b->businfo.platform, sizeof(drmPlatformBusInfo)) == 0;
3277 case DRM_BUS_HOST1X:
3278 return memcmp(a->businfo.host1x, b->businfo.host1x, sizeof(drmHost1xBusInfo)) == 0;
3287 static int drmGetNodeType(const char *name)
3289 if (strncmp(name, DRM_CONTROL_MINOR_NAME,
3290 sizeof(DRM_CONTROL_MINOR_NAME ) - 1) == 0)
3291 return DRM_NODE_CONTROL;
3293 if (strncmp(name, DRM_RENDER_MINOR_NAME,
3294 sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
3295 return DRM_NODE_RENDER;
3297 if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
3298 sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
3299 return DRM_NODE_PRIMARY;
3304 static int drmGetMaxNodeName(void)
3306 return sizeof(DRM_DIR_NAME) +
3307 MAX3(sizeof(DRM_PRIMARY_MINOR_NAME),
3308 sizeof(DRM_CONTROL_MINOR_NAME),
3309 sizeof(DRM_RENDER_MINOR_NAME)) +
3310 3 /* length of the node number */;
3314 static int parse_separate_sysfs_files(int maj, int min,
3315 drmPciDeviceInfoPtr device,
3316 bool ignore_revision)
3318 static const char *attrs[] = {
3319 "revision", /* Older kernels are missing the file, so check for it first */
3325 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3326 unsigned int data[ARRAY_SIZE(attrs)];
3330 get_pci_path(maj, min, pci_path);
3332 for (unsigned i = ignore_revision ? 1 : 0; i < ARRAY_SIZE(attrs); i++) {
3333 snprintf(path, PATH_MAX, "%s/%s", pci_path, attrs[i]);
3334 fp = fopen(path, "r");
3338 ret = fscanf(fp, "%x", &data[i]);
3345 device->revision_id = ignore_revision ? 0xff : data[0] & 0xff;
3346 device->vendor_id = data[1] & 0xffff;
3347 device->device_id = data[2] & 0xffff;
3348 device->subvendor_id = data[3] & 0xffff;
3349 device->subdevice_id = data[4] & 0xffff;
3354 static int parse_config_sysfs_file(int maj, int min,
3355 drmPciDeviceInfoPtr device)
3357 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3358 unsigned char config[64];
3361 get_pci_path(maj, min, pci_path);
3363 snprintf(path, PATH_MAX, "%s/config", pci_path);
3364 fd = open(path, O_RDONLY);
3368 ret = read(fd, config, sizeof(config));
3373 device->vendor_id = config[0] | (config[1] << 8);
3374 device->device_id = config[2] | (config[3] << 8);
3375 device->revision_id = config[8];
3376 device->subvendor_id = config[44] | (config[45] << 8);
3377 device->subdevice_id = config[46] | (config[47] << 8);
3383 static int drmParsePciDeviceInfo(int maj, int min,
3384 drmPciDeviceInfoPtr device,
3388 if (!(flags & DRM_DEVICE_GET_PCI_REVISION))
3389 return parse_separate_sysfs_files(maj, min, device, true);
3391 if (parse_separate_sysfs_files(maj, min, device, false))
3392 return parse_config_sysfs_file(maj, min, device);
3395 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3396 struct drm_pciinfo pinfo;
3399 type = drmGetMinorType(maj, min);
3403 fd = drmOpenMinor(min, 0, type);
3407 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3413 device->vendor_id = pinfo.vendor_id;
3414 device->device_id = pinfo.device_id;
3415 device->revision_id = pinfo.revision_id;
3416 device->subvendor_id = pinfo.subvendor_id;
3417 device->subdevice_id = pinfo.subdevice_id;
3422 struct pci_conf_io pc;
3423 struct pci_match_conf patterns[1];
3424 struct pci_conf results[1];
3427 if (get_sysctl_pci_bus_info(maj, min, &info) != 0)
3430 fd = open("/dev/pci", O_RDONLY, 0);
3434 bzero(&patterns, sizeof(patterns));
3435 patterns[0].pc_sel.pc_domain = info.domain;
3436 patterns[0].pc_sel.pc_bus = info.bus;
3437 patterns[0].pc_sel.pc_dev = info.dev;
3438 patterns[0].pc_sel.pc_func = info.func;
3439 patterns[0].flags = PCI_GETCONF_MATCH_DOMAIN | PCI_GETCONF_MATCH_BUS
3440 | PCI_GETCONF_MATCH_DEV | PCI_GETCONF_MATCH_FUNC;
3441 bzero(&pc, sizeof(struct pci_conf_io));
3442 pc.num_patterns = 1;
3443 pc.pat_buf_len = sizeof(patterns);
3444 pc.patterns = patterns;
3445 pc.match_buf_len = sizeof(results);
3446 pc.matches = results;
3448 if (ioctl(fd, PCIOCGETCONF, &pc) || pc.status == PCI_GETCONF_ERROR) {
3455 device->vendor_id = results[0].pc_vendor;
3456 device->device_id = results[0].pc_device;
3457 device->subvendor_id = results[0].pc_subvendor;
3458 device->subdevice_id = results[0].pc_subdevice;
3459 device->revision_id = results[0].pc_revid;
3463 #warning "Missing implementation of drmParsePciDeviceInfo"
3468 static void drmFreePlatformDevice(drmDevicePtr device)
3470 if (device->deviceinfo.platform) {
3471 if (device->deviceinfo.platform->compatible) {
3472 char **compatible = device->deviceinfo.platform->compatible;
3474 while (*compatible) {
3479 free(device->deviceinfo.platform->compatible);
3484 static void drmFreeHost1xDevice(drmDevicePtr device)
3486 if (device->deviceinfo.host1x) {
3487 if (device->deviceinfo.host1x->compatible) {
3488 char **compatible = device->deviceinfo.host1x->compatible;
3490 while (*compatible) {
3495 free(device->deviceinfo.host1x->compatible);
3500 drm_public void drmFreeDevice(drmDevicePtr *device)
3506 switch ((*device)->bustype) {
3507 case DRM_BUS_PLATFORM:
3508 drmFreePlatformDevice(*device);
3511 case DRM_BUS_HOST1X:
3512 drmFreeHost1xDevice(*device);
3521 drm_public void drmFreeDevices(drmDevicePtr devices[], int count)
3525 if (devices == NULL)
3528 for (i = 0; i < count; i++)
3530 drmFreeDevice(&devices[i]);
3533 static drmDevicePtr drmDeviceAlloc(unsigned int type, const char *node,
3534 size_t bus_size, size_t device_size,
3537 size_t max_node_length, extra, size;
3538 drmDevicePtr device;
3542 max_node_length = ALIGN(drmGetMaxNodeName(), sizeof(void *));
3543 extra = DRM_NODE_MAX * (sizeof(void *) + max_node_length);
3545 size = sizeof(*device) + extra + bus_size + device_size;
3547 device = calloc(1, size);
3551 device->available_nodes = 1 << type;
3553 ptr = (char *)device + sizeof(*device);
3554 device->nodes = (char **)ptr;
3556 ptr += DRM_NODE_MAX * sizeof(void *);
3558 for (i = 0; i < DRM_NODE_MAX; i++) {
3559 device->nodes[i] = ptr;
3560 ptr += max_node_length;
3563 memcpy(device->nodes[type], node, max_node_length);
3570 static int drmProcessPciDevice(drmDevicePtr *device,
3571 const char *node, int node_type,
3572 int maj, int min, bool fetch_deviceinfo,
3579 dev = drmDeviceAlloc(node_type, node, sizeof(drmPciBusInfo),
3580 sizeof(drmPciDeviceInfo), &addr);
3584 dev->bustype = DRM_BUS_PCI;
3586 dev->businfo.pci = (drmPciBusInfoPtr)addr;
3588 ret = drmParsePciBusInfo(maj, min, dev->businfo.pci);
3592 // Fetch the device info if the user has requested it
3593 if (fetch_deviceinfo) {
3594 addr += sizeof(drmPciBusInfo);
3595 dev->deviceinfo.pci = (drmPciDeviceInfoPtr)addr;
3597 ret = drmParsePciDeviceInfo(maj, min, dev->deviceinfo.pci, flags);
3611 static int drmParseUsbBusInfo(int maj, int min, drmUsbBusInfoPtr info)
3614 char path[PATH_MAX + 1], *value;
3615 unsigned int bus, dev;
3618 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3620 value = sysfs_uevent_get(path, "BUSNUM");
3624 ret = sscanf(value, "%03u", &bus);
3630 value = sysfs_uevent_get(path, "DEVNUM");
3634 ret = sscanf(value, "%03u", &dev);
3645 #warning "Missing implementation of drmParseUsbBusInfo"
3650 static int drmParseUsbDeviceInfo(int maj, int min, drmUsbDeviceInfoPtr info)
3653 char path[PATH_MAX + 1], *value;
3654 unsigned int vendor, product;
3657 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3659 value = sysfs_uevent_get(path, "PRODUCT");
3663 ret = sscanf(value, "%x/%x", &vendor, &product);
3669 info->vendor = vendor;
3670 info->product = product;
3674 #warning "Missing implementation of drmParseUsbDeviceInfo"
3679 static int drmProcessUsbDevice(drmDevicePtr *device, const char *node,
3680 int node_type, int maj, int min,
3681 bool fetch_deviceinfo, uint32_t flags)
3687 dev = drmDeviceAlloc(node_type, node, sizeof(drmUsbBusInfo),
3688 sizeof(drmUsbDeviceInfo), &ptr);
3692 dev->bustype = DRM_BUS_USB;
3694 dev->businfo.usb = (drmUsbBusInfoPtr)ptr;
3696 ret = drmParseUsbBusInfo(maj, min, dev->businfo.usb);
3700 if (fetch_deviceinfo) {
3701 ptr += sizeof(drmUsbBusInfo);
3702 dev->deviceinfo.usb = (drmUsbDeviceInfoPtr)ptr;
3704 ret = drmParseUsbDeviceInfo(maj, min, dev->deviceinfo.usb);
3718 static int drmParseOFBusInfo(int maj, int min, char *fullname)
3721 char path[PATH_MAX + 1], *name, *tmp_name;
3723 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3725 name = sysfs_uevent_get(path, "OF_FULLNAME");
3728 /* If the device lacks OF data, pick the MODALIAS info */
3729 name = sysfs_uevent_get(path, "MODALIAS");
3733 /* .. and strip the MODALIAS=[platform,usb...]: part. */
3734 tmp_name = strrchr(name, ':');
3742 strncpy(fullname, tmp_name, DRM_PLATFORM_DEVICE_NAME_LEN);
3743 fullname[DRM_PLATFORM_DEVICE_NAME_LEN - 1] = '\0';
3748 #warning "Missing implementation of drmParseOFBusInfo"
3753 static int drmParseOFDeviceInfo(int maj, int min, char ***compatible)
3756 char path[PATH_MAX + 1], *value, *tmp_name;
3757 unsigned int count, i;
3760 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3762 value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
3764 sscanf(value, "%u", &count);
3767 /* Assume one entry if the device lack OF data */
3771 *compatible = calloc(count + 1, sizeof(char *));
3775 for (i = 0; i < count; i++) {
3776 value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
3779 /* If the device lacks OF data, pick the MODALIAS info */
3780 value = sysfs_uevent_get(path, "MODALIAS");
3786 /* .. and strip the MODALIAS=[platform,usb...]: part. */
3787 tmp_name = strrchr(value, ':');
3792 tmp_name = strdup(tmp_name + 1);
3796 (*compatible)[i] = tmp_name;
3803 free((*compatible)[i]);
3808 #warning "Missing implementation of drmParseOFDeviceInfo"
3813 static int drmProcessPlatformDevice(drmDevicePtr *device,
3814 const char *node, int node_type,
3815 int maj, int min, bool fetch_deviceinfo,
3822 dev = drmDeviceAlloc(node_type, node, sizeof(drmPlatformBusInfo),
3823 sizeof(drmPlatformDeviceInfo), &ptr);
3827 dev->bustype = DRM_BUS_PLATFORM;
3829 dev->businfo.platform = (drmPlatformBusInfoPtr)ptr;
3831 ret = drmParseOFBusInfo(maj, min, dev->businfo.platform->fullname);
3835 if (fetch_deviceinfo) {
3836 ptr += sizeof(drmPlatformBusInfo);
3837 dev->deviceinfo.platform = (drmPlatformDeviceInfoPtr)ptr;
3839 ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.platform->compatible);
3853 static int drmProcessHost1xDevice(drmDevicePtr *device,
3854 const char *node, int node_type,
3855 int maj, int min, bool fetch_deviceinfo,
3862 dev = drmDeviceAlloc(node_type, node, sizeof(drmHost1xBusInfo),
3863 sizeof(drmHost1xDeviceInfo), &ptr);
3867 dev->bustype = DRM_BUS_HOST1X;
3869 dev->businfo.host1x = (drmHost1xBusInfoPtr)ptr;
3871 ret = drmParseOFBusInfo(maj, min, dev->businfo.host1x->fullname);
3875 if (fetch_deviceinfo) {
3876 ptr += sizeof(drmHost1xBusInfo);
3877 dev->deviceinfo.host1x = (drmHost1xDeviceInfoPtr)ptr;
3879 ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.host1x->compatible);
3894 process_device(drmDevicePtr *device, const char *d_name,
3895 int req_subsystem_type,
3896 bool fetch_deviceinfo, uint32_t flags)
3899 char node[PATH_MAX + 1];
3900 int node_type, subsystem_type;
3901 unsigned int maj, min;
3903 node_type = drmGetNodeType(d_name);
3907 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, d_name);
3908 if (stat(node, &sbuf))
3911 maj = major(sbuf.st_rdev);
3912 min = minor(sbuf.st_rdev);
3914 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3917 subsystem_type = drmParseSubsystemType(maj, min);
3918 if (req_subsystem_type != -1 && req_subsystem_type != subsystem_type)
3921 switch (subsystem_type) {
3923 return drmProcessPciDevice(device, node, node_type, maj, min,
3924 fetch_deviceinfo, flags);
3926 return drmProcessUsbDevice(device, node, node_type, maj, min,
3927 fetch_deviceinfo, flags);
3928 case DRM_BUS_PLATFORM:
3929 return drmProcessPlatformDevice(device, node, node_type, maj, min,
3930 fetch_deviceinfo, flags);
3931 case DRM_BUS_HOST1X:
3932 return drmProcessHost1xDevice(device, node, node_type, maj, min,
3933 fetch_deviceinfo, flags);
3939 /* Consider devices located on the same bus as duplicate and fold the respective
3940 * entries into a single one.
3942 * Note: this leaves "gaps" in the array, while preserving the length.
3944 static void drmFoldDuplicatedDevices(drmDevicePtr local_devices[], int count)
3946 int node_type, i, j;
3948 for (i = 0; i < count; i++) {
3949 for (j = i + 1; j < count; j++) {
3950 if (drmDevicesEqual(local_devices[i], local_devices[j])) {
3951 local_devices[i]->available_nodes |= local_devices[j]->available_nodes;
3952 node_type = log2(local_devices[j]->available_nodes);
3953 memcpy(local_devices[i]->nodes[node_type],
3954 local_devices[j]->nodes[node_type], drmGetMaxNodeName());
3955 drmFreeDevice(&local_devices[j]);
3961 /* Check that the given flags are valid returning 0 on success */
3963 drm_device_validate_flags(uint32_t flags)
3965 return (flags & ~DRM_DEVICE_GET_PCI_REVISION);
3969 drm_device_has_rdev(drmDevicePtr device, dev_t find_rdev)
3973 for (int i = 0; i < DRM_NODE_MAX; i++) {
3974 if (device->available_nodes & 1 << i) {
3975 if (stat(device->nodes[i], &sbuf) == 0 &&
3976 sbuf.st_rdev == find_rdev)
3984 * The kernel drm core has a number of places that assume maximum of
3985 * 3x64 devices nodes. That's 64 for each of primary, control and
3986 * render nodes. Rounded it up to 256 for simplicity.
3988 #define MAX_DRM_NODES 256
3991 * Get information about the opened drm device
3993 * \param fd file descriptor of the drm device
3994 * \param flags feature/behaviour bitmask
3995 * \param device the address of a drmDevicePtr where the information
3996 * will be allocated in stored
3998 * \return zero on success, negative error code otherwise.
4000 * \note Unlike drmGetDevice it does not retrieve the pci device revision field
4001 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
4003 drm_public int drmGetDevice2(int fd, uint32_t flags, drmDevicePtr *device)
4007 * DRI device nodes on OpenBSD are not in their own directory, they reside
4008 * in /dev along with a large number of statically generated /dev nodes.
4009 * Avoid stat'ing all of /dev needlessly by implementing this custom path.
4013 char node[PATH_MAX + 1];
4014 const char *dev_name;
4015 int node_type, subsystem_type;
4016 int maj, min, n, ret;
4018 if (fd == -1 || device == NULL)
4021 if (fstat(fd, &sbuf))
4024 maj = major(sbuf.st_rdev);
4025 min = minor(sbuf.st_rdev);
4027 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4030 node_type = drmGetMinorType(maj, min);
4031 if (node_type == -1)
4034 dev_name = drmGetDeviceName(node_type);
4038 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min);
4039 if (n == -1 || n >= PATH_MAX)
4041 if (stat(node, &sbuf))
4044 subsystem_type = drmParseSubsystemType(maj, min);
4045 if (subsystem_type != DRM_BUS_PCI)
4048 ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
4056 drmDevicePtr local_devices[MAX_DRM_NODES];
4059 struct dirent *dent;
4063 int ret, i, node_count;
4066 if (drm_device_validate_flags(flags))
4069 if (fd == -1 || device == NULL)
4072 if (fstat(fd, &sbuf))
4075 find_rdev = sbuf.st_rdev;
4076 maj = major(sbuf.st_rdev);
4077 min = minor(sbuf.st_rdev);
4079 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4082 subsystem_type = drmParseSubsystemType(maj, min);
4083 if (subsystem_type < 0)
4084 return subsystem_type;
4086 sysdir = opendir(DRM_DIR_NAME);
4091 while ((dent = readdir(sysdir))) {
4092 ret = process_device(&d, dent->d_name, subsystem_type, true, flags);
4096 if (i >= MAX_DRM_NODES) {
4097 fprintf(stderr, "More than %d drm nodes detected. "
4098 "Please report a bug - that should not happen.\n"
4099 "Skipping extra nodes\n", MAX_DRM_NODES);
4102 local_devices[i] = d;
4107 drmFoldDuplicatedDevices(local_devices, node_count);
4111 for (i = 0; i < node_count; i++) {
4112 if (!local_devices[i])
4115 if (drm_device_has_rdev(local_devices[i], find_rdev))
4116 *device = local_devices[i];
4118 drmFreeDevice(&local_devices[i]);
4122 if (*device == NULL)
4129 * Get information about the opened drm device
4131 * \param fd file descriptor of the drm device
4132 * \param device the address of a drmDevicePtr where the information
4133 * will be allocated in stored
4135 * \return zero on success, negative error code otherwise.
4137 drm_public int drmGetDevice(int fd, drmDevicePtr *device)
4139 return drmGetDevice2(fd, DRM_DEVICE_GET_PCI_REVISION, device);
4143 * Get drm devices on the system
4145 * \param flags feature/behaviour bitmask
4146 * \param devices the array of devices with drmDevicePtr elements
4147 * can be NULL to get the device number first
4148 * \param max_devices the maximum number of devices for the array
4150 * \return on error - negative error code,
4151 * if devices is NULL - total number of devices available on the system,
4152 * alternatively the number of devices stored in devices[], which is
4153 * capped by the max_devices.
4155 * \note Unlike drmGetDevices it does not retrieve the pci device revision field
4156 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
4158 drm_public int drmGetDevices2(uint32_t flags, drmDevicePtr devices[],
4161 drmDevicePtr local_devices[MAX_DRM_NODES];
4162 drmDevicePtr device;
4164 struct dirent *dent;
4165 int ret, i, node_count, device_count;
4167 if (drm_device_validate_flags(flags))
4170 sysdir = opendir(DRM_DIR_NAME);
4175 while ((dent = readdir(sysdir))) {
4176 ret = process_device(&device, dent->d_name, -1, devices != NULL, flags);
4180 if (i >= MAX_DRM_NODES) {
4181 fprintf(stderr, "More than %d drm nodes detected. "
4182 "Please report a bug - that should not happen.\n"
4183 "Skipping extra nodes\n", MAX_DRM_NODES);
4186 local_devices[i] = device;
4191 drmFoldDuplicatedDevices(local_devices, node_count);
4194 for (i = 0; i < node_count; i++) {
4195 if (!local_devices[i])
4198 if ((devices != NULL) && (device_count < max_devices))
4199 devices[device_count] = local_devices[i];
4201 drmFreeDevice(&local_devices[i]);
4207 return device_count;
4211 * Get drm devices on the system
4213 * \param devices the array of devices with drmDevicePtr elements
4214 * can be NULL to get the device number first
4215 * \param max_devices the maximum number of devices for the array
4217 * \return on error - negative error code,
4218 * if devices is NULL - total number of devices available on the system,
4219 * alternatively the number of devices stored in devices[], which is
4220 * capped by the max_devices.
4222 drm_public int drmGetDevices(drmDevicePtr devices[], int max_devices)
4224 return drmGetDevices2(DRM_DEVICE_GET_PCI_REVISION, devices, max_devices);
4227 drm_public char *drmGetDeviceNameFromFd2(int fd)
4231 char path[PATH_MAX + 1], *value;
4232 unsigned int maj, min;
4234 if (fstat(fd, &sbuf))
4237 maj = major(sbuf.st_rdev);
4238 min = minor(sbuf.st_rdev);
4240 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4243 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d", maj, min);
4245 value = sysfs_uevent_get(path, "DEVNAME");
4249 snprintf(path, sizeof(path), "/dev/%s", value);
4252 return strdup(path);
4254 return drmGetDeviceNameFromFd(fd);
4257 char node[PATH_MAX + 1];
4258 const char *dev_name;
4262 if (fstat(fd, &sbuf))
4265 maj = major(sbuf.st_rdev);
4266 min = minor(sbuf.st_rdev);
4268 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4271 node_type = drmGetMinorType(maj, min);
4272 if (node_type == -1)
4275 dev_name = drmGetDeviceName(node_type);
4279 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min);
4280 if (n == -1 || n >= PATH_MAX)
4283 return strdup(node);
4287 drm_public int drmSyncobjCreate(int fd, uint32_t flags, uint32_t *handle)
4289 struct drm_syncobj_create args;
4295 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_CREATE, &args);
4298 *handle = args.handle;
4302 drm_public int drmSyncobjDestroy(int fd, uint32_t handle)
4304 struct drm_syncobj_destroy args;
4307 args.handle = handle;
4308 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_DESTROY, &args);
4311 drm_public int drmSyncobjHandleToFD(int fd, uint32_t handle, int *obj_fd)
4313 struct drm_syncobj_handle args;
4318 args.handle = handle;
4319 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4326 drm_public int drmSyncobjFDToHandle(int fd, int obj_fd, uint32_t *handle)
4328 struct drm_syncobj_handle args;
4334 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4337 *handle = args.handle;
4341 drm_public int drmSyncobjImportSyncFile(int fd, uint32_t handle,
4344 struct drm_syncobj_handle args;
4347 args.fd = sync_file_fd;
4348 args.handle = handle;
4349 args.flags = DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE;
4350 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4353 drm_public int drmSyncobjExportSyncFile(int fd, uint32_t handle,
4356 struct drm_syncobj_handle args;
4361 args.handle = handle;
4362 args.flags = DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE;
4363 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4366 *sync_file_fd = args.fd;
4370 drm_public int drmSyncobjWait(int fd, uint32_t *handles, unsigned num_handles,
4371 int64_t timeout_nsec, unsigned flags,
4372 uint32_t *first_signaled)
4374 struct drm_syncobj_wait args;
4378 args.handles = (uintptr_t)handles;
4379 args.timeout_nsec = timeout_nsec;
4380 args.count_handles = num_handles;
4383 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_WAIT, &args);
4388 *first_signaled = args.first_signaled;
4392 drm_public int drmSyncobjReset(int fd, const uint32_t *handles,
4393 uint32_t handle_count)
4395 struct drm_syncobj_array args;
4399 args.handles = (uintptr_t)handles;
4400 args.count_handles = handle_count;
4402 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_RESET, &args);
4406 drm_public int drmSyncobjSignal(int fd, const uint32_t *handles,
4407 uint32_t handle_count)
4409 struct drm_syncobj_array args;
4413 args.handles = (uintptr_t)handles;
4414 args.count_handles = handle_count;
4416 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_SIGNAL, &args);
4420 drm_public int drmSyncobjTimelineSignal(int fd, const uint32_t *handles,
4421 uint64_t *points, uint32_t handle_count)
4423 struct drm_syncobj_timeline_array args;
4427 args.handles = (uintptr_t)handles;
4428 args.points = (uintptr_t)points;
4429 args.count_handles = handle_count;
4431 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TIMELINE_SIGNAL, &args);
4435 drm_public int drmSyncobjTimelineWait(int fd, uint32_t *handles, uint64_t *points,
4436 unsigned num_handles,
4437 int64_t timeout_nsec, unsigned flags,
4438 uint32_t *first_signaled)
4440 struct drm_syncobj_timeline_wait args;
4444 args.handles = (uintptr_t)handles;
4445 args.points = (uintptr_t)points;
4446 args.timeout_nsec = timeout_nsec;
4447 args.count_handles = num_handles;
4450 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TIMELINE_WAIT, &args);
4455 *first_signaled = args.first_signaled;
4460 drm_public int drmSyncobjQuery(int fd, uint32_t *handles, uint64_t *points,
4461 uint32_t handle_count)
4463 struct drm_syncobj_timeline_array args;
4467 args.handles = (uintptr_t)handles;
4468 args.points = (uintptr_t)points;
4469 args.count_handles = handle_count;
4471 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_QUERY, &args);
4477 drm_public int drmSyncobjQuery2(int fd, uint32_t *handles, uint64_t *points,
4478 uint32_t handle_count, uint32_t flags)
4480 struct drm_syncobj_timeline_array args;
4483 args.handles = (uintptr_t)handles;
4484 args.points = (uintptr_t)points;
4485 args.count_handles = handle_count;
4488 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_QUERY, &args);
4492 drm_public int drmSyncobjTransfer(int fd,
4493 uint32_t dst_handle, uint64_t dst_point,
4494 uint32_t src_handle, uint64_t src_point,
4497 struct drm_syncobj_transfer args;
4501 args.src_handle = src_handle;
4502 args.dst_handle = dst_handle;
4503 args.src_point = src_point;
4504 args.dst_point = dst_point;
4507 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TRANSFER, &args);