1 /**
2 * \file xf86drm.c
3 * User-level interface to DRM device
4 *
5 * \author Rickard E. (Rik) Faith <faith@valinux.com>
6 * \author Kevin E. Martin <martin@valinux.com>
7 */
8
9 /*
10 * Copyright 1999 Precision Insight, Inc., Cedar Park, Texas.
11 * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California.
12 * All Rights Reserved.
13 *
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:
20 *
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
23 * Software.
24 *
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.
32 */
33
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <stdbool.h>
37 #include <unistd.h>
38 #include <string.h>
39 #include <strings.h>
40 #include <ctype.h>
41 #include <dirent.h>
42 #include <stddef.h>
43 #include <fcntl.h>
44 #include <errno.h>
45 #include <limits.h>
46 #include <signal.h>
47 #include <time.h>
48 #include <sys/types.h>
49 #include <sys/stat.h>
50 #define stat_t struct stat
51 #include <sys/ioctl.h>
52 #include <sys/time.h>
53 #include <stdarg.h>
54 #ifdef MAJOR_IN_MKDEV
55 #include <sys/mkdev.h>
56 #endif
57 #ifdef MAJOR_IN_SYSMACROS
58 #include <sys/sysmacros.h>
59 #endif
60 #if HAVE_SYS_SYSCTL_H
61 #include <sys/sysctl.h>
62 #endif
63 #include <math.h>
64 #include <inttypes.h>
65
66 #if defined(__FreeBSD__)
67 #include <sys/param.h>
68 #include <sys/pciio.h>
69 #endif
70
71 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
72
73 /* Not all systems have MAP_FAILED defined */
74 #ifndef MAP_FAILED
75 #define MAP_FAILED ((void *)-1)
76 #endif
77
78 #include "xf86drm.h"
79 #include "libdrm_macros.h"
80 #include "drm_fourcc.h"
81
82 #include "util_math.h"
83
84 #ifdef __DragonFly__
85 #define DRM_MAJOR 145
86 #endif
87
88 #ifdef __NetBSD__
89 #define DRM_MAJOR 34
90 #endif
91
92 #ifdef __OpenBSD__
93 #ifdef __i386__
94 #define DRM_MAJOR 88
95 #else
96 #define DRM_MAJOR 87
97 #endif
98 #endif /* __OpenBSD__ */
99
100 #ifndef DRM_MAJOR
101 #define DRM_MAJOR 226 /* Linux */
102 #endif
103
104 #if defined(__OpenBSD__) || defined(__DragonFly__)
105 struct drm_pciinfo {
106 uint16_t domain;
107 uint8_t bus;
108 uint8_t dev;
109 uint8_t func;
110 uint16_t vendor_id;
111 uint16_t device_id;
112 uint16_t subvendor_id;
113 uint16_t subdevice_id;
114 uint8_t revision_id;
115 };
116
117 #define DRM_IOCTL_GET_PCIINFO DRM_IOR(0x15, struct drm_pciinfo)
118 #endif
119
120 #define DRM_MSG_VERBOSITY 3
121
122 #define memclear(s) memset(&s, 0, sizeof(s))
123
124 static drmServerInfoPtr drm_server_info;
125
126 static bool drmNodeIsDRM(int maj, int min);
127 static char *drmGetMinorNameForFD(int fd, int type);
128
129 #define DRM_MODIFIER(v, f, f_name) \
130 .modifier = DRM_FORMAT_MOD_##v ## _ ##f, \
131 .modifier_name = #f_name
132
133 #define DRM_MODIFIER_INVALID(v, f_name) \
134 .modifier = DRM_FORMAT_MOD_INVALID, .modifier_name = #f_name
135
136 #define DRM_MODIFIER_LINEAR(v, f_name) \
137 .modifier = DRM_FORMAT_MOD_LINEAR, .modifier_name = #f_name
138
139 /* Intel is abit special as the format doesn't follow other vendors naming
140 * scheme */
141 #define DRM_MODIFIER_INTEL(f, f_name) \
142 .modifier = I915_FORMAT_MOD_##f, .modifier_name = #f_name
143
144 struct drmFormatModifierInfo {
145 uint64_t modifier;
146 const char *modifier_name;
147 };
148
149 struct drmFormatModifierVendorInfo {
150 uint8_t vendor;
151 const char *vendor_name;
152 };
153
154 #include "generated_static_table_fourcc.h"
155
156 struct drmVendorInfo {
157 uint8_t vendor;
158 char *(*vendor_cb)(uint64_t modifier);
159 };
160
161 struct drmFormatVendorModifierInfo {
162 uint64_t modifier;
163 const char *modifier_name;
164 };
165
166 static char *
167 drmGetFormatModifierNameFromArm(uint64_t modifier);
168
169 static char *
170 drmGetFormatModifierNameFromNvidia(uint64_t modifier);
171
172 static char *
173 drmGetFormatModifierNameFromAmd(uint64_t modifier);
174
175 static char *
176 drmGetFormatModifierNameFromAmlogic(uint64_t modifier);
177
178 static char *
179 drmGetFormatModifierNameFromVivante(uint64_t modifier);
180
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 },
187 };
188
189 #ifndef AFBC_FORMAT_MOD_MODE_VALUE_MASK
190 #define AFBC_FORMAT_MOD_MODE_VALUE_MASK 0x000fffffffffffffULL
191 #endif
192
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" },
203 };
204
is_x_t_amd_gfx9_tile(uint64_t tile)205 static bool is_x_t_amd_gfx9_tile(uint64_t tile)
206 {
207 switch (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:
211 return true;
212 }
213
214 return false;
215 }
216
217 static bool
drmGetAfbcFormatModifierNameFromArm(uint64_t modifier,FILE * fp)218 drmGetAfbcFormatModifierNameFromArm(uint64_t modifier, FILE *fp)
219 {
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;
222
223 const char *block = NULL;
224 const char *mode = NULL;
225 bool did_print_mode = false;
226
227 /* add block, can only have a (single) block */
228 switch (block_size) {
229 case AFBC_FORMAT_MOD_BLOCK_SIZE_16x16:
230 block = "16x16";
231 break;
232 case AFBC_FORMAT_MOD_BLOCK_SIZE_32x8:
233 block = "32x8";
234 break;
235 case AFBC_FORMAT_MOD_BLOCK_SIZE_64x4:
236 block = "64x4";
237 break;
238 case AFBC_FORMAT_MOD_BLOCK_SIZE_32x8_64x4:
239 block = "32x8_64x4";
240 break;
241 }
242
243 if (!block) {
244 return false;
245 }
246
247 fprintf(fp, "BLOCK_SIZE=%s,", block);
248
249 /* add mode */
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;
256 } else {
257 fprintf(fp, "|%s", mode);
258 }
259 }
260 }
261
262 return true;
263 }
264
265 static bool
drmGetAfrcFormatModifierNameFromArm(uint64_t modifier,FILE * fp)266 drmGetAfrcFormatModifierNameFromArm(uint64_t modifier, FILE *fp)
267 {
268 bool scan_layout;
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;
273
274 switch (coding_unit_block) {
275 case AFRC_FORMAT_MOD_CU_SIZE_16:
276 coding_unit_size = "CU_16";
277 break;
278 case AFRC_FORMAT_MOD_CU_SIZE_24:
279 coding_unit_size = "CU_24";
280 break;
281 case AFRC_FORMAT_MOD_CU_SIZE_32:
282 coding_unit_size = "CU_32";
283 break;
284 }
285
286 if (!coding_unit_size) {
287 if (i == 0) {
288 return false;
289 }
290 break;
291 }
292
293 if (i == 0) {
294 fprintf(fp, "P0=%s,", coding_unit_size);
295 } else {
296 fprintf(fp, "P12=%s,", coding_unit_size);
297 }
298 }
299
300 scan_layout =
301 (modifier & AFRC_FORMAT_MOD_LAYOUT_SCAN) == AFRC_FORMAT_MOD_LAYOUT_SCAN;
302 if (scan_layout) {
303 fprintf(fp, "SCAN");
304 } else {
305 fprintf(fp, "ROT");
306 }
307 return true;
308 }
309
310 static char *
drmGetFormatModifierNameFromArm(uint64_t modifier)311 drmGetFormatModifierNameFromArm(uint64_t modifier)
312 {
313 uint64_t type = (modifier >> 52) & 0xf;
314
315 FILE *fp;
316 size_t size = 0;
317 char *modifier_name = NULL;
318 bool result = false;
319
320 fp = open_memstream(&modifier_name, &size);
321 if (!fp)
322 return NULL;
323
324 switch (type) {
325 case DRM_FORMAT_MOD_ARM_TYPE_AFBC:
326 result = drmGetAfbcFormatModifierNameFromArm(modifier, fp);
327 break;
328 case DRM_FORMAT_MOD_ARM_TYPE_AFRC:
329 result = drmGetAfrcFormatModifierNameFromArm(modifier, fp);
330 break;
331 /* misc type is already handled by the static table */
332 case DRM_FORMAT_MOD_ARM_TYPE_MISC:
333 default:
334 result = false;
335 break;
336 }
337
338 fclose(fp);
339 if (!result) {
340 free(modifier_name);
341 return NULL;
342 }
343
344 return modifier_name;
345 }
346
347 static char *
drmGetFormatModifierNameFromNvidia(uint64_t modifier)348 drmGetFormatModifierNameFromNvidia(uint64_t modifier)
349 {
350 uint64_t height, kind, gen, sector, compression;
351
352 height = modifier & 0xf;
353 kind = (modifier >> 12) & 0xff;
354
355 gen = (modifier >> 20) & 0x3;
356 sector = (modifier >> 22) & 0x1;
357 compression = (modifier >> 23) & 0x7;
358
359 /* just in case there could other simpler modifiers, not yet added, avoid
360 * testing against TEGRA_TILE */
361 if ((modifier & 0x10) == 0x10) {
362 char *mod_nvidia;
363 asprintf(&mod_nvidia, "BLOCK_LINEAR_2D,HEIGHT=%"PRIu64",KIND=%"PRIu64","
364 "GEN=%"PRIu64",SECTOR=%"PRIu64",COMPRESSION=%"PRIu64"", height,
365 kind, gen, sector, compression);
366 return mod_nvidia;
367 }
368
369 return NULL;
370 }
371
372 static void
drmGetFormatModifierNameFromAmdDcc(uint64_t modifier,FILE * fp)373 drmGetFormatModifierNameFromAmdDcc(uint64_t modifier, FILE *fp)
374 {
375 uint64_t dcc_max_compressed_block =
376 AMD_FMT_MOD_GET(DCC_MAX_COMPRESSED_BLOCK, modifier);
377 uint64_t dcc_retile = AMD_FMT_MOD_GET(DCC_RETILE, modifier);
378
379 const char *dcc_max_compressed_block_str = NULL;
380
381 fprintf(fp, ",DCC");
382
383 if (dcc_retile)
384 fprintf(fp, ",DCC_RETILE");
385
386 if (!dcc_retile && AMD_FMT_MOD_GET(DCC_PIPE_ALIGN, modifier))
387 fprintf(fp, ",DCC_PIPE_ALIGN");
388
389 if (AMD_FMT_MOD_GET(DCC_INDEPENDENT_64B, modifier))
390 fprintf(fp, ",DCC_INDEPENDENT_64B");
391
392 if (AMD_FMT_MOD_GET(DCC_INDEPENDENT_128B, modifier))
393 fprintf(fp, ",DCC_INDEPENDENT_128B");
394
395 switch (dcc_max_compressed_block) {
396 case AMD_FMT_MOD_DCC_BLOCK_64B:
397 dcc_max_compressed_block_str = "64B";
398 break;
399 case AMD_FMT_MOD_DCC_BLOCK_128B:
400 dcc_max_compressed_block_str = "128B";
401 break;
402 case AMD_FMT_MOD_DCC_BLOCK_256B:
403 dcc_max_compressed_block_str = "256B";
404 break;
405 }
406
407 if (dcc_max_compressed_block_str)
408 fprintf(fp, ",DCC_MAX_COMPRESSED_BLOCK=%s",
409 dcc_max_compressed_block_str);
410
411 if (AMD_FMT_MOD_GET(DCC_CONSTANT_ENCODE, modifier))
412 fprintf(fp, ",DCC_CONSTANT_ENCODE");
413 }
414
415 static void
drmGetFormatModifierNameFromAmdTile(uint64_t modifier,FILE * fp)416 drmGetFormatModifierNameFromAmdTile(uint64_t modifier, FILE *fp)
417 {
418 uint64_t pipe_xor_bits, bank_xor_bits, packers, rb;
419 uint64_t pipe, pipe_align, dcc, dcc_retile, tile_version;
420
421 pipe_align = AMD_FMT_MOD_GET(DCC_PIPE_ALIGN, modifier);
422 pipe_xor_bits = AMD_FMT_MOD_GET(PIPE_XOR_BITS, modifier);
423 dcc = AMD_FMT_MOD_GET(DCC, modifier);
424 dcc_retile = AMD_FMT_MOD_GET(DCC_RETILE, modifier);
425 tile_version = AMD_FMT_MOD_GET(TILE_VERSION, modifier);
426
427 fprintf(fp, ",PIPE_XOR_BITS=%"PRIu64, pipe_xor_bits);
428
429 if (tile_version == AMD_FMT_MOD_TILE_VER_GFX9) {
430 bank_xor_bits = AMD_FMT_MOD_GET(BANK_XOR_BITS, modifier);
431 fprintf(fp, ",BANK_XOR_BITS=%"PRIu64, bank_xor_bits);
432 }
433
434 if (tile_version == AMD_FMT_MOD_TILE_VER_GFX10_RBPLUS) {
435 packers = AMD_FMT_MOD_GET(PACKERS, modifier);
436 fprintf(fp, ",PACKERS=%"PRIu64, packers);
437 }
438
439 if (dcc && tile_version == AMD_FMT_MOD_TILE_VER_GFX9) {
440 rb = AMD_FMT_MOD_GET(RB, modifier);
441 fprintf(fp, ",RB=%"PRIu64, rb);
442 }
443
444 if (dcc && tile_version == AMD_FMT_MOD_TILE_VER_GFX9 &&
445 (dcc_retile || pipe_align)) {
446 pipe = AMD_FMT_MOD_GET(PIPE, modifier);
447 fprintf(fp, ",PIPE_%"PRIu64, pipe);
448 }
449 }
450
451 static char *
drmGetFormatModifierNameFromAmd(uint64_t modifier)452 drmGetFormatModifierNameFromAmd(uint64_t modifier)
453 {
454 uint64_t tile, tile_version, dcc;
455 FILE *fp;
456 char *mod_amd = NULL;
457 size_t size = 0;
458
459 const char *str_tile = NULL;
460 const char *str_tile_version = NULL;
461
462 tile = AMD_FMT_MOD_GET(TILE, modifier);
463 tile_version = AMD_FMT_MOD_GET(TILE_VERSION, modifier);
464 dcc = AMD_FMT_MOD_GET(DCC, modifier);
465
466 fp = open_memstream(&mod_amd, &size);
467 if (!fp)
468 return NULL;
469
470 /* add tile */
471 switch (tile_version) {
472 case AMD_FMT_MOD_TILE_VER_GFX9:
473 str_tile_version = "GFX9";
474 break;
475 case AMD_FMT_MOD_TILE_VER_GFX10:
476 str_tile_version = "GFX10";
477 break;
478 case AMD_FMT_MOD_TILE_VER_GFX10_RBPLUS:
479 str_tile_version = "GFX10_RBPLUS";
480 break;
481 case AMD_FMT_MOD_TILE_VER_GFX11:
482 str_tile_version = "GFX11";
483 break;
484 }
485
486 if (str_tile_version) {
487 fprintf(fp, "%s", str_tile_version);
488 } else {
489 fclose(fp);
490 free(mod_amd);
491 return NULL;
492 }
493
494 /* add tile str */
495 switch (tile) {
496 case AMD_FMT_MOD_TILE_GFX9_64K_S:
497 str_tile = "GFX9_64K_S";
498 break;
499 case AMD_FMT_MOD_TILE_GFX9_64K_D:
500 str_tile = "GFX9_64K_D";
501 break;
502 case AMD_FMT_MOD_TILE_GFX9_64K_S_X:
503 str_tile = "GFX9_64K_S_X";
504 break;
505 case AMD_FMT_MOD_TILE_GFX9_64K_D_X:
506 str_tile = "GFX9_64K_D_X";
507 break;
508 case AMD_FMT_MOD_TILE_GFX9_64K_R_X:
509 str_tile = "GFX9_64K_R_X";
510 break;
511 case AMD_FMT_MOD_TILE_GFX11_256K_R_X:
512 str_tile = "GFX11_256K_R_X";
513 break;
514 }
515
516 if (str_tile)
517 fprintf(fp, ",%s", str_tile);
518
519 if (dcc)
520 drmGetFormatModifierNameFromAmdDcc(modifier, fp);
521
522 if (tile_version >= AMD_FMT_MOD_TILE_VER_GFX9 && is_x_t_amd_gfx9_tile(tile))
523 drmGetFormatModifierNameFromAmdTile(modifier, fp);
524
525 fclose(fp);
526 return mod_amd;
527 }
528
529 static char *
drmGetFormatModifierNameFromAmlogic(uint64_t modifier)530 drmGetFormatModifierNameFromAmlogic(uint64_t modifier)
531 {
532 uint64_t layout = modifier & 0xff;
533 uint64_t options = (modifier >> 8) & 0xff;
534 char *mod_amlogic = NULL;
535
536 const char *layout_str;
537 const char *opts_str;
538
539 switch (layout) {
540 case AMLOGIC_FBC_LAYOUT_BASIC:
541 layout_str = "BASIC";
542 break;
543 case AMLOGIC_FBC_LAYOUT_SCATTER:
544 layout_str = "SCATTER";
545 break;
546 default:
547 layout_str = "INVALID_LAYOUT";
548 break;
549 }
550
551 if (options & AMLOGIC_FBC_OPTION_MEM_SAVING)
552 opts_str = "MEM_SAVING";
553 else
554 opts_str = "0";
555
556 asprintf(&mod_amlogic, "FBC,LAYOUT=%s,OPTIONS=%s", layout_str, opts_str);
557 return mod_amlogic;
558 }
559
560 static char *
drmGetFormatModifierNameFromVivante(uint64_t modifier)561 drmGetFormatModifierNameFromVivante(uint64_t modifier)
562 {
563 const char *color_tiling, *tile_status, *compression;
564 char *mod_vivante = NULL;
565
566 switch (modifier & VIVANTE_MOD_TS_MASK) {
567 case 0:
568 tile_status = "";
569 break;
570 case VIVANTE_MOD_TS_64_4:
571 tile_status = ",TS=64B_4";
572 break;
573 case VIVANTE_MOD_TS_64_2:
574 tile_status = ",TS=64B_2";
575 break;
576 case VIVANTE_MOD_TS_128_4:
577 tile_status = ",TS=128B_4";
578 break;
579 case VIVANTE_MOD_TS_256_4:
580 tile_status = ",TS=256B_4";
581 break;
582 default:
583 tile_status = ",TS=UNKNOWN";
584 break;
585 }
586
587 switch (modifier & VIVANTE_MOD_COMP_MASK) {
588 case 0:
589 compression = "";
590 break;
591 case VIVANTE_MOD_COMP_DEC400:
592 compression = ",COMP=DEC400";
593 break;
594 default:
595 compression = ",COMP=UNKNOWN";
596 break;
597 }
598
599 switch (modifier & ~VIVANTE_MOD_EXT_MASK) {
600 case 0:
601 color_tiling = "LINEAR";
602 break;
603 case DRM_FORMAT_MOD_VIVANTE_TILED:
604 color_tiling = "TILED";
605 break;
606 case DRM_FORMAT_MOD_VIVANTE_SUPER_TILED:
607 color_tiling = "SUPER_TILED";
608 break;
609 case DRM_FORMAT_MOD_VIVANTE_SPLIT_TILED:
610 color_tiling = "SPLIT_TILED";
611 break;
612 case DRM_FORMAT_MOD_VIVANTE_SPLIT_SUPER_TILED:
613 color_tiling = "SPLIT_SUPER_TILED";
614 break;
615 default:
616 color_tiling = "UNKNOWN";
617 break;
618 }
619
620 asprintf(&mod_vivante, "%s%s%s", color_tiling, tile_status, compression);
621 return mod_vivante;
622 }
623
log2_int(unsigned x)624 static unsigned log2_int(unsigned x)
625 {
626 unsigned l;
627
628 if (x < 2) {
629 return 0;
630 }
631 for (l = 2; ; l++) {
632 if ((unsigned)(1 << l) > x) {
633 return l - 1;
634 }
635 }
636 return 0;
637 }
638
639
drmSetServerInfo(drmServerInfoPtr info)640 drm_public void drmSetServerInfo(drmServerInfoPtr info)
641 {
642 drm_server_info = info;
643 }
644
645 /**
646 * Output a message to stderr.
647 *
648 * \param format printf() like format string.
649 *
650 * \internal
651 * This function is a wrapper around vfprintf().
652 */
653
654 static int DRM_PRINTFLIKE(1, 0)
drmDebugPrint(const char * format,va_list ap)655 drmDebugPrint(const char *format, va_list ap)
656 {
657 return vfprintf(stderr, format, ap);
658 }
659
660 drm_public void
drmMsg(const char * format,...)661 drmMsg(const char *format, ...)
662 {
663 va_list ap;
664 const char *env;
665 if (((env = getenv("LIBGL_DEBUG")) && strstr(env, "verbose")) ||
666 (drm_server_info && drm_server_info->debug_print))
667 {
668 va_start(ap, format);
669 if (drm_server_info) {
670 drm_server_info->debug_print(format,ap);
671 } else {
672 drmDebugPrint(format, ap);
673 }
674 va_end(ap);
675 }
676 }
677
678 static void *drmHashTable = NULL; /* Context switch callbacks */
679
drmGetHashTable(void)680 drm_public void *drmGetHashTable(void)
681 {
682 return drmHashTable;
683 }
684
drmMalloc(int size)685 drm_public void *drmMalloc(int size)
686 {
687 return calloc(1, size);
688 }
689
drmFree(void * pt)690 drm_public void drmFree(void *pt)
691 {
692 free(pt);
693 }
694
695 /**
696 * Call ioctl, restarting if it is interrupted
697 */
698 drm_public int
drmIoctl(int fd,unsigned long request,void * arg)699 drmIoctl(int fd, unsigned long request, void *arg)
700 {
701 int ret;
702
703 do {
704 ret = ioctl(fd, request, arg);
705 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
706 return ret;
707 }
708
drmGetKeyFromFd(int fd)709 static unsigned long drmGetKeyFromFd(int fd)
710 {
711 stat_t st;
712
713 st.st_rdev = 0;
714 fstat(fd, &st);
715 return st.st_rdev;
716 }
717
drmGetEntry(int fd)718 drm_public drmHashEntry *drmGetEntry(int fd)
719 {
720 unsigned long key = drmGetKeyFromFd(fd);
721 void *value;
722 drmHashEntry *entry;
723
724 if (!drmHashTable)
725 drmHashTable = drmHashCreate();
726
727 if (drmHashLookup(drmHashTable, key, &value)) {
728 entry = drmMalloc(sizeof(*entry));
729 entry->fd = fd;
730 entry->f = NULL;
731 entry->tagTable = drmHashCreate();
732 drmHashInsert(drmHashTable, key, entry);
733 } else {
734 entry = value;
735 }
736 return entry;
737 }
738
739 /**
740 * Compare two busid strings
741 *
742 * \param first
743 * \param second
744 *
745 * \return 1 if matched.
746 *
747 * \internal
748 * This function compares two bus ID strings. It understands the older
749 * PCI:b:d:f format and the newer pci:oooo:bb:dd.f format. In the format, o is
750 * domain, b is bus, d is device, f is function.
751 */
drmMatchBusID(const char * id1,const char * id2,int pci_domain_ok)752 static int drmMatchBusID(const char *id1, const char *id2, int pci_domain_ok)
753 {
754 /* First, check if the IDs are exactly the same */
755 if (strcasecmp(id1, id2) == 0)
756 return 1;
757
758 /* Try to match old/new-style PCI bus IDs. */
759 if (strncasecmp(id1, "pci", 3) == 0) {
760 unsigned int o1, b1, d1, f1;
761 unsigned int o2, b2, d2, f2;
762 int ret;
763
764 ret = sscanf(id1, "pci:%04x:%02x:%02x.%u", &o1, &b1, &d1, &f1);
765 if (ret != 4) {
766 o1 = 0;
767 ret = sscanf(id1, "PCI:%u:%u:%u", &b1, &d1, &f1);
768 if (ret != 3)
769 return 0;
770 }
771
772 ret = sscanf(id2, "pci:%04x:%02x:%02x.%u", &o2, &b2, &d2, &f2);
773 if (ret != 4) {
774 o2 = 0;
775 ret = sscanf(id2, "PCI:%u:%u:%u", &b2, &d2, &f2);
776 if (ret != 3)
777 return 0;
778 }
779
780 /* If domains aren't properly supported by the kernel interface,
781 * just ignore them, which sucks less than picking a totally random
782 * card with "open by name"
783 */
784 if (!pci_domain_ok)
785 o1 = o2 = 0;
786
787 if ((o1 != o2) || (b1 != b2) || (d1 != d2) || (f1 != f2))
788 return 0;
789 else
790 return 1;
791 }
792 return 0;
793 }
794
795 /**
796 * Handles error checking for chown call.
797 *
798 * \param path to file.
799 * \param id of the new owner.
800 * \param id of the new group.
801 *
802 * \return zero if success or -1 if failure.
803 *
804 * \internal
805 * Checks for failure. If failure was caused by signal call chown again.
806 * If any other failure happened then it will output error message using
807 * drmMsg() call.
808 */
809 #if !UDEV
chown_check_return(const char * path,uid_t owner,gid_t group)810 static int chown_check_return(const char *path, uid_t owner, gid_t group)
811 {
812 int rv;
813
814 do {
815 rv = chown(path, owner, group);
816 } while (rv != 0 && errno == EINTR);
817
818 if (rv == 0)
819 return 0;
820
821 drmMsg("Failed to change owner or group for file %s! %d: %s\n",
822 path, errno, strerror(errno));
823 return -1;
824 }
825 #endif
826
drmGetDeviceName(int type)827 static const char *drmGetDeviceName(int type)
828 {
829 switch (type) {
830 case DRM_NODE_PRIMARY:
831 return DRM_DEV_NAME;
832 case DRM_NODE_RENDER:
833 return DRM_RENDER_DEV_NAME;
834 }
835 return NULL;
836 }
837
838 /**
839 * Open the DRM device, creating it if necessary.
840 *
841 * \param dev major and minor numbers of the device.
842 * \param minor minor number of the device.
843 *
844 * \return a file descriptor on success, or a negative value on error.
845 *
846 * \internal
847 * Assembles the device name from \p minor and opens it, creating the device
848 * special file node with the major and minor numbers specified by \p dev and
849 * parent directory if necessary and was called by root.
850 */
drmOpenDevice(dev_t dev,int minor,int type)851 static int drmOpenDevice(dev_t dev, int minor, int type)
852 {
853 stat_t st;
854 const char *dev_name = drmGetDeviceName(type);
855 char buf[DRM_NODE_NAME_MAX];
856 int fd;
857 mode_t devmode = DRM_DEV_MODE, serv_mode;
858 gid_t serv_group;
859 #if !UDEV
860 int isroot = !geteuid();
861 uid_t user = DRM_DEV_UID;
862 gid_t group = DRM_DEV_GID;
863 #endif
864
865 if (!dev_name)
866 return -EINVAL;
867
868 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
869 drmMsg("drmOpenDevice: node name is %s\n", buf);
870
871 if (drm_server_info && drm_server_info->get_perms) {
872 drm_server_info->get_perms(&serv_group, &serv_mode);
873 devmode = serv_mode ? serv_mode : DRM_DEV_MODE;
874 devmode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
875 }
876
877 #if !UDEV
878 if (stat(DRM_DIR_NAME, &st)) {
879 if (!isroot)
880 return DRM_ERR_NOT_ROOT;
881 mkdir(DRM_DIR_NAME, DRM_DEV_DIRMODE);
882 chown_check_return(DRM_DIR_NAME, 0, 0); /* root:root */
883 chmod(DRM_DIR_NAME, DRM_DEV_DIRMODE);
884 }
885
886 /* Check if the device node exists and create it if necessary. */
887 if (stat(buf, &st)) {
888 if (!isroot)
889 return DRM_ERR_NOT_ROOT;
890 remove(buf);
891 mknod(buf, S_IFCHR | devmode, dev);
892 }
893
894 if (drm_server_info && drm_server_info->get_perms) {
895 group = ((int)serv_group >= 0) ? serv_group : DRM_DEV_GID;
896 chown_check_return(buf, user, group);
897 chmod(buf, devmode);
898 }
899 #else
900 /* if we modprobed then wait for udev */
901 {
902 int udev_count = 0;
903 wait_for_udev:
904 if (stat(DRM_DIR_NAME, &st)) {
905 usleep(20);
906 udev_count++;
907
908 if (udev_count == 50)
909 return -1;
910 goto wait_for_udev;
911 }
912
913 if (stat(buf, &st)) {
914 usleep(20);
915 udev_count++;
916
917 if (udev_count == 50)
918 return -1;
919 goto wait_for_udev;
920 }
921 }
922 #endif
923
924 fd = open(buf, O_RDWR | O_CLOEXEC);
925 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
926 fd, fd < 0 ? strerror(errno) : "OK");
927 if (fd >= 0)
928 return fd;
929
930 #if !UDEV
931 /* Check if the device node is not what we expect it to be, and recreate it
932 * and try again if so.
933 */
934 if (st.st_rdev != dev) {
935 if (!isroot)
936 return DRM_ERR_NOT_ROOT;
937 remove(buf);
938 mknod(buf, S_IFCHR | devmode, dev);
939 if (drm_server_info && drm_server_info->get_perms) {
940 chown_check_return(buf, user, group);
941 chmod(buf, devmode);
942 }
943 }
944 fd = open(buf, O_RDWR | O_CLOEXEC);
945 drmMsg("drmOpenDevice: open result is %d, (%s)\n",
946 fd, fd < 0 ? strerror(errno) : "OK");
947 if (fd >= 0)
948 return fd;
949
950 drmMsg("drmOpenDevice: Open failed\n");
951 remove(buf);
952 #endif
953 return -errno;
954 }
955
956
957 /**
958 * Open the DRM device
959 *
960 * \param minor device minor number.
961 * \param create allow to create the device if set.
962 *
963 * \return a file descriptor on success, or a negative value on error.
964 *
965 * \internal
966 * Calls drmOpenDevice() if \p create is set, otherwise assembles the device
967 * name from \p minor and opens it.
968 */
drmOpenMinor(int minor,int create,int type)969 static int drmOpenMinor(int minor, int create, int type)
970 {
971 int fd;
972 char buf[DRM_NODE_NAME_MAX];
973 const char *dev_name = drmGetDeviceName(type);
974
975 if (create)
976 return drmOpenDevice(makedev(DRM_MAJOR, minor), minor, type);
977
978 if (!dev_name)
979 return -EINVAL;
980
981 sprintf(buf, dev_name, DRM_DIR_NAME, minor);
982 if ((fd = open(buf, O_RDWR | O_CLOEXEC)) >= 0)
983 return fd;
984 return -errno;
985 }
986
987
988 /**
989 * Determine whether the DRM kernel driver has been loaded.
990 *
991 * \return 1 if the DRM driver is loaded, 0 otherwise.
992 *
993 * \internal
994 * Determine the presence of the kernel driver by attempting to open the 0
995 * minor and get version information. For backward compatibility with older
996 * Linux implementations, /proc/dri is also checked.
997 */
drmAvailable(void)998 drm_public int drmAvailable(void)
999 {
1000 drmVersionPtr version;
1001 int retval = 0;
1002 int fd;
1003
1004 if ((fd = drmOpenMinor(0, 1, DRM_NODE_PRIMARY)) < 0) {
1005 #ifdef __linux__
1006 /* Try proc for backward Linux compatibility */
1007 if (!access("/proc/dri/0", R_OK))
1008 return 1;
1009 #endif
1010 return 0;
1011 }
1012
1013 if ((version = drmGetVersion(fd))) {
1014 retval = 1;
1015 drmFreeVersion(version);
1016 }
1017 close(fd);
1018
1019 return retval;
1020 }
1021
drmGetMinorBase(int type)1022 static int drmGetMinorBase(int type)
1023 {
1024 switch (type) {
1025 case DRM_NODE_PRIMARY:
1026 return 0;
1027 case DRM_NODE_RENDER:
1028 return 128;
1029 default:
1030 return -1;
1031 };
1032 }
1033
drmGetMinorType(int major,int minor)1034 static int drmGetMinorType(int major, int minor)
1035 {
1036 #ifdef __FreeBSD__
1037 char name[SPECNAMELEN];
1038 int id;
1039
1040 if (!devname_r(makedev(major, minor), S_IFCHR, name, sizeof(name)))
1041 return -1;
1042
1043 if (sscanf(name, "drm/%d", &id) != 1) {
1044 // If not in /dev/drm/ we have the type in the name
1045 if (sscanf(name, "dri/card%d\n", &id) >= 1)
1046 return DRM_NODE_PRIMARY;
1047 else if (sscanf(name, "dri/renderD%d\n", &id) >= 1)
1048 return DRM_NODE_RENDER;
1049 return -1;
1050 }
1051
1052 minor = id;
1053 #endif
1054 char path[DRM_NODE_NAME_MAX];
1055 const char *dev_name;
1056 int i;
1057
1058 for (i = DRM_NODE_PRIMARY; i < DRM_NODE_MAX; i++) {
1059 dev_name = drmGetDeviceName(i);
1060 if (!dev_name)
1061 continue;
1062 snprintf(path, sizeof(path), dev_name, DRM_DIR_NAME, minor);
1063 if (!access(path, F_OK))
1064 return i;
1065 }
1066
1067 return -1;
1068 }
1069
drmGetMinorName(int type)1070 static const char *drmGetMinorName(int type)
1071 {
1072 switch (type) {
1073 case DRM_NODE_PRIMARY:
1074 return DRM_PRIMARY_MINOR_NAME;
1075 case DRM_NODE_RENDER:
1076 return DRM_RENDER_MINOR_NAME;
1077 default:
1078 return NULL;
1079 }
1080 }
1081
1082 /**
1083 * Open the device by bus ID.
1084 *
1085 * \param busid bus ID.
1086 * \param type device node type.
1087 *
1088 * \return a file descriptor on success, or a negative value on error.
1089 *
1090 * \internal
1091 * This function attempts to open every possible minor (up to DRM_MAX_MINOR),
1092 * comparing the device bus ID with the one supplied.
1093 *
1094 * \sa drmOpenMinor() and drmGetBusid().
1095 */
drmOpenByBusid(const char * busid,int type)1096 static int drmOpenByBusid(const char *busid, int type)
1097 {
1098 int i, pci_domain_ok = 1;
1099 int fd;
1100 const char *buf;
1101 drmSetVersion sv;
1102 int base = drmGetMinorBase(type);
1103
1104 if (base < 0)
1105 return -1;
1106
1107 drmMsg("drmOpenByBusid: Searching for BusID %s\n", busid);
1108 for (i = base; i < base + DRM_MAX_MINOR; i++) {
1109 fd = drmOpenMinor(i, 1, type);
1110 drmMsg("drmOpenByBusid: drmOpenMinor returns %d\n", fd);
1111 if (fd >= 0) {
1112 /* We need to try for 1.4 first for proper PCI domain support
1113 * and if that fails, we know the kernel is busted
1114 */
1115 sv.drm_di_major = 1;
1116 sv.drm_di_minor = 4;
1117 sv.drm_dd_major = -1; /* Don't care */
1118 sv.drm_dd_minor = -1; /* Don't care */
1119 if (drmSetInterfaceVersion(fd, &sv)) {
1120 #ifndef __alpha__
1121 pci_domain_ok = 0;
1122 #endif
1123 sv.drm_di_major = 1;
1124 sv.drm_di_minor = 1;
1125 sv.drm_dd_major = -1; /* Don't care */
1126 sv.drm_dd_minor = -1; /* Don't care */
1127 drmMsg("drmOpenByBusid: Interface 1.4 failed, trying 1.1\n");
1128 drmSetInterfaceVersion(fd, &sv);
1129 }
1130 buf = drmGetBusid(fd);
1131 drmMsg("drmOpenByBusid: drmGetBusid reports %s\n", buf);
1132 if (buf && drmMatchBusID(buf, busid, pci_domain_ok)) {
1133 drmFreeBusid(buf);
1134 return fd;
1135 }
1136 if (buf)
1137 drmFreeBusid(buf);
1138 close(fd);
1139 }
1140 }
1141 return -1;
1142 }
1143
1144
1145 /**
1146 * Open the device by name.
1147 *
1148 * \param name driver name.
1149 * \param type the device node type.
1150 *
1151 * \return a file descriptor on success, or a negative value on error.
1152 *
1153 * \internal
1154 * This function opens the first minor number that matches the driver name and
1155 * isn't already in use. If it's in use it then it will already have a bus ID
1156 * assigned.
1157 *
1158 * \sa drmOpenMinor(), drmGetVersion() and drmGetBusid().
1159 */
drmOpenByName(const char * name,int type)1160 static int drmOpenByName(const char *name, int type)
1161 {
1162 int i;
1163 int fd;
1164 drmVersionPtr version;
1165 char * id;
1166 int base = drmGetMinorBase(type);
1167
1168 if (base < 0)
1169 return -1;
1170
1171 /*
1172 * Open the first minor number that matches the driver name and isn't
1173 * already in use. If it's in use it will have a busid assigned already.
1174 */
1175 for (i = base; i < base + DRM_MAX_MINOR; i++) {
1176 if ((fd = drmOpenMinor(i, 1, type)) >= 0) {
1177 if ((version = drmGetVersion(fd))) {
1178 if (!strcmp(version->name, name)) {
1179 drmFreeVersion(version);
1180 id = drmGetBusid(fd);
1181 drmMsg("drmGetBusid returned '%s'\n", id ? id : "NULL");
1182 if (!id || !*id) {
1183 if (id)
1184 drmFreeBusid(id);
1185 return fd;
1186 } else {
1187 drmFreeBusid(id);
1188 }
1189 } else {
1190 drmFreeVersion(version);
1191 }
1192 }
1193 close(fd);
1194 }
1195 }
1196
1197 #ifdef __linux__
1198 /* Backward-compatibility /proc support */
1199 for (i = 0; i < 8; i++) {
1200 char proc_name[64], buf[512];
1201 char *driver, *pt, *devstring;
1202 int retcode;
1203
1204 sprintf(proc_name, "/proc/dri/%d/name", i);
1205 if ((fd = open(proc_name, O_RDONLY)) >= 0) {
1206 retcode = read(fd, buf, sizeof(buf)-1);
1207 close(fd);
1208 if (retcode) {
1209 buf[retcode-1] = '\0';
1210 for (driver = pt = buf; *pt && *pt != ' '; ++pt)
1211 ;
1212 if (*pt) { /* Device is next */
1213 *pt = '\0';
1214 if (!strcmp(driver, name)) { /* Match */
1215 for (devstring = ++pt; *pt && *pt != ' '; ++pt)
1216 ;
1217 if (*pt) { /* Found busid */
1218 return drmOpenByBusid(++pt, type);
1219 } else { /* No busid */
1220 return drmOpenDevice(strtol(devstring, NULL, 0),i, type);
1221 }
1222 }
1223 }
1224 }
1225 }
1226 }
1227 #endif
1228
1229 return -1;
1230 }
1231
1232
1233 /**
1234 * Open the DRM device.
1235 *
1236 * Looks up the specified name and bus ID, and opens the device found. The
1237 * entry in /dev/dri is created if necessary and if called by root.
1238 *
1239 * \param name driver name. Not referenced if bus ID is supplied.
1240 * \param busid bus ID. Zero if not known.
1241 *
1242 * \return a file descriptor on success, or a negative value on error.
1243 *
1244 * \internal
1245 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
1246 * otherwise.
1247 */
drmOpen(const char * name,const char * busid)1248 drm_public int drmOpen(const char *name, const char *busid)
1249 {
1250 return drmOpenWithType(name, busid, DRM_NODE_PRIMARY);
1251 }
1252
1253 /**
1254 * Open the DRM device with specified type.
1255 *
1256 * Looks up the specified name and bus ID, and opens the device found. The
1257 * entry in /dev/dri is created if necessary and if called by root.
1258 *
1259 * \param name driver name. Not referenced if bus ID is supplied.
1260 * \param busid bus ID. Zero if not known.
1261 * \param type the device node type to open, PRIMARY or RENDER
1262 *
1263 * \return a file descriptor on success, or a negative value on error.
1264 *
1265 * \internal
1266 * It calls drmOpenByBusid() if \p busid is specified or drmOpenByName()
1267 * otherwise.
1268 */
drmOpenWithType(const char * name,const char * busid,int type)1269 drm_public int drmOpenWithType(const char *name, const char *busid, int type)
1270 {
1271 if (name != NULL && drm_server_info &&
1272 drm_server_info->load_module && !drmAvailable()) {
1273 /* try to load the kernel module */
1274 if (!drm_server_info->load_module(name)) {
1275 drmMsg("[drm] failed to load kernel module \"%s\"\n", name);
1276 return -1;
1277 }
1278 }
1279
1280 if (busid) {
1281 int fd = drmOpenByBusid(busid, type);
1282 if (fd >= 0)
1283 return fd;
1284 }
1285
1286 if (name)
1287 return drmOpenByName(name, type);
1288
1289 return -1;
1290 }
1291
drmOpenControl(int minor)1292 drm_public int drmOpenControl(int minor)
1293 {
1294 return -EINVAL;
1295 }
1296
drmOpenRender(int minor)1297 drm_public int drmOpenRender(int minor)
1298 {
1299 return drmOpenMinor(minor, 0, DRM_NODE_RENDER);
1300 }
1301
1302 /**
1303 * Free the version information returned by drmGetVersion().
1304 *
1305 * \param v pointer to the version information.
1306 *
1307 * \internal
1308 * It frees the memory pointed by \p %v as well as all the non-null strings
1309 * pointers in it.
1310 */
drmFreeVersion(drmVersionPtr v)1311 drm_public void drmFreeVersion(drmVersionPtr v)
1312 {
1313 if (!v)
1314 return;
1315 drmFree(v->name);
1316 drmFree(v->date);
1317 drmFree(v->desc);
1318 drmFree(v);
1319 }
1320
1321
1322 /**
1323 * Free the non-public version information returned by the kernel.
1324 *
1325 * \param v pointer to the version information.
1326 *
1327 * \internal
1328 * Used by drmGetVersion() to free the memory pointed by \p %v as well as all
1329 * the non-null strings pointers in it.
1330 */
drmFreeKernelVersion(drm_version_t * v)1331 static void drmFreeKernelVersion(drm_version_t *v)
1332 {
1333 if (!v)
1334 return;
1335 drmFree(v->name);
1336 drmFree(v->date);
1337 drmFree(v->desc);
1338 drmFree(v);
1339 }
1340
1341
1342 /**
1343 * Copy version information.
1344 *
1345 * \param d destination pointer.
1346 * \param s source pointer.
1347 *
1348 * \internal
1349 * Used by drmGetVersion() to translate the information returned by the ioctl
1350 * interface in a private structure into the public structure counterpart.
1351 */
drmCopyVersion(drmVersionPtr d,const drm_version_t * s)1352 static void drmCopyVersion(drmVersionPtr d, const drm_version_t *s)
1353 {
1354 d->version_major = s->version_major;
1355 d->version_minor = s->version_minor;
1356 d->version_patchlevel = s->version_patchlevel;
1357 d->name_len = s->name_len;
1358 d->name = strdup(s->name);
1359 d->date_len = s->date_len;
1360 d->date = strdup(s->date);
1361 d->desc_len = s->desc_len;
1362 d->desc = strdup(s->desc);
1363 }
1364
1365
1366 /**
1367 * Query the driver version information.
1368 *
1369 * \param fd file descriptor.
1370 *
1371 * \return pointer to a drmVersion structure which should be freed with
1372 * drmFreeVersion().
1373 *
1374 * \note Similar information is available via /proc/dri.
1375 *
1376 * \internal
1377 * It gets the version information via successive DRM_IOCTL_VERSION ioctls,
1378 * first with zeros to get the string lengths, and then the actually strings.
1379 * It also null-terminates them since they might not be already.
1380 */
drmGetVersion(int fd)1381 drm_public drmVersionPtr drmGetVersion(int fd)
1382 {
1383 drmVersionPtr retval;
1384 drm_version_t *version = drmMalloc(sizeof(*version));
1385
1386 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
1387 drmFreeKernelVersion(version);
1388 return NULL;
1389 }
1390
1391 if (version->name_len)
1392 version->name = drmMalloc(version->name_len + 1);
1393 if (version->date_len)
1394 version->date = drmMalloc(version->date_len + 1);
1395 if (version->desc_len)
1396 version->desc = drmMalloc(version->desc_len + 1);
1397
1398 if (drmIoctl(fd, DRM_IOCTL_VERSION, version)) {
1399 drmMsg("DRM_IOCTL_VERSION: %s\n", strerror(errno));
1400 drmFreeKernelVersion(version);
1401 return NULL;
1402 }
1403
1404 /* The results might not be null-terminated strings, so terminate them. */
1405 if (version->name_len) version->name[version->name_len] = '\0';
1406 if (version->date_len) version->date[version->date_len] = '\0';
1407 if (version->desc_len) version->desc[version->desc_len] = '\0';
1408
1409 retval = drmMalloc(sizeof(*retval));
1410 drmCopyVersion(retval, version);
1411 drmFreeKernelVersion(version);
1412 return retval;
1413 }
1414
1415
1416 /**
1417 * Get version information for the DRM user space library.
1418 *
1419 * This version number is driver independent.
1420 *
1421 * \param fd file descriptor.
1422 *
1423 * \return version information.
1424 *
1425 * \internal
1426 * This function allocates and fills a drm_version structure with a hard coded
1427 * version number.
1428 */
drmGetLibVersion(int fd)1429 drm_public drmVersionPtr drmGetLibVersion(int fd)
1430 {
1431 drm_version_t *version = drmMalloc(sizeof(*version));
1432
1433 /* Version history:
1434 * NOTE THIS MUST NOT GO ABOVE VERSION 1.X due to drivers needing it
1435 * revision 1.0.x = original DRM interface with no drmGetLibVersion
1436 * entry point and many drm<Device> extensions
1437 * revision 1.1.x = added drmCommand entry points for device extensions
1438 * added drmGetLibVersion to identify libdrm.a version
1439 * revision 1.2.x = added drmSetInterfaceVersion
1440 * modified drmOpen to handle both busid and name
1441 * revision 1.3.x = added server + memory manager
1442 */
1443 version->version_major = 1;
1444 version->version_minor = 3;
1445 version->version_patchlevel = 0;
1446
1447 return (drmVersionPtr)version;
1448 }
1449
drmGetCap(int fd,uint64_t capability,uint64_t * value)1450 drm_public int drmGetCap(int fd, uint64_t capability, uint64_t *value)
1451 {
1452 struct drm_get_cap cap;
1453 int ret;
1454
1455 memclear(cap);
1456 cap.capability = capability;
1457
1458 ret = drmIoctl(fd, DRM_IOCTL_GET_CAP, &cap);
1459 if (ret)
1460 return ret;
1461
1462 *value = cap.value;
1463 return 0;
1464 }
1465
drmSetClientCap(int fd,uint64_t capability,uint64_t value)1466 drm_public int drmSetClientCap(int fd, uint64_t capability, uint64_t value)
1467 {
1468 struct drm_set_client_cap cap;
1469
1470 memclear(cap);
1471 cap.capability = capability;
1472 cap.value = value;
1473
1474 return drmIoctl(fd, DRM_IOCTL_SET_CLIENT_CAP, &cap);
1475 }
1476
1477 /**
1478 * Free the bus ID information.
1479 *
1480 * \param busid bus ID information string as given by drmGetBusid().
1481 *
1482 * \internal
1483 * This function is just frees the memory pointed by \p busid.
1484 */
drmFreeBusid(const char * busid)1485 drm_public void drmFreeBusid(const char *busid)
1486 {
1487 drmFree((void *)busid);
1488 }
1489
1490
1491 /**
1492 * Get the bus ID of the device.
1493 *
1494 * \param fd file descriptor.
1495 *
1496 * \return bus ID string.
1497 *
1498 * \internal
1499 * This function gets the bus ID via successive DRM_IOCTL_GET_UNIQUE ioctls to
1500 * get the string length and data, passing the arguments in a drm_unique
1501 * structure.
1502 */
drmGetBusid(int fd)1503 drm_public char *drmGetBusid(int fd)
1504 {
1505 drm_unique_t u;
1506
1507 memclear(u);
1508
1509 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u))
1510 return NULL;
1511 u.unique = drmMalloc(u.unique_len + 1);
1512 if (drmIoctl(fd, DRM_IOCTL_GET_UNIQUE, &u)) {
1513 drmFree(u.unique);
1514 return NULL;
1515 }
1516 u.unique[u.unique_len] = '\0';
1517
1518 return u.unique;
1519 }
1520
1521
1522 /**
1523 * Set the bus ID of the device.
1524 *
1525 * \param fd file descriptor.
1526 * \param busid bus ID string.
1527 *
1528 * \return zero on success, negative on failure.
1529 *
1530 * \internal
1531 * This function is a wrapper around the DRM_IOCTL_SET_UNIQUE ioctl, passing
1532 * the arguments in a drm_unique structure.
1533 */
drmSetBusid(int fd,const char * busid)1534 drm_public int drmSetBusid(int fd, const char *busid)
1535 {
1536 drm_unique_t u;
1537
1538 memclear(u);
1539 u.unique = (char *)busid;
1540 u.unique_len = strlen(busid);
1541
1542 if (drmIoctl(fd, DRM_IOCTL_SET_UNIQUE, &u)) {
1543 return -errno;
1544 }
1545 return 0;
1546 }
1547
drmGetMagic(int fd,drm_magic_t * magic)1548 drm_public int drmGetMagic(int fd, drm_magic_t * magic)
1549 {
1550 drm_auth_t auth;
1551
1552 memclear(auth);
1553
1554 *magic = 0;
1555 if (drmIoctl(fd, DRM_IOCTL_GET_MAGIC, &auth))
1556 return -errno;
1557 *magic = auth.magic;
1558 return 0;
1559 }
1560
drmAuthMagic(int fd,drm_magic_t magic)1561 drm_public int drmAuthMagic(int fd, drm_magic_t magic)
1562 {
1563 drm_auth_t auth;
1564
1565 memclear(auth);
1566 auth.magic = magic;
1567 if (drmIoctl(fd, DRM_IOCTL_AUTH_MAGIC, &auth))
1568 return -errno;
1569 return 0;
1570 }
1571
1572 /**
1573 * Specifies a range of memory that is available for mapping by a
1574 * non-root process.
1575 *
1576 * \param fd file descriptor.
1577 * \param offset usually the physical address. The actual meaning depends of
1578 * the \p type parameter. See below.
1579 * \param size of the memory in bytes.
1580 * \param type type of the memory to be mapped.
1581 * \param flags combination of several flags to modify the function actions.
1582 * \param handle will be set to a value that may be used as the offset
1583 * parameter for mmap().
1584 *
1585 * \return zero on success or a negative value on error.
1586 *
1587 * \par Mapping the frame buffer
1588 * For the frame buffer
1589 * - \p offset will be the physical address of the start of the frame buffer,
1590 * - \p size will be the size of the frame buffer in bytes, and
1591 * - \p type will be DRM_FRAME_BUFFER.
1592 *
1593 * \par
1594 * The area mapped will be uncached. If MTRR support is available in the
1595 * kernel, the frame buffer area will be set to write combining.
1596 *
1597 * \par Mapping the MMIO register area
1598 * For the MMIO register area,
1599 * - \p offset will be the physical address of the start of the register area,
1600 * - \p size will be the size of the register area bytes, and
1601 * - \p type will be DRM_REGISTERS.
1602 * \par
1603 * The area mapped will be uncached.
1604 *
1605 * \par Mapping the SAREA
1606 * For the SAREA,
1607 * - \p offset will be ignored and should be set to zero,
1608 * - \p size will be the desired size of the SAREA in bytes,
1609 * - \p type will be DRM_SHM.
1610 *
1611 * \par
1612 * A shared memory area of the requested size will be created and locked in
1613 * kernel memory. This area may be mapped into client-space by using the handle
1614 * returned.
1615 *
1616 * \note May only be called by root.
1617 *
1618 * \internal
1619 * This function is a wrapper around the DRM_IOCTL_ADD_MAP ioctl, passing
1620 * the arguments in a drm_map structure.
1621 */
drmAddMap(int fd,drm_handle_t offset,drmSize size,drmMapType type,drmMapFlags flags,drm_handle_t * handle)1622 drm_public int drmAddMap(int fd, drm_handle_t offset, drmSize size, drmMapType type,
1623 drmMapFlags flags, drm_handle_t *handle)
1624 {
1625 drm_map_t map;
1626
1627 memclear(map);
1628 map.offset = offset;
1629 map.size = size;
1630 map.type = (enum drm_map_type)type;
1631 map.flags = (enum drm_map_flags)flags;
1632 if (drmIoctl(fd, DRM_IOCTL_ADD_MAP, &map))
1633 return -errno;
1634 if (handle)
1635 *handle = (drm_handle_t)(uintptr_t)map.handle;
1636 return 0;
1637 }
1638
drmRmMap(int fd,drm_handle_t handle)1639 drm_public int drmRmMap(int fd, drm_handle_t handle)
1640 {
1641 drm_map_t map;
1642
1643 memclear(map);
1644 map.handle = (void *)(uintptr_t)handle;
1645
1646 if(drmIoctl(fd, DRM_IOCTL_RM_MAP, &map))
1647 return -errno;
1648 return 0;
1649 }
1650
1651 /**
1652 * Make buffers available for DMA transfers.
1653 *
1654 * \param fd file descriptor.
1655 * \param count number of buffers.
1656 * \param size size of each buffer.
1657 * \param flags buffer allocation flags.
1658 * \param agp_offset offset in the AGP aperture
1659 *
1660 * \return number of buffers allocated, negative on error.
1661 *
1662 * \internal
1663 * This function is a wrapper around DRM_IOCTL_ADD_BUFS ioctl.
1664 *
1665 * \sa drm_buf_desc.
1666 */
drmAddBufs(int fd,int count,int size,drmBufDescFlags flags,int agp_offset)1667 drm_public int drmAddBufs(int fd, int count, int size, drmBufDescFlags flags,
1668 int agp_offset)
1669 {
1670 drm_buf_desc_t request;
1671
1672 memclear(request);
1673 request.count = count;
1674 request.size = size;
1675 request.flags = (int)flags;
1676 request.agp_start = agp_offset;
1677
1678 if (drmIoctl(fd, DRM_IOCTL_ADD_BUFS, &request))
1679 return -errno;
1680 return request.count;
1681 }
1682
drmMarkBufs(int fd,double low,double high)1683 drm_public int drmMarkBufs(int fd, double low, double high)
1684 {
1685 drm_buf_info_t info;
1686 int i;
1687
1688 memclear(info);
1689
1690 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1691 return -EINVAL;
1692
1693 if (!info.count)
1694 return -EINVAL;
1695
1696 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1697 return -ENOMEM;
1698
1699 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1700 int retval = -errno;
1701 drmFree(info.list);
1702 return retval;
1703 }
1704
1705 for (i = 0; i < info.count; i++) {
1706 info.list[i].low_mark = low * info.list[i].count;
1707 info.list[i].high_mark = high * info.list[i].count;
1708 if (drmIoctl(fd, DRM_IOCTL_MARK_BUFS, &info.list[i])) {
1709 int retval = -errno;
1710 drmFree(info.list);
1711 return retval;
1712 }
1713 }
1714 drmFree(info.list);
1715
1716 return 0;
1717 }
1718
1719 /**
1720 * Free buffers.
1721 *
1722 * \param fd file descriptor.
1723 * \param count number of buffers to free.
1724 * \param list list of buffers to be freed.
1725 *
1726 * \return zero on success, or a negative value on failure.
1727 *
1728 * \note This function is primarily used for debugging.
1729 *
1730 * \internal
1731 * This function is a wrapper around the DRM_IOCTL_FREE_BUFS ioctl, passing
1732 * the arguments in a drm_buf_free structure.
1733 */
drmFreeBufs(int fd,int count,int * list)1734 drm_public int drmFreeBufs(int fd, int count, int *list)
1735 {
1736 drm_buf_free_t request;
1737
1738 memclear(request);
1739 request.count = count;
1740 request.list = list;
1741 if (drmIoctl(fd, DRM_IOCTL_FREE_BUFS, &request))
1742 return -errno;
1743 return 0;
1744 }
1745
1746
1747 /**
1748 * Close the device.
1749 *
1750 * \param fd file descriptor.
1751 *
1752 * \internal
1753 * This function closes the file descriptor.
1754 */
drmClose(int fd)1755 drm_public int drmClose(int fd)
1756 {
1757 unsigned long key = drmGetKeyFromFd(fd);
1758 drmHashEntry *entry = drmGetEntry(fd);
1759
1760 drmHashDestroy(entry->tagTable);
1761 entry->fd = 0;
1762 entry->f = NULL;
1763 entry->tagTable = NULL;
1764
1765 drmHashDelete(drmHashTable, key);
1766 drmFree(entry);
1767
1768 return close(fd);
1769 }
1770
1771
1772 /**
1773 * Map a region of memory.
1774 *
1775 * \param fd file descriptor.
1776 * \param handle handle returned by drmAddMap().
1777 * \param size size in bytes. Must match the size used by drmAddMap().
1778 * \param address will contain the user-space virtual address where the mapping
1779 * begins.
1780 *
1781 * \return zero on success, or a negative value on failure.
1782 *
1783 * \internal
1784 * This function is a wrapper for mmap().
1785 */
drmMap(int fd,drm_handle_t handle,drmSize size,drmAddressPtr address)1786 drm_public int drmMap(int fd, drm_handle_t handle, drmSize size,
1787 drmAddressPtr address)
1788 {
1789 static unsigned long pagesize_mask = 0;
1790
1791 if (fd < 0)
1792 return -EINVAL;
1793
1794 if (!pagesize_mask)
1795 pagesize_mask = getpagesize() - 1;
1796
1797 size = (size + pagesize_mask) & ~pagesize_mask;
1798
1799 *address = drm_mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, handle);
1800 if (*address == MAP_FAILED)
1801 return -errno;
1802 return 0;
1803 }
1804
1805
1806 /**
1807 * Unmap mappings obtained with drmMap().
1808 *
1809 * \param address address as given by drmMap().
1810 * \param size size in bytes. Must match the size used by drmMap().
1811 *
1812 * \return zero on success, or a negative value on failure.
1813 *
1814 * \internal
1815 * This function is a wrapper for munmap().
1816 */
drmUnmap(drmAddress address,drmSize size)1817 drm_public int drmUnmap(drmAddress address, drmSize size)
1818 {
1819 return drm_munmap(address, size);
1820 }
1821
drmGetBufInfo(int fd)1822 drm_public drmBufInfoPtr drmGetBufInfo(int fd)
1823 {
1824 drm_buf_info_t info;
1825 drmBufInfoPtr retval;
1826 int i;
1827
1828 memclear(info);
1829
1830 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info))
1831 return NULL;
1832
1833 if (info.count) {
1834 if (!(info.list = drmMalloc(info.count * sizeof(*info.list))))
1835 return NULL;
1836
1837 if (drmIoctl(fd, DRM_IOCTL_INFO_BUFS, &info)) {
1838 drmFree(info.list);
1839 return NULL;
1840 }
1841
1842 retval = drmMalloc(sizeof(*retval));
1843 retval->count = info.count;
1844 if (!(retval->list = drmMalloc(info.count * sizeof(*retval->list)))) {
1845 drmFree(retval);
1846 drmFree(info.list);
1847 return NULL;
1848 }
1849
1850 for (i = 0; i < info.count; i++) {
1851 retval->list[i].count = info.list[i].count;
1852 retval->list[i].size = info.list[i].size;
1853 retval->list[i].low_mark = info.list[i].low_mark;
1854 retval->list[i].high_mark = info.list[i].high_mark;
1855 }
1856 drmFree(info.list);
1857 return retval;
1858 }
1859 return NULL;
1860 }
1861
1862 /**
1863 * Map all DMA buffers into client-virtual space.
1864 *
1865 * \param fd file descriptor.
1866 *
1867 * \return a pointer to a ::drmBufMap structure.
1868 *
1869 * \note The client may not use these buffers until obtaining buffer indices
1870 * with drmDMA().
1871 *
1872 * \internal
1873 * This function calls the DRM_IOCTL_MAP_BUFS ioctl and copies the returned
1874 * information about the buffers in a drm_buf_map structure into the
1875 * client-visible data structures.
1876 */
drmMapBufs(int fd)1877 drm_public drmBufMapPtr drmMapBufs(int fd)
1878 {
1879 drm_buf_map_t bufs;
1880 drmBufMapPtr retval;
1881 int i;
1882
1883 memclear(bufs);
1884 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs))
1885 return NULL;
1886
1887 if (!bufs.count)
1888 return NULL;
1889
1890 if (!(bufs.list = drmMalloc(bufs.count * sizeof(*bufs.list))))
1891 return NULL;
1892
1893 if (drmIoctl(fd, DRM_IOCTL_MAP_BUFS, &bufs)) {
1894 drmFree(bufs.list);
1895 return NULL;
1896 }
1897
1898 retval = drmMalloc(sizeof(*retval));
1899 retval->count = bufs.count;
1900 retval->list = drmMalloc(bufs.count * sizeof(*retval->list));
1901 for (i = 0; i < bufs.count; i++) {
1902 retval->list[i].idx = bufs.list[i].idx;
1903 retval->list[i].total = bufs.list[i].total;
1904 retval->list[i].used = 0;
1905 retval->list[i].address = bufs.list[i].address;
1906 }
1907
1908 drmFree(bufs.list);
1909 return retval;
1910 }
1911
1912
1913 /**
1914 * Unmap buffers allocated with drmMapBufs().
1915 *
1916 * \return zero on success, or negative value on failure.
1917 *
1918 * \internal
1919 * Calls munmap() for every buffer stored in \p bufs and frees the
1920 * memory allocated by drmMapBufs().
1921 */
drmUnmapBufs(drmBufMapPtr bufs)1922 drm_public int drmUnmapBufs(drmBufMapPtr bufs)
1923 {
1924 int i;
1925
1926 for (i = 0; i < bufs->count; i++) {
1927 drm_munmap(bufs->list[i].address, bufs->list[i].total);
1928 }
1929
1930 drmFree(bufs->list);
1931 drmFree(bufs);
1932 return 0;
1933 }
1934
1935
1936 #define DRM_DMA_RETRY 16
1937
1938 /**
1939 * Reserve DMA buffers.
1940 *
1941 * \param fd file descriptor.
1942 * \param request
1943 *
1944 * \return zero on success, or a negative value on failure.
1945 *
1946 * \internal
1947 * Assemble the arguments into a drm_dma structure and keeps issuing the
1948 * DRM_IOCTL_DMA ioctl until success or until maximum number of retries.
1949 */
drmDMA(int fd,drmDMAReqPtr request)1950 drm_public int drmDMA(int fd, drmDMAReqPtr request)
1951 {
1952 drm_dma_t dma;
1953 int ret, i = 0;
1954
1955 dma.context = request->context;
1956 dma.send_count = request->send_count;
1957 dma.send_indices = request->send_list;
1958 dma.send_sizes = request->send_sizes;
1959 dma.flags = (enum drm_dma_flags)request->flags;
1960 dma.request_count = request->request_count;
1961 dma.request_size = request->request_size;
1962 dma.request_indices = request->request_list;
1963 dma.request_sizes = request->request_sizes;
1964 dma.granted_count = 0;
1965
1966 do {
1967 ret = ioctl( fd, DRM_IOCTL_DMA, &dma );
1968 } while ( ret && errno == EAGAIN && i++ < DRM_DMA_RETRY );
1969
1970 if ( ret == 0 ) {
1971 request->granted_count = dma.granted_count;
1972 return 0;
1973 } else {
1974 return -errno;
1975 }
1976 }
1977
1978
1979 /**
1980 * Obtain heavyweight hardware lock.
1981 *
1982 * \param fd file descriptor.
1983 * \param context context.
1984 * \param flags flags that determine the state of the hardware when the function
1985 * returns.
1986 *
1987 * \return always zero.
1988 *
1989 * \internal
1990 * This function translates the arguments into a drm_lock structure and issue
1991 * the DRM_IOCTL_LOCK ioctl until the lock is successfully acquired.
1992 */
drmGetLock(int fd,drm_context_t context,drmLockFlags flags)1993 drm_public int drmGetLock(int fd, drm_context_t context, drmLockFlags flags)
1994 {
1995 drm_lock_t lock;
1996
1997 memclear(lock);
1998 lock.context = context;
1999 lock.flags = 0;
2000 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
2001 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
2002 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
2003 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
2004 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2005 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2006
2007 while (drmIoctl(fd, DRM_IOCTL_LOCK, &lock))
2008 ;
2009 return 0;
2010 }
2011
2012 /**
2013 * Release the hardware lock.
2014 *
2015 * \param fd file descriptor.
2016 * \param context context.
2017 *
2018 * \return zero on success, or a negative value on failure.
2019 *
2020 * \internal
2021 * This function is a wrapper around the DRM_IOCTL_UNLOCK ioctl, passing the
2022 * argument in a drm_lock structure.
2023 */
drmUnlock(int fd,drm_context_t context)2024 drm_public int drmUnlock(int fd, drm_context_t context)
2025 {
2026 drm_lock_t lock;
2027
2028 memclear(lock);
2029 lock.context = context;
2030 return drmIoctl(fd, DRM_IOCTL_UNLOCK, &lock);
2031 }
2032
drmGetReservedContextList(int fd,int * count)2033 drm_public drm_context_t *drmGetReservedContextList(int fd, int *count)
2034 {
2035 drm_ctx_res_t res;
2036 drm_ctx_t *list;
2037 drm_context_t * retval;
2038 int i;
2039
2040 memclear(res);
2041 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
2042 return NULL;
2043
2044 if (!res.count)
2045 return NULL;
2046
2047 if (!(list = drmMalloc(res.count * sizeof(*list))))
2048 return NULL;
2049 if (!(retval = drmMalloc(res.count * sizeof(*retval))))
2050 goto err_free_list;
2051
2052 res.contexts = list;
2053 if (drmIoctl(fd, DRM_IOCTL_RES_CTX, &res))
2054 goto err_free_context;
2055
2056 for (i = 0; i < res.count; i++)
2057 retval[i] = list[i].handle;
2058 drmFree(list);
2059
2060 *count = res.count;
2061 return retval;
2062
2063 err_free_list:
2064 drmFree(list);
2065 err_free_context:
2066 drmFree(retval);
2067 return NULL;
2068 }
2069
drmFreeReservedContextList(drm_context_t * pt)2070 drm_public void drmFreeReservedContextList(drm_context_t *pt)
2071 {
2072 drmFree(pt);
2073 }
2074
2075 /**
2076 * Create context.
2077 *
2078 * Used by the X server during GLXContext initialization. This causes
2079 * per-context kernel-level resources to be allocated.
2080 *
2081 * \param fd file descriptor.
2082 * \param handle is set on success. To be used by the client when requesting DMA
2083 * dispatch with drmDMA().
2084 *
2085 * \return zero on success, or a negative value on failure.
2086 *
2087 * \note May only be called by root.
2088 *
2089 * \internal
2090 * This function is a wrapper around the DRM_IOCTL_ADD_CTX ioctl, passing the
2091 * argument in a drm_ctx structure.
2092 */
drmCreateContext(int fd,drm_context_t * handle)2093 drm_public int drmCreateContext(int fd, drm_context_t *handle)
2094 {
2095 drm_ctx_t ctx;
2096
2097 memclear(ctx);
2098 if (drmIoctl(fd, DRM_IOCTL_ADD_CTX, &ctx))
2099 return -errno;
2100 *handle = ctx.handle;
2101 return 0;
2102 }
2103
drmSwitchToContext(int fd,drm_context_t context)2104 drm_public int drmSwitchToContext(int fd, drm_context_t context)
2105 {
2106 drm_ctx_t ctx;
2107
2108 memclear(ctx);
2109 ctx.handle = context;
2110 if (drmIoctl(fd, DRM_IOCTL_SWITCH_CTX, &ctx))
2111 return -errno;
2112 return 0;
2113 }
2114
drmSetContextFlags(int fd,drm_context_t context,drm_context_tFlags flags)2115 drm_public int drmSetContextFlags(int fd, drm_context_t context,
2116 drm_context_tFlags flags)
2117 {
2118 drm_ctx_t ctx;
2119
2120 /*
2121 * Context preserving means that no context switches are done between DMA
2122 * buffers from one context and the next. This is suitable for use in the
2123 * X server (which promises to maintain hardware context), or in the
2124 * client-side library when buffers are swapped on behalf of two threads.
2125 */
2126 memclear(ctx);
2127 ctx.handle = context;
2128 if (flags & DRM_CONTEXT_PRESERVED)
2129 ctx.flags |= _DRM_CONTEXT_PRESERVED;
2130 if (flags & DRM_CONTEXT_2DONLY)
2131 ctx.flags |= _DRM_CONTEXT_2DONLY;
2132 if (drmIoctl(fd, DRM_IOCTL_MOD_CTX, &ctx))
2133 return -errno;
2134 return 0;
2135 }
2136
drmGetContextFlags(int fd,drm_context_t context,drm_context_tFlagsPtr flags)2137 drm_public int drmGetContextFlags(int fd, drm_context_t context,
2138 drm_context_tFlagsPtr flags)
2139 {
2140 drm_ctx_t ctx;
2141
2142 memclear(ctx);
2143 ctx.handle = context;
2144 if (drmIoctl(fd, DRM_IOCTL_GET_CTX, &ctx))
2145 return -errno;
2146 *flags = 0;
2147 if (ctx.flags & _DRM_CONTEXT_PRESERVED)
2148 *flags |= DRM_CONTEXT_PRESERVED;
2149 if (ctx.flags & _DRM_CONTEXT_2DONLY)
2150 *flags |= DRM_CONTEXT_2DONLY;
2151 return 0;
2152 }
2153
2154 /**
2155 * Destroy context.
2156 *
2157 * Free any kernel-level resources allocated with drmCreateContext() associated
2158 * with the context.
2159 *
2160 * \param fd file descriptor.
2161 * \param handle handle given by drmCreateContext().
2162 *
2163 * \return zero on success, or a negative value on failure.
2164 *
2165 * \note May only be called by root.
2166 *
2167 * \internal
2168 * This function is a wrapper around the DRM_IOCTL_RM_CTX ioctl, passing the
2169 * argument in a drm_ctx structure.
2170 */
drmDestroyContext(int fd,drm_context_t handle)2171 drm_public int drmDestroyContext(int fd, drm_context_t handle)
2172 {
2173 drm_ctx_t ctx;
2174
2175 memclear(ctx);
2176 ctx.handle = handle;
2177 if (drmIoctl(fd, DRM_IOCTL_RM_CTX, &ctx))
2178 return -errno;
2179 return 0;
2180 }
2181
drmCreateDrawable(int fd,drm_drawable_t * handle)2182 drm_public int drmCreateDrawable(int fd, drm_drawable_t *handle)
2183 {
2184 drm_draw_t draw;
2185
2186 memclear(draw);
2187 if (drmIoctl(fd, DRM_IOCTL_ADD_DRAW, &draw))
2188 return -errno;
2189 *handle = draw.handle;
2190 return 0;
2191 }
2192
drmDestroyDrawable(int fd,drm_drawable_t handle)2193 drm_public int drmDestroyDrawable(int fd, drm_drawable_t handle)
2194 {
2195 drm_draw_t draw;
2196
2197 memclear(draw);
2198 draw.handle = handle;
2199 if (drmIoctl(fd, DRM_IOCTL_RM_DRAW, &draw))
2200 return -errno;
2201 return 0;
2202 }
2203
drmUpdateDrawableInfo(int fd,drm_drawable_t handle,drm_drawable_info_type_t type,unsigned int num,void * data)2204 drm_public int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
2205 drm_drawable_info_type_t type,
2206 unsigned int num, void *data)
2207 {
2208 drm_update_draw_t update;
2209
2210 memclear(update);
2211 update.handle = handle;
2212 update.type = type;
2213 update.num = num;
2214 update.data = (unsigned long long)(unsigned long)data;
2215
2216 if (drmIoctl(fd, DRM_IOCTL_UPDATE_DRAW, &update))
2217 return -errno;
2218
2219 return 0;
2220 }
2221
drmCrtcGetSequence(int fd,uint32_t crtcId,uint64_t * sequence,uint64_t * ns)2222 drm_public int drmCrtcGetSequence(int fd, uint32_t crtcId, uint64_t *sequence,
2223 uint64_t *ns)
2224 {
2225 struct drm_crtc_get_sequence get_seq;
2226 int ret;
2227
2228 memclear(get_seq);
2229 get_seq.crtc_id = crtcId;
2230 ret = drmIoctl(fd, DRM_IOCTL_CRTC_GET_SEQUENCE, &get_seq);
2231 if (ret)
2232 return ret;
2233
2234 if (sequence)
2235 *sequence = get_seq.sequence;
2236 if (ns)
2237 *ns = get_seq.sequence_ns;
2238 return 0;
2239 }
2240
drmCrtcQueueSequence(int fd,uint32_t crtcId,uint32_t flags,uint64_t sequence,uint64_t * sequence_queued,uint64_t user_data)2241 drm_public int drmCrtcQueueSequence(int fd, uint32_t crtcId, uint32_t flags,
2242 uint64_t sequence,
2243 uint64_t *sequence_queued,
2244 uint64_t user_data)
2245 {
2246 struct drm_crtc_queue_sequence queue_seq;
2247 int ret;
2248
2249 memclear(queue_seq);
2250 queue_seq.crtc_id = crtcId;
2251 queue_seq.flags = flags;
2252 queue_seq.sequence = sequence;
2253 queue_seq.user_data = user_data;
2254
2255 ret = drmIoctl(fd, DRM_IOCTL_CRTC_QUEUE_SEQUENCE, &queue_seq);
2256 if (ret == 0 && sequence_queued)
2257 *sequence_queued = queue_seq.sequence;
2258
2259 return ret;
2260 }
2261
2262 /**
2263 * Acquire the AGP device.
2264 *
2265 * Must be called before any of the other AGP related calls.
2266 *
2267 * \param fd file descriptor.
2268 *
2269 * \return zero on success, or a negative value on failure.
2270 *
2271 * \internal
2272 * This function is a wrapper around the DRM_IOCTL_AGP_ACQUIRE ioctl.
2273 */
drmAgpAcquire(int fd)2274 drm_public int drmAgpAcquire(int fd)
2275 {
2276 if (drmIoctl(fd, DRM_IOCTL_AGP_ACQUIRE, NULL))
2277 return -errno;
2278 return 0;
2279 }
2280
2281
2282 /**
2283 * Release the AGP device.
2284 *
2285 * \param fd file descriptor.
2286 *
2287 * \return zero on success, or a negative value on failure.
2288 *
2289 * \internal
2290 * This function is a wrapper around the DRM_IOCTL_AGP_RELEASE ioctl.
2291 */
drmAgpRelease(int fd)2292 drm_public int drmAgpRelease(int fd)
2293 {
2294 if (drmIoctl(fd, DRM_IOCTL_AGP_RELEASE, NULL))
2295 return -errno;
2296 return 0;
2297 }
2298
2299
2300 /**
2301 * Set the AGP mode.
2302 *
2303 * \param fd file descriptor.
2304 * \param mode AGP mode.
2305 *
2306 * \return zero on success, or a negative value on failure.
2307 *
2308 * \internal
2309 * This function is a wrapper around the DRM_IOCTL_AGP_ENABLE ioctl, passing the
2310 * argument in a drm_agp_mode structure.
2311 */
drmAgpEnable(int fd,unsigned long mode)2312 drm_public int drmAgpEnable(int fd, unsigned long mode)
2313 {
2314 drm_agp_mode_t m;
2315
2316 memclear(m);
2317 m.mode = mode;
2318 if (drmIoctl(fd, DRM_IOCTL_AGP_ENABLE, &m))
2319 return -errno;
2320 return 0;
2321 }
2322
2323
2324 /**
2325 * Allocate a chunk of AGP memory.
2326 *
2327 * \param fd file descriptor.
2328 * \param size requested memory size in bytes. Will be rounded to page boundary.
2329 * \param type type of memory to allocate.
2330 * \param address if not zero, will be set to the physical address of the
2331 * allocated memory.
2332 * \param handle on success will be set to a handle of the allocated memory.
2333 *
2334 * \return zero on success, or a negative value on failure.
2335 *
2336 * \internal
2337 * This function is a wrapper around the DRM_IOCTL_AGP_ALLOC ioctl, passing the
2338 * arguments in a drm_agp_buffer structure.
2339 */
drmAgpAlloc(int fd,unsigned long size,unsigned long type,unsigned long * address,drm_handle_t * handle)2340 drm_public int drmAgpAlloc(int fd, unsigned long size, unsigned long type,
2341 unsigned long *address, drm_handle_t *handle)
2342 {
2343 drm_agp_buffer_t b;
2344
2345 memclear(b);
2346 *handle = DRM_AGP_NO_HANDLE;
2347 b.size = size;
2348 b.type = type;
2349 if (drmIoctl(fd, DRM_IOCTL_AGP_ALLOC, &b))
2350 return -errno;
2351 if (address != 0UL)
2352 *address = b.physical;
2353 *handle = b.handle;
2354 return 0;
2355 }
2356
2357
2358 /**
2359 * Free a chunk of AGP memory.
2360 *
2361 * \param fd file descriptor.
2362 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
2363 *
2364 * \return zero on success, or a negative value on failure.
2365 *
2366 * \internal
2367 * This function is a wrapper around the DRM_IOCTL_AGP_FREE ioctl, passing the
2368 * argument in a drm_agp_buffer structure.
2369 */
drmAgpFree(int fd,drm_handle_t handle)2370 drm_public int drmAgpFree(int fd, drm_handle_t handle)
2371 {
2372 drm_agp_buffer_t b;
2373
2374 memclear(b);
2375 b.handle = handle;
2376 if (drmIoctl(fd, DRM_IOCTL_AGP_FREE, &b))
2377 return -errno;
2378 return 0;
2379 }
2380
2381
2382 /**
2383 * Bind a chunk of AGP memory.
2384 *
2385 * \param fd file descriptor.
2386 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
2387 * \param offset offset in bytes. It will round to page boundary.
2388 *
2389 * \return zero on success, or a negative value on failure.
2390 *
2391 * \internal
2392 * This function is a wrapper around the DRM_IOCTL_AGP_BIND ioctl, passing the
2393 * argument in a drm_agp_binding structure.
2394 */
drmAgpBind(int fd,drm_handle_t handle,unsigned long offset)2395 drm_public int drmAgpBind(int fd, drm_handle_t handle, unsigned long offset)
2396 {
2397 drm_agp_binding_t b;
2398
2399 memclear(b);
2400 b.handle = handle;
2401 b.offset = offset;
2402 if (drmIoctl(fd, DRM_IOCTL_AGP_BIND, &b))
2403 return -errno;
2404 return 0;
2405 }
2406
2407
2408 /**
2409 * Unbind a chunk of AGP memory.
2410 *
2411 * \param fd file descriptor.
2412 * \param handle handle to the allocated memory, as given by drmAgpAllocate().
2413 *
2414 * \return zero on success, or a negative value on failure.
2415 *
2416 * \internal
2417 * This function is a wrapper around the DRM_IOCTL_AGP_UNBIND ioctl, passing
2418 * the argument in a drm_agp_binding structure.
2419 */
drmAgpUnbind(int fd,drm_handle_t handle)2420 drm_public int drmAgpUnbind(int fd, drm_handle_t handle)
2421 {
2422 drm_agp_binding_t b;
2423
2424 memclear(b);
2425 b.handle = handle;
2426 if (drmIoctl(fd, DRM_IOCTL_AGP_UNBIND, &b))
2427 return -errno;
2428 return 0;
2429 }
2430
2431
2432 /**
2433 * Get AGP driver major version number.
2434 *
2435 * \param fd file descriptor.
2436 *
2437 * \return major version number on success, or a negative value on failure..
2438 *
2439 * \internal
2440 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2441 * necessary information in a drm_agp_info structure.
2442 */
drmAgpVersionMajor(int fd)2443 drm_public int drmAgpVersionMajor(int fd)
2444 {
2445 drm_agp_info_t i;
2446
2447 memclear(i);
2448
2449 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2450 return -errno;
2451 return i.agp_version_major;
2452 }
2453
2454
2455 /**
2456 * Get AGP driver minor version number.
2457 *
2458 * \param fd file descriptor.
2459 *
2460 * \return minor version number on success, or a negative value on failure.
2461 *
2462 * \internal
2463 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2464 * necessary information in a drm_agp_info structure.
2465 */
drmAgpVersionMinor(int fd)2466 drm_public int drmAgpVersionMinor(int fd)
2467 {
2468 drm_agp_info_t i;
2469
2470 memclear(i);
2471
2472 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2473 return -errno;
2474 return i.agp_version_minor;
2475 }
2476
2477
2478 /**
2479 * Get AGP mode.
2480 *
2481 * \param fd file descriptor.
2482 *
2483 * \return mode on success, or zero on failure.
2484 *
2485 * \internal
2486 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2487 * necessary information in a drm_agp_info structure.
2488 */
drmAgpGetMode(int fd)2489 drm_public unsigned long drmAgpGetMode(int fd)
2490 {
2491 drm_agp_info_t i;
2492
2493 memclear(i);
2494
2495 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2496 return 0;
2497 return i.mode;
2498 }
2499
2500
2501 /**
2502 * Get AGP aperture base.
2503 *
2504 * \param fd file descriptor.
2505 *
2506 * \return aperture base on success, zero on failure.
2507 *
2508 * \internal
2509 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2510 * necessary information in a drm_agp_info structure.
2511 */
drmAgpBase(int fd)2512 drm_public unsigned long drmAgpBase(int fd)
2513 {
2514 drm_agp_info_t i;
2515
2516 memclear(i);
2517
2518 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2519 return 0;
2520 return i.aperture_base;
2521 }
2522
2523
2524 /**
2525 * Get AGP aperture size.
2526 *
2527 * \param fd file descriptor.
2528 *
2529 * \return aperture size on success, zero on failure.
2530 *
2531 * \internal
2532 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2533 * necessary information in a drm_agp_info structure.
2534 */
drmAgpSize(int fd)2535 drm_public unsigned long drmAgpSize(int fd)
2536 {
2537 drm_agp_info_t i;
2538
2539 memclear(i);
2540
2541 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2542 return 0;
2543 return i.aperture_size;
2544 }
2545
2546
2547 /**
2548 * Get used AGP memory.
2549 *
2550 * \param fd file descriptor.
2551 *
2552 * \return memory used on success, or zero on failure.
2553 *
2554 * \internal
2555 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2556 * necessary information in a drm_agp_info structure.
2557 */
drmAgpMemoryUsed(int fd)2558 drm_public unsigned long drmAgpMemoryUsed(int fd)
2559 {
2560 drm_agp_info_t i;
2561
2562 memclear(i);
2563
2564 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2565 return 0;
2566 return i.memory_used;
2567 }
2568
2569
2570 /**
2571 * Get available AGP memory.
2572 *
2573 * \param fd file descriptor.
2574 *
2575 * \return memory available on success, or zero on failure.
2576 *
2577 * \internal
2578 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2579 * necessary information in a drm_agp_info structure.
2580 */
drmAgpMemoryAvail(int fd)2581 drm_public unsigned long drmAgpMemoryAvail(int fd)
2582 {
2583 drm_agp_info_t i;
2584
2585 memclear(i);
2586
2587 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2588 return 0;
2589 return i.memory_allowed;
2590 }
2591
2592
2593 /**
2594 * Get hardware vendor ID.
2595 *
2596 * \param fd file descriptor.
2597 *
2598 * \return vendor ID on success, or zero on failure.
2599 *
2600 * \internal
2601 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2602 * necessary information in a drm_agp_info structure.
2603 */
drmAgpVendorId(int fd)2604 drm_public unsigned int drmAgpVendorId(int fd)
2605 {
2606 drm_agp_info_t i;
2607
2608 memclear(i);
2609
2610 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2611 return 0;
2612 return i.id_vendor;
2613 }
2614
2615
2616 /**
2617 * Get hardware device ID.
2618 *
2619 * \param fd file descriptor.
2620 *
2621 * \return zero on success, or zero on failure.
2622 *
2623 * \internal
2624 * This function is a wrapper around the DRM_IOCTL_AGP_INFO ioctl, getting the
2625 * necessary information in a drm_agp_info structure.
2626 */
drmAgpDeviceId(int fd)2627 drm_public unsigned int drmAgpDeviceId(int fd)
2628 {
2629 drm_agp_info_t i;
2630
2631 memclear(i);
2632
2633 if (drmIoctl(fd, DRM_IOCTL_AGP_INFO, &i))
2634 return 0;
2635 return i.id_device;
2636 }
2637
drmScatterGatherAlloc(int fd,unsigned long size,drm_handle_t * handle)2638 drm_public int drmScatterGatherAlloc(int fd, unsigned long size,
2639 drm_handle_t *handle)
2640 {
2641 drm_scatter_gather_t sg;
2642
2643 memclear(sg);
2644
2645 *handle = 0;
2646 sg.size = size;
2647 if (drmIoctl(fd, DRM_IOCTL_SG_ALLOC, &sg))
2648 return -errno;
2649 *handle = sg.handle;
2650 return 0;
2651 }
2652
drmScatterGatherFree(int fd,drm_handle_t handle)2653 drm_public int drmScatterGatherFree(int fd, drm_handle_t handle)
2654 {
2655 drm_scatter_gather_t sg;
2656
2657 memclear(sg);
2658 sg.handle = handle;
2659 if (drmIoctl(fd, DRM_IOCTL_SG_FREE, &sg))
2660 return -errno;
2661 return 0;
2662 }
2663
2664 /**
2665 * Wait for VBLANK.
2666 *
2667 * \param fd file descriptor.
2668 * \param vbl pointer to a drmVBlank structure.
2669 *
2670 * \return zero on success, or a negative value on failure.
2671 *
2672 * \internal
2673 * This function is a wrapper around the DRM_IOCTL_WAIT_VBLANK ioctl.
2674 */
drmWaitVBlank(int fd,drmVBlankPtr vbl)2675 drm_public int drmWaitVBlank(int fd, drmVBlankPtr vbl)
2676 {
2677 struct timespec timeout, cur;
2678 int ret;
2679
2680 ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2681 if (ret < 0) {
2682 fprintf(stderr, "clock_gettime failed: %s\n", strerror(errno));
2683 goto out;
2684 }
2685 timeout.tv_sec++;
2686
2687 do {
2688 ret = ioctl(fd, DRM_IOCTL_WAIT_VBLANK, vbl);
2689 vbl->request.type &= ~DRM_VBLANK_RELATIVE;
2690 if (ret && errno == EINTR) {
2691 clock_gettime(CLOCK_MONOTONIC, &cur);
2692 /* Timeout after 1s */
2693 if (cur.tv_sec > timeout.tv_sec + 1 ||
2694 (cur.tv_sec == timeout.tv_sec && cur.tv_nsec >=
2695 timeout.tv_nsec)) {
2696 errno = EBUSY;
2697 ret = -1;
2698 break;
2699 }
2700 }
2701 } while (ret && errno == EINTR);
2702
2703 out:
2704 return ret;
2705 }
2706
drmError(int err,const char * label)2707 drm_public int drmError(int err, const char *label)
2708 {
2709 switch (err) {
2710 case DRM_ERR_NO_DEVICE:
2711 fprintf(stderr, "%s: no device\n", label);
2712 break;
2713 case DRM_ERR_NO_ACCESS:
2714 fprintf(stderr, "%s: no access\n", label);
2715 break;
2716 case DRM_ERR_NOT_ROOT:
2717 fprintf(stderr, "%s: not root\n", label);
2718 break;
2719 case DRM_ERR_INVALID:
2720 fprintf(stderr, "%s: invalid args\n", label);
2721 break;
2722 default:
2723 if (err < 0)
2724 err = -err;
2725 fprintf( stderr, "%s: error %d (%s)\n", label, err, strerror(err) );
2726 break;
2727 }
2728
2729 return 1;
2730 }
2731
2732 /**
2733 * Install IRQ handler.
2734 *
2735 * \param fd file descriptor.
2736 * \param irq IRQ number.
2737 *
2738 * \return zero on success, or a negative value on failure.
2739 *
2740 * \internal
2741 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2742 * argument in a drm_control structure.
2743 */
drmCtlInstHandler(int fd,int irq)2744 drm_public int drmCtlInstHandler(int fd, int irq)
2745 {
2746 drm_control_t ctl;
2747
2748 memclear(ctl);
2749 ctl.func = DRM_INST_HANDLER;
2750 ctl.irq = irq;
2751 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2752 return -errno;
2753 return 0;
2754 }
2755
2756
2757 /**
2758 * Uninstall IRQ handler.
2759 *
2760 * \param fd file descriptor.
2761 *
2762 * \return zero on success, or a negative value on failure.
2763 *
2764 * \internal
2765 * This function is a wrapper around the DRM_IOCTL_CONTROL ioctl, passing the
2766 * argument in a drm_control structure.
2767 */
drmCtlUninstHandler(int fd)2768 drm_public int drmCtlUninstHandler(int fd)
2769 {
2770 drm_control_t ctl;
2771
2772 memclear(ctl);
2773 ctl.func = DRM_UNINST_HANDLER;
2774 ctl.irq = 0;
2775 if (drmIoctl(fd, DRM_IOCTL_CONTROL, &ctl))
2776 return -errno;
2777 return 0;
2778 }
2779
drmFinish(int fd,int context,drmLockFlags flags)2780 drm_public int drmFinish(int fd, int context, drmLockFlags flags)
2781 {
2782 drm_lock_t lock;
2783
2784 memclear(lock);
2785 lock.context = context;
2786 if (flags & DRM_LOCK_READY) lock.flags |= _DRM_LOCK_READY;
2787 if (flags & DRM_LOCK_QUIESCENT) lock.flags |= _DRM_LOCK_QUIESCENT;
2788 if (flags & DRM_LOCK_FLUSH) lock.flags |= _DRM_LOCK_FLUSH;
2789 if (flags & DRM_LOCK_FLUSH_ALL) lock.flags |= _DRM_LOCK_FLUSH_ALL;
2790 if (flags & DRM_HALT_ALL_QUEUES) lock.flags |= _DRM_HALT_ALL_QUEUES;
2791 if (flags & DRM_HALT_CUR_QUEUES) lock.flags |= _DRM_HALT_CUR_QUEUES;
2792 if (drmIoctl(fd, DRM_IOCTL_FINISH, &lock))
2793 return -errno;
2794 return 0;
2795 }
2796
2797 /**
2798 * Get IRQ from bus ID.
2799 *
2800 * \param fd file descriptor.
2801 * \param busnum bus number.
2802 * \param devnum device number.
2803 * \param funcnum function number.
2804 *
2805 * \return IRQ number on success, or a negative value on failure.
2806 *
2807 * \internal
2808 * This function is a wrapper around the DRM_IOCTL_IRQ_BUSID ioctl, passing the
2809 * arguments in a drm_irq_busid structure.
2810 */
drmGetInterruptFromBusID(int fd,int busnum,int devnum,int funcnum)2811 drm_public int drmGetInterruptFromBusID(int fd, int busnum, int devnum,
2812 int funcnum)
2813 {
2814 drm_irq_busid_t p;
2815
2816 memclear(p);
2817 p.busnum = busnum;
2818 p.devnum = devnum;
2819 p.funcnum = funcnum;
2820 if (drmIoctl(fd, DRM_IOCTL_IRQ_BUSID, &p))
2821 return -errno;
2822 return p.irq;
2823 }
2824
drmAddContextTag(int fd,drm_context_t context,void * tag)2825 drm_public int drmAddContextTag(int fd, drm_context_t context, void *tag)
2826 {
2827 drmHashEntry *entry = drmGetEntry(fd);
2828
2829 if (drmHashInsert(entry->tagTable, context, tag)) {
2830 drmHashDelete(entry->tagTable, context);
2831 drmHashInsert(entry->tagTable, context, tag);
2832 }
2833 return 0;
2834 }
2835
drmDelContextTag(int fd,drm_context_t context)2836 drm_public int drmDelContextTag(int fd, drm_context_t context)
2837 {
2838 drmHashEntry *entry = drmGetEntry(fd);
2839
2840 return drmHashDelete(entry->tagTable, context);
2841 }
2842
drmGetContextTag(int fd,drm_context_t context)2843 drm_public void *drmGetContextTag(int fd, drm_context_t context)
2844 {
2845 drmHashEntry *entry = drmGetEntry(fd);
2846 void *value;
2847
2848 if (drmHashLookup(entry->tagTable, context, &value))
2849 return NULL;
2850
2851 return value;
2852 }
2853
drmAddContextPrivateMapping(int fd,drm_context_t ctx_id,drm_handle_t handle)2854 drm_public int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
2855 drm_handle_t handle)
2856 {
2857 drm_ctx_priv_map_t map;
2858
2859 memclear(map);
2860 map.ctx_id = ctx_id;
2861 map.handle = (void *)(uintptr_t)handle;
2862
2863 if (drmIoctl(fd, DRM_IOCTL_SET_SAREA_CTX, &map))
2864 return -errno;
2865 return 0;
2866 }
2867
drmGetContextPrivateMapping(int fd,drm_context_t ctx_id,drm_handle_t * handle)2868 drm_public int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
2869 drm_handle_t *handle)
2870 {
2871 drm_ctx_priv_map_t map;
2872
2873 memclear(map);
2874 map.ctx_id = ctx_id;
2875
2876 if (drmIoctl(fd, DRM_IOCTL_GET_SAREA_CTX, &map))
2877 return -errno;
2878 if (handle)
2879 *handle = (drm_handle_t)(uintptr_t)map.handle;
2880
2881 return 0;
2882 }
2883
drmGetMap(int fd,int idx,drm_handle_t * offset,drmSize * size,drmMapType * type,drmMapFlags * flags,drm_handle_t * handle,int * mtrr)2884 drm_public int drmGetMap(int fd, int idx, drm_handle_t *offset, drmSize *size,
2885 drmMapType *type, drmMapFlags *flags,
2886 drm_handle_t *handle, int *mtrr)
2887 {
2888 drm_map_t map;
2889
2890 memclear(map);
2891 map.offset = idx;
2892 if (drmIoctl(fd, DRM_IOCTL_GET_MAP, &map))
2893 return -errno;
2894 *offset = map.offset;
2895 *size = map.size;
2896 *type = (drmMapType)map.type;
2897 *flags = (drmMapFlags)map.flags;
2898 *handle = (unsigned long)map.handle;
2899 *mtrr = map.mtrr;
2900 return 0;
2901 }
2902
drmGetClient(int fd,int idx,int * auth,int * pid,int * uid,unsigned long * magic,unsigned long * iocs)2903 drm_public int drmGetClient(int fd, int idx, int *auth, int *pid, int *uid,
2904 unsigned long *magic, unsigned long *iocs)
2905 {
2906 drm_client_t client;
2907
2908 memclear(client);
2909 client.idx = idx;
2910 if (drmIoctl(fd, DRM_IOCTL_GET_CLIENT, &client))
2911 return -errno;
2912 *auth = client.auth;
2913 *pid = client.pid;
2914 *uid = client.uid;
2915 *magic = client.magic;
2916 *iocs = client.iocs;
2917 return 0;
2918 }
2919
drmGetStats(int fd,drmStatsT * stats)2920 drm_public int drmGetStats(int fd, drmStatsT *stats)
2921 {
2922 drm_stats_t s;
2923 unsigned i;
2924
2925 memclear(s);
2926 if (drmIoctl(fd, DRM_IOCTL_GET_STATS, &s))
2927 return -errno;
2928
2929 stats->count = 0;
2930 memset(stats, 0, sizeof(*stats));
2931 if (s.count > sizeof(stats->data)/sizeof(stats->data[0]))
2932 return -1;
2933
2934 #define SET_VALUE \
2935 stats->data[i].long_format = "%-20.20s"; \
2936 stats->data[i].rate_format = "%8.8s"; \
2937 stats->data[i].isvalue = 1; \
2938 stats->data[i].verbose = 0
2939
2940 #define SET_COUNT \
2941 stats->data[i].long_format = "%-20.20s"; \
2942 stats->data[i].rate_format = "%5.5s"; \
2943 stats->data[i].isvalue = 0; \
2944 stats->data[i].mult_names = "kgm"; \
2945 stats->data[i].mult = 1000; \
2946 stats->data[i].verbose = 0
2947
2948 #define SET_BYTE \
2949 stats->data[i].long_format = "%-20.20s"; \
2950 stats->data[i].rate_format = "%5.5s"; \
2951 stats->data[i].isvalue = 0; \
2952 stats->data[i].mult_names = "KGM"; \
2953 stats->data[i].mult = 1024; \
2954 stats->data[i].verbose = 0
2955
2956
2957 stats->count = s.count;
2958 for (i = 0; i < s.count; i++) {
2959 stats->data[i].value = s.data[i].value;
2960 switch (s.data[i].type) {
2961 case _DRM_STAT_LOCK:
2962 stats->data[i].long_name = "Lock";
2963 stats->data[i].rate_name = "Lock";
2964 SET_VALUE;
2965 break;
2966 case _DRM_STAT_OPENS:
2967 stats->data[i].long_name = "Opens";
2968 stats->data[i].rate_name = "O";
2969 SET_COUNT;
2970 stats->data[i].verbose = 1;
2971 break;
2972 case _DRM_STAT_CLOSES:
2973 stats->data[i].long_name = "Closes";
2974 stats->data[i].rate_name = "Lock";
2975 SET_COUNT;
2976 stats->data[i].verbose = 1;
2977 break;
2978 case _DRM_STAT_IOCTLS:
2979 stats->data[i].long_name = "Ioctls";
2980 stats->data[i].rate_name = "Ioc/s";
2981 SET_COUNT;
2982 break;
2983 case _DRM_STAT_LOCKS:
2984 stats->data[i].long_name = "Locks";
2985 stats->data[i].rate_name = "Lck/s";
2986 SET_COUNT;
2987 break;
2988 case _DRM_STAT_UNLOCKS:
2989 stats->data[i].long_name = "Unlocks";
2990 stats->data[i].rate_name = "Unl/s";
2991 SET_COUNT;
2992 break;
2993 case _DRM_STAT_IRQ:
2994 stats->data[i].long_name = "IRQs";
2995 stats->data[i].rate_name = "IRQ/s";
2996 SET_COUNT;
2997 break;
2998 case _DRM_STAT_PRIMARY:
2999 stats->data[i].long_name = "Primary Bytes";
3000 stats->data[i].rate_name = "PB/s";
3001 SET_BYTE;
3002 break;
3003 case _DRM_STAT_SECONDARY:
3004 stats->data[i].long_name = "Secondary Bytes";
3005 stats->data[i].rate_name = "SB/s";
3006 SET_BYTE;
3007 break;
3008 case _DRM_STAT_DMA:
3009 stats->data[i].long_name = "DMA";
3010 stats->data[i].rate_name = "DMA/s";
3011 SET_COUNT;
3012 break;
3013 case _DRM_STAT_SPECIAL:
3014 stats->data[i].long_name = "Special DMA";
3015 stats->data[i].rate_name = "dma/s";
3016 SET_COUNT;
3017 break;
3018 case _DRM_STAT_MISSED:
3019 stats->data[i].long_name = "Miss";
3020 stats->data[i].rate_name = "Ms/s";
3021 SET_COUNT;
3022 break;
3023 case _DRM_STAT_VALUE:
3024 stats->data[i].long_name = "Value";
3025 stats->data[i].rate_name = "Value";
3026 SET_VALUE;
3027 break;
3028 case _DRM_STAT_BYTE:
3029 stats->data[i].long_name = "Bytes";
3030 stats->data[i].rate_name = "B/s";
3031 SET_BYTE;
3032 break;
3033 case _DRM_STAT_COUNT:
3034 default:
3035 stats->data[i].long_name = "Count";
3036 stats->data[i].rate_name = "Cnt/s";
3037 SET_COUNT;
3038 break;
3039 }
3040 }
3041 return 0;
3042 }
3043
3044 /**
3045 * Issue a set-version ioctl.
3046 *
3047 * \param fd file descriptor.
3048 * \param drmCommandIndex command index
3049 * \param data source pointer of the data to be read and written.
3050 * \param size size of the data to be read and written.
3051 *
3052 * \return zero on success, or a negative value on failure.
3053 *
3054 * \internal
3055 * It issues a read-write ioctl given by
3056 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
3057 */
drmSetInterfaceVersion(int fd,drmSetVersion * version)3058 drm_public int drmSetInterfaceVersion(int fd, drmSetVersion *version)
3059 {
3060 int retcode = 0;
3061 drm_set_version_t sv;
3062
3063 memclear(sv);
3064 sv.drm_di_major = version->drm_di_major;
3065 sv.drm_di_minor = version->drm_di_minor;
3066 sv.drm_dd_major = version->drm_dd_major;
3067 sv.drm_dd_minor = version->drm_dd_minor;
3068
3069 if (drmIoctl(fd, DRM_IOCTL_SET_VERSION, &sv)) {
3070 retcode = -errno;
3071 }
3072
3073 version->drm_di_major = sv.drm_di_major;
3074 version->drm_di_minor = sv.drm_di_minor;
3075 version->drm_dd_major = sv.drm_dd_major;
3076 version->drm_dd_minor = sv.drm_dd_minor;
3077
3078 return retcode;
3079 }
3080
3081 /**
3082 * Send a device-specific command.
3083 *
3084 * \param fd file descriptor.
3085 * \param drmCommandIndex command index
3086 *
3087 * \return zero on success, or a negative value on failure.
3088 *
3089 * \internal
3090 * It issues a ioctl given by
3091 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
3092 */
drmCommandNone(int fd,unsigned long drmCommandIndex)3093 drm_public int drmCommandNone(int fd, unsigned long drmCommandIndex)
3094 {
3095 unsigned long request;
3096
3097 request = DRM_IO( DRM_COMMAND_BASE + drmCommandIndex);
3098
3099 if (drmIoctl(fd, request, NULL)) {
3100 return -errno;
3101 }
3102 return 0;
3103 }
3104
3105
3106 /**
3107 * Send a device-specific read command.
3108 *
3109 * \param fd file descriptor.
3110 * \param drmCommandIndex command index
3111 * \param data destination pointer of the data to be read.
3112 * \param size size of the data to be read.
3113 *
3114 * \return zero on success, or a negative value on failure.
3115 *
3116 * \internal
3117 * It issues a read ioctl given by
3118 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
3119 */
drmCommandRead(int fd,unsigned long drmCommandIndex,void * data,unsigned long size)3120 drm_public int drmCommandRead(int fd, unsigned long drmCommandIndex,
3121 void *data, unsigned long size)
3122 {
3123 unsigned long request;
3124
3125 request = DRM_IOC( DRM_IOC_READ, DRM_IOCTL_BASE,
3126 DRM_COMMAND_BASE + drmCommandIndex, size);
3127
3128 if (drmIoctl(fd, request, data)) {
3129 return -errno;
3130 }
3131 return 0;
3132 }
3133
3134
3135 /**
3136 * Send a device-specific write command.
3137 *
3138 * \param fd file descriptor.
3139 * \param drmCommandIndex command index
3140 * \param data source pointer of the data to be written.
3141 * \param size size of the data to be written.
3142 *
3143 * \return zero on success, or a negative value on failure.
3144 *
3145 * \internal
3146 * It issues a write ioctl given by
3147 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
3148 */
drmCommandWrite(int fd,unsigned long drmCommandIndex,void * data,unsigned long size)3149 drm_public int drmCommandWrite(int fd, unsigned long drmCommandIndex,
3150 void *data, unsigned long size)
3151 {
3152 unsigned long request;
3153
3154 request = DRM_IOC( DRM_IOC_WRITE, DRM_IOCTL_BASE,
3155 DRM_COMMAND_BASE + drmCommandIndex, size);
3156
3157 if (drmIoctl(fd, request, data)) {
3158 return -errno;
3159 }
3160 return 0;
3161 }
3162
3163
3164 /**
3165 * Send a device-specific read-write command.
3166 *
3167 * \param fd file descriptor.
3168 * \param drmCommandIndex command index
3169 * \param data source pointer of the data to be read and written.
3170 * \param size size of the data to be read and written.
3171 *
3172 * \return zero on success, or a negative value on failure.
3173 *
3174 * \internal
3175 * It issues a read-write ioctl given by
3176 * \code DRM_COMMAND_BASE + drmCommandIndex \endcode.
3177 */
drmCommandWriteRead(int fd,unsigned long drmCommandIndex,void * data,unsigned long size)3178 drm_public int drmCommandWriteRead(int fd, unsigned long drmCommandIndex,
3179 void *data, unsigned long size)
3180 {
3181 unsigned long request;
3182
3183 request = DRM_IOC( DRM_IOC_READ|DRM_IOC_WRITE, DRM_IOCTL_BASE,
3184 DRM_COMMAND_BASE + drmCommandIndex, size);
3185
3186 if (drmIoctl(fd, request, data))
3187 return -errno;
3188 return 0;
3189 }
3190
3191 #define DRM_MAX_FDS 16
3192 static struct {
3193 char *BusID;
3194 int fd;
3195 int refcount;
3196 int type;
3197 } connection[DRM_MAX_FDS];
3198
3199 static int nr_fds = 0;
3200
drmOpenOnce(void * unused,const char * BusID,int * newlyopened)3201 drm_public int drmOpenOnce(void *unused, const char *BusID, int *newlyopened)
3202 {
3203 return drmOpenOnceWithType(BusID, newlyopened, DRM_NODE_PRIMARY);
3204 }
3205
drmOpenOnceWithType(const char * BusID,int * newlyopened,int type)3206 drm_public int drmOpenOnceWithType(const char *BusID, int *newlyopened,
3207 int type)
3208 {
3209 int i;
3210 int fd;
3211
3212 for (i = 0; i < nr_fds; i++)
3213 if ((strcmp(BusID, connection[i].BusID) == 0) &&
3214 (connection[i].type == type)) {
3215 connection[i].refcount++;
3216 *newlyopened = 0;
3217 return connection[i].fd;
3218 }
3219
3220 fd = drmOpenWithType(NULL, BusID, type);
3221 if (fd < 0 || nr_fds == DRM_MAX_FDS)
3222 return fd;
3223
3224 connection[nr_fds].BusID = strdup(BusID);
3225 connection[nr_fds].fd = fd;
3226 connection[nr_fds].refcount = 1;
3227 connection[nr_fds].type = type;
3228 *newlyopened = 1;
3229
3230 if (0)
3231 fprintf(stderr, "saved connection %d for %s %d\n",
3232 nr_fds, connection[nr_fds].BusID,
3233 strcmp(BusID, connection[nr_fds].BusID));
3234
3235 nr_fds++;
3236
3237 return fd;
3238 }
3239
drmCloseOnce(int fd)3240 drm_public void drmCloseOnce(int fd)
3241 {
3242 int i;
3243
3244 for (i = 0; i < nr_fds; i++) {
3245 if (fd == connection[i].fd) {
3246 if (--connection[i].refcount == 0) {
3247 drmClose(connection[i].fd);
3248 free(connection[i].BusID);
3249
3250 if (i < --nr_fds)
3251 connection[i] = connection[nr_fds];
3252
3253 return;
3254 }
3255 }
3256 }
3257 }
3258
drmSetMaster(int fd)3259 drm_public int drmSetMaster(int fd)
3260 {
3261 return drmIoctl(fd, DRM_IOCTL_SET_MASTER, NULL);
3262 }
3263
drmDropMaster(int fd)3264 drm_public int drmDropMaster(int fd)
3265 {
3266 return drmIoctl(fd, DRM_IOCTL_DROP_MASTER, NULL);
3267 }
3268
drmIsMaster(int fd)3269 drm_public int drmIsMaster(int fd)
3270 {
3271 /* Detect master by attempting something that requires master.
3272 *
3273 * Authenticating magic tokens requires master and 0 is an
3274 * internal kernel detail which we could use. Attempting this on
3275 * a master fd would fail therefore fail with EINVAL because 0
3276 * is invalid.
3277 *
3278 * A non-master fd will fail with EACCES, as the kernel checks
3279 * for master before attempting to do anything else.
3280 *
3281 * Since we don't want to leak implementation details, use
3282 * EACCES.
3283 */
3284 return drmAuthMagic(fd, 0) != -EACCES;
3285 }
3286
drmGetDeviceNameFromFd(int fd)3287 drm_public char *drmGetDeviceNameFromFd(int fd)
3288 {
3289 #ifdef __FreeBSD__
3290 struct stat sbuf;
3291 int maj, min;
3292 int nodetype;
3293
3294 if (fstat(fd, &sbuf))
3295 return NULL;
3296
3297 maj = major(sbuf.st_rdev);
3298 min = minor(sbuf.st_rdev);
3299 nodetype = drmGetMinorType(maj, min);
3300 return drmGetMinorNameForFD(fd, nodetype);
3301 #else
3302 char name[128];
3303 struct stat sbuf;
3304 dev_t d;
3305 int i;
3306
3307 /* The whole drmOpen thing is a fiasco and we need to find a way
3308 * back to just using open(2). For now, however, lets just make
3309 * things worse with even more ad hoc directory walking code to
3310 * discover the device file name. */
3311
3312 fstat(fd, &sbuf);
3313 d = sbuf.st_rdev;
3314
3315 for (i = 0; i < DRM_MAX_MINOR; i++) {
3316 snprintf(name, sizeof name, DRM_DEV_NAME, DRM_DIR_NAME, i);
3317 if (stat(name, &sbuf) == 0 && sbuf.st_rdev == d)
3318 break;
3319 }
3320 if (i == DRM_MAX_MINOR)
3321 return NULL;
3322
3323 return strdup(name);
3324 #endif
3325 }
3326
drmNodeIsDRM(int maj,int min)3327 static bool drmNodeIsDRM(int maj, int min)
3328 {
3329 #ifdef __linux__
3330 char path[64];
3331 struct stat sbuf;
3332
3333 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device/drm",
3334 maj, min);
3335 return stat(path, &sbuf) == 0;
3336 #elif defined(__FreeBSD__)
3337 char name[SPECNAMELEN];
3338
3339 if (!devname_r(makedev(maj, min), S_IFCHR, name, sizeof(name)))
3340 return 0;
3341 /* Handle drm/ and dri/ as both are present in different FreeBSD version
3342 * FreeBSD on amd64/i386/powerpc external kernel modules create node in
3343 * in /dev/drm/ and links in /dev/dri while a WIP in kernel driver creates
3344 * only device nodes in /dev/dri/ */
3345 return (!strncmp(name, "drm/", 4) || !strncmp(name, "dri/", 4));
3346 #else
3347 return maj == DRM_MAJOR;
3348 #endif
3349 }
3350
drmGetNodeTypeFromFd(int fd)3351 drm_public int drmGetNodeTypeFromFd(int fd)
3352 {
3353 struct stat sbuf;
3354 int maj, min, type;
3355
3356 if (fstat(fd, &sbuf))
3357 return -1;
3358
3359 maj = major(sbuf.st_rdev);
3360 min = minor(sbuf.st_rdev);
3361
3362 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode)) {
3363 errno = EINVAL;
3364 return -1;
3365 }
3366
3367 type = drmGetMinorType(maj, min);
3368 if (type == -1)
3369 errno = ENODEV;
3370 return type;
3371 }
3372
drmPrimeHandleToFD(int fd,uint32_t handle,uint32_t flags,int * prime_fd)3373 drm_public int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags,
3374 int *prime_fd)
3375 {
3376 struct drm_prime_handle args;
3377 int ret;
3378
3379 memclear(args);
3380 args.fd = -1;
3381 args.handle = handle;
3382 args.flags = flags;
3383 ret = drmIoctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
3384 if (ret)
3385 return ret;
3386
3387 *prime_fd = args.fd;
3388 return 0;
3389 }
3390
drmPrimeFDToHandle(int fd,int prime_fd,uint32_t * handle)3391 drm_public int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle)
3392 {
3393 struct drm_prime_handle args;
3394 int ret;
3395
3396 memclear(args);
3397 args.fd = prime_fd;
3398 ret = drmIoctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
3399 if (ret)
3400 return ret;
3401
3402 *handle = args.handle;
3403 return 0;
3404 }
3405
drmCloseBufferHandle(int fd,uint32_t handle)3406 drm_public int drmCloseBufferHandle(int fd, uint32_t handle)
3407 {
3408 struct drm_gem_close args;
3409
3410 memclear(args);
3411 args.handle = handle;
3412 return drmIoctl(fd, DRM_IOCTL_GEM_CLOSE, &args);
3413 }
3414
drmGetMinorNameForFD(int fd,int type)3415 static char *drmGetMinorNameForFD(int fd, int type)
3416 {
3417 #ifdef __linux__
3418 DIR *sysdir;
3419 struct dirent *ent;
3420 struct stat sbuf;
3421 const char *name = drmGetMinorName(type);
3422 int len;
3423 char dev_name[64], buf[64];
3424 int maj, min;
3425
3426 if (!name)
3427 return NULL;
3428
3429 len = strlen(name);
3430
3431 if (fstat(fd, &sbuf))
3432 return NULL;
3433
3434 maj = major(sbuf.st_rdev);
3435 min = minor(sbuf.st_rdev);
3436
3437 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3438 return NULL;
3439
3440 snprintf(buf, sizeof(buf), "/sys/dev/char/%d:%d/device/drm", maj, min);
3441
3442 sysdir = opendir(buf);
3443 if (!sysdir)
3444 return NULL;
3445
3446 while ((ent = readdir(sysdir))) {
3447 if (strncmp(ent->d_name, name, len) == 0) {
3448 if (snprintf(dev_name, sizeof(dev_name), DRM_DIR_NAME "/%s",
3449 ent->d_name) < 0)
3450 return NULL;
3451
3452 closedir(sysdir);
3453 return strdup(dev_name);
3454 }
3455 }
3456
3457 closedir(sysdir);
3458 return NULL;
3459 #elif defined(__FreeBSD__)
3460 struct stat sbuf;
3461 char dname[SPECNAMELEN];
3462 const char *mname;
3463 char name[SPECNAMELEN];
3464 int id, maj, min, nodetype, i;
3465
3466 if (fstat(fd, &sbuf))
3467 return NULL;
3468
3469 maj = major(sbuf.st_rdev);
3470 min = minor(sbuf.st_rdev);
3471
3472 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3473 return NULL;
3474
3475 if (!devname_r(sbuf.st_rdev, S_IFCHR, dname, sizeof(dname)))
3476 return NULL;
3477
3478 /* Handle both /dev/drm and /dev/dri
3479 * FreeBSD on amd64/i386/powerpc external kernel modules create node in
3480 * in /dev/drm/ and links in /dev/dri while a WIP in kernel driver creates
3481 * only device nodes in /dev/dri/ */
3482
3483 /* Get the node type represented by fd so we can deduce the target name */
3484 nodetype = drmGetMinorType(maj, min);
3485 if (nodetype == -1)
3486 return (NULL);
3487 mname = drmGetMinorName(type);
3488
3489 for (i = 0; i < SPECNAMELEN; i++) {
3490 if (isalpha(dname[i]) == 0 && dname[i] != '/')
3491 break;
3492 }
3493 if (dname[i] == '\0')
3494 return (NULL);
3495
3496 id = (int)strtol(&dname[i], NULL, 10);
3497 id -= drmGetMinorBase(nodetype);
3498 snprintf(name, sizeof(name), DRM_DIR_NAME "/%s%d", mname,
3499 id + drmGetMinorBase(type));
3500
3501 return strdup(name);
3502 #else
3503 struct stat sbuf;
3504 char buf[PATH_MAX + 1];
3505 const char *dev_name = drmGetDeviceName(type);
3506 unsigned int maj, min;
3507 int n;
3508
3509 if (fstat(fd, &sbuf))
3510 return NULL;
3511
3512 maj = major(sbuf.st_rdev);
3513 min = minor(sbuf.st_rdev);
3514
3515 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
3516 return NULL;
3517
3518 if (!dev_name)
3519 return NULL;
3520
3521 n = snprintf(buf, sizeof(buf), dev_name, DRM_DIR_NAME, min);
3522 if (n == -1 || n >= sizeof(buf))
3523 return NULL;
3524
3525 return strdup(buf);
3526 #endif
3527 }
3528
drmGetPrimaryDeviceNameFromFd(int fd)3529 drm_public char *drmGetPrimaryDeviceNameFromFd(int fd)
3530 {
3531 return drmGetMinorNameForFD(fd, DRM_NODE_PRIMARY);
3532 }
3533
drmGetRenderDeviceNameFromFd(int fd)3534 drm_public char *drmGetRenderDeviceNameFromFd(int fd)
3535 {
3536 return drmGetMinorNameForFD(fd, DRM_NODE_RENDER);
3537 }
3538
3539 #ifdef __linux__
3540 static char * DRM_PRINTFLIKE(2, 3)
sysfs_uevent_get(const char * path,const char * fmt,...)3541 sysfs_uevent_get(const char *path, const char *fmt, ...)
3542 {
3543 char filename[PATH_MAX + 1], *key, *line = NULL, *value = NULL;
3544 size_t size = 0, len;
3545 ssize_t num;
3546 va_list ap;
3547 FILE *fp;
3548
3549 va_start(ap, fmt);
3550 num = vasprintf(&key, fmt, ap);
3551 va_end(ap);
3552 len = num;
3553
3554 snprintf(filename, sizeof(filename), "%s/uevent", path);
3555
3556 fp = fopen(filename, "r");
3557 if (!fp) {
3558 free(key);
3559 return NULL;
3560 }
3561
3562 while ((num = getline(&line, &size, fp)) >= 0) {
3563 if ((strncmp(line, key, len) == 0) && (line[len] == '=')) {
3564 char *start = line + len + 1, *end = line + num - 1;
3565
3566 if (*end != '\n')
3567 end++;
3568
3569 value = strndup(start, end - start);
3570 break;
3571 }
3572 }
3573
3574 free(line);
3575 fclose(fp);
3576
3577 free(key);
3578
3579 return value;
3580 }
3581 #endif
3582
3583 /* Little white lie to avoid major rework of the existing code */
3584 #define DRM_BUS_VIRTIO 0x10
3585
3586 #ifdef __linux__
get_subsystem_type(const char * device_path)3587 static int get_subsystem_type(const char *device_path)
3588 {
3589 char path[PATH_MAX + 1] = "";
3590 char link[PATH_MAX + 1] = "";
3591 char *name;
3592 struct {
3593 const char *name;
3594 int bus_type;
3595 } bus_types[] = {
3596 { "/pci", DRM_BUS_PCI },
3597 { "/usb", DRM_BUS_USB },
3598 { "/platform", DRM_BUS_PLATFORM },
3599 { "/spi", DRM_BUS_PLATFORM },
3600 { "/host1x", DRM_BUS_HOST1X },
3601 { "/virtio", DRM_BUS_VIRTIO },
3602 };
3603
3604 strncpy(path, device_path, PATH_MAX);
3605 strncat(path, "/subsystem", PATH_MAX);
3606
3607 if (readlink(path, link, PATH_MAX) < 0)
3608 return -errno;
3609
3610 name = strrchr(link, '/');
3611 if (!name)
3612 return -EINVAL;
3613
3614 for (unsigned i = 0; i < ARRAY_SIZE(bus_types); i++) {
3615 if (strncmp(name, bus_types[i].name, strlen(bus_types[i].name)) == 0)
3616 return bus_types[i].bus_type;
3617 }
3618
3619 return -EINVAL;
3620 }
3621 #endif
3622
drmParseSubsystemType(int maj,int min)3623 static int drmParseSubsystemType(int maj, int min)
3624 {
3625 #ifdef __linux__
3626 char path[PATH_MAX + 1] = "";
3627 char real_path[PATH_MAX + 1] = "";
3628 int subsystem_type;
3629
3630 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3631
3632 subsystem_type = get_subsystem_type(path);
3633 /* Try to get the parent (underlying) device type */
3634 if (subsystem_type == DRM_BUS_VIRTIO) {
3635 /* Assume virtio-pci on error */
3636 if (!realpath(path, real_path))
3637 return DRM_BUS_VIRTIO;
3638 strncat(path, "/..", PATH_MAX);
3639 subsystem_type = get_subsystem_type(path);
3640 if (subsystem_type < 0)
3641 return DRM_BUS_VIRTIO;
3642 }
3643 return subsystem_type;
3644 #elif defined(__OpenBSD__) || defined(__DragonFly__) || defined(__FreeBSD__)
3645 return DRM_BUS_PCI;
3646 #else
3647 #warning "Missing implementation of drmParseSubsystemType"
3648 return -EINVAL;
3649 #endif
3650 }
3651
3652 #ifdef __linux__
3653 static void
get_pci_path(int maj,int min,char * pci_path)3654 get_pci_path(int maj, int min, char *pci_path)
3655 {
3656 char path[PATH_MAX + 1], *term;
3657
3658 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
3659 if (!realpath(path, pci_path)) {
3660 strcpy(pci_path, path);
3661 return;
3662 }
3663
3664 term = strrchr(pci_path, '/');
3665 if (term && strncmp(term, "/virtio", 7) == 0)
3666 *term = 0;
3667 }
3668 #endif
3669
3670 #ifdef __FreeBSD__
get_sysctl_pci_bus_info(int maj,int min,drmPciBusInfoPtr info)3671 static int get_sysctl_pci_bus_info(int maj, int min, drmPciBusInfoPtr info)
3672 {
3673 char dname[SPECNAMELEN];
3674 char sysctl_name[16];
3675 char sysctl_val[256];
3676 size_t sysctl_len;
3677 int id, type, nelem;
3678 unsigned int rdev, majmin, domain, bus, dev, func;
3679
3680 rdev = makedev(maj, min);
3681 if (!devname_r(rdev, S_IFCHR, dname, sizeof(dname)))
3682 return -EINVAL;
3683
3684 if (sscanf(dname, "drm/%d\n", &id) != 1)
3685 return -EINVAL;
3686 type = drmGetMinorType(maj, min);
3687 if (type == -1)
3688 return -EINVAL;
3689
3690 /* BUG: This above section is iffy, since it mandates that a driver will
3691 * create both card and render node.
3692 * If it does not, the next DRM device will create card#X and
3693 * renderD#(128+X)-1.
3694 * This is a possibility in FreeBSD but for now there is no good way for
3695 * obtaining the info.
3696 */
3697 switch (type) {
3698 case DRM_NODE_PRIMARY:
3699 break;
3700 case DRM_NODE_RENDER:
3701 id -= 128;
3702 break;
3703 }
3704 if (id < 0)
3705 return -EINVAL;
3706
3707 if (snprintf(sysctl_name, sizeof(sysctl_name), "hw.dri.%d.busid", id) <= 0)
3708 return -EINVAL;
3709 sysctl_len = sizeof(sysctl_val);
3710 if (sysctlbyname(sysctl_name, sysctl_val, &sysctl_len, NULL, 0))
3711 return -EINVAL;
3712
3713 #define bus_fmt "pci:%04x:%02x:%02x.%u"
3714
3715 nelem = sscanf(sysctl_val, bus_fmt, &domain, &bus, &dev, &func);
3716 if (nelem != 4)
3717 return -EINVAL;
3718 info->domain = domain;
3719 info->bus = bus;
3720 info->dev = dev;
3721 info->func = func;
3722
3723 return 0;
3724 }
3725 #endif
3726
drmParsePciBusInfo(int maj,int min,drmPciBusInfoPtr info)3727 static int drmParsePciBusInfo(int maj, int min, drmPciBusInfoPtr info)
3728 {
3729 #ifdef __linux__
3730 unsigned int domain, bus, dev, func;
3731 char pci_path[PATH_MAX + 1], *value;
3732 int num;
3733
3734 get_pci_path(maj, min, pci_path);
3735
3736 value = sysfs_uevent_get(pci_path, "PCI_SLOT_NAME");
3737 if (!value)
3738 return -ENOENT;
3739
3740 num = sscanf(value, "%04x:%02x:%02x.%1u", &domain, &bus, &dev, &func);
3741 free(value);
3742
3743 if (num != 4)
3744 return -EINVAL;
3745
3746 info->domain = domain;
3747 info->bus = bus;
3748 info->dev = dev;
3749 info->func = func;
3750
3751 return 0;
3752 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3753 struct drm_pciinfo pinfo;
3754 int fd, type;
3755
3756 type = drmGetMinorType(maj, min);
3757 if (type == -1)
3758 return -ENODEV;
3759
3760 fd = drmOpenMinor(min, 0, type);
3761 if (fd < 0)
3762 return -errno;
3763
3764 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3765 close(fd);
3766 return -errno;
3767 }
3768 close(fd);
3769
3770 info->domain = pinfo.domain;
3771 info->bus = pinfo.bus;
3772 info->dev = pinfo.dev;
3773 info->func = pinfo.func;
3774
3775 return 0;
3776 #elif defined(__FreeBSD__)
3777 return get_sysctl_pci_bus_info(maj, min, info);
3778 #else
3779 #warning "Missing implementation of drmParsePciBusInfo"
3780 return -EINVAL;
3781 #endif
3782 }
3783
drmDevicesEqual(drmDevicePtr a,drmDevicePtr b)3784 drm_public int drmDevicesEqual(drmDevicePtr a, drmDevicePtr b)
3785 {
3786 if (a == NULL || b == NULL)
3787 return 0;
3788
3789 if (a->bustype != b->bustype)
3790 return 0;
3791
3792 switch (a->bustype) {
3793 case DRM_BUS_PCI:
3794 return memcmp(a->businfo.pci, b->businfo.pci, sizeof(drmPciBusInfo)) == 0;
3795
3796 case DRM_BUS_USB:
3797 return memcmp(a->businfo.usb, b->businfo.usb, sizeof(drmUsbBusInfo)) == 0;
3798
3799 case DRM_BUS_PLATFORM:
3800 return memcmp(a->businfo.platform, b->businfo.platform, sizeof(drmPlatformBusInfo)) == 0;
3801
3802 case DRM_BUS_HOST1X:
3803 return memcmp(a->businfo.host1x, b->businfo.host1x, sizeof(drmHost1xBusInfo)) == 0;
3804
3805 default:
3806 break;
3807 }
3808
3809 return 0;
3810 }
3811
drmGetNodeType(const char * name)3812 static int drmGetNodeType(const char *name)
3813 {
3814 if (strncmp(name, DRM_RENDER_MINOR_NAME,
3815 sizeof(DRM_RENDER_MINOR_NAME) - 1) == 0)
3816 return DRM_NODE_RENDER;
3817
3818 if (strncmp(name, DRM_PRIMARY_MINOR_NAME,
3819 sizeof(DRM_PRIMARY_MINOR_NAME) - 1) == 0)
3820 return DRM_NODE_PRIMARY;
3821
3822 return -EINVAL;
3823 }
3824
drmGetMaxNodeName(void)3825 static int drmGetMaxNodeName(void)
3826 {
3827 return sizeof(DRM_DIR_NAME) +
3828 MAX3(sizeof(DRM_PRIMARY_MINOR_NAME),
3829 sizeof(DRM_CONTROL_MINOR_NAME),
3830 sizeof(DRM_RENDER_MINOR_NAME)) +
3831 3 /* length of the node number */;
3832 }
3833
3834 #ifdef __linux__
parse_separate_sysfs_files(int maj,int min,drmPciDeviceInfoPtr device,bool ignore_revision)3835 static int parse_separate_sysfs_files(int maj, int min,
3836 drmPciDeviceInfoPtr device,
3837 bool ignore_revision)
3838 {
3839 static const char *attrs[] = {
3840 "revision", /* Older kernels are missing the file, so check for it first */
3841 "vendor",
3842 "device",
3843 "subsystem_vendor",
3844 "subsystem_device",
3845 };
3846 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3847 unsigned int data[ARRAY_SIZE(attrs)];
3848 FILE *fp;
3849 int ret;
3850
3851 get_pci_path(maj, min, pci_path);
3852
3853 for (unsigned i = ignore_revision ? 1 : 0; i < ARRAY_SIZE(attrs); i++) {
3854 if (snprintf(path, PATH_MAX, "%s/%s", pci_path, attrs[i]) < 0)
3855 return -errno;
3856
3857 fp = fopen(path, "r");
3858 if (!fp)
3859 return -errno;
3860
3861 ret = fscanf(fp, "%x", &data[i]);
3862 fclose(fp);
3863 if (ret != 1)
3864 return -errno;
3865
3866 }
3867
3868 device->revision_id = ignore_revision ? 0xff : data[0] & 0xff;
3869 device->vendor_id = data[1] & 0xffff;
3870 device->device_id = data[2] & 0xffff;
3871 device->subvendor_id = data[3] & 0xffff;
3872 device->subdevice_id = data[4] & 0xffff;
3873
3874 return 0;
3875 }
3876
parse_config_sysfs_file(int maj,int min,drmPciDeviceInfoPtr device)3877 static int parse_config_sysfs_file(int maj, int min,
3878 drmPciDeviceInfoPtr device)
3879 {
3880 char path[PATH_MAX + 1], pci_path[PATH_MAX + 1];
3881 unsigned char config[64];
3882 int fd, ret;
3883
3884 get_pci_path(maj, min, pci_path);
3885
3886 if (snprintf(path, PATH_MAX, "%s/config", pci_path) < 0)
3887 return -errno;
3888
3889 fd = open(path, O_RDONLY);
3890 if (fd < 0)
3891 return -errno;
3892
3893 ret = read(fd, config, sizeof(config));
3894 close(fd);
3895 if (ret < 0)
3896 return -errno;
3897
3898 device->vendor_id = config[0] | (config[1] << 8);
3899 device->device_id = config[2] | (config[3] << 8);
3900 device->revision_id = config[8];
3901 device->subvendor_id = config[44] | (config[45] << 8);
3902 device->subdevice_id = config[46] | (config[47] << 8);
3903
3904 return 0;
3905 }
3906 #endif
3907
drmParsePciDeviceInfo(int maj,int min,drmPciDeviceInfoPtr device,uint32_t flags)3908 static int drmParsePciDeviceInfo(int maj, int min,
3909 drmPciDeviceInfoPtr device,
3910 uint32_t flags)
3911 {
3912 #ifdef __linux__
3913 if (!(flags & DRM_DEVICE_GET_PCI_REVISION))
3914 return parse_separate_sysfs_files(maj, min, device, true);
3915
3916 if (parse_separate_sysfs_files(maj, min, device, false))
3917 return parse_config_sysfs_file(maj, min, device);
3918
3919 return 0;
3920 #elif defined(__OpenBSD__) || defined(__DragonFly__)
3921 struct drm_pciinfo pinfo;
3922 int fd, type;
3923
3924 type = drmGetMinorType(maj, min);
3925 if (type == -1)
3926 return -ENODEV;
3927
3928 fd = drmOpenMinor(min, 0, type);
3929 if (fd < 0)
3930 return -errno;
3931
3932 if (drmIoctl(fd, DRM_IOCTL_GET_PCIINFO, &pinfo)) {
3933 close(fd);
3934 return -errno;
3935 }
3936 close(fd);
3937
3938 device->vendor_id = pinfo.vendor_id;
3939 device->device_id = pinfo.device_id;
3940 device->revision_id = pinfo.revision_id;
3941 device->subvendor_id = pinfo.subvendor_id;
3942 device->subdevice_id = pinfo.subdevice_id;
3943
3944 return 0;
3945 #elif defined(__FreeBSD__)
3946 drmPciBusInfo info;
3947 struct pci_conf_io pc;
3948 struct pci_match_conf patterns[1];
3949 struct pci_conf results[1];
3950 int fd, error;
3951
3952 if (get_sysctl_pci_bus_info(maj, min, &info) != 0)
3953 return -EINVAL;
3954
3955 fd = open("/dev/pci", O_RDONLY);
3956 if (fd < 0)
3957 return -errno;
3958
3959 bzero(&patterns, sizeof(patterns));
3960 patterns[0].pc_sel.pc_domain = info.domain;
3961 patterns[0].pc_sel.pc_bus = info.bus;
3962 patterns[0].pc_sel.pc_dev = info.dev;
3963 patterns[0].pc_sel.pc_func = info.func;
3964 patterns[0].flags = PCI_GETCONF_MATCH_DOMAIN | PCI_GETCONF_MATCH_BUS
3965 | PCI_GETCONF_MATCH_DEV | PCI_GETCONF_MATCH_FUNC;
3966 bzero(&pc, sizeof(struct pci_conf_io));
3967 pc.num_patterns = 1;
3968 pc.pat_buf_len = sizeof(patterns);
3969 pc.patterns = patterns;
3970 pc.match_buf_len = sizeof(results);
3971 pc.matches = results;
3972
3973 if (ioctl(fd, PCIOCGETCONF, &pc) || pc.status == PCI_GETCONF_ERROR) {
3974 error = errno;
3975 close(fd);
3976 return -error;
3977 }
3978 close(fd);
3979
3980 device->vendor_id = results[0].pc_vendor;
3981 device->device_id = results[0].pc_device;
3982 device->subvendor_id = results[0].pc_subvendor;
3983 device->subdevice_id = results[0].pc_subdevice;
3984 device->revision_id = results[0].pc_revid;
3985
3986 return 0;
3987 #else
3988 #warning "Missing implementation of drmParsePciDeviceInfo"
3989 return -EINVAL;
3990 #endif
3991 }
3992
drmFreePlatformDevice(drmDevicePtr device)3993 static void drmFreePlatformDevice(drmDevicePtr device)
3994 {
3995 if (device->deviceinfo.platform) {
3996 if (device->deviceinfo.platform->compatible) {
3997 char **compatible = device->deviceinfo.platform->compatible;
3998
3999 while (*compatible) {
4000 free(*compatible);
4001 compatible++;
4002 }
4003
4004 free(device->deviceinfo.platform->compatible);
4005 }
4006 }
4007 }
4008
drmFreeHost1xDevice(drmDevicePtr device)4009 static void drmFreeHost1xDevice(drmDevicePtr device)
4010 {
4011 if (device->deviceinfo.host1x) {
4012 if (device->deviceinfo.host1x->compatible) {
4013 char **compatible = device->deviceinfo.host1x->compatible;
4014
4015 while (*compatible) {
4016 free(*compatible);
4017 compatible++;
4018 }
4019
4020 free(device->deviceinfo.host1x->compatible);
4021 }
4022 }
4023 }
4024
drmFreeDevice(drmDevicePtr * device)4025 drm_public void drmFreeDevice(drmDevicePtr *device)
4026 {
4027 if (device == NULL)
4028 return;
4029
4030 if (*device) {
4031 switch ((*device)->bustype) {
4032 case DRM_BUS_PLATFORM:
4033 drmFreePlatformDevice(*device);
4034 break;
4035
4036 case DRM_BUS_HOST1X:
4037 drmFreeHost1xDevice(*device);
4038 break;
4039 }
4040 }
4041
4042 free(*device);
4043 *device = NULL;
4044 }
4045
drmFreeDevices(drmDevicePtr devices[],int count)4046 drm_public void drmFreeDevices(drmDevicePtr devices[], int count)
4047 {
4048 int i;
4049
4050 if (devices == NULL)
4051 return;
4052
4053 for (i = 0; i < count; i++)
4054 if (devices[i])
4055 drmFreeDevice(&devices[i]);
4056 }
4057
drmDeviceAlloc(unsigned int type,const char * node,size_t bus_size,size_t device_size,char ** ptrp)4058 static drmDevicePtr drmDeviceAlloc(unsigned int type, const char *node,
4059 size_t bus_size, size_t device_size,
4060 char **ptrp)
4061 {
4062 size_t max_node_length, extra, size;
4063 drmDevicePtr device;
4064 unsigned int i;
4065 char *ptr;
4066
4067 max_node_length = ALIGN(drmGetMaxNodeName(), sizeof(void *));
4068 extra = DRM_NODE_MAX * (sizeof(void *) + max_node_length);
4069
4070 size = sizeof(*device) + extra + bus_size + device_size;
4071
4072 device = calloc(1, size);
4073 if (!device)
4074 return NULL;
4075
4076 device->available_nodes = 1 << type;
4077
4078 ptr = (char *)device + sizeof(*device);
4079 device->nodes = (char **)ptr;
4080
4081 ptr += DRM_NODE_MAX * sizeof(void *);
4082
4083 for (i = 0; i < DRM_NODE_MAX; i++) {
4084 device->nodes[i] = ptr;
4085 ptr += max_node_length;
4086 }
4087
4088 memcpy(device->nodes[type], node, max_node_length);
4089
4090 *ptrp = ptr;
4091
4092 return device;
4093 }
4094
drmProcessPciDevice(drmDevicePtr * device,const char * node,int node_type,int maj,int min,bool fetch_deviceinfo,uint32_t flags)4095 static int drmProcessPciDevice(drmDevicePtr *device,
4096 const char *node, int node_type,
4097 int maj, int min, bool fetch_deviceinfo,
4098 uint32_t flags)
4099 {
4100 drmDevicePtr dev;
4101 char *addr;
4102 int ret;
4103
4104 dev = drmDeviceAlloc(node_type, node, sizeof(drmPciBusInfo),
4105 sizeof(drmPciDeviceInfo), &addr);
4106 if (!dev)
4107 return -ENOMEM;
4108
4109 dev->bustype = DRM_BUS_PCI;
4110
4111 dev->businfo.pci = (drmPciBusInfoPtr)addr;
4112
4113 ret = drmParsePciBusInfo(maj, min, dev->businfo.pci);
4114 if (ret)
4115 goto free_device;
4116
4117 // Fetch the device info if the user has requested it
4118 if (fetch_deviceinfo) {
4119 addr += sizeof(drmPciBusInfo);
4120 dev->deviceinfo.pci = (drmPciDeviceInfoPtr)addr;
4121
4122 ret = drmParsePciDeviceInfo(maj, min, dev->deviceinfo.pci, flags);
4123 if (ret)
4124 goto free_device;
4125 }
4126
4127 *device = dev;
4128
4129 return 0;
4130
4131 free_device:
4132 free(dev);
4133 return ret;
4134 }
4135
4136 #ifdef __linux__
drm_usb_dev_path(int maj,int min,char * path,size_t len)4137 static int drm_usb_dev_path(int maj, int min, char *path, size_t len)
4138 {
4139 char *value, *tmp_path, *slash;
4140 bool usb_device, usb_interface;
4141
4142 snprintf(path, len, "/sys/dev/char/%d:%d/device", maj, min);
4143
4144 value = sysfs_uevent_get(path, "DEVTYPE");
4145 if (!value)
4146 return -ENOENT;
4147
4148 usb_device = strcmp(value, "usb_device") == 0;
4149 usb_interface = strcmp(value, "usb_interface") == 0;
4150 free(value);
4151
4152 if (usb_device)
4153 return 0;
4154 if (!usb_interface)
4155 return -ENOTSUP;
4156
4157 /* The parent of a usb_interface is a usb_device */
4158
4159 tmp_path = realpath(path, NULL);
4160 if (!tmp_path)
4161 return -errno;
4162
4163 slash = strrchr(tmp_path, '/');
4164 if (!slash) {
4165 free(tmp_path);
4166 return -EINVAL;
4167 }
4168
4169 *slash = '\0';
4170
4171 if (snprintf(path, len, "%s", tmp_path) >= (int)len) {
4172 free(tmp_path);
4173 return -EINVAL;
4174 }
4175
4176 free(tmp_path);
4177 return 0;
4178 }
4179 #endif
4180
drmParseUsbBusInfo(int maj,int min,drmUsbBusInfoPtr info)4181 static int drmParseUsbBusInfo(int maj, int min, drmUsbBusInfoPtr info)
4182 {
4183 #ifdef __linux__
4184 char path[PATH_MAX + 1], *value;
4185 unsigned int bus, dev;
4186 int ret;
4187
4188 ret = drm_usb_dev_path(maj, min, path, sizeof(path));
4189 if (ret < 0)
4190 return ret;
4191
4192 value = sysfs_uevent_get(path, "BUSNUM");
4193 if (!value)
4194 return -ENOENT;
4195
4196 ret = sscanf(value, "%03u", &bus);
4197 free(value);
4198
4199 if (ret <= 0)
4200 return -errno;
4201
4202 value = sysfs_uevent_get(path, "DEVNUM");
4203 if (!value)
4204 return -ENOENT;
4205
4206 ret = sscanf(value, "%03u", &dev);
4207 free(value);
4208
4209 if (ret <= 0)
4210 return -errno;
4211
4212 info->bus = bus;
4213 info->dev = dev;
4214
4215 return 0;
4216 #else
4217 #warning "Missing implementation of drmParseUsbBusInfo"
4218 return -EINVAL;
4219 #endif
4220 }
4221
drmParseUsbDeviceInfo(int maj,int min,drmUsbDeviceInfoPtr info)4222 static int drmParseUsbDeviceInfo(int maj, int min, drmUsbDeviceInfoPtr info)
4223 {
4224 #ifdef __linux__
4225 char path[PATH_MAX + 1], *value;
4226 unsigned int vendor, product;
4227 int ret;
4228
4229 ret = drm_usb_dev_path(maj, min, path, sizeof(path));
4230 if (ret < 0)
4231 return ret;
4232
4233 value = sysfs_uevent_get(path, "PRODUCT");
4234 if (!value)
4235 return -ENOENT;
4236
4237 ret = sscanf(value, "%x/%x", &vendor, &product);
4238 free(value);
4239
4240 if (ret <= 0)
4241 return -errno;
4242
4243 info->vendor = vendor;
4244 info->product = product;
4245
4246 return 0;
4247 #else
4248 #warning "Missing implementation of drmParseUsbDeviceInfo"
4249 return -EINVAL;
4250 #endif
4251 }
4252
drmProcessUsbDevice(drmDevicePtr * device,const char * node,int node_type,int maj,int min,bool fetch_deviceinfo,uint32_t flags)4253 static int drmProcessUsbDevice(drmDevicePtr *device, const char *node,
4254 int node_type, int maj, int min,
4255 bool fetch_deviceinfo, uint32_t flags)
4256 {
4257 drmDevicePtr dev;
4258 char *ptr;
4259 int ret;
4260
4261 dev = drmDeviceAlloc(node_type, node, sizeof(drmUsbBusInfo),
4262 sizeof(drmUsbDeviceInfo), &ptr);
4263 if (!dev)
4264 return -ENOMEM;
4265
4266 dev->bustype = DRM_BUS_USB;
4267
4268 dev->businfo.usb = (drmUsbBusInfoPtr)ptr;
4269
4270 ret = drmParseUsbBusInfo(maj, min, dev->businfo.usb);
4271 if (ret < 0)
4272 goto free_device;
4273
4274 if (fetch_deviceinfo) {
4275 ptr += sizeof(drmUsbBusInfo);
4276 dev->deviceinfo.usb = (drmUsbDeviceInfoPtr)ptr;
4277
4278 ret = drmParseUsbDeviceInfo(maj, min, dev->deviceinfo.usb);
4279 if (ret < 0)
4280 goto free_device;
4281 }
4282
4283 *device = dev;
4284
4285 return 0;
4286
4287 free_device:
4288 free(dev);
4289 return ret;
4290 }
4291
drmParseOFBusInfo(int maj,int min,char * fullname)4292 static int drmParseOFBusInfo(int maj, int min, char *fullname)
4293 {
4294 #ifdef __linux__
4295 char path[PATH_MAX + 1], *name, *tmp_name;
4296
4297 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
4298
4299 name = sysfs_uevent_get(path, "OF_FULLNAME");
4300 tmp_name = name;
4301 if (!name) {
4302 /* If the device lacks OF data, pick the MODALIAS info */
4303 name = sysfs_uevent_get(path, "MODALIAS");
4304 if (!name)
4305 return -ENOENT;
4306
4307 /* .. and strip the MODALIAS=[platform,usb...]: part. */
4308 tmp_name = strrchr(name, ':');
4309 if (!tmp_name) {
4310 free(name);
4311 return -ENOENT;
4312 }
4313 tmp_name++;
4314 }
4315
4316 strncpy(fullname, tmp_name, DRM_PLATFORM_DEVICE_NAME_LEN);
4317 fullname[DRM_PLATFORM_DEVICE_NAME_LEN - 1] = '\0';
4318 free(name);
4319
4320 return 0;
4321 #else
4322 #warning "Missing implementation of drmParseOFBusInfo"
4323 return -EINVAL;
4324 #endif
4325 }
4326
drmParseOFDeviceInfo(int maj,int min,char *** compatible)4327 static int drmParseOFDeviceInfo(int maj, int min, char ***compatible)
4328 {
4329 #ifdef __linux__
4330 char path[PATH_MAX + 1], *value, *tmp_name;
4331 unsigned int count, i;
4332 int err;
4333
4334 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d/device", maj, min);
4335
4336 value = sysfs_uevent_get(path, "OF_COMPATIBLE_N");
4337 if (value) {
4338 sscanf(value, "%u", &count);
4339 free(value);
4340 } else {
4341 /* Assume one entry if the device lack OF data */
4342 count = 1;
4343 }
4344
4345 *compatible = calloc(count + 1, sizeof(char *));
4346 if (!*compatible)
4347 return -ENOMEM;
4348
4349 for (i = 0; i < count; i++) {
4350 value = sysfs_uevent_get(path, "OF_COMPATIBLE_%u", i);
4351 tmp_name = value;
4352 if (!value) {
4353 /* If the device lacks OF data, pick the MODALIAS info */
4354 value = sysfs_uevent_get(path, "MODALIAS");
4355 if (!value) {
4356 err = -ENOENT;
4357 goto free;
4358 }
4359
4360 /* .. and strip the MODALIAS=[platform,usb...]: part. */
4361 tmp_name = strrchr(value, ':');
4362 if (!tmp_name) {
4363 free(value);
4364 return -ENOENT;
4365 }
4366 tmp_name = strdup(tmp_name + 1);
4367 free(value);
4368 }
4369
4370 (*compatible)[i] = tmp_name;
4371 }
4372
4373 return 0;
4374
4375 free:
4376 while (i--)
4377 free((*compatible)[i]);
4378
4379 free(*compatible);
4380 return err;
4381 #else
4382 #warning "Missing implementation of drmParseOFDeviceInfo"
4383 return -EINVAL;
4384 #endif
4385 }
4386
drmProcessPlatformDevice(drmDevicePtr * device,const char * node,int node_type,int maj,int min,bool fetch_deviceinfo,uint32_t flags)4387 static int drmProcessPlatformDevice(drmDevicePtr *device,
4388 const char *node, int node_type,
4389 int maj, int min, bool fetch_deviceinfo,
4390 uint32_t flags)
4391 {
4392 drmDevicePtr dev;
4393 char *ptr;
4394 int ret;
4395
4396 dev = drmDeviceAlloc(node_type, node, sizeof(drmPlatformBusInfo),
4397 sizeof(drmPlatformDeviceInfo), &ptr);
4398 if (!dev)
4399 return -ENOMEM;
4400
4401 dev->bustype = DRM_BUS_PLATFORM;
4402
4403 dev->businfo.platform = (drmPlatformBusInfoPtr)ptr;
4404
4405 ret = drmParseOFBusInfo(maj, min, dev->businfo.platform->fullname);
4406 if (ret < 0)
4407 goto free_device;
4408
4409 if (fetch_deviceinfo) {
4410 ptr += sizeof(drmPlatformBusInfo);
4411 dev->deviceinfo.platform = (drmPlatformDeviceInfoPtr)ptr;
4412
4413 ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.platform->compatible);
4414 if (ret < 0)
4415 goto free_device;
4416 }
4417
4418 *device = dev;
4419
4420 return 0;
4421
4422 free_device:
4423 free(dev);
4424 return ret;
4425 }
4426
drmProcessHost1xDevice(drmDevicePtr * device,const char * node,int node_type,int maj,int min,bool fetch_deviceinfo,uint32_t flags)4427 static int drmProcessHost1xDevice(drmDevicePtr *device,
4428 const char *node, int node_type,
4429 int maj, int min, bool fetch_deviceinfo,
4430 uint32_t flags)
4431 {
4432 drmDevicePtr dev;
4433 char *ptr;
4434 int ret;
4435
4436 dev = drmDeviceAlloc(node_type, node, sizeof(drmHost1xBusInfo),
4437 sizeof(drmHost1xDeviceInfo), &ptr);
4438 if (!dev)
4439 return -ENOMEM;
4440
4441 dev->bustype = DRM_BUS_HOST1X;
4442
4443 dev->businfo.host1x = (drmHost1xBusInfoPtr)ptr;
4444
4445 ret = drmParseOFBusInfo(maj, min, dev->businfo.host1x->fullname);
4446 if (ret < 0)
4447 goto free_device;
4448
4449 if (fetch_deviceinfo) {
4450 ptr += sizeof(drmHost1xBusInfo);
4451 dev->deviceinfo.host1x = (drmHost1xDeviceInfoPtr)ptr;
4452
4453 ret = drmParseOFDeviceInfo(maj, min, &dev->deviceinfo.host1x->compatible);
4454 if (ret < 0)
4455 goto free_device;
4456 }
4457
4458 *device = dev;
4459
4460 return 0;
4461
4462 free_device:
4463 free(dev);
4464 return ret;
4465 }
4466
4467 static int
process_device(drmDevicePtr * device,const char * d_name,int req_subsystem_type,bool fetch_deviceinfo,uint32_t flags)4468 process_device(drmDevicePtr *device, const char *d_name,
4469 int req_subsystem_type,
4470 bool fetch_deviceinfo, uint32_t flags)
4471 {
4472 struct stat sbuf;
4473 char node[PATH_MAX + 1];
4474 int node_type, subsystem_type;
4475 unsigned int maj, min;
4476
4477 node_type = drmGetNodeType(d_name);
4478 if (node_type < 0)
4479 return -1;
4480
4481 snprintf(node, PATH_MAX, "%s/%s", DRM_DIR_NAME, d_name);
4482 if (stat(node, &sbuf))
4483 return -1;
4484
4485 maj = major(sbuf.st_rdev);
4486 min = minor(sbuf.st_rdev);
4487
4488 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4489 return -1;
4490
4491 subsystem_type = drmParseSubsystemType(maj, min);
4492 if (req_subsystem_type != -1 && req_subsystem_type != subsystem_type)
4493 return -1;
4494
4495 switch (subsystem_type) {
4496 case DRM_BUS_PCI:
4497 case DRM_BUS_VIRTIO:
4498 return drmProcessPciDevice(device, node, node_type, maj, min,
4499 fetch_deviceinfo, flags);
4500 case DRM_BUS_USB:
4501 return drmProcessUsbDevice(device, node, node_type, maj, min,
4502 fetch_deviceinfo, flags);
4503 case DRM_BUS_PLATFORM:
4504 return drmProcessPlatformDevice(device, node, node_type, maj, min,
4505 fetch_deviceinfo, flags);
4506 case DRM_BUS_HOST1X:
4507 return drmProcessHost1xDevice(device, node, node_type, maj, min,
4508 fetch_deviceinfo, flags);
4509 default:
4510 return -1;
4511 }
4512 }
4513
4514 /* Consider devices located on the same bus as duplicate and fold the respective
4515 * entries into a single one.
4516 *
4517 * Note: this leaves "gaps" in the array, while preserving the length.
4518 */
drmFoldDuplicatedDevices(drmDevicePtr local_devices[],int count)4519 static void drmFoldDuplicatedDevices(drmDevicePtr local_devices[], int count)
4520 {
4521 int node_type, i, j;
4522
4523 for (i = 0; i < count; i++) {
4524 for (j = i + 1; j < count; j++) {
4525 if (drmDevicesEqual(local_devices[i], local_devices[j])) {
4526 local_devices[i]->available_nodes |= local_devices[j]->available_nodes;
4527 node_type = log2_int(local_devices[j]->available_nodes);
4528 memcpy(local_devices[i]->nodes[node_type],
4529 local_devices[j]->nodes[node_type], drmGetMaxNodeName());
4530 drmFreeDevice(&local_devices[j]);
4531 }
4532 }
4533 }
4534 }
4535
4536 /* Check that the given flags are valid returning 0 on success */
4537 static int
drm_device_validate_flags(uint32_t flags)4538 drm_device_validate_flags(uint32_t flags)
4539 {
4540 return (flags & ~DRM_DEVICE_GET_PCI_REVISION);
4541 }
4542
4543 static bool
drm_device_has_rdev(drmDevicePtr device,dev_t find_rdev)4544 drm_device_has_rdev(drmDevicePtr device, dev_t find_rdev)
4545 {
4546 struct stat sbuf;
4547
4548 for (int i = 0; i < DRM_NODE_MAX; i++) {
4549 if (device->available_nodes & 1 << i) {
4550 if (stat(device->nodes[i], &sbuf) == 0 &&
4551 sbuf.st_rdev == find_rdev)
4552 return true;
4553 }
4554 }
4555 return false;
4556 }
4557
4558 /*
4559 * The kernel drm core has a number of places that assume maximum of
4560 * 3x64 devices nodes. That's 64 for each of primary, control and
4561 * render nodes. Rounded it up to 256 for simplicity.
4562 */
4563 #define MAX_DRM_NODES 256
4564
4565 /**
4566 * Get information about a device from its dev_t identifier
4567 *
4568 * \param find_rdev dev_t identifier of the device
4569 * \param flags feature/behaviour bitmask
4570 * \param device the address of a drmDevicePtr where the information
4571 * will be allocated in stored
4572 *
4573 * \return zero on success, negative error code otherwise.
4574 */
drmGetDeviceFromDevId(dev_t find_rdev,uint32_t flags,drmDevicePtr * device)4575 drm_public int drmGetDeviceFromDevId(dev_t find_rdev, uint32_t flags, drmDevicePtr *device)
4576 {
4577 #ifdef __OpenBSD__
4578 /*
4579 * DRI device nodes on OpenBSD are not in their own directory, they reside
4580 * in /dev along with a large number of statically generated /dev nodes.
4581 * Avoid stat'ing all of /dev needlessly by implementing this custom path.
4582 */
4583 drmDevicePtr d;
4584 char node[PATH_MAX + 1];
4585 const char *dev_name;
4586 int node_type, subsystem_type;
4587 int maj, min, n, ret;
4588
4589 if (device == NULL)
4590 return -EINVAL;
4591
4592 maj = major(find_rdev);
4593 min = minor(find_rdev);
4594
4595 if (!drmNodeIsDRM(maj, min))
4596 return -EINVAL;
4597
4598 node_type = drmGetMinorType(maj, min);
4599 if (node_type == -1)
4600 return -ENODEV;
4601
4602 dev_name = drmGetDeviceName(node_type);
4603 if (!dev_name)
4604 return -EINVAL;
4605
4606 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min);
4607 if (n == -1 || n >= PATH_MAX)
4608 return -errno;
4609 if (stat(node, &sbuf))
4610 return -EINVAL;
4611
4612 subsystem_type = drmParseSubsystemType(maj, min);
4613 if (subsystem_type != DRM_BUS_PCI)
4614 return -ENODEV;
4615
4616 ret = drmProcessPciDevice(&d, node, node_type, maj, min, true, flags);
4617 if (ret)
4618 return ret;
4619
4620 *device = d;
4621
4622 return 0;
4623 #else
4624 drmDevicePtr local_devices[MAX_DRM_NODES];
4625 drmDevicePtr d;
4626 DIR *sysdir;
4627 struct dirent *dent;
4628 int subsystem_type;
4629 int maj, min;
4630 int ret, i, node_count;
4631
4632 if (drm_device_validate_flags(flags))
4633 return -EINVAL;
4634
4635 if (device == NULL)
4636 return -EINVAL;
4637
4638 maj = major(find_rdev);
4639 min = minor(find_rdev);
4640
4641 if (!drmNodeIsDRM(maj, min))
4642 return -EINVAL;
4643
4644 subsystem_type = drmParseSubsystemType(maj, min);
4645 if (subsystem_type < 0)
4646 return subsystem_type;
4647
4648 sysdir = opendir(DRM_DIR_NAME);
4649 if (!sysdir)
4650 return -errno;
4651
4652 i = 0;
4653 while ((dent = readdir(sysdir))) {
4654 ret = process_device(&d, dent->d_name, subsystem_type, true, flags);
4655 if (ret)
4656 continue;
4657
4658 if (i >= MAX_DRM_NODES) {
4659 fprintf(stderr, "More than %d drm nodes detected. "
4660 "Please report a bug - that should not happen.\n"
4661 "Skipping extra nodes\n", MAX_DRM_NODES);
4662 break;
4663 }
4664 local_devices[i] = d;
4665 i++;
4666 }
4667 node_count = i;
4668
4669 drmFoldDuplicatedDevices(local_devices, node_count);
4670
4671 *device = NULL;
4672
4673 for (i = 0; i < node_count; i++) {
4674 if (!local_devices[i])
4675 continue;
4676
4677 if (drm_device_has_rdev(local_devices[i], find_rdev))
4678 *device = local_devices[i];
4679 else
4680 drmFreeDevice(&local_devices[i]);
4681 }
4682
4683 closedir(sysdir);
4684 if (*device == NULL)
4685 return -ENODEV;
4686 return 0;
4687 #endif
4688 }
4689
drmGetNodeTypeFromDevId(dev_t devid)4690 drm_public int drmGetNodeTypeFromDevId(dev_t devid)
4691 {
4692 int maj, min, node_type;
4693
4694 maj = major(devid);
4695 min = minor(devid);
4696
4697 if (!drmNodeIsDRM(maj, min))
4698 return -EINVAL;
4699
4700 node_type = drmGetMinorType(maj, min);
4701 if (node_type == -1)
4702 return -ENODEV;
4703
4704 return node_type;
4705 }
4706
4707 /**
4708 * Get information about the opened drm device
4709 *
4710 * \param fd file descriptor of the drm device
4711 * \param flags feature/behaviour bitmask
4712 * \param device the address of a drmDevicePtr where the information
4713 * will be allocated in stored
4714 *
4715 * \return zero on success, negative error code otherwise.
4716 *
4717 * \note Unlike drmGetDevice it does not retrieve the pci device revision field
4718 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
4719 */
drmGetDevice2(int fd,uint32_t flags,drmDevicePtr * device)4720 drm_public int drmGetDevice2(int fd, uint32_t flags, drmDevicePtr *device)
4721 {
4722 struct stat sbuf;
4723
4724 if (fd == -1)
4725 return -EINVAL;
4726
4727 if (fstat(fd, &sbuf))
4728 return -errno;
4729
4730 if (!S_ISCHR(sbuf.st_mode))
4731 return -EINVAL;
4732
4733 return drmGetDeviceFromDevId(sbuf.st_rdev, flags, device);
4734 }
4735
4736 /**
4737 * Get information about the opened drm device
4738 *
4739 * \param fd file descriptor of the drm device
4740 * \param device the address of a drmDevicePtr where the information
4741 * will be allocated in stored
4742 *
4743 * \return zero on success, negative error code otherwise.
4744 */
drmGetDevice(int fd,drmDevicePtr * device)4745 drm_public int drmGetDevice(int fd, drmDevicePtr *device)
4746 {
4747 return drmGetDevice2(fd, DRM_DEVICE_GET_PCI_REVISION, device);
4748 }
4749
4750 /**
4751 * Get drm devices on the system
4752 *
4753 * \param flags feature/behaviour bitmask
4754 * \param devices the array of devices with drmDevicePtr elements
4755 * can be NULL to get the device number first
4756 * \param max_devices the maximum number of devices for the array
4757 *
4758 * \return on error - negative error code,
4759 * if devices is NULL - total number of devices available on the system,
4760 * alternatively the number of devices stored in devices[], which is
4761 * capped by the max_devices.
4762 *
4763 * \note Unlike drmGetDevices it does not retrieve the pci device revision field
4764 * unless the DRM_DEVICE_GET_PCI_REVISION \p flag is set.
4765 */
drmGetDevices2(uint32_t flags,drmDevicePtr devices[],int max_devices)4766 drm_public int drmGetDevices2(uint32_t flags, drmDevicePtr devices[],
4767 int max_devices)
4768 {
4769 drmDevicePtr local_devices[MAX_DRM_NODES];
4770 drmDevicePtr device;
4771 DIR *sysdir;
4772 struct dirent *dent;
4773 int ret, i, node_count, device_count;
4774
4775 if (drm_device_validate_flags(flags))
4776 return -EINVAL;
4777
4778 sysdir = opendir(DRM_DIR_NAME);
4779 if (!sysdir)
4780 return -errno;
4781
4782 i = 0;
4783 while ((dent = readdir(sysdir))) {
4784 ret = process_device(&device, dent->d_name, -1, devices != NULL, flags);
4785 if (ret)
4786 continue;
4787
4788 if (i >= MAX_DRM_NODES) {
4789 fprintf(stderr, "More than %d drm nodes detected. "
4790 "Please report a bug - that should not happen.\n"
4791 "Skipping extra nodes\n", MAX_DRM_NODES);
4792 break;
4793 }
4794 local_devices[i] = device;
4795 i++;
4796 }
4797 node_count = i;
4798
4799 drmFoldDuplicatedDevices(local_devices, node_count);
4800
4801 device_count = 0;
4802 for (i = 0; i < node_count; i++) {
4803 if (!local_devices[i])
4804 continue;
4805
4806 if ((devices != NULL) && (device_count < max_devices))
4807 devices[device_count] = local_devices[i];
4808 else
4809 drmFreeDevice(&local_devices[i]);
4810
4811 device_count++;
4812 }
4813
4814 closedir(sysdir);
4815
4816 if (devices != NULL)
4817 return MIN2(device_count, max_devices);
4818
4819 return device_count;
4820 }
4821
4822 /**
4823 * Get drm devices on the system
4824 *
4825 * \param devices the array of devices with drmDevicePtr elements
4826 * can be NULL to get the device number first
4827 * \param max_devices the maximum number of devices for the array
4828 *
4829 * \return on error - negative error code,
4830 * if devices is NULL - total number of devices available on the system,
4831 * alternatively the number of devices stored in devices[], which is
4832 * capped by the max_devices.
4833 */
drmGetDevices(drmDevicePtr devices[],int max_devices)4834 drm_public int drmGetDevices(drmDevicePtr devices[], int max_devices)
4835 {
4836 return drmGetDevices2(DRM_DEVICE_GET_PCI_REVISION, devices, max_devices);
4837 }
4838
drmGetDeviceNameFromFd2(int fd)4839 drm_public char *drmGetDeviceNameFromFd2(int fd)
4840 {
4841 #ifdef __linux__
4842 struct stat sbuf;
4843 char path[PATH_MAX + 1], *value;
4844 unsigned int maj, min;
4845
4846 if (fstat(fd, &sbuf))
4847 return NULL;
4848
4849 maj = major(sbuf.st_rdev);
4850 min = minor(sbuf.st_rdev);
4851
4852 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4853 return NULL;
4854
4855 snprintf(path, sizeof(path), "/sys/dev/char/%d:%d", maj, min);
4856
4857 value = sysfs_uevent_get(path, "DEVNAME");
4858 if (!value)
4859 return NULL;
4860
4861 snprintf(path, sizeof(path), "/dev/%s", value);
4862 free(value);
4863
4864 return strdup(path);
4865 #elif defined(__FreeBSD__)
4866 return drmGetDeviceNameFromFd(fd);
4867 #else
4868 struct stat sbuf;
4869 char node[PATH_MAX + 1];
4870 const char *dev_name;
4871 int node_type;
4872 int maj, min, n;
4873
4874 if (fstat(fd, &sbuf))
4875 return NULL;
4876
4877 maj = major(sbuf.st_rdev);
4878 min = minor(sbuf.st_rdev);
4879
4880 if (!drmNodeIsDRM(maj, min) || !S_ISCHR(sbuf.st_mode))
4881 return NULL;
4882
4883 node_type = drmGetMinorType(maj, min);
4884 if (node_type == -1)
4885 return NULL;
4886
4887 dev_name = drmGetDeviceName(node_type);
4888 if (!dev_name)
4889 return NULL;
4890
4891 n = snprintf(node, PATH_MAX, dev_name, DRM_DIR_NAME, min);
4892 if (n == -1 || n >= PATH_MAX)
4893 return NULL;
4894
4895 return strdup(node);
4896 #endif
4897 }
4898
drmSyncobjCreate(int fd,uint32_t flags,uint32_t * handle)4899 drm_public int drmSyncobjCreate(int fd, uint32_t flags, uint32_t *handle)
4900 {
4901 struct drm_syncobj_create args;
4902 int ret;
4903
4904 memclear(args);
4905 args.flags = flags;
4906 args.handle = 0;
4907 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_CREATE, &args);
4908 if (ret)
4909 return ret;
4910 *handle = args.handle;
4911 return 0;
4912 }
4913
drmSyncobjDestroy(int fd,uint32_t handle)4914 drm_public int drmSyncobjDestroy(int fd, uint32_t handle)
4915 {
4916 struct drm_syncobj_destroy args;
4917
4918 memclear(args);
4919 args.handle = handle;
4920 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_DESTROY, &args);
4921 }
4922
drmSyncobjHandleToFD(int fd,uint32_t handle,int * obj_fd)4923 drm_public int drmSyncobjHandleToFD(int fd, uint32_t handle, int *obj_fd)
4924 {
4925 struct drm_syncobj_handle args;
4926 int ret;
4927
4928 memclear(args);
4929 args.fd = -1;
4930 args.handle = handle;
4931 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4932 if (ret)
4933 return ret;
4934 *obj_fd = args.fd;
4935 return 0;
4936 }
4937
drmSyncobjFDToHandle(int fd,int obj_fd,uint32_t * handle)4938 drm_public int drmSyncobjFDToHandle(int fd, int obj_fd, uint32_t *handle)
4939 {
4940 struct drm_syncobj_handle args;
4941 int ret;
4942
4943 memclear(args);
4944 args.fd = obj_fd;
4945 args.handle = 0;
4946 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4947 if (ret)
4948 return ret;
4949 *handle = args.handle;
4950 return 0;
4951 }
4952
drmSyncobjImportSyncFile(int fd,uint32_t handle,int sync_file_fd)4953 drm_public int drmSyncobjImportSyncFile(int fd, uint32_t handle,
4954 int sync_file_fd)
4955 {
4956 struct drm_syncobj_handle args;
4957
4958 memclear(args);
4959 args.fd = sync_file_fd;
4960 args.handle = handle;
4961 args.flags = DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE;
4962 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE, &args);
4963 }
4964
drmSyncobjExportSyncFile(int fd,uint32_t handle,int * sync_file_fd)4965 drm_public int drmSyncobjExportSyncFile(int fd, uint32_t handle,
4966 int *sync_file_fd)
4967 {
4968 struct drm_syncobj_handle args;
4969 int ret;
4970
4971 memclear(args);
4972 args.fd = -1;
4973 args.handle = handle;
4974 args.flags = DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE;
4975 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD, &args);
4976 if (ret)
4977 return ret;
4978 *sync_file_fd = args.fd;
4979 return 0;
4980 }
4981
drmSyncobjWait(int fd,uint32_t * handles,unsigned num_handles,int64_t timeout_nsec,unsigned flags,uint32_t * first_signaled)4982 drm_public int drmSyncobjWait(int fd, uint32_t *handles, unsigned num_handles,
4983 int64_t timeout_nsec, unsigned flags,
4984 uint32_t *first_signaled)
4985 {
4986 struct drm_syncobj_wait args;
4987 int ret;
4988
4989 memclear(args);
4990 args.handles = (uintptr_t)handles;
4991 args.timeout_nsec = timeout_nsec;
4992 args.count_handles = num_handles;
4993 args.flags = flags;
4994
4995 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_WAIT, &args);
4996 if (ret < 0)
4997 return -errno;
4998
4999 if (first_signaled)
5000 *first_signaled = args.first_signaled;
5001 return ret;
5002 }
5003
drmSyncobjReset(int fd,const uint32_t * handles,uint32_t handle_count)5004 drm_public int drmSyncobjReset(int fd, const uint32_t *handles,
5005 uint32_t handle_count)
5006 {
5007 struct drm_syncobj_array args;
5008 int ret;
5009
5010 memclear(args);
5011 args.handles = (uintptr_t)handles;
5012 args.count_handles = handle_count;
5013
5014 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_RESET, &args);
5015 return ret;
5016 }
5017
drmSyncobjSignal(int fd,const uint32_t * handles,uint32_t handle_count)5018 drm_public int drmSyncobjSignal(int fd, const uint32_t *handles,
5019 uint32_t handle_count)
5020 {
5021 struct drm_syncobj_array args;
5022 int ret;
5023
5024 memclear(args);
5025 args.handles = (uintptr_t)handles;
5026 args.count_handles = handle_count;
5027
5028 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_SIGNAL, &args);
5029 return ret;
5030 }
5031
drmSyncobjTimelineSignal(int fd,const uint32_t * handles,uint64_t * points,uint32_t handle_count)5032 drm_public int drmSyncobjTimelineSignal(int fd, const uint32_t *handles,
5033 uint64_t *points, uint32_t handle_count)
5034 {
5035 struct drm_syncobj_timeline_array args;
5036 int ret;
5037
5038 memclear(args);
5039 args.handles = (uintptr_t)handles;
5040 args.points = (uintptr_t)points;
5041 args.count_handles = handle_count;
5042
5043 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TIMELINE_SIGNAL, &args);
5044 return ret;
5045 }
5046
drmSyncobjTimelineWait(int fd,uint32_t * handles,uint64_t * points,unsigned num_handles,int64_t timeout_nsec,unsigned flags,uint32_t * first_signaled)5047 drm_public int drmSyncobjTimelineWait(int fd, uint32_t *handles, uint64_t *points,
5048 unsigned num_handles,
5049 int64_t timeout_nsec, unsigned flags,
5050 uint32_t *first_signaled)
5051 {
5052 struct drm_syncobj_timeline_wait args;
5053 int ret;
5054
5055 memclear(args);
5056 args.handles = (uintptr_t)handles;
5057 args.points = (uintptr_t)points;
5058 args.timeout_nsec = timeout_nsec;
5059 args.count_handles = num_handles;
5060 args.flags = flags;
5061
5062 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TIMELINE_WAIT, &args);
5063 if (ret < 0)
5064 return -errno;
5065
5066 if (first_signaled)
5067 *first_signaled = args.first_signaled;
5068 return ret;
5069 }
5070
5071
drmSyncobjQuery(int fd,uint32_t * handles,uint64_t * points,uint32_t handle_count)5072 drm_public int drmSyncobjQuery(int fd, uint32_t *handles, uint64_t *points,
5073 uint32_t handle_count)
5074 {
5075 struct drm_syncobj_timeline_array args;
5076 int ret;
5077
5078 memclear(args);
5079 args.handles = (uintptr_t)handles;
5080 args.points = (uintptr_t)points;
5081 args.count_handles = handle_count;
5082
5083 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_QUERY, &args);
5084 if (ret)
5085 return ret;
5086 return 0;
5087 }
5088
drmSyncobjQuery2(int fd,uint32_t * handles,uint64_t * points,uint32_t handle_count,uint32_t flags)5089 drm_public int drmSyncobjQuery2(int fd, uint32_t *handles, uint64_t *points,
5090 uint32_t handle_count, uint32_t flags)
5091 {
5092 struct drm_syncobj_timeline_array args;
5093
5094 memclear(args);
5095 args.handles = (uintptr_t)handles;
5096 args.points = (uintptr_t)points;
5097 args.count_handles = handle_count;
5098 args.flags = flags;
5099
5100 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_QUERY, &args);
5101 }
5102
5103
drmSyncobjTransfer(int fd,uint32_t dst_handle,uint64_t dst_point,uint32_t src_handle,uint64_t src_point,uint32_t flags)5104 drm_public int drmSyncobjTransfer(int fd,
5105 uint32_t dst_handle, uint64_t dst_point,
5106 uint32_t src_handle, uint64_t src_point,
5107 uint32_t flags)
5108 {
5109 struct drm_syncobj_transfer args;
5110 int ret;
5111
5112 memclear(args);
5113 args.src_handle = src_handle;
5114 args.dst_handle = dst_handle;
5115 args.src_point = src_point;
5116 args.dst_point = dst_point;
5117 args.flags = flags;
5118
5119 ret = drmIoctl(fd, DRM_IOCTL_SYNCOBJ_TRANSFER, &args);
5120
5121 return ret;
5122 }
5123
drmSyncobjEventfd(int fd,uint32_t handle,uint64_t point,int ev_fd,uint32_t flags)5124 drm_public int drmSyncobjEventfd(int fd, uint32_t handle, uint64_t point, int ev_fd,
5125 uint32_t flags)
5126 {
5127 struct drm_syncobj_eventfd args;
5128
5129 memclear(args);
5130 args.handle = handle;
5131 args.point = point;
5132 args.fd = ev_fd;
5133 args.flags = flags;
5134
5135 return drmIoctl(fd, DRM_IOCTL_SYNCOBJ_EVENTFD, &args);
5136 }
5137
5138 static char *
drmGetFormatModifierFromSimpleTokens(uint64_t modifier)5139 drmGetFormatModifierFromSimpleTokens(uint64_t modifier)
5140 {
5141 unsigned int i;
5142
5143 for (i = 0; i < ARRAY_SIZE(drm_format_modifier_table); i++) {
5144 if (drm_format_modifier_table[i].modifier == modifier)
5145 return strdup(drm_format_modifier_table[i].modifier_name);
5146 }
5147
5148 return NULL;
5149 }
5150
5151 /** Retrieves a human-readable representation of a vendor (as a string) from
5152 * the format token modifier
5153 *
5154 * \param modifier the format modifier token
5155 * \return a char pointer to the human-readable form of the vendor. Caller is
5156 * responsible for freeing it.
5157 */
5158 drm_public char *
drmGetFormatModifierVendor(uint64_t modifier)5159 drmGetFormatModifierVendor(uint64_t modifier)
5160 {
5161 unsigned int i;
5162 uint8_t vendor = fourcc_mod_get_vendor(modifier);
5163
5164 for (i = 0; i < ARRAY_SIZE(drm_format_modifier_vendor_table); i++) {
5165 if (drm_format_modifier_vendor_table[i].vendor == vendor)
5166 return strdup(drm_format_modifier_vendor_table[i].vendor_name);
5167 }
5168
5169 return NULL;
5170 }
5171
5172 /** Retrieves a human-readable representation string from a format token
5173 * modifier
5174 *
5175 * If the dedicated function was not able to extract a valid name or searching
5176 * the format modifier was not in the table, this function would return NULL.
5177 *
5178 * \param modifier the token format
5179 * \return a malloc'ed string representation of the modifier. Caller is
5180 * responsible for freeing the string returned.
5181 *
5182 */
5183 drm_public char *
drmGetFormatModifierName(uint64_t modifier)5184 drmGetFormatModifierName(uint64_t modifier)
5185 {
5186 uint8_t vendorid = fourcc_mod_get_vendor(modifier);
5187 char *modifier_found = NULL;
5188 unsigned int i;
5189
5190 for (i = 0; i < ARRAY_SIZE(modifier_format_vendor_table); i++) {
5191 if (modifier_format_vendor_table[i].vendor == vendorid)
5192 modifier_found = modifier_format_vendor_table[i].vendor_cb(modifier);
5193 }
5194
5195 if (!modifier_found)
5196 return drmGetFormatModifierFromSimpleTokens(modifier);
5197
5198 return modifier_found;
5199 }
5200
5201 /**
5202 * Get a human-readable name for a DRM FourCC format.
5203 *
5204 * \param format The format.
5205 * \return A malloc'ed string containing the format name. Caller is responsible
5206 * for freeing it.
5207 */
5208 drm_public char *
drmGetFormatName(uint32_t format)5209 drmGetFormatName(uint32_t format)
5210 {
5211 char *str, code[5];
5212 const char *be;
5213 size_t str_size, i;
5214
5215 be = (format & DRM_FORMAT_BIG_ENDIAN) ? "_BE" : "";
5216 format &= ~DRM_FORMAT_BIG_ENDIAN;
5217
5218 if (format == DRM_FORMAT_INVALID)
5219 return strdup("INVALID");
5220
5221 code[0] = (char) ((format >> 0) & 0xFF);
5222 code[1] = (char) ((format >> 8) & 0xFF);
5223 code[2] = (char) ((format >> 16) & 0xFF);
5224 code[3] = (char) ((format >> 24) & 0xFF);
5225 code[4] = '\0';
5226
5227 /* Trim spaces at the end */
5228 for (i = 3; i > 0 && code[i] == ' '; i--)
5229 code[i] = '\0';
5230
5231 str_size = strlen(code) + strlen(be) + 1;
5232 str = malloc(str_size);
5233 if (!str)
5234 return NULL;
5235
5236 snprintf(str, str_size, "%s%s", code, be);
5237
5238 return str;
5239 }
5240