consortium-cfg 0.5.0

Configuration subsystem support for the Consortium project.
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
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
// 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

//! Loads a `Consortium.toml` manifest and binds it to its chip-family database.

use std::collections::HashMap;

use consortium_cfg_common::config::{Config, MemoryRegion, Party, VisibleCore};
use consortium_cfg_common::database::{ChipDatabase, HardwareDoorbellPeripheral};

use consortium_data::DataError;

use crate::{database, error::CfgError};

/// A parsed manifest resolved against the database for its target chip.
#[derive(Debug, Clone)]
pub struct Session {
    /// The parsed `Consortium.toml`.
    pub config: Config,
    /// The chip-family database selected by `[profile] chip`.
    pub database: ChipDatabase,
}

impl Session {
    /// Parses a `Consortium.toml` string, resolves its chip database, and
    /// validates that the manifest only references resources the chip provides.
    ///
    /// # Errors
    ///
    /// - [`CfgError::Manifest`] if the TOML is malformed.
    /// - [`DataError::UnknownChip`] / [`DataError::DatabaseParse`] if the chip
    ///   cannot be resolved to a bundled database.
    /// - [`CfgError::UnknownDoorbell`] / [`CfgError::OwnerNotVisible`] from
    ///   [`Self::validate`].
    pub fn from_toml(content: &str) -> Result<Self, CfgError> {
        consortium_log::trace!("parsing Consortium.toml ({} bytes)", content.len());
        let config: Config = toml::from_str(content).map_err(|err| {
            consortium_log::trace!("manifest TOML parse failed: {}", err);
            CfgError::Manifest(err.to_string())
        })?;
        consortium_log::trace!("resolving chip database for '{}'", config.profile.chip);
        let database = database::load(&config.profile.chip)?;

        let session = Self { config, database };
        session.validate()?;
        Ok(session)
    }

    /// Checks that every doorbell and peripheral owner named in the manifest
    /// exists on the target chip, and that the shared-memory regions fit within
    /// the chip's SRAM without overlapping.
    pub fn validate(&self) -> Result<(), CfgError> {
        let chip = &self.config.profile.chip;
        consortium_log::trace!("validating manifest against chip '{}'", chip);

        self.validate_memory()?;
        self.validate_ipc()?;
        self.validate_dbg()?;
        self.validate_remoteproc()?;

        for (name, peripheral) in &self.config.peripheral {
            consortium_log::trace!(
                "validating peripheral '{}' owned by '{}'",
                name,
                peripheral.owner
            );
            if !self.is_core(peripheral.owner) {
                consortium_log::trace!("peripheral '{}' owner not visible on chip", name);
                return Err(CfgError::OwnerNotVisible(
                    name.clone(),
                    peripheral.owner.to_string(),
                    chip.clone(),
                ));
            }

            // A coprocessor may only own a peripheral its core can actually
            // reach. The owning core's chip dump lists exactly those peripherals,
            // so presence in that map is the accessibility filter. AP-owned
            // peripherals are surfaced to Linux via the DTS transpilers instead,
            // so they are not checked here. When no dump is bundled for the
            // owning core, the filter cannot be applied and the peripheral is
            // left unvalidated (it also gets no generated bring-up).
            if let VisibleCore::Mcore(_) = peripheral.owner {
                let core = peripheral.owner.to_string();
                match crate::chipmap::load(chip, &core) {
                    Ok(map) => {
                        if !map.contains_peripheral(name) {
                            consortium_log::trace!(
                                "peripheral '{}' absent from chip map for core '{}'",
                                name,
                                core
                            );
                            return Err(CfgError::PeripheralNotOnCore {
                                name: name.clone(),
                                core,
                                chip: chip.clone(),
                            });
                        }
                    }
                    Err(DataError::ChipMapUnavailable { .. }) => {
                        consortium_log::trace!(
                            "no chip map bundled for core '{}'; skipping peripheral accessibility check",
                            core
                        );
                    }
                    Err(err) => {
                        consortium_log::trace!("chip map load failed for core '{}': {}", core, err);
                        return Err(err.into());
                    }
                }
            }
        }

        Ok(())
    }

