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