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);
179 drmGetFormatModifierNameFromVivante(uint64_t modifier);
181 static const struct drmVendorInfo modifier_format_vendor_table[] = {
182 { DRM_FORMAT_MOD_VENDOR_ARM, drmGetFormatModifierNameFromArm },
183 { DRM_FORMAT_MOD_VENDOR_NVIDIA, drmGetFormatModifierNameFromNvidia },
184 { DRM_FORMAT_MOD_VENDOR_AMD, drmGetFormatModifierNameFromAmd },
185 { DRM_FORMAT_MOD_VENDOR_AMLOGIC, drmGetFormatModifierNameFromAmlogic },
186 { DRM_FORMAT_MOD_VENDOR_VIVANTE, drmGetFormatModifierNameFromVivante },
189 #ifndef AFBC_FORMAT_MOD_MODE_VALUE_MASK
190 #define AFBC_FORMAT_MOD_MODE_VALUE_MASK 0x000fffffffffffffULL
193 static const struct drmFormatVendorModifierInfo arm_mode_value_table[] = {
194 { AFBC_FORMAT_MOD_YTR, "YTR" },
195 { AFBC_FORMAT_MOD_SPLIT, "SPLIT" },
196 { AFBC_FORMAT_MOD_SPARSE, "SPARSE" },
197 { AFBC_FORMAT_MOD_CBR, "CBR" },
198 { AFBC_FORMAT_MOD_TILED, "TILED" },
199 { AFBC_FORMAT_MOD_SC, "SC" },
200 { AFBC_FORMAT_MOD_DB, "DB" },
201 { AFBC_FORMAT_MOD_BCH, "BCH" },
202 { AFBC_FORMAT_MOD_USM, "USM" },
205 static bool is_x_t_amd_gfx9_tile(uint64_t tile)
208 case AMD_FMT_MOD_TILE_GFX9_64K_S_X:
209 case AMD_FMT_MOD_TILE_GFX9_64K_D_X:
210 case AMD_FMT_MOD_TILE_GFX9_64K_R_X:
218 drmGetAfbcFormatModifierNameFromArm(uint64_t modifier, FILE *fp)
220 uint64_t mode_value = modifier & AFBC_FORMAT_MOD_MODE_VALUE_MASK;
221 uint64_t block_size = mode_value & AFBC_FORMAT_MOD_BLOCK_SIZE_MASK;
223 const char *block = NULL;
224 const char *mode = NULL;
225 bool did_print_mode = false;
227 /* add block, can only have a (single) block */
228 switch (block_size) {
229 case AFBC_FORMAT_MOD_BLOCK_SIZE_16x16:
232 case AFBC_FORMAT_MOD_BLOCK_SIZE_32x8:
235 case AFBC_FORMAT_MOD_BLOCK_SIZE_64x4:
238 case AFBC_FORMAT_MOD_BLOCK_SIZE_32x8_64x4:
247 fprintf(fp, "BLOCK_SIZE=%s,", block);
250 for (unsigned int i = 0; i < ARRAY_SIZE(arm_mode_value_table); i++) {
251 if (arm_mode_value_table[i].modifier & mode_value) {
252 mode = arm_mode_value_table[i].modifier_name;
253 if (!did_print_mode) {
254 fprintf(fp, "MODE=%s", mode);
255 did_print_mode = true;
257 fprintf(fp, "|%s", mode);
266 drmGetAfrcFormatModifierNameFromArm(uint64_t modifier, FILE *fp)
269 for (unsigned int i = 0; i < 2; ++i) {
270 uint64_t coding_unit_block =
271 (modifier >> (i * 4)) & AFRC_FORMAT_MOD_CU_SIZE_MASK;
272 const char *coding_unit_size = NULL;
274 switch (coding_unit_block) {
275 case AFRC_FORMAT_MOD_CU_SIZE_16:
276 coding_unit_size = "CU_16";
278 case AFRC_FORMAT_MOD_CU_SIZE_24:
279 coding_unit_size = "CU_24";
281 case AFRC_FORMAT_MOD_CU_SIZE_32:
282 coding_unit_size = "CU_32";
286 if (!coding_unit_size) {
294 fprintf(fp, "P0=%s,", coding_unit_size);
296 fprintf(fp, "P12=%s,", coding_unit_size);
301 (modifier & AFRC_FORMAT_MOD_LAYOUT_SCAN) == AFRC_FORMAT_MOD_LAYOUT_SCAN;
311 drmGetFormatModifierNameFromArm(uint64_t modifier)
313 uint64_t type = (modifier >> 52) & 0xf;
317 char *modifier_name = NULL;
320 fp = open_memstream(&modifier_name, &size);
325 case DRM_FORMAT_MOD_ARM_TYPE_AFBC:
326 result = drmGetAfbcFormatModifierNameFromArm(modifier, fp);
328 case DRM_FORMAT_MOD_ARM_TYPE_AFRC:
329 result = drmGetAfrcFormatModifierNameFromArm(modifier, fp);
331 /* misc type is already handled by the static table */
332 case DRM_FORMAT_MOD_ARM_TYPE_MISC:
344 return modifier_name;
348 drmGetFormatModifierNameFromNvidia(uint64_t modifier)
350 uint64_t height, kind, gen, sector, compression;
352 height = modifier & 0xf;
353 kind = (modifier >> 12) & 0xff;
355 gen = (modifier >> 20) & 0x3;
356 sector = (modifier >> 22) & 0x1;
357 compression = (modifier >> 23) & 0x7;
359 /* just in case there could other simpler modifiers, not yet added, avoid
360 * testing against TEGRA_TILE */
361 if ((modifier & 0x10) == 0x10) {
363 asprintf(&mod_nvidia, "BLOCK_LINEAR_2D,HEIGHT=%"PRIu64",KIND=%"PRIu64","
364 "GEN=%"PRIu64",SECTOR=%"PRIu64",COMPRESSION=%"PRIu64"", height,
365 kind, gen, sector, compression);
373 drmGetFormatModifierNameFromAmdDcc(uint64_t modifier, FILE *fp)
375 uint64_t dcc_max_compressed_block =
376 AMD_FMT_MOD_GET(DCC_MAX_COMPRESSED_BLOCK, modifier);
377 uint64_t dcc_retile = AMD_FMT_MOD_GET(DCC_RETILE, modifier);
379 const char *dcc_max_compressed_block_str = NULL;
384 fprintf(fp, ",DCC_RETILE");
386 if (!dcc_retile && AMD_FMT_MOD_GET(DCC_PIPE_ALIGN, modifier))
387 fprintf(fp, ",DCC_PIPE_ALIGN");
389 if (AMD_FMT_MOD_GET(DCC_INDEPENDENT_64B, modifier))
390 fprintf(fp, ",DCC_INDEPENDENT_64B");
392 if (AMD_FMT_MOD_GET(DCC_INDEPENDENT_128B, modifier))
393 fprintf(fp, ",DCC_INDEPENDENT_128B");
395 switch (dcc_max_compressed_block) {
396 case AMD_FMT_MOD_DCC_BLOCK_64B:
397 dcc_max_compressed_block_str = "64B";
399 case AMD_FMT_MOD_DCC_BLOCK_128B:
400 dcc_max_compressed_block_str = "128B";
402 case AMD_FMT_MOD_DCC_BLOCK_256B:
403 dcc_max_compressed_block_str = "256B";
407 if (dcc_max_compressed_block_str)
408 fprintf(fp, ",DCC_MAX_COMPRESSED_BLOCK=%s",
409 dcc_max_compressed_block_str);
411 if (AMD_FMT_MOD_GET(DCC_CONSTANT_ENCODE, modifier))
412 fprintf(fp, ",DCC_CONSTANT_ENCODE");
416 drmGetFormatModifierNameFromAmdTile(uint64_t modifier, FILE *fp)
418 uint64_t pipe_xor_bits, bank_xor_bits, packers, rb;
419 uint64_t pipe, pipe_align, dcc, dcc_retile, tile_version;
421 pipe_align = AMD_FMT_MOD_GET(DCC_PIPE_ALIGN, modifier);
422 pipe_xor_bits = AMD_FMT_MOD_GET(PIPE_XOR_BITS, modifier);
423 dcc = AMD_FMT_MOD_GET(DCC, modifier);
424 dcc_retile = AMD_FMT_MOD_GET(DCC_RETILE, modifier);
425 tile_version = AMD_FMT_MOD_GET(TILE_VERSION, modifier);
427 fprintf(fp, ",PIPE_XOR_BITS=%"PRIu64, pipe_xor_bits);
429 if (tile_version == AMD_FMT_MOD_TILE_VER_GFX9) {
430 bank_xor_bits = AMD_FMT_MOD_GET(BANK_XOR_BITS, modifier);
431 fprintf(fp, ",BANK_XOR_BITS=%"PRIu64, bank_xor_bits);
434 if (tile_version == AMD_FMT_MOD_TILE_VER_GFX10_RBPLUS) {
435 packers = AMD_FMT_MOD_GET(PACKERS, modifier);
436 fprintf(fp, ",PACKERS=%"PRIu64, packers);
439 if (dcc && tile_version == AMD_FMT_MOD_TILE_VER_GFX9) {
440 rb = AMD_FMT_MOD_GET(RB, modifier);
441 fprintf(fp, ",RB=%"PRIu64, rb);
444 if (dcc && tile_version == AMD_FMT_MOD_TILE_VER_GFX9 &&
445 (dcc_retile || pipe_align)) {
446 pipe = AMD_FMT_MOD_GET(PIPE, modifier);
447 fprintf(fp, ",PIPE_%"PRIu64, pipe);
452 drmGetFormatModifierNameFromAmd(uint64_t modifier)
454 uint64_t tile, tile_version, dcc;
456 char *mod_amd = NULL;
459 const char *str_tile = NULL;
460 const char *str_tile_version = NULL;
462 tile = AMD_FMT_MOD_GET(TILE, modifier);
463 tile_version = AMD_FMT_MOD_GET(TILE_VERSION, modifier);
464 dcc = AMD_FMT_MOD_GET(DCC, modifier);
466 fp = open_memstream(&mod_amd, &size);
471 switch (tile_version) {
472 case AMD_FMT_MOD_TILE_VER_GFX9:
473 str_tile_version = "GFX9";
475 case AMD_FMT_MOD_TILE_VER_GFX10:
476 str_tile_version = "GFX10";
478 case AMD_FMT_MOD_TILE_VER_GFX10_RBPLUS:
479 str_tile_version = "GFX10_RBPLUS";
483 if (str_tile_version) {
484 fprintf(fp, "%s", str_tile_version);
493 case AMD_FMT_MOD_TILE_GFX9_64K_S:
494 str_tile = "GFX9_64K_S";
496 case AMD_FMT_MOD_TILE_GFX9_64K_D:
497 str_tile = "GFX9_64K_D";
499 case AMD_FMT_MOD_TILE_GFX9_64K_S_X:
500 str_tile = "GFX9_64K_S_X";
502 case AMD_FMT_MOD_TILE_GFX9_64K_D_X:
503 str_tile = "GFX9_64K_D_X";
505 case AMD_FMT_MOD_TILE_GFX9_64K_R_X:
506 str_tile = "GFX9_64K_R_X";
511 fprintf(fp, ",%s", str_tile);
514 drmGetFormatModifierNameFromAmdDcc(modifier, fp);
516 if (tile_version >= AMD_FMT_MOD_TILE_VER_GFX9 && is_x_t_amd_gfx9_tile(tile))
517 drmGetFormatModifierNameFromAmdTile(modifier, fp);
524 drmGetFormatModifierNameFromAmlogic(uint64_t modifier)
526 uint64_t layout = modifier & 0xff;
527 uint64_t options = (modifier >> 8) & 0xff;
528 char *mod_amlogic = NULL;
530 const char *layout_str;
531 const char *opts_str;
534 case AMLOGIC_FBC_LAYOUT_BASIC:
535 layout_str = "BASIC";
537 case AMLOGIC_FBC_LAYOUT_SCATTER:
538 layout_str = "SCATTER";
541 layout_str = "INVALID_LAYOUT";
545 if (options & AMLOGIC_FBC_OPTION_MEM_SAVING)
546 opts_str = "MEM_SAVING";
550 asprintf(&mod_amlogic, "FBC,LAYOUT=%s,OPTIONS=%s", layout_str, opts_str);
555 drmGetFormatModifierNameFromVivante(uint64_t modifier)
557 const char *color_tiling, *tile_status, *compression;
558 const char *mod_vivante = NULL;
560 switch (modifier & VIVANTE_MOD_TS_MASK) {
564 case VIVANTE_MOD_TS_64_4:
565 tile_status = ",TS=64B_4";
567 case VIVANTE_MOD_TS_64_2:
568 tile_status = ",TS=64B_2";
570 case VIVANTE_MOD_TS_128_4:
571 tile_status = ",TS=128B_4";
573 case VIVANTE_MOD_TS_256_4:
574 tile_status = ",TS=256B_4";
577 tile_status = ",TS=UNKNOWN";
581 switch (modifier & VIVANTE_MOD_COMP_MASK) {
585 case VIVANTE_MOD_COMP_DEC400:
586 compression = ",COMP=DEC400";
589 compression = ",COMP=UNKNOWN";
593 switch (modifier & ~VIVANTE_MOD_EXT_MASK) {
595 color_tiling = "LINEAR";
597 case DRM_FORMAT_MOD_VIVANTE_TILED:
598 color_tiling = "TILED";
600 case DRM_FORMAT_MOD_VIVANTE_SUPER_TILED:
601 color_tiling = "SUPER_TILED";
603 case DRM_FORMAT_MOD_VIVANTE_SPLIT_TILED:
604 color_tiling = "SPLIT_TILED";
606 case DRM_FORMAT_MOD_VIVANTE_SPLIT_SUPER_TILED:
607 color_tiling = "SPLIT_SUPER_TILED";
610 color_tiling = "UNKNOWN";
614 asprintf(&mod_vivante, "%s%s%s", color_tiling, tile_status, compression);
618 static unsigned log2_int(unsigned x)
626 if ((unsigned)(1 << l) > x) {
634 drm_public void drmSetServerInfo(drmServerInfoPtr info)
636 drm_server_info = info;
640 * Output a message to stderr.
642 * \param format printf() like format string.
645 * This function is a wrapper around vfprintf().
648 static int DRM_PRINTFLIKE(1, 0)
649 drmDebugPrint(const char *format, va_list ap)
651 return vfprintf(stderr, format, ap);
655 drmMsg(const char *format, ...)
659 if (((env = getenv("LIBGL_DEBUG")) && strstr(env, "verbose")) ||
660 (drm_server_info && drm_server_info->debug_print))
662 va_start(ap, format);
663 if (drm_server_info) {
664 drm_server_info->debug_print(format,ap);
666 drmDebugPrint(format, ap);
672 static void *drmHashTable = NULL; /* Context switch callbacks */
674 drm_public void *drmGetHashTable(void)
679 drm_public void *drmMalloc(int size)
681 return calloc(1, size);
684 drm_public void drmFree(void *pt)
690 * Call ioctl, restarting if it is interrupted
693 drmIoctl(int fd, unsigned long request, void *arg)
698 ret = ioctl(fd, request, arg);
699 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
703 static unsigned long drmGetKeyFromFd(int fd)
712 drm_public drmHashEntry *drmGetEntry(int fd)
714 unsigned long key = drmGetKeyFromFd(fd);
719 drmHashTable = drmHashCreate();
721 if (drmHashLookup(drmHashTable, key, &value)) {
722 entry = drmMalloc(sizeof(*entry));
725 entry->tagTable = drmHashCreate();
726 drmHashInsert(drmHashTable, key, entry);
734 * Compare two busid strings
739 * \return 1 if matched.
742 * This function compares two bus ID strings. It understands the older
743 * PCI:b:d:f format and the newer pci:oooo:bb:dd.f format. In the format, o is
744 * domain, b is bus, d is device, f is function.
746 static int drmMatchBusID(const char *id1, const char *id2, int pci_domain_ok)
748 /* First, check if the IDs are exactly the same */
749 if (strcasecmp(id1, id2) == 0)
752 /* Try to match old/new-style PCI bus IDs. */
753 if (strncasecmp(id1, "pci", 3) == 0) {
754 unsigned int o1, b1, d1, f1;
755 unsigned int o2, b2, d2, f2;
758 ret = sscanf(id1, "pci:%04x:%02x:%02x.%u", &o1, &b1, &d1, &f1);
761 ret = sscanf(id1, "PCI:%u:%u:%u", &b1, &d1, &f1);
766 ret = sscanf(id2, "pci:%04x:%02x:%02x.%u", &o2, &b2, &d2, &f2);
769 ret = sscanf(id2, "PCI:%u:%u:%u", &b2, &d2, &f2);
774 /* If domains aren't properly supported by the kernel interface,
775 * just ignore them, which sucks less than picking a totally random
776 * card with "open by name"
781 if ((o1 != o2) || (b1 != b2) || (d1 != d2) || (f1 != f2))
790 * Handles error checking for chown call.
792 * \param path to file.
793 * \param id of the new owner.
794 * \param id of the new group.
796 * \return zero if success or -1 if failure.
799 * Checks for failure. If failure was caused by signal call chown again.
800 * If any other failure happened then it will output error message using
804 static int chown_check_return(const char *path, uid_t owner, gid_t group)
809 rv = chown(path, owner, group);
810 } while (rv != 0 && errno == EINTR);
815 drmMsg("Failed to change owner or group for file %s! %d: %s\n",
816 path, errno, strerror(errno));
821 static const char *drmGetDeviceName(int type)
824 case DRM_NODE_PRIMARY:
826 case DRM_NODE_CONTROL:
827 return DRM_CONTROL_DEV_NAME;
828 case DRM_NODE_RENDER:
829 return DRM_RENDER_DEV_NAME;
835 * Open the DRM device, creating it if necessary.
837 * \param dev major and minor numbers of the device.
838 * \param minor minor number of the device.
840 * \return a file descriptor on success, or a negative value on error.
843 * Assembles the device name from \p minor and opens it, creating the device
844 * special file node with the major and minor numbers specified by \p dev and
845 * parent directory if necessary and was called by root.
847 static int drmOpenDevice(dev_t dev, int minor, int type)
850 const char *dev_name = drmGetDeviceName(type);
851 char buf[DRM_NODE_NAME_MAX];
853 mode_t devmode = DRM_DEV_MODE, serv_mode;
856 int isroot = !geteuid();
857 uid_t user = DRM_DEV_UID;
858 gid_t group = DRM_DEV_GID;
864 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
865 drmMsg("drmOpenDevice: node name is %s\n", buf);
867 if (drm_server_info && drm_server_info->get_perms) {
868 drm_server_info->get_perms(&serv_group, &serv_mode);
869 devmode = serv_mode ? serv_mode : DRM_DEV_MODE;
870 devmode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
874 if (stat(DRM_DIR_NAME, &st)) {
876 return DRM_ERR_NOT_ROOT;
877 mkdir(DRM_DIR_NAME, DRM_DEV_DIRMODE);
878 chown_check_return(DRM_DIR_NAME, 0, 0); /* root:root */
879 chmod(DRM_DIR_NAME, DRM_DEV_DIRMODE);
882 /* Check if the device node exists and create it if necessary. */
883 if (stat(buf, &st)) {
885 return DRM_ERR_NOT_ROOT;
887 mknod(buf, S_IFCHR | devmode, dev);
890 if (drm_server_info && drm_server_info->get_perms) {
891 group = ((int)serv_group >= 0) ? serv_group : DRM_DEV_GID;
892 chown_check_return(buf, user, group);
896 /* if we modprobed then wait for udev */
900 if (stat(DRM_DIR_NAME, &st)) {
904 if (udev_count == 50)
909 if (stat(buf, &st)) {
913 if (udev_count == 50)
920 fd = open(buf, O_RDWR | O_CLOEXEC);
921 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
922 fd, fd < 0 ? strerror(errno) : "OK");
927 /* Check if the device node is not what we expect it to be, and recreate it
928 * and try again if so.
930 if (st.st_rdev != dev) {
932 return DRM_ERR_NOT_ROOT;
934 mknod(buf, S_IFCHR | devmode, dev);
935 if (drm_server_info && drm_server_info->get_perms) {
936 chown_check_return(buf, user, group);
940 fd = open(buf, O_RDWR | O_CLOEXEC);
941 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
942 fd, fd < 0 ? strerror(errno) : "OK");
946 drmMsg("drmOpenDevice: Open failed\n");
954 * Open the DRM device
956 * \param minor device minor number.
957 * \param create allow to create the device if set.
959 * \return a file descriptor on success, or a negative value on error.
962 * Calls drmOpenDevice() if \p create is set, otherwise assembles the device
963 * name from \p minor and opens it.
965 static int drmOpenMinor(int minor, int create, int type)
968 char buf[DRM_NODE_NAME_MAX];
969 const char *dev_name = drmGetDeviceName(type);
972 return drmOpenDevice(makedev(DRM_MAJOR, minor), minor, type);
977 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
978 if ((fd = open(buf, O_RDWR | O_CLOEXEC)) >= 0)
985 * Determine whether the DRM kernel driver has been loaded.
987 * \return 1 if the DRM driver is loaded, 0 otherwise.
990 * Determine the presence of the kernel driver by attempting to open the 0
991 * minor and get version information. For backward compatibility with older
992 * Linux implementations, /proc/dri is also checked.
994 drm_public int drmAvailable(void)
996 drmVersionPtr version;
1000 if ((fd = drmOpenMinor(0, 1, DRM_NODE_PRIMARY)) < 0) {
1002 /* Try proc for backward Linux compatibility */
1003 if (!access("/proc/dri/0", R_OK))
1009 if ((version = drmGetVersion(fd))) {
1011 drmFreeVersion(version);
1018 static int drmGetMinorBase(int type)
1021 case DRM_NODE_PRIMARY:
1023 case DRM_NODE_CONTROL:
1025 case DRM_NODE_RENDER:
1032 static int drmGetMinorType(int major, int minor)
1035 char name[SPECNAMELEN];
1038 if (!devname_r(makedev(major, minor), S_IFCHR, name, sizeof(name)))
1041 if (sscanf(name, "drm/%d", &id) != 1) {
1042 // If not in /dev/drm/ we have the type in the name
1043 if (sscanf(name, "dri/card%d\n", &id) >= 1)
1044 return DRM_NODE_PRIMARY;
1045 else if (sscanf(name, "dri/control%d\n", &id) >= 1)
1046 return DRM_NODE_CONTROL;
1047 else if (sscanf(name, "dri/renderD%d\n", &id) >= 1)
1048 return DRM_NODE_RENDER;
1054 int type = minor >> 6;
1060 case DRM_NODE_PRIMARY:
1061 case DRM_NODE_CONTROL:
1062 case DRM_NODE_RENDER:
1069 static const char *drmGetMinorName(int type)
1072 case DRM_NODE_PRIMARY:
1073 return DRM_PRIMARY_MINOR_NAME;
1074 case DRM_NODE_CONTROL:
1075 return DRM_CONTROL_MINOR_NAME;
1076 case DRM_NODE_RENDER:
1077 return DRM_RENDER_MINOR_NAME;
1084 * Open the device by bus ID.
1086 * \param busid bus ID.
1087 * \param type device node type.
1089 * \return a file descriptor on success, or a negative value on error.
1092 * This function attempts to open every possible minor (up to DRM_MAX_MINOR),
1093 * comparing the device bus ID with the one supplied.
1095 * \sa drmOpenMinor() and drmGetBusid().
1097 static int drmOpenByBusid(const char *busid, int type)
1099 int i, pci_domain_ok = 1;
1103 int base = drmGetMinorBase(type);
1108 drmMsg("drmOpenByBusid: Searching for BusID %s\n", busid);
1109 for (i = base; i < base + DRM_MAX_MINOR; i++) {
1110 fd = drmOpenMinor(i, 1, type);
1111 drmMsg("drmOpenByBusid: drmOpenMinor returns %d\n", fd);
1113 /* We need to try for 1.4 first for proper PCI domain support
1114 * and if that fails, we know the kernel is busted
1116 sv.drm_di_major = 1;
1117 sv.drm_di_minor = 4;
1118 sv.drm_dd_major = -1; /* Don't care */
1119 sv.drm_dd_minor = -1; /* Don't care */
1120 if (drmSetInterfaceVersion(fd, &sv)) {
1124 sv.drm_di_major = 1;
1125 sv.drm_di_minor = 1;
1126 sv.drm_dd_major = -1; /* Don't care */
1127 sv.drm_dd_minor = -1; /* Don't care */
1128 drmMsg("drmOpenByBusid: Interface 1.4 failed, trying 1.1\n");
1129 drmSetInterfaceVersion(fd, &sv);
1131 buf = drmGetBusid(fd);
1132 drmMsg("drmOpenByBusid: drmGetBusid reports %s\n", buf);
1133 if (buf && drmMatchBusID(buf, busid, pci_domain_ok)) {
1147 * Open the device by name.
1149 * \param name driver name.
1150 * \param type the device node type.
1152 * \return a file descriptor on success, or a negative value on error.
1155 * This function opens the first minor number that matches the driver name and
1156 * isn't already in use. If it's in use it then it will already have a bus ID
1159 * \sa drmOpenMinor(), drmGetVersion() and drmGetBusid().
1161 static int drmOpenByName(const char *name, int type)
1165 drmVersionPtr version;
1167 int base = drmGetMinorBase(type);
1173 * Open the first minor number that matches the driver name and isn't
1174 * already in use. If it's in use it will have a busid assigned already.
1176 for (i = base; i < base + DRM_MAX_MINOR; i++) {
1177 if ((fd = drmOpenMinor(i, 1, type)) >= 0) {
1178 if ((version = drmGetVersion(fd))) {
1179 if (!strcmp(version->name, name)) {
1180 drmFreeVersion(version);
1181 id = drmGetBusid(fd);
1182 drmMsg("drmGetBusid returned '%s'\n", id ? id : "NULL");
1191 drmFreeVersion(version);
1199 /* Backward-compatibility /proc support */
1200 for (i = 0; i < 8; i++) {
1201 char proc_name[64], buf[512];
1202 char *driver, *pt, *devstring;
1205 sprintf(proc_name, "/proc/dri/%d/name", i);
1206 if ((fd = open(proc_name, O_RDONLY)) >= 0) {
1207 retcode = read(fd, buf, sizeof(buf)-1);
1210 buf[retcode-1] = '\0';
1211 for (driver = pt = buf; *pt && *pt != ' '; ++pt)
1213 if (*pt) { /* Device is next */
1215 if (!strcmp(driver, name)) { /* Match */
1216 for (devstring = ++pt; *pt && *pt != ' '; ++pt)
1218 if (*pt) { /* Found busid */
1219 return drmOpenByBusid(++pt, type);
1220 } else { /* No busid */
1221 return drmOpenDevice(strtol(devstring, NULL, 0),i, type);
1235 * Open the DRM device.
1237 * Looks up the specified name and bus ID, and opens the device found. The
1238 * entry in /dev/dri is created if necessary and if called by root.
1240 * \param name driver name. Not referenced if bus ID is supplied.
1241 * \param busid bus ID. Zero if not known.
1243 * \return a file descriptor on success, or a negative value on error.
1246 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
1249 drm_public int drmOpen(const char *name, const char *busid)
1251 return drmOpenWithType(name, busid, DRM_NODE_PRIMARY);
1255 * Open the DRM device with specified type.
1257 * Looks up the specified name and bus ID, and opens the device found. The
1258 * entry in /dev/dri is created if necessary and if called by root.
1260 * \param name driver name. Not referenced if bus ID is supplied.
1261 * \param busid bus ID. Zero if not known.
1262 * \param type the device node type to open, PRIMARY, CONTROL or RENDER
1264 * \return a file descriptor on success, or a negative value on error.
1267 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
1270 drm_public int drmOpenWithType(const char *name, const char *busid, int type)
1272 if (name != NULL && drm_server_info &&
1273 drm_server_info->load_module && !drmAvailable()) {
1274 /* try to load the kernel module */
1275 if (!drm_server_info->load_module(name)) {
1276 drmMsg("[drm] failed to load kernel module \"%s\"\n", name);
1282 int fd = drmOpenByBusid(busid, type);
1288 return drmOpenByName(name, type);
1293 drm_public int drmOpenControl(int minor)
1295 return drmOpenMinor(minor, 0, DRM_NODE_CONTROL);
1298 drm_public int drmOpenRender(int minor)
1300 return drmOpenMinor(minor, 0, DRM_NODE_RENDER);
1304 * Free the version information returned by drmGetVersion().
1306 * \param v pointer to the version information.
1309 * It frees the memory pointed by \p %v as well as all the non-null strings
1312 drm_public void drmFreeVersion(drmVersionPtr v)
1324 * Free the non-public version information returned by the kernel.
1326 * \param v pointer to the version information.
1329 * Used by drmGetVersion() to free the memory pointed by \p %v as well as all
1330 * the non-null strings pointers in it.
1332 static void drmFreeKernelVersion(drm_version_t *v)
1344 * Copy version information.
1346 * \param d destination pointer.
1347 * \param s source pointer.
1350 * Used by drmGetVersion() to translate the information returned by the ioctl
1351 * interface in a private structure into the public structure counterpart.
1353 static void drmCopyVersion(drmVersionPtr d, const drm_version_t *s)
1355 d->version_major = s->version_major;
1356 d->version_minor = s->version_minor;
1357 d->version_patchlevel = s->version_patchlevel;
1358 d->name_len = s->name_len;
1359 d->name = strdup(s->name);
1360 d->date_len = s->date_len;
1361 d->date = strdup(s->date);
1362 d->desc_len = s->desc_len;
1363 d->desc = strdup(s->desc);
1368 * Query the driver version information.
1370 * \param fd file descriptor.
1372 * \return pointer to a drmVersion structure which should be freed with
1375 * \note Similar information is available via /proc/dri.
1378 * It gets the version information via successive DRM_IOCTL_VERSION ioctls,
1379 * first with zeros to get the string lengths, and then the actually strings.
1380 * It also null-terminates them since they might not be already.
1382 drm_public drmVersionPtr drmGetVersion(int fd)
1384 drmVersionPtr retval;
1385 drm_version_t *version = drmMalloc(sizeof(*version));
1387 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
1388 drmFreeKernelVersion(version);
1392 if (version->name_len)
1393 version->name = drmMalloc(version->name_len + 1);
1394 if (version->date_len)
1395 version->date = drmMalloc(version->date_len + 1);
1396 if (version->desc_len)
1397 version->desc = drmMalloc(version->desc_len + 1);
1399 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
1400 drmMsg("DRM_IOCTL_VERSION: %s\n", strerror(errno));
1401 drmFreeKernelVersion(version);
1405 /* The results might not be null-terminated strings, so terminate them. */
1406 if (version->name_len) version->name[version->name_len] = '\0';
1407 if (version->date_len) version->date[version->date_len] = '\0';
1408 if (version->desc_len) version->desc[version->desc_len] = '\0';
1410 retval = drmMalloc(sizeof(*retval));
1411 drmCopyVersion(retval, version);
1412 drmFreeKernelVersion(version);
1418 * Get version information for the DRM user space library.
1420 * This version number is driver independent.
1422 * \param fd file descriptor.
1424 * \return version information.
1427 * This function allocates and fills a drm_version structure with a hard coded
1430 drm_public drmVersionPtr drmGetLibVersion(int fd)
1432 drm_version_t *version = drmMalloc(sizeof(*version));
1435 * NOTE THIS MUST NOT GO ABOVE VERSION 1.X due to drivers needing it
1436 * revision 1.0.x = original DRM interface with no drmGetLibVersion
1437 * entry point and many drm<Device> extensions
1438 * revision 1.1.x = added drmCommand entry points for device extensions
1439 * added drmGetLibVersion to identify libdrm.a version
1440 * revision 1.2.x = added drmSetInterfaceVersion
1441 * modified drmOpen to handle both busid and name
1442 * revision 1.3.x = added server + memory manager
1444 version->version_major = 1;
1445 version->version_minor = 3;
1446 version->version_patchlevel = 0;
1448 return (drmVersionPtr)version;
1451 drm_public int drmGetCap(int fd, uint64_t capability, uint64_t *value)
1453 struct drm_get_cap cap;
1457 cap.capability = capability;
1459 ret = drmIoctl(fd, DRM_IOCTL_GET_CAP, &cap);
1467 drm_public int drmSetClientCap(int fd, uint64_t capability, uint64_t value)
1469 struct drm_set_client_cap cap;
1472 cap.capability = capability;
1475 return drmIoctl(fd, DRM_IOCTL_SET_CLIENT_CAP, &cap);
1479 * Free the bus ID information.
1481 * \param busid bus ID information string as given by drmGetBusid().
1484 * This function is just frees the memory pointed by \p busid.
1486 drm_public void drmFreeBusid(const char *busid)
1488 drmFree((void *)busid);
1493 * Get the bus ID of the device.
1495 * \param fd file descriptor.
1497 * \return bus ID string.
1500 * This function gets the bus ID via successive DRM_IOCTL_GET_UNIQUE ioctls to
1501 * get the string length and data, passing the arguments in a drm_unique
1504 drm_public char *drmGetBusid(int fd)
1510 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
1512 u.unique = drmMalloc(u.unique_len + 1);
1513 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u)) {
1517 u.unique[u.unique_len] = '\0';
1524 * Set the bus ID of the device.
1526 * \param fd file descriptor.
1527 * \param busid bus ID string.
1529 * \return zero on success, negative on failure.
1532 * This function is a wrapper around the DRM_IOCTL_SET_UNIQUE ioctl, passing
1533 * the arguments in a drm_unique structure.
1535 drm_public int drmSetBusid(int fd, const char *busid)
1540 u.unique = (char *)busid;
1541 u.unique_len = strlen(busid);
1543 if (drmIoctl(fd, DRM_IOCTL_SET_UNIQUE, &u)) {
1549 drm_public int drmGetMagic(int fd, drm_magic_t * magic)
1556 if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
1558 *magic = auth.magic;
1562 drm_public int drmAuthMagic(int fd, drm_magic_t magic)
1568 if (drmIoctl(fd, DRM_IOCTL_AUTH_MAGIC, &auth))
1574 * Specifies a range of memory that is available for mapping by a
1577 * \param fd file descriptor.
1578 * \param offset usually the physical address. The actual meaning depends of
1579 * the \p type parameter. See below.
1580 * \param size of the memory in bytes.
1581 * \param type type of the memory to be mapped.
1582 * \param flags combination of several flags to modify the function actions.
1583 * \param handle will be set to a value that may be used as the offset
1584 * parameter for mmap().
1586 * \return zero on success or a negative value on error.
1588 * \par Mapping the frame buffer
1589 * For the frame buffer
1590 * - \p offset will be the physical address of the start of the frame buffer,
1591 * - \p size will be the size of the frame buffer in bytes, and
1592 * - \p type will be DRM_FRAME_BUFFER.
1595 * The area mapped will be uncached. If MTRR support is available in the
1596 * kernel, the frame buffer area will be set to write combining.
1598 * \par Mapping the MMIO register area
1599 * For the MMIO register area,
1600 * - \p offset will be the physical address of the start of the register area,
1601 * - \p size will be the size of the register area bytes, and
1602 * - \p type will be DRM_REGISTERS.
1604 * The area mapped will be uncached.
1606 * \par Mapping the SAREA
1608 * - \p offset will be ignored and should be set to zero,
1609 * - \p size will be the desired size of the SAREA in bytes,
1610 * - \p type will be DRM_SHM.
1613 * A shared memory area of the requested size will be created and locked in
1614 * kernel memory. This area may be mapped into client-space by using the handle
1617 * \note May only be called by root.
1620 * This function is a wrapper around the DRM_IOCTL_ADD_MAP ioctl, passing
1621 * the arguments in a drm_map structure.
1623 drm_public int drmAddMap(int fd, drm_handle_t offset, drmSize size, drmMapType type,
1624 drmMapFlags flags, drm_handle_t *handle)
1629 map.offset = offset;
1631 map.type = (enum drm_map_type)type;
1632 map.flags = (enum drm_map_flags)flags;
1633 if (drmIoctl(fd, DRM_IOCTL_ADD_MAP, &map))
1636 *handle = (drm_handle_t)(uintptr_t)map.handle;
1640 drm_public int drmRmMap(int fd, drm_handle_t handle)
1645 map.handle = (void *)(uintptr_t)handle;
1647 if(drmIoctl(fd, DRM_IOCTL_RM_MAP, &map))
1653 * Make buffers available for DMA transfers.
1655 * \param fd file descriptor.
1656 * \param count number of buffers.
1657 * \param size size of each buffer.
1658 * \param flags buffer allocation flags.
1659 * \param agp_offset offset in the AGP aperture
1661 * \return number of buffers allocated, negative on error.
1664 * This function is a wrapper around DRM_IOCTL_ADD_BUFS ioctl.
1668 drm_public int drmAddBufs(int fd, int count, int size, drmBufDescFlags flags,
1671 drm_buf_desc_t request;
1674 request.count = count;
1675 request.size = size;
1676 request.flags = (int)flags;
1677 request.agp_start = agp_offset;
1679 if (drmIoctl(fd, DRM_IOCTL_ADD_BUFS, &request))
1681 return request.count;
1684 drm_public int drmMarkBufs(int fd, double low, double high)
1686 drm_buf_info_t info;
1691 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1697 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1700 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1701 int retval = -errno;
1706 for (i = 0; i < info.count; i++) {
1707 info.list[i].low_mark = low * info.list[i].count;
1708 info.list[i].high_mark = high * info.list[i].count;
1709 if (drmIoctl(fd, DRM_IOCTL_MARK_BUFS, &info.list[i])) {
1710 int retval = -errno;
1723 * \param fd file descriptor.
1724 * \param count number of buffers to free.
1725 * \param list list of buffers to be freed.
1727 * \return zero on success, or a negative value on failure.
1729 * \note This function is primarily used for debugging.
1732 * This function is a wrapper around the DRM_IOCTL_FREE_BUFS ioctl, passing
1733 * the arguments in a drm_buf_free structure.
1735 drm_public int drmFreeBufs(int fd, int count, int *list)
1737 drm_buf_free_t request;
1740 request.count = count;
1741 request.list = list;
1742 if (drmIoctl(fd, DRM_IOCTL_FREE_BUFS, &request))
1751 * \param fd file descriptor.
1754 * This function closes the file descriptor.
1756 drm_public int drmClose(int fd)
1758 unsigned long key = drmGetKeyFromFd(fd);
1759 drmHashEntry *entry = drmGetEntry(fd);
1761 drmHashDestroy(entry->tagTable);
1764 entry->tagTable = NULL;
1766 drmHashDelete(drmHashTable, key);
1774 * Map a region of memory.
1776 * \param fd file descriptor.
1777 * \param handle handle returned by drmAddMap().
1778 * \param size size in bytes. Must match the size used by drmAddMap().
1779 * \param address will contain the user-space virtual address where the mapping
1782 * \return zero on success, or a negative value on failure.
1785 * This function is a wrapper for mmap().
1787 drm_public int drmMap(int fd, drm_handle_t handle, drmSize size,
1788 drmAddressPtr address)
1790 static unsigned long pagesize_mask = 0;
1796 pagesize_mask = getpagesize() - 1;
1798 size = (size + pagesize_mask) & ~pagesize_mask;
1800 *address = drm_mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1801 if (*address == MAP_FAILED)
1808 * Unmap mappings obtained with drmMap().
1810 * \param address address as given by drmMap().
1811 * \param size size in bytes. Must match the size used by drmMap().
1813 * \return zero on success, or a negative value on failure.
1816 * This function is a wrapper for munmap().
1818 drm_public int drmUnmap(drmAddress address, drmSize size)
1820 return drm_munmap(address, size);
1823 drm_public drmBufInfoPtr drmGetBufInfo(int fd)
1825 drm_buf_info_t info;
1826 drmBufInfoPtr retval;
1831 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1835 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1838 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1843 retval = drmMalloc(sizeof(*retval));
1844 retval->count = info.count;
1845 if (!(retval->list = drmMalloc(info.count * sizeof(*retval->list)))) {
1851 for (i = 0; i < info.count; i++) {
1852 retval->list[i].count = info.list[i].count;
1853 retval->list[i].size = info.list[i].size;
1854 retval->list[i].low_mark = info.list[i].low_mark;
1855 retval->list[i].high_mark = info.list[i].high_mark;
1864 * Map all DMA buffers into client-virtual space.
1866 * \param fd file descriptor.
1868 * \return a pointer to a ::drmBufMap structure.
1870 * \note The client may not use these buffers until obtaining buffer indices
1874 * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1875 * information about the buffers in a drm_buf_map structure into the
1876 * client-visible data structures.
1878 drm_public drmBufMapPtr drmMapBufs(int fd)
1881 drmBufMapPtr retval;
1885 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1891 if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1894 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1899 retval = drmMalloc(sizeof(*retval));
1900 retval->count = bufs.count;
1901 retval->list = drmMalloc(bufs.count * sizeof(*retval->list));
1902 for (i = 0; i < bufs.count; i++) {
1903 retval->list[i].idx = bufs.list[i].idx;
1904 retval->list[i].total = bufs.list[i].total;
1905 retval->list[i].used = 0;
1906 retval->list[i].address = bufs.list[i].address;
1915 * Unmap buffers allocated with drmMapBufs().
1917 * \return zero on success, or negative value on failure.
1920 * Calls munmap() for every buffer stored in \p bufs and frees the
1921 * memory allocated by drmMapBufs().
1923 drm_public int drmUnmapBufs(drmBufMapPtr bufs)
1927 for (i = 0; i < bufs->count; i++) {
1928 drm_munmap(bufs->list[i].address, bufs->list[i].total);
1931 drmFree(bufs->list);
1937 #define DRM_DMA_RETRY 16
1940 * Reserve DMA buffers.
1942 * \param fd file descriptor.
1945 * \return zero on success, or a negative value on failure.
1948 * Assemble the arguments into a drm_dma structure and keeps issuing the
1949 * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1951 drm_public int drmDMA(int fd, drmDMAReqPtr request)
1956 dma.context = request->context;
1957 dma.send_count = request->send_count;
1958 dma.send_indices = request->send_list;
1959 dma.send_sizes = request->send_sizes;
1960 dma.flags = (enum drm_dma_flags)request->flags;
1961 dma.request_count = request->request_count;
1962 dma.request_size = request->request_size;
1963 dma.request_indices = request->request_list;
1964 dma.request_sizes = request->request_sizes;
1965 dma.granted_count = 0;
1968 ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1969 } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1972 request->granted_count = dma.granted_count;
1981 * Obtain heavyweight hardware lock.
1983 * \param fd file descriptor.
1984 * \param context context.
1985 * \param flags flags that determine the state of the hardware when the function
1988 * \return always zero.
1991 * This function translates the arguments into a drm_lock structure and issue
1992 * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1994 drm_public int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
1999 lock.context = context;
2001 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
2002 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
2003 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
2004 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
2005 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2006 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2008 while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
2014 * Release the hardware lock.
2016 * \param fd file descriptor.
2017 * \param context context.
2019 * \return zero on success, or a negative value on failure.
2022 * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
2023 * argument in a drm_lock structure.
2025 drm_public int drmUnlock(int fd, drm_context_t context)
2030 lock.context = context;
2031 return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
2034 drm_public drm_context_t *drmGetReservedContextList(int fd, int *count)
2038 drm_context_t * retval;
2042 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
2048 if (!(list = drmMalloc(res.count * sizeof(*list))))
2050 if (!(retval = drmMalloc(res.count * sizeof(*retval))))
2053 res.contexts = list;
2054 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
2055 goto err_free_context;
2057 for (i = 0; i < res.count; i++)
2058 retval[i] = list[i].handle;
2071 drm_public void drmFreeReservedContextList(drm_context_t *pt)
2079 * Used by the X server during GLXContext initialization. This causes
2080 * per-context kernel-level resources to be allocated.
2082 * \param fd file descriptor.
2083 * \param handle is set on success. To be used by the client when requesting DMA
2084 * dispatch with drmDMA().
2086 * \return zero on success, or a negative value on failure.
2088 * \note May only be called by root.
2091 * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
2092 * argument in a drm_ctx structure.
2094 drm_public int drmCreateContext(int fd, drm_context_t *handle)
2099 if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
2101 *handle = ctx.handle;
2105 drm_public int drmSwitchToContext(int fd, drm_context_t context)
2110 ctx.handle = context;
2111 if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
2116 drm_public int drmSetContextFlags(int fd, drm_context_t context,
2117 drm_context_tFlags flags)
2122 * Context preserving means that no context switches are done between DMA
2123 * buffers from one context and the next. This is suitable for use in the
2124 * X server (which promises to maintain hardware context), or in the
2125 * client-side library when buffers are swapped on behalf of two threads.
2128 ctx.handle = context;
2129 if (flags & DRM_CONTEXT_PRESERVED)
2130 ctx.flags |= _DRM_CONTEXT_PRESERVED;
2131 if (flags & DRM_CONTEXT_2DONLY)
2132 ctx.flags |= _DRM_CONTEXT_2DONLY;
2133 if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
2138 drm_public int drmGetContextFlags(int fd, drm_context_t context,
2139 drm_context_tFlagsPtr flags)
2144 ctx.handle = context;
2145 if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
2148 if (ctx.flags & _DRM_CONTEXT_PRESERVED)
2149 *flags |= DRM_CONTEXT_PRESERVED;
2150 if (ctx.flags & _DRM_CONTEXT_2DONLY)
2151 *flags |= DRM_CONTEXT_2DONLY;
2158 * Free any kernel-level resources allocated with drmCreateContext() associated
2161 * \param fd file descriptor.
2162 * \param handle handle given by drmCreateContext().
2164 * \return zero on success, or a negative value on failure.
2166 * \note May only be called by root.
2169 * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
2170 * argument in a drm_ctx structure.
2172 drm_public int drmDestroyContext(int fd, drm_context_t handle)
2177 ctx.handle = handle;
2178 if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
2183 drm_public int drmCreateDrawable(int fd, drm_drawable_t *handle)
2188 if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
2190 *handle = draw.handle;
2194 drm_public int drmDestroyDrawable(int fd, drm_drawable_t handle)
2199 draw.handle = handle;
2200 if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
2205 drm_public int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
2206 drm_drawable_info_type_t type,
2207 unsigned int num, void *data)
2209 drm_update_draw_t update;
2212 update.handle = handle;
2215 update.data = (unsigned long long)(unsigned long)data;
2217 if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
2223 drm_public int drmCrtcGetSequence(int fd, uint32_t crtcId, uint64_t *sequence,
2226 struct drm_crtc_get_sequence get_seq;
2230 get_seq.crtc_id = crtcId;
2231 ret = drmIoctl(fd, DRM_IOCTL_CRTC_GET_SEQUENCE, &get_seq);
2236 *sequence = get_seq.sequence;
2238 *ns = get_seq.sequence_ns;
2242 drm_public int drmCrtcQueueSequence(int fd, uint32_t crtcId, uint32_t flags,
2244 uint64_t *sequence_queued,
2247 struct drm_crtc_queue_sequence queue_seq;
2250 memclear(queue_seq);
2251 queue_seq.crtc_id = crtcId;
2252 queue_seq.flags = flags;
2253 queue_seq.sequence = sequence;
2254 queue_seq.user_data = user_data;
2256 ret = drmIoctl(fd, DRM_IOCTL_CRTC_QUEUE_SEQUENCE, &queue_seq);
2257 if (ret == 0 && sequence_queued)
2258 *sequence_queued = queue_seq.sequence;
2264 * Acquire the AGP device.
2266 * Must be called before any of the other AGP related calls.
2268 * \param fd file descriptor.
2270 * \return zero on success, or a negative value on failure.
2273 * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
2275 drm_public int drmAgpAcquire(int fd)
2277 if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
2284 * Release the AGP device.
2286 * \param fd file descriptor.
2288 * \return zero on success, or a negative value on failure.
2291 * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
2293 drm_public int drmAgpRelease(int fd)
2295 if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
2304 * \param fd file descriptor.
2305 * \param mode AGP mode.
2307 * \return zero on success, or a negative value on failure.
2310 * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
2311 * argument in a drm_agp_mode structure.
2313 drm_public int drmAgpEnable(int fd, unsigned long mode)
2319 if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
2326 * Allocate a chunk of AGP memory.
2328 * \param fd file descriptor.
2329 * \param size requested memory size in bytes. Will be rounded to page boundary.
2330 * \param type type of memory to allocate.
2331 * \param address if not zero, will be set to the physical address of the
2333 * \param handle on success will be set to a handle of the allocated memory.
2335 * \return zero on success, or a negative value on failure.
2338 * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
2339 * arguments in a drm_agp_buffer structure.
2341 drm_public int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
2342 unsigned long *address, drm_handle_t *handle)
2347 *handle = DRM_AGP_NO_HANDLE;
2350 if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
2353 *address = b.physical;
2360 * Free a chunk of AGP memory.
2362 * \param fd file descriptor.
2363 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
2365 * \return zero on success, or a negative value on failure.
2368 * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
2369 * argument in a drm_agp_buffer structure.
2371 drm_public int drmAgpFree(int fd, drm_handle_t handle)
2377 if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
2384 * Bind a chunk of AGP memory.
2386 * \param fd file descriptor.
2387 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
2388 * \param offset offset in bytes. It will round to page boundary.
2390 * \return zero on success, or a negative value on failure.
2393 * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
2394 * argument in a drm_agp_binding structure.
2396 drm_public int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
2398 drm_agp_binding_t b;
2403 if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
2410 * Unbind a chunk of AGP memory.
2412 * \param fd file descriptor.
2413 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
2415 * \return zero on success, or a negative value on failure.
2418 * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
2419 * the argument in a drm_agp_binding structure.
2421 drm_public int drmAgpUnbind(int fd, drm_handle_t handle)
2423 drm_agp_binding_t b;
2427 if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
2434 * Get AGP driver major version number.
2436 * \param fd file descriptor.
2438 * \return major version number on success, or a negative value on failure..
2441 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2442 * necessary information in a drm_agp_info structure.
2444 drm_public int drmAgpVersionMajor(int fd)
2450 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2452 return i.agp_version_major;
2457 * Get AGP driver minor version number.
2459 * \param fd file descriptor.
2461 * \return minor version number on success, or a negative value on failure.
2464 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2465 * necessary information in a drm_agp_info structure.
2467 drm_public int drmAgpVersionMinor(int fd)
2473 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2475 return i.agp_version_minor;
2482 * \param fd file descriptor.
2484 * \return mode on success, or zero on failure.
2487 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2488 * necessary information in a drm_agp_info structure.
2490 drm_public unsigned long drmAgpGetMode(int fd)
2496 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2503 * Get AGP aperture base.
2505 * \param fd file descriptor.
2507 * \return aperture base on success, zero on failure.
2510 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2511 * necessary information in a drm_agp_info structure.
2513 drm_public unsigned long drmAgpBase(int fd)
2519 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2521 return i.aperture_base;
2526 * Get AGP aperture size.
2528 * \param fd file descriptor.
2530 * \return aperture size on success, zero on failure.
2533 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2534 * necessary information in a drm_agp_info structure.
2536 drm_public unsigned long drmAgpSize(int fd)
2542 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2544 return i.aperture_size;
2549 * Get used AGP memory.
2551 * \param fd file descriptor.
2553 * \return memory used on success, or zero on failure.
2556 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2557 * necessary information in a drm_agp_info structure.
2559 drm_public unsigned long drmAgpMemoryUsed(int fd)
2565 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2567 return i.memory_used;
2572 * Get available AGP memory.
2574 * \param fd file descriptor.
2576 * \return memory available on success, or zero on failure.
2579 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2580 * necessary information in a drm_agp_info structure.
2582 drm_public unsigned long drmAgpMemoryAvail(int fd)
2588 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2590 return i.memory_allowed;
2595 * Get hardware vendor ID.
2597 * \param fd file descriptor.
2599 * \return vendor ID on success, or zero on failure.
2602 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2603 * necessary information in a drm_agp_info structure.
2605 drm_public unsigned int drmAgpVendorId(int fd)
2611 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2618 * Get hardware device ID.
2620 * \param fd file descriptor.
2622 * \return zero on success, or zero on failure.
2625 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2626 * necessary information in a drm_agp_info structure.
2628 drm_public unsigned int drmAgpDeviceId(int fd)
2634 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2639 drm_public int drmScatterGatherAlloc(int fd, unsigned long size,
2640 drm_handle_t *handle)
2642 drm_scatter_gather_t sg;
2648 if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
2650 *handle = sg.handle;
2654 drm_public int drmScatterGatherFree(int fd, drm_handle_t handle)
2656 drm_scatter_gather_t sg;
2660 if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
2668 * \param fd file descriptor.
2669 * \param vbl pointer to a drmVBlank structure.
2671 * \return zero on success, or a negative value on failure.
2674 * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
2676 drm_public int drmWaitVBlank(int fd, drmVBlankPtr vbl)
2678 struct timespec timeout, cur;
2681 ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2683 fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
2689 ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
2690 vbl->request.type &= ~DRM_VBLANK_RELATIVE;
2691 if (ret && errno == EINTR) {
2692 clock_gettime(CLOCK_MONOTONIC, &cur);
2693 /* Timeout after 1s */
2694 if (cur.tv_sec > timeout.tv_sec + 1 ||
2695 (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
2702 } while (ret && errno == EINTR);
2708 drm_public int drmError(int err, const char *label)
2711 case DRM_ERR_NO_DEVICE:
2712 fprintf(stderr, "%s: no device\n", label);
2714 case DRM_ERR_NO_ACCESS:
2715 fprintf(stderr, "%s: no access\n", label);
2717 case DRM_ERR_NOT_ROOT:
2718 fprintf(stderr, "%s: not root\n", label);
2720 case DRM_ERR_INVALID:
2721 fprintf(stderr, "%s: invalid args\n", label);
2726 fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2734 * Install IRQ handler.
2736 * \param fd file descriptor.
2737 * \param irq IRQ number.
2739 * \return zero on success, or a negative value on failure.
2742 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2743 * argument in a drm_control structure.
2745 drm_public int drmCtlInstHandler(int fd, int irq)
2750 ctl.func = DRM_INST_HANDLER;
2752 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2759 * Uninstall IRQ handler.
2761 * \param fd file descriptor.
2763 * \return zero on success, or a negative value on failure.
2766 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2767 * argument in a drm_control structure.
2769 drm_public int drmCtlUninstHandler(int fd)
2774 ctl.func = DRM_UNINST_HANDLER;
2776 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2781 drm_public int drmFinish(int fd, int context, drmLockFlags flags)
2786 lock.context = context;
2787 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
2788 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
2789 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
2790 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
2791 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2792 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2793 if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2799 * Get IRQ from bus ID.
2801 * \param fd file descriptor.
2802 * \param busnum bus number.
2803 * \param devnum device number.
2804 * \param funcnum function number.
2806 * \return IRQ number on success, or a negative value on failure.
2809 * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2810 * arguments in a drm_irq_busid structure.
2812 drm_public int drmGetInterruptFromBusID(int fd, int busnum, int devnum,
2820 p.funcnum = funcnum;
2821 if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2826 drm_public int drmAddContextTag(int fd, drm_context_t context, void *tag)
2828 drmHashEntry *entry = drmGetEntry(fd);
2830 if (drmHashInsert(entry->tagTable, context, tag)) {
2831 drmHashDelete(entry->tagTable, context);
2832 drmHashInsert(entry->tagTable, context, tag);
2837 drm_public int drmDelContextTag(int fd, drm_context_t context)
2839 drmHashEntry *entry = drmGetEntry(fd);
2841 return drmHashDelete(entry->tagTable, context);
2844 drm_public void *drmGetContextTag(int fd, drm_context_t context)
2846 drmHashEntry *entry = drmGetEntry(fd);
2849 if (drmHashLookup(entry->tagTable, context, &value))
2855 drm_public int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2856 drm_handle_t handle)
2858 drm_ctx_priv_map_t map;
2861 map.ctx_id = ctx_id;
2862 map.handle = (void *)(uintptr_t)handle;
2864 if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2869 drm_public int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2870 drm_handle_t *handle)
2872 drm_ctx_priv_map_t map;
2875 map.ctx_id = ctx_id;
2877 if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2880 *handle = (drm_handle_t)(uintptr_t)map.handle;
2885 drm_public int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2886 drmMapType *type, drmMapFlags *flags,
2887 drm_handle_t *handle, int *mtrr)
2893 if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2895 *offset = map.offset;
2897 *type = (drmMapType)map.type;
2898 *flags = (drmMapFlags)map.flags;
2899 *handle = (unsigned long)map.handle;
2904 drm_public int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2905 unsigned long *magic, unsigned long *iocs)
2907 drm_client_t client;
2911 if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2913 *auth = client.auth;
2916 *magic = client.magic;
2917 *iocs = client.iocs;
2921 drm_public int drmGetStats(int fd, drmStatsT *stats)
2927 if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2931 memset(stats, 0, sizeof(*stats));
2932 if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2936 stats->data[i].long_format = "%-20.20s"; \
2937 stats->data[i].rate_format = "%8.8s"; \
2938 stats->data[i].isvalue = 1; \
2939 stats->data[i].verbose = 0
2942 stats->data[i].long_format = "%-20.20s"; \
2943 stats->data[i].rate_format = "%5.5s"; \
2944 stats->data[i].isvalue = 0; \
2945 stats->data[i].mult_names = "kgm"; \
2946 stats->data[i].mult = 1000; \
2947 stats->data[i].verbose = 0
2950 stats->data[i].long_format = "%-20.20s"; \
2951 stats->data[i].rate_format = "%5.5s"; \
2952 stats->data[i].isvalue = 0; \
2953 stats->data[i].mult_names = "KGM"; \
2954 stats->data[i].mult = 1024; \
2955 stats->data[i].verbose = 0
2958 stats->count = s.count;
2959 for (i = 0; i < s.count; i++) {
2960 stats->data[i].value = s.data[i].value;
2961 switch (s.data[i].type) {
2962 case _DRM_STAT_LOCK:
2963 stats->data[i].long_name = "Lock";
2964 stats->data[i].rate_name = "Lock";
2967 case _DRM_STAT_OPENS:
2968 stats->data[i].long_name = "Opens";
2969 stats->data[i].rate_name = "O";
2971 stats->data[i].verbose = 1;
2973 case _DRM_STAT_CLOSES:
2974 stats->data[i].long_name = "Closes";
2975 stats->data[i].rate_name = "Lock";
2977 stats->data[i].verbose = 1;
2979 case _DRM_STAT_IOCTLS:
2980 stats->data[i].long_name = "Ioctls";
2981 stats->data[i].rate_name = "Ioc/s";
2984 case _DRM_STAT_LOCKS:
2985 stats->data[i].long_name = "Locks";
2986 stats->data[i].rate_name = "Lck/s";
2989 case _DRM_STAT_UNLOCKS:
2990 stats->data[i].long_name = "Unlocks";
2991 stats->data[i].rate_name = "Unl/s";
2995 stats->data[i].long_name = "IRQs";
2996 stats->data[i].rate_name = "IRQ/s";
2999 case _DRM_STAT_PRIMARY:
3000 stats->data[i].long_name = "Primary Bytes";
3001 stats->data[i].rate_name = "PB/s";
3004 case _DRM_STAT_SECONDARY:
3005 stats->data[i].long_name = "Secondary Bytes";
3006 stats->data[i].rate_name = "SB/s";
3010 stats->data[i].long_name = "DMA";
3011 stats->data[i].rate_name = "DMA/s";
3014 case _DRM_STAT_SPECIAL:
3015 stats->data[i].long_name = "Special DMA";
3016 stats->data[i].rate_name = "dma/s";
3019 case _DRM_STAT_MISSED:
3020 stats->data[i].long_name = "Miss";
3021 stats->data[i].rate_name = "Ms/s";
3024 case _DRM_STAT_VALUE:
3025 stats->data[i].long_name = "Value";
3026 stats->data[i].rate_name = "Value";
3029 case _DRM_STAT_BYTE:
3030 stats->data[i].long_name = "Bytes";
3031 stats->data[i].rate_name = "B/s";
3034 case _DRM_STAT_COUNT:
3036 stats->data[i].long_name = "Count";
3037 stats->data[i].rate_name = "Cnt/s";
3046 * Issue a set-version ioctl.
3048 * \param fd file descriptor.
3049 * \param drmCommandIndex command index
3050 * \param data source pointer of the data to be read and written.
3051 * \param size size of the data to be read and written.
3053 * \return zero on success, or a negative value on failure.
3056 * It issues a read-write ioctl given by
3057 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
3059 drm_public int drmSetInterfaceVersion(int fd, drmSetVersion *version)
3062 drm_set_version_t sv;
3065 sv.drm_di_major = version->drm_di_major;
3066 sv.drm_di_minor = version->drm_di_minor;
3067 sv.drm_dd_major = version->drm_dd_major;
3068 sv.drm_dd_minor = version->drm_dd_minor;
3070 if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
3074 version->drm_di_major = sv.drm_di_major;
3075 version->drm_di_minor = sv.drm_di_minor;
3076 version->drm_dd_major = sv.drm_dd_major;
3077 version->drm_dd_minor = sv.drm_dd_minor;
3083 * Send a device-specific command.
3085 * \param fd file descriptor.
3086 * \param drmCommandIndex command index
3088 * \return zero on success, or a negative value on failure.
3091 * It issues a ioctl given by
3092 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
3094 drm_public int drmCommandNone(int fd, unsigned long drmCommandIndex)
3096 unsigned long request;
3098 request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
3100 if (drmIoctl(fd, request, NULL)) {
3108 * Send a device-specific read command.
3110 * \param fd file descriptor.
3111 * \param drmCommandIndex command index
3112 * \param data destination pointer of the data to be read.
3113 * \param size size of the data to be read.
3115 * \return zero on success, or a negative value on failure.
3118 * It issues a read ioctl given by
3119 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
3121 drm_public int drmCommandRead(int fd, unsigned long drmCommandIndex,
3122 void *data, unsigned long size)
3124 unsigned long request;
3126 request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
3127 DRM_COMMAND_BASE + drmCommandIndex, size);
3129 if (drmIoctl(fd, request, data)) {
3137 * Send a device-specific write command.
3139 * \param fd file descriptor.
3140 * \param drmCommandIndex command index
3141 * \param data source pointer of the data to be written.
3142 * \param size size of the data to be written.
3144 * \return zero on success, or a negative value on failure.
3147 * It issues a write ioctl given by
3148 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
3150 drm_public int drmCommandWrite(int fd, unsigned long drmCommandIndex,
3151 void *data, unsigned long size)
3153 unsigned long request;
3155 request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
3156 DRM_COMMAND_BASE + drmCommandIndex, size);
3158 if (drmIoctl(fd, request, data)) {
3166 * Send a device-specific read-write command.
3168 * \param fd file descriptor.
3169 * \param drmCommandIndex command index
3170 * \param data source pointer of the data to be read and written.
3171 * \param size size of the data to be read and written.
3173 * \return zero on success, or a negative value on failure.
3176 * It issues a read-write ioctl given by
3177 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
3179 drm_public int drmCommandWriteRead(int fd, unsigned long drmCommandIndex,
3180 void *data, unsigned long size)
3182 unsigned long request;
3184 request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
3185 DRM_COMMAND_BASE + drmCommandIndex, size);
3187 if (drmIoctl(fd, request, data))
3192 #define DRM_MAX_FDS 16
3198 } connection[DRM_MAX_FDS];
3200 static int nr_fds = 0;
3202 drm_public int drmOpenOnce(void *unused, const char *BusID, int *newlyopened)
3204 return drmOpenOnceWithType(BusID, newlyopened, DRM_NODE_PRIMARY);
3207 drm_public int drmOpenOnceWithType(const char *BusID, int *newlyopened,
3213 for (i = 0; i < nr_fds; i++)
3214 if ((strcmp(BusID, connection[i].BusID) == 0) &&
3215 (connection[i].type == type)) {
3216 connection[i].refcount++;
3218 return connection[i].fd;
3221 fd = drmOpenWithType(NULL, BusID, type);
3222 if (fd < 0 || nr_fds == DRM_MAX_FDS)
3225 connection[nr_fds].BusID = strdup(BusID);
3226 connection[nr_fds].fd = fd;
3227 connection[nr_fds].refcount = 1;
3228 connection[nr_fds].type = type;
3232 fprintf(stderr, "saved connection %d for %s %d\n",
3233 nr_fds, connection[nr_fds].BusID,
3234 strcmp(BusID, connection[nr_fds].BusID));
3241 drm_public void drmCloseOnce(int fd)
3245 for (i = 0; i < nr_fds; i++) {
3246 if (fd == connection[i].fd) {
3247 if (--connection[i].refcount == 0) {
3248 drmClose(connection[i].fd);
3249 free(connection[i].BusID);
3252 connection[i] = connection[nr_fds];
3260 drm_public int drmSetMaster(int fd)
3262 return drmIoctl(fd, DRM_IOCTL_SET_MASTER, NULL);
3265 drm_public int drmDropMaster(int fd)
3267 return drmIoctl(fd, DRM_IOCTL_DROP_MASTER, NULL);
3270 drm_public int drmIsMaster(int fd)
3272 /* Detect master by attempting something that requires master.
3274 * Authenticating magic tokens requires master and 0 is an
3275 * internal kernel detail which we could use. Attempting this on
3276 * a master fd would fail therefore fail with EINVAL because 0
3279 * A non-master fd will fail with EACCES, as the kernel checks
3280 * for master before attempting to do anything else.
3282 * Since we don't want to leak implementation details, use
3285 return drmAuthMagic(fd, 0) != -EACCES;
3288 drm_public char *drmGetDeviceNameFromFd(int fd)
3295 if (fstat(fd, &sbuf))
3298 maj = major(sbuf.st_rdev);
3299 min = minor(sbuf.st_rdev);
3300 nodetype = drmGetMinorType(maj, min);
3301 return drmGetMinorNameForFD(fd, nodetype);
3308 /* The whole drmOpen thing is a fiasco and we need to find a way
3309 * back to just using open(2). For now, however, lets just make
3310 * things worse with even more ad hoc directory walking code to
3311 * discover the device file name. */
3316 for (i = 0; i < DRM_MAX_MINOR; i++) {
3317 snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
3318 if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
3321 if (i == DRM_MAX_MINOR)
3324 return strdup(name);
3328 static bool drmNodeIsDRM(int maj, int min)
3334 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device/drm",
3336 return stat(path, &sbuf) == 0;
3337 #elif defined(__FreeBSD__)
3338 char name[SPECNAMELEN];
3340 if (!devname_r(makedev(maj, min), S_IFCHR, name, sizeof(name)))
3342 /* Handle drm/ and dri/ as both are present in different FreeBSD version
3343 * FreeBSD on amd64/i386/powerpc external kernel modules create node in
3344 * in /dev/drm/ and links in /dev/dri while a WIP in kernel driver creates
3345 * only device nodes in /dev/dri/ */
3346 return (!strncmp(name, "drm/", 4) || !strncmp(name, "dri/", 4));
3348 return maj == DRM_MAJOR;
3352 drm_public int drmGetNodeTypeFromFd(int fd)
3357 if (fstat(fd, &sbuf))
3360 maj = major(sbuf.st_rdev);
3361 min = minor(sbuf.st_rdev);
3363 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode)) {
3368 type = drmGetMinorType(maj, min);
3374 drm_public int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags,
3377 struct drm_prime_handle args;
3382 args.handle = handle;
3384 ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
3388 *prime_fd = args.fd;
3392 drm_public int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
3394 struct drm_prime_handle args;
3399 ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
3403 *handle = args.handle;
3407 drm_public int drmCloseBufferHandle(int fd, uint32_t handle)
3409 struct drm_gem_close args;
3412 args.handle = handle;
3413 return drmIoctl(fd, DRM_IOCTL_GEM_CLOSE, &args);
3416 static char *drmGetMinorNameForFD(int fd, int type)
3422 const char *name = drmGetMinorName(type);
3424 char dev_name[64], buf[64];
3432 if (fstat(fd, &sbuf))
3435 maj = major(sbuf.st_rdev);
3436 min = minor(sbuf.st_rdev);
3438 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3441 snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
3443 sysdir = opendir(buf);
3447 while ((ent = readdir(sysdir))) {
3448 if (strncmp(ent->d_name, name, len) == 0) {
3449 if (snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
3454 return strdup(dev_name);
3460 #elif defined(__FreeBSD__)
3462 char dname[SPECNAMELEN];
3464 char name[SPECNAMELEN];
3465 int id, maj, min, nodetype, i;
3467 if (fstat(fd, &sbuf))
3470 maj = major(sbuf.st_rdev);
3471 min = minor(sbuf.st_rdev);
3473 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3476 if (!devname_r(sbuf.st_rdev, S_IFCHR, dname, sizeof(dname)))
3479 /* Handle both /dev/drm and /dev/dri
3480 * FreeBSD on amd64/i386/powerpc external kernel modules create node in
3481 * in /dev/drm/ and links in /dev/dri while a WIP in kernel driver creates
3482 * only device nodes in /dev/dri/ */
3484 /* Get the node type represented by fd so we can deduce the target name */
3485 nodetype = drmGetMinorType(maj, min);
3488 mname = drmGetMinorName(type);
3490 for (i = 0; i < SPECNAMELEN; i++) {
3491 if (isalpha(dname[i]) == 0 && dname[i] != '/')
3494 if (dname[i] == '\0')
3497 id = (int)strtol(&dname[i], NULL, 10);
3498 id -= drmGetMinorBase(nodetype);
3499 snprintf(name, sizeof(name), DRM_DIR_NAME "/%s%d", mname,
3500 id + drmGetMinorBase(type));
3502 return strdup(name);
3505 char buf[PATH_MAX + 1];
3506 const char *dev_name = drmGetDeviceName(type);
3507 unsigned int maj, min;
3510 if (fstat(fd, &sbuf))
3513 maj = major(sbuf.st_rdev);
3514 min = minor(sbuf.st_rdev);
3516 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3522 n = snprintf(buf, sizeof(buf), dev_name, DRM_DIR_NAME, min);
3523 if (n == -1 || n >= sizeof(buf))
3530 drm_public char *drmGetPrimaryDeviceNameFromFd(int fd)
3532 return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
3535 drm_public char *drmGetRenderDeviceNameFromFd(int fd)
3537 return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
3541 static char * DRM_PRINTFLIKE(2, 3)
3542 sysfs_uevent_get(const char *path, const char *fmt, ...)
3544 char filename[PATH_MAX + 1], *key, *line = NULL, *value = NULL;
3545 size_t size = 0, len;
3551 num = vasprintf(&key, fmt, ap);
3555 snprintf(filename, sizeof(filename), "%s/uevent", path);
3557 fp = fopen(filename, "r");
3563 while ((num = getline(&line, &size, fp)) >= 0) {
3564 if ((strncmp(line, key, len) == 0) && (line[len] == '=')) {
3565 char *start = line + len + 1, *end = line + num - 1;
3570 value = strndup(start, end - start);
3584 /* Little white lie to avoid major rework of the existing code */
3585 #define DRM_BUS_VIRTIO 0x10
3588 static int get_subsystem_type(const char *device_path)
3590 char path[PATH_MAX + 1] = "";
3591 char link[PATH_MAX + 1] = "";
3597 { "/pci", DRM_BUS_PCI },
3598 { "/usb", DRM_BUS_USB },
3599 { "/platform", DRM_BUS_PLATFORM },
3600 { "/spi", DRM_BUS_PLATFORM },
3601 { "/host1x", DRM_BUS_HOST1X },
3602 { "/virtio", DRM_BUS_VIRTIO },
3605 strncpy(path, device_path, PATH_MAX);
3606 strncat(path, "/subsystem", PATH_MAX);
3608 if (readlink(path, link, PATH_MAX) < 0)
3611 name = strrchr(link, '/');
3615 for (unsigned i = 0; i < ARRAY_SIZE(bus_types); i++) {
3616 if (strncmp(name, bus_types[i].name, strlen(bus_types[i].name)) == 0)
3617 return bus_types[i].bus_type;
3624 static int drmParseSubsystemType(int maj, int min)
3627 char path[PATH_MAX + 1] = "";
3628 char real_path[PATH_MAX + 1] = "";
3631 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3633 subsystem_type = get_subsystem_type(path);
3634 /* Try to get the parent (underlying) device type */
3635 if (subsystem_type == DRM_BUS_VIRTIO) {
3636 /* Assume virtio-pci on error */
3637 if (!realpath(path, real_path))
3638 return DRM_BUS_VIRTIO;
3639 strncat(path, "/..", PATH_MAX);
3640 subsystem_type = get_subsystem_type(path);
3641 if (subsystem_type < 0)
3642 return DRM_BUS_VIRTIO;
3644 return subsystem_type;
3645 #elif defined(__OpenBSD__) || defined(__DragonFly__) || defined(__FreeBSD__)
3648 #warning "Missing implementation of drmParseSubsystemType"
3655 get_pci_path(int maj, int min, char *pci_path)
3657 char path[PATH_MAX + 1], *term;
3659 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3660 if (!realpath(path, pci_path)) {
3661 strcpy(pci_path, path);
3665 term = strrchr(pci_path, '/');
3666 if (term && strncmp(term, "/virtio", 7) == 0)
3672 static int get_sysctl_pci_bus_info(int maj, int min, drmPciBusInfoPtr info)
3674 char dname[SPECNAMELEN];
3675 char sysctl_name[16];
3676 char sysctl_val[256];
3678 int id, type, nelem;
3679 unsigned int rdev, majmin, domain, bus, dev, func;
3681 rdev = makedev(maj, min);
3682 if (!devname_r(rdev, S_IFCHR, dname, sizeof(dname)))
3685 if (sscanf(dname, "drm/%d\n", &id) != 1)
3687 type = drmGetMinorType(maj, min);
3691 /* BUG: This above section is iffy, since it mandates that a driver will
3692 * create both card and render node.
3693 * If it does not, the next DRM device will create card#X and
3694 * renderD#(128+X)-1.
3695 * This is a possibility in FreeBSD but for now there is no good way for
3696 * obtaining the info.
3699 case DRM_NODE_PRIMARY:
3701 case DRM_NODE_CONTROL:
3704 case DRM_NODE_RENDER:
3711 if (snprintf(sysctl_name, sizeof(sysctl_name), "hw.dri.%d.busid", id) <= 0)
3713 sysctl_len = sizeof(sysctl_val);
3714 if (sysctlbyname(sysctl_name, sysctl_val, &sysctl_len, NULL, 0))
3717 #define bus_fmt "pci:%04x:%02x:%02x.%u"
3719 nelem = sscanf(sysctl_val, bus_fmt, &domain, &bus, &dev, &func);
3722 info->domain = domain;
3731 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
3734 unsigned int domain, bus, dev, func;
3735 char pci_path[PATH_MAX + 1], *value;
3738 get_pci_path(maj, min, pci_path);
3740 value = sysfs_uevent_get(pci_path, "PCI_SLOT_NAME");
3744 num = sscanf(value, "%04x:%02x:%02x.%1u", &domain, &bus, &dev, &func);
3750 info->domain = domain;
3756 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3757 struct drm_pciinfo pinfo;
3760 type = drmGetMinorType(maj, min);
3764 fd = drmOpenMinor(min, 0, type);
3768 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3774 info->domain = pinfo.domain;
3775 info->bus = pinfo.bus;
3776 info->dev = pinfo.dev;
3777 info->func = pinfo.func;
3780 #elif defined(__FreeBSD__)
3781 return get_sysctl_pci_bus_info(maj, min, info);
3783 #warning "Missing implementation of drmParsePciBusInfo"
3788 drm_public int drmDevicesEqual(drmDevicePtr a, drmDevicePtr b)
3790 if (a == NULL || b == NULL)
3793 if (a->bustype != b->bustype)
3796 switch (a->bustype) {
3798 return memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo)) == 0;
3801 return memcmp(a->businfo.usb, b->businfo.usb, sizeof(drmUsbBusInfo)) == 0;
3803 case DRM_BUS_PLATFORM:
3804 return memcmp(a->businfo.platform, b->businfo.platform, sizeof(drmPlatformBusInfo)) == 0;
3806 case DRM_BUS_HOST1X:
3807 return memcmp(a->businfo.host1x, b->businfo.host1x, sizeof(drmHost1xBusInfo)) == 0;
3816 static int drmGetNodeType(const char *name)
3818 if (strncmp(name, DRM_CONTROL_MINOR_NAME,
3819 sizeof(DRM_CONTROL_MINOR_NAME ) - 1) == 0)
3820 return DRM_NODE_CONTROL;
3822 if (strncmp(name, DRM_RENDER_MINOR_NAME,
3823 sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
3824 return DRM_NODE_RENDER;
3826 if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
3827 sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
3828 return DRM_NODE_PRIMARY;
3833 static int drmGetMaxNodeName(void)
3835 return sizeof(DRM_DIR_NAME) +
3836 MAX3(sizeof(DRM_PRIMARY_MINOR_NAME),
3837 sizeof(DRM_CONTROL_MINOR_NAME),
3838 sizeof(DRM_RENDER_MINOR_NAME)) +
3839 3 /* length of the node number */;
3843 static int parse_separate_sysfs_files(int maj, int min,
3844 drmPciDeviceInfoPtr device,
3845 bool ignore_revision)
3847 static const char *attrs[] = {
3848 "revision", /* Older kernels are missing the file, so check for it first */
3854 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3855 unsigned int data[ARRAY_SIZE(attrs)];
3859 get_pci_path(maj, min, pci_path);
3861 for (unsigned i = ignore_revision ? 1 : 0; i < ARRAY_SIZE(attrs); i++) {
3862 if (snprintf(path, PATH_MAX, "%s/%s", pci_path, attrs[i]) < 0)
3865 fp = fopen(path, "r");
3869 ret = fscanf(fp, "%x", &data[i]);
3876 device->revision_id = ignore_revision ? 0xff : data[0] & 0xff;
3877 device->vendor_id = data[1] & 0xffff;
3878 device->device_id = data[2] & 0xffff;
3879 device->subvendor_id = data[3] & 0xffff;
3880 device->subdevice_id = data[4] & 0xffff;
3885 static int parse_config_sysfs_file(int maj, int min,
3886 drmPciDeviceInfoPtr device)
3888 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3889 unsigned char config[64];
3892 get_pci_path(maj, min, pci_path);
3894 if (snprintf(path, PATH_MAX, "%s/config", pci_path) < 0)
3897 fd = open(path, O_RDONLY);
3901 ret = read(fd, config, sizeof(config));
3906 device->vendor_id = config[0] | (config[1] << 8);
3907 device->device_id = config[2] | (config[3] << 8);
3908 device->revision_id = config[8];
3909 device->subvendor_id = config[44] | (config[45] << 8);
3910 device->subdevice_id = config[46] | (config[47] << 8);
3916 static int drmParsePciDeviceInfo(int maj, int min,
3917 drmPciDeviceInfoPtr device,
3921 if (!(flags & DRM_DEVICE_GET_PCI_REVISION))
3922 return parse_separate_sysfs_files(maj, min, device, true);
3924 if (parse_separate_sysfs_files(maj, min, device, false))
3925 return parse_config_sysfs_file(maj, min, device);
3928 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3929 struct drm_pciinfo pinfo;
3932 type = drmGetMinorType(maj, min);
3936 fd = drmOpenMinor(min, 0, type);
3940 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3946 device->vendor_id = pinfo.vendor_id;
3947 device->device_id = pinfo.device_id;
3948 device->revision_id = pinfo.revision_id;
3949 device->subvendor_id = pinfo.subvendor_id;
3950 device->subdevice_id = pinfo.subdevice_id;
3953 #elif defined(__FreeBSD__)
3955 struct pci_conf_io pc;
3956 struct pci_match_conf patterns[1];
3957 struct pci_conf results[1];
3960 if (get_sysctl_pci_bus_info(maj, min, &info) != 0)
3963 fd = open("/dev/pci", O_RDONLY);
3967 bzero(&patterns, sizeof(patterns));
3968 patterns[0].pc_sel.pc_domain = info.domain;
3969 patterns[0].pc_sel.pc_bus = info.bus;
3970 patterns[0].pc_sel.pc_dev = info.dev;
3971 patterns[0].pc_sel.pc_func = info.func;
3972 patterns[0].flags = PCI_GETCONF_MATCH_DOMAIN | PCI_GETCONF_MATCH_BUS
3973 | PCI_GETCONF_MATCH_DEV | PCI_GETCONF_MATCH_FUNC;
3974 bzero(&pc, sizeof(struct pci_conf_io));
3975 pc.num_patterns = 1;
3976 pc.pat_buf_len = sizeof(patterns);
3977 pc.patterns = patterns;
3978 pc.match_buf_len = sizeof(results);
3979 pc.matches = results;
3981 if (ioctl(fd, PCIOCGETCONF, &pc) || pc.status == PCI_GETCONF_ERROR) {
3988 device->vendor_id = results[0].pc_vendor;
3989 device->device_id = results[0].pc_device;
3990 device->subvendor_id = results[0].pc_subvendor;
3991 device->subdevice_id = results[0].pc_subdevice;
3992 device->revision_id = results[0].pc_revid;
3996 #warning "Missing implementation of drmParsePciDeviceInfo"
4001 static void drmFreePlatformDevice(drmDevicePtr device)
4003 if (device->deviceinfo.platform) {
4004 if (device->deviceinfo.platform->compatible) {
4005 char **compatible = device->deviceinfo.platform->compatible;
4007 while (*compatible) {
4012 free(device->deviceinfo.platform->compatible);
4017 static void drmFreeHost1xDevice(drmDevicePtr device)
4019 if (device->deviceinfo.host1x) {
4020 if (device->deviceinfo.host1x->compatible) {
4021 char **compatible = device->deviceinfo.host1x->compatible;
4023 while (*compatible) {
4028 free(device->deviceinfo.host1x->compatible);
4033 drm_public void drmFreeDevice(drmDevicePtr *device)
4039 switch ((*device)->bustype) {
4040 case DRM_BUS_PLATFORM:
4041 drmFreePlatformDevice(*device);
4044 case DRM_BUS_HOST1X:
4045 drmFreeHost1xDevice(*device);
4054 drm_public void drmFreeDevices(drmDevicePtr devices[], int count)
4058 if (devices == NULL)
4061 for (i = 0; i < count; i++)
4063 drmFreeDevice(&devices[i]);
4066 static drmDevicePtr drmDeviceAlloc(unsigned int type, const char *node,
4067 size_t bus_size, size_t device_size,
4070 size_t max_node_length, extra, size;
4071 drmDevicePtr device;
4075 max_node_length = ALIGN(drmGetMaxNodeName(), sizeof(void *));
4076 extra = DRM_NODE_MAX * (sizeof(void *) + max_node_length);
4078 size = sizeof(*device) + extra + bus_size + device_size;
4080 device = calloc(1, size);
4084 device->available_nodes = 1 << type;
4086 ptr = (char *)device + sizeof(*device);
4087 device->nodes = (char **)ptr;
4089 ptr += DRM_NODE_MAX * sizeof(void *);
4091 for (i = 0; i < DRM_NODE_MAX; i++) {
4092 device->nodes[i] = ptr;
4093 ptr += max_node_length;
4096 memcpy(device->nodes[type], node, max_node_length);
4103 static int drmProcessPciDevice(drmDevicePtr *device,
4104 const char *node, int node_type,
4105 int maj, int min, bool fetch_deviceinfo,
4112 dev = drmDeviceAlloc(node_type, node, sizeof(drmPciBusInfo),
4113 sizeof(drmPciDeviceInfo), &addr);
4117 dev->bustype = DRM_BUS_PCI;
4119 dev->businfo.pci = (drmPciBusInfoPtr)addr;
4121 ret = drmParsePciBusInfo(maj, min, dev->businfo.pci);
4125 // Fetch the device info if the user has requested it
4126 if (fetch_deviceinfo) {
4127 addr += sizeof(drmPciBusInfo);
4128 dev->deviceinfo.pci = (drmPciDeviceInfoPtr)addr;
4130 ret = drmParsePciDeviceInfo(maj, min, dev->deviceinfo.pci, flags);
4145 static int drm_usb_dev_path(int maj, int min, char *path, size_t len)
4147 char *value, *tmp_path, *slash;
4148 bool usb_device, usb_interface;
4150 snprintf(path, len, "/sys/dev/char/%d:%d/device", maj, min);
4152 value = sysfs_uevent_get(path, "DEVTYPE");
4156 usb_device = strcmp(value, "usb_device") == 0;
4157 usb_interface = strcmp(value, "usb_interface") == 0;
4165 /* The parent of a usb_interface is a usb_device */
4167 tmp_path = realpath(path, NULL);
4171 slash = strrchr(tmp_path, '/');
4179 if (snprintf(path, len, "%s", tmp_path) >= (int)len) {
4189 static int drmParseUsbBusInfo(int maj, int min, drmUsbBusInfoPtr info)
4192 char path[PATH_MAX + 1], *value;
4193 unsigned int bus, dev;
4196 ret = drm_usb_dev_path(maj, min, path, sizeof(path));
4200 value = sysfs_uevent_get(path, "BUSNUM");
4204 ret = sscanf(value, "%03u", &bus);
4210 value = sysfs_uevent_get(path, "DEVNUM");
4214 ret = sscanf(value, "%03u", &dev);
4225 #warning "Missing implementation of drmParseUsbBusInfo"
4230 static int drmParseUsbDeviceInfo(int maj, int min, drmUsbDeviceInfoPtr info)
4233 char path[PATH_MAX + 1], *value;
4234 unsigned int vendor, product;
4237 ret = drm_usb_dev_path(maj, min, path, sizeof(path));
4241 value = sysfs_uevent_get(path, "PRODUCT");
4245 ret = sscanf(value, "%x/%x", &vendor, &product);
4251 info->vendor = vendor;
4252 info->product = product;
4256 #warning "Missing implementation of drmParseUsbDeviceInfo"
4261 static int drmProcessUsbDevice(drmDevicePtr *device, const char *node,
4262 int node_type, int maj, int min,
4263 bool fetch_deviceinfo, uint32_t flags)
4269 dev = drmDeviceAlloc(node_type, node, sizeof(drmUsbBusInfo),
4270 sizeof(drmUsbDeviceInfo), &ptr);
4274 dev->bustype = DRM_BUS_USB;
4276 dev->businfo.usb = (drmUsbBusInfoPtr)ptr;
4278 ret = drmParseUsbBusInfo(maj, min, dev->businfo.usb);
4282 if (fetch_deviceinfo) {
4283 ptr += sizeof(drmUsbBusInfo);
4284 dev->deviceinfo.usb = (drmUsbDeviceInfoPtr)ptr;
4286 ret = drmParseUsbDeviceInfo(maj, min, dev->deviceinfo.usb);
4300 static int drmParseOFBusInfo(int maj, int min, char *fullname)
4303 char path[PATH_MAX + 1], *name, *tmp_name;
4305 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
4307 name = sysfs_uevent_get(path, "OF_FULLNAME");
4310 /* If the device lacks OF data, pick the MODALIAS info */
4311 name = sysfs_uevent_get(path, "MODALIAS");
4315 /* .. and strip the MODALIAS=[platform,usb...]: part. */
4316 tmp_name = strrchr(name, ':');
4324 strncpy(fullname, tmp_name, DRM_PLATFORM_DEVICE_NAME_LEN);
4325 fullname[DRM_PLATFORM_DEVICE_NAME_LEN - 1] = '\0';
4330 #warning "Missing implementation of drmParseOFBusInfo"
4335 static int drmParseOFDeviceInfo(int maj, int min, char ***compatible)
4338 char path[PATH_MAX + 1], *value, *tmp_name;
4339 unsigned int count, i;
4342 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
4344 value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
4346 sscanf(value, "%u", &count);
4349 /* Assume one entry if the device lack OF data */
4353 *compatible = calloc(count + 1, sizeof(char *));
4357 for (i = 0; i < count; i++) {
4358 value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
4361 /* If the device lacks OF data, pick the MODALIAS info */
4362 value = sysfs_uevent_get(path, "MODALIAS");
4368 /* .. and strip the MODALIAS=[platform,usb...]: part. */
4369 tmp_name = strrchr(value, ':');
4374 tmp_name = strdup(tmp_name + 1);
4378 (*compatible)[i] = tmp_name;
4385 free((*compatible)[i]);
4390 #warning "Missing implementation of drmParseOFDeviceInfo"
4395 static int drmProcessPlatformDevice(drmDevicePtr *device,
4396 const char *node, int node_type,
4397 int maj, int min, bool fetch_deviceinfo,
4404 dev = drmDeviceAlloc(node_type, node, sizeof(drmPlatformBusInfo),
4405 sizeof(drmPlatformDeviceInfo), &ptr);
4409 dev->bustype = DRM_BUS_PLATFORM;
4411 dev->businfo.platform = (drmPlatformBusInfoPtr)ptr;
4413 ret = drmParseOFBusInfo(maj, min, dev->businfo.platform->fullname);
4417 if (fetch_deviceinfo) {
4418 ptr += sizeof(drmPlatformBusInfo);
4419 dev->deviceinfo.platform = (drmPlatformDeviceInfoPtr)ptr;
4421 ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.platform->compatible);
4435 static int drmProcessHost1xDevice(drmDevicePtr *device,
4436 const char *node, int node_type,
4437 int maj, int min, bool fetch_deviceinfo,
4444 dev = drmDeviceAlloc(node_type, node, sizeof(drmHost1xBusInfo),
4445 sizeof(drmHost1xDeviceInfo), &ptr);
4449 dev->bustype = DRM_BUS_HOST1X;
4451 dev->businfo.host1x = (drmHost1xBusInfoPtr)ptr;
4453 ret = drmParseOFBusInfo(maj, min, dev->businfo.host1x->fullname);
4457 if (fetch_deviceinfo) {
4458 ptr += sizeof(drmHost1xBusInfo);
4459 dev->deviceinfo.host1x = (drmHost1xDeviceInfoPtr)ptr;
4461 ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.host1x->compatible);
4476 process_device(drmDevicePtr *device, const char *d_name,
4477 int req_subsystem_type,
4478 bool fetch_deviceinfo, uint32_t flags)
4481 char node[PATH_MAX + 1];
4482 int node_type, subsystem_type;
4483 unsigned int maj, min;
4485 node_type = drmGetNodeType(d_name);
4489 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, d_name);
4490 if (stat(node, &sbuf))
4493 maj = major(sbuf.st_rdev);
4494 min = minor(sbuf.st_rdev);
4496 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4499 subsystem_type = drmParseSubsystemType(maj, min);
4500 if (req_subsystem_type != -1 && req_subsystem_type != subsystem_type)
4503 switch (subsystem_type) {
4505 case DRM_BUS_VIRTIO:
4506 return drmProcessPciDevice(device, node, node_type, maj, min,
4507 fetch_deviceinfo, flags);
4509 return drmProcessUsbDevice(device, node, node_type, maj, min,
4510 fetch_deviceinfo, flags);
4511 case DRM_BUS_PLATFORM:
4512 return drmProcessPlatformDevice(device, node, node_type, maj, min,
4513 fetch_deviceinfo, flags);
4514 case DRM_BUS_HOST1X:
4515 return drmProcessHost1xDevice(device, node, node_type, maj, min,
4516 fetch_deviceinfo, flags);
4522 /* Consider devices located on the same bus as duplicate and fold the respective
4523 * entries into a single one.
4525 * Note: this leaves "gaps" in the array, while preserving the length.
4527 static void drmFoldDuplicatedDevices(drmDevicePtr local_devices[], int count)
4529 int node_type, i, j;
4531 for (i = 0; i < count; i++) {
4532 for (j = i + 1; j < count; j++) {
4533 if (drmDevicesEqual(local_devices[i], local_devices[j])) {
4534 local_devices[i]->available_nodes |= local_devices[j]->available_nodes;
4535 node_type = log2_int(local_devices[j]->available_nodes);
4536 memcpy(local_devices[i]->nodes[node_type],
4537 local_devices[j]->nodes[node_type], drmGetMaxNodeName());
4538 drmFreeDevice(&local_devices[j]);
4544 /* Check that the given flags are valid returning 0 on success */
4546 drm_device_validate_flags(uint32_t flags)
4548 return (flags & ~DRM_DEVICE_GET_PCI_REVISION);
4552 drm_device_has_rdev(drmDevicePtr device, dev_t find_rdev)
4556 for (int i = 0; i < DRM_NODE_MAX; i++) {
4557 if (device->available_nodes & 1 << i) {
4558 if (stat(device->nodes[i], &sbuf) == 0 &&
4559 sbuf.st_rdev == find_rdev)
4567 * The kernel drm core has a number of places that assume maximum of
4568 * 3x64 devices nodes. That's 64 for each of primary, control and
4569 * render nodes. Rounded it up to 256 for simplicity.
4571 #define MAX_DRM_NODES 256
4574 * Get information about a device from its dev_t identifier
4576 * \param find_rdev dev_t identifier of the device
4577 * \param flags feature/behaviour bitmask
4578 * \param device the address of a drmDevicePtr where the information
4579 * will be allocated in stored
4581 * \return zero on success, negative error code otherwise.
4583 drm_public int drmGetDeviceFromDevId(dev_t find_rdev, uint32_t flags, drmDevicePtr *device)
4587 * DRI device nodes on OpenBSD are not in their own directory, they reside
4588 * in /dev along with a large number of statically generated /dev nodes.
4589 * Avoid stat'ing all of /dev needlessly by implementing this custom path.
4592 char node[PATH_MAX + 1];
4593 const char *dev_name;
4594 int node_type, subsystem_type;
4595 int maj, min, n, ret;
4600 maj = major(find_rdev);
4601 min = minor(find_rdev);
4603 if (!drmNodeIsDRM(maj, min))
4606 node_type = drmGetMinorType(maj, min);
4607 if (node_type == -1)
4610 dev_name = drmGetDeviceName(node_type);
4614 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min);
4615 if (n == -1 || n >= PATH_MAX)
4617 if (stat(node, &sbuf))
4620 subsystem_type = drmParseSubsystemType(maj, min);
4621 if (subsystem_type != DRM_BUS_PCI)
4624 ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
4632 drmDevicePtr local_devices[MAX_DRM_NODES];
4635 struct dirent *dent;
4638 int ret, i, node_count;
4640 if (drm_device_validate_flags(flags))
4646 maj = major(find_rdev);
4647 min = minor(find_rdev);
4649 if (!drmNodeIsDRM(maj, min))
4652 subsystem_type = drmParseSubsystemType(maj, min);
4653 if (subsystem_type < 0)
4654 return subsystem_type;
4656 sysdir = opendir(DRM_DIR_NAME);
4661 while ((dent = readdir(sysdir))) {
4662 ret = process_device(&d, dent->d_name, subsystem_type, true, flags);
4666 if (i >= MAX_DRM_NODES) {
4667 fprintf(stderr, "More than %d drm nodes detected. "
4668 "Please report a bug - that should not happen.\n"
4669 "Skipping extra nodes\n", MAX_DRM_NODES);
4672 local_devices[i] = d;
4677 drmFoldDuplicatedDevices(local_devices, node_count);
4681 for (i = 0; i < node_count; i++) {
4682 if (!local_devices[i])
4685 if (drm_device_has_rdev(local_devices[i], find_rdev))
4686 *device = local_devices[i];
4688 drmFreeDevice(&local_devices[i]);
4692 if (*device == NULL)
4699 * Get information about the opened drm device
4701 * \param fd file descriptor of the drm device
4702 * \param flags feature/behaviour bitmask
4703 * \param device the address of a drmDevicePtr where the information
4704 * will be allocated in stored
4706 * \return zero on success, negative error code otherwise.
4708 * \note Unlike drmGetDevice it does not retrieve the pci device revision field
4709 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
4711 drm_public int drmGetDevice2(int fd, uint32_t flags, drmDevicePtr *device)
4718 if (fstat(fd, &sbuf))
4721 if (!S_ISCHR(sbuf.st_mode))
4724 return drmGetDeviceFromDevId(sbuf.st_rdev, flags, device);
4728 * Get information about the opened drm device
4730 * \param fd file descriptor of the drm device
4731 * \param device the address of a drmDevicePtr where the information
4732 * will be allocated in stored
4734 * \return zero on success, negative error code otherwise.
4736 drm_public int drmGetDevice(int fd, drmDevicePtr *device)
4738 return drmGetDevice2(fd, DRM_DEVICE_GET_PCI_REVISION, device);
4742 * Get drm devices on the system
4744 * \param flags feature/behaviour bitmask
4745 * \param devices the array of devices with drmDevicePtr elements
4746 * can be NULL to get the device number first
4747 * \param max_devices the maximum number of devices for the array
4749 * \return on error - negative error code,
4750 * if devices is NULL - total number of devices available on the system,
4751 * alternatively the number of devices stored in devices[], which is
4752 * capped by the max_devices.
4754 * \note Unlike drmGetDevices it does not retrieve the pci device revision field
4755 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
4757 drm_public int drmGetDevices2(uint32_t flags, drmDevicePtr devices[],
4760 drmDevicePtr local_devices[MAX_DRM_NODES];
4761 drmDevicePtr device;
4763 struct dirent *dent;
4764 int ret, i, node_count, device_count;
4766 if (drm_device_validate_flags(flags))
4769 sysdir = opendir(DRM_DIR_NAME);
4774 while ((dent = readdir(sysdir))) {
4775 ret = process_device(&device, dent->d_name, -1, devices != NULL, flags);
4779 if (i >= MAX_DRM_NODES) {
4780 fprintf(stderr, "More than %d drm nodes detected. "
4781 "Please report a bug - that should not happen.\n"
4782 "Skipping extra nodes\n", MAX_DRM_NODES);
4785 local_devices[i] = device;
4790 drmFoldDuplicatedDevices(local_devices, node_count);
4793 for (i = 0; i < node_count; i++) {
4794 if (!local_devices[i])
4797 if ((devices != NULL) && (device_count < max_devices))
4798 devices[device_count] = local_devices[i];
4800 drmFreeDevice(&local_devices[i]);
4807 if (devices != NULL)
4808 return MIN2(device_count, max_devices);
4810 return device_count;
4814 * Get drm devices on the system
4816 * \param devices the array of devices with drmDevicePtr elements
4817 * can be NULL to get the device number first
4818 * \param max_devices the maximum number of devices for the array
4820 * \return on error - negative error code,
4821 * if devices is NULL - total number of devices available on the system,
4822 * alternatively the number of devices stored in devices[], which is
4823 * capped by the max_devices.
4825 drm_public int drmGetDevices(drmDevicePtr devices[], int max_devices)
4827 return drmGetDevices2(DRM_DEVICE_GET_PCI_REVISION, devices, max_devices);
4830 drm_public char *drmGetDeviceNameFromFd2(int fd)
4834 char path[PATH_MAX + 1], *value;
4835 unsigned int maj, min;
4837 if (fstat(fd, &sbuf))
4840 maj = major(sbuf.st_rdev);
4841 min = minor(sbuf.st_rdev);
4843 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4846 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d", maj, min);
4848 value = sysfs_uevent_get(path, "DEVNAME");
4852 snprintf(path, sizeof(path), "/dev/%s", value);
4855 return strdup(path);
4856 #elif defined(__FreeBSD__)
4857 return drmGetDeviceNameFromFd(fd);
4860 char node[PATH_MAX + 1];
4861 const char *dev_name;
4865 if (fstat(fd, &sbuf))
4868 maj = major(sbuf.st_rdev);
4869 min = minor(sbuf.st_rdev);
4871 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4874 node_type = drmGetMinorType(maj, min);
4875 if (node_type == -1)
4878 dev_name = drmGetDeviceName(node_type);
4882 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min);
4883 if (n == -1 || n >= PATH_MAX)
4886 return strdup(node);
4890 drm_public int drmSyncobjCreate(int fd, uint32_t flags, uint32_t *handle)
4892 struct drm_syncobj_create args;
4898 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_CREATE, &args);
4901 *handle = args.handle;
4905 drm_public int drmSyncobjDestroy(int fd, uint32_t handle)
4907 struct drm_syncobj_destroy args;
4910 args.handle = handle;
4911 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_DESTROY, &args);
4914 drm_public int drmSyncobjHandleToFD(int fd, uint32_t handle, int *obj_fd)
4916 struct drm_syncobj_handle args;
4921 args.handle = handle;
4922 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4929 drm_public int drmSyncobjFDToHandle(int fd, int obj_fd, uint32_t *handle)
4931 struct drm_syncobj_handle args;
4937 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4940 *handle = args.handle;
4944 drm_public int drmSyncobjImportSyncFile(int fd, uint32_t handle,
4947 struct drm_syncobj_handle args;
4950 args.fd = sync_file_fd;
4951 args.handle = handle;
4952 args.flags = DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE;
4953 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4956 drm_public int drmSyncobjExportSyncFile(int fd, uint32_t handle,
4959 struct drm_syncobj_handle args;
4964 args.handle = handle;
4965 args.flags = DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE;
4966 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4969 *sync_file_fd = args.fd;
4973 drm_public int drmSyncobjWait(int fd, uint32_t *handles, unsigned num_handles,
4974 int64_t timeout_nsec, unsigned flags,
4975 uint32_t *first_signaled)
4977 struct drm_syncobj_wait args;
4981 args.handles = (uintptr_t)handles;
4982 args.timeout_nsec = timeout_nsec;
4983 args.count_handles = num_handles;
4986 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_WAIT, &args);
4991 *first_signaled = args.first_signaled;
4995 drm_public int drmSyncobjReset(int fd, const uint32_t *handles,
4996 uint32_t handle_count)
4998 struct drm_syncobj_array args;
5002 args.handles = (uintptr_t)handles;
5003 args.count_handles = handle_count;
5005 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_RESET, &args);
5009 drm_public int drmSyncobjSignal(int fd, const uint32_t *handles,
5010 uint32_t handle_count)
5012 struct drm_syncobj_array args;
5016 args.handles = (uintptr_t)handles;
5017 args.count_handles = handle_count;
5019 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_SIGNAL, &args);
5023 drm_public int drmSyncobjTimelineSignal(int fd, const uint32_t *handles,
5024 uint64_t *points, uint32_t handle_count)
5026 struct drm_syncobj_timeline_array args;
5030 args.handles = (uintptr_t)handles;
5031 args.points = (uintptr_t)points;
5032 args.count_handles = handle_count;
5034 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TIMELINE_SIGNAL, &args);
5038 drm_public int drmSyncobjTimelineWait(int fd, uint32_t *handles, uint64_t *points,
5039 unsigned num_handles,
5040 int64_t timeout_nsec, unsigned flags,
5041 uint32_t *first_signaled)
5043 struct drm_syncobj_timeline_wait args;
5047 args.handles = (uintptr_t)handles;
5048 args.points = (uintptr_t)points;
5049 args.timeout_nsec = timeout_nsec;
5050 args.count_handles = num_handles;
5053 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TIMELINE_WAIT, &args);
5058 *first_signaled = args.first_signaled;
5063 drm_public int drmSyncobjQuery(int fd, uint32_t *handles, uint64_t *points,
5064 uint32_t handle_count)
5066 struct drm_syncobj_timeline_array args;
5070 args.handles = (uintptr_t)handles;
5071 args.points = (uintptr_t)points;
5072 args.count_handles = handle_count;
5074 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_QUERY, &args);
5080 drm_public int drmSyncobjQuery2(int fd, uint32_t *handles, uint64_t *points,
5081 uint32_t handle_count, uint32_t flags)
5083 struct drm_syncobj_timeline_array args;
5086 args.handles = (uintptr_t)handles;
5087 args.points = (uintptr_t)points;
5088 args.count_handles = handle_count;
5091 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_QUERY, &args);
5095 drm_public int drmSyncobjTransfer(int fd,
5096 uint32_t dst_handle, uint64_t dst_point,
5097 uint32_t src_handle, uint64_t src_point,
5100 struct drm_syncobj_transfer args;
5104 args.src_handle = src_handle;
5105 args.dst_handle = dst_handle;
5106 args.src_point = src_point;
5107 args.dst_point = dst_point;
5110 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TRANSFER, &args);
5116 drmGetFormatModifierFromSimpleTokens(uint64_t modifier)
5120 for (i = 0; i < ARRAY_SIZE(drm_format_modifier_table); i++) {
5121 if (drm_format_modifier_table[i].modifier == modifier)
5122 return strdup(drm_format_modifier_table[i].modifier_name);
5128 /** Retrieves a human-readable representation of a vendor (as a string) from
5129 * the format token modifier
5131 * \param modifier the format modifier token
5132 * \return a char pointer to the human-readable form of the vendor. Caller is
5133 * responsible for freeing it.
5136 drmGetFormatModifierVendor(uint64_t modifier)
5139 uint8_t vendor = fourcc_mod_get_vendor(modifier);
5141 for (i = 0; i < ARRAY_SIZE(drm_format_modifier_vendor_table); i++) {
5142 if (drm_format_modifier_vendor_table[i].vendor == vendor)
5143 return strdup(drm_format_modifier_vendor_table[i].vendor_name);
5149 /** Retrieves a human-readable representation string from a format token
5152 * If the dedicated function was not able to extract a valid name or searching
5153 * the format modifier was not in the table, this function would return NULL.
5155 * \param modifier the token format
5156 * \return a malloc'ed string representation of the modifier. Caller is
5157 * responsible for freeing the string returned.
5161 drmGetFormatModifierName(uint64_t modifier)
5163 uint8_t vendorid = fourcc_mod_get_vendor(modifier);
5164 char *modifier_found = NULL;
5167 for (i = 0; i < ARRAY_SIZE(modifier_format_vendor_table); i++) {
5168 if (modifier_format_vendor_table[i].vendor == vendorid)
5169 modifier_found = modifier_format_vendor_table[i].vendor_cb(modifier);
5172 if (!modifier_found)
5173 return drmGetFormatModifierFromSimpleTokens(modifier);
5175 return modifier_found;
5179 * Get a human-readable name for a DRM FourCC format.
5181 * \param format The format.
5182 * \return A malloc'ed string containing the format name. Caller is responsible
5186 drmGetFormatName(uint32_t format)
5192 be = (format & DRM_FORMAT_BIG_ENDIAN) ? "_BE" : "";
5193 format &= ~DRM_FORMAT_BIG_ENDIAN;
5195 if (format == DRM_FORMAT_INVALID)
5196 return strdup("INVALID");
5198 code[0] = (char) ((format >> 0) & 0xFF);
5199 code[1] = (char) ((format >> 8) & 0xFF);
5200 code[2] = (char) ((format >> 16) & 0xFF);
5201 code[3] = (char) ((format >> 24) & 0xFF);
5204 /* Trim spaces at the end */
5205 for (i = 3; i > 0 && code[i] == ' '; i--)
5208 str_size = strlen(code) + strlen(be) + 1;
5209 str = malloc(str_size);
5213 snprintf(str, str_size, "%s%s", code, be);