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
//! # Clocking API v1
//!
//! Configuring the system clock sources. You will typically need to create an
//! instance of `GenericClockController` before you can set up most of the
//! peripherals on the atsamd51 device. The other types in this module are used
//! to enforce at compile time that the peripherals have been correctly
//! configured.
#![allow(clippy::from_over_into)]

use crate::clock::v2::pclk::{ids::*, Pclk, PclkSourceId};
use crate::pac::gclk::genctrl::SRC_A::*;
use crate::pac::gclk::pchctrl::GEN_A::*;
use crate::pac::{self, GCLK, MCLK, NVMCTRL, OSC32KCTRL, OSCCTRL};
use crate::sercom::*;
use crate::time::{Hertz, MegaHertz};

pub type ClockGenId = pac::gclk::pchctrl::GEN_A;
pub type ClockSource = pac::gclk::genctrl::SRC_A;

#[allow(non_camel_case_types)]
pub enum ClockId {
    DFLL48 = 0,
    FDPLL0,
    FDPLL1,
    SLOW_32K,
    EIC,
    FREQM_MSR,
    FREQM_REF,
    SERCOM0_CORE,
    SERCOM1_CORE,
    TC0_TC1,
    USB,
    EVSYS0,
    EVSYS1,
    EVSYS2,
    EVSYS3,
    EVSYS4,
    EVSYS5,
    EVSYS6,
    EVSYS7,
    EVSYS8,
    EVSYS9,
    EVSYS10,
    EVSYS11,
    SERCOM2_CORE,
    SERCOM3_CORE,
    TCC0_TCC1,
    TC2_TC3,
    CAN0,
    CAN1,
    TCC2_TCC3,
    TC4_TC5,
    PDEC,
    AC,
    CCL,
    SERCOM4_CORE,
    SERCOM5_CORE,
    SERCOM6_CORE,
    SERCOM7_CORE,
    TCC4,
    TC6_TC7,
    ADC0,
    ADC1,
    DAC,
    I2S0,
    I2S1,
    SDHC0,
    SDHC1,
    CM4_TRACE,
}

impl From<ClockId> for u8 {
    fn from(clock: ClockId) -> u8 {
        clock as u8
    }
}

/// Represents a configured clock generator.
/// Can be converted into the effective clock frequency.
/// Its primary purpose is to be passed in to methods
/// such as `GenericClockController::tcc2_tc3` to configure
/// the clock for a peripheral.
//#[derive(Clone, Copy)]
pub struct GClock {
    gclk: ClockGenId,
    freq: Hertz,
}

impl Into<Hertz> for GClock {
    fn into(self) -> Hertz {
        self.freq
    }
}

struct State {
    gclk: GCLK,
}

impl State {
    fn reset_gclk(&mut self) {
        self.gclk.ctrla.write(|w| w.swrst().set_bit());
        while self.gclk.ctrla.read().swrst().bit_is_set() || self.gclk.syncbusy.read().bits() != 0 {
        }
    }

    fn wait_for_sync(&mut self) {
        while self.gclk.syncbusy.read().bits() != 0 {}
    }

    fn set_gclk_divider_and_source(
        &mut self,
        gclk: ClockGenId,
        divider: u16,
        src: ClockSource,
        improve_duty_cycle: bool,
    ) {
        // validate the divisor factor based on gclk ID (see 14.8.3)
        let mut divisor_invalid = false;
        if gclk == GCLK1 {
            if divider as u32 >= 2_u32.pow(16) {
                divisor_invalid = true;
            }
        } else if divider >= 2_u16.pow(8) {
            divisor_invalid = true;
        }
        if divisor_invalid {
            panic!("invalid divisor {} for GCLK {}", divider, gclk as u8);
        }

        self.gclk.genctrl[u8::from(gclk) as usize].write(|w| unsafe {
            w.src().variant(src);
            w.div().bits(divider);
            // divide directly by divider, rather than 2^(n+1)
            w.divsel().clear_bit();
            w.idc().bit(improve_duty_cycle);
            w.genen().set_bit();
            w.oe().set_bit()
        });

        self.wait_for_sync();
    }

