pthread_create.c 16 KB

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