pthread.cpp 26 KB

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