freertos-in-rust 0.3.0

Pure-Rust no_std FreeRTOS kernel translation with safe Rust APIs
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
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
/*
 * FreeRTOS Kernel <DEVELOPMENT BRANCH>
 * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * SPDX-License-Identifier: MIT
 *
 * [AMENDMENT] This is the Cortex-A9 port for FreeRTOS-in-Rust.
 * Ported from portable/GCC/ARM_CA9/port.c and portASM.S
 *
 * This port is for ARM Cortex-A9 (ARMv7-A) application processors.
 * It uses:
 * - GIC (Generic Interrupt Controller) for interrupt priority masking
 * - SWI (Software Interrupt) for context switching
 * - Platform-specific timer for tick interrupts (user provides configSETUP_TICK_INTERRUPT)
 *
 * Key differences from Cortex-M:
 * - Runs in System mode (privileged, uses user-mode registers)
 * - Uses GIC priority masking instead of NVIC BASEPRI
 * - Context switch via SWI instead of PendSV
 * - Multiple ARM processor modes (SYS, SVC, IRQ, etc.)
 */

//! ARM Cortex-A9 Port Implementation
//!
//! This port provides hardware-specific implementations for ARM Cortex-A9:
//! - Critical sections using GIC priority masking
//! - Context switching via SWI exception
//! - First task start via vPortRestoreTaskContext
//! - Tick timer is platform-specific (user-provided)
//!
//! ## Usage
//!
//! Enable with `--features port-cortex-a9` and compile for `armv7a-none-eabi`.
//!
//! ## Platform Configuration
//!
//! The current implementation uses the QEMU vexpress-a9 GIC addresses and
//! priority layout below. Supporting another Cortex-A9 platform requires a
//! proper configuration interface rather than undeclared Cargo features.
//!
//! ## Vector Table
//!
//! The application must install FreeRTOS_SWI_Handler and FreeRTOS_IRQ_Handler
//! in the ARM vector table for SWI and IRQ exceptions.

use core::arch::global_asm;
use core::ffi::c_void;

use crate::config::*;
use crate::types::*;

// =============================================================================
// Port Constants
// =============================================================================

/// Stack growth direction: -1 for descending (ARM uses descending stack)
pub const portSTACK_GROWTH: BaseType_t = -1;

/// Byte alignment requirement for stack
pub const portBYTE_ALIGNMENT: usize = 8;

/// Architecture name string for this port
pub const portARCH_NAME: &str = "ARM Cortex-A9";

// =============================================================================
// ARM Processor Mode Constants
// =============================================================================

/// System mode - privileged, uses user-mode registers
const SYS_MODE: u32 = 0x1F;

/// Supervisor mode
const SVC_MODE: u32 = 0x13;

/// IRQ mode
const IRQ_MODE: u32 = 0x12;

/// Initial SPSR value: System mode, ARM state, IRQ+FIQ enabled
const portINITIAL_SPSR: StackType_t = SYS_MODE as StackType_t;

/// Thumb mode bit in SPSR
const portTHUMB_MODE_BIT: StackType_t = 0x20;

/// Thumb mode address indicator (LSB set)
const portTHUMB_MODE_ADDRESS: u32 = 0x01;

/// No critical nesting value
const portNO_CRITICAL_NESTING: u32 = 0;

/// No floating point context flag
const portNO_FLOATING_POINT_CONTEXT: StackType_t = 0;

/// APSR mode bits mask
const portAPSR_MODE_BITS_MASK: u32 = 0x1F;

/// User mode APSR value
const portAPSR_USER_MODE: u32 = 0x10;

/// Unmask all interrupt priorities
const portUNMASK_VALUE: u32 = 0xFF;

// =============================================================================
// GIC Configuration
// =============================================================================

/// GIC CPU interface register offsets
const portICCPMR_PRIORITY_MASK_OFFSET: usize = 0x04;
const portICCIAR_INTERRUPT_ACKNOWLEDGE_OFFSET: usize = 0x0C;
const portICCEOIR_END_OF_INTERRUPT_OFFSET: usize = 0x10;
const portICCBPR_BINARY_POINT_OFFSET: usize = 0x08;
const portICCRPR_RUNNING_PRIORITY_OFFSET: usize = 0x14;

/// Number of unique interrupt priorities implemented by QEMU vexpress-a9.
pub const configUNIQUE_INTERRUPT_PRIORITIES: u32 = 32;

/// Priority shift based on number of implemented priority bits
const portPRIORITY_SHIFT: u32 = 3; // 32 priorities = 5 bits, shift by 3

/// Binary point maximum value
const portMAX_BINARY_POINT_VALUE: u32 = 2;

/// Lowest interrupt priority
pub const portLOWEST_INTERRUPT_PRIORITY: u32 = configUNIQUE_INTERRUPT_PRIORITIES - 1;

/// Lowest usable interrupt priority (one above lowest)
pub const portLOWEST_USABLE_INTERRUPT_PRIORITY: u32 = portLOWEST_INTERRUPT_PRIORITY - 1;

// =============================================================================
// GIC Address Calculation
// =============================================================================

/// GIC base address for QEMU vexpress-a9.
pub const configINTERRUPT_CONTROLLER_BASE_ADDRESS: usize = 0x1E00_0000;

