dec_and_lock.c 911 B

1234567891011121314151617181920212223242526272829303132333435363738
  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. int _atomic_dec_and_lock(atomic_t *atomic, spinlock_t *lock)
  15. {
  16. int counter;
  17. int newcount;
  18. for (;;) {
  19. counter = atomic_read(atomic);
  20. newcount = counter - 1;
  21. if (!newcount)
  22. break; /* do it the slow way */
  23. newcount = cmpxchg(&atomic->counter, counter, newcount);
  24. if (newcount == counter)
  25. return 0;
  26. }
  27. spin_lock(lock);
  28. if (atomic_dec_and_test(atomic))
  29. return 1;
  30. spin_unlock(lock);
  31. return 0;
  32. }
  33. EXPORT_SYMBOL(_atomic_dec_and_lock);