srcu.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. static void wait_idx(struct srcu_struct *sp, int idx, bool expedited)
  232. {
  233. int trycount = 0;
  234. /*
  235. * If a reader fetches the index before the ->completed increment,
  236. * but increments its counter after srcu_readers_active_idx_check()
  237. * sums it, then smp_mb() D will pair with __srcu_read_lock()'s
  238. * smp_mb() B to ensure that the SRCU read-side critical section
  239. * will see any updates that the current task performed before its
  240. * call to synchronize_srcu(), or to synchronize_srcu_expedited(),
  241. * as the case may be.
  242. */
  243. smp_mb(); /* D */
  244. /*
  245. * SRCU read-side critical sections are normally short, so wait
  246. * a small amount of time before possibly blocking.
  247. */
  248. if (!srcu_readers_active_idx_check(sp, idx)) {
  249. udelay(SYNCHRONIZE_SRCU_READER_DELAY);
  250. while (!srcu_readers_active_idx_check(sp, idx)) {
  251. if (expedited && ++ trycount < 10)
  252. udelay(SYNCHRONIZE_SRCU_READER_DELAY);
  253. else
  254. schedule_timeout_interruptible(1);
  255. }
  256. }
  257. /*
  258. * The following smp_mb() E pairs with srcu_read_unlock()'s
  259. * smp_mb C to ensure that if srcu_readers_active_idx_check()
  260. * sees srcu_read_unlock()'s counter decrement, then any
  261. * of the current task's subsequent code will happen after
  262. * that SRCU read-side critical section.
  263. *
  264. * It also ensures the order between the above waiting and
  265. * the next flipping.
  266. */
  267. smp_mb(); /* E */
  268. }
  269. /*
  270. * Flip the readers' index by incrementing ->completed, then wait
  271. * until there are no more readers using the counters referenced by
  272. * the old index value. (Recall that the index is the bottom bit
  273. * of ->completed.)
  274. *
  275. * Of course, it is possible that a reader might be delayed for the
  276. * full duration of flip_idx_and_wait() between fetching the
  277. * index and incrementing its counter. This possibility is handled
  278. * by the next __synchronize_srcu() invoking wait_idx() for such readers
  279. * before starting a new grace period.
  280. */
  281. static void flip_idx_and_wait(struct srcu_struct *sp, bool expedited)
  282. {
  283. int idx;
  284. idx = sp->completed++ & 0x1;
  285. wait_idx(sp, idx, expedited);
  286. }
  287. /*
  288. * Helper function for synchronize_srcu() and synchronize_srcu_expedited().
  289. */
  290. static void __synchronize_srcu(struct srcu_struct *sp, bool expedited)
  291. {
  292. rcu_lockdep_assert(!lock_is_held(&sp->dep_map) &&
  293. !lock_is_held(&rcu_bh_lock_map) &&
  294. !lock_is_held(&rcu_lock_map) &&
  295. !lock_is_held(&rcu_sched_lock_map),
  296. "Illegal synchronize_srcu() in same-type SRCU (or RCU) read-side critical section");
  297. mutex_lock(&sp->mutex);
  298. /*
  299. * Suppose that during the previous grace period, a reader
  300. * picked up the old value of the index, but did not increment
  301. * its counter until after the previous instance of
  302. * __synchronize_srcu() did the counter summation and recheck.
  303. * That previous grace period was OK because the reader did
  304. * not start until after the grace period started, so the grace
  305. * period was not obligated to wait for that reader.
  306. *
  307. * However, the current SRCU grace period does have to wait for
  308. * that reader. This is handled by invoking wait_idx() on the
  309. * non-active set of counters (hence sp->completed - 1). Once
  310. * wait_idx() returns, we know that all readers that picked up
  311. * the old value of ->completed and that already incremented their
  312. * counter will have completed.
  313. *
  314. * But what about readers that picked up the old value of
  315. * ->completed, but -still- have not managed to increment their
  316. * counter? We do not need to wait for those readers, because
  317. * they will have started their SRCU read-side critical section
  318. * after the current grace period starts.
  319. *
  320. * Because it is unlikely that readers will be preempted between
  321. * fetching ->completed and incrementing their counter, wait_idx()
  322. * will normally not need to wait.
  323. */
  324. wait_idx(sp, (sp->completed - 1) & 0x1, expedited);
  325. /*
  326. * Now that wait_idx() has waited for the really old readers,
  327. * invoke flip_idx_and_wait() to flip the counter and wait
  328. * for current SRCU readers.
  329. */
  330. flip_idx_and_wait(sp, expedited);
  331. mutex_unlock(&sp->mutex);
  332. }
  333. /**
  334. * synchronize_srcu - wait for prior SRCU read-side critical-section completion
  335. * @sp: srcu_struct with which to synchronize.
  336. *
  337. * Flip the completed counter, and wait for the old count to drain to zero.
  338. * As with classic RCU, the updater must use some separate means of
  339. * synchronizing concurrent updates. Can block; must be called from
  340. * process context.
  341. *
  342. * Note that it is illegal to call synchronize_srcu() from the corresponding
  343. * SRCU read-side critical section; doing so will result in deadlock.
  344. * However, it is perfectly legal to call synchronize_srcu() on one
  345. * srcu_struct from some other srcu_struct's read-side critical section.
  346. */
  347. void synchronize_srcu(struct srcu_struct *sp)
  348. {
  349. __synchronize_srcu(sp, 0);
  350. }
  351. EXPORT_SYMBOL_GPL(synchronize_srcu);
  352. /**
  353. * synchronize_srcu_expedited - Brute-force SRCU grace period
  354. * @sp: srcu_struct with which to synchronize.
  355. *
  356. * Wait for an SRCU grace period to elapse, but be more aggressive about
  357. * spinning rather than blocking when waiting.
  358. *
  359. * Note that it is illegal to call this function while holding any lock
  360. * that is acquired by a CPU-hotplug notifier. It is also illegal to call
  361. * synchronize_srcu_expedited() from the corresponding SRCU read-side
  362. * critical section; doing so will result in deadlock. However, it is
  363. * perfectly legal to call synchronize_srcu_expedited() on one srcu_struct
  364. * from some other srcu_struct's read-side critical section, as long as
  365. * the resulting graph of srcu_structs is acyclic.
  366. */
  367. void synchronize_srcu_expedited(struct srcu_struct *sp)
  368. {
  369. __synchronize_srcu(sp, 1);
  370. }
  371. EXPORT_SYMBOL_GPL(synchronize_srcu_expedited);
  372. /**
  373. * srcu_batches_completed - return batches completed.
  374. * @sp: srcu_struct on which to report batch completion.
  375. *
  376. * Report the number of batches, correlated with, but not necessarily
  377. * precisely the same as, the number of grace periods that have elapsed.
  378. */
  379. long srcu_batches_completed(struct srcu_struct *sp)
  380. {
  381. return sp->completed;
  382. }
  383. EXPORT_SYMBOL_GPL(srcu_batches_completed);