consortium-data 0.6.0

Embedded chip-family databases and generated chip dumps for Consortium.
Documentation
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
// Copyright 2026 Ethan Wu
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0

//! Per-family pin-mux and DMA-request maps, embedded at compile time from the
//! generated signal databases (`database/signal/<family>.json`).
//!
//! A chip map says which peripherals one *core* can reach; a signal map says
//! which *pads* a peripheral's signals can be routed to, how each pad is muxed,
//! which packages bond the pad out, and which DMA request number each
//! peripheral signal raises. Pads and DMA requests belong to the die, so there is
//! one map per family rather than one per core.
//!
//! Both vendors share one shape: ST pads carry an AF number (or need no AF, or
//! are analog inputs), i.MX pads carry their IOMUXC registers. ST sources say
//! which packages bond each pad out; i.MX sources do not, so an i.MX
//! [`Pad::packages`] is `None`.
//!
//! The data is generated by `scripts/pac/parse_signals_*.py` from
//! `STM32_open_pin_data` (BSD-3-Clause, © STMicroelectronics), STM32CubeMP2, and
//! MCUX `mcux-devices-imx` (BSD-3-Clause, © NXP); see this crate's `NOTICE`.

use std::collections::HashMap;

use crate::error::DataError;
use crate::family::{matches, normalize};

/// A signal database bundled into the binary, with the family prefix that
/// selects it.
struct Embedded {
    /// Lowercase part-number prefix that selects this family (e.g. `stm32mp25`).
    family: &'static str,
    /// The raw JSON database.
    json: &'static str,
}

const FAMILIES: &[Embedded] = &[
    Embedded {
        family: "stm32mp25",
        json: include_str!("../database/signal/stm32mp25.json"),
    },
    Embedded {
        family: "stm32mp23",
        json: include_str!("../database/signal/stm32mp23.json"),
    },
    Embedded {
        family: "stm32mp21",
        json: include_str!("../database/signal/stm32mp21.json"),
    },
    Embedded {
        family: "mimx952",
        json: include_str!("../database/signal/mimx952.json"),
    },
    Embedded {
        family: "mimx95",
        json: include_str!("../database/signal/mimx95.json"),
    },
    Embedded {
        family: "mimx93",
        json: include_str!("../database/signal/mimx93.json"),
    },
];

#[derive(serde::Deserialize)]
struct RawMap {
    packages: Vec<RawPackage>,
    pads: Vec<RawPad>,
    signals: Vec<RawSignal>,
    dma: Vec<DmaRequest>,
}

#[derive(serde::Deserialize)]
struct RawPackage {
    name: String,
    parts: Vec<String>,
}

#[derive(serde::Deserialize)]
struct RawPad {
    name: String,
    packages: Option<Vec<String>>,
}

#[derive(serde::Deserialize)]
struct RawSignal {
    pad: String,
    function: String,
    peripheral: Option<String>,
    signal: Option<String>,
    mux: RawMux,
}

#[derive(serde::Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum RawMux {
    Af {
        af: u8,
    },
    Additional,
    Analog,
    Iomuxc {
        mux_register: String,
        mux_mode: u8,
        input_register: Option<String>,
        input_daisy: Option<u8>,
        config_register: String,
    },
}

/// How a pad is switched to a signal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mux {
    /// STM32 alternate function `AFn` in the port's `AFRL`/`AFRH`.
    Af(u8),
    /// An STM32 pad function that needs no AF (`RTC_OUT1`, `PWR_WKUP1`,
    /// `TAMP_IN1`, `ADCx_EXTIn`): the owning block takes the pad over.
    Additional,
    /// An STM32 ADC input: the pad in analog mode.
    Analog,
    /// An i.MX IOMUXC routing.
    Iomuxc {
        /// `SW_MUX_CTL_PAD_*` register address.
        mux_register: u32,
        /// `MUX_MODE` value selecting this function.
        mux_mode: u8,
        /// Input-select (daisy) register address and the value routing this
        /// pad to it, for signals that have one.
        input: Option<(u32, u8)>,
        /// `SW_PAD_CTL_PAD_*` register address.
        config_register: u32,
    },
}

/// A package and the part numbers that come in it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Package {
    /// Package name, e.g. `TFBGA436`.
    pub name: String,
    /// CubeMX part references, e.g. `STM32MP257FAKx` (the trailing `x` stands
    /// for the temperature-range digit).
    pub parts: Vec<String>,
}

/// A muxable pad.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Pad {
    /// Pad name as the vendor spells it: `PA4` on STM32, `UART1_TXD` on i.MX.
    pub name: String,
    /// Packages that bond this pad out, or `None` when the source does not say.
    pub packages: Option<Vec<String>>,
}

