manager.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  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 <assert.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 <locale.h> /* for __uselocale */
  29. #include <resolv.h> /* for __resp */
  30. #include "pthread.h"
  31. #include "internals.h"
  32. #include "spinlock.h"
  33. #include "restart.h"
  34. #include "semaphore.h"
  35. #include <not-cancel.h>
  36. #define __clone clone
  37. #if !(USE_TLS && HAVE___THREAD) && defined __UCLIBC_HAS_XLOCALE__
  38. #define __uselocale(x) uselocale(x)
  39. #endif
  40. /* For debugging purposes put the maximum number of threads in a variable. */
  41. const int __linuxthreads_pthread_threads_max = PTHREAD_THREADS_MAX;
  42. #ifndef THREAD_SELF
  43. /* Indicate whether at least one thread has a user-defined stack (if 1),
  44. or if all threads have stacks supplied by LinuxThreads (if 0). */
  45. int __pthread_nonstandard_stacks;
  46. #endif
  47. /* Number of active entries in __pthread_handles (used by gdb) */
  48. volatile int __pthread_handles_num = 2;
  49. /* Whether to use debugger additional actions for thread creation
  50. (set to 1 by gdb) */
  51. volatile int __pthread_threads_debug;
  52. /* Globally enabled events. */
  53. volatile td_thr_events_t __pthread_threads_events;
  54. /* Pointer to thread descriptor with last event. */
  55. volatile pthread_descr __pthread_last_event;
  56. static pthread_descr manager_thread;
  57. /* Mapping from stack segment to thread descriptor. */
  58. /* Stack segment numbers are also indices into the __pthread_handles array. */
  59. /* Stack segment number 0 is reserved for the initial thread. */
  60. #if FLOATING_STACKS
  61. # define thread_segment(seq) NULL
  62. #else
  63. static inline pthread_descr thread_segment(int seg)
  64. {
  65. # ifdef _STACK_GROWS_UP
  66. return (pthread_descr)(THREAD_STACK_START_ADDRESS + (seg - 1) * STACK_SIZE)
  67. + 1;
  68. # else
  69. return (pthread_descr)(THREAD_STACK_START_ADDRESS - (seg - 1) * STACK_SIZE)
  70. - 1;
  71. # endif
  72. }
  73. #endif
  74. /* Flag set in signal handler to record child termination */
  75. static volatile int terminated_children;
  76. /* Flag set when the initial thread is blocked on pthread_exit waiting
  77. for all other threads to terminate */
  78. static int main_thread_exiting;
  79. /* Counter used to generate unique thread identifier.
  80. Thread identifier is pthread_threads_counter + segment. */
  81. static pthread_t pthread_threads_counter;
  82. /* Forward declarations */
  83. static int pthread_handle_create(pthread_t *thread, const pthread_attr_t *attr,
  84. void * (*start_routine)(void *), void *arg,
  85. sigset_t *mask, int father_pid,
  86. int report_events,
  87. td_thr_events_t *event_maskp);
  88. static void pthread_handle_free(pthread_t th_id);
  89. static void pthread_handle_exit(pthread_descr issuing_thread, int exitcode)
  90. __attribute__ ((noreturn));
  91. static void pthread_reap_children(void);
  92. static void pthread_kill_all_threads(int sig, int main_thread_also);
  93. static void pthread_for_each_thread(void *arg,
  94. void (*fn)(void *, pthread_descr));
  95. /* The server thread managing requests for thread creation and termination */
  96. int
  97. __attribute__ ((noreturn))
  98. __pthread_manager(void *arg)
  99. {
  100. pthread_descr self = manager_thread = arg;
  101. int reqfd = __pthread_manager_reader;
  102. struct pollfd ufd;
  103. sigset_t manager_mask;
  104. int n;
  105. struct pthread_request request;
  106. /* If we have special thread_self processing, initialize it. */
  107. #ifdef INIT_THREAD_SELF
  108. INIT_THREAD_SELF(self, 1);
  109. #endif
  110. #if !(USE_TLS && HAVE___THREAD)
  111. /* Set the error variable. */
  112. self->p_errnop = &self->p_errno;
  113. self->p_h_errnop = &self->p_h_errno;
  114. #endif
  115. /* Block all signals except __pthread_sig_cancel and SIGTRAP */
  116. sigfillset(&manager_mask);
  117. sigdelset(&manager_mask, __pthread_sig_cancel); /* for thread termination */
  118. sigdelset(&manager_mask, SIGTRAP); /* for debugging purposes */
  119. if (__pthread_threads_debug && __pthread_sig_debug > 0)
  120. sigdelset(&manager_mask, __pthread_sig_debug);
  121. sigprocmask(SIG_SETMASK, &manager_mask, NULL);
  122. /* Raise our priority to match that of main thread */
  123. __pthread_manager_adjust_prio(__pthread_main_thread->p_priority);
  124. /* Synchronize debugging of the thread manager */
  125. n = TEMP_FAILURE_RETRY(read_not_cancel(reqfd, (char *)&request,
  126. sizeof(request)));
  127. ASSERT(n == sizeof(request) && request.req_kind == REQ_DEBUG);
  128. ufd.fd = reqfd;
  129. ufd.events = POLLIN;
  130. /* Enter server loop */
  131. while(1) {
  132. n = __poll(&ufd, 1, 2000);
  133. /* Check for termination of the main thread */
  134. if (getppid() == 1) {
  135. pthread_kill_all_threads(SIGKILL, 0);
  136. _exit(0);
  137. }
  138. /* Check for dead children */
  139. if (terminated_children) {
  140. terminated_children = 0;
  141. pthread_reap_children();
  142. }
  143. /* Read and execute request */
  144. if (n == 1 && (ufd.revents & POLLIN)) {
  145. n = TEMP_FAILURE_RETRY(read_not_cancel(reqfd, (char *)&request,
  146. sizeof(request)));
  147. #ifdef DEBUG
  148. if (n < 0) {
  149. char d[64];
  150. write(STDERR_FILENO, d, snprintf(d, sizeof(d), "*** read err %m\n"));
  151. } else if (n != sizeof(request)) {
  152. write(STDERR_FILENO, "*** short read in manager\n", 26);
  153. }
  154. #endif
  155. switch(request.req_kind) {
  156. case REQ_CREATE:
  157. request.req_thread->p_retcode =
  158. pthread_handle_create((pthread_t *) &request.req_thread->p_retval,
  159. request.req_args.create.attr,
  160. request.req_args.create.fn,
  161. request.req_args.create.arg,
  162. &request.req_args.create.mask,
  163. request.req_thread->p_pid,
  164. request.req_thread->p_report_events,
  165. &request.req_thread->p_eventbuf.eventmask);
  166. restart(request.req_thread);
  167. break;
  168. case REQ_FREE:
  169. pthread_handle_free(request.req_args.free.thread_id);
  170. break;
  171. case REQ_PROCESS_EXIT:
  172. pthread_handle_exit(request.req_thread,
  173. request.req_args.exit.code);
  174. /* NOTREACHED */
  175. break;
  176. case REQ_MAIN_THREAD_EXIT:
  177. main_thread_exiting = 1;
  178. /* Reap children in case all other threads died and the signal handler
  179. went off before we set main_thread_exiting to 1, and therefore did
  180. not do REQ_KICK. */
  181. pthread_reap_children();
  182. if (__pthread_main_thread->p_nextlive == __pthread_main_thread) {
  183. restart(__pthread_main_thread);
  184. /* The main thread will now call exit() which will trigger an
  185. __on_exit handler, which in turn will send REQ_PROCESS_EXIT
  186. to the thread manager. In case you are wondering how the
  187. manager terminates from its loop here. */
  188. }
  189. break;
  190. case REQ_POST:
  191. sem_post(request.req_args.post);
  192. break;
  193. case REQ_DEBUG:
  194. /* Make gdb aware of new thread and gdb will restart the
  195. new thread when it is ready to handle the new thread. */
  196. if (__pthread_threads_debug && __pthread_sig_debug > 0)
  197. raise(__pthread_sig_debug);
  198. break;
  199. case REQ_KICK:
  200. /* This is just a prod to get the manager to reap some
  201. threads right away, avoiding a potential delay at shutdown. */
  202. break;
  203. case REQ_FOR_EACH_THREAD:
  204. pthread_for_each_thread(request.req_args.for_each.arg,
  205. request.req_args.for_each.fn);
  206. restart(request.req_thread);
  207. break;
  208. }
  209. }
  210. }
  211. }
  212. int __pthread_manager_event(void *arg)
  213. {
  214. pthread_descr self = arg;
  215. /* If we have special thread_self processing, initialize it. */
  216. #ifdef INIT_THREAD_SELF
  217. INIT_THREAD_SELF(self, 1);
  218. #endif
  219. /* Get the lock the manager will free once all is correctly set up. */
  220. __pthread_lock (THREAD_GETMEM(self, p_lock), NULL);
  221. /* Free it immediately. */
  222. __pthread_unlock (THREAD_GETMEM(self, p_lock));
  223. return __pthread_manager(arg);
  224. }
  225. /* Process creation */
  226. static int
  227. __attribute__ ((noreturn))
  228. pthread_start_thread(void *arg)
  229. {
  230. pthread_descr self = (pthread_descr) arg;
  231. struct pthread_request request;
  232. void * outcome;
  233. #if HP_TIMING_AVAIL
  234. hp_timing_t tmpclock;
  235. #endif
  236. /* Initialize special thread_self processing, if any. */
  237. #ifdef INIT_THREAD_SELF
  238. INIT_THREAD_SELF(self, self->p_nr);
  239. #endif
  240. #if HP_TIMING_AVAIL
  241. HP_TIMING_NOW (tmpclock);
  242. THREAD_SETMEM (self, p_cpuclock_offset, tmpclock);
  243. #endif
  244. /* Make sure our pid field is initialized, just in case we get there
  245. before our father has initialized it. */
  246. THREAD_SETMEM(self, p_pid, __getpid());
  247. /* Initial signal mask is that of the creating thread. (Otherwise,
  248. we'd just inherit the mask of the thread manager.) */
  249. sigprocmask(SIG_SETMASK, &self->p_start_args.mask, NULL);
  250. /* Set the scheduling policy and priority for the new thread, if needed */
  251. if (THREAD_GETMEM(self, p_start_args.schedpolicy) >= 0)
  252. /* Explicit scheduling attributes were provided: apply them */
  253. __sched_setscheduler(THREAD_GETMEM(self, p_pid),
  254. THREAD_GETMEM(self, p_start_args.schedpolicy),
  255. &self->p_start_args.schedparam);
  256. else if (manager_thread->p_priority > 0)
  257. /* Default scheduling required, but thread manager runs in realtime
  258. scheduling: switch new thread to SCHED_OTHER policy */
  259. {
  260. struct sched_param default_params;
  261. default_params.sched_priority = 0;
  262. __sched_setscheduler(THREAD_GETMEM(self, p_pid),
  263. SCHED_OTHER, &default_params);
  264. }
  265. #if !(USE_TLS && HAVE___THREAD)
  266. /* Initialize thread-locale current locale to point to the global one.
  267. With __thread support, the variable's initializer takes care of this. */
  268. #ifdef __UCLIBC_HAS_XLOCALE__
  269. __uselocale (LC_GLOBAL_LOCALE);
  270. #endif
  271. #else
  272. /* Initialize __resp. */
  273. __resp = &self->p_res;
  274. #endif
  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_not_cancel(__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. #if defined USE_TLS && !FLOATING_STACKS
  308. # error "TLS can only work with floating stacks"
  309. #endif
  310. static int pthread_allocate_stack(const pthread_attr_t *attr,
  311. pthread_descr default_new_thread,
  312. int pagesize,
  313. char ** out_new_thread,
  314. char ** out_new_thread_bottom,
  315. char ** out_guardaddr,
  316. size_t * out_guardsize,
  317. size_t * out_stacksize)
  318. {
  319. pthread_descr new_thread;
  320. char * new_thread_bottom;
  321. char * guardaddr;
  322. size_t stacksize, guardsize;
  323. #ifdef USE_TLS
  324. /* TLS cannot work with fixed thread descriptor addresses. */
  325. assert (default_new_thread == NULL);
  326. #endif
  327. if (attr != NULL && attr->__stackaddr_set)
  328. {
  329. #ifdef _STACK_GROWS_UP
  330. /* The user provided a stack. */
  331. # ifdef USE_TLS
  332. /* This value is not needed. */
  333. new_thread = (pthread_descr) attr->__stackaddr;
  334. new_thread_bottom = (char *) new_thread;
  335. # else
  336. new_thread = (pthread_descr) attr->__stackaddr;
  337. new_thread_bottom = (char *) (new_thread + 1);
  338. # endif
  339. guardaddr = attr->__stackaddr + attr->__stacksize;
  340. guardsize = 0;
  341. #else
  342. /* The user provided a stack. For now we interpret the supplied
  343. address as 1 + the highest addr. in the stack segment. If a
  344. separate register stack is needed, we place it at the low end
  345. of the segment, relying on the associated stacksize to
  346. determine the low end of the segment. This differs from many
  347. (but not all) other pthreads implementations. The intent is
  348. that on machines with a single stack growing toward higher
  349. addresses, stackaddr would be the lowest address in the stack
  350. segment, so that it is consistently close to the initial sp
  351. value. */
  352. # ifdef USE_TLS
  353. new_thread = (pthread_descr) attr->__stackaddr;
  354. # else
  355. new_thread =
  356. (pthread_descr) ((long)(attr->__stackaddr) & -sizeof(void *)) - 1;
  357. # endif
  358. new_thread_bottom = (char *) attr->__stackaddr - attr->__stacksize;
  359. guardaddr = new_thread_bottom;
  360. guardsize = 0;
  361. #endif
  362. #ifndef THREAD_SELF
  363. __pthread_nonstandard_stacks = 1;
  364. #endif
  365. #ifndef USE_TLS
  366. /* Clear the thread data structure. */
  367. memset (new_thread, '\0', sizeof (*new_thread));
  368. #endif
  369. stacksize = attr->__stacksize;
  370. }
  371. else
  372. {
  373. #ifdef NEED_SEPARATE_REGISTER_STACK
  374. const size_t granularity = 2 * pagesize;
  375. /* Try to make stacksize/2 a multiple of pagesize */
  376. #else
  377. const size_t granularity = pagesize;
  378. #endif
  379. void *map_addr;
  380. /* Allocate space for stack and thread descriptor at default address */
  381. #if FLOATING_STACKS
  382. if (attr != NULL)
  383. {
  384. guardsize = page_roundup (attr->__guardsize, granularity);
  385. stacksize = __pthread_max_stacksize - guardsize;
  386. stacksize = MIN (stacksize,
  387. page_roundup (attr->__stacksize, granularity));
  388. }
  389. else
  390. {
  391. guardsize = granularity;
  392. stacksize = __pthread_max_stacksize - guardsize;
  393. }
  394. map_addr = mmap(NULL, stacksize + guardsize,
  395. PROT_READ | PROT_WRITE | PROT_EXEC,
  396. MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  397. if (map_addr == MAP_FAILED)
  398. /* No more memory available. */
  399. return -1;
  400. # ifdef NEED_SEPARATE_REGISTER_STACK
  401. guardaddr = map_addr + stacksize / 2;
  402. if (guardsize > 0)
  403. mprotect (guardaddr, guardsize, PROT_NONE);
  404. new_thread_bottom = (char *) map_addr;
  405. # ifdef USE_TLS
  406. new_thread = ((pthread_descr) (new_thread_bottom + stacksize
  407. + guardsize));
  408. # else
  409. new_thread = ((pthread_descr) (new_thread_bottom + stacksize
  410. + guardsize)) - 1;
  411. # endif
  412. # elif _STACK_GROWS_DOWN
  413. guardaddr = map_addr;
  414. if (guardsize > 0)
  415. mprotect (guardaddr, guardsize, PROT_NONE);
  416. new_thread_bottom = (char *) map_addr + guardsize;
  417. # ifdef USE_TLS
  418. new_thread = ((pthread_descr) (new_thread_bottom + stacksize));
  419. # else
  420. new_thread = ((pthread_descr) (new_thread_bottom + stacksize)) - 1;
  421. # endif
  422. # elif _STACK_GROWS_UP
  423. guardaddr = map_addr + stacksize;
  424. if (guardsize > 0)
  425. mprotect (guardaddr, guardsize, PROT_NONE);
  426. new_thread = (pthread_descr) map_addr;
  427. # ifdef USE_TLS
  428. new_thread_bottom = (char *) new_thread;
  429. # else
  430. new_thread_bottom = (char *) (new_thread + 1);
  431. # endif
  432. # else
  433. # error You must define a stack direction
  434. # endif /* Stack direction */
  435. #else /* !FLOATING_STACKS */
  436. # if !defined NEED_SEPARATE_REGISTER_STACK && defined _STACK_GROWS_DOWN
  437. void *res_addr;
  438. # endif
  439. if (attr != NULL)
  440. {
  441. guardsize = page_roundup (attr->__guardsize, granularity);
  442. stacksize = STACK_SIZE - guardsize;
  443. stacksize = MIN (stacksize,
  444. page_roundup (attr->__stacksize, granularity));
  445. }
  446. else
  447. {
  448. guardsize = granularity;
  449. stacksize = STACK_SIZE - granularity;
  450. }
  451. # ifdef NEED_SEPARATE_REGISTER_STACK
  452. new_thread = default_new_thread;
  453. new_thread_bottom = (char *) (new_thread + 1) - stacksize - guardsize;
  454. /* Includes guard area, unlike the normal case. Use the bottom
  455. end of the segment as backing store for the register stack.
  456. Needed on IA64. In this case, we also map the entire stack at
  457. once. According to David Mosberger, that's cheaper. It also
  458. avoids the risk of intermittent failures due to other mappings
  459. in the same region. The cost is that we might be able to map
  460. slightly fewer stacks. */
  461. /* First the main stack: */
  462. map_addr = (caddr_t)((char *)(new_thread + 1) - stacksize / 2);
  463. res_addr = mmap(map_addr, stacksize / 2,
  464. PROT_READ | PROT_WRITE | PROT_EXEC,
  465. MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  466. if (res_addr != map_addr)
  467. {
  468. /* Bad luck, this segment is already mapped. */
  469. if (res_addr != MAP_FAILED)
  470. munmap(res_addr, stacksize / 2);
  471. return -1;
  472. }
  473. /* Then the register stack: */
  474. map_addr = (caddr_t)new_thread_bottom;
  475. res_addr = mmap(map_addr, stacksize/2,
  476. PROT_READ | PROT_WRITE | PROT_EXEC,
  477. MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  478. if (res_addr != map_addr)
  479. {
  480. if (res_addr != MAP_FAILED)
  481. munmap(res_addr, stacksize / 2);
  482. munmap((caddr_t)((char *)(new_thread + 1) - stacksize/2),
  483. stacksize/2);
  484. return -1;
  485. }
  486. guardaddr = new_thread_bottom + stacksize/2;
  487. /* We leave the guard area in the middle unmapped. */
  488. # else /* !NEED_SEPARATE_REGISTER_STACK */
  489. # ifdef _STACK_GROWS_DOWN
  490. new_thread = default_new_thread;
  491. new_thread_bottom = (char *) (new_thread + 1) - stacksize;
  492. map_addr = new_thread_bottom - guardsize;
  493. res_addr = mmap(map_addr, stacksize + guardsize,
  494. PROT_READ | PROT_WRITE | PROT_EXEC,
  495. MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  496. if (res_addr != map_addr)
  497. {
  498. /* Bad luck, this segment is already mapped. */
  499. if (res_addr != MAP_FAILED)
  500. munmap (res_addr, stacksize + guardsize);
  501. return -1;
  502. }
  503. /* We manage to get a stack. Protect the guard area pages if
  504. necessary. */
  505. guardaddr = map_addr;
  506. if (guardsize > 0)
  507. mprotect (guardaddr, guardsize, PROT_NONE);
  508. # else
  509. /* The thread description goes at the bottom of this area, and
  510. * the stack starts directly above it.
  511. */
  512. new_thread = (pthread_descr)((unsigned long)default_new_thread &~ (STACK_SIZE - 1));
  513. map_addr = mmap(new_thread, stacksize + guardsize,
  514. PROT_READ | PROT_WRITE | PROT_EXEC,
  515. MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  516. if (map_addr == MAP_FAILED)
  517. return -1;
  518. new_thread_bottom = map_addr + sizeof(*new_thread);
  519. guardaddr = map_addr + stacksize;
  520. if (guardsize > 0)
  521. mprotect (guardaddr, guardsize, PROT_NONE);
  522. # endif /* stack direction */
  523. # endif /* !NEED_SEPARATE_REGISTER_STACK */
  524. #endif /* !FLOATING_STACKS */
  525. }
  526. *out_new_thread = (char *) new_thread;
  527. *out_new_thread_bottom = new_thread_bottom;
  528. *out_guardaddr = guardaddr;
  529. *out_guardsize = guardsize;
  530. #ifdef NEED_SEPARATE_REGISTER_STACK
  531. *out_stacksize = stacksize / 2;
  532. #else
  533. *out_stacksize = stacksize;
  534. #endif
  535. return 0;
  536. }
  537. static int pthread_handle_create(pthread_t *thread, const pthread_attr_t *attr,
  538. void * (*start_routine)(void *), void *arg,
  539. sigset_t * mask, int father_pid,
  540. int report_events,
  541. td_thr_events_t *event_maskp)
  542. {
  543. size_t sseg;
  544. int pid;
  545. pthread_descr new_thread;
  546. char *stack_addr;
  547. char * new_thread_bottom;
  548. pthread_t new_thread_id;
  549. char *guardaddr = NULL;
  550. size_t guardsize = 0, stksize = 0;
  551. int pagesize = __getpagesize();
  552. int saved_errno = 0;
  553. #ifdef USE_TLS
  554. new_thread = _dl_allocate_tls (NULL);
  555. if (new_thread == NULL)
  556. return EAGAIN;
  557. # if TLS_DTV_AT_TP
  558. /* pthread_descr is below TP. */
  559. new_thread = (pthread_descr) ((char *) new_thread - TLS_PRE_TCB_SIZE);
  560. # endif
  561. #else
  562. /* Prevent warnings. */
  563. new_thread = NULL;
  564. #endif
  565. /* First check whether we have to change the policy and if yes, whether
  566. we can do this. Normally this should be done by examining the
  567. return value of the __sched_setscheduler call in pthread_start_thread
  568. but this is hard to implement. FIXME */
  569. if (attr != NULL && attr->__schedpolicy != SCHED_OTHER && geteuid () != 0)
  570. return EPERM;
  571. /* Find a free segment for the thread, and allocate a stack if needed */
  572. for (sseg = 2; ; sseg++)
  573. {
  574. if (sseg >= PTHREAD_THREADS_MAX)
  575. {
  576. #ifdef USE_TLS
  577. # if TLS_DTV_AT_TP
  578. new_thread = (pthread_descr) ((char *) new_thread + TLS_PRE_TCB_SIZE);
  579. # endif
  580. _dl_deallocate_tls (new_thread, true);
  581. #endif
  582. return EAGAIN;
  583. }
  584. if (__pthread_handles[sseg].h_descr != NULL)
  585. continue;
  586. if (pthread_allocate_stack(attr, thread_segment(sseg),
  587. pagesize, &stack_addr, &new_thread_bottom,
  588. &guardaddr, &guardsize, &stksize) == 0)
  589. {
  590. #ifdef USE_TLS
  591. new_thread->p_stackaddr = stack_addr;
  592. #else
  593. new_thread = (pthread_descr) stack_addr;
  594. #endif
  595. break;
  596. #ifndef __ARCH_HAS_MMU__
  597. } else {
  598. /* When there is MMU, mmap () is used to allocate the stack. If one
  599. * segment is already mapped, we should continue to see if we can
  600. * use the next one. However, when there is no MMU, malloc () is used.
  601. * It's waste of CPU cycles to continue to try if it fails. */
  602. return EAGAIN;
  603. #endif
  604. }
  605. }
  606. __pthread_handles_num++;
  607. /* Allocate new thread identifier */
  608. pthread_threads_counter += PTHREAD_THREADS_MAX;
  609. new_thread_id = sseg + pthread_threads_counter;
  610. /* Initialize the thread descriptor. Elements which have to be
  611. initialized to zero already have this value. */
  612. #if !defined USE_TLS || !TLS_DTV_AT_TP
  613. new_thread->p_header.data.tcb = new_thread;
  614. new_thread->p_header.data.self = new_thread;
  615. #endif
  616. #if TLS_MULTIPLE_THREADS_IN_TCB || !defined USE_TLS || !TLS_DTV_AT_TP
  617. new_thread->p_multiple_threads = 1;
  618. #endif
  619. new_thread->p_tid = new_thread_id;
  620. new_thread->p_lock = &(__pthread_handles[sseg].h_lock);
  621. new_thread->p_cancelstate = PTHREAD_CANCEL_ENABLE;
  622. new_thread->p_canceltype = PTHREAD_CANCEL_DEFERRED;
  623. #if !(USE_TLS && HAVE___THREAD)
  624. new_thread->p_errnop = &new_thread->p_errno;
  625. new_thread->p_h_errnop = &new_thread->p_h_errno;
  626. new_thread->p_resp = &new_thread->p_res;
  627. #endif
  628. new_thread->p_guardaddr = guardaddr;
  629. new_thread->p_guardsize = guardsize;
  630. new_thread->p_nr = sseg;
  631. new_thread->p_inheritsched = attr ? attr->__inheritsched : 0;
  632. new_thread->p_alloca_cutoff = stksize / 4 > __MAX_ALLOCA_CUTOFF
  633. ? __MAX_ALLOCA_CUTOFF : stksize / 4;
  634. /* Initialize the thread handle */
  635. __pthread_init_lock(&__pthread_handles[sseg].h_lock);
  636. __pthread_handles[sseg].h_descr = new_thread;
  637. __pthread_handles[sseg].h_bottom = new_thread_bottom;
  638. /* Determine scheduling parameters for the thread */
  639. new_thread->p_start_args.schedpolicy = -1;
  640. if (attr != NULL) {
  641. new_thread->p_detached = attr->__detachstate;
  642. new_thread->p_userstack = attr->__stackaddr_set;
  643. switch(attr->__inheritsched) {
  644. case PTHREAD_EXPLICIT_SCHED:
  645. new_thread->p_start_args.schedpolicy = attr->__schedpolicy;
  646. memcpy (&new_thread->p_start_args.schedparam, &attr->__schedparam,
  647. sizeof (struct sched_param));
  648. break;
  649. case PTHREAD_INHERIT_SCHED:
  650. new_thread->p_start_args.schedpolicy = __sched_getscheduler(father_pid);
  651. __sched_getparam(father_pid, &new_thread->p_start_args.schedparam);
  652. break;
  653. }
  654. new_thread->p_priority =
  655. new_thread->p_start_args.schedparam.sched_priority;
  656. }
  657. /* Finish setting up arguments to pthread_start_thread */
  658. new_thread->p_start_args.start_routine = start_routine;
  659. new_thread->p_start_args.arg = arg;
  660. new_thread->p_start_args.mask = *mask;
  661. /* Make the new thread ID available already now. If any of the later
  662. functions fail we return an error value and the caller must not use
  663. the stored thread ID. */
  664. *thread = new_thread_id;
  665. /* Raise priority of thread manager if needed */
  666. __pthread_manager_adjust_prio(new_thread->p_priority);
  667. /* Do the cloning. We have to use two different functions depending
  668. on whether we are debugging or not. */
  669. pid = 0; /* Note that the thread never can have PID zero. */
  670. if (report_events)
  671. {
  672. /* See whether the TD_CREATE event bit is set in any of the
  673. masks. */
  674. int idx = __td_eventword (TD_CREATE);
  675. uint32_t mask = __td_eventmask (TD_CREATE);
  676. if ((mask & (__pthread_threads_events.event_bits[idx]
  677. | event_maskp->event_bits[idx])) != 0)
  678. {
  679. /* Lock the mutex the child will use now so that it will stop. */
  680. __pthread_lock(new_thread->p_lock, NULL);
  681. /* We have to report this event. */
  682. #ifdef NEED_SEPARATE_REGISTER_STACK
  683. /* Perhaps this version should be used on all platforms. But
  684. this requires that __clone2 be uniformly supported
  685. everywhere.
  686. And there is some argument for changing the __clone2
  687. interface to pass sp and bsp instead, making it more IA64
  688. specific, but allowing stacks to grow outward from each
  689. other, to get less paging and fewer mmaps. */
  690. pid = __clone2(pthread_start_thread_event,
  691. (void **)new_thread_bottom,
  692. (char *)stack_addr - new_thread_bottom,
  693. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
  694. __pthread_sig_cancel, new_thread);
  695. #elif _STACK_GROWS_UP
  696. pid = __clone(pthread_start_thread_event, (void *) new_thread_bottom,
  697. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
  698. __pthread_sig_cancel, new_thread);
  699. #else
  700. pid = __clone(pthread_start_thread_event, stack_addr,
  701. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
  702. __pthread_sig_cancel, new_thread);
  703. #endif
  704. saved_errno = errno;
  705. if (pid != -1)
  706. {
  707. /* Now fill in the information about the new thread in
  708. the newly created thread's data structure. We cannot let
  709. the new thread do this since we don't know whether it was
  710. already scheduled when we send the event. */
  711. new_thread->p_eventbuf.eventdata = new_thread;
  712. new_thread->p_eventbuf.eventnum = TD_CREATE;
  713. __pthread_last_event = new_thread;
  714. /* We have to set the PID here since the callback function
  715. in the debug library will need it and we cannot guarantee
  716. the child got scheduled before the debugger. */
  717. new_thread->p_pid = pid;
  718. /* Now call the function which signals the event. */
  719. __linuxthreads_create_event ();
  720. /* Now restart the thread. */
  721. __pthread_unlock(new_thread->p_lock);
  722. }
  723. }
  724. }
  725. if (pid == 0)
  726. {
  727. #ifdef NEED_SEPARATE_REGISTER_STACK
  728. pid = __clone2(pthread_start_thread,
  729. (void **)new_thread_bottom,
  730. (char *)stack_addr - new_thread_bottom,
  731. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
  732. __pthread_sig_cancel, new_thread);
  733. #elif _STACK_GROWS_UP
  734. pid = __clone(pthread_start_thread, (void *) new_thread_bottom,
  735. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
  736. __pthread_sig_cancel, new_thread);
  737. #else
  738. pid = __clone(pthread_start_thread, stack_addr,
  739. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
  740. __pthread_sig_cancel, new_thread);
  741. #endif /* !NEED_SEPARATE_REGISTER_STACK */
  742. saved_errno = errno;
  743. }
  744. /* Check if cloning succeeded */
  745. if (pid == -1) {
  746. /* Free the stack if we allocated it */
  747. if (attr == NULL || !attr->__stackaddr_set)
  748. {
  749. #ifdef NEED_SEPARATE_REGISTER_STACK
  750. size_t stacksize = ((char *)(new_thread->p_guardaddr)
  751. - new_thread_bottom);
  752. munmap((caddr_t)new_thread_bottom,
  753. 2 * stacksize + new_thread->p_guardsize);
  754. #elif _STACK_GROWS_UP
  755. # ifdef USE_TLS
  756. size_t stacksize = guardaddr - stack_addr;
  757. munmap(stack_addr, stacksize + guardsize);
  758. # else
  759. size_t stacksize = guardaddr - (char *)new_thread;
  760. munmap(new_thread, stacksize + guardsize);
  761. # endif
  762. #else
  763. # ifdef USE_TLS
  764. size_t stacksize = stack_addr - new_thread_bottom;
  765. # else
  766. size_t stacksize = (char *)(new_thread+1) - new_thread_bottom;
  767. # endif
  768. munmap(new_thread_bottom - guardsize, guardsize + stacksize);
  769. #endif
  770. }
  771. #ifdef USE_TLS
  772. # if TLS_DTV_AT_TP
  773. new_thread = (pthread_descr) ((char *) new_thread + TLS_PRE_TCB_SIZE);
  774. # endif
  775. _dl_deallocate_tls (new_thread, true);
  776. #endif
  777. __pthread_handles[sseg].h_descr = NULL;
  778. __pthread_handles[sseg].h_bottom = NULL;
  779. __pthread_handles_num--;
  780. return saved_errno;
  781. }
  782. /* Insert new thread in doubly linked list of active threads */
  783. new_thread->p_prevlive = __pthread_main_thread;
  784. new_thread->p_nextlive = __pthread_main_thread->p_nextlive;
  785. __pthread_main_thread->p_nextlive->p_prevlive = new_thread;
  786. __pthread_main_thread->p_nextlive = new_thread;
  787. /* Set pid field of the new thread, in case we get there before the
  788. child starts. */
  789. new_thread->p_pid = pid;
  790. return 0;
  791. }
  792. /* Try to free the resources of a thread when requested by pthread_join
  793. or pthread_detach on a terminated thread. */
  794. static void pthread_free(pthread_descr th)
  795. {
  796. pthread_handle handle;
  797. pthread_readlock_info *iter, *next;
  798. ASSERT(th->p_exited);
  799. /* Make the handle invalid */
  800. handle = thread_handle(th->p_tid);
  801. __pthread_lock(&handle->h_lock, NULL);
  802. handle->h_descr = NULL;
  803. handle->h_bottom = (char *)(-1L);
  804. __pthread_unlock(&handle->h_lock);
  805. #ifdef FREE_THREAD
  806. FREE_THREAD(th, th->p_nr);
  807. #endif
  808. /* One fewer threads in __pthread_handles */
  809. __pthread_handles_num--;
  810. /* Destroy read lock list, and list of free read lock structures.
  811. If the former is not empty, it means the thread exited while
  812. holding read locks! */
  813. for (iter = th->p_readlock_list; iter != NULL; iter = next)
  814. {
  815. next = iter->pr_next;
  816. free(iter);
  817. }
  818. for (iter = th->p_readlock_free; iter != NULL; iter = next)
  819. {
  820. next = iter->pr_next;
  821. free(iter);
  822. }
  823. /* If initial thread, nothing to free */
  824. if (!th->p_userstack)
  825. {
  826. size_t guardsize = th->p_guardsize;
  827. /* Free the stack and thread descriptor area */
  828. char *guardaddr = th->p_guardaddr;
  829. #ifdef _STACK_GROWS_UP
  830. # ifdef USE_TLS
  831. size_t stacksize = guardaddr - th->p_stackaddr;
  832. # else
  833. size_t stacksize = guardaddr - (char *)th;
  834. # endif
  835. guardaddr = (char *)th;
  836. #else
  837. /* Guardaddr is always set, even if guardsize is 0. This allows
  838. us to compute everything else. */
  839. # ifdef USE_TLS
  840. size_t stacksize = th->p_stackaddr - guardaddr - guardsize;
  841. # else
  842. size_t stacksize = (char *)(th+1) - guardaddr - guardsize;
  843. # endif
  844. # ifdef NEED_SEPARATE_REGISTER_STACK
  845. /* Take account of the register stack, which is below guardaddr. */
  846. guardaddr -= stacksize;
  847. stacksize *= 2;
  848. # endif
  849. #endif
  850. /* Unmap the stack. */
  851. munmap(guardaddr, stacksize + guardsize);
  852. }
  853. #ifdef USE_TLS
  854. # if TLS_DTV_AT_TP
  855. th = (pthread_descr) ((char *) th + TLS_PRE_TCB_SIZE);
  856. # endif
  857. _dl_deallocate_tls (th, true);
  858. #endif
  859. }
  860. /* Handle threads that have exited */
  861. static void pthread_exited(pid_t pid)
  862. {
  863. pthread_descr th;
  864. int detached;
  865. /* Find thread with that pid */
  866. for (th = __pthread_main_thread->p_nextlive;
  867. th != __pthread_main_thread;
  868. th = th->p_nextlive) {
  869. if (th->p_pid == pid) {
  870. /* Remove thread from list of active threads */
  871. th->p_nextlive->p_prevlive = th->p_prevlive;
  872. th->p_prevlive->p_nextlive = th->p_nextlive;
  873. /* Mark thread as exited, and if detached, free its resources */
  874. __pthread_lock(th->p_lock, NULL);
  875. th->p_exited = 1;
  876. /* If we have to signal this event do it now. */
  877. if (th->p_report_events)
  878. {
  879. /* See whether TD_REAP is in any of the mask. */
  880. int idx = __td_eventword (TD_REAP);
  881. uint32_t mask = __td_eventmask (TD_REAP);
  882. if ((mask & (__pthread_threads_events.event_bits[idx]
  883. | th->p_eventbuf.eventmask.event_bits[idx])) != 0)
  884. {
  885. /* Yep, we have to signal the reapage. */
  886. th->p_eventbuf.eventnum = TD_REAP;
  887. th->p_eventbuf.eventdata = th;
  888. __pthread_last_event = th;
  889. /* Now call the function to signal the event. */
  890. __linuxthreads_reap_event();
  891. }
  892. }
  893. detached = th->p_detached;
  894. __pthread_unlock(th->p_lock);
  895. if (detached)
  896. pthread_free(th);
  897. break;
  898. }
  899. }
  900. /* If all threads have exited and the main thread is pending on a
  901. pthread_exit, wake up the main thread and terminate ourselves. */
  902. if (main_thread_exiting &&
  903. __pthread_main_thread->p_nextlive == __pthread_main_thread) {
  904. restart(__pthread_main_thread);
  905. /* Same logic as REQ_MAIN_THREAD_EXIT. */
  906. }
  907. }
  908. static void pthread_reap_children(void)
  909. {
  910. pid_t pid;
  911. int status;
  912. while ((pid = waitpid_not_cancel(-1, &status, WNOHANG | __WCLONE)) > 0) {
  913. pthread_exited(pid);
  914. if (WIFSIGNALED(status)) {
  915. /* If a thread died due to a signal, send the same signal to
  916. all other threads, including the main thread. */
  917. pthread_kill_all_threads(WTERMSIG(status), 1);
  918. _exit(0);
  919. }
  920. }
  921. }
  922. /* Try to free the resources of a thread when requested by pthread_join
  923. or pthread_detach on a terminated thread. */
  924. static void pthread_handle_free(pthread_t th_id)
  925. {
  926. pthread_handle handle = thread_handle(th_id);
  927. pthread_descr th;
  928. __pthread_lock(&handle->h_lock, NULL);
  929. if (nonexisting_handle(handle, th_id)) {
  930. /* pthread_reap_children has deallocated the thread already,
  931. nothing needs to be done */
  932. __pthread_unlock(&handle->h_lock);
  933. return;
  934. }
  935. th = handle->h_descr;
  936. if (th->p_exited) {
  937. __pthread_unlock(&handle->h_lock);
  938. pthread_free(th);
  939. } else {
  940. /* The Unix process of the thread is still running.
  941. Mark the thread as detached so that the thread manager will
  942. deallocate its resources when the Unix process exits. */
  943. th->p_detached = 1;
  944. __pthread_unlock(&handle->h_lock);
  945. }
  946. }
  947. /* Send a signal to all running threads */
  948. static void pthread_kill_all_threads(int sig, int main_thread_also)
  949. {
  950. pthread_descr th;
  951. for (th = __pthread_main_thread->p_nextlive;
  952. th != __pthread_main_thread;
  953. th = th->p_nextlive) {
  954. kill(th->p_pid, sig);
  955. }
  956. if (main_thread_also) {
  957. kill(__pthread_main_thread->p_pid, sig);
  958. }
  959. }
  960. static void pthread_for_each_thread(void *arg,
  961. void (*fn)(void *, pthread_descr))
  962. {
  963. pthread_descr th;
  964. for (th = __pthread_main_thread->p_nextlive;
  965. th != __pthread_main_thread;
  966. th = th->p_nextlive) {
  967. fn(arg, th);
  968. }
  969. fn(arg, __pthread_main_thread);
  970. }
  971. /* Process-wide exit() */
  972. static void pthread_handle_exit(pthread_descr issuing_thread, int exitcode)
  973. {
  974. pthread_descr th;
  975. __pthread_exit_requested = 1;
  976. __pthread_exit_code = exitcode;
  977. /* A forced asynchronous cancellation follows. Make sure we won't
  978. get stuck later in the main thread with a system lock being held
  979. by one of the cancelled threads. Ideally one would use the same
  980. code as in pthread_atfork(), but we can't distinguish system and
  981. user handlers there. */
  982. __flockfilelist();
  983. /* Send the CANCEL signal to all running threads, including the main
  984. thread, but excluding the thread from which the exit request originated
  985. (that thread must complete the exit, e.g. calling atexit functions
  986. and flushing stdio buffers). */
  987. for (th = issuing_thread->p_nextlive;
  988. th != issuing_thread;
  989. th = th->p_nextlive) {
  990. kill(th->p_pid, __pthread_sig_cancel);
  991. }
  992. /* Now, wait for all these threads, so that they don't become zombies
  993. and their times are properly added to the thread manager's times. */
  994. for (th = issuing_thread->p_nextlive;
  995. th != issuing_thread;
  996. th = th->p_nextlive) {
  997. waitpid(th->p_pid, NULL, __WCLONE);
  998. }
  999. __fresetlockfiles();
  1000. restart(issuing_thread);
  1001. _exit(0);
  1002. }
  1003. /* Handler for __pthread_sig_cancel in thread manager thread */
  1004. void __pthread_manager_sighandler(int sig)
  1005. {
  1006. int kick_manager = terminated_children == 0 && main_thread_exiting;
  1007. terminated_children = 1;
  1008. /* If the main thread is terminating, kick the thread manager loop
  1009. each time some threads terminate. This eliminates a two second
  1010. shutdown delay caused by the thread manager sleeping in the
  1011. call to __poll(). Instead, the thread manager is kicked into
  1012. action, reaps the outstanding threads and resumes the main thread
  1013. so that it can complete the shutdown. */
  1014. if (kick_manager) {
  1015. struct pthread_request request;
  1016. request.req_thread = 0;
  1017. request.req_kind = REQ_KICK;
  1018. TEMP_FAILURE_RETRY(write_not_cancel(__pthread_manager_request,
  1019. (char *) &request, sizeof(request)));
  1020. }
  1021. }
  1022. /* Adjust priority of thread manager so that it always run at a priority
  1023. higher than all threads */
  1024. void __pthread_manager_adjust_prio(int thread_prio)
  1025. {
  1026. struct sched_param param;
  1027. if (thread_prio <= manager_thread->p_priority) return;
  1028. param.sched_priority =
  1029. thread_prio < __sched_get_priority_max(SCHED_FIFO)
  1030. ? thread_prio + 1 : thread_prio;
  1031. __sched_setscheduler(manager_thread->p_pid, SCHED_FIFO, &param);
  1032. manager_thread->p_priority = thread_prio;
  1033. }