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