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