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