/// GIC CPU interface offset from the QEMU vexpress-a9 base.
pub const configINTERRUPT_CONTROLLER_CPU_INTERFACE_OFFSET: usize = 0x100;

/// Maximum API call interrupt priority (must be > UNIQUE_PRIORITIES / 2)
/// Interrupts at this priority or lower can call FreeRTOS FromISR APIs
pub const configMAX_API_CALL_INTERRUPT_PRIORITY: u32 = 18;

/// Computed GIC CPU interface address
const GIC_CPU_INTERFACE_ADDRESS: usize =
    configINTERRUPT_CONTROLLER_BASE_ADDRESS + configINTERRUPT_CONTROLLER_CPU_INTERFACE_OFFSET;

/// GIC Priority Mask Register address
const ICCPMR_ADDRESS: usize = GIC_CPU_INTERFACE_ADDRESS + portICCPMR_PRIORITY_MASK_OFFSET;

/// GIC Interrupt Acknowledge Register address
const ICCIAR_ADDRESS: usize = GIC_CPU_INTERFACE_ADDRESS + portICCIAR_INTERRUPT_ACKNOWLEDGE_OFFSET;

/// GIC End of Interrupt Register address
const ICCEOIR_ADDRESS: usize = GIC_CPU_INTERFACE_ADDRESS + portICCEOIR_END_OF_INTERRUPT_OFFSET;

/// GIC Binary Point Register address
const ICCBPR_ADDRESS: usize = GIC_CPU_INTERFACE_ADDRESS + portICCBPR_BINARY_POINT_OFFSET;

/// GIC Running Priority Register address
const ICCRPR_ADDRESS: usize = GIC_CPU_INTERFACE_ADDRESS + portICCRPR_RUNNING_PRIORITY_OFFSET;

/// Maximum API priority mask value (shifted)
const ulMaxAPIPriorityMask: u32 = configMAX_API_CALL_INTERRUPT_PRIORITY << portPRIORITY_SHIFT;

// =============================================================================
// Port State Variables
// =============================================================================

/// Critical section nesting counter.
/// Initialized to a non-zero value to ensure interrupts don't get unmasked
/// before the scheduler starts. Set to 0 when first task starts.
#[no_mangle]
pub static mut ulCriticalNesting: u32 = 9999;

/// FPU context flag for current task.
/// 0 = no FPU context, non-zero = task has FPU context
#[no_mangle]
pub static mut ulPortTaskHasFPUContext: u32 = pdFALSE as u32;

/// Yield required flag. Set to pdTRUE in ISR to request context switch.
#[no_mangle]
pub static mut ulPortYieldRequired: u32 = pdFALSE as u32;

/// Interrupt nesting depth. Context switch only allowed when this is 0.
#[no_mangle]
pub static mut ulPortInterruptNesting: u32 = 0;

// GIC register addresses for assembly code
#[no_mangle]
pub static ulICCIARAddress: u32 = ICCIAR_ADDRESS as u32;
#[no_mangle]
pub static ulICCEOIRAddress: u32 = ICCEOIR_ADDRESS as u32;
#[no_mangle]
pub static ulICCPMRAddress: u32 = ICCPMR_ADDRESS as u32;
#[no_mangle]
pub static ulMaxAPIPriorityMaskConst: u32 = ulMaxAPIPriorityMask;

// =============================================================================
// Critical Section Management
// =============================================================================

/// Enter a critical section by masking interrupts via GIC priority register
#[inline(always)]
pub fn portENTER_CRITICAL() {
    vPortEnterCritical();
}

/// Exit a critical section, potentially unmasking interrupts
#[inline(always)]
pub fn portEXIT_CRITICAL() {
    vPortExitCritical();
}

/// Enter critical section implementation
#[no_mangle]
pub extern "C" fn vPortEnterCritical() {
    // Mask interrupts up to max syscall priority
    ulPortSetInterruptMask();

    // Increment nesting count
    unsafe {
        ulCriticalNesting += 1;

        // Assert we're not in interrupt context (only on first entry)
        if ulCriticalNesting == 1 {
            configASSERT(ulPortInterruptNesting == 0);
        }
    }
}

/// Exit critical section implementation
#[no_mangle]
pub extern "C" fn vPortExitCritical() {
    unsafe {
        if ulCriticalNesting > portNO_CRITICAL_NESTING {
            ulCriticalNesting -= 1;

            if ulCriticalNesting == portNO_CRITICAL_NESTING {
                // Unmask all interrupt priorities
                portCLEAR_INTERRUPT_MASK();
            }
        }
    }
}

/// Disable interrupts by setting GIC priority mask
#[inline(always)]
pub fn portDISABLE_INTERRUPTS() -> UBaseType_t {
    ulPortSetInterruptMask()
}

/// Enable interrupts by clearing GIC priority mask
#[inline(always)]
pub fn portENABLE_INTERRUPTS() {
    vPortClearInterruptMask(0);
}

