X-Git-Url: https://git.liburcu.org/?p=urcu.git;a=blobdiff_plain;f=urcu%2Fref.h;h=e546da567120e086e5773950ac135d510900b4fc;hp=74be50d6bbe4e46d28603ba4cb8de3db2ed7794a;hb=4d0d7cbccec1c35f544f6fee24b762e398a2f0b9;hpb=cd21955a846566b3cd7ca77d58cd3d006f3c533a diff --git a/urcu/ref.h b/urcu/ref.h index 74be50d..e546da5 100644 --- a/urcu/ref.h +++ b/urcu/ref.h @@ -16,6 +16,8 @@ #include #include +#include +#include #include struct urcu_ref { @@ -32,9 +34,29 @@ static inline void urcu_ref_init(struct urcu_ref *ref) urcu_ref_set(ref, 1); } +static inline bool __attribute__((warn_unused_result)) + urcu_ref_get_safe(struct urcu_ref *ref) +{ + long old, _new, res; + + old = uatomic_read(&ref->refcount); + for (;;) { + if (old == LONG_MAX) { + return false; /* Failure. */ + } + _new = old + 1; + res = uatomic_cmpxchg(&ref->refcount, old, _new); + if (res == old) { + return true; /* Success. */ + } + old = res; + } +} + static inline void urcu_ref_get(struct urcu_ref *ref) { - uatomic_add(&ref->refcount, 1); + if (!urcu_ref_get_safe(ref)) + abort(); } static inline void urcu_ref_put(struct urcu_ref *ref, @@ -53,7 +75,8 @@ static inline void urcu_ref_put(struct urcu_ref *ref, * zero. Returns true if the reference is taken, false otherwise. This * needs to be used in conjunction with another synchronization * technique (e.g. RCU or mutex) to ensure existence of the reference - * count. + * count. False is also returned in case incrementing the refcount would + * result in an overflow. */ static inline bool urcu_ref_get_unless_zero(struct urcu_ref *ref) { @@ -61,7 +84,7 @@ static inline bool urcu_ref_get_unless_zero(struct urcu_ref *ref) old = uatomic_read(&ref->refcount); for (;;) { - if (old == 0) + if (old == 0 || old == LONG_MAX) return false; /* Failure. */ _new = old + 1; res = uatomic_cmpxchg(&ref->refcount, old, _new);