Skip to main content

strat9_kernel/s9vm/
keyfeed.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//! Host keystrokes waiting to be typed into a DOS guest.
24//!
25//! A key has two encodings, and a PC guest consumes exactly one of them:
26//!
27//! - the 8042 data port yields PS/2 set-1 scancodes (make/break, with a shift
28//!   bracket for shifted characters and the `0xE0` prefix for arrows), which the
29//!   guest's own `INT 9` handler reads;
30//! - the firmware keyboard buffer holds `(scan code, ASCII)` pairs, which a guest
31//!   that kept `INT 16h` at the firmware reads.
32//!
33//! The queue therefore stores whole keys, not bytes: the cursor is one key
34//! index shared by both views. That matters because the two consumers are never
35//! both fed — the runner types into the 8042 only once the guest owns `INT 9`,
36//! and into the buffer before that. Advancing only one view used to leave a
37//! phantom remainder in the other (a hardware run reported "4 keys not typed"
38//! for keys that had all reached the 8042) and would have re-typed the same keys
39//! after a restart.
40//!
41//! The module is pure — it only touches the keyboard and BIOS models — which is
42//! what lets the host tests drive it without VT-x.
43
44use alloc::vec::Vec;
45
46use super::{bios, keyboard};
47
48/// One queued key, in the encodings the two PC consumers expect.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub struct Key {
51    /// Scancode bytes the 8042 must receive (2 or 4 bytes).
52    pub(crate) bytes: [u8; 4],
53    /// Number of valid bytes in [`Self::bytes`].
54    pub(crate) len: u8,
55    /// Scan code the firmware keyboard buffer stores.
56    pub(crate) scan: u8,
57    /// ASCII byte the firmware keyboard buffer stores (0 for extended keys).
58    pub(crate) ascii: u8,
59}
60
61impl Key {
62    /// Translates one host byte into its two encodings.
63    ///
64    /// `None` means the byte cannot be typed on a PC keyboard (a control byte
65    /// other than the named ones), so it is skipped instead of typed as garbage.
66    fn build(byte: u8) -> Option<Self> {
67        let mut scratch = Vec::new();
68        let (scan, ascii) = keyboard::keystroke_for(byte, &mut scratch)?;
69        if scratch.len() > 4 {
70            return None;
71        }
72        let mut bytes = [0u8; 4];
73        bytes[..scratch.len()].copy_from_slice(&scratch);
74        Some(Self {
75            bytes,
76            len: scratch.len() as u8,
77            scan,
78            ascii,
79        })
80    }
81
82    /// Number of scancode bytes this key occupies on the 8042 path.
83    pub const fn scancode_len(&self) -> usize {
84        self.len as usize
85    }
86}
87
88/// Host text waiting to be typed into a DOS guest.
89pub struct KeyboardFeed {
90    /// Keys still to deliver, in order; the front has not been consumed yet.
91    keys: Vec<Key>,
92    /// Index of the next key to deliver (shared by both consumer views).
93    next: usize,
94}
95
96impl KeyboardFeed {
97    /// Builds a feed from host text.
98    pub fn new(text: &[u8]) -> Self {
99        let mut feed = Self::empty();
100        feed.extend(text);
101        feed
102    }
103
104    /// A feed with nothing queued.
105    pub const fn empty() -> Self {
106        Self {
107            keys: Vec::new(),
108            next: 0,
109        }
110    }
111
112    /// Continues a previous slice from exactly where it stopped.
113    ///
114    /// Whole keys are stored, so a slice hand-over cannot split a make/break
115    /// pair or replay a key the guest already received.
116    pub fn from_pending(keys: Vec<Key>) -> Self {
117        Self { keys, next: 0 }
118    }
119
120    /// Appends more host text to the queue.
121    pub fn extend(&mut self, text: &[u8]) {
122        for &byte in text {
123            if let Some(key) = Key::build(byte) {
124                self.keys.push(key);
125            }
126        }
127    }
128
129    /// Keys not handed to the guest yet.
130    pub fn remaining(&self) -> usize {
131        self.keys.len().saturating_sub(self.next)
132    }
133
134    /// Copies the keys a slice hand-over must carry to the next slice.
135    pub fn remaining_keys(&self) -> Vec<Key> {
136        self.keys[self.next..].to_vec()
137    }
138
139    /// Queues whole keys on the 8042 path; returns how many scancode bytes were
140    /// accepted.
141    ///
142    /// A key is only started when the controller has room for all of its bytes,
143    /// so the guest never sees half of a make/break pair, and `limit` (a byte
144    /// budget) can never split a key either.
145    pub fn fill(&mut self, controller: &mut keyboard::KeyboardController, limit: usize) -> usize {
146        let mut sent = 0usize;
147        while self.next < self.keys.len() {
148            let key = self.keys[self.next];
149            let need = key.scancode_len();
150            if sent + need > limit {
151                break;
152            }
153            if usize::from(controller.pending_scancodes()) + need > keyboard::INPUT_CAPACITY {
154                break;
155            }
156            for byte in &key.bytes[..need] {
157                if !controller.push_scancode(*byte) {
158                    return sent;
159                }
160            }
161            sent += need;
162            self.next += 1;
163        }
164        sent
165    }
166
167    /// Pushes whole keys into the firmware keyboard buffer.
168    ///
169    /// This is the path of a guest that did not install its own `INT 9`: its
170    /// `INT 16h` calls still reach the firmware model, so the keys have to
171    /// appear where that service reads them.
172    pub fn fill_bios(&mut self, bios: &mut bios::BiosState, limit: usize) -> usize {
173        let mut sent = 0;
174        while sent < limit && self.next < self.keys.len() {
175            let key = self.keys[self.next];
176            bios.push_scan_key(key.scan, key.ascii);
177            self.next += 1;
178            sent += 1;
179        }
180        sent
181    }
182}