pthread.cpp 27 KB

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