Merge branch '2.4.x' into 2.5.x
[catacomb] / base / dispatch.c
CommitLineData
08e2be29
MW
1/* -*-c-*-
2 *
3 * CPU-specific dispatch
4 *
5 * (c) 2015 Straylight/Edgeware
6 */
7
8/*----- Licensing notice --------------------------------------------------*
9 *
10 * This file is part of Catacomb.
11 *
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.
16 *
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.
21 *
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,
25 * MA 02111-1307, USA.
26 */
27
28/*----- Header files ------------------------------------------------------*/
29
30#include "config.h"
31
32#include <ctype.h>
fac645f7
MW
33#include <stdarg.h>
34#include <stdio.h>
08e2be29
MW
35#include <stdlib.h>
36#include <string.h>
37
38#include <mLib/macros.h>
39
40#include "dispatch.h"
41
d26ad211 42/*----- Intel x86/AMD64 feature probing -----------------------------------*/
08e2be29 43
0f23f75f 44#if CPUFAM_X86 || CPUFAM_AMD64
08e2be29 45
7680f863
MW
46# define EFLAGS_ID (1u << 21)
47# define CPUID1D_SSE2 (1u << 26)
48# define CPUID1D_FXSR (1u << 24)
9e6a4409
MW
49# define CPUID1C_PCLMUL (1u << 1)
50# define CPUID1C_SSSE3 (1u << 9)
7680f863 51# define CPUID1C_AESNI (1u << 25)
b9b279b4 52# define CPUID1C_AVX (1u << 28)
d25653be 53# define CPUID1C_RDRAND (1u << 30)
08e2be29
MW
54
55struct cpuid { unsigned a, b, c, d; };
56
57/* --- @cpuid@ --- *
58 *
59 * Arguments: @struct cpuid *cc@ = where to write the result
60 * @unsigned a, c@ = EAX and ECX registers to set
61 *
62 * Returns: ---
63 *
64 * Use: Minimal C wrapper around the x86 `CPUID' instruction. Checks
65 * that the instruction is actually available before invoking
66 * it; fills the output structure with zero if it's not going to
67 * work.
68 */
69
70#ifdef __GNUC__
0f23f75f 71# if CPUFAM_X86
08e2be29
MW
72static __inline__ unsigned getflags(void)
73 { unsigned f; __asm__ ("pushf; popl %0" : "=g" (f)); return (f); }
74static __inline__ unsigned setflags(unsigned f)
75{
76 unsigned ff;
77 __asm__ ("pushf; pushl %1; popf; pushf; popl %0; popf"
25eccdf7
MW
78 : "=r" (ff)
79 : "r" (f));
08e2be29
MW
80 return (ff);
81}
0f23f75f
MW
82# else
83static __inline__ unsigned long getflags(void)
84 { unsigned long f; __asm__ ("pushf; popq %0" : "=g" (f)); return (f); }
85static __inline__ unsigned long long setflags(unsigned long f)
86{
87 unsigned long ff;
88 __asm__ ("pushf; pushq %1; popf; pushf; popq %0; popf"
25eccdf7
MW
89 : "=r" (ff)
90 : "r" (f));
0f23f75f
MW
91 return (ff);
92}
93# endif
08e2be29
MW
94#endif
95
96static void cpuid(struct cpuid *cc, unsigned a, unsigned c)
97{
98#ifdef __GNUC__
99 unsigned f;
100#endif
101
102 cc->a = cc->b = cc->c = cc->d = 0;
103
104#ifdef __GNUC__
105 /* Stupid dance to detect whether the CPUID instruction is available. */
106 f = getflags();
fac645f7
MW
107 if (!(setflags(f | EFLAGS_ID) & EFLAGS_ID) ||
108 setflags(f & ~EFLAGS_ID) & EFLAGS_ID) {
109 dispatch_debug("CPUID instruction not available");
110 return;
111 }
08e2be29
MW
112 setflags(f);
113
114 /* Alas, EBX is magical in PIC code, so abuse ESI instead. This isn't
115 * pretty, but it works.
116 */
0f23f75f 117# if CPUFAM_X86
08e2be29
MW
118 __asm__ ("pushl %%ebx; cpuid; movl %%ebx, %%esi; popl %%ebx"
119 : "=a" (cc->a), "=S" (cc->b), "=c" (cc->c), "=d" (cc->d)
120 : "a" (a) , "c" (c));
0f23f75f
MW
121# elif CPUFAM_AMD64
122 __asm__ ("pushq %%rbx; cpuid; movl %%ebx, %%esi; popq %%rbx"
123 : "=a" (cc->a), "=S" (cc->b), "=c" (cc->c), "=d" (cc->d)
124 : "a" (a) , "c" (c));
125# else
126# error "I'm confused."
127# endif
128 dispatch_debug("CPUID(%08x, %08x) -> %08x, %08x, %08x, %08x",
129 a, c, cc->a, cc->b, cc->c, cc->d);
fac645f7
MW
130#else
131 dispatch_debug("GNU inline assembler not available; can't CPUID");
08e2be29
MW
132#endif
133}
134
135static unsigned cpuid_maxleaf(void)
136 { struct cpuid c; cpuid(&c, 0, 0); return (c.a); }
137
11b17977
MW
138/* --- @cpuid_features_p@ --- *
139 *
140 * Arguments: @unsigned dbits@ = bits to check in EDX
141 * @unsigned cbits@ = bits to check in ECX
142 *
143 * Returns: Nonzero if all the requested bits are set in the CPUID result
144 * on leaf 1.
145 */
146
08e2be29
MW
147static int cpuid_features_p(unsigned dbits, unsigned cbits)
148{
149 struct cpuid c;
150 if (cpuid_maxleaf() < 1) return (0);
151 cpuid(&c, 1, 0);
152 return ((c.d & dbits) == dbits && (c.c & cbits) == cbits);
153}
154
11b17977
MW
155/* --- @xmm_registers_available_p@ --- *
156 *
157 * Arguments: ---
158 *
159 * Returns: Nonzero if the operating system has made the XMM registers
160 * available for use.
161 */
162
acbe16df
MW
163static int xmm_registers_available_p(void)
164{
165#ifdef __GNUC__
166 unsigned f;
167 /* This hack is by Agner Fog. Use FXSAVE/FXRSTOR to figure out whether the
168 * XMM registers are actually alive.
169 */
170 if (!cpuid_features_p(CPUID1D_FXSR, 0)) return (0);
0f23f75f 171# if CPUFAM_X86
acbe16df
MW
172 __asm__ ("movl %%esp, %%edx; subl $512, %%esp; andl $~15, %%esp\n"
173 "fxsave (%%esp)\n"
174 "movl 160(%%esp), %%eax; xorl $0xaaaa5555, 160(%%esp)\n"
175 "fxrstor (%%esp); fxsave (%%esp)\n"
176 "movl 160(%%esp), %%ecx; movl %%eax, 160(%%esp)\n"
177 "fxrstor (%%esp); movl %%edx, %%esp\n"
178 "xorl %%ecx, %%eax"
179 : "=a" (f)
180 : /* no inputs */
181 : "%ecx", "%edx");
0f23f75f
MW
182# elif CPUFAM_AMD64
183 __asm__ ("movq %%rsp, %%rdx; subq $512, %%rsp; andq $~15, %%rsp\n"
184 "fxsave (%%rsp)\n"
185 "movl 160(%%rsp), %%eax; xorl $0xaaaa5555, 160(%%rsp)\n"
186 "fxrstor (%%rsp); fxsave (%%rsp)\n"
187 "movl 160(%%rsp), %%ecx; movl %%eax, 160(%%rsp)\n"
188 "fxrstor (%%rsp); movq %%rdx, %%rsp\n"
189 "xorl %%ecx, %%eax"
190 : "=a" (f)
191 : /* no inputs */
192 : "%ecx", "%rdx");
193# else
194# error "I'm confused."
195# endif
196 dispatch_debug("XMM registers %savailable", f ? "" : "not ");
acbe16df
MW
197 return (f);
198#else
fac645f7 199 dispatch_debug("GNU inline assembler not available; can't check for XMM");
acbe16df
MW
200 return (0);
201#endif
202}
203
08e2be29
MW
204#endif
205
a02a22d4
MW
206/*----- General feature probing using auxiliary vectors -------------------*/
207
208/* Try to find the system's definitions for auxiliary vector entries. */
209#ifdef HAVE_SYS_AUXV_H
210# include <sys/auxv.h>
a0e9bb8a
MW
211#endif
212#ifdef HAVE_LINUX_AUXVEC_H
213# include <linux/auxvec.h>
214#endif
215#ifdef HAVE_ASM_HWCAP_H
216# include <asm/hwcap.h>
a02a22d4
MW
217#endif
218
219/* The type of entries in the auxiliary vector. I'm assuming that `unsigned
220 * long' matches each platform's word length; if this is false then we'll
221 * need some host-specific tweaking here.
222 */
223union auxval { long i; unsigned long u; const void *p; };
224struct auxentry { unsigned long type; union auxval value; };
225
226/* Register each CPU family's interest in the auxiliary vector. Make sure
227 * that the necessary entry types are defined. This is primarily ordered by
228 * entry type to minimize duplication.
229 */
61bd904b
MW
230#if defined(AT_HWCAP) && CPUFAM_ARMEL
231# define WANT_ANY 1
232# define WANT_AT_HWCAP(_) _(AT_HWCAP, u, hwcap)
233#endif
a02a22d4 234
e492db88
MW
235#if defined(AT_HWCAP) && CPUFAM_ARM64
236# define WANT_ANY 1
237# define WANT_AT_HWCAP(_) _(AT_HWCAP, u, hwcap)
238#endif
239
26e182fc
MW
240#if defined(AT_HWCAP2) && CPUFAM_ARMEL
241# define WANT_ANY 1
242# define WANT_AT_HWCAP2(_) _(AT_HWCAP2, u, hwcap2)
243#endif
244
a02a22d4
MW
245/* If we couldn't find any interesting entries then we can switch all of this
246 * machinery off. Also do that if we have no means for atomic updates.
247 */
248#if WANT_ANY && CPU_DISPATCH_P
249
250/* The main output of this section is a bitmask of detected features. The
251 * least significant bit will be set if we've tried to probe. Always access
252 * this using `DISPATCH_LOAD' and `DISPATCH_STORE'.
253 */
254static unsigned hwcaps = 0;
255
256/* For each potentially interesting type which turned out not to exist or be
257 * wanted, define a dummy macro for the sake of the next step.
258 */
259#ifndef WANT_AT_HWCAP
260# define WANT_AT_HWCAP(_)
261#endif
f013a4f2
MW
262#ifndef WANT_AT_HWCAP2
263# define WANT_AT_HWCAP2(_)
264#endif
a02a22d4
MW
265
266/* For each CPU family, define two lists.
267 *
268 * * `WANTAUX' is a list of the `WANT_AT_MUMBLE' macros which the CPU
269 * family tried to register interest in above. Each entry contains the
270 * interesting auxiliary vector entry type, the name of the union branch
271 * for its value, and the name of the slot in `struct auxprobe' in which
272 * to store the value.
273 *
274 * * `CAPMAP' is a list describing the output features which the CPU family
275 * intends to satisfy from the auxiliary vector. Each entry contains a
276 * feature name suffix, and the token name (for `check_env').
277 */
61bd904b
MW
278#if CPUFAM_ARMEL
279# define WANTAUX(_) \
26e182fc
MW
280 WANT_AT_HWCAP(_) \
281 WANT_AT_HWCAP2(_)
61bd904b
MW
282# define CAPMAP(_) \
283 _(ARM_VFP, "arm:vfp") \
284 _(ARM_NEON, "arm:neon") \
285 _(ARM_V4, "arm:v4") \
26e182fc 286 _(ARM_D32, "arm:d32") \
9e6a4409
MW
287 _(ARM_AES, "arm:aes") \
288 _(ARM_PMULL, "arm:pmull")
61bd904b 289#endif
e492db88
MW
290#if CPUFAM_ARM64
291# define WANTAUX(_) \
292 WANT_AT_HWCAP(_)
293# define CAPMAP(_) \
9e6a4409
MW
294 _(ARM_AES, "arm:aes") \
295 _(ARM_PMULL, "arm:pmull")
e492db88 296#endif
a02a22d4
MW
297
298/* Build the bitmask for `hwcaps' from the `CAPMAP' list. */
299enum {
300 HFI_PROBED = 0,
301#define HFI__ENUM(feat, tok) HFI_##feat,
302 CAPMAP(HFI__ENUM)
303#undef HFI__ENUM
304 HFI__END
305};
306enum {
307 HF_PROBED = 1,
308#define HF__FLAG(feat, tok) HF_##feat = 1 << HFI_##feat,
309 CAPMAP(HF__FLAG)
310#undef HF__FLAG
311 HF__END
312};
313
314/* Build a structure in which we can capture the interesting data from the
315 * auxiliary vector.
316 */
317#define AUXUTYPE_i long
318#define AUXUTYPE_u unsigned long
319#define AUXUTYPE_p const void *
320struct auxprobe {
321#define AUXPROBE__SLOT(type, ubranch, slot) AUXUTYPE_##ubranch slot;
322 WANTAUX(AUXPROBE__SLOT)
323#undef AUXPROBE_SLOT
324};
325
326/* --- @probe_hwcaps@ --- *
327 *
328 * Arguments: ---
329 *
330 * Returns: ---
331 *
332 * Use: Attempt to find the auxiliary vector (which is well hidden)
333 * and discover interesting features from it.
334 */
335
336static void probe_hwcaps(void)
337{
338 unsigned hw = HF_PROBED;
339 struct auxprobe probed = { 0 };
340
341 /* Populate `probed' with the information we manage to retrieve from the
342 * auxiliary vector. Slots we couldn't find are left zero-valued.
343 */
344#if defined(HAVE_GETAUXVAL)
345 /* Shiny new libc lets us request individual entry types. This is almost
346 * too easy.
347 */
84850eec
MW
348# define CAP__GET(type, ubranch, slot) \
349 probed.slot = (AUXUTYPE_##ubranch)getauxval(type);
a02a22d4
MW
350 WANTAUX(CAP__GET)
351#else
352 /* Otherwise we're a bit stuck, really. Modern Linux kernels make a copy
353 * of the vector available in `/procc' so we could try that.
354 *
355 * The usual place is stuck on the end of the environment vector, but that
356 * may well have moved, and we have no way of telling whether it has or
357 * whether there was ever an auxiliary vector there at all; so don't do
358 * that.
359 */
360 {
361 FILE *fp = 0;
362 unsigned char *p = 0, *q = 0;
363 const struct auxentry *a;
364 size_t sz, off, n;
365
366 /* Open the file and read it into a memory chunk. */
367 if ((fp = fopen("/proc/self/auxv", "rb")) == 0) goto clean;
368 sz = 4096; off = 0;
369 if ((p = malloc(sz)) == 0) goto clean;
370 for (;;) {
371 n = fread(p + off, 1, sz - off, fp);
372 off += n;
373 if (off < sz) break;
374 sz *= 2; if ((q = realloc(p, sz)) == 0) break;
375 p = q;
376 }
377
378 /* Work through the vector (or as much of it as we found) and extract the
379 * types we're interested in.
380 */
381 for (a = (const struct auxentry *)p,
382 n = sz/sizeof(struct auxentry);
383 n--; a++) {
384 switch (a->type) {
385#define CAP__SWITCH(type, ubranch, slot) \
386 case type: probed.slot = a->value.ubranch; break;
387 WANTAUX(CAP__SWITCH)
dfcb2a0b 388 case AT_NULL: goto clean;
a02a22d4
MW
389 }
390 }
391
392 clean:
393 if (p) free(p);
394 if (fp) fclose(fp);
395 }
396#endif
397
398 /* Each CPU family now has to pick through what was found and stashed in
399 * `probed', and set the appropriate flag bits in `hw'.
400 */
61bd904b
MW
401#if CPUFAM_ARMEL
402 if (probed.hwcap & HWCAP_VFPv3) hw |= HF_ARM_VFP;
403 if (probed.hwcap & HWCAP_NEON) hw |= HF_ARM_NEON;
404 if (probed.hwcap & HWCAP_VFPD32) hw |= HF_ARM_D32;
405 if (probed.hwcap & HWCAP_VFPv4) hw |= HF_ARM_V4;
26e182fc
MW
406# ifdef HWCAP2_AES
407 if (probed.hwcap2 & HWCAP2_AES) hw |= HF_ARM_AES;
408# endif
9e6a4409
MW
409# ifdef HWCAP2_PMULL
410 if (probed.hwcap2 & HWCAP2_PMULL) hw |= HF_ARM_PMULL;
411# endif
61bd904b 412#endif
e492db88
MW
413#if CPUFAM_ARM64
414 if (probed.hwcap & HWCAP_AES) hw |= HF_ARM_AES;
9e6a4409 415 if (probed.hwcap & HWCAP_PMULL) hw |= HF_ARM_PMULL;
e492db88 416#endif
a02a22d4
MW
417
418 /* Store the bitmask of features we probed for everyone to see. */
419 DISPATCH_STORE(hwcaps, hw);
420
421 /* Finally, make a report about the things we found. (Doing this earlier
422 * will pointlessly widen the window in which multiple threads will do the
423 * above auxiliary-vector probing.)
424 */
425#define CAP__DEBUG(feat, tok) \
426 dispatch_debug("check auxv for feature `%s': %s", tok, \
427 hw & HF_##feat ? "available" : "absent");
428 CAPMAP(CAP__DEBUG)
429#undef CAP__DEBUG
430}
431
432/* --- @get_hwcaps@ --- *
433 *
434 * Arguments: ---
435 *
436 * Returns: A mask of hardware capabilities and other features, as probed
437 * from the auxiliary vector.
438 */
439
440static unsigned get_hwcaps(void)
441{
442 unsigned hw;
443
444 DISPATCH_LOAD(hwcaps, hw);
445 if (!(hwcaps & HF_PROBED)) { probe_hwcaps(); DISPATCH_LOAD(hwcaps, hw); }
446 return (hw);
447}
448
449#endif
450
d26ad211
MW
451/*----- External interface ------------------------------------------------*/
452
fac645f7
MW
453/* --- @dispatch_debug@ --- *
454 *
455 * Arguments: @const char *fmt@ = a format string
456 * @...@ = additional arguments
457 *
458 * Returns: ---
459 *
460 * Use: Writes a formatted message to standard output if dispatch
461 * debugging is enabled.
462 */
463
464void dispatch_debug(const char *fmt, ...)
465{
466 va_list ap;
467 const char *e = getenv("CATACOMB_CPUDISPATCH_DEBUG");
468
469 if (e && *e != 'n' && *e != '0') {
470 va_start(ap, fmt);
471 fputs("Catacomb CPUDISPATCH: ", stderr);
472 vfprintf(stderr, fmt, ap);
473 fputc('\n', stderr);
474 va_end(ap);
475 }
476}
477
08e2be29
MW
478/* --- @check_env@ --- *
479 *
480 * Arguments: @const char *ftok@ = feature token
481 *
482 * Returns: Zero if the feature is forced off; positive if it's forced
483 * on; negative if the user hasn't decided.
484 *
485 * Use: Checks the environment variable `CATACOMB_CPUFEAT' for the
486 * feature token @ftok@. The variable, if it exists, should be
487 * a space-separated sequence of `+tok' and `-tok' items. These
488 * tokens may end in `*', which matches any suffix.
489 */
490
491static int IGNORABLE check_env(const char *ftok)
492{
493 const char *p, *q, *pp;
494 int d;
495
496 p = getenv("CATACOMB_CPUFEAT");
497 if (!p) return (-1);
498
499 for (;;) {
500 while (isspace((unsigned char)*p)) p++;
501 if (!*p) return (-1);
502 switch (*p) {
503 case '+': d = +1; p++; break;
504 case '-': d = 0; p++; break;
505 default: d = -1; break;
506 }
507 for (q = p; *q && !isspace((unsigned char)*q); q++);
508 if (d >= 0) {
509 for (pp = ftok; p < q && *pp && *p == *pp; p++, pp++);
510 if ((p == q && !*pp) || (*p == '*' && p + 1 == q)) return (d);
511 }
512 p = q;
513 }
514 return (-1);
515}
516
517/* --- @cpu_feature_p@ --- *
518 *
519 * Arguments: @unsigned feat@ = a @CPUFEAT_...@ code
520 *
521 * Returns: Nonzero if the feature is available.
522 */
523
524#include <stdio.h>
525
fac645f7
MW
526static int IGNORABLE
527 feat_debug(const char *ftok, const char *check, int verdict)
528{
529 if (verdict >= 0) {
530 dispatch_debug("feature `%s': %s -> %s", ftok, check,
531 verdict ? "available" : "absent");
532 }
533 return (verdict);
534}
535
08e2be29
MW
536int cpu_feature_p(int feat)
537{
538 int IGNORABLE f;
539 IGNORE(f);
fac645f7
MW
540#define CASE_CPUFEAT(feat, ftok, cond) case CPUFEAT_##feat: \
541 if ((f = feat_debug(ftok, "environment override", \
542 check_env(ftok))) >= 0) \
543 return (f); \
544 else \
545 return (feat_debug(ftok, "runtime probe", cond));
08e2be29
MW
546
547 switch (feat) {
0f23f75f 548#if CPUFAM_X86 || CPUFAM_AMD64
fac645f7 549 CASE_CPUFEAT(X86_SSE2, "x86:sse2",
4fab22c2
MW
550 cpuid_features_p(CPUID1D_SSE2, 0) &&
551 xmm_registers_available_p());
fac645f7 552 CASE_CPUFEAT(X86_AESNI, "x86:aesni",
4fab22c2
MW
553 cpuid_features_p(CPUID1D_SSE2, CPUID1C_AESNI) &&
554 xmm_registers_available_p());
d25653be
MW
555 CASE_CPUFEAT(X86_RDRAND, "x86:rdrand",
556 cpuid_features_p(0, CPUID1C_RDRAND));
b9b279b4 557 CASE_CPUFEAT(X86_AVX, "x86:avx",
6af2607b
MW
558 cpuid_features_p(0, CPUID1C_AVX) &&
559 xmm_registers_available_p());
9e6a4409 560 CASE_CPUFEAT(X86_SSSE3, "x86:ssse3",
6af2607b
MW
561 cpuid_features_p(0, CPUID1C_SSSE3) &&
562 xmm_registers_available_p());
9e6a4409 563 CASE_CPUFEAT(X86_PCLMUL, "x86:pclmul",
6af2607b
MW
564 cpuid_features_p(0, CPUID1C_PCLMUL) &&
565 xmm_registers_available_p());
08e2be29 566#endif
a02a22d4
MW
567#ifdef CAPMAP
568# define FEATP__CASE(feat, tok) \
0aec0658 569 CASE_CPUFEAT(feat, tok, get_hwcaps() & HF_##feat)
a02a22d4
MW
570 CAPMAP(FEATP__CASE)
571#undef FEATP__CASE
572#endif
08e2be29 573 default:
fac645f7 574 dispatch_debug("denying unknown feature %d", feat);
08e2be29
MW
575 return (0);
576 }
fac645f7 577#undef CASE_CPUFEAT
08e2be29
MW
578}
579
580/*----- That's all, folks -------------------------------------------------*/