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. /* Initialize resolver state pointer. */
  190. __resp = &pd->res;
  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. #ifdef _STACK_GROWS_DOWN
  315. char *sp = CURRENT_STACK_FRAME;
  316. size_t freesize = (sp - (char *) pd->stackblock) & ~pagesize_m1;
  317. #else
  318. # error "to do"
  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. #ifdef 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)