manager.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  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. char *new_stack;
  346. if ((new_stack = malloc(INITIAL_STACK_SIZE)) == NULL) {
  347. /* bad luck, we cannot malloc any more */
  348. return -1;
  349. }
  350. PDEBUG("malloced chunk: base=%p, size=0x%04x\n", new_stack, INITIAL_STACK_SIZE);
  351. /* Set up the pointers. new_thread marks the TOP of the stack frame and
  352. * the address of the pthread_descr struct at the same time. Therefore we
  353. * must account for its size and fit it in the malloc()'ed block. The
  354. * value of `new_thread' is then passed to clone() as the stack argument.
  355. *
  356. * ^ +------------------------+
  357. * | | pthread_descr struct |
  358. * | +------------------------+ <- new_thread
  359. * malloc block | | |
  360. * | | thread stack |
  361. * | | |
  362. * v +------------------------+ <- new_thread_bottom
  363. *
  364. * Note: The calculated value of new_thread must be word aligned otherwise
  365. * the kernel chokes on a non-aligned stack frame. Choose the lower
  366. * available word boundary.
  367. */
  368. new_thread_bottom = (pthread_descr) new_stack;
  369. new_thread = (long)((char *) new_stack + INITIAL_STACK_SIZE - sizeof(*new_thread) - 1)
  370. & -sizeof(void*); /* align new_thread */
  371. guardaddr = NULL;
  372. guardsize = 0;
  373. PDEBUG("thread stack: bos=%p, tos=%p\n", new_thread_bottom, new_thread);
  374. /* check the initial thread stack boundaries so they don't overlap */
  375. NOMMU_INITIAL_THREAD_BOUNDS(new_thread, new_thread_bottom);
  376. PDEBUG("initial stack: bos=%p, tos=%p\n", __pthread_initial_thread_bos,
  377. __pthread_initial_thread_tos);
  378. /* on non-MMU systems we always have non-standard stack frames */
  379. __pthread_nonstandard_stacks = 1;
  380. #endif /* __UCLIBC_HAS_MMU__ */
  381. }
  382. /* Clear the thread data structure. */
  383. memset (new_thread, '\0', sizeof (*new_thread));
  384. *out_new_thread = new_thread;
  385. *out_new_thread_bottom = new_thread_bottom;
  386. *out_guardaddr = guardaddr;
  387. *out_guardsize = guardsize;
  388. return 0;
  389. }
  390. static int pthread_handle_create(pthread_t *thread, const pthread_attr_t *attr,
  391. void * (*start_routine)(void *), void *arg,
  392. sigset_t * mask, int father_pid,
  393. int report_events,
  394. td_thr_events_t *event_maskp)
  395. {
  396. size_t sseg;
  397. int pid;
  398. pthread_descr new_thread;
  399. char * new_thread_bottom;
  400. pthread_t new_thread_id;
  401. char *guardaddr = NULL;
  402. size_t guardsize = 0;
  403. int pagesize = __getpagesize();
  404. /* First check whether we have to change the policy and if yes, whether
  405. we can do this. Normally this should be done by examining the
  406. return value of the sched_setscheduler call in pthread_start_thread
  407. but this is hard to implement. FIXME */
  408. if (attr != NULL && attr->__schedpolicy != SCHED_OTHER && geteuid () != 0)
  409. return EPERM;
  410. /* Find a free segment for the thread, and allocate a stack if needed */
  411. for (sseg = 2; ; sseg++)
  412. {
  413. if (sseg >= PTHREAD_THREADS_MAX)
  414. return EAGAIN;
  415. if (__pthread_handles[sseg].h_descr != NULL)
  416. continue;
  417. if (pthread_allocate_stack(attr, thread_segment(sseg), pagesize,
  418. &new_thread, &new_thread_bottom,
  419. &guardaddr, &guardsize) == 0)
  420. break;
  421. }
  422. __pthread_handles_num++;
  423. /* Allocate new thread identifier */
  424. pthread_threads_counter += PTHREAD_THREADS_MAX;
  425. new_thread_id = sseg + pthread_threads_counter;
  426. /* Initialize the thread descriptor. Elements which have to be
  427. initialized to zero already have this value. */
  428. new_thread->p_tid = new_thread_id;
  429. new_thread->p_lock = &(__pthread_handles[sseg].h_lock);
  430. new_thread->p_cancelstate = PTHREAD_CANCEL_ENABLE;
  431. new_thread->p_canceltype = PTHREAD_CANCEL_DEFERRED;
  432. new_thread->p_errnop = &new_thread->p_errno;
  433. new_thread->p_h_errnop = &new_thread->p_h_errno;
  434. new_thread->p_guardaddr = guardaddr;
  435. new_thread->p_guardsize = guardsize;
  436. new_thread->p_self = new_thread;
  437. new_thread->p_nr = sseg;
  438. /* Initialize the thread handle */
  439. __pthread_init_lock(&__pthread_handles[sseg].h_lock);
  440. __pthread_handles[sseg].h_descr = new_thread;
  441. __pthread_handles[sseg].h_bottom = new_thread_bottom;
  442. /* Determine scheduling parameters for the thread */
  443. new_thread->p_start_args.schedpolicy = -1;
  444. if (attr != NULL) {
  445. new_thread->p_detached = attr->__detachstate;
  446. new_thread->p_userstack = attr->__stackaddr_set;
  447. switch(attr->__inheritsched) {
  448. case PTHREAD_EXPLICIT_SCHED:
  449. new_thread->p_start_args.schedpolicy = attr->__schedpolicy;
  450. memcpy (&new_thread->p_start_args.schedparam, &attr->__schedparam,
  451. sizeof (struct sched_param));
  452. break;
  453. case PTHREAD_INHERIT_SCHED:
  454. new_thread->p_start_args.schedpolicy = sched_getscheduler(father_pid);
  455. sched_getparam(father_pid, &new_thread->p_start_args.schedparam);
  456. break;
  457. }
  458. new_thread->p_priority =
  459. new_thread->p_start_args.schedparam.sched_priority;
  460. }
  461. /* Finish setting up arguments to pthread_start_thread */
  462. new_thread->p_start_args.start_routine = start_routine;
  463. new_thread->p_start_args.arg = arg;
  464. new_thread->p_start_args.mask = *mask;
  465. /* Raise priority of thread manager if needed */
  466. __pthread_manager_adjust_prio(new_thread->p_priority);
  467. /* Do the cloning. We have to use two different functions depending
  468. on whether we are debugging or not. */
  469. pid = 0; /* Note that the thread never can have PID zero. */
  470. /* ******************************************************** */
  471. /* This code was moved from below to cope with running threads
  472. * on uClinux systems. See comment below...
  473. * Insert new thread in doubly linked list of active threads */
  474. new_thread->p_prevlive = __pthread_main_thread;
  475. new_thread->p_nextlive = __pthread_main_thread->p_nextlive;
  476. __pthread_main_thread->p_nextlive->p_prevlive = new_thread;
  477. __pthread_main_thread->p_nextlive = new_thread;
  478. /* ********************************************************* */
  479. if (report_events)
  480. {
  481. /* See whether the TD_CREATE event bit is set in any of the
  482. masks. */
  483. int idx = __td_eventword (TD_CREATE);
  484. uint32_t mask = __td_eventmask (TD_CREATE);
  485. if ((mask & (__pthread_threads_events.event_bits[idx]
  486. | event_maskp->event_bits[idx])) != 0)
  487. {
  488. /* Lock the mutex the child will use now so that it will stop. */
  489. __pthread_lock(new_thread->p_lock, NULL);
  490. /* We have to report this event. */
  491. pid = clone(pthread_start_thread_event, (void **) new_thread,
  492. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
  493. __pthread_sig_cancel, new_thread);
  494. if (pid != -1)
  495. {
  496. /* Now fill in the information about the new thread in
  497. the newly created thread's data structure. We cannot let
  498. the new thread do this since we don't know whether it was
  499. already scheduled when we send the event. */
  500. new_thread->p_eventbuf.eventdata = new_thread;
  501. new_thread->p_eventbuf.eventnum = TD_CREATE;
  502. __pthread_last_event = new_thread;
  503. /* We have to set the PID here since the callback function
  504. in the debug library will need it and we cannot guarantee
  505. the child got scheduled before the debugger. */
  506. new_thread->p_pid = pid;
  507. /* Now call the function which signals the event. */
  508. __linuxthreads_create_event ();
  509. /* Now restart the thread. */
  510. __pthread_unlock(new_thread->p_lock);
  511. }
  512. }
  513. }
  514. if (pid == 0)
  515. PDEBUG("cloning new_thread = %p\n", new_thread);
  516. pid = clone(pthread_start_thread, (void **) new_thread,
  517. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
  518. __pthread_sig_cancel, new_thread);
  519. /* Check if cloning succeeded */
  520. if (pid == -1) {
  521. /********************************************************
  522. * Code inserted to remove the thread from our list of active
  523. * threads in case of failure (needed to cope with uClinux),
  524. * See comment below. */
  525. new_thread->p_nextlive->p_prevlive = new_thread->p_prevlive;
  526. new_thread->p_prevlive->p_nextlive = new_thread->p_nextlive;
  527. /********************************************************/
  528. /* Free the stack if we allocated it */
  529. if (attr == NULL || !attr->__stackaddr_set)
  530. {
  531. #ifdef __UCLIBC_HAS_MMU__
  532. if (new_thread->p_guardsize != 0)
  533. munmap(new_thread->p_guardaddr, new_thread->p_guardsize);
  534. munmap((caddr_t)((char *)(new_thread+1) - INITIAL_STACK_SIZE),
  535. INITIAL_STACK_SIZE);
  536. #else
  537. free(new_thread_bottom);
  538. #endif /* __UCLIBC_HAS_MMU__ */
  539. }
  540. __pthread_handles[sseg].h_descr = NULL;
  541. __pthread_handles[sseg].h_bottom = NULL;
  542. __pthread_handles_num--;
  543. return errno;
  544. }
  545. PDEBUG("new thread pid = %d\n", pid);
  546. #if 0
  547. /* ***********************************************************
  548. This code has been moved before the call to clone(). In uClinux,
  549. the use of wait on a semaphore is dependant upon that the child so
  550. the child must be in the active threads list. This list is used in
  551. pthread_find_self() to get the pthread_descr of self. So, if the
  552. child calls sem_wait before this code is executed , it will hang
  553. forever and initial_thread will instead be posted by a sem_post
  554. call. */
  555. /* Insert new thread in doubly linked list of active threads */
  556. new_thread->p_prevlive = __pthread_main_thread;
  557. new_thread->p_nextlive = __pthread_main_thread->p_nextlive;
  558. __pthread_main_thread->p_nextlive->p_prevlive = new_thread;
  559. __pthread_main_thread->p_nextlive = new_thread;
  560. /************************************************************/
  561. #endif
  562. /* Set pid field of the new thread, in case we get there before the
  563. child starts. */
  564. new_thread->p_pid = pid;
  565. /* We're all set */
  566. *thread = new_thread_id;
  567. return 0;
  568. }
  569. /* Try to free the resources of a thread when requested by pthread_join
  570. or pthread_detach on a terminated thread. */
  571. static void pthread_free(pthread_descr th)
  572. {
  573. pthread_handle handle;
  574. pthread_readlock_info *iter, *next;
  575. char *h_bottom_save;
  576. ASSERT(th->p_exited);
  577. /* Make the handle invalid */
  578. handle = thread_handle(th->p_tid);
  579. __pthread_lock(&handle->h_lock, NULL);
  580. h_bottom_save = handle->h_bottom;
  581. handle->h_descr = NULL;
  582. handle->h_bottom = (char *)(-1L);
  583. __pthread_unlock(&handle->h_lock);
  584. #ifdef FREE_THREAD_SELF
  585. FREE_THREAD_SELF(th, th->p_nr);
  586. #endif
  587. /* One fewer threads in __pthread_handles */
  588. __pthread_handles_num--;
  589. /* Destroy read lock list, and list of free read lock structures.
  590. If the former is not empty, it means the thread exited while
  591. holding read locks! */
  592. for (iter = th->p_readlock_list; iter != NULL; iter = next)
  593. {
  594. next = iter->pr_next;
  595. free(iter);
  596. }
  597. for (iter = th->p_readlock_free; iter != NULL; iter = next)
  598. {
  599. next = iter->pr_next;
  600. free(iter);
  601. }
  602. /* If initial thread, nothing to free */
  603. if (th == &__pthread_initial_thread) return;
  604. #ifdef __UCLIBC_HAS_MMU__
  605. if (!th->p_userstack)
  606. {
  607. /* Free the stack and thread descriptor area */
  608. if (th->p_guardsize != 0)
  609. munmap(th->p_guardaddr, th->p_guardsize);
  610. munmap((caddr_t) ((char *)(th+1) - STACK_SIZE), STACK_SIZE);
  611. }
  612. #else
  613. /* For non-MMU systems we always malloc the stack, so free it here. -StS */
  614. if (!th->p_userstack) {
  615. free(h_bottom_save);
  616. }
  617. #endif /* __UCLIBC_HAS_MMU__ */
  618. }
  619. /* Handle threads that have exited */
  620. static void pthread_exited(pid_t pid)
  621. {
  622. pthread_descr th;
  623. int detached;
  624. /* Find thread with that pid */
  625. for (th = __pthread_main_thread->p_nextlive;
  626. th != __pthread_main_thread;
  627. th = th->p_nextlive) {
  628. if (th->p_pid == pid) {
  629. /* Remove thread from list of active threads */
  630. th->p_nextlive->p_prevlive = th->p_prevlive;
  631. th->p_prevlive->p_nextlive = th->p_nextlive;
  632. /* Mark thread as exited, and if detached, free its resources */
  633. __pthread_lock(th->p_lock, NULL);
  634. th->p_exited = 1;
  635. /* If we have to signal this event do it now. */
  636. if (th->p_report_events)
  637. {
  638. /* See whether TD_DEATH is in any of the mask. */
  639. int idx = __td_eventword (TD_REAP);
  640. uint32_t mask = __td_eventmask (TD_REAP);
  641. if ((mask & (__pthread_threads_events.event_bits[idx]
  642. | th->p_eventbuf.eventmask.event_bits[idx])) != 0)
  643. {
  644. /* Yep, we have to signal the death. */
  645. th->p_eventbuf.eventnum = TD_DEATH;
  646. th->p_eventbuf.eventdata = th;
  647. __pthread_last_event = th;
  648. /* Now call the function to signal the event. */
  649. __linuxthreads_reap_event();
  650. }
  651. }
  652. detached = th->p_detached;
  653. __pthread_unlock(th->p_lock);
  654. if (detached)
  655. pthread_free(th);
  656. break;
  657. }
  658. }
  659. /* If all threads have exited and the main thread is pending on a
  660. pthread_exit, wake up the main thread and terminate ourselves. */
  661. if (main_thread_exiting &&
  662. __pthread_main_thread->p_nextlive == __pthread_main_thread) {
  663. restart(__pthread_main_thread);
  664. _exit(0);
  665. }
  666. }
  667. static void pthread_reap_children(void)
  668. {
  669. pid_t pid;
  670. int status;
  671. PDEBUG("\n");
  672. while ((pid = __libc_waitpid(-1, &status, WNOHANG | __WCLONE)) > 0) {
  673. pthread_exited(pid);
  674. if (WIFSIGNALED(status)) {
  675. /* If a thread died due to a signal, send the same signal to
  676. all other threads, including the main thread. */
  677. pthread_kill_all_threads(WTERMSIG(status), 1);
  678. _exit(0);
  679. }
  680. }
  681. }
  682. /* Try to free the resources of a thread when requested by pthread_join
  683. or pthread_detach on a terminated thread. */
  684. static void pthread_handle_free(pthread_t th_id)
  685. {
  686. pthread_handle handle = thread_handle(th_id);
  687. pthread_descr th;
  688. __pthread_lock(&handle->h_lock, NULL);
  689. if (invalid_handle(handle, th_id)) {
  690. /* pthread_reap_children has deallocated the thread already,
  691. nothing needs to be done */
  692. __pthread_unlock(&handle->h_lock);
  693. return;
  694. }
  695. th = handle->h_descr;
  696. if (th->p_exited) {
  697. __pthread_unlock(&handle->h_lock);
  698. pthread_free(th);
  699. } else {
  700. /* The Unix process of the thread is still running.
  701. Mark the thread as detached so that the thread manager will
  702. deallocate its resources when the Unix process exits. */
  703. th->p_detached = 1;
  704. __pthread_unlock(&handle->h_lock);
  705. }
  706. }
  707. /* Send a signal to all running threads */
  708. static void pthread_kill_all_threads(int sig, int main_thread_also)
  709. {
  710. pthread_descr th;
  711. for (th = __pthread_main_thread->p_nextlive;
  712. th != __pthread_main_thread;
  713. th = th->p_nextlive) {
  714. kill(th->p_pid, sig);
  715. }
  716. if (main_thread_also) {
  717. kill(__pthread_main_thread->p_pid, sig);
  718. }
  719. }
  720. /* Process-wide exit() */
  721. static void pthread_handle_exit(pthread_descr issuing_thread, int exitcode)
  722. {
  723. pthread_descr th;
  724. __pthread_exit_requested = 1;
  725. __pthread_exit_code = exitcode;
  726. /* Send the CANCEL signal to all running threads, including the main
  727. thread, but excluding the thread from which the exit request originated
  728. (that thread must complete the exit, e.g. calling atexit functions
  729. and flushing stdio buffers). */
  730. for (th = issuing_thread->p_nextlive;
  731. th != issuing_thread;
  732. th = th->p_nextlive) {
  733. kill(th->p_pid, __pthread_sig_cancel);
  734. }
  735. /* Now, wait for all these threads, so that they don't become zombies
  736. and their times are properly added to the thread manager's times. */
  737. for (th = issuing_thread->p_nextlive;
  738. th != issuing_thread;
  739. th = th->p_nextlive) {
  740. waitpid(th->p_pid, NULL, __WCLONE);
  741. }
  742. restart(issuing_thread);
  743. _exit(0);
  744. }
  745. /* Handler for __pthread_sig_cancel in thread manager thread */
  746. void __pthread_manager_sighandler(int sig)
  747. {
  748. terminated_children = 1;
  749. }
  750. /* Adjust priority of thread manager so that it always run at a priority
  751. higher than all threads */
  752. void __pthread_manager_adjust_prio(int thread_prio)
  753. {
  754. struct sched_param param;
  755. if (thread_prio <= __pthread_manager_thread.p_priority) return;
  756. param.sched_priority =
  757. thread_prio < sched_get_priority_max(SCHED_FIFO)
  758. ? thread_prio + 1 : thread_prio;
  759. sched_setscheduler(__pthread_manager_thread.p_pid, SCHED_FIFO, &param);
  760. __pthread_manager_thread.p_priority = thread_prio;
  761. }