Skip to main content

shutdown_shim/
lib.rs

1// Copyright 2024 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4mod reboot_reasons;
5mod shutdown_watcher;
6
7use crate::reboot_reasons::ShutdownOptionsWrapper;
8use crate::shutdown_watcher::ShutdownWatcher;
9use anyhow::{Context, format_err};
10use fidl::endpoints::{DiscoverableProtocolMarker, ServerEnd};
11use fidl_fuchsia_hardware_power_statecontrol::{
12    AdminRequest, AdminRequestStream, AdminShutdownResponder,
13    RebootMethodsWatcherRegisterRequestStream, ShutdownAction, ShutdownOptions, ShutdownReason,
14    ShutdownWatcherRegisterRequestStream,
15};
16use fidl_fuchsia_io as fio;
17use fidl_fuchsia_power::CollaborativeRebootInitiatorRequestStream;
18use fidl_fuchsia_power_internal::{
19    CollaborativeRebootReason, CollaborativeRebootSchedulerRequestStream,
20};
21use fidl_fuchsia_power_system as fsystem;
22use fidl_fuchsia_sys2::SystemControllerMarker;
23use fidl_fuchsia_system_state::{
24    SystemPowerState, SystemStateTransitionRequest, SystemStateTransitionRequestStream,
25};
26use fuchsia_async as fasync;
27use fuchsia_component::client;
28use fuchsia_component::directory::{AsRefDirectory, Directory};
29use fuchsia_component::server::ServiceFs;
30use fuchsia_sync::Mutex;
31use futures::channel::mpsc;
32use futures::lock::Mutex as AMutex;
33use futures::prelude::*;
34use futures::select;
35use shutdown_shim_config::Config;
36use std::pin::pin;
37use std::sync::{Arc, LazyLock};
38use std::time::Duration;
39
40mod collaborative_reboot;
41
42// The amount of time that the shim will spend waiting for a manually trigger
43// system shutdown to finish before forcefully restarting the system.
44const MANUAL_SYSTEM_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(60 * 60);
45
46enum IncomingRequest {
47    SystemStateTransition(SystemStateTransitionRequestStream),
48    Admin(AdminRequestStream),
49    CollaborativeRebootInitiator(CollaborativeRebootInitiatorRequestStream),
50    CollaborativeRebootScheduler(CollaborativeRebootSchedulerRequestStream),
51    RebootMethodsWatcherRegister(RebootMethodsWatcherRegisterRequestStream),
52    ShutdownWatcherRegister(ShutdownWatcherRegisterRequestStream),
53}
54
55pub async fn main(
56    svc: impl Directory + AsRefDirectory + 'static,
57    directory_request: ServerEnd<fio::DirectoryMarker>,
58    config_vmo: Option<zx::Vmo>,
59) -> Result<(), anyhow::Error> {
60    // Check the config
61    let config = Config::from_vmo(&config_vmo.expect("Config VMO handle must be present."))?;
62    println!("[shutdown-shim]: started with config: {:?}", config);
63
64    // Initialize the inspect framework.
65    //
66    // Note that shutdown-shim is a builtin component of ComponentManager, which
67    // means we must setup the inspector in a non-conventional way:
68    // * We must initialize the connection to the inspect sink relative to the
69    // `svc` directory.
70    // * We must not use the global `fuchsia_inspect::component::inspector()`;
71    //   this instance instance is a singleton and would be shared with
72    //   ComponentManager. Instead we declare our own local inspector.
73    let inspector = fuchsia_inspect::Inspector::new(fuchsia_inspect::InspectorConfig::default());
74    let (client, server) =
75        fidl::endpoints::create_endpoints::<fidl_fuchsia_inspect::InspectSinkMarker>();
76    // Note: The inspect server is detached, so we need not poll it.
77    let _inspect_server_task = inspect_runtime::publish(
78        &inspector,
79        inspect_runtime::PublishOptions::default().on_inspect_sink_client(client),
80    )
81    .ok_or_else(|| format_err!("failed to initialize inspect framework"))?;
82    svc.as_ref_directory()
83        .open(
84            fidl_fuchsia_inspect::InspectSinkMarker::PROTOCOL_NAME,
85            fio::Flags::PROTOCOL_SERVICE,
86            server.into_channel().into(),
87        )
88        .context("failed to connect to InspectSink")?;
89
90    let mut service_fs = ServiceFs::new();
91    service_fs.dir("svc").add_fidl_service(IncomingRequest::Admin);
92    service_fs.dir("svc").add_fidl_service(IncomingRequest::RebootMethodsWatcherRegister);
93    service_fs.dir("svc").add_fidl_service(IncomingRequest::ShutdownWatcherRegister);
94    service_fs.dir("svc").add_fidl_service(IncomingRequest::SystemStateTransition);
95    service_fs.dir("svc").add_fidl_service(IncomingRequest::CollaborativeRebootInitiator);
96    service_fs.dir("svc").add_fidl_service(IncomingRequest::CollaborativeRebootScheduler);
97    service_fs.serve_connection(directory_request).context("failed to serve outgoing namespace")?;
98
99    let (abort_tx, mut abort_rx) = mpsc::unbounded::<()>();
100    let (cr_state, cr_cancellations) = collaborative_reboot::new(&inspector);
101    let ctx = ProgramContext {
102        svc,
103        abort_tx,
104        collaborative_reboot: cr_state,
105        shutdown_pending: Arc::new(AMutex::new(false)),
106        shutdown_watcher: ShutdownWatcher::new_with_inspector(&inspector),
107        config,
108    };
109
110    let shutdown_watcher = ctx.shutdown_watcher.clone();
111    let mut service_fut = service_fs
112        .for_each_concurrent(None, |request: IncomingRequest| async {
113            match request {
114                IncomingRequest::Admin(stream) => ctx.handle_admin_request(stream).await,
115                IncomingRequest::RebootMethodsWatcherRegister(stream) => {
116                    shutdown_watcher.clone().handle_reboot_register_request(stream).await;
117                }
118                IncomingRequest::ShutdownWatcherRegister(stream) => {
119                    shutdown_watcher.clone().handle_shutdown_register_request(stream).await
120                }
121                IncomingRequest::SystemStateTransition(stream) => {
122                    ctx.handle_system_state_transition(stream).await
123                }
124                IncomingRequest::CollaborativeRebootInitiator(stream) => {
125                    ctx.collaborative_reboot.handle_initiator_requests(stream, &ctx).await
126                }
127                IncomingRequest::CollaborativeRebootScheduler(stream) => {
128                    ctx.collaborative_reboot.handle_scheduler_requests(stream).await
129                }
130            }
131        })
132        .fuse();
133    let collaborative_reboot_cancellation_fut = pin!(cr_cancellations.run());
134    let mut collaborative_reboot_cancellation_fut = collaborative_reboot_cancellation_fut.fuse();
135    let mut abort_fut = abort_rx.next().fuse();
136
137    select! {
138        () = service_fut => {},
139        () = collaborative_reboot_cancellation_fut => unreachable!(),
140        _ = abort_fut => {},
141    };
142
143    Err(format_err!("exited unexpectedly"))
144}
145
146struct ProgramContext<D: Directory + AsRefDirectory> {
147    svc: D,
148    abort_tx: mpsc::UnboundedSender<()>,
149    collaborative_reboot: collaborative_reboot::State,
150
151    /// Tracks the current shutdown request state. Used to ignore shutdown requests while a current
152    /// request is being processed.
153    shutdown_pending: Arc<AMutex<bool>>,
154
155    shutdown_watcher: Arc<ShutdownWatcher>,
156    config: Config,
157}
158
159impl<D: Directory + AsRefDirectory> ProgramContext<D> {
160    async fn handle_admin_request(&self, mut stream: AdminRequestStream) {
161        while let Ok(Some(request)) = stream.try_next().await {
162            match request {
163                AdminRequest::PowerFullyOn { responder, .. } => {
164                    let _ = responder.send(Err(zx::Status::NOT_SUPPORTED.into_raw()));
165                }
166                AdminRequest::Shutdown { options, responder } => {
167                    self.shutdown_request(options, responder).await;
168                }
169                AdminRequest::PerformReboot { options, responder } => {
170                    let options = match options.reasons {
171                        Some(reasons) => {
172                            Some(ShutdownOptionsWrapper::from_reboot_reason2_deprecated(&reasons))
173                        }
174                        None => None,
175                    };
176
177                    let target_state = if options.as_ref().is_some_and(|options| {
178                        options.reasons.contains(&ShutdownReason::OutOfMemory)
179                    }) {
180                        SystemPowerState::RebootKernelInitiated
181                    } else {
182                        SystemPowerState::Reboot
183                    };
184
185                    let res = self.shutdown(target_state, options).await;
186                    let _ = responder.send(res.map_err(|s| s.into_raw()));
187                }
188                AdminRequest::RebootToBootloader { responder } => {
189                    let res = self.shutdown(SystemPowerState::RebootBootloader, None).await;
190                    let _ = responder.send(res.map_err(|s| s.into_raw()));
191                }
192                AdminRequest::RebootToRecovery { responder } => {
193                    let res = self.shutdown(SystemPowerState::RebootRecovery, None).await;
194                    let _ = responder.send(res.map_err(|s| s.into_raw()));
195                }
196                AdminRequest::Poweroff { responder } => {
197                    let res = self.shutdown(SystemPowerState::Poweroff, None).await;
198                    let _ = responder.send(res.map_err(|s| s.into_raw()));
199                }
200                // TODO(https://fxbug.dev/572808810): Remove once all API levels containing
201                // SuspendToRam are retired.
202                AdminRequest::SuspendToRam { responder } => {
203                    let _ = responder.send(Err(zx::Status::NOT_SUPPORTED.into_raw()));
204                }
205                AdminRequest::Mexec { responder, .. } => {
206                    // TODO(https://fxbug.dev/573204187): Delete once Admin.Mexec is gone
207                    // from all supported API levels.
208                    let _ = responder.send(Err(zx::Status::NOT_SUPPORTED.into_raw()));
209                }
210            }
211        }
212    }
213
214    async fn shutdown_request(&self, options: ShutdownOptions, responder: AdminShutdownResponder) {
215        let Some(action) = options.action else {
216            println!("[shutdown-shim]: error, shutdown action must be specified");
217            let _ = responder.send(Err(zx::Status::INVALID_ARGS.into_raw()));
218            return;
219        };
220
221        let options = match options.reasons {
222            Some(reasons) => ShutdownOptionsWrapper { action, reasons },
223            None => ShutdownOptionsWrapper { action, reasons: vec![] },
224        };
225
226        match action {
227            ShutdownAction::Reboot => {
228                let target_state = if options.reasons.contains(&ShutdownReason::OutOfMemory) {
229                    SystemPowerState::RebootKernelInitiated
230                } else {
231                    SystemPowerState::Reboot
232                };
233
234                let res = self.shutdown(target_state, Some(options)).await;
235                let _ = responder.send(res.map_err(|s| s.into_raw()));
236            }
237            ShutdownAction::RebootToBootloader => {
238                let res = self.shutdown(SystemPowerState::RebootBootloader, Some(options)).await;
239                let _ = responder.send(res.map_err(|s| s.into_raw()));
240            }
241            ShutdownAction::RebootToRecovery => {
242                let res = self.shutdown(SystemPowerState::RebootRecovery, Some(options)).await;
243                let _ = responder.send(res.map_err(|s| s.into_raw()));
244            }
245            ShutdownAction::Poweroff => {
246                let res = self.shutdown(SystemPowerState::Poweroff, Some(options)).await;
247                let _ = responder.send(res.map_err(|s| s.into_raw()));
248            }
249            ShutdownAction::__SourceBreaking { unknown_ordinal } => {
250                println!(
251                    "[shutdown-shim]: error, unrecognized shutdown action ordinal '{unknown_ordinal}'"
252                );
253                let _ = responder.send(Err(zx::Status::INVALID_ARGS.into_raw()));
254            }
255        }
256    }
257
258    async fn handle_system_state_transition(&self, mut stream: SystemStateTransitionRequestStream) {
259        while let Ok(Some(request)) = stream.try_next().await {
260            match request {
261                SystemStateTransitionRequest::GetTerminationSystemState { responder } => {
262                    let state = (*SYSTEM_STATE).lock();
263                    let _ = responder.send(state.power_state);
264                }
265            }
266        }
267    }
268
269    // TODO(https://fxbug.dev/414413282): make `options` non-optional once deprecated shutdown
270    // methods are removed.
271    async fn shutdown(
272        &self,
273        target_state: SystemPowerState,
274        options: Option<ShutdownOptionsWrapper>,
275    ) -> Result<(), zx::Status> {
276        println!("[shutdown-shim] shutdown with options [{:?}]", options);
277        let _reboot_control_lease = self.acquire_shutdown_control_lease().await;
278        self.forward_command(target_state, options).await
279    }
280
281    async fn forward_command(
282        &self,
283        fallback_state: SystemPowerState,
284        options: Option<ShutdownOptionsWrapper>,
285    ) -> Result<(), zx::Status> {
286        // Return if shutdown is already pending. The termination state must only be updated by
287        // the request that wins this check, otherwise a rejected concurrent request could change
288        // the in-progress shutdown (e.g. turn a reboot into a reboot to bootloader).
289        {
290            let mut shutdown_pending = self.shutdown_pending.lock().await;
291            if *shutdown_pending {
292                println!(
293                    "[shutdown-shim] ignoring {:?} request, shutdown already pending",
294                    fallback_state
295                );
296                return Err(zx::Status::ALREADY_EXISTS);
297            }
298            *shutdown_pending = true;
299            set_system_power_state(fallback_state);
300        }
301        println!("[shutdown-shim] entering {:?} state", fallback_state);
302
303        self.shutdown_watcher.handle_system_shutdown_message(options).await;
304
305        self.drive_shutdown_manually().await;
306
307        // We should block on fuchsia.sys.SystemController forever on this task, if
308        // it returns something has gone wrong.
309        eprintln!("[shutdown-shim]: we shouldn't still be running, crashing the system");
310        Self::abort(self.abort_tx.clone()).await
311    }
312
313    async fn drive_shutdown_manually(&self) {
314        let abort_tx = self.abort_tx.clone();
315        fasync::Task::spawn(async {
316            fasync::Timer::new(MANUAL_SYSTEM_SHUTDOWN_TIMEOUT).await;
317            // We shouldn't still be running at this point
318            Self::abort(abort_tx).await;
319        })
320        .detach();
321
322        if let Err(e) = self.initiate_component_shutdown().await {
323            eprintln!(
324                "[shutdown-shim]: error initiating component shutdown, system shutdown impossible: {e}"
325            );
326            // Recovery from this state is impossible. Exit with a non-zero exit code,
327            // so our critical marking causes the system to forcefully restart.
328            Self::abort(self.abort_tx.clone()).await;
329        }
330    }
331
332    async fn initiate_component_shutdown(&self) -> Result<(), anyhow::Error> {
333        println!("[shutdown-shim] shutting down components");
334        let system_controller_client = self
335            .connect_to_protocol::<SystemControllerMarker>()
336            .context("error connecting to component_manager")?;
337
338        system_controller_client.shutdown().await.context("failed to initiate shutdown")
339    }
340
341    async fn acquire_shutdown_control_lease(&self) -> Option<zx::EventPair> {
342        if !self.config.suspend_enabled {
343            return None;
344        }
345        let res = async {
346            let activity_governor = self
347                .connect_to_protocol::<fsystem::ActivityGovernorMarker>()
348                .context("error connecting to system_activity_governor")?;
349            activity_governor
350                .acquire_wake_lease("shutdown_control")
351                .await
352                .context("failed to acquire wake lease")
353        }
354        .await;
355        match res {
356            Ok(Ok(token)) => Some(token),
357            e => {
358                eprintln!("[shutdown-shim]: {:?}", e);
359                None
360            }
361        }
362    }
363
364    /// Cause the program to terminate.
365    async fn abort(mut abort_tx: mpsc::UnboundedSender<()>) -> ! {
366        let _ = abort_tx.send(()).await;
367        std::future::pending::<()>().await;
368        unreachable!();
369    }
370
371    fn connect_to_protocol<P: DiscoverableProtocolMarker>(
372        &self,
373    ) -> Result<P::Proxy, anyhow::Error> {
374        client::connect_to_protocol_at_dir_root::<P>(&self.svc)
375    }
376}
377
378impl<D: Directory + AsRefDirectory> collaborative_reboot::RebootActuator for ProgramContext<D> {
379    async fn perform_reboot(
380        &self,
381        reasons: Vec<CollaborativeRebootReason>,
382    ) -> Result<(), zx::Status> {
383        // Transform the reasons, and dispatch the request along the standard
384        // reboot pipeline.
385        let reasons = reasons
386            .into_iter()
387            .map(|reason| match reason {
388                CollaborativeRebootReason::SystemUpdate => ShutdownReason::SystemUpdate,
389            })
390            .collect();
391        self.shutdown(
392            SystemPowerState::Reboot,
393            Some(ShutdownOptionsWrapper { action: ShutdownAction::Reboot, reasons }),
394        )
395        .await
396    }
397}
398
399struct SystemState {
400    power_state: SystemPowerState,
401}
402
403impl SystemState {
404    fn new() -> Self {
405        Self { power_state: SystemPowerState::FullyOn }
406    }
407}
408
409static SYSTEM_STATE: LazyLock<Mutex<SystemState>> =
410    LazyLock::new(|| Mutex::new(SystemState::new()));
411
412fn set_system_power_state(new: SystemPowerState) {
413    let mut s = (*SYSTEM_STATE).lock();
414    s.power_state = new;
415}