Debian Codegraph @

psutil/arch/osx/cpu.c

raw
1 /*
2 * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
3 * Use of this source code is governed by a BSD-style license that can be
4 * found in the LICENSE file.
5 */
6
7 /*
8 System-wide CPU related functions.
9
10 Original code was refactored and moved from psutil/_psutil_osx.c in 2020
11 right before a4c0a0eb0d2a872ab7a45e47fcf37ef1fde5b012.
12 For reference, here's the git history with original implementations:
13
14 - CPU count logical: 3d291d425b856077e65163e43244050fb188def1
15 - CPU count physical: 4263e354bb4984334bc44adf5dd2f32013d69fba
16 - CPU times: 32488bdf54aed0f8cef90d639c1667ffaa3c31c7
17 - CPU stat: fa00dfb961ef63426c7818899340866ced8d2418
18 - CPU frequency: 6ba1ac4ebfcd8c95fca324b15606ab0ec1412d39
19 */
20
21 #include <Python.h>
22 #include <mach/mach_error.h>
23 #include <mach/mach_host.h>
24 #include <mach/mach_port.h>
25 #include <mach/mach_vm.h>
26 #include <sys/sysctl.h>
27 #include <sys/vmmeter.h>
28 #include <mach/mach.h>
29 #if defined(__arm64__) || defined(__aarch64__)
30 #include <CoreFoundation/CoreFoundation.h>
31 #include <IOKit/IOKitLib.h>
32 #endif
33
34 #include "../../arch/all/init.h"
35
36 // added in macOS 12
37 #ifndef kIOMainPortDefault
38 #define kIOMainPortDefault 0
39 #endif
40
41 PyObject *
42 psutil_cpu_count_logical(PyObject *self, PyObject *args) {
43 int num;
44
45 if (psutil_sysctlbyname("hw.logicalcpu", &num, sizeof(num)) != 0)
46 Py_RETURN_NONE; // mimic os.cpu_count()
47 else
48 return Py_BuildValue("i", num);
49 }
50
51
52 PyObject *
53 psutil_cpu_count_cores(PyObject *self, PyObject *args) {
54 int num;
55
56 if (psutil_sysctlbyname("hw.physicalcpu", &num, sizeof(num)) != 0)
57 Py_RETURN_NONE; // mimic os.cpu_count()
58 else
59 return Py_BuildValue("i", num);
60 }
61
62
63 PyObject *
64 psutil_cpu_times(PyObject *self, PyObject *args) {
65 mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;
66 kern_return_t error;
67 host_cpu_load_info_data_t r_load;
68 mach_port_t mport;
69
70 mport = mach_host_self();
71 if (mport == MACH_PORT_NULL) {
72 PyErr_SetString(PyExc_RuntimeError,
73 "mach_host_self() returned MACH_PORT_NULL");
74 return NULL;
75 }
76
77 error = host_statistics(mport, HOST_CPU_LOAD_INFO,
78 (host_info_t)&r_load, &count);
79 if (error != KERN_SUCCESS) {
80 mach_port_deallocate(mach_task_self(), mport);
81 return PyErr_Format(
82 PyExc_RuntimeError,
83 "host_statistics(HOST_CPU_LOAD_INFO) syscall failed: %s",
84 mach_error_string(error));
85 }
86 mach_port_deallocate(mach_task_self(), mport);
87
88 return Py_BuildValue(
89 "(dddd)",
90 (double)r_load.cpu_ticks[CPU_STATE_USER] / CLK_TCK,
91 (double)r_load.cpu_ticks[CPU_STATE_NICE] / CLK_TCK,
92 (double)r_load.cpu_ticks[CPU_STATE_SYSTEM] / CLK_TCK,
93 (double)r_load.cpu_ticks[CPU_STATE_IDLE] / CLK_TCK
94 );
95 }
96
97
98 PyObject *
99 psutil_cpu_stats(PyObject *self, PyObject *args) {
100 kern_return_t ret;
101 mach_msg_type_number_t count;
102 mach_port_t mport;
103 struct vmmeter vmstat;
104
105 mport = mach_host_self();
106 if (mport == MACH_PORT_NULL) {
107 PyErr_SetString(PyExc_RuntimeError,
108 "mach_host_self() returned MACH_PORT_NULL");
109 return NULL;
110 }
111
112 count = HOST_VM_INFO_COUNT;
113 ret = host_statistics(mport, HOST_VM_INFO, (host_info_t)&vmstat, &count);
114 if (ret != KERN_SUCCESS) {
115 mach_port_deallocate(mach_task_self(), mport);
116 PyErr_Format(
117 PyExc_RuntimeError,
118 "host_statistics(HOST_VM_INFO) failed: %s",
119 mach_error_string(ret));
120 return NULL;
121 }
122
123 mach_port_deallocate(mach_task_self(), mport);
124 return Py_BuildValue(
125 "IIIII",
126 vmstat.v_swtch, // context switches
127 vmstat.v_intr, // interrupts
128 vmstat.v_soft, // software interrupts
129 #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) \
130 && __MAC_OS_X_VERSION_MIN_REQUIRED__ >= 120000
131 0,
132 #else
133 vmstat.v_syscall, // system calls (if available)
134 #endif
135 vmstat.v_trap // traps
136 );
137 }
138
139
140 #if defined(__arm64__) || defined(__aarch64__)
141
142 // Helper to locate the 'pmgr' entry in AppleARMIODevice. Returns 0 on
143 // failure, nonzero on success, and stores the found entry in
144 // *out_entry. Caller is responsible for IOObjectRelease(*out_entry).
145 // Needed because on GitHub CI sometimes (but not all the times)
146 // "AppleARMIODevice" is not available.
147 static int
148 psutil_find_pmgr_entry(io_registry_entry_t *out_entry) {
149
150 kern_return_t status;
151 io_iterator_t iter = 0;
152 io_registry_entry_t entry = 0;
153 CFDictionaryRef matching;
154 io_name_t name;
155 int found = 0;
156
157 *out_entry = 0;
158
159 matching = IOServiceMatching("AppleARMIODevice");
160 if (matching == NULL)
161 return 0;
162
163 status = IOServiceGetMatchingServices(kIOMainPortDefault, matching, &iter);
164 if (status != KERN_SUCCESS)
165 return 0;
166
167 while ((entry = IOIteratorNext(iter)) != 0) {
168 status = IORegistryEntryGetName(entry, name);
169 if (status == KERN_SUCCESS && strcmp(name, "pmgr") == 0) {
170 found = 1;
171 break;
172 }
173 IOObjectRelease(entry);
174 }
175
176 IOObjectRelease(iter);
177
178 if (found) {
179 *out_entry = entry; // caller must release
180 return 1;
181 }
182
183 return 0;
184 }
185
186 // Python wrapper: return True/False.
187 PyObject *
188 psutil_has_cpu_freq(PyObject *self, PyObject *args) {
189 io_registry_entry_t entry = 0;
190 int ok = psutil_find_pmgr_entry(&entry);
191 if (entry != 0)
192 IOObjectRelease(entry);
193 if (ok)
194 Py_RETURN_TRUE;
195 Py_RETURN_FALSE;
196 }
197
198
199 PyObject *
200 psutil_cpu_freq(PyObject *self, PyObject *args) {
201 io_registry_entry_t entry = 0;
202 CFTypeRef pCoreRef = NULL;
203 CFTypeRef eCoreRef = NULL;
204 size_t pCoreLength;
205 uint32_t pMin = 0, eMin = 0, min = 0, max = 0, curr = 0;
206
207 if (!psutil_find_pmgr_entry(&entry)) {
208 return PyErr_Format(
209 PyExc_RuntimeError,
210 "'pmgr' entry was not found in AppleARMIODevice service"
211 );
212 }
213
214 pCoreRef = IORegistryEntryCreateCFProperty(
215 entry, CFSTR("voltage-states5-sram"), kCFAllocatorDefault, 0
216 );
217 if (pCoreRef == NULL ||
218 CFGetTypeID(pCoreRef) != CFDataGetTypeID() ||
219 CFDataGetLength(pCoreRef) < 8) {
220 PyErr_SetString(
221 PyExc_RuntimeError,
222 "'voltage-states5-sram' is missing or invalid"
223 );
224 goto error;
225 }
226
227 eCoreRef = IORegistryEntryCreateCFProperty(
228 entry, CFSTR("voltage-states1-sram"), kCFAllocatorDefault, 0
229 );
230 if (eCoreRef == NULL ||
231 CFGetTypeID(eCoreRef) != CFDataGetTypeID() ||
232 CFDataGetLength(eCoreRef) < 4) {
233 PyErr_SetString(
234 PyExc_RuntimeError,
235 "'voltage-states1-sram' is missing or invalid"
236 );
237 goto error;
238 }
239
240 pCoreLength = CFDataGetLength(pCoreRef);
241 CFDataGetBytes(pCoreRef, CFRangeMake(0, 4), (UInt8 *)&pMin);
242 CFDataGetBytes(eCoreRef, CFRangeMake(0, 4), (UInt8 *)&eMin);
243 CFDataGetBytes(pCoreRef, CFRangeMake(pCoreLength - 8, 4), (UInt8 *)&max);
244
245 min = (pMin < eMin) ? pMin : eMin;
246 curr = max;
247
248 if (pCoreRef)
249 CFRelease(pCoreRef);
250 if (eCoreRef)
251 CFRelease(eCoreRef);
252 if (entry)
253 IOObjectRelease(entry);
254
255 return Py_BuildValue(
256 "KKK",
257 (unsigned long long)(curr / 1000 / 1000),
258 (unsigned long long)(min / 1000 / 1000),
259 (unsigned long long)(max / 1000 / 1000)
260 );
261
262 error:
263 if (pCoreRef)
264 CFRelease(pCoreRef);
265 if (eCoreRef)
266 CFRelease(eCoreRef);
267 if (entry)
268 IOObjectRelease(entry);
269 return NULL;
270 }
271 #else // not ARM64 / ARCH64
272 PyObject *
273 psutil_has_cpu_freq(PyObject *self, PyObject *args) {
274 Py_RETURN_TRUE;
275 }
276
277 PyObject *
278 psutil_cpu_freq(PyObject *self, PyObject *args) {
279 unsigned int curr;
280 int64_t min;
281 int64_t max;
282 int mib[2];
283
284 // also available as "hw.cpufrequency" but it's deprecated
285 mib[0] = CTL_HW;
286 mib[1] = HW_CPU_FREQ;
287
288 if (psutil_sysctl(mib, 2, &curr, sizeof(curr)) < 0)
289 return psutil_PyErr_SetFromOSErrnoWithSyscall("sysctl(HW_CPU_FREQ)");
290
291 if (psutil_sysctlbyname("hw.cpufrequency_min", &min, sizeof(min)) != 0) {
292 min = 0;
293 psutil_debug("sysctlbyname('hw.cpufrequency_min') failed (set to 0)");
294 }
295
296 if (psutil_sysctlbyname("hw.cpufrequency_max", &max, sizeof(max)) != 0) {
297 max = 0;
298 psutil_debug("sysctlbyname('hw.cpufrequency_max') failed (set to 0)");
299 }
300
301 return Py_BuildValue(
302 "KKK",
303 (unsigned long long)(curr / 1000 / 1000),
304 (unsigned long long)(min / 1000 / 1000),
305 (unsigned long long)(max / 1000 / 1000));
306 }
307 #endif
308
309 PyObject *
310 psutil_per_cpu_times(PyObject *self, PyObject *args) {
311 natural_t cpu_count;
312 natural_t i;
313 processor_info_array_t info_array = NULL;
314 mach_msg_type_number_t info_count;
315 kern_return_t error;
316 processor_cpu_load_info_data_t *cpu_load_info = NULL;
317 int ret;
318 mach_port_t mport;
319 PyObject *py_retlist = PyList_New(0);
320 PyObject *py_cputime = NULL;
321
322 if (py_retlist == NULL)
323 return NULL;
324
325 mport = mach_host_self();
326 if (mport == MACH_PORT_NULL) {
327 PyErr_SetString(PyExc_RuntimeError,
328 "mach_host_self() returned MACH_PORT_NULL");
329 goto error;
330 }
331
332 error = host_processor_info(mport, PROCESSOR_CPU_LOAD_INFO,
333 &cpu_count, &info_array, &info_count);
334 if (error != KERN_SUCCESS) {
335 mach_port_deallocate(mach_task_self(), mport);
336 PyErr_Format(
337 PyExc_RuntimeError,
338 "host_processor_info(PROCESSOR_CPU_LOAD_INFO) syscall failed: %s",
339 mach_error_string(error));
340 goto error;
341 }
342 mach_port_deallocate(mach_task_self(), mport);
343
344 cpu_load_info = (processor_cpu_load_info_data_t *) info_array;
345
346 for (i = 0; i < cpu_count; i++) {
347 py_cputime = Py_BuildValue(
348 "(dddd)",
349 (double)cpu_load_info[i].cpu_ticks[CPU_STATE_USER] / CLK_TCK,
350 (double)cpu_load_info[i].cpu_ticks[CPU_STATE_NICE] / CLK_TCK,
351 (double)cpu_load_info[i].cpu_ticks[CPU_STATE_SYSTEM] / CLK_TCK,
352 (double)cpu_load_info[i].cpu_ticks[CPU_STATE_IDLE] / CLK_TCK
353 );
354 if (!py_cputime)
355 goto error;
356 if (PyList_Append(py_retlist, py_cputime)) {
357 Py_DECREF(py_cputime);
358 goto error;
359 }
360 Py_CLEAR(py_cputime);
361 }
362
363 ret = vm_deallocate(mach_task_self(), (vm_address_t)info_array,
364 info_count * sizeof(integer_t));
365 if (ret != KERN_SUCCESS)
366 PyErr_WarnEx(PyExc_RuntimeWarning, "vm_deallocate() failed", 2);
367 return py_retlist;
368
369 error:
370 Py_XDECREF(py_cputime);
371 Py_DECREF(py_retlist);
372 if (info_array != NULL) {
373 ret = vm_deallocate(mach_task_self(), (vm_address_t)info_array,
374 info_count * sizeof(integer_t));
375 if (ret != KERN_SUCCESS)
376 PyErr_WarnEx(PyExc_RuntimeWarning, "vm_deallocate() failed", 2);
377 }
378 return NULL;
379 }