psoc-drivers 0.1.0

Hardware driver implementations for psoc-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
//! Functions for configuring and managing clocks.
// Copyright (c) 2026, Infineon Technologies AG or an affiliate of Infineon Technologies AG.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing permissions and
// limitations under the License.

use core::{fmt::Debug, marker::PhantomData, num::NonZeroU32, sync::atomic::AtomicU32};

use regs::srss::{clk_dsi_select::DsiMux, clk_path_select::PathMux};

use crate::regs;

#[cfg(any(mxs40srss, mxs40ssrss))]
/// Frequency-locked loops.
pub mod fll;

#[cfg(mxs40ssrss)]
/// Low-power digital phase-locked loops.
pub mod lpdpll;

// TODO: implement MXS40 PLL

static HF_CLOCK_FREQUENCIES: [AtomicU32; 16] = [const { AtomicU32::new(0) }; 16];

/// The ClockHf index of the CPU clock.
pub const CLOCK_HF_CPU: usize = 0;

/// Returns the current CPU frequency in Hz.
pub fn current_cpu_frequency() -> u32 {
    ClockHf::<CLOCK_HF_CPU>::frequency()
        .map(NonZeroU32::get)
        .unwrap_or(8_000_000)
}

/// The system clock driver.
#[derive(Debug)]
#[non_exhaustive]
pub struct SysClock;

impl SysClock {
    /// Unsafely creates the system clock driver, without applying any configuration.
    ///
    /// # Safety
    ///
    /// The caller is responsible for ensuring the hardware is present on the device, configured
    /// correctly, and not accessed concurrently.
    pub const unsafe fn steal() -> Self {
        SysClock
    }
}

impl SysClock {
    /// Returns a reference to a clock path.
    pub fn clock_path<const N: usize>(&mut self) -> &mut ClockPath<N>
    where
        ClockPath<N>: ClockPathPresent,
    {
        unsafe { ClockPath::steal() }
    }

    /// Returns a reference to a high-frequency clock root.
    pub fn clock_hf<const N: usize>(&mut self) -> &mut ClockHf<N> {
        const {
            match N {
                #[cfg(clock_hf_0)]
                0 => {}
                #[cfg(clock_hf_1)]
                1 => {}
                #[cfg(clock_hf_2)]
                2 => {}
                #[cfg(clock_hf_3)]
                3 => {}
                #[cfg(clock_hf_4)]
                4 => {}
                #[cfg(clock_hf_5)]
                5 => {}
                #[cfg(clock_hf_6)]
                6 => {}
                #[cfg(clock_hf_7)]
                7 => {}
                #[cfg(clock_hf_8)]
                8 => {}
                #[cfg(clock_hf_9)]
                9 => {}
                #[cfg(clock_hf_10)]
                10 => {}
                #[cfg(clock_hf_11)]
                11 => {}
                #[cfg(clock_hf_12)]
                12 => {}
                #[cfg(clock_hf_13)]
                13 => {}
                #[cfg(clock_hf_14)]
                14 => {}
                #[cfg(clock_hf_15)]
                15 => {}

                _ => panic!("Invalid high-frequency clock root index"),
            }
        }
        unsafe { ClockHf::steal() }
    }

