percpu-refcount.c 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. #define pr_fmt(fmt) "%s: " fmt "\n", __func__
  2. #include <linux/kernel.h>
  3. #include <linux/sched.h>
  4. #include <linux/wait.h>
  5. #include <linux/percpu-refcount.h>
  6. /*
  7. * Initially, a percpu refcount is just a set of percpu counters. Initially, we
  8. * don't try to detect the ref hitting 0 - which means that get/put can just
  9. * increment or decrement the local counter. Note that the counter on a
  10. * particular cpu can (and will) wrap - this is fine, when we go to shutdown the
  11. * percpu counters will all sum to the correct value
  12. *
  13. * (More precisely: because moduler arithmatic is commutative the sum of all the
  14. * percpu_count vars will be equal to what it would have been if all the gets
  15. * and puts were done to a single integer, even if some of the percpu integers
  16. * overflow or underflow).
  17. *
  18. * The real trick to implementing percpu refcounts is shutdown. We can't detect
  19. * the ref hitting 0 on every put - this would require global synchronization
  20. * and defeat the whole purpose of using percpu refs.
  21. *
  22. * What we do is require the user to keep track of the initial refcount; we know
  23. * the ref can't hit 0 before the user drops the initial ref, so as long as we
  24. * convert to non percpu mode before the initial ref is dropped everything
  25. * works.
  26. *
  27. * Converting to non percpu mode is done with some RCUish stuff in
  28. * percpu_ref_kill. Additionally, we need a bias value so that the
  29. * atomic_long_t can't hit 0 before we've added up all the percpu refs.
  30. */
  31. #define PERCPU_COUNT_BIAS (1LU << (BITS_PER_LONG - 1))
  32. static DECLARE_WAIT_QUEUE_HEAD(percpu_ref_switch_waitq);
  33. static unsigned long __percpu *percpu_count_ptr(struct percpu_ref *ref)
  34. {
  35. return (unsigned long __percpu *)
  36. (ref->percpu_count_ptr & ~__PERCPU_REF_ATOMIC_DEAD);
  37. }
  38. /**
  39. * percpu_ref_init - initialize a percpu refcount
  40. * @ref: percpu_ref to initialize
  41. * @release: function which will be called when refcount hits 0
  42. * @gfp: allocation mask to use
  43. *
  44. * Initializes the refcount in single atomic counter mode with a refcount of 1;
  45. * analagous to atomic_long_set(ref, 1).
  46. *
  47. * Note that @release must not sleep - it may potentially be called from RCU
  48. * callback context by percpu_ref_kill().
  49. */
  50. int percpu_ref_init(struct percpu_ref *ref, percpu_ref_func_t *release,
  51. gfp_t gfp)
  52. {
  53. size_t align = max_t(size_t, 1 << __PERCPU_REF_FLAG_BITS,
  54. __alignof__(unsigned long));
  55. atomic_long_set(&ref->count, 1 + PERCPU_COUNT_BIAS);
  56. ref->percpu_count_ptr = (unsigned long)
  57. __alloc_percpu_gfp(sizeof(unsigned long), align, gfp);
  58. if (!ref->percpu_count_ptr)
  59. return -ENOMEM;
  60. ref->release = release;
  61. return 0;
  62. }
  63. EXPORT_SYMBOL_GPL(percpu_ref_init);
  64. /**
  65. * percpu_ref_exit - undo percpu_ref_init()
  66. * @ref: percpu_ref to exit
  67. *
  68. * This function exits @ref. The caller is responsible for ensuring that
  69. * @ref is no longer in active use. The usual places to invoke this
  70. * function from are the @ref->release() callback or in init failure path
  71. * where percpu_ref_init() succeeded but other parts of the initialization
  72. * of the embedding object failed.
  73. */
  74. void percpu_ref_exit(struct percpu_ref *ref)
  75. {
  76. unsigned long __percpu *percpu_count = percpu_count_ptr(ref);
  77. if (percpu_count) {
  78. free_percpu(percpu_count);
  79. ref->percpu_count_ptr = __PERCPU_REF_ATOMIC_DEAD;
  80. }
  81. }
  82. EXPORT_SYMBOL_GPL(percpu_ref_exit);
  83. static void percpu_ref_call_confirm_rcu(struct rcu_head *rcu)
  84. {
  85. struct percpu_ref *ref = container_of(rcu, struct percpu_ref, rcu);
  86. ref->confirm_switch(ref);
  87. ref->confirm_switch = NULL;
  88. wake_up_all(&percpu_ref_switch_waitq);
  89. /* drop ref from percpu_ref_switch_to_atomic() */
  90. percpu_ref_put(ref);
  91. }
  92. static void percpu_ref_switch_to_atomic_rcu(struct rcu_head *rcu)
  93. {
  94. struct percpu_ref *ref = container_of(rcu, struct percpu_ref, rcu);
  95. unsigned long __percpu *percpu_count = percpu_count_ptr(ref);
  96. unsigned long count = 0;
  97. int cpu;
  98. for_each_possible_cpu(cpu)
  99. count += *per_cpu_ptr(percpu_count, cpu);
  100. pr_debug("global %ld percpu %ld",
  101. atomic_long_read(&ref->count), (long)count);
  102. /*
  103. * It's crucial that we sum the percpu counters _before_ adding the sum
  104. * to &ref->count; since gets could be happening on one cpu while puts
  105. * happen on another, adding a single cpu's count could cause
  106. * @ref->count to hit 0 before we've got a consistent value - but the
  107. * sum of all the counts will be consistent and correct.
  108. *
  109. * Subtracting the bias value then has to happen _after_ adding count to
  110. * &ref->count; we need the bias value to prevent &ref->count from
  111. * reaching 0 before we add the percpu counts. But doing it at the same
  112. * time is equivalent and saves us atomic operations:
  113. */
  114. atomic_long_add((long)count - PERCPU_COUNT_BIAS, &ref->count);
  115. WARN_ONCE(atomic_long_read(&ref->count) <= 0,
  116. "percpu ref (%pf) <= 0 (%ld) after switching to atomic",
  117. ref->release, atomic_long_read(&ref->count));
  118. /* @ref is viewed as dead on all CPUs, send out switch confirmation */
  119. percpu_ref_call_confirm_rcu(rcu);
  120. }
  121. static void percpu_ref_noop_confirm_switch(struct percpu_ref *ref)
  122. {
  123. }
  124. static void __percpu_ref_switch_to_atomic(struct percpu_ref *ref,
  125. percpu_ref_func_t *confirm_switch)
  126. {
  127. if (!(ref->percpu_count_ptr & __PERCPU_REF_ATOMIC)) {
  128. /* switching from percpu to atomic */
  129. ref->percpu_count_ptr |= __PERCPU_REF_ATOMIC;
  130. /*
  131. * Non-NULL ->confirm_switch is used to indicate that
  132. * switching is in progress. Use noop one if unspecified.
  133. */
  134. WARN_ON_ONCE(ref->confirm_switch);
  135. ref->confirm_switch =
  136. confirm_switch ?: percpu_ref_noop_confirm_switch;
  137. percpu_ref_get(ref); /* put after confirmation */
  138. call_rcu_sched(&ref->rcu, percpu_ref_switch_to_atomic_rcu);
  139. } else if (confirm_switch) {
  140. /*
  141. * Somebody already set ATOMIC. Switching may still be in
  142. * progress. @confirm_switch must be invoked after the
  143. * switching is complete and a full sched RCU grace period
  144. * has passed. Wait synchronously for the previous
  145. * switching and schedule @confirm_switch invocation.
  146. */
  147. wait_event(percpu_ref_switch_waitq, !ref->confirm_switch);
  148. ref->confirm_switch = confirm_switch;
  149. percpu_ref_get(ref); /* put after confirmation */
  150. call_rcu_sched(&ref->rcu, percpu_ref_call_confirm_rcu);
  151. }
  152. }
  153. /**
  154. * percpu_ref_switch_to_atomic - switch a percpu_ref to atomic mode
  155. * @ref: percpu_ref to switch to atomic mode
  156. * @confirm_switch: optional confirmation callback
  157. *
  158. * There's no reason to use this function for the usual reference counting.
  159. * Use percpu_ref_kill[_and_confirm]().
  160. *
  161. * Schedule switching of @ref to atomic mode. All its percpu counts will
  162. * be collected to the main atomic counter. On completion, when all CPUs
  163. * are guaraneed to be in atomic mode, @confirm_switch, which may not
  164. * block, is invoked. This function may be invoked concurrently with all
  165. * the get/put operations and can safely be mixed with kill and reinit
  166. * operations.
  167. *
  168. * This function normally doesn't block and can be called from any context
  169. * but it may block if @confirm_kill is specified and @ref is already in
  170. * the process of switching to atomic mode. In such cases, @confirm_switch
  171. * will be invoked after the switching is complete.
  172. *
  173. * Due to the way percpu_ref is implemented, @confirm_switch will be called
  174. * after at least one full sched RCU grace period has passed but this is an
  175. * implementation detail and must not be depended upon.
  176. */
  177. void percpu_ref_switch_to_atomic(struct percpu_ref *ref,
  178. percpu_ref_func_t *confirm_switch)
  179. {
  180. __percpu_ref_switch_to_atomic(ref, confirm_switch);
  181. }
  182. /**
  183. * percpu_ref_reinit - re-initialize a percpu refcount
  184. * @ref: perpcu_ref to re-initialize
  185. *
  186. * Re-initialize @ref so that it's in the same state as when it finished
  187. * percpu_ref_init(). @ref must have been initialized successfully, killed
  188. * and reached 0 but not exited.
  189. *
  190. * Note that percpu_ref_tryget[_live]() are safe to perform on @ref while
  191. * this function is in progress.
  192. */
  193. void percpu_ref_reinit(struct percpu_ref *ref)
  194. {
  195. unsigned long __percpu *percpu_count = percpu_count_ptr(ref);
  196. int cpu;
  197. BUG_ON(!percpu_count);
  198. WARN_ON_ONCE(!percpu_ref_is_zero(ref));
  199. atomic_long_set(&ref->count, 1 + PERCPU_COUNT_BIAS);
  200. /*
  201. * Restore per-cpu operation. smp_store_release() is paired with
  202. * smp_read_barrier_depends() in __ref_is_percpu() and guarantees
  203. * that the zeroing is visible to all percpu accesses which can see
  204. * the following __PERCPU_REF_ATOMIC_DEAD clearing.
  205. */
  206. for_each_possible_cpu(cpu)
  207. *per_cpu_ptr(percpu_count, cpu) = 0;
  208. smp_store_release(&ref->percpu_count_ptr,
  209. ref->percpu_count_ptr & ~__PERCPU_REF_ATOMIC_DEAD);
  210. }
  211. EXPORT_SYMBOL_GPL(percpu_ref_reinit);
  212. /**
  213. * percpu_ref_kill_and_confirm - drop the initial ref and schedule confirmation
  214. * @ref: percpu_ref to kill
  215. * @confirm_kill: optional confirmation callback
  216. *
  217. * Equivalent to percpu_ref_kill() but also schedules kill confirmation if
  218. * @confirm_kill is not NULL. @confirm_kill, which may not block, will be
  219. * called after @ref is seen as dead from all CPUs at which point all
  220. * further invocations of percpu_ref_tryget_live() will fail. See
  221. * percpu_ref_tryget_live() for details.
  222. *
  223. * This function normally doesn't block and can be called from any context
  224. * but it may block if @confirm_kill is specified and @ref is already in
  225. * the process of switching to atomic mode by percpu_ref_switch_atomic().
  226. *
  227. * Due to the way percpu_ref is implemented, @confirm_switch will be called
  228. * after at least one full sched RCU grace period has passed but this is an
  229. * implementation detail and must not be depended upon.
  230. */
  231. void percpu_ref_kill_and_confirm(struct percpu_ref *ref,
  232. percpu_ref_func_t *confirm_kill)
  233. {
  234. WARN_ONCE(ref->percpu_count_ptr & __PERCPU_REF_DEAD,
  235. "%s called more than once on %pf!", __func__, ref->release);
  236. ref->percpu_count_ptr |= __PERCPU_REF_DEAD;
  237. __percpu_ref_switch_to_atomic(ref, confirm_kill);
  238. percpu_ref_put(ref);
  239. }
  240. EXPORT_SYMBOL_GPL(percpu_ref_kill_and_confirm);