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
// 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 crate::{
    regs::{self, RegisterValue},
    sys,
};

use super::{Bypass, Multiplier};

/// A low-power digital phase-locked loop.
///
/// A DPLL consists of a phase-frequency detector and a digitally controlled oscillator. The output
/// of the DCO is compared to a reference clock, and the difference is used to adjust the trim of
/// the DCO to match frequency and phase.
///
/// The DPLL supports integer and fractional multiplication, as well as spread spectrum clock generation.
#[derive(Debug)]
#[non_exhaustive]
pub struct LpDpll<const N: usize>;

/// Configuration for a low-power DPLL.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LpDpllConfig {
    /// Configures the bypass multiplexer located after the DPLL's output.
    pub bypass: Bypass,

    /// Divider for the reference clock (Q). Must be in 1..=16.
    pub reference_divider: u8,

    /// Divider on the feedback path, i.e. PLL multiplication factor (P). Must be in 1..=125.
    pub feedback_divider: u8,

    /// Fractional component of `feedback_divider`, between 0 and 2^24-1.
    pub fractional_divider: Option<u32>,

    /// Divider on the DCO output. Must be in (1..=16).
    pub output_divider: u8,

    /// Enables dithering in fractional mode.
    pub dither: bool,

    /// Options for spread spectrum modulation. Not compatible with fractional operation.
    pub spread_spectrum: Option<SpreadSpectrumConfig>,

    /// The input frequency range for the phase-frequency detector.
    ///
    /// `CLK_DPLL_LPn_CONFIG.PLL_DCO_CODE_MULT` bit.
    pub pfd_range: PfdRange,

    /// When to transition from `kp_cold_start`/`ki_cold_start` to `kp`/`ki`.
    pub cold_start_mode: ColdStartMode,

    /// Proportional gain for the DPLL's feedback loop.
    ///
    /// The actual gain is 2^p_gain, and the value of p_gain must be in 0..=15,
    /// resulting in a gain between 1 and 32,768.
    pub p_gain: u8,

    /// Integral gain for the DPLL's feedback loop.
    ///
    /// The actual gain is 2^i_gain, and the value of i_gain must be in 0..=15,
    /// resulting in a gain between 1 and 32,768.
    pub i_gain: u8,

    /// Proportional gain during cold start.
    pub p_cold_start: u8,

    /// Integral gain during cold start.
    pub i_cold_start: u8,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg(mxs40ssrss)]
/// Range of input frequency to the phase-frequency detector.
pub enum PfdRange {
    /// f_PFD <= 8 Mhz.
    LessThan8Mhz,

    /// f_PFD > 8 Mhz.
    GreaterThan8Mhz,
}

/// Options for spread-spectrum clock generation.
#[cfg(mxs40ssrss)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SpreadSpectrumConfig {
    /// The modulation rate.
    pub rate: SpreadSpectrumRate,

    /// The modulation depth.
    pub depth: SpreadSpectrumDepth,
}

/// Spread spectrum modulation depth.
///
/// The modulation depth is expressed as a fraction of f_PFD, the input frequency to the PFD (f_ref / Q).
///
/// The resulting modulation rate must be less than 32 kHz. Audio applications should choose a
/// setting that results in a modulation rate greater than 20 kHz.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg(mxs40ssrss)]
#[repr(u8)]
pub enum SpreadSpectrumRate {
    /// f_PFD / 4096
    Div4096 = 0,
    /// f_PFD / 2048
    Div2048,
    /// f_PFD / 1024
    Div1024,
    /// f_PFD / 512
    Div512,
    /// f_PFD / 256
    Div256,
    /// f_PFD / 128
    Div128,
    /// f_PFD / 744
    Div744,
}

/// Spread spectrum modulation rate.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg(mxs40ssrss)]
pub enum SpreadSpectrumDepth {
    /// Modulation by 0.5% downwards.
    Percent0_5,
    /// Modulation by 1% downwards.
    Percent1,
    /// Modulation by 2% downwards.
    Percent2,
    /// Modulation by 3% downwards.
    Percent3,
}
#[cfg(mxs40ssrss)]
impl SpreadSpectrumDepth {
    const fn value(&self) -> u16 {
        match self {
            SpreadSpectrumDepth::Percent0_5 => 0x29,
            SpreadSpectrumDepth::Percent1 => 0x52,
            SpreadSpectrumDepth::Percent2 => 0xa4,
            SpreadSpectrumDepth::Percent3 => 0xf6,
        }
    }
}

