earlgrey/
pinmux.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
// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.

//! Mux'ing between physical pads and GPIO or other peripherals.

use kernel::hil::gpio;
use kernel::hil::gpio::{Configuration, Configure, FloatingState};
use kernel::utilities::registers::interfaces::{Readable, Writeable};
use kernel::utilities::registers::{register_bitfields, FieldValue, LocalRegisterCopy};
use kernel::utilities::StaticRef;

use crate::registers::pinmux_regs::{
    PinmuxRegisters, DIO_PAD_ATTR_REGWEN, MIO_OUTSEL_REGWEN, MIO_PAD_ATTR_REGWEN,
    MIO_PERIPH_INSEL_REGWEN,
};
use crate::registers::top_earlgrey::{
    DirectPads, MuxedPads, PinmuxInsel, PinmuxOutsel, PinmuxPeripheralIn, PINMUX_AON_BASE_ADDR,
    PINMUX_MIO_PERIPH_INSEL_IDX_OFFSET,
};

pub const PINMUX_BASE: StaticRef<PinmuxRegisters> =
    unsafe { StaticRef::new(PINMUX_AON_BASE_ADDR as *const PinmuxRegisters) };

// To avoid code duplication for MIO/DIO we introduce
// one register layout for both types of IO. In the future this code
// should be replaced by official improved auto generated definitions.
// OpenTitan documentation reference:
// <https://opentitan.org/book/hw/ip/pinmux/doc/registers.html#fields-6>
// <https://opentitan.org/book/hw/ip/pinmux/doc/registers.html#fields-8>
register_bitfields![u32,
    pub(crate) PAD_ATTR [
        INVERT OFFSET(0) NUMBITS(1) [],
        VIRTUAL_OPEN_DRAIN_EN OFFSET(1) NUMBITS(1) [],
        PULL_EN OFFSET(2) NUMBITS(1) [],
        PULL OFFSET(3) NUMBITS(1) [
            DOWN = 0,
            UP = 1,
        ],
        KEEPER_EN OFFSET(4) NUMBITS(1) [],
        SCHMITT_EN OFFSET(5) NUMBITS(1) [],
        OPEN_DRAIN_EN OFFSET(6) NUMBITS(1) [],
        SLEW_RATE OFFSET(16) NUMBITS(2) [],
        DRIVE_STRENGTH OFFSET(20) NUMBITS(4) [],
    ],
];

type PadAttribute = LocalRegisterCopy<u32, PAD_ATTR::Register>;

#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Pad {
    Mio(MuxedPads),
    Dio(DirectPads),
}

impl Pad {
    /// Extract value of attributes using common layout
    fn pad_attr(&self) -> PadAttribute {
        PadAttribute::new(match *self {
            Self::Mio(mio) => PINMUX_BASE.mio_pad_attr[mio as usize].get(),
            Self::Dio(dio) => PINMUX_BASE.dio_pad_attr[dio as usize].get(),
        })
    }

    /// Modify value of pad attribute using common MIO/DIO register layout
    fn modify_pad_attr(&self, flags: FieldValue<u32, PAD_ATTR::Register>) {
        let mut attr = self.pad_attr();
        attr.modify(flags);
        match *self {
            Self::Mio(mio) => &PINMUX_BASE.mio_pad_attr[mio as usize].set(attr.get()),
            Self::Dio(dio) => &PINMUX_BASE.dio_pad_attr[dio as usize].set(attr.get()),
        };
    }

    pub fn set_floating_state(&self, mode: gpio::FloatingState) {
        self.modify_pad_attr(match mode {
            gpio::FloatingState::PullUp => PAD_ATTR::PULL_EN::SET + PAD_ATTR::PULL::UP,
            gpio::FloatingState::PullDown => PAD_ATTR::PULL_EN::SET + PAD_ATTR::PULL::DOWN,
            gpio::FloatingState::PullNone => PAD_ATTR::PULL_EN::CLEAR + PAD_ATTR::PULL::CLEAR,
        });
    }

