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