atomic-gcc.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. #include <linux/bitops.h>
  7. /*
  8. * Atomic operations that C can't guarantee us. Useful for
  9. * resource counting etc..
  10. *
  11. * Excerpts obtained from the Linux kernel sources.
  12. */
  13. #define ATOMIC_INIT(i) { (i) }
  14. /**
  15. * atomic_read - read atomic variable
  16. * @v: pointer of type atomic_t
  17. *
  18. * Atomically reads the value of @v.
  19. */
  20. static inline int atomic_read(const atomic_t *v)
  21. {
  22. return READ_ONCE((v)->counter);
  23. }
  24. /**
  25. * atomic_set - set atomic variable
  26. * @v: pointer of type atomic_t
  27. * @i: required value
  28. *
  29. * Atomically sets the value of @v to @i.
  30. */
  31. static inline void atomic_set(atomic_t *v, int i)
  32. {
  33. v->counter = i;
  34. }
  35. /**
  36. * atomic_inc - increment atomic variable
  37. * @v: pointer of type atomic_t
  38. *
  39. * Atomically increments @v by 1.
  40. */
  41. static inline void atomic_inc(atomic_t *v)
  42. {
  43. __sync_add_and_fetch(&v->counter, 1);
  44. }
  45. /**
  46. * atomic_dec_and_test - decrement and test
  47. * @v: pointer of type atomic_t
  48. *
  49. * Atomically decrements @v by 1 and
  50. * returns true if the result is 0, or false for all other
  51. * cases.
  52. */
  53. static inline int atomic_dec_and_test(atomic_t *v)
  54. {
  55. return __sync_sub_and_fetch(&v->counter, 1) == 0;
  56. }
  57. #define cmpxchg(ptr, oldval, newval) \
  58. __sync_val_compare_and_swap(ptr, oldval, newval)
  59. static inline int atomic_cmpxchg(atomic_t *v, int oldval, int newval)
  60. {
  61. return cmpxchg(&(v)->counter, oldval, newval);
  62. }
  63. static inline int test_and_set_bit(long nr, unsigned long *addr)
  64. {
  65. unsigned long mask = BIT_MASK(nr);
  66. long old;
  67. addr += BIT_WORD(nr);
  68. old = __sync_fetch_and_or(addr, mask);
  69. return !!(old & mask);
  70. }
  71. static inline int test_and_clear_bit(long nr, unsigned long *addr)
  72. {
  73. unsigned long mask = BIT_MASK(nr);
  74. long old;
  75. addr += BIT_WORD(nr);
  76. old = __sync_fetch_and_and(addr, ~mask);
  77. return !!(old & mask);
  78. }
  79. #endif /* __TOOLS_ASM_GENERIC_ATOMIC_H */