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