ax-sync 0.5.32

ArceOS synchronization primitives
Documentation
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//! Hidden runtime boundary for the OS-independent lock wrappers.

use core::{
    panic::Location,
    sync::atomic::{AtomicBool, AtomicPtr, AtomicU32, AtomicU64, AtomicUsize},
};

/// Do not alter the current execution context.
pub const CONTEXT_RAW: u8 = 0;
/// Disable preemption while the lock is held.
pub const CONTEXT_PREEMPT: u8 = 1;
/// Save and disable local IRQs while the guard is alive.
pub const CONTEXT_IRQSAVE: u8 = 2;
/// Disable preemption, then save and disable local IRQs.
pub const CONTEXT_PREEMPT_IRQSAVE: u8 = 3;

/// An exclusive spin lock operation.
pub const LOCK_KIND_SPIN: u8 = 0;
/// A spin read-write lock operation.
pub const LOCK_KIND_RW: u8 = 1;
/// A sleepable mutex operation.
pub const LOCK_KIND_MUTEX: u8 = 2;

/// Exclusive ownership.
pub const LOCK_MODE_EXCLUSIVE: u8 = 0;
/// Shared read ownership.
pub const LOCK_MODE_READ: u8 = 1;
/// Exclusive write ownership.
pub const LOCK_MODE_WRITE: u8 = 2;

/// Result of one complete non-sleeping acquisition transaction.
#[derive(Clone, Copy)]
#[repr(C)]
pub struct AcquireResult {
    acquired: u8,
    _reserved: [u8; 7],
    context_state: usize,
}

impl AcquireResult {
    /// Creates a provider result.
    #[doc(hidden)]
    pub const fn new(acquired: bool, context_state: usize) -> Self {
        Self {
            acquired: acquired as u8,
            _reserved: [0; 7],
            context_state,
        }
    }

    pub(crate) const fn acquired(self) -> bool {
        self.acquired != 0
    }

    pub(crate) const fn context_state(self) -> usize {
        self.context_state
    }
}

/// Lock-class storage whose layout is shared with the native provider.
#[repr(C)]
pub struct LockMetadata {
    class_id: AtomicU32,
    class_key: AtomicPtr<Location<'static>>,
}

impl LockMetadata {
    /// Creates metadata for a statically constructed lock class.
    #[track_caller]
    pub const fn new() -> Self {
        Self {
            class_id: AtomicU32::new(0),
            class_key: AtomicPtr::new(
                Location::caller() as *const Location<'static> as *mut Location<'static>
            ),
        }
    }

    /// Returns the class-id storage for the runtime adapter.
    #[doc(hidden)]
    pub const fn class_id(&self) -> &AtomicU32 {
        &self.class_id
    }

    /// Returns the class-key storage for the runtime adapter.
    #[doc(hidden)]
    pub const fn class_key(&self) -> &AtomicPtr<Location<'static>> {
        &self.class_key
    }
}

impl Default for LockMetadata {
    fn default() -> Self {
        Self::new()
    }
}

/// Complete execution-context operations used by standalone guards.
#[ax_crate_interface::def_interface]
pub trait ContextOps {
    /// Enters `context` and returns its opaque restore token.
    fn enter(context: u8) -> usize;

    /// Leaves `context` using the matching token.
    fn exit(context: u8, state: usize);

    /// Leaves a preemption context at the final IRQ-return boundary.
    fn exit_preempt_from_irq_return(state: usize);
}

/// Complete spin-lock acquisition and release operations.
#[ax_crate_interface::def_interface]
pub trait SpinOps {
    fn acquire(
        locked: &AtomicBool,
        metadata: &LockMetadata,
        lock_addr: usize,
        context: u8,
        subclass: u32,
        is_try: bool,
        caller: &'static Location<'static>,
    ) -> AcquireResult;

    fn release(locked: &AtomicBool, lock_addr: usize, context: u8, context_state: usize);

    fn force_release(locked: &AtomicBool, lock_addr: usize, context: u8);

    fn is_locked(locked: &AtomicBool) -> bool;
}