    fn enable_clock_generator(&mut self, clock: ClockId, generator: ClockGenId) {
        self.gclk.pchctrl[u8::from(clock) as usize].write(|w| unsafe {
            w.gen().bits(generator.into());
            w.chen().set_bit()
        });
        self.wait_for_sync();
    }

    fn configure_standby(&mut self, gclk: ClockGenId, enable: bool) {
        self.gclk.genctrl[u8::from(gclk) as usize].modify(|_, w| w.runstdby().bit(enable));
        self.wait_for_sync();
    }
}

/// `GenericClockController` encapsulates the GCLK hardware.
/// It provides a type safe way to configure the system clocks.
/// Initializing the `GenericClockController` instance configures
/// the system to run at 120MHz by taking the DFLL48
/// and feeding it into the DPLL0 hardware which multiplies the
/// signal by 2.5x.
pub struct GenericClockController {
    state: State,
    gclks: [Hertz; 12],
    used_clocks: u64,
}

impl GenericClockController {
    /// Reset the clock controller, configure the system to run
    /// at 120Mhz and reset various clock dividers.
    pub fn with_internal_32kosc(
        gclk: GCLK,
        mclk: &mut MCLK,
        osc32kctrl: &mut OSC32KCTRL,
        oscctrl: &mut OSCCTRL,
        nvmctrl: &mut NVMCTRL,
    ) -> Self {
        Self::new(gclk, mclk, osc32kctrl, oscctrl, nvmctrl, false)
    }

    /// Reset the clock controller, configure the system to run
    /// at 120Mhz and reset various clock dividers.
    pub fn with_external_32kosc(
        gclk: GCLK,
        mclk: &mut MCLK,
        osc32kctrl: &mut OSC32KCTRL,
        oscctrl: &mut OSCCTRL,
        nvmctrl: &mut NVMCTRL,
    ) -> Self {
        Self::new(gclk, mclk, osc32kctrl, oscctrl, nvmctrl, true)
    }

    fn new(
        gclk: GCLK,
        mclk: &mut MCLK,
        osc32kctrl: &mut OSC32KCTRL,
        oscctrl: &mut OSCCTRL,
        nvmctrl: &mut NVMCTRL,
        use_external_crystal: bool,
    ) -> Self {
        let mut state = State { gclk };

        set_flash_to_half_auto_wait_state(nvmctrl);
        enable_gclk_apb(mclk);

        if use_external_crystal {
            enable_external_32kosc(osc32kctrl);
            state.reset_gclk();
            state.set_gclk_divider_and_source(GCLK1, 1, XOSC32K, false);
        } else {
            enable_internal_32kosc(osc32kctrl);
            state.reset_gclk();
            state.set_gclk_divider_and_source(GCLK1, 1, OSCULP32K, false);
        }

        while state.gclk.syncbusy.read().genctrl().is_gclk0() {}

        #[cfg(feature = "usb")]
        configure_usb_correction(oscctrl);

        // GCLK5 set to 2MHz
        unsafe {
            state.gclk.genctrl[5].write(|w| {
                w.src().dfll();
                w.genen().set_bit();
                w.div().bits(24)
            });
        }

        while state.gclk.syncbusy.read().genctrl().is_gclk5() {}

        configure_and_enable_dpll0(oscctrl, &mut state.gclk);
        wait_for_dpllrdy(oscctrl);

        unsafe {
            // GCLK0 set to DPLL0 (120MHz)
            state.gclk.genctrl[0].write(|w| {
                w.src().dpll0();
                w.div().bits(1);
                w.oe().set_bit();
                w.genen().set_bit()
            });
        }

        while state.gclk.syncbusy.read().genctrl().is_gclk0() {}

        mclk.cpudiv.write(|w| w.div().div1());

        Self {
            state,
            gclks: [
                OSC120M_FREQ,
                OSC32K_FREQ,
                Hertz(0),
                Hertz(0),
                Hertz(0),
                MegaHertz(2).into(),
                Hertz(0),
                Hertz(0),
                Hertz(0),
                Hertz(0),
                Hertz(0),
                Hertz(0),
            ],
            used_clocks: 1u64 << u8::from(ClockId::FDPLL0),
        }
    }

    /// Returns a `GClock` for gclk0, the 120MHz oscillator.
    pub fn gclk0(&mut self) -> GClock {
        GClock {
            gclk: GCLK0,
            freq: self.gclks[0],
        }
    }

