srcu.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. /*
  2. * Sleepable Read-Copy Update mechanism for mutual exclusion.
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software
  16. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  17. *
  18. * Copyright (C) IBM Corporation, 2006
  19. *
  20. * Author: Paul McKenney <paulmck@us.ibm.com>
  21. *
  22. * For detailed explanation of Read-Copy Update mechanism see -
  23. * Documentation/RCU/ *.txt
  24. *
  25. */
  26. #include <linux/export.h>
  27. #include <linux/mutex.h>
  28. #include <linux/percpu.h>
  29. #include <linux/preempt.h>
  30. #include <linux/rcupdate.h>
  31. #include <linux/sched.h>
  32. #include <linux/smp.h>
  33. #include <linux/delay.h>
  34. #include <linux/srcu.h>
  35. static int init_srcu_struct_fields(struct srcu_struct *sp)
  36. {
  37. sp->completed = 0;
  38. mutex_init(&sp->mutex);
  39. sp->per_cpu_ref = alloc_percpu(struct srcu_struct_array);
  40. return sp->per_cpu_ref ? 0 : -ENOMEM;
  41. }
  42. #ifdef CONFIG_DEBUG_LOCK_ALLOC
  43. int __init_srcu_struct(struct srcu_struct *sp, const char *name,
  44. struct lock_class_key *key)
  45. {
  46. /* Don't re-initialize a lock while it is held. */
  47. debug_check_no_locks_freed((void *)sp, sizeof(*sp));
  48. lockdep_init_map(&sp->dep_map, name, key, 0);
  49. return init_srcu_struct_fields(sp);
  50. }
  51. EXPORT_SYMBOL_GPL(__init_srcu_struct);
  52. #else /* #ifdef CONFIG_DEBUG_LOCK_ALLOC */
  53. /**
  54. * init_srcu_struct - initialize a sleep-RCU structure
  55. * @sp: structure to initialize.
  56. *
  57. * Must invoke this on a given srcu_struct before passing that srcu_struct
  58. * to any other function. Each srcu_struct represents a separate domain
  59. * of SRCU protection.
  60. */
  61. int init_srcu_struct(struct srcu_struct *sp)
  62. {
  63. return init_srcu_struct_fields(sp);
  64. }
  65. EXPORT_SYMBOL_GPL(init_srcu_struct);
  66. #endif /* #else #ifdef CONFIG_DEBUG_LOCK_ALLOC */
  67. /*
  68. * Returns approximate number of readers active on the specified rank
  69. * of per-CPU counters. Also snapshots each counter's value in the
  70. * corresponding element of sp->snap[] for later use validating
  71. * the sum.
  72. */
  73. static unsigned long srcu_readers_active_idx(struct srcu_struct *sp, int idx)
  74. {
  75. int cpu;
  76. unsigned long sum = 0;
  77. unsigned long t;
  78. for_each_possible_cpu(cpu) {
  79. t = ACCESS_ONCE(per_cpu_ptr(sp->per_cpu_ref, cpu)->c[idx]);
  80. sum += t;
  81. sp->snap[cpu] = t;
  82. }
  83. return sum & SRCU_REF_MASK;
  84. }
  85. /*
  86. * To be called from the update side after an index flip. Returns true
  87. * if the modulo sum of the counters is stably zero, false if there is
  88. * some possibility of non-zero.
  89. */
  90. static bool srcu_readers_active_idx_check(struct srcu_struct *sp, int idx)
  91. {
  92. int cpu;
  93. /*
  94. * Note that srcu_readers_active_idx() can incorrectly return
  95. * zero even though there is a pre-existing reader throughout.
  96. * To see this, suppose that task A is in a very long SRCU
  97. * read-side critical section that started on CPU 0, and that
  98. * no other reader exists, so that the modulo sum of the counters
  99. * is equal to one. Then suppose that task B starts executing
  100. * srcu_readers_active_idx(), summing up to CPU 1, and then that
  101. * task C starts reading on CPU 0, so that its increment is not
  102. * summed, but finishes reading on CPU 2, so that its decrement
  103. * -is- summed. Then when task B completes its sum, it will
  104. * incorrectly get zero, despite the fact that task A has been
  105. * in its SRCU read-side critical section the whole time.
  106. *
  107. * We therefore do a validation step should srcu_readers_active_idx()
  108. * return zero.
  109. */
  110. if (srcu_readers_active_idx(sp, idx) != 0)
  111. return false;
  112. /*
  113. * Since the caller recently flipped ->completed, we can see at
  114. * most one increment of each CPU's counter from this point
  115. * forward. The reason for this is that the reader CPU must have
  116. * fetched the index before srcu_readers_active_idx checked
  117. * that CPU's counter, but not yet incremented its counter.
  118. * Its eventual counter increment will follow the read in
  119. * srcu_readers_active_idx(), and that increment is immediately
  120. * followed by smp_mb() B. Because smp_mb() D is between
  121. * the ->completed flip and srcu_readers_active_idx()'s read,
  122. * that CPU's subsequent load of ->completed must see the new
  123. * value, and therefore increment the counter in the other rank.
  124. */
  125. smp_mb(); /* A */
  126. /*
  127. * Now, we check the ->snap array that srcu_readers_active_idx()
  128. * filled in from the per-CPU counter values. Since both
  129. * __srcu_read_lock() and __srcu_read_unlock() increment the
  130. * upper bits of the per-CPU counter, an increment/decrement
  131. * pair will change the value of the counter. Since there is
  132. * only one possible increment, the only way to wrap the counter
  133. * is to have a huge number of counter decrements, which requires
  134. * a huge number of tasks and huge SRCU read-side critical-section
  135. * nesting levels, even on 32-bit systems.
  136. *
  137. * All of the ways of confusing the readings require that the scan
  138. * in srcu_readers_active_idx() see the read-side task's decrement,
  139. * but not its increment. However, between that decrement and
  140. * increment are smb_mb() B and C. Either or both of these pair
  141. * with smp_mb() A above to ensure that the scan below will see
  142. * the read-side tasks's increment, thus noting a difference in
  143. * the counter values between the two passes.
  144. *
  145. * Therefore, if srcu_readers_active_idx() returned zero, and
  146. * none of the counters changed, we know that the zero was the
  147. * correct sum.
  148. *
  149. * Of course, it is possible that a task might be delayed
  150. * for a very long time in __srcu_read_lock() after fetching
  151. * the index but before incrementing its counter. This
  152. * possibility will be dealt with in __synchronize_srcu().
  153. */
  154. for_each_possible_cpu(cpu)
  155. if (sp->snap[cpu] !=
  156. ACCESS_ONCE(per_cpu_ptr(sp->per_cpu_ref, cpu)->c[idx]))
  157. return false; /* False zero reading! */
  158. return true;
  159. }
  160. /**
  161. * srcu_readers_active - returns approximate number of readers.
  162. * @sp: which srcu_struct to count active readers (holding srcu_read_lock).
  163. *
  164. * Note that this is not an atomic primitive, and can therefore suffer
  165. * severe errors when invoked on an active srcu_struct. That said, it
  166. * can be useful as an error check at cleanup time.
  167. */
  168. static int srcu_readers_active(struct srcu_struct *sp)
  169. {
  170. return srcu_readers_active_idx(sp, 0) + srcu_readers_active_idx(sp, 1);
  171. }
  172. /**
  173. * cleanup_srcu_struct - deconstruct a sleep-RCU structure
  174. * @sp: structure to clean up.
  175. *
  176. * Must invoke this after you are finished using a given srcu_struct that
  177. * was initialized via init_srcu_struct(), else you leak memory.
  178. */
  179. void cleanup_srcu_struct(struct srcu_struct *sp)
  180. {
  181. int sum;
  182. sum = srcu_readers_active(sp);
  183. WARN_ON(sum); /* Leakage unless caller handles error. */
  184. if (sum != 0)
  185. return;
  186. free_percpu(sp->per_cpu_ref);
  187. sp->per_cpu_ref = NULL;
  188. }
  189. EXPORT_SYMBOL_GPL(cleanup_srcu_struct);
  190. /*
  191. * Counts the new reader in the appropriate per-CPU element of the
  192. * srcu_struct. Must be called from process context.
  193. * Returns an index that must be passed to the matching srcu_read_unlock().
  194. */
  195. int __srcu_read_lock(struct srcu_struct *sp)
  196. {
  197. int idx;
  198. preempt_disable();
  199. idx = rcu_dereference_index_check(sp->completed,
  200. rcu_read_lock_sched_held()) & 0x1;
  201. ACCESS_ONCE(this_cpu_ptr(sp->per_cpu_ref)->c[idx]) +=
  202. SRCU_USAGE_COUNT + 1;
  203. smp_mb(); /* B */ /* Avoid leaking the critical section. */
  204. preempt_enable();
  205. return idx;
  206. }
  207. EXPORT_SYMBOL_GPL(__srcu_read_lock);
  208. /*
  209. * Removes the count for the old reader from the appropriate per-CPU
  210. * element of the srcu_struct. Note that this may well be a different
  211. * CPU than that which was incremented by the corresponding srcu_read_lock().
  212. * Must be called from process context.
  213. */
  214. void __srcu_read_unlock(struct srcu_struct *sp, int idx)
  215. {
  216. preempt_disable();
  217. smp_mb(); /* C */ /* Avoid leaking the critical section. */
  218. ACCESS_ONCE(this_cpu_ptr(sp->per_cpu_ref)->c[idx]) +=
  219. SRCU_USAGE_COUNT - 1;
  220. preempt_enable();
  221. }
  222. EXPORT_SYMBOL_GPL(__srcu_read_unlock);
  223. /*
  224. * We use an adaptive strategy for synchronize_srcu() and especially for
  225. * synchronize_srcu_expedited(). We spin for a fixed time period
  226. * (defined below) to allow SRCU readers to exit their read-side critical
  227. * sections. If there are still some readers after 10 microseconds,
  228. * we repeatedly block for 1-millisecond time periods. This approach
  229. * has done well in testing, so there is no need for a config parameter.
  230. */
  231. #define SYNCHRONIZE_SRCU_READER_DELAY 5
  232. /*
  233. * Flip the readers' index by incrementing ->completed, then wait
  234. * until there are no more readers using the counters referenced by
  235. * the old index value. (Recall that the index is the bottom bit
  236. * of ->completed.)
  237. *
  238. * Of course, it is possible that a reader might be delayed for the
  239. * full duration of flip_idx_and_wait() between fetching the
  240. * index and incrementing its counter. This possibility is handled
  241. * by __synchronize_srcu() invoking flip_idx_and_wait() twice.
  242. */
  243. static void flip_idx_and_wait(struct srcu_struct *sp, bool expedited)
  244. {
  245. int idx;
  246. int trycount = 0;
  247. idx = sp->completed++ & 0x1;
  248. /*
  249. * If a reader fetches the index before the above increment,
  250. * but increments its counter after srcu_readers_active_idx_check()
  251. * sums it, then smp_mb() D will pair with __srcu_read_lock()'s
  252. * smp_mb() B to ensure that the SRCU read-side critical section
  253. * will see any updates that the current task performed before its
  254. * call to synchronize_srcu(), or to synchronize_srcu_expedited(),
  255. * as the case may be.
  256. */
  257. smp_mb(); /* D */
  258. /*
  259. * SRCU read-side critical sections are normally short, so wait
  260. * a small amount of time before possibly blocking.
  261. */
  262. if (!srcu_readers_active_idx_check(sp, idx)) {
  263. udelay(SYNCHRONIZE_SRCU_READER_DELAY);
  264. while (!srcu_readers_active_idx_check(sp, idx)) {
  265. if (expedited && ++ trycount < 10)
  266. udelay(SYNCHRONIZE_SRCU_READER_DELAY);
  267. else
  268. schedule_timeout_interruptible(1);
  269. }
  270. }
  271. /*
  272. * The following smp_mb() E pairs with srcu_read_unlock()'s
  273. * smp_mb C to ensure that if srcu_readers_active_idx_check()
  274. * sees srcu_read_unlock()'s counter decrement, then any
  275. * of the current task's subsequent code will happen after
  276. * that SRCU read-side critical section.
  277. */
  278. smp_mb(); /* E */
  279. }
  280. /*
  281. * Helper function for synchronize_srcu() and synchronize_srcu_expedited().
  282. */
  283. static void __synchronize_srcu(struct srcu_struct *sp, bool expedited)
  284. {
  285. int idx;
  286. rcu_lockdep_assert(!lock_is_held(&sp->dep_map) &&
  287. !lock_is_held(&rcu_bh_lock_map) &&
  288. !lock_is_held(&rcu_lock_map) &&
  289. !lock_is_held(&rcu_sched_lock_map),
  290. "Illegal synchronize_srcu() in same-type SRCU (or RCU) read-side critical section");
  291. smp_mb(); /* Ensure prior action happens before grace period. */
  292. idx = ACCESS_ONCE(sp->completed);
  293. smp_mb(); /* Access to ->completed before lock acquisition. */
  294. mutex_lock(&sp->mutex);
  295. /*
  296. * Check to see if someone else did the work for us while we were
  297. * waiting to acquire the lock. We need -three- advances of
  298. * the counter, not just one. If there was but one, we might have
  299. * shown up -after- our helper's first synchronize_sched(), thus
  300. * having failed to prevent CPU-reordering races with concurrent
  301. * srcu_read_unlock()s on other CPUs (see comment below). If there
  302. * was only two, we are guaranteed to have waited through only one
  303. * full index-flip phase. So we either (1) wait for three or
  304. * (2) supply the additional ones we need.
  305. */
  306. if (sp->completed == idx + 2)
  307. idx = 1;
  308. else if (sp->completed == idx + 3) {
  309. mutex_unlock(&sp->mutex);
  310. return;
  311. } else
  312. idx = 0;
  313. /*
  314. * If there were no helpers, then we need to do two flips of
  315. * the index. The first flip is required if there are any
  316. * outstanding SRCU readers even if there are no new readers
  317. * running concurrently with the first counter flip.
  318. *
  319. * The second flip is required when a new reader picks up
  320. * the old value of the index, but does not increment its
  321. * counter until after its counters is summed/rechecked by
  322. * srcu_readers_active_idx_check(). In this case, the current SRCU
  323. * grace period would be OK because the SRCU read-side critical
  324. * section started after this SRCU grace period started, so the
  325. * grace period is not required to wait for the reader.
  326. *
  327. * However, the next SRCU grace period would be waiting for the
  328. * other set of counters to go to zero, and therefore would not
  329. * wait for the reader, which would be very bad. To avoid this
  330. * bad scenario, we flip and wait twice, clearing out both sets
  331. * of counters.
  332. */
  333. for (; idx < 2; idx++)
  334. flip_idx_and_wait(sp, expedited);
  335. mutex_unlock(&sp->mutex);
  336. }
  337. /**
  338. * synchronize_srcu - wait for prior SRCU read-side critical-section completion
  339. * @sp: srcu_struct with which to synchronize.
  340. *
  341. * Flip the completed counter, and wait for the old count to drain to zero.
  342. * As with classic RCU, the updater must use some separate means of
  343. * synchronizing concurrent updates. Can block; must be called from
  344. * process context.
  345. *
  346. * Note that it is illegal to call synchronize_srcu() from the corresponding
  347. * SRCU read-side critical section; doing so will result in deadlock.
  348. * However, it is perfectly legal to call synchronize_srcu() on one
  349. * srcu_struct from some other srcu_struct's read-side critical section.
  350. */
  351. void synchronize_srcu(struct srcu_struct *sp)
  352. {
  353. __synchronize_srcu(sp, 0);
  354. }
  355. EXPORT_SYMBOL_GPL(synchronize_srcu);
  356. /**
  357. * synchronize_srcu_expedited - Brute-force SRCU grace period
  358. * @sp: srcu_struct with which to synchronize.
  359. *
  360. * Wait for an SRCU grace period to elapse, but be more aggressive about
  361. * spinning rather than blocking when waiting.
  362. *
  363. * Note that it is illegal to call this function while holding any lock
  364. * that is acquired by a CPU-hotplug notifier. It is also illegal to call
  365. * synchronize_srcu_expedited() from the corresponding SRCU read-side
  366. * critical section; doing so will result in deadlock. However, it is
  367. * perfectly legal to call synchronize_srcu_expedited() on one srcu_struct
  368. * from some other srcu_struct's read-side critical section, as long as
  369. * the resulting graph of srcu_structs is acyclic.
  370. */
  371. void synchronize_srcu_expedited(struct srcu_struct *sp)
  372. {
  373. __synchronize_srcu(sp, 1);
  374. }
  375. EXPORT_SYMBOL_GPL(synchronize_srcu_expedited);
  376. /**
  377. * srcu_batches_completed - return batches completed.
  378. * @sp: srcu_struct on which to report batch completion.
  379. *
  380. * Report the number of batches, correlated with, but not necessarily
  381. * precisely the same as, the number of grace periods that have elapsed.
  382. */
  383. long srcu_batches_completed(struct srcu_struct *sp)
  384. {
  385. return sp->completed;
  386. }
  387. EXPORT_SYMBOL_GPL(srcu_batches_completed);