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.
51 #include <sys/types.h>
53 #define stat_t struct stat
54 #include <sys/ioctl.h>
58 #include <sys/mkdev.h>
60 #ifdef MAJOR_IN_SYSMACROS
61 #include <sys/sysmacros.h>
65 /* Not all systems have MAP_FAILED defined */
67 #define MAP_FAILED ((void *)-1)
71 #include "libdrm_macros.h"
73 #include "util_math.h"
76 #define DRM_PRIMARY_MINOR_NAME "drm"
77 #define DRM_CONTROL_MINOR_NAME "drmC"
78 #define DRM_RENDER_MINOR_NAME "drmR"
80 #define DRM_PRIMARY_MINOR_NAME "card"
81 #define DRM_CONTROL_MINOR_NAME "controlD"
82 #define DRM_RENDER_MINOR_NAME "renderD"
85 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
99 #endif /* __OpenBSD__ */
102 #define DRM_MAJOR 226 /* Linux */
113 uint16_t subvendor_id;
114 uint16_t subdevice_id;
118 #define DRM_IOCTL_GET_PCIINFO DRM_IOR(0x15, struct drm_pciinfo)
121 #define DRM_MSG_VERBOSITY 3
123 #define memclear(s) memset(&s, 0, sizeof(s))
125 static drmServerInfoPtr drm_server_info;
127 void drmSetServerInfo(drmServerInfoPtr info)
129 drm_server_info = info;
133 * Output a message to stderr.
135 * \param format printf() like format string.
138 * This function is a wrapper around vfprintf().
141 static int DRM_PRINTFLIKE(1, 0)
142 drmDebugPrint(const char *format, va_list ap)
144 return vfprintf(stderr, format, ap);
148 drmMsg(const char *format, ...)
152 if (((env = getenv("LIBGL_DEBUG")) && strstr(env, "verbose")) ||
153 (drm_server_info && drm_server_info->debug_print))
155 va_start(ap, format);
156 if (drm_server_info) {
157 drm_server_info->debug_print(format,ap);
159 drmDebugPrint(format, ap);
165 static void *drmHashTable = NULL; /* Context switch callbacks */
167 void *drmGetHashTable(void)
172 void *drmMalloc(int size)
174 return calloc(1, size);
177 void drmFree(void *pt)
183 * Call ioctl, restarting if it is interupted
186 drmIoctl(int fd, unsigned long request, void *arg)
191 ret = ioctl(fd, request, arg);
192 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
196 static unsigned long drmGetKeyFromFd(int fd)
205 drmHashEntry *drmGetEntry(int fd)
207 unsigned long key = drmGetKeyFromFd(fd);
212 drmHashTable = drmHashCreate();
214 if (drmHashLookup(drmHashTable, key, &value)) {
215 entry = drmMalloc(sizeof(*entry));
218 entry->tagTable = drmHashCreate();
219 drmHashInsert(drmHashTable, key, entry);
227 * Compare two busid strings
232 * \return 1 if matched.
235 * This function compares two bus ID strings. It understands the older
236 * PCI:b:d:f format and the newer pci:oooo:bb:dd.f format. In the format, o is
237 * domain, b is bus, d is device, f is function.
239 static int drmMatchBusID(const char *id1, const char *id2, int pci_domain_ok)
241 /* First, check if the IDs are exactly the same */
242 if (strcasecmp(id1, id2) == 0)
245 /* Try to match old/new-style PCI bus IDs. */
246 if (strncasecmp(id1, "pci", 3) == 0) {
247 unsigned int o1, b1, d1, f1;
248 unsigned int o2, b2, d2, f2;
251 ret = sscanf(id1, "pci:%04x:%02x:%02x.%u", &o1, &b1, &d1, &f1);
254 ret = sscanf(id1, "PCI:%u:%u:%u", &b1, &d1, &f1);
259 ret = sscanf(id2, "pci:%04x:%02x:%02x.%u", &o2, &b2, &d2, &f2);
262 ret = sscanf(id2, "PCI:%u:%u:%u", &b2, &d2, &f2);
267 /* If domains aren't properly supported by the kernel interface,
268 * just ignore them, which sucks less than picking a totally random
269 * card with "open by name"
274 if ((o1 != o2) || (b1 != b2) || (d1 != d2) || (f1 != f2))
283 * Handles error checking for chown call.
285 * \param path to file.
286 * \param id of the new owner.
287 * \param id of the new group.
289 * \return zero if success or -1 if failure.
292 * Checks for failure. If failure was caused by signal call chown again.
293 * If any other failure happened then it will output error mesage using
297 static int chown_check_return(const char *path, uid_t owner, gid_t group)
302 rv = chown(path, owner, group);
303 } while (rv != 0 && errno == EINTR);
308 drmMsg("Failed to change owner or group for file %s! %d: %s\n",
309 path, errno, strerror(errno));
315 * Open the DRM device, creating it if necessary.
317 * \param dev major and minor numbers of the device.
318 * \param minor minor number of the device.
320 * \return a file descriptor on success, or a negative value on error.
323 * Assembles the device name from \p minor and opens it, creating the device
324 * special file node with the major and minor numbers specified by \p dev and
325 * parent directory if necessary and was called by root.
327 static int drmOpenDevice(dev_t dev, int minor, int type)
330 const char *dev_name;
333 mode_t devmode = DRM_DEV_MODE, serv_mode;
336 int isroot = !geteuid();
337 uid_t user = DRM_DEV_UID;
338 gid_t group = DRM_DEV_GID;
342 case DRM_NODE_PRIMARY:
343 dev_name = DRM_DEV_NAME;
345 case DRM_NODE_CONTROL:
346 dev_name = DRM_CONTROL_DEV_NAME;
348 case DRM_NODE_RENDER:
349 dev_name = DRM_RENDER_DEV_NAME;
355 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
356 drmMsg("drmOpenDevice: node name is %s\n", buf);
358 if (drm_server_info && drm_server_info->get_perms) {
359 drm_server_info->get_perms(&serv_group, &serv_mode);
360 devmode = serv_mode ? serv_mode : DRM_DEV_MODE;
361 devmode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
365 if (stat(DRM_DIR_NAME, &st)) {
367 return DRM_ERR_NOT_ROOT;
368 mkdir(DRM_DIR_NAME, DRM_DEV_DIRMODE);
369 chown_check_return(DRM_DIR_NAME, 0, 0); /* root:root */
370 chmod(DRM_DIR_NAME, DRM_DEV_DIRMODE);
373 /* Check if the device node exists and create it if necessary. */
374 if (stat(buf, &st)) {
376 return DRM_ERR_NOT_ROOT;
378 mknod(buf, S_IFCHR | devmode, dev);
381 if (drm_server_info && drm_server_info->get_perms) {
382 group = ((int)serv_group >= 0) ? serv_group : DRM_DEV_GID;
383 chown_check_return(buf, user, group);
387 /* if we modprobed then wait for udev */
391 if (stat(DRM_DIR_NAME, &st)) {
395 if (udev_count == 50)
400 if (stat(buf, &st)) {
404 if (udev_count == 50)
411 fd = open(buf, O_RDWR, 0);
412 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
413 fd, fd < 0 ? strerror(errno) : "OK");
418 /* Check if the device node is not what we expect it to be, and recreate it
419 * and try again if so.
421 if (st.st_rdev != dev) {
423 return DRM_ERR_NOT_ROOT;
425 mknod(buf, S_IFCHR | devmode, dev);
426 if (drm_server_info && drm_server_info->get_perms) {
427 chown_check_return(buf, user, group);
431 fd = open(buf, O_RDWR, 0);
432 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
433 fd, fd < 0 ? strerror(errno) : "OK");
437 drmMsg("drmOpenDevice: Open failed\n");
445 * Open the DRM device
447 * \param minor device minor number.
448 * \param create allow to create the device if set.
450 * \return a file descriptor on success, or a negative value on error.
453 * Calls drmOpenDevice() if \p create is set, otherwise assembles the device
454 * name from \p minor and opens it.
456 static int drmOpenMinor(int minor, int create, int type)
460 const char *dev_name;
463 return drmOpenDevice(makedev(DRM_MAJOR, minor), minor, type);
466 case DRM_NODE_PRIMARY:
467 dev_name = DRM_DEV_NAME;
469 case DRM_NODE_CONTROL:
470 dev_name = DRM_CONTROL_DEV_NAME;
472 case DRM_NODE_RENDER:
473 dev_name = DRM_RENDER_DEV_NAME;
479 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
480 if ((fd = open(buf, O_RDWR, 0)) >= 0)
487 * Determine whether the DRM kernel driver has been loaded.
489 * \return 1 if the DRM driver is loaded, 0 otherwise.
492 * Determine the presence of the kernel driver by attempting to open the 0
493 * minor and get version information. For backward compatibility with older
494 * Linux implementations, /proc/dri is also checked.
496 int drmAvailable(void)
498 drmVersionPtr version;
502 if ((fd = drmOpenMinor(0, 1, DRM_NODE_PRIMARY)) < 0) {
504 /* Try proc for backward Linux compatibility */
505 if (!access("/proc/dri/0", R_OK))
511 if ((version = drmGetVersion(fd))) {
513 drmFreeVersion(version);
520 static int drmGetMinorBase(int type)
523 case DRM_NODE_PRIMARY:
525 case DRM_NODE_CONTROL:
527 case DRM_NODE_RENDER:
534 static int drmGetMinorType(int minor)
536 int type = minor >> 6;
542 case DRM_NODE_PRIMARY:
543 case DRM_NODE_CONTROL:
544 case DRM_NODE_RENDER:
551 static const char *drmGetMinorName(int type)
554 case DRM_NODE_PRIMARY:
555 return DRM_PRIMARY_MINOR_NAME;
556 case DRM_NODE_CONTROL:
557 return DRM_CONTROL_MINOR_NAME;
558 case DRM_NODE_RENDER:
559 return DRM_RENDER_MINOR_NAME;
566 * Open the device by bus ID.
568 * \param busid bus ID.
569 * \param type device node type.
571 * \return a file descriptor on success, or a negative value on error.
574 * This function attempts to open every possible minor (up to DRM_MAX_MINOR),
575 * comparing the device bus ID with the one supplied.
577 * \sa drmOpenMinor() and drmGetBusid().
579 static int drmOpenByBusid(const char *busid, int type)
581 int i, pci_domain_ok = 1;
585 int base = drmGetMinorBase(type);
590 drmMsg("drmOpenByBusid: Searching for BusID %s\n", busid);
591 for (i = base; i < base + DRM_MAX_MINOR; i++) {
592 fd = drmOpenMinor(i, 1, type);
593 drmMsg("drmOpenByBusid: drmOpenMinor returns %d\n", fd);
595 /* We need to try for 1.4 first for proper PCI domain support
596 * and if that fails, we know the kernel is busted
600 sv.drm_dd_major = -1; /* Don't care */
601 sv.drm_dd_minor = -1; /* Don't care */
602 if (drmSetInterfaceVersion(fd, &sv)) {
608 sv.drm_dd_major = -1; /* Don't care */
609 sv.drm_dd_minor = -1; /* Don't care */
610 drmMsg("drmOpenByBusid: Interface 1.4 failed, trying 1.1\n");
611 drmSetInterfaceVersion(fd, &sv);
613 buf = drmGetBusid(fd);
614 drmMsg("drmOpenByBusid: drmGetBusid reports %s\n", buf);
615 if (buf && drmMatchBusID(buf, busid, pci_domain_ok)) {
629 * Open the device by name.
631 * \param name driver name.
632 * \param type the device node type.
634 * \return a file descriptor on success, or a negative value on error.
637 * This function opens the first minor number that matches the driver name and
638 * isn't already in use. If it's in use it then it will already have a bus ID
641 * \sa drmOpenMinor(), drmGetVersion() and drmGetBusid().
643 static int drmOpenByName(const char *name, int type)
647 drmVersionPtr version;
649 int base = drmGetMinorBase(type);
655 * Open the first minor number that matches the driver name and isn't
656 * already in use. If it's in use it will have a busid assigned already.
658 for (i = base; i < base + DRM_MAX_MINOR; i++) {
659 if ((fd = drmOpenMinor(i, 1, type)) >= 0) {
660 if ((version = drmGetVersion(fd))) {
661 if (!strcmp(version->name, name)) {
662 drmFreeVersion(version);
663 id = drmGetBusid(fd);
664 drmMsg("drmGetBusid returned '%s'\n", id ? id : "NULL");
673 drmFreeVersion(version);
681 /* Backward-compatibility /proc support */
682 for (i = 0; i < 8; i++) {
683 char proc_name[64], buf[512];
684 char *driver, *pt, *devstring;
687 sprintf(proc_name, "/proc/dri/%d/name", i);
688 if ((fd = open(proc_name, 0, 0)) >= 0) {
689 retcode = read(fd, buf, sizeof(buf)-1);
692 buf[retcode-1] = '\0';
693 for (driver = pt = buf; *pt && *pt != ' '; ++pt)
695 if (*pt) { /* Device is next */
697 if (!strcmp(driver, name)) { /* Match */
698 for (devstring = ++pt; *pt && *pt != ' '; ++pt)
700 if (*pt) { /* Found busid */
701 return drmOpenByBusid(++pt, type);
702 } else { /* No busid */
703 return drmOpenDevice(strtol(devstring, NULL, 0),i, type);
717 * Open the DRM device.
719 * Looks up the specified name and bus ID, and opens the device found. The
720 * entry in /dev/dri is created if necessary and if called by root.
722 * \param name driver name. Not referenced if bus ID is supplied.
723 * \param busid bus ID. Zero if not known.
725 * \return a file descriptor on success, or a negative value on error.
728 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
731 int drmOpen(const char *name, const char *busid)
733 return drmOpenWithType(name, busid, DRM_NODE_PRIMARY);
737 * Open the DRM device with specified type.
739 * Looks up the specified name and bus ID, and opens the device found. The
740 * entry in /dev/dri is created if necessary and if called by root.
742 * \param name driver name. Not referenced if bus ID is supplied.
743 * \param busid bus ID. Zero if not known.
744 * \param type the device node type to open, PRIMARY, CONTROL or RENDER
746 * \return a file descriptor on success, or a negative value on error.
749 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
752 int drmOpenWithType(const char *name, const char *busid, int type)
754 if (!drmAvailable() && name != NULL && drm_server_info &&
755 drm_server_info->load_module) {
756 /* try to load the kernel module */
757 if (!drm_server_info->load_module(name)) {
758 drmMsg("[drm] failed to load kernel module \"%s\"\n", name);
764 int fd = drmOpenByBusid(busid, type);
770 return drmOpenByName(name, type);
775 int drmOpenControl(int minor)
777 return drmOpenMinor(minor, 0, DRM_NODE_CONTROL);
780 int drmOpenRender(int minor)
782 return drmOpenMinor(minor, 0, DRM_NODE_RENDER);
786 * Free the version information returned by drmGetVersion().
788 * \param v pointer to the version information.
791 * It frees the memory pointed by \p %v as well as all the non-null strings
794 void drmFreeVersion(drmVersionPtr v)
806 * Free the non-public version information returned by the kernel.
808 * \param v pointer to the version information.
811 * Used by drmGetVersion() to free the memory pointed by \p %v as well as all
812 * the non-null strings pointers in it.
814 static void drmFreeKernelVersion(drm_version_t *v)
826 * Copy version information.
828 * \param d destination pointer.
829 * \param s source pointer.
832 * Used by drmGetVersion() to translate the information returned by the ioctl
833 * interface in a private structure into the public structure counterpart.
835 static void drmCopyVersion(drmVersionPtr d, const drm_version_t *s)
837 d->version_major = s->version_major;
838 d->version_minor = s->version_minor;
839 d->version_patchlevel = s->version_patchlevel;
840 d->name_len = s->name_len;
841 d->name = strdup(s->name);
842 d->date_len = s->date_len;
843 d->date = strdup(s->date);
844 d->desc_len = s->desc_len;
845 d->desc = strdup(s->desc);
850 * Query the driver version information.
852 * \param fd file descriptor.
854 * \return pointer to a drmVersion structure which should be freed with
857 * \note Similar information is available via /proc/dri.
860 * It gets the version information via successive DRM_IOCTL_VERSION ioctls,
861 * first with zeros to get the string lengths, and then the actually strings.
862 * It also null-terminates them since they might not be already.
864 drmVersionPtr drmGetVersion(int fd)
866 drmVersionPtr retval;
867 drm_version_t *version = drmMalloc(sizeof(*version));
871 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
872 drmFreeKernelVersion(version);
876 if (version->name_len)
877 version->name = drmMalloc(version->name_len + 1);
878 if (version->date_len)
879 version->date = drmMalloc(version->date_len + 1);
880 if (version->desc_len)
881 version->desc = drmMalloc(version->desc_len + 1);
883 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
884 drmMsg("DRM_IOCTL_VERSION: %s\n", strerror(errno));
885 drmFreeKernelVersion(version);
889 /* The results might not be null-terminated strings, so terminate them. */
890 if (version->name_len) version->name[version->name_len] = '\0';
891 if (version->date_len) version->date[version->date_len] = '\0';
892 if (version->desc_len) version->desc[version->desc_len] = '\0';
894 retval = drmMalloc(sizeof(*retval));
895 drmCopyVersion(retval, version);
896 drmFreeKernelVersion(version);
902 * Get version information for the DRM user space library.
904 * This version number is driver independent.
906 * \param fd file descriptor.
908 * \return version information.
911 * This function allocates and fills a drm_version structure with a hard coded
914 drmVersionPtr drmGetLibVersion(int fd)
916 drm_version_t *version = drmMalloc(sizeof(*version));
919 * NOTE THIS MUST NOT GO ABOVE VERSION 1.X due to drivers needing it
920 * revision 1.0.x = original DRM interface with no drmGetLibVersion
921 * entry point and many drm<Device> extensions
922 * revision 1.1.x = added drmCommand entry points for device extensions
923 * added drmGetLibVersion to identify libdrm.a version
924 * revision 1.2.x = added drmSetInterfaceVersion
925 * modified drmOpen to handle both busid and name
926 * revision 1.3.x = added server + memory manager
928 version->version_major = 1;
929 version->version_minor = 3;
930 version->version_patchlevel = 0;
932 return (drmVersionPtr)version;
935 int drmGetCap(int fd, uint64_t capability, uint64_t *value)
937 struct drm_get_cap cap;
941 cap.capability = capability;
943 ret = drmIoctl(fd, DRM_IOCTL_GET_CAP, &cap);
951 int drmSetClientCap(int fd, uint64_t capability, uint64_t value)
953 struct drm_set_client_cap cap;
956 cap.capability = capability;
959 return drmIoctl(fd, DRM_IOCTL_SET_CLIENT_CAP, &cap);
963 * Free the bus ID information.
965 * \param busid bus ID information string as given by drmGetBusid().
968 * This function is just frees the memory pointed by \p busid.
970 void drmFreeBusid(const char *busid)
972 drmFree((void *)busid);
977 * Get the bus ID of the device.
979 * \param fd file descriptor.
981 * \return bus ID string.
984 * This function gets the bus ID via successive DRM_IOCTL_GET_UNIQUE ioctls to
985 * get the string length and data, passing the arguments in a drm_unique
988 char *drmGetBusid(int fd)
994 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
996 u.unique = drmMalloc(u.unique_len + 1);
997 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u)) {
1001 u.unique[u.unique_len] = '\0';
1008 * Set the bus ID of the device.
1010 * \param fd file descriptor.
1011 * \param busid bus ID string.
1013 * \return zero on success, negative on failure.
1016 * This function is a wrapper around the DRM_IOCTL_SET_UNIQUE ioctl, passing
1017 * the arguments in a drm_unique structure.
1019 int drmSetBusid(int fd, const char *busid)
1024 u.unique = (char *)busid;
1025 u.unique_len = strlen(busid);
1027 if (drmIoctl(fd, DRM_IOCTL_SET_UNIQUE, &u)) {
1033 int drmGetMagic(int fd, drm_magic_t * magic)
1040 if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
1042 *magic = auth.magic;
1046 int drmAuthMagic(int fd, drm_magic_t magic)
1052 if (drmIoctl(fd, DRM_IOCTL_AUTH_MAGIC, &auth))
1058 * Specifies a range of memory that is available for mapping by a
1061 * \param fd file descriptor.
1062 * \param offset usually the physical address. The actual meaning depends of
1063 * the \p type parameter. See below.
1064 * \param size of the memory in bytes.
1065 * \param type type of the memory to be mapped.
1066 * \param flags combination of several flags to modify the function actions.
1067 * \param handle will be set to a value that may be used as the offset
1068 * parameter for mmap().
1070 * \return zero on success or a negative value on error.
1072 * \par Mapping the frame buffer
1073 * For the frame buffer
1074 * - \p offset will be the physical address of the start of the frame buffer,
1075 * - \p size will be the size of the frame buffer in bytes, and
1076 * - \p type will be DRM_FRAME_BUFFER.
1079 * The area mapped will be uncached. If MTRR support is available in the
1080 * kernel, the frame buffer area will be set to write combining.
1082 * \par Mapping the MMIO register area
1083 * For the MMIO register area,
1084 * - \p offset will be the physical address of the start of the register area,
1085 * - \p size will be the size of the register area bytes, and
1086 * - \p type will be DRM_REGISTERS.
1088 * The area mapped will be uncached.
1090 * \par Mapping the SAREA
1092 * - \p offset will be ignored and should be set to zero,
1093 * - \p size will be the desired size of the SAREA in bytes,
1094 * - \p type will be DRM_SHM.
1097 * A shared memory area of the requested size will be created and locked in
1098 * kernel memory. This area may be mapped into client-space by using the handle
1101 * \note May only be called by root.
1104 * This function is a wrapper around the DRM_IOCTL_ADD_MAP ioctl, passing
1105 * the arguments in a drm_map structure.
1107 int drmAddMap(int fd, drm_handle_t offset, drmSize size, drmMapType type,
1108 drmMapFlags flags, drm_handle_t *handle)
1113 map.offset = offset;
1117 if (drmIoctl(fd, DRM_IOCTL_ADD_MAP, &map))
1120 *handle = (drm_handle_t)(uintptr_t)map.handle;
1124 int drmRmMap(int fd, drm_handle_t handle)
1129 map.handle = (void *)(uintptr_t)handle;
1131 if(drmIoctl(fd, DRM_IOCTL_RM_MAP, &map))
1137 * Make buffers available for DMA transfers.
1139 * \param fd file descriptor.
1140 * \param count number of buffers.
1141 * \param size size of each buffer.
1142 * \param flags buffer allocation flags.
1143 * \param agp_offset offset in the AGP aperture
1145 * \return number of buffers allocated, negative on error.
1148 * This function is a wrapper around DRM_IOCTL_ADD_BUFS ioctl.
1152 int drmAddBufs(int fd, int count, int size, drmBufDescFlags flags,
1155 drm_buf_desc_t request;
1158 request.count = count;
1159 request.size = size;
1160 request.flags = flags;
1161 request.agp_start = agp_offset;
1163 if (drmIoctl(fd, DRM_IOCTL_ADD_BUFS, &request))
1165 return request.count;
1168 int drmMarkBufs(int fd, double low, double high)
1170 drm_buf_info_t info;
1175 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1181 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1184 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1185 int retval = -errno;
1190 for (i = 0; i < info.count; i++) {
1191 info.list[i].low_mark = low * info.list[i].count;
1192 info.list[i].high_mark = high * info.list[i].count;
1193 if (drmIoctl(fd, DRM_IOCTL_MARK_BUFS, &info.list[i])) {
1194 int retval = -errno;
1207 * \param fd file descriptor.
1208 * \param count number of buffers to free.
1209 * \param list list of buffers to be freed.
1211 * \return zero on success, or a negative value on failure.
1213 * \note This function is primarily used for debugging.
1216 * This function is a wrapper around the DRM_IOCTL_FREE_BUFS ioctl, passing
1217 * the arguments in a drm_buf_free structure.
1219 int drmFreeBufs(int fd, int count, int *list)
1221 drm_buf_free_t request;
1224 request.count = count;
1225 request.list = list;
1226 if (drmIoctl(fd, DRM_IOCTL_FREE_BUFS, &request))
1235 * \param fd file descriptor.
1238 * This function closes the file descriptor.
1240 int drmClose(int fd)
1242 unsigned long key = drmGetKeyFromFd(fd);
1243 drmHashEntry *entry = drmGetEntry(fd);
1245 drmHashDestroy(entry->tagTable);
1248 entry->tagTable = NULL;
1250 drmHashDelete(drmHashTable, key);
1258 * Map a region of memory.
1260 * \param fd file descriptor.
1261 * \param handle handle returned by drmAddMap().
1262 * \param size size in bytes. Must match the size used by drmAddMap().
1263 * \param address will contain the user-space virtual address where the mapping
1266 * \return zero on success, or a negative value on failure.
1269 * This function is a wrapper for mmap().
1271 int drmMap(int fd, drm_handle_t handle, drmSize size, drmAddressPtr address)
1273 static unsigned long pagesize_mask = 0;
1279 pagesize_mask = getpagesize() - 1;
1281 size = (size + pagesize_mask) & ~pagesize_mask;
1283 *address = drm_mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1284 if (*address == MAP_FAILED)
1291 * Unmap mappings obtained with drmMap().
1293 * \param address address as given by drmMap().
1294 * \param size size in bytes. Must match the size used by drmMap().
1296 * \return zero on success, or a negative value on failure.
1299 * This function is a wrapper for munmap().
1301 int drmUnmap(drmAddress address, drmSize size)
1303 return drm_munmap(address, size);
1306 drmBufInfoPtr drmGetBufInfo(int fd)
1308 drm_buf_info_t info;
1309 drmBufInfoPtr retval;
1314 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1318 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1321 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1326 retval = drmMalloc(sizeof(*retval));
1327 retval->count = info.count;
1328 retval->list = drmMalloc(info.count * sizeof(*retval->list));
1329 for (i = 0; i < info.count; i++) {
1330 retval->list[i].count = info.list[i].count;
1331 retval->list[i].size = info.list[i].size;
1332 retval->list[i].low_mark = info.list[i].low_mark;
1333 retval->list[i].high_mark = info.list[i].high_mark;
1342 * Map all DMA buffers into client-virtual space.
1344 * \param fd file descriptor.
1346 * \return a pointer to a ::drmBufMap structure.
1348 * \note The client may not use these buffers until obtaining buffer indices
1352 * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1353 * information about the buffers in a drm_buf_map structure into the
1354 * client-visible data structures.
1356 drmBufMapPtr drmMapBufs(int fd)
1359 drmBufMapPtr retval;
1363 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1369 if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1372 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1377 retval = drmMalloc(sizeof(*retval));
1378 retval->count = bufs.count;
1379 retval->list = drmMalloc(bufs.count * sizeof(*retval->list));
1380 for (i = 0; i < bufs.count; i++) {
1381 retval->list[i].idx = bufs.list[i].idx;
1382 retval->list[i].total = bufs.list[i].total;
1383 retval->list[i].used = 0;
1384 retval->list[i].address = bufs.list[i].address;
1393 * Unmap buffers allocated with drmMapBufs().
1395 * \return zero on success, or negative value on failure.
1398 * Calls munmap() for every buffer stored in \p bufs and frees the
1399 * memory allocated by drmMapBufs().
1401 int drmUnmapBufs(drmBufMapPtr bufs)
1405 for (i = 0; i < bufs->count; i++) {
1406 drm_munmap(bufs->list[i].address, bufs->list[i].total);
1409 drmFree(bufs->list);
1415 #define DRM_DMA_RETRY 16
1418 * Reserve DMA buffers.
1420 * \param fd file descriptor.
1423 * \return zero on success, or a negative value on failure.
1426 * Assemble the arguments into a drm_dma structure and keeps issuing the
1427 * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1429 int drmDMA(int fd, drmDMAReqPtr request)
1434 dma.context = request->context;
1435 dma.send_count = request->send_count;
1436 dma.send_indices = request->send_list;
1437 dma.send_sizes = request->send_sizes;
1438 dma.flags = request->flags;
1439 dma.request_count = request->request_count;
1440 dma.request_size = request->request_size;
1441 dma.request_indices = request->request_list;
1442 dma.request_sizes = request->request_sizes;
1443 dma.granted_count = 0;
1446 ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1447 } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1450 request->granted_count = dma.granted_count;
1459 * Obtain heavyweight hardware lock.
1461 * \param fd file descriptor.
1462 * \param context context.
1463 * \param flags flags that determine the sate of the hardware when the function
1466 * \return always zero.
1469 * This function translates the arguments into a drm_lock structure and issue
1470 * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1472 int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
1477 lock.context = context;
1479 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
1480 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
1481 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
1482 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
1483 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
1484 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
1486 while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
1492 * Release the hardware lock.
1494 * \param fd file descriptor.
1495 * \param context context.
1497 * \return zero on success, or a negative value on failure.
1500 * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
1501 * argument in a drm_lock structure.
1503 int drmUnlock(int fd, drm_context_t context)
1508 lock.context = context;
1509 return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
1512 drm_context_t *drmGetReservedContextList(int fd, int *count)
1516 drm_context_t * retval;
1520 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1526 if (!(list = drmMalloc(res.count * sizeof(*list))))
1528 if (!(retval = drmMalloc(res.count * sizeof(*retval))))
1531 res.contexts = list;
1532 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1533 goto err_free_context;
1535 for (i = 0; i < res.count; i++)
1536 retval[i] = list[i].handle;
1549 void drmFreeReservedContextList(drm_context_t *pt)
1557 * Used by the X server during GLXContext initialization. This causes
1558 * per-context kernel-level resources to be allocated.
1560 * \param fd file descriptor.
1561 * \param handle is set on success. To be used by the client when requesting DMA
1562 * dispatch with drmDMA().
1564 * \return zero on success, or a negative value on failure.
1566 * \note May only be called by root.
1569 * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
1570 * argument in a drm_ctx structure.
1572 int drmCreateContext(int fd, drm_context_t *handle)
1577 if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
1579 *handle = ctx.handle;
1583 int drmSwitchToContext(int fd, drm_context_t context)
1588 ctx.handle = context;
1589 if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
1594 int drmSetContextFlags(int fd, drm_context_t context, drm_context_tFlags flags)
1599 * Context preserving means that no context switches are done between DMA
1600 * buffers from one context and the next. This is suitable for use in the
1601 * X server (which promises to maintain hardware context), or in the
1602 * client-side library when buffers are swapped on behalf of two threads.
1605 ctx.handle = context;
1606 if (flags & DRM_CONTEXT_PRESERVED)
1607 ctx.flags |= _DRM_CONTEXT_PRESERVED;
1608 if (flags & DRM_CONTEXT_2DONLY)
1609 ctx.flags |= _DRM_CONTEXT_2DONLY;
1610 if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
1615 int drmGetContextFlags(int fd, drm_context_t context,
1616 drm_context_tFlagsPtr flags)
1621 ctx.handle = context;
1622 if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
1625 if (ctx.flags & _DRM_CONTEXT_PRESERVED)
1626 *flags |= DRM_CONTEXT_PRESERVED;
1627 if (ctx.flags & _DRM_CONTEXT_2DONLY)
1628 *flags |= DRM_CONTEXT_2DONLY;
1635 * Free any kernel-level resources allocated with drmCreateContext() associated
1638 * \param fd file descriptor.
1639 * \param handle handle given by drmCreateContext().
1641 * \return zero on success, or a negative value on failure.
1643 * \note May only be called by root.
1646 * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
1647 * argument in a drm_ctx structure.
1649 int drmDestroyContext(int fd, drm_context_t handle)
1654 ctx.handle = handle;
1655 if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
1660 int drmCreateDrawable(int fd, drm_drawable_t *handle)
1665 if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
1667 *handle = draw.handle;
1671 int drmDestroyDrawable(int fd, drm_drawable_t handle)
1676 draw.handle = handle;
1677 if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
1682 int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
1683 drm_drawable_info_type_t type, unsigned int num,
1686 drm_update_draw_t update;
1689 update.handle = handle;
1692 update.data = (unsigned long long)(unsigned long)data;
1694 if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
1701 * Acquire the AGP device.
1703 * Must be called before any of the other AGP related calls.
1705 * \param fd file descriptor.
1707 * \return zero on success, or a negative value on failure.
1710 * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
1712 int drmAgpAcquire(int fd)
1714 if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
1721 * Release the AGP device.
1723 * \param fd file descriptor.
1725 * \return zero on success, or a negative value on failure.
1728 * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
1730 int drmAgpRelease(int fd)
1732 if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
1741 * \param fd file descriptor.
1742 * \param mode AGP mode.
1744 * \return zero on success, or a negative value on failure.
1747 * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
1748 * argument in a drm_agp_mode structure.
1750 int drmAgpEnable(int fd, unsigned long mode)
1756 if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
1763 * Allocate a chunk of AGP memory.
1765 * \param fd file descriptor.
1766 * \param size requested memory size in bytes. Will be rounded to page boundary.
1767 * \param type type of memory to allocate.
1768 * \param address if not zero, will be set to the physical address of the
1770 * \param handle on success will be set to a handle of the allocated memory.
1772 * \return zero on success, or a negative value on failure.
1775 * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
1776 * arguments in a drm_agp_buffer structure.
1778 int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
1779 unsigned long *address, drm_handle_t *handle)
1784 *handle = DRM_AGP_NO_HANDLE;
1787 if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
1790 *address = b.physical;
1797 * Free a chunk of AGP memory.
1799 * \param fd file descriptor.
1800 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1802 * \return zero on success, or a negative value on failure.
1805 * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
1806 * argument in a drm_agp_buffer structure.
1808 int drmAgpFree(int fd, drm_handle_t handle)
1814 if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
1821 * Bind a chunk of AGP memory.
1823 * \param fd file descriptor.
1824 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1825 * \param offset offset in bytes. It will round to page boundary.
1827 * \return zero on success, or a negative value on failure.
1830 * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
1831 * argument in a drm_agp_binding structure.
1833 int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
1835 drm_agp_binding_t b;
1840 if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
1847 * Unbind 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_UNBIND ioctl, passing
1856 * the argument in a drm_agp_binding structure.
1858 int drmAgpUnbind(int fd, drm_handle_t handle)
1860 drm_agp_binding_t b;
1864 if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
1871 * Get AGP driver major version number.
1873 * \param fd file descriptor.
1875 * \return major version number on success, or a negative value on failure..
1878 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1879 * necessary information in a drm_agp_info structure.
1881 int drmAgpVersionMajor(int fd)
1887 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1889 return i.agp_version_major;
1894 * Get AGP driver minor version number.
1896 * \param fd file descriptor.
1898 * \return minor version number on success, or a negative value on failure.
1901 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1902 * necessary information in a drm_agp_info structure.
1904 int drmAgpVersionMinor(int fd)
1910 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1912 return i.agp_version_minor;
1919 * \param fd file descriptor.
1921 * \return mode on success, or zero on failure.
1924 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1925 * necessary information in a drm_agp_info structure.
1927 unsigned long drmAgpGetMode(int fd)
1933 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1940 * Get AGP aperture base.
1942 * \param fd file descriptor.
1944 * \return aperture base on success, zero on failure.
1947 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1948 * necessary information in a drm_agp_info structure.
1950 unsigned long drmAgpBase(int fd)
1956 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1958 return i.aperture_base;
1963 * Get AGP aperture size.
1965 * \param fd file descriptor.
1967 * \return aperture size on success, zero on failure.
1970 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1971 * necessary information in a drm_agp_info structure.
1973 unsigned long drmAgpSize(int fd)
1979 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1981 return i.aperture_size;
1986 * Get used AGP memory.
1988 * \param fd file descriptor.
1990 * \return memory used on success, or zero on failure.
1993 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1994 * necessary information in a drm_agp_info structure.
1996 unsigned long drmAgpMemoryUsed(int fd)
2002 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2004 return i.memory_used;
2009 * Get available AGP memory.
2011 * \param fd file descriptor.
2013 * \return memory available on success, or zero on failure.
2016 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2017 * necessary information in a drm_agp_info structure.
2019 unsigned long drmAgpMemoryAvail(int fd)
2025 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2027 return i.memory_allowed;
2032 * Get hardware vendor ID.
2034 * \param fd file descriptor.
2036 * \return vendor ID on success, or zero on failure.
2039 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2040 * necessary information in a drm_agp_info structure.
2042 unsigned int drmAgpVendorId(int fd)
2048 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2055 * Get hardware device ID.
2057 * \param fd file descriptor.
2059 * \return zero on success, or zero on failure.
2062 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2063 * necessary information in a drm_agp_info structure.
2065 unsigned int drmAgpDeviceId(int fd)
2071 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2076 int drmScatterGatherAlloc(int fd, unsigned long size, drm_handle_t *handle)
2078 drm_scatter_gather_t sg;
2084 if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
2086 *handle = sg.handle;
2090 int drmScatterGatherFree(int fd, drm_handle_t handle)
2092 drm_scatter_gather_t sg;
2096 if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
2104 * \param fd file descriptor.
2105 * \param vbl pointer to a drmVBlank structure.
2107 * \return zero on success, or a negative value on failure.
2110 * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
2112 int drmWaitVBlank(int fd, drmVBlankPtr vbl)
2114 struct timespec timeout, cur;
2117 ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2119 fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
2125 ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
2126 vbl->request.type &= ~DRM_VBLANK_RELATIVE;
2127 if (ret && errno == EINTR) {
2128 clock_gettime(CLOCK_MONOTONIC, &cur);
2129 /* Timeout after 1s */
2130 if (cur.tv_sec > timeout.tv_sec + 1 ||
2131 (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
2138 } while (ret && errno == EINTR);
2144 int drmError(int err, const char *label)
2147 case DRM_ERR_NO_DEVICE:
2148 fprintf(stderr, "%s: no device\n", label);
2150 case DRM_ERR_NO_ACCESS:
2151 fprintf(stderr, "%s: no access\n", label);
2153 case DRM_ERR_NOT_ROOT:
2154 fprintf(stderr, "%s: not root\n", label);
2156 case DRM_ERR_INVALID:
2157 fprintf(stderr, "%s: invalid args\n", label);
2162 fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2170 * Install IRQ handler.
2172 * \param fd file descriptor.
2173 * \param irq IRQ number.
2175 * \return zero on success, or a negative value on failure.
2178 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2179 * argument in a drm_control structure.
2181 int drmCtlInstHandler(int fd, int irq)
2186 ctl.func = DRM_INST_HANDLER;
2188 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2195 * Uninstall IRQ handler.
2197 * \param fd file descriptor.
2199 * \return zero on success, or a negative value on failure.
2202 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2203 * argument in a drm_control structure.
2205 int drmCtlUninstHandler(int fd)
2210 ctl.func = DRM_UNINST_HANDLER;
2212 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2217 int drmFinish(int fd, int context, drmLockFlags flags)
2222 lock.context = context;
2223 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
2224 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
2225 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
2226 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
2227 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2228 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2229 if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2235 * Get IRQ from bus ID.
2237 * \param fd file descriptor.
2238 * \param busnum bus number.
2239 * \param devnum device number.
2240 * \param funcnum function number.
2242 * \return IRQ number on success, or a negative value on failure.
2245 * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2246 * arguments in a drm_irq_busid structure.
2248 int drmGetInterruptFromBusID(int fd, int busnum, int devnum, int funcnum)
2255 p.funcnum = funcnum;
2256 if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2261 int drmAddContextTag(int fd, drm_context_t context, void *tag)
2263 drmHashEntry *entry = drmGetEntry(fd);
2265 if (drmHashInsert(entry->tagTable, context, tag)) {
2266 drmHashDelete(entry->tagTable, context);
2267 drmHashInsert(entry->tagTable, context, tag);
2272 int drmDelContextTag(int fd, drm_context_t context)
2274 drmHashEntry *entry = drmGetEntry(fd);
2276 return drmHashDelete(entry->tagTable, context);
2279 void *drmGetContextTag(int fd, drm_context_t context)
2281 drmHashEntry *entry = drmGetEntry(fd);
2284 if (drmHashLookup(entry->tagTable, context, &value))
2290 int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2291 drm_handle_t handle)
2293 drm_ctx_priv_map_t map;
2296 map.ctx_id = ctx_id;
2297 map.handle = (void *)(uintptr_t)handle;
2299 if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2304 int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2305 drm_handle_t *handle)
2307 drm_ctx_priv_map_t map;
2310 map.ctx_id = ctx_id;
2312 if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2315 *handle = (drm_handle_t)(uintptr_t)map.handle;
2320 int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2321 drmMapType *type, drmMapFlags *flags, drm_handle_t *handle,
2328 if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2330 *offset = map.offset;
2334 *handle = (unsigned long)map.handle;
2339 int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2340 unsigned long *magic, unsigned long *iocs)
2342 drm_client_t client;
2346 if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2348 *auth = client.auth;
2351 *magic = client.magic;
2352 *iocs = client.iocs;
2356 int drmGetStats(int fd, drmStatsT *stats)
2362 if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2366 memset(stats, 0, sizeof(*stats));
2367 if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2371 stats->data[i].long_format = "%-20.20s"; \
2372 stats->data[i].rate_format = "%8.8s"; \
2373 stats->data[i].isvalue = 1; \
2374 stats->data[i].verbose = 0
2377 stats->data[i].long_format = "%-20.20s"; \
2378 stats->data[i].rate_format = "%5.5s"; \
2379 stats->data[i].isvalue = 0; \
2380 stats->data[i].mult_names = "kgm"; \
2381 stats->data[i].mult = 1000; \
2382 stats->data[i].verbose = 0
2385 stats->data[i].long_format = "%-20.20s"; \
2386 stats->data[i].rate_format = "%5.5s"; \
2387 stats->data[i].isvalue = 0; \
2388 stats->data[i].mult_names = "KGM"; \
2389 stats->data[i].mult = 1024; \
2390 stats->data[i].verbose = 0
2393 stats->count = s.count;
2394 for (i = 0; i < s.count; i++) {
2395 stats->data[i].value = s.data[i].value;
2396 switch (s.data[i].type) {
2397 case _DRM_STAT_LOCK:
2398 stats->data[i].long_name = "Lock";
2399 stats->data[i].rate_name = "Lock";
2402 case _DRM_STAT_OPENS:
2403 stats->data[i].long_name = "Opens";
2404 stats->data[i].rate_name = "O";
2406 stats->data[i].verbose = 1;
2408 case _DRM_STAT_CLOSES:
2409 stats->data[i].long_name = "Closes";
2410 stats->data[i].rate_name = "Lock";
2412 stats->data[i].verbose = 1;
2414 case _DRM_STAT_IOCTLS:
2415 stats->data[i].long_name = "Ioctls";
2416 stats->data[i].rate_name = "Ioc/s";
2419 case _DRM_STAT_LOCKS:
2420 stats->data[i].long_name = "Locks";
2421 stats->data[i].rate_name = "Lck/s";
2424 case _DRM_STAT_UNLOCKS:
2425 stats->data[i].long_name = "Unlocks";
2426 stats->data[i].rate_name = "Unl/s";
2430 stats->data[i].long_name = "IRQs";
2431 stats->data[i].rate_name = "IRQ/s";
2434 case _DRM_STAT_PRIMARY:
2435 stats->data[i].long_name = "Primary Bytes";
2436 stats->data[i].rate_name = "PB/s";
2439 case _DRM_STAT_SECONDARY:
2440 stats->data[i].long_name = "Secondary Bytes";
2441 stats->data[i].rate_name = "SB/s";
2445 stats->data[i].long_name = "DMA";
2446 stats->data[i].rate_name = "DMA/s";
2449 case _DRM_STAT_SPECIAL:
2450 stats->data[i].long_name = "Special DMA";
2451 stats->data[i].rate_name = "dma/s";
2454 case _DRM_STAT_MISSED:
2455 stats->data[i].long_name = "Miss";
2456 stats->data[i].rate_name = "Ms/s";
2459 case _DRM_STAT_VALUE:
2460 stats->data[i].long_name = "Value";
2461 stats->data[i].rate_name = "Value";
2464 case _DRM_STAT_BYTE:
2465 stats->data[i].long_name = "Bytes";
2466 stats->data[i].rate_name = "B/s";
2469 case _DRM_STAT_COUNT:
2471 stats->data[i].long_name = "Count";
2472 stats->data[i].rate_name = "Cnt/s";
2481 * Issue a set-version ioctl.
2483 * \param fd file descriptor.
2484 * \param drmCommandIndex command index
2485 * \param data source pointer of the data to be read and written.
2486 * \param size size of the data to be read and written.
2488 * \return zero on success, or a negative value on failure.
2491 * It issues a read-write ioctl given by
2492 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2494 int drmSetInterfaceVersion(int fd, drmSetVersion *version)
2497 drm_set_version_t sv;
2500 sv.drm_di_major = version->drm_di_major;
2501 sv.drm_di_minor = version->drm_di_minor;
2502 sv.drm_dd_major = version->drm_dd_major;
2503 sv.drm_dd_minor = version->drm_dd_minor;
2505 if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
2509 version->drm_di_major = sv.drm_di_major;
2510 version->drm_di_minor = sv.drm_di_minor;
2511 version->drm_dd_major = sv.drm_dd_major;
2512 version->drm_dd_minor = sv.drm_dd_minor;
2518 * Send a device-specific command.
2520 * \param fd file descriptor.
2521 * \param drmCommandIndex command index
2523 * \return zero on success, or a negative value on failure.
2526 * It issues a ioctl given by
2527 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2529 int drmCommandNone(int fd, unsigned long drmCommandIndex)
2531 unsigned long request;
2533 request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
2535 if (drmIoctl(fd, request, NULL)) {
2543 * Send a device-specific read command.
2545 * \param fd file descriptor.
2546 * \param drmCommandIndex command index
2547 * \param data destination pointer of the data to be read.
2548 * \param size size of the data to be read.
2550 * \return zero on success, or a negative value on failure.
2553 * It issues a read ioctl given by
2554 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2556 int drmCommandRead(int fd, unsigned long drmCommandIndex, void *data,
2559 unsigned long request;
2561 request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
2562 DRM_COMMAND_BASE + drmCommandIndex, size);
2564 if (drmIoctl(fd, request, data)) {
2572 * Send a device-specific write command.
2574 * \param fd file descriptor.
2575 * \param drmCommandIndex command index
2576 * \param data source pointer of the data to be written.
2577 * \param size size of the data to be written.
2579 * \return zero on success, or a negative value on failure.
2582 * It issues a write ioctl given by
2583 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2585 int drmCommandWrite(int fd, unsigned long drmCommandIndex, void *data,
2588 unsigned long request;
2590 request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
2591 DRM_COMMAND_BASE + drmCommandIndex, size);
2593 if (drmIoctl(fd, request, data)) {
2601 * Send a device-specific read-write command.
2603 * \param fd file descriptor.
2604 * \param drmCommandIndex command index
2605 * \param data source pointer of the data to be read and written.
2606 * \param size size of the data to be read and written.
2608 * \return zero on success, or a negative value on failure.
2611 * It issues a read-write ioctl given by
2612 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2614 int drmCommandWriteRead(int fd, unsigned long drmCommandIndex, void *data,
2617 unsigned long request;
2619 request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
2620 DRM_COMMAND_BASE + drmCommandIndex, size);
2622 if (drmIoctl(fd, request, data))
2627 #define DRM_MAX_FDS 16
2633 } connection[DRM_MAX_FDS];
2635 static int nr_fds = 0;
2637 int drmOpenOnce(void *unused,
2641 return drmOpenOnceWithType(BusID, newlyopened, DRM_NODE_PRIMARY);
2644 int drmOpenOnceWithType(const char *BusID, int *newlyopened, int type)
2649 for (i = 0; i < nr_fds; i++)
2650 if ((strcmp(BusID, connection[i].BusID) == 0) &&
2651 (connection[i].type == type)) {
2652 connection[i].refcount++;
2654 return connection[i].fd;
2657 fd = drmOpenWithType(NULL, BusID, type);
2658 if (fd < 0 || nr_fds == DRM_MAX_FDS)
2661 connection[nr_fds].BusID = strdup(BusID);
2662 connection[nr_fds].fd = fd;
2663 connection[nr_fds].refcount = 1;
2664 connection[nr_fds].type = type;
2668 fprintf(stderr, "saved connection %d for %s %d\n",
2669 nr_fds, connection[nr_fds].BusID,
2670 strcmp(BusID, connection[nr_fds].BusID));
2677 void drmCloseOnce(int fd)
2681 for (i = 0; i < nr_fds; i++) {
2682 if (fd == connection[i].fd) {
2683 if (--connection[i].refcount == 0) {
2684 drmClose(connection[i].fd);
2685 free(connection[i].BusID);
2688 connection[i] = connection[nr_fds];
2696 int drmSetMaster(int fd)
2698 return drmIoctl(fd, DRM_IOCTL_SET_MASTER, NULL);
2701 int drmDropMaster(int fd)
2703 return drmIoctl(fd, DRM_IOCTL_DROP_MASTER, NULL);
2706 char *drmGetDeviceNameFromFd(int fd)
2713 /* The whole drmOpen thing is a fiasco and we need to find a way
2714 * back to just using open(2). For now, however, lets just make
2715 * things worse with even more ad hoc directory walking code to
2716 * discover the device file name. */
2721 for (i = 0; i < DRM_MAX_MINOR; i++) {
2722 snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
2723 if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
2726 if (i == DRM_MAX_MINOR)
2729 return strdup(name);
2732 int drmGetNodeTypeFromFd(int fd)
2737 if (fstat(fd, &sbuf))
2740 maj = major(sbuf.st_rdev);
2741 min = minor(sbuf.st_rdev);
2743 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode)) {
2748 type = drmGetMinorType(min);
2754 int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags, int *prime_fd)
2756 struct drm_prime_handle args;
2761 args.handle = handle;
2763 ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
2767 *prime_fd = args.fd;
2771 int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
2773 struct drm_prime_handle args;
2778 ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
2782 *handle = args.handle;
2786 static char *drmGetMinorNameForFD(int fd, int type)
2790 struct dirent *pent, *ent;
2792 const char *name = drmGetMinorName(type);
2794 char dev_name[64], buf[64];
2803 if (fstat(fd, &sbuf))
2806 maj = major(sbuf.st_rdev);
2807 min = minor(sbuf.st_rdev);
2809 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
2812 snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
2814 sysdir = opendir(buf);
2818 name_max = fpathconf(dirfd(sysdir), _PC_NAME_MAX);
2822 pent = malloc(offsetof(struct dirent, d_name) + name_max + 1);
2826 while (readdir_r(sysdir, pent, &ent) == 0 && ent != NULL) {
2827 if (strncmp(ent->d_name, name, len) == 0) {
2828 snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
2834 return strdup(dev_name);
2844 char buf[PATH_MAX + 1];
2845 const char *dev_name;
2846 unsigned int maj, min;
2849 if (fstat(fd, &sbuf))
2852 maj = major(sbuf.st_rdev);
2853 min = minor(sbuf.st_rdev);
2855 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
2859 case DRM_NODE_PRIMARY:
2860 dev_name = DRM_DEV_NAME;
2862 case DRM_NODE_CONTROL:
2863 dev_name = DRM_CONTROL_DEV_NAME;
2865 case DRM_NODE_RENDER:
2866 dev_name = DRM_RENDER_DEV_NAME;
2872 base = drmGetMinorBase(type);
2876 n = snprintf(buf, sizeof(buf), dev_name, DRM_DIR_NAME, min - base);
2877 if (n == -1 || n >= sizeof(buf))
2885 char *drmGetPrimaryDeviceNameFromFd(int fd)
2887 return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
2890 char *drmGetRenderDeviceNameFromFd(int fd)
2892 return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
2896 static char * DRM_PRINTFLIKE(2, 3)
2897 sysfs_uevent_get(const char *path, const char *fmt, ...)
2899 char filename[PATH_MAX + 1], *key, *line = NULL, *value = NULL;
2900 size_t size = 0, len;
2906 num = vasprintf(&key, fmt, ap);
2910 snprintf(filename, sizeof(filename), "%s/uevent", path);
2912 fp = fopen(filename, "r");
2918 while ((num = getline(&line, &size, fp)) >= 0) {
2919 if ((strncmp(line, key, len) == 0) && (line[len] == '=')) {
2920 char *start = line + len + 1, *end = line + num - 1;
2925 value = strndup(start, end - start);
2939 static int drmParseSubsystemType(int maj, int min)
2942 char path[PATH_MAX + 1];
2943 char link[PATH_MAX + 1] = "";
2946 snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/subsystem",
2949 if (readlink(path, link, PATH_MAX) < 0)
2952 name = strrchr(link, '/');
2956 if (strncmp(name, "/pci", 4) == 0)
2959 if (strncmp(name, "/usb", 4) == 0)
2962 if (strncmp(name, "/platform", 9) == 0)
2963 return DRM_BUS_PLATFORM;
2965 if (strncmp(name, "/host1x", 7) == 0)
2966 return DRM_BUS_HOST1X;
2969 #elif defined(__OpenBSD__)
2972 #warning "Missing implementation of drmParseSubsystemType"
2977 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
2980 unsigned int domain, bus, dev, func;
2981 char path[PATH_MAX + 1], *value;
2984 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
2986 value = sysfs_uevent_get(path, "PCI_SLOT_NAME");
2990 num = sscanf(value, "%04x:%02x:%02x.%1u", &domain, &bus, &dev, &func);
2996 info->domain = domain;
3002 #elif defined(__OpenBSD__)
3003 struct drm_pciinfo pinfo;
3006 type = drmGetMinorType(min);
3010 fd = drmOpenMinor(min, 0, type);
3014 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3020 info->domain = pinfo.domain;
3021 info->bus = pinfo.bus;
3022 info->dev = pinfo.dev;
3023 info->func = pinfo.func;
3027 #warning "Missing implementation of drmParsePciBusInfo"
3032 int drmDevicesEqual(drmDevicePtr a, drmDevicePtr b)
3034 if (a == NULL || b == NULL)
3037 if (a->bustype != b->bustype)
3040 switch (a->bustype) {
3042 return memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo)) == 0;
3045 return memcmp(a->businfo.usb, b->businfo.usb, sizeof(drmUsbBusInfo)) == 0;
3047 case DRM_BUS_PLATFORM:
3048 return memcmp(a->businfo.platform, b->businfo.platform, sizeof(drmPlatformBusInfo)) == 0;
3050 case DRM_BUS_HOST1X:
3051 return memcmp(a->businfo.host1x, b->businfo.host1x, sizeof(drmHost1xBusInfo)) == 0;
3060 static int drmGetNodeType(const char *name)
3062 if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
3063 sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
3064 return DRM_NODE_PRIMARY;
3066 if (strncmp(name, DRM_CONTROL_MINOR_NAME,
3067 sizeof(DRM_CONTROL_MINOR_NAME ) - 1) == 0)
3068 return DRM_NODE_CONTROL;
3070 if (strncmp(name, DRM_RENDER_MINOR_NAME,
3071 sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
3072 return DRM_NODE_RENDER;
3077 static int drmGetMaxNodeName(void)
3079 return sizeof(DRM_DIR_NAME) +
3080 MAX3(sizeof(DRM_PRIMARY_MINOR_NAME),
3081 sizeof(DRM_CONTROL_MINOR_NAME),
3082 sizeof(DRM_RENDER_MINOR_NAME)) +
3083 3 /* length of the node number */;
3087 static int parse_separate_sysfs_files(int maj, int min,
3088 drmPciDeviceInfoPtr device,
3089 bool ignore_revision)
3091 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3092 static const char *attrs[] = {
3093 "revision", /* Older kernels are missing the file, so check for it first */
3099 char path[PATH_MAX + 1];
3100 unsigned int data[ARRAY_SIZE(attrs)];
3104 for (unsigned i = ignore_revision ? 1 : 0; i < ARRAY_SIZE(attrs); i++) {
3105 snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/%s", maj, min,
3107 fp = fopen(path, "r");
3111 ret = fscanf(fp, "%x", &data[i]);
3118 device->revision_id = ignore_revision ? 0xff : data[0] & 0xff;
3119 device->vendor_id = data[1] & 0xffff;
3120 device->device_id = data[2] & 0xffff;
3121 device->subvendor_id = data[3] & 0xffff;
3122 device->subdevice_id = data[4] & 0xffff;
3127 static int parse_config_sysfs_file(int maj, int min,
3128 drmPciDeviceInfoPtr device)
3130 char path[PATH_MAX + 1];
3131 unsigned char config[64];
3134 snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/config", maj, min);
3135 fd = open(path, O_RDONLY);
3139 ret = read(fd, config, sizeof(config));
3144 device->vendor_id = config[0] | (config[1] << 8);
3145 device->device_id = config[2] | (config[3] << 8);
3146 device->revision_id = config[8];
3147 device->subvendor_id = config[44] | (config[45] << 8);
3148 device->subdevice_id = config[46] | (config[47] << 8);
3154 static int drmParsePciDeviceInfo(int maj, int min,
3155 drmPciDeviceInfoPtr device,
3159 if (!(flags & DRM_DEVICE_GET_PCI_REVISION))
3160 return parse_separate_sysfs_files(maj, min, device, true);
3162 if (parse_separate_sysfs_files(maj, min, device, false))
3163 return parse_config_sysfs_file(maj, min, device);
3166 #elif defined(__OpenBSD__)
3167 struct drm_pciinfo pinfo;
3170 type = drmGetMinorType(min);
3174 fd = drmOpenMinor(min, 0, type);
3178 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3184 device->vendor_id = pinfo.vendor_id;
3185 device->device_id = pinfo.device_id;
3186 device->revision_id = pinfo.revision_id;
3187 device->subvendor_id = pinfo.subvendor_id;
3188 device->subdevice_id = pinfo.subdevice_id;
3192 #warning "Missing implementation of drmParsePciDeviceInfo"
3197 static void drmFreePlatformDevice(drmDevicePtr device)
3199 if (device->deviceinfo.platform) {
3200 if (device->deviceinfo.platform->compatible) {
3201 char **compatible = device->deviceinfo.platform->compatible;
3203 while (*compatible) {
3208 free(device->deviceinfo.platform->compatible);
3213 static void drmFreeHost1xDevice(drmDevicePtr device)
3215 if (device->deviceinfo.host1x) {
3216 if (device->deviceinfo.host1x->compatible) {
3217 char **compatible = device->deviceinfo.host1x->compatible;
3219 while (*compatible) {
3224 free(device->deviceinfo.host1x->compatible);
3229 void drmFreeDevice(drmDevicePtr *device)
3235 switch ((*device)->bustype) {
3236 case DRM_BUS_PLATFORM:
3237 drmFreePlatformDevice(*device);
3240 case DRM_BUS_HOST1X:
3241 drmFreeHost1xDevice(*device);
3250 void drmFreeDevices(drmDevicePtr devices[], int count)
3254 if (devices == NULL)
3257 for (i = 0; i < count; i++)
3259 drmFreeDevice(&devices[i]);
3262 static drmDevicePtr drmDeviceAlloc(unsigned int type, const char *node,
3263 size_t bus_size, size_t device_size,
3266 size_t max_node_length, extra, size;
3267 drmDevicePtr device;
3271 max_node_length = ALIGN(drmGetMaxNodeName(), sizeof(void *));
3272 extra = DRM_NODE_MAX * (sizeof(void *) + max_node_length);
3274 size = sizeof(*device) + extra + bus_size + device_size;
3276 device = calloc(1, size);
3280 device->available_nodes = 1 << type;
3282 ptr = (char *)device + sizeof(*device);
3283 device->nodes = (char **)ptr;
3285 ptr += DRM_NODE_MAX * sizeof(void *);
3287 for (i = 0; i < DRM_NODE_MAX; i++) {
3288 device->nodes[i] = ptr;
3289 ptr += max_node_length;
3292 memcpy(device->nodes[type], node, max_node_length);
3299 static int drmProcessPciDevice(drmDevicePtr *device,
3300 const char *node, int node_type,
3301 int maj, int min, bool fetch_deviceinfo,
3308 dev = drmDeviceAlloc(node_type, node, sizeof(drmPciBusInfo),
3309 sizeof(drmPciDeviceInfo), &addr);
3313 dev->bustype = DRM_BUS_PCI;
3315 dev->businfo.pci = (drmPciBusInfoPtr)addr;
3317 ret = drmParsePciBusInfo(maj, min, dev->businfo.pci);
3321 // Fetch the device info if the user has requested it
3322 if (fetch_deviceinfo) {
3323 addr += sizeof(drmPciBusInfo);
3324 dev->deviceinfo.pci = (drmPciDeviceInfoPtr)addr;
3326 ret = drmParsePciDeviceInfo(maj, min, dev->deviceinfo.pci, flags);
3340 static int drmParseUsbBusInfo(int maj, int min, drmUsbBusInfoPtr info)
3343 char path[PATH_MAX + 1], *value;
3344 unsigned int bus, dev;
3347 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3349 value = sysfs_uevent_get(path, "BUSNUM");
3353 ret = sscanf(value, "%03u", &bus);
3359 value = sysfs_uevent_get(path, "DEVNUM");
3363 ret = sscanf(value, "%03u", &dev);
3374 #warning "Missing implementation of drmParseUsbBusInfo"
3379 static int drmParseUsbDeviceInfo(int maj, int min, drmUsbDeviceInfoPtr info)
3382 char path[PATH_MAX + 1], *value;
3383 unsigned int vendor, product;
3386 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3388 value = sysfs_uevent_get(path, "PRODUCT");
3392 ret = sscanf(value, "%x/%x", &vendor, &product);
3398 info->vendor = vendor;
3399 info->product = product;
3403 #warning "Missing implementation of drmParseUsbDeviceInfo"
3408 static int drmProcessUsbDevice(drmDevicePtr *device, const char *node,
3409 int node_type, int maj, int min,
3410 bool fetch_deviceinfo, uint32_t flags)
3416 dev = drmDeviceAlloc(node_type, node, sizeof(drmUsbBusInfo),
3417 sizeof(drmUsbDeviceInfo), &ptr);
3421 dev->bustype = DRM_BUS_USB;
3423 dev->businfo.usb = (drmUsbBusInfoPtr)ptr;
3425 ret = drmParseUsbBusInfo(maj, min, dev->businfo.usb);
3429 if (fetch_deviceinfo) {
3430 ptr += sizeof(drmUsbBusInfo);
3431 dev->deviceinfo.usb = (drmUsbDeviceInfoPtr)ptr;
3433 ret = drmParseUsbDeviceInfo(maj, min, dev->deviceinfo.usb);
3447 static int drmParsePlatformBusInfo(int maj, int min, drmPlatformBusInfoPtr info)
3450 char path[PATH_MAX + 1], *name;
3452 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3454 name = sysfs_uevent_get(path, "OF_FULLNAME");
3458 strncpy(info->fullname, name, DRM_PLATFORM_DEVICE_NAME_LEN);
3459 info->fullname[DRM_PLATFORM_DEVICE_NAME_LEN - 1] = '\0';
3464 #warning "Missing implementation of drmParsePlatformBusInfo"
3469 static int drmParsePlatformDeviceInfo(int maj, int min,
3470 drmPlatformDeviceInfoPtr info)
3473 char path[PATH_MAX + 1], *value;
3474 unsigned int count, i;
3477 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3479 value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
3483 sscanf(value, "%u", &count);
3486 info->compatible = calloc(count + 1, sizeof(*info->compatible));
3487 if (!info->compatible)
3490 for (i = 0; i < count; i++) {
3491 value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
3497 info->compatible[i] = value;
3504 free(info->compatible[i]);
3506 free(info->compatible);
3509 #warning "Missing implementation of drmParsePlatformDeviceInfo"
3514 static int drmProcessPlatformDevice(drmDevicePtr *device,
3515 const char *node, int node_type,
3516 int maj, int min, bool fetch_deviceinfo,
3523 dev = drmDeviceAlloc(node_type, node, sizeof(drmPlatformBusInfo),
3524 sizeof(drmPlatformDeviceInfo), &ptr);
3528 dev->bustype = DRM_BUS_PLATFORM;
3530 dev->businfo.platform = (drmPlatformBusInfoPtr)ptr;
3532 ret = drmParsePlatformBusInfo(maj, min, dev->businfo.platform);
3536 if (fetch_deviceinfo) {
3537 ptr += sizeof(drmPlatformBusInfo);
3538 dev->deviceinfo.platform = (drmPlatformDeviceInfoPtr)ptr;
3540 ret = drmParsePlatformDeviceInfo(maj, min, dev->deviceinfo.platform);
3554 static int drmParseHost1xBusInfo(int maj, int min, drmHost1xBusInfoPtr info)
3557 char path[PATH_MAX + 1], *name;
3559 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3561 name = sysfs_uevent_get(path, "OF_FULLNAME");
3565 strncpy(info->fullname, name, DRM_HOST1X_DEVICE_NAME_LEN);
3566 info->fullname[DRM_HOST1X_DEVICE_NAME_LEN - 1] = '\0';
3571 #warning "Missing implementation of drmParseHost1xBusInfo"
3576 static int drmParseHost1xDeviceInfo(int maj, int min,
3577 drmHost1xDeviceInfoPtr info)
3580 char path[PATH_MAX + 1], *value;
3581 unsigned int count, i;
3584 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3586 value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
3590 sscanf(value, "%u", &count);
3593 info->compatible = calloc(count + 1, sizeof(*info->compatible));
3594 if (!info->compatible)
3597 for (i = 0; i < count; i++) {
3598 value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
3604 info->compatible[i] = value;
3611 free(info->compatible[i]);
3613 free(info->compatible);
3616 #warning "Missing implementation of drmParseHost1xDeviceInfo"
3621 static int drmProcessHost1xDevice(drmDevicePtr *device,
3622 const char *node, int node_type,
3623 int maj, int min, bool fetch_deviceinfo,
3630 dev = drmDeviceAlloc(node_type, node, sizeof(drmHost1xBusInfo),
3631 sizeof(drmHost1xDeviceInfo), &ptr);
3635 dev->bustype = DRM_BUS_HOST1X;
3637 dev->businfo.host1x = (drmHost1xBusInfoPtr)ptr;
3639 ret = drmParseHost1xBusInfo(maj, min, dev->businfo.host1x);
3643 if (fetch_deviceinfo) {
3644 ptr += sizeof(drmHost1xBusInfo);
3645 dev->deviceinfo.host1x = (drmHost1xDeviceInfoPtr)ptr;
3647 ret = drmParseHost1xDeviceInfo(maj, min, dev->deviceinfo.host1x);
3661 /* Consider devices located on the same bus as duplicate and fold the respective
3662 * entries into a single one.
3664 * Note: this leaves "gaps" in the array, while preserving the length.
3666 static void drmFoldDuplicatedDevices(drmDevicePtr local_devices[], int count)
3668 int node_type, i, j;
3670 for (i = 0; i < count; i++) {
3671 for (j = i + 1; j < count; j++) {
3672 if (drmCompareDevices(local_devices[i], local_devices[j])) {
3673 local_devices[i]->available_nodes |= local_devices[j]->available_nodes;
3674 node_type = log2(local_devices[j]->available_nodes);
3675 memcpy(local_devices[i]->nodes[node_type],
3676 local_devices[j]->nodes[node_type], drmGetMaxNodeName());
3677 drmFreeDevice(&local_devices[j]);
3683 /* Check that the given flags are valid returning 0 on success */
3685 drm_device_validate_flags(uint32_t flags)
3687 return (flags & ~DRM_DEVICE_GET_PCI_REVISION);
3691 * Get information about the opened drm device
3693 * \param fd file descriptor of the drm device
3694 * \param flags feature/behaviour bitmask
3695 * \param device the address of a drmDevicePtr where the information
3696 * will be allocated in stored
3698 * \return zero on success, negative error code otherwise.
3700 * \note Unlike drmGetDevice it does not retrieve the pci device revision field
3701 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
3703 int drmGetDevice2(int fd, uint32_t flags, drmDevicePtr *device)
3707 * DRI device nodes on OpenBSD are not in their own directory, they reside
3708 * in /dev along with a large number of statically generated /dev nodes.
3709 * Avoid stat'ing all of /dev needlessly by implementing this custom path.
3713 char node[PATH_MAX + 1];
3714 const char *dev_name;
3715 int node_type, subsystem_type;
3716 int maj, min, n, ret, base;
3718 if (fd == -1 || device == NULL)
3721 if (fstat(fd, &sbuf))
3724 maj = major(sbuf.st_rdev);
3725 min = minor(sbuf.st_rdev);
3727 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3730 node_type = drmGetMinorType(min);
3731 if (node_type == -1)
3734 switch (node_type) {
3735 case DRM_NODE_PRIMARY:
3736 dev_name = DRM_DEV_NAME;
3738 case DRM_NODE_CONTROL:
3739 dev_name = DRM_CONTROL_DEV_NAME;
3741 case DRM_NODE_RENDER:
3742 dev_name = DRM_RENDER_DEV_NAME;
3748 base = drmGetMinorBase(node_type);
3752 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min - base);
3753 if (n == -1 || n >= PATH_MAX)
3755 if (stat(node, &sbuf))
3758 subsystem_type = drmParseSubsystemType(maj, min);
3759 if (subsystem_type != DRM_BUS_PCI)
3762 ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
3770 drmDevicePtr *local_devices;
3773 struct dirent *dent;
3775 char node[PATH_MAX + 1];
3776 int node_type, subsystem_type;
3778 int ret, i, node_count;
3782 if (drm_device_validate_flags(flags))
3785 if (fd == -1 || device == NULL)
3788 if (fstat(fd, &sbuf))
3791 find_rdev = sbuf.st_rdev;
3792 maj = major(sbuf.st_rdev);
3793 min = minor(sbuf.st_rdev);
3795 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3798 subsystem_type = drmParseSubsystemType(maj, min);
3800 local_devices = calloc(max_count, sizeof(drmDevicePtr));
3801 if (local_devices == NULL)
3804 sysdir = opendir(DRM_DIR_NAME);
3811 while ((dent = readdir(sysdir))) {
3812 node_type = drmGetNodeType(dent->d_name);
3816 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, dent->d_name);
3817 if (stat(node, &sbuf))
3820 maj = major(sbuf.st_rdev);
3821 min = minor(sbuf.st_rdev);
3823 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3826 if (drmParseSubsystemType(maj, min) != subsystem_type)
3829 switch (subsystem_type) {
3831 ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
3838 ret = drmProcessUsbDevice(&d, node, node_type, maj, min, true, flags);
3844 case DRM_BUS_PLATFORM:
3845 ret = drmProcessPlatformDevice(&d, node, node_type, maj, min, true, flags);
3851 case DRM_BUS_HOST1X:
3852 ret = drmProcessHost1xDevice(&d, node, node_type, maj, min, true, flags);
3862 if (i >= max_count) {
3866 temp = realloc(local_devices, max_count * sizeof(drmDevicePtr));
3869 local_devices = temp;
3872 /* store target at local_devices[0] for ease to use below */
3873 if (find_rdev == sbuf.st_rdev && i) {
3874 local_devices[i] = local_devices[0];
3875 local_devices[0] = d;
3878 local_devices[i] = d;
3883 drmFoldDuplicatedDevices(local_devices, node_count);
3885 *device = local_devices[0];
3886 drmFreeDevices(&local_devices[1], node_count - 1);
3889 free(local_devices);
3890 if (*device == NULL)
3895 drmFreeDevices(local_devices, i);
3899 free(local_devices);
3905 * Get information about the opened drm device
3907 * \param fd file descriptor of the drm device
3908 * \param device the address of a drmDevicePtr where the information
3909 * will be allocated in stored
3911 * \return zero on success, negative error code otherwise.
3913 int drmGetDevice(int fd, drmDevicePtr *device)
3915 return drmGetDevice2(fd, DRM_DEVICE_GET_PCI_REVISION, device);
3919 * Get drm devices on the system
3921 * \param flags feature/behaviour bitmask
3922 * \param devices the array of devices with drmDevicePtr elements
3923 * can be NULL to get the device number first
3924 * \param max_devices the maximum number of devices for the array
3926 * \return on error - negative error code,
3927 * if devices is NULL - total number of devices available on the system,
3928 * alternatively the number of devices stored in devices[], which is
3929 * capped by the max_devices.
3931 * \note Unlike drmGetDevices it does not retrieve the pci device revision field
3932 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
3934 int drmGetDevices2(uint32_t flags, drmDevicePtr devices[], int max_devices)
3936 drmDevicePtr *local_devices;
3937 drmDevicePtr device;
3939 struct dirent *dent;
3941 char node[PATH_MAX + 1];
3942 int node_type, subsystem_type;
3944 int ret, i, node_count, device_count;
3947 if (drm_device_validate_flags(flags))
3950 local_devices = calloc(max_count, sizeof(drmDevicePtr));
3951 if (local_devices == NULL)
3954 sysdir = opendir(DRM_DIR_NAME);
3961 while ((dent = readdir(sysdir))) {
3962 node_type = drmGetNodeType(dent->d_name);
3966 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, dent->d_name);
3967 if (stat(node, &sbuf))
3970 maj = major(sbuf.st_rdev);
3971 min = minor(sbuf.st_rdev);
3973 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3976 subsystem_type = drmParseSubsystemType(maj, min);
3978 if (subsystem_type < 0)
3981 switch (subsystem_type) {
3983 ret = drmProcessPciDevice(&device, node, node_type,
3984 maj, min, devices != NULL, flags);
3991 ret = drmProcessUsbDevice(&device, node, node_type, maj, min,
3992 devices != NULL, flags);
3998 case DRM_BUS_PLATFORM:
3999 ret = drmProcessPlatformDevice(&device, node, node_type, maj, min,
4000 devices != NULL, flags);
4006 case DRM_BUS_HOST1X:
4007 ret = drmProcessHost1xDevice(&device, node, node_type, maj, min,
4008 devices != NULL, flags);
4018 if (i >= max_count) {
4022 temp = realloc(local_devices, max_count * sizeof(drmDevicePtr));
4025 local_devices = temp;
4028 local_devices[i] = device;
4033 drmFoldDuplicatedDevices(local_devices, node_count);
4036 for (i = 0; i < node_count; i++) {
4037 if (!local_devices[i])
4040 if ((devices != NULL) && (device_count < max_devices))
4041 devices[device_count] = local_devices[i];
4043 drmFreeDevice(&local_devices[i]);
4049 free(local_devices);
4050 return device_count;
4053 drmFreeDevices(local_devices, i);
4057 free(local_devices);
4062 * Get drm devices on the system
4064 * \param devices the array of devices with drmDevicePtr elements
4065 * can be NULL to get the device number first
4066 * \param max_devices the maximum number of devices for the array
4068 * \return on error - negative error code,
4069 * if devices is NULL - total number of devices available on the system,
4070 * alternatively the number of devices stored in devices[], which is
4071 * capped by the max_devices.
4073 int drmGetDevices(drmDevicePtr devices[], int max_devices)
4075 return drmGetDevices2(DRM_DEVICE_GET_PCI_REVISION, devices, max_devices);
4078 char *drmGetDeviceNameFromFd2(int fd)
4082 char path[PATH_MAX + 1], *value;
4083 unsigned int maj, min;
4085 if (fstat(fd, &sbuf))
4088 maj = major(sbuf.st_rdev);
4089 min = minor(sbuf.st_rdev);
4091 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
4094 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d", maj, min);
4096 value = sysfs_uevent_get(path, "DEVNAME");
4100 snprintf(path, sizeof(path), "/dev/%s", value);
4103 return strdup(path);
4106 char node[PATH_MAX + 1];
4107 const char *dev_name;
4109 int maj, min, n, base;
4111 if (fstat(fd, &sbuf))
4114 maj = major(sbuf.st_rdev);
4115 min = minor(sbuf.st_rdev);
4117 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
4120 node_type = drmGetMinorType(min);
4121 if (node_type == -1)
4124 switch (node_type) {
4125 case DRM_NODE_PRIMARY:
4126 dev_name = DRM_DEV_NAME;
4128 case DRM_NODE_CONTROL:
4129 dev_name = DRM_CONTROL_DEV_NAME;
4131 case DRM_NODE_RENDER:
4132 dev_name = DRM_RENDER_DEV_NAME;
4138 base = drmGetMinorBase(node_type);
4142 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min - base);
4143 if (n == -1 || n >= PATH_MAX)
4146 return strdup(node);