manager.c 27 KB

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