[PATCH] OCFS2: The Second Oracle Cluster Filesystem
[linux-2.6/mini2440.git] / lib / dec_and_lock.c
blob305a9663aee39aba26532082319433e0a4e9ae33
1 #include <linux/module.h>
2 #include <linux/spinlock.h>
3 #include <asm/atomic.h>
4 #include <asm/system.h>
6 #ifdef __HAVE_ARCH_CMPXCHG
7 /*
8 * This is an implementation of the notion of "decrement a
9 * reference count, and return locked if it decremented to zero".
11 * This implementation can be used on any architecture that
12 * has a cmpxchg, and where atomic->value is an int holding
13 * the value of the atomic (i.e. the high bits aren't used
14 * for a lock or anything like that).
16 int _atomic_dec_and_lock(atomic_t *atomic, spinlock_t *lock)
18 int counter;
19 int newcount;
21 for (;;) {
22 counter = atomic_read(atomic);
23 newcount = counter - 1;
24 if (!newcount)
25 break; /* do it the slow way */
27 newcount = cmpxchg(&atomic->counter, counter, newcount);
28 if (newcount == counter)
29 return 0;
32 spin_lock(lock);
33 if (atomic_dec_and_test(atomic))
34 return 1;
35 spin_unlock(lock);
36 return 0;
38 #else
40 * This is an architecture-neutral, but slow,
41 * implementation of the notion of "decrement
42 * a reference count, and return locked if it
43 * decremented to zero".
45 * NOTE NOTE NOTE! This is _not_ equivalent to
47 * if (atomic_dec_and_test(&atomic)) {
48 * spin_lock(&lock);
49 * return 1;
50 * }
51 * return 0;
53 * because the spin-lock and the decrement must be
54 * "atomic".
56 * This slow version gets the spinlock unconditionally,
57 * and releases it if it isn't needed. Architectures
58 * are encouraged to come up with better approaches,
59 * this is trivially done efficiently using a load-locked
60 * store-conditional approach, for example.
62 int _atomic_dec_and_lock(atomic_t *atomic, spinlock_t *lock)
64 spin_lock(lock);
65 if (atomic_dec_and_test(atomic))
66 return 1;
67 spin_unlock(lock);
68 return 0;
70 #endif
72 EXPORT_SYMBOL(_atomic_dec_and_lock);