manager.c 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  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) && defined __UCLIBC_HAS_XLOCALE__
  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. __uselocale (LC_GLOBAL_LOCALE);
  269. #else
  270. /* Initialize __resp. */
  271. __resp = &self->p_res;
  272. #endif
  273. /* Make gdb aware of new thread */
  274. if (__pthread_threads_debug && __pthread_sig_debug > 0) {
  275. request.req_thread = self;
  276. request.req_kind = REQ_DEBUG;
  277. TEMP_FAILURE_RETRY(write_not_cancel(__pthread_manager_request,
  278. (char *) &request, sizeof(request)));
  279. suspend(self);
  280. }
  281. /* Run the thread code */
  282. outcome = self->p_start_args.start_routine(THREAD_GETMEM(self,
  283. p_start_args.arg));
  284. /* Exit with the given return value */
  285. __pthread_do_exit(outcome, CURRENT_STACK_FRAME);
  286. }
  287. static int
  288. __attribute__ ((noreturn))
  289. pthread_start_thread_event(void *arg)
  290. {
  291. pthread_descr self = (pthread_descr) arg;
  292. #ifdef INIT_THREAD_SELF
  293. INIT_THREAD_SELF(self, self->p_nr);
  294. #endif
  295. /* Make sure our pid field is initialized, just in case we get there
  296. before our father has initialized it. */
  297. THREAD_SETMEM(self, p_pid, __getpid());
  298. /* Get the lock the manager will free once all is correctly set up. */
  299. __pthread_lock (THREAD_GETMEM(self, p_lock), NULL);
  300. /* Free it immediately. */
  301. __pthread_unlock (THREAD_GETMEM(self, p_lock));
  302. /* Continue with the real function. */
  303. pthread_start_thread (arg);
  304. }
  305. #if defined USE_TLS && !FLOATING_STACKS
  306. # error "TLS can only work with floating stacks"
  307. #endif
  308. static int pthread_allocate_stack(const pthread_attr_t *attr,
  309. pthread_descr default_new_thread,
  310. int pagesize,
  311. char ** out_new_thread,
  312. char ** out_new_thread_bottom,
  313. char ** out_guardaddr,
  314. size_t * out_guardsize,
  315. size_t * out_stacksize)
  316. {
  317. pthread_descr new_thread;
  318. char * new_thread_bottom;
  319. char * guardaddr;
  320. size_t stacksize, guardsize;
  321. #ifdef USE_TLS
  322. /* TLS cannot work with fixed thread descriptor addresses. */
  323. assert (default_new_thread == NULL);
  324. #endif
  325. if (attr != NULL && attr->__stackaddr_set)
  326. {
  327. #ifdef _STACK_GROWS_UP
  328. /* The user provided a stack. */
  329. # ifdef USE_TLS
  330. /* This value is not needed. */
  331. new_thread = (pthread_descr) attr->__stackaddr;
  332. new_thread_bottom = (char *) new_thread;
  333. # else
  334. new_thread = (pthread_descr) attr->__stackaddr;
  335. new_thread_bottom = (char *) (new_thread + 1);
  336. # endif
  337. guardaddr = attr->__stackaddr + attr->__stacksize;
  338. guardsize = 0;
  339. #else
  340. /* The user provided a stack. For now we interpret the supplied
  341. address as 1 + the highest addr. in the stack segment. If a
  342. separate register stack is needed, we place it at the low end
  343. of the segment, relying on the associated stacksize to
  344. determine the low end of the segment. This differs from many
  345. (but not all) other pthreads implementations. The intent is
  346. that on machines with a single stack growing toward higher
  347. addresses, stackaddr would be the lowest address in the stack
  348. segment, so that it is consistently close to the initial sp
  349. value. */
  350. # ifdef USE_TLS
  351. new_thread = (pthread_descr) attr->__stackaddr;
  352. # else
  353. new_thread =
  354. (pthread_descr) ((long)(attr->__stackaddr) & -sizeof(void *)) - 1;
  355. # endif
  356. new_thread_bottom = (char *) attr->__stackaddr - attr->__stacksize;
  357. guardaddr = new_thread_bottom;
  358. guardsize = 0;
  359. #endif
  360. #ifndef THREAD_SELF
  361. __pthread_nonstandard_stacks = 1;
  362. #endif
  363. #ifndef USE_TLS
  364. /* Clear the thread data structure. */
  365. memset (new_thread, '\0', sizeof (*new_thread));
  366. #endif
  367. stacksize = attr->__stacksize;
  368. }
  369. else
  370. {
  371. #ifdef NEED_SEPARATE_REGISTER_STACK
  372. const size_t granularity = 2 * pagesize;
  373. /* Try to make stacksize/2 a multiple of pagesize */
  374. #else
  375. const size_t granularity = pagesize;
  376. #endif
  377. void *map_addr;
  378. /* Allocate space for stack and thread descriptor at default address */
  379. #if FLOATING_STACKS
  380. if (attr != NULL)
  381. {
  382. guardsize = page_roundup (attr->__guardsize, granularity);
  383. stacksize = __pthread_max_stacksize - guardsize;
  384. stacksize = MIN (stacksize,
  385. page_roundup (attr->__stacksize, granularity));
  386. }
  387. else
  388. {
  389. guardsize = granularity;
  390. stacksize = __pthread_max_stacksize - guardsize;
  391. }
  392. map_addr = mmap(NULL, stacksize + guardsize,
  393. PROT_READ | PROT_WRITE | PROT_EXEC,
  394. MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  395. if (map_addr == MAP_FAILED)
  396. /* No more memory available. */
  397. return -1;
  398. # ifdef NEED_SEPARATE_REGISTER_STACK
  399. guardaddr = map_addr + stacksize / 2;
  400. if (guardsize > 0)
  401. mprotect (guardaddr, guardsize, PROT_NONE);
  402. new_thread_bottom = (char *) map_addr;
  403. # ifdef USE_TLS
  404. new_thread = ((pthread_descr) (new_thread_bottom + stacksize
  405. + guardsize));
  406. # else
  407. new_thread = ((pthread_descr) (new_thread_bottom + stacksize
  408. + guardsize)) - 1;
  409. # endif
  410. # elif _STACK_GROWS_DOWN
  411. guardaddr = map_addr;
  412. if (guardsize > 0)
  413. mprotect (guardaddr, guardsize, PROT_NONE);
  414. new_thread_bottom = (char *) map_addr + guardsize;
  415. # ifdef USE_TLS
  416. new_thread = ((pthread_descr) (new_thread_bottom + stacksize));
  417. # else
  418. new_thread = ((pthread_descr) (new_thread_bottom + stacksize)) - 1;
  419. # endif
  420. # elif _STACK_GROWS_UP
  421. guardaddr = map_addr + stacksize;
  422. if (guardsize > 0)
  423. mprotect (guardaddr, guardsize, PROT_NONE);
  424. new_thread = (pthread_descr) map_addr;
  425. # ifdef USE_TLS
  426. new_thread_bottom = (char *) new_thread;
  427. # else
  428. new_thread_bottom = (char *) (new_thread + 1);
  429. # endif
  430. # else
  431. # error You must define a stack direction
  432. # endif /* Stack direction */
  433. #else /* !FLOATING_STACKS */
  434. # if !defined NEED_SEPARATE_REGISTER_STACK && defined _STACK_GROWS_DOWN
  435. void *res_addr;
  436. # endif
  437. if (attr != NULL)
  438. {
  439. guardsize = page_roundup (attr->__guardsize, granularity);
  440. stacksize = STACK_SIZE - guardsize;
  441. stacksize = MIN (stacksize,
  442. page_roundup (attr->__stacksize, granularity));
  443. }
  444. else
  445. {
  446. guardsize = granularity;
  447. stacksize = STACK_SIZE - granularity;
  448. }
  449. # ifdef NEED_SEPARATE_REGISTER_STACK
  450. new_thread = default_new_thread;
  451. new_thread_bottom = (char *) (new_thread + 1) - stacksize - guardsize;
  452. /* Includes guard area, unlike the normal case. Use the bottom
  453. end of the segment as backing store for the register stack.
  454. Needed on IA64. In this case, we also map the entire stack at
  455. once. According to David Mosberger, that's cheaper. It also
  456. avoids the risk of intermittent failures due to other mappings
  457. in the same region. The cost is that we might be able to map
  458. slightly fewer stacks. */
  459. /* First the main stack: */
  460. map_addr = (caddr_t)((char *)(new_thread + 1) - stacksize / 2);
  461. res_addr = mmap(map_addr, stacksize / 2,
  462. PROT_READ | PROT_WRITE | PROT_EXEC,
  463. MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  464. if (res_addr != map_addr)
  465. {
  466. /* Bad luck, this segment is already mapped. */
  467. if (res_addr != MAP_FAILED)
  468. munmap(res_addr, stacksize / 2);
  469. return -1;
  470. }
  471. /* Then the register stack: */
  472. map_addr = (caddr_t)new_thread_bottom;
  473. res_addr = mmap(map_addr, stacksize/2,
  474. PROT_READ | PROT_WRITE | PROT_EXEC,
  475. MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  476. if (res_addr != map_addr)
  477. {
  478. if (res_addr != MAP_FAILED)
  479. munmap(res_addr, stacksize / 2);
  480. munmap((caddr_t)((char *)(new_thread + 1) - stacksize/2),
  481. stacksize/2);
  482. return -1;
  483. }
  484. guardaddr = new_thread_bottom + stacksize/2;
  485. /* We leave the guard area in the middle unmapped. */
  486. # else /* !NEED_SEPARATE_REGISTER_STACK */
  487. # ifdef _STACK_GROWS_DOWN
  488. new_thread = default_new_thread;
  489. new_thread_bottom = (char *) (new_thread + 1) - stacksize;
  490. map_addr = new_thread_bottom - guardsize;
  491. res_addr = mmap(map_addr, stacksize + guardsize,
  492. PROT_READ | PROT_WRITE | PROT_EXEC,
  493. MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  494. if (res_addr != map_addr)
  495. {
  496. /* Bad luck, this segment is already mapped. */
  497. if (res_addr != MAP_FAILED)
  498. munmap (res_addr, stacksize + guardsize);
  499. return -1;
  500. }
  501. /* We manage to get a stack. Protect the guard area pages if
  502. necessary. */
  503. guardaddr = map_addr;
  504. if (guardsize > 0)
  505. mprotect (guardaddr, guardsize, PROT_NONE);
  506. # else
  507. /* The thread description goes at the bottom of this area, and
  508. * the stack starts directly above it.
  509. */
  510. new_thread = (pthread_descr)((unsigned long)default_new_thread &~ (STACK_SIZE - 1));
  511. map_addr = mmap(new_thread, stacksize + guardsize,
  512. PROT_READ | PROT_WRITE | PROT_EXEC,
  513. MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  514. if (map_addr == MAP_FAILED)
  515. return -1;
  516. new_thread_bottom = map_addr + sizeof(*new_thread);
  517. guardaddr = map_addr + stacksize;
  518. if (guardsize > 0)
  519. mprotect (guardaddr, guardsize, PROT_NONE);
  520. # endif /* stack direction */
  521. # endif /* !NEED_SEPARATE_REGISTER_STACK */
  522. #endif /* !FLOATING_STACKS */
  523. }
  524. *out_new_thread = (char *) new_thread;
  525. *out_new_thread_bottom = new_thread_bottom;
  526. *out_guardaddr = guardaddr;
  527. *out_guardsize = guardsize;
  528. #ifdef NEED_SEPARATE_REGISTER_STACK
  529. *out_stacksize = stacksize / 2;
  530. #else
  531. *out_stacksize = stacksize;
  532. #endif
  533. return 0;
  534. }
  535. static int pthread_handle_create(pthread_t *thread, const pthread_attr_t *attr,
  536. void * (*start_routine)(void *), void *arg,
  537. sigset_t * mask, int father_pid,
  538. int report_events,
  539. td_thr_events_t *event_maskp)
  540. {
  541. size_t sseg;
  542. int pid;
  543. pthread_descr new_thread;
  544. char *stack_addr;
  545. char * new_thread_bottom;
  546. pthread_t new_thread_id;
  547. char *guardaddr = NULL;
  548. size_t guardsize = 0, stksize = 0;
  549. int pagesize = __getpagesize();
  550. int saved_errno = 0;
  551. #ifdef USE_TLS
  552. new_thread = _dl_allocate_tls (NULL);
  553. if (new_thread == NULL)
  554. return EAGAIN;
  555. # if TLS_DTV_AT_TP
  556. /* pthread_descr is below TP. */
  557. new_thread = (pthread_descr) ((char *) new_thread - TLS_PRE_TCB_SIZE);
  558. # endif
  559. #else
  560. /* Prevent warnings. */
  561. new_thread = NULL;
  562. #endif
  563. /* First check whether we have to change the policy and if yes, whether
  564. we can do this. Normally this should be done by examining the
  565. return value of the __sched_setscheduler call in pthread_start_thread
  566. but this is hard to implement. FIXME */
  567. if (attr != NULL && attr->__schedpolicy != SCHED_OTHER && geteuid () != 0)
  568. return EPERM;
  569. /* Find a free segment for the thread, and allocate a stack if needed */
  570. for (sseg = 2; ; sseg++)
  571. {
  572. if (sseg >= PTHREAD_THREADS_MAX)
  573. {
  574. #ifdef USE_TLS
  575. # if TLS_DTV_AT_TP
  576. new_thread = (pthread_descr) ((char *) new_thread + TLS_PRE_TCB_SIZE);
  577. # endif
  578. _dl_deallocate_tls (new_thread, true);
  579. #endif
  580. return EAGAIN;
  581. }
  582. if (__pthread_handles[sseg].h_descr != NULL)
  583. continue;
  584. if (pthread_allocate_stack(attr, thread_segment(sseg),
  585. pagesize, &stack_addr, &new_thread_bottom,
  586. &guardaddr, &guardsize, &stksize) == 0)
  587. {
  588. #ifdef USE_TLS
  589. new_thread->p_stackaddr = stack_addr;
  590. #else
  591. new_thread = (pthread_descr) stack_addr;
  592. #endif
  593. break;
  594. #ifndef __ARCH_HAS_MMU__
  595. } else {
  596. /* When there is MMU, mmap () is used to allocate the stack. If one
  597. * segment is already mapped, we should continue to see if we can
  598. * use the next one. However, when there is no MMU, malloc () is used.
  599. * It's waste of CPU cycles to continue to try if it fails. */
  600. return EAGAIN;
  601. #endif
  602. }
  603. }
  604. __pthread_handles_num++;
  605. /* Allocate new thread identifier */
  606. pthread_threads_counter += PTHREAD_THREADS_MAX;
  607. new_thread_id = sseg + pthread_threads_counter;
  608. /* Initialize the thread descriptor. Elements which have to be
  609. initialized to zero already have this value. */
  610. #if !defined USE_TLS || !TLS_DTV_AT_TP
  611. new_thread->p_header.data.tcb = new_thread;
  612. new_thread->p_header.data.self = new_thread;
  613. #endif
  614. #if TLS_MULTIPLE_THREADS_IN_TCB || !defined USE_TLS || !TLS_DTV_AT_TP
  615. new_thread->p_multiple_threads = 1;
  616. #endif
  617. new_thread->p_tid = new_thread_id;
  618. new_thread->p_lock = &(__pthread_handles[sseg].h_lock);
  619. new_thread->p_cancelstate = PTHREAD_CANCEL_ENABLE;
  620. new_thread->p_canceltype = PTHREAD_CANCEL_DEFERRED;
  621. #if !(USE_TLS && HAVE___THREAD)
  622. new_thread->p_errnop = &new_thread->p_errno;
  623. new_thread->p_h_errnop = &new_thread->p_h_errno;
  624. new_thread->p_resp = &new_thread->p_res;
  625. #endif
  626. new_thread->p_guardaddr = guardaddr;
  627. new_thread->p_guardsize = guardsize;
  628. new_thread->p_nr = sseg;
  629. new_thread->p_inheritsched = attr ? attr->__inheritsched : 0;
  630. new_thread->p_alloca_cutoff = stksize / 4 > __MAX_ALLOCA_CUTOFF
  631. ? __MAX_ALLOCA_CUTOFF : stksize / 4;
  632. /* Initialize the thread handle */
  633. __pthread_init_lock(&__pthread_handles[sseg].h_lock);
  634. __pthread_handles[sseg].h_descr = new_thread;
  635. __pthread_handles[sseg].h_bottom = new_thread_bottom;
  636. /* Determine scheduling parameters for the thread */
  637. new_thread->p_start_args.schedpolicy = -1;
  638. if (attr != NULL) {
  639. new_thread->p_detached = attr->__detachstate;
  640. new_thread->p_userstack = attr->__stackaddr_set;
  641. switch(attr->__inheritsched) {
  642. case PTHREAD_EXPLICIT_SCHED:
  643. new_thread->p_start_args.schedpolicy = attr->__schedpolicy;
  644. memcpy (&new_thread->p_start_args.schedparam, &attr->__schedparam,
  645. sizeof (struct sched_param));
  646. break;
  647. case PTHREAD_INHERIT_SCHED:
  648. new_thread->p_start_args.schedpolicy = __sched_getscheduler(father_pid);
  649. __sched_getparam(father_pid, &new_thread->p_start_args.schedparam);
  650. break;
  651. }
  652. new_thread->p_priority =
  653. new_thread->p_start_args.schedparam.sched_priority;
  654. }
  655. /* Finish setting up arguments to pthread_start_thread */
  656. new_thread->p_start_args.start_routine = start_routine;
  657. new_thread->p_start_args.arg = arg;
  658. new_thread->p_start_args.mask = *mask;
  659. /* Make the new thread ID available already now. If any of the later
  660. functions fail we return an error value and the caller must not use
  661. the stored thread ID. */
  662. *thread = new_thread_id;
  663. /* Raise priority of thread manager if needed */
  664. __pthread_manager_adjust_prio(new_thread->p_priority);
  665. /* Do the cloning. We have to use two different functions depending
  666. on whether we are debugging or not. */
  667. pid = 0; /* Note that the thread never can have PID zero. */
  668. if (report_events)
  669. {
  670. /* See whether the TD_CREATE event bit is set in any of the
  671. masks. */
  672. int idx = __td_eventword (TD_CREATE);
  673. uint32_t mask = __td_eventmask (TD_CREATE);
  674. if ((mask & (__pthread_threads_events.event_bits[idx]
  675. | event_maskp->event_bits[idx])) != 0)
  676. {
  677. /* Lock the mutex the child will use now so that it will stop. */
  678. __pthread_lock(new_thread->p_lock, NULL);
  679. /* We have to report this event. */
  680. #ifdef NEED_SEPARATE_REGISTER_STACK
  681. /* Perhaps this version should be used on all platforms. But
  682. this requires that __clone2 be uniformly supported
  683. everywhere.
  684. And there is some argument for changing the __clone2
  685. interface to pass sp and bsp instead, making it more IA64
  686. specific, but allowing stacks to grow outward from each
  687. other, to get less paging and fewer mmaps. */
  688. pid = __clone2(pthread_start_thread_event,
  689. (void **)new_thread_bottom,
  690. (char *)stack_addr - new_thread_bottom,
  691. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
  692. __pthread_sig_cancel, new_thread);
  693. #elif _STACK_GROWS_UP
  694. pid = __clone(pthread_start_thread_event, (void *) new_thread_bottom,
  695. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
  696. __pthread_sig_cancel, new_thread);
  697. #else
  698. pid = __clone(pthread_start_thread_event, stack_addr,
  699. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
  700. __pthread_sig_cancel, new_thread);
  701. #endif
  702. saved_errno = errno;
  703. if (pid != -1)
  704. {
  705. /* Now fill in the information about the new thread in
  706. the newly created thread's data structure. We cannot let
  707. the new thread do this since we don't know whether it was
  708. already scheduled when we send the event. */
  709. new_thread->p_eventbuf.eventdata = new_thread;
  710. new_thread->p_eventbuf.eventnum = TD_CREATE;
  711. __pthread_last_event = new_thread;
  712. /* We have to set the PID here since the callback function
  713. in the debug library will need it and we cannot guarantee
  714. the child got scheduled before the debugger. */
  715. new_thread->p_pid = pid;
  716. /* Now call the function which signals the event. */
  717. __linuxthreads_create_event ();
  718. /* Now restart the thread. */
  719. __pthread_unlock(new_thread->p_lock);
  720. }
  721. }
  722. }
  723. if (pid == 0)
  724. {
  725. #ifdef NEED_SEPARATE_REGISTER_STACK
  726. pid = __clone2(pthread_start_thread,
  727. (void **)new_thread_bottom,
  728. (char *)stack_addr - new_thread_bottom,
  729. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
  730. __pthread_sig_cancel, new_thread);
  731. #elif _STACK_GROWS_UP
  732. pid = __clone(pthread_start_thread, (void *) new_thread_bottom,
  733. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
  734. __pthread_sig_cancel, new_thread);
  735. #else
  736. pid = __clone(pthread_start_thread, stack_addr,
  737. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
  738. __pthread_sig_cancel, new_thread);
  739. #endif /* !NEED_SEPARATE_REGISTER_STACK */
  740. saved_errno = errno;
  741. }
  742. /* Check if cloning succeeded */
  743. if (pid == -1) {
  744. /* Free the stack if we allocated it */
  745. if (attr == NULL || !attr->__stackaddr_set)
  746. {
  747. #ifdef NEED_SEPARATE_REGISTER_STACK
  748. size_t stacksize = ((char *)(new_thread->p_guardaddr)
  749. - new_thread_bottom);
  750. munmap((caddr_t)new_thread_bottom,
  751. 2 * stacksize + new_thread->p_guardsize);
  752. #elif _STACK_GROWS_UP
  753. # ifdef USE_TLS
  754. size_t stacksize = guardaddr - stack_addr;
  755. munmap(stack_addr, stacksize + guardsize);
  756. # else
  757. size_t stacksize = guardaddr - (char *)new_thread;
  758. munmap(new_thread, stacksize + guardsize);
  759. # endif
  760. #else
  761. # ifdef USE_TLS
  762. size_t stacksize = stack_addr - new_thread_bottom;
  763. # else
  764. size_t stacksize = (char *)(new_thread+1) - new_thread_bottom;
  765. # endif
  766. munmap(new_thread_bottom - guardsize, guardsize + stacksize);
  767. #endif
  768. }
  769. #ifdef USE_TLS
  770. # if TLS_DTV_AT_TP
  771. new_thread = (pthread_descr) ((char *) new_thread + TLS_PRE_TCB_SIZE);
  772. # endif
  773. _dl_deallocate_tls (new_thread, true);
  774. #endif
  775. __pthread_handles[sseg].h_descr = NULL;
  776. __pthread_handles[sseg].h_bottom = NULL;
  777. __pthread_handles_num--;
  778. return saved_errno;
  779. }
  780. /* Insert new thread in doubly linked list of active threads */
  781. new_thread->p_prevlive = __pthread_main_thread;
  782. new_thread->p_nextlive = __pthread_main_thread->p_nextlive;
  783. __pthread_main_thread->p_nextlive->p_prevlive = new_thread;
  784. __pthread_main_thread->p_nextlive = new_thread;
  785. /* Set pid field of the new thread, in case we get there before the
  786. child starts. */
  787. new_thread->p_pid = pid;
  788. return 0;
  789. }
  790. /* Try to free the resources of a thread when requested by pthread_join
  791. or pthread_detach on a terminated thread. */
  792. static void pthread_free(pthread_descr th)
  793. {
  794. pthread_handle handle;
  795. pthread_readlock_info *iter, *next;
  796. ASSERT(th->p_exited);
  797. /* Make the handle invalid */
  798. handle = thread_handle(th->p_tid);
  799. __pthread_lock(&handle->h_lock, NULL);
  800. handle->h_descr = NULL;
  801. handle->h_bottom = (char *)(-1L);
  802. __pthread_unlock(&handle->h_lock);
  803. #ifdef FREE_THREAD
  804. FREE_THREAD(th, th->p_nr);
  805. #endif
  806. /* One fewer threads in __pthread_handles */
  807. __pthread_handles_num--;
  808. /* Destroy read lock list, and list of free read lock structures.
  809. If the former is not empty, it means the thread exited while
  810. holding read locks! */
  811. for (iter = th->p_readlock_list; iter != NULL; iter = next)
  812. {
  813. next = iter->pr_next;
  814. free(iter);
  815. }
  816. for (iter = th->p_readlock_free; iter != NULL; iter = next)
  817. {
  818. next = iter->pr_next;
  819. free(iter);
  820. }
  821. /* If initial thread, nothing to free */
  822. if (!th->p_userstack)
  823. {
  824. size_t guardsize = th->p_guardsize;
  825. /* Free the stack and thread descriptor area */
  826. char *guardaddr = th->p_guardaddr;
  827. #ifdef _STACK_GROWS_UP
  828. # ifdef USE_TLS
  829. size_t stacksize = guardaddr - th->p_stackaddr;
  830. # else
  831. size_t stacksize = guardaddr - (char *)th;
  832. # endif
  833. guardaddr = (char *)th;
  834. #else
  835. /* Guardaddr is always set, even if guardsize is 0. This allows
  836. us to compute everything else. */
  837. # ifdef USE_TLS
  838. size_t stacksize = th->p_stackaddr - guardaddr - guardsize;
  839. # else
  840. size_t stacksize = (char *)(th+1) - guardaddr - guardsize;
  841. # endif
  842. # ifdef NEED_SEPARATE_REGISTER_STACK
  843. /* Take account of the register stack, which is below guardaddr. */
  844. guardaddr -= stacksize;
  845. stacksize *= 2;
  846. # endif
  847. #endif
  848. /* Unmap the stack. */
  849. munmap(guardaddr, stacksize + guardsize);
  850. }
  851. #ifdef USE_TLS
  852. # if TLS_DTV_AT_TP
  853. th = (pthread_descr) ((char *) th + TLS_PRE_TCB_SIZE);
  854. # endif
  855. _dl_deallocate_tls (th, true);
  856. #endif
  857. }
  858. /* Handle threads that have exited */
  859. static void pthread_exited(pid_t pid)
  860. {
  861. pthread_descr th;
  862. int detached;
  863. /* Find thread with that pid */
  864. for (th = __pthread_main_thread->p_nextlive;
  865. th != __pthread_main_thread;
  866. th = th->p_nextlive) {
  867. if (th->p_pid == pid) {
  868. /* Remove thread from list of active threads */
  869. th->p_nextlive->p_prevlive = th->p_prevlive;
  870. th->p_prevlive->p_nextlive = th->p_nextlive;
  871. /* Mark thread as exited, and if detached, free its resources */
  872. __pthread_lock(th->p_lock, NULL);
  873. th->p_exited = 1;
  874. /* If we have to signal this event do it now. */
  875. if (th->p_report_events)
  876. {
  877. /* See whether TD_REAP is in any of the mask. */
  878. int idx = __td_eventword (TD_REAP);
  879. uint32_t mask = __td_eventmask (TD_REAP);
  880. if ((mask & (__pthread_threads_events.event_bits[idx]
  881. | th->p_eventbuf.eventmask.event_bits[idx])) != 0)
  882. {
  883. /* Yep, we have to signal the reapage. */
  884. th->p_eventbuf.eventnum = TD_REAP;
  885. th->p_eventbuf.eventdata = th;
  886. __pthread_last_event = th;
  887. /* Now call the function to signal the event. */
  888. __linuxthreads_reap_event();
  889. }
  890. }
  891. detached = th->p_detached;
  892. __pthread_unlock(th->p_lock);
  893. if (detached)
  894. pthread_free(th);
  895. break;
  896. }
  897. }
  898. /* If all threads have exited and the main thread is pending on a
  899. pthread_exit, wake up the main thread and terminate ourselves. */
  900. if (main_thread_exiting &&
  901. __pthread_main_thread->p_nextlive == __pthread_main_thread) {
  902. restart(__pthread_main_thread);
  903. /* Same logic as REQ_MAIN_THREAD_EXIT. */
  904. }
  905. }
  906. static void pthread_reap_children(void)
  907. {
  908. pid_t pid;
  909. int status;
  910. while ((pid = waitpid_not_cancel(-1, &status, WNOHANG | __WCLONE)) > 0) {
  911. pthread_exited(pid);
  912. if (WIFSIGNALED(status)) {
  913. /* If a thread died due to a signal, send the same signal to
  914. all other threads, including the main thread. */
  915. pthread_kill_all_threads(WTERMSIG(status), 1);
  916. _exit(0);
  917. }
  918. }
  919. }
  920. /* Try to free the resources of a thread when requested by pthread_join
  921. or pthread_detach on a terminated thread. */
  922. static void pthread_handle_free(pthread_t th_id)
  923. {
  924. pthread_handle handle = thread_handle(th_id);
  925. pthread_descr th;
  926. __pthread_lock(&handle->h_lock, NULL);
  927. if (nonexisting_handle(handle, th_id)) {
  928. /* pthread_reap_children has deallocated the thread already,
  929. nothing needs to be done */
  930. __pthread_unlock(&handle->h_lock);
  931. return;
  932. }
  933. th = handle->h_descr;
  934. if (th->p_exited) {
  935. __pthread_unlock(&handle->h_lock);
  936. pthread_free(th);
  937. } else {
  938. /* The Unix process of the thread is still running.
  939. Mark the thread as detached so that the thread manager will
  940. deallocate its resources when the Unix process exits. */
  941. th->p_detached = 1;
  942. __pthread_unlock(&handle->h_lock);
  943. }
  944. }
  945. /* Send a signal to all running threads */
  946. static void pthread_kill_all_threads(int sig, int main_thread_also)
  947. {
  948. pthread_descr th;
  949. for (th = __pthread_main_thread->p_nextlive;
  950. th != __pthread_main_thread;
  951. th = th->p_nextlive) {
  952. kill(th->p_pid, sig);
  953. }
  954. if (main_thread_also) {
  955. kill(__pthread_main_thread->p_pid, sig);
  956. }
  957. }
  958. static void pthread_for_each_thread(void *arg,
  959. void (*fn)(void *, pthread_descr))
  960. {
  961. pthread_descr th;
  962. for (th = __pthread_main_thread->p_nextlive;
  963. th != __pthread_main_thread;
  964. th = th->p_nextlive) {
  965. fn(arg, th);
  966. }
  967. fn(arg, __pthread_main_thread);
  968. }
  969. /* Process-wide exit() */
  970. static void pthread_handle_exit(pthread_descr issuing_thread, int exitcode)
  971. {
  972. pthread_descr th;
  973. __pthread_exit_requested = 1;
  974. __pthread_exit_code = exitcode;
  975. /* A forced asynchronous cancellation follows. Make sure we won't
  976. get stuck later in the main thread with a system lock being held
  977. by one of the cancelled threads. Ideally one would use the same
  978. code as in pthread_atfork(), but we can't distinguish system and
  979. user handlers there. */
  980. __flockfilelist();
  981. /* Send the CANCEL signal to all running threads, including the main
  982. thread, but excluding the thread from which the exit request originated
  983. (that thread must complete the exit, e.g. calling atexit functions
  984. and flushing stdio buffers). */
  985. for (th = issuing_thread->p_nextlive;
  986. th != issuing_thread;
  987. th = th->p_nextlive) {
  988. kill(th->p_pid, __pthread_sig_cancel);
  989. }
  990. /* Now, wait for all these threads, so that they don't become zombies
  991. and their times are properly added to the thread manager's times. */
  992. for (th = issuing_thread->p_nextlive;
  993. th != issuing_thread;
  994. th = th->p_nextlive) {
  995. waitpid(th->p_pid, NULL, __WCLONE);
  996. }
  997. __fresetlockfiles();
  998. restart(issuing_thread);
  999. _exit(0);
  1000. }
  1001. /* Handler for __pthread_sig_cancel in thread manager thread */
  1002. void __pthread_manager_sighandler(int sig)
  1003. {
  1004. int kick_manager = terminated_children == 0 && main_thread_exiting;
  1005. terminated_children = 1;
  1006. /* If the main thread is terminating, kick the thread manager loop
  1007. each time some threads terminate. This eliminates a two second
  1008. shutdown delay caused by the thread manager sleeping in the
  1009. call to __poll(). Instead, the thread manager is kicked into
  1010. action, reaps the outstanding threads and resumes the main thread
  1011. so that it can complete the shutdown. */
  1012. if (kick_manager) {
  1013. struct pthread_request request;
  1014. request.req_thread = 0;
  1015. request.req_kind = REQ_KICK;
  1016. TEMP_FAILURE_RETRY(write_not_cancel(__pthread_manager_request,
  1017. (char *) &request, sizeof(request)));
  1018. }
  1019. }
  1020. /* Adjust priority of thread manager so that it always run at a priority
  1021. higher than all threads */
  1022. void __pthread_manager_adjust_prio(int thread_prio)
  1023. {
  1024. struct sched_param param;
  1025. if (thread_prio <= manager_thread->p_priority) return;
  1026. param.sched_priority =
  1027. thread_prio < __sched_get_priority_max(SCHED_FIFO)
  1028. ? thread_prio + 1 : thread_prio;
  1029. __sched_setscheduler(manager_thread->p_pid, SCHED_FIFO, &param);
  1030. manager_thread->p_priority = thread_prio;
  1031. }