xref: /DragonOS/kernel/src/driver/base/device/bus.rs (revision f9fe30be89e89499aad4ef52b4648986bef5a7d8)
1 use super::{
2     driver::{Driver, DriverMatchName, DriverMatcher},
3     sys_devices_kset, Device, DeviceMatchName, DeviceMatcher, DeviceState,
4 };
5 use crate::{
6     driver::base::{
7         device::{device_manager, driver::driver_manager},
8         kobject::{KObjType, KObject, KObjectManager},
9         kset::KSet,
10         subsys::SubSysPrivate,
11     },
12     filesystem::{
13         sysfs::{
14             file::sysfs_emit_str, sysfs_instance, Attribute, AttributeGroup, SysFSOps,
15             SysFSOpsSupport, SYSFS_ATTR_MODE_RW, SYSFS_ATTR_MODE_WO,
16         },
17         vfs::syscall::ModeType,
18     },
19     libs::rwlock::RwLock,
20 };
21 use alloc::{
22     string::{String, ToString},
23     sync::{Arc, Weak},
24 };
25 use core::{ffi::CStr, fmt::Debug, intrinsics::unlikely};
26 use hashbrown::HashMap;
27 use intertrait::cast::CastArc;
28 use log::{debug, error, info};
29 use system_error::SystemError;
30 
31 /// `/sys/bus`的kset
32 static mut BUS_KSET_INSTANCE: Option<Arc<KSet>> = None;
33 /// `/sys/devices/system`的kset
34 static mut DEVICES_SYSTEM_KSET_INSTANCE: Option<Arc<KSet>> = None;
35 
36 static mut BUS_MANAGER_INSTANCE: Option<BusManager> = None;
37 
38 #[inline(always)]
39 pub fn sys_bus_kset() -> Arc<KSet> {
40     unsafe { BUS_KSET_INSTANCE.clone().unwrap() }
41 }
42 
43 #[inline(always)]
44 #[allow(dead_code)]
45 pub fn sys_devices_system_kset() -> Arc<KSet> {
46     unsafe { DEVICES_SYSTEM_KSET_INSTANCE.clone().unwrap() }
47 }
48 
49 #[inline(always)]
50 pub fn bus_manager() -> &'static BusManager {
51     unsafe { BUS_MANAGER_INSTANCE.as_ref().unwrap() }
52 }
53 
54 #[inline(always)]
55 pub fn subsystem_manager() -> &'static SubSystemManager {
56     &SubSystemManager
57 }
58 
59 /// @brief: 总线状态
60 #[derive(Debug, Copy, Clone)]
61 pub enum BusState {
62     NotInitialized = 0, // 未初始化
63     Initialized = 1,    // 已初始化
64     UnDefined = 2,      // 未定义的
65 }
66 
67 /// @brief: 将u32类型转换为总线状态类型
68 impl From<u32> for BusState {
69     fn from(state: u32) -> Self {
70         match state {
71             0 => BusState::NotInitialized,
72             1 => BusState::Initialized,
73             _ => BusState::UnDefined,
74         }
75     }
76 }
77 
78 /// @brief: 将总线状态类型转换为u32类型
79 impl From<DeviceState> for BusState {
80     fn from(state: DeviceState) -> Self {
81         match state {
82             DeviceState::Initialized => BusState::Initialized,
83             DeviceState::NotInitialized => BusState::NotInitialized,
84             DeviceState::UnDefined => BusState::UnDefined,
85         }
86     }
87 }
88 
89 /// @brief: 将总线状态类型转换为设备状态类型
90 impl From<BusState> for DeviceState {
91     fn from(state: BusState) -> Self {
92         match state {
93             BusState::Initialized => DeviceState::Initialized,
94             BusState::NotInitialized => DeviceState::NotInitialized,
95             BusState::UnDefined => DeviceState::UnDefined,
96         }
97     }
98 }
99 
100 /// 总线子系统的trait,所有总线都应实现该trait
101 ///
102 /// 请注意,这个trait是用于实现总线子系统的,而不是总线驱动/总线设备。
103 /// https://code.dragonos.org.cn/xref/linux-6.1.9/include/linux/device/bus.h#84
104 pub trait Bus: Debug + Send + Sync {
105     fn name(&self) -> String;
106     /// Used for subsystems to enumerate devices like ("foo%u", dev->id).
107     fn dev_name(&self) -> String;
108     fn root_device(&self) -> Option<Weak<dyn Device>> {
109         None
110     }
111 
112     fn set_root_device(&self, _dev: Option<Weak<dyn Device>>) {}
113 
114     /// 总线上的设备的默认属性组
115     fn dev_groups(&self) -> &'static [&'static dyn AttributeGroup] {
116         &[]
117     }
118 
119     /// 总线的默认属性组
120     fn bus_groups(&self) -> &'static [&'static dyn AttributeGroup] {
121         &[]
122     }
123 
124     /// 总线上的驱动的默认属性组
125     fn drv_groups(&self) -> &'static [&'static dyn AttributeGroup] {
126         &[]
127     }
128 
129     /// 检查设备是否可以被总线绑定,如果可以,就绑定它们。
130     /// 绑定之后,device的driver字段会被设置为驱动实例。
131     ///
132     /// ## 参数
133     ///
134     /// - `device` - 设备实例
135     ///
136     /// ## 默认实现
137     ///
138     /// 如果总线不支持该操作,返回`SystemError::ENOSYS`
139     fn probe(&self, _device: &Arc<dyn Device>) -> Result<(), SystemError> {
140         return Err(SystemError::ENOSYS);
141     }
142     fn remove(&self, _device: &Arc<dyn Device>) -> Result<(), SystemError>;
143     fn sync_state(&self, _device: &Arc<dyn Device>) {}
144     fn shutdown(&self, _device: &Arc<dyn Device>);
145     fn suspend(&self, _device: &Arc<dyn Device>) {
146         // todo: implement suspend
147     }
148 
149     fn resume(&self, device: &Arc<dyn Device>) -> Result<(), SystemError>;
150 
151     /// match device to driver.
152     ///
153     /// ## 参数
154     ///
155     /// * `device` - device
156     /// * `driver` - driver
157     ///
158     /// ## 返回
159     ///
160     /// - `Ok(true)` - 匹配成功
161     /// - `Ok(false)` - 匹配失败
162     /// - `Err(_)` - 由于内部错误导致匹配失败
163     /// - `Err(SystemError::ENOSYS)` - 该总线不支持该操作
164     fn match_device(
165         &self,
166         _device: &Arc<dyn Device>,
167         _driver: &Arc<dyn Driver>,
168     ) -> Result<bool, SystemError> {
169         return Err(SystemError::ENOSYS);
170     }
171 
172     fn subsystem(&self) -> &SubSysPrivate;
173 
174     /// 对当前总线操作的时候需要获取父级总线的锁
175     fn need_parent_lock(&self) -> bool {
176         false
177     }
178 }
179 
180 impl dyn Bus {
181     /// 在bus上,根据条件寻找一个特定的设备
182     ///
183     /// ## 参数
184     ///
185     /// - `matcher` - 匹配器
186     /// - `data` - 传给匹配器的数据
187     pub fn find_device<T: Copy>(
188         &self,
189         matcher: &dyn DeviceMatcher<T>,
190         data: T,
191     ) -> Option<Arc<dyn Device>> {
192         let subsys = self.subsystem();
193         let guard = subsys.devices();
194         for dev in guard.iter() {
195             if matcher.match_device(dev, data) {
196                 return Some(dev.clone());
197             }
198         }
199         return None;
200     }
201 
202     /// 根据名称匹配设备
203     ///
204     /// ## 参数
205     ///
206     /// - name 设备名称
207     pub fn find_device_by_name(&self, name: &str) -> Option<Arc<dyn Device>> {
208         return self.find_device(&DeviceMatchName, name);
209     }
210 
211     /// 在bus上,根据条件寻找一个特定的驱动
212     ///
213     /// ## 参数
214     ///
215     /// - `matcher` - 匹配器
216     /// - `data` - 传给匹配器的数据
217     pub fn find_driver<T: Copy>(
218         &self,
219         matcher: &dyn DriverMatcher<T>,
220         data: T,
221     ) -> Option<Arc<dyn Driver>> {
222         let subsys = self.subsystem();
223         let guard = subsys.drivers();
224         for drv in guard.iter() {
225             if matcher.match_driver(drv, data) {
226                 return Some(drv.clone());
227             }
228         }
229         return None;
230     }
231 
232     /// 根据名称在bus上匹配驱动
233     pub fn find_driver_by_name(&self, name: &str) -> Option<Arc<dyn Driver>> {
234         return self.find_driver(&DriverMatchName, name);
235     }
236 }
237 
238 /// @brief: 总线管理结构体
239 #[derive(Debug)]
240 pub struct BusManager {
241     /// 存储总线bus的kset结构体与bus实例的映射(用于在sysfs callback的时候,根据kset找到bus实例)
242     kset_bus_map: RwLock<HashMap<Arc<KSet>, Arc<dyn Bus>>>,
243 }
244 
245 impl BusManager {
246     pub fn new() -> Self {
247         return Self {
248             kset_bus_map: RwLock::new(HashMap::new()),
249         };
250     }
251 
252     /// 把一个设备添加到总线上
253     ///
254     /// ## 描述
255     ///
256     /// - 添加一个设备的与bus相关的属性
257     /// - 在bus和设备文件夹下,创建软链接
258     /// - 把设备添加到它的总线的设备列表中
259     ///
260     /// 参考: https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/bus.c?fi=bus_add_device#441
261     ///
262     /// ## 参数
263     ///
264     /// - `dev` - 要被添加的设备
265     pub fn add_device(&self, dev: &Arc<dyn Device>) -> Result<(), SystemError> {
266         let bus = dev.bus().and_then(|bus| bus.upgrade());
267         if let Some(bus) = bus {
268             device_manager().add_groups(dev, bus.dev_groups())?;
269 
270             // 增加符号链接
271             let bus_devices_kset = bus
272                 .subsystem()
273                 .devices_kset()
274                 .expect("bus devices kset is none, maybe bus is not registered");
275             let dev_kobj = dev.clone() as Arc<dyn KObject>;
276 
277             sysfs_instance().create_link(
278                 Some(&bus_devices_kset.as_kobject()),
279                 &dev_kobj,
280                 dev.name(),
281             )?;
282             sysfs_instance().create_link(
283                 Some(&dev_kobj),
284                 &bus.subsystem().subsys().as_kobject(),
285                 "subsystem".to_string(),
286             )?;
287             bus.subsystem().add_device_to_vec(dev)?;
288         }
289         return Ok(());
290     }
291 
292     /// 在总线上添加一个驱动
293     ///
294     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/bus.c?fi=bus_add_driver#590
295     pub fn add_driver(&self, driver: &Arc<dyn Driver>) -> Result<(), SystemError> {
296         let bus = driver
297             .bus()
298             .and_then(|bus| bus.upgrade())
299             .ok_or(SystemError::EINVAL)?;
300         debug!("bus '{}' add driver '{}'", bus.name(), driver.name());
301 
302         // driver.set_kobj_type(Some(&BusDriverKType));
303         let kobj = driver.clone() as Arc<dyn KObject>;
304         // KObjectManager::add_kobj(kobj, bus.subsystem().drivers_kset())?;
305         KObjectManager::init_and_add_kobj(
306             kobj,
307             bus.subsystem().drivers_kset(),
308             Some(&BusDriverKType),
309         )?;
310 
311         bus.subsystem().add_driver_to_vec(driver)?;
312         if bus.subsystem().drivers_autoprobe() {
313             let r = driver_manager().driver_attach(driver);
314             if let Err(e) = r {
315                 bus.subsystem().remove_driver_from_vec(driver);
316                 return Err(e);
317             }
318         }
319 
320         driver_manager()
321             .add_groups(driver, bus.drv_groups())
322             .map_err(|e| {
323                 error!(
324                     "BusManager::add_driver: driver '{:?}' add_groups failed, err: '{:?}",
325                     driver.name(),
326                     e
327                 );
328                 e
329             })
330             .ok();
331 
332         if !driver.suppress_bind_attrs() {
333             self.add_bind_files(driver)
334                 .map_err(|e| {
335                     error!(
336                         "BusManager::add_driver: driver '{:?}' add_bind_files failed, err: '{:?}",
337                         driver.name(),
338                         e
339                     );
340                     e
341                 })
342                 .ok();
343         }
344 
345         return Ok(());
346     }
347 
348     ///
349     /// bus_register - register a driver-core subsystem
350     ///
351     /// ## 参数
352     /// - `bus` - bus to register
353     ///
354     /// Once we have that, we register the bus with the kobject
355     /// infrastructure, then register the children subsystems it has:
356     /// the devices and drivers that belong to the subsystem.
357     ///
358     /// 参考: https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/bus.c?fi=bus_register#783
359     ///
360     /// todo: 增加错误处理逻辑
361     pub fn register(&self, bus: Arc<dyn Bus>) -> Result<(), SystemError> {
362         bus.subsystem().set_bus(Some(Arc::downgrade(&bus)));
363 
364         let subsys_kset = bus.subsystem().subsys();
365         subsys_kset.set_name(bus.name());
366         bus.subsystem().set_drivers_autoprobe(true);
367 
368         subsys_kset.register(Some(sys_bus_kset()))?;
369 
370         let devices_kset =
371             KSet::new_and_add("devices".to_string(), None, Some(subsys_kset.clone()))?;
372         bus.subsystem().set_devices_kset(devices_kset);
373         let drivers_kset =
374             KSet::new_and_add("drivers".to_string(), None, Some(subsys_kset.clone()))?;
375         bus.subsystem().set_drivers_kset(drivers_kset);
376 
377         self.add_probe_files(&bus)?;
378         let bus_groups = bus.bus_groups();
379         self.add_groups(&bus, bus_groups)?;
380         // 把bus实例添加到总线管理器中(方便在sysfs callback的时候,根据kset找到bus实例)
381         self.kset_bus_map.write().insert(subsys_kset, bus.clone());
382         return Ok(());
383     }
384 
385     pub fn unregister(&self, _bus: Arc<dyn Bus>) -> Result<(), SystemError> {
386         todo!("bus_unregister")
387     }
388 
389     fn add_probe_files(&self, bus: &Arc<dyn Bus>) -> Result<(), SystemError> {
390         self.create_file(bus, &BusAttrDriversProbe)?;
391         let r = self.create_file(bus, &BusAttrDriversAutoprobe);
392 
393         if r.is_err() {
394             self.remove_file(bus, &BusAttrDriversProbe);
395         }
396         return r;
397     }
398 
399     #[allow(dead_code)]
400     fn remove_probe_files(&self, bus: &Arc<dyn Bus>) {
401         self.remove_file(bus, &BusAttrDriversAutoprobe);
402         self.remove_file(bus, &BusAttrDriversProbe);
403     }
404 
405     fn create_file(
406         &self,
407         bus: &Arc<dyn Bus>,
408         attr: &'static dyn Attribute,
409     ) -> Result<(), SystemError> {
410         let bus_kobj = bus.subsystem().subsys() as Arc<dyn KObject>;
411         return sysfs_instance().create_file(&bus_kobj, attr);
412     }
413 
414     fn remove_file(&self, bus: &Arc<dyn Bus>, attr: &'static dyn Attribute) {
415         let bus_kobj = bus.subsystem().subsys() as Arc<dyn KObject>;
416         sysfs_instance().remove_file(&bus_kobj, attr);
417     }
418 
419     #[inline]
420     fn add_groups(
421         &self,
422         bus: &Arc<dyn Bus>,
423         groups: &[&'static dyn AttributeGroup],
424     ) -> Result<(), SystemError> {
425         let bus_kobj = bus.subsystem().subsys() as Arc<dyn KObject>;
426         return sysfs_instance().create_groups(&bus_kobj, groups);
427     }
428 
429     /// 根据bus的kset找到bus实例
430     fn get_bus_by_kset(&self, kset: &Arc<KSet>) -> Option<Arc<dyn Bus>> {
431         return self.kset_bus_map.read().get(kset).cloned();
432     }
433 
434     /// 为bus上的设备选择可能的驱动程序
435     ///
436     /// 这个函数会扫描总线上的所有没有驱动的设备,然后为它们选择可能的驱动程序。
437     ///
438     /// ## 参数
439     ///
440     /// - `bus` - bus实例
441     #[allow(dead_code)]
442     pub fn rescan_devices(&self, bus: &Arc<dyn Bus>) -> Result<(), SystemError> {
443         for dev in bus.subsystem().devices().iter() {
444             rescan_devices_helper(dev)?;
445         }
446         return Ok(());
447     }
448 
449     /// 为新设备探测驱动
450     ///
451     /// Automatically probe for a driver if the bus allows it.
452     pub fn probe_device(&self, dev: &Arc<dyn Device>) {
453         let bus = dev.bus().and_then(|bus| bus.upgrade());
454         if bus.is_none() {
455             return;
456         }
457         let bus = bus.unwrap();
458         if bus.subsystem().drivers_autoprobe() {
459             log::info!("MT bus '{}' autoprobe driver", bus.name());
460             device_manager().device_initial_probe(dev).ok();
461         }
462         for interface in bus.subsystem().interfaces() {
463             interface.add_device(dev).ok();
464         }
465     }
466 
467     /// 从总线上移除一个驱动
468     ///
469     /// Detach the driver from the devices it controls, and remove
470     /// it from its bus's list of drivers. Finally, we drop the reference
471     /// to the bus.
472     ///
473     /// ## 参数
474     ///
475     /// - `driver` - 驱动实例
476     ///
477     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/bus.c?fi=bus_remove_driver#666
478     pub fn remove_driver(&self, _driver: &Arc<dyn Driver>) {
479         todo!("BusManager::remove_driver")
480     }
481 
482     fn add_bind_files(&self, driver: &Arc<dyn Driver>) -> Result<(), SystemError> {
483         driver_manager().create_attr_file(driver, &DriverAttrUnbind)?;
484 
485         driver_manager()
486             .create_attr_file(driver, &DriverAttrBind)
487             .inspect_err(|_e| {
488                 driver_manager().remove_attr_file(driver, &DriverAttrUnbind);
489             })?;
490 
491         return Ok(());
492     }
493 }
494 
495 /// 参考: https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/bus.c?r=&mo=5649&fi=241#684
496 fn rescan_devices_helper(dev: &Arc<dyn Device>) -> Result<(), SystemError> {
497     if dev.driver().is_none() {
498         let need_parent_lock = dev
499             .bus()
500             .map(|bus| bus.upgrade().unwrap().need_parent_lock())
501             .unwrap_or(false);
502         if unlikely(need_parent_lock) {
503             // todo: lock device parent
504             unimplemented!()
505         }
506         device_manager().device_attach(dev)?;
507     }
508     return Ok(());
509 }
510 
511 ///
512 /// bus_register - register a driver-core subsystem
513 ///
514 /// ## 参数
515 /// - `bus` - bus to register
516 ///
517 /// Once we have that, we register the bus with the kobject
518 /// infrastructure, then register the children subsystems it has:
519 /// the devices and drivers that belong to the subsystem.
520 pub fn bus_register(bus: Arc<dyn Bus>) -> Result<(), SystemError> {
521     return bus_manager().register(bus);
522 }
523 
524 /// @brief: 总线注销,并在sys/bussys/devices下删除文件夹
525 /// @parameter bus: Bus设备实体
526 /// @return: 成功:()   失败:SystemError
527 #[allow(dead_code)]
528 pub fn bus_unregister(bus: Arc<dyn Bus>) -> Result<(), SystemError> {
529     return bus_manager().unregister(bus);
530 }
531 
532 pub fn buses_init() -> Result<(), SystemError> {
533     let bus_kset = KSet::new("bus".to_string());
534     bus_kset.register(None).expect("bus kset register failed");
535     unsafe {
536         BUS_KSET_INSTANCE = Some(bus_kset);
537     }
538 
539     // 初始化 /sys/devices/system
540     {
541         let devices_system_kset = KSet::new("system".to_string());
542         let parent = sys_devices_kset() as Arc<dyn KObject>;
543         devices_system_kset.set_parent(Some(Arc::downgrade(&parent)));
544         devices_system_kset
545             .register(Some(sys_devices_kset()))
546             .expect("devices system kset register failed");
547         unsafe {
548             DEVICES_SYSTEM_KSET_INSTANCE = Some(devices_system_kset);
549         }
550     }
551 
552     // 初始化总线管理器
553     {
554         let bus_manager = BusManager::new();
555         unsafe {
556             BUS_MANAGER_INSTANCE = Some(bus_manager);
557         }
558     }
559     return Ok(());
560 }
561 
562 /// 把一个设备添加到总线上
563 ///
564 /// ## 描述
565 ///
566 /// - 添加一个设备的与bus相关的属性
567 /// - 在bus和设备文件夹下,创建软链接
568 /// - 把设备添加到它的总线的设备列表中
569 ///
570 /// 参考: https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/bus.c?fi=bus_add_device#441
571 ///
572 /// ## 参数
573 ///
574 /// - `dev` - 要被添加的设备
575 pub fn bus_add_device(dev: &Arc<dyn Device>) -> Result<(), SystemError> {
576     return bus_manager().add_device(dev);
577 }
578 
579 /// 自动为设备在总线上寻找可用的驱动程序
580 ///
581 /// Automatically probe for a driver if the bus allows it.
582 ///
583 /// ## 参数
584 ///
585 /// - `dev` - 要被添加的设备
586 ///
587 /// 参考: https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/bus.c?fi=bus_probe_device#478
588 pub fn bus_probe_device(dev: &Arc<dyn Device>) {
589     info!("bus_probe_device: dev: {:?}", dev.name());
590     bus_manager().probe_device(dev);
591 }
592 
593 #[derive(Debug)]
594 struct BusAttrDriversProbe;
595 
596 impl Attribute for BusAttrDriversProbe {
597     fn mode(&self) -> ModeType {
598         return ModeType::S_IWUSR;
599     }
600 
601     fn name(&self) -> &str {
602         return "drivers_probe";
603     }
604 
605     fn support(&self) -> SysFSOpsSupport {
606         return SysFSOpsSupport::ATTR_STORE;
607     }
608 
609     /// 参考: https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/bus.c?r=&mo=5649&fi=241#241
610     fn store(&self, kobj: Arc<dyn KObject>, buf: &[u8]) -> Result<usize, SystemError> {
611         let kset: Arc<KSet> = kobj.arc_any().downcast().map_err(|_| SystemError::EINVAL)?;
612         let bus = bus_manager()
613             .get_bus_by_kset(&kset)
614             .ok_or(SystemError::EINVAL)?;
615 
616         let name = CStr::from_bytes_with_nul(buf)
617             .map_err(|_| SystemError::EINVAL)?
618             .to_str()
619             .map_err(|_| SystemError::EINVAL)?;
620 
621         let device = bus.find_device_by_name(name).ok_or(SystemError::ENODEV)?;
622 
623         if rescan_devices_helper(&device).is_ok() {
624             return Ok(buf.len());
625         }
626 
627         return Err(SystemError::EINVAL);
628     }
629 }
630 
631 #[derive(Debug)]
632 struct BusAttrDriversAutoprobe;
633 
634 impl Attribute for BusAttrDriversAutoprobe {
635     fn mode(&self) -> ModeType {
636         SYSFS_ATTR_MODE_RW
637     }
638 
639     fn name(&self) -> &str {
640         return "drivers_autoprobe";
641     }
642 
643     fn support(&self) -> SysFSOpsSupport {
644         return SysFSOpsSupport::ATTR_STORE | SysFSOpsSupport::ATTR_SHOW;
645     }
646 
647     /// 参考: https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/bus.c?r=&mo=5649&fi=241#231
648     fn store(&self, kobj: Arc<dyn KObject>, buf: &[u8]) -> Result<usize, SystemError> {
649         if buf.is_empty() {
650             return Ok(0);
651         }
652 
653         let kset: Arc<KSet> = kobj.arc_any().downcast().map_err(|_| SystemError::EINVAL)?;
654         let bus = bus_manager()
655             .get_bus_by_kset(&kset)
656             .ok_or(SystemError::EINVAL)?;
657 
658         if buf[0] == b'0' {
659             bus.subsystem().set_drivers_autoprobe(false);
660         } else {
661             bus.subsystem().set_drivers_autoprobe(true);
662         }
663 
664         return Ok(buf.len());
665     }
666 
667     /// 参考: https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/bus.c?r=&mo=5649&fi=241#226
668     fn show(&self, kobj: Arc<dyn KObject>, buf: &mut [u8]) -> Result<usize, SystemError> {
669         let kset: Arc<KSet> = kobj.arc_any().downcast().map_err(|_| SystemError::EINVAL)?;
670         let bus = bus_manager()
671             .get_bus_by_kset(&kset)
672             .ok_or(SystemError::EINVAL)?;
673         let val = if bus.subsystem().drivers_autoprobe() {
674             1
675         } else {
676             0
677         };
678         return sysfs_emit_str(buf, format!("{val}\n").as_str());
679     }
680 }
681 
682 #[allow(dead_code)]
683 #[derive(Debug, Clone, Copy)]
684 pub enum BusNotifyEvent {
685     /// 一个设备被添加到总线上
686     AddDevice,
687     /// 一个设备将要被移除
688     DelDevice,
689     /// 一个设备已经被移除
690     RemovedDevice,
691     /// 一个驱动将要被绑定
692     BindDriver,
693     /// 一个驱动已经被绑定
694     BoundDriver,
695     /// 一个驱动将要被解绑
696     UnbindDriver,
697     /// 一个驱动已经被解绑
698     UnboundDriver,
699     /// 驱动绑定失败
700     DriverNotBound,
701 }
702 
703 #[derive(Debug)]
704 struct BusDriverKType;
705 
706 impl KObjType for BusDriverKType {
707     fn sysfs_ops(&self) -> Option<&dyn SysFSOps> {
708         Some(&BusDriverSysFSOps)
709     }
710 
711     fn attribute_groups(&self) -> Option<&'static [&'static dyn AttributeGroup]> {
712         None
713     }
714 }
715 
716 #[derive(Debug)]
717 struct BusDriverSysFSOps;
718 
719 impl SysFSOps for BusDriverSysFSOps {
720     #[inline]
721     fn show(
722         &self,
723         kobj: Arc<dyn KObject>,
724         attr: &dyn Attribute,
725         buf: &mut [u8],
726     ) -> Result<usize, SystemError> {
727         attr.show(kobj, buf)
728     }
729 
730     #[inline]
731     fn store(
732         &self,
733         kobj: Arc<dyn KObject>,
734         attr: &dyn Attribute,
735         buf: &[u8],
736     ) -> Result<usize, SystemError> {
737         attr.store(kobj, buf)
738     }
739 }
740 
741 #[derive(Debug)]
742 struct DriverAttrUnbind;
743 
744 impl Attribute for DriverAttrUnbind {
745     fn mode(&self) -> ModeType {
746         SYSFS_ATTR_MODE_WO
747     }
748 
749     fn name(&self) -> &str {
750         "unbind"
751     }
752 
753     fn store(&self, kobj: Arc<dyn KObject>, buf: &[u8]) -> Result<usize, SystemError> {
754         let driver = kobj.cast::<dyn Driver>().map_err(|kobj| {
755             error!(
756                 "Intertrait casting not implemented for kobj: {}",
757                 kobj.name()
758             );
759             SystemError::ENOSYS
760         })?;
761 
762         let bus = driver
763             .bus()
764             .and_then(|bus| bus.upgrade())
765             .ok_or(SystemError::ENODEV)?;
766 
767         let s = CStr::from_bytes_with_nul(buf)
768             .map_err(|_| SystemError::EINVAL)?
769             .to_str()
770             .map_err(|_| SystemError::EINVAL)?;
771         let dev = bus.find_device_by_name(s).ok_or(SystemError::ENODEV)?;
772         let p = dev.driver().ok_or(SystemError::ENODEV)?;
773         if Arc::ptr_eq(&p, &driver) {
774             device_manager().device_driver_detach(&dev);
775             return Ok(buf.len());
776         }
777         return Err(SystemError::ENODEV);
778     }
779 
780     fn support(&self) -> SysFSOpsSupport {
781         SysFSOpsSupport::ATTR_STORE
782     }
783 }
784 
785 #[derive(Debug)]
786 struct DriverAttrBind;
787 
788 impl Attribute for DriverAttrBind {
789     fn name(&self) -> &str {
790         "bind"
791     }
792 
793     fn mode(&self) -> ModeType {
794         SYSFS_ATTR_MODE_WO
795     }
796 
797     /*
798      * Manually attach a device to a driver.
799      * Note: the driver must want to bind to the device,
800      * it is not possible to override the driver's id table.
801      */
802     fn store(&self, kobj: Arc<dyn KObject>, buf: &[u8]) -> Result<usize, SystemError> {
803         let driver = kobj.cast::<dyn Driver>().map_err(|kobj| {
804             error!(
805                 "Intertrait casting not implemented for kobj: {}",
806                 kobj.name()
807             );
808             SystemError::ENOSYS
809         })?;
810 
811         let bus = driver
812             .bus()
813             .and_then(|bus| bus.upgrade())
814             .ok_or(SystemError::ENODEV)?;
815         let device = bus
816             .find_device_by_name(
817                 CStr::from_bytes_with_nul(buf)
818                     .map_err(|_| SystemError::EINVAL)?
819                     .to_str()
820                     .map_err(|_| SystemError::EINVAL)?,
821             )
822             .ok_or(SystemError::ENODEV)?;
823 
824         if driver_manager().match_device(&driver, &device)? {
825             device_manager().device_driver_attach(&driver, &device)?;
826             return Ok(buf.len());
827         }
828         return Err(SystemError::ENODEV);
829     }
830     fn support(&self) -> SysFSOpsSupport {
831         SysFSOpsSupport::ATTR_STORE
832     }
833 }
834 
835 #[derive(Debug)]
836 pub struct SubSystemManager;
837 
838 impl SubSystemManager {
839     /// 注册一个子系统,并在`/sys/bus`和指定的父级文件夹下创建子文件夹
840     ///
841     /// ## 参数
842     ///
843     /// - `subsys` - 子系统实例
844     /// - `fake_root_dev` - 该子系统的伪根设备
845     /// - `parent_of_root` - 该子系统的伪根设备的父级节点
846     ///
847     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/bus.c?fi=subsys_system_register#1078
848     pub fn subsys_register(
849         &self,
850         subsys: &Arc<dyn Bus>,
851         fake_root_dev: &Arc<dyn Device>,
852         parent_of_root: &Arc<dyn KObject>,
853     ) -> Result<(), SystemError> {
854         bus_manager().register(subsys.clone())?;
855         fake_root_dev.set_name(subsys.name());
856         fake_root_dev.set_parent(Some(Arc::downgrade(parent_of_root)));
857 
858         device_manager().register(fake_root_dev.clone())?;
859 
860         subsys.set_root_device(Some(Arc::downgrade(fake_root_dev)));
861         return Ok(());
862     }
863 
864     /// register a subsystem at /sys/devices/system/
865     /// 并且在/sys/bus和/sys/devices下创建文件夹
866     ///
867     /// All 'system' subsystems have a /sys/devices/system/<name> root device
868     /// with the name of the subsystem. The root device can carry subsystem-
869     /// wide attributes. All registered devices are below this single root
870     /// device and are named after the subsystem with a simple enumeration
871     /// number appended. The registered devices are not explicitly named;
872     /// only 'id' in the device needs to be set.
873     pub fn subsys_system_register(
874         &self,
875         subsys: &Arc<dyn Bus>,
876         fake_root_dev: &Arc<dyn Device>,
877     ) -> Result<(), SystemError> {
878         return self.subsys_register(
879             subsys,
880             fake_root_dev,
881             &(sys_devices_system_kset() as Arc<dyn KObject>),
882         );
883     }
884 }
885