/// Set interrupt mask and return previous state
#[no_mangle]
pub extern "C" fn ulPortSetInterruptMask() -> u32 {
    let ulReturn: u32;

    unsafe {
        // Disable CPU IRQ while modifying ICCPMR
        core::arch::asm!("cpsid i", options(nomem, nostack));

        let iccpmr = ICCPMR_ADDRESS as *mut u32;
        let current = core::ptr::read_volatile(iccpmr);

        if current == ulMaxAPIPriorityMask {
            // Already masked
            ulReturn = pdTRUE as u32;
        } else {
            ulReturn = pdFALSE as u32;
            core::ptr::write_volatile(iccpmr, ulMaxAPIPriorityMask);
            core::arch::asm!("dsb", "isb", options(nomem, nostack));
        }

        // Re-enable CPU IRQ
        core::arch::asm!("cpsie i", options(nomem, nostack));
    }

    ulReturn
}

/// Clear interrupt mask (restore previous state)
#[no_mangle]
pub extern "C" fn vPortClearInterruptMask(ulNewMaskValue: u32) {
    if ulNewMaskValue == pdFALSE as u32 {
        portCLEAR_INTERRUPT_MASK();
    }
}

/// Clear interrupt mask macro implementation
#[inline(always)]
fn portCLEAR_INTERRUPT_MASK() {
    unsafe {
        core::arch::asm!("cpsid i", options(nomem, nostack));

        let iccpmr = ICCPMR_ADDRESS as *mut u32;
        core::ptr::write_volatile(iccpmr, portUNMASK_VALUE);

        core::arch::asm!("dsb", "isb", options(nomem, nostack));
        core::arch::asm!("cpsie i", options(nomem, nostack));
    }
}

/// Set interrupt mask from ISR
#[inline(always)]
pub fn portSET_INTERRUPT_MASK_FROM_ISR() -> UBaseType_t {
    ulPortSetInterruptMask()
}

/// Clear interrupt mask from ISR
#[inline(always)]
pub fn portCLEAR_INTERRUPT_MASK_FROM_ISR(uxSavedInterruptStatus: UBaseType_t) {
    vPortClearInterruptMask(uxSavedInterruptStatus as u32);
}

// =============================================================================
// Context Switching / Yield
// =============================================================================

/// Trigger a context switch via SWI
#[inline(always)]
pub fn portYIELD() {
    unsafe {
        core::arch::asm!("svc 0", options(nomem, nostack));
    }
}

/// Yield from ISR by setting yield required flag
#[inline(always)]
pub fn portYIELD_FROM_ISR(xSwitchRequired: BaseType_t) {
    if xSwitchRequired != pdFALSE {
        unsafe {
            ulPortYieldRequired = pdTRUE as u32;
        }
    }
}

/// End switching ISR (same as yield from ISR)
#[inline(always)]
pub fn portEND_SWITCHING_ISR(xSwitchRequired: BaseType_t) {
    portYIELD_FROM_ISR(xSwitchRequired);
}

// =============================================================================
// Stack Initialization
// =============================================================================

/// Initialize a task's stack for Cortex-A9
///
/// Stack layout (high to low address):
/// - 3 NULL values (for GDB stack unwinding)
/// - SPSR (System mode, optionally Thumb bit)
/// - PC (task entry point)
/// - LR (R14) - prvTaskExitError
/// - R12, R11, R10, R9, R8, R7, R6, R5, R4, R3, R2, R1
/// - R0 (pvParameters)
/// - ulCriticalNesting (0)
/// - ulPortTaskHasFPUContext (0 or pdTRUE with FPU registers)
///
/// # Safety
///
/// `pxTopOfStack` must be non-null, correctly aligned, and lie near the high
/// end of a uniquely writable allocation with enough lower-addressed room for
/// the complete initial context. The allocation must remain live and
/// stationary for the task lifetime. `pvParameters` must satisfy `pxCode`.
pub unsafe fn pxPortInitialiseStack(
    pxTopOfStack: *mut StackType_t,
    pxCode: TaskFunction_t,
    pvParameters: *mut c_void,
) -> *mut StackType_t {
    unsafe {
        let mut pxStack = pxTopOfStack;

        // Add NULL values for GDB stack unwinding
        *pxStack = 0;
        pxStack = pxStack.sub(1);
        *pxStack = 0;
        pxStack = pxStack.sub(1);
        *pxStack = 0;
        pxStack = pxStack.sub(1);

        // SPSR - System mode, ARM state (check for Thumb entry)
        let mut spsr = portINITIAL_SPSR;
        if (pxCode as u32 & portTHUMB_MODE_ADDRESS) != 0 {
            spsr |= portTHUMB_MODE_BIT;
        }
        *pxStack = spsr;
        pxStack = pxStack.sub(1);

        // PC - task entry point
        *pxStack = pxCode as StackType_t;
        pxStack = pxStack.sub(1);

        // LR (R14) - task exit error handler
        *pxStack = prvTaskExitError as StackType_t;
        pxStack = pxStack.sub(1);

        // R12
        *pxStack = 0x12121212;
        pxStack = pxStack.sub(1);

        // R11
        *pxStack = 0x11111111;
        pxStack = pxStack.sub(1);

        // R10
        *pxStack = 0x10101010;
        pxStack = pxStack.sub(1);

        // R9
        *pxStack = 0x09090909;
        pxStack = pxStack.sub(1);

        // R8
        *pxStack = 0x08080808;
        pxStack = pxStack.sub(1);

        // R7
        *pxStack = 0x07070707;
        pxStack = pxStack.sub(1);

        // R6
        *pxStack = 0x06060606;
        pxStack = pxStack.sub(1);

        // R5
        *pxStack = 0x05050505;
        pxStack = pxStack.sub(1);

        // R4
        *pxStack = 0x04040404;
        pxStack = pxStack.sub(1);

        // R3
        *pxStack = 0x03030303;
        pxStack = pxStack.sub(1);

        // R2
        *pxStack = 0x02020202;
        pxStack = pxStack.sub(1);

        // R1
        *pxStack = 0x01010101;
        pxStack = pxStack.sub(1);

        // R0 - first argument (pvParameters)
        *pxStack = pvParameters as StackType_t;
        pxStack = pxStack.sub(1);

        // Critical nesting count (0 = interrupts enabled)
        *pxStack = portNO_CRITICAL_NESTING as StackType_t;
        pxStack = pxStack.sub(1);

        // FPU context flag (no FPU context initially)
        *pxStack = portNO_FLOATING_POINT_CONTEXT;

        pxStack
    }
}

