xref: /DragonOS/kernel/src/driver/base/device/mod.rs (revision c3dc6f2ff9169c309d1cbf47dcb9e4528d509b2f)
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 pub(self) unsafe fn set_sys_dev_block_kset(kset: Arc<KSet>) {
102     DEV_BLOCK_KSET_INSTANCE = Some(kset);
103 }
104 
105 pub(self) 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 pub(self) 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(DeviceNumber::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 Into<SystemError> for DeviceError {
311     fn into(self) -> SystemError {
312         match self {
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             .map(|x| x.upgrade())
435             .flatten()
436             .map(|x| x.arc_any().cast::<dyn Device>().ok())
437             .flatten();
438 
439         let actual_parent = self.get_device_parent(&device, current_parent)?;
440         if let Some(actual_parent) = actual_parent {
441             // kdebug!(
442             //     "device '{}' parent is '{}', strong_count: {}",
443             //     device.name().to_string(),
444             //     actual_parent.name(),
445             //     Arc::strong_count(&actual_parent)
446             // );
447             device.set_parent(Some(Arc::downgrade(&actual_parent)));
448         }
449 
450         KObjectManager::add_kobj(device.clone() as Arc<dyn KObject>, None).map_err(|e| {
451             kerror!("add device '{:?}' failed: {:?}", device.name(), e);
452             e
453         })?;
454 
455         self.device_platform_notify(&device);
456 
457         self.add_class_symlinks(&device)?;
458 
459         self.add_attrs(&device)?;
460 
461         bus_add_device(&device)?;
462 
463         if device.id_table().device_number().major() != Major::UNNAMED_MAJOR {
464             self.create_file(&device, &DeviceAttrDev)?;
465 
466             self.create_sys_dev_entry(&device)?;
467         }
468 
469         // 通知客户端有关设备添加的信息。此调用必须在 dpm_sysfs_add() 之后且在 kobject_uevent() 之前执行。
470         if let Some(bus) = device.bus().map(|bus| bus.upgrade()).flatten() {
471             bus.subsystem().bus_notifier().call_chain(
472                 bus::BusNotifyEvent::AddDevice,
473                 Some(&device),
474                 None,
475             );
476         }
477 
478         // todo: 发送uevent: KOBJ_ADD
479 
480         // probe drivers for a new device
481         bus_probe_device(&device);
482 
483         if let Some(class) = device.class() {
484             class.subsystem().add_device_to_vec(&device)?;
485 
486             for class_interface in class.subsystem().interfaces() {
487                 class_interface.add_device(&device).ok();
488             }
489         }
490 
491         return Ok(());
492     }
493 
494     /// 获取设备真实的parent kobject
495     ///
496     /// ## 参数
497     ///
498     /// - `device`: 设备
499     /// - `current_parent`: 当前的parent kobject
500     ///
501     /// ## 返回值
502     ///
503     /// - `Ok(Some(kobj))`: 如果找到了真实的parent kobject,那么返回它
504     /// - `Ok(None)`: 如果没有找到真实的parent kobject,那么返回None
505     /// - `Err(e)`: 如果发生错误,那么返回错误
506     fn get_device_parent(
507         &self,
508         device: &Arc<dyn Device>,
509         current_parent: Option<Arc<dyn Device>>,
510     ) -> Result<Option<Arc<dyn KObject>>, SystemError> {
511         // kdebug!("get_device_parent() device:{:?}", device.name());
512         if let Some(_) = device.class() {
513             let parent_kobj: Arc<dyn KObject>;
514             // kdebug!("current_parent:{:?}", current_parent);
515             if current_parent.is_none() {
516                 parent_kobj = sys_devices_virtual_kset() as Arc<dyn KObject>;
517             } else {
518                 let cp = current_parent.unwrap();
519 
520                 if cp.class().is_some() {
521                     return Ok(Some(cp.clone() as Arc<dyn KObject>));
522                 } else {
523                     parent_kobj = cp.clone() as Arc<dyn KObject>;
524                 }
525             }
526 
527             // 是否需要glue dir?
528 
529             return Ok(Some(parent_kobj));
530         }
531 
532         // subsystems can specify a default root directory for their devices
533         if current_parent.is_none() {
534             if let Some(bus) = device.bus().map(|bus| bus.upgrade()).flatten() {
535                 if let Some(root) = bus.root_device().map(|x| x.upgrade()).flatten() {
536                     return Ok(Some(root as Arc<dyn KObject>));
537                 }
538             }
539         }
540 
541         if current_parent.is_some() {
542             return Ok(Some(current_parent.unwrap().clone() as Arc<dyn KObject>));
543         }
544 
545         return Ok(None);
546     }
547 
548     /// @brief: 卸载设备
549     /// @parameter id_table: 总线标识符,用于唯一标识该设备
550     /// @return: None
551     ///
552     /// ## 注意
553     /// 该函数已废弃,不再使用
554     #[inline]
555     #[allow(dead_code)]
556     pub fn remove_device(&self, _id_table: &IdTable) {
557         todo!()
558     }
559 
560     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c?fi=driver_attach#542
561     pub fn remove(&self, _dev: &Arc<dyn Device>) {
562         todo!("DeviceManager::remove")
563     }
564 
565     /// @brief: 获取设备
566     /// @parameter id_table: 设备标识符,用于唯一标识该设备
567     /// @return: 设备实例
568     #[inline]
569     #[allow(dead_code)]
570     pub fn find_device_by_idtable(&self, _id_table: &IdTable) -> Option<Arc<dyn Device>> {
571         todo!("find_device_by_idtable")
572     }
573 
574     fn device_platform_notify(&self, dev: &Arc<dyn Device>) {
575         acpi_device_notify(dev);
576         software_node_notify(dev);
577     }
578 
579     // 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/core.c#3224
580     fn add_class_symlinks(&self, dev: &Arc<dyn Device>) -> Result<(), SystemError> {
581         let class = dev.class();
582         if class.is_none() {
583             return Ok(());
584         }
585 
586         // 定义错误处理函数,用于在添加符号链接失败时,移除已经添加的符号链接
587 
588         let err_remove_device = |dev_kobj: &Arc<dyn KObject>| {
589             sysfs_instance().remove_link(dev_kobj, "device".to_string());
590         };
591 
592         let err_remove_subsystem = |dev_kobj: &Arc<dyn KObject>| {
593             sysfs_instance().remove_link(dev_kobj, "subsystem".to_string());
594         };
595 
596         let class = class.unwrap();
597         let dev_kobj = dev.clone() as Arc<dyn KObject>;
598         let subsys_kobj = class.subsystem().subsys() as Arc<dyn KObject>;
599         sysfs_instance().create_link(Some(&dev_kobj), &subsys_kobj, "subsystem".to_string())?;
600 
601         // todo: 这里需要处理class的parent逻辑, 添加device链接
602         if let Some(parent) = dev.parent().map(|x| x.upgrade()).flatten() {
603             let parent_kobj = parent.clone() as Arc<dyn KObject>;
604             sysfs_instance()
605                 .create_link(Some(&dev_kobj), &&parent_kobj, "device".to_string())
606                 .map_err(|e| {
607                     err_remove_subsystem(&dev_kobj);
608                     e
609                 })?;
610         }
611 
612         sysfs_instance()
613             .create_link(Some(&subsys_kobj), &dev_kobj, dev.name())
614             .map_err(|e| {
615                 err_remove_device(&dev_kobj);
616                 err_remove_subsystem(&dev_kobj);
617                 e
618             })?;
619 
620         return Ok(());
621     }
622 
623     /// 在sysfs中,为指定的设备创建属性文件
624     ///
625     /// ## 参数
626     ///
627     /// - `dev`: 设备
628     fn add_attrs(&self, dev: &Arc<dyn Device>) -> Result<(), SystemError> {
629         // 定义错误处理函数,用于在添加属性文件失败时,移除已经添加的属性组
630         let err_remove_class_groups = |dev: &Arc<dyn Device>| {
631             if let Some(class) = dev.class() {
632                 let attr_groups = class.dev_groups();
633                 self.remove_groups(dev, attr_groups);
634             }
635         };
636 
637         let err_remove_kobj_type_groups = |dev: &Arc<dyn Device>| {
638             if let Some(kobj_type) = dev.kobj_type() {
639                 let attr_groups = kobj_type.attribute_groups().unwrap_or(&[]);
640                 self.remove_groups(dev, attr_groups);
641             }
642         };
643 
644         // 真正开始添加属性文件
645 
646         // 添加设备类的属性文件
647         if let Some(class) = dev.class() {
648             let attr_groups = class.dev_groups();
649             self.add_groups(dev, attr_groups)?;
650         }
651 
652         // 添加kobj_type的属性文件
653         if let Some(kobj_type) = dev.kobj_type() {
654             self.add_groups(dev, kobj_type.attribute_groups().unwrap_or(&[]))
655                 .map_err(|e| {
656                     err_remove_class_groups(dev);
657                     e
658                 })?;
659         }
660 
661         // 添加设备本身的属性文件
662         self.add_groups(dev, dev.attribute_groups().unwrap_or(&[]))
663             .map_err(|e| {
664                 err_remove_kobj_type_groups(dev);
665                 err_remove_class_groups(dev);
666                 e
667             })?;
668 
669         return Ok(());
670     }
671 
672     /// 在sysfs中,为指定的设备创建属性组,以及属性组中的属性文件
673     ///
674     /// ## 参数
675     ///
676     /// - `dev`: 设备
677     /// - `attr_groups`: 属性组
678     pub fn add_groups(
679         &self,
680         dev: &Arc<dyn Device>,
681         attr_groups: &'static [&dyn AttributeGroup],
682     ) -> Result<(), SystemError> {
683         let kobj = dev.clone() as Arc<dyn KObject>;
684         return sysfs_instance().create_groups(&kobj, attr_groups);
685     }
686 
687     /// 在sysfs中,为指定的设备移除属性组,以及属性组中的属性文件
688     ///
689     /// ## 参数
690     ///
691     /// - `dev`: 设备
692     /// - `attr_groups`: 要移除的属性组
693     pub fn remove_groups(
694         &self,
695         dev: &Arc<dyn Device>,
696         attr_groups: &'static [&dyn AttributeGroup],
697     ) {
698         let kobj = dev.clone() as Arc<dyn KObject>;
699         sysfs_instance().remove_groups(&kobj, attr_groups);
700     }
701 
702     /// 为设备在sysfs中创建属性文件
703     ///
704     /// ## 参数
705     ///
706     /// - `dev`: 设备
707     /// - `attr`: 属性
708     pub fn create_file(
709         &self,
710         dev: &Arc<dyn Device>,
711         attr: &'static dyn Attribute,
712     ) -> Result<(), SystemError> {
713         if unlikely(
714             attr.mode().contains(ModeType::S_IRUGO)
715                 && (!attr.support().contains(SysFSOpsSupport::ATTR_SHOW)),
716         ) {
717             kwarn!(
718                 "Attribute '{}': read permission without 'show'",
719                 attr.name()
720             );
721         }
722         if unlikely(
723             attr.mode().contains(ModeType::S_IWUGO)
724                 && (!attr.support().contains(SysFSOpsSupport::ATTR_STORE)),
725         ) {
726             kwarn!(
727                 "Attribute '{}': write permission without 'store'",
728                 attr.name()
729             );
730         }
731 
732         let kobj = dev.clone() as Arc<dyn KObject>;
733 
734         return sysfs_instance().create_file(&kobj, attr);
735     }
736 
737     /// 在/sys/dev下,或者设备所属的class下,为指定的设备创建链接
738     fn create_sys_dev_entry(&self, dev: &Arc<dyn Device>) -> Result<(), SystemError> {
739         let target_kobj = self.device_to_dev_kobj(dev);
740         let name = dev.id_table().name();
741         let current_kobj = dev.clone() as Arc<dyn KObject>;
742         return sysfs_instance().create_link(Some(&target_kobj), &current_kobj, name);
743     }
744 
745     /// Delete symlink for device in `/sys/dev` or `/sys/class/<class_name>`
746     #[allow(dead_code)]
747     fn remove_sys_dev_entry(&self, dev: &Arc<dyn Device>) {
748         let kobj = self.device_to_dev_kobj(dev);
749         let name = dev.id_table().name();
750         sysfs_instance().remove_link(&kobj, name);
751     }
752 
753     /// device_to_dev_kobj - select a /sys/dev/ directory for the device
754     ///
755     /// By default we select char/ for new entries.
756     ///
757     /// ## 参数
758     ///
759     /// - `dev`: 设备
760     fn device_to_dev_kobj(&self, _dev: &Arc<dyn Device>) -> Arc<dyn KObject> {
761         // todo: 处理class的逻辑
762         let kobj = sys_dev_char_kset().as_kobject();
763         return kobj;
764     }
765 
766     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/core.c?fi=device_links_force_bind#1226
767     pub fn device_links_force_bind(&self, _dev: &Arc<dyn Device>) {
768         todo!("device_links_force_bind")
769     }
770 
771     /// 把device对象的一些结构进行默认初始化
772     ///
773     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/core.c?fi=device_initialize#2976
774     pub fn device_default_initialize(&self, dev: &Arc<dyn Device>) {
775         dev.set_kset(Some(sys_devices_kset()));
776         dev.set_kobj_type(Some(&DeviceKObjType));
777         return;
778     }
779 
780     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c?r=&mo=29885&fi=1100#1100
781     pub fn device_driver_attach(
782         &self,
783         _driver: &Arc<dyn Driver>,
784         _dev: &Arc<dyn Device>,
785     ) -> Result<(), SystemError> {
786         todo!("device_driver_attach")
787     }
788 
789     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c?r=&mo=35401&fi=1313#1313
790     pub fn device_driver_detach(&self, _dev: &Arc<dyn Device>) {
791         todo!("device_driver_detach")
792     }
793 }
794 
795 /// @brief: 设备注册
796 /// @parameter: name: 设备名
797 /// @return: 操作成功,返回(),操作失败,返回错误码
798 pub fn device_register<T: Device>(device: Arc<T>) -> Result<(), SystemError> {
799     return device_manager().register(device);
800 }
801 
802 /// @brief: 设备卸载
803 /// @parameter: name: 设备名
804 /// @return: 操作成功,返回(),操作失败,返回错误码
805 pub fn device_unregister<T: Device>(_device: Arc<T>) {
806     // DEVICE_MANAGER.add_device(device.id_table(), device.clone());
807     // match sys_device_unregister(&device.id_table().name()) {
808     //     Ok(_) => {
809     //         device.set_inode(None);
810     //         return Ok(());
811     //     }
812     //     Err(_) => Err(DeviceError::RegisterError),
813     // }
814     todo!("device_unregister")
815 }
816 
817 /// 设备文件夹下的`dev`文件的属性
818 #[derive(Debug, Clone, Copy)]
819 pub struct DeviceAttrDev;
820 
821 impl Attribute for DeviceAttrDev {
822     fn mode(&self) -> ModeType {
823         // 0o444
824         return ModeType::S_IRUGO;
825     }
826 
827     fn name(&self) -> &str {
828         "dev"
829     }
830 
831     fn show(&self, kobj: Arc<dyn KObject>, buf: &mut [u8]) -> Result<usize, SystemError> {
832         let dev = kobj.cast::<dyn Device>().map_err(|kobj| {
833             kerror!(
834                 "Intertrait casting not implemented for kobj: {}",
835                 kobj.name()
836             );
837             SystemError::EOPNOTSUPP_OR_ENOTSUP
838         })?;
839 
840         let device_number = dev.id_table().device_number();
841         let s = format!(
842             "{}:{}\n",
843             device_number.major().data(),
844             device_number.minor()
845         );
846 
847         return sysfs_emit_str(buf, &s);
848     }
849 
850     fn support(&self) -> SysFSOpsSupport {
851         SysFSOpsSupport::ATTR_SHOW
852     }
853 }
854 
855 /// 设备匹配器
856 ///
857 /// 用于匹配设备是否符合某个条件
858 ///
859 /// ## 参数
860 ///
861 /// - `T` - 匹配器的数据类型
862 /// - `data` - 匹配器的数据
863 pub trait DeviceMatcher<T>: Debug {
864     fn match_device(&self, device: &Arc<dyn Device>, data: T) -> bool;
865 }
866 
867 /// 用于根据名称匹配设备的匹配器
868 #[derive(Debug)]
869 pub struct DeviceMatchName;
870 
871 impl DeviceMatcher<&str> for DeviceMatchName {
872     #[inline]
873     fn match_device(&self, device: &Arc<dyn Device>, data: &str) -> bool {
874         return device.name() == data;
875     }
876 }
877 
878 /// Cookie to identify the device
879 #[derive(Debug, Clone, Hash)]
880 pub struct DeviceId {
881     data: Option<&'static str>,
882     allocated: Option<String>,
883 }
884 
885 impl DeviceId {
886     #[allow(dead_code)]
887     pub fn new(data: Option<&'static str>, allocated: Option<String>) -> Option<Arc<Self>> {
888         if data.is_none() && allocated.is_none() {
889             return None;
890         }
891 
892         // 如果data和allocated都有值,那么返回None
893         if data.is_some() && allocated.is_some() {
894             return None;
895         }
896 
897         return Some(Arc::new(Self { data, allocated }));
898     }
899 
900     pub fn id(&self) -> Option<&str> {
901         if self.data.is_some() {
902             return Some(self.data.unwrap());
903         } else {
904             return self.allocated.as_deref();
905         }
906     }
907 
908     #[allow(dead_code)]
909     pub fn set_allocated(&mut self, allocated: String) {
910         self.allocated = Some(allocated);
911         self.data = None;
912     }
913 }
914 
915 impl PartialEq for DeviceId {
916     fn eq(&self, other: &Self) -> bool {
917         return self.id() == other.id();
918     }
919 }
920 
921 impl Eq for DeviceId {}
922 
923 impl IrqHandlerData for DeviceId {}
924