Libatomic support

Daniel Cederman cederman at gaisler.com
Wed Oct 1 14:20:21 UTC 2014


Hi,

I'm looking at GCC's libatomic, which provides software emulation of 
atomic operations that are not supported by hardware. It does this by 
using a compare-and-swap loop, or, failing that, using locks. At the 
moment it is not selected for compilation for RTEMS since it requires 
operating system (or architecture) support for the locks. It needs 
support for two types of lock/unlock operations. Here is a cut-and-paste 
from the libatomic_i.h file in libatomic:

 >/* Locking for a "small" operation.  In the bare-metal single processor
 >   cases this could be implemented by disabling interrupts.  Thus the 
extra
 >   word passed between the two functions, saving the interrupt level.
 >   It is assumed that the object being locked does not cross the locking
 >   granularity.
 >
 >   Not actually declared here so that they can be defined static inline
 >   in a target-specfic <host-config.h>.
 >
 >UWORD protect_start (void *ptr);
 >void protect_end (void *ptr, UWORD);
 >*/
 >
 >/* Locking for a "large' operation.  This should always be some sort of
 >   test-and-set operation, as we assume that the interrupt latency would
 >   be unreasonably large.  */
 >void libat_lock_n (void *ptr, size_t n);
 >void libat_unlock_n (void *ptr, size_t n);

Currently there exists support for POSIX systems, for which libatomic 
uses pthread mutexes as locks. It looked a bit wrong, so I submitted a 
patch:
https://gcc.gnu.org/ml/gcc-patches/2014-09/msg01127.html

For RTEMS we could implement these two functions directly in the kernel 
instead of in libatomics, since we always link directly to the kernel.

The macro ATOMIC_INT_LOCK_FREE can be used to check if the RTEMS ticket 
lock is implemented using hardware primitives. If it is, we could use 
that for the libatomic locks. If not, then we can use 
atomic_flag_test_and_set instead to implement a spinlock. If I 
understand correctly, that function should always be lockless.

libat_lock_n currently does not support a context, which the ticket lock 
requires. The comment also seems to indicate that interrupts should not 
be disabled, but that would probably easily cause a deadlock in a 
real-time system? I'm new to using locks in a real-time setting so any 
comments on the matter are appreciated.

Does this seem like a possible approach to bringing libatomic support to 
RTEMS? Any comments welcome.

Best regards,
Daniel C


More information about the devel mailing list