xref: /DragonOS/kernel/src/driver/base/platform/platform_driver.rs (revision 55e6f0b65f91b32638fd56581f711a816eccdcd1)
1 use alloc::sync::Arc;
2 
3 use crate::driver::base::device::{
4     bus::Bus,
5     driver::{driver_manager, Driver},
6 };
7 
8 use system_error::SystemError;
9 
10 use super::{platform_bus, platform_device::PlatformDevice};
11 
12 /// @brief: 实现该trait的设备驱动实例应挂载在platform总线上,
13 ///         同时应该实现Driver trait
14 ///
15 /// ## 注意
16 ///
17 /// 应当在所有实现这个trait的结构体上方,添加 `#[cast_to([sync] PlatformDriver)]`,
18 /// 否则运行时将报错“该对象不是PlatformDriver”
19 #[allow(dead_code)]
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://code.dragonos.org.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(Arc::downgrade(&(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