Skip to main content

strat9_kernel/s9vm/
firmware.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 : generic guest-firmware images (SeaBIOS and other BIOS ROMs).
24//!
25//! A world can boot either the s9vm stub firmware built by [`biosrom`] or a
26//! **real firmware image** supplied by the caller. This module owns the second
27//! path and makes it reusable: it validates a flat BIOS image and its optional
28//! VGA option ROM, places them at the PC-compatible addresses, and returns the
29//! reset state the vCPU must start from.
30//!
31//! # Image kinds
32//!
33//! | Kind | Layout | Validation |
34//! |---|---|---|
35//! | BIOS | flat image ending at `0x10_0000` | power-of-two size, reset vector at `size - 16` |
36//! | option ROM | starts at `0xC_0000` | `0x55AA` signature, size code, checksum zero |
37//!
38//! A **BIOS image** is not an option ROM: QEMU-style BIOSes such as SeaBIOS
39//! carry no `0x55AA` trailer. The classic x86 reset vector is the far jump at
40//! `0xF000:0xFFF0` (linear `0xFFFF0`), which is the 16 bytes at the end of the
41//! image; [`validate_bios`] checks that jump and [`FirmwareLayout`] exposes the
42//! linear address the vCPU must start at.
43//!
44//! # Example
45//!
46//! ```ignore
47//! let layout = firmware::install_seabios(&mut memory, firmware::FirmwareConfig::freedos())?;
48//! let guest = layout.reset_state();
49//! ```
50//!
51//! The caller maps the memory windows first: the BIOS at
52//! `layout.bios_base..0x10_0000`, the option ROM at
53//! `layout.option_rom_base..+option_rom_len`, and the low RAM the firmware
54//! sizes from CMOS. Nothing in this module touches the world: it only writes
55//! through [`RomMemory`].
56
57use alloc::{vec, vec::Vec};
58
59use super::biosrom::{RomMemory, SECTOR_SIZE};
60
61/// Top of the 1 MiB legacy address space; the BIOS image ends here.
62pub const BIOS_TOP: u32 = 0x10_0000;
63/// Conventional base of the option-ROM scan window.
64pub const OPTION_ROM_BASE: u32 = 0xC_0000;
65/// End of the option-ROM scan window (the BIOS window starts here).
66pub const OPTION_ROM_END: u32 = 0xF_0000;
67/// Smallest accepted BIOS image (32 KiB).
68pub const MIN_BIOS_LEN: usize = 0x8000;
69/// Largest accepted BIOS image (256 KiB).
70pub const MAX_BIOS_LEN: usize = 0x4_0000;
71/// Number of bytes at the end of a BIOS image holding the reset vector.
72pub const RESET_VECTOR_LEN: usize = 16;
73/// Real-mode segment of the reset vector.
74pub const RESET_SEGMENT: u16 = 0xF000;
75/// Instruction pointer of the reset vector inside [`RESET_SEGMENT`].
76pub const RESET_IP: u16 = 0xFFF0;
77/// Linear address of the reset vector (`0xF000:0xFFF0`).
78pub const RESET_LINEAR: u32 = 0xFFFF0;
79/// Option-ROM signature.
80pub const OPTION_ROM_SIGNATURE: [u8; 2] = [0x55, 0xAA];
81/// Offset of the option-ROM size code, in 512-byte units.
82pub const OPTION_ROM_SIZE_OFFSET: usize = 2;
83/// Offset of the option-ROM initialisation entry point.
84pub const OPTION_ROM_ENTRY_OFFSET: usize = 3;
85/// CMOS register holding the floppy drive types (high nibble = drive A).
86pub const CMOS_FLOPPY_TYPE: u8 = 0x10;
87/// CMOS register holding the low byte of the extended-memory size.
88pub const CMOS_EXTMEM_LOW: u8 = 0x30;
89/// CMOS register holding the high byte of the extended-memory size.
90pub const CMOS_EXTMEM_HIGH: u8 = 0x31;
91/// CMOS register holding the high nibble of the QEMU/SeaBIOS boot order.
92pub const CMOS_BOOTFLAG1: u8 = 0x38;
93/// CMOS register holding the low byte of the QEMU/SeaBIOS boot order.
94pub const CMOS_BOOTFLAG2: u8 = 0x3D;
95/// Boot-order value selecting the floppy first (`1` in the first nibble).
96pub const BOOT_ORDER_FLOPPY_FIRST: u8 = 0x01;
97/// CMOS value advertising one 1.44 MiB drive as drive A (`4 << 4`).
98pub const FLOPPY_TYPE_1_44M: u8 = 0x40;
99
100/// SeaBIOS 1.17.0 flat BIOS image (`bios.bin`, 256 KiB).
101///
102/// Provenance, checksums and licence are documented in
103/// `workspace/assets/firmware/README.md`.
104pub fn seabios_image() -> &'static [u8] {
105    include_bytes!("../../../assets/firmware/seabios-1.17.0.bin")
106}
107
108/// SeaVGABIOS standard-VGA option ROM shipped with SeaBIOS 1.17.0.
109pub fn seabios_vga_rom() -> &'static [u8] {
110    include_bytes!("../../../assets/firmware/seabios-vgabios-stdvga-1.17.0.bin")
111}
112
113/// Why a firmware image was rejected.
114#[derive(Debug, Clone, Copy, PartialEq, Eq)]
115pub enum FirmwareError {
116    /// The image is empty or smaller than [`MIN_BIOS_LEN`].
117    TooSmall,
118    /// The image is larger than [`MAX_BIOS_LEN`].
119    TooLarge,
120    /// The BIOS size is not a power of two.
121    NotPowerOfTwo,
122    /// The last 16 bytes are not a `FAR JMP 0xF000:xxxx` reset vector.
123    BadResetVector,
124    /// The option ROM does not start with `0x55AA`.
125    BadOptionRomSignature,
126    /// The option ROM size code does not fit the image.
127    BadOptionRomSize,
128    /// The option ROM checksum is not zero (modulo 256).
129    BadOptionRomChecksum,
130    /// The BIOS image and the option ROM would occupy the same addresses.
131    OverlappingImages,
132    /// The target memory refused a write.
133    WriteFailed,
134}
135
136impl FirmwareError {
137    /// Human-readable reason, used in the kernel diagnostics.
138    pub const fn as_str(self) -> &'static str {
139        match self {
140            Self::TooSmall => "firmware image too small",
141            Self::TooLarge => "firmware image too large",
142            Self::NotPowerOfTwo => "firmware image size is not a power of two",
143            Self::BadResetVector => "firmware reset vector is invalid",
144            Self::BadOptionRomSignature => "option ROM signature is invalid",
145            Self::BadOptionRomSize => "option ROM size code is invalid",
146            Self::BadOptionRomChecksum => "option ROM checksum is invalid",
147            Self::OverlappingImages => "firmware images overlap",
148            Self::WriteFailed => "firmware memory write failed",
149        }
150    }
151}
152
153/// Validated BIOS image description.
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub struct BiosInfo {
156    /// Image length in bytes (power of two).
157    pub len: u32,
158    /// Guest-physical base the image must be copied to.
159    pub base: u32,
160    /// Far-jump target of the reset vector, relative to [`RESET_SEGMENT`].
161    pub reset_offset: u16,
162    /// Modulo-256 sum of the image (QEMU-style BIOSes are not required to be
163    /// zero, so this is informational).
164    pub checksum: u8,
165}
166
167/// Validated option-ROM description.
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub struct OptionRomInfo {
170    /// Effective length declared by the size code, in bytes.
171    pub len: u32,
172    /// Guest-physical base the ROM must be copied to.
173    pub base: u32,
174    /// Initialisation entry point, relative to [`OPTION_ROM_BASE`].
175    pub entry: u16,
176}
177
178/// Result of installing a firmware image in a world.
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180pub struct FirmwareLayout {
181    /// Validated BIOS image.
182    pub bios: BiosInfo,
183    /// VGA option ROM, when one was installed.
184    pub option_rom: Option<OptionRomInfo>,
185    /// CMOS floppy-drive type written by the caller.
186    pub cmos_floppy_type: u8,
187    /// Extended memory advertised to the firmware, in KiB (above 1 MiB).
188    pub extended_memory_kib: u16,
189}
190
191impl FirmwareLayout {
192    /// Linear address of the first instruction the vCPU executes.
193    pub const fn reset_linear(&self) -> u32 {
194        RESET_LINEAR
195    }
196
197    /// Real-mode segment of the reset state.
198    pub const fn reset_segment(&self) -> u16 {
199        RESET_SEGMENT
200    }
201
202    /// Real-mode instruction pointer of the reset state.
203    pub const fn reset_ip(&self) -> u16 {
204        RESET_IP
205    }
206
207    /// True when `gpa` lies inside the installed BIOS image.
208    pub const fn contains_bios(&self, gpa: u32) -> bool {
209        gpa >= self.bios.base && gpa < BIOS_TOP
210    }
211}
212
213/// Tunables a firmware image needs from the machine description.
214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
215pub struct FirmwareConfig {
216    /// CMOS `0x10` value: high nibble = drive A type, low nibble = drive B.
217    pub cmos_floppy_type: u8,
218    /// Extended memory above 1 MiB, in KiB. SeaBIOS derives `RamSize` from
219    /// CMOS `0x30`/`0x31` when no fw_cfg channel is present.
220    pub extended_memory_kib: u16,
221    /// Install the bundled SeaVGABIOS option ROM at [`OPTION_ROM_BASE`].
222    pub install_vga_rom: bool,
223}
224
225impl FirmwareConfig {
226    /// Configuration used by the FreeDOS test world: one 1.44 MiB floppy and
227    /// 3 MiB of extended memory (a 4 MiB machine).
228    pub const fn freedos() -> Self {
229        Self {
230            cmos_floppy_type: FLOPPY_TYPE_1_44M,
231            extended_memory_kib: 3 * 1024,
232            install_vga_rom: true,
233        }
234    }
235
236    /// CMOS `0x30`/`0x31` bytes encoding [`Self::extended_memory_kib`].
237    ///
238    /// SeaBIOS computes `(low << 10) | (high << 18) + 1 MiB`; the encoding is
239    /// therefore a 16-bit count in KiB split as `low` (1 KiB units) and
240    /// `high` (256 KiB units).
241    pub const fn extmem_cmos(self) -> (u8, u8) {
242        let kib = self.extended_memory_kib as u32;
243        let low = (kib & 0xFF) as u8;
244        let high = ((kib >> 8) & 0xFF) as u8;
245        (low, high)
246    }
247}
248
249impl Default for FirmwareConfig {
250    fn default() -> Self {
251        Self::freedos()
252    }
253}
254
255/// Validates a flat BIOS image and computes its placement.
256///
257/// The image must be a power-of-two length between [`MIN_BIOS_LEN`] and
258/// [`MAX_BIOS_LEN`] and end with a `FAR JMP 0xF000:xxxx` reset vector, which is
259/// the architectural x86 reset entry. The image is placed so that it **ends**
260/// at [`BIOS_TOP`]; the official 256 KiB SeaBIOS therefore lands at `0xC_0000`
261/// and leaves its first 64 KiB zero-filled for option ROMs.
262pub fn validate_bios(image: &[u8]) -> Result<BiosInfo, FirmwareError> {
263    let len = image.len();
264    if len < MIN_BIOS_LEN {
265        return Err(FirmwareError::TooSmall);
266    }
267    if len > MAX_BIOS_LEN {
268        return Err(FirmwareError::TooLarge);
269    }
270    if !len.is_power_of_two() {
271        return Err(FirmwareError::NotPowerOfTwo);
272    }
273    let reset = &image[len - RESET_VECTOR_LEN..];
274    // `EA off_lo off_hi seg_lo seg_hi`: far jump to F000:offset.
275    if reset[0] != 0xEA || reset[3] != 0x00 || reset[4] != 0xF0 {
276        return Err(FirmwareError::BadResetVector);
277    }
278    let reset_offset = u16::from_le_bytes([reset[1], reset[2]]);
279    Ok(BiosInfo {
280        len: len as u32,
281        base: BIOS_TOP - len as u32,
282        reset_offset,
283        checksum: checksum(image),
284    })
285}
286
287/// Validates an option ROM and computes its placement.
288///
289/// The size code at offset 2 is in 512-byte units. Only the declared portion
290/// is checksummed and installed, which is what the PC option-ROM scan does.
291pub fn validate_option_rom(image: &[u8]) -> Result<OptionRomInfo, FirmwareError> {
292    if image.len() < SECTOR_SIZE || image[..2] != OPTION_ROM_SIGNATURE {
293        return Err(FirmwareError::BadOptionRomSignature);
294    }
295    let units = u32::from(image[OPTION_ROM_SIZE_OFFSET]);
296    let len = units * SECTOR_SIZE as u32;
297    if len == 0 || len as usize > image.len() {
298        return Err(FirmwareError::BadOptionRomSize);
299    }
300    if checksum(&image[..len as usize]) != 0 {
301        return Err(FirmwareError::BadOptionRomChecksum);
302    }
303    let entry = u16::from_le_bytes([
304        image[OPTION_ROM_ENTRY_OFFSET],
305        image[OPTION_ROM_ENTRY_OFFSET + 1],
306    ]);
307    Ok(OptionRomInfo {
308        len,
309        base: OPTION_ROM_BASE,
310        entry,
311    })
312}
313
314/// Installs a validated BIOS image and an optional VGA option ROM.
315///
316/// The BIOS is written at `bios.base`; the option ROM at
317/// [`OPTION_ROM_BASE`]. Both ranges must already be mapped writable in the
318/// world, and the caller must map the RAM the returned configuration
319/// describes before entering the guest.
320pub fn install(
321    memory: &mut impl RomMemory,
322    image: &[u8],
323    option_rom: Option<&[u8]>,
324    config: FirmwareConfig,
325) -> Result<FirmwareLayout, FirmwareError> {
326    let bios = validate_bios(image)?;
327    let option_info = match (config.install_vga_rom, option_rom) {
328        (true, Some(rom)) => {
329            let info = validate_option_rom(rom)?;
330            if info.base + info.len > OPTION_ROM_END {
331                return Err(FirmwareError::BadOptionRomSize);
332            }
333            if info.base + info.len > bios.base && info.base < BIOS_TOP {
334                // A 256 KiB BIOS starts at 0xC0000 and covers the option-ROM
335                // window. The official SeaBIOS image leaves that prefix
336                // zero-filled: an option ROM may live there, but only if the
337                // bytes it replaces are unused padding.
338                let start = (info.base - bios.base) as usize;
339                let end = start + info.len as usize;
340                let Some(padding) = image.get(start..end) else {
341                    return Err(FirmwareError::OverlappingImages);
342                };
343                if padding.iter().any(|byte| *byte != 0) {
344                    return Err(FirmwareError::OverlappingImages);
345                }
346            }
347            Some(info)
348        }
349        _ => None,
350    };
351    if !memory.write(bios.base, image) {
352        return Err(FirmwareError::WriteFailed);
353    }
354    let option_rom = match (option_info, option_rom) {
355        (Some(info), Some(rom)) => {
356            if !memory.write(info.base, &rom[..info.len as usize]) {
357                return Err(FirmwareError::WriteFailed);
358            }
359            Some(info)
360        }
361        _ => None,
362    };
363    Ok(FirmwareLayout {
364        bios,
365        option_rom,
366        cmos_floppy_type: config.cmos_floppy_type,
367        extended_memory_kib: config.extended_memory_kib,
368    })
369}
370
371/// Installs the bundled SeaBIOS images with the FreeDOS configuration.
372pub fn install_seabios(
373    memory: &mut impl RomMemory,
374    config: FirmwareConfig,
375) -> Result<FirmwareLayout, FirmwareError> {
376    install(memory, seabios_image(), Some(seabios_vga_rom()), config)
377}
378
379/// Modulo-256 sum of `bytes`.
380pub fn checksum(bytes: &[u8]) -> u8 {
381    bytes.iter().fold(0u8, |sum, byte| sum.wrapping_add(*byte))
382}
383
384/// Reads the validated reset vector bytes as `(offset, segment)`.
385///
386/// Useful for diagnostics and host tests; the installer already checked them.
387pub fn reset_vector(image: &[u8]) -> Option<(u16, u16)> {
388    let info = validate_bios(image).ok()?;
389    Some((info.reset_offset, RESET_SEGMENT))
390}
391
392/// Builds a flat zero image with the given BIOS placed at its final address.
393///
394/// Host-test helper: the kernel installs into world memory directly.
395pub fn flat_image_with_bios(image: &[u8]) -> Result<Vec<u8>, FirmwareError> {
396    let info = validate_bios(image)?;
397    let mut flat = vec![0u8; BIOS_TOP as usize];
398    flat[info.base as usize..].copy_from_slice(image);
399    Ok(flat)
400}