rtsched 0.2.0

A no_std runtime scheduler for Cortex-M thread management
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 kwangdo.yi

//! Synchronization primitives built on the scheduler wait queue.

use core::cell::UnsafeCell;
use core::marker::PhantomData;
use core::mem::offset_of;
use core::ops::{Deref, DerefMut};
use core::ptr;
use core::sync::atomic::{AtomicUsize, Ordering};

use crate::arch::platform::{blocking_context_available, request_context_switch};
use crate::critical_section;
use crate::ktimer::{
    CFS_KTIMER, dequeue_ktimerq_to_waitq, earliest_queued_scheduler_expire_at,
    elapsed_ticks_since_current_reload, enqueue_ktimerq_from_waitq, program_wait_ktimer,
    set_thread_scheduler_expire_at, thread_scheduler_expire_at, yield_ktimer,
};
use crate::rbtree::{RBTree, RBTreeNode, RbNode};
use crate::runq::{dequeue_runq_to_waitq, enqueue_runq_from_waitq};
use crate::sched::CURRENT_THREAD_CTX;
use crate::thread::{
    ThreadHandle, ThreadKind, ThreadState, rt_ktimer_entity, sync_entity,
    thread_handle_from_sync_entity,
};
use crate::waitq::{WaitQueueError, remove_wait_thread, wait_entity};

/// Synchronization primitive type encoded in a waiting thread's event tag.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u32)]
pub enum SyncType {
    BinarySemaphore = u32::from_be_bytes(*b"semb"),
    CountingSemaphore = u32::from_be_bytes(*b"semc"),
    Mutex = u32::from_be_bytes(*b"mute"),
    MessageQueueSend = u32::from_be_bytes(*b"mqtx"),
    MessageQueueReceive = u32::from_be_bytes(*b"mqrx"),
}

impl PartialOrd for SyncType {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for SyncType {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.wait_event().cmp(&other.wait_event())
    }
}

impl SyncType {
    /// Return the wait-queue event tag for this synchronization type.
    pub const fn wait_event(self) -> u32 {
        self as u32
    }

    /// Decode a wait-queue event tag into a synchronization type.
    pub const fn from_wait_event(wait_event: u32) -> Option<Self> {
        if wait_event == Self::BinarySemaphore.wait_event() {
            Some(Self::BinarySemaphore)
        } else if wait_event == Self::CountingSemaphore.wait_event() {
            Some(Self::CountingSemaphore)
        } else if wait_event == Self::Mutex.wait_event() {
            Some(Self::Mutex)
        } else if wait_event == Self::MessageQueueSend.wait_event() {
            Some(Self::MessageQueueSend)
        } else if wait_event == Self::MessageQueueReceive.wait_event() {
            Some(Self::MessageQueueReceive)
        } else {
            None
        }
    }
}

const WAIT_FOREVER_TICKS: u64 = u64::MAX;

pub(crate) type WaitTree = RBTree<SyncEntity>;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum MessageWaitResult {
    Pending,
    Notified,
    TimedOut,
    Cancelled,
}

#[repr(C)]
pub(crate) struct SyncEntity {
    deadline_at: u64,
    rb_node: RbNode,
    message_wait_tree: *mut WaitTree,
    message_wait_result: MessageWaitResult,
}

impl SyncEntity {
    pub(crate) const fn new() -> Self {
        Self {
            deadline_at: 0,
            rb_node: RbNode::new(),
            message_wait_tree: ptr::null_mut(),
            message_wait_result: MessageWaitResult::Notified,
        }
    }

    fn set_deadline_at(&mut self, deadline_at: u64) {
        self.deadline_at = deadline_at;
    }

    #[allow(dead_code)]
    fn deadline_at(&self) -> u64 {
        self.deadline_at
    }

    fn reset_links(&mut self) {
        self.rb_node.reset_links();
    }
}

unsafe impl RBTreeNode for SyncEntity {
    fn node(entity: *mut Self) -> *mut RbNode {
        if entity.is_null() {
            ptr::null_mut()
        } else {
            unsafe { ptr::addr_of_mut!((*entity).rb_node) }
        }
    }

