| 1 | /* |
| 2 | * Copyright (C) 2011 - David Goulet <david.goulet@polymtl.ca> |
| 3 | * Mathieu Desnoyers <mathieu.desnoyers@efficios.com> |
| 4 | * |
| 5 | * This program is free software; you can redistribute it and/or |
| 6 | * modify it under the terms of the GNU General Public License |
| 7 | * as published by the Free Software Foundation; only version 2 |
| 8 | * of the License. |
| 9 | * |
| 10 | * This program is distributed in the hope that it will be useful, |
| 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | * GNU General Public License for more details. |
| 14 | * |
| 15 | * You should have received a copy of the GNU General Public License |
| 16 | * along with this program; if not, write to the Free Software |
| 17 | * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
| 18 | */ |
| 19 | |
| 20 | #define _GNU_SOURCE |
| 21 | #include <sys/syscall.h> |
| 22 | #include <unistd.h> |
| 23 | #include <urcu.h> |
| 24 | #include <urcu/futex.h> |
| 25 | |
| 26 | #include <lttngerr.h> |
| 27 | |
| 28 | #include "futex.h" |
| 29 | |
| 30 | /* |
| 31 | * This futex wait/wake scheme only works for N wakers / 1 waiters. Hence the |
| 32 | * "nto1" added to all function signature. |
| 33 | * |
| 34 | * Please see wait_gp()/update_counter_and_wait() calls in urcu.c in the urcu |
| 35 | * git tree for a detail example of this scheme being used. futex_async() is |
| 36 | * the urcu wrapper over the futex() sycall. |
| 37 | * |
| 38 | * There is also a formal verification available in the git tree. |
| 39 | * |
| 40 | * branch: formal-model |
| 41 | * commit id: 2a8044f3493046fcc8c67016902dc7beec6f026a |
| 42 | * |
| 43 | * Ref: git://git.lttng.org/userspace-rcu.git |
| 44 | */ |
| 45 | |
| 46 | /* |
| 47 | * Prepare futex. |
| 48 | */ |
| 49 | void futex_nto1_prepare(int32_t *futex) |
| 50 | { |
| 51 | uatomic_set(futex, -1); |
| 52 | cmm_smp_mb(); |
| 53 | |
| 54 | DBG("Futex n to 1 prepare done"); |
| 55 | } |
| 56 | |
| 57 | /* |
| 58 | * Wait futex. |
| 59 | */ |
| 60 | void futex_nto1_wait(int32_t *futex) |
| 61 | { |
| 62 | cmm_smp_mb(); |
| 63 | |
| 64 | if (uatomic_read(futex) == -1) { |
| 65 | futex_async(futex, FUTEX_WAIT, -1, NULL, NULL, 0); |
| 66 | } |
| 67 | |
| 68 | DBG("Futex n to 1 wait done"); |
| 69 | } |
| 70 | |
| 71 | /* |
| 72 | * Wake 1 futex. |
| 73 | */ |
| 74 | void futex_nto1_wake(int32_t *futex) |
| 75 | { |
| 76 | if (unlikely(uatomic_read(futex) == -1)) { |
| 77 | uatomic_set(futex, 0); |
| 78 | futex_async(futex, FUTEX_WAKE, 1, NULL, NULL, 0); |
| 79 | } |
| 80 | |
| 81 | DBG("Futex n to 1 wake done"); |
| 82 | } |