manager.c 32 KB

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