pthread_create.c 17 KB

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