LLVM 23.0.0git
Threading.inc
Go to the documentation of this file.
1//===- Unix/Threading.inc - Unix Threading Implementation ----- -*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides the Unix specific implementation of Threading functions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "Unix.h"
14#include "llvm/ADT/ScopeExit.h"
17#include "llvm/ADT/StringRef.h"
18#include "llvm/ADT/Twine.h"
21
22#if defined(__APPLE__)
23#include <mach/mach_init.h>
24#include <mach/mach_port.h>
25#include <pthread/qos.h>
26#include <sys/sysctl.h>
27#include <sys/types.h>
28#endif
29
30#include <pthread.h>
31
32#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
33#include <pthread_np.h> // For pthread_getthreadid_np() / pthread_set_name_np()
34#endif
35
36// Must be included after Threading.inc to provide definition for llvm::thread
37// because FreeBSD's condvar.h (included by user.h) misuses the "thread"
38// keyword.
39#ifndef __FreeBSD__
40#include "llvm/Support/thread.h"
41#endif
42
43#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
44#include <errno.h>
45#include <sys/cpuset.h>
46#include <sys/sysctl.h>
47#include <sys/user.h>
48#include <unistd.h>
49#endif
50
51#if defined(__NetBSD__)
52#include <lwp.h> // For _lwp_self()
53#endif
54
55#if defined(__OpenBSD__)
56#include <unistd.h> // For getthrid()
57#endif
58
59#if defined(__linux__)
60#include <sched.h> // For sched_getaffinity
61#include <sys/syscall.h> // For syscall codes
62#include <unistd.h> // For syscall()
63#endif
64
65#if defined(__CYGWIN__)
66#include <sys/cpuset.h>
67#endif
68
69#if defined(__HAIKU__)
70#include <OS.h> // For B_OS_NAME_LENGTH
71#endif
72
73namespace llvm {
74pthread_t
75llvm_execute_on_thread_impl(void *(*ThreadFunc)(void *), void *Arg,
76 std::optional<unsigned> StackSizeInBytes) {
77 int errnum;
78
79 // Construct the attributes object.
80 pthread_attr_t Attr;
81 if ((errnum = ::pthread_attr_init(&Attr)) != 0) {
82 ReportErrnumFatal("pthread_attr_init failed", errnum);
83 }
84
85 llvm::scope_exit AttrGuard([&] {
86 if ((errnum = ::pthread_attr_destroy(&Attr)) != 0) {
87 ReportErrnumFatal("pthread_attr_destroy failed", errnum);
88 }
89 });
90
91 // Set the requested stack size, if given.
92 if (StackSizeInBytes) {
93 if ((errnum = ::pthread_attr_setstacksize(&Attr, *StackSizeInBytes)) != 0) {
94 ReportErrnumFatal("pthread_attr_setstacksize failed", errnum);
95 }
96 }
97
98 // Construct and execute the thread.
99 pthread_t Thread;
100 if ((errnum = ::pthread_create(&Thread, &Attr, ThreadFunc, Arg)) != 0)
101 ReportErrnumFatal("pthread_create failed", errnum);
102
103 return Thread;
104}
105
106void llvm_thread_detach_impl(pthread_t Thread) {
107 int errnum;
108
109 if ((errnum = ::pthread_detach(Thread)) != 0) {
110 ReportErrnumFatal("pthread_detach failed", errnum);
111 }
112}
113
114void llvm_thread_join_impl(pthread_t Thread) {
115 int errnum;
116
117 if ((errnum = ::pthread_join(Thread, nullptr)) != 0) {
118 ReportErrnumFatal("pthread_join failed", errnum);
119 }
120}
121
122llvm::thread::id llvm_thread_get_id_impl(pthread_t Thread) {
123#ifdef __MVS__
124 return Thread.__;
125#else
126 return Thread;
127#endif
128}
129
130llvm::thread::id llvm_thread_get_current_id_impl() {
131 return llvm_thread_get_id_impl(::pthread_self());
132}
133
134} // namespace llvm
135
137#if defined(__APPLE__)
138 // Calling "mach_thread_self()" bumps the reference count on the thread
139 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
140 // count.
141 static thread_local thread_port_t Self = [] {
142 thread_port_t InitSelf = mach_thread_self();
143 mach_port_deallocate(mach_task_self(), Self);
144 return InitSelf;
145 }();
146 return Self;
147#elif defined(__FreeBSD__) || defined(__DragonFly__)
148 return uint64_t(pthread_getthreadid_np());
149#elif defined(__NetBSD__)
150 return uint64_t(_lwp_self());
151#elif defined(__OpenBSD__)
152 return uint64_t(getthrid());
153#elif defined(__ANDROID__)
154 return uint64_t(gettid());
155#elif defined(__linux__)
156 return uint64_t(syscall(__NR_gettid));
157#elif defined(_AIX)
158 return uint64_t(thread_self());
159#elif defined(__MVS__)
160 return llvm_thread_get_id_impl(pthread_self());
161#else
162 return uint64_t(pthread_self());
163#endif
164}
165
166static constexpr uint32_t get_max_thread_name_length_impl() {
167#if defined(PTHREAD_MAX_NAMELEN_NP)
168 return PTHREAD_MAX_NAMELEN_NP;
169#elif defined(__HAIKU__)
170 return B_OS_NAME_LENGTH;
171#elif defined(__APPLE__)
172 return 64;
173#elif defined(__sun__) && defined(__svr4__)
174 return 31;
175#elif defined(__linux__) && HAVE_PTHREAD_SETNAME_NP
176 return 16;
177#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \
178 defined(__DragonFly__)
179 return 16;
180#elif defined(__OpenBSD__)
181 return 24;
182#elif defined(__CYGWIN__)
183 return 16;
184#else
185 return 0;
186#endif
187}
188
190 return get_max_thread_name_length_impl();
191}
192
193void llvm::set_thread_name(const Twine &Name) {
194 // Make sure the input is null terminated.
195 SmallString<64> Storage;
196 StringRef NameStr = Name.toNullTerminatedStringRef(Storage);
197
198 // Truncate from the beginning, not the end, if the specified name is too
199 // long. For one, this ensures that the resulting string is still null
200 // terminated, but additionally the end of a long thread name will usually
201 // be more unique than the beginning, since a common pattern is for similar
202 // threads to share a common prefix.
203 // Note that the name length includes the null terminator.
205 NameStr = NameStr.take_back(get_max_thread_name_length() - 1);
206 (void)NameStr;
207#if defined(HAVE_PTHREAD_SET_NAME_NP) && HAVE_PTHREAD_SET_NAME_NP
208 ::pthread_set_name_np(::pthread_self(), NameStr.data());
209#elif defined(HAVE_PTHREAD_SETNAME_NP) && HAVE_PTHREAD_SETNAME_NP
210#if defined(__NetBSD__)
211 ::pthread_setname_np(::pthread_self(), "%s",
212 const_cast<char *>(NameStr.data()));
213#elif defined(__APPLE__)
214 ::pthread_setname_np(NameStr.data());
215#else
216 ::pthread_setname_np(::pthread_self(), NameStr.data());
217#endif
218#endif
219}
220
221void llvm::get_thread_name(SmallVectorImpl<char> &Name) {
222 Name.clear();
223
224#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
225 int pid = ::getpid();
226 uint64_t tid = get_threadid();
227
228 struct kinfo_proc *kp = nullptr, *nkp;
229 size_t len = 0;
230 int error;
231 int ctl[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID | KERN_PROC_INC_THREAD,
232 (int)pid};
233
234 while (1) {
235 error = sysctl(ctl, 4, kp, &len, nullptr, 0);
236 if (kp == nullptr || (error != 0 && errno == ENOMEM)) {
237 // Add extra space in case threads are added before next call.
238 len += sizeof(*kp) + len / 10;
239 nkp = (struct kinfo_proc *)::realloc(kp, len);
240 if (nkp == nullptr) {
241 free(kp);
242 return;
243 }
244 kp = nkp;
245 continue;
246 }
247 if (error != 0)
248 len = 0;
249 break;
250 }
251
252 for (size_t i = 0; i < len / sizeof(*kp); i++) {
253 if (kp[i].ki_tid == (lwpid_t)tid) {
254 Name.append(kp[i].ki_tdname, kp[i].ki_tdname + strlen(kp[i].ki_tdname));
255 break;
256 }
257 }
258 free(kp);
259 return;
260#elif (defined(__linux__) || defined(__CYGWIN__)) && HAVE_PTHREAD_GETNAME_NP
261 constexpr uint32_t len = get_max_thread_name_length_impl();
262 char Buffer[len] = {'\0'}; // FIXME: working around MSan false positive.
263 if (0 == ::pthread_getname_np(::pthread_self(), Buffer, len))
264 Name.append(Buffer, Buffer + strlen(Buffer));
265#elif defined(HAVE_PTHREAD_GET_NAME_NP) && HAVE_PTHREAD_GET_NAME_NP
266 constexpr uint32_t len = get_max_thread_name_length_impl();
267 char buf[len];
268 ::pthread_get_name_np(::pthread_self(), buf, len);
269
270 Name.append(buf, buf + strlen(buf));
271
272#elif defined(HAVE_PTHREAD_GETNAME_NP) && HAVE_PTHREAD_GETNAME_NP
273 constexpr uint32_t len = get_max_thread_name_length_impl();
274 char buf[len];
275 ::pthread_getname_np(::pthread_self(), buf, len);
276
277 Name.append(buf, buf + strlen(buf));
278#endif
279}
280
281SetThreadPriorityResult llvm::set_thread_priority(ThreadPriority Priority) {
282#if (defined(__linux__) || defined(__CYGWIN__)) && defined(SCHED_IDLE)
283 // Some *really* old glibcs are missing SCHED_IDLE.
284 // http://man7.org/linux/man-pages/man3/pthread_setschedparam.3.html
285 // http://man7.org/linux/man-pages/man2/sched_setscheduler.2.html
286 sched_param priority;
287 // For each of the above policies, param->sched_priority must be 0.
288 priority.sched_priority = 0;
289 // SCHED_IDLE for running very low priority background jobs.
290 // SCHED_OTHER the standard round-robin time-sharing policy;
291 return !pthread_setschedparam(
292 pthread_self(),
293 // FIXME: consider SCHED_BATCH for Low
294 Priority == ThreadPriority::Default ? SCHED_OTHER : SCHED_IDLE,
295 &priority)
296 ? SetThreadPriorityResult::SUCCESS
297 : SetThreadPriorityResult::FAILURE;
298#elif defined(__APPLE__)
299 // https://developer.apple.com/documentation/apple-silicon/tuning-your-code-s-performance-for-apple-silicon
300 //
301 // Background - Applies to work that isn’t visible to the user and may take
302 // significant time to complete. Examples include indexing, backing up, or
303 // synchronizing data. This class emphasizes energy efficiency.
304 //
305 // Utility - Applies to work that takes anywhere from a few seconds to a few
306 // minutes to complete. Examples include downloading a document or importing
307 // data. This class offers a balance between responsiveness, performance, and
308 // energy efficiency.
309 const auto qosClass = [&]() {
310 switch (Priority) {
311 case ThreadPriority::Background:
312 return QOS_CLASS_BACKGROUND;
313 case ThreadPriority::Low:
314 return QOS_CLASS_UTILITY;
315 case ThreadPriority::Default:
316 return QOS_CLASS_DEFAULT;
317 }
318 }();
319 return !pthread_set_qos_class_self_np(qosClass, 0)
320 ? SetThreadPriorityResult::SUCCESS
321 : SetThreadPriorityResult::FAILURE;
322#endif
323 return SetThreadPriorityResult::FAILURE;
324}
325
326#include <thread>
327
328static int computeHostNumHardwareThreads() {
329#if defined(__FreeBSD__)
330 cpuset_t mask;
331 CPU_ZERO(&mask);
332 if (cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, sizeof(mask),
333 &mask) == 0)
334 return CPU_COUNT(&mask);
335#elif (defined(__linux__) || defined(__CYGWIN__))
336 cpu_set_t Set;
337 CPU_ZERO(&Set);
338 if (sched_getaffinity(0, sizeof(Set), &Set) == 0)
339 return CPU_COUNT(&Set);
340#endif
341 // Guard against std::thread::hardware_concurrency() returning 0.
342 if (unsigned Val = std::thread::hardware_concurrency())
343 return Val;
344 return 1;
345}
346
348 unsigned ThreadPoolNum) const {}
349
351 // FIXME: Implement
352 llvm_unreachable("Not implemented!");
353}
354
355unsigned llvm::get_cpus() { return 1; }
356
357#if (defined(__linux__) || defined(__CYGWIN__)) && \
358 (defined(__i386__) || defined(__x86_64__))
359// On Linux, the number of physical cores can be computed from /proc/cpuinfo,
360// using the number of unique physical/core id pairs. The following
361// implementation reads the /proc/cpuinfo format on an x86_64 system.
362static int computeHostNumPhysicalCores() {
363 // Enabled represents the number of physical id/core id pairs with at least
364 // one processor id enabled by the CPU affinity mask.
365 cpu_set_t Affinity, Enabled;
366 if (sched_getaffinity(0, sizeof(Affinity), &Affinity) != 0)
367 return -1;
368 CPU_ZERO(&Enabled);
369
370 // Read /proc/cpuinfo as a stream (until EOF reached). It cannot be
371 // mmapped because it appears to have 0 size.
374 if (std::error_code EC = Text.getError()) {
375 llvm::errs() << "Can't read "
376 << "/proc/cpuinfo: " << EC.message() << "\n";
377 return -1;
378 }
380 (*Text)->getBuffer().split(strs, "\n", /*MaxSplit=*/-1,
381 /*KeepEmpty=*/false);
382 int CurProcessor = -1;
383 int CurPhysicalId = -1;
384 int CurSiblings = -1;
385 int CurCoreId = -1;
386 for (StringRef Line : strs) {
387 std::pair<StringRef, StringRef> Data = Line.split(':');
388 auto Name = Data.first.trim();
389 auto Val = Data.second.trim();
390 // These fields are available if the kernel is configured with CONFIG_SMP.
391 if (Name == "processor")
392 Val.getAsInteger(10, CurProcessor);
393 else if (Name == "physical id")
394 Val.getAsInteger(10, CurPhysicalId);
395 else if (Name == "siblings")
396 Val.getAsInteger(10, CurSiblings);
397 else if (Name == "core id") {
398 Val.getAsInteger(10, CurCoreId);
399 // The processor id corresponds to an index into cpu_set_t.
400 if (CPU_ISSET(CurProcessor, &Affinity))
401 CPU_SET(CurPhysicalId * CurSiblings + CurCoreId, &Enabled);
402 }
403 }
404 return CPU_COUNT(&Enabled);
405}
406#elif (defined(__linux__) && defined(__s390x__)) || defined(_AIX)
407static int computeHostNumPhysicalCores() {
408 return sysconf(_SC_NPROCESSORS_ONLN);
409}
410#elif defined(__linux__)
411static int computeHostNumPhysicalCores() {
412 cpu_set_t Affinity;
413 if (sched_getaffinity(0, sizeof(Affinity), &Affinity) == 0)
414 return CPU_COUNT(&Affinity);
415
416 // The call to sched_getaffinity() may have failed because the Affinity
417 // mask is too small for the number of CPU's on the system (i.e. the
418 // system has more than 1024 CPUs). Allocate a mask large enough for
419 // twice as many CPUs.
420 cpu_set_t *DynAffinity;
421 DynAffinity = CPU_ALLOC(2048);
422 if (sched_getaffinity(0, CPU_ALLOC_SIZE(2048), DynAffinity) == 0) {
423 int NumCPUs = CPU_COUNT(DynAffinity);
424 CPU_FREE(DynAffinity);
425 return NumCPUs;
426 }
427 return -1;
428}
429#elif defined(__APPLE__)
430// Gets the number of *physical cores* on the machine.
431static int computeHostNumPhysicalCores() {
432 uint32_t count;
433 size_t len = sizeof(count);
434 sysctlbyname("hw.physicalcpu", &count, &len, NULL, 0);
435 if (count < 1) {
436 int nm[2];
437 nm[0] = CTL_HW;
438 nm[1] = HW_AVAILCPU;
439 sysctl(nm, 2, &count, &len, NULL, 0);
440 if (count < 1)
441 return -1;
442 }
443 return count;
444}
445#elif defined(__MVS__)
446static int computeHostNumPhysicalCores() {
447 enum {
448 // Byte offset of the pointer to the Communications Vector Table (CVT) in
449 // the Prefixed Save Area (PSA). The table entry is a 31-bit pointer and
450 // will be zero-extended to uintptr_t.
451 FLCCVT = 16,
452 // Byte offset of the pointer to the Common System Data Area (CSD) in the
453 // CVT. The table entry is a 31-bit pointer and will be zero-extended to
454 // uintptr_t.
455 CVTCSD = 660,
456 // Byte offset to the number of live CPs in the LPAR, stored as a signed
457 // 32-bit value in the table.
458 CSD_NUMBER_ONLINE_STANDARD_CPS = 264,
459 };
460 char *PSA = 0;
461 char *CVT = reinterpret_cast<char *>(
462 static_cast<uintptr_t>(reinterpret_cast<unsigned int &>(PSA[FLCCVT])));
463 char *CSD = reinterpret_cast<char *>(
464 static_cast<uintptr_t>(reinterpret_cast<unsigned int &>(CVT[CVTCSD])));
465 return reinterpret_cast<int &>(CSD[CSD_NUMBER_ONLINE_STANDARD_CPS]);
466}
467#else
468// On other systems, return -1 to indicate unknown.
469static int computeHostNumPhysicalCores() { return -1; }
470#endif
471
473 static int NumCores = computeHostNumPhysicalCores();
474 return NumCores;
475}
static constexpr unsigned long long mask(BlockVerifier::State S)
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallString class.
This file defines the SmallVector class.
#define error(X)
static void ReportErrnumFatal(const char *Msg, int errnum)
Definition Unix.h:63
Represents either an error or a value T.
Definition ErrorOr.h:56
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileAsStream(const Twine &Filename)
Read all of the specified file into a MemoryBuffer as a stream (i.e.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
LLVM_ABI void apply_thread_strategy(unsigned ThreadPoolNum) const
Assign the current thread to an ideal hardware CPU or NUMA node.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
LLVM_ABI llvm::BitVector get_thread_affinity_mask()
Returns a mask that represents on which hardware thread, core, CPU, NUMA group, the calling thread ca...
Definition Threading.cpp:40
LLVM_ABI uint32_t get_max_thread_name_length()
Get the maximum length of a thread name on this platform.
Definition Threading.cpp:34
LLVM_ABI SetThreadPriorityResult set_thread_priority(ThreadPriority Priority)
LLVM_ABI unsigned get_cpus()
Returns how many physical CPUs or NUMA groups the system has.
LLVM_ABI void set_thread_name(const Twine &Name)
Set the name of the current thread.
Definition Threading.cpp:36
SetThreadPriorityResult
Definition Threading.h:285
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI void get_thread_name(SmallVectorImpl< char > &Name)
Get the name of the current thread.
Definition Threading.cpp:38
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:189
LLVM_ABI int get_physical_cores()
Returns how many physical cores (as opposed to logical cores returned from thread::hardware_concurren...
Definition Threading.cpp:48
LLVM_ABI uint64_t get_threadid()
Return the current thread id, as used in various OS system calls.
Definition Threading.cpp:32
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2002
@ Enabled
Convert any .debug_str_offsets tables to DWARF64 if needed.
Definition DWP.h:27