manager.c 37 KB

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