3 * User-level interface to DRM device
5 * \author Rickard E. (Rik) Faith <faith@valinux.com>
6 * \author Kevin E. Martin <martin@valinux.com>
10 * Copyright 1999 Precision Insight, Inc., Cedar Park, Texas.
11 * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California.
12 * All Rights Reserved.
14 * Permission is hereby granted, free of charge, to any person obtaining a
15 * copy of this software and associated documentation files (the "Software"),
16 * to deal in the Software without restriction, including without limitation
17 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
18 * and/or sell copies of the Software, and to permit persons to whom the
19 * Software is furnished to do so, subject to the following conditions:
21 * The above copyright notice and this permission notice (including the next
22 * paragraph) shall be included in all copies or substantial portions of the
25 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
28 * PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
29 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
30 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
31 * DEALINGS IN THE SOFTWARE.
48 #include <sys/types.h>
50 #define stat_t struct stat
51 #include <sys/ioctl.h>
55 #include <sys/mkdev.h>
57 #ifdef MAJOR_IN_SYSMACROS
58 #include <sys/sysmacros.h>
62 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
64 /* Not all systems have MAP_FAILED defined */
66 #define MAP_FAILED ((void *)-1)
70 #include "libdrm_macros.h"
72 #include "util_math.h"
78 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
92 #endif /* __OpenBSD__ */
95 #define DRM_MAJOR 226 /* Linux */
98 #if defined(__OpenBSD__) || defined(__DragonFly__)
106 uint16_t subvendor_id;
107 uint16_t subdevice_id;
111 #define DRM_IOCTL_GET_PCIINFO DRM_IOR(0x15, struct drm_pciinfo)
114 #define DRM_MSG_VERBOSITY 3
116 #define memclear(s) memset(&s, 0, sizeof(s))
118 static drmServerInfoPtr drm_server_info;
120 drm_public void drmSetServerInfo(drmServerInfoPtr info)
122 drm_server_info = info;
126 * Output a message to stderr.
128 * \param format printf() like format string.
131 * This function is a wrapper around vfprintf().
134 static int DRM_PRINTFLIKE(1, 0)
135 drmDebugPrint(const char *format, va_list ap)
138 return __android_log_vprint(ANDROID_LOG_DEBUG, "libdrm", format, ap);
140 return vfprintf(stderr, format, ap);
145 drmMsg(const char *format, ...)
150 if (((env = getenv("LIBGL_DEBUG")) && strstr(env, "verbose")) ||
151 (drm_server_info && drm_server_info->debug_print))
154 va_start(ap, format);
155 if (drm_server_info) {
156 drm_server_info->debug_print(format,ap);
158 drmDebugPrint(format, ap);
164 static void *drmHashTable = NULL; /* Context switch callbacks */
166 drm_public void *drmGetHashTable(void)
171 drm_public void *drmMalloc(int size)
173 return calloc(1, size);
176 drm_public void drmFree(void *pt)
182 * Call ioctl, restarting if it is interrupted
185 drmIoctl(int fd, unsigned long request, void *arg)
190 ret = ioctl(fd, request, arg);
191 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
195 static unsigned long drmGetKeyFromFd(int fd)
204 drm_public drmHashEntry *drmGetEntry(int fd)
206 unsigned long key = drmGetKeyFromFd(fd);
211 drmHashTable = drmHashCreate();
213 if (drmHashLookup(drmHashTable, key, &value)) {
214 entry = drmMalloc(sizeof(*entry));
217 entry->tagTable = drmHashCreate();
218 drmHashInsert(drmHashTable, key, entry);
226 * Compare two busid strings
231 * \return 1 if matched.
234 * This function compares two bus ID strings. It understands the older
235 * PCI:b:d:f format and the newer pci:oooo:bb:dd.f format. In the format, o is
236 * domain, b is bus, d is device, f is function.
238 static int drmMatchBusID(const char *id1, const char *id2, int pci_domain_ok)
240 /* First, check if the IDs are exactly the same */
241 if (strcasecmp(id1, id2) == 0)
244 /* Try to match old/new-style PCI bus IDs. */
245 if (strncasecmp(id1, "pci", 3) == 0) {
246 unsigned int o1, b1, d1, f1;
247 unsigned int o2, b2, d2, f2;
250 ret = sscanf(id1, "pci:%04x:%02x:%02x.%u", &o1, &b1, &d1, &f1);
253 ret = sscanf(id1, "PCI:%u:%u:%u", &b1, &d1, &f1);
258 ret = sscanf(id2, "pci:%04x:%02x:%02x.%u", &o2, &b2, &d2, &f2);
261 ret = sscanf(id2, "PCI:%u:%u:%u", &b2, &d2, &f2);
266 /* If domains aren't properly supported by the kernel interface,
267 * just ignore them, which sucks less than picking a totally random
268 * card with "open by name"
273 if ((o1 != o2) || (b1 != b2) || (d1 != d2) || (f1 != f2))
282 * Handles error checking for chown call.
284 * \param path to file.
285 * \param id of the new owner.
286 * \param id of the new group.
288 * \return zero if success or -1 if failure.
291 * Checks for failure. If failure was caused by signal call chown again.
292 * If any other failure happened then it will output error message using
296 static int chown_check_return(const char *path, uid_t owner, gid_t group)
301 rv = chown(path, owner, group);
302 } while (rv != 0 && errno == EINTR);
307 drmMsg("Failed to change owner or group for file %s! %d: %s\n",
308 path, errno, strerror(errno));
313 static const char *drmGetDeviceName(int type)
316 case DRM_NODE_PRIMARY:
318 case DRM_NODE_CONTROL:
319 return DRM_CONTROL_DEV_NAME;
320 case DRM_NODE_RENDER:
321 return DRM_RENDER_DEV_NAME;
327 * Open the DRM device, creating it if necessary.
329 * \param dev major and minor numbers of the device.
330 * \param minor minor number of the device.
332 * \return a file descriptor on success, or a negative value on error.
335 * Assembles the device name from \p minor and opens it, creating the device
336 * special file node with the major and minor numbers specified by \p dev and
337 * parent directory if necessary and was called by root.
339 static int drmOpenDevice(dev_t dev, int minor, int type)
342 const char *dev_name = drmGetDeviceName(type);
343 char buf[DRM_NODE_NAME_MAX];
345 mode_t devmode = DRM_DEV_MODE, serv_mode;
348 int isroot = !geteuid();
349 uid_t user = DRM_DEV_UID;
350 gid_t group = DRM_DEV_GID;
356 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
357 drmMsg("drmOpenDevice: node name is %s\n", buf);
359 if (drm_server_info && drm_server_info->get_perms) {
360 drm_server_info->get_perms(&serv_group, &serv_mode);
361 devmode = serv_mode ? serv_mode : DRM_DEV_MODE;
362 devmode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
366 if (stat(DRM_DIR_NAME, &st)) {
368 return DRM_ERR_NOT_ROOT;
369 mkdir(DRM_DIR_NAME, DRM_DEV_DIRMODE);
370 chown_check_return(DRM_DIR_NAME, 0, 0); /* root:root */
371 chmod(DRM_DIR_NAME, DRM_DEV_DIRMODE);
374 /* Check if the device node exists and create it if necessary. */
375 if (stat(buf, &st)) {
377 return DRM_ERR_NOT_ROOT;
379 mknod(buf, S_IFCHR | devmode, dev);
382 if (drm_server_info && drm_server_info->get_perms) {
383 group = ((int)serv_group >= 0) ? serv_group : DRM_DEV_GID;
384 chown_check_return(buf, user, group);
388 /* if we modprobed then wait for udev */
392 if (stat(DRM_DIR_NAME, &st)) {
396 if (udev_count == 50)
401 if (stat(buf, &st)) {
405 if (udev_count == 50)
412 fd = open(buf, O_RDWR | O_CLOEXEC, 0);
413 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
414 fd, fd < 0 ? strerror(errno) : "OK");
419 /* Check if the device node is not what we expect it to be, and recreate it
420 * and try again if so.
422 if (st.st_rdev != dev) {
424 return DRM_ERR_NOT_ROOT;
426 mknod(buf, S_IFCHR | devmode, dev);
427 if (drm_server_info && drm_server_info->get_perms) {
428 chown_check_return(buf, user, group);
432 fd = open(buf, O_RDWR | O_CLOEXEC, 0);
433 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
434 fd, fd < 0 ? strerror(errno) : "OK");
438 drmMsg("drmOpenDevice: Open failed\n");
446 * Open the DRM device
448 * \param minor device minor number.
449 * \param create allow to create the device if set.
451 * \return a file descriptor on success, or a negative value on error.
454 * Calls drmOpenDevice() if \p create is set, otherwise assembles the device
455 * name from \p minor and opens it.
457 static int drmOpenMinor(int minor, int create, int type)
460 char buf[DRM_NODE_NAME_MAX];
461 const char *dev_name = drmGetDeviceName(type);
464 return drmOpenDevice(makedev(DRM_MAJOR, minor), minor, type);
469 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
470 if ((fd = open(buf, O_RDWR | O_CLOEXEC, 0)) >= 0)
477 * Determine whether the DRM kernel driver has been loaded.
479 * \return 1 if the DRM driver is loaded, 0 otherwise.
482 * Determine the presence of the kernel driver by attempting to open the 0
483 * minor and get version information. For backward compatibility with older
484 * Linux implementations, /proc/dri is also checked.
486 drm_public int drmAvailable(void)
488 drmVersionPtr version;
492 if ((fd = drmOpenMinor(0, 1, DRM_NODE_PRIMARY)) < 0) {
494 /* Try proc for backward Linux compatibility */
495 if (!access("/proc/dri/0", R_OK))
501 if ((version = drmGetVersion(fd))) {
503 drmFreeVersion(version);
510 static int drmGetMinorBase(int type)
513 case DRM_NODE_PRIMARY:
515 case DRM_NODE_CONTROL:
517 case DRM_NODE_RENDER:
524 static int drmGetMinorType(int minor)
526 int type = minor >> 6;
532 case DRM_NODE_PRIMARY:
533 case DRM_NODE_CONTROL:
534 case DRM_NODE_RENDER:
541 static const char *drmGetMinorName(int type)
544 case DRM_NODE_PRIMARY:
545 return DRM_PRIMARY_MINOR_NAME;
546 case DRM_NODE_CONTROL:
547 return DRM_CONTROL_MINOR_NAME;
548 case DRM_NODE_RENDER:
549 return DRM_RENDER_MINOR_NAME;
556 * Open the device by bus ID.
558 * \param busid bus ID.
559 * \param type device node type.
561 * \return a file descriptor on success, or a negative value on error.
564 * This function attempts to open every possible minor (up to DRM_MAX_MINOR),
565 * comparing the device bus ID with the one supplied.
567 * \sa drmOpenMinor() and drmGetBusid().
569 static int drmOpenByBusid(const char *busid, int type)
571 int i, pci_domain_ok = 1;
575 int base = drmGetMinorBase(type);
580 drmMsg("drmOpenByBusid: Searching for BusID %s\n", busid);
581 for (i = base; i < base + DRM_MAX_MINOR; i++) {
582 fd = drmOpenMinor(i, 1, type);
583 drmMsg("drmOpenByBusid: drmOpenMinor returns %d\n", fd);
585 /* We need to try for 1.4 first for proper PCI domain support
586 * and if that fails, we know the kernel is busted
590 sv.drm_dd_major = -1; /* Don't care */
591 sv.drm_dd_minor = -1; /* Don't care */
592 if (drmSetInterfaceVersion(fd, &sv)) {
598 sv.drm_dd_major = -1; /* Don't care */
599 sv.drm_dd_minor = -1; /* Don't care */
600 drmMsg("drmOpenByBusid: Interface 1.4 failed, trying 1.1\n");
601 drmSetInterfaceVersion(fd, &sv);
603 buf = drmGetBusid(fd);
604 drmMsg("drmOpenByBusid: drmGetBusid reports %s\n", buf);
605 if (buf && drmMatchBusID(buf, busid, pci_domain_ok)) {
619 * Open the device by name.
621 * \param name driver name.
622 * \param type the device node type.
624 * \return a file descriptor on success, or a negative value on error.
627 * This function opens the first minor number that matches the driver name and
628 * isn't already in use. If it's in use it then it will already have a bus ID
631 * \sa drmOpenMinor(), drmGetVersion() and drmGetBusid().
633 static int drmOpenByName(const char *name, int type)
637 drmVersionPtr version;
639 int base = drmGetMinorBase(type);
645 * Open the first minor number that matches the driver name and isn't
646 * already in use. If it's in use it will have a busid assigned already.
648 for (i = base; i < base + DRM_MAX_MINOR; i++) {
649 if ((fd = drmOpenMinor(i, 1, type)) >= 0) {
650 if ((version = drmGetVersion(fd))) {
651 if (!strcmp(version->name, name)) {
652 drmFreeVersion(version);
653 id = drmGetBusid(fd);
654 drmMsg("drmGetBusid returned '%s'\n", id ? id : "NULL");
663 drmFreeVersion(version);
671 /* Backward-compatibility /proc support */
672 for (i = 0; i < 8; i++) {
673 char proc_name[64], buf[512];
674 char *driver, *pt, *devstring;
677 sprintf(proc_name, "/proc/dri/%d/name", i);
678 if ((fd = open(proc_name, 0, 0)) >= 0) {
679 retcode = read(fd, buf, sizeof(buf)-1);
682 buf[retcode-1] = '\0';
683 for (driver = pt = buf; *pt && *pt != ' '; ++pt)
685 if (*pt) { /* Device is next */
687 if (!strcmp(driver, name)) { /* Match */
688 for (devstring = ++pt; *pt && *pt != ' '; ++pt)
690 if (*pt) { /* Found busid */
691 return drmOpenByBusid(++pt, type);
692 } else { /* No busid */
693 return drmOpenDevice(strtol(devstring, NULL, 0),i, type);
707 * Open the DRM device.
709 * Looks up the specified name and bus ID, and opens the device found. The
710 * entry in /dev/dri is created if necessary and if called by root.
712 * \param name driver name. Not referenced if bus ID is supplied.
713 * \param busid bus ID. Zero if not known.
715 * \return a file descriptor on success, or a negative value on error.
718 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
721 drm_public int drmOpen(const char *name, const char *busid)
723 return drmOpenWithType(name, busid, DRM_NODE_PRIMARY);
727 * Open the DRM device with specified type.
729 * Looks up the specified name and bus ID, and opens the device found. The
730 * entry in /dev/dri is created if necessary and if called by root.
732 * \param name driver name. Not referenced if bus ID is supplied.
733 * \param busid bus ID. Zero if not known.
734 * \param type the device node type to open, PRIMARY, CONTROL or RENDER
736 * \return a file descriptor on success, or a negative value on error.
739 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
742 drm_public int drmOpenWithType(const char *name, const char *busid, int type)
744 if (name != NULL && drm_server_info &&
745 drm_server_info->load_module && !drmAvailable()) {
746 /* try to load the kernel module */
747 if (!drm_server_info->load_module(name)) {
748 drmMsg("[drm] failed to load kernel module \"%s\"\n", name);
754 int fd = drmOpenByBusid(busid, type);
760 return drmOpenByName(name, type);
765 drm_public int drmOpenControl(int minor)
767 return drmOpenMinor(minor, 0, DRM_NODE_CONTROL);
770 drm_public int drmOpenRender(int minor)
772 return drmOpenMinor(minor, 0, DRM_NODE_RENDER);
776 * Free the version information returned by drmGetVersion().
778 * \param v pointer to the version information.
781 * It frees the memory pointed by \p %v as well as all the non-null strings
784 drm_public void drmFreeVersion(drmVersionPtr v)
796 * Free the non-public version information returned by the kernel.
798 * \param v pointer to the version information.
801 * Used by drmGetVersion() to free the memory pointed by \p %v as well as all
802 * the non-null strings pointers in it.
804 static void drmFreeKernelVersion(drm_version_t *v)
816 * Copy version information.
818 * \param d destination pointer.
819 * \param s source pointer.
822 * Used by drmGetVersion() to translate the information returned by the ioctl
823 * interface in a private structure into the public structure counterpart.
825 static void drmCopyVersion(drmVersionPtr d, const drm_version_t *s)
827 d->version_major = s->version_major;
828 d->version_minor = s->version_minor;
829 d->version_patchlevel = s->version_patchlevel;
830 d->name_len = s->name_len;
831 d->name = strdup(s->name);
832 d->date_len = s->date_len;
833 d->date = strdup(s->date);
834 d->desc_len = s->desc_len;
835 d->desc = strdup(s->desc);
840 * Query the driver version information.
842 * \param fd file descriptor.
844 * \return pointer to a drmVersion structure which should be freed with
847 * \note Similar information is available via /proc/dri.
850 * It gets the version information via successive DRM_IOCTL_VERSION ioctls,
851 * first with zeros to get the string lengths, and then the actually strings.
852 * It also null-terminates them since they might not be already.
854 drm_public drmVersionPtr drmGetVersion(int fd)
856 drmVersionPtr retval;
857 drm_version_t *version = drmMalloc(sizeof(*version));
859 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
860 drmFreeKernelVersion(version);
864 if (version->name_len)
865 version->name = drmMalloc(version->name_len + 1);
866 if (version->date_len)
867 version->date = drmMalloc(version->date_len + 1);
868 if (version->desc_len)
869 version->desc = drmMalloc(version->desc_len + 1);
871 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
872 drmMsg("DRM_IOCTL_VERSION: %s\n", strerror(errno));
873 drmFreeKernelVersion(version);
877 /* The results might not be null-terminated strings, so terminate them. */
878 if (version->name_len) version->name[version->name_len] = '\0';
879 if (version->date_len) version->date[version->date_len] = '\0';
880 if (version->desc_len) version->desc[version->desc_len] = '\0';
882 retval = drmMalloc(sizeof(*retval));
883 drmCopyVersion(retval, version);
884 drmFreeKernelVersion(version);
890 * Get version information for the DRM user space library.
892 * This version number is driver independent.
894 * \param fd file descriptor.
896 * \return version information.
899 * This function allocates and fills a drm_version structure with a hard coded
902 drm_public drmVersionPtr drmGetLibVersion(int fd)
904 drm_version_t *version = drmMalloc(sizeof(*version));
907 * NOTE THIS MUST NOT GO ABOVE VERSION 1.X due to drivers needing it
908 * revision 1.0.x = original DRM interface with no drmGetLibVersion
909 * entry point and many drm<Device> extensions
910 * revision 1.1.x = added drmCommand entry points for device extensions
911 * added drmGetLibVersion to identify libdrm.a version
912 * revision 1.2.x = added drmSetInterfaceVersion
913 * modified drmOpen to handle both busid and name
914 * revision 1.3.x = added server + memory manager
916 version->version_major = 1;
917 version->version_minor = 3;
918 version->version_patchlevel = 0;
920 return (drmVersionPtr)version;
923 drm_public int drmGetCap(int fd, uint64_t capability, uint64_t *value)
925 struct drm_get_cap cap;
929 cap.capability = capability;
931 ret = drmIoctl(fd, DRM_IOCTL_GET_CAP, &cap);
939 drm_public int drmSetClientCap(int fd, uint64_t capability, uint64_t value)
941 struct drm_set_client_cap cap;
944 cap.capability = capability;
947 return drmIoctl(fd, DRM_IOCTL_SET_CLIENT_CAP, &cap);
951 * Free the bus ID information.
953 * \param busid bus ID information string as given by drmGetBusid().
956 * This function is just frees the memory pointed by \p busid.
958 drm_public void drmFreeBusid(const char *busid)
960 drmFree((void *)busid);
965 * Get the bus ID of the device.
967 * \param fd file descriptor.
969 * \return bus ID string.
972 * This function gets the bus ID via successive DRM_IOCTL_GET_UNIQUE ioctls to
973 * get the string length and data, passing the arguments in a drm_unique
976 drm_public char *drmGetBusid(int fd)
982 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
984 u.unique = drmMalloc(u.unique_len + 1);
985 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u)) {
989 u.unique[u.unique_len] = '\0';
996 * Set the bus ID of the device.
998 * \param fd file descriptor.
999 * \param busid bus ID string.
1001 * \return zero on success, negative on failure.
1004 * This function is a wrapper around the DRM_IOCTL_SET_UNIQUE ioctl, passing
1005 * the arguments in a drm_unique structure.
1007 drm_public int drmSetBusid(int fd, const char *busid)
1012 u.unique = (char *)busid;
1013 u.unique_len = strlen(busid);
1015 if (drmIoctl(fd, DRM_IOCTL_SET_UNIQUE, &u)) {
1021 drm_public int drmGetMagic(int fd, drm_magic_t * magic)
1028 if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
1030 *magic = auth.magic;
1034 drm_public int drmAuthMagic(int fd, drm_magic_t magic)
1040 if (drmIoctl(fd, DRM_IOCTL_AUTH_MAGIC, &auth))
1046 * Specifies a range of memory that is available for mapping by a
1049 * \param fd file descriptor.
1050 * \param offset usually the physical address. The actual meaning depends of
1051 * the \p type parameter. See below.
1052 * \param size of the memory in bytes.
1053 * \param type type of the memory to be mapped.
1054 * \param flags combination of several flags to modify the function actions.
1055 * \param handle will be set to a value that may be used as the offset
1056 * parameter for mmap().
1058 * \return zero on success or a negative value on error.
1060 * \par Mapping the frame buffer
1061 * For the frame buffer
1062 * - \p offset will be the physical address of the start of the frame buffer,
1063 * - \p size will be the size of the frame buffer in bytes, and
1064 * - \p type will be DRM_FRAME_BUFFER.
1067 * The area mapped will be uncached. If MTRR support is available in the
1068 * kernel, the frame buffer area will be set to write combining.
1070 * \par Mapping the MMIO register area
1071 * For the MMIO register area,
1072 * - \p offset will be the physical address of the start of the register area,
1073 * - \p size will be the size of the register area bytes, and
1074 * - \p type will be DRM_REGISTERS.
1076 * The area mapped will be uncached.
1078 * \par Mapping the SAREA
1080 * - \p offset will be ignored and should be set to zero,
1081 * - \p size will be the desired size of the SAREA in bytes,
1082 * - \p type will be DRM_SHM.
1085 * A shared memory area of the requested size will be created and locked in
1086 * kernel memory. This area may be mapped into client-space by using the handle
1089 * \note May only be called by root.
1092 * This function is a wrapper around the DRM_IOCTL_ADD_MAP ioctl, passing
1093 * the arguments in a drm_map structure.
1095 drm_public int drmAddMap(int fd, drm_handle_t offset, drmSize size, drmMapType type,
1096 drmMapFlags flags, drm_handle_t *handle)
1101 map.offset = offset;
1105 if (drmIoctl(fd, DRM_IOCTL_ADD_MAP, &map))
1108 *handle = (drm_handle_t)(uintptr_t)map.handle;
1112 drm_public int drmRmMap(int fd, drm_handle_t handle)
1117 map.handle = (void *)(uintptr_t)handle;
1119 if(drmIoctl(fd, DRM_IOCTL_RM_MAP, &map))
1125 * Make buffers available for DMA transfers.
1127 * \param fd file descriptor.
1128 * \param count number of buffers.
1129 * \param size size of each buffer.
1130 * \param flags buffer allocation flags.
1131 * \param agp_offset offset in the AGP aperture
1133 * \return number of buffers allocated, negative on error.
1136 * This function is a wrapper around DRM_IOCTL_ADD_BUFS ioctl.
1140 drm_public int drmAddBufs(int fd, int count, int size, drmBufDescFlags flags,
1143 drm_buf_desc_t request;
1146 request.count = count;
1147 request.size = size;
1148 request.flags = flags;
1149 request.agp_start = agp_offset;
1151 if (drmIoctl(fd, DRM_IOCTL_ADD_BUFS, &request))
1153 return request.count;
1156 drm_public int drmMarkBufs(int fd, double low, double high)
1158 drm_buf_info_t info;
1163 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1169 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1172 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1173 int retval = -errno;
1178 for (i = 0; i < info.count; i++) {
1179 info.list[i].low_mark = low * info.list[i].count;
1180 info.list[i].high_mark = high * info.list[i].count;
1181 if (drmIoctl(fd, DRM_IOCTL_MARK_BUFS, &info.list[i])) {
1182 int retval = -errno;
1195 * \param fd file descriptor.
1196 * \param count number of buffers to free.
1197 * \param list list of buffers to be freed.
1199 * \return zero on success, or a negative value on failure.
1201 * \note This function is primarily used for debugging.
1204 * This function is a wrapper around the DRM_IOCTL_FREE_BUFS ioctl, passing
1205 * the arguments in a drm_buf_free structure.
1207 drm_public int drmFreeBufs(int fd, int count, int *list)
1209 drm_buf_free_t request;
1212 request.count = count;
1213 request.list = list;
1214 if (drmIoctl(fd, DRM_IOCTL_FREE_BUFS, &request))
1223 * \param fd file descriptor.
1226 * This function closes the file descriptor.
1228 drm_public int drmClose(int fd)
1230 unsigned long key = drmGetKeyFromFd(fd);
1231 drmHashEntry *entry = drmGetEntry(fd);
1233 drmHashDestroy(entry->tagTable);
1236 entry->tagTable = NULL;
1238 drmHashDelete(drmHashTable, key);
1246 * Map a region of memory.
1248 * \param fd file descriptor.
1249 * \param handle handle returned by drmAddMap().
1250 * \param size size in bytes. Must match the size used by drmAddMap().
1251 * \param address will contain the user-space virtual address where the mapping
1254 * \return zero on success, or a negative value on failure.
1257 * This function is a wrapper for mmap().
1259 drm_public int drmMap(int fd, drm_handle_t handle, drmSize size,
1260 drmAddressPtr address)
1262 static unsigned long pagesize_mask = 0;
1268 pagesize_mask = getpagesize() - 1;
1270 size = (size + pagesize_mask) & ~pagesize_mask;
1272 *address = drm_mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1273 if (*address == MAP_FAILED)
1280 * Unmap mappings obtained with drmMap().
1282 * \param address address as given by drmMap().
1283 * \param size size in bytes. Must match the size used by drmMap().
1285 * \return zero on success, or a negative value on failure.
1288 * This function is a wrapper for munmap().
1290 drm_public int drmUnmap(drmAddress address, drmSize size)
1292 return drm_munmap(address, size);
1295 drm_public drmBufInfoPtr drmGetBufInfo(int fd)
1297 drm_buf_info_t info;
1298 drmBufInfoPtr retval;
1303 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1307 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1310 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1315 retval = drmMalloc(sizeof(*retval));
1316 retval->count = info.count;
1317 retval->list = drmMalloc(info.count * sizeof(*retval->list));
1318 for (i = 0; i < info.count; i++) {
1319 retval->list[i].count = info.list[i].count;
1320 retval->list[i].size = info.list[i].size;
1321 retval->list[i].low_mark = info.list[i].low_mark;
1322 retval->list[i].high_mark = info.list[i].high_mark;
1331 * Map all DMA buffers into client-virtual space.
1333 * \param fd file descriptor.
1335 * \return a pointer to a ::drmBufMap structure.
1337 * \note The client may not use these buffers until obtaining buffer indices
1341 * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1342 * information about the buffers in a drm_buf_map structure into the
1343 * client-visible data structures.
1345 drm_public drmBufMapPtr drmMapBufs(int fd)
1348 drmBufMapPtr retval;
1352 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1358 if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1361 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1366 retval = drmMalloc(sizeof(*retval));
1367 retval->count = bufs.count;
1368 retval->list = drmMalloc(bufs.count * sizeof(*retval->list));
1369 for (i = 0; i < bufs.count; i++) {
1370 retval->list[i].idx = bufs.list[i].idx;
1371 retval->list[i].total = bufs.list[i].total;
1372 retval->list[i].used = 0;
1373 retval->list[i].address = bufs.list[i].address;
1382 * Unmap buffers allocated with drmMapBufs().
1384 * \return zero on success, or negative value on failure.
1387 * Calls munmap() for every buffer stored in \p bufs and frees the
1388 * memory allocated by drmMapBufs().
1390 drm_public int drmUnmapBufs(drmBufMapPtr bufs)
1394 for (i = 0; i < bufs->count; i++) {
1395 drm_munmap(bufs->list[i].address, bufs->list[i].total);
1398 drmFree(bufs->list);
1404 #define DRM_DMA_RETRY 16
1407 * Reserve DMA buffers.
1409 * \param fd file descriptor.
1412 * \return zero on success, or a negative value on failure.
1415 * Assemble the arguments into a drm_dma structure and keeps issuing the
1416 * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1418 drm_public int drmDMA(int fd, drmDMAReqPtr request)
1423 dma.context = request->context;
1424 dma.send_count = request->send_count;
1425 dma.send_indices = request->send_list;
1426 dma.send_sizes = request->send_sizes;
1427 dma.flags = request->flags;
1428 dma.request_count = request->request_count;
1429 dma.request_size = request->request_size;
1430 dma.request_indices = request->request_list;
1431 dma.request_sizes = request->request_sizes;
1432 dma.granted_count = 0;
1435 ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1436 } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1439 request->granted_count = dma.granted_count;
1448 * Obtain heavyweight hardware lock.
1450 * \param fd file descriptor.
1451 * \param context context.
1452 * \param flags flags that determine the state of the hardware when the function
1455 * \return always zero.
1458 * This function translates the arguments into a drm_lock structure and issue
1459 * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1461 drm_public int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
1466 lock.context = context;
1468 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
1469 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
1470 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
1471 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
1472 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
1473 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
1475 while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
1481 * Release the hardware lock.
1483 * \param fd file descriptor.
1484 * \param context context.
1486 * \return zero on success, or a negative value on failure.
1489 * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
1490 * argument in a drm_lock structure.
1492 drm_public int drmUnlock(int fd, drm_context_t context)
1497 lock.context = context;
1498 return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
1501 drm_public drm_context_t *drmGetReservedContextList(int fd, int *count)
1505 drm_context_t * retval;
1509 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1515 if (!(list = drmMalloc(res.count * sizeof(*list))))
1517 if (!(retval = drmMalloc(res.count * sizeof(*retval))))
1520 res.contexts = list;
1521 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1522 goto err_free_context;
1524 for (i = 0; i < res.count; i++)
1525 retval[i] = list[i].handle;
1538 drm_public void drmFreeReservedContextList(drm_context_t *pt)
1546 * Used by the X server during GLXContext initialization. This causes
1547 * per-context kernel-level resources to be allocated.
1549 * \param fd file descriptor.
1550 * \param handle is set on success. To be used by the client when requesting DMA
1551 * dispatch with drmDMA().
1553 * \return zero on success, or a negative value on failure.
1555 * \note May only be called by root.
1558 * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
1559 * argument in a drm_ctx structure.
1561 drm_public int drmCreateContext(int fd, drm_context_t *handle)
1566 if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
1568 *handle = ctx.handle;
1572 drm_public int drmSwitchToContext(int fd, drm_context_t context)
1577 ctx.handle = context;
1578 if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
1583 drm_public int drmSetContextFlags(int fd, drm_context_t context,
1584 drm_context_tFlags flags)
1589 * Context preserving means that no context switches are done between DMA
1590 * buffers from one context and the next. This is suitable for use in the
1591 * X server (which promises to maintain hardware context), or in the
1592 * client-side library when buffers are swapped on behalf of two threads.
1595 ctx.handle = context;
1596 if (flags & DRM_CONTEXT_PRESERVED)
1597 ctx.flags |= _DRM_CONTEXT_PRESERVED;
1598 if (flags & DRM_CONTEXT_2DONLY)
1599 ctx.flags |= _DRM_CONTEXT_2DONLY;
1600 if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
1605 drm_public int drmGetContextFlags(int fd, drm_context_t context,
1606 drm_context_tFlagsPtr flags)
1611 ctx.handle = context;
1612 if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
1615 if (ctx.flags & _DRM_CONTEXT_PRESERVED)
1616 *flags |= DRM_CONTEXT_PRESERVED;
1617 if (ctx.flags & _DRM_CONTEXT_2DONLY)
1618 *flags |= DRM_CONTEXT_2DONLY;
1625 * Free any kernel-level resources allocated with drmCreateContext() associated
1628 * \param fd file descriptor.
1629 * \param handle handle given by drmCreateContext().
1631 * \return zero on success, or a negative value on failure.
1633 * \note May only be called by root.
1636 * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
1637 * argument in a drm_ctx structure.
1639 drm_public int drmDestroyContext(int fd, drm_context_t handle)
1644 ctx.handle = handle;
1645 if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
1650 drm_public int drmCreateDrawable(int fd, drm_drawable_t *handle)
1655 if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
1657 *handle = draw.handle;
1661 drm_public int drmDestroyDrawable(int fd, drm_drawable_t handle)
1666 draw.handle = handle;
1667 if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
1672 drm_public int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
1673 drm_drawable_info_type_t type,
1674 unsigned int num, void *data)
1676 drm_update_draw_t update;
1679 update.handle = handle;
1682 update.data = (unsigned long long)(unsigned long)data;
1684 if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
1690 drm_public int drmCrtcGetSequence(int fd, uint32_t crtcId, uint64_t *sequence,
1693 struct drm_crtc_get_sequence get_seq;
1697 get_seq.crtc_id = crtcId;
1698 ret = drmIoctl(fd, DRM_IOCTL_CRTC_GET_SEQUENCE, &get_seq);
1703 *sequence = get_seq.sequence;
1705 *ns = get_seq.sequence_ns;
1709 drm_public int drmCrtcQueueSequence(int fd, uint32_t crtcId, uint32_t flags,
1711 uint64_t *sequence_queued,
1714 struct drm_crtc_queue_sequence queue_seq;
1717 memclear(queue_seq);
1718 queue_seq.crtc_id = crtcId;
1719 queue_seq.flags = flags;
1720 queue_seq.sequence = sequence;
1721 queue_seq.user_data = user_data;
1723 ret = drmIoctl(fd, DRM_IOCTL_CRTC_QUEUE_SEQUENCE, &queue_seq);
1724 if (ret == 0 && sequence_queued)
1725 *sequence_queued = queue_seq.sequence;
1731 * Acquire the AGP device.
1733 * Must be called before any of the other AGP related calls.
1735 * \param fd file descriptor.
1737 * \return zero on success, or a negative value on failure.
1740 * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
1742 drm_public int drmAgpAcquire(int fd)
1744 if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
1751 * Release the AGP device.
1753 * \param fd file descriptor.
1755 * \return zero on success, or a negative value on failure.
1758 * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
1760 drm_public int drmAgpRelease(int fd)
1762 if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
1771 * \param fd file descriptor.
1772 * \param mode AGP mode.
1774 * \return zero on success, or a negative value on failure.
1777 * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
1778 * argument in a drm_agp_mode structure.
1780 drm_public int drmAgpEnable(int fd, unsigned long mode)
1786 if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
1793 * Allocate a chunk of AGP memory.
1795 * \param fd file descriptor.
1796 * \param size requested memory size in bytes. Will be rounded to page boundary.
1797 * \param type type of memory to allocate.
1798 * \param address if not zero, will be set to the physical address of the
1800 * \param handle on success will be set to a handle of the allocated memory.
1802 * \return zero on success, or a negative value on failure.
1805 * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
1806 * arguments in a drm_agp_buffer structure.
1808 drm_public int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
1809 unsigned long *address, drm_handle_t *handle)
1814 *handle = DRM_AGP_NO_HANDLE;
1817 if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
1820 *address = b.physical;
1827 * Free a chunk of AGP memory.
1829 * \param fd file descriptor.
1830 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1832 * \return zero on success, or a negative value on failure.
1835 * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
1836 * argument in a drm_agp_buffer structure.
1838 drm_public int drmAgpFree(int fd, drm_handle_t handle)
1844 if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
1851 * Bind a chunk of AGP memory.
1853 * \param fd file descriptor.
1854 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1855 * \param offset offset in bytes. It will round to page boundary.
1857 * \return zero on success, or a negative value on failure.
1860 * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
1861 * argument in a drm_agp_binding structure.
1863 drm_public int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
1865 drm_agp_binding_t b;
1870 if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
1877 * Unbind a chunk of AGP memory.
1879 * \param fd file descriptor.
1880 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1882 * \return zero on success, or a negative value on failure.
1885 * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
1886 * the argument in a drm_agp_binding structure.
1888 drm_public int drmAgpUnbind(int fd, drm_handle_t handle)
1890 drm_agp_binding_t b;
1894 if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
1901 * Get AGP driver major version number.
1903 * \param fd file descriptor.
1905 * \return major version number on success, or a negative value on failure..
1908 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1909 * necessary information in a drm_agp_info structure.
1911 drm_public int drmAgpVersionMajor(int fd)
1917 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1919 return i.agp_version_major;
1924 * Get AGP driver minor version number.
1926 * \param fd file descriptor.
1928 * \return minor version number on success, or a negative value on failure.
1931 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1932 * necessary information in a drm_agp_info structure.
1934 drm_public int drmAgpVersionMinor(int fd)
1940 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1942 return i.agp_version_minor;
1949 * \param fd file descriptor.
1951 * \return mode on success, or zero on failure.
1954 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1955 * necessary information in a drm_agp_info structure.
1957 drm_public unsigned long drmAgpGetMode(int fd)
1963 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1970 * Get AGP aperture base.
1972 * \param fd file descriptor.
1974 * \return aperture base on success, zero on failure.
1977 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1978 * necessary information in a drm_agp_info structure.
1980 drm_public unsigned long drmAgpBase(int fd)
1986 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1988 return i.aperture_base;
1993 * Get AGP aperture size.
1995 * \param fd file descriptor.
1997 * \return aperture size on success, zero on failure.
2000 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2001 * necessary information in a drm_agp_info structure.
2003 drm_public unsigned long drmAgpSize(int fd)
2009 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2011 return i.aperture_size;
2016 * Get used AGP memory.
2018 * \param fd file descriptor.
2020 * \return memory used on success, or zero on failure.
2023 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2024 * necessary information in a drm_agp_info structure.
2026 drm_public unsigned long drmAgpMemoryUsed(int fd)
2032 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2034 return i.memory_used;
2039 * Get available AGP memory.
2041 * \param fd file descriptor.
2043 * \return memory available on success, or zero on failure.
2046 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2047 * necessary information in a drm_agp_info structure.
2049 drm_public unsigned long drmAgpMemoryAvail(int fd)
2055 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2057 return i.memory_allowed;
2062 * Get hardware vendor ID.
2064 * \param fd file descriptor.
2066 * \return vendor ID on success, or zero on failure.
2069 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2070 * necessary information in a drm_agp_info structure.
2072 drm_public unsigned int drmAgpVendorId(int fd)
2078 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2085 * Get hardware device ID.
2087 * \param fd file descriptor.
2089 * \return zero on success, or zero on failure.
2092 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2093 * necessary information in a drm_agp_info structure.
2095 drm_public unsigned int drmAgpDeviceId(int fd)
2101 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2106 drm_public int drmScatterGatherAlloc(int fd, unsigned long size,
2107 drm_handle_t *handle)
2109 drm_scatter_gather_t sg;
2115 if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
2117 *handle = sg.handle;
2121 drm_public int drmScatterGatherFree(int fd, drm_handle_t handle)
2123 drm_scatter_gather_t sg;
2127 if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
2135 * \param fd file descriptor.
2136 * \param vbl pointer to a drmVBlank structure.
2138 * \return zero on success, or a negative value on failure.
2141 * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
2143 drm_public int drmWaitVBlank(int fd, drmVBlankPtr vbl)
2145 struct timespec timeout, cur;
2148 ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2150 fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
2156 ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
2157 vbl->request.type &= ~DRM_VBLANK_RELATIVE;
2158 if (ret && errno == EINTR) {
2159 clock_gettime(CLOCK_MONOTONIC, &cur);
2160 /* Timeout after 1s */
2161 if (cur.tv_sec > timeout.tv_sec + 1 ||
2162 (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
2169 } while (ret && errno == EINTR);
2175 drm_public int drmError(int err, const char *label)
2178 case DRM_ERR_NO_DEVICE:
2179 fprintf(stderr, "%s: no device\n", label);
2181 case DRM_ERR_NO_ACCESS:
2182 fprintf(stderr, "%s: no access\n", label);
2184 case DRM_ERR_NOT_ROOT:
2185 fprintf(stderr, "%s: not root\n", label);
2187 case DRM_ERR_INVALID:
2188 fprintf(stderr, "%s: invalid args\n", label);
2193 fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2201 * Install IRQ handler.
2203 * \param fd file descriptor.
2204 * \param irq IRQ number.
2206 * \return zero on success, or a negative value on failure.
2209 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2210 * argument in a drm_control structure.
2212 drm_public int drmCtlInstHandler(int fd, int irq)
2217 ctl.func = DRM_INST_HANDLER;
2219 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2226 * Uninstall IRQ handler.
2228 * \param fd file descriptor.
2230 * \return zero on success, or a negative value on failure.
2233 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2234 * argument in a drm_control structure.
2236 drm_public int drmCtlUninstHandler(int fd)
2241 ctl.func = DRM_UNINST_HANDLER;
2243 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2248 drm_public int drmFinish(int fd, int context, drmLockFlags flags)
2253 lock.context = context;
2254 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
2255 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
2256 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
2257 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
2258 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2259 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2260 if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2266 * Get IRQ from bus ID.
2268 * \param fd file descriptor.
2269 * \param busnum bus number.
2270 * \param devnum device number.
2271 * \param funcnum function number.
2273 * \return IRQ number on success, or a negative value on failure.
2276 * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2277 * arguments in a drm_irq_busid structure.
2279 drm_public int drmGetInterruptFromBusID(int fd, int busnum, int devnum,
2287 p.funcnum = funcnum;
2288 if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2293 drm_public int drmAddContextTag(int fd, drm_context_t context, void *tag)
2295 drmHashEntry *entry = drmGetEntry(fd);
2297 if (drmHashInsert(entry->tagTable, context, tag)) {
2298 drmHashDelete(entry->tagTable, context);
2299 drmHashInsert(entry->tagTable, context, tag);
2304 drm_public int drmDelContextTag(int fd, drm_context_t context)
2306 drmHashEntry *entry = drmGetEntry(fd);
2308 return drmHashDelete(entry->tagTable, context);
2311 drm_public void *drmGetContextTag(int fd, drm_context_t context)
2313 drmHashEntry *entry = drmGetEntry(fd);
2316 if (drmHashLookup(entry->tagTable, context, &value))
2322 drm_public int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2323 drm_handle_t handle)
2325 drm_ctx_priv_map_t map;
2328 map.ctx_id = ctx_id;
2329 map.handle = (void *)(uintptr_t)handle;
2331 if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2336 drm_public int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2337 drm_handle_t *handle)
2339 drm_ctx_priv_map_t map;
2342 map.ctx_id = ctx_id;
2344 if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2347 *handle = (drm_handle_t)(uintptr_t)map.handle;
2352 drm_public int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2353 drmMapType *type, drmMapFlags *flags,
2354 drm_handle_t *handle, int *mtrr)
2360 if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2362 *offset = map.offset;
2366 *handle = (unsigned long)map.handle;
2371 drm_public int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2372 unsigned long *magic, unsigned long *iocs)
2374 drm_client_t client;
2378 if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2380 *auth = client.auth;
2383 *magic = client.magic;
2384 *iocs = client.iocs;
2388 drm_public int drmGetStats(int fd, drmStatsT *stats)
2394 if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2398 memset(stats, 0, sizeof(*stats));
2399 if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2403 stats->data[i].long_format = "%-20.20s"; \
2404 stats->data[i].rate_format = "%8.8s"; \
2405 stats->data[i].isvalue = 1; \
2406 stats->data[i].verbose = 0
2409 stats->data[i].long_format = "%-20.20s"; \
2410 stats->data[i].rate_format = "%5.5s"; \
2411 stats->data[i].isvalue = 0; \
2412 stats->data[i].mult_names = "kgm"; \
2413 stats->data[i].mult = 1000; \
2414 stats->data[i].verbose = 0
2417 stats->data[i].long_format = "%-20.20s"; \
2418 stats->data[i].rate_format = "%5.5s"; \
2419 stats->data[i].isvalue = 0; \
2420 stats->data[i].mult_names = "KGM"; \
2421 stats->data[i].mult = 1024; \
2422 stats->data[i].verbose = 0
2425 stats->count = s.count;
2426 for (i = 0; i < s.count; i++) {
2427 stats->data[i].value = s.data[i].value;
2428 switch (s.data[i].type) {
2429 case _DRM_STAT_LOCK:
2430 stats->data[i].long_name = "Lock";
2431 stats->data[i].rate_name = "Lock";
2434 case _DRM_STAT_OPENS:
2435 stats->data[i].long_name = "Opens";
2436 stats->data[i].rate_name = "O";
2438 stats->data[i].verbose = 1;
2440 case _DRM_STAT_CLOSES:
2441 stats->data[i].long_name = "Closes";
2442 stats->data[i].rate_name = "Lock";
2444 stats->data[i].verbose = 1;
2446 case _DRM_STAT_IOCTLS:
2447 stats->data[i].long_name = "Ioctls";
2448 stats->data[i].rate_name = "Ioc/s";
2451 case _DRM_STAT_LOCKS:
2452 stats->data[i].long_name = "Locks";
2453 stats->data[i].rate_name = "Lck/s";
2456 case _DRM_STAT_UNLOCKS:
2457 stats->data[i].long_name = "Unlocks";
2458 stats->data[i].rate_name = "Unl/s";
2462 stats->data[i].long_name = "IRQs";
2463 stats->data[i].rate_name = "IRQ/s";
2466 case _DRM_STAT_PRIMARY:
2467 stats->data[i].long_name = "Primary Bytes";
2468 stats->data[i].rate_name = "PB/s";
2471 case _DRM_STAT_SECONDARY:
2472 stats->data[i].long_name = "Secondary Bytes";
2473 stats->data[i].rate_name = "SB/s";
2477 stats->data[i].long_name = "DMA";
2478 stats->data[i].rate_name = "DMA/s";
2481 case _DRM_STAT_SPECIAL:
2482 stats->data[i].long_name = "Special DMA";
2483 stats->data[i].rate_name = "dma/s";
2486 case _DRM_STAT_MISSED:
2487 stats->data[i].long_name = "Miss";
2488 stats->data[i].rate_name = "Ms/s";
2491 case _DRM_STAT_VALUE:
2492 stats->data[i].long_name = "Value";
2493 stats->data[i].rate_name = "Value";
2496 case _DRM_STAT_BYTE:
2497 stats->data[i].long_name = "Bytes";
2498 stats->data[i].rate_name = "B/s";
2501 case _DRM_STAT_COUNT:
2503 stats->data[i].long_name = "Count";
2504 stats->data[i].rate_name = "Cnt/s";
2513 * Issue a set-version ioctl.
2515 * \param fd file descriptor.
2516 * \param drmCommandIndex command index
2517 * \param data source pointer of the data to be read and written.
2518 * \param size size of the data to be read and written.
2520 * \return zero on success, or a negative value on failure.
2523 * It issues a read-write ioctl given by
2524 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2526 drm_public int drmSetInterfaceVersion(int fd, drmSetVersion *version)
2529 drm_set_version_t sv;
2532 sv.drm_di_major = version->drm_di_major;
2533 sv.drm_di_minor = version->drm_di_minor;
2534 sv.drm_dd_major = version->drm_dd_major;
2535 sv.drm_dd_minor = version->drm_dd_minor;
2537 if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
2541 version->drm_di_major = sv.drm_di_major;
2542 version->drm_di_minor = sv.drm_di_minor;
2543 version->drm_dd_major = sv.drm_dd_major;
2544 version->drm_dd_minor = sv.drm_dd_minor;
2550 * Send a device-specific command.
2552 * \param fd file descriptor.
2553 * \param drmCommandIndex command index
2555 * \return zero on success, or a negative value on failure.
2558 * It issues a ioctl given by
2559 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2561 drm_public int drmCommandNone(int fd, unsigned long drmCommandIndex)
2563 unsigned long request;
2565 request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
2567 if (drmIoctl(fd, request, NULL)) {
2575 * Send a device-specific read command.
2577 * \param fd file descriptor.
2578 * \param drmCommandIndex command index
2579 * \param data destination pointer of the data to be read.
2580 * \param size size of the data to be read.
2582 * \return zero on success, or a negative value on failure.
2585 * It issues a read ioctl given by
2586 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2588 drm_public int drmCommandRead(int fd, unsigned long drmCommandIndex,
2589 void *data, unsigned long size)
2591 unsigned long request;
2593 request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
2594 DRM_COMMAND_BASE + drmCommandIndex, size);
2596 if (drmIoctl(fd, request, data)) {
2604 * Send a device-specific write command.
2606 * \param fd file descriptor.
2607 * \param drmCommandIndex command index
2608 * \param data source pointer of the data to be written.
2609 * \param size size of the data to be written.
2611 * \return zero on success, or a negative value on failure.
2614 * It issues a write ioctl given by
2615 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2617 drm_public int drmCommandWrite(int fd, unsigned long drmCommandIndex,
2618 void *data, unsigned long size)
2620 unsigned long request;
2622 request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
2623 DRM_COMMAND_BASE + drmCommandIndex, size);
2625 if (drmIoctl(fd, request, data)) {
2633 * Send a device-specific read-write command.
2635 * \param fd file descriptor.
2636 * \param drmCommandIndex command index
2637 * \param data source pointer of the data to be read and written.
2638 * \param size size of the data to be read and written.
2640 * \return zero on success, or a negative value on failure.
2643 * It issues a read-write ioctl given by
2644 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2646 drm_public int drmCommandWriteRead(int fd, unsigned long drmCommandIndex,
2647 void *data, unsigned long size)
2649 unsigned long request;
2651 request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
2652 DRM_COMMAND_BASE + drmCommandIndex, size);
2654 if (drmIoctl(fd, request, data))
2659 #define DRM_MAX_FDS 16
2665 } connection[DRM_MAX_FDS];
2667 static int nr_fds = 0;
2669 drm_public int drmOpenOnce(void *unused, const char *BusID, int *newlyopened)
2671 return drmOpenOnceWithType(BusID, newlyopened, DRM_NODE_PRIMARY);
2674 drm_public int drmOpenOnceWithType(const char *BusID, int *newlyopened,
2680 for (i = 0; i < nr_fds; i++)
2681 if ((strcmp(BusID, connection[i].BusID) == 0) &&
2682 (connection[i].type == type)) {
2683 connection[i].refcount++;
2685 return connection[i].fd;
2688 fd = drmOpenWithType(NULL, BusID, type);
2689 if (fd < 0 || nr_fds == DRM_MAX_FDS)
2692 connection[nr_fds].BusID = strdup(BusID);
2693 connection[nr_fds].fd = fd;
2694 connection[nr_fds].refcount = 1;
2695 connection[nr_fds].type = type;
2699 fprintf(stderr, "saved connection %d for %s %d\n",
2700 nr_fds, connection[nr_fds].BusID,
2701 strcmp(BusID, connection[nr_fds].BusID));
2708 drm_public void drmCloseOnce(int fd)
2712 for (i = 0; i < nr_fds; i++) {
2713 if (fd == connection[i].fd) {
2714 if (--connection[i].refcount == 0) {
2715 drmClose(connection[i].fd);
2716 free(connection[i].BusID);
2719 connection[i] = connection[nr_fds];
2727 drm_public int drmSetMaster(int fd)
2729 return drmIoctl(fd, DRM_IOCTL_SET_MASTER, NULL);
2732 drm_public int drmDropMaster(int fd)
2734 return drmIoctl(fd, DRM_IOCTL_DROP_MASTER, NULL);
2737 drm_public int drmIsMaster(int fd)
2739 /* Detect master by attempting something that requires master.
2741 * Authenticating magic tokens requires master and 0 is an
2742 * internal kernel detail which we could use. Attempting this on
2743 * a master fd would fail therefore fail with EINVAL because 0
2746 * A non-master fd will fail with EACCES, as the kernel checks
2747 * for master before attempting to do anything else.
2749 * Since we don't want to leak implementation details, use
2752 return drmAuthMagic(fd, 0) != -EACCES;
2755 drm_public char *drmGetDeviceNameFromFd(int fd)
2762 /* The whole drmOpen thing is a fiasco and we need to find a way
2763 * back to just using open(2). For now, however, lets just make
2764 * things worse with even more ad hoc directory walking code to
2765 * discover the device file name. */
2770 for (i = 0; i < DRM_MAX_MINOR; i++) {
2771 snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
2772 if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
2775 if (i == DRM_MAX_MINOR)
2778 return strdup(name);
2781 static bool drmNodeIsDRM(int maj, int min)
2787 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device/drm",
2789 return stat(path, &sbuf) == 0;
2791 return maj == DRM_MAJOR;
2795 drm_public int drmGetNodeTypeFromFd(int fd)
2800 if (fstat(fd, &sbuf))
2803 maj = major(sbuf.st_rdev);
2804 min = minor(sbuf.st_rdev);
2806 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode)) {
2811 type = drmGetMinorType(min);
2817 drm_public int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags,
2820 struct drm_prime_handle args;
2825 args.handle = handle;
2827 ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
2831 *prime_fd = args.fd;
2835 drm_public int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
2837 struct drm_prime_handle args;
2842 ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
2846 *handle = args.handle;
2850 static char *drmGetMinorNameForFD(int fd, int type)
2856 const char *name = drmGetMinorName(type);
2858 char dev_name[64], buf[64];
2866 if (fstat(fd, &sbuf))
2869 maj = major(sbuf.st_rdev);
2870 min = minor(sbuf.st_rdev);
2872 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
2875 snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
2877 sysdir = opendir(buf);
2881 while ((ent = readdir(sysdir))) {
2882 if (strncmp(ent->d_name, name, len) == 0) {
2883 snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
2887 return strdup(dev_name);
2895 char buf[PATH_MAX + 1];
2896 const char *dev_name = drmGetDeviceName(type);
2897 unsigned int maj, min;
2900 if (fstat(fd, &sbuf))
2903 maj = major(sbuf.st_rdev);
2904 min = minor(sbuf.st_rdev);
2906 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
2912 n = snprintf(buf, sizeof(buf), dev_name, DRM_DIR_NAME, min);
2913 if (n == -1 || n >= sizeof(buf))
2920 drm_public char *drmGetPrimaryDeviceNameFromFd(int fd)
2922 return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
2925 drm_public char *drmGetRenderDeviceNameFromFd(int fd)
2927 return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
2931 static char * DRM_PRINTFLIKE(2, 3)
2932 sysfs_uevent_get(const char *path, const char *fmt, ...)
2934 char filename[PATH_MAX + 1], *key, *line = NULL, *value = NULL;
2935 size_t size = 0, len;
2941 num = vasprintf(&key, fmt, ap);
2945 snprintf(filename, sizeof(filename), "%s/uevent", path);
2947 fp = fopen(filename, "r");
2953 while ((num = getline(&line, &size, fp)) >= 0) {
2954 if ((strncmp(line, key, len) == 0) && (line[len] == '=')) {
2955 char *start = line + len + 1, *end = line + num - 1;
2960 value = strndup(start, end - start);
2974 /* Little white lie to avoid major rework of the existing code */
2975 #define DRM_BUS_VIRTIO 0x10
2977 static int drmParseSubsystemType(int maj, int min)
2980 char path[PATH_MAX + 1];
2981 char link[PATH_MAX + 1] = "";
2987 { "/pci", DRM_BUS_PCI },
2988 { "/usb", DRM_BUS_USB },
2989 { "/platform", DRM_BUS_PLATFORM },
2990 { "/spi", DRM_BUS_PLATFORM },
2991 { "/host1x", DRM_BUS_HOST1X },
2992 { "/virtio", DRM_BUS_VIRTIO },
2995 snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/subsystem",
2998 if (readlink(path, link, PATH_MAX) < 0)
3001 name = strrchr(link, '/');
3005 for (unsigned i = 0; i < ARRAY_SIZE(bus_types); i++) {
3006 if (strncmp(name, bus_types[i].name, strlen(bus_types[i].name)) == 0)
3007 return bus_types[i].bus_type;
3011 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3014 #warning "Missing implementation of drmParseSubsystemType"
3020 get_pci_path(int maj, int min, char *pci_path)
3022 char path[PATH_MAX + 1], *term;
3024 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3025 if (!realpath(path, pci_path)) {
3026 strcpy(pci_path, path);
3030 term = strrchr(pci_path, '/');
3031 if (term && strncmp(term, "/virtio", 7) == 0)
3035 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
3038 unsigned int domain, bus, dev, func;
3039 char pci_path[PATH_MAX + 1], *value;
3042 get_pci_path(maj, min, pci_path);
3044 value = sysfs_uevent_get(pci_path, "PCI_SLOT_NAME");
3048 num = sscanf(value, "%04x:%02x:%02x.%1u", &domain, &bus, &dev, &func);
3054 info->domain = domain;
3060 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3061 struct drm_pciinfo pinfo;
3064 type = drmGetMinorType(min);
3068 fd = drmOpenMinor(min, 0, type);
3072 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3078 info->domain = pinfo.domain;
3079 info->bus = pinfo.bus;
3080 info->dev = pinfo.dev;
3081 info->func = pinfo.func;
3085 #warning "Missing implementation of drmParsePciBusInfo"
3090 drm_public int drmDevicesEqual(drmDevicePtr a, drmDevicePtr b)
3092 if (a == NULL || b == NULL)
3095 if (a->bustype != b->bustype)
3098 switch (a->bustype) {
3100 return memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo)) == 0;
3103 return memcmp(a->businfo.usb, b->businfo.usb, sizeof(drmUsbBusInfo)) == 0;
3105 case DRM_BUS_PLATFORM:
3106 return memcmp(a->businfo.platform, b->businfo.platform, sizeof(drmPlatformBusInfo)) == 0;
3108 case DRM_BUS_HOST1X:
3109 return memcmp(a->businfo.host1x, b->businfo.host1x, sizeof(drmHost1xBusInfo)) == 0;
3118 static int drmGetNodeType(const char *name)
3120 if (strncmp(name, DRM_CONTROL_MINOR_NAME,
3121 sizeof(DRM_CONTROL_MINOR_NAME ) - 1) == 0)
3122 return DRM_NODE_CONTROL;
3124 if (strncmp(name, DRM_RENDER_MINOR_NAME,
3125 sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
3126 return DRM_NODE_RENDER;
3128 if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
3129 sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
3130 return DRM_NODE_PRIMARY;
3135 static int drmGetMaxNodeName(void)
3137 return sizeof(DRM_DIR_NAME) +
3138 MAX3(sizeof(DRM_PRIMARY_MINOR_NAME),
3139 sizeof(DRM_CONTROL_MINOR_NAME),
3140 sizeof(DRM_RENDER_MINOR_NAME)) +
3141 3 /* length of the node number */;
3145 static int parse_separate_sysfs_files(int maj, int min,
3146 drmPciDeviceInfoPtr device,
3147 bool ignore_revision)
3149 static const char *attrs[] = {
3150 "revision", /* Older kernels are missing the file, so check for it first */
3156 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3157 unsigned int data[ARRAY_SIZE(attrs)];
3161 get_pci_path(maj, min, pci_path);
3163 for (unsigned i = ignore_revision ? 1 : 0; i < ARRAY_SIZE(attrs); i++) {
3164 snprintf(path, PATH_MAX, "%s/%s", pci_path, attrs[i]);
3165 fp = fopen(path, "r");
3169 ret = fscanf(fp, "%x", &data[i]);
3176 device->revision_id = ignore_revision ? 0xff : data[0] & 0xff;
3177 device->vendor_id = data[1] & 0xffff;
3178 device->device_id = data[2] & 0xffff;
3179 device->subvendor_id = data[3] & 0xffff;
3180 device->subdevice_id = data[4] & 0xffff;
3185 static int parse_config_sysfs_file(int maj, int min,
3186 drmPciDeviceInfoPtr device)
3188 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3189 unsigned char config[64];
3192 get_pci_path(maj, min, pci_path);
3194 snprintf(path, PATH_MAX, "%s/config", pci_path);
3195 fd = open(path, O_RDONLY);
3199 ret = read(fd, config, sizeof(config));
3204 device->vendor_id = config[0] | (config[1] << 8);
3205 device->device_id = config[2] | (config[3] << 8);
3206 device->revision_id = config[8];
3207 device->subvendor_id = config[44] | (config[45] << 8);
3208 device->subdevice_id = config[46] | (config[47] << 8);
3214 static int drmParsePciDeviceInfo(int maj, int min,
3215 drmPciDeviceInfoPtr device,
3219 if (!(flags & DRM_DEVICE_GET_PCI_REVISION))
3220 return parse_separate_sysfs_files(maj, min, device, true);
3222 if (parse_separate_sysfs_files(maj, min, device, false))
3223 return parse_config_sysfs_file(maj, min, device);
3226 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3227 struct drm_pciinfo pinfo;
3230 type = drmGetMinorType(min);
3234 fd = drmOpenMinor(min, 0, type);
3238 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3244 device->vendor_id = pinfo.vendor_id;
3245 device->device_id = pinfo.device_id;
3246 device->revision_id = pinfo.revision_id;
3247 device->subvendor_id = pinfo.subvendor_id;
3248 device->subdevice_id = pinfo.subdevice_id;
3252 #warning "Missing implementation of drmParsePciDeviceInfo"
3257 static void drmFreePlatformDevice(drmDevicePtr device)
3259 if (device->deviceinfo.platform) {
3260 if (device->deviceinfo.platform->compatible) {
3261 char **compatible = device->deviceinfo.platform->compatible;
3263 while (*compatible) {
3268 free(device->deviceinfo.platform->compatible);
3273 static void drmFreeHost1xDevice(drmDevicePtr device)
3275 if (device->deviceinfo.host1x) {
3276 if (device->deviceinfo.host1x->compatible) {
3277 char **compatible = device->deviceinfo.host1x->compatible;
3279 while (*compatible) {
3284 free(device->deviceinfo.host1x->compatible);
3289 drm_public void drmFreeDevice(drmDevicePtr *device)
3295 switch ((*device)->bustype) {
3296 case DRM_BUS_PLATFORM:
3297 drmFreePlatformDevice(*device);
3300 case DRM_BUS_HOST1X:
3301 drmFreeHost1xDevice(*device);
3310 drm_public void drmFreeDevices(drmDevicePtr devices[], int count)
3314 if (devices == NULL)
3317 for (i = 0; i < count; i++)
3319 drmFreeDevice(&devices[i]);
3322 static drmDevicePtr drmDeviceAlloc(unsigned int type, const char *node,
3323 size_t bus_size, size_t device_size,
3326 size_t max_node_length, extra, size;
3327 drmDevicePtr device;
3331 max_node_length = ALIGN(drmGetMaxNodeName(), sizeof(void *));
3332 extra = DRM_NODE_MAX * (sizeof(void *) + max_node_length);
3334 size = sizeof(*device) + extra + bus_size + device_size;
3336 device = calloc(1, size);
3340 device->available_nodes = 1 << type;
3342 ptr = (char *)device + sizeof(*device);
3343 device->nodes = (char **)ptr;
3345 ptr += DRM_NODE_MAX * sizeof(void *);
3347 for (i = 0; i < DRM_NODE_MAX; i++) {
3348 device->nodes[i] = ptr;
3349 ptr += max_node_length;
3352 memcpy(device->nodes[type], node, max_node_length);
3359 static int drmProcessPciDevice(drmDevicePtr *device,
3360 const char *node, int node_type,
3361 int maj, int min, bool fetch_deviceinfo,
3368 dev = drmDeviceAlloc(node_type, node, sizeof(drmPciBusInfo),
3369 sizeof(drmPciDeviceInfo), &addr);
3373 dev->bustype = DRM_BUS_PCI;
3375 dev->businfo.pci = (drmPciBusInfoPtr)addr;
3377 ret = drmParsePciBusInfo(maj, min, dev->businfo.pci);
3381 // Fetch the device info if the user has requested it
3382 if (fetch_deviceinfo) {
3383 addr += sizeof(drmPciBusInfo);
3384 dev->deviceinfo.pci = (drmPciDeviceInfoPtr)addr;
3386 ret = drmParsePciDeviceInfo(maj, min, dev->deviceinfo.pci, flags);
3400 static int drmParseUsbBusInfo(int maj, int min, drmUsbBusInfoPtr info)
3403 char path[PATH_MAX + 1], *value;
3404 unsigned int bus, dev;
3407 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3409 value = sysfs_uevent_get(path, "BUSNUM");
3413 ret = sscanf(value, "%03u", &bus);
3419 value = sysfs_uevent_get(path, "DEVNUM");
3423 ret = sscanf(value, "%03u", &dev);
3434 #warning "Missing implementation of drmParseUsbBusInfo"
3439 static int drmParseUsbDeviceInfo(int maj, int min, drmUsbDeviceInfoPtr info)
3442 char path[PATH_MAX + 1], *value;
3443 unsigned int vendor, product;
3446 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3448 value = sysfs_uevent_get(path, "PRODUCT");
3452 ret = sscanf(value, "%x/%x", &vendor, &product);
3458 info->vendor = vendor;
3459 info->product = product;
3463 #warning "Missing implementation of drmParseUsbDeviceInfo"
3468 static int drmProcessUsbDevice(drmDevicePtr *device, const char *node,
3469 int node_type, int maj, int min,
3470 bool fetch_deviceinfo, uint32_t flags)
3476 dev = drmDeviceAlloc(node_type, node, sizeof(drmUsbBusInfo),
3477 sizeof(drmUsbDeviceInfo), &ptr);
3481 dev->bustype = DRM_BUS_USB;
3483 dev->businfo.usb = (drmUsbBusInfoPtr)ptr;
3485 ret = drmParseUsbBusInfo(maj, min, dev->businfo.usb);
3489 if (fetch_deviceinfo) {
3490 ptr += sizeof(drmUsbBusInfo);
3491 dev->deviceinfo.usb = (drmUsbDeviceInfoPtr)ptr;
3493 ret = drmParseUsbDeviceInfo(maj, min, dev->deviceinfo.usb);
3507 static int drmParseOFBusInfo(int maj, int min, char *fullname)
3510 char path[PATH_MAX + 1], *name, *tmp_name;
3512 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3514 name = sysfs_uevent_get(path, "OF_FULLNAME");
3517 /* If the device lacks OF data, pick the MODALIAS info */
3518 name = sysfs_uevent_get(path, "MODALIAS");
3522 /* .. and strip the MODALIAS=[platform,usb...]: part. */
3523 tmp_name = strrchr(name, ':');
3531 strncpy(fullname, tmp_name, DRM_PLATFORM_DEVICE_NAME_LEN);
3532 fullname[DRM_PLATFORM_DEVICE_NAME_LEN - 1] = '\0';
3537 #warning "Missing implementation of drmParseOFBusInfo"
3542 static int drmParseOFDeviceInfo(int maj, int min, char ***compatible)
3545 char path[PATH_MAX + 1], *value, *tmp_name;
3546 unsigned int count, i;
3549 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3551 value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
3553 sscanf(value, "%u", &count);
3556 /* Assume one entry if the device lack OF data */
3560 *compatible = calloc(count + 1, sizeof(char *));
3564 for (i = 0; i < count; i++) {
3565 value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
3568 /* If the device lacks OF data, pick the MODALIAS info */
3569 value = sysfs_uevent_get(path, "MODALIAS");
3575 /* .. and strip the MODALIAS=[platform,usb...]: part. */
3576 tmp_name = strrchr(value, ':');
3581 tmp_name = strdup(tmp_name + 1);
3585 (*compatible)[i] = tmp_name;
3592 free((*compatible)[i]);
3597 #warning "Missing implementation of drmParseOFDeviceInfo"
3602 static int drmProcessPlatformDevice(drmDevicePtr *device,
3603 const char *node, int node_type,
3604 int maj, int min, bool fetch_deviceinfo,
3611 dev = drmDeviceAlloc(node_type, node, sizeof(drmPlatformBusInfo),
3612 sizeof(drmPlatformDeviceInfo), &ptr);
3616 dev->bustype = DRM_BUS_PLATFORM;
3618 dev->businfo.platform = (drmPlatformBusInfoPtr)ptr;
3620 ret = drmParseOFBusInfo(maj, min, dev->businfo.platform->fullname);
3624 if (fetch_deviceinfo) {
3625 ptr += sizeof(drmPlatformBusInfo);
3626 dev->deviceinfo.platform = (drmPlatformDeviceInfoPtr)ptr;
3628 ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.platform->compatible);
3642 static int drmProcessHost1xDevice(drmDevicePtr *device,
3643 const char *node, int node_type,
3644 int maj, int min, bool fetch_deviceinfo,
3651 dev = drmDeviceAlloc(node_type, node, sizeof(drmHost1xBusInfo),
3652 sizeof(drmHost1xDeviceInfo), &ptr);
3656 dev->bustype = DRM_BUS_HOST1X;
3658 dev->businfo.host1x = (drmHost1xBusInfoPtr)ptr;
3660 ret = drmParseOFBusInfo(maj, min, dev->businfo.host1x->fullname);
3664 if (fetch_deviceinfo) {
3665 ptr += sizeof(drmHost1xBusInfo);
3666 dev->deviceinfo.host1x = (drmHost1xDeviceInfoPtr)ptr;
3668 ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.host1x->compatible);
3683 process_device(drmDevicePtr *device, const char *d_name,
3684 int req_subsystem_type,
3685 bool fetch_deviceinfo, uint32_t flags)
3688 char node[PATH_MAX + 1];
3689 int node_type, subsystem_type;
3690 unsigned int maj, min;
3692 node_type = drmGetNodeType(d_name);
3696 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, d_name);
3697 if (stat(node, &sbuf))
3700 maj = major(sbuf.st_rdev);
3701 min = minor(sbuf.st_rdev);
3703 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3706 subsystem_type = drmParseSubsystemType(maj, min);
3707 if (req_subsystem_type != -1 && req_subsystem_type != subsystem_type)
3710 switch (subsystem_type) {
3712 case DRM_BUS_VIRTIO:
3713 return drmProcessPciDevice(device, node, node_type, maj, min,
3714 fetch_deviceinfo, flags);
3716 return drmProcessUsbDevice(device, node, node_type, maj, min,
3717 fetch_deviceinfo, flags);
3718 case DRM_BUS_PLATFORM:
3719 return drmProcessPlatformDevice(device, node, node_type, maj, min,
3720 fetch_deviceinfo, flags);
3721 case DRM_BUS_HOST1X:
3722 return drmProcessHost1xDevice(device, node, node_type, maj, min,
3723 fetch_deviceinfo, flags);
3729 /* Consider devices located on the same bus as duplicate and fold the respective
3730 * entries into a single one.
3732 * Note: this leaves "gaps" in the array, while preserving the length.
3734 static void drmFoldDuplicatedDevices(drmDevicePtr local_devices[], int count)
3736 int node_type, i, j;
3738 for (i = 0; i < count; i++) {
3739 for (j = i + 1; j < count; j++) {
3740 if (drmDevicesEqual(local_devices[i], local_devices[j])) {
3741 local_devices[i]->available_nodes |= local_devices[j]->available_nodes;
3742 node_type = log2(local_devices[j]->available_nodes);
3743 memcpy(local_devices[i]->nodes[node_type],
3744 local_devices[j]->nodes[node_type], drmGetMaxNodeName());
3745 drmFreeDevice(&local_devices[j]);
3751 /* Check that the given flags are valid returning 0 on success */
3753 drm_device_validate_flags(uint32_t flags)
3755 return (flags & ~DRM_DEVICE_GET_PCI_REVISION);
3759 drm_device_has_rdev(drmDevicePtr device, dev_t find_rdev)
3763 for (int i = 0; i < DRM_NODE_MAX; i++) {
3764 if (device->available_nodes & 1 << i) {
3765 if (stat(device->nodes[i], &sbuf) == 0 &&
3766 sbuf.st_rdev == find_rdev)
3774 * The kernel drm core has a number of places that assume maximum of
3775 * 3x64 devices nodes. That's 64 for each of primary, control and
3776 * render nodes. Rounded it up to 256 for simplicity.
3778 #define MAX_DRM_NODES 256
3781 * Get information about the opened drm device
3783 * \param fd file descriptor of the drm device
3784 * \param flags feature/behaviour bitmask
3785 * \param device the address of a drmDevicePtr where the information
3786 * will be allocated in stored
3788 * \return zero on success, negative error code otherwise.
3790 * \note Unlike drmGetDevice it does not retrieve the pci device revision field
3791 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
3793 drm_public int drmGetDevice2(int fd, uint32_t flags, drmDevicePtr *device)
3797 * DRI device nodes on OpenBSD are not in their own directory, they reside
3798 * in /dev along with a large number of statically generated /dev nodes.
3799 * Avoid stat'ing all of /dev needlessly by implementing this custom path.
3803 char node[PATH_MAX + 1];
3804 const char *dev_name;
3805 int node_type, subsystem_type;
3806 int maj, min, n, ret;
3808 if (fd == -1 || device == NULL)
3811 if (fstat(fd, &sbuf))
3814 maj = major(sbuf.st_rdev);
3815 min = minor(sbuf.st_rdev);
3817 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3820 node_type = drmGetMinorType(min);
3821 if (node_type == -1)
3824 dev_name = drmGetDeviceName(node_type);
3828 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min);
3829 if (n == -1 || n >= PATH_MAX)
3831 if (stat(node, &sbuf))
3834 subsystem_type = drmParseSubsystemType(maj, min);
3835 if (subsystem_type != DRM_BUS_PCI)
3838 ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
3846 drmDevicePtr local_devices[MAX_DRM_NODES];
3849 struct dirent *dent;
3853 int ret, i, node_count;
3856 if (drm_device_validate_flags(flags))
3859 if (fd == -1 || device == NULL)
3862 if (fstat(fd, &sbuf))
3865 find_rdev = sbuf.st_rdev;
3866 maj = major(sbuf.st_rdev);
3867 min = minor(sbuf.st_rdev);
3869 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3872 subsystem_type = drmParseSubsystemType(maj, min);
3873 if (subsystem_type < 0)
3874 return subsystem_type;
3876 sysdir = opendir(DRM_DIR_NAME);
3881 while ((dent = readdir(sysdir))) {
3882 ret = process_device(&d, dent->d_name, subsystem_type, true, flags);
3886 if (i >= MAX_DRM_NODES) {
3887 fprintf(stderr, "More than %d drm nodes detected. "
3888 "Please report a bug - that should not happen.\n"
3889 "Skipping extra nodes\n", MAX_DRM_NODES);
3892 local_devices[i] = d;
3897 drmFoldDuplicatedDevices(local_devices, node_count);
3901 for (i = 0; i < node_count; i++) {
3902 if (!local_devices[i])
3905 if (drm_device_has_rdev(local_devices[i], find_rdev))
3906 *device = local_devices[i];
3908 drmFreeDevice(&local_devices[i]);
3912 if (*device == NULL)
3919 * Get information about the opened drm device
3921 * \param fd file descriptor of the drm device
3922 * \param device the address of a drmDevicePtr where the information
3923 * will be allocated in stored
3925 * \return zero on success, negative error code otherwise.
3927 drm_public int drmGetDevice(int fd, drmDevicePtr *device)
3929 return drmGetDevice2(fd, DRM_DEVICE_GET_PCI_REVISION, device);
3933 * Get drm devices on the system
3935 * \param flags feature/behaviour bitmask
3936 * \param devices the array of devices with drmDevicePtr elements
3937 * can be NULL to get the device number first
3938 * \param max_devices the maximum number of devices for the array
3940 * \return on error - negative error code,
3941 * if devices is NULL - total number of devices available on the system,
3942 * alternatively the number of devices stored in devices[], which is
3943 * capped by the max_devices.
3945 * \note Unlike drmGetDevices it does not retrieve the pci device revision field
3946 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
3948 drm_public int drmGetDevices2(uint32_t flags, drmDevicePtr devices[],
3951 drmDevicePtr local_devices[MAX_DRM_NODES];
3952 drmDevicePtr device;
3954 struct dirent *dent;
3955 int ret, i, node_count, device_count;
3957 if (drm_device_validate_flags(flags))
3960 sysdir = opendir(DRM_DIR_NAME);
3965 while ((dent = readdir(sysdir))) {
3966 ret = process_device(&device, dent->d_name, -1, devices != NULL, flags);
3970 if (i >= MAX_DRM_NODES) {
3971 fprintf(stderr, "More than %d drm nodes detected. "
3972 "Please report a bug - that should not happen.\n"
3973 "Skipping extra nodes\n", MAX_DRM_NODES);
3976 local_devices[i] = device;
3981 drmFoldDuplicatedDevices(local_devices, node_count);
3984 for (i = 0; i < node_count; i++) {
3985 if (!local_devices[i])
3988 if ((devices != NULL) && (device_count < max_devices))
3989 devices[device_count] = local_devices[i];
3991 drmFreeDevice(&local_devices[i]);
3997 return device_count;
4001 * Get drm devices on the system
4003 * \param devices the array of devices with drmDevicePtr elements
4004 * can be NULL to get the device number first
4005 * \param max_devices the maximum number of devices for the array
4007 * \return on error - negative error code,
4008 * if devices is NULL - total number of devices available on the system,
4009 * alternatively the number of devices stored in devices[], which is
4010 * capped by the max_devices.
4012 drm_public int drmGetDevices(drmDevicePtr devices[], int max_devices)
4014 return drmGetDevices2(DRM_DEVICE_GET_PCI_REVISION, devices, max_devices);
4017 drm_public char *drmGetDeviceNameFromFd2(int fd)
4021 char path[PATH_MAX + 1], *value;
4022 unsigned int maj, min;
4024 if (fstat(fd, &sbuf))
4027 maj = major(sbuf.st_rdev);
4028 min = minor(sbuf.st_rdev);
4030 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4033 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d", maj, min);
4035 value = sysfs_uevent_get(path, "DEVNAME");
4039 snprintf(path, sizeof(path), "/dev/%s", value);
4042 return strdup(path);
4045 char node[PATH_MAX + 1];
4046 const char *dev_name;
4050 if (fstat(fd, &sbuf))
4053 maj = major(sbuf.st_rdev);
4054 min = minor(sbuf.st_rdev);
4056 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4059 node_type = drmGetMinorType(min);
4060 if (node_type == -1)
4063 dev_name = drmGetDeviceName(node_type);
4067 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min);
4068 if (n == -1 || n >= PATH_MAX)
4071 return strdup(node);
4075 drm_public int drmSyncobjCreate(int fd, uint32_t flags, uint32_t *handle)
4077 struct drm_syncobj_create args;
4083 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_CREATE, &args);
4086 *handle = args.handle;
4090 drm_public int drmSyncobjDestroy(int fd, uint32_t handle)
4092 struct drm_syncobj_destroy args;
4095 args.handle = handle;
4096 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_DESTROY, &args);
4099 drm_public int drmSyncobjHandleToFD(int fd, uint32_t handle, int *obj_fd)
4101 struct drm_syncobj_handle args;
4106 args.handle = handle;
4107 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4114 drm_public int drmSyncobjFDToHandle(int fd, int obj_fd, uint32_t *handle)
4116 struct drm_syncobj_handle args;
4122 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4125 *handle = args.handle;
4129 drm_public int drmSyncobjImportSyncFile(int fd, uint32_t handle,
4132 struct drm_syncobj_handle args;
4135 args.fd = sync_file_fd;
4136 args.handle = handle;
4137 args.flags = DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE;
4138 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4141 drm_public int drmSyncobjExportSyncFile(int fd, uint32_t handle,
4144 struct drm_syncobj_handle args;
4149 args.handle = handle;
4150 args.flags = DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE;
4151 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4154 *sync_file_fd = args.fd;
4158 drm_public int drmSyncobjWait(int fd, uint32_t *handles, unsigned num_handles,
4159 int64_t timeout_nsec, unsigned flags,
4160 uint32_t *first_signaled)
4162 struct drm_syncobj_wait args;
4166 args.handles = (uintptr_t)handles;
4167 args.timeout_nsec = timeout_nsec;
4168 args.count_handles = num_handles;
4171 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_WAIT, &args);
4176 *first_signaled = args.first_signaled;
4180 drm_public int drmSyncobjReset(int fd, const uint32_t *handles,
4181 uint32_t handle_count)
4183 struct drm_syncobj_array args;
4187 args.handles = (uintptr_t)handles;
4188 args.count_handles = handle_count;
4190 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_RESET, &args);
4194 drm_public int drmSyncobjSignal(int fd, const uint32_t *handles,
4195 uint32_t handle_count)
4197 struct drm_syncobj_array args;
4201 args.handles = (uintptr_t)handles;
4202 args.count_handles = handle_count;
4204 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_SIGNAL, &args);
4208 drm_public int drmSyncobjTimelineSignal(int fd, const uint32_t *handles,
4209 uint64_t *points, uint32_t handle_count)
4211 struct drm_syncobj_timeline_array args;
4215 args.handles = (uintptr_t)handles;
4216 args.points = (uintptr_t)points;
4217 args.count_handles = handle_count;
4219 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TIMELINE_SIGNAL, &args);
4223 drm_public int drmSyncobjTimelineWait(int fd, uint32_t *handles, uint64_t *points,
4224 unsigned num_handles,
4225 int64_t timeout_nsec, unsigned flags,
4226 uint32_t *first_signaled)
4228 struct drm_syncobj_timeline_wait args;
4232 args.handles = (uintptr_t)handles;
4233 args.points = (uintptr_t)points;
4234 args.timeout_nsec = timeout_nsec;
4235 args.count_handles = num_handles;
4238 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TIMELINE_WAIT, &args);
4243 *first_signaled = args.first_signaled;
4248 drm_public int drmSyncobjQuery(int fd, uint32_t *handles, uint64_t *points,
4249 uint32_t handle_count)
4251 struct drm_syncobj_timeline_array args;
4255 args.handles = (uintptr_t)handles;
4256 args.points = (uintptr_t)points;
4257 args.count_handles = handle_count;
4259 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_QUERY, &args);
4265 drm_public int drmSyncobjTransfer(int fd,
4266 uint32_t dst_handle, uint64_t dst_point,
4267 uint32_t src_handle, uint64_t src_point,
4270 struct drm_syncobj_transfer args;
4274 args.src_handle = src_handle;
4275 args.dst_handle = dst_handle;
4276 args.src_point = src_point;
4277 args.dst_point = dst_point;
4280 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TRANSFER, &args);