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.
49 #include <sys/types.h>
51 #define stat_t struct stat
52 #include <sys/ioctl.h>
55 #ifdef HAVE_SYS_MKDEV_H
56 # include <sys/mkdev.h> /* defines major(), minor(), and makedev() on Solaris */
60 /* Not all systems have MAP_FAILED defined */
62 #define MAP_FAILED ((void *)-1)
66 #include "libdrm_macros.h"
69 #define DRM_PRIMARY_MINOR_NAME "drm"
70 #define DRM_CONTROL_MINOR_NAME "drmC"
71 #define DRM_RENDER_MINOR_NAME "drmR"
73 #define DRM_PRIMARY_MINOR_NAME "card"
74 #define DRM_CONTROL_MINOR_NAME "controlD"
75 #define DRM_RENDER_MINOR_NAME "renderD"
78 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
92 #endif /* __OpenBSD__ */
95 #define DRM_MAJOR 226 /* Linux */
99 * This definition needs to be changed on some systems if dev_t is a structure.
100 * If there is a header file we can get it from, there would be best.
103 #define makedev(x,y) ((dev_t)(((x) << 8) | (y)))
106 #define DRM_MSG_VERBOSITY 3
108 #define memclear(s) memset(&s, 0, sizeof(s))
110 static drmServerInfoPtr drm_server_info;
112 void drmSetServerInfo(drmServerInfoPtr info)
114 drm_server_info = info;
118 * Output a message to stderr.
120 * \param format printf() like format string.
123 * This function is a wrapper around vfprintf().
126 static int DRM_PRINTFLIKE(1, 0)
127 drmDebugPrint(const char *format, va_list ap)
129 return vfprintf(stderr, format, ap);
133 drmMsg(const char *format, ...)
137 if (((env = getenv("LIBGL_DEBUG")) && strstr(env, "verbose")) ||
138 (drm_server_info && drm_server_info->debug_print))
140 va_start(ap, format);
141 if (drm_server_info) {
142 drm_server_info->debug_print(format,ap);
144 drmDebugPrint(format, ap);
150 static void *drmHashTable = NULL; /* Context switch callbacks */
152 void *drmGetHashTable(void)
157 void *drmMalloc(int size)
159 return calloc(1, size);
162 void drmFree(void *pt)
168 * Call ioctl, restarting if it is interupted
171 drmIoctl(int fd, unsigned long request, void *arg)
176 ret = ioctl(fd, request, arg);
177 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
181 static unsigned long drmGetKeyFromFd(int fd)
190 drmHashEntry *drmGetEntry(int fd)
192 unsigned long key = drmGetKeyFromFd(fd);
197 drmHashTable = drmHashCreate();
199 if (drmHashLookup(drmHashTable, key, &value)) {
200 entry = drmMalloc(sizeof(*entry));
203 entry->tagTable = drmHashCreate();
204 drmHashInsert(drmHashTable, key, entry);
212 * Compare two busid strings
217 * \return 1 if matched.
220 * This function compares two bus ID strings. It understands the older
221 * PCI:b:d:f format and the newer pci:oooo:bb:dd.f format. In the format, o is
222 * domain, b is bus, d is device, f is function.
224 static int drmMatchBusID(const char *id1, const char *id2, int pci_domain_ok)
226 /* First, check if the IDs are exactly the same */
227 if (strcasecmp(id1, id2) == 0)
230 /* Try to match old/new-style PCI bus IDs. */
231 if (strncasecmp(id1, "pci", 3) == 0) {
232 unsigned int o1, b1, d1, f1;
233 unsigned int o2, b2, d2, f2;
236 ret = sscanf(id1, "pci:%04x:%02x:%02x.%u", &o1, &b1, &d1, &f1);
239 ret = sscanf(id1, "PCI:%u:%u:%u", &b1, &d1, &f1);
244 ret = sscanf(id2, "pci:%04x:%02x:%02x.%u", &o2, &b2, &d2, &f2);
247 ret = sscanf(id2, "PCI:%u:%u:%u", &b2, &d2, &f2);
252 /* If domains aren't properly supported by the kernel interface,
253 * just ignore them, which sucks less than picking a totally random
254 * card with "open by name"
259 if ((o1 != o2) || (b1 != b2) || (d1 != d2) || (f1 != f2))
268 * Handles error checking for chown call.
270 * \param path to file.
271 * \param id of the new owner.
272 * \param id of the new group.
274 * \return zero if success or -1 if failure.
277 * Checks for failure. If failure was caused by signal call chown again.
278 * If any other failure happened then it will output error mesage using
282 static int chown_check_return(const char *path, uid_t owner, gid_t group)
287 rv = chown(path, owner, group);
288 } while (rv != 0 && errno == EINTR);
293 drmMsg("Failed to change owner or group for file %s! %d: %s\n",
294 path, errno, strerror(errno));
300 * Open the DRM device, creating it if necessary.
302 * \param dev major and minor numbers of the device.
303 * \param minor minor number of the device.
305 * \return a file descriptor on success, or a negative value on error.
308 * Assembles the device name from \p minor and opens it, creating the device
309 * special file node with the major and minor numbers specified by \p dev and
310 * parent directory if necessary and was called by root.
312 static int drmOpenDevice(dev_t dev, int minor, int type)
315 const char *dev_name;
318 mode_t devmode = DRM_DEV_MODE, serv_mode;
321 int isroot = !geteuid();
322 uid_t user = DRM_DEV_UID;
323 gid_t group = DRM_DEV_GID;
327 case DRM_NODE_PRIMARY:
328 dev_name = DRM_DEV_NAME;
330 case DRM_NODE_CONTROL:
331 dev_name = DRM_CONTROL_DEV_NAME;
333 case DRM_NODE_RENDER:
334 dev_name = DRM_RENDER_DEV_NAME;
340 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
341 drmMsg("drmOpenDevice: node name is %s\n", buf);
343 if (drm_server_info && drm_server_info->get_perms) {
344 drm_server_info->get_perms(&serv_group, &serv_mode);
345 devmode = serv_mode ? serv_mode : DRM_DEV_MODE;
346 devmode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
350 if (stat(DRM_DIR_NAME, &st)) {
352 return DRM_ERR_NOT_ROOT;
353 mkdir(DRM_DIR_NAME, DRM_DEV_DIRMODE);
354 chown_check_return(DRM_DIR_NAME, 0, 0); /* root:root */
355 chmod(DRM_DIR_NAME, DRM_DEV_DIRMODE);
358 /* Check if the device node exists and create it if necessary. */
359 if (stat(buf, &st)) {
361 return DRM_ERR_NOT_ROOT;
363 mknod(buf, S_IFCHR | devmode, dev);
366 if (drm_server_info && drm_server_info->get_perms) {
367 group = ((int)serv_group >= 0) ? serv_group : DRM_DEV_GID;
368 chown_check_return(buf, user, group);
372 /* if we modprobed then wait for udev */
376 if (stat(DRM_DIR_NAME, &st)) {
380 if (udev_count == 50)
385 if (stat(buf, &st)) {
389 if (udev_count == 50)
396 fd = open(buf, O_RDWR, 0);
397 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
398 fd, fd < 0 ? strerror(errno) : "OK");
403 /* Check if the device node is not what we expect it to be, and recreate it
404 * and try again if so.
406 if (st.st_rdev != dev) {
408 return DRM_ERR_NOT_ROOT;
410 mknod(buf, S_IFCHR | devmode, dev);
411 if (drm_server_info && drm_server_info->get_perms) {
412 chown_check_return(buf, user, group);
416 fd = open(buf, O_RDWR, 0);
417 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
418 fd, fd < 0 ? strerror(errno) : "OK");
422 drmMsg("drmOpenDevice: Open failed\n");
430 * Open the DRM device
432 * \param minor device minor number.
433 * \param create allow to create the device if set.
435 * \return a file descriptor on success, or a negative value on error.
438 * Calls drmOpenDevice() if \p create is set, otherwise assembles the device
439 * name from \p minor and opens it.
441 static int drmOpenMinor(int minor, int create, int type)
445 const char *dev_name;
448 return drmOpenDevice(makedev(DRM_MAJOR, minor), minor, type);
451 case DRM_NODE_PRIMARY:
452 dev_name = DRM_DEV_NAME;
454 case DRM_NODE_CONTROL:
455 dev_name = DRM_CONTROL_DEV_NAME;
457 case DRM_NODE_RENDER:
458 dev_name = DRM_RENDER_DEV_NAME;
464 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
465 if ((fd = open(buf, O_RDWR, 0)) >= 0)
472 * Determine whether the DRM kernel driver has been loaded.
474 * \return 1 if the DRM driver is loaded, 0 otherwise.
477 * Determine the presence of the kernel driver by attempting to open the 0
478 * minor and get version information. For backward compatibility with older
479 * Linux implementations, /proc/dri is also checked.
481 int drmAvailable(void)
483 drmVersionPtr version;
487 if ((fd = drmOpenMinor(0, 1, DRM_NODE_PRIMARY)) < 0) {
489 /* Try proc for backward Linux compatibility */
490 if (!access("/proc/dri/0", R_OK))
496 if ((version = drmGetVersion(fd))) {
498 drmFreeVersion(version);
505 static int drmGetMinorBase(int type)
508 case DRM_NODE_PRIMARY:
510 case DRM_NODE_CONTROL:
512 case DRM_NODE_RENDER:
519 static int drmGetMinorType(int minor)
521 int type = minor >> 6;
527 case DRM_NODE_PRIMARY:
528 case DRM_NODE_CONTROL:
529 case DRM_NODE_RENDER:
536 static const char *drmGetMinorName(int type)
539 case DRM_NODE_PRIMARY:
540 return DRM_PRIMARY_MINOR_NAME;
541 case DRM_NODE_CONTROL:
542 return DRM_CONTROL_MINOR_NAME;
543 case DRM_NODE_RENDER:
544 return DRM_RENDER_MINOR_NAME;
551 * Open the device by bus ID.
553 * \param busid bus ID.
554 * \param type device node type.
556 * \return a file descriptor on success, or a negative value on error.
559 * This function attempts to open every possible minor (up to DRM_MAX_MINOR),
560 * comparing the device bus ID with the one supplied.
562 * \sa drmOpenMinor() and drmGetBusid().
564 static int drmOpenByBusid(const char *busid, int type)
566 int i, pci_domain_ok = 1;
570 int base = drmGetMinorBase(type);
575 drmMsg("drmOpenByBusid: Searching for BusID %s\n", busid);
576 for (i = base; i < base + DRM_MAX_MINOR; i++) {
577 fd = drmOpenMinor(i, 1, type);
578 drmMsg("drmOpenByBusid: drmOpenMinor returns %d\n", fd);
580 /* We need to try for 1.4 first for proper PCI domain support
581 * and if that fails, we know the kernel is busted
585 sv.drm_dd_major = -1; /* Don't care */
586 sv.drm_dd_minor = -1; /* Don't care */
587 if (drmSetInterfaceVersion(fd, &sv)) {
593 sv.drm_dd_major = -1; /* Don't care */
594 sv.drm_dd_minor = -1; /* Don't care */
595 drmMsg("drmOpenByBusid: Interface 1.4 failed, trying 1.1\n");
596 drmSetInterfaceVersion(fd, &sv);
598 buf = drmGetBusid(fd);
599 drmMsg("drmOpenByBusid: drmGetBusid reports %s\n", buf);
600 if (buf && drmMatchBusID(buf, busid, pci_domain_ok)) {
614 * Open the device by name.
616 * \param name driver name.
617 * \param type the device node type.
619 * \return a file descriptor on success, or a negative value on error.
622 * This function opens the first minor number that matches the driver name and
623 * isn't already in use. If it's in use it then it will already have a bus ID
626 * \sa drmOpenMinor(), drmGetVersion() and drmGetBusid().
628 static int drmOpenByName(const char *name, int type)
632 drmVersionPtr version;
634 int base = drmGetMinorBase(type);
640 * Open the first minor number that matches the driver name and isn't
641 * already in use. If it's in use it will have a busid assigned already.
643 for (i = base; i < base + DRM_MAX_MINOR; i++) {
644 if ((fd = drmOpenMinor(i, 1, type)) >= 0) {
645 if ((version = drmGetVersion(fd))) {
646 if (!strcmp(version->name, name)) {
647 drmFreeVersion(version);
648 id = drmGetBusid(fd);
649 drmMsg("drmGetBusid returned '%s'\n", id ? id : "NULL");
658 drmFreeVersion(version);
666 /* Backward-compatibility /proc support */
667 for (i = 0; i < 8; i++) {
668 char proc_name[64], buf[512];
669 char *driver, *pt, *devstring;
672 sprintf(proc_name, "/proc/dri/%d/name", i);
673 if ((fd = open(proc_name, 0, 0)) >= 0) {
674 retcode = read(fd, buf, sizeof(buf)-1);
677 buf[retcode-1] = '\0';
678 for (driver = pt = buf; *pt && *pt != ' '; ++pt)
680 if (*pt) { /* Device is next */
682 if (!strcmp(driver, name)) { /* Match */
683 for (devstring = ++pt; *pt && *pt != ' '; ++pt)
685 if (*pt) { /* Found busid */
686 return drmOpenByBusid(++pt, type);
687 } else { /* No busid */
688 return drmOpenDevice(strtol(devstring, NULL, 0),i, type);
702 * Open the DRM device.
704 * Looks up the specified name and bus ID, and opens the device found. The
705 * entry in /dev/dri is created if necessary and if called by root.
707 * \param name driver name. Not referenced if bus ID is supplied.
708 * \param busid bus ID. Zero if not known.
710 * \return a file descriptor on success, or a negative value on error.
713 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
716 int drmOpen(const char *name, const char *busid)
718 return drmOpenWithType(name, busid, DRM_NODE_PRIMARY);
722 * Open the DRM device with specified type.
724 * Looks up the specified name and bus ID, and opens the device found. The
725 * entry in /dev/dri is created if necessary and if called by root.
727 * \param name driver name. Not referenced if bus ID is supplied.
728 * \param busid bus ID. Zero if not known.
729 * \param type the device node type to open, PRIMARY, CONTROL or RENDER
731 * \return a file descriptor on success, or a negative value on error.
734 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
737 int drmOpenWithType(const char *name, const char *busid, int type)
739 if (!drmAvailable() && name != NULL && drm_server_info &&
740 drm_server_info->load_module) {
741 /* try to load the kernel module */
742 if (!drm_server_info->load_module(name)) {
743 drmMsg("[drm] failed to load kernel module \"%s\"\n", name);
749 int fd = drmOpenByBusid(busid, type);
755 return drmOpenByName(name, type);
760 int drmOpenControl(int minor)
762 return drmOpenMinor(minor, 0, DRM_NODE_CONTROL);
765 int drmOpenRender(int minor)
767 return drmOpenMinor(minor, 0, DRM_NODE_RENDER);
771 * Free the version information returned by drmGetVersion().
773 * \param v pointer to the version information.
776 * It frees the memory pointed by \p %v as well as all the non-null strings
779 void drmFreeVersion(drmVersionPtr v)
791 * Free the non-public version information returned by the kernel.
793 * \param v pointer to the version information.
796 * Used by drmGetVersion() to free the memory pointed by \p %v as well as all
797 * the non-null strings pointers in it.
799 static void drmFreeKernelVersion(drm_version_t *v)
811 * Copy version information.
813 * \param d destination pointer.
814 * \param s source pointer.
817 * Used by drmGetVersion() to translate the information returned by the ioctl
818 * interface in a private structure into the public structure counterpart.
820 static void drmCopyVersion(drmVersionPtr d, const drm_version_t *s)
822 d->version_major = s->version_major;
823 d->version_minor = s->version_minor;
824 d->version_patchlevel = s->version_patchlevel;
825 d->name_len = s->name_len;
826 d->name = strdup(s->name);
827 d->date_len = s->date_len;
828 d->date = strdup(s->date);
829 d->desc_len = s->desc_len;
830 d->desc = strdup(s->desc);
835 * Query the driver version information.
837 * \param fd file descriptor.
839 * \return pointer to a drmVersion structure which should be freed with
842 * \note Similar information is available via /proc/dri.
845 * It gets the version information via successive DRM_IOCTL_VERSION ioctls,
846 * first with zeros to get the string lengths, and then the actually strings.
847 * It also null-terminates them since they might not be already.
849 drmVersionPtr drmGetVersion(int fd)
851 drmVersionPtr retval;
852 drm_version_t *version = drmMalloc(sizeof(*version));
856 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
857 drmFreeKernelVersion(version);
861 if (version->name_len)
862 version->name = drmMalloc(version->name_len + 1);
863 if (version->date_len)
864 version->date = drmMalloc(version->date_len + 1);
865 if (version->desc_len)
866 version->desc = drmMalloc(version->desc_len + 1);
868 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
869 drmMsg("DRM_IOCTL_VERSION: %s\n", strerror(errno));
870 drmFreeKernelVersion(version);
874 /* The results might not be null-terminated strings, so terminate them. */
875 if (version->name_len) version->name[version->name_len] = '\0';
876 if (version->date_len) version->date[version->date_len] = '\0';
877 if (version->desc_len) version->desc[version->desc_len] = '\0';
879 retval = drmMalloc(sizeof(*retval));
880 drmCopyVersion(retval, version);
881 drmFreeKernelVersion(version);
887 * Get version information for the DRM user space library.
889 * This version number is driver independent.
891 * \param fd file descriptor.
893 * \return version information.
896 * This function allocates and fills a drm_version structure with a hard coded
899 drmVersionPtr drmGetLibVersion(int fd)
901 drm_version_t *version = drmMalloc(sizeof(*version));
904 * NOTE THIS MUST NOT GO ABOVE VERSION 1.X due to drivers needing it
905 * revision 1.0.x = original DRM interface with no drmGetLibVersion
906 * entry point and many drm<Device> extensions
907 * revision 1.1.x = added drmCommand entry points for device extensions
908 * added drmGetLibVersion to identify libdrm.a version
909 * revision 1.2.x = added drmSetInterfaceVersion
910 * modified drmOpen to handle both busid and name
911 * revision 1.3.x = added server + memory manager
913 version->version_major = 1;
914 version->version_minor = 3;
915 version->version_patchlevel = 0;
917 return (drmVersionPtr)version;
920 int drmGetCap(int fd, uint64_t capability, uint64_t *value)
922 struct drm_get_cap cap;
926 cap.capability = capability;
928 ret = drmIoctl(fd, DRM_IOCTL_GET_CAP, &cap);
936 int drmSetClientCap(int fd, uint64_t capability, uint64_t value)
938 struct drm_set_client_cap cap;
941 cap.capability = capability;
944 return drmIoctl(fd, DRM_IOCTL_SET_CLIENT_CAP, &cap);
948 * Free the bus ID information.
950 * \param busid bus ID information string as given by drmGetBusid().
953 * This function is just frees the memory pointed by \p busid.
955 void drmFreeBusid(const char *busid)
957 drmFree((void *)busid);
962 * Get the bus ID of the device.
964 * \param fd file descriptor.
966 * \return bus ID string.
969 * This function gets the bus ID via successive DRM_IOCTL_GET_UNIQUE ioctls to
970 * get the string length and data, passing the arguments in a drm_unique
973 char *drmGetBusid(int fd)
979 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
981 u.unique = drmMalloc(u.unique_len + 1);
982 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
984 u.unique[u.unique_len] = '\0';
991 * Set the bus ID of the device.
993 * \param fd file descriptor.
994 * \param busid bus ID string.
996 * \return zero on success, negative on failure.
999 * This function is a wrapper around the DRM_IOCTL_SET_UNIQUE ioctl, passing
1000 * the arguments in a drm_unique structure.
1002 int drmSetBusid(int fd, const char *busid)
1007 u.unique = (char *)busid;
1008 u.unique_len = strlen(busid);
1010 if (drmIoctl(fd, DRM_IOCTL_SET_UNIQUE, &u)) {
1016 int drmGetMagic(int fd, drm_magic_t * magic)
1023 if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
1025 *magic = auth.magic;
1029 int drmAuthMagic(int fd, drm_magic_t magic)
1035 if (drmIoctl(fd, DRM_IOCTL_AUTH_MAGIC, &auth))
1041 * Specifies a range of memory that is available for mapping by a
1044 * \param fd file descriptor.
1045 * \param offset usually the physical address. The actual meaning depends of
1046 * the \p type parameter. See below.
1047 * \param size of the memory in bytes.
1048 * \param type type of the memory to be mapped.
1049 * \param flags combination of several flags to modify the function actions.
1050 * \param handle will be set to a value that may be used as the offset
1051 * parameter for mmap().
1053 * \return zero on success or a negative value on error.
1055 * \par Mapping the frame buffer
1056 * For the frame buffer
1057 * - \p offset will be the physical address of the start of the frame buffer,
1058 * - \p size will be the size of the frame buffer in bytes, and
1059 * - \p type will be DRM_FRAME_BUFFER.
1062 * The area mapped will be uncached. If MTRR support is available in the
1063 * kernel, the frame buffer area will be set to write combining.
1065 * \par Mapping the MMIO register area
1066 * For the MMIO register area,
1067 * - \p offset will be the physical address of the start of the register area,
1068 * - \p size will be the size of the register area bytes, and
1069 * - \p type will be DRM_REGISTERS.
1071 * The area mapped will be uncached.
1073 * \par Mapping the SAREA
1075 * - \p offset will be ignored and should be set to zero,
1076 * - \p size will be the desired size of the SAREA in bytes,
1077 * - \p type will be DRM_SHM.
1080 * A shared memory area of the requested size will be created and locked in
1081 * kernel memory. This area may be mapped into client-space by using the handle
1084 * \note May only be called by root.
1087 * This function is a wrapper around the DRM_IOCTL_ADD_MAP ioctl, passing
1088 * the arguments in a drm_map structure.
1090 int drmAddMap(int fd, drm_handle_t offset, drmSize size, drmMapType type,
1091 drmMapFlags flags, drm_handle_t *handle)
1096 map.offset = offset;
1100 if (drmIoctl(fd, DRM_IOCTL_ADD_MAP, &map))
1103 *handle = (drm_handle_t)(uintptr_t)map.handle;
1107 int drmRmMap(int fd, drm_handle_t handle)
1112 map.handle = (void *)(uintptr_t)handle;
1114 if(drmIoctl(fd, DRM_IOCTL_RM_MAP, &map))
1120 * Make buffers available for DMA transfers.
1122 * \param fd file descriptor.
1123 * \param count number of buffers.
1124 * \param size size of each buffer.
1125 * \param flags buffer allocation flags.
1126 * \param agp_offset offset in the AGP aperture
1128 * \return number of buffers allocated, negative on error.
1131 * This function is a wrapper around DRM_IOCTL_ADD_BUFS ioctl.
1135 int drmAddBufs(int fd, int count, int size, drmBufDescFlags flags,
1138 drm_buf_desc_t request;
1141 request.count = count;
1142 request.size = size;
1143 request.flags = flags;
1144 request.agp_start = agp_offset;
1146 if (drmIoctl(fd, DRM_IOCTL_ADD_BUFS, &request))
1148 return request.count;
1151 int drmMarkBufs(int fd, double low, double high)
1153 drm_buf_info_t info;
1158 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1164 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1167 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1168 int retval = -errno;
1173 for (i = 0; i < info.count; i++) {
1174 info.list[i].low_mark = low * info.list[i].count;
1175 info.list[i].high_mark = high * info.list[i].count;
1176 if (drmIoctl(fd, DRM_IOCTL_MARK_BUFS, &info.list[i])) {
1177 int retval = -errno;
1190 * \param fd file descriptor.
1191 * \param count number of buffers to free.
1192 * \param list list of buffers to be freed.
1194 * \return zero on success, or a negative value on failure.
1196 * \note This function is primarily used for debugging.
1199 * This function is a wrapper around the DRM_IOCTL_FREE_BUFS ioctl, passing
1200 * the arguments in a drm_buf_free structure.
1202 int drmFreeBufs(int fd, int count, int *list)
1204 drm_buf_free_t request;
1207 request.count = count;
1208 request.list = list;
1209 if (drmIoctl(fd, DRM_IOCTL_FREE_BUFS, &request))
1218 * \param fd file descriptor.
1221 * This function closes the file descriptor.
1223 int drmClose(int fd)
1225 unsigned long key = drmGetKeyFromFd(fd);
1226 drmHashEntry *entry = drmGetEntry(fd);
1228 drmHashDestroy(entry->tagTable);
1231 entry->tagTable = NULL;
1233 drmHashDelete(drmHashTable, key);
1241 * Map a region of memory.
1243 * \param fd file descriptor.
1244 * \param handle handle returned by drmAddMap().
1245 * \param size size in bytes. Must match the size used by drmAddMap().
1246 * \param address will contain the user-space virtual address where the mapping
1249 * \return zero on success, or a negative value on failure.
1252 * This function is a wrapper for mmap().
1254 int drmMap(int fd, drm_handle_t handle, drmSize size, drmAddressPtr address)
1256 static unsigned long pagesize_mask = 0;
1262 pagesize_mask = getpagesize() - 1;
1264 size = (size + pagesize_mask) & ~pagesize_mask;
1266 *address = drm_mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1267 if (*address == MAP_FAILED)
1274 * Unmap mappings obtained with drmMap().
1276 * \param address address as given by drmMap().
1277 * \param size size in bytes. Must match the size used by drmMap().
1279 * \return zero on success, or a negative value on failure.
1282 * This function is a wrapper for munmap().
1284 int drmUnmap(drmAddress address, drmSize size)
1286 return drm_munmap(address, size);
1289 drmBufInfoPtr drmGetBufInfo(int fd)
1291 drm_buf_info_t info;
1292 drmBufInfoPtr retval;
1297 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1301 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1304 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1309 retval = drmMalloc(sizeof(*retval));
1310 retval->count = info.count;
1311 retval->list = drmMalloc(info.count * sizeof(*retval->list));
1312 for (i = 0; i < info.count; i++) {
1313 retval->list[i].count = info.list[i].count;
1314 retval->list[i].size = info.list[i].size;
1315 retval->list[i].low_mark = info.list[i].low_mark;
1316 retval->list[i].high_mark = info.list[i].high_mark;
1325 * Map all DMA buffers into client-virtual space.
1327 * \param fd file descriptor.
1329 * \return a pointer to a ::drmBufMap structure.
1331 * \note The client may not use these buffers until obtaining buffer indices
1335 * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1336 * information about the buffers in a drm_buf_map structure into the
1337 * client-visible data structures.
1339 drmBufMapPtr drmMapBufs(int fd)
1342 drmBufMapPtr retval;
1346 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1352 if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1355 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1360 retval = drmMalloc(sizeof(*retval));
1361 retval->count = bufs.count;
1362 retval->list = drmMalloc(bufs.count * sizeof(*retval->list));
1363 for (i = 0; i < bufs.count; i++) {
1364 retval->list[i].idx = bufs.list[i].idx;
1365 retval->list[i].total = bufs.list[i].total;
1366 retval->list[i].used = 0;
1367 retval->list[i].address = bufs.list[i].address;
1377 * Unmap buffers allocated with drmMapBufs().
1379 * \return zero on success, or negative value on failure.
1382 * Calls munmap() for every buffer stored in \p bufs and frees the
1383 * memory allocated by drmMapBufs().
1385 int drmUnmapBufs(drmBufMapPtr bufs)
1389 for (i = 0; i < bufs->count; i++) {
1390 drm_munmap(bufs->list[i].address, bufs->list[i].total);
1393 drmFree(bufs->list);
1400 #define DRM_DMA_RETRY 16
1403 * Reserve DMA buffers.
1405 * \param fd file descriptor.
1408 * \return zero on success, or a negative value on failure.
1411 * Assemble the arguments into a drm_dma structure and keeps issuing the
1412 * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1414 int drmDMA(int fd, drmDMAReqPtr request)
1419 dma.context = request->context;
1420 dma.send_count = request->send_count;
1421 dma.send_indices = request->send_list;
1422 dma.send_sizes = request->send_sizes;
1423 dma.flags = request->flags;
1424 dma.request_count = request->request_count;
1425 dma.request_size = request->request_size;
1426 dma.request_indices = request->request_list;
1427 dma.request_sizes = request->request_sizes;
1428 dma.granted_count = 0;
1431 ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1432 } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1435 request->granted_count = dma.granted_count;
1444 * Obtain heavyweight hardware lock.
1446 * \param fd file descriptor.
1447 * \param context context.
1448 * \param flags flags that determine the sate of the hardware when the function
1451 * \return always zero.
1454 * This function translates the arguments into a drm_lock structure and issue
1455 * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1457 int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
1462 lock.context = context;
1464 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
1465 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
1466 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
1467 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
1468 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
1469 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
1471 while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
1477 * Release the hardware lock.
1479 * \param fd file descriptor.
1480 * \param context context.
1482 * \return zero on success, or a negative value on failure.
1485 * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
1486 * argument in a drm_lock structure.
1488 int drmUnlock(int fd, drm_context_t context)
1493 lock.context = context;
1494 return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
1497 drm_context_t *drmGetReservedContextList(int fd, int *count)
1501 drm_context_t * retval;
1505 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1511 if (!(list = drmMalloc(res.count * sizeof(*list))))
1513 if (!(retval = drmMalloc(res.count * sizeof(*retval)))) {
1518 res.contexts = list;
1519 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1522 for (i = 0; i < res.count; i++)
1523 retval[i] = list[i].handle;
1530 void drmFreeReservedContextList(drm_context_t *pt)
1538 * Used by the X server during GLXContext initialization. This causes
1539 * per-context kernel-level resources to be allocated.
1541 * \param fd file descriptor.
1542 * \param handle is set on success. To be used by the client when requesting DMA
1543 * dispatch with drmDMA().
1545 * \return zero on success, or a negative value on failure.
1547 * \note May only be called by root.
1550 * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
1551 * argument in a drm_ctx structure.
1553 int drmCreateContext(int fd, drm_context_t *handle)
1558 if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
1560 *handle = ctx.handle;
1564 int drmSwitchToContext(int fd, drm_context_t context)
1569 ctx.handle = context;
1570 if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
1575 int drmSetContextFlags(int fd, drm_context_t context, drm_context_tFlags flags)
1580 * Context preserving means that no context switches are done between DMA
1581 * buffers from one context and the next. This is suitable for use in the
1582 * X server (which promises to maintain hardware context), or in the
1583 * client-side library when buffers are swapped on behalf of two threads.
1586 ctx.handle = context;
1587 if (flags & DRM_CONTEXT_PRESERVED)
1588 ctx.flags |= _DRM_CONTEXT_PRESERVED;
1589 if (flags & DRM_CONTEXT_2DONLY)
1590 ctx.flags |= _DRM_CONTEXT_2DONLY;
1591 if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
1596 int drmGetContextFlags(int fd, drm_context_t context,
1597 drm_context_tFlagsPtr flags)
1602 ctx.handle = context;
1603 if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
1606 if (ctx.flags & _DRM_CONTEXT_PRESERVED)
1607 *flags |= DRM_CONTEXT_PRESERVED;
1608 if (ctx.flags & _DRM_CONTEXT_2DONLY)
1609 *flags |= DRM_CONTEXT_2DONLY;
1616 * Free any kernel-level resources allocated with drmCreateContext() associated
1619 * \param fd file descriptor.
1620 * \param handle handle given by drmCreateContext().
1622 * \return zero on success, or a negative value on failure.
1624 * \note May only be called by root.
1627 * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
1628 * argument in a drm_ctx structure.
1630 int drmDestroyContext(int fd, drm_context_t handle)
1635 ctx.handle = handle;
1636 if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
1641 int drmCreateDrawable(int fd, drm_drawable_t *handle)
1646 if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
1648 *handle = draw.handle;
1652 int drmDestroyDrawable(int fd, drm_drawable_t handle)
1657 draw.handle = handle;
1658 if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
1663 int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
1664 drm_drawable_info_type_t type, unsigned int num,
1667 drm_update_draw_t update;
1670 update.handle = handle;
1673 update.data = (unsigned long long)(unsigned long)data;
1675 if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
1682 * Acquire the AGP device.
1684 * Must be called before any of the other AGP related calls.
1686 * \param fd file descriptor.
1688 * \return zero on success, or a negative value on failure.
1691 * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
1693 int drmAgpAcquire(int fd)
1695 if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
1702 * Release the AGP device.
1704 * \param fd file descriptor.
1706 * \return zero on success, or a negative value on failure.
1709 * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
1711 int drmAgpRelease(int fd)
1713 if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
1722 * \param fd file descriptor.
1723 * \param mode AGP mode.
1725 * \return zero on success, or a negative value on failure.
1728 * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
1729 * argument in a drm_agp_mode structure.
1731 int drmAgpEnable(int fd, unsigned long mode)
1737 if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
1744 * Allocate a chunk of AGP memory.
1746 * \param fd file descriptor.
1747 * \param size requested memory size in bytes. Will be rounded to page boundary.
1748 * \param type type of memory to allocate.
1749 * \param address if not zero, will be set to the physical address of the
1751 * \param handle on success will be set to a handle of the allocated memory.
1753 * \return zero on success, or a negative value on failure.
1756 * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
1757 * arguments in a drm_agp_buffer structure.
1759 int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
1760 unsigned long *address, drm_handle_t *handle)
1765 *handle = DRM_AGP_NO_HANDLE;
1768 if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
1771 *address = b.physical;
1778 * Free a chunk of AGP memory.
1780 * \param fd file descriptor.
1781 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1783 * \return zero on success, or a negative value on failure.
1786 * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
1787 * argument in a drm_agp_buffer structure.
1789 int drmAgpFree(int fd, drm_handle_t handle)
1795 if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
1802 * Bind a chunk of AGP memory.
1804 * \param fd file descriptor.
1805 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1806 * \param offset offset in bytes. It will round to page boundary.
1808 * \return zero on success, or a negative value on failure.
1811 * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
1812 * argument in a drm_agp_binding structure.
1814 int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
1816 drm_agp_binding_t b;
1821 if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
1828 * Unbind a chunk of AGP memory.
1830 * \param fd file descriptor.
1831 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1833 * \return zero on success, or a negative value on failure.
1836 * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
1837 * the argument in a drm_agp_binding structure.
1839 int drmAgpUnbind(int fd, drm_handle_t handle)
1841 drm_agp_binding_t b;
1845 if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
1852 * Get AGP driver major version number.
1854 * \param fd file descriptor.
1856 * \return major version number on success, or a negative value on failure..
1859 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1860 * necessary information in a drm_agp_info structure.
1862 int drmAgpVersionMajor(int fd)
1868 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1870 return i.agp_version_major;
1875 * Get AGP driver minor version number.
1877 * \param fd file descriptor.
1879 * \return minor version number on success, or a negative value on failure.
1882 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1883 * necessary information in a drm_agp_info structure.
1885 int drmAgpVersionMinor(int fd)
1891 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1893 return i.agp_version_minor;
1900 * \param fd file descriptor.
1902 * \return mode on success, or zero on failure.
1905 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1906 * necessary information in a drm_agp_info structure.
1908 unsigned long drmAgpGetMode(int fd)
1914 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1921 * Get AGP aperture base.
1923 * \param fd file descriptor.
1925 * \return aperture base on success, zero on failure.
1928 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1929 * necessary information in a drm_agp_info structure.
1931 unsigned long drmAgpBase(int fd)
1937 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1939 return i.aperture_base;
1944 * Get AGP aperture size.
1946 * \param fd file descriptor.
1948 * \return aperture size on success, zero on failure.
1951 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1952 * necessary information in a drm_agp_info structure.
1954 unsigned long drmAgpSize(int fd)
1960 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1962 return i.aperture_size;
1967 * Get used AGP memory.
1969 * \param fd file descriptor.
1971 * \return memory used on success, or zero on failure.
1974 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1975 * necessary information in a drm_agp_info structure.
1977 unsigned long drmAgpMemoryUsed(int fd)
1983 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1985 return i.memory_used;
1990 * Get available AGP memory.
1992 * \param fd file descriptor.
1994 * \return memory available on success, or zero on failure.
1997 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1998 * necessary information in a drm_agp_info structure.
2000 unsigned long drmAgpMemoryAvail(int fd)
2006 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2008 return i.memory_allowed;
2013 * Get hardware vendor ID.
2015 * \param fd file descriptor.
2017 * \return vendor ID on success, or zero on failure.
2020 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2021 * necessary information in a drm_agp_info structure.
2023 unsigned int drmAgpVendorId(int fd)
2029 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2036 * Get hardware device ID.
2038 * \param fd file descriptor.
2040 * \return zero on success, or zero on failure.
2043 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2044 * necessary information in a drm_agp_info structure.
2046 unsigned int drmAgpDeviceId(int fd)
2052 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2057 int drmScatterGatherAlloc(int fd, unsigned long size, drm_handle_t *handle)
2059 drm_scatter_gather_t sg;
2065 if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
2067 *handle = sg.handle;
2071 int drmScatterGatherFree(int fd, drm_handle_t handle)
2073 drm_scatter_gather_t sg;
2077 if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
2085 * \param fd file descriptor.
2086 * \param vbl pointer to a drmVBlank structure.
2088 * \return zero on success, or a negative value on failure.
2091 * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
2093 int drmWaitVBlank(int fd, drmVBlankPtr vbl)
2095 struct timespec timeout, cur;
2098 ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2100 fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
2106 ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
2107 vbl->request.type &= ~DRM_VBLANK_RELATIVE;
2108 if (ret && errno == EINTR) {
2109 clock_gettime(CLOCK_MONOTONIC, &cur);
2110 /* Timeout after 1s */
2111 if (cur.tv_sec > timeout.tv_sec + 1 ||
2112 (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
2119 } while (ret && errno == EINTR);
2125 int drmError(int err, const char *label)
2128 case DRM_ERR_NO_DEVICE:
2129 fprintf(stderr, "%s: no device\n", label);
2131 case DRM_ERR_NO_ACCESS:
2132 fprintf(stderr, "%s: no access\n", label);
2134 case DRM_ERR_NOT_ROOT:
2135 fprintf(stderr, "%s: not root\n", label);
2137 case DRM_ERR_INVALID:
2138 fprintf(stderr, "%s: invalid args\n", label);
2143 fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2151 * Install IRQ handler.
2153 * \param fd file descriptor.
2154 * \param irq IRQ number.
2156 * \return zero on success, or a negative value on failure.
2159 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2160 * argument in a drm_control structure.
2162 int drmCtlInstHandler(int fd, int irq)
2167 ctl.func = DRM_INST_HANDLER;
2169 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2176 * Uninstall IRQ handler.
2178 * \param fd file descriptor.
2180 * \return zero on success, or a negative value on failure.
2183 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2184 * argument in a drm_control structure.
2186 int drmCtlUninstHandler(int fd)
2191 ctl.func = DRM_UNINST_HANDLER;
2193 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2198 int drmFinish(int fd, int context, drmLockFlags flags)
2203 lock.context = context;
2204 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
2205 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
2206 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
2207 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
2208 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2209 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2210 if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2216 * Get IRQ from bus ID.
2218 * \param fd file descriptor.
2219 * \param busnum bus number.
2220 * \param devnum device number.
2221 * \param funcnum function number.
2223 * \return IRQ number on success, or a negative value on failure.
2226 * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2227 * arguments in a drm_irq_busid structure.
2229 int drmGetInterruptFromBusID(int fd, int busnum, int devnum, int funcnum)
2236 p.funcnum = funcnum;
2237 if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2242 int drmAddContextTag(int fd, drm_context_t context, void *tag)
2244 drmHashEntry *entry = drmGetEntry(fd);
2246 if (drmHashInsert(entry->tagTable, context, tag)) {
2247 drmHashDelete(entry->tagTable, context);
2248 drmHashInsert(entry->tagTable, context, tag);
2253 int drmDelContextTag(int fd, drm_context_t context)
2255 drmHashEntry *entry = drmGetEntry(fd);
2257 return drmHashDelete(entry->tagTable, context);
2260 void *drmGetContextTag(int fd, drm_context_t context)
2262 drmHashEntry *entry = drmGetEntry(fd);
2265 if (drmHashLookup(entry->tagTable, context, &value))
2271 int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2272 drm_handle_t handle)
2274 drm_ctx_priv_map_t map;
2277 map.ctx_id = ctx_id;
2278 map.handle = (void *)(uintptr_t)handle;
2280 if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2285 int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2286 drm_handle_t *handle)
2288 drm_ctx_priv_map_t map;
2291 map.ctx_id = ctx_id;
2293 if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2296 *handle = (drm_handle_t)(uintptr_t)map.handle;
2301 int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2302 drmMapType *type, drmMapFlags *flags, drm_handle_t *handle,
2309 if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2311 *offset = map.offset;
2315 *handle = (unsigned long)map.handle;
2320 int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2321 unsigned long *magic, unsigned long *iocs)
2323 drm_client_t client;
2327 if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2329 *auth = client.auth;
2332 *magic = client.magic;
2333 *iocs = client.iocs;
2337 int drmGetStats(int fd, drmStatsT *stats)
2343 if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2347 memset(stats, 0, sizeof(*stats));
2348 if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2352 stats->data[i].long_format = "%-20.20s"; \
2353 stats->data[i].rate_format = "%8.8s"; \
2354 stats->data[i].isvalue = 1; \
2355 stats->data[i].verbose = 0
2358 stats->data[i].long_format = "%-20.20s"; \
2359 stats->data[i].rate_format = "%5.5s"; \
2360 stats->data[i].isvalue = 0; \
2361 stats->data[i].mult_names = "kgm"; \
2362 stats->data[i].mult = 1000; \
2363 stats->data[i].verbose = 0
2366 stats->data[i].long_format = "%-20.20s"; \
2367 stats->data[i].rate_format = "%5.5s"; \
2368 stats->data[i].isvalue = 0; \
2369 stats->data[i].mult_names = "KGM"; \
2370 stats->data[i].mult = 1024; \
2371 stats->data[i].verbose = 0
2374 stats->count = s.count;
2375 for (i = 0; i < s.count; i++) {
2376 stats->data[i].value = s.data[i].value;
2377 switch (s.data[i].type) {
2378 case _DRM_STAT_LOCK:
2379 stats->data[i].long_name = "Lock";
2380 stats->data[i].rate_name = "Lock";
2383 case _DRM_STAT_OPENS:
2384 stats->data[i].long_name = "Opens";
2385 stats->data[i].rate_name = "O";
2387 stats->data[i].verbose = 1;
2389 case _DRM_STAT_CLOSES:
2390 stats->data[i].long_name = "Closes";
2391 stats->data[i].rate_name = "Lock";
2393 stats->data[i].verbose = 1;
2395 case _DRM_STAT_IOCTLS:
2396 stats->data[i].long_name = "Ioctls";
2397 stats->data[i].rate_name = "Ioc/s";
2400 case _DRM_STAT_LOCKS:
2401 stats->data[i].long_name = "Locks";
2402 stats->data[i].rate_name = "Lck/s";
2405 case _DRM_STAT_UNLOCKS:
2406 stats->data[i].long_name = "Unlocks";
2407 stats->data[i].rate_name = "Unl/s";
2411 stats->data[i].long_name = "IRQs";
2412 stats->data[i].rate_name = "IRQ/s";
2415 case _DRM_STAT_PRIMARY:
2416 stats->data[i].long_name = "Primary Bytes";
2417 stats->data[i].rate_name = "PB/s";
2420 case _DRM_STAT_SECONDARY:
2421 stats->data[i].long_name = "Secondary Bytes";
2422 stats->data[i].rate_name = "SB/s";
2426 stats->data[i].long_name = "DMA";
2427 stats->data[i].rate_name = "DMA/s";
2430 case _DRM_STAT_SPECIAL:
2431 stats->data[i].long_name = "Special DMA";
2432 stats->data[i].rate_name = "dma/s";
2435 case _DRM_STAT_MISSED:
2436 stats->data[i].long_name = "Miss";
2437 stats->data[i].rate_name = "Ms/s";
2440 case _DRM_STAT_VALUE:
2441 stats->data[i].long_name = "Value";
2442 stats->data[i].rate_name = "Value";
2445 case _DRM_STAT_BYTE:
2446 stats->data[i].long_name = "Bytes";
2447 stats->data[i].rate_name = "B/s";
2450 case _DRM_STAT_COUNT:
2452 stats->data[i].long_name = "Count";
2453 stats->data[i].rate_name = "Cnt/s";
2462 * Issue a set-version ioctl.
2464 * \param fd file descriptor.
2465 * \param drmCommandIndex command index
2466 * \param data source pointer of the data to be read and written.
2467 * \param size size of the data to be read and written.
2469 * \return zero on success, or a negative value on failure.
2472 * It issues a read-write ioctl given by
2473 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2475 int drmSetInterfaceVersion(int fd, drmSetVersion *version)
2478 drm_set_version_t sv;
2481 sv.drm_di_major = version->drm_di_major;
2482 sv.drm_di_minor = version->drm_di_minor;
2483 sv.drm_dd_major = version->drm_dd_major;
2484 sv.drm_dd_minor = version->drm_dd_minor;
2486 if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
2490 version->drm_di_major = sv.drm_di_major;
2491 version->drm_di_minor = sv.drm_di_minor;
2492 version->drm_dd_major = sv.drm_dd_major;
2493 version->drm_dd_minor = sv.drm_dd_minor;
2499 * Send a device-specific command.
2501 * \param fd file descriptor.
2502 * \param drmCommandIndex command index
2504 * \return zero on success, or a negative value on failure.
2507 * It issues a ioctl given by
2508 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2510 int drmCommandNone(int fd, unsigned long drmCommandIndex)
2512 unsigned long request;
2514 request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
2516 if (drmIoctl(fd, request, NULL)) {
2524 * Send a device-specific read command.
2526 * \param fd file descriptor.
2527 * \param drmCommandIndex command index
2528 * \param data destination pointer of the data to be read.
2529 * \param size size of the data to be read.
2531 * \return zero on success, or a negative value on failure.
2534 * It issues a read ioctl given by
2535 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2537 int drmCommandRead(int fd, unsigned long drmCommandIndex, void *data,
2540 unsigned long request;
2542 request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
2543 DRM_COMMAND_BASE + drmCommandIndex, size);
2545 if (drmIoctl(fd, request, data)) {
2553 * Send a device-specific write command.
2555 * \param fd file descriptor.
2556 * \param drmCommandIndex command index
2557 * \param data source pointer of the data to be written.
2558 * \param size size of the data to be written.
2560 * \return zero on success, or a negative value on failure.
2563 * It issues a write ioctl given by
2564 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2566 int drmCommandWrite(int fd, unsigned long drmCommandIndex, void *data,
2569 unsigned long request;
2571 request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
2572 DRM_COMMAND_BASE + drmCommandIndex, size);
2574 if (drmIoctl(fd, request, data)) {
2582 * Send a device-specific read-write command.
2584 * \param fd file descriptor.
2585 * \param drmCommandIndex command index
2586 * \param data source pointer of the data to be read and written.
2587 * \param size size of the data to be read and written.
2589 * \return zero on success, or a negative value on failure.
2592 * It issues a read-write ioctl given by
2593 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2595 int drmCommandWriteRead(int fd, unsigned long drmCommandIndex, void *data,
2598 unsigned long request;
2600 request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
2601 DRM_COMMAND_BASE + drmCommandIndex, size);
2603 if (drmIoctl(fd, request, data))
2608 #define DRM_MAX_FDS 16
2614 } connection[DRM_MAX_FDS];
2616 static int nr_fds = 0;
2618 int drmOpenOnce(void *unused,
2622 return drmOpenOnceWithType(BusID, newlyopened, DRM_NODE_PRIMARY);
2625 int drmOpenOnceWithType(const char *BusID, int *newlyopened, int type)
2630 for (i = 0; i < nr_fds; i++)
2631 if ((strcmp(BusID, connection[i].BusID) == 0) &&
2632 (connection[i].type == type)) {
2633 connection[i].refcount++;
2635 return connection[i].fd;
2638 fd = drmOpenWithType(NULL, BusID, type);
2639 if (fd < 0 || nr_fds == DRM_MAX_FDS)
2642 connection[nr_fds].BusID = strdup(BusID);
2643 connection[nr_fds].fd = fd;
2644 connection[nr_fds].refcount = 1;
2645 connection[nr_fds].type = type;
2649 fprintf(stderr, "saved connection %d for %s %d\n",
2650 nr_fds, connection[nr_fds].BusID,
2651 strcmp(BusID, connection[nr_fds].BusID));
2658 void drmCloseOnce(int fd)
2662 for (i = 0; i < nr_fds; i++) {
2663 if (fd == connection[i].fd) {
2664 if (--connection[i].refcount == 0) {
2665 drmClose(connection[i].fd);
2666 free(connection[i].BusID);
2669 connection[i] = connection[nr_fds];
2677 int drmSetMaster(int fd)
2679 return drmIoctl(fd, DRM_IOCTL_SET_MASTER, NULL);
2682 int drmDropMaster(int fd)
2684 return drmIoctl(fd, DRM_IOCTL_DROP_MASTER, NULL);
2687 char *drmGetDeviceNameFromFd(int fd)
2694 /* The whole drmOpen thing is a fiasco and we need to find a way
2695 * back to just using open(2). For now, however, lets just make
2696 * things worse with even more ad hoc directory walking code to
2697 * discover the device file name. */
2702 for (i = 0; i < DRM_MAX_MINOR; i++) {
2703 snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
2704 if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
2707 if (i == DRM_MAX_MINOR)
2710 return strdup(name);
2713 int drmGetNodeTypeFromFd(int fd)
2718 if (fstat(fd, &sbuf))
2721 maj = major(sbuf.st_rdev);
2722 min = minor(sbuf.st_rdev);
2724 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode)) {
2729 type = drmGetMinorType(min);
2735 int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags, int *prime_fd)
2737 struct drm_prime_handle args;
2742 args.handle = handle;
2744 ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
2748 *prime_fd = args.fd;
2752 int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
2754 struct drm_prime_handle args;
2759 ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
2763 *handle = args.handle;
2767 static char *drmGetMinorNameForFD(int fd, int type)
2771 struct dirent *pent, *ent;
2773 const char *name = drmGetMinorName(type);
2775 char dev_name[64], buf[64];
2784 if (fstat(fd, &sbuf))
2787 maj = major(sbuf.st_rdev);
2788 min = minor(sbuf.st_rdev);
2790 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
2793 snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
2795 sysdir = opendir(buf);
2799 name_max = fpathconf(dirfd(sysdir), _PC_NAME_MAX);
2803 pent = malloc(offsetof(struct dirent, d_name) + name_max + 1);
2807 while (readdir_r(sysdir, pent, &ent) == 0 && ent != NULL) {
2808 if (strncmp(ent->d_name, name, len) == 0) {
2809 snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
2815 return strdup(dev_name);
2827 char *drmGetPrimaryDeviceNameFromFd(int fd)
2829 return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
2832 char *drmGetRenderDeviceNameFromFd(int fd)
2834 return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
2838 static int drmParseSubsystemType(const char *str)
2840 char link[PATH_MAX + 1] = "";
2843 if (readlink(str, link, PATH_MAX) < 0)
2846 name = strrchr(link, '/');
2852 if (strncmp(name, "pci", 3) == 0)
2858 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
2860 char path[PATH_MAX + 1];
2863 int domain, bus, dev, func;
2866 snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/uevent", maj, min);
2867 fd = open(path, O_RDONLY);
2871 ret = read(fd, data, sizeof(data));
2876 #define TAG "PCI_SLOT_NAME="
2877 str = strstr(data, TAG);
2881 if (sscanf(str, TAG "%04x:%02x:%02x.%1u",
2882 &domain, &bus, &dev, &func) != 4)
2886 info->domain = domain;
2894 static int drmSameDevice(drmDevicePtr a, drmDevicePtr b)
2896 if (a->bustype != b->bustype)
2899 switch (a->bustype) {
2901 if (memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo)) == 0)
2910 static int drmGetNodeType(const char *name)
2912 if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
2913 sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
2914 return DRM_NODE_PRIMARY;
2916 if (strncmp(name, DRM_CONTROL_MINOR_NAME,
2917 sizeof(DRM_CONTROL_MINOR_NAME ) - 1) == 0)
2918 return DRM_NODE_CONTROL;
2920 if (strncmp(name, DRM_RENDER_MINOR_NAME,
2921 sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
2922 return DRM_NODE_RENDER;
2927 static int drmParsePciDeviceInfo(const unsigned char *config,
2928 drmPciDeviceInfoPtr device)
2933 device->vendor_id = config[0] | (config[1] << 8);
2934 device->device_id = config[2] | (config[3] << 8);
2935 device->revision_id = config[8];
2936 device->subvendor_id = config[44] | (config[45] << 8);
2937 device->subdevice_id = config[46] | (config[47] << 8);
2942 static void drmFreeDevice(drmDevicePtr device)
2949 if (device->nodes != NULL)
2950 for (i = 0; i < DRM_NODE_MAX; i++)
2951 free(device->nodes[i]);
2953 free(device->nodes);
2954 free(device->businfo.pci);
2955 free(device->deviceinfo.pci);
2958 void drmFreeDevices(drmDevicePtr devices[], int count)
2962 if (devices == NULL)
2965 for (i = 0; i < count; i++) {
2966 drmFreeDevice(devices[i]);
2973 * Get drm devices on the system
2975 * \param devices the array of devices with drmDevicePtr elements
2976 * can be NULL to get the device number first
2977 * \param max_devices the maximum number of devices for the array
2979 * \return on error - negative error code,
2980 * if devices is NULL - total number of devices available on the system,
2981 * alternatively the number of devices stored in devices[], which is
2982 * capped by the max_devices.
2984 int drmGetDevices(drmDevicePtr devices[], int max_devices)
2986 drmDevicePtr devs = NULL;
2987 drmPciBusInfoPtr pcibus = NULL;
2988 drmPciDeviceInfoPtr pcidevice = NULL;
2990 struct dirent *dent = NULL;
2991 struct stat sbuf = {0};
2992 char node[PATH_MAX + 1] = "";
2993 char path[PATH_MAX + 1] = "";
2994 unsigned char config[64] = "";
2995 int node_type, subsystem_type;
2998 int ret, i = 0, j, node_count, device_count = 0;
3000 int *duplicated = NULL;
3002 devs = calloc(max_count, sizeof(*devs));
3006 sysdir = opendir(DRM_DIR_NAME);
3012 while ((dent = readdir(sysdir))) {
3013 node_type = drmGetNodeType(dent->d_name);
3017 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, dent->d_name);
3018 if (stat(node, &sbuf))
3021 maj = major(sbuf.st_rdev);
3022 min = minor(sbuf.st_rdev);
3024 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
3027 snprintf(path, PATH_MAX, "/sys/dev/char/%d:%d/device/subsystem",
3029 subsystem_type = drmParseSubsystemType(path);
3031 if (subsystem_type < 0)
3034 switch (subsystem_type) {
3036 pcibus = calloc(1, sizeof(*pcibus));
3037 if (pcibus == NULL) {
3042 ret = drmParsePciBusInfo(maj, min, pcibus);
3046 if (i >= max_count) {
3048 devs = realloc(devs, max_count * sizeof(*devs));
3051 devs[i].businfo.pci = pcibus;
3052 devs[i].bustype = subsystem_type;
3053 devs[i].nodes = calloc(DRM_NODE_MAX, sizeof(char *));
3054 if (devs[i].nodes == NULL) {
3058 devs[i].nodes[node_type] = strdup(node);
3059 if (devs[i].nodes[node_type] == NULL) {
3063 devs[i].available_nodes = 1 << node_type;
3065 if (devices != NULL) {
3066 snprintf(path, PATH_MAX, "/sys/class/drm/%s/device/config",
3068 fd = open(path, O_RDONLY);
3073 ret = read(fd, config, 64);
3080 pcidevice = calloc(1, sizeof(*pcidevice));
3081 if (pcidevice == NULL) {
3086 ret = drmParsePciDeviceInfo(config, pcidevice);
3090 devs[i].deviceinfo.pci = pcidevice;
3095 fprintf(stderr, "The subsystem type is not supported yet\n");
3103 /* merge duplicated devices with same domain/bus/device/func IDs */
3104 duplicated = calloc(node_count, sizeof(*duplicated));
3105 if (duplicated == NULL) {
3110 for (i = 0; i < node_count; i++) {
3111 for (j = i+1; j < node_count; j++) {
3112 if (duplicated[i] || duplicated[j])
3114 if (drmSameDevice(&devs[i], &devs[j])) {
3116 devs[i].available_nodes |= devs[j].available_nodes;
3117 node_type = log2(devs[j].available_nodes);
3118 devs[i].nodes[node_type] = devs[j].nodes[node_type];
3119 free(devs[j].nodes);
3120 free(devs[j].businfo.pci);
3121 free(devs[j].deviceinfo.pci);
3126 for (i = 0; i < node_count; i++) {
3127 if(duplicated[i] == 0) {
3128 if ((devices != NULL) && (device_count < max_devices)) {
3129 devices[device_count] = calloc(1, sizeof(drmDevice));
3130 if (devices[device_count] == NULL) {
3134 memcpy(devices[device_count], &devs[i], sizeof(drmDevice));
3136 drmFreeDevice(&devs[i]);
3141 if (i < node_count) {
3142 drmFreeDevices(devices, device_count);
3143 for ( ; i < node_count; i++)
3144 if(duplicated[i] == 0)
3145 drmFreeDevice(&devs[i]);
3155 for (j = 0; j < i; j++)
3156 drmFreeDevice(&devs[j]);
3164 void drmFreeDevices(drmDevicePtr devices[], int count)
3170 int drmGetDevices(drmDevicePtr devices[], int max_devices)
3177 #warning "Missing implementation of drmGetDevices/drmFreeDevices"