1 use alloc::{ 2 collections::BTreeMap, 3 string::{String, ToString}, 4 sync::Arc, 5 }; 6 7 use crate::{ 8 driver::base::map::{LockedDevsMap, LockedKObjMap}, 9 filesystem::{ 10 sysfs::{ 11 devices::{sys_device_register, sys_device_unregister}, 12 SYS_DEVICES_INODE, 13 }, 14 vfs::IndexNode, 15 }, 16 libs::spinlock::SpinLock, 17 syscall::SystemError, 18 }; 19 use core::{any::Any, fmt::Debug}; 20 21 use super::platform::CompatibleTable; 22 23 pub mod bus; 24 pub mod driver; 25 pub mod init; 26 27 lazy_static! { 28 pub static ref DEVICE_MANAGER: Arc<LockedDeviceManager> = Arc::new(LockedDeviceManager::new()); 29 } 30 lazy_static! { 31 // 全局字符设备号管理实例 32 pub static ref CHARDEVS: Arc<LockedDevsMap> = Arc::new(LockedDevsMap::default()); 33 34 // 全局块设备管理实例 35 pub static ref BLOCKDEVS: Arc<LockedDevsMap> = Arc::new(LockedDevsMap::default()); 36 37 // 全局设备管理实例 38 pub static ref DEVMAP: Arc<LockedKObjMap> = Arc::new(LockedKObjMap::default()); 39 40 } 41 42 pub trait KObject: Any + Send + Sync + Debug {} 43 /// @brief 设备应该实现的操作 44 /// @usage Device::read_at() 45 pub trait Device: KObject { 46 // TODO: 待实现 open, close 47 fn as_any_ref(&self) -> &dyn core::any::Any; 48 /// @brief: 获取设备类型 49 /// @parameter: None 50 /// @return: 实现该trait的设备所属类型 51 fn dev_type(&self) -> DeviceType; 52 53 /// @brief: 获取设备标识 54 /// @parameter: None 55 /// @return: 该设备唯一标识 56 fn id_table(&self) -> IdTable; 57 58 /// @brief: 设置sysfs info 59 /// @parameter: None 60 /// @return: 该设备唯一标识 61 fn set_sys_info(&self, _sys_info: Option<Arc<dyn IndexNode>>); 62 63 /// @brief: 获取设备的sys information 64 /// @parameter id_table: 设备标识符,用于唯一标识该设备 65 /// @return: 设备实例 66 fn sys_info(&self) -> Option<Arc<dyn IndexNode>>; 67 } 68 69 // 暂定是不可修改的,在初始化的时候就要确定。以后可能会包括例如硬件中断包含的信息 70 #[allow(dead_code)] 71 #[derive(Debug, Clone)] 72 pub struct DevicePrivateData { 73 id_table: IdTable, 74 resource: Option<DeviceResource>, 75 compatible_table: CompatibleTable, 76 state: DeviceState, 77 } 78 79 impl DevicePrivateData { 80 pub fn new( 81 id_table: IdTable, 82 resource: Option<DeviceResource>, 83 compatible_table: CompatibleTable, 84 state: DeviceState, 85 ) -> Self { 86 Self { 87 id_table, 88 resource, 89 compatible_table, 90 state, 91 } 92 } 93 94 pub fn id_table(&self) -> &IdTable { 95 &self.id_table 96 } 97 98 pub fn state(&self) -> DeviceState { 99 self.state 100 } 101 102 #[allow(dead_code)] 103 pub fn resource(&self) -> Option<&DeviceResource> { 104 self.resource.as_ref() 105 } 106 107 pub fn compatible_table(&self) -> &CompatibleTable { 108 &self.compatible_table 109 } 110 111 pub fn set_state(&mut self, state: DeviceState) { 112 self.state = state; 113 } 114 } 115 116 #[derive(Debug, Clone)] 117 pub struct DeviceResource { 118 //可能会用来保存例如 IRQ PWM 内存地址等需要申请的资源,将来由资源管理器+Framework框架进行管理。 119 } 120 121 impl Default for DeviceResource { 122 fn default() -> Self { 123 return Self {}; 124 } 125 } 126 127 int_like!(DeviceNumber, usize); 128 129 impl Default for DeviceNumber { 130 fn default() -> Self { 131 DeviceNumber(0) 132 } 133 } 134 135 impl From<usize> for DeviceNumber { 136 fn from(dev_t: usize) -> Self { 137 DeviceNumber(dev_t) 138 } 139 } 140 141 impl Into<usize> for DeviceNumber { 142 fn into(self) -> usize { 143 self.0 144 } 145 } 146 147 impl core::hash::Hash for DeviceNumber { 148 fn hash<H: core::hash::Hasher>(&self, state: &mut H) { 149 self.0.hash(state); 150 } 151 } 152 153 impl DeviceNumber { 154 /// @brief: 设备号创建 155 /// @parameter: dev_t: 设备号 156 /// @return: 设备号实例 157 pub fn new(dev_t: usize) -> DeviceNumber { 158 Self(dev_t) 159 } 160 161 /// @brief: 获取主设备号 162 /// @parameter: none 163 /// @return: 主设备号 164 pub fn major(&self) -> usize { 165 (self.0 >> 20) & 0xfff 166 } 167 168 /// @brief: 获取次设备号 169 /// @parameter: none 170 /// @return: 次设备号 171 pub fn minor(&self) -> usize { 172 self.0 & 0xfffff 173 } 174 175 pub fn from_major_minor(major: usize, minor: usize) -> usize { 176 ((major & 0xffffff) << 8) | (minor & 0xff) 177 } 178 } 179 180 /// @brief: 根据主次设备号创建设备号实例 181 /// @parameter: major: 主设备号 182 /// minor: 次设备号 183 /// @return: 设备号实例 184 pub fn mkdev(major: usize, minor: usize) -> DeviceNumber { 185 DeviceNumber(((major & 0xfff) << 20) | (minor & 0xfffff)) 186 } 187 188 /// @brief: 设备类型 189 #[allow(dead_code)] 190 #[derive(Debug, Eq, PartialEq)] 191 pub enum DeviceType { 192 Bus, 193 Net, 194 Gpu, 195 Input, 196 Block, 197 Rtc, 198 Serial, 199 Intc, 200 PlatformDev, 201 } 202 203 /// @brief: 设备标识符类型 204 #[derive(Debug, Clone, Hash, PartialOrd, PartialEq, Ord, Eq)] 205 pub struct IdTable(String, DeviceNumber); 206 207 /// @brief: 设备标识符操作方法集 208 impl IdTable { 209 /// @brief: 创建一个新的设备标识符 210 /// @parameter name: 设备名 211 /// @parameter id: 设备id 212 /// @return: 设备标识符 213 pub fn new(name: String, id: DeviceNumber) -> IdTable { 214 Self(name, id) 215 } 216 217 /// @brief: 将设备标识符转换成name 218 /// @parameter None 219 /// @return: 设备名 220 pub fn name(&self) -> String { 221 return format!("{}:{:?}", self.0, self.1 .0); 222 } 223 224 pub fn device_number(&self) -> DeviceNumber { 225 return self.1; 226 } 227 } 228 229 impl Default for IdTable { 230 fn default() -> Self { 231 IdTable("unknown".to_string(), DeviceNumber::new(0)) 232 } 233 } 234 235 // 以现在的模型,设备在加载到系统中就是已经初始化的状态了,因此可以考虑把这个删掉 236 /// @brief: 设备当前状态 237 #[derive(Debug, Clone, Copy)] 238 pub enum DeviceState { 239 NotInitialized = 0, 240 Initialized = 1, 241 UnDefined = 2, 242 } 243 244 /// @brief: 设备错误类型 245 #[allow(dead_code)] 246 #[derive(Debug, Copy, Clone)] 247 pub enum DeviceError { 248 DriverExists, // 设备已存在 249 DeviceExists, // 驱动已存在 250 InitializeFailed, // 初始化错误 251 NotInitialized, // 未初始化的设备 252 NoDeviceForDriver, // 没有合适的设备匹配驱动 253 NoDriverForDevice, // 没有合适的驱动匹配设备 254 RegisterError, // 注册失败 255 UnsupportedOperation, // 不支持的操作 256 } 257 258 impl Into<SystemError> for DeviceError { 259 fn into(self) -> SystemError { 260 match self { 261 DeviceError::DriverExists => SystemError::EEXIST, 262 DeviceError::DeviceExists => SystemError::EEXIST, 263 DeviceError::InitializeFailed => SystemError::EIO, 264 DeviceError::NotInitialized => SystemError::ENODEV, 265 DeviceError::NoDeviceForDriver => SystemError::ENODEV, 266 DeviceError::NoDriverForDevice => SystemError::ENODEV, 267 DeviceError::RegisterError => SystemError::EIO, 268 DeviceError::UnsupportedOperation => SystemError::EIO, 269 } 270 } 271 } 272 273 /// @brief: 将u32类型转换为设备状态类型 274 impl From<u32> for DeviceState { 275 fn from(state: u32) -> Self { 276 match state { 277 0 => DeviceState::NotInitialized, 278 1 => DeviceState::Initialized, 279 _ => todo!(), 280 } 281 } 282 } 283 284 /// @brief: 将设备状态转换为u32类型 285 impl From<DeviceState> for u32 { 286 fn from(state: DeviceState) -> Self { 287 match state { 288 DeviceState::NotInitialized => 0, 289 DeviceState::Initialized => 1, 290 DeviceState::UnDefined => 2, 291 } 292 } 293 } 294 295 /// @brief Device管理器(锁) 296 #[derive(Debug)] 297 pub struct LockedDeviceManager(SpinLock<DeviceManager>); 298 299 impl LockedDeviceManager { 300 fn new() -> LockedDeviceManager { 301 LockedDeviceManager(SpinLock::new(DeviceManager::new())) 302 } 303 304 /// @brief: 添加设备 305 /// @parameter id_table: 总线标识符,用于唯一标识该总线 306 /// @parameter dev: 设备实例 307 /// @return: None 308 #[inline] 309 #[allow(dead_code)] 310 pub fn add_device(&self, id_table: IdTable, dev: Arc<dyn Device>) { 311 let mut device_manager = self.0.lock(); 312 device_manager.devices.insert(id_table, dev); 313 } 314 315 /// @brief: 卸载设备 316 /// @parameter id_table: 总线标识符,用于唯一标识该设备 317 /// @return: None 318 #[inline] 319 #[allow(dead_code)] 320 pub fn remove_device(&self, id_table: &IdTable) { 321 let mut device_manager = self.0.lock(); 322 device_manager.devices.remove(id_table); 323 } 324 325 /// @brief: 获取设备 326 /// @parameter id_table: 设备标识符,用于唯一标识该设备 327 /// @return: 设备实例 328 #[inline] 329 #[allow(dead_code)] 330 pub fn get_device(&self, id_table: &IdTable) -> Option<Arc<dyn Device>> { 331 let device_manager = self.0.lock(); 332 device_manager.devices.get(id_table).cloned() 333 } 334 335 /// @brief: 获取设备管理器的sys information 336 /// @parameter id_table: 设备标识符,用于唯一标识该设备 337 /// @return: 设备实例 338 #[inline] 339 #[allow(dead_code)] 340 fn sys_info(&self) -> Option<Arc<dyn IndexNode>> { 341 return self.0.lock().sys_info.clone(); 342 } 343 } 344 345 /// @brief Device管理器 346 #[derive(Debug, Clone)] 347 pub struct DeviceManager { 348 devices: BTreeMap<IdTable, Arc<dyn Device>>, // 所有设备 349 sys_info: Option<Arc<dyn IndexNode>>, // sys information 350 } 351 352 impl DeviceManager { 353 /// @brief: 创建一个新的设备管理器 354 /// @parameter: None 355 /// @return: DeviceManager实体 356 #[inline] 357 fn new() -> DeviceManager { 358 DeviceManager { 359 devices: BTreeMap::new(), 360 sys_info: Some(SYS_DEVICES_INODE()), 361 } 362 } 363 } 364 365 /// @brief: 设备注册 366 /// @parameter: name: 设备名 367 /// @return: 操作成功,返回(),操作失败,返回错误码 368 pub fn device_register<T: Device>(device: Arc<T>) -> Result<(), DeviceError> { 369 DEVICE_MANAGER.add_device(device.id_table(), device.clone()); 370 match sys_device_register(&device.id_table().name()) { 371 Ok(sys_info) => { 372 device.set_sys_info(Some(sys_info)); 373 return Ok(()); 374 } 375 Err(_) => Err(DeviceError::RegisterError), 376 } 377 } 378 379 /// @brief: 设备卸载 380 /// @parameter: name: 设备名 381 /// @return: 操作成功,返回(),操作失败,返回错误码 382 pub fn device_unregister<T: Device>(device: Arc<T>) -> Result<(), DeviceError> { 383 DEVICE_MANAGER.add_device(device.id_table(), device.clone()); 384 match sys_device_unregister(&device.id_table().name()) { 385 Ok(_) => { 386 device.set_sys_info(None); 387 return Ok(()); 388 } 389 Err(_) => Err(DeviceError::RegisterError), 390 } 391 } 392