    fn validate_remoteproc(&self) -> Result<(), CfgError> {
        let layouts = self.lower_remoteproc()?;
        if !layouts.is_empty() && self.config.dts.mode.is_overlay() {
            return Err(CfgError::Manifest(
                "remoteproc deployment requires `[dts] mode = \"merge\"`".into(),
            ));
        }
        let shared =
            self.config
                .dbg
                .cores
                .iter()
                .map(|(core, entry)| (format!("dbg.{core}"), entry.memory))
                .chain(self.config.ipc.channels.iter().enumerate().filter_map(
                    |(index, channel)| {
                        channel
                            .memory()
                            .map(|memory| (format!("ipc.channel[{index}].config.memory"), memory))
                    },
                ));

        for layout in layouts.values() {
            let windows = [
                ("vector".to_string(), layout.vector.window),
                ("flash".to_string(), layout.flash),
                ("shmem".to_string(), layout.shmem.window),
                ("ram".to_string(), layout.ram),
            ]
            .into_iter()
            .chain(
                layout
                    .regions
                    .iter()
                    .map(|region| (format!("regions.{}", region.name), region.window)),
            );
            for (window_name, window) in windows {
                if !window.reserve {
                    continue;
                }
                let window_end = window.end().expect("layout is validated");
                for (name, region) in shared.clone() {
                    let start = u64::from(region.base);
                    let end = start + u64::from(region.length);
                    if window.origin < end && start < window_end {
                        return Err(CfgError::Manifest(format!(
                            "[remoteproc.{}].{window_name} overlaps {name} in memory",
                            layout.core
                        )));
                    }
                }
            }
        }
        Ok(())
    }

    /// Validates IPC doorbell references, party support, and channel allocation.
    fn validate_ipc(&self) -> Result<(), CfgError> {
        let chip = &self.config.profile.chip;
        let mut used_channels: HashMap<(String, u32), Party> = HashMap::new();

        for channel in &self.config.ipc.channels {
            consortium_log::trace!(
                "validating ipc channel '{}' on doorbell '{}'",
                channel.name,
                channel.doorbell
            );

            if let Some(memory) = channel.memory() {
                let required =
                    consortium_ipc_transport_memory::required_region_len(2, channel.mtu as usize);
                if (memory.length as usize) < required {
                    consortium_log::trace!(
                        "ipc channel '{}' region length {:#x} is smaller than aligned layout {:#x}",
                        channel.name,
                        memory.length,
                        required
                    );
                    return Err(CfgError::IpcRegionTooSmall {
                        channel: channel.name.clone(),
                        length: memory.length,
                        mtu: channel.mtu,
                        required,
                    });
                }
            }

            if channel.cache() {
                let controller = [channel.secondary, channel.primary]
                    .into_iter()
                    .map(Party::core)
                    .find(|core| *core != VisibleCore::Ap);
                if controller
                    != Some(VisibleCore::Mcore(
                        consortium_cfg_common::config::McoreName::Cm7,
                    ))
                {
                    let core = controller
                        .map_or_else(|| VisibleCore::Ap.to_string(), |core| core.to_string());
                    consortium_log::trace!(
                        "ipc channel '{}' enables caching on unsupported core '{}'",
                        channel.name,
                        core
                    );
                    return Err(CfgError::IpcCacheUnsupported {
                        channel: channel.name.clone(),
                        core,
                    });
                }
            }
            let doorbell = self.doorbell(&channel.doorbell).ok_or_else(|| {
                consortium_log::trace!("unknown doorbell '{}'", channel.doorbell);
                self.unknown_doorbell(&channel.doorbell)
            })?;

            for (party, endpoint) in &channel.endpoints {
                if !self.is_party(*party) {
                    consortium_log::trace!("ipc endpoint party '{}' not visible on chip", party);
                    return Err(CfgError::IpcEndpointNotVisible(
                        channel.doorbell.clone(),
                        party.to_string(),
                        chip.clone(),
                    ));
                }

                if !doorbell.parties.iter().any(|entry| entry.core == *party) {
                    consortium_log::trace!("doorbell '{}' has no party '{}'", doorbell.name, party);
                    return Err(self.doorbell_party_unavailable(doorbell, *party));
                }

                // An acknowledgement line is a doorbell channel like any other, so it goes
                // through the same bounds and collision checks — that is what stops one
                // from silently aliasing a data line or another endpoint's.
                match (channel.ack(), endpoint.ack_chan) {
                    (true, None) => {
                        consortium_log::trace!(
                            "ipc channel '{}' party '{}' sets config.ack without an ack_chan",
                            channel.name,
                            party
                        );
                        return Err(CfgError::IpcAckChannelMissing {
                            channel: channel.name.clone(),
                            party: party.to_string(),
                        });
                    }
                    (false, Some(_)) => {
                        consortium_log::trace!(
                            "ipc channel '{}' party '{}' declares ack_chan without config.ack",
                            channel.name,
                            party
                        );
                        return Err(CfgError::IpcAckChannelUnexpected {
                            channel: channel.name.clone(),
                            party: party.to_string(),
                        });
                    }
                    _ => {}
                }

                for chan in [Some(endpoint.chan), endpoint.ack_chan]
                    .into_iter()
                    .flatten()
                {
                    if chan >= doorbell.channels {
                        consortium_log::trace!(
                            "doorbell '{}' channel {} out of bounds ({} channels)",
                            doorbell.name,
                            chan,
                            doorbell.channels
                        );
                        return Err(CfgError::DoorbellChannelUnavailable {
                            doorbell: doorbell.name.clone(),
                            channel: chan,
                            channels: doorbell.channels,
                            chip: chip.clone(),
                            trm: self.database.trm.clone(),
                            page: doorbell.channel_page,
                        });
                    }

                    let key = (doorbell.name.to_ascii_lowercase(), chan);
                    if let Some(first_party) = used_channels.insert(key, *party) {
                        consortium_log::trace!(
                            "doorbell '{}' channel {} claimed by both '{}' and '{}'",
                            doorbell.name,
                            chan,
                            first_party,
                            party
                        );
                        return Err(CfgError::DoorbellChannelDuplicate {
                            doorbell: doorbell.name.clone(),
                            channel: chan,
                            first_party: first_party.to_string(),
                            second_party: party.to_string(),
                        });
                    }
                }
            }
        }

        Ok(())
    }

