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
//! # Advanced high performance bus clocks
//!
//! ## Overview
//!
//! AHB clocks facilitate communication between the processor core and
//! peripherals on the AHB bus. To communicate with a peripheral, the
//! corresponding AHB clock must be enabled, which is done by setting a bit in
//! the `AHBMASK` register.
//!
//! In this module, *enabled* AHB clocks are represented by the [`AhbClk<A>`]
//! struct, where the type parameter `A` is a type that implements [`AhbId`] and
//! corresponds to one of the bits in the `AHBMASK` register.
//!
//! While most other clocks in the `clock` module are configured through
//! mutually exclusive registers, the [`AhbClk`]s share a single `AHBMASK`
//! register. This presents a challenge for memory safety. Specifically, if we
//! allowed unrestricted access to the `AHBMASK` register through each `AhbClk`,
//! we could create data races.
//!
//! To solve this problem, we restrict access to the `AHBMASK` register using
//! the [`Ahb`] type. `Ahb` was created to act as a gateway to the `AHBMASK`
//! register, allowing us to use `&mut Ahb` as compile-time proof of exclusive
//! access to it.
//!
//! ## Example
//!
//! Enabling and disabling the [`AhbClk`]s proceeds according to the principles
//! outlined in the [`clock` module documentation]. It is best shown with an
//! example.
//!
//! Let's start by using [`clock_system_at_reset`] to access the HAL clocking
//! structs.
//!
//! ```no_run
//! use atsamd_hal::{
//!     clock::v2::{
//!         clock_system_at_reset,
//!     },
//!     pac::Peripherals,
//! };
//! let mut pac = Peripherals::take().unwrap();
//! let (mut buses, clocks, tokens) = clock_system_at_reset(
//!     pac.OSCCTRL,
//!     pac.OSC32KCTRL,
//!     pac.GCLK,
//!     pac.MCLK,
//!     &mut pac.NVMCTRL,
//! );
//! ```
//!
//! All AHB clocks are enabled at power-on reset. We can find them in the
//! [`Clocks`] struct.
//!
//! ```no_run
//! # use atsamd_hal::{
//! #     clock::v2::{
//! #         clock_system_at_reset,
//! #     },
//! #     pac::Peripherals,
//! # };
//! # let mut pac = Peripherals::take().unwrap();
//! # let (mut buses, clocks, tokens) = clock_system_at_reset(
//! #     pac.OSCCTRL,
//! #     pac.OSC32KCTRL,
//! #     pac.GCLK,
//! #     pac.MCLK,
//! #     &mut pac.NVMCTRL,
//! # );
//! let ahb_qspi = clocks.ahbs.qspi;
//! ```
//!
//! To disable an `AhbClk`, we must have access to the [`Ahb`] bus type, which
//! is found in the [`Buses`] struct. As described above, [`Ahb`] mediates
//! access to the shared `AHBMASK` register. We call [`Ahb::disable`] to convert
//! an [`AhbClk`] into the corresponding [`AhbToken`].
//!
//! ```no_run
//! # use atsamd_hal::{
//! #     clock::v2::{
//! #         clock_system_at_reset,
//! #     },
//! #     pac::Peripherals,
//! # };
//! # let mut pac = Peripherals::take().unwrap();
//! # let (mut buses, clocks, tokens) = clock_system_at_reset(
//! #     pac.OSCCTRL,
//! #     pac.OSC32KCTRL,
//! #     pac.GCLK,
//! #     pac.MCLK,
//! #     &mut pac.NVMCTRL,
//! # );
//! # let ahb_qspi = clocks.ahbs.qspi;
//! let ahb_qspi = buses.ahb.disable(ahb_qspi);
//! ```
//!
//! To reenable an `AhbClk`, users must save the `AhbToken` and use it when
//! calling [`Ahb::enable`].
//!
//! The complete example is shown below.
//!
//! ```no_run
//! use atsamd_hal::{
//!     clock::v2::{
//!         clock_system_at_reset,
//!     },
//!     pac::Peripherals,
//! };
//! let mut pac = Peripherals::take().unwrap();
//! let (mut buses, clocks, tokens) = clock_system_at_reset(
//!     pac.OSCCTRL,
//!     pac.OSC32KCTRL,
//!     pac.GCLK,
//!     pac.MCLK,
//!     &mut pac.NVMCTRL,
//! );
//! let ahb_qspi = clocks.ahbs.qspi;
//! let ahb_qspi = buses.ahb.disable(ahb_qspi);
//! ```
//!
//! [`clock` module documentation]: super
//! [`clock_system_at_reset`]: super::clock_system_at_reset
//! [`Clocks`]: super::Clocks
//! [`Buses`]: super::Buses

