pthread.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. #include <AK/Assertions.h>
  2. #include <AK/Atomic.h>
  3. #include <AK/InlineLinkedList.h>
  4. #include <AK/StdLibExtras.h>
  5. #include <Kernel/Syscall.h>
  6. #include <limits.h>
  7. #include <pthread.h>
  8. #include <signal.h>
  9. #include <stdio.h>
  10. #include <sys/mman.h>
  11. #include <time.h>
  12. #include <unistd.h>
  13. #define PTHREAD_DEBUG
  14. namespace {
  15. using PthreadAttrImpl = Syscall::SC_create_thread_params;
  16. } // end anonymous namespace
  17. constexpr size_t required_stack_alignment = 4 * MB;
  18. constexpr size_t highest_reasonable_guard_size = 32 * PAGE_SIZE;
  19. constexpr size_t highest_reasonable_stack_size = 8 * MB; // That's the default in Ubuntu?
  20. extern "C" {
  21. static int create_thread(void* (*entry)(void*), void* argument, void* thread_params)
  22. {
  23. return syscall(SC_create_thread, entry, argument, thread_params);
  24. }
  25. static void exit_thread(void* code)
  26. {
  27. syscall(SC_exit_thread, code);
  28. ASSERT_NOT_REACHED();
  29. }
  30. int pthread_self()
  31. {
  32. return gettid();
  33. }
  34. int pthread_create(pthread_t* thread, pthread_attr_t* attributes, void* (*start_routine)(void*), void* argument_to_start_routine)
  35. {
  36. if (!thread)
  37. return -EINVAL;
  38. PthreadAttrImpl default_attributes {};
  39. PthreadAttrImpl** arg_attributes = reinterpret_cast<PthreadAttrImpl**>(attributes);
  40. PthreadAttrImpl* used_attributes = arg_attributes ? *arg_attributes : &default_attributes;
  41. if (!used_attributes->m_stack_location) {
  42. // adjust stack size, user might have called setstacksize, which has no restrictions on size/alignment
  43. if (0 != (used_attributes->m_stack_size % required_stack_alignment))
  44. used_attributes->m_stack_size += required_stack_alignment - (used_attributes->m_stack_size % required_stack_alignment);
  45. used_attributes->m_stack_location = mmap_with_name(nullptr, used_attributes->m_stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, 0, 0, "Thread stack");
  46. if (!used_attributes->m_stack_location)
  47. return -1;
  48. }
  49. #ifdef PTHREAD_DEBUG
  50. printf("pthread_create: Creating thread with attributes at %p, detach state %s, priority %d, guard page size %d, stack size %d, stack location %p\n",
  51. used_attributes,
  52. (PTHREAD_CREATE_JOINABLE == used_attributes->m_detach_state) ? "joinable" : "detached",
  53. used_attributes->m_schedule_priority,
  54. used_attributes->m_guard_page_size,
  55. used_attributes->m_stack_size,
  56. used_attributes->m_stack_location);
  57. #endif
  58. int rc = create_thread(start_routine, argument_to_start_routine, used_attributes);
  59. if (rc < 0)
  60. return rc;
  61. *thread = rc;
  62. return 0;
  63. }
  64. void pthread_exit(void* value_ptr)
  65. {
  66. exit_thread(value_ptr);
  67. }
  68. int pthread_join(pthread_t thread, void** exit_value_ptr)
  69. {
  70. return syscall(SC_join_thread, thread, exit_value_ptr);
  71. }
  72. int pthread_detach(pthread_t thread)
  73. {
  74. return syscall(SC_detach_thread, thread);
  75. }
  76. int pthread_sigmask(int how, const sigset_t* set, sigset_t* old_set)
  77. {
  78. if (sigprocmask(how, set, old_set))
  79. return errno;
  80. return 0;
  81. }
  82. int pthread_mutex_init(pthread_mutex_t* mutex, const pthread_mutexattr_t* attributes)
  83. {
  84. // FIXME: Implement mutex attributes
  85. UNUSED_PARAM(attributes);
  86. *mutex = 0;
  87. return 0;
  88. }
  89. int pthread_mutex_destroy(pthread_mutex_t*)
  90. {
  91. return 0;
  92. }
  93. int pthread_mutex_lock(pthread_mutex_t* mutex)
  94. {
  95. auto* atomic = reinterpret_cast<Atomic<u32>*>(mutex);
  96. for (;;) {
  97. u32 expected = false;
  98. if (atomic->compare_exchange_strong(expected, true, AK::memory_order_acq_rel))
  99. return 0;
  100. sched_yield();
  101. }
  102. }
  103. int pthread_mutex_trylock(pthread_mutex_t* mutex)
  104. {
  105. auto* atomic = reinterpret_cast<Atomic<u32>*>(mutex);
  106. u32 expected = false;
  107. if (atomic->compare_exchange_strong(expected, true, AK::memory_order_acq_rel))
  108. return 0;
  109. return EBUSY;
  110. }
  111. int pthread_mutex_unlock(pthread_mutex_t* mutex)
  112. {
  113. auto* atomic = reinterpret_cast<Atomic<u32>*>(mutex);
  114. atomic->store(false, AK::memory_order_release);
  115. return 0;
  116. }
  117. int pthread_mutexattr_init(pthread_mutexattr_t* attr)
  118. {
  119. attr->type = PTHREAD_MUTEX_NORMAL;
  120. return 0;
  121. }
  122. int pthread_mutexattr_destroy(pthread_mutexattr_t*)
  123. {
  124. return 0;
  125. }
  126. int pthread_attr_init(pthread_attr_t* attributes)
  127. {
  128. auto* impl = new PthreadAttrImpl {};
  129. *attributes = impl;
  130. #ifdef PTHREAD_DEBUG
  131. printf("pthread_attr_init: New thread attributes at %p, detach state %s, priority %d, guard page size %d, stack size %d, stack location %p\n",
  132. impl,
  133. (PTHREAD_CREATE_JOINABLE == impl->m_detach_state) ? "joinable" : "detached",
  134. impl->m_schedule_priority,
  135. impl->m_guard_page_size,
  136. impl->m_stack_size,
  137. impl->m_stack_location);
  138. #endif
  139. return 0;
  140. }
  141. int pthread_attr_destroy(pthread_attr_t* attributes)
  142. {
  143. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  144. delete attributes_impl;
  145. return 0;
  146. }
  147. int pthread_attr_getdetachstate(const pthread_attr_t* attributes, int* p_detach_state)
  148. {
  149. auto* attributes_impl = *(reinterpret_cast<const PthreadAttrImpl* const*>(attributes));
  150. if (!attributes_impl || !p_detach_state)
  151. return EINVAL;
  152. *p_detach_state = attributes_impl->m_detach_state;
  153. return 0;
  154. }
  155. int pthread_attr_setdetachstate(pthread_attr_t* attributes, int detach_state)
  156. {
  157. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  158. if (!attributes_impl)
  159. return EINVAL;
  160. if ((PTHREAD_CREATE_JOINABLE != detach_state) || PTHREAD_CREATE_DETACHED != detach_state)
  161. return EINVAL;
  162. attributes_impl->m_detach_state = detach_state;
  163. #ifdef PTHREAD_DEBUG
  164. printf("pthread_attr_setdetachstate: Thread attributes at %p, detach state %s, priority %d, guard page size %d, stack size %d, stack location %p\n",
  165. attributes_impl,
  166. (PTHREAD_CREATE_JOINABLE == attributes_impl->m_detach_state) ? "joinable" : "detached",
  167. attributes_impl->m_schedule_priority,
  168. attributes_impl->m_guard_page_size,
  169. attributes_impl->m_stack_size,
  170. attributes_impl->m_stack_location);
  171. #endif
  172. return 0;
  173. }
  174. int pthread_attr_getguardsize(const pthread_attr_t* attributes, size_t* p_guard_size)
  175. {
  176. auto* attributes_impl = *(reinterpret_cast<const PthreadAttrImpl* const*>(attributes));
  177. if (!attributes_impl || !p_guard_size)
  178. return EINVAL;
  179. *p_guard_size = attributes_impl->m_reported_guard_page_size;
  180. return 0;
  181. }
  182. int pthread_attr_setguardsize(pthread_attr_t* attributes, size_t guard_size)
  183. {
  184. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  185. if (!attributes_impl)
  186. return EINVAL;
  187. size_t actual_guard_size = guard_size;
  188. // round up
  189. if (0 != (guard_size % PAGE_SIZE))
  190. actual_guard_size += PAGE_SIZE - (guard_size % PAGE_SIZE);
  191. // what is the user even doing?
  192. if (actual_guard_size > highest_reasonable_guard_size) {
  193. return EINVAL;
  194. }
  195. attributes_impl->m_guard_page_size = actual_guard_size;
  196. attributes_impl->m_reported_guard_page_size = guard_size; // POSIX, why?
  197. #ifdef PTHREAD_DEBUG
  198. printf("pthread_attr_setguardsize: Thread attributes at %p, detach state %s, priority %d, guard page size %d, stack size %d, stack location %p\n",
  199. attributes_impl,
  200. (PTHREAD_CREATE_JOINABLE == attributes_impl->m_detach_state) ? "joinable" : "detached",
  201. attributes_impl->m_schedule_priority,
  202. attributes_impl->m_guard_page_size,
  203. attributes_impl->m_stack_size,
  204. attributes_impl->m_stack_location);
  205. #endif
  206. return 0;
  207. }
  208. int pthread_attr_getschedparam(const pthread_attr_t* attributes, struct sched_param* p_sched_param)
  209. {
  210. auto* attributes_impl = *(reinterpret_cast<const PthreadAttrImpl* const*>(attributes));
  211. if (!attributes_impl || !p_sched_param)
  212. return EINVAL;
  213. p_sched_param->sched_priority = attributes_impl->m_schedule_priority;
  214. return 0;
  215. }
  216. int pthread_attr_setschedparam(pthread_attr_t* attributes, const struct sched_param* p_sched_param)
  217. {
  218. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  219. if (!attributes_impl || !p_sched_param)
  220. return EINVAL;
  221. // NOTE: This must track sched_get_priority_[min,max] and ThreadPriority enum in Thread.h
  222. if (p_sched_param->sched_priority < 0 || p_sched_param->sched_priority > 3)
  223. return ENOTSUP;
  224. attributes_impl->m_schedule_priority = p_sched_param->sched_priority;
  225. #ifdef PTHREAD_DEBUG
  226. printf("pthread_attr_setschedparam: Thread attributes at %p, detach state %s, priority %d, guard page size %d, stack size %d, stack location %p\n",
  227. attributes_impl,
  228. (PTHREAD_CREATE_JOINABLE == attributes_impl->m_detach_state) ? "joinable" : "detached",
  229. attributes_impl->m_schedule_priority,
  230. attributes_impl->m_guard_page_size,
  231. attributes_impl->m_stack_size,
  232. attributes_impl->m_stack_location);
  233. #endif
  234. return 0;
  235. }
  236. int pthread_attr_getstack(const pthread_attr_t* attributes, void** p_stack_ptr, size_t* p_stack_size)
  237. {
  238. auto* attributes_impl = *(reinterpret_cast<const PthreadAttrImpl* const*>(attributes));
  239. if (!attributes_impl || !p_stack_ptr || !p_stack_size)
  240. return EINVAL;
  241. *p_stack_ptr = attributes_impl->m_stack_location;
  242. *p_stack_size = attributes_impl->m_stack_size;
  243. return 0;
  244. }
  245. int pthread_attr_setstack(pthread_attr_t* attributes, void* p_stack, size_t stack_size)
  246. {
  247. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  248. if (!attributes_impl || !p_stack)
  249. return EINVAL;
  250. // Check for required alignment on size
  251. if (0 != (stack_size % required_stack_alignment))
  252. return EINVAL;
  253. // FIXME: Check for required alignment on pointer?
  254. // FIXME: "[EACCES] The stack page(s) described by stackaddr and stacksize are not both readable and writable by the thread."
  255. // Have to check that the whole range is mapped to this process/thread? Can we defer this to create_thread?
  256. attributes_impl->m_stack_size = stack_size;
  257. attributes_impl->m_stack_location = p_stack;
  258. #ifdef PTHREAD_DEBUG
  259. printf("pthread_attr_setstack: Thread attributes at %p, detach state %s, priority %d, guard page size %d, stack size %d, stack location %p\n",
  260. attributes_impl,
  261. (PTHREAD_CREATE_JOINABLE == attributes_impl->m_detach_state) ? "joinable" : "detached",
  262. attributes_impl->m_schedule_priority,
  263. attributes_impl->m_guard_page_size,
  264. attributes_impl->m_stack_size,
  265. attributes_impl->m_stack_location);
  266. #endif
  267. return 0;
  268. }
  269. int pthread_attr_getstacksize(const pthread_attr_t* attributes, size_t* p_stack_size)
  270. {
  271. auto* attributes_impl = *(reinterpret_cast<const PthreadAttrImpl* const*>(attributes));
  272. if (!attributes_impl || !p_stack_size)
  273. return EINVAL;
  274. *p_stack_size = attributes_impl->m_stack_size;
  275. return 0;
  276. }
  277. int pthread_attr_setstacksize(pthread_attr_t* attributes, size_t stack_size)
  278. {
  279. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  280. if (!attributes_impl)
  281. return EINVAL;
  282. if ((stack_size < PTHREAD_STACK_MIN) || stack_size > highest_reasonable_stack_size)
  283. return EINVAL;
  284. attributes_impl->m_stack_size = stack_size;
  285. #ifdef PTHREAD_DEBUG
  286. printf("pthread_attr_setstacksize: Thread attributes at %p, detach state %s, priority %d, guard page size %d, stack size %d, stack location %p\n",
  287. attributes_impl,
  288. (PTHREAD_CREATE_JOINABLE == attributes_impl->m_detach_state) ? "joinable" : "detached",
  289. attributes_impl->m_schedule_priority,
  290. attributes_impl->m_guard_page_size,
  291. attributes_impl->m_stack_size,
  292. attributes_impl->m_stack_location);
  293. #endif
  294. return 0;
  295. }
  296. int pthread_getschedparam(pthread_t thread, int* policy, struct sched_param* param)
  297. {
  298. (void)thread;
  299. (void)policy;
  300. (void)param;
  301. return 0;
  302. }
  303. int pthread_setschedparam(pthread_t thread, int policy, const struct sched_param* param)
  304. {
  305. (void)thread;
  306. (void)policy;
  307. (void)param;
  308. return 0;
  309. }
  310. struct WaitNode : public InlineLinkedListNode<WaitNode> {
  311. volatile bool waiting { true };
  312. WaitNode* m_next { nullptr };
  313. WaitNode* m_prev { nullptr };
  314. };
  315. struct ConditionVariable {
  316. InlineLinkedList<WaitNode> waiters;
  317. clockid_t clock { CLOCK_MONOTONIC };
  318. };
  319. int pthread_cond_init(pthread_cond_t* cond, const pthread_condattr_t* attr)
  320. {
  321. auto& condvar = *new ConditionVariable;
  322. cond->storage = &condvar;
  323. if (attr)
  324. condvar.clock = attr->clockid;
  325. return 0;
  326. }
  327. int pthread_cond_destroy(pthread_cond_t* cond)
  328. {
  329. delete static_cast<ConditionVariable*>(cond->storage);
  330. return 0;
  331. }
  332. int pthread_cond_wait(pthread_cond_t* cond, pthread_mutex_t* mutex)
  333. {
  334. WaitNode node;
  335. auto& condvar = *(ConditionVariable*)cond->storage;
  336. condvar.waiters.append(&node);
  337. while (node.waiting) {
  338. pthread_mutex_unlock(mutex);
  339. sched_yield();
  340. pthread_mutex_lock(mutex);
  341. }
  342. return 0;
  343. }
  344. int pthread_condattr_init(pthread_condattr_t* attr)
  345. {
  346. attr->clockid = CLOCK_MONOTONIC;
  347. return 0;
  348. }
  349. int pthread_condattr_destroy(pthread_condattr_t*)
  350. {
  351. return 0;
  352. }
  353. int pthread_condattr_setclock(pthread_condattr_t* attr, clockid_t clock)
  354. {
  355. attr->clockid = clock;
  356. return 0;
  357. }
  358. int pthread_cond_timedwait(pthread_cond_t* cond, pthread_mutex_t* mutex, const struct timespec* abstime)
  359. {
  360. WaitNode node;
  361. auto& condvar = *(ConditionVariable*)cond->storage;
  362. condvar.waiters.append(&node);
  363. while (node.waiting) {
  364. struct timespec now;
  365. if (clock_gettime(condvar.clock, &now) < 0) {
  366. dbgprintf("pthread_cond_timedwait: clock_gettime() failed\n");
  367. return errno;
  368. }
  369. if ((abstime->tv_sec < now.tv_sec) || (abstime->tv_sec == now.tv_sec && abstime->tv_nsec <= now.tv_nsec)) {
  370. return ETIMEDOUT;
  371. }
  372. pthread_mutex_unlock(mutex);
  373. sched_yield();
  374. pthread_mutex_lock(mutex);
  375. }
  376. return 0;
  377. }
  378. int pthread_cond_signal(pthread_cond_t* cond)
  379. {
  380. auto& condvar = *(ConditionVariable*)cond->storage;
  381. if (condvar.waiters.is_empty())
  382. return 0;
  383. auto* node = condvar.waiters.remove_head();
  384. node->waiting = false;
  385. return 0;
  386. }
  387. int pthread_cond_broadcast(pthread_cond_t* cond)
  388. {
  389. auto& condvar = *(ConditionVariable*)cond->storage;
  390. while (!condvar.waiters.is_empty()) {
  391. auto* node = condvar.waiters.remove_head();
  392. node->waiting = false;
  393. }
  394. return 0;
  395. }
  396. static const int max_keys = 64;
  397. typedef void (*KeyDestructor)(void*);
  398. struct KeyTable {
  399. // FIXME: Invoke key destructors on thread exit!
  400. KeyDestructor destructors[64] { nullptr };
  401. int next { 0 };
  402. pthread_mutex_t mutex { PTHREAD_MUTEX_INITIALIZER };
  403. };
  404. struct SpecificTable {
  405. void* values[64] { nullptr };
  406. };
  407. static KeyTable s_keys;
  408. __thread SpecificTable t_specifics;
  409. int pthread_key_create(pthread_key_t* key, KeyDestructor destructor)
  410. {
  411. int ret = 0;
  412. pthread_mutex_lock(&s_keys.mutex);
  413. if (s_keys.next >= max_keys) {
  414. ret = ENOMEM;
  415. } else {
  416. *key = s_keys.next++;
  417. s_keys.destructors[*key] = destructor;
  418. ret = 0;
  419. }
  420. pthread_mutex_unlock(&s_keys.mutex);
  421. return ret;
  422. }
  423. void* pthread_getspecific(pthread_key_t key)
  424. {
  425. if (key < 0)
  426. return nullptr;
  427. if (key >= max_keys)
  428. return nullptr;
  429. return t_specifics.values[key];
  430. }
  431. int pthread_setspecific(pthread_key_t key, const void* value)
  432. {
  433. if (key < 0)
  434. return EINVAL;
  435. if (key >= max_keys)
  436. return EINVAL;
  437. t_specifics.values[key] = const_cast<void*>(value);
  438. return 0;
  439. }
  440. int pthread_setname_np(pthread_t thread, const char* buffer, int buffer_size)
  441. {
  442. return syscall(SC_set_thread_name, thread, buffer, buffer_size);
  443. }
  444. int pthread_getname_np(pthread_t thread, char* buffer, int buffer_size)
  445. {
  446. return syscall(SC_get_thread_name, thread, buffer, buffer_size);
  447. }
  448. } // extern "C"