18c2ecf20Sopenharmony_ci// SPDX-License-Identifier: GPL-2.0 28c2ecf20Sopenharmony_ci#include <linux/export.h> 38c2ecf20Sopenharmony_ci#include <linux/spinlock.h> 48c2ecf20Sopenharmony_ci#include <linux/atomic.h> 58c2ecf20Sopenharmony_ci 68c2ecf20Sopenharmony_ci/* 78c2ecf20Sopenharmony_ci * This is an implementation of the notion of "decrement a 88c2ecf20Sopenharmony_ci * reference count, and return locked if it decremented to zero". 98c2ecf20Sopenharmony_ci * 108c2ecf20Sopenharmony_ci * NOTE NOTE NOTE! This is _not_ equivalent to 118c2ecf20Sopenharmony_ci * 128c2ecf20Sopenharmony_ci * if (atomic_dec_and_test(&atomic)) { 138c2ecf20Sopenharmony_ci * spin_lock(&lock); 148c2ecf20Sopenharmony_ci * return 1; 158c2ecf20Sopenharmony_ci * } 168c2ecf20Sopenharmony_ci * return 0; 178c2ecf20Sopenharmony_ci * 188c2ecf20Sopenharmony_ci * because the spin-lock and the decrement must be 198c2ecf20Sopenharmony_ci * "atomic". 208c2ecf20Sopenharmony_ci */ 218c2ecf20Sopenharmony_ciint _atomic_dec_and_lock(atomic_t *atomic, spinlock_t *lock) 228c2ecf20Sopenharmony_ci{ 238c2ecf20Sopenharmony_ci /* Subtract 1 from counter unless that drops it to 0 (ie. it was 1) */ 248c2ecf20Sopenharmony_ci if (atomic_add_unless(atomic, -1, 1)) 258c2ecf20Sopenharmony_ci return 0; 268c2ecf20Sopenharmony_ci 278c2ecf20Sopenharmony_ci /* Otherwise do it the slow way */ 288c2ecf20Sopenharmony_ci spin_lock(lock); 298c2ecf20Sopenharmony_ci if (atomic_dec_and_test(atomic)) 308c2ecf20Sopenharmony_ci return 1; 318c2ecf20Sopenharmony_ci spin_unlock(lock); 328c2ecf20Sopenharmony_ci return 0; 338c2ecf20Sopenharmony_ci} 348c2ecf20Sopenharmony_ci 358c2ecf20Sopenharmony_ciEXPORT_SYMBOL(_atomic_dec_and_lock); 368c2ecf20Sopenharmony_ci 378c2ecf20Sopenharmony_ciint _atomic_dec_and_lock_irqsave(atomic_t *atomic, spinlock_t *lock, 388c2ecf20Sopenharmony_ci unsigned long *flags) 398c2ecf20Sopenharmony_ci{ 408c2ecf20Sopenharmony_ci /* Subtract 1 from counter unless that drops it to 0 (ie. it was 1) */ 418c2ecf20Sopenharmony_ci if (atomic_add_unless(atomic, -1, 1)) 428c2ecf20Sopenharmony_ci return 0; 438c2ecf20Sopenharmony_ci 448c2ecf20Sopenharmony_ci /* Otherwise do it the slow way */ 458c2ecf20Sopenharmony_ci spin_lock_irqsave(lock, *flags); 468c2ecf20Sopenharmony_ci if (atomic_dec_and_test(atomic)) 478c2ecf20Sopenharmony_ci return 1; 488c2ecf20Sopenharmony_ci spin_unlock_irqrestore(lock, *flags); 498c2ecf20Sopenharmony_ci return 0; 508c2ecf20Sopenharmony_ci} 518c2ecf20Sopenharmony_ciEXPORT_SYMBOL(_atomic_dec_and_lock_irqsave); 52