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
//! Abstractions around port MMIO access.
//!
//! This file defines the PortAccess trait, which implements access to port MMIO registers.
//! There are two implementations of PortAccess: PortRegAccess, which simply writes to the
//! hardware registers directly; and InitPortAccess, which caches register values in local RAM to
//! allow for much better compiler optimizations when initializing all the pins in a port.
// 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.
#![allow(missing_debug_implementations)] // The types in this module are private

use regs::RegisterValue;

#[cfg(trustzone)]
use crate::security::WithSecurity;

use super::*;

#[repr(usize)]
#[derive(Clone, Copy)]
pub enum Reg {
    Cfg,
    CfgIn,

    Slew,
    #[cfg(mxs40ioss)]
    DriveStrength,

    #[cfg(mxs40sioss)]
    DriveStrength0,
    #[cfg(mxs40sioss)]
    DriveStrength1,

    IntrCfg,
    IntrMask,

    Sel0,
    Sel1,

    #[cfg(trustzone)]
    NonsecureMask,

    In,
    Out,
}
const NUM_PORT_REGS: usize = Reg::Out as usize + 1;

pub trait PortAccess {
    /// Reads from a port register.
    ///
    /// SAFETY: The port must exist on the HW and be safe to access.
    unsafe fn read(&self, reg: Reg) -> u32;

    /// Reads from a port register.
    ///
    /// SAFETY: The port must exist on the HW and be safe to access.
    unsafe fn write(&mut self, reg: Reg, v: u32);
}

impl<T: PortAccess> PortAccess for &mut T {
    unsafe fn read(&self, reg: Reg) -> u32 {
        unsafe { (**self).read(reg) }
    }

    unsafe fn write(&mut self, reg: Reg, v: u32) {
        unsafe { (**self).write(reg, v) }
    }
}

pub struct PortRegAccess(pub u8, pub SecurityAttribute);

impl PortAccess for PortRegAccess {
    //#[inline(always)]
    unsafe fn read(&self, reg: Reg) -> u32 {
        unsafe {
            let port = regs::GPIO
                .prt()
                .get_unchecked(self.0 as usize)
                .with_security(self.1);
            let hsiom = regs::HSIOM
                .prt()
                .get_unchecked(self.0 as usize)
                .with_security(self.1);

            #[cfg(trustzone)]
            let hsiom_secure = regs::HSIOM
                .secure_prt()
                .get_unchecked(self.0 as usize)
                .with_security(self.1);
            match reg {
                Reg::Cfg => port.cfg().read().get_raw(),
                Reg::CfgIn => port.cfg_in().read().get_raw(),

                #[cfg(mxs40ioss)]
                Reg::Slew => port.cfg_out().read().get_raw() & 0xFFFF,
                #[cfg(mxs40sioss)]
                Reg::Slew => port.cfg_slew_ext().read().get_raw(),

                #[cfg(mxs40ioss)]
                Reg::DriveStrength => port.cfg_out().read().get_raw() >> 16,
                #[cfg(mxs40sioss)]
                Reg::DriveStrength0 => port.cfg_drive_ext0().read().get_raw(),
                #[cfg(mxs40sioss)]
                Reg::DriveStrength1 => port.cfg_drive_ext1().read().get_raw(),

                Reg::IntrCfg => port.intr_cfg().read().get_raw(),
                Reg::IntrMask => port.intr_mask().read().get_raw(),
                Reg::Sel0 => hsiom.port_sel0().read().get_raw(),
                Reg::Sel1 => hsiom.port_sel1().read().get_raw(),
                #[cfg(trustzone)]
                Reg::NonsecureMask => hsiom_secure.nonsecure_mask().read().get_raw(),
                Reg::In => port.r#in().read().get_raw(),
                Reg::Out => port.out().read().get_raw(),
            }
        }
    }