    /// Returns a reference to the low-frequency clock.
    pub fn clock_lf(&mut self) -> ClockLf<'_> {
        unsafe { ClockLf::steal() }
    }

    /// Returns a reference to the internal low-frequency oscillator.
    pub fn ilo(&mut self) -> Ilo<'_> {
        unsafe { Ilo::steal() }
    }

    /// Returns a reference to the watch crystal oscillator.
    pub fn wco(&mut self) -> Wco<'_> {
        unsafe { Wco::steal() }
    }

    /// Applies a configuration to the clock tree.
    ///
    /// `config` is the new configuration to apply, and `old` (if provided) is the previous
    /// configuration, to minimize redundant reconfiguration.
    ///
    /// Note that this function is marked #[inline(always)] for better optimizations in cases where
    /// the configuration is a compile-time constant. If the configuration is dynamic at runtime, it
    /// may be best to call this from a wrapper function to avoid code size bloat.
    #[inline(always)]
    pub fn configure(&mut self, config: &ClockConfig, old: Option<&ClockConfig>) {
        macro_rules! for_each {
            ($thing:literal, $body:ident) => {
                for_each!($thing, $body @ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
            };

            ($thing:literal, $body:ident @ $($n:literal),*) => {$(
                paste::paste! {
                    #[cfg([<$thing _ $n>])]
                    $body!([<$thing _ $n>], $n);
                }
            )*};
        }

        // Set worst-case wait states.
        #[cfg(mxs40srss)]
        self.set_wait_states(u32::MAX, false);

        // Enable any clock sources that need to be enabled.
        if config.ilo.is_some() && config.ilo.as_ref() != old.and_then(|c| c.ilo.as_ref()) {
            self.ilo().configure(config.ilo.as_ref());
        }
        if config.wco.is_some() && config.wco.as_ref() != old.and_then(|c| c.wco.as_ref()) {
            self.wco().configure(config.wco.as_ref());
        }

        // First, bypass any multipliers that need to be bypassed, to avoid accidentally generating
        // too-high frequencies.
        macro_rules! bypass_multiplier {
            ($path:ident, $n:literal) => {
                if config.$path.multiplier_config.is_none()
                    && old.is_none_or(|c| c.$path.multiplier_config.is_some())
                {
                    self.clock_path::<$n>().multiplier().configure(None);
                }
            };
        }
        for_each!("clock_path", bypass_multiplier);

        // Configure each clock path to use the correct source.
        macro_rules! set_path {
            ($path:ident, $n:literal) => {
                if Some(config.$path.source) != old.map(|c| c.$path.source) {
                    self.clock_path::<$n>().set_source(config.$path.source);
                }
            };
        }
        for_each!("clock_path", set_path);

        // Configure each clock root to use the correct path.
        macro_rules! set_hf_root {
            ($hf:ident, 0) => {
                if Some(config.$hf) != old.map(|c| c.$hf) {
                    self.clock_hf::<0>().configure(Some(&config.$hf));
                }
            };
            ($hf:ident, $n:literal) => {
                if Some(config.$hf) != old.map(|c| c.$hf) {
                    self.clock_hf::<$n>().configure(config.$hf.as_ref());
                }
            };
        }
        for_each!("clock_hf", set_hf_root);

        // Set actual wait states.
        #[cfg(mxs40srss)]
        self.set_wait_states(current_cpu_frequency(), config.is_ulp);

        // Enable any multipliers that need to be enabled.
        macro_rules! configure_multiplier {
            ($path:ident, $n:literal) => {
                if config.$path.multiplier_config.as_ref().is_some()
                    && config.$path.multiplier_config.as_ref()
                        != old.and_then(|c| c.$path.multiplier_config.as_ref())
                {
                    self.clock_path::<$n>()
                        .multiplier()
                        .configure(config.$path.multiplier_config.as_ref());
                }
            };
        }
        for_each!("clock_path", configure_multiplier);

        // Disable any clock sources that need to be disabled.
        if config.ilo.is_none() && old.and_then(|c| c.ilo.as_ref()).is_some() {
            self.ilo().configure(None);
        }
        if config.wco.is_none() && old.and_then(|c| c.wco.as_ref()).is_some() {
            self.wco().configure(None);
        }
    }

    /// Configures wait states for the given CPU frequency and power mode.
    #[cfg(mxs40srss)]
    pub fn set_wait_states(&mut self, cpu_freq: u32, is_ulp: bool) {
        let ram_wait_states = match cpu_freq {
            0..=25_000_000 => 0,
            25_000_001..=100_000_000 if !is_ulp => 0,
            25_000_001..=100_000_000 => 1,
            100_000_001.. => 1,
        };

        let flash_wait_states = if is_ulp {
            match cpu_freq {
                0..=16_000_000 => 0,
                16_000_001..=33_000_000 => 1,
                33_000_001.. => 2,
            }
        } else {
            match cpu_freq {
                0..=29_000_000 => 0,
                29_000_001..=58_000_000 => 1,
                58_000_001..=87_000_000 => 2,
                87_000_001..=120_000_000 => 3,
                120_000_001.. => 4,
            }
        };

        unsafe {
            regs::CPUSS
                .rom_ctl()
                .modify(|r| r.fast_ws().set(0).slow_ws().set(ram_wait_states));
            regs::CPUSS
                .ram0_ctl0()
                .modify(|r| r.fast_ws().set(0).slow_ws().set(ram_wait_states));
            #[cfg(ramc1)]
            regs::CPUSS
                .ram1_ctl0()
                .modify(|r| r.fast_ws().set(0).slow_ws().set(ram_wait_states));
            #[cfg(ramc2)]
            regs::CPUSS
                .ram2_ctl0()
                .modify(|r| r.fast_ws().set(0).slow_ws().set(ram_wait_states));

            regs::FLASHC
                .flash_ctl()
                .modify(|r| r.main_ws().set(flash_wait_states));
        }
    }
}

/// A configuration of the entire clock tree.
#[derive(Debug, Clone)]
pub struct ClockConfig {
    /// The configuration for the internal low-frequency oscillator.
    pub ilo: Option<IloConfig>,

    /// The configuration for the internal low-frequency oscillator.
    pub wco: Option<WcoConfig>,

    #[cfg(clock_path_0)]
    /// The configuration for clock path 0.
    pub clock_path_0: ClockPathConfig<0>,

