consortium-cfg 0.3.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
//! Shared-memory IPC code generation: the largest component, and the one that
//! removes the most hand-written firmware.
//!
//! What a manifest's `[[ipc.channel]]` entries become here:
//!
//! - a [`Channel`] per direction, carrying its validated doorbell channel id and the
//!   message type name;
//! - a [`Transceiver`] pairing two channels over one shared window;
//! - a [`ShuHan`] aggregating every transceiver on a core; [`initialize_instances`]
//!   emits channel markers, instance metadata, and transport installation.
//!
//! # Doorbell ownership across transceivers
//!
//! On a controller core a doorbell is a *singleton* the driver consumes, so it can
//! move exactly once — but two transceivers may legitimately share one doorbell block
//! (disjoint channels of the same MU or IPCC). [`DoorbellSource`] resolves that: the
//! first user takes the constructor parameter ([`Owned`](DoorbellSource::Owned)) and
//! later ones borrow from it ([`Shared`](DoorbellSource::Shared)).
//!
//! The AP has no singletons at all — it reaches its doorbells through UIO `mmap`, so
//! every AP-side source is [`Uio`](DoorbellSource::Uio). A controller core with no
//! bundled chip map, or whose map does not reach the window, falls back to the same
//! address-based construction it has always used.

use core::fmt;
use std::str::FromStr;

use consortium_cfg_common::{
    config::{Codec, VisibleCore},
    database::HardwareDoorbellPeripheralType,
};
use proc_macro2::{Literal, Span, TokenStream};
use quote::format_ident;
use syn::{Ident, Path};

use crate::{
    components::{address::Address, region::Region},
    error::CfgError,
};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Channel {
    /// doorbell channel id, verified before codegen
    pub doorbell_chan: u8,
    /// type name
    pub type_name: String,
    /// buffer name
    pub buffer_name: String,
}