    //#[inline(always)]
    unsafe fn write(&mut self, reg: Reg, v: u32) {
        unsafe {
            let port = regs::GPIO
                .prt()
                .get_unchecked(self.0 as usize)
                .with_security(self.1);
            let hsiom = regs::HSIOM
                .prt()
                .get_unchecked(self.0 as usize)
                .with_security(self.1);

            #[cfg(trustzone)]
            let hsiom_secure = regs::HSIOM
                .secure_prt()
                .get_unchecked(self.0 as usize)
                .with_security(self.1);
            match reg {
                Reg::Cfg => port.cfg().write_raw(v),
                Reg::CfgIn => port.cfg_in().write_raw(v),

                #[cfg(mxs40ioss)]
                Reg::Slew => port
                    .cfg_out()
                    .modify(|reg| reg.set_raw((reg.get_raw() & !0xFFFF) | (v & 0xFFFF))),
                #[cfg(mxs40sioss)]
                Reg::Slew => port.cfg_slew_ext().write_raw(v),

                #[cfg(mxs40ioss)]
                Reg::DriveStrength => port
                    .cfg_out()
                    .modify(|reg| reg.set_raw((reg.get_raw() & 0xFFFF) | (v << 16))),
                #[cfg(mxs40sioss)]
                Reg::DriveStrength0 => port.cfg_drive_ext0().write_raw(v),
                #[cfg(mxs40sioss)]
                Reg::DriveStrength1 => port.cfg_drive_ext1().write_raw(v),

                Reg::IntrCfg => port.intr_cfg().write_raw(v),
                Reg::IntrMask => port.intr_mask().write_raw(v),
                Reg::Sel0 => hsiom.port_sel0().write_raw(v),
                Reg::Sel1 => hsiom.port_sel1().write_raw(v),
                #[cfg(trustzone)]
                Reg::NonsecureMask => hsiom_secure.nonsecure_mask().write_raw(v),
                Reg::In => {}
                Reg::Out => port.out().write_raw(v),
            }
        }
    }
}

/// A PortAccess that caches intermediate register values to improve compiler optimizations when
/// initializing an entire port at once.
///
/// Using a PortAccess to configure all pins in a port generates suboptimal code, because:
/// - The compiler must read back the old register values and insert the new bitfield values.
/// - The compiler is not allowed to combine writes, since registers are volatile.
///
/// Hence, we cache the register values in an array. This allows the compiler to apply
/// constant-folding optimizations to compute the final values to be written to each register, then
/// just directly emit a series of 32-bit register writes.
pub struct InitPortAccess<P: PortAccess> {
    port: P,
    regs: [u32; NUM_PORT_REGS],
}

impl<P: PortAccess> InitPortAccess<P> {
    pub fn new(port: P) -> Self {
        #[cfg_attr(not(trustzone), expect(unused_mut))]
        let mut this = Self {
            port,
            regs: Default::default(),
        };
        #[cfg(trustzone)]
        unsafe {
            this.write(Reg::NonsecureMask, 0xff)
        };

        this
    }

    fn write_reg(&mut self, reg: Reg) {
        unsafe {
            self.port.write(reg, self.regs[reg as usize]);
        }
    }

    #[inline(always)]
    pub fn finish(mut self) {
        #[cfg(trustzone)]
        self.write_reg(Reg::NonsecureMask);

        self.write_reg(Reg::Cfg);
        self.write_reg(Reg::CfgIn);

        self.write_reg(Reg::Slew);
        #[cfg(mxs40ioss)]
        self.write_reg(Reg::DriveStrength);

        #[cfg(mxs40sioss)]
        self.write_reg(Reg::DriveStrength0);
        #[cfg(mxs40sioss)]
        self.write_reg(Reg::DriveStrength1);

        self.write_reg(Reg::IntrCfg);
        self.write_reg(Reg::IntrMask);

        self.write_reg(Reg::Sel0);
        self.write_reg(Reg::Sel1);

        self.write_reg(Reg::In);
        self.write_reg(Reg::Out);
    }
}

impl<P: PortAccess> PortAccess for InitPortAccess<P> {
    unsafe fn read(&self, reg: Reg) -> u32 {
        self.regs[reg as usize]
    }