/// Cold start mode for a DPLL. Determines when to transition from from the p/i gain constants for
/// cold start to the ones for normal operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg(mxs40ssrss)]
pub enum ColdStartMode {
    /// Transition after a sufficient number of reference clock cycles have elapsed.
    Counter,

    /// Transition once lock has been achieved.
    Lock,
}

impl<const N: usize> Multiplier for LpDpll<N> {
    type Config = LpDpllConfig;
    unsafe fn steal() -> &'static mut Self {
        // SAFETY: LpDll is a zero-sized type
        unsafe { &mut *core::ptr::dangling_mut() }
    }

    /// Enables or disables the DPLL with the given configuration.
    #[inline]
    fn configure(&mut self, config: Option<&LpDpllConfig>) {
        unsafe {
            let reg = &regs::SRSS.clk_dpll_lp()[N];
            if let Some(config) = config {
                // If the PLL is already enabled, disable it first.
                if reg.config().read().enable().get() {
                    self.configure(None);
                }

                // Configure the PLL settings.
                let config_reg = regs::srss::clk_dpll_lp::Config::default()
                    .enable()
                    .set(false)
                    .bypass_sel()
                    .set(
                        (match config.bypass {
                            Bypass::MultiplierOutputOnly => Bypass::Auto,
                            m => m,
                        } as u8)
                            .into(),
                    )
                    .pll_dco_code_mult()
                    .set(config.pfd_range == PfdRange::GreaterThan8Mhz)
                    .output_div()
                    .set(config.output_divider)
                    .reference_div()
                    .set(config.reference_divider)
                    .feedback_div()
                    .set(config.feedback_divider);
                reg.config().write(config_reg);

                reg.config2().init(|r| {
                    r.frac_en()
                        .set(config.fractional_divider.is_some())
                        .frac_div()
                        .set(config.fractional_divider.unwrap_or(0))
                        .frac_dither_en()
                        .set(config.dither as u8)
                });

                reg.config3().init(|r| {
                    r.sscg_en()
                        .set(config.spread_spectrum.is_some())
                        .sscg_rate()
                        .set(config.spread_spectrum.map_or(0, |s| s.rate as u8))
                        .sscg_depth()
                        .set(config.spread_spectrum.map_or(0, |s| s.depth.value()))
                });

                reg.config4().init(|r| {
                    r.acc_cnt_lock()
                        .set(config.cold_start_mode == ColdStartMode::Lock)
                        .pll_tg()
                        .set(if config.fractional_divider.unwrap_or(0) <= (1 << 23) {
                            0
                        } else {
                            2
                        })
                });

                let gains = regs::srss::clk_dpll_lp::Config5::default()
                    .kp_int()
                    .set(config.p_gain)
                    .ki_int()
                    .set(config.i_gain)
                    .kp_acc_int()
                    .set(config.p_cold_start)
                    .ki_acc_int()
                    .set(config.i_cold_start);
                reg.config5().write_raw(gains.get_raw());
                reg.config6().write_raw(gains.get_raw());
                reg.config7().write_raw(gains.get_raw());

                // Enable the PLL.
                reg.config().write(config_reg.enable().set(true));

                // If the bypass mode is PLL output only, we need to switch it once locked.
                if config.bypass == Bypass::MultiplierOutputOnly {
                    while !reg.status().read().locked().get() {}
                    reg.config().modify(|r| {
                        r.bypass_sel()
                            .set((Bypass::MultiplierOutputOnly as u8).into())
                    });
                }
            } else {
                // Disable the PLL.
                if reg.config().read().enable().get() {
                    // Bypass the PLL output.
                    reg.config().modify(|r| {
                        r.bypass_sel()
                            .set((Bypass::ReferenceInputOnly as u8).into())
                    });

                    // Wait at least 6 reference clock cycles.
                    sys::delay_microseconds(2);

                    reg.config().modify(|r| r.enable().set(false));
                }
            }
        }
    }
}

