Skip to main content

strat9_kernel/s9vm/
bootinfo.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! s9vm : guest boot information page.
24//!
25//! A world starts with a guest that must be told what its machine looks like:
26//! which memory ranges are usable, which virtual devices exist, where their
27//! MMIO pages are and which interrupt lines they use. Firmware (ACPI) is the
28//! long-term answer for a full operating system; this page is the direct,
29//! minimal interface for s9vm's own guests and for early bring-up.
30//!
31//! The layout is a fixed 512-byte little-endian structure with a magic, a
32//! version, bounds-checked counts and a fixed number of slots, so it can be
33//! parsed by a guest without allocating and cannot describe itself outside
34//! the page. Encoding and decoding live here as pure code and are host-tested;
35//! the kernel only computes the contents and copies them into guest memory.
36
37/// Magic value: the ASCII bytes `S9VMBOOT` read as a little-endian `u64`.
38pub const MAGIC: u64 = 0x544F_4F42_4D56_3953;
39/// Layout version.
40pub const VERSION: u32 = 1;
41/// Total size of the page.
42pub const SIZE: usize = 512;
43/// Maximum number of memory ranges described.
44pub const MAX_MEMORY_ENTRIES: usize = 16;
45/// Maximum number of devices described.
46pub const MAX_DEVICE_ENTRIES: usize = 4;
47
48/// Kind of a memory range.
49pub mod memory_kind {
50    /// Usable guest RAM.
51    pub const RAM: u32 = 1;
52    /// Reserved (firmware, holes).
53    pub const RESERVED: u32 = 2;
54    /// Device MMIO window.
55    pub const MMIO: u32 = 3;
56}
57
58/// Kind of a device.
59pub mod device_kind {
60    /// Console (virtio-mmio transport).
61    pub const CONSOLE: u32 = 1;
62    /// Block device (virtio-mmio transport).
63    pub const BLOCK: u32 = 2;
64    /// Network device (virtio-mmio transport).
65    pub const NETWORK: u32 = 3;
66}
67
68/// Flags.
69pub mod flags {
70    /// The page is complete and the guest may boot.
71    pub const COMPLETE: u32 = 1;
72    /// A console device is present.
73    pub const HAS_CONSOLE: u32 = 2;
74    /// A block device is present.
75    pub const HAS_BLOCK: u32 = 4;
76    /// A network device is present.
77    pub const HAS_NETWORK: u32 = 8;
78}
79
80/// One memory range.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub struct MemoryEntry {
83    /// Guest-physical base address.
84    pub base: u64,
85    /// Length in bytes.
86    pub len: u64,
87    /// [`memory_kind`] value.
88    pub kind: u32,
89}
90
91/// One device.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub struct DeviceEntry {
94    /// [`device_kind`] value.
95    pub kind: u32,
96    /// Interrupt line in the I/O APIC.
97    pub irq_line: u32,
98    /// Guest-physical address of the MMIO transport page.
99    pub mmio_base: u64,
100    /// Device-specific value: block capacity in sectors, MAC for network.
101    pub config: u64,
102}
103
104/// Decoding error.
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub enum BootInfoError {
107    /// The magic value does not match.
108    BadMagic,
109    /// The layout version is not supported.
110    BadVersion,
111    /// The structure size field does not match [`SIZE`].
112    BadSize,
113    /// A count exceeds its slot array.
114    TooManyEntries,
115    /// The input slice is smaller than [`SIZE`].
116    Truncated,
117}
118
119/// Boot information page.
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub struct BootInfo {
122    /// [`flags`] bits.
123    pub flags: u32,
124    /// Memory ranges.
125    pub memory: [MemoryEntry; MAX_MEMORY_ENTRIES],
126    /// Number of valid memory ranges.
127    pub memory_count: u8,
128    /// Devices.
129    pub devices: [DeviceEntry; MAX_DEVICE_ENTRIES],
130    /// Number of valid devices.
131    pub device_count: u8,
132}
133
134impl BootInfo {
135    /// Empty page.
136    pub const fn new() -> Self {
137        Self {
138            flags: 0,
139            memory: [MemoryEntry {
140                base: 0,
141                len: 0,
142                kind: 0,
143            }; MAX_MEMORY_ENTRIES],
144            memory_count: 0,
145            devices: [DeviceEntry {
146                kind: 0,
147                irq_line: 0,
148                mmio_base: 0,
149                config: 0,
150            }; MAX_DEVICE_ENTRIES],
151            device_count: 0,
152        }
153    }
154
155    /// Adds a memory range. Returns false when the slot array is full.
156    pub fn add_memory(&mut self, base: u64, len: u64, kind: u32) -> bool {
157        let index = self.memory_count as usize;
158        if index >= MAX_MEMORY_ENTRIES {
159            return false;
160        }
161        self.memory[index] = MemoryEntry { base, len, kind };
162        self.memory_count += 1;
163        true
164    }
165
166    /// Adds a device. Returns false when the slot array is full.
167    pub fn add_device(&mut self, kind: u32, irq_line: u32, mmio_base: u64, config: u64) -> bool {
168        let index = self.device_count as usize;
169        if index >= MAX_DEVICE_ENTRIES {
170            return false;
171        }
172        self.devices[index] = DeviceEntry {
173            kind,
174            irq_line,
175            mmio_base,
176            config,
177        };
178        self.device_count += 1;
179        true
180    }
181
182    /// Encodes the page into `out`.
183    pub fn encode(&self, out: &mut [u8; SIZE]) {
184        out.fill(0);
185        put_u64(out, 0x000, MAGIC);
186        put_u32(out, 0x008, VERSION);
187        put_u32(out, 0x00C, SIZE as u32);
188        put_u32(out, 0x010, self.flags);
189        put_u32(out, 0x014, u32::from(self.memory_count));
190        put_u32(out, 0x018, u32::from(self.device_count));
191        let memory_base = 0x020;
192        for (index, entry) in self.memory[..usize::from(self.memory_count)]
193            .iter()
194            .enumerate()
195        {
196            let offset = memory_base + index * 24;
197            put_u64(out, offset, entry.base);
198            put_u64(out, offset + 8, entry.len);
199            put_u32(out, offset + 16, entry.kind);
200        }
201        let device_base = memory_base + MAX_MEMORY_ENTRIES * 24;
202        for (index, entry) in self.devices[..usize::from(self.device_count)]
203            .iter()
204            .enumerate()
205        {
206            let offset = device_base + index * 24;
207            put_u32(out, offset, entry.kind);
208            put_u32(out, offset + 4, entry.irq_line);
209            put_u64(out, offset + 8, entry.mmio_base);
210            put_u64(out, offset + 16, entry.config);
211        }
212    }
213
214    /// Decodes a page.
215    pub fn decode(bytes: &[u8]) -> Result<Self, BootInfoError> {
216        if bytes.len() < SIZE {
217            return Err(BootInfoError::Truncated);
218        }
219        if get_u64(bytes, 0x000) != MAGIC {
220            return Err(BootInfoError::BadMagic);
221        }
222        if get_u32(bytes, 0x008) != VERSION {
223            return Err(BootInfoError::BadVersion);
224        }
225        if get_u32(bytes, 0x00C) as usize != SIZE {
226            return Err(BootInfoError::BadSize);
227        }
228        let mut info = Self::new();
229        info.flags = get_u32(bytes, 0x010);
230        let memory_count = get_u32(bytes, 0x014) as usize;
231        let device_count = get_u32(bytes, 0x018) as usize;
232        if memory_count > MAX_MEMORY_ENTRIES || device_count > MAX_DEVICE_ENTRIES {
233            return Err(BootInfoError::TooManyEntries);
234        }
235        let memory_base = 0x020;
236        for index in 0..memory_count {
237            let offset = memory_base + index * 24;
238            info.memory[index] = MemoryEntry {
239                base: get_u64(bytes, offset),
240                len: get_u64(bytes, offset + 8),
241                kind: get_u32(bytes, offset + 16),
242            };
243        }
244        info.memory_count = memory_count as u8;
245        let device_base = memory_base + MAX_MEMORY_ENTRIES * 24;
246        for index in 0..device_count {
247            let offset = device_base + index * 24;
248            info.devices[index] = DeviceEntry {
249                kind: get_u32(bytes, offset),
250                irq_line: get_u32(bytes, offset + 4),
251                mmio_base: get_u64(bytes, offset + 8),
252                config: get_u64(bytes, offset + 16),
253            };
254        }
255        info.device_count = device_count as u8;
256        Ok(info)
257    }
258}
259
260impl Default for BootInfo {
261    fn default() -> Self {
262        Self::new()
263    }
264}
265
266/// Writes a little-endian `u32` at `offset`.
267fn put_u32(out: &mut [u8; SIZE], offset: usize, value: u32) {
268    out[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
269}
270
271/// Writes a little-endian `u64` at `offset`.
272fn put_u64(out: &mut [u8; SIZE], offset: usize, value: u64) {
273    out[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
274}
275
276/// Reads a little-endian `u32` at `offset`.
277fn get_u32(bytes: &[u8], offset: usize) -> u32 {
278    u32::from_le_bytes([
279        bytes[offset],
280        bytes[offset + 1],
281        bytes[offset + 2],
282        bytes[offset + 3],
283    ])
284}
285
286/// Reads a little-endian `u64` at `offset`.
287fn get_u64(bytes: &[u8], offset: usize) -> u64 {
288    u64::from_le_bytes([
289        bytes[offset],
290        bytes[offset + 1],
291        bytes[offset + 2],
292        bytes[offset + 3],
293        bytes[offset + 4],
294        bytes[offset + 5],
295        bytes[offset + 6],
296        bytes[offset + 7],
297    ])
298}