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