Refactor drivers

This commit is contained in:
Yuke Peng 2023-11-20 20:37:51 +08:00 committed by Tate, Hongliang Tian
parent d809eca81d
commit edd808bd3d
12 changed files with 87 additions and 67 deletions

View File

@ -53,7 +53,9 @@ fn print_stack_trace() {
let fde_initial_address = _Unwind_FindEnclosingFunction(pc as *mut c_void) as usize; let fde_initial_address = _Unwind_FindEnclosingFunction(pc as *mut c_void) as usize;
early_println!( early_println!(
"{:4}: fn {:#18x} - pc {:#18x} / registers:", "{:4}: fn {:#18x} - pc {:#18x} / registers:",
data.counter, fde_initial_address, pc, data.counter,
fde_initial_address,
pc,
); );
// Print the first 8 general registers for any architecture. The register number follows // Print the first 8 general registers for any architecture. The register number follows
// the DWARF standard. // the DWARF standard.

View File

@ -26,20 +26,30 @@ pub trait BlockDevice: Send + Sync + Any + Debug {
} }
pub fn register_device(name: String, device: Arc<dyn BlockDevice>) { pub fn register_device(name: String, device: Arc<dyn BlockDevice>) {
COMPONENT.get().unwrap().devices.lock().insert(name, device); COMPONENT
.get()
.unwrap()
.block_device_table
.lock()
.insert(name, device);
} }
pub fn get_device(str: &String) -> Option<Arc<dyn BlockDevice>> { pub fn get_device(str: &str) -> Option<Arc<dyn BlockDevice>> {
COMPONENT.get().unwrap().devices.lock().get(str).cloned() COMPONENT
.get()
.unwrap()
.block_device_table
.lock()
.get(str)
.cloned()
} }
pub fn all_devices() -> Vec<(String, Arc<dyn BlockDevice>)> { pub fn all_devices() -> Vec<(String, Arc<dyn BlockDevice>)> {
let lock = COMPONENT.get().unwrap().devices.lock(); let block_devs = COMPONENT.get().unwrap().block_device_table.lock();
let mut vec = Vec::new(); block_devs
for (name, device) in lock.iter() { .iter()
vec.push((name.clone(), device.clone())); .map(|(name, device)| (name.clone(), device.clone()))
} .collect()
vec
} }
static COMPONENT: Once<Component> = Once::new(); static COMPONENT: Once<Component> = Once::new();
@ -53,13 +63,13 @@ fn component_init() -> Result<(), ComponentInitError> {
#[derive(Debug)] #[derive(Debug)]
struct Component { struct Component {
devices: SpinLock<BTreeMap<String, Arc<dyn BlockDevice>>>, block_device_table: SpinLock<BTreeMap<String, Arc<dyn BlockDevice>>>,
} }
impl Component { impl Component {
pub fn init() -> Result<Self, ComponentInitError> { pub fn init() -> Result<Self, ComponentInitError> {
Ok(Self { Ok(Self {
devices: SpinLock::new(BTreeMap::new()), block_device_table: SpinLock::new(BTreeMap::new()),
}) })
} }
} }

View File

@ -25,7 +25,7 @@ pub fn register_device(name: String, device: Arc<dyn AnyConsoleDevice>) {
COMPONENT COMPONENT
.get() .get()
.unwrap() .unwrap()
.console_table .console_device_table
.lock() .lock()
.insert(name, device); .insert(name, device);
} }
@ -34,15 +34,15 @@ pub fn get_device(str: &str) -> Option<Arc<dyn AnyConsoleDevice>> {
COMPONENT COMPONENT
.get() .get()
.unwrap() .unwrap()
.console_table .console_device_table
.lock() .lock()
.get(str) .get(str)
.cloned() .cloned()
} }
pub fn all_devices() -> Vec<(String, Arc<dyn AnyConsoleDevice>)> { pub fn all_devices() -> Vec<(String, Arc<dyn AnyConsoleDevice>)> {
let consoles = COMPONENT.get().unwrap().console_table.lock(); let console_devs = COMPONENT.get().unwrap().console_device_table.lock();
consoles console_devs
.iter() .iter()
.map(|(name, device)| (name.clone(), device.clone())) .map(|(name, device)| (name.clone(), device.clone()))
.collect() .collect()
@ -59,13 +59,13 @@ fn component_init() -> Result<(), ComponentInitError> {
#[derive(Debug)] #[derive(Debug)]
struct Component { struct Component {
console_table: SpinLock<BTreeMap<String, Arc<dyn AnyConsoleDevice>>>, console_device_table: SpinLock<BTreeMap<String, Arc<dyn AnyConsoleDevice>>>,
} }
impl Component { impl Component {
pub fn init() -> Result<Self, ComponentInitError> { pub fn init() -> Result<Self, ComponentInitError> {
Ok(Self { Ok(Self {
console_table: SpinLock::new(BTreeMap::new()), console_device_table: SpinLock::new(BTreeMap::new()),
}) })
} }
} }

View File

@ -24,20 +24,30 @@ pub trait InputDevice: Send + Sync + Any + Debug {
} }
pub fn register_device(name: String, device: Arc<dyn InputDevice>) { pub fn register_device(name: String, device: Arc<dyn InputDevice>) {
COMPONENT.get().unwrap().devices.lock().insert(name, device); COMPONENT
.get()
.unwrap()
.input_device_table
.lock()
.insert(name, device);
} }
pub fn get_device(str: &String) -> Option<Arc<dyn InputDevice>> { pub fn get_device(str: &str) -> Option<Arc<dyn InputDevice>> {
COMPONENT.get().unwrap().devices.lock().get(str).cloned() COMPONENT
.get()
.unwrap()
.input_device_table
.lock()
.get(str)
.cloned()
} }
pub fn all_devices() -> Vec<(String, Arc<dyn InputDevice>)> { pub fn all_devices() -> Vec<(String, Arc<dyn InputDevice>)> {
let lock = COMPONENT.get().unwrap().devices.lock(); let input_devs = COMPONENT.get().unwrap().input_device_table.lock();
let mut vec = Vec::new(); input_devs
for (name, device) in lock.iter() { .iter()
vec.push((name.clone(), device.clone())); .map(|(name, device)| (name.clone(), device.clone()))
} .collect()
vec
} }
static COMPONENT: Once<Component> = Once::new(); static COMPONENT: Once<Component> = Once::new();
@ -51,13 +61,13 @@ fn component_init() -> Result<(), ComponentInitError> {
#[derive(Debug)] #[derive(Debug)]
struct Component { struct Component {
devices: SpinLock<BTreeMap<String, Arc<dyn InputDevice>>>, input_device_table: SpinLock<BTreeMap<String, Arc<dyn InputDevice>>>,
} }
impl Component { impl Component {
pub fn init() -> Result<Self, ComponentInitError> { pub fn init() -> Result<Self, ComponentInitError> {
Ok(Self { Ok(Self {
devices: SpinLock::new(BTreeMap::new()), input_device_table: SpinLock::new(BTreeMap::new()),
}) })
} }
} }

View File

@ -3,10 +3,10 @@ use smoltcp::{phy, time::Instant};
use crate::{ use crate::{
buffer::{RxBuffer, TxBuffer}, buffer::{RxBuffer, TxBuffer},
NetworkDevice, AnyNetworkDevice,
}; };
impl phy::Device for dyn NetworkDevice { impl phy::Device for dyn AnyNetworkDevice {
type RxToken<'a> = RxToken; type RxToken<'a> = RxToken;
type TxToken<'a> = TxToken<'a>; type TxToken<'a> = TxToken<'a>;
@ -43,7 +43,7 @@ impl phy::RxToken for RxToken {
} }
} }
pub struct TxToken<'a>(&'a mut dyn NetworkDevice); pub struct TxToken<'a>(&'a mut dyn AnyNetworkDevice);
impl<'a> phy::TxToken for TxToken<'a> { impl<'a> phy::TxToken for TxToken<'a> {
fn consume<R, F>(self, len: usize, f: F) -> R fn consume<R, F>(self, len: usize, f: F) -> R

View File

@ -35,7 +35,7 @@ pub enum VirtioNetError {
Unknown, Unknown,
} }
pub trait NetworkDevice: Send + Sync + Any + Debug { pub trait AnyNetworkDevice: Send + Sync + Any + Debug {
// ================Device Information================= // ================Device Information=================
fn mac_addr(&self) -> EthernetAddr; fn mac_addr(&self) -> EthernetAddr;
@ -54,33 +54,33 @@ pub trait NetworkDevice: Send + Sync + Any + Debug {
pub trait NetDeviceIrqHandler = Fn() + Send + Sync + 'static; pub trait NetDeviceIrqHandler = Fn() + Send + Sync + 'static;
pub fn register_device(name: String, device: Arc<SpinLock<Box<dyn NetworkDevice>>>) { pub fn register_device(name: String, device: Arc<SpinLock<Box<dyn AnyNetworkDevice>>>) {
COMPONENT COMPONENT
.get() .get()
.unwrap() .unwrap()
.devices .network_device_table
.lock() .lock()
.insert(name, (Arc::new(SpinLock::new(Vec::new())), device)); .insert(name, (Arc::new(SpinLock::new(Vec::new())), device));
} }
pub fn get_device(str: &String) -> Option<Arc<SpinLock<Box<dyn NetworkDevice>>>> { pub fn get_device(str: &str) -> Option<Arc<SpinLock<Box<dyn AnyNetworkDevice>>>> {
let lock = COMPONENT.get().unwrap().devices.lock(); let lock = COMPONENT.get().unwrap().network_device_table.lock();
let Some((_, device)) = lock.get(str) else { let Some((_, device)) = lock.get(str) else {
return None; return None;
}; };
Some(device.clone()) Some(device.clone())
} }
pub fn register_recv_callback(name: &String, callback: impl NetDeviceIrqHandler) { pub fn register_recv_callback(name: &str, callback: impl NetDeviceIrqHandler) {
let lock = COMPONENT.get().unwrap().devices.lock(); let lock = COMPONENT.get().unwrap().network_device_table.lock();
let Some((callbacks, _)) = lock.get(name) else { let Some((callbacks, _)) = lock.get(name) else {
return; return;
}; };
callbacks.lock().push(Arc::new(callback)); callbacks.lock().push(Arc::new(callback));
} }
pub fn handle_recv_irq(name: &String) { pub fn handle_recv_irq(name: &str) {
let lock = COMPONENT.get().unwrap().devices.lock(); let lock = COMPONENT.get().unwrap().network_device_table.lock();
let Some((callbacks, _)) = lock.get(name) else { let Some((callbacks, _)) = lock.get(name) else {
return; return;
}; };
@ -92,12 +92,11 @@ pub fn handle_recv_irq(name: &String) {
} }
pub fn all_devices() -> Vec<(String, NetworkDeviceRef)> { pub fn all_devices() -> Vec<(String, NetworkDeviceRef)> {
let lock = COMPONENT.get().unwrap().devices.lock(); let network_devs = COMPONENT.get().unwrap().network_device_table.lock();
let mut vec = Vec::new(); network_devs
for (name, (_, device)) in lock.iter() { .iter()
vec.push((name.clone(), device.clone())); .map(|(name, (_, device))| (name.clone(), device.clone()))
} .collect()
vec
} }
static COMPONENT: Once<Component> = Once::new(); static COMPONENT: Once<Component> = Once::new();
@ -113,17 +112,18 @@ fn init() -> Result<(), ComponentInitError> {
} }
type NetDeviceIrqHandlerListRef = Arc<SpinLock<Vec<Arc<dyn NetDeviceIrqHandler>>>>; type NetDeviceIrqHandlerListRef = Arc<SpinLock<Vec<Arc<dyn NetDeviceIrqHandler>>>>;
type NetworkDeviceRef = Arc<SpinLock<Box<dyn NetworkDevice>>>; type NetworkDeviceRef = Arc<SpinLock<Box<dyn AnyNetworkDevice>>>;
struct Component { struct Component {
/// Device list, the key is device name, value is (callbacks, device); /// Device list, the key is device name, value is (callbacks, device);
devices: SpinLock<BTreeMap<String, (NetDeviceIrqHandlerListRef, NetworkDeviceRef)>>, network_device_table:
SpinLock<BTreeMap<String, (NetDeviceIrqHandlerListRef, NetworkDeviceRef)>>,
} }
impl Component { impl Component {
pub fn init() -> Result<Self, ComponentInitError> { pub fn init() -> Result<Self, ComponentInitError> {
Ok(Self { Ok(Self {
devices: SpinLock::new(BTreeMap::new()), network_device_table: SpinLock::new(BTreeMap::new()),
}) })
} }
} }

View File

@ -95,7 +95,7 @@ impl BlockDevice {
.unwrap(); .unwrap();
fn handle_block_device(_: &TrapFrame) { fn handle_block_device(_: &TrapFrame) {
jinux_block::get_device(&(super::DEVICE_NAME.to_string())) jinux_block::get_device(super::DEVICE_NAME)
.unwrap() .unwrap()
.handle_irq(); .handle_irq();
} }

View File

@ -112,14 +112,14 @@ impl ConsoleDevice {
callbacks: SpinLock::new(Vec::new()), callbacks: SpinLock::new(Vec::new()),
}; };
let mut recv_lock = device.receive_queue.lock(); let mut receive_queue = device.receive_queue.lock();
recv_lock receive_queue
.add(&[], &[device.buffer.lock().as_mut()]) .add(&[], &[device.buffer.lock().as_mut()])
.unwrap(); .unwrap();
if recv_lock.should_notify() { if receive_queue.should_notify() {
recv_lock.notify(); receive_queue.notify();
} }
drop(recv_lock); drop(receive_queue);
device device
.transport .transport
.register_queue_callback(RECV0_QUEUE_INDEX, Box::new(handle_console_input), false) .register_queue_callback(RECV0_QUEUE_INDEX, Box::new(handle_console_input), false)
@ -137,9 +137,7 @@ impl ConsoleDevice {
} }
fn handle_console_input(_: &TrapFrame) { fn handle_console_input(_: &TrapFrame) {
jinux_console::get_device(&DEVICE_NAME.to_string()) jinux_console::get_device(DEVICE_NAME).unwrap().handle_irq();
.unwrap()
.handle_irq();
} }
fn config_space_change(_: &TrapFrame) { fn config_space_change(_: &TrapFrame) {

View File

@ -111,7 +111,7 @@ impl InputDevice {
fn handle_input(_: &TrapFrame) { fn handle_input(_: &TrapFrame) {
debug!("Handle Virtio input interrupt"); debug!("Handle Virtio input interrupt");
let device = jinux_input::get_device(&(super::DEVICE_NAME.to_string())).unwrap(); let device = jinux_input::get_device(super::DEVICE_NAME).unwrap();
device.handle_irq().unwrap(); device.handle_irq().unwrap();
} }

View File

@ -4,7 +4,7 @@ use alloc::{boxed::Box, string::ToString, sync::Arc, vec::Vec};
use jinux_frame::{offset_of, sync::SpinLock, trap::TrapFrame}; use jinux_frame::{offset_of, sync::SpinLock, trap::TrapFrame};
use jinux_network::{ use jinux_network::{
buffer::{RxBuffer, TxBuffer}, buffer::{RxBuffer, TxBuffer},
EthernetAddr, NetDeviceIrqHandler, VirtioNetError, AnyNetworkDevice, EthernetAddr, NetDeviceIrqHandler, VirtioNetError,
}; };
use jinux_util::{field_ptr, slot_vec::SlotVec}; use jinux_util::{field_ptr, slot_vec::SlotVec};
use log::debug; use log::debug;
@ -86,7 +86,7 @@ impl NetworkDevice {
/// Interrupt handler if network device receives some packet /// Interrupt handler if network device receives some packet
fn handle_network_event(_: &TrapFrame) { fn handle_network_event(_: &TrapFrame) {
jinux_network::handle_recv_irq(&(super::DEVICE_NAME.to_string())); jinux_network::handle_recv_irq(super::DEVICE_NAME);
} }
device device
@ -169,7 +169,7 @@ fn queue_to_network_error(err: QueueError) -> VirtioNetError {
} }
} }
impl jinux_network::NetworkDevice for NetworkDevice { impl AnyNetworkDevice for NetworkDevice {
fn mac_addr(&self) -> EthernetAddr { fn mac_addr(&self) -> EthernetAddr {
self.mac_addr self.mac_addr
} }

View File

@ -119,7 +119,7 @@ fn is_component(package: &JsonValue) -> bool {
} }
/// Get all the components name, this function will also check if the Components.toml contain all the components. /// Get all the components name, this function will also check if the Components.toml contain all the components.
fn get_components_name(workspace_root: &String, packages: &JsonValue) -> Vec<String> { fn get_components_name(workspace_root: &str, packages: &JsonValue) -> Vec<String> {
let file_components_name = read_component_file(workspace_root); let file_components_name = read_component_file(workspace_root);
let mut comps_name = Vec::new(); let mut comps_name = Vec::new();
for package in packages.members() { for package in packages.members() {

View File

@ -1,6 +1,6 @@
use crate::prelude::*; use crate::prelude::*;
use jinux_frame::sync::SpinLock; use jinux_frame::sync::SpinLock;
use jinux_network::NetworkDevice; use jinux_network::AnyNetworkDevice;
use jinux_virtio::device::network::DEVICE_NAME; use jinux_virtio::device::network::DEVICE_NAME;
use smoltcp::{ use smoltcp::{
iface::{Config, Routes, SocketHandle, SocketSet}, iface::{Config, Routes, SocketHandle, SocketSet},
@ -11,7 +11,7 @@ use smoltcp::{
use super::{common::IfaceCommon, internal::IfaceInternal, Iface}; use super::{common::IfaceCommon, internal::IfaceInternal, Iface};
pub struct IfaceVirtio { pub struct IfaceVirtio {
driver: Arc<SpinLock<Box<dyn NetworkDevice>>>, driver: Arc<SpinLock<Box<dyn AnyNetworkDevice>>>,
common: IfaceCommon, common: IfaceCommon,
dhcp_handle: SocketHandle, dhcp_handle: SocketHandle,
weak_self: Weak<Self>, weak_self: Weak<Self>,
@ -19,7 +19,7 @@ pub struct IfaceVirtio {
impl IfaceVirtio { impl IfaceVirtio {
pub fn new() -> Arc<Self> { pub fn new() -> Arc<Self> {
let virtio_net = jinux_network::get_device(&(DEVICE_NAME).to_string()).unwrap(); let virtio_net = jinux_network::get_device(DEVICE_NAME).unwrap();
let interface = { let interface = {
let mac_addr = virtio_net.lock().mac_addr(); let mac_addr = virtio_net.lock().mac_addr();
let ip_addr = IpCidr::new(wire::IpAddress::Ipv4(wire::Ipv4Address::UNSPECIFIED), 0); let ip_addr = IpCidr::new(wire::IpAddress::Ipv4(wire::Ipv4Address::UNSPECIFIED), 0);