xref: /DragonOS/kernel/src/driver/pci/driver.rs (revision 59a6bcf6aee15a11a16431bdf875905c5ecf9157)
1 use alloc::{sync::Arc, vec::Vec};
2 use system_error::SystemError;
3 
4 use crate::driver::base::device::{
5     bus::Bus,
6     driver::{driver_manager, Driver},
7 };
8 
9 use super::{dev_id::PciDeviceID, device::PciDevice, subsys::pci_bus};
10 
11 /// # trait功能
12 /// Pci驱动应该实现的trait
13 ///
14 /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/include/linux/pci.h#907
15 #[allow(dead_code)]
16 pub trait PciDriver: Driver {
17     /// # 函数的功能
18     /// 对设备进行probe操作
19     ///
20     /// ## 参数:
21     /// - 'device' :要进行probe的设备
22     /// - 'id' :设备的ID(暂时不清楚为什么需要这个,依Linux实现是有ID的)
23     ///
24     /// ## 返回值:
25     /// - Ok:probe成功
26     /// - Err:probe失败
27     fn probe(&self, device: &Arc<dyn PciDevice>, id: &PciDeviceID) -> Result<(), SystemError>;
28     fn remove(&self, device: &Arc<dyn PciDevice>) -> Result<(), SystemError>;
29     fn shutdown(&self, device: &Arc<dyn PciDevice>) -> Result<(), SystemError>;
30     fn suspend(&self, device: &Arc<dyn PciDevice>) -> Result<(), SystemError>;
31     fn resume(&self, device: &Arc<dyn PciDevice>) -> Result<(), SystemError>;
32     /// # 函数的功能
33     /// 向驱动中加入一个PciDeviceID,表示该驱动可以支持该ID的设备
34     ///
35     /// ## 参数:
36     /// - 'id' :要添加的ID
37     ///
38     /// ## 返回值:
39     /// - 'Ok':添加成功
40     /// - 'Err':添加失败
41     fn add_dynid(&mut self, id: PciDeviceID) -> Result<(), SystemError>;
42     /// # 函数的功能
43     /// 每个Pci驱动都应该持有一个支持ID的列表,并通过该函数进行访问
44     ///
45     /// ## 返回值:
46     /// - 'Some(Vec)': 支持ID的列表
47     /// - 'None':未能获取列表
48     fn locked_dynid_list(&self) -> Option<Vec<Arc<PciDeviceID>>>;
49     /// # 函数的功能
50     /// 检测当前驱动是否支持目标设备
51     ///
52     /// ## 参数:
53     /// - 'dev' :要检测的设备
54     ///
55     /// ## 返回值:
56     /// - 'Some(Arc<PciDeviceID>)': 如果支持,则返回支持的ID
57     /// - 'None': 不支持的设备
58     fn match_dev(&self, dev: &Arc<dyn PciDevice>) -> Option<Arc<PciDeviceID>> {
59         for i in self.locked_dynid_list()?.iter() {
60             if i.match_dev(dev) {
61                 return Some(i.clone());
62             }
63         }
64         return None;
65     }
66 }
67 
68 pub struct PciDriverManager;
69 
70 pub fn pci_driver_manager() -> &'static PciDriverManager {
71     &PciDriverManager
72 }
73 
74 impl PciDriverManager {
75     pub fn register(&self, driver: Arc<dyn PciDriver>) -> Result<(), SystemError> {
76         driver.set_bus(Some(Arc::downgrade(&(pci_bus() as Arc<dyn Bus>))));
77         return driver_manager().register(driver as Arc<dyn Driver>);
78     }
79 
80     #[allow(dead_code)]
81     pub fn unregister(&self, driver: &Arc<dyn PciDriver>) {
82         driver_manager().unregister(&(driver.clone() as Arc<dyn Driver>));
83     }
84 }
85