strat9_kernel/s9vm/bios.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 : pure PC BIOS service model for a real-mode DOS-class guest.
24//!
25//! This module implements the software half of the classic firmware surface:
26//! it takes the guest register file captured at a BIOS interrupt, performs the
27//! requested service on a guest memory image and a synthetic block device, and
28//! returns the updated register values. It **touches no hardware**: the kernel
29//! adapter ([`BiosMemory`] / [`BiosDisk`]) supplies guest memory and disk
30//! sectors, and publishes the resulting `CF`/`ZF` through the scratch byte.
31//!
32//! # Scratch-byte protocol
33//!
34//! The real-mode ROM stubs installed by [`crate::s9vm::biosrom`] cannot return
35//! values in registers by themselves: they `OUT` to a debug port, the host
36//! services the call, and the stub patches the caller's stacked `FLAGS` from a
37//! single byte at [`SCRATCH_GPA`]. At the end of **every** call, handled or
38//! not, this model writes that byte:
39//!
40//! ```text
41//! bit 0 CF value ([`SCRATCH_CF`])
42//! bit 1 ZF value ([`SCRATCH_ZF`])
43//! other zero
44//! ```
45//!
46//! [`BiosOutcome::Unknown`] writes `0x00` (`CF=0`, `ZF=0`) and leaves the BDA
47//! alone: the guest is expected to have installed its own handler for that
48//! vector. On handled calls the two flags are also mirrored into
49//! [`BiosRegisters::flags`], for adapters that derive the scratch byte from the
50//! returned register file; the scratch byte stays authoritative.
51//!
52//! # Services
53//!
54//! | Vector | Function | Behaviour |
55//! |---|---|---|
56//! | `05h` | print screen | accepted, no-op (`CF=0`) |
57//! | `08h`, `1Ch` | timer / user tick | [`BiosOutcome::Unknown`] |
58//! | `10h` | video | mode, cursor, scroll, characters, string |
59//! | `11h` | equipment | `AX=0x0021` |
60//! | `12h` | memory size | `AX=640` KiB |
61//! | `13h` | disk | reset, status, CHS read, params, type, extensions, DAP read |
62//! | `15h` | system | `88h` only; `C0h`/`E8h` rejected |
63//! | `16h` | keyboard | polling queue, `AH=00/01/02` |
64//! | `17h` | printer | accepted, status `30h` |
65//! | `1Ah` | time | tick count and RTC time |
66//!
67//! Any other vector is [`BiosOutcome::Unknown`].
68//!
69//! # Failure statuses
70//!
71//! Every rejected request sets `CF=1` and a documented status:
72//!
73//! | Constant | Value | Used by |
74//! |---|---|---|
75//! | [`STATUS_INVALID_FUNCTION`] | `01h` | video/system/keyboard/disk subfunction |
76//! | [`DISK_STATUS_WRITE_PROTECTED`] | `03h` | disk write requests (synthetic disk) |
77//! | [`DISK_STATUS_SECTOR_NOT_FOUND`] | `04h` | bad CHS/LBA, backend error, unmapped buffer |
78//! | [`DISK_STATUS_MEDIA_NOT_FOUND`] | `0Ch` | unsupported drive number |
79//! | [`STATUS_NOT_SUPPORTED`] | `86h` | unsupported `INT 15h` subfunction |
80//!
81//! # BIOS data area
82//!
83//! [`initialise_bda`] fills the fields a DOS boot reads (equipment, memory
84//! size, EBDA segment, keyboard head/tail, tick count, video mode, columns,
85//! cursor, page, CRTC port, rows and character height). After every handled
86//! call [`BiosState::handle`] republishes the fields it owns: video mode,
87//! cursor, tick count and keyboard head/tail.
88//!
89//! The keyboard buffer is modelled as a compact [`alloc::collections::VecDeque`]
90//! rather than a real ring. The BDA therefore publishes a synthetic ring
91//! descriptor: head `0`, tail `2 * queued bytes` capped at the 32-byte buffer.
92//! This keeps the "head equals tail when empty" invariant without storing ring
93//! indices in the state.
94//!
95//! # Disk geometry
96//!
97//! [`FLOPPY_1440`] is the canonical 80 x 2 x 18 x 512 geometry (2880 sectors,
98//! 1.44 MiB). [`DiskGeometry::from_sectors`] returns it for images of at most
99//! 2880 sectors and a documented fixed-disk-ish 1024 x 16 x 63 x 512 geometry
100//! above that (1,032,192 sectors, about 504 MiB). The geometry only describes
101//! CHS decoding; the authoritative sector count is
102//! [`BiosDisk::sectors`], and reads past it fail with status `04h`.
103//!
104//! `CHS` sectors are one-based, as on the PC. Cylinder bits 9:8 travel in
105//! `CL` bits 7:6 and are reassembled by the model.
106//!
107//! # Documented deviations
108//!
109//! - `INT 10h AH=03` returns the cursor shape in `CX=0x0607`; the prompt also
110//! said `CH=0`, but the two cannot both hold, and `0x0607` wins because the
111//! shape is the documented return value. `CH` is `0x06` (shape start line).
112//! - `INT 11h` returns `AX=0x0021`. In that word bit 0 announces the floppy
113//! drive and bits 7:6 are `00b`, **not** `01b`: the two fields would make
114//! `0x0061`, so the authoritative literal `0x0021` is used.
115//! - `INT 13h AH=08` returns `DL=2` for drive `00h` and `DL=3` for drive
116//! `80h`. Only those two drive numbers are accepted (a stricter reading of
117//! the classic "below `0x80` means floppy" shorthand); anything else fails
118//! with status `0Ch`.
119//! - Text services write the default attribute `07h` where the caller does not
120//! supply one (`AH=0Eh`, scrolling blank lines use `BH`).
121//! - Guest buffer writes are attempted byte by byte through [`BiosMemory`].
122//! A byte the adapter refuses aborts the call with status `04h`; bytes
123//! already written stay written (the adapter is free to reject a range that
124//! crosses the end of mapped memory).
125//! - `INT 17h` accepts output but has no parallel port to deliver it to; the
126//! bytes are discarded and only the ready status is reported.
127
128use alloc::{collections::VecDeque, string::String, vec::Vec};
129
130/// Guest-physical address of the byte the ROM stubs read back.
131pub const SCRATCH_GPA: u32 = 0x0500;
132/// Scratch bit 0: carry flag.
133pub const SCRATCH_CF: u8 = 1;
134/// Scratch bit 1: zero flag.
135pub const SCRATCH_ZF: u8 = 2;
136
137/// Base of the BIOS data area.
138pub const BDA_BASE: u32 = 0x0400;
139/// BDA field: extended BIOS data area segment.
140pub const BDA_EBDA_SEGMENT: u32 = 0x040E;
141/// BDA field: installed equipment word.
142pub const BDA_EQUIPMENT: u32 = 0x0410;
143/// BDA field: conventional memory size, in KiB.
144pub const BDA_MEMORY_SIZE: u32 = 0x0413;
145/// BDA field: keyboard buffer head offset.
146pub const BDA_KEYBOARD_HEAD: u32 = 0x041A;
147/// BDA field: keyboard buffer tail offset.
148pub const BDA_KEYBOARD_TAIL: u32 = 0x041C;
149/// BDA field: current video mode.
150pub const BDA_VIDEO_MODE: u32 = 0x0449;
151/// BDA field: number of text columns.
152pub const BDA_COLUMNS: u32 = 0x044A;
153/// BDA field: cursor position of page 0 (`row << 8 | column`).
154pub const BDA_CURSOR: u32 = 0x0450;
155/// BDA field: active display page.
156pub const BDA_PAGE: u32 = 0x0462;
157/// BDA field: CRTC I/O port base.
158pub const BDA_CRTC_PORT: u32 = 0x0463;
159/// BDA field: timer tick counter, 32 bits.
160pub const BDA_TICK_COUNT: u32 = 0x046C;
161/// BDA field: text rows minus one.
162pub const BDA_ROWS: u32 = 0x0484;
163/// BDA field: character height, in scan lines.
164pub const BDA_CHAR_HEIGHT: u32 = 0x0485;
165
166/// BDA equipment word: one floppy drive, 80x25 colour (bit 0 and bits 5:4).
167///
168/// The floppy-count field in bits 7:6 stays `00b`; drive presence is carried by
169/// bit 0. This is the value the guest sees through `INT 11h`.
170pub const EQUIPMENT_WORD: u16 = 0x0021;
171/// Conventional memory size reported by [`initialise_bda`] and `INT 12h`.
172pub const MEMORY_SIZE_KIB: u16 = 640;
173/// Extended BIOS data area segment written by [`initialise_bda`].
174pub const EBDA_SEGMENT: u16 = 0x9FC0;
175/// Video mode installed by [`initialise_bda`] (80x25 colour text).
176pub const DEFAULT_VIDEO_MODE: u8 = 3;
177/// Text columns installed in the BDA.
178pub const DEFAULT_COLUMNS: u16 = 80;
179/// CRTC I/O port base installed in the BDA.
180pub const DEFAULT_CRTC_PORT: u16 = 0x03D4;
181/// Text rows minus one installed in the BDA.
182pub const DEFAULT_ROWS_MINUS_ONE: u8 = 24;
183/// Character height, in scan lines, installed in the BDA.
184pub const DEFAULT_CHAR_HEIGHT: u8 = 16;
185/// Active display page installed in the BDA.
186pub const DEFAULT_PAGE: u8 = 0;
187/// Attribute used by text services that do not take one from the caller.
188pub const DEFAULT_ATTRIBUTE: u8 = 0x07;
189/// Character written to blank cells.
190pub const SPACE: u8 = 0x20;
191/// Maximum number of keys the model queues.
192pub const KEY_BUFFER_CAPACITY: usize = 16;
193/// Size of the BDA-visible keyboard ring, in bytes.
194pub const KEY_BUFFER_BYTES: u16 = 32;
195/// First slot offset of the BDA keyboard ring.
196///
197/// The BDA head/tail words (`0x41A`/`0x41C`) hold offsets relative to the BDA
198/// base, so the first entry of the ring sits at `0x41E` and the values wrap
199/// inside `0x1E..=0x3E`, exactly as a PC firmware leaves them.
200pub const KEY_BUFFER_FIRST_OFFSET: u16 = 0x1E;
201/// Guest-physical base of the BDA keyboard ring entries.
202pub const BDA_KEY_BUFFER: u32 = 0x041E;
203
204/// Guest-physical base of text-mode video memory.
205pub const VIDEO_BASE: u32 = 0xB8000;
206/// Size of the video window cleared when a mode is set.
207pub const VIDEO_LEN: u32 = 0x8000;
208/// Text columns of the modelled screen.
209pub const TEXT_COLUMNS: u8 = 80;
210/// Text rows of the modelled screen.
211pub const TEXT_ROWS: u8 = 25;
212
213/// `FLAGS` bit 0: carry.
214pub const FLAG_CARRY: u16 = 1 << 0;
215/// `FLAGS` bit 6: zero.
216pub const FLAG_ZERO: u16 = 1 << 6;
217
218/// Success status (`CF=0`).
219pub const STATUS_OK: u8 = 0x00;
220/// Invalid function or invalid parameter status.
221pub const STATUS_INVALID_FUNCTION: u8 = 0x01;
222/// Unsupported system function status (`INT 15h`).
223pub const STATUS_NOT_SUPPORTED: u8 = 0x86;
224
225/// Disk status: success.
226pub const DISK_STATUS_OK: u8 = 0x00;
227/// Disk status: invalid function or invalid address packet.
228pub const DISK_STATUS_INVALID_FUNCTION: u8 = 0x01;
229/// Disk status: the synthetic disk is read-only.
230pub const DISK_STATUS_WRITE_PROTECTED: u8 = 0x03;
231/// Disk status: bad CHS/LBA, backend error, or unmapped guest buffer.
232pub const DISK_STATUS_SECTOR_NOT_FOUND: u8 = 0x04;
233/// Disk status: unsupported drive number.
234pub const DISK_STATUS_MEDIA_NOT_FOUND: u8 = 0x0C;
235/// Floppy drive number.
236pub const FLOPPY_DRIVE: u8 = 0x00;
237/// Fixed-disk drive number.
238pub const HARD_DISK_DRIVE: u8 = 0x80;
239/// Signature returned by the disk extensions presence check.
240pub const EXTENSIONS_SIGNATURE: u16 = 0xAA55;
241/// Required size of an extended disk address packet.
242pub const DAP_SIZE: u8 = 16;
243/// Status reported by the printer service: selected and ready.
244pub const PRINTER_STATUS: u8 = 0x30;
245
246/// Total number of sectors of a 1.44 MiB floppy.
247pub const FLOPPY_TOTAL_SECTORS: u64 = 2880;
248/// Size of one disk sector, in bytes.
249pub const SECTOR_SIZE: usize = 512;
250/// Floppy geometry installed by [`BiosState::new`]: 80 x 2 x 18 x 512.
251pub const FLOPPY_1440: DiskGeometry = DiskGeometry {
252 cylinders: 80,
253 heads: 2,
254 sectors_per_track: 18,
255 sector_size: 512,
256};
257/// Fixed-disk-ish geometry for images larger than a floppy: 1024 x 16 x 63 x
258/// 512 (about 504 MiB, 1,032,192 sectors).
259pub const HARD_DISK_GEOMETRY: DiskGeometry = DiskGeometry {
260 cylinders: 1024,
261 heads: 16,
262 sectors_per_track: 63,
263 sector_size: 512,
264};
265
266/// Guest register file visible to one BIOS call.
267///
268/// The fields mirror the 16-bit real-mode register set. [`gpr`] and
269/// [`set_gpr`] use the x86 encoding order so the kernel adapter can move the
270/// eight general-purpose registers without a lookup table of its own.
271#[derive(Debug, Clone, Copy, PartialEq, Eq)]
272pub struct BiosRegisters {
273 /// Accumulator.
274 pub ax: u16,
275 /// Base.
276 pub bx: u16,
277 /// Counter.
278 pub cx: u16,
279 /// Data.
280 pub dx: u16,
281 /// Source index.
282 pub si: u16,
283 /// Destination index.
284 pub di: u16,
285 /// Base pointer.
286 pub bp: u16,
287 /// Stack pointer.
288 pub sp: u16,
289 /// Data segment.
290 pub ds: u16,
291 /// Extra segment.
292 pub es: u16,
293 /// Stack segment.
294 pub ss: u16,
295 /// Code segment.
296 pub cs: u16,
297 /// Instruction pointer.
298 pub ip: u16,
299 /// Flags word; only `CF` and `ZF` are interpreted by this module.
300 pub flags: u16,
301}
302
303impl BiosRegisters {
304 /// Creates a zeroed register file.
305 pub const fn new() -> Self {
306 Self {
307 ax: 0,
308 bx: 0,
309 cx: 0,
310 dx: 0,
311 si: 0,
312 di: 0,
313 bp: 0,
314 sp: 0,
315 ds: 0,
316 es: 0,
317 ss: 0,
318 cs: 0,
319 ip: 0,
320 flags: 0,
321 }
322 }
323
324 /// Returns a general-purpose register in x86 encoding order.
325 ///
326 /// `0=ax`, `1=cx`, `2=dx`, `3=bx`, `4=sp`, `5=bp`, `6=si`, `7=di`.
327 /// Encodings 8..=15 (and anything above) read as zero.
328 pub fn gpr(&self, register: u8) -> u16 {
329 match register {
330 0 => self.ax,
331 1 => self.cx,
332 2 => self.dx,
333 3 => self.bx,
334 4 => self.sp,
335 5 => self.bp,
336 6 => self.si,
337 7 => self.di,
338 _ => 0,
339 }
340 }
341
342 /// Writes a general-purpose register in x86 encoding order.
343 ///
344 /// Encodings 8..=15 (and anything above) are ignored.
345 pub fn set_gpr(&mut self, register: u8, value: u16) {
346 match register {
347 0 => self.ax = value,
348 1 => self.cx = value,
349 2 => self.dx = value,
350 3 => self.bx = value,
351 4 => self.sp = value,
352 5 => self.bp = value,
353 6 => self.si = value,
354 7 => self.di = value,
355 _ => {}
356 }
357 }
358
359 /// True when the carry flag is set in [`BiosRegisters::flags`].
360 pub const fn carry(&self) -> bool {
361 self.flags & FLAG_CARRY != 0
362 }
363
364 /// Sets or clears the carry flag in [`BiosRegisters::flags`].
365 pub fn set_carry(&mut self, value: bool) {
366 if value {
367 self.flags |= FLAG_CARRY;
368 } else {
369 self.flags &= !FLAG_CARRY;
370 }
371 }
372
373 /// True when the zero flag is set in [`BiosRegisters::flags`].
374 pub const fn zero(&self) -> bool {
375 self.flags & FLAG_ZERO != 0
376 }
377
378 /// Sets or clears the zero flag in [`BiosRegisters::flags`].
379 pub fn set_zero(&mut self, value: bool) {
380 if value {
381 self.flags |= FLAG_ZERO;
382 } else {
383 self.flags &= !FLAG_ZERO;
384 }
385 }
386}
387
388impl Default for BiosRegisters {
389 fn default() -> Self {
390 Self::new()
391 }
392}
393
394/// Guest memory access used by the service model.
395///
396/// Addresses are guest-physical (linear) addresses. Every method is
397/// bounds-checked by the adapter: an unmapped or out-of-range access returns
398/// `None`/`false` and never panics.
399pub trait BiosMemory {
400 /// Reads one byte. Returns `None` when the address is not readable.
401 fn read_u8(&mut self, linear: u32) -> Option<u8>;
402
403 /// Writes one byte. Returns `false` when the address is not writable.
404 fn write_u8(&mut self, linear: u32, value: u8) -> bool;
405
406 /// Reads `out.len()` bytes. Returns `false` when the range is not readable.
407 fn read(&mut self, linear: u32, out: &mut [u8]) -> bool;
408
409 /// Writes `bytes`. Returns `false` when the range is not writable.
410 fn write(&mut self, linear: u32, bytes: &[u8]) -> bool;
411}
412
413/// Synthetic block-device access used by `INT 13h`.
414///
415/// Sector numbers are linear block addresses. A read-only medium (the default)
416/// keeps `INT 13h AH=03`/`AH=43h` reporting write-protected; a backend that can
417/// persist writes overrides [`BiosDisk::write_sector`].
418pub trait BiosDisk {
419 /// Number of 512-byte sectors available.
420 fn sectors(&self) -> u64;
421
422 /// Reads one sector into `out`. Returns `false` on a backend error.
423 fn read_sector(&mut self, sector: u64, out: &mut [u8; 512]) -> bool;
424
425 /// Writes one sector from `data`.
426 ///
427 /// The default implementation reports a read-only medium.
428 fn write_sector(&mut self, sector: u64, data: &[u8; 512]) -> bool {
429 let _ = (sector, data);
430 false
431 }
432}
433
434/// CHS geometry used to decode and report disk addresses.
435#[derive(Debug, Clone, Copy, PartialEq, Eq)]
436pub struct DiskGeometry {
437 /// Number of cylinders.
438 pub cylinders: u16,
439 /// Number of heads.
440 pub heads: u8,
441 /// Sectors per track (one-based sectors).
442 pub sectors_per_track: u8,
443 /// Bytes per sector.
444 pub sector_size: u16,
445}
446
447impl DiskGeometry {
448 /// Converts a one-based CHS address to a linear block address.
449 ///
450 /// Returns `None` when the cylinder, head or sector is outside the
451 /// geometry. A sector of zero is invalid.
452 pub fn lba(&self, cyl: u16, head: u8, sector: u8) -> Option<u64> {
453 if cyl >= self.cylinders
454 || head >= self.heads
455 || sector == 0
456 || sector > self.sectors_per_track
457 {
458 return None;
459 }
460 Some(
461 (cyl as u64 * self.heads as u64 + head as u64) * self.sectors_per_track as u64
462 + sector as u64
463 - 1,
464 )
465 }
466
467 /// Selects a geometry from an image sector count.
468 ///
469 /// Images of at most [`FLOPPY_TOTAL_SECTORS`] sectors get [`FLOPPY_1440`];
470 /// larger images get [`HARD_DISK_GEOMETRY`] (1024 x 16 x 63 x 512).
471 pub const fn from_sectors(sectors: u64) -> Self {
472 if sectors <= FLOPPY_TOTAL_SECTORS {
473 FLOPPY_1440
474 } else {
475 HARD_DISK_GEOMETRY
476 }
477 }
478}
479
480/// Result of dispatching one interrupt vector.
481#[derive(Debug, Clone, Copy, PartialEq, Eq)]
482pub enum BiosOutcome {
483 /// The model serviced the call; the scratch byte carries `CF`/`ZF`.
484 Handled,
485 /// No service is installed: the guest owns this vector. The scratch byte
486 /// is still written, with `CF=0` and `ZF=0`.
487 Unknown,
488}
489
490/// Architectural state of the BIOS service model.
491///
492/// The state is deliberately small: cursor, mode, tick counter, keyboard queue,
493/// disk geometry and a frozen RTC time. The kernel adapter owns the guest
494/// memory image and the backing disk; [`BiosState::handle`] only mutates the
495/// state and the memory/disk it is given.
496#[derive(Debug)]
497pub struct BiosState {
498 /// Cursor row, 0..=24.
499 pub cursor_row: u8,
500 /// Cursor column, 0..=79.
501 pub cursor_col: u8,
502 /// Current video mode (3 or 7).
503 pub video_mode: u8,
504 /// Timer tick counter (nominally 18.2 Hz).
505 pub ticks: u32,
506 /// Keys waiting for `INT 16h`, oldest first.
507 /// Queued (scan code, ASCII) pairs, the layout INT 16h returns.
508 ///
509 /// A printable key carries its ASCII byte with a zero scan code until a
510 /// guest handler fills the BDA ring; an extended key (arrows, Home/End)
511 /// carries the scan code with a zero ASCII byte, which is exactly what a
512 /// PC keyboard buffer holds.
513 pub keyboard: VecDeque<(u8, u8)>,
514 /// CHS geometry reported to the guest.
515 pub disk: DiskGeometry,
516 /// RTC hour, binary, 0..=23 by convention.
517 pub rtc_hour: u8,
518 /// RTC minute, binary, 0..=59 by convention.
519 pub rtc_minute: u8,
520 /// RTC second, binary, 0..=59 by convention.
521 pub rtc_second: u8,
522}
523
524impl BiosState {
525 /// Creates the reset state: mode 3, cursor at home, floppy geometry, empty
526 /// keyboard queue and a midnight RTC.
527 pub fn new() -> Self {
528 Self {
529 cursor_row: 0,
530 cursor_col: 0,
531 video_mode: DEFAULT_VIDEO_MODE,
532 ticks: 0,
533 keyboard: VecDeque::new(),
534 disk: FLOPPY_1440,
535 rtc_hour: 0,
536 rtc_minute: 0,
537 rtc_second: 0,
538 }
539 }
540
541 /// Queues one ASCII key for `INT 16h`.
542 ///
543 /// The queue is bounded by [`KEY_BUFFER_CAPACITY`]; keys arriving when it
544 /// is full are dropped, like a real keyboard controller overrun.
545 pub fn push_key(&mut self, ascii: u8) {
546 self.push_scan_key(0, ascii);
547 }
548
549 /// Queues the `(scan code, ASCII)` pair `INT 16h` returns.
550 ///
551 /// A guest `INT 9` handler stores this pair in the BDA ring, so the runner
552 /// feeds extended keys (arrows, Home/End) through the same bounded queue:
553 /// they carry the scan code and a zero ASCII byte.
554 pub fn push_scan_key(&mut self, scan: u8, ascii: u8) {
555 if self.keyboard.len() < KEY_BUFFER_CAPACITY {
556 self.keyboard.push_back((scan, ascii));
557 }
558 }
559
560 /// Advances the 18.2 Hz tick counter (wrapping).
561 pub fn advance_ticks(&mut self, ticks: u32) {
562 self.ticks = self.ticks.wrapping_add(ticks);
563 }
564
565 /// Services one BIOS interrupt.
566 ///
567 /// `vector` is the interrupt number, `regs` the guest register file (read
568 /// for arguments and updated with results), `mem` the guest memory image
569 /// and `disk` the synthetic block device. The scratch byte is written on
570 /// every path; the BDA is refreshed on every handled path.
571 pub fn handle(
572 &mut self,
573 vector: u8,
574 regs: &mut BiosRegisters,
575 mem: &mut impl BiosMemory,
576 disk: &mut dyn BiosDisk,
577 ) -> BiosOutcome {
578 let completion = match vector {
579 0x05 => Some(Completion::OK),
580 0x08 | 0x1C => None,
581 0x10 => Some(self.video_service(regs, mem)),
582 0x11 => {
583 regs.ax = EQUIPMENT_WORD;
584 Some(Completion::OK)
585 }
586 0x12 => {
587 regs.ax = MEMORY_SIZE_KIB;
588 Some(Completion::OK)
589 }
590 0x13 => Some(self.disk_service(regs, mem, disk)),
591 0x15 => Some(self.system_service(regs)),
592 0x16 => Some(self.keyboard_service(regs, mem)),
593 0x17 => Some(self.printer_service(regs)),
594 0x1A => Some(self.time_service(regs)),
595 _ => None,
596 };
597 match completion {
598 Some(completion) => {
599 self.sync_bda(mem);
600 // The scratch byte is the authoritative return path, but the
601 // flags are mirrored into the register file too so adapters
602 // that publish the scratch byte from the returned registers
603 // observe the same values.
604 regs.set_carry(completion.carry);
605 regs.set_zero(completion.zero);
606 let mut scratch = 0u8;
607 if completion.carry {
608 scratch |= SCRATCH_CF;
609 }
610 if completion.zero {
611 scratch |= SCRATCH_ZF;
612 }
613 let _ = mem.write_u8(SCRATCH_GPA, scratch);
614 BiosOutcome::Handled
615 }
616 None => {
617 let _ = mem.write_u8(SCRATCH_GPA, 0);
618 BiosOutcome::Unknown
619 }
620 }
621 }
622
623 /// Republishes the BDA fields owned by the model.
624 fn sync_bda(&self, mem: &mut impl BiosMemory) {
625 let _ = mem.write_u8(BDA_VIDEO_MODE, self.video_mode);
626 let _ = write_u16(
627 mem,
628 BDA_CURSOR,
629 (self.cursor_row as u16) << 8 | self.cursor_col as u16,
630 );
631 let _ = write_u32(mem, BDA_TICK_COUNT, self.ticks);
632 // The keyboard ring (head/tail at 0x41A/0x41C, entries at 0x41E) is
633 // maintained by whoever owns the keyboard: once the guest installs its
634 // own `INT 9` handler, DOS fills it and the firmware `INT 16h` service
635 // consumes it. Republishing it from the model queue here would reset
636 // the ring on every unrelated BIOS call (every INT 10h/INT 13h).
637 }
638
639 /// Clamps and stores the text cursor.
640 fn set_cursor(&mut self, row: u8, col: u8) {
641 self.cursor_row = row.min(TEXT_ROWS - 1);
642 self.cursor_col = col.min(TEXT_COLUMNS - 1);
643 }
644
645 /// Sets up one text mode and clears the video window.
646 fn set_video_mode(&mut self, mode: u8, mem: &mut impl BiosMemory) {
647 self.video_mode = mode;
648 self.cursor_row = 0;
649 self.cursor_col = 0;
650 let mut address = VIDEO_BASE;
651 let end = VIDEO_BASE + VIDEO_LEN;
652 while address < end {
653 let _ = mem.write_u8(address, SPACE);
654 let _ = mem.write_u8(address + 1, DEFAULT_ATTRIBUTE);
655 address += 2;
656 }
657 let _ = write_u16(mem, BDA_COLUMNS, DEFAULT_COLUMNS);
658 let _ = mem.write_u8(BDA_ROWS, DEFAULT_ROWS_MINUS_ONE);
659 let _ = mem.write_u8(BDA_CHAR_HEIGHT, DEFAULT_CHAR_HEIGHT);
660 }
661
662 /// `INT 10h`: video services.
663 fn video_service(&mut self, regs: &mut BiosRegisters, mem: &mut impl BiosMemory) -> Completion {
664 match (regs.ax >> 8) as u8 {
665 0x00 => {
666 let mode = regs.ax as u8;
667 if mode == 3 || mode == 7 {
668 self.set_video_mode(mode, mem);
669 set_ah(regs, STATUS_OK);
670 Completion::OK
671 } else {
672 fail_ah(regs, STATUS_INVALID_FUNCTION)
673 }
674 }
675 0x01 => {
676 // Cursor shape is accepted but not stored: the model reports a
677 // fixed 0x0607 shape through AH=03.
678 Completion::OK
679 }
680 0x02 => {
681 self.set_cursor((regs.dx >> 8) as u8, regs.dx as u8);
682 Completion::OK
683 }
684 0x03 => {
685 let row = self.cursor_row;
686 let col = self.cursor_col;
687 regs.cx = 0x0607;
688 regs.dx = (row as u16) << 8 | col as u16;
689 Completion::OK
690 }
691 0x05 => {
692 if regs.ax as u8 == DEFAULT_PAGE {
693 let _ = mem.write_u8(BDA_PAGE, DEFAULT_PAGE);
694 Completion::OK
695 } else {
696 fail_ah(regs, STATUS_INVALID_FUNCTION)
697 }
698 }
699 0x06 | 0x07 => {
700 let up = (regs.ax >> 8) as u8 == 0x06;
701 let lines = regs.ax as u8;
702 let attr = (regs.bx >> 8) as u8;
703 let top = ((regs.cx >> 8) as u8).min(TEXT_ROWS - 1);
704 let left = (regs.cx as u8).min(TEXT_COLUMNS - 1);
705 let bottom = ((regs.dx >> 8) as u8).min(TEXT_ROWS - 1);
706 let right = (regs.dx as u8).min(TEXT_COLUMNS - 1);
707 if top <= bottom && left <= right {
708 let _ = scroll_region(mem, up, lines, attr, top, left, bottom, right);
709 }
710 Completion::OK
711 }
712 0x08 => {
713 let (ch, attr) = read_cell(mem, self.cursor_row, self.cursor_col);
714 regs.ax = (attr as u16) << 8 | ch as u16;
715 Completion::OK
716 }
717 0x09 => {
718 self.write_repeated(regs.ax as u8, regs.cx, Some(regs.bx as u8), mem);
719 Completion::OK
720 }
721 0x0A => {
722 self.write_repeated(regs.ax as u8, regs.cx, None, mem);
723 Completion::OK
724 }
725 0x0E => {
726 self.teletype(regs.ax as u8, mem);
727 Completion::OK
728 }
729 0x0F => {
730 regs.ax = (DEFAULT_COLUMNS << 8) | self.video_mode as u16;
731 Completion::OK
732 }
733 0x13 => self.write_string(regs, mem),
734 _ => fail_ah(regs, STATUS_INVALID_FUNCTION),
735 }
736 }
737
738 /// Writes `count` copies of `ch` at the cursor, optionally keeping the
739 /// existing attribute (`attr` is `None`). The cursor does not move; cells
740 /// are filled across rows up to the end of the screen.
741 fn write_repeated(&self, ch: u8, count: u16, attr: Option<u8>, mem: &mut impl BiosMemory) {
742 let total = TEXT_COLUMNS as u32 * TEXT_ROWS as u32;
743 let mut index = self.cursor_row as u32 * TEXT_COLUMNS as u32 + self.cursor_col as u32;
744 for _ in 0..count {
745 if index >= total {
746 break;
747 }
748 let row = (index / TEXT_COLUMNS as u32) as u8;
749 let col = (index % TEXT_COLUMNS as u32) as u8;
750 let attribute = match attr {
751 Some(value) => value,
752 None => read_cell(mem, row, col).1,
753 };
754 let _ = write_cell(mem, row, col, ch, attribute);
755 index += 1;
756 }
757 }
758
759 /// `INT 10h AH=0Eh`: teletype output.
760 fn teletype(&mut self, ch: u8, mem: &mut impl BiosMemory) {
761 match ch {
762 0x07 => {}
763 0x08 => {
764 if self.cursor_col > 0 {
765 self.cursor_col -= 1;
766 } else if self.cursor_row > 0 {
767 self.cursor_row -= 1;
768 self.cursor_col = TEXT_COLUMNS - 1;
769 }
770 }
771 0x09 => {
772 let next = (self.cursor_col / 8 + 1) * 8;
773 if next < TEXT_COLUMNS {
774 self.cursor_col = next;
775 } else {
776 self.cursor_col = 0;
777 self.newline(mem);
778 }
779 }
780 0x0A => self.newline(mem),
781 0x0D => self.cursor_col = 0,
782 _ => {
783 let _ = write_cell(mem, self.cursor_row, self.cursor_col, ch, DEFAULT_ATTRIBUTE);
784 self.cursor_col += 1;
785 if self.cursor_col >= TEXT_COLUMNS {
786 self.cursor_col = 0;
787 self.newline(mem);
788 }
789 }
790 }
791 }
792
793 /// Moves to the next teletype line, scrolling when already on the last one.
794 fn newline(&mut self, mem: &mut impl BiosMemory) {
795 if self.cursor_row + 1 < TEXT_ROWS {
796 self.cursor_row += 1;
797 } else {
798 let _ = scroll_region(
799 mem,
800 true,
801 1,
802 DEFAULT_ATTRIBUTE,
803 0,
804 0,
805 TEXT_ROWS - 1,
806 TEXT_COLUMNS - 1,
807 );
808 }
809 }
810
811 /// `INT 10h AH=13h`: writes a counted string with optional attribute pairs.
812 fn write_string(&mut self, regs: &mut BiosRegisters, mem: &mut impl BiosMemory) -> Completion {
813 let length = regs.cx as usize;
814 let mode = regs.ax as u8;
815 let default_attr = regs.bx as u8;
816 let base = linear_address(regs.es, regs.bp);
817 let with_attributes = mode & 0x02 != 0;
818 let update_cursor = mode & 0x01 != 0;
819 let stride = if with_attributes { 2 } else { 1 };
820 let mut row = ((regs.dx >> 8) as u8).min(TEXT_ROWS - 1);
821 let mut col = (regs.dx as u8).min(TEXT_COLUMNS - 1);
822 for index in 0..length {
823 let address = base.saturating_add((index * stride) as u32);
824 let Some(ch) = mem.read_u8(address) else {
825 break;
826 };
827 let attribute = if with_attributes {
828 mem.read_u8(address + 1).unwrap_or(default_attr)
829 } else {
830 default_attr
831 };
832 if !write_cell(mem, row, col, ch, attribute) {
833 break;
834 }
835 col += 1;
836 if col >= TEXT_COLUMNS {
837 col = 0;
838 if row + 1 >= TEXT_ROWS {
839 row = TEXT_ROWS - 1;
840 col = TEXT_COLUMNS - 1;
841 break;
842 }
843 row += 1;
844 }
845 }
846 if update_cursor {
847 self.set_cursor(row, col);
848 }
849 Completion::OK
850 }
851
852 /// `INT 13h`: disk services.
853 fn disk_service(
854 &mut self,
855 regs: &mut BiosRegisters,
856 mem: &mut impl BiosMemory,
857 disk: &mut dyn BiosDisk,
858 ) -> Completion {
859 match (regs.ax >> 8) as u8 {
860 0x00 => {
861 set_ah(regs, DISK_STATUS_OK);
862 Completion::OK
863 }
864 0x01 => {
865 set_ah(regs, DISK_STATUS_OK);
866 Completion::OK
867 }
868 0x02 => {
869 let Some(_hard) = drive_kind(regs.dx as u8) else {
870 return fail_ah(regs, DISK_STATUS_MEDIA_NOT_FOUND);
871 };
872 let count = (regs.ax & 0xFF) as u64;
873 let sector = (regs.cx & 0x3F) as u8;
874 let cyl = ((regs.cx >> 8) & 0xFF) | (((regs.cx >> 6) & 0x03) << 8);
875 let head = (regs.dx >> 8) as u8;
876 let Some(lba) = self.disk.lba(cyl, head, sector) else {
877 return fail_ah(regs, DISK_STATUS_SECTOR_NOT_FOUND);
878 };
879 let buffer = linear_address(regs.es, regs.bx);
880 match read_sectors(mem, disk, lba, count, buffer) {
881 Ok(()) => {
882 set_ah(regs, DISK_STATUS_OK);
883 Completion::OK
884 }
885 Err(status) => fail_ah(regs, status),
886 }
887 }
888 0x03 => {
889 let Some(_hard) = drive_kind(regs.dx as u8) else {
890 return fail_ah(regs, DISK_STATUS_MEDIA_NOT_FOUND);
891 };
892 let count = (regs.ax & 0xFF) as u64;
893 let sector = (regs.cx & 0x3F) as u8;
894 let cyl = ((regs.cx >> 8) & 0xFF) | (((regs.cx >> 6) & 0x03) << 8);
895 let head = (regs.dx >> 8) as u8;
896 let Some(lba) = self.disk.lba(cyl, head, sector) else {
897 return fail_ah(regs, DISK_STATUS_SECTOR_NOT_FOUND);
898 };
899 let buffer = linear_address(regs.es, regs.bx);
900 match write_sectors(mem, disk, lba, count, buffer) {
901 Ok(()) => {
902 set_ah(regs, DISK_STATUS_OK);
903 Completion::OK
904 }
905 Err(status) => fail_ah(regs, status),
906 }
907 }
908 0x04 => {
909 // Verify sectors: the track and sector addresses must exist on
910 // the medium, but there is no data transfer. DOS issues this
911 // after every write when verification is on, and formatters use
912 // it to validate the volume they just created.
913 let Some(_hard) = drive_kind(regs.dx as u8) else {
914 return fail_ah(regs, DISK_STATUS_MEDIA_NOT_FOUND);
915 };
916 let count = (regs.ax & 0xFF) as u64;
917 let sector = (regs.cx & 0x3F) as u8;
918 let cyl = ((regs.cx >> 8) & 0xFF) | (((regs.cx >> 6) & 0x03) << 8);
919 let head = (regs.dx >> 8) as u8;
920 let Some(lba) = self.disk.lba(cyl, head, sector) else {
921 return fail_ah(regs, DISK_STATUS_SECTOR_NOT_FOUND);
922 };
923 match verify_sectors(disk, lba, count) {
924 Ok(()) => {
925 set_ah(regs, DISK_STATUS_OK);
926 Completion::OK
927 }
928 Err(status) => fail_ah(regs, status),
929 }
930 }
931 0x05 => {
932 let Some(_hard) = drive_kind(regs.dx as u8) else {
933 return fail_ah(regs, DISK_STATUS_MEDIA_NOT_FOUND);
934 };
935 let count = u64::from(regs.ax & 0xFF);
936 let table = linear_address(regs.es, regs.bx);
937 match self.format_track(mem, disk, count, table) {
938 Ok(()) => {
939 set_ah(regs, DISK_STATUS_OK);
940 Completion::OK
941 }
942 Err(status) => fail_ah(regs, status),
943 }
944 }
945 0x09 | 0x0C | 0x0D | 0x0E | 0x0F => {
946 // Initialise, seek, reset and sector-buffer services: the
947 // synthetic controller is always ready and has no seek latency.
948 set_ah(regs, DISK_STATUS_OK);
949 Completion::OK
950 }
951 0x08 => {
952 let Some(hard) = drive_kind(regs.dx as u8) else {
953 return fail_ah(regs, DISK_STATUS_MEDIA_NOT_FOUND);
954 };
955 let cylinders = self.disk.cylinders.saturating_sub(1);
956 let heads = self.disk.heads.saturating_sub(1);
957 regs.cx = ((cylinders & 0xFF) << 8)
958 | (self.disk.sectors_per_track as u16 & 0x3F)
959 | (((cylinders >> 8) & 0x03) << 6);
960 // DL is the number of drives of the requested class, not the
961 // AH=15h type code: one modelled drive per class. A larger
962 // count makes DOS probe absent drives (0x81, 0x82, ...).
963 regs.dx = (heads as u16) << 8 | 1;
964 // BL: CMOS drive type for floppies (4 = 1.44 MB), 0 for disks.
965 regs.bx = (regs.bx & 0xFF00) | if hard { 0 } else { 4 };
966 regs.es = 0;
967 regs.di = 0;
968 set_ah(regs, DISK_STATUS_OK);
969 Completion::OK
970 }
971 0x15 => {
972 let Some(hard) = drive_kind(regs.dx as u8) else {
973 return fail_ah(regs, DISK_STATUS_MEDIA_NOT_FOUND);
974 };
975 set_ah(regs, if hard { 3 } else { 2 });
976 Completion::OK
977 }
978 0x16 => {
979 // Detect disk change. The modelled medium never changes
980 // underneath the guest, so a known drive reports "no change"
981 // instead of the "general failure" DOS shows for an
982 // unsupported service on removable media.
983 let Some(_hard) = drive_kind(regs.dx as u8) else {
984 return fail_ah(regs, DISK_STATUS_MEDIA_NOT_FOUND);
985 };
986 regs.ax &= 0xFF00;
987 set_ah(regs, DISK_STATUS_OK);
988 Completion::OK
989 }
990 0x17 => {
991 // Set DASD type. The medium type is fixed by the modelled drive
992 // (1.44 MB floppy), so the request is accepted as a no-op; DOS
993 // uses it before formatting a fixed disk.
994 let Some(_hard) = drive_kind(regs.dx as u8) else {
995 return fail_ah(regs, DISK_STATUS_MEDIA_NOT_FOUND);
996 };
997 set_ah(regs, DISK_STATUS_OK);
998 Completion::OK
999 }
1000 0x41 => {
1001 regs.bx = EXTENSIONS_SIGNATURE;
1002 set_ah(regs, DISK_STATUS_OK);
1003 Completion::OK
1004 }
1005 0x42 => {
1006 let dap = linear_address(regs.ds, regs.si);
1007 let Some(size) = mem.read_u8(dap) else {
1008 return fail_ah(regs, DISK_STATUS_INVALID_FUNCTION);
1009 };
1010 if size != DAP_SIZE {
1011 return fail_ah(regs, DISK_STATUS_INVALID_FUNCTION);
1012 }
1013 let Some(count) = read_u16(mem, dap + 2) else {
1014 return fail_ah(regs, DISK_STATUS_INVALID_FUNCTION);
1015 };
1016 let Some(offset) = read_u16(mem, dap + 4) else {
1017 return fail_ah(regs, DISK_STATUS_INVALID_FUNCTION);
1018 };
1019 let Some(segment) = read_u16(mem, dap + 6) else {
1020 return fail_ah(regs, DISK_STATUS_INVALID_FUNCTION);
1021 };
1022 let Some(lba) = read_u64(mem, dap + 8) else {
1023 return fail_ah(regs, DISK_STATUS_INVALID_FUNCTION);
1024 };
1025 let buffer = linear_address(segment, offset);
1026 match read_sectors(mem, disk, lba, u64::from(count), buffer) {
1027 Ok(()) => {
1028 set_ah(regs, DISK_STATUS_OK);
1029 Completion::OK
1030 }
1031 Err(status) => fail_ah(regs, status),
1032 }
1033 }
1034 0x43 => {
1035 let dap = linear_address(regs.ds, regs.si);
1036 let Some(size) = mem.read_u8(dap) else {
1037 return fail_ah(regs, DISK_STATUS_INVALID_FUNCTION);
1038 };
1039 if size != DAP_SIZE {
1040 return fail_ah(regs, DISK_STATUS_INVALID_FUNCTION);
1041 }
1042 let Some(count) = read_u16(mem, dap + 2) else {
1043 return fail_ah(regs, DISK_STATUS_INVALID_FUNCTION);
1044 };
1045 let Some(offset) = read_u16(mem, dap + 4) else {
1046 return fail_ah(regs, DISK_STATUS_INVALID_FUNCTION);
1047 };
1048 let Some(segment) = read_u16(mem, dap + 6) else {
1049 return fail_ah(regs, DISK_STATUS_INVALID_FUNCTION);
1050 };
1051 let Some(lba) = read_u64(mem, dap + 8) else {
1052 return fail_ah(regs, DISK_STATUS_INVALID_FUNCTION);
1053 };
1054 let buffer = linear_address(segment, offset);
1055 match write_sectors(mem, disk, lba, u64::from(count), buffer) {
1056 Ok(()) => {
1057 set_ah(regs, DISK_STATUS_OK);
1058 Completion::OK
1059 }
1060 Err(status) => fail_ah(regs, status),
1061 }
1062 }
1063 _ => fail_ah(regs, DISK_STATUS_INVALID_FUNCTION),
1064 }
1065 }
1066
1067 /// `INT 13h AH=05h`: formats a track.
1068 ///
1069 /// `table` points at the classic four-byte record per sector (cylinder,
1070 /// head, sector, size code). Every described sector is zero-filled through
1071 /// the block backend, which is the state a freshly formatted FAT volume
1072 /// expects. A read-only backend fails with the write-protected status.
1073 fn format_track(
1074 &self,
1075 mem: &mut impl BiosMemory,
1076 disk: &mut dyn BiosDisk,
1077 count: u64,
1078 table: u32,
1079 ) -> Result<(), u8> {
1080 let zero = [0u8; SECTOR_SIZE];
1081 for index in 0..count {
1082 let entry = table + (index as u32) * 4;
1083 let cyl = u16::from(mem.read_u8(entry).ok_or(DISK_STATUS_SECTOR_NOT_FOUND)?);
1084 let head = mem.read_u8(entry + 1).ok_or(DISK_STATUS_SECTOR_NOT_FOUND)?;
1085 let sector = mem.read_u8(entry + 2).ok_or(DISK_STATUS_SECTOR_NOT_FOUND)?;
1086 let Some(lba) = self.disk.lba(cyl, head, sector) else {
1087 return Err(DISK_STATUS_SECTOR_NOT_FOUND);
1088 };
1089 if lba >= disk.sectors() {
1090 return Err(DISK_STATUS_SECTOR_NOT_FOUND);
1091 }
1092 if !disk.write_sector(lba, &zero) {
1093 return Err(DISK_STATUS_WRITE_PROTECTED);
1094 }
1095 }
1096 Ok(())
1097 }
1098
1099 /// `INT 15h`: system services.
1100 fn system_service(&mut self, regs: &mut BiosRegisters) -> Completion {
1101 match (regs.ax >> 8) as u8 {
1102 0x88 => {
1103 // No extended memory above 1 MiB in this model.
1104 regs.ax = 0;
1105 Completion::OK
1106 }
1107 _ => fail_ah(regs, STATUS_NOT_SUPPORTED),
1108 }
1109 }
1110
1111 /// `INT 16h`: keyboard services.
1112 ///
1113 /// The ring at `0x41E` is the interface DOS uses: its own `INT 9` handler
1114 /// translates each scancode and stores it there (head/tail at
1115 /// `0x41A`/`0x41C`), and the firmware service is expected to consume it.
1116 /// The model queue is only a fallback for a guest that never installed its
1117 /// own handler (there the firmware is the only producer).
1118 fn keyboard_service(
1119 &mut self,
1120 regs: &mut BiosRegisters,
1121 mem: &mut impl BiosMemory,
1122 ) -> Completion {
1123 match (regs.ax >> 8) as u8 {
1124 0x00 => match self.take_key(mem, true) {
1125 Some((scan, ascii)) => {
1126 regs.ax = (u16::from(scan) << 8) | u16::from(ascii);
1127 Completion::with_zero(false)
1128 }
1129 None => {
1130 regs.ax = 0;
1131 Completion::with_zero(true)
1132 }
1133 },
1134 0x01 => match self.take_key(mem, false) {
1135 Some((scan, ascii)) => {
1136 regs.ax = (u16::from(scan) << 8) | u16::from(ascii);
1137 Completion::with_zero(false)
1138 }
1139 None => {
1140 regs.ax = 0;
1141 Completion::with_zero(true)
1142 }
1143 },
1144 0x02 => {
1145 // Shift status lives in the BDA (`0x417`); the model keeps no
1146 // shift state, so report "no shift held".
1147 regs.ax &= 0xFF00;
1148 Completion::OK
1149 }
1150 _ => fail_ah(regs, STATUS_INVALID_FUNCTION),
1151 }
1152 }
1153
1154 /// Returns the next key from the guest ring, then from the model queue.
1155 ///
1156 /// `consume` advances the ring tail by one entry (two bytes) or pops the
1157 /// model queue; a peek reads without changing either.
1158 fn take_key(&mut self, mem: &mut impl BiosMemory, consume: bool) -> Option<(u8, u8)> {
1159 if let Some((head, tail)) = self.keyboard_ring(mem) {
1160 if head != tail {
1161 let offset = ring_offset(tail)?;
1162 let scan = mem.read_u8(BDA_KEY_BUFFER + u32::from(offset))?;
1163 let ascii = mem.read_u8(BDA_KEY_BUFFER + u32::from(offset) + 1)?;
1164 if consume {
1165 let next = KEY_BUFFER_FIRST_OFFSET + ((offset + 2) & (KEY_BUFFER_BYTES - 1));
1166 let _ = write_u16(mem, BDA_KEYBOARD_TAIL, next);
1167 }
1168 return Some((scan, ascii));
1169 }
1170 }
1171 if consume {
1172 self.keyboard.pop_front()
1173 } else {
1174 self.keyboard.front().copied()
1175 }
1176 }
1177
1178 /// Reads the guest keyboard ring head/tail words.
1179 fn keyboard_ring(&self, mem: &mut impl BiosMemory) -> Option<(u16, u16)> {
1180 let head = read_u16(mem, BDA_KEYBOARD_HEAD)?;
1181 let tail = read_u16(mem, BDA_KEYBOARD_TAIL)?;
1182 Some((head, tail))
1183 }
1184
1185 /// `INT 17h`: printer services (accepted, output discarded).
1186 fn printer_service(&mut self, regs: &mut BiosRegisters) -> Completion {
1187 match (regs.ax >> 8) as u8 {
1188 0x00 | 0x01 | 0x02 => {
1189 set_ah(regs, PRINTER_STATUS);
1190 Completion::OK
1191 }
1192 _ => fail_ah(regs, STATUS_INVALID_FUNCTION),
1193 }
1194 }
1195
1196 /// `INT 1Ah`: time services.
1197 fn time_service(&mut self, regs: &mut BiosRegisters) -> Completion {
1198 match (regs.ax >> 8) as u8 {
1199 0x00 => {
1200 regs.cx = (self.ticks >> 16) as u16;
1201 regs.dx = self.ticks as u16;
1202 regs.ax &= 0xFF00;
1203 Completion::OK
1204 }
1205 0x02 => {
1206 regs.cx = (bcd(self.rtc_hour) as u16) << 8 | bcd(self.rtc_minute) as u16;
1207 regs.dx = (bcd(self.rtc_second) as u16) << 8;
1208 Completion::OK
1209 }
1210 _ => fail_ah(regs, STATUS_INVALID_FUNCTION),
1211 }
1212 }
1213}
1214
1215impl Default for BiosState {
1216 fn default() -> Self {
1217 Self::new()
1218 }
1219}
1220
1221/// Outcome of one service handler: the pair of flags the scratch byte carries.
1222#[derive(Debug, Clone, Copy)]
1223struct Completion {
1224 carry: bool,
1225 zero: bool,
1226}
1227
1228impl Completion {
1229 /// `CF=0`, `ZF=0`.
1230 const OK: Self = Self {
1231 carry: false,
1232 zero: false,
1233 };
1234
1235 /// `CF=0`, `ZF=value`.
1236 const fn with_zero(value: bool) -> Self {
1237 Self {
1238 carry: false,
1239 zero: value,
1240 }
1241 }
1242}
1243
1244/// Writes `status` into `AH` and reports a failure.
1245fn fail_ah(regs: &mut BiosRegisters, status: u8) -> Completion {
1246 set_ah(regs, status);
1247 Completion {
1248 carry: true,
1249 zero: false,
1250 }
1251}
1252
1253/// Replaces `AH` without touching `AL`.
1254fn set_ah(regs: &mut BiosRegisters, value: u8) {
1255 regs.ax = (regs.ax & 0x00FF) | (u16::from(value) << 8);
1256}
1257
1258/// Accepts only the two documented drive numbers.
1259///
1260/// Returns `Some(true)` for the fixed disk, `Some(false)` for the floppy and
1261/// `None` for anything else.
1262fn drive_kind(drive: u8) -> Option<bool> {
1263 match drive {
1264 FLOPPY_DRIVE => Some(false),
1265 HARD_DISK_DRIVE => Some(true),
1266 _ => None,
1267 }
1268}
1269
1270/// Computes a real-mode linear address from a segment and an offset.
1271pub const fn linear_address(segment: u16, offset: u16) -> u32 {
1272 (segment as u32) * 16 + offset as u32
1273}
1274
1275/// Checks that `count` sectors starting at `lba` exist on the medium.
1276///
1277/// `INT 13h AH=04h` verifies addresses without transferring data: the synthetic
1278/// controller has no latent media errors, so an in-range request succeeds. DOS
1279/// issues it after each write when verification is enabled, and formatters use
1280/// it to check the volume they just created.
1281fn verify_sectors(disk: &mut dyn BiosDisk, lba: u64, count: u64) -> Result<(), u8> {
1282 let total = disk.sectors();
1283 for index in 0..count {
1284 let current = lba.checked_add(index).ok_or(DISK_STATUS_SECTOR_NOT_FOUND)?;
1285 if current >= total {
1286 return Err(DISK_STATUS_SECTOR_NOT_FOUND);
1287 }
1288 }
1289 Ok(())
1290}
1291
1292/// Reads one sector after another into a guest buffer.
1293///
1294/// Each byte is written through [`BiosMemory`], so a buffer that leaves mapped
1295/// memory aborts the transfer with [`DISK_STATUS_SECTOR_NOT_FOUND`] instead of
1296/// panicking. Bytes already written are not rolled back.
1297fn read_sectors(
1298 mem: &mut impl BiosMemory,
1299 disk: &mut dyn BiosDisk,
1300 lba: u64,
1301 count: u64,
1302 buffer: u32,
1303) -> Result<(), u8> {
1304 let mut sector = [0u8; SECTOR_SIZE];
1305 let total = disk.sectors();
1306 for index in 0..count {
1307 let current = lba.checked_add(index).ok_or(DISK_STATUS_SECTOR_NOT_FOUND)?;
1308 if current >= total || !disk.read_sector(current, &mut sector) {
1309 return Err(DISK_STATUS_SECTOR_NOT_FOUND);
1310 }
1311 let base = u64::from(buffer) + index * SECTOR_SIZE as u64;
1312 for (offset, byte) in sector.iter().enumerate() {
1313 let address = base + offset as u64;
1314 if address > u64::from(u32::MAX) {
1315 return Err(DISK_STATUS_SECTOR_NOT_FOUND);
1316 }
1317 if !mem.write_u8(address as u32, *byte) {
1318 return Err(DISK_STATUS_SECTOR_NOT_FOUND);
1319 }
1320 }
1321 }
1322 Ok(())
1323}
1324
1325/// Writes `count` sectors from a guest buffer, one sector at a time.
1326///
1327/// Mirrors [`read_sectors`]: the guest buffer is read byte by byte so an
1328/// unmapped page fails the call instead of touching host memory.
1329fn write_sectors(
1330 mem: &mut impl BiosMemory,
1331 disk: &mut dyn BiosDisk,
1332 lba: u64,
1333 count: u64,
1334 buffer: u32,
1335) -> Result<(), u8> {
1336 let mut sector = [0u8; SECTOR_SIZE];
1337 let total = disk.sectors();
1338 for index in 0..count {
1339 let current = lba.checked_add(index).ok_or(DISK_STATUS_SECTOR_NOT_FOUND)?;
1340 if current >= total {
1341 return Err(DISK_STATUS_SECTOR_NOT_FOUND);
1342 }
1343 let base = u64::from(buffer) + index * SECTOR_SIZE as u64;
1344 for (offset, slot) in sector.iter_mut().enumerate() {
1345 let address = base + offset as u64;
1346 if address > u64::from(u32::MAX) {
1347 return Err(DISK_STATUS_SECTOR_NOT_FOUND);
1348 }
1349 *slot = mem
1350 .read_u8(address as u32)
1351 .ok_or(DISK_STATUS_SECTOR_NOT_FOUND)?;
1352 }
1353 if !disk.write_sector(current, §or) {
1354 return Err(DISK_STATUS_WRITE_PROTECTED);
1355 }
1356 }
1357 Ok(())
1358}
1359
1360/// Decodes a BDA keyboard ring offset.
1361///
1362/// A PC firmware keeps the head/tail words as offsets inside the BDA
1363/// (`0x1E..=0x3E`); a guest that kept the older `0..0x20` convention is also
1364/// accepted, which keeps the model usable from either producer.
1365fn ring_offset(value: u16) -> Option<u16> {
1366 if value >= KEY_BUFFER_FIRST_OFFSET && value < KEY_BUFFER_FIRST_OFFSET + KEY_BUFFER_BYTES {
1367 Some(value - KEY_BUFFER_FIRST_OFFSET)
1368 } else if value < KEY_BUFFER_BYTES {
1369 Some(value)
1370 } else {
1371 None
1372 }
1373}
1374/// Reads a little-endian `u16` from guest memory.
1375fn read_u16(mem: &mut impl BiosMemory, address: u32) -> Option<u16> {
1376 let mut bytes = [0u8; 2];
1377 if mem.read(address, &mut bytes) {
1378 Some(u16::from_le_bytes(bytes))
1379 } else {
1380 None
1381 }
1382}
1383
1384/// Reads a little-endian `u64` from guest memory.
1385fn read_u64(mem: &mut impl BiosMemory, address: u32) -> Option<u64> {
1386 let mut bytes = [0u8; 8];
1387 if mem.read(address, &mut bytes) {
1388 Some(u64::from_le_bytes(bytes))
1389 } else {
1390 None
1391 }
1392}
1393
1394/// Writes a little-endian `u16` to guest memory.
1395fn write_u16(mem: &mut impl BiosMemory, address: u32, value: u16) -> bool {
1396 mem.write(address, &value.to_le_bytes())
1397}
1398
1399/// Writes a little-endian `u32` to guest memory.
1400fn write_u32(mem: &mut impl BiosMemory, address: u32, value: u32) -> bool {
1401 mem.write(address, &value.to_le_bytes())
1402}
1403
1404/// Guest-physical address of one text cell.
1405const fn video_cell(row: u8, col: u8) -> u32 {
1406 VIDEO_BASE + (row as u32 * TEXT_COLUMNS as u32 + col as u32) * 2
1407}
1408
1409/// Reads one character/attribute cell, falling back to a blank cell.
1410fn read_cell(mem: &mut impl BiosMemory, row: u8, col: u8) -> (u8, u8) {
1411 let address = video_cell(row, col);
1412 let ch = mem.read_u8(address).unwrap_or(SPACE);
1413 let attr = mem.read_u8(address + 1).unwrap_or(DEFAULT_ATTRIBUTE);
1414 (ch, attr)
1415}
1416
1417/// Writes one character/attribute cell when it is inside the text screen.
1418fn write_cell(mem: &mut impl BiosMemory, row: u8, col: u8, ch: u8, attr: u8) -> bool {
1419 if row >= TEXT_ROWS || col >= TEXT_COLUMNS {
1420 return false;
1421 }
1422 let address = video_cell(row, col);
1423 let character = mem.write_u8(address, ch);
1424 let attribute = mem.write_u8(address + 1, attr);
1425 character && attribute
1426}
1427
1428/// Scrolls a rectangular text window up or down.
1429///
1430/// `lines == 0` blanks the whole window. Vacated cells receive `attr`. The
1431/// caller has already clamped the window to the screen and checked that
1432/// `top <= bottom` and `left <= right`.
1433fn scroll_region(
1434 mem: &mut impl BiosMemory,
1435 up: bool,
1436 lines: u8,
1437 attr: u8,
1438 top: u8,
1439 left: u8,
1440 bottom: u8,
1441 right: u8,
1442) -> bool {
1443 let height = bottom - top + 1;
1444 let count = if lines == 0 {
1445 height
1446 } else {
1447 lines.min(height)
1448 };
1449 if up {
1450 for row in top..=bottom {
1451 for col in left..=right {
1452 let (ch, attribute) = if row + count <= bottom {
1453 read_cell(mem, row + count, col)
1454 } else {
1455 (SPACE, attr)
1456 };
1457 let _ = write_cell(mem, row, col, ch, attribute);
1458 }
1459 }
1460 } else {
1461 for row in (top..=bottom).rev() {
1462 for col in left..=right {
1463 let (ch, attribute) = if row >= top + count {
1464 read_cell(mem, row - count, col)
1465 } else {
1466 (SPACE, attr)
1467 };
1468 let _ = write_cell(mem, row, col, ch, attribute);
1469 }
1470 }
1471 }
1472 true
1473}
1474
1475/// Encodes a binary byte as two packed BCD digits.
1476///
1477/// Values above 99 are clamped so the result always consists of valid digits;
1478/// callers are expected to keep the RTC fields in range.
1479fn bcd(value: u8) -> u8 {
1480 let clamped = value.min(99);
1481 (clamped / 10 << 4) | (clamped % 10)
1482}
1483
1484/// Installs the BIOS data area fields a DOS boot reads.
1485///
1486/// The image receives a 640 KiB machine with one 1.44 MiB floppy, an EBDA
1487/// segment, a home cursor on page 0, an 80x25 colour text mode, a `0x03D4`
1488/// CRTC port and a zero tick counter. Writes that the adapter refuses are
1489/// ignored: the helper never panics.
1490pub fn initialise_bda(mem: &mut impl BiosMemory) {
1491 let _ = write_u16(mem, BDA_EBDA_SEGMENT, EBDA_SEGMENT);
1492 let _ = write_u16(mem, BDA_EQUIPMENT, EQUIPMENT_WORD);
1493 let _ = write_u16(mem, BDA_MEMORY_SIZE, MEMORY_SIZE_KIB);
1494 // A PC firmware leaves the keyboard ring empty: head == tail == the first
1495 // slot offset (0x1E), the convention DOS continues from.
1496 let _ = write_u16(mem, BDA_KEYBOARD_HEAD, KEY_BUFFER_FIRST_OFFSET);
1497 let _ = write_u16(mem, BDA_KEYBOARD_TAIL, KEY_BUFFER_FIRST_OFFSET);
1498 let _ = mem.write_u8(BDA_VIDEO_MODE, DEFAULT_VIDEO_MODE);
1499 let _ = write_u16(mem, BDA_COLUMNS, DEFAULT_COLUMNS);
1500 let _ = write_u16(mem, BDA_CURSOR, 0);
1501 let _ = mem.write_u8(BDA_PAGE, DEFAULT_PAGE);
1502 let _ = write_u16(mem, BDA_CRTC_PORT, DEFAULT_CRTC_PORT);
1503 let _ = mem.write_u8(BDA_ROWS, DEFAULT_ROWS_MINUS_ONE);
1504 let _ = mem.write_u8(BDA_CHAR_HEIGHT, DEFAULT_CHAR_HEIGHT);
1505 let _ = write_u32(mem, BDA_TICK_COUNT, 0);
1506}
1507
1508/// Renders the 80x25 text screen as trimmed lines.
1509///
1510/// Each row is read from [`VIDEO_BASE`] (character bytes at even addresses),
1511/// trailing spaces are removed, trailing empty rows are dropped and rows are
1512/// joined with `'\n'`. Bytes outside the printable ASCII range become spaces.
1513pub fn read_text(mem: &mut impl BiosMemory) -> String {
1514 let mut rows: Vec<String> = Vec::with_capacity(TEXT_ROWS as usize);
1515 for row in 0..TEXT_ROWS {
1516 let mut line = String::new();
1517 for col in 0..TEXT_COLUMNS {
1518 let (ch, _) = read_cell(mem, row, col);
1519 line.push(if (0x20..=0x7E).contains(&ch) {
1520 ch as char
1521 } else {
1522 ' '
1523 });
1524 }
1525 while line.ends_with(' ') {
1526 line.pop();
1527 }
1528 rows.push(line);
1529 }
1530 while rows.last().map_or(false, |line| line.is_empty()) {
1531 rows.pop();
1532 }
1533 let mut text = String::new();
1534 for (index, line) in rows.iter().enumerate() {
1535 if index != 0 {
1536 text.push('\n');
1537 }
1538 text.push_str(line);
1539 }
1540 text
1541}