[<prev] [next>] [thread-next>] [day] [month] [year] [list]
Message-ID: <20190502152621.GB18948@bombadil.infradead.org>
Date: Thu, 2 May 2019 08:26:21 -0700
From: Matthew Wilcox <willy@...radead.org>
To: Kees Cook <keescook@...omium.org>,
Peter Zijlstra <peterz@...radead.org>,
Ingo Molnar <mingo@...nel.org>, linux-kernel@...r.kernel.org
Subject: Alloc refcount increments to fail
In the comments section of a recent LWN article [1], Neil asked if we
could have a way for refcount users to avoid getting to the saturated
state if they have a way of handling fallback gracefully. Here's an
attempt to provide that functionality. I'm not sure it's compatible
with Kees' "x86/asm: Implement fast refcount overflow protection", but
I thought I'd send it out anyway so people who have thought about this
more deeply than I have can tell me if it's an idea worth pursuing or not.
[1] https://lwn.net/Articles/786044/
diff --git a/include/linux/refcount.h b/include/linux/refcount.h
index e28cce21bad6..c4b15b5ec084 100644
--- a/include/linux/refcount.h
+++ b/include/linux/refcount.h
@@ -108,6 +108,21 @@ static inline void refcount_dec(refcount_t *r)
# endif /* !CONFIG_ARCH_HAS_REFCOUNT */
#endif /* CONFIG_REFCOUNT_FULL */
+/**
+ * refcount_try_inc - Increment a refcount if it's below INT_MAX
+ * @r: the refcount to increment
+ *
+ * Avoid the counter saturating by declining to increment the counter
+ * if it is more than halfway to saturation.
+ */
+static inline __must_check bool refcount_try_inc(refcount_t *r)
+{
+ if (refcount_read(r) < 0)
+ return false;
+ refcount_inc(r);
+ return true;
+}
+
extern __must_check bool refcount_dec_if_one(refcount_t *r);
extern __must_check bool refcount_dec_not_one(refcount_t *r);
extern __must_check bool refcount_dec_and_mutex_lock(refcount_t *r, struct mutex *lock);
Powered by blists - more mailing lists