/// One signal a pad can carry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Signal {
    /// Pad name.
    pub pad: String,
    /// Vendor function name, verbatim: `USART2_TX`, `LPUART1_TX`.
    pub function: String,
    /// Chip-dump peripheral the function belongs to, when any core can reach
    /// it (`None` for A-core-only blocks such as i.MX `ENET1`).
    pub peripheral: Option<String>,
    /// The rest of `function` after the peripheral, e.g. `TX`.
    pub signal: Option<String>,
    /// How the pad is switched to this function.
    pub mux: Mux,
}

/// One DMA request line.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
pub struct DmaRequest {
    /// Request-routing controller: `HPDMA`/`LPDMA` on STM32MP2, `DMA3`/`DMA4`/
    /// `DMA5` on i.MX 9.
    pub controller: String,
    /// Request number to program into the controller.
    pub request: u16,
    /// Vendor function name, e.g. `USART1_TX` or `TPM1_OVERFLOW_REQUEST`.
    pub function: String,
    /// Chip-dump peripheral, as for [`Signal::peripheral`].
    pub peripheral: Option<String>,
    /// The rest of `function` after the peripheral.
    pub signal: Option<String>,
}

/// A family's pads, signals, packages, and DMA requests.
#[derive(Debug, Clone)]
pub struct SignalMap {
    packages: Vec<Package>,
    /// Pads keyed by uppercased name.
    pads: HashMap<String, Pad>,
    signals: Vec<Signal>,
    dma: Vec<DmaRequest>,
}

impl SignalMap {
    /// Every package of the family.
    pub fn packages(&self) -> &[Package] {
        &self.packages
    }

    /// The package a part number comes in, if the family lists packages and
    /// `chip` is specific enough to pick one.
    ///
    /// CubeMX writes a part as `STM32MP257FAKx`, where the `x` is the
    /// temperature-range digit, so `stm32mp257fak3` matches it and
    /// `stm32mp257` (no package letters) matches nothing.
    pub fn package_of(&self, chip: &str) -> Option<&Package> {
        let chip = chip.to_ascii_uppercase();
        self.packages.iter().find(|package| {
            package.parts.iter().any(|part| {
                let stem = part.strip_suffix(['x', 'X']).unwrap_or(part);
                chip.starts_with(&stem.to_ascii_uppercase())
            })
        })
    }

    /// Look up a pad by name (case-insensitive).
    pub fn pad(&self, name: &str) -> Option<&Pad> {
        self.pads.get(&name.to_ascii_uppercase())
    }

    /// Every pad signal of the family.
    pub fn signals(&self) -> &[Signal] {
        &self.signals
    }

    /// Every pad that can carry `<peripheral>_<signal>` (case-insensitive),
    /// e.g. `("usart2", "tx")`.
    ///
    /// Matching is on the vendor's function name, so it also works for blocks
    /// no controller core can reach (whose [`Signal::peripheral`] is `None`).
    pub fn signal_routes(&self, peripheral: &str, signal: &str) -> Vec<&Signal> {
        let function = format!("{peripheral}_{signal}").to_ascii_uppercase();
        self.signals
            .iter()
            .filter(|s| s.function == function)
            .collect()
    }

    /// Every DMA request line of the family.
    pub fn dma_requests(&self) -> &[DmaRequest] {
        &self.dma
    }

    /// The DMA request lines `peripheral` raises (case-insensitive).
    pub fn dma_requests_for(&self, peripheral: &str) -> Vec<&DmaRequest> {
        let prefix = format!("{}_", peripheral.to_ascii_uppercase());
        self.dma
            .iter()
            .filter(|d| {
                d.peripheral
                    .as_deref()
                    .is_some_and(|p| p.eq_ignore_ascii_case(peripheral))
                    || d.function.starts_with(&prefix)
            })
            .collect()
    }
}

