1 #include <alloca.h>
2 #include <errno.h>
3 #include <string.h>
4
5 #include <sys/sysctl.h>
6 #include <sys/types.h>
7
8 #include <cpuinfo/log.h>
9 #include <mach/api.h>
10
11 #include <TargetConditionals.h>
12
cpuinfo_mach_detect_topology(void)13 struct cpuinfo_mach_topology cpuinfo_mach_detect_topology(void) {
14 int cores = 1;
15 size_t sizeof_cores = sizeof(cores);
16 if (sysctlbyname("hw.physicalcpu_max", &cores, &sizeof_cores, NULL, 0) != 0) {
17 cpuinfo_log_error("sysctlbyname(\"hw.physicalcpu_max\") failed: %s", strerror(errno));
18 } else if (cores <= 0) {
19 cpuinfo_log_error("sysctlbyname(\"hw.physicalcpu_max\") returned invalid value %d", cores);
20 cores = 1;
21 }
22
23 int threads = 1;
24 size_t sizeof_threads = sizeof(threads);
25 if (sysctlbyname("hw.logicalcpu_max", &threads, &sizeof_threads, NULL, 0) != 0) {
26 cpuinfo_log_error("sysctlbyname(\"hw.logicalcpu_max\") failed: %s", strerror(errno));
27 } else if (threads <= 0) {
28 cpuinfo_log_error("sysctlbyname(\"hw.logicalcpu_max\") returned invalid value %d", threads);
29 threads = cores;
30 }
31
32 int packages = 1;
33 #if !TARGET_OS_IPHONE
34 size_t sizeof_packages = sizeof(packages);
35 if (sysctlbyname("hw.packages", &packages, &sizeof_packages, NULL, 0) != 0) {
36 cpuinfo_log_error("sysctlbyname(\"hw.packages\") failed: %s", strerror(errno));
37 } else if (packages <= 0) {
38 cpuinfo_log_error("sysctlbyname(\"hw.packages\") returned invalid value %d", packages);
39 packages = 1;
40 }
41 #endif
42
43 cpuinfo_log_debug("mach topology: packages = %d, cores = %d, threads = %d", packages, (int)cores, (int)threads);
44 struct cpuinfo_mach_topology topology = {
45 .packages = (uint32_t)packages, .cores = (uint32_t)cores, .threads = (uint32_t)threads};
46
47 #if !TARGET_OS_IPHONE
48 size_t cacheconfig_size = 0;
49 if (sysctlbyname("hw.cacheconfig", NULL, &cacheconfig_size, NULL, 0) != 0) {
50 cpuinfo_log_error("sysctlbyname(\"hw.cacheconfig\") failed: %s", strerror(errno));
51 } else {
52 uint64_t* cacheconfig = alloca(cacheconfig_size);
53 if (sysctlbyname("hw.cacheconfig", cacheconfig, &cacheconfig_size, NULL, 0) != 0) {
54 cpuinfo_log_error("sysctlbyname(\"hw.cacheconfig\") failed: %s", strerror(errno));
55 } else {
56 size_t cache_configs = cacheconfig_size / sizeof(uint64_t);
57 cpuinfo_log_debug("mach hw.cacheconfig count: %zu", cache_configs);
58 if (cache_configs > CPUINFO_MACH_MAX_CACHE_LEVELS) {
59 cache_configs = CPUINFO_MACH_MAX_CACHE_LEVELS;
60 }
61 for (size_t i = 0; i < cache_configs; i++) {
62 cpuinfo_log_debug("mach hw.cacheconfig[%zu]: %" PRIu64, i, cacheconfig[i]);
63 topology.threads_per_cache[i] = cacheconfig[i];
64 }
65 }
66 }
67 #endif
68 return topology;
69 }
70