base/dispatch.c, base/dispatch-x86ish.S: Add opcode to `rdrand_works_p'.
[catacomb] / base / dispatch.c
index 337f2be..bda7f88 100644 (file)
 
 #include "config.h"
 
+#include <assert.h>
 #include <ctype.h>
+#include <stdarg.h>
+#include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 
 
 /*----- Intel x86/AMD64 feature probing -----------------------------------*/
 
-#ifdef CPUFAM_X86
+#if CPUFAM_X86 || CPUFAM_AMD64
+
+enum {
+  CPUID_1_D,                           /* eax = 1 => edx&?? */
+#  define CPUID1D_SSE2 (1u << 26)
+#  define CPUID1D_FXSR (1u << 24)
 
-#define EFLAGS_ID (1u << 21)
-#define CPUID1D_SSE2 (1u << 26)
-#define CPUID1D_FXSR (1u << 24)
-#define CPUID1C_AESNI (1u << 25)
+  CPUID_1_C,                           /* eax = 1 => ecx&?? */
+#  define CPUID1C_PCLMUL (1u << 1)
+#  define CPUID1C_SSSE3 (1u << 9)
+#  define CPUID1C_AESNI (1u << 25)
+#  define CPUID1C_AVX (1u << 28)
+#  define CPUID1C_RDRAND (1u << 30)
+
+};
 
 struct cpuid { unsigned a, b, c, d; };
+extern int dispatch_x86ish_cpuid(struct cpuid *, unsigned a, unsigned c);
+extern int dispatch_x86ish_xmmregisters_p(void);
+extern int dispatch_x86ish_rdrand(unsigned op, unsigned *);
+
+static void cpuid(struct cpuid *cc, unsigned a, unsigned c)
+{
+  int rc = dispatch_x86ish_cpuid(cc, a, c);
+  if (rc)
+    dispatch_debug("CPUID instruction not available");
+  else
+    dispatch_debug("CPUID(%08x, %08x) -> %08x, %08x, %08x, %08x",
+                  a, c, cc->a, cc->b, cc->c, cc->d);
+}
+
+static unsigned cpuid_maxleaf(void)
+  { struct cpuid c; cpuid(&c, 0, 0); return (c.a); }
 
-/* --- @cpuid@ --- *
+/* --- @cpuid_feature_p@ --- *
  *
- * Arguments:  @struct cpuid *cc@ = where to write the result
- *             @unsigned a, c@ = EAX and ECX registers to set
+ * Arguments:  @unsigned leaf@ = leaf to look up
+ *             @unsigned bits@ = bits to check
  *
- * Returns:    ---
+ * Returns:    Nonzero if all the requested bits are set in the requested
+ *             CPUID result.
+ */
+
+static int cpuid_feature_p(unsigned leaf, unsigned bits)
+{
+  struct cpuid c;
+  unsigned r;
+
+  switch (leaf) {
+    case CPUID_1_D:
+      if (cpuid_maxleaf() < 1) return (0);
+      cpuid(&c, 1, 0); r = c.d;
+      break;
+    case CPUID_1_C:
+      if (cpuid_maxleaf() < 1) return (0);
+      cpuid(&c, 1, 0); r = c.c;
+      break;
+    default:
+      assert(!"unknown cpuid leaf");
+  }
+  return ((r&bits) == bits);
+}
+
+/* --- @xmm_registers_available_p@ --- *
  *
- * Use:                Minimal C wrapper around the x86 `CPUID' instruction.  Checks
- *             that the instruction is actually available before invoking
- *             it; fills the output structure with zero if it's not going to
- *             work.
+ * Arguments:  ---
+ *
+ * Returns:    Nonzero if the operating system has made the XMM registers
+ *             available for use.
  */
 
-#ifdef __GNUC__
-static __inline__ unsigned getflags(void)
-  { unsigned f; __asm__ ("pushf; popl %0" : "=g" (f)); return (f); }
-static __inline__ unsigned setflags(unsigned f)
+static int xmm_registers_available_p(void)
 {
-  unsigned ff;
-  __asm__ ("pushf; pushl %1; popf; pushf; popl %0; popf"
-          : "=g" (ff)
-          : "g" (f));
-  return (ff);
+  int f = dispatch_x86ish_xmmregisters_p();
+
+  dispatch_debug("XMM registers %savailable", f ? "" : "not ");
+  return (f);
 }
-#endif
 
