[RFC PATCH 01/15] cmpxchg_local() is not signed-value safe, so fix generic atomics
From: David Howells
Date: Wed May 18 2016 - 11:11:03 EST
cmpxchg_local() is not signed-value safe because on a 64-bit machine signed
int arguments to it may be sign-extended to signed long _before_ begin cast
to unsigned long. This potentially causes comparisons to fail when dealing
with negative values.
Fix the generic atomic functions that are implemented in terms of cmpxchg()
to cast their arguments to unsigned int before calling cmpxchg().
Signed-off-by: David Howells <dhowells@xxxxxxxxxx>
---
include/asm-generic/atomic.h | 17 +++++++++++------
1 file changed, 11 insertions(+), 6 deletions(-)
diff --git a/include/asm-generic/atomic.h b/include/asm-generic/atomic.h
index 74f1a3704d7a..e6c71c52edfe 100644
--- a/include/asm-generic/atomic.h
+++ b/include/asm-generic/atomic.h
@@ -37,28 +37,33 @@
#ifdef CONFIG_SMP
-/* we can build all atomic primitives from cmpxchg */
+/*
+ * We can build all atomic primitives from cmpxchg(), but we have to beware of
+ * implicit casting of signed int parameters to signed long and thence to
+ * unsigned long on a 64-bit machine if we don't explicitly cast to unsigned
+ * int.
+ */
#define ATOMIC_OP(op, c_op) \
static inline void atomic_##op(int i, atomic_t *v) \
{ \
- int c, old; \
+ unsigned int c, old; \
\
c = v->counter; \
- while ((old = cmpxchg(&v->counter, c, c c_op i)) != c) \
+ while ((old = cmpxchg(&v->counter, c, c c_op (unsigned int)i)) != c) \
c = old; \
}
#define ATOMIC_OP_RETURN(op, c_op) \
static inline int atomic_##op##_return(int i, atomic_t *v) \
{ \
- int c, old; \
+ unsigned int c, old; \
\
c = v->counter; \
- while ((old = cmpxchg(&v->counter, c, c c_op i)) != c) \
+ while ((old = cmpxchg(&v->counter, c, c c_op (unsigned int)i)) != c) \
c = old; \
\
- return c c_op i; \
+ return c c_op (unsigned int)i; \
}
#else