pthread_create.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. /* Copyright (C) 2002, 2003, 2004, 2005 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. /* 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;
  32. /* Pointer to descriptor with the last event. */
  33. static struct pthread *__nptl_last_event;
  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 (pd)
  43. struct pthread *pd;
  44. {
  45. list_t *entry;
  46. struct pthread *result = NULL;
  47. lll_lock (stack_cache_lock);
  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);
  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. /* Queue the stack memory block for reuse and exit the process. The
  166. kernel will signal via writing to the address returned by
  167. QUEUE-STACK when the stack is available. */
  168. __deallocate_stack (pd);
  169. }
  170. }
  171. static int
  172. start_thread (void *arg)
  173. {
  174. struct pthread *pd = (struct pthread *) arg;
  175. #if HP_TIMING_AVAIL
  176. /* Remember the time when the thread was started. */
  177. hp_timing_t now;
  178. HP_TIMING_NOW (now);
  179. THREAD_SETMEM (pd, cpuclock_offset, now);
  180. #endif
  181. /* Initialize resolver state pointer. */
  182. __resp = &pd->res;
  183. /* This is where the try/finally block should be created. For
  184. compilers without that support we do use setjmp. */
  185. struct pthread_unwind_buf unwind_buf;
  186. /* No previous handlers. */
  187. unwind_buf.priv.data.prev = NULL;
  188. unwind_buf.priv.data.cleanup = NULL;
  189. int not_first_call;
  190. not_first_call = setjmp ((struct __jmp_buf_tag *) unwind_buf.cancel_jmp_buf);
  191. if (__builtin_expect (! not_first_call, 1))
  192. {
  193. /* Store the new cleanup handler info. */
  194. THREAD_SETMEM (pd, cleanup_jmp_buf, &unwind_buf);
  195. if (__builtin_expect (pd->stopped_start, 0))
  196. {
  197. int oldtype = CANCEL_ASYNC ();
  198. /* Get the lock the parent locked to force synchronization. */
  199. lll_lock (pd->lock);
  200. /* And give it up right away. */
  201. lll_unlock (pd->lock);
  202. CANCEL_RESET (oldtype);
  203. }
  204. /* Run the code the user provided. */
  205. #ifdef CALL_THREAD_FCT
  206. THREAD_SETMEM (pd, result, CALL_THREAD_FCT (pd));
  207. #else
  208. THREAD_SETMEM (pd, result, pd->start_routine (pd->arg));
  209. #endif
  210. }
  211. /* Run the destructor for the thread-local data. */
  212. __nptl_deallocate_tsd ();
  213. /* If this is the last thread we terminate the process now. We
  214. do not notify the debugger, it might just irritate it if there
  215. is no thread left. */
  216. if (__builtin_expect (atomic_decrement_and_test (&__nptl_nthreads), 0))
  217. /* This was the last thread. */
  218. exit (0);
  219. /* Report the death of the thread if this is wanted. */
  220. if (__builtin_expect (pd->report_events, 0))
  221. {
  222. /* See whether TD_DEATH is in any of the mask. */
  223. const int idx = __td_eventword (TD_DEATH);
  224. const uint32_t mask = __td_eventmask (TD_DEATH);
  225. if ((mask & (__nptl_threads_events.event_bits[idx]
  226. | pd->eventbuf.eventmask.event_bits[idx])) != 0)
  227. {
  228. /* Yep, we have to signal the death. Add the descriptor to
  229. the list but only if it is not already on it. */
  230. if (pd->nextevent == NULL)
  231. {
  232. pd->eventbuf.eventnum = TD_DEATH;
  233. pd->eventbuf.eventdata = pd;
  234. do
  235. pd->nextevent = __nptl_last_event;
  236. while (atomic_compare_and_exchange_bool_acq (&__nptl_last_event,
  237. pd, pd->nextevent));
  238. }
  239. /* Now call the function to signal the event. */
  240. __nptl_death_event ();
  241. }
  242. }
  243. /* The thread is exiting now. Don't set this bit until after we've hit
  244. the event-reporting breakpoint, so that td_thr_get_info on us while at
  245. the breakpoint reports TD_THR_RUN state rather than TD_THR_ZOMBIE. */
  246. atomic_bit_set (&pd->cancelhandling, EXITING_BIT);
  247. /* If the thread is detached free the TCB. */
  248. if (IS_DETACHED (pd))
  249. /* Free the TCB. */
  250. __free_tcb (pd);
  251. /* We cannot call '_exit' here. '_exit' will terminate the process.
  252. The 'exit' implementation in the kernel will signal when the
  253. process is really dead since 'clone' got passed the CLONE_CLEARTID
  254. flag. The 'tid' field in the TCB will be set to zero.
  255. The exit code is zero since in case all threads exit by calling
  256. 'pthread_exit' the exit status must be 0 (zero). */
  257. __exit_thread_inline (0);
  258. /* NOTREACHED */
  259. return 0;
  260. }
  261. /* Default thread attributes for the case when the user does not
  262. provide any. */
  263. static const struct pthread_attr default_attr =
  264. {
  265. /* Just some value > 0 which gets rounded to the nearest page size. */
  266. .guardsize = 1,
  267. };
  268. int
  269. __pthread_create_2_1 (newthread, attr, start_routine, arg)
  270. pthread_t *newthread;
  271. const pthread_attr_t *attr;
  272. void *(*start_routine) (void *);
  273. void *arg;
  274. {
  275. STACK_VARIABLES;
  276. const struct pthread_attr *iattr = (struct pthread_attr *) attr;
  277. if (iattr == NULL)
  278. /* Is this the best idea? On NUMA machines this could mean
  279. accessing far-away memory. */
  280. iattr = &default_attr;
  281. struct pthread *pd = 0;
  282. int err = ALLOCATE_STACK (iattr, &pd);
  283. if (__builtin_expect (err != 0, 0))
  284. /* Something went wrong. Maybe a parameter of the attributes is
  285. invalid or we could not allocate memory. */
  286. return err;
  287. /* Initialize the TCB. All initializations with zero should be
  288. performed in 'get_cached_stack'. This way we avoid doing this if
  289. the stack freshly allocated with 'mmap'. */
  290. #ifdef TLS_TCB_AT_TP
  291. /* Reference to the TCB itself. */
  292. pd->header.self = pd;
  293. /* Self-reference for TLS. */
  294. pd->header.tcb = pd;
  295. #endif
  296. /* Store the address of the start routine and the parameter. Since
  297. we do not start the function directly the stillborn thread will
  298. get the information from its thread descriptor. */
  299. pd->start_routine = start_routine;
  300. pd->arg = arg;
  301. /* Copy the thread attribute flags. */
  302. struct pthread *self = THREAD_SELF;
  303. pd->flags = ((iattr->flags & ~(ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET))
  304. | (self->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)));
  305. /* Initialize the field for the ID of the thread which is waiting
  306. for us. This is a self-reference in case the thread is created
  307. detached. */
  308. pd->joinid = iattr->flags & ATTR_FLAG_DETACHSTATE ? pd : NULL;
  309. /* The debug events are inherited from the parent. */
  310. pd->eventbuf = self->eventbuf;
  311. /* Copy the parent's scheduling parameters. The flags will say what
  312. is valid and what is not. */
  313. pd->schedpolicy = self->schedpolicy;
  314. pd->schedparam = self->schedparam;
  315. /* Copy the stack guard canary. */
  316. #ifdef THREAD_COPY_STACK_GUARD
  317. THREAD_COPY_STACK_GUARD (pd);
  318. #endif
  319. /* Determine scheduling parameters for the thread. */
  320. if (attr != NULL
  321. && __builtin_expect ((iattr->flags & ATTR_FLAG_NOTINHERITSCHED) != 0, 0)
  322. && (iattr->flags & (ATTR_FLAG_SCHED_SET | ATTR_FLAG_POLICY_SET)) != 0)
  323. {
  324. INTERNAL_SYSCALL_DECL (scerr);
  325. /* Use the scheduling parameters the user provided. */
  326. if (iattr->flags & ATTR_FLAG_POLICY_SET)
  327. pd->schedpolicy = iattr->schedpolicy;
  328. else if ((pd->flags & ATTR_FLAG_POLICY_SET) == 0)
  329. {
  330. pd->schedpolicy = INTERNAL_SYSCALL (sched_getscheduler, scerr, 1, 0);
  331. pd->flags |= ATTR_FLAG_POLICY_SET;
  332. }
  333. if (iattr->flags & ATTR_FLAG_SCHED_SET)
  334. memcpy (&pd->schedparam, &iattr->schedparam,
  335. sizeof (struct sched_param));
  336. else if ((pd->flags & ATTR_FLAG_SCHED_SET) == 0)
  337. {
  338. INTERNAL_SYSCALL (sched_getparam, scerr, 2, 0, &pd->schedparam);
  339. pd->flags |= ATTR_FLAG_SCHED_SET;
  340. }
  341. /* Check for valid priorities. */
  342. int minprio = INTERNAL_SYSCALL (sched_get_priority_min, scerr, 1,
  343. iattr->schedpolicy);
  344. int maxprio = INTERNAL_SYSCALL (sched_get_priority_max, scerr, 1,
  345. iattr->schedpolicy);
  346. if (pd->schedparam.sched_priority < minprio
  347. || pd->schedparam.sched_priority > maxprio)
  348. {
  349. err = EINVAL;
  350. goto errout;
  351. }
  352. }
  353. /* Pass the descriptor to the caller. */
  354. *newthread = (pthread_t) pd;
  355. /* Remember whether the thread is detached or not. In case of an
  356. error we have to free the stacks of non-detached stillborn
  357. threads. */
  358. bool is_detached = IS_DETACHED (pd);
  359. /* Start the thread. */
  360. err = create_thread (pd, iattr, STACK_VARIABLES_ARGS);
  361. if (err != 0)
  362. {
  363. /* Something went wrong. Free the resources. */
  364. if (!is_detached)
  365. {
  366. errout:
  367. __deallocate_stack (pd);
  368. }
  369. return err;
  370. }
  371. return 0;
  372. }
  373. weak_alias(__pthread_create_2_1, pthread_create)
  374. /* Information for libthread_db. */
  375. #include "../nptl_db/db_info.c"
  376. /* If pthread_create is present, libgcc_eh.a and libsupc++.a expects some other POSIX thread
  377. functions to be present as well. */
  378. PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_lock)
  379. PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_unlock)
  380. PTHREAD_STATIC_FN_REQUIRE (pthread_once)
  381. PTHREAD_STATIC_FN_REQUIRE (pthread_cancel)
  382. PTHREAD_STATIC_FN_REQUIRE (pthread_key_create)
  383. PTHREAD_STATIC_FN_REQUIRE (pthread_setspecific)
  384. PTHREAD_STATIC_FN_REQUIRE (pthread_getspecific)
  385. /* UCLIBC_MUTEX_xxx macros expects to have these as well */
  386. PTHREAD_STATIC_FN_REQUIRE (pthread_mutex_init)
  387. PTHREAD_STATIC_FN_REQUIRE (_pthread_cleanup_push_defer)
  388. PTHREAD_STATIC_FN_REQUIRE (_pthread_cleanup_pop_restore)