-static void cpuid(struct cpuid *cc, unsigned a, unsigned c)
+/* --- @rdrand_works_p@ --- *
+ *
+ *
+ * Arguments:  ---
+ *
+ * Returns:    Nonzero if the `rdrand' instruction actually works.  Assumes
+ *             that it's already been verified to be safe to issue.
+ */
+
+enum { OP_RDRAND, OP_RDSEED };
+
+static int rdrand_works_p(unsigned op)
 {
-#ifdef __GNUC__
-  unsigned f;
+  unsigned ref, x, i;
+  const char *what;
+
+  switch (op) {
+    case OP_RDRAND: what = "RDRAND"; break;
+    default: assert(!"unexpected op");
+  }
+
+  /* Check that it doesn't always give the same answer.  Try four times: this
+   * will fail with probability %$2^{-128}$% with a truly random generator,
+   * which seems fair enough.
+   */
+  if (dispatch_x86ish_rdrand(op, &ref)) goto fail;
+  for (i = 0; i < 4; i++) {
+    if (dispatch_x86ish_rdrand(op, &x)) goto fail;
+    if (x != ref) goto not_stuck;
+  }
+  dispatch_debug("%s always returns 0x%08x!", what, ref);
+  return (0);
+
+not_stuck:
+  dispatch_debug("%s instruction looks plausible", what);
+  return (1);
+
+fail:
+  dispatch_debug("%s instruction fails too often", what);
+  return (0);
+}
+
 #endif
 
-  cc->a = cc->b = cc->c = cc->d = 0;
+/*----- General feature probing using auxiliary vectors -------------------*/
 
-#ifdef __GNUC__
-  /* Stupid dance to detect whether the CPUID instruction is available. */
-  f = getflags();
-  if (!(setflags(f |  EFLAGS_ID) & EFLAGS_ID)) return;
-  if (  setflags(f & ~EFLAGS_ID) & EFLAGS_ID ) return;
-  setflags(f);
+/* Try to find the system's definitions for auxiliary vector entries. */
+#ifdef HAVE_SYS_AUXV_H
+#  include <sys/auxv.h>
+#endif
+#ifdef HAVE_LINUX_AUXVEC_H
+#  include <linux/auxvec.h>
+#endif
+#ifdef HAVE_ASM_HWCAP_H
+#  include <asm/hwcap.h>
+#endif
 
-  /* Alas, EBX is magical in PIC code, so abuse ESI instead.  This isn't
-   * pretty, but it works.
-   */
-  __asm__ ("pushl %%ebx; cpuid; movl %%ebx, %%esi; popl %%ebx"
-          : "=a" (cc->a), "=S" (cc->b), "=c" (cc->c), "=d" (cc->d)
-          : "a" (a) , "c" (c));
+/* The type of entries in the auxiliary vector.  I'm assuming that `unsigned
+ * long' matches each platform's word length; if this is false then we'll
+ * need some host-specific tweaking here.
+ */
+union auxval { long i; unsigned long u; const void *p; };
+struct auxentry { unsigned long type; union auxval value; };
+
+/* Register each CPU family's interest in the auxiliary vector.  Make sure
+ * that the necessary entry types are defined.  This is primarily ordered by
+ * entry type to minimize duplication.
+ */
+#if defined(AT_HWCAP) && CPUFAM_ARMEL
+#  define WANT_ANY 1
+#  define WANT_AT_HWCAP(_) _(AT_HWCAP, u, hwcap)
 #endif
-}
 
-static unsigned cpuid_maxleaf(void)
-  { struct cpuid c; cpuid(&c, 0, 0); return (c.a); }
+#if defined(AT_HWCAP) && CPUFAM_ARM64
+#  define WANT_ANY 1
+#  define WANT_AT_HWCAP(_) _(AT_HWCAP, u, hwcap)
+#endif
 
-static int cpuid_features_p(unsigned dbits, unsigned cbits)
-{
-  struct cpuid c;
-  if (cpuid_maxleaf() < 1) return (0);
-  cpuid(&c, 1, 0);
-  return ((c.d & dbits) == dbits && (c.c & cbits) == cbits);
-}
+#if defined(AT_HWCAP2) && CPUFAM_ARMEL
+#  define WANT_ANY 1
+#  define WANT_AT_HWCAP2(_) _(AT_HWCAP2, u, hwcap2)
+#endif
 