/// Complete spin read-write lock operations.
#[ax_crate_interface::def_interface]
pub trait RwLockOps {
    fn acquire(
        state: &AtomicUsize,
        metadata: &LockMetadata,
        lock_addr: usize,
        context: u8,
        mode: u8,
        is_try: bool,
        caller: &'static Location<'static>,
    ) -> AcquireResult;

    fn release(state: &AtomicUsize, lock_addr: usize, context: u8, context_state: usize, mode: u8);

    fn force_read_decrement(state: &AtomicUsize, lock_addr: usize, context: u8);
}

/// Complete sleepable mutex operations.
#[ax_crate_interface::def_interface]
pub trait MutexOps {
    fn acquire(
        wait_queue: &AtomicPtr<()>,
        owner_id: &AtomicU64,
        metadata: &LockMetadata,
        lock_addr: usize,
        subclass: u32,
        is_try: bool,
        caller: &'static Location<'static>,
    ) -> bool;

    fn release(wait_queue: &AtomicPtr<()>, owner_id: &AtomicU64, lock_addr: usize);

    fn force_release(wait_queue: &AtomicPtr<()>, owner_id: &AtomicU64, lock_addr: usize);

    fn is_owned_by_current(owner_id: &AtomicU64) -> bool;

    fn is_locked(owner_id: &AtomicU64) -> bool;

    fn drop_wait_queue(wait_queue: *mut ());
}

/// Runtime lockdep diagnostics which do not belong to one lock acquisition.
#[ax_crate_interface::def_interface]
pub trait LockdepOps {
    fn set_trace_enabled(enabled: bool);
    fn dump_trace();
}

pub(crate) fn context_enter(context: u8) -> usize {
    #[cfg(all(feature = "host-test", not(target_os = "none")))]
    return crate::host::context_enter(context);
    #[cfg(not(all(feature = "host-test", not(target_os = "none"))))]
    return ax_crate_interface::call_interface!(ContextOps::enter, context);
}

pub(crate) fn context_exit(context: u8, state: usize) {
    #[cfg(all(feature = "host-test", not(target_os = "none")))]
    return crate::host::context_exit(context, state);
    #[cfg(not(all(feature = "host-test", not(target_os = "none"))))]
    ax_crate_interface::call_interface!(ContextOps::exit, context, state);
}

pub(crate) fn preempt_exit_from_irq_return(state: usize) {
    #[cfg(all(feature = "host-test", not(target_os = "none")))]
    return crate::host::context_exit(CONTEXT_PREEMPT, state);
    #[cfg(not(all(feature = "host-test", not(target_os = "none"))))]
    ax_crate_interface::call_interface!(ContextOps::exit_preempt_from_irq_return, state);
}

pub(crate) fn spin_acquire(
    locked: &AtomicBool,
    metadata: &LockMetadata,
    lock_addr: usize,
    context: u8,
    subclass: u32,
    is_try: bool,
    caller: &'static Location<'static>,
) -> AcquireResult {
    #[cfg(all(feature = "host-test", not(target_os = "none")))]
    return crate::host::spin_acquire(
        locked, metadata, lock_addr, context, subclass, is_try, caller,
    );
    #[cfg(not(all(feature = "host-test", not(target_os = "none"))))]
    return ax_crate_interface::call_interface!(
        SpinOps::acquire,
        locked,
        metadata,
        lock_addr,
        context,
        subclass,
        is_try,
        caller
    );
}

pub(crate) fn spin_release(
    locked: &AtomicBool,
    lock_addr: usize,
    context: u8,
    context_state: usize,
) {
    #[cfg(all(feature = "host-test", not(target_os = "none")))]
    return crate::host::spin_release(locked, lock_addr, context, context_state);
    #[cfg(not(all(feature = "host-test", not(target_os = "none"))))]
    ax_crate_interface::call_interface!(
        SpinOps::release,
        locked,
        lock_addr,
        context,
        context_state
    );
}

