[PATCH 1/2] kref: add kref_test_and_get

Previous message: [thread] [date] [author]
Next message: [thread] [date] [author]
From: Jerome Marchand
Date: Tuesday, January 4, 2011 - 8:52 am

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>
---
 include/linux/kref.h |    1 +
 lib/kref.c           |   16 ++++++++++++++++
 2 files changed, 17 insertions(+)

diff --git a/include/linux/kref.h b/include/linux/kref.h
index 6cc38fc..90b9e44 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 d3d227a..5f663b9 100644
--- a/lib/kref.c
+++ b/lib/kref.c
@@ -37,6 +37,22 @@ void kref_get(struct kref *kref)
 }
 
 /**
+ * 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)
+{
+	int ret;
+	smp_mb__before_atomic_inc();
+	ret = atomic_inc_not_zero(&kref->refcount);
+	smp_mb__after_atomic_inc();
+	return ret;
+}
+
+/**
  * kref_put - decrement refcount for object.
  * @kref: object.
  * @release: pointer to the function that will clean up the object when the
--
Previous message: [thread] [date] [author]
Next message: [thread] [date] [author]

Messages in current thread:
[PATCH 1/2] Don't merge different partition's IOs, Yasuaki Ishimatsu, (Mon Dec 6, 2:44 am)
Re: [PATCH 1/2] Don't merge different partition's IOs, Linus Torvalds, (Mon Dec 6, 9:08 am)
Re: [PATCH 1/2] Don't merge different partition's IOs, Satoru Takeuchi, (Tue Dec 7, 12:18 am)
Re: [PATCH 1/2] Don't merge different partition's IOs, Vivek Goyal, (Tue Dec 7, 11:39 am)
Re: [PATCH 1/2] Don't merge different partition's IOs, Satoru Takeuchi, (Wed Dec 8, 12:59 am)
Re: [PATCH 1/2] Don't merge different partition's IOs, Satoru Takeuchi, (Wed Dec 8, 1:11 am)
Re: [PATCH 1/2] Don't merge different partition's IOs, Jerome Marchand, (Fri Dec 10, 4:22 am)
Re: [PATCH 1/2] Don't merge different partition's IOs, Jerome Marchand, (Fri Dec 10, 9:12 am)
Re: [PATCH 1/2] Don't merge different partition's IOs, Vivek Goyal, (Fri Dec 10, 9:55 am)
[PATCH] block: fix accounting bug on cross partition merges, Jerome Marchand, (Fri Dec 17, 6:42 am)
[PATCH 1/2] kref: add kref_test_and_get, Jerome Marchand, (Tue Jan 4, 8:52 am)
Re: [PATCH 1/2] kref: add kref_test_and_get, Eric Dumazet, (Tue Jan 4, 9:05 am)
Re: [PATCH 1/2] kref: add kref_test_and_get, Greg KH, (Tue Jan 4, 1:57 pm)