use core::marker::PhantomData;

use bitflags;
use paste::paste;

use crate::pac::{mclk, MCLK};

use super::types::*;

//==============================================================================
// Ahb
//==============================================================================

/// AHB clock controller
///
/// As described in the [module-level documentation](self), this struct mediates
/// access to the shared `AHBMASK` register. Users can convert a disabled
/// [`AhbToken<A>`] into an enabled [`AhbClk<A>`] using [`Ahb::enable`], and
/// vice versa with [`Ahb::disable`].
pub struct Ahb(());

impl Ahb {
    /// Create a new instance of [`Ahb`]
    ///
    /// # Safety
    ///
    /// Because the `Ahb` mediates access to the `AHBMASK` register, it must be
    /// a singleton. There must never be two simulatenous instances of it at a
    /// time. See the notes on `Token` types and memory safety in the root of
    /// the `clock` module for more details.
    #[inline]
    pub(super) unsafe fn new() -> Self {
        Self(())
    }

    #[inline]
    fn ahbmask(&mut self) -> &mclk::AHBMASK {
        // Safety: The `Ahb` type has exclusive access to the `AHBMASK`
        // register. See the notes on `Token` types and memory safety in the
        // root of the `clock` module for more details.
        unsafe { &(*MCLK::PTR).ahbmask }
    }

    #[inline]
    fn enable_mask(&mut self, mask: AhbMask) {
        // Safety: The mask bits are derived from a `bitflags` struct, so they
        // are guaranteed to be valid.
        self.ahbmask()
            .modify(|r, w| unsafe { w.bits(r.bits() | mask.bits()) });
    }

    #[inline]
    fn disable_mask(&mut self, mask: AhbMask) {
        // Safety: The mask bits are derived from a `bitflags` struct, so they
        // are guaranteed to be valid.
        self.ahbmask()
            .modify(|r, w| unsafe { w.bits(r.bits() & !mask.bits()) });
    }

    /// Enable the corresponding AHB clock
    ///
    /// Consume an [`AhbToken`], enable the corresponding AHB clock and return
    /// an [`AhbClk`]. The `AhbClk` represents proof that the corresponding AHB
    /// clock has been enabled.
    #[inline]
    pub fn enable<A: AhbId>(&mut self, token: AhbToken<A>) -> AhbClk<A> {
        self.enable_mask(A::DYN.into());
        AhbClk::new(token)
    }

    /// Disable the corresponding AHB clock
    ///
    /// Consume the [`AhbClk`], disable the corresponding AHB clock and return
    /// the [`AhbToken`].
    #[inline]
    pub fn disable<A: AhbId>(&mut self, clock: AhbClk<A>) -> AhbToken<A> {
        self.disable_mask(A::DYN.into());
        clock.free()
    }
}

//==============================================================================
// AhbId
//==============================================================================

/// Type-level enum identifying one of the possible AHB clocks
///
/// The types implementing this trait are type-level variants of `AhbId`, and
/// they identify one of the possible AHB clocks, which can vary by chip. Each
/// type corresponds to a specific bit in the `AHBMASK` register.
///
/// `AhbId` is the type-level equivalent of [`DynAhbId`]. See the documentation
/// on [type-level programming] and specifically [type-level enums] for more
/// details.
///
/// [type-level programming]: crate::typelevel
/// [type-level enums]: crate::typelevel#type-level-enums
pub trait AhbId: crate::typelevel::Sealed {
    /// Corresponding [`DynAhbId`]
    const DYN: DynAhbId;
}

//==============================================================================
// AhbToken
//==============================================================================

/// Singleton token that can be exchanged for an [`AhbClk`]
///
/// As explained in the [`clock` module documentation](super), instances of
/// various `Token` types can be exchanged for actual clock types. They
/// represent clocks that are disabled.
///
/// The type parameter `A` is an [`AhbId`] indicating which AHB clock is
/// represented by this token. To enable the corresponding AHB clock, use the
/// [`Ahb::enable`] method.
pub struct AhbToken<A: AhbId> {
    id: PhantomData<A>,
}

