atomic.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. #ifndef _INTERNAL_ATOMIC_H
  2. #define _INTERNAL_ATOMIC_H
  3. #include <stdint.h>
  4. static inline int a_ctz_l(unsigned long x)
  5. {
  6. static const char debruijn32[32] = {
  7. 0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13,
  8. 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14
  9. };
  10. return debruijn32[(x&-x)*0x076be629 >> 27];
  11. }
  12. static inline int a_ctz_64(uint64_t x)
  13. {
  14. uint32_t y = x;
  15. if (!y) {
  16. y = x>>32;
  17. return 32 + a_ctz_l(y);
  18. }
  19. return a_ctz_l(y);
  20. }
  21. static inline int a_cas(volatile int *p, int t, int s)
  22. {
  23. __asm__("1: l.lwa %0, %1\n"
  24. " l.sfeq %0, %2\n"
  25. " l.bnf 1f\n"
  26. " l.nop\n"
  27. " l.swa %1, %3\n"
  28. " l.bnf 1b\n"
  29. " l.nop\n"
  30. "1: \n"
  31. : "=&r"(t), "+m"(*p) : "r"(t), "r"(s) : "cc", "memory" );
  32. return t;
  33. }
  34. static inline void *a_cas_p(volatile void *p, void *t, void *s)
  35. {
  36. return (void *)a_cas(p, (int)t, (int)s);
  37. }
  38. static inline int a_swap(volatile int *x, int v)
  39. {
  40. int old;
  41. do old = *x;
  42. while (a_cas(x, old, v) != old);
  43. return old;
  44. }
  45. static inline int a_fetch_add(volatile int *x, int v)
  46. {
  47. int old;
  48. do old = *x;
  49. while (a_cas(x, old, old+v) != old);
  50. return old;
  51. }
  52. static inline void a_inc(volatile int *x)
  53. {
  54. a_fetch_add(x, 1);
  55. }
  56. static inline void a_dec(volatile int *x)
  57. {
  58. a_fetch_add(x, -1);
  59. }
  60. static inline void a_store(volatile int *p, int x)
  61. {
  62. a_swap(p, x);
  63. }
  64. #define a_spin a_barrier
  65. static inline void a_barrier()
  66. {
  67. a_cas(&(int){0}, 0, 0);
  68. }
  69. static inline void a_crash()
  70. {
  71. *(volatile char *)0=0;
  72. }
  73. static inline void a_and(volatile int *p, int v)
  74. {
  75. int old;
  76. do old = *p;
  77. while (a_cas(p, old, old&v) != old);
  78. }
  79. static inline void a_or(volatile int *p, int v)
  80. {
  81. int old;
  82. do old = *p;
  83. while (a_cas(p, old, old|v) != old);
  84. }
  85. static inline void a_or_l(volatile void *p, long v)
  86. {
  87. a_or(p, v);
  88. }
  89. static inline void a_and_64(volatile uint64_t *p, uint64_t v)
  90. {
  91. union { uint64_t v; uint32_t r[2]; } u = { v };
  92. a_and((int *)p, u.r[0]);
  93. a_and((int *)p+1, u.r[1]);
  94. }
  95. static inline void a_or_64(volatile uint64_t *p, uint64_t v)
  96. {
  97. union { uint64_t v; uint32_t r[2]; } u = { v };
  98. a_or((int *)p, u.r[0]);
  99. a_or((int *)p+1, u.r[1]);
  100. }
  101. #endif