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
// 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::{marker::PhantomData, ops::Deref};

#[cfg(mxs40ssrss)]
use crate::regs::srss::mcwdt_struct::mcwdt_config::{WdtLowerMode0, WdtLowerMode1};
use crate::{
    regs::{
        self, AsPtr, RegisterValue,
        srss::{
            McwdtStruct,
            mcwdt_struct::{
                mcwdt_config::{WdtMode0, WdtMode1, WdtMode2},
                mcwdt_lock,
            },
        },
    },
    security::{self, Security, WithSecurity},
};

/// A multi-counter watchdog timer.
///
/// The MCWDT contains three independent sub-counters: two 16-bit counters and one 32-bit counter.
/// The sub-counters can be cascaded together (counter 0 into counter 1, counter 1 into counter 2).
/// The 16-bit counters can generate an interrupt or reset the device on match. The 32-bit counter
/// can only generate an interrupt.
///
#[cfg_attr(
    mxs40ssrss,
    doc = "The 16-bit sub-counters additionally support a configurable lower limit; servicing"
)]
#[cfg_attr(
    mxs40ssrss,
    doc = "the watchdog before the counter reaches the lower limit can raise an interrupt or"
)]
#[cfg_attr(mxs40ssrss, doc = "reset the device.")]
///
/// `N` selects which MCWDT instance is driven.
#[non_exhaustive]
#[derive(Debug)]
pub struct MultiWdt<const N: u8, Sec: Security = security::Default>(Sec);

impl<const N: u8> MultiWdt<N> {
    /// Unsafely creates the MCWDT driver instance.
    ///
    /// # 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 {
        cfg_select! {
            not(mcwdt1) => {
                const { assert!(N == 0, "this device only has a single MCWDT") };
            }
            _ => {}
        }
        Self(security::DEFAULT)
    }
}

impl<const N: u8, Sec: Security> MultiWdt<N, Sec> {
    /// Changes the security attribute which will be used to access this MCWDT.
    pub const fn with_security<New: Security>(self, sec: New) -> MultiWdt<N, New> {
        MultiWdt(sec)
    }

    #[inline(always)]
    fn regs(&self) -> McwdtStruct {
        cfg_select! {
            not(mcwdt1) => {
                let _ = N;
                regs::SRSS.mcwdt_struct().with_security(self.0)
            }
            _ => {
                regs::SRSS.mcwdt_struct().get(N as usize).with_security(self.0)
            }
        }
    }

    #[inline(always)]
    fn erased(&self) -> AnyMultiWdt<'_> {
        AnyMultiWdt {
            regs: self.regs(),
            _p: PhantomData,
        }
    }

    /// Type-erases this MCWDT, returning an `AnyMultiWdt` with the static lifetime.
    pub fn into_erased(self) -> AnyMultiWdt<'static> {
        AnyMultiWdt {
            regs: self.regs(),
            _p: PhantomData,
        }
    }

    /// Type-erases this MCWDT, returning an `AnyMultiWdt` with a borrowed lifetime.
    pub fn as_erased(&mut self) -> AnyMultiWdt<'_> {
        self.erased()
    }

    /// Unlocks the MCWDT, allowing writes to its configuration registers.
    pub fn unlock(&mut self) -> UnlockedMultiWdt<'_, N, Sec> {
        self.as_erased().unlock();
        UnlockedMultiWdt {
            inner: Self(self.0),
            _p: PhantomData,
        }
    }

    /// Unlocks the MCWDT, consuming `self`.
    pub fn into_unlocked(mut self) -> UnlockedMultiWdt<'static, N, Sec> {
        self.unlock();
        UnlockedMultiWdt {
            inner: Self(self.0),
            _p: PhantomData,
        }
    }

    /// Returns the current values of the two 16-bit sub-counters.
    pub fn counters_16bit(&self) -> (u16, u16) {
        self.erased().counters_16bit()
    }

    /// Returns the current value of the 32-bit sub-counter.
    pub fn counter_32bit(&self) -> u32 {
        self.erased().counter_32bit()
    }

    /// Returns the current MCWDT configuration.
    pub fn config(&self) -> Config {
        self.erased().config()
    }

    /// Returns the lower limits for the two 16-bit sub-counters.
    ///
    /// Servicing the watchdog before a sub-counter reaches its lower limit triggers the action
    /// configured in [`Config::lower_mode_16bit_0`]/[`Config::lower_mode_16bit_1`].
    #[cfg(mxs40ssrss)]
    pub fn lower_limits(&self) -> (u16, u16) {
        self.erased().lower_limits()
    }

    /// Waits for any pending MCWDT control updates to take effect.
    ///
    /// Writes to [`set_control`][UnlockedMultiWdt::set_control] are applied asynchronously over a
    /// small number of LFCLK cycles. This method blocks until none of the sub-counters have a
    /// pending reset and the enable state of every sub-counter matches its requested state.
    pub fn wait_control(&self) {
        self.erased().wait_control()
    }

    /// Returns the set of pending MCWDT interrupts.
    pub fn requested_interrupts(&self) -> InterruptSet {
        self.erased().requested_interrupts()
    }

    /// Returns the set of pending and unmasked MCWDT interrupts.
    pub fn masked_interrupts(&self) -> InterruptSet {
        self.erased().masked_interrupts()
    }
}