    fn entity_of(node: *mut RbNode) -> *mut Self {
        if node.is_null() {
            ptr::null_mut()
        } else {
            unsafe {
                (node as *mut u8)
                    .sub(offset_of!(SyncEntity, rb_node))
                    .cast::<SyncEntity>()
            }
        }
    }

    fn entity_of_const(node: *const RbNode) -> *const Self {
        if node.is_null() {
            ptr::null()
        } else {
            unsafe {
                (node as *const u8)
                    .sub(offset_of!(SyncEntity, rb_node))
                    .cast::<SyncEntity>()
            }
        }
    }

    unsafe fn cmp(a: *const Self, b: *const Self) -> core::cmp::Ordering {
        unsafe {
            match (*a).deadline_at.cmp(&(*b).deadline_at) {
                core::cmp::Ordering::Equal => (a as usize).cmp(&(b as usize)),
                other => other,
            }
        }
    }
}

trait SyncWaitObject {
    const SYNC_TYPE: SyncType;

    fn waiters_mut(&mut self) -> &mut WaitTree;
}

/// Error returned by semaphore operations.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SemaphoreError {
    /// The semaphore is not currently available for a non-blocking take.
    WouldBlock,
    /// The semaphore is already available and cannot hold another token.
    Full,
    /// A blocking take was requested before the scheduler selected a thread.
    NoCurrentThread,
    /// Waiting requires a running, non-idle thread with context switching available.
    InvalidContext,
    /// The scheduler could not move a thread between wait and ready queues.
    WaitQueue(WaitQueueError),
}

impl From<WaitQueueError> for SemaphoreError {
    fn from(error: WaitQueueError) -> Self {
        Self::WaitQueue(error)
    }
}

struct BinarySemaphoreState {
    available: AtomicUsize,
    waiters: WaitTree,
}

impl BinarySemaphoreState {
    const fn new(available: bool) -> Self {
        Self {
            available: AtomicUsize::new(available as usize),
            waiters: WaitTree::new(),
        }
    }
}

impl SyncWaitObject for BinarySemaphoreState {
    const SYNC_TYPE: SyncType = SyncType::BinarySemaphore;

    fn waiters_mut(&mut self) -> &mut WaitTree {
        &mut self.waiters
    }
}

/// A no-heap binary semaphore.
///
/// The semaphore stores a single token. `try_take` consumes that token when it
/// is available. `take` blocks the current scheduler thread when the token is
/// unavailable, and `give` either wakes the blocked waiter with the earliest
/// scheduler deadline or restores the token for a future taker.
pub struct BinarySemaphore {
    state: UnsafeCell<BinarySemaphoreState>,
}

unsafe impl Sync for BinarySemaphore {}

impl BinarySemaphore {
    /// Create a binary semaphore.
    ///
    /// Pass `true` to create it with an available token, or `false` to require
    /// a later `give` before the first take can complete.
    pub const fn new(available: bool) -> Self {
        Self {
            state: UnsafeCell::new(BinarySemaphoreState::new(available)),
        }
    }

    /// Create a binary semaphore with an available token.
    pub const fn available() -> Self {
        Self::new(true)
    }

    /// Create a binary semaphore with no available token.
    pub const fn empty() -> Self {
        Self::new(false)
    }

    /// Return whether the semaphore currently has a token available.
    pub fn is_available(&self) -> bool {
        unsafe { load_word(&(*self.state.get()).available) != 0 }
    }

    /// Try to take the semaphore without blocking.
    pub fn try_take(&self) -> Result<(), SemaphoreError> {
        unsafe {
            if decrement_word_if_positive(&(*self.state.get()).available) {
                Ok(())
            } else {
                Err(SemaphoreError::WouldBlock)
            }
        }
    }

    /// Take the semaphore, blocking the current scheduler thread if needed.
    ///
    /// If unavailable, returns [`SemaphoreError::InvalidContext`] unless called
    /// by a running, non-idle thread with PendSV unmasked. Do not wait from an
    /// interrupt handler or an outer critical section. Immediate acquisition
    /// succeeds even when blocking is unavailable. If waiting is required with
    /// no selected thread, returns [`SemaphoreError::NoCurrentThread`]. Native
    /// host builds cannot block scheduler threads.
    pub fn take(&self) -> Result<(), SemaphoreError> {
        self.take_with_context(blocking_context_available())
    }

