pthread_create.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. /* Copyright (C) 2002-2007,2008,2009 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. Contributed by Ulrich Drepper <drepper@redhat.com>, 2002.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include <errno.h>
  16. #include <stdbool.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include "pthreadP.h"
  20. #include <hp-timing.h>
  21. #include <ldsodefs.h>
  22. #include <atomic.h>
  23. #include <resolv.h>
  24. #include <bits/kernel-features.h>
  25. /* Local function to start thread and handle cleanup. */
  26. static int start_thread (void *arg);
  27. /* Nozero if debugging mode is enabled. */
  28. int __pthread_debug;
  29. /* Globally enabled events. */
  30. static td_thr_events_t __nptl_threads_events __attribute_used__;
  31. /* Pointer to descriptor with the last event. */
  32. static struct pthread *__nptl_last_event __attribute_used__;
  33. /* Number of threads running. */
  34. unsigned int __nptl_nthreads = 1;
  35. /* Code to allocate and deallocate a stack. */
  36. #include "allocatestack.c"
  37. /* Code to create the thread. */
  38. #include <createthread.c>
  39. struct pthread *
  40. internal_function
  41. __find_in_stack_list (
  42. struct pthread *pd)
  43. {
  44. list_t *entry;
  45. struct pthread *result = NULL;
  46. lll_lock (stack_cache_lock, LLL_PRIVATE);
  47. list_for_each (entry, &stack_used)
  48. {
  49. struct pthread *curp;
  50. curp = list_entry (entry, struct pthread, list);
  51. if (curp == pd)
  52. {
  53. result = curp;
  54. break;
  55. }
  56. }
  57. if (result == NULL)
  58. list_for_each (entry, &__stack_user)
  59. {
  60. struct pthread *curp;
  61. curp = list_entry (entry, struct pthread, list);
  62. if (curp == pd)
  63. {
  64. result = curp;
  65. break;
  66. }
  67. }
  68. lll_unlock (stack_cache_lock, LLL_PRIVATE);
  69. return result;
  70. }
  71. /* Deallocate POSIX thread-local-storage. */
  72. void
  73. attribute_hidden
  74. __nptl_deallocate_tsd (void)
  75. {
  76. struct pthread *self = THREAD_SELF;
  77. /* Maybe no data was ever allocated. This happens often so we have
  78. a flag for this. */
  79. if (THREAD_GETMEM (self, specific_used))
  80. {
  81. size_t round;
  82. size_t cnt;
  83. round = 0;
  84. do
  85. {
  86. size_t idx;
  87. /* So far no new nonzero data entry. */
  88. THREAD_SETMEM (self, specific_used, false);
  89. for (cnt = idx = 0; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
  90. {
  91. struct pthread_key_data *level2;
  92. level2 = THREAD_GETMEM_NC (self, specific, cnt);
  93. if (level2 != NULL)
  94. {
  95. size_t inner;
  96. for (inner = 0; inner < PTHREAD_KEY_2NDLEVEL_SIZE;
  97. ++inner, ++idx)
  98. {
  99. void *data = level2[inner].data;
  100. if (data != NULL)
  101. {
  102. /* Always clear the data. */
  103. level2[inner].data = NULL;
  104. /* Make sure the data corresponds to a valid
  105. key. This test fails if the key was
  106. deallocated and also if it was
  107. re-allocated. It is the user's
  108. responsibility to free the memory in this
  109. case. */
  110. if (level2[inner].seq
  111. == __pthread_keys[idx].seq
  112. /* It is not necessary to register a destructor
  113. function. */
  114. && __pthread_keys[idx].destr != NULL)
  115. /* Call the user-provided destructor. */
  116. __pthread_keys[idx].destr (data);
  117. }
  118. }
  119. }
  120. else
  121. idx += PTHREAD_KEY_1STLEVEL_SIZE;
  122. }
  123. if (THREAD_GETMEM (self, specific_used) == 0)
  124. /* No data has been modified. */
  125. goto just_free;
  126. }
  127. /* We only repeat the process a fixed number of times. */
  128. while (__builtin_expect (++round < PTHREAD_DESTRUCTOR_ITERATIONS, 0));
  129. /* Just clear the memory of the first block for reuse. */
  130. memset (&THREAD_SELF->specific_1stblock, '\0',
  131. sizeof (self->specific_1stblock));
  132. just_free:
  133. /* Free the memory for the other blocks. */
  134. for (cnt = 1; cnt < PTHREAD_KEY_1STLEVEL_SIZE; ++cnt)
  135. {
  136. struct pthread_key_data *level2;
  137. level2 = THREAD_GETMEM_NC (self, specific, cnt);
  138. if (level2 != NULL)
  139. {
  140. /* The first block is allocated as part of the thread
  141. descriptor. */
  142. free (level2);
  143. THREAD_SETMEM_NC (self, specific, cnt, NULL);
  144. }
  145. }
  146. THREAD_SETMEM (self, specific_used, false);
  147. }
  148. }
  149. /* Deallocate a thread's stack after optionally making sure the thread
  150. descriptor is still valid. */
  151. void
  152. internal_function
  153. __free_tcb (struct pthread *pd)
  154. {
  155. /* The thread is exiting now. */
  156. if (__builtin_expect (atomic_bit_test_set (&pd->cancelhandling,
  157. TERMINATED_BIT) == 0, 1))
  158. {
  159. /* Remove the descriptor from the list. */
  160. if (DEBUGGING_P && __find_in_stack_list (pd) == NULL)
  161. /* Something is really wrong. The descriptor for a still
  162. running thread is gone. */
  163. abort ();
  164. /* Free TPP data. */
  165. if (__builtin_expect (pd->tpp != NULL, 0))
  166. {
  167. struct priority_protection_data *tpp = pd->tpp;
  168. pd->tpp = NULL;
  169. free (tpp);
  170. }
  171. /* Queue the stack memory block for reuse and exit the process. The
  172. kernel will signal via writing to the address returned by
  173. QUEUE-STACK when the stack is available. */
  174. __deallocate_stack (pd);
  175. }
  176. }
  177. static int
  178. start_thread (void *arg)
  179. {
  180. struct pthread *pd = (struct pthread *) arg;
  181. #if HP_TIMING_AVAIL
  182. /* Remember the time when the thread was started. */
  183. hp_timing_t now;
  184. HP_TIMING_NOW (now);
  185. THREAD_SETMEM (pd, cpuclock_offset, now);
  186. #endif
  187. #if defined __UCLIBC_HAS_RESOLVER_SUPPORT__
  188. /* Initialize resolver state pointer. */
  189. __resp = &pd->res;
  190. #endif
  191. #ifdef __NR_set_robust_list
  192. # ifndef __ASSUME_SET_ROBUST_LIST
  193. if (__set_robust_list_avail >= 0)
  194. # endif
  195. {
  196. INTERNAL_SYSCALL_DECL (err);
  197. /* This call should never fail because the initial call in init.c
  198. succeeded. */
  199. INTERNAL_SYSCALL (set_robust_list, err, 2, &pd->robust_head,
  200. sizeof (struct robust_list_head));
  201. }
  202. #endif
  203. /* If the parent was running cancellation handlers while creating
  204. the thread the new thread inherited the signal mask. Reset the
  205. cancellation signal mask. */
  206. if (__builtin_expect (pd->parent_cancelhandling & CANCELING_BITMASK, 0))
  207. {
  208. INTERNAL_SYSCALL_DECL (err);
  209. sigset_t mask;
  210. __sigemptyset (&mask);
  211. __sigaddset (&mask, SIGCANCEL);
  212. (void) INTERNAL_SYSCALL (rt_sigprocmask, err, 4, SIG_UNBLOCK, &mask,
  213. NULL, _NSIG / 8);
  214. }
  215. /* This is where the try/finally block should be created. For
  216. compilers without that support we do use setjmp. */
  217. struct pthread_unwind_buf unwind_buf;
  218. /* No previous handlers. */
  219. unwind_buf.priv.data.prev = NULL;
  220. unwind_buf.priv.data.cleanup = NULL;
  221. int not_first_call;
  222. not_first_call = setjmp ((struct __jmp_buf_tag *) unwind_buf.cancel_jmp_buf);
  223. if (__builtin_expect (! not_first_call, 1))
  224. {
  225. /* Store the new cleanup handler info. */
  226. THREAD_SETMEM (pd, cleanup_jmp_buf, &unwind_buf);
  227. if (__builtin_expect (pd->stopped_start, 0))
  228. {
  229. int oldtype = CANCEL_ASYNC ();
  230. /* Get the lock the parent locked to force synchronization. */
  231. lll_lock (pd->lock, LLL_PRIVATE);
  232. /* And give it up right away. */
  233. lll_unlock (pd->lock, LLL_PRIVATE);
  234. CANCEL_RESET (oldtype);
  235. }
  236. /* Run the code the user provided. */
  237. #ifdef CALL_THREAD_FCT
  238. THREAD_SETMEM (pd, result, CALL_THREAD_FCT (pd));
  239. #else
  240. THREAD_SETMEM (pd, result, pd->start_routine (pd->arg));
  241. #endif
  242. }
  243. /* Run the destructor for the thread-local data. */
  244. __nptl_deallocate_tsd ();
  245. /* Clean up any state libc stored in thread-local variables. */
  246. /* disable for now
  247. __libc_thread_freeres ();
  248. */
  249. /* If this is the last thread we terminate the process now. We
  250. do not notify the debugger, it might just irritate it if there
  251. is no thread left. */
  252. if (__builtin_expect (atomic_decrement_and_test (&__nptl_nthreads), 0))
  253. /* This was the last thread. */
  254. exit (0);
  255. /* Report the death of the thread if this is wanted. */
  256. if (__builtin_expect (pd->report_events, 0))
  257. {
  258. /* See whether TD_DEATH is in any of the mask. */
  259. const int idx = __td_eventword (TD_DEATH);
  260. const uint32_t mask = __td_eventmask (TD_DEATH);
  261. if ((mask & (__nptl_threads_events.event_bits[idx]
  262. | pd->eventbuf.eventmask.event_bits[idx])) != 0)
  263. {
  264. /* Yep, we have to signal the death. Add the descriptor to
  265. the list but only if it is not already on it. */
  266. if (pd->nextevent == NULL)
  267. {
  268. pd->eventbuf.eventnum = TD_DEATH;
  269. pd->eventbuf.eventdata = pd;
  270. do
  271. pd->nextevent = __nptl_last_event;
  272. while (atomic_compare_and_exchange_bool_acq (&__nptl_last_event,
  273. pd, pd->nextevent));
  274. }
  275. /* Now call the function to signal the event. */
  276. __nptl_death_event ();
  277. }
  278. }
  279. /* The thread is exiting now. Don't set this bit until after we've hit
  280. the event-reporting breakpoint, so that td_thr_get_info on us while at
  281. the breakpoint reports TD_THR_RUN state rather than TD_THR_ZOMBIE. */
  282. atomic_bit_set (&pd->cancelhandling, EXITING_BIT);
  283. #ifndef __ASSUME_SET_ROBUST_LIST
  284. /* If this thread has any robust mutexes locked, handle them now. */
  285. # if __WORDSIZE == 64
  286. void *robust = pd->robust_head.list;
  287. # else
  288. __pthread_slist_t *robust = pd->robust_list.__next;
  289. # endif
  290. /* We let the kernel do the notification if it is able to do so.
  291. If we have to do it here there for sure are no PI mutexes involved
  292. since the kernel support for them is even more recent. */
  293. if (__set_robust_list_avail < 0
  294. && __builtin_expect (robust != (void *) &pd->robust_head, 0))
  295. {
  296. do
  297. {
  298. struct __pthread_mutex_s *this = (struct __pthread_mutex_s *)
  299. ((char *) robust - offsetof (struct __pthread_mutex_s,
  300. __list.__next));
  301. robust = *((void **) robust);
  302. # ifdef __PTHREAD_MUTEX_HAVE_PREV
  303. this->__list.__prev = NULL;
  304. # endif
  305. this->__list.__next = NULL;
  306. lll_robust_dead (this->__lock, /* XYZ */ LLL_SHARED);
  307. }
  308. while (robust != (void *) &pd->robust_head);
  309. }
  310. #endif
  311. /* Mark the memory of the stack as usable to the kernel. We free
  312. everything except for the space used for the TCB itself. */
  313. size_t pagesize_m1 = __getpagesize () - 1;
  314. char *sp = CURRENT_STACK_FRAME;
  315. #ifdef _STACK_GROWS_DOWN
  316. size_t freesize = (sp - (char *) pd->stackblock) & ~pagesize_m1;
  317. #else
  318. size_t freesize = ((char *) pd->stackblock - sp) & ~pagesize_m1;
  319. #endif
  320. assert (freesize < pd->stackblock_size);
  321. if (freesize > PTHREAD_STACK_MIN)
  322. madvise (pd->stackblock, freesize - PTHREAD_STACK_MIN, MADV_DONTNEED);
  323. /* If the thread is detached free the TCB. */
  324. if (IS_DETACHED (pd))
  325. /* Free the TCB. */
  326. __free_tcb (pd);
  327. else if (__builtin_expect (pd->cancelhandling & SETXID_BITMASK, 0))
  328. {
  329. /* Some other thread might call any of the setXid functions and expect
  330. us to reply. In this case wait until we did that. */
  331. do
  332. lll_futex_wait (&pd->setxid_futex, 0, LLL_PRIVATE);
  333. while (pd->cancelhandling & SETXID_BITMASK);
  334. /* Reset the value so that the stack can be reused. */
  335. pd->setxid_futex = 0;
  336. }
  337. /* We cannot call '_exit' here. '_exit' will terminate the process.
  338. The 'exit' implementation in the kernel will signal when the
  339. process is really dead since 'clone' got passed the CLONE_CLEARTID
  340. flag. The 'tid' field in the TCB will be set to zero.
  341. The exit code is zero since in case all threads exit by calling
  342. 'pthread_exit' the exit status must be 0 (zero). */
  343. __exit_thread_inline (0);
  344. /* NOTREACHED */
  345. return 0;
  346. }
  347. /* Default thread attributes for the case when the user does not
  348. provide any. */
  349. static const struct pthread_attr default_attr =
  350. {
  351. /* Just some value > 0 which gets rounded to the nearest page size. */
  352. .guardsize = 1,
  353. };
  354. int
  355. __pthread_create_2_1 (
  356. pthread_t *newthread,
  357. const pthread_attr_t *attr,
  358. void *(*start_routine) (void *),
  359. void *arg)
  360. {
  361. STACK_VARIABLES;
  362. const struct pthread_attr *iattr = (struct pthread_attr *) attr;
  363. if (iattr == NULL)
  364. /* Is this the best idea? On NUMA machines this could mean
  365. accessing far-away memory. */
  366. iattr = &default_attr;
  367. struct pthread *pd = NULL;
  368. int err = ALLOCATE_STACK (iattr, &pd);
  369. if (__builtin_expect (err != 0, 0))
  370. /* Something went wrong. Maybe a parameter of the attributes is
  371. invalid or we could not allocate memory. */
  372. return err;
  373. /* Initialize the TCB. All initializations with zero should be
  374. performed in 'get_cached_stack'. This way we avoid doing this if
  375. the stack freshly allocated with 'mmap'. */
  376. #if TLS_TCB_AT_TP
  377. /* Reference to the TCB itself. */
  378. pd->header.self = pd;
  379. /* Self-reference for TLS. */
  380. pd->header.tcb = pd;
  381. #endif
  382. /* Store the address of the start routine and the parameter. Since
  383. we do not start the function directly the stillborn thread will
  384. get the information from its thread descriptor. */
  385. pd->start_routine = start_routine;
  386. pd->arg = arg;
  387. /* Copy the thread attribute flags. */
  388. struct pthread *self = THREAD_SELF;
  389. pd->flags = ((iattr->flags & ~(ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET))
  390. | (self->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)));
  391. /* Initialize the field for the ID of the thread which is waiting
  392. for us. This is a self-reference in case the thread is created
  393. detached. */
  394. pd->joinid = iattr->flags & ATTR_FLAG_DETACHSTATE ? pd : NULL;
  395. /* The debug events are inherited from the parent. */
  396. pd->eventbuf = self->eventbuf;
  397. /* Copy the parent's scheduling parameters. The flags will say what
  398. is valid and what is not. */
  399. pd->schedpolicy = self->schedpolicy;
  400. pd->schedparam = self->schedparam;
  401. /* Copy the stack guard canary. */
  402. #ifdef THREAD_COPY_STACK_GUARD
  403. THREAD_COPY_STACK_GUARD (pd);
  404. #endif
  405. /* Copy the pointer guard value. */
  406. #ifdef THREAD_COPY_POINTER_GUARD
  407. THREAD_COPY_POINTER_GUARD (pd);
  408. #endif
  409. /* Determine scheduling parameters for the thread. */
  410. if (attr != NULL
  411. && __builtin_expect ((iattr->flags & ATTR_FLAG_NOTINHERITSCHED) != 0, 0)
  412. && (iattr->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)) != 0)
  413. {
  414. INTERNAL_SYSCALL_DECL (scerr);
  415. /* Use the scheduling parameters the user provided. */
  416. if (iattr->flags & ATTR_FLAG_POLICY_SET)
  417. pd->schedpolicy = iattr->schedpolicy;
  418. else if ((pd->flags & ATTR_FLAG_POLICY_SET) == 0)
  419. {
  420. pd->schedpolicy = INTERNAL_SYSCALL (sched_getscheduler, scerr, 1, 0);
  421. pd->flags |= ATTR_FLAG_POLICY_SET;
  422. }
  423. if (iattr->flags & ATTR_FLAG_SCHED_SET)
  424. memcpy (&pd->schedparam, &iattr->schedparam,
  425. sizeof (struct sched_param));
  426. else if ((pd->flags & ATTR_FLAG_SCHED_SET) == 0)
  427. {
  428. INTERNAL_SYSCALL (sched_getparam, scerr, 2, 0, &pd->schedparam);
  429. pd->flags |= ATTR_FLAG_SCHED_SET;
  430. }
  431. /* Check for valid priorities. */
  432. int minprio = INTERNAL_SYSCALL (sched_get_priority_min, scerr, 1,
  433. iattr->schedpolicy);
  434. int maxprio = INTERNAL_SYSCALL (sched_get_priority_max, scerr, 1,
  435. iattr->schedpolicy);
  436. if (pd->schedparam.sched_priority < minprio
  437. || pd->schedparam.sched_priority > maxprio)
  438. {
  439. err = EINVAL;
  440. goto errout;
  441. }
  442. }
  443. /* Pass the descriptor to the caller. */
  444. *newthread = (pthread_t) pd;
  445. /* Remember whether the thread is detached or not. In case of an
  446. error we have to free the stacks of non-detached stillborn
  447. threads. */
  448. bool is_detached = IS_DETACHED (pd);
  449. /* Start the thread. */
  450. err = create_thread (pd, iattr, STACK_VARIABLES_ARGS);
  451. if (err != 0)
  452. {
  453. /* Something went wrong. Free the resources. */
  454. if (!is_detached)
  455. {
  456. errout:
  457. __deallocate_stack (pd);
  458. }
  459. return err;
  460. }
  461. return 0;
  462. }
  463. weak_alias(__pthread_create_2_1, pthread_create)
  464. /* Information for libthread_db. */
  465. #include "../nptl_db/db_info.c"
  466. /* If pthread_create is present, libgcc_eh.a and libsupc++.a expects some other POSIX thread
  467. functions to be present as well. */
  468. PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_lock)
  469. PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_trylock)
  470. PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_unlock)
  471. PTHREAD_STATIC_FN_REQUIRE (pthread_once)
  472. PTHREAD_STATIC_FN_REQUIRE (pthread_cancel)
  473. PTHREAD_STATIC_FN_REQUIRE (pthread_key_create)
  474. PTHREAD_STATIC_FN_REQUIRE (pthread_key_delete)
  475. PTHREAD_STATIC_FN_REQUIRE (pthread_setspecific)
  476. PTHREAD_STATIC_FN_REQUIRE (pthread_getspecific)
  477. /* UCLIBC_MUTEX_xxx macros expects to have these as well */
  478. PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_init)
  479. PTHREAD_STATIC_FN_REQUIRE (_pthread_cleanup_push_defer)
  480. PTHREAD_STATIC_FN_REQUIRE (_pthread_cleanup_pop_restore)