dec_and_lock.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include <linux/module.h>
  2. #include <linux/spinlock.h>
  3. #include <asm/atomic.h>
  4. #include <asm/system.h>
  5. /*
  6. * This is an implementation of the notion of "decrement a
  7. * reference count, and return locked if it decremented to zero".
  8. *
  9. * This implementation can be used on any architecture that
  10. * has a cmpxchg, and where atomic->value is an int holding
  11. * the value of the atomic (i.e. the high bits aren't used
  12. * for a lock or anything like that).
  13. *
  14. * N.B. ATOMIC_DEC_AND_LOCK gets defined in include/linux/spinlock.h
  15. * if spinlocks are empty and thus atomic_dec_and_lock is defined
  16. * to be atomic_dec_and_test - in that case we don't need it
  17. * defined here as well.
  18. */
  19. #ifndef ATOMIC_DEC_AND_LOCK
  20. int _atomic_dec_and_lock(atomic_t *atomic, spinlock_t *lock)
  21. {
  22. int counter;
  23. int newcount;
  24. for (;;) {
  25. counter = atomic_read(atomic);
  26. newcount = counter - 1;
  27. if (!newcount)
  28. break; /* do it the slow way */
  29. newcount = cmpxchg(&atomic->counter, counter, newcount);
  30. if (newcount == counter)
  31. return 0;
  32. }
  33. spin_lock(lock);
  34. if (atomic_dec_and_test(atomic))
  35. return 1;
  36. spin_unlock(lock);
  37. return 0;
  38. }
  39. EXPORT_SYMBOL(_atomic_dec_and_lock);
  40. #endif /* ATOMIC_DEC_AND_LOCK */