chiark / gitweb /
base/dispatch.c, base/dispatch-x86ish.S: Add opcode to `rdrand_works_p'.
[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 };
60
61 struct cpuid { unsigned a, b, c, d; };
62 extern int dispatch_x86ish_cpuid(struct cpuid *, unsigned a, unsigned c);
63 extern int dispatch_x86ish_xmmregisters_p(void);
64 extern int dispatch_x86ish_rdrand(unsigned op, unsigned *);
65
66 static void cpuid(struct cpuid *cc, unsigned a, unsigned c)
67 {
68   int rc = dispatch_x86ish_cpuid(cc, a, c);
69   if (rc)
70     dispatch_debug("CPUID instruction not available");
71   else
72     dispatch_debug("CPUID(%08x, %08x) -> %08x, %08x, %08x, %08x",
73                    a, c, cc->a, cc->b, cc->c, cc->d);
74 }
75
76 static unsigned cpuid_maxleaf(void)
77   { struct cpuid c; cpuid(&c, 0, 0); return (c.a); }
78
79 /* --- @cpuid_feature_p@ --- *
80  *
81  * Arguments:   @unsigned leaf@ = leaf to look up
82  *              @unsigned bits@ = bits to check
83  *
84  * Returns:     Nonzero if all the requested bits are set in the requested
85  *              CPUID result.
86  */
87
88 static int cpuid_feature_p(unsigned leaf, unsigned bits)
89 {
90   struct cpuid c;
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);
106 }
107
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
116 static int xmm_registers_available_p(void)
117 {
118   int f = dispatch_x86ish_xmmregisters_p();
119
120   dispatch_debug("XMM registers %savailable", f ? "" : "not ");
121   return (f);
122 }
123
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
133 enum { OP_RDRAND, OP_RDSEED };
134
135 static int rdrand_works_p(unsigned op)
136 {
137   unsigned ref, x, i;
138   const char *what;
139
140   switch (op) {
141     case OP_RDRAND: what = "RDRAND"; break;
142     default: assert(!"unexpected op");
143   }
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    */
149   if (dispatch_x86ish_rdrand(op, &ref)) goto fail;
150   for (i = 0; i < 4; i++) {
151     if (dispatch_x86ish_rdrand(op, &x)) goto fail;
152     if (x != ref) goto not_stuck;
153   }
154   dispatch_debug("%s always returns 0x%08x!", what, ref);
155   return (0);
156
157 not_stuck:
158   dispatch_debug("%s instruction looks plausible", what);
159   return (1);
160
161 fail:
162   dispatch_debug("%s instruction fails too often", what);
163   return (0);
164 }
165
166 #endif
167
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>
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>
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  */
185 union auxval { long i; unsigned long u; const void *p; };
186 struct 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  */
192 #if defined(AT_HWCAP) && CPUFAM_ARMEL
193 #  define WANT_ANY 1
194 #  define WANT_AT_HWCAP(_) _(AT_HWCAP, u, hwcap)
195 #endif
196
197 #if defined(AT_HWCAP) && CPUFAM_ARM64
198 #  define WANT_ANY 1
199 #  define WANT_AT_HWCAP(_) _(AT_HWCAP, u, hwcap)
200 #endif
201
202 #if defined(AT_HWCAP2) && CPUFAM_ARMEL
203 #  define WANT_ANY 1
204 #  define WANT_AT_HWCAP2(_) _(AT_HWCAP2, u, hwcap2)
205 #endif
206
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  */
216 static 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
224 #ifndef WANT_AT_HWCAP2
225 #  define WANT_AT_HWCAP2(_)
226 #endif
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  */
240 #if CPUFAM_ARMEL
241 #  define WANTAUX(_)                                                    \
242         WANT_AT_HWCAP(_)                                                \
243         WANT_AT_HWCAP2(_)
244 #  define CAPMAP(_)                                                     \
245         _(ARM_VFP, "arm:vfp")                                           \
246         _(ARM_NEON, "arm:neon")                                         \
247         _(ARM_V4, "arm:v4")                                             \
248         _(ARM_D32, "arm:d32")                                           \
249         _(ARM_AES, "arm:aes")                                           \
250         _(ARM_PMULL, "arm:pmull")
251 #endif
252 #if CPUFAM_ARM64
253 #  define WANTAUX(_)                                                    \
254         WANT_AT_HWCAP(_)
255 #  define CAPMAP(_)                                                     \
256         _(ARM_NEON, "arm:neon")                                         \
257         _(ARM_AES, "arm:aes")                                           \
258         _(ARM_PMULL, "arm:pmull")
259 #endif
260
261 /* Build the bitmask for `hwcaps' from the `CAPMAP' list. */
262 enum {
263   HFI_PROBED = 0,
264 #define HFI__ENUM(feat, tok) HFI_##feat,
265   CAPMAP(HFI__ENUM)
266 #undef HFI__ENUM
267   HFI__END
268 };
269 enum {
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 *
283 struct 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
299 static 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    */
311 #  define CAP__GET(type, ubranch, slot)                                 \
312         probed.slot = (AUXUTYPE_##ubranch)getauxval(type);
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)
351         case AT_NULL: goto clean;
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    */
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;
369 #  ifdef HWCAP2_AES
370   if (probed.hwcap2 & HWCAP2_AES) hw |= HF_ARM_AES;
371 #  endif
372 #  ifdef HWCAP2_PMULL
373   if (probed.hwcap2 & HWCAP2_PMULL) hw |= HF_ARM_PMULL;
374 #  endif
375 #endif
376 #if CPUFAM_ARM64
377   if (probed.hwcap & HWCAP_ASIMD) hw |= HF_ARM_NEON;
378   if (probed.hwcap & HWCAP_AES) hw |= HF_ARM_AES;
379   if (probed.hwcap & HWCAP_PMULL) hw |= HF_ARM_PMULL;
380 #endif
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
404 static 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
415 /*----- External interface ------------------------------------------------*/
416
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
428 void 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
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
455 static 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 (;;) {
464     while (ISSPACE(*p)) p++;
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     }
471     for (q = p; *q && !ISSPACE(*q); q++);
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
490 static 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
500 int cpu_feature_p(int feat)
501 {
502   int IGNORABLE f;
503   IGNORE(f);
504 #define CASE_CPUFEAT(feat, ftok, cond) case CPUFEAT_##feat:             \
505   if ((f = feat_debug(ftok, "environment override", check_env(ftok))) >= 0) \
506     return (f);                                                         \
507   else                                                                  \
508     return (feat_debug(ftok, "runtime probe", cond));
509
510   switch (feat) {
511 #if CPUFAM_X86 || CPUFAM_AMD64
512     CASE_CPUFEAT(X86_SSE2, "x86:sse2",
513                  cpuid_feature_p(CPUID_1_D, CPUID1D_SSE2) &&
514                  xmm_registers_available_p());
515     CASE_CPUFEAT(X86_AESNI, "x86:aesni",
516                  cpuid_feature_p(CPUID_1_D, CPUID1C_AESNI) &&
517                  xmm_registers_available_p());
518     CASE_CPUFEAT(X86_RDRAND, "x86:rdrand",
519                  cpuid_feature_p(CPUID_1_C, CPUID1C_RDRAND) &&
520                  rdrand_works_p(OP_RDRAND));
521     CASE_CPUFEAT(X86_AVX, "x86:avx",
522                  cpuid_feature_p(CPUID_1_C, CPUID1C_AVX) &&
523                  xmm_registers_available_p());
524     CASE_CPUFEAT(X86_SSSE3, "x86:ssse3",
525                  cpuid_feature_p(CPUID_1_C, CPUID1C_SSSE3) &&
526                  xmm_registers_available_p());
527     CASE_CPUFEAT(X86_PCLMUL, "x86:pclmul",
528                  cpuid_feature_p(CPUID_1_C, CPUID1C_PCLMUL) &&
529                  xmm_registers_available_p());
530 #endif
531 #ifdef CAPMAP
532 #  define FEATP__CASE(feat, tok)                                        \
533         CASE_CPUFEAT(feat, tok, get_hwcaps() & HF_##feat)
534     CAPMAP(FEATP__CASE)
535 #undef FEATP__CASE
536 #endif
537     default:
538       dispatch_debug("denying unknown feature %d", feat);
539       return (0);
540   }
541 #undef CASE_CPUFEAT
542 }
543
544 /*----- That's all, folks -------------------------------------------------*/