/// Called if a task returns from its implementing function
fn prvTaskExitError() -> ! {
    // Tasks should never return. If they do, halt.
    configASSERT(false);
    portDISABLE_INTERRUPTS();
    loop {
        unsafe {
            core::arch::asm!("wfi", options(nomem, nostack));
        }
    }
}

// =============================================================================
// Scheduler Start
// =============================================================================

/// Start the scheduler
///
/// Verifies we're not in user mode, sets up tick interrupt, and
/// starts the first task via vPortRestoreTaskContext.
#[no_mangle]
pub extern "C" fn xPortStartScheduler() -> BaseType_t {
    let ulAPSR: u32;

    // Check processor mode
    unsafe {
        core::arch::asm!("mrs {}, cpsr", out(reg) ulAPSR);
    }
    let mode = ulAPSR & portAPSR_MODE_BITS_MASK;

    configASSERT(mode != portAPSR_USER_MODE);

    if mode != portAPSR_USER_MODE {
        // Check binary point register is set correctly
        let bpr = unsafe { core::ptr::read_volatile(ICCBPR_ADDRESS as *const u32) };
        configASSERT((bpr & 0x03) <= portMAX_BINARY_POINT_VALUE);

        if (bpr & 0x03) <= portMAX_BINARY_POINT_VALUE {
            // Disable CPU IRQ before starting
            unsafe {
                core::arch::asm!("cpsid i", options(nomem, nostack));
            }

            // User must call vPortSetupTimerInterrupt or equivalent
            // before calling vTaskStartScheduler

            // Start first task
            unsafe {
                vPortRestoreTaskContext();
            }
        }
    }

    // Should never get here
    0
}

/// End the scheduler (not really supported on Cortex-A)
pub fn vPortEndScheduler() {
    configASSERT(false);
    loop {
        unsafe {
            core::arch::asm!("wfi", options(nomem, nostack));
        }
    }
}

// =============================================================================
// Tick Handler
// =============================================================================

/// FreeRTOS tick handler - called from platform-specific timer ISR
///
/// The user must:
/// 1. Set up a timer to call this function at configTICK_RATE_HZ
/// 2. Clear the timer interrupt after calling this
#[no_mangle]
pub extern "C" fn FreeRTOS_Tick_Handler() {
    // Mask interrupts up to max syscall priority
    unsafe {
        core::arch::asm!("cpsid i", options(nomem, nostack));

        let iccpmr = ICCPMR_ADDRESS as *mut u32;
        core::ptr::write_volatile(iccpmr, ulMaxAPIPriorityMask);

        core::arch::asm!("dsb", "isb", options(nomem, nostack));
        core::arch::asm!("cpsie i", options(nomem, nostack));
    }

    // Increment tick count
    // Safety: this is the configured tick ISR with scheduler state live and
    // the port interrupt mask in force.
    if unsafe { crate::kernel::tasks::xTaskIncrementTick() } != pdFALSE {
        unsafe {
            ulPortYieldRequired = pdTRUE as u32;
        }
    }

    // Unmask all priorities
    portCLEAR_INTERRUPT_MASK();

    // User must clear tick interrupt in their timer handler
}

// =============================================================================
// FPU Support
// =============================================================================

/// Mark current task as using FPU
///
/// Call this from a task before using any FPU instructions.
/// This ensures the FPU context will be saved/restored on context switch.
#[no_mangle]
pub extern "C" fn vPortTaskUsesFPU() {
    unsafe {
        ulPortTaskHasFPUContext = pdTRUE as u32;

        // Initialize FPSCR
        let fpscr: u32 = 0;
        core::arch::asm!("vmsr fpscr, {}", in(reg) fpscr, options(nomem, nostack));
    }
}

// =============================================================================
// Utility Functions
// =============================================================================

/// Check if currently executing in an interrupt context
#[inline(always)]
pub fn xPortIsInsideInterrupt() -> BaseType_t {
    unsafe {
        if ulPortInterruptNesting > 0 {
            pdTRUE
        } else {
            pdFALSE
        }
    }
}

/// No-operation
#[inline(always)]
pub fn portNOP() {
    unsafe {
        core::arch::asm!("nop", options(nomem, nostack));
    }
}

/// Memory barrier
#[inline(always)]
pub fn portMEMORY_BARRIER() {
    unsafe {
        core::arch::asm!("dmb", options(nomem, nostack));
    }
}