    #[cfg(clock_path_1)]
    /// The configuration for clock path 1.
    pub clock_path_1: ClockPathConfig<1>,

    #[cfg(clock_path_2)]
    /// The configuration for clock path 2.
    pub clock_path_2: ClockPathConfig<2>,

    #[cfg(clock_path_3)]
    /// The configuration for clock path 3.
    pub clock_path_3: ClockPathConfig<3>,

    #[cfg(clock_path_4)]
    /// The configuration for clock path 4.
    pub clock_path_4: ClockPathConfig<4>,

    #[cfg(clock_path_5)]
    /// The configuration for clock path 5.
    pub clock_path_5: ClockPathConfig<5>,

    #[cfg(clock_path_6)]
    /// The configuration for clock path 6.
    pub clock_path_6: ClockPathConfig<6>,

    #[cfg(clock_path_7)]
    /// The configuration for clock path 7.
    pub clock_path_7: ClockPathConfig<7>,

    #[cfg(clock_path_8)]
    /// The configuration for clock path 8.
    pub clock_path_8: ClockPathConfig<8>,

    #[cfg(clock_path_9)]
    /// The configuration for clock path 9.
    pub clock_path_9: ClockPathConfig<9>,

    #[cfg(clock_path_10)]
    /// The configuration for clock path 10.
    pub clock_path_10: ClockPathConfig<10>,

    #[cfg(clock_path_11)]
    /// The configuration for clock path 11.
    pub clock_path_11: ClockPathConfig<11>,

    #[cfg(clock_path_12)]
    /// The configuration for clock path 12.
    pub clock_path_12: ClockPathConfig<12>,

    #[cfg(clock_path_13)]
    /// The configuration for clock path 13.
    pub clock_path_13: ClockPathConfig<13>,

    #[cfg(clock_path_14)]
    /// The configuration for clock path 14.
    pub clock_path_14: ClockPathConfig<14>,

    #[cfg(clock_path_15)]
    /// The configuration for clock path 15.
    pub clock_path_15: ClockPathConfig<15>,

    /// The configuration for high-frequency clock root 0.
    #[cfg(clock_hf_0)]
    pub clock_hf_0: ClockHfConfig,

    /// The configuration for high-frequency clock root 1.
    #[cfg(clock_hf_1)]
    pub clock_hf_1: Option<ClockHfConfig>,

    /// The configuration for high-frequency clock root 2.
    #[cfg(clock_hf_2)]
    pub clock_hf_2: Option<ClockHfConfig>,

    /// The configuration for high-frequency clock root 3.
    #[cfg(clock_hf_3)]
    pub clock_hf_3: Option<ClockHfConfig>,

    /// The configuration for high-frequency clock root 4.
    #[cfg(clock_hf_4)]
    pub clock_hf_4: Option<ClockHfConfig>,

    /// The configuration for high-frequency clock root 5.
    #[cfg(clock_hf_5)]
    pub clock_hf_5: Option<ClockHfConfig>,

    /// The configuration for high-frequency clock root 6.
    #[cfg(clock_hf_6)]
    pub clock_hf_6: Option<ClockHfConfig>,

    /// The configuration for high-frequency clock root 7.
    #[cfg(clock_hf_7)]
    pub clock_hf_7: Option<ClockHfConfig>,

    /// The configuration for high-frequency clock root 8.
    #[cfg(clock_hf_8)]
    pub clock_hf_8: Option<ClockHfConfig>,

    /// The configuration for high-frequency clock root 9.
    #[cfg(clock_hf_9)]
    pub clock_hf_9: Option<ClockHfConfig>,

    /// The configuration for high-frequency clock root 10.
    #[cfg(clock_hf_10)]
    pub clock_hf_10: Option<ClockHfConfig>,

    /// The configuration for high-frequency clock root 11.
    #[cfg(clock_hf_11)]
    pub clock_hf_11: Option<ClockHfConfig>,

    /// The configuration for high-frequency clock root 12.
    #[cfg(clock_hf_12)]
    pub clock_hf_12: Option<ClockHfConfig>,

    /// The configuration for high-frequency clock root 13.
    #[cfg(clock_hf_13)]
    pub clock_hf_13: Option<ClockHfConfig>,

    /// The configuration for high-frequency clock root 14.
    #[cfg(clock_hf_14)]
    pub clock_hf_14: Option<ClockHfConfig>,

    /// The configuration for high-frequency clock root 15.
    #[cfg(clock_hf_15)]
    pub clock_hf_15: Option<ClockHfConfig>,

    /// The configuratino for the low-frequency clock.
    pub clock_lf: ClockLfIn,

    /// Whether the system is in ultra-low-power mode (0.9V core voltage).
    /// Needed to configure wait states.
    #[cfg(mxs40srss)]
    pub is_ulp: bool,
}