    unsafe fn write(&mut self, reg: Reg, v: u32) {
        self.regs[reg as usize] = v;
    }
}

pub struct PinAccess<'a, P, AccessType> {
    pub port: P,
    pub pin: u8,
    _access_type: AccessType,
    _p: PhantomData<&'a ()>,
}

// Markers to indicate whether a PinAccess is safe for modifications
// (i.e. interrupts are disabled or we have exclusive access to the port)
pub struct Read;
pub struct Modify;

#[derive(Clone, Copy)]
pub struct Field<const N: usize = 1> {
    regs: [Reg; N],
    width: u8,
}
impl<const N: usize> Field<N> {
    #[inline(always)]
    fn reg(&self, pin: u8) -> Reg {
        self.regs[((pin * self.width) / 32) as usize]
    }

    #[inline(always)]
    fn shift(&self, pin: u8) -> u8 {
        (self.width * pin) & 31
    }

    #[inline(always)]
    fn mask(&self) -> u32 {
        (1 << self.width) - 1
    }
}
const fn field(reg: Reg, width: u8) -> Field {
    Field { regs: [reg], width }
}

const MODE: Field = field(Reg::Cfg, 4);
const THRESHOLD: Field = field(Reg::CfgIn, 1);

const SLEW: Field = field(Reg::Slew, 1);

#[cfg(mxs40ioss)]
const DRIVE_STRENGTH: Field = field(Reg::DriveStrength, 2);

#[cfg(mxs40sioss)]
const DRIVE_STRENGTH: Field<2> = Field {
    regs: [Reg::DriveStrength0, Reg::DriveStrength1],
    width: 8,
};

const INTERRUPT_MASK: Field = field(Reg::IntrMask, 1);
const INTERRUPT_EDGE: Field = field(Reg::IntrCfg, 2);

const IO_SEL: Field<2> = Field {
    regs: [Reg::Sel0, Reg::Sel1],
    width: 8,
};

#[cfg(trustzone)]
const NONSECURE_MASK: Field = field(Reg::NonsecureMask, 1);

const IN: Field = field(Reg::In, 1);
const OUT: Field = field(Reg::Out, 1);

impl<P: PortAccess> PinAccess<'_, P, Read> {
    pub unsafe fn steal_read(port: P, pin: u8) -> Self {
        PinAccess {
            port,
            pin,
            _access_type: Read,
            _p: PhantomData,
        }
    }
}

impl<P: PortAccess, AccessType> PinAccess<'_, P, AccessType> {
    //#[inline(always)]
    fn read<const N: usize>(&self, field: Field<N>) -> u32 {
        unsafe { (self.port.read(field.reg(self.pin)) >> field.shift(self.pin)) & field.mask() }
    }

    pub fn mode(&self) -> (DriveMode, bool) {
        let mode = self.read(MODE);
        let drive_mode = unsafe { core::mem::transmute::<u32, DriveMode>(mode & 0x7) };
        let input_buffer = (mode & 0x8) != 0;
        (drive_mode, input_buffer)
    }

    pub fn threshold(&self) -> VtripMode {
        unsafe { core::mem::transmute::<u32, VtripMode>(self.read(THRESHOLD)) }
    }
    pub fn slew_rate(&self) -> SlewRate {
        unsafe { core::mem::transmute::<u32, SlewRate>(self.read(SLEW)) }
    }
    pub fn drive_strength(&self) -> DriveStrength {
        unsafe { core::mem::transmute::<u32, DriveStrength>(self.read(DRIVE_STRENGTH)) }
    }
    pub fn interrupt_mask(&self) -> bool {
        self.read(INTERRUPT_MASK) != 0
    }
    pub fn interrupt_edge(&self) -> InterruptEdge {
        unsafe { core::mem::transmute::<u32, InterruptEdge>(self.read(INTERRUPT_EDGE)) }
    }
    pub fn io_sel(&self) -> IoSelector {
        unsafe { core::mem::transmute::<u32, IoSelector>(self.read(IO_SEL)) }
    }
    #[cfg(trustzone)]
    pub fn nonsecure_mask(&self) -> bool {
        self.read(NONSECURE_MASK) != 0
    }
    pub fn input(&self) -> PinState {
        (self.read(IN) != 0).into()
    }
    pub fn out(&self) -> PinState {
        (self.read(OUT) != 0).into()
    }
}