-static int xmm_registers_available_p(void)
+/* If we couldn't find any interesting entries then we can switch all of this
+ * machinery off.  Also do that if we have no means for atomic updates.
+ */
+#if WANT_ANY && CPU_DISPATCH_P
+
+/* The main output of this section is a bitmask of detected features.  The
+ * least significant bit will be set if we've tried to probe.  Always access
+ * this using `DISPATCH_LOAD' and `DISPATCH_STORE'.
+ */
+static unsigned hwcaps = 0;
+
+/* For each potentially interesting type which turned out not to exist or be
+ * wanted, define a dummy macro for the sake of the next step.
+ */
+#ifndef WANT_AT_HWCAP
+#  define WANT_AT_HWCAP(_)
+#endif
+#ifndef WANT_AT_HWCAP2
+#  define WANT_AT_HWCAP2(_)
+#endif
+
+/* For each CPU family, define two lists.
+ *
+ *   * `WANTAUX' is a list of the `WANT_AT_MUMBLE' macros which the CPU
+ *     family tried to register interest in above.  Each entry contains the
+ *     interesting auxiliary vector entry type, the name of the union branch
+ *     for its value, and the name of the slot in `struct auxprobe' in which
+ *     to store the value.
+ *
+ *   * `CAPMAP' is a list describing the output features which the CPU family
+ *     intends to satisfy from the auxiliary vector.  Each entry contains a
+ *     feature name suffix, and the token name (for `check_env').
+ */
+#if CPUFAM_ARMEL
+#  define WANTAUX(_)                                                   \
+       WANT_AT_HWCAP(_)                                                \
+       WANT_AT_HWCAP2(_)
+#  define CAPMAP(_)                                                    \
+       _(ARM_VFP, "arm:vfp")                                           \
+       _(ARM_NEON, "arm:neon")                                         \
+       _(ARM_V4, "arm:v4")                                             \
+       _(ARM_D32, "arm:d32")                                           \
+       _(ARM_AES, "arm:aes")                                           \
+       _(ARM_PMULL, "arm:pmull")
+#endif
+#if CPUFAM_ARM64
+#  define WANTAUX(_)                                                   \
+       WANT_AT_HWCAP(_)
+#  define CAPMAP(_)                                                    \
+       _(ARM_NEON, "arm:neon")                                         \
+       _(ARM_AES, "arm:aes")                                           \
+       _(ARM_PMULL, "arm:pmull")
+#endif
+
+/* Build the bitmask for `hwcaps' from the `CAPMAP' list. */
+enum {
+  HFI_PROBED = 0,
+#define HFI__ENUM(feat, tok) HFI_##feat,
+  CAPMAP(HFI__ENUM)
+#undef HFI__ENUM
+  HFI__END
+};
+enum {
+  HF_PROBED = 1,
+#define HF__FLAG(feat, tok) HF_##feat = 1 << HFI_##feat,
+  CAPMAP(HF__FLAG)
+#undef HF__FLAG
+  HF__END
+};
+
+/* Build a structure in which we can capture the interesting data from the
+ * auxiliary vector.
+ */
+#define AUXUTYPE_i long
+#define AUXUTYPE_u unsigned long
+#define AUXUTYPE_p const void *
+struct auxprobe {
+#define AUXPROBE__SLOT(type, ubranch, slot) AUXUTYPE_##ubranch slot;
+  WANTAUX(AUXPROBE__SLOT)
+#undef AUXPROBE_SLOT
+};
+
+/* --- @probe_hwcaps@ --- *
+ *
+ * Arguments:  ---
+ *
+ * Returns:    ---
+ *
+ * Use:                Attempt to find the auxiliary vector (which is well hidden)
+ *             and discover interesting features from it.
+ */
+
+static void probe_hwcaps(void)
 {
-#ifdef __GNUC__
-  unsigned f;
-  /* This hack is by Agner Fog.  Use FXSAVE/FXRSTOR to figure out whether the
-   * XMM registers are actually alive.
+  unsigned hw = HF_PROBED;
+  struct auxprobe probed = { 0 };
+
+  /* Populate `probed' with the information we manage to retrieve from the
+   * auxiliary vector.  Slots we couldn't find are left zero-valued.
    */
-  if (!cpuid_features_p(CPUID1D_FXSR, 0)) return (0);
-  __asm__ ("movl %%esp, %%edx; subl $512, %%esp; andl $~15, %%esp\n"
-          "fxsave (%%esp)\n"
-          "movl 160(%%esp), %%eax; xorl $0xaaaa5555, 160(%%esp)\n"
-          "fxrstor (%%esp); fxsave (%%esp)\n"
-          "movl 160(%%esp), %%ecx; movl %%eax, 160(%%esp)\n"
-          "fxrstor (%%esp); movl %%edx, %%esp\n"
-          "xorl %%ecx, %%eax"
-          : "=a" (f)
-          : /* no inputs */
-          : "%ecx", "%edx");
-  return (f);
+#if defined(HAVE_GETAUXVAL)
+  /* Shiny new libc lets us request individual entry types.  This is almost
+   * too easy.
+   */
+#  define CAP__GET(type, ubranch, slot)                                        \
+       probed.slot = (AUXUTYPE_##ubranch)getauxval(type);
+  WANTAUX(CAP__GET)
 #else
-  return (0);
+  /* Otherwise we're a bit stuck, really.  Modern Linux kernels make a copy
+   * of the vector available in `/procc' so we could try that.
+   *
+   * The usual place is stuck on the end of the environment vector, but that
+   * may well have moved, and we have no way of telling whether it has or
+   * whether there was ever an auxiliary vector there at all; so don't do
+   * that.
+   */
+  {
+    FILE *fp = 0;
+    unsigned char *p = 0, *q = 0;
+    const struct auxentry *a;
+    size_t sz, off, n;
+
+    /* Open the file and read it into a memory chunk. */
+    if ((fp = fopen("/proc/self/auxv", "rb")) == 0) goto clean;
+    sz = 4096; off = 0;
+    if ((p = malloc(sz)) == 0) goto clean;
+    for (;;) {
+      n = fread(p + off, 1, sz - off, fp);
+      off += n;
+      if (off < sz) break;
+      sz *= 2; if ((q = realloc(p, sz)) == 0) break;
+      p = q;
+    }
+
+    /* Work through the vector (or as much of it as we found) and extract the
+     * types we're interested in.
+     */
+    for (a = (const struct auxentry *)p,
+          n = sz/sizeof(struct auxentry);
+        n--; a++) {
+      switch (a->type) {
+#define CAP__SWITCH(type, ubranch, slot)                               \
+       case type: probed.slot = a->value.ubranch; break;
+       WANTAUX(CAP__SWITCH)
+       case AT_NULL: goto clean;
+      }
+    }
+
+  clean:
+    if (p) free(p);
+    if (fp) fclose(fp);
+  }
 #endif
+
+  /* Each CPU family now has to pick through what was found and stashed in
+   * `probed', and set the appropriate flag bits in `hw'.
+   */
+#if CPUFAM_ARMEL
+  if (probed.hwcap & HWCAP_VFPv3) hw |= HF_ARM_VFP;
+  if (probed.hwcap & HWCAP_NEON) hw |= HF_ARM_NEON;
+  if (probed.hwcap & HWCAP_VFPD32) hw |= HF_ARM_D32;
+  if (probed.hwcap & HWCAP_VFPv4) hw |= HF_ARM_V4;
+#  ifdef HWCAP2_AES
+  if (probed.hwcap2 & HWCAP2_AES) hw |= HF_ARM_AES;
+#  endif
+#  ifdef HWCAP2_PMULL
+  if (probed.hwcap2 & HWCAP2_PMULL) hw |= HF_ARM_PMULL;
+#  endif
+#endif
+#if CPUFAM_ARM64
+  if (probed.hwcap & HWCAP_ASIMD) hw |= HF_ARM_NEON;
+  if (probed.hwcap & HWCAP_AES) hw |= HF_ARM_AES;
+  if (probed.hwcap & HWCAP_PMULL) hw |= HF_ARM_PMULL;
+#endif
+
+  /* Store the bitmask of features we probed for everyone to see. */
+  DISPATCH_STORE(hwcaps, hw);
+
+  /* Finally, make a report about the things we found.  (Doing this earlier
+   * will pointlessly widen the window in which multiple threads will do the
+   * above auxiliary-vector probing.)
+   */
+#define CAP__DEBUG(feat, tok)                                          \
+  dispatch_debug("check auxv for feature `%s': %s", tok,               \
+                hw & HF_##feat ? "available" : "absent");
+  CAPMAP(CAP__DEBUG)
+#undef CAP__DEBUG
+}
+
+/* --- @get_hwcaps@ --- *
+ *
+ * Arguments:  ---
+ *
+ * Returns:    A mask of hardware capabilities and other features, as probed
+ *             from the auxiliary vector.
+ */
+
+static unsigned get_hwcaps(void)
+{
+  unsigned hw;
+
+  DISPATCH_LOAD(hwcaps, hw);
+  if (!(hwcaps & HF_PROBED)) { probe_hwcaps(); DISPATCH_LOAD(hwcaps, hw); }
+  return (hw);
 }
 
 #endif
 
 /*----- External interface ------------------------------------------------*/
 
+/* --- @dispatch_debug@ --- *
+ *
+ * Arguments:  @const char *fmt@ = a format string
+ *             @...@ = additional arguments
+ *
+ * Returns:    ---
+ *
+ * Use:                Writes a formatted message to standard output if dispatch
+ *             debugging is enabled.
+ */
+
+void dispatch_debug(const char *fmt, ...)
+{
+  va_list ap;
+  const char *e = getenv("CATACOMB_CPUDISPATCH_DEBUG");
+
+  if (e && *e != 'n' && *e != '0') {
+    va_start(ap, fmt);
+    fputs("Catacomb CPUDISPATCH: ", stderr);
+    vfprintf(stderr, fmt, ap);
+    fputc('\n', stderr);
+    va_end(ap);
+  }
+}
+
 /* --- @check_env@ --- *
  *
  * Arguments:  @const char *ftok@ = feature token
@@ -159,14 +461,14 @@ static int IGNORABLE check_env(const char *ftok)
   if (!p) return (-1);
 
   for (;;) {
-    while (isspace((unsigned char)*p)) p++;
+    while (ISSPACE(*p)) p++;
     if (!*p) return (-1);
     switch (*p) {
       case '+': d = +1; p++; break;
       case '-': d =  0; p++; break;
       default:  d = -1;      break;
     }
-    for (q = p; *q && !isspace((unsigned char)*q); q++);
+    for (q = p; *q && !ISSPACE(*q); q++);
     if (d >= 0) {
       for (pp = ftok; p < q && *pp && *p == *pp; p++, pp++);
       if ((p == q && !*pp) || (*p == '*' && p + 1 == q)) return (d);
@@ -185,30 +487,58 @@ static int IGNORABLE check_env(const char *ftok)
 
 #include <stdio.h>
 
+static int IGNORABLE
+  feat_debug(const char *ftok, const char *check, int verdict)
+{
+  if (verdict >= 0) {
+    dispatch_debug("feature `%s': %s -> %s", ftok, check,
+                  verdict ? "available" : "absent");
+  }
+  return (verdict);
+}
+
 int cpu_feature_p(int feat)
 {
   int IGNORABLE f;
   IGNORE(f);
-#define CHECK_ENV(ftok)                                                        \
-  do { if ((f = check_env(ftok)) >= 0) return (f); } while (0)
+#define CASE_CPUFEAT(feat, ftok, cond) case CPUFEAT_##feat:            \
+  if ((f = feat_debug(ftok, "environment override", check_env(ftok))) >= 0) \
+    return (f);                                                                \
+  else                                                                 \
+    return (feat_debug(ftok, "runtime probe", cond));
 
   switch (feat) {
-#ifdef CPUFAM_X86
-    case CPUFEAT_X86_SSE2: {
-      CHECK_ENV("x86:sse2");
-      return (xmm_registers_available_p() &&
-             cpuid_features_p(CPUID1D_SSE2, 0));
-    }
-    case CPUFEAT_X86_AESNI: {
-      check_env("x86:aesni");
-      return (xmm_registers_available_p() &&
-             cpuid_features_p(CPUID1D_SSE2, CPUID1C_AESNI));
-    }
+#if CPUFAM_X86 || CPUFAM_AMD64
+    CASE_CPUFEAT(X86_SSE2, "x86:sse2",
+                cpuid_feature_p(CPUID_1_D, CPUID1D_SSE2) &&
+                xmm_registers_available_p());
+    CASE_CPUFEAT(X86_AESNI, "x86:aesni",
+                cpuid_feature_p(CPUID_1_D, CPUID1C_AESNI) &&
+                xmm_registers_available_p());
+    CASE_CPUFEAT(X86_RDRAND, "x86:rdrand",
+                cpuid_feature_p(CPUID_1_C, CPUID1C_RDRAND) &&
+                rdrand_works_p(OP_RDRAND));
+    CASE_CPUFEAT(X86_AVX, "x86:avx",
+                cpuid_feature_p(CPUID_1_C, CPUID1C_AVX) &&
+                xmm_registers_available_p());
+    CASE_CPUFEAT(X86_SSSE3, "x86:ssse3",
+                cpuid_feature_p(CPUID_1_C, CPUID1C_SSSE3) &&
+                xmm_registers_available_p());
+    CASE_CPUFEAT(X86_PCLMUL, "x86:pclmul",
+                cpuid_feature_p(CPUID_1_C, CPUID1C_PCLMUL) &&
+                xmm_registers_available_p());
+#endif
+#ifdef CAPMAP
+#  define FEATP__CASE(feat, tok)                                       \
+       CASE_CPUFEAT(feat, tok, get_hwcaps() & HF_##feat)
+    CAPMAP(FEATP__CASE)
+#undef FEATP__CASE
 #endif
     default:
+      dispatch_debug("denying unknown feature %d", feat);
       return (0);
   }
-#undef CHECK_ENV
+#undef CASE_CPUFEAT
 }
 
 /*----- That's all, folks -------------------------------------------------*/