percpu-refcount.c 12 KB

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