sentry_uapi/
systypes.rs

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
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
// SPDX-FileCopyrightText: 2023 Ledger SAS
// SPDX-License-Identifier: Apache-2.0

/// This library defines types (structs, enums, ...) related to syscalls,
/// that need to be shared between the kernel and the uapi.
///
/// Most important enum is `Syscall`, which defines the list of available
/// syscalls and sets their identifier/number.
///

/// This macro takes an enum and implements fallible conversion from a u8
/// exhaustively, as required by the SVC Handler.
///
/// ```
/// pub enum Syscall {
///     Exit,
/// }
///
/// impl TryFrom<u8> for Syscall {
///     type Error = ();
///     fn try_from(v: u8) -> Result<Self, Self::Error> {
///         match v {
///             x if x == Syscall::Exit as u8 => Ok(Syscall::Exit),
///             _ => Err(())
///         }
///     }
/// }
/// ```
/// (inspired by https://stackoverflow.com/a/58715864)
///
/// It also ensures that there cannot be a mismatch between the u8 value
/// used to define the enum, and the value used for converting to it.
macro_rules! syscall_list {
    ($vis:vis enum $name:ident {
        $($vname:ident,)*
    }) => {
        #[repr(C)]
        #[cfg_attr(debug_assertions, derive(Debug))]
        $vis enum $name {
            $($vname,)*
        }

        impl TryFrom<u8> for $name {
            type Error = Status;

            fn try_from(v: u8) -> Result<Self, Self::Error> {
                match v {
                    $(x if x == $name::$vname as u8 => Ok($name::$vname),)*
                    _ => Err(Status::Invalid),
                }
            }
        }
    }
}

syscall_list! {
pub enum Syscall {
    Exit,
    GetProcessHandle,
    GetDeviceHandle,
    Yield,
    Sleep,
    Start,
    MapDev,
    MapShm,
    UnmapDev,
    UnmapShm,
    SHMSetCredential,
    SendIPC,
    SendSignal,
    WaitForEvent,
    PmManage,
    PmSetClock,
    Log,
    Alarm,
    GetRandom,
    GetCycle,
    GpioGet,
    GpioSet,
    GpioReset,
    GpioToggle,
    GpioConfigure,
    IrqAcknowledge,
    IrqEnable,
    IrqDisable,
    GetShmHandle,
    GetDmaStreamHandle,
    DmaStartStream,
    DmaSuspendStream,
    DmaGetStreamStatus,
    ShmGetInfos,
    DmaAssignStream,
    DmaUnassignStream,
    DmaGetStreamInfo,
    DmaResumeStream,
}
}

macro_rules! mirror_enum {
    ($to:ty, $vis:vis enum $name:ident {
        $($vname:ident,)*
    }) => {
        #[repr(C)]
        $vis enum $name {
            $($vname,)*
        }

        impl TryFrom<$to> for $name {
            type Error = Status;

            fn try_from(v: $to) -> Result<Self, Self::Error> {
                match v {
                    $(x if x == $name::$vname as $to => Ok($name::$vname),)*
                    _ => Err(Status::Invalid),
                }
            }
        }
    }
}

/// Sentry syscall return values
///
/// Note: the kernel also hold, at kernel level, another value denoted
/// 'NonSense'. This value must never be returned to userspace. This
/// is why this value do not exist here.
///
/// Such a return should raise a security exception. All syscalls that can't set
/// they return code synchronously (e.g. IPC), MUST use this value as
/// default one
#[repr(C)]
#[cfg_attr(debug_assertions, derive(Debug, PartialEq))]
#[derive(Copy, Clone)]
pub enum Status {
    /// Successful result, the kernel has terminated its task with no error
    Ok,
    /// At least one parameter is not valid (not allowed or not found)
    Invalid,
    /// The requested action is not allowed for caller, or the resource is not owned
    Denied,
    /// The requested resource do not exist
    NoEntity,
    /// The requested resource is in a state that do now allow the current call
    Busy,
    /// The requested resource is already mapped
    AlreadyMapped,
    /// Critical (mostly security-related) unexpected event
    Critical,
    /// The requested resource did not respond or the call has reached its maximum wait time
    Timeout,
    /// The requested resource is not here yet, come back later
    Again,
    /// The call has been interrupted sooner than expected. Used for blocking calls
    Intr,
    /// The requested resource can't be manipulated without generating a dead lock
    Deadlk,
}