// =============================================================================
// Run-time Stats Timer Support
// =============================================================================

/// Cortex-A9 MPCore global timer registers on the supported vexpress-a9
/// private-peripheral map. Unlike the PMU cycle counter, this timer continues
/// advancing while the core is in WFI, so tickless idle remains accounted.
#[cfg(feature = "generate-run-time-stats")]
const A9_GLOBAL_TIMER_COUNTER_LOW: usize = configINTERRUPT_CONTROLLER_BASE_ADDRESS + 0x200;
#[cfg(feature = "generate-run-time-stats")]
const A9_GLOBAL_TIMER_COUNTER_HIGH: usize = configINTERRUPT_CONTROLLER_BASE_ADDRESS + 0x204;
#[cfg(feature = "generate-run-time-stats")]
const A9_GLOBAL_TIMER_CONTROL: usize = configINTERRUPT_CONTROLLER_BASE_ADDRESS + 0x208;
#[cfg(feature = "generate-run-time-stats")]
const A9_GLOBAL_TIMER_ENABLE: u32 = 1;

#[cfg(feature = "generate-run-time-stats")]
static mut ullRunTimeCounterStart: u64 = 0;

#[cfg(feature = "generate-run-time-stats")]
#[inline(always)]
fn prvReadRunTimeCounter() -> u64 {
    loop {
        let high_before =
            unsafe { core::ptr::read_volatile(A9_GLOBAL_TIMER_COUNTER_HIGH as *const u32) };
        let low = unsafe { core::ptr::read_volatile(A9_GLOBAL_TIMER_COUNTER_LOW as *const u32) };
        let high_after =
            unsafe { core::ptr::read_volatile(A9_GLOBAL_TIMER_COUNTER_HIGH as *const u32) };

        if high_before == high_after {
            return ((high_before as u64) << 32) | low as u64;
        }
    }
}

#[cfg(feature = "generate-run-time-stats")]
#[inline(always)]
pub fn portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() {
    unsafe {
        let control = A9_GLOBAL_TIMER_CONTROL as *mut u32;
        let current = core::ptr::read_volatile(control);
        core::ptr::write_volatile(control, current | A9_GLOBAL_TIMER_ENABLE);
        core::arch::asm!("dsb", "isb", options(nomem, nostack));
        ullRunTimeCounterStart = prvReadRunTimeCounter();
    }
}

#[cfg(feature = "generate-run-time-stats")]
#[inline(always)]
pub fn portGET_RUN_TIME_COUNTER_VALUE() -> crate::config::configRUN_TIME_COUNTER_TYPE {
    prvReadRunTimeCounter().wrapping_sub(unsafe { ullRunTimeCounterStart })
        as crate::config::configRUN_TIME_COUNTER_TYPE
}

#[cfg(feature = "generate-run-time-stats")]
#[inline(always)]
pub fn portINCREMENT_RUN_TIME_COUNTER() {
    // The MPCore global timer is the time base and advances independently.
}

// =============================================================================
// Tickless Idle
// =============================================================================

/// SP804 Timer register offsets (for tickless idle)
const SP804_TIMER_LOAD: usize = 0x00;
const SP804_TIMER_VALUE: usize = 0x04;
const SP804_TIMER_CONTROL: usize = 0x08;
const SP804_TIMER_INTCLR: usize = 0x0C;
const SP804_TIMER_RIS: usize = 0x10;
const SP804_TIMER_BGLOAD: usize = 0x18;

/// SP804 Timer control bits
const SP804_CTRL_ENABLE: u32 = 1 << 7;
const SP804_CTRL_PERIODIC: u32 = 1 << 6;
const SP804_CTRL_INTENABLE: u32 = 1 << 5;
const SP804_CTRL_32BIT: u32 = 1 << 1;

/// Timer base address for tickless idle - must be set by user before scheduler starts
/// For vexpress-a9: 0x10011000
#[no_mangle]
pub static mut ulTimerBaseAddress: usize = 0;

/// Timer counts per tick (set based on timer frequency and tick rate)
/// For vexpress-a9 at 1MHz with 1000Hz tick rate: 1000
#[no_mangle]
pub static mut ulTimerCountsForOneTick: u32 = 1000;

/// Maximum ticks that can be suppressed (limited by timer counter width)
#[no_mangle]
pub static mut ulMaximumPossibleSuppressedTicks: TickType_t = 0xFFFFFFFF / 1000;

/// Compensation for time spent entering/exiting sleep
#[no_mangle]
pub static mut ulStoppedTimerCompensation: u32 = 45;

/// Configure timer for tickless idle
/// Call this before starting the scheduler with the timer base address and counts per tick
#[no_mangle]
pub extern "C" fn vPortConfigureTimerForTickless(
    timer_base: usize,
    counts_per_tick: u32,
    timer_max_count: u32,
) {
    unsafe {
        ulTimerBaseAddress = timer_base;
        ulTimerCountsForOneTick = counts_per_tick;
        ulMaximumPossibleSuppressedTicks = if counts_per_tick > 1 {
            (timer_max_count / counts_per_tick) as TickType_t
        } else {
            0
        };
    }
}