impl<P: PortAccess> PinAccess<'_, P, Modify> {
    pub unsafe fn steal_modify(port: P, pin: u8) -> Self {
        PinAccess {
            port,
            pin,
            _access_type: Modify,
            _p: PhantomData,
        }
    }

    #[inline(always)]
    fn write<const N: usize>(&mut self, field: Field<N>, v: u32) {
        let v = v & field.mask();
        unsafe {
            let old_value =
                self.port.read(field.reg(self.pin)) & !(field.mask() << field.shift(self.pin));
            self.port
                .write(field.reg(self.pin), old_value | v << field.shift(self.pin))
        }
    }

    pub fn set_mode(&mut self, drive_mode: DriveMode, input_buffer: bool) {
        let mode = (input_buffer as u32) << 3 | (drive_mode as u32);
        self.write(MODE, mode);
    }

    // Helpers to save a read_volatile when accessing just one sub-field of the pin mode
    // configuration
    pub fn set_drive_mode(&mut self, drive_mode: DriveMode) {
        unsafe {
            let mut cfg = self.port.read(MODE.reg(self.pin));
            cfg &= !(0x7 << MODE.shift(self.pin));
            cfg |= (drive_mode as u32) << MODE.shift(self.pin);
            self.port.write(MODE.reg(self.pin), cfg);
        }
    }
    pub fn set_input_buffer(&mut self, enabled: bool) {
        unsafe {
            let mut cfg = self.port.read(MODE.reg(self.pin));
            cfg &= !(0x8 << MODE.shift(self.pin));
            cfg |= ((enabled as u32) << 3) << MODE.shift(self.pin);
            self.port.write(MODE.reg(self.pin), cfg);
        }
    }

    pub fn set_threshold(&mut self, v: VtripMode) {
        self.write(THRESHOLD, v as u32);
    }
    pub fn set_slew_rate(&mut self, v: SlewRate) {
        self.write(SLEW, v as u32);
    }
    pub fn set_drive_strength(&mut self, v: DriveStrength) {
        self.write(DRIVE_STRENGTH, v as u32);
    }
    pub fn set_interrupt_mask(&mut self, v: bool) {
        self.write(INTERRUPT_MASK, v as u32);
    }
    pub fn set_interrupt_edge(&mut self, v: InterruptEdge) {
        self.write(INTERRUPT_EDGE, v as u32);
    }
    pub fn set_io_sel(&mut self, v: IoSelector) {
        self.write(IO_SEL, v as u32);
    }
    #[cfg(trustzone)]
    pub fn set_nonsecure_mask(&mut self, v: bool) {
        self.write(NONSECURE_MASK, v as u32);
    }
    pub fn set_out(&mut self, v: PinState) {
        self.write(OUT, v as u32);
    }

    #[inline(always)]
    pub fn initialize<Mode: PinMode>(
        &mut self,
        _mode: Mode,
        config: PinConfig,
        security: security::SecurityAttribute,
    ) {
        _ = security;
        #[cfg(trustzone)]
        self.set_nonsecure_mask(security.is_nonsecure());
        self.set_mode(Mode::DRIVE_MODE, Mode::INPUT_BUFFER);
        self.set_io_sel(Mode::IO_SELECTOR);
        self.set_threshold(config.threshold);
        self.set_slew_rate(config.slew_rate);
        self.set_drive_strength(config.drive_strength);
        self.set_interrupt_edge(config.interrupt_edge);
        self.set_interrupt_mask(config.interrupt_enabled);
        self.set_out(config.initial_output);
    }
}