pthread.cpp 30 KB

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