Skip to main content

fic/ccfg/
ring.rs

1//! Each buffered channel's ring ([`rings`]), sized as filib lays it out:
2//! [`HEADER`], then as many payload-sized slots as fit. A lowering, not a
3//! type, so it is sized here; a region with no slot is an error.
4
5use serde::Serialize;
6
7use crate::base::{ChanId, IdVec, MrId};
8use crate::error::{Diagnostic, Diagnostics};
9use crate::tast::{Ty, TyEnv};
10
11/// filib's `ring::HEADER`.
12pub const HEADER: u64 = 16;
13
14/// filib's `ring::MAX_CAPACITY`, the same for every ring: the indices are
15/// `u32` and run mod 2N, so 2N fits a `u32`. A ring holds at most what fits
16/// in its region, ⌊(size − [`HEADER`]) / sizeof(T)⌋, capped at this.
17pub const MAX_CAPACITY: u64 = (1 << 31) - 1;
18
19/// An `Address` on `AArch64`.
20const ADDRESS_BYTES: u64 = 8;
21
22/// `capacity` slots of `slot_size` bytes after the header.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
24pub struct Ring {
25    /// `N`, at least one.
26    pub capacity: u64,
27    /// The payload's bytes, at least one.
28    pub slot_size: u64,
29}
30
31/// Every channel's ring, `None` if unbuffered, and a warning for each ring
32/// that leaves part of its region unused because what fits is more than
33/// [`MAX_CAPACITY`].
34///
35/// # Errors
36///
37/// A payload with no bytes, a region with no slot, or a declared capacity
38/// of 0 or more than fits, each at its channel.
39pub fn rings(tenv: &TyEnv) -> Result<(IdVec<ChanId, Option<Ring>>, Diagnostics), Diagnostics> {
40    let mut errors = Vec::new();
41    let mut warnings = Vec::new();
42    let rings = tenv
43        .chans
44        .iter()
45        .map(|ch| {
46            let (Some(buffer), Some(payload)) = (&ch.buffer, &ch.payload) else {
47                return None;
48            };
49            let at = |m: String| (format!("channel '{}': {m}", ch.name), ch.span.clone());
50            match ring(tenv, buffer.region, payload, ch.capacity) {
51                Ok((ring, unused)) => {
52                    if let Some(m) = unused {
53                        let (m, span) = at(m);
54                        warnings.push(Diagnostic::warn_at(m, span, tenv.file.clone()));
55                    }
56                    Some(ring)
57                }
58                Err(m) => {
59                    let (m, span) = at(m);
60                    errors.push(Diagnostic::at(m, span, tenv.file.clone()));
61                    None
62                }
63            }
64        })
65        .collect();
66    if errors.is_empty() {
67        Ok((rings, Diagnostics(warnings)))
68    } else {
69        Err(Diagnostics(errors))
70    }
71}
72
73/// The ring, and a warning if it takes [`MAX_CAPACITY`] slots of a region
74/// that fits more.
75fn ring(
76    tenv: &TyEnv,
77    region: MrId,
78    payload: &Ty,
79    declared: Option<u64>,
80) -> Result<(Ring, Option<String>), String> {
81    let name = named(tenv, payload);
82    let slot_size = bytes(tenv, payload);
83    if slot_size == 0 {
84        return Err(format!(
85            "payload '{name}' has no bytes: a ring's slot holds at least one"
86        ));
87    }
88    let region = &tenv.mrs[region];
89    let size = region.size.value();
90    // What fits or MAX_CAPACITY, whichever is smaller: the one limit a
91    // capacity meets.
92    let fits = size.saturating_sub(HEADER) / slot_size;
93    let fit = fits.min(MAX_CAPACITY);
94    let capacity = declared.unwrap_or(fit);
95    if capacity == 0 || capacity > fit {
96        let r = &region.name;
97        let header = format!("after the ring's {HEADER}-byte header");
98        return Err(if fit == 0 {
99            format!("region '{r}' ({size:#x} bytes) holds no slot of '{name}' ({slot_size} bytes) {header}")
100        } else {
101            format!("capacity {capacity}: region '{r}' ({size:#x} bytes) holds 1 to {fit} slots of '{name}' ({slot_size} bytes) {header}")
102        });
103    }
104    let unused = (declared.is_none() && fits > MAX_CAPACITY).then(|| {
105        format!(
106            "region '{}' fits {fits} slots of '{name}', but a ring's u32 indices reach {MAX_CAPACITY}: it takes {MAX_CAPACITY}, and {:#x} bytes of the region are unused",
107            region.name,
108            size - HEADER - MAX_CAPACITY * slot_size
109        )
110    });
111    Ok((
112        Ring {
113            capacity,
114            slot_size,
115        },
116        unused,
117    ))
118}
119
120/// A type as the source writes it.
121pub(super) fn named(tenv: &TyEnv, ty: &Ty) -> String {
122    match ty {
123        Ty::Prim(p) => p.to_string(),
124        Ty::Addr(_) => "Address".to_owned(),
125        Ty::Struct(id) => tenv.structs[*id].name.clone(),
126        Ty::Array { elem, len } => format!("{}[{}]", named(tenv, elem), len.len),
127    }
128}
129
130/// A value's bytes, as the C backend lays it out.
131pub fn bytes(tenv: &TyEnv, ty: &Ty) -> u64 {
132    match ty {
133        Ty::Prim(p) => p.size_bytes().map_or(0, |n| n as u64),
134        Ty::Addr(_) => ADDRESS_BYTES,
135        Ty::Struct(id) => tenv.structs[*id].size,
136        Ty::Array { elem, len } => len.len * bytes(tenv, elem),
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143    use crate::base::Idx;
144    use crate::tast::env::built;
145
146    fn ring_of(fis: &str) -> Ring {
147        let tenv = built(fis, &[]).expect("builds").0.tenv;
148        rings(&tenv).expect("sized").0[ChanId::new(0)].expect("buffered")
149    }
150
151    fn rejected(fis: &str) -> String {
152        let tenv = built(fis, &[]).expect("builds").0.tenv;
153        rings(&tenv).expect_err("rejected").to_string()
154    }
155
156    fn system(region: &str, payload: &str) -> String {
157        format!(
158            "struct Slot {{ flags: uint16; seq: uint16; length: uint16; kind: uint16; offset: uint32; }}
159             struct Empty {{ }}
160             MemoryRegion ring({region});
161             ProtectionDomain a(10);
162             ProtectionDomain b(20);
163             Chan c = a --> b via ring<{payload}>;"
164        )
165    }
166
167    #[test]
168    fn the_header_and_the_cap_are_filibs() {
169        assert_eq!(HEADER, filib::ring::HEADER as u64);
170        assert_eq!(MAX_CAPACITY, u64::from(filib::ring::MAX_CAPACITY));
171    }
172
173    #[test]
174    fn a_ring_holds_every_slot_that_fits_after_the_header() {
175        assert_eq!(
176            ring_of(&system("0x200000, 0x200000", "Slot")),
177            Ring {
178                capacity: (0x20_0000 - 16) / 12,
179                slot_size: 12
180            }
181        );
182        assert_eq!(
183            ring_of(&system("0x1000", "uint64")),
184            Ring {
185                capacity: 510,
186                slot_size: 8
187            }
188        );
189    }
190
191    #[test]
192    fn int_and_address_are_sized_as_typed() {
193        for payload in ["int", "Address"] {
194            assert_eq!(
195                ring_of(&system("0x1000", payload)),
196                Ring {
197                    capacity: 510,
198                    slot_size: 8
199                },
200                "{payload}"
201            );
202        }
203    }
204
205    #[test]
206    fn a_declared_capacity_is_the_ring_s() {
207        assert_eq!(
208            ring_of(&system("0x1000", "uint64, 100")),
209            Ring {
210                capacity: 100,
211                slot_size: 8
212            }
213        );
214        let fis = "const N: int = 7;
215             MemoryRegion ring(0x1000);
216             ProtectionDomain a(10);
217             ProtectionDomain b(20);
218             Chan c = a --> b via ring<uint64, N>;";
219        assert_eq!(ring_of(fis).capacity, 7);
220        // Exactly what fits.
221        assert_eq!(ring_of(&system("0x1000", "uint64, 510")).capacity, 510);
222    }
223
224    #[test]
225    fn a_declared_capacity_must_fit_and_hold_one() {
226        for n in [511, 0] {
227            let e = rejected(&system("0x1000", &format!("uint64, {n}")));
228            assert!(
229                e.contains(&format!("channel 'c': capacity {n}: region 'ring' (0x1000 bytes) holds 1 to 510 slots of 'uint64' (8 bytes) after the ring's 16-byte header")),
230                "{e}"
231            );
232        }
233    }
234
235    #[test]
236    fn a_payload_without_bytes_has_no_ring() {
237        let e = rejected(&system("0x1000", "Empty"));
238        assert!(
239            e.contains("channel 'c': payload 'Empty' has no bytes"),
240            "{e}"
241        );
242    }
243
244    #[test]
245    fn a_region_too_small_for_one_slot_is_reported_at_the_channel() {
246        let fis = "struct Big { bytes: uint8[4096]; }
247             MemoryRegion ring(0x1000);
248             ProtectionDomain a(10);
249             ProtectionDomain b(20);
250             Chan c = a --> b via ring<Big>;";
251        let e = rejected(fis);
252        assert!(
253            e.contains("channel 'c': region 'ring' (0x1000 bytes) holds no slot of 'Big' (4096 bytes) after the ring's 16-byte header"),
254            "{e}"
255        );
256    }
257
258    #[test]
259    fn a_ring_holds_at_most_the_cap_whatever_fits() {
260        let huge = "0x100000000, 0x200000";
261        assert_eq!(ring_of(&system(huge, "byte")).capacity, MAX_CAPACITY);
262        let tenv = built(&system(huge, "byte"), &[]).expect("builds").0.tenv;
263        let warned = rings(&tenv).expect("sized").1.to_string();
264        assert!(
265            warned.contains("region 'ring' fits 4294967280 slots of 'uint8', but a ring's u32 indices reach 2147483647: it takes 2147483647, and 0x7ffffff1 bytes of the region are unused"),
266            "{warned}"
267        );
268        // A declared capacity is the developer's choice: no warning.
269        let declared = built(&system(huge, "byte, 100"), &[])
270            .expect("builds")
271            .0
272            .tenv;
273        assert!(rings(&declared).expect("sized").1.is_empty());
274        let e = rejected(&system(huge, &format!("byte, {}", MAX_CAPACITY + 1)));
275        assert!(e.contains("holds 1 to 2147483647 slots of 'uint8'"), "{e}");
276    }
277}