/// An MCWDT that has been unlocked, allowing writes to its configuration registers.
#[derive(Debug)]
pub struct UnlockedMultiWdt<'a, const N: u8, Sec: Security = security::Default> {
    inner: MultiWdt<N, Sec>,
    _p: PhantomData<&'a mut MultiWdt<N>>,
}

impl<const N: u8, Sec: Security> Deref for UnlockedMultiWdt<'_, N, Sec> {
    type Target = MultiWdt<N, Sec>;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<'a, const N: u8> UnlockedMultiWdt<'a, N> {
    /// Changes the security attribute which will be used to access this MCWDT.
    pub fn with_security<New: Security>(self, sec: New) -> UnlockedMultiWdt<'a, N, New> {
        UnlockedMultiWdt {
            inner: self.inner.with_security(sec),
            _p: PhantomData,
        }
    }

    #[inline(always)]
    fn erased(&mut self) -> AnyUnlockedMultiWdt<'_> {
        AnyUnlockedMultiWdt {
            regs: self.regs(),
            _p: PhantomData,
        }
    }

    /// Type-erases this unlocked MCWDT, returning an `AnyUnlockedMultiWdt` with a borrowed
    /// lifetime.
    pub fn as_erased(&mut self) -> AnyUnlockedMultiWdt<'_> {
        self.erased()
    }

    /// Sets the MCWDT configuration register.
    ///
    /// Configures the per-sub-counter match action, cascade chain, clear-on-match behavior, and
    /// the bit position used by the 32-bit sub-counter to generate matches.
    pub fn set_config(&mut self, config: Config) {
        self.erased().set_config(config)
    }

    /// Sets the MCWDT control register.
    ///
    /// Writes are applied asynchronously; use [`wait_control`][MultiWdt::wait_control] to block
    /// until they take effect.
    pub fn set_control(&mut self, ctl: Control) {
        self.erased().set_control(ctl)
    }

    /// Sets the match values for the two 16-bit sub-counters.
    pub fn set_match_16bit(&mut self, counter0: u16, counter1: u16) {
        self.erased().set_match_16bit(counter0, counter1)
    }

    /// Sets the lower limits for the two 16-bit sub-counters.
    ///
    /// See [`MultiWdt::lower_limits`] for details.
    #[cfg(mxs40ssrss)]
    pub fn set_lower_limits(&mut self, counter0: u16, counter1: u16) {
        self.erased().set_lower_limits(counter0, counter1)
    }

    /// Enables the given set of MCWDT interrupts.
    pub fn enable_interrupts(&mut self, interrupts: impl Into<InterruptSet>) {
        self.erased().enable_interrupts(interrupts)
    }

    /// Disables the given set of MCWDT interrupts.
    pub fn disable_interrupts(&mut self, interrupts: impl Into<InterruptSet>) {
        self.erased().disable_interrupts(interrupts)
    }

    /// Sets the full set of enabled MCWDT interrupts, replacing the previous mask.
    pub fn set_enabled_interrupts(&mut self, interrupts: impl Into<InterruptSet>) {
        self.erased().set_enabled_interrupts(interrupts)
    }

    /// Clears the given set of pending MCWDT interrupts.
    pub fn clear_interrupts(&mut self, interrupts: impl Into<InterruptSet>) {
        self.erased().clear_interrupts(interrupts)
    }
}

