1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
// Copyright 2024 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::sys::{
    zx_futex_get_owner, zx_futex_requeue, zx_futex_requeue_single_owner, zx_futex_t, zx_futex_wait,
    zx_futex_wake, zx_futex_wake_handle_close_thread_exit, zx_futex_wake_single_owner,
    ZX_HANDLE_INVALID, ZX_KOID_INVALID, ZX_OK,
};
use crate::{AsHandleRef, Handle, Koid, MonotonicInstant, Status, Thread};

/// A safe wrapper around zx_futex_t, generally called as part of higher-level synchronization
/// primitives.
#[derive(Debug)]
pub struct Futex {
    inner: zx_futex_t,
}

impl std::ops::Deref for Futex {
    type Target = zx_futex_t;
    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl Futex {
    #[inline]
    pub const fn new(value: i32) -> Self {
        Self { inner: zx_futex_t::new(value) }
    }

    fn value_ptr(&self) -> *const zx_futex_t {
        std::ptr::addr_of!(self.inner)
    }

    /// See https://fuchsia.dev/reference/syscalls/futex_wake.
    #[inline]
    pub fn wake(&self, wake_count: u32) {
        // SAFETY: Arguments for this system call do not have any liveness or validity requirements.
        let status = unsafe { zx_futex_wake(self.value_ptr(), wake_count) };
        assert_eq!(status, ZX_OK, "only fails due to misaligned or unmapped pointers");
    }

    /// Wakes the maximum number of waiters possible.
    ///
    /// See https://fuchsia.dev/reference/syscalls/futex_wake.
    #[inline]
    pub fn wake_all(&self) {
        self.wake(u32::MAX)
    }

    /// See https://fuchsia.dev/reference/syscalls/futex_wake_single_owner.
    #[inline]
    pub fn wake_single_owner(&self) {
        // SAFETY: Arguments for this system call do not have any liveness or validity requirements.
        let status = unsafe { zx_futex_wake_single_owner(self.value_ptr()) };
        assert_eq!(status, ZX_OK, "only fails due to misaligned or unampped pointers")
    }

    /// See https://fuchsia.dev/reference/syscalls/futex_wake_handle_close_thread_exit.
    pub fn wake_handle_close_thread_exit(
        &self,
        wake_count: u32,
        new_value: i32,
        to_close: Handle,
    ) -> ! {
        // SAFETY: Arguments for this system call do not have any liveness or validity requirements.
        unsafe {
            zx_futex_wake_handle_close_thread_exit(
                self.value_ptr(),
                wake_count,
                new_value,
                to_close.raw_handle(),
            );
        }
        unreachable!("zx_futex_wake_handle_close_thread_exit() does not return.");
    }

    /// See https://fuchsia.dev/reference/syscalls/futex_requeue.
    #[inline]
    pub fn requeue(
        &self,
        wake_count: u32,
        current_value: i32,
        requeue_to: &Self,
        requeue_count: u32,
        new_requeue_owner: Option<&Thread>,
    ) -> Result<(), Status> {
        // SAFETY: Arguments for this system call do not have any liveness or validity requirements.
        Status::ok(unsafe {
            zx_futex_requeue(
                self.value_ptr(),
                wake_count,
                current_value,
                requeue_to.value_ptr(),
                requeue_count,
                new_requeue_owner.map(|o| o.raw_handle()).unwrap_or(ZX_HANDLE_INVALID),
            )
        })
    }

    /// See https://fuchsia.dev/reference/syscalls/futex_requeue_single_owner.
    #[inline]
    pub fn requeue_single_owner(
        &self,
        current_value: i32,
        requeue_to: &Self,
        requeue_count: u32,
        new_requeue_owner: Option<&Thread>,
    ) -> Result<(), Status> {
        // SAFETY: Arguments for this system call do not have any liveness or validity requirements.
        Status::ok(unsafe {
            zx_futex_requeue_single_owner(
                self.value_ptr(),
                current_value,
                requeue_to.value_ptr(),
                requeue_count,
                new_requeue_owner.map(|o| o.raw_handle()).unwrap_or(ZX_HANDLE_INVALID),
            )
        })
    }

    /// See https://fuchsia.dev/reference/syscalls/futex_wait.
    #[inline]
    pub fn wait(
        &self,
        current_value: i32,
        new_owner: Option<&Thread>,
        deadline: MonotonicInstant,
    ) -> Result<(), Status> {
        // SAFETY: Arguments for this system call do not have any liveness or validity requirements.
        Status::ok(unsafe {
            zx_futex_wait(
                self.value_ptr(),
                current_value,
                new_owner.map(|o| o.raw_handle()).unwrap_or(ZX_HANDLE_INVALID),
                deadline.into_nanos(),
            )
        })
    }

    /// See https://fuchsia.dev/reference/syscalls/futex_get_owner.
    pub fn get_owner(&self) -> Option<Koid> {
        let mut koid = ZX_KOID_INVALID;

        // SAFETY: Arguments for this system call do not have any liveness or validity requirements.
        // `&mut koid` is valid for the entire duration of the call.
        Status::ok(unsafe { zx_futex_get_owner(self.value_ptr(), &mut koid) })
            .expect("get_owner only fails due to misaligned or unmapped pointers");

        if koid != ZX_KOID_INVALID {
            Some(Koid::from_raw(koid))
        } else {
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Duration, Unowned};

    #[test]
    fn basic_wait_wake() {
        // SAFETY: converting between versions of the same types, the handle is valid
        let main_thread =
            unsafe { Unowned::from_raw_handle(fuchsia_runtime::thread_self().raw_handle()) };
        let futex = Futex::new(0);
        std::thread::scope(|s| {
            s.spawn(|| futex.wait(0, Some(&*main_thread), MonotonicInstant::INFINITE).unwrap());
            while futex.get_owner().is_none() {
                std::thread::sleep(std::time::Duration::from_secs(1));
            }
            futex.wake_single_owner();
        });
    }

    #[test]
    fn cant_wait_with_wrong_value() {
        let futex = Futex::new(0);
        assert_eq!(futex.wait(5, None, MonotonicInstant::INFINITE).unwrap_err(), Status::BAD_STATE);
    }

    #[test]
    fn wait_timed_out() {
        assert_eq!(
            Futex::new(0)
                .wait(0, None, MonotonicInstant::after(Duration::from_seconds(1)))
                .unwrap_err(),
            Status::TIMED_OUT,
        );
    }
}