#ifndef _LINUXKPI_LINUX_KREF_H_
#define _LINUXKPI_LINUX_KREF_H_
#include <sys/types.h>
#include <sys/refcount.h>
#include <linux/compiler.h>
#include <linux/kernel.h>
#include <linux/mutex.h>
#include <linux/refcount.h>
#include <asm/atomic.h>
struct kref {
refcount_t refcount;
};
static inline void
kref_init(struct kref *kref)
{
refcount_init((uint32_t *)&kref->refcount, 1);
}
static inline unsigned int
kref_read(const struct kref *kref)
{
return (refcount_load(__DECONST(u_int32_t *, &kref->refcount)));
}
static inline void
kref_get(struct kref *kref)
{
refcount_acquire((uint32_t *)&kref->refcount);
}
static inline int
kref_put(struct kref *kref, void (*rel)(struct kref *kref))
{
if (refcount_release((uint32_t *)&kref->refcount)) {
rel(kref);
return 1;
}
return 0;
}
static inline int
kref_put_lock(struct kref *kref, void (*rel)(struct kref *kref),
spinlock_t *lock)
{
if (refcount_release((uint32_t *)&kref->refcount)) {
spin_lock(lock);
rel(kref);
return (1);
}
return (0);
}
static inline int
kref_sub(struct kref *kref, unsigned int count,
void (*rel)(struct kref *kref))
{
while (count--) {
if (refcount_release((uint32_t *)&kref->refcount)) {
rel(kref);
return 1;
}
}
return 0;
}
static inline int __must_check
kref_get_unless_zero(struct kref *kref)
{
return refcount_acquire_if_not_zero((uint32_t *)&kref->refcount);
}
static inline int kref_put_mutex(struct kref *kref,
void (*release)(struct kref *kref), struct mutex *lock)
{
WARN_ON(release == NULL);
if (unlikely(!refcount_release_if_not_last((uint32_t *)&kref->refcount))) {
mutex_lock(lock);
if (unlikely(!refcount_release((uint32_t *)&kref->refcount))) {
mutex_unlock(lock);
return 0;
}
release(kref);
return 1;
}
return 0;
}
#endif