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
mod keyboard;
mod mouse;
mod ps2;

use alloc::sync::Arc;
use core::fmt;

use crate::{
    cpu::{
        self,
        idt::{BasicInterruptHandler, InterruptStackFrame64},
        interrupts::apic,
    },
    sync::{once::OnceLock, spin::mutex::Mutex},
};

pub use kernel_user_link::{keyboard::Key, mouse::MouseEvent};

use self::{
    keyboard::{Keyboard, KEYBOARD_INT_NUM},
    mouse::{Mouse, MOUSE_INT_NUM},
    ps2::status,
};

pub use self::{keyboard::KeyboardReader, mouse::MouseReader};

use super::Device;

static KEYBOARD_MOUSE: OnceLock<KeyboardMouse> = OnceLock::new();

pub fn init_device() {
    let device = KeyboardMouse::new();

    KEYBOARD_MOUSE
        .set(device)
        .unwrap_or_else(|_| panic!("keyboard-mouse already initialized"));

    // assign after we have assigned the device
    apic::assign_io_irq(
        ps2_interrupt_handler as BasicInterruptHandler,
        KEYBOARD_INT_NUM,
        cpu::cpu(),
    );
    apic::assign_io_irq(
        ps2_interrupt_handler as BasicInterruptHandler,
        MOUSE_INT_NUM,
        cpu::cpu(),
    );
}

pub fn poll_events() {
    KEYBOARD_MOUSE.try_get().map(KeyboardMouse::read_all_events);
}

pub fn get_keyboard_reader() -> KeyboardReader {
    KEYBOARD_MOUSE.get().get_keyboard_reader()
}

pub fn get_mouse_reader() -> MouseReader {
    KEYBOARD_MOUSE.get().get_mouse_reader()
}

pub fn reset_system() -> ! {
    KEYBOARD_MOUSE.get().ps2.reset_system();
}

// A mini keyboard driver/mapper
pub struct KeyboardMouse {
    keyboard: Keyboard,
    mouse: Mouse,
    ps2: ps2::Ps2,
}

impl fmt::Debug for KeyboardMouse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Keyboard").finish()
    }
}

impl KeyboardMouse {
    pub fn new() -> KeyboardMouse {
        let ps2 = ps2::Ps2;
        let keyboard = Keyboard::new(ps2);
        let mouse = Mouse::new(ps2);

        KeyboardMouse {
            keyboard,
            mouse,
            ps2,
        }
    }

    fn fetch_next_data(&self) -> bool {
        let status = self.ps2.read_status();

        if status & status::DATA_READY == 0 {
            return false;
        }

        if status & status::PARITY_ERROR != 0 {
            // ignore the data
            self.ps2.read_data();
            return false;
        }

        if status & status::KEYBOARD_TIMEOUT_MOUSE_DATA != 0 {
            self.mouse.handle_mouse_data();
        } else {
            self.keyboard.handle_keyboard_data();
        }

        true
    }

    fn read_all_events(&self) {
        while self.fetch_next_data() {
            // keep fetching
        }
    }

    pub fn get_keyboard_reader(&self) -> KeyboardReader {
        self.keyboard.new_receiver()
    }

    #[allow(dead_code)]
    pub fn get_mouse_reader(&self) -> MouseReader {
        self.mouse.new_receiver()
    }
}

extern "x86-interrupt" fn ps2_interrupt_handler(_stack_frame: InterruptStackFrame64) {
    poll_events();
    apic::return_from_interrupt();
}

// Virtual devices
// -------------------

/// This is just a helper definition, and should not be used directly in any file
#[derive(Debug)]
pub struct KeyboardDeviceCreator;

impl Device for KeyboardDeviceCreator {
    fn name(&self) -> &str {
        "keyboard"
    }

    fn clone_device(&self) -> Result<(), crate::fs::FileSystemError> {
        Err(crate::fs::FileSystemError::OperationNotSupported)
    }

    fn try_create(&self) -> Option<Result<Arc<dyn Device>, crate::fs::FileSystemError>> {
        Some(Ok(Arc::new(KeyboardDevice {
            reader: Mutex::new(get_keyboard_reader()),
        })))
    }
}

pub struct KeyboardDevice {
    reader: Mutex<KeyboardReader>,
}

impl fmt::Debug for KeyboardDevice {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "KeyboardDevice")
    }
}

impl Device for KeyboardDevice {
    fn name(&self) -> &str {
        "keyboard_instance"
    }

    fn read(&self, _offset: u64, buf: &mut [u8]) -> Result<u64, crate::fs::FileSystemError> {
        if buf.len() < Key::BYTES_SIZE {
            return Err(crate::fs::FileSystemError::BufferNotLargeEnough(
                Key::BYTES_SIZE,
            ));
        }

        let mut reader = self.reader.lock();

        let mut i = 0;

        while i + Key::BYTES_SIZE <= buf.len() {
            if let Some(key) = reader.recv() {
                let key_bytes = key.as_bytes();
                buf[i..i + Key::BYTES_SIZE].copy_from_slice(&key_bytes);
                i += Key::BYTES_SIZE;
            } else {
                break;
            }
        }

        Ok(i as u64)
    }
}

#[derive(Debug)]
pub struct MouseDeviceCreator;

impl Device for MouseDeviceCreator {
    fn name(&self) -> &str {
        "mouse"
    }

    fn clone_device(&self) -> Result<(), crate::fs::FileSystemError> {
        Err(crate::fs::FileSystemError::OperationNotSupported)
    }

    fn try_create(&self) -> Option<Result<Arc<dyn Device>, crate::fs::FileSystemError>> {
        Some(Ok(Arc::new(MouseDevice {
            reader: Mutex::new(get_mouse_reader()),
        })))
    }
}

pub struct MouseDevice {
    reader: Mutex<MouseReader>,
}

impl fmt::Debug for MouseDevice {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "MouseDevice")
    }
}

impl Device for MouseDevice {
    fn name(&self) -> &str {
        "mouse_instance"
    }

    fn read(&self, _offset: u64, buf: &mut [u8]) -> Result<u64, crate::fs::FileSystemError> {
        if buf.len() < MouseEvent::BYTES_SIZE {
            return Err(crate::fs::FileSystemError::BufferNotLargeEnough(
                MouseEvent::BYTES_SIZE,
            ));
        }

        let mut reader = self.reader.lock();

        let mut i = 0;

        while i + MouseEvent::BYTES_SIZE <= buf.len() {
            if let Some(mouse_event) = reader.recv() {
                let event_bytes = mouse_event.as_bytes();
                buf[i..i + MouseEvent::BYTES_SIZE].copy_from_slice(&event_bytes);
                i += MouseEvent::BYTES_SIZE;
            } else {
                break;
            }
        }

        Ok(i as u64)
    }
}