pthread.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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. mutex->lock = 0;
  85. mutex->owner = 0;
  86. mutex->level = 0;
  87. mutex->type = attributes ? attributes->type : PTHREAD_MUTEX_NORMAL;
  88. return 0;
  89. }
  90. int pthread_mutex_destroy(pthread_mutex_t*)
  91. {
  92. return 0;
  93. }
  94. int pthread_mutex_lock(pthread_mutex_t* mutex)
  95. {
  96. auto& atomic = reinterpret_cast<Atomic<u32>&>(mutex->lock);
  97. pthread_t this_thread = pthread_self();
  98. for (;;) {
  99. u32 expected = false;
  100. if (!atomic.compare_exchange_strong(expected, true, AK::memory_order_acq_rel)) {
  101. if (mutex->type == PTHREAD_MUTEX_RECURSIVE && mutex->owner == this_thread) {
  102. mutex->level++;
  103. return 0;
  104. }
  105. sched_yield();
  106. continue;
  107. }
  108. mutex->owner = this_thread;
  109. mutex->level = 0;
  110. return 0;
  111. }
  112. }
  113. int pthread_mutex_trylock(pthread_mutex_t* mutex)
  114. {
  115. auto& atomic = reinterpret_cast<Atomic<u32>&>(mutex->lock);
  116. u32 expected = false;
  117. if (!atomic.compare_exchange_strong(expected, true, AK::memory_order_acq_rel)) {
  118. if (mutex->type == PTHREAD_MUTEX_RECURSIVE && mutex->owner == pthread_self()) {
  119. mutex->level++;
  120. return 0;
  121. }
  122. return EBUSY;
  123. }
  124. mutex->owner = pthread_self();
  125. mutex->level = 0;
  126. return 0;
  127. }
  128. int pthread_mutex_unlock(pthread_mutex_t* mutex)
  129. {
  130. if (mutex->type == PTHREAD_MUTEX_RECURSIVE && mutex->level > 0) {
  131. mutex->level--;
  132. return 0;
  133. }
  134. mutex->owner = 0;
  135. mutex->lock = 0;
  136. return 0;
  137. }
  138. int pthread_mutexattr_init(pthread_mutexattr_t* attr)
  139. {
  140. attr->type = PTHREAD_MUTEX_NORMAL;
  141. return 0;
  142. }
  143. int pthread_mutexattr_destroy(pthread_mutexattr_t*)
  144. {
  145. return 0;
  146. }
  147. int pthread_mutexattr_settype(pthread_mutexattr_t* attr, int type)
  148. {
  149. if (!attr)
  150. return EINVAL;
  151. if (type != PTHREAD_MUTEX_NORMAL && type != PTHREAD_MUTEX_RECURSIVE)
  152. return EINVAL;
  153. attr->type = type;
  154. return 0;
  155. }
  156. int pthread_attr_init(pthread_attr_t* attributes)
  157. {
  158. auto* impl = new PthreadAttrImpl {};
  159. *attributes = impl;
  160. #ifdef PTHREAD_DEBUG
  161. 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",
  162. impl,
  163. (PTHREAD_CREATE_JOINABLE == impl->m_detach_state) ? "joinable" : "detached",
  164. impl->m_schedule_priority,
  165. impl->m_guard_page_size,
  166. impl->m_stack_size,
  167. impl->m_stack_location);
  168. #endif
  169. return 0;
  170. }
  171. int pthread_attr_destroy(pthread_attr_t* attributes)
  172. {
  173. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  174. delete attributes_impl;
  175. return 0;
  176. }
  177. int pthread_attr_getdetachstate(const pthread_attr_t* attributes, int* p_detach_state)
  178. {
  179. auto* attributes_impl = *(reinterpret_cast<const PthreadAttrImpl* const*>(attributes));
  180. if (!attributes_impl || !p_detach_state)
  181. return EINVAL;
  182. *p_detach_state = attributes_impl->m_detach_state;
  183. return 0;
  184. }
  185. int pthread_attr_setdetachstate(pthread_attr_t* attributes, int detach_state)
  186. {
  187. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  188. if (!attributes_impl)
  189. return EINVAL;
  190. if ((PTHREAD_CREATE_JOINABLE != detach_state) || PTHREAD_CREATE_DETACHED != detach_state)
  191. return EINVAL;
  192. attributes_impl->m_detach_state = detach_state;
  193. #ifdef PTHREAD_DEBUG
  194. printf("pthread_attr_setdetachstate: Thread attributes at %p, detach state %s, priority %d, guard page size %d, stack size %d, stack location %p\n",
  195. attributes_impl,
  196. (PTHREAD_CREATE_JOINABLE == attributes_impl->m_detach_state) ? "joinable" : "detached",
  197. attributes_impl->m_schedule_priority,
  198. attributes_impl->m_guard_page_size,
  199. attributes_impl->m_stack_size,
  200. attributes_impl->m_stack_location);
  201. #endif
  202. return 0;
  203. }
  204. int pthread_attr_getguardsize(const pthread_attr_t* attributes, size_t* p_guard_size)
  205. {
  206. auto* attributes_impl = *(reinterpret_cast<const PthreadAttrImpl* const*>(attributes));
  207. if (!attributes_impl || !p_guard_size)
  208. return EINVAL;
  209. *p_guard_size = attributes_impl->m_reported_guard_page_size;
  210. return 0;
  211. }
  212. int pthread_attr_setguardsize(pthread_attr_t* attributes, size_t guard_size)
  213. {
  214. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  215. if (!attributes_impl)
  216. return EINVAL;
  217. size_t actual_guard_size = guard_size;
  218. // round up
  219. if (0 != (guard_size % PAGE_SIZE))
  220. actual_guard_size += PAGE_SIZE - (guard_size % PAGE_SIZE);
  221. // what is the user even doing?
  222. if (actual_guard_size > highest_reasonable_guard_size) {
  223. return EINVAL;
  224. }
  225. attributes_impl->m_guard_page_size = actual_guard_size;
  226. attributes_impl->m_reported_guard_page_size = guard_size; // POSIX, why?
  227. #ifdef PTHREAD_DEBUG
  228. printf("pthread_attr_setguardsize: Thread attributes at %p, detach state %s, priority %d, guard page size %d, stack size %d, stack location %p\n",
  229. attributes_impl,
  230. (PTHREAD_CREATE_JOINABLE == attributes_impl->m_detach_state) ? "joinable" : "detached",
  231. attributes_impl->m_schedule_priority,
  232. attributes_impl->m_guard_page_size,
  233. attributes_impl->m_stack_size,
  234. attributes_impl->m_stack_location);
  235. #endif
  236. return 0;
  237. }
  238. int pthread_attr_getschedparam(const pthread_attr_t* attributes, struct sched_param* p_sched_param)
  239. {
  240. auto* attributes_impl = *(reinterpret_cast<const PthreadAttrImpl* const*>(attributes));
  241. if (!attributes_impl || !p_sched_param)
  242. return EINVAL;
  243. p_sched_param->sched_priority = attributes_impl->m_schedule_priority;
  244. return 0;
  245. }
  246. int pthread_attr_setschedparam(pthread_attr_t* attributes, const struct sched_param* p_sched_param)
  247. {
  248. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  249. if (!attributes_impl || !p_sched_param)
  250. return EINVAL;
  251. // NOTE: This must track sched_get_priority_[min,max] and ThreadPriority enum in Thread.h
  252. if (p_sched_param->sched_priority < 0 || p_sched_param->sched_priority > 3)
  253. return ENOTSUP;
  254. attributes_impl->m_schedule_priority = p_sched_param->sched_priority;
  255. #ifdef PTHREAD_DEBUG
  256. printf("pthread_attr_setschedparam: Thread attributes at %p, detach state %s, priority %d, guard page size %d, stack size %d, stack location %p\n",
  257. attributes_impl,
  258. (PTHREAD_CREATE_JOINABLE == attributes_impl->m_detach_state) ? "joinable" : "detached",
  259. attributes_impl->m_schedule_priority,
  260. attributes_impl->m_guard_page_size,
  261. attributes_impl->m_stack_size,
  262. attributes_impl->m_stack_location);
  263. #endif
  264. return 0;
  265. }
  266. int pthread_attr_getstack(const pthread_attr_t* attributes, void** p_stack_ptr, size_t* p_stack_size)
  267. {
  268. auto* attributes_impl = *(reinterpret_cast<const PthreadAttrImpl* const*>(attributes));
  269. if (!attributes_impl || !p_stack_ptr || !p_stack_size)
  270. return EINVAL;
  271. *p_stack_ptr = attributes_impl->m_stack_location;
  272. *p_stack_size = attributes_impl->m_stack_size;
  273. return 0;
  274. }
  275. int pthread_attr_setstack(pthread_attr_t* attributes, void* p_stack, size_t stack_size)
  276. {
  277. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  278. if (!attributes_impl || !p_stack)
  279. return EINVAL;
  280. // Check for required alignment on size
  281. if (0 != (stack_size % required_stack_alignment))
  282. return EINVAL;
  283. // FIXME: Check for required alignment on pointer?
  284. // FIXME: "[EACCES] The stack page(s) described by stackaddr and stacksize are not both readable and writable by the thread."
  285. // Have to check that the whole range is mapped to this process/thread? Can we defer this to create_thread?
  286. attributes_impl->m_stack_size = stack_size;
  287. attributes_impl->m_stack_location = p_stack;
  288. #ifdef PTHREAD_DEBUG
  289. printf("pthread_attr_setstack: Thread attributes at %p, detach state %s, priority %d, guard page size %d, stack size %d, stack location %p\n",
  290. attributes_impl,
  291. (PTHREAD_CREATE_JOINABLE == attributes_impl->m_detach_state) ? "joinable" : "detached",
  292. attributes_impl->m_schedule_priority,
  293. attributes_impl->m_guard_page_size,
  294. attributes_impl->m_stack_size,
  295. attributes_impl->m_stack_location);
  296. #endif
  297. return 0;
  298. }
  299. int pthread_attr_getstacksize(const pthread_attr_t* attributes, size_t* p_stack_size)
  300. {
  301. auto* attributes_impl = *(reinterpret_cast<const PthreadAttrImpl* const*>(attributes));
  302. if (!attributes_impl || !p_stack_size)
  303. return EINVAL;
  304. *p_stack_size = attributes_impl->m_stack_size;
  305. return 0;
  306. }
  307. int pthread_attr_setstacksize(pthread_attr_t* attributes, size_t stack_size)
  308. {
  309. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  310. if (!attributes_impl)
  311. return EINVAL;
  312. if ((stack_size < PTHREAD_STACK_MIN) || stack_size > highest_reasonable_stack_size)
  313. return EINVAL;
  314. attributes_impl->m_stack_size = stack_size;
  315. #ifdef PTHREAD_DEBUG
  316. printf("pthread_attr_setstacksize: Thread attributes at %p, detach state %s, priority %d, guard page size %d, stack size %d, stack location %p\n",
  317. attributes_impl,
  318. (PTHREAD_CREATE_JOINABLE == attributes_impl->m_detach_state) ? "joinable" : "detached",
  319. attributes_impl->m_schedule_priority,
  320. attributes_impl->m_guard_page_size,
  321. attributes_impl->m_stack_size,
  322. attributes_impl->m_stack_location);
  323. #endif
  324. return 0;
  325. }
  326. int pthread_getschedparam(pthread_t thread, int* policy, struct sched_param* param)
  327. {
  328. (void)thread;
  329. (void)policy;
  330. (void)param;
  331. return 0;
  332. }
  333. int pthread_setschedparam(pthread_t thread, int policy, const struct sched_param* param)
  334. {
  335. (void)thread;
  336. (void)policy;
  337. (void)param;
  338. return 0;
  339. }
  340. struct WaitNode : public InlineLinkedListNode<WaitNode> {
  341. volatile bool waiting { true };
  342. WaitNode* m_next { nullptr };
  343. WaitNode* m_prev { nullptr };
  344. };
  345. struct ConditionVariable {
  346. InlineLinkedList<WaitNode> waiters;
  347. clockid_t clock { CLOCK_MONOTONIC };
  348. };
  349. int pthread_cond_init(pthread_cond_t* cond, const pthread_condattr_t* attr)
  350. {
  351. auto& condvar = *new ConditionVariable;
  352. cond->storage = &condvar;
  353. if (attr)
  354. condvar.clock = attr->clockid;
  355. return 0;
  356. }
  357. int pthread_cond_destroy(pthread_cond_t* cond)
  358. {
  359. delete static_cast<ConditionVariable*>(cond->storage);
  360. return 0;
  361. }
  362. int pthread_cond_wait(pthread_cond_t* cond, pthread_mutex_t* mutex)
  363. {
  364. WaitNode node;
  365. auto& condvar = *(ConditionVariable*)cond->storage;
  366. condvar.waiters.append(&node);
  367. while (node.waiting) {
  368. pthread_mutex_unlock(mutex);
  369. sched_yield();
  370. pthread_mutex_lock(mutex);
  371. }
  372. return 0;
  373. }
  374. int pthread_condattr_init(pthread_condattr_t* attr)
  375. {
  376. attr->clockid = CLOCK_MONOTONIC;
  377. return 0;
  378. }
  379. int pthread_condattr_destroy(pthread_condattr_t*)
  380. {
  381. return 0;
  382. }
  383. int pthread_condattr_setclock(pthread_condattr_t* attr, clockid_t clock)
  384. {
  385. attr->clockid = clock;
  386. return 0;
  387. }
  388. int pthread_cond_timedwait(pthread_cond_t* cond, pthread_mutex_t* mutex, const struct timespec* abstime)
  389. {
  390. WaitNode node;
  391. auto& condvar = *(ConditionVariable*)cond->storage;
  392. condvar.waiters.append(&node);
  393. while (node.waiting) {
  394. struct timespec now;
  395. if (clock_gettime(condvar.clock, &now) < 0) {
  396. dbgprintf("pthread_cond_timedwait: clock_gettime() failed\n");
  397. return errno;
  398. }
  399. if ((abstime->tv_sec < now.tv_sec) || (abstime->tv_sec == now.tv_sec && abstime->tv_nsec <= now.tv_nsec)) {
  400. return ETIMEDOUT;
  401. }
  402. pthread_mutex_unlock(mutex);
  403. sched_yield();
  404. pthread_mutex_lock(mutex);
  405. }
  406. return 0;
  407. }
  408. int pthread_cond_signal(pthread_cond_t* cond)
  409. {
  410. auto& condvar = *(ConditionVariable*)cond->storage;
  411. if (condvar.waiters.is_empty())
  412. return 0;
  413. auto* node = condvar.waiters.remove_head();
  414. node->waiting = false;
  415. return 0;
  416. }
  417. int pthread_cond_broadcast(pthread_cond_t* cond)
  418. {
  419. auto& condvar = *(ConditionVariable*)cond->storage;
  420. while (!condvar.waiters.is_empty()) {
  421. auto* node = condvar.waiters.remove_head();
  422. node->waiting = false;
  423. }
  424. return 0;
  425. }
  426. static const int max_keys = 64;
  427. typedef void (*KeyDestructor)(void*);
  428. struct KeyTable {
  429. // FIXME: Invoke key destructors on thread exit!
  430. KeyDestructor destructors[64] { nullptr };
  431. int next { 0 };
  432. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  433. };
  434. struct SpecificTable {
  435. void* values[64] { nullptr };
  436. };
  437. static KeyTable s_keys;
  438. __thread SpecificTable t_specifics;
  439. int pthread_key_create(pthread_key_t* key, KeyDestructor destructor)
  440. {
  441. int ret = 0;
  442. pthread_mutex_lock(&s_keys.mutex);
  443. if (s_keys.next >= max_keys) {
  444. ret = ENOMEM;
  445. } else {
  446. *key = s_keys.next++;
  447. s_keys.destructors[*key] = destructor;
  448. ret = 0;
  449. }
  450. pthread_mutex_unlock(&s_keys.mutex);
  451. return ret;
  452. }
  453. void* pthread_getspecific(pthread_key_t key)
  454. {
  455. if (key < 0)
  456. return nullptr;
  457. if (key >= max_keys)
  458. return nullptr;
  459. return t_specifics.values[key];
  460. }
  461. int pthread_setspecific(pthread_key_t key, const void* value)
  462. {
  463. if (key < 0)
  464. return EINVAL;
  465. if (key >= max_keys)
  466. return EINVAL;
  467. t_specifics.values[key] = const_cast<void*>(value);
  468. return 0;
  469. }
  470. int pthread_setname_np(pthread_t thread, const char* buffer, int buffer_size)
  471. {
  472. return syscall(SC_set_thread_name, thread, buffer, buffer_size);
  473. }
  474. int pthread_getname_np(pthread_t thread, char* buffer, int buffer_size)
  475. {
  476. return syscall(SC_get_thread_name, thread, buffer, buffer_size);
  477. }
  478. } // extern "C"