srcu.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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
  129. * __srcu_read_lock() increments the upper bits of the per-CPU
  130. * counter, an increment/decrement pair will change the value
  131. * of the counter. Since there is only one possible increment,
  132. * the only way to wrap the counter is to have a huge number of
  133. * counter decrements, which requires a huge number of tasks and
  134. * huge SRCU read-side critical-section nesting levels, even on
  135. * 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]) -= 1;
  219. preempt_enable();
  220. }
  221. EXPORT_SYMBOL_GPL(__srcu_read_unlock);
  222. /*
  223. * We use an adaptive strategy for synchronize_srcu() and especially for
  224. * synchronize_srcu_expedited(). We spin for a fixed time period
  225. * (defined below) to allow SRCU readers to exit their read-side critical
  226. * sections. If there are still some readers after 10 microseconds,
  227. * we repeatedly block for 1-millisecond time periods. This approach
  228. * has done well in testing, so there is no need for a config parameter.
  229. */
  230. #define SYNCHRONIZE_SRCU_READER_DELAY 5
  231. /*
  232. * Wait until all pre-existing readers complete. Such readers
  233. * will have used the index specified by "idx".
  234. */
  235. static void wait_idx(struct srcu_struct *sp, int idx, bool expedited)
  236. {
  237. int trycount = 0;
  238. /*
  239. * If a reader fetches the index before the ->completed increment,
  240. * but increments its counter after srcu_readers_active_idx_check()
  241. * sums it, then smp_mb() D will pair with __srcu_read_lock()'s
  242. * smp_mb() B to ensure that the SRCU read-side critical section
  243. * will see any updates that the current task performed before its
  244. * call to synchronize_srcu(), or to synchronize_srcu_expedited(),
  245. * as the case may be.
  246. */
  247. smp_mb(); /* D */
  248. /*
  249. * SRCU read-side critical sections are normally short, so wait
  250. * a small amount of time before possibly blocking.
  251. */
  252. if (!srcu_readers_active_idx_check(sp, idx)) {
  253. udelay(SYNCHRONIZE_SRCU_READER_DELAY);
  254. while (!srcu_readers_active_idx_check(sp, idx)) {
  255. if (expedited && ++ trycount < 10)
  256. udelay(SYNCHRONIZE_SRCU_READER_DELAY);
  257. else
  258. schedule_timeout_interruptible(1);
  259. }
  260. }
  261. /*
  262. * The following smp_mb() E pairs with srcu_read_unlock()'s
  263. * smp_mb C to ensure that if srcu_readers_active_idx_check()
  264. * sees srcu_read_unlock()'s counter decrement, then any
  265. * of the current task's subsequent code will happen after
  266. * that SRCU read-side critical section.
  267. *
  268. * It also ensures the order between the above waiting and
  269. * the next flipping.
  270. */
  271. smp_mb(); /* E */
  272. }
  273. static void srcu_flip(struct srcu_struct *sp)
  274. {
  275. sp->completed++;
  276. }
  277. /*
  278. * Helper function for synchronize_srcu() and synchronize_srcu_expedited().
  279. */
  280. static void __synchronize_srcu(struct srcu_struct *sp, bool expedited)
  281. {
  282. int busy_idx;
  283. rcu_lockdep_assert(!lock_is_held(&sp->dep_map) &&
  284. !lock_is_held(&rcu_bh_lock_map) &&
  285. !lock_is_held(&rcu_lock_map) &&
  286. !lock_is_held(&rcu_sched_lock_map),
  287. "Illegal synchronize_srcu() in same-type SRCU (or RCU) read-side critical section");
  288. mutex_lock(&sp->mutex);
  289. busy_idx = sp->completed & 0X1UL;
  290. /*
  291. * If we recently flipped the index, there will be some readers
  292. * using idx=0 and others using idx=1. Therefore, two calls to
  293. * wait_idx()s suffice to ensure that all pre-existing readers
  294. * have completed:
  295. *
  296. * __synchronize_srcu() {
  297. * wait_idx(sp, 0, expedited);
  298. * wait_idx(sp, 1, expedited);
  299. * }
  300. *
  301. * Starvation is prevented by the fact that we flip the index.
  302. * While we wait on one index to clear out, almost all new readers
  303. * will be using the other index. The number of new readers using the
  304. * index we are waiting on is sharply bounded by roughly the number
  305. * of CPUs.
  306. *
  307. * How can new readers possibly using the old pre-flip value of
  308. * the index? Consider the following sequence of events:
  309. *
  310. * Suppose that during the previous grace period, a reader
  311. * picked up the old value of the index, but did not increment
  312. * its counter until after the previous instance of
  313. * __synchronize_srcu() did the counter summation and recheck.
  314. * That previous grace period was OK because the reader did
  315. * not start until after the grace period started, so the grace
  316. * period was not obligated to wait for that reader.
  317. *
  318. * However, this sequence of events is quite improbable, so
  319. * this call to wait_idx(), which waits on really old readers
  320. * describe in this comment above, will almost never need to wait.
  321. */
  322. wait_idx(sp, 1 - busy_idx, expedited);
  323. /* Flip the index to avoid reader-induced starvation. */
  324. srcu_flip(sp);
  325. /* Wait for recent pre-existing readers. */
  326. wait_idx(sp, busy_idx, expedited);
  327. mutex_unlock(&sp->mutex);
  328. }
  329. /**
  330. * synchronize_srcu - wait for prior SRCU read-side critical-section completion
  331. * @sp: srcu_struct with which to synchronize.
  332. *
  333. * Flip the completed counter, and wait for the old count to drain to zero.
  334. * As with classic RCU, the updater must use some separate means of
  335. * synchronizing concurrent updates. Can block; must be called from
  336. * process context.
  337. *
  338. * Note that it is illegal to call synchronize_srcu() from the corresponding
  339. * SRCU read-side critical section; doing so will result in deadlock.
  340. * However, it is perfectly legal to call synchronize_srcu() on one
  341. * srcu_struct from some other srcu_struct's read-side critical section.
  342. */
  343. void synchronize_srcu(struct srcu_struct *sp)
  344. {
  345. __synchronize_srcu(sp, 0);
  346. }
  347. EXPORT_SYMBOL_GPL(synchronize_srcu);
  348. /**
  349. * synchronize_srcu_expedited - Brute-force SRCU grace period
  350. * @sp: srcu_struct with which to synchronize.
  351. *
  352. * Wait for an SRCU grace period to elapse, but be more aggressive about
  353. * spinning rather than blocking when waiting.
  354. *
  355. * Note that it is illegal to call this function while holding any lock
  356. * that is acquired by a CPU-hotplug notifier. It is also illegal to call
  357. * synchronize_srcu_expedited() from the corresponding SRCU read-side
  358. * critical section; doing so will result in deadlock. However, it is
  359. * perfectly legal to call synchronize_srcu_expedited() on one srcu_struct
  360. * from some other srcu_struct's read-side critical section, as long as
  361. * the resulting graph of srcu_structs is acyclic.
  362. */
  363. void synchronize_srcu_expedited(struct srcu_struct *sp)
  364. {
  365. __synchronize_srcu(sp, 1);
  366. }
  367. EXPORT_SYMBOL_GPL(synchronize_srcu_expedited);
  368. /**
  369. * srcu_batches_completed - return batches completed.
  370. * @sp: srcu_struct on which to report batch completion.
  371. *
  372. * Report the number of batches, correlated with, but not necessarily
  373. * precisely the same as, the number of grace periods that have elapsed.
  374. */
  375. long srcu_batches_completed(struct srcu_struct *sp)
  376. {
  377. return sp->completed;
  378. }
  379. EXPORT_SYMBOL_GPL(srcu_batches_completed);