aboutsummaryrefslogtreecommitdiff
path: root/platform/linux-generic/include/odp/api/plat/rwlock_inlines.h
blob: 7df3727dd73775e4c47ca0923678deca0c94fb82 (plain)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/* SPDX-License-Identifier: BSD-3-Clause
 * Copyright (c) 2014-2018 Linaro Limited
 * Copyright (c) 2022 Nokia
 */

#ifndef ODP_PLAT_RWLOCK_INLINES_H_
#define ODP_PLAT_RWLOCK_INLINES_H_

#include <odp/api/atomic.h>
#include <odp/api/cpu.h>

#include <odp/api/abi/rwlock.h>

#include <stdint.h>

/** @cond _ODP_HIDE_FROM_DOXYGEN_ */

#ifndef _ODP_NO_INLINE
	/* Inline functions by default */
	#define _ODP_INLINE static inline
	#define odp_rwlock_init __odp_rwlock_init
	#define odp_rwlock_read_lock __odp_rwlock_read_lock
	#define odp_rwlock_read_trylock __odp_rwlock_read_trylock
	#define odp_rwlock_read_unlock __odp_rwlock_read_unlock
	#define odp_rwlock_write_lock __odp_rwlock_write_lock
	#define odp_rwlock_write_trylock __odp_rwlock_write_trylock
	#define odp_rwlock_write_unlock __odp_rwlock_write_unlock
#else
	#undef _ODP_INLINE
	#define _ODP_INLINE
#endif

_ODP_INLINE void odp_rwlock_init(odp_rwlock_t *rwlock)
{
	odp_atomic_init_u32(&rwlock->cnt, 0);
}

_ODP_INLINE void odp_rwlock_read_lock(odp_rwlock_t *rwlock)
{
	uint32_t cnt;
	int is_locked = 0;

	while (is_locked == 0) {
		cnt = odp_atomic_load_u32(&rwlock->cnt);
		/* waiting for read lock */
		if ((int32_t)cnt < 0) {
			odp_cpu_pause();
			continue;
		}
		is_locked = odp_atomic_cas_acq_u32(&rwlock->cnt, &cnt, cnt + 1);
	}
}

_ODP_INLINE int odp_rwlock_read_trylock(odp_rwlock_t *rwlock)
{
	uint32_t cnt = odp_atomic_load_u32(&rwlock->cnt);

	while (cnt != (uint32_t)-1) {
		if (odp_atomic_cas_acq_u32(&rwlock->cnt, &cnt, cnt + 1))
			return 1;
	}

	return 0;
}

_ODP_INLINE void odp_rwlock_read_unlock(odp_rwlock_t *rwlock)
{
	odp_atomic_sub_rel_u32(&rwlock->cnt, 1);
}

_ODP_INLINE void odp_rwlock_write_lock(odp_rwlock_t *rwlock)
{
	uint32_t cnt;
	int is_locked = 0;

	while (is_locked == 0) {
		uint32_t zero = 0;

		cnt = odp_atomic_load_u32(&rwlock->cnt);
		/* lock acquired, wait */
		if (cnt != 0) {
			odp_cpu_pause();
			continue;
		}
		is_locked = odp_atomic_cas_acq_u32(&rwlock->cnt, &zero, (uint32_t)-1);
	}
}

_ODP_INLINE int odp_rwlock_write_trylock(odp_rwlock_t *rwlock)
{
	uint32_t zero = 0;

	return odp_atomic_cas_acq_u32(&rwlock->cnt, &zero, (uint32_t)-1);
}

_ODP_INLINE void odp_rwlock_write_unlock(odp_rwlock_t *rwlock)
{
	odp_atomic_store_rel_u32(&rwlock->cnt, 0);
}

/** @endcond */

#endif