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