impl<const N: u8> UnlockedMultiWdt<'static, N> {
    /// Unsafely creates an unlocked MCWDT driver instance.
    ///
    /// # 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 {
        unsafe {
            UnlockedMultiWdt {
                inner: MultiWdt::<N>::steal(),
                _p: PhantomData,
            }
        }
    }
}

impl<const N: u8, Sec: Security> UnlockedMultiWdt<'static, N, Sec> {
    /// Type-erases this unlocked MCWDT, returning an `AnyUnlockedMultiWdt` with the static
    /// lifetime.
    pub fn into_erased(self) -> AnyUnlockedMultiWdt<'static> {
        AnyUnlockedMultiWdt {
            regs: self.regs(),
            _p: PhantomData,
        }
    }

    /// Locks the MCWDT.
    pub fn lock(self) {
        unsafe {
            self.regs()
                .mcwdt_lock()
                .modify(|r| r.mcwdt_lock().set(mcwdt_lock::McwdtLock::SET_01))
        }
    }

    /// Consumes `self` and returns a locked MCWDT.
    pub fn into_locked(self) -> MultiWdt<N> {
        self.lock();
        unsafe { MultiWdt::steal() }
    }
}

impl<const N: u8> From<MultiWdt<N>> for AnyMultiWdt<'static> {
    fn from(wdt: MultiWdt<N>) -> Self {
        wdt.into_erased()
    }
}

impl<'a, const N: u8> From<&'a mut MultiWdt<N>> for AnyMultiWdt<'a> {
    fn from(wdt: &'a mut MultiWdt<N>) -> Self {
        wdt.as_erased()
    }
}

/// A bit set of MCWDT sub-counter interrupts.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct InterruptSet(u8);

impl InterruptSet {
    /// Creates an empty `InterruptSet`.
    pub const fn new() -> Self {
        Self(0)
    }

    /// Creates an `InterruptSet` containing every sub-counter interrupt.
    pub const fn all() -> Self {
        Self(0b111)
    }

    /// Returns whether this set contains the interrupt for the given sub-counter.
    pub const fn contains(self, subcounter: SubCounter) -> bool {
        self.0 & (1 << subcounter as u8) != 0
    }

    /// Inserts the interrupt for the given sub-counter, returning the new set.
    pub const fn insert(mut self, subcounter: SubCounter) -> Self {
        self.0 |= 1 << subcounter as u8;
        self
    }

    /// Removes the interrupt for the given sub-counter, returning the new set.
    pub const fn remove(mut self, subcounter: SubCounter) -> Self {
        self.0 &= !(1 << subcounter as u8);
        self
    }
}

impl From<SubCounter> for InterruptSet {
    fn from(value: SubCounter) -> Self {
        Self::new().insert(value)
    }
}

/// MCWDT configuration.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct Config {
    /// Action taken when the first 16-bit sub-counter matches.
    pub mode_16bit_0: MatchAction,
    /// Cascade behavior for the first 16-bit sub-counter into the second.
    pub cascade_0_1: CascadeMode,
    /// Clear the first 16-bit sub-counter when it matches.
    pub clear_on_match_0: bool,
    /// Action taken when the second 16-bit sub-counter matches.
    pub mode_16bit_1: MatchAction,
    /// Cascade behavior for the second 16-bit sub-counter into the 32-bit sub-counter.
    pub cascade_1_2: CascadeMode,
    /// Clear the second 16-bit sub-counter when it matches.
    pub clear_on_match_1: bool,
    /// If `Some(bit)`, raise an interrupt one LFCLK cycle after `bit` (0..=31) of the 32-bit
    /// sub-counter toggles. If `None`, the 32-bit sub-counter free-runs without raising
    /// interrupts.
    pub interrupt_bit_32bit: Option<u8>,
    /// Action taken when the watchdog is serviced before the first 16-bit sub-counter reaches
    /// its lower limit.
    #[cfg(mxs40ssrss)]
    pub lower_mode_16bit_0: LowerMatchAction,
    /// When [`cascade_0_1`][Self::cascade_0_1] is not [`CascadeMode::Independent`], only consider
    /// the cascade match condition satisfied when sub-counters 0 and 1 match simultaneously,
    /// instead of just sub-counter 1.
    #[cfg(mxs40ssrss)]
    pub require_double_match_0_1: bool,
    /// Action taken when the watchdog is serviced before the second 16-bit sub-counter reaches
    /// its lower limit.
    #[cfg(mxs40ssrss)]
    pub lower_mode_16bit_1: LowerMatchAction,
    /// When [`cascade_1_2`][Self::cascade_1_2] is not [`CascadeMode::Independent`], only consider
    /// the cascade match condition satisfied when sub-counters 1 and 2 match simultaneously,
    /// instead of just sub-counter 2.
    #[cfg(mxs40ssrss)]
    pub require_double_match_1_2: bool,
}

