pthread_support.c 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295
  1. /*
  2. * Copyright (c) 1994 by Xerox Corporation. All rights reserved.
  3. * Copyright (c) 1996 by Silicon Graphics. All rights reserved.
  4. * Copyright (c) 1998 by Fergus Henderson. All rights reserved.
  5. * Copyright (c) 2000-2005 by Hewlett-Packard Company. All rights reserved.
  6. *
  7. * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
  8. * OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
  9. *
  10. * Permission is hereby granted to use or copy this program
  11. * for any purpose, provided the above notices are retained on all copies.
  12. * Permission to modify the code and to distribute modified code is granted,
  13. * provided the above notices are retained, and a notice that the code was
  14. * modified is included with the above copyright notice.
  15. */
  16. #include "private/pthread_support.h"
  17. /*
  18. * Support code originally for LinuxThreads, the clone()-based kernel
  19. * thread package for Linux which is included in libc6.
  20. *
  21. * This code no doubt makes some assumptions beyond what is
  22. * guaranteed by the pthread standard, though it now does
  23. * very little of that. It now also supports NPTL, and many
  24. * other Posix thread implementations. We are trying to merge
  25. * all flavors of pthread support code into this file.
  26. */
  27. #if defined(GC_PTHREADS) && !defined(GC_WIN32_THREADS)
  28. # include <stdlib.h>
  29. # include <pthread.h>
  30. # include <sched.h>
  31. # include <time.h>
  32. # include <errno.h>
  33. # include <unistd.h>
  34. # if !defined(SN_TARGET_ORBIS) && !defined(SN_TARGET_PSP2)
  35. # if !defined(GC_RTEMS_PTHREADS)
  36. # include <sys/mman.h>
  37. # endif
  38. # include <sys/time.h>
  39. # include <sys/types.h>
  40. # include <sys/stat.h>
  41. # include <fcntl.h>
  42. # endif
  43. # include <signal.h>
  44. # include "gc_inline.h"
  45. #if defined(GC_DARWIN_THREADS)
  46. # include "private/darwin_semaphore.h"
  47. #else
  48. # include <semaphore.h>
  49. #endif /* !GC_DARWIN_THREADS */
  50. #if defined(GC_DARWIN_THREADS) || defined(GC_FREEBSD_THREADS)
  51. # include <sys/sysctl.h>
  52. #endif /* GC_DARWIN_THREADS */
  53. #if defined(GC_NETBSD_THREADS) || defined(GC_OPENBSD_THREADS)
  54. # include <sys/param.h>
  55. # include <sys/sysctl.h>
  56. #endif /* GC_NETBSD_THREADS */
  57. /* Allocator lock definitions. */
  58. #if !defined(USE_SPIN_LOCK)
  59. GC_INNER pthread_mutex_t GC_allocate_ml = PTHREAD_MUTEX_INITIALIZER;
  60. #endif
  61. #ifdef GC_ASSERTIONS
  62. GC_INNER unsigned long GC_lock_holder = NO_THREAD;
  63. /* Used only for assertions. */
  64. #endif
  65. #if defined(GC_DGUX386_THREADS)
  66. # include <sys/dg_sys_info.h>
  67. # include <sys/_int_psem.h>
  68. /* sem_t is an uint in DG/UX */
  69. typedef unsigned int sem_t;
  70. #endif /* GC_DGUX386_THREADS */
  71. /* Undefine macros used to redirect pthread primitives. */
  72. # undef pthread_create
  73. # ifndef GC_NO_PTHREAD_SIGMASK
  74. # undef pthread_sigmask
  75. # endif
  76. # ifndef GC_NO_PTHREAD_CANCEL
  77. # undef pthread_cancel
  78. # endif
  79. # ifdef GC_HAVE_PTHREAD_EXIT
  80. # undef pthread_exit
  81. # endif
  82. # undef pthread_join
  83. # undef pthread_detach
  84. # if defined(GC_OSF1_THREADS) && defined(_PTHREAD_USE_MANGLED_NAMES_) \
  85. && !defined(_PTHREAD_USE_PTDNAM_)
  86. /* Restore the original mangled names on Tru64 UNIX. */
  87. # define pthread_create __pthread_create
  88. # define pthread_join __pthread_join
  89. # define pthread_detach __pthread_detach
  90. # ifndef GC_NO_PTHREAD_CANCEL
  91. # define pthread_cancel __pthread_cancel
  92. # endif
  93. # ifdef GC_HAVE_PTHREAD_EXIT
  94. # define pthread_exit __pthread_exit
  95. # endif
  96. # endif
  97. #ifdef GC_USE_LD_WRAP
  98. # define WRAP_FUNC(f) __wrap_##f
  99. # define REAL_FUNC(f) __real_##f
  100. int REAL_FUNC(pthread_create)(pthread_t *,
  101. GC_PTHREAD_CREATE_CONST pthread_attr_t *,
  102. void *(*start_routine)(void *), void *);
  103. int REAL_FUNC(pthread_join)(pthread_t, void **);
  104. int REAL_FUNC(pthread_detach)(pthread_t);
  105. # ifndef GC_NO_PTHREAD_SIGMASK
  106. int REAL_FUNC(pthread_sigmask)(int, const sigset_t *, sigset_t *);
  107. # endif
  108. # ifndef GC_NO_PTHREAD_CANCEL
  109. int REAL_FUNC(pthread_cancel)(pthread_t);
  110. # endif
  111. # ifdef GC_HAVE_PTHREAD_EXIT
  112. void REAL_FUNC(pthread_exit)(void *) GC_PTHREAD_EXIT_ATTRIBUTE;
  113. # endif
  114. #else
  115. # ifdef GC_USE_DLOPEN_WRAP
  116. # include <dlfcn.h>
  117. # define WRAP_FUNC(f) f
  118. # define REAL_FUNC(f) GC_real_##f
  119. /* We define both GC_f and plain f to be the wrapped function. */
  120. /* In that way plain calls work, as do calls from files that */
  121. /* included gc.h, which redefined f to GC_f. */
  122. /* FIXME: Needs work for DARWIN and True64 (OSF1) */
  123. typedef int (* GC_pthread_create_t)(pthread_t *,
  124. GC_PTHREAD_CREATE_CONST pthread_attr_t *,
  125. void * (*)(void *), void *);
  126. static GC_pthread_create_t REAL_FUNC(pthread_create);
  127. # ifndef GC_NO_PTHREAD_SIGMASK
  128. typedef int (* GC_pthread_sigmask_t)(int, const sigset_t *,
  129. sigset_t *);
  130. static GC_pthread_sigmask_t REAL_FUNC(pthread_sigmask);
  131. # endif
  132. typedef int (* GC_pthread_join_t)(pthread_t, void **);
  133. static GC_pthread_join_t REAL_FUNC(pthread_join);
  134. typedef int (* GC_pthread_detach_t)(pthread_t);
  135. static GC_pthread_detach_t REAL_FUNC(pthread_detach);
  136. # ifndef GC_NO_PTHREAD_CANCEL
  137. typedef int (* GC_pthread_cancel_t)(pthread_t);
  138. static GC_pthread_cancel_t REAL_FUNC(pthread_cancel);
  139. # endif
  140. # ifdef GC_HAVE_PTHREAD_EXIT
  141. typedef void (* GC_pthread_exit_t)(void *) GC_PTHREAD_EXIT_ATTRIBUTE;
  142. static GC_pthread_exit_t REAL_FUNC(pthread_exit);
  143. # endif
  144. # else
  145. # define WRAP_FUNC(f) GC_##f
  146. # if !defined(GC_DGUX386_THREADS)
  147. # define REAL_FUNC(f) f
  148. # else /* GC_DGUX386_THREADS */
  149. # define REAL_FUNC(f) __d10_##f
  150. # endif /* GC_DGUX386_THREADS */
  151. # endif
  152. #endif
  153. #if defined(GC_USE_LD_WRAP) || defined(GC_USE_DLOPEN_WRAP)
  154. /* Define GC_ functions as aliases for the plain ones, which will */
  155. /* be intercepted. This allows files which include gc.h, and hence */
  156. /* generate references to the GC_ symbols, to see the right symbols. */
  157. GC_API int GC_pthread_create(pthread_t * t,
  158. GC_PTHREAD_CREATE_CONST pthread_attr_t *a,
  159. void * (* fn)(void *), void * arg)
  160. {
  161. return pthread_create(t, a, fn, arg);
  162. }
  163. # ifndef GC_NO_PTHREAD_SIGMASK
  164. GC_API int GC_pthread_sigmask(int how, const sigset_t *mask,
  165. sigset_t *old)
  166. {
  167. return pthread_sigmask(how, mask, old);
  168. }
  169. # endif /* !GC_NO_PTHREAD_SIGMASK */
  170. GC_API int GC_pthread_join(pthread_t t, void **res)
  171. {
  172. return pthread_join(t, res);
  173. }
  174. GC_API int GC_pthread_detach(pthread_t t)
  175. {
  176. return pthread_detach(t);
  177. }
  178. # ifndef GC_NO_PTHREAD_CANCEL
  179. GC_API int GC_pthread_cancel(pthread_t t)
  180. {
  181. return pthread_cancel(t);
  182. }
  183. # endif /* !GC_NO_PTHREAD_CANCEL */
  184. # ifdef GC_HAVE_PTHREAD_EXIT
  185. GC_API GC_PTHREAD_EXIT_ATTRIBUTE void GC_pthread_exit(void *retval)
  186. {
  187. pthread_exit(retval);
  188. }
  189. # endif
  190. #endif /* Linker-based interception. */
  191. #ifdef GC_USE_DLOPEN_WRAP
  192. STATIC GC_bool GC_syms_initialized = FALSE;
  193. STATIC void GC_init_real_syms(void)
  194. {
  195. void *dl_handle;
  196. if (GC_syms_initialized) return;
  197. # ifdef RTLD_NEXT
  198. dl_handle = RTLD_NEXT;
  199. # else
  200. dl_handle = dlopen("libpthread.so.0", RTLD_LAZY);
  201. if (NULL == dl_handle) {
  202. dl_handle = dlopen("libpthread.so", RTLD_LAZY); /* without ".0" */
  203. }
  204. if (NULL == dl_handle) ABORT("Couldn't open libpthread");
  205. # endif
  206. REAL_FUNC(pthread_create) = (GC_pthread_create_t)(word)
  207. dlsym(dl_handle, "pthread_create");
  208. # ifdef RTLD_NEXT
  209. if (REAL_FUNC(pthread_create) == 0)
  210. ABORT("pthread_create not found"
  211. " (probably -lgc is specified after -lpthread)");
  212. # endif
  213. # ifndef GC_NO_PTHREAD_SIGMASK
  214. REAL_FUNC(pthread_sigmask) = (GC_pthread_sigmask_t)(word)
  215. dlsym(dl_handle, "pthread_sigmask");
  216. # endif
  217. REAL_FUNC(pthread_join) = (GC_pthread_join_t)(word)
  218. dlsym(dl_handle, "pthread_join");
  219. REAL_FUNC(pthread_detach) = (GC_pthread_detach_t)(word)
  220. dlsym(dl_handle, "pthread_detach");
  221. # ifndef GC_NO_PTHREAD_CANCEL
  222. REAL_FUNC(pthread_cancel) = (GC_pthread_cancel_t)(word)
  223. dlsym(dl_handle, "pthread_cancel");
  224. # endif
  225. # ifdef GC_HAVE_PTHREAD_EXIT
  226. REAL_FUNC(pthread_exit) = (GC_pthread_exit_t)(word)
  227. dlsym(dl_handle, "pthread_exit");
  228. # endif
  229. GC_syms_initialized = TRUE;
  230. }
  231. # define INIT_REAL_SYMS() if (EXPECT(GC_syms_initialized, TRUE)) {} \
  232. else GC_init_real_syms()
  233. #else
  234. # define INIT_REAL_SYMS() (void)0
  235. #endif
  236. static GC_bool parallel_initialized = FALSE;
  237. #ifndef GC_ALWAYS_MULTITHREADED
  238. GC_INNER GC_bool GC_need_to_lock = FALSE;
  239. #endif
  240. STATIC int GC_nprocs = 1;
  241. /* Number of processors. We may not have */
  242. /* access to all of them, but this is as good */
  243. /* a guess as any ... */
  244. #ifdef THREAD_LOCAL_ALLOC
  245. /* We must explicitly mark ptrfree and gcj free lists, since the free */
  246. /* list links wouldn't otherwise be found. We also set them in the */
  247. /* normal free lists, since that involves touching less memory than */
  248. /* if we scanned them normally. */
  249. GC_INNER void GC_mark_thread_local_free_lists(void)
  250. {
  251. int i;
  252. GC_thread p;
  253. for (i = 0; i < THREAD_TABLE_SZ; ++i) {
  254. for (p = GC_threads[i]; 0 != p; p = p -> next) {
  255. if (!(p -> flags & FINISHED))
  256. GC_mark_thread_local_fls_for(&(p->tlfs));
  257. }
  258. }
  259. }
  260. # if defined(GC_ASSERTIONS)
  261. /* Check that all thread-local free-lists are completely marked. */
  262. /* Also check that thread-specific-data structures are marked. */
  263. void GC_check_tls(void)
  264. {
  265. int i;
  266. GC_thread p;
  267. for (i = 0; i < THREAD_TABLE_SZ; ++i) {
  268. for (p = GC_threads[i]; 0 != p; p = p -> next) {
  269. if (!(p -> flags & FINISHED))
  270. GC_check_tls_for(&(p->tlfs));
  271. }
  272. }
  273. # if defined(USE_CUSTOM_SPECIFIC)
  274. if (GC_thread_key != 0)
  275. GC_check_tsd_marks(GC_thread_key);
  276. # endif
  277. }
  278. # endif /* GC_ASSERTIONS */
  279. #endif /* THREAD_LOCAL_ALLOC */
  280. #ifdef PARALLEL_MARK
  281. # ifndef MAX_MARKERS
  282. # define MAX_MARKERS 16
  283. # endif
  284. static ptr_t marker_sp[MAX_MARKERS - 1] = {0};
  285. #ifdef IA64
  286. static ptr_t marker_bsp[MAX_MARKERS - 1] = {0};
  287. #endif
  288. #if defined(GC_DARWIN_THREADS) && !defined(GC_NO_THREADS_DISCOVERY)
  289. static mach_port_t marker_mach_threads[MAX_MARKERS - 1] = {0};
  290. /* Used only by GC_suspend_thread_list(). */
  291. GC_INNER GC_bool GC_is_mach_marker(thread_act_t thread)
  292. {
  293. int i;
  294. for (i = 0; i < GC_markers_m1; i++) {
  295. if (marker_mach_threads[i] == thread)
  296. return TRUE;
  297. }
  298. return FALSE;
  299. }
  300. #endif /* GC_DARWIN_THREADS */
  301. STATIC void * GC_mark_thread(void * id)
  302. {
  303. word my_mark_no = 0;
  304. IF_CANCEL(int cancel_state;)
  305. if ((word)id == (word)-1) return 0; /* to make compiler happy */
  306. DISABLE_CANCEL(cancel_state);
  307. /* Mark threads are not cancellable; they */
  308. /* should be invisible to client. */
  309. marker_sp[(word)id] = GC_approx_sp();
  310. # ifdef IA64
  311. marker_bsp[(word)id] = GC_save_regs_in_stack();
  312. # endif
  313. # if defined(GC_DARWIN_THREADS) && !defined(GC_NO_THREADS_DISCOVERY)
  314. marker_mach_threads[(word)id] = mach_thread_self();
  315. # endif
  316. /* Inform GC_start_mark_threads about completion of marker data init. */
  317. GC_acquire_mark_lock();
  318. if (0 == --GC_fl_builder_count) /* count may have a negative value */
  319. GC_notify_all_builder();
  320. for (;; ++my_mark_no) {
  321. /* GC_mark_no is passed only to allow GC_help_marker to terminate */
  322. /* promptly. This is important if it were called from the signal */
  323. /* handler or from the GC lock acquisition code. Under Linux, it's */
  324. /* not safe to call it from a signal handler, since it uses mutexes */
  325. /* and condition variables. Since it is called only here, the */
  326. /* argument is unnecessary. */
  327. if (my_mark_no < GC_mark_no || my_mark_no > GC_mark_no + 2) {
  328. /* resynchronize if we get far off, e.g. because GC_mark_no */
  329. /* wrapped. */
  330. my_mark_no = GC_mark_no;
  331. }
  332. # ifdef DEBUG_THREADS
  333. GC_log_printf("Starting mark helper for mark number %lu\n",
  334. (unsigned long)my_mark_no);
  335. # endif
  336. GC_help_marker(my_mark_no);
  337. }
  338. }
  339. STATIC pthread_t GC_mark_threads[MAX_MARKERS];
  340. #ifdef CAN_HANDLE_FORK
  341. static int available_markers_m1 = 0;
  342. static pthread_cond_t mark_cv;
  343. /* initialized by GC_start_mark_threads_inner */
  344. #else
  345. # define available_markers_m1 GC_markers_m1
  346. static pthread_cond_t mark_cv = PTHREAD_COND_INITIALIZER;
  347. #endif
  348. GC_INNER void GC_start_mark_threads_inner(void)
  349. {
  350. int i;
  351. pthread_attr_t attr;
  352. # ifndef NO_MARKER_SPECIAL_SIGMASK
  353. sigset_t set, oldset;
  354. # endif
  355. GC_ASSERT(I_DONT_HOLD_LOCK());
  356. if (available_markers_m1 <= 0) return;
  357. /* Skip if parallel markers disabled or already started. */
  358. # ifdef CAN_HANDLE_FORK
  359. if (GC_parallel) return;
  360. /* Initialize mark_cv (for the first time), or cleanup its value */
  361. /* after forking in the child process. All the marker threads in */
  362. /* the parent process were blocked on this variable at fork, so */
  363. /* pthread_cond_wait() malfunction (hang) is possible in the */
  364. /* child process without such a cleanup. */
  365. /* TODO: This is not portable, it is better to shortly unblock */
  366. /* all marker threads in the parent process at fork. */
  367. {
  368. pthread_cond_t mark_cv_local = PTHREAD_COND_INITIALIZER;
  369. BCOPY(&mark_cv_local, &mark_cv, sizeof(mark_cv));
  370. }
  371. # endif
  372. GC_ASSERT(GC_fl_builder_count == 0);
  373. INIT_REAL_SYMS(); /* for pthread_create */
  374. if (0 != pthread_attr_init(&attr)) ABORT("pthread_attr_init failed");
  375. if (0 != pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED))
  376. ABORT("pthread_attr_setdetachstate failed");
  377. # ifdef DEFAULT_STACK_MAYBE_SMALL
  378. /* Default stack size is usually too small: increase it. */
  379. /* Otherwise marker threads or GC may run out of space. */
  380. {
  381. size_t old_size;
  382. if (pthread_attr_getstacksize(&attr, &old_size) != 0)
  383. ABORT("pthread_attr_getstacksize failed");
  384. if (old_size < MIN_STACK_SIZE
  385. && old_size != 0 /* stack size is known */) {
  386. if (pthread_attr_setstacksize(&attr, MIN_STACK_SIZE) != 0)
  387. ABORT("pthread_attr_setstacksize failed");
  388. }
  389. }
  390. # endif /* DEFAULT_STACK_MAYBE_SMALL */
  391. # ifndef NO_MARKER_SPECIAL_SIGMASK
  392. /* Apply special signal mask to GC marker threads, and don't drop */
  393. /* user defined signals by GC marker threads. */
  394. if (sigfillset(&set) != 0)
  395. ABORT("sigfillset failed");
  396. # if !defined(GC_DARWIN_THREADS) && !defined(GC_OPENBSD_UTHREADS) \
  397. && !defined(NACL)
  398. /* These are used by GC to stop and restart the world. */
  399. if (sigdelset(&set, GC_get_suspend_signal()) != 0
  400. || sigdelset(&set, GC_get_thr_restart_signal()) != 0)
  401. ABORT("sigdelset failed");
  402. # endif
  403. if (pthread_sigmask(SIG_BLOCK, &set, &oldset) < 0) {
  404. WARN("pthread_sigmask set failed, no markers started,"
  405. " errno = %" WARN_PRIdPTR "\n", errno);
  406. GC_markers_m1 = 0;
  407. (void)pthread_attr_destroy(&attr);
  408. return;
  409. }
  410. # endif /* !NO_MARKER_SPECIAL_SIGMASK */
  411. # ifdef CAN_HANDLE_FORK
  412. /* To have proper GC_parallel value in GC_help_marker. */
  413. GC_markers_m1 = available_markers_m1;
  414. # endif
  415. for (i = 0; i < available_markers_m1; ++i) {
  416. if (0 != REAL_FUNC(pthread_create)(GC_mark_threads + i, &attr,
  417. GC_mark_thread, (void *)(word)i)) {
  418. WARN("Marker thread creation failed, errno = %" WARN_PRIdPTR "\n",
  419. errno);
  420. /* Don't try to create other marker threads. */
  421. GC_markers_m1 = i;
  422. break;
  423. }
  424. }
  425. # ifndef NO_MARKER_SPECIAL_SIGMASK
  426. /* Restore previous signal mask. */
  427. if (pthread_sigmask(SIG_SETMASK, &oldset, NULL) < 0) {
  428. WARN("pthread_sigmask restore failed, errno = %" WARN_PRIdPTR "\n",
  429. errno);
  430. }
  431. # endif
  432. (void)pthread_attr_destroy(&attr);
  433. GC_wait_for_markers_init();
  434. GC_COND_LOG_PRINTF("Started %d mark helper threads\n", GC_markers_m1);
  435. }
  436. #endif /* PARALLEL_MARK */
  437. GC_INNER GC_bool GC_thr_initialized = FALSE;
  438. GC_INNER volatile GC_thread GC_threads[THREAD_TABLE_SZ] = {0};
  439. void GC_push_thread_structures(void)
  440. {
  441. GC_ASSERT(I_HOLD_LOCK());
  442. GC_PUSH_ALL_SYM(GC_threads);
  443. # if defined(THREAD_LOCAL_ALLOC)
  444. GC_PUSH_ALL_SYM(GC_thread_key);
  445. # endif
  446. }
  447. #ifdef DEBUG_THREADS
  448. STATIC int GC_count_threads(void)
  449. {
  450. int i;
  451. int count = 0;
  452. GC_ASSERT(I_HOLD_LOCK());
  453. for (i = 0; i < THREAD_TABLE_SZ; ++i) {
  454. GC_thread th = GC_threads[i];
  455. while (th) {
  456. if (!(th->flags & FINISHED))
  457. ++count;
  458. th = th->next;
  459. }
  460. }
  461. return count;
  462. }
  463. #endif /* DEBUG_THREADS */
  464. /* It may not be safe to allocate when we register the first thread. */
  465. /* As "next" and "status" fields are unused, no need to push this. */
  466. static struct GC_Thread_Rep first_thread;
  467. /* Add a thread to GC_threads. We assume it wasn't already there. */
  468. /* Caller holds allocation lock. */
  469. STATIC GC_thread GC_new_thread(pthread_t id)
  470. {
  471. int hv = THREAD_TABLE_INDEX(id);
  472. GC_thread result;
  473. static GC_bool first_thread_used = FALSE;
  474. # ifdef DEBUG_THREADS
  475. GC_log_printf("Creating thread %p\n", (void *)id);
  476. for (result = GC_threads[hv]; result != NULL; result = result->next)
  477. if (!THREAD_EQUAL(result->id, id)) {
  478. GC_log_printf("Hash collision at GC_threads[%d]\n", hv);
  479. break;
  480. }
  481. # endif
  482. GC_ASSERT(I_HOLD_LOCK());
  483. if (!EXPECT(first_thread_used, TRUE)) {
  484. result = &first_thread;
  485. first_thread_used = TRUE;
  486. GC_ASSERT(NULL == GC_threads[hv]);
  487. # if defined(THREAD_SANITIZER) && defined(CPPCHECK)
  488. GC_noop1(result->dummy[0]);
  489. # endif
  490. } else {
  491. result = (struct GC_Thread_Rep *)
  492. GC_INTERNAL_MALLOC(sizeof(struct GC_Thread_Rep), NORMAL);
  493. if (result == 0) return(0);
  494. }
  495. result -> id = id;
  496. # ifdef USE_TKILL_ON_ANDROID
  497. result -> kernel_id = gettid();
  498. # endif
  499. result -> next = GC_threads[hv];
  500. GC_threads[hv] = result;
  501. # ifdef NACL
  502. GC_nacl_gc_thread_self = result;
  503. GC_nacl_initialize_gc_thread();
  504. # endif
  505. GC_ASSERT(result -> flags == 0 && result -> thread_blocked == 0);
  506. if (EXPECT(result != &first_thread, TRUE))
  507. GC_dirty(result);
  508. return(result);
  509. }
  510. /* Delete a thread from GC_threads. We assume it is there. */
  511. /* (The code intentionally traps if it wasn't.) */
  512. /* It is safe to delete the main thread. */
  513. STATIC void GC_delete_thread(pthread_t id)
  514. {
  515. int hv = THREAD_TABLE_INDEX(id);
  516. GC_thread p = GC_threads[hv];
  517. GC_thread prev = NULL;
  518. # ifdef DEBUG_THREADS
  519. GC_log_printf("Deleting thread %p, n_threads = %d\n",
  520. (void *)id, GC_count_threads());
  521. # endif
  522. # ifdef NACL
  523. GC_nacl_shutdown_gc_thread();
  524. GC_nacl_gc_thread_self = NULL;
  525. # endif
  526. GC_ASSERT(I_HOLD_LOCK());
  527. while (!THREAD_EQUAL(p -> id, id)) {
  528. prev = p;
  529. p = p -> next;
  530. }
  531. if (prev == 0) {
  532. GC_threads[hv] = p -> next;
  533. } else {
  534. GC_ASSERT(prev != &first_thread);
  535. prev -> next = p -> next;
  536. GC_dirty(prev);
  537. }
  538. if (p != &first_thread) {
  539. # ifdef GC_DARWIN_THREADS
  540. mach_port_deallocate(mach_task_self(), p->stop_info.mach_thread);
  541. # endif
  542. GC_INTERNAL_FREE(p);
  543. }
  544. }
  545. /* If a thread has been joined, but we have not yet */
  546. /* been notified, then there may be more than one thread */
  547. /* in the table with the same pthread id. */
  548. /* This is OK, but we need a way to delete a specific one. */
  549. STATIC void GC_delete_gc_thread(GC_thread t)
  550. {
  551. pthread_t id = t -> id;
  552. int hv = THREAD_TABLE_INDEX(id);
  553. GC_thread p = GC_threads[hv];
  554. GC_thread prev = NULL;
  555. GC_ASSERT(I_HOLD_LOCK());
  556. while (p != t) {
  557. prev = p;
  558. p = p -> next;
  559. }
  560. if (prev == 0) {
  561. GC_threads[hv] = p -> next;
  562. } else {
  563. GC_ASSERT(prev != &first_thread);
  564. prev -> next = p -> next;
  565. GC_dirty(prev);
  566. }
  567. # ifdef GC_DARWIN_THREADS
  568. mach_port_deallocate(mach_task_self(), p->stop_info.mach_thread);
  569. # endif
  570. GC_INTERNAL_FREE(p);
  571. # ifdef DEBUG_THREADS
  572. GC_log_printf("Deleted thread %p, n_threads = %d\n",
  573. (void *)id, GC_count_threads());
  574. # endif
  575. }
  576. /* Return a GC_thread corresponding to a given pthread_t. */
  577. /* Returns 0 if it's not there. */
  578. /* Caller holds allocation lock or otherwise inhibits */
  579. /* updates. */
  580. /* If there is more than one thread with the given id we */
  581. /* return the most recent one. */
  582. GC_INNER GC_thread GC_lookup_thread(pthread_t id)
  583. {
  584. GC_thread p = GC_threads[THREAD_TABLE_INDEX(id)];
  585. while (p != 0 && !THREAD_EQUAL(p -> id, id)) p = p -> next;
  586. return(p);
  587. }
  588. /* Called by GC_finalize() (in case of an allocation failure observed). */
  589. GC_INNER void GC_reset_finalizer_nested(void)
  590. {
  591. GC_thread me = GC_lookup_thread(pthread_self());
  592. me->finalizer_nested = 0;
  593. }
  594. /* Checks and updates the thread-local level of finalizers recursion. */
  595. /* Returns NULL if GC_invoke_finalizers() should not be called by the */
  596. /* collector (to minimize the risk of a deep finalizers recursion), */
  597. /* otherwise returns a pointer to the thread-local finalizer_nested. */
  598. /* Called by GC_notify_or_invoke_finalizers() only (the lock is held). */
  599. GC_INNER unsigned char *GC_check_finalizer_nested(void)
  600. {
  601. GC_thread me = GC_lookup_thread(pthread_self());
  602. unsigned nesting_level = me->finalizer_nested;
  603. if (nesting_level) {
  604. /* We are inside another GC_invoke_finalizers(). */
  605. /* Skip some implicitly-called GC_invoke_finalizers() */
  606. /* depending on the nesting (recursion) level. */
  607. if (++me->finalizer_skipped < (1U << nesting_level)) return NULL;
  608. me->finalizer_skipped = 0;
  609. }
  610. me->finalizer_nested = (unsigned char)(nesting_level + 1);
  611. return &me->finalizer_nested;
  612. }
  613. #if defined(GC_ASSERTIONS) && defined(THREAD_LOCAL_ALLOC)
  614. /* This is called from thread-local GC_malloc(). */
  615. GC_bool GC_is_thread_tsd_valid(void *tsd)
  616. {
  617. GC_thread me;
  618. DCL_LOCK_STATE;
  619. LOCK();
  620. me = GC_lookup_thread(pthread_self());
  621. UNLOCK();
  622. return (word)tsd >= (word)(&me->tlfs)
  623. && (word)tsd < (word)(&me->tlfs) + sizeof(me->tlfs);
  624. }
  625. #endif /* GC_ASSERTIONS && THREAD_LOCAL_ALLOC */
  626. GC_API int GC_CALL GC_thread_is_registered(void)
  627. {
  628. pthread_t self = pthread_self();
  629. GC_thread me;
  630. DCL_LOCK_STATE;
  631. LOCK();
  632. me = GC_lookup_thread(self);
  633. UNLOCK();
  634. return me != NULL;
  635. }
  636. static pthread_t main_pthread_id;
  637. static void *main_stack, *main_altstack;
  638. static word main_stack_size, main_altstack_size;
  639. GC_API void GC_CALL GC_register_altstack(void *stack, GC_word stack_size,
  640. void *altstack,
  641. GC_word altstack_size)
  642. {
  643. GC_thread me;
  644. pthread_t self = pthread_self();
  645. DCL_LOCK_STATE;
  646. LOCK();
  647. me = GC_lookup_thread(self);
  648. if (me != NULL) {
  649. me->stack = (ptr_t)stack;
  650. me->stack_size = stack_size;
  651. me->altstack = (ptr_t)altstack;
  652. me->altstack_size = altstack_size;
  653. } else {
  654. /* This happens if we are called before GC_thr_init. */
  655. main_pthread_id = self;
  656. main_stack = stack;
  657. main_stack_size = stack_size;
  658. main_altstack = altstack;
  659. main_altstack_size = altstack_size;
  660. }
  661. UNLOCK();
  662. }
  663. #ifdef CAN_HANDLE_FORK
  664. /* Prevent TSan false positive about the race during items removal */
  665. /* from GC_threads. (The race cannot happen since only one thread */
  666. /* survives in the child.) */
  667. # ifdef CAN_CALL_ATFORK
  668. GC_ATTR_NO_SANITIZE_THREAD
  669. # endif
  670. static void store_to_threads_table(int hv, GC_thread me)
  671. {
  672. GC_threads[hv] = me;
  673. }
  674. /* Remove all entries from the GC_threads table, except the */
  675. /* one for the current thread. We need to do this in the child */
  676. /* process after a fork(), since only the current thread */
  677. /* survives in the child. */
  678. STATIC void GC_remove_all_threads_but_me(void)
  679. {
  680. pthread_t self = pthread_self();
  681. int hv;
  682. GC_thread p, next, me;
  683. for (hv = 0; hv < THREAD_TABLE_SZ; ++hv) {
  684. me = 0;
  685. for (p = GC_threads[hv]; 0 != p; p = next) {
  686. next = p -> next;
  687. if (THREAD_EQUAL(p -> id, self)
  688. && me == NULL) { /* ignore dead threads with the same id */
  689. me = p;
  690. p -> next = 0;
  691. # ifdef GC_DARWIN_THREADS
  692. /* Update thread Id after fork (it is OK to call */
  693. /* GC_destroy_thread_local and GC_free_internal */
  694. /* before update). */
  695. me -> stop_info.mach_thread = mach_thread_self();
  696. # endif
  697. # ifdef USE_TKILL_ON_ANDROID
  698. me -> kernel_id = gettid();
  699. # endif
  700. # if defined(THREAD_LOCAL_ALLOC) && !defined(USE_CUSTOM_SPECIFIC)
  701. {
  702. int res;
  703. /* Some TLS implementations might be not fork-friendly, so */
  704. /* we re-assign thread-local pointer to 'tlfs' for safety */
  705. /* instead of the assertion check (again, it is OK to call */
  706. /* GC_destroy_thread_local and GC_free_internal before). */
  707. res = GC_setspecific(GC_thread_key, &me->tlfs);
  708. if (COVERT_DATAFLOW(res) != 0)
  709. ABORT("GC_setspecific failed (in child)");
  710. }
  711. # endif
  712. } else {
  713. # ifdef THREAD_LOCAL_ALLOC
  714. if (!(p -> flags & FINISHED)) {
  715. /* Cannot call GC_destroy_thread_local here. The free */
  716. /* lists may be in an inconsistent state (as thread p may */
  717. /* be updating one of the lists by GC_generic_malloc_many */
  718. /* or GC_FAST_MALLOC_GRANS when fork is invoked). */
  719. /* This should not be a problem because the lost elements */
  720. /* of the free lists will be collected during GC. */
  721. GC_remove_specific_after_fork(GC_thread_key, p -> id);
  722. }
  723. # endif
  724. /* TODO: To avoid TSan hang (when updating GC_bytes_freed), */
  725. /* we just skip explicit freeing of GC_threads entries. */
  726. # if !defined(THREAD_SANITIZER) || !defined(CAN_CALL_ATFORK)
  727. if (p != &first_thread) GC_INTERNAL_FREE(p);
  728. # endif
  729. }
  730. }
  731. store_to_threads_table(hv, me);
  732. }
  733. }
  734. #endif /* CAN_HANDLE_FORK */
  735. #ifdef USE_PROC_FOR_LIBRARIES
  736. GC_INNER GC_bool GC_segment_is_thread_stack(ptr_t lo, ptr_t hi)
  737. {
  738. int i;
  739. GC_thread p;
  740. GC_ASSERT(I_HOLD_LOCK());
  741. # ifdef PARALLEL_MARK
  742. for (i = 0; i < GC_markers_m1; ++i) {
  743. if ((word)marker_sp[i] > (word)lo && (word)marker_sp[i] < (word)hi)
  744. return TRUE;
  745. # ifdef IA64
  746. if ((word)marker_bsp[i] > (word)lo
  747. && (word)marker_bsp[i] < (word)hi)
  748. return TRUE;
  749. # endif
  750. }
  751. # endif
  752. for (i = 0; i < THREAD_TABLE_SZ; i++) {
  753. for (p = GC_threads[i]; p != 0; p = p -> next) {
  754. if (0 != p -> stack_end) {
  755. # ifdef STACK_GROWS_UP
  756. if ((word)p->stack_end >= (word)lo
  757. && (word)p->stack_end < (word)hi)
  758. return TRUE;
  759. # else /* STACK_GROWS_DOWN */
  760. if ((word)p->stack_end > (word)lo
  761. && (word)p->stack_end <= (word)hi)
  762. return TRUE;
  763. # endif
  764. }
  765. }
  766. }
  767. return FALSE;
  768. }
  769. #endif /* USE_PROC_FOR_LIBRARIES */
  770. #ifdef IA64
  771. /* Find the largest stack_base smaller than bound. May be used */
  772. /* to find the boundary between a register stack and adjacent */
  773. /* immediately preceding memory stack. */
  774. GC_INNER ptr_t GC_greatest_stack_base_below(ptr_t bound)
  775. {
  776. int i;
  777. GC_thread p;
  778. ptr_t result = 0;
  779. GC_ASSERT(I_HOLD_LOCK());
  780. # ifdef PARALLEL_MARK
  781. for (i = 0; i < GC_markers_m1; ++i) {
  782. if ((word)marker_sp[i] > (word)result
  783. && (word)marker_sp[i] < (word)bound)
  784. result = marker_sp[i];
  785. }
  786. # endif
  787. for (i = 0; i < THREAD_TABLE_SZ; i++) {
  788. for (p = GC_threads[i]; p != 0; p = p -> next) {
  789. if ((word)p->stack_end > (word)result
  790. && (word)p->stack_end < (word)bound) {
  791. result = p -> stack_end;
  792. }
  793. }
  794. }
  795. return result;
  796. }
  797. #endif /* IA64 */
  798. #ifndef STAT_READ
  799. /* Also defined in os_dep.c. */
  800. # define STAT_BUF_SIZE 4096
  801. # define STAT_READ read
  802. /* If read is wrapped, this may need to be redefined to call */
  803. /* the real one. */
  804. #endif
  805. #ifdef GC_HPUX_THREADS
  806. # define GC_get_nprocs() pthread_num_processors_np()
  807. #elif defined(GC_OSF1_THREADS) || defined(GC_AIX_THREADS) \
  808. || defined(GC_HAIKU_THREADS) || defined(GC_SOLARIS_THREADS) \
  809. || defined(HURD) || defined(HOST_ANDROID) || defined(NACL)
  810. GC_INLINE int GC_get_nprocs(void)
  811. {
  812. int nprocs = (int)sysconf(_SC_NPROCESSORS_ONLN);
  813. return nprocs > 0 ? nprocs : 1; /* ignore error silently */
  814. }
  815. #elif defined(GC_IRIX_THREADS)
  816. GC_INLINE int GC_get_nprocs(void)
  817. {
  818. int nprocs = (int)sysconf(_SC_NPROC_ONLN);
  819. return nprocs > 0 ? nprocs : 1; /* ignore error silently */
  820. }
  821. #elif defined(GC_LINUX_THREADS) /* && !HOST_ANDROID && !NACL */
  822. /* Return the number of processors. */
  823. STATIC int GC_get_nprocs(void)
  824. {
  825. /* Should be "return sysconf(_SC_NPROCESSORS_ONLN);" but that */
  826. /* appears to be buggy in many cases. */
  827. /* We look for lines "cpu<n>" in /proc/stat. */
  828. char stat_buf[STAT_BUF_SIZE];
  829. int f;
  830. int result, i, len;
  831. f = open("/proc/stat", O_RDONLY);
  832. if (f < 0) {
  833. WARN("Couldn't read /proc/stat\n", 0);
  834. return 1; /* assume an uniprocessor */
  835. }
  836. len = STAT_READ(f, stat_buf, STAT_BUF_SIZE);
  837. close(f);
  838. result = 1;
  839. /* Some old kernels only have a single "cpu nnnn ..." */
  840. /* entry in /proc/stat. We identify those as */
  841. /* uniprocessors. */
  842. for (i = 0; i < len - 100; ++i) {
  843. if (stat_buf[i] == '\n' && stat_buf[i+1] == 'c'
  844. && stat_buf[i+2] == 'p' && stat_buf[i+3] == 'u') {
  845. int cpu_no = atoi(&stat_buf[i + 4]);
  846. if (cpu_no >= result)
  847. result = cpu_no + 1;
  848. }
  849. }
  850. return result;
  851. }
  852. #elif defined(GC_DGUX386_THREADS)
  853. /* Return the number of processors, or i <= 0 if it can't be determined. */
  854. STATIC int GC_get_nprocs(void)
  855. {
  856. int numCpus;
  857. struct dg_sys_info_pm_info pm_sysinfo;
  858. int status = 0;
  859. status = dg_sys_info((long int *) &pm_sysinfo,
  860. DG_SYS_INFO_PM_INFO_TYPE, DG_SYS_INFO_PM_CURRENT_VERSION);
  861. if (status < 0)
  862. /* set -1 for error */
  863. numCpus = -1;
  864. else
  865. /* Active CPUs */
  866. numCpus = pm_sysinfo.idle_vp_count;
  867. return(numCpus);
  868. }
  869. #elif defined(GC_DARWIN_THREADS) || defined(GC_FREEBSD_THREADS) \
  870. || defined(GC_NETBSD_THREADS) || defined(GC_OPENBSD_THREADS)
  871. STATIC int GC_get_nprocs(void)
  872. {
  873. int mib[] = {CTL_HW,HW_NCPU};
  874. int res;
  875. size_t len = sizeof(res);
  876. sysctl(mib, sizeof(mib)/sizeof(int), &res, &len, NULL, 0);
  877. return res;
  878. }
  879. #else
  880. /* E.g., GC_RTEMS_PTHREADS */
  881. # define GC_get_nprocs() 1 /* not implemented */
  882. #endif /* !GC_LINUX_THREADS && !GC_DARWIN_THREADS && ... */
  883. #if defined(ARM32) && defined(GC_LINUX_THREADS) && !defined(NACL)
  884. /* Some buggy Linux/arm kernels show only non-sleeping CPUs in */
  885. /* /proc/stat (and /proc/cpuinfo), so another data system source is */
  886. /* tried first. Result <= 0 on error. */
  887. STATIC int GC_get_nprocs_present(void)
  888. {
  889. char stat_buf[16];
  890. int f;
  891. int len;
  892. f = open("/sys/devices/system/cpu/present", O_RDONLY);
  893. if (f < 0)
  894. return -1; /* cannot open the file */
  895. len = STAT_READ(f, stat_buf, sizeof(stat_buf));
  896. close(f);
  897. /* Recognized file format: "0\n" or "0-<max_cpu_id>\n" */
  898. /* The file might probably contain a comma-separated list */
  899. /* but we do not need to handle it (just silently ignore). */
  900. if (len < 2 || stat_buf[0] != '0' || stat_buf[len - 1] != '\n') {
  901. return 0; /* read error or unrecognized content */
  902. } else if (len == 2) {
  903. return 1; /* an uniprocessor */
  904. } else if (stat_buf[1] != '-') {
  905. return 0; /* unrecognized content */
  906. }
  907. stat_buf[len - 1] = '\0'; /* terminate the string */
  908. return atoi(&stat_buf[2]) + 1; /* skip "0-" and parse max_cpu_num */
  909. }
  910. #endif /* ARM32 && GC_LINUX_THREADS && !NACL */
  911. /* We hold the GC lock. Wait until an in-progress GC has finished. */
  912. /* Repeatedly RELEASES GC LOCK in order to wait. */
  913. /* If wait_for_all is true, then we exit with the GC lock held and no */
  914. /* collection in progress; otherwise we just wait for the current GC */
  915. /* to finish. */
  916. STATIC void GC_wait_for_gc_completion(GC_bool wait_for_all)
  917. {
  918. DCL_LOCK_STATE;
  919. # if !defined(THREAD_SANITIZER) || !defined(CAN_CALL_ATFORK)
  920. /* GC_lock_holder is accessed with the lock held, so there is no */
  921. /* data race actually (unlike what is reported by TSan). */
  922. GC_ASSERT(I_HOLD_LOCK());
  923. # endif
  924. ASSERT_CANCEL_DISABLED();
  925. if (GC_incremental && GC_collection_in_progress()) {
  926. word old_gc_no = GC_gc_no;
  927. /* Make sure that no part of our stack is still on the mark stack, */
  928. /* since it's about to be unmapped. */
  929. while (GC_incremental && GC_collection_in_progress()
  930. && (wait_for_all || old_gc_no == GC_gc_no)) {
  931. ENTER_GC();
  932. GC_in_thread_creation = TRUE;
  933. GC_collect_a_little_inner(1);
  934. GC_in_thread_creation = FALSE;
  935. EXIT_GC();
  936. UNLOCK();
  937. sched_yield();
  938. LOCK();
  939. }
  940. }
  941. }
  942. #ifdef CAN_HANDLE_FORK
  943. /* Procedures called before and after a fork. The goal here is to make */
  944. /* it safe to call GC_malloc() in a forked child. It's unclear that is */
  945. /* attainable, since the single UNIX spec seems to imply that one */
  946. /* should only call async-signal-safe functions, and we probably can't */
  947. /* quite guarantee that. But we give it our best shot. (That same */
  948. /* spec also implies that it's not safe to call the system malloc */
  949. /* between fork() and exec(). Thus we're doing no worse than it.) */
  950. IF_CANCEL(static int fork_cancel_state;)
  951. /* protected by allocation lock. */
  952. /* Called before a fork() */
  953. #if defined(GC_ASSERTIONS) && defined(CAN_CALL_ATFORK)
  954. /* GC_lock_holder is updated safely (no data race actually). */
  955. GC_ATTR_NO_SANITIZE_THREAD
  956. #endif
  957. static void fork_prepare_proc(void)
  958. {
  959. /* Acquire all relevant locks, so that after releasing the locks */
  960. /* the child will see a consistent state in which monitor */
  961. /* invariants hold. Unfortunately, we can't acquire libc locks */
  962. /* we might need, and there seems to be no guarantee that libc */
  963. /* must install a suitable fork handler. */
  964. /* Wait for an ongoing GC to finish, since we can't finish it in */
  965. /* the (one remaining thread in) the child. */
  966. LOCK();
  967. DISABLE_CANCEL(fork_cancel_state);
  968. /* Following waits may include cancellation points. */
  969. # if defined(PARALLEL_MARK)
  970. if (GC_parallel)
  971. GC_wait_for_reclaim();
  972. # endif
  973. GC_wait_for_gc_completion(TRUE);
  974. # if defined(PARALLEL_MARK)
  975. if (GC_parallel)
  976. GC_acquire_mark_lock();
  977. # endif
  978. }
  979. /* Called in parent after a fork() (even if the latter failed). */
  980. #if defined(GC_ASSERTIONS) && defined(CAN_CALL_ATFORK)
  981. GC_ATTR_NO_SANITIZE_THREAD
  982. #endif
  983. static void fork_parent_proc(void)
  984. {
  985. # if defined(PARALLEL_MARK)
  986. if (GC_parallel)
  987. GC_release_mark_lock();
  988. # endif
  989. RESTORE_CANCEL(fork_cancel_state);
  990. UNLOCK();
  991. }
  992. /* Called in child after a fork() */
  993. #if defined(GC_ASSERTIONS) && defined(CAN_CALL_ATFORK)
  994. GC_ATTR_NO_SANITIZE_THREAD
  995. #endif
  996. static void fork_child_proc(void)
  997. {
  998. /* Clean up the thread table, so that just our thread is left. */
  999. # if defined(PARALLEL_MARK)
  1000. if (GC_parallel)
  1001. GC_release_mark_lock();
  1002. # endif
  1003. GC_remove_all_threads_but_me();
  1004. # ifdef PARALLEL_MARK
  1005. /* Turn off parallel marking in the child, since we are probably */
  1006. /* just going to exec, and we would have to restart mark threads. */
  1007. GC_parallel = FALSE;
  1008. # endif /* PARALLEL_MARK */
  1009. RESTORE_CANCEL(fork_cancel_state);
  1010. UNLOCK();
  1011. /* Even though after a fork the child only inherits the single */
  1012. /* thread that called the fork(), if another thread in the parent */
  1013. /* was attempting to lock the mutex while being held in */
  1014. /* fork_child_prepare(), the mutex will be left in an inconsistent */
  1015. /* state in the child after the UNLOCK. This is the case, at */
  1016. /* least, in Mac OS X and leads to an unusable GC in the child */
  1017. /* which will block when attempting to perform any GC operation */
  1018. /* that acquires the allocation mutex. */
  1019. # ifdef USE_PTHREAD_LOCKS
  1020. GC_ASSERT(I_DONT_HOLD_LOCK());
  1021. /* Reinitialize the mutex. It should be safe since we are */
  1022. /* running this in the child which only inherits a single thread. */
  1023. /* mutex_destroy() may return EBUSY, which makes no sense, but */
  1024. /* that is the reason for the need of the reinitialization. */
  1025. (void)pthread_mutex_destroy(&GC_allocate_ml);
  1026. /* TODO: Probably some targets might need the default mutex */
  1027. /* attribute to be passed instead of NULL. */
  1028. if (0 != pthread_mutex_init(&GC_allocate_ml, NULL))
  1029. ABORT("pthread_mutex_init failed (in child)");
  1030. # endif
  1031. }
  1032. /* Routines for fork handling by client (no-op if pthread_atfork works). */
  1033. GC_API void GC_CALL GC_atfork_prepare(void)
  1034. {
  1035. if (!EXPECT(GC_is_initialized, TRUE)) GC_init();
  1036. # if defined(GC_DARWIN_THREADS) && defined(MPROTECT_VDB)
  1037. if (GC_incremental) {
  1038. GC_ASSERT(0 == GC_handle_fork);
  1039. ABORT("Unable to fork while mprotect_thread is running");
  1040. }
  1041. # endif
  1042. if (GC_handle_fork <= 0)
  1043. fork_prepare_proc();
  1044. }
  1045. GC_API void GC_CALL GC_atfork_parent(void)
  1046. {
  1047. if (GC_handle_fork <= 0)
  1048. fork_parent_proc();
  1049. }
  1050. GC_API void GC_CALL GC_atfork_child(void)
  1051. {
  1052. if (GC_handle_fork <= 0)
  1053. fork_child_proc();
  1054. }
  1055. #endif /* CAN_HANDLE_FORK */
  1056. #ifdef INCLUDE_LINUX_THREAD_DESCR
  1057. __thread int GC_dummy_thread_local;
  1058. #endif
  1059. #ifdef PARALLEL_MARK
  1060. static void setup_mark_lock(void);
  1061. #endif
  1062. GC_INNER void GC_thr_init(void)
  1063. {
  1064. GC_ASSERT(I_HOLD_LOCK());
  1065. if (GC_thr_initialized) return;
  1066. GC_thr_initialized = TRUE;
  1067. GC_ASSERT((word)&GC_threads % sizeof(word) == 0);
  1068. # ifdef CAN_HANDLE_FORK
  1069. /* Prepare for forks if requested. */
  1070. if (GC_handle_fork) {
  1071. # ifdef CAN_CALL_ATFORK
  1072. if (pthread_atfork(fork_prepare_proc, fork_parent_proc,
  1073. fork_child_proc) == 0) {
  1074. /* Handlers successfully registered. */
  1075. GC_handle_fork = 1;
  1076. } else
  1077. # endif
  1078. /* else */ if (GC_handle_fork != -1)
  1079. ABORT("pthread_atfork failed");
  1080. }
  1081. # endif
  1082. # ifdef INCLUDE_LINUX_THREAD_DESCR
  1083. /* Explicitly register the region including the address */
  1084. /* of a thread local variable. This should include thread */
  1085. /* locals for the main thread, except for those allocated */
  1086. /* in response to dlopen calls. */
  1087. {
  1088. ptr_t thread_local_addr = (ptr_t)(&GC_dummy_thread_local);
  1089. ptr_t main_thread_start, main_thread_end;
  1090. if (!GC_enclosing_mapping(thread_local_addr, &main_thread_start,
  1091. &main_thread_end)) {
  1092. ABORT("Failed to find mapping for main thread thread locals");
  1093. } else {
  1094. /* main_thread_start and main_thread_end are initialized. */
  1095. GC_add_roots_inner(main_thread_start, main_thread_end, FALSE);
  1096. }
  1097. }
  1098. # endif
  1099. /* Add the initial thread, so we can stop it. */
  1100. {
  1101. pthread_t self = pthread_self();
  1102. GC_thread t = GC_new_thread(self);
  1103. if (t == NULL)
  1104. ABORT("Failed to allocate memory for the initial thread");
  1105. # ifdef GC_DARWIN_THREADS
  1106. t -> stop_info.mach_thread = mach_thread_self();
  1107. # else
  1108. t -> stop_info.stack_ptr = GC_approx_sp();
  1109. # endif
  1110. t -> flags = DETACHED | MAIN_THREAD;
  1111. if (THREAD_EQUAL(self, main_pthread_id)) {
  1112. t -> stack = (ptr_t)main_stack;
  1113. t -> stack_size = main_stack_size;
  1114. t -> altstack = (ptr_t)main_altstack;
  1115. t -> altstack_size = main_altstack_size;
  1116. }
  1117. }
  1118. # ifndef GC_DARWIN_THREADS
  1119. GC_stop_init();
  1120. # endif
  1121. /* Set GC_nprocs. */
  1122. {
  1123. char * nprocs_string = GETENV("GC_NPROCS");
  1124. GC_nprocs = -1;
  1125. if (nprocs_string != NULL) GC_nprocs = atoi(nprocs_string);
  1126. }
  1127. if (GC_nprocs <= 0
  1128. # if defined(ARM32) && defined(GC_LINUX_THREADS) && !defined(NACL)
  1129. && (GC_nprocs = GC_get_nprocs_present()) <= 1
  1130. /* Workaround for some Linux/arm kernels */
  1131. # endif
  1132. )
  1133. {
  1134. GC_nprocs = GC_get_nprocs();
  1135. }
  1136. if (GC_nprocs <= 0) {
  1137. WARN("GC_get_nprocs() returned %" WARN_PRIdPTR "\n", GC_nprocs);
  1138. GC_nprocs = 2; /* assume dual-core */
  1139. # ifdef PARALLEL_MARK
  1140. available_markers_m1 = 0; /* but use only one marker */
  1141. # endif
  1142. } else {
  1143. # ifdef PARALLEL_MARK
  1144. {
  1145. char * markers_string = GETENV("GC_MARKERS");
  1146. int markers;
  1147. if (markers_string != NULL) {
  1148. markers = atoi(markers_string);
  1149. if (markers <= 0 || markers > MAX_MARKERS) {
  1150. WARN("Too big or invalid number of mark threads: %" WARN_PRIdPTR
  1151. "; using maximum threads\n", (signed_word)markers);
  1152. markers = MAX_MARKERS;
  1153. }
  1154. } else {
  1155. markers = GC_nprocs;
  1156. # if defined(GC_MIN_MARKERS) && !defined(CPPCHECK)
  1157. /* This is primarily for targets without getenv(). */
  1158. if (markers < GC_MIN_MARKERS)
  1159. markers = GC_MIN_MARKERS;
  1160. # endif
  1161. if (markers > MAX_MARKERS)
  1162. markers = MAX_MARKERS; /* silently limit the value */
  1163. }
  1164. available_markers_m1 = markers - 1;
  1165. }
  1166. # endif
  1167. }
  1168. GC_COND_LOG_PRINTF("Number of processors = %d\n", GC_nprocs);
  1169. # ifdef PARALLEL_MARK
  1170. if (available_markers_m1 <= 0) {
  1171. /* Disable parallel marking. */
  1172. GC_parallel = FALSE;
  1173. GC_COND_LOG_PRINTF(
  1174. "Single marker thread, turning off parallel marking\n");
  1175. } else {
  1176. /* Disable true incremental collection, but generational is OK. */
  1177. GC_time_limit = GC_TIME_UNLIMITED;
  1178. setup_mark_lock();
  1179. }
  1180. # endif
  1181. }
  1182. /* Perform all initializations, including those that */
  1183. /* may require allocation. */
  1184. /* Called without allocation lock. */
  1185. /* Must be called before a second thread is created. */
  1186. /* Did we say it's called without the allocation lock? */
  1187. GC_INNER void GC_init_parallel(void)
  1188. {
  1189. # if defined(THREAD_LOCAL_ALLOC)
  1190. DCL_LOCK_STATE;
  1191. # endif
  1192. if (parallel_initialized) return;
  1193. parallel_initialized = TRUE;
  1194. /* GC_init() calls us back, so set flag first. */
  1195. if (!GC_is_initialized) GC_init();
  1196. /* Initialize thread local free lists if used. */
  1197. # if defined(THREAD_LOCAL_ALLOC)
  1198. LOCK();
  1199. GC_init_thread_local(&(GC_lookup_thread(pthread_self())->tlfs));
  1200. UNLOCK();
  1201. # endif
  1202. }
  1203. #ifndef GC_NO_PTHREAD_SIGMASK
  1204. GC_API int WRAP_FUNC(pthread_sigmask)(int how, const sigset_t *set,
  1205. sigset_t *oset)
  1206. {
  1207. sigset_t fudged_set;
  1208. INIT_REAL_SYMS();
  1209. if (set != NULL && (how == SIG_BLOCK || how == SIG_SETMASK)) {
  1210. int sig_suspend = GC_get_suspend_signal();
  1211. fudged_set = *set;
  1212. GC_ASSERT(sig_suspend >= 0);
  1213. if (sigdelset(&fudged_set, sig_suspend) != 0)
  1214. ABORT("sigdelset failed");
  1215. set = &fudged_set;
  1216. }
  1217. return(REAL_FUNC(pthread_sigmask)(how, set, oset));
  1218. }
  1219. #endif /* !GC_NO_PTHREAD_SIGMASK */
  1220. /* Wrapper for functions that are likely to block for an appreciable */
  1221. /* length of time. */
  1222. GC_INNER void GC_do_blocking_inner(ptr_t data, void * context GC_ATTR_UNUSED)
  1223. {
  1224. struct blocking_data * d = (struct blocking_data *) data;
  1225. pthread_t self = pthread_self();
  1226. GC_thread me;
  1227. # if defined(SPARC) || defined(IA64)
  1228. ptr_t stack_ptr = GC_save_regs_in_stack();
  1229. # endif
  1230. # if defined(GC_DARWIN_THREADS) && !defined(DARWIN_DONT_PARSE_STACK)
  1231. GC_bool topOfStackUnset = FALSE;
  1232. # endif
  1233. DCL_LOCK_STATE;
  1234. LOCK();
  1235. me = GC_lookup_thread(self);
  1236. GC_ASSERT(!(me -> thread_blocked));
  1237. # ifdef SPARC
  1238. me -> stop_info.stack_ptr = stack_ptr;
  1239. # else
  1240. me -> stop_info.stack_ptr = GC_approx_sp();
  1241. # endif
  1242. # if defined(GC_DARWIN_THREADS) && !defined(DARWIN_DONT_PARSE_STACK)
  1243. if (me -> topOfStack == NULL) {
  1244. /* GC_do_blocking_inner is not called recursively, */
  1245. /* so topOfStack should be computed now. */
  1246. topOfStackUnset = TRUE;
  1247. me -> topOfStack = GC_FindTopOfStack(0);
  1248. }
  1249. # endif
  1250. # ifdef IA64
  1251. me -> backing_store_ptr = stack_ptr;
  1252. # endif
  1253. me -> thread_blocked = (unsigned char)TRUE;
  1254. /* Save context here if we want to support precise stack marking */
  1255. UNLOCK();
  1256. d -> client_data = (d -> fn)(d -> client_data);
  1257. LOCK(); /* This will block if the world is stopped. */
  1258. me -> thread_blocked = FALSE;
  1259. # if defined(GC_DARWIN_THREADS) && !defined(DARWIN_DONT_PARSE_STACK)
  1260. if (topOfStackUnset)
  1261. me -> topOfStack = NULL; /* make topOfStack unset again */
  1262. # endif
  1263. UNLOCK();
  1264. }
  1265. /* GC_call_with_gc_active() has the opposite to GC_do_blocking() */
  1266. /* functionality. It might be called from a user function invoked by */
  1267. /* GC_do_blocking() to temporarily back allow calling any GC function */
  1268. /* and/or manipulating pointers to the garbage collected heap. */
  1269. GC_API void * GC_CALL GC_call_with_gc_active(GC_fn_type fn,
  1270. void * client_data)
  1271. {
  1272. struct GC_traced_stack_sect_s stacksect;
  1273. pthread_t self = pthread_self();
  1274. GC_thread me;
  1275. DCL_LOCK_STATE;
  1276. LOCK(); /* This will block if the world is stopped. */
  1277. me = GC_lookup_thread(self);
  1278. /* Adjust our stack base value (this could happen unless */
  1279. /* GC_get_stack_base() was used which returned GC_SUCCESS). */
  1280. if ((me -> flags & MAIN_THREAD) == 0) {
  1281. GC_ASSERT(me -> stack_end != NULL);
  1282. if ((word)me->stack_end HOTTER_THAN (word)(&stacksect))
  1283. me -> stack_end = (ptr_t)(&stacksect);
  1284. } else {
  1285. /* The original stack. */
  1286. if ((word)GC_stackbottom HOTTER_THAN (word)(&stacksect))
  1287. GC_stackbottom = (ptr_t)(&stacksect);
  1288. }
  1289. if (!me->thread_blocked) {
  1290. /* We are not inside GC_do_blocking() - do nothing more. */
  1291. UNLOCK();
  1292. client_data = fn(client_data);
  1293. /* Prevent treating the above as a tail call. */
  1294. GC_noop1((word)(&stacksect));
  1295. return client_data; /* result */
  1296. }
  1297. /* Setup new "stack section". */
  1298. stacksect.saved_stack_ptr = me -> stop_info.stack_ptr;
  1299. # ifdef IA64
  1300. /* This is the same as in GC_call_with_stack_base(). */
  1301. stacksect.backing_store_end = GC_save_regs_in_stack();
  1302. /* Unnecessarily flushes register stack, */
  1303. /* but that probably doesn't hurt. */
  1304. stacksect.saved_backing_store_ptr = me -> backing_store_ptr;
  1305. # endif
  1306. stacksect.prev = me -> traced_stack_sect;
  1307. me -> thread_blocked = FALSE;
  1308. me -> traced_stack_sect = &stacksect;
  1309. UNLOCK();
  1310. client_data = fn(client_data);
  1311. GC_ASSERT(me -> thread_blocked == FALSE);
  1312. GC_ASSERT(me -> traced_stack_sect == &stacksect);
  1313. /* Restore original "stack section". */
  1314. LOCK();
  1315. me -> traced_stack_sect = stacksect.prev;
  1316. # ifdef IA64
  1317. me -> backing_store_ptr = stacksect.saved_backing_store_ptr;
  1318. # endif
  1319. me -> thread_blocked = (unsigned char)TRUE;
  1320. me -> stop_info.stack_ptr = stacksect.saved_stack_ptr;
  1321. UNLOCK();
  1322. return client_data; /* result */
  1323. }
  1324. STATIC void GC_unregister_my_thread_inner(GC_thread me)
  1325. {
  1326. # ifdef DEBUG_THREADS
  1327. GC_log_printf(
  1328. "Unregistering thread %p, gc_thread = %p, n_threads = %d\n",
  1329. (void *)me->id, (void *)me, GC_count_threads());
  1330. # endif
  1331. GC_ASSERT(!(me -> flags & FINISHED));
  1332. # if defined(THREAD_LOCAL_ALLOC)
  1333. GC_ASSERT(GC_getspecific(GC_thread_key) == &me->tlfs);
  1334. GC_destroy_thread_local(&(me->tlfs));
  1335. # endif
  1336. # if defined(GC_HAVE_PTHREAD_EXIT) || !defined(GC_NO_PTHREAD_CANCEL)
  1337. /* Handle DISABLED_GC flag which is set by the */
  1338. /* intercepted pthread_cancel or pthread_exit. */
  1339. if ((me -> flags & DISABLED_GC) != 0) {
  1340. GC_dont_gc--;
  1341. }
  1342. # endif
  1343. if (me -> flags & DETACHED) {
  1344. GC_delete_thread(pthread_self());
  1345. } else {
  1346. me -> flags |= FINISHED;
  1347. }
  1348. # if defined(THREAD_LOCAL_ALLOC)
  1349. /* It is required to call remove_specific defined in specific.c. */
  1350. GC_remove_specific(GC_thread_key);
  1351. # endif
  1352. }
  1353. GC_API int GC_CALL GC_unregister_my_thread(void)
  1354. {
  1355. pthread_t self = pthread_self();
  1356. GC_thread me;
  1357. IF_CANCEL(int cancel_state;)
  1358. DCL_LOCK_STATE;
  1359. LOCK();
  1360. DISABLE_CANCEL(cancel_state);
  1361. /* Wait for any GC that may be marking from our stack to */
  1362. /* complete before we remove this thread. */
  1363. GC_wait_for_gc_completion(FALSE);
  1364. me = GC_lookup_thread(self);
  1365. # ifdef DEBUG_THREADS
  1366. GC_log_printf(
  1367. "Called GC_unregister_my_thread on %p, gc_thread = %p\n",
  1368. (void *)self, (void *)me);
  1369. # endif
  1370. GC_ASSERT(THREAD_EQUAL(me->id, self));
  1371. GC_unregister_my_thread_inner(me);
  1372. RESTORE_CANCEL(cancel_state);
  1373. UNLOCK();
  1374. return GC_SUCCESS;
  1375. }
  1376. /* Called at thread exit. */
  1377. /* Never called for main thread. That's OK, since it */
  1378. /* results in at most a tiny one-time leak. And */
  1379. /* linuxthreads doesn't reclaim the main threads */
  1380. /* resources or id anyway. */
  1381. GC_INNER_PTHRSTART void GC_thread_exit_proc(void *arg)
  1382. {
  1383. IF_CANCEL(int cancel_state;)
  1384. DCL_LOCK_STATE;
  1385. # ifdef DEBUG_THREADS
  1386. GC_log_printf("Called GC_thread_exit_proc on %p, gc_thread = %p\n",
  1387. (void *)((GC_thread)arg)->id, arg);
  1388. # endif
  1389. LOCK();
  1390. DISABLE_CANCEL(cancel_state);
  1391. GC_wait_for_gc_completion(FALSE);
  1392. GC_unregister_my_thread_inner((GC_thread)arg);
  1393. RESTORE_CANCEL(cancel_state);
  1394. UNLOCK();
  1395. }
  1396. #if !defined(SN_TARGET_ORBIS) && !defined(SN_TARGET_PSP2)
  1397. GC_API int WRAP_FUNC(pthread_join)(pthread_t thread, void **retval)
  1398. {
  1399. int result;
  1400. GC_thread t;
  1401. DCL_LOCK_STATE;
  1402. INIT_REAL_SYMS();
  1403. LOCK();
  1404. t = GC_lookup_thread(thread);
  1405. /* This is guaranteed to be the intended one, since the thread id */
  1406. /* can't have been recycled by pthreads. */
  1407. UNLOCK();
  1408. result = REAL_FUNC(pthread_join)(thread, retval);
  1409. # if defined(GC_FREEBSD_THREADS)
  1410. /* On FreeBSD, the wrapped pthread_join() sometimes returns (what
  1411. appears to be) a spurious EINTR which caused the test and real code
  1412. to gratuitously fail. Having looked at system pthread library source
  1413. code, I see how this return code may be generated. In one path of
  1414. code, pthread_join() just returns the errno setting of the thread
  1415. being joined. This does not match the POSIX specification or the
  1416. local man pages thus I have taken the liberty to catch this one
  1417. spurious return value properly conditionalized on GC_FREEBSD_THREADS. */
  1418. if (result == EINTR) result = 0;
  1419. # endif
  1420. if (result == 0) {
  1421. LOCK();
  1422. /* Here the pthread thread id may have been recycled. */
  1423. /* Delete the thread from GC_threads (unless it has been */
  1424. /* registered again from the client thread key destructor). */
  1425. if ((t -> flags & FINISHED) != 0)
  1426. GC_delete_gc_thread(t);
  1427. UNLOCK();
  1428. }
  1429. return result;
  1430. }
  1431. GC_API int WRAP_FUNC(pthread_detach)(pthread_t thread)
  1432. {
  1433. int result;
  1434. GC_thread t;
  1435. DCL_LOCK_STATE;
  1436. INIT_REAL_SYMS();
  1437. LOCK();
  1438. t = GC_lookup_thread(thread);
  1439. UNLOCK();
  1440. result = REAL_FUNC(pthread_detach)(thread);
  1441. if (result == 0) {
  1442. LOCK();
  1443. t -> flags |= DETACHED;
  1444. /* Here the pthread thread id may have been recycled. */
  1445. if ((t -> flags & FINISHED) != 0) {
  1446. GC_delete_gc_thread(t);
  1447. }
  1448. UNLOCK();
  1449. }
  1450. return result;
  1451. }
  1452. #endif /* !SN_TARGET_ORBIS && !SN_TARGET_PSP2 */
  1453. #ifndef GC_NO_PTHREAD_CANCEL
  1454. /* We should deal with the fact that apparently on Solaris and, */
  1455. /* probably, on some Linux we can't collect while a thread is */
  1456. /* exiting, since signals aren't handled properly. This currently */
  1457. /* gives rise to deadlocks. The only workaround seen is to intercept */
  1458. /* pthread_cancel() and pthread_exit(), and disable the collections */
  1459. /* until the thread exit handler is called. That's ugly, because we */
  1460. /* risk growing the heap unnecessarily. But it seems that we don't */
  1461. /* really have an option in that the process is not in a fully */
  1462. /* functional state while a thread is exiting. */
  1463. GC_API int WRAP_FUNC(pthread_cancel)(pthread_t thread)
  1464. {
  1465. # ifdef CANCEL_SAFE
  1466. GC_thread t;
  1467. DCL_LOCK_STATE;
  1468. # endif
  1469. INIT_REAL_SYMS();
  1470. # ifdef CANCEL_SAFE
  1471. LOCK();
  1472. t = GC_lookup_thread(thread);
  1473. /* We test DISABLED_GC because pthread_exit could be called at */
  1474. /* the same time. (If t is NULL then pthread_cancel should */
  1475. /* return ESRCH.) */
  1476. if (t != NULL && (t -> flags & DISABLED_GC) == 0) {
  1477. t -> flags |= DISABLED_GC;
  1478. GC_dont_gc++;
  1479. }
  1480. UNLOCK();
  1481. # endif
  1482. return REAL_FUNC(pthread_cancel)(thread);
  1483. }
  1484. #endif /* !GC_NO_PTHREAD_CANCEL */
  1485. #ifdef GC_HAVE_PTHREAD_EXIT
  1486. GC_API GC_PTHREAD_EXIT_ATTRIBUTE void WRAP_FUNC(pthread_exit)(void *retval)
  1487. {
  1488. pthread_t self = pthread_self();
  1489. GC_thread me;
  1490. DCL_LOCK_STATE;
  1491. INIT_REAL_SYMS();
  1492. LOCK();
  1493. me = GC_lookup_thread(self);
  1494. /* We test DISABLED_GC because someone else could call */
  1495. /* pthread_cancel at the same time. */
  1496. if (me != 0 && (me -> flags & DISABLED_GC) == 0) {
  1497. me -> flags |= DISABLED_GC;
  1498. GC_dont_gc++;
  1499. }
  1500. UNLOCK();
  1501. REAL_FUNC(pthread_exit)(retval);
  1502. }
  1503. #endif /* GC_HAVE_PTHREAD_EXIT */
  1504. GC_INNER GC_bool GC_in_thread_creation = FALSE;
  1505. /* Protected by allocation lock. */
  1506. GC_INLINE void GC_record_stack_base(GC_thread me,
  1507. const struct GC_stack_base *sb)
  1508. {
  1509. # ifndef GC_DARWIN_THREADS
  1510. me -> stop_info.stack_ptr = (ptr_t)sb->mem_base;
  1511. # endif
  1512. me -> stack_end = (ptr_t)sb->mem_base;
  1513. if (me -> stack_end == NULL)
  1514. ABORT("Bad stack base in GC_register_my_thread");
  1515. # ifdef IA64
  1516. me -> backing_store_end = (ptr_t)sb->reg_base;
  1517. # endif
  1518. }
  1519. STATIC GC_thread GC_register_my_thread_inner(const struct GC_stack_base *sb,
  1520. pthread_t my_pthread)
  1521. {
  1522. GC_thread me;
  1523. GC_in_thread_creation = TRUE; /* OK to collect from unknown thread. */
  1524. me = GC_new_thread(my_pthread);
  1525. GC_in_thread_creation = FALSE;
  1526. if (me == 0)
  1527. ABORT("Failed to allocate memory for thread registering");
  1528. # ifdef GC_DARWIN_THREADS
  1529. me -> stop_info.mach_thread = mach_thread_self();
  1530. # endif
  1531. GC_record_stack_base(me, sb);
  1532. # ifdef GC_EXPLICIT_SIGNALS_UNBLOCK
  1533. /* Since this could be executed from a detached thread */
  1534. /* destructor, our signals might already be blocked. */
  1535. GC_unblock_gc_signals();
  1536. # endif
  1537. return me;
  1538. }
  1539. GC_API void GC_CALL GC_allow_register_threads(void)
  1540. {
  1541. /* Check GC is initialized and the current thread is registered. */
  1542. GC_ASSERT(GC_lookup_thread(pthread_self()) != 0);
  1543. set_need_to_lock();
  1544. }
  1545. GC_API int GC_CALL GC_register_my_thread(const struct GC_stack_base *sb)
  1546. {
  1547. pthread_t self = pthread_self();
  1548. GC_thread me;
  1549. DCL_LOCK_STATE;
  1550. if (GC_need_to_lock == FALSE)
  1551. ABORT("Threads explicit registering is not previously enabled");
  1552. LOCK();
  1553. me = GC_lookup_thread(self);
  1554. if (0 == me) {
  1555. me = GC_register_my_thread_inner(sb, self);
  1556. me -> flags |= DETACHED;
  1557. /* Treat as detached, since we do not need to worry about */
  1558. /* pointer results. */
  1559. # if defined(THREAD_LOCAL_ALLOC)
  1560. GC_init_thread_local(&(me->tlfs));
  1561. # endif
  1562. UNLOCK();
  1563. return GC_SUCCESS;
  1564. } else if ((me -> flags & FINISHED) != 0) {
  1565. /* This code is executed when a thread is registered from the */
  1566. /* client thread key destructor. */
  1567. # ifdef GC_DARWIN_THREADS
  1568. /* Reinitialize mach_thread to avoid thread_suspend fail */
  1569. /* with MACH_SEND_INVALID_DEST error. */
  1570. me -> stop_info.mach_thread = mach_thread_self();
  1571. # endif
  1572. GC_record_stack_base(me, sb);
  1573. me -> flags &= ~FINISHED; /* but not DETACHED */
  1574. # ifdef GC_EXPLICIT_SIGNALS_UNBLOCK
  1575. /* Since this could be executed from a thread destructor, */
  1576. /* our signals might be blocked. */
  1577. GC_unblock_gc_signals();
  1578. # endif
  1579. # if defined(THREAD_LOCAL_ALLOC)
  1580. GC_init_thread_local(&(me->tlfs));
  1581. # endif
  1582. UNLOCK();
  1583. return GC_SUCCESS;
  1584. } else {
  1585. UNLOCK();
  1586. return GC_DUPLICATE;
  1587. }
  1588. }
  1589. struct start_info {
  1590. void *(*start_routine)(void *);
  1591. void *arg;
  1592. word flags;
  1593. sem_t registered; /* 1 ==> in our thread table, but */
  1594. /* parent hasn't yet noticed. */
  1595. };
  1596. /* Called from GC_inner_start_routine(). Defined in this file to */
  1597. /* minimize the number of include files in pthread_start.c (because */
  1598. /* sem_t and sem_post() are not used that file directly). */
  1599. GC_INNER_PTHRSTART GC_thread GC_start_rtn_prepare_thread(
  1600. void *(**pstart)(void *),
  1601. void **pstart_arg,
  1602. struct GC_stack_base *sb, void *arg)
  1603. {
  1604. struct start_info * si = (struct start_info *)arg;
  1605. pthread_t self = pthread_self();
  1606. GC_thread me;
  1607. DCL_LOCK_STATE;
  1608. # ifdef DEBUG_THREADS
  1609. GC_log_printf("Starting thread %p, pid = %ld, sp = %p\n",
  1610. (void *)self, (long)getpid(), (void *)&arg);
  1611. # endif
  1612. LOCK();
  1613. me = GC_register_my_thread_inner(sb, self);
  1614. me -> flags = si -> flags;
  1615. # if defined(THREAD_LOCAL_ALLOC)
  1616. GC_init_thread_local(&(me->tlfs));
  1617. # endif
  1618. UNLOCK();
  1619. *pstart = si -> start_routine;
  1620. # ifdef DEBUG_THREADS
  1621. GC_log_printf("start_routine = %p\n", (void *)(signed_word)(*pstart));
  1622. # endif
  1623. *pstart_arg = si -> arg;
  1624. sem_post(&(si -> registered)); /* Last action on si. */
  1625. /* OK to deallocate. */
  1626. return me;
  1627. }
  1628. #if !defined(SN_TARGET_ORBIS) && !defined(SN_TARGET_PSP2)
  1629. STATIC void * GC_start_routine(void * arg)
  1630. {
  1631. # ifdef INCLUDE_LINUX_THREAD_DESCR
  1632. struct GC_stack_base sb;
  1633. # ifdef REDIRECT_MALLOC
  1634. /* GC_get_stack_base may call pthread_getattr_np, which can */
  1635. /* unfortunately call realloc, which may allocate from an */
  1636. /* unregistered thread. This is unpleasant, since it might */
  1637. /* force heap growth (or, even, heap overflow). */
  1638. GC_disable();
  1639. # endif
  1640. if (GC_get_stack_base(&sb) != GC_SUCCESS)
  1641. ABORT("Failed to get thread stack base");
  1642. # ifdef REDIRECT_MALLOC
  1643. GC_enable();
  1644. # endif
  1645. return GC_inner_start_routine(&sb, arg);
  1646. # else
  1647. return GC_call_with_stack_base(GC_inner_start_routine, arg);
  1648. # endif
  1649. }
  1650. GC_API int WRAP_FUNC(pthread_create)(pthread_t *new_thread,
  1651. GC_PTHREAD_CREATE_CONST pthread_attr_t *attr,
  1652. void *(*start_routine)(void *), void *arg)
  1653. {
  1654. int result;
  1655. int detachstate;
  1656. word my_flags = 0;
  1657. struct start_info * si;
  1658. DCL_LOCK_STATE;
  1659. /* This is otherwise saved only in an area mmapped by the thread */
  1660. /* library, which isn't visible to the collector. */
  1661. /* We resist the temptation to muck with the stack size here, */
  1662. /* even if the default is unreasonably small. That's the client's */
  1663. /* responsibility. */
  1664. INIT_REAL_SYMS();
  1665. LOCK();
  1666. si = (struct start_info *)GC_INTERNAL_MALLOC(sizeof(struct start_info),
  1667. NORMAL);
  1668. UNLOCK();
  1669. if (!EXPECT(parallel_initialized, TRUE))
  1670. GC_init_parallel();
  1671. if (EXPECT(0 == si, FALSE) &&
  1672. (si = (struct start_info *)
  1673. (*GC_get_oom_fn())(sizeof(struct start_info))) == 0)
  1674. return(ENOMEM);
  1675. if (sem_init(&(si -> registered), GC_SEM_INIT_PSHARED, 0) != 0)
  1676. ABORT("sem_init failed");
  1677. si -> start_routine = start_routine;
  1678. si -> arg = arg;
  1679. LOCK();
  1680. if (!EXPECT(GC_thr_initialized, TRUE))
  1681. GC_thr_init();
  1682. # ifdef GC_ASSERTIONS
  1683. {
  1684. size_t stack_size = 0;
  1685. if (NULL != attr) {
  1686. if (pthread_attr_getstacksize(attr, &stack_size) != 0)
  1687. ABORT("pthread_attr_getstacksize failed");
  1688. }
  1689. if (0 == stack_size) {
  1690. pthread_attr_t my_attr;
  1691. if (pthread_attr_init(&my_attr) != 0)
  1692. ABORT("pthread_attr_init failed");
  1693. if (pthread_attr_getstacksize(&my_attr, &stack_size) != 0)
  1694. ABORT("pthread_attr_getstacksize failed");
  1695. (void)pthread_attr_destroy(&my_attr);
  1696. }
  1697. /* On Solaris 10, with default attr initialization, */
  1698. /* stack_size remains 0. Fudge it. */
  1699. if (0 == stack_size) {
  1700. # ifndef SOLARIS
  1701. WARN("Failed to get stack size for assertion checking\n", 0);
  1702. # endif
  1703. stack_size = 1000000;
  1704. }
  1705. GC_ASSERT(stack_size >= 65536);
  1706. /* Our threads may need to do some work for the GC. */
  1707. /* Ridiculously small threads won't work, and they */
  1708. /* probably wouldn't work anyway. */
  1709. }
  1710. # endif
  1711. if (NULL == attr) {
  1712. detachstate = PTHREAD_CREATE_JOINABLE;
  1713. } else {
  1714. pthread_attr_getdetachstate(attr, &detachstate);
  1715. }
  1716. if (PTHREAD_CREATE_DETACHED == detachstate) my_flags |= DETACHED;
  1717. si -> flags = my_flags;
  1718. UNLOCK();
  1719. # ifdef DEBUG_THREADS
  1720. GC_log_printf("About to start new thread from thread %p\n",
  1721. (void *)pthread_self());
  1722. # endif
  1723. set_need_to_lock();
  1724. result = REAL_FUNC(pthread_create)(new_thread, attr, GC_start_routine, si);
  1725. /* Wait until child has been added to the thread table. */
  1726. /* This also ensures that we hold onto si until the child is done */
  1727. /* with it. Thus it doesn't matter whether it is otherwise */
  1728. /* visible to the collector. */
  1729. if (0 == result) {
  1730. IF_CANCEL(int cancel_state;)
  1731. # ifdef DEBUG_THREADS
  1732. /* new_thread is non-NULL because pthread_create requires it. */
  1733. GC_log_printf("Started thread %p\n", (void *)(*new_thread));
  1734. # endif
  1735. DISABLE_CANCEL(cancel_state);
  1736. /* pthread_create is not a cancellation point. */
  1737. while (0 != sem_wait(&(si -> registered))) {
  1738. # if defined(GC_HAIKU_THREADS)
  1739. /* To workaround some bug in Haiku semaphores. */
  1740. if (EACCES == errno) continue;
  1741. # endif
  1742. if (EINTR != errno) ABORT("sem_wait failed");
  1743. }
  1744. RESTORE_CANCEL(cancel_state);
  1745. }
  1746. sem_destroy(&(si -> registered));
  1747. LOCK();
  1748. GC_INTERNAL_FREE(si);
  1749. UNLOCK();
  1750. return(result);
  1751. }
  1752. #endif /* !SN_TARGET_ORBIS && !SN_TARGET_PSP2 */
  1753. #if defined(USE_SPIN_LOCK) || !defined(NO_PTHREAD_TRYLOCK)
  1754. /* Spend a few cycles in a way that can't introduce contention with */
  1755. /* other threads. */
  1756. #define GC_PAUSE_SPIN_CYCLES 10
  1757. STATIC void GC_pause(void)
  1758. {
  1759. int i;
  1760. #ifndef GC_ATOMIC_OPS_H
  1761. volatile word dummy = 0;
  1762. #endif
  1763. for (i = 0; i < GC_PAUSE_SPIN_CYCLES; ++i) {
  1764. /* Something that's unlikely to be optimized away. */
  1765. #ifndef GC_ATOMIC_OPS_H
  1766. GC_noop1(++dummy);
  1767. #else
  1768. AO_compiler_barrier();
  1769. #endif
  1770. }
  1771. }
  1772. #endif
  1773. #ifndef SPIN_MAX
  1774. # define SPIN_MAX 128 /* Maximum number of calls to GC_pause before */
  1775. /* give up. */
  1776. #endif
  1777. GC_INNER volatile GC_bool GC_collecting = FALSE;
  1778. /* A hint that we're in the collector and */
  1779. /* holding the allocation lock for an */
  1780. /* extended period. */
  1781. #if (!defined(USE_SPIN_LOCK) && !defined(NO_PTHREAD_TRYLOCK)) \
  1782. || defined(PARALLEL_MARK)
  1783. /* If we don't want to use the below spinlock implementation, either */
  1784. /* because we don't have a GC_test_and_set implementation, or because */
  1785. /* we don't want to risk sleeping, we can still try spinning on */
  1786. /* pthread_mutex_trylock for a while. This appears to be very */
  1787. /* beneficial in many cases. */
  1788. /* I suspect that under high contention this is nearly always better */
  1789. /* than the spin lock. But it's a bit slower on a uniprocessor. */
  1790. /* Hence we still default to the spin lock. */
  1791. /* This is also used to acquire the mark lock for the parallel */
  1792. /* marker. */
  1793. /* Here we use a strict exponential backoff scheme. I don't know */
  1794. /* whether that's better or worse than the above. We eventually */
  1795. /* yield by calling pthread_mutex_lock(); it never makes sense to */
  1796. /* explicitly sleep. */
  1797. /* #define LOCK_STATS */
  1798. /* Note that LOCK_STATS requires AO_HAVE_test_and_set. */
  1799. #ifdef LOCK_STATS
  1800. volatile AO_t GC_spin_count = 0;
  1801. volatile AO_t GC_block_count = 0;
  1802. volatile AO_t GC_unlocked_count = 0;
  1803. #endif
  1804. STATIC void GC_generic_lock(pthread_mutex_t * lock)
  1805. {
  1806. #ifndef NO_PTHREAD_TRYLOCK
  1807. unsigned pause_length = 1;
  1808. unsigned i;
  1809. if (0 == pthread_mutex_trylock(lock)) {
  1810. # ifdef LOCK_STATS
  1811. (void)AO_fetch_and_add1(&GC_unlocked_count);
  1812. # endif
  1813. return;
  1814. }
  1815. for (; pause_length <= SPIN_MAX; pause_length <<= 1) {
  1816. for (i = 0; i < pause_length; ++i) {
  1817. GC_pause();
  1818. }
  1819. switch(pthread_mutex_trylock(lock)) {
  1820. case 0:
  1821. # ifdef LOCK_STATS
  1822. (void)AO_fetch_and_add1(&GC_spin_count);
  1823. # endif
  1824. return;
  1825. case EBUSY:
  1826. break;
  1827. default:
  1828. ABORT("Unexpected error from pthread_mutex_trylock");
  1829. }
  1830. }
  1831. #endif /* !NO_PTHREAD_TRYLOCK */
  1832. # ifdef LOCK_STATS
  1833. (void)AO_fetch_and_add1(&GC_block_count);
  1834. # endif
  1835. pthread_mutex_lock(lock);
  1836. }
  1837. #endif /* !USE_SPIN_LOCK || ... */
  1838. #ifdef AO_HAVE_char_load
  1839. # define is_collecting() \
  1840. ((GC_bool)AO_char_load((unsigned char *)&GC_collecting))
  1841. #else
  1842. /* GC_collecting is a hint, a potential data race between */
  1843. /* GC_lock() and ENTER/EXIT_GC() is OK to ignore. */
  1844. # define is_collecting() GC_collecting
  1845. #endif
  1846. #if defined(USE_SPIN_LOCK)
  1847. /* Reasonably fast spin locks. Basically the same implementation */
  1848. /* as STL alloc.h. This isn't really the right way to do this. */
  1849. /* but until the POSIX scheduling mess gets straightened out ... */
  1850. GC_INNER volatile AO_TS_t GC_allocate_lock = AO_TS_INITIALIZER;
  1851. # define low_spin_max 30 /* spin cycles if we suspect uniprocessor */
  1852. # define high_spin_max SPIN_MAX /* spin cycles for multiprocessor */
  1853. static volatile AO_t spin_max = low_spin_max;
  1854. static volatile AO_t last_spins = 0;
  1855. /* A potential data race between */
  1856. /* threads invoking GC_lock which reads */
  1857. /* and updates spin_max and last_spins */
  1858. /* could be ignored because these */
  1859. /* variables are hints only. */
  1860. GC_INNER void GC_lock(void)
  1861. {
  1862. unsigned my_spin_max;
  1863. unsigned my_last_spins;
  1864. unsigned i;
  1865. if (AO_test_and_set_acquire(&GC_allocate_lock) == AO_TS_CLEAR) {
  1866. return;
  1867. }
  1868. my_spin_max = (unsigned)AO_load(&spin_max);
  1869. my_last_spins = (unsigned)AO_load(&last_spins);
  1870. for (i = 0; i < my_spin_max; i++) {
  1871. if (is_collecting() || GC_nprocs == 1)
  1872. goto yield;
  1873. if (i < my_last_spins/2) {
  1874. GC_pause();
  1875. continue;
  1876. }
  1877. if (AO_test_and_set_acquire(&GC_allocate_lock) == AO_TS_CLEAR) {
  1878. /*
  1879. * got it!
  1880. * Spinning worked. Thus we're probably not being scheduled
  1881. * against the other process with which we were contending.
  1882. * Thus it makes sense to spin longer the next time.
  1883. */
  1884. AO_store(&last_spins, (AO_t)i);
  1885. AO_store(&spin_max, (AO_t)high_spin_max);
  1886. return;
  1887. }
  1888. }
  1889. /* We are probably being scheduled against the other process. Sleep. */
  1890. AO_store(&spin_max, (AO_t)low_spin_max);
  1891. yield:
  1892. for (i = 0;; ++i) {
  1893. if (AO_test_and_set_acquire(&GC_allocate_lock) == AO_TS_CLEAR) {
  1894. return;
  1895. }
  1896. # define SLEEP_THRESHOLD 12
  1897. /* Under Linux very short sleeps tend to wait until */
  1898. /* the current time quantum expires. On old Linux */
  1899. /* kernels nanosleep (<= 2 msecs) just spins. */
  1900. /* (Under 2.4, this happens only for real-time */
  1901. /* processes.) We want to minimize both behaviors */
  1902. /* here. */
  1903. if (i < SLEEP_THRESHOLD) {
  1904. sched_yield();
  1905. } else {
  1906. struct timespec ts;
  1907. if (i > 24) i = 24;
  1908. /* Don't wait for more than about 15 msecs, */
  1909. /* even under extreme contention. */
  1910. ts.tv_sec = 0;
  1911. ts.tv_nsec = 1 << i;
  1912. nanosleep(&ts, 0);
  1913. }
  1914. }
  1915. }
  1916. #else /* !USE_SPIN_LOCK */
  1917. GC_INNER void GC_lock(void)
  1918. {
  1919. #ifndef NO_PTHREAD_TRYLOCK
  1920. if (1 == GC_nprocs || is_collecting()) {
  1921. pthread_mutex_lock(&GC_allocate_ml);
  1922. } else {
  1923. GC_generic_lock(&GC_allocate_ml);
  1924. }
  1925. #else /* !NO_PTHREAD_TRYLOCK */
  1926. pthread_mutex_lock(&GC_allocate_ml);
  1927. #endif /* !NO_PTHREAD_TRYLOCK */
  1928. }
  1929. #endif /* !USE_SPIN_LOCK */
  1930. #ifdef PARALLEL_MARK
  1931. # ifdef GC_ASSERTIONS
  1932. STATIC unsigned long GC_mark_lock_holder = NO_THREAD;
  1933. # define SET_MARK_LOCK_HOLDER \
  1934. (void)(GC_mark_lock_holder = NUMERIC_THREAD_ID(pthread_self()))
  1935. # define UNSET_MARK_LOCK_HOLDER \
  1936. do { \
  1937. GC_ASSERT(GC_mark_lock_holder \
  1938. == NUMERIC_THREAD_ID(pthread_self())); \
  1939. GC_mark_lock_holder = NO_THREAD; \
  1940. } while (0)
  1941. # else
  1942. # define SET_MARK_LOCK_HOLDER (void)0
  1943. # define UNSET_MARK_LOCK_HOLDER (void)0
  1944. # endif /* !GC_ASSERTIONS */
  1945. #ifdef GLIBC_2_1_MUTEX_HACK
  1946. /* Ugly workaround for a linux threads bug in the final versions */
  1947. /* of glibc2.1. Pthread_mutex_trylock sets the mutex owner */
  1948. /* field even when it fails to acquire the mutex. This causes */
  1949. /* pthread_cond_wait to die. Remove for glibc2.2. */
  1950. /* According to the man page, we should use */
  1951. /* PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP, but that isn't actually */
  1952. /* defined. */
  1953. static pthread_mutex_t mark_mutex =
  1954. {0, 0, 0, PTHREAD_MUTEX_ERRORCHECK_NP, {0, 0}};
  1955. #else
  1956. static pthread_mutex_t mark_mutex = PTHREAD_MUTEX_INITIALIZER;
  1957. #endif
  1958. static pthread_cond_t builder_cv = PTHREAD_COND_INITIALIZER;
  1959. #ifdef GLIBC_2_19_TSX_BUG
  1960. /* Parse string like <major>[.<minor>[<tail>]] and return major value. */
  1961. static int parse_version(int *pminor, const char *pverstr) {
  1962. char *endp;
  1963. unsigned long value = strtoul(pverstr, &endp, 10);
  1964. int major = (int)value;
  1965. if (major < 0 || (char *)pverstr == endp || (unsigned)major != value) {
  1966. /* Parse error */
  1967. return -1;
  1968. }
  1969. if (*endp != '.') {
  1970. /* No minor part. */
  1971. *pminor = -1;
  1972. } else {
  1973. value = strtoul(endp + 1, &endp, 10);
  1974. *pminor = (int)value;
  1975. if (*pminor < 0 || (unsigned)(*pminor) != value) {
  1976. return -1;
  1977. }
  1978. }
  1979. return major;
  1980. }
  1981. #endif /* GLIBC_2_19_TSX_BUG */
  1982. static void setup_mark_lock(void)
  1983. {
  1984. # ifdef GLIBC_2_19_TSX_BUG
  1985. pthread_mutexattr_t mattr;
  1986. int glibc_minor = -1;
  1987. int glibc_major = parse_version(&glibc_minor, gnu_get_libc_version());
  1988. if (glibc_major > 2 || (glibc_major == 2 && glibc_minor >= 19)) {
  1989. /* TODO: disable this workaround for glibc with fixed TSX */
  1990. /* This disables lock elision to workaround a bug in glibc 2.19+ */
  1991. if (0 != pthread_mutexattr_init(&mattr)) {
  1992. ABORT("pthread_mutexattr_init failed");
  1993. }
  1994. if (0 != pthread_mutexattr_settype(&mattr, PTHREAD_MUTEX_NORMAL)) {
  1995. ABORT("pthread_mutexattr_settype failed");
  1996. }
  1997. if (0 != pthread_mutex_init(&mark_mutex, &mattr)) {
  1998. ABORT("pthread_mutex_init failed");
  1999. }
  2000. (void)pthread_mutexattr_destroy(&mattr);
  2001. }
  2002. # endif
  2003. }
  2004. GC_INNER void GC_acquire_mark_lock(void)
  2005. {
  2006. # if defined(NUMERIC_THREAD_ID_UNIQUE) && !defined(THREAD_SANITIZER)
  2007. GC_ASSERT(GC_mark_lock_holder != NUMERIC_THREAD_ID(pthread_self()));
  2008. # endif
  2009. GC_generic_lock(&mark_mutex);
  2010. SET_MARK_LOCK_HOLDER;
  2011. }
  2012. GC_INNER void GC_release_mark_lock(void)
  2013. {
  2014. UNSET_MARK_LOCK_HOLDER;
  2015. if (pthread_mutex_unlock(&mark_mutex) != 0) {
  2016. ABORT("pthread_mutex_unlock failed");
  2017. }
  2018. }
  2019. /* Collector must wait for a freelist builders for 2 reasons: */
  2020. /* 1) Mark bits may still be getting examined without lock. */
  2021. /* 2) Partial free lists referenced only by locals may not be scanned */
  2022. /* correctly, e.g. if they contain "pointer-free" objects, since the */
  2023. /* free-list link may be ignored. */
  2024. STATIC void GC_wait_builder(void)
  2025. {
  2026. ASSERT_CANCEL_DISABLED();
  2027. UNSET_MARK_LOCK_HOLDER;
  2028. if (pthread_cond_wait(&builder_cv, &mark_mutex) != 0) {
  2029. ABORT("pthread_cond_wait failed");
  2030. }
  2031. GC_ASSERT(GC_mark_lock_holder == NO_THREAD);
  2032. SET_MARK_LOCK_HOLDER;
  2033. }
  2034. GC_INNER void GC_wait_for_reclaim(void)
  2035. {
  2036. GC_acquire_mark_lock();
  2037. while (GC_fl_builder_count > 0) {
  2038. GC_wait_builder();
  2039. }
  2040. GC_release_mark_lock();
  2041. }
  2042. GC_INNER void GC_notify_all_builder(void)
  2043. {
  2044. GC_ASSERT(GC_mark_lock_holder == NUMERIC_THREAD_ID(pthread_self()));
  2045. if (pthread_cond_broadcast(&builder_cv) != 0) {
  2046. ABORT("pthread_cond_broadcast failed");
  2047. }
  2048. }
  2049. GC_INNER void GC_wait_marker(void)
  2050. {
  2051. ASSERT_CANCEL_DISABLED();
  2052. GC_ASSERT(GC_parallel);
  2053. UNSET_MARK_LOCK_HOLDER;
  2054. if (pthread_cond_wait(&mark_cv, &mark_mutex) != 0) {
  2055. ABORT("pthread_cond_wait failed");
  2056. }
  2057. GC_ASSERT(GC_mark_lock_holder == NO_THREAD);
  2058. SET_MARK_LOCK_HOLDER;
  2059. }
  2060. GC_INNER void GC_notify_all_marker(void)
  2061. {
  2062. GC_ASSERT(GC_parallel);
  2063. if (pthread_cond_broadcast(&mark_cv) != 0) {
  2064. ABORT("pthread_cond_broadcast failed");
  2065. }
  2066. }
  2067. #endif /* PARALLEL_MARK */
  2068. #ifdef PTHREAD_REGISTER_CANCEL_WEAK_STUBS
  2069. /* Workaround "undefined reference" linkage errors on some targets. */
  2070. EXTERN_C_BEGIN
  2071. extern void __pthread_register_cancel(void) __attribute__((__weak__));
  2072. extern void __pthread_unregister_cancel(void) __attribute__((__weak__));
  2073. EXTERN_C_END
  2074. void __pthread_register_cancel(void) {}
  2075. void __pthread_unregister_cancel(void) {}
  2076. #endif
  2077. #endif /* GC_PTHREADS */