/// u32 to Status converter, required to support register encoded value
impl From<u32> for Status {
    fn from(status_int: u32) -> Status {
        match status_int {
            0 => Status::Ok,
            1 => Status::Invalid,
            2 => Status::Denied,
            3 => Status::NoEntity,
            4 => Status::Busy,
            5 => Status::AlreadyMapped,
            6 => Status::Critical,
            7 => Status::Timeout,
            8 => Status::Again,
            9 => Status::Intr,
            10 => Status::Deadlk,
            _ => panic!(),
        }
    }
}

/// A process label is a development-time fixed identifier that can be used hardcoded
///  in the source code. This can be used in order to get back remote process effective
/// identifier from label at any time in order to communicate
pub type TaskLabel = u32;

/// A shm label is a development-time fixed identifier that can be used hardcoded
/// in the source code. This label is set in the device-tree in the shm declaration,
/// and can be used in order to get back the effective shm handler from it in order
/// to manipulate it
pub type ShmLabel = u32;

/// A stream label is a development-time fixed identifier that can be used hardcoded
/// in the source code in order to identify declared DMA streams.
/// This label is set in the device-tree in the stream declaration,
/// and can be used in order to get back the effective DMA stream handler from it in order
/// to manipulate it
pub type StreamLabel = u32;

/// A device label is a development-time fixed identifier that can be used hardcoded
/// in the source code in order to identify declared device.
/// This label is, by now, the result of the device tree analysis but will be replaced by
/// a clean outpost,label field at dts level, in the same way other label are set, to
/// highly simplify userspace level usage.
/// This label is used to get back the associated handle at run time.
pub type DeviceLabel = u32;

/// A device handle is a unique identifier required to manipulate a devive
///
/// That handle is forged by the kernel at bootup time and vary from one boot to another.
/// The device handle can be retrieved by using the [`crate::syscall::get_device_handle`]
/// syscall.
///
pub type DeviceHandle = u32;

/// A task handle is a unique identifier required to communicate with another task.
///
/// A task handle is associated to a job, meaning that if a task job terminates and
/// is restarted, the associated handle is reforged and diverge from the previous one.
///
/// All jobs have a task handle. This handle is the only way to uniquely identify a
/// given job with which we need to communicate..
/// The task handle can be retrieved by using the [`crate::syscall::get_process_handle`]
/// syscall.
///
pub type TaskHandle = u32;

/// A SHM handle is a unique identifier required to manipulate a shared memory.
///
/// That handle is forged by the kernel at bootup time and vary from one boot to another.
/// The SHM handle can be retrieved by using the [`crate::syscall::get_shm_handle`]
/// syscall.
///
pub type ShmHandle = u32;

/// A DMA stream handle is a unique identifier required to manipulate a DMA stream.
///
/// That handle is forged by the kernel at bootup time and vary from one boot to another.
/// The DMA stream handle can be retrieved by using the [`crate::syscall::get_dma_stream_handle`]
/// syscall.
///
pub type StreamHandle = u32;

/// Definition of Sentry events
///
/// Multiple events can targets a given task. These events are strictly
/// identified so that the task can easily differentiate them.
///
/// As multiple events can be set at once, event field is using a
/// bitfield model to keep C+Rust usage easy
#[repr(C)]
pub enum EventType {
    /// No event
    None = 0,
    /// Inter-task slow path IPC event
    Ipc = 1,
    /// Inter-task signal event
    Signal = 2,
    /// Hardware interrupt event
    Irq = 4,
    /// DMA stream event
    Dma = 8,
    /// Any of the above events
    All = 15,
}

/// Event Type to register (u32) converter
impl From<EventType> for u32 {
    fn from(event: EventType) -> u32 {
        match event {
            EventType::None => 0,
            EventType::Ipc => 1,
            EventType::Signal => 2,
            EventType::Irq => 4,
            EventType::Dma => 8,
            EventType::All => 15,
        }
    }
}

/// Erase type that can be used to clear the SVC_Exchange.
///
/// TODO: to be moved to svc_exchange module as used exclusively by
/// this module primitives.
///
/// There are two types of erase model:
/// - Zeroify, that write 0x0 pattern in the SVC exchange zone
/// - Random, that write a random pattern
///
/// By now, only Zeroify is supported.
#[repr(C)]
pub enum EraseType {
    Zeroify = 0x5a,
    Random = 0xa5,
}

impl From<EraseType> for u32 {
    fn from(etype: EraseType) -> u32 {
        match etype {
            EraseType::Zeroify => 0x5a,
            EraseType::Random => 0xa5,
        }
    }
}

