Skip to main content

lifecycle/
supervisor.rs

1//! System shutdown pipeline over the task manager, the VFS and the power device.
2
3use crate::{Action, Controller, Error, Stages, tasks};
4use core::time::Duration;
5use device::power::{Capabilities, GET_CAPABILITIES, POWER_OFF, RESTART, SLEEP};
6use file_system::AccessFlags;
7use task::TaskIdentifier;
8use virtual_file_system::{File, VirtualFileSystem};
9
10/// System power device node, mounted by the platform.
11pub const POWER_DEVICE_PATH: &str = "/devices/power";
12
13/// Platform driver stop hook, run after storage was committed and unmounted.
14#[allow(async_fn_in_trait)]
15pub trait Drivers {
16    /// Stop drivers in dependency order. Must not use unmounted storage.
17    async fn stop(&mut self) -> Result<(), Error>;
18}
19
20/// No driver needs an explicit stop.
21impl Drivers for () {
22    async fn stop(&mut self) -> Result<(), Error> {
23        Ok(())
24    }
25}
26
27/// Runs the pipeline for a platform: quiesce the descendants of `task`
28/// (except `services`), commit storage, stop drivers, then perform the action
29/// through the power device.
30///
31/// The power device is opened by `task` before anything is stopped, so the
32/// final action does not depend on path resolution after the root filesystem
33/// was unmounted, and an unsupported action fails before any work is done.
34pub struct Supervisor<'a> {
35    pub virtual_file_system: &'static VirtualFileSystem,
36    pub time_manager: &'static time::Manager<'static>,
37    /// Supervisor task; its descendants are stopped.
38    pub task: TaskIdentifier,
39    /// Runtime service subtrees left running (stopped by [`Drivers`]).
40    pub services: &'a [TaskIdentifier],
41    /// Quiescence budget on the monotonic clock.
42    pub budget: Duration,
43}
44
45/// How long the supervisor retries opening a power device held by a request.
46const OPEN_ATTEMPTS: usize = 50;
47const OPEN_RETRY: Duration = Duration::from_millis(20);
48
49impl Supervisor<'_> {
50    /// Run the accepted request of `controller` once. Returns only on failure
51    /// or when the final action returns.
52    pub async fn run(
53        &self,
54        controller: &Controller,
55        drivers: &mut impl Drivers,
56    ) -> Result<(), Error> {
57        let mut device = self.open_power_device().await;
58        let capabilities = match device.as_mut() {
59            Some(device) => device
60                .control(GET_CAPABILITIES, &())
61                .await
62                .map(Capabilities)
63                .unwrap_or_default(),
64            None => Capabilities::NONE,
65        };
66        let mut stages = SystemStages {
67            supervisor: self,
68            device,
69            capabilities,
70            drivers,
71        };
72        let result = controller.run(&mut stages, self.budget).await;
73        if let Some(device) = stages.device.take() {
74            let _ = device.close(self.virtual_file_system).await;
75        }
76        result
77    }
78
79    async fn open_power_device(&self) -> Option<File<'static>> {
80        for _ in 0..OPEN_ATTEMPTS {
81            match File::open(
82                self.virtual_file_system,
83                self.task,
84                POWER_DEVICE_PATH,
85                AccessFlags::Write.into(),
86            )
87            .await
88            {
89                Ok(device) => return Some(device),
90                // A concurrent privileged request briefly holds the device.
91                Err(file_system::IoErrorKind::ResourceBusy) => {
92                    task::Manager::sleep(OPEN_RETRY).await
93                }
94                Err(_) => return None,
95            }
96        }
97        None
98    }
99}
100
101struct SystemStages<'a, 'b, D> {
102    supervisor: &'a Supervisor<'b>,
103    device: Option<File<'static>>,
104    capabilities: Capabilities,
105    drivers: &'a mut D,
106}
107
108impl<D: Drivers> Stages for SystemStages<'_, '_, D> {
109    fn capabilities(&self) -> Capabilities {
110        self.capabilities
111    }
112
113    async fn quiesce(&mut self, budget: Duration) -> Result<(), Error> {
114        let supervisor = self.supervisor;
115        tasks::stop(
116            supervisor.virtual_file_system.task_manager(),
117            supervisor.task,
118            supervisor.services,
119            || supervisor.time_manager.monotonic_now(),
120            budget,
121        )
122        .await
123    }
124
125    async fn storage(&mut self) -> Result<(), Error> {
126        self.supervisor
127            .virtual_file_system
128            .shutdown_storage()
129            .await
130            .map_err(|_| Error::Storage)
131    }
132
133    async fn drivers(&mut self) -> Result<(), Error> {
134        self.drivers.stop().await
135    }
136
137    async fn finalize(&mut self, action: Action, status: u8) -> Result<(), Error> {
138        let device = self.device.as_mut().ok_or(Error::Unsupported)?;
139        let result = match action {
140            Action::PowerOff => device.control(POWER_OFF, &status).await,
141            Action::Restart => device.control(RESTART, &status).await,
142            Action::Sleep => device.control(SLEEP, &()).await,
143        };
144        result.map_err(|error| match error {
145            file_system::IoErrorKind::Unsupported => Error::Unsupported,
146            _ => Error::Power,
147        })
148    }
149}