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