1 //===- Unix/Threading.inc - Unix Threading Implementation ----- -*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file provides the Unix specific implementation of Threading functions.
11 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/ScopeExit.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/Twine.h"
18 #if defined(__APPLE__)
19 #include <mach/mach_init.h>
20 #include <mach/mach_port.h>
25 #if defined(__FreeBSD__) || defined(__OpenBSD__)
26 #include <pthread_np.h> // For pthread_getthreadid_np() / pthread_set_name_np()
29 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
31 #include <sys/cpuset.h>
32 #include <sys/sysctl.h>
37 #if defined(__NetBSD__)
38 #include <lwp.h> // For _lwp_self()
41 #if defined(__OpenBSD__)
42 #include <unistd.h> // For getthrid()
45 #if defined(__linux__)
46 #include <sched.h> // For sched_getaffinity
47 #include <sys/syscall.h> // For syscall codes
48 #include <unistd.h> // For syscall()
53 llvm_execute_on_thread_impl(void *(*ThreadFunc)(void *), void *Arg,
54 llvm::Optional<unsigned> StackSizeInBytes) {
57 // Construct the attributes object.
59 if ((errnum = ::pthread_attr_init(&Attr)) != 0) {
60 ReportErrnumFatal("pthread_attr_init failed", errnum);
63 auto AttrGuard = llvm::make_scope_exit([&] {
64 if ((errnum = ::pthread_attr_destroy(&Attr)) != 0) {
65 ReportErrnumFatal("pthread_attr_destroy failed", errnum);
69 // Set the requested stack size, if given.
70 if (StackSizeInBytes) {
71 if ((errnum = ::pthread_attr_setstacksize(&Attr, *StackSizeInBytes)) != 0) {
72 ReportErrnumFatal("pthread_attr_setstacksize failed", errnum);
76 // Construct and execute the thread.
78 if ((errnum = ::pthread_create(&Thread, &Attr, ThreadFunc, Arg)) != 0)
79 ReportErrnumFatal("pthread_create failed", errnum);
84 void llvm_thread_detach_impl(pthread_t Thread) {
87 if ((errnum = ::pthread_detach(Thread)) != 0) {
88 ReportErrnumFatal("pthread_detach failed", errnum);
92 void llvm_thread_join_impl(pthread_t Thread) {
95 if ((errnum = ::pthread_join(Thread, nullptr)) != 0) {
96 ReportErrnumFatal("pthread_join failed", errnum);
100 pthread_t llvm_thread_get_id_impl(pthread_t Thread) {
104 pthread_t llvm_thread_get_current_id_impl() {
105 return ::pthread_self();
110 uint64_t llvm::get_threadid() {
111 #if defined(__APPLE__)
112 // Calling "mach_thread_self()" bumps the reference count on the thread
113 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
115 thread_port_t Self = mach_thread_self();
116 mach_port_deallocate(mach_task_self(), Self);
118 #elif defined(__FreeBSD__)
119 return uint64_t(pthread_getthreadid_np());
120 #elif defined(__NetBSD__)
121 return uint64_t(_lwp_self());
122 #elif defined(__OpenBSD__)
123 return uint64_t(getthrid());
124 #elif defined(__ANDROID__)
125 return uint64_t(gettid());
126 #elif defined(__linux__)
127 return uint64_t(syscall(SYS_gettid));
129 return uint64_t(pthread_self());
134 static constexpr uint32_t get_max_thread_name_length_impl() {
135 #if defined(__NetBSD__)
136 return PTHREAD_MAX_NAMELEN_NP;
137 #elif defined(__APPLE__)
139 #elif defined(__linux__)
140 #if HAVE_PTHREAD_SETNAME_NP
145 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
147 #elif defined(__OpenBSD__)
154 uint32_t llvm::get_max_thread_name_length() {
155 return get_max_thread_name_length_impl();
158 void llvm::set_thread_name(const Twine &Name) {
159 // Make sure the input is null terminated.
160 SmallString<64> Storage;
161 StringRef NameStr = Name.toNullTerminatedStringRef(Storage);
163 // Truncate from the beginning, not the end, if the specified name is too
164 // long. For one, this ensures that the resulting string is still null
165 // terminated, but additionally the end of a long thread name will usually
166 // be more unique than the beginning, since a common pattern is for similar
167 // threads to share a common prefix.
168 // Note that the name length includes the null terminator.
169 if (get_max_thread_name_length() > 0)
170 NameStr = NameStr.take_back(get_max_thread_name_length() - 1);
172 #if defined(__linux__)
173 #if (defined(__GLIBC__) && defined(_GNU_SOURCE)) || defined(__ANDROID__)
174 #if HAVE_PTHREAD_SETNAME_NP
175 ::pthread_setname_np(::pthread_self(), NameStr.data());
178 #elif defined(__FreeBSD__) || defined(__OpenBSD__)
179 ::pthread_set_name_np(::pthread_self(), NameStr.data());
180 #elif defined(__NetBSD__)
181 ::pthread_setname_np(::pthread_self(), "%s",
182 const_cast<char *>(NameStr.data()));
183 #elif defined(__APPLE__)
184 ::pthread_setname_np(NameStr.data());
188 void llvm::get_thread_name(SmallVectorImpl<char> &Name) {
191 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
192 int pid = ::getpid();
193 uint64_t tid = get_threadid();
195 struct kinfo_proc *kp = nullptr, *nkp;
198 int ctl[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID | KERN_PROC_INC_THREAD,
202 error = sysctl(ctl, 4, kp, &len, nullptr, 0);
203 if (kp == nullptr || (error != 0 && errno == ENOMEM)) {
204 // Add extra space in case threads are added before next call.
205 len += sizeof(*kp) + len / 10;
206 nkp = (struct kinfo_proc *)::realloc(kp, len);
207 if (nkp == nullptr) {
219 for (size_t i = 0; i < len / sizeof(*kp); i++) {
220 if (kp[i].ki_tid == (lwpid_t)tid) {
221 Name.append(kp[i].ki_tdname, kp[i].ki_tdname + strlen(kp[i].ki_tdname));
227 #elif defined(__NetBSD__)
228 constexpr uint32_t len = get_max_thread_name_length_impl();
230 ::pthread_getname_np(::pthread_self(), buf, len);
232 Name.append(buf, buf + strlen(buf));
233 #elif defined(__OpenBSD__)
234 constexpr uint32_t len = get_max_thread_name_length_impl();
236 ::pthread_get_name_np(::pthread_self(), buf, len);
238 Name.append(buf, buf + strlen(buf));
239 #elif defined(__linux__)
240 #if HAVE_PTHREAD_GETNAME_NP
241 constexpr uint32_t len = get_max_thread_name_length_impl();
242 char Buffer[len] = {'\0'}; // FIXME: working around MSan false positive.
243 if (0 == ::pthread_getname_np(::pthread_self(), Buffer, len))
244 Name.append(Buffer, Buffer + strlen(Buffer));
249 SetThreadPriorityResult llvm::set_thread_priority(ThreadPriority Priority) {
250 #if defined(__linux__) && defined(SCHED_IDLE)
251 // Some *really* old glibcs are missing SCHED_IDLE.
252 // http://man7.org/linux/man-pages/man3/pthread_setschedparam.3.html
253 // http://man7.org/linux/man-pages/man2/sched_setscheduler.2.html
254 sched_param priority;
255 // For each of the above policies, param->sched_priority must be 0.
256 priority.sched_priority = 0;
257 // SCHED_IDLE for running very low priority background jobs.
258 // SCHED_OTHER the standard round-robin time-sharing policy;
259 return !pthread_setschedparam(
261 Priority == ThreadPriority::Background ? SCHED_IDLE : SCHED_OTHER,
263 ? SetThreadPriorityResult::SUCCESS
264 : SetThreadPriorityResult::FAILURE;
265 #elif defined(__APPLE__)
266 // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/getpriority.2.html
267 // When setting a thread into background state the scheduling priority is set
268 // to lowest value, disk and network IO are throttled. Network IO will be
269 // throttled for any sockets the thread opens after going into background
270 // state. Any previously opened sockets are not affected.
272 // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/getiopolicy_np.3.html
273 // I/Os with THROTTLE policy are called THROTTLE I/Os. If a THROTTLE I/O
274 // request occurs within a small time window (usually a fraction of a second)
275 // of another NORMAL I/O request, the thread that issues the THROTTLE I/O is
276 // forced to sleep for a certain interval. This slows down the thread that
277 // issues the THROTTLE I/O so that NORMAL I/Os can utilize most of the disk
279 return !setpriority(PRIO_DARWIN_THREAD, 0,
280 Priority == ThreadPriority::Background ? PRIO_DARWIN_BG
282 ? SetThreadPriorityResult::SUCCESS
283 : SetThreadPriorityResult::FAILURE;
285 return SetThreadPriorityResult::FAILURE;
290 int computeHostNumHardwareThreads() {
291 #if defined(__FreeBSD__)
294 if (cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, sizeof(mask),
296 return CPU_COUNT(&mask);
297 #elif defined(__linux__)
299 if (sched_getaffinity(0, sizeof(Set), &Set) == 0)
300 return CPU_COUNT(&Set);
302 // Guard against std::thread::hardware_concurrency() returning 0.
303 if (unsigned Val = std::thread::hardware_concurrency())
308 void llvm::ThreadPoolStrategy::apply_thread_strategy(
309 unsigned ThreadPoolNum) const {}
311 llvm::BitVector llvm::get_thread_affinity_mask() {
313 llvm_unreachable("Not implemented!");
316 unsigned llvm::get_cpus() { return 1; }