os/device/
mod.rs

1//! 设备抽象层,提供块设备接口、内存磁盘实现和网络设备接口
2
3#[macro_use]
4pub mod bus;
5pub mod block;
6pub mod console;
7pub mod gpu;
8pub mod input;
9pub mod irq;
10pub mod net;
11pub mod rtc;
12pub mod serial;
13pub mod virtio_hal;
14
15pub mod device_tree;
16
17use alloc::sync::Arc;
18pub use block::ram_disk::RamDisk;
19use spin::RwLock;
20
21use crate::device::rtc::RtcDriver;
22
23use crate::device::serial::SerialDriver;
24use crate::device::{block::BlockDriver, net::net_device::NetDevice};
25
26use alloc::{string::String, vec::Vec};
27use lazy_static::lazy_static;
28
29/// 设备类型枚举
30#[derive(Debug, Eq, PartialEq)]
31pub enum DeviceType {
32    /// 网络设备
33    Net,
34    /// 图形处理单元设备
35    Gpu,
36    /// 输入设备
37    Input,
38    /// 块设备
39    Block,
40    /// 实时时钟设备
41    Rtc,
42    /// 串行设备
43    Serial,
44    /// 中断控制器
45    Intc,
46}
47
48/// 设备驱动程序特征
49pub trait Driver: Send + Sync {
50    // 如果中断属于此驱动程序,则处理它并返回 true
51    // 否则返回 false
52    // 中断号在可用时提供
53    // 如果中断号不匹配,驱动程序应跳过处理。
54    fn try_handle_interrupt(&self, irq: Option<usize>) -> bool;
55
56    // 返回对应的设备类型,请参阅 DeviceType
57    fn device_type(&self) -> DeviceType;
58
59    // 获取此设备的唯一标识符
60    // 每个实例的标识符应该不同
61    fn get_id(&self) -> String;
62
63    /// 将驱动程序转换为网络驱动程序(如果适用)
64    fn as_net(&self) -> Option<&dyn NetDevice> {
65        None
66    }
67
68    /// 将驱动程序转换为网络驱动程序 Arc(如果适用)
69    fn as_net_arc(self: Arc<Self>) -> Option<Arc<dyn NetDevice>> {
70        None
71    }
72
73    /// 将驱动程序转换为块设备驱动程序(如果适用)
74    fn as_block(&self) -> Option<&dyn BlockDriver> {
75        None
76    }
77
78    /// 将驱动程序转换为块设备驱动程序 Arc(如果适用)
79    fn as_block_arc(self: Arc<Self>) -> Option<Arc<dyn BlockDriver>> {
80        None
81    }
82
83    /// 将驱动程序转换为实时时钟驱动程序(如果适用)
84    fn as_rtc(&self) -> Option<&dyn RtcDriver> {
85        None
86    }
87
88    /// 将驱动程序转换为实时时钟驱动程序 Arc(如果适用)
89    fn as_rtc_arc(self: Arc<Self>) -> Option<Arc<dyn RtcDriver>> {
90        None
91    }
92
93    /// 将驱动程序转换为串口驱动程序(如果适用)
94    fn as_serial(&self) -> Option<&dyn serial::SerialDriver> {
95        None
96    }
97}
98
99lazy_static! {
100    // NOTE: RwLock 只在初始化阶段有写操作,运行时均为读操作
101    pub static ref DRIVERS: RwLock<Vec<Arc<dyn Driver>>> = RwLock::new(Vec::new());
102    pub static ref BLK_DRIVERS: RwLock<Vec<Arc<dyn BlockDriver>>> = RwLock::new(Vec::new());
103    pub static ref RTC_DRIVERS: RwLock<Vec<Arc<dyn RtcDriver>>> = RwLock::new(Vec::new());
104    pub static ref SERIAL_DRIVERS: RwLock<Vec<Arc<dyn SerialDriver>>> = RwLock::new(Vec::new());
105    pub static ref IRQ_MANAGER: RwLock<irq::IrqManager> = RwLock::new(irq::IrqManager::new(true));
106}
107
108lazy_static! {
109    // 内核命令行参数
110    // 存储从设备树中提取的 bootargs 属性
111    pub static ref CMDLINE: RwLock<String> = RwLock::new(String::new());
112}
113
114/// 注册设备驱动
115pub fn register_driver(driver: Arc<dyn Driver>) {
116    DRIVERS.write().push(driver);
117}