pub(crate) fn spin_force_release(locked: &AtomicBool, lock_addr: usize, context: u8) {
    #[cfg(all(feature = "host-test", not(target_os = "none")))]
    return crate::host::spin_force_release(locked, lock_addr, context);
    #[cfg(not(all(feature = "host-test", not(target_os = "none"))))]
    ax_crate_interface::call_interface!(SpinOps::force_release, locked, lock_addr, context);
}

pub(crate) fn spin_is_locked(locked: &AtomicBool) -> bool {
    #[cfg(all(feature = "host-test", not(target_os = "none")))]
    return crate::host::spin_is_locked(locked);
    #[cfg(not(all(feature = "host-test", not(target_os = "none"))))]
    return ax_crate_interface::call_interface!(SpinOps::is_locked, locked);
}

pub(crate) fn rwlock_acquire(
    state: &AtomicUsize,
    metadata: &LockMetadata,
    lock_addr: usize,
    context: u8,
    mode: u8,
    is_try: bool,
    caller: &'static Location<'static>,
) -> AcquireResult {
    #[cfg(all(feature = "host-test", not(target_os = "none")))]
    return crate::host::rwlock_acquire(state, metadata, lock_addr, context, mode, is_try, caller);
    #[cfg(not(all(feature = "host-test", not(target_os = "none"))))]
    return ax_crate_interface::call_interface!(
        RwLockOps::acquire,
        state,
        metadata,
        lock_addr,
        context,
        mode,
        is_try,
        caller
    );
}

pub(crate) fn rwlock_release(
    state: &AtomicUsize,
    lock_addr: usize,
    context: u8,
    context_state: usize,
    mode: u8,
) {
    #[cfg(all(feature = "host-test", not(target_os = "none")))]
    return crate::host::rwlock_release(state, lock_addr, context, context_state, mode);
    #[cfg(not(all(feature = "host-test", not(target_os = "none"))))]
    ax_crate_interface::call_interface!(
        RwLockOps::release,
        state,
        lock_addr,
        context,
        context_state,
        mode
    );
}

pub(crate) fn rwlock_force_read_decrement(state: &AtomicUsize, lock_addr: usize, context: u8) {
    #[cfg(all(feature = "host-test", not(target_os = "none")))]
    return crate::host::rwlock_force_read_decrement(state, lock_addr, context);
    #[cfg(not(all(feature = "host-test", not(target_os = "none"))))]
    ax_crate_interface::call_interface!(RwLockOps::force_read_decrement, state, lock_addr, context);
}

#[cfg(feature = "sleep")]
pub(crate) fn mutex_acquire(
    wait_queue: &AtomicPtr<()>,
    owner_id: &AtomicU64,
    metadata: &LockMetadata,
    lock_addr: usize,
    subclass: u32,
    is_try: bool,
    caller: &'static Location<'static>,
) -> bool {
    #[cfg(all(feature = "host-test", not(target_os = "none")))]
    return crate::host::mutex_acquire(
        wait_queue, owner_id, metadata, lock_addr, subclass, is_try, caller,
    );
    #[cfg(not(all(feature = "host-test", not(target_os = "none"))))]
    return ax_crate_interface::call_interface!(
        MutexOps::acquire,
        wait_queue,
        owner_id,
        metadata,
        lock_addr,
        subclass,
        is_try,
        caller
    );
}

#[cfg(feature = "sleep")]
pub(crate) fn mutex_release(wait_queue: &AtomicPtr<()>, owner_id: &AtomicU64, lock_addr: usize) {
    #[cfg(all(feature = "host-test", not(target_os = "none")))]
    return crate::host::mutex_release(wait_queue, owner_id, lock_addr);
    #[cfg(not(all(feature = "host-test", not(target_os = "none"))))]
    ax_crate_interface::call_interface!(MutexOps::release, wait_queue, owner_id, lock_addr);
}

