1#![no_std]
12
13extern crate alloc;
14
15mod supervisor;
16pub mod tasks;
17
18pub use supervisor::{Drivers, POWER_DEVICE_PATH, Supervisor};
19
20use core::time::Duration;
21use device::power::Capabilities;
22use file_system::AccessFlags;
23use portable_atomic::{AtomicU16, Ordering};
24use task::TaskIdentifier;
25use virtual_file_system::{File, VirtualFileSystem};
26
27#[repr(u8)]
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub enum Action {
31 PowerOff = 1,
33 Restart = 2,
35 Sleep = 3,
37}
38
39impl Action {
40 const fn from_bits(value: u16) -> Option<Self> {
41 match value {
42 1 => Some(Self::PowerOff),
43 2 => Some(Self::Restart),
44 3 => Some(Self::Sleep),
45 _ => None,
46 }
47 }
48
49 pub const fn capability(self) -> Capabilities {
51 match self {
52 Self::PowerOff => Capabilities::POWER_OFF,
53 Self::Restart => Capabilities::RESTART,
54 Self::Sleep => Capabilities::SLEEP,
55 }
56 }
57}
58
59#[repr(u8)]
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62pub enum State {
63 Running = 0,
64 Requested = 1,
66 Quiescing = 2,
68 Syncing = 3,
70 StoppingDrivers = 4,
72 Finalizing = 5,
74 Returned = 6,
76 Failed = 7,
78}
79
80impl State {
81 const fn from_bits(value: u16) -> Self {
82 match value {
83 0 => Self::Running,
84 1 => Self::Requested,
85 2 => Self::Quiescing,
86 3 => Self::Syncing,
87 4 => Self::StoppingDrivers,
88 5 => Self::Finalizing,
89 6 => Self::Returned,
90 _ => Self::Failed,
91 }
92 }
93}
94
95#[derive(Clone, Copy, Debug, PartialEq, Eq)]
97pub enum Error {
98 PermissionDenied,
100 Busy,
102 Timeout,
104 Storage,
106 Driver,
108 Unsupported,
110 Power,
112}
113
114impl core::fmt::Display for Error {
115 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
116 formatter.write_str(match self {
117 Self::PermissionDenied => "lifecycle request not permitted",
118 Self::Busy => "lifecycle request already in progress",
119 Self::Timeout => "tasks did not stop before the deadline",
120 Self::Storage => "storage commit failed",
121 Self::Driver => "driver stop failed",
122 Self::Unsupported => "unsupported power action",
123 Self::Power => "power action failed",
124 })
125 }
126}
127
128const STATE_MASK: u16 = 0x000f;
129const ACTION_SHIFT: u16 = 4;
130const STATUS_SHIFT: u16 = 8;
131
132pub struct Controller(AtomicU16);
135
136impl Default for Controller {
137 fn default() -> Self {
138 Self::new()
139 }
140}
141
142impl Controller {
143 pub const fn new() -> Self {
144 Self(AtomicU16::new(State::Running as u16))
145 }
146
147 fn word(&self) -> u16 {
148 self.0.load(Ordering::Acquire)
149 }
150
151 pub fn state(&self) -> State {
152 State::from_bits(self.word() & STATE_MASK)
153 }
154
155 pub fn is_running(&self) -> bool {
156 self.state() == State::Running
157 }
158
159 pub fn action(&self) -> Option<Action> {
161 Action::from_bits((self.word() >> ACTION_SHIFT) & 0xf)
162 }
163
164 pub fn status(&self) -> u8 {
166 (self.word() >> STATUS_SHIFT) as u8
167 }
168
169 pub fn request(&self, action: Action, status: u8) -> Result<(), State> {
177 let word = (status as u16) << STATUS_SHIFT
178 | (action as u16) << ACTION_SHIFT
179 | State::Requested as u16;
180 self.0
181 .compare_exchange(
182 State::Running as u16,
183 word,
184 Ordering::AcqRel,
185 Ordering::Acquire,
186 )
187 .map(|_| ())
188 .map_err(|word| State::from_bits(word & STATE_MASK))
189 }
190
191 fn advance(&self, from: State, to: State) -> Result<(), State> {
192 let word = self.word();
193 if word & STATE_MASK != from as u16 {
194 return Err(State::from_bits(word & STATE_MASK));
195 }
196 self.0
197 .compare_exchange(
198 word,
199 word & !STATE_MASK | to as u16,
200 Ordering::AcqRel,
201 Ordering::Acquire,
202 )
203 .map(|_| ())
204 .map_err(|word| State::from_bits(word & STATE_MASK))
205 }
206
207 fn fail(&self, from: State) {
208 let _ = self.advance(from, State::Failed);
209 }
210
211 pub async fn run<S: Stages>(&self, stages: &mut S, budget: Duration) -> Result<(), Error> {
218 self.execute(stages, budget, false).await.map(|_| ())
219 }
220
221 pub async fn run_forced<S: Stages>(
227 &self,
228 stages: &mut S,
229 budget: Duration,
230 ) -> Result<Option<Error>, Error> {
231 self.execute(stages, budget, true).await
232 }
233
234 async fn execute<S: Stages>(
235 &self,
236 stages: &mut S,
237 budget: Duration,
238 force: bool,
239 ) -> Result<Option<Error>, Error> {
240 self.advance(State::Requested, State::Quiescing)
241 .map_err(|_| Error::Busy)?;
242 let action = self.action().ok_or(Error::Busy)?;
243 if !stages.capabilities().contains(action.capability()) {
244 self.fail(State::Quiescing);
245 return Err(Error::Unsupported);
246 }
247
248 let mut skipped = None;
249 let mut check = |state: State, result: Result<(), Error>| match result {
250 Ok(()) => Ok(()),
251 Err(error) if force => {
252 skipped.get_or_insert(error);
253 Ok(())
254 }
255 Err(error) => {
256 self.fail(state);
257 Err(error)
258 }
259 };
260
261 check(State::Quiescing, stages.quiesce(budget).await)?;
262 self.advance(State::Quiescing, State::Syncing)
263 .map_err(|_| Error::Busy)?;
264 check(State::Syncing, stages.storage().await)?;
265 self.advance(State::Syncing, State::StoppingDrivers)
266 .map_err(|_| Error::Busy)?;
267 check(State::StoppingDrivers, stages.drivers().await)?;
268 self.advance(State::StoppingDrivers, State::Finalizing)
269 .map_err(|_| Error::Busy)?;
270 if let Err(error) = stages.finalize(action, self.status()).await {
271 self.fail(State::Finalizing);
272 return Err(error);
273 }
274 self.advance(State::Finalizing, State::Returned)
275 .map_err(|_| Error::Busy)?;
276 Ok(skipped)
277 }
278}
279
280#[allow(async_fn_in_trait)]
283pub trait Stages {
284 fn capabilities(&self) -> Capabilities;
286
287 async fn quiesce(&mut self, budget: Duration) -> Result<(), Error>;
291
292 async fn storage(&mut self) -> Result<(), Error>;
295
296 async fn drivers(&mut self) -> Result<(), Error>;
298
299 async fn finalize(&mut self, action: Action, status: u8) -> Result<(), Error>;
301}
302
303pub static SYSTEM: Controller = Controller::new();
305
306pub async fn request(
314 virtual_file_system: &VirtualFileSystem,
315 task: TaskIdentifier,
316 action: Action,
317 status: u8,
318) -> Result<(), Error> {
319 request_with(&SYSTEM, virtual_file_system, task, action, status).await
320}
321
322pub(crate) async fn request_with(
323 controller: &Controller,
324 virtual_file_system: &VirtualFileSystem,
325 task: TaskIdentifier,
326 action: Action,
327 status: u8,
328) -> Result<(), Error> {
329 use virtual_file_system::IoErrorKind;
330 let mut device = File::open(
331 virtual_file_system,
332 task,
333 POWER_DEVICE_PATH,
334 AccessFlags::Write.into(),
335 )
336 .await
337 .map_err(|error| match error {
338 IoErrorKind::PermissionDenied => Error::PermissionDenied,
339 IoErrorKind::ResourceBusy => Error::Busy,
340 _ => Error::Unsupported,
341 })?;
342 let capabilities = device.control(device::power::GET_CAPABILITIES, &()).await;
343 let _ = device.close(virtual_file_system).await;
344 let capabilities = Capabilities(capabilities.map_err(|_| Error::Unsupported)?);
345 if !capabilities.contains(action.capability()) {
346 return Err(Error::Unsupported);
347 }
348 controller.request(action, status).map_err(|_| Error::Busy)
349}
350
351#[cfg(test)]
352mod tests {
353 extern crate std;
354
355 use super::*;
356 use core::{
357 future::Future,
358 pin::pin,
359 task::{Context, Poll, Waker},
360 };
361
362 #[test]
363 fn concurrent_requests_have_exactly_one_winner() {
364 let controller = Controller::new();
365 let winners = std::thread::scope(|scope| {
366 let threads: std::vec::Vec<_> = (0..16u8)
367 .map(|index| {
368 let controller = &controller;
369 scope.spawn(move || {
370 let action = if index % 2 == 0 {
371 Action::PowerOff
372 } else {
373 Action::Restart
374 };
375 controller
376 .request(action, index)
377 .ok()
378 .map(|()| (action, index))
379 })
380 })
381 .collect();
382 threads
383 .into_iter()
384 .filter_map(|thread| thread.join().unwrap())
385 .collect::<std::vec::Vec<_>>()
386 });
387 assert_eq!(winners.len(), 1);
388 assert_eq!(controller.state(), State::Requested);
389 assert_eq!(controller.action(), Some(winners[0].0));
391 assert_eq!(controller.status(), winners[0].1);
392 }
393
394 #[test]
395 fn states_never_rewind() {
396 let controller = Controller::new();
397 assert_eq!(
398 controller.advance(State::Requested, State::Quiescing),
399 Err(State::Running)
400 );
401 controller.request(Action::PowerOff, 143).unwrap();
402 assert_eq!(
403 controller.request(Action::Restart, 0),
404 Err(State::Requested)
405 );
406 controller
407 .advance(State::Requested, State::Quiescing)
408 .unwrap();
409 assert_eq!(
410 controller.advance(State::Requested, State::Quiescing),
411 Err(State::Quiescing)
412 );
413 controller.fail(State::Quiescing);
414 assert_eq!(controller.request(Action::Restart, 0), Err(State::Failed));
415 assert_eq!(
416 controller.advance(State::Quiescing, State::Syncing),
417 Err(State::Failed)
418 );
419 assert_eq!(controller.action(), Some(Action::PowerOff));
420 assert_eq!(controller.status(), 143);
421 }
422
423 #[derive(Default)]
424 struct Mock {
425 calls: std::vec::Vec<&'static str>,
426 fail: Option<(&'static str, Error)>,
427 capabilities: Option<Capabilities>,
428 finalized: Option<(Action, u8)>,
429 }
430
431 impl Mock {
432 fn step(&mut self, name: &'static str) -> Result<(), Error> {
433 self.calls.push(name);
434 match self.fail {
435 Some((stage, error)) if stage == name => Err(error),
436 _ => Ok(()),
437 }
438 }
439 }
440
441 impl Stages for Mock {
442 fn capabilities(&self) -> Capabilities {
443 self.capabilities.unwrap_or(Capabilities::POWER_OFF)
444 }
445 async fn quiesce(&mut self, _: Duration) -> Result<(), Error> {
446 self.step("quiesce")
447 }
448 async fn storage(&mut self) -> Result<(), Error> {
449 self.step("storage")
450 }
451 async fn drivers(&mut self) -> Result<(), Error> {
452 self.step("drivers")
453 }
454 async fn finalize(&mut self, action: Action, status: u8) -> Result<(), Error> {
455 self.finalized = Some((action, status));
456 self.step("finalize")
457 }
458 }
459
460 fn ready<T>(future: impl Future<Output = T>) -> T {
461 match pin!(future).poll(&mut Context::from_waker(Waker::noop())) {
462 Poll::Ready(output) => output,
463 Poll::Pending => panic!("mock stages never suspend"),
464 }
465 }
466
467 fn requested(action: Action) -> Controller {
468 let controller = Controller::new();
469 controller.request(action, 0).unwrap();
470 controller
471 }
472
473 const BUDGET: Duration = Duration::from_secs(5);
474
475 #[test]
476 fn success_runs_every_stage_once_in_order() {
477 let controller = Controller::new();
478 controller.request(Action::PowerOff, 3).unwrap();
479 let mut mock = Mock::default();
480 assert_eq!(ready(controller.run(&mut mock, BUDGET)), Ok(()));
481 assert_eq!(mock.calls, ["quiesce", "storage", "drivers", "finalize"]);
482 assert_eq!(mock.finalized, Some((Action::PowerOff, 3)));
483 assert_eq!(controller.state(), State::Returned);
484 assert_eq!(ready(controller.run(&mut mock, BUDGET)), Err(Error::Busy));
485 assert_eq!(mock.calls.len(), 4);
486 }
487
488 #[test]
489 fn run_without_request_is_rejected() {
490 let controller = Controller::new();
491 let mut mock = Mock::default();
492 assert_eq!(ready(controller.run(&mut mock, BUDGET)), Err(Error::Busy));
493 assert!(mock.calls.is_empty());
494 assert_eq!(controller.state(), State::Running);
495 }
496
497 #[test]
498 fn storage_failure_stops_before_drivers_and_power_action() {
499 let controller = requested(Action::PowerOff);
500 let mut mock = Mock {
501 fail: Some(("storage", Error::Storage)),
502 ..Default::default()
503 };
504 assert_eq!(
505 ready(controller.run(&mut mock, BUDGET)),
506 Err(Error::Storage)
507 );
508 assert_eq!(mock.calls, ["quiesce", "storage"]);
509 assert_eq!(mock.finalized, None);
510 assert_eq!(controller.state(), State::Failed);
511 assert_eq!(ready(controller.run(&mut mock, BUDGET)), Err(Error::Busy));
512 }
513
514 #[test]
515 fn quiescence_timeout_keeps_storage_and_drivers_untouched() {
516 let controller = requested(Action::PowerOff);
517 let mut mock = Mock {
518 fail: Some(("quiesce", Error::Timeout)),
519 ..Default::default()
520 };
521 assert_eq!(
522 ready(controller.run(&mut mock, BUDGET)),
523 Err(Error::Timeout)
524 );
525 assert_eq!(mock.calls, ["quiesce"]);
526 assert_eq!(controller.state(), State::Failed);
527 }
528
529 #[test]
530 fn unsupported_action_fails_before_quiescence() {
531 let controller = requested(Action::Sleep);
532 let mut mock = Mock::default();
533 assert_eq!(
534 ready(controller.run(&mut mock, BUDGET)),
535 Err(Error::Unsupported)
536 );
537 assert!(mock.calls.is_empty());
538 assert_eq!(controller.state(), State::Failed);
539 }
540
541 #[test]
542 fn forced_run_reaches_the_power_action_and_reports_the_skipped_failure() {
543 let controller = requested(Action::PowerOff);
544 let mut mock = Mock {
545 fail: Some(("storage", Error::Storage)),
546 ..Default::default()
547 };
548 assert_eq!(
549 ready(controller.run_forced(&mut mock, BUDGET)),
550 Ok(Some(Error::Storage))
551 );
552 assert_eq!(mock.calls, ["quiesce", "storage", "drivers", "finalize"]);
553 assert_eq!(controller.state(), State::Returned);
554 }
555
556 #[test]
557 fn power_action_failure_is_terminal() {
558 let controller = requested(Action::Restart);
559 let mut mock = Mock {
560 fail: Some(("finalize", Error::Power)),
561 capabilities: Some(Capabilities::RESTART),
562 ..Default::default()
563 };
564 assert_eq!(ready(controller.run(&mut mock, BUDGET)), Err(Error::Power));
565 assert_eq!(controller.state(), State::Failed);
566 }
567}