xref: /DragonOS/kernel/src/driver/input/ps2_mouse/ps_mouse_device.rs (revision f79998f626801329580c782fd05e36cb2027f474)
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                 DeviceType, IdTable,
20             },
21             kobject::{KObjType, KObject, 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                 bus: None,
188                 class: None,
189                 driver: None,
190                 kern_inode: None,
191                 parent: None,
192                 kset: None,
193                 kobj_type: None,
194                 current_packet: 0,
195                 current_state: MouseState::new(),
196                 buf: AllocRingBuffer::new(MOUSE_BUFFER_CAPACITY),
197                 devfs_metadata: Metadata {
198                     dev_id: 1,
199                     inode_id: generate_inode_id(),
200                     size: 4096,
201                     blk_size: 0,
202                     blocks: 0,
203                     atime: PosixTimeSpec::default(),
204                     mtime: PosixTimeSpec::default(),
205                     ctime: PosixTimeSpec::default(),
206                     file_type: FileType::CharDevice, // 文件夹,block设备,char设备
207                     mode: ModeType::from_bits_truncate(0o644),
208                     nlinks: 1,
209                     uid: 0,
210                     gid: 0,
211                     raw_dev: DeviceNumber::default(), // 这里用来作为device number
212                 },
213                 device_inode_fs: None,
214             }),
215             kobj_state: LockedKObjectState::new(None),
216         };
217         return r;
218     }
219 
220     pub fn init(&self) -> Result<(), SystemError> {
221         let _irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
222 
223         self.write_control_port(KEYBOARD_COMMAND_ENABLE_PS2_MOUSE_PORT)?;
224         for _i in 0..1000 {
225             for _j in 0..1000 {
226                 spin_loop();
227             }
228         }
229         self.read_data_port().ok();
230 
231         self.send_command_to_ps2mouse(PsMouseCommand::EnablePacketStreaming)
232             .map_err(|e| {
233                 error!("ps2 mouse init error: {:?}", e);
234                 e
235             })?;
236         self.read_data_port().ok();
237         for _i in 0..1000 {
238             for _j in 0..1000 {
239                 spin_loop();
240             }
241         }
242 
243         // self.send_command_to_ps2mouse(PsMouseCommand::InitKeyboard)?;
244         self.do_send_command(DATA_PORT_ADDRESS as u8, PsMouseCommand::InitKeyboard.into())?;
245         self.read_data_port().ok();
246         for _i in 0..1000 {
247             for _j in 0..1000 {
248                 spin_loop();
249             }
250         }
251 
252         self.set_sample_rate(20)?;
253         // self.get_mouse_id()?;
254         Ok(())
255     }
256 
257     #[allow(dead_code)]
258     pub fn get_mouse_id(&self) -> Result<(), SystemError> {
259         self.send_command_to_ps2mouse(PsMouseCommand::GetMouseId)?;
260         let _mouse_id = self.read_data_port()?;
261         Ok(())
262     }
263 
264     /// 设置鼠标采样率
265     ///
266     /// `hz` 合法值为 10,20,40,60,80,100,200
267     pub fn set_sample_rate(&self, hz: u8) -> Result<(), SystemError> {
268         const SAMPLE_RATE: [u8; 7] = [10, 20, 40, 60, 80, 100, 200];
269         if !SAMPLE_RATE.contains(&hz) {
270             return Err(SystemError::EINVAL);
271         }
272 
273         self.send_command_to_ps2mouse(PsMouseCommand::SetSampleRate)?;
274         self.read_data_port().ok();
275         for _i in 0..1000 {
276             for _j in 0..1000 {
277                 spin_loop();
278             }
279         }
280 
281         self.send_command_to_ps2mouse(PsMouseCommand::SampleRate(hz))?;
282         for _i in 0..1000 {
283             for _j in 0..1000 {
284                 spin_loop();
285             }
286         }
287         self.read_data_port().ok();
288         Ok(())
289     }
290 
291     /// # 函数的功能
292     /// 鼠标设备处理数据包
293     pub fn process_packet(&self) -> Result<(), SystemError> {
294         let packet = self.read_data_port()?;
295         let mut guard = self.inner.lock();
296         guard.buf.push(packet); // 更新缓冲区
297         match guard.current_packet {
298             0 => {
299                 let flags: MouseFlags = MouseFlags::from_bits_truncate(packet);
300                 if !flags.contains(MouseFlags::ALWAYS_ONE) {
301                     return Ok(());
302                 }
303                 guard.current_state.flags = flags;
304             }
305             1 => {
306                 let flags = guard.current_state.flags;
307                 if !flags.contains(MouseFlags::X_OVERFLOW) {
308                     guard.current_state.x = self.get_x_movement(packet, flags);
309                 }
310             }
311             2 => {
312                 let flags = guard.current_state.flags;
313                 if !flags.contains(MouseFlags::Y_OVERFLOW) {
314                     guard.current_state.y = self.get_y_movement(packet, flags);
315                 }
316 
317                 // debug!(
318                 //     "Ps2MouseDevice packet : flags:{}, x:{}, y:{}\n",
319                 //     guard.current_state.flags.bits,
320                 //     guard.current_state.x,
321                 //     guard.current_state.y
322                 // );
323             }
324             _ => unreachable!(),
325         }
326         guard.current_packet = (guard.current_packet + 1) % 3;
327         Ok(())
328     }
329 
330     fn get_x_movement(&self, packet: u8, flags: MouseFlags) -> i16 {
331         if flags.contains(MouseFlags::X_SIGN) {
332             return self.sign_extend(packet);
333         } else {
334             return packet as i16;
335         }
336     }
337 
338     fn get_y_movement(&self, packet: u8, flags: MouseFlags) -> i16 {
339         if flags.contains(MouseFlags::Y_SIGN) {
340             return self.sign_extend(packet);
341         } else {
342             return packet as i16;
343         }
344     }
345 
346     fn sign_extend(&self, packet: u8) -> i16 {
347         ((packet as u16) | 0xFF00) as i16
348     }
349 
350     fn read_data_port(&self) -> Result<u8, SystemError> {
351         self.wait_for_write()?;
352         let cmd = unsafe { CurrentPortIOArch::in8(ADDRESS_PORT_ADDRESS) };
353         if (cmd & 0x21) == 0x21 {
354             let data = unsafe { CurrentPortIOArch::in8(DATA_PORT_ADDRESS) };
355             return Ok(data);
356         } else {
357             return Err(SystemError::ENODATA);
358         }
359     }
360 
361     #[inline(never)]
362     fn send_command_to_ps2mouse(&self, command: PsMouseCommand) -> Result<(), SystemError> {
363         self.do_send_command(KEYBOARD_COMMAND_SEND_TO_PS2_MOUSE, command.into())?;
364         Ok(())
365     }
366 
367     #[inline(never)]
368     fn do_send_command(&self, ctrl: u8, command: u8) -> Result<(), SystemError> {
369         self.write_control_port(ctrl)?;
370         self.write_data_port(command)?;
371         return Ok(());
372     }
373 
374     fn write_data_port(&self, data: u8) -> Result<(), SystemError> {
375         self.wait_for_write()?;
376         unsafe {
377             CurrentPortIOArch::out8(DATA_PORT_ADDRESS, data);
378         }
379         Ok(())
380     }
381 
382     fn write_control_port(&self, command: u8) -> Result<(), SystemError> {
383         self.wait_for_write()?;
384         unsafe {
385             CurrentPortIOArch::out8(ADDRESS_PORT_ADDRESS, command);
386         }
387         Ok(())
388     }
389 
390     fn wait_for_read(&self) -> Result<(), SystemError> {
391         let timeout = 100_000;
392         for _ in 0..timeout {
393             let value = unsafe { CurrentPortIOArch::in8(ADDRESS_PORT_ADDRESS) };
394             if (value & 0x1) == 0x1 {
395                 return Ok(());
396             }
397         }
398         Err(SystemError::ETIMEDOUT)
399     }
400 
401     fn wait_for_write(&self) -> Result<(), SystemError> {
402         let timeout = 100_000;
403         for _ in 0..timeout {
404             let value = unsafe { CurrentPortIOArch::in8(ADDRESS_PORT_ADDRESS) };
405             if (value & 0x2) == 0 {
406                 return Ok(());
407             }
408         }
409         Err(SystemError::ETIMEDOUT)
410     }
411 }
412 
413 #[derive(Debug)]
414 struct InnerPs2MouseDevice {
415     bus: Option<Weak<dyn Bus>>,
416     class: Option<Weak<dyn Class>>,
417     driver: Option<Weak<dyn Driver>>,
418     kern_inode: Option<Arc<KernFSInode>>,
419     parent: Option<Weak<dyn KObject>>,
420     kset: Option<Arc<KSet>>,
421     kobj_type: Option<&'static dyn KObjType>,
422 
423     /// 鼠标数据
424     current_state: MouseState,
425     current_packet: u8,
426     /// 鼠标数据环形缓冲区
427     buf: AllocRingBuffer<u8>,
428 
429     /// device inode要求的字段
430     device_inode_fs: Option<Weak<DevFS>>,
431     devfs_metadata: Metadata,
432 }
433 
434 impl Device for Ps2MouseDevice {
435     fn is_dead(&self) -> bool {
436         false
437     }
438 
439     fn dev_type(&self) -> DeviceType {
440         DeviceType::Char
441     }
442 
443     fn id_table(&self) -> IdTable {
444         IdTable::new(self.name().to_string(), None)
445     }
446 
447     fn set_bus(&self, bus: Option<alloc::sync::Weak<dyn Bus>>) {
448         self.inner.lock_irqsave().bus = bus;
449     }
450 
451     fn set_class(&self, class: Option<alloc::sync::Weak<dyn Class>>) {
452         self.inner.lock_irqsave().class = class;
453     }
454 
455     fn driver(&self) -> Option<alloc::sync::Arc<dyn Driver>> {
456         self.inner.lock_irqsave().driver.clone()?.upgrade()
457     }
458 
459     fn set_driver(&self, driver: Option<alloc::sync::Weak<dyn Driver>>) {
460         self.inner.lock_irqsave().driver = driver;
461     }
462 
463     fn can_match(&self) -> bool {
464         true
465     }
466 
467     fn set_can_match(&self, _can_match: bool) {}
468 
469     fn state_synced(&self) -> bool {
470         true
471     }
472 
473     fn bus(&self) -> Option<alloc::sync::Weak<dyn Bus>> {
474         self.inner.lock_irqsave().bus.clone()
475     }
476 
477     fn class(&self) -> Option<Arc<dyn Class>> {
478         let mut guard = self.inner.lock_irqsave();
479         let r = guard.class.clone()?.upgrade();
480         if r.is_none() {
481             guard.class = None;
482         }
483 
484         return r;
485     }
486 }
487 
488 impl SerioDevice for Ps2MouseDevice {
489     fn write(
490         &self,
491         _device: &alloc::sync::Arc<dyn SerioDevice>,
492         _data: u8,
493     ) -> Result<(), system_error::SystemError> {
494         todo!()
495     }
496 
497     fn open(
498         &self,
499         _device: &alloc::sync::Arc<dyn SerioDevice>,
500     ) -> Result<(), system_error::SystemError> {
501         todo!()
502     }
503 
504     fn close(
505         &self,
506         _device: &alloc::sync::Arc<dyn SerioDevice>,
507     ) -> Result<(), system_error::SystemError> {
508         todo!()
509     }
510 
511     fn start(
512         &self,
513         _device: &alloc::sync::Arc<dyn SerioDevice>,
514     ) -> Result<(), system_error::SystemError> {
515         todo!()
516     }
517 
518     fn stop(
519         &self,
520         _device: &alloc::sync::Arc<dyn SerioDevice>,
521     ) -> Result<(), system_error::SystemError> {
522         todo!()
523     }
524 }
525 
526 impl KObject for Ps2MouseDevice {
527     fn as_any_ref(&self) -> &dyn core::any::Any {
528         self
529     }
530 
531     fn set_inode(&self, inode: Option<alloc::sync::Arc<KernFSInode>>) {
532         self.inner.lock_irqsave().kern_inode = inode;
533     }
534 
535     fn inode(&self) -> Option<alloc::sync::Arc<KernFSInode>> {
536         self.inner.lock_irqsave().kern_inode.clone()
537     }
538 
539     fn parent(&self) -> Option<alloc::sync::Weak<dyn KObject>> {
540         self.inner.lock_irqsave().parent.clone()
541     }
542 
543     fn set_parent(&self, parent: Option<alloc::sync::Weak<dyn KObject>>) {
544         self.inner.lock_irqsave().parent = parent
545     }
546 
547     fn kset(&self) -> Option<alloc::sync::Arc<KSet>> {
548         self.inner.lock_irqsave().kset.clone()
549     }
550 
551     fn set_kset(&self, kset: Option<alloc::sync::Arc<KSet>>) {
552         self.inner.lock_irqsave().kset = kset;
553     }
554 
555     fn kobj_type(&self) -> Option<&'static dyn KObjType> {
556         self.inner.lock_irqsave().kobj_type
557     }
558 
559     fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
560         self.inner.lock_irqsave().kobj_type = ktype;
561     }
562 
563     fn name(&self) -> alloc::string::String {
564         Self::NAME.to_string()
565     }
566 
567     fn set_name(&self, _name: alloc::string::String) {}
568 
569     fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
570         self.kobj_state.read()
571     }
572 
573     fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
574         self.kobj_state.write()
575     }
576 
577     fn set_kobj_state(&self, state: KObjectState) {
578         *self.kobj_state.write() = state;
579     }
580 }
581 
582 impl DeviceINode for Ps2MouseDevice {
583     fn set_fs(&self, fs: Weak<DevFS>) {
584         self.inner.lock_irqsave().device_inode_fs = Some(fs);
585     }
586 }
587 
588 impl IndexNode for Ps2MouseDevice {
589     fn open(
590         &self,
591         _data: SpinLockGuard<FilePrivateData>,
592         _mode: &crate::filesystem::vfs::file::FileMode,
593     ) -> Result<(), SystemError> {
594         let mut guard = self.inner.lock_irqsave();
595         guard.buf.clear();
596         Ok(())
597     }
598 
599     fn close(&self, _data: SpinLockGuard<FilePrivateData>) -> Result<(), SystemError> {
600         let mut guard = self.inner.lock_irqsave();
601         guard.buf.clear();
602         Ok(())
603     }
604 
605     fn read_at(
606         &self,
607         _offset: usize,
608         _len: usize,
609         buf: &mut [u8],
610         _data: SpinLockGuard<FilePrivateData>,
611     ) -> Result<usize, SystemError> {
612         let mut guard = self.inner.lock_irqsave();
613 
614         if guard.buf.len() >= 3 {
615             for item in buf.iter_mut().take(3) {
616                 *item = guard.buf.dequeue().unwrap();
617             }
618             return Ok(3);
619         } else {
620             return Ok(0);
621         }
622     }
623 
624     fn write_at(
625         &self,
626         _offset: usize,
627         _len: usize,
628         _buf: &[u8],
629         _data: SpinLockGuard<FilePrivateData>,
630     ) -> Result<usize, SystemError> {
631         return Err(SystemError::ENOSYS);
632     }
633 
634     fn fs(&self) -> Arc<dyn FileSystem> {
635         self.inner
636             .lock_irqsave()
637             .device_inode_fs
638             .as_ref()
639             .unwrap()
640             .upgrade()
641             .unwrap()
642     }
643 
644     fn as_any_ref(&self) -> &dyn core::any::Any {
645         self
646     }
647 
648     fn list(&self) -> Result<Vec<alloc::string::String>, SystemError> {
649         todo!()
650     }
651 
652     fn metadata(&self) -> Result<Metadata, SystemError> {
653         Ok(self.inner.lock_irqsave().devfs_metadata.clone())
654     }
655 
656     fn resize(&self, _len: usize) -> Result<(), SystemError> {
657         Ok(())
658     }
659 
660     fn dname(&self) -> Result<DName, SystemError> {
661         Ok(DName::from(self.name()))
662     }
663 }
664 
665 impl Ps2Device for Ps2MouseDevice {}
666 
667 pub fn rs_ps2_mouse_device_init(parent: Arc<dyn KObject>) -> Result<(), SystemError> {
668     debug!("ps2_mouse_device initializing...");
669     let psmouse = Arc::new(Ps2MouseDevice::new());
670 
671     device_manager().device_default_initialize(&(psmouse.clone() as Arc<dyn Device>));
672     psmouse.set_parent(Some(Arc::downgrade(&parent)));
673     serio_device_manager().register_port(psmouse.clone() as Arc<dyn SerioDevice>)?;
674 
675     devfs_register(&psmouse.name(), psmouse.clone()).map_err(|e| {
676         error!(
677             "register psmouse device '{}' to devfs failed: {:?}",
678             psmouse.name(),
679             e
680         );
681         device_manager().remove(&(psmouse.clone() as Arc<dyn Device>));
682         e
683     })?;
684 
685     unsafe { PS2_MOUSE_DEVICE = Some(psmouse) };
686     return Ok(());
687 }
688