    fn take_with_context(&self, can_block: bool) -> Result<(), SemaphoreError> {
        if self.try_take().is_ok() {
            return Ok(());
        }

        critical_section(|| unsafe {
            let state = &mut *self.state.get();
            if decrement_word_if_positive(&state.available) {
                return Ok(());
            }

            let Some(current_thread) = current_thread_handle() else {
                return Err(SemaphoreError::NoCurrentThread);
            };
            if !can_block
                || (*current_thread.as_ptr()).state != ThreadState::Running
                || (*current_thread.as_ptr()).is_idle()
            {
                return Err(SemaphoreError::InvalidContext);
            }

            block_current_thread_on(state, current_thread)?;
            Ok(())
        })
    }

    /// Give the semaphore.
    ///
    /// If one or more threads are blocked in `take`, the earliest-deadline
    /// waiter is made ready and receives the token directly. Otherwise this
    /// restores the token for a future taker, unless the semaphore is already
    /// full.
    pub fn give(&self) -> Result<(), SemaphoreError> {
        critical_section(|| unsafe {
            let state = &mut *self.state.get();

            if let Some(waiter) = pop_waiting_thread(&mut state.waiters) {
                wake_waiter(waiter)?;
                request_context_switch();
                return Ok(());
            }

            if increment_word_if_below(&state.available, 1) {
                Ok(())
            } else {
                Err(SemaphoreError::Full)
            }
        })
    }
}

struct CountingSemaphoreState {
    count: AtomicUsize,
    max_count: AtomicUsize,
    waiters: WaitTree,
}

impl CountingSemaphoreState {
    const fn new(max_count: u32, initial_count: u32) -> Self {
        Self {
            count: AtomicUsize::new(initial_count as usize),
            max_count: AtomicUsize::new(max_count as usize),
            waiters: WaitTree::new(),
        }
    }
}

impl SyncWaitObject for CountingSemaphoreState {
    const SYNC_TYPE: SyncType = SyncType::CountingSemaphore;

    fn waiters_mut(&mut self) -> &mut WaitTree {
        &mut self.waiters
    }
}

/// A no-heap counting semaphore.
///
/// The semaphore stores up to `max_count` tokens. `try_take` consumes one token
/// when available. `take` blocks the current scheduler thread when no tokens
/// are available, and `give` either wakes the blocked waiter with the earliest
/// scheduler deadline or stores one token for a future taker.
pub struct CountingSemaphore {
    state: UnsafeCell<CountingSemaphoreState>,
}

unsafe impl Sync for CountingSemaphore {}

impl CountingSemaphore {
    /// Create a counting semaphore.
    ///
    /// `max_count` must be non-zero and `initial_count` must not exceed
    /// `max_count`.
    pub const fn new(max_count: u32, initial_count: u32) -> Self {
        assert!(
            max_count != 0,
            "counting semaphore max_count must be non-zero"
        );
        assert!(
            initial_count <= max_count,
            "counting semaphore initial_count must not exceed max_count"
        );

        Self {
            state: UnsafeCell::new(CountingSemaphoreState::new(max_count, initial_count)),
        }
    }

    /// Create a counting semaphore with no available tokens.
    pub const fn empty(max_count: u32) -> Self {
        Self::new(max_count, 0)
    }

    /// Create a counting semaphore with all tokens available.
    pub const fn full(max_count: u32) -> Self {
        Self::new(max_count, max_count)
    }

    /// Return the current number of available tokens.
    pub fn count(&self) -> u32 {
        unsafe { load_word(&(*self.state.get()).count) as u32 }
    }

    /// Return the maximum number of tokens this semaphore can store.
    pub fn max_count(&self) -> u32 {
        unsafe { load_word(&(*self.state.get()).max_count) as u32 }
    }

    /// Try to take one token without blocking.
    pub fn try_take(&self) -> Result<(), SemaphoreError> {
        unsafe {
            if decrement_word_if_positive(&(*self.state.get()).count) {
                Ok(())
            } else {
                Err(SemaphoreError::WouldBlock)
            }
        }
    }

