atomic-ops.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* Copyright (c) 2013, Ben Noordhuis <[email protected]>
  2. *
  3. * Permission to use, copy, modify, and/or distribute this software for any
  4. * purpose with or without fee is hereby granted, provided that the above
  5. * copyright notice and this permission notice appear in all copies.
  6. *
  7. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. */
  15. #ifndef UV_ATOMIC_OPS_H_
  16. #define UV_ATOMIC_OPS_H_
  17. #include "internal.h" /* UV_UNUSED */
  18. #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
  19. #include <atomic.h>
  20. #endif
  21. UV_UNUSED(static int cmpxchgi(int* ptr, int oldval, int newval));
  22. UV_UNUSED(static void cpu_relax(void));
  23. /* Prefer hand-rolled assembly over the gcc builtins because the latter also
  24. * issue full memory barriers.
  25. */
  26. UV_UNUSED(static int cmpxchgi(int* ptr, int oldval, int newval)) {
  27. #if defined(__i386__) || defined(__x86_64__)
  28. int out;
  29. __asm__ __volatile__ ("lock; cmpxchg %2, %1;"
  30. : "=a" (out), "+m" (*(volatile int*) ptr)
  31. : "r" (newval), "0" (oldval)
  32. : "memory");
  33. return out;
  34. #elif defined(_AIX) && (defined(__xlC__) || defined(__ibmxl__))
  35. const int out = (*(volatile int*) ptr);
  36. __compare_and_swap(ptr, &oldval, newval);
  37. return out;
  38. #elif defined(__MVS__)
  39. unsigned int op4;
  40. if (__plo_CSST(ptr, (unsigned int*) &oldval, newval,
  41. (unsigned int*) ptr, *ptr, &op4))
  42. return oldval;
  43. else
  44. return op4;
  45. #elif defined(__SUNPRO_C) || defined(__SUNPRO_CC)
  46. return atomic_cas_uint((uint_t *)ptr, (uint_t)oldval, (uint_t)newval);
  47. #else
  48. return __sync_val_compare_and_swap(ptr, oldval, newval);
  49. #endif
  50. }
  51. UV_UNUSED(static void cpu_relax(void)) {
  52. #if defined(__i386__) || defined(__x86_64__)
  53. __asm__ __volatile__ ("rep; nop"); /* a.k.a. PAUSE */
  54. #endif
  55. }
  56. #endif /* UV_ATOMIC_OPS_H_ */