|
| 1 | +/* Copyright (c) 2013, Ben Noordhuis <info@bnoordhuis.nl> |
| 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 | + |
| 16 | +#ifndef UV_ATOMIC_OPS_H_ |
| 17 | +#define UV_ATOMIC_OPS_H_ |
| 18 | + |
| 19 | +#include "internal.h" /* UV_UNUSED */ |
| 20 | + |
| 21 | +UV_UNUSED(static int cmpxchgi(int* ptr, int oldval, int newval)); |
| 22 | +UV_UNUSED(static long cmpxchgl(long* ptr, long oldval, long newval)); |
| 23 | +UV_UNUSED(static void cpu_relax(void)); |
| 24 | + |
| 25 | +/* Prefer hand-rolled assembly over the gcc builtins because the latter also |
| 26 | + * issue full memory barriers. |
| 27 | + */ |
| 28 | +UV_UNUSED(static int cmpxchgi(int* ptr, int oldval, int newval)) { |
| 29 | +#if defined(__i386__) || defined(__x86_64__) |
| 30 | + int out; |
| 31 | + __asm__ __volatile__ ("lock; cmpxchg %2, %1;" |
| 32 | + : "=a" (out), "+m" (*(volatile int*) ptr) |
| 33 | + : "r" (newval), "0" (oldval) |
| 34 | + : "memory"); |
| 35 | + return out; |
| 36 | +#else |
| 37 | + return __sync_val_compare_and_swap(ptr, oldval, newval); |
| 38 | +#endif |
| 39 | +} |
| 40 | + |
| 41 | +UV_UNUSED(static long cmpxchgl(long* ptr, long oldval, long newval)) { |
| 42 | +#if defined(__i386__) || defined(__x86_64__) |
| 43 | + long out; |
| 44 | + __asm__ __volatile__ ("lock; cmpxchg %2, %1;" |
| 45 | + : "=a" (out), "+m" (*(volatile long*) ptr) |
| 46 | + : "r" (newval), "0" (oldval) |
| 47 | + : "memory"); |
| 48 | + return out; |
| 49 | +#else |
| 50 | + return __sync_val_compare_and_swap(ptr, oldval, newval); |
| 51 | +#endif |
| 52 | +} |
| 53 | + |
| 54 | +UV_UNUSED(static void cpu_relax(void)) { |
| 55 | +#if defined(__i386__) || defined(__x86_64__) |
| 56 | + __asm__ __volatile__ ("rep; nop"); /* a.k.a. PAUSE */ |
| 57 | +#endif |
| 58 | +} |
| 59 | + |
| 60 | +#endif /* UV_ATOMIC_OPS_H_ */ |
0 commit comments