xref: /DragonOS/kernel/src/driver/base/platform/platform_driver.rs (revision 1ea2daad8121b77ed704e6d7c3a09f478147441d)
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 pub trait PlatformDriver: Driver {
20     /// 检测设备是否能绑定到这个驱动
21     ///
22     /// 如果能,则把设备的driver字段指向这个驱动。
23     /// 请注意,这个函数不应该把driver加入驱动的devices列表,相关工作会在外部的函数里面处理。
24     fn probe(&self, device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError>;
25     fn remove(&self, device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError>;
26     fn shutdown(&self, device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError>;
27     fn suspend(&self, device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError>;
28     fn resume(&self, device: &Arc<dyn PlatformDevice>) -> Result<(), SystemError>;
29 }
30 
31 #[inline(always)]
32 pub fn platform_driver_manager() -> &'static PlatformDriverManager {
33     &PlatformDriverManager
34 }
35 
36 #[derive(Debug)]
37 pub struct PlatformDriverManager;
38 
39 impl PlatformDriverManager {
40     /// 注册平台设备驱动
41     ///
42     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/platform.c?fi=__platform_driver_register#861
43     pub fn register(&self, driver: Arc<dyn PlatformDriver>) -> Result<(), SystemError> {
44         driver.set_bus(Some(Arc::downgrade(&(platform_bus() as Arc<dyn Bus>))));
45         return driver_manager().register(driver as Arc<dyn Driver>);
46     }
47 
48     /// 卸载平台设备驱动
49     #[allow(dead_code)]
50     pub fn unregister(&self, driver: &Arc<dyn PlatformDriver>) {
51         driver_manager().unregister(&(driver.clone() as Arc<dyn Driver>));
52     }
53 }
54