    /// Validates `[dbg.<core>]` entries: each must name a coprocessor visible
    /// on the chip. The application processor is always the host that decodes
    /// the logs, so it can never be a logger and `[dbg.ap]` is rejected.
    fn validate_dbg(&self) -> Result<(), CfgError> {
        let chip = &self.config.profile.chip;

        for core in self.config.dbg.cores.keys() {
            consortium_log::trace!("validating dbg logger on core '{}'", core);
            if *core == VisibleCore::Ap {
                consortium_log::trace!("dbg core is the AP host, which cannot be a logger");
                return Err(CfgError::DbgHostNotLoggable);
            }

            if !self.is_core(*core) {
                consortium_log::trace!("dbg core '{}' not visible on chip", core);
                return Err(CfgError::DbgCoreNotVisible {
                    core: core.to_string(),
                    chip: chip.clone(),
                });
            }
        }

        Ok(())
    }

    /// Validates shared-memory regions: each must have a non-zero length, lie
    /// entirely within one of the chip's SRAM regions, and not overlap another.
    fn validate_memory(&self) -> Result<(), CfgError> {
        let mut regions = Vec::new();

        for (core, entry) in &self.config.dbg.cores {
            regions.push((format!("dbg.{core}"), entry.memory, false));
        }

        for (index, channel) in self.config.ipc.channels.iter().enumerate() {
            if let Some(memory) = channel.memory() {
                regions.push((
                    format!("ipc.channel[{index}].config.memory"),
                    memory,
                    channel.cache(),
                ));
            }
        }

        for (name, region, cache) in &regions {
            self.validate_memory_region(name, *region, *cache)?;
        }

        for (left_index, (left_name, left, _)) in regions.iter().enumerate() {
            let left_end = left.base + left.length;
            for (right_name, right, _) in regions.iter().skip(left_index + 1) {
                let right_end = right.base + right.length;
                if left.base < right_end && right.base < left_end {
                    consortium_log::trace!(
                        "shared-memory regions '{}' and '{}' overlap",
                        left_name,
                        right_name
                    );
                    return Err(CfgError::RegionOverlap {
                        a: left_name.clone(),
                        a_base: left.base,
                        a_end: left_end,
                        b: right_name.clone(),
                        b_base: right.base,
                        b_end: right_end,
                    });
                }
            }
        }

        Ok(())
    }

    fn validate_memory_region(
        &self,
        name: &str,
        region: MemoryRegion,
        cache: bool,
    ) -> Result<(), CfgError> {
        consortium_log::trace!(
            "validating region '{}' base {:#x} length {:#x}",
            name,
            region.base,
            region.length
        );
        // Exclusive end address; a region that wraps past u64::MAX cannot
        // fit in any SRAM window, so treat the overflow as out-of-bounds.
        let Some(end) = region.base.checked_add(region.length) else {
            consortium_log::trace!("region '{}' end address overflows", name);
            return Err(self.region_out_of_bounds(name, region.base, region.base));
        };

        if region.length == 0 {
            consortium_log::trace!("region '{}' has zero length", name);
            return Err(CfgError::RegionEmpty {
                region: name.to_string(),
            });
        }

        if cache {
            // Cache maintenance is destructive at cache-line granularity. Keep
            // both boundaries on 64-byte lines: this covers AArch64's fixed
            // sweep size and Cortex-M7's 32-byte SCB helper requirement.
            let requirement = if !region.base.is_multiple_of(64) {
                Some("base must be aligned to 64 bytes")
            } else if !region.length.is_multiple_of(64) {
                Some("size must be a multiple of 64 bytes")
            } else {
                None
            };
            if let Some(requirement) = requirement {
                consortium_log::trace!("region '{}' not cache-line aligned: {}", name, requirement);
                return Err(CfgError::RegionNotCacheAligned {
                    region: name.to_string(),
                    base: region.base,
                    length: region.length,
                    requirement,
                });
            }
        } else {
            // MPU constraints (ARMv7-M / ARMv8-M): a region's size must be a
            // power of two of at least 32 bytes, and its base must be aligned
            // to that size. Uncached controller mappings need an MPU entry.
            let mpu_requirement = if !region.length.is_power_of_two() {
                Some("size must be a power of two")
            } else if region.length < 32 {
                Some("size must be at least 32 bytes")
            } else if !region.base.is_multiple_of(region.length) {
                Some("base must be aligned to the region size")
            } else {
                None
            };
            if let Some(requirement) = mpu_requirement {
                consortium_log::trace!("region '{}' not MPU-aligned: {}", name, requirement);
                return Err(CfgError::RegionNotMpuAligned {
                    region: name.to_string(),
                    base: region.base,
                    length: region.length,
                    requirement,
                });
            }
        }

        let contained = self.database.memory.regions.iter().any(|sram| {
            let sram_base = sram.base;
            let sram_end = sram_base + sram.length;
            region.base >= sram_base && end <= sram_end
        });
        if !contained {
            consortium_log::trace!(
                "region '{}' ({:#x}..{:#x}) not contained in any SRAM window",
                name,
                region.base,
                end
            );
            return Err(self.region_out_of_bounds(name, region.base, end));
        }

        Ok(())
    }

