Skip to main content

strat9_kernel/arch/x86_64/
mouse.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//! PS/2 Mouse driver (IRQ12)
24//!
25//! Supports standard 3-byte PS/2 mouse and IntelliMouse (4-byte, scroll wheel).
26//! Initialization follows the standard PS/2 controller protocol via I/O ports
27//! 0x60 (data) and 0x64 (command/status).
28
29use super::io::{inb, outb};
30use core::sync::atomic::{AtomicBool, AtomicI32, AtomicU8, Ordering};
31use spin::Mutex;
32
33// === PS/2 controller ports =========================
34const PS2_DATA: u16 = 0x60;
35const PS2_CMD: u16 = 0x64;
36
37// PS/2 controller commands
38const CMD_READ_CFG: u8 = 0x20;
39const CMD_WRITE_CFG: u8 = 0x60;
40const CMD_ENABLE_AUX: u8 = 0xA8;
41const CMD_SEND_TO_MOUSE: u8 = 0xD4;
42
43// Mouse commands
44const MOUSE_RESET: u8 = 0xFF;
45const MOUSE_SET_DEFAULTS: u8 = 0xF6;
46const MOUSE_ENABLE_STREAM: u8 = 0xF4;
47const MOUSE_GET_ID: u8 = 0xF2;
48const MOUSE_SET_SAMPLE_RATE: u8 = 0xF3;
49const MOUSE_ACK: u8 = 0xFA;
50
51// PS/2 status bits
52const STATUS_OUTPUT_FULL: u8 = 0x01; // data available on port 0x60
53const STATUS_INPUT_FULL: u8 = 0x02; // controller busy, don't write
54
55//  === Event ring buffer ==========
56const EVENT_BUF_SIZE: usize = 64;
57
58struct EventBuffer {
59    buf: [MouseEvent; EVENT_BUF_SIZE],
60    head: usize,
61    tail: usize,
62}
63
64static EVENT_BUF: Mutex<EventBuffer> = Mutex::new(EventBuffer {
65    buf: [MouseEvent {
66        dx: 0,
67        dy: 0,
68        dz: 0,
69        left: false,
70        right: false,
71        middle: false,
72    }; EVENT_BUF_SIZE],
73    head: 0,
74    tail: 0,
75});
76
77//  === Absolute cursor position (accumulated) ======================
78static MOUSE_ABS_X: AtomicI32 = AtomicI32::new(0);
79static MOUSE_ABS_Y: AtomicI32 = AtomicI32::new(0);
80// Cached screen bounds to avoid locking VGA from IRQ context.
81static SCREEN_W: AtomicI32 = AtomicI32::new(1280);
82static SCREEN_H: AtomicI32 = AtomicI32::new(800);
83
84//  === Packet state machine =================================
85/// Current byte index within the current packet (0, 1, 2, [3])
86static MOUSE_CYCLE: AtomicU8 = AtomicU8::new(0);
87/// Whether IntelliMouse (4-byte) mode is active
88static INTELLIMOUSE: AtomicBool = AtomicBool::new(false);
89/// Mouse is initialized and streaming
90pub static MOUSE_READY: AtomicBool = AtomicBool::new(false);
91
92static PACKET_BUF: Mutex<[u8; 4]> = Mutex::new([0u8; 4]);
93
94/// A decoded mouse event.
95#[derive(Clone, Copy)]
96pub struct MouseEvent {
97    /// Horizontal delta (positive = right)
98    pub dx: i16,
99    /// Vertical delta (positive = down, matching screen coordinates)
100    pub dy: i16,
101    /// Scroll wheel delta (negative = scroll down / forward)
102    pub dz: i8,
103    pub left: bool,
104    pub right: bool,
105    pub middle: bool,
106}
107
108//  === PS/2 helpers ==============================
109
110/// Spin until the PS/2 input buffer is empty (safe to write).
111#[inline]
112fn wait_write() {
113    for _ in 0..100_000u32 {
114        if unsafe { inb(PS2_CMD) } & STATUS_INPUT_FULL == 0 {
115            return;
116        }
117        core::hint::spin_loop();
118    }
119}
120
121/// Spin until the PS/2 output buffer has data (safe to read).
122#[inline]
123fn wait_read() {
124    for _ in 0..100_000u32 {
125        if unsafe { inb(PS2_CMD) } & STATUS_OUTPUT_FULL != 0 {
126            return;
127        }
128        core::hint::spin_loop();
129    }
130}
131
132/// Read a byte from the PS/2 data port (waits for data).
133fn ps2_read() -> u8 {
134    wait_read();
135    unsafe { inb(PS2_DATA) }
136}
137
138/// Write a byte to the PS/2 command port.
139fn ps2_write_cmd(cmd: u8) {
140    wait_write();
141    unsafe { outb(PS2_CMD, cmd) };
142}
143
144/// Write a byte to the PS/2 data port.
145fn ps2_write_data(data: u8) {
146    wait_write();
147    unsafe { outb(PS2_DATA, data) };
148}
149
150/// Send a byte directly to the mouse (via the 0xD4 mux).
151fn mouse_write(data: u8) {
152    ps2_write_cmd(CMD_SEND_TO_MOUSE);
153    ps2_write_data(data);
154}
155
156/// Send a command to the mouse and wait for ACK. Returns true on success.
157fn mouse_cmd(cmd: u8) -> bool {
158    mouse_write(cmd);
159    let ack = ps2_read();
160    ack == MOUSE_ACK
161}
162
163/// Send a command + argument to the mouse and wait for ACK.
164fn mouse_cmd_arg(cmd: u8, arg: u8) -> bool {
165    mouse_write(cmd);
166    let ack = ps2_read();
167    if ack != MOUSE_ACK {
168        return false;
169    }
170    mouse_write(arg);
171    let ack2 = ps2_read();
172    ack2 == MOUSE_ACK
173}
174
175/// Drain any pending bytes in the PS/2 output buffer.
176fn flush_output() {
177    for _ in 0..16 {
178        if unsafe { inb(PS2_CMD) } & STATUS_OUTPUT_FULL == 0 {
179            break;
180        }
181        unsafe { inb(PS2_DATA) };
182    }
183}
184
185// === Initialization ====================
186
187/// Initialize the PS/2 mouse.
188///
189/// Must be called after the IDT and I/O APIC are set up (IRQ12 routed).
190/// Returns `true` on success.
191pub fn init() -> bool {
192    flush_output();
193
194    // Enable the PS/2 auxiliary (mouse) channel
195    ps2_write_cmd(CMD_ENABLE_AUX);
196
197    // Enable IRQ12 in the PS/2 controller configuration byte
198    ps2_write_cmd(CMD_READ_CFG);
199    let mut cfg = ps2_read();
200    cfg |= 0x02; // enable IRQ12 (mouse interrupt)
201    cfg &= !0x20; // clear "mouse clock disable" bit
202    ps2_write_cmd(CMD_WRITE_CFG);
203    ps2_write_data(cfg);
204
205    // Reset the mouse
206    mouse_cmd(MOUSE_RESET);
207    // Drain the reset response (0xAA 0x00)
208    flush_output();
209
210    // Set defaults
211    if !mouse_cmd(MOUSE_SET_DEFAULTS) {
212        crate::serial_println!("[mouse] set_defaults failed");
213        return false;
214    }
215
216    // Attempt IntelliMouse activation (magic sequence: rates 200, 100, 80)
217    let intellimouse = try_enable_intellimouse();
218    INTELLIMOUSE.store(intellimouse, Ordering::Relaxed);
219    if intellimouse {
220        crate::serial_println!("[mouse] IntelliMouse (scroll wheel) detected");
221    } else {
222        crate::serial_println!("[mouse] Standard PS/2 mouse (3-byte packets)");
223    }
224
225    // Enable mouse data streaming
226    if !mouse_cmd(MOUSE_ENABLE_STREAM) {
227        crate::serial_println!("[mouse] enable_stream failed");
228        return false;
229    }
230
231    // Cache screen size once (safe in init context) to avoid locking VGA in IRQs.
232    let w = crate::arch::x86_64::vga::width() as i32;
233    let h = crate::arch::x86_64::vga::height() as i32;
234    if w > 0 {
235        SCREEN_W.store(w, Ordering::Relaxed);
236    }
237    if h > 0 {
238        SCREEN_H.store(h, Ordering::Relaxed);
239    }
240
241    MOUSE_READY.store(true, Ordering::Relaxed);
242    crate::serial_println!("[mouse] PS/2 mouse initialized OK");
243    true
244}
245
246/// Try activating IntelliMouse scroll wheel mode.
247/// Returns true if the mouse identifies as IntelliMouse (ID = 0x03).
248fn try_enable_intellimouse() -> bool {
249    // Magic rate sequence to unlock IntelliMouse mode
250    mouse_cmd_arg(MOUSE_SET_SAMPLE_RATE, 200);
251    mouse_cmd_arg(MOUSE_SET_SAMPLE_RATE, 100);
252    mouse_cmd_arg(MOUSE_SET_SAMPLE_RATE, 80);
253
254    // Query device ID
255    mouse_write(MOUSE_GET_ID);
256    let ack = ps2_read();
257    if ack != MOUSE_ACK {
258        return false;
259    }
260    let id = ps2_read();
261    id == 0x03
262}
263
264//  === IRQ12 handler ==============================
265
266/// Called from the IDT IRQ12 handler (interrupt context, interrupts disabled).
267///
268/// Reads one byte from the PS/2 data port and advances the packet state machine.
269pub fn handle_irq() {
270    let byte = unsafe { inb(PS2_DATA) };
271    let cycle = MOUSE_CYCLE.load(Ordering::Relaxed);
272    let packet_len: u8 = if INTELLIMOUSE.load(Ordering::Relaxed) {
273        4
274    } else {
275        3
276    };
277
278    // Byte 0 sanity check: bit 3 must always be set; resync if not
279    if cycle == 0 && (byte & 0x08) == 0 {
280        // Out of sync – just drop and wait for a valid first byte
281        return;
282    }
283
284    // Store byte in packet buffer
285    {
286        if let Some(mut buf) = PACKET_BUF.try_lock() {
287            buf[cycle as usize] = byte;
288        } else {
289            return; // IRQ re-entrancy guard: drop
290        }
291    }
292
293    let next_cycle = cycle + 1;
294    if next_cycle >= packet_len {
295        // Full packet received – decode it
296        MOUSE_CYCLE.store(0, Ordering::Relaxed);
297        decode_packet();
298    } else {
299        MOUSE_CYCLE.store(next_cycle, Ordering::Relaxed);
300    }
301}
302
303/// Decode the current packet buffer and push a `MouseEvent`.
304fn decode_packet() {
305    let buf = {
306        match PACKET_BUF.try_lock() {
307            Some(b) => *b,
308            None => return,
309        }
310    };
311
312    let flags = buf[0];
313    let raw_dx = buf[1] as i16;
314    let raw_dy = buf[2] as i16;
315
316    // Sign-extend dx / dy using bits 4 and 5 of flags (overflow bits 6/7 ignored)
317    let dx: i16 = if flags & 0x10 != 0 {
318        raw_dx - 256
319    } else {
320        raw_dx
321    };
322    // Y axis: PS/2 uses positive = up; we flip to positive = down (screen coords)
323    let dy_ps2: i16 = if flags & 0x20 != 0 {
324        raw_dy - 256
325    } else {
326        raw_dy
327    };
328    let dy = -dy_ps2;
329
330    let dz: i8 = if INTELLIMOUSE.load(Ordering::Relaxed) {
331        // Lower 4 bits of byte 3, sign-extend
332        let raw = (buf[3] & 0x0F) as i8;
333        if raw & 0x08 != 0 {
334            raw | -16i8
335        } else {
336            raw
337        }
338    } else {
339        0
340    };
341
342    let left = flags & 0x01 != 0;
343    let right = flags & 0x02 != 0;
344    let middle = flags & 0x04 != 0;
345
346    // Clamp and accumulate absolute position using cached bounds (IRQ-safe)
347    let scr_w = SCREEN_W.load(Ordering::Relaxed);
348    let scr_h = SCREEN_H.load(Ordering::Relaxed);
349    let max_x = if scr_w > 0 { scr_w - 1 } else { 1279 };
350    let max_y = if scr_h > 0 { scr_h - 1 } else { 799 };
351
352    let prev_x = MOUSE_ABS_X.load(Ordering::Relaxed);
353    let prev_y = MOUSE_ABS_Y.load(Ordering::Relaxed);
354    let new_x = (prev_x + dx as i32).clamp(0, max_x);
355    let new_y = (prev_y + dy as i32).clamp(0, max_y);
356    MOUSE_ABS_X.store(new_x, Ordering::Relaxed);
357    MOUSE_ABS_Y.store(new_y, Ordering::Relaxed);
358
359    let event = MouseEvent {
360        dx,
361        dy,
362        dz,
363        left,
364        right,
365        middle,
366    };
367
368    // Push to event ring buffer (non-blocking, drop on overflow)
369    if let Some(mut q) = EVENT_BUF.try_lock() {
370        let tail = q.tail;
371        let next_tail = (tail + 1) % EVENT_BUF_SIZE;
372        if next_tail != q.head {
373            q.buf[tail] = event;
374            q.tail = next_tail;
375        }
376    }
377}
378
379// === Public API ========================================
380
381/// Dequeue the oldest mouse event (non-blocking).
382///
383/// Must be called from task context only (not interrupt context).
384pub fn read_event() -> Option<MouseEvent> {
385    // Disable interrupts before taking the lock to prevent IRQ12 deadlock.
386    let saved = super::save_flags_and_cli();
387    let result = {
388        let mut q = EVENT_BUF.lock();
389        if q.head == q.tail {
390            None
391        } else {
392            let ev = q.buf[q.head];
393            q.head = (q.head + 1) % EVENT_BUF_SIZE;
394            Some(ev)
395        }
396    };
397    super::restore_flags(saved);
398    result
399}
400
401/// Returns `true` if at least one mouse event is pending.
402pub fn has_event() -> bool {
403    let saved = super::save_flags_and_cli();
404    let result = {
405        let q = EVENT_BUF.lock();
406        q.head != q.tail
407    };
408    super::restore_flags(saved);
409    result
410}
411
412/// Returns the current accumulated mouse position (pixel coordinates).
413pub fn mouse_pos() -> (i32, i32) {
414    (
415        MOUSE_ABS_X.load(Ordering::Relaxed),
416        MOUSE_ABS_Y.load(Ordering::Relaxed),
417    )
418}
419
420/// Push a mouse event from USB HID or other non-PS/2 source.
421///
422/// Must be called from task context only. Updates absolute position and
423/// enqueues the event for consumption by `read_event()`.
424/// Used by hid::poll_all() when USB HID mouse reports arrive.
425pub fn push_event_from_hid(dx: i16, dy: i16, dz: i8, left: bool, right: bool, middle: bool) {
426    let saved = super::save_flags_and_cli();
427    {
428        let scr_w = SCREEN_W.load(Ordering::Relaxed);
429        let scr_h = SCREEN_H.load(Ordering::Relaxed);
430        let max_x = if scr_w > 0 { scr_w - 1 } else { 1279 };
431        let max_y = if scr_h > 0 { scr_h - 1 } else { 799 };
432        let prev_x = MOUSE_ABS_X.load(Ordering::Relaxed);
433        let prev_y = MOUSE_ABS_Y.load(Ordering::Relaxed);
434        let new_x = (prev_x + dx as i32).clamp(0, max_x);
435        let new_y = (prev_y + dy as i32).clamp(0, max_y);
436        MOUSE_ABS_X.store(new_x, Ordering::Relaxed);
437        MOUSE_ABS_Y.store(new_y, Ordering::Relaxed);
438
439        let event = MouseEvent {
440            dx,
441            dy,
442            dz,
443            left,
444            right,
445            middle,
446        };
447        if let Some(mut q) = EVENT_BUF.try_lock() {
448            let tail = q.tail;
449            let next_tail = (tail + 1) % EVENT_BUF_SIZE;
450            if next_tail != q.head {
451                q.buf[tail] = event;
452                q.tail = next_tail;
453            }
454        }
455    }
456    super::restore_flags(saved);
457}