X-Git-Url: http://git.onelab.eu/?a=blobdiff_plain;f=lib%2Fovs-atomic.h;h=4d43a42a5e6e739c627407492316d3fc5fe98290;hb=fe29af4c888d48cc1f16b1a247c2ffb6f0864522;hp=e7141145b5d243bf5a682ac98f0bd5e511949326;hpb=4597d2a57226eaec787d6501e88ab32f3b6209e1;p=sliver-openvswitch.git diff --git a/lib/ovs-atomic.h b/lib/ovs-atomic.h index e7141145b..4d43a42a5 100644 --- a/lib/ovs-atomic.h +++ b/lib/ovs-atomic.h @@ -84,8 +84,8 @@ * that. * * - * Initialization - * ============== + * Life Cycle + * ========== * * To initialize an atomic variable at its point of definition, use * ATOMIC_VAR_INIT: @@ -98,6 +98,15 @@ * ... * atomic_init(&ai, 123); * + * C11 does not hav an destruction function for atomic types, but some + * implementations of the OVS atomics do need them. Thus, the following + * function is provided for destroying non-static atomic objects (A is any + * atomic type): + * + * void atomic_destroy(A *object); + * + * Destroys 'object'. + * * * Barriers * ======== @@ -271,4 +280,65 @@ #endif #undef IN_OVS_ATOMIC_H +/* Reference count. */ +struct ovs_refcount { + atomic_uint count; +}; + +/* Initializes 'refcount'. The reference count is initially 1. */ +static inline void +ovs_refcount_init(struct ovs_refcount *refcount) +{ + atomic_init(&refcount->count, 1); +} + +/* Destroys 'refcount'. */ +static inline void +ovs_refcount_destroy(struct ovs_refcount *refcount) +{ + atomic_destroy(&refcount->count); +} + +/* Increments 'refcount'. */ +static inline void +ovs_refcount_ref(struct ovs_refcount *refcount) +{ + unsigned int old_refcount; + + atomic_add(&refcount->count, 1, &old_refcount); + ovs_assert(old_refcount > 0); +} + +/* Decrements 'refcount' and returns the previous reference count. Often used + * in this form: + * + * if (ovs_refcount_unref(&object->ref_cnt) == 1) { + * // ...uninitialize object... + * free(object); + * } + */ +static inline unsigned int +ovs_refcount_unref(struct ovs_refcount *refcount) +{ + unsigned int old_refcount; + + atomic_sub(&refcount->count, 1, &old_refcount); + ovs_assert(old_refcount > 0); + return old_refcount; +} + +/* Reads and returns 'ref_count_''s current reference count. + * + * Rarely useful. */ +static inline unsigned int +ovs_refcount_read(const struct ovs_refcount *refcount_) +{ + struct ovs_refcount *refcount + = CONST_CAST(struct ovs_refcount *, refcount_); + unsigned int count; + + atomic_read(&refcount->count, &count); + return count; +} + #endif /* ovs-atomic.h */