/// Erase mode that can be used to clear the SVC_Exchange.
///
/// There are two types of erase mode:
/// - UserErase, leaving the write action to the UAPI crate, withtout kernel call
/// - KernelErase, requiring the kernel to execute the erasing.
///   This last mode ensure that the erasing is atomic while it is started.
///
/// By now, only UserErase ils supported.
#[repr(C)]
pub enum EraseMode {
    UserErase = 0x72,
    KernelErase = 0x27,
}

impl From<EraseMode> for u32 {
    fn from(emode: EraseMode) -> u32 {
        match emode {
            EraseMode::UserErase => 0x72,
            EraseMode::KernelErase => 0x27,
        }
    }
}

/// Alarm type for alarm-related API
#[repr(C)]
pub enum AlarmFlag {
    /// Start an alarm
    AlarmStart,
    /// Start a periodic alarm
    AlarmStartPeriodic,
    /// Stop an alarm, being periodic or not
    AlarmStop,
}

impl From<AlarmFlag> for u32 {
    fn from(mode: AlarmFlag) -> u32 {
        match mode {
            AlarmFlag::AlarmStart => 0,
            AlarmFlag::AlarmStartPeriodic => 1,
            AlarmFlag::AlarmStop => 2,
        }
    }
}

/// Permission model definition for shared memories
#[repr(C)]
pub enum SHMPermission {
    /// allows target process to map the SHM. No read nor write though
    Map,

    /// allows target process to read the mapped SHM. Requires MAP
    Read,

    /// allows target process to write shared memory. Requires MAP
    Write,

    /// allows target process to transfer SHM to another, pre-allowed, process
    Transfer,
}

/// Converter for SHM permission to register encoding (u32)
impl From<SHMPermission> for u32 {
    fn from(shm_perm: SHMPermission) -> u32 {
        match shm_perm {
            SHMPermission::Map => 0x1,
            SHMPermission::Read => 0x2,
            SHMPermission::Write => 0x4,
            SHMPermission::Transfer => 0x8,
        }
    }
}

/// Sentry signals definition. Most of them are aligned on standard POSIX signals
#[repr(C)]
pub enum Signal {
    /// Abort signal
    Abort = 1,

    /// Timer (from alarm)
    Alarm,

    /// Bus error (bad memory access, memory required)
    Bus,

    /// Continue if previously stopped
    Cont,

    /// Illegal instruction. Can be also used for upper provtocols
    Ill,

    /// I/O now ready
    Io,

    /// Broken pipe
    Pipe,

    /// Event pollable
    Poll,

    /// Termination signal
    Term,

    /// Trace/bp signal (debug usage only)
    Trap,

    /// 1st user-defined signal
    Usr1,

    /// 2nd user-defined signal
    Usr2,

    #[cfg(CONFIG_BUILD_TARGET_AUTOTEST)]
    /// Autotest-specific: User hardfault detected
    PanicUserHardFault,
    #[cfg(CONFIG_BUILD_TARGET_AUTOTEST)]
    /// Autotest-specific: A panic() has been reached in kernel handler
    PanicKernelHardFault,
    #[cfg(CONFIG_BUILD_TARGET_AUTOTEST)]
    /// Autotest-specific: User bus fault detected
    PanicUserBusFault,
    #[cfg(CONFIG_BUILD_TARGET_AUTOTEST)]
    /// Autotest-specific: Kernel bus fault detected
    PanicKernelBusFault,
    #[cfg(CONFIG_BUILD_TARGET_AUTOTEST)]
    /// Autotest-specific: User user usage fault detected
    PanicUserUsageFault,
    #[cfg(CONFIG_BUILD_TARGET_AUTOTEST)]
    /// Autotest-specific: Kernel usage fault detected
    PanicKernelUsageFault,
    #[cfg(CONFIG_BUILD_TARGET_AUTOTEST)]
    /// Autotest-specific: User memory fault detected
    PanicUserMemAccess,
    #[cfg(CONFIG_BUILD_TARGET_AUTOTEST)]
    /// Autotest-specific: Kernel memoryfault detected
    PanicKernelMemAccess,
    #[cfg(CONFIG_BUILD_TARGET_AUTOTEST)]
    /// Autotest-specific: Invalid userspace input received
    PanicKernelInvalidUserspaceInput,
    #[cfg(CONFIG_BUILD_TARGET_AUTOTEST)]
    /// Autotest-specific: Memory limit reached in a kernel buffer
    PanicKernelShorterKBuffersConfig,
    #[cfg(CONFIG_BUILD_TARGET_AUTOTEST)]
    /// Autotest-specific: A given manager returns invalid state error
    PanicKernelInvalidManagerState,
    #[cfg(CONFIG_BUILD_TARGET_AUTOTEST)]
    /// Autotest-specific: A given manager return an invalid response
    PanicKernelInvalidManagerResponse,
    #[cfg(CONFIG_BUILD_TARGET_AUTOTEST)]
    /// Autotest-specific: Kernel handler as reach timeout limit
    PanicKernelTimeout,
    #[cfg(CONFIG_BUILD_TARGET_AUTOTEST)]
    /// Autotest-specific: Kernel CFI violation
    PanicKernelBadCFICalculation,
    #[cfg(CONFIG_BUILD_TARGET_AUTOTEST)]
    /// Autotest-specific: Kernel-related hardware IP (MPU, etc.) is in invalid state
    PanicHardwareInvalidState,
    #[cfg(CONFIG_BUILD_TARGET_AUTOTEST)]
    /// Autotest-specific: An unexpected modification of a kernel context has been detected
    PanicHardwareUnexpectedModification,
    #[cfg(CONFIG_BUILD_TARGET_AUTOTEST)]
    /// Autotest-specific: Requested kernel autotest has finished successfully
    AutotestDone,
    #[cfg(CONFIG_BUILD_TARGET_AUTOTEST)]
    /// Autotest-specific: Requested kernel autotest has finished with a failure
    AutotestFailed,
    #[cfg(CONFIG_BUILD_TARGET_AUTOTEST)]
    /// Autotest-specific: Requested kernel autotest has timed-out
    AutotestTimedOut,
}

