manager.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  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. /* The "thread manager" thread: manages creation and termination of threads */
  15. #include <features.h>
  16. #include <errno.h>
  17. #include <sched.h>
  18. #include <stddef.h>
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <unistd.h>
  23. #include <sys/poll.h> /* for poll */
  24. #include <sys/mman.h> /* for mmap */
  25. #include <sys/param.h>
  26. #include <sys/time.h>
  27. #include <sys/wait.h> /* for waitpid macros */
  28. #include "pthread.h"
  29. #include "internals.h"
  30. #include "spinlock.h"
  31. #include "restart.h"
  32. #include "semaphore.h"
  33. #include "debug.h" /* PDEBUG, added by StS */
  34. /* poll() is not supported in kernel <= 2.0, therefore is __NR_poll is
  35. * not available, we assume an old Linux kernel is in use and we will
  36. * use select() instead. */
  37. #include <sys/syscall.h>
  38. #ifndef __NR_poll
  39. # define USE_SELECT
  40. #endif
  41. libpthread_hidden_proto(waitpid)
  42. libpthread_hidden_proto(raise)
  43. /* Array of active threads. Entry 0 is reserved for the initial thread. */
  44. struct pthread_handle_struct __pthread_handles[PTHREAD_THREADS_MAX] =
  45. { { __LOCK_INITIALIZER, &__pthread_initial_thread, 0},
  46. { __LOCK_INITIALIZER, &__pthread_manager_thread, 0}, /* All NULLs */ };
  47. /* For debugging purposes put the maximum number of threads in a variable. */
  48. const int __linuxthreads_pthread_threads_max = PTHREAD_THREADS_MAX;
  49. /* Indicate whether at least one thread has a user-defined stack (if 1),
  50. or if all threads have stacks supplied by LinuxThreads (if 0). */
  51. int __pthread_nonstandard_stacks;
  52. /* Number of active entries in __pthread_handles (used by gdb) */
  53. volatile int __pthread_handles_num = 2;
  54. /* Whether to use debugger additional actions for thread creation
  55. (set to 1 by gdb) */
  56. volatile int __pthread_threads_debug;
  57. /* Globally enabled events. */
  58. volatile td_thr_events_t __pthread_threads_events;
  59. /* Pointer to thread descriptor with last event. */
  60. volatile pthread_descr __pthread_last_event;
  61. /* Mapping from stack segment to thread descriptor. */
  62. /* Stack segment numbers are also indices into the __pthread_handles array. */
  63. /* Stack segment number 0 is reserved for the initial thread. */
  64. static inline pthread_descr thread_segment(int seg)
  65. {
  66. return (pthread_descr)(THREAD_STACK_START_ADDRESS - (seg - 1) * STACK_SIZE)
  67. - 1;
  68. }
  69. /* Flag set in signal handler to record child termination */
  70. static volatile int terminated_children = 0;
  71. /* Flag set when the initial thread is blocked on pthread_exit waiting
  72. for all other threads to terminate */
  73. static int main_thread_exiting = 0;
  74. /* Counter used to generate unique thread identifier.
  75. Thread identifier is pthread_threads_counter + segment. */
  76. static pthread_t pthread_threads_counter = 0;
  77. /* Forward declarations */
  78. static int pthread_handle_create(pthread_t *thread, const pthread_attr_t *attr,
  79. void * (*start_routine)(void *), void *arg,
  80. sigset_t *mask, int father_pid,
  81. int report_events,
  82. td_thr_events_t *event_maskp);
  83. static void pthread_handle_free(pthread_t th_id);
  84. static void pthread_handle_exit(pthread_descr issuing_thread, int exitcode) attribute_noreturn;
  85. static void pthread_reap_children(void);
  86. static void pthread_kill_all_threads(int sig, int main_thread_also);
  87. /* The server thread managing requests for thread creation and termination */
  88. int attribute_noreturn __pthread_manager(void *arg)
  89. {
  90. int reqfd = (int) (long int) arg;
  91. #ifdef USE_SELECT
  92. struct timeval tv;
  93. fd_set fd;
  94. #else
  95. struct pollfd ufd;
  96. #endif
  97. sigset_t manager_mask;
  98. int n;
  99. struct pthread_request request;
  100. /* If we have special thread_self processing, initialize it. */
  101. #ifdef INIT_THREAD_SELF
  102. INIT_THREAD_SELF(&__pthread_manager_thread, 1);
  103. #endif
  104. /* Set the error variable. */
  105. __pthread_manager_thread.p_errnop = &__pthread_manager_thread.p_errno;
  106. __pthread_manager_thread.p_h_errnop = &__pthread_manager_thread.p_h_errno;
  107. #ifdef __UCLIBC_HAS_XLOCALE__
  108. /* Initialize thread's locale to the global locale. */
  109. __pthread_manager_thread.locale = __global_locale;
  110. #endif /* __UCLIBC_HAS_XLOCALE__ */
  111. /* Block all signals except __pthread_sig_cancel and SIGTRAP */
  112. sigfillset(&manager_mask);
  113. sigdelset(&manager_mask, __pthread_sig_cancel); /* for thread termination */
  114. sigdelset(&manager_mask, SIGTRAP); /* for debugging purposes */
  115. if (__pthread_threads_debug && __pthread_sig_debug > 0)
  116. sigdelset(&manager_mask, __pthread_sig_debug);
  117. sigprocmask(SIG_SETMASK, &manager_mask, NULL);
  118. /* Raise our priority to match that of main thread */
  119. __pthread_manager_adjust_prio(__pthread_main_thread->p_priority);
  120. /* Synchronize debugging of the thread manager */
  121. n = TEMP_FAILURE_RETRY(__libc_read(reqfd, (char *)&request,
  122. sizeof(request)));
  123. ASSERT(n == sizeof(request) && request.req_kind == REQ_DEBUG);
  124. #ifndef USE_SELECT
  125. ufd.fd = reqfd;
  126. ufd.events = POLLIN;
  127. #endif
  128. /* Enter server loop */
  129. while(1) {
  130. #ifdef USE_SELECT
  131. tv.tv_sec = 2;
  132. tv.tv_usec = 0;
  133. FD_ZERO (&fd);
  134. FD_SET (reqfd, &fd);
  135. n = select (reqfd + 1, &fd, NULL, NULL, &tv);
  136. #else
  137. PDEBUG("before poll\n");
  138. n = poll(&ufd, 1, 2000);
  139. PDEBUG("after poll\n");
  140. #endif
  141. /* Check for termination of the main thread */
  142. if (getppid() == 1) {
  143. pthread_kill_all_threads(SIGKILL, 0);
  144. _exit(0);
  145. }
  146. /* Check for dead children */
  147. if (terminated_children) {
  148. terminated_children = 0;
  149. pthread_reap_children();
  150. }
  151. /* Read and execute request */
  152. #ifdef USE_SELECT
  153. if (n == 1)
  154. #else
  155. if (n == 1 && (ufd.revents & POLLIN))
  156. #endif
  157. {
  158. PDEBUG("before __libc_read\n");
  159. n = __libc_read(reqfd, (char *)&request, sizeof(request));
  160. PDEBUG("after __libc_read, n=%d\n", n);
  161. ASSERT(n == sizeof(request));
  162. switch(request.req_kind) {
  163. case REQ_CREATE:
  164. PDEBUG("got REQ_CREATE\n");
  165. request.req_thread->p_retcode =
  166. pthread_handle_create((pthread_t *) &request.req_thread->p_retval,
  167. request.req_args.create.attr,
  168. request.req_args.create.fn,
  169. request.req_args.create.arg,
  170. &request.req_args.create.mask,
  171. request.req_thread->p_pid,
  172. request.req_thread->p_report_events,
  173. &request.req_thread->p_eventbuf.eventmask);
  174. PDEBUG("restarting %d\n", request.req_thread);
  175. restart(request.req_thread);
  176. break;
  177. case REQ_FREE:
  178. PDEBUG("got REQ_FREE\n");
  179. pthread_handle_free(request.req_args.free.thread_id);
  180. break;
  181. case REQ_PROCESS_EXIT:
  182. PDEBUG("got REQ_PROCESS_EXIT from %d, exit code = %d\n",
  183. request.req_thread, request.req_args.exit.code);
  184. pthread_handle_exit(request.req_thread,
  185. request.req_args.exit.code);
  186. break;
  187. case REQ_MAIN_THREAD_EXIT:
  188. PDEBUG("got REQ_MAIN_THREAD_EXIT\n");
  189. main_thread_exiting = 1;
  190. /* Reap children in case all other threads died and the signal handler
  191. went off before we set main_thread_exiting to 1, and therefore did
  192. not do REQ_KICK. */
  193. pthread_reap_children();
  194. if (__pthread_main_thread->p_nextlive == __pthread_main_thread) {
  195. restart(__pthread_main_thread);
  196. /* The main thread will now call exit() which will trigger an
  197. __on_exit handler, which in turn will send REQ_PROCESS_EXIT
  198. to the thread manager. In case you are wondering how the
  199. manager terminates from its loop here. */
  200. }
  201. break;
  202. case REQ_POST:
  203. PDEBUG("got REQ_POST\n");
  204. __new_sem_post(request.req_args.post);
  205. break;
  206. case REQ_DEBUG:
  207. PDEBUG("got REQ_DEBUG\n");
  208. /* Make gdb aware of new thread and gdb will restart the
  209. new thread when it is ready to handle the new thread. */
  210. if (__pthread_threads_debug && __pthread_sig_debug > 0) {
  211. PDEBUG("about to call raise(__pthread_sig_debug)\n");
  212. raise(__pthread_sig_debug);
  213. }
  214. case REQ_KICK:
  215. /* This is just a prod to get the manager to reap some
  216. threads right away, avoiding a potential delay at shutdown. */
  217. break;
  218. }
  219. }
  220. }
  221. }
  222. int __pthread_manager_event(void *arg)
  223. {
  224. /* If we have special thread_self processing, initialize it. */
  225. #ifdef INIT_THREAD_SELF
  226. INIT_THREAD_SELF(&__pthread_manager_thread, 1);
  227. #endif
  228. /* Get the lock the manager will free once all is correctly set up. */
  229. __pthread_lock (THREAD_GETMEM((&__pthread_manager_thread), p_lock), NULL);
  230. /* Free it immediately. */
  231. __pthread_unlock (THREAD_GETMEM((&__pthread_manager_thread), p_lock));
  232. return __pthread_manager(arg);
  233. }
  234. /* Process creation */
  235. static int
  236. attribute_noreturn
  237. pthread_start_thread(void *arg)
  238. {
  239. pthread_descr self = (pthread_descr) arg;
  240. struct pthread_request request;
  241. void * outcome;
  242. /* Initialize special thread_self processing, if any. */
  243. #ifdef INIT_THREAD_SELF
  244. INIT_THREAD_SELF(self, self->p_nr);
  245. #endif
  246. PDEBUG("\n");
  247. /* Make sure our pid field is initialized, just in case we get there
  248. before our father has initialized it. */
  249. THREAD_SETMEM(self, p_pid, getpid());
  250. /* Initial signal mask is that of the creating thread. (Otherwise,
  251. we'd just inherit the mask of the thread manager.) */
  252. sigprocmask(SIG_SETMASK, &self->p_start_args.mask, NULL);
  253. /* Set the scheduling policy and priority for the new thread, if needed */
  254. if (THREAD_GETMEM(self, p_start_args.schedpolicy) >= 0)
  255. /* Explicit scheduling attributes were provided: apply them */
  256. sched_setscheduler(THREAD_GETMEM(self, p_pid),
  257. THREAD_GETMEM(self, p_start_args.schedpolicy),
  258. &self->p_start_args.schedparam);
  259. else if (__pthread_manager_thread.p_priority > 0)
  260. /* Default scheduling required, but thread manager runs in realtime
  261. scheduling: switch new thread to SCHED_OTHER policy */
  262. {
  263. struct sched_param default_params;
  264. default_params.sched_priority = 0;
  265. sched_setscheduler(THREAD_GETMEM(self, p_pid),
  266. SCHED_OTHER, &default_params);
  267. }
  268. /* Make gdb aware of new thread */
  269. if (__pthread_threads_debug && __pthread_sig_debug > 0) {
  270. request.req_thread = self;
  271. request.req_kind = REQ_DEBUG;
  272. TEMP_FAILURE_RETRY(__libc_write(__pthread_manager_request,
  273. (char *) &request, sizeof(request)));
  274. suspend(self);
  275. }
  276. /* Run the thread code */
  277. outcome = self->p_start_args.start_routine(THREAD_GETMEM(self,
  278. p_start_args.arg));
  279. /* Exit with the given return value */
  280. pthread_exit(outcome);
  281. }
  282. static int
  283. attribute_noreturn
  284. pthread_start_thread_event(void *arg)
  285. {
  286. pthread_descr self = (pthread_descr) arg;
  287. #ifdef INIT_THREAD_SELF
  288. INIT_THREAD_SELF(self, self->p_nr);
  289. #endif
  290. /* Make sure our pid field is initialized, just in case we get there
  291. before our father has initialized it. */
  292. THREAD_SETMEM(self, p_pid, getpid());
  293. /* Get the lock the manager will free once all is correctly set up. */
  294. __pthread_lock (THREAD_GETMEM(self, p_lock), NULL);
  295. /* Free it immediately. */
  296. __pthread_unlock (THREAD_GETMEM(self, p_lock));
  297. /* Continue with the real function. */
  298. pthread_start_thread (arg);
  299. }
  300. static int pthread_allocate_stack(const pthread_attr_t *attr,
  301. pthread_descr default_new_thread,
  302. int pagesize,
  303. pthread_descr * out_new_thread,
  304. char ** out_new_thread_bottom,
  305. char ** out_guardaddr,
  306. size_t * out_guardsize)
  307. {
  308. pthread_descr new_thread;
  309. char * new_thread_bottom;
  310. char * guardaddr;
  311. size_t stacksize, guardsize;
  312. if (attr != NULL && attr->__stackaddr_set)
  313. {
  314. /* The user provided a stack. */
  315. new_thread =
  316. (pthread_descr) ((long)(attr->__stackaddr) & -sizeof(void *)) - 1;
  317. new_thread_bottom = (char *) attr->__stackaddr - attr->__stacksize;
  318. guardaddr = NULL;
  319. guardsize = 0;
  320. __pthread_nonstandard_stacks = 1;
  321. }
  322. else
  323. {
  324. #ifdef __ARCH_USE_MMU__
  325. stacksize = STACK_SIZE - pagesize;
  326. if (attr != NULL)
  327. stacksize = MIN (stacksize, roundup(attr->__stacksize, pagesize));
  328. /* Allocate space for stack and thread descriptor at default address */
  329. new_thread = default_new_thread;
  330. new_thread_bottom = (char *) (new_thread + 1) - stacksize;
  331. if (mmap((caddr_t)((char *)(new_thread + 1) - INITIAL_STACK_SIZE),
  332. INITIAL_STACK_SIZE, PROT_READ | PROT_WRITE | PROT_EXEC,
  333. MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED | MAP_GROWSDOWN,
  334. -1, 0) == MAP_FAILED)
  335. /* Bad luck, this segment is already mapped. */
  336. return -1;
  337. /* We manage to get a stack. Now see whether we need a guard
  338. and allocate it if necessary. Notice that the default
  339. attributes (stack_size = STACK_SIZE - pagesize) do not need
  340. a guard page, since the RLIMIT_STACK soft limit prevents stacks
  341. from running into one another. */
  342. if (stacksize == (size_t) (STACK_SIZE - pagesize))
  343. {
  344. /* We don't need a guard page. */
  345. guardaddr = NULL;
  346. guardsize = 0;
  347. }
  348. else
  349. {
  350. /* Put a bad page at the bottom of the stack */
  351. guardsize = attr->__guardsize;
  352. guardaddr = (void *)new_thread_bottom - guardsize;
  353. if (mmap ((caddr_t) guardaddr, guardsize, 0, MAP_FIXED, -1, 0)
  354. == MAP_FAILED)
  355. {
  356. /* We don't make this an error. */
  357. guardaddr = NULL;
  358. guardsize = 0;
  359. }
  360. }
  361. #else
  362. /* We cannot mmap to this huge chunk of stack space when we don't have
  363. * an MMU. Pretend we are using a user provided stack even if there was
  364. * none provided by the user. Thus, we get around the mmap and reservation
  365. * of a huge stack segment. -StS */
  366. stacksize = INITIAL_STACK_SIZE;
  367. /* The user may want to use a non-default stacksize */
  368. if (attr != NULL)
  369. {
  370. stacksize = attr->__stacksize;
  371. }
  372. /* malloc a stack - memory from the bottom up */
  373. if ((new_thread_bottom = malloc(stacksize)) == NULL)
  374. {
  375. /* bad luck, we cannot malloc any more */
  376. return -1 ;
  377. }
  378. PDEBUG("malloced chunk: base=%p, size=0x%04x\n", new_thread_bottom, stacksize);
  379. /* Set up the pointers. new_thread marks the TOP of the stack frame and
  380. * the address of the pthread_descr struct at the same time. Therefore we
  381. * must account for its size and fit it in the malloc()'ed block. The
  382. * value of `new_thread' is then passed to clone() as the stack argument.
  383. *
  384. * ^ +------------------------+
  385. * | | pthread_descr struct |
  386. * | +------------------------+ <- new_thread
  387. * malloc block | | |
  388. * | | thread stack |
  389. * | | |
  390. * v +------------------------+ <- new_thread_bottom
  391. *
  392. * Note: The calculated value of new_thread must be word aligned otherwise
  393. * the kernel chokes on a non-aligned stack frame. Choose the lower
  394. * available word boundary.
  395. */
  396. new_thread = ((pthread_descr) ((int)(new_thread_bottom + stacksize) & -sizeof(void*))) - 1;
  397. guardaddr = NULL;
  398. guardsize = 0;
  399. PDEBUG("thread stack: bos=%p, tos=%p\n", new_thread_bottom, new_thread);
  400. /* check the initial thread stack boundaries so they don't overlap */
  401. NOMMU_INITIAL_THREAD_BOUNDS((char *) new_thread, (char *) new_thread_bottom);
  402. PDEBUG("initial stack: bos=%p, tos=%p\n", __pthread_initial_thread_bos,
  403. __pthread_initial_thread_tos);
  404. /* on non-MMU systems we always have non-standard stack frames */
  405. __pthread_nonstandard_stacks = 1;
  406. #endif /* __ARCH_USE_MMU__ */
  407. }
  408. /* Clear the thread data structure. */
  409. memset (new_thread, '\0', sizeof (*new_thread));
  410. *out_new_thread = new_thread;
  411. *out_new_thread_bottom = new_thread_bottom;
  412. *out_guardaddr = guardaddr;
  413. *out_guardsize = guardsize;
  414. return 0;
  415. }
  416. static int pthread_handle_create(pthread_t *thread, const pthread_attr_t *attr,
  417. void * (*start_routine)(void *), void *arg,
  418. sigset_t * mask, int father_pid,
  419. int report_events,
  420. td_thr_events_t *event_maskp)
  421. {
  422. size_t sseg;
  423. int pid;
  424. pthread_descr new_thread;
  425. char * new_thread_bottom;
  426. pthread_t new_thread_id;
  427. char *guardaddr = NULL;
  428. size_t guardsize = 0;
  429. int pagesize = getpagesize();
  430. int saved_errno = 0;
  431. /* First check whether we have to change the policy and if yes, whether
  432. we can do this. Normally this should be done by examining the
  433. return value of the sched_setscheduler call in pthread_start_thread
  434. but this is hard to implement. FIXME */
  435. if (attr != NULL && attr->__schedpolicy != SCHED_OTHER && geteuid () != 0)
  436. return EPERM;
  437. /* Find a free segment for the thread, and allocate a stack if needed */
  438. for (sseg = 2; ; sseg++)
  439. {
  440. if (sseg >= PTHREAD_THREADS_MAX)
  441. return EAGAIN;
  442. if (__pthread_handles[sseg].h_descr != NULL)
  443. continue;
  444. if (pthread_allocate_stack(attr, thread_segment(sseg), pagesize,
  445. &new_thread, &new_thread_bottom,
  446. &guardaddr, &guardsize) == 0)
  447. break;
  448. #ifndef __ARCH_USE_MMU__
  449. else
  450. /* When there is MMU, mmap () is used to allocate the stack. If one
  451. * segment is already mapped, we should continue to see if we can
  452. * use the next one. However, when there is no MMU, malloc () is used.
  453. * It's waste of CPU cycles to continue to try if it fails. */
  454. return EAGAIN;
  455. #endif
  456. }
  457. __pthread_handles_num++;
  458. /* Allocate new thread identifier */
  459. pthread_threads_counter += PTHREAD_THREADS_MAX;
  460. new_thread_id = sseg + pthread_threads_counter;
  461. /* Initialize the thread descriptor. Elements which have to be
  462. initialized to zero already have this value. */
  463. new_thread->p_tid = new_thread_id;
  464. new_thread->p_lock = &(__pthread_handles[sseg].h_lock);
  465. new_thread->p_cancelstate = PTHREAD_CANCEL_ENABLE;
  466. new_thread->p_canceltype = PTHREAD_CANCEL_DEFERRED;
  467. new_thread->p_errnop = &new_thread->p_errno;
  468. new_thread->p_h_errnop = &new_thread->p_h_errno;
  469. #ifdef __UCLIBC_HAS_XLOCALE__
  470. /* Initialize thread's locale to the global locale. */
  471. new_thread->locale = __global_locale;
  472. #endif /* __UCLIBC_HAS_XLOCALE__ */
  473. new_thread->p_guardaddr = guardaddr;
  474. new_thread->p_guardsize = guardsize;
  475. new_thread->p_self = new_thread;
  476. new_thread->p_nr = sseg;
  477. /* Initialize the thread handle */
  478. __pthread_init_lock(&__pthread_handles[sseg].h_lock);
  479. __pthread_handles[sseg].h_descr = new_thread;
  480. __pthread_handles[sseg].h_bottom = new_thread_bottom;
  481. /* Determine scheduling parameters for the thread */
  482. new_thread->p_start_args.schedpolicy = -1;
  483. if (attr != NULL) {
  484. new_thread->p_detached = attr->__detachstate;
  485. new_thread->p_userstack = attr->__stackaddr_set;
  486. switch(attr->__inheritsched) {
  487. case PTHREAD_EXPLICIT_SCHED:
  488. new_thread->p_start_args.schedpolicy = attr->__schedpolicy;
  489. memcpy (&new_thread->p_start_args.schedparam, &attr->__schedparam,
  490. sizeof (struct sched_param));
  491. break;
  492. case PTHREAD_INHERIT_SCHED:
  493. new_thread->p_start_args.schedpolicy = sched_getscheduler(father_pid);
  494. sched_getparam(father_pid, &new_thread->p_start_args.schedparam);
  495. break;
  496. }
  497. new_thread->p_priority =
  498. new_thread->p_start_args.schedparam.sched_priority;
  499. }
  500. /* Finish setting up arguments to pthread_start_thread */
  501. new_thread->p_start_args.start_routine = start_routine;
  502. new_thread->p_start_args.arg = arg;
  503. new_thread->p_start_args.mask = *mask;
  504. /* Raise priority of thread manager if needed */
  505. __pthread_manager_adjust_prio(new_thread->p_priority);
  506. /* Do the cloning. We have to use two different functions depending
  507. on whether we are debugging or not. */
  508. pid = 0; /* Note that the thread never can have PID zero. */
  509. /* ******************************************************** */
  510. /* This code was moved from below to cope with running threads
  511. * on uClinux systems. See comment below...
  512. * Insert new thread in doubly linked list of active threads */
  513. new_thread->p_prevlive = __pthread_main_thread;
  514. new_thread->p_nextlive = __pthread_main_thread->p_nextlive;
  515. __pthread_main_thread->p_nextlive->p_prevlive = new_thread;
  516. __pthread_main_thread->p_nextlive = new_thread;
  517. /* ********************************************************* */
  518. if (report_events)
  519. {
  520. /* See whether the TD_CREATE event bit is set in any of the
  521. masks. */
  522. int idx = __td_eventword (TD_CREATE);
  523. uint32_t mask = __td_eventmask (TD_CREATE);
  524. if ((mask & (__pthread_threads_events.event_bits[idx]
  525. | event_maskp->event_bits[idx])) != 0)
  526. {
  527. /* Lock the mutex the child will use now so that it will stop. */
  528. __pthread_lock(new_thread->p_lock, NULL);
  529. /* We have to report this event. */
  530. #ifdef __ia64__
  531. pid = __clone2(pthread_start_thread_event, (void **) new_thread,
  532. (char *)new_thread - new_thread_bottom,
  533. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
  534. __pthread_sig_cancel, new_thread);
  535. #else
  536. pid = clone(pthread_start_thread_event, (void **) new_thread,
  537. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
  538. __pthread_sig_cancel, new_thread);
  539. #endif
  540. saved_errno = errno;
  541. if (pid != -1)
  542. {
  543. /* Now fill in the information about the new thread in
  544. the newly created thread's data structure. We cannot let
  545. the new thread do this since we don't know whether it was
  546. already scheduled when we send the event. */
  547. new_thread->p_eventbuf.eventdata = new_thread;
  548. new_thread->p_eventbuf.eventnum = TD_CREATE;
  549. __pthread_last_event = new_thread;
  550. /* We have to set the PID here since the callback function
  551. in the debug library will need it and we cannot guarantee
  552. the child got scheduled before the debugger. */
  553. new_thread->p_pid = pid;
  554. /* Now call the function which signals the event. */
  555. __linuxthreads_create_event ();
  556. /* Now restart the thread. */
  557. __pthread_unlock(new_thread->p_lock);
  558. }
  559. }
  560. }
  561. if (pid == 0)
  562. {
  563. PDEBUG("cloning new_thread = %p\n", new_thread);
  564. #ifdef __ia64__
  565. pid = __clone2(pthread_start_thread, (void **) new_thread,
  566. (char *)new_thread - new_thread_bottom,
  567. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
  568. __pthread_sig_cancel, new_thread);
  569. #else
  570. pid = clone(pthread_start_thread, (void **) new_thread,
  571. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
  572. __pthread_sig_cancel, new_thread);
  573. #endif
  574. saved_errno = errno;
  575. }
  576. /* Check if cloning succeeded */
  577. if (pid == -1) {
  578. /********************************************************
  579. * Code inserted to remove the thread from our list of active
  580. * threads in case of failure (needed to cope with uClinux),
  581. * See comment below. */
  582. new_thread->p_nextlive->p_prevlive = new_thread->p_prevlive;
  583. new_thread->p_prevlive->p_nextlive = new_thread->p_nextlive;
  584. /********************************************************/
  585. /* Free the stack if we allocated it */
  586. if (attr == NULL || !attr->__stackaddr_set)
  587. {
  588. #ifdef __ARCH_USE_MMU__
  589. if (new_thread->p_guardsize != 0)
  590. munmap(new_thread->p_guardaddr, new_thread->p_guardsize);
  591. munmap((caddr_t)((char *)(new_thread+1) - INITIAL_STACK_SIZE),
  592. INITIAL_STACK_SIZE);
  593. #else
  594. free(new_thread_bottom);
  595. #endif /* __ARCH_USE_MMU__ */
  596. }
  597. __pthread_handles[sseg].h_descr = NULL;
  598. __pthread_handles[sseg].h_bottom = NULL;
  599. __pthread_handles_num--;
  600. return errno;
  601. }
  602. PDEBUG("new thread pid = %d\n", pid);
  603. #if 0
  604. /* ***********************************************************
  605. This code has been moved before the call to clone(). In uClinux,
  606. the use of wait on a semaphore is dependant upon that the child so
  607. the child must be in the active threads list. This list is used in
  608. pthread_find_self() to get the pthread_descr of self. So, if the
  609. child calls sem_wait before this code is executed , it will hang
  610. forever and initial_thread will instead be posted by a sem_post
  611. call. */
  612. /* Insert new thread in doubly linked list of active threads */
  613. new_thread->p_prevlive = __pthread_main_thread;
  614. new_thread->p_nextlive = __pthread_main_thread->p_nextlive;
  615. __pthread_main_thread->p_nextlive->p_prevlive = new_thread;
  616. __pthread_main_thread->p_nextlive = new_thread;
  617. /************************************************************/
  618. #endif
  619. /* Set pid field of the new thread, in case we get there before the
  620. child starts. */
  621. new_thread->p_pid = pid;
  622. /* We're all set */
  623. *thread = new_thread_id;
  624. return 0;
  625. }
  626. /* Try to free the resources of a thread when requested by pthread_join
  627. or pthread_detach on a terminated thread. */
  628. static void pthread_free(pthread_descr th)
  629. {
  630. pthread_handle handle;
  631. pthread_readlock_info *iter, *next;
  632. char *h_bottom_save;
  633. ASSERT(th->p_exited);
  634. /* Make the handle invalid */
  635. handle = thread_handle(th->p_tid);
  636. __pthread_lock(&handle->h_lock, NULL);
  637. h_bottom_save = handle->h_bottom;
  638. handle->h_descr = NULL;
  639. handle->h_bottom = (char *)(-1L);
  640. __pthread_unlock(&handle->h_lock);
  641. #ifdef FREE_THREAD_SELF
  642. FREE_THREAD_SELF(th, th->p_nr);
  643. #endif
  644. /* One fewer threads in __pthread_handles */
  645. __pthread_handles_num--;
  646. /* Destroy read lock list, and list of free read lock structures.
  647. If the former is not empty, it means the thread exited while
  648. holding read locks! */
  649. for (iter = th->p_readlock_list; iter != NULL; iter = next)
  650. {
  651. next = iter->pr_next;
  652. free(iter);
  653. }
  654. for (iter = th->p_readlock_free; iter != NULL; iter = next)
  655. {
  656. next = iter->pr_next;
  657. free(iter);
  658. }
  659. /* If initial thread, nothing to free */
  660. if (th == &__pthread_initial_thread) return;
  661. #ifdef __ARCH_USE_MMU__
  662. if (!th->p_userstack)
  663. {
  664. /* Free the stack and thread descriptor area */
  665. if (th->p_guardsize != 0)
  666. munmap(th->p_guardaddr, th->p_guardsize);
  667. munmap((caddr_t) ((char *)(th+1) - STACK_SIZE), STACK_SIZE);
  668. }
  669. #else
  670. /* For non-MMU systems we always malloc the stack, so free it here. -StS */
  671. if (!th->p_userstack) {
  672. free(h_bottom_save);
  673. }
  674. #endif /* __ARCH_USE_MMU__ */
  675. }
  676. /* Handle threads that have exited */
  677. static void pthread_exited(pid_t pid)
  678. {
  679. pthread_descr th;
  680. int detached;
  681. /* Find thread with that pid */
  682. for (th = __pthread_main_thread->p_nextlive;
  683. th != __pthread_main_thread;
  684. th = th->p_nextlive) {
  685. if (th->p_pid == pid) {
  686. /* Remove thread from list of active threads */
  687. th->p_nextlive->p_prevlive = th->p_prevlive;
  688. th->p_prevlive->p_nextlive = th->p_nextlive;
  689. /* Mark thread as exited, and if detached, free its resources */
  690. __pthread_lock(th->p_lock, NULL);
  691. th->p_exited = 1;
  692. /* If we have to signal this event do it now. */
  693. if (th->p_report_events)
  694. {
  695. /* See whether TD_REAP is in any of the mask. */
  696. int idx = __td_eventword (TD_REAP);
  697. uint32_t mask = __td_eventmask (TD_REAP);
  698. if ((mask & (__pthread_threads_events.event_bits[idx]
  699. | th->p_eventbuf.eventmask.event_bits[idx])) != 0)
  700. {
  701. /* Yep, we have to signal the reapage. */
  702. th->p_eventbuf.eventnum = TD_REAP;
  703. th->p_eventbuf.eventdata = th;
  704. __pthread_last_event = th;
  705. /* Now call the function to signal the event. */
  706. __linuxthreads_reap_event();
  707. }
  708. }
  709. detached = th->p_detached;
  710. __pthread_unlock(th->p_lock);
  711. if (detached)
  712. pthread_free(th);
  713. break;
  714. }
  715. }
  716. /* If all threads have exited and the main thread is pending on a
  717. pthread_exit, wake up the main thread and terminate ourselves. */
  718. if (main_thread_exiting &&
  719. __pthread_main_thread->p_nextlive == __pthread_main_thread) {
  720. restart(__pthread_main_thread);
  721. /* Same logic as REQ_MAIN_THREAD_EXIT. */
  722. }
  723. }
  724. static void pthread_reap_children(void)
  725. {
  726. pid_t pid;
  727. int status;
  728. PDEBUG("\n");
  729. while ((pid = __libc_waitpid(-1, &status, WNOHANG | __WCLONE)) > 0) {
  730. pthread_exited(pid);
  731. if (WIFSIGNALED(status)) {
  732. /* If a thread died due to a signal, send the same signal to
  733. all other threads, including the main thread. */
  734. pthread_kill_all_threads(WTERMSIG(status), 1);
  735. _exit(0);
  736. }
  737. }
  738. }
  739. /* Try to free the resources of a thread when requested by pthread_join
  740. or pthread_detach on a terminated thread. */
  741. static void pthread_handle_free(pthread_t th_id)
  742. {
  743. pthread_handle handle = thread_handle(th_id);
  744. pthread_descr th;
  745. __pthread_lock(&handle->h_lock, NULL);
  746. if (invalid_handle(handle, th_id)) {
  747. /* pthread_reap_children has deallocated the thread already,
  748. nothing needs to be done */
  749. __pthread_unlock(&handle->h_lock);
  750. return;
  751. }
  752. th = handle->h_descr;
  753. if (th->p_exited) {
  754. __pthread_unlock(&handle->h_lock);
  755. pthread_free(th);
  756. } else {
  757. /* The Unix process of the thread is still running.
  758. Mark the thread as detached so that the thread manager will
  759. deallocate its resources when the Unix process exits. */
  760. th->p_detached = 1;
  761. __pthread_unlock(&handle->h_lock);
  762. }
  763. }
  764. /* Send a signal to all running threads */
  765. static void pthread_kill_all_threads(int sig, int main_thread_also)
  766. {
  767. pthread_descr th;
  768. for (th = __pthread_main_thread->p_nextlive;
  769. th != __pthread_main_thread;
  770. th = th->p_nextlive) {
  771. kill(th->p_pid, sig);
  772. }
  773. if (main_thread_also) {
  774. kill(__pthread_main_thread->p_pid, sig);
  775. }
  776. }
  777. /* Process-wide exit() */
  778. static void pthread_handle_exit(pthread_descr issuing_thread, int exitcode)
  779. {
  780. pthread_descr th;
  781. __pthread_exit_requested = 1;
  782. __pthread_exit_code = exitcode;
  783. /* Send the CANCEL signal to all running threads, including the main
  784. thread, but excluding the thread from which the exit request originated
  785. (that thread must complete the exit, e.g. calling atexit functions
  786. and flushing stdio buffers). */
  787. for (th = issuing_thread->p_nextlive;
  788. th != issuing_thread;
  789. th = th->p_nextlive) {
  790. kill(th->p_pid, __pthread_sig_cancel);
  791. }
  792. /* Now, wait for all these threads, so that they don't become zombies
  793. and their times are properly added to the thread manager's times. */
  794. for (th = issuing_thread->p_nextlive;
  795. th != issuing_thread;
  796. th = th->p_nextlive) {
  797. waitpid(th->p_pid, NULL, __WCLONE);
  798. }
  799. restart(issuing_thread);
  800. _exit(0);
  801. }
  802. /* Handler for __pthread_sig_cancel in thread manager thread */
  803. void __pthread_manager_sighandler(int sig attribute_unused)
  804. {
  805. int kick_manager = terminated_children == 0 && main_thread_exiting;
  806. terminated_children = 1;
  807. /* If the main thread is terminating, kick the thread manager loop
  808. each time some threads terminate. This eliminates a two second
  809. shutdown delay caused by the thread manager sleeping in the
  810. call to __poll(). Instead, the thread manager is kicked into
  811. action, reaps the outstanding threads and resumes the main thread
  812. so that it can complete the shutdown. */
  813. if (kick_manager) {
  814. struct pthread_request request;
  815. request.req_thread = 0;
  816. request.req_kind = REQ_KICK;
  817. TEMP_FAILURE_RETRY(__libc_write(__pthread_manager_request,
  818. (char *) &request, sizeof(request)));
  819. }
  820. }
  821. /* Adjust priority of thread manager so that it always run at a priority
  822. higher than all threads */
  823. void __pthread_manager_adjust_prio(int thread_prio)
  824. {
  825. struct sched_param param;
  826. if (thread_prio <= __pthread_manager_thread.p_priority) return;
  827. param.sched_priority =
  828. thread_prio < sched_get_priority_max(SCHED_FIFO)
  829. ? thread_prio + 1 : thread_prio;
  830. sched_setscheduler(__pthread_manager_thread.p_pid, SCHED_FIFO, &param);
  831. __pthread_manager_thread.p_priority = thread_prio;
  832. }