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 Into<SystemError> for DriverError { 28 fn into(self) -> SystemError { 29 match self { 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::EOPNOTSUPP_OR_ENOTSUP) 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 impl dyn Driver { 113 pub fn allows_async_probing(&self) -> bool { 114 match self.probe_type() { 115 DriverProbeType::PreferAsync => true, 116 DriverProbeType::ForceSync => false, 117 DriverProbeType::DefaultStrategy => { 118 // todo: 判断是否请求异步探测,如果是的话,就返回true 119 120 // 由于目前还没有支持异步探测,因此这里暂时返回false 121 false 122 } 123 } 124 } 125 126 /// 根据条件寻找一个绑定到这个驱动的设备(低效实现) 127 /// 128 /// ## 参数 129 /// 130 /// - `matcher` - 匹配器 131 /// - `data` - 传给匹配器的数据 132 /// 133 /// ## 注意 134 /// 135 /// 这里的默认实现很低效,请为特定的驱动自行实现高效的查询 136 fn find_device_slow<T: Copy>( 137 &self, 138 matcher: &dyn DeviceMatcher<T>, 139 data: T, 140 ) -> Option<Arc<dyn Device>> { 141 for dev in self.devices() { 142 if matcher.match_device(&dev, data) { 143 return Some(dev); 144 } 145 } 146 147 return None; 148 } 149 150 /// 根据设备名称查找绑定到驱动的设备 151 /// 152 /// ## 注意 153 /// 154 /// 这里的默认实现很低效,请为特定的驱动自行实现高效的查询 155 pub fn find_device_by_name(&self, name: &str) -> Option<Arc<dyn Device>> { 156 if let Some(r) = self.__find_device_by_name_fast(name) { 157 return Some(r); 158 } 159 160 return self.find_device_slow(&DeviceMatchName, name); 161 } 162 } 163 164 /// @brief: 驱动管理器 165 #[derive(Debug, Clone)] 166 pub struct DriverManager; 167 168 impl DriverManager { 169 /// 注册设备驱动。该设备驱动应当已经设置好其bus字段 170 /// 171 /// ## 参数 172 /// 173 /// - driver: 驱动 174 /// 175 /// 参考 https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/driver.c#222 176 pub fn register(&self, driver: Arc<dyn Driver>) -> Result<(), SystemError> { 177 let bus = driver 178 .bus() 179 .map(|bus| bus.upgrade()) 180 .flatten() 181 .ok_or_else(|| { 182 kerror!( 183 "DriverManager::register() failed: driver.bus() is None. Driver: '{:?}'", 184 driver.name() 185 ); 186 SystemError::EINVAL 187 })?; 188 189 let drv_name = driver.name(); 190 let other = bus.find_driver_by_name(&drv_name); 191 if other.is_some() { 192 kerror!( 193 "DriverManager::register() failed: driver '{}' already registered", 194 drv_name 195 ); 196 return Err(SystemError::EBUSY); 197 } 198 199 bus_manager().add_driver(&driver)?; 200 201 self.add_groups(&driver, driver.groups()).map_err(|e| { 202 bus_manager().remove_driver(&driver); 203 e 204 })?; 205 206 // todo: 发送uevent 207 208 return Ok(()); 209 } 210 211 /// 从系统中删除一个驱动程序 212 #[allow(dead_code)] 213 pub fn unregister(&self, driver: &Arc<dyn Driver>) { 214 self.remove_groups(driver, driver.groups()); 215 bus_manager().remove_driver(driver); 216 } 217 218 /// 参考: https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/dd.c#434 219 pub fn driver_sysfs_add(&self, _dev: &Arc<dyn Device>) -> Result<(), SystemError> { 220 todo!("DriverManager::driver_sysfs_add()"); 221 } 222 223 pub fn add_groups( 224 &self, 225 driver: &Arc<dyn Driver>, 226 groups: &'static [&dyn AttributeGroup], 227 ) -> Result<(), SystemError> { 228 let kobj = driver.clone() as Arc<dyn KObject>; 229 return sysfs_instance().create_groups(&kobj, groups); 230 } 231 232 pub fn remove_groups(&self, driver: &Arc<dyn Driver>, groups: &'static [&dyn AttributeGroup]) { 233 let kobj = driver.clone() as Arc<dyn KObject>; 234 sysfs_instance().remove_groups(&kobj, groups); 235 } 236 237 /// 为指定的驱动创建一个属性文件 238 /// 239 /// ## 参数 240 /// 241 /// - `driver` 要创建属性文件的驱动 242 /// - `attr` 属性 243 pub fn create_attr_file( 244 &self, 245 driver: &Arc<dyn Driver>, 246 attr: &'static dyn Attribute, 247 ) -> Result<(), SystemError> { 248 let kobj = driver.clone() as Arc<dyn KObject>; 249 return sysfs_instance().create_file(&kobj, attr); 250 } 251 252 /// 为指定的驱动删除一个属性文件 253 /// 254 /// 如果属性不存在,也不会报错 255 /// 256 /// ## 参数 257 /// 258 /// - `driver` 要删除属性文件的驱动 259 /// - `attr` 属性 260 pub fn remove_attr_file(&self, driver: &Arc<dyn Driver>, attr: &'static dyn Attribute) { 261 let kobj = driver.clone() as Arc<dyn KObject>; 262 sysfs_instance().remove_file(&kobj, attr); 263 } 264 } 265 266 /// 驱动匹配器 267 /// 268 /// 用于匹配驱动是否符合某个条件 269 /// 270 /// ## 参数 271 /// 272 /// - `T` - 匹配器的数据类型 273 /// - `data` - 匹配器的数据 274 pub trait DriverMatcher<T>: Debug { 275 fn match_driver(&self, driver: &Arc<dyn Driver>, data: T) -> bool; 276 } 277 278 /// 根据名称匹配驱动 279 #[derive(Debug)] 280 pub struct DriverMatchName; 281 282 impl DriverMatcher<&str> for DriverMatchName { 283 #[inline(always)] 284 fn match_driver(&self, driver: &Arc<dyn Driver>, data: &str) -> bool { 285 driver.name() == data 286 } 287 } 288 289 /// enum probe_type - device driver probe type to try 290 /// Device drivers may opt in for special handling of their 291 /// respective probe routines. This tells the core what to 292 /// expect and prefer. 293 /// 294 /// Note that the end goal is to switch the kernel to use asynchronous 295 /// probing by default, so annotating drivers with 296 /// %PROBE_PREFER_ASYNCHRONOUS is a temporary measure that allows us 297 /// to speed up boot process while we are validating the rest of the 298 /// drivers. 299 #[allow(dead_code)] 300 #[derive(Debug)] 301 pub enum DriverProbeType { 302 /// Used by drivers that work equally well 303 /// whether probed synchronously or asynchronously. 304 DefaultStrategy, 305 306 /// Drivers for "slow" devices which 307 /// probing order is not essential for booting the system may 308 /// opt into executing their probes asynchronously. 309 PreferAsync, 310 311 /// Use this to annotate drivers that need 312 /// their probe routines to run synchronously with driver and 313 /// device registration (with the exception of -EPROBE_DEFER 314 /// handling - re-probing always ends up being done asynchronously). 315 ForceSync, 316 } 317 318 impl Default for DriverProbeType { 319 fn default() -> Self { 320 DriverProbeType::DefaultStrategy 321 } 322 } 323