/// Sleep durations input values for the sleep API
#[repr(C)]
pub enum SleepDuration {
    /// Sleep for 1ms
    D1ms,
    /// Sleep for 2ms
    D2ms,
    /// Sleep for 5ms
    D5ms,
    /// Sleep for 10ms
    D10ms,
    /// Sleep for 20ms
    D20ms,
    /// Sleep for 50ms
    D50ms,
    /// Sleep for a user-specificed number of ms (>0)
    ArbitraryMs(u32),
}

/// Converter for SleepDuration type to register-encoded value
impl From<SleepDuration> for u32 {
    fn from(duration: SleepDuration) -> u32 {
        match duration {
            SleepDuration::D1ms => 1,
            SleepDuration::D2ms => 2,
            SleepDuration::D5ms => 5,
            SleepDuration::D10ms => 10,
            SleepDuration::D20ms => 20,
            SleepDuration::D50ms => 50,
            SleepDuration::ArbitraryMs(v) => v,
        }
    }
}

/// Sleep mode requested
#[repr(C)]
pub enum SleepMode {
    /// Sleep in shallow mode. External events awake the job
    Shallow,
    /// Sleep in deep mode. No sleep interruption
    Deep,
}

/// Converter for SleepMode type to register-encoded value
impl From<SleepMode> for u32 {
    fn from(mode: SleepMode) -> u32 {
        match mode {
            SleepMode::Shallow => 0,
            SleepMode::Deep => 1,
        }
    }
}

/// Converter from register-encoded or C FFI defined value to SleepMode
impl TryFrom<u32> for SleepMode {
    type Error = Status;
    fn try_from(mode: u32) -> Result<SleepMode, Self::Error> {
        match mode {
            0 => Ok(SleepMode::Shallow),
            1 => Ok(SleepMode::Deep),
            _ => Err(Status::Invalid),
        }
    }
}

/// Low power configuration support, defining the CPU sleep state exit event
///
/// There are multiple HW events that may terminate a low-power hardware cycle.
/// These are separated in two main families:
///
/// - Interrupt event (external interrupt)
/// - external event (not interrupt related)
///
/// Moreover, there is some time when the CPU must NOT enter sleep mode for a
/// given amount of time. This can be set with this CPUSleep configuration state.
///
/// > **FIXME**: the sleep trigger and the sleep constraints shoud be defined in separated
/// > types and calls.
#[repr(C)]
pub enum CPUSleep {
    /// Enter sleep mode and wait for external interrupt
    WaitForInterrupt,
    /// Enter sleep mode and wait for external event
    WaitForEvent,
    /// Disable any enter to the low power mode
    ForbidSleep,
    /// Re-enable low power
    AllowSleep,
}

impl From<CPUSleep> for u32 {
    fn from(mode: CPUSleep) -> u32 {
        match mode {
            CPUSleep::WaitForInterrupt => 0,
            CPUSleep::WaitForEvent => 1,
            CPUSleep::ForbidSleep => 2,
            CPUSleep::AllowSleep => 3,
        }
    }
}

