From 9faa11cddcf2a9fad24aa057fe55d37427ab739f Mon Sep 17 00:00:00 2001 From: Max Wash Date: Tue, 24 Mar 2026 19:09:36 +0000 Subject: [PATCH] kernel: add atomic operations --- include/kernel/atomic.h | 66 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 include/kernel/atomic.h diff --git a/include/kernel/atomic.h b/include/kernel/atomic.h new file mode 100644 index 0000000..0230c99 --- /dev/null +++ b/include/kernel/atomic.h @@ -0,0 +1,66 @@ +#ifndef KERNEL_ATOMIC_H_ +#define KERNEL_ATOMIC_H_ + +#include +#include + +typedef int64_t atomic_t; + +/* load and return the value pointed to by `v` */ +static inline atomic_t atomic_load(atomic_t *v) +{ + return __atomic_load_n(v, __ATOMIC_ACQUIRE); +} +/* store the value `v` to the pointer `dest` */ +static inline void atomic_store(atomic_t *dest, atomic_t v) +{ + __atomic_store_n(dest, v, __ATOMIC_ACQUIRE); +} +/* store the value `v` to the pointer `dest`, and return the value previously + * stored at `dest` */ +static inline atomic_t atomic_exchange(atomic_t *dest, atomic_t v) +{ + return __atomic_exchange_n(dest, v, __ATOMIC_ACQUIRE); +} +/* compare the contents of `ptr` to the contents of `expected`. + * if they match, store the value `desired` to the pointer `ptr` and return + * true. if the do NOT match, store the value `*ptr` to the pointer `desired` + * and return false. + */ +static inline bool atomic_compare_exchange( + atomic_t *ptr, + atomic_t *expected, + atomic_t desired) +{ + return __atomic_compare_exchange_n( + ptr, + expected, + desired, + false, + __ATOMIC_ACQUIRE, + __ATOMIC_ACQUIRE); +} + +/* perform the operation *ptr += val, and return the result */ +static inline atomic_t atomic_add_fetch(atomic_t *ptr, atomic_t val) +{ + return __atomic_add_fetch(ptr, val, __ATOMIC_ACQUIRE); +} +/* perform the operation *ptr -= val, and return the result */ +static inline atomic_t atomic_sub_fetch(atomic_t *ptr, atomic_t val) +{ + return __atomic_sub_fetch(ptr, val, __ATOMIC_ACQUIRE); +} + +/* perform the operation *ptr += val, and return the previous value of *ptr */ +static inline atomic_t atomic_fetch_add(atomic_t *ptr, atomic_t val) +{ + return __atomic_fetch_add(ptr, val, __ATOMIC_ACQUIRE); +} +/* perform the operation *ptr -= val, and return the previous value of *ptr */ +static inline atomic_t atomic_fetch_sub(atomic_t *ptr, atomic_t val) +{ + return __atomic_fetch_sub(ptr, val, __ATOMIC_ACQUIRE); +} + +#endif