blob: ef9db9fdae30bf7adb56ae937982644151e749ae [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
Tom Cherryede0d532017-07-06 14:20:11 -070042#include <android-base/chrono_utils.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070043#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070044#include <android-base/logging.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070045#include <android-base/macros.h>
Tom Cherryccf23532017-03-28 16:40:41 -070046#include <android-base/properties.h>
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010047#include <android-base/scopeguard.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070048#include <android-base/strings.h>
Keun-young Park2ba5c812017-03-29 12:54:40 -070049#include <android-base/unique_fd.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070050#include <bootloader_message/bootloader_message.h>
51#include <cutils/android_reboot.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070052#include <fs_mgr.h>
Akilesh Kailash2c52d092023-01-03 04:39:28 +000053#include <libsnapshot/snapshot.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070054#include <logwrap/logwrap.h>
Todd Poynorfc827be2017-04-13 15:17:24 -070055#include <private/android_filesystem_config.h>
Tom Cherry0c8d6d22017-08-10 12:22:44 -070056#include <selinux/selinux.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070057
Nikita Ioffeba6968e2019-10-07 16:26:33 +010058#include "action.h"
Tom Cherry7fd3bc22018-02-13 15:36:14 -080059#include "action_manager.h"
Nikita Ioffeba6968e2019-10-07 16:26:33 +010060#include "builtin_arguments.h"
Wei Wangeeab4912017-06-27 22:08:45 -070061#include "init.h"
Nikita Ioffeab91ee92019-11-06 21:40:31 +000062#include "mount_namespace.h"
Tom Cherry802864c2020-03-12 14:29:25 -070063#include "property_service.h"
Tom Cherry44aceed2018-08-03 13:36:18 -070064#include "reboot_utils.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070065#include "service.h"
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070066#include "service_list.h"
Luis Hector Chavez9f97f472017-09-06 13:43:57 -070067#include "sigchld_handler.h"
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010068#include "util.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070069
Tom Cherry2436e6b2019-09-19 11:16:19 -070070using namespace std::literals;
71
Nikita Ioffec0df1872019-11-13 21:47:06 +000072using android::base::boot_clock;
Tom Cherry4f4cacc2019-01-08 10:39:00 -080073using android::base::GetBoolProperty;
Nikita Ioffe7b41a152020-03-25 00:06:51 +000074using android::base::GetUintProperty;
Nikita Ioffec0df1872019-11-13 21:47:06 +000075using android::base::SetProperty;
Mark Salyzyn62909822017-10-09 09:27:16 -070076using android::base::Split;
Tom Cherryede0d532017-07-06 14:20:11 -070077using android::base::Timer;
Jaegeuk Kim2aedc822018-11-20 13:27:06 -080078using android::base::unique_fd;
Nikita Ioffec0df1872019-11-13 21:47:06 +000079using android::base::WaitForProperty;
josephjangaaddf282019-04-16 18:46:24 +080080using android::base::WriteStringToFile;
Keun-young Park8d01f632017-03-13 11:54:47 -070081
Tom Cherry81f5d3e2017-06-22 12:53:17 -070082namespace android {
83namespace init {
84
Nikita Ioffeba6968e2019-10-07 16:26:33 +010085static bool shutting_down = false;
86
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010087static const std::set<std::string> kDebuggingServices{"tombstoned", "logd", "adbd", "console"};
88
Nikita Ioffed485bbb2020-02-26 15:18:56 +000089static void PersistRebootReason(const char* reason, bool write_to_property) {
90 if (write_to_property) {
91 SetProperty(LAST_REBOOT_REASON_PROPERTY, reason);
92 }
Tom Cherry10615eb2020-03-31 16:31:37 -070093 auto fd = unique_fd(TEMP_FAILURE_RETRY(open(
94 LAST_REBOOT_REASON_FILE, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY, 0666)));
95 if (!fd.ok()) {
96 PLOG(ERROR) << "Could not open '" << LAST_REBOOT_REASON_FILE
97 << "' to persist reboot reason";
98 return;
99 }
100 WriteStringToFd(reason, fd);
101 fsync(fd.get());
Nikita Ioffed0bc0b62020-02-19 16:21:11 +0000102}
103
Keun-young Park8d01f632017-03-13 11:54:47 -0700104// represents umount status during reboot / shutdown.
105enum UmountStat {
106 /* umount succeeded. */
107 UMOUNT_STAT_SUCCESS = 0,
108 /* umount was not run. */
109 UMOUNT_STAT_SKIPPED = 1,
110 /* umount failed with timeout. */
111 UMOUNT_STAT_TIMEOUT = 2,
112 /* could not run due to error */
113 UMOUNT_STAT_ERROR = 3,
114 /* not used by init but reserved for other part to use this to represent the
115 the state where umount status before reboot is not found / available. */
116 UMOUNT_STAT_NOT_AVAILABLE = 4,
117};
118
119// Utility for struct mntent
120class MountEntry {
121 public:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700122 explicit MountEntry(const mntent& entry)
Keun-young Park8d01f632017-03-13 11:54:47 -0700123 : mnt_fsname_(entry.mnt_fsname),
124 mnt_dir_(entry.mnt_dir),
125 mnt_type_(entry.mnt_type),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700126 mnt_opts_(entry.mnt_opts) {}
Keun-young Park8d01f632017-03-13 11:54:47 -0700127
Jaegeuk Kim0f04f722017-09-25 10:55:39 -0700128 bool Umount(bool force) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800129 LOG(INFO) << "Unmounting " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Jaegeuk Kim0f04f722017-09-25 10:55:39 -0700130 int r = umount2(mnt_dir_.c_str(), force ? MNT_FORCE : 0);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700131 if (r == 0) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800132 LOG(INFO) << "Umounted " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700133 return true;
134 } else {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800135 PLOG(WARNING) << "Cannot umount " << mnt_fsname_ << ":" << mnt_dir_ << " opts "
Keun-young Park2ba5c812017-03-29 12:54:40 -0700136 << mnt_opts_;
137 return false;
138 }
139 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700140
Keun-young Park2ba5c812017-03-29 12:54:40 -0700141 void DoFsck() {
142 int st;
143 if (IsF2Fs()) {
144 const char* f2fs_argv[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800145 "/system/bin/fsck.f2fs",
146 "-a",
147 mnt_fsname_.c_str(),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700148 };
Tom Cherry3a803eb2019-09-25 16:23:50 -0700149 logwrap_fork_execvp(arraysize(f2fs_argv), f2fs_argv, &st, false, LOG_KLOG, true,
150 nullptr);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700151 } else if (IsExt4()) {
152 const char* ext4_argv[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800153 "/system/bin/e2fsck",
154 "-y",
155 mnt_fsname_.c_str(),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700156 };
Tom Cherry3a803eb2019-09-25 16:23:50 -0700157 logwrap_fork_execvp(arraysize(ext4_argv), ext4_argv, &st, false, LOG_KLOG, true,
158 nullptr);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700159 }
160 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700161
162 static bool IsBlockDevice(const struct mntent& mntent) {
163 return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
164 }
165
166 static bool IsEmulatedDevice(const struct mntent& mntent) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700167 return android::base::StartsWith(mntent.mnt_fsname, "/data/");
Keun-young Park8d01f632017-03-13 11:54:47 -0700168 }
169
170 private:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700171 bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
172
173 bool IsExt4() const { return mnt_type_ == "ext4"; }
174
Keun-young Park8d01f632017-03-13 11:54:47 -0700175 std::string mnt_fsname_;
176 std::string mnt_dir_;
177 std::string mnt_type_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700178 std::string mnt_opts_;
Keun-young Park8d01f632017-03-13 11:54:47 -0700179};
180
181// Turn off backlight while we are performing power down cleanup activities.
Tom Cherry832f9f12020-03-10 11:47:24 -0700182static void TurnOffBacklight() {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800183 Service* service = ServiceList::GetInstance().FindService("blank_screen");
184 if (service == nullptr) {
185 LOG(WARNING) << "cannot find blank_screen in TurnOffBacklight";
Keun-young Park8d01f632017-03-13 11:54:47 -0700186 return;
187 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900188 if (auto result = service->Start(); !result.ok()) {
Tom Cherryd9872642018-10-11 10:38:05 -0700189 LOG(WARNING) << "Could not start blank_screen service: " << result.error();
190 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700191}
192
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000193static Result<void> CallVdc(const std::string& system, const std::string& cmd) {
Nikita Ioffea3be9962020-04-16 21:37:03 +0100194 LOG(INFO) << "Calling /system/bin/vdc " << system << " " << cmd;
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000195 const char* vdc_argv[] = {"/system/bin/vdc", system.c_str(), cmd.c_str()};
Keun-young Park8d01f632017-03-13 11:54:47 -0700196 int status;
Nikita Ioffe12a36072019-10-23 20:11:32 +0100197 if (logwrap_fork_execvp(arraysize(vdc_argv), vdc_argv, &status, false, LOG_KLOG, true,
198 nullptr) != 0) {
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000199 return ErrnoError() << "Failed to call '/system/bin/vdc " << system << " " << cmd << "'";
Nikita Ioffe12a36072019-10-23 20:11:32 +0100200 }
201 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
202 return {};
203 }
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000204 return Error() << "'/system/bin/vdc " << system << " " << cmd << "' failed : " << status;
Keun-young Park8d01f632017-03-13 11:54:47 -0700205}
206
207static void LogShutdownTime(UmountStat stat, Timer* t) {
Tom Cherryede0d532017-07-06 14:20:11 -0700208 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration().count()) << ":"
209 << stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700210}
211
Jaegeuk Kim3e595d52022-04-15 12:31:46 -0700212static bool IsDataMounted(const std::string& fstype) {
Tom Cherry2436e6b2019-09-19 11:16:19 -0700213 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
214 if (fp == nullptr) {
215 PLOG(ERROR) << "Failed to open /proc/mounts";
216 return false;
217 }
218 mntent* mentry;
219 while ((mentry = getmntent(fp.get())) != nullptr) {
220 if (mentry->mnt_dir == "/data"s) {
Jaegeuk Kim3e595d52022-04-15 12:31:46 -0700221 return fstype == "*" || mentry->mnt_type == fstype;
Tom Cherry2436e6b2019-09-19 11:16:19 -0700222 }
223 }
224 return false;
225}
226
227// Find all read+write block devices and emulated devices in /proc/mounts and add them to
228// the correpsponding list.
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100229static bool FindPartitionsToUmount(std::vector<MountEntry>* block_dev_partitions,
230 std::vector<MountEntry>* emulated_partitions, bool dump) {
Tom Cherryf274e782018-10-03 13:13:41 -0700231 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
Keun-young Park8d01f632017-03-13 11:54:47 -0700232 if (fp == nullptr) {
233 PLOG(ERROR) << "Failed to open /proc/mounts";
234 return false;
235 }
236 mntent* mentry;
237 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700238 if (dump) {
239 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
240 << mentry->mnt_opts << " type " << mentry->mnt_type;
241 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
Keun-young Park6e12b382017-07-17 12:20:33 -0700242 std::string mount_dir(mentry->mnt_dir);
243 // These are R/O partitions changed to R/W after adb remount.
244 // Do not umount them as shutdown critical services may rely on them.
Wei Wanga01c27e2017-07-25 10:52:08 -0700245 if (mount_dir != "/" && mount_dir != "/system" && mount_dir != "/vendor" &&
246 mount_dir != "/oem") {
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100247 block_dev_partitions->emplace(block_dev_partitions->begin(), *mentry);
Keun-young Park6e12b382017-07-17 12:20:33 -0700248 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700249 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100250 emulated_partitions->emplace(emulated_partitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700251 }
252 }
253 return true;
254}
255
Jonglin Lee28a2c922019-01-15 16:38:44 -0800256static void DumpUmountDebuggingInfo() {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700257 int status;
258 if (!security_getenforce()) {
259 LOG(INFO) << "Run lsof";
260 const char* lsof_argv[] = {"/system/bin/lsof"};
Tom Cherry3a803eb2019-09-25 16:23:50 -0700261 logwrap_fork_execvp(arraysize(lsof_argv), lsof_argv, &status, false, LOG_KLOG, true,
262 nullptr);
Keun-young Park8d01f632017-03-13 11:54:47 -0700263 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700264 FindPartitionsToUmount(nullptr, nullptr, true);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800265 // dump current CPU stack traces and uninterruptible tasks
josephjangaaddf282019-04-16 18:46:24 +0800266 WriteStringToFile("l", PROC_SYSRQ);
267 WriteStringToFile("w", PROC_SYSRQ);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700268}
269
Tom Cherryede0d532017-07-06 14:20:11 -0700270static UmountStat UmountPartitions(std::chrono::milliseconds timeout) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700271 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700272 /* data partition needs all pending writes to be completed and all emulated partitions
273 * umounted.If the current waiting is not good enough, give
274 * up and leave it to e2fsck after reboot to fix it.
275 */
276 while (true) {
277 std::vector<MountEntry> block_devices;
278 std::vector<MountEntry> emulated_devices;
279 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
280 return UMOUNT_STAT_ERROR;
281 }
282 if (block_devices.size() == 0) {
Wei Wang8c00e422017-08-16 14:01:46 -0700283 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700284 }
Wei Wang8c00e422017-08-16 14:01:46 -0700285 bool unmount_done = true;
286 if (emulated_devices.size() > 0) {
Wei Wang25dc30f2017-10-23 15:32:03 -0700287 for (auto& entry : emulated_devices) {
288 if (!entry.Umount(false)) unmount_done = false;
289 }
Wei Wang8c00e422017-08-16 14:01:46 -0700290 if (unmount_done) {
291 sync();
292 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700293 }
Wei Wang25dc30f2017-10-23 15:32:03 -0700294 for (auto& entry : block_devices) {
295 if (!entry.Umount(timeout == 0ms)) unmount_done = false;
296 }
Wei Wang8c00e422017-08-16 14:01:46 -0700297 if (unmount_done) {
298 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700299 }
Wei Wang8c00e422017-08-16 14:01:46 -0700300 if ((timeout < t.duration())) { // try umount at least once
301 return UMOUNT_STAT_TIMEOUT;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700302 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700303 std::this_thread::sleep_for(100ms);
304 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700305}
306
josephjangaaddf282019-04-16 18:46:24 +0800307static void KillAllProcesses() {
308 WriteStringToFile("i", PROC_SYSRQ);
309}
310
311// Create reboot/shutdwon monitor thread
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100312void RebootMonitorThread(unsigned int cmd, const std::string& reboot_target,
313 sem_t* reboot_semaphore, std::chrono::milliseconds shutdown_timeout,
314 bool* reboot_monitor_run) {
josephjangaaddf282019-04-16 18:46:24 +0800315 unsigned int remaining_shutdown_time = 0;
316
Tom Cherry10615eb2020-03-31 16:31:37 -0700317 // 300 seconds more than the timeout passed to the thread as there is a final Umount pass
josephjangaaddf282019-04-16 18:46:24 +0800318 // after the timeout is reached.
Tom Cherry10615eb2020-03-31 16:31:37 -0700319 constexpr unsigned int shutdown_watchdog_timeout_default = 300;
josephjangaaddf282019-04-16 18:46:24 +0800320 auto shutdown_watchdog_timeout = android::base::GetUintProperty(
321 "ro.build.shutdown.watchdog.timeout", shutdown_watchdog_timeout_default);
322 remaining_shutdown_time = shutdown_watchdog_timeout + shutdown_timeout.count() / 1000;
323
324 while (*reboot_monitor_run == true) {
325 if (TEMP_FAILURE_RETRY(sem_wait(reboot_semaphore)) == -1) {
326 LOG(ERROR) << "sem_wait failed and exit RebootMonitorThread()";
327 return;
328 }
329
330 timespec shutdown_timeout_timespec;
331 if (clock_gettime(CLOCK_MONOTONIC, &shutdown_timeout_timespec) == -1) {
332 LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
333 return;
334 }
335
336 // If there are some remaining shutdown time left from previous round, we use
337 // remaining time here.
338 shutdown_timeout_timespec.tv_sec += remaining_shutdown_time;
339
340 LOG(INFO) << "shutdown_timeout_timespec.tv_sec: " << shutdown_timeout_timespec.tv_sec;
341
342 int sem_return = 0;
343 while ((sem_return = sem_timedwait_monotonic_np(reboot_semaphore,
344 &shutdown_timeout_timespec)) == -1 &&
345 errno == EINTR) {
346 }
347
348 if (sem_return == -1) {
349 LOG(ERROR) << "Reboot thread timed out";
350
351 if (android::base::GetBoolProperty("ro.debuggable", false) == true) {
Tom Cherry2436e6b2019-09-19 11:16:19 -0700352 if (false) {
353 // SEPolicy will block debuggerd from running and this is intentional.
354 // But these lines are left to be enabled during debugging.
355 LOG(INFO) << "Try to dump init process call trace:";
356 const char* vdc_argv[] = {"/system/bin/debuggerd", "-b", "1"};
357 int status;
Tom Cherry3a803eb2019-09-25 16:23:50 -0700358 logwrap_fork_execvp(arraysize(vdc_argv), vdc_argv, &status, false, LOG_KLOG,
359 true, nullptr);
Tom Cherry2436e6b2019-09-19 11:16:19 -0700360 }
josephjangaaddf282019-04-16 18:46:24 +0800361 LOG(INFO) << "Show stack for all active CPU:";
362 WriteStringToFile("l", PROC_SYSRQ);
363
364 LOG(INFO) << "Show tasks that are in disk sleep(uninterruptable sleep), which are "
365 "like "
366 "blocked in mutex or hardware register access:";
367 WriteStringToFile("w", PROC_SYSRQ);
368 }
369
370 // In shutdown case,notify kernel to sync and umount fs to read-only before shutdown.
371 if (cmd == ANDROID_RB_POWEROFF || cmd == ANDROID_RB_THERMOFF) {
372 WriteStringToFile("s", PROC_SYSRQ);
373
374 WriteStringToFile("u", PROC_SYSRQ);
375
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100376 RebootSystem(cmd, reboot_target);
josephjangaaddf282019-04-16 18:46:24 +0800377 }
378
379 LOG(ERROR) << "Trigger crash at last!";
380 WriteStringToFile("c", PROC_SYSRQ);
381 } else {
382 timespec current_time_timespec;
383
384 if (clock_gettime(CLOCK_MONOTONIC, &current_time_timespec) == -1) {
385 LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
386 return;
387 }
388
389 remaining_shutdown_time =
390 shutdown_timeout_timespec.tv_sec - current_time_timespec.tv_sec;
391
392 LOG(INFO) << "remaining_shutdown_time: " << remaining_shutdown_time;
393 }
394 }
395}
Keun-young Park3ee0df92017-03-27 11:21:09 -0700396
Keun-young Park8d01f632017-03-13 11:54:47 -0700397/* Try umounting all emulated file systems R/W block device cfile systems.
398 * This will just try umount and give it up if it fails.
399 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
400 * and necessary check can be done at the next reboot.
401 * For safer shutdown, caller needs to make sure that
402 * all processes / emulated partition for the target fs are all cleaned-up.
403 *
404 * return true when umount was successful. false when timed out.
405 */
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100406static UmountStat TryUmountAndFsck(unsigned int cmd, bool run_fsck,
josephjangaaddf282019-04-16 18:46:24 +0800407 std::chrono::milliseconds timeout, sem_t* reboot_semaphore) {
Keun-young Park3ee0df92017-03-27 11:21:09 -0700408 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700409 std::vector<MountEntry> block_devices;
410 std::vector<MountEntry> emulated_devices;
Keun-young Park8d01f632017-03-13 11:54:47 -0700411
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100412 if (run_fsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700413 return UMOUNT_STAT_ERROR;
414 }
Akilesh Kailash2c52d092023-01-03 04:39:28 +0000415 auto sm = snapshot::SnapshotManager::New();
416 bool ota_update_in_progress = false;
417 if (sm->IsUserspaceSnapshotUpdateInProgress()) {
418 LOG(INFO) << "OTA update in progress";
419 ota_update_in_progress = true;
420 }
Tom Cherryede0d532017-07-06 14:20:11 -0700421 UmountStat stat = UmountPartitions(timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700422 if (stat != UMOUNT_STAT_SUCCESS) {
423 LOG(INFO) << "umount timeout, last resort, kill all and try";
Jonglin Lee28a2c922019-01-15 16:38:44 -0800424 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Akilesh Kailash2c52d092023-01-03 04:39:28 +0000425 // Since umount timedout, we will try to kill all processes
426 // and do one more attempt to umount the partitions.
427 //
428 // However, if OTA update is in progress, we don't want
429 // to kill the snapuserd daemon as the daemon will
430 // be serving I/O requests. Killing the daemon will
431 // end up with I/O failures. If the update is in progress,
432 // we will just return the umount failure status immediately.
433 // This is ok, given the fact that killing the processes
434 // and doing an umount is just a last effort. We are
435 // still not doing fsck when all processes are killed.
436 //
437 if (ota_update_in_progress) {
438 return stat;
439 }
Keun-young Park3ee0df92017-03-27 11:21:09 -0700440 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700441 // 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 -0700442 UmountStat st = UmountPartitions(0ms);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800443 if ((st != UMOUNT_STAT_SUCCESS) && DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park8d01f632017-03-13 11:54:47 -0700444 }
445
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100446 if (stat == UMOUNT_STAT_SUCCESS && run_fsck) {
josephjangaaddf282019-04-16 18:46:24 +0800447 LOG(INFO) << "Pause reboot monitor thread before fsck";
448 sem_post(reboot_semaphore);
449
Keun-young Park2ba5c812017-03-29 12:54:40 -0700450 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
451 // and should not affect reboot time.
452 for (auto& entry : block_devices) {
453 entry.DoFsck();
454 }
josephjangaaddf282019-04-16 18:46:24 +0800455
456 LOG(INFO) << "Resume reboot monitor thread after fsck";
457 sem_post(reboot_semaphore);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700458 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700459 return stat;
460}
461
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800462// zram is able to use backing device on top of a loopback device.
463// In order to unmount /data successfully, we have to kill the loopback device first
luwei98a3653c2021-04-14 14:34:59 +0800464#define ZRAM_DEVICE "/dev/block/zram0"
465#define ZRAM_RESET "/sys/block/zram0/reset"
466#define ZRAM_BACK_DEV "/sys/block/zram0/backing_dev"
467#define ZRAM_INITSTATE "/sys/block/zram0/initstate"
Nikita Ioffe12a36072019-10-23 20:11:32 +0100468static Result<void> KillZramBackingDevice() {
luwei98a3653c2021-04-14 14:34:59 +0800469 std::string zram_initstate;
470 if (!android::base::ReadFileToString(ZRAM_INITSTATE, &zram_initstate)) {
471 return ErrnoError() << "Failed to read " << ZRAM_INITSTATE;
472 }
473
474 zram_initstate.erase(zram_initstate.length() - 1);
475 if (zram_initstate == "0") {
476 LOG(INFO) << "Zram has not been swapped on";
477 return {};
478 }
479
Nikita Ioffea3be9962020-04-16 21:37:03 +0100480 if (access(ZRAM_BACK_DEV, F_OK) != 0 && errno == ENOENT) {
481 LOG(INFO) << "No zram backing device configured";
482 return {};
483 }
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800484 std::string backing_dev;
Nikita Ioffea3be9962020-04-16 21:37:03 +0100485 if (!android::base::ReadFileToString(ZRAM_BACK_DEV, &backing_dev)) {
486 return ErrnoError() << "Failed to read " << ZRAM_BACK_DEV;
487 }
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800488
489 // cut the last "\n"
490 backing_dev.erase(backing_dev.length() - 1);
491
shisiyuan423c4f12021-05-18 11:47:43 +0800492 if (android::base::StartsWith(backing_dev, "none")) {
493 LOG(INFO) << "No zram backing device configured";
494 return {};
495 }
496
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800497 // shutdown zram handle
498 Timer swap_timer;
499 LOG(INFO) << "swapoff() start...";
500 if (swapoff(ZRAM_DEVICE) == -1) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100501 return ErrnoError() << "zram_backing_dev: swapoff (" << backing_dev << ")"
502 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800503 }
JeongHyeon Lee170855d2022-04-14 18:06:18 +0900504 LOG(INFO) << "swapoff() took " << swap_timer;
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800505
josephjangaaddf282019-04-16 18:46:24 +0800506 if (!WriteStringToFile("1", ZRAM_RESET)) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100507 return Error() << "zram_backing_dev: reset (" << backing_dev << ")"
508 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800509 }
510
Nikita Ioffea3be9962020-04-16 21:37:03 +0100511 if (!android::base::StartsWith(backing_dev, "/dev/block/loop")) {
512 LOG(INFO) << backing_dev << " is not a loop device. Exiting early";
513 return {};
514 }
515
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800516 // clear loopback device
517 unique_fd loop(TEMP_FAILURE_RETRY(open(backing_dev.c_str(), O_RDWR | O_CLOEXEC)));
518 if (loop.get() < 0) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100519 return ErrnoError() << "zram_backing_dev: open(" << backing_dev << ")"
520 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800521 }
522
523 if (ioctl(loop.get(), LOOP_CLR_FD, 0) < 0) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100524 return ErrnoError() << "zram_backing_dev: loop_clear (" << backing_dev << ")"
525 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800526 }
527 LOG(INFO) << "zram_backing_dev: `" << backing_dev << "` is cleared successfully.";
Nikita Ioffe12a36072019-10-23 20:11:32 +0100528 return {};
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800529}
530
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100531// Stops given services, waits for them to be stopped for |timeout| ms.
532// If terminate is true, then SIGTERM is sent to services, otherwise SIGKILL is sent.
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000533// Note that services are stopped in order given by |ServiceList::services_in_shutdown_order|
534// function.
535static void StopServices(const std::set<std::string>& services, std::chrono::milliseconds timeout,
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100536 bool terminate) {
537 LOG(INFO) << "Stopping " << services.size() << " services by sending "
538 << (terminate ? "SIGTERM" : "SIGKILL");
539 std::vector<pid_t> pids;
540 pids.reserve(services.size());
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000541 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
542 if (services.count(s->name()) == 0) {
543 continue;
544 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100545 if (s->pid() > 0) {
546 pids.push_back(s->pid());
547 }
548 if (terminate) {
549 s->Terminate();
550 } else {
551 s->Stop();
552 }
553 }
554 if (timeout > 0ms) {
Bart Van Assche97047b52023-11-16 12:42:35 -0800555 WaitToBeReaped(Service::GetSigchldFd(), pids, timeout);
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100556 } else {
557 // Even if we don't to wait for services to stop, we still optimistically reap zombies.
558 ReapAnyOutstandingChildren();
559 }
560}
561
562// Like StopServices, but also logs all the services that failed to stop after the provided timeout.
563// Returns number of violators.
Nikita Ioffe660ffde2020-12-10 16:52:35 +0000564int StopServicesAndLogViolations(const std::set<std::string>& services,
565 std::chrono::milliseconds timeout, bool terminate) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100566 StopServices(services, timeout, terminate);
567 int still_running = 0;
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000568 for (const auto& s : ServiceList::GetInstance()) {
569 if (s->IsRunning() && services.count(s->name())) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100570 LOG(ERROR) << "[service-misbehaving] : service '" << s->name() << "' is still running "
571 << timeout.count() << "ms after receiving "
572 << (terminate ? "SIGTERM" : "SIGKILL");
573 still_running++;
574 }
575 }
576 return still_running;
577}
578
Nikita Ioffe91a98482020-06-10 00:53:59 +0100579static Result<void> UnmountAllApexes() {
Inseob Kim0fbc1d72022-11-09 12:50:14 +0900580 // don't need to unmount because apexd doesn't use /data in Microdroid
581 if (IsMicrodroid()) {
582 return {};
583 }
584
Nikita Ioffe91a98482020-06-10 00:53:59 +0100585 const char* args[] = {"/system/bin/apexd", "--unmount-all"};
586 int status;
587 if (logwrap_fork_execvp(arraysize(args), args, &status, false, LOG_KLOG, true, nullptr) != 0) {
588 return ErrnoError() << "Failed to call '/system/bin/apexd --unmount-all'";
589 }
590 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
591 return {};
592 }
593 return Error() << "'/system/bin/apexd --unmount-all' failed : " << status;
594}
595
Tom Cherry44aceed2018-08-03 13:36:18 -0700596//* Reboot / shutdown the system.
597// cmd ANDROID_RB_* as defined in android_reboot.h
598// reason Reason string like "reboot", "shutdown,userrequested"
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100599// reboot_target Reboot target string like "bootloader". Otherwise, it should be an empty string.
600// run_fsck Whether to run fsck after umount is done.
Tom Cherry44aceed2018-08-03 13:36:18 -0700601//
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100602static void DoReboot(unsigned int cmd, const std::string& reason, const std::string& reboot_target,
603 bool run_fsck) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700604 Timer t;
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100605 LOG(INFO) << "Reboot start, reason: " << reason << ", reboot_target: " << reboot_target;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700606
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700607 bool is_thermal_shutdown = cmd == ANDROID_RB_THERMOFF;
608
609 auto shutdown_timeout = 0ms;
610 if (!SHUTDOWN_ZERO_TIMEOUT) {
Wei Wangb5de0882018-10-09 12:42:06 -0700611 constexpr unsigned int shutdown_timeout_default = 6;
612 constexpr unsigned int max_thermal_shutdown_timeout = 3;
613 auto shutdown_timeout_final = android::base::GetUintProperty("ro.build.shutdown_timeout",
614 shutdown_timeout_default);
615 if (is_thermal_shutdown && shutdown_timeout_final > max_thermal_shutdown_timeout) {
616 shutdown_timeout_final = max_thermal_shutdown_timeout;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700617 }
Wei Wangb5de0882018-10-09 12:42:06 -0700618 shutdown_timeout = std::chrono::seconds(shutdown_timeout_final);
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700619 }
620 LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " ms";
621
josephjangaaddf282019-04-16 18:46:24 +0800622 sem_t reboot_semaphore;
623 if (sem_init(&reboot_semaphore, false, 0) == -1) {
624 // These should never fail, but if they do, skip the graceful reboot and reboot immediately.
625 LOG(ERROR) << "sem_init() fail and RebootSystem() return!";
Sayanna Chandula5754b5a2022-10-04 15:06:05 -0700626 RebootSystem(cmd, reboot_target, reason);
josephjangaaddf282019-04-16 18:46:24 +0800627 }
628
629 // Start a thread to monitor init shutdown process
630 LOG(INFO) << "Create reboot monitor thread.";
631 bool reboot_monitor_run = true;
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100632 std::thread reboot_monitor_thread(&RebootMonitorThread, cmd, reboot_target, &reboot_semaphore,
josephjangaaddf282019-04-16 18:46:24 +0800633 shutdown_timeout, &reboot_monitor_run);
634 reboot_monitor_thread.detach();
635
636 // Start reboot monitor thread
637 sem_post(&reboot_semaphore);
638
Tom Cherry10615eb2020-03-31 16:31:37 -0700639 // Ensure last reboot reason is reduced to canonical
640 // alias reported in bootloader or system boot reason.
641 size_t skip = 0;
642 std::vector<std::string> reasons = Split(reason, ",");
643 if (reasons.size() >= 2 && reasons[0] == "reboot" &&
644 (reasons[1] == "recovery" || reasons[1] == "bootloader" || reasons[1] == "cold" ||
645 reasons[1] == "hard" || reasons[1] == "warm")) {
646 skip = strlen("reboot,");
647 }
648 PersistRebootReason(reason.c_str() + skip, true);
649
650 // If /data isn't mounted then we can skip the extra reboot steps below, since we don't need to
651 // worry about unmounting it.
Jaegeuk Kim3e595d52022-04-15 12:31:46 -0700652 if (!IsDataMounted("*")) {
Tom Cherry10615eb2020-03-31 16:31:37 -0700653 sync();
Sayanna Chandula5754b5a2022-10-04 15:06:05 -0700654 RebootSystem(cmd, reboot_target, reason);
Tom Cherry10615eb2020-03-31 16:31:37 -0700655 abort();
656 }
657
zengshuchuan21c97a52021-08-10 14:04:34 +0800658 bool do_shutdown_animation = GetBoolProperty("ro.init.shutdown_animation", false);
Keun-young Park7830d592017-03-27 16:07:02 -0700659 // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700660 const std::set<std::string> to_starts{"watchdogd"};
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000661 std::set<std::string> stop_first;
Tom Cherry911b9b12017-07-27 16:20:58 -0700662 for (const auto& s : ServiceList::GetInstance()) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100663 if (kDebuggingServices.count(s->name())) {
664 // keep debugging tools until non critical ones are all gone.
Keun-young Park7830d592017-03-27 16:07:02 -0700665 s->SetShutdownCritical();
666 } else if (to_starts.count(s->name())) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900667 if (auto result = s->Start(); !result.ok()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700668 LOG(ERROR) << "Could not start shutdown 'to_start' service '" << s->name()
669 << "': " << result.error();
670 }
Keun-young Park7830d592017-03-27 16:07:02 -0700671 s->SetShutdownCritical();
David Anderson07533c52023-06-02 12:00:12 -0700672 } else if (do_shutdown_animation && s->classnames().count("animation") > 0) {
673 // Need these for shutdown animations.
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700674 } else if (s->IsShutdownCritical()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700675 // Start shutdown critical service if not started.
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900676 if (auto result = s->Start(); !result.ok()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700677 LOG(ERROR) << "Could not start shutdown critical service '" << s->name()
678 << "': " << result.error();
679 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100680 } else {
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000681 stop_first.insert(s->name());
Keun-young Park8d01f632017-03-13 11:54:47 -0700682 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700683 }
Keun-young Park7830d592017-03-27 16:07:02 -0700684
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800685 // remaining operations (specifically fsck) may take a substantial duration
zengshuchuan21c97a52021-08-10 14:04:34 +0800686 if (!do_shutdown_animation && (cmd == ANDROID_RB_POWEROFF || is_thermal_shutdown)) {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800687 TurnOffBacklight();
688 }
689
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100690 Service* boot_anim = ServiceList::GetInstance().FindService("bootanim");
691 Service* surface_flinger = ServiceList::GetInstance().FindService("surfaceflinger");
692 if (boot_anim != nullptr && surface_flinger != nullptr && surface_flinger->IsRunning()) {
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800693
694 if (do_shutdown_animation) {
Tom Cherryc88d8f92019-08-19 15:21:25 -0700695 SetProperty("service.bootanim.exit", "0");
Nicolas Geoffraye106f0a2020-12-15 18:34:47 +0000696 SetProperty("service.bootanim.progress", "0");
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800697 // Could be in the middle of animation. Stop and start so that it can pick
698 // up the right mode.
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100699 boot_anim->Stop();
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800700 }
701
Tom Cherry911b9b12017-07-27 16:20:58 -0700702 for (const auto& service : ServiceList::GetInstance()) {
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800703 if (service->classnames().count("animation") == 0) {
704 continue;
705 }
706
707 // start all animation classes if stopped.
708 if (do_shutdown_animation) {
Tom Cherry9949ec52019-05-16 16:54:49 -0700709 service->Start();
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800710 }
711 service->SetShutdownCritical(); // will not check animation class separately
712 }
713
714 if (do_shutdown_animation) {
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100715 boot_anim->Start();
716 surface_flinger->SetShutdownCritical();
717 boot_anim->SetShutdownCritical();
Tom Cherry911b9b12017-07-27 16:20:58 -0700718 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700719 }
Keun-young Park7830d592017-03-27 16:07:02 -0700720
Keun-young Park8d01f632017-03-13 11:54:47 -0700721 // optional shutdown step
722 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Keun-young Park30173872017-07-18 10:58:28 -0700723 if (shutdown_timeout > 0ms) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100724 StopServicesAndLogViolations(stop_first, shutdown_timeout / 2, true /* SIGTERM */);
Keun-young Park8d01f632017-03-13 11:54:47 -0700725 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100726 // Send SIGKILL to ones that didn't terminate cleanly.
727 StopServicesAndLogViolations(stop_first, 0ms, false /* SIGKILL */);
Luis Hector Chavez92c49bc2018-07-27 11:19:25 -0700728 SubcontextTerminate();
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100729 // Reap subcontext pids.
Tom Cherryeeee8312017-07-28 15:22:23 -0700730 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700731
Martijn Coenen860ba642020-05-28 16:42:10 +0200732 // 3. send volume abort_fuse and volume shutdown to vold
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100733 Service* vold_service = ServiceList::GetInstance().FindService("vold");
734 if (vold_service != nullptr && vold_service->IsRunning()) {
Martijn Coenen860ba642020-05-28 16:42:10 +0200735 // Manually abort FUSE connections, since the FUSE daemon is already dead
736 // at this point, and unmounting it might hang.
737 CallVdc("volume", "abort_fuse");
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000738 CallVdc("volume", "shutdown");
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100739 vold_service->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700740 } else {
741 LOG(INFO) << "vold not running, skipping vold shutdown";
742 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700743 // logcat stopped here
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000744 StopServices(kDebuggingServices, 0ms, false /* SIGKILL */);
Keun-young Park8d01f632017-03-13 11:54:47 -0700745 // 4. sync, try umount, and optionally run fsck for user shutdown
Tom Cherry1f9d5402018-03-15 10:22:40 -0700746 {
747 Timer sync_timer;
748 LOG(INFO) << "sync() before umount...";
749 sync();
750 LOG(INFO) << "sync() before umount took" << sync_timer;
751 }
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800752 // 5. drop caches and disable zram backing device, if exist
753 KillZramBackingDevice();
754
Nikita Ioffe91a98482020-06-10 00:53:59 +0100755 LOG(INFO) << "Ready to unmount apexes. So far shutdown sequence took " << t;
756 // 6. unmount active apexes, otherwise they might prevent clean unmount of /data.
757 if (auto ret = UnmountAllApexes(); !ret.ok()) {
758 LOG(ERROR) << ret.error();
759 }
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100760 UmountStat stat =
761 TryUmountAndFsck(cmd, run_fsck, shutdown_timeout - t.duration(), &reboot_semaphore);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700762 // Follow what linux shutdown is doing: one more sync with little bit delay
Tom Cherry1f9d5402018-03-15 10:22:40 -0700763 {
764 Timer sync_timer;
765 LOG(INFO) << "sync() after umount...";
766 sync();
767 LOG(INFO) << "sync() after umount took" << sync_timer;
768 }
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700769 if (!is_thermal_shutdown) std::this_thread::sleep_for(100ms);
Keun-young Park8d01f632017-03-13 11:54:47 -0700770 LogShutdownTime(stat, &t);
josephjangaaddf282019-04-16 18:46:24 +0800771
772 // Send signal to terminate reboot monitor thread.
773 reboot_monitor_run = false;
774 sem_post(&reboot_semaphore);
775
Keun-young Park8d01f632017-03-13 11:54:47 -0700776 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
Jaegeuk Kim3e595d52022-04-15 12:31:46 -0700777 if (IsDataMounted("f2fs")) {
778 uint32_t flag = F2FS_GOING_DOWN_FULLSYNC;
779 unique_fd fd(TEMP_FAILURE_RETRY(open("/data", O_RDONLY)));
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800780 int ret = ioctl(fd.get(), F2FS_IOC_SHUTDOWN, &flag);
Jaegeuk Kim3e595d52022-04-15 12:31:46 -0700781 if (ret) {
782 PLOG(ERROR) << "Shutdown /data: ";
783 } else {
784 LOG(INFO) << "Shutdown /data";
785 }
786 }
Sayanna Chandula5754b5a2022-10-04 15:06:05 -0700787 RebootSystem(cmd, reboot_target, reason);
Keun-young Park8d01f632017-03-13 11:54:47 -0700788 abort();
789}
Tom Cherry98ad32a2017-04-17 16:34:20 -0700790
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100791static void EnterShutdown() {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100792 LOG(INFO) << "Entering shutdown mode";
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100793 shutting_down = true;
794 // Skip wait for prop if it is in progress
795 ResetWaitForProp();
796 // Clear EXEC flag if there is one pending
797 for (const auto& s : ServiceList::GetInstance()) {
798 s->UnSetExec();
799 }
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100800}
801
Sam Protsenko2c7c3c72019-12-26 21:55:08 +0200802/**
803 * Check if "command" field is set in bootloader message.
804 *
805 * If "command" field is broken (contains non-printable characters prior to
806 * terminating zero), it will be zeroed.
807 *
808 * @param[in,out] boot Bootloader message (BCB) structure
809 * @return true if "command" field is already set, and false if it's empty
810 */
811static bool CommandIsPresent(bootloader_message* boot) {
812 if (boot->command[0] == '\0')
813 return false;
814
815 for (size_t i = 0; i < arraysize(boot->command); ++i) {
816 if (boot->command[i] == '\0')
817 return true;
818 if (!isprint(boot->command[i]))
819 break;
820 }
821
822 memset(boot->command, 0, sizeof(boot->command));
823 return false;
824}
825
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100826void HandlePowerctlMessage(const std::string& command) {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700827 unsigned int cmd = 0;
Mark Salyzyn62909822017-10-09 09:27:16 -0700828 std::vector<std::string> cmd_params = Split(command, ",");
Tom Cherry98ad32a2017-04-17 16:34:20 -0700829 std::string reboot_target = "";
830 bool run_fsck = false;
831 bool command_invalid = false;
832
Mark Salyzynd7931f12019-07-10 10:33:09 -0700833 if (cmd_params[0] == "shutdown") {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700834 cmd = ANDROID_RB_POWEROFF;
Mark Salyzynd7931f12019-07-10 10:33:09 -0700835 if (cmd_params.size() >= 2) {
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700836 if (cmd_params[1] == "userrequested") {
837 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
838 // Run fsck once the file system is remounted in read-only mode.
839 run_fsck = true;
840 } else if (cmd_params[1] == "thermal") {
Mark Salyzynbfd05b62017-09-26 11:10:12 -0700841 // Turn off sources of heat immediately.
842 TurnOffBacklight();
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700843 // run_fsck is false to avoid delay
844 cmd = ANDROID_RB_THERMOFF;
845 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700846 }
847 } else if (cmd_params[0] == "reboot") {
848 cmd = ANDROID_RB_RESTART2;
849 if (cmd_params.size() >= 2) {
850 reboot_target = cmd_params[1];
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100851 if (reboot_target == "userspace") {
Jooyung Hane34549a2024-08-09 15:58:53 +0900852 LOG(ERROR) << "Userspace reboot is deprecated.";
853 return;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100854 }
Hridya Valsaraju54258262018-09-19 21:14:18 -0700855 // adb reboot fastboot should boot into bootloader for devices not
856 // supporting logical partitions.
857 if (reboot_target == "fastboot" &&
Yifan Hong0e0f8182018-11-16 12:49:06 -0800858 !android::base::GetBoolProperty("ro.boot.dynamic_partitions", false)) {
Hridya Valsaraju54258262018-09-19 21:14:18 -0700859 reboot_target = "bootloader";
860 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700861 // When rebooting to the bootloader notify the bootloader writing
862 // also the BCB.
863 if (reboot_target == "bootloader") {
864 std::string err;
865 if (!write_reboot_bootloader(&err)) {
866 LOG(ERROR) << "reboot-bootloader: Error writing "
867 "bootloader_message: "
868 << err;
869 }
Tianjie Xu5e98b632019-07-18 12:48:28 -0700870 } else if (reboot_target == "recovery") {
871 bootloader_message boot = {};
872 if (std::string err; !read_bootloader_message(&boot, &err)) {
873 LOG(ERROR) << "Failed to read bootloader message: " << err;
874 }
875 // Update the boot command field if it's empty, and preserve
876 // the other arguments in the bootloader message.
Sam Protsenko2c7c3c72019-12-26 21:55:08 +0200877 if (!CommandIsPresent(&boot)) {
Tianjie Xu5e98b632019-07-18 12:48:28 -0700878 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
879 if (std::string err; !write_bootloader_message(boot, &err)) {
880 LOG(ERROR) << "Failed to set bootloader message: " << err;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100881 return;
Tianjie Xu5e98b632019-07-18 12:48:28 -0700882 }
883 }
Veena Arvindb46e5e62024-03-07 22:55:28 +0000884 } else if (std::find(cmd_params.begin(), cmd_params.end(), "quiescent")
885 != cmd_params.end()) { // Quiescent can be either subreason or details.
Chenfu.Liaod672e472021-06-29 15:41:22 +0800886 bootloader_message boot = {};
887 if (std::string err; !read_bootloader_message(&boot, &err)) {
888 LOG(ERROR) << "Failed to read bootloader message: " << err;
889 }
890 // Update the boot command field if it's empty, and preserve
891 // the other arguments in the bootloader message.
892 if (!CommandIsPresent(&boot)) {
893 strlcpy(boot.command, "boot-quiescent", sizeof(boot.command));
894 if (std::string err; !write_bootloader_message(boot, &err)) {
895 LOG(ERROR) << "Failed to set bootloader message: " << err;
896 return;
897 }
898 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700899 } else if (reboot_target == "sideload" || reboot_target == "sideload-auto-reboot" ||
900 reboot_target == "fastboot") {
901 std::string arg = reboot_target == "sideload-auto-reboot" ? "sideload_auto_reboot"
902 : reboot_target;
903 const std::vector<std::string> options = {
904 "--" + arg,
905 };
906 std::string err;
907 if (!write_bootloader_message(options, &err)) {
908 LOG(ERROR) << "Failed to set bootloader message: " << err;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100909 return;
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700910 }
911 reboot_target = "recovery";
Tom Cherry98ad32a2017-04-17 16:34:20 -0700912 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700913
Mark Salyzynd7931f12019-07-10 10:33:09 -0700914 // If there are additional parameter, pass them along
915 for (size_t i = 2; (cmd_params.size() > i) && cmd_params[i].size(); ++i) {
916 reboot_target += "," + cmd_params[i];
Tom Cherry98ad32a2017-04-17 16:34:20 -0700917 }
918 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700919 } else {
920 command_invalid = true;
921 }
922 if (command_invalid) {
923 LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100924 return;
925 }
926
Tom Cherry802864c2020-03-12 14:29:25 -0700927 // We do not want to process any messages (queue'ing triggers, shutdown messages, control
928 // messages, etc) from properties during reboot.
929 StopSendingMessages();
930
Wei Wangeeab4912017-06-27 22:08:45 -0700931 LOG(INFO) << "Clear action queue and start shutdown trigger";
932 ActionManager::GetInstance().ClearQueue();
933 // Queue shutdown trigger first
934 ActionManager::GetInstance().QueueEventTrigger("shutdown");
935 // Queue built-in shutdown_done
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700936 auto shutdown_handler = [cmd, command, reboot_target, run_fsck](const BuiltinArguments&) {
Wei Wangeeab4912017-06-27 22:08:45 -0700937 DoReboot(cmd, command, reboot_target, run_fsck);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700938 return Result<void>{};
Wei Wangeeab4912017-06-27 22:08:45 -0700939 };
940 ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
941
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100942 EnterShutdown();
943}
Wei Wangeeab4912017-06-27 22:08:45 -0700944
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100945bool IsShuttingDown() {
946 return shutting_down;
Tom Cherry98ad32a2017-04-17 16:34:20 -0700947}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700948
949} // namespace init
950} // namespace android