manager.c 33 KB

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