]> xenbits.xensource.com Git - xen.git/commitdiff
x86: provide arch_fetch_and_add()
authorDavid Vrabel <david.vrabel@citrix.com>
Fri, 8 May 2015 08:59:26 +0000 (10:59 +0200)
committerJan Beulich <jbeulich@suse.com>
Fri, 8 May 2015 08:59:26 +0000 (10:59 +0200)
arch_fetch_and_add() atomically adds a value and returns the previous
value.

This is needed to implement ticket locks.

Signed-off-by: David Vrabel <david.vrabel@citrix.com>
xen/include/asm-x86/system.h

index 71113295bde35c134aed05b5416a63e852396cef..efe721cb44b57c8b2d3ec0837f4b0dcb02e4cba9 100644 (file)
@@ -117,6 +117,52 @@ static always_inline unsigned long __cmpxchg(
                                    (unsigned long)__n,sizeof(*(ptr)))); \
 })
 
+/*
+ * Undefined symbol to cause link failure if a wrong size is used with
+ * arch_fetch_and_add().
+ */
+extern unsigned long __bad_fetch_and_add_size(void);
+
+static always_inline unsigned long __xadd(
+    volatile void *ptr, unsigned long v, int size)
+{
+    switch ( size )
+    {
+    case 1:
+        asm volatile ( "lock; xaddb %b0,%1"
+                       : "+r" (v), "+m" (*__xg(ptr))
+                       :: "memory");
+        return v;
+    case 2:
+        asm volatile ( "lock; xaddw %w0,%1"
+                       : "+r" (v), "+m" (*__xg(ptr))
+                       :: "memory");
+        return v;
+    case 4:
+        asm volatile ( "lock; xaddl %k0,%1"
+                       : "+r" (v), "+m" (*__xg(ptr))
+                       :: "memory");
+        return v;
+    case 8:
+        asm volatile ( "lock; xaddq %q0,%1"
+                       : "+r" (v), "+m" (*__xg(ptr))
+                       :: "memory");
+
+        return v;
+    default:
+        return __bad_fetch_and_add_size();
+    }
+}
+
+/*
+ * Atomically add @v to the 1, 2, 4, or 8 byte value at @ptr.  Returns
+ * the previous value.
+ *
+ * This is a full memory barrier.
+ */
+#define arch_fetch_and_add(ptr, v) \
+    ((typeof(*(ptr)))__xadd(ptr, (typeof(*(ptr)))(v), sizeof(*(ptr))))
+
 /*
  * Both Intel and AMD agree that, from a programmer's viewpoint:
  *  Loads cannot be reordered relative to other loads.