Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 #define pr_fmt(fmt) "%s: " fmt, __func__
0003 
0004 #include <linux/kernel.h>
0005 #include <linux/sched.h>
0006 #include <linux/wait.h>
0007 #include <linux/slab.h>
0008 #include <linux/mm.h>
0009 #include <linux/percpu-refcount.h>
0010 
0011 /*
0012  * Initially, a percpu refcount is just a set of percpu counters. Initially, we
0013  * don't try to detect the ref hitting 0 - which means that get/put can just
0014  * increment or decrement the local counter. Note that the counter on a
0015  * particular cpu can (and will) wrap - this is fine, when we go to shutdown the
0016  * percpu counters will all sum to the correct value
0017  *
0018  * (More precisely: because modular arithmetic is commutative the sum of all the
0019  * percpu_count vars will be equal to what it would have been if all the gets
0020  * and puts were done to a single integer, even if some of the percpu integers
0021  * overflow or underflow).
0022  *
0023  * The real trick to implementing percpu refcounts is shutdown. We can't detect
0024  * the ref hitting 0 on every put - this would require global synchronization
0025  * and defeat the whole purpose of using percpu refs.
0026  *
0027  * What we do is require the user to keep track of the initial refcount; we know
0028  * the ref can't hit 0 before the user drops the initial ref, so as long as we
0029  * convert to non percpu mode before the initial ref is dropped everything
0030  * works.
0031  *
0032  * Converting to non percpu mode is done with some RCUish stuff in
0033  * percpu_ref_kill. Additionally, we need a bias value so that the
0034  * atomic_long_t can't hit 0 before we've added up all the percpu refs.
0035  */
0036 
0037 #define PERCPU_COUNT_BIAS   (1LU << (BITS_PER_LONG - 1))
0038 
0039 static DEFINE_SPINLOCK(percpu_ref_switch_lock);
0040 static DECLARE_WAIT_QUEUE_HEAD(percpu_ref_switch_waitq);
0041 
0042 static unsigned long __percpu *percpu_count_ptr(struct percpu_ref *ref)
0043 {
0044     return (unsigned long __percpu *)
0045         (ref->percpu_count_ptr & ~__PERCPU_REF_ATOMIC_DEAD);
0046 }
0047 
0048 /**
0049  * percpu_ref_init - initialize a percpu refcount
0050  * @ref: percpu_ref to initialize
0051  * @release: function which will be called when refcount hits 0
0052  * @flags: PERCPU_REF_INIT_* flags
0053  * @gfp: allocation mask to use
0054  *
0055  * Initializes @ref.  @ref starts out in percpu mode with a refcount of 1 unless
0056  * @flags contains PERCPU_REF_INIT_ATOMIC or PERCPU_REF_INIT_DEAD.  These flags
0057  * change the start state to atomic with the latter setting the initial refcount
0058  * to 0.  See the definitions of PERCPU_REF_INIT_* flags for flag behaviors.
0059  *
0060  * Note that @release must not sleep - it may potentially be called from RCU
0061  * callback context by percpu_ref_kill().
0062  */
0063 int percpu_ref_init(struct percpu_ref *ref, percpu_ref_func_t *release,
0064             unsigned int flags, gfp_t gfp)
0065 {
0066     size_t align = max_t(size_t, 1 << __PERCPU_REF_FLAG_BITS,
0067                  __alignof__(unsigned long));
0068     unsigned long start_count = 0;
0069     struct percpu_ref_data *data;
0070 
0071     ref->percpu_count_ptr = (unsigned long)
0072         __alloc_percpu_gfp(sizeof(unsigned long), align, gfp);
0073     if (!ref->percpu_count_ptr)
0074         return -ENOMEM;
0075 
0076     data = kzalloc(sizeof(*ref->data), gfp);
0077     if (!data) {
0078         free_percpu((void __percpu *)ref->percpu_count_ptr);
0079         ref->percpu_count_ptr = 0;
0080         return -ENOMEM;
0081     }
0082 
0083     data->force_atomic = flags & PERCPU_REF_INIT_ATOMIC;
0084     data->allow_reinit = flags & PERCPU_REF_ALLOW_REINIT;
0085 
0086     if (flags & (PERCPU_REF_INIT_ATOMIC | PERCPU_REF_INIT_DEAD)) {
0087         ref->percpu_count_ptr |= __PERCPU_REF_ATOMIC;
0088         data->allow_reinit = true;
0089     } else {
0090         start_count += PERCPU_COUNT_BIAS;
0091     }
0092 
0093     if (flags & PERCPU_REF_INIT_DEAD)
0094         ref->percpu_count_ptr |= __PERCPU_REF_DEAD;
0095     else
0096         start_count++;
0097 
0098     atomic_long_set(&data->count, start_count);
0099 
0100     data->release = release;
0101     data->confirm_switch = NULL;
0102     data->ref = ref;
0103     ref->data = data;
0104     return 0;
0105 }
0106 EXPORT_SYMBOL_GPL(percpu_ref_init);
0107 
0108 static void __percpu_ref_exit(struct percpu_ref *ref)
0109 {
0110     unsigned long __percpu *percpu_count = percpu_count_ptr(ref);
0111 
0112     if (percpu_count) {
0113         /* non-NULL confirm_switch indicates switching in progress */
0114         WARN_ON_ONCE(ref->data && ref->data->confirm_switch);
0115         free_percpu(percpu_count);
0116         ref->percpu_count_ptr = __PERCPU_REF_ATOMIC_DEAD;
0117     }
0118 }
0119 
0120 /**
0121  * percpu_ref_exit - undo percpu_ref_init()
0122  * @ref: percpu_ref to exit
0123  *
0124  * This function exits @ref.  The caller is responsible for ensuring that
0125  * @ref is no longer in active use.  The usual places to invoke this
0126  * function from are the @ref->release() callback or in init failure path
0127  * where percpu_ref_init() succeeded but other parts of the initialization
0128  * of the embedding object failed.
0129  */
0130 void percpu_ref_exit(struct percpu_ref *ref)
0131 {
0132     struct percpu_ref_data *data = ref->data;
0133     unsigned long flags;
0134 
0135     __percpu_ref_exit(ref);
0136 
0137     if (!data)
0138         return;
0139 
0140     spin_lock_irqsave(&percpu_ref_switch_lock, flags);
0141     ref->percpu_count_ptr |= atomic_long_read(&ref->data->count) <<
0142         __PERCPU_REF_FLAG_BITS;
0143     ref->data = NULL;
0144     spin_unlock_irqrestore(&percpu_ref_switch_lock, flags);
0145 
0146     kfree(data);
0147 }
0148 EXPORT_SYMBOL_GPL(percpu_ref_exit);
0149 
0150 static void percpu_ref_call_confirm_rcu(struct rcu_head *rcu)
0151 {
0152     struct percpu_ref_data *data = container_of(rcu,
0153             struct percpu_ref_data, rcu);
0154     struct percpu_ref *ref = data->ref;
0155 
0156     data->confirm_switch(ref);
0157     data->confirm_switch = NULL;
0158     wake_up_all(&percpu_ref_switch_waitq);
0159 
0160     if (!data->allow_reinit)
0161         __percpu_ref_exit(ref);
0162 
0163     /* drop ref from percpu_ref_switch_to_atomic() */
0164     percpu_ref_put(ref);
0165 }
0166 
0167 static void percpu_ref_switch_to_atomic_rcu(struct rcu_head *rcu)
0168 {
0169     struct percpu_ref_data *data = container_of(rcu,
0170             struct percpu_ref_data, rcu);
0171     struct percpu_ref *ref = data->ref;
0172     unsigned long __percpu *percpu_count = percpu_count_ptr(ref);
0173     static atomic_t underflows;
0174     unsigned long count = 0;
0175     int cpu;
0176 
0177     for_each_possible_cpu(cpu)
0178         count += *per_cpu_ptr(percpu_count, cpu);
0179 
0180     pr_debug("global %lu percpu %lu\n",
0181          atomic_long_read(&data->count), count);
0182 
0183     /*
0184      * It's crucial that we sum the percpu counters _before_ adding the sum
0185      * to &ref->count; since gets could be happening on one cpu while puts
0186      * happen on another, adding a single cpu's count could cause
0187      * @ref->count to hit 0 before we've got a consistent value - but the
0188      * sum of all the counts will be consistent and correct.
0189      *
0190      * Subtracting the bias value then has to happen _after_ adding count to
0191      * &ref->count; we need the bias value to prevent &ref->count from
0192      * reaching 0 before we add the percpu counts. But doing it at the same
0193      * time is equivalent and saves us atomic operations:
0194      */
0195     atomic_long_add((long)count - PERCPU_COUNT_BIAS, &data->count);
0196 
0197     if (WARN_ONCE(atomic_long_read(&data->count) <= 0,
0198               "percpu ref (%ps) <= 0 (%ld) after switching to atomic",
0199               data->release, atomic_long_read(&data->count)) &&
0200         atomic_inc_return(&underflows) < 4) {
0201         pr_err("%s(): percpu_ref underflow", __func__);
0202         mem_dump_obj(data);
0203     }
0204 
0205     /* @ref is viewed as dead on all CPUs, send out switch confirmation */
0206     percpu_ref_call_confirm_rcu(rcu);
0207 }
0208 
0209 static void percpu_ref_noop_confirm_switch(struct percpu_ref *ref)
0210 {
0211 }
0212 
0213 static void __percpu_ref_switch_to_atomic(struct percpu_ref *ref,
0214                       percpu_ref_func_t *confirm_switch)
0215 {
0216     if (ref->percpu_count_ptr & __PERCPU_REF_ATOMIC) {
0217         if (confirm_switch)
0218             confirm_switch(ref);
0219         return;
0220     }
0221 
0222     /* switching from percpu to atomic */
0223     ref->percpu_count_ptr |= __PERCPU_REF_ATOMIC;
0224 
0225     /*
0226      * Non-NULL ->confirm_switch is used to indicate that switching is
0227      * in progress.  Use noop one if unspecified.
0228      */
0229     ref->data->confirm_switch = confirm_switch ?:
0230         percpu_ref_noop_confirm_switch;
0231 
0232     percpu_ref_get(ref);    /* put after confirmation */
0233     call_rcu(&ref->data->rcu, percpu_ref_switch_to_atomic_rcu);
0234 }
0235 
0236 static void __percpu_ref_switch_to_percpu(struct percpu_ref *ref)
0237 {
0238     unsigned long __percpu *percpu_count = percpu_count_ptr(ref);
0239     int cpu;
0240 
0241     BUG_ON(!percpu_count);
0242 
0243     if (!(ref->percpu_count_ptr & __PERCPU_REF_ATOMIC))
0244         return;
0245 
0246     if (WARN_ON_ONCE(!ref->data->allow_reinit))
0247         return;
0248 
0249     atomic_long_add(PERCPU_COUNT_BIAS, &ref->data->count);
0250 
0251     /*
0252      * Restore per-cpu operation.  smp_store_release() is paired
0253      * with READ_ONCE() in __ref_is_percpu() and guarantees that the
0254      * zeroing is visible to all percpu accesses which can see the
0255      * following __PERCPU_REF_ATOMIC clearing.
0256      */
0257     for_each_possible_cpu(cpu)
0258         *per_cpu_ptr(percpu_count, cpu) = 0;
0259 
0260     smp_store_release(&ref->percpu_count_ptr,
0261               ref->percpu_count_ptr & ~__PERCPU_REF_ATOMIC);
0262 }
0263 
0264 static void __percpu_ref_switch_mode(struct percpu_ref *ref,
0265                      percpu_ref_func_t *confirm_switch)
0266 {
0267     struct percpu_ref_data *data = ref->data;
0268 
0269     lockdep_assert_held(&percpu_ref_switch_lock);
0270 
0271     /*
0272      * If the previous ATOMIC switching hasn't finished yet, wait for
0273      * its completion.  If the caller ensures that ATOMIC switching
0274      * isn't in progress, this function can be called from any context.
0275      */
0276     wait_event_lock_irq(percpu_ref_switch_waitq, !data->confirm_switch,
0277                 percpu_ref_switch_lock);
0278 
0279     if (data->force_atomic || percpu_ref_is_dying(ref))
0280         __percpu_ref_switch_to_atomic(ref, confirm_switch);
0281     else
0282         __percpu_ref_switch_to_percpu(ref);
0283 }
0284 
0285 /**
0286  * percpu_ref_switch_to_atomic - switch a percpu_ref to atomic mode
0287  * @ref: percpu_ref to switch to atomic mode
0288  * @confirm_switch: optional confirmation callback
0289  *
0290  * There's no reason to use this function for the usual reference counting.
0291  * Use percpu_ref_kill[_and_confirm]().
0292  *
0293  * Schedule switching of @ref to atomic mode.  All its percpu counts will
0294  * be collected to the main atomic counter.  On completion, when all CPUs
0295  * are guaraneed to be in atomic mode, @confirm_switch, which may not
0296  * block, is invoked.  This function may be invoked concurrently with all
0297  * the get/put operations and can safely be mixed with kill and reinit
0298  * operations.  Note that @ref will stay in atomic mode across kill/reinit
0299  * cycles until percpu_ref_switch_to_percpu() is called.
0300  *
0301  * This function may block if @ref is in the process of switching to atomic
0302  * mode.  If the caller ensures that @ref is not in the process of
0303  * switching to atomic mode, this function can be called from any context.
0304  */
0305 void percpu_ref_switch_to_atomic(struct percpu_ref *ref,
0306                  percpu_ref_func_t *confirm_switch)
0307 {
0308     unsigned long flags;
0309 
0310     spin_lock_irqsave(&percpu_ref_switch_lock, flags);
0311 
0312     ref->data->force_atomic = true;
0313     __percpu_ref_switch_mode(ref, confirm_switch);
0314 
0315     spin_unlock_irqrestore(&percpu_ref_switch_lock, flags);
0316 }
0317 EXPORT_SYMBOL_GPL(percpu_ref_switch_to_atomic);
0318 
0319 /**
0320  * percpu_ref_switch_to_atomic_sync - switch a percpu_ref to atomic mode
0321  * @ref: percpu_ref to switch to atomic mode
0322  *
0323  * Schedule switching the ref to atomic mode, and wait for the
0324  * switch to complete.  Caller must ensure that no other thread
0325  * will switch back to percpu mode.
0326  */
0327 void percpu_ref_switch_to_atomic_sync(struct percpu_ref *ref)
0328 {
0329     percpu_ref_switch_to_atomic(ref, NULL);
0330     wait_event(percpu_ref_switch_waitq, !ref->data->confirm_switch);
0331 }
0332 EXPORT_SYMBOL_GPL(percpu_ref_switch_to_atomic_sync);
0333 
0334 /**
0335  * percpu_ref_switch_to_percpu - switch a percpu_ref to percpu mode
0336  * @ref: percpu_ref to switch to percpu mode
0337  *
0338  * There's no reason to use this function for the usual reference counting.
0339  * To re-use an expired ref, use percpu_ref_reinit().
0340  *
0341  * Switch @ref to percpu mode.  This function may be invoked concurrently
0342  * with all the get/put operations and can safely be mixed with kill and
0343  * reinit operations.  This function reverses the sticky atomic state set
0344  * by PERCPU_REF_INIT_ATOMIC or percpu_ref_switch_to_atomic().  If @ref is
0345  * dying or dead, the actual switching takes place on the following
0346  * percpu_ref_reinit().
0347  *
0348  * This function may block if @ref is in the process of switching to atomic
0349  * mode.  If the caller ensures that @ref is not in the process of
0350  * switching to atomic mode, this function can be called from any context.
0351  */
0352 void percpu_ref_switch_to_percpu(struct percpu_ref *ref)
0353 {
0354     unsigned long flags;
0355 
0356     spin_lock_irqsave(&percpu_ref_switch_lock, flags);
0357 
0358     ref->data->force_atomic = false;
0359     __percpu_ref_switch_mode(ref, NULL);
0360 
0361     spin_unlock_irqrestore(&percpu_ref_switch_lock, flags);
0362 }
0363 EXPORT_SYMBOL_GPL(percpu_ref_switch_to_percpu);
0364 
0365 /**
0366  * percpu_ref_kill_and_confirm - drop the initial ref and schedule confirmation
0367  * @ref: percpu_ref to kill
0368  * @confirm_kill: optional confirmation callback
0369  *
0370  * Equivalent to percpu_ref_kill() but also schedules kill confirmation if
0371  * @confirm_kill is not NULL.  @confirm_kill, which may not block, will be
0372  * called after @ref is seen as dead from all CPUs at which point all
0373  * further invocations of percpu_ref_tryget_live() will fail.  See
0374  * percpu_ref_tryget_live() for details.
0375  *
0376  * This function normally doesn't block and can be called from any context
0377  * but it may block if @confirm_kill is specified and @ref is in the
0378  * process of switching to atomic mode by percpu_ref_switch_to_atomic().
0379  *
0380  * There are no implied RCU grace periods between kill and release.
0381  */
0382 void percpu_ref_kill_and_confirm(struct percpu_ref *ref,
0383                  percpu_ref_func_t *confirm_kill)
0384 {
0385     unsigned long flags;
0386 
0387     spin_lock_irqsave(&percpu_ref_switch_lock, flags);
0388 
0389     WARN_ONCE(percpu_ref_is_dying(ref),
0390           "%s called more than once on %ps!", __func__,
0391           ref->data->release);
0392 
0393     ref->percpu_count_ptr |= __PERCPU_REF_DEAD;
0394     __percpu_ref_switch_mode(ref, confirm_kill);
0395     percpu_ref_put(ref);
0396 
0397     spin_unlock_irqrestore(&percpu_ref_switch_lock, flags);
0398 }
0399 EXPORT_SYMBOL_GPL(percpu_ref_kill_and_confirm);
0400 
0401 /**
0402  * percpu_ref_is_zero - test whether a percpu refcount reached zero
0403  * @ref: percpu_ref to test
0404  *
0405  * Returns %true if @ref reached zero.
0406  *
0407  * This function is safe to call as long as @ref is between init and exit.
0408  */
0409 bool percpu_ref_is_zero(struct percpu_ref *ref)
0410 {
0411     unsigned long __percpu *percpu_count;
0412     unsigned long count, flags;
0413 
0414     if (__ref_is_percpu(ref, &percpu_count))
0415         return false;
0416 
0417     /* protect us from being destroyed */
0418     spin_lock_irqsave(&percpu_ref_switch_lock, flags);
0419     if (ref->data)
0420         count = atomic_long_read(&ref->data->count);
0421     else
0422         count = ref->percpu_count_ptr >> __PERCPU_REF_FLAG_BITS;
0423     spin_unlock_irqrestore(&percpu_ref_switch_lock, flags);
0424 
0425     return count == 0;
0426 }
0427 EXPORT_SYMBOL_GPL(percpu_ref_is_zero);
0428 
0429 /**
0430  * percpu_ref_reinit - re-initialize a percpu refcount
0431  * @ref: perpcu_ref to re-initialize
0432  *
0433  * Re-initialize @ref so that it's in the same state as when it finished
0434  * percpu_ref_init() ignoring %PERCPU_REF_INIT_DEAD.  @ref must have been
0435  * initialized successfully and reached 0 but not exited.
0436  *
0437  * Note that percpu_ref_tryget[_live]() are safe to perform on @ref while
0438  * this function is in progress.
0439  */
0440 void percpu_ref_reinit(struct percpu_ref *ref)
0441 {
0442     WARN_ON_ONCE(!percpu_ref_is_zero(ref));
0443 
0444     percpu_ref_resurrect(ref);
0445 }
0446 EXPORT_SYMBOL_GPL(percpu_ref_reinit);
0447 
0448 /**
0449  * percpu_ref_resurrect - modify a percpu refcount from dead to live
0450  * @ref: perpcu_ref to resurrect
0451  *
0452  * Modify @ref so that it's in the same state as before percpu_ref_kill() was
0453  * called. @ref must be dead but must not yet have exited.
0454  *
0455  * If @ref->release() frees @ref then the caller is responsible for
0456  * guaranteeing that @ref->release() does not get called while this
0457  * function is in progress.
0458  *
0459  * Note that percpu_ref_tryget[_live]() are safe to perform on @ref while
0460  * this function is in progress.
0461  */
0462 void percpu_ref_resurrect(struct percpu_ref *ref)
0463 {
0464     unsigned long __percpu *percpu_count;
0465     unsigned long flags;
0466 
0467     spin_lock_irqsave(&percpu_ref_switch_lock, flags);
0468 
0469     WARN_ON_ONCE(!percpu_ref_is_dying(ref));
0470     WARN_ON_ONCE(__ref_is_percpu(ref, &percpu_count));
0471 
0472     ref->percpu_count_ptr &= ~__PERCPU_REF_DEAD;
0473     percpu_ref_get(ref);
0474     __percpu_ref_switch_mode(ref, NULL);
0475 
0476     spin_unlock_irqrestore(&percpu_ref_switch_lock, flags);
0477 }
0478 EXPORT_SYMBOL_GPL(percpu_ref_resurrect);