pthread.cpp 28 KB

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