1 use alloc::{ 2 string::{String, ToString}, 3 sync::{Arc, Weak}, 4 }; 5 use intertrait::cast::CastArc; 6 7 use crate::{ 8 driver::{ 9 acpi::glue::acpi_device_notify, 10 base::map::{LockedDevsMap, LockedKObjMap}, 11 }, 12 filesystem::{ 13 sysfs::{ 14 file::sysfs_emit_str, sysfs_instance, Attribute, AttributeGroup, SysFSOps, 15 SysFSOpsSupport, 16 }, 17 vfs::syscall::ModeType, 18 }, 19 }; 20 21 use core::fmt::Debug; 22 use core::intrinsics::unlikely; 23 use system_error::SystemError; 24 25 use self::{ 26 bus::{bus_add_device, bus_probe_device, Bus}, 27 device_number::{DeviceNumber, Major}, 28 driver::Driver, 29 }; 30 31 use super::{ 32 class::Class, 33 kobject::{KObjType, KObject, KObjectManager, KObjectState}, 34 kset::KSet, 35 swnode::software_node_notify, 36 }; 37 38 pub mod bus; 39 pub mod dd; 40 pub mod device_number; 41 pub mod driver; 42 pub mod init; 43 44 static mut DEVICE_MANAGER: Option<DeviceManager> = None; 45 46 #[inline(always)] 47 pub fn device_manager() -> &'static DeviceManager { 48 unsafe { DEVICE_MANAGER.as_ref().unwrap() } 49 } 50 51 lazy_static! { 52 // 全局字符设备号管理实例 53 pub static ref CHARDEVS: Arc<LockedDevsMap> = Arc::new(LockedDevsMap::default()); 54 55 // 全局块设备管理实例 56 pub static ref BLOCKDEVS: Arc<LockedDevsMap> = Arc::new(LockedDevsMap::default()); 57 58 // 全局设备管理实例 59 pub static ref DEVMAP: Arc<LockedKObjMap> = Arc::new(LockedKObjMap::default()); 60 61 } 62 63 /// `/sys/devices` 的 kset 实例 64 static mut DEVICES_KSET_INSTANCE: Option<Arc<KSet>> = None; 65 /// `/sys/dev` 的 kset 实例 66 static mut DEV_KSET_INSTANCE: Option<Arc<KSet>> = None; 67 /// `/sys/dev/block` 的 kset 实例 68 static mut DEV_BLOCK_KSET_INSTANCE: Option<Arc<KSet>> = None; 69 /// `/sys/dev/char` 的 kset 实例 70 static mut DEV_CHAR_KSET_INSTANCE: Option<Arc<KSet>> = None; 71 72 /// `/sys/devices/virtual` 的 kset 实例 73 static mut DEVICES_VIRTUAL_KSET_INSTANCE: Option<Arc<KSet>> = None; 74 75 /// 获取`/sys/devices`的kset实例 76 #[inline(always)] 77 pub(super) fn sys_devices_kset() -> Arc<KSet> { 78 unsafe { DEVICES_KSET_INSTANCE.as_ref().unwrap().clone() } 79 } 80 81 /// 获取`/sys/dev`的kset实例 82 #[inline(always)] 83 pub(super) fn sys_dev_kset() -> Arc<KSet> { 84 unsafe { DEV_KSET_INSTANCE.as_ref().unwrap().clone() } 85 } 86 87 /// 获取`/sys/dev/block`的kset实例 88 #[inline(always)] 89 #[allow(dead_code)] 90 pub fn sys_dev_block_kset() -> Arc<KSet> { 91 unsafe { DEV_BLOCK_KSET_INSTANCE.as_ref().unwrap().clone() } 92 } 93 94 /// 获取`/sys/dev/char`的kset实例 95 #[inline(always)] 96 pub fn sys_dev_char_kset() -> Arc<KSet> { 97 unsafe { DEV_CHAR_KSET_INSTANCE.as_ref().unwrap().clone() } 98 } 99 100 pub(self) unsafe fn set_sys_dev_block_kset(kset: Arc<KSet>) { 101 DEV_BLOCK_KSET_INSTANCE = Some(kset); 102 } 103 104 pub(self) unsafe fn set_sys_dev_char_kset(kset: Arc<KSet>) { 105 DEV_CHAR_KSET_INSTANCE = Some(kset); 106 } 107 108 /// 获取`/sys/devices/virtual`的kset实例 109 pub fn sys_devices_virtual_kset() -> Arc<KSet> { 110 unsafe { DEVICES_VIRTUAL_KSET_INSTANCE.as_ref().unwrap().clone() } 111 } 112 113 pub(self) unsafe fn set_sys_devices_virtual_kset(kset: Arc<KSet>) { 114 DEVICES_VIRTUAL_KSET_INSTANCE = Some(kset); 115 } 116 117 /// 设备应该实现的操作 118 /// 119 /// ## 注意 120 /// 121 /// 由于设备驱动模型需要从Arc<dyn KObject>转换为Arc<dyn Device>, 122 /// 因此,所有的实现了Device trait的结构体,都应该在结构体上方标注`#[cast_to([sync] Device)]`, 123 /// 124 /// 否则在释放设备资源的时候,会由于无法转换为Arc<dyn Device>而导致资源泄露,并且release回调函数也不会被调用。 125 pub trait Device: KObject { 126 // TODO: 待实现 open, close 127 128 /// @brief: 获取设备类型 129 /// @parameter: None 130 /// @return: 实现该trait的设备所属类型 131 fn dev_type(&self) -> DeviceType; 132 133 /// @brief: 获取设备标识 134 /// @parameter: None 135 /// @return: 该设备唯一标识 136 fn id_table(&self) -> IdTable; 137 138 /// 设备释放时的回调函数 139 fn release(&self) { 140 let name = self.name(); 141 kwarn!( 142 "device {} does not have a release() function, it is broken and must be fixed.", 143 name 144 ); 145 } 146 147 /// 获取当前设备所属的总线 148 fn bus(&self) -> Option<Weak<dyn Bus>> { 149 return None; 150 } 151 152 /// 设置当前设备所属的总线 153 /// 154 /// (一定要传入Arc,因为bus的subsysprivate里面存储的是Device的Arc指针) 155 /// 156 /// 注意,如果实现了当前方法,那么必须实现`bus()`方法 157 fn set_bus(&self, bus: Option<Weak<dyn Bus>>); 158 159 /// 获取当前设备所属的类 160 fn class(&self) -> Option<Arc<dyn Class>> { 161 return None; 162 } 163 164 /// 设置当前设备所属的类 165 /// 166 /// 注意,如果实现了当前方法,那么必须实现`class()`方法 167 fn set_class(&self, class: Option<Arc<dyn Class>>); 168 169 /// 返回已经与当前设备匹配好的驱动程序 170 fn driver(&self) -> Option<Arc<dyn Driver>>; 171 172 fn set_driver(&self, driver: Option<Weak<dyn Driver>>); 173 174 /// 当前设备是否已经挂掉了 175 fn is_dead(&self) -> bool; 176 177 /// 当前设备是否处于可以被匹配的状态 178 /// 179 /// The device has matched with a driver at least once or it is in 180 /// a bus (like AMBA) which can't check for matching drivers until 181 /// other devices probe successfully. 182 fn can_match(&self) -> bool; 183 184 fn set_can_match(&self, can_match: bool); 185 186 /// The hardware state of this device has been synced to match 187 /// the software state of this device by calling the driver/bus 188 /// sync_state() callback. 189 fn state_synced(&self) -> bool; 190 191 fn attribute_groups(&self) -> Option<&'static [&'static dyn AttributeGroup]> { 192 None 193 } 194 } 195 196 impl dyn Device { 197 #[inline(always)] 198 pub fn is_registered(&self) -> bool { 199 self.kobj_state().contains(KObjectState::IN_SYSFS) 200 } 201 } 202 203 // 暂定是不可修改的,在初始化的时候就要确定。以后可能会包括例如硬件中断包含的信息 204 #[allow(dead_code)] 205 #[derive(Debug, Clone)] 206 pub struct DevicePrivateData { 207 id_table: IdTable, 208 state: DeviceState, 209 } 210 211 #[allow(dead_code)] 212 impl DevicePrivateData { 213 pub fn new(id_table: IdTable, state: DeviceState) -> Self { 214 Self { id_table, state } 215 } 216 217 pub fn id_table(&self) -> &IdTable { 218 &self.id_table 219 } 220 221 pub fn state(&self) -> DeviceState { 222 self.state 223 } 224 225 pub fn set_state(&mut self, state: DeviceState) { 226 self.state = state; 227 } 228 } 229 230 /// @brief: 设备类型 231 #[allow(dead_code)] 232 #[derive(Debug, Eq, PartialEq)] 233 pub enum DeviceType { 234 Bus, 235 Net, 236 Gpu, 237 Input, 238 Block, 239 Rtc, 240 Serial, 241 Intc, 242 PlatformDev, 243 Char, 244 } 245 246 /// @brief: 设备标识符类型 247 #[derive(Debug, Clone, Hash, PartialOrd, PartialEq, Ord, Eq)] 248 pub struct IdTable { 249 basename: String, 250 id: Option<DeviceNumber>, 251 } 252 253 /// @brief: 设备标识符操作方法集 254 impl IdTable { 255 /// @brief: 创建一个新的设备标识符 256 /// @parameter name: 设备名 257 /// @parameter id: 设备id 258 /// @return: 设备标识符 259 pub fn new(basename: String, id: Option<DeviceNumber>) -> IdTable { 260 return IdTable { basename, id }; 261 } 262 263 /// @brief: 将设备标识符转换成name 264 /// @parameter None 265 /// @return: 设备名 266 pub fn name(&self) -> String { 267 if self.id.is_none() { 268 return self.basename.clone(); 269 } else { 270 let id = self.id.unwrap(); 271 return format!("{}:{}", id.major().data(), id.minor()); 272 } 273 } 274 275 pub fn device_number(&self) -> DeviceNumber { 276 return self.id.unwrap_or(DeviceNumber::default()); 277 } 278 } 279 280 impl Default for IdTable { 281 fn default() -> Self { 282 IdTable::new("unknown".to_string(), None) 283 } 284 } 285 286 // 以现在的模型,设备在加载到系统中就是已经初始化的状态了,因此可以考虑把这个删掉 287 /// @brief: 设备当前状态 288 #[derive(Debug, Clone, Copy, Eq, PartialEq)] 289 pub enum DeviceState { 290 NotInitialized = 0, 291 Initialized = 1, 292 UnDefined = 2, 293 } 294 295 /// @brief: 设备错误类型 296 #[allow(dead_code)] 297 #[derive(Debug, Copy, Clone)] 298 pub enum DeviceError { 299 DriverExists, // 设备已存在 300 DeviceExists, // 驱动已存在 301 InitializeFailed, // 初始化错误 302 NotInitialized, // 未初始化的设备 303 NoDeviceForDriver, // 没有合适的设备匹配驱动 304 NoDriverForDevice, // 没有合适的驱动匹配设备 305 RegisterError, // 注册失败 306 UnsupportedOperation, // 不支持的操作 307 } 308 309 impl Into<SystemError> for DeviceError { 310 fn into(self) -> SystemError { 311 match self { 312 DeviceError::DriverExists => SystemError::EEXIST, 313 DeviceError::DeviceExists => SystemError::EEXIST, 314 DeviceError::InitializeFailed => SystemError::EIO, 315 DeviceError::NotInitialized => SystemError::ENODEV, 316 DeviceError::NoDeviceForDriver => SystemError::ENODEV, 317 DeviceError::NoDriverForDevice => SystemError::ENODEV, 318 DeviceError::RegisterError => SystemError::EIO, 319 DeviceError::UnsupportedOperation => SystemError::EIO, 320 } 321 } 322 } 323 324 /// @brief: 将u32类型转换为设备状态类型 325 impl From<u32> for DeviceState { 326 fn from(state: u32) -> Self { 327 match state { 328 0 => DeviceState::NotInitialized, 329 1 => DeviceState::Initialized, 330 _ => todo!(), 331 } 332 } 333 } 334 335 /// @brief: 将设备状态转换为u32类型 336 impl From<DeviceState> for u32 { 337 fn from(state: DeviceState) -> Self { 338 match state { 339 DeviceState::NotInitialized => 0, 340 DeviceState::Initialized => 1, 341 DeviceState::UnDefined => 2, 342 } 343 } 344 } 345 346 #[derive(Debug)] 347 pub struct DeviceKObjType; 348 349 impl KObjType for DeviceKObjType { 350 // https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/core.c#2307 351 fn release(&self, kobj: Arc<dyn KObject>) { 352 let dev = kobj.cast::<dyn Device>().unwrap(); 353 /* 354 * Some platform devices are driven without driver attached 355 * and managed resources may have been acquired. Make sure 356 * all resources are released. 357 * 358 * Drivers still can add resources into device after device 359 * is deleted but alive, so release devres here to avoid 360 * possible memory leak. 361 */ 362 363 // todo: 在引入devres之后再实现 364 // devres_release_all(kobj); 365 dev.release(); 366 } 367 368 fn attribute_groups(&self) -> Option<&'static [&'static dyn AttributeGroup]> { 369 None 370 } 371 372 fn sysfs_ops(&self) -> Option<&dyn SysFSOps> { 373 Some(&DeviceSysFSOps) 374 } 375 } 376 377 #[derive(Debug)] 378 pub(super) struct DeviceSysFSOps; 379 380 impl SysFSOps for DeviceSysFSOps { 381 fn store( 382 &self, 383 kobj: Arc<dyn KObject>, 384 attr: &dyn Attribute, 385 buf: &[u8], 386 ) -> Result<usize, SystemError> { 387 return attr.store(kobj, buf); 388 } 389 390 fn show( 391 &self, 392 kobj: Arc<dyn KObject>, 393 attr: &dyn Attribute, 394 buf: &mut [u8], 395 ) -> Result<usize, SystemError> { 396 return attr.show(kobj, buf); 397 } 398 } 399 400 /// @brief Device管理器 401 #[derive(Debug)] 402 pub struct DeviceManager; 403 404 impl DeviceManager { 405 /// @brief: 创建一个新的设备管理器 406 /// @parameter: None 407 /// @return: DeviceManager实体 408 #[inline] 409 const fn new() -> DeviceManager { 410 return Self; 411 } 412 413 pub fn register(&self, device: Arc<dyn Device>) -> Result<(), SystemError> { 414 self.device_default_initialize(&device); 415 return self.add_device(device); 416 } 417 418 /// @brief: 添加设备 419 /// @parameter id_table: 总线标识符,用于唯一标识该总线 420 /// @parameter dev: 设备实例 421 /// @return: None 422 /// 423 /// https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/core.c#3398 424 /// 425 /// todo: 完善错误处理逻辑:如果添加失败,需要将之前添加的内容全部回滚 426 #[inline] 427 #[allow(dead_code)] 428 pub fn add_device(&self, device: Arc<dyn Device>) -> Result<(), SystemError> { 429 // 在这里处理与parent相关的逻辑 430 431 let current_parent = device 432 .parent() 433 .map(|x| x.upgrade()) 434 .flatten() 435 .map(|x| x.arc_any().cast::<dyn Device>().ok()) 436 .flatten(); 437 438 let actual_parent = self.get_device_parent(&device, current_parent)?; 439 if let Some(actual_parent) = actual_parent { 440 // kdebug!( 441 // "device '{}' parent is '{}', strong_count: {}", 442 // device.name().to_string(), 443 // actual_parent.name(), 444 // Arc::strong_count(&actual_parent) 445 // ); 446 device.set_parent(Some(Arc::downgrade(&actual_parent))); 447 } 448 449 KObjectManager::add_kobj(device.clone() as Arc<dyn KObject>, None).map_err(|e| { 450 kerror!("add device '{:?}' failed: {:?}", device.name(), e); 451 e 452 })?; 453 454 self.device_platform_notify(&device); 455 456 self.add_class_symlinks(&device)?; 457 458 self.add_attrs(&device)?; 459 460 bus_add_device(&device)?; 461 462 if device.id_table().device_number().major() != Major::UNNAMED_MAJOR { 463 self.create_file(&device, &DeviceAttrDev)?; 464 465 self.create_sys_dev_entry(&device)?; 466 } 467 468 // 通知客户端有关设备添加的信息。此调用必须在 dpm_sysfs_add() 之后且在 kobject_uevent() 之前执行。 469 if let Some(bus) = device.bus().map(|bus| bus.upgrade()).flatten() { 470 bus.subsystem().bus_notifier().call_chain( 471 bus::BusNotifyEvent::AddDevice, 472 Some(&device), 473 None, 474 ); 475 } 476 477 // todo: 发送uevent: KOBJ_ADD 478 479 // probe drivers for a new device 480 bus_probe_device(&device); 481 482 if let Some(class) = device.class() { 483 class.subsystem().add_device_to_vec(&device)?; 484 485 for class_interface in class.subsystem().interfaces() { 486 class_interface.add_device(&device).ok(); 487 } 488 } 489 490 return Ok(()); 491 } 492 493 /// 获取设备真实的parent kobject 494 /// 495 /// ## 参数 496 /// 497 /// - `device`: 设备 498 /// - `current_parent`: 当前的parent kobject 499 /// 500 /// ## 返回值 501 /// 502 /// - `Ok(Some(kobj))`: 如果找到了真实的parent kobject,那么返回它 503 /// - `Ok(None)`: 如果没有找到真实的parent kobject,那么返回None 504 /// - `Err(e)`: 如果发生错误,那么返回错误 505 fn get_device_parent( 506 &self, 507 device: &Arc<dyn Device>, 508 current_parent: Option<Arc<dyn Device>>, 509 ) -> Result<Option<Arc<dyn KObject>>, SystemError> { 510 // kdebug!("get_device_parent() device:{:?}", device.name()); 511 if let Some(_) = device.class() { 512 let parent_kobj: Arc<dyn KObject>; 513 // kdebug!("current_parent:{:?}", current_parent); 514 if current_parent.is_none() { 515 parent_kobj = sys_devices_virtual_kset() as Arc<dyn KObject>; 516 } else { 517 let cp = current_parent.unwrap(); 518 519 if cp.class().is_some() { 520 return Ok(Some(cp.clone() as Arc<dyn KObject>)); 521 } else { 522 parent_kobj = cp.clone() as Arc<dyn KObject>; 523 } 524 } 525 526 // 是否需要glue dir? 527 528 return Ok(Some(parent_kobj)); 529 } 530 531 // subsystems can specify a default root directory for their devices 532 if current_parent.is_none() { 533 if let Some(bus) = device.bus().map(|bus| bus.upgrade()).flatten() { 534 if let Some(root) = bus.root_device().map(|x| x.upgrade()).flatten() { 535 return Ok(Some(root as Arc<dyn KObject>)); 536 } 537 } 538 } 539 540 if current_parent.is_some() { 541 return Ok(Some(current_parent.unwrap().clone() as Arc<dyn KObject>)); 542 } 543 544 return Ok(None); 545 } 546 547 /// @brief: 卸载设备 548 /// @parameter id_table: 总线标识符,用于唯一标识该设备 549 /// @return: None 550 #[inline] 551 #[allow(dead_code)] 552 pub fn remove_device(&self, _id_table: &IdTable) { 553 todo!() 554 } 555 556 /// 参考 https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/dd.c?fi=driver_attach#542 557 fn remove(&self, _dev: &Arc<dyn Device>) { 558 todo!("DeviceManager::remove") 559 } 560 561 /// @brief: 获取设备 562 /// @parameter id_table: 设备标识符,用于唯一标识该设备 563 /// @return: 设备实例 564 #[inline] 565 #[allow(dead_code)] 566 pub fn find_device_by_idtable(&self, _id_table: &IdTable) -> Option<Arc<dyn Device>> { 567 todo!("find_device_by_idtable") 568 } 569 570 fn device_platform_notify(&self, dev: &Arc<dyn Device>) { 571 acpi_device_notify(dev); 572 software_node_notify(dev); 573 } 574 575 // 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/core.c#3224 576 fn add_class_symlinks(&self, dev: &Arc<dyn Device>) -> Result<(), SystemError> { 577 let class = dev.class(); 578 if class.is_none() { 579 return Ok(()); 580 } 581 582 // 定义错误处理函数,用于在添加符号链接失败时,移除已经添加的符号链接 583 584 let err_remove_device = |dev_kobj: &Arc<dyn KObject>| { 585 sysfs_instance().remove_link(dev_kobj, "device".to_string()); 586 }; 587 588 let err_remove_subsystem = |dev_kobj: &Arc<dyn KObject>| { 589 sysfs_instance().remove_link(dev_kobj, "subsystem".to_string()); 590 }; 591 592 let class = class.unwrap(); 593 let dev_kobj = dev.clone() as Arc<dyn KObject>; 594 let subsys_kobj = class.subsystem().subsys() as Arc<dyn KObject>; 595 sysfs_instance().create_link(Some(&dev_kobj), &subsys_kobj, "subsystem".to_string())?; 596 597 // todo: 这里需要处理class的parent逻辑, 添加device链接 598 if let Some(parent) = dev.parent().map(|x| x.upgrade()).flatten() { 599 let parent_kobj = parent.clone() as Arc<dyn KObject>; 600 sysfs_instance() 601 .create_link(Some(&dev_kobj), &&parent_kobj, "device".to_string()) 602 .map_err(|e| { 603 err_remove_subsystem(&dev_kobj); 604 e 605 })?; 606 } 607 608 sysfs_instance() 609 .create_link(Some(&subsys_kobj), &dev_kobj, dev.name()) 610 .map_err(|e| { 611 err_remove_device(&dev_kobj); 612 err_remove_subsystem(&dev_kobj); 613 e 614 })?; 615 616 return Ok(()); 617 } 618 619 /// 在sysfs中,为指定的设备创建属性文件 620 /// 621 /// ## 参数 622 /// 623 /// - `dev`: 设备 624 fn add_attrs(&self, dev: &Arc<dyn Device>) -> Result<(), SystemError> { 625 // 定义错误处理函数,用于在添加属性文件失败时,移除已经添加的属性组 626 let err_remove_class_groups = |dev: &Arc<dyn Device>| { 627 if let Some(class) = dev.class() { 628 let attr_groups = class.dev_groups(); 629 self.remove_groups(dev, attr_groups); 630 } 631 }; 632 633 let err_remove_kobj_type_groups = |dev: &Arc<dyn Device>| { 634 if let Some(kobj_type) = dev.kobj_type() { 635 let attr_groups = kobj_type.attribute_groups().unwrap_or(&[]); 636 self.remove_groups(dev, attr_groups); 637 } 638 }; 639 640 // 真正开始添加属性文件 641 642 // 添加设备类的属性文件 643 if let Some(class) = dev.class() { 644 let attr_groups = class.dev_groups(); 645 self.add_groups(dev, attr_groups)?; 646 } 647 648 // 添加kobj_type的属性文件 649 if let Some(kobj_type) = dev.kobj_type() { 650 self.add_groups(dev, kobj_type.attribute_groups().unwrap_or(&[])) 651 .map_err(|e| { 652 err_remove_class_groups(dev); 653 e 654 })?; 655 } 656 657 // 添加设备本身的属性文件 658 self.add_groups(dev, dev.attribute_groups().unwrap_or(&[])) 659 .map_err(|e| { 660 err_remove_kobj_type_groups(dev); 661 err_remove_class_groups(dev); 662 e 663 })?; 664 665 return Ok(()); 666 } 667 668 /// 在sysfs中,为指定的设备创建属性组,以及属性组中的属性文件 669 /// 670 /// ## 参数 671 /// 672 /// - `dev`: 设备 673 /// - `attr_groups`: 属性组 674 pub fn add_groups( 675 &self, 676 dev: &Arc<dyn Device>, 677 attr_groups: &'static [&dyn AttributeGroup], 678 ) -> Result<(), SystemError> { 679 let kobj = dev.clone() as Arc<dyn KObject>; 680 return sysfs_instance().create_groups(&kobj, attr_groups); 681 } 682 683 /// 在sysfs中,为指定的设备移除属性组,以及属性组中的属性文件 684 /// 685 /// ## 参数 686 /// 687 /// - `dev`: 设备 688 /// - `attr_groups`: 要移除的属性组 689 pub fn remove_groups( 690 &self, 691 dev: &Arc<dyn Device>, 692 attr_groups: &'static [&dyn AttributeGroup], 693 ) { 694 let kobj = dev.clone() as Arc<dyn KObject>; 695 sysfs_instance().remove_groups(&kobj, attr_groups); 696 } 697 698 /// 为设备在sysfs中创建属性文件 699 /// 700 /// ## 参数 701 /// 702 /// - `dev`: 设备 703 /// - `attr`: 属性 704 pub fn create_file( 705 &self, 706 dev: &Arc<dyn Device>, 707 attr: &'static dyn Attribute, 708 ) -> Result<(), SystemError> { 709 if unlikely( 710 attr.mode().contains(ModeType::S_IRUGO) 711 && (!attr.support().contains(SysFSOpsSupport::SHOW)), 712 ) { 713 kwarn!( 714 "Attribute '{}': read permission without 'show'", 715 attr.name() 716 ); 717 } 718 if unlikely( 719 attr.mode().contains(ModeType::S_IWUGO) 720 && (!attr.support().contains(SysFSOpsSupport::STORE)), 721 ) { 722 kwarn!( 723 "Attribute '{}': write permission without 'store'", 724 attr.name() 725 ); 726 } 727 728 let kobj = dev.clone() as Arc<dyn KObject>; 729 730 return sysfs_instance().create_file(&kobj, attr); 731 } 732 733 /// 在/sys/dev下,或者设备所属的class下,为指定的设备创建链接 734 fn create_sys_dev_entry(&self, dev: &Arc<dyn Device>) -> Result<(), SystemError> { 735 let target_kobj = self.device_to_dev_kobj(dev); 736 let name = dev.id_table().name(); 737 let current_kobj = dev.clone() as Arc<dyn KObject>; 738 return sysfs_instance().create_link(Some(&target_kobj), ¤t_kobj, name); 739 } 740 741 /// Delete symlink for device in `/sys/dev` or `/sys/class/<class_name>` 742 #[allow(dead_code)] 743 fn remove_sys_dev_entry(&self, dev: &Arc<dyn Device>) { 744 let kobj = self.device_to_dev_kobj(dev); 745 let name = dev.id_table().name(); 746 sysfs_instance().remove_link(&kobj, name); 747 } 748 749 /// device_to_dev_kobj - select a /sys/dev/ directory for the device 750 /// 751 /// By default we select char/ for new entries. 752 /// 753 /// ## 参数 754 /// 755 /// - `dev`: 设备 756 fn device_to_dev_kobj(&self, _dev: &Arc<dyn Device>) -> Arc<dyn KObject> { 757 // todo: 处理class的逻辑 758 let kobj = sys_dev_char_kset().as_kobject(); 759 return kobj; 760 } 761 762 /// 参考 https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/core.c?fi=device_links_force_bind#1226 763 pub fn device_links_force_bind(&self, _dev: &Arc<dyn Device>) { 764 todo!("device_links_force_bind") 765 } 766 767 /// 把device对象的一些结构进行默认初始化 768 /// 769 /// 参考 https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/core.c?fi=device_initialize#2976 770 pub fn device_default_initialize(&self, dev: &Arc<dyn Device>) { 771 dev.set_kset(Some(sys_devices_kset())); 772 dev.set_kobj_type(Some(&DeviceKObjType)); 773 return; 774 } 775 776 /// 参考 https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/dd.c?r=&mo=29885&fi=1100#1100 777 pub fn device_driver_attach( 778 &self, 779 _driver: &Arc<dyn Driver>, 780 _dev: &Arc<dyn Device>, 781 ) -> Result<(), SystemError> { 782 todo!("device_driver_attach") 783 } 784 785 /// 参考 https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/dd.c?r=&mo=35401&fi=1313#1313 786 pub fn device_driver_detach(&self, _dev: &Arc<dyn Device>) { 787 todo!("device_driver_detach") 788 } 789 } 790 791 /// @brief: 设备注册 792 /// @parameter: name: 设备名 793 /// @return: 操作成功,返回(),操作失败,返回错误码 794 pub fn device_register<T: Device>(device: Arc<T>) -> Result<(), SystemError> { 795 return device_manager().register(device); 796 } 797 798 /// @brief: 设备卸载 799 /// @parameter: name: 设备名 800 /// @return: 操作成功,返回(),操作失败,返回错误码 801 pub fn device_unregister<T: Device>(_device: Arc<T>) { 802 // DEVICE_MANAGER.add_device(device.id_table(), device.clone()); 803 // match sys_device_unregister(&device.id_table().name()) { 804 // Ok(_) => { 805 // device.set_inode(None); 806 // return Ok(()); 807 // } 808 // Err(_) => Err(DeviceError::RegisterError), 809 // } 810 todo!("device_unregister") 811 } 812 813 /// 设备文件夹下的`dev`文件的属性 814 #[derive(Debug, Clone, Copy)] 815 pub struct DeviceAttrDev; 816 817 impl Attribute for DeviceAttrDev { 818 fn mode(&self) -> ModeType { 819 // 0o444 820 return ModeType::S_IRUGO; 821 } 822 823 fn name(&self) -> &str { 824 "dev" 825 } 826 827 fn show(&self, kobj: Arc<dyn KObject>, buf: &mut [u8]) -> Result<usize, SystemError> { 828 let dev = kobj.cast::<dyn Device>().map_err(|kobj| { 829 kerror!( 830 "Intertrait casting not implemented for kobj: {}", 831 kobj.name() 832 ); 833 SystemError::EOPNOTSUPP_OR_ENOTSUP 834 })?; 835 836 let device_number = dev.id_table().device_number(); 837 let s = format!( 838 "{}:{}\n", 839 device_number.major().data(), 840 device_number.minor() 841 ); 842 843 return sysfs_emit_str(buf, &s); 844 } 845 846 fn support(&self) -> SysFSOpsSupport { 847 SysFSOpsSupport::SHOW 848 } 849 } 850 851 /// 设备匹配器 852 /// 853 /// 用于匹配设备是否符合某个条件 854 /// 855 /// ## 参数 856 /// 857 /// - `T` - 匹配器的数据类型 858 /// - `data` - 匹配器的数据 859 pub trait DeviceMatcher<T>: Debug { 860 fn match_device(&self, device: &Arc<dyn Device>, data: T) -> bool; 861 } 862 863 /// 用于根据名称匹配设备的匹配器 864 #[derive(Debug)] 865 pub struct DeviceMatchName; 866 867 impl DeviceMatcher<&str> for DeviceMatchName { 868 #[inline] 869 fn match_device(&self, device: &Arc<dyn Device>, data: &str) -> bool { 870 return device.name() == data; 871 } 872 } 873