pthread_cond_common.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. /* pthread_cond_common -- shared code for condition variable.
  2. Copyright (C) 2016-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  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, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include <atomic.h>
  16. #include <stdint.h>
  17. #include <pthread.h>
  18. /* We need 3 least-significant bits on __wrefs for something else. */
  19. #define __PTHREAD_COND_MAX_GROUP_SIZE ((unsigned) 1 << 29)
  20. #if __HAVE_64B_ATOMICS == 1
  21. static uint64_t __attribute__ ((unused))
  22. __condvar_load_wseq_relaxed (pthread_cond_t *cond)
  23. {
  24. return atomic_load_relaxed (&cond->__data.__wseq);
  25. }
  26. static uint64_t __attribute__ ((unused))
  27. __condvar_fetch_add_wseq_acquire (pthread_cond_t *cond, unsigned int val)
  28. {
  29. return atomic_fetch_add_acquire (&cond->__data.__wseq, val);
  30. }
  31. static uint64_t __attribute__ ((unused))
  32. __condvar_fetch_xor_wseq_release (pthread_cond_t *cond, unsigned int val)
  33. {
  34. return atomic_fetch_xor_release (&cond->__data.__wseq, val);
  35. }
  36. static uint64_t __attribute__ ((unused))
  37. __condvar_load_g1_start_relaxed (pthread_cond_t *cond)
  38. {
  39. return atomic_load_relaxed (&cond->__data.__g1_start);
  40. }
  41. static void __attribute__ ((unused))
  42. __condvar_add_g1_start_relaxed (pthread_cond_t *cond, unsigned int val)
  43. {
  44. atomic_store_relaxed (&cond->__data.__g1_start,
  45. atomic_load_relaxed (&cond->__data.__g1_start) + val);
  46. }
  47. #else
  48. /* We use two 64b counters: __wseq and __g1_start. They are monotonically
  49. increasing and single-writer-multiple-readers counters, so we can implement
  50. load, fetch-and-add, and fetch-and-xor operations even when we just have
  51. 32b atomics. Values we add or xor are less than or equal to 1<<31 (*),
  52. so we only have to make overflow-and-addition atomic wrt. to concurrent
  53. load operations and xor operations. To do that, we split each counter into
  54. two 32b values of which we reserve the MSB of each to represent an
  55. overflow from the lower-order half to the higher-order half.
  56. In the common case, the state is (higher-order / lower-order half, and . is
  57. basically concatenation of the bits):
  58. 0.h / 0.l = h.l
  59. When we add a value of x that overflows (i.e., 0.l + x == 1.L), we run the
  60. following steps S1-S4 (the values these represent are on the right-hand
  61. side):
  62. S1: 0.h / 1.L == (h+1).L
  63. S2: 1.(h+1) / 1.L == (h+1).L
  64. S3: 1.(h+1) / 0.L == (h+1).L
  65. S4: 0.(h+1) / 0.L == (h+1).L
  66. If the LSB of the higher-order half is set, readers will ignore the
  67. overflow bit in the lower-order half.
  68. To get an atomic snapshot in load operations, we exploit that the
  69. higher-order half is monotonically increasing; if we load a value V from
  70. it, then read the lower-order half, and then read the higher-order half
  71. again and see the same value V, we know that both halves have existed in
  72. the sequence of values the full counter had. This is similar to the
  73. validated reads in the time-based STMs in GCC's libitm (e.g.,
  74. method_ml_wt).
  75. The xor operation needs to be an atomic read-modify-write. The write
  76. itself is not an issue as it affects just the lower-order half but not bits
  77. used in the add operation. To make the full fetch-and-xor atomic, we
  78. exploit that concurrently, the value can increase by at most 1<<31 (*): The
  79. xor operation is only called while having acquired the lock, so not more
  80. than __PTHREAD_COND_MAX_GROUP_SIZE waiters can enter concurrently and thus
  81. increment __wseq. Therefore, if the xor operation observes a value of
  82. __wseq, then the value it applies the modification to later on can be
  83. derived (see below).
  84. One benefit of this scheme is that this makes load operations
  85. obstruction-free because unlike if we would just lock the counter, readers
  86. can almost always interpret a snapshot of each halves. Readers can be
  87. forced to read a new snapshot when the read is concurrent with an overflow.
  88. However, overflows will happen infrequently, so load operations are
  89. practically lock-free.
  90. (*) The highest value we add is __PTHREAD_COND_MAX_GROUP_SIZE << 2 to
  91. __g1_start (the two extra bits are for the lock in the two LSBs of
  92. __g1_start). */
  93. typedef struct
  94. {
  95. unsigned int low;
  96. unsigned int high;
  97. } _condvar_lohi;
  98. static uint64_t
  99. __condvar_fetch_add_64_relaxed (_condvar_lohi *lh, unsigned int op)
  100. {
  101. /* S1. Note that this is an atomic read-modify-write so it extends the
  102. release sequence of release MO store at S3. */
  103. unsigned int l = atomic_fetch_add_relaxed (&lh->low, op);
  104. unsigned int h = atomic_load_relaxed (&lh->high);
  105. uint64_t result = ((uint64_t) h << 31) | l;
  106. l += op;
  107. if ((l >> 31) > 0)
  108. {
  109. /* Overflow. Need to increment higher-order half. Note that all
  110. add operations are ordered in happens-before. */
  111. h++;
  112. /* S2. Release MO to synchronize with the loads of the higher-order half
  113. in the load operation. See __condvar_load_64_relaxed. */
  114. atomic_store_release (&lh->high, h | ((unsigned int) 1 << 31));
  115. l ^= (unsigned int) 1 << 31;
  116. /* S3. See __condvar_load_64_relaxed. */
  117. atomic_store_release (&lh->low, l);
  118. /* S4. Likewise. */
  119. atomic_store_release (&lh->high, h);
  120. }
  121. return result;
  122. }
  123. static uint64_t
  124. __condvar_load_64_relaxed (_condvar_lohi *lh)
  125. {
  126. unsigned int h, l, h2;
  127. do
  128. {
  129. /* This load and the second one below to the same location read from the
  130. stores in the overflow handling of the add operation or the
  131. initializing stores (which is a simple special case because
  132. initialization always completely happens before further use).
  133. Because no two stores to the higher-order half write the same value,
  134. the loop ensures that if we continue to use the snapshot, this load
  135. and the second one read from the same store operation. All candidate
  136. store operations have release MO.
  137. If we read from S2 in the first load, then we will see the value of
  138. S1 on the next load (because we synchronize with S2), or a value
  139. later in modification order. We correctly ignore the lower-half's
  140. overflow bit in this case. If we read from S4, then we will see the
  141. value of S3 in the next load (or a later value), which does not have
  142. the overflow bit set anymore.
  143. */
  144. h = atomic_load_acquire (&lh->high);
  145. /* This will read from the release sequence of S3 (i.e, either the S3
  146. store or the read-modify-writes at S1 following S3 in modification
  147. order). Thus, the read synchronizes with S3, and the following load
  148. of the higher-order half will read from the matching S2 (or a later
  149. value).
  150. Thus, if we read a lower-half value here that already overflowed and
  151. belongs to an increased higher-order half value, we will see the
  152. latter and h and h2 will not be equal. */
  153. l = atomic_load_acquire (&lh->low);
  154. /* See above. */
  155. h2 = atomic_load_relaxed (&lh->high);
  156. }
  157. while (h != h2);
  158. if (((l >> 31) > 0) && ((h >> 31) > 0))
  159. l ^= (unsigned int) 1 << 31;
  160. return ((uint64_t) (h & ~((unsigned int) 1 << 31)) << 31) + l;
  161. }
  162. static uint64_t __attribute__ ((unused))
  163. __condvar_load_wseq_relaxed (pthread_cond_t *cond)
  164. {
  165. return __condvar_load_64_relaxed ((_condvar_lohi *) &cond->__data.__wseq32);
  166. }
  167. static uint64_t __attribute__ ((unused))
  168. __condvar_fetch_add_wseq_acquire (pthread_cond_t *cond, unsigned int val)
  169. {
  170. uint64_t r = __condvar_fetch_add_64_relaxed
  171. ((_condvar_lohi *) &cond->__data.__wseq32, val);
  172. atomic_thread_fence_acquire ();
  173. return r;
  174. }
  175. static uint64_t __attribute__ ((unused))
  176. __condvar_fetch_xor_wseq_release (pthread_cond_t *cond, unsigned int val)
  177. {
  178. _condvar_lohi *lh = (_condvar_lohi *) &cond->__data.__wseq32;
  179. /* First, get the current value. See __condvar_load_64_relaxed. */
  180. unsigned int h, l, h2;
  181. do
  182. {
  183. h = atomic_load_acquire (&lh->high);
  184. l = atomic_load_acquire (&lh->low);
  185. h2 = atomic_load_relaxed (&lh->high);
  186. }
  187. while (h != h2);
  188. if (((l >> 31) > 0) && ((h >> 31) == 0))
  189. h++;
  190. h &= ~((unsigned int) 1 << 31);
  191. l &= ~((unsigned int) 1 << 31);
  192. /* Now modify. Due to the coherence rules, the prior load will read a value
  193. earlier in modification order than the following fetch-xor.
  194. This uses release MO to make the full operation have release semantics
  195. (all other operations access the lower-order half). */
  196. unsigned int l2 = atomic_fetch_xor_release (&lh->low, val)
  197. & ~((unsigned int) 1 << 31);
  198. if (l2 < l)
  199. /* The lower-order half overflowed in the meantime. This happened exactly
  200. once due to the limit on concurrent waiters (see above). */
  201. h++;
  202. return ((uint64_t) h << 31) + l2;
  203. }
  204. static uint64_t __attribute__ ((unused))
  205. __condvar_load_g1_start_relaxed (pthread_cond_t *cond)
  206. {
  207. return __condvar_load_64_relaxed
  208. ((_condvar_lohi *) &cond->__data.__g1_start32);
  209. }
  210. static void __attribute__ ((unused))
  211. __condvar_add_g1_start_relaxed (pthread_cond_t *cond, unsigned int val)
  212. {
  213. ignore_value (__condvar_fetch_add_64_relaxed
  214. ((_condvar_lohi *) &cond->__data.__g1_start32, val));
  215. }
  216. #endif /* !__HAVE_64B_ATOMICS */
  217. /* The lock that signalers use. See pthread_cond_wait_common for uses.
  218. The lock is our normal three-state lock: not acquired (0) / acquired (1) /
  219. acquired-with-futex_wake-request (2). However, we need to preserve the
  220. other bits in the unsigned int used for the lock, and therefore it is a
  221. little more complex. */
  222. static void __attribute__ ((unused))
  223. __condvar_acquire_lock (pthread_cond_t *cond, int private)
  224. {
  225. unsigned int s = atomic_load_relaxed (&cond->__data.__g1_orig_size);
  226. while ((s & 3) == 0)
  227. {
  228. if (atomic_compare_exchange_weak_acquire (&cond->__data.__g1_orig_size,
  229. &s, s | 1))
  230. return;
  231. /* TODO Spinning and back-off. */
  232. }
  233. /* We can't change from not acquired to acquired, so try to change to
  234. acquired-with-futex-wake-request and do a futex wait if we cannot change
  235. from not acquired. */
  236. while (1)
  237. {
  238. while ((s & 3) != 2)
  239. {
  240. if (atomic_compare_exchange_weak_acquire
  241. (&cond->__data.__g1_orig_size, &s, (s & ~(unsigned int) 3) | 2))
  242. {
  243. if ((s & 3) == 0)
  244. return;
  245. break;
  246. }
  247. /* TODO Back off. */
  248. }
  249. futex_wait_simple (&cond->__data.__g1_orig_size,
  250. (s & ~(unsigned int) 3) | 2, private);
  251. /* Reload so we see a recent value. */
  252. s = atomic_load_relaxed (&cond->__data.__g1_orig_size);
  253. }
  254. }
  255. /* See __condvar_acquire_lock. */
  256. static void __attribute__ ((unused))
  257. __condvar_release_lock (pthread_cond_t *cond, int private)
  258. {
  259. if ((atomic_fetch_and_release (&cond->__data.__g1_orig_size,
  260. ~(unsigned int) 3) & 3)
  261. == 2)
  262. futex_wake (&cond->__data.__g1_orig_size, 1, private);
  263. }
  264. /* Only use this when having acquired the lock. */
  265. static unsigned int __attribute__ ((unused))
  266. __condvar_get_orig_size (pthread_cond_t *cond)
  267. {
  268. return atomic_load_relaxed (&cond->__data.__g1_orig_size) >> 2;
  269. }
  270. /* Only use this when having acquired the lock. */
  271. static void __attribute__ ((unused))
  272. __condvar_set_orig_size (pthread_cond_t *cond, unsigned int size)
  273. {
  274. /* We have acquired the lock, but might get one concurrent update due to a
  275. lock state change from acquired to acquired-with-futex_wake-request.
  276. The store with relaxed MO is fine because there will be no further
  277. changes to the lock bits nor the size, and we will subsequently release
  278. the lock with release MO. */
  279. unsigned int s;
  280. s = (atomic_load_relaxed (&cond->__data.__g1_orig_size) & 3)
  281. | (size << 2);
  282. if ((atomic_exchange_relaxed (&cond->__data.__g1_orig_size, s) & 3)
  283. != (s & 3))
  284. atomic_store_relaxed (&cond->__data.__g1_orig_size, (size << 2) | 2);
  285. }
  286. /* Returns FUTEX_SHARED or FUTEX_PRIVATE based on the provided __wrefs
  287. value. */
  288. static int __attribute__ ((unused))
  289. __condvar_get_private (int flags)
  290. {
  291. if ((flags & __PTHREAD_COND_SHARED_MASK) == 0)
  292. return FUTEX_PRIVATE;
  293. else
  294. return FUTEX_SHARED;
  295. }
  296. /* This closes G1 (whose index is in G1INDEX), waits for all futex waiters to
  297. leave G1, converts G1 into a fresh G2, and then switches group roles so that
  298. the former G2 becomes the new G1 ending at the current __wseq value when we
  299. eventually make the switch (WSEQ is just an observation of __wseq by the
  300. signaler).
  301. If G2 is empty, it will not switch groups because then it would create an
  302. empty G1 which would require switching groups again on the next signal.
  303. Returns false iff groups were not switched because G2 was empty. */
  304. static bool __attribute__ ((unused))
  305. __condvar_quiesce_and_switch_g1 (pthread_cond_t *cond, uint64_t wseq,
  306. unsigned int *g1index, int private)
  307. {
  308. const unsigned int maxspin = 0;
  309. unsigned int g1 = *g1index;
  310. /* If there is no waiter in G2, we don't do anything. The expression may
  311. look odd but remember that __g_size might hold a negative value, so
  312. putting the expression this way avoids relying on implementation-defined
  313. behavior.
  314. Note that this works correctly for a zero-initialized condvar too. */
  315. unsigned int old_orig_size = __condvar_get_orig_size (cond);
  316. uint64_t old_g1_start = __condvar_load_g1_start_relaxed (cond) >> 1;
  317. if (((unsigned) (wseq - old_g1_start - old_orig_size)
  318. + cond->__data.__g_size[g1 ^ 1]) == 0)
  319. return false;
  320. /* Now try to close and quiesce G1. We have to consider the following kinds
  321. of waiters:
  322. * Waiters from less recent groups than G1 are not affected because
  323. nothing will change for them apart from __g1_start getting larger.
  324. * New waiters arriving concurrently with the group switching will all go
  325. into G2 until we atomically make the switch. Waiters existing in G2
  326. are not affected.
  327. * Waiters in G1 will be closed out immediately by setting a flag in
  328. __g_signals, which will prevent waiters from blocking using a futex on
  329. __g_signals and also notifies them that the group is closed. As a
  330. result, they will eventually remove their group reference, allowing us
  331. to close switch group roles. */
  332. /* First, set the closed flag on __g_signals. This tells waiters that are
  333. about to wait that they shouldn't do that anymore. This basically
  334. serves as an advance notificaton of the upcoming change to __g1_start;
  335. waiters interpret it as if __g1_start was larger than their waiter
  336. sequence position. This allows us to change __g1_start after waiting
  337. for all existing waiters with group references to leave, which in turn
  338. makes recovery after stealing a signal simpler because it then can be
  339. skipped if __g1_start indicates that the group is closed (otherwise,
  340. we would have to recover always because waiters don't know how big their
  341. groups are). Relaxed MO is fine. */
  342. atomic_fetch_or_relaxed (cond->__data.__g_signals + g1, 1);
  343. /* Wait until there are no group references anymore. The fetch-or operation
  344. injects us into the modification order of __g_refs; release MO ensures
  345. that waiters incrementing __g_refs after our fetch-or see the previous
  346. changes to __g_signals and to __g1_start that had to happen before we can
  347. switch this G1 and alias with an older group (we have two groups, so
  348. aliasing requires switching group roles twice). Note that nobody else
  349. can have set the wake-request flag, so we do not have to act upon it.
  350. Also note that it is harmless if older waiters or waiters from this G1
  351. get a group reference after we have quiesced the group because it will
  352. remain closed for them either because of the closed flag in __g_signals
  353. or the later update to __g1_start. New waiters will never arrive here
  354. but instead continue to go into the still current G2. */
  355. unsigned r = atomic_fetch_or_release (cond->__data.__g_refs + g1, 0);
  356. while ((r >> 1) > 0)
  357. {
  358. for (unsigned int spin = maxspin; ((r >> 1) > 0) && (spin > 0); spin--)
  359. {
  360. /* TODO Back off. */
  361. r = atomic_load_relaxed (cond->__data.__g_refs + g1);
  362. }
  363. if ((r >> 1) > 0)
  364. {
  365. /* There is still a waiter after spinning. Set the wake-request
  366. flag and block. Relaxed MO is fine because this is just about
  367. this futex word.
  368. Update r to include the set wake-request flag so that the upcoming
  369. futex_wait only blocks if the flag is still set (otherwise, we'd
  370. violate the basic client-side futex protocol). */
  371. r = atomic_fetch_or_relaxed (cond->__data.__g_refs + g1, 1) | 1;
  372. if ((r >> 1) > 0)
  373. futex_wait_simple (cond->__data.__g_refs + g1, r, private);
  374. /* Reload here so we eventually see the most recent value even if we
  375. do not spin. */
  376. r = atomic_load_relaxed (cond->__data.__g_refs + g1);
  377. }
  378. }
  379. /* Acquire MO so that we synchronize with the release operation that waiters
  380. use to decrement __g_refs and thus happen after the waiters we waited
  381. for. */
  382. atomic_thread_fence_acquire ();
  383. /* Update __g1_start, which finishes closing this group. The value we add
  384. will never be negative because old_orig_size can only be zero when we
  385. switch groups the first time after a condvar was initialized, in which
  386. case G1 will be at index 1 and we will add a value of 1. See above for
  387. why this takes place after waiting for quiescence of the group.
  388. Relaxed MO is fine because the change comes with no additional
  389. constraints that others would have to observe. */
  390. __condvar_add_g1_start_relaxed (cond,
  391. (old_orig_size << 1) + (g1 == 1 ? 1 : - 1));
  392. /* Now reopen the group, thus enabling waiters to again block using the
  393. futex controlled by __g_signals. Release MO so that observers that see
  394. no signals (and thus can block) also see the write __g1_start and thus
  395. that this is now a new group (see __pthread_cond_wait_common for the
  396. matching acquire MO loads). */
  397. atomic_store_release (cond->__data.__g_signals + g1, 0);
  398. /* At this point, the old G1 is now a valid new G2 (but not in use yet).
  399. No old waiter can neither grab a signal nor acquire a reference without
  400. noticing that __g1_start is larger.
  401. We can now publish the group switch by flipping the G2 index in __wseq.
  402. Release MO so that this synchronizes with the acquire MO operation
  403. waiters use to obtain a position in the waiter sequence. */
  404. wseq = __condvar_fetch_xor_wseq_release (cond, 1) >> 1;
  405. g1 ^= 1;
  406. *g1index ^= 1;
  407. /* These values are just observed by signalers, and thus protected by the
  408. lock. */
  409. unsigned int orig_size = wseq - (old_g1_start + old_orig_size);
  410. __condvar_set_orig_size (cond, orig_size);
  411. /* Use and addition to not loose track of cancellations in what was
  412. previously G2. */
  413. cond->__data.__g_size[g1] += orig_size;
  414. /* The new G1's size may be zero because of cancellations during its time
  415. as G2. If this happens, there are no waiters that have to receive a
  416. signal, so we do not need to add any and return false. */
  417. if (cond->__data.__g_size[g1] == 0)
  418. return false;
  419. return true;
  420. }