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