]> git.sesse.net Git - vlc/blob - src/misc/cpu.c
utf8_vasprintf(): avoid useless strdup if UTF-8 is assumed
[vlc] / src / misc / cpu.c
1 /*****************************************************************************
2  * cpu.c: CPU detection code
3  *****************************************************************************
4  * Copyright (C) 1998-2004 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Samuel Hocevar <sam@zoy.org>
8  *          Christophe Massiot <massiot@via.ecp.fr>
9  *          Eugenio Jarosiewicz <ej0@cise.ufl.eduEujenio>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc_common.h>
34 #include <vlc_cpu.h>
35
36 #include <sys/types.h>
37 #ifndef WIN32
38 #include <unistd.h>
39 #include <sys/wait.h>
40 #include <signal.h>
41 #else
42 #include <errno.h>
43 #endif
44 #include <assert.h>
45
46 #include "libvlc.h"
47
48 #if defined(__APPLE__)
49 #include <sys/sysctl.h>
50 #endif
51
52 #if defined(__SunOS)
53 #include <unistd.h>
54 #include <sys/types.h>
55 #include <sys/processor.h>
56 #include <sys/pset.h>
57 #endif
58
59 #if defined( __i386__ ) || defined( __x86_64__ ) || defined( __powerpc__ ) \
60  || defined( __ppc__ ) || defined( __ppc64__ ) || defined( __powerpc64__ )
61 # ifndef WIN32
62 static bool check_OS_capability( const char *psz_capability, pid_t pid )
63 {
64     int status;
65
66     if( pid == -1 )
67         return false; /* fail safe :-/ */
68
69     while( waitpid( pid, &status, 0 ) == -1 );
70
71     if( WIFEXITED( status ) && WEXITSTATUS( status ) == 0 )
72         return true;
73
74     fprintf( stderr, "warning: your CPU has %s instructions, but not your "
75                      "operating system.\n", psz_capability );
76     fprintf( stderr, "         some optimizations will be disabled unless "
77                      "you upgrade your OS\n" );
78     return false;
79 }
80
81 #  define check_capability(name, flag, code)   \
82      do {                                      \
83         pid_t pid = fork();                    \
84         if( pid == 0 )                         \
85         {                                      \
86             signal(SIGILL, SIG_DFL);           \
87             __asm__ __volatile__ ( code : : ); \
88             _exit(0);                          \
89         }                                      \
90         if( check_OS_capability((name), pid )) \
91             i_capabilities |= (flag);          \
92      } while(0)
93
94 # else /* WIN32 */
95 #  define check_capability(name, flag, code)   \
96         i_capabilities |= (flag);
97 # endif
98 #endif
99
100 /*****************************************************************************
101  * CPUCapabilities: get the CPU capabilities
102  *****************************************************************************
103  * This function is called to list extensions the CPU may have.
104  *****************************************************************************/
105 uint32_t CPUCapabilities( void )
106 {
107     uint32_t i_capabilities = 0;
108
109 #if defined( __i386__ ) || defined( __x86_64__ )
110      unsigned int i_eax, i_ebx, i_ecx, i_edx;
111      bool b_amd;
112
113     /* Needed for x86 CPU capabilities detection */
114 #   if defined( __x86_64__ )
115 #       define cpuid( reg )                    \
116             asm volatile ( "cpuid\n\t"         \
117                            "movl %%ebx,%1\n\t" \
118                          : "=a" ( i_eax ),     \
119                            "=b" ( i_ebx ),     \
120                            "=c" ( i_ecx ),     \
121                            "=d" ( i_edx )      \
122                          : "a"  ( reg )        \
123                          : "cc" );
124 #   else
125 #       define cpuid( reg )                    \
126             asm volatile ( "push %%ebx\n\t"    \
127                            "cpuid\n\t"         \
128                            "movl %%ebx,%1\n\t" \
129                            "pop %%ebx\n\t"     \
130                          : "=a" ( i_eax ),     \
131                            "=r" ( i_ebx ),     \
132                            "=c" ( i_ecx ),     \
133                            "=d" ( i_edx )      \
134                          : "a"  ( reg )        \
135                          : "cc" );
136 #   endif
137      /* Check if the OS really supports the requested instructions */
138 # if defined (__i386__) && !defined (__i486__) && !defined (__i586__) \
139   && !defined (__i686__) && !defined (__pentium4__) \
140   && !defined (__k6__) && !defined (__athlon__) && !defined (__k8__)
141     /* check if cpuid instruction is supported */
142     asm volatile ( "push %%ebx\n\t"
143                    "pushf\n\t"
144                    "pop %%eax\n\t"
145                    "movl %%eax, %%ebx\n\t"
146                    "xorl $0x200000, %%eax\n\t"
147                    "push %%eax\n\t"
148                    "popf\n\t"
149                    "pushf\n\t"
150                    "pop %%eax\n\t"
151                    "movl %%ebx,%1\n\t"
152                    "pop %%ebx\n\t"
153                  : "=a" ( i_eax ),
154                    "=r" ( i_ebx )
155                  :
156                  : "cc" );
157
158     if( i_eax == i_ebx )
159         goto out;
160 # endif
161
162     /* the CPU supports the CPUID instruction - get its level */
163     cpuid( 0x00000000 );
164
165 # if defined (__i386__) && !defined (__i586__) \
166   && !defined (__i686__) && !defined (__pentium4__) \
167   && !defined (__k6__) && !defined (__athlon__) && !defined (__k8__)
168     if( !i_eax )
169         goto out;
170 #endif
171
172     /* borrowed from mpeg2dec */
173     b_amd = ( i_ebx == 0x68747541 ) && ( i_ecx == 0x444d4163 )
174                     && ( i_edx == 0x69746e65 );
175
176     /* test for the MMX flag */
177     cpuid( 0x00000001 );
178 # if !defined (__MMX__)
179     if( ! (i_edx & 0x00800000) )
180         goto out;
181 # endif
182     i_capabilities |= CPU_CAPABILITY_MMX;
183
184 # if defined (__SSE__)
185     i_capabilities |= CPU_CAPABILITY_MMXEXT | CPU_CAPABILITY_SSE;
186 # else
187     if( i_edx & 0x02000000 )
188     {
189         i_capabilities |= CPU_CAPABILITY_MMXEXT;
190
191 #   ifdef CAN_COMPILE_SSE
192         check_capability( "SSE", CPU_CAPABILITY_SSE,
193                           "xorps %%xmm0,%%xmm0\n" );
194 #   endif
195     }
196 # endif
197
198 # if defined (__SSE2__)
199     i_capabilities |= CPU_CAPABILITY_SSE2;
200 # elif defined (CAN_COMPILE_SSE2)
201     if( i_edx & 0x04000000 )
202         check_capability( "SSE2", CPU_CAPABILITY_SSE2,
203                           "movupd %%xmm0, %%xmm0\n" );
204 # endif
205
206 # if defined (__SSE3__)
207     i_capabilities |= CPU_CAPABILITY_SSE3;
208 # elif defined (CAN_COMPILE_SSE3)
209     if( i_ecx & 0x00000001 )
210         check_capability( "SSE3", CPU_CAPABILITY_SSE3,
211                           "movsldup %%xmm1, %%xmm0\n" );
212 # endif
213
214 # if defined (__SSSE3__)
215     i_capabilities |= CPU_CAPABILITY_SSSE3;
216 # elif defined (CAN_COMPILE_SSSE3)
217     if( i_ecx & 0x00000200 )
218         check_capability( "SSSE3", CPU_CAPABILITY_SSSE3,
219                           "pabsw %%xmm1, %%xmm0\n" );
220 # endif
221
222 # if defined (__SSE4_1__)
223     i_capabilities |= CPU_CAPABILITY_SSE4_1;
224 # elif defined (CAN_COMPILE_SSE4_1)
225     if( i_ecx & 0x00080000 )
226         check_capability( "SSE4.1", CPU_CAPABILITY_SSE4_1,
227                           "pmaxsb %%xmm1, %%xmm0\n" );
228 # endif
229
230 # if defined (__SSE4_2__)
231     i_capabilities |= CPU_CAPABILITY_SSE4_2;
232 # elif defined (CAN_COMPILE_SSE4_2)
233     if( i_ecx & 0x00100000 )
234         check_capability( "SSE4.2", CPU_CAPABILITY_SSE4_2,
235                           "pcmpgtq %%xmm1, %%xmm0\n" );
236 # endif
237
238     /* test for additional capabilities */
239     cpuid( 0x80000000 );
240
241     if( i_eax < 0x80000001 )
242         goto out;
243
244     /* list these additional capabilities */
245     cpuid( 0x80000001 );
246
247 # if defined (__3dNOW__)
248     i_capabilities |= CPU_CAPABILITY_3DNOW;
249 # elif defined (CAN_COMPILE_3DNOW)
250     if( i_edx & 0x80000000 )
251         check_capability( "3D Now!", CPU_CAPABILITY_3DNOW,
252                           "pfadd %%mm0,%%mm0\n" "femms\n" );
253 # endif
254
255     if( b_amd && ( i_edx & 0x00400000 ) )
256     {
257         i_capabilities |= CPU_CAPABILITY_MMXEXT;
258     }
259 out:
260
261 #elif defined( __arm__ )
262 #   if defined( __ARM_NEON__ )
263     i_capabilities |= CPU_CAPABILITY_NEON;
264 #   endif
265
266 #elif defined( __powerpc__ ) || defined( __ppc__ ) || defined( __powerpc64__ ) \
267     || defined( __ppc64__ )
268
269 #   if defined(__APPLE__)
270     int selectors[2] = { CTL_HW, HW_VECTORUNIT };
271     int i_has_altivec = 0;
272     size_t i_length = sizeof( i_has_altivec );
273     int i_error = sysctl( selectors, 2, &i_has_altivec, &i_length, NULL, 0);
274
275     if( i_error == 0 && i_has_altivec != 0 )
276         i_capabilities |= CPU_CAPABILITY_ALTIVEC;
277
278 #   elif defined( CAN_COMPILE_ALTIVEC )
279     pid_t pid = fork();
280     if( pid == 0 )
281     {
282         signal(SIGILL, SIG_DFL);
283         asm volatile ("mtspr 256, %0\n\t"
284                       "vand %%v0, %%v0, %%v0"
285                       :
286                       : "r" (-1));
287         _exit(0);
288     }
289
290     if( check_OS_capability( "Altivec", pid ) )
291         i_capabilities |= CPU_CAPABILITY_ALTIVEC;
292
293 #   endif
294
295 #endif
296     return i_capabilities;
297 }
298
299 uint32_t cpu_flags = 0;
300
301
302 /*****************************************************************************
303  * vlc_CPU: get pre-computed CPU capability flags
304  ****************************************************************************/
305 unsigned vlc_CPU (void)
306 {
307     return cpu_flags;
308 }
309
310 const struct
311 {
312     uint32_t value;
313     char name[12];
314 } cap_dirs[] = {
315 #if defined ( __i386__ ) || defined ( __x86_64__ )
316     { CPU_CAPABILITY_MMX,     "mmx" },
317     { CPU_CAPABILITY_MMXEXT,  "mmxext" },
318     { CPU_CAPABILITY_3DNOW,   "3dnow" },
319     { CPU_CAPABILITY_SSE,     "sse" },
320 #endif
321 #if defined (__ppc__) || defined (__ppc64__) || defined (__powerpc__)
322     { CPU_CAPABILITY_ALTIVEC, "altivec" },
323 #endif
324 #if defined (__arm__)
325     { CPU_CAPABILITY_NEON,    "arm_neon" },
326 #endif
327 };
328
329 /**
330  * Return the number of available logical CPU.
331  */
332 unsigned vlc_GetCPUCount(void)
333 {
334 #if defined(WIN32) && !defined(UNDER_CE)
335     DWORD process_mask;
336     DWORD system_mask;
337     if (!GetProcessAffinityMask(GetCurrentProcess(), &process_mask, &system_mask))
338         return 1;
339
340     unsigned count = 0;
341     while (system_mask) {
342         count++;
343         system_mask >>= 1;
344     }
345     return count;
346 #elif defined(HAVE_SCHED_GETAFFINITY)
347     cpu_set_t cpu;
348     CPU_ZERO(&cpu);
349     if (sched_getaffinity(0, sizeof(cpu), &cpu) < 0)
350         return 1;
351     unsigned count = 0;
352     for (unsigned i = 0; i < CPU_SETSIZE; i++)
353         count += CPU_ISSET(i, &cpu) != 0;
354     return count;
355 #elif defined(__APPLE__)
356     int count;
357     size_t size = sizeof(count) ;
358     if (sysctlbyname("hw.ncpu", &count, &size, NULL, 0))
359         return 1; /* Failure */
360     return count;
361 #elif defined(__SunOS)
362     unsigned count = 0;
363     int type;
364     u_int numcpus;
365     processorid_t *cpulist;
366     processor_info_t cpuinfo;
367     cpulist = malloc(sizeof(processorid_t) * sysconf(_SC_NPROCESSORS_MAX));
368     if (!cpulist) return 1;
369     if (pset_info(PS_MYID, &type, &numcpus, cpulist)==0)
370     {
371         for (u_int i = 0; i < numcpus; i++)
372         {
373             if (!processor_info(cpulist[i], &cpuinfo))
374                 count += (cpuinfo.pi_state == P_ONLINE)?1:0;
375         }
376     } else {
377         count = sysconf(_SC_NPROCESSORS_ONLN);
378     }
379     free(cpulist);
380     return (count>0)?count:1;
381 #else
382 #   warning "vlc_GetCPUCount is not implemented for your platform"
383     return 1;
384 #endif
385 }
386
387 /**
388  * Check if a directory name contains usable plugins w.r.t. the hardware
389  * capabilities. Loading a plugin when the hardware has insufficient
390  * capabilities may lead to illegal instructions (SIGILL) and must be avoided.
391  *
392  * @param name the name of the directory (<b>not</b> the path)
393  *
394  * @return true if the hardware has sufficient capabilities or the directory
395  * does not require any special capability; false if the running hardware has
396  * insufficient capabilities.
397  */
398 bool vlc_CPU_CheckPluginDir (const char *name)
399 {
400     const unsigned flags = vlc_CPU ();
401     for (size_t i = 0; i < sizeof (cap_dirs) / sizeof (cap_dirs[0]); i++)
402     {
403         if (strcmp (name, cap_dirs[i].name))
404             continue;
405         return (flags & cap_dirs[i].value) != 0;
406     }
407     return true;
408 }
409
410 static vlc_memcpy_t pf_vlc_memcpy = memcpy;
411 static vlc_memset_t pf_vlc_memset = memset;
412
413 void vlc_fastmem_register (vlc_memcpy_t cpy, vlc_memset_t set)
414 {
415     if (cpy)
416         pf_vlc_memcpy = cpy;
417     if (set)
418         pf_vlc_memset = set;
419 }
420
421 /**
422  * vlc_memcpy: fast CPU-dependent memcpy
423  */
424 void *vlc_memcpy (void *tgt, const void *src, size_t n)
425 {
426     return pf_vlc_memcpy (tgt, src, n);
427 }
428
429 /**
430  * vlc_memset: fast CPU-dependent memset
431  */
432 void *vlc_memset (void *tgt, int c, size_t n)
433 {
434     return pf_vlc_memset (tgt, c, n);
435 }
436
437 /**
438  * Returned an aligned pointer on newly allocated memory.
439  * \param alignment must be a power of 2 and a multiple of sizeof(void*)
440  * \param size is the size of the usable memory returned.
441  *
442  * It must not be freed directly, *base must.
443  */
444 void *vlc_memalign(void **base, size_t alignment, size_t size)
445 {
446     assert(alignment >= sizeof(void*));
447     for (size_t t = alignment; t > 1; t >>= 1)
448         assert((t&1) == 0);
449 #if defined(HAVE_POSIX_MEMALIGN)
450     if (posix_memalign(base, alignment, size)) {
451         *base = NULL;
452         return NULL;
453     }
454     return *base;
455 #elif defined(HAVE_MEMALIGN)
456     return *base = memalign(alignment, size);
457 #else
458     unsigned char *p = *base = malloc(size + alignment - 1);
459     if (!p)
460         return NULL;
461     return (void*)((uintptr_t)(p + alignment - 1) & ~(alignment - 1));
462 #endif
463 }
464