Skip to main content

strat9_kernel/s9vm/
biosrom.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 : real-mode BIOS ROM stubs, low-memory layout and demo boot image.
24//!
25//! A DOS-class guest needs the classic 16-bit firmware surface: an interrupt
26//! vector table, a BIOS data area, ROM interrupt stubs and a bootable disk
27//! image. This module produces all of it as pure data:
28//!
29//! - [`stub_bytes`] hand-encodes one 16-bit real-mode interrupt stub: it saves
30//!   the caller registers, reports the interrupt number on the debug port, and
31//!   patches the caller's stacked `FLAGS` (`CF`/`ZF`) from a scratch byte;
32//! - [`install`] writes the stubs, the IVT entries and the BDA/EBDA fields into
33//!   a guest low-memory image through the [`RomMemory`] trait;
34//! - [`demo_disk_image`] builds a deterministic 1.44 MiB floppy image whose
35//!   boot sector prints a banner, loads the second stage through `INT 13h` and
36//!   jumps to it; the second stage prints its own banner, reads a key through
37//!   `INT 16h` (bounded retry), and reports success with the byte `0x4B` on
38//!   debug port `0x00E9`.
39//!
40//! # Low-memory layout
41//!
42//! | Range | Content |
43//! |---|---|
44//! | `0x0000..0x0400` | interrupt vector table (256 far pointers) |
45//! | `0x0400..0x0500` | BIOS data area |
46//! | `0x0500` | scratch byte used by the BIOS stubs ([`SCRATCH_GPA`]) |
47//! | `0x7C00..0x7E00` | boot sector ([`BOOT_SECTOR_GPA`]) |
48//! | `0x7E00..0x8000` | demo second stage |
49//! | `0xB8000..0xBFFFF` | text mode video memory ([`VIDEO_BASE`]) |
50//! | `0xF0000..0xF8000` | BIOS ROM image (`F000:0000`, [`ROM_BASE`]) |
51//!
52//! The ROM image is 32 KiB at segment `F000`. The per-vector stubs live at
53//! `F000:0100 + vector * 0x10` (at most [`MAX_STUB_LEN`] bytes each; all 256
54//! stubs end at `F000:1100`) and the shared tail every serviced stub jumps to
55//! is at `F000:1100`, followed by the rest of the free ROM area.
56//!
57//! # Vectors with no firmware service
58//!
59//! A real firmware installs a handler for *every* vector: leaving an entry at
60//! `0000:0000` makes the CPU execute the interrupt vector table itself, so any
61//! stray `INT`, CPU exception or spurious IRQ becomes an unexplained jump to
62//! zero. [`install`] therefore fills the remaining vectors with
63//! [`fault_stub_bytes`], which reports the vector on port
64//! [`FAULT_PORT_BASE`]` + vector` and returns with `IRET`: the kernel logs the
65//! event with the faulting `CS:IP` and decides whether the run must stop.
66//!
67//! # Per-vector stub disassembly (vector `0x10`, port `0xE010`)
68//!
69//! Each per-vector stub only sets `DX` to the debug port and jumps to the
70//! shared tail; the `OUT` and the flag patch happen there, once.
71//!
72//! ```text
73//! offset  bytes        instruction            meaning
74//! 0x00    BA 10 E0     mov dx, 0xE010         port = 0xE000 + vector
75//! 0x03    E9 xx xx     jmp 0x0900             shared tail (relative)
76//! ```
77//!
78//! # Shared tail disassembly (`F000:1100`, 46 bytes)
79//!
80//! Entry state (the `INT` instruction already pushed the interrupt frame):
81//! `[SP] = IP`, `[SP+2] = CS`, `[SP+4] = FLAGS`; `DX` holds the port chosen by
82//! the per-vector stub. The tail echoes `AL` (the incoming argument, which
83//! identifies the caller request on the reported port), then patches only the
84//! stacked `FLAGS` word and returns with every register preserved. This is
85//! essential: the kernel writes BIOS return values into the guest register file
86//! at the `OUT` exit (AX for `INT 16h`, AH for `INT 13h`, CX/DX for `INT 10h`
87//! AH=03, ...) and those values must reach the caller through the `IRET`.
88//!
89//! ```text
90//! offset  bytes              instruction                     meaning
91//! 0x00    EE                 out dx, al                      report vector, AL intact
92//! 0x01    1E                 push ds                         save the caller DS
93//! 0x02    6A 00              push 0                          DS = 0
94//! 0x04    1F                 pop ds
95//! 0x05    50                 push ax                         save the returned AX
96//! 0x06    55                 push bp
97//! 0x07    89 E5              mov bp, sp                      frame; FLAGS at [bp+0x0A]
98//! 0x09    A0 00 05           mov al, [0x0500]                scratch byte
99//! 0x0C    A8 01              test al, 1                      CF from bit 0
100//! 0x0E    74 06              jz 0x16
101//! 0x10    83 4E 0A 01        or word [bp+0x0A], 0x0001
102//! 0x14    EB 04              jmp 0x1A
103//! 0x16    83 66 0A FE        and word [bp+0x0A], 0xFFFE
104//! 0x1A    A8 02              test al, 2                      ZF from bit 1
105//! 0x1C    74 06              jz 0x24
106//! 0x1E    83 4E 0A 40        or word [bp+0x0A], 0x0040
107//! 0x22    EB 04              jmp 0x28
108//! 0x24    83 66 0A BF        and word [bp+0x0A], 0xFFBF
109//! 0x28    1F                 pop ds                          restore the caller DS
110//! 0x29    5D                 pop bp                          restore the caller BP
111//! 0x2A    58                 pop ax                          restore the kernel-written AX
112//! 0x2B    CF                 iret
113//! ```
114//!
115//! The three pushes (`AX`, `BP`, `DS`) are undone in reverse order: the caller
116//! `DS` and `BP` must come back exactly as the guest left them, because a DOS
117//! guest keeps its data in `DS` and its frame in `BP` across a BIOS call.
118//!
119//! Scratch byte semantics: bit 0 = carry flag, bit 1 = zero flag; every other
120//! bit is ignored. Only 8- and 16-bit instructions are used, so the upper halves
121//! of the 32-bit registers are never touched. `SP`, `SS` and `ES` are not
122//! modified at all; `AX`, `BP` and `DS` are saved and restored.
123//!
124//! # Demo boot sector disassembly (`0x7C00`, 0x65 code bytes)
125//!
126//! ```text
127//! 0x00  EB 1C              jmp short main
128//! 0x02  90                 nop
129//! 0x03  53 39 56 4D 20 ... 'S9VM DOS-BOOT', 13, 10, 0
130//! 0x13  44 49 53 4B 20 ... 'DISK ERR', 13, 10, 0
131//! 0x1E  FA                 cli
132//! 0x1F  31 C0              xor ax, ax
133//! 0x21  8E D0              mov ss, ax
134//! 0x23  BC 00 7C           mov sp, 0x7C00
135//! 0x26  8E D8              mov ds, ax
136//! 0x28  8E C0              mov es, ax
137//! 0x2A  FB                 sti
138//! 0x2B  BE 03 7C           mov si, 0x7C03            banner
139//! 0x2E  E8 28 00           call print
140//! 0x31  B4 02              mov ah, 0x02              INT 13h: read one sector
141//! 0x33  B0 01              mov al, 0x01
142//! 0x35  B5 00              mov ch, 0x00              cylinder 0
143//! 0x37  B1 02              mov cl, 0x02              sector 2 (1-based)
144//! 0x39  B6 00              mov dh, 0x00              head 0
145//! 0x3B  B2 00              mov dl, 0x00              drive 0
146//! 0x3D  BB 00 7E           mov bx, 0x7E00            ES:BX destination
147//! 0x40  CD 13              int 0x13
148//! 0x42  72 05              jc disk_error
149//! 0x44  EA 00 7E 00 00     jmp far 0x0000:0x7E00    run the second stage
150//! 0x49  BE 13 7C           mov si, 0x7C13            error message
151//! 0x4C  E8 0A 00           call print
152//! 0x4F  B0 46              mov al, 0x46              failure marker 'F'
153//! 0x51  BA E9 00           mov dx, 0x00E9
154//! 0x54  EE                 out dx, al
155//! 0x55  FA                 cli
156//! 0x56  F4                 hlt
157//! 0x57  EB FC              jmp 0x55                  halt forever
158//! 0x59  B4 0E              print: mov ah, 0x0E       INT 10h teletype
159//! 0x5B  AC                 lodsb
160//! 0x5C  84 C0              test al, al
161//! 0x5E  74 04              jz done
162//! 0x60  CD 10              int 0x10
163//! 0x62  EB F7              jmp next
164//! 0x64  C3                 ret
165//! ```
166//!
167//! # Demo second stage disassembly (`0x7E00`, 0x48 code bytes)
168//!
169//! ```text
170//! 0x00  FA                 cli
171//! 0x01  31 C0              xor ax, ax
172//! 0x03  8E D8              mov ds, ax
173//! 0x05  8E C0              mov es, ax
174//! 0x07  8E D0              mov ss, ax
175//! 0x09  BC 00 7C           mov sp, 0x7C00
176//! 0x0C  FB                 sti
177//! 0x0D  BE 3C 7E           mov si, 0x7E3C            'STAGE2 OK' banner
178//! 0x10  E8 1D 00           call print
179//! 0x13  B9 10 00           mov cx, 0x0010            bounded retry count
180//! 0x16  B4 00              retry: mov ah, 0x00       INT 16h: read a key
181//! 0x18  CD 16              int 0x16
182//! 0x1A  75 06              jnz key                   ZF=0: a key is available
183//! 0x1C  E2 F8              loop retry
184//! 0x1E  B0 3F              mov al, '?'               give up: print '?'
185//! 0x20  EB 00              jmp show
186//! 0x22  B4 0E              show: mov ah, 0x0E        print the character
187//! 0x24  CD 10              int 0x10
188//! 0x26  B0 4B              mov al, 0x4B              success marker 'K'
189//! 0x28  BA E9 00           mov dx, 0x00E9
190//! 0x2B  EE                 out dx, al
191//! 0x2C  FA                 cli
192//! 0x2D  F4                 hlt
193//! 0x2E  EB FD              jmp 0x2D                  halt forever
194//! 0x30  B4 0E              print: mov ah, 0x0E
195//! 0x32  AC                 lodsb
196//! 0x33  84 C0              test al, al
197//! 0x35  74 04              jz done
198//! 0x37  CD 10              int 0x10
199//! 0x39  EB F7              jmp next
200//! 0x3B  C3                 ret
201//! 0x3C  53 54 41 47 ...    'STAGE2 OK', 13, 10, 0
202//! ```
203//!
204//! The demo is deliberately hand-assembled data: there is no assembler in the
205//! build, and the exact bytes are part of the contract the selftest checks.
206//! The shared tail patches only `CF`/`ZF` and preserves the register file, so
207//! when the kernel answers `INT 16h` by writing the key into `AX` at the `OUT`
208//! exit, the demo's `INT 16h` returns that key and prints it; `'?'` is printed
209//! only when the bounded retry loop gives up.
210
211use alloc::{vec, vec::Vec};
212
213/// Base of the interrupt vector table.
214pub const IVT_BASE: u32 = 0x0000;
215/// Base of the BIOS data area.
216pub const BDA_BASE: u32 = 0x0400;
217/// Scratch byte read by the interrupt stubs (`CF` = bit 0, `ZF` = bit 1).
218pub const SCRATCH_GPA: u32 = 0x0500;
219/// Guest-physical address where a boot sector is loaded.
220pub const BOOT_SECTOR_GPA: u32 = 0x7C00;
221/// Initial real-mode stack pointer (`SS:SP = 0x0000:0x7C00`).
222pub const BOOT_STACK_TOP: u16 = 0x7C00;
223/// Guest-physical base of the text-mode video memory.
224pub const VIDEO_BASE: u32 = 0xB8000;
225/// Real-mode segment of the BIOS ROM.
226pub const ROM_SEGMENT: u16 = 0xF000;
227/// Guest-physical base of the BIOS ROM.
228pub const ROM_BASE: u32 = 0xF0000;
229/// Size of the BIOS ROM image.
230pub const ROM_LEN: u32 = 0x8000;
231/// Offset inside the ROM segment of the first interrupt stub.
232pub const ROM_STUB_BASE: u16 = 0x0100;
233/// First I/O port used to report an interrupt: `port = base + vector`.
234pub const BIOS_PORT_BASE: u16 = 0xE000;
235/// Spacing between two per-vector stubs in the ROM.
236pub const STUB_STRIDE: u16 = 0x10;
237/// Length of one per-vector stub: `mov dx, port` (3) + `jmp tail` (3).
238pub const MAX_STUB_LEN: u16 = 11;
239/// ROM offset of the shared stub tail (after the 256 per-vector stubs).
240pub const ROM_SHARED_TAIL: u16 = 0x1100;
241/// First I/O port used to report an interrupt that has no firmware service:
242/// `port = base + vector`.
243pub const FAULT_PORT_BASE: u16 = 0xE100;
244/// Upper bound on the shared tail length, so the tail stays inside the ROM.
245pub const MAX_SHARED_TAIL_LEN: u16 = 0x80;
246/// Offset inside the stacked interrupt frame where the shared tail patches the
247/// caller `FLAGS` word, relative to the tail's `BP` frame: `[BP + 0x0A]`.
248pub const TAIL_FLAGS_OFFSET: u16 = 0x0A;
249
250/// Vectors a stub is installed for.
251///
252/// The set is the classic BIOS/DOS surface: print screen (`0x05`), the timer
253/// and IRQ vectors (`0x08..=0x0F`, including the printer line), the main BIOS
254/// services (`0x10` video, `0x11` equipment, `0x12` memory size, `0x13` disk,
255/// `0x14` serial, `0x15` system, `0x16` keyboard, `0x17` printer), the time
256/// service (`0x1A`), the user timer-tick hook (`0x1C`) and the RTC alarm
257/// (`0x4A`).
258pub const VECTORS: [u8; 22] = [
259    0x05, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
260    0x17, 0x18, 0x19, 0x1A, 0x1C, 0x4A,
261];
262
263/// Debug port used by the demo boot image to report its progress.
264pub const DEMO_DEBUG_PORT: u16 = 0x00E9;
265/// Marker written on the debug port when the demo succeeds (`'K'`).
266pub const DEMO_SUCCESS_MARKER: u8 = 0x4B;
267/// Marker written on the debug port when the demo cannot load its stage 2.
268pub const DEMO_FAILURE_MARKER: u8 = 0x46;
269/// Demo boot-sector banner (without CR/LF).
270pub const DEMO_BANNER: &[u8] = b"S9VM DOS-BOOT";
271/// Demo stage-2 banner (without CR/LF).
272pub const DEMO_STAGE2_BANNER: &[u8] = b"STAGE2 OK";
273/// Demo disk-error message (without CR/LF).
274pub const DEMO_ERROR: &[u8] = b"DISK ERR";
275
276/// Floppy geometry: 80 cylinders.
277pub const FLOPPY_CYLINDERS: u16 = 80;
278/// Floppy geometry: 2 heads.
279pub const FLOPPY_HEADS: u8 = 2;
280/// Floppy geometry: 18 sectors per track.
281pub const FLOPPY_SECTORS: u8 = 18;
282/// Size of one disk sector.
283pub const SECTOR_SIZE: usize = 512;
284/// Total size of a 1.44 MiB floppy image.
285pub const FLOPPY_BYTES: usize = 1_474_560;
286/// Total number of sectors of the floppy image.
287pub const FLOPPY_TOTAL_SECTORS: u64 = 2_880;
288
289/// BDA field: installed equipment word.
290pub const BDA_EQUIPMENT: u32 = 0x0410;
291/// BDA field: conventional memory size in KiB (low 16 bits).
292pub const BDA_MEMORY_SIZE: u32 = 0x0413;
293/// BDA field: keyboard buffer head offset.
294pub const BDA_KEYBOARD_HEAD: u32 = 0x041A;
295/// BDA field: keyboard buffer tail offset.
296pub const BDA_KEYBOARD_TAIL: u32 = 0x041C;
297/// First slot offset a PC firmware leaves in the keyboard ring head/tail.
298pub const KEY_BUFFER_FIRST_OFFSET: u16 = 0x1E;
299/// BDA field: extended BIOS data area segment.
300pub const BDA_EBDA_SEGMENT: u32 = 0x040E;
301/// BDA field: current video mode.
302pub const BDA_VIDEO_MODE: u32 = 0x0449;
303/// BDA field: number of text columns.
304pub const BDA_COLUMNS: u32 = 0x044A;
305/// BDA field: cursor position of page 0 (row/column).
306pub const BDA_CURSOR: u32 = 0x0450;
307/// BDA field: CRTC I/O port base.
308pub const BDA_CRTC_PORT: u32 = 0x0463;
309/// BDA field: number of text rows minus one.
310pub const BDA_ROWS: u32 = 0x0484;
311/// BDA field: character height in scan lines.
312pub const BDA_CHAR_HEIGHT: u32 = 0x0485;
313/// BDA field: timer tick counter (32 bits).
314pub const BDA_TICK_COUNT: u32 = 0x046C;
315
316/// Equipment word value: one floppy drive, 80x25 colour, no coprocessor.
317pub const EQUIPMENT_VALUE: u16 = 0x0021;
318/// Conventional memory size value, in KiB.
319pub const MEMORY_SIZE_VALUE: u16 = 640;
320/// Extended BIOS data area segment value.
321pub const EBDA_SEGMENT_VALUE: u16 = 0x9FC0;
322/// Video mode value: 80x25 colour text.
323pub const VIDEO_MODE_VALUE: u8 = 3;
324/// Text column count value.
325pub const COLUMNS_VALUE: u16 = 80;
326/// Cursor position value (row 0, column 0).
327pub const CURSOR_VALUE: u16 = 0;
328/// CRTC I/O port base value.
329pub const CRTC_PORT_VALUE: u16 = 0x03D4;
330/// Text row count value (rows minus one).
331pub const ROWS_VALUE: u8 = 24;
332/// Character height value, in scan lines.
333pub const CHAR_HEIGHT_VALUE: u8 = 16;
334/// Initial timer tick value.
335pub const TICK_COUNT_VALUE: u32 = 0;
336
337/// Reasons why a ROM install operation is rejected.
338#[derive(Debug, Clone, Copy, PartialEq, Eq)]
339pub enum RomError {
340    /// A region is too small to hold the BIOS data it must receive.
341    TooSmall,
342    /// A requested vector is outside the supported set ([`VECTORS`]).
343    UnsupportedVector(u8),
344    /// The target memory refused a write (out of its mapped range).
345    WriteFailed,
346}
347
348/// Minimal guest low-memory access used by the install helpers.
349///
350/// The real guest memory implementation lives in the kernel loader; tests use
351/// a flat `Vec<u8>`. Addresses are guest-physical (linear) addresses.
352pub trait RomMemory {
353    /// Writes `bytes` at `linear`. Returns `false` when the range is not
354    /// writable or not mapped.
355    fn write(&mut self, linear: u32, bytes: &[u8]) -> bool;
356
357    /// Reads `out.len()` bytes from `linear`. Returns `false` when the range is
358    /// not readable or not mapped.
359    fn read(&mut self, linear: u32, out: &mut [u8]) -> bool;
360
361    /// Writes a little-endian `u16` at `linear`.
362    fn write_u16(&mut self, linear: u32, value: u16) -> bool {
363        self.write(linear, &value.to_le_bytes())
364    }
365
366    /// Writes a little-endian `u32` at `linear`.
367    fn write_u32(&mut self, linear: u32, value: u32) -> bool {
368        self.write(linear, &value.to_le_bytes())
369    }
370}
371
372/// I/O port that reports `vector` to the host.
373pub const fn bios_port(vector: u8) -> u16 {
374    BIOS_PORT_BASE + vector as u16
375}
376
377/// ROM offset of the stub for `vector`.
378pub const fn stub_offset(vector: u8) -> u16 {
379    ROM_STUB_BASE + vector as u16 * STUB_STRIDE
380}
381
382/// Guest-physical address of the stub for `vector`.
383pub const fn stub_gpa(vector: u8) -> u32 {
384    ROM_BASE + stub_offset(vector) as u32
385}
386
387/// Guest-physical address of the shared stub tail.
388pub const fn shared_tail_gpa() -> u32 {
389    ROM_BASE + ROM_SHARED_TAIL as u32
390}
391
392/// Returns true when `vector` belongs to [`VECTORS`].
393pub fn is_supported_vector(vector: u8) -> bool {
394    VECTORS.contains(&vector)
395}
396
397/// Encodes the per-vector real-mode stub for `vector`.
398///
399/// The stub must not destroy the registers the BIOS service uses: it pushes the
400/// caller `AX` and `DX` (the kernel reads them back from the guest stack at the
401/// `OUT` exit), loads the debug port into `DX`, moves the command byte (`AH`)
402/// into `AL` for the `OUT`, then jumps to the shared tail
403/// ([`shared_tail_bytes`]) which drops the saved registers, restores the
404/// kernel-written results and patches the caller's stacked `FLAGS`.
405///
406/// The encoding is at most [`MAX_STUB_LEN`] bytes.
407pub fn stub_bytes(vector: u8) -> Vec<u8> {
408    let port = bios_port(vector);
409    let port_lo = (port & 0xFF) as u8;
410    let port_hi = (port >> 8) as u8;
411    // Address of the instruction after the jump, inside the ROM.
412    let next = u32::from(stub_offset(vector)) + u32::from(MAX_STUB_LEN);
413    // The tail always follows the 256 per-vector stubs, so the displacement is
414    // positive and fits in the signed 16-bit jump offset.
415    let displacement = (u32::from(ROM_SHARED_TAIL) as i32 - next as i32) as i16;
416    let rel = displacement.to_le_bytes();
417    vec![
418        0x50, // push ax (the BIOS command is in AH)
419        0x52, // push dx (drive/head for INT 13h, page for INT 10h)
420        0x88, 0xE0, // mov al, ah (send the command as the OUT byte)
421        0xBA, port_lo, port_hi, // mov dx, port
422        0xEE,    // out dx, al
423        0xE9, rel[0], rel[1], // jmp shared_tail
424    ]
425}
426
427/// Encodes the shared stub tail installed at [`ROM_SHARED_TAIL`].
428///
429/// The `OUT` already happened in the stub; on entry the caller `DX` and `AX`
430/// are saved on the guest stack and the kernel has overwritten the guest `AX`
431/// (and possibly `DX`) with the BIOS result. The tail drops the saved values,
432/// patches only the caller's stacked `FLAGS` from the scratch byte at
433/// [`SCRATCH_GPA`] (bit 0 -> `CF`, bit 1 -> `ZF`) and returns with `iret`, so
434/// the BIOS return values written by the kernel reach the guest.
435pub fn shared_tail_bytes() -> Vec<u8> {
436    let flags = TAIL_FLAGS_OFFSET as u8;
437    vec![
438        0x83, 0xC4, 0x04, // add sp, 4 (drop the saved DX and AX)
439        0x50, // push ax (kernel result)
440        0x55, // push bp
441        0x1E, // push ds
442        0x6A, 0x00, // push 0
443        0x1F, // pop ds
444        0x89, 0xE5, // mov bp, sp
445        0xA0, 0x00, 0x05, // mov al, [0x0500]
446        0xA8, 0x01, // test al, 1
447        0x74, 0x06, // jz clear_cf
448        0x83, 0x4E, flags, 0x01, // or word [bp+flags], 0x0001
449        0xEB, 0x04, // jmp zf
450        0x83, 0x66, flags, 0xFE, // and word [bp+flags], 0xFFFE
451        0xA8, 0x02, // test al, 2
452        0x74, 0x06, // jz clear_zf
453        0x83, 0x4E, flags, 0x40, // or word [bp+flags], 0x0040
454        0xEB, 0x04, // jmp done
455        0x83, 0x66, flags, 0xBF, // and word [bp+flags], 0xFFBF
456        0x1F, // pop ds (restore the caller DS)
457        0x5D, // pop bp (restore the caller BP)
458        0x58, // pop ax (restore the kernel-written AX)
459        0xCF, // iret
460    ]
461}
462
463/// I/O port that reports an unhandled guest interrupt `vector` to the host.
464pub const fn fault_port(vector: u8) -> u16 {
465    FAULT_PORT_BASE + vector as u16
466}
467
468/// Decodes a [`FAULT_PORT_BASE`] port back to the interrupt vector it reports.
469///
470/// Returns `None` for any other port, so the kernel can test a port exit with
471/// one call before treating it as a firmware event.
472pub const fn fault_vector(port: u16) -> Option<u8> {
473    if port >= FAULT_PORT_BASE && port < FAULT_PORT_BASE + 0x100 {
474        Some((port - FAULT_PORT_BASE) as u8)
475    } else {
476        None
477    }
478}
479
480/// Encodes the catch-all stub installed for a vector with no firmware service.
481///
482/// The stub saves `DX`, loads the fault port, reports the vector and returns
483/// with `IRET`. `AL` is not modified, so the guest sees no register change from
484/// an event it did not ask for; the reported port alone identifies the vector.
485/// The encoding is at most [`MAX_STUB_LEN`] bytes.
486pub fn fault_stub_bytes(vector: u8) -> Vec<u8> {
487    let port = fault_port(vector);
488    vec![
489        0x52, // push dx (the caller DX must survive)
490        0xBA,
491        (port & 0xFF) as u8,
492        (port >> 8) as u8, // mov dx, port
493        0xEE,              // out dx, al
494        0x5A,              // pop dx
495        0xCF,              // iret
496    ]
497}
498
499/// Writes one IVT entry per supported vector.
500///
501/// The entry is a real-mode far pointer `offset:segment` where `offset` is
502/// [`stub_offset`] and `segment` is [`ROM_SEGMENT`].
503pub fn write_ivt(mem: &mut impl RomMemory, vectors: &[u8]) -> Result<(), RomError> {
504    for &vector in vectors {
505        if !is_supported_vector(vector) {
506            return Err(RomError::UnsupportedVector(vector));
507        }
508        let entry = IVT_BASE + u32::from(vector) * 4;
509        let offset = stub_offset(vector);
510        if !mem.write_u16(entry, offset) || !mem.write_u16(entry + 2, ROM_SEGMENT) {
511            return Err(RomError::WriteFailed);
512        }
513    }
514    Ok(())
515}
516
517/// Writes one IVT entry for every vector: the serviced ones point at their
518/// BIOS stub, the others at their [`fault_stub_bytes`] catch-all handler.
519pub fn write_all_ivt(mem: &mut impl RomMemory, vectors: &[u8]) -> Result<(), RomError> {
520    write_ivt(mem, vectors)?;
521    for vector in 0..=u8::MAX {
522        if vectors.contains(&vector) {
523            continue;
524        }
525        let entry = IVT_BASE + u32::from(vector) * 4;
526        let offset = stub_offset(vector);
527        if !mem.write_u16(entry, offset) || !mem.write_u16(entry + 2, ROM_SEGMENT) {
528            return Err(RomError::WriteFailed);
529        }
530    }
531    Ok(())
532}
533
534/// Writes the BIOS data area fields a DOS boot needs.
535pub fn write_bda(mem: &mut impl RomMemory) -> Result<(), RomError> {
536    let writes: [(u32, u16); 6] = [
537        (BDA_EQUIPMENT, EQUIPMENT_VALUE),
538        (BDA_MEMORY_SIZE, MEMORY_SIZE_VALUE),
539        (BDA_EBDA_SEGMENT, EBDA_SEGMENT_VALUE),
540        (BDA_COLUMNS, COLUMNS_VALUE),
541        (BDA_CURSOR, CURSOR_VALUE),
542        (BDA_CRTC_PORT, CRTC_PORT_VALUE),
543    ];
544    for (address, value) in writes {
545        if !mem.write_u16(address, value) {
546            return Err(RomError::WriteFailed);
547        }
548    }
549    // Empty keyboard ring in the PC convention (head == tail == 0x1E): DOS's
550    // `INT 9` handler fills it and the firmware `INT 16h` service consumes it.
551    if !mem.write_u16(BDA_KEYBOARD_HEAD, KEY_BUFFER_FIRST_OFFSET)
552        || !mem.write_u16(BDA_KEYBOARD_TAIL, KEY_BUFFER_FIRST_OFFSET)
553    {
554        return Err(RomError::WriteFailed);
555    }
556    if !mem.write(BDA_VIDEO_MODE, &[VIDEO_MODE_VALUE])
557        || !mem.write(BDA_ROWS, &[ROWS_VALUE])
558        || !mem.write(BDA_CHAR_HEIGHT, &[CHAR_HEIGHT_VALUE])
559        || !mem.write_u32(BDA_TICK_COUNT, TICK_COUNT_VALUE)
560    {
561        return Err(RomError::WriteFailed);
562    }
563    Ok(())
564}
565
566/// Installs the per-vector stubs, the shared tail, the IVT entries and the BDA
567/// fields.
568///
569/// The stubs are written at [`stub_gpa`], the shared tail at
570/// [`shared_tail_gpa`], the IVT entries point at the per-vector stubs and the
571/// BDA/EBDA fields are initialised for a 640 KiB machine. The scratch byte is
572/// left untouched: the host sets it before each interrupt.
573///
574/// Every vector outside `vectors` receives a [`fault_stub_bytes`] handler, so a
575/// stray `INT`, a CPU exception or a spurious IRQ is reported to the kernel
576/// instead of jumping through the zeroed IVT entry at `0000:0000`.
577pub fn install(mem: &mut impl RomMemory, vectors: &[u8]) -> Result<(), RomError> {
578    for &vector in vectors {
579        if !is_supported_vector(vector) {
580            return Err(RomError::UnsupportedVector(vector));
581        }
582        let stub = stub_bytes(vector);
583        if !mem.write(stub_gpa(vector), &stub) {
584            return Err(RomError::WriteFailed);
585        }
586    }
587    for vector in 0..=u8::MAX {
588        if vectors.contains(&vector) {
589            continue;
590        }
591        let stub = fault_stub_bytes(vector);
592        if !mem.write(stub_gpa(vector), &stub) {
593            return Err(RomError::WriteFailed);
594        }
595    }
596    let tail = shared_tail_bytes();
597    if !mem.write(shared_tail_gpa(), &tail) {
598        return Err(RomError::WriteFailed);
599    }
600    write_all_ivt(mem, vectors)?;
601    write_bda(mem)
602}
603
604/// Builds a complete ROM image (zero-filled [`ROM_LEN`] bytes) with the stubs
605/// and the shared tail installed at their ROM offsets.
606///
607/// Useful for a loader that copies one contiguous ROM blob instead of writing
608/// the pieces individually.
609pub fn rom_image(vectors: &[u8]) -> Result<Vec<u8>, RomError> {
610    let stub_area_end = u32::from(ROM_STUB_BASE) + 256 * u32::from(STUB_STRIDE);
611    let tail_end = u32::from(ROM_SHARED_TAIL) + u32::from(MAX_SHARED_TAIL_LEN);
612    if stub_area_end > u32::from(ROM_SHARED_TAIL) || tail_end > ROM_LEN {
613        return Err(RomError::TooSmall);
614    }
615    let mut rom = vec![0u8; ROM_LEN as usize];
616    for &vector in vectors {
617        if !is_supported_vector(vector) {
618            return Err(RomError::UnsupportedVector(vector));
619        }
620        let stub = stub_bytes(vector);
621        let offset = stub_offset(vector) as usize;
622        rom[offset..offset + stub.len()].copy_from_slice(&stub);
623    }
624    for vector in 0..=u8::MAX {
625        if vectors.contains(&vector) {
626            continue;
627        }
628        let stub = fault_stub_bytes(vector);
629        let offset = stub_offset(vector) as usize;
630        rom[offset..offset + stub.len()].copy_from_slice(&stub);
631    }
632    let tail = shared_tail_bytes();
633    let tail_offset = ROM_SHARED_TAIL as usize;
634    rom[tail_offset..tail_offset + tail.len()].copy_from_slice(&tail);
635    Ok(rom)
636}
637
638/// Converts a floppy CHS address (sector is 1-based) to a linear block address.
639///
640/// Returns `None` when the cylinder, head or sector is outside the 1.44 MiB
641/// geometry ([`FLOPPY_CYLINDERS`] x [`FLOPPY_HEADS`] x [`FLOPPY_SECTORS`]).
642pub const fn chs_to_lba(cyl: u16, head: u8, sector: u8) -> Option<u64> {
643    if cyl >= FLOPPY_CYLINDERS || head >= FLOPPY_HEADS || sector == 0 || sector > FLOPPY_SECTORS {
644        return None;
645    }
646    Some(
647        (cyl as u64 * FLOPPY_HEADS as u64 + head as u64) * FLOPPY_SECTORS as u64
648            + (sector as u64 - 1),
649    )
650}
651
652/// Converts a linear block address back to a floppy CHS address (1-based
653/// sector). Returns `None` for an LBA outside the image.
654pub const fn lba_to_chs(lba: u64) -> Option<(u16, u8, u8)> {
655    if lba >= FLOPPY_TOTAL_SECTORS {
656        return None;
657    }
658    let per_cylinder = FLOPPY_HEADS as u64 * FLOPPY_SECTORS as u64;
659    let cyl = lba / per_cylinder;
660    let remainder = lba % per_cylinder;
661    let head = remainder / FLOPPY_SECTORS as u64;
662    let sector = remainder % FLOPPY_SECTORS as u64 + 1;
663    Some((cyl as u16, head as u8, sector as u8))
664}
665
666/// Demo boot-sector code and strings (before the trailing signature).
667///
668/// Hand-assembled 16-bit real mode; see the module documentation for the
669/// instruction-by-instruction disassembly.
670const DEMO_BOOT_CODE: &[u8] = &[
671    0xEB, 0x1C, 0x90, 0x53, 0x39, 0x56, 0x4D, 0x20, 0x44, 0x4F, 0x53, 0x2D, 0x42, 0x4F, 0x4F, 0x54,
672    0x0D, 0x0A, 0x00, 0x44, 0x49, 0x53, 0x4B, 0x20, 0x45, 0x52, 0x52, 0x0D, 0x0A, 0x00, 0xFA, 0x31,
673    0xC0, 0x8E, 0xD0, 0xBC, 0x00, 0x7C, 0x8E, 0xD8, 0x8E, 0xC0, 0xFB, 0xBE, 0x03, 0x7C, 0xE8, 0x28,
674    0x00, 0xB4, 0x02, 0xB0, 0x01, 0xB5, 0x00, 0xB1, 0x02, 0xB6, 0x00, 0xB2, 0x00, 0xBB, 0x00, 0x7E,
675    0xCD, 0x13, 0x72, 0x05, 0xEA, 0x00, 0x7E, 0x00, 0x00, 0xBE, 0x13, 0x7C, 0xE8, 0x0A, 0x00, 0xB0,
676    0x46, 0xBA, 0xE9, 0x00, 0xEE, 0xFA, 0xF4, 0xEB, 0xFC, 0xB4, 0x0E, 0xAC, 0x84, 0xC0, 0x74, 0x04,
677    0xCD, 0x10, 0xEB, 0xF7, 0xC3,
678];
679
680/// Demo second-stage code and strings (before the trailing signature).
681///
682/// Hand-assembled 16-bit real mode; see the module documentation for the
683/// instruction-by-instruction disassembly.
684const DEMO_STAGE2_CODE: &[u8] = &[
685    0xFA, 0x31, 0xC0, 0x8E, 0xD8, 0x8E, 0xC0, 0x8E, 0xD0, 0xBC, 0x00, 0x7C, 0xFB, 0xBE, 0x3C, 0x7E,
686    0xE8, 0x1D, 0x00, 0xB9, 0x10, 0x00, 0xB4, 0x00, 0xCD, 0x16, 0x75, 0x06, 0xE2, 0xF8, 0xB0, 0x3F,
687    0xEB, 0x00, 0xB4, 0x0E, 0xCD, 0x10, 0xB0, 0x4B, 0xBA, 0xE9, 0x00, 0xEE, 0xFA, 0xF4, 0xEB, 0xFD,
688    0xB4, 0x0E, 0xAC, 0x84, 0xC0, 0x74, 0x04, 0xCD, 0x10, 0xEB, 0xF7, 0xC3, 0x53, 0x54, 0x41, 0x47,
689    0x45, 0x32, 0x20, 0x4F, 0x4B, 0x0D, 0x0A, 0x00,
690];
691
692/// Builds the demo boot sector: code, zero padding and the `0x55AA` signature.
693pub fn demo_boot_sector() -> [u8; SECTOR_SIZE] {
694    let mut sector = [0u8; SECTOR_SIZE];
695    sector[..DEMO_BOOT_CODE.len()].copy_from_slice(DEMO_BOOT_CODE);
696    sector[510] = 0x55;
697    sector[511] = 0xAA;
698    sector
699}
700
701/// Builds the demo second stage: code, zero padding and the `0x55AA` signature.
702pub fn demo_stage2() -> [u8; SECTOR_SIZE] {
703    let mut sector = [0u8; SECTOR_SIZE];
704    sector[..DEMO_STAGE2_CODE.len()].copy_from_slice(DEMO_STAGE2_CODE);
705    sector[510] = 0x55;
706    sector[511] = 0xAA;
707    sector
708}
709
710/// Builds the deterministic 1.44 MiB demo floppy image.
711///
712/// Sector 0 is [`demo_boot_sector`], sector 1 is [`demo_stage2`]; every other
713/// sector is zero.
714pub fn demo_disk_image() -> Vec<u8> {
715    let mut image = vec![0u8; FLOPPY_BYTES];
716    image[..SECTOR_SIZE].copy_from_slice(&demo_boot_sector());
717    image[SECTOR_SIZE..2 * SECTOR_SIZE].copy_from_slice(&demo_stage2());
718    image
719}