• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**************************************************************************
2  *
3  * Copyright 2008 Dennis Smit
4  * All Rights Reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * on the rights to use, copy, modify, merge, publish, distribute, sub
10  * license, and/or sell copies of the Software, and to permit persons to whom
11  * the Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice (including the next
14  * paragraph) shall be included in all copies or substantial portions of the
15  * Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.  IN NO EVENT SHALL
20  * AUTHORS, COPYRIGHT HOLDERS, AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
21  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
22  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
23  * USE OR OTHER DEALINGS IN THE SOFTWARE.
24  *
25  **************************************************************************/
26 
27 /**
28  * @file
29  * CPU feature detection.
30  *
31  * @author Dennis Smit
32  * @author Based on the work of Eric Anholt <anholt@FreeBSD.org>
33  */
34 
35 #include "util/detect.h"
36 #include "util/compiler.h"
37 
38 #include "util/u_debug.h"
39 #include "u_cpu_detect.h"
40 #include "u_math.h"
41 #include "os_file.h"
42 #include "c11/threads.h"
43 
44 #include <stdio.h>
45 #include <inttypes.h>
46 
47 #if DETECT_ARCH_PPC
48 #if DETECT_OS_APPLE
49 #include <sys/sysctl.h>
50 #else
51 #include <signal.h>
52 #include <setjmp.h>
53 #endif
54 #endif
55 
56 #if DETECT_OS_BSD
57 #include <sys/param.h>
58 #include <sys/sysctl.h>
59 #include <machine/cpu.h>
60 #endif
61 
62 #if DETECT_OS_FREEBSD || DETECT_OS_OPENBSD
63 #if __has_include(<sys/auxv.h>)
64 #include <sys/auxv.h>
65 #define HAVE_ELF_AUX_INFO
66 #endif
67 #endif
68 
69 #if DETECT_OS_LINUX
70 #include <signal.h>
71 #include <fcntl.h>
72 #include <elf.h>
73 #endif
74 
75 #if DETECT_OS_POSIX
76 #include <unistd.h>
77 #endif
78 
79 #if defined(HAS_ANDROID_CPUFEATURES)
80 #include <cpu-features.h>
81 #endif
82 
83 #if DETECT_OS_WINDOWS
84 #include <windows.h>
85 #if DETECT_CC_MSVC
86 #include <intrin.h>
87 #endif
88 #endif
89 
90 #if defined(HAS_SCHED_H)
91 #include <sched.h>
92 #endif
93 
94 // prevent inadvert infinite recursion
95 #define util_get_cpu_caps() util_get_cpu_caps_DO_NOT_USE()
96 
97 DEBUG_GET_ONCE_BOOL_OPTION(dump_cpu, "GALLIUM_DUMP_CPU", false)
98 
99 static
100 struct util_cpu_caps_t util_cpu_caps;
101 
102 /* Do not try to access _util_cpu_caps_state directly, call to util_get_cpu_caps instead */
103 struct _util_cpu_caps_state_t _util_cpu_caps_state = {
104    .once_flag = ONCE_FLAG_INIT,
105    .detect_done = 0,
106 };
107 
108 #if DETECT_ARCH_X86 || DETECT_ARCH_X86_64
109 static int has_cpuid(void);
110 #endif
111 
112 
113 #if DETECT_ARCH_PPC && !DETECT_OS_APPLE && !DETECT_OS_BSD && !DETECT_OS_LINUX
114 static jmp_buf  __lv_powerpc_jmpbuf;
115 static volatile sig_atomic_t __lv_powerpc_canjump = 0;
116 
117 static void
sigill_handler(int sig)118 sigill_handler(int sig)
119 {
120    if (!__lv_powerpc_canjump) {
121       signal (sig, SIG_DFL);
122       raise (sig);
123    }
124 
125    __lv_powerpc_canjump = 0;
126    longjmp(__lv_powerpc_jmpbuf, 1);
127 }
128 #endif
129 
130 #if DETECT_ARCH_PPC
131 static void
check_os_altivec_support(void)132 check_os_altivec_support(void)
133 {
134 #if defined(__ALTIVEC__)
135    util_cpu_caps.has_altivec = 1;
136 #endif
137 #if defined(__VSX__)
138    util_cpu_caps.has_vsx = 1;
139 #endif
140 #if defined(__ALTIVEC__) && defined(__VSX__)
141 /* Do nothing */
142 #elif DETECT_OS_FREEBSD || (DETECT_OS_OPENBSD && HAVE_ELF_AUX_INFO) /* !__ALTIVEC__ || !__VSX__ */
143    unsigned long hwcap = 0;
144 #ifdef HAVE_ELF_AUX_INFO
145    elf_aux_info(AT_HWCAP, &hwcap, sizeof(hwcap));
146 #elif DETECT_OS_FREEBSD
147    size_t len = sizeof(hwcap);
148    sysctlbyname("hw.cpu_features", &hwcap, &len, NULL, 0);
149 #endif
150    if (hwcap & PPC_FEATURE_HAS_ALTIVEC)
151       util_cpu_caps.has_altivec = 1;
152    if (hwcap & PPC_FEATURE_HAS_VSX)
153       util_cpu_caps.has_vsx = 1;
154 #elif DETECT_OS_APPLE || DETECT_OS_NETBSD || DETECT_OS_OPENBSD
155 #ifdef HW_VECTORUNIT
156    int sels[2] = {CTL_HW, HW_VECTORUNIT};
157 #else
158    int sels[2] = {CTL_MACHDEP, CPU_ALTIVEC};
159 #endif
160    int has_vu = 0;
161    size_t len = sizeof (has_vu);
162    int err;
163 
164    err = sysctl(sels, 2, &has_vu, &len, NULL, 0);
165 
166    if (err == 0) {
167       if (has_vu != 0) {
168          util_cpu_caps.has_altivec = 1;
169       }
170    }
171 #elif DETECT_OS_LINUX /* !DETECT_OS_APPLE && !DETECT_OS_NETBSD && !DETECT_OS_OPENBSD */
172 #if DETECT_ARCH_PPC_64
173     Elf64_auxv_t aux;
174 #else
175     Elf32_auxv_t aux;
176 #endif
177     int fd = open("/proc/self/auxv", O_RDONLY | O_CLOEXEC);
178     if (fd >= 0) {
179        while (read(fd, &aux, sizeof(aux)) == sizeof(aux)) {
180           if (aux.a_type == AT_HWCAP) {
181              char *env_vsx = getenv("GALLIVM_VSX");
182              uint64_t hwcap = aux.a_un.a_val;
183              util_cpu_caps.has_altivec = (hwcap >> 28) & 1;
184              if (!env_vsx || env_vsx[0] != '0') {
185                 util_cpu_caps.has_vsx  = (hwcap >>  7) & 1;
186              }
187              break;
188           }
189        }
190        close(fd);
191     }
192 #else /* !DETECT_OS_APPLE && !DETECT_OS_BSD && !DETECT_OS_LINUX */
193    /* not on Apple/Darwin or Linux, do it the brute-force way */
194    /* this is borrowed from the libmpeg2 library */
195    signal(SIGILL, sigill_handler);
196    if (setjmp(__lv_powerpc_jmpbuf)) {
197       signal(SIGILL, SIG_DFL);
198    } else {
199       bool enable_altivec = true;    /* Default: enable  if available, and if not overridden */
200       bool enable_vsx = true;
201 #if MESA_DEBUG
202       /* Disabling Altivec code generation is not the same as disabling VSX code generation,
203        * which can be done simply by passing -mattr=-vsx to the LLVM compiler; cf.
204        * lp_build_create_jit_compiler_for_module().
205        * If you want to disable Altivec code generation, the best place to do it is here.
206        */
207       char *env_control = getenv("GALLIVM_ALTIVEC");    /* 1=enable (default); 0=disable */
208       if (env_control && env_control[0] == '0') {
209          enable_altivec = false;
210       }
211 #endif
212       /* VSX instructions can be explicitly enabled/disabled via GALLIVM_VSX=1 or 0 */
213       char *env_vsx = getenv("GALLIVM_VSX");
214       if (env_vsx && env_vsx[0] == '0') {
215          enable_vsx = false;
216       }
217       if (enable_altivec) {
218          __lv_powerpc_canjump = 1;
219 
220          __asm __volatile
221             ("mtspr 256, %0\n\t"
222              "vand %%v0, %%v0, %%v0"
223              :
224              : "r" (-1));
225 
226          util_cpu_caps.has_altivec = 1;
227 
228          if (enable_vsx) {
229             __asm __volatile("xxland %vs0, %vs0, %vs0");
230             util_cpu_caps.has_vsx = 1;
231          }
232          signal(SIGILL, SIG_DFL);
233       } else {
234          util_cpu_caps.has_altivec = 0;
235       }
236    }
237 #endif /* !DETECT_OS_APPLE && !DETECT_OS_LINUX */
238 }
239 #endif /* DETECT_ARCH_PPC */
240 
241 
242 #if DETECT_ARCH_X86 || DETECT_ARCH_X86_64
has_cpuid(void)243 static int has_cpuid(void)
244 {
245 #if DETECT_ARCH_X86
246 #if DETECT_OS_GCC
247    int a, c;
248 
249    __asm __volatile
250       ("pushf\n"
251        "popl %0\n"
252        "movl %0, %1\n"
253        "xorl $0x200000, %0\n"
254        "push %0\n"
255        "popf\n"
256        "pushf\n"
257        "popl %0\n"
258        : "=a" (a), "=c" (c)
259        :
260        : "cc");
261 
262    return a != c;
263 #else
264    /* FIXME */
265    return 1;
266 #endif
267 #elif DETECT_ARCH_X86_64
268    return 1;
269 #else
270    return 0;
271 #endif
272 }
273 
274 
275 /**
276  * @sa cpuid.h included in gcc-4.3 onwards.
277  * @sa http://msdn.microsoft.com/en-us/library/hskdteyh.aspx
278  */
279 static inline void
cpuid(uint32_t ax,uint32_t * p)280 cpuid(uint32_t ax, uint32_t *p)
281 {
282 #if DETECT_CC_GCC && DETECT_ARCH_X86
283    __asm __volatile (
284      "xchgl %%ebx, %1\n\t"
285      "cpuid\n\t"
286      "xchgl %%ebx, %1"
287      : "=a" (p[0]),
288        "=S" (p[1]),
289        "=c" (p[2]),
290        "=d" (p[3])
291      : "0" (ax)
292    );
293 #elif DETECT_CC_GCC && DETECT_ARCH_X86_64
294    __asm __volatile (
295      "cpuid\n\t"
296      : "=a" (p[0]),
297        "=b" (p[1]),
298        "=c" (p[2]),
299        "=d" (p[3])
300      : "0" (ax)
301    );
302 #elif DETECT_CC_MSVC
303    __cpuid(p, ax);
304 #else
305    p[0] = 0;
306    p[1] = 0;
307    p[2] = 0;
308    p[3] = 0;
309 #endif
310 }
311 
312 /**
313  * @sa cpuid.h included in gcc-4.4 onwards.
314  * @sa http://msdn.microsoft.com/en-us/library/hskdteyh%28v=vs.90%29.aspx
315  */
316 static inline void
cpuid_count(uint32_t ax,uint32_t cx,uint32_t * p)317 cpuid_count(uint32_t ax, uint32_t cx, uint32_t *p)
318 {
319 #if DETECT_CC_GCC && DETECT_ARCH_X86
320    __asm __volatile (
321      "xchgl %%ebx, %1\n\t"
322      "cpuid\n\t"
323      "xchgl %%ebx, %1"
324      : "=a" (p[0]),
325        "=S" (p[1]),
326        "=c" (p[2]),
327        "=d" (p[3])
328      : "0" (ax), "2" (cx)
329    );
330 #elif DETECT_CC_GCC && DETECT_ARCH_X86_64
331    __asm __volatile (
332      "cpuid\n\t"
333      : "=a" (p[0]),
334        "=b" (p[1]),
335        "=c" (p[2]),
336        "=d" (p[3])
337      : "0" (ax), "2" (cx)
338    );
339 #elif DETECT_CC_MSVC
340    __cpuidex(p, ax, cx);
341 #else
342    p[0] = 0;
343    p[1] = 0;
344    p[2] = 0;
345    p[3] = 0;
346 #endif
347 }
348 
349 
xgetbv(void)350 static inline uint64_t xgetbv(void)
351 {
352 #if DETECT_CC_GCC
353    uint32_t eax, edx;
354 
355    __asm __volatile (
356      ".byte 0x0f, 0x01, 0xd0" // xgetbv isn't supported on gcc < 4.4
357      : "=a"(eax),
358        "=d"(edx)
359      : "c"(0)
360    );
361 
362    return ((uint64_t)edx << 32) | eax;
363 #elif DETECT_CC_MSVC && defined(_MSC_FULL_VER) && defined(_XCR_XFEATURE_ENABLED_MASK)
364    return _xgetbv(_XCR_XFEATURE_ENABLED_MASK);
365 #else
366    return 0;
367 #endif
368 }
369 
370 
371 #if DETECT_ARCH_X86
372 UTIL_ALIGN_STACK
373 static inline bool
sse2_has_daz(void)374 sse2_has_daz(void)
375 {
376    struct area_t {
377       uint32_t pad1[7];
378       uint32_t mxcsr_mask;
379       uint32_t pad2[128-8];
380    };
381    alignas(16) struct area_t fxarea;
382 
383    fxarea.mxcsr_mask = 0;
384 #if DETECT_CC_GCC
385    __asm __volatile ("fxsave %0" : "+m" (fxarea));
386 #elif DETECT_CC_MSVC || DETECT_CC_ICL
387    _fxsave(&fxarea);
388 #else
389    fxarea.mxcsr_mask = 0;
390 #endif
391    return !!(fxarea.mxcsr_mask & (1 << 6));
392 }
393 #endif
394 
395 #endif /* X86 or X86_64 */
396 
397 #if DETECT_ARCH_ARM
398 static void
check_os_arm_support(void)399 check_os_arm_support(void)
400 {
401    /*
402     * On Android, the cpufeatures library is preferred way of checking
403     * CPU capabilities. However, it is not available for standalone Mesa
404     * builds, i.e. when Android build system (Android.mk-based) is not
405     * used. Because of this we cannot use DETECT_OS_ANDROID here, but rather
406     * have a separate macro that only gets enabled from respective Android.mk.
407     */
408 #if defined(__ARM_NEON) || defined(__ARM_NEON__)
409    util_cpu_caps.has_neon = 1;
410 #elif (DETECT_OS_FREEBSD || DETECT_OS_OPENBSD) && defined(HAVE_ELF_AUX_INFO)
411    unsigned long hwcap = 0;
412    elf_aux_info(AT_HWCAP, &hwcap, sizeof(hwcap));
413    if (hwcap & HWCAP_NEON)
414       util_cpu_caps.has_neon = 1;
415 #elif defined(HAS_ANDROID_CPUFEATURES)
416    AndroidCpuFamily cpu_family = android_getCpuFamily();
417    uint64_t cpu_features = android_getCpuFeatures();
418 
419    if (cpu_family == ANDROID_CPU_FAMILY_ARM) {
420       if (cpu_features & ANDROID_CPU_ARM_FEATURE_NEON)
421          util_cpu_caps.has_neon = 1;
422    }
423 #elif DETECT_OS_LINUX
424     Elf32_auxv_t aux;
425     int fd;
426 
427     fd = open("/proc/self/auxv", O_RDONLY | O_CLOEXEC);
428     if (fd >= 0) {
429        while (read(fd, &aux, sizeof(Elf32_auxv_t)) == sizeof(Elf32_auxv_t)) {
430           if (aux.a_type == AT_HWCAP) {
431              uint32_t hwcap = aux.a_un.a_val;
432 
433              util_cpu_caps.has_neon = (hwcap >> 12) & 1;
434              break;
435           }
436        }
437        close (fd);
438     }
439 #endif /* DETECT_OS_LINUX */
440 }
441 
442 #elif DETECT_ARCH_AARCH64
443 static void
check_os_arm_support(void)444 check_os_arm_support(void)
445 {
446     util_cpu_caps.has_neon = true;
447 }
448 #endif /* DETECT_ARCH_ARM || DETECT_ARCH_AARCH64 */
449 
450 #if DETECT_ARCH_MIPS64
451 static void
check_os_mips64_support(void)452 check_os_mips64_support(void)
453 {
454 #if DETECT_OS_LINUX
455     Elf64_auxv_t aux;
456     int fd;
457 
458     fd = open("/proc/self/auxv", O_RDONLY | O_CLOEXEC);
459     if (fd >= 0) {
460        while (read(fd, &aux, sizeof(Elf64_auxv_t)) == sizeof(Elf64_auxv_t)) {
461           if (aux.a_type == AT_HWCAP) {
462              uint64_t hwcap = aux.a_un.a_val;
463 
464              util_cpu_caps.has_msa = (hwcap >> 1) & 1;
465              break;
466           }
467        }
468        close (fd);
469     }
470 #endif /* DETECT_OS_LINUX */
471 }
472 #endif /* DETECT_ARCH_MIPS64 */
473 
474 #if DETECT_ARCH_LOONGARCH64
475 static void
check_os_loongarch64_support(void)476 check_os_loongarch64_support(void)
477 {
478 #if DETECT_OS_LINUX
479     Elf64_auxv_t aux;
480     int fd;
481 
482     fd = open("/proc/self/auxv", O_RDONLY | O_CLOEXEC);
483     if (fd >= 0) {
484        while (read(fd, &aux, sizeof(Elf64_auxv_t)) == sizeof(Elf64_auxv_t)) {
485           if (aux.a_type == AT_HWCAP) {
486              uint64_t hwcap = aux.a_un.a_val;
487 
488              util_cpu_caps.has_lsx = (hwcap >> 4) & 1;
489              util_cpu_caps.has_lasx = (hwcap >> 5) & 1;
490              break;
491           }
492        }
493        close (fd);
494     }
495 #endif /* DETECT_OS_LINUX */
496 }
497 #endif /* DETECT_ARCH_LOONGARCH64 */
498 
499 
500 static void
get_cpu_topology(void)501 get_cpu_topology(void)
502 {
503    /* Default. This is OK if L3 is not present or there is only one. */
504    util_cpu_caps.num_L3_caches = 1;
505 
506    memset(util_cpu_caps.cpu_to_L3, 0xff, sizeof(util_cpu_caps.cpu_to_L3));
507 
508 #if DETECT_OS_LINUX
509    uint64_t big_cap = 0;
510    unsigned num_big_cpus = 0;
511    uint64_t *caps = malloc(sizeof(uint64_t) * util_cpu_caps.max_cpus);
512    bool fail = false;
513    for (unsigned i = 0; caps && i < util_cpu_caps.max_cpus; i++) {
514       char name[PATH_MAX];
515       snprintf(name, sizeof(name), "/sys/devices/system/cpu/cpu%u/cpu_capacity", i);
516       size_t size = 0;
517       char *cap = os_read_file(name, &size);
518       if (!cap) {
519          num_big_cpus = 0;
520          fail = true;
521          break;
522       }
523       errno = 0;
524       caps[i] = strtoull(cap, NULL, 10);
525       free(cap);
526       if (errno) {
527          fail = true;
528          break;
529       }
530       big_cap = MAX2(caps[i], big_cap);
531    }
532    if (!fail) {
533       for (unsigned i = 0; caps && i < util_cpu_caps.max_cpus; i++) {
534          if (caps[i] >= big_cap / 2)
535             num_big_cpus++;
536       }
537    }
538    free(caps);
539    util_cpu_caps.nr_big_cpus = num_big_cpus;
540 #endif
541 
542 #if DETECT_ARCH_X86 || DETECT_ARCH_X86_64
543    /* AMD Zen */
544    if (util_cpu_caps.family >= CPU_AMD_ZEN1_ZEN2 &&
545        util_cpu_caps.family < CPU_AMD_LAST) {
546       uint32_t regs[4];
547 
548       uint32_t saved_mask[UTIL_MAX_CPUS / 32] = {0};
549       uint32_t mask[UTIL_MAX_CPUS / 32] = {0};
550       bool saved = false;
551 
552       uint32_t L3_found[UTIL_MAX_CPUS] = {0};
553       uint32_t num_L3_caches = 0;
554       util_affinity_mask *L3_affinity_masks = NULL;
555 
556       /* Query APIC IDs from each CPU core.
557        *
558        * An APIC ID is a logical ID of the CPU with respect to the cache
559        * hierarchy, meaning that consecutive APIC IDs are neighbours in
560        * the hierarchy, e.g. sharing the same cache.
561        *
562        * For example, CPU 0 can have APIC ID 0 and CPU 12 can have APIC ID 1,
563        * which means that both CPU 0 and 12 are next to each other.
564        * (e.g. they are 2 threads belonging to 1 SMT2 core)
565        *
566        * We need to find out which CPUs share the same L3 cache and they can
567        * be all over the place.
568        *
569        * Querying the APIC ID can only be done by pinning the current thread
570        * to each core. The original affinity mask is saved.
571        *
572        * Loop over all possible CPUs even though some may be offline.
573        */
574       for (int16_t i = 0; i < util_cpu_caps.max_cpus && i < UTIL_MAX_CPUS; i++) {
575          uint32_t cpu_bit = 1u << (i % 32);
576 
577          mask[i / 32] = cpu_bit;
578 
579          /* The assumption is that trying to bind the thread to a CPU that is
580           * offline will fail.
581           */
582          if (util_set_current_thread_affinity(mask,
583                                               !saved ? saved_mask : NULL,
584                                               util_cpu_caps.num_cpu_mask_bits)) {
585             saved = true;
586 
587             /* Query the APIC ID of the current core. */
588             cpuid(0x00000001, regs);
589             unsigned apic_id = regs[1] >> 24;
590 
591             /* Query the total core count for the CPU */
592             uint32_t core_count = 1;
593             if (regs[3] & (1 << 28))
594                core_count = (regs[1] >> 16) & 0xff;
595 
596             core_count = util_next_power_of_two(core_count);
597 
598             /* Query the L3 cache count. */
599             cpuid_count(0x8000001D, 3, regs);
600             unsigned cache_level = (regs[0] >> 5) & 0x7;
601             unsigned cores_per_L3 = ((regs[0] >> 14) & 0xfff) + 1;
602 
603             if (cache_level != 3)
604                continue;
605 
606             unsigned local_core_id = apic_id & (core_count - 1);
607             unsigned phys_id = (apic_id & ~(core_count - 1)) >> util_logbase2(core_count);
608             unsigned local_l3_cache_index = local_core_id / util_next_power_of_two(cores_per_L3);
609 #define L3_ID(p, i) (p << 16 | i << 1 | 1);
610 
611             unsigned l3_id = L3_ID(phys_id, local_l3_cache_index);
612             int idx = -1;
613             for (unsigned c = 0; c < num_L3_caches; c++) {
614                if (L3_found[c] == l3_id) {
615                   idx = c;
616                   break;
617                }
618             }
619             if (idx == -1) {
620                idx = num_L3_caches;
621                L3_found[num_L3_caches++] = l3_id;
622                L3_affinity_masks = realloc(L3_affinity_masks, sizeof(util_affinity_mask) * num_L3_caches);
623                if (!L3_affinity_masks)
624                   return;
625                memset(&L3_affinity_masks[num_L3_caches - 1], 0, sizeof(util_affinity_mask));
626             }
627             util_cpu_caps.cpu_to_L3[i] = idx;
628             L3_affinity_masks[idx][i / 32] |= cpu_bit;
629 
630          }
631          mask[i / 32] = 0;
632       }
633 
634       util_cpu_caps.num_L3_caches = num_L3_caches;
635       util_cpu_caps.L3_affinity_mask = L3_affinity_masks;
636 
637       if (saved) {
638          if (debug_get_option_dump_cpu()) {
639             fprintf(stderr, "CPU <-> L3 cache mapping:\n");
640             for (unsigned i = 0; i < util_cpu_caps.num_L3_caches; i++) {
641                fprintf(stderr, "  - L3 %u mask = ", i);
642                for (int j = util_cpu_caps.max_cpus - 1; j >= 0; j -= 32)
643                   fprintf(stderr, "%08x ", util_cpu_caps.L3_affinity_mask[i][j / 32]);
644                fprintf(stderr, "\n");
645             }
646          }
647 
648          /* Restore the original affinity mask. */
649          util_set_current_thread_affinity(saved_mask, NULL,
650                                           util_cpu_caps.num_cpu_mask_bits);
651       } else {
652          if (debug_get_option_dump_cpu())
653             fprintf(stderr, "Cannot set thread affinity for any thread.\n");
654       }
655    }
656 #endif
657 }
658 
659 static
check_cpu_caps_override(void)660 void check_cpu_caps_override(void)
661 {
662    const char *override_cpu_caps = debug_get_option("GALLIUM_OVERRIDE_CPU_CAPS", NULL);
663 #if DETECT_ARCH_X86 || DETECT_ARCH_X86_64
664    if (debug_get_bool_option("GALLIUM_NOSSE", false)) {
665       util_cpu_caps.has_sse = 0;
666    }
667 #if MESA_DEBUG
668    /* For simulating less capable machines */
669    if (debug_get_bool_option("LP_FORCE_SSE2", false)) {
670       util_cpu_caps.has_sse3 = 0;
671    }
672 #endif
673 #endif /* DETECT_ARCH_X86 || DETECT_ARCH_X86_64 */
674 
675    if (override_cpu_caps != NULL) {
676 #if DETECT_ARCH_X86 || DETECT_ARCH_X86_64
677       if (!strcmp(override_cpu_caps, "nosse")) {
678          util_cpu_caps.has_sse = 0;
679       } else if (!strcmp(override_cpu_caps, "sse")) {
680          util_cpu_caps.has_sse2 = 0;
681       } else if (!strcmp(override_cpu_caps, "sse2")) {
682          util_cpu_caps.has_sse3 = 0;
683       } else if (!strcmp(override_cpu_caps, "sse3")) {
684          util_cpu_caps.has_ssse3 = 0;
685       } else if (!strcmp(override_cpu_caps, "ssse3")) {
686          util_cpu_caps.has_sse4_1 = 0;
687       } else if (!strcmp(override_cpu_caps, "sse4.1")) {
688          util_cpu_caps.has_avx = 0;
689       } else if (!strcmp(override_cpu_caps, "avx")) {
690          util_cpu_caps.has_avx512f = 0;
691       }
692 #endif /* DETECT_ARCH_X86 || DETECT_ARCH_X86_64 */
693    }
694 
695 #if DETECT_ARCH_X86 || DETECT_ARCH_X86_64
696    if (!util_cpu_caps.has_sse) {
697       util_cpu_caps.has_sse2 = 0;
698    }
699    if (!util_cpu_caps.has_sse2) {
700       util_cpu_caps.has_sse3 = 0;
701    }
702    if (!util_cpu_caps.has_sse3) {
703       util_cpu_caps.has_ssse3 = 0;
704    }
705    if (!util_cpu_caps.has_ssse3) {
706       util_cpu_caps.has_sse4_1 = 0;
707    }
708    if (!util_cpu_caps.has_sse4_1) {
709       util_cpu_caps.has_sse4_2 = 0;
710       util_cpu_caps.has_avx = 0;
711    }
712    if (!util_cpu_caps.has_avx) {
713       util_cpu_caps.has_avx2 = 0;
714       util_cpu_caps.has_f16c = 0;
715       util_cpu_caps.has_fma = 0;
716       util_cpu_caps.has_avx512f = 0;
717    }
718    if (!util_cpu_caps.has_avx512f) {
719       /* avx512 are cleared */
720       util_cpu_caps.has_avx512dq   = 0;
721       util_cpu_caps.has_avx512ifma = 0;
722       util_cpu_caps.has_avx512pf   = 0;
723       util_cpu_caps.has_avx512er   = 0;
724       util_cpu_caps.has_avx512cd   = 0;
725       util_cpu_caps.has_avx512bw   = 0;
726       util_cpu_caps.has_avx512vl   = 0;
727       util_cpu_caps.has_avx512vbmi = 0;
728    }
729 #endif /* DETECT_ARCH_X86 || DETECT_ARCH_X86_64 */
730 }
731 
732 static
check_max_vector_bits(void)733 void check_max_vector_bits(void)
734 {
735    /* Leave it at 128, even when no SIMD extensions are available.
736     * Really needs to be a multiple of 128 so can fit 4 floats.
737     */
738    util_cpu_caps.max_vector_bits = 128;
739 #if DETECT_ARCH_X86 || DETECT_ARCH_X86_64
740    if (util_cpu_caps.has_avx512f) {
741       util_cpu_caps.max_vector_bits = 512;
742    } else if (util_cpu_caps.has_avx) {
743       util_cpu_caps.max_vector_bits = 256;
744    }
745 #endif
746 }
747 
748 void _util_cpu_detect_once(void);
749 
750 void
_util_cpu_detect_once(void)751 _util_cpu_detect_once(void)
752 {
753    int available_cpus = 0;
754    int total_cpus = 0;
755 
756    memset(&util_cpu_caps, 0, sizeof util_cpu_caps);
757 
758    /* Count the number of CPUs in system */
759 #if DETECT_OS_WINDOWS
760    {
761       SYSTEM_INFO system_info;
762       GetSystemInfo(&system_info);
763       available_cpus = MAX2(1, system_info.dwNumberOfProcessors);
764    }
765 #elif DETECT_OS_POSIX
766 #  if defined(HAS_SCHED_GETAFFINITY)
767    {
768       /* sched_setaffinity() can be used to further restrict the number of
769        * CPUs on which the process can run.  Use sched_getaffinity() to
770        * determine the true number of available CPUs.
771        *
772        * FIXME: The Linux manual page for sched_getaffinity describes how this
773        * simple implementation will fail with > 1024 CPUs, and we'll fall back
774        * to the _SC_NPROCESSORS_ONLN path.  Support for > 1024 CPUs can be
775        * added to this path once someone has such a system for testing.
776        */
777       cpu_set_t affin;
778       if (sched_getaffinity(getpid(), sizeof(affin), &affin) == 0)
779          available_cpus = CPU_COUNT(&affin);
780    }
781 #  endif
782 
783    /* Linux, FreeBSD, DragonFly, and Mac OS X should have
784     * _SC_NOPROCESSORS_ONLN.  NetBSD and OpenBSD should have HW_NCPUONLINE.
785     * This is what FFmpeg uses on those platforms.
786     */
787 #  if DETECT_OS_BSD && defined(HW_NCPUONLINE)
788    if (available_cpus == 0) {
789       const int mib[] = { CTL_HW, HW_NCPUONLINE };
790       int ncpu;
791       size_t len = sizeof(ncpu);
792 
793       sysctl(mib, 2, &ncpu, &len, NULL, 0);
794       available_cpus = ncpu;
795    }
796 #  elif defined(_SC_NPROCESSORS_ONLN)
797    if (available_cpus == 0) {
798       available_cpus = sysconf(_SC_NPROCESSORS_ONLN);
799       if (available_cpus == ~0)
800          available_cpus = 1;
801    }
802 #  elif DETECT_OS_BSD
803    if (available_cpus == 0) {
804       const int mib[] = { CTL_HW, HW_NCPU };
805       int ncpu;
806       int len = sizeof(ncpu);
807 
808       sysctl(mib, 2, &ncpu, &len, NULL, 0);
809       available_cpus = ncpu;
810    }
811 #  endif /* DETECT_OS_BSD */
812 
813    /* Determine the maximum number of CPUs configured in the system.  This is
814     * used to properly set num_cpu_mask_bits below.  On BSDs that don't have
815     * HW_NCPUONLINE, it was not clear whether HW_NCPU is the number of
816     * configured or the number of online CPUs.  For that reason, prefer the
817     * _SC_NPROCESSORS_CONF path on all BSDs.
818     */
819 #  if defined(_SC_NPROCESSORS_CONF)
820    total_cpus = sysconf(_SC_NPROCESSORS_CONF);
821    if (total_cpus == ~0)
822       total_cpus = 1;
823 #  elif DETECT_OS_BSD
824    {
825       const int mib[] = { CTL_HW, HW_NCPU };
826       int ncpu;
827       int len = sizeof(ncpu);
828 
829       sysctl(mib, 2, &ncpu, &len, NULL, 0);
830       total_cpus = ncpu;
831    }
832 #  endif /* DETECT_OS_BSD */
833 #endif /* DETECT_OS_POSIX */
834 
835    util_cpu_caps.nr_cpus = MAX2(1, available_cpus);
836    total_cpus = MAX2(total_cpus, util_cpu_caps.nr_cpus);
837 
838    util_cpu_caps.max_cpus = total_cpus;
839    util_cpu_caps.num_cpu_mask_bits = align(total_cpus, 32);
840 
841    /* Make the fallback cacheline size nonzero so that it can be
842     * safely passed to align().
843     */
844    util_cpu_caps.cacheline = sizeof(void *);
845 
846 #if DETECT_ARCH_X86 || DETECT_ARCH_X86_64
847    if (has_cpuid()) {
848       uint32_t regs[4];
849       uint32_t regs2[4];
850 
851       util_cpu_caps.cacheline = 32;
852 
853       /* Get max cpuid level */
854       cpuid(0x00000000, regs);
855 
856       if (regs[0] >= 0x00000001) {
857          unsigned int cacheline;
858 
859          cpuid (0x00000001, regs2);
860 
861          util_cpu_caps.x86_cpu_type = (regs2[0] >> 8) & 0xf;
862          /* Add "extended family". */
863          if (util_cpu_caps.x86_cpu_type == 0xf)
864              util_cpu_caps.x86_cpu_type += ((regs2[0] >> 20) & 0xff);
865 
866          switch (util_cpu_caps.x86_cpu_type) {
867          case 0x17:
868             util_cpu_caps.family = CPU_AMD_ZEN1_ZEN2;
869             break;
870          case 0x18:
871             util_cpu_caps.family = CPU_AMD_ZEN_HYGON;
872             break;
873          case 0x19:
874             util_cpu_caps.family = CPU_AMD_ZEN3;
875             break;
876          default:
877             if (util_cpu_caps.x86_cpu_type > 0x19)
878                util_cpu_caps.family = CPU_AMD_ZEN_NEXT;
879          }
880 
881          /* general feature flags */
882          util_cpu_caps.has_sse    = (regs2[3] >> 25) & 1; /* 0x2000000 */
883          util_cpu_caps.has_sse2   = (regs2[3] >> 26) & 1; /* 0x4000000 */
884          util_cpu_caps.has_sse3   = (regs2[2] >>  0) & 1; /* 0x0000001 */
885          util_cpu_caps.has_ssse3  = (regs2[2] >>  9) & 1; /* 0x0000020 */
886          util_cpu_caps.has_sse4_1 = (regs2[2] >> 19) & 1;
887          util_cpu_caps.has_sse4_2 = (regs2[2] >> 20) & 1;
888          util_cpu_caps.has_popcnt = (regs2[2] >> 23) & 1;
889          util_cpu_caps.has_avx    = ((regs2[2] >> 28) & 1) && // AVX
890                                     ((regs2[2] >> 27) & 1) && // OSXSAVE
891                                     ((xgetbv() & 6) == 6);    // XMM & YMM
892          util_cpu_caps.has_f16c   = ((regs2[2] >> 29) & 1) && util_cpu_caps.has_avx;
893          util_cpu_caps.has_fma    = ((regs2[2] >> 12) & 1) && util_cpu_caps.has_avx;
894 #if DETECT_ARCH_X86_64
895          util_cpu_caps.has_daz = 1;
896 #else
897          util_cpu_caps.has_daz = util_cpu_caps.has_sse3 ||
898             (util_cpu_caps.has_sse2 && sse2_has_daz());
899 #endif
900 
901          cacheline = ((regs2[1] >> 8) & 0xFF) * 8;
902          if (cacheline > 0)
903             util_cpu_caps.cacheline = cacheline;
904       }
905       if (regs[0] >= 0x00000007) {
906          uint32_t regs7[4];
907          cpuid_count(0x00000007, 0x00000000, regs7);
908          util_cpu_caps.has_clflushopt = (regs7[1] >> 23) & 1;
909          if (util_cpu_caps.has_avx) {
910             util_cpu_caps.has_avx2 = (regs7[1] >> 5) & 1;
911 
912             // check for avx512
913             if (xgetbv() & (0x7 << 5)) { // OPMASK: upper-256 enabled by OS
914                util_cpu_caps.has_avx512f    = (regs7[1] >> 16) & 1;
915                util_cpu_caps.has_avx512dq   = (regs7[1] >> 17) & 1;
916                util_cpu_caps.has_avx512ifma = (regs7[1] >> 21) & 1;
917                util_cpu_caps.has_avx512pf   = (regs7[1] >> 26) & 1;
918                util_cpu_caps.has_avx512er   = (regs7[1] >> 27) & 1;
919                util_cpu_caps.has_avx512cd   = (regs7[1] >> 28) & 1;
920                util_cpu_caps.has_avx512bw   = (regs7[1] >> 30) & 1;
921                util_cpu_caps.has_avx512vl   = (regs7[1] >> 31) & 1;
922                util_cpu_caps.has_avx512vbmi = (regs7[2] >>  1) & 1;
923             }
924          }
925       }
926 
927       cpuid(0x80000000, regs);
928 
929       if (regs[0] >= 0x80000006) {
930          /* should we really do this if the clflush size above worked? */
931          unsigned int cacheline;
932          cpuid(0x80000006, regs2);
933          cacheline = regs2[2] & 0xFF;
934          if (cacheline > 0)
935             util_cpu_caps.cacheline = cacheline;
936       }
937    }
938 #endif /* DETECT_ARCH_X86 || DETECT_ARCH_X86_64 */
939 
940 #if DETECT_ARCH_ARM || DETECT_ARCH_AARCH64
941    check_os_arm_support();
942 #endif
943 
944 #if DETECT_ARCH_PPC
945    check_os_altivec_support();
946 #endif /* DETECT_ARCH_PPC */
947 
948 #if DETECT_ARCH_MIPS64
949    check_os_mips64_support();
950 #endif /* DETECT_ARCH_MIPS64 */
951 
952 #if DETECT_ARCH_LOONGARCH64
953    check_os_loongarch64_support();
954 #endif /* DETECT_ARCH_LOONGARCH64 */
955 
956 #if DETECT_ARCH_S390
957    util_cpu_caps.family = CPU_S390X;
958 #endif
959 
960    check_cpu_caps_override();
961 
962    /* max_vector_bits should be checked after cpu caps override */
963    check_max_vector_bits();
964 
965    get_cpu_topology();
966 
967    if (debug_get_option_dump_cpu()) {
968       printf("util_cpu_caps.nr_cpus = %u\n", util_cpu_caps.nr_cpus);
969 
970       printf("util_cpu_caps.x86_cpu_type = %u\n", util_cpu_caps.x86_cpu_type);
971       printf("util_cpu_caps.cacheline = %u\n", util_cpu_caps.cacheline);
972 
973       printf("util_cpu_caps.has_sse = %u\n", util_cpu_caps.has_sse);
974       printf("util_cpu_caps.has_sse2 = %u\n", util_cpu_caps.has_sse2);
975       printf("util_cpu_caps.has_sse3 = %u\n", util_cpu_caps.has_sse3);
976       printf("util_cpu_caps.has_ssse3 = %u\n", util_cpu_caps.has_ssse3);
977       printf("util_cpu_caps.has_sse4_1 = %u\n", util_cpu_caps.has_sse4_1);
978       printf("util_cpu_caps.has_sse4_2 = %u\n", util_cpu_caps.has_sse4_2);
979       printf("util_cpu_caps.has_avx = %u\n", util_cpu_caps.has_avx);
980       printf("util_cpu_caps.has_avx2 = %u\n", util_cpu_caps.has_avx2);
981       printf("util_cpu_caps.has_f16c = %u\n", util_cpu_caps.has_f16c);
982       printf("util_cpu_caps.has_popcnt = %u\n", util_cpu_caps.has_popcnt);
983       printf("util_cpu_caps.has_altivec = %u\n", util_cpu_caps.has_altivec);
984       printf("util_cpu_caps.has_vsx = %u\n", util_cpu_caps.has_vsx);
985       printf("util_cpu_caps.has_neon = %u\n", util_cpu_caps.has_neon);
986       printf("util_cpu_caps.has_msa = %u\n", util_cpu_caps.has_msa);
987       printf("util_cpu_caps.has_daz = %u\n", util_cpu_caps.has_daz);
988       printf("util_cpu_caps.has_lsx = %u\n", util_cpu_caps.has_lsx);
989       printf("util_cpu_caps.has_lasx = %u\n", util_cpu_caps.has_lasx);
990       printf("util_cpu_caps.has_avx512f = %u\n", util_cpu_caps.has_avx512f);
991       printf("util_cpu_caps.has_avx512dq = %u\n", util_cpu_caps.has_avx512dq);
992       printf("util_cpu_caps.has_avx512ifma = %u\n", util_cpu_caps.has_avx512ifma);
993       printf("util_cpu_caps.has_avx512pf = %u\n", util_cpu_caps.has_avx512pf);
994       printf("util_cpu_caps.has_avx512er = %u\n", util_cpu_caps.has_avx512er);
995       printf("util_cpu_caps.has_avx512cd = %u\n", util_cpu_caps.has_avx512cd);
996       printf("util_cpu_caps.has_avx512bw = %u\n", util_cpu_caps.has_avx512bw);
997       printf("util_cpu_caps.has_avx512vl = %u\n", util_cpu_caps.has_avx512vl);
998       printf("util_cpu_caps.has_avx512vbmi = %u\n", util_cpu_caps.has_avx512vbmi);
999       printf("util_cpu_caps.has_clflushopt = %u\n", util_cpu_caps.has_clflushopt);
1000       printf("util_cpu_caps.num_L3_caches = %u\n", util_cpu_caps.num_L3_caches);
1001       printf("util_cpu_caps.num_cpu_mask_bits = %u\n", util_cpu_caps.num_cpu_mask_bits);
1002    }
1003    _util_cpu_caps_state.caps = util_cpu_caps;
1004 
1005    /* This must happen at the end as it's used to guard everything else */
1006    p_atomic_set(&_util_cpu_caps_state.detect_done, 1);
1007 }
1008