xref: /DragonOS/kernel/src/driver/base/device/driver.rs (revision 9430523b465b19db4dd476e9fd3038bdc2aa0c8d)
1 use super::{
2     bus::{bus_manager, Bus},
3     Device, DeviceMatchName, DeviceMatcher, IdTable,
4 };
5 use crate::{
6     driver::base::kobject::KObject,
7     filesystem::sysfs::{sysfs_instance, Attribute, AttributeGroup},
8 };
9 use alloc::{
10     sync::{Arc, Weak},
11     vec::Vec,
12 };
13 use core::fmt::Debug;
14 use system_error::SystemError;
15 
16 /// @brief: Driver error
17 #[allow(dead_code)]
18 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
19 pub enum DriverError {
20     ProbeError,            // 探测设备失败(该驱动不能初始化这个设备)
21     RegisterError,         // 设备注册失败
22     AllocateResourceError, // 获取设备所需资源失败
23     UnsupportedOperation,  // 不支持的操作
24     UnInitialized,         // 未初始化
25 }
26 
27 impl From<DriverError> for SystemError {
28     fn from(value: DriverError) -> Self {
29         match value {
30             DriverError::ProbeError => SystemError::ENODEV,
31             DriverError::RegisterError => SystemError::ENODEV,
32             DriverError::AllocateResourceError => SystemError::EIO,
33             DriverError::UnsupportedOperation => SystemError::EIO,
34             DriverError::UnInitialized => SystemError::ENODEV,
35         }
36     }
37 }
38 
39 #[inline(always)]
40 pub fn driver_manager() -> &'static DriverManager {
41     &DriverManager
42 }
43 
44 /// 驱动程序应当实现的trait
45 ///
46 /// ## 注意
47 ///
48 /// 由于设备驱动模型需要从Arc<dyn KObject>转换为Arc<dyn Driver>,
49 /// 因此,所有的实现了 Driver trait的结构体,都应该在结构体上方标注`#[cast_to([sync] Driver)]`,
50 /// 否则在运行时会报错
51 pub trait Driver: Sync + Send + Debug + KObject {
52     fn coredump(&self, _device: &Arc<dyn Device>) -> Result<(), SystemError> {
53         Err(SystemError::ENOSYS)
54     }
55 
56     /// @brief: 获取驱动标识符
57     /// @parameter: None
58     /// @return: 该驱动驱动唯一标识符
59     fn id_table(&self) -> Option<IdTable>;
60 
61     fn devices(&self) -> Vec<Arc<dyn Device>>;
62 
63     /// 把设备加入当前驱动管理的列表中
64     fn add_device(&self, device: Arc<dyn Device>);
65 
66     /// 从当前驱动管理的列表中删除设备
67     fn delete_device(&self, device: &Arc<dyn Device>);
68 
69     /// 根据设备名称查找绑定到驱动的设备
70     ///
71     /// 该方法是一个快速查找方法,要求驱动开发者自行实现。
72     ///
73     /// 如果开发者没有实现该方法,则应当返回None
74     ///
75     /// ## 注意
76     ///
77     /// 这是一个内部方法,不应当被外部调用,若要查找设备,请使用`find_device_by_name()`
78     fn __find_device_by_name_fast(&self, _name: &str) -> Option<Arc<dyn Device>> {
79         None
80     }
81 
82     /// 是否禁用sysfs的bind/unbind属性
83     ///
84     /// ## 返回
85     ///
86     /// - true: 禁用
87     /// - false: 不禁用(默认)
88     fn suppress_bind_attrs(&self) -> bool {
89         false
90     }
91 
92     fn bus(&self) -> Option<Weak<dyn Bus>> {
93         None
94     }
95 
96     fn set_bus(&self, bus: Option<Weak<dyn Bus>>);
97 
98     fn groups(&self) -> &'static [&'static dyn AttributeGroup] {
99         &[]
100     }
101 
102     fn dev_groups(&self) -> &'static [&'static dyn AttributeGroup] {
103         &[]
104     }
105 
106     /// 使用什么样的策略来探测设备
107     fn probe_type(&self) -> DriverProbeType {
108         DriverProbeType::DefaultStrategy
109     }
110 }
111 
112 #[derive(Debug, Default)]
113 pub struct DriverCommonData {
114     pub devices: Vec<Arc<dyn Device>>,
115     pub bus: Option<Weak<dyn Bus>>,
116 }
117 
118 impl DriverCommonData {
119     pub fn push_device(&mut self, device: Arc<dyn Device>) {
120         if !self.devices.iter().any(|d| Arc::ptr_eq(d, &device)) {
121             self.devices.push(device);
122         }
123     }
124 
125     pub fn delete_device(&mut self, device: &Arc<dyn Device>) {
126         self.devices.retain(|d| !Arc::ptr_eq(d, device));
127     }
128 }
129 
130 impl dyn Driver {
131     pub fn allows_async_probing(&self) -> bool {
132         match self.probe_type() {
133             DriverProbeType::PreferAsync => true,
134             DriverProbeType::ForceSync => false,
135             DriverProbeType::DefaultStrategy => {
136                 // todo: 判断是否请求异步探测,如果是的话,就返回true
137 
138                 // 由于目前还没有支持异步探测,因此这里暂时返回false
139                 false
140             }
141         }
142     }
143 
144     /// 根据条件寻找一个绑定到这个驱动的设备(低效实现)
145     ///
146     /// ## 参数
147     ///
148     /// - `matcher` - 匹配器
149     /// - `data` - 传给匹配器的数据
150     ///
151     /// ## 注意
152     ///
153     /// 这里的默认实现很低效,请为特定的驱动自行实现高效的查询
154     fn find_device_slow<T: Copy>(
155         &self,
156         matcher: &dyn DeviceMatcher<T>,
157         data: T,
158     ) -> Option<Arc<dyn Device>> {
159         self.devices()
160             .into_iter()
161             .find(|dev| matcher.match_device(dev, data))
162     }
163 
164     /// 根据设备名称查找绑定到驱动的设备
165     ///
166     /// ## 注意
167     ///
168     /// 这里的默认实现很低效,请为特定的驱动自行实现高效的查询
169     pub fn find_device_by_name(&self, name: &str) -> Option<Arc<dyn Device>> {
170         if let Some(r) = self.__find_device_by_name_fast(name) {
171             return Some(r);
172         }
173 
174         return self.find_device_slow(&DeviceMatchName, name);
175     }
176 }
177 
178 /// @brief: 驱动管理器
179 #[derive(Debug, Clone)]
180 pub struct DriverManager;
181 
182 impl DriverManager {
183     /// 注册设备驱动。该设备驱动应当已经设置好其bus字段
184     ///
185     /// ## 参数
186     ///
187     /// - driver: 驱动
188     ///
189     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/driver.c#222
190     pub fn register(&self, driver: Arc<dyn Driver>) -> Result<(), SystemError> {
191         let bus = driver.bus().and_then(|bus| bus.upgrade()).ok_or_else(|| {
192             kerror!(
193                 "DriverManager::register() failed: driver.bus() is None. Driver: '{:?}'",
194                 driver.name()
195             );
196             SystemError::EINVAL
197         })?;
198 
199         let drv_name = driver.name();
200         let other = bus.find_driver_by_name(&drv_name);
201         if other.is_some() {
202             kerror!(
203                 "DriverManager::register() failed: driver '{}' already registered",
204                 drv_name
205             );
206             return Err(SystemError::EBUSY);
207         }
208 
209         bus_manager().add_driver(&driver)?;
210 
211         self.add_groups(&driver, driver.groups()).map_err(|e| {
212             bus_manager().remove_driver(&driver);
213             e
214         })?;
215 
216         // todo: 发送uevent
217 
218         return Ok(());
219     }
220 
221     /// 从系统中删除一个驱动程序
222     #[allow(dead_code)]
223     pub fn unregister(&self, driver: &Arc<dyn Driver>) {
224         self.remove_groups(driver, driver.groups());
225         bus_manager().remove_driver(driver);
226     }
227 
228     /// 参考: https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c#434
229     pub fn driver_sysfs_add(&self, _dev: &Arc<dyn Device>) -> Result<(), SystemError> {
230         todo!("DriverManager::driver_sysfs_add()");
231     }
232 
233     pub fn add_groups(
234         &self,
235         driver: &Arc<dyn Driver>,
236         groups: &'static [&dyn AttributeGroup],
237     ) -> Result<(), SystemError> {
238         let kobj = driver.clone() as Arc<dyn KObject>;
239         return sysfs_instance().create_groups(&kobj, groups);
240     }
241 
242     pub fn remove_groups(&self, driver: &Arc<dyn Driver>, groups: &'static [&dyn AttributeGroup]) {
243         let kobj = driver.clone() as Arc<dyn KObject>;
244         sysfs_instance().remove_groups(&kobj, groups);
245     }
246 
247     /// 为指定的驱动创建一个属性文件
248     ///
249     /// ## 参数
250     ///
251     /// - `driver` 要创建属性文件的驱动
252     /// - `attr` 属性
253     pub fn create_attr_file(
254         &self,
255         driver: &Arc<dyn Driver>,
256         attr: &'static dyn Attribute,
257     ) -> Result<(), SystemError> {
258         let kobj = driver.clone() as Arc<dyn KObject>;
259         return sysfs_instance().create_file(&kobj, attr);
260     }
261 
262     /// 为指定的驱动删除一个属性文件
263     ///
264     /// 如果属性不存在,也不会报错
265     ///
266     /// ## 参数
267     ///
268     /// - `driver` 要删除属性文件的驱动
269     /// - `attr` 属性
270     pub fn remove_attr_file(&self, driver: &Arc<dyn Driver>, attr: &'static dyn Attribute) {
271         let kobj = driver.clone() as Arc<dyn KObject>;
272         sysfs_instance().remove_file(&kobj, attr);
273     }
274 }
275 
276 /// 驱动匹配器
277 ///
278 /// 用于匹配驱动是否符合某个条件
279 ///
280 /// ## 参数
281 ///
282 /// - `T` - 匹配器的数据类型
283 /// - `data` - 匹配器的数据
284 pub trait DriverMatcher<T>: Debug {
285     fn match_driver(&self, driver: &Arc<dyn Driver>, data: T) -> bool;
286 }
287 
288 /// 根据名称匹配驱动
289 #[derive(Debug)]
290 pub struct DriverMatchName;
291 
292 impl DriverMatcher<&str> for DriverMatchName {
293     #[inline(always)]
294     fn match_driver(&self, driver: &Arc<dyn Driver>, data: &str) -> bool {
295         driver.name() == data
296     }
297 }
298 
299 /// enum probe_type - device driver probe type to try
300 /// Device drivers may opt in for special handling of their
301 /// respective probe routines. This tells the core what to
302 /// expect and prefer.
303 ///
304 /// Note that the end goal is to switch the kernel to use asynchronous
305 /// probing by default, so annotating drivers with
306 /// %PROBE_PREFER_ASYNCHRONOUS is a temporary measure that allows us
307 /// to speed up boot process while we are validating the rest of the
308 /// drivers.
309 #[allow(dead_code)]
310 #[derive(Debug, Default)]
311 pub enum DriverProbeType {
312     /// Drivers for "slow" devices which
313     /// probing order is not essential for booting the system may
314     /// opt into executing their probes asynchronously.
315     PreferAsync,
316 
317     /// Use this to annotate drivers that need
318     /// their probe routines to run synchronously with driver and
319     /// device registration (with the exception of -EPROBE_DEFER
320     /// handling - re-probing always ends up being done asynchronously).
321     ForceSync,
322 
323     #[default]
324     /// Used by drivers that work equally well
325     /// whether probed synchronously or asynchronously.
326     DefaultStrategy,
327 }
328