pthread.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  1. /* Linuxthreads - a simple clone()-based implementation of Posix */
  2. /* threads for Linux. */
  3. /* Copyright (C) 1996 Xavier Leroy (Xavier.Leroy@inria.fr) */
  4. /* */
  5. /* This program is free software; you can redistribute it and/or */
  6. /* modify it under the terms of the GNU Library General Public License */
  7. /* as published by the Free Software Foundation; either version 2 */
  8. /* of the License, or (at your option) any later version. */
  9. /* */
  10. /* This program is distributed in the hope that it will be useful, */
  11. /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
  12. /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
  13. /* GNU Library General Public License for more details. */
  14. /* Thread creation, initialization, and basic low-level routines */
  15. #define __FORCE_GLIBC
  16. #include <features.h>
  17. #include <errno.h>
  18. #include <netdb.h> /* for h_errno */
  19. #include <stddef.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <unistd.h>
  24. #include <fcntl.h>
  25. #include <sys/wait.h>
  26. #include <sys/resource.h>
  27. #include "pthread.h"
  28. #include "internals.h"
  29. #include "spinlock.h"
  30. #include "restart.h"
  31. #include "debug.h" /* added to linuxthreads -StS */
  32. /* mods for uClibc: getpwd and getpagesize are the syscalls */
  33. #define __getpid getpid
  34. #define __getpagesize getpagesize
  35. /* mods for uClibc: __libc_sigaction is not in any standard headers */
  36. #include <signal.h>
  37. extern int __libc_sigaction (int sig, const struct sigaction *act, struct sigaction *oact);
  38. /* These variables are used by the setup code. */
  39. extern int _errno;
  40. extern int _h_errno;
  41. /* Descriptor of the initial thread */
  42. struct _pthread_descr_struct __pthread_initial_thread = {
  43. &__pthread_initial_thread, /* pthread_descr p_nextlive */
  44. &__pthread_initial_thread, /* pthread_descr p_prevlive */
  45. NULL, /* pthread_descr p_nextwaiting */
  46. NULL, /* pthread_descr p_nextlock */
  47. PTHREAD_THREADS_MAX, /* pthread_t p_tid */
  48. 0, /* int p_pid */
  49. 0, /* int p_priority */
  50. &__pthread_handles[0].h_lock, /* struct _pthread_fastlock * p_lock */
  51. 0, /* int p_signal */
  52. NULL, /* sigjmp_buf * p_signal_buf */
  53. NULL, /* sigjmp_buf * p_cancel_buf */
  54. 0, /* char p_terminated */
  55. 0, /* char p_detached */
  56. 0, /* char p_exited */
  57. NULL, /* void * p_retval */
  58. 0, /* int p_retval */
  59. NULL, /* pthread_descr p_joining */
  60. NULL, /* struct _pthread_cleanup_buffer * p_cleanup */
  61. 0, /* char p_cancelstate */
  62. 0, /* char p_canceltype */
  63. 0, /* char p_canceled */
  64. &_errno, /* int *p_errnop */
  65. 0, /* int p_errno */
  66. &_h_errno, /* int *p_h_errnop */
  67. 0, /* int p_h_errno */
  68. NULL, /* char * p_in_sighandler */
  69. 0, /* char p_sigwaiting */
  70. PTHREAD_START_ARGS_INITIALIZER, /* struct pthread_start_args p_start_args */
  71. {NULL}, /* void ** p_specific[PTHREAD_KEY_1STLEVEL_SIZE] */
  72. {NULL}, /* void * p_libc_specific[_LIBC_TSD_KEY_N] */
  73. 0, /* int p_userstack */
  74. NULL, /* void * p_guardaddr */
  75. 0, /* size_t p_guardsize */
  76. &__pthread_initial_thread, /* pthread_descr p_self */
  77. 0, /* Always index 0 */
  78. 0, /* int p_report_events */
  79. {{{0, }}, 0, NULL}, /* td_eventbuf_t p_eventbuf */
  80. ATOMIC_INITIALIZER, /* struct pthread_atomic p_resume_count */
  81. 0, /* char p_woken_by_cancel */
  82. NULL, /* struct pthread_extricate_if *p_extricate */
  83. NULL, /* pthread_readlock_info *p_readlock_list; */
  84. NULL, /* pthread_readlock_info *p_readlock_free; */
  85. 0 /* int p_untracked_readlock_count; */
  86. };
  87. /* Descriptor of the manager thread; none of this is used but the error
  88. variables, the p_pid and p_priority fields,
  89. and the address for identification. */
  90. struct _pthread_descr_struct __pthread_manager_thread = {
  91. NULL, /* pthread_descr p_nextlive */
  92. NULL, /* pthread_descr p_prevlive */
  93. NULL, /* pthread_descr p_nextwaiting */
  94. NULL, /* pthread_descr p_nextlock */
  95. 0, /* int p_tid */
  96. 0, /* int p_pid */
  97. 0, /* int p_priority */
  98. &__pthread_handles[1].h_lock, /* struct _pthread_fastlock * p_lock */
  99. 0, /* int p_signal */
  100. NULL, /* sigjmp_buf * p_signal_buf */
  101. NULL, /* sigjmp_buf * p_cancel_buf */
  102. 0, /* char p_terminated */
  103. 0, /* char p_detached */
  104. 0, /* char p_exited */
  105. NULL, /* void * p_retval */
  106. 0, /* int p_retval */
  107. NULL, /* pthread_descr p_joining */
  108. NULL, /* struct _pthread_cleanup_buffer * p_cleanup */
  109. 0, /* char p_cancelstate */
  110. 0, /* char p_canceltype */
  111. 0, /* char p_canceled */
  112. &__pthread_manager_thread.p_errno, /* int *p_errnop */
  113. 0, /* int p_errno */
  114. NULL, /* int *p_h_errnop */
  115. 0, /* int p_h_errno */
  116. NULL, /* char * p_in_sighandler */
  117. 0, /* char p_sigwaiting */
  118. PTHREAD_START_ARGS_INITIALIZER, /* struct pthread_start_args p_start_args */
  119. {NULL}, /* void ** p_specific[PTHREAD_KEY_1STLEVEL_SIZE] */
  120. {NULL}, /* void * p_libc_specific[_LIBC_TSD_KEY_N] */
  121. 0, /* int p_userstack */
  122. NULL, /* void * p_guardaddr */
  123. 0, /* size_t p_guardsize */
  124. &__pthread_manager_thread, /* pthread_descr p_self */
  125. 1, /* Always index 1 */
  126. 0, /* int p_report_events */
  127. {{{0, }}, 0, NULL}, /* td_eventbuf_t p_eventbuf */
  128. ATOMIC_INITIALIZER, /* struct pthread_atomic p_resume_count */
  129. 0, /* char p_woken_by_cancel */
  130. NULL, /* struct pthread_extricate_if *p_extricate */
  131. NULL, /* pthread_readlock_info *p_readlock_list; */
  132. NULL, /* pthread_readlock_info *p_readlock_free; */
  133. 0 /* int p_untracked_readlock_count; */
  134. };
  135. /* Pointer to the main thread (the father of the thread manager thread) */
  136. /* Originally, this is the initial thread, but this changes after fork() */
  137. pthread_descr __pthread_main_thread = &__pthread_initial_thread;
  138. /* Limit between the stack of the initial thread (above) and the
  139. stacks of other threads (below). Aligned on a STACK_SIZE boundary. */
  140. char *__pthread_initial_thread_bos = NULL;
  141. /* For non-MMU systems also remember to stack top of the initial thread.
  142. * This is adapted when other stacks are malloc'ed since we don't know
  143. * the bounds a-priori. -StS */
  144. #ifndef __UCLIBC_HAS_MMU__
  145. char *__pthread_initial_thread_tos = NULL;
  146. #endif /* __UCLIBC_HAS_MMU__ */
  147. /* File descriptor for sending requests to the thread manager. */
  148. /* Initially -1, meaning that the thread manager is not running. */
  149. int __pthread_manager_request = -1;
  150. /* Other end of the pipe for sending requests to the thread manager. */
  151. int __pthread_manager_reader;
  152. /* Limits of the thread manager stack */
  153. char *__pthread_manager_thread_bos = NULL;
  154. char *__pthread_manager_thread_tos = NULL;
  155. /* For process-wide exit() */
  156. int __pthread_exit_requested = 0;
  157. int __pthread_exit_code = 0;
  158. /* Pointers that select new or old suspend/resume functions
  159. based on availability of rt signals. */
  160. void (*__pthread_restart)(pthread_descr) = __pthread_restart_old;
  161. void (*__pthread_suspend)(pthread_descr) = __pthread_suspend_old;
  162. /* Communicate relevant LinuxThreads constants to gdb */
  163. const int __pthread_threads_max = PTHREAD_THREADS_MAX;
  164. const int __pthread_sizeof_handle = sizeof(struct pthread_handle_struct);
  165. const int __pthread_offsetof_descr = offsetof(struct pthread_handle_struct,
  166. h_descr);
  167. const int __pthread_offsetof_pid = offsetof(struct _pthread_descr_struct,
  168. p_pid);
  169. /* Forward declarations */
  170. static void pthread_exit_process(int retcode, void *arg);
  171. #ifndef __i386__
  172. static void pthread_handle_sigcancel(int sig);
  173. static void pthread_handle_sigrestart(int sig);
  174. #else
  175. static void pthread_handle_sigcancel(int sig, struct sigcontext ctx);
  176. static void pthread_handle_sigrestart(int sig, struct sigcontext ctx);
  177. #endif
  178. static void pthread_handle_sigdebug(int sig);
  179. /* Signal numbers used for the communication.
  180. In these variables we keep track of the used variables. If the
  181. platform does not support any real-time signals we will define the
  182. values to some unreasonable value which will signal failing of all
  183. the functions below. */
  184. #ifndef __SIGRTMIN
  185. static int current_rtmin = -1;
  186. static int current_rtmax = -1;
  187. int __pthread_sig_restart = SIGUSR1;
  188. int __pthread_sig_cancel = SIGUSR2;
  189. int __pthread_sig_debug = 0;
  190. #else
  191. static int current_rtmin;
  192. static int current_rtmax;
  193. #if __SIGRTMAX - __SIGRTMIN >= 3
  194. int __pthread_sig_restart = __SIGRTMIN;
  195. int __pthread_sig_cancel = __SIGRTMIN + 1;
  196. int __pthread_sig_debug = __SIGRTMIN + 2;
  197. #else
  198. int __pthread_sig_restart = SIGUSR1;
  199. int __pthread_sig_cancel = SIGUSR2;
  200. int __pthread_sig_debug = 0;
  201. #endif
  202. static int rtsigs_initialized;
  203. #include "testrtsig.h"
  204. static void
  205. init_rtsigs (void)
  206. {
  207. if (!kernel_has_rtsig ())
  208. {
  209. current_rtmin = -1;
  210. current_rtmax = -1;
  211. #if __SIGRTMAX - __SIGRTMIN >= 3
  212. __pthread_sig_restart = SIGUSR1;
  213. __pthread_sig_cancel = SIGUSR2;
  214. __pthread_sig_debug = 0;
  215. #endif
  216. PDEBUG("no rt-sigs, sig_restart=%d, sig_cancel=%d.\n", __pthread_sig_restart, __pthread_sig_cancel );
  217. __pthread_init_condvar(0);
  218. }
  219. else
  220. {
  221. #if __SIGRTMAX - __SIGRTMIN >= 3
  222. current_rtmin = __SIGRTMIN + 3;
  223. __pthread_restart = __pthread_restart_new;
  224. __pthread_suspend = __pthread_wait_for_restart_signal;
  225. __pthread_init_condvar(1);
  226. #else
  227. current_rtmin = __SIGRTMIN;
  228. __pthread_init_condvar(0);
  229. #endif
  230. current_rtmax = __SIGRTMAX;
  231. PDEBUG("have rt-sigs, rtmin = %d, rtmax = %d.\n", current_rtmin, current_rtmax);
  232. }
  233. rtsigs_initialized = 1;
  234. }
  235. #endif
  236. /* Return number of available real-time signal with highest priority. */
  237. int
  238. __libc_current_sigrtmin (void)
  239. {
  240. #ifdef __SIGRTMIN
  241. if (!rtsigs_initialized)
  242. init_rtsigs ();
  243. #endif
  244. return current_rtmin;
  245. }
  246. /* Return number of available real-time signal with lowest priority. */
  247. int
  248. __libc_current_sigrtmax (void)
  249. {
  250. #ifdef __SIGRTMIN
  251. if (!rtsigs_initialized)
  252. init_rtsigs ();
  253. #endif
  254. return current_rtmax;
  255. }
  256. /* Allocate real-time signal with highest/lowest available
  257. priority. Please note that we don't use a lock since we assume
  258. this function to be called at program start. */
  259. int
  260. __libc_allocate_rtsig (int high)
  261. {
  262. #ifndef __SIGRTMIN
  263. return -1;
  264. #else
  265. if (!rtsigs_initialized)
  266. init_rtsigs ();
  267. if (current_rtmin == -1 || current_rtmin > current_rtmax)
  268. /* We don't have anymore signal available. */
  269. return -1;
  270. return high ? current_rtmin++ : current_rtmax--;
  271. #endif
  272. }
  273. /* Initialize the pthread library.
  274. Initialization is split in two functions:
  275. - a constructor function that blocks the __pthread_sig_restart signal
  276. (must do this very early, since the program could capture the signal
  277. mask with e.g. sigsetjmp before creating the first thread);
  278. - a regular function called from pthread_create when needed. */
  279. static void pthread_initialize(void) __attribute__((constructor));
  280. static void pthread_initialize(void)
  281. {
  282. struct sigaction sa;
  283. sigset_t mask;
  284. struct rlimit limit;
  285. int max_stack;
  286. /* If already done (e.g. by a constructor called earlier!), bail out */
  287. if (__pthread_initial_thread_bos != NULL) return;
  288. #ifdef TEST_FOR_COMPARE_AND_SWAP
  289. /* Test if compare-and-swap is available */
  290. __pthread_has_cas = compare_and_swap_is_available();
  291. #endif
  292. /* For the initial stack, reserve at least STACK_SIZE bytes of stack
  293. below the current stack address, and align that on a
  294. STACK_SIZE boundary. */
  295. __pthread_initial_thread_bos =
  296. (char *)(((long)CURRENT_STACK_FRAME - 2 * STACK_SIZE) & ~(STACK_SIZE - 1));
  297. /* Update the descriptor for the initial thread. */
  298. __pthread_initial_thread.p_pid = __getpid();
  299. /* If we have special thread_self processing, initialize that for the
  300. main thread now. */
  301. #ifdef INIT_THREAD_SELF
  302. INIT_THREAD_SELF(&__pthread_initial_thread, 0);
  303. #endif
  304. /* The errno/h_errno variable of the main thread are the global ones. */
  305. __pthread_initial_thread.p_errnop = &_errno;
  306. __pthread_initial_thread.p_h_errnop = &_h_errno;
  307. /* Play with the stack size limit to make sure that no stack ever grows
  308. beyond STACK_SIZE minus two pages (one page for the thread descriptor
  309. immediately beyond, and one page to act as a guard page). */
  310. #ifdef __UCLIBC_HAS_MMU__
  311. /* We cannot allocate a huge chunk of memory to mmap all thread stacks later
  312. * on a non-MMU system. Thus, we don't need the rlimit either. -StS */
  313. getrlimit(RLIMIT_STACK, &limit);
  314. max_stack = STACK_SIZE - 2 * __getpagesize();
  315. if (limit.rlim_cur > max_stack) {
  316. limit.rlim_cur = max_stack;
  317. setrlimit(RLIMIT_STACK, &limit);
  318. }
  319. #else
  320. /* For non-MMU assume __pthread_initial_thread_tos at upper page boundary, and
  321. * __pthread_initial_thread_bos at address 0. These bounds are refined as we
  322. * malloc other stack frames such that they don't overlap. -StS
  323. */
  324. __pthread_initial_thread_tos =
  325. (char *)(((long)CURRENT_STACK_FRAME + __getpagesize()) & ~(__getpagesize() - 1));
  326. __pthread_initial_thread_bos = (char *) 1; /* set it non-zero so we know we have been here */
  327. PDEBUG("initial thread stack bounds: bos=%p, tos=%p\n",
  328. __pthread_initial_thread_bos, __pthread_initial_thread_tos);
  329. #endif /* __UCLIBC_HAS_MMU__ */
  330. #ifdef __SIGRTMIN
  331. /* Initialize real-time signals. */
  332. init_rtsigs ();
  333. #endif
  334. /* Setup signal handlers for the initial thread.
  335. Since signal handlers are shared between threads, these settings
  336. will be inherited by all other threads. */
  337. #ifndef __i386__
  338. sa.sa_handler = pthread_handle_sigrestart;
  339. #else
  340. sa.sa_handler = (__sighandler_t) pthread_handle_sigrestart;
  341. #endif
  342. sigemptyset(&sa.sa_mask);
  343. sa.sa_flags = 0;
  344. __libc_sigaction(__pthread_sig_restart, &sa, NULL);
  345. #ifndef __i386__
  346. sa.sa_handler = pthread_handle_sigcancel;
  347. #else
  348. sa.sa_handler = (__sighandler_t) pthread_handle_sigcancel;
  349. #endif
  350. sa.sa_flags = 0;
  351. __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
  352. if (__pthread_sig_debug > 0) {
  353. sa.sa_handler = pthread_handle_sigdebug;
  354. sigemptyset(&sa.sa_mask);
  355. sa.sa_flags = 0;
  356. __libc_sigaction(__pthread_sig_debug, &sa, NULL);
  357. }
  358. /* Initially, block __pthread_sig_restart. Will be unblocked on demand. */
  359. sigemptyset(&mask);
  360. sigaddset(&mask, __pthread_sig_restart);
  361. PDEBUG("block mask = %x\n", mask);
  362. sigprocmask(SIG_BLOCK, &mask, NULL);
  363. /* Register an exit function to kill all other threads. */
  364. /* Do it early so that user-registered atexit functions are called
  365. before pthread_exit_process. */
  366. on_exit(pthread_exit_process, NULL);
  367. }
  368. void __pthread_initialize(void)
  369. {
  370. pthread_initialize();
  371. }
  372. int __pthread_initialize_manager(void)
  373. {
  374. int manager_pipe[2];
  375. int pid;
  376. struct pthread_request request;
  377. /* If basic initialization not done yet (e.g. we're called from a
  378. constructor run before our constructor), do it now */
  379. if (__pthread_initial_thread_bos == NULL) pthread_initialize();
  380. /* Setup stack for thread manager */
  381. __pthread_manager_thread_bos = malloc(THREAD_MANAGER_STACK_SIZE);
  382. if (__pthread_manager_thread_bos == NULL) return -1;
  383. __pthread_manager_thread_tos =
  384. __pthread_manager_thread_bos + THREAD_MANAGER_STACK_SIZE;
  385. /* On non-MMU systems we make sure that the initial thread bounds don't overlap
  386. * with the manager stack frame */
  387. NOMMU_INITIAL_THREAD_BOUNDS(__pthread_manager_thread_tos,__pthread_manager_thread_bos);
  388. PDEBUG("manager stack: size=%d, bos=%p, tos=%p\n", THREAD_MANAGER_STACK_SIZE,
  389. __pthread_manager_thread_bos, __pthread_manager_thread_tos);
  390. PDEBUG("initial stack: estimate bos=%p, tos=%p\n",
  391. __pthread_initial_thread_bos, __pthread_initial_thread_tos);
  392. /* Setup pipe to communicate with thread manager */
  393. if (pipe(manager_pipe) == -1) {
  394. free(__pthread_manager_thread_bos);
  395. return -1;
  396. }
  397. /* Start the thread manager */
  398. pid = 0;
  399. if (__pthread_initial_thread.p_report_events)
  400. {
  401. /* It's a bit more complicated. We have to report the creation of
  402. the manager thread. */
  403. int idx = __td_eventword (TD_CREATE);
  404. uint32_t mask = __td_eventmask (TD_CREATE);
  405. if ((mask & (__pthread_threads_events.event_bits[idx]
  406. | __pthread_initial_thread.p_eventbuf.eventmask.event_bits[idx]))
  407. != 0)
  408. {
  409. pid = clone(__pthread_manager_event,
  410. (void **) __pthread_manager_thread_tos,
  411. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
  412. (void *)(long)manager_pipe[0]);
  413. if (pid != -1)
  414. {
  415. /* Now fill in the information about the new thread in
  416. the newly created thread's data structure. We cannot let
  417. the new thread do this since we don't know whether it was
  418. already scheduled when we send the event. */
  419. __pthread_manager_thread.p_eventbuf.eventdata =
  420. &__pthread_manager_thread;
  421. __pthread_manager_thread.p_eventbuf.eventnum = TD_CREATE;
  422. __pthread_last_event = &__pthread_manager_thread;
  423. __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
  424. __pthread_manager_thread.p_pid = pid;
  425. /* Now call the function which signals the event. */
  426. __linuxthreads_create_event ();
  427. /* Now restart the thread. */
  428. __pthread_unlock(__pthread_manager_thread.p_lock);
  429. }
  430. }
  431. }
  432. if (pid == 0) {
  433. pid = clone(__pthread_manager, (void **) __pthread_manager_thread_tos,
  434. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
  435. (void *)(long)manager_pipe[0]);
  436. }
  437. if (pid == -1) {
  438. free(__pthread_manager_thread_bos);
  439. __libc_close(manager_pipe[0]);
  440. __libc_close(manager_pipe[1]);
  441. return -1;
  442. }
  443. __pthread_manager_request = manager_pipe[1]; /* writing end */
  444. __pthread_manager_reader = manager_pipe[0]; /* reading end */
  445. __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
  446. __pthread_manager_thread.p_pid = pid;
  447. /* Make gdb aware of new thread manager */
  448. if (__pthread_threads_debug && __pthread_sig_debug > 0)
  449. {
  450. raise(__pthread_sig_debug);
  451. /* We suspend ourself and gdb will wake us up when it is
  452. ready to handle us. */
  453. __pthread_wait_for_restart_signal(thread_self());
  454. }
  455. /* Synchronize debugging of the thread manager */
  456. PDEBUG("send REQ_DEBUG to manager thread\n");
  457. request.req_kind = REQ_DEBUG;
  458. __libc_write(__pthread_manager_request, (char *) &request, sizeof(request));
  459. return 0;
  460. }
  461. /* Thread creation */
  462. int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
  463. void * (*start_routine)(void *), void *arg)
  464. {
  465. pthread_descr self = thread_self();
  466. struct pthread_request request;
  467. if (__pthread_manager_request < 0) {
  468. if (__pthread_initialize_manager() < 0) return EAGAIN;
  469. }
  470. request.req_thread = self;
  471. request.req_kind = REQ_CREATE;
  472. request.req_args.create.attr = attr;
  473. request.req_args.create.fn = start_routine;
  474. request.req_args.create.arg = arg;
  475. sigprocmask(SIG_SETMASK, (const sigset_t *) NULL,
  476. &request.req_args.create.mask);
  477. PDEBUG("write REQ_CREATE to manager thread\n");
  478. __libc_write(__pthread_manager_request, (char *) &request, sizeof(request));
  479. PDEBUG("before suspend(self)\n");
  480. suspend(self);
  481. PDEBUG("after suspend(self)\n");
  482. if (THREAD_GETMEM(self, p_retcode) == 0)
  483. *thread = (pthread_t) THREAD_GETMEM(self, p_retval);
  484. return THREAD_GETMEM(self, p_retcode);
  485. }
  486. /* Simple operations on thread identifiers */
  487. pthread_t pthread_self(void)
  488. {
  489. pthread_descr self = thread_self();
  490. return THREAD_GETMEM(self, p_tid);
  491. }
  492. int pthread_equal(pthread_t thread1, pthread_t thread2)
  493. {
  494. return thread1 == thread2;
  495. }
  496. /* Helper function for thread_self in the case of user-provided stacks */
  497. #ifndef THREAD_SELF
  498. pthread_descr __pthread_find_self()
  499. {
  500. char * sp = CURRENT_STACK_FRAME;
  501. pthread_handle h;
  502. /* __pthread_handles[0] is the initial thread, __pthread_handles[1] is
  503. the manager threads handled specially in thread_self(), so start at 2 */
  504. h = __pthread_handles + 2;
  505. while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom)) h++;
  506. #ifdef DEBUG_PT
  507. if (h->h_descr == NULL) {
  508. printf("*** "__FUNCTION__" ERROR descriptor is NULL!!!!! ***\n\n");
  509. _exit(1);
  510. }
  511. #endif
  512. return h->h_descr;
  513. }
  514. #endif
  515. /* Thread scheduling */
  516. int pthread_setschedparam(pthread_t thread, int policy,
  517. const struct sched_param *param)
  518. {
  519. pthread_handle handle = thread_handle(thread);
  520. pthread_descr th;
  521. __pthread_lock(&handle->h_lock, NULL);
  522. if (invalid_handle(handle, thread)) {
  523. __pthread_unlock(&handle->h_lock);
  524. return ESRCH;
  525. }
  526. th = handle->h_descr;
  527. if (sched_setscheduler(th->p_pid, policy, param) == -1) {
  528. __pthread_unlock(&handle->h_lock);
  529. return errno;
  530. }
  531. th->p_priority = policy == SCHED_OTHER ? 0 : param->sched_priority;
  532. __pthread_unlock(&handle->h_lock);
  533. if (__pthread_manager_request >= 0)
  534. __pthread_manager_adjust_prio(th->p_priority);
  535. return 0;
  536. }
  537. int pthread_getschedparam(pthread_t thread, int *policy,
  538. struct sched_param *param)
  539. {
  540. pthread_handle handle = thread_handle(thread);
  541. int pid, pol;
  542. __pthread_lock(&handle->h_lock, NULL);
  543. if (invalid_handle(handle, thread)) {
  544. __pthread_unlock(&handle->h_lock);
  545. return ESRCH;
  546. }
  547. pid = handle->h_descr->p_pid;
  548. __pthread_unlock(&handle->h_lock);
  549. pol = sched_getscheduler(pid);
  550. if (pol == -1) return errno;
  551. if (sched_getparam(pid, param) == -1) return errno;
  552. *policy = pol;
  553. return 0;
  554. }
  555. /* Process-wide exit() request */
  556. static void pthread_exit_process(int retcode, void *arg)
  557. {
  558. struct pthread_request request;
  559. pthread_descr self = thread_self();
  560. if (__pthread_manager_request >= 0) {
  561. request.req_thread = self;
  562. request.req_kind = REQ_PROCESS_EXIT;
  563. request.req_args.exit.code = retcode;
  564. __libc_write(__pthread_manager_request,
  565. (char *) &request, sizeof(request));
  566. suspend(self);
  567. /* Main thread should accumulate times for thread manager and its
  568. children, so that timings for main thread account for all threads. */
  569. if (self == __pthread_main_thread)
  570. waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
  571. }
  572. }
  573. /* The handler for the RESTART signal just records the signal received
  574. in the thread descriptor, and optionally performs a siglongjmp
  575. (for pthread_cond_timedwait). */
  576. #ifndef __i386__
  577. static void pthread_handle_sigrestart(int sig)
  578. {
  579. pthread_descr self = thread_self();
  580. PDEBUG("got called in non-i386 mode for %u\n", self);
  581. #else
  582. static void pthread_handle_sigrestart(int sig, struct sigcontext ctx)
  583. {
  584. pthread_descr self;
  585. asm volatile ("movw %w0,%%gs" : : "r" (ctx.gs));
  586. self = thread_self();
  587. PDEBUG("got called in i386-mode for %u\n", self);
  588. #endif
  589. THREAD_SETMEM(self, p_signal, sig);
  590. if (THREAD_GETMEM(self, p_signal_jmp) != NULL)
  591. siglongjmp(*THREAD_GETMEM(self, p_signal_jmp), 1);
  592. }
  593. /* The handler for the CANCEL signal checks for cancellation
  594. (in asynchronous mode), for process-wide exit and exec requests.
  595. For the thread manager thread, redirect the signal to
  596. __pthread_manager_sighandler. */
  597. #ifndef __i386__
  598. static void pthread_handle_sigcancel(int sig)
  599. {
  600. pthread_descr self = thread_self();
  601. sigjmp_buf * jmpbuf;
  602. #else
  603. static void pthread_handle_sigcancel(int sig, struct sigcontext ctx)
  604. {
  605. pthread_descr self;
  606. sigjmp_buf * jmpbuf;
  607. asm volatile ("movw %w0,%%gs" : : "r" (ctx.gs));
  608. self = thread_self();
  609. #endif
  610. if (self == &__pthread_manager_thread)
  611. {
  612. __pthread_manager_sighandler(sig);
  613. return;
  614. }
  615. if (__pthread_exit_requested) {
  616. /* Main thread should accumulate times for thread manager and its
  617. children, so that timings for main thread account for all threads. */
  618. if (self == __pthread_main_thread)
  619. waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
  620. _exit(__pthread_exit_code);
  621. }
  622. if (THREAD_GETMEM(self, p_canceled)
  623. && THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE) {
  624. if (THREAD_GETMEM(self, p_canceltype) == PTHREAD_CANCEL_ASYNCHRONOUS)
  625. pthread_exit(PTHREAD_CANCELED);
  626. jmpbuf = THREAD_GETMEM(self, p_cancel_jmp);
  627. if (jmpbuf != NULL) {
  628. THREAD_SETMEM(self, p_cancel_jmp, NULL);
  629. siglongjmp(*jmpbuf, 1);
  630. }
  631. }
  632. }
  633. /* Handler for the DEBUG signal.
  634. The debugging strategy is as follows:
  635. On reception of a REQ_DEBUG request (sent by new threads created to
  636. the thread manager under debugging mode), the thread manager throws
  637. __pthread_sig_debug to itself. The debugger (if active) intercepts
  638. this signal, takes into account new threads and continue execution
  639. of the thread manager by propagating the signal because it doesn't
  640. know what it is specifically done for. In the current implementation,
  641. the thread manager simply discards it. */
  642. static void pthread_handle_sigdebug(int sig)
  643. {
  644. /* Nothing */
  645. }
  646. /* Reset the state of the thread machinery after a fork().
  647. Close the pipe used for requests and set the main thread to the forked
  648. thread.
  649. Notice that we can't free the stack segments, as the forked thread
  650. may hold pointers into them. */
  651. void __pthread_reset_main_thread()
  652. {
  653. pthread_descr self = thread_self();
  654. if (__pthread_manager_request != -1) {
  655. /* Free the thread manager stack */
  656. free(__pthread_manager_thread_bos);
  657. __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
  658. /* Close the two ends of the pipe */
  659. __libc_close(__pthread_manager_request);
  660. __libc_close(__pthread_manager_reader);
  661. __pthread_manager_request = __pthread_manager_reader = -1;
  662. }
  663. /* Update the pid of the main thread */
  664. THREAD_SETMEM(self, p_pid, __getpid());
  665. /* Make the forked thread the main thread */
  666. __pthread_main_thread = self;
  667. THREAD_SETMEM(self, p_nextlive, self);
  668. THREAD_SETMEM(self, p_prevlive, self);
  669. /* Now this thread modifies the global variables. */
  670. THREAD_SETMEM(self, p_errnop, &_errno);
  671. THREAD_SETMEM(self, p_h_errnop, &_h_errno);
  672. }
  673. /* Process-wide exec() request */
  674. void __pthread_kill_other_threads_np(void)
  675. {
  676. struct sigaction sa;
  677. /* Terminate all other threads and thread manager */
  678. pthread_exit_process(0, NULL);
  679. /* Make current thread the main thread in case the calling thread
  680. changes its mind, does not exec(), and creates new threads instead. */
  681. __pthread_reset_main_thread();
  682. /* Reset the signal handlers behaviour for the signals the
  683. implementation uses since this would be passed to the new
  684. process. */
  685. sigemptyset(&sa.sa_mask);
  686. sa.sa_flags = 0;
  687. sa.sa_handler = SIG_DFL;
  688. __libc_sigaction(__pthread_sig_restart, &sa, NULL);
  689. __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
  690. if (__pthread_sig_debug > 0)
  691. __libc_sigaction(__pthread_sig_debug, &sa, NULL);
  692. }
  693. weak_alias (__pthread_kill_other_threads_np, pthread_kill_other_threads_np)
  694. /* Concurrency symbol level. */
  695. static int current_level;
  696. int __pthread_setconcurrency(int level)
  697. {
  698. /* We don't do anything unless we have found a useful interpretation. */
  699. current_level = level;
  700. return 0;
  701. }
  702. weak_alias (__pthread_setconcurrency, pthread_setconcurrency)
  703. int __pthread_getconcurrency(void)
  704. {
  705. return current_level;
  706. }
  707. weak_alias (__pthread_getconcurrency, pthread_getconcurrency)
  708. void __pthread_set_own_extricate_if(pthread_descr self, pthread_extricate_if *peif)
  709. {
  710. __pthread_lock(self->p_lock, self);
  711. THREAD_SETMEM(self, p_extricate, peif);
  712. __pthread_unlock(self->p_lock);
  713. }
  714. /* Primitives for controlling thread execution */
  715. void __pthread_wait_for_restart_signal(pthread_descr self)
  716. {
  717. sigset_t mask;
  718. sigprocmask(SIG_SETMASK, NULL, &mask); /* Get current signal mask */
  719. sigdelset(&mask, __pthread_sig_restart); /* Unblock the restart signal */
  720. do {
  721. self->p_signal = 0;
  722. PDEBUG("temporary block mask = %x\n", mask);
  723. sigsuspend(&mask); /* Wait for signal */
  724. PDEBUG(" *** after sigsuspend *** \n");
  725. } while (self->p_signal !=__pthread_sig_restart );
  726. }
  727. /* The _old variants are for 2.0 and early 2.1 kernels which don't have RT signals.
  728. On these kernels, we use SIGUSR1 and SIGUSR2 for restart and cancellation.
  729. Since the restart signal does not queue, we use an atomic counter to create
  730. queuing semantics. This is needed to resolve a rare race condition in
  731. pthread_cond_timedwait_relative. */
  732. void __pthread_restart_old(pthread_descr th)
  733. {
  734. if (atomic_increment(&th->p_resume_count) == -1)
  735. kill(th->p_pid, __pthread_sig_restart);
  736. }
  737. void __pthread_suspend_old(pthread_descr self)
  738. {
  739. if (atomic_decrement(&self->p_resume_count) <= 0)
  740. __pthread_wait_for_restart_signal(self);
  741. }
  742. void __pthread_restart_new(pthread_descr th)
  743. {
  744. kill(th->p_pid, __pthread_sig_restart);
  745. }
  746. /* There is no __pthread_suspend_new because it would just
  747. be a wasteful wrapper for __pthread_wait_for_restart_signal */
  748. /* Debugging aid */
  749. #ifdef DEBUG_PT
  750. #include <stdarg.h>
  751. void __pthread_message(char * fmt, ...)
  752. {
  753. char buffer[1024];
  754. va_list args;
  755. sprintf(buffer, "%05d : ", __getpid());
  756. va_start(args, fmt);
  757. vsnprintf(buffer + 8, sizeof(buffer) - 8, fmt, args);
  758. va_end(args);
  759. __libc_write(2, buffer, strlen(buffer));
  760. }
  761. #endif
  762. #ifndef PIC
  763. /* We need a hook to force the cancelation wrappers to be linked in when
  764. static libpthread is used. */
  765. extern const int __pthread_provide_wrappers;
  766. static const int *const __pthread_require_wrappers =
  767. &__pthread_provide_wrappers;
  768. #endif