xref: /DragonOS/kernel/src/driver/base/device/mod.rs (revision bd70d2d1f490aabd570a5301b858bd5eb04149fa)
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                 .inspect_err(|_e| {
650                     err_remove_subsystem(&dev_kobj);
651                 })?;
652         }
653 
654         sysfs_instance()
655             .create_link(Some(&subsys_kobj), &dev_kobj, dev.name())
656             .inspect_err(|_e| {
657                 err_remove_device(&dev_kobj);
658                 err_remove_subsystem(&dev_kobj);
659             })?;
660 
661         return Ok(());
662     }
663 
664     /// 在sysfs中,为指定的设备创建属性文件
665     ///
666     /// ## 参数
667     ///
668     /// - `dev`: 设备
669     fn add_attrs(&self, dev: &Arc<dyn Device>) -> Result<(), SystemError> {
670         // 定义错误处理函数,用于在添加属性文件失败时,移除已经添加的属性组
671         let err_remove_class_groups = |dev: &Arc<dyn Device>| {
672             if let Some(class) = dev.class() {
673                 let attr_groups = class.dev_groups();
674                 self.remove_groups(dev, attr_groups);
675             }
676         };
677 
678         let err_remove_kobj_type_groups = |dev: &Arc<dyn Device>| {
679             if let Some(kobj_type) = dev.kobj_type() {
680                 let attr_groups = kobj_type.attribute_groups().unwrap_or(&[]);
681                 self.remove_groups(dev, attr_groups);
682             }
683         };
684 
685         // 真正开始添加属性文件
686 
687         // 添加设备类的属性文件
688         if let Some(class) = dev.class() {
689             let attr_groups = class.dev_groups();
690             self.add_groups(dev, attr_groups)?;
691         }
692 
693         // 添加kobj_type的属性文件
694         if let Some(kobj_type) = dev.kobj_type() {
695             self.add_groups(dev, kobj_type.attribute_groups().unwrap_or(&[]))
696                 .inspect_err(|_e| {
697                     err_remove_class_groups(dev);
698                 })?;
699         }
700 
701         // 添加设备本身的属性文件
702         self.add_groups(dev, dev.attribute_groups().unwrap_or(&[]))
703             .inspect_err(|_e| {
704                 err_remove_kobj_type_groups(dev);
705                 err_remove_class_groups(dev);
706             })?;
707 
708         return Ok(());
709     }
710 
711     /// 在sysfs中,为指定的设备创建属性组,以及属性组中的属性文件
712     ///
713     /// ## 参数
714     ///
715     /// - `dev`: 设备
716     /// - `attr_groups`: 属性组
717     pub fn add_groups(
718         &self,
719         dev: &Arc<dyn Device>,
720         attr_groups: &'static [&dyn AttributeGroup],
721     ) -> Result<(), SystemError> {
722         let kobj = dev.clone() as Arc<dyn KObject>;
723         return sysfs_instance().create_groups(&kobj, attr_groups);
724     }
725 
726     /// 在sysfs中,为指定的设备移除属性组,以及属性组中的属性文件
727     ///
728     /// ## 参数
729     ///
730     /// - `dev`: 设备
731     /// - `attr_groups`: 要移除的属性组
732     pub fn remove_groups(
733         &self,
734         dev: &Arc<dyn Device>,
735         attr_groups: &'static [&dyn AttributeGroup],
736     ) {
737         let kobj = dev.clone() as Arc<dyn KObject>;
738         sysfs_instance().remove_groups(&kobj, attr_groups);
739     }
740 
741     /// 为设备在sysfs中创建属性文件
742     ///
743     /// ## 参数
744     ///
745     /// - `dev`: 设备
746     /// - `attr`: 属性
747     pub fn create_file(
748         &self,
749         dev: &Arc<dyn Device>,
750         attr: &'static dyn Attribute,
751     ) -> Result<(), SystemError> {
752         if unlikely(
753             attr.mode().contains(ModeType::S_IRUGO)
754                 && (!attr.support().contains(SysFSOpsSupport::ATTR_SHOW)),
755         ) {
756             warn!(
757                 "Attribute '{}': read permission without 'show'",
758                 attr.name()
759             );
760         }
761         if unlikely(
762             attr.mode().contains(ModeType::S_IWUGO)
763                 && (!attr.support().contains(SysFSOpsSupport::ATTR_STORE)),
764         ) {
765             warn!(
766                 "Attribute '{}': write permission without 'store'",
767                 attr.name()
768             );
769         }
770 
771         let kobj = dev.clone() as Arc<dyn KObject>;
772 
773         return sysfs_instance().create_file(&kobj, attr);
774     }
775 
776     /// 在/sys/dev下,或者设备所属的class下,为指定的设备创建链接
777     fn create_sys_dev_entry(&self, dev: &Arc<dyn Device>) -> Result<(), SystemError> {
778         let target_kobj = self.device_to_dev_kobj(dev);
779         let name = dev.id_table().name();
780         let current_kobj = dev.clone() as Arc<dyn KObject>;
781         return sysfs_instance().create_link(Some(&target_kobj), &current_kobj, name);
782     }
783 
784     /// Delete symlink for device in `/sys/dev` or `/sys/class/<class_name>`
785     #[allow(dead_code)]
786     fn remove_sys_dev_entry(&self, dev: &Arc<dyn Device>) {
787         let kobj = self.device_to_dev_kobj(dev);
788         let name = dev.id_table().name();
789         sysfs_instance().remove_link(&kobj, name);
790     }
791 
792     /// device_to_dev_kobj - select a /sys/dev/ directory for the device
793     ///
794     /// By default we select char/ for new entries.
795     ///
796     /// ## 参数
797     ///
798     /// - `dev`: 设备
799     fn device_to_dev_kobj(&self, _dev: &Arc<dyn Device>) -> Arc<dyn KObject> {
800         // todo: 处理class的逻辑
801         let kobj = sys_dev_char_kset().as_kobject();
802         return kobj;
803     }
804 
805     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/core.c?fi=device_links_force_bind#1226
806     pub fn device_links_force_bind(&self, _dev: &Arc<dyn Device>) {
807         warn!("device_links_force_bind not implemented");
808     }
809 
810     /// 把device对象的一些结构进行默认初始化
811     ///
812     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/core.c?fi=device_initialize#2976
813     pub fn device_default_initialize(&self, dev: &Arc<dyn Device>) {
814         dev.set_kset(Some(sys_devices_kset()));
815         dev.set_kobj_type(Some(&DeviceKObjType));
816         return;
817     }
818 
819     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c?r=&mo=29885&fi=1100#1100
820     pub fn device_driver_attach(
821         &self,
822         _driver: &Arc<dyn Driver>,
823         _dev: &Arc<dyn Device>,
824     ) -> Result<(), SystemError> {
825         todo!("device_driver_attach")
826     }
827 
828     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c?r=&mo=35401&fi=1313#1313
829     pub fn device_driver_detach(&self, _dev: &Arc<dyn Device>) {
830         todo!("device_driver_detach")
831     }
832 }
833 
834 /// @brief: 设备注册
835 /// @parameter: name: 设备名
836 /// @return: 操作成功,返回(),操作失败,返回错误码
837 pub fn device_register<T: Device>(device: Arc<T>) -> Result<(), SystemError> {
838     return device_manager().register(device);
839 }
840 
841 /// @brief: 设备卸载
842 /// @parameter: name: 设备名
843 /// @return: 操作成功,返回(),操作失败,返回错误码
844 pub fn device_unregister<T: Device>(_device: Arc<T>) {
845     // DEVICE_MANAGER.add_device(device.id_table(), device.clone());
846     // match sys_device_unregister(&device.id_table().name()) {
847     //     Ok(_) => {
848     //         device.set_inode(None);
849     //         return Ok(());
850     //     }
851     //     Err(_) => Err(DeviceError::RegisterError),
852     // }
853     todo!("device_unregister")
854 }
855 
856 /// 设备文件夹下的`dev`文件的属性
857 #[derive(Debug, Clone, Copy)]
858 pub struct DeviceAttrDev;
859 
860 impl Attribute for DeviceAttrDev {
861     fn mode(&self) -> ModeType {
862         // 0o444
863         return ModeType::S_IRUGO;
864     }
865 
866     fn name(&self) -> &str {
867         "dev"
868     }
869 
870     fn show(&self, kobj: Arc<dyn KObject>, buf: &mut [u8]) -> Result<usize, SystemError> {
871         let dev = kobj.cast::<dyn Device>().map_err(|kobj| {
872             error!(
873                 "Intertrait casting not implemented for kobj: {}",
874                 kobj.name()
875             );
876             SystemError::ENOSYS
877         })?;
878 
879         let device_number = dev.id_table().device_number();
880         let s = format!(
881             "{}:{}\n",
882             device_number.major().data(),
883             device_number.minor()
884         );
885 
886         return sysfs_emit_str(buf, &s);
887     }
888 
889     fn support(&self) -> SysFSOpsSupport {
890         SysFSOpsSupport::ATTR_SHOW
891     }
892 }
893 
894 /// 设备匹配器
895 ///
896 /// 用于匹配设备是否符合某个条件
897 ///
898 /// ## 参数
899 ///
900 /// - `T` - 匹配器的数据类型
901 /// - `data` - 匹配器的数据
902 pub trait DeviceMatcher<T>: Debug {
903     fn match_device(&self, device: &Arc<dyn Device>, data: T) -> bool;
904 }
905 
906 /// 用于根据名称匹配设备的匹配器
907 #[derive(Debug)]
908 pub struct DeviceMatchName;
909 
910 impl DeviceMatcher<&str> for DeviceMatchName {
911     #[inline]
912     fn match_device(&self, device: &Arc<dyn Device>, data: &str) -> bool {
913         return device.name() == data;
914     }
915 }
916 
917 /// Cookie to identify the device
918 #[derive(Debug, Clone)]
919 pub struct DeviceId {
920     data: Option<&'static str>,
921     allocated: Option<String>,
922 }
923 
924 impl DeviceId {
925     #[allow(dead_code)]
926     pub fn new(data: Option<&'static str>, allocated: Option<String>) -> Option<Arc<Self>> {
927         if data.is_none() && allocated.is_none() {
928             return None;
929         }
930 
931         // 如果data和allocated都有值,那么返回None
932         if data.is_some() && allocated.is_some() {
933             return None;
934         }
935 
936         return Some(Arc::new(Self { data, allocated }));
937     }
938 
939     pub fn id(&self) -> Option<&str> {
940         if self.data.is_some() {
941             return Some(self.data.unwrap());
942         } else {
943             return self.allocated.as_deref();
944         }
945     }
946 
947     #[allow(dead_code)]
948     pub fn set_allocated(&mut self, allocated: String) {
949         self.allocated = Some(allocated);
950         self.data = None;
951     }
952 }
953 
954 impl PartialEq for DeviceId {
955     fn eq(&self, other: &Self) -> bool {
956         return self.id() == other.id();
957     }
958 }
959 
960 impl core::hash::Hash for DeviceId {
961     fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
962         self.id().hash(state);
963     }
964 }
965 
966 impl Eq for DeviceId {}
967 
968 impl IrqHandlerData for DeviceId {}
969