atomic.h 2.1 KB

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