/// Action taken by a 16-bit MCWDT sub-counter on a match condition.
#[repr(u8)]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum MatchAction {
    /// Do nothing on match.
    #[default]
    None = 0,
    /// Raise an interrupt on match.
    Interrupt = 1,
    /// Reset the device on match.
    Reset = 2,
    /// Raise an interrupt on match; reset the device if three consecutive matches are unserviced.
    InterruptThenReset = 3,
}

/// Action taken by a 16-bit MCWDT sub-counter when the watchdog is serviced before its lower
/// limit is reached.
#[cfg(mxs40ssrss)]
#[repr(u8)]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum LowerMatchAction {
    /// Do nothing.
    #[default]
    None = 0,
    /// Raise an interrupt.
    Interrupt = 1,
    /// Reset the device.
    Reset = 2,
}

/// How an MCWDT sub-counter increments its successor in a cascade chain.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum CascadeMode {
    /// The sub-counters are not cascaded.
    #[default]
    Independent,
    /// Increment the successor when the current sub-counter matches.
    CarryOnMatch,
    /// Increment the successor when the current sub-counter rolls over.
    #[cfg(mxs40ssrss)]
    CarryOnRollover,
}

impl CascadeMode {
    #[inline(always)]
    fn from_bits(cascade: bool, #[cfg(mxs40ssrss)] carry_on_rollover: bool) -> Self {
        if !cascade {
            return Self::Independent;
        }
        cfg_select! {
            mxs40ssrss => {
                if carry_on_rollover {
                    Self::CarryOnRollover
                } else {
                    Self::CarryOnMatch
                }
            }
            _ => Self::CarryOnMatch,
        }
    }

    /// Returns `(cascade, carry_on_rollover)`.
    #[inline(always)]
    fn to_bits(self) -> (bool, bool) {
        match self {
            Self::Independent => (false, false),
            Self::CarryOnMatch => (true, false),
            #[cfg(mxs40ssrss)]
            Self::CarryOnRollover => (true, true),
        }
    }
}

/// MCWDT control register state.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct Control {
    /// Request a reset of the first 16-bit sub-counter.
    pub reset_16bit_0: bool,
    /// Enable the first 16-bit sub-counter.
    pub enable_16bit_0: bool,
    /// Request a reset of the second 16-bit sub-counter.
    pub reset_16bit_1: bool,
    /// Enable the second 16-bit sub-counter.
    pub enable_16bit_1: bool,
    /// Request a reset of the 32-bit sub-counter.
    pub reset_32bit: bool,
    /// Enable the 32-bit sub-counter.
    pub enable_32bit: bool,
}

/// Identifies one of the MCWDT sub-counters.
#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[allow(non_camel_case_types)]
pub enum SubCounter {
    /// The first 16-bit sub-counter.
    _16bit_0 = 0,
    /// The second 16-bit sub-counter.
    _16bit_1 = 1,
    /// The 32-bit sub-counter.
    _32bit = 2,
}

/// A type-erased multi-counter watchdog timer. The MCWDT instance is tracked at runtime.
///
/// See [`MultiWdt`] for documentation on the MCWDT hardware.
#[non_exhaustive]
pub struct AnyMultiWdt<'a> {
    regs: McwdtStruct,
    _p: PhantomData<&'a ()>,
}

impl core::fmt::Debug for AnyMultiWdt<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("AnyMultiWdt")
            .field("regs", &self.regs.as_ptr())
            .finish()
    }
}

