VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/darwin/mp-darwin.cpp@ 106949

Last change on this file since 106949 was 106931, checked in by vboxsync, 4 months ago

IPRT/mp-darwin.cpp: some musings regarding RTMpCpuId [scm fix]

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 14.4 KB
Line 
1/* $Id: mp-darwin.cpp 106931 2024-11-11 16:07:13Z vboxsync $ */
2/** @file
3 * IPRT - Multiprocessor, Darwin.
4 */
5
6/*
7 * Copyright (C) 2006-2024 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * The contents of this file may alternatively be used under the terms
26 * of the Common Development and Distribution License Version 1.0
27 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
28 * in the VirtualBox distribution, in which case the provisions of the
29 * CDDL are applicable instead of those of the GPL.
30 *
31 * You may elect to license modified versions of this file under the
32 * terms and conditions of either the GPL or the CDDL or both.
33 *
34 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
35 */
36
37
38/*********************************************************************************************************************************
39* Header Files *
40*********************************************************************************************************************************/
41#define LOG_GROUP RTLOGGROUP_DEFAULT /*RTLOGGROUP_SYSTEM*/
42#include <iprt/types.h>
43
44#include <unistd.h>
45#include <stdio.h>
46#include <sys/sysctl.h>
47#include <sys/stat.h>
48#include <sys/fcntl.h>
49#include <errno.h>
50#include <mach/mach.h>
51
52#include <CoreFoundation/CFBase.h>
53#include <IOKit/IOKitLib.h>
54/*#include <IOKit/IOBSD.h>
55#include <IOKit/storage/IOStorageDeviceCharacteristics.h>
56#include <IOKit/storage/IOBlockStorageDevice.h>
57#include <IOKit/storage/IOMedia.h>
58#include <IOKit/storage/IOCDMedia.h>
59#include <IOKit/scsi/SCSITaskLib.h>
60#include <SystemConfiguration/SystemConfiguration.h>
61#include <mach/mach_error.h>
62#include <sys/param.h>
63#include <paths.h>*/
64
65#include <iprt/mp.h>
66#include <iprt/assert.h>
67#include <iprt/cpuset.h>
68#include <iprt/log.h>
69#include <iprt/string.h>
70
71
72/**
73 * Internal worker that determines the max possible logical CPU count (hyperthreads).
74 *
75 * @returns Max cpus.
76 */
77static RTCPUID rtMpDarwinMaxLogicalCpus(void)
78{
79 int cCpus = -1;
80 size_t cb = sizeof(cCpus);
81 int rc = sysctlbyname("hw.logicalcpu_max", &cCpus, &cb, NULL, 0);
82 if (rc != -1 && cCpus >= 1)
83 return cCpus;
84 AssertFailed();
85 return 1;
86}
87
88/**
89 * Internal worker that determines the max possible physical core count.
90 *
91 * @returns Max cpus.
92 */
93static RTCPUID rtMpDarwinMaxPhysicalCpus(void)
94{
95 int cCpus = -1;
96 size_t cb = sizeof(cCpus);
97 int rc = sysctlbyname("hw.physicalcpu_max", &cCpus, &cb, NULL, 0);
98 if (rc != -1 && cCpus >= 1)
99 return cCpus;
100 AssertFailed();
101 return 1;
102}
103
104
105#if 0 /* unused */
106/**
107 * Internal worker that determines the current number of logical CPUs (hyperthreads).
108 *
109 * @returns Max cpus.
110 */
111static RTCPUID rtMpDarwinOnlineLogicalCpus(void)
112{
113 int cCpus = -1;
114 size_t cb = sizeof(cCpus);
115 int rc = sysctlbyname("hw.logicalcpu", &cCpus, &cb, NULL, 0);
116 if (rc != -1 && cCpus >= 1)
117 return cCpus;
118 AssertFailed();
119 return 1;
120}
121#endif /* unused */
122
123
124/**
125 * Internal worker that determines the current number of physical CPUs.
126 *
127 * @returns Max cpus.
128 */
129static RTCPUID rtMpDarwinOnlinePhysicalCpus(void)
130{
131 int cCpus = -1;
132 size_t cb = sizeof(cCpus);
133 int rc = sysctlbyname("hw.physicalcpu", &cCpus, &cb, NULL, 0);
134 if (rc != -1 && cCpus >= 1)
135 return cCpus;
136 AssertFailed();
137 return 1;
138}
139
140
141#if defined(RT_ARCH_ARM64)
142RTDECL(RTCPUID) RTMpCpuId(void)
143{
144 /* xnu-7195.50.7.100.1/osfmk/arm64/start.s and machine_routines.c sets TPIDRRO_EL0
145 to the cpu_data_t::cpu_id value. */
146/** @todo r=bird: set_thread_register() in cswitch.s OTOH, applies MACHDEP_CPUNUM_MASK to
147 * the value before taking it as the CPU number. In libsyscall/os/tsd.h it is masked by
148 * the same value in _os_cpu_number(). */
149 uint64_t u64Ret;
150 __asm__ __volatile__("mrs %0,TPIDRRO_EL0\n\t" : "=r" (u64Ret));
151 return (RTCPUID)u64Ret;
152}
153#elif defined(RT_ARCH_ARM32)
154RTDECL(RTCPUID) RTMpCpuId(void)
155{
156 /* xnu-7195.50.7.100.1/osfmk/arm/start.s and machine_routines.c sets TPIDRURO
157 to the cpu_data_t::cpu_id value. */
158 uint32_t u32Ret;
159 __asm__ __volatile__("mrs p15, 0, %0, c13, c0, 3\n\t" : "=r" (u32Ret));
160 return (RTCPUID)u32Ret;
161}
162#endif
163
164
165RTDECL(int) RTMpCpuIdToSetIndex(RTCPUID idCpu)
166{
167 return idCpu < RTCPUSET_MAX_CPUS && idCpu < rtMpDarwinMaxLogicalCpus() ? idCpu : -1;
168}
169
170
171RTDECL(RTCPUID) RTMpCpuIdFromSetIndex(int iCpu)
172{
173 return (unsigned)iCpu < rtMpDarwinMaxLogicalCpus() ? iCpu : NIL_RTCPUID;
174}
175
176
177RTDECL(RTCPUID) RTMpGetMaxCpuId(void)
178{
179 return rtMpDarwinMaxLogicalCpus() - 1;
180}
181
182
183RTDECL(bool) RTMpIsCpuOnline(RTCPUID idCpu)
184{
185#if 0
186 return RTMpIsCpuPossible(idCpu);
187#else
188 /** @todo proper ring-3 support on darwin, see @bugref{3014}. */
189 natural_t cCpus;
190 processor_basic_info_t paInfo;
191 mach_msg_type_number_t cInfo;
192 kern_return_t krc = host_processor_info(mach_host_self(), PROCESSOR_BASIC_INFO,
193 &cCpus, (processor_info_array_t*)&paInfo, &cInfo);
194 AssertReturn(krc == KERN_SUCCESS, true);
195 bool const fIsOnline = idCpu < cCpus ? paInfo[idCpu].running : false;
196 vm_deallocate(mach_task_self(), (vm_address_t)paInfo, cInfo * sizeof(paInfo[0]));
197 return fIsOnline;
198#endif
199}
200
201
202RTDECL(bool) RTMpIsCpuPossible(RTCPUID idCpu)
203{
204 return idCpu != NIL_RTCPUID
205 && idCpu < rtMpDarwinMaxLogicalCpus();
206}
207
208
209RTDECL(PRTCPUSET) RTMpGetSet(PRTCPUSET pSet)
210{
211#if 0
212 RTCPUID cCpus = rtMpDarwinMaxLogicalCpus();
213 return RTCpuSetFromU64(RT_BIT_64(cCpus) - 1);
214
215#else
216 RTCpuSetEmpty(pSet);
217 RTCPUID cMax = rtMpDarwinMaxLogicalCpus();
218 for (RTCPUID idCpu = 0; idCpu < cMax; idCpu++)
219 if (RTMpIsCpuPossible(idCpu))
220 RTCpuSetAdd(pSet, idCpu);
221 return pSet;
222#endif
223}
224
225
226RTDECL(RTCPUID) RTMpGetCount(void)
227{
228 return rtMpDarwinMaxLogicalCpus();
229}
230
231
232RTDECL(RTCPUID) RTMpGetCoreCount(void)
233{
234 return rtMpDarwinMaxPhysicalCpus();
235}
236
237
238RTDECL(PRTCPUSET) RTMpGetOnlineSet(PRTCPUSET pSet)
239{
240 RTCpuSetEmpty(pSet);
241#if 0
242 RTCPUID cMax = rtMpDarwinMaxLogicalCpus();
243 for (RTCPUID idCpu = 0; idCpu < cMax; idCpu++)
244 if (RTMpIsCpuOnline(idCpu))
245 RTCpuSetAdd(pSet, idCpu);
246#else
247 natural_t cCpus = 0;
248 processor_basic_info_t paInfo = NULL;
249 mach_msg_type_number_t cInfo = 0;
250 kern_return_t krc = host_processor_info(mach_host_self(), PROCESSOR_BASIC_INFO,
251 &cCpus, (processor_info_array_t *)&paInfo, &cInfo);
252 AssertReturn(krc == KERN_SUCCESS, pSet);
253
254 AssertStmt(cCpus <= RTCPUSET_MAX_CPUS, cCpus = RTCPUSET_MAX_CPUS);
255 for (natural_t idCpu = 0; idCpu < cCpus; idCpu++)
256 if (paInfo[idCpu].running)
257 RTCpuSetAdd(pSet, idCpu);
258
259 vm_deallocate(mach_task_self(), (vm_address_t)paInfo, cInfo * sizeof(paInfo[0]));
260#endif
261 return pSet;
262}
263
264
265RTDECL(RTCPUID) RTMpGetOnlineCount(void)
266{
267 RTCPUSET Set;
268 RTMpGetOnlineSet(&Set);
269 return RTCpuSetCount(&Set);
270}
271
272
273RTDECL(RTCPUID) RTMpGetOnlineCoreCount(void)
274{
275 return rtMpDarwinOnlinePhysicalCpus();
276}
277
278
279RTDECL(uint32_t) RTMpGetCurFrequency(RTCPUID idCpu)
280{
281 /** @todo figure out how to get the current cpu speed on darwin. Have to
282 * check what powermanagement does. The powermetrics uses a private
283 * IOReportXxxx interface and *seems* (guessing) to calculate the frequency
284 * based on the frequency distribution over the last report period... This
285 * means that it's not really an suitable API for here. */
286 NOREF(idCpu);
287 return 0;
288}
289
290
291/**
292 * Worker for RTMpGetMaxFrequency.
293 * @returns Non-zero frequency in MHz on success, 0 on failure.
294 */
295static uint32_t rtMpDarwinGetMaxFrequencyFromIOService(io_service_t hCpu)
296{
297 io_struct_inband_t Buf = {0};
298 uint32_t cbActual = sizeof(Buf);
299 kern_return_t krc = IORegistryEntryGetProperty(hCpu, "clock-frequency", Buf, &cbActual);
300 Log2(("rtMpDarwinGetMaxFrequencyFromIOService: krc=%d; cbActual=%#x %.16Rhxs\n", krc, cbActual, Buf));
301 if (krc == kIOReturnSuccess)
302 {
303 switch (cbActual)
304 {
305 case sizeof(uint32_t):
306 return RT_BE2H_U32(*(uint32_t *)Buf) / 1000;
307 case sizeof(uint64_t):
308 AssertFailed();
309 return RT_BE2H_U64(*(uint64_t *)Buf) / 1000;
310 default:
311 AssertFailed();
312 }
313 }
314 return 0;
315}
316
317
318RTDECL(uint32_t) RTMpGetMaxFrequency(RTCPUID idCpu)
319{
320 if (!RTMpIsCpuOnline(idCpu))
321 return 0;
322
323 /*
324 * Try the 'hw.cpufrequency_max' one.
325 */
326 uint64_t CpuFrequencyMax = 0;
327 size_t cb = sizeof(CpuFrequencyMax);
328 int rc = sysctlbyname("hw.cpufrequency_max", &CpuFrequencyMax, &cb, NULL, 0);
329 if (!rc)
330 return (CpuFrequencyMax + 999999) / 1000000;
331
332 /*
333 * Use the deprecated one.
334 */
335 int aiMib[2];
336 aiMib[0] = CTL_HW;
337 aiMib[1] = HW_CPU_FREQ;
338 int iDeprecatedFrequency = -1;
339 cb = sizeof(iDeprecatedFrequency);
340 rc = sysctl(aiMib, RT_ELEMENTS(aiMib), &iDeprecatedFrequency, &cb, NULL, 0);
341 if (rc != -1 && iDeprecatedFrequency >= 1)
342 return iDeprecatedFrequency;
343
344 /*
345 * The above does not work for Apple M1 / xnu 20.1.0, so go look at the I/O registry instead.
346 *
347 * A sample ARM layout:
348 * | +-o cpu1@1 <class IOPlatformDevice, id 0x100000110, registered, matched, active, busy 0 (182 ms), retain 8>
349 * | | +-o AppleARMCPU <class AppleARMCPU, id 0x10000021b, registered, matched, active, busy 0 (1 ms), retain 6>
350 * | +-o cpu2@2 <class IOPlatformDevice, id 0x100000111, registered, matched, active, busy 0 (175 ms), retain 8>
351 * | | +-o AppleARMCPU <class AppleARMCPU, id 0x10000021c, registered, matched, active, busy 0 (3 ms), retain 6>
352 * | +-o cpu3@3 <class IOPlatformDevice, id 0x100000112, registered, matched, active, busy 0 (171 ms), retain 8>
353 * | | +-o AppleARMCPU <class AppleARMCPU, id 0x10000021d, registered, matched, active, busy 0 (1 ms), retain 6>
354 * | +-o cpu4@100 <class IOPlatformDevice, id 0x100000113, registered, matched, active, busy 0 (171 ms), retain 8>
355 * | | +-o AppleARMCPU <class AppleARMCPU, id 0x10000021e, registered, matched, active, busy 0 (1 ms), retain 6>
356 * | +-o cpu5@101 <class IOPlatformDevice, id 0x100000114, registered, matched, active, busy 0 (179 ms), retain 8>
357 * | | +-o AppleARMCPU <class AppleARMCPU, id 0x10000021f, registered, matched, active, busy 0 (9 ms), retain 6>
358 * | +-o cpu6@102 <class IOPlatformDevice, id 0x100000115, registered, matched, active, busy 0 (172 ms), retain 8>
359 * | | +-o AppleARMCPU <class AppleARMCPU, id 0x100000220, registered, matched, active, busy 0 (1 ms), retain 6>
360 * | +-o cpu7@103 <class IOPlatformDevice, id 0x100000116, registered, matched, active, busy 0 (175 ms), retain 8>
361 * | | +-o AppleARMCPU <class AppleARMCPU, id 0x100000221, registered, matched, active, busy 0 (5 ms), retain 6>
362 * | +-o cpus <class IOPlatformDevice, id 0x10000010e, registered, matched, active, busy 0 (12 ms), retain 15>
363 *
364 */
365
366#if 1 /* simpler way to get at it inspired by powermetrics, this is also used
367 in the arm version of RTMpGetDescription. */
368 /* Assume names on the form "cpu<N>" are only for CPUs. */
369 char szCpuPath[64];
370# if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
371 RTStrPrintf(szCpuPath, sizeof(szCpuPath), "IODeviceTree:/cpus/CPU%X", idCpu);
372# else
373 RTStrPrintf(szCpuPath, sizeof(szCpuPath), "IODeviceTree:/cpus/cpu%x", idCpu); /** @todo Hex? M1 Max only has 10 cores... */
374# endif
375
376 RT_GCC_NO_WARN_DEPRECATED_BEGIN
377 io_registry_entry_t hIoRegEntry = IORegistryEntryFromPath(kIOMasterPortDefault, szCpuPath); /* kIOMasterPortDefault: Deprecated since 12.0. */
378 RT_GCC_NO_WARN_DEPRECATED_END
379
380 if (hIoRegEntry != MACH_PORT_NULL)
381 {
382 uint32_t uCpuFrequency = rtMpDarwinGetMaxFrequencyFromIOService(hIoRegEntry);
383 IOObjectRelease(hIoRegEntry);
384 if (uCpuFrequency)
385 return uCpuFrequency;
386 }
387
388#else
389 /* Assume names on the form "cpu<N>" are only for CPUs. */
390 char szCpuName[32];
391 RTStrPrintf(szCpuName, sizeof(szCpuName), "cpu%u", idCpu);
392 CFMutableDictionaryRef hMatchingDict = IOServiceNameMatching(szCpuName);
393 AssertReturn(hMatchingDict, 0);
394
395 /* Just get the first one. */
396 io_object_t hCpu = IOServiceGetMatchingService(kIOMasterPortDefault, hMatchingDict);
397 if (hCpu != 0)
398 {
399 uint32_t uCpuFrequency = rtMpDarwinGetMaxFrequencyFromIOService(hCpu);
400 IOObjectRelease(hCpu);
401 if (uCpuFrequency)
402 return uCpuFrequency;
403 }
404
405# if 1 /* Just in case... */
406 /* Create a matching dictionary for searching for CPU services in the IOKit. */
407# if defined(RT_ARCH_ARM64) || defined(RT_ARCH_ARM32)
408 hMatchingDict = IOServiceMatching("AppleARMCPU");
409# elif defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
410 hMatchingDict = IOServiceMatching("AppleACPICPU");
411# else
412# error "Port me!"
413# endif
414 AssertReturn(hMatchingDict, 0);
415
416 /* Perform the search and get a collection of Apple CPU services. */
417 io_iterator_t hCpuServices = IO_OBJECT_NULL;
418 IOReturn irc = IOServiceGetMatchingServices(kIOMasterPortDefault, hMatchingDict, &hCpuServices);
419 AssertMsgReturn(irc == kIOReturnSuccess, ("irc=%d\n", irc), 0);
420 hMatchingDict = NULL; /* the reference is consumed by IOServiceGetMatchingServices. */
421
422 /* Enumerate the matching services. */
423 uint32_t uCpuFrequency = 0;
424 io_object_t hCurCpu;
425 while (uCpuFrequency == 0 && (hCurCpu = IOIteratorNext(hCpuServices)) != IO_OBJECT_NULL)
426 {
427 io_object_t hParent = (io_object_t)0;
428 irc = IORegistryEntryGetParentEntry(hCurCpu, kIOServicePlane, &hParent);
429 if (irc == kIOReturnSuccess && hParent)
430 {
431 uCpuFrequency = rtMpDarwinGetMaxFrequencyFromIOService(hParent);
432 IOObjectRelease(hParent);
433 }
434 IOObjectRelease(hCurCpu);
435 }
436 IOObjectRelease(hCpuServices);
437# endif
438#endif
439 AssertFailed();
440 return 0;
441}
442
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette