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