strat9_kernel/s9vm/keyboard.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//! 8042 keyboard controller model (ports `0x60`/`0x64`).
24//!
25//! A DOS-class guest talks to the keyboard controller directly before (and
26//! independently of) the BIOS keyboard service: it polls the status port for
27//! "output buffer full", sends controller commands to port `0x64`, keyboard
28//! commands to port `0x60`, and reads acknowledgements from the data port.
29//!
30//! The model answers the controller self-test (`0xAA` → `0x55`), the keyboard
31//! interface test (`0xAB` → `0x00`), and acknowledges every keyboard command
32//! (`0xFA`); a keyboard reset (`0xFF`) returns the ACK followed by the
33//! self-test success byte (`0xAA`). Without those responses PC firmware (and
34//! externally SeaBIOS) spends seconds in its timeout loops before deciding the
35//! keyboard is absent.
36//!
37//! The host can also type into the guest: [`KeyboardController::push_scancode`]
38//! queues set-1 scancodes exactly as a PS/2 keyboard would send them, the
39//! status port reports "output buffer full" while the queue is not empty, and
40//! the runner raises `IRQ1` while bytes are waiting. [`text_to_scancodes`]
41//! translates host text (ASCII) into that make/break stream, so a DOS guest
42//! with its own `INT 9` handler sees a real keyboard instead of only the BIOS
43//! `INT 16h` polling path.
44
45/// Keyboard data port (read: controller output, write: keyboard command/data).
46pub const DATA_PORT: u16 = 0x60;
47/// Keyboard controller status/command port.
48pub const STATUS_PORT: u16 = 0x64;
49
50/// Status byte: output buffer empty, input buffer empty, system flag set,
51/// keyboard enabled.
52const IDLE_STATUS: u8 = 0x14;
53/// Status bit 0: output buffer full.
54const STATUS_OUTPUT_FULL: u8 = 0x01;
55/// Keyboard acknowledgement byte.
56const PS2_ACK: u8 = 0xFA;
57/// Keyboard self-test success byte.
58const PS2_SELFTEST_OK: u8 = 0xAA;
59/// Keyboard ID bytes for `0xF2` (MF2 keyboard, translated).
60const PS2_ID: [u8; 2] = [0xAB, 0x83];
61
62/// Controller command: read configuration byte.
63const CTL_READ_CONFIG: u8 = 0x20;
64/// Controller command: write configuration byte (next data byte).
65const CTL_WRITE_CONFIG: u8 = 0x60;
66/// Controller command: write output port (next data byte goes there).
67const CTL_WRITE_OUTPUT_PORT: u8 = 0xD1;
68/// Controller command: write auxiliary device (next data byte).
69const CTL_WRITE_AUX: u8 = 0xD4;
70/// Controller command: controller self-test.
71const CTL_SELFTEST: u8 = 0xAA;
72/// Controller command: keyboard interface test.
73const CTL_KBD_TEST: u8 = 0xAB;
74/// Keyboard command: read ID.
75const KBD_READ_ID: u8 = 0xF2;
76/// Keyboard command: reset and self-test.
77const KBD_RESET: u8 = 0xFF;
78
79/// Capacity of the controller output queue.
80const OUTPUT_CAPACITY: usize = 8;
81/// Capacity of the host-to-guest scancode queue.
82pub const INPUT_CAPACITY: usize = 32;
83
84/// PS/2 set-1 scancodes used by [`text_to_scancodes`].
85const SCANCODE_ESCAPE: u8 = 0x01;
86const SCANCODE_BACKSPACE: u8 = 0x0E;
87const SCANCODE_TAB: u8 = 0x0F;
88const SCANCODE_ENTER: u8 = 0x1C;
89const SCANCODE_LEFT_SHIFT: u8 = 0x2A;
90#[allow(dead_code)] // Retained PS/2 right-shift scancode.
91const SCANCODE_RIGHT_SHIFT: u8 = 0x36;
92const SCANCODE_SPACE: u8 = 0x39;
93const SCANCODE_BREAK: u8 = 0x80;
94
95/// True if the port belongs to the 8042.
96pub const fn handles_port(port: u16) -> bool {
97 port == DATA_PORT || port == STATUS_PORT
98}
99
100/// Minimal 8042 state with a small controller-to-host output queue.
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub struct KeyboardController {
103 /// Bytes waiting for the host on the data port (controller replies).
104 output: [u8; OUTPUT_CAPACITY],
105 /// Number of valid bytes in `output` (at the front).
106 output_len: u8,
107 /// Scancodes typed by the host and not read by the guest yet.
108 input: [u8; INPUT_CAPACITY],
109 /// Number of valid scancodes in `input` (at the front).
110 input_len: u8,
111 /// Last command written to port `0x64`.
112 last_command: u8,
113 /// Number of data-port reads the guest performed (diagnostics only).
114 ///
115 /// A guest that queues scancodes but never reads `0x60` is the difference
116 /// between "the interrupt never arrived" and "the handler read the port".
117 data_reads: u32,
118 /// Reads of `0x60` answered from the controller reply queue (diagnostics).
119 reply_reads: u32,
120 /// Reads of `0x60` answered from the host scancode queue (diagnostics).
121 scancode_reads: u32,
122 /// Next data-port write goes to the controller output port, not the
123 /// keyboard (set by command `0xD1`).
124 output_port_write: bool,
125 /// Next data-port write is a controller parameter (config/aux), not a
126 /// keyboard command, so it must not produce a keyboard ACK.
127 controller_data: bool,
128}
129
130impl KeyboardController {
131 /// Creates an idle controller.
132 pub const fn new() -> Self {
133 Self {
134 output: [0; OUTPUT_CAPACITY],
135 output_len: 0,
136 input: [0; INPUT_CAPACITY],
137 input_len: 0,
138 last_command: 0,
139 data_reads: 0,
140 reply_reads: 0,
141 scancode_reads: 0,
142 output_port_write: false,
143 controller_data: false,
144 }
145 }
146
147 /// Queues one set-1 scancode as if the PS/2 keyboard sent it.
148 ///
149 /// Returns `false` when the queue is full: the caller keeps the remaining
150 /// bytes and retries after the guest has read some.
151 pub fn push_scancode(&mut self, code: u8) -> bool {
152 let len = usize::from(self.input_len);
153 if len >= INPUT_CAPACITY {
154 return false;
155 }
156 self.input[len] = code;
157 self.input_len += 1;
158 true
159 }
160
161 /// True while the guest has not read every queued scancode.
162 pub const fn has_scancode(&self) -> bool {
163 self.input_len != 0
164 }
165
166 /// Number of scancodes waiting to be read by the guest.
167 pub const fn pending_scancodes(&self) -> u8 {
168 self.input_len
169 }
170
171 /// Reads one port.
172 pub fn read(&mut self, port: u16) -> Option<u8> {
173 match port {
174 DATA_PORT => {
175 self.data_reads = self.data_reads.saturating_add(1);
176 if self.output_len != 0 {
177 let value = self.output[0];
178 self.reply_reads = self.reply_reads.saturating_add(1);
179 self.pop_front();
180 Some(value)
181 } else if self.input_len != 0 {
182 self.scancode_reads = self.scancode_reads.saturating_add(1);
183 // The host reuses the same output buffer for scancodes: a
184 // real controller only has one byte path to the guest.
185 let value = self.input[0];
186 self.pop_input_front();
187 Some(value)
188 } else {
189 Some(0)
190 }
191 }
192 STATUS_PORT => Some(self.status()),
193 _ => None,
194 }
195 }
196
197 /// Writes one port.
198 pub fn write(&mut self, port: u16, value: u8) {
199 match port {
200 DATA_PORT => self.write_data(value),
201 STATUS_PORT => self.write_command(value),
202 _ => {}
203 }
204 }
205
206 /// Number of data-port reads observed so far (diagnostics only).
207 pub const fn data_reads(&self) -> u32 {
208 self.data_reads
209 }
210
211 /// Reads of `0x60` answered from the controller reply queue.
212 pub const fn reply_reads(&self) -> u32 {
213 self.reply_reads
214 }
215
216 /// Reads of `0x60` answered from the host scancode queue.
217 pub const fn scancode_reads(&self) -> u32 {
218 self.scancode_reads
219 }
220
221 /// Last command written to the status port (diagnostics).
222 pub const fn last_command(&self) -> u8 {
223 self.last_command
224 }
225
226 /// Current status byte.
227 pub fn status(&self) -> u8 {
228 let mut status = IDLE_STATUS;
229 if self.output_len != 0 || self.input_len != 0 {
230 status |= STATUS_OUTPUT_FULL;
231 }
232 status
233 }
234
235 /// Handles a data-port write (keyboard command or parameter).
236 fn write_data(&mut self, value: u8) {
237 if self.output_port_write {
238 // `0xD1` selected the controller output port (A20/gate control,
239 // not modeled); consume the byte without a keyboard reply.
240 self.output_port_write = false;
241 return;
242 }
243 if self.controller_data {
244 // Configuration byte or auxiliary-device byte: no keyboard ACK.
245 self.controller_data = false;
246 return;
247 }
248 self.push(PS2_ACK);
249 match value {
250 KBD_RESET => self.push(PS2_SELFTEST_OK),
251 KBD_READ_ID => {
252 self.push(PS2_ID[0]);
253 self.push(PS2_ID[1]);
254 }
255 _ => {}
256 }
257 }
258
259 /// Handles a status-port write (controller command).
260 fn write_command(&mut self, value: u8) {
261 self.last_command = value;
262 self.output_port_write = value == CTL_WRITE_OUTPUT_PORT;
263 self.controller_data = matches!(value, CTL_WRITE_CONFIG | CTL_WRITE_AUX);
264 match value {
265 CTL_SELFTEST => self.push(0x55),
266 CTL_KBD_TEST => self.push(0x00),
267 CTL_READ_CONFIG => self.push(IDLE_STATUS),
268 _ => {}
269 }
270 }
271
272 /// Appends one byte to the output queue when there is room.
273 fn push(&mut self, value: u8) {
274 let len = usize::from(self.output_len);
275 if len < OUTPUT_CAPACITY {
276 self.output[len] = value;
277 self.output_len += 1;
278 }
279 }
280
281 /// Drops the front byte of the output queue.
282 fn pop_front(&mut self) {
283 if self.output_len == 0 {
284 return;
285 }
286 let len = usize::from(self.output_len);
287 for index in 1..len {
288 self.output[index - 1] = self.output[index];
289 }
290 self.output_len -= 1;
291 }
292
293 /// Drops the front scancode of the input queue.
294 fn pop_input_front(&mut self) {
295 if self.input_len == 0 {
296 return;
297 }
298 let len = usize::from(self.input_len);
299 for index in 1..len {
300 self.input[index - 1] = self.input[index];
301 }
302 self.input_len -= 1;
303 }
304}
305
306/// One scancode of a key press, with the shift state it needs.
307///
308/// `shift` selects the shifted row of a US layout, so an uppercase letter or a
309/// symbol (`!`, `"`, `?`, ...) is reported with the shift key held while its
310/// make code is sent. The break code (make | `0x80`) always follows.
311#[derive(Debug, Clone, Copy, PartialEq, Eq)]
312pub struct KeyStroke {
313 /// Set-1 make code of the key.
314 pub scancode: u8,
315 /// True when the shift key must be down for this character.
316 pub shift: bool,
317}
318
319/// Maps one ASCII byte to a US-layout key stroke.
320///
321/// Returns `None` for characters a PC keyboard cannot type directly (control
322/// bytes other than the named ones, non-ASCII). [`text_to_scancodes`] skips
323/// them so a caller can pass a raw line of text.
324pub fn ascii_keystroke(byte: u8) -> Option<KeyStroke> {
325 let (scancode, shift) = match byte {
326 b'\x1b' => (SCANCODE_ESCAPE, false),
327 b'\x08' => (SCANCODE_BACKSPACE, false),
328 b'\t' => (SCANCODE_TAB, false),
329 b'\r' => (SCANCODE_ENTER, false),
330 b'\n' => (SCANCODE_ENTER, false),
331 b' ' => (SCANCODE_SPACE, false),
332 b'1'..=b'9' => (0x02 + (byte - b'1'), false),
333 b'0' => (0x0B, false),
334 b'-' => (0x0C, false),
335 b'=' => (0x0D, false),
336 b'!' => (0x02, true),
337 b'@' => (0x03, true),
338 b'#' => (0x04, true),
339 b'$' => (0x05, true),
340 b'%' => (0x06, true),
341 b'^' => (0x07, true),
342 b'&' => (0x08, true),
343 b'*' => (0x09, true),
344 b'(' => (0x0A, true),
345 b')' => (0x0B, true),
346 b'_' => (0x0C, true),
347 b'+' => (0x0D, true),
348 b'q' | b'Q' => (0x10, byte == b'Q'),
349 b'w' | b'W' => (0x11, byte == b'W'),
350 b'e' | b'E' => (0x12, byte == b'E'),
351 b'r' | b'R' => (0x13, byte == b'R'),
352 b't' | b'T' => (0x14, byte == b'T'),
353 b'y' | b'Y' => (0x15, byte == b'Y'),
354 b'u' | b'U' => (0x16, byte == b'U'),
355 b'i' | b'I' => (0x17, byte == b'I'),
356 b'o' | b'O' => (0x18, byte == b'O'),
357 b'p' | b'P' => (0x19, byte == b'P'),
358 b'[' | b'{' => (0x1A, byte == b'{'),
359 b']' | b'}' => (0x1B, byte == b'}'),
360 b'a' | b'A' => (0x1E, byte == b'A'),
361 b's' | b'S' => (0x1F, byte == b'S'),
362 b'd' | b'D' => (0x20, byte == b'D'),
363 b'f' | b'F' => (0x21, byte == b'F'),
364 b'g' | b'G' => (0x22, byte == b'G'),
365 b'h' | b'H' => (0x23, byte == b'H'),
366 b'j' | b'J' => (0x24, byte == b'J'),
367 b'k' | b'K' => (0x25, byte == b'K'),
368 b'l' | b'L' => (0x26, byte == b'L'),
369 b';' | b':' => (0x27, byte == b':'),
370 b'\'' | b'"' => (0x28, byte == b'"'),
371 b'`' | b'~' => (0x29, byte == b'~'),
372 b'\\' | b'|' => (0x2B, byte == b'|'),
373 b'z' | b'Z' => (0x2C, byte == b'Z'),
374 b'x' | b'X' => (0x2D, byte == b'X'),
375 b'c' | b'C' => (0x2E, byte == b'C'),
376 b'v' | b'V' => (0x2F, byte == b'V'),
377 b'b' | b'B' => (0x30, byte == b'B'),
378 b'n' | b'N' => (0x31, byte == b'N'),
379 b'm' | b'M' => (0x32, byte == b'M'),
380 b',' | b'<' => (0x33, byte == b'<'),
381 b'.' | b'>' => (0x34, byte == b'>'),
382 b'/' | b'?' => (0x35, byte == b'?'),
383 _ => return None,
384 };
385 Some(KeyStroke { scancode, shift })
386}
387
388/// Appends the make/break scancodes that type `text` on a US keyboard.
389///
390/// A shifted key is bracketed by a shift press and release, so every character
391/// is self-contained: the guest's `INT 9` handler decodes the same key the host
392/// typed without any cross-character state.
393pub fn text_to_scancodes(text: &[u8], out: &mut alloc::vec::Vec<u8>) {
394 for &byte in text {
395 let Some(stroke) = ascii_keystroke(byte) else {
396 continue;
397 };
398 if stroke.shift {
399 out.push(SCANCODE_LEFT_SHIFT);
400 }
401 out.push(stroke.scancode);
402 out.push(stroke.scancode | SCANCODE_BREAK);
403 if stroke.shift {
404 out.push(SCANCODE_LEFT_SHIFT | SCANCODE_BREAK);
405 }
406 }
407}
408
409/// Prefix of an extended PS/2 set-1 scan code (arrows, Home/End, keypad).
410pub const SCANCODE_EXTENDED: u8 = 0xE0;
411
412/// Extended scan code of one key the rest of the system reports above `0x7F`.
413///
414/// The kernel keyboard driver yields single bytes for the special keys (see
415/// `strat9_keymap::{KEY_UP, …}`). A PC sends those as `0xE0` followed
416/// by the code below, and a DOS `INT 9` handler stores them in the keyboard
417/// buffer with a zero ASCII byte, which is how `INT 16h` reports an arrow.
418pub const fn extended_scan(key: u8) -> Option<u8> {
419 match key {
420 strat9_keymap::KEY_UP => Some(0x48), // up
421 strat9_keymap::KEY_DOWN => Some(0x50), // down
422 strat9_keymap::KEY_LEFT => Some(0x4B), // left
423 strat9_keymap::KEY_RIGHT => Some(0x4D), // right
424 strat9_keymap::KEY_HOME => Some(0x47), // home
425 strat9_keymap::KEY_END => Some(0x4F), // end
426 _ => None,
427 }
428}
429
430/// Appends the scancodes that type one byte, and returns the firmware-buffer
431/// entry it produces.
432///
433/// Printable and named ASCII bytes get the same sequence [`text_to_scancodes`]
434/// produces. The special keys above `0x7F` get an `0xE0`-prefixed make/break
435/// pair and a buffer entry with a zero ASCII byte. `None` means the byte cannot
436/// be typed on a PC keyboard.
437pub fn keystroke_for(byte: u8, out: &mut alloc::vec::Vec<u8>) -> Option<(u8, u8)> {
438 if let Some(scan) = extended_scan(byte) {
439 out.push(SCANCODE_EXTENDED);
440 out.push(scan);
441 out.push(SCANCODE_EXTENDED);
442 out.push(scan | SCANCODE_BREAK);
443 return Some((scan, 0));
444 }
445 let stroke = ascii_keystroke(byte)?;
446 if stroke.shift {
447 out.push(SCANCODE_LEFT_SHIFT);
448 }
449 out.push(stroke.scancode);
450 out.push(stroke.scancode | SCANCODE_BREAK);
451 if stroke.shift {
452 out.push(SCANCODE_LEFT_SHIFT | SCANCODE_BREAK);
453 }
454 // Line feeds never reach DOS: `INT 16h` reports Enter as CR.
455 Some((0, if byte == b'\n' { b'\r' } else { byte }))
456}
457
458impl Default for KeyboardController {
459 fn default() -> Self {
460 Self::new()
461 }
462}