impl TryFrom<u32> for CPUSleep {
    type Error = Status;
    fn try_from(mode: u32) -> Result<CPUSleep, Self::Error> {
        match mode {
            0 => Ok(CPUSleep::WaitForInterrupt),
            1 => Ok(CPUSleep::WaitForEvent),
            2 => Ok(CPUSleep::ForbidSleep),
            3 => Ok(CPUSleep::AllowSleep),
            _ => Err(Status::Invalid),
        }
    }
}

mirror_enum! {
    u32,
    pub enum Precision {
        Cycle,
        Nanoseconds,
        Microseconds,
        Milliseconds,
    }
}

/// Device related types definitions
pub mod dev {

    #[repr(C)]
    #[derive(Debug, Copy, Clone)]
    pub struct InterruptInfo {
        /// interrupt number
        pub num: u16,
        /// interrupt controler identifier
        pub controller: u8,
    }

    #[test]
    fn test_layout_it_info() {
        const UNINIT: ::std::mem::MaybeUninit<InterruptInfo> = ::std::mem::MaybeUninit::uninit();
        let ptr = UNINIT.as_ptr();
        assert_eq!(
            ::std::mem::size_of::<InterruptInfo>(),
            4usize,
            concat!("Size of: ", stringify!(InterruptInfo))
        );
        assert_eq!(
            ::std::mem::align_of::<InterruptInfo>(),
            2usize,
            concat!("Alignment of ", stringify!(InterruptInfo))
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).num) as usize - ptr as usize },
            0usize,
            concat!(
                "Offset of field: ",
                stringify!(InterruptInfo),
                "::",
                stringify!(num)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).controller) as usize - ptr as usize },
            2usize,
            concat!(
                "Offset of field: ",
                stringify!(InterruptInfo),
                "::",
                stringify!(controller)
            )
        );
    }

    #[repr(C)]
    #[derive(Debug, Copy, Clone)]
    pub struct IoInfo {
        /// GPIO port identifier, declared in DTS
        pub port: u8,
        /// GPIO pin identifier, declared in DTS
        pub pin: u8,
        pub mode: u8,
        /// GPIO AF identifier, declared in DTS
        pub af: u8,
        /// GPIO ppull config, declared in DTS
        pub ppull: u8,
        /// GPIO speed config, declared in DTS
        pub speed: u8,
        // GPIO pupdr config, declared in DTS
        pub pupdr: u32,
    }
    #[test]
    fn test_layout_io_info() {
        const UNINIT: ::std::mem::MaybeUninit<IoInfo> = ::std::mem::MaybeUninit::uninit();
        let ptr = UNINIT.as_ptr();
        assert_eq!(
            ::std::mem::size_of::<IoInfo>(),
            12usize,
            concat!("Size of: ", stringify!(IoInfo))
        );
        assert_eq!(
            ::std::mem::align_of::<IoInfo>(),
            4usize,
            concat!("Alignment of ", stringify!(IoInfo))
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).port) as usize - ptr as usize },
            0usize,
            concat!(
                "Offset of field: ",
                stringify!(IoInfo),
                "::",
                stringify!(port)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).pin) as usize - ptr as usize },
            1usize,
            concat!(
                "Offset of field: ",
                stringify!(IoInfo),
                "::",
                stringify!(pin)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).mode) as usize - ptr as usize },
            2usize,
            concat!(
                "Offset of field: ",
                stringify!(IoInfo),
                "::",
                stringify!(mode)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).af) as usize - ptr as usize },
            3usize,
            concat!(
                "Offset of field: ",
                stringify!(IoInfo),
                "::",
                stringify!(af)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).ppull) as usize - ptr as usize },
            4usize,
            concat!(
                "Offset of field: ",
                stringify!(IoInfo),
                "::",
                stringify!(ppull)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).speed) as usize - ptr as usize },
            5usize,
            concat!(
                "Offset of field: ",
                stringify!(IoInfo),
                "::",
                stringify!(speed)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).pupdr) as usize - ptr as usize },
            8usize,
            concat!(
                "Offset of field: ",
                stringify!(IoInfo),
                "::",
                stringify!(pupdr)
            )
        );
    }

    /// userspace oriented device definition
    ///
    #[repr(C)]
    #[derive(Debug, Copy, Clone)]
    pub struct DevInfo {
        pub id: u32,
        /// mappable device. Direct-IO (LED...) are not
        pub mappable: bool,
        /// for mappable devices, base address
        pub baseaddr: usize,
        /// for mappable devices, mapped size */\n/**<\n  number of device's interrupt.
        /// Can be EXTI (button) or NVIC interrupts (SoC device)
        pub size: usize,
        /// number of device interrupts
        pub num_interrupt: u8,
        /// device interrupt list
        pub its: [InterruptInfo; 8usize],
        /// number of device I/O (pinmux)
        pub num_ios: u8,
        /// device I/O list
        pub ios: [IoInfo; 8usize],
    }
    #[test]
    fn test_layout_devinfo() {
        const UNINIT: ::std::mem::MaybeUninit<DevInfo> = ::std::mem::MaybeUninit::uninit();
        let ptr = UNINIT.as_ptr();
        assert_eq!(
            ::std::mem::size_of::<DevInfo>(),
            160usize,
            concat!("Size of: ", stringify!(DevInfo))
        );
        assert_eq!(
            ::std::mem::align_of::<DevInfo>(),
            8usize,
            concat!("Alignment of ", stringify!(DevInfo))
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).id) as usize - ptr as usize },
            0usize,
            concat!(
                "Offset of field: ",
                stringify!(DevInfo),
                "::",
                stringify!(id)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).mappable) as usize - ptr as usize },
            4usize,
            concat!(
                "Offset of field: ",
                stringify!(DevInfo),
                "::",
                stringify!(mappable)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).baseaddr) as usize - ptr as usize },
            8usize,
            concat!(
                "Offset of field: ",
                stringify!(DevInfo),
                "::",
                stringify!(baseaddr)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).size) as usize - ptr as usize },
            16usize,
            concat!(
                "Offset of field: ",
                stringify!(DevInfo),
                "::",
                stringify!(size)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).num_interrupt) as usize - ptr as usize },
            24usize,
            concat!(
                "Offset of field: ",
                stringify!(DevInfo),
                "::",
                stringify!(num_interrupt)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).its) as usize - ptr as usize },
            26usize,
            concat!(
                "Offset of field: ",
                stringify!(DevInfo),
                "::",
                stringify!(its)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).num_ios) as usize - ptr as usize },
            58usize,
            concat!(
                "Offset of field: ",
                stringify!(DevInfo),
                "::",
                stringify!(num_ios)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).ios) as usize - ptr as usize },
            60usize,
            concat!(
                "Offset of field: ",
                stringify!(DevInfo),
                "::",
                stringify!(ios)
            )
        );
    }
}

