xref: /DragonOS/kernel/src/driver/input/ps2_mouse/ps_mouse_device.rs (revision fae6e9ade46a52976ad5d099643d51cc20876448)
1 use core::hint::spin_loop;
2 
3 use alloc::{
4     string::ToString,
5     sync::{Arc, Weak},
6     vec::Vec,
7 };
8 use kdepends::ringbuffer::{AllocRingBuffer, RingBuffer};
9 use log::{debug, error};
10 use system_error::SystemError;
11 
12 use crate::{
13     arch::{io::PortIOArch, CurrentIrqArch, CurrentPortIOArch},
14     driver::{
15         base::{
16             class::Class,
17             device::{
18                 bus::Bus, device_manager, device_number::DeviceNumber, driver::Driver, Device,
19                 DeviceCommonData, DeviceType, IdTable,
20             },
21             kobject::{KObjType, KObject, KObjectCommonData, KObjectState, LockedKObjectState},
22             kset::KSet,
23         },
24         input::{
25             ps2_dev::ps2_device::Ps2Device,
26             serio::serio_device::{serio_device_manager, SerioDevice},
27         },
28     },
29     exception::InterruptArch,
30     filesystem::{
31         devfs::{devfs_register, DevFS, DeviceINode},
32         kernfs::KernFSInode,
33         vfs::{
34             core::generate_inode_id, syscall::ModeType, utils::DName, FilePrivateData, FileSystem,
35             FileType, IndexNode, Metadata,
36         },
37     },
38     libs::{
39         rwlock::{RwLockReadGuard, RwLockWriteGuard},
40         spinlock::{SpinLock, SpinLockGuard},
41     },
42     time::PosixTimeSpec,
43 };
44 
45 static mut PS2_MOUSE_DEVICE: Option<Arc<Ps2MouseDevice>> = None;
46 
47 pub fn ps2_mouse_device() -> Option<Arc<Ps2MouseDevice>> {
48     unsafe { PS2_MOUSE_DEVICE.clone() }
49 }
50 
51 const ADDRESS_PORT_ADDRESS: u16 = 0x64;
52 const DATA_PORT_ADDRESS: u16 = 0x60;
53 
54 const KEYBOARD_COMMAND_ENABLE_PS2_MOUSE_PORT: u8 = 0xa8;
55 const KEYBOARD_COMMAND_SEND_TO_PS2_MOUSE: u8 = 0xd4;
56 
57 const MOUSE_BUFFER_CAPACITY: usize = 15;
58 
59 bitflags! {
60     /// Represents the flags currently set for the mouse.
61     #[derive(Default)]
62     pub struct MouseFlags: u8 {
63         /// Whether or not the left mouse button is pressed.
64         const LEFT_BUTTON = 0b0000_0001;
65 
66         /// Whether or not the right mouse button is pressed.
67         const RIGHT_BUTTON = 0b0000_0010;
68 
69         /// Whether or not the middle mouse button is pressed.
70         const MIDDLE_BUTTON = 0b0000_0100;
71 
72         /// Whether or not the packet is valid or not.
73         const ALWAYS_ONE = 0b0000_1000;
74 
75         /// Whether or not the x delta is negative.
76         const X_SIGN = 0b0001_0000;
77 
78         /// Whether or not the y delta is negative.
79         const Y_SIGN = 0b0010_0000;
80 
81         /// Whether or not the x delta overflowed.
82         const X_OVERFLOW = 0b0100_0000;
83 
84         /// Whether or not the y delta overflowed.
85         const Y_OVERFLOW = 0b1000_0000;
86     }
87 }
88 
89 #[derive(Debug)]
90 enum PsMouseCommand {
91     SampleRate(u8),
92     EnablePacketStreaming,
93     // SetDefaults = 0xF6,
94     InitKeyboard,
95     GetMouseId,
96     SetSampleRate,
97 }
98 
99 impl From<PsMouseCommand> for u8 {
100     fn from(val: PsMouseCommand) -> Self {
101         match val {
102             PsMouseCommand::SampleRate(x) => x,
103             PsMouseCommand::EnablePacketStreaming => 0xf4,
104             PsMouseCommand::InitKeyboard => 0x47,
105             PsMouseCommand::GetMouseId => 0xf2,
106             PsMouseCommand::SetSampleRate => 0xf3,
107         }
108     }
109 }
110 
111 #[derive(Debug)]
112 pub struct MouseState {
113     flags: MouseFlags,
114     x: i16,
115     y: i16,
116 }
117 
118 #[allow(dead_code)]
119 impl MouseState {
120     /// Returns a new `MouseState`.
121     pub const fn new() -> MouseState {
122         MouseState {
123             flags: MouseFlags::empty(),
124             x: 0,
125             y: 0,
126         }
127     }
128 
129     /// Returns true if the left mouse button is currently down.
130     pub fn left_button_down(&self) -> bool {
131         self.flags.contains(MouseFlags::LEFT_BUTTON)
132     }
133 
134     /// Returns true if the left mouse button is currently up.
135     pub fn left_button_up(&self) -> bool {
136         !self.flags.contains(MouseFlags::LEFT_BUTTON)
137     }
138 
139     /// Returns true if the right mouse button is currently down.
140     pub fn right_button_down(&self) -> bool {
141         self.flags.contains(MouseFlags::RIGHT_BUTTON)
142     }
143 
144     /// Returns true if the right mouse button is currently up.
145     pub fn right_button_up(&self) -> bool {
146         !self.flags.contains(MouseFlags::RIGHT_BUTTON)
147     }
148 
149     /// Returns true if the x axis has moved.
150     pub fn x_moved(&self) -> bool {
151         self.x != 0
152     }
153 
154     /// Returns true if the y axis has moved.
155     pub fn y_moved(&self) -> bool {
156         self.y != 0
157     }
158 
159     /// Returns true if the x or y axis has moved.
160     pub fn moved(&self) -> bool {
161         self.x_moved() || self.y_moved()
162     }
163 
164     /// Returns the x delta of the mouse state.
165     pub fn get_x(&self) -> i16 {
166         self.x
167     }
168 
169     /// Returns the y delta of the mouse state.
170     pub fn get_y(&self) -> i16 {
171         self.y
172     }
173 }
174 
175 #[derive(Debug)]
176 #[cast_to([sync] Device, SerioDevice)]
177 pub struct Ps2MouseDevice {
178     inner: SpinLock<InnerPs2MouseDevice>,
179     kobj_state: LockedKObjectState,
180 }
181 
182 impl Ps2MouseDevice {
183     pub const NAME: &'static str = "psmouse";
184     pub fn new() -> Self {
185         let r = Self {
186             inner: SpinLock::new(InnerPs2MouseDevice {
187                 device_common: DeviceCommonData::default(),
188                 kobject_common: KObjectCommonData::default(),
189                 current_packet: 0,
190                 current_state: MouseState::new(),
191                 buf: AllocRingBuffer::new(MOUSE_BUFFER_CAPACITY),
192                 devfs_metadata: Metadata {
193                     dev_id: 1,
194                     inode_id: generate_inode_id(),
195                     size: 4096,
196                     blk_size: 0,
197                     blocks: 0,
198                     atime: PosixTimeSpec::default(),
199                     mtime: PosixTimeSpec::default(),
200                     ctime: PosixTimeSpec::default(),
201                     file_type: FileType::CharDevice, // 文件夹,block设备,char设备
202                     mode: ModeType::from_bits_truncate(0o644),
203                     nlinks: 1,
204                     uid: 0,
205                     gid: 0,
206                     raw_dev: DeviceNumber::default(), // 这里用来作为device number
207                 },
208                 device_inode_fs: None,
209             }),
210             kobj_state: LockedKObjectState::new(None),
211         };
212         return r;
213     }
214 
215     pub fn init(&self) -> Result<(), SystemError> {
216         let _irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
217 
218         self.write_control_port(KEYBOARD_COMMAND_ENABLE_PS2_MOUSE_PORT)?;
219         for _i in 0..1000 {
220             for _j in 0..1000 {
221                 spin_loop();
222             }
223         }
224         self.read_data_port().ok();
225 
226         self.send_command_to_ps2mouse(PsMouseCommand::EnablePacketStreaming)
227             .map_err(|e| {
228                 error!("ps2 mouse init error: {:?}", e);
229                 e
230             })?;
231         self.read_data_port().ok();
232         for _i in 0..1000 {
233             for _j in 0..1000 {
234                 spin_loop();
235             }
236         }
237 
238         // self.send_command_to_ps2mouse(PsMouseCommand::InitKeyboard)?;
239         self.do_send_command(DATA_PORT_ADDRESS as u8, PsMouseCommand::InitKeyboard.into())?;
240         self.read_data_port().ok();
241         for _i in 0..1000 {
242             for _j in 0..1000 {
243                 spin_loop();
244             }
245         }
246 
247         self.set_sample_rate(20)?;
248         // self.get_mouse_id()?;
249         Ok(())
250     }
251 
252     #[allow(dead_code)]
253     pub fn get_mouse_id(&self) -> Result<(), SystemError> {
254         self.send_command_to_ps2mouse(PsMouseCommand::GetMouseId)?;
255         let _mouse_id = self.read_data_port()?;
256         Ok(())
257     }
258 
259     /// 设置鼠标采样率
260     ///
261     /// `hz` 合法值为 10,20,40,60,80,100,200
262     pub fn set_sample_rate(&self, hz: u8) -> Result<(), SystemError> {
263         const SAMPLE_RATE: [u8; 7] = [10, 20, 40, 60, 80, 100, 200];
264         if !SAMPLE_RATE.contains(&hz) {
265             return Err(SystemError::EINVAL);
266         }
267 
268         self.send_command_to_ps2mouse(PsMouseCommand::SetSampleRate)?;
269         self.read_data_port().ok();
270         for _i in 0..1000 {
271             for _j in 0..1000 {
272                 spin_loop();
273             }
274         }
275 
276         self.send_command_to_ps2mouse(PsMouseCommand::SampleRate(hz))?;
277         for _i in 0..1000 {
278             for _j in 0..1000 {
279                 spin_loop();
280             }
281         }
282         self.read_data_port().ok();
283         Ok(())
284     }
285 
286     /// # 函数的功能
287     /// 鼠标设备处理数据包
288     pub fn process_packet(&self) -> Result<(), SystemError> {
289         let packet = self.read_data_port()?;
290         let mut guard = self.inner.lock();
291         guard.buf.push(packet); // 更新缓冲区
292         match guard.current_packet {
293             0 => {
294                 let flags: MouseFlags = MouseFlags::from_bits_truncate(packet);
295                 if !flags.contains(MouseFlags::ALWAYS_ONE) {
296                     return Ok(());
297                 }
298                 guard.current_state.flags = flags;
299             }
300             1 => {
301                 let flags = guard.current_state.flags;
302                 if !flags.contains(MouseFlags::X_OVERFLOW) {
303                     guard.current_state.x = self.get_x_movement(packet, flags);
304                 }
305             }
306             2 => {
307                 let flags = guard.current_state.flags;
308                 if !flags.contains(MouseFlags::Y_OVERFLOW) {
309                     guard.current_state.y = self.get_y_movement(packet, flags);
310                 }
311 
312                 // debug!(
313                 //     "Ps2MouseDevice packet : flags:{}, x:{}, y:{}\n",
314                 //     guard.current_state.flags.bits,
315                 //     guard.current_state.x,
316                 //     guard.current_state.y
317                 // );
318             }
319             _ => unreachable!(),
320         }
321         guard.current_packet = (guard.current_packet + 1) % 3;
322         Ok(())
323     }
324 
325     fn get_x_movement(&self, packet: u8, flags: MouseFlags) -> i16 {
326         if flags.contains(MouseFlags::X_SIGN) {
327             return self.sign_extend(packet);
328         } else {
329             return packet as i16;
330         }
331     }
332 
333     fn get_y_movement(&self, packet: u8, flags: MouseFlags) -> i16 {
334         if flags.contains(MouseFlags::Y_SIGN) {
335             return self.sign_extend(packet);
336         } else {
337             return packet as i16;
338         }
339     }
340 
341     fn sign_extend(&self, packet: u8) -> i16 {
342         ((packet as u16) | 0xFF00) as i16
343     }
344 
345     fn read_data_port(&self) -> Result<u8, SystemError> {
346         self.wait_for_write()?;
347         let cmd = unsafe { CurrentPortIOArch::in8(ADDRESS_PORT_ADDRESS) };
348         if (cmd & 0x21) == 0x21 {
349             let data = unsafe { CurrentPortIOArch::in8(DATA_PORT_ADDRESS) };
350             return Ok(data);
351         } else {
352             return Err(SystemError::ENODATA);
353         }
354     }
355 
356     #[inline(never)]
357     fn send_command_to_ps2mouse(&self, command: PsMouseCommand) -> Result<(), SystemError> {
358         self.do_send_command(KEYBOARD_COMMAND_SEND_TO_PS2_MOUSE, command.into())?;
359         Ok(())
360     }
361 
362     #[inline(never)]
363     fn do_send_command(&self, ctrl: u8, command: u8) -> Result<(), SystemError> {
364         self.write_control_port(ctrl)?;
365         self.write_data_port(command)?;
366         return Ok(());
367     }
368 
369     fn write_data_port(&self, data: u8) -> Result<(), SystemError> {
370         self.wait_for_write()?;
371         unsafe {
372             CurrentPortIOArch::out8(DATA_PORT_ADDRESS, data);
373         }
374         Ok(())
375     }
376 
377     fn write_control_port(&self, command: u8) -> Result<(), SystemError> {
378         self.wait_for_write()?;
379         unsafe {
380             CurrentPortIOArch::out8(ADDRESS_PORT_ADDRESS, command);
381         }
382         Ok(())
383     }
384 
385     #[allow(dead_code)]
386     fn wait_for_read(&self) -> Result<(), SystemError> {
387         let timeout = 100_000;
388         for _ in 0..timeout {
389             let value = unsafe { CurrentPortIOArch::in8(ADDRESS_PORT_ADDRESS) };
390             if (value & 0x1) == 0x1 {
391                 return Ok(());
392             }
393         }
394         Err(SystemError::ETIMEDOUT)
395     }
396 
397     fn wait_for_write(&self) -> Result<(), SystemError> {
398         let timeout = 100_000;
399         for _ in 0..timeout {
400             let value = unsafe { CurrentPortIOArch::in8(ADDRESS_PORT_ADDRESS) };
401             if (value & 0x2) == 0 {
402                 return Ok(());
403             }
404         }
405         Err(SystemError::ETIMEDOUT)
406     }
407 
408     fn inner(&self) -> SpinLockGuard<InnerPs2MouseDevice> {
409         self.inner.lock_irqsave()
410     }
411 }
412 
413 #[derive(Debug)]
414 struct InnerPs2MouseDevice {
415     device_common: DeviceCommonData,
416     kobject_common: KObjectCommonData,
417 
418     /// 鼠标数据
419     current_state: MouseState,
420     current_packet: u8,
421     /// 鼠标数据环形缓冲区
422     buf: AllocRingBuffer<u8>,
423 
424     /// device inode要求的字段
425     device_inode_fs: Option<Weak<DevFS>>,
426     devfs_metadata: Metadata,
427 }
428 
429 impl Device for Ps2MouseDevice {
430     fn is_dead(&self) -> bool {
431         false
432     }
433 
434     fn dev_type(&self) -> DeviceType {
435         DeviceType::Char
436     }
437 
438     fn id_table(&self) -> IdTable {
439         IdTable::new(self.name().to_string(), None)
440     }
441 
442     fn set_bus(&self, bus: Option<alloc::sync::Weak<dyn Bus>>) {
443         self.inner().device_common.bus = bus;
444     }
445 
446     fn set_class(&self, class: Option<alloc::sync::Weak<dyn Class>>) {
447         self.inner().device_common.class = class;
448     }
449 
450     fn driver(&self) -> Option<alloc::sync::Arc<dyn Driver>> {
451         self.inner().device_common.driver.clone()?.upgrade()
452     }
453 
454     fn set_driver(&self, driver: Option<alloc::sync::Weak<dyn Driver>>) {
455         self.inner().device_common.driver = driver;
456     }
457 
458     fn can_match(&self) -> bool {
459         true
460     }
461 
462     fn set_can_match(&self, _can_match: bool) {}
463 
464     fn state_synced(&self) -> bool {
465         true
466     }
467 
468     fn bus(&self) -> Option<alloc::sync::Weak<dyn Bus>> {
469         self.inner().device_common.bus.clone()
470     }
471 
472     fn class(&self) -> Option<Arc<dyn Class>> {
473         let mut guard = self.inner();
474         let r = guard.device_common.class.clone()?.upgrade();
475         if r.is_none() {
476             guard.device_common.class = None;
477         }
478 
479         return r;
480     }
481 
482     fn dev_parent(&self) -> Option<alloc::sync::Weak<dyn Device>> {
483         self.inner().device_common.get_parent_weak_or_clear()
484     }
485 
486     fn set_dev_parent(&self, dev_parent: Option<alloc::sync::Weak<dyn Device>>) {
487         self.inner().device_common.parent = dev_parent;
488     }
489 }
490 
491 impl SerioDevice for Ps2MouseDevice {
492     fn write(
493         &self,
494         _device: &alloc::sync::Arc<dyn SerioDevice>,
495         _data: u8,
496     ) -> Result<(), system_error::SystemError> {
497         todo!()
498     }
499 
500     fn open(
501         &self,
502         _device: &alloc::sync::Arc<dyn SerioDevice>,
503     ) -> Result<(), system_error::SystemError> {
504         todo!()
505     }
506 
507     fn close(
508         &self,
509         _device: &alloc::sync::Arc<dyn SerioDevice>,
510     ) -> Result<(), system_error::SystemError> {
511         todo!()
512     }
513 
514     fn start(
515         &self,
516         _device: &alloc::sync::Arc<dyn SerioDevice>,
517     ) -> Result<(), system_error::SystemError> {
518         todo!()
519     }
520 
521     fn stop(
522         &self,
523         _device: &alloc::sync::Arc<dyn SerioDevice>,
524     ) -> Result<(), system_error::SystemError> {
525         todo!()
526     }
527 }
528 
529 impl KObject for Ps2MouseDevice {
530     fn as_any_ref(&self) -> &dyn core::any::Any {
531         self
532     }
533 
534     fn set_inode(&self, inode: Option<alloc::sync::Arc<KernFSInode>>) {
535         self.inner().kobject_common.kern_inode = inode;
536     }
537 
538     fn inode(&self) -> Option<alloc::sync::Arc<KernFSInode>> {
539         self.inner().kobject_common.kern_inode.clone()
540     }
541 
542     fn parent(&self) -> Option<alloc::sync::Weak<dyn KObject>> {
543         self.inner().kobject_common.parent.clone()
544     }
545 
546     fn set_parent(&self, parent: Option<alloc::sync::Weak<dyn KObject>>) {
547         self.inner().kobject_common.parent = parent
548     }
549 
550     fn kset(&self) -> Option<alloc::sync::Arc<KSet>> {
551         self.inner().kobject_common.kset.clone()
552     }
553 
554     fn set_kset(&self, kset: Option<alloc::sync::Arc<KSet>>) {
555         self.inner().kobject_common.kset = kset;
556     }
557 
558     fn kobj_type(&self) -> Option<&'static dyn KObjType> {
559         self.inner().kobject_common.kobj_type
560     }
561 
562     fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
563         self.inner().kobject_common.kobj_type = ktype;
564     }
565 
566     fn name(&self) -> alloc::string::String {
567         Self::NAME.to_string()
568     }
569 
570     fn set_name(&self, _name: alloc::string::String) {}
571 
572     fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
573         self.kobj_state.read()
574     }
575 
576     fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
577         self.kobj_state.write()
578     }
579 
580     fn set_kobj_state(&self, state: KObjectState) {
581         *self.kobj_state.write() = state;
582     }
583 }
584 
585 impl DeviceINode for Ps2MouseDevice {
586     fn set_fs(&self, fs: Weak<DevFS>) {
587         self.inner.lock_irqsave().device_inode_fs = Some(fs);
588     }
589 }
590 
591 impl IndexNode for Ps2MouseDevice {
592     fn open(
593         &self,
594         _data: SpinLockGuard<FilePrivateData>,
595         _mode: &crate::filesystem::vfs::file::FileMode,
596     ) -> Result<(), SystemError> {
597         let mut guard = self.inner.lock_irqsave();
598         guard.buf.clear();
599         Ok(())
600     }
601 
602     fn close(&self, _data: SpinLockGuard<FilePrivateData>) -> Result<(), SystemError> {
603         let mut guard = self.inner.lock_irqsave();
604         guard.buf.clear();
605         Ok(())
606     }
607 
608     fn read_at(
609         &self,
610         _offset: usize,
611         _len: usize,
612         buf: &mut [u8],
613         _data: SpinLockGuard<FilePrivateData>,
614     ) -> Result<usize, SystemError> {
615         let mut guard = self.inner.lock_irqsave();
616 
617         if guard.buf.len() >= 3 {
618             for item in buf.iter_mut().take(3) {
619                 *item = guard.buf.dequeue().unwrap();
620             }
621             return Ok(3);
622         } else {
623             return Ok(0);
624         }
625     }
626 
627     fn write_at(
628         &self,
629         _offset: usize,
630         _len: usize,
631         _buf: &[u8],
632         _data: SpinLockGuard<FilePrivateData>,
633     ) -> Result<usize, SystemError> {
634         return Err(SystemError::ENOSYS);
635     }
636 
637     fn fs(&self) -> Arc<dyn FileSystem> {
638         self.inner
639             .lock_irqsave()
640             .device_inode_fs
641             .as_ref()
642             .unwrap()
643             .upgrade()
644             .unwrap()
645     }
646 
647     fn as_any_ref(&self) -> &dyn core::any::Any {
648         self
649     }
650 
651     fn list(&self) -> Result<Vec<alloc::string::String>, SystemError> {
652         todo!()
653     }
654 
655     fn metadata(&self) -> Result<Metadata, SystemError> {
656         Ok(self.inner.lock_irqsave().devfs_metadata.clone())
657     }
658 
659     fn resize(&self, _len: usize) -> Result<(), SystemError> {
660         Ok(())
661     }
662 
663     fn dname(&self) -> Result<DName, SystemError> {
664         Ok(DName::from(self.name()))
665     }
666 }
667 
668 impl Ps2Device for Ps2MouseDevice {}
669 
670 pub fn rs_ps2_mouse_device_init(dev_parent: Arc<dyn Device>) -> Result<(), SystemError> {
671     debug!("ps2_mouse_device initializing...");
672     let psmouse = Arc::new(Ps2MouseDevice::new());
673 
674     device_manager().device_default_initialize(&(psmouse.clone() as Arc<dyn Device>));
675     psmouse.set_dev_parent(Some(Arc::downgrade(&dev_parent)));
676     serio_device_manager().register_port(psmouse.clone() as Arc<dyn SerioDevice>)?;
677 
678     devfs_register(&psmouse.name(), psmouse.clone()).map_err(|e| {
679         error!(
680             "register psmouse device '{}' to devfs failed: {:?}",
681             psmouse.name(),
682             e
683         );
684         device_manager().remove(&(psmouse.clone() as Arc<dyn Device>));
685         e
686     })?;
687 
688     unsafe { PS2_MOUSE_DEVICE = Some(psmouse) };
689     return Ok(());
690 }
691