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__) || defined(__FreeBSD_kernel__) 30#include <errno.h> 31#include <sys/cpuset.h> 32#include <sys/sysctl.h> 33#include <sys/user.h> 34#include <unistd.h> 35#endif 36 37#if defined(__NetBSD__) 38#include <lwp.h> // For _lwp_self() 39#endif 40 41#if defined(__OpenBSD__) 42#include <unistd.h> // For getthrid() 43#endif 44 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() 49#endif 50 51namespace llvm { 52pthread_t 53llvm_execute_on_thread_impl(void *(*ThreadFunc)(void *), void *Arg, 54 llvm::Optional<unsigned> StackSizeInBytes) { 55 int errnum; 56 57 // Construct the attributes object. 58 pthread_attr_t Attr; 59 if ((errnum = ::pthread_attr_init(&Attr)) != 0) { 60 ReportErrnumFatal("pthread_attr_init failed", errnum); 61 } 62 63 auto AttrGuard = llvm::make_scope_exit([&] { 64 if ((errnum = ::pthread_attr_destroy(&Attr)) != 0) { 65 ReportErrnumFatal("pthread_attr_destroy failed", errnum); 66 } 67 }); 68 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); 73 } 74 } 75 76 // Construct and execute the thread. 77 pthread_t Thread; 78 if ((errnum = ::pthread_create(&Thread, &Attr, ThreadFunc, Arg)) != 0) 79 ReportErrnumFatal("pthread_create failed", errnum); 80 81 return Thread; 82} 83 84void llvm_thread_detach_impl(pthread_t Thread) { 85 int errnum; 86 87 if ((errnum = ::pthread_detach(Thread)) != 0) { 88 ReportErrnumFatal("pthread_detach failed", errnum); 89 } 90} 91 92void llvm_thread_join_impl(pthread_t Thread) { 93 int errnum; 94 95 if ((errnum = ::pthread_join(Thread, nullptr)) != 0) { 96 ReportErrnumFatal("pthread_join failed", errnum); 97 } 98} 99 100pthread_t llvm_thread_get_id_impl(pthread_t Thread) { 101 return Thread; 102} 103 104pthread_t llvm_thread_get_current_id_impl() { 105 return ::pthread_self(); 106} 107 108} // namespace llvm 109 110uint64_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 114 // count. 115 thread_port_t Self = mach_thread_self(); 116 mach_port_deallocate(mach_task_self(), Self); 117 return 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)); 128#else 129 return uint64_t(pthread_self()); 130#endif 131} 132 133 134static constexpr uint32_t get_max_thread_name_length_impl() { 135#if defined(__NetBSD__) 136 return PTHREAD_MAX_NAMELEN_NP; 137#elif defined(__APPLE__) 138 return 64; 139#elif defined(__linux__) 140#if HAVE_PTHREAD_SETNAME_NP 141 return 16; 142#else 143 return 0; 144#endif 145#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) 146 return 16; 147#elif defined(__OpenBSD__) 148 return 32; 149#else 150 return 0; 151#endif 152} 153 154uint32_t llvm::get_max_thread_name_length() { 155 return get_max_thread_name_length_impl(); 156} 157 158void 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); 162 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); 171 (void)NameStr; 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()); 176#endif 177#endif 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()); 185#endif 186} 187 188void llvm::get_thread_name(SmallVectorImpl<char> &Name) { 189 Name.clear(); 190 191#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) 192 int pid = ::getpid(); 193 uint64_t tid = get_threadid(); 194 195 struct kinfo_proc *kp = nullptr, *nkp; 196 size_t len = 0; 197 int error; 198 int ctl[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID | KERN_PROC_INC_THREAD, 199 (int)pid }; 200 201 while (1) { 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) { 208 free(kp); 209 return; 210 } 211 kp = nkp; 212 continue; 213 } 214 if (error != 0) 215 len = 0; 216 break; 217 } 218 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)); 222 break; 223 } 224 } 225 free(kp); 226 return; 227#elif defined(__NetBSD__) 228 constexpr uint32_t len = get_max_thread_name_length_impl(); 229 char buf[len]; 230 ::pthread_getname_np(::pthread_self(), buf, len); 231 232 Name.append(buf, buf + strlen(buf)); 233#elif defined(__OpenBSD__) 234 constexpr uint32_t len = get_max_thread_name_length_impl(); 235 char buf[len]; 236 ::pthread_get_name_np(::pthread_self(), buf, len); 237 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)); 245#endif 246#endif 247} 248 249SetThreadPriorityResult 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( 260 pthread_self(), 261 Priority == ThreadPriority::Background ? SCHED_IDLE : SCHED_OTHER, 262 &priority) 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. 271 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 278 // I/O bandwidth. 279 return !setpriority(PRIO_DARWIN_THREAD, 0, 280 Priority == ThreadPriority::Background ? PRIO_DARWIN_BG 281 : 0) 282 ? SetThreadPriorityResult::SUCCESS 283 : SetThreadPriorityResult::FAILURE; 284#endif 285 return SetThreadPriorityResult::FAILURE; 286} 287 288#include <thread> 289 290int computeHostNumHardwareThreads() { 291#if defined(__FreeBSD__) 292 cpuset_t mask; 293 CPU_ZERO(&mask); 294 if (cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, sizeof(mask), 295 &mask) == 0) 296 return CPU_COUNT(&mask); 297#elif defined(__linux__) 298 cpu_set_t Set; 299 if (sched_getaffinity(0, sizeof(Set), &Set) == 0) 300 return CPU_COUNT(&Set); 301#endif 302 // Guard against std::thread::hardware_concurrency() returning 0. 303 if (unsigned Val = std::thread::hardware_concurrency()) 304 return Val; 305 return 1; 306} 307 308void llvm::ThreadPoolStrategy::apply_thread_strategy( 309 unsigned ThreadPoolNum) const {} 310 311llvm::BitVector llvm::get_thread_affinity_mask() { 312 // FIXME: Implement 313 llvm_unreachable("Not implemented!"); 314} 315 316unsigned llvm::get_cpus() { return 1; } 317