arm_vgic 0.6.1

ARM Virtual Generic Interrupt Controller (VGIC) implementation.
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
//! Validated per-VM GICv3 configuration.

use alloc::vec::Vec;

use axdevice_base::ItsId;

use crate::{LPI_INTID_BASE, LPI_INTID_MAX, VgicError, VgicResult};

/// Policy describing which SPIs are visible through the guest Distributor.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum GicV3SpiOwnership {
    /// Every implemented SPI belongs to a fully virtual machine.
    AllGuestOwned,
    /// An SPI is RAZ/WI until an endpoint explicitly claims it for the VM.
    Explicit,
}

/// Validated capabilities reported by a physical GICv3 Distributor.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct GicV3HardwareCapabilities {
    spi_count: usize,
    affinity_level_3: bool,
    range_selector: bool,
}

impl GicV3HardwareCapabilities {
    /// Decodes the implemented SPI range from `GICD_TYPER.ITLinesNumber`.
    pub fn from_distributor_typer(typer: u32) -> VgicResult<Self> {
        let implemented_intids = ((typer & 0x1f) as usize + 1) * 32;
        let spi_count = implemented_intids
            .min(1020)
            .checked_sub(32)
            .filter(|count| *count != 0)
            .ok_or_else(|| VgicError::InvalidConfig {
                detail: alloc::format!("GICD_TYPER {typer:#x} exposes no SPIs"),
            })?;
        Ok(Self {
            spi_count,
            affinity_level_3: typer & (1 << 24) != 0,
            range_selector: typer & (1 << 26) != 0,
        })
    }

    /// Returns the number of implemented SPIs.
    pub const fn spi_count(self) -> usize {
        self.spi_count
    }

    /// Returns whether affinity level 3 is implemented for SPI routing.
    pub const fn affinity_level_3(self) -> bool {
        self.affinity_level_3
    }

    /// Returns whether SGI range selection is implemented.
    pub const fn range_selector(self) -> bool {
        self.range_selector
    }
}

/// One guest-visible MMIO register frame.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct GicV3MmioRegion {
    base: u64,
    size: u64,
}

impl GicV3MmioRegion {
    /// Creates a non-empty, non-wrapping register frame.
    pub fn new(base: u64, size: u64) -> VgicResult<Self> {
        if size == 0 {
            return Err(VgicError::InvalidConfig {
                detail: "GICv3 MMIO region must not be empty".into(),
            });
        }
        if base.checked_add(size).is_none() {
            return Err(VgicError::InvalidConfig {
                detail: alloc::format!(
                    "GICv3 MMIO region [{base:#x}, +{size:#x}) wraps the address space"
                ),
            });
        }
        Ok(Self { base, size })
    }

    /// Returns the guest physical base address.
    pub const fn base(self) -> u64 {
        self.base
    }

    /// Returns the frame size in bytes.
    pub const fn size(self) -> u64 {
        self.size
    }

    /// Returns whether the region contains an entire access.
    pub fn contains(self, address: u64, length: usize) -> bool {
        address >= self.base
            && address
                .checked_add(length as u64)
                .is_some_and(|end| end <= self.base + self.size)
    }
}

/// Complete configuration for one VM-local GICv3 controller.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GicV3Config {
    spi_ownership: GicV3SpiOwnership,
    distributor: GicV3MmioRegion,
    redistributors: Vec<GicV3MmioRegion>,
    redistributor_stride: u64,
    vcpu_count: usize,
    its: Vec<(ItsId, GicV3MmioRegion)>,
    spi_count: usize,
    affinity_level_3: bool,
    range_selector: bool,
    lpi_limit: u32,
    list_register_count: usize,
    its_command_budget: usize,
}

impl GicV3Config {
    /// Creates a GICv3 configuration with architectural defaults.
    pub fn new(
        spi_ownership: GicV3SpiOwnership,
        distributor: GicV3MmioRegion,
        redistributors: GicV3MmioRegion,
        redistributor_stride: u64,
        vcpu_count: usize,
    ) -> VgicResult<Self> {
        Self::new_with_redistributor_regions(
            spi_ownership,
            distributor,
            alloc::vec![redistributors],
            redistributor_stride,
            vcpu_count,
        )
    }

    /// Creates a GICv3 configuration backed by one or more Redistributor
    /// regions.
    pub fn new_with_redistributor_regions(
        spi_ownership: GicV3SpiOwnership,
        distributor: GicV3MmioRegion,
        redistributors: Vec<GicV3MmioRegion>,
        redistributor_stride: u64,
        vcpu_count: usize,
    ) -> VgicResult<Self> {
        let config = Self {
            spi_ownership,
            distributor,
            redistributors,
            redistributor_stride,
            vcpu_count,
            its: Vec::new(),
            spi_count: 988,
            affinity_level_3: true,
            range_selector: true,
            lpi_limit: LPI_INTID_MAX,
            list_register_count: 16,
            its_command_budget: 256,
        };
        config.validate()?;
        Ok(config)
    }

