chiark / gitweb /
61c45fa7840289c39be659b284a7b38bf45c9c81
[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 #ifdef CPUFAM_X86
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 static __inline__ unsigned getflags(void)
68   { unsigned f; __asm__ ("pushf; popl %0" : "=g" (f)); return (f); }
69 static __inline__ unsigned setflags(unsigned f)
70 {
71   unsigned ff;
72   __asm__ ("pushf; pushl %1; popf; pushf; popl %0; popf"
73            : "=g" (ff)
74            : "g" (f));
75   return (ff);
76 }
77 #endif
78
79 static void cpuid(struct cpuid *cc, unsigned a, unsigned c)
80 {
81 #ifdef __GNUC__
82   unsigned f;
83 #endif
84
85   cc->a = cc->b = cc->c = cc->d = 0;
86
87 #ifdef __GNUC__
88   /* Stupid dance to detect whether the CPUID instruction is available. */
89   f = getflags();
90   if (!(setflags(f |  EFLAGS_ID) & EFLAGS_ID) ||
91         setflags(f & ~EFLAGS_ID) & EFLAGS_ID) {
92     dispatch_debug("CPUID instruction not available");
93     return;
94   }
95   setflags(f);
96
97   /* Alas, EBX is magical in PIC code, so abuse ESI instead.  This isn't
98    * pretty, but it works.
99    */
100   __asm__ ("pushl %%ebx; cpuid; movl %%ebx, %%esi; popl %%ebx"
101            : "=a" (cc->a), "=S" (cc->b), "=c" (cc->c), "=d" (cc->d)
102            : "a" (a) , "c" (c));
103 #else
104   dispatch_debug("GNU inline assembler not available; can't CPUID");
105 #endif
106 }
107
108 static unsigned cpuid_maxleaf(void)
109   { struct cpuid c; cpuid(&c, 0, 0); return (c.a); }
110
111 /* --- @cpuid_features_p@ --- *
112  *
113  * Arguments:   @unsigned dbits@ = bits to check in EDX
114  *              @unsigned cbits@ = bits to check in ECX
115  *
116  * Returns:     Nonzero if all the requested bits are set in the CPUID result
117  *              on leaf 1.
118  */
119
120 static int cpuid_features_p(unsigned dbits, unsigned cbits)
121 {
122   struct cpuid c;
123   if (cpuid_maxleaf() < 1) return (0);
124   cpuid(&c, 1, 0);
125   return ((c.d & dbits) == dbits && (c.c & cbits) == cbits);
126 }
127
128 /* --- @xmm_registers_available_p@ --- *
129  *
130  * Arguments:   ---
131  *
132  * Returns:     Nonzero if the operating system has made the XMM registers
133  *              available for use.
134  */
135
136 static int xmm_registers_available_p(void)
137 {
138 #ifdef __GNUC__
139   unsigned f;
140   /* This hack is by Agner Fog.  Use FXSAVE/FXRSTOR to figure out whether the
141    * XMM registers are actually alive.
142    */
143   if (!cpuid_features_p(CPUID1D_FXSR, 0)) return (0);
144   __asm__ ("movl %%esp, %%edx; subl $512, %%esp; andl $~15, %%esp\n"
145            "fxsave (%%esp)\n"
146            "movl 160(%%esp), %%eax; xorl $0xaaaa5555, 160(%%esp)\n"
147            "fxrstor (%%esp); fxsave (%%esp)\n"
148            "movl 160(%%esp), %%ecx; movl %%eax, 160(%%esp)\n"
149            "fxrstor (%%esp); movl %%edx, %%esp\n"
150            "xorl %%ecx, %%eax"
151            : "=a" (f)
152            : /* no inputs */
153            : "%ecx", "%edx");
154   return (f);
155 #else
156   dispatch_debug("GNU inline assembler not available; can't check for XMM");
157   return (0);
158 #endif
159 }
160
161 #endif
162
163 /*----- External interface ------------------------------------------------*/
164
165 /* --- @dispatch_debug@ --- *
166  *
167  * Arguments:   @const char *fmt@ = a format string
168  *              @...@ = additional arguments
169  *
170  * Returns:     ---
171  *
172  * Use:         Writes a formatted message to standard output if dispatch
173  *              debugging is enabled.
174  */
175
176 void dispatch_debug(const char *fmt, ...)
177 {
178   va_list ap;
179   const char *e = getenv("CATACOMB_CPUDISPATCH_DEBUG");
180
181   if (e && *e != 'n' && *e != '0') {
182     va_start(ap, fmt);
183     fputs("Catacomb CPUDISPATCH: ", stderr);
184     vfprintf(stderr, fmt, ap);
185     fputc('\n', stderr);
186     va_end(ap);
187   }
188 }
189
190 /* --- @check_env@ --- *
191  *
192  * Arguments:   @const char *ftok@ = feature token
193  *
194  * Returns:     Zero if the feature is forced off; positive if it's forced
195  *              on; negative if the user hasn't decided.
196  *
197  * Use:         Checks the environment variable `CATACOMB_CPUFEAT' for the
198  *              feature token @ftok@.  The variable, if it exists, should be
199  *              a space-separated sequence of `+tok' and `-tok' items.  These
200  *              tokens may end in `*', which matches any suffix.
201  */
202
203 static int IGNORABLE check_env(const char *ftok)
204 {
205   const char *p, *q, *pp;
206   int d;
207
208   p = getenv("CATACOMB_CPUFEAT");
209   if (!p) return (-1);
210
211   for (;;) {
212     while (isspace((unsigned char)*p)) p++;
213     if (!*p) return (-1);
214     switch (*p) {
215       case '+': d = +1; p++; break;
216       case '-': d =  0; p++; break;
217       default:  d = -1;      break;
218     }
219     for (q = p; *q && !isspace((unsigned char)*q); q++);
220     if (d >= 0) {
221       for (pp = ftok; p < q && *pp && *p == *pp; p++, pp++);
222       if ((p == q && !*pp) || (*p == '*' && p + 1 == q)) return (d);
223     }
224     p = q;
225   }
226   return (-1);
227 }
228
229 /* --- @cpu_feature_p@ --- *
230  *
231  * Arguments:   @unsigned feat@ = a @CPUFEAT_...@ code
232  *
233  * Returns:     Nonzero if the feature is available.
234  */
235
236 #include <stdio.h>
237
238 static int IGNORABLE
239   feat_debug(const char *ftok, const char *check, int verdict)
240 {
241   if (verdict >= 0) {
242     dispatch_debug("feature `%s': %s -> %s", ftok, check,
243                    verdict ? "available" : "absent");
244   }
245   return (verdict);
246 }
247
248 int cpu_feature_p(int feat)
249 {
250   int IGNORABLE f;
251   IGNORE(f);
252 #define CASE_CPUFEAT(feat, ftok, cond) case CPUFEAT_##feat:             \
253   if ((f = feat_debug(ftok, "environment override",                     \
254                       check_env(ftok))) >= 0)                           \
255     return (f);                                                         \
256   else                                                                  \
257     return (feat_debug(ftok, "runtime probe", cond));
258
259   switch (feat) {
260 #ifdef CPUFAM_X86
261     CASE_CPUFEAT(X86_SSE2, "x86:sse2",
262                  xmm_registers_available_p() &&
263                  cpuid_features_p(CPUID1D_SSE2, 0));
264     CASE_CPUFEAT(X86_AESNI, "x86:aesni",
265                  xmm_registers_available_p() &&
266                  cpuid_features_p(CPUID1D_SSE2, CPUID1C_AESNI));
267 #endif
268     default:
269       dispatch_debug("denying unknown feature %d", feat);
270       return (0);
271   }
272 #undef CASE_CPUFEAT
273 }
274
275 /*----- That's all, folks -------------------------------------------------*/