blob: 66ee9772af36c9704696937cff7c976a9e31f303 [file] [log] [blame]
Keun-young Park8d01f632017-03-13 11:54:47 -07001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Tom Cherry3f5eaae52017-04-06 16:30:22 -070016
17#include "reboot.h"
18
Keun-young Park8d01f632017-03-13 11:54:47 -070019#include <dirent.h>
20#include <fcntl.h>
Jaegeuk Kim3e595d52022-04-15 12:31:46 -070021#include <linux/f2fs.h>
Keun-young Park2ba5c812017-03-29 12:54:40 -070022#include <linux/fs.h>
Jaegeuk Kim2aedc822018-11-20 13:27:06 -080023#include <linux/loop.h>
josephjangaaddf282019-04-16 18:46:24 +080024#include <mntent.h>
25#include <semaphore.h>
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010026#include <stdlib.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070027#include <sys/cdefs.h>
Keun-young Park2ba5c812017-03-29 12:54:40 -070028#include <sys/ioctl.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070029#include <sys/mount.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070030#include <sys/stat.h>
josephjangaaddf282019-04-16 18:46:24 +080031#include <sys/swap.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070032#include <sys/syscall.h>
33#include <sys/types.h>
34#include <sys/wait.h>
35
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010036#include <chrono>
Keun-young Park8d01f632017-03-13 11:54:47 -070037#include <memory>
Keun-young Park7830d592017-03-27 16:07:02 -070038#include <set>
Keun-young Park8d01f632017-03-13 11:54:47 -070039#include <thread>
40#include <vector>
41
Nikita Ioffe23dbd6d2019-11-14 01:21:24 +000042#include <InitProperties.sysprop.h>
Tom Cherryede0d532017-07-06 14:20:11 -070043#include <android-base/chrono_utils.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070044#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070045#include <android-base/logging.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070046#include <android-base/macros.h>
Tom Cherryccf23532017-03-28 16:40:41 -070047#include <android-base/properties.h>
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010048#include <android-base/scopeguard.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070049#include <android-base/strings.h>
Keun-young Park2ba5c812017-03-29 12:54:40 -070050#include <android-base/unique_fd.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070051#include <bootloader_message/bootloader_message.h>
52#include <cutils/android_reboot.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070053#include <fs_mgr.h>
Akilesh Kailash2c52d092023-01-03 04:39:28 +000054#include <libsnapshot/snapshot.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070055#include <logwrap/logwrap.h>
Todd Poynorfc827be2017-04-13 15:17:24 -070056#include <private/android_filesystem_config.h>
Tom Cherry0c8d6d22017-08-10 12:22:44 -070057#include <selinux/selinux.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070058
Nikita Ioffeba6968e2019-10-07 16:26:33 +010059#include "action.h"
Tom Cherry7fd3bc22018-02-13 15:36:14 -080060#include "action_manager.h"
Nikita Ioffeba6968e2019-10-07 16:26:33 +010061#include "builtin_arguments.h"
Wei Wangeeab4912017-06-27 22:08:45 -070062#include "init.h"
Nikita Ioffeab91ee92019-11-06 21:40:31 +000063#include "mount_namespace.h"
Tom Cherry802864c2020-03-12 14:29:25 -070064#include "property_service.h"
Tom Cherry44aceed2018-08-03 13:36:18 -070065#include "reboot_utils.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070066#include "service.h"
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070067#include "service_list.h"
Luis Hector Chavez9f97f472017-09-06 13:43:57 -070068#include "sigchld_handler.h"
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010069#include "util.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070070
Tom Cherry2436e6b2019-09-19 11:16:19 -070071using namespace std::literals;
72
Nikita Ioffec0df1872019-11-13 21:47:06 +000073using android::base::boot_clock;
Tom Cherry4f4cacc2019-01-08 10:39:00 -080074using android::base::GetBoolProperty;
Nikita Ioffe7b41a152020-03-25 00:06:51 +000075using android::base::GetUintProperty;
Nikita Ioffec0df1872019-11-13 21:47:06 +000076using android::base::SetProperty;
Mark Salyzyn62909822017-10-09 09:27:16 -070077using android::base::Split;
Tom Cherryede0d532017-07-06 14:20:11 -070078using android::base::Timer;
Jaegeuk Kim2aedc822018-11-20 13:27:06 -080079using android::base::unique_fd;
Nikita Ioffec0df1872019-11-13 21:47:06 +000080using android::base::WaitForProperty;
josephjangaaddf282019-04-16 18:46:24 +080081using android::base::WriteStringToFile;
Keun-young Park8d01f632017-03-13 11:54:47 -070082
Tom Cherry81f5d3e2017-06-22 12:53:17 -070083namespace android {
84namespace init {
85
Nikita Ioffeba6968e2019-10-07 16:26:33 +010086static bool shutting_down = false;
87
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010088static const std::set<std::string> kDebuggingServices{"tombstoned", "logd", "adbd", "console"};
89
Nikita Ioffed485bbb2020-02-26 15:18:56 +000090static void PersistRebootReason(const char* reason, bool write_to_property) {
91 if (write_to_property) {
92 SetProperty(LAST_REBOOT_REASON_PROPERTY, reason);
93 }
Tom Cherry10615eb2020-03-31 16:31:37 -070094 auto fd = unique_fd(TEMP_FAILURE_RETRY(open(
95 LAST_REBOOT_REASON_FILE, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY, 0666)));
96 if (!fd.ok()) {
97 PLOG(ERROR) << "Could not open '" << LAST_REBOOT_REASON_FILE
98 << "' to persist reboot reason";
99 return;
100 }
101 WriteStringToFd(reason, fd);
102 fsync(fd.get());
Nikita Ioffed0bc0b62020-02-19 16:21:11 +0000103}
104
Keun-young Park8d01f632017-03-13 11:54:47 -0700105// represents umount status during reboot / shutdown.
106enum UmountStat {
107 /* umount succeeded. */
108 UMOUNT_STAT_SUCCESS = 0,
109 /* umount was not run. */
110 UMOUNT_STAT_SKIPPED = 1,
111 /* umount failed with timeout. */
112 UMOUNT_STAT_TIMEOUT = 2,
113 /* could not run due to error */
114 UMOUNT_STAT_ERROR = 3,
115 /* not used by init but reserved for other part to use this to represent the
116 the state where umount status before reboot is not found / available. */
117 UMOUNT_STAT_NOT_AVAILABLE = 4,
118};
119
120// Utility for struct mntent
121class MountEntry {
122 public:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700123 explicit MountEntry(const mntent& entry)
Keun-young Park8d01f632017-03-13 11:54:47 -0700124 : mnt_fsname_(entry.mnt_fsname),
125 mnt_dir_(entry.mnt_dir),
126 mnt_type_(entry.mnt_type),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700127 mnt_opts_(entry.mnt_opts) {}
Keun-young Park8d01f632017-03-13 11:54:47 -0700128
Jaegeuk Kim0f04f722017-09-25 10:55:39 -0700129 bool Umount(bool force) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800130 LOG(INFO) << "Unmounting " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Jaegeuk Kim0f04f722017-09-25 10:55:39 -0700131 int r = umount2(mnt_dir_.c_str(), force ? MNT_FORCE : 0);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700132 if (r == 0) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800133 LOG(INFO) << "Umounted " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700134 return true;
135 } else {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800136 PLOG(WARNING) << "Cannot umount " << mnt_fsname_ << ":" << mnt_dir_ << " opts "
Keun-young Park2ba5c812017-03-29 12:54:40 -0700137 << mnt_opts_;
138 return false;
139 }
140 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700141
Keun-young Park2ba5c812017-03-29 12:54:40 -0700142 void DoFsck() {
143 int st;
144 if (IsF2Fs()) {
145 const char* f2fs_argv[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800146 "/system/bin/fsck.f2fs",
147 "-a",
148 mnt_fsname_.c_str(),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700149 };
Tom Cherry3a803eb2019-09-25 16:23:50 -0700150 logwrap_fork_execvp(arraysize(f2fs_argv), f2fs_argv, &st, false, LOG_KLOG, true,
151 nullptr);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700152 } else if (IsExt4()) {
153 const char* ext4_argv[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800154 "/system/bin/e2fsck",
155 "-y",
156 mnt_fsname_.c_str(),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700157 };
Tom Cherry3a803eb2019-09-25 16:23:50 -0700158 logwrap_fork_execvp(arraysize(ext4_argv), ext4_argv, &st, false, LOG_KLOG, true,
159 nullptr);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700160 }
161 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700162
163 static bool IsBlockDevice(const struct mntent& mntent) {
164 return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
165 }
166
167 static bool IsEmulatedDevice(const struct mntent& mntent) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700168 return android::base::StartsWith(mntent.mnt_fsname, "/data/");
Keun-young Park8d01f632017-03-13 11:54:47 -0700169 }
170
171 private:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700172 bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
173
174 bool IsExt4() const { return mnt_type_ == "ext4"; }
175
Keun-young Park8d01f632017-03-13 11:54:47 -0700176 std::string mnt_fsname_;
177 std::string mnt_dir_;
178 std::string mnt_type_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700179 std::string mnt_opts_;
Keun-young Park8d01f632017-03-13 11:54:47 -0700180};
181
182// Turn off backlight while we are performing power down cleanup activities.
Tom Cherry832f9f12020-03-10 11:47:24 -0700183static void TurnOffBacklight() {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800184 Service* service = ServiceList::GetInstance().FindService("blank_screen");
185 if (service == nullptr) {
186 LOG(WARNING) << "cannot find blank_screen in TurnOffBacklight";
Keun-young Park8d01f632017-03-13 11:54:47 -0700187 return;
188 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900189 if (auto result = service->Start(); !result.ok()) {
Tom Cherryd9872642018-10-11 10:38:05 -0700190 LOG(WARNING) << "Could not start blank_screen service: " << result.error();
191 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700192}
193
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000194static Result<void> CallVdc(const std::string& system, const std::string& cmd) {
Nikita Ioffea3be9962020-04-16 21:37:03 +0100195 LOG(INFO) << "Calling /system/bin/vdc " << system << " " << cmd;
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000196 const char* vdc_argv[] = {"/system/bin/vdc", system.c_str(), cmd.c_str()};
Keun-young Park8d01f632017-03-13 11:54:47 -0700197 int status;
Nikita Ioffe12a36072019-10-23 20:11:32 +0100198 if (logwrap_fork_execvp(arraysize(vdc_argv), vdc_argv, &status, false, LOG_KLOG, true,
199 nullptr) != 0) {
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000200 return ErrnoError() << "Failed to call '/system/bin/vdc " << system << " " << cmd << "'";
Nikita Ioffe12a36072019-10-23 20:11:32 +0100201 }
202 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
203 return {};
204 }
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000205 return Error() << "'/system/bin/vdc " << system << " " << cmd << "' failed : " << status;
Keun-young Park8d01f632017-03-13 11:54:47 -0700206}
207
208static void LogShutdownTime(UmountStat stat, Timer* t) {
Tom Cherryede0d532017-07-06 14:20:11 -0700209 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration().count()) << ":"
210 << stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700211}
212
Jaegeuk Kim3e595d52022-04-15 12:31:46 -0700213static bool IsDataMounted(const std::string& fstype) {
Tom Cherry2436e6b2019-09-19 11:16:19 -0700214 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
215 if (fp == nullptr) {
216 PLOG(ERROR) << "Failed to open /proc/mounts";
217 return false;
218 }
219 mntent* mentry;
220 while ((mentry = getmntent(fp.get())) != nullptr) {
221 if (mentry->mnt_dir == "/data"s) {
Jaegeuk Kim3e595d52022-04-15 12:31:46 -0700222 return fstype == "*" || mentry->mnt_type == fstype;
Tom Cherry2436e6b2019-09-19 11:16:19 -0700223 }
224 }
225 return false;
226}
227
228// Find all read+write block devices and emulated devices in /proc/mounts and add them to
229// the correpsponding list.
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100230static bool FindPartitionsToUmount(std::vector<MountEntry>* block_dev_partitions,
231 std::vector<MountEntry>* emulated_partitions, bool dump) {
Tom Cherryf274e782018-10-03 13:13:41 -0700232 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
Keun-young Park8d01f632017-03-13 11:54:47 -0700233 if (fp == nullptr) {
234 PLOG(ERROR) << "Failed to open /proc/mounts";
235 return false;
236 }
237 mntent* mentry;
238 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700239 if (dump) {
240 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
241 << mentry->mnt_opts << " type " << mentry->mnt_type;
242 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
Keun-young Park6e12b382017-07-17 12:20:33 -0700243 std::string mount_dir(mentry->mnt_dir);
244 // These are R/O partitions changed to R/W after adb remount.
245 // Do not umount them as shutdown critical services may rely on them.
Wei Wanga01c27e2017-07-25 10:52:08 -0700246 if (mount_dir != "/" && mount_dir != "/system" && mount_dir != "/vendor" &&
247 mount_dir != "/oem") {
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100248 block_dev_partitions->emplace(block_dev_partitions->begin(), *mentry);
Keun-young Park6e12b382017-07-17 12:20:33 -0700249 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700250 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100251 emulated_partitions->emplace(emulated_partitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700252 }
253 }
254 return true;
255}
256
Jonglin Lee28a2c922019-01-15 16:38:44 -0800257static void DumpUmountDebuggingInfo() {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700258 int status;
259 if (!security_getenforce()) {
260 LOG(INFO) << "Run lsof";
261 const char* lsof_argv[] = {"/system/bin/lsof"};
Tom Cherry3a803eb2019-09-25 16:23:50 -0700262 logwrap_fork_execvp(arraysize(lsof_argv), lsof_argv, &status, false, LOG_KLOG, true,
263 nullptr);
Keun-young Park8d01f632017-03-13 11:54:47 -0700264 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700265 FindPartitionsToUmount(nullptr, nullptr, true);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800266 // dump current CPU stack traces and uninterruptible tasks
josephjangaaddf282019-04-16 18:46:24 +0800267 WriteStringToFile("l", PROC_SYSRQ);
268 WriteStringToFile("w", PROC_SYSRQ);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700269}
270
Tom Cherryede0d532017-07-06 14:20:11 -0700271static UmountStat UmountPartitions(std::chrono::milliseconds timeout) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700272 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700273 /* data partition needs all pending writes to be completed and all emulated partitions
274 * umounted.If the current waiting is not good enough, give
275 * up and leave it to e2fsck after reboot to fix it.
276 */
277 while (true) {
278 std::vector<MountEntry> block_devices;
279 std::vector<MountEntry> emulated_devices;
280 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
281 return UMOUNT_STAT_ERROR;
282 }
283 if (block_devices.size() == 0) {
Wei Wang8c00e422017-08-16 14:01:46 -0700284 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700285 }
Wei Wang8c00e422017-08-16 14:01:46 -0700286 bool unmount_done = true;
287 if (emulated_devices.size() > 0) {
Wei Wang25dc30f2017-10-23 15:32:03 -0700288 for (auto& entry : emulated_devices) {
289 if (!entry.Umount(false)) unmount_done = false;
290 }
Wei Wang8c00e422017-08-16 14:01:46 -0700291 if (unmount_done) {
292 sync();
293 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700294 }
Wei Wang25dc30f2017-10-23 15:32:03 -0700295 for (auto& entry : block_devices) {
296 if (!entry.Umount(timeout == 0ms)) unmount_done = false;
297 }
Wei Wang8c00e422017-08-16 14:01:46 -0700298 if (unmount_done) {
299 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700300 }
Wei Wang8c00e422017-08-16 14:01:46 -0700301 if ((timeout < t.duration())) { // try umount at least once
302 return UMOUNT_STAT_TIMEOUT;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700303 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700304 std::this_thread::sleep_for(100ms);
305 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700306}
307
josephjangaaddf282019-04-16 18:46:24 +0800308static void KillAllProcesses() {
309 WriteStringToFile("i", PROC_SYSRQ);
310}
311
312// Create reboot/shutdwon monitor thread
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100313void RebootMonitorThread(unsigned int cmd, const std::string& reboot_target,
314 sem_t* reboot_semaphore, std::chrono::milliseconds shutdown_timeout,
315 bool* reboot_monitor_run) {
josephjangaaddf282019-04-16 18:46:24 +0800316 unsigned int remaining_shutdown_time = 0;
317
Tom Cherry10615eb2020-03-31 16:31:37 -0700318 // 300 seconds more than the timeout passed to the thread as there is a final Umount pass
josephjangaaddf282019-04-16 18:46:24 +0800319 // after the timeout is reached.
Tom Cherry10615eb2020-03-31 16:31:37 -0700320 constexpr unsigned int shutdown_watchdog_timeout_default = 300;
josephjangaaddf282019-04-16 18:46:24 +0800321 auto shutdown_watchdog_timeout = android::base::GetUintProperty(
322 "ro.build.shutdown.watchdog.timeout", shutdown_watchdog_timeout_default);
323 remaining_shutdown_time = shutdown_watchdog_timeout + shutdown_timeout.count() / 1000;
324
325 while (*reboot_monitor_run == true) {
326 if (TEMP_FAILURE_RETRY(sem_wait(reboot_semaphore)) == -1) {
327 LOG(ERROR) << "sem_wait failed and exit RebootMonitorThread()";
328 return;
329 }
330
331 timespec shutdown_timeout_timespec;
332 if (clock_gettime(CLOCK_MONOTONIC, &shutdown_timeout_timespec) == -1) {
333 LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
334 return;
335 }
336
337 // If there are some remaining shutdown time left from previous round, we use
338 // remaining time here.
339 shutdown_timeout_timespec.tv_sec += remaining_shutdown_time;
340
341 LOG(INFO) << "shutdown_timeout_timespec.tv_sec: " << shutdown_timeout_timespec.tv_sec;
342
343 int sem_return = 0;
344 while ((sem_return = sem_timedwait_monotonic_np(reboot_semaphore,
345 &shutdown_timeout_timespec)) == -1 &&
346 errno == EINTR) {
347 }
348
349 if (sem_return == -1) {
350 LOG(ERROR) << "Reboot thread timed out";
351
352 if (android::base::GetBoolProperty("ro.debuggable", false) == true) {
Tom Cherry2436e6b2019-09-19 11:16:19 -0700353 if (false) {
354 // SEPolicy will block debuggerd from running and this is intentional.
355 // But these lines are left to be enabled during debugging.
356 LOG(INFO) << "Try to dump init process call trace:";
357 const char* vdc_argv[] = {"/system/bin/debuggerd", "-b", "1"};
358 int status;
Tom Cherry3a803eb2019-09-25 16:23:50 -0700359 logwrap_fork_execvp(arraysize(vdc_argv), vdc_argv, &status, false, LOG_KLOG,
360 true, nullptr);
Tom Cherry2436e6b2019-09-19 11:16:19 -0700361 }
josephjangaaddf282019-04-16 18:46:24 +0800362 LOG(INFO) << "Show stack for all active CPU:";
363 WriteStringToFile("l", PROC_SYSRQ);
364
365 LOG(INFO) << "Show tasks that are in disk sleep(uninterruptable sleep), which are "
366 "like "
367 "blocked in mutex or hardware register access:";
368 WriteStringToFile("w", PROC_SYSRQ);
369 }
370
371 // In shutdown case,notify kernel to sync and umount fs to read-only before shutdown.
372 if (cmd == ANDROID_RB_POWEROFF || cmd == ANDROID_RB_THERMOFF) {
373 WriteStringToFile("s", PROC_SYSRQ);
374
375 WriteStringToFile("u", PROC_SYSRQ);
376
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100377 RebootSystem(cmd, reboot_target);
josephjangaaddf282019-04-16 18:46:24 +0800378 }
379
380 LOG(ERROR) << "Trigger crash at last!";
381 WriteStringToFile("c", PROC_SYSRQ);
382 } else {
383 timespec current_time_timespec;
384
385 if (clock_gettime(CLOCK_MONOTONIC, &current_time_timespec) == -1) {
386 LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
387 return;
388 }
389
390 remaining_shutdown_time =
391 shutdown_timeout_timespec.tv_sec - current_time_timespec.tv_sec;
392
393 LOG(INFO) << "remaining_shutdown_time: " << remaining_shutdown_time;
394 }
395 }
396}
Keun-young Park3ee0df92017-03-27 11:21:09 -0700397
Keun-young Park8d01f632017-03-13 11:54:47 -0700398/* Try umounting all emulated file systems R/W block device cfile systems.
399 * This will just try umount and give it up if it fails.
400 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
401 * and necessary check can be done at the next reboot.
402 * For safer shutdown, caller needs to make sure that
403 * all processes / emulated partition for the target fs are all cleaned-up.
404 *
405 * return true when umount was successful. false when timed out.
406 */
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100407static UmountStat TryUmountAndFsck(unsigned int cmd, bool run_fsck,
josephjangaaddf282019-04-16 18:46:24 +0800408 std::chrono::milliseconds timeout, sem_t* reboot_semaphore) {
Keun-young Park3ee0df92017-03-27 11:21:09 -0700409 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700410 std::vector<MountEntry> block_devices;
411 std::vector<MountEntry> emulated_devices;
Keun-young Park8d01f632017-03-13 11:54:47 -0700412
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100413 if (run_fsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700414 return UMOUNT_STAT_ERROR;
415 }
Akilesh Kailash2c52d092023-01-03 04:39:28 +0000416 auto sm = snapshot::SnapshotManager::New();
417 bool ota_update_in_progress = false;
418 if (sm->IsUserspaceSnapshotUpdateInProgress()) {
419 LOG(INFO) << "OTA update in progress";
420 ota_update_in_progress = true;
421 }
Tom Cherryede0d532017-07-06 14:20:11 -0700422 UmountStat stat = UmountPartitions(timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700423 if (stat != UMOUNT_STAT_SUCCESS) {
424 LOG(INFO) << "umount timeout, last resort, kill all and try";
Jonglin Lee28a2c922019-01-15 16:38:44 -0800425 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Akilesh Kailash2c52d092023-01-03 04:39:28 +0000426 // Since umount timedout, we will try to kill all processes
427 // and do one more attempt to umount the partitions.
428 //
429 // However, if OTA update is in progress, we don't want
430 // to kill the snapuserd daemon as the daemon will
431 // be serving I/O requests. Killing the daemon will
432 // end up with I/O failures. If the update is in progress,
433 // we will just return the umount failure status immediately.
434 // This is ok, given the fact that killing the processes
435 // and doing an umount is just a last effort. We are
436 // still not doing fsck when all processes are killed.
437 //
438 if (ota_update_in_progress) {
439 return stat;
440 }
Keun-young Park3ee0df92017-03-27 11:21:09 -0700441 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700442 // even if it succeeds, still it is timeout and do not run fsck with all processes killed
Keun-young Parkc59b8222017-07-18 18:52:25 -0700443 UmountStat st = UmountPartitions(0ms);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800444 if ((st != UMOUNT_STAT_SUCCESS) && DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park8d01f632017-03-13 11:54:47 -0700445 }
446
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100447 if (stat == UMOUNT_STAT_SUCCESS && run_fsck) {
josephjangaaddf282019-04-16 18:46:24 +0800448 LOG(INFO) << "Pause reboot monitor thread before fsck";
449 sem_post(reboot_semaphore);
450
Keun-young Park2ba5c812017-03-29 12:54:40 -0700451 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
452 // and should not affect reboot time.
453 for (auto& entry : block_devices) {
454 entry.DoFsck();
455 }
josephjangaaddf282019-04-16 18:46:24 +0800456
457 LOG(INFO) << "Resume reboot monitor thread after fsck";
458 sem_post(reboot_semaphore);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700459 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700460 return stat;
461}
462
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800463// zram is able to use backing device on top of a loopback device.
464// In order to unmount /data successfully, we have to kill the loopback device first
luwei98a3653c2021-04-14 14:34:59 +0800465#define ZRAM_DEVICE "/dev/block/zram0"
466#define ZRAM_RESET "/sys/block/zram0/reset"
467#define ZRAM_BACK_DEV "/sys/block/zram0/backing_dev"
468#define ZRAM_INITSTATE "/sys/block/zram0/initstate"
Nikita Ioffe12a36072019-10-23 20:11:32 +0100469static Result<void> KillZramBackingDevice() {
luwei98a3653c2021-04-14 14:34:59 +0800470 std::string zram_initstate;
471 if (!android::base::ReadFileToString(ZRAM_INITSTATE, &zram_initstate)) {
472 return ErrnoError() << "Failed to read " << ZRAM_INITSTATE;
473 }
474
475 zram_initstate.erase(zram_initstate.length() - 1);
476 if (zram_initstate == "0") {
477 LOG(INFO) << "Zram has not been swapped on";
478 return {};
479 }
480
Nikita Ioffea3be9962020-04-16 21:37:03 +0100481 if (access(ZRAM_BACK_DEV, F_OK) != 0 && errno == ENOENT) {
482 LOG(INFO) << "No zram backing device configured";
483 return {};
484 }
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800485 std::string backing_dev;
Nikita Ioffea3be9962020-04-16 21:37:03 +0100486 if (!android::base::ReadFileToString(ZRAM_BACK_DEV, &backing_dev)) {
487 return ErrnoError() << "Failed to read " << ZRAM_BACK_DEV;
488 }
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800489
490 // cut the last "\n"
491 backing_dev.erase(backing_dev.length() - 1);
492
shisiyuan423c4f12021-05-18 11:47:43 +0800493 if (android::base::StartsWith(backing_dev, "none")) {
494 LOG(INFO) << "No zram backing device configured";
495 return {};
496 }
497
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800498 // shutdown zram handle
499 Timer swap_timer;
500 LOG(INFO) << "swapoff() start...";
501 if (swapoff(ZRAM_DEVICE) == -1) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100502 return ErrnoError() << "zram_backing_dev: swapoff (" << backing_dev << ")"
503 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800504 }
JeongHyeon Lee170855d2022-04-14 18:06:18 +0900505 LOG(INFO) << "swapoff() took " << swap_timer;
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800506
josephjangaaddf282019-04-16 18:46:24 +0800507 if (!WriteStringToFile("1", ZRAM_RESET)) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100508 return Error() << "zram_backing_dev: reset (" << backing_dev << ")"
509 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800510 }
511
Nikita Ioffea3be9962020-04-16 21:37:03 +0100512 if (!android::base::StartsWith(backing_dev, "/dev/block/loop")) {
513 LOG(INFO) << backing_dev << " is not a loop device. Exiting early";
514 return {};
515 }
516
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800517 // clear loopback device
518 unique_fd loop(TEMP_FAILURE_RETRY(open(backing_dev.c_str(), O_RDWR | O_CLOEXEC)));
519 if (loop.get() < 0) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100520 return ErrnoError() << "zram_backing_dev: open(" << backing_dev << ")"
521 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800522 }
523
524 if (ioctl(loop.get(), LOOP_CLR_FD, 0) < 0) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100525 return ErrnoError() << "zram_backing_dev: loop_clear (" << backing_dev << ")"
526 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800527 }
528 LOG(INFO) << "zram_backing_dev: `" << backing_dev << "` is cleared successfully.";
Nikita Ioffe12a36072019-10-23 20:11:32 +0100529 return {};
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800530}
531
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100532// Stops given services, waits for them to be stopped for |timeout| ms.
533// If terminate is true, then SIGTERM is sent to services, otherwise SIGKILL is sent.
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000534// Note that services are stopped in order given by |ServiceList::services_in_shutdown_order|
535// function.
536static void StopServices(const std::set<std::string>& services, std::chrono::milliseconds timeout,
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100537 bool terminate) {
538 LOG(INFO) << "Stopping " << services.size() << " services by sending "
539 << (terminate ? "SIGTERM" : "SIGKILL");
540 std::vector<pid_t> pids;
541 pids.reserve(services.size());
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000542 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
543 if (services.count(s->name()) == 0) {
544 continue;
545 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100546 if (s->pid() > 0) {
547 pids.push_back(s->pid());
548 }
549 if (terminate) {
550 s->Terminate();
551 } else {
552 s->Stop();
553 }
554 }
555 if (timeout > 0ms) {
Bart Van Assche97047b52023-11-16 12:42:35 -0800556 WaitToBeReaped(Service::GetSigchldFd(), pids, timeout);
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100557 } else {
558 // Even if we don't to wait for services to stop, we still optimistically reap zombies.
559 ReapAnyOutstandingChildren();
560 }
561}
562
563// Like StopServices, but also logs all the services that failed to stop after the provided timeout.
564// Returns number of violators.
Nikita Ioffe660ffde2020-12-10 16:52:35 +0000565int StopServicesAndLogViolations(const std::set<std::string>& services,
566 std::chrono::milliseconds timeout, bool terminate) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100567 StopServices(services, timeout, terminate);
568 int still_running = 0;
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000569 for (const auto& s : ServiceList::GetInstance()) {
570 if (s->IsRunning() && services.count(s->name())) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100571 LOG(ERROR) << "[service-misbehaving] : service '" << s->name() << "' is still running "
572 << timeout.count() << "ms after receiving "
573 << (terminate ? "SIGTERM" : "SIGKILL");
574 still_running++;
575 }
576 }
577 return still_running;
578}
579
Nikita Ioffe91a98482020-06-10 00:53:59 +0100580static Result<void> UnmountAllApexes() {
Inseob Kim0fbc1d72022-11-09 12:50:14 +0900581 // don't need to unmount because apexd doesn't use /data in Microdroid
582 if (IsMicrodroid()) {
583 return {};
584 }
585
Nikita Ioffe91a98482020-06-10 00:53:59 +0100586 const char* args[] = {"/system/bin/apexd", "--unmount-all"};
587 int status;
588 if (logwrap_fork_execvp(arraysize(args), args, &status, false, LOG_KLOG, true, nullptr) != 0) {
589 return ErrnoError() << "Failed to call '/system/bin/apexd --unmount-all'";
590 }
591 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
592 return {};
593 }
594 return Error() << "'/system/bin/apexd --unmount-all' failed : " << status;
595}
596
Tom Cherry44aceed2018-08-03 13:36:18 -0700597//* Reboot / shutdown the system.
598// cmd ANDROID_RB_* as defined in android_reboot.h
599// reason Reason string like "reboot", "shutdown,userrequested"
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100600// reboot_target Reboot target string like "bootloader". Otherwise, it should be an empty string.
601// run_fsck Whether to run fsck after umount is done.
Tom Cherry44aceed2018-08-03 13:36:18 -0700602//
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100603static void DoReboot(unsigned int cmd, const std::string& reason, const std::string& reboot_target,
604 bool run_fsck) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700605 Timer t;
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100606 LOG(INFO) << "Reboot start, reason: " << reason << ", reboot_target: " << reboot_target;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700607
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700608 bool is_thermal_shutdown = cmd == ANDROID_RB_THERMOFF;
609
610 auto shutdown_timeout = 0ms;
611 if (!SHUTDOWN_ZERO_TIMEOUT) {
Wei Wangb5de0882018-10-09 12:42:06 -0700612 constexpr unsigned int shutdown_timeout_default = 6;
613 constexpr unsigned int max_thermal_shutdown_timeout = 3;
614 auto shutdown_timeout_final = android::base::GetUintProperty("ro.build.shutdown_timeout",
615 shutdown_timeout_default);
616 if (is_thermal_shutdown && shutdown_timeout_final > max_thermal_shutdown_timeout) {
617 shutdown_timeout_final = max_thermal_shutdown_timeout;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700618 }
Wei Wangb5de0882018-10-09 12:42:06 -0700619 shutdown_timeout = std::chrono::seconds(shutdown_timeout_final);
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700620 }
621 LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " ms";
622
josephjangaaddf282019-04-16 18:46:24 +0800623 sem_t reboot_semaphore;
624 if (sem_init(&reboot_semaphore, false, 0) == -1) {
625 // These should never fail, but if they do, skip the graceful reboot and reboot immediately.
626 LOG(ERROR) << "sem_init() fail and RebootSystem() return!";
Sayanna Chandula5754b5a2022-10-04 15:06:05 -0700627 RebootSystem(cmd, reboot_target, reason);
josephjangaaddf282019-04-16 18:46:24 +0800628 }
629
630 // Start a thread to monitor init shutdown process
631 LOG(INFO) << "Create reboot monitor thread.";
632 bool reboot_monitor_run = true;
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100633 std::thread reboot_monitor_thread(&RebootMonitorThread, cmd, reboot_target, &reboot_semaphore,
josephjangaaddf282019-04-16 18:46:24 +0800634 shutdown_timeout, &reboot_monitor_run);
635 reboot_monitor_thread.detach();
636
637 // Start reboot monitor thread
638 sem_post(&reboot_semaphore);
639
Tom Cherry10615eb2020-03-31 16:31:37 -0700640 // Ensure last reboot reason is reduced to canonical
641 // alias reported in bootloader or system boot reason.
642 size_t skip = 0;
643 std::vector<std::string> reasons = Split(reason, ",");
644 if (reasons.size() >= 2 && reasons[0] == "reboot" &&
645 (reasons[1] == "recovery" || reasons[1] == "bootloader" || reasons[1] == "cold" ||
646 reasons[1] == "hard" || reasons[1] == "warm")) {
647 skip = strlen("reboot,");
648 }
649 PersistRebootReason(reason.c_str() + skip, true);
650
651 // If /data isn't mounted then we can skip the extra reboot steps below, since we don't need to
652 // worry about unmounting it.
Jaegeuk Kim3e595d52022-04-15 12:31:46 -0700653 if (!IsDataMounted("*")) {
Tom Cherry10615eb2020-03-31 16:31:37 -0700654 sync();
Sayanna Chandula5754b5a2022-10-04 15:06:05 -0700655 RebootSystem(cmd, reboot_target, reason);
Tom Cherry10615eb2020-03-31 16:31:37 -0700656 abort();
657 }
658
zengshuchuan21c97a52021-08-10 14:04:34 +0800659 bool do_shutdown_animation = GetBoolProperty("ro.init.shutdown_animation", false);
Keun-young Park7830d592017-03-27 16:07:02 -0700660 // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700661 const std::set<std::string> to_starts{"watchdogd"};
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000662 std::set<std::string> stop_first;
Tom Cherry911b9b12017-07-27 16:20:58 -0700663 for (const auto& s : ServiceList::GetInstance()) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100664 if (kDebuggingServices.count(s->name())) {
665 // keep debugging tools until non critical ones are all gone.
Keun-young Park7830d592017-03-27 16:07:02 -0700666 s->SetShutdownCritical();
667 } else if (to_starts.count(s->name())) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900668 if (auto result = s->Start(); !result.ok()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700669 LOG(ERROR) << "Could not start shutdown 'to_start' service '" << s->name()
670 << "': " << result.error();
671 }
Keun-young Park7830d592017-03-27 16:07:02 -0700672 s->SetShutdownCritical();
David Anderson07533c52023-06-02 12:00:12 -0700673 } else if (do_shutdown_animation && s->classnames().count("animation") > 0) {
674 // Need these for shutdown animations.
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700675 } else if (s->IsShutdownCritical()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700676 // Start shutdown critical service if not started.
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900677 if (auto result = s->Start(); !result.ok()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700678 LOG(ERROR) << "Could not start shutdown critical service '" << s->name()
679 << "': " << result.error();
680 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100681 } else {
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000682 stop_first.insert(s->name());
Keun-young Park8d01f632017-03-13 11:54:47 -0700683 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700684 }
Keun-young Park7830d592017-03-27 16:07:02 -0700685
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800686 // remaining operations (specifically fsck) may take a substantial duration
zengshuchuan21c97a52021-08-10 14:04:34 +0800687 if (!do_shutdown_animation && (cmd == ANDROID_RB_POWEROFF || is_thermal_shutdown)) {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800688 TurnOffBacklight();
689 }
690
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100691 Service* boot_anim = ServiceList::GetInstance().FindService("bootanim");
692 Service* surface_flinger = ServiceList::GetInstance().FindService("surfaceflinger");
693 if (boot_anim != nullptr && surface_flinger != nullptr && surface_flinger->IsRunning()) {
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800694
695 if (do_shutdown_animation) {
Tom Cherryc88d8f92019-08-19 15:21:25 -0700696 SetProperty("service.bootanim.exit", "0");
Nicolas Geoffraye106f0a2020-12-15 18:34:47 +0000697 SetProperty("service.bootanim.progress", "0");
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800698 // Could be in the middle of animation. Stop and start so that it can pick
699 // up the right mode.
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100700 boot_anim->Stop();
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800701 }
702
Tom Cherry911b9b12017-07-27 16:20:58 -0700703 for (const auto& service : ServiceList::GetInstance()) {
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800704 if (service->classnames().count("animation") == 0) {
705 continue;
706 }
707
708 // start all animation classes if stopped.
709 if (do_shutdown_animation) {
Tom Cherry9949ec52019-05-16 16:54:49 -0700710 service->Start();
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800711 }
712 service->SetShutdownCritical(); // will not check animation class separately
713 }
714
715 if (do_shutdown_animation) {
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100716 boot_anim->Start();
717 surface_flinger->SetShutdownCritical();
718 boot_anim->SetShutdownCritical();
Tom Cherry911b9b12017-07-27 16:20:58 -0700719 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700720 }
Keun-young Park7830d592017-03-27 16:07:02 -0700721
Keun-young Park8d01f632017-03-13 11:54:47 -0700722 // optional shutdown step
723 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Keun-young Park30173872017-07-18 10:58:28 -0700724 if (shutdown_timeout > 0ms) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100725 StopServicesAndLogViolations(stop_first, shutdown_timeout / 2, true /* SIGTERM */);
Keun-young Park8d01f632017-03-13 11:54:47 -0700726 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100727 // Send SIGKILL to ones that didn't terminate cleanly.
728 StopServicesAndLogViolations(stop_first, 0ms, false /* SIGKILL */);
Luis Hector Chavez92c49bc2018-07-27 11:19:25 -0700729 SubcontextTerminate();
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100730 // Reap subcontext pids.
Tom Cherryeeee8312017-07-28 15:22:23 -0700731 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700732
Martijn Coenen860ba642020-05-28 16:42:10 +0200733 // 3. send volume abort_fuse and volume shutdown to vold
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100734 Service* vold_service = ServiceList::GetInstance().FindService("vold");
735 if (vold_service != nullptr && vold_service->IsRunning()) {
Martijn Coenen860ba642020-05-28 16:42:10 +0200736 // Manually abort FUSE connections, since the FUSE daemon is already dead
737 // at this point, and unmounting it might hang.
738 CallVdc("volume", "abort_fuse");
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000739 CallVdc("volume", "shutdown");
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100740 vold_service->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700741 } else {
742 LOG(INFO) << "vold not running, skipping vold shutdown";
743 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700744 // logcat stopped here
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000745 StopServices(kDebuggingServices, 0ms, false /* SIGKILL */);
Keun-young Park8d01f632017-03-13 11:54:47 -0700746 // 4. sync, try umount, and optionally run fsck for user shutdown
Tom Cherry1f9d5402018-03-15 10:22:40 -0700747 {
748 Timer sync_timer;
749 LOG(INFO) << "sync() before umount...";
750 sync();
751 LOG(INFO) << "sync() before umount took" << sync_timer;
752 }
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800753 // 5. drop caches and disable zram backing device, if exist
754 KillZramBackingDevice();
755
Nikita Ioffe91a98482020-06-10 00:53:59 +0100756 LOG(INFO) << "Ready to unmount apexes. So far shutdown sequence took " << t;
757 // 6. unmount active apexes, otherwise they might prevent clean unmount of /data.
758 if (auto ret = UnmountAllApexes(); !ret.ok()) {
759 LOG(ERROR) << ret.error();
760 }
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100761 UmountStat stat =
762 TryUmountAndFsck(cmd, run_fsck, shutdown_timeout - t.duration(), &reboot_semaphore);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700763 // Follow what linux shutdown is doing: one more sync with little bit delay
Tom Cherry1f9d5402018-03-15 10:22:40 -0700764 {
765 Timer sync_timer;
766 LOG(INFO) << "sync() after umount...";
767 sync();
768 LOG(INFO) << "sync() after umount took" << sync_timer;
769 }
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700770 if (!is_thermal_shutdown) std::this_thread::sleep_for(100ms);
Keun-young Park8d01f632017-03-13 11:54:47 -0700771 LogShutdownTime(stat, &t);
josephjangaaddf282019-04-16 18:46:24 +0800772
773 // Send signal to terminate reboot monitor thread.
774 reboot_monitor_run = false;
775 sem_post(&reboot_semaphore);
776
Keun-young Park8d01f632017-03-13 11:54:47 -0700777 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
Jaegeuk Kim3e595d52022-04-15 12:31:46 -0700778 if (IsDataMounted("f2fs")) {
779 uint32_t flag = F2FS_GOING_DOWN_FULLSYNC;
780 unique_fd fd(TEMP_FAILURE_RETRY(open("/data", O_RDONLY)));
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800781 int ret = ioctl(fd.get(), F2FS_IOC_SHUTDOWN, &flag);
Jaegeuk Kim3e595d52022-04-15 12:31:46 -0700782 if (ret) {
783 PLOG(ERROR) << "Shutdown /data: ";
784 } else {
785 LOG(INFO) << "Shutdown /data";
786 }
787 }
Sayanna Chandula5754b5a2022-10-04 15:06:05 -0700788 RebootSystem(cmd, reboot_target, reason);
Keun-young Park8d01f632017-03-13 11:54:47 -0700789 abort();
790}
Tom Cherry98ad32a2017-04-17 16:34:20 -0700791
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100792static void EnterShutdown() {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100793 LOG(INFO) << "Entering shutdown mode";
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100794 shutting_down = true;
795 // Skip wait for prop if it is in progress
796 ResetWaitForProp();
797 // Clear EXEC flag if there is one pending
798 for (const auto& s : ServiceList::GetInstance()) {
799 s->UnSetExec();
800 }
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100801}
802
Sam Protsenko2c7c3c72019-12-26 21:55:08 +0200803/**
804 * Check if "command" field is set in bootloader message.
805 *
806 * If "command" field is broken (contains non-printable characters prior to
807 * terminating zero), it will be zeroed.
808 *
809 * @param[in,out] boot Bootloader message (BCB) structure
810 * @return true if "command" field is already set, and false if it's empty
811 */
812static bool CommandIsPresent(bootloader_message* boot) {
813 if (boot->command[0] == '\0')
814 return false;
815
816 for (size_t i = 0; i < arraysize(boot->command); ++i) {
817 if (boot->command[i] == '\0')
818 return true;
819 if (!isprint(boot->command[i]))
820 break;
821 }
822
823 memset(boot->command, 0, sizeof(boot->command));
824 return false;
825}
826
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100827void HandlePowerctlMessage(const std::string& command) {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700828 unsigned int cmd = 0;
Mark Salyzyn62909822017-10-09 09:27:16 -0700829 std::vector<std::string> cmd_params = Split(command, ",");
Tom Cherry98ad32a2017-04-17 16:34:20 -0700830 std::string reboot_target = "";
831 bool run_fsck = false;
832 bool command_invalid = false;
833
Mark Salyzynd7931f12019-07-10 10:33:09 -0700834 if (cmd_params[0] == "shutdown") {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700835 cmd = ANDROID_RB_POWEROFF;
Mark Salyzynd7931f12019-07-10 10:33:09 -0700836 if (cmd_params.size() >= 2) {
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700837 if (cmd_params[1] == "userrequested") {
838 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
839 // Run fsck once the file system is remounted in read-only mode.
840 run_fsck = true;
841 } else if (cmd_params[1] == "thermal") {
Mark Salyzynbfd05b62017-09-26 11:10:12 -0700842 // Turn off sources of heat immediately.
843 TurnOffBacklight();
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700844 // run_fsck is false to avoid delay
845 cmd = ANDROID_RB_THERMOFF;
846 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700847 }
848 } else if (cmd_params[0] == "reboot") {
849 cmd = ANDROID_RB_RESTART2;
850 if (cmd_params.size() >= 2) {
851 reboot_target = cmd_params[1];
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100852 if (reboot_target == "userspace") {
Jooyung Hane34549a2024-08-09 15:58:53 +0900853 LOG(ERROR) << "Userspace reboot is deprecated.";
854 return;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100855 }
Hridya Valsaraju54258262018-09-19 21:14:18 -0700856 // adb reboot fastboot should boot into bootloader for devices not
857 // supporting logical partitions.
858 if (reboot_target == "fastboot" &&
Yifan Hong0e0f8182018-11-16 12:49:06 -0800859 !android::base::GetBoolProperty("ro.boot.dynamic_partitions", false)) {
Hridya Valsaraju54258262018-09-19 21:14:18 -0700860 reboot_target = "bootloader";
861 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700862 // When rebooting to the bootloader notify the bootloader writing
863 // also the BCB.
864 if (reboot_target == "bootloader") {
865 std::string err;
866 if (!write_reboot_bootloader(&err)) {
867 LOG(ERROR) << "reboot-bootloader: Error writing "
868 "bootloader_message: "
869 << err;
870 }
Tianjie Xu5e98b632019-07-18 12:48:28 -0700871 } else if (reboot_target == "recovery") {
872 bootloader_message boot = {};
873 if (std::string err; !read_bootloader_message(&boot, &err)) {
874 LOG(ERROR) << "Failed to read bootloader message: " << err;
875 }
876 // Update the boot command field if it's empty, and preserve
877 // the other arguments in the bootloader message.
Sam Protsenko2c7c3c72019-12-26 21:55:08 +0200878 if (!CommandIsPresent(&boot)) {
Tianjie Xu5e98b632019-07-18 12:48:28 -0700879 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
880 if (std::string err; !write_bootloader_message(boot, &err)) {
881 LOG(ERROR) << "Failed to set bootloader message: " << err;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100882 return;
Tianjie Xu5e98b632019-07-18 12:48:28 -0700883 }
884 }
Veena Arvindb46e5e62024-03-07 22:55:28 +0000885 } else if (std::find(cmd_params.begin(), cmd_params.end(), "quiescent")
886 != cmd_params.end()) { // Quiescent can be either subreason or details.
Chenfu.Liaod672e472021-06-29 15:41:22 +0800887 bootloader_message boot = {};
888 if (std::string err; !read_bootloader_message(&boot, &err)) {
889 LOG(ERROR) << "Failed to read bootloader message: " << err;
890 }
891 // Update the boot command field if it's empty, and preserve
892 // the other arguments in the bootloader message.
893 if (!CommandIsPresent(&boot)) {
894 strlcpy(boot.command, "boot-quiescent", sizeof(boot.command));
895 if (std::string err; !write_bootloader_message(boot, &err)) {
896 LOG(ERROR) << "Failed to set bootloader message: " << err;
897 return;
898 }
899 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700900 } else if (reboot_target == "sideload" || reboot_target == "sideload-auto-reboot" ||
901 reboot_target == "fastboot") {
902 std::string arg = reboot_target == "sideload-auto-reboot" ? "sideload_auto_reboot"
903 : reboot_target;
904 const std::vector<std::string> options = {
905 "--" + arg,
906 };
907 std::string err;
908 if (!write_bootloader_message(options, &err)) {
909 LOG(ERROR) << "Failed to set bootloader message: " << err;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100910 return;
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700911 }
912 reboot_target = "recovery";
Tom Cherry98ad32a2017-04-17 16:34:20 -0700913 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700914
Mark Salyzynd7931f12019-07-10 10:33:09 -0700915 // If there are additional parameter, pass them along
916 for (size_t i = 2; (cmd_params.size() > i) && cmd_params[i].size(); ++i) {
917 reboot_target += "," + cmd_params[i];
Tom Cherry98ad32a2017-04-17 16:34:20 -0700918 }
919 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700920 } else {
921 command_invalid = true;
922 }
923 if (command_invalid) {
924 LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100925 return;
926 }
927
Tom Cherry802864c2020-03-12 14:29:25 -0700928 // We do not want to process any messages (queue'ing triggers, shutdown messages, control
929 // messages, etc) from properties during reboot.
930 StopSendingMessages();
931
Wei Wangeeab4912017-06-27 22:08:45 -0700932 LOG(INFO) << "Clear action queue and start shutdown trigger";
933 ActionManager::GetInstance().ClearQueue();
934 // Queue shutdown trigger first
935 ActionManager::GetInstance().QueueEventTrigger("shutdown");
936 // Queue built-in shutdown_done
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700937 auto shutdown_handler = [cmd, command, reboot_target, run_fsck](const BuiltinArguments&) {
Wei Wangeeab4912017-06-27 22:08:45 -0700938 DoReboot(cmd, command, reboot_target, run_fsck);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700939 return Result<void>{};
Wei Wangeeab4912017-06-27 22:08:45 -0700940 };
941 ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
942
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100943 EnterShutdown();
944}
Wei Wangeeab4912017-06-27 22:08:45 -0700945
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100946bool IsShuttingDown() {
947 return shutting_down;
Tom Cherry98ad32a2017-04-17 16:34:20 -0700948}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700949
950} // namespace init
951} // namespace android