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