Threading.inc 9.7 KB

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