impl<'a> AnyMultiWdt<'a> {
    /// Changes the security attribute which will be used to access this MCWDT.
    pub fn with_security<Sec: Security>(self, sec: Sec) -> AnyMultiWdt<'a> {
        AnyMultiWdt {
            regs: self.regs.with_security(sec),
            _p: PhantomData,
        }
    }

    /// Reborrows this MCWDT with a shorter lifetime.
    pub fn reborrow(&mut self) -> AnyMultiWdt<'_> {
        AnyMultiWdt {
            regs: self.regs,
            _p: PhantomData,
        }
    }

    /// Unlocks the MCWDT, allowing writes to its configuration registers.
    pub fn unlock(&mut self) -> AnyUnlockedMultiWdt<'_> {
        unsafe {
            self.regs
                .mcwdt_lock()
                .init(|r| r.mcwdt_lock().set(mcwdt_lock::McwdtLock::CLR_0));
            self.regs
                .mcwdt_lock()
                .init(|r| r.mcwdt_lock().set(mcwdt_lock::McwdtLock::CLR_1));
        }
        AnyUnlockedMultiWdt {
            regs: self.regs,
            _p: PhantomData,
        }
    }

    /// Unlocks the MCWDT, consuming `self`.
    pub fn into_unlocked(mut self) -> AnyUnlockedMultiWdt<'static> {
        self.unlock();
        AnyUnlockedMultiWdt {
            regs: self.regs,
            _p: PhantomData,
        }
    }

    /// Returns the current values of the two 16-bit sub-counters.
    pub fn counters_16bit(&self) -> (u16, u16) {
        let v = unsafe { self.regs.mcwdt_cntlow().read() };
        (v.wdt_ctr0().get(), v.wdt_ctr1().get())
    }

    /// Returns the current value of the 32-bit sub-counter.
    pub fn counter_32bit(&self) -> u32 {
        unsafe { self.regs.mcwdt_cnthigh().read().wdt_ctr2().get() }
    }

    /// Returns the current MCWDT configuration.
    pub fn config(&self) -> Config {
        unsafe {
            let v = self.regs.mcwdt_config().read();
            Config {
                mode_16bit_0: core::mem::transmute::<u8, MatchAction>(v.wdt_mode0().get().0),
                cascade_0_1: CascadeMode::from_bits(
                    v.wdt_cascade0_1().get(),
                    #[cfg(mxs40ssrss)]
                    v.wdt_carry0_1().get(),
                ),
                clear_on_match_0: v.wdt_clear0().get(),
                mode_16bit_1: core::mem::transmute::<u8, MatchAction>(v.wdt_mode1().get().0),
                cascade_1_2: CascadeMode::from_bits(
                    v.wdt_cascade1_2().get(),
                    #[cfg(mxs40ssrss)]
                    v.wdt_carry1_2().get(),
                ),
                clear_on_match_1: v.wdt_clear1().get(),
                interrupt_bit_32bit: (v.wdt_mode2().get().0 != 0).then(|| v.wdt_bits2().get()),
                #[cfg(mxs40ssrss)]
                lower_mode_16bit_0: core::mem::transmute::<u8, LowerMatchAction>(
                    v.wdt_lower_mode0().get().0,
                ),
                #[cfg(mxs40ssrss)]
                require_double_match_0_1: v.wdt_match0_1().get(),
                #[cfg(mxs40ssrss)]
                lower_mode_16bit_1: core::mem::transmute::<u8, LowerMatchAction>(
                    v.wdt_lower_mode1().get().0,
                ),
                #[cfg(mxs40ssrss)]
                require_double_match_1_2: v.wdt_match1_2().get(),
            }
        }
    }

    /// Returns the lower limits for the two 16-bit sub-counters.
    ///
    /// Servicing the watchdog before a sub-counter reaches its lower limit triggers the action
    /// configured in [`Config::lower_mode_16bit_0`]/[`Config::lower_mode_16bit_1`].
    #[cfg(mxs40ssrss)]
    pub fn lower_limits(&self) -> (u16, u16) {
        let v = unsafe { self.regs.mcwdt_lower_limit().read() };
        (v.wdt_lower_limit0().get(), v.wdt_lower_limit1().get())
    }

    /// Waits for any pending MCWDT control updates to take effect.
    ///
    /// Writes to [`set_control`][AnyUnlockedMultiWdt::set_control] are applied asynchronously over
    /// a small number of LFCLK cycles. This method blocks until none of the sub-counters have a
    /// pending reset and the enable state of every sub-counter matches its requested state.
    pub fn wait_control(&self) {
        loop {
            let v = unsafe { self.regs.mcwdt_ctl().read() };

            if v.wdt_reset0().get() || v.wdt_reset1().get() || v.wdt_reset2().get() {
                continue;
            }

            if v.wdt_enable0().get() != v.wdt_enabled0().get() {
                continue;
            }
            if v.wdt_enable1().get() != v.wdt_enabled1().get() {
                continue;
            }
            if v.wdt_enable2().get() != v.wdt_enabled2().get() {
                continue;
            }

            break;
        }
    }

    /// Returns the set of pending MCWDT interrupts.
    pub fn requested_interrupts(&self) -> InterruptSet {
        unsafe {
            let bits = self.regs.mcwdt_intr().read().get_raw();
            InterruptSet(bits as u8 & InterruptSet::all().0)
        }
    }

    /// Returns the set of pending and unmasked MCWDT interrupts.
    pub fn masked_interrupts(&self) -> InterruptSet {
        unsafe {
            let bits = self.regs.mcwdt_intr_masked().read().get_raw();
            InterruptSet(bits as u8 & InterruptSet::all().0)
        }
    }
}

