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