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 /* Not all systems have MAP_FAILED defined */
64 #define MAP_FAILED ((void *)-1)
68 #include "libdrm_macros.h"
70 #include "util_math.h"
73 #define DRM_PRIMARY_MINOR_NAME "drm"
74 #define DRM_CONTROL_MINOR_NAME "drmC"
75 #define DRM_RENDER_MINOR_NAME "drmR"
77 #define DRM_PRIMARY_MINOR_NAME "card"
78 #define DRM_CONTROL_MINOR_NAME "controlD"
79 #define DRM_RENDER_MINOR_NAME "renderD"
82 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
96 #endif /* __OpenBSD__ */
99 #define DRM_MAJOR 226 /* Linux */
110 uint16_t subvendor_id;
111 uint16_t subdevice_id;
115 #define DRM_IOCTL_GET_PCIINFO DRM_IOR(0x15, struct drm_pciinfo)
118 #define DRM_MSG_VERBOSITY 3
120 #define memclear(s) memset(&s, 0, sizeof(s))
122 static drmServerInfoPtr drm_server_info;
124 drm_public void drmSetServerInfo(drmServerInfoPtr info)
126 drm_server_info = info;
130 * Output a message to stderr.
132 * \param format printf() like format string.
135 * This function is a wrapper around vfprintf().
138 static int DRM_PRINTFLIKE(1, 0)
139 drmDebugPrint(const char *format, va_list ap)
141 return vfprintf(stderr, format, ap);
145 drmMsg(const char *format, ...)
149 if (((env = getenv("LIBGL_DEBUG")) && strstr(env, "verbose")) ||
150 (drm_server_info && drm_server_info->debug_print))
152 va_start(ap, format);
153 if (drm_server_info) {
154 drm_server_info->debug_print(format,ap);
156 drmDebugPrint(format, ap);
162 static void *drmHashTable = NULL; /* Context switch callbacks */
164 drm_public void *drmGetHashTable(void)
169 drm_public void *drmMalloc(int size)
171 return calloc(1, size);
174 drm_public void drmFree(void *pt)
180 * Call ioctl, restarting if it is interupted
183 drmIoctl(int fd, unsigned long request, void *arg)
188 ret = ioctl(fd, request, arg);
189 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
193 static unsigned long drmGetKeyFromFd(int fd)
202 drm_public drmHashEntry *drmGetEntry(int fd)
204 unsigned long key = drmGetKeyFromFd(fd);
209 drmHashTable = drmHashCreate();
211 if (drmHashLookup(drmHashTable, key, &value)) {
212 entry = drmMalloc(sizeof(*entry));
215 entry->tagTable = drmHashCreate();
216 drmHashInsert(drmHashTable, key, entry);
224 * Compare two busid strings
229 * \return 1 if matched.
232 * This function compares two bus ID strings. It understands the older
233 * PCI:b:d:f format and the newer pci:oooo:bb:dd.f format. In the format, o is
234 * domain, b is bus, d is device, f is function.
236 static int drmMatchBusID(const char *id1, const char *id2, int pci_domain_ok)
238 /* First, check if the IDs are exactly the same */
239 if (strcasecmp(id1, id2) == 0)
242 /* Try to match old/new-style PCI bus IDs. */
243 if (strncasecmp(id1, "pci", 3) == 0) {
244 unsigned int o1, b1, d1, f1;
245 unsigned int o2, b2, d2, f2;
248 ret = sscanf(id1, "pci:%04x:%02x:%02x.%u", &o1, &b1, &d1, &f1);
251 ret = sscanf(id1, "PCI:%u:%u:%u", &b1, &d1, &f1);
256 ret = sscanf(id2, "pci:%04x:%02x:%02x.%u", &o2, &b2, &d2, &f2);
259 ret = sscanf(id2, "PCI:%u:%u:%u", &b2, &d2, &f2);
264 /* If domains aren't properly supported by the kernel interface,
265 * just ignore them, which sucks less than picking a totally random
266 * card with "open by name"
271 if ((o1 != o2) || (b1 != b2) || (d1 != d2) || (f1 != f2))
280 * Handles error checking for chown call.
282 * \param path to file.
283 * \param id of the new owner.
284 * \param id of the new group.
286 * \return zero if success or -1 if failure.
289 * Checks for failure. If failure was caused by signal call chown again.
290 * If any other failure happened then it will output error mesage using
294 static int chown_check_return(const char *path, uid_t owner, gid_t group)
299 rv = chown(path, owner, group);
300 } while (rv != 0 && errno == EINTR);
305 drmMsg("Failed to change owner or group for file %s! %d: %s\n",
306 path, errno, strerror(errno));
312 * Open the DRM device, creating it if necessary.
314 * \param dev major and minor numbers of the device.
315 * \param minor minor number of the device.
317 * \return a file descriptor on success, or a negative value on error.
320 * Assembles the device name from \p minor and opens it, creating the device
321 * special file node with the major and minor numbers specified by \p dev and
322 * parent directory if necessary and was called by root.
324 static int drmOpenDevice(dev_t dev, int minor, int type)
327 const char *dev_name;
330 mode_t devmode = DRM_DEV_MODE, serv_mode;
333 int isroot = !geteuid();
334 uid_t user = DRM_DEV_UID;
335 gid_t group = DRM_DEV_GID;
339 case DRM_NODE_PRIMARY:
340 dev_name = DRM_DEV_NAME;
342 case DRM_NODE_CONTROL:
343 dev_name = DRM_CONTROL_DEV_NAME;
345 case DRM_NODE_RENDER:
346 dev_name = DRM_RENDER_DEV_NAME;
352 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
353 drmMsg("drmOpenDevice: node name is %s\n", buf);
355 if (drm_server_info && drm_server_info->get_perms) {
356 drm_server_info->get_perms(&serv_group, &serv_mode);
357 devmode = serv_mode ? serv_mode : DRM_DEV_MODE;
358 devmode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
362 if (stat(DRM_DIR_NAME, &st)) {
364 return DRM_ERR_NOT_ROOT;
365 mkdir(DRM_DIR_NAME, DRM_DEV_DIRMODE);
366 chown_check_return(DRM_DIR_NAME, 0, 0); /* root:root */
367 chmod(DRM_DIR_NAME, DRM_DEV_DIRMODE);
370 /* Check if the device node exists and create it if necessary. */
371 if (stat(buf, &st)) {
373 return DRM_ERR_NOT_ROOT;
375 mknod(buf, S_IFCHR | devmode, dev);
378 if (drm_server_info && drm_server_info->get_perms) {
379 group = ((int)serv_group >= 0) ? serv_group : DRM_DEV_GID;
380 chown_check_return(buf, user, group);
384 /* if we modprobed then wait for udev */
388 if (stat(DRM_DIR_NAME, &st)) {
392 if (udev_count == 50)
397 if (stat(buf, &st)) {
401 if (udev_count == 50)
408 fd = open(buf, O_RDWR | O_CLOEXEC, 0);
409 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
410 fd, fd < 0 ? strerror(errno) : "OK");
415 /* Check if the device node is not what we expect it to be, and recreate it
416 * and try again if so.
418 if (st.st_rdev != dev) {
420 return DRM_ERR_NOT_ROOT;
422 mknod(buf, S_IFCHR | devmode, dev);
423 if (drm_server_info && drm_server_info->get_perms) {
424 chown_check_return(buf, user, group);
428 fd = open(buf, O_RDWR | O_CLOEXEC, 0);
429 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
430 fd, fd < 0 ? strerror(errno) : "OK");
434 drmMsg("drmOpenDevice: Open failed\n");
442 * Open the DRM device
444 * \param minor device minor number.
445 * \param create allow to create the device if set.
447 * \return a file descriptor on success, or a negative value on error.
450 * Calls drmOpenDevice() if \p create is set, otherwise assembles the device
451 * name from \p minor and opens it.
453 static int drmOpenMinor(int minor, int create, int type)
457 const char *dev_name;
460 return drmOpenDevice(makedev(DRM_MAJOR, minor), minor, type);
463 case DRM_NODE_PRIMARY:
464 dev_name = DRM_DEV_NAME;
466 case DRM_NODE_CONTROL:
467 dev_name = DRM_CONTROL_DEV_NAME;
469 case DRM_NODE_RENDER:
470 dev_name = DRM_RENDER_DEV_NAME;
476 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
477 if ((fd = open(buf, O_RDWR | O_CLOEXEC, 0)) >= 0)
484 * Determine whether the DRM kernel driver has been loaded.
486 * \return 1 if the DRM driver is loaded, 0 otherwise.
489 * Determine the presence of the kernel driver by attempting to open the 0
490 * minor and get version information. For backward compatibility with older
491 * Linux implementations, /proc/dri is also checked.
493 drm_public int drmAvailable(void)
495 drmVersionPtr version;
499 if ((fd = drmOpenMinor(0, 1, DRM_NODE_PRIMARY)) < 0) {
501 /* Try proc for backward Linux compatibility */
502 if (!access("/proc/dri/0", R_OK))
508 if ((version = drmGetVersion(fd))) {
510 drmFreeVersion(version);
517 static int drmGetMinorBase(int type)
520 case DRM_NODE_PRIMARY:
522 case DRM_NODE_CONTROL:
524 case DRM_NODE_RENDER:
531 static int drmGetMinorType(int minor)
533 int type = minor >> 6;
539 case DRM_NODE_PRIMARY:
540 case DRM_NODE_CONTROL:
541 case DRM_NODE_RENDER:
548 static const char *drmGetMinorName(int type)
551 case DRM_NODE_PRIMARY:
552 return DRM_PRIMARY_MINOR_NAME;
553 case DRM_NODE_CONTROL:
554 return DRM_CONTROL_MINOR_NAME;
555 case DRM_NODE_RENDER:
556 return DRM_RENDER_MINOR_NAME;
563 * Open the device by bus ID.
565 * \param busid bus ID.
566 * \param type device node type.
568 * \return a file descriptor on success, or a negative value on error.
571 * This function attempts to open every possible minor (up to DRM_MAX_MINOR),
572 * comparing the device bus ID with the one supplied.
574 * \sa drmOpenMinor() and drmGetBusid().
576 static int drmOpenByBusid(const char *busid, int type)
578 int i, pci_domain_ok = 1;
582 int base = drmGetMinorBase(type);
587 drmMsg("drmOpenByBusid: Searching for BusID %s\n", busid);
588 for (i = base; i < base + DRM_MAX_MINOR; i++) {
589 fd = drmOpenMinor(i, 1, type);
590 drmMsg("drmOpenByBusid: drmOpenMinor returns %d\n", fd);
592 /* We need to try for 1.4 first for proper PCI domain support
593 * and if that fails, we know the kernel is busted
597 sv.drm_dd_major = -1; /* Don't care */
598 sv.drm_dd_minor = -1; /* Don't care */
599 if (drmSetInterfaceVersion(fd, &sv)) {
605 sv.drm_dd_major = -1; /* Don't care */
606 sv.drm_dd_minor = -1; /* Don't care */
607 drmMsg("drmOpenByBusid: Interface 1.4 failed, trying 1.1\n");
608 drmSetInterfaceVersion(fd, &sv);
610 buf = drmGetBusid(fd);
611 drmMsg("drmOpenByBusid: drmGetBusid reports %s\n", buf);
612 if (buf && drmMatchBusID(buf, busid, pci_domain_ok)) {
626 * Open the device by name.
628 * \param name driver name.
629 * \param type the device node type.
631 * \return a file descriptor on success, or a negative value on error.
634 * This function opens the first minor number that matches the driver name and
635 * isn't already in use. If it's in use it then it will already have a bus ID
638 * \sa drmOpenMinor(), drmGetVersion() and drmGetBusid().
640 static int drmOpenByName(const char *name, int type)
644 drmVersionPtr version;
646 int base = drmGetMinorBase(type);
652 * Open the first minor number that matches the driver name and isn't
653 * already in use. If it's in use it will have a busid assigned already.
655 for (i = base; i < base + DRM_MAX_MINOR; i++) {
656 if ((fd = drmOpenMinor(i, 1, type)) >= 0) {
657 if ((version = drmGetVersion(fd))) {
658 if (!strcmp(version->name, name)) {
659 drmFreeVersion(version);
660 id = drmGetBusid(fd);
661 drmMsg("drmGetBusid returned '%s'\n", id ? id : "NULL");
670 drmFreeVersion(version);
678 /* Backward-compatibility /proc support */
679 for (i = 0; i < 8; i++) {
680 char proc_name[64], buf[512];
681 char *driver, *pt, *devstring;
684 sprintf(proc_name, "/proc/dri/%d/name", i);
685 if ((fd = open(proc_name, 0, 0)) >= 0) {
686 retcode = read(fd, buf, sizeof(buf)-1);
689 buf[retcode-1] = '\0';
690 for (driver = pt = buf; *pt && *pt != ' '; ++pt)
692 if (*pt) { /* Device is next */
694 if (!strcmp(driver, name)) { /* Match */
695 for (devstring = ++pt; *pt && *pt != ' '; ++pt)
697 if (*pt) { /* Found busid */
698 return drmOpenByBusid(++pt, type);
699 } else { /* No busid */
700 return drmOpenDevice(strtol(devstring, NULL, 0),i, type);
714 * Open the DRM device.
716 * Looks up the specified name and bus ID, and opens the device found. The
717 * entry in /dev/dri is created if necessary and if called by root.
719 * \param name driver name. Not referenced if bus ID is supplied.
720 * \param busid bus ID. Zero if not known.
722 * \return a file descriptor on success, or a negative value on error.
725 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
728 drm_public int drmOpen(const char *name, const char *busid)
730 return drmOpenWithType(name, busid, DRM_NODE_PRIMARY);
734 * Open the DRM device with specified type.
736 * Looks up the specified name and bus ID, and opens the device found. The
737 * entry in /dev/dri is created if necessary and if called by root.
739 * \param name driver name. Not referenced if bus ID is supplied.
740 * \param busid bus ID. Zero if not known.
741 * \param type the device node type to open, PRIMARY, CONTROL or RENDER
743 * \return a file descriptor on success, or a negative value on error.
746 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
749 drm_public int drmOpenWithType(const char *name, const char *busid, int type)
751 if (!drmAvailable() && name != NULL && drm_server_info &&
752 drm_server_info->load_module) {
753 /* try to load the kernel module */
754 if (!drm_server_info->load_module(name)) {
755 drmMsg("[drm] failed to load kernel module \"%s\"\n", name);
761 int fd = drmOpenByBusid(busid, type);
767 return drmOpenByName(name, type);
772 drm_public int drmOpenControl(int minor)
774 return drmOpenMinor(minor, 0, DRM_NODE_CONTROL);
777 drm_public int drmOpenRender(int minor)
779 return drmOpenMinor(minor, 0, DRM_NODE_RENDER);
783 * Free the version information returned by drmGetVersion().
785 * \param v pointer to the version information.
788 * It frees the memory pointed by \p %v as well as all the non-null strings
791 drm_public void drmFreeVersion(drmVersionPtr v)
803 * Free the non-public version information returned by the kernel.
805 * \param v pointer to the version information.
808 * Used by drmGetVersion() to free the memory pointed by \p %v as well as all
809 * the non-null strings pointers in it.
811 static void drmFreeKernelVersion(drm_version_t *v)
823 * Copy version information.
825 * \param d destination pointer.
826 * \param s source pointer.
829 * Used by drmGetVersion() to translate the information returned by the ioctl
830 * interface in a private structure into the public structure counterpart.
832 static void drmCopyVersion(drmVersionPtr d, const drm_version_t *s)
834 d->version_major = s->version_major;
835 d->version_minor = s->version_minor;
836 d->version_patchlevel = s->version_patchlevel;
837 d->name_len = s->name_len;
838 d->name = strdup(s->name);
839 d->date_len = s->date_len;
840 d->date = strdup(s->date);
841 d->desc_len = s->desc_len;
842 d->desc = strdup(s->desc);
847 * Query the driver version information.
849 * \param fd file descriptor.
851 * \return pointer to a drmVersion structure which should be freed with
854 * \note Similar information is available via /proc/dri.
857 * It gets the version information via successive DRM_IOCTL_VERSION ioctls,
858 * first with zeros to get the string lengths, and then the actually strings.
859 * It also null-terminates them since they might not be already.
861 drm_public drmVersionPtr drmGetVersion(int fd)
863 drmVersionPtr retval;
864 drm_version_t *version = drmMalloc(sizeof(*version));
866 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
867 drmFreeKernelVersion(version);
871 if (version->name_len)
872 version->name = drmMalloc(version->name_len + 1);
873 if (version->date_len)
874 version->date = drmMalloc(version->date_len + 1);
875 if (version->desc_len)
876 version->desc = drmMalloc(version->desc_len + 1);
878 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
879 drmMsg("DRM_IOCTL_VERSION: %s\n", strerror(errno));
880 drmFreeKernelVersion(version);
884 /* The results might not be null-terminated strings, so terminate them. */
885 if (version->name_len) version->name[version->name_len] = '\0';
886 if (version->date_len) version->date[version->date_len] = '\0';
887 if (version->desc_len) version->desc[version->desc_len] = '\0';
889 retval = drmMalloc(sizeof(*retval));
890 drmCopyVersion(retval, version);
891 drmFreeKernelVersion(version);
897 * Get version information for the DRM user space library.
899 * This version number is driver independent.
901 * \param fd file descriptor.
903 * \return version information.
906 * This function allocates and fills a drm_version structure with a hard coded
909 drm_public drmVersionPtr drmGetLibVersion(int fd)
911 drm_version_t *version = drmMalloc(sizeof(*version));
914 * NOTE THIS MUST NOT GO ABOVE VERSION 1.X due to drivers needing it
915 * revision 1.0.x = original DRM interface with no drmGetLibVersion
916 * entry point and many drm<Device> extensions
917 * revision 1.1.x = added drmCommand entry points for device extensions
918 * added drmGetLibVersion to identify libdrm.a version
919 * revision 1.2.x = added drmSetInterfaceVersion
920 * modified drmOpen to handle both busid and name
921 * revision 1.3.x = added server + memory manager
923 version->version_major = 1;
924 version->version_minor = 3;
925 version->version_patchlevel = 0;
927 return (drmVersionPtr)version;
930 drm_public int drmGetCap(int fd, uint64_t capability, uint64_t *value)
932 struct drm_get_cap cap;
936 cap.capability = capability;
938 ret = drmIoctl(fd, DRM_IOCTL_GET_CAP, &cap);
946 drm_public int drmSetClientCap(int fd, uint64_t capability, uint64_t value)
948 struct drm_set_client_cap cap;
951 cap.capability = capability;
954 return drmIoctl(fd, DRM_IOCTL_SET_CLIENT_CAP, &cap);
958 * Free the bus ID information.
960 * \param busid bus ID information string as given by drmGetBusid().
963 * This function is just frees the memory pointed by \p busid.
965 drm_public void drmFreeBusid(const char *busid)
967 drmFree((void *)busid);
972 * Get the bus ID of the device.
974 * \param fd file descriptor.
976 * \return bus ID string.
979 * This function gets the bus ID via successive DRM_IOCTL_GET_UNIQUE ioctls to
980 * get the string length and data, passing the arguments in a drm_unique
983 drm_public char *drmGetBusid(int fd)
989 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
991 u.unique = drmMalloc(u.unique_len + 1);
992 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u)) {
996 u.unique[u.unique_len] = '\0';
1003 * Set the bus ID of the device.
1005 * \param fd file descriptor.
1006 * \param busid bus ID string.
1008 * \return zero on success, negative on failure.
1011 * This function is a wrapper around the DRM_IOCTL_SET_UNIQUE ioctl, passing
1012 * the arguments in a drm_unique structure.
1014 drm_public int drmSetBusid(int fd, const char *busid)
1019 u.unique = (char *)busid;
1020 u.unique_len = strlen(busid);
1022 if (drmIoctl(fd, DRM_IOCTL_SET_UNIQUE, &u)) {
1028 drm_public int drmGetMagic(int fd, drm_magic_t * magic)
1035 if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
1037 *magic = auth.magic;
1041 drm_public int drmAuthMagic(int fd, drm_magic_t magic)
1047 if (drmIoctl(fd, DRM_IOCTL_AUTH_MAGIC, &auth))
1053 * Specifies a range of memory that is available for mapping by a
1056 * \param fd file descriptor.
1057 * \param offset usually the physical address. The actual meaning depends of
1058 * the \p type parameter. See below.
1059 * \param size of the memory in bytes.
1060 * \param type type of the memory to be mapped.
1061 * \param flags combination of several flags to modify the function actions.
1062 * \param handle will be set to a value that may be used as the offset
1063 * parameter for mmap().
1065 * \return zero on success or a negative value on error.
1067 * \par Mapping the frame buffer
1068 * For the frame buffer
1069 * - \p offset will be the physical address of the start of the frame buffer,
1070 * - \p size will be the size of the frame buffer in bytes, and
1071 * - \p type will be DRM_FRAME_BUFFER.
1074 * The area mapped will be uncached. If MTRR support is available in the
1075 * kernel, the frame buffer area will be set to write combining.
1077 * \par Mapping the MMIO register area
1078 * For the MMIO register area,
1079 * - \p offset will be the physical address of the start of the register area,
1080 * - \p size will be the size of the register area bytes, and
1081 * - \p type will be DRM_REGISTERS.
1083 * The area mapped will be uncached.
1085 * \par Mapping the SAREA
1087 * - \p offset will be ignored and should be set to zero,
1088 * - \p size will be the desired size of the SAREA in bytes,
1089 * - \p type will be DRM_SHM.
1092 * A shared memory area of the requested size will be created and locked in
1093 * kernel memory. This area may be mapped into client-space by using the handle
1096 * \note May only be called by root.
1099 * This function is a wrapper around the DRM_IOCTL_ADD_MAP ioctl, passing
1100 * the arguments in a drm_map structure.
1102 drm_public int drmAddMap(int fd, drm_handle_t offset, drmSize size, drmMapType type,
1103 drmMapFlags flags, drm_handle_t *handle)
1108 map.offset = offset;
1112 if (drmIoctl(fd, DRM_IOCTL_ADD_MAP, &map))
1115 *handle = (drm_handle_t)(uintptr_t)map.handle;
1119 drm_public int drmRmMap(int fd, drm_handle_t handle)
1124 map.handle = (void *)(uintptr_t)handle;
1126 if(drmIoctl(fd, DRM_IOCTL_RM_MAP, &map))
1132 * Make buffers available for DMA transfers.
1134 * \param fd file descriptor.
1135 * \param count number of buffers.
1136 * \param size size of each buffer.
1137 * \param flags buffer allocation flags.
1138 * \param agp_offset offset in the AGP aperture
1140 * \return number of buffers allocated, negative on error.
1143 * This function is a wrapper around DRM_IOCTL_ADD_BUFS ioctl.
1147 drm_public int drmAddBufs(int fd, int count, int size, drmBufDescFlags flags,
1150 drm_buf_desc_t request;
1153 request.count = count;
1154 request.size = size;
1155 request.flags = flags;
1156 request.agp_start = agp_offset;
1158 if (drmIoctl(fd, DRM_IOCTL_ADD_BUFS, &request))
1160 return request.count;
1163 drm_public int drmMarkBufs(int fd, double low, double high)
1165 drm_buf_info_t info;
1170 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1176 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1179 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1180 int retval = -errno;
1185 for (i = 0; i < info.count; i++) {
1186 info.list[i].low_mark = low * info.list[i].count;
1187 info.list[i].high_mark = high * info.list[i].count;
1188 if (drmIoctl(fd, DRM_IOCTL_MARK_BUFS, &info.list[i])) {
1189 int retval = -errno;
1202 * \param fd file descriptor.
1203 * \param count number of buffers to free.
1204 * \param list list of buffers to be freed.
1206 * \return zero on success, or a negative value on failure.
1208 * \note This function is primarily used for debugging.
1211 * This function is a wrapper around the DRM_IOCTL_FREE_BUFS ioctl, passing
1212 * the arguments in a drm_buf_free structure.
1214 drm_public int drmFreeBufs(int fd, int count, int *list)
1216 drm_buf_free_t request;
1219 request.count = count;
1220 request.list = list;
1221 if (drmIoctl(fd, DRM_IOCTL_FREE_BUFS, &request))
1230 * \param fd file descriptor.
1233 * This function closes the file descriptor.
1235 drm_public int drmClose(int fd)
1237 unsigned long key = drmGetKeyFromFd(fd);
1238 drmHashEntry *entry = drmGetEntry(fd);
1240 drmHashDestroy(entry->tagTable);
1243 entry->tagTable = NULL;
1245 drmHashDelete(drmHashTable, key);
1253 * Map a region of memory.
1255 * \param fd file descriptor.
1256 * \param handle handle returned by drmAddMap().
1257 * \param size size in bytes. Must match the size used by drmAddMap().
1258 * \param address will contain the user-space virtual address where the mapping
1261 * \return zero on success, or a negative value on failure.
1264 * This function is a wrapper for mmap().
1266 drm_public int drmMap(int fd, drm_handle_t handle, drmSize size,
1267 drmAddressPtr address)
1269 static unsigned long pagesize_mask = 0;
1275 pagesize_mask = getpagesize() - 1;
1277 size = (size + pagesize_mask) & ~pagesize_mask;
1279 *address = drm_mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1280 if (*address == MAP_FAILED)
1287 * Unmap mappings obtained with drmMap().
1289 * \param address address as given by drmMap().
1290 * \param size size in bytes. Must match the size used by drmMap().
1292 * \return zero on success, or a negative value on failure.
1295 * This function is a wrapper for munmap().
1297 drm_public int drmUnmap(drmAddress address, drmSize size)
1299 return drm_munmap(address, size);
1302 drm_public drmBufInfoPtr drmGetBufInfo(int fd)
1304 drm_buf_info_t info;
1305 drmBufInfoPtr retval;
1310 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1314 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1317 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1322 retval = drmMalloc(sizeof(*retval));
1323 retval->count = info.count;
1324 retval->list = drmMalloc(info.count * sizeof(*retval->list));
1325 for (i = 0; i < info.count; i++) {
1326 retval->list[i].count = info.list[i].count;
1327 retval->list[i].size = info.list[i].size;
1328 retval->list[i].low_mark = info.list[i].low_mark;
1329 retval->list[i].high_mark = info.list[i].high_mark;
1338 * Map all DMA buffers into client-virtual space.
1340 * \param fd file descriptor.
1342 * \return a pointer to a ::drmBufMap structure.
1344 * \note The client may not use these buffers until obtaining buffer indices
1348 * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1349 * information about the buffers in a drm_buf_map structure into the
1350 * client-visible data structures.
1352 drm_public drmBufMapPtr drmMapBufs(int fd)
1355 drmBufMapPtr retval;
1359 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1365 if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1368 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1373 retval = drmMalloc(sizeof(*retval));
1374 retval->count = bufs.count;
1375 retval->list = drmMalloc(bufs.count * sizeof(*retval->list));
1376 for (i = 0; i < bufs.count; i++) {
1377 retval->list[i].idx = bufs.list[i].idx;
1378 retval->list[i].total = bufs.list[i].total;
1379 retval->list[i].used = 0;
1380 retval->list[i].address = bufs.list[i].address;
1389 * Unmap buffers allocated with drmMapBufs().
1391 * \return zero on success, or negative value on failure.
1394 * Calls munmap() for every buffer stored in \p bufs and frees the
1395 * memory allocated by drmMapBufs().
1397 drm_public int drmUnmapBufs(drmBufMapPtr bufs)
1401 for (i = 0; i < bufs->count; i++) {
1402 drm_munmap(bufs->list[i].address, bufs->list[i].total);
1405 drmFree(bufs->list);
1411 #define DRM_DMA_RETRY 16
1414 * Reserve DMA buffers.
1416 * \param fd file descriptor.
1419 * \return zero on success, or a negative value on failure.
1422 * Assemble the arguments into a drm_dma structure and keeps issuing the
1423 * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1425 drm_public int drmDMA(int fd, drmDMAReqPtr request)
1430 dma.context = request->context;
1431 dma.send_count = request->send_count;
1432 dma.send_indices = request->send_list;
1433 dma.send_sizes = request->send_sizes;
1434 dma.flags = request->flags;
1435 dma.request_count = request->request_count;
1436 dma.request_size = request->request_size;
1437 dma.request_indices = request->request_list;
1438 dma.request_sizes = request->request_sizes;
1439 dma.granted_count = 0;
1442 ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1443 } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1446 request->granted_count = dma.granted_count;
1455 * Obtain heavyweight hardware lock.
1457 * \param fd file descriptor.
1458 * \param context context.
1459 * \param flags flags that determine the sate of the hardware when the function
1462 * \return always zero.
1465 * This function translates the arguments into a drm_lock structure and issue
1466 * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1468 drm_public int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
1473 lock.context = context;
1475 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
1476 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
1477 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
1478 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
1479 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
1480 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
1482 while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
1488 * Release the hardware lock.
1490 * \param fd file descriptor.
1491 * \param context context.
1493 * \return zero on success, or a negative value on failure.
1496 * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
1497 * argument in a drm_lock structure.
1499 drm_public int drmUnlock(int fd, drm_context_t context)
1504 lock.context = context;
1505 return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
1508 drm_public drm_context_t *drmGetReservedContextList(int fd, int *count)
1512 drm_context_t * retval;
1516 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1522 if (!(list = drmMalloc(res.count * sizeof(*list))))
1524 if (!(retval = drmMalloc(res.count * sizeof(*retval))))
1527 res.contexts = list;
1528 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1529 goto err_free_context;
1531 for (i = 0; i < res.count; i++)
1532 retval[i] = list[i].handle;
1545 drm_public void drmFreeReservedContextList(drm_context_t *pt)
1553 * Used by the X server during GLXContext initialization. This causes
1554 * per-context kernel-level resources to be allocated.
1556 * \param fd file descriptor.
1557 * \param handle is set on success. To be used by the client when requesting DMA
1558 * dispatch with drmDMA().
1560 * \return zero on success, or a negative value on failure.
1562 * \note May only be called by root.
1565 * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
1566 * argument in a drm_ctx structure.
1568 drm_public int drmCreateContext(int fd, drm_context_t *handle)
1573 if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
1575 *handle = ctx.handle;
1579 drm_public int drmSwitchToContext(int fd, drm_context_t context)
1584 ctx.handle = context;
1585 if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
1590 drm_public int drmSetContextFlags(int fd, drm_context_t context,
1591 drm_context_tFlags flags)
1596 * Context preserving means that no context switches are done between DMA
1597 * buffers from one context and the next. This is suitable for use in the
1598 * X server (which promises to maintain hardware context), or in the
1599 * client-side library when buffers are swapped on behalf of two threads.
1602 ctx.handle = context;
1603 if (flags & DRM_CONTEXT_PRESERVED)
1604 ctx.flags |= _DRM_CONTEXT_PRESERVED;
1605 if (flags & DRM_CONTEXT_2DONLY)
1606 ctx.flags |= _DRM_CONTEXT_2DONLY;
1607 if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
1612 drm_public int drmGetContextFlags(int fd, drm_context_t context,
1613 drm_context_tFlagsPtr flags)
1618 ctx.handle = context;
1619 if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
1622 if (ctx.flags & _DRM_CONTEXT_PRESERVED)
1623 *flags |= DRM_CONTEXT_PRESERVED;
1624 if (ctx.flags & _DRM_CONTEXT_2DONLY)
1625 *flags |= DRM_CONTEXT_2DONLY;
1632 * Free any kernel-level resources allocated with drmCreateContext() associated
1635 * \param fd file descriptor.
1636 * \param handle handle given by drmCreateContext().
1638 * \return zero on success, or a negative value on failure.
1640 * \note May only be called by root.
1643 * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
1644 * argument in a drm_ctx structure.
1646 drm_public int drmDestroyContext(int fd, drm_context_t handle)
1651 ctx.handle = handle;
1652 if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
1657 drm_public int drmCreateDrawable(int fd, drm_drawable_t *handle)
1662 if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
1664 *handle = draw.handle;
1668 drm_public int drmDestroyDrawable(int fd, drm_drawable_t handle)
1673 draw.handle = handle;
1674 if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
1679 drm_public int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
1680 drm_drawable_info_type_t type,
1681 unsigned int num, void *data)
1683 drm_update_draw_t update;
1686 update.handle = handle;
1689 update.data = (unsigned long long)(unsigned long)data;
1691 if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
1697 drm_public int drmCrtcGetSequence(int fd, uint32_t crtcId, uint64_t *sequence,
1700 struct drm_crtc_get_sequence get_seq;
1704 get_seq.crtc_id = crtcId;
1705 ret = drmIoctl(fd, DRM_IOCTL_CRTC_GET_SEQUENCE, &get_seq);
1710 *sequence = get_seq.sequence;
1712 *ns = get_seq.sequence_ns;
1716 drm_public int drmCrtcQueueSequence(int fd, uint32_t crtcId, uint32_t flags,
1718 uint64_t *sequence_queued,
1721 struct drm_crtc_queue_sequence queue_seq;
1724 memclear(queue_seq);
1725 queue_seq.crtc_id = crtcId;
1726 queue_seq.flags = flags;
1727 queue_seq.sequence = sequence;
1728 queue_seq.user_data = user_data;
1730 ret = drmIoctl(fd, DRM_IOCTL_CRTC_QUEUE_SEQUENCE, &queue_seq);
1731 if (ret == 0 && sequence_queued)
1732 *sequence_queued = queue_seq.sequence;
1738 * Acquire the AGP device.
1740 * Must be called before any of the other AGP related calls.
1742 * \param fd file descriptor.
1744 * \return zero on success, or a negative value on failure.
1747 * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
1749 drm_public int drmAgpAcquire(int fd)
1751 if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
1758 * Release the AGP device.
1760 * \param fd file descriptor.
1762 * \return zero on success, or a negative value on failure.
1765 * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
1767 drm_public int drmAgpRelease(int fd)
1769 if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
1778 * \param fd file descriptor.
1779 * \param mode AGP mode.
1781 * \return zero on success, or a negative value on failure.
1784 * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
1785 * argument in a drm_agp_mode structure.
1787 drm_public int drmAgpEnable(int fd, unsigned long mode)
1793 if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
1800 * Allocate a chunk of AGP memory.
1802 * \param fd file descriptor.
1803 * \param size requested memory size in bytes. Will be rounded to page boundary.
1804 * \param type type of memory to allocate.
1805 * \param address if not zero, will be set to the physical address of the
1807 * \param handle on success will be set to a handle of the allocated memory.
1809 * \return zero on success, or a negative value on failure.
1812 * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
1813 * arguments in a drm_agp_buffer structure.
1815 drm_public int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
1816 unsigned long *address, drm_handle_t *handle)
1821 *handle = DRM_AGP_NO_HANDLE;
1824 if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
1827 *address = b.physical;
1834 * Free a chunk of AGP memory.
1836 * \param fd file descriptor.
1837 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1839 * \return zero on success, or a negative value on failure.
1842 * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
1843 * argument in a drm_agp_buffer structure.
1845 drm_public int drmAgpFree(int fd, drm_handle_t handle)
1851 if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
1858 * Bind a chunk of AGP memory.
1860 * \param fd file descriptor.
1861 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1862 * \param offset offset in bytes. It will round to page boundary.
1864 * \return zero on success, or a negative value on failure.
1867 * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
1868 * argument in a drm_agp_binding structure.
1870 drm_public int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
1872 drm_agp_binding_t b;
1877 if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
1884 * Unbind a chunk of AGP memory.
1886 * \param fd file descriptor.
1887 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1889 * \return zero on success, or a negative value on failure.
1892 * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
1893 * the argument in a drm_agp_binding structure.
1895 drm_public int drmAgpUnbind(int fd, drm_handle_t handle)
1897 drm_agp_binding_t b;
1901 if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
1908 * Get AGP driver major version number.
1910 * \param fd file descriptor.
1912 * \return major version number on success, or a negative value on failure..
1915 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1916 * necessary information in a drm_agp_info structure.
1918 drm_public int drmAgpVersionMajor(int fd)
1924 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1926 return i.agp_version_major;
1931 * Get AGP driver minor version number.
1933 * \param fd file descriptor.
1935 * \return minor version number on success, or a negative value on failure.
1938 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1939 * necessary information in a drm_agp_info structure.
1941 drm_public int drmAgpVersionMinor(int fd)
1947 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1949 return i.agp_version_minor;
1956 * \param fd file descriptor.
1958 * \return mode on success, or zero on failure.
1961 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1962 * necessary information in a drm_agp_info structure.
1964 drm_public unsigned long drmAgpGetMode(int fd)
1970 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1977 * Get AGP aperture base.
1979 * \param fd file descriptor.
1981 * \return aperture base on success, zero on failure.
1984 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1985 * necessary information in a drm_agp_info structure.
1987 drm_public unsigned long drmAgpBase(int fd)
1993 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1995 return i.aperture_base;
2000 * Get AGP aperture size.
2002 * \param fd file descriptor.
2004 * \return aperture size on success, zero on failure.
2007 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2008 * necessary information in a drm_agp_info structure.
2010 drm_public unsigned long drmAgpSize(int fd)
2016 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2018 return i.aperture_size;
2023 * Get used AGP memory.
2025 * \param fd file descriptor.
2027 * \return memory used on success, or zero on failure.
2030 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2031 * necessary information in a drm_agp_info structure.
2033 drm_public unsigned long drmAgpMemoryUsed(int fd)
2039 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2041 return i.memory_used;
2046 * Get available AGP memory.
2048 * \param fd file descriptor.
2050 * \return memory available on success, or zero on failure.
2053 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2054 * necessary information in a drm_agp_info structure.
2056 drm_public unsigned long drmAgpMemoryAvail(int fd)
2062 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2064 return i.memory_allowed;
2069 * Get hardware vendor ID.
2071 * \param fd file descriptor.
2073 * \return vendor ID on success, or zero on failure.
2076 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2077 * necessary information in a drm_agp_info structure.
2079 drm_public unsigned int drmAgpVendorId(int fd)
2085 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2092 * Get hardware device ID.
2094 * \param fd file descriptor.
2096 * \return zero on success, or zero on failure.
2099 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2100 * necessary information in a drm_agp_info structure.
2102 drm_public unsigned int drmAgpDeviceId(int fd)
2108 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2113 drm_public int drmScatterGatherAlloc(int fd, unsigned long size,
2114 drm_handle_t *handle)
2116 drm_scatter_gather_t sg;
2122 if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
2124 *handle = sg.handle;
2128 drm_public int drmScatterGatherFree(int fd, drm_handle_t handle)
2130 drm_scatter_gather_t sg;
2134 if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
2142 * \param fd file descriptor.
2143 * \param vbl pointer to a drmVBlank structure.
2145 * \return zero on success, or a negative value on failure.
2148 * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
2150 drm_public int drmWaitVBlank(int fd, drmVBlankPtr vbl)
2152 struct timespec timeout, cur;
2155 ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2157 fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
2163 ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
2164 vbl->request.type &= ~DRM_VBLANK_RELATIVE;
2165 if (ret && errno == EINTR) {
2166 clock_gettime(CLOCK_MONOTONIC, &cur);
2167 /* Timeout after 1s */
2168 if (cur.tv_sec > timeout.tv_sec + 1 ||
2169 (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
2176 } while (ret && errno == EINTR);
2182 drm_public int drmError(int err, const char *label)
2185 case DRM_ERR_NO_DEVICE:
2186 fprintf(stderr, "%s: no device\n", label);
2188 case DRM_ERR_NO_ACCESS:
2189 fprintf(stderr, "%s: no access\n", label);
2191 case DRM_ERR_NOT_ROOT:
2192 fprintf(stderr, "%s: not root\n", label);
2194 case DRM_ERR_INVALID:
2195 fprintf(stderr, "%s: invalid args\n", label);
2200 fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2208 * Install IRQ handler.
2210 * \param fd file descriptor.
2211 * \param irq IRQ number.
2213 * \return zero on success, or a negative value on failure.
2216 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2217 * argument in a drm_control structure.
2219 drm_public int drmCtlInstHandler(int fd, int irq)
2224 ctl.func = DRM_INST_HANDLER;
2226 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2233 * Uninstall IRQ handler.
2235 * \param fd file descriptor.
2237 * \return zero on success, or a negative value on failure.
2240 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2241 * argument in a drm_control structure.
2243 drm_public int drmCtlUninstHandler(int fd)
2248 ctl.func = DRM_UNINST_HANDLER;
2250 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2255 drm_public int drmFinish(int fd, int context, drmLockFlags flags)
2260 lock.context = context;
2261 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
2262 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
2263 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
2264 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
2265 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2266 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2267 if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2273 * Get IRQ from bus ID.
2275 * \param fd file descriptor.
2276 * \param busnum bus number.
2277 * \param devnum device number.
2278 * \param funcnum function number.
2280 * \return IRQ number on success, or a negative value on failure.
2283 * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2284 * arguments in a drm_irq_busid structure.
2286 drm_public int drmGetInterruptFromBusID(int fd, int busnum, int devnum,
2294 p.funcnum = funcnum;
2295 if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2300 drm_public int drmAddContextTag(int fd, drm_context_t context, void *tag)
2302 drmHashEntry *entry = drmGetEntry(fd);
2304 if (drmHashInsert(entry->tagTable, context, tag)) {
2305 drmHashDelete(entry->tagTable, context);
2306 drmHashInsert(entry->tagTable, context, tag);
2311 drm_public int drmDelContextTag(int fd, drm_context_t context)
2313 drmHashEntry *entry = drmGetEntry(fd);
2315 return drmHashDelete(entry->tagTable, context);
2318 drm_public void *drmGetContextTag(int fd, drm_context_t context)
2320 drmHashEntry *entry = drmGetEntry(fd);
2323 if (drmHashLookup(entry->tagTable, context, &value))
2329 drm_public int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2330 drm_handle_t handle)
2332 drm_ctx_priv_map_t map;
2335 map.ctx_id = ctx_id;
2336 map.handle = (void *)(uintptr_t)handle;
2338 if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2343 drm_public int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2344 drm_handle_t *handle)
2346 drm_ctx_priv_map_t map;
2349 map.ctx_id = ctx_id;
2351 if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2354 *handle = (drm_handle_t)(uintptr_t)map.handle;
2359 drm_public int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2360 drmMapType *type, drmMapFlags *flags,
2361 drm_handle_t *handle, int *mtrr)
2367 if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2369 *offset = map.offset;
2373 *handle = (unsigned long)map.handle;
2378 drm_public int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2379 unsigned long *magic, unsigned long *iocs)
2381 drm_client_t client;
2385 if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2387 *auth = client.auth;
2390 *magic = client.magic;
2391 *iocs = client.iocs;
2395 drm_public int drmGetStats(int fd, drmStatsT *stats)
2401 if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2405 memset(stats, 0, sizeof(*stats));
2406 if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2410 stats->data[i].long_format = "%-20.20s"; \
2411 stats->data[i].rate_format = "%8.8s"; \
2412 stats->data[i].isvalue = 1; \
2413 stats->data[i].verbose = 0
2416 stats->data[i].long_format = "%-20.20s"; \
2417 stats->data[i].rate_format = "%5.5s"; \
2418 stats->data[i].isvalue = 0; \
2419 stats->data[i].mult_names = "kgm"; \
2420 stats->data[i].mult = 1000; \
2421 stats->data[i].verbose = 0
2424 stats->data[i].long_format = "%-20.20s"; \
2425 stats->data[i].rate_format = "%5.5s"; \
2426 stats->data[i].isvalue = 0; \
2427 stats->data[i].mult_names = "KGM"; \
2428 stats->data[i].mult = 1024; \
2429 stats->data[i].verbose = 0
2432 stats->count = s.count;
2433 for (i = 0; i < s.count; i++) {
2434 stats->data[i].value = s.data[i].value;
2435 switch (s.data[i].type) {
2436 case _DRM_STAT_LOCK:
2437 stats->data[i].long_name = "Lock";
2438 stats->data[i].rate_name = "Lock";
2441 case _DRM_STAT_OPENS:
2442 stats->data[i].long_name = "Opens";
2443 stats->data[i].rate_name = "O";
2445 stats->data[i].verbose = 1;
2447 case _DRM_STAT_CLOSES:
2448 stats->data[i].long_name = "Closes";
2449 stats->data[i].rate_name = "Lock";
2451 stats->data[i].verbose = 1;
2453 case _DRM_STAT_IOCTLS:
2454 stats->data[i].long_name = "Ioctls";
2455 stats->data[i].rate_name = "Ioc/s";
2458 case _DRM_STAT_LOCKS:
2459 stats->data[i].long_name = "Locks";
2460 stats->data[i].rate_name = "Lck/s";
2463 case _DRM_STAT_UNLOCKS:
2464 stats->data[i].long_name = "Unlocks";
2465 stats->data[i].rate_name = "Unl/s";
2469 stats->data[i].long_name = "IRQs";
2470 stats->data[i].rate_name = "IRQ/s";
2473 case _DRM_STAT_PRIMARY:
2474 stats->data[i].long_name = "Primary Bytes";
2475 stats->data[i].rate_name = "PB/s";
2478 case _DRM_STAT_SECONDARY:
2479 stats->data[i].long_name = "Secondary Bytes";
2480 stats->data[i].rate_name = "SB/s";
2484 stats->data[i].long_name = "DMA";
2485 stats->data[i].rate_name = "DMA/s";
2488 case _DRM_STAT_SPECIAL:
2489 stats->data[i].long_name = "Special DMA";
2490 stats->data[i].rate_name = "dma/s";
2493 case _DRM_STAT_MISSED:
2494 stats->data[i].long_name = "Miss";
2495 stats->data[i].rate_name = "Ms/s";
2498 case _DRM_STAT_VALUE:
2499 stats->data[i].long_name = "Value";
2500 stats->data[i].rate_name = "Value";
2503 case _DRM_STAT_BYTE:
2504 stats->data[i].long_name = "Bytes";
2505 stats->data[i].rate_name = "B/s";
2508 case _DRM_STAT_COUNT:
2510 stats->data[i].long_name = "Count";
2511 stats->data[i].rate_name = "Cnt/s";
2520 * Issue a set-version ioctl.
2522 * \param fd file descriptor.
2523 * \param drmCommandIndex command index
2524 * \param data source pointer of the data to be read and written.
2525 * \param size size of the data to be read and written.
2527 * \return zero on success, or a negative value on failure.
2530 * It issues a read-write ioctl given by
2531 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2533 drm_public int drmSetInterfaceVersion(int fd, drmSetVersion *version)
2536 drm_set_version_t sv;
2539 sv.drm_di_major = version->drm_di_major;
2540 sv.drm_di_minor = version->drm_di_minor;
2541 sv.drm_dd_major = version->drm_dd_major;
2542 sv.drm_dd_minor = version->drm_dd_minor;
2544 if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
2548 version->drm_di_major = sv.drm_di_major;
2549 version->drm_di_minor = sv.drm_di_minor;
2550 version->drm_dd_major = sv.drm_dd_major;
2551 version->drm_dd_minor = sv.drm_dd_minor;
2557 * Send a device-specific command.
2559 * \param fd file descriptor.
2560 * \param drmCommandIndex command index
2562 * \return zero on success, or a negative value on failure.
2565 * It issues a ioctl given by
2566 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2568 drm_public int drmCommandNone(int fd, unsigned long drmCommandIndex)
2570 unsigned long request;
2572 request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
2574 if (drmIoctl(fd, request, NULL)) {
2582 * Send a device-specific read command.
2584 * \param fd file descriptor.
2585 * \param drmCommandIndex command index
2586 * \param data destination pointer of the data to be read.
2587 * \param size size of the data to be read.
2589 * \return zero on success, or a negative value on failure.
2592 * It issues a read ioctl given by
2593 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2595 drm_public int drmCommandRead(int fd, unsigned long drmCommandIndex,
2596 void *data, unsigned long size)
2598 unsigned long request;
2600 request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
2601 DRM_COMMAND_BASE + drmCommandIndex, size);
2603 if (drmIoctl(fd, request, data)) {
2611 * Send a device-specific write command.
2613 * \param fd file descriptor.
2614 * \param drmCommandIndex command index
2615 * \param data source pointer of the data to be written.
2616 * \param size size of the data to be written.
2618 * \return zero on success, or a negative value on failure.
2621 * It issues a write ioctl given by
2622 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2624 drm_public int drmCommandWrite(int fd, unsigned long drmCommandIndex,
2625 void *data, unsigned long size)
2627 unsigned long request;
2629 request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
2630 DRM_COMMAND_BASE + drmCommandIndex, size);
2632 if (drmIoctl(fd, request, data)) {
2640 * Send a device-specific read-write command.
2642 * \param fd file descriptor.
2643 * \param drmCommandIndex command index
2644 * \param data source pointer of the data to be read and written.
2645 * \param size size of the data to be read and written.
2647 * \return zero on success, or a negative value on failure.
2650 * It issues a read-write ioctl given by
2651 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2653 drm_public int drmCommandWriteRead(int fd, unsigned long drmCommandIndex,
2654 void *data, unsigned long size)
2656 unsigned long request;
2658 request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
2659 DRM_COMMAND_BASE + drmCommandIndex, size);
2661 if (drmIoctl(fd, request, data))
2666 #define DRM_MAX_FDS 16
2672 } connection[DRM_MAX_FDS];
2674 static int nr_fds = 0;
2676 drm_public int drmOpenOnce(void *unused, const char *BusID, int *newlyopened)
2678 return drmOpenOnceWithType(BusID, newlyopened, DRM_NODE_PRIMARY);
2681 drm_public int drmOpenOnceWithType(const char *BusID, int *newlyopened,
2687 for (i = 0; i < nr_fds; i++)
2688 if ((strcmp(BusID, connection[i].BusID) == 0) &&
2689 (connection[i].type == type)) {
2690 connection[i].refcount++;
2692 return connection[i].fd;
2695 fd = drmOpenWithType(NULL, BusID, type);
2696 if (fd < 0 || nr_fds == DRM_MAX_FDS)
2699 connection[nr_fds].BusID = strdup(BusID);
2700 connection[nr_fds].fd = fd;
2701 connection[nr_fds].refcount = 1;
2702 connection[nr_fds].type = type;
2706 fprintf(stderr, "saved connection %d for %s %d\n",
2707 nr_fds, connection[nr_fds].BusID,
2708 strcmp(BusID, connection[nr_fds].BusID));
2715 drm_public void drmCloseOnce(int fd)
2719 for (i = 0; i < nr_fds; i++) {
2720 if (fd == connection[i].fd) {
2721 if (--connection[i].refcount == 0) {
2722 drmClose(connection[i].fd);
2723 free(connection[i].BusID);
2726 connection[i] = connection[nr_fds];
2734 drm_public int drmSetMaster(int fd)
2736 return drmIoctl(fd, DRM_IOCTL_SET_MASTER, NULL);
2739 drm_public int drmDropMaster(int fd)
2741 return drmIoctl(fd, DRM_IOCTL_DROP_MASTER, NULL);
2744 drm_public char *drmGetDeviceNameFromFd(int fd)
2751 /* The whole drmOpen thing is a fiasco and we need to find a way
2752 * back to just using open(2). For now, however, lets just make
2753 * things worse with even more ad hoc directory walking code to
2754 * discover the device file name. */
2759 for (i = 0; i < DRM_MAX_MINOR; i++) {
2760 snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
2761 if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
2764 if (i == DRM_MAX_MINOR)
2767 return strdup(name);
2770 static bool drmNodeIsDRM(int maj, int min)
2776 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device/drm",
2778 return stat(path, &sbuf) == 0;
2780 return maj == DRM_MAJOR;
2784 drm_public int drmGetNodeTypeFromFd(int fd)
2789 if (fstat(fd, &sbuf))
2792 maj = major(sbuf.st_rdev);
2793 min = minor(sbuf.st_rdev);
2795 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode)) {
2800 type = drmGetMinorType(min);
2806 drm_public int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags,
2809 struct drm_prime_handle args;
2814 args.handle = handle;
2816 ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
2820 *prime_fd = args.fd;
2824 drm_public int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
2826 struct drm_prime_handle args;
2831 ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
2835 *handle = args.handle;
2839 static char *drmGetMinorNameForFD(int fd, int type)
2845 const char *name = drmGetMinorName(type);
2847 char dev_name[64], buf[64];
2855 if (fstat(fd, &sbuf))
2858 maj = major(sbuf.st_rdev);
2859 min = minor(sbuf.st_rdev);
2861 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
2864 snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
2866 sysdir = opendir(buf);
2870 while ((ent = readdir(sysdir))) {
2871 if (strncmp(ent->d_name, name, len) == 0) {
2872 snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
2876 return strdup(dev_name);
2884 char buf[PATH_MAX + 1];
2885 const char *dev_name;
2886 unsigned int maj, min;
2889 if (fstat(fd, &sbuf))
2892 maj = major(sbuf.st_rdev);
2893 min = minor(sbuf.st_rdev);
2895 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
2899 case DRM_NODE_PRIMARY:
2900 dev_name = DRM_DEV_NAME;
2902 case DRM_NODE_CONTROL:
2903 dev_name = DRM_CONTROL_DEV_NAME;
2905 case DRM_NODE_RENDER:
2906 dev_name = DRM_RENDER_DEV_NAME;
2912 base = drmGetMinorBase(type);
2916 n = snprintf(buf, sizeof(buf), dev_name, DRM_DIR_NAME, min - base);
2917 if (n == -1 || n >= sizeof(buf))
2924 drm_public char *drmGetPrimaryDeviceNameFromFd(int fd)
2926 return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
2929 drm_public char *drmGetRenderDeviceNameFromFd(int fd)
2931 return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
2935 static char * DRM_PRINTFLIKE(2, 3)
2936 sysfs_uevent_get(const char *path, const char *fmt, ...)
2938 char filename[PATH_MAX + 1], *key, *line = NULL, *value = NULL;
2939 size_t size = 0, len;
2945 num = vasprintf(&key, fmt, ap);
2949 snprintf(filename, sizeof(filename), "%s/uevent", path);
2951 fp = fopen(filename, "r");
2957 while ((num = getline(&line, &size, fp)) >= 0) {
2958 if ((strncmp(line, key, len) == 0) && (line[len] == '=')) {
2959 char *start = line + len + 1, *end = line + num - 1;
2964 value = strndup(start, end - start);
2978 /* Little white lie to avoid major rework of the existing code */
2979 #define DRM_BUS_VIRTIO 0x10
2981 static int drmParseSubsystemType(int maj, int min)
2984 char path[PATH_MAX + 1];
2985 char link[PATH_MAX + 1] = "";
2988 snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/subsystem",
2991 if (readlink(path, link, PATH_MAX) < 0)
2994 name = strrchr(link, '/');
2998 if (strncmp(name, "/pci", 4) == 0)
3001 if (strncmp(name, "/usb", 4) == 0)
3004 if (strncmp(name, "/platform", 9) == 0)
3005 return DRM_BUS_PLATFORM;
3007 if (strncmp(name, "/host1x", 7) == 0)
3008 return DRM_BUS_HOST1X;
3010 if (strncmp(name, "/virtio", 7) == 0)
3011 return DRM_BUS_VIRTIO;
3014 #elif defined(__OpenBSD__)
3017 #warning "Missing implementation of drmParseSubsystemType"
3023 get_pci_path(int maj, int min, char *pci_path)
3025 char path[PATH_MAX + 1], *term;
3027 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3028 if (!realpath(path, pci_path)) {
3029 strcpy(pci_path, path);
3033 term = strrchr(pci_path, '/');
3034 if (term && strncmp(term, "/virtio", 7) == 0)
3038 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
3041 unsigned int domain, bus, dev, func;
3042 char pci_path[PATH_MAX + 1], *value;
3045 get_pci_path(maj, min, pci_path);
3047 value = sysfs_uevent_get(pci_path, "PCI_SLOT_NAME");
3051 num = sscanf(value, "%04x:%02x:%02x.%1u", &domain, &bus, &dev, &func);
3057 info->domain = domain;
3063 #elif defined(__OpenBSD__)
3064 struct drm_pciinfo pinfo;
3067 type = drmGetMinorType(min);
3071 fd = drmOpenMinor(min, 0, type);
3075 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3081 info->domain = pinfo.domain;
3082 info->bus = pinfo.bus;
3083 info->dev = pinfo.dev;
3084 info->func = pinfo.func;
3088 #warning "Missing implementation of drmParsePciBusInfo"
3093 drm_public int drmDevicesEqual(drmDevicePtr a, drmDevicePtr b)
3095 if (a == NULL || b == NULL)
3098 if (a->bustype != b->bustype)
3101 switch (a->bustype) {
3103 return memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo)) == 0;
3106 return memcmp(a->businfo.usb, b->businfo.usb, sizeof(drmUsbBusInfo)) == 0;
3108 case DRM_BUS_PLATFORM:
3109 return memcmp(a->businfo.platform, b->businfo.platform, sizeof(drmPlatformBusInfo)) == 0;
3111 case DRM_BUS_HOST1X:
3112 return memcmp(a->businfo.host1x, b->businfo.host1x, sizeof(drmHost1xBusInfo)) == 0;
3121 static int drmGetNodeType(const char *name)
3123 if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
3124 sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
3125 return DRM_NODE_PRIMARY;
3127 if (strncmp(name, DRM_CONTROL_MINOR_NAME,
3128 sizeof(DRM_CONTROL_MINOR_NAME ) - 1) == 0)
3129 return DRM_NODE_CONTROL;
3131 if (strncmp(name, DRM_RENDER_MINOR_NAME,
3132 sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
3133 return DRM_NODE_RENDER;
3138 static int drmGetMaxNodeName(void)
3140 return sizeof(DRM_DIR_NAME) +
3141 MAX3(sizeof(DRM_PRIMARY_MINOR_NAME),
3142 sizeof(DRM_CONTROL_MINOR_NAME),
3143 sizeof(DRM_RENDER_MINOR_NAME)) +
3144 3 /* length of the node number */;
3148 static int parse_separate_sysfs_files(int maj, int min,
3149 drmPciDeviceInfoPtr device,
3150 bool ignore_revision)
3152 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3153 static const char *attrs[] = {
3154 "revision", /* Older kernels are missing the file, so check for it first */
3160 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3161 unsigned int data[ARRAY_SIZE(attrs)];
3165 get_pci_path(maj, min, pci_path);
3167 for (unsigned i = ignore_revision ? 1 : 0; i < ARRAY_SIZE(attrs); i++) {
3168 snprintf(path, PATH_MAX, "%s/%s", pci_path, attrs[i]);
3169 fp = fopen(path, "r");
3173 ret = fscanf(fp, "%x", &data[i]);
3180 device->revision_id = ignore_revision ? 0xff : data[0] & 0xff;
3181 device->vendor_id = data[1] & 0xffff;
3182 device->device_id = data[2] & 0xffff;
3183 device->subvendor_id = data[3] & 0xffff;
3184 device->subdevice_id = data[4] & 0xffff;
3189 static int parse_config_sysfs_file(int maj, int min,
3190 drmPciDeviceInfoPtr device)
3192 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3193 unsigned char config[64];
3196 get_pci_path(maj, min, pci_path);
3198 snprintf(path, PATH_MAX, "%s/config", pci_path);
3199 fd = open(path, O_RDONLY);
3203 ret = read(fd, config, sizeof(config));
3208 device->vendor_id = config[0] | (config[1] << 8);
3209 device->device_id = config[2] | (config[3] << 8);
3210 device->revision_id = config[8];
3211 device->subvendor_id = config[44] | (config[45] << 8);
3212 device->subdevice_id = config[46] | (config[47] << 8);
3218 static int drmParsePciDeviceInfo(int maj, int min,
3219 drmPciDeviceInfoPtr device,
3223 if (!(flags & DRM_DEVICE_GET_PCI_REVISION))
3224 return parse_separate_sysfs_files(maj, min, device, true);
3226 if (parse_separate_sysfs_files(maj, min, device, false))
3227 return parse_config_sysfs_file(maj, min, device);
3230 #elif defined(__OpenBSD__)
3231 struct drm_pciinfo pinfo;
3234 type = drmGetMinorType(min);
3238 fd = drmOpenMinor(min, 0, type);
3242 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3248 device->vendor_id = pinfo.vendor_id;
3249 device->device_id = pinfo.device_id;
3250 device->revision_id = pinfo.revision_id;
3251 device->subvendor_id = pinfo.subvendor_id;
3252 device->subdevice_id = pinfo.subdevice_id;
3256 #warning "Missing implementation of drmParsePciDeviceInfo"
3261 static void drmFreePlatformDevice(drmDevicePtr device)
3263 if (device->deviceinfo.platform) {
3264 if (device->deviceinfo.platform->compatible) {
3265 char **compatible = device->deviceinfo.platform->compatible;
3267 while (*compatible) {
3272 free(device->deviceinfo.platform->compatible);
3277 static void drmFreeHost1xDevice(drmDevicePtr device)
3279 if (device->deviceinfo.host1x) {
3280 if (device->deviceinfo.host1x->compatible) {
3281 char **compatible = device->deviceinfo.host1x->compatible;
3283 while (*compatible) {
3288 free(device->deviceinfo.host1x->compatible);
3293 drm_public void drmFreeDevice(drmDevicePtr *device)
3299 switch ((*device)->bustype) {
3300 case DRM_BUS_PLATFORM:
3301 drmFreePlatformDevice(*device);
3304 case DRM_BUS_HOST1X:
3305 drmFreeHost1xDevice(*device);
3314 drm_public void drmFreeDevices(drmDevicePtr devices[], int count)
3318 if (devices == NULL)
3321 for (i = 0; i < count; i++)
3323 drmFreeDevice(&devices[i]);
3326 static drmDevicePtr drmDeviceAlloc(unsigned int type, const char *node,
3327 size_t bus_size, size_t device_size,
3330 size_t max_node_length, extra, size;
3331 drmDevicePtr device;
3335 max_node_length = ALIGN(drmGetMaxNodeName(), sizeof(void *));
3336 extra = DRM_NODE_MAX * (sizeof(void *) + max_node_length);
3338 size = sizeof(*device) + extra + bus_size + device_size;
3340 device = calloc(1, size);
3344 device->available_nodes = 1 << type;
3346 ptr = (char *)device + sizeof(*device);
3347 device->nodes = (char **)ptr;
3349 ptr += DRM_NODE_MAX * sizeof(void *);
3351 for (i = 0; i < DRM_NODE_MAX; i++) {
3352 device->nodes[i] = ptr;
3353 ptr += max_node_length;
3356 memcpy(device->nodes[type], node, max_node_length);
3363 static int drmProcessPciDevice(drmDevicePtr *device,
3364 const char *node, int node_type,
3365 int maj, int min, bool fetch_deviceinfo,
3372 dev = drmDeviceAlloc(node_type, node, sizeof(drmPciBusInfo),
3373 sizeof(drmPciDeviceInfo), &addr);
3377 dev->bustype = DRM_BUS_PCI;
3379 dev->businfo.pci = (drmPciBusInfoPtr)addr;
3381 ret = drmParsePciBusInfo(maj, min, dev->businfo.pci);
3385 // Fetch the device info if the user has requested it
3386 if (fetch_deviceinfo) {
3387 addr += sizeof(drmPciBusInfo);
3388 dev->deviceinfo.pci = (drmPciDeviceInfoPtr)addr;
3390 ret = drmParsePciDeviceInfo(maj, min, dev->deviceinfo.pci, flags);
3404 static int drmParseUsbBusInfo(int maj, int min, drmUsbBusInfoPtr info)
3407 char path[PATH_MAX + 1], *value;
3408 unsigned int bus, dev;
3411 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3413 value = sysfs_uevent_get(path, "BUSNUM");
3417 ret = sscanf(value, "%03u", &bus);
3423 value = sysfs_uevent_get(path, "DEVNUM");
3427 ret = sscanf(value, "%03u", &dev);
3438 #warning "Missing implementation of drmParseUsbBusInfo"
3443 static int drmParseUsbDeviceInfo(int maj, int min, drmUsbDeviceInfoPtr info)
3446 char path[PATH_MAX + 1], *value;
3447 unsigned int vendor, product;
3450 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3452 value = sysfs_uevent_get(path, "PRODUCT");
3456 ret = sscanf(value, "%x/%x", &vendor, &product);
3462 info->vendor = vendor;
3463 info->product = product;
3467 #warning "Missing implementation of drmParseUsbDeviceInfo"
3472 static int drmProcessUsbDevice(drmDevicePtr *device, const char *node,
3473 int node_type, int maj, int min,
3474 bool fetch_deviceinfo, uint32_t flags)
3480 dev = drmDeviceAlloc(node_type, node, sizeof(drmUsbBusInfo),
3481 sizeof(drmUsbDeviceInfo), &ptr);
3485 dev->bustype = DRM_BUS_USB;
3487 dev->businfo.usb = (drmUsbBusInfoPtr)ptr;
3489 ret = drmParseUsbBusInfo(maj, min, dev->businfo.usb);
3493 if (fetch_deviceinfo) {
3494 ptr += sizeof(drmUsbBusInfo);
3495 dev->deviceinfo.usb = (drmUsbDeviceInfoPtr)ptr;
3497 ret = drmParseUsbDeviceInfo(maj, min, dev->deviceinfo.usb);
3511 static int drmParsePlatformBusInfo(int maj, int min, drmPlatformBusInfoPtr info)
3514 char path[PATH_MAX + 1], *name;
3516 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3518 name = sysfs_uevent_get(path, "OF_FULLNAME");
3522 strncpy(info->fullname, name, DRM_PLATFORM_DEVICE_NAME_LEN);
3523 info->fullname[DRM_PLATFORM_DEVICE_NAME_LEN - 1] = '\0';
3528 #warning "Missing implementation of drmParsePlatformBusInfo"
3533 static int drmParsePlatformDeviceInfo(int maj, int min,
3534 drmPlatformDeviceInfoPtr info)
3537 char path[PATH_MAX + 1], *value;
3538 unsigned int count, i;
3541 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3543 value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
3547 sscanf(value, "%u", &count);
3550 info->compatible = calloc(count + 1, sizeof(*info->compatible));
3551 if (!info->compatible)
3554 for (i = 0; i < count; i++) {
3555 value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
3561 info->compatible[i] = value;
3568 free(info->compatible[i]);
3570 free(info->compatible);
3573 #warning "Missing implementation of drmParsePlatformDeviceInfo"
3578 static int drmProcessPlatformDevice(drmDevicePtr *device,
3579 const char *node, int node_type,
3580 int maj, int min, bool fetch_deviceinfo,
3587 dev = drmDeviceAlloc(node_type, node, sizeof(drmPlatformBusInfo),
3588 sizeof(drmPlatformDeviceInfo), &ptr);
3592 dev->bustype = DRM_BUS_PLATFORM;
3594 dev->businfo.platform = (drmPlatformBusInfoPtr)ptr;
3596 ret = drmParsePlatformBusInfo(maj, min, dev->businfo.platform);
3600 if (fetch_deviceinfo) {
3601 ptr += sizeof(drmPlatformBusInfo);
3602 dev->deviceinfo.platform = (drmPlatformDeviceInfoPtr)ptr;
3604 ret = drmParsePlatformDeviceInfo(maj, min, dev->deviceinfo.platform);
3618 static int drmParseHost1xBusInfo(int maj, int min, drmHost1xBusInfoPtr info)
3621 char path[PATH_MAX + 1], *name;
3623 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3625 name = sysfs_uevent_get(path, "OF_FULLNAME");
3629 strncpy(info->fullname, name, DRM_HOST1X_DEVICE_NAME_LEN);
3630 info->fullname[DRM_HOST1X_DEVICE_NAME_LEN - 1] = '\0';
3635 #warning "Missing implementation of drmParseHost1xBusInfo"
3640 static int drmParseHost1xDeviceInfo(int maj, int min,
3641 drmHost1xDeviceInfoPtr info)
3644 char path[PATH_MAX + 1], *value;
3645 unsigned int count, i;
3648 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3650 value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
3654 sscanf(value, "%u", &count);
3657 info->compatible = calloc(count + 1, sizeof(*info->compatible));
3658 if (!info->compatible)
3661 for (i = 0; i < count; i++) {
3662 value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
3668 info->compatible[i] = value;
3675 free(info->compatible[i]);
3677 free(info->compatible);
3680 #warning "Missing implementation of drmParseHost1xDeviceInfo"
3685 static int drmProcessHost1xDevice(drmDevicePtr *device,
3686 const char *node, int node_type,
3687 int maj, int min, bool fetch_deviceinfo,
3694 dev = drmDeviceAlloc(node_type, node, sizeof(drmHost1xBusInfo),
3695 sizeof(drmHost1xDeviceInfo), &ptr);
3699 dev->bustype = DRM_BUS_HOST1X;
3701 dev->businfo.host1x = (drmHost1xBusInfoPtr)ptr;
3703 ret = drmParseHost1xBusInfo(maj, min, dev->businfo.host1x);
3707 if (fetch_deviceinfo) {
3708 ptr += sizeof(drmHost1xBusInfo);
3709 dev->deviceinfo.host1x = (drmHost1xDeviceInfoPtr)ptr;
3711 ret = drmParseHost1xDeviceInfo(maj, min, dev->deviceinfo.host1x);
3726 process_device(drmDevicePtr *device, const char *d_name,
3727 int req_subsystem_type,
3728 bool fetch_deviceinfo, uint32_t flags)
3731 char node[PATH_MAX + 1];
3732 int node_type, subsystem_type;
3733 unsigned int maj, min;
3735 node_type = drmGetNodeType(d_name);
3739 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, d_name);
3740 if (stat(node, &sbuf))
3743 maj = major(sbuf.st_rdev);
3744 min = minor(sbuf.st_rdev);
3746 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3749 subsystem_type = drmParseSubsystemType(maj, min);
3750 if (req_subsystem_type != -1 && req_subsystem_type != subsystem_type)
3753 switch (subsystem_type) {
3755 case DRM_BUS_VIRTIO:
3756 return drmProcessPciDevice(device, node, node_type, maj, min,
3757 fetch_deviceinfo, flags);
3759 return drmProcessUsbDevice(device, node, node_type, maj, min,
3760 fetch_deviceinfo, flags);
3761 case DRM_BUS_PLATFORM:
3762 return drmProcessPlatformDevice(device, node, node_type, maj, min,
3763 fetch_deviceinfo, flags);
3764 case DRM_BUS_HOST1X:
3765 return drmProcessHost1xDevice(device, node, node_type, maj, min,
3766 fetch_deviceinfo, flags);
3772 /* Consider devices located on the same bus as duplicate and fold the respective
3773 * entries into a single one.
3775 * Note: this leaves "gaps" in the array, while preserving the length.
3777 static void drmFoldDuplicatedDevices(drmDevicePtr local_devices[], int count)
3779 int node_type, i, j;
3781 for (i = 0; i < count; i++) {
3782 for (j = i + 1; j < count; j++) {
3783 if (drmDevicesEqual(local_devices[i], local_devices[j])) {
3784 local_devices[i]->available_nodes |= local_devices[j]->available_nodes;
3785 node_type = log2(local_devices[j]->available_nodes);
3786 memcpy(local_devices[i]->nodes[node_type],
3787 local_devices[j]->nodes[node_type], drmGetMaxNodeName());
3788 drmFreeDevice(&local_devices[j]);
3794 /* Check that the given flags are valid returning 0 on success */
3796 drm_device_validate_flags(uint32_t flags)
3798 return (flags & ~DRM_DEVICE_GET_PCI_REVISION);
3802 drm_device_has_rdev(drmDevicePtr device, dev_t find_rdev)
3806 for (int i = 0; i < DRM_NODE_MAX; i++) {
3807 if (device->available_nodes & 1 << i) {
3808 if (stat(device->nodes[i], &sbuf) == 0 &&
3809 sbuf.st_rdev == find_rdev)
3817 * The kernel drm core has a number of places that assume maximum of
3818 * 3x64 devices nodes. That's 64 for each of primary, control and
3819 * render nodes. Rounded it up to 256 for simplicity.
3821 #define MAX_DRM_NODES 256
3824 * Get information about the opened drm device
3826 * \param fd file descriptor of the drm device
3827 * \param flags feature/behaviour bitmask
3828 * \param device the address of a drmDevicePtr where the information
3829 * will be allocated in stored
3831 * \return zero on success, negative error code otherwise.
3833 * \note Unlike drmGetDevice it does not retrieve the pci device revision field
3834 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
3836 drm_public int drmGetDevice2(int fd, uint32_t flags, drmDevicePtr *device)
3840 * DRI device nodes on OpenBSD are not in their own directory, they reside
3841 * in /dev along with a large number of statically generated /dev nodes.
3842 * Avoid stat'ing all of /dev needlessly by implementing this custom path.
3846 char node[PATH_MAX + 1];
3847 const char *dev_name;
3848 int node_type, subsystem_type;
3849 int maj, min, n, ret, base;
3851 if (fd == -1 || device == NULL)
3854 if (fstat(fd, &sbuf))
3857 maj = major(sbuf.st_rdev);
3858 min = minor(sbuf.st_rdev);
3860 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3863 node_type = drmGetMinorType(min);
3864 if (node_type == -1)
3867 switch (node_type) {
3868 case DRM_NODE_PRIMARY:
3869 dev_name = DRM_DEV_NAME;
3871 case DRM_NODE_CONTROL:
3872 dev_name = DRM_CONTROL_DEV_NAME;
3874 case DRM_NODE_RENDER:
3875 dev_name = DRM_RENDER_DEV_NAME;
3881 base = drmGetMinorBase(node_type);
3885 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min - base);
3886 if (n == -1 || n >= PATH_MAX)
3888 if (stat(node, &sbuf))
3891 subsystem_type = drmParseSubsystemType(maj, min);
3892 if (subsystem_type != DRM_BUS_PCI)
3895 ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
3903 drmDevicePtr local_devices[MAX_DRM_NODES];
3906 struct dirent *dent;
3910 int ret, i, node_count;
3913 if (drm_device_validate_flags(flags))
3916 if (fd == -1 || device == NULL)
3919 if (fstat(fd, &sbuf))
3922 find_rdev = sbuf.st_rdev;
3923 maj = major(sbuf.st_rdev);
3924 min = minor(sbuf.st_rdev);
3926 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3929 subsystem_type = drmParseSubsystemType(maj, min);
3930 if (subsystem_type < 0)
3931 return subsystem_type;
3933 sysdir = opendir(DRM_DIR_NAME);
3938 while ((dent = readdir(sysdir))) {
3939 ret = process_device(&d, dent->d_name, subsystem_type, true, flags);
3943 if (i >= MAX_DRM_NODES) {
3944 fprintf(stderr, "More than %d drm nodes detected. "
3945 "Please report a bug - that should not happen.\n"
3946 "Skipping extra nodes\n", MAX_DRM_NODES);
3949 local_devices[i] = d;
3954 drmFoldDuplicatedDevices(local_devices, node_count);
3958 for (i = 0; i < node_count; i++) {
3959 if (!local_devices[i])
3962 if (drm_device_has_rdev(local_devices[i], find_rdev))
3963 *device = local_devices[i];
3965 drmFreeDevice(&local_devices[i]);
3969 if (*device == NULL)
3976 * Get information about the opened drm device
3978 * \param fd file descriptor of the drm device
3979 * \param device the address of a drmDevicePtr where the information
3980 * will be allocated in stored
3982 * \return zero on success, negative error code otherwise.
3984 drm_public int drmGetDevice(int fd, drmDevicePtr *device)
3986 return drmGetDevice2(fd, DRM_DEVICE_GET_PCI_REVISION, device);
3990 * Get drm devices on the system
3992 * \param flags feature/behaviour bitmask
3993 * \param devices the array of devices with drmDevicePtr elements
3994 * can be NULL to get the device number first
3995 * \param max_devices the maximum number of devices for the array
3997 * \return on error - negative error code,
3998 * if devices is NULL - total number of devices available on the system,
3999 * alternatively the number of devices stored in devices[], which is
4000 * capped by the max_devices.
4002 * \note Unlike drmGetDevices it does not retrieve the pci device revision field
4003 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
4005 drm_public int drmGetDevices2(uint32_t flags, drmDevicePtr devices[],
4008 drmDevicePtr local_devices[MAX_DRM_NODES];
4009 drmDevicePtr device;
4011 struct dirent *dent;
4012 int ret, i, node_count, device_count;
4014 if (drm_device_validate_flags(flags))
4017 sysdir = opendir(DRM_DIR_NAME);
4022 while ((dent = readdir(sysdir))) {
4023 ret = process_device(&device, dent->d_name, -1, devices != NULL, flags);
4027 if (i >= MAX_DRM_NODES) {
4028 fprintf(stderr, "More than %d drm nodes detected. "
4029 "Please report a bug - that should not happen.\n"
4030 "Skipping extra nodes\n", MAX_DRM_NODES);
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 return device_count;
4058 * Get drm devices on the system
4060 * \param devices the array of devices with drmDevicePtr elements
4061 * can be NULL to get the device number first
4062 * \param max_devices the maximum number of devices for the array
4064 * \return on error - negative error code,
4065 * if devices is NULL - total number of devices available on the system,
4066 * alternatively the number of devices stored in devices[], which is
4067 * capped by the max_devices.
4069 drm_public int drmGetDevices(drmDevicePtr devices[], int max_devices)
4071 return drmGetDevices2(DRM_DEVICE_GET_PCI_REVISION, devices, max_devices);
4074 drm_public char *drmGetDeviceNameFromFd2(int fd)
4078 char path[PATH_MAX + 1], *value;
4079 unsigned int maj, min;
4081 if (fstat(fd, &sbuf))
4084 maj = major(sbuf.st_rdev);
4085 min = minor(sbuf.st_rdev);
4087 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4090 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d", maj, min);
4092 value = sysfs_uevent_get(path, "DEVNAME");
4096 snprintf(path, sizeof(path), "/dev/%s", value);
4099 return strdup(path);
4102 char node[PATH_MAX + 1];
4103 const char *dev_name;
4105 int maj, min, n, base;
4107 if (fstat(fd, &sbuf))
4110 maj = major(sbuf.st_rdev);
4111 min = minor(sbuf.st_rdev);
4113 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4116 node_type = drmGetMinorType(min);
4117 if (node_type == -1)
4120 switch (node_type) {
4121 case DRM_NODE_PRIMARY:
4122 dev_name = DRM_DEV_NAME;
4124 case DRM_NODE_CONTROL:
4125 dev_name = DRM_CONTROL_DEV_NAME;
4127 case DRM_NODE_RENDER:
4128 dev_name = DRM_RENDER_DEV_NAME;
4134 base = drmGetMinorBase(node_type);
4138 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min - base);
4139 if (n == -1 || n >= PATH_MAX)
4142 return strdup(node);
4146 drm_public int drmSyncobjCreate(int fd, uint32_t flags, uint32_t *handle)
4148 struct drm_syncobj_create args;
4154 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_CREATE, &args);
4157 *handle = args.handle;
4161 drm_public int drmSyncobjDestroy(int fd, uint32_t handle)
4163 struct drm_syncobj_destroy args;
4166 args.handle = handle;
4167 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_DESTROY, &args);
4170 drm_public int drmSyncobjHandleToFD(int fd, uint32_t handle, int *obj_fd)
4172 struct drm_syncobj_handle args;
4177 args.handle = handle;
4178 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4185 drm_public int drmSyncobjFDToHandle(int fd, int obj_fd, uint32_t *handle)
4187 struct drm_syncobj_handle args;
4193 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4196 *handle = args.handle;
4200 drm_public int drmSyncobjImportSyncFile(int fd, uint32_t handle,
4203 struct drm_syncobj_handle args;
4206 args.fd = sync_file_fd;
4207 args.handle = handle;
4208 args.flags = DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE;
4209 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4212 drm_public int drmSyncobjExportSyncFile(int fd, uint32_t handle,
4215 struct drm_syncobj_handle args;
4220 args.handle = handle;
4221 args.flags = DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE;
4222 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4225 *sync_file_fd = args.fd;
4229 drm_public int drmSyncobjWait(int fd, uint32_t *handles, unsigned num_handles,
4230 int64_t timeout_nsec, unsigned flags,
4231 uint32_t *first_signaled)
4233 struct drm_syncobj_wait args;
4237 args.handles = (uintptr_t)handles;
4238 args.timeout_nsec = timeout_nsec;
4239 args.count_handles = num_handles;
4242 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_WAIT, &args);
4247 *first_signaled = args.first_signaled;
4251 drm_public int drmSyncobjReset(int fd, const uint32_t *handles,
4252 uint32_t handle_count)
4254 struct drm_syncobj_array args;
4258 args.handles = (uintptr_t)handles;
4259 args.count_handles = handle_count;
4261 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_RESET, &args);
4265 drm_public int drmSyncobjSignal(int fd, const uint32_t *handles,
4266 uint32_t handle_count)
4268 struct drm_syncobj_array args;
4272 args.handles = (uintptr_t)handles;
4273 args.count_handles = handle_count;
4275 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_SIGNAL, &args);