3 * User-level interface to DRM device
5 * \author Rickard E. (Rik) Faith <faith@valinux.com>
6 * \author Kevin E. Martin <martin@valinux.com>
10 * Copyright 1999 Precision Insight, Inc., Cedar Park, Texas.
11 * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California.
12 * All Rights Reserved.
14 * Permission is hereby granted, free of charge, to any person obtaining a
15 * copy of this software and associated documentation files (the "Software"),
16 * to deal in the Software without restriction, including without limitation
17 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
18 * and/or sell copies of the Software, and to permit persons to whom the
19 * Software is furnished to do so, subject to the following conditions:
21 * The above copyright notice and this permission notice (including the next
22 * paragraph) shall be included in all copies or substantial portions of the
25 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
28 * PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
29 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
30 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
31 * DEALINGS IN THE SOFTWARE.
48 #include <sys/types.h>
50 #define stat_t struct stat
51 #include <sys/ioctl.h>
55 #include <sys/mkdev.h>
57 #ifdef MAJOR_IN_SYSMACROS
58 #include <sys/sysmacros.h>
61 #include <sys/sysctl.h>
66 #if defined(__FreeBSD__)
67 #include <sys/param.h>
68 #include <sys/pciio.h>
71 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
73 /* Not all systems have MAP_FAILED defined */
75 #define MAP_FAILED ((void *)-1)
79 #include "libdrm_macros.h"
80 #include "drm_fourcc.h"
82 #include "util_math.h"
98 #endif /* __OpenBSD__ */
101 #define DRM_MAJOR 226 /* Linux */
104 #if defined(__OpenBSD__) || defined(__DragonFly__)
112 uint16_t subvendor_id;
113 uint16_t subdevice_id;
117 #define DRM_IOCTL_GET_PCIINFO DRM_IOR(0x15, struct drm_pciinfo)
120 #define DRM_MSG_VERBOSITY 3
122 #define memclear(s) memset(&s, 0, sizeof(s))
124 static drmServerInfoPtr drm_server_info;
126 static bool drmNodeIsDRM(int maj, int min);
127 static char *drmGetMinorNameForFD(int fd, int type);
129 #define DRM_MODIFIER(v, f, f_name) \
130 .modifier = DRM_FORMAT_MOD_##v ## _ ##f, \
131 .modifier_name = #f_name
133 #define DRM_MODIFIER_INVALID(v, f_name) \
134 .modifier = DRM_FORMAT_MOD_INVALID, .modifier_name = #f_name
136 #define DRM_MODIFIER_LINEAR(v, f_name) \
137 .modifier = DRM_FORMAT_MOD_LINEAR, .modifier_name = #f_name
139 /* Intel is abit special as the format doesn't follow other vendors naming
141 #define DRM_MODIFIER_INTEL(f, f_name) \
142 .modifier = I915_FORMAT_MOD_##f, .modifier_name = #f_name
144 struct drmFormatModifierInfo {
146 const char *modifier_name;
149 struct drmFormatModifierVendorInfo {
151 const char *vendor_name;
154 #include "generated_static_table_fourcc.h"
156 struct drmVendorInfo {
158 char *(*vendor_cb)(uint64_t modifier);
161 struct drmFormatVendorModifierInfo {
163 const char *modifier_name;
167 drmGetFormatModifierNameFromArm(uint64_t modifier);
170 drmGetFormatModifierNameFromNvidia(uint64_t modifier);
173 drmGetFormatModifierNameFromAmd(uint64_t modifier);
176 drmGetFormatModifierNameFromAmlogic(uint64_t modifier);
178 static const struct drmVendorInfo modifier_format_vendor_table[] = {
179 { DRM_FORMAT_MOD_VENDOR_ARM, drmGetFormatModifierNameFromArm },
180 { DRM_FORMAT_MOD_VENDOR_NVIDIA, drmGetFormatModifierNameFromNvidia },
181 { DRM_FORMAT_MOD_VENDOR_AMD, drmGetFormatModifierNameFromAmd },
182 { DRM_FORMAT_MOD_VENDOR_AMLOGIC, drmGetFormatModifierNameFromAmlogic },
185 #ifndef AFBC_FORMAT_MOD_MODE_VALUE_MASK
186 #define AFBC_FORMAT_MOD_MODE_VALUE_MASK 0x000fffffffffffffULL
189 static const struct drmFormatVendorModifierInfo arm_mode_value_table[] = {
190 { AFBC_FORMAT_MOD_YTR, "YTR" },
191 { AFBC_FORMAT_MOD_SPLIT, "SPLIT" },
192 { AFBC_FORMAT_MOD_SPARSE, "SPARSE" },
193 { AFBC_FORMAT_MOD_CBR, "CBR" },
194 { AFBC_FORMAT_MOD_TILED, "TILED" },
195 { AFBC_FORMAT_MOD_SC, "SC" },
196 { AFBC_FORMAT_MOD_DB, "DB" },
197 { AFBC_FORMAT_MOD_BCH, "BCH" },
198 { AFBC_FORMAT_MOD_USM, "USM" },
201 static bool is_x_t_amd_gfx9_tile(uint64_t tile)
204 case AMD_FMT_MOD_TILE_GFX9_64K_S_X:
205 case AMD_FMT_MOD_TILE_GFX9_64K_D_X:
206 case AMD_FMT_MOD_TILE_GFX9_64K_R_X:
214 drmGetAfbcFormatModifierNameFromArm(uint64_t modifier, FILE *fp)
216 uint64_t mode_value = modifier & AFBC_FORMAT_MOD_MODE_VALUE_MASK;
217 uint64_t block_size = mode_value & AFBC_FORMAT_MOD_BLOCK_SIZE_MASK;
219 const char *block = NULL;
220 const char *mode = NULL;
221 bool did_print_mode = false;
223 /* add block, can only have a (single) block */
224 switch (block_size) {
225 case AFBC_FORMAT_MOD_BLOCK_SIZE_16x16:
228 case AFBC_FORMAT_MOD_BLOCK_SIZE_32x8:
231 case AFBC_FORMAT_MOD_BLOCK_SIZE_64x4:
234 case AFBC_FORMAT_MOD_BLOCK_SIZE_32x8_64x4:
243 fprintf(fp, "BLOCK_SIZE=%s,", block);
246 for (unsigned int i = 0; i < ARRAY_SIZE(arm_mode_value_table); i++) {
247 if (arm_mode_value_table[i].modifier & mode_value) {
248 mode = arm_mode_value_table[i].modifier_name;
249 if (!did_print_mode) {
250 fprintf(fp, "MODE=%s", mode);
251 did_print_mode = true;
253 fprintf(fp, "|%s", mode);
262 drmGetAfrcFormatModifierNameFromArm(uint64_t modifier, FILE *fp)
265 for (unsigned int i = 0; i < 2; ++i) {
266 uint64_t coding_unit_block =
267 (modifier >> (i * 4)) & AFRC_FORMAT_MOD_CU_SIZE_MASK;
268 const char *coding_unit_size = NULL;
270 switch (coding_unit_block) {
271 case AFRC_FORMAT_MOD_CU_SIZE_16:
272 coding_unit_size = "CU_16";
274 case AFRC_FORMAT_MOD_CU_SIZE_24:
275 coding_unit_size = "CU_24";
277 case AFRC_FORMAT_MOD_CU_SIZE_32:
278 coding_unit_size = "CU_32";
282 if (!coding_unit_size) {
290 fprintf(fp, "P0=%s,", coding_unit_size);
292 fprintf(fp, "P12=%s,", coding_unit_size);
297 (modifier & AFRC_FORMAT_MOD_LAYOUT_SCAN) == AFRC_FORMAT_MOD_LAYOUT_SCAN;
307 drmGetFormatModifierNameFromArm(uint64_t modifier)
309 uint64_t type = (modifier >> 52) & 0xf;
313 char *modifier_name = NULL;
316 fp = open_memstream(&modifier_name, &size);
321 case DRM_FORMAT_MOD_ARM_TYPE_AFBC:
322 result = drmGetAfbcFormatModifierNameFromArm(modifier, fp);
324 case DRM_FORMAT_MOD_ARM_TYPE_AFRC:
325 result = drmGetAfrcFormatModifierNameFromArm(modifier, fp);
327 /* misc type is already handled by the static table */
328 case DRM_FORMAT_MOD_ARM_TYPE_MISC:
340 return modifier_name;
344 drmGetFormatModifierNameFromNvidia(uint64_t modifier)
346 uint64_t height, kind, gen, sector, compression;
348 height = modifier & 0xf;
349 kind = (modifier >> 12) & 0xff;
351 gen = (modifier >> 20) & 0x3;
352 sector = (modifier >> 22) & 0x1;
353 compression = (modifier >> 23) & 0x7;
355 /* just in case there could other simpler modifiers, not yet added, avoid
356 * testing against TEGRA_TILE */
357 if ((modifier & 0x10) == 0x10) {
359 asprintf(&mod_nvidia, "BLOCK_LINEAR_2D,HEIGHT=%"PRIu64",KIND=%"PRIu64","
360 "GEN=%"PRIu64",SECTOR=%"PRIu64",COMPRESSION=%"PRIu64"", height,
361 kind, gen, sector, compression);
369 drmGetFormatModifierNameFromAmdDcc(uint64_t modifier, FILE *fp)
371 uint64_t dcc_max_compressed_block =
372 AMD_FMT_MOD_GET(DCC_MAX_COMPRESSED_BLOCK, modifier);
373 uint64_t dcc_retile = AMD_FMT_MOD_GET(DCC_RETILE, modifier);
375 const char *dcc_max_compressed_block_str = NULL;
380 fprintf(fp, ",DCC_RETILE");
382 if (!dcc_retile && AMD_FMT_MOD_GET(DCC_PIPE_ALIGN, modifier))
383 fprintf(fp, ",DCC_PIPE_ALIGN");
385 if (AMD_FMT_MOD_GET(DCC_INDEPENDENT_64B, modifier))
386 fprintf(fp, ",DCC_INDEPENDENT_64B");
388 if (AMD_FMT_MOD_GET(DCC_INDEPENDENT_128B, modifier))
389 fprintf(fp, ",DCC_INDEPENDENT_128B");
391 switch (dcc_max_compressed_block) {
392 case AMD_FMT_MOD_DCC_BLOCK_64B:
393 dcc_max_compressed_block_str = "64B";
395 case AMD_FMT_MOD_DCC_BLOCK_128B:
396 dcc_max_compressed_block_str = "128B";
398 case AMD_FMT_MOD_DCC_BLOCK_256B:
399 dcc_max_compressed_block_str = "256B";
403 if (dcc_max_compressed_block_str)
404 fprintf(fp, ",DCC_MAX_COMPRESSED_BLOCK=%s",
405 dcc_max_compressed_block_str);
407 if (AMD_FMT_MOD_GET(DCC_CONSTANT_ENCODE, modifier))
408 fprintf(fp, ",DCC_CONSTANT_ENCODE");
412 drmGetFormatModifierNameFromAmdTile(uint64_t modifier, FILE *fp)
414 uint64_t pipe_xor_bits, bank_xor_bits, packers, rb;
415 uint64_t pipe, pipe_align, dcc, dcc_retile, tile_version;
417 pipe_align = AMD_FMT_MOD_GET(DCC_PIPE_ALIGN, modifier);
418 pipe_xor_bits = AMD_FMT_MOD_GET(PIPE_XOR_BITS, modifier);
419 dcc = AMD_FMT_MOD_GET(DCC, modifier);
420 dcc_retile = AMD_FMT_MOD_GET(DCC_RETILE, modifier);
421 tile_version = AMD_FMT_MOD_GET(TILE_VERSION, modifier);
423 fprintf(fp, ",PIPE_XOR_BITS=%"PRIu64, pipe_xor_bits);
425 if (tile_version == AMD_FMT_MOD_TILE_VER_GFX9) {
426 bank_xor_bits = AMD_FMT_MOD_GET(BANK_XOR_BITS, modifier);
427 fprintf(fp, ",BANK_XOR_BITS=%"PRIu64, bank_xor_bits);
430 if (tile_version == AMD_FMT_MOD_TILE_VER_GFX10_RBPLUS) {
431 packers = AMD_FMT_MOD_GET(PACKERS, modifier);
432 fprintf(fp, ",PACKERS=%"PRIu64, packers);
435 if (dcc && tile_version == AMD_FMT_MOD_TILE_VER_GFX9) {
436 rb = AMD_FMT_MOD_GET(RB, modifier);
437 fprintf(fp, ",RB=%"PRIu64, rb);
440 if (dcc && tile_version == AMD_FMT_MOD_TILE_VER_GFX9 &&
441 (dcc_retile || pipe_align)) {
442 pipe = AMD_FMT_MOD_GET(PIPE, modifier);
443 fprintf(fp, ",PIPE_%"PRIu64, pipe);
448 drmGetFormatModifierNameFromAmd(uint64_t modifier)
450 uint64_t tile, tile_version, dcc;
452 char *mod_amd = NULL;
455 const char *str_tile = NULL;
456 const char *str_tile_version = NULL;
458 tile = AMD_FMT_MOD_GET(TILE, modifier);
459 tile_version = AMD_FMT_MOD_GET(TILE_VERSION, modifier);
460 dcc = AMD_FMT_MOD_GET(DCC, modifier);
462 fp = open_memstream(&mod_amd, &size);
467 switch (tile_version) {
468 case AMD_FMT_MOD_TILE_VER_GFX9:
469 str_tile_version = "GFX9";
471 case AMD_FMT_MOD_TILE_VER_GFX10:
472 str_tile_version = "GFX10";
474 case AMD_FMT_MOD_TILE_VER_GFX10_RBPLUS:
475 str_tile_version = "GFX10_RBPLUS";
479 if (str_tile_version) {
480 fprintf(fp, "%s", str_tile_version);
489 case AMD_FMT_MOD_TILE_GFX9_64K_S:
490 str_tile = "GFX9_64K_S";
492 case AMD_FMT_MOD_TILE_GFX9_64K_D:
493 str_tile = "GFX9_64K_D";
495 case AMD_FMT_MOD_TILE_GFX9_64K_S_X:
496 str_tile = "GFX9_64K_S_X";
498 case AMD_FMT_MOD_TILE_GFX9_64K_D_X:
499 str_tile = "GFX9_64K_D_X";
501 case AMD_FMT_MOD_TILE_GFX9_64K_R_X:
502 str_tile = "GFX9_64K_R_X";
507 fprintf(fp, ",%s", str_tile);
510 drmGetFormatModifierNameFromAmdDcc(modifier, fp);
512 if (tile_version >= AMD_FMT_MOD_TILE_VER_GFX9 && is_x_t_amd_gfx9_tile(tile))
513 drmGetFormatModifierNameFromAmdTile(modifier, fp);
520 drmGetFormatModifierNameFromAmlogic(uint64_t modifier)
522 uint64_t layout = modifier & 0xff;
523 uint64_t options = (modifier >> 8) & 0xff;
524 char *mod_amlogic = NULL;
526 const char *layout_str;
527 const char *opts_str;
530 case AMLOGIC_FBC_LAYOUT_BASIC:
531 layout_str = "BASIC";
533 case AMLOGIC_FBC_LAYOUT_SCATTER:
534 layout_str = "SCATTER";
537 layout_str = "INVALID_LAYOUT";
541 if (options & AMLOGIC_FBC_OPTION_MEM_SAVING)
542 opts_str = "MEM_SAVING";
546 asprintf(&mod_amlogic, "FBC,LAYOUT=%s,OPTIONS=%s", layout_str, opts_str);
550 static unsigned log2_int(unsigned x)
558 if ((unsigned)(1 << l) > x) {
566 drm_public void drmSetServerInfo(drmServerInfoPtr info)
568 drm_server_info = info;
572 * Output a message to stderr.
574 * \param format printf() like format string.
577 * This function is a wrapper around vfprintf().
580 static int DRM_PRINTFLIKE(1, 0)
581 drmDebugPrint(const char *format, va_list ap)
583 return vfprintf(stderr, format, ap);
587 drmMsg(const char *format, ...)
591 if (((env = getenv("LIBGL_DEBUG")) && strstr(env, "verbose")) ||
592 (drm_server_info && drm_server_info->debug_print))
594 va_start(ap, format);
595 if (drm_server_info) {
596 drm_server_info->debug_print(format,ap);
598 drmDebugPrint(format, ap);
604 static void *drmHashTable = NULL; /* Context switch callbacks */
606 drm_public void *drmGetHashTable(void)
611 drm_public void *drmMalloc(int size)
613 return calloc(1, size);
616 drm_public void drmFree(void *pt)
622 * Call ioctl, restarting if it is interrupted
625 drmIoctl(int fd, unsigned long request, void *arg)
630 ret = ioctl(fd, request, arg);
631 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
635 static unsigned long drmGetKeyFromFd(int fd)
644 drm_public drmHashEntry *drmGetEntry(int fd)
646 unsigned long key = drmGetKeyFromFd(fd);
651 drmHashTable = drmHashCreate();
653 if (drmHashLookup(drmHashTable, key, &value)) {
654 entry = drmMalloc(sizeof(*entry));
657 entry->tagTable = drmHashCreate();
658 drmHashInsert(drmHashTable, key, entry);
666 * Compare two busid strings
671 * \return 1 if matched.
674 * This function compares two bus ID strings. It understands the older
675 * PCI:b:d:f format and the newer pci:oooo:bb:dd.f format. In the format, o is
676 * domain, b is bus, d is device, f is function.
678 static int drmMatchBusID(const char *id1, const char *id2, int pci_domain_ok)
680 /* First, check if the IDs are exactly the same */
681 if (strcasecmp(id1, id2) == 0)
684 /* Try to match old/new-style PCI bus IDs. */
685 if (strncasecmp(id1, "pci", 3) == 0) {
686 unsigned int o1, b1, d1, f1;
687 unsigned int o2, b2, d2, f2;
690 ret = sscanf(id1, "pci:%04x:%02x:%02x.%u", &o1, &b1, &d1, &f1);
693 ret = sscanf(id1, "PCI:%u:%u:%u", &b1, &d1, &f1);
698 ret = sscanf(id2, "pci:%04x:%02x:%02x.%u", &o2, &b2, &d2, &f2);
701 ret = sscanf(id2, "PCI:%u:%u:%u", &b2, &d2, &f2);
706 /* If domains aren't properly supported by the kernel interface,
707 * just ignore them, which sucks less than picking a totally random
708 * card with "open by name"
713 if ((o1 != o2) || (b1 != b2) || (d1 != d2) || (f1 != f2))
722 * Handles error checking for chown call.
724 * \param path to file.
725 * \param id of the new owner.
726 * \param id of the new group.
728 * \return zero if success or -1 if failure.
731 * Checks for failure. If failure was caused by signal call chown again.
732 * If any other failure happened then it will output error message using
736 static int chown_check_return(const char *path, uid_t owner, gid_t group)
741 rv = chown(path, owner, group);
742 } while (rv != 0 && errno == EINTR);
747 drmMsg("Failed to change owner or group for file %s! %d: %s\n",
748 path, errno, strerror(errno));
753 static const char *drmGetDeviceName(int type)
756 case DRM_NODE_PRIMARY:
758 case DRM_NODE_CONTROL:
759 return DRM_CONTROL_DEV_NAME;
760 case DRM_NODE_RENDER:
761 return DRM_RENDER_DEV_NAME;
767 * Open the DRM device, creating it if necessary.
769 * \param dev major and minor numbers of the device.
770 * \param minor minor number of the device.
772 * \return a file descriptor on success, or a negative value on error.
775 * Assembles the device name from \p minor and opens it, creating the device
776 * special file node with the major and minor numbers specified by \p dev and
777 * parent directory if necessary and was called by root.
779 static int drmOpenDevice(dev_t dev, int minor, int type)
782 const char *dev_name = drmGetDeviceName(type);
783 char buf[DRM_NODE_NAME_MAX];
785 mode_t devmode = DRM_DEV_MODE, serv_mode;
788 int isroot = !geteuid();
789 uid_t user = DRM_DEV_UID;
790 gid_t group = DRM_DEV_GID;
796 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
797 drmMsg("drmOpenDevice: node name is %s\n", buf);
799 if (drm_server_info && drm_server_info->get_perms) {
800 drm_server_info->get_perms(&serv_group, &serv_mode);
801 devmode = serv_mode ? serv_mode : DRM_DEV_MODE;
802 devmode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
806 if (stat(DRM_DIR_NAME, &st)) {
808 return DRM_ERR_NOT_ROOT;
809 mkdir(DRM_DIR_NAME, DRM_DEV_DIRMODE);
810 chown_check_return(DRM_DIR_NAME, 0, 0); /* root:root */
811 chmod(DRM_DIR_NAME, DRM_DEV_DIRMODE);
814 /* Check if the device node exists and create it if necessary. */
815 if (stat(buf, &st)) {
817 return DRM_ERR_NOT_ROOT;
819 mknod(buf, S_IFCHR | devmode, dev);
822 if (drm_server_info && drm_server_info->get_perms) {
823 group = ((int)serv_group >= 0) ? serv_group : DRM_DEV_GID;
824 chown_check_return(buf, user, group);
828 /* if we modprobed then wait for udev */
832 if (stat(DRM_DIR_NAME, &st)) {
836 if (udev_count == 50)
841 if (stat(buf, &st)) {
845 if (udev_count == 50)
852 fd = open(buf, O_RDWR | O_CLOEXEC, 0);
853 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
854 fd, fd < 0 ? strerror(errno) : "OK");
859 /* Check if the device node is not what we expect it to be, and recreate it
860 * and try again if so.
862 if (st.st_rdev != dev) {
864 return DRM_ERR_NOT_ROOT;
866 mknod(buf, S_IFCHR | devmode, dev);
867 if (drm_server_info && drm_server_info->get_perms) {
868 chown_check_return(buf, user, group);
872 fd = open(buf, O_RDWR | O_CLOEXEC, 0);
873 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
874 fd, fd < 0 ? strerror(errno) : "OK");
878 drmMsg("drmOpenDevice: Open failed\n");
886 * Open the DRM device
888 * \param minor device minor number.
889 * \param create allow to create the device if set.
891 * \return a file descriptor on success, or a negative value on error.
894 * Calls drmOpenDevice() if \p create is set, otherwise assembles the device
895 * name from \p minor and opens it.
897 static int drmOpenMinor(int minor, int create, int type)
900 char buf[DRM_NODE_NAME_MAX];
901 const char *dev_name = drmGetDeviceName(type);
904 return drmOpenDevice(makedev(DRM_MAJOR, minor), minor, type);
909 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
910 if ((fd = open(buf, O_RDWR | O_CLOEXEC, 0)) >= 0)
917 * Determine whether the DRM kernel driver has been loaded.
919 * \return 1 if the DRM driver is loaded, 0 otherwise.
922 * Determine the presence of the kernel driver by attempting to open the 0
923 * minor and get version information. For backward compatibility with older
924 * Linux implementations, /proc/dri is also checked.
926 drm_public int drmAvailable(void)
928 drmVersionPtr version;
932 if ((fd = drmOpenMinor(0, 1, DRM_NODE_PRIMARY)) < 0) {
934 /* Try proc for backward Linux compatibility */
935 if (!access("/proc/dri/0", R_OK))
941 if ((version = drmGetVersion(fd))) {
943 drmFreeVersion(version);
950 static int drmGetMinorBase(int type)
953 case DRM_NODE_PRIMARY:
955 case DRM_NODE_CONTROL:
957 case DRM_NODE_RENDER:
964 static int drmGetMinorType(int major, int minor)
967 char name[SPECNAMELEN];
970 if (!devname_r(makedev(major, minor), S_IFCHR, name, sizeof(name)))
973 if (sscanf(name, "drm/%d", &id) != 1) {
974 // If not in /dev/drm/ we have the type in the name
975 if (sscanf(name, "dri/card%d\n", &id) >= 1)
976 return DRM_NODE_PRIMARY;
977 else if (sscanf(name, "dri/control%d\n", &id) >= 1)
978 return DRM_NODE_CONTROL;
979 else if (sscanf(name, "dri/renderD%d\n", &id) >= 1)
980 return DRM_NODE_RENDER;
986 int type = minor >> 6;
992 case DRM_NODE_PRIMARY:
993 case DRM_NODE_CONTROL:
994 case DRM_NODE_RENDER:
1001 static const char *drmGetMinorName(int type)
1004 case DRM_NODE_PRIMARY:
1005 return DRM_PRIMARY_MINOR_NAME;
1006 case DRM_NODE_CONTROL:
1007 return DRM_CONTROL_MINOR_NAME;
1008 case DRM_NODE_RENDER:
1009 return DRM_RENDER_MINOR_NAME;
1016 * Open the device by bus ID.
1018 * \param busid bus ID.
1019 * \param type device node type.
1021 * \return a file descriptor on success, or a negative value on error.
1024 * This function attempts to open every possible minor (up to DRM_MAX_MINOR),
1025 * comparing the device bus ID with the one supplied.
1027 * \sa drmOpenMinor() and drmGetBusid().
1029 static int drmOpenByBusid(const char *busid, int type)
1031 int i, pci_domain_ok = 1;
1035 int base = drmGetMinorBase(type);
1040 drmMsg("drmOpenByBusid: Searching for BusID %s\n", busid);
1041 for (i = base; i < base + DRM_MAX_MINOR; i++) {
1042 fd = drmOpenMinor(i, 1, type);
1043 drmMsg("drmOpenByBusid: drmOpenMinor returns %d\n", fd);
1045 /* We need to try for 1.4 first for proper PCI domain support
1046 * and if that fails, we know the kernel is busted
1048 sv.drm_di_major = 1;
1049 sv.drm_di_minor = 4;
1050 sv.drm_dd_major = -1; /* Don't care */
1051 sv.drm_dd_minor = -1; /* Don't care */
1052 if (drmSetInterfaceVersion(fd, &sv)) {
1056 sv.drm_di_major = 1;
1057 sv.drm_di_minor = 1;
1058 sv.drm_dd_major = -1; /* Don't care */
1059 sv.drm_dd_minor = -1; /* Don't care */
1060 drmMsg("drmOpenByBusid: Interface 1.4 failed, trying 1.1\n");
1061 drmSetInterfaceVersion(fd, &sv);
1063 buf = drmGetBusid(fd);
1064 drmMsg("drmOpenByBusid: drmGetBusid reports %s\n", buf);
1065 if (buf && drmMatchBusID(buf, busid, pci_domain_ok)) {
1079 * Open the device by name.
1081 * \param name driver name.
1082 * \param type the device node type.
1084 * \return a file descriptor on success, or a negative value on error.
1087 * This function opens the first minor number that matches the driver name and
1088 * isn't already in use. If it's in use it then it will already have a bus ID
1091 * \sa drmOpenMinor(), drmGetVersion() and drmGetBusid().
1093 static int drmOpenByName(const char *name, int type)
1097 drmVersionPtr version;
1099 int base = drmGetMinorBase(type);
1105 * Open the first minor number that matches the driver name and isn't
1106 * already in use. If it's in use it will have a busid assigned already.
1108 for (i = base; i < base + DRM_MAX_MINOR; i++) {
1109 if ((fd = drmOpenMinor(i, 1, type)) >= 0) {
1110 if ((version = drmGetVersion(fd))) {
1111 if (!strcmp(version->name, name)) {
1112 drmFreeVersion(version);
1113 id = drmGetBusid(fd);
1114 drmMsg("drmGetBusid returned '%s'\n", id ? id : "NULL");
1123 drmFreeVersion(version);
1131 /* Backward-compatibility /proc support */
1132 for (i = 0; i < 8; i++) {
1133 char proc_name[64], buf[512];
1134 char *driver, *pt, *devstring;
1137 sprintf(proc_name, "/proc/dri/%d/name", i);
1138 if ((fd = open(proc_name, O_RDONLY, 0)) >= 0) {
1139 retcode = read(fd, buf, sizeof(buf)-1);
1142 buf[retcode-1] = '\0';
1143 for (driver = pt = buf; *pt && *pt != ' '; ++pt)
1145 if (*pt) { /* Device is next */
1147 if (!strcmp(driver, name)) { /* Match */
1148 for (devstring = ++pt; *pt && *pt != ' '; ++pt)
1150 if (*pt) { /* Found busid */
1151 return drmOpenByBusid(++pt, type);
1152 } else { /* No busid */
1153 return drmOpenDevice(strtol(devstring, NULL, 0),i, type);
1167 * Open the DRM device.
1169 * Looks up the specified name and bus ID, and opens the device found. The
1170 * entry in /dev/dri is created if necessary and if called by root.
1172 * \param name driver name. Not referenced if bus ID is supplied.
1173 * \param busid bus ID. Zero if not known.
1175 * \return a file descriptor on success, or a negative value on error.
1178 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
1181 drm_public int drmOpen(const char *name, const char *busid)
1183 return drmOpenWithType(name, busid, DRM_NODE_PRIMARY);
1187 * Open the DRM device with specified type.
1189 * Looks up the specified name and bus ID, and opens the device found. The
1190 * entry in /dev/dri is created if necessary and if called by root.
1192 * \param name driver name. Not referenced if bus ID is supplied.
1193 * \param busid bus ID. Zero if not known.
1194 * \param type the device node type to open, PRIMARY, CONTROL or RENDER
1196 * \return a file descriptor on success, or a negative value on error.
1199 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
1202 drm_public int drmOpenWithType(const char *name, const char *busid, int type)
1204 if (name != NULL && drm_server_info &&
1205 drm_server_info->load_module && !drmAvailable()) {
1206 /* try to load the kernel module */
1207 if (!drm_server_info->load_module(name)) {
1208 drmMsg("[drm] failed to load kernel module \"%s\"\n", name);
1214 int fd = drmOpenByBusid(busid, type);
1220 return drmOpenByName(name, type);
1225 drm_public int drmOpenControl(int minor)
1227 return drmOpenMinor(minor, 0, DRM_NODE_CONTROL);
1230 drm_public int drmOpenRender(int minor)
1232 return drmOpenMinor(minor, 0, DRM_NODE_RENDER);
1236 * Free the version information returned by drmGetVersion().
1238 * \param v pointer to the version information.
1241 * It frees the memory pointed by \p %v as well as all the non-null strings
1244 drm_public void drmFreeVersion(drmVersionPtr v)
1256 * Free the non-public version information returned by the kernel.
1258 * \param v pointer to the version information.
1261 * Used by drmGetVersion() to free the memory pointed by \p %v as well as all
1262 * the non-null strings pointers in it.
1264 static void drmFreeKernelVersion(drm_version_t *v)
1276 * Copy version information.
1278 * \param d destination pointer.
1279 * \param s source pointer.
1282 * Used by drmGetVersion() to translate the information returned by the ioctl
1283 * interface in a private structure into the public structure counterpart.
1285 static void drmCopyVersion(drmVersionPtr d, const drm_version_t *s)
1287 d->version_major = s->version_major;
1288 d->version_minor = s->version_minor;
1289 d->version_patchlevel = s->version_patchlevel;
1290 d->name_len = s->name_len;
1291 d->name = strdup(s->name);
1292 d->date_len = s->date_len;
1293 d->date = strdup(s->date);
1294 d->desc_len = s->desc_len;
1295 d->desc = strdup(s->desc);
1300 * Query the driver version information.
1302 * \param fd file descriptor.
1304 * \return pointer to a drmVersion structure which should be freed with
1307 * \note Similar information is available via /proc/dri.
1310 * It gets the version information via successive DRM_IOCTL_VERSION ioctls,
1311 * first with zeros to get the string lengths, and then the actually strings.
1312 * It also null-terminates them since they might not be already.
1314 drm_public drmVersionPtr drmGetVersion(int fd)
1316 drmVersionPtr retval;
1317 drm_version_t *version = drmMalloc(sizeof(*version));
1319 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
1320 drmFreeKernelVersion(version);
1324 if (version->name_len)
1325 version->name = drmMalloc(version->name_len + 1);
1326 if (version->date_len)
1327 version->date = drmMalloc(version->date_len + 1);
1328 if (version->desc_len)
1329 version->desc = drmMalloc(version->desc_len + 1);
1331 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
1332 drmMsg("DRM_IOCTL_VERSION: %s\n", strerror(errno));
1333 drmFreeKernelVersion(version);
1337 /* The results might not be null-terminated strings, so terminate them. */
1338 if (version->name_len) version->name[version->name_len] = '\0';
1339 if (version->date_len) version->date[version->date_len] = '\0';
1340 if (version->desc_len) version->desc[version->desc_len] = '\0';
1342 retval = drmMalloc(sizeof(*retval));
1343 drmCopyVersion(retval, version);
1344 drmFreeKernelVersion(version);
1350 * Get version information for the DRM user space library.
1352 * This version number is driver independent.
1354 * \param fd file descriptor.
1356 * \return version information.
1359 * This function allocates and fills a drm_version structure with a hard coded
1362 drm_public drmVersionPtr drmGetLibVersion(int fd)
1364 drm_version_t *version = drmMalloc(sizeof(*version));
1367 * NOTE THIS MUST NOT GO ABOVE VERSION 1.X due to drivers needing it
1368 * revision 1.0.x = original DRM interface with no drmGetLibVersion
1369 * entry point and many drm<Device> extensions
1370 * revision 1.1.x = added drmCommand entry points for device extensions
1371 * added drmGetLibVersion to identify libdrm.a version
1372 * revision 1.2.x = added drmSetInterfaceVersion
1373 * modified drmOpen to handle both busid and name
1374 * revision 1.3.x = added server + memory manager
1376 version->version_major = 1;
1377 version->version_minor = 3;
1378 version->version_patchlevel = 0;
1380 return (drmVersionPtr)version;
1383 drm_public int drmGetCap(int fd, uint64_t capability, uint64_t *value)
1385 struct drm_get_cap cap;
1389 cap.capability = capability;
1391 ret = drmIoctl(fd, DRM_IOCTL_GET_CAP, &cap);
1399 drm_public int drmSetClientCap(int fd, uint64_t capability, uint64_t value)
1401 struct drm_set_client_cap cap;
1404 cap.capability = capability;
1407 return drmIoctl(fd, DRM_IOCTL_SET_CLIENT_CAP, &cap);
1411 * Free the bus ID information.
1413 * \param busid bus ID information string as given by drmGetBusid().
1416 * This function is just frees the memory pointed by \p busid.
1418 drm_public void drmFreeBusid(const char *busid)
1420 drmFree((void *)busid);
1425 * Get the bus ID of the device.
1427 * \param fd file descriptor.
1429 * \return bus ID string.
1432 * This function gets the bus ID via successive DRM_IOCTL_GET_UNIQUE ioctls to
1433 * get the string length and data, passing the arguments in a drm_unique
1436 drm_public char *drmGetBusid(int fd)
1442 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
1444 u.unique = drmMalloc(u.unique_len + 1);
1445 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u)) {
1449 u.unique[u.unique_len] = '\0';
1456 * Set the bus ID of the device.
1458 * \param fd file descriptor.
1459 * \param busid bus ID string.
1461 * \return zero on success, negative on failure.
1464 * This function is a wrapper around the DRM_IOCTL_SET_UNIQUE ioctl, passing
1465 * the arguments in a drm_unique structure.
1467 drm_public int drmSetBusid(int fd, const char *busid)
1472 u.unique = (char *)busid;
1473 u.unique_len = strlen(busid);
1475 if (drmIoctl(fd, DRM_IOCTL_SET_UNIQUE, &u)) {
1481 drm_public int drmGetMagic(int fd, drm_magic_t * magic)
1488 if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
1490 *magic = auth.magic;
1494 drm_public int drmAuthMagic(int fd, drm_magic_t magic)
1500 if (drmIoctl(fd, DRM_IOCTL_AUTH_MAGIC, &auth))
1506 * Specifies a range of memory that is available for mapping by a
1509 * \param fd file descriptor.
1510 * \param offset usually the physical address. The actual meaning depends of
1511 * the \p type parameter. See below.
1512 * \param size of the memory in bytes.
1513 * \param type type of the memory to be mapped.
1514 * \param flags combination of several flags to modify the function actions.
1515 * \param handle will be set to a value that may be used as the offset
1516 * parameter for mmap().
1518 * \return zero on success or a negative value on error.
1520 * \par Mapping the frame buffer
1521 * For the frame buffer
1522 * - \p offset will be the physical address of the start of the frame buffer,
1523 * - \p size will be the size of the frame buffer in bytes, and
1524 * - \p type will be DRM_FRAME_BUFFER.
1527 * The area mapped will be uncached. If MTRR support is available in the
1528 * kernel, the frame buffer area will be set to write combining.
1530 * \par Mapping the MMIO register area
1531 * For the MMIO register area,
1532 * - \p offset will be the physical address of the start of the register area,
1533 * - \p size will be the size of the register area bytes, and
1534 * - \p type will be DRM_REGISTERS.
1536 * The area mapped will be uncached.
1538 * \par Mapping the SAREA
1540 * - \p offset will be ignored and should be set to zero,
1541 * - \p size will be the desired size of the SAREA in bytes,
1542 * - \p type will be DRM_SHM.
1545 * A shared memory area of the requested size will be created and locked in
1546 * kernel memory. This area may be mapped into client-space by using the handle
1549 * \note May only be called by root.
1552 * This function is a wrapper around the DRM_IOCTL_ADD_MAP ioctl, passing
1553 * the arguments in a drm_map structure.
1555 drm_public int drmAddMap(int fd, drm_handle_t offset, drmSize size, drmMapType type,
1556 drmMapFlags flags, drm_handle_t *handle)
1561 map.offset = offset;
1563 map.type = (enum drm_map_type)type;
1564 map.flags = (enum drm_map_flags)flags;
1565 if (drmIoctl(fd, DRM_IOCTL_ADD_MAP, &map))
1568 *handle = (drm_handle_t)(uintptr_t)map.handle;
1572 drm_public int drmRmMap(int fd, drm_handle_t handle)
1577 map.handle = (void *)(uintptr_t)handle;
1579 if(drmIoctl(fd, DRM_IOCTL_RM_MAP, &map))
1585 * Make buffers available for DMA transfers.
1587 * \param fd file descriptor.
1588 * \param count number of buffers.
1589 * \param size size of each buffer.
1590 * \param flags buffer allocation flags.
1591 * \param agp_offset offset in the AGP aperture
1593 * \return number of buffers allocated, negative on error.
1596 * This function is a wrapper around DRM_IOCTL_ADD_BUFS ioctl.
1600 drm_public int drmAddBufs(int fd, int count, int size, drmBufDescFlags flags,
1603 drm_buf_desc_t request;
1606 request.count = count;
1607 request.size = size;
1608 request.flags = (int)flags;
1609 request.agp_start = agp_offset;
1611 if (drmIoctl(fd, DRM_IOCTL_ADD_BUFS, &request))
1613 return request.count;
1616 drm_public int drmMarkBufs(int fd, double low, double high)
1618 drm_buf_info_t info;
1623 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1629 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1632 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1633 int retval = -errno;
1638 for (i = 0; i < info.count; i++) {
1639 info.list[i].low_mark = low * info.list[i].count;
1640 info.list[i].high_mark = high * info.list[i].count;
1641 if (drmIoctl(fd, DRM_IOCTL_MARK_BUFS, &info.list[i])) {
1642 int retval = -errno;
1655 * \param fd file descriptor.
1656 * \param count number of buffers to free.
1657 * \param list list of buffers to be freed.
1659 * \return zero on success, or a negative value on failure.
1661 * \note This function is primarily used for debugging.
1664 * This function is a wrapper around the DRM_IOCTL_FREE_BUFS ioctl, passing
1665 * the arguments in a drm_buf_free structure.
1667 drm_public int drmFreeBufs(int fd, int count, int *list)
1669 drm_buf_free_t request;
1672 request.count = count;
1673 request.list = list;
1674 if (drmIoctl(fd, DRM_IOCTL_FREE_BUFS, &request))
1683 * \param fd file descriptor.
1686 * This function closes the file descriptor.
1688 drm_public int drmClose(int fd)
1690 unsigned long key = drmGetKeyFromFd(fd);
1691 drmHashEntry *entry = drmGetEntry(fd);
1693 drmHashDestroy(entry->tagTable);
1696 entry->tagTable = NULL;
1698 drmHashDelete(drmHashTable, key);
1706 * Map a region of memory.
1708 * \param fd file descriptor.
1709 * \param handle handle returned by drmAddMap().
1710 * \param size size in bytes. Must match the size used by drmAddMap().
1711 * \param address will contain the user-space virtual address where the mapping
1714 * \return zero on success, or a negative value on failure.
1717 * This function is a wrapper for mmap().
1719 drm_public int drmMap(int fd, drm_handle_t handle, drmSize size,
1720 drmAddressPtr address)
1722 static unsigned long pagesize_mask = 0;
1728 pagesize_mask = getpagesize() - 1;
1730 size = (size + pagesize_mask) & ~pagesize_mask;
1732 *address = drm_mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1733 if (*address == MAP_FAILED)
1740 * Unmap mappings obtained with drmMap().
1742 * \param address address as given by drmMap().
1743 * \param size size in bytes. Must match the size used by drmMap().
1745 * \return zero on success, or a negative value on failure.
1748 * This function is a wrapper for munmap().
1750 drm_public int drmUnmap(drmAddress address, drmSize size)
1752 return drm_munmap(address, size);
1755 drm_public drmBufInfoPtr drmGetBufInfo(int fd)
1757 drm_buf_info_t info;
1758 drmBufInfoPtr retval;
1763 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1767 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1770 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1775 retval = drmMalloc(sizeof(*retval));
1776 retval->count = info.count;
1777 if (!(retval->list = drmMalloc(info.count * sizeof(*retval->list)))) {
1783 for (i = 0; i < info.count; i++) {
1784 retval->list[i].count = info.list[i].count;
1785 retval->list[i].size = info.list[i].size;
1786 retval->list[i].low_mark = info.list[i].low_mark;
1787 retval->list[i].high_mark = info.list[i].high_mark;
1796 * Map all DMA buffers into client-virtual space.
1798 * \param fd file descriptor.
1800 * \return a pointer to a ::drmBufMap structure.
1802 * \note The client may not use these buffers until obtaining buffer indices
1806 * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1807 * information about the buffers in a drm_buf_map structure into the
1808 * client-visible data structures.
1810 drm_public drmBufMapPtr drmMapBufs(int fd)
1813 drmBufMapPtr retval;
1817 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1823 if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1826 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1831 retval = drmMalloc(sizeof(*retval));
1832 retval->count = bufs.count;
1833 retval->list = drmMalloc(bufs.count * sizeof(*retval->list));
1834 for (i = 0; i < bufs.count; i++) {
1835 retval->list[i].idx = bufs.list[i].idx;
1836 retval->list[i].total = bufs.list[i].total;
1837 retval->list[i].used = 0;
1838 retval->list[i].address = bufs.list[i].address;
1847 * Unmap buffers allocated with drmMapBufs().
1849 * \return zero on success, or negative value on failure.
1852 * Calls munmap() for every buffer stored in \p bufs and frees the
1853 * memory allocated by drmMapBufs().
1855 drm_public int drmUnmapBufs(drmBufMapPtr bufs)
1859 for (i = 0; i < bufs->count; i++) {
1860 drm_munmap(bufs->list[i].address, bufs->list[i].total);
1863 drmFree(bufs->list);
1869 #define DRM_DMA_RETRY 16
1872 * Reserve DMA buffers.
1874 * \param fd file descriptor.
1877 * \return zero on success, or a negative value on failure.
1880 * Assemble the arguments into a drm_dma structure and keeps issuing the
1881 * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1883 drm_public int drmDMA(int fd, drmDMAReqPtr request)
1888 dma.context = request->context;
1889 dma.send_count = request->send_count;
1890 dma.send_indices = request->send_list;
1891 dma.send_sizes = request->send_sizes;
1892 dma.flags = (enum drm_dma_flags)request->flags;
1893 dma.request_count = request->request_count;
1894 dma.request_size = request->request_size;
1895 dma.request_indices = request->request_list;
1896 dma.request_sizes = request->request_sizes;
1897 dma.granted_count = 0;
1900 ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1901 } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1904 request->granted_count = dma.granted_count;
1913 * Obtain heavyweight hardware lock.
1915 * \param fd file descriptor.
1916 * \param context context.
1917 * \param flags flags that determine the state of the hardware when the function
1920 * \return always zero.
1923 * This function translates the arguments into a drm_lock structure and issue
1924 * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1926 drm_public int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
1931 lock.context = context;
1933 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
1934 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
1935 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
1936 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
1937 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
1938 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
1940 while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
1946 * Release the hardware lock.
1948 * \param fd file descriptor.
1949 * \param context context.
1951 * \return zero on success, or a negative value on failure.
1954 * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
1955 * argument in a drm_lock structure.
1957 drm_public int drmUnlock(int fd, drm_context_t context)
1962 lock.context = context;
1963 return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
1966 drm_public drm_context_t *drmGetReservedContextList(int fd, int *count)
1970 drm_context_t * retval;
1974 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1980 if (!(list = drmMalloc(res.count * sizeof(*list))))
1982 if (!(retval = drmMalloc(res.count * sizeof(*retval))))
1985 res.contexts = list;
1986 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
1987 goto err_free_context;
1989 for (i = 0; i < res.count; i++)
1990 retval[i] = list[i].handle;
2003 drm_public void drmFreeReservedContextList(drm_context_t *pt)
2011 * Used by the X server during GLXContext initialization. This causes
2012 * per-context kernel-level resources to be allocated.
2014 * \param fd file descriptor.
2015 * \param handle is set on success. To be used by the client when requesting DMA
2016 * dispatch with drmDMA().
2018 * \return zero on success, or a negative value on failure.
2020 * \note May only be called by root.
2023 * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
2024 * argument in a drm_ctx structure.
2026 drm_public int drmCreateContext(int fd, drm_context_t *handle)
2031 if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
2033 *handle = ctx.handle;
2037 drm_public int drmSwitchToContext(int fd, drm_context_t context)
2042 ctx.handle = context;
2043 if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
2048 drm_public int drmSetContextFlags(int fd, drm_context_t context,
2049 drm_context_tFlags flags)
2054 * Context preserving means that no context switches are done between DMA
2055 * buffers from one context and the next. This is suitable for use in the
2056 * X server (which promises to maintain hardware context), or in the
2057 * client-side library when buffers are swapped on behalf of two threads.
2060 ctx.handle = context;
2061 if (flags & DRM_CONTEXT_PRESERVED)
2062 ctx.flags |= _DRM_CONTEXT_PRESERVED;
2063 if (flags & DRM_CONTEXT_2DONLY)
2064 ctx.flags |= _DRM_CONTEXT_2DONLY;
2065 if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
2070 drm_public int drmGetContextFlags(int fd, drm_context_t context,
2071 drm_context_tFlagsPtr flags)
2076 ctx.handle = context;
2077 if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
2080 if (ctx.flags & _DRM_CONTEXT_PRESERVED)
2081 *flags |= DRM_CONTEXT_PRESERVED;
2082 if (ctx.flags & _DRM_CONTEXT_2DONLY)
2083 *flags |= DRM_CONTEXT_2DONLY;
2090 * Free any kernel-level resources allocated with drmCreateContext() associated
2093 * \param fd file descriptor.
2094 * \param handle handle given by drmCreateContext().
2096 * \return zero on success, or a negative value on failure.
2098 * \note May only be called by root.
2101 * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
2102 * argument in a drm_ctx structure.
2104 drm_public int drmDestroyContext(int fd, drm_context_t handle)
2109 ctx.handle = handle;
2110 if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
2115 drm_public int drmCreateDrawable(int fd, drm_drawable_t *handle)
2120 if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
2122 *handle = draw.handle;
2126 drm_public int drmDestroyDrawable(int fd, drm_drawable_t handle)
2131 draw.handle = handle;
2132 if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
2137 drm_public int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
2138 drm_drawable_info_type_t type,
2139 unsigned int num, void *data)
2141 drm_update_draw_t update;
2144 update.handle = handle;
2147 update.data = (unsigned long long)(unsigned long)data;
2149 if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
2155 drm_public int drmCrtcGetSequence(int fd, uint32_t crtcId, uint64_t *sequence,
2158 struct drm_crtc_get_sequence get_seq;
2162 get_seq.crtc_id = crtcId;
2163 ret = drmIoctl(fd, DRM_IOCTL_CRTC_GET_SEQUENCE, &get_seq);
2168 *sequence = get_seq.sequence;
2170 *ns = get_seq.sequence_ns;
2174 drm_public int drmCrtcQueueSequence(int fd, uint32_t crtcId, uint32_t flags,
2176 uint64_t *sequence_queued,
2179 struct drm_crtc_queue_sequence queue_seq;
2182 memclear(queue_seq);
2183 queue_seq.crtc_id = crtcId;
2184 queue_seq.flags = flags;
2185 queue_seq.sequence = sequence;
2186 queue_seq.user_data = user_data;
2188 ret = drmIoctl(fd, DRM_IOCTL_CRTC_QUEUE_SEQUENCE, &queue_seq);
2189 if (ret == 0 && sequence_queued)
2190 *sequence_queued = queue_seq.sequence;
2196 * Acquire the AGP device.
2198 * Must be called before any of the other AGP related calls.
2200 * \param fd file descriptor.
2202 * \return zero on success, or a negative value on failure.
2205 * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
2207 drm_public int drmAgpAcquire(int fd)
2209 if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
2216 * Release the AGP device.
2218 * \param fd file descriptor.
2220 * \return zero on success, or a negative value on failure.
2223 * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
2225 drm_public int drmAgpRelease(int fd)
2227 if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
2236 * \param fd file descriptor.
2237 * \param mode AGP mode.
2239 * \return zero on success, or a negative value on failure.
2242 * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
2243 * argument in a drm_agp_mode structure.
2245 drm_public int drmAgpEnable(int fd, unsigned long mode)
2251 if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
2258 * Allocate a chunk of AGP memory.
2260 * \param fd file descriptor.
2261 * \param size requested memory size in bytes. Will be rounded to page boundary.
2262 * \param type type of memory to allocate.
2263 * \param address if not zero, will be set to the physical address of the
2265 * \param handle on success will be set to a handle of the allocated memory.
2267 * \return zero on success, or a negative value on failure.
2270 * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
2271 * arguments in a drm_agp_buffer structure.
2273 drm_public int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
2274 unsigned long *address, drm_handle_t *handle)
2279 *handle = DRM_AGP_NO_HANDLE;
2282 if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
2285 *address = b.physical;
2292 * Free a chunk of AGP memory.
2294 * \param fd file descriptor.
2295 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
2297 * \return zero on success, or a negative value on failure.
2300 * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
2301 * argument in a drm_agp_buffer structure.
2303 drm_public int drmAgpFree(int fd, drm_handle_t handle)
2309 if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
2316 * Bind a chunk of AGP memory.
2318 * \param fd file descriptor.
2319 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
2320 * \param offset offset in bytes. It will round to page boundary.
2322 * \return zero on success, or a negative value on failure.
2325 * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
2326 * argument in a drm_agp_binding structure.
2328 drm_public int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
2330 drm_agp_binding_t b;
2335 if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
2342 * Unbind a chunk of AGP memory.
2344 * \param fd file descriptor.
2345 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
2347 * \return zero on success, or a negative value on failure.
2350 * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
2351 * the argument in a drm_agp_binding structure.
2353 drm_public int drmAgpUnbind(int fd, drm_handle_t handle)
2355 drm_agp_binding_t b;
2359 if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
2366 * Get AGP driver major version number.
2368 * \param fd file descriptor.
2370 * \return major version number on success, or a negative value on failure..
2373 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2374 * necessary information in a drm_agp_info structure.
2376 drm_public int drmAgpVersionMajor(int fd)
2382 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2384 return i.agp_version_major;
2389 * Get AGP driver minor version number.
2391 * \param fd file descriptor.
2393 * \return minor version number on success, or a negative value on failure.
2396 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2397 * necessary information in a drm_agp_info structure.
2399 drm_public int drmAgpVersionMinor(int fd)
2405 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2407 return i.agp_version_minor;
2414 * \param fd file descriptor.
2416 * \return mode on success, or zero on failure.
2419 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2420 * necessary information in a drm_agp_info structure.
2422 drm_public unsigned long drmAgpGetMode(int fd)
2428 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2435 * Get AGP aperture base.
2437 * \param fd file descriptor.
2439 * \return aperture base on success, zero on failure.
2442 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2443 * necessary information in a drm_agp_info structure.
2445 drm_public unsigned long drmAgpBase(int fd)
2451 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2453 return i.aperture_base;
2458 * Get AGP aperture size.
2460 * \param fd file descriptor.
2462 * \return aperture size on success, zero on failure.
2465 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2466 * necessary information in a drm_agp_info structure.
2468 drm_public unsigned long drmAgpSize(int fd)
2474 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2476 return i.aperture_size;
2481 * Get used AGP memory.
2483 * \param fd file descriptor.
2485 * \return memory used on success, or zero on failure.
2488 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2489 * necessary information in a drm_agp_info structure.
2491 drm_public unsigned long drmAgpMemoryUsed(int fd)
2497 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2499 return i.memory_used;
2504 * Get available AGP memory.
2506 * \param fd file descriptor.
2508 * \return memory available on success, or zero on failure.
2511 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2512 * necessary information in a drm_agp_info structure.
2514 drm_public unsigned long drmAgpMemoryAvail(int fd)
2520 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2522 return i.memory_allowed;
2527 * Get hardware vendor ID.
2529 * \param fd file descriptor.
2531 * \return vendor ID on success, or zero on failure.
2534 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2535 * necessary information in a drm_agp_info structure.
2537 drm_public unsigned int drmAgpVendorId(int fd)
2543 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2550 * Get hardware device ID.
2552 * \param fd file descriptor.
2554 * \return zero on success, or zero on failure.
2557 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2558 * necessary information in a drm_agp_info structure.
2560 drm_public unsigned int drmAgpDeviceId(int fd)
2566 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2571 drm_public int drmScatterGatherAlloc(int fd, unsigned long size,
2572 drm_handle_t *handle)
2574 drm_scatter_gather_t sg;
2580 if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
2582 *handle = sg.handle;
2586 drm_public int drmScatterGatherFree(int fd, drm_handle_t handle)
2588 drm_scatter_gather_t sg;
2592 if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
2600 * \param fd file descriptor.
2601 * \param vbl pointer to a drmVBlank structure.
2603 * \return zero on success, or a negative value on failure.
2606 * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
2608 drm_public int drmWaitVBlank(int fd, drmVBlankPtr vbl)
2610 struct timespec timeout, cur;
2613 ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2615 fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
2621 ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
2622 vbl->request.type &= ~DRM_VBLANK_RELATIVE;
2623 if (ret && errno == EINTR) {
2624 clock_gettime(CLOCK_MONOTONIC, &cur);
2625 /* Timeout after 1s */
2626 if (cur.tv_sec > timeout.tv_sec + 1 ||
2627 (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
2634 } while (ret && errno == EINTR);
2640 drm_public int drmError(int err, const char *label)
2643 case DRM_ERR_NO_DEVICE:
2644 fprintf(stderr, "%s: no device\n", label);
2646 case DRM_ERR_NO_ACCESS:
2647 fprintf(stderr, "%s: no access\n", label);
2649 case DRM_ERR_NOT_ROOT:
2650 fprintf(stderr, "%s: not root\n", label);
2652 case DRM_ERR_INVALID:
2653 fprintf(stderr, "%s: invalid args\n", label);
2658 fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2666 * Install IRQ handler.
2668 * \param fd file descriptor.
2669 * \param irq IRQ number.
2671 * \return zero on success, or a negative value on failure.
2674 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2675 * argument in a drm_control structure.
2677 drm_public int drmCtlInstHandler(int fd, int irq)
2682 ctl.func = DRM_INST_HANDLER;
2684 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2691 * Uninstall IRQ handler.
2693 * \param fd file descriptor.
2695 * \return zero on success, or a negative value on failure.
2698 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2699 * argument in a drm_control structure.
2701 drm_public int drmCtlUninstHandler(int fd)
2706 ctl.func = DRM_UNINST_HANDLER;
2708 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2713 drm_public int drmFinish(int fd, int context, drmLockFlags flags)
2718 lock.context = context;
2719 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
2720 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
2721 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
2722 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
2723 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2724 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2725 if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2731 * Get IRQ from bus ID.
2733 * \param fd file descriptor.
2734 * \param busnum bus number.
2735 * \param devnum device number.
2736 * \param funcnum function number.
2738 * \return IRQ number on success, or a negative value on failure.
2741 * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2742 * arguments in a drm_irq_busid structure.
2744 drm_public int drmGetInterruptFromBusID(int fd, int busnum, int devnum,
2752 p.funcnum = funcnum;
2753 if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2758 drm_public int drmAddContextTag(int fd, drm_context_t context, void *tag)
2760 drmHashEntry *entry = drmGetEntry(fd);
2762 if (drmHashInsert(entry->tagTable, context, tag)) {
2763 drmHashDelete(entry->tagTable, context);
2764 drmHashInsert(entry->tagTable, context, tag);
2769 drm_public int drmDelContextTag(int fd, drm_context_t context)
2771 drmHashEntry *entry = drmGetEntry(fd);
2773 return drmHashDelete(entry->tagTable, context);
2776 drm_public void *drmGetContextTag(int fd, drm_context_t context)
2778 drmHashEntry *entry = drmGetEntry(fd);
2781 if (drmHashLookup(entry->tagTable, context, &value))
2787 drm_public int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2788 drm_handle_t handle)
2790 drm_ctx_priv_map_t map;
2793 map.ctx_id = ctx_id;
2794 map.handle = (void *)(uintptr_t)handle;
2796 if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2801 drm_public int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2802 drm_handle_t *handle)
2804 drm_ctx_priv_map_t map;
2807 map.ctx_id = ctx_id;
2809 if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2812 *handle = (drm_handle_t)(uintptr_t)map.handle;
2817 drm_public int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2818 drmMapType *type, drmMapFlags *flags,
2819 drm_handle_t *handle, int *mtrr)
2825 if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2827 *offset = map.offset;
2829 *type = (drmMapType)map.type;
2830 *flags = (drmMapFlags)map.flags;
2831 *handle = (unsigned long)map.handle;
2836 drm_public int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2837 unsigned long *magic, unsigned long *iocs)
2839 drm_client_t client;
2843 if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2845 *auth = client.auth;
2848 *magic = client.magic;
2849 *iocs = client.iocs;
2853 drm_public int drmGetStats(int fd, drmStatsT *stats)
2859 if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2863 memset(stats, 0, sizeof(*stats));
2864 if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2868 stats->data[i].long_format = "%-20.20s"; \
2869 stats->data[i].rate_format = "%8.8s"; \
2870 stats->data[i].isvalue = 1; \
2871 stats->data[i].verbose = 0
2874 stats->data[i].long_format = "%-20.20s"; \
2875 stats->data[i].rate_format = "%5.5s"; \
2876 stats->data[i].isvalue = 0; \
2877 stats->data[i].mult_names = "kgm"; \
2878 stats->data[i].mult = 1000; \
2879 stats->data[i].verbose = 0
2882 stats->data[i].long_format = "%-20.20s"; \
2883 stats->data[i].rate_format = "%5.5s"; \
2884 stats->data[i].isvalue = 0; \
2885 stats->data[i].mult_names = "KGM"; \
2886 stats->data[i].mult = 1024; \
2887 stats->data[i].verbose = 0
2890 stats->count = s.count;
2891 for (i = 0; i < s.count; i++) {
2892 stats->data[i].value = s.data[i].value;
2893 switch (s.data[i].type) {
2894 case _DRM_STAT_LOCK:
2895 stats->data[i].long_name = "Lock";
2896 stats->data[i].rate_name = "Lock";
2899 case _DRM_STAT_OPENS:
2900 stats->data[i].long_name = "Opens";
2901 stats->data[i].rate_name = "O";
2903 stats->data[i].verbose = 1;
2905 case _DRM_STAT_CLOSES:
2906 stats->data[i].long_name = "Closes";
2907 stats->data[i].rate_name = "Lock";
2909 stats->data[i].verbose = 1;
2911 case _DRM_STAT_IOCTLS:
2912 stats->data[i].long_name = "Ioctls";
2913 stats->data[i].rate_name = "Ioc/s";
2916 case _DRM_STAT_LOCKS:
2917 stats->data[i].long_name = "Locks";
2918 stats->data[i].rate_name = "Lck/s";
2921 case _DRM_STAT_UNLOCKS:
2922 stats->data[i].long_name = "Unlocks";
2923 stats->data[i].rate_name = "Unl/s";
2927 stats->data[i].long_name = "IRQs";
2928 stats->data[i].rate_name = "IRQ/s";
2931 case _DRM_STAT_PRIMARY:
2932 stats->data[i].long_name = "Primary Bytes";
2933 stats->data[i].rate_name = "PB/s";
2936 case _DRM_STAT_SECONDARY:
2937 stats->data[i].long_name = "Secondary Bytes";
2938 stats->data[i].rate_name = "SB/s";
2942 stats->data[i].long_name = "DMA";
2943 stats->data[i].rate_name = "DMA/s";
2946 case _DRM_STAT_SPECIAL:
2947 stats->data[i].long_name = "Special DMA";
2948 stats->data[i].rate_name = "dma/s";
2951 case _DRM_STAT_MISSED:
2952 stats->data[i].long_name = "Miss";
2953 stats->data[i].rate_name = "Ms/s";
2956 case _DRM_STAT_VALUE:
2957 stats->data[i].long_name = "Value";
2958 stats->data[i].rate_name = "Value";
2961 case _DRM_STAT_BYTE:
2962 stats->data[i].long_name = "Bytes";
2963 stats->data[i].rate_name = "B/s";
2966 case _DRM_STAT_COUNT:
2968 stats->data[i].long_name = "Count";
2969 stats->data[i].rate_name = "Cnt/s";
2978 * Issue a set-version ioctl.
2980 * \param fd file descriptor.
2981 * \param drmCommandIndex command index
2982 * \param data source pointer of the data to be read and written.
2983 * \param size size of the data to be read and written.
2985 * \return zero on success, or a negative value on failure.
2988 * It issues a read-write ioctl given by
2989 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
2991 drm_public int drmSetInterfaceVersion(int fd, drmSetVersion *version)
2994 drm_set_version_t sv;
2997 sv.drm_di_major = version->drm_di_major;
2998 sv.drm_di_minor = version->drm_di_minor;
2999 sv.drm_dd_major = version->drm_dd_major;
3000 sv.drm_dd_minor = version->drm_dd_minor;
3002 if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
3006 version->drm_di_major = sv.drm_di_major;
3007 version->drm_di_minor = sv.drm_di_minor;
3008 version->drm_dd_major = sv.drm_dd_major;
3009 version->drm_dd_minor = sv.drm_dd_minor;
3015 * Send a device-specific command.
3017 * \param fd file descriptor.
3018 * \param drmCommandIndex command index
3020 * \return zero on success, or a negative value on failure.
3023 * It issues a ioctl given by
3024 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
3026 drm_public int drmCommandNone(int fd, unsigned long drmCommandIndex)
3028 unsigned long request;
3030 request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
3032 if (drmIoctl(fd, request, NULL)) {
3040 * Send a device-specific read command.
3042 * \param fd file descriptor.
3043 * \param drmCommandIndex command index
3044 * \param data destination pointer of the data to be read.
3045 * \param size size of the data to be read.
3047 * \return zero on success, or a negative value on failure.
3050 * It issues a read ioctl given by
3051 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
3053 drm_public int drmCommandRead(int fd, unsigned long drmCommandIndex,
3054 void *data, unsigned long size)
3056 unsigned long request;
3058 request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
3059 DRM_COMMAND_BASE + drmCommandIndex, size);
3061 if (drmIoctl(fd, request, data)) {
3069 * Send a device-specific write command.
3071 * \param fd file descriptor.
3072 * \param drmCommandIndex command index
3073 * \param data source pointer of the data to be written.
3074 * \param size size of the data to be written.
3076 * \return zero on success, or a negative value on failure.
3079 * It issues a write ioctl given by
3080 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
3082 drm_public int drmCommandWrite(int fd, unsigned long drmCommandIndex,
3083 void *data, unsigned long size)
3085 unsigned long request;
3087 request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
3088 DRM_COMMAND_BASE + drmCommandIndex, size);
3090 if (drmIoctl(fd, request, data)) {
3098 * Send a device-specific read-write command.
3100 * \param fd file descriptor.
3101 * \param drmCommandIndex command index
3102 * \param data source pointer of the data to be read and written.
3103 * \param size size of the data to be read and written.
3105 * \return zero on success, or a negative value on failure.
3108 * It issues a read-write ioctl given by
3109 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
3111 drm_public int drmCommandWriteRead(int fd, unsigned long drmCommandIndex,
3112 void *data, unsigned long size)
3114 unsigned long request;
3116 request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
3117 DRM_COMMAND_BASE + drmCommandIndex, size);
3119 if (drmIoctl(fd, request, data))
3124 #define DRM_MAX_FDS 16
3130 } connection[DRM_MAX_FDS];
3132 static int nr_fds = 0;
3134 drm_public int drmOpenOnce(void *unused, const char *BusID, int *newlyopened)
3136 return drmOpenOnceWithType(BusID, newlyopened, DRM_NODE_PRIMARY);
3139 drm_public int drmOpenOnceWithType(const char *BusID, int *newlyopened,
3145 for (i = 0; i < nr_fds; i++)
3146 if ((strcmp(BusID, connection[i].BusID) == 0) &&
3147 (connection[i].type == type)) {
3148 connection[i].refcount++;
3150 return connection[i].fd;
3153 fd = drmOpenWithType(NULL, BusID, type);
3154 if (fd < 0 || nr_fds == DRM_MAX_FDS)
3157 connection[nr_fds].BusID = strdup(BusID);
3158 connection[nr_fds].fd = fd;
3159 connection[nr_fds].refcount = 1;
3160 connection[nr_fds].type = type;
3164 fprintf(stderr, "saved connection %d for %s %d\n",
3165 nr_fds, connection[nr_fds].BusID,
3166 strcmp(BusID, connection[nr_fds].BusID));
3173 drm_public void drmCloseOnce(int fd)
3177 for (i = 0; i < nr_fds; i++) {
3178 if (fd == connection[i].fd) {
3179 if (--connection[i].refcount == 0) {
3180 drmClose(connection[i].fd);
3181 free(connection[i].BusID);
3184 connection[i] = connection[nr_fds];
3192 drm_public int drmSetMaster(int fd)
3194 return drmIoctl(fd, DRM_IOCTL_SET_MASTER, NULL);
3197 drm_public int drmDropMaster(int fd)
3199 return drmIoctl(fd, DRM_IOCTL_DROP_MASTER, NULL);
3202 drm_public int drmIsMaster(int fd)
3204 /* Detect master by attempting something that requires master.
3206 * Authenticating magic tokens requires master and 0 is an
3207 * internal kernel detail which we could use. Attempting this on
3208 * a master fd would fail therefore fail with EINVAL because 0
3211 * A non-master fd will fail with EACCES, as the kernel checks
3212 * for master before attempting to do anything else.
3214 * Since we don't want to leak implementation details, use
3217 return drmAuthMagic(fd, 0) != -EACCES;
3220 drm_public char *drmGetDeviceNameFromFd(int fd)
3227 if (fstat(fd, &sbuf))
3230 maj = major(sbuf.st_rdev);
3231 min = minor(sbuf.st_rdev);
3232 nodetype = drmGetMinorType(maj, min);
3233 return drmGetMinorNameForFD(fd, nodetype);
3240 /* The whole drmOpen thing is a fiasco and we need to find a way
3241 * back to just using open(2). For now, however, lets just make
3242 * things worse with even more ad hoc directory walking code to
3243 * discover the device file name. */
3248 for (i = 0; i < DRM_MAX_MINOR; i++) {
3249 snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
3250 if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
3253 if (i == DRM_MAX_MINOR)
3256 return strdup(name);
3260 static bool drmNodeIsDRM(int maj, int min)
3266 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device/drm",
3268 return stat(path, &sbuf) == 0;
3269 #elif defined(__FreeBSD__)
3270 char name[SPECNAMELEN];
3272 if (!devname_r(makedev(maj, min), S_IFCHR, name, sizeof(name)))
3274 /* Handle drm/ and dri/ as both are present in different FreeBSD version
3275 * FreeBSD on amd64/i386/powerpc external kernel modules create node in
3276 * in /dev/drm/ and links in /dev/dri while a WIP in kernel driver creates
3277 * only device nodes in /dev/dri/ */
3278 return (!strncmp(name, "drm/", 4) || !strncmp(name, "dri/", 4));
3280 return maj == DRM_MAJOR;
3284 drm_public int drmGetNodeTypeFromFd(int fd)
3289 if (fstat(fd, &sbuf))
3292 maj = major(sbuf.st_rdev);
3293 min = minor(sbuf.st_rdev);
3295 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode)) {
3300 type = drmGetMinorType(maj, min);
3306 drm_public int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags,
3309 struct drm_prime_handle args;
3314 args.handle = handle;
3316 ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
3320 *prime_fd = args.fd;
3324 drm_public int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
3326 struct drm_prime_handle args;
3331 ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
3335 *handle = args.handle;
3339 drm_public int drmCloseBufferHandle(int fd, uint32_t handle)
3341 struct drm_gem_close args;
3344 args.handle = handle;
3345 return drmIoctl(fd, DRM_IOCTL_GEM_CLOSE, &args);
3348 static char *drmGetMinorNameForFD(int fd, int type)
3354 const char *name = drmGetMinorName(type);
3356 char dev_name[64], buf[64];
3364 if (fstat(fd, &sbuf))
3367 maj = major(sbuf.st_rdev);
3368 min = minor(sbuf.st_rdev);
3370 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3373 snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
3375 sysdir = opendir(buf);
3379 while ((ent = readdir(sysdir))) {
3380 if (strncmp(ent->d_name, name, len) == 0) {
3381 if (snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
3386 return strdup(dev_name);
3392 #elif defined(__FreeBSD__)
3394 char dname[SPECNAMELEN];
3396 char name[SPECNAMELEN];
3397 int id, maj, min, nodetype, i;
3399 if (fstat(fd, &sbuf))
3402 maj = major(sbuf.st_rdev);
3403 min = minor(sbuf.st_rdev);
3405 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3408 if (!devname_r(sbuf.st_rdev, S_IFCHR, dname, sizeof(dname)))
3411 /* Handle both /dev/drm and /dev/dri
3412 * FreeBSD on amd64/i386/powerpc external kernel modules create node in
3413 * in /dev/drm/ and links in /dev/dri while a WIP in kernel driver creates
3414 * only device nodes in /dev/dri/ */
3416 /* Get the node type represented by fd so we can deduce the target name */
3417 nodetype = drmGetMinorType(maj, min);
3420 mname = drmGetMinorName(type);
3422 for (i = 0; i < SPECNAMELEN; i++) {
3423 if (isalpha(dname[i]) == 0 && dname[i] != '/')
3426 if (dname[i] == '\0')
3429 id = (int)strtol(&dname[i], NULL, 10);
3430 id -= drmGetMinorBase(nodetype);
3431 snprintf(name, sizeof(name), DRM_DIR_NAME "/%s%d", mname,
3432 id + drmGetMinorBase(type));
3434 return strdup(name);
3437 char buf[PATH_MAX + 1];
3438 const char *dev_name = drmGetDeviceName(type);
3439 unsigned int maj, min;
3442 if (fstat(fd, &sbuf))
3445 maj = major(sbuf.st_rdev);
3446 min = minor(sbuf.st_rdev);
3448 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3454 n = snprintf(buf, sizeof(buf), dev_name, DRM_DIR_NAME, min);
3455 if (n == -1 || n >= sizeof(buf))
3462 drm_public char *drmGetPrimaryDeviceNameFromFd(int fd)
3464 return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
3467 drm_public char *drmGetRenderDeviceNameFromFd(int fd)
3469 return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
3473 static char * DRM_PRINTFLIKE(2, 3)
3474 sysfs_uevent_get(const char *path, const char *fmt, ...)
3476 char filename[PATH_MAX + 1], *key, *line = NULL, *value = NULL;
3477 size_t size = 0, len;
3483 num = vasprintf(&key, fmt, ap);
3487 snprintf(filename, sizeof(filename), "%s/uevent", path);
3489 fp = fopen(filename, "r");
3495 while ((num = getline(&line, &size, fp)) >= 0) {
3496 if ((strncmp(line, key, len) == 0) && (line[len] == '=')) {
3497 char *start = line + len + 1, *end = line + num - 1;
3502 value = strndup(start, end - start);
3516 /* Little white lie to avoid major rework of the existing code */
3517 #define DRM_BUS_VIRTIO 0x10
3520 static int get_subsystem_type(const char *device_path)
3522 char path[PATH_MAX + 1] = "";
3523 char link[PATH_MAX + 1] = "";
3529 { "/pci", DRM_BUS_PCI },
3530 { "/usb", DRM_BUS_USB },
3531 { "/platform", DRM_BUS_PLATFORM },
3532 { "/spi", DRM_BUS_PLATFORM },
3533 { "/host1x", DRM_BUS_HOST1X },
3534 { "/virtio", DRM_BUS_VIRTIO },
3537 strncpy(path, device_path, PATH_MAX);
3538 strncat(path, "/subsystem", PATH_MAX);
3540 if (readlink(path, link, PATH_MAX) < 0)
3543 name = strrchr(link, '/');
3547 for (unsigned i = 0; i < ARRAY_SIZE(bus_types); i++) {
3548 if (strncmp(name, bus_types[i].name, strlen(bus_types[i].name)) == 0)
3549 return bus_types[i].bus_type;
3556 static int drmParseSubsystemType(int maj, int min)
3559 char path[PATH_MAX + 1] = "";
3560 char real_path[PATH_MAX + 1] = "";
3563 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3565 subsystem_type = get_subsystem_type(path);
3566 /* Try to get the parent (underlying) device type */
3567 if (subsystem_type == DRM_BUS_VIRTIO) {
3568 /* Assume virtio-pci on error */
3569 if (!realpath(path, real_path))
3570 return DRM_BUS_VIRTIO;
3571 strncat(path, "/..", PATH_MAX);
3572 subsystem_type = get_subsystem_type(path);
3573 if (subsystem_type < 0)
3574 return DRM_BUS_VIRTIO;
3576 return subsystem_type;
3577 #elif defined(__OpenBSD__) || defined(__DragonFly__) || defined(__FreeBSD__)
3580 #warning "Missing implementation of drmParseSubsystemType"
3587 get_pci_path(int maj, int min, char *pci_path)
3589 char path[PATH_MAX + 1], *term;
3591 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3592 if (!realpath(path, pci_path)) {
3593 strcpy(pci_path, path);
3597 term = strrchr(pci_path, '/');
3598 if (term && strncmp(term, "/virtio", 7) == 0)
3604 static int get_sysctl_pci_bus_info(int maj, int min, drmPciBusInfoPtr info)
3606 char dname[SPECNAMELEN];
3607 char sysctl_name[16];
3608 char sysctl_val[256];
3610 int id, type, nelem;
3611 unsigned int rdev, majmin, domain, bus, dev, func;
3613 rdev = makedev(maj, min);
3614 if (!devname_r(rdev, S_IFCHR, dname, sizeof(dname)))
3617 if (sscanf(dname, "drm/%d\n", &id) != 1)
3619 type = drmGetMinorType(maj, min);
3623 /* BUG: This above section is iffy, since it mandates that a driver will
3624 * create both card and render node.
3625 * If it does not, the next DRM device will create card#X and
3626 * renderD#(128+X)-1.
3627 * This is a possibility in FreeBSD but for now there is no good way for
3628 * obtaining the info.
3631 case DRM_NODE_PRIMARY:
3633 case DRM_NODE_CONTROL:
3636 case DRM_NODE_RENDER:
3643 if (snprintf(sysctl_name, sizeof(sysctl_name), "hw.dri.%d.busid", id) <= 0)
3645 sysctl_len = sizeof(sysctl_val);
3646 if (sysctlbyname(sysctl_name, sysctl_val, &sysctl_len, NULL, 0))
3649 #define bus_fmt "pci:%04x:%02x:%02x.%u"
3651 nelem = sscanf(sysctl_val, bus_fmt, &domain, &bus, &dev, &func);
3654 info->domain = domain;
3663 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
3666 unsigned int domain, bus, dev, func;
3667 char pci_path[PATH_MAX + 1], *value;
3670 get_pci_path(maj, min, pci_path);
3672 value = sysfs_uevent_get(pci_path, "PCI_SLOT_NAME");
3676 num = sscanf(value, "%04x:%02x:%02x.%1u", &domain, &bus, &dev, &func);
3682 info->domain = domain;
3688 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3689 struct drm_pciinfo pinfo;
3692 type = drmGetMinorType(maj, min);
3696 fd = drmOpenMinor(min, 0, type);
3700 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3706 info->domain = pinfo.domain;
3707 info->bus = pinfo.bus;
3708 info->dev = pinfo.dev;
3709 info->func = pinfo.func;
3712 #elif defined(__FreeBSD__)
3713 return get_sysctl_pci_bus_info(maj, min, info);
3715 #warning "Missing implementation of drmParsePciBusInfo"
3720 drm_public int drmDevicesEqual(drmDevicePtr a, drmDevicePtr b)
3722 if (a == NULL || b == NULL)
3725 if (a->bustype != b->bustype)
3728 switch (a->bustype) {
3730 return memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo)) == 0;
3733 return memcmp(a->businfo.usb, b->businfo.usb, sizeof(drmUsbBusInfo)) == 0;
3735 case DRM_BUS_PLATFORM:
3736 return memcmp(a->businfo.platform, b->businfo.platform, sizeof(drmPlatformBusInfo)) == 0;
3738 case DRM_BUS_HOST1X:
3739 return memcmp(a->businfo.host1x, b->businfo.host1x, sizeof(drmHost1xBusInfo)) == 0;
3748 static int drmGetNodeType(const char *name)
3750 if (strncmp(name, DRM_CONTROL_MINOR_NAME,
3751 sizeof(DRM_CONTROL_MINOR_NAME ) - 1) == 0)
3752 return DRM_NODE_CONTROL;
3754 if (strncmp(name, DRM_RENDER_MINOR_NAME,
3755 sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
3756 return DRM_NODE_RENDER;
3758 if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
3759 sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
3760 return DRM_NODE_PRIMARY;
3765 static int drmGetMaxNodeName(void)
3767 return sizeof(DRM_DIR_NAME) +
3768 MAX3(sizeof(DRM_PRIMARY_MINOR_NAME),
3769 sizeof(DRM_CONTROL_MINOR_NAME),
3770 sizeof(DRM_RENDER_MINOR_NAME)) +
3771 3 /* length of the node number */;
3775 static int parse_separate_sysfs_files(int maj, int min,
3776 drmPciDeviceInfoPtr device,
3777 bool ignore_revision)
3779 static const char *attrs[] = {
3780 "revision", /* Older kernels are missing the file, so check for it first */
3786 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3787 unsigned int data[ARRAY_SIZE(attrs)];
3791 get_pci_path(maj, min, pci_path);
3793 for (unsigned i = ignore_revision ? 1 : 0; i < ARRAY_SIZE(attrs); i++) {
3794 if (snprintf(path, PATH_MAX, "%s/%s", pci_path, attrs[i]) < 0)
3797 fp = fopen(path, "r");
3801 ret = fscanf(fp, "%x", &data[i]);
3808 device->revision_id = ignore_revision ? 0xff : data[0] & 0xff;
3809 device->vendor_id = data[1] & 0xffff;
3810 device->device_id = data[2] & 0xffff;
3811 device->subvendor_id = data[3] & 0xffff;
3812 device->subdevice_id = data[4] & 0xffff;
3817 static int parse_config_sysfs_file(int maj, int min,
3818 drmPciDeviceInfoPtr device)
3820 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3821 unsigned char config[64];
3824 get_pci_path(maj, min, pci_path);
3826 if (snprintf(path, PATH_MAX, "%s/config", pci_path) < 0)
3829 fd = open(path, O_RDONLY);
3833 ret = read(fd, config, sizeof(config));
3838 device->vendor_id = config[0] | (config[1] << 8);
3839 device->device_id = config[2] | (config[3] << 8);
3840 device->revision_id = config[8];
3841 device->subvendor_id = config[44] | (config[45] << 8);
3842 device->subdevice_id = config[46] | (config[47] << 8);
3848 static int drmParsePciDeviceInfo(int maj, int min,
3849 drmPciDeviceInfoPtr device,
3853 if (!(flags & DRM_DEVICE_GET_PCI_REVISION))
3854 return parse_separate_sysfs_files(maj, min, device, true);
3856 if (parse_separate_sysfs_files(maj, min, device, false))
3857 return parse_config_sysfs_file(maj, min, device);
3860 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3861 struct drm_pciinfo pinfo;
3864 type = drmGetMinorType(maj, min);
3868 fd = drmOpenMinor(min, 0, type);
3872 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3878 device->vendor_id = pinfo.vendor_id;
3879 device->device_id = pinfo.device_id;
3880 device->revision_id = pinfo.revision_id;
3881 device->subvendor_id = pinfo.subvendor_id;
3882 device->subdevice_id = pinfo.subdevice_id;
3885 #elif defined(__FreeBSD__)
3887 struct pci_conf_io pc;
3888 struct pci_match_conf patterns[1];
3889 struct pci_conf results[1];
3892 if (get_sysctl_pci_bus_info(maj, min, &info) != 0)
3895 fd = open("/dev/pci", O_RDONLY, 0);
3899 bzero(&patterns, sizeof(patterns));
3900 patterns[0].pc_sel.pc_domain = info.domain;
3901 patterns[0].pc_sel.pc_bus = info.bus;
3902 patterns[0].pc_sel.pc_dev = info.dev;
3903 patterns[0].pc_sel.pc_func = info.func;
3904 patterns[0].flags = PCI_GETCONF_MATCH_DOMAIN | PCI_GETCONF_MATCH_BUS
3905 | PCI_GETCONF_MATCH_DEV | PCI_GETCONF_MATCH_FUNC;
3906 bzero(&pc, sizeof(struct pci_conf_io));
3907 pc.num_patterns = 1;
3908 pc.pat_buf_len = sizeof(patterns);
3909 pc.patterns = patterns;
3910 pc.match_buf_len = sizeof(results);
3911 pc.matches = results;
3913 if (ioctl(fd, PCIOCGETCONF, &pc) || pc.status == PCI_GETCONF_ERROR) {
3920 device->vendor_id = results[0].pc_vendor;
3921 device->device_id = results[0].pc_device;
3922 device->subvendor_id = results[0].pc_subvendor;
3923 device->subdevice_id = results[0].pc_subdevice;
3924 device->revision_id = results[0].pc_revid;
3928 #warning "Missing implementation of drmParsePciDeviceInfo"
3933 static void drmFreePlatformDevice(drmDevicePtr device)
3935 if (device->deviceinfo.platform) {
3936 if (device->deviceinfo.platform->compatible) {
3937 char **compatible = device->deviceinfo.platform->compatible;
3939 while (*compatible) {
3944 free(device->deviceinfo.platform->compatible);
3949 static void drmFreeHost1xDevice(drmDevicePtr device)
3951 if (device->deviceinfo.host1x) {
3952 if (device->deviceinfo.host1x->compatible) {
3953 char **compatible = device->deviceinfo.host1x->compatible;
3955 while (*compatible) {
3960 free(device->deviceinfo.host1x->compatible);
3965 drm_public void drmFreeDevice(drmDevicePtr *device)
3971 switch ((*device)->bustype) {
3972 case DRM_BUS_PLATFORM:
3973 drmFreePlatformDevice(*device);
3976 case DRM_BUS_HOST1X:
3977 drmFreeHost1xDevice(*device);
3986 drm_public void drmFreeDevices(drmDevicePtr devices[], int count)
3990 if (devices == NULL)
3993 for (i = 0; i < count; i++)
3995 drmFreeDevice(&devices[i]);
3998 static drmDevicePtr drmDeviceAlloc(unsigned int type, const char *node,
3999 size_t bus_size, size_t device_size,
4002 size_t max_node_length, extra, size;
4003 drmDevicePtr device;
4007 max_node_length = ALIGN(drmGetMaxNodeName(), sizeof(void *));
4008 extra = DRM_NODE_MAX * (sizeof(void *) + max_node_length);
4010 size = sizeof(*device) + extra + bus_size + device_size;
4012 device = calloc(1, size);
4016 device->available_nodes = 1 << type;
4018 ptr = (char *)device + sizeof(*device);
4019 device->nodes = (char **)ptr;
4021 ptr += DRM_NODE_MAX * sizeof(void *);
4023 for (i = 0; i < DRM_NODE_MAX; i++) {
4024 device->nodes[i] = ptr;
4025 ptr += max_node_length;
4028 memcpy(device->nodes[type], node, max_node_length);
4035 static int drmProcessPciDevice(drmDevicePtr *device,
4036 const char *node, int node_type,
4037 int maj, int min, bool fetch_deviceinfo,
4044 dev = drmDeviceAlloc(node_type, node, sizeof(drmPciBusInfo),
4045 sizeof(drmPciDeviceInfo), &addr);
4049 dev->bustype = DRM_BUS_PCI;
4051 dev->businfo.pci = (drmPciBusInfoPtr)addr;
4053 ret = drmParsePciBusInfo(maj, min, dev->businfo.pci);
4057 // Fetch the device info if the user has requested it
4058 if (fetch_deviceinfo) {
4059 addr += sizeof(drmPciBusInfo);
4060 dev->deviceinfo.pci = (drmPciDeviceInfoPtr)addr;
4062 ret = drmParsePciDeviceInfo(maj, min, dev->deviceinfo.pci, flags);
4077 static int drm_usb_dev_path(int maj, int min, char *path, size_t len)
4079 char *value, *tmp_path, *slash;
4080 bool usb_device, usb_interface;
4082 snprintf(path, len, "/sys/dev/char/%d:%d/device", maj, min);
4084 value = sysfs_uevent_get(path, "DEVTYPE");
4088 usb_device = strcmp(value, "usb_device") == 0;
4089 usb_interface = strcmp(value, "usb_interface") == 0;
4097 /* The parent of a usb_interface is a usb_device */
4099 tmp_path = realpath(path, NULL);
4103 slash = strrchr(tmp_path, '/');
4111 if (snprintf(path, len, "%s", tmp_path) >= (int)len) {
4121 static int drmParseUsbBusInfo(int maj, int min, drmUsbBusInfoPtr info)
4124 char path[PATH_MAX + 1], *value;
4125 unsigned int bus, dev;
4128 ret = drm_usb_dev_path(maj, min, path, sizeof(path));
4132 value = sysfs_uevent_get(path, "BUSNUM");
4136 ret = sscanf(value, "%03u", &bus);
4142 value = sysfs_uevent_get(path, "DEVNUM");
4146 ret = sscanf(value, "%03u", &dev);
4157 #warning "Missing implementation of drmParseUsbBusInfo"
4162 static int drmParseUsbDeviceInfo(int maj, int min, drmUsbDeviceInfoPtr info)
4165 char path[PATH_MAX + 1], *value;
4166 unsigned int vendor, product;
4169 ret = drm_usb_dev_path(maj, min, path, sizeof(path));
4173 value = sysfs_uevent_get(path, "PRODUCT");
4177 ret = sscanf(value, "%x/%x", &vendor, &product);
4183 info->vendor = vendor;
4184 info->product = product;
4188 #warning "Missing implementation of drmParseUsbDeviceInfo"
4193 static int drmProcessUsbDevice(drmDevicePtr *device, const char *node,
4194 int node_type, int maj, int min,
4195 bool fetch_deviceinfo, uint32_t flags)
4201 dev = drmDeviceAlloc(node_type, node, sizeof(drmUsbBusInfo),
4202 sizeof(drmUsbDeviceInfo), &ptr);
4206 dev->bustype = DRM_BUS_USB;
4208 dev->businfo.usb = (drmUsbBusInfoPtr)ptr;
4210 ret = drmParseUsbBusInfo(maj, min, dev->businfo.usb);
4214 if (fetch_deviceinfo) {
4215 ptr += sizeof(drmUsbBusInfo);
4216 dev->deviceinfo.usb = (drmUsbDeviceInfoPtr)ptr;
4218 ret = drmParseUsbDeviceInfo(maj, min, dev->deviceinfo.usb);
4232 static int drmParseOFBusInfo(int maj, int min, char *fullname)
4235 char path[PATH_MAX + 1], *name, *tmp_name;
4237 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
4239 name = sysfs_uevent_get(path, "OF_FULLNAME");
4242 /* If the device lacks OF data, pick the MODALIAS info */
4243 name = sysfs_uevent_get(path, "MODALIAS");
4247 /* .. and strip the MODALIAS=[platform,usb...]: part. */
4248 tmp_name = strrchr(name, ':');
4256 strncpy(fullname, tmp_name, DRM_PLATFORM_DEVICE_NAME_LEN);
4257 fullname[DRM_PLATFORM_DEVICE_NAME_LEN - 1] = '\0';
4262 #warning "Missing implementation of drmParseOFBusInfo"
4267 static int drmParseOFDeviceInfo(int maj, int min, char ***compatible)
4270 char path[PATH_MAX + 1], *value, *tmp_name;
4271 unsigned int count, i;
4274 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
4276 value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
4278 sscanf(value, "%u", &count);
4281 /* Assume one entry if the device lack OF data */
4285 *compatible = calloc(count + 1, sizeof(char *));
4289 for (i = 0; i < count; i++) {
4290 value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
4293 /* If the device lacks OF data, pick the MODALIAS info */
4294 value = sysfs_uevent_get(path, "MODALIAS");
4300 /* .. and strip the MODALIAS=[platform,usb...]: part. */
4301 tmp_name = strrchr(value, ':');
4306 tmp_name = strdup(tmp_name + 1);
4310 (*compatible)[i] = tmp_name;
4317 free((*compatible)[i]);
4322 #warning "Missing implementation of drmParseOFDeviceInfo"
4327 static int drmProcessPlatformDevice(drmDevicePtr *device,
4328 const char *node, int node_type,
4329 int maj, int min, bool fetch_deviceinfo,
4336 dev = drmDeviceAlloc(node_type, node, sizeof(drmPlatformBusInfo),
4337 sizeof(drmPlatformDeviceInfo), &ptr);
4341 dev->bustype = DRM_BUS_PLATFORM;
4343 dev->businfo.platform = (drmPlatformBusInfoPtr)ptr;
4345 ret = drmParseOFBusInfo(maj, min, dev->businfo.platform->fullname);
4349 if (fetch_deviceinfo) {
4350 ptr += sizeof(drmPlatformBusInfo);
4351 dev->deviceinfo.platform = (drmPlatformDeviceInfoPtr)ptr;
4353 ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.platform->compatible);
4367 static int drmProcessHost1xDevice(drmDevicePtr *device,
4368 const char *node, int node_type,
4369 int maj, int min, bool fetch_deviceinfo,
4376 dev = drmDeviceAlloc(node_type, node, sizeof(drmHost1xBusInfo),
4377 sizeof(drmHost1xDeviceInfo), &ptr);
4381 dev->bustype = DRM_BUS_HOST1X;
4383 dev->businfo.host1x = (drmHost1xBusInfoPtr)ptr;
4385 ret = drmParseOFBusInfo(maj, min, dev->businfo.host1x->fullname);
4389 if (fetch_deviceinfo) {
4390 ptr += sizeof(drmHost1xBusInfo);
4391 dev->deviceinfo.host1x = (drmHost1xDeviceInfoPtr)ptr;
4393 ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.host1x->compatible);
4408 process_device(drmDevicePtr *device, const char *d_name,
4409 int req_subsystem_type,
4410 bool fetch_deviceinfo, uint32_t flags)
4413 char node[PATH_MAX + 1];
4414 int node_type, subsystem_type;
4415 unsigned int maj, min;
4417 node_type = drmGetNodeType(d_name);
4421 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, d_name);
4422 if (stat(node, &sbuf))
4425 maj = major(sbuf.st_rdev);
4426 min = minor(sbuf.st_rdev);
4428 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4431 subsystem_type = drmParseSubsystemType(maj, min);
4432 if (req_subsystem_type != -1 && req_subsystem_type != subsystem_type)
4435 switch (subsystem_type) {
4437 case DRM_BUS_VIRTIO:
4438 return drmProcessPciDevice(device, node, node_type, maj, min,
4439 fetch_deviceinfo, flags);
4441 return drmProcessUsbDevice(device, node, node_type, maj, min,
4442 fetch_deviceinfo, flags);
4443 case DRM_BUS_PLATFORM:
4444 return drmProcessPlatformDevice(device, node, node_type, maj, min,
4445 fetch_deviceinfo, flags);
4446 case DRM_BUS_HOST1X:
4447 return drmProcessHost1xDevice(device, node, node_type, maj, min,
4448 fetch_deviceinfo, flags);
4454 /* Consider devices located on the same bus as duplicate and fold the respective
4455 * entries into a single one.
4457 * Note: this leaves "gaps" in the array, while preserving the length.
4459 static void drmFoldDuplicatedDevices(drmDevicePtr local_devices[], int count)
4461 int node_type, i, j;
4463 for (i = 0; i < count; i++) {
4464 for (j = i + 1; j < count; j++) {
4465 if (drmDevicesEqual(local_devices[i], local_devices[j])) {
4466 local_devices[i]->available_nodes |= local_devices[j]->available_nodes;
4467 node_type = log2_int(local_devices[j]->available_nodes);
4468 memcpy(local_devices[i]->nodes[node_type],
4469 local_devices[j]->nodes[node_type], drmGetMaxNodeName());
4470 drmFreeDevice(&local_devices[j]);
4476 /* Check that the given flags are valid returning 0 on success */
4478 drm_device_validate_flags(uint32_t flags)
4480 return (flags & ~DRM_DEVICE_GET_PCI_REVISION);
4484 drm_device_has_rdev(drmDevicePtr device, dev_t find_rdev)
4488 for (int i = 0; i < DRM_NODE_MAX; i++) {
4489 if (device->available_nodes & 1 << i) {
4490 if (stat(device->nodes[i], &sbuf) == 0 &&
4491 sbuf.st_rdev == find_rdev)
4499 * The kernel drm core has a number of places that assume maximum of
4500 * 3x64 devices nodes. That's 64 for each of primary, control and
4501 * render nodes. Rounded it up to 256 for simplicity.
4503 #define MAX_DRM_NODES 256
4506 * Get information about a device from its dev_t identifier
4508 * \param find_rdev dev_t identifier of the device
4509 * \param flags feature/behaviour bitmask
4510 * \param device the address of a drmDevicePtr where the information
4511 * will be allocated in stored
4513 * \return zero on success, negative error code otherwise.
4515 drm_public int drmGetDeviceFromDevId(dev_t find_rdev, uint32_t flags, drmDevicePtr *device)
4519 * DRI device nodes on OpenBSD are not in their own directory, they reside
4520 * in /dev along with a large number of statically generated /dev nodes.
4521 * Avoid stat'ing all of /dev needlessly by implementing this custom path.
4524 char node[PATH_MAX + 1];
4525 const char *dev_name;
4526 int node_type, subsystem_type;
4527 int maj, min, n, ret;
4532 maj = major(find_rdev);
4533 min = minor(find_rdev);
4535 if (!drmNodeIsDRM(maj, min))
4538 node_type = drmGetMinorType(maj, min);
4539 if (node_type == -1)
4542 dev_name = drmGetDeviceName(node_type);
4546 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min);
4547 if (n == -1 || n >= PATH_MAX)
4549 if (stat(node, &sbuf))
4552 subsystem_type = drmParseSubsystemType(maj, min);
4553 if (subsystem_type != DRM_BUS_PCI)
4556 ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
4564 drmDevicePtr local_devices[MAX_DRM_NODES];
4567 struct dirent *dent;
4570 int ret, i, node_count;
4572 if (drm_device_validate_flags(flags))
4578 maj = major(find_rdev);
4579 min = minor(find_rdev);
4581 if (!drmNodeIsDRM(maj, min))
4584 subsystem_type = drmParseSubsystemType(maj, min);
4585 if (subsystem_type < 0)
4586 return subsystem_type;
4588 sysdir = opendir(DRM_DIR_NAME);
4593 while ((dent = readdir(sysdir))) {
4594 ret = process_device(&d, dent->d_name, subsystem_type, true, flags);
4598 if (i >= MAX_DRM_NODES) {
4599 fprintf(stderr, "More than %d drm nodes detected. "
4600 "Please report a bug - that should not happen.\n"
4601 "Skipping extra nodes\n", MAX_DRM_NODES);
4604 local_devices[i] = d;
4609 drmFoldDuplicatedDevices(local_devices, node_count);
4613 for (i = 0; i < node_count; i++) {
4614 if (!local_devices[i])
4617 if (drm_device_has_rdev(local_devices[i], find_rdev))
4618 *device = local_devices[i];
4620 drmFreeDevice(&local_devices[i]);
4624 if (*device == NULL)
4631 * Get information about the opened drm device
4633 * \param fd file descriptor of the drm device
4634 * \param flags feature/behaviour bitmask
4635 * \param device the address of a drmDevicePtr where the information
4636 * will be allocated in stored
4638 * \return zero on success, negative error code otherwise.
4640 * \note Unlike drmGetDevice it does not retrieve the pci device revision field
4641 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
4643 drm_public int drmGetDevice2(int fd, uint32_t flags, drmDevicePtr *device)
4650 if (fstat(fd, &sbuf))
4653 if (!S_ISCHR(sbuf.st_mode))
4656 return drmGetDeviceFromDevId(sbuf.st_rdev, flags, device);
4660 * Get information about the opened drm device
4662 * \param fd file descriptor of the drm device
4663 * \param device the address of a drmDevicePtr where the information
4664 * will be allocated in stored
4666 * \return zero on success, negative error code otherwise.
4668 drm_public int drmGetDevice(int fd, drmDevicePtr *device)
4670 return drmGetDevice2(fd, DRM_DEVICE_GET_PCI_REVISION, device);
4674 * Get drm devices on the system
4676 * \param flags feature/behaviour bitmask
4677 * \param devices the array of devices with drmDevicePtr elements
4678 * can be NULL to get the device number first
4679 * \param max_devices the maximum number of devices for the array
4681 * \return on error - negative error code,
4682 * if devices is NULL - total number of devices available on the system,
4683 * alternatively the number of devices stored in devices[], which is
4684 * capped by the max_devices.
4686 * \note Unlike drmGetDevices it does not retrieve the pci device revision field
4687 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
4689 drm_public int drmGetDevices2(uint32_t flags, drmDevicePtr devices[],
4692 drmDevicePtr local_devices[MAX_DRM_NODES];
4693 drmDevicePtr device;
4695 struct dirent *dent;
4696 int ret, i, node_count, device_count;
4698 if (drm_device_validate_flags(flags))
4701 sysdir = opendir(DRM_DIR_NAME);
4706 while ((dent = readdir(sysdir))) {
4707 ret = process_device(&device, dent->d_name, -1, devices != NULL, flags);
4711 if (i >= MAX_DRM_NODES) {
4712 fprintf(stderr, "More than %d drm nodes detected. "
4713 "Please report a bug - that should not happen.\n"
4714 "Skipping extra nodes\n", MAX_DRM_NODES);
4717 local_devices[i] = device;
4722 drmFoldDuplicatedDevices(local_devices, node_count);
4725 for (i = 0; i < node_count; i++) {
4726 if (!local_devices[i])
4729 if ((devices != NULL) && (device_count < max_devices))
4730 devices[device_count] = local_devices[i];
4732 drmFreeDevice(&local_devices[i]);
4739 if (devices != NULL)
4740 return MIN2(device_count, max_devices);
4742 return device_count;
4746 * Get drm devices on the system
4748 * \param devices the array of devices with drmDevicePtr elements
4749 * can be NULL to get the device number first
4750 * \param max_devices the maximum number of devices for the array
4752 * \return on error - negative error code,
4753 * if devices is NULL - total number of devices available on the system,
4754 * alternatively the number of devices stored in devices[], which is
4755 * capped by the max_devices.
4757 drm_public int drmGetDevices(drmDevicePtr devices[], int max_devices)
4759 return drmGetDevices2(DRM_DEVICE_GET_PCI_REVISION, devices, max_devices);
4762 drm_public char *drmGetDeviceNameFromFd2(int fd)
4766 char path[PATH_MAX + 1], *value;
4767 unsigned int maj, min;
4769 if (fstat(fd, &sbuf))
4772 maj = major(sbuf.st_rdev);
4773 min = minor(sbuf.st_rdev);
4775 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4778 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d", maj, min);
4780 value = sysfs_uevent_get(path, "DEVNAME");
4784 snprintf(path, sizeof(path), "/dev/%s", value);
4787 return strdup(path);
4788 #elif defined(__FreeBSD__)
4789 return drmGetDeviceNameFromFd(fd);
4792 char node[PATH_MAX + 1];
4793 const char *dev_name;
4797 if (fstat(fd, &sbuf))
4800 maj = major(sbuf.st_rdev);
4801 min = minor(sbuf.st_rdev);
4803 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4806 node_type = drmGetMinorType(maj, min);
4807 if (node_type == -1)
4810 dev_name = drmGetDeviceName(node_type);
4814 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min);
4815 if (n == -1 || n >= PATH_MAX)
4818 return strdup(node);
4822 drm_public int drmSyncobjCreate(int fd, uint32_t flags, uint32_t *handle)
4824 struct drm_syncobj_create args;
4830 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_CREATE, &args);
4833 *handle = args.handle;
4837 drm_public int drmSyncobjDestroy(int fd, uint32_t handle)
4839 struct drm_syncobj_destroy args;
4842 args.handle = handle;
4843 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_DESTROY, &args);
4846 drm_public int drmSyncobjHandleToFD(int fd, uint32_t handle, int *obj_fd)
4848 struct drm_syncobj_handle args;
4853 args.handle = handle;
4854 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4861 drm_public int drmSyncobjFDToHandle(int fd, int obj_fd, uint32_t *handle)
4863 struct drm_syncobj_handle args;
4869 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4872 *handle = args.handle;
4876 drm_public int drmSyncobjImportSyncFile(int fd, uint32_t handle,
4879 struct drm_syncobj_handle args;
4882 args.fd = sync_file_fd;
4883 args.handle = handle;
4884 args.flags = DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE;
4885 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4888 drm_public int drmSyncobjExportSyncFile(int fd, uint32_t handle,
4891 struct drm_syncobj_handle args;
4896 args.handle = handle;
4897 args.flags = DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE;
4898 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4901 *sync_file_fd = args.fd;
4905 drm_public int drmSyncobjWait(int fd, uint32_t *handles, unsigned num_handles,
4906 int64_t timeout_nsec, unsigned flags,
4907 uint32_t *first_signaled)
4909 struct drm_syncobj_wait args;
4913 args.handles = (uintptr_t)handles;
4914 args.timeout_nsec = timeout_nsec;
4915 args.count_handles = num_handles;
4918 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_WAIT, &args);
4923 *first_signaled = args.first_signaled;
4927 drm_public int drmSyncobjReset(int fd, const uint32_t *handles,
4928 uint32_t handle_count)
4930 struct drm_syncobj_array args;
4934 args.handles = (uintptr_t)handles;
4935 args.count_handles = handle_count;
4937 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_RESET, &args);
4941 drm_public int drmSyncobjSignal(int fd, const uint32_t *handles,
4942 uint32_t handle_count)
4944 struct drm_syncobj_array args;
4948 args.handles = (uintptr_t)handles;
4949 args.count_handles = handle_count;
4951 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_SIGNAL, &args);
4955 drm_public int drmSyncobjTimelineSignal(int fd, const uint32_t *handles,
4956 uint64_t *points, uint32_t handle_count)
4958 struct drm_syncobj_timeline_array args;
4962 args.handles = (uintptr_t)handles;
4963 args.points = (uintptr_t)points;
4964 args.count_handles = handle_count;
4966 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TIMELINE_SIGNAL, &args);
4970 drm_public int drmSyncobjTimelineWait(int fd, uint32_t *handles, uint64_t *points,
4971 unsigned num_handles,
4972 int64_t timeout_nsec, unsigned flags,
4973 uint32_t *first_signaled)
4975 struct drm_syncobj_timeline_wait args;
4979 args.handles = (uintptr_t)handles;
4980 args.points = (uintptr_t)points;
4981 args.timeout_nsec = timeout_nsec;
4982 args.count_handles = num_handles;
4985 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TIMELINE_WAIT, &args);
4990 *first_signaled = args.first_signaled;
4995 drm_public int drmSyncobjQuery(int fd, uint32_t *handles, uint64_t *points,
4996 uint32_t handle_count)
4998 struct drm_syncobj_timeline_array args;
5002 args.handles = (uintptr_t)handles;
5003 args.points = (uintptr_t)points;
5004 args.count_handles = handle_count;
5006 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_QUERY, &args);
5012 drm_public int drmSyncobjQuery2(int fd, uint32_t *handles, uint64_t *points,
5013 uint32_t handle_count, uint32_t flags)
5015 struct drm_syncobj_timeline_array args;
5018 args.handles = (uintptr_t)handles;
5019 args.points = (uintptr_t)points;
5020 args.count_handles = handle_count;
5023 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_QUERY, &args);
5027 drm_public int drmSyncobjTransfer(int fd,
5028 uint32_t dst_handle, uint64_t dst_point,
5029 uint32_t src_handle, uint64_t src_point,
5032 struct drm_syncobj_transfer args;
5036 args.src_handle = src_handle;
5037 args.dst_handle = dst_handle;
5038 args.src_point = src_point;
5039 args.dst_point = dst_point;
5042 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TRANSFER, &args);
5048 drmGetFormatModifierFromSimpleTokens(uint64_t modifier)
5052 for (i = 0; i < ARRAY_SIZE(drm_format_modifier_table); i++) {
5053 if (drm_format_modifier_table[i].modifier == modifier)
5054 return strdup(drm_format_modifier_table[i].modifier_name);
5060 /** Retrieves a human-readable representation of a vendor (as a string) from
5061 * the format token modifier
5063 * \param modifier the format modifier token
5064 * \return a char pointer to the human-readable form of the vendor. Caller is
5065 * responsible for freeing it.
5068 drmGetFormatModifierVendor(uint64_t modifier)
5071 uint8_t vendor = fourcc_mod_get_vendor(modifier);
5073 for (i = 0; i < ARRAY_SIZE(drm_format_modifier_vendor_table); i++) {
5074 if (drm_format_modifier_vendor_table[i].vendor == vendor)
5075 return strdup(drm_format_modifier_vendor_table[i].vendor_name);
5081 /** Retrieves a human-readable representation string from a format token
5084 * If the dedicated function was not able to extract a valid name or searching
5085 * the format modifier was not in the table, this function would return NULL.
5087 * \param modifier the token format
5088 * \return a malloc'ed string representation of the modifier. Caller is
5089 * responsible for freeing the string returned.
5093 drmGetFormatModifierName(uint64_t modifier)
5095 uint8_t vendorid = fourcc_mod_get_vendor(modifier);
5096 char *modifier_found = NULL;
5099 for (i = 0; i < ARRAY_SIZE(modifier_format_vendor_table); i++) {
5100 if (modifier_format_vendor_table[i].vendor == vendorid)
5101 modifier_found = modifier_format_vendor_table[i].vendor_cb(modifier);
5104 if (!modifier_found)
5105 return drmGetFormatModifierFromSimpleTokens(modifier);
5107 return modifier_found;