xref: /DragonOS/kernel/src/driver/base/platform/platform_driver.rs (revision 70a4e5550a9fb49b537092287c3ddc36448c5b78)
1 use alloc::sync::Arc;
2 
3 use crate::{
4     driver::base::device::{
5         bus::Bus,
6         driver::{driver_manager, Driver},
7     },
8     syscall::SystemError,
9 };
10 
11 use super::{platform_bus, platform_device::PlatformDevice};
12 
13 /// @brief: 实现该trait的设备驱动实例应挂载在platform总线上,
14 ///         同时应该实现Driver trait
15 ///
16 /// ## 注意
17 ///
18 /// 应当在所有实现这个trait的结构体上方,添加 `#[cast_to([sync] PlatformDriver)]`,
19 /// 否则运行时将报错“该对象不是PlatformDriver”
20 pub trait PlatformDriver: Driver {
21     /// 检测设备是否能绑定到这个驱动
22     ///
23     /// 如果能,则把设备的driver指向这个驱动。
24     /// 请注意,这个函数不应该把driver加入驱动的devices列表,相关工作会在外部的函数里面处理。
25     fn probe(&self, device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError>;
26     fn remove(&self, device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError>;
27     fn shutdown(&self, device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError>;
28     fn suspend(&self, device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError>;
29     fn resume(&self, device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError>;
30 }
31 
32 #[inline(always)]
33 pub fn platform_driver_manager() -> &'static PlatformDriverManager {
34     &PlatformDriverManager
35 }
36 
37 #[derive(Debug)]
38 pub struct PlatformDriverManager;
39 
40 impl PlatformDriverManager {
41     /// 注册平台设备驱动
42     ///
43     /// 参考 https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/platform.c?fi=__platform_driver_register#861
44     pub fn register(&self, driver: Arc<dyn PlatformDriver>) -> Result<(), SystemError> {
45         driver.set_bus(Some(platform_bus() as Arc<dyn Bus>));
46         return driver_manager().register(driver as Arc<dyn Driver>);
47     }
48 
49     /// 卸载平台设备驱动
50     #[allow(dead_code)]
51     pub fn unregister(&self, driver: &Arc<dyn PlatformDriver>) {
52         driver_manager().unregister(&(driver.clone() as Arc<dyn Driver>));
53     }
54 }
55