1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
//! VMM event loop.
//!
//! This module provides the main event loop that coordinates vCPU execution,
//! device I/O, and timers.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use tokio::sync::mpsc;
use crate::error::{Result, VmmError};
use arcbox_hypervisor::VcpuExit;
/// VMM events.
#[derive(Debug)]
pub enum VmmEvent {
/// vCPU exit event.
VcpuExit {
/// vCPU ID.
vcpu_id: u32,
/// Exit reason.
exit: VcpuExit,
},
/// Device I/O event.
DeviceIo {
/// Device ID.
device_id: u32,
/// Is this a read operation?
is_read: bool,
/// Address.
addr: u64,
/// Data (for writes).
data: Option<u64>,
},
/// Timer expired.
Timer {
/// Timer ID.
id: u32,
},
/// Shutdown requested.
Shutdown,
}
/// Event loop for the VMM.
///
/// Coordinates events from multiple sources: vCPUs, devices, and timers.
pub struct EventLoop {
/// Whether the event loop is running.
running: Arc<AtomicBool>,
/// Event sender (for posting events).
event_tx: mpsc::UnboundedSender<VmmEvent>,
/// Event receiver.
event_rx: mpsc::UnboundedReceiver<VmmEvent>,
}
impl EventLoop {
/// Creates a new event loop.
///
/// # Errors
///
/// Returns an error if the event loop cannot be created.
pub fn new() -> Result<Self> {
let (event_tx, event_rx) = mpsc::unbounded_channel();
Ok(Self {
running: Arc::new(AtomicBool::new(false)),
event_tx,
event_rx,
})
}
/// Returns a sender for posting events.
#[must_use]
pub fn event_sender(&self) -> mpsc::UnboundedSender<VmmEvent> {
self.event_tx.clone()
}
/// Returns whether the event loop is running.
#[must_use]
pub fn is_running(&self) -> bool {
self.running.load(Ordering::SeqCst)
}
/// Starts the event loop.
///
/// # Errors
///
/// Returns an error if the event loop cannot be started.
pub fn start(&mut self) -> Result<()> {
self.running.store(true, Ordering::SeqCst);
tracing::debug!("Event loop started");
Ok(())
}
/// Stops the event loop.
pub fn stop(&mut self) {
self.running.store(false, Ordering::SeqCst);
tracing::debug!("Event loop stopped");
}
/// Posts an event to the event loop.
///
/// # Errors
///
/// Returns an error if the event cannot be posted.
pub fn post_event(&self, event: VmmEvent) -> Result<()> {
self.event_tx
.send(event)
.map_err(|e| VmmError::EventLoop(format!("failed to post event: {e}")))
}
/// Polls for the next event.
///
/// Returns `None` if no event is available or the loop is stopped.
pub async fn poll(&mut self) -> Option<VmmEvent> {
if !self.is_running() {
return None;
}
// Use a timeout to allow periodic checks
tokio::select! {
event = self.event_rx.recv() => {
event
}
() = tokio::time::sleep(Duration::from_millis(100)) => {
None
}
}
}
/// Polls for events without blocking.
pub fn try_poll(&mut self) -> Option<VmmEvent> {
self.event_rx.try_recv().ok()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_event_loop_creation() {
let event_loop = EventLoop::new().unwrap();
assert!(!event_loop.is_running());
}
#[tokio::test]
async fn test_event_posting() {
let mut event_loop = EventLoop::new().unwrap();
event_loop.start().unwrap();
// Post an event
event_loop.post_event(VmmEvent::Shutdown).unwrap();
// Poll for it
let event = event_loop.poll().await;
assert!(matches!(event, Some(VmmEvent::Shutdown)));
}
#[tokio::test]
async fn test_event_loop_stop() {
let mut event_loop = EventLoop::new().unwrap();
event_loop.start().unwrap();
assert!(event_loop.is_running());
event_loop.stop();
assert!(!event_loop.is_running());
// Polling stopped loop returns None
let event = event_loop.poll().await;
assert!(event.is_none());
}
}