#[cfg(feature = "sleep")]
pub(crate) fn mutex_force_release(
    wait_queue: &AtomicPtr<()>,
    owner_id: &AtomicU64,
    lock_addr: usize,
) {
    #[cfg(all(feature = "host-test", not(target_os = "none")))]
    return crate::host::mutex_force_release(wait_queue, owner_id, lock_addr);
    #[cfg(not(all(feature = "host-test", not(target_os = "none"))))]
    ax_crate_interface::call_interface!(MutexOps::force_release, wait_queue, owner_id, lock_addr);
}

#[cfg(feature = "sleep")]
pub(crate) fn mutex_is_owned_by_current(owner_id: &AtomicU64) -> bool {
    #[cfg(all(feature = "host-test", not(target_os = "none")))]
    return crate::host::mutex_is_owned_by_current(owner_id);
    #[cfg(not(all(feature = "host-test", not(target_os = "none"))))]
    return ax_crate_interface::call_interface!(MutexOps::is_owned_by_current, owner_id);
}

#[cfg(feature = "sleep")]
pub(crate) fn mutex_is_locked(owner_id: &AtomicU64) -> bool {
    #[cfg(all(feature = "host-test", not(target_os = "none")))]
    return crate::host::mutex_is_locked(owner_id);
    #[cfg(not(all(feature = "host-test", not(target_os = "none"))))]
    return ax_crate_interface::call_interface!(MutexOps::is_locked, owner_id);
}

#[cfg(feature = "sleep")]
pub(crate) fn mutex_drop_wait_queue(wait_queue: *mut ()) {
    #[cfg(all(feature = "host-test", not(target_os = "none")))]
    return crate::host::mutex_drop_wait_queue(wait_queue);
    #[cfg(not(all(feature = "host-test", not(target_os = "none"))))]
    ax_crate_interface::call_interface!(MutexOps::drop_wait_queue, wait_queue);
}

pub(crate) fn set_trace_enabled(enabled: bool) {
    #[cfg(all(feature = "host-test", not(target_os = "none")))]
    return crate::host::set_trace_enabled(enabled);
    #[cfg(not(all(feature = "host-test", not(target_os = "none"))))]
    ax_crate_interface::call_interface!(LockdepOps::set_trace_enabled, enabled);
}

pub(crate) fn dump_trace() {
    #[cfg(all(feature = "host-test", not(target_os = "none")))]
    return crate::host::dump_trace();
    #[cfg(not(all(feature = "host-test", not(target_os = "none"))))]
    ax_crate_interface::call_interface!(LockdepOps::dump_trace);
}

#[cfg(test)]
mod tests {
    use core::mem::{align_of, offset_of, size_of};

    use super::*;

    #[test]
    fn acquire_result_has_fixed_bridge_layout() {
        assert_eq!(offset_of!(AcquireResult, acquired), 0);
        assert_eq!(offset_of!(AcquireResult, context_state), 8);
        assert_eq!(align_of::<AcquireResult>(), align_of::<usize>());
        assert_eq!(size_of::<AcquireResult>(), 8 + size_of::<usize>());

        let failed = AcquireResult::new(false, usize::MAX);
        assert!(!failed.acquired());
        assert_eq!(failed.context_state(), usize::MAX);

        let acquired = AcquireResult::new(true, 0x5a5a);
        assert!(acquired.acquired());
        assert_eq!(acquired.context_state(), 0x5a5a);
    }

    #[test]
    fn lock_metadata_has_fixed_bridge_layout() {
        let pointer_offset = offset_of!(LockMetadata, class_key);
        let pointer_alignment = align_of::<AtomicPtr<Location<'static>>>();
        let expected_pointer_offset = size_of::<AtomicU32>().next_multiple_of(pointer_alignment);
        let expected_alignment = align_of::<AtomicU32>().max(pointer_alignment);
        let expected_size = (pointer_offset + size_of::<AtomicPtr<Location<'static>>>())
            .next_multiple_of(expected_alignment);

        assert_eq!(offset_of!(LockMetadata, class_id), 0);
        assert_eq!(pointer_offset, expected_pointer_offset);
        assert_eq!(align_of::<LockMetadata>(), expected_alignment);
        assert_eq!(size_of::<LockMetadata>(), expected_size);
    }
}