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