git clone https://garage44.eu/jeroen/pinnacle.git.. /kernel/src/drivers/ps2.rs
//! A PC's keyboard controller (the i8042, at I/O ports 0x60 and 0x64) and
//! what is behind it: a laptop's own keyboard, and its touchpad as a mouse
//! (every touchpad speaks the PS/2 mouse protocol until a driver asks it
//! for more). Most laptops wire their keyboard here even now, through the
//! embedded controller, whatever the touchpad is on.
//!
//! The controller translates the keyboard's scan codes to set 1, whose
//! codes are Linux's key codes for the main block; the E0-prefixed ones
//! (arrows, the right-hand modifiers, the media keys) come from a table.
//! The mouse sends three-byte packets, four with a wheel (the IntelliMouse
//! knock: sample rates 200, 100, 80), moving a pointer the kernel keeps,
//! as a USB mouse does. Interrupts 1 and 12, through the I/O APIC.
use crate::arch::{in8, out8};
use crate::sync::SpinLock;
use alloc::vec::Vec;
use pinnacle_abi::InputEvent;
const DATA: u16 = 0x60;
const STATUS: u16 = 0x64;
const COMMAND: u16 = 0x64;
/// Status: a byte to read; the controller still holding what was written;
/// the byte to read is the mouse's.
const OUTPUT_FULL: u8 = 1;
const INPUT_FULL: u8 = 1 << 1;
const FROM_MOUSE: u8 = 1 << 5;
/// The configuration byte: each port's interrupt, translation to set 1.
const CONFIG_IRQ1: u8 = 1;
const CONFIG_IRQ12: u8 = 1 << 1;
/// Each port's clock off: set by the disabling at the start, and so in
/// the byte read back then; written back, it would turn both off again.
const CONFIG_CLOCKS_OFF: u8 = 0b11 << 4;
const CONFIG_TRANSLATE: u8 = 1 << 6;
const ACK: u8 = 0xfa;
/// Linux's key codes for the E0-prefixed set 1 codes, by the code's low
/// seven bits; 0 for none.
fn extended(code: u8) -> u16 {
match code {
0x1c => 96, // keypad Enter
0x1d => 97, // right Ctrl
0x20 => 113, // mute
0x2e => 114, // volume down
0x30 => 115, // volume up
0x35 => 98, // keypad /
0x37 => 99, // Print Screen
0x38 => 100, // right Alt
0x47 => 102, // Home
0x48 => 103, // Up
0x49 => 104, // Page Up
0x4b => 105, // Left
0x4d => 106, // Right
0x4f => 107, // End
0x50 => 108, // Down
0x51 => 109, // Page Down
0x52 => 110, // Insert
0x53 => 111, // Delete
0x5b => 125, // left Meta
0x5c => 126, // right Meta
0x5d => 127, // Menu
0x5e => 116, // Power
_ => 0,
}
}
struct State {
keyboard: bool,
mouse: bool,
/// The mouse's packet length: 3, or 4 with a wheel.
packet_len: usize,
/// The vectors interrupts 1 and 12 arrive as.
vectors: [u32; 2],
/// An E0 prefix seen; E1 bytes still to skip (Pause sends six).
e0: bool,
skip: u8,
packet: [u8; 4],
have: usize,
x: i32,
y: i32,
buttons: u8,
}
static STATE: SpinLock<State> = SpinLock::new(State {
keyboard: false,
mouse: false,
packet_len: 3,
vectors: [0; 2],
e0: false,
skip: 0,
packet: [0; 4],
have: 0,
x: 0,
y: 0,
buttons: 0,
});
/// Waits until the controller takes a byte; false after 50 ms.
fn wait_writable() -> bool {
let deadline = crate::timer::now_ms() + 50;
while in8(STATUS) & INPUT_FULL != 0 {
if crate::timer::now_ms() > deadline {
return false;
}
core::hint::spin_loop();
}
true
}
/// A byte from the controller, within `ms`.
fn read(ms: u64) -> Option<u8> {
let deadline = crate::timer::now_ms() + ms;
while in8(STATUS) & OUTPUT_FULL == 0 {
if crate::timer::now_ms() > deadline {
return None;
}
core::hint::spin_loop();
}
Some(in8(DATA))
}
fn command(byte: u8) -> bool {
wait_writable() && {
out8(COMMAND, byte);
true
}
}
fn write_data(byte: u8) -> bool {
wait_writable() && {
out8(DATA, byte);
true
}
}
/// Sends `byte` to the keyboard (or, `mouse`, to the mouse) and waits
/// for its acknowledgement.
fn send(mouse: bool, byte: u8) -> bool {
for _ in 0..3 {
if mouse && !command(0xd4) {
return false;
}
if !write_data(byte) {
return false;
}
match read(100) {
Some(ACK) => return true,
// Resend.
Some(0xfe) => continue,
_ => return false,
}
}
false
}
/// Empties the controller's output, what the firmware left in it.
fn flush() {
for _ in 0..64 {
if in8(STATUS) & OUTPUT_FULL == 0 {
break;
}
in8(DATA);
}
}
/// Finds the controller and sets up what is behind it, its interrupts
/// routed. Returns (keyboard, mouse) found.
pub fn init() -> (bool, bool) {
// No controller: the bus floats.
if in8(STATUS) == 0xff {
return (false, false);
}
// Both ports off while it is set up, what is pending dropped.
command(0xad);
command(0xa7);
flush();
if !command(0x20) {
return (false, false);
}
let Some(config) = read(50) else {
return (false, false);
};
let config = (config & !(CONFIG_IRQ1 | CONFIG_IRQ12 | CONFIG_CLOCKS_OFF)) | CONFIG_TRANSLATE;
command(0x60);
write_data(config);
command(0xae);
command(0xa8);
flush();
// The keyboard: scanning on (a reset would wait on some for a second).
let keyboard = send(false, 0xf4);
// The mouse: defaults, the wheel asked for, then streaming.
let mut mouse = send(true, 0xf6);
let mut packet_len = 3;
if mouse {
for rate in [200, 100, 80] {
send(true, 0xf3);
send(true, rate);
}
if send(true, 0xf2) && read(50) == Some(3) {
packet_len = 4;
}
mouse = send(true, 0xf4);
}
flush();
let mut vectors = [0; 2];
for (i, (irq, there)) in [(1, keyboard), (12, mouse)].into_iter().enumerate() {
if there {
let (gsi, trigger) = crate::ioapic::isa(irq, crate::ioapic::ISA);
vectors[i] = crate::gic::wired_interrupt(gsi, trigger).unwrap_or(0);
}
}
let (width, height) = screen();
{
let mut s = STATE.lock();
s.keyboard = keyboard;
s.mouse = mouse;
s.packet_len = packet_len;
s.vectors = vectors;
s.x = width / 2;
s.y = height / 2;
}
// Interrupts on, for the ports that answered.
let on = if keyboard { CONFIG_IRQ1 } else { 0 } | if mouse { CONFIG_IRQ12 } else { 0 };
command(0x60);
write_data(config | on);
if keyboard || mouse {
crate::println!(
"ps2: {}{}{}",
if keyboard { "a keyboard" } else { "" },
if keyboard && mouse { " and " } else { "" },
match (mouse, packet_len) {
(false, _) => "",
(true, 4) => "a mouse or touchpad, with a wheel",
(true, _) => "a mouse or touchpad",
}
);
}
(keyboard, mouse)
}
/// The screen's size, which the pointer is kept in.
fn screen() -> (i32, i32) {
crate::drivers::display::DISPLAY
.lock()
.as_ref()
.map_or((1, 1), |d| (d.width as i32, d.height as i32))
}
fn event(kind: u16, code: u16, value: i32, x: i32, y: i32) -> InputEvent {
InputEvent {
kind,
code,
value,
x,
y,
synthetic: false,
}
}
impl State {
fn keyboard_byte(&mut self, byte: u8, out: &mut Vec<InputEvent>) {
if self.skip > 0 {
self.skip -= 1;
return;
}
match byte {
0xe0 => {
self.e0 = true;
return;
}
// Pause: E1 1D 45 E1 9D C5, no key code of Linux's set here.
0xe1 => {
self.skip = 5;
return;
}
// Acknowledgements, and the keyboard's errors.
0xfa | 0xfe | 0x00 | 0xff | 0xaa if !self.e0 => return,
_ => {}
}
let extended_code = core::mem::take(&mut self.e0);
let (code, pressed) = (byte & 0x7f, byte & 0x80 == 0);
let key = if extended_code {
// E0 2A and E0 AA: a shift the keyboard pretends around
// Print Screen and the like.
if code == 0x2a || code == 0x36 {
return;
}
extended(code)
} else if code <= 0x58 {
u16::from(code)
} else {
0
};
if key != 0 {
out.push(event(InputEvent::KEY, key, i32::from(pressed), 0, 0));
}
}
fn mouse_byte(&mut self, byte: u8, out: &mut Vec<InputEvent>) {
// A packet's first byte has bit 3 set: anything else is out of step.
if self.have == 0 && byte & 0x08 == 0 {
return;
}
self.packet[self.have] = byte;
self.have += 1;
if self.have < self.packet_len {
return;
}
self.have = 0;
let [flags, dx, dy, _] = self.packet;
// Overflowed: the movement is not to be trusted.
if flags & 0xc0 != 0 {
return;
}
let dx = i32::from(dx) - if flags & 0x10 != 0 { 256 } else { 0 };
let dy = i32::from(dy) - if flags & 0x20 != 0 { 256 } else { 0 };
let (width, height) = screen();
let (x, y) = (self.x, self.y);
// The mouse's y runs up, the screen's down.
self.x = (self.x + dx).clamp(0, width - 1);
self.y = (self.y - dy).clamp(0, height - 1);
if (self.x, self.y) != (x, y) {
out.push(event(InputEvent::MOVE, InputEvent::BY_MOUSE, 0, self.x, self.y));
}
let buttons = flags & 0x07;
// The left button is a touch, as a USB mouse's first is.
if (buttons ^ self.buttons) & 1 != 0 {
out.push(event(
InputEvent::PRESS,
0,
i32::from(buttons & 1),
self.x,
self.y,
));
}
self.buttons = buttons;
}
}
/// Interrupt 1 or 12. False if `vector` is neither's.
pub fn interrupt(vector: u32) -> bool {
if vector == 0 || !STATE.lock().vectors.contains(&vector) {
return false;
}
take("interrupt");
true
}
/// Core 0's tick: what the controller holds, taken as its interrupt would.
/// A firmware that routes interrupt 1 elsewhere than its tables say, or an
/// edge lost while setting up, leaves the keyboard working this way.
pub fn poll() {
if STATE.lock().vectors != [0; 2] && in8(STATUS) & OUTPUT_FULL != 0 {
take("poll");
}
}
/// Every byte the controller holds, from either port (the status says
/// whose), made into input events. The first of each port's is told, and
/// how it came: on hardware nobody has tried, whether the keyboard reaches
/// the kernel at all.
fn take(how: &str) {
static TOLD: core::sync::atomic::AtomicU8 = core::sync::atomic::AtomicU8::new(0);
let mut out = Vec::new();
let mut first = 0u8;
{
let mut s = STATE.lock();
for _ in 0..16 {
let status = in8(STATUS);
if status & OUTPUT_FULL == 0 {
break;
}
let byte = in8(DATA);
if status & FROM_MOUSE != 0 {
first |= 2;
s.mouse_byte(byte, &mut out);
} else {
first |= 1;
s.keyboard_byte(byte, &mut out);
}
}
}
let new = first & !TOLD.fetch_or(first, core::sync::atomic::Ordering::Relaxed);
if new & 1 != 0 {
crate::println!("ps2: the keyboard's first byte, by {how}");
}
if new & 2 != 0 {
crate::println!("ps2: the mouse's first byte, by {how}");
}
if !out.is_empty() {
super::input::deliver(out);
}
}