xref: /DragonOS/kernel/src/driver/base/device/mod.rs (revision ab5c8ca46db8e7d4793a9791292122b0b9684274)
1 use alloc::{collections::BTreeMap, string::String, sync::Arc};
2 
3 use crate::{
4     filesystem::{
5         sysfs::{
6             devices::{sys_device_register, sys_device_unregister},
7             SYS_DEVICES_INODE,
8         },
9         vfs::IndexNode,
10     },
11     libs::spinlock::SpinLock,
12     syscall::SystemError,
13 };
14 use core::{any::Any, fmt::Debug};
15 
16 pub mod bus;
17 pub mod driver;
18 
19 lazy_static! {
20     pub static ref DEVICE_MANAGER: Arc<LockedDeviceManager> = Arc::new(LockedDeviceManager::new());
21 }
22 
23 /// @brief: 设备类型
24 #[allow(dead_code)]
25 #[derive(Debug, Eq, PartialEq)]
26 pub enum DeviceType {
27     Bus,
28     Net,
29     Gpu,
30     Input,
31     Block,
32     Rtc,
33     Serial,
34     Intc,
35     PlatformDev,
36 }
37 
38 /// @brief: 设备标识符类型
39 #[derive(Debug, Clone, Hash, PartialOrd, PartialEq, Ord, Eq)]
40 pub struct IdTable(&'static str, u32);
41 
42 /// @brief: 设备标识符操作方法集
43 impl IdTable {
44     /// @brief: 创建一个新的设备标识符
45     /// @parameter name: 设备名
46     /// @parameter id: 设备id
47     /// @return: 设备标识符
48     pub fn new(name: &'static str, id: u32) -> IdTable {
49         Self(name, id)
50     }
51 
52     /// @brief: 将设备标识符转换成name
53     /// @parameter None
54     /// @return: 设备名
55     pub fn to_name(&self) -> String {
56         return format!("{}:{}", self.0, self.1);
57     }
58 }
59 
60 /// @brief: 设备当前状态
61 #[derive(Debug, Clone, Copy)]
62 pub enum DeviceState {
63     NotInitialized = 0,
64     Initialized = 1,
65     UnDefined = 2,
66 }
67 
68 /// @brief: 设备错误类型
69 #[derive(Debug, Copy, Clone)]
70 pub enum DeviceError {
71     DriverExists,      // 设备已存在
72     DeviceExists,      // 驱动已存在
73     InitializeFailed,  // 初始化错误
74     NoDeviceForDriver, // 没有合适的设备匹配驱动
75     NoDriverForDevice, // 没有合适的驱动匹配设备
76     RegisterError,     // 注册失败
77 }
78 
79 impl Into<SystemError> for DeviceError {
80     fn into(self) -> SystemError {
81         match self {
82             DeviceError::DriverExists => SystemError::EEXIST,
83             DeviceError::DeviceExists => SystemError::EEXIST,
84             DeviceError::InitializeFailed => SystemError::EIO,
85             DeviceError::NoDeviceForDriver => SystemError::ENODEV,
86             DeviceError::NoDriverForDevice => SystemError::ENODEV,
87             DeviceError::RegisterError => SystemError::EIO,
88         }
89     }
90 }
91 
92 /// @brief: 将u32类型转换为设备状态类型
93 impl From<u32> for DeviceState {
94     fn from(state: u32) -> Self {
95         match state {
96             0 => DeviceState::NotInitialized,
97             1 => DeviceState::Initialized,
98             _ => todo!(),
99         }
100     }
101 }
102 
103 /// @brief: 将设备状态转换为u32类型
104 impl From<DeviceState> for u32 {
105     fn from(state: DeviceState) -> Self {
106         match state {
107             DeviceState::NotInitialized => 0,
108             DeviceState::Initialized => 1,
109             DeviceState::UnDefined => 2,
110         }
111     }
112 }
113 
114 /// @brief: 所有设备都应该实现该trait
115 pub trait Device: Any + Send + Sync + Debug {
116     /// @brief: 获取设备类型
117     /// @parameter: None
118     /// @return: 实现该trait的设备所属类型
119     fn get_type(&self) -> DeviceType;
120 
121     /// @brief: 获取设备标识
122     /// @parameter: None
123     /// @return: 该设备唯一标识
124     fn get_id_table(&self) -> IdTable;
125 
126     /// @brief: 设置sysfs info
127     /// @parameter: None
128     /// @return: 该设备唯一标识
129     fn set_sys_info(&self, sys_info: Option<Arc<dyn IndexNode>>);
130 
131     /// @brief: 获取设备的sys information
132     /// @parameter id_table: 设备标识符,用于唯一标识该设备
133     /// @return: 设备实例
134     fn sys_info(&self) -> Option<Arc<dyn IndexNode>>;
135 }
136 
137 /// @brief Device管理器(锁)
138 #[derive(Debug)]
139 pub struct LockedDeviceManager(SpinLock<DeviceManager>);
140 
141 impl LockedDeviceManager {
142     fn new() -> LockedDeviceManager {
143         LockedDeviceManager(SpinLock::new(DeviceManager::new()))
144     }
145 
146     /// @brief: 添加设备
147     /// @parameter id_table: 总线标识符,用于唯一标识该总线
148     /// @parameter dev: 设备实例
149     /// @return: None
150     #[inline]
151     #[allow(dead_code)]
152     pub fn add_device(&self, id_table: IdTable, dev: Arc<dyn Device>) {
153         let mut device_manager = self.0.lock();
154         device_manager.devices.insert(id_table, dev);
155     }
156 
157     /// @brief: 卸载设备
158     /// @parameter id_table: 总线标识符,用于唯一标识该设备
159     /// @return: None
160     #[inline]
161     #[allow(dead_code)]
162     pub fn remove_device(&self, id_table: &IdTable) {
163         let mut device_manager = self.0.lock();
164         device_manager.devices.remove(id_table);
165     }
166 
167     /// @brief: 获取设备
168     /// @parameter id_table: 设备标识符,用于唯一标识该设备
169     /// @return: 设备实例
170     #[inline]
171     #[allow(dead_code)]
172     pub fn get_device(&self, id_table: &IdTable) -> Option<Arc<dyn Device>> {
173         let device_manager = self.0.lock();
174         device_manager.devices.get(id_table).cloned()
175     }
176 
177     /// @brief: 获取设备管理器的sys information
178     /// @parameter id_table: 设备标识符,用于唯一标识该设备
179     /// @return: 设备实例
180     #[inline]
181     #[allow(dead_code)]
182     fn sys_info(&self) -> Option<Arc<dyn IndexNode>> {
183         return self.0.lock().sys_info.clone();
184     }
185 }
186 
187 /// @brief Device管理器
188 #[derive(Debug, Clone)]
189 pub struct DeviceManager {
190     devices: BTreeMap<IdTable, Arc<dyn Device>>, // 所有设备
191     sys_info: Option<Arc<dyn IndexNode>>,        // sys information
192 }
193 
194 impl DeviceManager {
195     /// @brief: 创建一个新的设备管理器
196     /// @parameter: None
197     /// @return: DeviceManager实体
198     #[inline]
199     fn new() -> DeviceManager {
200         DeviceManager {
201             devices: BTreeMap::new(),
202             sys_info: Some(SYS_DEVICES_INODE()),
203         }
204     }
205 }
206 
207 /// @brief: 设备注册
208 /// @parameter: name: 设备名
209 /// @return: 操作成功,返回(),操作失败,返回错误码
210 pub fn device_register<T: Device>(device: Arc<T>) -> Result<(), DeviceError> {
211     DEVICE_MANAGER.add_device(device.get_id_table(), device.clone());
212     match sys_device_register(&device.get_id_table().to_name()) {
213         Ok(sys_info) => {
214             device.set_sys_info(Some(sys_info));
215             return Ok(());
216         }
217         Err(_) => Err(DeviceError::RegisterError),
218     }
219 }
220 
221 /// @brief: 设备卸载
222 /// @parameter: name: 设备名
223 /// @return: 操作成功,返回(),操作失败,返回错误码
224 pub fn device_unregister<T: Device>(device: Arc<T>) -> Result<(), DeviceError> {
225     DEVICE_MANAGER.add_device(device.get_id_table(), device.clone());
226     match sys_device_unregister(&device.get_id_table().to_name()) {
227         Ok(_) => {
228             device.set_sys_info(None);
229             return Ok(());
230         }
231         Err(_) => Err(DeviceError::RegisterError),
232     }
233 }
234