manager.c 37 KB

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