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
|
/* Copyright (c) 2014, Linaro Limited
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <stdbool.h>
#include <odp/api/atomic.h>
#include <odp/api/rwlock.h>
#include <odp/api/cpu.h>
void odp_rwlock_init(odp_rwlock_t *rwlock)
{
odp_atomic_init_u32(&rwlock->cnt, 0);
}
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);
}
}
int odp_rwlock_read_trylock(odp_rwlock_t *rwlock)
{
uint32_t zero = 0;
return odp_atomic_cas_acq_u32(&rwlock->cnt, &zero, (uint32_t)1);
}
void odp_rwlock_read_unlock(odp_rwlock_t *rwlock)
{
odp_atomic_sub_rel_u32(&rwlock->cnt, 1);
}
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);
}
}
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);
}
void odp_rwlock_write_unlock(odp_rwlock_t *rwlock)
{
odp_atomic_store_rel_u32(&rwlock->cnt, 0);
}
|