pthread.c 29 KB

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