    /// Take one token, blocking the current scheduler thread if needed.
    ///
    /// If unavailable, returns [`SemaphoreError::InvalidContext`] unless called
    /// by a running, non-idle thread with PendSV unmasked. Do not wait from an
    /// interrupt handler or an outer critical section. Immediate acquisition
    /// succeeds even when blocking is unavailable. If waiting is required with
    /// no selected thread, returns [`SemaphoreError::NoCurrentThread`]. Native
    /// host builds cannot block scheduler threads.
    pub fn take(&self) -> Result<(), SemaphoreError> {
        self.take_with_context(blocking_context_available())
    }

    fn take_with_context(&self, can_block: bool) -> Result<(), SemaphoreError> {
        if self.try_take().is_ok() {
            return Ok(());
        }

        critical_section(|| unsafe {
            let state = &mut *self.state.get();
            if decrement_word_if_positive(&state.count) {
                return Ok(());
            }

            let Some(current_thread) = current_thread_handle() else {
                return Err(SemaphoreError::NoCurrentThread);
            };
            if !can_block
                || (*current_thread.as_ptr()).state != ThreadState::Running
                || (*current_thread.as_ptr()).is_idle()
            {
                return Err(SemaphoreError::InvalidContext);
            }

            block_current_thread_on(state, current_thread)?;
            Ok(())
        })
    }

    /// Give one token.
    ///
    /// If one or more threads are blocked in `take`, the earliest-deadline
    /// waiter is made ready and receives the token directly. Otherwise the
    /// token is stored unless the semaphore is already full.
    pub fn give(&self) -> Result<(), SemaphoreError> {
        critical_section(|| unsafe {
            let state = &mut *self.state.get();

            if let Some(waiter) = pop_waiting_thread(&mut state.waiters) {
                wake_waiter(waiter)?;
                request_context_switch();
                return Ok(());
            }

            if increment_word_if_below(&state.count, load_word(&state.max_count)) {
                Ok(())
            } else {
                Err(SemaphoreError::Full)
            }
        })
    }
}

/// Error returned by mutex operations.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MutexError {
    /// The mutex is owned by another thread and cannot be taken without blocking.
    WouldBlock,
    /// The current thread already owns this non-recursive mutex.
    WouldDeadlock,
    /// A lock was requested before the scheduler selected a thread.
    NoCurrentThread,
    /// Waiting requires a running, non-idle thread with context switching available.
    InvalidContext,
    /// The scheduler could not move a thread between wait and ready queues.
    WaitQueue(WaitQueueError),
}

impl From<WaitQueueError> for MutexError {
    fn from(error: WaitQueueError) -> Self {
        Self::WaitQueue(error)
    }
}

struct MutexState {
    owner: AtomicUsize,
    waiters: WaitTree,
    owner_original_deadline_at: u64,
    owner_boosted: bool,
}

impl MutexState {
    const fn new() -> Self {
        Self {
            owner: AtomicUsize::new(0),
            waiters: WaitTree::new(),
            owner_original_deadline_at: 0,
            owner_boosted: false,
        }
    }
}

impl SyncWaitObject for MutexState {
    const SYNC_TYPE: SyncType = SyncType::Mutex;

    fn waiters_mut(&mut self) -> &mut WaitTree {
        &mut self.waiters
    }
}

/// A no-heap, non-recursive scheduler mutex protecting a value of type `T`.
///
/// The mutex is owned by a scheduler thread while a [`MutexGuard`] exists. If
/// another thread calls `lock`, it is moved to the wait queue and the guard
/// returned to it once the current owner drops its guard and it has the
/// earliest scheduler deadline among the mutex waiters.
pub struct Mutex<T> {
    state: UnsafeCell<MutexState>,
    data: UnsafeCell<T>,
}

unsafe impl<T: Send> Sync for Mutex<T> {}

impl<T> Mutex<T> {
    /// Create a mutex containing `value`.
    pub const fn new(value: T) -> Self {
        Self {
            state: UnsafeCell::new(MutexState::new()),
            data: UnsafeCell::new(value),
        }
    }

    /// Consume the mutex and return its inner value.
    pub fn into_inner(self) -> T {
        self.data.into_inner()
    }

    /// Return a mutable reference to the inner value.
    ///
    /// This requires unique access to the mutex, so no scheduler locking is
    /// needed.
    pub fn get_mut(&mut self) -> &mut T {
        self.data.get_mut()
    }

