xref: /DragonOS/kernel/src/driver/base/device/mod.rs (revision a30434f5201ca4c60b9515c8c23444fea3b5a8c6)
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 pub trait KObject: Any + Send + Sync + Debug {}
24 
25 /// @brief: 设备号实例
26 #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
27 pub struct DeviceNumber(usize);
28 
29 impl Default for DeviceNumber {
30     fn default() -> Self {
31         DeviceNumber(0)
32     }
33 }
34 
35 impl From<usize> for DeviceNumber {
36     fn from(dev_t: usize) -> Self {
37         DeviceNumber(dev_t)
38     }
39 }
40 
41 impl Into<usize> for DeviceNumber {
42     fn into(self) -> usize {
43         self.0
44     }
45 }
46 
47 impl DeviceNumber {
48     /// @brief: 设备号创建
49     /// @parameter: dev_t: 设备号
50     /// @return: 设备号实例
51     pub fn new(dev_t: usize) -> DeviceNumber {
52         Self(dev_t)
53     }
54 
55     /// @brief: 获取主设备号
56     /// @parameter: none
57     /// @return: 主设备号
58     pub fn major(&self) -> usize {
59         (self.0 >> 20) & 0xfff
60     }
61 
62     /// @brief: 获取次设备号
63     /// @parameter: none
64     /// @return: 次设备号
65     pub fn minor(&self) -> usize {
66         self.0 & 0xfffff
67     }
68 }
69 
70 /// @brief: 根据主次设备号创建设备号实例
71 /// @parameter: major: 主设备号
72 ///             minor: 次设备号
73 /// @return: 设备号实例
74 pub fn mkdev(major: usize, minor: usize) -> DeviceNumber {
75     DeviceNumber(((major & 0xfff) << 20) | (minor & 0xfffff))
76 }
77 
78 /// @brief: 设备类型
79 #[allow(dead_code)]
80 #[derive(Debug, Eq, PartialEq)]
81 pub enum DeviceType {
82     Bus,
83     Net,
84     Gpu,
85     Input,
86     Block,
87     Rtc,
88     Serial,
89     Intc,
90     PlatformDev,
91 }
92 
93 /// @brief: 设备标识符类型
94 #[derive(Debug, Clone, Hash, PartialOrd, PartialEq, Ord, Eq)]
95 pub struct IdTable(&'static str, u32);
96 
97 /// @brief: 设备标识符操作方法集
98 impl IdTable {
99     /// @brief: 创建一个新的设备标识符
100     /// @parameter name: 设备名
101     /// @parameter id: 设备id
102     /// @return: 设备标识符
103     pub fn new(name: &'static str, id: u32) -> IdTable {
104         Self(name, id)
105     }
106 
107     /// @brief: 将设备标识符转换成name
108     /// @parameter None
109     /// @return: 设备名
110     pub fn to_name(&self) -> String {
111         return format!("{}:{}", self.0, self.1);
112     }
113 }
114 
115 /// @brief: 设备当前状态
116 #[derive(Debug, Clone, Copy)]
117 pub enum DeviceState {
118     NotInitialized = 0,
119     Initialized = 1,
120     UnDefined = 2,
121 }
122 
123 /// @brief: 设备错误类型
124 #[derive(Debug, Copy, Clone)]
125 pub enum DeviceError {
126     DriverExists,      // 设备已存在
127     DeviceExists,      // 驱动已存在
128     InitializeFailed,  // 初始化错误
129     NoDeviceForDriver, // 没有合适的设备匹配驱动
130     NoDriverForDevice, // 没有合适的驱动匹配设备
131     RegisterError,     // 注册失败
132 }
133 
134 impl Into<SystemError> for DeviceError {
135     fn into(self) -> SystemError {
136         match self {
137             DeviceError::DriverExists => SystemError::EEXIST,
138             DeviceError::DeviceExists => SystemError::EEXIST,
139             DeviceError::InitializeFailed => SystemError::EIO,
140             DeviceError::NoDeviceForDriver => SystemError::ENODEV,
141             DeviceError::NoDriverForDevice => SystemError::ENODEV,
142             DeviceError::RegisterError => SystemError::EIO,
143         }
144     }
145 }
146 
147 /// @brief: 将u32类型转换为设备状态类型
148 impl From<u32> for DeviceState {
149     fn from(state: u32) -> Self {
150         match state {
151             0 => DeviceState::NotInitialized,
152             1 => DeviceState::Initialized,
153             _ => todo!(),
154         }
155     }
156 }
157 
158 /// @brief: 将设备状态转换为u32类型
159 impl From<DeviceState> for u32 {
160     fn from(state: DeviceState) -> Self {
161         match state {
162             DeviceState::NotInitialized => 0,
163             DeviceState::Initialized => 1,
164             DeviceState::UnDefined => 2,
165         }
166     }
167 }
168 
169 /// @brief: 所有设备都应该实现该trait
170 pub trait Device: KObject {
171     /// @brief: 本函数用于实现动态转换
172     /// @parameter: None
173     /// @return: any
174     fn as_any_ref(&'static self) -> &'static dyn core::any::Any;
175 
176     /// @brief: 获取设备类型
177     /// @parameter: None
178     /// @return: 实现该trait的设备所属类型
179     fn dev_type(&self) -> DeviceType;
180 
181     /// @brief: 获取设备标识
182     /// @parameter: None
183     /// @return: 该设备唯一标识
184     fn id_table(&self) -> IdTable;
185 
186     /// @brief: 设置sysfs info
187     /// @parameter: None
188     /// @return: 该设备唯一标识
189     fn set_sys_info(&self, sys_info: Option<Arc<dyn IndexNode>>);
190 
191     /// @brief: 获取设备的sys information
192     /// @parameter id_table: 设备标识符,用于唯一标识该设备
193     /// @return: 设备实例
194     fn sys_info(&self) -> Option<Arc<dyn IndexNode>>;
195 }
196 
197 /// @brief Device管理器(锁)
198 #[derive(Debug)]
199 pub struct LockedDeviceManager(SpinLock<DeviceManager>);
200 
201 impl LockedDeviceManager {
202     fn new() -> LockedDeviceManager {
203         LockedDeviceManager(SpinLock::new(DeviceManager::new()))
204     }
205 
206     /// @brief: 添加设备
207     /// @parameter id_table: 总线标识符,用于唯一标识该总线
208     /// @parameter dev: 设备实例
209     /// @return: None
210     #[inline]
211     #[allow(dead_code)]
212     pub fn add_device(&self, id_table: IdTable, dev: Arc<dyn Device>) {
213         let mut device_manager = self.0.lock();
214         device_manager.devices.insert(id_table, dev);
215     }
216 
217     /// @brief: 卸载设备
218     /// @parameter id_table: 总线标识符,用于唯一标识该设备
219     /// @return: None
220     #[inline]
221     #[allow(dead_code)]
222     pub fn remove_device(&self, id_table: &IdTable) {
223         let mut device_manager = self.0.lock();
224         device_manager.devices.remove(id_table);
225     }
226 
227     /// @brief: 获取设备
228     /// @parameter id_table: 设备标识符,用于唯一标识该设备
229     /// @return: 设备实例
230     #[inline]
231     #[allow(dead_code)]
232     pub fn get_device(&self, id_table: &IdTable) -> Option<Arc<dyn Device>> {
233         let device_manager = self.0.lock();
234         device_manager.devices.get(id_table).cloned()
235     }
236 
237     /// @brief: 获取设备管理器的sys information
238     /// @parameter id_table: 设备标识符,用于唯一标识该设备
239     /// @return: 设备实例
240     #[inline]
241     #[allow(dead_code)]
242     fn sys_info(&self) -> Option<Arc<dyn IndexNode>> {
243         return self.0.lock().sys_info.clone();
244     }
245 }
246 
247 /// @brief Device管理器
248 #[derive(Debug, Clone)]
249 pub struct DeviceManager {
250     devices: BTreeMap<IdTable, Arc<dyn Device>>, // 所有设备
251     sys_info: Option<Arc<dyn IndexNode>>,        // sys information
252 }
253 
254 impl DeviceManager {
255     /// @brief: 创建一个新的设备管理器
256     /// @parameter: None
257     /// @return: DeviceManager实体
258     #[inline]
259     fn new() -> DeviceManager {
260         DeviceManager {
261             devices: BTreeMap::new(),
262             sys_info: Some(SYS_DEVICES_INODE()),
263         }
264     }
265 }
266 
267 /// @brief: 设备注册
268 /// @parameter: name: 设备名
269 /// @return: 操作成功,返回(),操作失败,返回错误码
270 pub fn device_register<T: Device>(device: Arc<T>) -> Result<(), DeviceError> {
271     DEVICE_MANAGER.add_device(device.id_table(), device.clone());
272     match sys_device_register(&device.id_table().to_name()) {
273         Ok(sys_info) => {
274             device.set_sys_info(Some(sys_info));
275             return Ok(());
276         }
277         Err(_) => Err(DeviceError::RegisterError),
278     }
279 }
280 
281 /// @brief: 设备卸载
282 /// @parameter: name: 设备名
283 /// @return: 操作成功,返回(),操作失败,返回错误码
284 pub fn device_unregister<T: Device>(device: Arc<T>) -> Result<(), DeviceError> {
285     DEVICE_MANAGER.add_device(device.id_table(), device.clone());
286     match sys_device_unregister(&device.id_table().to_name()) {
287         Ok(_) => {
288             device.set_sys_info(None);
289             return Ok(());
290         }
291         Err(_) => Err(DeviceError::RegisterError),
292     }
293 }
294