impl ClockConfig {
    /// The default clock configuration.
    pub const DEFAULT: Self = cfg_select! {
        die = "psc3" => { Self {
            ilo: Some(IloConfig {
                backup_domain: false,
            }),
            wco: None,
            clock_path_0: ClockPathConfig {
                source: ClockSource::Imo,
                multiplier_config: Some(fll::FllConfig::from_frequency(8_000_000, 100_000_000)),
            },
            clock_path_1: ClockPathConfig {
                source: ClockSource::Iho,
                multiplier_config: Some(lpdpll::LpDpllConfig::from_frequency(
                    48_000_000,
                    180_000_000,
                    lpdpll::LpDllMode::Integer,
                )),
            },
            clock_path_2: ClockPathConfig {
                source: ClockSource::Iho,
                multiplier_config: Some(lpdpll::LpDpllConfig::from_frequency(
                    48_000_000,
                    240_000_000,
                    lpdpll::LpDllMode::Integer,
                )),
            },
            clock_path_3: ClockPathConfig {
                source: ClockSource::Imo,
                multiplier_config: None,
            },
            clock_path_4: ClockPathConfig {
                source: ClockSource::Imo,
                multiplier_config: None,
            },
            clock_path_5: ClockPathConfig {
                source: ClockSource::Imo,
                multiplier_config: None,
            },
            clock_hf_0: ClockHfConfig {
                source_path: ClockHfIn::ClockPath0,
                divider: 1,
                frequency: 100_000_000,
            },
            clock_hf_1: Some(ClockHfConfig {
                source_path: ClockHfIn::ClockPath1,
                divider: 1,
                frequency: 180_000_000,
            }),
            clock_hf_2: Some(ClockHfConfig {
                source_path: ClockHfIn::ClockPath0,
                divider: 1,
                frequency: 100_000_000,
            }),
            clock_hf_3: Some(ClockHfConfig {
                source_path: ClockHfIn::ClockPath2,
                divider: 1,
                frequency: 240_000_000,
            }),
            clock_hf_4: Some(ClockHfConfig {
                source_path: ClockHfIn::ClockPath0,
                divider: 1,
                frequency: 100_000_000,
            }),
            clock_hf_5: None,
            clock_hf_6: None,
            clock_lf: ClockLfIn::Ilo,
        }}

        any(die = "psoc6_01", die = "psoc6_02", die = "psoc6_03", die = "psoc6_04") => { Self {
            ilo: Some(IloConfig {
                backup_domain: false,
            }),
            wco: None,
            clock_path_0: ClockPathConfig {
                source: ClockSource::Imo,
                multiplier_config: Some(fll::FllConfig::from_frequency(8_000_000, 100_000_000)),
            },
            clock_path_1: ClockPathConfig {
                source: ClockSource::Imo,
                multiplier_config: None,
            },
            clock_path_2: ClockPathConfig {
                source: ClockSource::Imo,
                multiplier_config: None,
            },
            clock_path_3: ClockPathConfig {
                source: ClockSource::Imo,
                multiplier_config: None,
            },
            clock_path_4: ClockPathConfig {
                source: ClockSource::Imo,
                multiplier_config: None,
            },
            clock_path_5: ClockPathConfig {
                source: ClockSource::Imo,
                multiplier_config: None,
            },
            clock_hf_0: ClockHfConfig {
                source_path: ClockHfIn::ClockPath0,
                divider: 1,
                frequency: 100_000_000,
            },
            clock_hf_1: None,
            clock_hf_2: None,
            clock_hf_3: None,
            clock_hf_4: None,
            clock_hf_5: None,
            clock_lf: ClockLfIn::Ilo,
            is_ulp: false,
        }}
    };
}

impl Default for ClockConfig {
    fn default() -> Self {
        Self::DEFAULT
    }
}

/// A clock source for the high-frequency clock paths.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClockSource {
    /// Internal main oscillator.
    Imo,
    /// External clock signal on EXTCLK pin.
    ExtClk,
    /// External crystal oscillator.
    Eco,
    /// Internal high-frequency oscillator.
    #[cfg(mxs40ssrss)]
    Iho,
    /// Internal low-frequency oscillator.
    ///
    /// A low-power, low-accuracy 32.786 kHz oscillator.
    Ilo,
    /// Watch crystal oscillator.
    ///
    /// A highly accurate oscillator which uses an external 32.768-kHz watch crystal.
    Wco,
}
impl ClockSource {
    /// Returns (PATH_SELECT, DSI_SELECT) values for this clock source.
    fn value(&self) -> (PathMux, Option<DsiMux>) {
        match self {
            ClockSource::Imo => (PathMux::IMO, None),
            ClockSource::ExtClk => (PathMux::EXTCLK, None),
            ClockSource::Eco => (PathMux::ECO, None),
            #[cfg(mxs40ssrss)]
            ClockSource::Iho => (PathMux::IHO, None),

            ClockSource::Ilo => (PathMux::DSI_MUX, Some(DsiMux::ILO)),
            ClockSource::Wco => (PathMux::DSI_MUX, Some(DsiMux::WCO)),
        }
    }
}

