manager.c 33 KB

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