    /// Return whether the mutex is currently owned by a thread.
    pub fn is_locked(&self) -> bool {
        unsafe { load_word(&(*self.state.get()).owner) != 0 }
    }

    /// Try to lock the mutex without blocking.
    pub fn try_lock(&self) -> Result<MutexGuard<'_, T>, MutexError> {
        critical_section(|| unsafe {
            let current_thread = current_thread_handle().ok_or(MutexError::NoCurrentThread)?;
            let state = &mut *self.state.get();
            let current_owner = owner_token(current_thread);

            match compare_exchange_word(&state.owner, 0, current_owner) {
                Ok(_) => Ok(MutexGuard::new(self)),
                Err(owner) if owner == current_owner => Err(MutexError::WouldDeadlock),
                Err(_) => Err(MutexError::WouldBlock),
            }
        })
    }

    /// Lock the mutex, blocking the current scheduler thread if needed.
    ///
    /// If owned by another thread, returns [`MutexError::InvalidContext`]
    /// unless called by a running, non-idle thread with PendSV unmasked. Do not
    /// wait from an interrupt handler or an outer critical section. An unlocked
    /// mutex can still be acquired when blocking is unavailable, provided a
    /// scheduler thread is selected. Otherwise returns
    /// [`MutexError::NoCurrentThread`]. Recursive locking returns
    /// [`MutexError::WouldDeadlock`]. Native host builds cannot block scheduler
    /// threads.
    pub fn lock(&self) -> Result<MutexGuard<'_, T>, MutexError> {
        self.lock_with_context(blocking_context_available())
    }

    fn lock_with_context(&self, can_block: bool) -> Result<MutexGuard<'_, T>, MutexError> {
        critical_section(|| unsafe {
            let current_thread = current_thread_handle().ok_or(MutexError::NoCurrentThread)?;
            let state = &mut *self.state.get();
            let current_owner = owner_token(current_thread);

            match compare_exchange_word(&state.owner, 0, current_owner) {
                Ok(_) => {}
                Err(owner) if owner == current_owner => {
                    return Err(MutexError::WouldDeadlock);
                }
                Err(owner) => {
                    if !can_block
                        || (*current_thread.as_ptr()).state != ThreadState::Running
                        || (*current_thread.as_ptr()).is_idle()
                    {
                        return Err(MutexError::InvalidContext);
                    }
                    let waiter_deadline_at = block_current_thread_on(state, current_thread)?;
                    boost_owner_deadline(state, owner, current_thread, waiter_deadline_at);
                }
            }

            Ok(MutexGuard::new(self))
        })
    }

    fn unlock_guard(&self) -> Result<(), MutexError> {
        critical_section(|| unsafe {
            let current_owner = current_thread_handle().map(owner_token).unwrap_or_default();
            let state = &mut *self.state.get();
            let observed_owner = load_word(&state.owner);

            debug_assert_eq!(
                observed_owner, current_owner,
                "mutex guard must be dropped by its owning thread"
            );

            if observed_owner != current_owner {
                return Ok(());
            }

            restore_owner_deadline(state, current_owner);

            if let Some(waiter) = pop_waiting_thread(&mut state.waiters) {
                let _ = compare_exchange_word(&state.owner, current_owner, owner_token(waiter));
                wake_waiter(waiter)?;
                request_context_switch();
            } else {
                let _ = compare_exchange_word(&state.owner, current_owner, 0);
            }

            Ok(())
        })
    }
}

/// RAII guard returned by [`Mutex::lock`] and [`Mutex::try_lock`].
///
/// Dropping the guard unlocks the mutex and wakes the earliest-deadline waiting
/// thread, if one exists.
pub struct MutexGuard<'a, T> {
    mutex: &'a Mutex<T>,
    _not_send: PhantomData<*mut ()>,
}

impl<'a, T> MutexGuard<'a, T> {
    fn new(mutex: &'a Mutex<T>) -> Self {
        Self {
            mutex,
            _not_send: PhantomData,
        }
    }
}

impl<T> Deref for MutexGuard<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        unsafe { &*self.mutex.data.get() }
    }
}

impl<T> DerefMut for MutexGuard<'_, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { &mut *self.mutex.data.get() }
    }
}

impl<T> Drop for MutexGuard<'_, T> {
    fn drop(&mut self) {
        let _ = self.mutex.unlock_guard();
    }
}

