srcu.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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 total of the readers' ->seq[] values for the
  69. * rank of per-CPU counters specified by idx.
  70. */
  71. static unsigned long srcu_readers_seq_idx(struct srcu_struct *sp, int idx)
  72. {
  73. int cpu;
  74. unsigned long sum = 0;
  75. unsigned long t;
  76. for_each_possible_cpu(cpu) {
  77. t = ACCESS_ONCE(per_cpu_ptr(sp->per_cpu_ref, cpu)->seq[idx]);
  78. sum += t;
  79. }
  80. return sum;
  81. }
  82. /*
  83. * Returns approximate number of readers active on the specified rank
  84. * of the per-CPU ->c[] counters.
  85. */
  86. static unsigned long srcu_readers_active_idx(struct srcu_struct *sp, int idx)
  87. {
  88. int cpu;
  89. unsigned long sum = 0;
  90. unsigned long t;
  91. for_each_possible_cpu(cpu) {
  92. t = ACCESS_ONCE(per_cpu_ptr(sp->per_cpu_ref, cpu)->c[idx]);
  93. sum += t;
  94. }
  95. return sum;
  96. }
  97. /*
  98. * Return true if the number of pre-existing readers is determined to
  99. * be stably zero. An example unstable zero can occur if the call
  100. * to srcu_readers_active_idx() misses an __srcu_read_lock() increment,
  101. * but due to task migration, sees the corresponding __srcu_read_unlock()
  102. * decrement. This can happen because srcu_readers_active_idx() takes
  103. * time to sum the array, and might in fact be interrupted or preempted
  104. * partway through the summation.
  105. */
  106. static bool srcu_readers_active_idx_check(struct srcu_struct *sp, int idx)
  107. {
  108. unsigned long seq;
  109. seq = srcu_readers_seq_idx(sp, idx);
  110. /*
  111. * The following smp_mb() A pairs with the smp_mb() B located in
  112. * __srcu_read_lock(). This pairing ensures that if an
  113. * __srcu_read_lock() increments its counter after the summation
  114. * in srcu_readers_active_idx(), then the corresponding SRCU read-side
  115. * critical section will see any changes made prior to the start
  116. * of the current SRCU grace period.
  117. *
  118. * Also, if the above call to srcu_readers_seq_idx() saw the
  119. * increment of ->seq[], then the call to srcu_readers_active_idx()
  120. * must see the increment of ->c[].
  121. */
  122. smp_mb(); /* A */
  123. /*
  124. * Note that srcu_readers_active_idx() can incorrectly return
  125. * zero even though there is a pre-existing reader throughout.
  126. * To see this, suppose that task A is in a very long SRCU
  127. * read-side critical section that started on CPU 0, and that
  128. * no other reader exists, so that the sum of the counters
  129. * is equal to one. Then suppose that task B starts executing
  130. * srcu_readers_active_idx(), summing up to CPU 1, and then that
  131. * task C starts reading on CPU 0, so that its increment is not
  132. * summed, but finishes reading on CPU 2, so that its decrement
  133. * -is- summed. Then when task B completes its sum, it will
  134. * incorrectly get zero, despite the fact that task A has been
  135. * in its SRCU read-side critical section the whole time.
  136. *
  137. * We therefore do a validation step should srcu_readers_active_idx()
  138. * return zero.
  139. */
  140. if (srcu_readers_active_idx(sp, idx) != 0)
  141. return false;
  142. /*
  143. * The remainder of this function is the validation step.
  144. * The following smp_mb() D pairs with the smp_mb() C in
  145. * __srcu_read_unlock(). If the __srcu_read_unlock() was seen
  146. * by srcu_readers_active_idx() above, then any destructive
  147. * operation performed after the grace period will happen after
  148. * the corresponding SRCU read-side critical section.
  149. *
  150. * Note that there can be at most NR_CPUS worth of readers using
  151. * the old index, which is not enough to overflow even a 32-bit
  152. * integer. (Yes, this does mean that systems having more than
  153. * a billion or so CPUs need to be 64-bit systems.) Therefore,
  154. * the sum of the ->seq[] counters cannot possibly overflow.
  155. * Therefore, the only way that the return values of the two
  156. * calls to srcu_readers_seq_idx() can be equal is if there were
  157. * no increments of the corresponding rank of ->seq[] counts
  158. * in the interim. But the missed-increment scenario laid out
  159. * above includes an increment of the ->seq[] counter by
  160. * the corresponding __srcu_read_lock(). Therefore, if this
  161. * scenario occurs, the return values from the two calls to
  162. * srcu_readers_seq_idx() will differ, and thus the validation
  163. * step below suffices.
  164. */
  165. smp_mb(); /* D */
  166. return srcu_readers_seq_idx(sp, idx) == seq;
  167. }
  168. /**
  169. * srcu_readers_active - returns approximate number of readers.
  170. * @sp: which srcu_struct to count active readers (holding srcu_read_lock).
  171. *
  172. * Note that this is not an atomic primitive, and can therefore suffer
  173. * severe errors when invoked on an active srcu_struct. That said, it
  174. * can be useful as an error check at cleanup time.
  175. */
  176. static int srcu_readers_active(struct srcu_struct *sp)
  177. {
  178. return srcu_readers_active_idx(sp, 0) + srcu_readers_active_idx(sp, 1);
  179. }
  180. /**
  181. * cleanup_srcu_struct - deconstruct a sleep-RCU structure
  182. * @sp: structure to clean up.
  183. *
  184. * Must invoke this after you are finished using a given srcu_struct that
  185. * was initialized via init_srcu_struct(), else you leak memory.
  186. */
  187. void cleanup_srcu_struct(struct srcu_struct *sp)
  188. {
  189. int sum;
  190. sum = srcu_readers_active(sp);
  191. WARN_ON(sum); /* Leakage unless caller handles error. */
  192. if (sum != 0)
  193. return;
  194. free_percpu(sp->per_cpu_ref);
  195. sp->per_cpu_ref = NULL;
  196. }
  197. EXPORT_SYMBOL_GPL(cleanup_srcu_struct);
  198. /*
  199. * Counts the new reader in the appropriate per-CPU element of the
  200. * srcu_struct. Must be called from process context.
  201. * Returns an index that must be passed to the matching srcu_read_unlock().
  202. */
  203. int __srcu_read_lock(struct srcu_struct *sp)
  204. {
  205. int idx;
  206. preempt_disable();
  207. idx = rcu_dereference_index_check(sp->completed,
  208. rcu_read_lock_sched_held()) & 0x1;
  209. ACCESS_ONCE(this_cpu_ptr(sp->per_cpu_ref)->c[idx]) += 1;
  210. smp_mb(); /* B */ /* Avoid leaking the critical section. */
  211. ACCESS_ONCE(this_cpu_ptr(sp->per_cpu_ref)->seq[idx]) += 1;
  212. preempt_enable();
  213. return idx;
  214. }
  215. EXPORT_SYMBOL_GPL(__srcu_read_lock);
  216. /*
  217. * Removes the count for the old reader from the appropriate per-CPU
  218. * element of the srcu_struct. Note that this may well be a different
  219. * CPU than that which was incremented by the corresponding srcu_read_lock().
  220. * Must be called from process context.
  221. */
  222. void __srcu_read_unlock(struct srcu_struct *sp, int idx)
  223. {
  224. preempt_disable();
  225. smp_mb(); /* C */ /* Avoid leaking the critical section. */
  226. ACCESS_ONCE(this_cpu_ptr(sp->per_cpu_ref)->c[idx]) -= 1;
  227. preempt_enable();
  228. }
  229. EXPORT_SYMBOL_GPL(__srcu_read_unlock);
  230. /*
  231. * We use an adaptive strategy for synchronize_srcu() and especially for
  232. * synchronize_srcu_expedited(). We spin for a fixed time period
  233. * (defined below) to allow SRCU readers to exit their read-side critical
  234. * sections. If there are still some readers after 10 microseconds,
  235. * we repeatedly block for 1-millisecond time periods. This approach
  236. * has done well in testing, so there is no need for a config parameter.
  237. */
  238. #define SYNCHRONIZE_SRCU_READER_DELAY 5
  239. /*
  240. * Wait until all pre-existing readers complete. Such readers
  241. * will have used the index specified by "idx".
  242. */
  243. static void wait_idx(struct srcu_struct *sp, int idx, bool expedited)
  244. {
  245. int trycount = 0;
  246. /*
  247. * SRCU read-side critical sections are normally short, so wait
  248. * a small amount of time before possibly blocking.
  249. */
  250. if (!srcu_readers_active_idx_check(sp, idx)) {
  251. udelay(SYNCHRONIZE_SRCU_READER_DELAY);
  252. while (!srcu_readers_active_idx_check(sp, idx)) {
  253. if (expedited && ++ trycount < 10)
  254. udelay(SYNCHRONIZE_SRCU_READER_DELAY);
  255. else
  256. schedule_timeout_interruptible(1);
  257. }
  258. }
  259. }
  260. static void srcu_flip(struct srcu_struct *sp)
  261. {
  262. sp->completed++;
  263. }
  264. /*
  265. * Helper function for synchronize_srcu() and synchronize_srcu_expedited().
  266. */
  267. static void __synchronize_srcu(struct srcu_struct *sp, bool expedited)
  268. {
  269. int busy_idx;
  270. rcu_lockdep_assert(!lock_is_held(&sp->dep_map) &&
  271. !lock_is_held(&rcu_bh_lock_map) &&
  272. !lock_is_held(&rcu_lock_map) &&
  273. !lock_is_held(&rcu_sched_lock_map),
  274. "Illegal synchronize_srcu() in same-type SRCU (or RCU) read-side critical section");
  275. mutex_lock(&sp->mutex);
  276. busy_idx = sp->completed & 0X1UL;
  277. /*
  278. * If we recently flipped the index, there will be some readers
  279. * using idx=0 and others using idx=1. Therefore, two calls to
  280. * wait_idx()s suffice to ensure that all pre-existing readers
  281. * have completed:
  282. *
  283. * __synchronize_srcu() {
  284. * wait_idx(sp, 0, expedited);
  285. * wait_idx(sp, 1, expedited);
  286. * }
  287. *
  288. * Starvation is prevented by the fact that we flip the index.
  289. * While we wait on one index to clear out, almost all new readers
  290. * will be using the other index. The number of new readers using the
  291. * index we are waiting on is sharply bounded by roughly the number
  292. * of CPUs.
  293. *
  294. * How can new readers possibly using the old pre-flip value of
  295. * the index? Consider the following sequence of events:
  296. *
  297. * Suppose that during the previous grace period, a reader
  298. * picked up the old value of the index, but did not increment
  299. * its counter until after the previous instance of
  300. * __synchronize_srcu() did the counter summation and recheck.
  301. * That previous grace period was OK because the reader did
  302. * not start until after the grace period started, so the grace
  303. * period was not obligated to wait for that reader.
  304. *
  305. * However, this sequence of events is quite improbable, so
  306. * this call to wait_idx(), which waits on really old readers
  307. * describe in this comment above, will almost never need to wait.
  308. */
  309. wait_idx(sp, 1 - busy_idx, expedited);
  310. /* Flip the index to avoid reader-induced starvation. */
  311. srcu_flip(sp);
  312. /* Wait for recent pre-existing readers. */
  313. wait_idx(sp, busy_idx, expedited);
  314. mutex_unlock(&sp->mutex);
  315. }
  316. /**
  317. * synchronize_srcu - wait for prior SRCU read-side critical-section completion
  318. * @sp: srcu_struct with which to synchronize.
  319. *
  320. * Flip the completed counter, and wait for the old count to drain to zero.
  321. * As with classic RCU, the updater must use some separate means of
  322. * synchronizing concurrent updates. Can block; must be called from
  323. * process context.
  324. *
  325. * Note that it is illegal to call synchronize_srcu() from the corresponding
  326. * SRCU read-side critical section; doing so will result in deadlock.
  327. * However, it is perfectly legal to call synchronize_srcu() on one
  328. * srcu_struct from some other srcu_struct's read-side critical section.
  329. */
  330. void synchronize_srcu(struct srcu_struct *sp)
  331. {
  332. __synchronize_srcu(sp, 0);
  333. }
  334. EXPORT_SYMBOL_GPL(synchronize_srcu);
  335. /**
  336. * synchronize_srcu_expedited - Brute-force SRCU grace period
  337. * @sp: srcu_struct with which to synchronize.
  338. *
  339. * Wait for an SRCU grace period to elapse, but be more aggressive about
  340. * spinning rather than blocking when waiting.
  341. *
  342. * Note that it is illegal to call this function while holding any lock
  343. * that is acquired by a CPU-hotplug notifier. It is also illegal to call
  344. * synchronize_srcu_expedited() from the corresponding SRCU read-side
  345. * critical section; doing so will result in deadlock. However, it is
  346. * perfectly legal to call synchronize_srcu_expedited() on one srcu_struct
  347. * from some other srcu_struct's read-side critical section, as long as
  348. * the resulting graph of srcu_structs is acyclic.
  349. */
  350. void synchronize_srcu_expedited(struct srcu_struct *sp)
  351. {
  352. __synchronize_srcu(sp, 1);
  353. }
  354. EXPORT_SYMBOL_GPL(synchronize_srcu_expedited);
  355. /**
  356. * srcu_batches_completed - return batches completed.
  357. * @sp: srcu_struct on which to report batch completion.
  358. *
  359. * Report the number of batches, correlated with, but not necessarily
  360. * precisely the same as, the number of grace periods that have elapsed.
  361. */
  362. long srcu_batches_completed(struct srcu_struct *sp)
  363. {
  364. return sp->completed;
  365. }
  366. EXPORT_SYMBOL_GPL(srcu_batches_completed);