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