xref: /linux/fs/bcachefs/seqmutex.h (revision f44cc269)
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 
seqmutex_trylock(struct seqmutex * lock)14 static inline bool seqmutex_trylock(struct seqmutex *lock)
15 {
16 	return mutex_trylock(&lock->lock);
17 }
18 
seqmutex_lock(struct seqmutex * lock)19 static inline void seqmutex_lock(struct seqmutex *lock)
20 {
21 	mutex_lock(&lock->lock);
22 	lock->seq++;
23 }
24 
seqmutex_unlock(struct seqmutex * lock)25 static inline u32 seqmutex_unlock(struct seqmutex *lock)
26 {
27 	u32 seq = lock->seq;
28 	mutex_unlock(&lock->lock);
29 	return seq;
30 }
31 
seqmutex_relock(struct seqmutex * lock,u32 seq)32 static inline bool seqmutex_relock(struct seqmutex *lock, u32 seq)
33 {
34 	if (lock->seq != seq || !mutex_trylock(&lock->lock))
35 		return false;
36 
37 	if (lock->seq != seq) {
38 		mutex_unlock(&lock->lock);
39 		return false;
40 	}
41 
42 	return true;
43 }
44 
45 #endif /* _BCACHEFS_SEQMUTEX_H */
46