pthread.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Assertions.h>
  7. #include <AK/Atomic.h>
  8. #include <AK/Debug.h>
  9. #include <AK/Format.h>
  10. #include <AK/StdLibExtras.h>
  11. #include <Kernel/API/Syscall.h>
  12. #include <LibSystem/syscall.h>
  13. #include <bits/pthread_integration.h>
  14. #include <errno.h>
  15. #include <limits.h>
  16. #include <pthread.h>
  17. #include <serenity.h>
  18. #include <signal.h>
  19. #include <stdio.h>
  20. #include <string.h>
  21. #include <sys/mman.h>
  22. #include <syscall.h>
  23. #include <time.h>
  24. #include <unistd.h>
  25. namespace {
  26. using PthreadAttrImpl = Syscall::SC_create_thread_params;
  27. } // end anonymous namespace
  28. static constexpr size_t required_stack_alignment = 4 * MiB;
  29. static constexpr size_t highest_reasonable_guard_size = 32 * PAGE_SIZE;
  30. static constexpr size_t highest_reasonable_stack_size = 8 * MiB; // That's the default in Ubuntu?
  31. #ifndef X86_64_NO_TLS
  32. __thread
  33. #endif
  34. void* s_stack_location;
  35. #ifndef X86_64_NO_TLS
  36. __thread
  37. #endif
  38. size_t s_stack_size;
  39. #define __RETURN_PTHREAD_ERROR(rc) \
  40. return ((rc) < 0 ? -(rc) : 0)
  41. extern "C" {
  42. static void* pthread_create_helper(void* (*routine)(void*), void* argument, void* stack_location, size_t stack_size)
  43. {
  44. s_stack_location = stack_location;
  45. s_stack_size = stack_size;
  46. void* ret_val = routine(argument);
  47. pthread_exit(ret_val);
  48. }
  49. static int create_thread(pthread_t* thread, void* (*entry)(void*), void* argument, PthreadAttrImpl* thread_params)
  50. {
  51. void** stack = (void**)((uintptr_t)thread_params->stack_location + thread_params->stack_size);
  52. auto push_on_stack = [&](void* data) {
  53. stack--;
  54. *stack = data;
  55. thread_params->stack_size -= sizeof(void*);
  56. };
  57. // We set up the stack for pthread_create_helper.
  58. // Note that we need to align the stack to 16B, accounting for
  59. // the fact that we also push 16 bytes.
  60. while (((uintptr_t)stack - 16) % 16 != 0)
  61. push_on_stack(nullptr);
  62. push_on_stack((void*)(uintptr_t)thread_params->stack_size);
  63. push_on_stack(thread_params->stack_location);
  64. push_on_stack(argument);
  65. push_on_stack((void*)entry);
  66. VERIFY((uintptr_t)stack % 16 == 0);
  67. // Push a fake return address
  68. push_on_stack(nullptr);
  69. int rc = syscall(SC_create_thread, pthread_create_helper, thread_params);
  70. if (rc >= 0)
  71. *thread = rc;
  72. __RETURN_PTHREAD_ERROR(rc);
  73. }
  74. [[noreturn]] static void exit_thread(void* code, void* stack_location, size_t stack_size)
  75. {
  76. __pthread_key_destroy_for_current_thread();
  77. syscall(SC_exit_thread, code, stack_location, stack_size);
  78. VERIFY_NOT_REACHED();
  79. }
  80. int pthread_self()
  81. {
  82. return __pthread_self();
  83. }
  84. int pthread_create(pthread_t* thread, pthread_attr_t* attributes, void* (*start_routine)(void*), void* argument_to_start_routine)
  85. {
  86. if (!thread)
  87. return -EINVAL;
  88. PthreadAttrImpl default_attributes {};
  89. PthreadAttrImpl** arg_attributes = reinterpret_cast<PthreadAttrImpl**>(attributes);
  90. PthreadAttrImpl* used_attributes = arg_attributes ? *arg_attributes : &default_attributes;
  91. if (!used_attributes->stack_location) {
  92. // adjust stack size, user might have called setstacksize, which has no restrictions on size/alignment
  93. if (0 != (used_attributes->stack_size % required_stack_alignment))
  94. used_attributes->stack_size += required_stack_alignment - (used_attributes->stack_size % required_stack_alignment);
  95. used_attributes->stack_location = mmap_with_name(nullptr, used_attributes->stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, 0, 0, "Thread stack");
  96. if (!used_attributes->stack_location)
  97. return -1;
  98. }
  99. dbgln_if(PTHREAD_DEBUG, "pthread_create: Creating thread with attributes at {}, detach state {}, priority {}, guard page size {}, stack size {}, stack location {}",
  100. used_attributes,
  101. (PTHREAD_CREATE_JOINABLE == used_attributes->detach_state) ? "joinable" : "detached",
  102. used_attributes->schedule_priority,
  103. used_attributes->guard_page_size,
  104. used_attributes->stack_size,
  105. used_attributes->stack_location);
  106. return create_thread(thread, start_routine, argument_to_start_routine, used_attributes);
  107. }
  108. void pthread_exit(void* value_ptr)
  109. {
  110. exit_thread(value_ptr, s_stack_location, s_stack_size);
  111. }
  112. void pthread_cleanup_push([[maybe_unused]] void (*routine)(void*), [[maybe_unused]] void* arg)
  113. {
  114. TODO();
  115. }
  116. void pthread_cleanup_pop([[maybe_unused]] int execute)
  117. {
  118. TODO();
  119. }
  120. int pthread_join(pthread_t thread, void** exit_value_ptr)
  121. {
  122. int rc = syscall(SC_join_thread, thread, exit_value_ptr);
  123. __RETURN_PTHREAD_ERROR(rc);
  124. }
  125. int pthread_detach(pthread_t thread)
  126. {
  127. int rc = syscall(SC_detach_thread, thread);
  128. __RETURN_PTHREAD_ERROR(rc);
  129. }
  130. int pthread_sigmask(int how, const sigset_t* set, sigset_t* old_set)
  131. {
  132. if (sigprocmask(how, set, old_set))
  133. return errno;
  134. return 0;
  135. }
  136. int pthread_mutex_init(pthread_mutex_t* mutex, const pthread_mutexattr_t* attributes)
  137. {
  138. return __pthread_mutex_init(mutex, attributes);
  139. }
  140. int pthread_mutex_destroy(pthread_mutex_t*)
  141. {
  142. return 0;
  143. }
  144. int pthread_mutex_lock(pthread_mutex_t* mutex)
  145. {
  146. return __pthread_mutex_lock(mutex);
  147. }
  148. int pthread_mutex_trylock(pthread_mutex_t* mutex)
  149. {
  150. return __pthread_mutex_trylock(mutex);
  151. }
  152. int pthread_mutex_unlock(pthread_mutex_t* mutex)
  153. {
  154. return __pthread_mutex_unlock(mutex);
  155. }
  156. int pthread_mutexattr_init(pthread_mutexattr_t* attr)
  157. {
  158. attr->type = PTHREAD_MUTEX_NORMAL;
  159. return 0;
  160. }
  161. int pthread_mutexattr_destroy(pthread_mutexattr_t*)
  162. {
  163. return 0;
  164. }
  165. int pthread_mutexattr_settype(pthread_mutexattr_t* attr, int type)
  166. {
  167. if (!attr)
  168. return EINVAL;
  169. if (type != PTHREAD_MUTEX_NORMAL && type != PTHREAD_MUTEX_RECURSIVE)
  170. return EINVAL;
  171. attr->type = type;
  172. return 0;
  173. }
  174. int pthread_mutexattr_gettype(pthread_mutexattr_t* attr, int* type)
  175. {
  176. *type = attr->type;
  177. return 0;
  178. }
  179. int pthread_attr_init(pthread_attr_t* attributes)
  180. {
  181. auto* impl = new PthreadAttrImpl {};
  182. *attributes = impl;
  183. dbgln_if(PTHREAD_DEBUG, "pthread_attr_init: New thread attributes at {}, detach state {}, priority {}, guard page size {}, stack size {}, stack location {}",
  184. impl,
  185. (PTHREAD_CREATE_JOINABLE == impl->detach_state) ? "joinable" : "detached",
  186. impl->schedule_priority,
  187. impl->guard_page_size,
  188. impl->stack_size,
  189. impl->stack_location);
  190. return 0;
  191. }
  192. int pthread_attr_destroy(pthread_attr_t* attributes)
  193. {
  194. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  195. delete attributes_impl;
  196. return 0;
  197. }
  198. int pthread_attr_getdetachstate(const pthread_attr_t* attributes, int* p_detach_state)
  199. {
  200. auto* attributes_impl = *(reinterpret_cast<const PthreadAttrImpl* const*>(attributes));
  201. if (!attributes_impl || !p_detach_state)
  202. return EINVAL;
  203. *p_detach_state = attributes_impl->detach_state;
  204. return 0;
  205. }
  206. int pthread_attr_setdetachstate(pthread_attr_t* attributes, int detach_state)
  207. {
  208. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  209. if (!attributes_impl)
  210. return EINVAL;
  211. if (detach_state != PTHREAD_CREATE_JOINABLE && detach_state != PTHREAD_CREATE_DETACHED)
  212. return EINVAL;
  213. attributes_impl->detach_state = detach_state;
  214. dbgln_if(PTHREAD_DEBUG, "pthread_attr_setdetachstate: Thread attributes at {}, detach state {}, priority {}, guard page size {}, stack size {}, stack location {}",
  215. attributes_impl,
  216. (PTHREAD_CREATE_JOINABLE == attributes_impl->detach_state) ? "joinable" : "detached",
  217. attributes_impl->schedule_priority,
  218. attributes_impl->guard_page_size,
  219. attributes_impl->stack_size,
  220. attributes_impl->stack_location);
  221. return 0;
  222. }
  223. int pthread_attr_getguardsize(const pthread_attr_t* attributes, size_t* p_guard_size)
  224. {
  225. auto* attributes_impl = *(reinterpret_cast<const PthreadAttrImpl* const*>(attributes));
  226. if (!attributes_impl || !p_guard_size)
  227. return EINVAL;
  228. *p_guard_size = attributes_impl->reported_guard_page_size;
  229. return 0;
  230. }
  231. int pthread_attr_setguardsize(pthread_attr_t* attributes, size_t guard_size)
  232. {
  233. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  234. if (!attributes_impl)
  235. return EINVAL;
  236. size_t actual_guard_size = guard_size;
  237. // round up
  238. if (0 != (guard_size % PAGE_SIZE))
  239. actual_guard_size += PAGE_SIZE - (guard_size % PAGE_SIZE);
  240. // what is the user even doing?
  241. if (actual_guard_size > highest_reasonable_guard_size) {
  242. return EINVAL;
  243. }
  244. attributes_impl->guard_page_size = actual_guard_size;
  245. attributes_impl->reported_guard_page_size = guard_size; // POSIX, why?
  246. dbgln_if(PTHREAD_DEBUG, "pthread_attr_setguardsize: Thread attributes at {}, detach state {}, priority {}, guard page size {}, stack size {}, stack location {}",
  247. attributes_impl,
  248. (PTHREAD_CREATE_JOINABLE == attributes_impl->detach_state) ? "joinable" : "detached",
  249. attributes_impl->schedule_priority,
  250. attributes_impl->guard_page_size,
  251. attributes_impl->stack_size,
  252. attributes_impl->stack_location);
  253. return 0;
  254. }
  255. int pthread_attr_getschedparam(const pthread_attr_t* attributes, struct sched_param* p_sched_param)
  256. {
  257. auto* attributes_impl = *(reinterpret_cast<const PthreadAttrImpl* const*>(attributes));
  258. if (!attributes_impl || !p_sched_param)
  259. return EINVAL;
  260. p_sched_param->sched_priority = attributes_impl->schedule_priority;
  261. return 0;
  262. }
  263. int pthread_attr_setschedparam(pthread_attr_t* attributes, const struct sched_param* p_sched_param)
  264. {
  265. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  266. if (!attributes_impl || !p_sched_param)
  267. return EINVAL;
  268. if (p_sched_param->sched_priority < THREAD_PRIORITY_MIN || p_sched_param->sched_priority > THREAD_PRIORITY_MAX)
  269. return ENOTSUP;
  270. attributes_impl->schedule_priority = p_sched_param->sched_priority;
  271. dbgln_if(PTHREAD_DEBUG, "pthread_attr_setschedparam: Thread attributes at {}, detach state {}, priority {}, guard page size {}, stack size {}, stack location {}",
  272. attributes_impl,
  273. (PTHREAD_CREATE_JOINABLE == attributes_impl->detach_state) ? "joinable" : "detached",
  274. attributes_impl->schedule_priority,
  275. attributes_impl->guard_page_size,
  276. attributes_impl->stack_size,
  277. attributes_impl->stack_location);
  278. return 0;
  279. }
  280. int pthread_attr_getstack(const pthread_attr_t* attributes, void** p_stack_ptr, size_t* p_stack_size)
  281. {
  282. auto* attributes_impl = *(reinterpret_cast<const PthreadAttrImpl* const*>(attributes));
  283. if (!attributes_impl || !p_stack_ptr || !p_stack_size)
  284. return EINVAL;
  285. *p_stack_ptr = attributes_impl->stack_location;
  286. *p_stack_size = attributes_impl->stack_size;
  287. return 0;
  288. }
  289. int pthread_attr_setstack(pthread_attr_t* attributes, void* p_stack, size_t stack_size)
  290. {
  291. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  292. if (!attributes_impl || !p_stack)
  293. return EINVAL;
  294. // Check for required alignment on size
  295. if (0 != (stack_size % required_stack_alignment))
  296. return EINVAL;
  297. // FIXME: Check for required alignment on pointer?
  298. // FIXME: "[EACCES] The stack page(s) described by stackaddr and stacksize are not both readable and writable by the thread."
  299. // Have to check that the whole range is mapped to this process/thread? Can we defer this to create_thread?
  300. attributes_impl->stack_size = stack_size;
  301. attributes_impl->stack_location = p_stack;
  302. dbgln_if(PTHREAD_DEBUG, "pthread_attr_setstack: Thread attributes at {}, detach state {}, priority {}, guard page size {}, stack size {}, stack location {}",
  303. attributes_impl,
  304. (PTHREAD_CREATE_JOINABLE == attributes_impl->detach_state) ? "joinable" : "detached",
  305. attributes_impl->schedule_priority,
  306. attributes_impl->guard_page_size,
  307. attributes_impl->stack_size,
  308. attributes_impl->stack_location);
  309. return 0;
  310. }
  311. int pthread_attr_getstacksize(const pthread_attr_t* attributes, size_t* p_stack_size)
  312. {
  313. auto* attributes_impl = *(reinterpret_cast<const PthreadAttrImpl* const*>(attributes));
  314. if (!attributes_impl || !p_stack_size)
  315. return EINVAL;
  316. *p_stack_size = attributes_impl->stack_size;
  317. return 0;
  318. }
  319. int pthread_attr_setstacksize(pthread_attr_t* attributes, size_t stack_size)
  320. {
  321. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  322. if (!attributes_impl)
  323. return EINVAL;
  324. if ((stack_size < PTHREAD_STACK_MIN) || stack_size > highest_reasonable_stack_size)
  325. return EINVAL;
  326. attributes_impl->stack_size = stack_size;
  327. dbgln_if(PTHREAD_DEBUG, "pthread_attr_setstacksize: Thread attributes at {}, detach state {}, priority {}, guard page size {}, stack size {}, stack location {}",
  328. attributes_impl,
  329. (PTHREAD_CREATE_JOINABLE == attributes_impl->detach_state) ? "joinable" : "detached",
  330. attributes_impl->schedule_priority,
  331. attributes_impl->guard_page_size,
  332. attributes_impl->stack_size,
  333. attributes_impl->stack_location);
  334. return 0;
  335. }
  336. int pthread_attr_getscope([[maybe_unused]] const pthread_attr_t* attributes, [[maybe_unused]] int* contention_scope)
  337. {
  338. return 0;
  339. }
  340. int pthread_attr_setscope([[maybe_unused]] pthread_attr_t* attributes, [[maybe_unused]] int contention_scope)
  341. {
  342. return 0;
  343. }
  344. int pthread_getschedparam([[maybe_unused]] pthread_t thread, [[maybe_unused]] int* policy, [[maybe_unused]] struct sched_param* param)
  345. {
  346. return 0;
  347. }
  348. int pthread_setschedparam([[maybe_unused]] pthread_t thread, [[maybe_unused]] int policy, [[maybe_unused]] const struct sched_param* param)
  349. {
  350. return 0;
  351. }
  352. int pthread_cond_init(pthread_cond_t* cond, const pthread_condattr_t* attr)
  353. {
  354. cond->value = 0;
  355. cond->previous = 0;
  356. cond->clockid = attr ? attr->clockid : CLOCK_MONOTONIC_COARSE;
  357. return 0;
  358. }
  359. int pthread_cond_destroy(pthread_cond_t*)
  360. {
  361. return 0;
  362. }
  363. static int futex_wait(uint32_t& futex_addr, uint32_t value, const struct timespec* abstime)
  364. {
  365. int saved_errno = errno;
  366. // NOTE: FUTEX_WAIT takes a relative timeout, so use FUTEX_WAIT_BITSET instead!
  367. int rc = futex(&futex_addr, FUTEX_WAIT_BITSET | FUTEX_CLOCK_REALTIME, value, abstime, nullptr, FUTEX_BITSET_MATCH_ANY);
  368. if (rc < 0 && errno == EAGAIN) {
  369. // If we didn't wait, that's not an error
  370. errno = saved_errno;
  371. rc = 0;
  372. }
  373. return rc;
  374. }
  375. static int cond_wait(pthread_cond_t* cond, pthread_mutex_t* mutex, const struct timespec* abstime)
  376. {
  377. u32 value = cond->value;
  378. cond->previous = value;
  379. pthread_mutex_unlock(mutex);
  380. int rc = futex_wait(cond->value, value, abstime);
  381. pthread_mutex_lock(mutex);
  382. return rc;
  383. }
  384. int pthread_cond_wait(pthread_cond_t* cond, pthread_mutex_t* mutex)
  385. {
  386. int rc = cond_wait(cond, mutex, nullptr);
  387. VERIFY(rc == 0);
  388. return 0;
  389. }
  390. int pthread_condattr_init(pthread_condattr_t* attr)
  391. {
  392. attr->clockid = CLOCK_MONOTONIC_COARSE;
  393. return 0;
  394. }
  395. int pthread_condattr_destroy(pthread_condattr_t*)
  396. {
  397. return 0;
  398. }
  399. int pthread_condattr_setclock(pthread_condattr_t* attr, clockid_t clock)
  400. {
  401. attr->clockid = clock;
  402. return 0;
  403. }
  404. int pthread_cond_timedwait(pthread_cond_t* cond, pthread_mutex_t* mutex, const struct timespec* abstime)
  405. {
  406. return cond_wait(cond, mutex, abstime);
  407. }
  408. int pthread_cond_signal(pthread_cond_t* cond)
  409. {
  410. u32 value = cond->previous + 1;
  411. cond->value = value;
  412. int rc = futex(&cond->value, FUTEX_WAKE, 1, nullptr, nullptr, 0);
  413. VERIFY(rc >= 0);
  414. return 0;
  415. }
  416. int pthread_cond_broadcast(pthread_cond_t* cond)
  417. {
  418. u32 value = cond->previous + 1;
  419. cond->value = value;
  420. int rc = futex(&cond->value, FUTEX_WAKE, INT32_MAX, nullptr, nullptr, 0);
  421. VERIFY(rc >= 0);
  422. return 0;
  423. }
  424. // libgcc expects this function to exist in libpthread, even
  425. // if it is not implemented.
  426. int pthread_cancel(pthread_t)
  427. {
  428. TODO();
  429. }
  430. int pthread_key_create(pthread_key_t* key, KeyDestructor destructor)
  431. {
  432. return __pthread_key_create(key, destructor);
  433. }
  434. int pthread_key_delete(pthread_key_t key)
  435. {
  436. return __pthread_key_delete(key);
  437. }
  438. void* pthread_getspecific(pthread_key_t key)
  439. {
  440. return __pthread_getspecific(key);
  441. }
  442. int pthread_setspecific(pthread_key_t key, const void* value)
  443. {
  444. return __pthread_setspecific(key, value);
  445. }
  446. int pthread_setname_np(pthread_t thread, const char* name)
  447. {
  448. if (!name)
  449. return EFAULT;
  450. int rc = syscall(SC_set_thread_name, thread, name, strlen(name));
  451. __RETURN_PTHREAD_ERROR(rc);
  452. }
  453. int pthread_getname_np(pthread_t thread, char* buffer, size_t buffer_size)
  454. {
  455. int rc = syscall(SC_get_thread_name, thread, buffer, buffer_size);
  456. __RETURN_PTHREAD_ERROR(rc);
  457. }
  458. int pthread_setcancelstate(int state, int* oldstate)
  459. {
  460. if (oldstate)
  461. *oldstate = PTHREAD_CANCEL_DISABLE;
  462. dbgln("FIXME: Implement pthread_setcancelstate({}, ...)", state);
  463. if (state != PTHREAD_CANCEL_DISABLE)
  464. return EINVAL;
  465. return 0;
  466. }
  467. int pthread_setcanceltype(int type, int* oldtype)
  468. {
  469. if (oldtype)
  470. *oldtype = PTHREAD_CANCEL_DEFERRED;
  471. dbgln("FIXME: Implement pthread_setcanceltype({}, ...)", type);
  472. if (type != PTHREAD_CANCEL_DEFERRED)
  473. return EINVAL;
  474. return 0;
  475. }
  476. constexpr static pid_t spinlock_unlock_sentinel = 0;
  477. int pthread_spin_destroy(pthread_spinlock_t* lock)
  478. {
  479. auto current = AK::atomic_load(&lock->m_lock);
  480. if (current != spinlock_unlock_sentinel)
  481. return EBUSY;
  482. return 0;
  483. }
  484. int pthread_spin_init(pthread_spinlock_t* lock, [[maybe_unused]] int shared)
  485. {
  486. lock->m_lock = spinlock_unlock_sentinel;
  487. return 0;
  488. }
  489. int pthread_spin_lock(pthread_spinlock_t* lock)
  490. {
  491. const auto desired = gettid();
  492. while (true) {
  493. auto current = AK::atomic_load(&lock->m_lock);
  494. if (current == desired)
  495. return EDEADLK;
  496. if (AK::atomic_compare_exchange_strong(&lock->m_lock, current, desired, AK::MemoryOrder::memory_order_acquire))
  497. break;
  498. }
  499. return 0;
  500. }
  501. int pthread_spin_trylock(pthread_spinlock_t* lock)
  502. {
  503. // We expect the current value to be unlocked, as the specification
  504. // states that trylock should lock only if it is not held by ANY thread.
  505. auto current = spinlock_unlock_sentinel;
  506. auto desired = gettid();
  507. if (AK::atomic_compare_exchange_strong(&lock->m_lock, current, desired, AK::MemoryOrder::memory_order_acquire)) {
  508. return 0;
  509. } else {
  510. return EBUSY;
  511. }
  512. }
  513. int pthread_spin_unlock(pthread_spinlock_t* lock)
  514. {
  515. auto current = AK::atomic_load(&lock->m_lock);
  516. if (gettid() != current)
  517. return EPERM;
  518. AK::atomic_store(&lock->m_lock, spinlock_unlock_sentinel);
  519. return 0;
  520. }
  521. int pthread_equal(pthread_t t1, pthread_t t2)
  522. {
  523. return t1 == t2;
  524. }
  525. // FIXME: Use the fancy futex mechanism above to write an rw lock.
  526. // For the time being, let's just use a less-than-good lock to get things working.
  527. int pthread_rwlock_destroy(pthread_rwlock_t* rl)
  528. {
  529. if (!rl)
  530. return 0;
  531. return 0;
  532. }
  533. // In a very non-straightforward way, this value is composed of two 32-bit integers
  534. // the top 32 bits are reserved for the ID of write-locking thread (if any)
  535. // and the bottom 32 bits are:
  536. // top 2 bits (30,31): reader wake mask, writer wake mask
  537. // middle 16 bits: information
  538. // bit 16: someone is waiting to write
  539. // bit 17: locked for write
  540. // bottom 16 bits (0..15): reader count
  541. constexpr static u32 reader_wake_mask = 1 << 30;
  542. constexpr static u32 writer_wake_mask = 1 << 31;
  543. constexpr static u32 writer_locked_mask = 1 << 17;
  544. constexpr static u32 writer_intent_mask = 1 << 16;
  545. int pthread_rwlock_init(pthread_rwlock_t* __restrict lockp, const pthread_rwlockattr_t* __restrict attr)
  546. {
  547. // Just ignore the attributes. use defaults for now.
  548. (void)attr;
  549. // No readers, no writer, not locked at all.
  550. *lockp = 0;
  551. return 0;
  552. }
  553. // Note that this function does not care about the top 32 bits at all.
  554. static int rwlock_rdlock_maybe_timed(u32* lockp, const struct timespec* timeout = nullptr, bool only_once = false, int value_if_timeout = -1, int value_if_okay = -2)
  555. {
  556. auto current = AK::atomic_load(lockp);
  557. for (; !only_once;) {
  558. // First, see if this is locked for writing
  559. // if it's not, try to add to the counter.
  560. // If someone is waiting to write, and there is one or no other readers, let them have the lock.
  561. if (!(current & writer_locked_mask)) {
  562. auto count = (u16)current;
  563. if (!(current & writer_intent_mask) || count > 1) {
  564. ++count;
  565. auto desired = (current << 16) | count;
  566. auto did_exchange = AK::atomic_compare_exchange_strong(lockp, current, desired, AK::MemoryOrder::memory_order_acquire);
  567. if (!did_exchange)
  568. continue; // tough luck, try again.
  569. return value_if_okay;
  570. }
  571. }
  572. // If no one else is waiting for the read wake bit, set it.
  573. if (!(current & reader_wake_mask)) {
  574. auto desired = current | reader_wake_mask;
  575. auto did_exchange = AK::atomic_compare_exchange_strong(lockp, current, desired, AK::MemoryOrder::memory_order_acquire);
  576. if (!did_exchange)
  577. continue; // Something interesting happened!
  578. current = desired;
  579. }
  580. // Seems like someone is writing (or is interested in writing and we let them have the lock)
  581. // wait until they're done.
  582. auto rc = futex(lockp, FUTEX_WAIT_BITSET, current, timeout, nullptr, reader_wake_mask);
  583. if (rc < 0 && errno == ETIMEDOUT && timeout) {
  584. return value_if_timeout;
  585. }
  586. if (rc < 0 && errno != EAGAIN) {
  587. // Something broke. let's just bail out.
  588. return errno;
  589. }
  590. errno = 0;
  591. // Reload the 'current' value
  592. current = AK::atomic_load(lockp);
  593. }
  594. return value_if_timeout;
  595. }
  596. static int rwlock_wrlock_maybe_timed(pthread_rwlock_t* lockval_p, const struct timespec* timeout = nullptr, bool only_once = false, int value_if_timeout = -1, int value_if_okay = -2)
  597. {
  598. u32* lockp = reinterpret_cast<u32*>(lockval_p);
  599. auto current = AK::atomic_load(lockp);
  600. for (; !only_once;) {
  601. // First, see if this is locked for writing, and if there are any readers.
  602. // if not, lock it.
  603. // If someone is waiting to write, let them have the lock.
  604. if (!(current & writer_locked_mask) && ((u16)current) == 0) {
  605. if (!(current & writer_intent_mask)) {
  606. auto desired = current | writer_locked_mask | writer_intent_mask;
  607. auto did_exchange = AK::atomic_compare_exchange_strong(lockp, current, desired, AK::MemoryOrder::memory_order_acquire);
  608. if (!did_exchange)
  609. continue;
  610. // Now that we've locked the value, it's safe to set our thread ID.
  611. AK::atomic_store(reinterpret_cast<i32*>(lockval_p) + 1, pthread_self());
  612. return value_if_okay;
  613. }
  614. }
  615. // That didn't work, if no one else is waiting for the write bit, set it.
  616. if (!(current & writer_wake_mask)) {
  617. auto desired = current | writer_wake_mask | writer_intent_mask;
  618. auto did_exchange = AK::atomic_compare_exchange_strong(lockp, current, desired, AK::MemoryOrder::memory_order_acquire);
  619. if (!did_exchange)
  620. continue; // Something interesting happened!
  621. current = desired;
  622. }
  623. // Seems like someone is writing (or is interested in writing and we let them have the lock)
  624. // wait until they're done.
  625. auto rc = futex(lockp, FUTEX_WAIT_BITSET, current, timeout, nullptr, writer_wake_mask);
  626. if (rc < 0 && errno == ETIMEDOUT && timeout) {
  627. return value_if_timeout;
  628. }
  629. if (rc < 0 && errno != EAGAIN) {
  630. // Something broke. let's just bail out.
  631. return errno;
  632. }
  633. errno = 0;
  634. // Reload the 'current' value
  635. current = AK::atomic_load(lockp);
  636. }
  637. return value_if_timeout;
  638. }
  639. int pthread_rwlock_rdlock(pthread_rwlock_t* lockp)
  640. {
  641. if (!lockp)
  642. return EINVAL;
  643. return rwlock_rdlock_maybe_timed(reinterpret_cast<u32*>(lockp), nullptr, false, 0, 0);
  644. }
  645. int pthread_rwlock_timedrdlock(pthread_rwlock_t* __restrict lockp, const struct timespec* __restrict timespec)
  646. {
  647. if (!lockp)
  648. return EINVAL;
  649. auto rc = rwlock_rdlock_maybe_timed(reinterpret_cast<u32*>(lockp), timespec);
  650. if (rc == -1) // "ok"
  651. return 0;
  652. if (rc == -2) // "timed out"
  653. return 1;
  654. return rc;
  655. }
  656. int pthread_rwlock_timedwrlock(pthread_rwlock_t* __restrict lockp, const struct timespec* __restrict timespec)
  657. {
  658. if (!lockp)
  659. return EINVAL;
  660. auto rc = rwlock_wrlock_maybe_timed(lockp, timespec);
  661. if (rc == -1) // "ok"
  662. return 0;
  663. if (rc == -2) // "timed out"
  664. return 1;
  665. return rc;
  666. }
  667. int pthread_rwlock_tryrdlock(pthread_rwlock_t* lockp)
  668. {
  669. if (!lockp)
  670. return EINVAL;
  671. return rwlock_rdlock_maybe_timed(reinterpret_cast<u32*>(lockp), nullptr, true, EBUSY, 0);
  672. }
  673. int pthread_rwlock_trywrlock(pthread_rwlock_t* lockp)
  674. {
  675. if (!lockp)
  676. return EINVAL;
  677. return rwlock_wrlock_maybe_timed(lockp, nullptr, true, EBUSY, 0);
  678. }
  679. int pthread_rwlock_unlock(pthread_rwlock_t* lockval_p)
  680. {
  681. if (!lockval_p)
  682. return EINVAL;
  683. // This is a weird API, we don't really know whether we're unlocking write or read...
  684. auto lockp = reinterpret_cast<u32*>(lockval_p);
  685. auto current = AK::atomic_load(lockp, AK::MemoryOrder::memory_order_relaxed);
  686. if (current & writer_locked_mask) {
  687. // If this lock is locked for writing, its owner better be us!
  688. auto owner_id = AK::atomic_load(reinterpret_cast<i32*>(lockval_p) + 1);
  689. auto my_id = pthread_self();
  690. if (owner_id != my_id)
  691. return EINVAL; // you don't own this lock, silly.
  692. // Now just unlock it.
  693. auto desired = current & ~(writer_locked_mask | writer_intent_mask);
  694. AK::atomic_store(lockp, desired, AK::MemoryOrder::memory_order_release);
  695. // Then wake both readers and writers, if any.
  696. auto rc = futex(lockp, FUTEX_WAKE_BITSET, current, nullptr, nullptr, (current & writer_wake_mask) | reader_wake_mask);
  697. if (rc < 0)
  698. return errno;
  699. return 0;
  700. }
  701. for (;;) {
  702. auto count = (u16)current;
  703. if (!count) {
  704. // Are you crazy? this isn't even locked!
  705. return EINVAL;
  706. }
  707. --count;
  708. auto desired = (current << 16) | count;
  709. auto did_exchange = AK::atomic_compare_exchange_strong(lockp, current, desired, AK::MemoryOrder::memory_order_release);
  710. if (!did_exchange)
  711. continue; // tough luck, try again.
  712. }
  713. // Finally, unlocked at last!
  714. return 0;
  715. }
  716. int pthread_rwlock_wrlock(pthread_rwlock_t* lockp)
  717. {
  718. if (!lockp)
  719. return EINVAL;
  720. return rwlock_wrlock_maybe_timed(lockp, nullptr, false, 0, 0);
  721. }
  722. int pthread_rwlockattr_destroy(pthread_rwlockattr_t*)
  723. {
  724. return 0;
  725. }
  726. int pthread_rwlockattr_getpshared(const pthread_rwlockattr_t* __restrict, int* __restrict)
  727. {
  728. VERIFY_NOT_REACHED();
  729. }
  730. int pthread_rwlockattr_init(pthread_rwlockattr_t*)
  731. {
  732. VERIFY_NOT_REACHED();
  733. }
  734. int pthread_rwlockattr_setpshared(pthread_rwlockattr_t*, int)
  735. {
  736. VERIFY_NOT_REACHED();
  737. }
  738. int pthread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void))
  739. {
  740. if (prepare)
  741. __pthread_fork_atfork_register_prepare(prepare);
  742. if (parent)
  743. __pthread_fork_atfork_register_parent(parent);
  744. if (child)
  745. __pthread_fork_atfork_register_child(child);
  746. return 0;
  747. }
  748. } // extern "C"