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