/// Tickless idle implementation for Cortex-A9 with SP804 timer
#[cfg(feature = "tickless-idle")]
pub fn vPortSuppressTicksAndSleep(xExpectedIdleTime: TickType_t) {
    use crate::types::eSleepModeStatus;

    unsafe {
        // Check if timer is configured
        if ulTimerBaseAddress == 0
            || ulTimerCountsForOneTick < 2
            || ulMaximumPossibleSuppressedTicks < 2
            || xExpectedIdleTime < 2
        {
            return;
        }

        let timer_load = (ulTimerBaseAddress + SP804_TIMER_LOAD) as *mut u32;
        let timer_value = (ulTimerBaseAddress + SP804_TIMER_VALUE) as *const u32;
        let timer_control = (ulTimerBaseAddress + SP804_TIMER_CONTROL) as *mut u32;
        let timer_intclr = (ulTimerBaseAddress + SP804_TIMER_INTCLR) as *mut u32;
        let timer_ris = (ulTimerBaseAddress + SP804_TIMER_RIS) as *const u32;
        let timer_bgload = (ulTimerBaseAddress + SP804_TIMER_BGLOAD) as *mut u32;

        let mut xExpectedIdleTime = xExpectedIdleTime;

        // Limit to maximum possible
        if xExpectedIdleTime > ulMaximumPossibleSuppressedTicks {
            xExpectedIdleTime = ulMaximumPossibleSuppressedTicks;
        }

        // Disable interrupts (but not via GIC - use CPU flag)
        core::arch::asm!("cpsid i", options(nomem, nostack));
        core::arch::asm!("dsb", options(nomem, nostack));
        core::arch::asm!("isb", options(nomem, nostack));

        // Check if sleep should be aborted
        // Safety: the idle task has suspended the scheduler and this port has
        // masked IRQs for the tickless confirmation protocol.
        if crate::kernel::tasks::eTaskConfirmSleepModeStatus() == eSleepModeStatus::eAbortSleep {
            core::arch::asm!("cpsie i", options(nomem, nostack));
            return;
        }

        // Stop the timer
        let ctrl = core::ptr::read_volatile(timer_control);
        core::ptr::write_volatile(timer_control, ctrl & !SP804_CTRL_ENABLE);

        // Read current timer value (counts remaining until next tick)
        /* SP804 counts through zero, so VALUE + 1 is the number of timer
         * clocks left in the current tick.  Clamp a stale/out-of-range value
         * defensively to one normal tick. */
        let ulTimerDecrementsLeft = core::cmp::min(
            core::ptr::read_volatile(timer_value).saturating_add(1),
            ulTimerCountsForOneTick,
        );

        // Calculate reload value for expected idle time
        // -1 because we're partway through the current tick
        let mut ullReloadCounts = ulTimerDecrementsLeft as u64
            + ulTimerCountsForOneTick as u64 * (xExpectedIdleTime as u64 - 1);

        // Apply compensation for time spent in this function
        if ullReloadCounts > ulStoppedTimerCompensation as u64 {
            ullReloadCounts -= ulStoppedTimerCompensation as u64;
        }
        let ulReloadValue = (ullReloadCounts.saturating_sub(1) as u32).max(1);
        let ulPeriodicReloadValue = ulTimerCountsForOneTick.saturating_sub(1).max(1);

        /* LOAD changes the current count immediately. Enable before writing
         * BGLOAD: real SP804 hardware preserves the LOAD current value either
         * way, but QEMU selects the latest load source when a disabled timer
         * is enabled. Writing BGLOAD after enable preserves the long first
         * interval on both while restoring the next periodic reload. */
        core::ptr::write_volatile(timer_load, ulReloadValue);
        core::ptr::write_volatile(timer_intclr, 1); // Clear any pending interrupt
        core::ptr::write_volatile(
            timer_control,
            SP804_CTRL_ENABLE | SP804_CTRL_PERIODIC | SP804_CTRL_INTENABLE | SP804_CTRL_32BIT,
        );
        core::ptr::write_volatile(timer_bgload, ulPeriodicReloadValue);

        // Sleep until interrupt (WFI = Wait For Interrupt)
        core::arch::asm!("dsb", options(nomem, nostack));
        core::arch::asm!("wfi", options(nomem, nostack));
        core::arch::asm!("isb", options(nomem, nostack));

        /* Snapshot and stop the timer before servicing the wake source.  A
         * periodic SP804 has already reloaded by the time WFI returns on its
         * interrupt, so VALUE alone cannot distinguish an expiry from an
         * early external wake. */
        let xTimerExpired = core::ptr::read_volatile(timer_ris) != 0;
        let ulTimerValueAtWake = core::ptr::read_volatile(timer_value);
        let ctrl = core::ptr::read_volatile(timer_control);
        core::ptr::write_volatile(timer_control, ctrl & !SP804_CTRL_ENABLE);

        // Re-enable interrupts briefly to let the wake interrupt execute
        core::arch::asm!("cpsie i", options(nomem, nostack));
        core::arch::asm!("dsb", options(nomem, nostack));
        core::arch::asm!("isb", options(nomem, nostack));

        // Disable interrupts again for tick compensation
        core::arch::asm!("cpsid i", options(nomem, nostack));
        core::arch::asm!("dsb", options(nomem, nostack));
        core::arch::asm!("isb", options(nomem, nostack));

        // Calculate counter clocks elapsed before the wake interrupt ran.
        let ullCurrentCounts = ulTimerValueAtWake as u64 + 1;
        let ullSleepElapsedCounts = if xTimerExpired {
            let ullPeriodicCountsLeft =
                core::cmp::min(ullCurrentCounts, ulTimerCountsForOneTick as u64);
            ullReloadCounts + (ulTimerCountsForOneTick as u64).saturating_sub(ullPeriodicCountsLeft)
        } else if ullReloadCounts >= ullCurrentCounts {
            ullReloadCounts - ullCurrentCounts
        } else {
            0
        };

        /* Include the part of the current tick that elapsed before the timer
         * was stopped. If the timer expired, its ISR has contributed one
         * pended tick while the scheduler is suspended, so step no more than
         * expected-1 ticks here. */
        let ullCountsSinceTickBoundary =
            (ulTimerCountsForOneTick - ulTimerDecrementsLeft) as u64 + ullSleepElapsedCounts;
        let mut ulCompletedTicks = ullCountsSinceTickBoundary / ulTimerCountsForOneTick as u64;
        if xTimerExpired {
            ulCompletedTicks =
                core::cmp::min(ulCompletedTicks, xExpectedIdleTime.saturating_sub(1) as u64);
        }

        // Step the tick count forward
        if ulCompletedTicks > 0 {
            // Safety: IRQs remain masked, the scheduler is suspended, and the
            // completed interval was capped below the next unblock deadline.
            crate::kernel::tasks::vTaskStepTick(ulCompletedTicks as TickType_t);
        }

        // Calculate remaining counts until next tick
        let ulTickPhase = (ullCountsSinceTickBoundary % ulTimerCountsForOneTick as u64) as u32;
        let ulRemainingCounts = if ulTickPhase == 0 {
            ulTimerCountsForOneTick
        } else {
            ulTimerCountsForOneTick - ulTickPhase
        };
        let ulFirstReloadValue = ulRemainingCounts.saturating_sub(1).max(1);

        /* LOAD schedules the partial first interval. As above, enable before
         * BGLOAD so QEMU does not replace that current interval. */
        core::ptr::write_volatile(timer_load, ulFirstReloadValue);
        core::ptr::write_volatile(timer_intclr, 1);
        core::ptr::write_volatile(
            timer_control,
            SP804_CTRL_ENABLE | SP804_CTRL_PERIODIC | SP804_CTRL_INTENABLE | SP804_CTRL_32BIT,
        );
        core::ptr::write_volatile(timer_bgload, ulPeriodicReloadValue);

        // Re-enable interrupts
        core::arch::asm!("cpsie i", options(nomem, nostack));
    }
}

