From e4a683c899cd5a49f8d684a054c95bd115a0c005 Mon Sep 17 00:00:00 2001
From: Jerome Marchand <jmarchan@redhat.com>
Date: Wed, 5 Jan 2011 16:57:37 +0100
Subject: [PATCH] kref: add kref_test_and_get

Add kref_test_and_get() function, which atomically add a reference only if
refcount is not zero. This prevent to add a reference to an object that is
already being removed.

Signed-off-by: Jerome Marchand <jmarchan@redhat.com>
Cc: stable@kernel.org
Signed-off-by: Jens Axboe <jaxboe@fusionio.com>
---
 include/linux/kref.h |  1 +
 lib/kref.c           | 12 ++++++++++++
 2 files changed, 13 insertions(+)

diff --git a/include/linux/kref.h b/include/linux/kref.h
index 6cc38fc07ab76..90b9e44abf54a 100644
--- a/include/linux/kref.h
+++ b/include/linux/kref.h
@@ -23,6 +23,7 @@ struct kref {
 
 void kref_init(struct kref *kref);
 void kref_get(struct kref *kref);
+int kref_test_and_get(struct kref *kref);
 int kref_put(struct kref *kref, void (*release) (struct kref *kref));
 
 #endif /* _KREF_H_ */
diff --git a/lib/kref.c b/lib/kref.c
index d3d227a08a4bd..e7a6e10671223 100644
--- a/lib/kref.c
+++ b/lib/kref.c
@@ -36,6 +36,18 @@ void kref_get(struct kref *kref)
 	smp_mb__after_atomic_inc();
 }
 
+/**
+ * kref_test_and_get - increment refcount for object only if refcount is not
+ * zero.
+ * @kref: object.
+ *
+ * Return non-zero if the refcount was incremented, 0 otherwise
+ */
+int kref_test_and_get(struct kref *kref)
+{
+	return atomic_inc_not_zero(&kref->refcount);
+}
+
 /**
  * kref_put - decrement refcount for object.
  * @kref: object.
-- 
GitLab