-
Notifications
You must be signed in to change notification settings - Fork 0
/
spinlock.h
54 lines (41 loc) · 1.06 KB
/
spinlock.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#ifndef _SPINLOCK_XCHG_H
#define _SPINLOCK_XCHG_H
/* Spin lock using xchg.
* Copied from http://locklessinc.com/articles/locks/
*/
/* Compile read-write barrier */
#define barrier() asm volatile("": : :"memory")
/* Pause instruction to prevent excess processor bus usage */
#define cpu_relax() asm volatile("pause\n": : :"memory")
static inline unsigned short xchg_8(void *ptr, unsigned char x)
{
__asm__ __volatile__("xchgb %0,%1"
:"=r" (x)
:"m" (*(volatile unsigned char *)ptr), "0" (x)
:"memory");
return x;
}
#define BUSY 1
typedef unsigned char spinlock;
#define SPINLOCK_INITIALIZER 0
static inline void spin_lock(spinlock *lock)
{
while (1) {
if (!xchg_8(lock, BUSY)) return;
while (*lock) cpu_relax();
}
}
static inline void spin_unlock(spinlock *lock)
{
barrier();
*lock = 0;
}
static inline int spin_trylock(spinlock *lock)
{
return xchg_8(lock, BUSY);
}
static inline int spin_lockable(spinlock *lock)
{
return *lock != BUSY;
}
#endif /* _SPINLOCK_XCHG_H */