    /// Builds a [`CfgError::RegionOutOfBounds`] annotated with the chip's TRM
    /// URL and the memory-map page(s), so the user knows where to look.
    fn region_out_of_bounds(&self, region: &str, base: u32, end: u32) -> CfgError {
        let pages = self
            .database
            .memory
            .trm_page
            .iter()
            .map(u32::to_string)
            .collect::<Vec<_>>()
            .join(", ");

        CfgError::RegionOutOfBounds {
            region: region.to_string(),
            base,
            end,
            chip: self.config.profile.chip.clone(),
            trm: self.database.trm.clone(),
            pages,
        }
    }

    /// Builds a [`CfgError::UnknownDoorbell`] listing the doorbells the chip
    /// actually exposes, each with its TRM page.
    fn unknown_doorbell(&self, name: &str) -> CfgError {
        let available = self
            .database
            .peripheral
            .doorbells
            .iter()
            .map(|entry| format!("{} (TRM p. {})", entry.name, entry.page))
            .collect::<Vec<_>>()
            .join(", ");

        CfgError::UnknownDoorbell {
            name: name.to_string(),
            chip: self.config.profile.chip.clone(),
            trm: self.database.trm.clone(),
            available,
        }
    }

    /// Finds a database doorbell by manifest name, ignoring ASCII case.
    pub(crate) fn doorbell(&self, name: &str) -> Option<&HardwareDoorbellPeripheral> {
        self.database
            .peripheral
            .doorbells
            .iter()
            .find(|entry| entry.name.eq_ignore_ascii_case(name))
    }

    /// Builds a [`CfgError::DoorbellPartyUnavailable`] with the configured
    /// parties and the TRM page documenting party support.
    fn doorbell_party_unavailable(
        &self,
        doorbell: &HardwareDoorbellPeripheral,
        party: Party,
    ) -> CfgError {
        let available = doorbell
            .parties
            .iter()
            .map(|entry| {
                format!(
                    "{} (TRM memory p. {}, IRQ p. {})",
                    entry.core, entry.page_memory, entry.page_irq
                )
            })
            .collect::<Vec<_>>()
            .join(", ");

        CfgError::DoorbellPartyUnavailable {
            doorbell: doorbell.name.clone(),
            party: party.to_string(),
            chip: self.config.profile.chip.clone(),
            available,
            trm: self.database.trm.clone(),
            page: doorbell.party_page,
        }
    }

    /// Whether `core` is the application processor or one of the chip's
    /// declared coprocessors.
    fn is_core(&self, core: VisibleCore) -> bool {
        match core {
            VisibleCore::Ap => true,
            VisibleCore::Mcore(name) => self
                .database
                .cp
                .iter()
                .any(|cp| cp.name.eq_ignore_ascii_case(name.as_str())),
            VisibleCore::Rcore(name) => self
                .database
                .cp
                .iter()
                .any(|cp| cp.name.eq_ignore_ascii_case(name.as_str())),
            VisibleCore::Rvcore(name) => self
                .database
                .cp
                .iter()
                .any(|cp| cp.name.eq_ignore_ascii_case(&name.to_string())),
        }
    }

