1/*
2 * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25#include "precompiled/precompiled.hpp"
26#include "runtime/orderAccess.hpp"
27#include "runtime/os.hpp"
28#include "waitBarrier_linux.hpp"
29#include <sys/syscall.h>
30#include <linux/futex.h>
31
32#define check_with_errno(check_type, cond, msg) \
33 do { \
34 int err = errno; \
35 check_type(cond, "%s: error='%s' (errno=%s)", msg, os::strerror(err), \
36 os::errno_name(err)); \
37} while (false)
38
39#define guarantee_with_errno(cond, msg) check_with_errno(guarantee, cond, msg)
40
41static int futex(volatile int *addr, int futex_op, int op_arg) {
42 return syscall(SYS_futex, addr, futex_op, op_arg, NULL, NULL, 0);
43}
44
45void LinuxWaitBarrier::arm(int barrier_tag) {
46 assert(_futex_barrier == 0, "Should not be already armed: "
47 "_futex_barrier=%d", _futex_barrier);
48 _futex_barrier = barrier_tag;
49 OrderAccess::fence();
50}
51
52void LinuxWaitBarrier::disarm() {
53 assert(_futex_barrier != 0, "Should be armed/non-zero.");
54 _futex_barrier = 0;
55 int s = futex(&_futex_barrier,
56 FUTEX_WAKE_PRIVATE,
57 INT_MAX /* wake a max of this many threads */);
58 guarantee_with_errno(s > -1, "futex FUTEX_WAKE failed");
59}
60
61void LinuxWaitBarrier::wait(int barrier_tag) {
62 assert(barrier_tag != 0, "Trying to wait on disarmed value");
63 if (barrier_tag == 0 ||
64 barrier_tag != _futex_barrier) {
65 OrderAccess::fence();
66 return;
67 }
68 do {
69 int s = futex(&_futex_barrier,
70 FUTEX_WAIT_PRIVATE,
71 barrier_tag /* should be this tag */);
72 guarantee_with_errno((s == 0) ||
73 (s == -1 && errno == EAGAIN) ||
74 (s == -1 && errno == EINTR),
75 "futex FUTEX_WAIT failed");
76 // Return value 0: woken up, but re-check in case of spurious wakeup.
77 // Error EINTR: woken by signal, so re-check and re-wait if necessary.
78 // Error EAGAIN: we are already disarmed and so will pass the check.
79 } while (barrier_tag == _futex_barrier);
80}
81