Super Light Weight Reference counting

Venkatesh Srinivas me at
Tue Dec 21 10:04:50 PST 2010


Just an updated proposal, it seems that it'd be better to remove the
priv pointer from the reference structure entirely:
ref.h :============
struct kref {
	int		refcount;

void kref_init(struct kref *ref, int count);
void kref_inc(struct kref *ref);
void kref_dec(struct kref *ref, void (*deconstruct)(void*, void*),
	      void *priv1, void *priv2);

kern_ref.c :==============
#include <sys/atomic.h>

kref_init(struct kref *ref, int count)
        ref->refcount = count;

kref_inc(struct kref *ref)
        atomic_add_int(&ref->refcount, 1);

kref_dec(struct kref *ref, void (*deconstruct)(void *, void *),
         void *priv1, void *priv2)
        int val;

        val = atomic_fetchadd_int(&ref->refcount, -1);
        if (val == 1)
                deconstruct(priv1, priv2);


You can now kref_dec(&buf->ref, kfree, buf, M_AWESOME); to use this to
kfree buffers, for example.

Thanks to Aggelos again for convincing me to remove the priv pointer entirely.
-- vs

More information about the Kernel mailing list