Implementation of __sync_val_compare_and_swap function for Sparc V8

Question:

There is a cross compiler for the Sparc architecture. But it does not support Built-in functions for atomic memory access. I'm interested in the function __sync_val_compare_and_swap (long *ptr, long oldval long newval)

it performs an atomic compare and exchange operation: That is, if the current value of *ptr is oldval, then write newval into *ptr.

Here is the implementation for i386: Code:

struct __xchg_dummy { unsigned long a[100]; };
#define __xg(x) ((struct __xchg_dummy *)(x))

static inline unsigned long __cmpxchg(volatile void *ptr, unsigned long old,
                  unsigned long new, int size)
{
   unsigned long prev;
   switch (size) {
   case 1:
      __asm__ __volatile__(LOCK_PREFIX "cmpxchgb %b1,%2"
                 : "=a"(prev)
                 : "q"(new), "m"(*__xg(ptr)), "0"(old)
                 : "memory");
      return prev;
   case 2:
      __asm__ __volatile__(LOCK_PREFIX "cmpxchgw %w1,%2"
                 : "=a"(prev)
                 : "q"(new), "m"(*__xg(ptr)), "0"(old)
                 : "memory");
      return prev;
   case 4:
      __asm__ __volatile__(LOCK_PREFIX "cmpxchgl %1,%2"
                 : "=a"(prev)
                 : "q"(new), "m"(*__xg(ptr)), "0"(old)
                 : "memory");
      return prev;
   }
   return old;
}

#define cmpxchg(ptr,o,n)\
   ((__typeof__(*(ptr)))__cmpxchg((ptr),(unsigned long)(o),\
               (unsigned long)(n),sizeof(*(ptr))))

Is anyone familiar with writing assembler inserts (for C code) for the Sparc V8 architecture? I will be very grateful for help

Answer:

For Sparc, the same is done with instructions called CASA and CASXA. You can look for example in FreeBSD: functions : see casa , casxa , and their usage atomic_cas_32 , atomic_cas_64 .

Scroll to Top