    /// Adds a guest-visible ITS frame.
    pub fn with_its(mut self, its: GicV3MmioRegion) -> VgicResult<Self> {
        self.its = alloc::vec![(ItsId::new(0), its)];
        self.validate()?;
        Ok(self)
    }

    /// Adds all VM-local ITS instances.
    pub fn with_its_instances(mut self, its: Vec<(ItsId, GicV3MmioRegion)>) -> VgicResult<Self> {
        self.its = its;
        self.validate()?;
        Ok(self)
    }

    /// Sets the implemented SPI count.
    pub fn with_spi_count(mut self, spi_count: usize) -> VgicResult<Self> {
        self.spi_count = spi_count;
        self.validate()?;
        Ok(self)
    }

    /// Applies guest-visible capabilities obtained from an assigned physical GIC.
    pub fn with_hardware_capabilities(
        mut self,
        capabilities: GicV3HardwareCapabilities,
    ) -> VgicResult<Self> {
        self.spi_count = capabilities.spi_count();
        self.affinity_level_3 = capabilities.affinity_level_3();
        self.range_selector = capabilities.range_selector();
        self.validate()?;
        Ok(self)
    }

    /// Sets the highest implemented LPI INTID.
    pub fn with_lpi_limit(mut self, lpi_limit: u32) -> VgicResult<Self> {
        self.lpi_limit = lpi_limit;
        self.validate()?;
        Ok(self)
    }

    /// Sets the physical list-register count exposed by the backend.
    pub fn with_list_register_count(mut self, count: usize) -> VgicResult<Self> {
        self.list_register_count = count;
        self.validate()?;
        Ok(self)
    }

    /// Sets the maximum ITS commands processed by one CWRITER update.
    pub fn with_its_command_budget(mut self, budget: usize) -> VgicResult<Self> {
        self.its_command_budget = budget;
        self.validate()?;
        Ok(self)
    }

    /// Returns the guest-visible SPI ownership policy.
    pub const fn spi_ownership(&self) -> GicV3SpiOwnership {
        self.spi_ownership
    }

    /// Returns the Distributor frame.
    pub const fn distributor(&self) -> GicV3MmioRegion {
        self.distributor
    }

    /// Returns every Redistributor frame region.
    pub fn redistributors(&self) -> &[GicV3MmioRegion] {
        &self.redistributors
    }

    /// Returns the distance between Redistributor frames.
    pub const fn redistributor_stride(&self) -> u64 {
        self.redistributor_stride
    }

    /// Returns the configured vCPU count.
    pub const fn vcpu_count(&self) -> usize {
        self.vcpu_count
    }

    /// Returns the optional ITS frame.
    pub fn its(&self) -> Option<GicV3MmioRegion> {
        self.its.first().map(|(_, region)| *region)
    }

    /// Returns every VM-local ITS instance.
    pub fn its_instances(&self) -> &[(ItsId, GicV3MmioRegion)] {
        &self.its
    }

    /// Returns the implemented SPI count.
    pub const fn spi_count(&self) -> usize {
        self.spi_count
    }

    /// Returns whether affinity level 3 is exposed to the guest.
    pub const fn affinity_level_3(&self) -> bool {
        self.affinity_level_3
    }

    /// Returns whether SGI range selection is exposed to the guest.
    pub const fn range_selector(&self) -> bool {
        self.range_selector
    }

    /// Returns the exclusive upper bound of implemented SPI INTIDs.
    pub const fn spi_limit(&self) -> u32 {
        32 + self.spi_count as u32
    }

    /// Returns the highest implemented LPI.
    pub const fn lpi_limit(&self) -> u32 {
        self.lpi_limit
    }

    /// Returns the list-register count.
    pub const fn list_register_count(&self) -> usize {
        self.list_register_count
    }

    /// Returns the ITS submission budget.
    pub const fn its_command_budget(&self) -> usize {
        self.its_command_budget
    }