/// A clock path is a multiplexer that connects to a selectable clock source, possibly with a multiplier.
#[derive(Debug)]
#[non_exhaustive]
pub struct ClockPath<const N: usize>;

/// The configuration of a clock path.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ClockPathConfig<const N: usize>
where
    ClockPath<N>: ClockPathPresent,
{
    /// The clock source to select for this clock path.
    pub source: ClockSource,
    /// The configuration for the multiplier on this clock path, if present.
    pub multiplier_config:
        Option<<<ClockPath<N> as ClockPathPresent>::Multiplier as Multiplier>::Config>,
}

impl<const N: usize> ClockPath<N>
where
    Self: ClockPathPresent,
{
    /// Unsafely creates a reference to this clock path. Does not set any configuration.
    ///
    /// # Safety
    ///
    /// The caller is responsible for ensuring the hardware is present on the device, configured
    /// correctly, and not accessed concurrently.
    pub const unsafe fn steal() -> &'static mut ClockPath<N> {
        // SAFETY: ClockPath is a ZST
        unsafe { &mut *core::ptr::dangling_mut() }
    }

    /// Returns a reference to the multiplier on this clock path, if present.
    pub fn multiplier(&mut self) -> &mut <Self as ClockPathPresent>::Multiplier {
        unsafe { <Self as ClockPathPresent>::Multiplier::steal() }
    }

    /// Sets the source of this clock path.
    ///
    /// It takes four cycles of the originally selected clock to switch away from it; do not
    /// disable the original clock during this time.
    pub fn set_source(&mut self, source: ClockSource) {
        let (path_select, dsi_select) = source.value();
        unsafe {
            if let Some(dsi_select) = dsi_select {
                regs::SRSS.clk_dsi_select()[N].init(|r| r.dsi_mux().set(dsi_select));
            }
            regs::SRSS.clk_path_select()[N].init(|r| r.path_mux().set(path_select));
        }
    }
}

/// A high-frequency root clock.
///
/// Each high-frequency peripheral is clocked from a high-frequency root clock, which can be
/// sourced from the IMO or any of the clock paths via a multiplexer and divider.
#[derive(Debug)]
pub struct ClockHf<const N: usize>;

/// The input source for a high-frequency clock.
#[allow(missing_docs)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[repr(u8)]
pub enum ClockHfIn {
    #[cfg(clock_path_0)]
    ClockPath0 = 0,
    #[cfg(clock_path_1)]
    ClockPath1,
    #[cfg(clock_path_2)]
    ClockPath2,
    #[cfg(clock_path_3)]
    ClockPath3,
    #[cfg(clock_path_4)]
    ClockPath4,
    #[cfg(clock_path_5)]
    ClockPath5,
    #[cfg(clock_path_6)]
    ClockPath6,
    #[cfg(clock_path_7)]
    ClockPath7,
    #[cfg(clock_path_8)]
    ClockPath8,
    #[cfg(clock_path_9)]
    ClockPath9,
    #[cfg(clock_path_10)]
    ClockPath10,
    #[cfg(clock_path_11)]
    ClockPath11,
    #[cfg(clock_path_12)]
    ClockPath12,
    #[cfg(clock_path_13)]
    ClockPath13,
    #[cfg(clock_path_14)]
    ClockPath14,
    #[cfg(clock_path_15)]
    ClockPath15,

    /// Source directly from the internal main oscillator.
    #[cfg(mxs40ssrss)]
    Imo,
}

/// The configuration of a high-frequency clock.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ClockHfConfig {
    /// The clock path to source from.
    pub source_path: ClockHfIn,
    /// The divider to apply to the selected clock path. Must be in the range 1-16.
    pub divider: u8,

    /// The resulting frequency of this clock.
    pub frequency: u32,
}

