pthread.cpp 27 KB

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