adding a test case
[IRC.git] / Robust / src / Tests / memPool / mlp_lock.h
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <assert.h>
4
5
6 #define INTPTR long
7
8
9 #define __xg(x) ((volatile INTPTR *)(x))
10
11 #define CFENCE   asm volatile("":::"memory");
12
13 #define LOCK_PREFIX \
14   ".section .smp_locks,\"a\"\n"   \
15   "  .align 4\n"                  \
16   "  .long 661f\n"             /* address */\
17   ".previous\n"                   \
18   "661:\n\tlock; "
19
20
21 static inline void atomic_dec(volatile int *v) {
22   __asm__ __volatile__ (LOCK_PREFIX "decl %0"
23                         : "+m" (*v));
24 }
25
26 static inline void atomic_inc(volatile int *v) {
27   __asm__ __volatile__ (LOCK_PREFIX "incl %0"
28                         : "+m" (*v));
29 }
30
31 static inline int atomic_sub_and_test(int i, volatile int *v) {
32   unsigned char c;
33
34   __asm__ __volatile__ (LOCK_PREFIX "subl %2,%0; sete %1"
35                         : "+m" (*v), "=qm" (c)
36                         : "ir" (i) : "memory");
37   return c;
38 }
39
40 #ifdef BIT64
41 static inline INTPTR LOCKXCHG(volatile INTPTR * ptr, INTPTR val){
42   INTPTR retval;
43   //note: xchgl always implies lock 
44   __asm__ __volatile__("xchgq %0,%1"
45                        : "=r"(retval)
46                        : "m"(*ptr), "0"(val)
47                        : "memory");
48   return retval;
49  
50 }
51 #else
52 static inline int LOCKXCHG(volatile int* ptr, int val){
53   int retval;
54   //note: xchgl always implies lock 
55   __asm__ __volatile__("xchgl %0,%1"
56                        : "=r"(retval)
57                        : "m"(*ptr), "0"(val)
58                        : "memory");
59   return retval;
60  
61 }
62 #endif
63
64 /*
65 static inline int write_trylock(volatile int *lock) {
66   int retval=0;
67   __asm__ __volatile__("xchgl %0,%1"
68                        : "=r"(retval)
69                        : "m"(*lock), "0"(retval)
70                        : "memory");
71   return retval;
72 }
73 */
74
75 #ifdef BIT64
76 static inline INTPTR CAS(volatile void *ptr, unsigned INTPTR old, unsigned INTPTR new){
77   unsigned INTPTR prev;
78   __asm__ __volatile__("lock; cmpxchgq %1,%2"
79                        : "=a"(prev)
80                        : "r"(new), "m"(*__xg(ptr)), "0"(old)
81                        : "memory");
82   return prev;
83 }
84 #else
85 static inline long CAS(volatile void *ptr, unsigned long old, unsigned long new){
86   unsigned long prev;
87   __asm__ __volatile__("lock; cmpxchgl %k1,%2"
88                        : "=a"(prev)
89                        : "r"(new), "m"(*__xg(ptr)), "0"(old)
90                        : "memory");
91   return prev;
92 }
93 #endif
94
95 static inline int BARRIER(){
96   CFENCE;
97   return 1;
98 }