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 drm_public int drmGetNodeTypeFromFd(int fd)
2775 if (fstat(fd, &sbuf))
2778 maj = major(sbuf.st_rdev);
2779 min = minor(sbuf.st_rdev);
2781 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode)) {
2786 type = drmGetMinorType(min);
2792 drm_public int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags,
2795 struct drm_prime_handle args;
2800 args.handle = handle;
2802 ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
2806 *prime_fd = args.fd;
2810 drm_public int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
2812 struct drm_prime_handle args;
2817 ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
2821 *handle = args.handle;
2825 static char *drmGetMinorNameForFD(int fd, int type)
2831 const char *name = drmGetMinorName(type);
2833 char dev_name[64], buf[64];
2841 if (fstat(fd, &sbuf))
2844 maj = major(sbuf.st_rdev);
2845 min = minor(sbuf.st_rdev);
2847 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
2850 snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
2852 sysdir = opendir(buf);
2856 while ((ent = readdir(sysdir))) {
2857 if (strncmp(ent->d_name, name, len) == 0) {
2858 snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
2862 return strdup(dev_name);
2870 char buf[PATH_MAX + 1];
2871 const char *dev_name;
2872 unsigned int maj, min;
2875 if (fstat(fd, &sbuf))
2878 maj = major(sbuf.st_rdev);
2879 min = minor(sbuf.st_rdev);
2881 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
2885 case DRM_NODE_PRIMARY:
2886 dev_name = DRM_DEV_NAME;
2888 case DRM_NODE_CONTROL:
2889 dev_name = DRM_CONTROL_DEV_NAME;
2891 case DRM_NODE_RENDER:
2892 dev_name = DRM_RENDER_DEV_NAME;
2898 base = drmGetMinorBase(type);
2902 n = snprintf(buf, sizeof(buf), dev_name, DRM_DIR_NAME, min - base);
2903 if (n == -1 || n >= sizeof(buf))
2910 drm_public char *drmGetPrimaryDeviceNameFromFd(int fd)
2912 return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
2915 drm_public char *drmGetRenderDeviceNameFromFd(int fd)
2917 return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
2921 static char * DRM_PRINTFLIKE(2, 3)
2922 sysfs_uevent_get(const char *path, const char *fmt, ...)
2924 char filename[PATH_MAX + 1], *key, *line = NULL, *value = NULL;
2925 size_t size = 0, len;
2931 num = vasprintf(&key, fmt, ap);
2935 snprintf(filename, sizeof(filename), "%s/uevent", path);
2937 fp = fopen(filename, "r");
2943 while ((num = getline(&line, &size, fp)) >= 0) {
2944 if ((strncmp(line, key, len) == 0) && (line[len] == '=')) {
2945 char *start = line + len + 1, *end = line + num - 1;
2950 value = strndup(start, end - start);
2964 /* Little white lie to avoid major rework of the existing code */
2965 #define DRM_BUS_VIRTIO 0x10
2967 static int drmParseSubsystemType(int maj, int min)
2970 char path[PATH_MAX + 1];
2971 char link[PATH_MAX + 1] = "";
2974 snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/subsystem",
2977 if (readlink(path, link, PATH_MAX) < 0)
2980 name = strrchr(link, '/');
2984 if (strncmp(name, "/pci", 4) == 0)
2987 if (strncmp(name, "/usb", 4) == 0)
2990 if (strncmp(name, "/platform", 9) == 0)
2991 return DRM_BUS_PLATFORM;
2993 if (strncmp(name, "/host1x", 7) == 0)
2994 return DRM_BUS_HOST1X;
2996 if (strncmp(name, "/virtio", 7) == 0)
2997 return DRM_BUS_VIRTIO;
3000 #elif defined(__OpenBSD__)
3003 #warning "Missing implementation of drmParseSubsystemType"
3009 get_pci_path(int maj, int min, char *pci_path)
3011 char path[PATH_MAX + 1], *term;
3013 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3014 if (!realpath(path, pci_path)) {
3015 strcpy(pci_path, path);
3019 term = strrchr(pci_path, '/');
3020 if (term && strncmp(term, "/virtio", 7) == 0)
3024 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
3027 unsigned int domain, bus, dev, func;
3028 char pci_path[PATH_MAX + 1], *value;
3031 get_pci_path(maj, min, pci_path);
3033 value = sysfs_uevent_get(pci_path, "PCI_SLOT_NAME");
3037 num = sscanf(value, "%04x:%02x:%02x.%1u", &domain, &bus, &dev, &func);
3043 info->domain = domain;
3049 #elif defined(__OpenBSD__)
3050 struct drm_pciinfo pinfo;
3053 type = drmGetMinorType(min);
3057 fd = drmOpenMinor(min, 0, type);
3061 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3067 info->domain = pinfo.domain;
3068 info->bus = pinfo.bus;
3069 info->dev = pinfo.dev;
3070 info->func = pinfo.func;
3074 #warning "Missing implementation of drmParsePciBusInfo"
3079 drm_public int drmDevicesEqual(drmDevicePtr a, drmDevicePtr b)
3081 if (a == NULL || b == NULL)
3084 if (a->bustype != b->bustype)
3087 switch (a->bustype) {
3089 return memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo)) == 0;
3092 return memcmp(a->businfo.usb, b->businfo.usb, sizeof(drmUsbBusInfo)) == 0;
3094 case DRM_BUS_PLATFORM:
3095 return memcmp(a->businfo.platform, b->businfo.platform, sizeof(drmPlatformBusInfo)) == 0;
3097 case DRM_BUS_HOST1X:
3098 return memcmp(a->businfo.host1x, b->businfo.host1x, sizeof(drmHost1xBusInfo)) == 0;
3107 static int drmGetNodeType(const char *name)
3109 if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
3110 sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
3111 return DRM_NODE_PRIMARY;
3113 if (strncmp(name, DRM_CONTROL_MINOR_NAME,
3114 sizeof(DRM_CONTROL_MINOR_NAME ) - 1) == 0)
3115 return DRM_NODE_CONTROL;
3117 if (strncmp(name, DRM_RENDER_MINOR_NAME,
3118 sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
3119 return DRM_NODE_RENDER;
3124 static int drmGetMaxNodeName(void)
3126 return sizeof(DRM_DIR_NAME) +
3127 MAX3(sizeof(DRM_PRIMARY_MINOR_NAME),
3128 sizeof(DRM_CONTROL_MINOR_NAME),
3129 sizeof(DRM_RENDER_MINOR_NAME)) +
3130 3 /* length of the node number */;
3134 static int parse_separate_sysfs_files(int maj, int min,
3135 drmPciDeviceInfoPtr device,
3136 bool ignore_revision)
3138 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3139 static const char *attrs[] = {
3140 "revision", /* Older kernels are missing the file, so check for it first */
3146 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3147 unsigned int data[ARRAY_SIZE(attrs)];
3151 get_pci_path(maj, min, pci_path);
3153 for (unsigned i = ignore_revision ? 1 : 0; i < ARRAY_SIZE(attrs); i++) {
3154 snprintf(path, PATH_MAX, "%s/%s", pci_path, attrs[i]);
3155 fp = fopen(path, "r");
3159 ret = fscanf(fp, "%x", &data[i]);
3166 device->revision_id = ignore_revision ? 0xff : data[0] & 0xff;
3167 device->vendor_id = data[1] & 0xffff;
3168 device->device_id = data[2] & 0xffff;
3169 device->subvendor_id = data[3] & 0xffff;
3170 device->subdevice_id = data[4] & 0xffff;
3175 static int parse_config_sysfs_file(int maj, int min,
3176 drmPciDeviceInfoPtr device)
3178 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3179 unsigned char config[64];
3182 get_pci_path(maj, min, pci_path);
3184 snprintf(path, PATH_MAX, "%s/config", pci_path);
3185 fd = open(path, O_RDONLY);
3189 ret = read(fd, config, sizeof(config));
3194 device->vendor_id = config[0] | (config[1] << 8);
3195 device->device_id = config[2] | (config[3] << 8);
3196 device->revision_id = config[8];
3197 device->subvendor_id = config[44] | (config[45] << 8);
3198 device->subdevice_id = config[46] | (config[47] << 8);
3204 static int drmParsePciDeviceInfo(int maj, int min,
3205 drmPciDeviceInfoPtr device,
3209 if (!(flags & DRM_DEVICE_GET_PCI_REVISION))
3210 return parse_separate_sysfs_files(maj, min, device, true);
3212 if (parse_separate_sysfs_files(maj, min, device, false))
3213 return parse_config_sysfs_file(maj, min, device);
3216 #elif defined(__OpenBSD__)
3217 struct drm_pciinfo pinfo;
3220 type = drmGetMinorType(min);
3224 fd = drmOpenMinor(min, 0, type);
3228 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3234 device->vendor_id = pinfo.vendor_id;
3235 device->device_id = pinfo.device_id;
3236 device->revision_id = pinfo.revision_id;
3237 device->subvendor_id = pinfo.subvendor_id;
3238 device->subdevice_id = pinfo.subdevice_id;
3242 #warning "Missing implementation of drmParsePciDeviceInfo"
3247 static void drmFreePlatformDevice(drmDevicePtr device)
3249 if (device->deviceinfo.platform) {
3250 if (device->deviceinfo.platform->compatible) {
3251 char **compatible = device->deviceinfo.platform->compatible;
3253 while (*compatible) {
3258 free(device->deviceinfo.platform->compatible);
3263 static void drmFreeHost1xDevice(drmDevicePtr device)
3265 if (device->deviceinfo.host1x) {
3266 if (device->deviceinfo.host1x->compatible) {
3267 char **compatible = device->deviceinfo.host1x->compatible;
3269 while (*compatible) {
3274 free(device->deviceinfo.host1x->compatible);
3279 drm_public void drmFreeDevice(drmDevicePtr *device)
3285 switch ((*device)->bustype) {
3286 case DRM_BUS_PLATFORM:
3287 drmFreePlatformDevice(*device);
3290 case DRM_BUS_HOST1X:
3291 drmFreeHost1xDevice(*device);
3300 drm_public void drmFreeDevices(drmDevicePtr devices[], int count)
3304 if (devices == NULL)
3307 for (i = 0; i < count; i++)
3309 drmFreeDevice(&devices[i]);
3312 static drmDevicePtr drmDeviceAlloc(unsigned int type, const char *node,
3313 size_t bus_size, size_t device_size,
3316 size_t max_node_length, extra, size;
3317 drmDevicePtr device;
3321 max_node_length = ALIGN(drmGetMaxNodeName(), sizeof(void *));
3322 extra = DRM_NODE_MAX * (sizeof(void *) + max_node_length);
3324 size = sizeof(*device) + extra + bus_size + device_size;
3326 device = calloc(1, size);
3330 device->available_nodes = 1 << type;
3332 ptr = (char *)device + sizeof(*device);
3333 device->nodes = (char **)ptr;
3335 ptr += DRM_NODE_MAX * sizeof(void *);
3337 for (i = 0; i < DRM_NODE_MAX; i++) {
3338 device->nodes[i] = ptr;
3339 ptr += max_node_length;
3342 memcpy(device->nodes[type], node, max_node_length);
3349 static int drmProcessPciDevice(drmDevicePtr *device,
3350 const char *node, int node_type,
3351 int maj, int min, bool fetch_deviceinfo,
3358 dev = drmDeviceAlloc(node_type, node, sizeof(drmPciBusInfo),
3359 sizeof(drmPciDeviceInfo), &addr);
3363 dev->bustype = DRM_BUS_PCI;
3365 dev->businfo.pci = (drmPciBusInfoPtr)addr;
3367 ret = drmParsePciBusInfo(maj, min, dev->businfo.pci);
3371 // Fetch the device info if the user has requested it
3372 if (fetch_deviceinfo) {
3373 addr += sizeof(drmPciBusInfo);
3374 dev->deviceinfo.pci = (drmPciDeviceInfoPtr)addr;
3376 ret = drmParsePciDeviceInfo(maj, min, dev->deviceinfo.pci, flags);
3390 static int drmParseUsbBusInfo(int maj, int min, drmUsbBusInfoPtr info)
3393 char path[PATH_MAX + 1], *value;
3394 unsigned int bus, dev;
3397 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3399 value = sysfs_uevent_get(path, "BUSNUM");
3403 ret = sscanf(value, "%03u", &bus);
3409 value = sysfs_uevent_get(path, "DEVNUM");
3413 ret = sscanf(value, "%03u", &dev);
3424 #warning "Missing implementation of drmParseUsbBusInfo"
3429 static int drmParseUsbDeviceInfo(int maj, int min, drmUsbDeviceInfoPtr info)
3432 char path[PATH_MAX + 1], *value;
3433 unsigned int vendor, product;
3436 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3438 value = sysfs_uevent_get(path, "PRODUCT");
3442 ret = sscanf(value, "%x/%x", &vendor, &product);
3448 info->vendor = vendor;
3449 info->product = product;
3453 #warning "Missing implementation of drmParseUsbDeviceInfo"
3458 static int drmProcessUsbDevice(drmDevicePtr *device, const char *node,
3459 int node_type, int maj, int min,
3460 bool fetch_deviceinfo, uint32_t flags)
3466 dev = drmDeviceAlloc(node_type, node, sizeof(drmUsbBusInfo),
3467 sizeof(drmUsbDeviceInfo), &ptr);
3471 dev->bustype = DRM_BUS_USB;
3473 dev->businfo.usb = (drmUsbBusInfoPtr)ptr;
3475 ret = drmParseUsbBusInfo(maj, min, dev->businfo.usb);
3479 if (fetch_deviceinfo) {
3480 ptr += sizeof(drmUsbBusInfo);
3481 dev->deviceinfo.usb = (drmUsbDeviceInfoPtr)ptr;
3483 ret = drmParseUsbDeviceInfo(maj, min, dev->deviceinfo.usb);
3497 static int drmParsePlatformBusInfo(int maj, int min, drmPlatformBusInfoPtr info)
3500 char path[PATH_MAX + 1], *name;
3502 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3504 name = sysfs_uevent_get(path, "OF_FULLNAME");
3508 strncpy(info->fullname, name, DRM_PLATFORM_DEVICE_NAME_LEN);
3509 info->fullname[DRM_PLATFORM_DEVICE_NAME_LEN - 1] = '\0';
3514 #warning "Missing implementation of drmParsePlatformBusInfo"
3519 static int drmParsePlatformDeviceInfo(int maj, int min,
3520 drmPlatformDeviceInfoPtr info)
3523 char path[PATH_MAX + 1], *value;
3524 unsigned int count, i;
3527 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3529 value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
3533 sscanf(value, "%u", &count);
3536 info->compatible = calloc(count + 1, sizeof(*info->compatible));
3537 if (!info->compatible)
3540 for (i = 0; i < count; i++) {
3541 value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
3547 info->compatible[i] = value;
3554 free(info->compatible[i]);
3556 free(info->compatible);
3559 #warning "Missing implementation of drmParsePlatformDeviceInfo"
3564 static int drmProcessPlatformDevice(drmDevicePtr *device,
3565 const char *node, int node_type,
3566 int maj, int min, bool fetch_deviceinfo,
3573 dev = drmDeviceAlloc(node_type, node, sizeof(drmPlatformBusInfo),
3574 sizeof(drmPlatformDeviceInfo), &ptr);
3578 dev->bustype = DRM_BUS_PLATFORM;
3580 dev->businfo.platform = (drmPlatformBusInfoPtr)ptr;
3582 ret = drmParsePlatformBusInfo(maj, min, dev->businfo.platform);
3586 if (fetch_deviceinfo) {
3587 ptr += sizeof(drmPlatformBusInfo);
3588 dev->deviceinfo.platform = (drmPlatformDeviceInfoPtr)ptr;
3590 ret = drmParsePlatformDeviceInfo(maj, min, dev->deviceinfo.platform);
3604 static int drmParseHost1xBusInfo(int maj, int min, drmHost1xBusInfoPtr info)
3607 char path[PATH_MAX + 1], *name;
3609 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3611 name = sysfs_uevent_get(path, "OF_FULLNAME");
3615 strncpy(info->fullname, name, DRM_HOST1X_DEVICE_NAME_LEN);
3616 info->fullname[DRM_HOST1X_DEVICE_NAME_LEN - 1] = '\0';
3621 #warning "Missing implementation of drmParseHost1xBusInfo"
3626 static int drmParseHost1xDeviceInfo(int maj, int min,
3627 drmHost1xDeviceInfoPtr info)
3630 char path[PATH_MAX + 1], *value;
3631 unsigned int count, i;
3634 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3636 value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
3640 sscanf(value, "%u", &count);
3643 info->compatible = calloc(count + 1, sizeof(*info->compatible));
3644 if (!info->compatible)
3647 for (i = 0; i < count; i++) {
3648 value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
3654 info->compatible[i] = value;
3661 free(info->compatible[i]);
3663 free(info->compatible);
3666 #warning "Missing implementation of drmParseHost1xDeviceInfo"
3671 static int drmProcessHost1xDevice(drmDevicePtr *device,
3672 const char *node, int node_type,
3673 int maj, int min, bool fetch_deviceinfo,
3680 dev = drmDeviceAlloc(node_type, node, sizeof(drmHost1xBusInfo),
3681 sizeof(drmHost1xDeviceInfo), &ptr);
3685 dev->bustype = DRM_BUS_HOST1X;
3687 dev->businfo.host1x = (drmHost1xBusInfoPtr)ptr;
3689 ret = drmParseHost1xBusInfo(maj, min, dev->businfo.host1x);
3693 if (fetch_deviceinfo) {
3694 ptr += sizeof(drmHost1xBusInfo);
3695 dev->deviceinfo.host1x = (drmHost1xDeviceInfoPtr)ptr;
3697 ret = drmParseHost1xDeviceInfo(maj, min, dev->deviceinfo.host1x);
3712 process_device(drmDevicePtr *device, const char *d_name,
3713 int req_subsystem_type,
3714 bool fetch_deviceinfo, uint32_t flags)
3717 char node[PATH_MAX + 1];
3718 int node_type, subsystem_type;
3719 unsigned int maj, min;
3721 node_type = drmGetNodeType(d_name);
3725 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, d_name);
3726 if (stat(node, &sbuf))
3729 maj = major(sbuf.st_rdev);
3730 min = minor(sbuf.st_rdev);
3732 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3735 subsystem_type = drmParseSubsystemType(maj, min);
3736 if (req_subsystem_type != -1 && req_subsystem_type != subsystem_type)
3739 switch (subsystem_type) {
3741 case DRM_BUS_VIRTIO:
3742 return drmProcessPciDevice(device, node, node_type, maj, min,
3743 fetch_deviceinfo, flags);
3745 return drmProcessUsbDevice(device, node, node_type, maj, min,
3746 fetch_deviceinfo, flags);
3747 case DRM_BUS_PLATFORM:
3748 return drmProcessPlatformDevice(device, node, node_type, maj, min,
3749 fetch_deviceinfo, flags);
3750 case DRM_BUS_HOST1X:
3751 return drmProcessHost1xDevice(device, node, node_type, maj, min,
3752 fetch_deviceinfo, flags);
3758 /* Consider devices located on the same bus as duplicate and fold the respective
3759 * entries into a single one.
3761 * Note: this leaves "gaps" in the array, while preserving the length.
3763 static void drmFoldDuplicatedDevices(drmDevicePtr local_devices[], int count)
3765 int node_type, i, j;
3767 for (i = 0; i < count; i++) {
3768 for (j = i + 1; j < count; j++) {
3769 if (drmDevicesEqual(local_devices[i], local_devices[j])) {
3770 local_devices[i]->available_nodes |= local_devices[j]->available_nodes;
3771 node_type = log2(local_devices[j]->available_nodes);
3772 memcpy(local_devices[i]->nodes[node_type],
3773 local_devices[j]->nodes[node_type], drmGetMaxNodeName());
3774 drmFreeDevice(&local_devices[j]);
3780 /* Check that the given flags are valid returning 0 on success */
3782 drm_device_validate_flags(uint32_t flags)
3784 return (flags & ~DRM_DEVICE_GET_PCI_REVISION);
3788 drm_device_has_rdev(drmDevicePtr device, dev_t find_rdev)
3792 for (int i = 0; i < DRM_NODE_MAX; i++) {
3793 if (device->available_nodes & 1 << i) {
3794 if (stat(device->nodes[i], &sbuf) == 0 &&
3795 sbuf.st_rdev == find_rdev)
3803 * The kernel drm core has a number of places that assume maximum of
3804 * 3x64 devices nodes. That's 64 for each of primary, control and
3805 * render nodes. Rounded it up to 256 for simplicity.
3807 #define MAX_DRM_NODES 256
3810 * Get information about the opened drm device
3812 * \param fd file descriptor of the drm device
3813 * \param flags feature/behaviour bitmask
3814 * \param device the address of a drmDevicePtr where the information
3815 * will be allocated in stored
3817 * \return zero on success, negative error code otherwise.
3819 * \note Unlike drmGetDevice it does not retrieve the pci device revision field
3820 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
3822 drm_public int drmGetDevice2(int fd, uint32_t flags, drmDevicePtr *device)
3826 * DRI device nodes on OpenBSD are not in their own directory, they reside
3827 * in /dev along with a large number of statically generated /dev nodes.
3828 * Avoid stat'ing all of /dev needlessly by implementing this custom path.
3832 char node[PATH_MAX + 1];
3833 const char *dev_name;
3834 int node_type, subsystem_type;
3835 int maj, min, n, ret, base;
3837 if (fd == -1 || device == NULL)
3840 if (fstat(fd, &sbuf))
3843 maj = major(sbuf.st_rdev);
3844 min = minor(sbuf.st_rdev);
3846 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3849 node_type = drmGetMinorType(min);
3850 if (node_type == -1)
3853 switch (node_type) {
3854 case DRM_NODE_PRIMARY:
3855 dev_name = DRM_DEV_NAME;
3857 case DRM_NODE_CONTROL:
3858 dev_name = DRM_CONTROL_DEV_NAME;
3860 case DRM_NODE_RENDER:
3861 dev_name = DRM_RENDER_DEV_NAME;
3867 base = drmGetMinorBase(node_type);
3871 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min - base);
3872 if (n == -1 || n >= PATH_MAX)
3874 if (stat(node, &sbuf))
3877 subsystem_type = drmParseSubsystemType(maj, min);
3878 if (subsystem_type != DRM_BUS_PCI)
3881 ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
3889 drmDevicePtr local_devices[MAX_DRM_NODES];
3892 struct dirent *dent;
3896 int ret, i, node_count;
3899 if (drm_device_validate_flags(flags))
3902 if (fd == -1 || device == NULL)
3905 if (fstat(fd, &sbuf))
3908 find_rdev = sbuf.st_rdev;
3909 maj = major(sbuf.st_rdev);
3910 min = minor(sbuf.st_rdev);
3912 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3915 subsystem_type = drmParseSubsystemType(maj, min);
3916 if (subsystem_type < 0)
3917 return subsystem_type;
3919 sysdir = opendir(DRM_DIR_NAME);
3924 while ((dent = readdir(sysdir))) {
3925 ret = process_device(&d, dent->d_name, subsystem_type, true, flags);
3929 if (i >= MAX_DRM_NODES) {
3930 fprintf(stderr, "More than %d drm nodes detected. "
3931 "Please report a bug - that should not happen.\n"
3932 "Skipping extra nodes\n", MAX_DRM_NODES);
3935 local_devices[i] = d;
3940 drmFoldDuplicatedDevices(local_devices, node_count);
3944 for (i = 0; i < node_count; i++) {
3945 if (!local_devices[i])
3948 if (drm_device_has_rdev(local_devices[i], find_rdev))
3949 *device = local_devices[i];
3951 drmFreeDevice(&local_devices[i]);
3955 if (*device == NULL)
3962 * Get information about the opened drm device
3964 * \param fd file descriptor of the drm device
3965 * \param device the address of a drmDevicePtr where the information
3966 * will be allocated in stored
3968 * \return zero on success, negative error code otherwise.
3970 drm_public int drmGetDevice(int fd, drmDevicePtr *device)
3972 return drmGetDevice2(fd, DRM_DEVICE_GET_PCI_REVISION, device);
3976 * Get drm devices on the system
3978 * \param flags feature/behaviour bitmask
3979 * \param devices the array of devices with drmDevicePtr elements
3980 * can be NULL to get the device number first
3981 * \param max_devices the maximum number of devices for the array
3983 * \return on error - negative error code,
3984 * if devices is NULL - total number of devices available on the system,
3985 * alternatively the number of devices stored in devices[], which is
3986 * capped by the max_devices.
3988 * \note Unlike drmGetDevices it does not retrieve the pci device revision field
3989 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
3991 drm_public int drmGetDevices2(uint32_t flags, drmDevicePtr devices[],
3994 drmDevicePtr local_devices[MAX_DRM_NODES];
3995 drmDevicePtr device;
3997 struct dirent *dent;
3998 int ret, i, node_count, device_count;
4000 if (drm_device_validate_flags(flags))
4003 sysdir = opendir(DRM_DIR_NAME);
4008 while ((dent = readdir(sysdir))) {
4009 ret = process_device(&device, dent->d_name, -1, devices != NULL, flags);
4013 if (i >= MAX_DRM_NODES) {
4014 fprintf(stderr, "More than %d drm nodes detected. "
4015 "Please report a bug - that should not happen.\n"
4016 "Skipping extra nodes\n", MAX_DRM_NODES);
4019 local_devices[i] = device;
4024 drmFoldDuplicatedDevices(local_devices, node_count);
4027 for (i = 0; i < node_count; i++) {
4028 if (!local_devices[i])
4031 if ((devices != NULL) && (device_count < max_devices))
4032 devices[device_count] = local_devices[i];
4034 drmFreeDevice(&local_devices[i]);
4040 return device_count;
4044 * Get drm devices on the system
4046 * \param devices the array of devices with drmDevicePtr elements
4047 * can be NULL to get the device number first
4048 * \param max_devices the maximum number of devices for the array
4050 * \return on error - negative error code,
4051 * if devices is NULL - total number of devices available on the system,
4052 * alternatively the number of devices stored in devices[], which is
4053 * capped by the max_devices.
4055 drm_public int drmGetDevices(drmDevicePtr devices[], int max_devices)
4057 return drmGetDevices2(DRM_DEVICE_GET_PCI_REVISION, devices, max_devices);
4060 drm_public char *drmGetDeviceNameFromFd2(int fd)
4064 char path[PATH_MAX + 1], *value;
4065 unsigned int maj, min;
4067 if (fstat(fd, &sbuf))
4070 maj = major(sbuf.st_rdev);
4071 min = minor(sbuf.st_rdev);
4073 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
4076 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d", maj, min);
4078 value = sysfs_uevent_get(path, "DEVNAME");
4082 snprintf(path, sizeof(path), "/dev/%s", value);
4085 return strdup(path);
4088 char node[PATH_MAX + 1];
4089 const char *dev_name;
4091 int maj, min, n, base;
4093 if (fstat(fd, &sbuf))
4096 maj = major(sbuf.st_rdev);
4097 min = minor(sbuf.st_rdev);
4099 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
4102 node_type = drmGetMinorType(min);
4103 if (node_type == -1)
4106 switch (node_type) {
4107 case DRM_NODE_PRIMARY:
4108 dev_name = DRM_DEV_NAME;
4110 case DRM_NODE_CONTROL:
4111 dev_name = DRM_CONTROL_DEV_NAME;
4113 case DRM_NODE_RENDER:
4114 dev_name = DRM_RENDER_DEV_NAME;
4120 base = drmGetMinorBase(node_type);
4124 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min - base);
4125 if (n == -1 || n >= PATH_MAX)
4128 return strdup(node);
4132 drm_public int drmSyncobjCreate(int fd, uint32_t flags, uint32_t *handle)
4134 struct drm_syncobj_create args;
4140 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_CREATE, &args);
4143 *handle = args.handle;
4147 drm_public int drmSyncobjDestroy(int fd, uint32_t handle)
4149 struct drm_syncobj_destroy args;
4152 args.handle = handle;
4153 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_DESTROY, &args);
4156 drm_public int drmSyncobjHandleToFD(int fd, uint32_t handle, int *obj_fd)
4158 struct drm_syncobj_handle args;
4163 args.handle = handle;
4164 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4171 drm_public int drmSyncobjFDToHandle(int fd, int obj_fd, uint32_t *handle)
4173 struct drm_syncobj_handle args;
4179 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4182 *handle = args.handle;
4186 drm_public int drmSyncobjImportSyncFile(int fd, uint32_t handle,
4189 struct drm_syncobj_handle args;
4192 args.fd = sync_file_fd;
4193 args.handle = handle;
4194 args.flags = DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE;
4195 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4198 drm_public int drmSyncobjExportSyncFile(int fd, uint32_t handle,
4201 struct drm_syncobj_handle args;
4206 args.handle = handle;
4207 args.flags = DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE;
4208 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4211 *sync_file_fd = args.fd;
4215 drm_public int drmSyncobjWait(int fd, uint32_t *handles, unsigned num_handles,
4216 int64_t timeout_nsec, unsigned flags,
4217 uint32_t *first_signaled)
4219 struct drm_syncobj_wait args;
4223 args.handles = (uintptr_t)handles;
4224 args.timeout_nsec = timeout_nsec;
4225 args.count_handles = num_handles;
4228 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_WAIT, &args);
4233 *first_signaled = args.first_signaled;
4237 drm_public int drmSyncobjReset(int fd, const uint32_t *handles,
4238 uint32_t handle_count)
4240 struct drm_syncobj_array args;
4244 args.handles = (uintptr_t)handles;
4245 args.count_handles = handle_count;
4247 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_RESET, &args);
4251 drm_public int drmSyncobjSignal(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_SIGNAL, &args);