add failsafe for querying cache line size on linux

This commit is contained in:
hsnovel 2024-08-06 10:00:41 -07:00 committed by Sam Lantinga
parent 8a3bb11024
commit 83d1d1c053
1 changed files with 29 additions and 4 deletions

View File

@ -69,6 +69,10 @@
#endif #endif
#endif #endif
#if defined (SDL_PLATFORM_FREEBSD)
#include <sys/param.h>
#endif
#if defined(SDL_PLATFORM_ANDROID) && defined(__arm__) && !defined(HAVE_GETAUXVAL) #if defined(SDL_PLATFORM_ANDROID) && defined(__arm__) && !defined(HAVE_GETAUXVAL)
#include <cpu-features.h> #include <cpu-features.h>
#endif #endif
@ -841,6 +845,7 @@ static const char *SDL_GetCPUName(void)
int SDL_GetCPUCacheLineSize(void) int SDL_GetCPUCacheLineSize(void)
{ {
const char *cpuType = SDL_GetCPUType(); const char *cpuType = SDL_GetCPUType();
int cacheline_size = SDL_CACHELINE_SIZE; /* initial guess */
int a, b, c, d; int a, b, c, d;
(void)a; (void)a;
(void)b; (void)b;
@ -848,14 +853,34 @@ int SDL_GetCPUCacheLineSize(void)
(void)d; (void)d;
if (SDL_strcmp(cpuType, "GenuineIntel") == 0 || SDL_strcmp(cpuType, "CentaurHauls") == 0 || SDL_strcmp(cpuType, " Shanghai ") == 0) { if (SDL_strcmp(cpuType, "GenuineIntel") == 0 || SDL_strcmp(cpuType, "CentaurHauls") == 0 || SDL_strcmp(cpuType, " Shanghai ") == 0) {
cpuid(0x00000001, a, b, c, d); cpuid(0x00000001, a, b, c, d);
return ((b >> 8) & 0xff) * 8; cacheline_size = ((b >> 8) & 0xff) * 8;
} else if (SDL_strcmp(cpuType, "AuthenticAMD") == 0 || SDL_strcmp(cpuType, "HygonGenuine") == 0) { } else if (SDL_strcmp(cpuType, "AuthenticAMD") == 0 || SDL_strcmp(cpuType, "HygonGenuine") == 0) {
cpuid(0x80000005, a, b, c, d); cpuid(0x80000005, a, b, c, d);
return c & 0xff; cacheline_size = c & 0xff;
} else { } else {
/* Just make a guess here... */ #if defined(HAVE_SYSCONF) && defined(_SC_LEVEL1_DCACHE_LINESIZE)
return SDL_CACHELINE_SIZE; if ((cacheline_size = sysconf(_SC_LEVEL1_DCACHE_LINESIZE)) > 0) {
return cacheline_size;
} else {
cacheline_size = SDL_CACHELINE_SIZE;
} }
#endif
#if defined(SDL_PLATFORM_LINUX)
{
FILE *f = fopen("/sys/devices/system/cpu/cpu0/cache/index0/coherency_line_size", "r");
if (f) {
int size;
if (fscanf(f, "%d", &size) == 1) {
cacheline_size = size;
}
fclose(f);
}
}
#elif defined(__FREEBSD__) && defined(CACHE_LINE_SIZE)
cacheline_size = CACHE_LINE_SIZE;
#endif
}
return cacheline_size;
} }
#define SDL_CPUFEATURES_RESET_VALUE 0xFFFFFFFF #define SDL_CPUFEATURES_RESET_VALUE 0xFFFFFFFF