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