/// The codec type path for `codec`, used by both endpoint construction and the
/// transceiver type signature.
///
/// `scratch` is the channel MTU; only [`RkyvCodec`](consortium_codec::RkyvCodec)
/// is generic over it, sizing the on-stack serialization scratch in the
/// `no_std` (no-`alloc`) encode path. The other codecs ignore it.
fn codec_path(codec: Codec, scratch: u32) -> TokenStream {
    match codec {
        Codec::Postcard => quote::quote! { ::consortium_codec::PostcardCodec },
        Codec::Prost => quote::quote! { ::consortium_codec::ProstCodec },
        Codec::Rkyv => {
            let scratch = Literal::usize_suffixed(scratch as usize);
            quote::quote! { ::consortium_codec::RkyvCodec<#scratch> }
        }
    }
}

/// Generates channel singleton markers, their instance bindings, and the
/// transport installer called by generated `init`.
pub fn initialize_instances(
    shuhan: &ShuHan,
    core: VisibleCore,
    uio_ident: &Ident,
    ty_crate: &Path,
    hal_crate: &str,
    available: &[String],
) -> TokenStream {
    let (doorbell_params, sources) = shuhan.doorbell_sources(core, available);
    let markers = shuhan
        .transceivers
        .iter()
        .map(|t| Ident::new(&t.name.to_ascii_uppercase(), Span::call_site()))
        .collect::<Vec<_>>();

    let instance_impls = shuhan
        .transceivers
        .iter()
        .zip(markers.iter())
        .map(|(t, marker)| {
            let side = t
                .side(core)
                .expect("core must participate in generated transceiver");
            let side_ty = match side {
                DoorbellRingerSide::Primary => quote::quote! { ::consortium_ipc::Primary },
                DoorbellRingerSide::Secondary => quote::quote! { ::consortium_ipc::Secondary },
            };
            let doorbell_ty = t.doorbell.as_type(side);
            let region_ty = t.region_ty(core);
            let codec_ty = codec_path(t.codec, t.mtu);
            let (tx, rx) = match side {
                DoorbellRingerSide::Primary => (&t.channel_primary.1, &t.channel_secondary.1),
                DoorbellRingerSide::Secondary => (&t.channel_secondary.1, &t.channel_primary.1),
            };
            let tx_ty = Ident::new(&tx.type_name, Span::call_site());
            let rx_ty = Ident::new(&rx.type_name, Span::call_site());
            let chan_tx = tx.doorbell_chan;
            let chan_rx = rx.doorbell_chan;
            let mtu = Literal::usize_suffixed(t.mtu as usize);
            quote::quote! {
                ::consortium_ipc_transport_memory::impl_channel!(
                    #marker,
                    #side_ty,
                    #doorbell_ty,
                    #region_ty,
                    #ty_crate::#tx_ty,
                    #ty_crate::#rx_ty,
                    #codec_ty,
                    #chan_tx,
                    #chan_rx,
                    #mtu,
                );
            }
        })
        .collect::<Vec<_>>();

    let installs = shuhan
        .transceivers
        .iter()
        .zip(sources.iter())
        .zip(markers.iter())
        .map(|((t, source), marker)| {
            let transport = t.build_field_init(core, uio_ident, source.clone(), hal_crate);
            if core == VisibleCore::Ap {
                let region_uio = t.region.address.ap.uio_id;
                let doorbell_uio = t.doorbell_address.ap.uio_id;
                quote::quote! {
                    let mut transport = #transport;
                    transport.keep_alive(#uio_ident[#region_uio].clone());
                    transport.keep_alive(#uio_ident[#doorbell_uio].clone());
                    ::consortium_ipc_transport_memory::install::<channels::#marker>(transport);
                }
            } else {
                quote::quote! {
                    ::consortium_ipc_transport_memory::install::<channels::#marker>(#transport);
                }
            }
        })
        .collect::<Vec<_>>();

    let installer = if core == VisibleCore::Ap {
        quote::quote! {
            fn __consortium_install_channels(
                #uio_ident: &[::std::sync::Arc<::consortium_runtime_app::uio::UioDevice>],
            ) -> ::core::result::Result<(), ::consortium_runtime_app::uio::UioDeviceError> {
                #(#installs)*
                ::core::result::Result::Ok(())
            }
        }
    } else {
        let hal: syn::Path = syn::parse_str(hal_crate).expect("hal_crate must be a valid path");
        let parameters = doorbell_params.iter().map(|singleton| {
            let param = doorbell_param(singleton);
            quote::quote! {
                #param: #hal::Peri<'static, #hal::peripherals::#singleton>
            }
        });
        quote::quote! {
            #[cfg(target_arch = "arm")]
            fn __consortium_install_channels(#(#parameters),*) {
                #(#installs)*
            }
        }
    };

    quote::quote! {
        ::consortium_ipc_transport_memory::channels!(#(#markers),*);
        #(#instance_impls)*
        #installer
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Transceiver {
    /// the transceiver name, used for codegen
    pub name: String,
    /// doorbell base address pointer
    pub doorbell_address: Address,
    /// max transmission unit
    pub mtu: u32,
    /// codec name
    pub codec: Codec,
    /// address
    pub region: Region,
    /// primary to secondary channel
    pub channel_primary: (VisibleCore, Channel),
    /// secondary to primary channel
    pub channel_secondary: (VisibleCore, Channel),
    /// type-a doorbell metadata
    pub doorbell: DoorbellMeta,
}

impl Transceiver {
    pub fn max_channels(&self) -> u32 {
        // Length <= Descriptor + message slot * max channels.
        let total_len = u64::from(self.region.length);
        let slot_base = consortium_ipc_transport_memory::slot_offset(0, self.mtu as usize) as u64;
        let slot_size = u64::from(consortium_ipc_transport_memory::slot::SLOT_HEADER as u32)
            + u64::from(self.mtu);
        let first_slot_end = slot_base.saturating_add(slot_size);
        if total_len < first_slot_end {
            return 0;
        }

        let stride = consortium_ipc_transport_memory::slot_stride(self.mtu as usize) as u64;
        let slots = 1 + (total_len - first_slot_end) / stride;
        let slots = slots.min(consortium_ipc_transport_memory::CHANNEL_NUM_MAX as u64);
        (slots / 2 * 2) as u32
    }

    /// get the side
    fn side(&self, core: VisibleCore) -> Option<DoorbellRingerSide> {
        if self.channel_primary.0 == core {
            Some(DoorbellRingerSide::Primary)
        } else if self.channel_secondary.0 == core {
            Some(DoorbellRingerSide::Secondary)
        } else {
            None
        }
    }

    /// The shared-memory region type for this transceiver, in type position.
    fn region_ty(&self, core: VisibleCore) -> TokenStream {
        match (core, self.region.cache) {
            (VisibleCore::Ap, _) | (_, false) => {
                quote::quote! { ::consortium_shared_memory::regions::UncachedRegion }
            }
            (_, true) => quote::quote! { ::consortium_shared_memory::regions::CachedRegion },
        }
    }

    /// Build the region, doorbell, channel ids, and unsplit transport installed
    /// by synchronous generated init. This performs no peer handshake.
    pub fn build_field_init(
        &self,
        core: VisibleCore,
        uio_ident: &Ident,
        source: DoorbellSource,
        hal_crate: &str,
    ) -> TokenStream {
        let side = self
            .side(core)
            .expect("core must be either primary or secondary for the transceiver");

        let region_ident = format_ident!("region");
        let region_init = self.region.initialize(core, uio_ident);

        let doorbell_ident = format_ident!("doorbell");
        // The IRQ service binds to the *doorbell's* UIO device, not the
        // shared-memory region's: only the doorbell device is declared with an
        // interrupt, so only it is opened with `enable_irq` and runs an
        // `irq_loop`. Binding the service to the region device registers it on a
        // handle whose IRQ listener never runs, and the AP never wakes.
        let doorbell_code = self.doorbell.initialize(&DoorbellSite {
            side,
            core,
            uio_ident,
            uio_id: self.doorbell_address.ap.uio_id,
            base: self.doorbell_address.memory_lookup(core, uio_ident),
            ident: &doorbell_ident,
            source: &source,
            hal_crate,
        });

        let chan_id_tx = match side {
            DoorbellRingerSide::Primary => &self.channel_primary.1.doorbell_chan,
            DoorbellRingerSide::Secondary => &self.channel_secondary.1.doorbell_chan,
        };
        let chan_id_rx = match side {
            DoorbellRingerSide::Primary => &self.channel_secondary.1.doorbell_chan,
            DoorbellRingerSide::Secondary => &self.channel_primary.1.doorbell_chan,
        };

        let transport_side_ty = match side {
            DoorbellRingerSide::Primary => quote::quote! { ::consortium_ipc::Primary },
            DoorbellRingerSide::Secondary => quote::quote! { ::consortium_ipc::Secondary },
        };
        // The transport's descriptor base is the shared-memory region base
        // (offset 0x00), not the doorbell register window.
        let transport_address = self.region.address.memory_lookup(core, uio_ident);

        quote::quote! {{
            /// SAFETY: automatically generated by Consortium after matching with database
            let #region_ident = #region_init;
            #doorbell_code
            /// SAFETY: doorbell channel is verified to be valid in the config.
            let chan_tx = unsafe { ::consortium_ipc::Chan::new_unchecked(#chan_id_tx) };
            /// SAFETY: doorbell channel is verified to be valid in the config.
            let chan_rx = unsafe { ::consortium_ipc::Chan::new_unchecked(#chan_id_rx) };
            /// SAFETY: the base is offset 0x00 of the validated shared-memory
            /// region, and the channels/doorbell/region are this side's.
            unsafe {
                ::consortium_ipc_transport_memory::SharedMemoryTransport::<#transport_side_ty, _, _>::new(
                    chan_tx,
                    chan_rx,
                    #doorbell_ident,
                    #region_ident,
                    (#transport_address) as *mut u8,
                )
            }
        }}
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DoorbellMeta {
    /// doorbell type
    pub r#type: HardwareDoorbellPeripheralType,
    /// id
    pub id: Option<u8>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DoorbellRingerSide {
    Primary,
    Secondary,
}

/// Everything one transceiver's doorbell construction needs at its emit site.
///
/// `uio_id` must index the UIO device that *owns the doorbell's interrupt* —
/// the same device `base` is mapped from. Only devices declaring an `irq` are
/// opened with `enable_irq`, so only they run an `irq_loop` that can dispatch
/// the bound service.
pub struct DoorbellSite<'a> {
    /// Which side of the doorbell the core being generated drives.
    pub side: DoorbellRingerSide,
    /// The core being generated.
    pub core: VisibleCore,
    /// Ident of the opened-UIO-device slice in scope (AP only).
    pub uio_ident: &'a Ident,
    /// Index of the doorbell's own UIO device (AP only).
    pub uio_id: usize,
    /// Expression evaluating to the doorbell's register-window base (AP only).
    pub base: TokenStream,
    /// Ident to bind the constructed doorbell to.
    pub ident: &'a Ident,
    /// Where the doorbell handle comes from on this core.
    pub source: &'a DoorbellSource,
    /// Chip HAL crate path, for the `steal` fallback on a shared block.
    pub hal_crate: &'a str,
}

/// Where one transceiver's doorbell handle comes from on the core being
/// generated.
#[derive(Debug, Clone)]
pub enum DoorbellSource {
    /// Linux/AP: an `mmap` of the doorbell's UIO device, which has no
    /// peripheral singleton.
    Uio,
    /// Controller core, first user of this block: takes the singleton passed to
    /// the generated transport installer.
    Owned(Ident),
    /// Controller core, a later transceiver on a block another one already
    /// owns: steals the singleton, since the two drive disjoint channels.
    Shared(Ident),
}

impl DoorbellMeta {
    /// The chip HAL peripheral singleton naming this doorbell's register window
    /// on `side`, spelled as the chip database does.
    ///
    /// MU windows are per-side (`MU7_MUA` / `MU7_MUB`); HSEM and IPCC expose one
    /// block with a bank per core, so their singleton is side-independent and
    /// the side stays a type parameter of the doorbell.
    pub fn singleton(&self, side: DoorbellRingerSide) -> Ident {
        let id = self.id.unwrap_or(1);
        match self.r#type {
            HardwareDoorbellPeripheralType::Mu => {
                let window = match side {
                    DoorbellRingerSide::Primary => "MUA",
                    DoorbellRingerSide::Secondary => "MUB",
                };
                format_ident!("MU{id}_{window}")
            }
            HardwareDoorbellPeripheralType::Hsem => format_ident!("HSEM"),
            HardwareDoorbellPeripheralType::Ipcc => format_ident!("IPCC{id}"),
        }
    }

    /// The doorbell's crate path, type name, and IPC side marker idents.
    ///
    /// Shared by [`as_path`](Self::as_path) (expression position) and
    /// [`as_type`](Self::as_type) (type position), which differ only in turbofish.
    fn idents(&self, side: DoorbellRingerSide) -> (Ident, Ident, Ident) {
        let crate_ident = format_ident!(
            "consortium_ipc_doorbell_{}",
            self.r#type.to_string().to_lowercase()
        );
        let type_ident = format_ident!("{}Doorbell", self.r#type.to_string());
        let side_ident = format_ident!(
            "{}",
            match side {
                DoorbellRingerSide::Primary => "Primary",
                DoorbellRingerSide::Secondary => "Secondary",
            }
        );
        (crate_ident, type_ident, side_ident)
    }

    /// The doorbell type in expression/path position (turbofish form), for
    /// `<doorbell>::new(...)` construction.
    pub fn as_path(&self, side: DoorbellRingerSide) -> TokenStream {
        let id = self.id.unwrap_or(1) as usize;
        let (crate_ident, type_ident, side_ident) = self.idents(side);
        quote::quote! {
            ::#crate_ident::#type_ident::<::consortium_ipc::#side_ident, #id>
        }
    }

    /// The vector body that services this doorbell's interrupt from `side`.
    ///
    /// Each doorbell crate exposes one bare-metal entry point that masks the
    /// asserted lines before waking the futures waiting on them. All of them
    /// derive the register window from the crate's own vetted address table, so
    /// the call carries only the side and instance — no MMIO base ever appears
    /// in generated code.
    pub fn service_call(&self, side: DoorbellRingerSide) -> TokenStream {
        let id = self.id.unwrap_or(1) as usize;
        let (crate_ident, _, side_ident) = self.idents(side);
        match self.r#type {
            // HSEM shares one waker across the block, and its `wait` future owns
            // arming and masking the line, so the vector only wakes.
            HardwareDoorbellPeripheralType::Hsem => quote::quote! {
                ::#crate_ident::notify();
            },
            HardwareDoorbellPeripheralType::Ipcc => quote::quote! {
                ::#crate_ident::notify_rx_occupied_interrupt::<
                    ::consortium_ipc::#side_ident, #id
                >();
            },
            HardwareDoorbellPeripheralType::Mu => quote::quote! {
                ::#crate_ident::notify_gi_interrupt::<
                    ::consortium_ipc::#side_ident, #id
                >();
            },
        }
    }

    /// The doorbell type in type position (no turbofish), for naming the
    /// doorbell inside a transport type signature.
    pub fn as_type(&self, side: DoorbellRingerSide) -> TokenStream {
        let id = self.id.unwrap_or(1) as usize;
        let (crate_ident, type_ident, side_ident) = self.idents(side);
        quote::quote! {
            ::#crate_ident::#type_ident<::consortium_ipc::#side_ident, #id>
        }
    }

    /// Emit the doorbell construction, and on the AP its UIO IRQ binding.
    pub fn initialize(&self, site: &DoorbellSite<'_>) -> TokenStream {
        let DoorbellSite {
            side,
            core,
            uio_ident,
            uio_id: doorbell_uio_id,
            base: doorbell_base,
            ident: doorbell_ident,
            source,
            hal_crate,
        } = site;
        let (side, core) = (*side, *core);
        let doorbell = self.as_path(side);

        // On the AP the UIO IRQ fanout runs a per-doorbell service on every M→A
        // interrupt. Masking doorbells (IPCC, MU) bind their own IRQ entry point
        // — cloned so the original can still move into the transport — which
        // masks the asserted lines *before* waking, so a level-sensitive line
        // does not immediately re-fire the UIO IRQ. Doorbells with no masking
        // fall back to the plain `Notify` fanout.
        let binding_uio_stmt = match core {
            VisibleCore::Ap => {
                let bind = match self.r#type {
                    HardwareDoorbellPeripheralType::Ipcc => quote::quote! {
                        let __service_db = #doorbell_ident.clone();
                        #uio_ident[#doorbell_uio_id].bind_service(::std::sync::Arc::new(
                            move || __service_db.notify_rx_occupied_interrupt(),
                        ));
                    },
                    HardwareDoorbellPeripheralType::Mu => quote::quote! {
                        let __service_db = #doorbell_ident.clone();
                        #uio_ident[#doorbell_uio_id].bind_service(::std::sync::Arc::new(
                            move || __service_db.notify_gi_interrupt(),
                        ));
                    },
                    HardwareDoorbellPeripheralType::Hsem => quote::quote! {
                        #uio_ident[#doorbell_uio_id].bind_notifier(#doorbell_ident.notifier());
                    },
                };
                Some(bind)
            }
            _ => None,
        };

        // The AP reaches the doorbell through an `mmap` of its UIO device, which
        // has no peripheral singleton; controller cores own the real peripheral,
        // so they hand the doorbell its singleton and never name an address.
        let construct = match source {
            DoorbellSource::Uio => quote::quote! {
                /// SAFETY: the base is the UIO-mapped doorbell register window,
                /// resolved from the validated Consortium hardware database.
                let #doorbell_ident = unsafe { #doorbell::new_mapped(#doorbell_base) };
            },
            DoorbellSource::Owned(param) => quote::quote! {
                let #doorbell_ident = #doorbell::new(#param);
            },
            DoorbellSource::Shared(singleton) => {
                let hal: syn::Path =
                    syn::parse_str(hal_crate).expect("hal_crate must be a valid path");
                quote::quote! {
                    /// SAFETY: another transceiver on this core already owns this
                    /// doorbell block; the two address disjoint channels of it, as
                    /// the manifest's duplicate-channel validation guarantees.
                    let #doorbell_ident = #doorbell::new(unsafe {
                        #hal::peripherals::#singleton::steal()
                    });
                }
            }
        };

        quote::quote! {
            #construct
            #binding_uio_stmt
        }
    }
}

impl FromStr for DoorbellMeta {
    type Err = CfgError;

    /// Parses a doorbell peripheral name into a typed initiator.
    ///
    /// The name is an alphabetic peripheral type optionally followed by a
    /// numeric instance id, e.g. `mu7` -> `Mu`/`Some(7)`, `hsem` ->
    /// `Hsem`/`None`, `ipcc1` -> `Ipcc`/`Some(1)`.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let split = s.find(|ch: char| ch.is_ascii_digit()).unwrap_or(s.len());
        let (prefix, suffix) = s.split_at(split);

        let r#type = match prefix {
            "mu" => HardwareDoorbellPeripheralType::Mu,
            "hsem" => HardwareDoorbellPeripheralType::Hsem,
            "ipcc" => HardwareDoorbellPeripheralType::Ipcc,
            _ => return Err(CfgError::Manifest(format!("unknown doorbell type '{s}'"))),
        };

        let id = if suffix.is_empty() {
            None
        } else {
            Some(
                suffix
                    .parse()
                    .map_err(|_| CfgError::Manifest(format!("invalid doorbell id in '{s}'")))?,
            )
        };

        Ok(Self { r#type, id })
    }
}

impl fmt::Display for DoorbellMeta {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.r#type.to_string().to_lowercase())?;
        if let Some(id) = self.id {
            write!(f, "{id}")?;
        }
        Ok(())
    }
}

/// The transport-installer parameter that carries `singleton`.
fn doorbell_param(singleton: &Ident) -> Ident {
    format_ident!("__db_{}", singleton.to_string().to_lowercase())
}

/// SHared Memory Unified, Hardware abstraction node.
#[derive(Debug, Clone)]
pub struct ShuHan {
    transceivers: Vec<Transceiver>,
}

impl ShuHan {
    /// Builds a node from its transceivers.
    pub fn new(transceivers: Vec<Transceiver>) -> Self {
        Self { transceivers }
    }

    /// The transceivers this node generates.
    pub fn transceivers(&self) -> &[Transceiver] {
        &self.transceivers
    }

    /// Where each transceiver's doorbell comes from on `core`, plus the distinct
    /// singletons a controller core's transport installer must be handed.
    ///
    /// Two transceivers may share one doorbell block (disjoint channels of the
    /// same MU or IPCC) and a singleton moves only once, so the first user takes
    /// the parameter and later ones steal it. The AP has no singletons at all —
    /// it reaches its doorbells through UIO `mmap`.
    fn doorbell_sources(
        &self,
        core: VisibleCore,
        available: &[String],
    ) -> (Vec<Ident>, Vec<DoorbellSource>) {
        let mut owned: Vec<Ident> = Vec::new();
        let sources = self
            .transceivers
            .iter()
            .map(|t| {
                if core == VisibleCore::Ap {
                    return DoorbellSource::Uio;
                }
                let side = t
                    .side(core)
                    .expect("core must be either primary or secondary for the transceiver");
                let singleton = t.doorbell.singleton(side);
                // A core with no bundled chip map (or one whose map does not
                // reach this window) has no singleton to hand over, so it keeps
                // the address-based construction it has always used.
                if !available
                    .iter()
                    .any(|name| name.eq_ignore_ascii_case(&singleton.to_string()))
                {
                    return DoorbellSource::Uio;
                }
                if owned.contains(&singleton) {
                    return DoorbellSource::Shared(singleton);
                }
                owned.push(singleton.clone());
                DoorbellSource::Owned(doorbell_param(&singleton))
            })
            .collect();
        (owned, sources)
    }

    /// The distinct doorbell singletons `core` must hand to
    /// the generated transport installer, in parameter order.
    pub fn doorbell_singletons(&self, core: VisibleCore, available: &[String]) -> Vec<Ident> {
        self.doorbell_sources(core, available).0
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::*;
    use crate::components::address::ApAddress;
    use consortium_cfg_common::database::MemoryRegionType;
    use quote::format_ident;

    fn channel(doorbell_chan: u8) -> Channel {
        Channel {
            doorbell_chan,
            type_name: "Ping".to_string(),
            buffer_name: "ping_buf".to_string(),
        }
    }

    fn transceiver(length: u32, mtu: u32) -> Transceiver {
        let cm33 = VisibleCore::Mcore(consortium_cfg_common::config::McoreName::Cm33);
        let address = Address {
            ap: ApAddress {
                uio_id: 0,
                mmap_id: 0,
            },
            cp: HashMap::from([(cm33, 0x3400_0000)]),
        };
        Transceiver {
            name: "ping".to_string(),
            doorbell_address: address.clone(),
            mtu,
            codec: Codec::Postcard,
            region: Region {
                r#type: MemoryRegionType::Sram,
                cache: false,
                address,
                length,
            },
            channel_primary: (VisibleCore::Ap, channel(0)),
            channel_secondary: (cm33, channel(1)),
            doorbell: DoorbellMeta {
                r#type: HardwareDoorbellPeripheralType::Ipcc,
                id: Some(1),
            },
        }
    }

    const SLOT_BASE: u32 = consortium_ipc_transport_memory::slot_offset(0, 4) as u32;
    const SLOT_STRIDE: u32 = consortium_ipc_transport_memory::slot_stride(4) as u32;

    #[test]
    fn max_channels_is_zero_when_only_descriptor_fits() {
        // No room beyond the descriptor: no message slots can be carved out.
        assert_eq!(transceiver(SLOT_BASE, 4).max_channels(), 0);
    }

    #[test]
    fn max_channels_counts_slot_pairs() {
        // Each 16-byte logical slot occupies one 64-byte cache-line stride.
        // Three pairs of room => 6 channels.
        let pair_len = SLOT_STRIDE * 2;
        assert_eq!(transceiver(SLOT_BASE + pair_len * 3, 4).max_channels(), 6);
    }

    #[test]
    fn max_channels_counts_pair_without_trailing_padding() {
        let exact = consortium_ipc_transport_memory::required_region_len(2, 128) as u32;
        assert_eq!(exact, 0x24c);
        assert_eq!(transceiver(exact, 128).max_channels(), 2);
        assert_eq!(transceiver(exact - 1, 128).max_channels(), 0);
    }

    #[test]
    fn max_channels_saturates_at_channel_num_max() {
        let max = consortium_ipc_transport_memory::CHANNEL_NUM_MAX as u32;
        assert_eq!(transceiver(u32::MAX, 4).max_channels(), max);
    }

    #[test]
    fn cached_region_type_is_controller_only() {
        let mut transceiver = transceiver(SLOT_BASE + 4096, 128);
        transceiver.region.cache = true;
        let cm33 = VisibleCore::Mcore(consortium_cfg_common::config::McoreName::Cm33);

        assert!(
            transceiver
                .region_ty(cm33)
                .to_string()
                .contains("CachedRegion")
        );
        assert!(
            transceiver
                .region_ty(VisibleCore::Ap)
                .to_string()
                .contains("UncachedRegion")
        );
    }

    /// Only UIO devices declaring an `irq` are opened with `enable_irq` and run
    /// an `irq_loop`, and that is the doorbell's device — not the shared-memory
    /// region's. Binding the service to the region device registers it on a
    /// handle whose IRQ listener never runs, so the AP parks in `wait` forever
    /// while the controller keeps ringing.
    #[test]
    fn ap_binds_doorbell_service_to_the_doorbell_uio_device() {
        let mut t = transceiver(SLOT_BASE + 4096, 128);
        t.region.address.ap = ApAddress {
            uio_id: 1,
            mmap_id: 0,
        };
        t.doorbell_address.ap = ApAddress {
            uio_id: 2,
            mmap_id: 0,
        };
        // `transceiver` uses IPCC, a masking doorbell, so the AP binds the
        // masking service rather than a plain notifier.
        let uio = format_ident!("uio");
        let init = t
            .build_field_init(
                VisibleCore::Ap,
                &uio,
                DoorbellSource::Uio,
                "::consortium_hal_stm32mp2",
            )
            .to_string();

        assert!(init.contains("uio [2usize] . bind_service"), "{init}");
        assert!(!init.contains("uio [1usize] . bind_service"), "{init}");
        // The region and the doorbell window still map from their own devices.
        assert!(init.contains("uio [1usize] . mmap_zeroed"), "{init}");
        assert!(init.contains("uio [2usize] . mmap"), "{init}");
    }

    /// HSEM is the non-masking doorbell: its `wait` future owns arming and
    /// masking the line, so the AP binds a plain notifier instead of a service.
    #[test]
    fn ap_binds_a_plain_notifier_for_hsem() {
        let mut t = transceiver(SLOT_BASE + 4096, 128);
        t.doorbell_address.ap = ApAddress {
            uio_id: 2,
            mmap_id: 0,
        };
        t.doorbell = DoorbellMeta {
            r#type: HardwareDoorbellPeripheralType::Hsem,
            id: None,
        };

        let uio = format_ident!("uio");
        let init = t
            .build_field_init(
                VisibleCore::Ap,
                &uio,
                DoorbellSource::Uio,
                "::consortium_hal_stm32mp2",
            )
            .to_string();

        assert!(init.contains("uio [2usize] . bind_notifier"), "{init}");
        assert!(!init.contains("bind_service"), "{init}");
    }

    #[test]
    fn doorbell_path_resolves_crate_type_and_side() {
        let doorbell = DoorbellMeta {
            r#type: HardwareDoorbellPeripheralType::Mu,
            id: Some(7),
        };

        let tokens = doorbell.as_path(DoorbellRingerSide::Primary).to_string();
        assert!(tokens.contains(":: consortium_ipc_doorbell_mu :: MuDoorbell"));
        assert!(tokens.contains(":: consortium_ipc :: Primary"));
        assert!(tokens.contains("7usize"));
    }

    #[test]
    fn doorbell_path_defaults_missing_id_to_one() {
        let doorbell = DoorbellMeta {
            r#type: HardwareDoorbellPeripheralType::Hsem,
            id: None,
        };

        let tokens = doorbell.as_path(DoorbellRingerSide::Secondary).to_string();
        assert!(tokens.contains(":: consortium_ipc_doorbell_hsem :: HsemDoorbell"));
        assert!(tokens.contains(":: consortium_ipc :: Secondary"));
        assert!(tokens.contains("1usize"));
    }

    #[test]
    fn display_round_trips_through_from_str() {
        for s in ["mu7", "hsem", "ipcc1", "mu0"] {
            let doorbell: DoorbellMeta = s.parse().unwrap();
            assert_eq!(doorbell.to_string(), s);
        }
    }

    #[test]
    fn rejects_invalid_doorbell_id() {
        assert!("mu999".parse::<DoorbellMeta>().is_err());
    }

    #[test]
    fn parses_typed_doorbell_with_id() {
        assert_eq!(
            "mu7".parse::<DoorbellMeta>().unwrap(),
            DoorbellMeta {
                r#type: HardwareDoorbellPeripheralType::Mu,
                id: Some(7),
            }
        );
        assert_eq!(
            "ipcc1".parse::<DoorbellMeta>().unwrap(),
            DoorbellMeta {
                r#type: HardwareDoorbellPeripheralType::Ipcc,
                id: Some(1),
            }
        );
    }

    #[test]
    fn parses_typed_doorbell_without_id() {
        assert_eq!(
            "hsem".parse::<DoorbellMeta>().unwrap(),
            DoorbellMeta {
                r#type: HardwareDoorbellPeripheralType::Hsem,
                id: None,
            }
        );
    }

    #[test]
    fn rejects_unknown_doorbell_type() {
        assert!("foo3".parse::<DoorbellMeta>().is_err());
    }
}