fn load_word(word: &AtomicUsize) -> usize {
    word.load(Ordering::Acquire)
}

fn compare_exchange_word(word: &AtomicUsize, current: usize, new: usize) -> Result<usize, usize> {
    word.compare_exchange(current, new, Ordering::AcqRel, Ordering::Acquire)
}

fn decrement_word_if_positive(word: &AtomicUsize) -> bool {
    word.fetch_update(Ordering::AcqRel, Ordering::Acquire, |observed| {
        observed.checked_sub(1)
    })
    .is_ok()
}

fn increment_word_if_below(word: &AtomicUsize, max: usize) -> bool {
    word.fetch_update(Ordering::AcqRel, Ordering::Acquire, |observed| {
        if observed < max {
            Some(observed + 1)
        } else {
            None
        }
    })
    .is_ok()
}

fn owner_token(thread: ThreadHandle) -> usize {
    let token = thread.as_ptr() as usize;
    debug_assert_ne!(token, 0, "thread owner token must be non-zero");
    token
}

unsafe fn thread_from_owner_token(token: usize) -> Option<ThreadHandle> {
    if token == 0 {
        None
    } else {
        Some(unsafe { ThreadHandle::from_thread_ctx(token as *mut _) })
    }
}

unsafe fn boost_owner_deadline(
    state: &mut MutexState,
    owner: usize,
    waiter: ThreadHandle,
    waiter_deadline_at: u64,
) {
    let Some(owner) = (unsafe { thread_from_owner_token(owner) }) else {
        return;
    };

    let boost_deadline_at = unsafe {
        if (*owner.as_ptr()).is_cfs() && (*waiter.as_ptr()).is_cfs() {
            return;
        }

        waiter_deadline_at.min(earliest_queued_scheduler_expire_at())
    };

    let owner_deadline_at = unsafe { thread_scheduler_expire_at(owner) };
    if boost_deadline_at >= owner_deadline_at {
        return;
    }

    if !state.owner_boosted {
        state.owner_original_deadline_at = owner_deadline_at;
        state.owner_boosted = true;
    }

    unsafe {
        set_thread_scheduler_expire_at(owner, boost_deadline_at);
    }
}

unsafe fn restore_owner_deadline(state: &mut MutexState, owner: usize) {
    if !state.owner_boosted {
        return;
    }

    if let Some(owner) = unsafe { thread_from_owner_token(owner) } {
        unsafe {
            set_thread_scheduler_expire_at(owner, state.owner_original_deadline_at);
        }
    }

    state.owner_original_deadline_at = 0;
    state.owner_boosted = false;
}

pub(crate) unsafe fn current_thread_handle() -> Option<ThreadHandle> {
    unsafe {
        if CURRENT_THREAD_CTX.is_null() {
            None
        } else {
            Some(ThreadHandle::from_thread_ctx(CURRENT_THREAD_CTX))
        }
    }
}

pub(crate) unsafe fn block_current_thread(
    thread: ThreadHandle,
    sync_type: SyncType,
) -> Result<u64, WaitQueueError> {
    unsafe { block_current_thread_until(thread, sync_type, WAIT_FOREVER_TICKS) }
}

pub(crate) unsafe fn block_current_thread_until(
    thread: ThreadHandle,
    sync_type: SyncType,
    wake_at: u64,
) -> Result<u64, WaitQueueError> {
    unsafe {
        let current_thread_ctx = CURRENT_THREAD_CTX;

        debug_assert_eq!(
            thread.as_ptr(),
            current_thread_ctx,
            "only the current thread can block on a sync primitive"
        );

        let elapsed = elapsed_ticks_since_current_reload();
        let current_ktimer = match (*thread.as_ptr()).kind {
            ThreadKind::Cfs => ptr::addr_of_mut!(CFS_KTIMER.entity),
            ThreadKind::Rt => rt_ktimer_entity(thread),
            ThreadKind::Idle => return Err(WaitQueueError::NotFound),
        };

        let deadline_at = if current_ktimer.is_null() {
            WAIT_FOREVER_TICKS
        } else {
            (*current_ktimer).expire_at()
        };

        let _ = yield_ktimer(current_ktimer, elapsed, false);

        let wait_entity = wait_entity(thread);
        (*wait_entity).wake_at = wake_at;
        (*wait_entity).waitevt = Some(sync_type);

        match (*thread.as_ptr()).kind {
            ThreadKind::Cfs => dequeue_runq_to_waitq(thread)?,
            ThreadKind::Rt => dequeue_ktimerq_to_waitq(thread)?,
            ThreadKind::Idle => return Err(WaitQueueError::NotFound),
        }

        Ok(deadline_at)
    }
}

