xref: /DragonOS/kernel/src/driver/base/device/bus.rs (revision 06d5e247267cb65b84a80f219853ccd0f384b16e)
1 use super::{sys_devices_kset, Device, DeviceMatchName, DeviceMatcher, DeviceState};
2 use crate::{
3     driver::base::{device::device_manager, kobject::KObject, kset::KSet, subsys::SubSysPrivate},
4     filesystem::{
5         sysfs::{file::sysfs_emit_str, sysfs_instance, Attribute, AttributeGroup, SysFSOpsSupport},
6         vfs::syscall::ModeType,
7     },
8     libs::rwlock::RwLock,
9     syscall::SystemError,
10 };
11 use alloc::{
12     string::{String, ToString},
13     sync::Arc,
14 };
15 use core::{ffi::CStr, fmt::Debug, intrinsics::unlikely};
16 use hashbrown::HashMap;
17 
18 /// `/sys/bus`的kset
19 static mut BUS_KSET_INSTANCE: Option<Arc<KSet>> = None;
20 /// `/sys/devices/system`的kset
21 static mut DEVICES_SYSTEM_KSET_INSTANCE: Option<Arc<KSet>> = None;
22 
23 static mut BUS_MANAGER_INSTANCE: Option<BusManager> = None;
24 
25 #[inline(always)]
26 pub fn sys_bus_kset() -> Arc<KSet> {
27     unsafe { BUS_KSET_INSTANCE.clone().unwrap() }
28 }
29 
30 #[inline(always)]
31 #[allow(dead_code)]
32 pub fn sys_devices_system_kset() -> Arc<KSet> {
33     unsafe { DEVICES_SYSTEM_KSET_INSTANCE.clone().unwrap() }
34 }
35 
36 #[inline(always)]
37 pub fn bus_manager() -> &'static BusManager {
38     unsafe { BUS_MANAGER_INSTANCE.as_ref().unwrap() }
39 }
40 
41 /// @brief: 总线状态
42 #[derive(Debug, Copy, Clone)]
43 pub enum BusState {
44     NotInitialized = 0, // 未初始化
45     Initialized = 1,    // 已初始化
46     UnDefined = 2,      // 未定义的
47 }
48 
49 /// @brief: 将u32类型转换为总线状态类型
50 impl From<u32> for BusState {
51     fn from(state: u32) -> Self {
52         match state {
53             0 => BusState::NotInitialized,
54             1 => BusState::Initialized,
55             _ => BusState::UnDefined,
56         }
57     }
58 }
59 
60 /// @brief: 将总线状态类型转换为u32类型
61 impl From<DeviceState> for BusState {
62     fn from(state: DeviceState) -> Self {
63         match state {
64             DeviceState::Initialized => BusState::Initialized,
65             DeviceState::NotInitialized => BusState::NotInitialized,
66             DeviceState::UnDefined => BusState::UnDefined,
67         }
68     }
69 }
70 
71 /// @brief: 将总线状态类型转换为设备状态类型
72 impl From<BusState> for DeviceState {
73     fn from(state: BusState) -> Self {
74         match state {
75             BusState::Initialized => DeviceState::Initialized,
76             BusState::NotInitialized => DeviceState::NotInitialized,
77             BusState::UnDefined => DeviceState::UnDefined,
78         }
79     }
80 }
81 
82 /// 总线子系统的trait,所有总线都应实现该trait
83 ///
84 /// 请注意,这个trait是用于实现总线子系统的,而不是总线驱动/总线设备。
85 /// https://opengrok.ringotek.cn/xref/linux-6.1.9/include/linux/device/bus.h#84
86 pub trait Bus: Debug + Send + Sync {
87     fn name(&self) -> String;
88     fn dev_name(&self) -> String;
89     fn root_device(&self) -> Option<Arc<dyn Device>> {
90         None
91     }
92 
93     /// 总线上的设备的默认属性组
94     fn dev_groups(&self) -> &'static [&'static dyn AttributeGroup] {
95         &[]
96     }
97 
98     /// 总线的默认属性组
99     fn bus_groups(&self) -> &'static [&'static dyn AttributeGroup] {
100         &[]
101     }
102 
103     /// 总线上的驱动的默认属性组
104     fn drv_groups(&self) -> &'static [&'static dyn AttributeGroup] {
105         &[]
106     }
107 
108     fn subsystem(&self) -> &SubSysPrivate;
109 
110     /// 对当前总线操作的时候需要获取父级总线的锁
111     fn need_parent_lock(&self) -> bool {
112         false
113     }
114 }
115 
116 impl dyn Bus {
117     /// 在bus上,根据条件寻找一个特定的设备
118     ///
119     /// ## 参数
120     ///
121     /// - `matcher` - 匹配器
122     /// - `data` - 传给匹配器的数据
123     pub fn find_device<T: Copy>(
124         &self,
125         matcher: &dyn DeviceMatcher<T>,
126         data: T,
127     ) -> Option<Arc<dyn Device>> {
128         let subsys = self.subsystem();
129         let guard = subsys.devices().read();
130         for dev in guard.iter() {
131             let dev = dev.upgrade();
132             if let Some(dev) = dev {
133                 if matcher.match_device(&dev, data) {
134                     return Some(dev.clone());
135                 }
136             }
137         }
138         return None;
139     }
140 
141     /// 根据名称匹配设备
142     ///
143     /// ## 参数
144     ///
145     /// - name 设备名称
146     pub fn find_device_by_name(&self, name: &str) -> Option<Arc<dyn Device>> {
147         return self.find_device(&DeviceMatchName, name);
148     }
149 }
150 
151 /// @brief: 总线管理结构体
152 #[derive(Debug)]
153 pub struct BusManager {
154     /// 存储总线bus的kset结构体与bus实例的映射(用于在sysfs callback的时候,根据kset找到bus实例)
155     kset_bus_map: RwLock<HashMap<Arc<KSet>, Arc<dyn Bus>>>,
156 }
157 
158 impl BusManager {
159     pub fn new() -> Self {
160         return Self {
161             kset_bus_map: RwLock::new(HashMap::new()),
162         };
163     }
164 
165     ///
166     /// bus_register - register a driver-core subsystem
167     ///
168     /// ## 参数
169     /// - `bus` - bus to register
170     ///
171     /// Once we have that, we register the bus with the kobject
172     /// infrastructure, then register the children subsystems it has:
173     /// the devices and drivers that belong to the subsystem.
174     ///
175     /// 参考: https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/bus.c?fi=bus_register#783
176     ///
177     /// todo: 增加错误处理逻辑
178     pub fn register(&self, bus: Arc<dyn Bus>) -> Result<(), SystemError> {
179         bus.subsystem().set_bus(Arc::downgrade(&bus));
180 
181         let subsys_kset = bus.subsystem().subsys();
182         subsys_kset.set_name(bus.name());
183         bus.subsystem().set_drivers_autoprobe(true);
184 
185         subsys_kset.register(Some(sys_bus_kset()))?;
186 
187         let devices_kset =
188             KSet::new_and_add("devices".to_string(), None, Some(subsys_kset.clone()))?;
189         bus.subsystem().set_devices_kset(devices_kset);
190         let drivers_kset =
191             KSet::new_and_add("drivers".to_string(), None, Some(subsys_kset.clone()))?;
192         bus.subsystem().set_drivers_kset(drivers_kset);
193 
194         self.add_probe_files(&bus)?;
195         let bus_groups = bus.bus_groups();
196         self.add_groups(&bus, bus_groups)?;
197         // 把bus实例添加到总线管理器中(方便在sysfs callback的时候,根据kset找到bus实例)
198         self.kset_bus_map.write().insert(subsys_kset, bus.clone());
199         return Ok(());
200     }
201 
202     pub fn unregister(&self, _bus: Arc<dyn Bus>) -> Result<(), SystemError> {
203         todo!("bus_unregister")
204     }
205 
206     fn add_probe_files(&self, bus: &Arc<dyn Bus>) -> Result<(), SystemError> {
207         self.create_file(bus, &BusAttrDriversProbe)?;
208         let r = self.create_file(bus, &BusAttrDriversAutoprobe);
209 
210         if r.is_err() {
211             self.remove_file(bus, &BusAttrDriversProbe);
212         }
213         return r;
214     }
215 
216     #[allow(dead_code)]
217     fn remove_probe_files(&self, bus: &Arc<dyn Bus>) {
218         self.remove_file(bus, &BusAttrDriversAutoprobe);
219         self.remove_file(bus, &BusAttrDriversProbe);
220     }
221 
222     fn create_file(
223         &self,
224         bus: &Arc<dyn Bus>,
225         attr: &'static dyn Attribute,
226     ) -> Result<(), SystemError> {
227         let bus_kobj = bus.subsystem().subsys() as Arc<dyn KObject>;
228         return sysfs_instance().create_file(&bus_kobj, attr);
229     }
230 
231     fn remove_file(&self, bus: &Arc<dyn Bus>, attr: &'static dyn Attribute) {
232         let bus_kobj = bus.subsystem().subsys() as Arc<dyn KObject>;
233         sysfs_instance().remove_file(&bus_kobj, attr);
234     }
235 
236     #[inline]
237     fn add_groups(
238         &self,
239         bus: &Arc<dyn Bus>,
240         groups: &[&'static dyn AttributeGroup],
241     ) -> Result<(), SystemError> {
242         let bus_kobj = bus.subsystem().subsys() as Arc<dyn KObject>;
243         return sysfs_instance().create_groups(&bus_kobj, groups);
244     }
245 
246     /// 根据bus的kset找到bus实例
247     fn get_bus_by_kset(&self, kset: &Arc<KSet>) -> Option<Arc<dyn Bus>> {
248         return self.kset_bus_map.read().get(kset).map(|bus| bus.clone());
249     }
250 
251     /// 为bus上的设备选择可能的驱动程序
252     ///
253     /// 这个函数会扫描总线上的所有没有驱动的设备,然后为它们选择可能的驱动程序。
254     ///
255     /// ## 参数
256     ///
257     /// - `bus` - bus实例
258     #[allow(dead_code)]
259     pub fn rescan_devices(&self, bus: &Arc<dyn Bus>) -> Result<(), SystemError> {
260         for dev in bus.subsystem().devices().read().iter() {
261             let dev = dev.upgrade();
262             if let Some(dev) = dev {
263                 rescan_devices_helper(dev)?;
264             }
265         }
266         return Ok(());
267     }
268 
269     /// 为新设备探测驱动
270     ///
271     /// Automatically probe for a driver if the bus allows it.
272     pub fn probe_device(&self, dev: &Arc<dyn Device>) {
273         let bus = dev.bus();
274         if bus.is_none() {
275             return;
276         }
277         let bus = bus.unwrap();
278         if bus.subsystem().drivers_autoprobe() {
279             device_manager().device_initial_probe(dev).ok();
280         }
281         for interface in bus.subsystem().interfaces() {
282             interface.add_device(dev).ok();
283         }
284     }
285 
286     /// 在bus上,根据条件寻找一个特定的设备
287     ///
288     /// ## 参数
289     ///
290     /// - `matcher` - 匹配器
291     /// - `data` - 传给匹配器的数据
292     #[inline]
293     #[allow(dead_code)]
294     pub fn find_device<T: Copy>(
295         &self,
296         bus: &Arc<dyn Bus>,
297         matcher: &dyn DeviceMatcher<T>,
298         data: T,
299     ) -> Option<Arc<dyn Device>> {
300         return bus.find_device(matcher, data);
301     }
302 }
303 
304 /// 参考: https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/bus.c?r=&mo=5649&fi=241#684
305 fn rescan_devices_helper(dev: Arc<dyn Device>) -> Result<(), SystemError> {
306     if dev.driver().is_none() {
307         let need_parent_lock = dev.bus().map(|bus| bus.need_parent_lock()).unwrap_or(false);
308         if unlikely(need_parent_lock) {
309             // todo: lock device parent
310             unimplemented!()
311         }
312         device_manager().device_attach(&dev)?;
313     }
314     return Ok(());
315 }
316 
317 ///
318 /// bus_register - register a driver-core subsystem
319 ///
320 /// ## 参数
321 /// - `bus` - bus to register
322 ///
323 /// Once we have that, we register the bus with the kobject
324 /// infrastructure, then register the children subsystems it has:
325 /// the devices and drivers that belong to the subsystem.
326 pub fn bus_register(bus: Arc<dyn Bus>) -> Result<(), SystemError> {
327     return bus_manager().register(bus);
328 }
329 
330 /// @brief: 总线注销,并在sys/bussys/devices下删除文件夹
331 /// @parameter bus: Bus设备实体
332 /// @return: 成功:()   失败:SystemError
333 #[allow(dead_code)]
334 pub fn bus_unregister(bus: Arc<dyn Bus>) -> Result<(), SystemError> {
335     return bus_manager().unregister(bus);
336 }
337 
338 pub fn buses_init() -> Result<(), SystemError> {
339     let bus_kset = KSet::new("bus".to_string());
340     bus_kset.register(None).expect("bus kset register failed");
341     unsafe {
342         BUS_KSET_INSTANCE = Some(bus_kset);
343     }
344 
345     // 初始化 /sys/devices/system
346     {
347         let devices_system_kset = KSet::new("system".to_string());
348         let parent = sys_devices_kset() as Arc<dyn KObject>;
349         devices_system_kset.set_parent(Some(Arc::downgrade(&parent)));
350         devices_system_kset
351             .register(Some(sys_devices_kset()))
352             .expect("devices system kset register failed");
353     }
354 
355     // 初始化总线管理器
356     {
357         let bus_manager = BusManager::new();
358         unsafe {
359             BUS_MANAGER_INSTANCE = Some(bus_manager);
360         }
361     }
362     return Ok(());
363 }
364 
365 /// 把一个设备添加到总线上
366 ///
367 /// ## 描述
368 ///
369 /// - 添加一个设备的与bus相关的属性
370 /// - 在bus和设备文件夹下,创建软链接
371 /// - 把设备添加到它的总线的设备列表中
372 ///
373 /// 参考: https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/bus.c?fi=bus_add_device#441
374 ///
375 /// ## 参数
376 ///
377 /// - `dev` - 要被添加的设备
378 pub fn bus_add_device(dev: &Arc<dyn Device>) -> Result<(), SystemError> {
379     let bus = dev.bus();
380     if let Some(bus) = bus {
381         device_manager().add_groups(dev, bus.dev_groups())?;
382         // todo: 增加符号链接
383         todo!("bus_add_device")
384     }
385     return Ok(());
386 }
387 
388 /// 自动为设备在总线上寻找可用的驱动程序
389 ///
390 /// Automatically probe for a driver if the bus allows it.
391 ///
392 /// ## 参数
393 ///
394 /// - `dev` - 要被添加的设备
395 ///
396 /// 参考: https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/bus.c?fi=bus_probe_device#478
397 pub fn bus_probe_device(dev: &Arc<dyn Device>) {
398     bus_manager().probe_device(dev);
399 }
400 
401 #[derive(Debug)]
402 struct BusAttrDriversProbe;
403 
404 impl Attribute for BusAttrDriversProbe {
405     fn mode(&self) -> ModeType {
406         return ModeType::S_IWUSR;
407     }
408 
409     fn name(&self) -> &str {
410         return "drivers_probe";
411     }
412 
413     fn support(&self) -> SysFSOpsSupport {
414         return SysFSOpsSupport::STORE;
415     }
416 
417     /// 参考: https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/bus.c?r=&mo=5649&fi=241#241
418     fn store(&self, kobj: Arc<dyn KObject>, buf: &[u8]) -> Result<usize, SystemError> {
419         let kset: Arc<KSet> = kobj.arc_any().downcast().map_err(|_| SystemError::EINVAL)?;
420         let bus = bus_manager()
421             .get_bus_by_kset(&kset)
422             .ok_or(SystemError::EINVAL)?;
423 
424         let name = CStr::from_bytes_with_nul(buf)
425             .map_err(|_| SystemError::EINVAL)?
426             .to_str()
427             .map_err(|_| SystemError::EINVAL)?;
428 
429         let device = bus.find_device_by_name(name).ok_or(SystemError::ENODEV)?;
430 
431         if rescan_devices_helper(device).is_ok() {
432             return Ok(buf.len());
433         }
434 
435         return Err(SystemError::EINVAL);
436     }
437 }
438 
439 #[derive(Debug)]
440 struct BusAttrDriversAutoprobe;
441 
442 impl Attribute for BusAttrDriversAutoprobe {
443     fn mode(&self) -> ModeType {
444         return ModeType::from_bits_truncate(0o644);
445     }
446 
447     fn name(&self) -> &str {
448         return "drivers_autoprobe";
449     }
450 
451     fn support(&self) -> SysFSOpsSupport {
452         return SysFSOpsSupport::STORE | SysFSOpsSupport::SHOW;
453     }
454 
455     /// 参考: https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/bus.c?r=&mo=5649&fi=241#231
456     fn store(&self, kobj: Arc<dyn KObject>, buf: &[u8]) -> Result<usize, SystemError> {
457         if buf.len() == 0 {
458             return Ok(0);
459         }
460 
461         let kset: Arc<KSet> = kobj.arc_any().downcast().map_err(|_| SystemError::EINVAL)?;
462         let bus = bus_manager()
463             .get_bus_by_kset(&kset)
464             .ok_or(SystemError::EINVAL)?;
465 
466         if buf[0] == '0' as u8 {
467             bus.subsystem().set_drivers_autoprobe(false);
468         } else {
469             bus.subsystem().set_drivers_autoprobe(true);
470         }
471 
472         return Ok(buf.len());
473     }
474 
475     /// 参考: https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/bus.c?r=&mo=5649&fi=241#226
476     fn show(&self, kobj: Arc<dyn KObject>, buf: &mut [u8]) -> Result<usize, SystemError> {
477         let kset: Arc<KSet> = kobj.arc_any().downcast().map_err(|_| SystemError::EINVAL)?;
478         let bus = bus_manager()
479             .get_bus_by_kset(&kset)
480             .ok_or(SystemError::EINVAL)?;
481         let val = if bus.subsystem().drivers_autoprobe() {
482             1
483         } else {
484             0
485         };
486         return sysfs_emit_str(buf, format!("{val}\n").as_str());
487     }
488 }
489 
490 #[allow(dead_code)]
491 #[derive(Debug, Clone, Copy)]
492 pub enum BusNotifyEvent {
493     /// 一个设备被添加到总线上
494     AddDevice,
495     /// 一个设备将要被移除
496     DelDevice,
497     /// 一个设备已经被移除
498     RemovedDevice,
499     /// 一个驱动将要被绑定
500     BindDriver,
501     /// 一个驱动已经被绑定
502     BoundDriver,
503     /// 一个驱动将要被解绑
504     UnbindDriver,
505     /// 一个驱动已经被解绑
506     UnboundDriver,
507     /// 驱动绑定失败
508     DriverNotBound,
509 }
510