pthread_create.c 17 KB

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