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 */
59 /* Not all systems have MAP_FAILED defined */
61 #define MAP_FAILED ((void *)-1)
65 #include "libdrm_macros.h"
68 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
81 #define DRM_MAJOR 226 /* Linux */
85 * This definition needs to be changed on some systems if dev_t is a structure.
86 * If there is a header file we can get it from, there would be best.
89 #define makedev(x,y) ((dev_t)(((x) << 8) | (y)))
92 #define DRM_MSG_VERBOSITY 3
94 #define memclear(s) memset(&s, 0, sizeof(s))
96 static drmServerInfoPtr drm_server_info;
98 void drmSetServerInfo(drmServerInfoPtr info)
100 drm_server_info = info;
104 * Output a message to stderr.
106 * \param format printf() like format string.
109 * This function is a wrapper around vfprintf().
112 static int DRM_PRINTFLIKE(1, 0)
113 drmDebugPrint(const char *format, va_list ap)
115 return vfprintf(stderr, format, ap);
119 drmMsg(const char *format, ...)
123 if (((env = getenv("LIBGL_DEBUG")) && strstr(env, "verbose")) || drm_server_info)
125 va_start(ap, format);
126 if (drm_server_info) {
127 drm_server_info->debug_print(format,ap);
129 drmDebugPrint(format, ap);
135 static void *drmHashTable = NULL; /* Context switch callbacks */
137 void *drmGetHashTable(void)
142 void *drmMalloc(int size)
144 return calloc(1, size);
147 void drmFree(void *pt)
153 * Call ioctl, restarting if it is interupted
156 drmIoctl(int fd, unsigned long request, void *arg)
161 ret = ioctl(fd, request, arg);
162 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
166 static unsigned long drmGetKeyFromFd(int fd)
175 drmHashEntry *drmGetEntry(int fd)
177 unsigned long key = drmGetKeyFromFd(fd);
182 drmHashTable = drmHashCreate();
184 if (drmHashLookup(drmHashTable, key, &value)) {
185 entry = drmMalloc(sizeof(*entry));
188 entry->tagTable = drmHashCreate();
189 drmHashInsert(drmHashTable, key, entry);
197 * Compare two busid strings
202 * \return 1 if matched.
205 * This function compares two bus ID strings. It understands the older
206 * PCI:b:d:f format and the newer pci:oooo:bb:dd.f format. In the format, o is
207 * domain, b is bus, d is device, f is function.
209 static int drmMatchBusID(const char *id1, const char *id2, int pci_domain_ok)
211 /* First, check if the IDs are exactly the same */
212 if (strcasecmp(id1, id2) == 0)
215 /* Try to match old/new-style PCI bus IDs. */
216 if (strncasecmp(id1, "pci", 3) == 0) {
217 unsigned int o1, b1, d1, f1;
218 unsigned int o2, b2, d2, f2;
221 ret = sscanf(id1, "pci:%04x:%02x:%02x.%u", &o1, &b1, &d1, &f1);
224 ret = sscanf(id1, "PCI:%u:%u:%u", &b1, &d1, &f1);
229 ret = sscanf(id2, "pci:%04x:%02x:%02x.%u", &o2, &b2, &d2, &f2);
232 ret = sscanf(id2, "PCI:%u:%u:%u", &b2, &d2, &f2);
237 /* If domains aren't properly supported by the kernel interface,
238 * just ignore them, which sucks less than picking a totally random
239 * card with "open by name"
244 if ((o1 != o2) || (b1 != b2) || (d1 != d2) || (f1 != f2))
253 * Handles error checking for chown call.
255 * \param path to file.
256 * \param id of the new owner.
257 * \param id of the new group.
259 * \return zero if success or -1 if failure.
262 * Checks for failure. If failure was caused by signal call chown again.
263 * If any other failure happened then it will output error mesage using
267 static int chown_check_return(const char *path, uid_t owner, gid_t group)
272 rv = chown(path, owner, group);
273 } while (rv != 0 && errno == EINTR);
278 drmMsg("Failed to change owner or group for file %s! %d: %s\n",
279 path, errno, strerror(errno));
285 * Open the DRM device, creating it if necessary.
287 * \param dev major and minor numbers of the device.
288 * \param minor minor number of the device.
290 * \return a file descriptor on success, or a negative value on error.
293 * Assembles the device name from \p minor and opens it, creating the device
294 * special file node with the major and minor numbers specified by \p dev and
295 * parent directory if necessary and was called by root.
297 static int drmOpenDevice(dev_t dev, int minor, int type)
300 const char *dev_name;
303 mode_t devmode = DRM_DEV_MODE, serv_mode;
306 int isroot = !geteuid();
307 uid_t user = DRM_DEV_UID;
308 gid_t group = DRM_DEV_GID;
312 case DRM_NODE_PRIMARY:
313 dev_name = DRM_DEV_NAME;
315 case DRM_NODE_CONTROL:
316 dev_name = DRM_CONTROL_DEV_NAME;
318 case DRM_NODE_RENDER:
319 dev_name = DRM_RENDER_DEV_NAME;
325 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
326 drmMsg("drmOpenDevice: node name is %s\n", buf);
328 if (drm_server_info) {
329 drm_server_info->get_perms(&serv_group, &serv_mode);
330 devmode = serv_mode ? serv_mode : DRM_DEV_MODE;
331 devmode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
335 if (stat(DRM_DIR_NAME, &st)) {
337 return DRM_ERR_NOT_ROOT;
338 mkdir(DRM_DIR_NAME, DRM_DEV_DIRMODE);
339 chown_check_return(DRM_DIR_NAME, 0, 0); /* root:root */
340 chmod(DRM_DIR_NAME, DRM_DEV_DIRMODE);
343 /* Check if the device node exists and create it if necessary. */
344 if (stat(buf, &st)) {
346 return DRM_ERR_NOT_ROOT;
348 mknod(buf, S_IFCHR | devmode, dev);
351 if (drm_server_info) {
352 group = ((int)serv_group >= 0) ? serv_group : DRM_DEV_GID;
353 chown_check_return(buf, user, group);
357 /* if we modprobed then wait for udev */
361 if (stat(DRM_DIR_NAME, &st)) {
365 if (udev_count == 50)
370 if (stat(buf, &st)) {
374 if (udev_count == 50)
381 fd = open(buf, O_RDWR, 0);
382 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
383 fd, fd < 0 ? strerror(errno) : "OK");
388 /* Check if the device node is not what we expect it to be, and recreate it
389 * and try again if so.
391 if (st.st_rdev != dev) {
393 return DRM_ERR_NOT_ROOT;
395 mknod(buf, S_IFCHR | devmode, dev);
396 if (drm_server_info) {
397 chown_check_return(buf, user, group);
401 fd = open(buf, O_RDWR, 0);
402 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
403 fd, fd < 0 ? strerror(errno) : "OK");
407 drmMsg("drmOpenDevice: Open failed\n");
415 * Open the DRM device
417 * \param minor device minor number.
418 * \param create allow to create the device if set.
420 * \return a file descriptor on success, or a negative value on error.
423 * Calls drmOpenDevice() if \p create is set, otherwise assembles the device
424 * name from \p minor and opens it.
426 static int drmOpenMinor(int minor, int create, int type)
430 const char *dev_name;
433 return drmOpenDevice(makedev(DRM_MAJOR, minor), minor, type);
436 case DRM_NODE_PRIMARY:
437 dev_name = DRM_DEV_NAME;
439 case DRM_NODE_CONTROL:
440 dev_name = DRM_CONTROL_DEV_NAME;
442 case DRM_NODE_RENDER:
443 dev_name = DRM_RENDER_DEV_NAME;
449 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
450 if ((fd = open(buf, O_RDWR, 0)) >= 0)
457 * Determine whether the DRM kernel driver has been loaded.
459 * \return 1 if the DRM driver is loaded, 0 otherwise.
462 * Determine the presence of the kernel driver by attempting to open the 0
463 * minor and get version information. For backward compatibility with older
464 * Linux implementations, /proc/dri is also checked.
466 int drmAvailable(void)
468 drmVersionPtr version;
472 if ((fd = drmOpenMinor(0, 1, DRM_NODE_PRIMARY)) < 0) {
474 /* Try proc for backward Linux compatibility */
475 if (!access("/proc/dri/0", R_OK))
481 if ((version = drmGetVersion(fd))) {
483 drmFreeVersion(version);
490 static int drmGetMinorBase(int type)
493 case DRM_NODE_PRIMARY:
495 case DRM_NODE_CONTROL:
497 case DRM_NODE_RENDER:
504 static int drmGetMinorType(int minor)
506 int type = minor >> 6;
512 case DRM_NODE_PRIMARY:
513 case DRM_NODE_CONTROL:
514 case DRM_NODE_RENDER:
521 static const char *drmGetMinorName(int type)
524 case DRM_NODE_PRIMARY:
526 case DRM_NODE_CONTROL:
528 case DRM_NODE_RENDER:
536 * Open the device by bus ID.
538 * \param busid bus ID.
539 * \param type device node type.
541 * \return a file descriptor on success, or a negative value on error.
544 * This function attempts to open every possible minor (up to DRM_MAX_MINOR),
545 * comparing the device bus ID with the one supplied.
547 * \sa drmOpenMinor() and drmGetBusid().
549 static int drmOpenByBusid(const char *busid, int type)
551 int i, pci_domain_ok = 1;
555 int base = drmGetMinorBase(type);
560 drmMsg("drmOpenByBusid: Searching for BusID %s\n", busid);
561 for (i = base; i < base + DRM_MAX_MINOR; i++) {
562 fd = drmOpenMinor(i, 1, type);
563 drmMsg("drmOpenByBusid: drmOpenMinor returns %d\n", fd);
565 /* We need to try for 1.4 first for proper PCI domain support
566 * and if that fails, we know the kernel is busted
570 sv.drm_dd_major = -1; /* Don't care */
571 sv.drm_dd_minor = -1; /* Don't care */
572 if (drmSetInterfaceVersion(fd, &sv)) {
578 sv.drm_dd_major = -1; /* Don't care */
579 sv.drm_dd_minor = -1; /* Don't care */
580 drmMsg("drmOpenByBusid: Interface 1.4 failed, trying 1.1\n");
581 drmSetInterfaceVersion(fd, &sv);
583 buf = drmGetBusid(fd);
584 drmMsg("drmOpenByBusid: drmGetBusid reports %s\n", buf);
585 if (buf && drmMatchBusID(buf, busid, pci_domain_ok)) {
599 * Open the device by name.
601 * \param name driver name.
602 * \param type the device node type.
604 * \return a file descriptor on success, or a negative value on error.
607 * This function opens the first minor number that matches the driver name and
608 * isn't already in use. If it's in use it then it will already have a bus ID
611 * \sa drmOpenMinor(), drmGetVersion() and drmGetBusid().
613 static int drmOpenByName(const char *name, int type)
617 drmVersionPtr version;
619 int base = drmGetMinorBase(type);
625 * Open the first minor number that matches the driver name and isn't
626 * already in use. If it's in use it will have a busid assigned already.
628 for (i = base; i < base + DRM_MAX_MINOR; i++) {
629 if ((fd = drmOpenMinor(i, 1, type)) >= 0) {
630 if ((version = drmGetVersion(fd))) {
631 if (!strcmp(version->name, name)) {
632 drmFreeVersion(version);
633 id = drmGetBusid(fd);
634 drmMsg("drmGetBusid returned '%s'\n", id ? id : "NULL");
643 drmFreeVersion(version);
651 /* Backward-compatibility /proc support */
652 for (i = 0; i < 8; i++) {
653 char proc_name[64], buf[512];
654 char *driver, *pt, *devstring;
657 sprintf(proc_name, "/proc/dri/%d/name", i);
658 if ((fd = open(proc_name, 0, 0)) >= 0) {
659 retcode = read(fd, buf, sizeof(buf)-1);
662 buf[retcode-1] = '\0';
663 for (driver = pt = buf; *pt && *pt != ' '; ++pt)
665 if (*pt) { /* Device is next */
667 if (!strcmp(driver, name)) { /* Match */
668 for (devstring = ++pt; *pt && *pt != ' '; ++pt)
670 if (*pt) { /* Found busid */
671 return drmOpenByBusid(++pt, type);
672 } else { /* No busid */
673 return drmOpenDevice(strtol(devstring, NULL, 0),i, type);
687 * Open the DRM device.
689 * Looks up the specified name and bus ID, and opens the device found. The
690 * entry in /dev/dri is created if necessary and if called by root.
692 * \param name driver name. Not referenced if bus ID is supplied.
693 * \param busid bus ID. Zero if not known.
695 * \return a file descriptor on success, or a negative value on error.
698 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
701 int drmOpen(const char *name, const char *busid)
703 return drmOpenWithType(name, busid, DRM_NODE_PRIMARY);
707 * Open the DRM device with specified type.
709 * Looks up the specified name and bus ID, and opens the device found. The
710 * entry in /dev/dri is created if necessary and if called by root.
712 * \param name driver name. Not referenced if bus ID is supplied.
713 * \param busid bus ID. Zero if not known.
714 * \param type the device node type to open, PRIMARY, CONTROL or RENDER
716 * \return a file descriptor on success, or a negative value on error.
719 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
722 int drmOpenWithType(const char *name, const char *busid, int type)
724 if (!drmAvailable() && name != NULL && drm_server_info) {
725 /* try to load the kernel module */
726 if (!drm_server_info->load_module(name)) {
727 drmMsg("[drm] failed to load kernel module \"%s\"\n", name);
733 int fd = drmOpenByBusid(busid, type);
739 return drmOpenByName(name, type);
744 int drmOpenControl(int minor)
746 return drmOpenMinor(minor, 0, DRM_NODE_CONTROL);
749 int drmOpenRender(int minor)
751 return drmOpenMinor(minor, 0, DRM_NODE_RENDER);
755 * Free the version information returned by drmGetVersion().
757 * \param v pointer to the version information.
760 * It frees the memory pointed by \p %v as well as all the non-null strings
763 void drmFreeVersion(drmVersionPtr v)
775 * Free the non-public version information returned by the kernel.
777 * \param v pointer to the version information.
780 * Used by drmGetVersion() to free the memory pointed by \p %v as well as all
781 * the non-null strings pointers in it.
783 static void drmFreeKernelVersion(drm_version_t *v)
795 * Copy version information.
797 * \param d destination pointer.
798 * \param s source pointer.
801 * Used by drmGetVersion() to translate the information returned by the ioctl
802 * interface in a private structure into the public structure counterpart.
804 static void drmCopyVersion(drmVersionPtr d, const drm_version_t *s)
806 d->version_major = s->version_major;
807 d->version_minor = s->version_minor;
808 d->version_patchlevel = s->version_patchlevel;
809 d->name_len = s->name_len;
810 d->name = strdup(s->name);
811 d->date_len = s->date_len;
812 d->date = strdup(s->date);
813 d->desc_len = s->desc_len;
814 d->desc = strdup(s->desc);
819 * Query the driver version information.
821 * \param fd file descriptor.
823 * \return pointer to a drmVersion structure which should be freed with
826 * \note Similar information is available via /proc/dri.
829 * It gets the version information via successive DRM_IOCTL_VERSION ioctls,
830 * first with zeros to get the string lengths, and then the actually strings.
831 * It also null-terminates them since they might not be already.
833 drmVersionPtr drmGetVersion(int fd)
835 drmVersionPtr retval;
836 drm_version_t *version = drmMalloc(sizeof(*version));
840 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
841 drmFreeKernelVersion(version);
845 if (version->name_len)
846 version->name = drmMalloc(version->name_len + 1);
847 if (version->date_len)
848 version->date = drmMalloc(version->date_len + 1);
849 if (version->desc_len)
850 version->desc = drmMalloc(version->desc_len + 1);
852 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
853 drmMsg("DRM_IOCTL_VERSION: %s\n", strerror(errno));
854 drmFreeKernelVersion(version);
858 /* The results might not be null-terminated strings, so terminate them. */
859 if (version->name_len) version->name[version->name_len] = '\0';
860 if (version->date_len) version->date[version->date_len] = '\0';
861 if (version->desc_len) version->desc[version->desc_len] = '\0';
863 retval = drmMalloc(sizeof(*retval));
864 drmCopyVersion(retval, version);
865 drmFreeKernelVersion(version);
871 * Get version information for the DRM user space library.
873 * This version number is driver independent.
875 * \param fd file descriptor.
877 * \return version information.
880 * This function allocates and fills a drm_version structure with a hard coded
883 drmVersionPtr drmGetLibVersion(int fd)
885 drm_version_t *version = drmMalloc(sizeof(*version));
888 * NOTE THIS MUST NOT GO ABOVE VERSION 1.X due to drivers needing it
889 * revision 1.0.x = original DRM interface with no drmGetLibVersion
890 * entry point and many drm<Device> extensions
891 * revision 1.1.x = added drmCommand entry points for device extensions
892 * added drmGetLibVersion to identify libdrm.a version
893 * revision 1.2.x = added drmSetInterfaceVersion
894 * modified drmOpen to handle both busid and name
895 * revision 1.3.x = added server + memory manager
897 version->version_major = 1;
898 version->version_minor = 3;
899 version->version_patchlevel = 0;
901 return (drmVersionPtr)version;
904 int drmGetCap(int fd, uint64_t capability, uint64_t *value)
906 struct drm_get_cap cap;
910 cap.capability = capability;
912 ret = drmIoctl(fd, DRM_IOCTL_GET_CAP, &cap);
920 int drmSetClientCap(int fd, uint64_t capability, uint64_t value)
922 struct drm_set_client_cap cap;
925 cap.capability = capability;
928 return drmIoctl(fd, DRM_IOCTL_SET_CLIENT_CAP, &cap);
932 * Free the bus ID information.
934 * \param busid bus ID information string as given by drmGetBusid().
937 * This function is just frees the memory pointed by \p busid.
939 void drmFreeBusid(const char *busid)
941 drmFree((void *)busid);
946 * Get the bus ID of the device.
948 * \param fd file descriptor.
950 * \return bus ID string.
953 * This function gets the bus ID via successive DRM_IOCTL_GET_UNIQUE ioctls to
954 * get the string length and data, passing the arguments in a drm_unique
957 char *drmGetBusid(int fd)
963 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
965 u.unique = drmMalloc(u.unique_len + 1);
966 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
968 u.unique[u.unique_len] = '\0';
975 * Set the bus ID of the device.
977 * \param fd file descriptor.
978 * \param busid bus ID string.
980 * \return zero on success, negative on failure.
983 * This function is a wrapper around the DRM_IOCTL_SET_UNIQUE ioctl, passing
984 * the arguments in a drm_unique structure.
986 int drmSetBusid(int fd, const char *busid)
991 u.unique = (char *)busid;
992 u.unique_len = strlen(busid);
994 if (drmIoctl(fd, DRM_IOCTL_SET_UNIQUE, &u)) {
1000 int drmGetMagic(int fd, drm_magic_t * magic)
1007 if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
1009 *magic = auth.magic;
1013 int drmAuthMagic(int fd, drm_magic_t magic)
1019 if (drmIoctl(fd, DRM_IOCTL_AUTH_MAGIC, &auth))
1025 * Specifies a range of memory that is available for mapping by a
1028 * \param fd file descriptor.
1029 * \param offset usually the physical address. The actual meaning depends of
1030 * the \p type parameter. See below.
1031 * \param size of the memory in bytes.
1032 * \param type type of the memory to be mapped.
1033 * \param flags combination of several flags to modify the function actions.
1034 * \param handle will be set to a value that may be used as the offset
1035 * parameter for mmap().
1037 * \return zero on success or a negative value on error.
1039 * \par Mapping the frame buffer
1040 * For the frame buffer
1041 * - \p offset will be the physical address of the start of the frame buffer,
1042 * - \p size will be the size of the frame buffer in bytes, and
1043 * - \p type will be DRM_FRAME_BUFFER.
1046 * The area mapped will be uncached. If MTRR support is available in the
1047 * kernel, the frame buffer area will be set to write combining.
1049 * \par Mapping the MMIO register area
1050 * For the MMIO register area,
1051 * - \p offset will be the physical address of the start of the register area,
1052 * - \p size will be the size of the register area bytes, and
1053 * - \p type will be DRM_REGISTERS.
1055 * The area mapped will be uncached.
1057 * \par Mapping the SAREA
1059 * - \p offset will be ignored and should be set to zero,
1060 * - \p size will be the desired size of the SAREA in bytes,
1061 * - \p type will be DRM_SHM.
1064 * A shared memory area of the requested size will be created and locked in
1065 * kernel memory. This area may be mapped into client-space by using the handle
1068 * \note May only be called by root.
1071 * This function is a wrapper around the DRM_IOCTL_ADD_MAP ioctl, passing
1072 * the arguments in a drm_map structure.
1074 int drmAddMap(int fd, drm_handle_t offset, drmSize size, drmMapType type,
1075 drmMapFlags flags, drm_handle_t *handle)
1080 map.offset = offset;
1084 if (drmIoctl(fd, DRM_IOCTL_ADD_MAP, &map))
1087 *handle = (drm_handle_t)(uintptr_t)map.handle;
1091 int drmRmMap(int fd, drm_handle_t handle)
1096 map.handle = (void *)(uintptr_t)handle;
1098 if(drmIoctl(fd, DRM_IOCTL_RM_MAP, &map))
1104 * Make buffers available for DMA transfers.
1106 * \param fd file descriptor.
1107 * \param count number of buffers.
1108 * \param size size of each buffer.
1109 * \param flags buffer allocation flags.
1110 * \param agp_offset offset in the AGP aperture
1112 * \return number of buffers allocated, negative on error.
1115 * This function is a wrapper around DRM_IOCTL_ADD_BUFS ioctl.
1119 int drmAddBufs(int fd, int count, int size, drmBufDescFlags flags,
1122 drm_buf_desc_t request;
1125 request.count = count;
1126 request.size = size;
1127 request.flags = flags;
1128 request.agp_start = agp_offset;
1130 if (drmIoctl(fd, DRM_IOCTL_ADD_BUFS, &request))
1132 return request.count;
1135 int drmMarkBufs(int fd, double low, double high)
1137 drm_buf_info_t info;
1142 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1148 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1151 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1152 int retval = -errno;
1157 for (i = 0; i < info.count; i++) {
1158 info.list[i].low_mark = low * info.list[i].count;
1159 info.list[i].high_mark = high * info.list[i].count;
1160 if (drmIoctl(fd, DRM_IOCTL_MARK_BUFS, &info.list[i])) {
1161 int retval = -errno;
1174 * \param fd file descriptor.
1175 * \param count number of buffers to free.
1176 * \param list list of buffers to be freed.
1178 * \return zero on success, or a negative value on failure.
1180 * \note This function is primarily used for debugging.
1183 * This function is a wrapper around the DRM_IOCTL_FREE_BUFS ioctl, passing
1184 * the arguments in a drm_buf_free structure.
1186 int drmFreeBufs(int fd, int count, int *list)
1188 drm_buf_free_t request;
1191 request.count = count;
1192 request.list = list;
1193 if (drmIoctl(fd, DRM_IOCTL_FREE_BUFS, &request))
1202 * \param fd file descriptor.
1205 * This function closes the file descriptor.
1207 int drmClose(int fd)
1209 unsigned long key = drmGetKeyFromFd(fd);
1210 drmHashEntry *entry = drmGetEntry(fd);
1212 drmHashDestroy(entry->tagTable);
1215 entry->tagTable = NULL;
1217 drmHashDelete(drmHashTable, key);
1225 * Map a region of memory.
1227 * \param fd file descriptor.
1228 * \param handle handle returned by drmAddMap().
1229 * \param size size in bytes. Must match the size used by drmAddMap().
1230 * \param address will contain the user-space virtual address where the mapping
1233 * \return zero on success, or a negative value on failure.
1236 * This function is a wrapper for mmap().
1238 int drmMap(int fd, drm_handle_t handle, drmSize size, drmAddressPtr address)
1240 static unsigned long pagesize_mask = 0;
1246 pagesize_mask = getpagesize() - 1;
1248 size = (size + pagesize_mask) & ~pagesize_mask;
1250 *address = drm_mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1251 if (*address == MAP_FAILED)
1258 * Unmap mappings obtained with drmMap().
1260 * \param address address as given by drmMap().
1261 * \param size size in bytes. Must match the size used by drmMap().
1263 * \return zero on success, or a negative value on failure.
1266 * This function is a wrapper for munmap().
1268 int drmUnmap(drmAddress address, drmSize size)
1270 return drm_munmap(address, size);
1273 drmBufInfoPtr drmGetBufInfo(int fd)
1275 drm_buf_info_t info;
1276 drmBufInfoPtr retval;
1281 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1285 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1288 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1293 retval = drmMalloc(sizeof(*retval));
1294 retval->count = info.count;
1295 retval->list = drmMalloc(info.count * sizeof(*retval->list));
1296 for (i = 0; i < info.count; i++) {
1297 retval->list[i].count = info.list[i].count;
1298 retval->list[i].size = info.list[i].size;
1299 retval->list[i].low_mark = info.list[i].low_mark;
1300 retval->list[i].high_mark = info.list[i].high_mark;
1309 * Map all DMA buffers into client-virtual space.
1311 * \param fd file descriptor.
1313 * \return a pointer to a ::drmBufMap structure.
1315 * \note The client may not use these buffers until obtaining buffer indices
1319 * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1320 * information about the buffers in a drm_buf_map structure into the
1321 * client-visible data structures.
1323 drmBufMapPtr drmMapBufs(int fd)
1326 drmBufMapPtr retval;
1330 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1336 if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1339 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1344 retval = drmMalloc(sizeof(*retval));
1345 retval->count = bufs.count;
1346 retval->list = drmMalloc(bufs.count * sizeof(*retval->list));
1347 for (i = 0; i < bufs.count; i++) {
1348 retval->list[i].idx = bufs.list[i].idx;
1349 retval->list[i].total = bufs.list[i].total;
1350 retval->list[i].used = 0;
1351 retval->list[i].address = bufs.list[i].address;
1361 * Unmap buffers allocated with drmMapBufs().
1363 * \return zero on success, or negative value on failure.
1366 * Calls munmap() for every buffer stored in \p bufs and frees the
1367 * memory allocated by drmMapBufs().
1369 int drmUnmapBufs(drmBufMapPtr bufs)
1373 for (i = 0; i < bufs->count; i++) {
1374 drm_munmap(bufs->list[i].address, bufs->list[i].total);
1377 drmFree(bufs->list);
1384 #define DRM_DMA_RETRY 16
1387 * Reserve DMA buffers.
1389 * \param fd file descriptor.
1392 * \return zero on success, or a negative value on failure.
1395 * Assemble the arguments into a drm_dma structure and keeps issuing the
1396 * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1398 int drmDMA(int fd, drmDMAReqPtr request)
1403 dma.context = request->context;
1404 dma.send_count = request->send_count;
1405 dma.send_indices = request->send_list;
1406 dma.send_sizes = request->send_sizes;
1407 dma.flags = request->flags;
1408 dma.request_count = request->request_count;
1409 dma.request_size = request->request_size;
1410 dma.request_indices = request->request_list;
1411 dma.request_sizes = request->request_sizes;
1412 dma.granted_count = 0;
1415 ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1416 } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1419 request->granted_count = dma.granted_count;
1428 * Obtain heavyweight hardware lock.
1430 * \param fd file descriptor.
1431 * \param context context.
1432 * \param flags flags that determine the sate of the hardware when the function
1435 * \return always zero.
1438 * This function translates the arguments into a drm_lock structure and issue
1439 * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1441 int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
1446 lock.context = context;
1448 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
1449 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
1450 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
1451 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
1452 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
1453 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
1455 while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
1461 * Release the hardware lock.
1463 * \param fd file descriptor.
1464 * \param context context.
1466 * \return zero on success, or a negative value on failure.
1469 * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
1470 * argument in a drm_lock structure.
1472 int drmUnlock(int fd, drm_context_t context)
1477 lock.context = context;
1478 return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
1481 drm_context_t *drmGetReservedContextList(int fd, int *count)
1485 drm_context_t * retval;
1489 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1495 if (!(list = drmMalloc(res.count * sizeof(*list))))
1497 if (!(retval = drmMalloc(res.count * sizeof(*retval)))) {
1502 res.contexts = list;
1503 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1506 for (i = 0; i < res.count; i++)
1507 retval[i] = list[i].handle;
1514 void drmFreeReservedContextList(drm_context_t *pt)
1522 * Used by the X server during GLXContext initialization. This causes
1523 * per-context kernel-level resources to be allocated.
1525 * \param fd file descriptor.
1526 * \param handle is set on success. To be used by the client when requesting DMA
1527 * dispatch with drmDMA().
1529 * \return zero on success, or a negative value on failure.
1531 * \note May only be called by root.
1534 * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
1535 * argument in a drm_ctx structure.
1537 int drmCreateContext(int fd, drm_context_t *handle)
1542 if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
1544 *handle = ctx.handle;
1548 int drmSwitchToContext(int fd, drm_context_t context)
1553 ctx.handle = context;
1554 if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
1559 int drmSetContextFlags(int fd, drm_context_t context, drm_context_tFlags flags)
1564 * Context preserving means that no context switches are done between DMA
1565 * buffers from one context and the next. This is suitable for use in the
1566 * X server (which promises to maintain hardware context), or in the
1567 * client-side library when buffers are swapped on behalf of two threads.
1570 ctx.handle = context;
1571 if (flags & DRM_CONTEXT_PRESERVED)
1572 ctx.flags |= _DRM_CONTEXT_PRESERVED;
1573 if (flags & DRM_CONTEXT_2DONLY)
1574 ctx.flags |= _DRM_CONTEXT_2DONLY;
1575 if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
1580 int drmGetContextFlags(int fd, drm_context_t context,
1581 drm_context_tFlagsPtr flags)
1586 ctx.handle = context;
1587 if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
1590 if (ctx.flags & _DRM_CONTEXT_PRESERVED)
1591 *flags |= DRM_CONTEXT_PRESERVED;
1592 if (ctx.flags & _DRM_CONTEXT_2DONLY)
1593 *flags |= DRM_CONTEXT_2DONLY;
1600 * Free any kernel-level resources allocated with drmCreateContext() associated
1603 * \param fd file descriptor.
1604 * \param handle handle given by drmCreateContext().
1606 * \return zero on success, or a negative value on failure.
1608 * \note May only be called by root.
1611 * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
1612 * argument in a drm_ctx structure.
1614 int drmDestroyContext(int fd, drm_context_t handle)
1619 ctx.handle = handle;
1620 if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
1625 int drmCreateDrawable(int fd, drm_drawable_t *handle)
1630 if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
1632 *handle = draw.handle;
1636 int drmDestroyDrawable(int fd, drm_drawable_t handle)
1641 draw.handle = handle;
1642 if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
1647 int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
1648 drm_drawable_info_type_t type, unsigned int num,
1651 drm_update_draw_t update;
1654 update.handle = handle;
1657 update.data = (unsigned long long)(unsigned long)data;
1659 if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
1666 * Acquire the AGP device.
1668 * Must be called before any of the other AGP related calls.
1670 * \param fd file descriptor.
1672 * \return zero on success, or a negative value on failure.
1675 * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
1677 int drmAgpAcquire(int fd)
1679 if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
1686 * Release the AGP device.
1688 * \param fd file descriptor.
1690 * \return zero on success, or a negative value on failure.
1693 * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
1695 int drmAgpRelease(int fd)
1697 if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
1706 * \param fd file descriptor.
1707 * \param mode AGP mode.
1709 * \return zero on success, or a negative value on failure.
1712 * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
1713 * argument in a drm_agp_mode structure.
1715 int drmAgpEnable(int fd, unsigned long mode)
1721 if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
1728 * Allocate a chunk of AGP memory.
1730 * \param fd file descriptor.
1731 * \param size requested memory size in bytes. Will be rounded to page boundary.
1732 * \param type type of memory to allocate.
1733 * \param address if not zero, will be set to the physical address of the
1735 * \param handle on success will be set to a handle of the allocated memory.
1737 * \return zero on success, or a negative value on failure.
1740 * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
1741 * arguments in a drm_agp_buffer structure.
1743 int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
1744 unsigned long *address, drm_handle_t *handle)
1749 *handle = DRM_AGP_NO_HANDLE;
1752 if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
1755 *address = b.physical;
1762 * Free a chunk of AGP memory.
1764 * \param fd file descriptor.
1765 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1767 * \return zero on success, or a negative value on failure.
1770 * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
1771 * argument in a drm_agp_buffer structure.
1773 int drmAgpFree(int fd, drm_handle_t handle)
1779 if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
1786 * Bind a chunk of AGP memory.
1788 * \param fd file descriptor.
1789 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1790 * \param offset offset in bytes. It will round to page boundary.
1792 * \return zero on success, or a negative value on failure.
1795 * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
1796 * argument in a drm_agp_binding structure.
1798 int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
1800 drm_agp_binding_t b;
1805 if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
1812 * Unbind a chunk of AGP memory.
1814 * \param fd file descriptor.
1815 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
1817 * \return zero on success, or a negative value on failure.
1820 * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
1821 * the argument in a drm_agp_binding structure.
1823 int drmAgpUnbind(int fd, drm_handle_t handle)
1825 drm_agp_binding_t b;
1829 if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
1836 * Get AGP driver major version number.
1838 * \param fd file descriptor.
1840 * \return major version number on success, or a negative value on failure..
1843 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1844 * necessary information in a drm_agp_info structure.
1846 int drmAgpVersionMajor(int fd)
1852 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1854 return i.agp_version_major;
1859 * Get AGP driver minor version number.
1861 * \param fd file descriptor.
1863 * \return minor version number on success, or a negative value on failure.
1866 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1867 * necessary information in a drm_agp_info structure.
1869 int drmAgpVersionMinor(int fd)
1875 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1877 return i.agp_version_minor;
1884 * \param fd file descriptor.
1886 * \return mode on success, or zero on failure.
1889 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1890 * necessary information in a drm_agp_info structure.
1892 unsigned long drmAgpGetMode(int fd)
1898 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1905 * Get AGP aperture base.
1907 * \param fd file descriptor.
1909 * \return aperture base on success, zero on failure.
1912 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1913 * necessary information in a drm_agp_info structure.
1915 unsigned long drmAgpBase(int fd)
1921 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1923 return i.aperture_base;
1928 * Get AGP aperture size.
1930 * \param fd file descriptor.
1932 * \return aperture size on success, zero on failure.
1935 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1936 * necessary information in a drm_agp_info structure.
1938 unsigned long drmAgpSize(int fd)
1944 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1946 return i.aperture_size;
1951 * Get used AGP memory.
1953 * \param fd file descriptor.
1955 * \return memory used on success, or zero on failure.
1958 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1959 * necessary information in a drm_agp_info structure.
1961 unsigned long drmAgpMemoryUsed(int fd)
1967 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1969 return i.memory_used;
1974 * Get available AGP memory.
1976 * \param fd file descriptor.
1978 * \return memory available on success, or zero on failure.
1981 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
1982 * necessary information in a drm_agp_info structure.
1984 unsigned long drmAgpMemoryAvail(int fd)
1990 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
1992 return i.memory_allowed;
1997 * Get hardware vendor ID.
1999 * \param fd file descriptor.
2001 * \return vendor ID on success, or zero on failure.
2004 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2005 * necessary information in a drm_agp_info structure.
2007 unsigned int drmAgpVendorId(int fd)
2013 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2020 * Get hardware device ID.
2022 * \param fd file descriptor.
2024 * \return zero on success, or zero on failure.
2027 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2028 * necessary information in a drm_agp_info structure.
2030 unsigned int drmAgpDeviceId(int fd)
2036 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2041 int drmScatterGatherAlloc(int fd, unsigned long size, drm_handle_t *handle)
2043 drm_scatter_gather_t sg;
2049 if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
2051 *handle = sg.handle;
2055 int drmScatterGatherFree(int fd, drm_handle_t handle)
2057 drm_scatter_gather_t sg;
2061 if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
2069 * \param fd file descriptor.
2070 * \param vbl pointer to a drmVBlank structure.
2072 * \return zero on success, or a negative value on failure.
2075 * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
2077 int drmWaitVBlank(int fd, drmVBlankPtr vbl)
2079 struct timespec timeout, cur;
2082 ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2084 fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
2090 ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
2091 vbl->request.type &= ~DRM_VBLANK_RELATIVE;
2092 if (ret && errno == EINTR) {
2093 clock_gettime(CLOCK_MONOTONIC, &cur);
2094 /* Timeout after 1s */
2095 if (cur.tv_sec > timeout.tv_sec + 1 ||
2096 (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
2103 } while (ret && errno == EINTR);
2109 int drmError(int err, const char *label)
2112 case DRM_ERR_NO_DEVICE:
2113 fprintf(stderr, "%s: no device\n", label);
2115 case DRM_ERR_NO_ACCESS:
2116 fprintf(stderr, "%s: no access\n", label);
2118 case DRM_ERR_NOT_ROOT:
2119 fprintf(stderr, "%s: not root\n", label);
2121 case DRM_ERR_INVALID:
2122 fprintf(stderr, "%s: invalid args\n", label);
2127 fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2135 * Install IRQ handler.
2137 * \param fd file descriptor.
2138 * \param irq IRQ number.
2140 * \return zero on success, or a negative value on failure.
2143 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2144 * argument in a drm_control structure.
2146 int drmCtlInstHandler(int fd, int irq)
2151 ctl.func = DRM_INST_HANDLER;
2153 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2160 * Uninstall IRQ handler.
2162 * \param fd file descriptor.
2164 * \return zero on success, or a negative value on failure.
2167 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2168 * argument in a drm_control structure.
2170 int drmCtlUninstHandler(int fd)
2175 ctl.func = DRM_UNINST_HANDLER;
2177 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2182 int drmFinish(int fd, int context, drmLockFlags flags)
2187 lock.context = context;
2188 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
2189 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
2190 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
2191 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
2192 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2193 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2194 if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2200 * Get IRQ from bus ID.
2202 * \param fd file descriptor.
2203 * \param busnum bus number.
2204 * \param devnum device number.
2205 * \param funcnum function number.
2207 * \return IRQ number on success, or a negative value on failure.
2210 * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2211 * arguments in a drm_irq_busid structure.
2213 int drmGetInterruptFromBusID(int fd, int busnum, int devnum, int funcnum)
2220 p.funcnum = funcnum;
2221 if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2226 int drmAddContextTag(int fd, drm_context_t context, void *tag)
2228 drmHashEntry *entry = drmGetEntry(fd);
2230 if (drmHashInsert(entry->tagTable, context, tag)) {
2231 drmHashDelete(entry->tagTable, context);
2232 drmHashInsert(entry->tagTable, context, tag);
2237 int drmDelContextTag(int fd, drm_context_t context)
2239 drmHashEntry *entry = drmGetEntry(fd);
2241 return drmHashDelete(entry->tagTable, context);
2244 void *drmGetContextTag(int fd, drm_context_t context)
2246 drmHashEntry *entry = drmGetEntry(fd);
2249 if (drmHashLookup(entry->tagTable, context, &value))
2255 int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2256 drm_handle_t handle)
2258 drm_ctx_priv_map_t map;
2261 map.ctx_id = ctx_id;
2262 map.handle = (void *)(uintptr_t)handle;
2264 if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2269 int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2270 drm_handle_t *handle)
2272 drm_ctx_priv_map_t map;
2275 map.ctx_id = ctx_id;
2277 if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2280 *handle = (drm_handle_t)(uintptr_t)map.handle;
2285 int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2286 drmMapType *type, drmMapFlags *flags, drm_handle_t *handle,
2293 if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2295 *offset = map.offset;
2299 *handle = (unsigned long)map.handle;
2304 int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2305 unsigned long *magic, unsigned long *iocs)
2307 drm_client_t client;
2311 if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2313 *auth = client.auth;
2316 *magic = client.magic;
2317 *iocs = client.iocs;
2321 int drmGetStats(int fd, drmStatsT *stats)
2327 if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2331 memset(stats, 0, sizeof(*stats));
2332 if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2336 stats->data[i].long_format = "%-20.20s"; \
2337 stats->data[i].rate_format = "%8.8s"; \
2338 stats->data[i].isvalue = 1; \
2339 stats->data[i].verbose = 0
2342 stats->data[i].long_format = "%-20.20s"; \
2343 stats->data[i].rate_format = "%5.5s"; \
2344 stats->data[i].isvalue = 0; \
2345 stats->data[i].mult_names = "kgm"; \
2346 stats->data[i].mult = 1000; \
2347 stats->data[i].verbose = 0
2350 stats->data[i].long_format = "%-20.20s"; \
2351 stats->data[i].rate_format = "%5.5s"; \
2352 stats->data[i].isvalue = 0; \
2353 stats->data[i].mult_names = "KGM"; \
2354 stats->data[i].mult = 1024; \
2355 stats->data[i].verbose = 0
2358 stats->count = s.count;
2359 for (i = 0; i < s.count; i++) {
2360 stats->data[i].value = s.data[i].value;
2361 switch (s.data[i].type) {
2362 case _DRM_STAT_LOCK:
2363 stats->data[i].long_name = "Lock";
2364 stats->data[i].rate_name = "Lock";
2367 case _DRM_STAT_OPENS:
2368 stats->data[i].long_name = "Opens";
2369 stats->data[i].rate_name = "O";
2371 stats->data[i].verbose = 1;
2373 case _DRM_STAT_CLOSES:
2374 stats->data[i].long_name = "Closes";
2375 stats->data[i].rate_name = "Lock";
2377 stats->data[i].verbose = 1;
2379 case _DRM_STAT_IOCTLS:
2380 stats->data[i].long_name = "Ioctls";
2381 stats->data[i].rate_name = "Ioc/s";
2384 case _DRM_STAT_LOCKS:
2385 stats->data[i].long_name = "Locks";
2386 stats->data[i].rate_name = "Lck/s";
2389 case _DRM_STAT_UNLOCKS:
2390 stats->data[i].long_name = "Unlocks";
2391 stats->data[i].rate_name = "Unl/s";
2395 stats->data[i].long_name = "IRQs";
2396 stats->data[i].rate_name = "IRQ/s";
2399 case _DRM_STAT_PRIMARY:
2400 stats->data[i].long_name = "Primary Bytes";
2401 stats->data[i].rate_name = "PB/s";
2404 case _DRM_STAT_SECONDARY:
2405 stats->data[i].long_name = "Secondary Bytes";
2406 stats->data[i].rate_name = "SB/s";
2410 stats->data[i].long_name = "DMA";
2411 stats->data[i].rate_name = "DMA/s";
2414 case _DRM_STAT_SPECIAL:
2415 stats->data[i].long_name = "Special DMA";
2416 stats->data[i].rate_name = "dma/s";
2419 case _DRM_STAT_MISSED:
2420 stats->data[i].long_name = "Miss";
2421 stats->data[i].rate_name = "Ms/s";
2424 case _DRM_STAT_VALUE:
2425 stats->data[i].long_name = "Value";
2426 stats->data[i].rate_name = "Value";
2429 case _DRM_STAT_BYTE:
2430 stats->data[i].long_name = "Bytes";
2431 stats->data[i].rate_name = "B/s";
2434 case _DRM_STAT_COUNT:
2436 stats->data[i].long_name = "Count";
2437 stats->data[i].rate_name = "Cnt/s";
2446 * Issue a set-version ioctl.
2448 * \param fd file descriptor.
2449 * \param drmCommandIndex command index
2450 * \param data source pointer of the data to be read and written.
2451 * \param size size of the data to be read and written.
2453 * \return zero on success, or a negative value on failure.
2456 * It issues a read-write ioctl given by
2457 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2459 int drmSetInterfaceVersion(int fd, drmSetVersion *version)
2462 drm_set_version_t sv;
2465 sv.drm_di_major = version->drm_di_major;
2466 sv.drm_di_minor = version->drm_di_minor;
2467 sv.drm_dd_major = version->drm_dd_major;
2468 sv.drm_dd_minor = version->drm_dd_minor;
2470 if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
2474 version->drm_di_major = sv.drm_di_major;
2475 version->drm_di_minor = sv.drm_di_minor;
2476 version->drm_dd_major = sv.drm_dd_major;
2477 version->drm_dd_minor = sv.drm_dd_minor;
2483 * Send a device-specific command.
2485 * \param fd file descriptor.
2486 * \param drmCommandIndex command index
2488 * \return zero on success, or a negative value on failure.
2491 * It issues a ioctl given by
2492 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2494 int drmCommandNone(int fd, unsigned long drmCommandIndex)
2496 unsigned long request;
2498 request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
2500 if (drmIoctl(fd, request, NULL)) {
2508 * Send a device-specific read command.
2510 * \param fd file descriptor.
2511 * \param drmCommandIndex command index
2512 * \param data destination pointer of the data to be read.
2513 * \param size size of the data to be read.
2515 * \return zero on success, or a negative value on failure.
2518 * It issues a read ioctl given by
2519 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2521 int drmCommandRead(int fd, unsigned long drmCommandIndex, void *data,
2524 unsigned long request;
2526 request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
2527 DRM_COMMAND_BASE + drmCommandIndex, size);
2529 if (drmIoctl(fd, request, data)) {
2537 * Send a device-specific write command.
2539 * \param fd file descriptor.
2540 * \param drmCommandIndex command index
2541 * \param data source pointer of the data to be written.
2542 * \param size size of the data to be written.
2544 * \return zero on success, or a negative value on failure.
2547 * It issues a write ioctl given by
2548 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2550 int drmCommandWrite(int fd, unsigned long drmCommandIndex, void *data,
2553 unsigned long request;
2555 request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
2556 DRM_COMMAND_BASE + drmCommandIndex, size);
2558 if (drmIoctl(fd, request, data)) {
2566 * Send a device-specific read-write command.
2568 * \param fd file descriptor.
2569 * \param drmCommandIndex command index
2570 * \param data source pointer of the data to be read and written.
2571 * \param size size of the data to be read and written.
2573 * \return zero on success, or a negative value on failure.
2576 * It issues a read-write ioctl given by
2577 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2579 int drmCommandWriteRead(int fd, unsigned long drmCommandIndex, void *data,
2582 unsigned long request;
2584 request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
2585 DRM_COMMAND_BASE + drmCommandIndex, size);
2587 if (drmIoctl(fd, request, data))
2592 #define DRM_MAX_FDS 16
2598 } connection[DRM_MAX_FDS];
2600 static int nr_fds = 0;
2602 int drmOpenOnce(void *unused,
2606 return drmOpenOnceWithType(BusID, newlyopened, DRM_NODE_PRIMARY);
2609 int drmOpenOnceWithType(const char *BusID, int *newlyopened, int type)
2614 for (i = 0; i < nr_fds; i++)
2615 if ((strcmp(BusID, connection[i].BusID) == 0) &&
2616 (connection[i].type == type)) {
2617 connection[i].refcount++;
2619 return connection[i].fd;
2622 fd = drmOpenWithType(NULL, BusID, type);
2623 if (fd <= 0 || nr_fds == DRM_MAX_FDS)
2626 connection[nr_fds].BusID = strdup(BusID);
2627 connection[nr_fds].fd = fd;
2628 connection[nr_fds].refcount = 1;
2629 connection[nr_fds].type = type;
2633 fprintf(stderr, "saved connection %d for %s %d\n",
2634 nr_fds, connection[nr_fds].BusID,
2635 strcmp(BusID, connection[nr_fds].BusID));
2642 void drmCloseOnce(int fd)
2646 for (i = 0; i < nr_fds; i++) {
2647 if (fd == connection[i].fd) {
2648 if (--connection[i].refcount == 0) {
2649 drmClose(connection[i].fd);
2650 free(connection[i].BusID);
2653 connection[i] = connection[nr_fds];
2661 int drmSetMaster(int fd)
2663 return drmIoctl(fd, DRM_IOCTL_SET_MASTER, NULL);
2666 int drmDropMaster(int fd)
2668 return drmIoctl(fd, DRM_IOCTL_DROP_MASTER, NULL);
2671 char *drmGetDeviceNameFromFd(int fd)
2678 /* The whole drmOpen thing is a fiasco and we need to find a way
2679 * back to just using open(2). For now, however, lets just make
2680 * things worse with even more ad hoc directory walking code to
2681 * discover the device file name. */
2686 for (i = 0; i < DRM_MAX_MINOR; i++) {
2687 snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
2688 if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
2691 if (i == DRM_MAX_MINOR)
2694 return strdup(name);
2697 int drmGetNodeTypeFromFd(int fd)
2702 if (fstat(fd, &sbuf))
2705 maj = major(sbuf.st_rdev);
2706 min = minor(sbuf.st_rdev);
2708 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode)) {
2713 type = drmGetMinorType(min);
2719 int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags, int *prime_fd)
2721 struct drm_prime_handle args;
2724 args.handle = handle;
2726 ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
2730 *prime_fd = args.fd;
2734 int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
2736 struct drm_prime_handle args;
2741 ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
2745 *handle = args.handle;
2749 static char *drmGetMinorNameForFD(int fd, int type)
2753 struct dirent *pent, *ent;
2755 const char *name = drmGetMinorName(type);
2757 char dev_name[64], buf[64];
2766 if (fstat(fd, &sbuf))
2769 maj = major(sbuf.st_rdev);
2770 min = minor(sbuf.st_rdev);
2772 if (maj != DRM_MAJOR || !S_ISCHR(sbuf.st_mode))
2775 snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
2777 sysdir = opendir(buf);
2781 name_max = fpathconf(dirfd(sysdir), _PC_NAME_MAX);
2785 pent = malloc(offsetof(struct dirent, d_name) + name_max + 1);
2789 while (readdir_r(sysdir, pent, &ent) == 0 && ent != NULL) {
2790 if (strncmp(ent->d_name, name, len) == 0) {
2794 snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
2796 return strdup(dev_name);
2808 char *drmGetPrimaryDeviceNameFromFd(int fd)
2810 return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
2813 char *drmGetRenderDeviceNameFromFd(int fd)
2815 return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
2819 * Enumerate the GPU devices on the system
2821 * \param devs device array set to return the device information
2822 * (if NULL, the number of device is returned)
2823 * \param vendor the vendor ID for GPU devices to list
2824 * (optional, if not specified, all GPU devices are returned)
2826 * \return the number of GPU devices
2828 int drmGetPciDevices(drmPciDevicePtr devSet, uint16_t vendorId)
2830 struct udev *udev = NULL;
2831 struct udev_enumerate *udev_enumerate;
2832 struct udev_list_entry *list_entry;
2833 struct udev_device *device;
2834 int drmDevCount = 0;
2844 char config[64] = {0};
2845 char node[128] = {'\0'};
2846 char slot[] = "0000:00:00.0";
2847 const char *info = NULL;
2853 fprintf(stderr, "no context\n");
2856 udev_enumerate = udev_enumerate_new(udev);
2857 if (udev_enumerate == NULL)
2859 udev_enumerate_add_match_subsystem(udev_enumerate, "drm");
2860 udev_enumerate_add_match_property(udev_enumerate, "DEVTYPE", "drm_minor");
2862 udev_enumerate_scan_devices(udev_enumerate);
2864 udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(udev_enumerate)) {
2865 device = udev_device_new_from_syspath(udev_enumerate_get_udev(udev_enumerate),
2866 udev_list_entry_get_name(list_entry));
2867 if (device != NULL) {
2868 info = udev_device_get_property_value(device, "MINOR");
2869 if (!strcmp(info, "0")) {
2870 strcpy(node, udev_device_get_syspath(device));
2871 info = strstr(node, "/drm");
2872 strncpy(slot, info - strlen(slot), strlen(slot));
2873 if (sscanf(slot, "%4x:%2x:%2x.%1x", &domain, &bus, &dev, &func) != 4) {
2879 strcpy(node + strlen(node), "/device/config");
2881 fd = open(node, O_RDONLY);
2883 ret = read(fd, config, 64);
2885 vendor = config[0] + (config[1] << 8);
2886 devid = config[2] + (config[3] << 8);
2888 subdevid = config[44] + (config[45] << 8);
2893 if((vendorId == 0) || (vendorId == vendor)) {
2894 if(devSet != NULL) {
2895 devSet[drmDevCount].domain = domain;
2896 devSet[drmDevCount].bus = bus;
2897 devSet[drmDevCount].dev = dev;
2898 devSet[drmDevCount].func = func;
2899 devSet[drmDevCount].vendor_id = vendor;
2900 devSet[drmDevCount].device_id = devid;
2901 devSet[drmDevCount].subdevice_id = subdevid;
2902 devSet[drmDevCount].subvendor_id = subvendor;
2903 devSet[drmDevCount].revision_id = revid;
2909 udev_device_unref(device);
2911 udev_enumerate_unref(udev_enumerate);