/// A type-erased unlocked MCWDT, allowing writes to its configuration registers.
pub struct AnyUnlockedMultiWdt<'a> {
    regs: McwdtStruct,
    _p: PhantomData<&'a ()>,
}

impl core::fmt::Debug for AnyUnlockedMultiWdt<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("AnyUnlockedMultiWdt")
            .field("regs", &self.regs.as_ptr())
            .finish()
    }
}

impl Deref for AnyUnlockedMultiWdt<'_> {
    type Target = AnyMultiWdt<'static>;

    fn deref(&self) -> &Self::Target {
        // SAFETY: AnyMultiWdt and AnyUnlockedMultiWdt have identical layout (regs + PhantomData).
        unsafe { &*(self as *const Self as *const AnyMultiWdt<'static>) }
    }
}

impl<'a> AnyUnlockedMultiWdt<'a> {
    /// Changes the security attribute which will be used to access this MCWDT.
    pub fn with_security<Sec: Security>(self, sec: Sec) -> AnyMultiWdt<'a> {
        AnyMultiWdt {
            regs: self.regs.with_security(sec),
            _p: PhantomData,
        }
    }

    /// Reborrows this MCWDT with a shorter lifetime.
    pub fn reborrow(&mut self) -> AnyUnlockedMultiWdt<'_> {
        AnyUnlockedMultiWdt {
            regs: self.regs,
            _p: PhantomData,
        }
    }

    /// Sets the MCWDT configuration register.
    ///
    /// Configures the per-sub-counter match action, cascade chain, clear-on-match behavior, and
    /// the bit position used by the 32-bit sub-counter to generate matches.
    pub fn set_config(&mut self, config: Config) {
        let (mode_32bit, bits_32bit) = match config.interrupt_bit_32bit {
            Some(bit) => {
                debug_assert!(bit <= 31, "interrupt_bit_32bit must be at most 31");
                (1, bit)
            }
            None => (0, 0),
        };
        let (cascade_0_1, carry_0_1) = config.cascade_0_1.to_bits();
        let (cascade_1_2, carry_1_2) = config.cascade_1_2.to_bits();
        let _ = (carry_0_1, carry_1_2);
        unsafe {
            self.regs.mcwdt_config().init(|r| {
                let r = r
                    .wdt_mode0()
                    .set(WdtMode0::new(config.mode_16bit_0 as u8))
                    .wdt_clear0()
                    .set(config.clear_on_match_0)
                    .wdt_cascade0_1()
                    .set(cascade_0_1)
                    .wdt_mode1()
                    .set(WdtMode1::new(config.mode_16bit_1 as u8))
                    .wdt_clear1()
                    .set(config.clear_on_match_1)
                    .wdt_cascade1_2()
                    .set(cascade_1_2)
                    .wdt_mode2()
                    .set(WdtMode2::new(mode_32bit))
                    .wdt_bits2()
                    .set(bits_32bit);
                cfg_select! {
                    mxs40ssrss => {
                        r.wdt_carry0_1()
                            .set(carry_0_1)
                            .wdt_match0_1()
                            .set(config.require_double_match_0_1)
                            .wdt_lower_mode0()
                            .set(WdtLowerMode0::new(config.lower_mode_16bit_0 as u8))
                            .wdt_carry1_2()
                            .set(carry_1_2)
                            .wdt_match1_2()
                            .set(config.require_double_match_1_2)
                            .wdt_lower_mode1()
                            .set(WdtLowerMode1::new(config.lower_mode_16bit_1 as u8))
                    }
                    _ => r,
                }
            })
        }
    }

    /// Sets the MCWDT control register.
    ///
    /// Writes are applied asynchronously; use [`wait_control`][AnyMultiWdt::wait_control] to block
    /// until they take effect.
    pub fn set_control(&mut self, ctl: Control) {
        unsafe {
            self.regs.mcwdt_ctl().init(|r| {
                r.wdt_reset0()
                    .set(ctl.reset_16bit_0)
                    .wdt_enable0()
                    .set(ctl.enable_16bit_0)
                    .wdt_reset1()
                    .set(ctl.reset_16bit_1)
                    .wdt_enable1()
                    .set(ctl.enable_16bit_1)
                    .wdt_reset2()
                    .set(ctl.reset_32bit)
                    .wdt_enable2()
                    .set(ctl.enable_32bit)
            })
        }
    }

    /// Sets the match values for the two 16-bit sub-counters.
    pub fn set_match_16bit(&mut self, counter0: u16, counter1: u16) {
        unsafe {
            self.regs
                .mcwdt_match()
                .init(|r| r.wdt_match0().set(counter0).wdt_match1().set(counter1));
        }
    }

    /// Sets the lower limits for the two 16-bit sub-counters.
    ///
    /// See [`AnyMultiWdt::lower_limits`] for details.
    #[cfg(mxs40ssrss)]
    pub fn set_lower_limits(&mut self, counter0: u16, counter1: u16) {
        unsafe {
            self.regs.mcwdt_lower_limit().init(|r| {
                r.wdt_lower_limit0()
                    .set(counter0)
                    .wdt_lower_limit1()
                    .set(counter1)
            });
        }
    }

    /// Enables the given set of MCWDT interrupts.
    pub fn enable_interrupts(&mut self, interrupts: impl Into<InterruptSet>) {
        let mask = interrupts.into().0 as u32;
        unsafe {
            self.regs
                .mcwdt_intr_mask()
                .modify(|r| r.set_raw(r.get_raw() | mask));
        }
    }

    /// Disables the given set of MCWDT interrupts.
    pub fn disable_interrupts(&mut self, interrupts: impl Into<InterruptSet>) {
        let mask = interrupts.into().0 as u32;
        unsafe {
            self.regs
                .mcwdt_intr_mask()
                .modify(|r| r.set_raw(r.get_raw() & !mask));
        }
    }

    /// Sets the full set of enabled MCWDT interrupts, replacing the previous mask.
    pub fn set_enabled_interrupts(&mut self, interrupts: impl Into<InterruptSet>) {
        let mask = interrupts.into().0 as u32;
        unsafe {
            self.regs.mcwdt_intr_mask().init(|r| r.set_raw(mask));
        }
    }

    /// Clears the given set of pending MCWDT interrupts.
    pub fn clear_interrupts(&mut self, interrupts: impl Into<InterruptSet>) {
        let mask = interrupts.into().0 as u32;
        unsafe {
            self.regs.mcwdt_intr().init(|r| r.set_raw(mask));
        }
    }
}

impl AnyUnlockedMultiWdt<'static> {
    /// Locks the MCWDT.
    pub fn lock(self) {
        unsafe {
            self.regs
                .mcwdt_lock()
                .modify(|r| r.mcwdt_lock().set(mcwdt_lock::McwdtLock::SET_01))
        }
    }

    /// Consumes `self` and returns a locked type-erased MCWDT.
    pub fn into_locked(self) -> AnyMultiWdt<'static> {
        let regs = self.regs;
        self.lock();
        AnyMultiWdt {
            regs,
            _p: PhantomData,
        }
    }
}