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