impl<const N: usize> ClockHf<N> {
    /// Unsafely creates a reference to this high-frequency clock root. Does not set any
    /// configuration.
    ///
    /// # Safety
    ///
    /// The caller is responsible for ensuring the hardware is present on the device, configured
    /// correctly, and not accessed concurrently.
    pub unsafe fn steal() -> &'static mut Self {
        // SAFETY: ClockHf is a ZST
        unsafe { &mut *core::ptr::dangling_mut() }
    }

    #[cfg_attr(
        mxs40srss,
        doc = "Configures this high-frequency clock root.

        - `source_path` is the clock path to source from, or `None` to disable the clock.
        - `divider` is the divider to apply to the selected clock path, and must be one of 1, 2, 4, or 8."
    )]
    #[cfg_attr(
        mxs40ssrss,
        doc = "Configures this high-frequency clock root.\n\n\
        - `source_path` is the clock path to source from, or `None` to disable the clock.\n\
        - `divider` is the divider to apply to the selected clock path, and must be in the range 1-16.
        "
    )]
    pub fn configure(&mut self, config: Option<&ClockHfConfig>) {
        if N == 0 {
            debug_assert!(config.is_some(), "Can't disable HF0");
        }

        let value = config
            .map(|config| {
                let mut value = regs::srss::ClkRootSelect::default();
                value = value.enable().set(true);

                value = value.root_mux().set(
                    #[cfg(mxs40ssrss)]
                    if config.source_path == ClockHfIn::Imo {
                        0
                    } else {
                        config.source_path as u8
                    }
                    .into(),
                    #[cfg(mxs40srss)]
                    (config.source_path as u8).into(),
                );
                cfg_select! {
                    mxs40srss => {
                        value = value.root_div().set(Self::validate_divider(config.divider));
                    }
                    mxs40ssrss => {
                        value = value.root_div_int().set(Self::validate_divider(config.divider));
                    }
                }
                value
            })
            .unwrap_or_default();

        unsafe {
            #[cfg(mxs40ssrss)]
            if config.is_some_and(|c| c.source_path == ClockHfIn::Imo) {
                regs::SRSS.clk_direct_select()[N].init(|r| {
                    r.direct_mux()
                        .set(regs::srss::clk_direct_select::DirectMux::IMO)
                });
            }

            regs::SRSS.clk_root_select()[N].write(value);

            #[cfg(mxs40ssrss)]
            if config.is_none_or(|c| c.source_path != ClockHfIn::Imo) {
                regs::SRSS.clk_direct_select()[N].init(|r| {
                    r.direct_mux()
                        .set(regs::srss::clk_direct_select::DirectMux::ROOT_MUX)
                });
            }
        }

        HF_CLOCK_FREQUENCIES[N].store(
            config.map_or(0, |c| c.frequency),
            core::sync::atomic::Ordering::Release,
        );
    }

    /// Returns the frequency of this high-frequency clock root, or None
    /// if it is disabled or not present.
    pub fn frequency() -> Option<NonZeroU32> {
        HF_CLOCK_FREQUENCIES[N]
            .load(core::sync::atomic::Ordering::Acquire)
            .try_into()
            .ok()
    }

    #[cfg(mxs40srss)]
    fn validate_divider(divider: u8) -> regs::srss::clk_root_select::RootDiv {
        match divider {
            1 => regs::srss::clk_root_select::RootDiv::NO_DIV,
            2 => regs::srss::clk_root_select::RootDiv::DIV_BY_2,
            4 => regs::srss::clk_root_select::RootDiv::DIV_BY_4,
            8 => regs::srss::clk_root_select::RootDiv::DIV_BY_8,
            _ => panic!("Invalid divider value"),
        }
    }

    #[cfg(mxs40ssrss)]
    fn validate_divider(divider: u8) -> regs::srss::clk_root_select::RootDivInt {
        debug_assert!(matches!(divider, 1..=16));
        (divider - 1).into()
    }
}

/// Marker trait to indicate the presence of a specific clock path on a device.
pub trait ClockPathPresent {
    /// The multiplier on this clock path, or () if none is present.
    type Multiplier: Multiplier;
}

/// A clock multiplier.
pub trait Multiplier: 'static {
    /// This multiplier's configuration.
    type Config: Clone + Debug + Eq;

    /// Unsafely creates a multiplier. Does not set any configuration.
    ///
    /// # Safety
    ///
    /// The caller is responsible for ensuring the hardware is present on the device, configured
    /// correctly, and not accessed concurrently.
    unsafe fn steal() -> &'static mut Self;

    /// Applies a configuration to this multiplier.
    fn configure(&mut self, config: Option<&Self::Config>);
}
impl Multiplier for () {
    type Config = ();

    #[doc(hidden)]
    unsafe fn steal() -> &'static mut Self {
        // SAFETY: () is a zero-sized type
        unsafe { &mut *core::ptr::dangling_mut() }
    }

    #[doc(hidden)]
    fn configure(&mut self, _config: Option<&Self::Config>) {}
}

