3 * CPU-specific dispatch
5 * (c) 2015 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of Catacomb.
12 * Catacomb is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU Library General Public License as
14 * published by the Free Software Foundation; either version 2 of the
15 * License, or (at your option) any later version.
17 * Catacomb is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU Library General Public License for more details.
22 * You should have received a copy of the GNU Library General Public
23 * License along with Catacomb; if not, write to the Free
24 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
28 /*----- Header files ------------------------------------------------------*/
38 #include <mLib/macros.h>
42 /*----- Intel x86/AMD64 feature probing -----------------------------------*/
44 #if CPUFAM_X86 || CPUFAM_AMD64
46 # define EFLAGS_ID (1u << 21)
47 # define CPUID1D_SSE2 (1u << 26)
48 # define CPUID1D_FXSR (1u << 24)
49 # define CPUID1C_AESNI (1u << 25)
50 # define CPUID1C_AVX (1u << 28)
51 # define CPUID1C_RDRAND (1u << 30)
53 struct cpuid { unsigned a, b, c, d; };
57 * Arguments: @struct cpuid *cc@ = where to write the result
58 * @unsigned a, c@ = EAX and ECX registers to set
62 * Use: Minimal C wrapper around the x86 `CPUID' instruction. Checks
63 * that the instruction is actually available before invoking
64 * it; fills the output structure with zero if it's not going to
70 static __inline__ unsigned getflags(void)
71 { unsigned f; __asm__ ("pushf; popl %0" : "=g" (f)); return (f); }
72 static __inline__ unsigned setflags(unsigned f)
75 __asm__ ("pushf; pushl %1; popf; pushf; popl %0; popf"
81 static __inline__ unsigned long getflags(void)
82 { unsigned long f; __asm__ ("pushf; popq %0" : "=g" (f)); return (f); }
83 static __inline__ unsigned long long setflags(unsigned long f)
86 __asm__ ("pushf; pushq %1; popf; pushf; popq %0; popf"
94 static void cpuid(struct cpuid *cc, unsigned a, unsigned c)
100 cc->a = cc->b = cc->c = cc->d = 0;
103 /* Stupid dance to detect whether the CPUID instruction is available. */
105 if (!(setflags(f | EFLAGS_ID) & EFLAGS_ID) ||
106 setflags(f & ~EFLAGS_ID) & EFLAGS_ID) {
107 dispatch_debug("CPUID instruction not available");
112 /* Alas, EBX is magical in PIC code, so abuse ESI instead. This isn't
113 * pretty, but it works.
116 __asm__ ("pushl %%ebx; cpuid; movl %%ebx, %%esi; popl %%ebx"
117 : "=a" (cc->a), "=S" (cc->b), "=c" (cc->c), "=d" (cc->d)
118 : "a" (a) , "c" (c));
120 __asm__ ("pushq %%rbx; cpuid; movl %%ebx, %%esi; popq %%rbx"
121 : "=a" (cc->a), "=S" (cc->b), "=c" (cc->c), "=d" (cc->d)
122 : "a" (a) , "c" (c));
124 # error "I'm confused."
126 dispatch_debug("CPUID(%08x, %08x) -> %08x, %08x, %08x, %08x",
127 a, c, cc->a, cc->b, cc->c, cc->d);
129 dispatch_debug("GNU inline assembler not available; can't CPUID");
133 static unsigned cpuid_maxleaf(void)
134 { struct cpuid c; cpuid(&c, 0, 0); return (c.a); }
136 /* --- @cpuid_features_p@ --- *
138 * Arguments: @unsigned dbits@ = bits to check in EDX
139 * @unsigned cbits@ = bits to check in ECX
141 * Returns: Nonzero if all the requested bits are set in the CPUID result
145 static int cpuid_features_p(unsigned dbits, unsigned cbits)
148 if (cpuid_maxleaf() < 1) return (0);
150 return ((c.d & dbits) == dbits && (c.c & cbits) == cbits);
153 /* --- @xmm_registers_available_p@ --- *
157 * Returns: Nonzero if the operating system has made the XMM registers
161 static int xmm_registers_available_p(void)
165 /* This hack is by Agner Fog. Use FXSAVE/FXRSTOR to figure out whether the
166 * XMM registers are actually alive.
168 if (!cpuid_features_p(CPUID1D_FXSR, 0)) return (0);
170 __asm__ ("movl %%esp, %%edx; subl $512, %%esp; andl $~15, %%esp\n"
172 "movl 160(%%esp), %%eax; xorl $0xaaaa5555, 160(%%esp)\n"
173 "fxrstor (%%esp); fxsave (%%esp)\n"
174 "movl 160(%%esp), %%ecx; movl %%eax, 160(%%esp)\n"
175 "fxrstor (%%esp); movl %%edx, %%esp\n"
181 __asm__ ("movq %%rsp, %%rdx; subq $512, %%rsp; andq $~15, %%rsp\n"
183 "movl 160(%%rsp), %%eax; xorl $0xaaaa5555, 160(%%rsp)\n"
184 "fxrstor (%%rsp); fxsave (%%rsp)\n"
185 "movl 160(%%rsp), %%ecx; movl %%eax, 160(%%rsp)\n"
186 "fxrstor (%%rsp); movq %%rdx, %%rsp\n"
192 # error "I'm confused."
194 dispatch_debug("XMM registers %savailable", f ? "" : "not ");
197 dispatch_debug("GNU inline assembler not available; can't check for XMM");
204 /*----- General feature probing using auxiliary vectors -------------------*/
206 /* Try to find the system's definitions for auxiliary vector entries. */
207 #ifdef HAVE_SYS_AUXV_H
208 # include <sys/auxv.h>
210 #ifdef HAVE_LINUX_AUXVEC_H
211 # include <linux/auxvec.h>
213 #ifdef HAVE_ASM_HWCAP_H
214 # include <asm/hwcap.h>
217 /* The type of entries in the auxiliary vector. I'm assuming that `unsigned
218 * long' matches each platform's word length; if this is false then we'll
219 * need some host-specific tweaking here.
221 union auxval { long i; unsigned long u; const void *p; };
222 struct auxentry { unsigned long type; union auxval value; };
224 /* Register each CPU family's interest in the auxiliary vector. Make sure
225 * that the necessary entry types are defined. This is primarily ordered by
226 * entry type to minimize duplication.
228 #if defined(AT_HWCAP) && CPUFAM_ARMEL
230 # define WANT_AT_HWCAP(_) _(AT_HWCAP, u, hwcap)
233 #if defined(AT_HWCAP) && CPUFAM_ARM64
235 # define WANT_AT_HWCAP(_) _(AT_HWCAP, u, hwcap)
238 #if defined(AT_HWCAP2) && CPUFAM_ARMEL
240 # define WANT_AT_HWCAP2(_) _(AT_HWCAP2, u, hwcap2)
243 /* If we couldn't find any interesting entries then we can switch all of this
244 * machinery off. Also do that if we have no means for atomic updates.
246 #if WANT_ANY && CPU_DISPATCH_P
248 /* The main output of this section is a bitmask of detected features. The
249 * least significant bit will be set if we've tried to probe. Always access
250 * this using `DISPATCH_LOAD' and `DISPATCH_STORE'.
252 static unsigned hwcaps = 0;
254 /* For each potentially interesting type which turned out not to exist or be
255 * wanted, define a dummy macro for the sake of the next step.
257 #ifndef WANT_AT_HWCAP
258 # define WANT_AT_HWCAP(_)
260 #ifndef WANT_AT_HWCAP2
261 # define WANT_AT_HWCAP2(_)
264 /* For each CPU family, define two lists.
266 * * `WANTAUX' is a list of the `WANT_AT_MUMBLE' macros which the CPU
267 * family tried to register interest in above. Each entry contains the
268 * interesting auxiliary vector entry type, the name of the union branch
269 * for its value, and the name of the slot in `struct auxprobe' in which
270 * to store the value.
272 * * `CAPMAP' is a list describing the output features which the CPU family
273 * intends to satisfy from the auxiliary vector. Each entry contains a
274 * feature name suffix, and the token name (for `check_env').
277 # define WANTAUX(_) \
281 _(ARM_VFP, "arm:vfp") \
282 _(ARM_NEON, "arm:neon") \
283 _(ARM_V4, "arm:v4") \
284 _(ARM_D32, "arm:d32") \
285 _(ARM_AES, "arm:aes")
288 # define WANTAUX(_) \
291 _(ARM_AES, "arm:aes")
294 /* Build the bitmask for `hwcaps' from the `CAPMAP' list. */
297 #define HFI__ENUM(feat, tok) HFI_##feat,
304 #define HF__FLAG(feat, tok) HF_##feat = 1 << HFI_##feat,
310 /* Build a structure in which we can capture the interesting data from the
313 #define AUXUTYPE_i long
314 #define AUXUTYPE_u unsigned long
315 #define AUXUTYPE_p const void *
317 #define AUXPROBE__SLOT(type, ubranch, slot) AUXUTYPE_##ubranch slot;
318 WANTAUX(AUXPROBE__SLOT)
322 /* --- @probe_hwcaps@ --- *
328 * Use: Attempt to find the auxiliary vector (which is well hidden)
329 * and discover interesting features from it.
332 static void probe_hwcaps(void)
334 unsigned hw = HF_PROBED;
335 struct auxprobe probed = { 0 };
337 /* Populate `probed' with the information we manage to retrieve from the
338 * auxiliary vector. Slots we couldn't find are left zero-valued.
340 #if defined(HAVE_GETAUXVAL)
341 /* Shiny new libc lets us request individual entry types. This is almost
344 # define CAP__GET(type, ubranch, slot) \
345 probed.slot = (AUXUTYPE_##ubranch)getauxval(type);
348 /* Otherwise we're a bit stuck, really. Modern Linux kernels make a copy
349 * of the vector available in `/procc' so we could try that.
351 * The usual place is stuck on the end of the environment vector, but that
352 * may well have moved, and we have no way of telling whether it has or
353 * whether there was ever an auxiliary vector there at all; so don't do
358 unsigned char *p = 0, *q = 0;
359 const struct auxentry *a;
362 /* Open the file and read it into a memory chunk. */
363 if ((fp = fopen("/proc/self/auxv", "rb")) == 0) goto clean;
365 if ((p = malloc(sz)) == 0) goto clean;
367 n = fread(p + off, 1, sz - off, fp);
370 sz *= 2; if ((q = realloc(p, sz)) == 0) break;
374 /* Work through the vector (or as much of it as we found) and extract the
375 * types we're interested in.
377 for (a = (const struct auxentry *)p,
378 n = sz/sizeof(struct auxentry);
381 #define CAP__SWITCH(type, ubranch, slot) \
382 case type: probed.slot = a->value.ubranch; break;
384 case AT_NULL: goto clean;
394 /* Each CPU family now has to pick through what was found and stashed in
395 * `probed', and set the appropriate flag bits in `hw'.
398 if (probed.hwcap & HWCAP_VFPv3) hw |= HF_ARM_VFP;
399 if (probed.hwcap & HWCAP_NEON) hw |= HF_ARM_NEON;
400 if (probed.hwcap & HWCAP_VFPD32) hw |= HF_ARM_D32;
401 if (probed.hwcap & HWCAP_VFPv4) hw |= HF_ARM_V4;
403 if (probed.hwcap2 & HWCAP2_AES) hw |= HF_ARM_AES;
407 if (probed.hwcap & HWCAP_AES) hw |= HF_ARM_AES;
410 /* Store the bitmask of features we probed for everyone to see. */
411 DISPATCH_STORE(hwcaps, hw);
413 /* Finally, make a report about the things we found. (Doing this earlier
414 * will pointlessly widen the window in which multiple threads will do the
415 * above auxiliary-vector probing.)
417 #define CAP__DEBUG(feat, tok) \
418 dispatch_debug("check auxv for feature `%s': %s", tok, \
419 hw & HF_##feat ? "available" : "absent");
424 /* --- @get_hwcaps@ --- *
428 * Returns: A mask of hardware capabilities and other features, as probed
429 * from the auxiliary vector.
432 static unsigned get_hwcaps(void)
436 DISPATCH_LOAD(hwcaps, hw);
437 if (!(hwcaps & HF_PROBED)) { probe_hwcaps(); DISPATCH_LOAD(hwcaps, hw); }
443 /*----- External interface ------------------------------------------------*/
445 /* --- @dispatch_debug@ --- *
447 * Arguments: @const char *fmt@ = a format string
448 * @...@ = additional arguments
452 * Use: Writes a formatted message to standard output if dispatch
453 * debugging is enabled.
456 void dispatch_debug(const char *fmt, ...)
459 const char *e = getenv("CATACOMB_CPUDISPATCH_DEBUG");
461 if (e && *e != 'n' && *e != '0') {
463 fputs("Catacomb CPUDISPATCH: ", stderr);
464 vfprintf(stderr, fmt, ap);
470 /* --- @check_env@ --- *
472 * Arguments: @const char *ftok@ = feature token
474 * Returns: Zero if the feature is forced off; positive if it's forced
475 * on; negative if the user hasn't decided.
477 * Use: Checks the environment variable `CATACOMB_CPUFEAT' for the
478 * feature token @ftok@. The variable, if it exists, should be
479 * a space-separated sequence of `+tok' and `-tok' items. These
480 * tokens may end in `*', which matches any suffix.
483 static int IGNORABLE check_env(const char *ftok)
485 const char *p, *q, *pp;
488 p = getenv("CATACOMB_CPUFEAT");
492 while (isspace((unsigned char)*p)) p++;
493 if (!*p) return (-1);
495 case '+': d = +1; p++; break;
496 case '-': d = 0; p++; break;
497 default: d = -1; break;
499 for (q = p; *q && !isspace((unsigned char)*q); q++);
501 for (pp = ftok; p < q && *pp && *p == *pp; p++, pp++);
502 if ((p == q && !*pp) || (*p == '*' && p + 1 == q)) return (d);
509 /* --- @cpu_feature_p@ --- *
511 * Arguments: @unsigned feat@ = a @CPUFEAT_...@ code
513 * Returns: Nonzero if the feature is available.
519 feat_debug(const char *ftok, const char *check, int verdict)
522 dispatch_debug("feature `%s': %s -> %s", ftok, check,
523 verdict ? "available" : "absent");
528 int cpu_feature_p(int feat)
532 #define CASE_CPUFEAT(feat, ftok, cond) case CPUFEAT_##feat: \
533 if ((f = feat_debug(ftok, "environment override", \
534 check_env(ftok))) >= 0) \
537 return (feat_debug(ftok, "runtime probe", cond));
540 #if CPUFAM_X86 || CPUFAM_AMD64
541 CASE_CPUFEAT(X86_SSE2, "x86:sse2",
542 xmm_registers_available_p() &&
543 cpuid_features_p(CPUID1D_SSE2, 0));
544 CASE_CPUFEAT(X86_AESNI, "x86:aesni",
545 xmm_registers_available_p() &&
546 cpuid_features_p(CPUID1D_SSE2, CPUID1C_AESNI));
547 CASE_CPUFEAT(X86_RDRAND, "x86:rdrand",
548 cpuid_features_p(0, CPUID1C_RDRAND));
549 CASE_CPUFEAT(X86_AVX, "x86:avx",
550 xmm_registers_available_p() &&
551 cpuid_features_p(0, CPUID1C_AVX));
554 # define FEATP__CASE(feat, tok) \
555 CASE_CPUFEAT(feat, tok, get_hwcaps() & HF_##feat)
560 dispatch_debug("denying unknown feature %d", feat);
566 /*----- That's all, folks -------------------------------------------------*/