    pub fn set_output_open_drain(&self) {
        self.modify_pad_attr(PAD_ATTR::OPEN_DRAIN_EN::SET);
    }

    pub fn set_output_push_pull(&self) {
        self.modify_pad_attr(PAD_ATTR::OPEN_DRAIN_EN::CLEAR);
    }

    pub fn set_invert_sense(&self, invert: bool) {
        if invert {
            self.modify_pad_attr(PAD_ATTR::INVERT::SET)
        } else {
            self.modify_pad_attr(PAD_ATTR::INVERT::CLEAR)
        }
    }

    pub fn floating_state(&self) -> gpio::FloatingState {
        let pad_attr: PadAttribute = self.pad_attr();
        if pad_attr.matches_all(PAD_ATTR::PULL::UP + PAD_ATTR::PULL_EN::SET) {
            gpio::FloatingState::PullUp
        } else if pad_attr.matches_all(PAD_ATTR::PULL::DOWN + PAD_ATTR::PULL_EN::SET) {
            gpio::FloatingState::PullDown
        } else {
            gpio::FloatingState::PullNone
        }
    }

    /// Prohibits any further changes to input/output/open-drain or pullup configuration.
    pub fn lock_pad_attributes(&self) {
        match *self {
            Self::Mio(mio) => PINMUX_BASE.mio_pad_attr_regwen[(mio as u32) as usize]
                .write(MIO_PAD_ATTR_REGWEN::EN_0::CLEAR),
            Self::Dio(dio) => PINMUX_BASE.dio_pad_attr_regwen[(dio as u32) as usize]
                .write(DIO_PAD_ATTR_REGWEN::EN_0::CLEAR),
        };
    }
}

// Configuration of PINMUX multiplexers for I/O
// OpenTitan Documentation reference:
// https://opentitan.org/book/hw/ip/pinmux/doc/programmers_guide.html#pinmux-configuration

pub trait SelectOutput {
    /// Connect particular pad to internal peripheral
    fn connect_output(self, output: PinmuxOutsel);

    /// Connect particular pad output to always low
    fn connect_low(self);

    /// Connect particular pad output to always high
    fn connect_high(self);

    /// This function disconnect pad from peripheral
    /// and set it to High-Impedance state
    fn connect_high_z(self);

    /// Lock selection of output for particular pad
    fn lock(self);

    /// Get value of current output selection
    fn get_selector(self) -> PinmuxOutsel;
}

// We make a implicit conversion between PinmuxMioOut and MuxedPad
impl SelectOutput for MuxedPads {
    fn connect_output(self, output: PinmuxOutsel) {
        PINMUX_BASE.mio_outsel[self as usize].set(output as u32)
    }

    fn connect_low(self) {
        PINMUX_BASE.mio_outsel[self as usize].set(PinmuxOutsel::ConstantZero as u32)
    }

    fn connect_high(self) {
        PINMUX_BASE.mio_outsel[self as usize].set(PinmuxOutsel::ConstantOne as u32)
    }

    fn connect_high_z(self) {
        PINMUX_BASE.mio_outsel[self as usize].set(PinmuxOutsel::ConstantHighZ as u32)
    }

    fn lock(self) {
        PINMUX_BASE.mio_outsel_regwen[self as usize].write(MIO_OUTSEL_REGWEN::EN_0::CLEAR);
    }

    fn get_selector(self) -> PinmuxOutsel {
        match PinmuxOutsel::try_from(PINMUX_BASE.mio_outsel[self as usize].get()) {
            Ok(sel) => sel,
            // When this panic happend it mean we have some glitch in registers
            // or a incorect version definition of registers.
            Err(val) => panic!("PINMUX: Invalid register value: {}", val),
        }
    }
}

pub trait SelectInput {
    /// Connect internal peripheral input to particular pad
    fn connect_input(self, input: PinmuxInsel);

    /// Connect internal peripherals input to always low
    fn connect_low(self);

    /// Connect internal peripherals input to always high
    fn connect_high(self);

    /// Lock input configurations
    fn lock(self);

    /// Get value of current input selection
    fn get_selector(self) -> PinmuxInsel;
}