/// SHM related types definitions
pub mod shm {

    #[repr(C)]
    #[derive(PartialEq, Debug, Copy, Clone)]
    pub struct ShmInfo {
        pub handle: crate::systypes::ShmHandle,
        pub label: u32,
        pub base: usize,
        pub len: usize,
        pub perms: u32,
    }

    #[test]
    fn test_layout_shm_infos() {
        const UNINIT: ::std::mem::MaybeUninit<ShmInfo> = ::std::mem::MaybeUninit::uninit();
        let ptr = UNINIT.as_ptr();
        assert_eq!(
            ::std::mem::size_of::<ShmInfo>(),
            32usize,
            concat!("Size of: ", stringify!(ShmInfo))
        );
        assert_eq!(
            ::std::mem::align_of::<ShmInfo>(),
            8usize,
            concat!("Alignment of ", stringify!(ShmInfo))
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).handle) as usize - ptr as usize },
            0usize,
            concat!(
                "Offset of field: ",
                stringify!(ShmInfo),
                "::",
                stringify!(handle)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).label) as usize - ptr as usize },
            4usize,
            concat!(
                "Offset of field: ",
                stringify!(shm_infos),
                "::",
                stringify!(label)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).base) as usize - ptr as usize },
            8usize,
            concat!(
                "Offset of field: ",
                stringify!(shm_infos),
                "::",
                stringify!(base)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).len) as usize - ptr as usize },
            16usize,
            concat!(
                "Offset of field: ",
                stringify!(shm_infos),
                "::",
                stringify!(len)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).perms) as usize - ptr as usize },
            24usize,
            concat!(
                "Offset of field: ",
                stringify!(shm_infos),
                "::",
                stringify!(perms)
            )
        );
    }
}

