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 if (asprintf(&mod_nvidia, "BLOCK_LINEAR_2D,HEIGHT=%"PRIu64",KIND=%"PRIu64","
364 "GEN=%"PRIu64",SECTOR=%"PRIu64",COMPRESSION=%"PRIu64"", height,
365 kind, gen, sector, compression) < 0)
374 drmGetFormatModifierNameFromAmdDcc(uint64_t modifier, FILE *fp)
376 uint64_t dcc_max_compressed_block =
377 AMD_FMT_MOD_GET(DCC_MAX_COMPRESSED_BLOCK, modifier);
378 uint64_t dcc_retile = AMD_FMT_MOD_GET(DCC_RETILE, modifier);
380 const char *dcc_max_compressed_block_str = NULL;
385 fprintf(fp, ",DCC_RETILE");
387 if (!dcc_retile && AMD_FMT_MOD_GET(DCC_PIPE_ALIGN, modifier))
388 fprintf(fp, ",DCC_PIPE_ALIGN");
390 if (AMD_FMT_MOD_GET(DCC_INDEPENDENT_64B, modifier))
391 fprintf(fp, ",DCC_INDEPENDENT_64B");
393 if (AMD_FMT_MOD_GET(DCC_INDEPENDENT_128B, modifier))
394 fprintf(fp, ",DCC_INDEPENDENT_128B");
396 switch (dcc_max_compressed_block) {
397 case AMD_FMT_MOD_DCC_BLOCK_64B:
398 dcc_max_compressed_block_str = "64B";
400 case AMD_FMT_MOD_DCC_BLOCK_128B:
401 dcc_max_compressed_block_str = "128B";
403 case AMD_FMT_MOD_DCC_BLOCK_256B:
404 dcc_max_compressed_block_str = "256B";
408 if (dcc_max_compressed_block_str)
409 fprintf(fp, ",DCC_MAX_COMPRESSED_BLOCK=%s",
410 dcc_max_compressed_block_str);
412 if (AMD_FMT_MOD_GET(DCC_CONSTANT_ENCODE, modifier))
413 fprintf(fp, ",DCC_CONSTANT_ENCODE");
417 drmGetFormatModifierNameFromAmdTile(uint64_t modifier, FILE *fp)
419 uint64_t pipe_xor_bits, bank_xor_bits, packers, rb;
420 uint64_t pipe, pipe_align, dcc, dcc_retile, tile_version;
422 pipe_align = AMD_FMT_MOD_GET(DCC_PIPE_ALIGN, modifier);
423 pipe_xor_bits = AMD_FMT_MOD_GET(PIPE_XOR_BITS, modifier);
424 dcc = AMD_FMT_MOD_GET(DCC, modifier);
425 dcc_retile = AMD_FMT_MOD_GET(DCC_RETILE, modifier);
426 tile_version = AMD_FMT_MOD_GET(TILE_VERSION, modifier);
428 fprintf(fp, ",PIPE_XOR_BITS=%"PRIu64, pipe_xor_bits);
430 if (tile_version == AMD_FMT_MOD_TILE_VER_GFX9) {
431 bank_xor_bits = AMD_FMT_MOD_GET(BANK_XOR_BITS, modifier);
432 fprintf(fp, ",BANK_XOR_BITS=%"PRIu64, bank_xor_bits);
435 if (tile_version == AMD_FMT_MOD_TILE_VER_GFX10_RBPLUS) {
436 packers = AMD_FMT_MOD_GET(PACKERS, modifier);
437 fprintf(fp, ",PACKERS=%"PRIu64, packers);
440 if (dcc && tile_version == AMD_FMT_MOD_TILE_VER_GFX9) {
441 rb = AMD_FMT_MOD_GET(RB, modifier);
442 fprintf(fp, ",RB=%"PRIu64, rb);
445 if (dcc && tile_version == AMD_FMT_MOD_TILE_VER_GFX9 &&
446 (dcc_retile || pipe_align)) {
447 pipe = AMD_FMT_MOD_GET(PIPE, modifier);
448 fprintf(fp, ",PIPE_%"PRIu64, pipe);
453 drmGetFormatModifierNameFromAmd(uint64_t modifier)
455 uint64_t tile, tile_version, dcc;
457 char *mod_amd = NULL;
460 const char *str_tile = NULL;
461 const char *str_tile_version = NULL;
463 tile = AMD_FMT_MOD_GET(TILE, modifier);
464 tile_version = AMD_FMT_MOD_GET(TILE_VERSION, modifier);
465 dcc = AMD_FMT_MOD_GET(DCC, modifier);
467 fp = open_memstream(&mod_amd, &size);
472 switch (tile_version) {
473 case AMD_FMT_MOD_TILE_VER_GFX9:
474 str_tile_version = "GFX9";
476 case AMD_FMT_MOD_TILE_VER_GFX10:
477 str_tile_version = "GFX10";
479 case AMD_FMT_MOD_TILE_VER_GFX10_RBPLUS:
480 str_tile_version = "GFX10_RBPLUS";
482 case AMD_FMT_MOD_TILE_VER_GFX11:
483 str_tile_version = "GFX11";
487 if (str_tile_version) {
488 fprintf(fp, "%s", str_tile_version);
497 case AMD_FMT_MOD_TILE_GFX9_64K_S:
498 str_tile = "GFX9_64K_S";
500 case AMD_FMT_MOD_TILE_GFX9_64K_D:
501 str_tile = "GFX9_64K_D";
503 case AMD_FMT_MOD_TILE_GFX9_64K_S_X:
504 str_tile = "GFX9_64K_S_X";
506 case AMD_FMT_MOD_TILE_GFX9_64K_D_X:
507 str_tile = "GFX9_64K_D_X";
509 case AMD_FMT_MOD_TILE_GFX9_64K_R_X:
510 str_tile = "GFX9_64K_R_X";
512 case AMD_FMT_MOD_TILE_GFX11_256K_R_X:
513 str_tile = "GFX11_256K_R_X";
518 fprintf(fp, ",%s", str_tile);
521 drmGetFormatModifierNameFromAmdDcc(modifier, fp);
523 if (tile_version >= AMD_FMT_MOD_TILE_VER_GFX9 && is_x_t_amd_gfx9_tile(tile))
524 drmGetFormatModifierNameFromAmdTile(modifier, fp);
531 drmGetFormatModifierNameFromAmlogic(uint64_t modifier)
533 uint64_t layout = modifier & 0xff;
534 uint64_t options = (modifier >> 8) & 0xff;
535 char *mod_amlogic = NULL;
537 const char *layout_str;
538 const char *opts_str;
541 case AMLOGIC_FBC_LAYOUT_BASIC:
542 layout_str = "BASIC";
544 case AMLOGIC_FBC_LAYOUT_SCATTER:
545 layout_str = "SCATTER";
548 layout_str = "INVALID_LAYOUT";
552 if (options & AMLOGIC_FBC_OPTION_MEM_SAVING)
553 opts_str = "MEM_SAVING";
557 if (asprintf(&mod_amlogic, "FBC,LAYOUT=%s,OPTIONS=%s", layout_str, opts_str)
564 drmGetFormatModifierNameFromVivante(uint64_t modifier)
566 const char *color_tiling, *tile_status, *compression;
567 char *mod_vivante = NULL;
569 switch (modifier & VIVANTE_MOD_TS_MASK) {
573 case VIVANTE_MOD_TS_64_4:
574 tile_status = ",TS=64B_4";
576 case VIVANTE_MOD_TS_64_2:
577 tile_status = ",TS=64B_2";
579 case VIVANTE_MOD_TS_128_4:
580 tile_status = ",TS=128B_4";
582 case VIVANTE_MOD_TS_256_4:
583 tile_status = ",TS=256B_4";
586 tile_status = ",TS=UNKNOWN";
590 switch (modifier & VIVANTE_MOD_COMP_MASK) {
594 case VIVANTE_MOD_COMP_DEC400:
595 compression = ",COMP=DEC400";
598 compression = ",COMP=UNKNOWN";
602 switch (modifier & ~VIVANTE_MOD_EXT_MASK) {
604 color_tiling = "LINEAR";
606 case DRM_FORMAT_MOD_VIVANTE_TILED:
607 color_tiling = "TILED";
609 case DRM_FORMAT_MOD_VIVANTE_SUPER_TILED:
610 color_tiling = "SUPER_TILED";
612 case DRM_FORMAT_MOD_VIVANTE_SPLIT_TILED:
613 color_tiling = "SPLIT_TILED";
615 case DRM_FORMAT_MOD_VIVANTE_SPLIT_SUPER_TILED:
616 color_tiling = "SPLIT_SUPER_TILED";
619 color_tiling = "UNKNOWN";
623 if (asprintf(&mod_vivante, "%s%s%s", color_tiling, tile_status, compression)
629 static unsigned log2_int(unsigned x)
637 if ((unsigned)(1 << l) > x) {
645 drm_public void drmSetServerInfo(drmServerInfoPtr info)
647 drm_server_info = info;
651 * Output a message to stderr.
653 * \param format printf() like format string.
656 * This function is a wrapper around vfprintf().
659 static int DRM_PRINTFLIKE(1, 0)
660 drmDebugPrint(const char *format, va_list ap)
662 return vfprintf(stderr, format, ap);
666 drmMsg(const char *format, ...)
670 if (((env = getenv("LIBGL_DEBUG")) && strstr(env, "verbose")) ||
671 (drm_server_info && drm_server_info->debug_print))
673 va_start(ap, format);
674 if (drm_server_info) {
675 drm_server_info->debug_print(format,ap);
677 drmDebugPrint(format, ap);
683 static void *drmHashTable = NULL; /* Context switch callbacks */
685 drm_public void *drmGetHashTable(void)
690 drm_public void *drmMalloc(int size)
692 return calloc(1, size);
695 drm_public void drmFree(void *pt)
701 * Call ioctl, restarting if it is interrupted
704 drmIoctl(int fd, unsigned long request, void *arg)
709 ret = ioctl(fd, request, arg);
710 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
714 static unsigned long drmGetKeyFromFd(int fd)
723 drm_public drmHashEntry *drmGetEntry(int fd)
725 unsigned long key = drmGetKeyFromFd(fd);
730 drmHashTable = drmHashCreate();
732 if (drmHashLookup(drmHashTable, key, &value)) {
733 entry = drmMalloc(sizeof(*entry));
736 entry->tagTable = drmHashCreate();
737 drmHashInsert(drmHashTable, key, entry);
745 * Compare two busid strings
750 * \return 1 if matched.
753 * This function compares two bus ID strings. It understands the older
754 * PCI:b:d:f format and the newer pci:oooo:bb:dd.f format. In the format, o is
755 * domain, b is bus, d is device, f is function.
757 static int drmMatchBusID(const char *id1, const char *id2, int pci_domain_ok)
759 /* First, check if the IDs are exactly the same */
760 if (strcasecmp(id1, id2) == 0)
763 /* Try to match old/new-style PCI bus IDs. */
764 if (strncasecmp(id1, "pci", 3) == 0) {
765 unsigned int o1, b1, d1, f1;
766 unsigned int o2, b2, d2, f2;
769 ret = sscanf(id1, "pci:%04x:%02x:%02x.%u", &o1, &b1, &d1, &f1);
772 ret = sscanf(id1, "PCI:%u:%u:%u", &b1, &d1, &f1);
777 ret = sscanf(id2, "pci:%04x:%02x:%02x.%u", &o2, &b2, &d2, &f2);
780 ret = sscanf(id2, "PCI:%u:%u:%u", &b2, &d2, &f2);
785 /* If domains aren't properly supported by the kernel interface,
786 * just ignore them, which sucks less than picking a totally random
787 * card with "open by name"
792 if ((o1 != o2) || (b1 != b2) || (d1 != d2) || (f1 != f2))
801 * Handles error checking for chown call.
803 * \param path to file.
804 * \param id of the new owner.
805 * \param id of the new group.
807 * \return zero if success or -1 if failure.
810 * Checks for failure. If failure was caused by signal call chown again.
811 * If any other failure happened then it will output error message using
815 static int chown_check_return(const char *path, uid_t owner, gid_t group)
820 rv = chown(path, owner, group);
821 } while (rv != 0 && errno == EINTR);
826 drmMsg("Failed to change owner or group for file %s! %d: %s\n",
827 path, errno, strerror(errno));
832 static const char *drmGetDeviceName(int type)
835 case DRM_NODE_PRIMARY:
837 case DRM_NODE_RENDER:
838 return DRM_RENDER_DEV_NAME;
844 * Open the DRM device, creating it if necessary.
846 * \param dev major and minor numbers of the device.
847 * \param minor minor number of the device.
849 * \return a file descriptor on success, or a negative value on error.
852 * Assembles the device name from \p minor and opens it, creating the device
853 * special file node with the major and minor numbers specified by \p dev and
854 * parent directory if necessary and was called by root.
856 static int drmOpenDevice(dev_t dev, int minor, int type)
859 const char *dev_name = drmGetDeviceName(type);
860 char buf[DRM_NODE_NAME_MAX];
862 mode_t devmode = DRM_DEV_MODE, serv_mode;
865 int isroot = !geteuid();
866 uid_t user = DRM_DEV_UID;
867 gid_t group = DRM_DEV_GID;
873 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
874 drmMsg("drmOpenDevice: node name is %s\n", buf);
876 if (drm_server_info && drm_server_info->get_perms) {
877 drm_server_info->get_perms(&serv_group, &serv_mode);
878 devmode = serv_mode ? serv_mode : DRM_DEV_MODE;
879 devmode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
883 if (stat(DRM_DIR_NAME, &st)) {
885 return DRM_ERR_NOT_ROOT;
886 mkdir(DRM_DIR_NAME, DRM_DEV_DIRMODE);
887 chown_check_return(DRM_DIR_NAME, 0, 0); /* root:root */
888 chmod(DRM_DIR_NAME, DRM_DEV_DIRMODE);
891 /* Check if the device node exists and create it if necessary. */
892 if (stat(buf, &st)) {
894 return DRM_ERR_NOT_ROOT;
896 mknod(buf, S_IFCHR | devmode, dev);
899 if (drm_server_info && drm_server_info->get_perms) {
900 group = ((int)serv_group >= 0) ? serv_group : DRM_DEV_GID;
901 chown_check_return(buf, user, group);
905 /* if we modprobed then wait for udev */
909 if (stat(DRM_DIR_NAME, &st)) {
913 if (udev_count == 50)
918 if (stat(buf, &st)) {
922 if (udev_count == 50)
929 fd = open(buf, O_RDWR | O_CLOEXEC);
930 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
931 fd, fd < 0 ? strerror(errno) : "OK");
936 /* Check if the device node is not what we expect it to be, and recreate it
937 * and try again if so.
939 if (st.st_rdev != dev) {
941 return DRM_ERR_NOT_ROOT;
943 mknod(buf, S_IFCHR | devmode, dev);
944 if (drm_server_info && drm_server_info->get_perms) {
945 chown_check_return(buf, user, group);
949 fd = open(buf, O_RDWR | O_CLOEXEC);
950 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
951 fd, fd < 0 ? strerror(errno) : "OK");
955 drmMsg("drmOpenDevice: Open failed\n");
963 * Open the DRM device
965 * \param minor device minor number.
966 * \param create allow to create the device if set.
968 * \return a file descriptor on success, or a negative value on error.
971 * Calls drmOpenDevice() if \p create is set, otherwise assembles the device
972 * name from \p minor and opens it.
974 static int drmOpenMinor(int minor, int create, int type)
977 char buf[DRM_NODE_NAME_MAX];
978 const char *dev_name = drmGetDeviceName(type);
981 return drmOpenDevice(makedev(DRM_MAJOR, minor), minor, type);
986 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
987 if ((fd = open(buf, O_RDWR | O_CLOEXEC)) >= 0)
994 * Determine whether the DRM kernel driver has been loaded.
996 * \return 1 if the DRM driver is loaded, 0 otherwise.
999 * Determine the presence of the kernel driver by attempting to open the 0
1000 * minor and get version information. For backward compatibility with older
1001 * Linux implementations, /proc/dri is also checked.
1003 drm_public int drmAvailable(void)
1005 drmVersionPtr version;
1009 if ((fd = drmOpenMinor(0, 1, DRM_NODE_PRIMARY)) < 0) {
1011 /* Try proc for backward Linux compatibility */
1012 if (!access("/proc/dri/0", R_OK))
1018 if ((version = drmGetVersion(fd))) {
1020 drmFreeVersion(version);
1027 static int drmGetMinorBase(int type)
1030 case DRM_NODE_PRIMARY:
1032 case DRM_NODE_RENDER:
1039 static int drmGetMinorType(int major, int minor)
1042 char name[SPECNAMELEN];
1045 if (!devname_r(makedev(major, minor), S_IFCHR, name, sizeof(name)))
1048 if (sscanf(name, "drm/%d", &id) != 1) {
1049 // If not in /dev/drm/ we have the type in the name
1050 if (sscanf(name, "dri/card%d\n", &id) >= 1)
1051 return DRM_NODE_PRIMARY;
1052 else if (sscanf(name, "dri/renderD%d\n", &id) >= 1)
1053 return DRM_NODE_RENDER;
1059 char path[DRM_NODE_NAME_MAX];
1060 const char *dev_name;
1063 for (i = DRM_NODE_PRIMARY; i < DRM_NODE_MAX; i++) {
1064 dev_name = drmGetDeviceName(i);
1067 snprintf(path, sizeof(path), dev_name, DRM_DIR_NAME, minor);
1068 if (!access(path, F_OK))
1075 static const char *drmGetMinorName(int type)
1078 case DRM_NODE_PRIMARY:
1079 return DRM_PRIMARY_MINOR_NAME;
1080 case DRM_NODE_RENDER:
1081 return DRM_RENDER_MINOR_NAME;
1088 * Open the device by bus ID.
1090 * \param busid bus ID.
1091 * \param type device node type.
1093 * \return a file descriptor on success, or a negative value on error.
1096 * This function attempts to open every possible minor (up to DRM_MAX_MINOR),
1097 * comparing the device bus ID with the one supplied.
1099 * \sa drmOpenMinor() and drmGetBusid().
1101 static int drmOpenByBusid(const char *busid, int type)
1103 int i, pci_domain_ok = 1;
1107 int base = drmGetMinorBase(type);
1112 drmMsg("drmOpenByBusid: Searching for BusID %s\n", busid);
1113 for (i = base; i < base + DRM_MAX_MINOR; i++) {
1114 fd = drmOpenMinor(i, 1, type);
1115 drmMsg("drmOpenByBusid: drmOpenMinor returns %d\n", fd);
1117 /* We need to try for 1.4 first for proper PCI domain support
1118 * and if that fails, we know the kernel is busted
1120 sv.drm_di_major = 1;
1121 sv.drm_di_minor = 4;
1122 sv.drm_dd_major = -1; /* Don't care */
1123 sv.drm_dd_minor = -1; /* Don't care */
1124 if (drmSetInterfaceVersion(fd, &sv)) {
1128 sv.drm_di_major = 1;
1129 sv.drm_di_minor = 1;
1130 sv.drm_dd_major = -1; /* Don't care */
1131 sv.drm_dd_minor = -1; /* Don't care */
1132 drmMsg("drmOpenByBusid: Interface 1.4 failed, trying 1.1\n");
1133 drmSetInterfaceVersion(fd, &sv);
1135 buf = drmGetBusid(fd);
1136 drmMsg("drmOpenByBusid: drmGetBusid reports %s\n", buf);
1137 if (buf && drmMatchBusID(buf, busid, pci_domain_ok)) {
1151 * Open the device by name.
1153 * \param name driver name.
1154 * \param type the device node type.
1156 * \return a file descriptor on success, or a negative value on error.
1159 * This function opens the first minor number that matches the driver name and
1160 * isn't already in use. If it's in use it then it will already have a bus ID
1163 * \sa drmOpenMinor(), drmGetVersion() and drmGetBusid().
1165 static int drmOpenByName(const char *name, int type)
1169 drmVersionPtr version;
1171 int base = drmGetMinorBase(type);
1177 * Open the first minor number that matches the driver name and isn't
1178 * already in use. If it's in use it will have a busid assigned already.
1180 for (i = base; i < base + DRM_MAX_MINOR; i++) {
1181 if ((fd = drmOpenMinor(i, 1, type)) >= 0) {
1182 if ((version = drmGetVersion(fd))) {
1183 if (!strcmp(version->name, name)) {
1184 drmFreeVersion(version);
1185 id = drmGetBusid(fd);
1186 drmMsg("drmGetBusid returned '%s'\n", id ? id : "NULL");
1195 drmFreeVersion(version);
1203 /* Backward-compatibility /proc support */
1204 for (i = 0; i < 8; i++) {
1205 char proc_name[64], buf[512];
1206 char *driver, *pt, *devstring;
1209 sprintf(proc_name, "/proc/dri/%d/name", i);
1210 if ((fd = open(proc_name, O_RDONLY)) >= 0) {
1211 retcode = read(fd, buf, sizeof(buf)-1);
1214 buf[retcode-1] = '\0';
1215 for (driver = pt = buf; *pt && *pt != ' '; ++pt)
1217 if (*pt) { /* Device is next */
1219 if (!strcmp(driver, name)) { /* Match */
1220 for (devstring = ++pt; *pt && *pt != ' '; ++pt)
1222 if (*pt) { /* Found busid */
1223 return drmOpenByBusid(++pt, type);
1224 } else { /* No busid */
1225 return drmOpenDevice(strtol(devstring, NULL, 0),i, type);
1239 * Open the DRM device.
1241 * Looks up the specified name and bus ID, and opens the device found. The
1242 * entry in /dev/dri is created if necessary and if called by root.
1244 * \param name driver name. Not referenced if bus ID is supplied.
1245 * \param busid bus ID. Zero if not known.
1247 * \return a file descriptor on success, or a negative value on error.
1250 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
1253 drm_public int drmOpen(const char *name, const char *busid)
1255 return drmOpenWithType(name, busid, DRM_NODE_PRIMARY);
1259 * Open the DRM device with specified type.
1261 * Looks up the specified name and bus ID, and opens the device found. The
1262 * entry in /dev/dri is created if necessary and if called by root.
1264 * \param name driver name. Not referenced if bus ID is supplied.
1265 * \param busid bus ID. Zero if not known.
1266 * \param type the device node type to open, PRIMARY or RENDER
1268 * \return a file descriptor on success, or a negative value on error.
1271 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
1274 drm_public int drmOpenWithType(const char *name, const char *busid, int type)
1276 if (name != NULL && drm_server_info &&
1277 drm_server_info->load_module && !drmAvailable()) {
1278 /* try to load the kernel module */
1279 if (!drm_server_info->load_module(name)) {
1280 drmMsg("[drm] failed to load kernel module \"%s\"\n", name);
1286 int fd = drmOpenByBusid(busid, type);
1292 return drmOpenByName(name, type);
1297 drm_public int drmOpenControl(int minor)
1302 drm_public int drmOpenRender(int minor)
1304 return drmOpenMinor(minor, 0, DRM_NODE_RENDER);
1308 * Free the version information returned by drmGetVersion().
1310 * \param v pointer to the version information.
1313 * It frees the memory pointed by \p %v as well as all the non-null strings
1316 drm_public void drmFreeVersion(drmVersionPtr v)
1328 * Free the non-public version information returned by the kernel.
1330 * \param v pointer to the version information.
1333 * Used by drmGetVersion() to free the memory pointed by \p %v as well as all
1334 * the non-null strings pointers in it.
1336 static void drmFreeKernelVersion(drm_version_t *v)
1348 * Copy version information.
1350 * \param d destination pointer.
1351 * \param s source pointer.
1354 * Used by drmGetVersion() to translate the information returned by the ioctl
1355 * interface in a private structure into the public structure counterpart.
1357 static void drmCopyVersion(drmVersionPtr d, const drm_version_t *s)
1359 d->version_major = s->version_major;
1360 d->version_minor = s->version_minor;
1361 d->version_patchlevel = s->version_patchlevel;
1362 d->name_len = s->name_len;
1363 d->name = strdup(s->name);
1364 d->date_len = s->date_len;
1365 d->date = strdup(s->date);
1366 d->desc_len = s->desc_len;
1367 d->desc = strdup(s->desc);
1372 * Query the driver version information.
1374 * \param fd file descriptor.
1376 * \return pointer to a drmVersion structure which should be freed with
1379 * \note Similar information is available via /proc/dri.
1382 * It gets the version information via successive DRM_IOCTL_VERSION ioctls,
1383 * first with zeros to get the string lengths, and then the actually strings.
1384 * It also null-terminates them since they might not be already.
1386 drm_public drmVersionPtr drmGetVersion(int fd)
1388 drmVersionPtr retval;
1389 drm_version_t *version = drmMalloc(sizeof(*version));
1391 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
1392 drmFreeKernelVersion(version);
1396 if (version->name_len)
1397 version->name = drmMalloc(version->name_len + 1);
1398 if (version->date_len)
1399 version->date = drmMalloc(version->date_len + 1);
1400 if (version->desc_len)
1401 version->desc = drmMalloc(version->desc_len + 1);
1403 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
1404 drmMsg("DRM_IOCTL_VERSION: %s\n", strerror(errno));
1405 drmFreeKernelVersion(version);
1409 /* The results might not be null-terminated strings, so terminate them. */
1410 if (version->name_len) version->name[version->name_len] = '\0';
1411 if (version->date_len) version->date[version->date_len] = '\0';
1412 if (version->desc_len) version->desc[version->desc_len] = '\0';
1414 retval = drmMalloc(sizeof(*retval));
1415 drmCopyVersion(retval, version);
1416 drmFreeKernelVersion(version);
1422 * Get version information for the DRM user space library.
1424 * This version number is driver independent.
1426 * \param fd file descriptor.
1428 * \return version information.
1431 * This function allocates and fills a drm_version structure with a hard coded
1434 drm_public drmVersionPtr drmGetLibVersion(int fd)
1436 drm_version_t *version = drmMalloc(sizeof(*version));
1439 * NOTE THIS MUST NOT GO ABOVE VERSION 1.X due to drivers needing it
1440 * revision 1.0.x = original DRM interface with no drmGetLibVersion
1441 * entry point and many drm<Device> extensions
1442 * revision 1.1.x = added drmCommand entry points for device extensions
1443 * added drmGetLibVersion to identify libdrm.a version
1444 * revision 1.2.x = added drmSetInterfaceVersion
1445 * modified drmOpen to handle both busid and name
1446 * revision 1.3.x = added server + memory manager
1448 version->version_major = 1;
1449 version->version_minor = 3;
1450 version->version_patchlevel = 0;
1452 return (drmVersionPtr)version;
1455 drm_public int drmGetCap(int fd, uint64_t capability, uint64_t *value)
1457 struct drm_get_cap cap;
1461 cap.capability = capability;
1463 ret = drmIoctl(fd, DRM_IOCTL_GET_CAP, &cap);
1471 drm_public int drmSetClientCap(int fd, uint64_t capability, uint64_t value)
1473 struct drm_set_client_cap cap;
1476 cap.capability = capability;
1479 return drmIoctl(fd, DRM_IOCTL_SET_CLIENT_CAP, &cap);
1483 * Free the bus ID information.
1485 * \param busid bus ID information string as given by drmGetBusid().
1488 * This function is just frees the memory pointed by \p busid.
1490 drm_public void drmFreeBusid(const char *busid)
1492 drmFree((void *)busid);
1497 * Get the bus ID of the device.
1499 * \param fd file descriptor.
1501 * \return bus ID string.
1504 * This function gets the bus ID via successive DRM_IOCTL_GET_UNIQUE ioctls to
1505 * get the string length and data, passing the arguments in a drm_unique
1508 drm_public char *drmGetBusid(int fd)
1514 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
1516 u.unique = drmMalloc(u.unique_len + 1);
1517 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u)) {
1521 u.unique[u.unique_len] = '\0';
1528 * Set the bus ID of the device.
1530 * \param fd file descriptor.
1531 * \param busid bus ID string.
1533 * \return zero on success, negative on failure.
1536 * This function is a wrapper around the DRM_IOCTL_SET_UNIQUE ioctl, passing
1537 * the arguments in a drm_unique structure.
1539 drm_public int drmSetBusid(int fd, const char *busid)
1544 u.unique = (char *)busid;
1545 u.unique_len = strlen(busid);
1547 if (drmIoctl(fd, DRM_IOCTL_SET_UNIQUE, &u)) {
1553 drm_public int drmGetMagic(int fd, drm_magic_t * magic)
1560 if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
1562 *magic = auth.magic;
1566 drm_public int drmAuthMagic(int fd, drm_magic_t magic)
1572 if (drmIoctl(fd, DRM_IOCTL_AUTH_MAGIC, &auth))
1578 * Specifies a range of memory that is available for mapping by a
1581 * \param fd file descriptor.
1582 * \param offset usually the physical address. The actual meaning depends of
1583 * the \p type parameter. See below.
1584 * \param size of the memory in bytes.
1585 * \param type type of the memory to be mapped.
1586 * \param flags combination of several flags to modify the function actions.
1587 * \param handle will be set to a value that may be used as the offset
1588 * parameter for mmap().
1590 * \return zero on success or a negative value on error.
1592 * \par Mapping the frame buffer
1593 * For the frame buffer
1594 * - \p offset will be the physical address of the start of the frame buffer,
1595 * - \p size will be the size of the frame buffer in bytes, and
1596 * - \p type will be DRM_FRAME_BUFFER.
1599 * The area mapped will be uncached. If MTRR support is available in the
1600 * kernel, the frame buffer area will be set to write combining.
1602 * \par Mapping the MMIO register area
1603 * For the MMIO register area,
1604 * - \p offset will be the physical address of the start of the register area,
1605 * - \p size will be the size of the register area bytes, and
1606 * - \p type will be DRM_REGISTERS.
1608 * The area mapped will be uncached.
1610 * \par Mapping the SAREA
1612 * - \p offset will be ignored and should be set to zero,
1613 * - \p size will be the desired size of the SAREA in bytes,
1614 * - \p type will be DRM_SHM.
1617 * A shared memory area of the requested size will be created and locked in
1618 * kernel memory. This area may be mapped into client-space by using the handle
1621 * \note May only be called by root.
1624 * This function is a wrapper around the DRM_IOCTL_ADD_MAP ioctl, passing
1625 * the arguments in a drm_map structure.
1627 drm_public int drmAddMap(int fd, drm_handle_t offset, drmSize size, drmMapType type,
1628 drmMapFlags flags, drm_handle_t *handle)
1633 map.offset = offset;
1635 map.type = (enum drm_map_type)type;
1636 map.flags = (enum drm_map_flags)flags;
1637 if (drmIoctl(fd, DRM_IOCTL_ADD_MAP, &map))
1640 *handle = (drm_handle_t)(uintptr_t)map.handle;
1644 drm_public int drmRmMap(int fd, drm_handle_t handle)
1649 map.handle = (void *)(uintptr_t)handle;
1651 if(drmIoctl(fd, DRM_IOCTL_RM_MAP, &map))
1657 * Make buffers available for DMA transfers.
1659 * \param fd file descriptor.
1660 * \param count number of buffers.
1661 * \param size size of each buffer.
1662 * \param flags buffer allocation flags.
1663 * \param agp_offset offset in the AGP aperture
1665 * \return number of buffers allocated, negative on error.
1668 * This function is a wrapper around DRM_IOCTL_ADD_BUFS ioctl.
1672 drm_public int drmAddBufs(int fd, int count, int size, drmBufDescFlags flags,
1675 drm_buf_desc_t request;
1678 request.count = count;
1679 request.size = size;
1680 request.flags = (int)flags;
1681 request.agp_start = agp_offset;
1683 if (drmIoctl(fd, DRM_IOCTL_ADD_BUFS, &request))
1685 return request.count;
1688 drm_public int drmMarkBufs(int fd, double low, double high)
1690 drm_buf_info_t info;
1695 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1701 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1704 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1705 int retval = -errno;
1710 for (i = 0; i < info.count; i++) {
1711 info.list[i].low_mark = low * info.list[i].count;
1712 info.list[i].high_mark = high * info.list[i].count;
1713 if (drmIoctl(fd, DRM_IOCTL_MARK_BUFS, &info.list[i])) {
1714 int retval = -errno;
1727 * \param fd file descriptor.
1728 * \param count number of buffers to free.
1729 * \param list list of buffers to be freed.
1731 * \return zero on success, or a negative value on failure.
1733 * \note This function is primarily used for debugging.
1736 * This function is a wrapper around the DRM_IOCTL_FREE_BUFS ioctl, passing
1737 * the arguments in a drm_buf_free structure.
1739 drm_public int drmFreeBufs(int fd, int count, int *list)
1741 drm_buf_free_t request;
1744 request.count = count;
1745 request.list = list;
1746 if (drmIoctl(fd, DRM_IOCTL_FREE_BUFS, &request))
1755 * \param fd file descriptor.
1758 * This function closes the file descriptor.
1760 drm_public int drmClose(int fd)
1762 unsigned long key = drmGetKeyFromFd(fd);
1763 drmHashEntry *entry = drmGetEntry(fd);
1765 drmHashDestroy(entry->tagTable);
1768 entry->tagTable = NULL;
1770 drmHashDelete(drmHashTable, key);
1778 * Map a region of memory.
1780 * \param fd file descriptor.
1781 * \param handle handle returned by drmAddMap().
1782 * \param size size in bytes. Must match the size used by drmAddMap().
1783 * \param address will contain the user-space virtual address where the mapping
1786 * \return zero on success, or a negative value on failure.
1789 * This function is a wrapper for mmap().
1791 drm_public int drmMap(int fd, drm_handle_t handle, drmSize size,
1792 drmAddressPtr address)
1794 static unsigned long pagesize_mask = 0;
1800 pagesize_mask = getpagesize() - 1;
1802 size = (size + pagesize_mask) & ~pagesize_mask;
1804 *address = drm_mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1805 if (*address == MAP_FAILED)
1812 * Unmap mappings obtained with drmMap().
1814 * \param address address as given by drmMap().
1815 * \param size size in bytes. Must match the size used by drmMap().
1817 * \return zero on success, or a negative value on failure.
1820 * This function is a wrapper for munmap().
1822 drm_public int drmUnmap(drmAddress address, drmSize size)
1824 return drm_munmap(address, size);
1827 drm_public drmBufInfoPtr drmGetBufInfo(int fd)
1829 drm_buf_info_t info;
1830 drmBufInfoPtr retval;
1835 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1839 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1842 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1847 retval = drmMalloc(sizeof(*retval));
1848 retval->count = info.count;
1849 if (!(retval->list = drmMalloc(info.count * sizeof(*retval->list)))) {
1855 for (i = 0; i < info.count; i++) {
1856 retval->list[i].count = info.list[i].count;
1857 retval->list[i].size = info.list[i].size;
1858 retval->list[i].low_mark = info.list[i].low_mark;
1859 retval->list[i].high_mark = info.list[i].high_mark;
1868 * Map all DMA buffers into client-virtual space.
1870 * \param fd file descriptor.
1872 * \return a pointer to a ::drmBufMap structure.
1874 * \note The client may not use these buffers until obtaining buffer indices
1878 * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1879 * information about the buffers in a drm_buf_map structure into the
1880 * client-visible data structures.
1882 drm_public drmBufMapPtr drmMapBufs(int fd)
1885 drmBufMapPtr retval;
1889 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1895 if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1898 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1903 retval = drmMalloc(sizeof(*retval));
1904 retval->count = bufs.count;
1905 retval->list = drmMalloc(bufs.count * sizeof(*retval->list));
1906 for (i = 0; i < bufs.count; i++) {
1907 retval->list[i].idx = bufs.list[i].idx;
1908 retval->list[i].total = bufs.list[i].total;
1909 retval->list[i].used = 0;
1910 retval->list[i].address = bufs.list[i].address;
1919 * Unmap buffers allocated with drmMapBufs().
1921 * \return zero on success, or negative value on failure.
1924 * Calls munmap() for every buffer stored in \p bufs and frees the
1925 * memory allocated by drmMapBufs().
1927 drm_public int drmUnmapBufs(drmBufMapPtr bufs)
1931 for (i = 0; i < bufs->count; i++) {
1932 drm_munmap(bufs->list[i].address, bufs->list[i].total);
1935 drmFree(bufs->list);
1941 #define DRM_DMA_RETRY 16
1944 * Reserve DMA buffers.
1946 * \param fd file descriptor.
1949 * \return zero on success, or a negative value on failure.
1952 * Assemble the arguments into a drm_dma structure and keeps issuing the
1953 * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1955 drm_public int drmDMA(int fd, drmDMAReqPtr request)
1960 dma.context = request->context;
1961 dma.send_count = request->send_count;
1962 dma.send_indices = request->send_list;
1963 dma.send_sizes = request->send_sizes;
1964 dma.flags = (enum drm_dma_flags)request->flags;
1965 dma.request_count = request->request_count;
1966 dma.request_size = request->request_size;
1967 dma.request_indices = request->request_list;
1968 dma.request_sizes = request->request_sizes;
1969 dma.granted_count = 0;
1972 ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1973 } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1976 request->granted_count = dma.granted_count;
1985 * Obtain heavyweight hardware lock.
1987 * \param fd file descriptor.
1988 * \param context context.
1989 * \param flags flags that determine the state of the hardware when the function
1992 * \return always zero.
1995 * This function translates the arguments into a drm_lock structure and issue
1996 * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1998 drm_public int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
2003 lock.context = context;
2005 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
2006 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
2007 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
2008 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
2009 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2010 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2012 while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
2018 * Release the hardware lock.
2020 * \param fd file descriptor.
2021 * \param context context.
2023 * \return zero on success, or a negative value on failure.
2026 * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
2027 * argument in a drm_lock structure.
2029 drm_public int drmUnlock(int fd, drm_context_t context)
2034 lock.context = context;
2035 return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
2038 drm_public drm_context_t *drmGetReservedContextList(int fd, int *count)
2042 drm_context_t * retval;
2046 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
2052 if (!(list = drmMalloc(res.count * sizeof(*list))))
2054 if (!(retval = drmMalloc(res.count * sizeof(*retval))))
2057 res.contexts = list;
2058 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
2059 goto err_free_context;
2061 for (i = 0; i < res.count; i++)
2062 retval[i] = list[i].handle;
2075 drm_public void drmFreeReservedContextList(drm_context_t *pt)
2083 * Used by the X server during GLXContext initialization. This causes
2084 * per-context kernel-level resources to be allocated.
2086 * \param fd file descriptor.
2087 * \param handle is set on success. To be used by the client when requesting DMA
2088 * dispatch with drmDMA().
2090 * \return zero on success, or a negative value on failure.
2092 * \note May only be called by root.
2095 * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
2096 * argument in a drm_ctx structure.
2098 drm_public int drmCreateContext(int fd, drm_context_t *handle)
2103 if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
2105 *handle = ctx.handle;
2109 drm_public int drmSwitchToContext(int fd, drm_context_t context)
2114 ctx.handle = context;
2115 if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
2120 drm_public int drmSetContextFlags(int fd, drm_context_t context,
2121 drm_context_tFlags flags)
2126 * Context preserving means that no context switches are done between DMA
2127 * buffers from one context and the next. This is suitable for use in the
2128 * X server (which promises to maintain hardware context), or in the
2129 * client-side library when buffers are swapped on behalf of two threads.
2132 ctx.handle = context;
2133 if (flags & DRM_CONTEXT_PRESERVED)
2134 ctx.flags |= _DRM_CONTEXT_PRESERVED;
2135 if (flags & DRM_CONTEXT_2DONLY)
2136 ctx.flags |= _DRM_CONTEXT_2DONLY;
2137 if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
2142 drm_public int drmGetContextFlags(int fd, drm_context_t context,
2143 drm_context_tFlagsPtr flags)
2148 ctx.handle = context;
2149 if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
2152 if (ctx.flags & _DRM_CONTEXT_PRESERVED)
2153 *flags |= DRM_CONTEXT_PRESERVED;
2154 if (ctx.flags & _DRM_CONTEXT_2DONLY)
2155 *flags |= DRM_CONTEXT_2DONLY;
2162 * Free any kernel-level resources allocated with drmCreateContext() associated
2165 * \param fd file descriptor.
2166 * \param handle handle given by drmCreateContext().
2168 * \return zero on success, or a negative value on failure.
2170 * \note May only be called by root.
2173 * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
2174 * argument in a drm_ctx structure.
2176 drm_public int drmDestroyContext(int fd, drm_context_t handle)
2181 ctx.handle = handle;
2182 if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
2187 drm_public int drmCreateDrawable(int fd, drm_drawable_t *handle)
2192 if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
2194 *handle = draw.handle;
2198 drm_public int drmDestroyDrawable(int fd, drm_drawable_t handle)
2203 draw.handle = handle;
2204 if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
2209 drm_public int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
2210 drm_drawable_info_type_t type,
2211 unsigned int num, void *data)
2213 drm_update_draw_t update;
2216 update.handle = handle;
2219 update.data = (unsigned long long)(unsigned long)data;
2221 if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
2227 drm_public int drmCrtcGetSequence(int fd, uint32_t crtcId, uint64_t *sequence,
2230 struct drm_crtc_get_sequence get_seq;
2234 get_seq.crtc_id = crtcId;
2235 ret = drmIoctl(fd, DRM_IOCTL_CRTC_GET_SEQUENCE, &get_seq);
2240 *sequence = get_seq.sequence;
2242 *ns = get_seq.sequence_ns;
2246 drm_public int drmCrtcQueueSequence(int fd, uint32_t crtcId, uint32_t flags,
2248 uint64_t *sequence_queued,
2251 struct drm_crtc_queue_sequence queue_seq;
2254 memclear(queue_seq);
2255 queue_seq.crtc_id = crtcId;
2256 queue_seq.flags = flags;
2257 queue_seq.sequence = sequence;
2258 queue_seq.user_data = user_data;
2260 ret = drmIoctl(fd, DRM_IOCTL_CRTC_QUEUE_SEQUENCE, &queue_seq);
2261 if (ret == 0 && sequence_queued)
2262 *sequence_queued = queue_seq.sequence;
2268 * Acquire the AGP device.
2270 * Must be called before any of the other AGP related calls.
2272 * \param fd file descriptor.
2274 * \return zero on success, or a negative value on failure.
2277 * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
2279 drm_public int drmAgpAcquire(int fd)
2281 if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
2288 * Release the AGP device.
2290 * \param fd file descriptor.
2292 * \return zero on success, or a negative value on failure.
2295 * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
2297 drm_public int drmAgpRelease(int fd)
2299 if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
2308 * \param fd file descriptor.
2309 * \param mode AGP mode.
2311 * \return zero on success, or a negative value on failure.
2314 * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
2315 * argument in a drm_agp_mode structure.
2317 drm_public int drmAgpEnable(int fd, unsigned long mode)
2323 if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
2330 * Allocate a chunk of AGP memory.
2332 * \param fd file descriptor.
2333 * \param size requested memory size in bytes. Will be rounded to page boundary.
2334 * \param type type of memory to allocate.
2335 * \param address if not zero, will be set to the physical address of the
2337 * \param handle on success will be set to a handle of the allocated memory.
2339 * \return zero on success, or a negative value on failure.
2342 * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
2343 * arguments in a drm_agp_buffer structure.
2345 drm_public int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
2346 unsigned long *address, drm_handle_t *handle)
2351 *handle = DRM_AGP_NO_HANDLE;
2354 if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
2357 *address = b.physical;
2364 * Free a chunk of AGP memory.
2366 * \param fd file descriptor.
2367 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
2369 * \return zero on success, or a negative value on failure.
2372 * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
2373 * argument in a drm_agp_buffer structure.
2375 drm_public int drmAgpFree(int fd, drm_handle_t handle)
2381 if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
2388 * Bind a chunk of AGP memory.
2390 * \param fd file descriptor.
2391 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
2392 * \param offset offset in bytes. It will round to page boundary.
2394 * \return zero on success, or a negative value on failure.
2397 * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
2398 * argument in a drm_agp_binding structure.
2400 drm_public int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
2402 drm_agp_binding_t b;
2407 if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
2414 * Unbind a chunk of AGP memory.
2416 * \param fd file descriptor.
2417 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
2419 * \return zero on success, or a negative value on failure.
2422 * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
2423 * the argument in a drm_agp_binding structure.
2425 drm_public int drmAgpUnbind(int fd, drm_handle_t handle)
2427 drm_agp_binding_t b;
2431 if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
2438 * Get AGP driver major version number.
2440 * \param fd file descriptor.
2442 * \return major version number on success, or a negative value on failure..
2445 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2446 * necessary information in a drm_agp_info structure.
2448 drm_public int drmAgpVersionMajor(int fd)
2454 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2456 return i.agp_version_major;
2461 * Get AGP driver minor version number.
2463 * \param fd file descriptor.
2465 * \return minor version number on success, or a negative value on failure.
2468 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2469 * necessary information in a drm_agp_info structure.
2471 drm_public int drmAgpVersionMinor(int fd)
2477 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2479 return i.agp_version_minor;
2486 * \param fd file descriptor.
2488 * \return mode on success, or zero on failure.
2491 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2492 * necessary information in a drm_agp_info structure.
2494 drm_public unsigned long drmAgpGetMode(int fd)
2500 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2507 * Get AGP aperture base.
2509 * \param fd file descriptor.
2511 * \return aperture base on success, zero on failure.
2514 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2515 * necessary information in a drm_agp_info structure.
2517 drm_public unsigned long drmAgpBase(int fd)
2523 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2525 return i.aperture_base;
2530 * Get AGP aperture size.
2532 * \param fd file descriptor.
2534 * \return aperture size on success, zero on failure.
2537 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2538 * necessary information in a drm_agp_info structure.
2540 drm_public unsigned long drmAgpSize(int fd)
2546 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2548 return i.aperture_size;
2553 * Get used AGP memory.
2555 * \param fd file descriptor.
2557 * \return memory used on success, or zero on failure.
2560 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2561 * necessary information in a drm_agp_info structure.
2563 drm_public unsigned long drmAgpMemoryUsed(int fd)
2569 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2571 return i.memory_used;
2576 * Get available AGP memory.
2578 * \param fd file descriptor.
2580 * \return memory available on success, or zero on failure.
2583 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2584 * necessary information in a drm_agp_info structure.
2586 drm_public unsigned long drmAgpMemoryAvail(int fd)
2592 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2594 return i.memory_allowed;
2599 * Get hardware vendor ID.
2601 * \param fd file descriptor.
2603 * \return vendor ID on success, or zero on failure.
2606 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2607 * necessary information in a drm_agp_info structure.
2609 drm_public unsigned int drmAgpVendorId(int fd)
2615 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2622 * Get hardware device ID.
2624 * \param fd file descriptor.
2626 * \return zero on success, or zero on failure.
2629 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2630 * necessary information in a drm_agp_info structure.
2632 drm_public unsigned int drmAgpDeviceId(int fd)
2638 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2643 drm_public int drmScatterGatherAlloc(int fd, unsigned long size,
2644 drm_handle_t *handle)
2646 drm_scatter_gather_t sg;
2652 if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
2654 *handle = sg.handle;
2658 drm_public int drmScatterGatherFree(int fd, drm_handle_t handle)
2660 drm_scatter_gather_t sg;
2664 if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
2672 * \param fd file descriptor.
2673 * \param vbl pointer to a drmVBlank structure.
2675 * \return zero on success, or a negative value on failure.
2678 * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
2680 drm_public int drmWaitVBlank(int fd, drmVBlankPtr vbl)
2682 struct timespec timeout, cur;
2685 ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2687 fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
2693 ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
2694 vbl->request.type &= ~DRM_VBLANK_RELATIVE;
2695 if (ret && errno == EINTR) {
2696 clock_gettime(CLOCK_MONOTONIC, &cur);
2697 /* Timeout after 1s */
2698 if (cur.tv_sec > timeout.tv_sec + 1 ||
2699 (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
2706 } while (ret && errno == EINTR);
2712 drm_public int drmError(int err, const char *label)
2715 case DRM_ERR_NO_DEVICE:
2716 fprintf(stderr, "%s: no device\n", label);
2718 case DRM_ERR_NO_ACCESS:
2719 fprintf(stderr, "%s: no access\n", label);
2721 case DRM_ERR_NOT_ROOT:
2722 fprintf(stderr, "%s: not root\n", label);
2724 case DRM_ERR_INVALID:
2725 fprintf(stderr, "%s: invalid args\n", label);
2730 fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2738 * Install IRQ handler.
2740 * \param fd file descriptor.
2741 * \param irq IRQ number.
2743 * \return zero on success, or a negative value on failure.
2746 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2747 * argument in a drm_control structure.
2749 drm_public int drmCtlInstHandler(int fd, int irq)
2754 ctl.func = DRM_INST_HANDLER;
2756 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2763 * Uninstall IRQ handler.
2765 * \param fd file descriptor.
2767 * \return zero on success, or a negative value on failure.
2770 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2771 * argument in a drm_control structure.
2773 drm_public int drmCtlUninstHandler(int fd)
2778 ctl.func = DRM_UNINST_HANDLER;
2780 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2785 drm_public int drmFinish(int fd, int context, drmLockFlags flags)
2790 lock.context = context;
2791 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
2792 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
2793 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
2794 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
2795 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2796 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2797 if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2803 * Get IRQ from bus ID.
2805 * \param fd file descriptor.
2806 * \param busnum bus number.
2807 * \param devnum device number.
2808 * \param funcnum function number.
2810 * \return IRQ number on success, or a negative value on failure.
2813 * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2814 * arguments in a drm_irq_busid structure.
2816 drm_public int drmGetInterruptFromBusID(int fd, int busnum, int devnum,
2824 p.funcnum = funcnum;
2825 if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2830 drm_public int drmAddContextTag(int fd, drm_context_t context, void *tag)
2832 drmHashEntry *entry = drmGetEntry(fd);
2834 if (drmHashInsert(entry->tagTable, context, tag)) {
2835 drmHashDelete(entry->tagTable, context);
2836 drmHashInsert(entry->tagTable, context, tag);
2841 drm_public int drmDelContextTag(int fd, drm_context_t context)
2843 drmHashEntry *entry = drmGetEntry(fd);
2845 return drmHashDelete(entry->tagTable, context);
2848 drm_public void *drmGetContextTag(int fd, drm_context_t context)
2850 drmHashEntry *entry = drmGetEntry(fd);
2853 if (drmHashLookup(entry->tagTable, context, &value))
2859 drm_public int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2860 drm_handle_t handle)
2862 drm_ctx_priv_map_t map;
2865 map.ctx_id = ctx_id;
2866 map.handle = (void *)(uintptr_t)handle;
2868 if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2873 drm_public int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2874 drm_handle_t *handle)
2876 drm_ctx_priv_map_t map;
2879 map.ctx_id = ctx_id;
2881 if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2884 *handle = (drm_handle_t)(uintptr_t)map.handle;
2889 drm_public int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2890 drmMapType *type, drmMapFlags *flags,
2891 drm_handle_t *handle, int *mtrr)
2897 if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2899 *offset = map.offset;
2901 *type = (drmMapType)map.type;
2902 *flags = (drmMapFlags)map.flags;
2903 *handle = (unsigned long)map.handle;
2908 drm_public int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2909 unsigned long *magic, unsigned long *iocs)
2911 drm_client_t client;
2915 if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2917 *auth = client.auth;
2920 *magic = client.magic;
2921 *iocs = client.iocs;
2925 drm_public int drmGetStats(int fd, drmStatsT *stats)
2931 if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2935 memset(stats, 0, sizeof(*stats));
2936 if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2940 stats->data[i].long_format = "%-20.20s"; \
2941 stats->data[i].rate_format = "%8.8s"; \
2942 stats->data[i].isvalue = 1; \
2943 stats->data[i].verbose = 0
2946 stats->data[i].long_format = "%-20.20s"; \
2947 stats->data[i].rate_format = "%5.5s"; \
2948 stats->data[i].isvalue = 0; \
2949 stats->data[i].mult_names = "kgm"; \
2950 stats->data[i].mult = 1000; \
2951 stats->data[i].verbose = 0
2954 stats->data[i].long_format = "%-20.20s"; \
2955 stats->data[i].rate_format = "%5.5s"; \
2956 stats->data[i].isvalue = 0; \
2957 stats->data[i].mult_names = "KGM"; \
2958 stats->data[i].mult = 1024; \
2959 stats->data[i].verbose = 0
2962 stats->count = s.count;
2963 for (i = 0; i < s.count; i++) {
2964 stats->data[i].value = s.data[i].value;
2965 switch (s.data[i].type) {
2966 case _DRM_STAT_LOCK:
2967 stats->data[i].long_name = "Lock";
2968 stats->data[i].rate_name = "Lock";
2971 case _DRM_STAT_OPENS:
2972 stats->data[i].long_name = "Opens";
2973 stats->data[i].rate_name = "O";
2975 stats->data[i].verbose = 1;
2977 case _DRM_STAT_CLOSES:
2978 stats->data[i].long_name = "Closes";
2979 stats->data[i].rate_name = "Lock";
2981 stats->data[i].verbose = 1;
2983 case _DRM_STAT_IOCTLS:
2984 stats->data[i].long_name = "Ioctls";
2985 stats->data[i].rate_name = "Ioc/s";
2988 case _DRM_STAT_LOCKS:
2989 stats->data[i].long_name = "Locks";
2990 stats->data[i].rate_name = "Lck/s";
2993 case _DRM_STAT_UNLOCKS:
2994 stats->data[i].long_name = "Unlocks";
2995 stats->data[i].rate_name = "Unl/s";
2999 stats->data[i].long_name = "IRQs";
3000 stats->data[i].rate_name = "IRQ/s";
3003 case _DRM_STAT_PRIMARY:
3004 stats->data[i].long_name = "Primary Bytes";
3005 stats->data[i].rate_name = "PB/s";
3008 case _DRM_STAT_SECONDARY:
3009 stats->data[i].long_name = "Secondary Bytes";
3010 stats->data[i].rate_name = "SB/s";
3014 stats->data[i].long_name = "DMA";
3015 stats->data[i].rate_name = "DMA/s";
3018 case _DRM_STAT_SPECIAL:
3019 stats->data[i].long_name = "Special DMA";
3020 stats->data[i].rate_name = "dma/s";
3023 case _DRM_STAT_MISSED:
3024 stats->data[i].long_name = "Miss";
3025 stats->data[i].rate_name = "Ms/s";
3028 case _DRM_STAT_VALUE:
3029 stats->data[i].long_name = "Value";
3030 stats->data[i].rate_name = "Value";
3033 case _DRM_STAT_BYTE:
3034 stats->data[i].long_name = "Bytes";
3035 stats->data[i].rate_name = "B/s";
3038 case _DRM_STAT_COUNT:
3040 stats->data[i].long_name = "Count";
3041 stats->data[i].rate_name = "Cnt/s";
3050 * Issue a set-version ioctl.
3052 * \param fd file descriptor.
3053 * \param drmCommandIndex command index
3054 * \param data source pointer of the data to be read and written.
3055 * \param size size of the data to be read and written.
3057 * \return zero on success, or a negative value on failure.
3060 * It issues a read-write ioctl given by
3061 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
3063 drm_public int drmSetInterfaceVersion(int fd, drmSetVersion *version)
3066 drm_set_version_t sv;
3069 sv.drm_di_major = version->drm_di_major;
3070 sv.drm_di_minor = version->drm_di_minor;
3071 sv.drm_dd_major = version->drm_dd_major;
3072 sv.drm_dd_minor = version->drm_dd_minor;
3074 if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
3078 version->drm_di_major = sv.drm_di_major;
3079 version->drm_di_minor = sv.drm_di_minor;
3080 version->drm_dd_major = sv.drm_dd_major;
3081 version->drm_dd_minor = sv.drm_dd_minor;
3087 * Send a device-specific command.
3089 * \param fd file descriptor.
3090 * \param drmCommandIndex command index
3092 * \return zero on success, or a negative value on failure.
3095 * It issues a ioctl given by
3096 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
3098 drm_public int drmCommandNone(int fd, unsigned long drmCommandIndex)
3100 unsigned long request;
3102 request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
3104 if (drmIoctl(fd, request, NULL)) {
3112 * Send a device-specific read command.
3114 * \param fd file descriptor.
3115 * \param drmCommandIndex command index
3116 * \param data destination pointer of the data to be read.
3117 * \param size size of the data to be read.
3119 * \return zero on success, or a negative value on failure.
3122 * It issues a read ioctl given by
3123 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
3125 drm_public int drmCommandRead(int fd, unsigned long drmCommandIndex,
3126 void *data, unsigned long size)
3128 unsigned long request;
3130 request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
3131 DRM_COMMAND_BASE + drmCommandIndex, size);
3133 if (drmIoctl(fd, request, data)) {
3141 * Send a device-specific write command.
3143 * \param fd file descriptor.
3144 * \param drmCommandIndex command index
3145 * \param data source pointer of the data to be written.
3146 * \param size size of the data to be written.
3148 * \return zero on success, or a negative value on failure.
3151 * It issues a write ioctl given by
3152 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
3154 drm_public int drmCommandWrite(int fd, unsigned long drmCommandIndex,
3155 void *data, unsigned long size)
3157 unsigned long request;
3159 request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
3160 DRM_COMMAND_BASE + drmCommandIndex, size);
3162 if (drmIoctl(fd, request, data)) {
3170 * Send a device-specific read-write command.
3172 * \param fd file descriptor.
3173 * \param drmCommandIndex command index
3174 * \param data source pointer of the data to be read and written.
3175 * \param size size of the data to be read and written.
3177 * \return zero on success, or a negative value on failure.
3180 * It issues a read-write ioctl given by
3181 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
3183 drm_public int drmCommandWriteRead(int fd, unsigned long drmCommandIndex,
3184 void *data, unsigned long size)
3186 unsigned long request;
3188 request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
3189 DRM_COMMAND_BASE + drmCommandIndex, size);
3191 if (drmIoctl(fd, request, data))
3196 #define DRM_MAX_FDS 16
3202 } connection[DRM_MAX_FDS];
3204 static int nr_fds = 0;
3206 drm_public int drmOpenOnce(void *unused, const char *BusID, int *newlyopened)
3208 return drmOpenOnceWithType(BusID, newlyopened, DRM_NODE_PRIMARY);
3211 drm_public int drmOpenOnceWithType(const char *BusID, int *newlyopened,
3217 for (i = 0; i < nr_fds; i++)
3218 if ((strcmp(BusID, connection[i].BusID) == 0) &&
3219 (connection[i].type == type)) {
3220 connection[i].refcount++;
3222 return connection[i].fd;
3225 fd = drmOpenWithType(NULL, BusID, type);
3226 if (fd < 0 || nr_fds == DRM_MAX_FDS)
3229 connection[nr_fds].BusID = strdup(BusID);
3230 connection[nr_fds].fd = fd;
3231 connection[nr_fds].refcount = 1;
3232 connection[nr_fds].type = type;
3236 fprintf(stderr, "saved connection %d for %s %d\n",
3237 nr_fds, connection[nr_fds].BusID,
3238 strcmp(BusID, connection[nr_fds].BusID));
3245 drm_public void drmCloseOnce(int fd)
3249 for (i = 0; i < nr_fds; i++) {
3250 if (fd == connection[i].fd) {
3251 if (--connection[i].refcount == 0) {
3252 drmClose(connection[i].fd);
3253 free(connection[i].BusID);
3256 connection[i] = connection[nr_fds];
3264 drm_public int drmSetMaster(int fd)
3266 return drmIoctl(fd, DRM_IOCTL_SET_MASTER, NULL);
3269 drm_public int drmDropMaster(int fd)
3271 return drmIoctl(fd, DRM_IOCTL_DROP_MASTER, NULL);
3274 drm_public int drmIsMaster(int fd)
3276 /* Detect master by attempting something that requires master.
3278 * Authenticating magic tokens requires master and 0 is an
3279 * internal kernel detail which we could use. Attempting this on
3280 * a master fd would fail therefore fail with EINVAL because 0
3283 * A non-master fd will fail with EACCES, as the kernel checks
3284 * for master before attempting to do anything else.
3286 * Since we don't want to leak implementation details, use
3289 return drmAuthMagic(fd, 0) != -EACCES;
3292 drm_public char *drmGetDeviceNameFromFd(int fd)
3299 if (fstat(fd, &sbuf))
3302 maj = major(sbuf.st_rdev);
3303 min = minor(sbuf.st_rdev);
3304 nodetype = drmGetMinorType(maj, min);
3305 return drmGetMinorNameForFD(fd, nodetype);
3312 /* The whole drmOpen thing is a fiasco and we need to find a way
3313 * back to just using open(2). For now, however, lets just make
3314 * things worse with even more ad hoc directory walking code to
3315 * discover the device file name. */
3320 for (i = 0; i < DRM_MAX_MINOR; i++) {
3321 snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
3322 if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
3325 if (i == DRM_MAX_MINOR)
3328 return strdup(name);
3332 static bool drmNodeIsDRM(int maj, int min)
3338 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device/drm",
3340 return stat(path, &sbuf) == 0;
3341 #elif defined(__FreeBSD__)
3342 char name[SPECNAMELEN];
3344 if (!devname_r(makedev(maj, min), S_IFCHR, name, sizeof(name)))
3346 /* Handle drm/ and dri/ as both are present in different FreeBSD version
3347 * FreeBSD on amd64/i386/powerpc external kernel modules create node in
3348 * in /dev/drm/ and links in /dev/dri while a WIP in kernel driver creates
3349 * only device nodes in /dev/dri/ */
3350 return (!strncmp(name, "drm/", 4) || !strncmp(name, "dri/", 4));
3352 return maj == DRM_MAJOR;
3356 drm_public int drmGetNodeTypeFromFd(int fd)
3361 if (fstat(fd, &sbuf))
3364 maj = major(sbuf.st_rdev);
3365 min = minor(sbuf.st_rdev);
3367 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode)) {
3372 type = drmGetMinorType(maj, min);
3378 drm_public int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags,
3381 struct drm_prime_handle args;
3386 args.handle = handle;
3388 ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
3392 *prime_fd = args.fd;
3396 drm_public int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
3398 struct drm_prime_handle args;
3403 ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
3407 *handle = args.handle;
3411 drm_public int drmCloseBufferHandle(int fd, uint32_t handle)
3413 struct drm_gem_close args;
3416 args.handle = handle;
3417 return drmIoctl(fd, DRM_IOCTL_GEM_CLOSE, &args);
3420 static char *drmGetMinorNameForFD(int fd, int type)
3426 const char *name = drmGetMinorName(type);
3428 char dev_name[64], buf[64];
3436 if (fstat(fd, &sbuf))
3439 maj = major(sbuf.st_rdev);
3440 min = minor(sbuf.st_rdev);
3442 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3445 snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
3447 sysdir = opendir(buf);
3451 while ((ent = readdir(sysdir))) {
3452 if (strncmp(ent->d_name, name, len) == 0) {
3453 if (snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
3458 return strdup(dev_name);
3464 #elif defined(__FreeBSD__)
3466 char dname[SPECNAMELEN];
3468 char name[SPECNAMELEN];
3469 int id, maj, min, nodetype, i;
3471 if (fstat(fd, &sbuf))
3474 maj = major(sbuf.st_rdev);
3475 min = minor(sbuf.st_rdev);
3477 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3480 if (!devname_r(sbuf.st_rdev, S_IFCHR, dname, sizeof(dname)))
3483 /* Handle both /dev/drm and /dev/dri
3484 * FreeBSD on amd64/i386/powerpc external kernel modules create node in
3485 * in /dev/drm/ and links in /dev/dri while a WIP in kernel driver creates
3486 * only device nodes in /dev/dri/ */
3488 /* Get the node type represented by fd so we can deduce the target name */
3489 nodetype = drmGetMinorType(maj, min);
3492 mname = drmGetMinorName(type);
3494 for (i = 0; i < SPECNAMELEN; i++) {
3495 if (isalpha(dname[i]) == 0 && dname[i] != '/')
3498 if (dname[i] == '\0')
3501 id = (int)strtol(&dname[i], NULL, 10);
3502 id -= drmGetMinorBase(nodetype);
3503 snprintf(name, sizeof(name), DRM_DIR_NAME "/%s%d", mname,
3504 id + drmGetMinorBase(type));
3506 return strdup(name);
3509 char buf[PATH_MAX + 1];
3510 const char *dev_name = drmGetDeviceName(type);
3511 unsigned int maj, min;
3514 if (fstat(fd, &sbuf))
3517 maj = major(sbuf.st_rdev);
3518 min = minor(sbuf.st_rdev);
3520 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3526 n = snprintf(buf, sizeof(buf), dev_name, DRM_DIR_NAME, min);
3527 if (n == -1 || n >= sizeof(buf))
3534 drm_public char *drmGetPrimaryDeviceNameFromFd(int fd)
3536 return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
3539 drm_public char *drmGetRenderDeviceNameFromFd(int fd)
3541 return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
3545 static char * DRM_PRINTFLIKE(2, 3)
3546 sysfs_uevent_get(const char *path, const char *fmt, ...)
3548 char filename[PATH_MAX + 1], *key, *line = NULL, *value = NULL;
3549 size_t size = 0, len;
3555 num = vasprintf(&key, fmt, ap);
3559 snprintf(filename, sizeof(filename), "%s/uevent", path);
3561 fp = fopen(filename, "r");
3567 while ((num = getline(&line, &size, fp)) >= 0) {
3568 if ((strncmp(line, key, len) == 0) && (line[len] == '=')) {
3569 char *start = line + len + 1, *end = line + num - 1;
3574 value = strndup(start, end - start);
3588 /* Little white lie to avoid major rework of the existing code */
3589 #define DRM_BUS_VIRTIO 0x10
3592 static int get_subsystem_type(const char *device_path)
3594 char path[PATH_MAX + 1] = "";
3595 char link[PATH_MAX + 1] = "";
3601 { "/pci", DRM_BUS_PCI },
3602 { "/usb", DRM_BUS_USB },
3603 { "/platform", DRM_BUS_PLATFORM },
3604 { "/spi", DRM_BUS_PLATFORM },
3605 { "/host1x", DRM_BUS_HOST1X },
3606 { "/virtio", DRM_BUS_VIRTIO },
3609 strncpy(path, device_path, PATH_MAX);
3610 strncat(path, "/subsystem", PATH_MAX);
3612 if (readlink(path, link, PATH_MAX) < 0)
3615 name = strrchr(link, '/');
3619 for (unsigned i = 0; i < ARRAY_SIZE(bus_types); i++) {
3620 if (strncmp(name, bus_types[i].name, strlen(bus_types[i].name)) == 0)
3621 return bus_types[i].bus_type;
3628 static int drmParseSubsystemType(int maj, int min)
3631 char path[PATH_MAX + 1] = "";
3632 char real_path[PATH_MAX + 1] = "";
3635 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3637 subsystem_type = get_subsystem_type(path);
3638 /* Try to get the parent (underlying) device type */
3639 if (subsystem_type == DRM_BUS_VIRTIO) {
3640 /* Assume virtio-pci on error */
3641 if (!realpath(path, real_path))
3642 return DRM_BUS_VIRTIO;
3643 strncat(path, "/..", PATH_MAX);
3644 subsystem_type = get_subsystem_type(path);
3645 if (subsystem_type < 0)
3646 return DRM_BUS_VIRTIO;
3648 return subsystem_type;
3649 #elif defined(__OpenBSD__) || defined(__DragonFly__) || defined(__FreeBSD__)
3652 #warning "Missing implementation of drmParseSubsystemType"
3659 get_pci_path(int maj, int min, char *pci_path)
3661 char path[PATH_MAX + 1], *term;
3663 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3664 if (!realpath(path, pci_path)) {
3665 strcpy(pci_path, path);
3669 term = strrchr(pci_path, '/');
3670 if (term && strncmp(term, "/virtio", 7) == 0)
3676 static int get_sysctl_pci_bus_info(int maj, int min, drmPciBusInfoPtr info)
3678 char dname[SPECNAMELEN];
3679 char sysctl_name[16];
3680 char sysctl_val[256];
3682 int id, type, nelem;
3683 unsigned int rdev, majmin, domain, bus, dev, func;
3685 rdev = makedev(maj, min);
3686 if (!devname_r(rdev, S_IFCHR, dname, sizeof(dname)))
3689 if (sscanf(dname, "drm/%d\n", &id) != 1)
3691 type = drmGetMinorType(maj, min);
3695 /* BUG: This above section is iffy, since it mandates that a driver will
3696 * create both card and render node.
3697 * If it does not, the next DRM device will create card#X and
3698 * renderD#(128+X)-1.
3699 * This is a possibility in FreeBSD but for now there is no good way for
3700 * obtaining the info.
3703 case DRM_NODE_PRIMARY:
3705 case DRM_NODE_RENDER:
3712 if (snprintf(sysctl_name, sizeof(sysctl_name), "hw.dri.%d.busid", id) <= 0)
3714 sysctl_len = sizeof(sysctl_val);
3715 if (sysctlbyname(sysctl_name, sysctl_val, &sysctl_len, NULL, 0))
3718 #define bus_fmt "pci:%04x:%02x:%02x.%u"
3720 nelem = sscanf(sysctl_val, bus_fmt, &domain, &bus, &dev, &func);
3723 info->domain = domain;
3732 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
3735 unsigned int domain, bus, dev, func;
3736 char pci_path[PATH_MAX + 1], *value;
3739 get_pci_path(maj, min, pci_path);
3741 value = sysfs_uevent_get(pci_path, "PCI_SLOT_NAME");
3745 num = sscanf(value, "%04x:%02x:%02x.%1u", &domain, &bus, &dev, &func);
3751 info->domain = domain;
3757 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3758 struct drm_pciinfo pinfo;
3761 type = drmGetMinorType(maj, min);
3765 fd = drmOpenMinor(min, 0, type);
3769 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3775 info->domain = pinfo.domain;
3776 info->bus = pinfo.bus;
3777 info->dev = pinfo.dev;
3778 info->func = pinfo.func;
3781 #elif defined(__FreeBSD__)
3782 return get_sysctl_pci_bus_info(maj, min, info);
3784 #warning "Missing implementation of drmParsePciBusInfo"
3789 drm_public int drmDevicesEqual(drmDevicePtr a, drmDevicePtr b)
3791 if (a == NULL || b == NULL)
3794 if (a->bustype != b->bustype)
3797 switch (a->bustype) {
3799 return memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo)) == 0;
3802 return memcmp(a->businfo.usb, b->businfo.usb, sizeof(drmUsbBusInfo)) == 0;
3804 case DRM_BUS_PLATFORM:
3805 return memcmp(a->businfo.platform, b->businfo.platform, sizeof(drmPlatformBusInfo)) == 0;
3807 case DRM_BUS_HOST1X:
3808 return memcmp(a->businfo.host1x, b->businfo.host1x, sizeof(drmHost1xBusInfo)) == 0;
3817 static int drmGetNodeType(const char *name)
3819 if (strncmp(name, DRM_RENDER_MINOR_NAME,
3820 sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
3821 return DRM_NODE_RENDER;
3823 if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
3824 sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
3825 return DRM_NODE_PRIMARY;
3830 static int drmGetMaxNodeName(void)
3832 return sizeof(DRM_DIR_NAME) +
3833 MAX3(sizeof(DRM_PRIMARY_MINOR_NAME),
3834 sizeof(DRM_CONTROL_MINOR_NAME),
3835 sizeof(DRM_RENDER_MINOR_NAME)) +
3836 3 /* length of the node number */;
3840 static int parse_separate_sysfs_files(int maj, int min,
3841 drmPciDeviceInfoPtr device,
3842 bool ignore_revision)
3844 static const char *attrs[] = {
3845 "revision", /* Older kernels are missing the file, so check for it first */
3851 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3852 unsigned int data[ARRAY_SIZE(attrs)];
3856 get_pci_path(maj, min, pci_path);
3858 for (unsigned i = ignore_revision ? 1 : 0; i < ARRAY_SIZE(attrs); i++) {
3859 if (snprintf(path, PATH_MAX, "%s/%s", pci_path, attrs[i]) < 0)
3862 fp = fopen(path, "r");
3866 ret = fscanf(fp, "%x", &data[i]);
3873 device->revision_id = ignore_revision ? 0xff : data[0] & 0xff;
3874 device->vendor_id = data[1] & 0xffff;
3875 device->device_id = data[2] & 0xffff;
3876 device->subvendor_id = data[3] & 0xffff;
3877 device->subdevice_id = data[4] & 0xffff;
3882 static int parse_config_sysfs_file(int maj, int min,
3883 drmPciDeviceInfoPtr device)
3885 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3886 unsigned char config[64];
3889 get_pci_path(maj, min, pci_path);
3891 if (snprintf(path, PATH_MAX, "%s/config", pci_path) < 0)
3894 fd = open(path, O_RDONLY);
3898 ret = read(fd, config, sizeof(config));
3903 device->vendor_id = config[0] | (config[1] << 8);
3904 device->device_id = config[2] | (config[3] << 8);
3905 device->revision_id = config[8];
3906 device->subvendor_id = config[44] | (config[45] << 8);
3907 device->subdevice_id = config[46] | (config[47] << 8);
3913 static int drmParsePciDeviceInfo(int maj, int min,
3914 drmPciDeviceInfoPtr device,
3918 if (!(flags & DRM_DEVICE_GET_PCI_REVISION))
3919 return parse_separate_sysfs_files(maj, min, device, true);
3921 if (parse_separate_sysfs_files(maj, min, device, false))
3922 return parse_config_sysfs_file(maj, min, device);
3925 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3926 struct drm_pciinfo pinfo;
3929 type = drmGetMinorType(maj, min);
3933 fd = drmOpenMinor(min, 0, type);
3937 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3943 device->vendor_id = pinfo.vendor_id;
3944 device->device_id = pinfo.device_id;
3945 device->revision_id = pinfo.revision_id;
3946 device->subvendor_id = pinfo.subvendor_id;
3947 device->subdevice_id = pinfo.subdevice_id;
3950 #elif defined(__FreeBSD__)
3952 struct pci_conf_io pc;
3953 struct pci_match_conf patterns[1];
3954 struct pci_conf results[1];
3957 if (get_sysctl_pci_bus_info(maj, min, &info) != 0)
3960 fd = open("/dev/pci", O_RDONLY);
3964 bzero(&patterns, sizeof(patterns));
3965 patterns[0].pc_sel.pc_domain = info.domain;
3966 patterns[0].pc_sel.pc_bus = info.bus;
3967 patterns[0].pc_sel.pc_dev = info.dev;
3968 patterns[0].pc_sel.pc_func = info.func;
3969 patterns[0].flags = PCI_GETCONF_MATCH_DOMAIN | PCI_GETCONF_MATCH_BUS
3970 | PCI_GETCONF_MATCH_DEV | PCI_GETCONF_MATCH_FUNC;
3971 bzero(&pc, sizeof(struct pci_conf_io));
3972 pc.num_patterns = 1;
3973 pc.pat_buf_len = sizeof(patterns);
3974 pc.patterns = patterns;
3975 pc.match_buf_len = sizeof(results);
3976 pc.matches = results;
3978 if (ioctl(fd, PCIOCGETCONF, &pc) || pc.status == PCI_GETCONF_ERROR) {
3985 device->vendor_id = results[0].pc_vendor;
3986 device->device_id = results[0].pc_device;
3987 device->subvendor_id = results[0].pc_subvendor;
3988 device->subdevice_id = results[0].pc_subdevice;
3989 device->revision_id = results[0].pc_revid;
3993 #warning "Missing implementation of drmParsePciDeviceInfo"
3998 static void drmFreePlatformDevice(drmDevicePtr device)
4000 if (device->deviceinfo.platform) {
4001 if (device->deviceinfo.platform->compatible) {
4002 char **compatible = device->deviceinfo.platform->compatible;
4004 while (*compatible) {
4009 free(device->deviceinfo.platform->compatible);
4014 static void drmFreeHost1xDevice(drmDevicePtr device)
4016 if (device->deviceinfo.host1x) {
4017 if (device->deviceinfo.host1x->compatible) {
4018 char **compatible = device->deviceinfo.host1x->compatible;
4020 while (*compatible) {
4025 free(device->deviceinfo.host1x->compatible);
4030 drm_public void drmFreeDevice(drmDevicePtr *device)
4036 switch ((*device)->bustype) {
4037 case DRM_BUS_PLATFORM:
4038 drmFreePlatformDevice(*device);
4041 case DRM_BUS_HOST1X:
4042 drmFreeHost1xDevice(*device);
4051 drm_public void drmFreeDevices(drmDevicePtr devices[], int count)
4055 if (devices == NULL)
4058 for (i = 0; i < count; i++)
4060 drmFreeDevice(&devices[i]);
4063 static drmDevicePtr drmDeviceAlloc(unsigned int type, const char *node,
4064 size_t bus_size, size_t device_size,
4067 size_t max_node_length, extra, size;
4068 drmDevicePtr device;
4072 max_node_length = ALIGN(drmGetMaxNodeName(), sizeof(void *));
4073 extra = DRM_NODE_MAX * (sizeof(void *) + max_node_length);
4075 size = sizeof(*device) + extra + bus_size + device_size;
4077 device = calloc(1, size);
4081 device->available_nodes = 1 << type;
4083 ptr = (char *)device + sizeof(*device);
4084 device->nodes = (char **)ptr;
4086 ptr += DRM_NODE_MAX * sizeof(void *);
4088 for (i = 0; i < DRM_NODE_MAX; i++) {
4089 device->nodes[i] = ptr;
4090 ptr += max_node_length;
4093 memcpy(device->nodes[type], node, max_node_length);
4100 static int drmProcessPciDevice(drmDevicePtr *device,
4101 const char *node, int node_type,
4102 int maj, int min, bool fetch_deviceinfo,
4109 dev = drmDeviceAlloc(node_type, node, sizeof(drmPciBusInfo),
4110 sizeof(drmPciDeviceInfo), &addr);
4114 dev->bustype = DRM_BUS_PCI;
4116 dev->businfo.pci = (drmPciBusInfoPtr)addr;
4118 ret = drmParsePciBusInfo(maj, min, dev->businfo.pci);
4122 // Fetch the device info if the user has requested it
4123 if (fetch_deviceinfo) {
4124 addr += sizeof(drmPciBusInfo);
4125 dev->deviceinfo.pci = (drmPciDeviceInfoPtr)addr;
4127 ret = drmParsePciDeviceInfo(maj, min, dev->deviceinfo.pci, flags);
4142 static int drm_usb_dev_path(int maj, int min, char *path, size_t len)
4144 char *value, *tmp_path, *slash;
4145 bool usb_device, usb_interface;
4147 snprintf(path, len, "/sys/dev/char/%d:%d/device", maj, min);
4149 value = sysfs_uevent_get(path, "DEVTYPE");
4153 usb_device = strcmp(value, "usb_device") == 0;
4154 usb_interface = strcmp(value, "usb_interface") == 0;
4162 /* The parent of a usb_interface is a usb_device */
4164 tmp_path = realpath(path, NULL);
4168 slash = strrchr(tmp_path, '/');
4176 if (snprintf(path, len, "%s", tmp_path) >= (int)len) {
4186 static int drmParseUsbBusInfo(int maj, int min, drmUsbBusInfoPtr info)
4189 char path[PATH_MAX + 1], *value;
4190 unsigned int bus, dev;
4193 ret = drm_usb_dev_path(maj, min, path, sizeof(path));
4197 value = sysfs_uevent_get(path, "BUSNUM");
4201 ret = sscanf(value, "%03u", &bus);
4207 value = sysfs_uevent_get(path, "DEVNUM");
4211 ret = sscanf(value, "%03u", &dev);
4222 #warning "Missing implementation of drmParseUsbBusInfo"
4227 static int drmParseUsbDeviceInfo(int maj, int min, drmUsbDeviceInfoPtr info)
4230 char path[PATH_MAX + 1], *value;
4231 unsigned int vendor, product;
4234 ret = drm_usb_dev_path(maj, min, path, sizeof(path));
4238 value = sysfs_uevent_get(path, "PRODUCT");
4242 ret = sscanf(value, "%x/%x", &vendor, &product);
4248 info->vendor = vendor;
4249 info->product = product;
4253 #warning "Missing implementation of drmParseUsbDeviceInfo"
4258 static int drmProcessUsbDevice(drmDevicePtr *device, const char *node,
4259 int node_type, int maj, int min,
4260 bool fetch_deviceinfo, uint32_t flags)
4266 dev = drmDeviceAlloc(node_type, node, sizeof(drmUsbBusInfo),
4267 sizeof(drmUsbDeviceInfo), &ptr);
4271 dev->bustype = DRM_BUS_USB;
4273 dev->businfo.usb = (drmUsbBusInfoPtr)ptr;
4275 ret = drmParseUsbBusInfo(maj, min, dev->businfo.usb);
4279 if (fetch_deviceinfo) {
4280 ptr += sizeof(drmUsbBusInfo);
4281 dev->deviceinfo.usb = (drmUsbDeviceInfoPtr)ptr;
4283 ret = drmParseUsbDeviceInfo(maj, min, dev->deviceinfo.usb);
4297 static int drmParseOFBusInfo(int maj, int min, char *fullname)
4300 char path[PATH_MAX + 1], *name, *tmp_name;
4302 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
4304 name = sysfs_uevent_get(path, "OF_FULLNAME");
4307 /* If the device lacks OF data, pick the MODALIAS info */
4308 name = sysfs_uevent_get(path, "MODALIAS");
4312 /* .. and strip the MODALIAS=[platform,usb...]: part. */
4313 tmp_name = strrchr(name, ':');
4321 strncpy(fullname, tmp_name, DRM_PLATFORM_DEVICE_NAME_LEN);
4322 fullname[DRM_PLATFORM_DEVICE_NAME_LEN - 1] = '\0';
4327 #warning "Missing implementation of drmParseOFBusInfo"
4332 static int drmParseOFDeviceInfo(int maj, int min, char ***compatible)
4335 char path[PATH_MAX + 1], *value, *tmp_name;
4336 unsigned int count, i;
4339 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
4341 value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
4343 sscanf(value, "%u", &count);
4346 /* Assume one entry if the device lack OF data */
4350 *compatible = calloc(count + 1, sizeof(char *));
4354 for (i = 0; i < count; i++) {
4355 value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
4358 /* If the device lacks OF data, pick the MODALIAS info */
4359 value = sysfs_uevent_get(path, "MODALIAS");
4365 /* .. and strip the MODALIAS=[platform,usb...]: part. */
4366 tmp_name = strrchr(value, ':');
4371 tmp_name = strdup(tmp_name + 1);
4375 (*compatible)[i] = tmp_name;
4382 free((*compatible)[i]);
4387 #warning "Missing implementation of drmParseOFDeviceInfo"
4392 static int drmProcessPlatformDevice(drmDevicePtr *device,
4393 const char *node, int node_type,
4394 int maj, int min, bool fetch_deviceinfo,
4401 dev = drmDeviceAlloc(node_type, node, sizeof(drmPlatformBusInfo),
4402 sizeof(drmPlatformDeviceInfo), &ptr);
4406 dev->bustype = DRM_BUS_PLATFORM;
4408 dev->businfo.platform = (drmPlatformBusInfoPtr)ptr;
4410 ret = drmParseOFBusInfo(maj, min, dev->businfo.platform->fullname);
4414 if (fetch_deviceinfo) {
4415 ptr += sizeof(drmPlatformBusInfo);
4416 dev->deviceinfo.platform = (drmPlatformDeviceInfoPtr)ptr;
4418 ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.platform->compatible);
4432 static int drmProcessHost1xDevice(drmDevicePtr *device,
4433 const char *node, int node_type,
4434 int maj, int min, bool fetch_deviceinfo,
4441 dev = drmDeviceAlloc(node_type, node, sizeof(drmHost1xBusInfo),
4442 sizeof(drmHost1xDeviceInfo), &ptr);
4446 dev->bustype = DRM_BUS_HOST1X;
4448 dev->businfo.host1x = (drmHost1xBusInfoPtr)ptr;
4450 ret = drmParseOFBusInfo(maj, min, dev->businfo.host1x->fullname);
4454 if (fetch_deviceinfo) {
4455 ptr += sizeof(drmHost1xBusInfo);
4456 dev->deviceinfo.host1x = (drmHost1xDeviceInfoPtr)ptr;
4458 ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.host1x->compatible);
4473 process_device(drmDevicePtr *device, const char *d_name,
4474 int req_subsystem_type,
4475 bool fetch_deviceinfo, uint32_t flags)
4478 char node[PATH_MAX + 1];
4479 int node_type, subsystem_type;
4480 unsigned int maj, min;
4482 node_type = drmGetNodeType(d_name);
4486 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, d_name);
4487 if (stat(node, &sbuf))
4490 maj = major(sbuf.st_rdev);
4491 min = minor(sbuf.st_rdev);
4493 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4496 subsystem_type = drmParseSubsystemType(maj, min);
4497 if (req_subsystem_type != -1 && req_subsystem_type != subsystem_type)
4500 switch (subsystem_type) {
4502 case DRM_BUS_VIRTIO:
4503 return drmProcessPciDevice(device, node, node_type, maj, min,
4504 fetch_deviceinfo, flags);
4506 return drmProcessUsbDevice(device, node, node_type, maj, min,
4507 fetch_deviceinfo, flags);
4508 case DRM_BUS_PLATFORM:
4509 return drmProcessPlatformDevice(device, node, node_type, maj, min,
4510 fetch_deviceinfo, flags);
4511 case DRM_BUS_HOST1X:
4512 return drmProcessHost1xDevice(device, node, node_type, maj, min,
4513 fetch_deviceinfo, flags);
4519 /* Consider devices located on the same bus as duplicate and fold the respective
4520 * entries into a single one.
4522 * Note: this leaves "gaps" in the array, while preserving the length.
4524 static void drmFoldDuplicatedDevices(drmDevicePtr local_devices[], int count)
4526 int node_type, i, j;
4528 for (i = 0; i < count; i++) {
4529 for (j = i + 1; j < count; j++) {
4530 if (drmDevicesEqual(local_devices[i], local_devices[j])) {
4531 local_devices[i]->available_nodes |= local_devices[j]->available_nodes;
4532 node_type = log2_int(local_devices[j]->available_nodes);
4533 memcpy(local_devices[i]->nodes[node_type],
4534 local_devices[j]->nodes[node_type], drmGetMaxNodeName());
4535 drmFreeDevice(&local_devices[j]);
4541 /* Check that the given flags are valid returning 0 on success */
4543 drm_device_validate_flags(uint32_t flags)
4545 return (flags & ~DRM_DEVICE_GET_PCI_REVISION);
4549 drm_device_has_rdev(drmDevicePtr device, dev_t find_rdev)
4553 for (int i = 0; i < DRM_NODE_MAX; i++) {
4554 if (device->available_nodes & 1 << i) {
4555 if (stat(device->nodes[i], &sbuf) == 0 &&
4556 sbuf.st_rdev == find_rdev)
4564 * The kernel drm core has a number of places that assume maximum of
4565 * 3x64 devices nodes. That's 64 for each of primary, control and
4566 * render nodes. Rounded it up to 256 for simplicity.
4568 #define MAX_DRM_NODES 256
4571 * Get information about a device from its dev_t identifier
4573 * \param find_rdev dev_t identifier of the device
4574 * \param flags feature/behaviour bitmask
4575 * \param device the address of a drmDevicePtr where the information
4576 * will be allocated in stored
4578 * \return zero on success, negative error code otherwise.
4580 drm_public int drmGetDeviceFromDevId(dev_t find_rdev, uint32_t flags, drmDevicePtr *device)
4584 * DRI device nodes on OpenBSD are not in their own directory, they reside
4585 * in /dev along with a large number of statically generated /dev nodes.
4586 * Avoid stat'ing all of /dev needlessly by implementing this custom path.
4589 char node[PATH_MAX + 1];
4590 const char *dev_name;
4591 int node_type, subsystem_type;
4592 int maj, min, n, ret;
4597 maj = major(find_rdev);
4598 min = minor(find_rdev);
4600 if (!drmNodeIsDRM(maj, min))
4603 node_type = drmGetMinorType(maj, min);
4604 if (node_type == -1)
4607 dev_name = drmGetDeviceName(node_type);
4611 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min);
4612 if (n == -1 || n >= PATH_MAX)
4614 if (stat(node, &sbuf))
4617 subsystem_type = drmParseSubsystemType(maj, min);
4618 if (subsystem_type != DRM_BUS_PCI)
4621 ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
4629 drmDevicePtr local_devices[MAX_DRM_NODES];
4632 struct dirent *dent;
4635 int ret, i, node_count;
4637 if (drm_device_validate_flags(flags))
4643 maj = major(find_rdev);
4644 min = minor(find_rdev);
4646 if (!drmNodeIsDRM(maj, min))
4649 subsystem_type = drmParseSubsystemType(maj, min);
4650 if (subsystem_type < 0)
4651 return subsystem_type;
4653 sysdir = opendir(DRM_DIR_NAME);
4658 while ((dent = readdir(sysdir))) {
4659 ret = process_device(&d, dent->d_name, subsystem_type, true, flags);
4663 if (i >= MAX_DRM_NODES) {
4664 fprintf(stderr, "More than %d drm nodes detected. "
4665 "Please report a bug - that should not happen.\n"
4666 "Skipping extra nodes\n", MAX_DRM_NODES);
4669 local_devices[i] = d;
4674 drmFoldDuplicatedDevices(local_devices, node_count);
4678 for (i = 0; i < node_count; i++) {
4679 if (!local_devices[i])
4682 if (drm_device_has_rdev(local_devices[i], find_rdev))
4683 *device = local_devices[i];
4685 drmFreeDevice(&local_devices[i]);
4689 if (*device == NULL)
4695 drm_public int drmGetNodeTypeFromDevId(dev_t devid)
4697 int maj, min, node_type;
4702 if (!drmNodeIsDRM(maj, min))
4705 node_type = drmGetMinorType(maj, min);
4706 if (node_type == -1)
4713 * Get information about the opened drm device
4715 * \param fd file descriptor of the drm device
4716 * \param flags feature/behaviour bitmask
4717 * \param device the address of a drmDevicePtr where the information
4718 * will be allocated in stored
4720 * \return zero on success, negative error code otherwise.
4722 * \note Unlike drmGetDevice it does not retrieve the pci device revision field
4723 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
4725 drm_public int drmGetDevice2(int fd, uint32_t flags, drmDevicePtr *device)
4732 if (fstat(fd, &sbuf))
4735 if (!S_ISCHR(sbuf.st_mode))
4738 return drmGetDeviceFromDevId(sbuf.st_rdev, flags, device);
4742 * Get information about the opened drm device
4744 * \param fd file descriptor of the drm device
4745 * \param device the address of a drmDevicePtr where the information
4746 * will be allocated in stored
4748 * \return zero on success, negative error code otherwise.
4750 drm_public int drmGetDevice(int fd, drmDevicePtr *device)
4752 return drmGetDevice2(fd, DRM_DEVICE_GET_PCI_REVISION, device);
4756 * Get drm devices on the system
4758 * \param flags feature/behaviour bitmask
4759 * \param devices the array of devices with drmDevicePtr elements
4760 * can be NULL to get the device number first
4761 * \param max_devices the maximum number of devices for the array
4763 * \return on error - negative error code,
4764 * if devices is NULL - total number of devices available on the system,
4765 * alternatively the number of devices stored in devices[], which is
4766 * capped by the max_devices.
4768 * \note Unlike drmGetDevices it does not retrieve the pci device revision field
4769 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
4771 drm_public int drmGetDevices2(uint32_t flags, drmDevicePtr devices[],
4774 drmDevicePtr local_devices[MAX_DRM_NODES];
4775 drmDevicePtr device;
4777 struct dirent *dent;
4778 int ret, i, node_count, device_count;
4780 if (drm_device_validate_flags(flags))
4783 sysdir = opendir(DRM_DIR_NAME);
4788 while ((dent = readdir(sysdir))) {
4789 ret = process_device(&device, dent->d_name, -1, devices != NULL, flags);
4793 if (i >= MAX_DRM_NODES) {
4794 fprintf(stderr, "More than %d drm nodes detected. "
4795 "Please report a bug - that should not happen.\n"
4796 "Skipping extra nodes\n", MAX_DRM_NODES);
4799 local_devices[i] = device;
4804 drmFoldDuplicatedDevices(local_devices, node_count);
4807 for (i = 0; i < node_count; i++) {
4808 if (!local_devices[i])
4811 if ((devices != NULL) && (device_count < max_devices))
4812 devices[device_count] = local_devices[i];
4814 drmFreeDevice(&local_devices[i]);
4821 if (devices != NULL)
4822 return MIN2(device_count, max_devices);
4824 return device_count;
4828 * Get drm devices on the system
4830 * \param devices the array of devices with drmDevicePtr elements
4831 * can be NULL to get the device number first
4832 * \param max_devices the maximum number of devices for the array
4834 * \return on error - negative error code,
4835 * if devices is NULL - total number of devices available on the system,
4836 * alternatively the number of devices stored in devices[], which is
4837 * capped by the max_devices.
4839 drm_public int drmGetDevices(drmDevicePtr devices[], int max_devices)
4841 return drmGetDevices2(DRM_DEVICE_GET_PCI_REVISION, devices, max_devices);
4844 drm_public char *drmGetDeviceNameFromFd2(int fd)
4848 char path[PATH_MAX + 1], *value;
4849 unsigned int maj, min;
4851 if (fstat(fd, &sbuf))
4854 maj = major(sbuf.st_rdev);
4855 min = minor(sbuf.st_rdev);
4857 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4860 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d", maj, min);
4862 value = sysfs_uevent_get(path, "DEVNAME");
4866 snprintf(path, sizeof(path), "/dev/%s", value);
4869 return strdup(path);
4870 #elif defined(__FreeBSD__)
4871 return drmGetDeviceNameFromFd(fd);
4874 char node[PATH_MAX + 1];
4875 const char *dev_name;
4879 if (fstat(fd, &sbuf))
4882 maj = major(sbuf.st_rdev);
4883 min = minor(sbuf.st_rdev);
4885 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4888 node_type = drmGetMinorType(maj, min);
4889 if (node_type == -1)
4892 dev_name = drmGetDeviceName(node_type);
4896 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min);
4897 if (n == -1 || n >= PATH_MAX)
4900 return strdup(node);
4904 drm_public int drmSyncobjCreate(int fd, uint32_t flags, uint32_t *handle)
4906 struct drm_syncobj_create args;
4912 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_CREATE, &args);
4915 *handle = args.handle;
4919 drm_public int drmSyncobjDestroy(int fd, uint32_t handle)
4921 struct drm_syncobj_destroy args;
4924 args.handle = handle;
4925 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_DESTROY, &args);
4928 drm_public int drmSyncobjHandleToFD(int fd, uint32_t handle, int *obj_fd)
4930 struct drm_syncobj_handle args;
4935 args.handle = handle;
4936 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4943 drm_public int drmSyncobjFDToHandle(int fd, int obj_fd, uint32_t *handle)
4945 struct drm_syncobj_handle args;
4951 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4954 *handle = args.handle;
4958 drm_public int drmSyncobjImportSyncFile(int fd, uint32_t handle,
4961 struct drm_syncobj_handle args;
4964 args.fd = sync_file_fd;
4965 args.handle = handle;
4966 args.flags = DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE;
4967 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4970 drm_public int drmSyncobjExportSyncFile(int fd, uint32_t handle,
4973 struct drm_syncobj_handle args;
4978 args.handle = handle;
4979 args.flags = DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE;
4980 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4983 *sync_file_fd = args.fd;
4987 drm_public int drmSyncobjWait(int fd, uint32_t *handles, unsigned num_handles,
4988 int64_t timeout_nsec, unsigned flags,
4989 uint32_t *first_signaled)
4991 struct drm_syncobj_wait args;
4995 args.handles = (uintptr_t)handles;
4996 args.timeout_nsec = timeout_nsec;
4997 args.count_handles = num_handles;
5000 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_WAIT, &args);
5005 *first_signaled = args.first_signaled;
5009 drm_public int drmSyncobjReset(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_RESET, &args);
5023 drm_public int drmSyncobjSignal(int fd, const uint32_t *handles,
5024 uint32_t handle_count)
5026 struct drm_syncobj_array args;
5030 args.handles = (uintptr_t)handles;
5031 args.count_handles = handle_count;
5033 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_SIGNAL, &args);
5037 drm_public int drmSyncobjTimelineSignal(int fd, const uint32_t *handles,
5038 uint64_t *points, uint32_t handle_count)
5040 struct drm_syncobj_timeline_array args;
5044 args.handles = (uintptr_t)handles;
5045 args.points = (uintptr_t)points;
5046 args.count_handles = handle_count;
5048 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TIMELINE_SIGNAL, &args);
5052 drm_public int drmSyncobjTimelineWait(int fd, uint32_t *handles, uint64_t *points,
5053 unsigned num_handles,
5054 int64_t timeout_nsec, unsigned flags,
5055 uint32_t *first_signaled)
5057 struct drm_syncobj_timeline_wait args;
5061 args.handles = (uintptr_t)handles;
5062 args.points = (uintptr_t)points;
5063 args.timeout_nsec = timeout_nsec;
5064 args.count_handles = num_handles;
5067 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TIMELINE_WAIT, &args);
5072 *first_signaled = args.first_signaled;
5077 drm_public int drmSyncobjQuery(int fd, uint32_t *handles, uint64_t *points,
5078 uint32_t handle_count)
5080 struct drm_syncobj_timeline_array args;
5084 args.handles = (uintptr_t)handles;
5085 args.points = (uintptr_t)points;
5086 args.count_handles = handle_count;
5088 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_QUERY, &args);
5094 drm_public int drmSyncobjQuery2(int fd, uint32_t *handles, uint64_t *points,
5095 uint32_t handle_count, uint32_t flags)
5097 struct drm_syncobj_timeline_array args;
5100 args.handles = (uintptr_t)handles;
5101 args.points = (uintptr_t)points;
5102 args.count_handles = handle_count;
5105 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_QUERY, &args);
5109 drm_public int drmSyncobjTransfer(int fd,
5110 uint32_t dst_handle, uint64_t dst_point,
5111 uint32_t src_handle, uint64_t src_point,
5114 struct drm_syncobj_transfer args;
5118 args.src_handle = src_handle;
5119 args.dst_handle = dst_handle;
5120 args.src_point = src_point;
5121 args.dst_point = dst_point;
5124 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TRANSFER, &args);
5129 drm_public int drmSyncobjEventfd(int fd, uint32_t handle, uint64_t point, int ev_fd,
5132 struct drm_syncobj_eventfd args;
5135 args.handle = handle;
5140 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_EVENTFD, &args);
5144 drmGetFormatModifierFromSimpleTokens(uint64_t modifier)
5148 for (i = 0; i < ARRAY_SIZE(drm_format_modifier_table); i++) {
5149 if (drm_format_modifier_table[i].modifier == modifier)
5150 return strdup(drm_format_modifier_table[i].modifier_name);
5156 /** Retrieves a human-readable representation of a vendor (as a string) from
5157 * the format token modifier
5159 * \param modifier the format modifier token
5160 * \return a char pointer to the human-readable form of the vendor. Caller is
5161 * responsible for freeing it.
5164 drmGetFormatModifierVendor(uint64_t modifier)
5167 uint8_t vendor = fourcc_mod_get_vendor(modifier);
5169 for (i = 0; i < ARRAY_SIZE(drm_format_modifier_vendor_table); i++) {
5170 if (drm_format_modifier_vendor_table[i].vendor == vendor)
5171 return strdup(drm_format_modifier_vendor_table[i].vendor_name);
5177 /** Retrieves a human-readable representation string from a format token
5180 * If the dedicated function was not able to extract a valid name or searching
5181 * the format modifier was not in the table, this function would return NULL.
5183 * \param modifier the token format
5184 * \return a malloc'ed string representation of the modifier. Caller is
5185 * responsible for freeing the string returned.
5189 drmGetFormatModifierName(uint64_t modifier)
5191 uint8_t vendorid = fourcc_mod_get_vendor(modifier);
5192 char *modifier_found = NULL;
5195 for (i = 0; i < ARRAY_SIZE(modifier_format_vendor_table); i++) {
5196 if (modifier_format_vendor_table[i].vendor == vendorid)
5197 modifier_found = modifier_format_vendor_table[i].vendor_cb(modifier);
5200 if (!modifier_found)
5201 return drmGetFormatModifierFromSimpleTokens(modifier);
5203 return modifier_found;
5207 * Get a human-readable name for a DRM FourCC format.
5209 * \param format The format.
5210 * \return A malloc'ed string containing the format name. Caller is responsible
5214 drmGetFormatName(uint32_t format)
5220 be = (format & DRM_FORMAT_BIG_ENDIAN) ? "_BE" : "";
5221 format &= ~DRM_FORMAT_BIG_ENDIAN;
5223 if (format == DRM_FORMAT_INVALID)
5224 return strdup("INVALID");
5226 code[0] = (char) ((format >> 0) & 0xFF);
5227 code[1] = (char) ((format >> 8) & 0xFF);
5228 code[2] = (char) ((format >> 16) & 0xFF);
5229 code[3] = (char) ((format >> 24) & 0xFF);
5232 /* Trim spaces at the end */
5233 for (i = 3; i > 0 && code[i] == ' '; i--)
5236 str_size = strlen(code) + strlen(be) + 1;
5237 str = malloc(str_size);
5241 snprintf(str, str_size, "%s%s", code, be);