percpu-refcount.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. * @flags: PERCPU_REF_INIT_* flags
  43. * @gfp: allocation mask to use
  44. *
  45. * Initializes @ref. If @flags is zero, @ref starts in percpu mode with a
  46. * refcount of 1; analagous to atomic_long_set(ref, 1). See the
  47. * definitions of PERCPU_REF_INIT_* flags for flag behaviors.
  48. *
  49. * Note that @release must not sleep - it may potentially be called from RCU
  50. * callback context by percpu_ref_kill().
  51. */
  52. int percpu_ref_init(struct percpu_ref *ref, percpu_ref_func_t *release,
  53. unsigned int flags, gfp_t gfp)
  54. {
  55. size_t align = max_t(size_t, 1 << __PERCPU_REF_FLAG_BITS,
  56. __alignof__(unsigned long));
  57. unsigned long start_count = 0;
  58. ref->percpu_count_ptr = (unsigned long)
  59. __alloc_percpu_gfp(sizeof(unsigned long), align, gfp);
  60. if (!ref->percpu_count_ptr)
  61. return -ENOMEM;
  62. if (flags & (PERCPU_REF_INIT_ATOMIC | PERCPU_REF_INIT_DEAD))
  63. ref->percpu_count_ptr |= __PERCPU_REF_ATOMIC;
  64. else
  65. start_count += PERCPU_COUNT_BIAS;
  66. if (flags & PERCPU_REF_INIT_DEAD)
  67. ref->percpu_count_ptr |= __PERCPU_REF_DEAD;
  68. else
  69. start_count++;
  70. atomic_long_set(&ref->count, start_count);
  71. ref->release = release;
  72. return 0;
  73. }
  74. EXPORT_SYMBOL_GPL(percpu_ref_init);
  75. /**
  76. * percpu_ref_exit - undo percpu_ref_init()
  77. * @ref: percpu_ref to exit
  78. *
  79. * This function exits @ref. The caller is responsible for ensuring that
  80. * @ref is no longer in active use. The usual places to invoke this
  81. * function from are the @ref->release() callback or in init failure path
  82. * where percpu_ref_init() succeeded but other parts of the initialization
  83. * of the embedding object failed.
  84. */
  85. void percpu_ref_exit(struct percpu_ref *ref)
  86. {
  87. unsigned long __percpu *percpu_count = percpu_count_ptr(ref);
  88. if (percpu_count) {
  89. free_percpu(percpu_count);
  90. ref->percpu_count_ptr = __PERCPU_REF_ATOMIC_DEAD;
  91. }
  92. }
  93. EXPORT_SYMBOL_GPL(percpu_ref_exit);
  94. static void percpu_ref_call_confirm_rcu(struct rcu_head *rcu)
  95. {
  96. struct percpu_ref *ref = container_of(rcu, struct percpu_ref, rcu);
  97. ref->confirm_switch(ref);
  98. ref->confirm_switch = NULL;
  99. wake_up_all(&percpu_ref_switch_waitq);
  100. /* drop ref from percpu_ref_switch_to_atomic() */
  101. percpu_ref_put(ref);
  102. }
  103. static void percpu_ref_switch_to_atomic_rcu(struct rcu_head *rcu)
  104. {
  105. struct percpu_ref *ref = container_of(rcu, struct percpu_ref, rcu);
  106. unsigned long __percpu *percpu_count = percpu_count_ptr(ref);
  107. unsigned long count = 0;
  108. int cpu;
  109. for_each_possible_cpu(cpu)
  110. count += *per_cpu_ptr(percpu_count, cpu);
  111. pr_debug("global %ld percpu %ld",
  112. atomic_long_read(&ref->count), (long)count);
  113. /*
  114. * It's crucial that we sum the percpu counters _before_ adding the sum
  115. * to &ref->count; since gets could be happening on one cpu while puts
  116. * happen on another, adding a single cpu's count could cause
  117. * @ref->count to hit 0 before we've got a consistent value - but the
  118. * sum of all the counts will be consistent and correct.
  119. *
  120. * Subtracting the bias value then has to happen _after_ adding count to
  121. * &ref->count; we need the bias value to prevent &ref->count from
  122. * reaching 0 before we add the percpu counts. But doing it at the same
  123. * time is equivalent and saves us atomic operations:
  124. */
  125. atomic_long_add((long)count - PERCPU_COUNT_BIAS, &ref->count);
  126. WARN_ONCE(atomic_long_read(&ref->count) <= 0,
  127. "percpu ref (%pf) <= 0 (%ld) after switching to atomic",
  128. ref->release, atomic_long_read(&ref->count));
  129. /* @ref is viewed as dead on all CPUs, send out switch confirmation */
  130. percpu_ref_call_confirm_rcu(rcu);
  131. }
  132. static void percpu_ref_noop_confirm_switch(struct percpu_ref *ref)
  133. {
  134. }
  135. static void __percpu_ref_switch_to_atomic(struct percpu_ref *ref,
  136. percpu_ref_func_t *confirm_switch)
  137. {
  138. if (!(ref->percpu_count_ptr & __PERCPU_REF_ATOMIC)) {
  139. /* switching from percpu to atomic */
  140. ref->percpu_count_ptr |= __PERCPU_REF_ATOMIC;
  141. /*
  142. * Non-NULL ->confirm_switch is used to indicate that
  143. * switching is in progress. Use noop one if unspecified.
  144. */
  145. WARN_ON_ONCE(ref->confirm_switch);
  146. ref->confirm_switch =
  147. confirm_switch ?: percpu_ref_noop_confirm_switch;
  148. percpu_ref_get(ref); /* put after confirmation */
  149. call_rcu_sched(&ref->rcu, percpu_ref_switch_to_atomic_rcu);
  150. } else if (confirm_switch) {
  151. /*
  152. * Somebody already set ATOMIC. Switching may still be in
  153. * progress. @confirm_switch must be invoked after the
  154. * switching is complete and a full sched RCU grace period
  155. * has passed. Wait synchronously for the previous
  156. * switching and schedule @confirm_switch invocation.
  157. */
  158. wait_event(percpu_ref_switch_waitq, !ref->confirm_switch);
  159. ref->confirm_switch = confirm_switch;
  160. percpu_ref_get(ref); /* put after confirmation */
  161. call_rcu_sched(&ref->rcu, percpu_ref_call_confirm_rcu);
  162. }
  163. }
  164. /**
  165. * percpu_ref_switch_to_atomic - switch a percpu_ref to atomic mode
  166. * @ref: percpu_ref to switch to atomic mode
  167. * @confirm_switch: optional confirmation callback
  168. *
  169. * There's no reason to use this function for the usual reference counting.
  170. * Use percpu_ref_kill[_and_confirm]().
  171. *
  172. * Schedule switching of @ref to atomic mode. All its percpu counts will
  173. * be collected to the main atomic counter. On completion, when all CPUs
  174. * are guaraneed to be in atomic mode, @confirm_switch, which may not
  175. * block, is invoked. This function may be invoked concurrently with all
  176. * the get/put operations and can safely be mixed with kill and reinit
  177. * operations.
  178. *
  179. * This function normally doesn't block and can be called from any context
  180. * but it may block if @confirm_kill is specified and @ref is already in
  181. * the process of switching to atomic mode. In such cases, @confirm_switch
  182. * will be invoked after the switching is complete.
  183. *
  184. * Due to the way percpu_ref is implemented, @confirm_switch will be called
  185. * after at least one full sched RCU grace period has passed but this is an
  186. * implementation detail and must not be depended upon.
  187. */
  188. void percpu_ref_switch_to_atomic(struct percpu_ref *ref,
  189. percpu_ref_func_t *confirm_switch)
  190. {
  191. __percpu_ref_switch_to_atomic(ref, confirm_switch);
  192. }
  193. static void __percpu_ref_switch_to_percpu(struct percpu_ref *ref)
  194. {
  195. unsigned long __percpu *percpu_count = percpu_count_ptr(ref);
  196. int cpu;
  197. BUG_ON(!percpu_count);
  198. if (!(ref->percpu_count_ptr & __PERCPU_REF_ATOMIC))
  199. return;
  200. wait_event(percpu_ref_switch_waitq, !ref->confirm_switch);
  201. atomic_long_add(PERCPU_COUNT_BIAS, &ref->count);
  202. /*
  203. * Restore per-cpu operation. smp_store_release() is paired with
  204. * smp_read_barrier_depends() in __ref_is_percpu() and guarantees
  205. * that the zeroing is visible to all percpu accesses which can see
  206. * the following __PERCPU_REF_ATOMIC clearing.
  207. */
  208. for_each_possible_cpu(cpu)
  209. *per_cpu_ptr(percpu_count, cpu) = 0;
  210. smp_store_release(&ref->percpu_count_ptr,
  211. ref->percpu_count_ptr & ~__PERCPU_REF_ATOMIC);
  212. }
  213. /**
  214. * percpu_ref_switch_to_percpu - switch a percpu_ref to percpu mode
  215. * @ref: percpu_ref to switch to percpu mode
  216. *
  217. * There's no reason to use this function for the usual reference counting.
  218. * To re-use an expired ref, use percpu_ref_reinit().
  219. *
  220. * Switch @ref to percpu mode. This function may be invoked concurrently
  221. * with all the get/put operations and can safely be mixed with kill and
  222. * reinit operations.
  223. *
  224. * This function normally doesn't block and can be called from any context
  225. * but it may block if @ref is in the process of switching to atomic mode
  226. * by percpu_ref_switch_atomic().
  227. */
  228. void percpu_ref_switch_to_percpu(struct percpu_ref *ref)
  229. {
  230. /* a dying or dead ref can't be switched to percpu mode w/o reinit */
  231. if (!(ref->percpu_count_ptr & __PERCPU_REF_DEAD))
  232. __percpu_ref_switch_to_percpu(ref);
  233. }
  234. /**
  235. * percpu_ref_kill_and_confirm - drop the initial ref and schedule confirmation
  236. * @ref: percpu_ref to kill
  237. * @confirm_kill: optional confirmation callback
  238. *
  239. * Equivalent to percpu_ref_kill() but also schedules kill confirmation if
  240. * @confirm_kill is not NULL. @confirm_kill, which may not block, will be
  241. * called after @ref is seen as dead from all CPUs at which point all
  242. * further invocations of percpu_ref_tryget_live() will fail. See
  243. * percpu_ref_tryget_live() for details.
  244. *
  245. * This function normally doesn't block and can be called from any context
  246. * but it may block if @confirm_kill is specified and @ref is in the
  247. * process of switching to atomic mode by percpu_ref_switch_atomic().
  248. *
  249. * Due to the way percpu_ref is implemented, @confirm_switch will be called
  250. * after at least one full sched RCU grace period has passed but this is an
  251. * implementation detail and must not be depended upon.
  252. */
  253. void percpu_ref_kill_and_confirm(struct percpu_ref *ref,
  254. percpu_ref_func_t *confirm_kill)
  255. {
  256. WARN_ONCE(ref->percpu_count_ptr & __PERCPU_REF_DEAD,
  257. "%s called more than once on %pf!", __func__, ref->release);
  258. ref->percpu_count_ptr |= __PERCPU_REF_DEAD;
  259. __percpu_ref_switch_to_atomic(ref, confirm_kill);
  260. percpu_ref_put(ref);
  261. }
  262. EXPORT_SYMBOL_GPL(percpu_ref_kill_and_confirm);
  263. /**
  264. * percpu_ref_reinit - re-initialize a percpu refcount
  265. * @ref: perpcu_ref to re-initialize
  266. *
  267. * Re-initialize @ref so that it's in the same state as when it finished
  268. * percpu_ref_init(). @ref must have been initialized successfully and
  269. * reached 0 but not exited.
  270. *
  271. * Note that percpu_ref_tryget[_live]() are safe to perform on @ref while
  272. * this function is in progress.
  273. */
  274. void percpu_ref_reinit(struct percpu_ref *ref)
  275. {
  276. WARN_ON_ONCE(!percpu_ref_is_zero(ref));
  277. ref->percpu_count_ptr &= ~__PERCPU_REF_DEAD;
  278. percpu_ref_get(ref);
  279. __percpu_ref_switch_to_percpu(ref);
  280. }
  281. EXPORT_SYMBOL_GPL(percpu_ref_reinit);