My Kernel v0.1.0
refcnt.h
1/*
2 * Reference counting API.
3 *
4 * By definition a reference count is always a positive value. The object should
5 * be freed when the count reaches 0 (by means of refcnt_put()), and any further
6 * attempts to increase this count will panic.
7 */
8
9#ifndef KERNEL_REFCNT_H
10#define KERNEL_REFCNT_H
11
12#include <kernel/atomic.h>
13#include <kernel/logger.h>
14
15typedef atomic_t refcnt_t;
16
23static inline void refcnt_init(refcnt_t *ref)
24{
25 atomic_write(ref, 1);
26}
27
28#define REFCNT_INIT_STATIC() ((refcnt_t){.val = 1})
29
31static inline unsigned int refcnt_read(refcnt_t *ref)
32{
33 return atomic_read(ref);
34}
35
37static inline unsigned int refcnt_get(refcnt_t *ref)
38{
39 unsigned int refs;
40
41 /*
42 * All references to this object have been released already.
43 * Do not 'resurrect' it as it may have been scheduled to be
44 * garbage collected (e.g. process API).
45 */
46 refs = atomic_inc(ref);
47 ASSERT(refs > 0);
48
49 return refs;
50}
51
56static inline unsigned int refcnt_put(refcnt_t *ref)
57{
58 return atomic_dec(ref) - 1;
59}
60
61#endif /* KERNEL_REFCNT_H */
An atomic value.
Definition: atomic.h:22