    /// Returns a `GClock` for gclk1, the 32KHz oscillator.
    pub fn gclk1(&mut self) -> GClock {
        GClock {
            gclk: GCLK1,
            freq: self.gclks[1],
        }
    }

    /// Returns the `GClock` for the specified clock generator.
    /// If that clock generator has not yet been configured,
    /// returns None.
    pub fn get_gclk(&mut self, gclk: ClockGenId) -> Option<GClock> {
        let idx = u8::from(gclk) as usize;
        if self.gclks[idx].0 == 0 {
            None
        } else {
            Some(GClock {
                gclk,
                freq: self.gclks[idx],
            })
        }
    }

    /// Configures a clock generator with the specified divider and
    /// source.
    /// `divider` is a linear divider to be applied to the clock
    /// source.  While the hardware also supports an exponential divider,
    /// this function doesn't expose that functionality at this time.
    /// `improve_duty_cycle` is a boolean that, when set to true, enables
    /// a 50/50 duty cycle for odd divider values.
    /// Returns a `GClock` for the configured clock generator.
    /// Returns `None` if the clock generator has already been configured.
    pub fn configure_gclk_divider_and_source(
        &mut self,
        gclk: ClockGenId,
        divider: u16,
        src: ClockSource,
        improve_duty_cycle: bool,
    ) -> Option<GClock> {
        let idx = u8::from(gclk) as usize;
        if self.gclks[idx].0 != 0 {
            return None;
        }
        self.state
            .set_gclk_divider_and_source(gclk, divider, src, improve_duty_cycle);
        let freq: Hertz = match src {
            XOSC32K | OSCULP32K => OSC32K_FREQ,
            GCLKGEN1 => self.gclks[1],
            DFLL => OSC48M_FREQ,
            DPLL0 => OSC120M_FREQ,
            XOSC0 | XOSC1 | GCLKIN | DPLL1 => unimplemented!(),
        };
        self.gclks[idx] = Hertz(freq.0 / divider as u32);
        Some(GClock { gclk, freq })
    }

    /// Enables or disables the given GClk from operation in standby.
    pub fn configure_standby(&mut self, gclk: ClockGenId, enable: bool) {
        self.state.configure_standby(gclk, enable)
    }
}

