-
Notifications
You must be signed in to change notification settings - Fork 4
/
objref.h
77 lines (67 loc) · 2.05 KB
/
objref.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
* Generic reference counting infrastructure.
*
* Note: refcounts need more relaxed memory ordering that regular atomics.
*
* The increments provide no ordering, because it's expected that the object is
* held by something else that provides ordering.
*
* The decrements provide release order, such that all the prior loads and
* stores will be issued before, it also provides a control dependency, which
* will order against the subsequent free().
*
* The control dependency is against the load of the cmpxchg (ll/sc) that
* succeeded. This means the stores aren't fully ordered, but this is fine
* because the 1->0 transition indicates no concurrency.
*
* The decrements dec_and_test() and sub_and_test() also provide acquire
* ordering on success.
*/
#pragma once
#include <stdbool.h>
#include "catomic.h"
struct objref {
unsigned long refcount;
void (*release)(struct objref *objref);
};
static inline void objref_init(struct objref *objref,
void (*release)(struct objref *objref))
{
objref->release = release;
catomic_set(&objref->refcount, 1);
}
static inline unsigned int objref_read(struct objref *objref)
{
return catomic_read(&objref->refcount);
}
static inline void refcount_inc(unsigned long *ptr)
{
__atomic_fetch_add(ptr, 1, __ATOMIC_RELAXED);
}
static inline void objref_get(struct objref *objref)
{
refcount_inc(&objref->refcount);
}
static inline bool refcount_dec_and_test(unsigned long *ptr)
{
unsigned long old = __atomic_fetch_sub(ptr, 1, __ATOMIC_RELEASE);
if (old == 1) {
smp_mb_acquire();
return true;
}
return false;
}
/*
* Decrement refcount for object, and call @release if it drops to zero.
* Return true if the object was removed, otherwise return false.
* Note: only "true" is trustworthy, "false" doesn't prevent another thread
* from releasing the object.
*/
static inline bool objref_put(struct objref *objref)
{
if (refcount_dec_and_test(&objref->refcount)) {
objref->release(objref);
return true;
}
return false;
}