xref: /DragonOS/kernel/src/driver/base/device/mod.rs (revision 56cc4dbe27e132aac5c61b8bd4f4ec9a223b49ee)
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(super) 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 }
291 
292 /// @brief: 设备标识符类型
293 #[derive(Debug, Clone, Hash, PartialOrd, PartialEq, Ord, Eq)]
294 pub struct IdTable {
295     basename: String,
296     id: Option<DeviceNumber>,
297 }
298 
299 /// @brief: 设备标识符操作方法集
300 impl IdTable {
301     /// @brief: 创建一个新的设备标识符
302     /// @parameter name: 设备名
303     /// @parameter id: 设备id
304     /// @return: 设备标识符
305     pub fn new(basename: String, id: Option<DeviceNumber>) -> IdTable {
306         return IdTable { basename, id };
307     }
308 
309     /// @brief: 将设备标识符转换成name
310     /// @parameter None
311     /// @return: 设备名
312     pub fn name(&self) -> String {
313         if self.id.is_none() {
314             return self.basename.clone();
315         } else {
316             let id = self.id.unwrap();
317             return format!("{}:{}", id.major().data(), id.minor());
318         }
319     }
320 
321     pub fn device_number(&self) -> DeviceNumber {
322         return self.id.unwrap_or_default();
323     }
324 }
325 
326 impl Default for IdTable {
327     fn default() -> Self {
328         IdTable::new("unknown".to_string(), None)
329     }
330 }
331 
332 // 以现在的模型,设备在加载到系统中就是已经初始化的状态了,因此可以考虑把这个删掉
333 /// @brief: 设备当前状态
334 #[derive(Debug, Clone, Copy, Eq, PartialEq)]
335 pub enum DeviceState {
336     NotInitialized = 0,
337     Initialized = 1,
338     UnDefined = 2,
339 }
340 
341 /// @brief: 设备错误类型
342 #[allow(dead_code)]
343 #[derive(Debug, Copy, Clone)]
344 pub enum DeviceError {
345     DriverExists,         // 设备已存在
346     DeviceExists,         // 驱动已存在
347     InitializeFailed,     // 初始化错误
348     NotInitialized,       // 未初始化的设备
349     NoDeviceForDriver,    // 没有合适的设备匹配驱动
350     NoDriverForDevice,    // 没有合适的驱动匹配设备
351     RegisterError,        // 注册失败
352     UnsupportedOperation, // 不支持的操作
353 }
354 
355 impl From<DeviceError> for SystemError {
356     fn from(value: DeviceError) -> Self {
357         match value {
358             DeviceError::DriverExists => SystemError::EEXIST,
359             DeviceError::DeviceExists => SystemError::EEXIST,
360             DeviceError::InitializeFailed => SystemError::EIO,
361             DeviceError::NotInitialized => SystemError::ENODEV,
362             DeviceError::NoDeviceForDriver => SystemError::ENODEV,
363             DeviceError::NoDriverForDevice => SystemError::ENODEV,
364             DeviceError::RegisterError => SystemError::EIO,
365             DeviceError::UnsupportedOperation => SystemError::EIO,
366         }
367     }
368 }
369 
370 /// @brief: 将u32类型转换为设备状态类型
371 impl From<u32> for DeviceState {
372     fn from(state: u32) -> Self {
373         match state {
374             0 => DeviceState::NotInitialized,
375             1 => DeviceState::Initialized,
376             _ => todo!(),
377         }
378     }
379 }
380 
381 /// @brief: 将设备状态转换为u32类型
382 impl From<DeviceState> for u32 {
383     fn from(state: DeviceState) -> Self {
384         match state {
385             DeviceState::NotInitialized => 0,
386             DeviceState::Initialized => 1,
387             DeviceState::UnDefined => 2,
388         }
389     }
390 }
391 
392 #[derive(Debug)]
393 pub struct DeviceKObjType;
394 
395 impl KObjType for DeviceKObjType {
396     // https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/core.c#2307
397     fn release(&self, kobj: Arc<dyn KObject>) {
398         let dev = kobj.cast::<dyn Device>().unwrap();
399         /*
400          * Some platform devices are driven without driver attached
401          * and managed resources may have been acquired.  Make sure
402          * all resources are released.
403          *
404          * Drivers still can add resources into device after device
405          * is deleted but alive, so release devres here to avoid
406          * possible memory leak.
407          */
408 
409         // todo: 在引入devres之后再实现
410         // devres_release_all(kobj);
411         dev.release();
412     }
413 
414     fn attribute_groups(&self) -> Option<&'static [&'static dyn AttributeGroup]> {
415         None
416     }
417 
418     fn sysfs_ops(&self) -> Option<&dyn SysFSOps> {
419         Some(&DeviceSysFSOps)
420     }
421 }
422 
423 #[derive(Debug)]
424 pub(super) struct DeviceSysFSOps;
425 
426 impl SysFSOps for DeviceSysFSOps {
427     fn store(
428         &self,
429         kobj: Arc<dyn KObject>,
430         attr: &dyn Attribute,
431         buf: &[u8],
432     ) -> Result<usize, SystemError> {
433         return attr.store(kobj, buf);
434     }
435 
436     fn show(
437         &self,
438         kobj: Arc<dyn KObject>,
439         attr: &dyn Attribute,
440         buf: &mut [u8],
441     ) -> Result<usize, SystemError> {
442         return attr.show(kobj, buf);
443     }
444 }
445 
446 /// @brief Device管理器
447 #[derive(Debug)]
448 pub struct DeviceManager;
449 
450 impl DeviceManager {
451     /// @brief: 创建一个新的设备管理器
452     /// @parameter: None
453     /// @return: DeviceManager实体
454     #[inline]
455     const fn new() -> DeviceManager {
456         return Self;
457     }
458 
459     pub fn register(&self, device: Arc<dyn Device>) -> Result<(), SystemError> {
460         self.device_default_initialize(&device);
461         return self.add_device(device);
462     }
463 
464     /// @brief: 添加设备
465     /// @parameter id_table: 总线标识符,用于唯一标识该总线
466     /// @parameter dev: 设备实例
467     /// @return: None
468     ///
469     /// https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/core.c#3398
470     ///
471     /// todo: 完善错误处理逻辑:如果添加失败,需要将之前添加的内容全部回滚
472     #[inline(never)]
473     #[allow(dead_code)]
474     pub fn add_device(&self, device: Arc<dyn Device>) -> Result<(), SystemError> {
475         // 在这里处理与parent相关的逻辑
476 
477         let current_parent = device
478             .parent()
479             .and_then(|x| x.upgrade())
480             .and_then(|x| x.arc_any().cast::<dyn Device>().ok());
481 
482         let actual_parent = self.get_device_parent(&device, current_parent)?;
483         if let Some(actual_parent) = actual_parent {
484             // kdebug!(
485             //     "device '{}' parent is '{}', strong_count: {}",
486             //     device.name().to_string(),
487             //     actual_parent.name(),
488             //     Arc::strong_count(&actual_parent)
489             // );
490             device.set_parent(Some(Arc::downgrade(&actual_parent)));
491         }
492 
493         KObjectManager::add_kobj(device.clone() as Arc<dyn KObject>, None).map_err(|e| {
494             kerror!("add device '{:?}' failed: {:?}", device.name(), e);
495             e
496         })?;
497 
498         self.device_platform_notify(&device);
499 
500         self.add_class_symlinks(&device)?;
501 
502         self.add_attrs(&device)?;
503 
504         bus_add_device(&device)?;
505 
506         if device.id_table().device_number().major() != Major::UNNAMED_MAJOR {
507             self.create_file(&device, &DeviceAttrDev)?;
508 
509             self.create_sys_dev_entry(&device)?;
510         }
511 
512         // 通知客户端有关设备添加的信息。此调用必须在 dpm_sysfs_add() 之后且在 kobject_uevent() 之前执行。
513         if let Some(bus) = device.bus().and_then(|bus| bus.upgrade()) {
514             bus.subsystem().bus_notifier().call_chain(
515                 bus::BusNotifyEvent::AddDevice,
516                 Some(&device),
517                 None,
518             );
519         }
520 
521         // todo: 发送uevent: KOBJ_ADD
522 
523         // probe drivers for a new device
524         bus_probe_device(&device);
525 
526         if let Some(class) = device.class() {
527             class.subsystem().add_device_to_vec(&device)?;
528 
529             for class_interface in class.subsystem().interfaces() {
530                 class_interface.add_device(&device).ok();
531             }
532         }
533 
534         return Ok(());
535     }
536 
537     /// 获取设备真实的parent kobject
538     ///
539     /// ## 参数
540     ///
541     /// - `device`: 设备
542     /// - `current_parent`: 当前的parent kobject
543     ///
544     /// ## 返回值
545     ///
546     /// - `Ok(Some(kobj))`: 如果找到了真实的parent kobject,那么返回它
547     /// - `Ok(None)`: 如果没有找到真实的parent kobject,那么返回None
548     /// - `Err(e)`: 如果发生错误,那么返回错误
549     fn get_device_parent(
550         &self,
551         device: &Arc<dyn Device>,
552         current_parent: Option<Arc<dyn Device>>,
553     ) -> Result<Option<Arc<dyn KObject>>, SystemError> {
554         // kdebug!("get_device_parent() device:{:?}", device.name());
555         if device.class().is_some() {
556             let parent_kobj: Arc<dyn KObject>;
557             // kdebug!("current_parent:{:?}", current_parent);
558             if let Some(cp) = current_parent {
559                 if cp.class().is_some() {
560                     return Ok(Some(cp.clone() as Arc<dyn KObject>));
561                 } else {
562                     parent_kobj = cp.clone() as Arc<dyn KObject>;
563                 }
564             } else {
565                 parent_kobj = sys_devices_virtual_kset() as Arc<dyn KObject>;
566             }
567 
568             // 是否需要glue dir?
569 
570             return Ok(Some(parent_kobj));
571         }
572 
573         // subsystems can specify a default root directory for their devices
574         if current_parent.is_none() {
575             if let Some(bus) = device.bus().and_then(|bus| bus.upgrade()) {
576                 if let Some(root) = bus.root_device().and_then(|x| x.upgrade()) {
577                     return Ok(Some(root as Arc<dyn KObject>));
578                 }
579             }
580         }
581 
582         if let Some(current_parent) = current_parent {
583             return Ok(Some(current_parent as Arc<dyn KObject>));
584         }
585 
586         return Ok(None);
587     }
588 
589     /// @brief: 卸载设备
590     /// @parameter id_table: 总线标识符,用于唯一标识该设备
591     /// @return: None
592     ///
593     /// ## 注意
594     /// 该函数已废弃,不再使用
595     #[inline]
596     #[allow(dead_code)]
597     pub fn remove_device(&self, _id_table: &IdTable) {
598         todo!()
599     }
600 
601     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c?fi=driver_attach#542
602     pub fn remove(&self, _dev: &Arc<dyn Device>) {
603         todo!("DeviceManager::remove")
604     }
605 
606     /// @brief: 获取设备
607     /// @parameter id_table: 设备标识符,用于唯一标识该设备
608     /// @return: 设备实例
609     #[inline]
610     #[allow(dead_code)]
611     pub fn find_device_by_idtable(&self, _id_table: &IdTable) -> Option<Arc<dyn Device>> {
612         todo!("find_device_by_idtable")
613     }
614 
615     fn device_platform_notify(&self, dev: &Arc<dyn Device>) {
616         acpi_device_notify(dev);
617         software_node_notify(dev);
618     }
619 
620     // 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/core.c#3224
621     fn add_class_symlinks(&self, dev: &Arc<dyn Device>) -> Result<(), SystemError> {
622         let class = dev.class();
623         if class.is_none() {
624             return Ok(());
625         }
626 
627         // 定义错误处理函数,用于在添加符号链接失败时,移除已经添加的符号链接
628 
629         let err_remove_device = |dev_kobj: &Arc<dyn KObject>| {
630             sysfs_instance().remove_link(dev_kobj, "device".to_string());
631         };
632 
633         let err_remove_subsystem = |dev_kobj: &Arc<dyn KObject>| {
634             sysfs_instance().remove_link(dev_kobj, "subsystem".to_string());
635         };
636 
637         let class = class.unwrap();
638         let dev_kobj = dev.clone() as Arc<dyn KObject>;
639         let subsys_kobj = class.subsystem().subsys() as Arc<dyn KObject>;
640         sysfs_instance().create_link(Some(&dev_kobj), &subsys_kobj, "subsystem".to_string())?;
641 
642         // todo: 这里需要处理class的parent逻辑, 添加device链接
643         if let Some(parent) = dev.parent().and_then(|x| x.upgrade()) {
644             let parent_kobj = parent.clone() as Arc<dyn KObject>;
645             sysfs_instance()
646                 .create_link(Some(&dev_kobj), &parent_kobj, "device".to_string())
647                 .map_err(|e| {
648                     err_remove_subsystem(&dev_kobj);
649                     e
650                 })?;
651         }
652 
653         sysfs_instance()
654             .create_link(Some(&subsys_kobj), &dev_kobj, dev.name())
655             .map_err(|e| {
656                 err_remove_device(&dev_kobj);
657                 err_remove_subsystem(&dev_kobj);
658                 e
659             })?;
660 
661         return Ok(());
662     }
663 
664     /// 在sysfs中,为指定的设备创建属性文件
665     ///
666     /// ## 参数
667     ///
668     /// - `dev`: 设备
669     fn add_attrs(&self, dev: &Arc<dyn Device>) -> Result<(), SystemError> {
670         // 定义错误处理函数,用于在添加属性文件失败时,移除已经添加的属性组
671         let err_remove_class_groups = |dev: &Arc<dyn Device>| {
672             if let Some(class) = dev.class() {
673                 let attr_groups = class.dev_groups();
674                 self.remove_groups(dev, attr_groups);
675             }
676         };
677 
678         let err_remove_kobj_type_groups = |dev: &Arc<dyn Device>| {
679             if let Some(kobj_type) = dev.kobj_type() {
680                 let attr_groups = kobj_type.attribute_groups().unwrap_or(&[]);
681                 self.remove_groups(dev, attr_groups);
682             }
683         };
684 
685         // 真正开始添加属性文件
686 
687         // 添加设备类的属性文件
688         if let Some(class) = dev.class() {
689             let attr_groups = class.dev_groups();
690             self.add_groups(dev, attr_groups)?;
691         }
692 
693         // 添加kobj_type的属性文件
694         if let Some(kobj_type) = dev.kobj_type() {
695             self.add_groups(dev, kobj_type.attribute_groups().unwrap_or(&[]))
696                 .map_err(|e| {
697                     err_remove_class_groups(dev);
698                     e
699                 })?;
700         }
701 
702         // 添加设备本身的属性文件
703         self.add_groups(dev, dev.attribute_groups().unwrap_or(&[]))
704             .map_err(|e| {
705                 err_remove_kobj_type_groups(dev);
706                 err_remove_class_groups(dev);
707                 e
708             })?;
709 
710         return Ok(());
711     }
712 
713     /// 在sysfs中,为指定的设备创建属性组,以及属性组中的属性文件
714     ///
715     /// ## 参数
716     ///
717     /// - `dev`: 设备
718     /// - `attr_groups`: 属性组
719     pub fn add_groups(
720         &self,
721         dev: &Arc<dyn Device>,
722         attr_groups: &'static [&dyn AttributeGroup],
723     ) -> Result<(), SystemError> {
724         let kobj = dev.clone() as Arc<dyn KObject>;
725         return sysfs_instance().create_groups(&kobj, attr_groups);
726     }
727 
728     /// 在sysfs中,为指定的设备移除属性组,以及属性组中的属性文件
729     ///
730     /// ## 参数
731     ///
732     /// - `dev`: 设备
733     /// - `attr_groups`: 要移除的属性组
734     pub fn remove_groups(
735         &self,
736         dev: &Arc<dyn Device>,
737         attr_groups: &'static [&dyn AttributeGroup],
738     ) {
739         let kobj = dev.clone() as Arc<dyn KObject>;
740         sysfs_instance().remove_groups(&kobj, attr_groups);
741     }
742 
743     /// 为设备在sysfs中创建属性文件
744     ///
745     /// ## 参数
746     ///
747     /// - `dev`: 设备
748     /// - `attr`: 属性
749     pub fn create_file(
750         &self,
751         dev: &Arc<dyn Device>,
752         attr: &'static dyn Attribute,
753     ) -> Result<(), SystemError> {
754         if unlikely(
755             attr.mode().contains(ModeType::S_IRUGO)
756                 && (!attr.support().contains(SysFSOpsSupport::ATTR_SHOW)),
757         ) {
758             kwarn!(
759                 "Attribute '{}': read permission without 'show'",
760                 attr.name()
761             );
762         }
763         if unlikely(
764             attr.mode().contains(ModeType::S_IWUGO)
765                 && (!attr.support().contains(SysFSOpsSupport::ATTR_STORE)),
766         ) {
767             kwarn!(
768                 "Attribute '{}': write permission without 'store'",
769                 attr.name()
770             );
771         }
772 
773         let kobj = dev.clone() as Arc<dyn KObject>;
774 
775         return sysfs_instance().create_file(&kobj, attr);
776     }
777 
778     /// 在/sys/dev下,或者设备所属的class下,为指定的设备创建链接
779     fn create_sys_dev_entry(&self, dev: &Arc<dyn Device>) -> Result<(), SystemError> {
780         let target_kobj = self.device_to_dev_kobj(dev);
781         let name = dev.id_table().name();
782         let current_kobj = dev.clone() as Arc<dyn KObject>;
783         return sysfs_instance().create_link(Some(&target_kobj), &current_kobj, name);
784     }
785 
786     /// Delete symlink for device in `/sys/dev` or `/sys/class/<class_name>`
787     #[allow(dead_code)]
788     fn remove_sys_dev_entry(&self, dev: &Arc<dyn Device>) {
789         let kobj = self.device_to_dev_kobj(dev);
790         let name = dev.id_table().name();
791         sysfs_instance().remove_link(&kobj, name);
792     }
793 
794     /// device_to_dev_kobj - select a /sys/dev/ directory for the device
795     ///
796     /// By default we select char/ for new entries.
797     ///
798     /// ## 参数
799     ///
800     /// - `dev`: 设备
801     fn device_to_dev_kobj(&self, _dev: &Arc<dyn Device>) -> Arc<dyn KObject> {
802         // todo: 处理class的逻辑
803         let kobj = sys_dev_char_kset().as_kobject();
804         return kobj;
805     }
806 
807     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/core.c?fi=device_links_force_bind#1226
808     pub fn device_links_force_bind(&self, _dev: &Arc<dyn Device>) {
809         todo!("device_links_force_bind")
810     }
811 
812     /// 把device对象的一些结构进行默认初始化
813     ///
814     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/core.c?fi=device_initialize#2976
815     pub fn device_default_initialize(&self, dev: &Arc<dyn Device>) {
816         dev.set_kset(Some(sys_devices_kset()));
817         dev.set_kobj_type(Some(&DeviceKObjType));
818         return;
819     }
820 
821     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c?r=&mo=29885&fi=1100#1100
822     pub fn device_driver_attach(
823         &self,
824         _driver: &Arc<dyn Driver>,
825         _dev: &Arc<dyn Device>,
826     ) -> Result<(), SystemError> {
827         todo!("device_driver_attach")
828     }
829 
830     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c?r=&mo=35401&fi=1313#1313
831     pub fn device_driver_detach(&self, _dev: &Arc<dyn Device>) {
832         todo!("device_driver_detach")
833     }
834 }
835 
836 /// @brief: 设备注册
837 /// @parameter: name: 设备名
838 /// @return: 操作成功,返回(),操作失败,返回错误码
839 pub fn device_register<T: Device>(device: Arc<T>) -> Result<(), SystemError> {
840     return device_manager().register(device);
841 }
842 
843 /// @brief: 设备卸载
844 /// @parameter: name: 设备名
845 /// @return: 操作成功,返回(),操作失败,返回错误码
846 pub fn device_unregister<T: Device>(_device: Arc<T>) {
847     // DEVICE_MANAGER.add_device(device.id_table(), device.clone());
848     // match sys_device_unregister(&device.id_table().name()) {
849     //     Ok(_) => {
850     //         device.set_inode(None);
851     //         return Ok(());
852     //     }
853     //     Err(_) => Err(DeviceError::RegisterError),
854     // }
855     todo!("device_unregister")
856 }
857 
858 /// 设备文件夹下的`dev`文件的属性
859 #[derive(Debug, Clone, Copy)]
860 pub struct DeviceAttrDev;
861 
862 impl Attribute for DeviceAttrDev {
863     fn mode(&self) -> ModeType {
864         // 0o444
865         return ModeType::S_IRUGO;
866     }
867 
868     fn name(&self) -> &str {
869         "dev"
870     }
871 
872     fn show(&self, kobj: Arc<dyn KObject>, buf: &mut [u8]) -> Result<usize, SystemError> {
873         let dev = kobj.cast::<dyn Device>().map_err(|kobj| {
874             kerror!(
875                 "Intertrait casting not implemented for kobj: {}",
876                 kobj.name()
877             );
878             SystemError::EOPNOTSUPP_OR_ENOTSUP
879         })?;
880 
881         let device_number = dev.id_table().device_number();
882         let s = format!(
883             "{}:{}\n",
884             device_number.major().data(),
885             device_number.minor()
886         );
887 
888         return sysfs_emit_str(buf, &s);
889     }
890 
891     fn support(&self) -> SysFSOpsSupport {
892         SysFSOpsSupport::ATTR_SHOW
893     }
894 }
895 
896 /// 设备匹配器
897 ///
898 /// 用于匹配设备是否符合某个条件
899 ///
900 /// ## 参数
901 ///
902 /// - `T` - 匹配器的数据类型
903 /// - `data` - 匹配器的数据
904 pub trait DeviceMatcher<T>: Debug {
905     fn match_device(&self, device: &Arc<dyn Device>, data: T) -> bool;
906 }
907 
908 /// 用于根据名称匹配设备的匹配器
909 #[derive(Debug)]
910 pub struct DeviceMatchName;
911 
912 impl DeviceMatcher<&str> for DeviceMatchName {
913     #[inline]
914     fn match_device(&self, device: &Arc<dyn Device>, data: &str) -> bool {
915         return device.name() == data;
916     }
917 }
918 
919 /// Cookie to identify the device
920 #[derive(Debug, Clone)]
921 pub struct DeviceId {
922     data: Option<&'static str>,
923     allocated: Option<String>,
924 }
925 
926 impl DeviceId {
927     #[allow(dead_code)]
928     pub fn new(data: Option<&'static str>, allocated: Option<String>) -> Option<Arc<Self>> {
929         if data.is_none() && allocated.is_none() {
930             return None;
931         }
932 
933         // 如果data和allocated都有值,那么返回None
934         if data.is_some() && allocated.is_some() {
935             return None;
936         }
937 
938         return Some(Arc::new(Self { data, allocated }));
939     }
940 
941     pub fn id(&self) -> Option<&str> {
942         if self.data.is_some() {
943             return Some(self.data.unwrap());
944         } else {
945             return self.allocated.as_deref();
946         }
947     }
948 
949     #[allow(dead_code)]
950     pub fn set_allocated(&mut self, allocated: String) {
951         self.allocated = Some(allocated);
952         self.data = None;
953     }
954 }
955 
956 impl PartialEq for DeviceId {
957     fn eq(&self, other: &Self) -> bool {
958         return self.id() == other.id();
959     }
960 }
961 
962 impl core::hash::Hash for DeviceId {
963     fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
964         self.id().hash(state);
965     }
966 }
967 
968 impl Eq for DeviceId {}
969 
970 impl IrqHandlerData for DeviceId {}
971