/// Stub for when tickless idle is not enabled
#[cfg(not(feature = "tickless-idle"))]
pub fn vPortSuppressTicksAndSleep(_xExpectedIdleTime: TickType_t) {
    // No-op when tickless idle is disabled
}

// =============================================================================
// Assembly Handlers
// =============================================================================

// External references for assembly code
extern "C" {
    fn vPortRestoreTaskContext();
}

// Assembly code for context save/restore and exception handlers
global_asm!(
    // ARM mode
    ".arm",
    ".align 4",
    // Processor mode constants
    ".set SYS_MODE, 0x1f",
    ".set SVC_MODE, 0x13",
    ".set IRQ_MODE, 0x12",
    // ==========================================================================
    // portSAVE_CONTEXT macro
    // ==========================================================================
    ".macro portSAVE_CONTEXT",
    // Save LR and SPSR to system mode stack, then switch to system mode
    "srsdb sp!, #SYS_MODE",
    "cps #SYS_MODE",
    // Save R0-R12 and R14
    "push {{r0-r12, r14}}",
    // Push critical nesting count
    "ldr r2, =ulCriticalNesting",
    "ldr r1, [r2]",
    "push {{r1}}",
    // Check if FPU context needs saving
    "ldr r2, =ulPortTaskHasFPUContext",
    "ldr r3, [r2]",
    "cmp r3, #0",
    // Save FPU context if needed (conditional)
    "fmrxne r1, fpscr",
    "pushne {{r1}}",
    "vpushne {{d0-d15}}",
    "vpushne {{d16-d31}}",
    // Push FPU context flag
    "push {{r3}}",
    // Save stack pointer to TCB
    "ldr r0, =pxCurrentTCB",
    "ldr r1, [r0]",
    "str sp, [r1]",
    ".endm",
    // ==========================================================================
    // portRESTORE_CONTEXT macro
    // ==========================================================================
    ".macro portRESTORE_CONTEXT",
    // Get stack pointer from TCB
    "ldr r0, =pxCurrentTCB",
    "ldr r1, [r0]",
    "ldr sp, [r1]",
    // Pop FPU context flag
    "ldr r0, =ulPortTaskHasFPUContext",
    "pop {{r1}}",
    "str r1, [r0]",
    "cmp r1, #0",
    // Restore FPU context if needed (conditional)
    "vpopne {{d16-d31}}",
    "vpopne {{d0-d15}}",
    "popne {{r0}}",
    "vmsrne fpscr, r0",
    // Pop critical nesting count
    "ldr r0, =ulCriticalNesting",
    "pop {{r1}}",
    "str r1, [r0]",
    // Set GIC priority mask based on critical nesting
    "ldr r2, =ulICCPMRAddress",
    "ldr r2, [r2]",
    "cmp r1, #0",
    "moveq r4, #255",
    "ldrne r4, =ulMaxAPIPriorityMaskConst",
    "ldrne r4, [r4]",
    "str r4, [r2]",
    // Restore R0-R12 and R14
    "pop {{r0-r12, r14}}",
    // Return to task, loading CPSR
    "rfeia sp!",
    ".endm",
    // ==========================================================================
    // FreeRTOS_SWI_Handler - Software Interrupt Handler (Context Switch)
    // ==========================================================================
    ".global FreeRTOS_SWI_Handler",
    ".type FreeRTOS_SWI_Handler, %function",
    "FreeRTOS_SWI_Handler:",
    // Save context of current task
    "portSAVE_CONTEXT",
    // Ensure 8-byte stack alignment
    "mov r2, sp",
    "and r2, r2, #4",
    "sub sp, sp, r2",
    // Call vTaskSwitchContext
    "bl vTaskSwitchContext",
    // Restore context of next task
    "portRESTORE_CONTEXT",
    // ==========================================================================
    // vPortRestoreTaskContext - Start First Task
    // ==========================================================================
    ".global vPortRestoreTaskContext",
    ".type vPortRestoreTaskContext, %function",
    "vPortRestoreTaskContext:",
    // Switch to system mode and restore first task
    "cps #SYS_MODE",
    "portRESTORE_CONTEXT",
    // ==========================================================================
    // FreeRTOS_IRQ_Handler - IRQ Handler
    // ==========================================================================
    ".global FreeRTOS_IRQ_Handler",
    ".type FreeRTOS_IRQ_Handler, %function",
    "FreeRTOS_IRQ_Handler:",
    // Adjust LR for return (IRQ returns to next instruction)
    "sub lr, lr, #4",
    // Push return address and SPSR
    "push {{lr}}",
    "mrs lr, spsr",
    "push {{lr}}",
    // Switch to supervisor mode for reentry
    "cps #SVC_MODE",
    // Save used registers
    "push {{r0-r4, r12}}",
    // Increment interrupt nesting count
    "ldr r3, =ulPortInterruptNesting",
    "ldr r1, [r3]",
    "add r4, r1, #1",
    "str r4, [r3]",
    // Read interrupt acknowledge register
    "ldr r2, =ulICCIARAddress",
    "ldr r2, [r2]",
    "ldr r0, [r2]",
    // Ensure 8-byte stack alignment
    "mov r2, sp",
    "and r2, r2, #4",
    "sub sp, sp, r2",
    // Call application IRQ handler (r0 = ICCIAR value)
    "push {{r0-r4, lr}}",
    "bl vApplicationIRQHandler",
    "pop {{r0-r4, lr}}",
    "add sp, sp, r2",
    // Disable interrupts for EOI
    "cpsid i",
    "dsb",
    "isb",
    // Write to End of Interrupt register
    "ldr r4, =ulICCEOIRAddress",
    "ldr r4, [r4]",
    "str r0, [r4]",
    // Restore interrupt nesting count
    "str r1, [r3]",
    // Only switch context if nesting is 0
    "cmp r1, #0",
    "bne exit_without_switch",
    // Check if context switch requested
    "ldr r1, =ulPortYieldRequired",
    "ldr r0, [r1]",
    "cmp r0, #0",
    "bne switch_before_exit",
    "exit_without_switch:",
    // Restore used registers and return
    "pop {{r0-r4, r12}}",
    "cps #IRQ_MODE",
    "pop {{lr}}",
    "msr spsr_cxsf, lr",
    "pop {{lr}}",
    "movs pc, lr",
    "switch_before_exit:",
    // Clear yield flag
    "mov r0, #0",
    "str r0, [r1]",
    // Restore registers and prepare for context switch
    "pop {{r0-r4, r12}}",
    "cps #IRQ_MODE",
    "pop {{lr}}",
    "msr spsr_cxsf, lr",
    "pop {{lr}}",
    // Save context and switch
    "portSAVE_CONTEXT",
    // Ensure 8-byte alignment
    "mov r2, sp",
    "and r2, r2, #4",
    "sub sp, sp, r2",
    // Call vTaskSwitchContext
    "bl vTaskSwitchContext",
    // Restore new task context
    "portRESTORE_CONTEXT",
    // ==========================================================================
    // Weak default IRQ handler (calls vApplicationFPUSafeIRQHandler)
    // ==========================================================================
    ".weak vApplicationIRQHandler",
    ".type vApplicationIRQHandler, %function",
    "vApplicationIRQHandler:",
    // Save FPU registers before calling safe handler
    "push {{lr}}",
    "fmrx r1, fpscr",
    "vpush {{d0-d7}}",
    "vpush {{d16-d31}}",
    "push {{r1}}",
    // Call FPU-safe handler
    "bl vApplicationFPUSafeIRQHandler",
    // Restore FPU registers
    "pop {{r0}}",
    "vpop {{d16-d31}}",
    "vpop {{d0-d7}}",
    "vmsr fpscr, r0",
    "pop {{pc}}",
);

// vApplicationFPUSafeIRQHandler is declared in assembly as .weak and expects
// users to provide a strong implementation. If not provided, the assembly
// default will call this (which will assert), but typically users override it.