unsafe fn block_current_thread_on<T: SyncWaitObject>(
    object: &mut T,
    thread: ThreadHandle,
) -> Result<u64, WaitQueueError> {
    unsafe {
        let deadline_at = block_current_thread(thread, T::SYNC_TYPE)?;
        insert_sync_waiter(object.waiters_mut(), thread, deadline_at);
        request_context_switch();

        Ok(deadline_at)
    }
}

// Call with serialized scheduler access, a detached SyncEntity, and a thread
// already moved into the global blocked-thread index.
pub(crate) unsafe fn insert_sync_waiter(
    waiters: &mut WaitTree,
    thread: ThreadHandle,
    deadline_at: u64,
) {
    unsafe {
        let entity = sync_entity(thread);
        (*entity).set_deadline_at(deadline_at);
        (*entity).reset_links();
        waiters.insert(entity);
    }
}

// Message waits have two independent intrusive memberships. Remember their
// object tree so timer expiry can unlink it before making the thread runnable.
// The queue remains borrowed by the suspended send/receive call while linked.
pub(crate) unsafe fn insert_message_waiter(
    waiters: &mut WaitTree,
    thread: ThreadHandle,
    deadline_at: u64,
) {
    unsafe {
        let entity = sync_entity(thread);
        debug_assert!((*entity).message_wait_tree.is_null());
        insert_sync_waiter(waiters, thread, deadline_at);
        (*entity).message_wait_tree = waiters;
        (*entity).message_wait_result = MessageWaitResult::Pending;
    }
}

pub(crate) unsafe fn message_wait_tree(thread: ThreadHandle) -> *mut WaitTree {
    unsafe { (*sync_entity(thread)).message_wait_tree }
}

// Caller serializes scheduler access. This only unlinks the object tree; the
// caller must also remove/pop the global wait entry and restore runnable state.
pub(crate) unsafe fn finish_message_wait(thread: ThreadHandle, result: MessageWaitResult) -> bool {
    unsafe {
        let entity = sync_entity(thread);
        let tree = (*entity).message_wait_tree;
        if tree.is_null() {
            return false;
        }
        (*tree).remove(entity);
        (*entity).message_wait_tree = ptr::null_mut();
        (*entity).message_wait_result = result;
        true
    }
}

pub(crate) unsafe fn take_message_wait_result(thread: ThreadHandle) -> MessageWaitResult {
    unsafe {
        let entity = sync_entity(thread);
        debug_assert!((*entity).message_wait_tree.is_null());
        core::mem::replace(
            &mut (*entity).message_wait_result,
            MessageWaitResult::Notified,
        )
    }
}

pub(crate) unsafe fn pop_waiting_thread(waiters: &mut WaitTree) -> Option<ThreadHandle> {
    unsafe {
        let sync_entity = waiters.pop_first()?;
        let thread = thread_handle_from_sync_entity(sync_entity as *mut SyncEntity);
        let state = (*thread.as_ptr()).state;

        debug_assert!(state.is_blocked(), "sync waiter must remain blocked");
        if !state.is_blocked() {
            return None;
        }

        Some(thread)
    }
}

pub(crate) unsafe fn wake_waiter(thread: ThreadHandle) -> Result<(), WaitQueueError> {
    unsafe {
        if (*thread.as_ptr()).is_cfs() {
            remove_wait_thread(thread);
            crate::diagnostics::trace::record_wakeup(thread.as_ptr());
            enqueue_runq_from_waitq(thread);
            program_wait_ktimer();
        } else if (*thread.as_ptr()).is_rt() {
            enqueue_ktimerq_from_waitq(thread)?;
        }

        Ok(())
    }
}

#[cfg(feature = "host")]
#[path = "../tests/support/sync.rs"]
pub mod test_support;