/// MuxedPads names and values overlap with PinmuxInsel,
/// function below is used to convert it to valid PinmuxInsel.
/// OpenTitan documentation reference:
/// <https://opentitan.org/book/hw/ip/pinmux/doc/programmers_guide.html#pinmux-configuration>
impl From<MuxedPads> for PinmuxInsel {
    fn from(pad: MuxedPads) -> Self {
        // Add 2 to skip constant ConstantZero and ConstantOne.
        match PinmuxInsel::try_from(pad as u32 + PINMUX_MIO_PERIPH_INSEL_IDX_OFFSET as u32) {
            Ok(select) => select,
            Err(_) => PinmuxInsel::ConstantZero,
        }
    }
}

impl SelectInput for PinmuxPeripheralIn {
    fn connect_input(self, input: PinmuxInsel) {
        PINMUX_BASE.mio_periph_insel[self as usize].set(input as u32)
    }

    fn connect_low(self) {
        PINMUX_BASE.mio_periph_insel[self as usize].set(PinmuxInsel::ConstantZero as u32)
    }

    fn connect_high(self) {
        PINMUX_BASE.mio_periph_insel[self as usize].set(PinmuxInsel::ConstantOne as u32)
    }

    fn lock(self) {
        PINMUX_BASE.mio_periph_insel_regwen[self as usize]
            .write(MIO_PERIPH_INSEL_REGWEN::EN_0::CLEAR);
    }

    fn get_selector(self) -> PinmuxInsel {
        match PinmuxInsel::try_from(PINMUX_BASE.mio_periph_insel[self as usize].get()) {
            Ok(sel) => sel,
            //
            Err(val) => panic!("PINMUX: Invalid insel register value {}", val),
        }
    }
}

// Enum below represent connection betwen pad and peripherals
// Diagram bellow help with interpreting meaning of input/output in enum bellow
// <https://opentitan.org/book/hw/ip/pinmux/doc/theory_of_operation.html#muxing-matrix>
// According to OpenTitan documentations uninitialized pinmux I/O selector are set to default
// values. With are respectively
// output selector - PinmuxOutsel::ConstantHighZ
// input selector - PinmuxInsel::ConstantZero
// <https://opentitan.org/book/hw/ip/pinmux/doc/registers.html#mio_outsel>
// <https://opentitan.org/book/hw/ip/pinmux/doc/registers.html#mio_periph_insel>
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum PadConfig {
    // Internal Output and input not conected to any pad
    Unconnected,
    // Allow to pass signal from pad to peripheral
    // [PAD]------>[PeripherapInput]
    Input(MuxedPads, PinmuxPeripheralIn),
    // Allow to pass signal form peripheral to pad
    // [PAD]<------[PeripheralOut]
    Output(MuxedPads, PinmuxOutsel),
    // Allow to pass signal form pad to peripheral in bouth directions
    // [PAD]------>[PeripherapInput]
    // [PAD]<------[PeripheralOut]
    InOut(MuxedPads, PinmuxPeripheralIn, PinmuxOutsel),
}

impl PadConfig {
    /// Connect Pad to internal peripheral I/O using pinmux multiplexers
    pub fn connect(&self) {
        match *self {
            PadConfig::Unconnected => {}
            PadConfig::Input(pad, peripheral_in) => {
                peripheral_in.connect_input(PinmuxInsel::from(pad));
            }
            PadConfig::Output(pad, peripheral_out) => {
                pad.connect_output(peripheral_out);
            }
            PadConfig::InOut(pad, peripheral_in, peripheral_out) => {
                peripheral_in.connect_input(PinmuxInsel::from(pad));
                pad.connect_output(peripheral_out);
            }
        }
    }

    /// Disconnect pad from internal input and connect to always Low signal
    pub fn disconnect_input(&self) {
        match *self {
            PadConfig::Unconnected => {}
            PadConfig::Input(_pad, peripheral_in) => peripheral_in.connect_low(),
            PadConfig::Output(_pad, _peripheral_out) => {}
            PadConfig::InOut(_pad, peripheral_in, _peripheral_out) => {
                peripheral_in.connect_low();
            }
        };
    }