impl<A: AhbId> AhbToken<A> {
    /// Create a new instance of [`AhbToken`]
    ///
    /// # Safety
    ///
    /// Each `AhbToken` is a singleton. There must never be two simulatenous
    /// instances with the same [`AhbId`]. See the notes on `Token` types and
    /// memory safety in the root of the `clock` module for more details.
    #[inline]
    unsafe fn new() -> Self {
        AhbToken { id: PhantomData }
    }
}

//==============================================================================
// AhbClk
//==============================================================================

/// An enabled AHB clock
///
/// An [`AhbClk`] represents an enabled AHB clock. The type parameter `A` is an
/// [`AhbId`], which corresponds to a particular bit in the `AHBMASK`
/// register. An `AhbClk` can be disabled with the [`Ahb::disable`] method.
pub struct AhbClk<A: AhbId> {
    token: AhbToken<A>,
}

impl<A: AhbId> AhbClk<A> {
    #[inline]
    fn new(token: AhbToken<A>) -> Self {
        AhbClk { token }
    }

    #[inline]
    fn free(self) -> AhbToken<A> {
        self.token
    }
}

//==============================================================================
// DynAhbId & AhbClks
//==============================================================================

macro_rules! define_ahb_types {
    (
        $(
            $( #[$( $cfg:tt )+] )?
            $Type:ident = $BIT:literal,
        )+
    ) => {
        paste! {
            bitflags::bitflags! {
                /// AHB clock register mask
                ///
                /// This is a [`bitflags`] struct with a binary representation
                /// exactly matching the `AHBMASK` register.
                struct AhbMask: u32 {
                    $(
                        $( #[$( $cfg )+] )?
                        const [<$Type:upper>] = 1 << $BIT;
                    )+
                }
            }

            /// Value-level enum identifying a single AHB clock
            ///
            /// Each variant of this enum corresponds to a specific bit in the
            /// `AHBMASK` register and identifies one of the possible AHB
            /// clocks, which can vary by chip.
            ///
            /// `DynAhbId` is the value-level equivalent of [`AhbId`].
            #[repr(u8)]
            pub enum DynAhbId {
                $(
                    $( #[$( $cfg )+] )?
                    $Type = $BIT,
                )+
            }

            impl From<DynAhbId> for AhbMask {
                #[inline]
                fn from(id: DynAhbId) -> AhbMask {
                    match id {
                        $(
                            $( #[$( $cfg )+] )?
                            DynAhbId::$Type => AhbMask::[<$Type:upper>],
                        )+
                    }
                }
            }

            $(
                $( #[$( $cfg )+] )?
                impl AhbId for $Type {
                    const DYN: DynAhbId = DynAhbId::$Type;
                }
            )+

            /// Set of all [`AhbClk`]s
            ///
            /// All [`AhbClk`]s are enabled at power-on reset.
            pub struct AhbClks {
                $(
                    $( #[$( $cfg )+] )?
                    pub [<$Type:snake>]: AhbClk<$Type>,
                )+
            }
            impl AhbClks {
                /// Create the set of [`AhbClk`]s
                ///
                /// # Safety
                ///
                /// All invariants of `AhbToken::new` must be upheld here.
                #[inline]
                pub(super) unsafe fn new() -> Self {
                    AhbClks {
                        $(
                            $( #[$( $cfg )+] )?
                            [<$Type:snake>]: AhbClk::new(AhbToken::new()),
                        )+
                    }
                }
            }
        }
    };
}

define_ahb_types!(
    Hpb0 = 0,
    Hpb1 = 1,
    Hpb2 = 2,
    Hpb3 = 3,
    Dsu = 4,
    NvmCtrl = 6,
    Cmcc = 8,
    Dmac = 9,
    Usb = 10,
    Pac = 12,
    Qspi = 13,
    #[cfg(any(feature = "same53", feature = "same54"))]
    Gmac = 14,
    Sdhc0 = 15,
    #[cfg(feature = "min-samd51n")]
    Sdhc1 = 16,
    #[cfg(any(feature = "same51", feature = "same53", feature = "same54"))]
    Can0 = 17,
    #[cfg(any(feature = "same51", feature = "same53", feature = "same54"))]
    Can1 = 18,
    Icm = 19,
    Pukcc = 20,
    Qspi2x = 21,
    NvmCtrlSmeeProm = 22,
    NvmCtrlCache = 23,
);