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 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 void *drmGetHashTable(void)
169 void *drmMalloc(int size)
171 return calloc(1, size);
174 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 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 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 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 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 int drmOpenControl(int minor)
774 return drmOpenMinor(minor, 0, DRM_NODE_CONTROL);
777 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 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 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 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 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 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 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 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 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 int drmGetMagic(int fd, drm_magic_t * magic)
1035 if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
1037 *magic = auth.magic;
1041 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 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 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 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 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 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 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 int drmMap(int fd, drm_handle_t handle, drmSize size, drmAddressPtr address)
1268 static unsigned long pagesize_mask = 0;
1274 pagesize_mask = getpagesize() - 1;
1276 size = (size + pagesize_mask) & ~pagesize_mask;
1278 *address = drm_mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1279 if (*address == MAP_FAILED)
1286 * Unmap mappings obtained with drmMap().
1288 * \param address address as given by drmMap().
1289 * \param size size in bytes. Must match the size used by drmMap().
1291 * \return zero on success, or a negative value on failure.
1294 * This function is a wrapper for munmap().
1296 int drmUnmap(drmAddress address, drmSize size)
1298 return drm_munmap(address, size);
1301 drmBufInfoPtr drmGetBufInfo(int fd)
1303 drm_buf_info_t info;
1304 drmBufInfoPtr retval;
1309 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1313 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1316 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1321 retval = drmMalloc(sizeof(*retval));
1322 retval->count = info.count;
1323 retval->list = drmMalloc(info.count * sizeof(*retval->list));
1324 for (i = 0; i < info.count; i++) {
1325 retval->list[i].count = info.list[i].count;
1326 retval->list[i].size = info.list[i].size;
1327 retval->list[i].low_mark = info.list[i].low_mark;
1328 retval->list[i].high_mark = info.list[i].high_mark;
1337 * Map all DMA buffers into client-virtual space.
1339 * \param fd file descriptor.
1341 * \return a pointer to a ::drmBufMap structure.
1343 * \note The client may not use these buffers until obtaining buffer indices
1347 * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1348 * information about the buffers in a drm_buf_map structure into the
1349 * client-visible data structures.
1351 drmBufMapPtr drmMapBufs(int fd)
1354 drmBufMapPtr retval;
1358 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1364 if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1367 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1372 retval = drmMalloc(sizeof(*retval));
1373 retval->count = bufs.count;
1374 retval->list = drmMalloc(bufs.count * sizeof(*retval->list));
1375 for (i = 0; i < bufs.count; i++) {
1376 retval->list[i].idx = bufs.list[i].idx;
1377 retval->list[i].total = bufs.list[i].total;
1378 retval->list[i].used = 0;
1379 retval->list[i].address = bufs.list[i].address;
1388 * Unmap buffers allocated with drmMapBufs().
1390 * \return zero on success, or negative value on failure.
1393 * Calls munmap() for every buffer stored in \p bufs and frees the
1394 * memory allocated by drmMapBufs().
1396 int drmUnmapBufs(drmBufMapPtr bufs)
1400 for (i = 0; i < bufs->count; i++) {
1401 drm_munmap(bufs->list[i].address, bufs->list[i].total);
1404 drmFree(bufs->list);
1410 #define DRM_DMA_RETRY 16
1413 * Reserve DMA buffers.
1415 * \param fd file descriptor.
1418 * \return zero on success, or a negative value on failure.
1421 * Assemble the arguments into a drm_dma structure and keeps issuing the
1422 * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1424 int drmDMA(int fd, drmDMAReqPtr request)
1429 dma.context = request->context;
1430 dma.send_count = request->send_count;
1431 dma.send_indices = request->send_list;
1432 dma.send_sizes = request->send_sizes;
1433 dma.flags = request->flags;
1434 dma.request_count = request->request_count;
1435 dma.request_size = request->request_size;
1436 dma.request_indices = request->request_list;
1437 dma.request_sizes = request->request_sizes;
1438 dma.granted_count = 0;
1441 ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1442 } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1445 request->granted_count = dma.granted_count;
1454 * Obtain heavyweight hardware lock.
1456 * \param fd file descriptor.
1457 * \param context context.
1458 * \param flags flags that determine the sate of the hardware when the function
1461 * \return always zero.
1464 * This function translates the arguments into a drm_lock structure and issue
1465 * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1467 int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
1472 lock.context = context;
1474 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
1475 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
1476 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
1477 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
1478 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
1479 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
1481 while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
1487 * Release the hardware lock.
1489 * \param fd file descriptor.
1490 * \param context context.
1492 * \return zero on success, or a negative value on failure.
1495 * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
1496 * argument in a drm_lock structure.
1498 int drmUnlock(int fd, drm_context_t context)
1503 lock.context = context;
1504 return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
1507 drm_context_t *drmGetReservedContextList(int fd, int *count)
1511 drm_context_t * retval;
1515 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1521 if (!(list = drmMalloc(res.count * sizeof(*list))))
1523 if (!(retval = drmMalloc(res.count * sizeof(*retval))))
1526 res.contexts = list;
1527 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1528 goto err_free_context;
1530 for (i = 0; i < res.count; i++)
1531 retval[i] = list[i].handle;
1544 void drmFreeReservedContextList(drm_context_t *pt)
1552 * Used by the X server during GLXContext initialization. This causes
1553 * per-context kernel-level resources to be allocated.
1555 * \param fd file descriptor.
1556 * \param handle is set on success. To be used by the client when requesting DMA
1557 * dispatch with drmDMA().
1559 * \return zero on success, or a negative value on failure.
1561 * \note May only be called by root.
1564 * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
1565 * argument in a drm_ctx structure.
1567 int drmCreateContext(int fd, drm_context_t *handle)
1572 if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
1574 *handle = ctx.handle;
1578 int drmSwitchToContext(int fd, drm_context_t context)
1583 ctx.handle = context;
1584 if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
1589 int drmSetContextFlags(int fd, drm_context_t context, drm_context_tFlags flags)
1594 * Context preserving means that no context switches are done between DMA
1595 * buffers from one context and the next. This is suitable for use in the
1596 * X server (which promises to maintain hardware context), or in the
1597 * client-side library when buffers are swapped on behalf of two threads.
1600 ctx.handle = context;
1601 if (flags & DRM_CONTEXT_PRESERVED)
1602 ctx.flags |= _DRM_CONTEXT_PRESERVED;
1603 if (flags & DRM_CONTEXT_2DONLY)
1604 ctx.flags |= _DRM_CONTEXT_2DONLY;
1605 if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
1610 int drmGetContextFlags(int fd, drm_context_t context,
1611 drm_context_tFlagsPtr flags)
1616 ctx.handle = context;
1617 if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
1620 if (ctx.flags & _DRM_CONTEXT_PRESERVED)
1621 *flags |= DRM_CONTEXT_PRESERVED;
1622 if (ctx.flags & _DRM_CONTEXT_2DONLY)
1623 *flags |= DRM_CONTEXT_2DONLY;
1630 * Free any kernel-level resources allocated with drmCreateContext() associated
1633 * \param fd file descriptor.
1634 * \param handle handle given by drmCreateContext().
1636 * \return zero on success, or a negative value on failure.
1638 * \note May only be called by root.
1641 * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
1642 * argument in a drm_ctx structure.
1644 int drmDestroyContext(int fd, drm_context_t handle)
1649 ctx.handle = handle;
1650 if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
1655 int drmCreateDrawable(int fd, drm_drawable_t *handle)
1660 if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
1662 *handle = draw.handle;
1666 int drmDestroyDrawable(int fd, drm_drawable_t handle)
1671 draw.handle = handle;
1672 if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
1677 int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
1678 drm_drawable_info_type_t type, unsigned int num,
1681 drm_update_draw_t update;
1684 update.handle = handle;
1687 update.data = (unsigned long long)(unsigned long)data;
1689 if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
1695 int drmCrtcGetSequence(int fd, uint32_t crtcId, uint64_t *sequence, uint64_t *ns)
1697 struct drm_crtc_get_sequence get_seq;
1701 get_seq.crtc_id = crtcId;
1702 ret = drmIoctl(fd, DRM_IOCTL_CRTC_GET_SEQUENCE, &get_seq);
1707 *sequence = get_seq.sequence;
1709 *ns = get_seq.sequence_ns;
1713 int drmCrtcQueueSequence(int fd, uint32_t crtcId, uint32_t flags, uint64_t sequence,
1714 uint64_t *sequence_queued, uint64_t user_data)
1716 struct drm_crtc_queue_sequence queue_seq;
1719 memclear(queue_seq);
1720 queue_seq.crtc_id = crtcId;
1721 queue_seq.flags = flags;
1722 queue_seq.sequence = sequence;
1723 queue_seq.user_data = user_data;
1725 ret = drmIoctl(fd, DRM_IOCTL_CRTC_QUEUE_SEQUENCE, &queue_seq);
1726 if (ret == 0 && sequence_queued)
1727 *sequence_queued = queue_seq.sequence;
1733 * Acquire the AGP device.
1735 * Must be called before any of the other AGP related calls.
1737 * \param fd file descriptor.
1739 * \return zero on success, or a negative value on failure.
1742 * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
1744 int drmAgpAcquire(int fd)
1746 if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
1753 * Release the AGP device.
1755 * \param fd file descriptor.
1757 * \return zero on success, or a negative value on failure.
1760 * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
1762 int drmAgpRelease(int fd)
1764 if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
1773 * \param fd file descriptor.
1774 * \param mode AGP mode.
1776 * \return zero on success, or a negative value on failure.
1779 * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
1780 * argument in a drm_agp_mode structure.
1782 int drmAgpEnable(int fd, unsigned long mode)
1788 if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
1795 * Allocate a chunk of AGP memory.
1797 * \param fd file descriptor.
1798 * \param size requested memory size in bytes. Will be rounded to page boundary.
1799 * \param type type of memory to allocate.
1800 * \param address if not zero, will be set to the physical address of the
1802 * \param handle on success will be set to a handle of the allocated memory.
1804 * \return zero on success, or a negative value on failure.
1807 * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
1808 * arguments in a drm_agp_buffer structure.
1810 int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
1811 unsigned long *address, drm_handle_t *handle)
1816 *handle = DRM_AGP_NO_HANDLE;
1819 if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
1822 *address = b.physical;
1829 * Free a chunk of AGP memory.
1831 * \param fd file descriptor.
1832 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1834 * \return zero on success, or a negative value on failure.
1837 * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
1838 * argument in a drm_agp_buffer structure.
1840 int drmAgpFree(int fd, drm_handle_t handle)
1846 if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
1853 * Bind a chunk of AGP memory.
1855 * \param fd file descriptor.
1856 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1857 * \param offset offset in bytes. It will round to page boundary.
1859 * \return zero on success, or a negative value on failure.
1862 * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
1863 * argument in a drm_agp_binding structure.
1865 int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
1867 drm_agp_binding_t b;
1872 if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
1879 * Unbind a chunk of AGP memory.
1881 * \param fd file descriptor.
1882 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1884 * \return zero on success, or a negative value on failure.
1887 * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
1888 * the argument in a drm_agp_binding structure.
1890 int drmAgpUnbind(int fd, drm_handle_t handle)
1892 drm_agp_binding_t b;
1896 if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
1903 * Get AGP driver major version number.
1905 * \param fd file descriptor.
1907 * \return major version number on success, or a negative value on failure..
1910 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1911 * necessary information in a drm_agp_info structure.
1913 int drmAgpVersionMajor(int fd)
1919 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1921 return i.agp_version_major;
1926 * Get AGP driver minor version number.
1928 * \param fd file descriptor.
1930 * \return minor version number on success, or a negative value on failure.
1933 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1934 * necessary information in a drm_agp_info structure.
1936 int drmAgpVersionMinor(int fd)
1942 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1944 return i.agp_version_minor;
1951 * \param fd file descriptor.
1953 * \return mode on success, or zero on failure.
1956 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1957 * necessary information in a drm_agp_info structure.
1959 unsigned long drmAgpGetMode(int fd)
1965 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1972 * Get AGP aperture base.
1974 * \param fd file descriptor.
1976 * \return aperture base on success, zero on failure.
1979 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1980 * necessary information in a drm_agp_info structure.
1982 unsigned long drmAgpBase(int fd)
1988 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1990 return i.aperture_base;
1995 * Get AGP aperture size.
1997 * \param fd file descriptor.
1999 * \return aperture size on success, zero on failure.
2002 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2003 * necessary information in a drm_agp_info structure.
2005 unsigned long drmAgpSize(int fd)
2011 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2013 return i.aperture_size;
2018 * Get used AGP memory.
2020 * \param fd file descriptor.
2022 * \return memory used on success, or zero on failure.
2025 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2026 * necessary information in a drm_agp_info structure.
2028 unsigned long drmAgpMemoryUsed(int fd)
2034 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2036 return i.memory_used;
2041 * Get available AGP memory.
2043 * \param fd file descriptor.
2045 * \return memory available on success, or zero on failure.
2048 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2049 * necessary information in a drm_agp_info structure.
2051 unsigned long drmAgpMemoryAvail(int fd)
2057 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2059 return i.memory_allowed;
2064 * Get hardware vendor ID.
2066 * \param fd file descriptor.
2068 * \return vendor ID on success, or zero on failure.
2071 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2072 * necessary information in a drm_agp_info structure.
2074 unsigned int drmAgpVendorId(int fd)
2080 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2087 * Get hardware device ID.
2089 * \param fd file descriptor.
2091 * \return zero on success, or zero on failure.
2094 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2095 * necessary information in a drm_agp_info structure.
2097 unsigned int drmAgpDeviceId(int fd)
2103 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2108 int drmScatterGatherAlloc(int fd, unsigned long size, drm_handle_t *handle)
2110 drm_scatter_gather_t sg;
2116 if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
2118 *handle = sg.handle;
2122 int drmScatterGatherFree(int fd, drm_handle_t handle)
2124 drm_scatter_gather_t sg;
2128 if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
2136 * \param fd file descriptor.
2137 * \param vbl pointer to a drmVBlank structure.
2139 * \return zero on success, or a negative value on failure.
2142 * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
2144 int drmWaitVBlank(int fd, drmVBlankPtr vbl)
2146 struct timespec timeout, cur;
2149 ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2151 fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
2157 ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
2158 vbl->request.type &= ~DRM_VBLANK_RELATIVE;
2159 if (ret && errno == EINTR) {
2160 clock_gettime(CLOCK_MONOTONIC, &cur);
2161 /* Timeout after 1s */
2162 if (cur.tv_sec > timeout.tv_sec + 1 ||
2163 (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
2170 } while (ret && errno == EINTR);
2176 int drmError(int err, const char *label)
2179 case DRM_ERR_NO_DEVICE:
2180 fprintf(stderr, "%s: no device\n", label);
2182 case DRM_ERR_NO_ACCESS:
2183 fprintf(stderr, "%s: no access\n", label);
2185 case DRM_ERR_NOT_ROOT:
2186 fprintf(stderr, "%s: not root\n", label);
2188 case DRM_ERR_INVALID:
2189 fprintf(stderr, "%s: invalid args\n", label);
2194 fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2202 * Install IRQ handler.
2204 * \param fd file descriptor.
2205 * \param irq IRQ number.
2207 * \return zero on success, or a negative value on failure.
2210 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2211 * argument in a drm_control structure.
2213 int drmCtlInstHandler(int fd, int irq)
2218 ctl.func = DRM_INST_HANDLER;
2220 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2227 * Uninstall IRQ handler.
2229 * \param fd file descriptor.
2231 * \return zero on success, or a negative value on failure.
2234 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2235 * argument in a drm_control structure.
2237 int drmCtlUninstHandler(int fd)
2242 ctl.func = DRM_UNINST_HANDLER;
2244 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2249 int drmFinish(int fd, int context, drmLockFlags flags)
2254 lock.context = context;
2255 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
2256 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
2257 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
2258 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
2259 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2260 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2261 if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2267 * Get IRQ from bus ID.
2269 * \param fd file descriptor.
2270 * \param busnum bus number.
2271 * \param devnum device number.
2272 * \param funcnum function number.
2274 * \return IRQ number on success, or a negative value on failure.
2277 * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2278 * arguments in a drm_irq_busid structure.
2280 int drmGetInterruptFromBusID(int fd, int busnum, int devnum, int funcnum)
2287 p.funcnum = funcnum;
2288 if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2293 int drmAddContextTag(int fd, drm_context_t context, void *tag)
2295 drmHashEntry *entry = drmGetEntry(fd);
2297 if (drmHashInsert(entry->tagTable, context, tag)) {
2298 drmHashDelete(entry->tagTable, context);
2299 drmHashInsert(entry->tagTable, context, tag);
2304 int drmDelContextTag(int fd, drm_context_t context)
2306 drmHashEntry *entry = drmGetEntry(fd);
2308 return drmHashDelete(entry->tagTable, context);
2311 void *drmGetContextTag(int fd, drm_context_t context)
2313 drmHashEntry *entry = drmGetEntry(fd);
2316 if (drmHashLookup(entry->tagTable, context, &value))
2322 int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2323 drm_handle_t handle)
2325 drm_ctx_priv_map_t map;
2328 map.ctx_id = ctx_id;
2329 map.handle = (void *)(uintptr_t)handle;
2331 if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2336 int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2337 drm_handle_t *handle)
2339 drm_ctx_priv_map_t map;
2342 map.ctx_id = ctx_id;
2344 if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2347 *handle = (drm_handle_t)(uintptr_t)map.handle;
2352 int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2353 drmMapType *type, drmMapFlags *flags, drm_handle_t *handle,
2360 if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2362 *offset = map.offset;
2366 *handle = (unsigned long)map.handle;
2371 int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2372 unsigned long *magic, unsigned long *iocs)
2374 drm_client_t client;
2378 if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2380 *auth = client.auth;
2383 *magic = client.magic;
2384 *iocs = client.iocs;
2388 int drmGetStats(int fd, drmStatsT *stats)
2394 if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2398 memset(stats, 0, sizeof(*stats));
2399 if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2403 stats->data[i].long_format = "%-20.20s"; \
2404 stats->data[i].rate_format = "%8.8s"; \
2405 stats->data[i].isvalue = 1; \
2406 stats->data[i].verbose = 0
2409 stats->data[i].long_format = "%-20.20s"; \
2410 stats->data[i].rate_format = "%5.5s"; \
2411 stats->data[i].isvalue = 0; \
2412 stats->data[i].mult_names = "kgm"; \
2413 stats->data[i].mult = 1000; \
2414 stats->data[i].verbose = 0
2417 stats->data[i].long_format = "%-20.20s"; \
2418 stats->data[i].rate_format = "%5.5s"; \
2419 stats->data[i].isvalue = 0; \
2420 stats->data[i].mult_names = "KGM"; \
2421 stats->data[i].mult = 1024; \
2422 stats->data[i].verbose = 0
2425 stats->count = s.count;
2426 for (i = 0; i < s.count; i++) {
2427 stats->data[i].value = s.data[i].value;
2428 switch (s.data[i].type) {
2429 case _DRM_STAT_LOCK:
2430 stats->data[i].long_name = "Lock";
2431 stats->data[i].rate_name = "Lock";
2434 case _DRM_STAT_OPENS:
2435 stats->data[i].long_name = "Opens";
2436 stats->data[i].rate_name = "O";
2438 stats->data[i].verbose = 1;
2440 case _DRM_STAT_CLOSES:
2441 stats->data[i].long_name = "Closes";
2442 stats->data[i].rate_name = "Lock";
2444 stats->data[i].verbose = 1;
2446 case _DRM_STAT_IOCTLS:
2447 stats->data[i].long_name = "Ioctls";
2448 stats->data[i].rate_name = "Ioc/s";
2451 case _DRM_STAT_LOCKS:
2452 stats->data[i].long_name = "Locks";
2453 stats->data[i].rate_name = "Lck/s";
2456 case _DRM_STAT_UNLOCKS:
2457 stats->data[i].long_name = "Unlocks";
2458 stats->data[i].rate_name = "Unl/s";
2462 stats->data[i].long_name = "IRQs";
2463 stats->data[i].rate_name = "IRQ/s";
2466 case _DRM_STAT_PRIMARY:
2467 stats->data[i].long_name = "Primary Bytes";
2468 stats->data[i].rate_name = "PB/s";
2471 case _DRM_STAT_SECONDARY:
2472 stats->data[i].long_name = "Secondary Bytes";
2473 stats->data[i].rate_name = "SB/s";
2477 stats->data[i].long_name = "DMA";
2478 stats->data[i].rate_name = "DMA/s";
2481 case _DRM_STAT_SPECIAL:
2482 stats->data[i].long_name = "Special DMA";
2483 stats->data[i].rate_name = "dma/s";
2486 case _DRM_STAT_MISSED:
2487 stats->data[i].long_name = "Miss";
2488 stats->data[i].rate_name = "Ms/s";
2491 case _DRM_STAT_VALUE:
2492 stats->data[i].long_name = "Value";
2493 stats->data[i].rate_name = "Value";
2496 case _DRM_STAT_BYTE:
2497 stats->data[i].long_name = "Bytes";
2498 stats->data[i].rate_name = "B/s";
2501 case _DRM_STAT_COUNT:
2503 stats->data[i].long_name = "Count";
2504 stats->data[i].rate_name = "Cnt/s";
2513 * Issue a set-version ioctl.
2515 * \param fd file descriptor.
2516 * \param drmCommandIndex command index
2517 * \param data source pointer of the data to be read and written.
2518 * \param size size of the data to be read and written.
2520 * \return zero on success, or a negative value on failure.
2523 * It issues a read-write ioctl given by
2524 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2526 int drmSetInterfaceVersion(int fd, drmSetVersion *version)
2529 drm_set_version_t sv;
2532 sv.drm_di_major = version->drm_di_major;
2533 sv.drm_di_minor = version->drm_di_minor;
2534 sv.drm_dd_major = version->drm_dd_major;
2535 sv.drm_dd_minor = version->drm_dd_minor;
2537 if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
2541 version->drm_di_major = sv.drm_di_major;
2542 version->drm_di_minor = sv.drm_di_minor;
2543 version->drm_dd_major = sv.drm_dd_major;
2544 version->drm_dd_minor = sv.drm_dd_minor;
2550 * Send a device-specific command.
2552 * \param fd file descriptor.
2553 * \param drmCommandIndex command index
2555 * \return zero on success, or a negative value on failure.
2558 * It issues a ioctl given by
2559 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2561 int drmCommandNone(int fd, unsigned long drmCommandIndex)
2563 unsigned long request;
2565 request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
2567 if (drmIoctl(fd, request, NULL)) {
2575 * Send a device-specific read command.
2577 * \param fd file descriptor.
2578 * \param drmCommandIndex command index
2579 * \param data destination pointer of the data to be read.
2580 * \param size size of the data to be read.
2582 * \return zero on success, or a negative value on failure.
2585 * It issues a read ioctl given by
2586 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2588 int drmCommandRead(int fd, unsigned long drmCommandIndex, void *data,
2591 unsigned long request;
2593 request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
2594 DRM_COMMAND_BASE + drmCommandIndex, size);
2596 if (drmIoctl(fd, request, data)) {
2604 * Send a device-specific write command.
2606 * \param fd file descriptor.
2607 * \param drmCommandIndex command index
2608 * \param data source pointer of the data to be written.
2609 * \param size size of the data to be written.
2611 * \return zero on success, or a negative value on failure.
2614 * It issues a write ioctl given by
2615 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2617 int drmCommandWrite(int fd, unsigned long drmCommandIndex, void *data,
2620 unsigned long request;
2622 request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
2623 DRM_COMMAND_BASE + drmCommandIndex, size);
2625 if (drmIoctl(fd, request, data)) {
2633 * Send a device-specific read-write command.
2635 * \param fd file descriptor.
2636 * \param drmCommandIndex command index
2637 * \param data source pointer of the data to be read and written.
2638 * \param size size of the data to be read and written.
2640 * \return zero on success, or a negative value on failure.
2643 * It issues a read-write ioctl given by
2644 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2646 int drmCommandWriteRead(int fd, unsigned long drmCommandIndex, void *data,
2649 unsigned long request;
2651 request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
2652 DRM_COMMAND_BASE + drmCommandIndex, size);
2654 if (drmIoctl(fd, request, data))
2659 #define DRM_MAX_FDS 16
2665 } connection[DRM_MAX_FDS];
2667 static int nr_fds = 0;
2669 int drmOpenOnce(void *unused,
2673 return drmOpenOnceWithType(BusID, newlyopened, DRM_NODE_PRIMARY);
2676 int drmOpenOnceWithType(const char *BusID, int *newlyopened, int type)
2681 for (i = 0; i < nr_fds; i++)
2682 if ((strcmp(BusID, connection[i].BusID) == 0) &&
2683 (connection[i].type == type)) {
2684 connection[i].refcount++;
2686 return connection[i].fd;
2689 fd = drmOpenWithType(NULL, BusID, type);
2690 if (fd < 0 || nr_fds == DRM_MAX_FDS)
2693 connection[nr_fds].BusID = strdup(BusID);
2694 connection[nr_fds].fd = fd;
2695 connection[nr_fds].refcount = 1;
2696 connection[nr_fds].type = type;
2700 fprintf(stderr, "saved connection %d for %s %d\n",
2701 nr_fds, connection[nr_fds].BusID,
2702 strcmp(BusID, connection[nr_fds].BusID));
2709 void drmCloseOnce(int fd)
2713 for (i = 0; i < nr_fds; i++) {
2714 if (fd == connection[i].fd) {
2715 if (--connection[i].refcount == 0) {
2716 drmClose(connection[i].fd);
2717 free(connection[i].BusID);
2720 connection[i] = connection[nr_fds];
2728 int drmSetMaster(int fd)
2730 return drmIoctl(fd, DRM_IOCTL_SET_MASTER, NULL);
2733 int drmDropMaster(int fd)
2735 return drmIoctl(fd, DRM_IOCTL_DROP_MASTER, NULL);
2738 char *drmGetDeviceNameFromFd(int fd)
2745 /* The whole drmOpen thing is a fiasco and we need to find a way
2746 * back to just using open(2). For now, however, lets just make
2747 * things worse with even more ad hoc directory walking code to
2748 * discover the device file name. */
2753 for (i = 0; i < DRM_MAX_MINOR; i++) {
2754 snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
2755 if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
2758 if (i == DRM_MAX_MINOR)
2761 return strdup(name);
2764 int drmGetNodeTypeFromFd(int fd)
2769 if (fstat(fd, &sbuf))
2772 maj = major(sbuf.st_rdev);
2773 min = minor(sbuf.st_rdev);
2775 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode)) {
2780 type = drmGetMinorType(min);
2786 int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags, int *prime_fd)
2788 struct drm_prime_handle args;
2793 args.handle = handle;
2795 ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
2799 *prime_fd = args.fd;
2803 int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
2805 struct drm_prime_handle args;
2810 ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
2814 *handle = args.handle;
2818 static char *drmGetMinorNameForFD(int fd, int type)
2824 const char *name = drmGetMinorName(type);
2826 char dev_name[64], buf[64];
2834 if (fstat(fd, &sbuf))
2837 maj = major(sbuf.st_rdev);
2838 min = minor(sbuf.st_rdev);
2840 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
2843 snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
2845 sysdir = opendir(buf);
2849 while ((ent = readdir(sysdir))) {
2850 if (strncmp(ent->d_name, name, len) == 0) {
2851 snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
2855 return strdup(dev_name);
2863 char buf[PATH_MAX + 1];
2864 const char *dev_name;
2865 unsigned int maj, min;
2868 if (fstat(fd, &sbuf))
2871 maj = major(sbuf.st_rdev);
2872 min = minor(sbuf.st_rdev);
2874 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
2878 case DRM_NODE_PRIMARY:
2879 dev_name = DRM_DEV_NAME;
2881 case DRM_NODE_CONTROL:
2882 dev_name = DRM_CONTROL_DEV_NAME;
2884 case DRM_NODE_RENDER:
2885 dev_name = DRM_RENDER_DEV_NAME;
2891 base = drmGetMinorBase(type);
2895 n = snprintf(buf, sizeof(buf), dev_name, DRM_DIR_NAME, min - base);
2896 if (n == -1 || n >= sizeof(buf))
2903 char *drmGetPrimaryDeviceNameFromFd(int fd)
2905 return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
2908 char *drmGetRenderDeviceNameFromFd(int fd)
2910 return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
2914 static char * DRM_PRINTFLIKE(2, 3)
2915 sysfs_uevent_get(const char *path, const char *fmt, ...)
2917 char filename[PATH_MAX + 1], *key, *line = NULL, *value = NULL;
2918 size_t size = 0, len;
2924 num = vasprintf(&key, fmt, ap);
2928 snprintf(filename, sizeof(filename), "%s/uevent", path);
2930 fp = fopen(filename, "r");
2936 while ((num = getline(&line, &size, fp)) >= 0) {
2937 if ((strncmp(line, key, len) == 0) && (line[len] == '=')) {
2938 char *start = line + len + 1, *end = line + num - 1;
2943 value = strndup(start, end - start);
2957 static int drmParseSubsystemType(int maj, int min)
2960 char path[PATH_MAX + 1];
2961 char link[PATH_MAX + 1] = "";
2964 snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/subsystem",
2967 if (readlink(path, link, PATH_MAX) < 0)
2970 name = strrchr(link, '/');
2974 if (strncmp(name, "/pci", 4) == 0)
2977 if (strncmp(name, "/usb", 4) == 0)
2980 if (strncmp(name, "/platform", 9) == 0)
2981 return DRM_BUS_PLATFORM;
2983 if (strncmp(name, "/host1x", 7) == 0)
2984 return DRM_BUS_HOST1X;
2987 #elif defined(__OpenBSD__)
2990 #warning "Missing implementation of drmParseSubsystemType"
2995 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
2998 unsigned int domain, bus, dev, func;
2999 char path[PATH_MAX + 1], *value;
3002 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3004 value = sysfs_uevent_get(path, "PCI_SLOT_NAME");
3008 num = sscanf(value, "%04x:%02x:%02x.%1u", &domain, &bus, &dev, &func);
3014 info->domain = domain;
3020 #elif defined(__OpenBSD__)
3021 struct drm_pciinfo pinfo;
3024 type = drmGetMinorType(min);
3028 fd = drmOpenMinor(min, 0, type);
3032 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3038 info->domain = pinfo.domain;
3039 info->bus = pinfo.bus;
3040 info->dev = pinfo.dev;
3041 info->func = pinfo.func;
3045 #warning "Missing implementation of drmParsePciBusInfo"
3050 int drmDevicesEqual(drmDevicePtr a, drmDevicePtr b)
3052 if (a == NULL || b == NULL)
3055 if (a->bustype != b->bustype)
3058 switch (a->bustype) {
3060 return memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo)) == 0;
3063 return memcmp(a->businfo.usb, b->businfo.usb, sizeof(drmUsbBusInfo)) == 0;
3065 case DRM_BUS_PLATFORM:
3066 return memcmp(a->businfo.platform, b->businfo.platform, sizeof(drmPlatformBusInfo)) == 0;
3068 case DRM_BUS_HOST1X:
3069 return memcmp(a->businfo.host1x, b->businfo.host1x, sizeof(drmHost1xBusInfo)) == 0;
3078 static int drmGetNodeType(const char *name)
3080 if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
3081 sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
3082 return DRM_NODE_PRIMARY;
3084 if (strncmp(name, DRM_CONTROL_MINOR_NAME,
3085 sizeof(DRM_CONTROL_MINOR_NAME ) - 1) == 0)
3086 return DRM_NODE_CONTROL;
3088 if (strncmp(name, DRM_RENDER_MINOR_NAME,
3089 sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
3090 return DRM_NODE_RENDER;
3095 static int drmGetMaxNodeName(void)
3097 return sizeof(DRM_DIR_NAME) +
3098 MAX3(sizeof(DRM_PRIMARY_MINOR_NAME),
3099 sizeof(DRM_CONTROL_MINOR_NAME),
3100 sizeof(DRM_RENDER_MINOR_NAME)) +
3101 3 /* length of the node number */;
3105 static int parse_separate_sysfs_files(int maj, int min,
3106 drmPciDeviceInfoPtr device,
3107 bool ignore_revision)
3109 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3110 static const char *attrs[] = {
3111 "revision", /* Older kernels are missing the file, so check for it first */
3117 char path[PATH_MAX + 1];
3118 unsigned int data[ARRAY_SIZE(attrs)];
3122 for (unsigned i = ignore_revision ? 1 : 0; i < ARRAY_SIZE(attrs); i++) {
3123 snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/%s", maj, min,
3125 fp = fopen(path, "r");
3129 ret = fscanf(fp, "%x", &data[i]);
3136 device->revision_id = ignore_revision ? 0xff : data[0] & 0xff;
3137 device->vendor_id = data[1] & 0xffff;
3138 device->device_id = data[2] & 0xffff;
3139 device->subvendor_id = data[3] & 0xffff;
3140 device->subdevice_id = data[4] & 0xffff;
3145 static int parse_config_sysfs_file(int maj, int min,
3146 drmPciDeviceInfoPtr device)
3148 char path[PATH_MAX + 1];
3149 unsigned char config[64];
3152 snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/config", maj, min);
3153 fd = open(path, O_RDONLY);
3157 ret = read(fd, config, sizeof(config));
3162 device->vendor_id = config[0] | (config[1] << 8);
3163 device->device_id = config[2] | (config[3] << 8);
3164 device->revision_id = config[8];
3165 device->subvendor_id = config[44] | (config[45] << 8);
3166 device->subdevice_id = config[46] | (config[47] << 8);
3172 static int drmParsePciDeviceInfo(int maj, int min,
3173 drmPciDeviceInfoPtr device,
3177 if (!(flags & DRM_DEVICE_GET_PCI_REVISION))
3178 return parse_separate_sysfs_files(maj, min, device, true);
3180 if (parse_separate_sysfs_files(maj, min, device, false))
3181 return parse_config_sysfs_file(maj, min, device);
3184 #elif defined(__OpenBSD__)
3185 struct drm_pciinfo pinfo;
3188 type = drmGetMinorType(min);
3192 fd = drmOpenMinor(min, 0, type);
3196 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3202 device->vendor_id = pinfo.vendor_id;
3203 device->device_id = pinfo.device_id;
3204 device->revision_id = pinfo.revision_id;
3205 device->subvendor_id = pinfo.subvendor_id;
3206 device->subdevice_id = pinfo.subdevice_id;
3210 #warning "Missing implementation of drmParsePciDeviceInfo"
3215 static void drmFreePlatformDevice(drmDevicePtr device)
3217 if (device->deviceinfo.platform) {
3218 if (device->deviceinfo.platform->compatible) {
3219 char **compatible = device->deviceinfo.platform->compatible;
3221 while (*compatible) {
3226 free(device->deviceinfo.platform->compatible);
3231 static void drmFreeHost1xDevice(drmDevicePtr device)
3233 if (device->deviceinfo.host1x) {
3234 if (device->deviceinfo.host1x->compatible) {
3235 char **compatible = device->deviceinfo.host1x->compatible;
3237 while (*compatible) {
3242 free(device->deviceinfo.host1x->compatible);
3247 void drmFreeDevice(drmDevicePtr *device)
3253 switch ((*device)->bustype) {
3254 case DRM_BUS_PLATFORM:
3255 drmFreePlatformDevice(*device);
3258 case DRM_BUS_HOST1X:
3259 drmFreeHost1xDevice(*device);
3268 void drmFreeDevices(drmDevicePtr devices[], int count)
3272 if (devices == NULL)
3275 for (i = 0; i < count; i++)
3277 drmFreeDevice(&devices[i]);
3280 static drmDevicePtr drmDeviceAlloc(unsigned int type, const char *node,
3281 size_t bus_size, size_t device_size,
3284 size_t max_node_length, extra, size;
3285 drmDevicePtr device;
3289 max_node_length = ALIGN(drmGetMaxNodeName(), sizeof(void *));
3290 extra = DRM_NODE_MAX * (sizeof(void *) + max_node_length);
3292 size = sizeof(*device) + extra + bus_size + device_size;
3294 device = calloc(1, size);
3298 device->available_nodes = 1 << type;
3300 ptr = (char *)device + sizeof(*device);
3301 device->nodes = (char **)ptr;
3303 ptr += DRM_NODE_MAX * sizeof(void *);
3305 for (i = 0; i < DRM_NODE_MAX; i++) {
3306 device->nodes[i] = ptr;
3307 ptr += max_node_length;
3310 memcpy(device->nodes[type], node, max_node_length);
3317 static int drmProcessPciDevice(drmDevicePtr *device,
3318 const char *node, int node_type,
3319 int maj, int min, bool fetch_deviceinfo,
3326 dev = drmDeviceAlloc(node_type, node, sizeof(drmPciBusInfo),
3327 sizeof(drmPciDeviceInfo), &addr);
3331 dev->bustype = DRM_BUS_PCI;
3333 dev->businfo.pci = (drmPciBusInfoPtr)addr;
3335 ret = drmParsePciBusInfo(maj, min, dev->businfo.pci);
3339 // Fetch the device info if the user has requested it
3340 if (fetch_deviceinfo) {
3341 addr += sizeof(drmPciBusInfo);
3342 dev->deviceinfo.pci = (drmPciDeviceInfoPtr)addr;
3344 ret = drmParsePciDeviceInfo(maj, min, dev->deviceinfo.pci, flags);
3358 static int drmParseUsbBusInfo(int maj, int min, drmUsbBusInfoPtr info)
3361 char path[PATH_MAX + 1], *value;
3362 unsigned int bus, dev;
3365 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3367 value = sysfs_uevent_get(path, "BUSNUM");
3371 ret = sscanf(value, "%03u", &bus);
3377 value = sysfs_uevent_get(path, "DEVNUM");
3381 ret = sscanf(value, "%03u", &dev);
3392 #warning "Missing implementation of drmParseUsbBusInfo"
3397 static int drmParseUsbDeviceInfo(int maj, int min, drmUsbDeviceInfoPtr info)
3400 char path[PATH_MAX + 1], *value;
3401 unsigned int vendor, product;
3404 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3406 value = sysfs_uevent_get(path, "PRODUCT");
3410 ret = sscanf(value, "%x/%x", &vendor, &product);
3416 info->vendor = vendor;
3417 info->product = product;
3421 #warning "Missing implementation of drmParseUsbDeviceInfo"
3426 static int drmProcessUsbDevice(drmDevicePtr *device, const char *node,
3427 int node_type, int maj, int min,
3428 bool fetch_deviceinfo, uint32_t flags)
3434 dev = drmDeviceAlloc(node_type, node, sizeof(drmUsbBusInfo),
3435 sizeof(drmUsbDeviceInfo), &ptr);
3439 dev->bustype = DRM_BUS_USB;
3441 dev->businfo.usb = (drmUsbBusInfoPtr)ptr;
3443 ret = drmParseUsbBusInfo(maj, min, dev->businfo.usb);
3447 if (fetch_deviceinfo) {
3448 ptr += sizeof(drmUsbBusInfo);
3449 dev->deviceinfo.usb = (drmUsbDeviceInfoPtr)ptr;
3451 ret = drmParseUsbDeviceInfo(maj, min, dev->deviceinfo.usb);
3465 static int drmParsePlatformBusInfo(int maj, int min, drmPlatformBusInfoPtr info)
3468 char path[PATH_MAX + 1], *name;
3470 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3472 name = sysfs_uevent_get(path, "OF_FULLNAME");
3476 strncpy(info->fullname, name, DRM_PLATFORM_DEVICE_NAME_LEN);
3477 info->fullname[DRM_PLATFORM_DEVICE_NAME_LEN - 1] = '\0';
3482 #warning "Missing implementation of drmParsePlatformBusInfo"
3487 static int drmParsePlatformDeviceInfo(int maj, int min,
3488 drmPlatformDeviceInfoPtr info)
3491 char path[PATH_MAX + 1], *value;
3492 unsigned int count, i;
3495 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3497 value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
3501 sscanf(value, "%u", &count);
3504 info->compatible = calloc(count + 1, sizeof(*info->compatible));
3505 if (!info->compatible)
3508 for (i = 0; i < count; i++) {
3509 value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
3515 info->compatible[i] = value;
3522 free(info->compatible[i]);
3524 free(info->compatible);
3527 #warning "Missing implementation of drmParsePlatformDeviceInfo"
3532 static int drmProcessPlatformDevice(drmDevicePtr *device,
3533 const char *node, int node_type,
3534 int maj, int min, bool fetch_deviceinfo,
3541 dev = drmDeviceAlloc(node_type, node, sizeof(drmPlatformBusInfo),
3542 sizeof(drmPlatformDeviceInfo), &ptr);
3546 dev->bustype = DRM_BUS_PLATFORM;
3548 dev->businfo.platform = (drmPlatformBusInfoPtr)ptr;
3550 ret = drmParsePlatformBusInfo(maj, min, dev->businfo.platform);
3554 if (fetch_deviceinfo) {
3555 ptr += sizeof(drmPlatformBusInfo);
3556 dev->deviceinfo.platform = (drmPlatformDeviceInfoPtr)ptr;
3558 ret = drmParsePlatformDeviceInfo(maj, min, dev->deviceinfo.platform);
3572 static int drmParseHost1xBusInfo(int maj, int min, drmHost1xBusInfoPtr info)
3575 char path[PATH_MAX + 1], *name;
3577 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3579 name = sysfs_uevent_get(path, "OF_FULLNAME");
3583 strncpy(info->fullname, name, DRM_HOST1X_DEVICE_NAME_LEN);
3584 info->fullname[DRM_HOST1X_DEVICE_NAME_LEN - 1] = '\0';
3589 #warning "Missing implementation of drmParseHost1xBusInfo"
3594 static int drmParseHost1xDeviceInfo(int maj, int min,
3595 drmHost1xDeviceInfoPtr info)
3598 char path[PATH_MAX + 1], *value;
3599 unsigned int count, i;
3602 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3604 value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
3608 sscanf(value, "%u", &count);
3611 info->compatible = calloc(count + 1, sizeof(*info->compatible));
3612 if (!info->compatible)
3615 for (i = 0; i < count; i++) {
3616 value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
3622 info->compatible[i] = value;
3629 free(info->compatible[i]);
3631 free(info->compatible);
3634 #warning "Missing implementation of drmParseHost1xDeviceInfo"
3639 static int drmProcessHost1xDevice(drmDevicePtr *device,
3640 const char *node, int node_type,
3641 int maj, int min, bool fetch_deviceinfo,
3648 dev = drmDeviceAlloc(node_type, node, sizeof(drmHost1xBusInfo),
3649 sizeof(drmHost1xDeviceInfo), &ptr);
3653 dev->bustype = DRM_BUS_HOST1X;
3655 dev->businfo.host1x = (drmHost1xBusInfoPtr)ptr;
3657 ret = drmParseHost1xBusInfo(maj, min, dev->businfo.host1x);
3661 if (fetch_deviceinfo) {
3662 ptr += sizeof(drmHost1xBusInfo);
3663 dev->deviceinfo.host1x = (drmHost1xDeviceInfoPtr)ptr;
3665 ret = drmParseHost1xDeviceInfo(maj, min, dev->deviceinfo.host1x);
3679 /* Consider devices located on the same bus as duplicate and fold the respective
3680 * entries into a single one.
3682 * Note: this leaves "gaps" in the array, while preserving the length.
3684 static void drmFoldDuplicatedDevices(drmDevicePtr local_devices[], int count)
3686 int node_type, i, j;
3688 for (i = 0; i < count; i++) {
3689 for (j = i + 1; j < count; j++) {
3690 if (drmDevicesEqual(local_devices[i], local_devices[j])) {
3691 local_devices[i]->available_nodes |= local_devices[j]->available_nodes;
3692 node_type = log2(local_devices[j]->available_nodes);
3693 memcpy(local_devices[i]->nodes[node_type],
3694 local_devices[j]->nodes[node_type], drmGetMaxNodeName());
3695 drmFreeDevice(&local_devices[j]);
3701 /* Check that the given flags are valid returning 0 on success */
3703 drm_device_validate_flags(uint32_t flags)
3705 return (flags & ~DRM_DEVICE_GET_PCI_REVISION);
3709 * Get information about the opened drm device
3711 * \param fd file descriptor of the drm device
3712 * \param flags feature/behaviour bitmask
3713 * \param device the address of a drmDevicePtr where the information
3714 * will be allocated in stored
3716 * \return zero on success, negative error code otherwise.
3718 * \note Unlike drmGetDevice it does not retrieve the pci device revision field
3719 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
3721 int drmGetDevice2(int fd, uint32_t flags, drmDevicePtr *device)
3725 * DRI device nodes on OpenBSD are not in their own directory, they reside
3726 * in /dev along with a large number of statically generated /dev nodes.
3727 * Avoid stat'ing all of /dev needlessly by implementing this custom path.
3731 char node[PATH_MAX + 1];
3732 const char *dev_name;
3733 int node_type, subsystem_type;
3734 int maj, min, n, ret, base;
3736 if (fd == -1 || device == NULL)
3739 if (fstat(fd, &sbuf))
3742 maj = major(sbuf.st_rdev);
3743 min = minor(sbuf.st_rdev);
3745 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3748 node_type = drmGetMinorType(min);
3749 if (node_type == -1)
3752 switch (node_type) {
3753 case DRM_NODE_PRIMARY:
3754 dev_name = DRM_DEV_NAME;
3756 case DRM_NODE_CONTROL:
3757 dev_name = DRM_CONTROL_DEV_NAME;
3759 case DRM_NODE_RENDER:
3760 dev_name = DRM_RENDER_DEV_NAME;
3766 base = drmGetMinorBase(node_type);
3770 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min - base);
3771 if (n == -1 || n >= PATH_MAX)
3773 if (stat(node, &sbuf))
3776 subsystem_type = drmParseSubsystemType(maj, min);
3777 if (subsystem_type != DRM_BUS_PCI)
3780 ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
3788 drmDevicePtr *local_devices;
3791 struct dirent *dent;
3793 char node[PATH_MAX + 1];
3794 int node_type, subsystem_type;
3796 int ret, i, node_count;
3800 if (drm_device_validate_flags(flags))
3803 if (fd == -1 || device == NULL)
3806 if (fstat(fd, &sbuf))
3809 find_rdev = sbuf.st_rdev;
3810 maj = major(sbuf.st_rdev);
3811 min = minor(sbuf.st_rdev);
3813 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3816 subsystem_type = drmParseSubsystemType(maj, min);
3818 local_devices = calloc(max_count, sizeof(drmDevicePtr));
3819 if (local_devices == NULL)
3822 sysdir = opendir(DRM_DIR_NAME);
3829 while ((dent = readdir(sysdir))) {
3830 node_type = drmGetNodeType(dent->d_name);
3834 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, dent->d_name);
3835 if (stat(node, &sbuf))
3838 maj = major(sbuf.st_rdev);
3839 min = minor(sbuf.st_rdev);
3841 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3844 if (drmParseSubsystemType(maj, min) != subsystem_type)
3847 switch (subsystem_type) {
3849 ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
3856 ret = drmProcessUsbDevice(&d, node, node_type, maj, min, true, flags);
3862 case DRM_BUS_PLATFORM:
3863 ret = drmProcessPlatformDevice(&d, node, node_type, maj, min, true, flags);
3869 case DRM_BUS_HOST1X:
3870 ret = drmProcessHost1xDevice(&d, node, node_type, maj, min, true, flags);
3880 if (i >= max_count) {
3884 temp = realloc(local_devices, max_count * sizeof(drmDevicePtr));
3887 local_devices = temp;
3890 /* store target at local_devices[0] for ease to use below */
3891 if (find_rdev == sbuf.st_rdev && i) {
3892 local_devices[i] = local_devices[0];
3893 local_devices[0] = d;
3896 local_devices[i] = d;
3901 drmFoldDuplicatedDevices(local_devices, node_count);
3903 *device = local_devices[0];
3904 drmFreeDevices(&local_devices[1], node_count - 1);
3907 free(local_devices);
3908 if (*device == NULL)
3913 drmFreeDevices(local_devices, i);
3917 free(local_devices);
3923 * Get information about the opened drm device
3925 * \param fd file descriptor of the drm device
3926 * \param device the address of a drmDevicePtr where the information
3927 * will be allocated in stored
3929 * \return zero on success, negative error code otherwise.
3931 int drmGetDevice(int fd, drmDevicePtr *device)
3933 return drmGetDevice2(fd, DRM_DEVICE_GET_PCI_REVISION, device);
3937 * Get drm devices on the system
3939 * \param flags feature/behaviour bitmask
3940 * \param devices the array of devices with drmDevicePtr elements
3941 * can be NULL to get the device number first
3942 * \param max_devices the maximum number of devices for the array
3944 * \return on error - negative error code,
3945 * if devices is NULL - total number of devices available on the system,
3946 * alternatively the number of devices stored in devices[], which is
3947 * capped by the max_devices.
3949 * \note Unlike drmGetDevices it does not retrieve the pci device revision field
3950 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
3952 int drmGetDevices2(uint32_t flags, drmDevicePtr devices[], int max_devices)
3954 drmDevicePtr *local_devices;
3955 drmDevicePtr device;
3957 struct dirent *dent;
3959 char node[PATH_MAX + 1];
3960 int node_type, subsystem_type;
3962 int ret, i, node_count, device_count;
3965 if (drm_device_validate_flags(flags))
3968 local_devices = calloc(max_count, sizeof(drmDevicePtr));
3969 if (local_devices == NULL)
3972 sysdir = opendir(DRM_DIR_NAME);
3979 while ((dent = readdir(sysdir))) {
3980 node_type = drmGetNodeType(dent->d_name);
3984 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, dent->d_name);
3985 if (stat(node, &sbuf))
3988 maj = major(sbuf.st_rdev);
3989 min = minor(sbuf.st_rdev);
3991 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3994 subsystem_type = drmParseSubsystemType(maj, min);
3996 if (subsystem_type < 0)
3999 switch (subsystem_type) {
4001 ret = drmProcessPciDevice(&device, node, node_type,
4002 maj, min, devices != NULL, flags);
4009 ret = drmProcessUsbDevice(&device, node, node_type, maj, min,
4010 devices != NULL, flags);
4016 case DRM_BUS_PLATFORM:
4017 ret = drmProcessPlatformDevice(&device, node, node_type, maj, min,
4018 devices != NULL, flags);
4024 case DRM_BUS_HOST1X:
4025 ret = drmProcessHost1xDevice(&device, node, node_type, maj, min,
4026 devices != NULL, flags);
4036 if (i >= max_count) {
4040 temp = realloc(local_devices, max_count * sizeof(drmDevicePtr));
4043 local_devices = temp;
4046 local_devices[i] = device;
4051 drmFoldDuplicatedDevices(local_devices, node_count);
4054 for (i = 0; i < node_count; i++) {
4055 if (!local_devices[i])
4058 if ((devices != NULL) && (device_count < max_devices))
4059 devices[device_count] = local_devices[i];
4061 drmFreeDevice(&local_devices[i]);
4067 free(local_devices);
4068 return device_count;
4071 drmFreeDevices(local_devices, i);
4075 free(local_devices);
4080 * Get drm devices on the system
4082 * \param devices the array of devices with drmDevicePtr elements
4083 * can be NULL to get the device number first
4084 * \param max_devices the maximum number of devices for the array
4086 * \return on error - negative error code,
4087 * if devices is NULL - total number of devices available on the system,
4088 * alternatively the number of devices stored in devices[], which is
4089 * capped by the max_devices.
4091 int drmGetDevices(drmDevicePtr devices[], int max_devices)
4093 return drmGetDevices2(DRM_DEVICE_GET_PCI_REVISION, devices, max_devices);
4096 char *drmGetDeviceNameFromFd2(int fd)
4100 char path[PATH_MAX + 1], *value;
4101 unsigned int maj, min;
4103 if (fstat(fd, &sbuf))
4106 maj = major(sbuf.st_rdev);
4107 min = minor(sbuf.st_rdev);
4109 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
4112 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d", maj, min);
4114 value = sysfs_uevent_get(path, "DEVNAME");
4118 snprintf(path, sizeof(path), "/dev/%s", value);
4121 return strdup(path);
4124 char node[PATH_MAX + 1];
4125 const char *dev_name;
4127 int maj, min, n, base;
4129 if (fstat(fd, &sbuf))
4132 maj = major(sbuf.st_rdev);
4133 min = minor(sbuf.st_rdev);
4135 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
4138 node_type = drmGetMinorType(min);
4139 if (node_type == -1)
4142 switch (node_type) {
4143 case DRM_NODE_PRIMARY:
4144 dev_name = DRM_DEV_NAME;
4146 case DRM_NODE_CONTROL:
4147 dev_name = DRM_CONTROL_DEV_NAME;
4149 case DRM_NODE_RENDER:
4150 dev_name = DRM_RENDER_DEV_NAME;
4156 base = drmGetMinorBase(node_type);
4160 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min - base);
4161 if (n == -1 || n >= PATH_MAX)
4164 return strdup(node);
4168 int drmSyncobjCreate(int fd, uint32_t flags, uint32_t *handle)
4170 struct drm_syncobj_create args;
4176 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_CREATE, &args);
4179 *handle = args.handle;
4183 int drmSyncobjDestroy(int fd, uint32_t handle)
4185 struct drm_syncobj_destroy args;
4188 args.handle = handle;
4189 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_DESTROY, &args);
4192 int drmSyncobjHandleToFD(int fd, uint32_t handle, int *obj_fd)
4194 struct drm_syncobj_handle args;
4199 args.handle = handle;
4200 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4207 int drmSyncobjFDToHandle(int fd, int obj_fd, uint32_t *handle)
4209 struct drm_syncobj_handle args;
4215 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4218 *handle = args.handle;
4222 int drmSyncobjImportSyncFile(int fd, uint32_t handle, int sync_file_fd)
4224 struct drm_syncobj_handle args;
4227 args.fd = sync_file_fd;
4228 args.handle = handle;
4229 args.flags = DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE;
4230 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4233 int drmSyncobjExportSyncFile(int fd, uint32_t handle, int *sync_file_fd)
4235 struct drm_syncobj_handle args;
4240 args.handle = handle;
4241 args.flags = DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE;
4242 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4245 *sync_file_fd = args.fd;
4249 int drmSyncobjWait(int fd, uint32_t *handles, unsigned num_handles,
4250 int64_t timeout_nsec, unsigned flags,
4251 uint32_t *first_signaled)
4253 struct drm_syncobj_wait args;
4257 args.handles = (uintptr_t)handles;
4258 args.timeout_nsec = timeout_nsec;
4259 args.count_handles = num_handles;
4262 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_WAIT, &args);
4267 *first_signaled = args.first_signaled;
4271 int drmSyncobjReset(int fd, const uint32_t *handles, uint32_t handle_count)
4273 struct drm_syncobj_array args;
4277 args.handles = (uintptr_t)handles;
4278 args.count_handles = handle_count;
4280 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_RESET, &args);
4284 int drmSyncobjSignal(int fd, const uint32_t *handles, uint32_t handle_count)
4286 struct drm_syncobj_array args;
4290 args.handles = (uintptr_t)handles;
4291 args.count_handles = handle_count;
4293 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_SIGNAL, &args);