    // Disconnect pad from internal output and connect to Hi-Z
    pub fn disconnect_output(&self) {
        match *self {
            PadConfig::Unconnected => {}
            PadConfig::Input(_pad, _peripheral_in) => {}
            PadConfig::Output(pad, _peripheral_out) => pad.connect_high_z(),
            PadConfig::InOut(pad, _peripheral_in, _peripheral_out) => {
                pad.connect_high_z();
            }
        };
    }

    /// Disconnect input and output from peripheral/pad
    /// and connect to internal Hi-Z/Low signal
    pub fn disconnect(&self) {
        match *self {
            PadConfig::Unconnected => {}
            PadConfig::Input(_pad, peripheral_in) => {
                peripheral_in.connect_low();
            }
            PadConfig::Output(pad, _peripheral_out) => {
                pad.connect_high_z();
            }
            PadConfig::InOut(pad, peripheral_in, _peripheral_out) => {
                peripheral_in.connect_low();
                pad.connect_high_z();
            }
        }
    }

    /// Return copy of `enum` representing MIO pad
    /// associated with this connection
    pub fn get_pad(&self) -> Option<Pad> {
        match *self {
            PadConfig::Unconnected => None,
            PadConfig::Input(pad, _) => Some(Pad::Mio(pad)),
            PadConfig::Output(pad, _) => Some(Pad::Mio(pad)),
            PadConfig::InOut(pad, _, _) => Some(Pad::Mio(pad)),
        }
    }
}

impl From<PadConfig> for Configuration {
    fn from(pad: PadConfig) -> Configuration {
        match pad {
            PadConfig::Unconnected => Configuration::Other,
            PadConfig::Input(_pad, peripheral_in) => match peripheral_in.get_selector() {
                PinmuxInsel::ConstantZero => Configuration::LowPower,
                PinmuxInsel::ConstantOne => Configuration::Function,
                _ => Configuration::Input,
            },
            PadConfig::Output(pad, _peripheral_out) => match pad.get_selector() {
                PinmuxOutsel::ConstantZero => Configuration::Function,
                PinmuxOutsel::ConstantOne => Configuration::Function,
                PinmuxOutsel::ConstantHighZ => Configuration::LowPower,
                _ => Configuration::Output,
            },
            PadConfig::InOut(pad, peripheral_in, _peripheral_out) => {
                let input_selector = peripheral_in.get_selector();
                let output_selector = pad.get_selector();
                match (input_selector, output_selector) {
                    (PinmuxInsel::ConstantZero, PinmuxOutsel::ConstantHighZ) => {
                        Configuration::LowPower
                    }
                    (
                        PinmuxInsel::ConstantOne | PinmuxInsel::ConstantZero,
                        PinmuxOutsel::ConstantZero | PinmuxOutsel::ConstantOne,
                    ) => Configuration::Function,
                    (_, _) => Configuration::InputOutput,
                }
            }
        }
    }
}

impl Configure for PadConfig {
    fn configuration(&self) -> Configuration {
        Configuration::from(*self)
    }

    fn make_output(&self) -> Configuration {
        match self.configuration() {
            Configuration::LowPower => self.connect(),
            _ => {}
        };
        self.configuration()
    }

    fn disable_output(&self) -> Configuration {
        self.disconnect_output();
        self.configuration()
    }

    fn make_input(&self) -> Configuration {
        match self.configuration() {
            Configuration::LowPower => self.connect(),
            _ => {}
        };
        self.configuration()
    }

    fn disable_input(&self) -> Configuration {
        self.disconnect_input();
        self.configuration()
    }

    fn deactivate_to_low_power(&self) {
        self.disconnect();
    }

    fn set_floating_state(&self, state: FloatingState) {
        if let Some(pad) = self.get_pad() {
            pad.set_floating_state(state);
        }
    }

    fn floating_state(&self) -> FloatingState {
        if let Some(pad) = self.get_pad() {
            pad.floating_state()
        } else {
            FloatingState::PullNone
        }
    }
}