summaryrefslogtreecommitdiffstats
path: root/rsnix/src/ps2.rs
blob: b83a4e05ecd9b4202cc33d69ccc2424db80ff2ab (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
/// PS/2 keyboard driver — polling, scancode set 1, US QWERTY layout.
// Port addresses
const DATA_PORT: u16 = 0x60;
const STATUS_PORT: u16 = 0x64;

// Status register bits
const STAT_OUTPUT_FULL: u8 = 0x01;

// Modifier bit constants
const MOD_LSHIFT: u8 = 0x01;
const MOD_RSHIFT: u8 = 0x02;
const MOD_LCTRL: u8 = 0x04;
const MOD_RCTRL: u8 = 0x08;
const MOD_LALT: u8 = 0x10;
const MOD_RALT: u8 = 0x20;
const MOD_CAPS: u8 = 0x40;

/// A decoded key event.
pub enum KeyEvent {
    Char(char),
    Enter,
    Backspace,
    Tab,
    Escape,
    ArrowUp,
    ArrowDown,
    ArrowLeft,
    ArrowRight,
    Home,
    End,
    PageUp,
    PageDown,
    Delete,
    F(u8),
    Unknown(u8),
}

// ----- scancode-set-1 translation tables (US QWERTY) -----

/// Normal (unshifted) scancode → ASCII mapping.  0 = unmapped.
static SCAN_NORMAL: [u8; 128] = {
    let mut t = [0u8; 128];
    t[0x02] = b'1';
    t[0x03] = b'2';
    t[0x04] = b'3';
    t[0x05] = b'4';
    t[0x06] = b'5';
    t[0x07] = b'6';
    t[0x08] = b'7';
    t[0x09] = b'8';
    t[0x0A] = b'9';
    t[0x0B] = b'0';
    t[0x0C] = b'-';
    t[0x0D] = b'=';
    t[0x10] = b'q';
    t[0x11] = b'w';
    t[0x12] = b'e';
    t[0x13] = b'r';
    t[0x14] = b't';
    t[0x15] = b'y';
    t[0x16] = b'u';
    t[0x17] = b'i';
    t[0x18] = b'o';
    t[0x19] = b'p';
    t[0x1A] = b'[';
    t[0x1B] = b']';
    t[0x1E] = b'a';
    t[0x1F] = b's';
    t[0x20] = b'd';
    t[0x21] = b'f';
    t[0x22] = b'g';
    t[0x23] = b'h';
    t[0x24] = b'j';
    t[0x25] = b'k';
    t[0x26] = b'l';
    t[0x27] = b';';
    t[0x28] = b'\'';
    t[0x29] = b'`';
    t[0x2B] = b'\\';
    t[0x2C] = b'z';
    t[0x2D] = b'x';
    t[0x2E] = b'c';
    t[0x2F] = b'v';
    t[0x30] = b'b';
    t[0x31] = b'n';
    t[0x32] = b'm';
    t[0x33] = b',';
    t[0x34] = b'.';
    t[0x35] = b'/';
    t[0x37] = b'*';
    t[0x39] = b' ';
    t
};

/// Shifted scancode → ASCII.
static SCAN_SHIFT: [u8; 128] = {
    let mut t = [0u8; 128];
    t[0x02] = b'!';
    t[0x03] = b'@';
    t[0x04] = b'#';
    t[0x05] = b'$';
    t[0x06] = b'%';
    t[0x07] = b'^';
    t[0x08] = b'&';
    t[0x09] = b'*';
    t[0x0A] = b'(';
    t[0x0B] = b')';
    t[0x0C] = b'_';
    t[0x0D] = b'+';
    t[0x10] = b'Q';
    t[0x11] = b'W';
    t[0x12] = b'E';
    t[0x13] = b'R';
    t[0x14] = b'T';
    t[0x15] = b'Y';
    t[0x16] = b'U';
    t[0x17] = b'I';
    t[0x18] = b'O';
    t[0x19] = b'P';
    t[0x1A] = b'{';
    t[0x1B] = b'}';
    t[0x1E] = b'A';
    t[0x1F] = b'S';
    t[0x20] = b'D';
    t[0x21] = b'F';
    t[0x22] = b'G';
    t[0x23] = b'H';
    t[0x24] = b'J';
    t[0x25] = b'K';
    t[0x26] = b'L';
    t[0x27] = b':';
    t[0x28] = b'"';
    t[0x29] = b'~';
    t[0x2B] = b'|';
    t[0x2C] = b'Z';
    t[0x2D] = b'X';
    t[0x2E] = b'C';
    t[0x2F] = b'V';
    t[0x30] = b'B';
    t[0x31] = b'N';
    t[0x32] = b'M';
    t[0x33] = b'<';
    t[0x34] = b'>';
    t[0x35] = b'?';
    t[0x37] = b'*';
    t[0x39] = b' ';
    t
};

/// Internal keyboard state
struct KbdState {
    modifiers: u8,
    got_e0: bool,
}

static mut KBD: KbdState = KbdState {
    modifiers: 0,
    got_e0: false,
};

/// Initialise the PS/2 port: drain stale bytes + enable keyboard interrupt.
pub fn init() {
    drain_input();

    // Enable the keyboard interrupt on the PS/2 controller.
    // Read Configuration Byte (command 0x20), set bit 0 (IRQ1 enable),
    // write back (command 0x60).
    unsafe {
        // Tell the keyboard controller we want to read the config byte.
        // Need to wait for the controller to be ready first.
        wait_write();
        core::arch::asm!("out dx, al", in("dx") 0x64u16, in("al") 0x20u8,
            options(nostack, preserves_flags));
        wait_read();
        let mut cfg: u8;
        core::arch::asm!("in al, dx", out("al") cfg, in("dx") 0x60u16,
            options(nostack, preserves_flags));

        cfg |= 0x01; // enable keyboard interrupt

        // Write config byte back
        wait_write();
        core::arch::asm!("out dx, al", in("dx") 0x64u16, in("al") 0x60u8,
            options(nostack, preserves_flags));
        wait_write();
        core::arch::asm!("out dx, al", in("dx") 0x60u16, in("al") cfg,
            options(nostack, preserves_flags));
    }
}

/// Wait until the PS/2 controller is ready to receive a command.
fn wait_write() {
    unsafe {
        loop {
            let status: u8;
            core::arch::asm!("in al, dx", out("al") status, in("dx") 0x64u16,
                options(nostack, preserves_flags));
            if status & 0x02 == 0 {
                // Input buffer empty — controller ready to receive
                break;
            }
        }
    }
}

/// Wait until the PS/2 controller has data available to read.
fn wait_read() {
    unsafe {
        loop {
            let status: u8;
            core::arch::asm!("in al, dx", out("al") status, in("dx") 0x64u16,
                options(nostack, preserves_flags));
            if status & 0x01 != 0 {
                // Output buffer full — data ready to read
                break;
            }
        }
    }
}

fn drain_input() {
    unsafe {
        loop {
            let status: u8;
            core::arch::asm!("in al, dx", out("al") status, in("dx") STATUS_PORT,
                options(nostack, preserves_flags));
            if status & STAT_OUTPUT_FULL == 0 {
                break;
            }
            let _data: u8;
            core::arch::asm!("in al, dx", out("al") _data, in("dx") DATA_PORT,
                options(nostack, preserves_flags));
        }
    }
}

/// Poll for a key event. Blocks via `hlt` until a key is pressed.
/// The keyboard interrupt handler pushes raw scancodes to a ring buffer;
/// this function pops and decodes them.
pub fn poll_key() -> KeyEvent {
    loop {
        if let Some(byte) = crate::interrupts::read_scancode() {
            if let Some(ev) = process_byte(byte) {
                return ev;
            }
        } else {
            unsafe {
                core::arch::asm!("sti; hlt", options(nostack, preserves_flags));
            }
        }
    }
}

/// Non-blocking poll — read from the interrupt ring buffer if available.
pub fn try_poll_key() -> Option<KeyEvent> {
    let byte = crate::interrupts::read_scancode()?;
    process_byte(byte)
}

/// Process a single scancode byte. Returns Some(KeyEvent) when a visible
/// event happens; returns None for modifier changes, releases, and prefixes.
fn process_byte(byte: u8) -> Option<KeyEvent> {
    let state = unsafe { &mut KBD };

    if byte == 0xE0 {
        state.got_e0 = true;
        return None;
    }

    if state.got_e0 {
        state.got_e0 = false;
        return process_e0(byte);
    }

    // Break code (key release) — bit 7 set
    if byte & 0x80 != 0 {
        update_modifiers(byte & 0x7F, false, false);
        return None;
    }

    // Make code (key press)
    update_modifiers(byte, true, false);

    match byte {
        0x01 => Some(KeyEvent::Escape),
        0x0E => Some(KeyEvent::Backspace),
        0x0F => Some(KeyEvent::Tab),
        0x1C => Some(KeyEvent::Enter),
        0x37 => Some(KeyEvent::Char('*')),
        0x3B..=0x44 => Some(KeyEvent::F(byte - 0x3B + 1)),
        _ => {
            let shifted = (state.modifiers & (MOD_LSHIFT | MOD_RSHIFT)) != 0;
            // CapsLock inverts case for letters
            let caps = state.modifiers & MOD_CAPS != 0;
            let table = if shifted { SCAN_SHIFT } else { SCAN_NORMAL };
            let mut ch = table[byte as usize];
            // Handle CapsLock for letters
            if caps && ch.is_ascii_alphabetic() {
                // Swap case: if table gives lowercase, make uppercase; etc.
                // Since normal table has lowercase, shift table has uppercase:
                ch = if shifted {
                    ch.to_ascii_lowercase()
                } else {
                    ch.to_ascii_uppercase()
                };
            }
            if ch != 0 {
                Some(KeyEvent::Char(ch as char))
            } else {
                Some(KeyEvent::Unknown(byte))
            }
        }
    }
}

/// Process an E0-prefixed scancode.
fn process_e0(byte: u8) -> Option<KeyEvent> {
    if byte & 0x80 != 0 {
        update_modifiers(byte & 0x7F, false, true);
        return None;
    }

    update_modifiers(byte, true, true);

    match byte {
        0x48 => Some(KeyEvent::ArrowUp),
        0x50 => Some(KeyEvent::ArrowDown),
        0x4B => Some(KeyEvent::ArrowLeft),
        0x4D => Some(KeyEvent::ArrowRight),
        0x47 => Some(KeyEvent::Home),
        0x4F => Some(KeyEvent::End),
        0x49 => Some(KeyEvent::PageUp),
        0x51 => Some(KeyEvent::PageDown),
        0x53 => Some(KeyEvent::Delete),
        0x35 => Some(KeyEvent::Char('/')),
        _ => Some(KeyEvent::Unknown(byte)),
    }
}

fn update_modifiers(scancode: u8, pressed: bool, e0: bool) {
    let state = unsafe { &mut KBD };
    match (scancode, e0) {
        (0x2A, false) => set_mod(state, MOD_LSHIFT, pressed),
        (0x36, false) => set_mod(state, MOD_RSHIFT, pressed),
        (0x1D, false) => set_mod(state, MOD_LCTRL, pressed),
        (0x1D, true) => set_mod(state, MOD_RCTRL, pressed),
        (0x38, false) => set_mod(state, MOD_LALT, pressed),
        (0x38, true) => set_mod(state, MOD_RALT, pressed),
        (0x3A, false)
            if pressed => {
                state.modifiers ^= MOD_CAPS;
            }
        _ => {}
    }
}

fn set_mod(state: &mut KbdState, bit: u8, pressed: bool) {
    if pressed {
        state.modifiers |= bit;
    } else {
        state.modifiers &= !bit;
    }
}