manager.c 35 KB

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