/// Bypass selector for a clock multiplier.
#[repr(u8)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Bypass {
    /// Automatic using lock indicator. When locked, the multiplier output is used; when unlocked, the
    /// reference clock is used. Can be used to allow the system to start processing sooner after
    /// e.g. a DeepSleep wakeup. Incompatible with clock supervision, because the frequency changes
    /// based on the lock signal.
    Auto,

    /// When locked, the multiplier output is used; when unlocked, the output clock is gated off.
    LockedOrNothing,

    /// Bypasses the multiplier and outputs the reference clock.
    ReferenceInputOnly,

    /// Uses the multiplier output, regardless of lock status.
    MultiplierOutputOnly,
}

/// Marker trait to indicate the presence of a specific high-frequency clock root on a device.
pub trait ClockHfPresent<const N: usize> {}

macro_rules! impl_clock_path {
    ($($n:literal),*) => {$( paste::paste! {
        #[cfg([<clock_path _ $n>])]
        impl ClockPathPresent for ClockPath<[<$n>]> {
            type Multiplier = cfg_select! {
                clock_path_fll = $n => { fll::Fll }
                clock_path_pll0 = $n => { pll::Pll<0> }
                clock_path_pll1 = $n => { pll::Pll<1> }
                clock_path_dpll_lp0 = $n => { lpdpll::LpDpll<0> }
                clock_path_dpll_lp1 = $n => { lpdpll::LpDpll<1> }
                clock_path_dpll_hp0 = $n => { hpdpll::HpDpll<0> }
                _ => { () }
            };
        }
    })*};
}

macro_rules! impl_clock_hf {
    ($($n:literal),*) => {$( paste::paste! {
        #[cfg([<clock_hf _ $n>])]
        impl ClockHfPresent<[<$n>]> for ClockHf<[<$n>]> {}
    })*};
}

impl_clock_path!(
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"
);

impl_clock_hf!(
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"
);

/// The low-frequency clock, which can be sourced from the internal low-frequency oscillator,
/// a watch crystal oscillator, or external crystal oscillator.
///
/// This clock is used as a low-frequency source for timekeeping peripherals such as the WDT and
/// RTC. It is the only clock source that can be enabled in hibernate mode.
#[derive(Debug)]
pub struct ClockLf<'a>(PhantomData<&'a mut ()>);

/// The input source for the low-frequency clock.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum ClockLfIn {
    /// Internal low-frequency oscillator.
    Ilo,
    /// Watch crystal oscillator.
    Wco,
    /// External crystal oscillator, with a prescaler.
    /// Does not run in deep sleep or hibernate modes.
    #[cfg(mxs40ssrss)]
    Eco {
        /// The integer value of the prescaler. Must be in the range 1-1024.
        integer_divider: u16,
        /// The fractional value of the prescaler.
        fractional_divider: u8,
    },
}

impl ClockLf<'_> {
    /// Unsafely creates a reference to the low-frequency clock. Does not set any configuration.
    ///
    /// # Safety
    ///
    /// The caller is responsible for ensuring the hardware is present on the device, configured
    /// correctly, and not accessed concurrently.
    pub const unsafe fn steal() -> ClockLf<'static> {
        ClockLf(PhantomData)
    }

    /// Sets the source of the low-frequency clock.
    pub fn set_source(&mut self, source: ClockLfIn) {
        use regs::srss::clk_select::LfclkSel;
        use regs::srss::wdt_ctl::WdtLock;
        unsafe {
            #[cfg(mxs40ssrss)]
            if let ClockLfIn::Eco {
                integer_divider,
                fractional_divider,
            } = source
            {
                debug_assert!(matches!(integer_divider, 1..=1024));
                regs::SRSS.clk_eco_prescale().init(|r| {
                    r.eco_int_div()
                        .set(integer_divider - 1)
                        .eco_frac_div()
                        .set(fractional_divider)
                });
                regs::SRSS
                    .clk_eco_config()
                    .modify(|r| r.eco_div_enable().set(true));
                while !regs::SRSS.clk_eco_prescale().read().eco_div_enabled().get() {}
            } else {
                regs::SRSS
                    .clk_eco_config()
                    .modify(|r| r.eco_div_enable().set(false));
            }
            let source = match source {
                ClockLfIn::Ilo => LfclkSel::ILO,
                ClockLfIn::Wco => LfclkSel::WCO,
                #[cfg(mxs40ssrss)]
                ClockLfIn::Eco { .. } => LfclkSel::ECO_PRESCALER,
            };

            critical_section::with(|_cs| {
                // Unlock the WDT.
                let wdt_ctl = regs::SRSS.wdt_ctl().read();

                regs::SRSS
                    .wdt_ctl()
                    .write(wdt_ctl.wdt_lock().set(WdtLock::CLR_0));
                regs::SRSS
                    .wdt_ctl()
                    .write(wdt_ctl.wdt_lock().set(WdtLock::CLR_1));

                regs::SRSS
                    .clk_select()
                    .modify(|r| r.lfclk_sel().set(source));

                if wdt_ctl.wdt_lock().get() != WdtLock::new(0) {
                    regs::SRSS
                        .wdt_ctl()
                        .write(wdt_ctl.wdt_lock().set(WdtLock::SET_01));
                }
            });
        }
    }

    /// Returns the currently-selected source for the low-frequency clock.
    pub fn source(&self) -> ClockLfIn {
        use regs::srss::clk_select::LfclkSel;
        unsafe {
            match regs::SRSS.clk_select().read().lfclk_sel().get() {
                LfclkSel::ILO => ClockLfIn::Ilo,
                LfclkSel::WCO => ClockLfIn::Wco,
                #[cfg(mxs40ssrss)]
                LfclkSel::ECO_PRESCALER => {
                    let prescale = regs::SRSS.clk_eco_prescale().read();
                    ClockLfIn::Eco {
                        integer_divider: prescale.eco_int_div().get() + 1,
                        fractional_divider: prescale.eco_frac_div().get(),
                    }
                }
                _ => unreachable!(),
            }
        }
    }
}

