xref: /linux/fs/bcachefs/seqmutex.h (revision 9c93c0b44be36fd5267fb79ae33453f989fbe909)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _BCACHEFS_SEQMUTEX_H
3 #define _BCACHEFS_SEQMUTEX_H
4 
5 #include <linux/mutex.h>
6 
7 struct seqmutex {
8 	struct mutex	lock;
9 	u32		seq;
10 };
11 
12 #define seqmutex_init(_lock)	mutex_init(&(_lock)->lock)
13 
14 static inline bool seqmutex_trylock(struct seqmutex *lock)
15 {
16 	return mutex_trylock(&lock->lock);
17 }
18 
19 static inline void seqmutex_lock(struct seqmutex *lock)
20 {
21 	mutex_lock(&lock->lock);
22 }
23 
24 static inline void seqmutex_unlock(struct seqmutex *lock)
25 {
26 	lock->seq++;
27 	mutex_unlock(&lock->lock);
28 }
29 
30 static inline u32 seqmutex_seq(struct seqmutex *lock)
31 {
32 	return lock->seq;
33 }
34 
35 static inline bool seqmutex_relock(struct seqmutex *lock, u32 seq)
36 {
37 	if (lock->seq != seq || !mutex_trylock(&lock->lock))
38 		return false;
39 
40 	if (lock->seq != seq) {
41 		mutex_unlock(&lock->lock);
42 		return false;
43 	}
44 
45 	return true;
46 }
47 
48 #endif /* _BCACHEFS_SEQMUTEX_H */
49