manager.c 34 KB

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