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 static unsigned log2_int(unsigned x)
135 if ((unsigned)(1 << l) > x) {
143 drm_public void drmSetServerInfo(drmServerInfoPtr info)
145 drm_server_info = info;
149 * Output a message to stderr.
151 * \param format printf() like format string.
154 * This function is a wrapper around vfprintf().
157 static int DRM_PRINTFLIKE(1, 0)
158 drmDebugPrint(const char *format, va_list ap)
160 return vfprintf(stderr, format, ap);
164 drmMsg(const char *format, ...)
168 if (((env = getenv("LIBGL_DEBUG")) && strstr(env, "verbose")) ||
169 (drm_server_info && drm_server_info->debug_print))
171 va_start(ap, format);
172 if (drm_server_info) {
173 drm_server_info->debug_print(format,ap);
175 drmDebugPrint(format, ap);
181 static void *drmHashTable = NULL; /* Context switch callbacks */
183 drm_public void *drmGetHashTable(void)
188 drm_public void *drmMalloc(int size)
190 return calloc(1, size);
193 drm_public void drmFree(void *pt)
199 * Call ioctl, restarting if it is interrupted
202 drmIoctl(int fd, unsigned long request, void *arg)
207 ret = ioctl(fd, request, arg);
208 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
212 static unsigned long drmGetKeyFromFd(int fd)
221 drm_public drmHashEntry *drmGetEntry(int fd)
223 unsigned long key = drmGetKeyFromFd(fd);
228 drmHashTable = drmHashCreate();
230 if (drmHashLookup(drmHashTable, key, &value)) {
231 entry = drmMalloc(sizeof(*entry));
234 entry->tagTable = drmHashCreate();
235 drmHashInsert(drmHashTable, key, entry);
243 * Compare two busid strings
248 * \return 1 if matched.
251 * This function compares two bus ID strings. It understands the older
252 * PCI:b:d:f format and the newer pci:oooo:bb:dd.f format. In the format, o is
253 * domain, b is bus, d is device, f is function.
255 static int drmMatchBusID(const char *id1, const char *id2, int pci_domain_ok)
257 /* First, check if the IDs are exactly the same */
258 if (strcasecmp(id1, id2) == 0)
261 /* Try to match old/new-style PCI bus IDs. */
262 if (strncasecmp(id1, "pci", 3) == 0) {
263 unsigned int o1, b1, d1, f1;
264 unsigned int o2, b2, d2, f2;
267 ret = sscanf(id1, "pci:%04x:%02x:%02x.%u", &o1, &b1, &d1, &f1);
270 ret = sscanf(id1, "PCI:%u:%u:%u", &b1, &d1, &f1);
275 ret = sscanf(id2, "pci:%04x:%02x:%02x.%u", &o2, &b2, &d2, &f2);
278 ret = sscanf(id2, "PCI:%u:%u:%u", &b2, &d2, &f2);
283 /* If domains aren't properly supported by the kernel interface,
284 * just ignore them, which sucks less than picking a totally random
285 * card with "open by name"
290 if ((o1 != o2) || (b1 != b2) || (d1 != d2) || (f1 != f2))
299 * Handles error checking for chown call.
301 * \param path to file.
302 * \param id of the new owner.
303 * \param id of the new group.
305 * \return zero if success or -1 if failure.
308 * Checks for failure. If failure was caused by signal call chown again.
309 * If any other failure happened then it will output error message using
313 static int chown_check_return(const char *path, uid_t owner, gid_t group)
318 rv = chown(path, owner, group);
319 } while (rv != 0 && errno == EINTR);
324 drmMsg("Failed to change owner or group for file %s! %d: %s\n",
325 path, errno, strerror(errno));
330 static const char *drmGetDeviceName(int type)
333 case DRM_NODE_PRIMARY:
335 case DRM_NODE_CONTROL:
336 return DRM_CONTROL_DEV_NAME;
337 case DRM_NODE_RENDER:
338 return DRM_RENDER_DEV_NAME;
344 * Open the DRM device, creating it if necessary.
346 * \param dev major and minor numbers of the device.
347 * \param minor minor number of the device.
349 * \return a file descriptor on success, or a negative value on error.
352 * Assembles the device name from \p minor and opens it, creating the device
353 * special file node with the major and minor numbers specified by \p dev and
354 * parent directory if necessary and was called by root.
356 static int drmOpenDevice(dev_t dev, int minor, int type)
359 const char *dev_name = drmGetDeviceName(type);
360 char buf[DRM_NODE_NAME_MAX];
362 mode_t devmode = DRM_DEV_MODE, serv_mode;
365 int isroot = !geteuid();
366 uid_t user = DRM_DEV_UID;
367 gid_t group = DRM_DEV_GID;
373 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
374 drmMsg("drmOpenDevice: node name is %s\n", buf);
376 if (drm_server_info && drm_server_info->get_perms) {
377 drm_server_info->get_perms(&serv_group, &serv_mode);
378 devmode = serv_mode ? serv_mode : DRM_DEV_MODE;
379 devmode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
383 if (stat(DRM_DIR_NAME, &st)) {
385 return DRM_ERR_NOT_ROOT;
386 mkdir(DRM_DIR_NAME, DRM_DEV_DIRMODE);
387 chown_check_return(DRM_DIR_NAME, 0, 0); /* root:root */
388 chmod(DRM_DIR_NAME, DRM_DEV_DIRMODE);
391 /* Check if the device node exists and create it if necessary. */
392 if (stat(buf, &st)) {
394 return DRM_ERR_NOT_ROOT;
396 mknod(buf, S_IFCHR | devmode, dev);
399 if (drm_server_info && drm_server_info->get_perms) {
400 group = ((int)serv_group >= 0) ? serv_group : DRM_DEV_GID;
401 chown_check_return(buf, user, group);
405 /* if we modprobed then wait for udev */
409 if (stat(DRM_DIR_NAME, &st)) {
413 if (udev_count == 50)
418 if (stat(buf, &st)) {
422 if (udev_count == 50)
429 fd = open(buf, O_RDWR | O_CLOEXEC, 0);
430 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
431 fd, fd < 0 ? strerror(errno) : "OK");
436 /* Check if the device node is not what we expect it to be, and recreate it
437 * and try again if so.
439 if (st.st_rdev != dev) {
441 return DRM_ERR_NOT_ROOT;
443 mknod(buf, S_IFCHR | devmode, dev);
444 if (drm_server_info && drm_server_info->get_perms) {
445 chown_check_return(buf, user, group);
449 fd = open(buf, O_RDWR | O_CLOEXEC, 0);
450 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
451 fd, fd < 0 ? strerror(errno) : "OK");
455 drmMsg("drmOpenDevice: Open failed\n");
463 * Open the DRM device
465 * \param minor device minor number.
466 * \param create allow to create the device if set.
468 * \return a file descriptor on success, or a negative value on error.
471 * Calls drmOpenDevice() if \p create is set, otherwise assembles the device
472 * name from \p minor and opens it.
474 static int drmOpenMinor(int minor, int create, int type)
477 char buf[DRM_NODE_NAME_MAX];
478 const char *dev_name = drmGetDeviceName(type);
481 return drmOpenDevice(makedev(DRM_MAJOR, minor), minor, type);
486 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
487 if ((fd = open(buf, O_RDWR | O_CLOEXEC, 0)) >= 0)
494 * Determine whether the DRM kernel driver has been loaded.
496 * \return 1 if the DRM driver is loaded, 0 otherwise.
499 * Determine the presence of the kernel driver by attempting to open the 0
500 * minor and get version information. For backward compatibility with older
501 * Linux implementations, /proc/dri is also checked.
503 drm_public int drmAvailable(void)
505 drmVersionPtr version;
509 if ((fd = drmOpenMinor(0, 1, DRM_NODE_PRIMARY)) < 0) {
511 /* Try proc for backward Linux compatibility */
512 if (!access("/proc/dri/0", R_OK))
518 if ((version = drmGetVersion(fd))) {
520 drmFreeVersion(version);
527 static int drmGetMinorBase(int type)
530 case DRM_NODE_PRIMARY:
532 case DRM_NODE_CONTROL:
534 case DRM_NODE_RENDER:
541 static int drmGetMinorType(int major, int minor)
544 char name[SPECNAMELEN];
547 if (!devname_r(makedev(major, minor), S_IFCHR, name, sizeof(name)))
550 if (sscanf(name, "drm/%d", &id) != 1) {
551 // If not in /dev/drm/ we have the type in the name
552 if (sscanf(name, "dri/card%d\n", &id) >= 1)
553 return DRM_NODE_PRIMARY;
554 else if (sscanf(name, "dri/control%d\n", &id) >= 1)
555 return DRM_NODE_CONTROL;
556 else if (sscanf(name, "dri/renderD%d\n", &id) >= 1)
557 return DRM_NODE_RENDER;
563 int type = minor >> 6;
569 case DRM_NODE_PRIMARY:
570 case DRM_NODE_CONTROL:
571 case DRM_NODE_RENDER:
578 static const char *drmGetMinorName(int type)
581 case DRM_NODE_PRIMARY:
582 return DRM_PRIMARY_MINOR_NAME;
583 case DRM_NODE_CONTROL:
584 return DRM_CONTROL_MINOR_NAME;
585 case DRM_NODE_RENDER:
586 return DRM_RENDER_MINOR_NAME;
593 * Open the device by bus ID.
595 * \param busid bus ID.
596 * \param type device node type.
598 * \return a file descriptor on success, or a negative value on error.
601 * This function attempts to open every possible minor (up to DRM_MAX_MINOR),
602 * comparing the device bus ID with the one supplied.
604 * \sa drmOpenMinor() and drmGetBusid().
606 static int drmOpenByBusid(const char *busid, int type)
608 int i, pci_domain_ok = 1;
612 int base = drmGetMinorBase(type);
617 drmMsg("drmOpenByBusid: Searching for BusID %s\n", busid);
618 for (i = base; i < base + DRM_MAX_MINOR; i++) {
619 fd = drmOpenMinor(i, 1, type);
620 drmMsg("drmOpenByBusid: drmOpenMinor returns %d\n", fd);
622 /* We need to try for 1.4 first for proper PCI domain support
623 * and if that fails, we know the kernel is busted
627 sv.drm_dd_major = -1; /* Don't care */
628 sv.drm_dd_minor = -1; /* Don't care */
629 if (drmSetInterfaceVersion(fd, &sv)) {
635 sv.drm_dd_major = -1; /* Don't care */
636 sv.drm_dd_minor = -1; /* Don't care */
637 drmMsg("drmOpenByBusid: Interface 1.4 failed, trying 1.1\n");
638 drmSetInterfaceVersion(fd, &sv);
640 buf = drmGetBusid(fd);
641 drmMsg("drmOpenByBusid: drmGetBusid reports %s\n", buf);
642 if (buf && drmMatchBusID(buf, busid, pci_domain_ok)) {
656 * Open the device by name.
658 * \param name driver name.
659 * \param type the device node type.
661 * \return a file descriptor on success, or a negative value on error.
664 * This function opens the first minor number that matches the driver name and
665 * isn't already in use. If it's in use it then it will already have a bus ID
668 * \sa drmOpenMinor(), drmGetVersion() and drmGetBusid().
670 static int drmOpenByName(const char *name, int type)
674 drmVersionPtr version;
676 int base = drmGetMinorBase(type);
682 * Open the first minor number that matches the driver name and isn't
683 * already in use. If it's in use it will have a busid assigned already.
685 for (i = base; i < base + DRM_MAX_MINOR; i++) {
686 if ((fd = drmOpenMinor(i, 1, type)) >= 0) {
687 if ((version = drmGetVersion(fd))) {
688 if (!strcmp(version->name, name)) {
689 drmFreeVersion(version);
690 id = drmGetBusid(fd);
691 drmMsg("drmGetBusid returned '%s'\n", id ? id : "NULL");
700 drmFreeVersion(version);
708 /* Backward-compatibility /proc support */
709 for (i = 0; i < 8; i++) {
710 char proc_name[64], buf[512];
711 char *driver, *pt, *devstring;
714 sprintf(proc_name, "/proc/dri/%d/name", i);
715 if ((fd = open(proc_name, O_RDONLY, 0)) >= 0) {
716 retcode = read(fd, buf, sizeof(buf)-1);
719 buf[retcode-1] = '\0';
720 for (driver = pt = buf; *pt && *pt != ' '; ++pt)
722 if (*pt) { /* Device is next */
724 if (!strcmp(driver, name)) { /* Match */
725 for (devstring = ++pt; *pt && *pt != ' '; ++pt)
727 if (*pt) { /* Found busid */
728 return drmOpenByBusid(++pt, type);
729 } else { /* No busid */
730 return drmOpenDevice(strtol(devstring, NULL, 0),i, type);
744 * Open the DRM device.
746 * Looks up the specified name and bus ID, and opens the device found. The
747 * entry in /dev/dri is created if necessary and if called by root.
749 * \param name driver name. Not referenced if bus ID is supplied.
750 * \param busid bus ID. Zero if not known.
752 * \return a file descriptor on success, or a negative value on error.
755 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
758 drm_public int drmOpen(const char *name, const char *busid)
760 return drmOpenWithType(name, busid, DRM_NODE_PRIMARY);
764 * Open the DRM device with specified type.
766 * Looks up the specified name and bus ID, and opens the device found. The
767 * entry in /dev/dri is created if necessary and if called by root.
769 * \param name driver name. Not referenced if bus ID is supplied.
770 * \param busid bus ID. Zero if not known.
771 * \param type the device node type to open, PRIMARY, CONTROL or RENDER
773 * \return a file descriptor on success, or a negative value on error.
776 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
779 drm_public int drmOpenWithType(const char *name, const char *busid, int type)
781 if (name != NULL && drm_server_info &&
782 drm_server_info->load_module && !drmAvailable()) {
783 /* try to load the kernel module */
784 if (!drm_server_info->load_module(name)) {
785 drmMsg("[drm] failed to load kernel module \"%s\"\n", name);
791 int fd = drmOpenByBusid(busid, type);
797 return drmOpenByName(name, type);
802 drm_public int drmOpenControl(int minor)
804 return drmOpenMinor(minor, 0, DRM_NODE_CONTROL);
807 drm_public int drmOpenRender(int minor)
809 return drmOpenMinor(minor, 0, DRM_NODE_RENDER);
813 * Free the version information returned by drmGetVersion().
815 * \param v pointer to the version information.
818 * It frees the memory pointed by \p %v as well as all the non-null strings
821 drm_public void drmFreeVersion(drmVersionPtr v)
833 * Free the non-public version information returned by the kernel.
835 * \param v pointer to the version information.
838 * Used by drmGetVersion() to free the memory pointed by \p %v as well as all
839 * the non-null strings pointers in it.
841 static void drmFreeKernelVersion(drm_version_t *v)
853 * Copy version information.
855 * \param d destination pointer.
856 * \param s source pointer.
859 * Used by drmGetVersion() to translate the information returned by the ioctl
860 * interface in a private structure into the public structure counterpart.
862 static void drmCopyVersion(drmVersionPtr d, const drm_version_t *s)
864 d->version_major = s->version_major;
865 d->version_minor = s->version_minor;
866 d->version_patchlevel = s->version_patchlevel;
867 d->name_len = s->name_len;
868 d->name = strdup(s->name);
869 d->date_len = s->date_len;
870 d->date = strdup(s->date);
871 d->desc_len = s->desc_len;
872 d->desc = strdup(s->desc);
877 * Query the driver version information.
879 * \param fd file descriptor.
881 * \return pointer to a drmVersion structure which should be freed with
884 * \note Similar information is available via /proc/dri.
887 * It gets the version information via successive DRM_IOCTL_VERSION ioctls,
888 * first with zeros to get the string lengths, and then the actually strings.
889 * It also null-terminates them since they might not be already.
891 drm_public drmVersionPtr drmGetVersion(int fd)
893 drmVersionPtr retval;
894 drm_version_t *version = drmMalloc(sizeof(*version));
896 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
897 drmFreeKernelVersion(version);
901 if (version->name_len)
902 version->name = drmMalloc(version->name_len + 1);
903 if (version->date_len)
904 version->date = drmMalloc(version->date_len + 1);
905 if (version->desc_len)
906 version->desc = drmMalloc(version->desc_len + 1);
908 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
909 drmMsg("DRM_IOCTL_VERSION: %s\n", strerror(errno));
910 drmFreeKernelVersion(version);
914 /* The results might not be null-terminated strings, so terminate them. */
915 if (version->name_len) version->name[version->name_len] = '\0';
916 if (version->date_len) version->date[version->date_len] = '\0';
917 if (version->desc_len) version->desc[version->desc_len] = '\0';
919 retval = drmMalloc(sizeof(*retval));
920 drmCopyVersion(retval, version);
921 drmFreeKernelVersion(version);
927 * Get version information for the DRM user space library.
929 * This version number is driver independent.
931 * \param fd file descriptor.
933 * \return version information.
936 * This function allocates and fills a drm_version structure with a hard coded
939 drm_public drmVersionPtr drmGetLibVersion(int fd)
941 drm_version_t *version = drmMalloc(sizeof(*version));
944 * NOTE THIS MUST NOT GO ABOVE VERSION 1.X due to drivers needing it
945 * revision 1.0.x = original DRM interface with no drmGetLibVersion
946 * entry point and many drm<Device> extensions
947 * revision 1.1.x = added drmCommand entry points for device extensions
948 * added drmGetLibVersion to identify libdrm.a version
949 * revision 1.2.x = added drmSetInterfaceVersion
950 * modified drmOpen to handle both busid and name
951 * revision 1.3.x = added server + memory manager
953 version->version_major = 1;
954 version->version_minor = 3;
955 version->version_patchlevel = 0;
957 return (drmVersionPtr)version;
960 drm_public int drmGetCap(int fd, uint64_t capability, uint64_t *value)
962 struct drm_get_cap cap;
966 cap.capability = capability;
968 ret = drmIoctl(fd, DRM_IOCTL_GET_CAP, &cap);
976 drm_public int drmSetClientCap(int fd, uint64_t capability, uint64_t value)
978 struct drm_set_client_cap cap;
981 cap.capability = capability;
984 return drmIoctl(fd, DRM_IOCTL_SET_CLIENT_CAP, &cap);
988 * Free the bus ID information.
990 * \param busid bus ID information string as given by drmGetBusid().
993 * This function is just frees the memory pointed by \p busid.
995 drm_public void drmFreeBusid(const char *busid)
997 drmFree((void *)busid);
1002 * Get the bus ID of the device.
1004 * \param fd file descriptor.
1006 * \return bus ID string.
1009 * This function gets the bus ID via successive DRM_IOCTL_GET_UNIQUE ioctls to
1010 * get the string length and data, passing the arguments in a drm_unique
1013 drm_public char *drmGetBusid(int fd)
1019 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
1021 u.unique = drmMalloc(u.unique_len + 1);
1022 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u)) {
1026 u.unique[u.unique_len] = '\0';
1033 * Set the bus ID of the device.
1035 * \param fd file descriptor.
1036 * \param busid bus ID string.
1038 * \return zero on success, negative on failure.
1041 * This function is a wrapper around the DRM_IOCTL_SET_UNIQUE ioctl, passing
1042 * the arguments in a drm_unique structure.
1044 drm_public int drmSetBusid(int fd, const char *busid)
1049 u.unique = (char *)busid;
1050 u.unique_len = strlen(busid);
1052 if (drmIoctl(fd, DRM_IOCTL_SET_UNIQUE, &u)) {
1058 drm_public int drmGetMagic(int fd, drm_magic_t * magic)
1065 if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
1067 *magic = auth.magic;
1071 drm_public int drmAuthMagic(int fd, drm_magic_t magic)
1077 if (drmIoctl(fd, DRM_IOCTL_AUTH_MAGIC, &auth))
1083 * Specifies a range of memory that is available for mapping by a
1086 * \param fd file descriptor.
1087 * \param offset usually the physical address. The actual meaning depends of
1088 * the \p type parameter. See below.
1089 * \param size of the memory in bytes.
1090 * \param type type of the memory to be mapped.
1091 * \param flags combination of several flags to modify the function actions.
1092 * \param handle will be set to a value that may be used as the offset
1093 * parameter for mmap().
1095 * \return zero on success or a negative value on error.
1097 * \par Mapping the frame buffer
1098 * For the frame buffer
1099 * - \p offset will be the physical address of the start of the frame buffer,
1100 * - \p size will be the size of the frame buffer in bytes, and
1101 * - \p type will be DRM_FRAME_BUFFER.
1104 * The area mapped will be uncached. If MTRR support is available in the
1105 * kernel, the frame buffer area will be set to write combining.
1107 * \par Mapping the MMIO register area
1108 * For the MMIO register area,
1109 * - \p offset will be the physical address of the start of the register area,
1110 * - \p size will be the size of the register area bytes, and
1111 * - \p type will be DRM_REGISTERS.
1113 * The area mapped will be uncached.
1115 * \par Mapping the SAREA
1117 * - \p offset will be ignored and should be set to zero,
1118 * - \p size will be the desired size of the SAREA in bytes,
1119 * - \p type will be DRM_SHM.
1122 * A shared memory area of the requested size will be created and locked in
1123 * kernel memory. This area may be mapped into client-space by using the handle
1126 * \note May only be called by root.
1129 * This function is a wrapper around the DRM_IOCTL_ADD_MAP ioctl, passing
1130 * the arguments in a drm_map structure.
1132 drm_public int drmAddMap(int fd, drm_handle_t offset, drmSize size, drmMapType type,
1133 drmMapFlags flags, drm_handle_t *handle)
1138 map.offset = offset;
1142 if (drmIoctl(fd, DRM_IOCTL_ADD_MAP, &map))
1145 *handle = (drm_handle_t)(uintptr_t)map.handle;
1149 drm_public int drmRmMap(int fd, drm_handle_t handle)
1154 map.handle = (void *)(uintptr_t)handle;
1156 if(drmIoctl(fd, DRM_IOCTL_RM_MAP, &map))
1162 * Make buffers available for DMA transfers.
1164 * \param fd file descriptor.
1165 * \param count number of buffers.
1166 * \param size size of each buffer.
1167 * \param flags buffer allocation flags.
1168 * \param agp_offset offset in the AGP aperture
1170 * \return number of buffers allocated, negative on error.
1173 * This function is a wrapper around DRM_IOCTL_ADD_BUFS ioctl.
1177 drm_public int drmAddBufs(int fd, int count, int size, drmBufDescFlags flags,
1180 drm_buf_desc_t request;
1183 request.count = count;
1184 request.size = size;
1185 request.flags = flags;
1186 request.agp_start = agp_offset;
1188 if (drmIoctl(fd, DRM_IOCTL_ADD_BUFS, &request))
1190 return request.count;
1193 drm_public int drmMarkBufs(int fd, double low, double high)
1195 drm_buf_info_t info;
1200 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1206 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1209 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1210 int retval = -errno;
1215 for (i = 0; i < info.count; i++) {
1216 info.list[i].low_mark = low * info.list[i].count;
1217 info.list[i].high_mark = high * info.list[i].count;
1218 if (drmIoctl(fd, DRM_IOCTL_MARK_BUFS, &info.list[i])) {
1219 int retval = -errno;
1232 * \param fd file descriptor.
1233 * \param count number of buffers to free.
1234 * \param list list of buffers to be freed.
1236 * \return zero on success, or a negative value on failure.
1238 * \note This function is primarily used for debugging.
1241 * This function is a wrapper around the DRM_IOCTL_FREE_BUFS ioctl, passing
1242 * the arguments in a drm_buf_free structure.
1244 drm_public int drmFreeBufs(int fd, int count, int *list)
1246 drm_buf_free_t request;
1249 request.count = count;
1250 request.list = list;
1251 if (drmIoctl(fd, DRM_IOCTL_FREE_BUFS, &request))
1260 * \param fd file descriptor.
1263 * This function closes the file descriptor.
1265 drm_public int drmClose(int fd)
1267 unsigned long key = drmGetKeyFromFd(fd);
1268 drmHashEntry *entry = drmGetEntry(fd);
1270 drmHashDestroy(entry->tagTable);
1273 entry->tagTable = NULL;
1275 drmHashDelete(drmHashTable, key);
1283 * Map a region of memory.
1285 * \param fd file descriptor.
1286 * \param handle handle returned by drmAddMap().
1287 * \param size size in bytes. Must match the size used by drmAddMap().
1288 * \param address will contain the user-space virtual address where the mapping
1291 * \return zero on success, or a negative value on failure.
1294 * This function is a wrapper for mmap().
1296 drm_public int drmMap(int fd, drm_handle_t handle, drmSize size,
1297 drmAddressPtr address)
1299 static unsigned long pagesize_mask = 0;
1305 pagesize_mask = getpagesize() - 1;
1307 size = (size + pagesize_mask) & ~pagesize_mask;
1309 *address = drm_mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1310 if (*address == MAP_FAILED)
1317 * Unmap mappings obtained with drmMap().
1319 * \param address address as given by drmMap().
1320 * \param size size in bytes. Must match the size used by drmMap().
1322 * \return zero on success, or a negative value on failure.
1325 * This function is a wrapper for munmap().
1327 drm_public int drmUnmap(drmAddress address, drmSize size)
1329 return drm_munmap(address, size);
1332 drm_public drmBufInfoPtr drmGetBufInfo(int fd)
1334 drm_buf_info_t info;
1335 drmBufInfoPtr retval;
1340 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1344 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1347 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1352 retval = drmMalloc(sizeof(*retval));
1353 retval->count = info.count;
1354 retval->list = drmMalloc(info.count * sizeof(*retval->list));
1355 for (i = 0; i < info.count; i++) {
1356 retval->list[i].count = info.list[i].count;
1357 retval->list[i].size = info.list[i].size;
1358 retval->list[i].low_mark = info.list[i].low_mark;
1359 retval->list[i].high_mark = info.list[i].high_mark;
1368 * Map all DMA buffers into client-virtual space.
1370 * \param fd file descriptor.
1372 * \return a pointer to a ::drmBufMap structure.
1374 * \note The client may not use these buffers until obtaining buffer indices
1378 * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1379 * information about the buffers in a drm_buf_map structure into the
1380 * client-visible data structures.
1382 drm_public drmBufMapPtr drmMapBufs(int fd)
1385 drmBufMapPtr retval;
1389 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1395 if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1398 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1403 retval = drmMalloc(sizeof(*retval));
1404 retval->count = bufs.count;
1405 retval->list = drmMalloc(bufs.count * sizeof(*retval->list));
1406 for (i = 0; i < bufs.count; i++) {
1407 retval->list[i].idx = bufs.list[i].idx;
1408 retval->list[i].total = bufs.list[i].total;
1409 retval->list[i].used = 0;
1410 retval->list[i].address = bufs.list[i].address;
1419 * Unmap buffers allocated with drmMapBufs().
1421 * \return zero on success, or negative value on failure.
1424 * Calls munmap() for every buffer stored in \p bufs and frees the
1425 * memory allocated by drmMapBufs().
1427 drm_public int drmUnmapBufs(drmBufMapPtr bufs)
1431 for (i = 0; i < bufs->count; i++) {
1432 drm_munmap(bufs->list[i].address, bufs->list[i].total);
1435 drmFree(bufs->list);
1441 #define DRM_DMA_RETRY 16
1444 * Reserve DMA buffers.
1446 * \param fd file descriptor.
1449 * \return zero on success, or a negative value on failure.
1452 * Assemble the arguments into a drm_dma structure and keeps issuing the
1453 * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1455 drm_public int drmDMA(int fd, drmDMAReqPtr request)
1460 dma.context = request->context;
1461 dma.send_count = request->send_count;
1462 dma.send_indices = request->send_list;
1463 dma.send_sizes = request->send_sizes;
1464 dma.flags = request->flags;
1465 dma.request_count = request->request_count;
1466 dma.request_size = request->request_size;
1467 dma.request_indices = request->request_list;
1468 dma.request_sizes = request->request_sizes;
1469 dma.granted_count = 0;
1472 ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1473 } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1476 request->granted_count = dma.granted_count;
1485 * Obtain heavyweight hardware lock.
1487 * \param fd file descriptor.
1488 * \param context context.
1489 * \param flags flags that determine the state of the hardware when the function
1492 * \return always zero.
1495 * This function translates the arguments into a drm_lock structure and issue
1496 * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1498 drm_public int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
1503 lock.context = context;
1505 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
1506 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
1507 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
1508 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
1509 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
1510 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
1512 while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
1518 * Release the hardware lock.
1520 * \param fd file descriptor.
1521 * \param context context.
1523 * \return zero on success, or a negative value on failure.
1526 * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
1527 * argument in a drm_lock structure.
1529 drm_public int drmUnlock(int fd, drm_context_t context)
1534 lock.context = context;
1535 return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
1538 drm_public drm_context_t *drmGetReservedContextList(int fd, int *count)
1542 drm_context_t * retval;
1546 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1552 if (!(list = drmMalloc(res.count * sizeof(*list))))
1554 if (!(retval = drmMalloc(res.count * sizeof(*retval))))
1557 res.contexts = list;
1558 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1559 goto err_free_context;
1561 for (i = 0; i < res.count; i++)
1562 retval[i] = list[i].handle;
1575 drm_public void drmFreeReservedContextList(drm_context_t *pt)
1583 * Used by the X server during GLXContext initialization. This causes
1584 * per-context kernel-level resources to be allocated.
1586 * \param fd file descriptor.
1587 * \param handle is set on success. To be used by the client when requesting DMA
1588 * dispatch with drmDMA().
1590 * \return zero on success, or a negative value on failure.
1592 * \note May only be called by root.
1595 * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
1596 * argument in a drm_ctx structure.
1598 drm_public int drmCreateContext(int fd, drm_context_t *handle)
1603 if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
1605 *handle = ctx.handle;
1609 drm_public int drmSwitchToContext(int fd, drm_context_t context)
1614 ctx.handle = context;
1615 if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
1620 drm_public int drmSetContextFlags(int fd, drm_context_t context,
1621 drm_context_tFlags flags)
1626 * Context preserving means that no context switches are done between DMA
1627 * buffers from one context and the next. This is suitable for use in the
1628 * X server (which promises to maintain hardware context), or in the
1629 * client-side library when buffers are swapped on behalf of two threads.
1632 ctx.handle = context;
1633 if (flags & DRM_CONTEXT_PRESERVED)
1634 ctx.flags |= _DRM_CONTEXT_PRESERVED;
1635 if (flags & DRM_CONTEXT_2DONLY)
1636 ctx.flags |= _DRM_CONTEXT_2DONLY;
1637 if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
1642 drm_public int drmGetContextFlags(int fd, drm_context_t context,
1643 drm_context_tFlagsPtr flags)
1648 ctx.handle = context;
1649 if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
1652 if (ctx.flags & _DRM_CONTEXT_PRESERVED)
1653 *flags |= DRM_CONTEXT_PRESERVED;
1654 if (ctx.flags & _DRM_CONTEXT_2DONLY)
1655 *flags |= DRM_CONTEXT_2DONLY;
1662 * Free any kernel-level resources allocated with drmCreateContext() associated
1665 * \param fd file descriptor.
1666 * \param handle handle given by drmCreateContext().
1668 * \return zero on success, or a negative value on failure.
1670 * \note May only be called by root.
1673 * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
1674 * argument in a drm_ctx structure.
1676 drm_public int drmDestroyContext(int fd, drm_context_t handle)
1681 ctx.handle = handle;
1682 if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
1687 drm_public int drmCreateDrawable(int fd, drm_drawable_t *handle)
1692 if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
1694 *handle = draw.handle;
1698 drm_public int drmDestroyDrawable(int fd, drm_drawable_t handle)
1703 draw.handle = handle;
1704 if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
1709 drm_public int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
1710 drm_drawable_info_type_t type,
1711 unsigned int num, void *data)
1713 drm_update_draw_t update;
1716 update.handle = handle;
1719 update.data = (unsigned long long)(unsigned long)data;
1721 if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
1727 drm_public int drmCrtcGetSequence(int fd, uint32_t crtcId, uint64_t *sequence,
1730 struct drm_crtc_get_sequence get_seq;
1734 get_seq.crtc_id = crtcId;
1735 ret = drmIoctl(fd, DRM_IOCTL_CRTC_GET_SEQUENCE, &get_seq);
1740 *sequence = get_seq.sequence;
1742 *ns = get_seq.sequence_ns;
1746 drm_public int drmCrtcQueueSequence(int fd, uint32_t crtcId, uint32_t flags,
1748 uint64_t *sequence_queued,
1751 struct drm_crtc_queue_sequence queue_seq;
1754 memclear(queue_seq);
1755 queue_seq.crtc_id = crtcId;
1756 queue_seq.flags = flags;
1757 queue_seq.sequence = sequence;
1758 queue_seq.user_data = user_data;
1760 ret = drmIoctl(fd, DRM_IOCTL_CRTC_QUEUE_SEQUENCE, &queue_seq);
1761 if (ret == 0 && sequence_queued)
1762 *sequence_queued = queue_seq.sequence;
1768 * Acquire the AGP device.
1770 * Must be called before any of the other AGP related calls.
1772 * \param fd file descriptor.
1774 * \return zero on success, or a negative value on failure.
1777 * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
1779 drm_public int drmAgpAcquire(int fd)
1781 if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
1788 * Release the AGP device.
1790 * \param fd file descriptor.
1792 * \return zero on success, or a negative value on failure.
1795 * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
1797 drm_public int drmAgpRelease(int fd)
1799 if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
1808 * \param fd file descriptor.
1809 * \param mode AGP mode.
1811 * \return zero on success, or a negative value on failure.
1814 * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
1815 * argument in a drm_agp_mode structure.
1817 drm_public int drmAgpEnable(int fd, unsigned long mode)
1823 if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
1830 * Allocate a chunk of AGP memory.
1832 * \param fd file descriptor.
1833 * \param size requested memory size in bytes. Will be rounded to page boundary.
1834 * \param type type of memory to allocate.
1835 * \param address if not zero, will be set to the physical address of the
1837 * \param handle on success will be set to a handle of the allocated memory.
1839 * \return zero on success, or a negative value on failure.
1842 * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
1843 * arguments in a drm_agp_buffer structure.
1845 drm_public int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
1846 unsigned long *address, drm_handle_t *handle)
1851 *handle = DRM_AGP_NO_HANDLE;
1854 if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
1857 *address = b.physical;
1864 * Free a chunk of AGP memory.
1866 * \param fd file descriptor.
1867 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1869 * \return zero on success, or a negative value on failure.
1872 * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
1873 * argument in a drm_agp_buffer structure.
1875 drm_public int drmAgpFree(int fd, drm_handle_t handle)
1881 if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
1888 * Bind a chunk of AGP memory.
1890 * \param fd file descriptor.
1891 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1892 * \param offset offset in bytes. It will round to page boundary.
1894 * \return zero on success, or a negative value on failure.
1897 * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
1898 * argument in a drm_agp_binding structure.
1900 drm_public int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
1902 drm_agp_binding_t b;
1907 if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
1914 * Unbind a chunk of AGP memory.
1916 * \param fd file descriptor.
1917 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1919 * \return zero on success, or a negative value on failure.
1922 * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
1923 * the argument in a drm_agp_binding structure.
1925 drm_public int drmAgpUnbind(int fd, drm_handle_t handle)
1927 drm_agp_binding_t b;
1931 if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
1938 * Get AGP driver major version number.
1940 * \param fd file descriptor.
1942 * \return major version number on success, or a negative value on failure..
1945 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1946 * necessary information in a drm_agp_info structure.
1948 drm_public int drmAgpVersionMajor(int fd)
1954 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1956 return i.agp_version_major;
1961 * Get AGP driver minor version number.
1963 * \param fd file descriptor.
1965 * \return minor version number on success, or a negative value on failure.
1968 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1969 * necessary information in a drm_agp_info structure.
1971 drm_public int drmAgpVersionMinor(int fd)
1977 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1979 return i.agp_version_minor;
1986 * \param fd file descriptor.
1988 * \return mode on success, or zero on failure.
1991 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1992 * necessary information in a drm_agp_info structure.
1994 drm_public unsigned long drmAgpGetMode(int fd)
2000 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2007 * Get AGP aperture base.
2009 * \param fd file descriptor.
2011 * \return aperture base on success, zero on failure.
2014 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2015 * necessary information in a drm_agp_info structure.
2017 drm_public unsigned long drmAgpBase(int fd)
2023 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2025 return i.aperture_base;
2030 * Get AGP aperture size.
2032 * \param fd file descriptor.
2034 * \return aperture size on success, zero on failure.
2037 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2038 * necessary information in a drm_agp_info structure.
2040 drm_public unsigned long drmAgpSize(int fd)
2046 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2048 return i.aperture_size;
2053 * Get used AGP memory.
2055 * \param fd file descriptor.
2057 * \return memory used on success, or zero on failure.
2060 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2061 * necessary information in a drm_agp_info structure.
2063 drm_public unsigned long drmAgpMemoryUsed(int fd)
2069 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2071 return i.memory_used;
2076 * Get available AGP memory.
2078 * \param fd file descriptor.
2080 * \return memory available on success, or zero on failure.
2083 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2084 * necessary information in a drm_agp_info structure.
2086 drm_public unsigned long drmAgpMemoryAvail(int fd)
2092 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2094 return i.memory_allowed;
2099 * Get hardware vendor ID.
2101 * \param fd file descriptor.
2103 * \return vendor ID on success, or zero on failure.
2106 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2107 * necessary information in a drm_agp_info structure.
2109 drm_public unsigned int drmAgpVendorId(int fd)
2115 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2122 * Get hardware device ID.
2124 * \param fd file descriptor.
2126 * \return zero on success, or zero on failure.
2129 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2130 * necessary information in a drm_agp_info structure.
2132 drm_public unsigned int drmAgpDeviceId(int fd)
2138 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2143 drm_public int drmScatterGatherAlloc(int fd, unsigned long size,
2144 drm_handle_t *handle)
2146 drm_scatter_gather_t sg;
2152 if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
2154 *handle = sg.handle;
2158 drm_public int drmScatterGatherFree(int fd, drm_handle_t handle)
2160 drm_scatter_gather_t sg;
2164 if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
2172 * \param fd file descriptor.
2173 * \param vbl pointer to a drmVBlank structure.
2175 * \return zero on success, or a negative value on failure.
2178 * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
2180 drm_public int drmWaitVBlank(int fd, drmVBlankPtr vbl)
2182 struct timespec timeout, cur;
2185 ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2187 fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
2193 ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
2194 vbl->request.type &= ~DRM_VBLANK_RELATIVE;
2195 if (ret && errno == EINTR) {
2196 clock_gettime(CLOCK_MONOTONIC, &cur);
2197 /* Timeout after 1s */
2198 if (cur.tv_sec > timeout.tv_sec + 1 ||
2199 (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
2206 } while (ret && errno == EINTR);
2212 drm_public int drmError(int err, const char *label)
2215 case DRM_ERR_NO_DEVICE:
2216 fprintf(stderr, "%s: no device\n", label);
2218 case DRM_ERR_NO_ACCESS:
2219 fprintf(stderr, "%s: no access\n", label);
2221 case DRM_ERR_NOT_ROOT:
2222 fprintf(stderr, "%s: not root\n", label);
2224 case DRM_ERR_INVALID:
2225 fprintf(stderr, "%s: invalid args\n", label);
2230 fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2238 * Install IRQ handler.
2240 * \param fd file descriptor.
2241 * \param irq IRQ number.
2243 * \return zero on success, or a negative value on failure.
2246 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2247 * argument in a drm_control structure.
2249 drm_public int drmCtlInstHandler(int fd, int irq)
2254 ctl.func = DRM_INST_HANDLER;
2256 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2263 * Uninstall IRQ handler.
2265 * \param fd file descriptor.
2267 * \return zero on success, or a negative value on failure.
2270 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2271 * argument in a drm_control structure.
2273 drm_public int drmCtlUninstHandler(int fd)
2278 ctl.func = DRM_UNINST_HANDLER;
2280 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2285 drm_public int drmFinish(int fd, int context, drmLockFlags flags)
2290 lock.context = context;
2291 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
2292 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
2293 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
2294 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
2295 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2296 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2297 if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2303 * Get IRQ from bus ID.
2305 * \param fd file descriptor.
2306 * \param busnum bus number.
2307 * \param devnum device number.
2308 * \param funcnum function number.
2310 * \return IRQ number on success, or a negative value on failure.
2313 * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2314 * arguments in a drm_irq_busid structure.
2316 drm_public int drmGetInterruptFromBusID(int fd, int busnum, int devnum,
2324 p.funcnum = funcnum;
2325 if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2330 drm_public int drmAddContextTag(int fd, drm_context_t context, void *tag)
2332 drmHashEntry *entry = drmGetEntry(fd);
2334 if (drmHashInsert(entry->tagTable, context, tag)) {
2335 drmHashDelete(entry->tagTable, context);
2336 drmHashInsert(entry->tagTable, context, tag);
2341 drm_public int drmDelContextTag(int fd, drm_context_t context)
2343 drmHashEntry *entry = drmGetEntry(fd);
2345 return drmHashDelete(entry->tagTable, context);
2348 drm_public void *drmGetContextTag(int fd, drm_context_t context)
2350 drmHashEntry *entry = drmGetEntry(fd);
2353 if (drmHashLookup(entry->tagTable, context, &value))
2359 drm_public int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2360 drm_handle_t handle)
2362 drm_ctx_priv_map_t map;
2365 map.ctx_id = ctx_id;
2366 map.handle = (void *)(uintptr_t)handle;
2368 if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2373 drm_public int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2374 drm_handle_t *handle)
2376 drm_ctx_priv_map_t map;
2379 map.ctx_id = ctx_id;
2381 if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2384 *handle = (drm_handle_t)(uintptr_t)map.handle;
2389 drm_public int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2390 drmMapType *type, drmMapFlags *flags,
2391 drm_handle_t *handle, int *mtrr)
2397 if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2399 *offset = map.offset;
2403 *handle = (unsigned long)map.handle;
2408 drm_public int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2409 unsigned long *magic, unsigned long *iocs)
2411 drm_client_t client;
2415 if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2417 *auth = client.auth;
2420 *magic = client.magic;
2421 *iocs = client.iocs;
2425 drm_public int drmGetStats(int fd, drmStatsT *stats)
2431 if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2435 memset(stats, 0, sizeof(*stats));
2436 if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2440 stats->data[i].long_format = "%-20.20s"; \
2441 stats->data[i].rate_format = "%8.8s"; \
2442 stats->data[i].isvalue = 1; \
2443 stats->data[i].verbose = 0
2446 stats->data[i].long_format = "%-20.20s"; \
2447 stats->data[i].rate_format = "%5.5s"; \
2448 stats->data[i].isvalue = 0; \
2449 stats->data[i].mult_names = "kgm"; \
2450 stats->data[i].mult = 1000; \
2451 stats->data[i].verbose = 0
2454 stats->data[i].long_format = "%-20.20s"; \
2455 stats->data[i].rate_format = "%5.5s"; \
2456 stats->data[i].isvalue = 0; \
2457 stats->data[i].mult_names = "KGM"; \
2458 stats->data[i].mult = 1024; \
2459 stats->data[i].verbose = 0
2462 stats->count = s.count;
2463 for (i = 0; i < s.count; i++) {
2464 stats->data[i].value = s.data[i].value;
2465 switch (s.data[i].type) {
2466 case _DRM_STAT_LOCK:
2467 stats->data[i].long_name = "Lock";
2468 stats->data[i].rate_name = "Lock";
2471 case _DRM_STAT_OPENS:
2472 stats->data[i].long_name = "Opens";
2473 stats->data[i].rate_name = "O";
2475 stats->data[i].verbose = 1;
2477 case _DRM_STAT_CLOSES:
2478 stats->data[i].long_name = "Closes";
2479 stats->data[i].rate_name = "Lock";
2481 stats->data[i].verbose = 1;
2483 case _DRM_STAT_IOCTLS:
2484 stats->data[i].long_name = "Ioctls";
2485 stats->data[i].rate_name = "Ioc/s";
2488 case _DRM_STAT_LOCKS:
2489 stats->data[i].long_name = "Locks";
2490 stats->data[i].rate_name = "Lck/s";
2493 case _DRM_STAT_UNLOCKS:
2494 stats->data[i].long_name = "Unlocks";
2495 stats->data[i].rate_name = "Unl/s";
2499 stats->data[i].long_name = "IRQs";
2500 stats->data[i].rate_name = "IRQ/s";
2503 case _DRM_STAT_PRIMARY:
2504 stats->data[i].long_name = "Primary Bytes";
2505 stats->data[i].rate_name = "PB/s";
2508 case _DRM_STAT_SECONDARY:
2509 stats->data[i].long_name = "Secondary Bytes";
2510 stats->data[i].rate_name = "SB/s";
2514 stats->data[i].long_name = "DMA";
2515 stats->data[i].rate_name = "DMA/s";
2518 case _DRM_STAT_SPECIAL:
2519 stats->data[i].long_name = "Special DMA";
2520 stats->data[i].rate_name = "dma/s";
2523 case _DRM_STAT_MISSED:
2524 stats->data[i].long_name = "Miss";
2525 stats->data[i].rate_name = "Ms/s";
2528 case _DRM_STAT_VALUE:
2529 stats->data[i].long_name = "Value";
2530 stats->data[i].rate_name = "Value";
2533 case _DRM_STAT_BYTE:
2534 stats->data[i].long_name = "Bytes";
2535 stats->data[i].rate_name = "B/s";
2538 case _DRM_STAT_COUNT:
2540 stats->data[i].long_name = "Count";
2541 stats->data[i].rate_name = "Cnt/s";
2550 * Issue a set-version ioctl.
2552 * \param fd file descriptor.
2553 * \param drmCommandIndex command index
2554 * \param data source pointer of the data to be read and written.
2555 * \param size size of the data to be read and written.
2557 * \return zero on success, or a negative value on failure.
2560 * It issues a read-write ioctl given by
2561 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2563 drm_public int drmSetInterfaceVersion(int fd, drmSetVersion *version)
2566 drm_set_version_t sv;
2569 sv.drm_di_major = version->drm_di_major;
2570 sv.drm_di_minor = version->drm_di_minor;
2571 sv.drm_dd_major = version->drm_dd_major;
2572 sv.drm_dd_minor = version->drm_dd_minor;
2574 if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
2578 version->drm_di_major = sv.drm_di_major;
2579 version->drm_di_minor = sv.drm_di_minor;
2580 version->drm_dd_major = sv.drm_dd_major;
2581 version->drm_dd_minor = sv.drm_dd_minor;
2587 * Send a device-specific command.
2589 * \param fd file descriptor.
2590 * \param drmCommandIndex command index
2592 * \return zero on success, or a negative value on failure.
2595 * It issues a ioctl given by
2596 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2598 drm_public int drmCommandNone(int fd, unsigned long drmCommandIndex)
2600 unsigned long request;
2602 request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
2604 if (drmIoctl(fd, request, NULL)) {
2612 * Send a device-specific read command.
2614 * \param fd file descriptor.
2615 * \param drmCommandIndex command index
2616 * \param data destination pointer of the data to be read.
2617 * \param size size of the data to be read.
2619 * \return zero on success, or a negative value on failure.
2622 * It issues a read ioctl given by
2623 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2625 drm_public int drmCommandRead(int fd, unsigned long drmCommandIndex,
2626 void *data, unsigned long size)
2628 unsigned long request;
2630 request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
2631 DRM_COMMAND_BASE + drmCommandIndex, size);
2633 if (drmIoctl(fd, request, data)) {
2641 * Send a device-specific write command.
2643 * \param fd file descriptor.
2644 * \param drmCommandIndex command index
2645 * \param data source pointer of the data to be written.
2646 * \param size size of the data to be written.
2648 * \return zero on success, or a negative value on failure.
2651 * It issues a write ioctl given by
2652 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2654 drm_public int drmCommandWrite(int fd, unsigned long drmCommandIndex,
2655 void *data, unsigned long size)
2657 unsigned long request;
2659 request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
2660 DRM_COMMAND_BASE + drmCommandIndex, size);
2662 if (drmIoctl(fd, request, data)) {
2670 * Send a device-specific read-write command.
2672 * \param fd file descriptor.
2673 * \param drmCommandIndex command index
2674 * \param data source pointer of the data to be read and written.
2675 * \param size size of the data to be read and written.
2677 * \return zero on success, or a negative value on failure.
2680 * It issues a read-write ioctl given by
2681 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2683 drm_public int drmCommandWriteRead(int fd, unsigned long drmCommandIndex,
2684 void *data, unsigned long size)
2686 unsigned long request;
2688 request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
2689 DRM_COMMAND_BASE + drmCommandIndex, size);
2691 if (drmIoctl(fd, request, data))
2696 #define DRM_MAX_FDS 16
2702 } connection[DRM_MAX_FDS];
2704 static int nr_fds = 0;
2706 drm_public int drmOpenOnce(void *unused, const char *BusID, int *newlyopened)
2708 return drmOpenOnceWithType(BusID, newlyopened, DRM_NODE_PRIMARY);
2711 drm_public int drmOpenOnceWithType(const char *BusID, int *newlyopened,
2717 for (i = 0; i < nr_fds; i++)
2718 if ((strcmp(BusID, connection[i].BusID) == 0) &&
2719 (connection[i].type == type)) {
2720 connection[i].refcount++;
2722 return connection[i].fd;
2725 fd = drmOpenWithType(NULL, BusID, type);
2726 if (fd < 0 || nr_fds == DRM_MAX_FDS)
2729 connection[nr_fds].BusID = strdup(BusID);
2730 connection[nr_fds].fd = fd;
2731 connection[nr_fds].refcount = 1;
2732 connection[nr_fds].type = type;
2736 fprintf(stderr, "saved connection %d for %s %d\n",
2737 nr_fds, connection[nr_fds].BusID,
2738 strcmp(BusID, connection[nr_fds].BusID));
2745 drm_public void drmCloseOnce(int fd)
2749 for (i = 0; i < nr_fds; i++) {
2750 if (fd == connection[i].fd) {
2751 if (--connection[i].refcount == 0) {
2752 drmClose(connection[i].fd);
2753 free(connection[i].BusID);
2756 connection[i] = connection[nr_fds];
2764 drm_public int drmSetMaster(int fd)
2766 return drmIoctl(fd, DRM_IOCTL_SET_MASTER, NULL);
2769 drm_public int drmDropMaster(int fd)
2771 return drmIoctl(fd, DRM_IOCTL_DROP_MASTER, NULL);
2774 drm_public int drmIsMaster(int fd)
2776 /* Detect master by attempting something that requires master.
2778 * Authenticating magic tokens requires master and 0 is an
2779 * internal kernel detail which we could use. Attempting this on
2780 * a master fd would fail therefore fail with EINVAL because 0
2783 * A non-master fd will fail with EACCES, as the kernel checks
2784 * for master before attempting to do anything else.
2786 * Since we don't want to leak implementation details, use
2789 return drmAuthMagic(fd, 0) != -EACCES;
2792 drm_public char *drmGetDeviceNameFromFd(int fd)
2799 if (fstat(fd, &sbuf))
2802 maj = major(sbuf.st_rdev);
2803 min = minor(sbuf.st_rdev);
2804 nodetype = drmGetMinorType(maj, min);
2805 return drmGetMinorNameForFD(fd, nodetype);
2812 /* The whole drmOpen thing is a fiasco and we need to find a way
2813 * back to just using open(2). For now, however, lets just make
2814 * things worse with even more ad hoc directory walking code to
2815 * discover the device file name. */
2820 for (i = 0; i < DRM_MAX_MINOR; i++) {
2821 snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
2822 if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
2825 if (i == DRM_MAX_MINOR)
2828 return strdup(name);
2832 static bool drmNodeIsDRM(int maj, int min)
2838 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device/drm",
2840 return stat(path, &sbuf) == 0;
2841 #elif defined(__FreeBSD__)
2842 char name[SPECNAMELEN];
2844 if (!devname_r(makedev(maj, min), S_IFCHR, name, sizeof(name)))
2846 /* Handle drm/ and dri/ as both are present in different FreeBSD version
2847 * FreeBSD on amd64/i386/powerpc external kernel modules create node in
2848 * in /dev/drm/ and links in /dev/dri while a WIP in kernel driver creates
2849 * only device nodes in /dev/dri/ */
2850 return (!strncmp(name, "drm/", 4) || !strncmp(name, "dri/", 4));
2852 return maj == DRM_MAJOR;
2856 drm_public int drmGetNodeTypeFromFd(int fd)
2861 if (fstat(fd, &sbuf))
2864 maj = major(sbuf.st_rdev);
2865 min = minor(sbuf.st_rdev);
2867 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode)) {
2872 type = drmGetMinorType(maj, min);
2878 drm_public int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags,
2881 struct drm_prime_handle args;
2886 args.handle = handle;
2888 ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
2892 *prime_fd = args.fd;
2896 drm_public int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
2898 struct drm_prime_handle args;
2903 ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
2907 *handle = args.handle;
2911 static char *drmGetMinorNameForFD(int fd, int type)
2917 const char *name = drmGetMinorName(type);
2919 char dev_name[64], buf[64];
2927 if (fstat(fd, &sbuf))
2930 maj = major(sbuf.st_rdev);
2931 min = minor(sbuf.st_rdev);
2933 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
2936 snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
2938 sysdir = opendir(buf);
2942 while ((ent = readdir(sysdir))) {
2943 if (strncmp(ent->d_name, name, len) == 0) {
2944 snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
2948 return strdup(dev_name);
2954 #elif defined(__FreeBSD__)
2956 char dname[SPECNAMELEN];
2958 char name[SPECNAMELEN];
2959 int id, maj, min, nodetype, i;
2961 if (fstat(fd, &sbuf))
2964 maj = major(sbuf.st_rdev);
2965 min = minor(sbuf.st_rdev);
2967 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
2970 if (!devname_r(sbuf.st_rdev, S_IFCHR, dname, sizeof(dname)))
2973 /* Handle both /dev/drm and /dev/dri
2974 * FreeBSD on amd64/i386/powerpc external kernel modules create node in
2975 * in /dev/drm/ and links in /dev/dri while a WIP in kernel driver creates
2976 * only device nodes in /dev/dri/ */
2978 /* Get the node type represented by fd so we can deduce the target name */
2979 nodetype = drmGetMinorType(maj, min);
2982 mname = drmGetMinorName(type);
2984 for (i = 0; i < SPECNAMELEN; i++) {
2985 if (isalpha(dname[i]) == 0 && dname[i] != '/')
2988 if (dname[i] == '\0')
2991 id = (int)strtol(&dname[i], NULL, 10);
2992 id -= drmGetMinorBase(nodetype);
2993 snprintf(name, sizeof(name), DRM_DIR_NAME "/%s%d", mname,
2994 id + drmGetMinorBase(type));
2996 return strdup(name);
2999 char buf[PATH_MAX + 1];
3000 const char *dev_name = drmGetDeviceName(type);
3001 unsigned int maj, min;
3004 if (fstat(fd, &sbuf))
3007 maj = major(sbuf.st_rdev);
3008 min = minor(sbuf.st_rdev);
3010 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3016 n = snprintf(buf, sizeof(buf), dev_name, DRM_DIR_NAME, min);
3017 if (n == -1 || n >= sizeof(buf))
3024 drm_public char *drmGetPrimaryDeviceNameFromFd(int fd)
3026 return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
3029 drm_public char *drmGetRenderDeviceNameFromFd(int fd)
3031 return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
3035 static char * DRM_PRINTFLIKE(2, 3)
3036 sysfs_uevent_get(const char *path, const char *fmt, ...)
3038 char filename[PATH_MAX + 1], *key, *line = NULL, *value = NULL;
3039 size_t size = 0, len;
3045 num = vasprintf(&key, fmt, ap);
3049 snprintf(filename, sizeof(filename), "%s/uevent", path);
3051 fp = fopen(filename, "r");
3057 while ((num = getline(&line, &size, fp)) >= 0) {
3058 if ((strncmp(line, key, len) == 0) && (line[len] == '=')) {
3059 char *start = line + len + 1, *end = line + num - 1;
3064 value = strndup(start, end - start);
3078 /* Little white lie to avoid major rework of the existing code */
3079 #define DRM_BUS_VIRTIO 0x10
3082 static int get_subsystem_type(const char *device_path)
3084 char path[PATH_MAX + 1] = "";
3085 char link[PATH_MAX + 1] = "";
3091 { "/pci", DRM_BUS_PCI },
3092 { "/usb", DRM_BUS_USB },
3093 { "/platform", DRM_BUS_PLATFORM },
3094 { "/spi", DRM_BUS_PLATFORM },
3095 { "/host1x", DRM_BUS_HOST1X },
3096 { "/virtio", DRM_BUS_VIRTIO },
3099 strncpy(path, device_path, PATH_MAX);
3100 strncat(path, "/subsystem", PATH_MAX);
3102 if (readlink(path, link, PATH_MAX) < 0)
3105 name = strrchr(link, '/');
3109 for (unsigned i = 0; i < ARRAY_SIZE(bus_types); i++) {
3110 if (strncmp(name, bus_types[i].name, strlen(bus_types[i].name)) == 0)
3111 return bus_types[i].bus_type;
3118 static int drmParseSubsystemType(int maj, int min)
3121 char path[PATH_MAX + 1] = "";
3122 char real_path[PATH_MAX + 1] = "";
3125 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3127 subsystem_type = get_subsystem_type(path);
3128 /* Try to get the parent (underlying) device type */
3129 if (subsystem_type == DRM_BUS_VIRTIO) {
3130 /* Assume virtio-pci on error */
3131 if (!realpath(path, real_path))
3132 return DRM_BUS_VIRTIO;
3133 strncat(path, "/..", PATH_MAX);
3134 subsystem_type = get_subsystem_type(path);
3135 if (subsystem_type < 0)
3136 return DRM_BUS_VIRTIO;
3138 return subsystem_type;
3139 #elif defined(__OpenBSD__) || defined(__DragonFly__) || defined(__FreeBSD__)
3142 #warning "Missing implementation of drmParseSubsystemType"
3149 get_pci_path(int maj, int min, char *pci_path)
3151 char path[PATH_MAX + 1], *term;
3153 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3154 if (!realpath(path, pci_path)) {
3155 strcpy(pci_path, path);
3159 term = strrchr(pci_path, '/');
3160 if (term && strncmp(term, "/virtio", 7) == 0)
3166 static int get_sysctl_pci_bus_info(int maj, int min, drmPciBusInfoPtr info)
3168 char dname[SPECNAMELEN];
3169 char sysctl_name[16];
3170 char sysctl_val[256];
3172 int id, type, nelem;
3173 unsigned int rdev, majmin, domain, bus, dev, func;
3175 rdev = makedev(maj, min);
3176 if (!devname_r(rdev, S_IFCHR, dname, sizeof(dname)))
3179 if (sscanf(dname, "drm/%d\n", &id) != 1)
3181 type = drmGetMinorType(maj, min);
3185 /* BUG: This above section is iffy, since it mandates that a driver will
3186 * create both card and render node.
3187 * If it does not, the next DRM device will create card#X and
3188 * renderD#(128+X)-1.
3189 * This is a possibility in FreeBSD but for now there is no good way for
3190 * obtaining the info.
3193 case DRM_NODE_PRIMARY:
3195 case DRM_NODE_CONTROL:
3198 case DRM_NODE_RENDER:
3205 if (snprintf(sysctl_name, sizeof(sysctl_name), "hw.dri.%d.busid", id) <= 0)
3207 sysctl_len = sizeof(sysctl_val);
3208 if (sysctlbyname(sysctl_name, sysctl_val, &sysctl_len, NULL, 0))
3211 #define bus_fmt "pci:%04x:%02x:%02x.%u"
3213 nelem = sscanf(sysctl_val, bus_fmt, &domain, &bus, &dev, &func);
3216 info->domain = domain;
3225 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
3228 unsigned int domain, bus, dev, func;
3229 char pci_path[PATH_MAX + 1], *value;
3232 get_pci_path(maj, min, pci_path);
3234 value = sysfs_uevent_get(pci_path, "PCI_SLOT_NAME");
3238 num = sscanf(value, "%04x:%02x:%02x.%1u", &domain, &bus, &dev, &func);
3244 info->domain = domain;
3250 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3251 struct drm_pciinfo pinfo;
3254 type = drmGetMinorType(maj, min);
3258 fd = drmOpenMinor(min, 0, type);
3262 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3268 info->domain = pinfo.domain;
3269 info->bus = pinfo.bus;
3270 info->dev = pinfo.dev;
3271 info->func = pinfo.func;
3274 #elif defined(__FreeBSD__)
3275 return get_sysctl_pci_bus_info(maj, min, info);
3277 #warning "Missing implementation of drmParsePciBusInfo"
3282 drm_public int drmDevicesEqual(drmDevicePtr a, drmDevicePtr b)
3284 if (a == NULL || b == NULL)
3287 if (a->bustype != b->bustype)
3290 switch (a->bustype) {
3292 return memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo)) == 0;
3295 return memcmp(a->businfo.usb, b->businfo.usb, sizeof(drmUsbBusInfo)) == 0;
3297 case DRM_BUS_PLATFORM:
3298 return memcmp(a->businfo.platform, b->businfo.platform, sizeof(drmPlatformBusInfo)) == 0;
3300 case DRM_BUS_HOST1X:
3301 return memcmp(a->businfo.host1x, b->businfo.host1x, sizeof(drmHost1xBusInfo)) == 0;
3310 static int drmGetNodeType(const char *name)
3312 if (strncmp(name, DRM_CONTROL_MINOR_NAME,
3313 sizeof(DRM_CONTROL_MINOR_NAME ) - 1) == 0)
3314 return DRM_NODE_CONTROL;
3316 if (strncmp(name, DRM_RENDER_MINOR_NAME,
3317 sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
3318 return DRM_NODE_RENDER;
3320 if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
3321 sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
3322 return DRM_NODE_PRIMARY;
3327 static int drmGetMaxNodeName(void)
3329 return sizeof(DRM_DIR_NAME) +
3330 MAX3(sizeof(DRM_PRIMARY_MINOR_NAME),
3331 sizeof(DRM_CONTROL_MINOR_NAME),
3332 sizeof(DRM_RENDER_MINOR_NAME)) +
3333 3 /* length of the node number */;
3337 static int parse_separate_sysfs_files(int maj, int min,
3338 drmPciDeviceInfoPtr device,
3339 bool ignore_revision)
3341 static const char *attrs[] = {
3342 "revision", /* Older kernels are missing the file, so check for it first */
3348 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3349 unsigned int data[ARRAY_SIZE(attrs)];
3353 get_pci_path(maj, min, pci_path);
3355 for (unsigned i = ignore_revision ? 1 : 0; i < ARRAY_SIZE(attrs); i++) {
3356 snprintf(path, PATH_MAX, "%s/%s", pci_path, attrs[i]);
3357 fp = fopen(path, "r");
3361 ret = fscanf(fp, "%x", &data[i]);
3368 device->revision_id = ignore_revision ? 0xff : data[0] & 0xff;
3369 device->vendor_id = data[1] & 0xffff;
3370 device->device_id = data[2] & 0xffff;
3371 device->subvendor_id = data[3] & 0xffff;
3372 device->subdevice_id = data[4] & 0xffff;
3377 static int parse_config_sysfs_file(int maj, int min,
3378 drmPciDeviceInfoPtr device)
3380 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3381 unsigned char config[64];
3384 get_pci_path(maj, min, pci_path);
3386 snprintf(path, PATH_MAX, "%s/config", pci_path);
3387 fd = open(path, O_RDONLY);
3391 ret = read(fd, config, sizeof(config));
3396 device->vendor_id = config[0] | (config[1] << 8);
3397 device->device_id = config[2] | (config[3] << 8);
3398 device->revision_id = config[8];
3399 device->subvendor_id = config[44] | (config[45] << 8);
3400 device->subdevice_id = config[46] | (config[47] << 8);
3406 static int drmParsePciDeviceInfo(int maj, int min,
3407 drmPciDeviceInfoPtr device,
3411 if (!(flags & DRM_DEVICE_GET_PCI_REVISION))
3412 return parse_separate_sysfs_files(maj, min, device, true);
3414 if (parse_separate_sysfs_files(maj, min, device, false))
3415 return parse_config_sysfs_file(maj, min, device);
3418 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3419 struct drm_pciinfo pinfo;
3422 type = drmGetMinorType(maj, min);
3426 fd = drmOpenMinor(min, 0, type);
3430 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3436 device->vendor_id = pinfo.vendor_id;
3437 device->device_id = pinfo.device_id;
3438 device->revision_id = pinfo.revision_id;
3439 device->subvendor_id = pinfo.subvendor_id;
3440 device->subdevice_id = pinfo.subdevice_id;
3443 #elif defined(__FreeBSD__)
3445 struct pci_conf_io pc;
3446 struct pci_match_conf patterns[1];
3447 struct pci_conf results[1];
3450 if (get_sysctl_pci_bus_info(maj, min, &info) != 0)
3453 fd = open("/dev/pci", O_RDONLY, 0);
3457 bzero(&patterns, sizeof(patterns));
3458 patterns[0].pc_sel.pc_domain = info.domain;
3459 patterns[0].pc_sel.pc_bus = info.bus;
3460 patterns[0].pc_sel.pc_dev = info.dev;
3461 patterns[0].pc_sel.pc_func = info.func;
3462 patterns[0].flags = PCI_GETCONF_MATCH_DOMAIN | PCI_GETCONF_MATCH_BUS
3463 | PCI_GETCONF_MATCH_DEV | PCI_GETCONF_MATCH_FUNC;
3464 bzero(&pc, sizeof(struct pci_conf_io));
3465 pc.num_patterns = 1;
3466 pc.pat_buf_len = sizeof(patterns);
3467 pc.patterns = patterns;
3468 pc.match_buf_len = sizeof(results);
3469 pc.matches = results;
3471 if (ioctl(fd, PCIOCGETCONF, &pc) || pc.status == PCI_GETCONF_ERROR) {
3478 device->vendor_id = results[0].pc_vendor;
3479 device->device_id = results[0].pc_device;
3480 device->subvendor_id = results[0].pc_subvendor;
3481 device->subdevice_id = results[0].pc_subdevice;
3482 device->revision_id = results[0].pc_revid;
3486 #warning "Missing implementation of drmParsePciDeviceInfo"
3491 static void drmFreePlatformDevice(drmDevicePtr device)
3493 if (device->deviceinfo.platform) {
3494 if (device->deviceinfo.platform->compatible) {
3495 char **compatible = device->deviceinfo.platform->compatible;
3497 while (*compatible) {
3502 free(device->deviceinfo.platform->compatible);
3507 static void drmFreeHost1xDevice(drmDevicePtr device)
3509 if (device->deviceinfo.host1x) {
3510 if (device->deviceinfo.host1x->compatible) {
3511 char **compatible = device->deviceinfo.host1x->compatible;
3513 while (*compatible) {
3518 free(device->deviceinfo.host1x->compatible);
3523 drm_public void drmFreeDevice(drmDevicePtr *device)
3529 switch ((*device)->bustype) {
3530 case DRM_BUS_PLATFORM:
3531 drmFreePlatformDevice(*device);
3534 case DRM_BUS_HOST1X:
3535 drmFreeHost1xDevice(*device);
3544 drm_public void drmFreeDevices(drmDevicePtr devices[], int count)
3548 if (devices == NULL)
3551 for (i = 0; i < count; i++)
3553 drmFreeDevice(&devices[i]);
3556 static drmDevicePtr drmDeviceAlloc(unsigned int type, const char *node,
3557 size_t bus_size, size_t device_size,
3560 size_t max_node_length, extra, size;
3561 drmDevicePtr device;
3565 max_node_length = ALIGN(drmGetMaxNodeName(), sizeof(void *));
3566 extra = DRM_NODE_MAX * (sizeof(void *) + max_node_length);
3568 size = sizeof(*device) + extra + bus_size + device_size;
3570 device = calloc(1, size);
3574 device->available_nodes = 1 << type;
3576 ptr = (char *)device + sizeof(*device);
3577 device->nodes = (char **)ptr;
3579 ptr += DRM_NODE_MAX * sizeof(void *);
3581 for (i = 0; i < DRM_NODE_MAX; i++) {
3582 device->nodes[i] = ptr;
3583 ptr += max_node_length;
3586 memcpy(device->nodes[type], node, max_node_length);
3593 static int drmProcessPciDevice(drmDevicePtr *device,
3594 const char *node, int node_type,
3595 int maj, int min, bool fetch_deviceinfo,
3602 dev = drmDeviceAlloc(node_type, node, sizeof(drmPciBusInfo),
3603 sizeof(drmPciDeviceInfo), &addr);
3607 dev->bustype = DRM_BUS_PCI;
3609 dev->businfo.pci = (drmPciBusInfoPtr)addr;
3611 ret = drmParsePciBusInfo(maj, min, dev->businfo.pci);
3615 // Fetch the device info if the user has requested it
3616 if (fetch_deviceinfo) {
3617 addr += sizeof(drmPciBusInfo);
3618 dev->deviceinfo.pci = (drmPciDeviceInfoPtr)addr;
3620 ret = drmParsePciDeviceInfo(maj, min, dev->deviceinfo.pci, flags);
3635 static int drm_usb_dev_path(int maj, int min, char *path, size_t len)
3637 char *value, *tmp_path, *slash;
3639 snprintf(path, len, "/sys/dev/char/%d:%d/device", maj, min);
3641 value = sysfs_uevent_get(path, "DEVTYPE");
3645 if (strcmp(value, "usb_device") == 0)
3647 if (strcmp(value, "usb_interface") != 0)
3650 /* The parent of a usb_interface is a usb_device */
3652 tmp_path = realpath(path, NULL);
3656 slash = strrchr(tmp_path, '/');
3664 if (snprintf(path, len, "%s", tmp_path) >= (int)len) {
3674 static int drmParseUsbBusInfo(int maj, int min, drmUsbBusInfoPtr info)
3677 char path[PATH_MAX + 1], *value;
3678 unsigned int bus, dev;
3681 ret = drm_usb_dev_path(maj, min, path, sizeof(path));
3685 value = sysfs_uevent_get(path, "BUSNUM");
3689 ret = sscanf(value, "%03u", &bus);
3695 value = sysfs_uevent_get(path, "DEVNUM");
3699 ret = sscanf(value, "%03u", &dev);
3710 #warning "Missing implementation of drmParseUsbBusInfo"
3715 static int drmParseUsbDeviceInfo(int maj, int min, drmUsbDeviceInfoPtr info)
3718 char path[PATH_MAX + 1], *value;
3719 unsigned int vendor, product;
3722 ret = drm_usb_dev_path(maj, min, path, sizeof(path));
3726 value = sysfs_uevent_get(path, "PRODUCT");
3730 ret = sscanf(value, "%x/%x", &vendor, &product);
3736 info->vendor = vendor;
3737 info->product = product;
3741 #warning "Missing implementation of drmParseUsbDeviceInfo"
3746 static int drmProcessUsbDevice(drmDevicePtr *device, const char *node,
3747 int node_type, int maj, int min,
3748 bool fetch_deviceinfo, uint32_t flags)
3754 dev = drmDeviceAlloc(node_type, node, sizeof(drmUsbBusInfo),
3755 sizeof(drmUsbDeviceInfo), &ptr);
3759 dev->bustype = DRM_BUS_USB;
3761 dev->businfo.usb = (drmUsbBusInfoPtr)ptr;
3763 ret = drmParseUsbBusInfo(maj, min, dev->businfo.usb);
3767 if (fetch_deviceinfo) {
3768 ptr += sizeof(drmUsbBusInfo);
3769 dev->deviceinfo.usb = (drmUsbDeviceInfoPtr)ptr;
3771 ret = drmParseUsbDeviceInfo(maj, min, dev->deviceinfo.usb);
3785 static int drmParseOFBusInfo(int maj, int min, char *fullname)
3788 char path[PATH_MAX + 1], *name, *tmp_name;
3790 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3792 name = sysfs_uevent_get(path, "OF_FULLNAME");
3795 /* If the device lacks OF data, pick the MODALIAS info */
3796 name = sysfs_uevent_get(path, "MODALIAS");
3800 /* .. and strip the MODALIAS=[platform,usb...]: part. */
3801 tmp_name = strrchr(name, ':');
3809 strncpy(fullname, tmp_name, DRM_PLATFORM_DEVICE_NAME_LEN);
3810 fullname[DRM_PLATFORM_DEVICE_NAME_LEN - 1] = '\0';
3815 #warning "Missing implementation of drmParseOFBusInfo"
3820 static int drmParseOFDeviceInfo(int maj, int min, char ***compatible)
3823 char path[PATH_MAX + 1], *value, *tmp_name;
3824 unsigned int count, i;
3827 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3829 value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
3831 sscanf(value, "%u", &count);
3834 /* Assume one entry if the device lack OF data */
3838 *compatible = calloc(count + 1, sizeof(char *));
3842 for (i = 0; i < count; i++) {
3843 value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
3846 /* If the device lacks OF data, pick the MODALIAS info */
3847 value = sysfs_uevent_get(path, "MODALIAS");
3853 /* .. and strip the MODALIAS=[platform,usb...]: part. */
3854 tmp_name = strrchr(value, ':');
3859 tmp_name = strdup(tmp_name + 1);
3863 (*compatible)[i] = tmp_name;
3870 free((*compatible)[i]);
3875 #warning "Missing implementation of drmParseOFDeviceInfo"
3880 static int drmProcessPlatformDevice(drmDevicePtr *device,
3881 const char *node, int node_type,
3882 int maj, int min, bool fetch_deviceinfo,
3889 dev = drmDeviceAlloc(node_type, node, sizeof(drmPlatformBusInfo),
3890 sizeof(drmPlatformDeviceInfo), &ptr);
3894 dev->bustype = DRM_BUS_PLATFORM;
3896 dev->businfo.platform = (drmPlatformBusInfoPtr)ptr;
3898 ret = drmParseOFBusInfo(maj, min, dev->businfo.platform->fullname);
3902 if (fetch_deviceinfo) {
3903 ptr += sizeof(drmPlatformBusInfo);
3904 dev->deviceinfo.platform = (drmPlatformDeviceInfoPtr)ptr;
3906 ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.platform->compatible);
3920 static int drmProcessHost1xDevice(drmDevicePtr *device,
3921 const char *node, int node_type,
3922 int maj, int min, bool fetch_deviceinfo,
3929 dev = drmDeviceAlloc(node_type, node, sizeof(drmHost1xBusInfo),
3930 sizeof(drmHost1xDeviceInfo), &ptr);
3934 dev->bustype = DRM_BUS_HOST1X;
3936 dev->businfo.host1x = (drmHost1xBusInfoPtr)ptr;
3938 ret = drmParseOFBusInfo(maj, min, dev->businfo.host1x->fullname);
3942 if (fetch_deviceinfo) {
3943 ptr += sizeof(drmHost1xBusInfo);
3944 dev->deviceinfo.host1x = (drmHost1xDeviceInfoPtr)ptr;
3946 ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.host1x->compatible);
3961 process_device(drmDevicePtr *device, const char *d_name,
3962 int req_subsystem_type,
3963 bool fetch_deviceinfo, uint32_t flags)
3966 char node[PATH_MAX + 1];
3967 int node_type, subsystem_type;
3968 unsigned int maj, min;
3970 node_type = drmGetNodeType(d_name);
3974 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, d_name);
3975 if (stat(node, &sbuf))
3978 maj = major(sbuf.st_rdev);
3979 min = minor(sbuf.st_rdev);
3981 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3984 subsystem_type = drmParseSubsystemType(maj, min);
3985 if (req_subsystem_type != -1 && req_subsystem_type != subsystem_type)
3988 switch (subsystem_type) {
3990 case DRM_BUS_VIRTIO:
3991 return drmProcessPciDevice(device, node, node_type, maj, min,
3992 fetch_deviceinfo, flags);
3994 return drmProcessUsbDevice(device, node, node_type, maj, min,
3995 fetch_deviceinfo, flags);
3996 case DRM_BUS_PLATFORM:
3997 return drmProcessPlatformDevice(device, node, node_type, maj, min,
3998 fetch_deviceinfo, flags);
3999 case DRM_BUS_HOST1X:
4000 return drmProcessHost1xDevice(device, node, node_type, maj, min,
4001 fetch_deviceinfo, flags);
4007 /* Consider devices located on the same bus as duplicate and fold the respective
4008 * entries into a single one.
4010 * Note: this leaves "gaps" in the array, while preserving the length.
4012 static void drmFoldDuplicatedDevices(drmDevicePtr local_devices[], int count)
4014 int node_type, i, j;
4016 for (i = 0; i < count; i++) {
4017 for (j = i + 1; j < count; j++) {
4018 if (drmDevicesEqual(local_devices[i], local_devices[j])) {
4019 local_devices[i]->available_nodes |= local_devices[j]->available_nodes;
4020 node_type = log2_int(local_devices[j]->available_nodes);
4021 memcpy(local_devices[i]->nodes[node_type],
4022 local_devices[j]->nodes[node_type], drmGetMaxNodeName());
4023 drmFreeDevice(&local_devices[j]);
4029 /* Check that the given flags are valid returning 0 on success */
4031 drm_device_validate_flags(uint32_t flags)
4033 return (flags & ~DRM_DEVICE_GET_PCI_REVISION);
4037 drm_device_has_rdev(drmDevicePtr device, dev_t find_rdev)
4041 for (int i = 0; i < DRM_NODE_MAX; i++) {
4042 if (device->available_nodes & 1 << i) {
4043 if (stat(device->nodes[i], &sbuf) == 0 &&
4044 sbuf.st_rdev == find_rdev)
4052 * The kernel drm core has a number of places that assume maximum of
4053 * 3x64 devices nodes. That's 64 for each of primary, control and
4054 * render nodes. Rounded it up to 256 for simplicity.
4056 #define MAX_DRM_NODES 256
4059 * Get information about the opened drm device
4061 * \param fd file descriptor of the drm device
4062 * \param flags feature/behaviour bitmask
4063 * \param device the address of a drmDevicePtr where the information
4064 * will be allocated in stored
4066 * \return zero on success, negative error code otherwise.
4068 * \note Unlike drmGetDevice it does not retrieve the pci device revision field
4069 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
4071 drm_public int drmGetDevice2(int fd, uint32_t flags, drmDevicePtr *device)
4075 * DRI device nodes on OpenBSD are not in their own directory, they reside
4076 * in /dev along with a large number of statically generated /dev nodes.
4077 * Avoid stat'ing all of /dev needlessly by implementing this custom path.
4081 char node[PATH_MAX + 1];
4082 const char *dev_name;
4083 int node_type, subsystem_type;
4084 int maj, min, n, ret;
4086 if (fd == -1 || device == NULL)
4089 if (fstat(fd, &sbuf))
4092 maj = major(sbuf.st_rdev);
4093 min = minor(sbuf.st_rdev);
4095 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4098 node_type = drmGetMinorType(maj, min);
4099 if (node_type == -1)
4102 dev_name = drmGetDeviceName(node_type);
4106 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min);
4107 if (n == -1 || n >= PATH_MAX)
4109 if (stat(node, &sbuf))
4112 subsystem_type = drmParseSubsystemType(maj, min);
4113 if (subsystem_type != DRM_BUS_PCI)
4116 ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
4124 drmDevicePtr local_devices[MAX_DRM_NODES];
4127 struct dirent *dent;
4131 int ret, i, node_count;
4134 if (drm_device_validate_flags(flags))
4137 if (fd == -1 || device == NULL)
4140 if (fstat(fd, &sbuf))
4143 find_rdev = sbuf.st_rdev;
4144 maj = major(sbuf.st_rdev);
4145 min = minor(sbuf.st_rdev);
4147 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4150 subsystem_type = drmParseSubsystemType(maj, min);
4151 if (subsystem_type < 0)
4152 return subsystem_type;
4154 sysdir = opendir(DRM_DIR_NAME);
4159 while ((dent = readdir(sysdir))) {
4160 ret = process_device(&d, dent->d_name, subsystem_type, true, flags);
4164 if (i >= MAX_DRM_NODES) {
4165 fprintf(stderr, "More than %d drm nodes detected. "
4166 "Please report a bug - that should not happen.\n"
4167 "Skipping extra nodes\n", MAX_DRM_NODES);
4170 local_devices[i] = d;
4175 drmFoldDuplicatedDevices(local_devices, node_count);
4179 for (i = 0; i < node_count; i++) {
4180 if (!local_devices[i])
4183 if (drm_device_has_rdev(local_devices[i], find_rdev))
4184 *device = local_devices[i];
4186 drmFreeDevice(&local_devices[i]);
4190 if (*device == NULL)
4197 * Get information about the opened drm device
4199 * \param fd file descriptor of the drm device
4200 * \param device the address of a drmDevicePtr where the information
4201 * will be allocated in stored
4203 * \return zero on success, negative error code otherwise.
4205 drm_public int drmGetDevice(int fd, drmDevicePtr *device)
4207 return drmGetDevice2(fd, DRM_DEVICE_GET_PCI_REVISION, device);
4211 * Get drm devices on the system
4213 * \param flags feature/behaviour bitmask
4214 * \param devices the array of devices with drmDevicePtr elements
4215 * can be NULL to get the device number first
4216 * \param max_devices the maximum number of devices for the array
4218 * \return on error - negative error code,
4219 * if devices is NULL - total number of devices available on the system,
4220 * alternatively the number of devices stored in devices[], which is
4221 * capped by the max_devices.
4223 * \note Unlike drmGetDevices it does not retrieve the pci device revision field
4224 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
4226 drm_public int drmGetDevices2(uint32_t flags, drmDevicePtr devices[],
4229 drmDevicePtr local_devices[MAX_DRM_NODES];
4230 drmDevicePtr device;
4232 struct dirent *dent;
4233 int ret, i, node_count, device_count;
4235 if (drm_device_validate_flags(flags))
4238 sysdir = opendir(DRM_DIR_NAME);
4243 while ((dent = readdir(sysdir))) {
4244 ret = process_device(&device, dent->d_name, -1, devices != NULL, flags);
4248 if (i >= MAX_DRM_NODES) {
4249 fprintf(stderr, "More than %d drm nodes detected. "
4250 "Please report a bug - that should not happen.\n"
4251 "Skipping extra nodes\n", MAX_DRM_NODES);
4254 local_devices[i] = device;
4259 drmFoldDuplicatedDevices(local_devices, node_count);
4262 for (i = 0; i < node_count; i++) {
4263 if (!local_devices[i])
4266 if ((devices != NULL) && (device_count < max_devices))
4267 devices[device_count] = local_devices[i];
4269 drmFreeDevice(&local_devices[i]);
4275 return device_count;
4279 * Get drm devices on the system
4281 * \param devices the array of devices with drmDevicePtr elements
4282 * can be NULL to get the device number first
4283 * \param max_devices the maximum number of devices for the array
4285 * \return on error - negative error code,
4286 * if devices is NULL - total number of devices available on the system,
4287 * alternatively the number of devices stored in devices[], which is
4288 * capped by the max_devices.
4290 drm_public int drmGetDevices(drmDevicePtr devices[], int max_devices)
4292 return drmGetDevices2(DRM_DEVICE_GET_PCI_REVISION, devices, max_devices);
4295 drm_public char *drmGetDeviceNameFromFd2(int fd)
4299 char path[PATH_MAX + 1], *value;
4300 unsigned int maj, min;
4302 if (fstat(fd, &sbuf))
4305 maj = major(sbuf.st_rdev);
4306 min = minor(sbuf.st_rdev);
4308 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4311 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d", maj, min);
4313 value = sysfs_uevent_get(path, "DEVNAME");
4317 snprintf(path, sizeof(path), "/dev/%s", value);
4320 return strdup(path);
4321 #elif defined(__FreeBSD__)
4322 return drmGetDeviceNameFromFd(fd);
4325 char node[PATH_MAX + 1];
4326 const char *dev_name;
4330 if (fstat(fd, &sbuf))
4333 maj = major(sbuf.st_rdev);
4334 min = minor(sbuf.st_rdev);
4336 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4339 node_type = drmGetMinorType(maj, min);
4340 if (node_type == -1)
4343 dev_name = drmGetDeviceName(node_type);
4347 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min);
4348 if (n == -1 || n >= PATH_MAX)
4351 return strdup(node);
4355 drm_public int drmSyncobjCreate(int fd, uint32_t flags, uint32_t *handle)
4357 struct drm_syncobj_create args;
4363 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_CREATE, &args);
4366 *handle = args.handle;
4370 drm_public int drmSyncobjDestroy(int fd, uint32_t handle)
4372 struct drm_syncobj_destroy args;
4375 args.handle = handle;
4376 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_DESTROY, &args);
4379 drm_public int drmSyncobjHandleToFD(int fd, uint32_t handle, int *obj_fd)
4381 struct drm_syncobj_handle args;
4386 args.handle = handle;
4387 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4394 drm_public int drmSyncobjFDToHandle(int fd, int obj_fd, uint32_t *handle)
4396 struct drm_syncobj_handle args;
4402 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4405 *handle = args.handle;
4409 drm_public int drmSyncobjImportSyncFile(int fd, uint32_t handle,
4412 struct drm_syncobj_handle args;
4415 args.fd = sync_file_fd;
4416 args.handle = handle;
4417 args.flags = DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE;
4418 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4421 drm_public int drmSyncobjExportSyncFile(int fd, uint32_t handle,
4424 struct drm_syncobj_handle args;
4429 args.handle = handle;
4430 args.flags = DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE;
4431 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4434 *sync_file_fd = args.fd;
4438 drm_public int drmSyncobjWait(int fd, uint32_t *handles, unsigned num_handles,
4439 int64_t timeout_nsec, unsigned flags,
4440 uint32_t *first_signaled)
4442 struct drm_syncobj_wait args;
4446 args.handles = (uintptr_t)handles;
4447 args.timeout_nsec = timeout_nsec;
4448 args.count_handles = num_handles;
4451 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_WAIT, &args);
4456 *first_signaled = args.first_signaled;
4460 drm_public int drmSyncobjReset(int fd, const uint32_t *handles,
4461 uint32_t handle_count)
4463 struct drm_syncobj_array args;
4467 args.handles = (uintptr_t)handles;
4468 args.count_handles = handle_count;
4470 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_RESET, &args);
4474 drm_public int drmSyncobjSignal(int fd, const uint32_t *handles,
4475 uint32_t handle_count)
4477 struct drm_syncobj_array args;
4481 args.handles = (uintptr_t)handles;
4482 args.count_handles = handle_count;
4484 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_SIGNAL, &args);
4488 drm_public int drmSyncobjTimelineSignal(int fd, const uint32_t *handles,
4489 uint64_t *points, uint32_t handle_count)
4491 struct drm_syncobj_timeline_array args;
4495 args.handles = (uintptr_t)handles;
4496 args.points = (uintptr_t)points;
4497 args.count_handles = handle_count;
4499 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TIMELINE_SIGNAL, &args);
4503 drm_public int drmSyncobjTimelineWait(int fd, uint32_t *handles, uint64_t *points,
4504 unsigned num_handles,
4505 int64_t timeout_nsec, unsigned flags,
4506 uint32_t *first_signaled)
4508 struct drm_syncobj_timeline_wait args;
4512 args.handles = (uintptr_t)handles;
4513 args.points = (uintptr_t)points;
4514 args.timeout_nsec = timeout_nsec;
4515 args.count_handles = num_handles;
4518 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TIMELINE_WAIT, &args);
4523 *first_signaled = args.first_signaled;
4528 drm_public int drmSyncobjQuery(int fd, uint32_t *handles, uint64_t *points,
4529 uint32_t handle_count)
4531 struct drm_syncobj_timeline_array args;
4535 args.handles = (uintptr_t)handles;
4536 args.points = (uintptr_t)points;
4537 args.count_handles = handle_count;
4539 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_QUERY, &args);
4545 drm_public int drmSyncobjQuery2(int fd, uint32_t *handles, uint64_t *points,
4546 uint32_t handle_count, uint32_t flags)
4548 struct drm_syncobj_timeline_array args;
4551 args.handles = (uintptr_t)handles;
4552 args.points = (uintptr_t)points;
4553 args.count_handles = handle_count;
4556 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_QUERY, &args);
4560 drm_public int drmSyncobjTransfer(int fd,
4561 uint32_t dst_handle, uint64_t dst_point,
4562 uint32_t src_handle, uint64_t src_point,
4565 struct drm_syncobj_transfer args;
4569 args.src_handle = src_handle;
4570 args.dst_handle = dst_handle;
4571 args.src_point = src_point;
4572 args.dst_point = dst_point;
4575 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TRANSFER, &args);