percpu-refcount.c 12 KB

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