atomic-gcc.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* SPDX-License-Identifier: GPL-2.0 */
  2. #ifndef __TOOLS_ASM_GENERIC_ATOMIC_H
  3. #define __TOOLS_ASM_GENERIC_ATOMIC_H
  4. #include <linux/compiler.h>
  5. #include <linux/types.h>
  6. /*
  7. * Atomic operations that C can't guarantee us. Useful for
  8. * resource counting etc..
  9. *
  10. * Excerpts obtained from the Linux kernel sources.
  11. */
  12. #define ATOMIC_INIT(i) { (i) }
  13. /**
  14. * atomic_read - read atomic variable
  15. * @v: pointer of type atomic_t
  16. *
  17. * Atomically reads the value of @v.
  18. */
  19. static inline int atomic_read(const atomic_t *v)
  20. {
  21. return READ_ONCE((v)->counter);
  22. }
  23. /**
  24. * atomic_set - set atomic variable
  25. * @v: pointer of type atomic_t
  26. * @i: required value
  27. *
  28. * Atomically sets the value of @v to @i.
  29. */
  30. static inline void atomic_set(atomic_t *v, int i)
  31. {
  32. v->counter = i;
  33. }
  34. /**
  35. * atomic_inc - increment atomic variable
  36. * @v: pointer of type atomic_t
  37. *
  38. * Atomically increments @v by 1.
  39. */
  40. static inline void atomic_inc(atomic_t *v)
  41. {
  42. __sync_add_and_fetch(&v->counter, 1);
  43. }
  44. /**
  45. * atomic_dec_and_test - decrement and test
  46. * @v: pointer of type atomic_t
  47. *
  48. * Atomically decrements @v by 1 and
  49. * returns true if the result is 0, or false for all other
  50. * cases.
  51. */
  52. static inline int atomic_dec_and_test(atomic_t *v)
  53. {
  54. return __sync_sub_and_fetch(&v->counter, 1) == 0;
  55. }
  56. #define cmpxchg(ptr, oldval, newval) \
  57. __sync_val_compare_and_swap(ptr, oldval, newval)
  58. static inline int atomic_cmpxchg(atomic_t *v, int oldval, int newval)
  59. {
  60. return cmpxchg(&(v)->counter, oldval, newval);
  61. }
  62. #endif /* __TOOLS_ASM_GENERIC_ATOMIC_H */