manager.c 30 KB

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