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