/// The internal low-frequency oscillator.
///
/// The ILO is a low-power, low-accuracy 32,768 Hz oscillator that is available in all power modes
/// and can be used as a source for the low-frequency clock and RTC.
#[derive(Debug)]
pub struct Ilo<'a>(PhantomData<&'a mut ()>);

/// Configuration for the internal low-frequency oscillator.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct IloConfig {
    /// Whether the ILO is powered by the backup domain, which allows it to continue running in
    /// hibernate mode and during resets.
    pub backup_domain: bool,
}

impl Ilo<'_> {
    /// Unsafely creates a reference to the internal low-frequency oscillator. Does not set any
    /// configuration.
    ///
    /// # Safety
    ///
    /// The caller is responsible for ensuring the hardware is present on the device, configured
    /// correctly, and not accessed concurrently.
    pub const unsafe fn steal() -> Ilo<'static> {
        Ilo(PhantomData)
    }

    /// Configures the internal low-frequency oscillator.
    ///
    /// If `config` is `None`, the ILO is disabled.
    pub fn configure(&mut self, config: Option<&IloConfig>) {
        use regs::srss::wdt_ctl::WdtLock;
        unsafe {
            critical_section::with(|_cs| {
                // Unlock the WDT.
                let wdt_ctl = regs::SRSS.wdt_ctl().read();

                regs::SRSS
                    .wdt_ctl()
                    .write(wdt_ctl.wdt_lock().set(WdtLock::CLR_0));
                regs::SRSS
                    .wdt_ctl()
                    .write(wdt_ctl.wdt_lock().set(WdtLock::CLR_1));

                regs::SRSS.clk_ilo_config().init(|r| {
                    r.enable()
                        .set(config.is_some())
                        .ilo_backup()
                        .set(config.is_some_and(|c| c.backup_domain))
                });

                if wdt_ctl.wdt_lock().get() != WdtLock::new(0) {
                    regs::SRSS
                        .wdt_ctl()
                        .write(wdt_ctl.wdt_lock().set(WdtLock::SET_01));
                }
            });
        }
    }
}

/// The watch crystal oscillator.
///
/// The WCO is a highly-accurate clock source that can drive an external 32,768 Hz watch crystal,
/// or be driven by an external clock signal on the WCO output pin. It is the primary clock source
/// for the RTC, and can also be used as source for the low-frequency clock. The WCO can be active
/// in all power modes.
#[derive(Debug)]
pub struct Wco<'a>(PhantomData<&'a mut ()>);

/// Configuration for the watch crystal oscillator.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WcoConfig {
    /// If false, drive an external crystal oscillator. If true, use an external clock signal.
    bypass: bool,
}

impl Wco<'_> {
    /// Unsafely creates a reference to the watch crystal oscillator. Does not set any configuration.
    ///
    /// # Safety
    ///
    /// The caller is responsible for ensuring the hardware is present on the device, configured
    /// correctly, and not accessed concurrently.
    pub const unsafe fn steal() -> Wco<'static> {
        Wco(PhantomData)
    }

    /// Configures the watch crystal oscillator.
    ///
    /// If `config` is `None`, the WCO is disabled.
    pub fn configure(&mut self, config: Option<&WcoConfig>) {
        unsafe {
            regs::BACKUP.ctl().modify(|r| {
                r.wco_en()
                    .set(config.is_some())
                    .wco_bypass()
                    .set(config.is_some_and(|c| c.bypass))
            });

            // Wait for the WCO to be enabled.
            if config.is_some() {
                #[cfg(mxs40ssrss)]
                while !regs::BACKUP.wco_status().read().wco_ok().get() {}

                #[cfg(mxs40srss)]
                while !regs::BACKUP.status().read().wco_ok().get() {}
            }
        }
    }
}