xref: /DragonOS/kernel/src/driver/serial/serial8250/mod.rs (revision 28fe4ad2a0b0d8b5abf1f0cb402b1c3204b42242)
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             DeviceCommonData, DeviceKObjType, DeviceState, DeviceType, IdTable,
20         },
21         kobject::{KObjType, KObject, KObjectCommonData, 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().device_common.bus.clone()
216     }
217 
218     fn set_bus(&self, bus: Option<Weak<dyn Bus>>) {
219         self.inner.write().device_common.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().device_common.driver.clone()?.upgrade()
232     }
233 
234     fn set_driver(&self, driver: Option<Weak<dyn Driver>>) {
235         self.inner.write().device_common.driver = driver;
236     }
237 
238     fn can_match(&self) -> bool {
239         self.inner.read().device_common.can_match
240     }
241 
242     fn set_can_match(&self, can_match: bool) {
243         self.inner.write().device_common.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     fn dev_parent(&self) -> Option<Weak<dyn Device>> {
255         self.inner.read().device_common.parent.clone()
256     }
257 
258     fn set_dev_parent(&self, dev_parent: Option<Weak<dyn Device>>) {
259         self.inner.write().device_common.parent = dev_parent;
260     }
261 }
262 
263 impl KObject for Serial8250ISADevices {
264     fn as_any_ref(&self) -> &dyn Any {
265         self
266     }
267 
268     fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
269         self.inner.write().kobject_common.kern_inode = inode;
270     }
271 
272     fn inode(&self) -> Option<Arc<KernFSInode>> {
273         self.inner.read().kobject_common.kern_inode.clone()
274     }
275 
276     fn parent(&self) -> Option<Weak<dyn KObject>> {
277         self.inner.read().kobject_common.parent.clone()
278     }
279 
280     fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
281         self.inner.write().kobject_common.parent = parent;
282     }
283 
284     fn kset(&self) -> Option<Arc<KSet>> {
285         self.inner.read().kobject_common.kset.clone()
286     }
287 
288     fn set_kset(&self, kset: Option<Arc<KSet>>) {
289         self.inner.write().kobject_common.kset = kset;
290     }
291 
292     fn kobj_type(&self) -> Option<&'static dyn KObjType> {
293         Some(&DeviceKObjType)
294     }
295 
296     fn set_kobj_type(&self, _ktype: Option<&'static dyn KObjType>) {
297         // 不允许修改
298     }
299 
300     fn name(&self) -> String {
301         self.name.to_string()
302     }
303 
304     fn set_name(&self, _name: String) {}
305 
306     fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
307         self.kobj_state.read()
308     }
309 
310     fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
311         self.kobj_state.write()
312     }
313 
314     fn set_kobj_state(&self, state: KObjectState) {
315         *self.kobj_state.write() = state;
316     }
317 }
318 
319 #[derive(Debug)]
320 struct InnerSerial8250ISADevices {
321     kobject_common: KObjectCommonData,
322     device_common: DeviceCommonData,
323     device_state: DeviceState,
324 }
325 
326 impl InnerSerial8250ISADevices {
327     fn new() -> Self {
328         Self {
329             kobject_common: KObjectCommonData::default(),
330             device_common: DeviceCommonData::default(),
331             device_state: DeviceState::NotInitialized,
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                 error!("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         crate::arch::driver::sbi::console_putstr(s);
530     }
531 }
532