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