chiark / gitweb /
base/dispatch.c: Stop parsing the auxiliary vector when we hit `AT_NULL'.
[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 EFLAGS_ID (1u << 21)
47 #  define CPUID1D_SSE2 (1u << 26)
48 #  define CPUID1D_FXSR (1u << 24)
49 #  define CPUID1C_AESNI (1u << 25)
50
51 struct cpuid { unsigned a, b, c, d; };
52
53 /* --- @cpuid@ --- *
54  *
55  * Arguments:   @struct cpuid *cc@ = where to write the result
56  *              @unsigned a, c@ = EAX and ECX registers to set
57  *
58  * Returns:     ---
59  *
60  * Use:         Minimal C wrapper around the x86 `CPUID' instruction.  Checks
61  *              that the instruction is actually available before invoking
62  *              it; fills the output structure with zero if it's not going to
63  *              work.
64  */
65
66 #ifdef __GNUC__
67 #  if CPUFAM_X86
68 static __inline__ unsigned getflags(void)
69   { unsigned f; __asm__ ("pushf; popl %0" : "=g" (f)); return (f); }
70 static __inline__ unsigned setflags(unsigned f)
71 {
72   unsigned ff;
73   __asm__ ("pushf; pushl %1; popf; pushf; popl %0; popf"
74            : "=g" (ff)
75            : "g" (f));
76   return (ff);
77 }
78 #  else
79 static __inline__ unsigned long getflags(void)
80   { unsigned long f; __asm__ ("pushf; popq %0" : "=g" (f)); return (f); }
81 static __inline__ unsigned long long setflags(unsigned long f)
82 {
83   unsigned long ff;
84   __asm__ ("pushf; pushq %1; popf; pushf; popq %0; popf"
85            : "=g" (ff)
86            : "g" (f));
87   return (ff);
88 }
89 #  endif
90 #endif
91
92 static void cpuid(struct cpuid *cc, unsigned a, unsigned c)
93 {
94 #ifdef __GNUC__
95   unsigned f;
96 #endif
97
98   cc->a = cc->b = cc->c = cc->d = 0;
99
100 #ifdef __GNUC__
101   /* Stupid dance to detect whether the CPUID instruction is available. */
102   f = getflags();
103   if (!(setflags(f |  EFLAGS_ID) & EFLAGS_ID) ||
104         setflags(f & ~EFLAGS_ID) & EFLAGS_ID) {
105     dispatch_debug("CPUID instruction not available");
106     return;
107   }
108   setflags(f);
109
110   /* Alas, EBX is magical in PIC code, so abuse ESI instead.  This isn't
111    * pretty, but it works.
112    */
113 #  if CPUFAM_X86
114   __asm__ ("pushl %%ebx; cpuid; movl %%ebx, %%esi; popl %%ebx"
115            : "=a" (cc->a), "=S" (cc->b), "=c" (cc->c), "=d" (cc->d)
116            : "a" (a) , "c" (c));
117 #  elif CPUFAM_AMD64
118   __asm__ ("pushq %%rbx; cpuid; movl %%ebx, %%esi; popq %%rbx"
119            : "=a" (cc->a), "=S" (cc->b), "=c" (cc->c), "=d" (cc->d)
120            : "a" (a) , "c" (c));
121 #  else
122 #    error "I'm confused."
123 #  endif
124   dispatch_debug("CPUID(%08x, %08x) -> %08x, %08x, %08x, %08x",
125                  a, c, cc->a, cc->b, cc->c, cc->d);
126 #else
127   dispatch_debug("GNU inline assembler not available; can't CPUID");
128 #endif
129 }
130
131 static unsigned cpuid_maxleaf(void)
132   { struct cpuid c; cpuid(&c, 0, 0); return (c.a); }
133
134 /* --- @cpuid_features_p@ --- *
135  *
136  * Arguments:   @unsigned dbits@ = bits to check in EDX
137  *              @unsigned cbits@ = bits to check in ECX
138  *
139  * Returns:     Nonzero if all the requested bits are set in the CPUID result
140  *              on leaf 1.
141  */
142
143 static int cpuid_features_p(unsigned dbits, unsigned cbits)
144 {
145   struct cpuid c;
146   if (cpuid_maxleaf() < 1) return (0);
147   cpuid(&c, 1, 0);
148   return ((c.d & dbits) == dbits && (c.c & cbits) == cbits);
149 }
150
151 /* --- @xmm_registers_available_p@ --- *
152  *
153  * Arguments:   ---
154  *
155  * Returns:     Nonzero if the operating system has made the XMM registers
156  *              available for use.
157  */
158
159 static int xmm_registers_available_p(void)
160 {
161 #ifdef __GNUC__
162   unsigned f;
163   /* This hack is by Agner Fog.  Use FXSAVE/FXRSTOR to figure out whether the
164    * XMM registers are actually alive.
165    */
166   if (!cpuid_features_p(CPUID1D_FXSR, 0)) return (0);
167 #  if CPUFAM_X86
168   __asm__ ("movl %%esp, %%edx; subl $512, %%esp; andl $~15, %%esp\n"
169            "fxsave (%%esp)\n"
170            "movl 160(%%esp), %%eax; xorl $0xaaaa5555, 160(%%esp)\n"
171            "fxrstor (%%esp); fxsave (%%esp)\n"
172            "movl 160(%%esp), %%ecx; movl %%eax, 160(%%esp)\n"
173            "fxrstor (%%esp); movl %%edx, %%esp\n"
174            "xorl %%ecx, %%eax"
175            : "=a" (f)
176            : /* no inputs */
177            : "%ecx", "%edx");
178 #  elif CPUFAM_AMD64
179   __asm__ ("movq %%rsp, %%rdx; subq $512, %%rsp; andq $~15, %%rsp\n"
180            "fxsave (%%rsp)\n"
181            "movl 160(%%rsp), %%eax; xorl $0xaaaa5555, 160(%%rsp)\n"
182            "fxrstor (%%rsp); fxsave (%%rsp)\n"
183            "movl 160(%%rsp), %%ecx; movl %%eax, 160(%%rsp)\n"
184            "fxrstor (%%rsp); movq %%rdx, %%rsp\n"
185            "xorl %%ecx, %%eax"
186            : "=a" (f)
187            : /* no inputs */
188            : "%ecx", "%rdx");
189 #  else
190 #    error "I'm confused."
191 #  endif
192   dispatch_debug("XMM registers %savailable", f ? "" : "not ");
193   return (f);
194 #else
195   dispatch_debug("GNU inline assembler not available; can't check for XMM");
196   return (0);
197 #endif
198 }
199
200 #endif
201
202 /*----- General feature probing using auxiliary vectors -------------------*/
203
204 /* Try to find the system's definitions for auxiliary vector entries. */
205 #ifdef HAVE_SYS_AUXV_H
206 #  include <sys/auxv.h>
207 #else
208 #  ifdef HAVE_LINUX_AUXVEC_H
209 #    include <linux/auxvec.h>
210 #  endif
211 #  ifdef HAVE_ASM_HWCAP_H
212 #    include <asm/hwcap.h>
213 #  endif
214 #endif
215
216 /* The type of entries in the auxiliary vector.  I'm assuming that `unsigned
217  * long' matches each platform's word length; if this is false then we'll
218  * need some host-specific tweaking here.
219  */
220 union auxval { long i; unsigned long u; const void *p; };
221 struct auxentry { unsigned long type; union auxval value; };
222
223 /* Register each CPU family's interest in the auxiliary vector.  Make sure
224  * that the necessary entry types are defined.  This is primarily ordered by
225  * entry type to minimize duplication.
226  */
227 #if defined(AT_HWCAP) && CPUFAM_ARMEL
228 #  define WANT_ANY 1
229 #  define WANT_AT_HWCAP(_) _(AT_HWCAP, u, hwcap)
230 #endif
231
232 /* If we couldn't find any interesting entries then we can switch all of this
233  * machinery off.  Also do that if we have no means for atomic updates.
234  */
235 #if WANT_ANY && CPU_DISPATCH_P
236
237 /* The main output of this section is a bitmask of detected features.  The
238  * least significant bit will be set if we've tried to probe.  Always access
239  * this using `DISPATCH_LOAD' and `DISPATCH_STORE'.
240  */
241 static unsigned hwcaps = 0;
242
243 /* For each potentially interesting type which turned out not to exist or be
244  * wanted, define a dummy macro for the sake of the next step.
245  */
246 #ifndef WANT_AT_HWCAP
247 #  define WANT_AT_HWCAP(_)
248 #endif
249
250 /* For each CPU family, define two lists.
251  *
252  *   * `WANTAUX' is a list of the `WANT_AT_MUMBLE' macros which the CPU
253  *     family tried to register interest in above.  Each entry contains the
254  *     interesting auxiliary vector entry type, the name of the union branch
255  *     for its value, and the name of the slot in `struct auxprobe' in which
256  *     to store the value.
257  *
258  *   * `CAPMAP' is a list describing the output features which the CPU family
259  *     intends to satisfy from the auxiliary vector.  Each entry contains a
260  *     feature name suffix, and the token name (for `check_env').
261  */
262 #if CPUFAM_ARMEL
263 #  define WANTAUX(_)                                                    \
264         WANT_AT_HWCAP(_)
265 #  define CAPMAP(_)                                                     \
266         _(ARM_VFP, "arm:vfp")                                           \
267         _(ARM_NEON, "arm:neon")                                         \
268         _(ARM_V4, "arm:v4")                                             \
269         _(ARM_D32, "arm:d32")
270 #endif
271
272 /* Build the bitmask for `hwcaps' from the `CAPMAP' list. */
273 enum {
274   HFI_PROBED = 0,
275 #define HFI__ENUM(feat, tok) HFI_##feat,
276   CAPMAP(HFI__ENUM)
277 #undef HFI__ENUM
278   HFI__END
279 };
280 enum {
281   HF_PROBED = 1,
282 #define HF__FLAG(feat, tok) HF_##feat = 1 << HFI_##feat,
283   CAPMAP(HF__FLAG)
284 #undef HF__FLAG
285   HF__END
286 };
287
288 /* Build a structure in which we can capture the interesting data from the
289  * auxiliary vector.
290  */
291 #define AUXUTYPE_i long
292 #define AUXUTYPE_u unsigned long
293 #define AUXUTYPE_p const void *
294 struct auxprobe {
295 #define AUXPROBE__SLOT(type, ubranch, slot) AUXUTYPE_##ubranch slot;
296   WANTAUX(AUXPROBE__SLOT)
297 #undef AUXPROBE_SLOT
298 };
299
300 /* --- @probe_hwcaps@ --- *
301  *
302  * Arguments:   ---
303  *
304  * Returns:     ---
305  *
306  * Use:         Attempt to find the auxiliary vector (which is well hidden)
307  *              and discover interesting features from it.
308  */
309
310 static void probe_hwcaps(void)
311 {
312   unsigned hw = HF_PROBED;
313   struct auxprobe probed = { 0 };
314
315   /* Populate `probed' with the information we manage to retrieve from the
316    * auxiliary vector.  Slots we couldn't find are left zero-valued.
317    */
318 #if defined(HAVE_GETAUXVAL)
319   /* Shiny new libc lets us request individual entry types.  This is almost
320    * too easy.
321    */
322 #  define CAP__GET(type, slot, ubranch)                                 \
323         probed.slot.ubranch = (AUXUTYPE_##ubranch)getauxval(type);
324   WANTAUX(CAP__GET)
325 #else
326   /* Otherwise we're a bit stuck, really.  Modern Linux kernels make a copy
327    * of the vector available in `/procc' so we could try that.
328    *
329    * The usual place is stuck on the end of the environment vector, but that
330    * may well have moved, and we have no way of telling whether it has or
331    * whether there was ever an auxiliary vector there at all; so don't do
332    * that.
333    */
334   {
335     FILE *fp = 0;
336     unsigned char *p = 0, *q = 0;
337     const struct auxentry *a;
338     size_t sz, off, n;
339
340     /* Open the file and read it into a memory chunk. */
341     if ((fp = fopen("/proc/self/auxv", "rb")) == 0) goto clean;
342     sz = 4096; off = 0;
343     if ((p = malloc(sz)) == 0) goto clean;
344     for (;;) {
345       n = fread(p + off, 1, sz - off, fp);
346       off += n;
347       if (off < sz) break;
348       sz *= 2; if ((q = realloc(p, sz)) == 0) break;
349       p = q;
350     }
351
352     /* Work through the vector (or as much of it as we found) and extract the
353      * types we're interested in.
354      */
355     for (a = (const struct auxentry *)p,
356            n = sz/sizeof(struct auxentry);
357          n--; a++) {
358       switch (a->type) {
359 #define CAP__SWITCH(type, ubranch, slot)                                \
360         case type: probed.slot = a->value.ubranch; break;
361         WANTAUX(CAP__SWITCH)
362         case AT_NULL: goto clean;
363       }
364     }
365
366   clean:
367     if (p) free(p);
368     if (fp) fclose(fp);
369   }
370 #endif
371
372   /* Each CPU family now has to pick through what was found and stashed in
373    * `probed', and set the appropriate flag bits in `hw'.
374    */
375 #if CPUFAM_ARMEL
376   if (probed.hwcap & HWCAP_VFPv3) hw |= HF_ARM_VFP;
377   if (probed.hwcap & HWCAP_NEON) hw |= HF_ARM_NEON;
378   if (probed.hwcap & HWCAP_VFPD32) hw |= HF_ARM_D32;
379   if (probed.hwcap & HWCAP_VFPv4) hw |= HF_ARM_V4;
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((unsigned char)*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((unsigned char)*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",                     \
506                       check_env(ftok))) >= 0)                           \
507     return (f);                                                         \
508   else                                                                  \
509     return (feat_debug(ftok, "runtime probe", cond));
510
511   switch (feat) {
512 #if CPUFAM_X86 || CPUFAM_AMD64
513     CASE_CPUFEAT(X86_SSE2, "x86:sse2",
514                  xmm_registers_available_p() &&
515                  cpuid_features_p(CPUID1D_SSE2, 0));
516     CASE_CPUFEAT(X86_AESNI, "x86:aesni",
517                  xmm_registers_available_p() &&
518                  cpuid_features_p(CPUID1D_SSE2, CPUID1C_AESNI));
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 -------------------------------------------------*/