kernel/device/
mod.rs

1//! Device module.
2//! 
3//! This module provides a framework for managing devices in the kernel.
4//! It includes device information and driver management,
5//! as well as platform-specific device handling.
6
7
8pub mod manager;
9pub mod fdt;
10pub mod platform;
11pub mod block;
12pub mod char;
13
14extern crate alloc;
15use core::any::Any;
16
17use alloc::vec::Vec;
18
19pub trait DeviceInfo {
20    fn name(&self) -> &'static str;
21    fn id(&self) -> usize;
22    fn compatible(&self) -> Vec<&'static str>;
23    fn as_any(&self) -> &dyn Any;
24}
25
26/// Device driver trait.
27/// 
28/// This trait defines the interface for device drivers in the kernel.
29/// It includes methods for getting the driver's name,
30/// matching the driver to devices, and handling device probing and removal.
31pub trait DeviceDriver {
32    fn name(&self) -> &'static str;
33    fn match_table(&self) -> Vec<&'static str>;
34    fn probe(&self, device: &dyn DeviceInfo) -> Result<(), &'static str>;
35    fn remove(&self, device: &dyn DeviceInfo) -> Result<(), &'static str>;
36}
37
38/// Device type enumeration.
39/// 
40/// This enum defines the types of devices that can be managed by the kernel.
41/// It includes block devices, character devices, network devices,
42/// and generic devices.
43/// 
44#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
45pub enum DeviceType {
46    Block,
47    Char,
48    Network,
49    Generic,
50    #[cfg(test)]
51    NonExistent,
52}
53
54/// Device trait.
55/// 
56/// This trait defines the interface for devices in the kernel.
57/// 
58pub trait Device: Send + Sync {
59    fn device_type(&self) -> DeviceType;
60    fn name(&self) -> &'static str;
61    fn id(&self) -> usize;
62    fn as_any(&self) -> &dyn Any;
63    fn as_any_mut(&mut self) -> &mut dyn Any;
64    
65    /// Cast to CharDevice if this device is a character device
66    fn as_char_device(&mut self) -> Option<&mut dyn char::CharDevice> {
67        None
68    }
69    
70    /// Cast to BlockDevice if this device is a block device  
71    fn as_block_device(&mut self) -> Option<&mut dyn block::BlockDevice> {
72        None
73    }
74}
75
76pub struct GenericDevice {
77    device_type: DeviceType,
78    name: &'static str,
79    id: usize,
80}
81
82impl GenericDevice {
83    pub fn new(name: &'static str, id: usize) -> Self {
84        Self { device_type: DeviceType::Generic, name, id }
85    }
86}
87
88impl Device for GenericDevice {
89    fn device_type(&self) -> DeviceType {
90        self.device_type
91    }
92
93    fn name(&self) -> &'static str {
94        self.name
95    }
96
97    fn id(&self) -> usize {
98        self.id
99    }
100
101    fn as_any(&self) -> &dyn Any {
102        self
103    }
104    
105    fn as_any_mut(&mut self) -> &mut dyn Any {
106        self
107    }
108}