/// Mode of operation for a DPLL.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LpDllMode {
    /// Integer operation without spread-spectrum.
    Integer,

    /// Fractional operation without spread-spectrum.
    Fractional,

    /// Integer operation with spread-spectrum.
    SpreadSpectrum {
        /// The modulation depth.
        depth: SpreadSpectrumDepth,
    },
}

impl LpDpllConfig {
    /// Chooses a DPLL configuration for a target reference frequency and output frequency.
    pub const fn from_frequency(reference: u32, target: u32, mode: LpDllMode) -> Self {
        debug_assert!(reference >= 4_000_000 && reference <= 64_000_000);
        debug_assert!(target >= 10_000_000 && target <= 400_000_000);
        // Generate twice the target frequency and divide by two to ensure an even duty cycle.
        let target = target * 2;

        let target_ratio = target as f32 / reference as f32;

        let mut best: Option<(f32, u8, u8, u8, u32)> = None;

        let mut reference_divider = 1;

        'search: while reference_divider <= 16 {
            let mut output_divider = 1;
            while output_divider <= (16 / 2) {
                // output = reference * P / Q / N
                // P = (output / reference) * Q * N
                let feedback_divider = target_ratio * (reference_divider * output_divider) as f32;

                let (mut div_int, mut div_frac) = if let LpDllMode::Fractional = mode {
                    let div_int = feedback_divider as u8;
                    let div_frac =
                        ((feedback_divider - div_int as f32) * (1 << 24) as f32 + 0.5) as u32;
                    (div_int, div_frac)
                } else {
                    ((feedback_divider + 0.5) as u8, 0)
                };

                if div_int < 1 {
                    div_int = 1;
                    div_frac = 0;
                } else if div_int > 125 {
                    div_int = 125;
                    if let LpDllMode::Fractional = mode {
                        div_frac = (1 << 24) - 1;
                    }
                }

                let actual_divider = div_int as f32 + (div_frac as f32 / (1 << 24) as f32);
                let error = (actual_divider - feedback_divider).abs();
                if best.is_none() || error < best.unwrap().0 {
                    best = Some((error, reference_divider, output_divider, div_int, div_frac));
                }
                if error == 0. {
                    break 'search;
                }

                output_divider += 1;
            }
            reference_divider += 1;
        }

        let (_, reference_divider, output_divider, feedback_divider_int, feedback_divider_frac) =
            best.unwrap();

        let output_divider = output_divider * 2;

        let spread_spectrum = if let LpDllMode::SpreadSpectrum { depth } = mode {
            // Default to the highest modulation rate less than the max of 32 kHz.
            let rate = reference / 32_000;
            match rate {
                0..256 => SpreadSpectrumRate::Div256,
                256..512 => SpreadSpectrumRate::Div512,
                512..744 => SpreadSpectrumRate::Div744,
                744..1024 => SpreadSpectrumRate::Div1024,
                1024..2048 => SpreadSpectrumRate::Div2048,
                2048..4096 => SpreadSpectrumRate::Div4096,
                _ => panic!("Reference frequency out of range"),
            };
            Some(SpreadSpectrumConfig {
                rate: SpreadSpectrumRate::Div512,
                depth,
            })
        } else {
            None
        };

        let (p_gain, i_gain, p_cold_start, i_cold_start) = match mode {
            LpDllMode::Integer => (0x1C, 0x24, 0x1A, 0x23),
            LpDllMode::Fractional => (0x20, 0x24, 0x1A, 0x23),
            LpDllMode::SpreadSpectrum { .. } => (0x18, 0x18, 0x14, 0x16),
        };

        LpDpllConfig {
            bypass: Bypass::Auto,
            reference_divider,
            feedback_divider: feedback_divider_int,
            fractional_divider: if let LpDllMode::Fractional = mode {
                Some(feedback_divider_frac)
            } else {
                None
            },
            output_divider,
            dither: false,
            spread_spectrum,
            pfd_range: if reference <= (8_000_000 * reference_divider as u32) {
                PfdRange::LessThan8Mhz
            } else {
                PfdRange::GreaterThan8Mhz
            },
            cold_start_mode: ColdStartMode::Counter,
            p_gain,
            i_gain,
            p_cold_start,
            i_cold_start,
        }
    }
}