aboutsummaryrefslogtreecommitdiff
path: root/include/apos/lock.h
blob: f874399eaaf1f4b251b8a1f0bd4bbd40f669c467 (plain) (blame)
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
#ifndef APOS_LOCK_H
#define APOS_LOCK_H

/**
 * @file lock.h
 * Atomic locks, currently only \ref spin_lock() and \ref spin_unlock(). Mutex is
 * probably overkill for this project.
 */

#include <apos/atomic.h>
#include <apos/irq.h>

/**
 * Typedef for atomic_int.
 *
 * In apos, spinlocks are implemented with compiler-intrinsic atomic integers,
 * that essentially just contain some flags. Currently all spinlocks
 * enable/disable irqs.
 *
 * \todo irq contexts?
 */
typedef atomic_int spinlock_t;

#include <arch/lock.h>

/**
 * Lock a spinlock.
 *
 * @param lck Pointer to lock.
 */
static inline void spin_lock(spinlock_t *lck)
{
	disable_irq();
	do {
		while (atomic_load_explicit(lck, memory_order_acquire))
			optional_pause();

	} while (atomic_exchange_explicit(lck, 1, memory_order_acq_rel));
}

/**
 * Unlock a spinlock.
 *
 * @param lck Pointer to lock.
 */
static inline void spin_unlock(spinlock_t *lck)
{
	atomic_store_explicit(lck, 0, memory_order_release);
	enable_irq();
}

#endif /* APOS_LOCK_H */