macro_rules! clock_generator {
    (
        $(
            $(#[$attr:meta])*
            ($id:ident, $Type:ident, $clock:ident, $PclkId:ident),
        )+
    ) => {

$(

/// A typed token that indicates that the clock for the peripheral(s)
/// with the matching name has been configured.
/// The effective clock frequency is available via the `freq` method,
/// or by converting the object into a `Hertz` instance.
/// The peripheral initialization code will typically require passing
/// in this object to prove at compile time that the clock has been
/// correctly initialized.
$(#[$attr])*
#[derive(Debug)]
pub struct $Type {
    freq: Hertz,
}

$(#[$attr])*
impl $Type {
    /// Returns the frequency of the configured clock
    pub fn freq(&self) -> Hertz {
        self.freq
    }
}
$(#[$attr])*
impl Into<Hertz> for $Type {
    fn into(self) -> Hertz {
        self.freq
    }
}

/// V2 to V1 compatibility layer that allows to convert V2 [`Pclk`] constructs
/// into corresponding V1 `*Clock` types. Thus, user can manage V1 clocking
/// compatible peripherals while using V2 clocking API
$(#[$attr])*
impl<I: PclkSourceId> core::convert::From<Pclk<$PclkId, I>> for $Type {
    fn from(pclk: Pclk<$PclkId, I>) -> Self {
        $Type {
            freq: pclk.freq()
        }
    }
}


)+

impl GenericClockController {
    $(
    /// Configure the clock for peripheral(s) that match the name
    /// of this function to use the specific clock generator.
    /// The `GClock` parameter may be one of default clocks
    /// return from `gclk0()`, `gclk1()` or a clock configured
    /// by the host application using the `configure_gclk_divider_and_source`
    /// method.
    /// Returns a typed token that proves that the clock has been configured;
    /// the peripheral initialization code will typically require that this
    /// clock token be passed in to ensure that the clock has been initialized
    /// appropriately.
    /// Returns `None` is the specified generic clock has already been
    /// configured.
    $(#[$attr])*
    pub fn $id(&mut self, generator: &GClock) -> Option<$Type> {
        let bits: u64 = 1 << u8::from(ClockId::$clock) as u64;
        if (self.used_clocks & bits) != 0 {
            return None;
        }
        self.used_clocks |= bits;

        self.state.enable_clock_generator(ClockId::$clock, generator.gclk);
        let freq = self.gclks[u8::from(generator.gclk) as usize];
        Some($Type{freq})
    }
    )+
}
    }
}

clock_generator!(
    (tc0_tc1, Tc0Tc1Clock, TC0_TC1, Tc0Tc1),
    (tcc0_tcc1, Tcc0Tcc1Clock, TCC0_TCC1, Tcc0Tcc1),
    (tc2_tc3, Tc2Tc3Clock, TC2_TC3, Tc2Tc3),
    (tcc2_tcc3, Tcc2Tcc3Clock, TCC2_TCC3, Tcc2Tcc3),
    #[cfg(feature = "min-samd51j")]
    (tc4_tc5, Tc4Tc5Clock, TC4_TC5, Tc4Tc5),
    #[cfg(feature = "min-samd51j")]
    (tcc4, Tcc4Clock, TCC4, Tcc4),
    #[cfg(feature = "min-samd51n")]
    (tc6_tc7, Tc6Tc7Clock, TC6_TC7, Tc6Tc7),
    (sercom0_core, Sercom0CoreClock, SERCOM0_CORE, Sercom0),
    (sercom1_core, Sercom1CoreClock, SERCOM1_CORE, Sercom1),
    (sercom2_core, Sercom2CoreClock, SERCOM2_CORE, Sercom2),
    (sercom3_core, Sercom3CoreClock, SERCOM3_CORE, Sercom3),
    (sercom4_core, Sercom4CoreClock, SERCOM4_CORE, Sercom4),
    (sercom5_core, Sercom5CoreClock, SERCOM5_CORE, Sercom5),
    #[cfg(feature = "min-samd51n")]
    (sercom6_core, Sercom6CoreClock, SERCOM6_CORE, Sercom6),
    #[cfg(feature = "min-samd51n")]
    (sercom7_core, Sercom7CoreClock, SERCOM7_CORE, Sercom7),
    (usb, UsbClock, USB, Usb),
    (adc0, Adc0Clock, ADC0, Adc0),
    (adc1, Adc1Clock, ADC1, Adc1),
    (eic, EicClock, EIC, Eic),
    (freq_m_msr, FreqmMsrClock, FREQM_MSR, FreqMMeasure),
    (freq_m_ref, FreqmRefClock, FREQM_REF, FreqMReference),
    (evsys0, Evsys0Clock, EVSYS0, EvSys0),
    (evsys1, Evsys1Clock, EVSYS1, EvSys1),
    (evsys2, Evsys2Clock, EVSYS2, EvSys2),
    (evsys3, Evsys3Clock, EVSYS3, EvSys3),
    (evsys4, Evsys4Clock, EVSYS4, EvSys4),
    (evsys5, Evsys5Clock, EVSYS5, EvSys5),
    (evsys6, Evsys6Clock, EVSYS6, EvSys6),
    (evsys7, Evsys7Clock, EVSYS7, EvSys7),
    (evsys8, Evsys8Clock, EVSYS8, EvSys8),
    (evsys9, Evsys9Clock, EVSYS9, EvSys9),
    (evsys10, Evsys10Clock, EVSYS10, EvSys10),
    (evsys11, Evsys11Clock, EVSYS11, EvSys11),
    #[cfg(any(feature = "same51", feature = "same53", feature = "same54"))]
    (can0, Can0Clock, CAN0, Can0),
    #[cfg(any(feature = "same51", feature = "same53", feature = "same54"))]
    (can1, Can1Clock, CAN1, Can1),
    (pdec, PdecClock, PDEC, PDec),
    (ac, AcClock, AC, Ac),
    (ccl, CclClock, CCL, Ccl),
    (dac, DacClock, DAC, Dac),
    #[cfg(feature = "min-samd51j")]
    (i2s0, I2S0Clock, I2S0, I2S0),
    #[cfg(feature = "min-samd51j")]
    (i2s1, I2S1Clock, I2S1, I2S1),
    (sdhc0, Sdhc0Clock, SDHC0, Sdhc0),
    #[cfg(feature = "min-samd51n")]
    (sdhc1, Sdhc1Clock, SDHC1, Sdhc1),
    (cm4_trace, Cm4TraceClock, CM4_TRACE, CM4Trace),
);

/// The frequency of the 48Mhz source.
pub const OSC48M_FREQ: Hertz = Hertz(48_000_000);
/// The frequency of the 32Khz source.
pub const OSC32K_FREQ: Hertz = Hertz(32_768);
/// The frequency of the 120Mhz source.
pub const OSC120M_FREQ: Hertz = Hertz(120_000_000);

fn set_flash_to_half_auto_wait_state(nvmctrl: &mut NVMCTRL) {
    // Zero indicates zero wait states, one indicates one wait state, etc.,
    // up to 15 wait states.
    nvmctrl.ctrla.modify(|_, w| unsafe { w.rws().bits(0b0111) });
}

fn enable_gclk_apb(mclk: &mut MCLK) {
    mclk.apbamask.modify(|_, w| w.gclk_().set_bit());
}

/// Turn on the internal 32hkz oscillator
fn enable_internal_32kosc(osc32kctrl: &mut OSC32KCTRL) {
    osc32kctrl.osculp32k.modify(|_, w| {
        w.en32k().set_bit();
        w.en1k().set_bit()
    });
    osc32kctrl.rtcctrl.write(|w| w.rtcsel().ulp1k());
}

/// Turn on the external 32hkz oscillator
fn enable_external_32kosc(osc32kctrl: &mut OSC32KCTRL) {
    osc32kctrl.xosc32k.modify(|_, w| {
        w.ondemand().clear_bit();
        // Enable 32khz output
        w.en32k().set_bit();
        w.en1k().set_bit();
        // Crystal connected to xin32/xout32
        w.xtalen().set_bit();
        w.enable().set_bit();
        w.cgm().xt();
        w.runstdby().set_bit()
    });

    osc32kctrl.rtcctrl.write(|w| w.rtcsel().xosc1k());

    // Wait for the oscillator to stabilize
    while osc32kctrl.status.read().xosc32krdy().bit_is_clear() {}
}

fn wait_for_dpllrdy(oscctrl: &mut OSCCTRL) {
    while oscctrl.dpll[0].dpllstatus.read().lock().bit_is_clear()
        || oscctrl.dpll[0].dpllstatus.read().clkrdy().bit_is_clear()
    {}
}

/// Configure the dpll0 to run at 120MHz
fn configure_and_enable_dpll0(oscctrl: &mut OSCCTRL, gclk: &mut GCLK) {
    gclk.pchctrl[ClockId::FDPLL0 as usize].write(|w| {
        w.chen().set_bit();
        w.gen().gclk5()
    });
    unsafe {
        oscctrl.dpll[0].dpllratio.write(|w| {
            w.ldr().bits(59);
            w.ldrfrac().bits(0)
        });
    }
    oscctrl.dpll[0].dpllctrlb.write(|w| w.refclk().gclk());
    oscctrl.dpll[0].dpllctrla.write(|w| {
        w.enable().set_bit();
        w.ondemand().clear_bit()
    });
}

#[cfg(feature = "usb")]
/// Configure the dfll48m to calibrate against the 1Khz USB SOF reference.
fn configure_usb_correction(oscctrl: &mut OSCCTRL) {
    oscctrl.dfllmul.write(|w| unsafe {
        w.cstep().bits(0x1)
        .fstep().bits(0x1)
        // scaling factor for 1Khz SOF signal.
        .mul().bits((48_000_000u32 / 1000) as u16)
    });
    while oscctrl.dfllsync.read().dfllmul().bit_is_set() {}

    oscctrl.dfllctrlb.write(|w| {
        // closed loop mode
        w.mode().set_bit()
        // chill cycle disable
        .ccdis().set_bit()
        // usb correction
        .usbcrm().set_bit()
    });
    while oscctrl.dfllsync.read().dfllctrlb().bit_is_set() {}
}