    /// Whether `party` names one of the chip's visible runtime endpoints.
    fn is_party(&self, party: Party) -> bool {
        self.is_core(party.core())
    }
}

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

    const MANIFEST: &str = include_str!("../Consortium.example.stm32mp257.toml");

    fn imx95_cached_manifest(secondary: &str, doorbell: &str, base: u32, length: u32) -> String {
        format!(
            r#"
                [profile]
                chip = "mimx9596xvt"
                shared = "./shared"
                deploy_root = "/opt/consortium"

                [[ipc.channel]]
                name = "probe"
                doorbell = "{doorbell}"
                pattern = "memory"
                primary = "linux"
                secondary = "{secondary}"
                party.linux = {{ chan = 0, type = "Ping" }}
                party.{secondary} = {{ chan = 1, type = "Pong" }}
                config.memory = {{ base = {base}, length = {length} }}
                config.cache = true
                mtu = 128
            "#
        )
    }

    #[test]
    fn loads_example_manifest() {
        let session = Session::from_toml(MANIFEST).expect("example manifest should load");

        assert_eq!(session.config.profile.chip, "stm32mp257fak3");
        assert_eq!(session.database.name, "STM32MP25");
        assert_eq!(session.config.ipc.channels.len(), 2);
        assert_eq!(session.config.ipc.channels[0].doorbell, "ipcc1");
        assert_eq!(
            session.config.ipc.channels[0].endpoints[&Party::AcoreNonSecure].chan,
            0
        );
        assert_eq!(
            session.config.ipc.channels[0].endpoints[&"cm33".parse::<Party>().unwrap()].r#type,
            "MotionControl"
        );
        assert_eq!(
            session.config.ipc.channels[0].primary,
            Party::AcoreNonSecure
        );
        assert_eq!(
            session.config.ipc.channels[0].secondary,
            "cm33".parse::<Party>().unwrap()
        );
        assert_eq!(session.config.endpoints[&Party::AcoreNonSecure], "./app");
        assert_eq!(
            session
                .config
                .tee
                .as_ref()
                .unwrap()
                .uuid
                .to_string()
                .to_uppercase(),
            "48551DD5-74B2-4D24-BF9D-A09F02F5C56F"
        );

        // `[dbg] mode` flattens alongside the `[dbg.<core>]` tables.
        assert_eq!(
            session.config.dbg.mode,
            consortium_cfg_common::config::DbgMode::Auto
        );
        let cm33_dbg = session.config.dbg.cores[&"cm33".parse::<VisibleCore>().unwrap()];
        assert_eq!(cm33_dbg.mtu, 64);
        assert_eq!(cm33_dbg.memory.length, 0x2000);

        let i2c1 = &session.config.peripheral["i2c1"];
        assert_eq!(i2c1.owner, VisibleCore::Ap);
        assert_eq!(i2c1.pin["sda"], "PB0");

        let spi1 = &session.config.peripheral["spi1"];
        assert_eq!(spi1.owner, "cm33".parse().unwrap());
    }

    #[test]
    fn rejects_unknown_doorbell() {
        let manifest = r#"
            [profile]
            chip = "stm32mp257fak3"
            shared = "./shared"
            deploy_root = "/opt/consortium"

            [[ipc.channel]]
            name = "probe"
            doorbell = "nope"
            pattern = "memory"
            primary = "linux"
            secondary = "cm33"
            party.linux = { chan = 0, type = "Ping" }
            party.cm33 = { chan = 1, type = "Pong" }
            config.memory = { base = 0x00040000, length = 0x00008000 }
            mtu = 128
        "#;

        let err = Session::from_toml(manifest).unwrap_err();
        assert!(matches!(err, CfgError::UnknownDoorbell { .. }));
        // The hint lists real doorbells with their TRM pages.
        assert!(err.to_string().contains("HSEM (TRM p. 1306)"));
    }

    #[test]
    fn rejects_doorbell_party_unavailable() {
        let manifest = r#"
            [profile]
            chip = "stm32mp257fak3"
            shared = "./shared"
            deploy_root = "/opt/consortium"

            [[ipc.channel]]
            name = "probe"
            doorbell = "ipcc1"
            pattern = "memory"
            primary = "linux"
            secondary = "cm0p"
            party.cm0p = { chan = 0, type = "PowerMode" }
            config.memory = { base = 0x00040000, length = 0x00008000 }
            mtu = 128
        "#;

        let err = Session::from_toml(manifest).unwrap_err();
        assert!(matches!(err, CfgError::DoorbellPartyUnavailable { .. }));
        assert!(err.to_string().contains("Configured parties: linux"));
        assert!(err.to_string().contains("TRM"));
    }

    #[test]
    fn rejects_unavailable_doorbell_channel() {
        let manifest = r#"
            [profile]
            chip = "stm32mp257fak3"
            shared = "./shared"
            deploy_root = "/opt/consortium"

            [[ipc.channel]]
            name = "probe"
            doorbell = "ipcc1"
            pattern = "memory"
            primary = "linux"
            secondary = "cm33"
            party.linux = { chan = 32, type = "Ping" }
            config.memory = { base = 0x00040000, length = 0x00008000 }
            mtu = 128
        "#;

        // IPCC1 has 32 channels, so `chan = 32` is one past the last.
        assert!(matches!(
            Session::from_toml(manifest),
            Err(CfgError::DoorbellChannelUnavailable { .. })
        ));
    }

    #[test]
    fn rejects_duplicate_doorbell_channel() {
        let manifest = r#"
            [profile]
            chip = "stm32mp257fak3"
            shared = "./shared"
            deploy_root = "/opt/consortium"

            [[ipc.channel]]
            name = "probe"
            doorbell = "ipcc1"
            pattern = "memory"
            primary = "linux"
            secondary = "cm33"
            party.linux = { chan = 0, type = "Ping" }
            party.cm33 = { chan = 0, type = "Pong" }
            config.memory = { base = 0x00040000, length = 0x00008000 }
            mtu = 128
        "#;

        assert!(matches!(
            Session::from_toml(manifest),
            Err(CfgError::DoorbellChannelDuplicate { .. })
        ));
    }

    /// IPC region `0x40_0000..0x48_0000` sits outside every SRAM window on
    /// STM32MP25 (SRAM1 starts at `0x04_0000`, and the SRAM windows end at
    /// `0x08_0000`), so it must be rejected.
    #[test]
    fn rejects_region_outside_sram() {
        let manifest = r#"
            [profile]
            chip = "stm32mp257fak3"
            shared = "./shared"
            deploy_root = "/opt/consortium"

            [[ipc.channel]]
            name = "probe"
            doorbell = "ipcc1"
            pattern = "memory"
            primary = "linux"
            secondary = "cm33"
            party.linux = { chan = 0, type = "Ping" }
            config.memory = { base = 0x00400000, length = 0x00080000 }
            mtu = 128
        "#;

        assert!(matches!(
            Session::from_toml(manifest),
            Err(CfgError::RegionOutOfBounds { .. })
        ));
    }

    /// A non-power-of-two region length is not MPU-expressible.
    #[test]
    fn rejects_non_power_of_two_region() {
        let manifest = r#"
            [profile]
            chip = "stm32mp257fak3"
            shared = "./shared"
            deploy_root = "/opt/consortium"

            [[ipc.channel]]
            name = "probe"
            doorbell = "ipcc1"
            pattern = "memory"
            primary = "linux"
            secondary = "cm33"
            party.linux = { chan = 0, type = "Ping" }
            config.memory = { base = 0x00400000, length = 0x00006000 }
            mtu = 128
        "#;

        assert!(matches!(
            Session::from_toml(manifest),
            Err(CfgError::RegionNotMpuAligned { .. })
        ));
    }

    /// Manifest with one acknowledgement-capable MU channel, parameterised so each test
    /// can break exactly one thing about it.
    fn imx95_ack_manifest(linux_ack: &str, cm7_ack: &str, ack: bool) -> String {
        format!(
            r#"
            [profile]
            chip = "mimx9596xvt"
            shared = "./shared"
            deploy_root = "/opt/consortium"

            [[ipc.channel]]
            name = "sensor"
            doorbell = "mu7"
            pattern = "memory"
            primary = "linux"
            secondary = "cm7"
            party.linux = {{ chan = 6, {linux_ack} type = "SensorData" }}
            party.cm7 = {{ chan = 7, {cm7_ack} type = "MotionControl" }}
            config.memory = {{ base = 0x00488000, length = 0x4000 }}
            config.ack = {ack}
            mtu = 128
        "#
        )
    }

    #[test]
    fn accepts_ack_channels_alongside_the_data_lines() {
        let manifest = imx95_ack_manifest("ack_chan = 0,", "ack_chan = 1,", true);
        Session::from_toml(&manifest).expect("distinct ack lines should be valid");
    }

    /// Acknowledgement needs a line of its own, so opting in without naming one is a
    /// configuration error rather than a silent fallback.
    #[test]
    fn rejects_ack_without_an_ack_channel() {
        let manifest = imx95_ack_manifest("", "ack_chan = 1,", true);
        let err = Session::from_toml(&manifest).unwrap_err();
        assert!(matches!(err, CfgError::IpcAckChannelMissing { .. }));
        assert!(err.to_string().contains("ack_chan"));
    }

    /// The mirror image: a line declared for a capability the channel never enables would
    /// silently reserve a doorbell channel that nothing rings.
    #[test]
    fn rejects_an_ack_channel_without_the_capability() {
        let manifest = imx95_ack_manifest("ack_chan = 0,", "ack_chan = 1,", false);
        assert!(matches!(
            Session::from_toml(&manifest),
            Err(CfgError::IpcAckChannelUnexpected { .. })
        ));
    }

    /// An acknowledgement line is a doorbell channel like any other, so it goes through the
    /// same collision check — here it aliases the peer's data line, which would make the
    /// peer's receive half and this side's acknowledgement wait share one line.
    #[test]
    fn rejects_an_ack_channel_that_aliases_a_data_line() {
        let manifest = imx95_ack_manifest("ack_chan = 7,", "ack_chan = 1,", true);
        assert!(matches!(
            Session::from_toml(&manifest),
            Err(CfgError::DoorbellChannelDuplicate { channel: 7, .. })
        ));
    }

    /// ...and through the same bounds check: MU exposes eight channels.
    #[test]
    fn rejects_an_out_of_range_ack_channel() {
        let manifest = imx95_ack_manifest("ack_chan = 0,", "ack_chan = 64,", true);
        assert!(matches!(
            Session::from_toml(&manifest),
            Err(CfgError::DoorbellChannelUnavailable { channel: 64, .. })
        ));
    }

    #[test]
    fn accepts_cached_non_power_of_two_region() {
        let manifest = imx95_cached_manifest("cm7", "mu7", 0x0048_8000, 0x6000);
        Session::from_toml(&manifest).expect("cache-line-aligned cached region should be valid");
    }

    #[test]
    fn rejects_region_too_small_for_aligned_slot_pair() {
        let manifest = imx95_cached_manifest("cm7", "mu7", 0x0048_8000, 0x200);
        let err = Session::from_toml(&manifest).unwrap_err();
        assert!(matches!(
            err,
            CfgError::IpcRegionTooSmall {
                length: 0x200,
                mtu: 128,
                required: 0x24c,
                ..
            }
        ));
        assert!(err.to_string().contains("bidirectional slot pair"));
    }

    #[test]
    fn accepts_smallest_cache_aligned_region_for_slot_pair() {
        let manifest = imx95_cached_manifest("cm7", "mu7", 0x0048_8000, 0x280);
        Session::from_toml(&manifest)
            .expect("0x280 bytes contains both aligned 128-byte-MTU slots");
    }

    #[test]
    fn rejects_cached_region_with_partial_cache_line() {
        for (base, length) in [(0x0048_8000, 0x4020), (0x0048_8020, 0x4000)] {
            let manifest = imx95_cached_manifest("cm7", "mu7", base, length);
            assert!(matches!(
                Session::from_toml(&manifest),
                Err(CfgError::RegionNotCacheAligned { .. })
            ));
        }
    }

    #[test]
    fn rejects_cached_region_on_cacheless_controller() {
        let manifest = imx95_cached_manifest("cm33", "mu1", 0x0048_8000, 0x4000);
        let err = Session::from_toml(&manifest).unwrap_err();
        assert!(matches!(err, CfgError::IpcCacheUnsupported { .. }));
        assert!(err.to_string().contains("cm33"));
    }

    /// A region whose base is not aligned to its (power-of-two) size is not
    /// MPU-expressible.
    #[test]
    fn rejects_misaligned_region() {
        // length 0x4000 (16 KiB) but base 0x402000 is only 8 KiB-aligned.
        let manifest = r#"
            [profile]
            chip = "stm32mp257fak3"
            shared = "./shared"
            deploy_root = "/opt/consortium"

            [[ipc.channel]]
            name = "probe"
            doorbell = "ipcc1"
            pattern = "memory"
            primary = "linux"
            secondary = "cm33"
            party.linux = { chan = 0, type = "Ping" }
            config.memory = { base = 0x00402000, length = 0x00004000 }
            mtu = 128
        "#;

        let err = Session::from_toml(manifest).unwrap_err();
        assert!(matches!(err, CfgError::RegionNotMpuAligned { .. }));
        assert!(err.to_string().contains("aligned"));
    }

    /// A region smaller than the ARMv7-M minimum (32 bytes) is rejected.
    #[test]
    fn rejects_subminimal_region() {
        let manifest = r#"
            [profile]
            chip = "stm32mp257fak3"
            shared = "./shared"
            deploy_root = "/opt/consortium"

            [[ipc.channel]]
            name = "probe"
            doorbell = "ipcc1"
            pattern = "memory"
            primary = "linux"
            secondary = "cm33"
            party.linux = { chan = 0, type = "Ping" }
            config.memory = { base = 0x00400000, length = 0x10 }
            mtu = 128
        "#;

        assert!(matches!(
            Session::from_toml(manifest),
            Err(CfgError::RegionNotMpuAligned { .. })
        ));
    }

    /// `[dbg.ap]` is rejected: the AP is always the host, never a logger.
    #[test]
    fn rejects_dbg_on_application_processor() {
        let manifest = r#"
            [profile]
            chip = "stm32mp257fak3"
            shared = "./shared"
            deploy_root = "/opt/consortium"

            [dbg.ap]
            memory = { base = 0x00044000, length = 0x00002000 }
            mtu = 64
        "#;

        assert!(matches!(
            Session::from_toml(manifest),
            Err(CfgError::DbgHostNotLoggable)
        ));
    }

    /// A `[dbg.<core>]` table naming a core the chip does not expose is rejected.
    #[test]
    fn rejects_dbg_on_unknown_core() {
        let manifest = r#"
            [profile]
            chip = "stm32mp257fak3"
            shared = "./shared"
            deploy_root = "/opt/consortium"

            [dbg.cm7]
            memory = { base = 0x00044000, length = 0x00002000 }
            mtu = 64
        "#;

        assert!(matches!(
            Session::from_toml(manifest),
            Err(CfgError::DbgCoreNotVisible { .. })
        ));
    }

    #[test]
    fn rejects_overlapping_regions() {
        let manifest = r#"
            [profile]
            chip = "stm32mp257fak3"
            shared = "./shared"
            deploy_root = "/opt/consortium"

            [dbg.cm33]
            memory = { base = 0x00044000, length = 0x00002000 }
            mtu = 64

            [[ipc.channel]]
            name = "probe"
            doorbell = "ipcc1"
            pattern = "memory"
            primary = "linux"
            secondary = "cm33"
            party.linux = { chan = 0, type = "Ping" }
            config.memory = { base = 0x00040000, length = 0x00008000 }
            mtu = 128
        "#;

        assert!(matches!(
            Session::from_toml(manifest),
            Err(CfgError::RegionOverlap { .. })
        ));
    }

    /// A coprocessor-owned peripheral present in that core's chip map validates.
    #[test]
    fn accepts_peripheral_present_on_core() {
        let manifest = r#"
            [profile]
            chip = "stm32mp257fak3"
            shared = "./shared"
            deploy_root = "/opt/consortium"

            [[ipc.channel]]
            name = "probe"
            doorbell = "ipcc1"
            pattern = "memory"
            primary = "linux"
            secondary = "cm33"
            party.linux = { chan = 0, type = "Ping" }
            config.memory = { base = 0x00040000, length = 0x00002000 }
            mtu = 128

            [peripheral.i2c1]
            owner = "cm33"
            clock = 64000000
            frequency = 100000
        "#;

        assert!(Session::from_toml(manifest).is_ok());
    }

    /// A coprocessor-owned peripheral absent from that core's chip map is
    /// rejected: the map is the accessibility filter.
    #[test]
    fn rejects_peripheral_absent_on_core() {
        let manifest = r#"
            [profile]
            chip = "stm32mp257fak3"
            shared = "./shared"
            deploy_root = "/opt/consortium"

            [[ipc.channel]]
            name = "probe"
            doorbell = "ipcc1"
            pattern = "memory"
            primary = "linux"
            secondary = "cm33"
            party.linux = { chan = 0, type = "Ping" }
            config.memory = { base = 0x00040000, length = 0x00002000 }
            mtu = 128

            [peripheral.nonexistent99]
            owner = "cm33"
        "#;

        assert!(matches!(
            Session::from_toml(manifest),
            Err(CfgError::PeripheralNotOnCore { .. })
        ));
    }

    const MP235_MANIFEST: &str = include_str!("../Consortium.example.stm32mp235.toml");

    /// An STM32MP23 manifest with one CM33 channel and `extra` appended.
    fn mp235_manifest(doorbell: &str, secondary: &str, base: u32, extra: &str) -> String {
        format!(
            r#"
                [profile]
                chip = "stm32mp235fak3"
                shared = "./shared"
                deploy_root = "/opt/consortium"

                [[ipc.channel]]
                name = "probe"
                doorbell = "{doorbell}"
                pattern = "memory"
                primary = "linux"
                secondary = "{secondary}"
                party.linux = {{ chan = 0, type = "Ping" }}
                party.{secondary} = {{ chan = 1, type = "Pong" }}
                config.memory = {{ base = {base}, length = 0x4000 }}
                mtu = 128

                {extra}
            "#
        )
    }

    #[test]
    fn loads_mp235_example_manifest() {
        let session = Session::from_toml(MP235_MANIFEST).expect("MP235 example should load");
        assert_eq!(session.database.name, "STM32MP23");
        assert_eq!(session.config.ipc.channels.len(), 1);
    }

    /// IPCC2 is the MP25 CM0+'s mailbox; MP23 has no CM0+ and no IPCC2.
    #[test]
    fn mp235_rejects_ipcc2() {
        let manifest = mp235_manifest("ipcc2", "cm33", 0x0006_4000, "");
        assert!(matches!(
            Session::from_toml(&manifest),
            Err(CfgError::UnknownDoorbell { .. })
        ));
    }

    #[test]
    fn mp235_rejects_a_cm0p_endpoint() {
        let manifest = mp235_manifest("ipcc1", "cm0p", 0x0006_4000, "");
        assert!(Session::from_toml(&manifest).is_err());
    }

    /// I2C3 exists on MP25 but not MP23 (DS14634: 4x I2C, i.e. I2C1/2/7/8).
    #[test]
    fn mp235_rejects_an_mp25_only_peripheral() {
        let i2c = |name: &str| format!("[peripheral.{name}]\nowner = \"cm33\"");
        let absent = mp235_manifest("ipcc1", "cm33", 0x0006_4000, &i2c("i2c3"));
        assert!(matches!(
            Session::from_toml(&absent),
            Err(CfgError::PeripheralNotOnCore { .. })
        ));
        let present = mp235_manifest("ipcc1", "cm33", 0x0006_4000, &i2c("i2c8"));
        assert!(Session::from_toml(&present).is_ok());
    }

    /// The 32 KB MP23 lacks against MP25 is LPSRAM1-3 (776 KB vs 808 KB).
    #[test]
    fn mp235_rejects_an_lpsram_window() {
        let manifest = mp235_manifest("ipcc1", "cm33", 0x000C_4000, "");
        assert!(Session::from_toml(&manifest).is_err());
    }
}