xref: /DragonOS/kernel/src/driver/base/device/mod.rs (revision a03c4f9dee5705207325c56629c0ccd219168f10)
1 use alloc::{
2     string::{String, ToString},
3     sync::{Arc, Weak},
4 };
5 use intertrait::cast::CastArc;
6 
7 use crate::{
8     driver::{
9         acpi::glue::acpi_device_notify,
10         base::map::{LockedDevsMap, LockedKObjMap},
11     },
12     filesystem::{
13         sysfs::{
14             file::sysfs_emit_str, sysfs_instance, Attribute, AttributeGroup, SysFSOps,
15             SysFSOpsSupport,
16         },
17         vfs::syscall::ModeType,
18     },
19     syscall::SystemError,
20 };
21 use core::fmt::Debug;
22 use core::intrinsics::unlikely;
23 
24 use self::{
25     bus::{bus_add_device, bus_probe_device, Bus},
26     driver::Driver,
27 };
28 
29 use super::{
30     kobject::{KObjType, KObject, KObjectManager, KObjectState},
31     kset::KSet,
32     swnode::software_node_notify,
33 };
34 
35 pub mod bus;
36 pub mod dd;
37 pub mod driver;
38 pub mod init;
39 
40 static mut DEVICE_MANAGER: Option<DeviceManager> = None;
41 
42 #[inline(always)]
43 pub fn device_manager() -> &'static DeviceManager {
44     unsafe { DEVICE_MANAGER.as_ref().unwrap() }
45 }
46 
47 lazy_static! {
48     // 全局字符设备号管理实例
49     pub static ref CHARDEVS: Arc<LockedDevsMap> = Arc::new(LockedDevsMap::default());
50 
51     // 全局块设备管理实例
52     pub static ref BLOCKDEVS: Arc<LockedDevsMap> = Arc::new(LockedDevsMap::default());
53 
54     // 全局设备管理实例
55     pub static ref DEVMAP: Arc<LockedKObjMap> = Arc::new(LockedKObjMap::default());
56 
57 }
58 
59 /// `/sys/devices` 的 kset 实例
60 static mut DEVICES_KSET_INSTANCE: Option<Arc<KSet>> = None;
61 /// `/sys/dev` 的 kset 实例
62 static mut DEV_KSET_INSTANCE: Option<Arc<KSet>> = None;
63 /// `/sys/dev/block` 的 kset 实例
64 static mut DEV_BLOCK_KSET_INSTANCE: Option<Arc<KSet>> = None;
65 /// `/sys/dev/char` 的 kset 实例
66 static mut DEV_CHAR_KSET_INSTANCE: Option<Arc<KSet>> = None;
67 
68 #[inline(always)]
69 pub(super) fn sys_devices_kset() -> Arc<KSet> {
70     unsafe { DEVICES_KSET_INSTANCE.as_ref().unwrap().clone() }
71 }
72 
73 #[inline(always)]
74 pub(super) fn sys_dev_kset() -> Arc<KSet> {
75     unsafe { DEV_KSET_INSTANCE.as_ref().unwrap().clone() }
76 }
77 
78 #[inline(always)]
79 #[allow(dead_code)]
80 pub(super) fn sys_dev_block_kset() -> Arc<KSet> {
81     unsafe { DEV_BLOCK_KSET_INSTANCE.as_ref().unwrap().clone() }
82 }
83 
84 #[inline(always)]
85 pub(self) fn sys_dev_char_kset() -> Arc<KSet> {
86     unsafe { DEV_CHAR_KSET_INSTANCE.as_ref().unwrap().clone() }
87 }
88 
89 /// 设备应该实现的操作
90 ///
91 /// ## 注意
92 ///
93 /// 由于设备驱动模型需要从Arc<dyn KObject>转换为Arc<dyn Device>,
94 /// 因此,所有的实现了Device trait的结构体,都应该在结构体上方标注`#[cast_to([sync] Device)]`,
95 ///
96 /// 否则在释放设备资源的时候,会由于无法转换为Arc<dyn Device>而导致资源泄露,并且release回调函数也不会被调用。
97 pub trait Device: KObject {
98     // TODO: 待实现 open, close
99 
100     /// @brief: 获取设备类型
101     /// @parameter: None
102     /// @return: 实现该trait的设备所属类型
103     fn dev_type(&self) -> DeviceType;
104 
105     /// @brief: 获取设备标识
106     /// @parameter: None
107     /// @return: 该设备唯一标识
108     fn id_table(&self) -> IdTable;
109 
110     /// 设备释放时的回调函数
111     fn release(&self) {
112         let name = self.name();
113         kwarn!(
114             "device {} does not have a release() function, it is broken and must be fixed.",
115             name
116         );
117     }
118 
119     /// 获取当前设备所属的总线
120     fn bus(&self) -> Option<Arc<dyn Bus>> {
121         return None;
122     }
123 
124     /// 设置当前设备所属的总线
125     ///
126     /// (一定要传入Arc,因为bus的subsysprivate里面存储的是Device的Weak指针)
127     fn set_bus(&self, bus: Option<Arc<dyn Bus>>);
128 
129     /// 返回已经与当前设备匹配好的驱动程序
130     fn driver(&self) -> Option<Arc<dyn Driver>>;
131 
132     fn set_driver(&self, driver: Option<Weak<dyn Driver>>);
133 
134     /// 当前设备是否已经挂掉了
135     fn is_dead(&self) -> bool;
136 
137     /// 当前设备是否处于可以被匹配的状态
138     ///
139     /// The device has matched with a driver at least once or it is in
140     /// a bus (like AMBA) which can't check for matching drivers until
141     /// other devices probe successfully.
142     fn can_match(&self) -> bool;
143 
144     fn set_can_match(&self, can_match: bool);
145 
146     /// The hardware state of this device has been synced to match
147     /// the software state of this device by calling the driver/bus
148     /// sync_state() callback.
149     fn state_synced(&self) -> bool;
150 }
151 
152 impl dyn Device {
153     #[inline(always)]
154     pub fn is_registered(&self) -> bool {
155         self.kobj_state().contains(KObjectState::IN_SYSFS)
156     }
157 }
158 
159 // 暂定是不可修改的,在初始化的时候就要确定。以后可能会包括例如硬件中断包含的信息
160 #[allow(dead_code)]
161 #[derive(Debug, Clone)]
162 pub struct DevicePrivateData {
163     id_table: IdTable,
164     state: DeviceState,
165 }
166 
167 #[allow(dead_code)]
168 impl DevicePrivateData {
169     pub fn new(id_table: IdTable, state: DeviceState) -> Self {
170         Self { id_table, state }
171     }
172 
173     pub fn id_table(&self) -> &IdTable {
174         &self.id_table
175     }
176 
177     pub fn state(&self) -> DeviceState {
178         self.state
179     }
180 
181     pub fn set_state(&mut self, state: DeviceState) {
182         self.state = state;
183     }
184 }
185 
186 int_like!(DeviceNumber, usize);
187 
188 impl Default for DeviceNumber {
189     fn default() -> Self {
190         DeviceNumber(0)
191     }
192 }
193 
194 impl From<usize> for DeviceNumber {
195     fn from(dev_t: usize) -> Self {
196         DeviceNumber(dev_t)
197     }
198 }
199 
200 impl Into<usize> for DeviceNumber {
201     fn into(self) -> usize {
202         self.0
203     }
204 }
205 
206 impl core::hash::Hash for DeviceNumber {
207     fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
208         self.0.hash(state);
209     }
210 }
211 
212 impl DeviceNumber {
213     /// @brief: 获取主设备号
214     /// @parameter: none
215     /// @return: 主设备号
216     pub fn major(&self) -> usize {
217         (self.0 >> 8) & 0xffffff
218     }
219 
220     /// @brief: 获取次设备号
221     /// @parameter: none
222     /// @return: 次设备号
223     pub fn minor(&self) -> usize {
224         self.0 & 0xff
225     }
226 
227     #[inline]
228     #[allow(dead_code)]
229     pub fn from_major_minor(major: usize, minor: usize) -> usize {
230         ((major & 0xffffff) << 8) | (minor & 0xff)
231     }
232 }
233 
234 /// @brief: 根据主次设备号创建设备号实例
235 /// @parameter: major: 主设备号
236 ///             minor: 次设备号
237 /// @return: 设备号实例
238 pub fn mkdev(major: usize, minor: usize) -> DeviceNumber {
239     DeviceNumber(((major & 0xfff) << 20) | (minor & 0xfffff))
240 }
241 
242 /// @brief: 设备类型
243 #[allow(dead_code)]
244 #[derive(Debug, Eq, PartialEq)]
245 pub enum DeviceType {
246     Bus,
247     Net,
248     Gpu,
249     Input,
250     Block,
251     Rtc,
252     Serial,
253     Intc,
254     PlatformDev,
255 }
256 
257 /// @brief: 设备标识符类型
258 #[derive(Debug, Clone, Hash, PartialOrd, PartialEq, Ord, Eq)]
259 pub struct IdTable(String, DeviceNumber);
260 
261 /// @brief: 设备标识符操作方法集
262 impl IdTable {
263     /// @brief: 创建一个新的设备标识符
264     /// @parameter name: 设备名
265     /// @parameter id: 设备id
266     /// @return: 设备标识符
267     pub fn new(name: String, id: DeviceNumber) -> IdTable {
268         Self(name, id)
269     }
270 
271     /// @brief: 将设备标识符转换成name
272     /// @parameter None
273     /// @return: 设备名
274     pub fn name(&self) -> String {
275         return format!("{}:{}", self.0, self.1 .0);
276     }
277 
278     pub fn device_number(&self) -> DeviceNumber {
279         return self.1;
280     }
281 }
282 
283 impl Default for IdTable {
284     fn default() -> Self {
285         IdTable("unknown".to_string(), DeviceNumber::new(0))
286     }
287 }
288 
289 // 以现在的模型,设备在加载到系统中就是已经初始化的状态了,因此可以考虑把这个删掉
290 /// @brief: 设备当前状态
291 #[derive(Debug, Clone, Copy, Eq, PartialEq)]
292 pub enum DeviceState {
293     NotInitialized = 0,
294     Initialized = 1,
295     UnDefined = 2,
296 }
297 
298 /// @brief: 设备错误类型
299 #[allow(dead_code)]
300 #[derive(Debug, Copy, Clone)]
301 pub enum DeviceError {
302     DriverExists,         // 设备已存在
303     DeviceExists,         // 驱动已存在
304     InitializeFailed,     // 初始化错误
305     NotInitialized,       // 未初始化的设备
306     NoDeviceForDriver,    // 没有合适的设备匹配驱动
307     NoDriverForDevice,    // 没有合适的驱动匹配设备
308     RegisterError,        // 注册失败
309     UnsupportedOperation, // 不支持的操作
310 }
311 
312 impl Into<SystemError> for DeviceError {
313     fn into(self) -> SystemError {
314         match self {
315             DeviceError::DriverExists => SystemError::EEXIST,
316             DeviceError::DeviceExists => SystemError::EEXIST,
317             DeviceError::InitializeFailed => SystemError::EIO,
318             DeviceError::NotInitialized => SystemError::ENODEV,
319             DeviceError::NoDeviceForDriver => SystemError::ENODEV,
320             DeviceError::NoDriverForDevice => SystemError::ENODEV,
321             DeviceError::RegisterError => SystemError::EIO,
322             DeviceError::UnsupportedOperation => SystemError::EIO,
323         }
324     }
325 }
326 
327 /// @brief: 将u32类型转换为设备状态类型
328 impl From<u32> for DeviceState {
329     fn from(state: u32) -> Self {
330         match state {
331             0 => DeviceState::NotInitialized,
332             1 => DeviceState::Initialized,
333             _ => todo!(),
334         }
335     }
336 }
337 
338 /// @brief: 将设备状态转换为u32类型
339 impl From<DeviceState> for u32 {
340     fn from(state: DeviceState) -> Self {
341         match state {
342             DeviceState::NotInitialized => 0,
343             DeviceState::Initialized => 1,
344             DeviceState::UnDefined => 2,
345         }
346     }
347 }
348 
349 #[derive(Debug)]
350 pub struct DeviceKObjType;
351 
352 impl KObjType for DeviceKObjType {
353     // https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/core.c#2307
354     fn release(&self, kobj: Arc<dyn KObject>) {
355         let dev = kobj.cast::<dyn Device>().unwrap();
356         /*
357          * Some platform devices are driven without driver attached
358          * and managed resources may have been acquired.  Make sure
359          * all resources are released.
360          *
361          * Drivers still can add resources into device after device
362          * is deleted but alive, so release devres here to avoid
363          * possible memory leak.
364          */
365 
366         // todo: 在引入devres之后再实现
367         // devres_release_all(kobj);
368         dev.release();
369     }
370 
371     fn attribute_groups(&self) -> Option<&'static [&'static dyn AttributeGroup]> {
372         None
373     }
374 
375     fn sysfs_ops(&self) -> Option<&dyn SysFSOps> {
376         Some(&DeviceSysFSOps)
377     }
378 }
379 
380 #[derive(Debug)]
381 pub(super) struct DeviceSysFSOps;
382 
383 impl SysFSOps for DeviceSysFSOps {
384     fn store(
385         &self,
386         kobj: Arc<dyn KObject>,
387         attr: &dyn Attribute,
388         buf: &[u8],
389     ) -> Result<usize, SystemError> {
390         return attr.store(kobj, buf);
391     }
392 
393     fn show(
394         &self,
395         kobj: Arc<dyn KObject>,
396         attr: &dyn Attribute,
397         buf: &mut [u8],
398     ) -> Result<usize, SystemError> {
399         return attr.show(kobj, buf);
400     }
401 }
402 
403 /// @brief Device管理器
404 #[derive(Debug)]
405 pub struct DeviceManager;
406 
407 impl DeviceManager {
408     /// @brief: 创建一个新的设备管理器
409     /// @parameter: None
410     /// @return: DeviceManager实体
411     #[inline]
412     const fn new() -> DeviceManager {
413         return Self;
414     }
415 
416     /// @brief: 添加设备
417     /// @parameter id_table: 总线标识符,用于唯一标识该总线
418     /// @parameter dev: 设备实例
419     /// @return: None
420     ///
421     /// https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/core.c#3398
422     ///
423     /// todo: 完善错误处理逻辑:如果添加失败,需要将之前添加的内容全部回滚
424     #[inline]
425     #[allow(dead_code)]
426     pub fn add_device(&self, device: Arc<dyn Device>) -> Result<(), SystemError> {
427         // todo: 引入class后,在这里处理与parent相关的逻辑
428 
429         KObjectManager::add_kobj(device.clone() as Arc<dyn KObject>, None).map_err(|e| {
430             kerror!("add device '{:?}' failed: {:?}", device.name(), e);
431             e
432         })?;
433 
434         self.device_platform_notify(&device);
435 
436         self.add_class_symlinks(&device)?;
437 
438         self.add_attrs(&device)?;
439 
440         bus_add_device(&device)?;
441 
442         if device.id_table().device_number().major() != 0 {
443             self.create_file(&device, &DeviceAttrDev)?;
444 
445             self.create_sys_dev_entry(&device)?;
446         }
447 
448         // todo: Notify clients of device addition.This call must come
449         //  after dpm_sysfs_add() and before kobject_uevent().
450         // 参考:https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/core.c#3491
451 
452         // todo: 发送uevent
453 
454         // probe drivers for a new device
455         bus_probe_device(&device);
456 
457         return Ok(());
458     }
459 
460     /// @brief: 卸载设备
461     /// @parameter id_table: 总线标识符,用于唯一标识该设备
462     /// @return: None
463     #[inline]
464     #[allow(dead_code)]
465     pub fn remove_device(&self, _id_table: &IdTable) {
466         todo!()
467     }
468 
469     /// 参考 https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/dd.c?fi=driver_attach#542
470     fn remove(&self, _dev: &Arc<dyn Device>) {
471         todo!("DeviceManager::remove")
472     }
473 
474     /// @brief: 获取设备
475     /// @parameter id_table: 设备标识符,用于唯一标识该设备
476     /// @return: 设备实例
477     #[inline]
478     #[allow(dead_code)]
479     pub fn find_device_by_idtable(&self, _id_table: &IdTable) -> Option<Arc<dyn Device>> {
480         todo!("find_device_by_idtable")
481     }
482 
483     fn device_platform_notify(&self, dev: &Arc<dyn Device>) {
484         acpi_device_notify(dev);
485         software_node_notify(dev);
486     }
487 
488     fn add_class_symlinks(&self, _dev: &Arc<dyn Device>) -> Result<(), SystemError> {
489         // todo: 引入class后,在这里处理与class相关的逻辑
490         // https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/core.c#3224
491 
492         return Ok(());
493     }
494 
495     /// 在sysfs中,为指定的设备创建属性文件
496     ///
497     /// ## 参数
498     ///
499     /// - `dev`: 设备
500     fn add_attrs(&self, dev: &Arc<dyn Device>) -> Result<(), SystemError> {
501         let kobj_type = dev.kobj_type();
502         if kobj_type.is_none() {
503             return Ok(());
504         }
505 
506         let kobj_type = kobj_type.unwrap();
507 
508         let attr_groups = kobj_type.attribute_groups();
509 
510         if attr_groups.is_none() {
511             return Ok(());
512         }
513 
514         self.add_groups(dev, attr_groups.unwrap())?;
515 
516         return Ok(());
517     }
518 
519     /// 在sysfs中,为指定的设备创建属性组,以及属性组中的属性文件
520     ///
521     /// ## 参数
522     ///
523     /// - `dev`: 设备
524     /// - `attr_groups`: 属性组
525     pub fn add_groups(
526         &self,
527         dev: &Arc<dyn Device>,
528         attr_groups: &'static [&dyn AttributeGroup],
529     ) -> Result<(), SystemError> {
530         let kobj = dev.clone() as Arc<dyn KObject>;
531         return sysfs_instance().create_groups(&kobj, attr_groups);
532     }
533 
534     /// 为设备在sysfs中创建属性文件
535     ///
536     /// ## 参数
537     ///
538     /// - `dev`: 设备
539     /// - `attr`: 属性
540     pub fn create_file(
541         &self,
542         dev: &Arc<dyn Device>,
543         attr: &'static dyn Attribute,
544     ) -> Result<(), SystemError> {
545         if unlikely(
546             attr.mode().contains(ModeType::S_IRUGO)
547                 && (!attr.support().contains(SysFSOpsSupport::SHOW)),
548         ) {
549             kwarn!(
550                 "Attribute '{}': read permission without 'show'",
551                 attr.name()
552             );
553         }
554         if unlikely(
555             attr.mode().contains(ModeType::S_IWUGO)
556                 && (!attr.support().contains(SysFSOpsSupport::STORE)),
557         ) {
558             kwarn!(
559                 "Attribute '{}': write permission without 'store'",
560                 attr.name()
561             );
562         }
563 
564         let kobj = dev.clone() as Arc<dyn KObject>;
565 
566         return sysfs_instance().create_file(&kobj, attr);
567     }
568 
569     /// 在/sys/dev下,或者设备所属的class下,为指定的设备创建链接
570     fn create_sys_dev_entry(&self, dev: &Arc<dyn Device>) -> Result<(), SystemError> {
571         let target_kobj = self.device_to_dev_kobj(dev);
572         let name = dev.id_table().name();
573         let current_kobj = dev.clone() as Arc<dyn KObject>;
574         return sysfs_instance().create_link(Some(&current_kobj), &target_kobj, name);
575     }
576 
577     /// Delete symlink for device in `/sys/dev` or `/sys/class/<class_name>`
578     #[allow(dead_code)]
579     fn remove_sys_dev_entry(&self, dev: &Arc<dyn Device>) {
580         let kobj = self.device_to_dev_kobj(dev);
581         let name = dev.id_table().name();
582         sysfs_instance().remove_link(&kobj, name);
583     }
584 
585     /// device_to_dev_kobj - select a /sys/dev/ directory for the device
586     ///
587     /// By default we select char/ for new entries.
588     ///
589     /// ## 参数
590     ///
591     /// - `dev`: 设备
592     fn device_to_dev_kobj(&self, _dev: &Arc<dyn Device>) -> Arc<dyn KObject> {
593         // todo: 处理class的逻辑
594         let kobj = sys_dev_char_kset().as_kobject();
595         return kobj;
596     }
597 
598     /// 参考 https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/core.c?fi=device_links_force_bind#1226
599     pub fn device_links_force_bind(&self, _dev: &Arc<dyn Device>) {
600         todo!("device_links_force_bind")
601     }
602 
603     /// 把device对象的一些结构进行默认初始化
604     ///
605     /// 参考 https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/core.c?fi=device_initialize#2976
606     pub fn device_default_initialize(&self, dev: &Arc<dyn Device>) {
607         dev.set_kset(Some(sys_devices_kset()));
608         return;
609     }
610 
611     /// 参考 https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/dd.c?r=&mo=29885&fi=1100#1100
612     pub fn device_driver_attach(
613         &self,
614         _driver: &Arc<dyn Driver>,
615         _dev: &Arc<dyn Device>,
616     ) -> Result<(), SystemError> {
617         todo!("device_driver_attach")
618     }
619 
620     /// 参考 https://opengrok.ringotek.cn/xref/linux-6.1.9/drivers/base/dd.c?r=&mo=35401&fi=1313#1313
621     pub fn device_driver_detach(&self, _dev: &Arc<dyn Device>) {
622         todo!("device_driver_detach")
623     }
624 }
625 
626 /// @brief: 设备注册
627 /// @parameter: name: 设备名
628 /// @return: 操作成功,返回(),操作失败,返回错误码
629 pub fn device_register<T: Device>(device: Arc<T>) -> Result<(), SystemError> {
630     return device_manager().add_device(device);
631 }
632 
633 /// @brief: 设备卸载
634 /// @parameter: name: 设备名
635 /// @return: 操作成功,返回(),操作失败,返回错误码
636 pub fn device_unregister<T: Device>(_device: Arc<T>) {
637     // DEVICE_MANAGER.add_device(device.id_table(), device.clone());
638     // match sys_device_unregister(&device.id_table().name()) {
639     //     Ok(_) => {
640     //         device.set_inode(None);
641     //         return Ok(());
642     //     }
643     //     Err(_) => Err(DeviceError::RegisterError),
644     // }
645     todo!("device_unregister")
646 }
647 
648 /// 设备文件夹下的`dev`文件的属性
649 #[derive(Debug, Clone, Copy)]
650 pub struct DeviceAttrDev;
651 
652 impl Attribute for DeviceAttrDev {
653     fn mode(&self) -> ModeType {
654         // 0o444
655         return ModeType::S_IRUGO;
656     }
657 
658     fn name(&self) -> &str {
659         "dev"
660     }
661 
662     fn show(&self, kobj: Arc<dyn KObject>, buf: &mut [u8]) -> Result<usize, SystemError> {
663         let dev = kobj.cast::<dyn Device>().map_err(|kobj| {
664             kerror!(
665                 "Intertrait casting not implemented for kobj: {}",
666                 kobj.name()
667             );
668             SystemError::EOPNOTSUPP_OR_ENOTSUP
669         })?;
670 
671         let device_number = dev.id_table().device_number();
672         let s = format!("{}:{}\n", device_number.major(), device_number.minor());
673 
674         return sysfs_emit_str(buf, &s);
675     }
676 
677     fn support(&self) -> SysFSOpsSupport {
678         SysFSOpsSupport::SHOW
679     }
680 }
681 
682 /// 设备匹配器
683 ///
684 /// 用于匹配设备是否符合某个条件
685 ///
686 /// ## 参数
687 ///
688 /// - `T` - 匹配器的数据类型
689 /// - `data` - 匹配器的数据
690 pub trait DeviceMatcher<T>: Debug {
691     fn match_device(&self, device: &Arc<dyn Device>, data: T) -> bool;
692 }
693 
694 /// 用于根据名称匹配设备的匹配器
695 #[derive(Debug)]
696 pub struct DeviceMatchName;
697 
698 impl DeviceMatcher<&str> for DeviceMatchName {
699     #[inline]
700     fn match_device(&self, device: &Arc<dyn Device>, data: &str) -> bool {
701         return device.name() == data;
702     }
703 }
704