axdriver/
lib.rs

1//! [ArceOS](https://github.com/arceos-org/arceos) device drivers.
2//!
3//! # Usage
4//!
5//! All detected devices are composed into a large struct [`AllDevices`]
6//! and returned by the [`init_drivers`] function. The upperlayer subsystems
7//! (e.g., the network stack) may unpack the struct to get the specified device
8//! driver they want.
9//!
10//! For each device category (i.e., net, block, display, etc.), an unified type
11//! is used to represent all devices in that category. Currently, there are 3
12//! categories: [`AxNetDevice`], [`AxBlockDevice`], and [`AxDisplayDevice`].
13//!
14//! # Concepts
15//!
16//! This crate supports two device models depending on the `dyn` feature:
17//!
18//! - **Static**: The type of all devices is static, it is determined at compile
19//!   time by corresponding cargo features. For example, [`AxNetDevice`] will be
20//!   an alias of [`VirtioNetDev`] if the `virtio-net` feature is enabled. This
21//!   model provides the best performance as it avoids dynamic dispatch. But on
22//!   limitation, only one device instance is supported for each device category.
23//! - **Dynamic**: All device instance is using [trait objects] and wrapped in a
24//!   `Box<dyn Trait>`. For example, [`AxNetDevice`] will be [`Box<dyn NetDriverOps>`].
25//!   When call a method provided by the device, it uses [dynamic dispatch][dyn]
26//!   that may introduce a little overhead. But on the other hand, it is more
27//!   flexible, multiple instances of each device category are supported.
28//!
29//! # Supported Devices
30//!
31//! | Device Category | Cargo Feature | Description |
32//! |-|-|-|
33//! | Block | `ramdisk` | A RAM disk that stores data in a vector |
34//! | Block | `virtio-blk` | VirtIO block device |
35//! | Network | `virtio-net` | VirtIO network device |
36//! | Display | `virtio-gpu` | VirtIO graphics device |
37//!
38//! # Other Cargo Features
39//!
40//! - `dyn`: use the dynamic device model (see above).
41//! - `bus-mmio`: use device tree to probe all MMIO devices.
42//! - `bus-pci`: use PCI bus to probe all PCI devices. This feature is
43//!   enabled by default.
44//! - `virtio`: use VirtIO devices. This is enabled if any of `virtio-blk`,
45//!   `virtio-net` or `virtio-gpu` is enabled.
46//! - `net`: use network devices. This is enabled if any feature of network
47//!   devices is selected. If this feature is enabled without any network device
48//!   features, a dummy struct is used for [`AxNetDevice`].
49//! - `block`: use block storage devices. Similar to the `net` feature.
50//! - `display`: use graphics display devices. Similar to the `net` feature.
51//!
52//! [`VirtioNetDev`]: axdriver_virtio::VirtIoNetDev
53//! [`Box<dyn NetDriverOps>`]: axdriver_net::NetDriverOps
54//! [trait objects]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html
55//! [dyn]: https://doc.rust-lang.org/std/keyword.dyn.html
56
57#![no_std]
58#![feature(doc_auto_cfg)]
59#![feature(associated_type_defaults)]
60
61#[macro_use]
62extern crate log;
63
64#[cfg(feature = "dyn")]
65extern crate alloc;
66
67#[macro_use]
68mod macros;
69
70mod bus;
71mod drivers;
72mod dummy;
73mod structs;
74
75#[cfg(feature = "virtio")]
76mod virtio;
77
78#[cfg(feature = "ixgbe")]
79mod ixgbe;
80
81pub mod prelude;
82
83#[allow(unused_imports)]
84use self::prelude::*;
85pub use self::structs::{AxDeviceContainer, AxDeviceEnum};
86
87#[cfg(feature = "block")]
88pub use self::structs::AxBlockDevice;
89#[cfg(feature = "display")]
90pub use self::structs::AxDisplayDevice;
91#[cfg(feature = "net")]
92pub use self::structs::AxNetDevice;
93
94/// A structure that contains all device drivers, organized by their category.
95#[derive(Default)]
96pub struct AllDevices {
97    /// All network device drivers.
98    #[cfg(feature = "net")]
99    pub net: AxDeviceContainer<AxNetDevice>,
100    /// All block device drivers.
101    #[cfg(feature = "block")]
102    pub block: AxDeviceContainer<AxBlockDevice>,
103    /// All graphics device drivers.
104    #[cfg(feature = "display")]
105    pub display: AxDeviceContainer<AxDisplayDevice>,
106}
107
108impl AllDevices {
109    /// Returns the device model used, either `dyn` or `static`.
110    ///
111    /// See the [crate-level documentation](crate) for more details.
112    pub const fn device_model() -> &'static str {
113        if cfg!(feature = "dyn") {
114            "dyn"
115        } else {
116            "static"
117        }
118    }
119
120    /// Probes all supported devices.
121    fn probe(&mut self) {
122        for_each_drivers!(type Driver, {
123            if let Some(dev) = Driver::probe_global() {
124                info!(
125                    "registered a new {:?} device: {:?}",
126                    dev.device_type(),
127                    dev.device_name(),
128                );
129                self.add_device(dev);
130            }
131        });
132
133        self.probe_bus_devices();
134    }
135
136    /// Adds one device into the corresponding container, according to its device category.
137    #[allow(dead_code)]
138    fn add_device(&mut self, dev: AxDeviceEnum) {
139        match dev {
140            #[cfg(feature = "net")]
141            AxDeviceEnum::Net(dev) => self.net.push(dev),
142            #[cfg(feature = "block")]
143            AxDeviceEnum::Block(dev) => self.block.push(dev),
144            #[cfg(feature = "display")]
145            AxDeviceEnum::Display(dev) => self.display.push(dev),
146        }
147    }
148}
149
150/// Probes and initializes all device drivers, returns the [`AllDevices`] struct.
151pub fn init_drivers() -> AllDevices {
152    info!("Initialize device drivers...");
153    info!("  device model: {}", AllDevices::device_model());
154
155    let mut all_devs = AllDevices::default();
156    all_devs.probe();
157
158    #[cfg(feature = "net")]
159    {
160        debug!("number of NICs: {}", all_devs.net.len());
161        for (i, dev) in all_devs.net.iter().enumerate() {
162            assert_eq!(dev.device_type(), DeviceType::Net);
163            debug!("  NIC {}: {:?}", i, dev.device_name());
164        }
165    }
166    #[cfg(feature = "block")]
167    {
168        debug!("number of block devices: {}", all_devs.block.len());
169        for (i, dev) in all_devs.block.iter().enumerate() {
170            assert_eq!(dev.device_type(), DeviceType::Block);
171            debug!("  block device {}: {:?}", i, dev.device_name());
172        }
173    }
174    #[cfg(feature = "display")]
175    {
176        debug!("number of graphics devices: {}", all_devs.display.len());
177        for (i, dev) in all_devs.display.iter().enumerate() {
178            assert_eq!(dev.device_type(), DeviceType::Display);
179            debug!("  graphics device {}: {:?}", i, dev.device_name());
180        }
181    }
182
183    all_devs
184}