/// Resolve and parse the signal map for a chip part number.
///
/// The lookup is the same case-insensitive family match as
/// [`crate::chipmap::load`], with `imx*` rewritten to `mimx*`.
///
/// # Errors
///
/// Returns [`DataError::SignalMapUnavailable`] when no bundled database
/// matches, or [`DataError::SignalMapParse`] when it fails to deserialize.
pub fn load(chip: &str) -> Result<SignalMap, DataError> {
    let needle = normalize(chip);
    let entry = FAMILIES
        .iter()
        .find(|entry| matches(&needle, entry.family))
        .ok_or_else(|| DataError::SignalMapUnavailable(chip.to_string()))?;
    let parse_err = |detail: String| DataError::SignalMapParse {
        chip: chip.to_string(),
        detail,
    };

    let raw: RawMap = serde_json::from_str(entry.json).map_err(|err| parse_err(err.to_string()))?;

    let mut signals = Vec::with_capacity(raw.signals.len());
    for s in raw.signals {
        let register = |value: &str| {
            parse_hex(value).ok_or_else(|| {
                parse_err(format!(
                    "{} on {}: bad register '{value}'",
                    s.function, s.pad
                ))
            })
        };
        let mux = match &s.mux {
            RawMux::Af { af } => Mux::Af(*af),
            RawMux::Additional => Mux::Additional,
            RawMux::Analog => Mux::Analog,
            RawMux::Iomuxc {
                mux_register,
                mux_mode,
                input_register,
                input_daisy,
                config_register,
            } => Mux::Iomuxc {
                mux_register: register(mux_register)?,
                mux_mode: *mux_mode,
                input: match (input_register, input_daisy) {
                    (Some(reg), Some(daisy)) => Some((register(reg)?, *daisy)),
                    (None, None) => None,
                    _ => {
                        return Err(parse_err(format!(
                            "{} on {}: input register and daisy disagree",
                            s.function, s.pad
                        )));
                    }
                },
                config_register: register(config_register)?,
            },
        };
        signals.push(Signal {
            pad: s.pad,
            function: s.function,
            peripheral: s.peripheral,
            signal: s.signal,
            mux,
        });
    }

    Ok(SignalMap {
        packages: raw
            .packages
            .into_iter()
            .map(|p| Package {
                name: p.name,
                parts: p.parts,
            })
            .collect(),
        pads: raw
            .pads
            .into_iter()
            .map(|p| {
                (
                    p.name.to_ascii_uppercase(),
                    Pad {
                        name: p.name,
                        packages: p.packages,
                    },
                )
            })
            .collect(),
        signals,
        dma: raw.dma,
    })
}

fn parse_hex(value: &str) -> Option<u32> {
    u32::from_str_radix(value.strip_prefix("0x")?, 16).ok()
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Every bundled family parses, so a malformed regeneration fails here
    /// rather than at a user's `csti build`.
    #[test]
    fn every_family_parses() {
        for chip in [
            "stm32mp257fak3",
            "stm32mp235fak3",
            "stm32mp215fan3",
            "mimx9596xvt",
            "mimx9529avzxn",
            "mimx9352",
        ] {
            let map = load(chip).unwrap_or_else(|err| panic!("{chip}: {err}"));
            assert!(!map.signals().is_empty(), "{chip} has no signals");
            assert!(!map.dma_requests().is_empty(), "{chip} has no DMA requests");
        }
    }

    #[test]
    fn rejects_other_dies_sharing_an_imx_prefix() {
        for chip in ["mimx9375", "mimx9371xxvtx"] {
            assert!(
                matches!(load(chip), Err(DataError::SignalMapUnavailable(_))),
                "{chip} should not resolve"
            );
        }
    }

    #[test]
    fn stm32mp25_i2c1_sda_routes_and_package() {
        let map = load("stm32mp257fak3").unwrap();
        let mut routes: Vec<(String, Mux)> = map
            .signal_routes("i2c1", "sda")
            .into_iter()
            .map(|s| (s.pad.clone(), s.mux))
            .collect();
        routes.sort_by(|a, b| a.0.cmp(&b.0));
        assert_eq!(
            routes,
            [
                ("PA2".into(), Mux::Af(10)),
                ("PI1".into(), Mux::Af(9)),
                ("PJ10".into(), Mux::Af(9)),
            ]
        );

        let package = map
            .package_of("stm32mp257fak3")
            .expect("FAK is a known part");
        assert_eq!(package.name, "VFBGA424");
        assert!(map.package_of("stm32mp257").is_none());
        let pa0 = map.pad("pa0").expect("PA0 exists");
        assert!(pa0.packages.as_ref().unwrap().contains(&package.name));
    }

    #[test]
    fn mimx93_lpuart1_tx_iomuxc_and_dma() {
        let map = load("imx93").unwrap();
        let routes = map.signal_routes("LPUART1", "TX");
        assert_eq!(routes.len(), 1);
        assert_eq!(routes[0].pad, "UART1_TXD");
        assert_eq!(
            routes[0].mux,
            Mux::Iomuxc {
                mux_register: 0x543c_0184,
                mux_mode: 0,
                input: None,
                config_register: 0x543c_0334,
            }
        );
        assert!(map.package_of("mimx9352").is_none());
        assert_eq!(map.pad("UART1_TXD").unwrap().packages, None);

        let dma: Vec<(&str, u16)> = map
            .dma_requests_for("lpuart1")
            .into_iter()
            .map(|d| (d.function.as_str(), d.request))
            .collect();
        assert_eq!(dma, [("LPUART1_TX", 16), ("LPUART1_RX", 17)]);
    }

    #[test]
    fn rejects_unknown_family() {
        assert!(matches!(
            load("stm32h747"),
            Err(DataError::SignalMapUnavailable(_))
        ));
    }
}