/// DMA related types definitions
///
/// In order to help with proper hierarchy of types for Sentry UAPI, syscall families
/// that requires a lot of shared types. This is the case of the DMA subsystem for
/// which all related types and types helpers are stored in the dma submodule.
pub mod dma {
    // FIXME: this enum is used for bitfield-based manipulation, as the
    // interrupts field is a local OR of this enumerate values
    pub enum GpdmaChanInt {
        /// DMA channel trigger on transfer complete
        TransferComplete = 1,
        /// DMA channel trigger on half transfer and transfer complete
        HalfTransfer = 2,
        /// triggers on DMA transfer or config error, get status for complete information
        DmaError = 4,
    }

    // FIXME: the interrupts field is a bitfield of one to 3 possible interrupts
    // we mai consider intlevels (TC+Error, TC+HT+Error, etc.) meaning that the field
    // is no more a bitfield
    impl TryFrom<u8> for GpdmaChanInt {
        type Error = crate::systypes::Status;
        fn try_from(mode: u8) -> Result<GpdmaChanInt, Self::Error> {
            match mode {
                1 => Ok(GpdmaChanInt::TransferComplete),
                2 => Ok(GpdmaChanInt::HalfTransfer),
                4 => Ok(GpdmaChanInt::DmaError),
                _ => Err(crate::systypes::Status::Invalid),
            }
        }
    }

    pub enum GpdmaTransferType {
        MemoryToDevice = 0,
        DeviceToMemory = 1,
        MemoryToMemory = 2,
        DeviceToDevice = 3,
    }

    impl TryFrom<u16> for GpdmaTransferType {
        type Error = crate::systypes::Status;
        fn try_from(mode: u16) -> Result<GpdmaTransferType, Self::Error> {
            match mode {
                0 => Ok(GpdmaTransferType::MemoryToDevice),
                1 => Ok(GpdmaTransferType::DeviceToMemory),
                2 => Ok(GpdmaTransferType::MemoryToMemory),
                3 => Ok(GpdmaTransferType::DeviceToDevice),
                _ => Err(crate::systypes::Status::Invalid),
            }
        }
    }

    // FIXME: this is a bitmask. We may consider moving to enum value instead
    // for e.g. by using IncrementBoth = 3
    pub enum GpdmaTransferMode {
        IncrementNone = 0,
        IncrementSrc = 1,
        IncrementDest = 2,
    }

    pub enum GpdmaBeatLen {
        /// Data len to manipulate is in bytes
        Byte = 0,
        /// Data len to manipulate is in half word
        Halfword = 1,
        /// Data len to manipulate is in word
        Word = 2,
    }

    impl TryFrom<u8> for GpdmaBeatLen {
        type Error = crate::systypes::Status;
        fn try_from(mode: u8) -> Result<GpdmaBeatLen, Self::Error> {
            match mode {
                0 => Ok(GpdmaBeatLen::Byte),
                1 => Ok(GpdmaBeatLen::Halfword),
                2 => Ok(GpdmaBeatLen::Word),
                _ => Err(crate::systypes::Status::Invalid),
            }
        }
    }

    pub enum GpdmaPriority {
        Low = 0,
        Medium = 1,
        High = 2,
        VeryHigh = 3,
    }

    impl TryFrom<u8> for GpdmaPriority {
        type Error = crate::systypes::Status;
        fn try_from(mode: u8) -> Result<GpdmaPriority, Self::Error> {
            match mode {
                0 => Ok(GpdmaPriority::Low),
                1 => Ok(GpdmaPriority::Medium),
                2 => Ok(GpdmaPriority::High),
                3 => Ok(GpdmaPriority::VeryHigh),
                _ => Err(crate::systypes::Status::Invalid),
            }
        }
    }

    /// DMA static configuration information
    ///
    /// # Usage
    ///
    /// This structure is delivered by the kernel into svc_exchange when
    /// calling successfully [`crate::syscall::dma_get_stream_info()`].
    ///
    /// The structure content correspond to the static build-time information
    /// as defined in the device-tree and do not require any DTS manipulation
    /// in user-space.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let dmacfg: dma_stream_cfg;
    /// match get_dma_stream_info(dmah) {
    ///    Status::Ok => (svc_exchange::copy_from(&dma_stream_cfg, mem::sizeof(dma_stream_cfg)))
    /// }
    /// ```
    ///
    #[repr(C)]
    #[derive(Debug, Copy, Clone)]
    pub struct GpdmaStreamConfig {
        pub channel: u16,
        pub stream: u16,
        pub controller: u16,
        pub transfer_type: u16,
        pub source: usize,
        pub dest: usize,
        pub transfer_len: usize,
        pub circular_source: bool,
        pub circular_dest: bool,
        pub interrupts: u8,
        pub is_triggered: bool,
        pub trigger: u8,
        pub priority: u8,
        pub transfer_mode: u8,
        pub src_beat_len: u8,
        pub dest_beat_len: u8,
    }

