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))
999 u.unique[u.unique_len] = '\0';
1006 * Set the bus ID of the device.
1008 * \param fd file descriptor.
1009 * \param busid bus ID string.
1011 * \return zero on success, negative on failure.
1014 * This function is a wrapper around the DRM_IOCTL_SET_UNIQUE ioctl, passing
1015 * the arguments in a drm_unique structure.
1017 int drmSetBusid(int fd, const char *busid)
1022 u.unique = (char *)busid;
1023 u.unique_len = strlen(busid);
1025 if (drmIoctl(fd, DRM_IOCTL_SET_UNIQUE, &u)) {
1031 int drmGetMagic(int fd, drm_magic_t * magic)
1038 if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
1040 *magic = auth.magic;
1044 int drmAuthMagic(int fd, drm_magic_t magic)
1050 if (drmIoctl(fd, DRM_IOCTL_AUTH_MAGIC, &auth))
1056 * Specifies a range of memory that is available for mapping by a
1059 * \param fd file descriptor.
1060 * \param offset usually the physical address. The actual meaning depends of
1061 * the \p type parameter. See below.
1062 * \param size of the memory in bytes.
1063 * \param type type of the memory to be mapped.
1064 * \param flags combination of several flags to modify the function actions.
1065 * \param handle will be set to a value that may be used as the offset
1066 * parameter for mmap().
1068 * \return zero on success or a negative value on error.
1070 * \par Mapping the frame buffer
1071 * For the frame buffer
1072 * - \p offset will be the physical address of the start of the frame buffer,
1073 * - \p size will be the size of the frame buffer in bytes, and
1074 * - \p type will be DRM_FRAME_BUFFER.
1077 * The area mapped will be uncached. If MTRR support is available in the
1078 * kernel, the frame buffer area will be set to write combining.
1080 * \par Mapping the MMIO register area
1081 * For the MMIO register area,
1082 * - \p offset will be the physical address of the start of the register area,
1083 * - \p size will be the size of the register area bytes, and
1084 * - \p type will be DRM_REGISTERS.
1086 * The area mapped will be uncached.
1088 * \par Mapping the SAREA
1090 * - \p offset will be ignored and should be set to zero,
1091 * - \p size will be the desired size of the SAREA in bytes,
1092 * - \p type will be DRM_SHM.
1095 * A shared memory area of the requested size will be created and locked in
1096 * kernel memory. This area may be mapped into client-space by using the handle
1099 * \note May only be called by root.
1102 * This function is a wrapper around the DRM_IOCTL_ADD_MAP ioctl, passing
1103 * the arguments in a drm_map structure.
1105 int drmAddMap(int fd, drm_handle_t offset, drmSize size, drmMapType type,
1106 drmMapFlags flags, drm_handle_t *handle)
1111 map.offset = offset;
1115 if (drmIoctl(fd, DRM_IOCTL_ADD_MAP, &map))
1118 *handle = (drm_handle_t)(uintptr_t)map.handle;
1122 int drmRmMap(int fd, drm_handle_t handle)
1127 map.handle = (void *)(uintptr_t)handle;
1129 if(drmIoctl(fd, DRM_IOCTL_RM_MAP, &map))
1135 * Make buffers available for DMA transfers.
1137 * \param fd file descriptor.
1138 * \param count number of buffers.
1139 * \param size size of each buffer.
1140 * \param flags buffer allocation flags.
1141 * \param agp_offset offset in the AGP aperture
1143 * \return number of buffers allocated, negative on error.
1146 * This function is a wrapper around DRM_IOCTL_ADD_BUFS ioctl.
1150 int drmAddBufs(int fd, int count, int size, drmBufDescFlags flags,
1153 drm_buf_desc_t request;
1156 request.count = count;
1157 request.size = size;
1158 request.flags = flags;
1159 request.agp_start = agp_offset;
1161 if (drmIoctl(fd, DRM_IOCTL_ADD_BUFS, &request))
1163 return request.count;
1166 int drmMarkBufs(int fd, double low, double high)
1168 drm_buf_info_t info;
1173 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1179 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1182 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1183 int retval = -errno;
1188 for (i = 0; i < info.count; i++) {
1189 info.list[i].low_mark = low * info.list[i].count;
1190 info.list[i].high_mark = high * info.list[i].count;
1191 if (drmIoctl(fd, DRM_IOCTL_MARK_BUFS, &info.list[i])) {
1192 int retval = -errno;
1205 * \param fd file descriptor.
1206 * \param count number of buffers to free.
1207 * \param list list of buffers to be freed.
1209 * \return zero on success, or a negative value on failure.
1211 * \note This function is primarily used for debugging.
1214 * This function is a wrapper around the DRM_IOCTL_FREE_BUFS ioctl, passing
1215 * the arguments in a drm_buf_free structure.
1217 int drmFreeBufs(int fd, int count, int *list)
1219 drm_buf_free_t request;
1222 request.count = count;
1223 request.list = list;
1224 if (drmIoctl(fd, DRM_IOCTL_FREE_BUFS, &request))
1233 * \param fd file descriptor.
1236 * This function closes the file descriptor.
1238 int drmClose(int fd)
1240 unsigned long key = drmGetKeyFromFd(fd);
1241 drmHashEntry *entry = drmGetEntry(fd);
1243 drmHashDestroy(entry->tagTable);
1246 entry->tagTable = NULL;
1248 drmHashDelete(drmHashTable, key);
1256 * Map a region of memory.
1258 * \param fd file descriptor.
1259 * \param handle handle returned by drmAddMap().
1260 * \param size size in bytes. Must match the size used by drmAddMap().
1261 * \param address will contain the user-space virtual address where the mapping
1264 * \return zero on success, or a negative value on failure.
1267 * This function is a wrapper for mmap().
1269 int drmMap(int fd, drm_handle_t handle, drmSize size, drmAddressPtr address)
1271 static unsigned long pagesize_mask = 0;
1277 pagesize_mask = getpagesize() - 1;
1279 size = (size + pagesize_mask) & ~pagesize_mask;
1281 *address = drm_mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1282 if (*address == MAP_FAILED)
1289 * Unmap mappings obtained with drmMap().
1291 * \param address address as given by drmMap().
1292 * \param size size in bytes. Must match the size used by drmMap().
1294 * \return zero on success, or a negative value on failure.
1297 * This function is a wrapper for munmap().
1299 int drmUnmap(drmAddress address, drmSize size)
1301 return drm_munmap(address, size);
1304 drmBufInfoPtr drmGetBufInfo(int fd)
1306 drm_buf_info_t info;
1307 drmBufInfoPtr retval;
1312 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1316 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1319 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1324 retval = drmMalloc(sizeof(*retval));
1325 retval->count = info.count;
1326 retval->list = drmMalloc(info.count * sizeof(*retval->list));
1327 for (i = 0; i < info.count; i++) {
1328 retval->list[i].count = info.list[i].count;
1329 retval->list[i].size = info.list[i].size;
1330 retval->list[i].low_mark = info.list[i].low_mark;
1331 retval->list[i].high_mark = info.list[i].high_mark;
1340 * Map all DMA buffers into client-virtual space.
1342 * \param fd file descriptor.
1344 * \return a pointer to a ::drmBufMap structure.
1346 * \note The client may not use these buffers until obtaining buffer indices
1350 * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1351 * information about the buffers in a drm_buf_map structure into the
1352 * client-visible data structures.
1354 drmBufMapPtr drmMapBufs(int fd)
1357 drmBufMapPtr retval;
1361 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1367 if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1370 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1375 retval = drmMalloc(sizeof(*retval));
1376 retval->count = bufs.count;
1377 retval->list = drmMalloc(bufs.count * sizeof(*retval->list));
1378 for (i = 0; i < bufs.count; i++) {
1379 retval->list[i].idx = bufs.list[i].idx;
1380 retval->list[i].total = bufs.list[i].total;
1381 retval->list[i].used = 0;
1382 retval->list[i].address = bufs.list[i].address;
1391 * Unmap buffers allocated with drmMapBufs().
1393 * \return zero on success, or negative value on failure.
1396 * Calls munmap() for every buffer stored in \p bufs and frees the
1397 * memory allocated by drmMapBufs().
1399 int drmUnmapBufs(drmBufMapPtr bufs)
1403 for (i = 0; i < bufs->count; i++) {
1404 drm_munmap(bufs->list[i].address, bufs->list[i].total);
1407 drmFree(bufs->list);
1413 #define DRM_DMA_RETRY 16
1416 * Reserve DMA buffers.
1418 * \param fd file descriptor.
1421 * \return zero on success, or a negative value on failure.
1424 * Assemble the arguments into a drm_dma structure and keeps issuing the
1425 * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1427 int drmDMA(int fd, drmDMAReqPtr request)
1432 dma.context = request->context;
1433 dma.send_count = request->send_count;
1434 dma.send_indices = request->send_list;
1435 dma.send_sizes = request->send_sizes;
1436 dma.flags = request->flags;
1437 dma.request_count = request->request_count;
1438 dma.request_size = request->request_size;
1439 dma.request_indices = request->request_list;
1440 dma.request_sizes = request->request_sizes;
1441 dma.granted_count = 0;
1444 ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1445 } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1448 request->granted_count = dma.granted_count;
1457 * Obtain heavyweight hardware lock.
1459 * \param fd file descriptor.
1460 * \param context context.
1461 * \param flags flags that determine the sate of the hardware when the function
1464 * \return always zero.
1467 * This function translates the arguments into a drm_lock structure and issue
1468 * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1470 int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
1475 lock.context = context;
1477 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
1478 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
1479 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
1480 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
1481 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
1482 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
1484 while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
1490 * Release the hardware lock.
1492 * \param fd file descriptor.
1493 * \param context context.
1495 * \return zero on success, or a negative value on failure.
1498 * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
1499 * argument in a drm_lock structure.
1501 int drmUnlock(int fd, drm_context_t context)
1506 lock.context = context;
1507 return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
1510 drm_context_t *drmGetReservedContextList(int fd, int *count)
1514 drm_context_t * retval;
1518 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1524 if (!(list = drmMalloc(res.count * sizeof(*list))))
1526 if (!(retval = drmMalloc(res.count * sizeof(*retval)))) {
1531 res.contexts = list;
1532 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1535 for (i = 0; i < res.count; i++)
1536 retval[i] = list[i].handle;
1543 void drmFreeReservedContextList(drm_context_t *pt)
1551 * Used by the X server during GLXContext initialization. This causes
1552 * per-context kernel-level resources to be allocated.
1554 * \param fd file descriptor.
1555 * \param handle is set on success. To be used by the client when requesting DMA
1556 * dispatch with drmDMA().
1558 * \return zero on success, or a negative value on failure.
1560 * \note May only be called by root.
1563 * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
1564 * argument in a drm_ctx structure.
1566 int drmCreateContext(int fd, drm_context_t *handle)
1571 if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
1573 *handle = ctx.handle;
1577 int drmSwitchToContext(int fd, drm_context_t context)
1582 ctx.handle = context;
1583 if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
1588 int drmSetContextFlags(int fd, drm_context_t context, drm_context_tFlags flags)
1593 * Context preserving means that no context switches are done between DMA
1594 * buffers from one context and the next. This is suitable for use in the
1595 * X server (which promises to maintain hardware context), or in the
1596 * client-side library when buffers are swapped on behalf of two threads.
1599 ctx.handle = context;
1600 if (flags & DRM_CONTEXT_PRESERVED)
1601 ctx.flags |= _DRM_CONTEXT_PRESERVED;
1602 if (flags & DRM_CONTEXT_2DONLY)
1603 ctx.flags |= _DRM_CONTEXT_2DONLY;
1604 if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
1609 int drmGetContextFlags(int fd, drm_context_t context,
1610 drm_context_tFlagsPtr flags)
1615 ctx.handle = context;
1616 if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
1619 if (ctx.flags & _DRM_CONTEXT_PRESERVED)
1620 *flags |= DRM_CONTEXT_PRESERVED;
1621 if (ctx.flags & _DRM_CONTEXT_2DONLY)
1622 *flags |= DRM_CONTEXT_2DONLY;
1629 * Free any kernel-level resources allocated with drmCreateContext() associated
1632 * \param fd file descriptor.
1633 * \param handle handle given by drmCreateContext().
1635 * \return zero on success, or a negative value on failure.
1637 * \note May only be called by root.
1640 * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
1641 * argument in a drm_ctx structure.
1643 int drmDestroyContext(int fd, drm_context_t handle)
1648 ctx.handle = handle;
1649 if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
1654 int drmCreateDrawable(int fd, drm_drawable_t *handle)
1659 if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
1661 *handle = draw.handle;
1665 int drmDestroyDrawable(int fd, drm_drawable_t handle)
1670 draw.handle = handle;
1671 if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
1676 int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
1677 drm_drawable_info_type_t type, unsigned int num,
1680 drm_update_draw_t update;
1683 update.handle = handle;
1686 update.data = (unsigned long long)(unsigned long)data;
1688 if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
1695 * Acquire the AGP device.
1697 * Must be called before any of the other AGP related calls.
1699 * \param fd file descriptor.
1701 * \return zero on success, or a negative value on failure.
1704 * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
1706 int drmAgpAcquire(int fd)
1708 if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
1715 * Release the AGP device.
1717 * \param fd file descriptor.
1719 * \return zero on success, or a negative value on failure.
1722 * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
1724 int drmAgpRelease(int fd)
1726 if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
1735 * \param fd file descriptor.
1736 * \param mode AGP mode.
1738 * \return zero on success, or a negative value on failure.
1741 * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
1742 * argument in a drm_agp_mode structure.
1744 int drmAgpEnable(int fd, unsigned long mode)
1750 if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
1757 * Allocate a chunk of AGP memory.
1759 * \param fd file descriptor.
1760 * \param size requested memory size in bytes. Will be rounded to page boundary.
1761 * \param type type of memory to allocate.
1762 * \param address if not zero, will be set to the physical address of the
1764 * \param handle on success will be set to a handle of the allocated memory.
1766 * \return zero on success, or a negative value on failure.
1769 * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
1770 * arguments in a drm_agp_buffer structure.
1772 int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
1773 unsigned long *address, drm_handle_t *handle)
1778 *handle = DRM_AGP_NO_HANDLE;
1781 if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
1784 *address = b.physical;
1791 * Free a chunk of AGP memory.
1793 * \param fd file descriptor.
1794 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1796 * \return zero on success, or a negative value on failure.
1799 * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
1800 * argument in a drm_agp_buffer structure.
1802 int drmAgpFree(int fd, drm_handle_t handle)
1808 if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
1815 * Bind a chunk of AGP memory.
1817 * \param fd file descriptor.
1818 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1819 * \param offset offset in bytes. It will round to page boundary.
1821 * \return zero on success, or a negative value on failure.
1824 * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
1825 * argument in a drm_agp_binding structure.
1827 int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
1829 drm_agp_binding_t b;
1834 if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
1841 * Unbind a chunk of AGP memory.
1843 * \param fd file descriptor.
1844 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1846 * \return zero on success, or a negative value on failure.
1849 * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
1850 * the argument in a drm_agp_binding structure.
1852 int drmAgpUnbind(int fd, drm_handle_t handle)
1854 drm_agp_binding_t b;
1858 if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
1865 * Get AGP driver major version number.
1867 * \param fd file descriptor.
1869 * \return major version number on success, or a negative value on failure..
1872 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1873 * necessary information in a drm_agp_info structure.
1875 int drmAgpVersionMajor(int fd)
1881 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1883 return i.agp_version_major;
1888 * Get AGP driver minor version number.
1890 * \param fd file descriptor.
1892 * \return minor version number on success, or a negative value on failure.
1895 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1896 * necessary information in a drm_agp_info structure.
1898 int drmAgpVersionMinor(int fd)
1904 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1906 return i.agp_version_minor;
1913 * \param fd file descriptor.
1915 * \return mode on success, or zero on failure.
1918 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1919 * necessary information in a drm_agp_info structure.
1921 unsigned long drmAgpGetMode(int fd)
1927 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1934 * Get AGP aperture base.
1936 * \param fd file descriptor.
1938 * \return aperture base on success, zero on failure.
1941 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1942 * necessary information in a drm_agp_info structure.
1944 unsigned long drmAgpBase(int fd)
1950 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1952 return i.aperture_base;
1957 * Get AGP aperture size.
1959 * \param fd file descriptor.
1961 * \return aperture size on success, zero on failure.
1964 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1965 * necessary information in a drm_agp_info structure.
1967 unsigned long drmAgpSize(int fd)
1973 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1975 return i.aperture_size;
1980 * Get used AGP memory.
1982 * \param fd file descriptor.
1984 * \return memory used on success, or zero on failure.
1987 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1988 * necessary information in a drm_agp_info structure.
1990 unsigned long drmAgpMemoryUsed(int fd)
1996 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1998 return i.memory_used;
2003 * Get available AGP memory.
2005 * \param fd file descriptor.
2007 * \return memory available on success, or zero on failure.
2010 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2011 * necessary information in a drm_agp_info structure.
2013 unsigned long drmAgpMemoryAvail(int fd)
2019 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2021 return i.memory_allowed;
2026 * Get hardware vendor ID.
2028 * \param fd file descriptor.
2030 * \return vendor ID on success, or zero on failure.
2033 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2034 * necessary information in a drm_agp_info structure.
2036 unsigned int drmAgpVendorId(int fd)
2042 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2049 * Get hardware device ID.
2051 * \param fd file descriptor.
2053 * \return zero on success, or zero on failure.
2056 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2057 * necessary information in a drm_agp_info structure.
2059 unsigned int drmAgpDeviceId(int fd)
2065 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2070 int drmScatterGatherAlloc(int fd, unsigned long size, drm_handle_t *handle)
2072 drm_scatter_gather_t sg;
2078 if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
2080 *handle = sg.handle;
2084 int drmScatterGatherFree(int fd, drm_handle_t handle)
2086 drm_scatter_gather_t sg;
2090 if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
2098 * \param fd file descriptor.
2099 * \param vbl pointer to a drmVBlank structure.
2101 * \return zero on success, or a negative value on failure.
2104 * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
2106 int drmWaitVBlank(int fd, drmVBlankPtr vbl)
2108 struct timespec timeout, cur;
2111 ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2113 fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
2119 ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
2120 vbl->request.type &= ~DRM_VBLANK_RELATIVE;
2121 if (ret && errno == EINTR) {
2122 clock_gettime(CLOCK_MONOTONIC, &cur);
2123 /* Timeout after 1s */
2124 if (cur.tv_sec > timeout.tv_sec + 1 ||
2125 (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
2132 } while (ret && errno == EINTR);
2138 int drmError(int err, const char *label)
2141 case DRM_ERR_NO_DEVICE:
2142 fprintf(stderr, "%s: no device\n", label);
2144 case DRM_ERR_NO_ACCESS:
2145 fprintf(stderr, "%s: no access\n", label);
2147 case DRM_ERR_NOT_ROOT:
2148 fprintf(stderr, "%s: not root\n", label);
2150 case DRM_ERR_INVALID:
2151 fprintf(stderr, "%s: invalid args\n", label);
2156 fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2164 * Install IRQ handler.
2166 * \param fd file descriptor.
2167 * \param irq IRQ number.
2169 * \return zero on success, or a negative value on failure.
2172 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2173 * argument in a drm_control structure.
2175 int drmCtlInstHandler(int fd, int irq)
2180 ctl.func = DRM_INST_HANDLER;
2182 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2189 * Uninstall IRQ handler.
2191 * \param fd file descriptor.
2193 * \return zero on success, or a negative value on failure.
2196 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2197 * argument in a drm_control structure.
2199 int drmCtlUninstHandler(int fd)
2204 ctl.func = DRM_UNINST_HANDLER;
2206 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2211 int drmFinish(int fd, int context, drmLockFlags flags)
2216 lock.context = context;
2217 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
2218 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
2219 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
2220 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
2221 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2222 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2223 if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2229 * Get IRQ from bus ID.
2231 * \param fd file descriptor.
2232 * \param busnum bus number.
2233 * \param devnum device number.
2234 * \param funcnum function number.
2236 * \return IRQ number on success, or a negative value on failure.
2239 * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2240 * arguments in a drm_irq_busid structure.
2242 int drmGetInterruptFromBusID(int fd, int busnum, int devnum, int funcnum)
2249 p.funcnum = funcnum;
2250 if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2255 int drmAddContextTag(int fd, drm_context_t context, void *tag)
2257 drmHashEntry *entry = drmGetEntry(fd);
2259 if (drmHashInsert(entry->tagTable, context, tag)) {
2260 drmHashDelete(entry->tagTable, context);
2261 drmHashInsert(entry->tagTable, context, tag);
2266 int drmDelContextTag(int fd, drm_context_t context)
2268 drmHashEntry *entry = drmGetEntry(fd);
2270 return drmHashDelete(entry->tagTable, context);
2273 void *drmGetContextTag(int fd, drm_context_t context)
2275 drmHashEntry *entry = drmGetEntry(fd);
2278 if (drmHashLookup(entry->tagTable, context, &value))
2284 int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2285 drm_handle_t handle)
2287 drm_ctx_priv_map_t map;
2290 map.ctx_id = ctx_id;
2291 map.handle = (void *)(uintptr_t)handle;
2293 if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2298 int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2299 drm_handle_t *handle)
2301 drm_ctx_priv_map_t map;
2304 map.ctx_id = ctx_id;
2306 if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2309 *handle = (drm_handle_t)(uintptr_t)map.handle;
2314 int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2315 drmMapType *type, drmMapFlags *flags, drm_handle_t *handle,
2322 if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2324 *offset = map.offset;
2328 *handle = (unsigned long)map.handle;
2333 int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2334 unsigned long *magic, unsigned long *iocs)
2336 drm_client_t client;
2340 if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2342 *auth = client.auth;
2345 *magic = client.magic;
2346 *iocs = client.iocs;
2350 int drmGetStats(int fd, drmStatsT *stats)
2356 if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2360 memset(stats, 0, sizeof(*stats));
2361 if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2365 stats->data[i].long_format = "%-20.20s"; \
2366 stats->data[i].rate_format = "%8.8s"; \
2367 stats->data[i].isvalue = 1; \
2368 stats->data[i].verbose = 0
2371 stats->data[i].long_format = "%-20.20s"; \
2372 stats->data[i].rate_format = "%5.5s"; \
2373 stats->data[i].isvalue = 0; \
2374 stats->data[i].mult_names = "kgm"; \
2375 stats->data[i].mult = 1000; \
2376 stats->data[i].verbose = 0
2379 stats->data[i].long_format = "%-20.20s"; \
2380 stats->data[i].rate_format = "%5.5s"; \
2381 stats->data[i].isvalue = 0; \
2382 stats->data[i].mult_names = "KGM"; \
2383 stats->data[i].mult = 1024; \
2384 stats->data[i].verbose = 0
2387 stats->count = s.count;
2388 for (i = 0; i < s.count; i++) {
2389 stats->data[i].value = s.data[i].value;
2390 switch (s.data[i].type) {
2391 case _DRM_STAT_LOCK:
2392 stats->data[i].long_name = "Lock";
2393 stats->data[i].rate_name = "Lock";
2396 case _DRM_STAT_OPENS:
2397 stats->data[i].long_name = "Opens";
2398 stats->data[i].rate_name = "O";
2400 stats->data[i].verbose = 1;
2402 case _DRM_STAT_CLOSES:
2403 stats->data[i].long_name = "Closes";
2404 stats->data[i].rate_name = "Lock";
2406 stats->data[i].verbose = 1;
2408 case _DRM_STAT_IOCTLS:
2409 stats->data[i].long_name = "Ioctls";
2410 stats->data[i].rate_name = "Ioc/s";
2413 case _DRM_STAT_LOCKS:
2414 stats->data[i].long_name = "Locks";
2415 stats->data[i].rate_name = "Lck/s";
2418 case _DRM_STAT_UNLOCKS:
2419 stats->data[i].long_name = "Unlocks";
2420 stats->data[i].rate_name = "Unl/s";
2424 stats->data[i].long_name = "IRQs";
2425 stats->data[i].rate_name = "IRQ/s";
2428 case _DRM_STAT_PRIMARY:
2429 stats->data[i].long_name = "Primary Bytes";
2430 stats->data[i].rate_name = "PB/s";
2433 case _DRM_STAT_SECONDARY:
2434 stats->data[i].long_name = "Secondary Bytes";
2435 stats->data[i].rate_name = "SB/s";
2439 stats->data[i].long_name = "DMA";
2440 stats->data[i].rate_name = "DMA/s";
2443 case _DRM_STAT_SPECIAL:
2444 stats->data[i].long_name = "Special DMA";
2445 stats->data[i].rate_name = "dma/s";
2448 case _DRM_STAT_MISSED:
2449 stats->data[i].long_name = "Miss";
2450 stats->data[i].rate_name = "Ms/s";
2453 case _DRM_STAT_VALUE:
2454 stats->data[i].long_name = "Value";
2455 stats->data[i].rate_name = "Value";
2458 case _DRM_STAT_BYTE:
2459 stats->data[i].long_name = "Bytes";
2460 stats->data[i].rate_name = "B/s";
2463 case _DRM_STAT_COUNT:
2465 stats->data[i].long_name = "Count";
2466 stats->data[i].rate_name = "Cnt/s";
2475 * Issue a set-version ioctl.
2477 * \param fd file descriptor.
2478 * \param drmCommandIndex command index
2479 * \param data source pointer of the data to be read and written.
2480 * \param size size of the data to be read and written.
2482 * \return zero on success, or a negative value on failure.
2485 * It issues a read-write ioctl given by
2486 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2488 int drmSetInterfaceVersion(int fd, drmSetVersion *version)
2491 drm_set_version_t sv;
2494 sv.drm_di_major = version->drm_di_major;
2495 sv.drm_di_minor = version->drm_di_minor;
2496 sv.drm_dd_major = version->drm_dd_major;
2497 sv.drm_dd_minor = version->drm_dd_minor;
2499 if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
2503 version->drm_di_major = sv.drm_di_major;
2504 version->drm_di_minor = sv.drm_di_minor;
2505 version->drm_dd_major = sv.drm_dd_major;
2506 version->drm_dd_minor = sv.drm_dd_minor;
2512 * Send a device-specific command.
2514 * \param fd file descriptor.
2515 * \param drmCommandIndex command index
2517 * \return zero on success, or a negative value on failure.
2520 * It issues a ioctl given by
2521 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2523 int drmCommandNone(int fd, unsigned long drmCommandIndex)
2525 unsigned long request;
2527 request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
2529 if (drmIoctl(fd, request, NULL)) {
2537 * Send a device-specific read command.
2539 * \param fd file descriptor.
2540 * \param drmCommandIndex command index
2541 * \param data destination pointer of the data to be read.
2542 * \param size size of the data to be read.
2544 * \return zero on success, or a negative value on failure.
2547 * It issues a read ioctl given by
2548 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2550 int drmCommandRead(int fd, unsigned long drmCommandIndex, void *data,
2553 unsigned long request;
2555 request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
2556 DRM_COMMAND_BASE + drmCommandIndex, size);
2558 if (drmIoctl(fd, request, data)) {
2566 * Send a device-specific write command.
2568 * \param fd file descriptor.
2569 * \param drmCommandIndex command index
2570 * \param data source pointer of the data to be written.
2571 * \param size size of the data to be written.
2573 * \return zero on success, or a negative value on failure.
2576 * It issues a write ioctl given by
2577 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2579 int drmCommandWrite(int fd, unsigned long drmCommandIndex, void *data,
2582 unsigned long request;
2584 request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
2585 DRM_COMMAND_BASE + drmCommandIndex, size);
2587 if (drmIoctl(fd, request, data)) {
2595 * Send a device-specific read-write command.
2597 * \param fd file descriptor.
2598 * \param drmCommandIndex command index
2599 * \param data source pointer of the data to be read and written.
2600 * \param size size of the data to be read and written.
2602 * \return zero on success, or a negative value on failure.
2605 * It issues a read-write ioctl given by
2606 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2608 int drmCommandWriteRead(int fd, unsigned long drmCommandIndex, void *data,
2611 unsigned long request;
2613 request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
2614 DRM_COMMAND_BASE + drmCommandIndex, size);
2616 if (drmIoctl(fd, request, data))
2621 #define DRM_MAX_FDS 16
2627 } connection[DRM_MAX_FDS];
2629 static int nr_fds = 0;
2631 int drmOpenOnce(void *unused,
2635 return drmOpenOnceWithType(BusID, newlyopened, DRM_NODE_PRIMARY);
2638 int drmOpenOnceWithType(const char *BusID, int *newlyopened, int type)
2643 for (i = 0; i < nr_fds; i++)
2644 if ((strcmp(BusID, connection[i].BusID) == 0) &&
2645 (connection[i].type == type)) {
2646 connection[i].refcount++;
2648 return connection[i].fd;
2651 fd = drmOpenWithType(NULL, BusID, type);
2652 if (fd < 0 || nr_fds == DRM_MAX_FDS)
2655 connection[nr_fds].BusID = strdup(BusID);
2656 connection[nr_fds].fd = fd;
2657 connection[nr_fds].refcount = 1;
2658 connection[nr_fds].type = type;
2662 fprintf(stderr, "saved connection %d for %s %d\n",
2663 nr_fds, connection[nr_fds].BusID,
2664 strcmp(BusID, connection[nr_fds].BusID));
2671 void drmCloseOnce(int fd)
2675 for (i = 0; i < nr_fds; i++) {
2676 if (fd == connection[i].fd) {
2677 if (--connection[i].refcount == 0) {
2678 drmClose(connection[i].fd);
2679 free(connection[i].BusID);
2682 connection[i] = connection[nr_fds];
2690 int drmSetMaster(int fd)
2692 return drmIoctl(fd, DRM_IOCTL_SET_MASTER, NULL);
2695 int drmDropMaster(int fd)
2697 return drmIoctl(fd, DRM_IOCTL_DROP_MASTER, NULL);
2700 char *drmGetDeviceNameFromFd(int fd)
2707 /* The whole drmOpen thing is a fiasco and we need to find a way
2708 * back to just using open(2). For now, however, lets just make
2709 * things worse with even more ad hoc directory walking code to
2710 * discover the device file name. */
2715 for (i = 0; i < DRM_MAX_MINOR; i++) {
2716 snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
2717 if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
2720 if (i == DRM_MAX_MINOR)
2723 return strdup(name);
2726 int drmGetNodeTypeFromFd(int fd)
2731 if (fstat(fd, &sbuf))
2734 maj = major(sbuf.st_rdev);
2735 min = minor(sbuf.st_rdev);
2737 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode)) {
2742 type = drmGetMinorType(min);
2748 int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags, int *prime_fd)
2750 struct drm_prime_handle args;
2755 args.handle = handle;
2757 ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
2761 *prime_fd = args.fd;
2765 int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
2767 struct drm_prime_handle args;
2772 ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
2776 *handle = args.handle;
2780 static char *drmGetMinorNameForFD(int fd, int type)
2784 struct dirent *pent, *ent;
2786 const char *name = drmGetMinorName(type);
2788 char dev_name[64], buf[64];
2797 if (fstat(fd, &sbuf))
2800 maj = major(sbuf.st_rdev);
2801 min = minor(sbuf.st_rdev);
2803 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
2806 snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
2808 sysdir = opendir(buf);
2812 name_max = fpathconf(dirfd(sysdir), _PC_NAME_MAX);
2816 pent = malloc(offsetof(struct dirent, d_name) + name_max + 1);
2820 while (readdir_r(sysdir, pent, &ent) == 0 && ent != NULL) {
2821 if (strncmp(ent->d_name, name, len) == 0) {
2822 snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
2828 return strdup(dev_name);
2838 char buf[PATH_MAX + 1];
2839 const char *dev_name;
2840 unsigned int maj, min;
2843 if (fstat(fd, &sbuf))
2846 maj = major(sbuf.st_rdev);
2847 min = minor(sbuf.st_rdev);
2849 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
2853 case DRM_NODE_PRIMARY:
2854 dev_name = DRM_DEV_NAME;
2856 case DRM_NODE_CONTROL:
2857 dev_name = DRM_CONTROL_DEV_NAME;
2859 case DRM_NODE_RENDER:
2860 dev_name = DRM_RENDER_DEV_NAME;
2866 base = drmGetMinorBase(type);
2870 n = snprintf(buf, sizeof(buf), dev_name, DRM_DIR_NAME, min - base);
2871 if (n == -1 || n >= sizeof(buf))
2879 char *drmGetPrimaryDeviceNameFromFd(int fd)
2881 return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
2884 char *drmGetRenderDeviceNameFromFd(int fd)
2886 return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
2890 static char * DRM_PRINTFLIKE(2, 3)
2891 sysfs_uevent_get(const char *path, const char *fmt, ...)
2893 char filename[PATH_MAX + 1], *key, *line = NULL, *value = NULL;
2894 size_t size = 0, len;
2900 num = vasprintf(&key, fmt, ap);
2904 snprintf(filename, sizeof(filename), "%s/uevent", path);
2906 fp = fopen(filename, "r");
2912 while ((num = getline(&line, &size, fp)) >= 0) {
2913 if ((strncmp(line, key, len) == 0) && (line[len] == '=')) {
2914 char *start = line + len + 1, *end = line + num - 1;
2919 value = strndup(start, end - start);
2933 static int drmParseSubsystemType(int maj, int min)
2936 char path[PATH_MAX + 1];
2937 char link[PATH_MAX + 1] = "";
2940 snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/subsystem",
2943 if (readlink(path, link, PATH_MAX) < 0)
2946 name = strrchr(link, '/');
2950 if (strncmp(name, "/pci", 4) == 0)
2953 if (strncmp(name, "/usb", 4) == 0)
2956 if (strncmp(name, "/platform", 9) == 0)
2957 return DRM_BUS_PLATFORM;
2959 if (strncmp(name, "/host1x", 7) == 0)
2960 return DRM_BUS_HOST1X;
2963 #elif defined(__OpenBSD__)
2966 #warning "Missing implementation of drmParseSubsystemType"
2971 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
2974 char path[PATH_MAX + 1];
2977 int domain, bus, dev, func;
2980 snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/uevent", maj, min);
2981 fd = open(path, O_RDONLY);
2985 ret = read(fd, data, sizeof(data)-1);
2991 #define TAG "PCI_SLOT_NAME="
2992 str = strstr(data, TAG);
2996 if (sscanf(str, TAG "%04x:%02x:%02x.%1u",
2997 &domain, &bus, &dev, &func) != 4)
3001 info->domain = domain;
3007 #elif defined(__OpenBSD__)
3008 struct drm_pciinfo pinfo;
3011 type = drmGetMinorType(min);
3015 fd = drmOpenMinor(min, 0, type);
3019 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3025 info->domain = pinfo.domain;
3026 info->bus = pinfo.bus;
3027 info->dev = pinfo.dev;
3028 info->func = pinfo.func;
3032 #warning "Missing implementation of drmParsePciBusInfo"
3037 static int drmCompareBusInfo(drmDevicePtr a, drmDevicePtr b)
3039 if (a == NULL || b == NULL)
3042 if (a->bustype != b->bustype)
3045 switch (a->bustype) {
3047 return memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo));
3050 return memcmp(a->businfo.usb, b->businfo.usb, sizeof(drmUsbBusInfo));
3052 case DRM_BUS_PLATFORM:
3053 return memcmp(a->businfo.platform, b->businfo.platform, sizeof(drmPlatformBusInfo));
3055 case DRM_BUS_HOST1X:
3056 return memcmp(a->businfo.host1x, b->businfo.host1x, sizeof(drmHost1xBusInfo));
3065 static int drmGetNodeType(const char *name)
3067 if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
3068 sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
3069 return DRM_NODE_PRIMARY;
3071 if (strncmp(name, DRM_CONTROL_MINOR_NAME,
3072 sizeof(DRM_CONTROL_MINOR_NAME ) - 1) == 0)
3073 return DRM_NODE_CONTROL;
3075 if (strncmp(name, DRM_RENDER_MINOR_NAME,
3076 sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
3077 return DRM_NODE_RENDER;
3082 static int drmGetMaxNodeName(void)
3084 return sizeof(DRM_DIR_NAME) +
3085 MAX3(sizeof(DRM_PRIMARY_MINOR_NAME),
3086 sizeof(DRM_CONTROL_MINOR_NAME),
3087 sizeof(DRM_RENDER_MINOR_NAME)) +
3088 3 /* length of the node number */;
3092 static int parse_separate_sysfs_files(int maj, int min,
3093 drmPciDeviceInfoPtr device,
3094 bool ignore_revision)
3096 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3097 static const char *attrs[] = {
3098 "revision", /* Older kernels are missing the file, so check for it first */
3104 char path[PATH_MAX + 1];
3105 unsigned int data[ARRAY_SIZE(attrs)];
3109 for (unsigned i = ignore_revision ? 1 : 0; i < ARRAY_SIZE(attrs); i++) {
3110 snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/%s", maj, min,
3112 fp = fopen(path, "r");
3116 ret = fscanf(fp, "%x", &data[i]);
3123 device->revision_id = ignore_revision ? 0xff : data[0] & 0xff;
3124 device->vendor_id = data[1] & 0xffff;
3125 device->device_id = data[2] & 0xffff;
3126 device->subvendor_id = data[3] & 0xffff;
3127 device->subdevice_id = data[4] & 0xffff;
3132 static int parse_config_sysfs_file(int maj, int min,
3133 drmPciDeviceInfoPtr device)
3135 char path[PATH_MAX + 1];
3136 unsigned char config[64];
3139 snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/config", maj, min);
3140 fd = open(path, O_RDONLY);
3144 ret = read(fd, config, sizeof(config));
3149 device->vendor_id = config[0] | (config[1] << 8);
3150 device->device_id = config[2] | (config[3] << 8);
3151 device->revision_id = config[8];
3152 device->subvendor_id = config[44] | (config[45] << 8);
3153 device->subdevice_id = config[46] | (config[47] << 8);
3159 static int drmParsePciDeviceInfo(int maj, int min,
3160 drmPciDeviceInfoPtr device,
3164 if (!(flags & DRM_DEVICE_GET_PCI_REVISION))
3165 return parse_separate_sysfs_files(maj, min, device, true);
3167 if (parse_separate_sysfs_files(maj, min, device, false))
3168 return parse_config_sysfs_file(maj, min, device);
3171 #elif defined(__OpenBSD__)
3172 struct drm_pciinfo pinfo;
3175 type = drmGetMinorType(min);
3179 fd = drmOpenMinor(min, 0, type);
3183 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3189 device->vendor_id = pinfo.vendor_id;
3190 device->device_id = pinfo.device_id;
3191 device->revision_id = pinfo.revision_id;
3192 device->subvendor_id = pinfo.subvendor_id;
3193 device->subdevice_id = pinfo.subdevice_id;
3197 #warning "Missing implementation of drmParsePciDeviceInfo"
3202 static void drmFreePlatformDevice(drmDevicePtr device)
3204 if (device->deviceinfo.platform) {
3205 if (device->deviceinfo.platform->compatible) {
3206 char **compatible = device->deviceinfo.platform->compatible;
3208 while (*compatible) {
3213 free(device->deviceinfo.platform->compatible);
3218 static void drmFreeHost1xDevice(drmDevicePtr device)
3220 if (device->deviceinfo.host1x) {
3221 if (device->deviceinfo.host1x->compatible) {
3222 char **compatible = device->deviceinfo.host1x->compatible;
3224 while (*compatible) {
3229 free(device->deviceinfo.host1x->compatible);
3234 void drmFreeDevice(drmDevicePtr *device)
3240 switch ((*device)->bustype) {
3241 case DRM_BUS_PLATFORM:
3242 drmFreePlatformDevice(*device);
3245 case DRM_BUS_HOST1X:
3246 drmFreeHost1xDevice(*device);
3255 void drmFreeDevices(drmDevicePtr devices[], int count)
3259 if (devices == NULL)
3262 for (i = 0; i < count; i++)
3264 drmFreeDevice(&devices[i]);
3267 static drmDevicePtr drmDeviceAlloc(unsigned int type, const char *node,
3268 size_t bus_size, size_t device_size,
3271 size_t max_node_length, extra, size;
3272 drmDevicePtr device;
3276 max_node_length = ALIGN(drmGetMaxNodeName(), sizeof(void *));
3277 extra = DRM_NODE_MAX * (sizeof(void *) + max_node_length);
3279 size = sizeof(*device) + extra + bus_size + device_size;
3281 device = calloc(1, size);
3285 device->available_nodes = 1 << type;
3287 ptr = (char *)device + sizeof(*device);
3288 device->nodes = (char **)ptr;
3290 ptr += DRM_NODE_MAX * sizeof(void *);
3292 for (i = 0; i < DRM_NODE_MAX; i++) {
3293 device->nodes[i] = ptr;
3294 ptr += max_node_length;
3297 memcpy(device->nodes[type], node, max_node_length);
3304 static int drmProcessPciDevice(drmDevicePtr *device,
3305 const char *node, int node_type,
3306 int maj, int min, bool fetch_deviceinfo,
3313 dev = drmDeviceAlloc(node_type, node, sizeof(drmPciBusInfo),
3314 sizeof(drmPciDeviceInfo), &addr);
3318 dev->bustype = DRM_BUS_PCI;
3320 dev->businfo.pci = (drmPciBusInfoPtr)addr;
3322 ret = drmParsePciBusInfo(maj, min, dev->businfo.pci);
3326 // Fetch the device info if the user has requested it
3327 if (fetch_deviceinfo) {
3328 addr += sizeof(drmPciBusInfo);
3329 dev->deviceinfo.pci = (drmPciDeviceInfoPtr)addr;
3331 ret = drmParsePciDeviceInfo(maj, min, dev->deviceinfo.pci, flags);
3345 static int drmParseUsbBusInfo(int maj, int min, drmUsbBusInfoPtr info)
3348 char path[PATH_MAX + 1], *value;
3349 unsigned int bus, dev;
3352 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3354 value = sysfs_uevent_get(path, "BUSNUM");
3358 ret = sscanf(value, "%03u", &bus);
3364 value = sysfs_uevent_get(path, "DEVNUM");
3368 ret = sscanf(value, "%03u", &dev);
3379 #warning "Missing implementation of drmParseUsbBusInfo"
3384 static int drmParseUsbDeviceInfo(int maj, int min, drmUsbDeviceInfoPtr info)
3387 char path[PATH_MAX + 1], *value;
3388 unsigned int vendor, product;
3391 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3393 value = sysfs_uevent_get(path, "PRODUCT");
3397 ret = sscanf(value, "%x/%x", &vendor, &product);
3403 info->vendor = vendor;
3404 info->product = product;
3408 #warning "Missing implementation of drmParseUsbDeviceInfo"
3413 static int drmProcessUsbDevice(drmDevicePtr *device, const char *node,
3414 int node_type, int maj, int min,
3415 bool fetch_deviceinfo, uint32_t flags)
3421 dev = drmDeviceAlloc(node_type, node, sizeof(drmUsbBusInfo),
3422 sizeof(drmUsbDeviceInfo), &ptr);
3426 dev->bustype = DRM_BUS_USB;
3428 dev->businfo.usb = (drmUsbBusInfoPtr)ptr;
3430 ret = drmParseUsbBusInfo(maj, min, dev->businfo.usb);
3434 if (fetch_deviceinfo) {
3435 ptr += sizeof(drmUsbBusInfo);
3436 dev->deviceinfo.usb = (drmUsbDeviceInfoPtr)ptr;
3438 ret = drmParseUsbDeviceInfo(maj, min, dev->deviceinfo.usb);
3452 static int drmParsePlatformBusInfo(int maj, int min, drmPlatformBusInfoPtr info)
3455 char path[PATH_MAX + 1], *name;
3457 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3459 name = sysfs_uevent_get(path, "OF_FULLNAME");
3463 strncpy(info->fullname, name, DRM_PLATFORM_DEVICE_NAME_LEN);
3464 info->fullname[DRM_PLATFORM_DEVICE_NAME_LEN - 1] = '\0';
3469 #warning "Missing implementation of drmParsePlatformBusInfo"
3474 static int drmParsePlatformDeviceInfo(int maj, int min,
3475 drmPlatformDeviceInfoPtr info)
3478 char path[PATH_MAX + 1], *value;
3479 unsigned int count, i;
3482 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3484 value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
3488 sscanf(value, "%u", &count);
3491 info->compatible = calloc(count + 1, sizeof(*info->compatible));
3492 if (!info->compatible)
3495 for (i = 0; i < count; i++) {
3496 value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
3502 info->compatible[i] = value;
3509 free(info->compatible[i]);
3511 free(info->compatible);
3514 #warning "Missing implementation of drmParsePlatformDeviceInfo"
3519 static int drmProcessPlatformDevice(drmDevicePtr *device,
3520 const char *node, int node_type,
3521 int maj, int min, bool fetch_deviceinfo,
3528 dev = drmDeviceAlloc(node_type, node, sizeof(drmPlatformBusInfo),
3529 sizeof(drmPlatformDeviceInfo), &ptr);
3533 dev->bustype = DRM_BUS_PLATFORM;
3535 dev->businfo.platform = (drmPlatformBusInfoPtr)ptr;
3537 ret = drmParsePlatformBusInfo(maj, min, dev->businfo.platform);
3541 if (fetch_deviceinfo) {
3542 ptr += sizeof(drmPlatformBusInfo);
3543 dev->deviceinfo.platform = (drmPlatformDeviceInfoPtr)ptr;
3545 ret = drmParsePlatformDeviceInfo(maj, min, dev->deviceinfo.platform);
3559 static int drmParseHost1xBusInfo(int maj, int min, drmHost1xBusInfoPtr info)
3562 char path[PATH_MAX + 1], *name;
3564 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3566 name = sysfs_uevent_get(path, "OF_FULLNAME");
3570 strncpy(info->fullname, name, DRM_HOST1X_DEVICE_NAME_LEN);
3571 info->fullname[DRM_HOST1X_DEVICE_NAME_LEN - 1] = '\0';
3576 #warning "Missing implementation of drmParseHost1xBusInfo"
3581 static int drmParseHost1xDeviceInfo(int maj, int min,
3582 drmHost1xDeviceInfoPtr info)
3585 char path[PATH_MAX + 1], *value;
3586 unsigned int count, i;
3589 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3591 value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
3595 sscanf(value, "%u", &count);
3598 info->compatible = calloc(count + 1, sizeof(*info->compatible));
3599 if (!info->compatible)
3602 for (i = 0; i < count; i++) {
3603 value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
3609 info->compatible[i] = value;
3616 free(info->compatible[i]);
3618 free(info->compatible);
3621 #warning "Missing implementation of drmParseHost1xDeviceInfo"
3626 static int drmProcessHost1xDevice(drmDevicePtr *device,
3627 const char *node, int node_type,
3628 int maj, int min, bool fetch_deviceinfo,
3635 dev = drmDeviceAlloc(node_type, node, sizeof(drmHost1xBusInfo),
3636 sizeof(drmHost1xDeviceInfo), &ptr);
3640 dev->bustype = DRM_BUS_HOST1X;
3642 dev->businfo.host1x = (drmHost1xBusInfoPtr)ptr;
3644 ret = drmParseHost1xBusInfo(maj, min, dev->businfo.host1x);
3648 if (fetch_deviceinfo) {
3649 ptr += sizeof(drmHost1xBusInfo);
3650 dev->deviceinfo.host1x = (drmHost1xDeviceInfoPtr)ptr;
3652 ret = drmParseHost1xDeviceInfo(maj, min, dev->deviceinfo.host1x);
3666 /* Consider devices located on the same bus as duplicate and fold the respective
3667 * entries into a single one.
3669 * Note: this leaves "gaps" in the array, while preserving the length.
3671 static void drmFoldDuplicatedDevices(drmDevicePtr local_devices[], int count)
3673 int node_type, i, j;
3675 for (i = 0; i < count; i++) {
3676 for (j = i + 1; j < count; j++) {
3677 if (drmCompareBusInfo(local_devices[i], local_devices[j]) == 0) {
3678 local_devices[i]->available_nodes |= local_devices[j]->available_nodes;
3679 node_type = log2(local_devices[j]->available_nodes);
3680 memcpy(local_devices[i]->nodes[node_type],
3681 local_devices[j]->nodes[node_type], drmGetMaxNodeName());
3682 drmFreeDevice(&local_devices[j]);
3688 /* Check that the given flags are valid returning 0 on success */
3690 drm_device_validate_flags(uint32_t flags)
3692 return (flags & ~DRM_DEVICE_GET_PCI_REVISION);
3696 * Get information about the opened drm device
3698 * \param fd file descriptor of the drm device
3699 * \param flags feature/behaviour bitmask
3700 * \param device the address of a drmDevicePtr where the information
3701 * will be allocated in stored
3703 * \return zero on success, negative error code otherwise.
3705 * \note Unlike drmGetDevice it does not retrieve the pci device revision field
3706 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
3708 int drmGetDevice2(int fd, uint32_t flags, drmDevicePtr *device)
3712 * DRI device nodes on OpenBSD are not in their own directory, they reside
3713 * in /dev along with a large number of statically generated /dev nodes.
3714 * Avoid stat'ing all of /dev needlessly by implementing this custom path.
3718 char node[PATH_MAX + 1];
3719 const char *dev_name;
3720 int node_type, subsystem_type;
3721 int maj, min, n, ret, base;
3723 if (fd == -1 || device == NULL)
3726 if (fstat(fd, &sbuf))
3729 maj = major(sbuf.st_rdev);
3730 min = minor(sbuf.st_rdev);
3732 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3735 node_type = drmGetMinorType(min);
3736 if (node_type == -1)
3739 switch (node_type) {
3740 case DRM_NODE_PRIMARY:
3741 dev_name = DRM_DEV_NAME;
3743 case DRM_NODE_CONTROL:
3744 dev_name = DRM_CONTROL_DEV_NAME;
3746 case DRM_NODE_RENDER:
3747 dev_name = DRM_RENDER_DEV_NAME;
3753 base = drmGetMinorBase(node_type);
3757 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min - base);
3758 if (n == -1 || n >= PATH_MAX)
3760 if (stat(node, &sbuf))
3763 subsystem_type = drmParseSubsystemType(maj, min);
3764 if (subsystem_type != DRM_BUS_PCI)
3767 ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
3775 drmDevicePtr *local_devices;
3778 struct dirent *dent;
3780 char node[PATH_MAX + 1];
3781 int node_type, subsystem_type;
3783 int ret, i, node_count;
3787 if (drm_device_validate_flags(flags))
3790 if (fd == -1 || device == NULL)
3793 if (fstat(fd, &sbuf))
3796 find_rdev = sbuf.st_rdev;
3797 maj = major(sbuf.st_rdev);
3798 min = minor(sbuf.st_rdev);
3800 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3803 subsystem_type = drmParseSubsystemType(maj, min);
3805 local_devices = calloc(max_count, sizeof(drmDevicePtr));
3806 if (local_devices == NULL)
3809 sysdir = opendir(DRM_DIR_NAME);
3816 while ((dent = readdir(sysdir))) {
3817 node_type = drmGetNodeType(dent->d_name);
3821 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, dent->d_name);
3822 if (stat(node, &sbuf))
3825 maj = major(sbuf.st_rdev);
3826 min = minor(sbuf.st_rdev);
3828 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3831 if (drmParseSubsystemType(maj, min) != subsystem_type)
3834 switch (subsystem_type) {
3836 ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
3843 ret = drmProcessUsbDevice(&d, node, node_type, maj, min, true, flags);
3849 case DRM_BUS_PLATFORM:
3850 ret = drmProcessPlatformDevice(&d, node, node_type, maj, min, true, flags);
3856 case DRM_BUS_HOST1X:
3857 ret = drmProcessHost1xDevice(&d, node, node_type, maj, min, true, flags);
3867 if (i >= max_count) {
3871 temp = realloc(local_devices, max_count * sizeof(drmDevicePtr));
3874 local_devices = temp;
3877 /* store target at local_devices[0] for ease to use below */
3878 if (find_rdev == sbuf.st_rdev && i) {
3879 local_devices[i] = local_devices[0];
3880 local_devices[0] = d;
3883 local_devices[i] = d;
3888 drmFoldDuplicatedDevices(local_devices, node_count);
3890 *device = local_devices[0];
3891 drmFreeDevices(&local_devices[1], node_count - 1);
3894 free(local_devices);
3895 if (*device == NULL)
3900 drmFreeDevices(local_devices, i);
3904 free(local_devices);
3910 * Get information about the opened drm device
3912 * \param fd file descriptor of the drm device
3913 * \param device the address of a drmDevicePtr where the information
3914 * will be allocated in stored
3916 * \return zero on success, negative error code otherwise.
3918 int drmGetDevice(int fd, drmDevicePtr *device)
3920 return drmGetDevice2(fd, DRM_DEVICE_GET_PCI_REVISION, device);
3924 * Get drm devices on the system
3926 * \param flags feature/behaviour bitmask
3927 * \param devices the array of devices with drmDevicePtr elements
3928 * can be NULL to get the device number first
3929 * \param max_devices the maximum number of devices for the array
3931 * \return on error - negative error code,
3932 * if devices is NULL - total number of devices available on the system,
3933 * alternatively the number of devices stored in devices[], which is
3934 * capped by the max_devices.
3936 * \note Unlike drmGetDevices it does not retrieve the pci device revision field
3937 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
3939 int drmGetDevices2(uint32_t flags, drmDevicePtr devices[], int max_devices)
3941 drmDevicePtr *local_devices;
3942 drmDevicePtr device;
3944 struct dirent *dent;
3946 char node[PATH_MAX + 1];
3947 int node_type, subsystem_type;
3949 int ret, i, node_count, device_count;
3952 if (drm_device_validate_flags(flags))
3955 local_devices = calloc(max_count, sizeof(drmDevicePtr));
3956 if (local_devices == NULL)
3959 sysdir = opendir(DRM_DIR_NAME);
3966 while ((dent = readdir(sysdir))) {
3967 node_type = drmGetNodeType(dent->d_name);
3971 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, dent->d_name);
3972 if (stat(node, &sbuf))
3975 maj = major(sbuf.st_rdev);
3976 min = minor(sbuf.st_rdev);
3978 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3981 subsystem_type = drmParseSubsystemType(maj, min);
3983 if (subsystem_type < 0)
3986 switch (subsystem_type) {
3988 ret = drmProcessPciDevice(&device, node, node_type,
3989 maj, min, devices != NULL, flags);
3996 ret = drmProcessUsbDevice(&device, node, node_type, maj, min,
3997 devices != NULL, flags);
4003 case DRM_BUS_PLATFORM:
4004 ret = drmProcessPlatformDevice(&device, node, node_type, maj, min,
4005 devices != NULL, flags);
4011 case DRM_BUS_HOST1X:
4012 ret = drmProcessHost1xDevice(&device, node, node_type, maj, min,
4013 devices != NULL, flags);
4023 if (i >= max_count) {
4027 temp = realloc(local_devices, max_count * sizeof(drmDevicePtr));
4030 local_devices = temp;
4033 local_devices[i] = device;
4038 drmFoldDuplicatedDevices(local_devices, node_count);
4041 for (i = 0; i < node_count; i++) {
4042 if (!local_devices[i])
4045 if ((devices != NULL) && (device_count < max_devices))
4046 devices[device_count] = local_devices[i];
4048 drmFreeDevice(&local_devices[i]);
4054 free(local_devices);
4055 return device_count;
4058 drmFreeDevices(local_devices, i);
4062 free(local_devices);
4067 * Get drm devices on the system
4069 * \param devices the array of devices with drmDevicePtr elements
4070 * can be NULL to get the device number first
4071 * \param max_devices the maximum number of devices for the array
4073 * \return on error - negative error code,
4074 * if devices is NULL - total number of devices available on the system,
4075 * alternatively the number of devices stored in devices[], which is
4076 * capped by the max_devices.
4078 int drmGetDevices(drmDevicePtr devices[], int max_devices)
4080 return drmGetDevices2(DRM_DEVICE_GET_PCI_REVISION, devices, max_devices);
4083 char *drmGetDeviceNameFromFd2(int fd)
4087 char *device_name = NULL;
4088 unsigned int maj, min;
4091 static const char match[9] = "\nDEVNAME=";
4092 size_t expected = 1;
4095 if (fstat(fd, &sbuf))
4098 maj = major(sbuf.st_rdev);
4099 min = minor(sbuf.st_rdev);
4101 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
4104 snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/uevent", maj, min);
4105 if (!(f = fopen(buf, "r")))
4108 while (expected < sizeof(match)) {
4114 } else if (c == match[expected] )
4120 strcpy(buf, "/dev/");
4121 if (fgets(buf + 5, sizeof(buf) - 5, f)) {
4122 buf[strcspn(buf, "\n")] = '\0';
4123 device_name = strdup(buf);
4130 char node[PATH_MAX + 1];
4131 const char *dev_name;
4133 int maj, min, n, base;
4135 if (fstat(fd, &sbuf))
4138 maj = major(sbuf.st_rdev);
4139 min = minor(sbuf.st_rdev);
4141 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
4144 node_type = drmGetMinorType(min);
4145 if (node_type == -1)
4148 switch (node_type) {
4149 case DRM_NODE_PRIMARY:
4150 dev_name = DRM_DEV_NAME;
4152 case DRM_NODE_CONTROL:
4153 dev_name = DRM_CONTROL_DEV_NAME;
4155 case DRM_NODE_RENDER:
4156 dev_name = DRM_RENDER_DEV_NAME;
4162 base = drmGetMinorBase(node_type);
4166 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min - base);
4167 if (n == -1 || n >= PATH_MAX)
4170 return strdup(node);