xref: /freebsd/contrib/llvm-project/llvm/lib/Support/Unix/Threading.inc (revision cd8537910406e68d4719136a5b0cf6d23bb1b23b)
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"
15#include "llvm/ADT/SmallString.h"
16#include "llvm/ADT/Twine.h"
17
18#if defined(__APPLE__)
19#include <mach/mach_init.h>
20#include <mach/mach_port.h>
21#endif
22
23#include <pthread.h>
24
25#if defined(__FreeBSD__) || defined(__OpenBSD__)
26#include <pthread_np.h> // For pthread_getthreadid_np() / pthread_set_name_np()
27#endif
28
29#if defined(__FreeBSD__)
30#include <sys/cpuset.h>
31#endif
32
33#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
34#include <errno.h>
35#include <sys/sysctl.h>
36#include <sys/user.h>
37#include <unistd.h>
38#endif
39
40#if defined(__NetBSD__)
41#include <lwp.h> // For _lwp_self()
42#endif
43
44#if defined(__OpenBSD__)
45#include <unistd.h> // For getthrid()
46#endif
47
48#if defined(__linux__)
49#include <sched.h>       // For sched_getaffinity
50#include <sys/syscall.h> // For syscall codes
51#include <unistd.h>      // For syscall()
52#endif
53
54static void *threadFuncSync(void *Arg) {
55  SyncThreadInfo *TI = static_cast<SyncThreadInfo *>(Arg);
56  TI->UserFn(TI->UserData);
57  return nullptr;
58}
59
60static void *threadFuncAsync(void *Arg) {
61  std::unique_ptr<AsyncThreadInfo> Info(static_cast<AsyncThreadInfo *>(Arg));
62  (*Info)();
63  return nullptr;
64}
65
66static void
67llvm_execute_on_thread_impl(void *(*ThreadFunc)(void *), void *Arg,
68                            llvm::Optional<unsigned> StackSizeInBytes,
69                            JoiningPolicy JP) {
70  int errnum;
71
72  // Construct the attributes object.
73  pthread_attr_t Attr;
74  if ((errnum = ::pthread_attr_init(&Attr)) != 0) {
75    ReportErrnumFatal("pthread_attr_init failed", errnum);
76  }
77
78  auto AttrGuard = llvm::make_scope_exit([&] {
79    if ((errnum = ::pthread_attr_destroy(&Attr)) != 0) {
80      ReportErrnumFatal("pthread_attr_destroy failed", errnum);
81    }
82  });
83
84  // Set the requested stack size, if given.
85  if (StackSizeInBytes) {
86    if ((errnum = ::pthread_attr_setstacksize(&Attr, *StackSizeInBytes)) != 0) {
87      ReportErrnumFatal("pthread_attr_setstacksize failed", errnum);
88    }
89  }
90
91  // Construct and execute the thread.
92  pthread_t Thread;
93  if ((errnum = ::pthread_create(&Thread, &Attr, ThreadFunc, Arg)) != 0)
94    ReportErrnumFatal("pthread_create failed", errnum);
95
96  if (JP == JoiningPolicy::Join) {
97    // Wait for the thread
98    if ((errnum = ::pthread_join(Thread, nullptr)) != 0) {
99      ReportErrnumFatal("pthread_join failed", errnum);
100    }
101  } else if (JP == JoiningPolicy::Detach) {
102    if ((errnum = ::pthread_detach(Thread)) != 0) {
103      ReportErrnumFatal("pthread_detach failed", errnum);
104    }
105  }
106}
107
108uint64_t llvm::get_threadid() {
109#if defined(__APPLE__)
110  // Calling "mach_thread_self()" bumps the reference count on the thread
111  // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
112  // count.
113  thread_port_t Self = mach_thread_self();
114  mach_port_deallocate(mach_task_self(), Self);
115  return Self;
116#elif defined(__FreeBSD__)
117  return uint64_t(pthread_getthreadid_np());
118#elif defined(__NetBSD__)
119  return uint64_t(_lwp_self());
120#elif defined(__OpenBSD__)
121  return uint64_t(getthrid());
122#elif defined(__ANDROID__)
123  return uint64_t(gettid());
124#elif defined(__linux__)
125  return uint64_t(syscall(SYS_gettid));
126#else
127  return uint64_t(pthread_self());
128#endif
129}
130
131
132static constexpr uint32_t get_max_thread_name_length_impl() {
133#if defined(__NetBSD__)
134  return PTHREAD_MAX_NAMELEN_NP;
135#elif defined(__APPLE__)
136  return 64;
137#elif defined(__linux__)
138#if HAVE_PTHREAD_SETNAME_NP
139  return 16;
140#else
141  return 0;
142#endif
143#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
144  return 16;
145#elif defined(__OpenBSD__)
146  return 32;
147#else
148  return 0;
149#endif
150}
151
152uint32_t llvm::get_max_thread_name_length() {
153  return get_max_thread_name_length_impl();
154}
155
156void llvm::set_thread_name(const Twine &Name) {
157  // Make sure the input is null terminated.
158  SmallString<64> Storage;
159  StringRef NameStr = Name.toNullTerminatedStringRef(Storage);
160
161  // Truncate from the beginning, not the end, if the specified name is too
162  // long.  For one, this ensures that the resulting string is still null
163  // terminated, but additionally the end of a long thread name will usually
164  // be more unique than the beginning, since a common pattern is for similar
165  // threads to share a common prefix.
166  // Note that the name length includes the null terminator.
167  if (get_max_thread_name_length() > 0)
168    NameStr = NameStr.take_back(get_max_thread_name_length() - 1);
169  (void)NameStr;
170#if defined(__linux__)
171#if (defined(__GLIBC__) && defined(_GNU_SOURCE)) || defined(__ANDROID__)
172#if HAVE_PTHREAD_SETNAME_NP
173  ::pthread_setname_np(::pthread_self(), NameStr.data());
174#endif
175#endif
176#elif defined(__FreeBSD__) || defined(__OpenBSD__)
177  ::pthread_set_name_np(::pthread_self(), NameStr.data());
178#elif defined(__NetBSD__)
179  ::pthread_setname_np(::pthread_self(), "%s",
180    const_cast<char *>(NameStr.data()));
181#elif defined(__APPLE__)
182  ::pthread_setname_np(NameStr.data());
183#endif
184}
185
186void llvm::get_thread_name(SmallVectorImpl<char> &Name) {
187  Name.clear();
188
189#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
190  int pid = ::getpid();
191  uint64_t tid = get_threadid();
192
193  struct kinfo_proc *kp = nullptr, *nkp;
194  size_t len = 0;
195  int error;
196  int ctl[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID | KERN_PROC_INC_THREAD,
197    (int)pid };
198
199  while (1) {
200    error = sysctl(ctl, 4, kp, &len, nullptr, 0);
201    if (kp == nullptr || (error != 0 && errno == ENOMEM)) {
202      // Add extra space in case threads are added before next call.
203      len += sizeof(*kp) + len / 10;
204      nkp = (struct kinfo_proc *)::realloc(kp, len);
205      if (nkp == nullptr) {
206        free(kp);
207        return;
208      }
209      kp = nkp;
210      continue;
211    }
212    if (error != 0)
213      len = 0;
214    break;
215  }
216
217  for (size_t i = 0; i < len / sizeof(*kp); i++) {
218    if (kp[i].ki_tid == (lwpid_t)tid) {
219      Name.append(kp[i].ki_tdname, kp[i].ki_tdname + strlen(kp[i].ki_tdname));
220      break;
221    }
222  }
223  free(kp);
224  return;
225#elif defined(__NetBSD__)
226  constexpr uint32_t len = get_max_thread_name_length_impl();
227  char buf[len];
228  ::pthread_getname_np(::pthread_self(), buf, len);
229
230  Name.append(buf, buf + strlen(buf));
231#elif defined(__OpenBSD__)
232  constexpr uint32_t len = get_max_thread_name_length_impl();
233  char buf[len];
234  ::pthread_get_name_np(::pthread_self(), buf, len);
235
236  Name.append(buf, buf + strlen(buf));
237#elif defined(__linux__)
238#if HAVE_PTHREAD_GETNAME_NP
239  constexpr uint32_t len = get_max_thread_name_length_impl();
240  char Buffer[len] = {'\0'};  // FIXME: working around MSan false positive.
241  if (0 == ::pthread_getname_np(::pthread_self(), Buffer, len))
242    Name.append(Buffer, Buffer + strlen(Buffer));
243#endif
244#endif
245}
246
247SetThreadPriorityResult llvm::set_thread_priority(ThreadPriority Priority) {
248#if defined(__linux__) && defined(SCHED_IDLE)
249  // Some *really* old glibcs are missing SCHED_IDLE.
250  // http://man7.org/linux/man-pages/man3/pthread_setschedparam.3.html
251  // http://man7.org/linux/man-pages/man2/sched_setscheduler.2.html
252  sched_param priority;
253  // For each of the above policies, param->sched_priority must be 0.
254  priority.sched_priority = 0;
255  // SCHED_IDLE    for running very low priority background jobs.
256  // SCHED_OTHER   the standard round-robin time-sharing policy;
257  return !pthread_setschedparam(
258             pthread_self(),
259             Priority == ThreadPriority::Background ? SCHED_IDLE : SCHED_OTHER,
260             &priority)
261             ? SetThreadPriorityResult::SUCCESS
262             : SetThreadPriorityResult::FAILURE;
263#elif defined(__APPLE__)
264  // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/getpriority.2.html
265  // When setting a thread into background state the scheduling priority is set
266  // to lowest value, disk and network IO are throttled. Network IO will be
267  // throttled for any sockets the thread opens after going into background
268  // state. Any previously opened sockets are not affected.
269
270  // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/getiopolicy_np.3.html
271  // I/Os with THROTTLE policy are called THROTTLE I/Os. If a THROTTLE I/O
272  // request occurs within a small time window (usually a fraction of a second)
273  // of another NORMAL I/O request, the thread that issues the THROTTLE I/O is
274  // forced to sleep for a certain interval. This slows down the thread that
275  // issues the THROTTLE I/O so that NORMAL I/Os can utilize most of the disk
276  // I/O bandwidth.
277  return !setpriority(PRIO_DARWIN_THREAD, 0,
278                      Priority == ThreadPriority::Background ? PRIO_DARWIN_BG
279                                                             : 0)
280             ? SetThreadPriorityResult::SUCCESS
281             : SetThreadPriorityResult::FAILURE;
282#endif
283  return SetThreadPriorityResult::FAILURE;
284}
285
286#include <thread>
287
288int computeHostNumHardwareThreads() {
289#ifdef __FreeBSD__
290  cpuset_t mask;
291  CPU_ZERO(&mask);
292  if (cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, sizeof(mask),
293                         &mask) == 0)
294    return CPU_COUNT(&mask);
295#endif
296#ifdef __linux__
297  cpu_set_t Set;
298  if (sched_getaffinity(0, sizeof(Set), &Set) == 0)
299    return CPU_COUNT(&Set);
300#endif
301  // Guard against std::thread::hardware_concurrency() returning 0.
302  if (unsigned Val = std::thread::hardware_concurrency())
303    return Val;
304  return 1;
305}
306
307void llvm::ThreadPoolStrategy::apply_thread_strategy(
308    unsigned ThreadPoolNum) const {}
309
310llvm::BitVector llvm::get_thread_affinity_mask() {
311  // FIXME: Implement
312  llvm_unreachable("Not implemented!");
313}
314
315unsigned llvm::get_cpus() { return 1; }
316