    // test that the Rust structure fields offset do match the corresponding C one,
    // as the kernel delivers in its ABI the C-defined structure
    #[test]
    fn test_layout_gpdma_stream_cfg() {
        const UNINIT: ::std::mem::MaybeUninit<GpdmaStreamConfig> =
            ::std::mem::MaybeUninit::uninit();
        let ptr = UNINIT.as_ptr();
        assert_eq!(
            ::std::mem::size_of::<GpdmaStreamConfig>(),
            48usize,
            concat!("Size of: ", stringify!(GpdmaStreamConfig))
        );
        assert_eq!(
            ::std::mem::align_of::<GpdmaStreamConfig>(),
            8usize,
            concat!("Alignment of ", stringify!(GpdmaStreamConfig))
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).channel) as usize - ptr as usize },
            0usize,
            concat!(
                "Offset of field: ",
                stringify!(GpdmaStreamConfig),
                "::",
                stringify!(channel)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).stream) as usize - ptr as usize },
            2usize,
            concat!(
                "Offset of field: ",
                stringify!(gpdma_stream_cfg),
                "::",
                stringify!(stream)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).controller) as usize - ptr as usize },
            4usize,
            concat!(
                "Offset of field: ",
                stringify!(gpdma_stream_cfg),
                "::",
                stringify!(controller)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).transfer_type) as usize - ptr as usize },
            6usize,
            concat!(
                "Offset of field: ",
                stringify!(gpdma_stream_cfg),
                "::",
                stringify!(transfer_type)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).source) as usize - ptr as usize },
            8usize,
            concat!(
                "Offset of field: ",
                stringify!(gpdma_stream_cfg),
                "::",
                stringify!(source)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).dest) as usize - ptr as usize },
            16usize,
            concat!(
                "Offset of field: ",
                stringify!(gpdma_stream_cfg),
                "::",
                stringify!(dest)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).transfer_len) as usize - ptr as usize },
            24usize,
            concat!(
                "Offset of field: ",
                stringify!(gpdma_stream_cfg),
                "::",
                stringify!(transfer_len)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).circular_source) as usize - ptr as usize },
            32usize,
            concat!(
                "Offset of field: ",
                stringify!(gpdma_stream_cfg),
                "::",
                stringify!(circular_source)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).circular_dest) as usize - ptr as usize },
            33usize,
            concat!(
                "Offset of field: ",
                stringify!(gpdma_stream_cfg),
                "::",
                stringify!(circular_dest)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).interrupts) as usize - ptr as usize },
            34usize,
            concat!(
                "Offset of field: ",
                stringify!(gpdma_stream_cfg),
                "::",
                stringify!(interrupts)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).is_triggered) as usize - ptr as usize },
            35usize,
            concat!(
                "Offset of field: ",
                stringify!(gpdma_stream_cfg),
                "::",
                stringify!(is_triggered)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).trigger) as usize - ptr as usize },
            36usize,
            concat!(
                "Offset of field: ",
                stringify!(gpdma_stream_cfg),
                "::",
                stringify!(trigger)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).priority) as usize - ptr as usize },
            37usize,
            concat!(
                "Offset of field: ",
                stringify!(gpdma_stream_cfg),
                "::",
                stringify!(priority)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).transfer_mode) as usize - ptr as usize },
            38usize,
            concat!(
                "Offset of field: ",
                stringify!(gpdma_stream_cfg),
                "::",
                stringify!(transfer_mode)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).src_beat_len) as usize - ptr as usize },
            39usize,
            concat!(
                "Offset of field: ",
                stringify!(gpdma_stream_cfg),
                "::",
                stringify!(src_beat_len)
            )
        );
        assert_eq!(
            unsafe { ::std::ptr::addr_of!((*ptr).dest_beat_len) as usize - ptr as usize },
            40usize,
            concat!(
                "Offset of field: ",
                stringify!(gpdma_stream_cfg),
                "::",
                stringify!(dest_beat_len)
            )
        );
    }

    pub enum GpdmaChanState {
        Idle = 1,
        Running = 2,
        Aborted = 3,
        Suspended = 4,
        TransmissionFailure = 5,
        ConfigurationFailure = 6,
        Overrun = 7,
        TransferComplete = 8,
        HalfTransfer = 9,
    }
}