xref: /DragonOS/kernel/src/driver/serial/serial8250/mod.rs (revision 840045af94ea3391f29e87e968db5d9c48316981)
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 compatible_table(&self) -> crate::driver::base::platform::CompatibleTable {
181         unimplemented!()
182     }
183 
184     fn pdev_id(&self) -> (i32, bool) {
185         return (
186             self.id.load(Ordering::SeqCst),
187             self.id_auto.load(Ordering::SeqCst),
188         );
189     }
190 
191     fn set_pdev_id(&self, id: i32) {
192         self.id.store(id, Ordering::SeqCst);
193     }
194 
195     fn set_pdev_id_auto(&self, id_auto: bool) {
196         self.id_auto.store(id_auto, Ordering::SeqCst);
197     }
198 
199     fn pdev_name(&self) -> &str {
200         return self.name;
201     }
202 
203     fn is_initialized(&self) -> bool {
204         return self.inner.read().device_state == DeviceState::Initialized;
205     }
206 
207     fn set_state(&self, set_state: DeviceState) {
208         self.inner.write().device_state = set_state;
209     }
210 }
211 
212 impl Device for Serial8250ISADevices {
213     fn is_dead(&self) -> bool {
214         false
215     }
216     fn bus(&self) -> Option<Weak<dyn Bus>> {
217         self.inner.read().bus.clone()
218     }
219 
220     fn set_bus(&self, bus: Option<Weak<dyn Bus>>) {
221         self.inner.write().bus = bus;
222     }
223 
224     fn dev_type(&self) -> DeviceType {
225         DeviceType::Serial
226     }
227 
228     fn id_table(&self) -> IdTable {
229         return IdTable::new(self.name.to_string(), None);
230     }
231 
232     fn driver(&self) -> Option<Arc<dyn Driver>> {
233         self.inner.read().driver.clone()?.upgrade()
234     }
235 
236     fn set_driver(&self, driver: Option<Weak<dyn Driver>>) {
237         self.inner.write().driver = driver;
238     }
239 
240     fn can_match(&self) -> bool {
241         self.inner.read().can_match
242     }
243 
244     fn set_can_match(&self, can_match: bool) {
245         self.inner.write().can_match = can_match;
246     }
247 
248     fn state_synced(&self) -> bool {
249         true
250     }
251 
252     fn set_class(&self, _class: Option<Arc<dyn Class>>) {
253         todo!()
254     }
255 }
256 
257 impl KObject for Serial8250ISADevices {
258     fn as_any_ref(&self) -> &dyn Any {
259         self
260     }
261 
262     fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
263         self.inner.write().inode = inode;
264     }
265 
266     fn inode(&self) -> Option<Arc<KernFSInode>> {
267         self.inner.read().inode.clone()
268     }
269 
270     fn parent(&self) -> Option<Weak<dyn KObject>> {
271         self.inner.read().parent_kobj.clone()
272     }
273 
274     fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
275         self.inner.write().parent_kobj = parent;
276     }
277 
278     fn kset(&self) -> Option<Arc<KSet>> {
279         self.inner.read().kset.clone()
280     }
281 
282     fn set_kset(&self, kset: Option<Arc<KSet>>) {
283         self.inner.write().kset = kset;
284     }
285 
286     fn kobj_type(&self) -> Option<&'static dyn KObjType> {
287         Some(&DeviceKObjType)
288     }
289 
290     fn set_kobj_type(&self, _ktype: Option<&'static dyn KObjType>) {
291         // 不允许修改
292     }
293 
294     fn name(&self) -> String {
295         self.name.to_string()
296     }
297 
298     fn set_name(&self, _name: String) {}
299 
300     fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
301         self.kobj_state.read()
302     }
303 
304     fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
305         self.kobj_state.write()
306     }
307 
308     fn set_kobj_state(&self, state: KObjectState) {
309         *self.kobj_state.write() = state;
310     }
311 }
312 
313 #[derive(Debug)]
314 struct InnerSerial8250ISADevices {
315     /// 当前设备所述的kset
316     kset: Option<Arc<KSet>>,
317     parent_kobj: Option<Weak<dyn KObject>>,
318     /// 当前设备所述的总线
319     bus: Option<Weak<dyn Bus>>,
320     inode: Option<Arc<KernFSInode>>,
321     driver: Option<Weak<dyn Driver>>,
322     device_state: DeviceState,
323     can_match: bool,
324 }
325 
326 impl InnerSerial8250ISADevices {
327     fn new() -> Self {
328         Self {
329             kset: None,
330             parent_kobj: None,
331             bus: None,
332             inode: None,
333             driver: None,
334             device_state: DeviceState::NotInitialized,
335             can_match: false,
336         }
337     }
338 }
339 
340 /// Serial 8250平台设备的id
341 /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/include/linux/serial_8250.h?fi=PLAT8250_DEV_LEGACY#49
342 #[derive(Debug)]
343 #[repr(i32)]
344 enum Serial8250PlatformDeviceID {
345     Legacy = -1,
346 }
347 
348 #[derive(Debug)]
349 
350 struct InnerSerial8250ISADriver {
351     bus: Option<Weak<dyn Bus>>,
352     kobj_type: Option<&'static dyn KObjType>,
353     kset: Option<Arc<KSet>>,
354     parent_kobj: Option<Weak<dyn KObject>>,
355     kern_inode: Option<Arc<KernFSInode>>,
356     devices: Vec<Arc<dyn Device>>,
357 }
358 
359 impl InnerSerial8250ISADriver {
360     fn new() -> Self {
361         Self {
362             bus: None,
363             kobj_type: None,
364             kset: None,
365             parent_kobj: None,
366             kern_inode: None,
367             devices: Vec::new(),
368         }
369     }
370 }
371 
372 #[derive(Debug)]
373 #[cast_to([sync] Driver, PlatformDriver)]
374 #[allow(dead_code)]
375 struct Serial8250ISADriver {
376     inner: RwLock<InnerSerial8250ISADriver>,
377     name: &'static str,
378     kobj_state: LockedKObjectState,
379     self_ref: Weak<Self>,
380 }
381 
382 impl Serial8250ISADriver {
383     pub fn new() -> Arc<Self> {
384         let r = Arc::new(Self {
385             inner: RwLock::new(InnerSerial8250ISADriver::new()),
386             name: "serial8250",
387             kobj_state: LockedKObjectState::new(None),
388             self_ref: Weak::default(),
389         });
390 
391         unsafe {
392             let p = r.as_ref() as *const Self as *mut Self;
393             (*p).self_ref = Arc::downgrade(&r);
394         }
395 
396         return r;
397     }
398 }
399 
400 impl UartDriver for Serial8250ISADriver {
401     fn device_number(&self) -> DeviceNumber {
402         todo!()
403     }
404 
405     fn max_devs_num(&self) -> i32 {
406         todo!()
407     }
408 }
409 
410 impl PlatformDriver for Serial8250ISADriver {
411     fn probe(&self, device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError> {
412         let isa_dev = device
413             .clone()
414             .arc_any()
415             .downcast::<Serial8250ISADevices>()
416             .map_err(|_| {
417                 kerror!("Serial8250ISADriver::probe: device is not a Serial8250ISADevices");
418                 SystemError::EINVAL
419             })?;
420         isa_dev.set_driver(Some(self.self_ref.clone()));
421 
422         return Ok(());
423     }
424 
425     fn remove(&self, _device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError> {
426         todo!()
427     }
428 
429     fn shutdown(&self, _device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError> {
430         todo!()
431     }
432 
433     fn suspend(&self, _device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError> {
434         todo!()
435     }
436 
437     fn resume(&self, _device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError> {
438         todo!()
439     }
440 }
441 
442 impl Driver for Serial8250ISADriver {
443     fn id_table(&self) -> Option<IdTable> {
444         None
445     }
446 
447     fn devices(&self) -> Vec<Arc<dyn Device>> {
448         self.inner.read().devices.clone()
449     }
450 
451     fn add_device(&self, device: Arc<dyn Device>) {
452         self.inner.write().devices.push(device);
453     }
454 
455     fn delete_device(&self, device: &Arc<dyn Device>) {
456         let mut inner = self.inner.write();
457 
458         inner.devices.retain(|d| !Arc::ptr_eq(d, device));
459     }
460 
461     fn bus(&self) -> Option<Weak<dyn Bus>> {
462         self.inner.read().bus.clone()
463     }
464 
465     fn set_bus(&self, bus: Option<Weak<dyn Bus>>) {
466         self.inner.write().bus = bus;
467     }
468 }
469 
470 impl KObject for Serial8250ISADriver {
471     fn as_any_ref(&self) -> &dyn core::any::Any {
472         self
473     }
474 
475     fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
476         self.inner.write().kern_inode = inode;
477     }
478 
479     fn inode(&self) -> Option<Arc<KernFSInode>> {
480         self.inner.read().kern_inode.clone()
481     }
482 
483     fn parent(&self) -> Option<Weak<dyn KObject>> {
484         self.inner.read().parent_kobj.clone()
485     }
486 
487     fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
488         self.inner.write().parent_kobj = parent;
489     }
490 
491     fn kset(&self) -> Option<Arc<KSet>> {
492         self.inner.read().kset.clone()
493     }
494 
495     fn set_kset(&self, kset: Option<Arc<KSet>>) {
496         self.inner.write().kset = kset;
497     }
498 
499     fn kobj_type(&self) -> Option<&'static dyn KObjType> {
500         self.inner.read().kobj_type.clone()
501     }
502 
503     fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
504         self.inner.write().kobj_type = ktype;
505     }
506 
507     fn name(&self) -> String {
508         "serial8250".to_string()
509     }
510 
511     fn set_name(&self, _name: String) {}
512 
513     fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
514         self.kobj_state.read()
515     }
516 
517     fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
518         self.kobj_state.write()
519     }
520 
521     fn set_kobj_state(&self, state: KObjectState) {
522         *self.kobj_state.write() = state;
523     }
524 }
525 
526 /// 临时函数,用于向默认的串口发送数据
527 pub fn send_to_default_serial8250_port(s: &[u8]) {
528     #[cfg(target_arch = "x86_64")]
529     send_to_serial8250_pio_com1(s);
530 
531     #[cfg(target_arch = "riscv64")]
532     {
533         if unsafe { INITIALIZED } {
534             todo!("riscv64: send_to_default_serial8250_port")
535         } else {
536             crate::arch::driver::sbi::console_putstr(s);
537         }
538     }
539 }
540