pthread_create.c 15 KB

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