    fn validate(&self) -> VgicResult {
        const GICD_MIN_SIZE: u64 = 0x1_0000;
        const GIC_FRAME_ALIGNMENT: u64 = 0x1_0000;
        const GICR_MIN_STRIDE: u64 = 0x2_0000;

        validate_frame_alignment("Distributor", self.distributor, GIC_FRAME_ALIGNMENT)?;
        if self.distributor.size() < GICD_MIN_SIZE {
            return Err(VgicError::InvalidConfig {
                detail: alloc::format!(
                    "Distributor frame must be at least {GICD_MIN_SIZE:#x} bytes"
                ),
            });
        }
        if self.vcpu_count == 0 {
            return Err(VgicError::InvalidConfig {
                detail: "GICv3 requires at least one vCPU".into(),
            });
        }
        if self.vcpu_count > u16::MAX as usize + 1 {
            return Err(VgicError::InvalidConfig {
                detail: alloc::format!(
                    "GICv3 vCPU count {} exceeds the 16-bit Processor_Number namespace",
                    self.vcpu_count
                ),
            });
        }
        if self.redistributor_stride < GICR_MIN_STRIDE
            || !self.redistributor_stride.is_multiple_of(0x1_0000)
        {
            return Err(VgicError::InvalidConfig {
                detail: alloc::format!(
                    "Redistributor stride {:#x} must be a 64-KiB-aligned value of at least \
                     {GICR_MIN_STRIDE:#x}",
                    self.redistributor_stride
                ),
            });
        }
        if self.redistributors.is_empty() {
            return Err(VgicError::InvalidConfig {
                detail: "GICv3 requires at least one Redistributor region".into(),
            });
        }
        let mut redistributor_frames = 0usize;
        for (index, redistributor) in self.redistributors.iter().copied().enumerate() {
            validate_frame_alignment("Redistributor", redistributor, GIC_FRAME_ALIGNMENT)?;
            if !redistributor
                .size()
                .is_multiple_of(self.redistributor_stride)
            {
                return Err(VgicError::InvalidConfig {
                    detail: alloc::format!(
                        "Redistributor region {index} size {:#x} is not a multiple of stride {:#x}",
                        redistributor.size(),
                        self.redistributor_stride
                    ),
                });
            }
            if regions_overlap(self.distributor, redistributor) {
                return Err(VgicError::InvalidConfig {
                    detail: alloc::format!("Distributor and Redistributor region {index} overlap"),
                });
            }
            if self.redistributors[..index]
                .iter()
                .any(|existing| regions_overlap(*existing, redistributor))
            {
                return Err(VgicError::InvalidConfig {
                    detail: alloc::format!(
                        "Redistributor region {index} overlaps another Redistributor region"
                    ),
                });
            }
            redistributor_frames = redistributor_frames
                .checked_add((redistributor.size() / self.redistributor_stride) as usize)
                .ok_or_else(|| VgicError::InvalidConfig {
                    detail: "Redistributor frame count overflows".into(),
                })?;
        }
        if redistributor_frames < self.vcpu_count {
            return Err(VgicError::InvalidConfig {
                detail: alloc::format!(
                    "{redistributor_frames} Redistributor frames are available for {} vCPUs",
                    self.vcpu_count
                ),
            });
        }
        for (index, (id, its)) in self.its.iter().copied().enumerate() {
            if self.its[..index]
                .iter()
                .any(|(existing, _)| *existing == id)
            {
                return Err(VgicError::InvalidConfig {
                    detail: alloc::format!("ITS ID {id:?} is duplicated"),
                });
            }
            validate_frame_alignment("ITS", its, GIC_FRAME_ALIGNMENT)?;
            if its.size() < GICD_MIN_SIZE {
                return Err(VgicError::InvalidConfig {
                    detail: alloc::format!("ITS frame must be at least {GICD_MIN_SIZE:#x} bytes"),
                });
            }
            if regions_overlap(its, self.distributor)
                || self
                    .redistributors
                    .iter()
                    .any(|redistributor| regions_overlap(its, *redistributor))
            {
                return Err(VgicError::InvalidConfig {
                    detail: "ITS MMIO region overlaps another GICv3 frame".into(),
                });
            }
            if self.its[..index]
                .iter()
                .any(|(_, existing)| regions_overlap(*existing, its))
            {
                return Err(VgicError::InvalidConfig {
                    detail: alloc::format!("ITS {id:?} MMIO region overlaps another ITS"),
                });
            }
        }
        if self.spi_count == 0
            || self.spi_count > 988
            || (self.spi_count != 988 && !(self.spi_count + 32).is_multiple_of(32))
        {
            return Err(VgicError::InvalidConfig {
                detail: alloc::format!(
                    "SPI count {} must be a non-zero multiple of 32, or the architectural maximum \
                     988",
                    self.spi_count
                ),
            });
        }
        if !(LPI_INTID_BASE..=LPI_INTID_MAX).contains(&self.lpi_limit) {
            return Err(VgicError::InvalidConfig {
                detail: alloc::format!("invalid LPI limit {}", self.lpi_limit),
            });
        }
        if !(1..=16).contains(&self.list_register_count) {
            return Err(VgicError::InvalidConfig {
                detail: alloc::format!(
                    "list-register count {} must be in 1..=16",
                    self.list_register_count
                ),
            });
        }
        if self.its_command_budget == 0 {
            return Err(VgicError::InvalidConfig {
                detail: "ITS command budget must be non-zero".into(),
            });
        }
        Ok(())
    }
}

fn validate_frame_alignment(
    name: &'static str,
    region: GicV3MmioRegion,
    alignment: u64,
) -> VgicResult {
    if region.base().is_multiple_of(alignment) && region.size().is_multiple_of(alignment) {
        Ok(())
    } else {
        Err(VgicError::InvalidConfig {
            detail: alloc::format!(
                "{name} MMIO base {:#x} and size {:#x} must be {alignment:#x}-byte aligned",
                region.base(),
                region.size()
            ),
        })
    }
}

fn regions_overlap(left: GicV3MmioRegion, right: GicV3MmioRegion) -> bool {
    left.base() < right.base() + right.size() && right.base() < left.base() + left.size()
}