b7a7a3a2c0f3c3517edad8131aa57a21a9d9c525
[flac.git] / src / libFLAC / cpu.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2001-2009  Josh Coalson
3  * Copyright (C) 2011-2013  Xiph.Org Foundation
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * - Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *
12  * - Redistributions in binary form must reproduce the above copyright
13  * notice, this list of conditions and the following disclaimer in the
14  * documentation and/or other materials provided with the distribution.
15  *
16  * - Neither the name of the Xiph.org Foundation nor the names of its
17  * contributors may be used to endorse or promote products derived from
18  * this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
24  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
27  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
28  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
29  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
30  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32
33 #if HAVE_CONFIG_H
34 #  include <config.h>
35 #endif
36
37 #include "private/cpu.h"
38 #include <stdlib.h>
39 #include <stdio.h>
40
41 #if defined FLAC__CPU_IA32
42 # include <signal.h>
43 #elif defined FLAC__CPU_PPC
44 # if !defined FLAC__NO_ASM
45 #  if defined FLAC__SYS_DARWIN
46 #   include <sys/sysctl.h>
47 #   include <mach/mach.h>
48 #   include <mach/mach_host.h>
49 #   include <mach/host_info.h>
50 #   include <mach/machine.h>
51 #   ifndef CPU_SUBTYPE_POWERPC_970
52 #    define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
53 #   endif
54 #  else /* FLAC__SYS_DARWIN */
55
56 #   include <signal.h>
57 #   include <setjmp.h>
58
59 static sigjmp_buf jmpbuf;
60 static volatile sig_atomic_t canjump = 0;
61
62 static void sigill_handler (int sig)
63 {
64         if (!canjump) {
65                 signal (sig, SIG_DFL);
66                 raise (sig);
67         }
68         canjump = 0;
69         siglongjmp (jmpbuf, 1);
70 }
71 #  endif /* FLAC__SYS_DARWIN */
72 # endif /* FLAC__NO_ASM */
73 #endif /* FLAC__CPU_PPC */
74
75 #if defined (__NetBSD__) || defined(__OpenBSD__)
76 #include <sys/param.h>
77 #include <sys/sysctl.h>
78 #include <machine/cpu.h>
79 #endif
80
81 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
82 #include <sys/types.h>
83 #include <sys/sysctl.h>
84 #endif
85
86 #if defined(__APPLE__)
87 /* how to get sysctlbyname()? */
88 #endif
89
90 /* these are flags in EDX of CPUID AX=00000001 */
91 static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
92 static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
93 static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
94 static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
95 static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
96 /* these are flags in ECX of CPUID AX=00000001 */
97 static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
98 static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
99 /* these are flags in EDX of CPUID AX=80000001 */
100 static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
101 static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
102 static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
103
104
105 /*
106  * Extra stuff needed for detection of OS support for SSE on IA-32
107  */
108 #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
109 # if defined(__linux__)
110 /*
111  * If the OS doesn't support SSE, we will get here with a SIGILL.  We
112  * modify the return address to jump over the offending SSE instruction
113  * and also the operation following it that indicates the instruction
114  * executed successfully.  In this way we use no global variables and
115  * stay thread-safe.
116  *
117  * 3 + 3 + 6:
118  *   3 bytes for "xorps xmm0,xmm0"
119  *   3 bytes for estimate of how long the follwing "inc var" instruction is
120  *   6 bytes extra in case our estimate is wrong
121  * 12 bytes puts us in the NOP "landing zone"
122  */
123 #  undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
124 #  ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
125         static void sigill_handler_sse_os(int signal, struct sigcontext sc)
126         {
127                 (void)signal;
128                 sc.eip += 3 + 3 + 6;
129         }
130 #  else
131 #   include <sys/ucontext.h>
132         static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
133         {
134                 (void)signal, (void)si;
135                 ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
136         }
137 #  endif
138 # elif defined(_MSC_VER)
139 #  include <windows.h>
140 #  define USE_TRY_CATCH_FLAVOR /* sigill_handler flavor resulted in several crash reports on win32 */
141 #  ifdef USE_TRY_CATCH_FLAVOR
142 #  else
143         LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
144         {
145                 if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
146                         ep->ContextRecord->Eip += 3 + 3 + 6;
147                         return EXCEPTION_CONTINUE_EXECUTION;
148                 }
149                 return EXCEPTION_CONTINUE_SEARCH;
150         }
151 #  endif
152 # endif
153 #endif
154
155
156 void FLAC__cpu_info(FLAC__CPUInfo *info)
157 {
158 /*
159  * IA32-specific
160  */
161 #ifdef FLAC__CPU_IA32
162         info->type = FLAC__CPUINFO_TYPE_IA32;
163 #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
164         info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
165         info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
166         info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
167         info->data.ia32.cmov = false;
168         info->data.ia32.mmx = false;
169         info->data.ia32.fxsr = false;
170         info->data.ia32.sse = false;
171         info->data.ia32.sse2 = false;
172         info->data.ia32.sse3 = false;
173         info->data.ia32.ssse3 = false;
174         info->data.ia32._3dnow = false;
175         info->data.ia32.ext3dnow = false;
176         info->data.ia32.extmmx = false;
177         if(info->data.ia32.cpuid) {
178                 /* http://www.sandpile.org/ia32/cpuid.htm */
179                 FLAC__uint32 flags_edx, flags_ecx;
180                 FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
181                 info->data.ia32.cmov  = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
182                 info->data.ia32.mmx   = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX  )? true : false;
183                 info->data.ia32.fxsr  = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
184                 info->data.ia32.sse   = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE  )? true : false;
185                 info->data.ia32.sse2  = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
186                 info->data.ia32.sse3  = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
187                 info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
188
189 #ifdef FLAC__USE_3DNOW
190                 flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
191                 info->data.ia32._3dnow   = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW   )? true : false;
192                 info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
193                 info->data.ia32.extmmx   = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX  )? true : false;
194 #else
195                 info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
196 #endif
197
198 #ifdef DEBUG
199                 fprintf(stderr, "CPU info (IA-32):\n");
200                 fprintf(stderr, "  CPUID ...... %c\n", info->data.ia32.cpuid   ? 'Y' : 'n');
201                 fprintf(stderr, "  BSWAP ...... %c\n", info->data.ia32.bswap   ? 'Y' : 'n');
202                 fprintf(stderr, "  CMOV ....... %c\n", info->data.ia32.cmov    ? 'Y' : 'n');
203                 fprintf(stderr, "  MMX ........ %c\n", info->data.ia32.mmx     ? 'Y' : 'n');
204                 fprintf(stderr, "  FXSR ....... %c\n", info->data.ia32.fxsr    ? 'Y' : 'n');
205                 fprintf(stderr, "  SSE ........ %c\n", info->data.ia32.sse     ? 'Y' : 'n');
206                 fprintf(stderr, "  SSE2 ....... %c\n", info->data.ia32.sse2    ? 'Y' : 'n');
207                 fprintf(stderr, "  SSE3 ....... %c\n", info->data.ia32.sse3    ? 'Y' : 'n');
208                 fprintf(stderr, "  SSSE3 ...... %c\n", info->data.ia32.ssse3   ? 'Y' : 'n');
209                 fprintf(stderr, "  3DNow! ..... %c\n", info->data.ia32._3dnow  ? 'Y' : 'n');
210                 fprintf(stderr, "  3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
211                 fprintf(stderr, "  3DNow!-MMX . %c\n", info->data.ia32.extmmx  ? 'Y' : 'n');
212 #endif
213
214                 /*
215                  * now have to check for OS support of SSE/SSE2
216                  */
217                 if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
218 #if defined FLAC__NO_SSE_OS
219                         /* assume user knows better than us; turn it off */
220                         info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
221 #elif defined FLAC__SSE_OS
222                         /* assume user knows better than us; leave as detected above */
223 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
224                         int sse = 0;
225                         size_t len;
226                         /* at least one of these must work: */
227                         len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
228                         len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse"   , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
229                         if(!sse)
230                                 info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
231 #elif defined(__NetBSD__) || defined (__OpenBSD__)
232 # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
233                         int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
234                         size_t len = sizeof(val);
235                         if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
236                                 info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
237                         else { /* double-check SSE2 */
238                                 mib[1] = CPU_SSE2;
239                                 len = sizeof(val);
240                                 if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
241                                         info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
242                         }
243 # else
244                         info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
245 # endif
246 #elif defined(__linux__)
247                         int sse = 0;
248                         struct sigaction sigill_save;
249 #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
250                         if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
251 #else
252                         struct sigaction sigill_sse;
253                         sigill_sse.sa_sigaction = sigill_handler_sse_os;
254                         __sigemptyset(&sigill_sse.sa_mask);
255                         sigill_sse.sa_flags = SA_SIGINFO | SA_RESETHAND; /* SA_RESETHAND just in case our SIGILL return jump breaks, so we don't get stuck in a loop */
256                         if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
257 #endif
258                         {
259                                 /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
260                                 /* see sigill_handler_sse_os() for an explanation of the following: */
261                                 asm volatile (
262                                         "xorl %0,%0\n\t"          /* for some reason, still need to do this to clear 'sse' var */
263                                         "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
264                                         "incl %0\n\t"             /* SIGILL handler will jump over this */
265                                         /* landing zone */
266                                         "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
267                                         "nop\n\t"
268                                         "nop\n\t"
269                                         "nop\n\t"
270                                         "nop\n\t"
271                                         "nop\n\t"
272                                         "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
273                                         "nop\n\t"
274                                         "nop"     /* SIGILL jump lands here if "inc" is 1 byte */
275                                         : "=r"(sse)
276                                         : "r"(sse)
277                                 );
278
279                                 sigaction(SIGILL, &sigill_save, NULL);
280                         }
281
282                         if(!sse)
283                                 info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
284 #elif defined(_MSC_VER)
285 # ifdef USE_TRY_CATCH_FLAVOR
286                         _try {
287                                 __asm {
288                                         xorps xmm0,xmm0
289                                 }
290                         }
291                         _except(EXCEPTION_EXECUTE_HANDLER) {
292                                 if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
293                                         info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
294                         }
295 # else
296                         int sse = 0;
297                         LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
298                         /* see GCC version above for explanation */
299                         /*  http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
300                         /*  http://www.codeproject.com/cpp/gccasm.asp */
301                         /*  http://www.hick.org/~mmiller/msvc_inline_asm.html */
302                         __asm {
303                                 xorps xmm0,xmm0
304                                 inc sse
305                                 nop
306                                 nop
307                                 nop
308                                 nop
309                                 nop
310                                 nop
311                                 nop
312                                 nop
313                                 nop
314                         }
315                         SetUnhandledExceptionFilter(save);
316                         if(!sse)
317                                 info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
318 # endif
319 #else
320                         /* no way to test, disable to be safe */
321                         info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
322 #endif
323 #ifdef DEBUG
324                 fprintf(stderr, "  SSE OS sup . %c\n", info->data.ia32.sse     ? 'Y' : 'n');
325 #endif
326
327                 }
328         }
329 #else
330         info->use_asm = false;
331 #endif
332
333 /*
334  * PPC-specific
335  */
336 #elif defined FLAC__CPU_PPC
337         info->type = FLAC__CPUINFO_TYPE_PPC;
338 # if !defined FLAC__NO_ASM
339         info->use_asm = true;
340 #  ifdef FLAC__USE_ALTIVEC
341 #   if defined FLAC__SYS_DARWIN
342         {
343                 int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
344                 size_t len = sizeof(val);
345                 info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
346         }
347         {
348                 host_basic_info_data_t hostInfo;
349                 mach_msg_type_number_t infoCount;
350
351                 infoCount = HOST_BASIC_INFO_COUNT;
352                 host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
353
354                 info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
355         }
356 #   else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
357         {
358                 /* no Darwin, do it the brute-force way */
359                 /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
360                 info->data.ppc.altivec = 0;
361                 info->data.ppc.ppc64 = 0;
362
363                 signal (SIGILL, sigill_handler);
364                 canjump = 0;
365                 if (!sigsetjmp (jmpbuf, 1)) {
366                         canjump = 1;
367
368                         asm volatile (
369                                 "mtspr 256, %0\n\t"
370                                 "vand %%v0, %%v0, %%v0"
371                                 :
372                                 : "r" (-1)
373                         );
374
375                         info->data.ppc.altivec = 1;
376                 }
377                 canjump = 0;
378                 if (!sigsetjmp (jmpbuf, 1)) {
379                         int x = 0;
380                         canjump = 1;
381
382                         /* PPC64 hardware implements the cntlzd instruction */
383                         asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
384
385                         info->data.ppc.ppc64 = 1;
386                 }
387                 signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
388         }
389 #   endif
390 #  else /* !FLAC__USE_ALTIVEC */
391         info->data.ppc.altivec = 0;
392         info->data.ppc.ppc64 = 0;
393 #  endif
394 # else
395         info->use_asm = false;
396 # endif
397
398 /*
399  * unknown CPI
400  */
401 #else
402         info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
403         info->use_asm = false;
404 #endif
405 }