xref: /DragonOS/kernel/src/driver/serial/serial8250/mod.rs (revision 4b0170bd6bb374d0e9699a0076cc23b976ad6db7)
1 use core::{
2     any::Any,
3     sync::atomic::{AtomicBool, AtomicI32, Ordering},
4 };
5 
6 use alloc::{
7     string::{String, ToString},
8     sync::{Arc, Weak},
9     vec::Vec,
10 };
11 use system_error::SystemError;
12 
13 use crate::{
14     driver::base::{
15         class::Class,
16         device::{
17             bus::Bus, device_manager, device_number::DeviceNumber, driver::Driver, Device,
18             DeviceKObjType, DeviceState, DeviceType, IdTable,
19         },
20         kobject::{KObjType, KObject, KObjectState, LockedKObjectState},
21         kset::KSet,
22         platform::{
23             platform_device::{platform_device_manager, PlatformDevice},
24             platform_driver::{platform_driver_manager, PlatformDriver},
25         },
26     },
27     filesystem::kernfs::KernFSInode,
28     libs::rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard},
29 };
30 
31 use self::serial8250_pio::{send_to_serial8250_pio_com1, serial8250_pio_port_early_init};
32 
33 use super::{uart_manager, UartDriver, UartPort};
34 
35 mod serial8250_pio;
36 
37 static mut SERIAL8250_ISA_DEVICES: Option<Arc<Serial8250ISADevices>> = None;
38 static mut SERIAL8250_ISA_DRIVER: Option<Arc<Serial8250ISADriver>> = None;
39 
40 #[inline(always)]
41 #[allow(dead_code)]
42 fn serial8250_isa_devices() -> &'static Arc<Serial8250ISADevices> {
43     unsafe { SERIAL8250_ISA_DEVICES.as_ref().unwrap() }
44 }
45 
46 #[inline(always)]
47 #[allow(dead_code)]
48 fn serial8250_isa_driver() -> &'static Arc<Serial8250ISADriver> {
49     unsafe { SERIAL8250_ISA_DRIVER.as_ref().unwrap() }
50 }
51 
52 #[inline(always)]
53 pub(super) fn serial8250_manager() -> &'static Serial8250Manager {
54     &Serial8250Manager
55 }
56 
57 /// 标记serial8250是否已经初始化
58 static mut INITIALIZED: bool = false;
59 
60 #[derive(Debug)]
61 pub(super) struct Serial8250Manager;
62 
63 impl Serial8250Manager {
64     /// 初始化串口设备(在内存管理初始化之前)
65     pub fn early_init(&self) -> Result<(), SystemError> {
66         // todo: riscv64: 串口设备初始化
67         #[cfg(not(target_arch = "riscv64"))]
68         serial8250_pio_port_early_init()?;
69         return Ok(());
70     }
71 
72     /// 初始化serial8250设备、驱动
73     ///
74     /// 应当在设备驱动模型初始化之后调用这里
75     ///
76     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/tty/serial/8250/8250_core.c?r=&mo=30224&fi=1169#1169
77     pub fn init(&self) -> Result<(), SystemError> {
78         // 初始化serial8250 isa设备
79         let serial8250_isa_dev = Serial8250ISADevices::new();
80         unsafe {
81             SERIAL8250_ISA_DEVICES = Some(serial8250_isa_dev.clone());
82         }
83 
84         let serial8250_isa_driver = Serial8250ISADriver::new();
85         unsafe {
86             SERIAL8250_ISA_DRIVER = Some(serial8250_isa_driver.clone());
87         }
88         // todo: 把端口绑定到isa_dev、 isa_driver上
89         self.register_ports(&serial8250_isa_driver, &serial8250_isa_dev);
90 
91         serial8250_isa_dev.set_driver(Some(Arc::downgrade(
92             &(serial8250_isa_driver.clone() as Arc<dyn Driver>),
93         )));
94         // todo: 把驱动注册到uart层、tty层
95         uart_manager().register_driver(&(serial8250_isa_driver.clone() as Arc<dyn UartDriver>))?;
96 
97         // 注册isa设备到platform总线
98         platform_device_manager()
99             .device_add(serial8250_isa_dev.clone() as Arc<dyn PlatformDevice>)
100             .map_err(|e| {
101                 unsafe {
102                     SERIAL8250_ISA_DEVICES = None;
103                 }
104                 return e;
105             })?;
106 
107         // 把驱动注册到platform总线
108         platform_driver_manager()
109             .register(serial8250_isa_driver.clone() as Arc<dyn PlatformDriver>)?;
110 
111         unsafe {
112             INITIALIZED = true;
113         }
114 
115         return Ok(());
116     }
117 
118     /// 把uart端口与uart driver、uart device绑定
119     ///
120     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/tty/serial/8250/8250_core.c?r=&mo=30224&fi=1169#553
121     fn register_ports(
122         &self,
123         uart_driver: &Arc<Serial8250ISADriver>,
124         devs: &Arc<Serial8250ISADevices>,
125     ) {
126         self.bind_pio_ports(uart_driver, devs);
127     }
128 
129     /// 把uart端口与uart driver绑定
130     ///
131     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/tty/serial/serial_core.c?fi=uart_add_one_port#3048
132     pub(self) fn uart_add_one_port(
133         &self,
134         _uart_driver: &Arc<Serial8250ISADriver>,
135         _port: &dyn UartPort,
136     ) -> Result<(), SystemError> {
137         return Ok(());
138         // todo!("Serial8250Manager::uart_add_one_port")
139     }
140 }
141 
142 /// 所有的8250串口设备都应该实现的trait
143 trait Serial8250Port: UartPort {
144     fn device(&self) -> Option<Arc<Serial8250ISADevices>> {
145         None
146     }
147     fn set_device(&self, device: Option<&Arc<Serial8250ISADevices>>);
148 }
149 
150 #[derive(Debug)]
151 #[cast_to([sync] Device, PlatformDevice)]
152 struct Serial8250ISADevices {
153     /// 设备id是否自动分配
154     id_auto: AtomicBool,
155     /// 平台设备id
156     id: AtomicI32,
157 
158     inner: RwLock<InnerSerial8250ISADevices>,
159     name: &'static str,
160     kobj_state: LockedKObjectState,
161 }
162 
163 impl Serial8250ISADevices {
164     pub fn new() -> Arc<Self> {
165         let r = Arc::new(Self {
166             id_auto: AtomicBool::new(false),
167             id: AtomicI32::new(Serial8250PlatformDeviceID::Legacy as i32),
168             inner: RwLock::new(InnerSerial8250ISADevices::new()),
169             name: "serial8250",
170             kobj_state: LockedKObjectState::new(None),
171         });
172 
173         device_manager().device_default_initialize(&(r.clone() as Arc<dyn Device>));
174 
175         return r;
176     }
177 }
178 
179 impl PlatformDevice for Serial8250ISADevices {
180     fn pdev_id(&self) -> (i32, bool) {
181         return (
182             self.id.load(Ordering::SeqCst),
183             self.id_auto.load(Ordering::SeqCst),
184         );
185     }
186 
187     fn set_pdev_id(&self, id: i32) {
188         self.id.store(id, Ordering::SeqCst);
189     }
190 
191     fn set_pdev_id_auto(&self, id_auto: bool) {
192         self.id_auto.store(id_auto, Ordering::SeqCst);
193     }
194 
195     fn pdev_name(&self) -> &str {
196         return self.name;
197     }
198 
199     fn is_initialized(&self) -> bool {
200         return self.inner.read().device_state == DeviceState::Initialized;
201     }
202 
203     fn set_state(&self, set_state: DeviceState) {
204         self.inner.write().device_state = set_state;
205     }
206 }
207 
208 impl Device for Serial8250ISADevices {
209     fn is_dead(&self) -> bool {
210         false
211     }
212     fn bus(&self) -> Option<Weak<dyn Bus>> {
213         self.inner.read().bus.clone()
214     }
215 
216     fn set_bus(&self, bus: Option<Weak<dyn Bus>>) {
217         self.inner.write().bus = bus;
218     }
219 
220     fn dev_type(&self) -> DeviceType {
221         DeviceType::Serial
222     }
223 
224     fn id_table(&self) -> IdTable {
225         return IdTable::new(self.name.to_string(), None);
226     }
227 
228     fn driver(&self) -> Option<Arc<dyn Driver>> {
229         self.inner.read().driver.clone()?.upgrade()
230     }
231 
232     fn set_driver(&self, driver: Option<Weak<dyn Driver>>) {
233         self.inner.write().driver = driver;
234     }
235 
236     fn can_match(&self) -> bool {
237         self.inner.read().can_match
238     }
239 
240     fn set_can_match(&self, can_match: bool) {
241         self.inner.write().can_match = can_match;
242     }
243 
244     fn state_synced(&self) -> bool {
245         true
246     }
247 
248     fn set_class(&self, _class: Option<Weak<dyn Class>>) {
249         todo!()
250     }
251 }
252 
253 impl KObject for Serial8250ISADevices {
254     fn as_any_ref(&self) -> &dyn Any {
255         self
256     }
257 
258     fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
259         self.inner.write().inode = inode;
260     }
261 
262     fn inode(&self) -> Option<Arc<KernFSInode>> {
263         self.inner.read().inode.clone()
264     }
265 
266     fn parent(&self) -> Option<Weak<dyn KObject>> {
267         self.inner.read().parent_kobj.clone()
268     }
269 
270     fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
271         self.inner.write().parent_kobj = parent;
272     }
273 
274     fn kset(&self) -> Option<Arc<KSet>> {
275         self.inner.read().kset.clone()
276     }
277 
278     fn set_kset(&self, kset: Option<Arc<KSet>>) {
279         self.inner.write().kset = kset;
280     }
281 
282     fn kobj_type(&self) -> Option<&'static dyn KObjType> {
283         Some(&DeviceKObjType)
284     }
285 
286     fn set_kobj_type(&self, _ktype: Option<&'static dyn KObjType>) {
287         // 不允许修改
288     }
289 
290     fn name(&self) -> String {
291         self.name.to_string()
292     }
293 
294     fn set_name(&self, _name: String) {}
295 
296     fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
297         self.kobj_state.read()
298     }
299 
300     fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
301         self.kobj_state.write()
302     }
303 
304     fn set_kobj_state(&self, state: KObjectState) {
305         *self.kobj_state.write() = state;
306     }
307 }
308 
309 #[derive(Debug)]
310 struct InnerSerial8250ISADevices {
311     /// 当前设备所述的kset
312     kset: Option<Arc<KSet>>,
313     parent_kobj: Option<Weak<dyn KObject>>,
314     /// 当前设备所述的总线
315     bus: Option<Weak<dyn Bus>>,
316     inode: Option<Arc<KernFSInode>>,
317     driver: Option<Weak<dyn Driver>>,
318     device_state: DeviceState,
319     can_match: bool,
320 }
321 
322 impl InnerSerial8250ISADevices {
323     fn new() -> Self {
324         Self {
325             kset: None,
326             parent_kobj: None,
327             bus: None,
328             inode: None,
329             driver: None,
330             device_state: DeviceState::NotInitialized,
331             can_match: false,
332         }
333     }
334 }
335 
336 /// Serial 8250平台设备的id
337 /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/include/linux/serial_8250.h?fi=PLAT8250_DEV_LEGACY#49
338 #[derive(Debug)]
339 #[repr(i32)]
340 enum Serial8250PlatformDeviceID {
341     Legacy = -1,
342 }
343 
344 #[derive(Debug)]
345 
346 struct InnerSerial8250ISADriver {
347     bus: Option<Weak<dyn Bus>>,
348     kobj_type: Option<&'static dyn KObjType>,
349     kset: Option<Arc<KSet>>,
350     parent_kobj: Option<Weak<dyn KObject>>,
351     kern_inode: Option<Arc<KernFSInode>>,
352     devices: Vec<Arc<dyn Device>>,
353 }
354 
355 impl InnerSerial8250ISADriver {
356     fn new() -> Self {
357         Self {
358             bus: None,
359             kobj_type: None,
360             kset: None,
361             parent_kobj: None,
362             kern_inode: None,
363             devices: Vec::new(),
364         }
365     }
366 }
367 
368 #[derive(Debug)]
369 #[cast_to([sync] Driver, PlatformDriver)]
370 #[allow(dead_code)]
371 struct Serial8250ISADriver {
372     inner: RwLock<InnerSerial8250ISADriver>,
373     name: &'static str,
374     kobj_state: LockedKObjectState,
375     self_ref: Weak<Self>,
376 }
377 
378 impl Serial8250ISADriver {
379     pub fn new() -> Arc<Self> {
380         let r = Arc::new(Self {
381             inner: RwLock::new(InnerSerial8250ISADriver::new()),
382             name: "serial8250",
383             kobj_state: LockedKObjectState::new(None),
384             self_ref: Weak::default(),
385         });
386 
387         unsafe {
388             let p = r.as_ref() as *const Self as *mut Self;
389             (*p).self_ref = Arc::downgrade(&r);
390         }
391 
392         return r;
393     }
394 }
395 
396 impl UartDriver for Serial8250ISADriver {
397     fn device_number(&self) -> DeviceNumber {
398         todo!()
399     }
400 
401     fn max_devs_num(&self) -> i32 {
402         todo!()
403     }
404 }
405 
406 impl PlatformDriver for Serial8250ISADriver {
407     fn probe(&self, device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError> {
408         let isa_dev = device
409             .clone()
410             .arc_any()
411             .downcast::<Serial8250ISADevices>()
412             .map_err(|_| {
413                 kerror!("Serial8250ISADriver::probe: device is not a Serial8250ISADevices");
414                 SystemError::EINVAL
415             })?;
416         isa_dev.set_driver(Some(self.self_ref.clone()));
417 
418         return Ok(());
419     }
420 
421     fn remove(&self, _device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError> {
422         todo!()
423     }
424 
425     fn shutdown(&self, _device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError> {
426         todo!()
427     }
428 
429     fn suspend(&self, _device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError> {
430         todo!()
431     }
432 
433     fn resume(&self, _device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError> {
434         todo!()
435     }
436 }
437 
438 impl Driver for Serial8250ISADriver {
439     fn id_table(&self) -> Option<IdTable> {
440         None
441     }
442 
443     fn devices(&self) -> Vec<Arc<dyn Device>> {
444         self.inner.read().devices.clone()
445     }
446 
447     fn add_device(&self, device: Arc<dyn Device>) {
448         self.inner.write().devices.push(device);
449     }
450 
451     fn delete_device(&self, device: &Arc<dyn Device>) {
452         let mut inner = self.inner.write();
453 
454         inner.devices.retain(|d| !Arc::ptr_eq(d, device));
455     }
456 
457     fn bus(&self) -> Option<Weak<dyn Bus>> {
458         self.inner.read().bus.clone()
459     }
460 
461     fn set_bus(&self, bus: Option<Weak<dyn Bus>>) {
462         self.inner.write().bus = bus;
463     }
464 }
465 
466 impl KObject for Serial8250ISADriver {
467     fn as_any_ref(&self) -> &dyn core::any::Any {
468         self
469     }
470 
471     fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
472         self.inner.write().kern_inode = inode;
473     }
474 
475     fn inode(&self) -> Option<Arc<KernFSInode>> {
476         self.inner.read().kern_inode.clone()
477     }
478 
479     fn parent(&self) -> Option<Weak<dyn KObject>> {
480         self.inner.read().parent_kobj.clone()
481     }
482 
483     fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
484         self.inner.write().parent_kobj = parent;
485     }
486 
487     fn kset(&self) -> Option<Arc<KSet>> {
488         self.inner.read().kset.clone()
489     }
490 
491     fn set_kset(&self, kset: Option<Arc<KSet>>) {
492         self.inner.write().kset = kset;
493     }
494 
495     fn kobj_type(&self) -> Option<&'static dyn KObjType> {
496         self.inner.read().kobj_type
497     }
498 
499     fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
500         self.inner.write().kobj_type = ktype;
501     }
502 
503     fn name(&self) -> String {
504         "serial8250".to_string()
505     }
506 
507     fn set_name(&self, _name: String) {}
508 
509     fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
510         self.kobj_state.read()
511     }
512 
513     fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
514         self.kobj_state.write()
515     }
516 
517     fn set_kobj_state(&self, state: KObjectState) {
518         *self.kobj_state.write() = state;
519     }
520 }
521 
522 /// 临时函数,用于向默认的串口发送数据
523 pub fn send_to_default_serial8250_port(s: &[u8]) {
524     #[cfg(target_arch = "x86_64")]
525     send_to_serial8250_pio_com1(s);
526 
527     #[cfg(target_arch = "riscv64")]
528     {
529         if unsafe { INITIALIZED } {
530             todo!("riscv64: send_to_default_serial8250_port")
531         } else {
532             crate::arch::driver::sbi::console_putstr(s);
533         }
534     }
535 }
536