blob: a3fc534195c96b0391494dca8445ad0538e7cffe [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>
54#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 Ioffe7ba50302020-11-27 18:57:44 +000089static std::set<std::string> GetPostDataDebuggingServices() {
90 std::set<std::string> ret;
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010091 for (const auto& s : ServiceList::GetInstance()) {
Nikita Ioffe7ba50302020-11-27 18:57:44 +000092 if (kDebuggingServices.count(s->name()) && s->is_post_data()) {
93 ret.insert(s->name());
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010094 }
95 }
96 return ret;
97}
98
Nikita Ioffed485bbb2020-02-26 15:18:56 +000099static void PersistRebootReason(const char* reason, bool write_to_property) {
100 if (write_to_property) {
101 SetProperty(LAST_REBOOT_REASON_PROPERTY, reason);
102 }
Tom Cherry10615eb2020-03-31 16:31:37 -0700103 auto fd = unique_fd(TEMP_FAILURE_RETRY(open(
104 LAST_REBOOT_REASON_FILE, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY, 0666)));
105 if (!fd.ok()) {
106 PLOG(ERROR) << "Could not open '" << LAST_REBOOT_REASON_FILE
107 << "' to persist reboot reason";
108 return;
109 }
110 WriteStringToFd(reason, fd);
111 fsync(fd.get());
Nikita Ioffed0bc0b62020-02-19 16:21:11 +0000112}
113
Keun-young Park8d01f632017-03-13 11:54:47 -0700114// represents umount status during reboot / shutdown.
115enum UmountStat {
116 /* umount succeeded. */
117 UMOUNT_STAT_SUCCESS = 0,
118 /* umount was not run. */
119 UMOUNT_STAT_SKIPPED = 1,
120 /* umount failed with timeout. */
121 UMOUNT_STAT_TIMEOUT = 2,
122 /* could not run due to error */
123 UMOUNT_STAT_ERROR = 3,
124 /* not used by init but reserved for other part to use this to represent the
125 the state where umount status before reboot is not found / available. */
126 UMOUNT_STAT_NOT_AVAILABLE = 4,
127};
128
129// Utility for struct mntent
130class MountEntry {
131 public:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700132 explicit MountEntry(const mntent& entry)
Keun-young Park8d01f632017-03-13 11:54:47 -0700133 : mnt_fsname_(entry.mnt_fsname),
134 mnt_dir_(entry.mnt_dir),
135 mnt_type_(entry.mnt_type),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700136 mnt_opts_(entry.mnt_opts) {}
Keun-young Park8d01f632017-03-13 11:54:47 -0700137
Jaegeuk Kim0f04f722017-09-25 10:55:39 -0700138 bool Umount(bool force) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800139 LOG(INFO) << "Unmounting " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Jaegeuk Kim0f04f722017-09-25 10:55:39 -0700140 int r = umount2(mnt_dir_.c_str(), force ? MNT_FORCE : 0);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700141 if (r == 0) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800142 LOG(INFO) << "Umounted " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700143 return true;
144 } else {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800145 PLOG(WARNING) << "Cannot umount " << mnt_fsname_ << ":" << mnt_dir_ << " opts "
Keun-young Park2ba5c812017-03-29 12:54:40 -0700146 << mnt_opts_;
147 return false;
148 }
149 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700150
Keun-young Park2ba5c812017-03-29 12:54:40 -0700151 void DoFsck() {
152 int st;
153 if (IsF2Fs()) {
154 const char* f2fs_argv[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800155 "/system/bin/fsck.f2fs",
156 "-a",
157 mnt_fsname_.c_str(),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700158 };
Tom Cherry3a803eb2019-09-25 16:23:50 -0700159 logwrap_fork_execvp(arraysize(f2fs_argv), f2fs_argv, &st, false, LOG_KLOG, true,
160 nullptr);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700161 } else if (IsExt4()) {
162 const char* ext4_argv[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800163 "/system/bin/e2fsck",
164 "-y",
165 mnt_fsname_.c_str(),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700166 };
Tom Cherry3a803eb2019-09-25 16:23:50 -0700167 logwrap_fork_execvp(arraysize(ext4_argv), ext4_argv, &st, false, LOG_KLOG, true,
168 nullptr);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700169 }
170 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700171
172 static bool IsBlockDevice(const struct mntent& mntent) {
173 return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
174 }
175
176 static bool IsEmulatedDevice(const struct mntent& mntent) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700177 return android::base::StartsWith(mntent.mnt_fsname, "/data/");
Keun-young Park8d01f632017-03-13 11:54:47 -0700178 }
179
180 private:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700181 bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
182
183 bool IsExt4() const { return mnt_type_ == "ext4"; }
184
Keun-young Park8d01f632017-03-13 11:54:47 -0700185 std::string mnt_fsname_;
186 std::string mnt_dir_;
187 std::string mnt_type_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700188 std::string mnt_opts_;
Keun-young Park8d01f632017-03-13 11:54:47 -0700189};
190
191// Turn off backlight while we are performing power down cleanup activities.
Tom Cherry832f9f12020-03-10 11:47:24 -0700192static void TurnOffBacklight() {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800193 Service* service = ServiceList::GetInstance().FindService("blank_screen");
194 if (service == nullptr) {
195 LOG(WARNING) << "cannot find blank_screen in TurnOffBacklight";
Keun-young Park8d01f632017-03-13 11:54:47 -0700196 return;
197 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900198 if (auto result = service->Start(); !result.ok()) {
Tom Cherryd9872642018-10-11 10:38:05 -0700199 LOG(WARNING) << "Could not start blank_screen service: " << result.error();
200 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700201}
202
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000203static Result<void> CallVdc(const std::string& system, const std::string& cmd) {
Nikita Ioffea3be9962020-04-16 21:37:03 +0100204 LOG(INFO) << "Calling /system/bin/vdc " << system << " " << cmd;
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000205 const char* vdc_argv[] = {"/system/bin/vdc", system.c_str(), cmd.c_str()};
Keun-young Park8d01f632017-03-13 11:54:47 -0700206 int status;
Nikita Ioffe12a36072019-10-23 20:11:32 +0100207 if (logwrap_fork_execvp(arraysize(vdc_argv), vdc_argv, &status, false, LOG_KLOG, true,
208 nullptr) != 0) {
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000209 return ErrnoError() << "Failed to call '/system/bin/vdc " << system << " " << cmd << "'";
Nikita Ioffe12a36072019-10-23 20:11:32 +0100210 }
211 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
212 return {};
213 }
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000214 return Error() << "'/system/bin/vdc " << system << " " << cmd << "' failed : " << status;
Keun-young Park8d01f632017-03-13 11:54:47 -0700215}
216
217static void LogShutdownTime(UmountStat stat, Timer* t) {
Tom Cherryede0d532017-07-06 14:20:11 -0700218 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration().count()) << ":"
219 << stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700220}
221
Jaegeuk Kim3e595d52022-04-15 12:31:46 -0700222static bool IsDataMounted(const std::string& fstype) {
Tom Cherry2436e6b2019-09-19 11:16:19 -0700223 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
224 if (fp == nullptr) {
225 PLOG(ERROR) << "Failed to open /proc/mounts";
226 return false;
227 }
228 mntent* mentry;
229 while ((mentry = getmntent(fp.get())) != nullptr) {
230 if (mentry->mnt_dir == "/data"s) {
Jaegeuk Kim3e595d52022-04-15 12:31:46 -0700231 return fstype == "*" || mentry->mnt_type == fstype;
Tom Cherry2436e6b2019-09-19 11:16:19 -0700232 }
233 }
234 return false;
235}
236
237// Find all read+write block devices and emulated devices in /proc/mounts and add them to
238// the correpsponding list.
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100239static bool FindPartitionsToUmount(std::vector<MountEntry>* block_dev_partitions,
240 std::vector<MountEntry>* emulated_partitions, bool dump) {
Tom Cherryf274e782018-10-03 13:13:41 -0700241 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
Keun-young Park8d01f632017-03-13 11:54:47 -0700242 if (fp == nullptr) {
243 PLOG(ERROR) << "Failed to open /proc/mounts";
244 return false;
245 }
246 mntent* mentry;
247 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700248 if (dump) {
249 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
250 << mentry->mnt_opts << " type " << mentry->mnt_type;
251 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
Keun-young Park6e12b382017-07-17 12:20:33 -0700252 std::string mount_dir(mentry->mnt_dir);
253 // These are R/O partitions changed to R/W after adb remount.
254 // Do not umount them as shutdown critical services may rely on them.
Wei Wanga01c27e2017-07-25 10:52:08 -0700255 if (mount_dir != "/" && mount_dir != "/system" && mount_dir != "/vendor" &&
256 mount_dir != "/oem") {
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100257 block_dev_partitions->emplace(block_dev_partitions->begin(), *mentry);
Keun-young Park6e12b382017-07-17 12:20:33 -0700258 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700259 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100260 emulated_partitions->emplace(emulated_partitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700261 }
262 }
263 return true;
264}
265
Jonglin Lee28a2c922019-01-15 16:38:44 -0800266static void DumpUmountDebuggingInfo() {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700267 int status;
268 if (!security_getenforce()) {
269 LOG(INFO) << "Run lsof";
270 const char* lsof_argv[] = {"/system/bin/lsof"};
Tom Cherry3a803eb2019-09-25 16:23:50 -0700271 logwrap_fork_execvp(arraysize(lsof_argv), lsof_argv, &status, false, LOG_KLOG, true,
272 nullptr);
Keun-young Park8d01f632017-03-13 11:54:47 -0700273 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700274 FindPartitionsToUmount(nullptr, nullptr, true);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800275 // dump current CPU stack traces and uninterruptible tasks
josephjangaaddf282019-04-16 18:46:24 +0800276 WriteStringToFile("l", PROC_SYSRQ);
277 WriteStringToFile("w", PROC_SYSRQ);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700278}
279
Tom Cherryede0d532017-07-06 14:20:11 -0700280static UmountStat UmountPartitions(std::chrono::milliseconds timeout) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700281 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700282 /* data partition needs all pending writes to be completed and all emulated partitions
283 * umounted.If the current waiting is not good enough, give
284 * up and leave it to e2fsck after reboot to fix it.
285 */
286 while (true) {
287 std::vector<MountEntry> block_devices;
288 std::vector<MountEntry> emulated_devices;
289 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
290 return UMOUNT_STAT_ERROR;
291 }
292 if (block_devices.size() == 0) {
Wei Wang8c00e422017-08-16 14:01:46 -0700293 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700294 }
Wei Wang8c00e422017-08-16 14:01:46 -0700295 bool unmount_done = true;
296 if (emulated_devices.size() > 0) {
Wei Wang25dc30f2017-10-23 15:32:03 -0700297 for (auto& entry : emulated_devices) {
298 if (!entry.Umount(false)) unmount_done = false;
299 }
Wei Wang8c00e422017-08-16 14:01:46 -0700300 if (unmount_done) {
301 sync();
302 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700303 }
Wei Wang25dc30f2017-10-23 15:32:03 -0700304 for (auto& entry : block_devices) {
305 if (!entry.Umount(timeout == 0ms)) unmount_done = false;
306 }
Wei Wang8c00e422017-08-16 14:01:46 -0700307 if (unmount_done) {
308 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700309 }
Wei Wang8c00e422017-08-16 14:01:46 -0700310 if ((timeout < t.duration())) { // try umount at least once
311 return UMOUNT_STAT_TIMEOUT;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700312 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700313 std::this_thread::sleep_for(100ms);
314 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700315}
316
josephjangaaddf282019-04-16 18:46:24 +0800317static void KillAllProcesses() {
318 WriteStringToFile("i", PROC_SYSRQ);
319}
320
321// Create reboot/shutdwon monitor thread
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100322void RebootMonitorThread(unsigned int cmd, const std::string& reboot_target,
323 sem_t* reboot_semaphore, std::chrono::milliseconds shutdown_timeout,
324 bool* reboot_monitor_run) {
josephjangaaddf282019-04-16 18:46:24 +0800325 unsigned int remaining_shutdown_time = 0;
326
Tom Cherry10615eb2020-03-31 16:31:37 -0700327 // 300 seconds more than the timeout passed to the thread as there is a final Umount pass
josephjangaaddf282019-04-16 18:46:24 +0800328 // after the timeout is reached.
Tom Cherry10615eb2020-03-31 16:31:37 -0700329 constexpr unsigned int shutdown_watchdog_timeout_default = 300;
josephjangaaddf282019-04-16 18:46:24 +0800330 auto shutdown_watchdog_timeout = android::base::GetUintProperty(
331 "ro.build.shutdown.watchdog.timeout", shutdown_watchdog_timeout_default);
332 remaining_shutdown_time = shutdown_watchdog_timeout + shutdown_timeout.count() / 1000;
333
334 while (*reboot_monitor_run == true) {
335 if (TEMP_FAILURE_RETRY(sem_wait(reboot_semaphore)) == -1) {
336 LOG(ERROR) << "sem_wait failed and exit RebootMonitorThread()";
337 return;
338 }
339
340 timespec shutdown_timeout_timespec;
341 if (clock_gettime(CLOCK_MONOTONIC, &shutdown_timeout_timespec) == -1) {
342 LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
343 return;
344 }
345
346 // If there are some remaining shutdown time left from previous round, we use
347 // remaining time here.
348 shutdown_timeout_timespec.tv_sec += remaining_shutdown_time;
349
350 LOG(INFO) << "shutdown_timeout_timespec.tv_sec: " << shutdown_timeout_timespec.tv_sec;
351
352 int sem_return = 0;
353 while ((sem_return = sem_timedwait_monotonic_np(reboot_semaphore,
354 &shutdown_timeout_timespec)) == -1 &&
355 errno == EINTR) {
356 }
357
358 if (sem_return == -1) {
359 LOG(ERROR) << "Reboot thread timed out";
360
361 if (android::base::GetBoolProperty("ro.debuggable", false) == true) {
Tom Cherry2436e6b2019-09-19 11:16:19 -0700362 if (false) {
363 // SEPolicy will block debuggerd from running and this is intentional.
364 // But these lines are left to be enabled during debugging.
365 LOG(INFO) << "Try to dump init process call trace:";
366 const char* vdc_argv[] = {"/system/bin/debuggerd", "-b", "1"};
367 int status;
Tom Cherry3a803eb2019-09-25 16:23:50 -0700368 logwrap_fork_execvp(arraysize(vdc_argv), vdc_argv, &status, false, LOG_KLOG,
369 true, nullptr);
Tom Cherry2436e6b2019-09-19 11:16:19 -0700370 }
josephjangaaddf282019-04-16 18:46:24 +0800371 LOG(INFO) << "Show stack for all active CPU:";
372 WriteStringToFile("l", PROC_SYSRQ);
373
374 LOG(INFO) << "Show tasks that are in disk sleep(uninterruptable sleep), which are "
375 "like "
376 "blocked in mutex or hardware register access:";
377 WriteStringToFile("w", PROC_SYSRQ);
378 }
379
380 // In shutdown case,notify kernel to sync and umount fs to read-only before shutdown.
381 if (cmd == ANDROID_RB_POWEROFF || cmd == ANDROID_RB_THERMOFF) {
382 WriteStringToFile("s", PROC_SYSRQ);
383
384 WriteStringToFile("u", PROC_SYSRQ);
385
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100386 RebootSystem(cmd, reboot_target);
josephjangaaddf282019-04-16 18:46:24 +0800387 }
388
389 LOG(ERROR) << "Trigger crash at last!";
390 WriteStringToFile("c", PROC_SYSRQ);
391 } else {
392 timespec current_time_timespec;
393
394 if (clock_gettime(CLOCK_MONOTONIC, &current_time_timespec) == -1) {
395 LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
396 return;
397 }
398
399 remaining_shutdown_time =
400 shutdown_timeout_timespec.tv_sec - current_time_timespec.tv_sec;
401
402 LOG(INFO) << "remaining_shutdown_time: " << remaining_shutdown_time;
403 }
404 }
405}
Keun-young Park3ee0df92017-03-27 11:21:09 -0700406
Keun-young Park8d01f632017-03-13 11:54:47 -0700407/* Try umounting all emulated file systems R/W block device cfile systems.
408 * This will just try umount and give it up if it fails.
409 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
410 * and necessary check can be done at the next reboot.
411 * For safer shutdown, caller needs to make sure that
412 * all processes / emulated partition for the target fs are all cleaned-up.
413 *
414 * return true when umount was successful. false when timed out.
415 */
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100416static UmountStat TryUmountAndFsck(unsigned int cmd, bool run_fsck,
josephjangaaddf282019-04-16 18:46:24 +0800417 std::chrono::milliseconds timeout, sem_t* reboot_semaphore) {
Keun-young Park3ee0df92017-03-27 11:21:09 -0700418 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700419 std::vector<MountEntry> block_devices;
420 std::vector<MountEntry> emulated_devices;
Keun-young Park8d01f632017-03-13 11:54:47 -0700421
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100422 if (run_fsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700423 return UMOUNT_STAT_ERROR;
424 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700425
Tom Cherryede0d532017-07-06 14:20:11 -0700426 UmountStat stat = UmountPartitions(timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700427 if (stat != UMOUNT_STAT_SUCCESS) {
428 LOG(INFO) << "umount timeout, last resort, kill all and try";
Jonglin Lee28a2c922019-01-15 16:38:44 -0800429 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park3ee0df92017-03-27 11:21:09 -0700430 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700431 // 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 -0700432 UmountStat st = UmountPartitions(0ms);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800433 if ((st != UMOUNT_STAT_SUCCESS) && DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park8d01f632017-03-13 11:54:47 -0700434 }
435
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100436 if (stat == UMOUNT_STAT_SUCCESS && run_fsck) {
josephjangaaddf282019-04-16 18:46:24 +0800437 LOG(INFO) << "Pause reboot monitor thread before fsck";
438 sem_post(reboot_semaphore);
439
Keun-young Park2ba5c812017-03-29 12:54:40 -0700440 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
441 // and should not affect reboot time.
442 for (auto& entry : block_devices) {
443 entry.DoFsck();
444 }
josephjangaaddf282019-04-16 18:46:24 +0800445
446 LOG(INFO) << "Resume reboot monitor thread after fsck";
447 sem_post(reboot_semaphore);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700448 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700449 return stat;
450}
451
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800452// zram is able to use backing device on top of a loopback device.
453// In order to unmount /data successfully, we have to kill the loopback device first
luwei98a3653c2021-04-14 14:34:59 +0800454#define ZRAM_DEVICE "/dev/block/zram0"
455#define ZRAM_RESET "/sys/block/zram0/reset"
456#define ZRAM_BACK_DEV "/sys/block/zram0/backing_dev"
457#define ZRAM_INITSTATE "/sys/block/zram0/initstate"
Nikita Ioffe12a36072019-10-23 20:11:32 +0100458static Result<void> KillZramBackingDevice() {
luwei98a3653c2021-04-14 14:34:59 +0800459 std::string zram_initstate;
460 if (!android::base::ReadFileToString(ZRAM_INITSTATE, &zram_initstate)) {
461 return ErrnoError() << "Failed to read " << ZRAM_INITSTATE;
462 }
463
464 zram_initstate.erase(zram_initstate.length() - 1);
465 if (zram_initstate == "0") {
466 LOG(INFO) << "Zram has not been swapped on";
467 return {};
468 }
469
Nikita Ioffea3be9962020-04-16 21:37:03 +0100470 if (access(ZRAM_BACK_DEV, F_OK) != 0 && errno == ENOENT) {
471 LOG(INFO) << "No zram backing device configured";
472 return {};
473 }
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800474 std::string backing_dev;
Nikita Ioffea3be9962020-04-16 21:37:03 +0100475 if (!android::base::ReadFileToString(ZRAM_BACK_DEV, &backing_dev)) {
476 return ErrnoError() << "Failed to read " << ZRAM_BACK_DEV;
477 }
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800478
479 // cut the last "\n"
480 backing_dev.erase(backing_dev.length() - 1);
481
shisiyuan423c4f12021-05-18 11:47:43 +0800482 if (android::base::StartsWith(backing_dev, "none")) {
483 LOG(INFO) << "No zram backing device configured";
484 return {};
485 }
486
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800487 // shutdown zram handle
488 Timer swap_timer;
489 LOG(INFO) << "swapoff() start...";
490 if (swapoff(ZRAM_DEVICE) == -1) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100491 return ErrnoError() << "zram_backing_dev: swapoff (" << backing_dev << ")"
492 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800493 }
JeongHyeon Lee170855d2022-04-14 18:06:18 +0900494 LOG(INFO) << "swapoff() took " << swap_timer;
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800495
josephjangaaddf282019-04-16 18:46:24 +0800496 if (!WriteStringToFile("1", ZRAM_RESET)) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100497 return Error() << "zram_backing_dev: reset (" << backing_dev << ")"
498 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800499 }
500
Nikita Ioffea3be9962020-04-16 21:37:03 +0100501 if (!android::base::StartsWith(backing_dev, "/dev/block/loop")) {
502 LOG(INFO) << backing_dev << " is not a loop device. Exiting early";
503 return {};
504 }
505
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800506 // clear loopback device
507 unique_fd loop(TEMP_FAILURE_RETRY(open(backing_dev.c_str(), O_RDWR | O_CLOEXEC)));
508 if (loop.get() < 0) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100509 return ErrnoError() << "zram_backing_dev: open(" << backing_dev << ")"
510 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800511 }
512
513 if (ioctl(loop.get(), LOOP_CLR_FD, 0) < 0) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100514 return ErrnoError() << "zram_backing_dev: loop_clear (" << backing_dev << ")"
515 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800516 }
517 LOG(INFO) << "zram_backing_dev: `" << backing_dev << "` is cleared successfully.";
Nikita Ioffe12a36072019-10-23 20:11:32 +0100518 return {};
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800519}
520
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100521// Stops given services, waits for them to be stopped for |timeout| ms.
522// If terminate is true, then SIGTERM is sent to services, otherwise SIGKILL is sent.
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000523// Note that services are stopped in order given by |ServiceList::services_in_shutdown_order|
524// function.
525static void StopServices(const std::set<std::string>& services, std::chrono::milliseconds timeout,
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100526 bool terminate) {
527 LOG(INFO) << "Stopping " << services.size() << " services by sending "
528 << (terminate ? "SIGTERM" : "SIGKILL");
529 std::vector<pid_t> pids;
530 pids.reserve(services.size());
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000531 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
532 if (services.count(s->name()) == 0) {
533 continue;
534 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100535 if (s->pid() > 0) {
536 pids.push_back(s->pid());
537 }
538 if (terminate) {
539 s->Terminate();
540 } else {
541 s->Stop();
542 }
543 }
544 if (timeout > 0ms) {
545 WaitToBeReaped(pids, timeout);
546 } else {
547 // Even if we don't to wait for services to stop, we still optimistically reap zombies.
548 ReapAnyOutstandingChildren();
549 }
550}
551
552// Like StopServices, but also logs all the services that failed to stop after the provided timeout.
553// Returns number of violators.
Nikita Ioffe660ffde2020-12-10 16:52:35 +0000554int StopServicesAndLogViolations(const std::set<std::string>& services,
555 std::chrono::milliseconds timeout, bool terminate) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100556 StopServices(services, timeout, terminate);
557 int still_running = 0;
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000558 for (const auto& s : ServiceList::GetInstance()) {
559 if (s->IsRunning() && services.count(s->name())) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100560 LOG(ERROR) << "[service-misbehaving] : service '" << s->name() << "' is still running "
561 << timeout.count() << "ms after receiving "
562 << (terminate ? "SIGTERM" : "SIGKILL");
563 still_running++;
564 }
565 }
566 return still_running;
567}
568
Nikita Ioffe91a98482020-06-10 00:53:59 +0100569static Result<void> UnmountAllApexes() {
Inseob Kim0fbc1d72022-11-09 12:50:14 +0900570 // don't need to unmount because apexd doesn't use /data in Microdroid
571 if (IsMicrodroid()) {
572 return {};
573 }
574
Nikita Ioffe91a98482020-06-10 00:53:59 +0100575 const char* args[] = {"/system/bin/apexd", "--unmount-all"};
576 int status;
577 if (logwrap_fork_execvp(arraysize(args), args, &status, false, LOG_KLOG, true, nullptr) != 0) {
578 return ErrnoError() << "Failed to call '/system/bin/apexd --unmount-all'";
579 }
580 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
581 return {};
582 }
583 return Error() << "'/system/bin/apexd --unmount-all' failed : " << status;
584}
585
Tom Cherry44aceed2018-08-03 13:36:18 -0700586//* Reboot / shutdown the system.
587// cmd ANDROID_RB_* as defined in android_reboot.h
588// reason Reason string like "reboot", "shutdown,userrequested"
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100589// reboot_target Reboot target string like "bootloader". Otherwise, it should be an empty string.
590// run_fsck Whether to run fsck after umount is done.
Tom Cherry44aceed2018-08-03 13:36:18 -0700591//
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100592static void DoReboot(unsigned int cmd, const std::string& reason, const std::string& reboot_target,
593 bool run_fsck) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700594 Timer t;
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100595 LOG(INFO) << "Reboot start, reason: " << reason << ", reboot_target: " << reboot_target;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700596
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700597 bool is_thermal_shutdown = cmd == ANDROID_RB_THERMOFF;
598
599 auto shutdown_timeout = 0ms;
600 if (!SHUTDOWN_ZERO_TIMEOUT) {
Wei Wangb5de0882018-10-09 12:42:06 -0700601 constexpr unsigned int shutdown_timeout_default = 6;
602 constexpr unsigned int max_thermal_shutdown_timeout = 3;
603 auto shutdown_timeout_final = android::base::GetUintProperty("ro.build.shutdown_timeout",
604 shutdown_timeout_default);
605 if (is_thermal_shutdown && shutdown_timeout_final > max_thermal_shutdown_timeout) {
606 shutdown_timeout_final = max_thermal_shutdown_timeout;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700607 }
Wei Wangb5de0882018-10-09 12:42:06 -0700608 shutdown_timeout = std::chrono::seconds(shutdown_timeout_final);
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700609 }
610 LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " ms";
611
josephjangaaddf282019-04-16 18:46:24 +0800612 sem_t reboot_semaphore;
613 if (sem_init(&reboot_semaphore, false, 0) == -1) {
614 // These should never fail, but if they do, skip the graceful reboot and reboot immediately.
615 LOG(ERROR) << "sem_init() fail and RebootSystem() return!";
Sayanna Chandula5754b5a2022-10-04 15:06:05 -0700616 RebootSystem(cmd, reboot_target, reason);
josephjangaaddf282019-04-16 18:46:24 +0800617 }
618
619 // Start a thread to monitor init shutdown process
620 LOG(INFO) << "Create reboot monitor thread.";
621 bool reboot_monitor_run = true;
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100622 std::thread reboot_monitor_thread(&RebootMonitorThread, cmd, reboot_target, &reboot_semaphore,
josephjangaaddf282019-04-16 18:46:24 +0800623 shutdown_timeout, &reboot_monitor_run);
624 reboot_monitor_thread.detach();
625
626 // Start reboot monitor thread
627 sem_post(&reboot_semaphore);
628
Tom Cherry10615eb2020-03-31 16:31:37 -0700629 // Ensure last reboot reason is reduced to canonical
630 // alias reported in bootloader or system boot reason.
631 size_t skip = 0;
632 std::vector<std::string> reasons = Split(reason, ",");
633 if (reasons.size() >= 2 && reasons[0] == "reboot" &&
634 (reasons[1] == "recovery" || reasons[1] == "bootloader" || reasons[1] == "cold" ||
635 reasons[1] == "hard" || reasons[1] == "warm")) {
636 skip = strlen("reboot,");
637 }
638 PersistRebootReason(reason.c_str() + skip, true);
639
640 // If /data isn't mounted then we can skip the extra reboot steps below, since we don't need to
641 // worry about unmounting it.
Jaegeuk Kim3e595d52022-04-15 12:31:46 -0700642 if (!IsDataMounted("*")) {
Tom Cherry10615eb2020-03-31 16:31:37 -0700643 sync();
Sayanna Chandula5754b5a2022-10-04 15:06:05 -0700644 RebootSystem(cmd, reboot_target, reason);
Tom Cherry10615eb2020-03-31 16:31:37 -0700645 abort();
646 }
647
zengshuchuan21c97a52021-08-10 14:04:34 +0800648 bool do_shutdown_animation = GetBoolProperty("ro.init.shutdown_animation", false);
Keun-young Park7830d592017-03-27 16:07:02 -0700649 // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700650 const std::set<std::string> to_starts{"watchdogd"};
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000651 std::set<std::string> stop_first;
Tom Cherry911b9b12017-07-27 16:20:58 -0700652 for (const auto& s : ServiceList::GetInstance()) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100653 if (kDebuggingServices.count(s->name())) {
654 // keep debugging tools until non critical ones are all gone.
Keun-young Park7830d592017-03-27 16:07:02 -0700655 s->SetShutdownCritical();
656 } else if (to_starts.count(s->name())) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900657 if (auto result = s->Start(); !result.ok()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700658 LOG(ERROR) << "Could not start shutdown 'to_start' service '" << s->name()
659 << "': " << result.error();
660 }
Keun-young Park7830d592017-03-27 16:07:02 -0700661 s->SetShutdownCritical();
zengshuchuan21c97a52021-08-10 14:04:34 +0800662 } else if (do_shutdown_animation) {
663 continue;
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700664 } else if (s->IsShutdownCritical()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700665 // Start shutdown critical service if not started.
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900666 if (auto result = s->Start(); !result.ok()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700667 LOG(ERROR) << "Could not start shutdown critical service '" << s->name()
668 << "': " << result.error();
669 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100670 } else {
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000671 stop_first.insert(s->name());
Keun-young Park8d01f632017-03-13 11:54:47 -0700672 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700673 }
Keun-young Park7830d592017-03-27 16:07:02 -0700674
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800675 // remaining operations (specifically fsck) may take a substantial duration
zengshuchuan21c97a52021-08-10 14:04:34 +0800676 if (!do_shutdown_animation && (cmd == ANDROID_RB_POWEROFF || is_thermal_shutdown)) {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800677 TurnOffBacklight();
678 }
679
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100680 Service* boot_anim = ServiceList::GetInstance().FindService("bootanim");
681 Service* surface_flinger = ServiceList::GetInstance().FindService("surfaceflinger");
682 if (boot_anim != nullptr && surface_flinger != nullptr && surface_flinger->IsRunning()) {
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800683
684 if (do_shutdown_animation) {
Tom Cherryc88d8f92019-08-19 15:21:25 -0700685 SetProperty("service.bootanim.exit", "0");
Nicolas Geoffraye106f0a2020-12-15 18:34:47 +0000686 SetProperty("service.bootanim.progress", "0");
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800687 // Could be in the middle of animation. Stop and start so that it can pick
688 // up the right mode.
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100689 boot_anim->Stop();
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800690 }
691
Tom Cherry911b9b12017-07-27 16:20:58 -0700692 for (const auto& service : ServiceList::GetInstance()) {
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800693 if (service->classnames().count("animation") == 0) {
694 continue;
695 }
696
697 // start all animation classes if stopped.
698 if (do_shutdown_animation) {
Tom Cherry9949ec52019-05-16 16:54:49 -0700699 service->Start();
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800700 }
701 service->SetShutdownCritical(); // will not check animation class separately
702 }
703
704 if (do_shutdown_animation) {
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100705 boot_anim->Start();
706 surface_flinger->SetShutdownCritical();
707 boot_anim->SetShutdownCritical();
Tom Cherry911b9b12017-07-27 16:20:58 -0700708 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700709 }
Keun-young Park7830d592017-03-27 16:07:02 -0700710
Keun-young Park8d01f632017-03-13 11:54:47 -0700711 // optional shutdown step
712 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Keun-young Park30173872017-07-18 10:58:28 -0700713 if (shutdown_timeout > 0ms) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100714 StopServicesAndLogViolations(stop_first, shutdown_timeout / 2, true /* SIGTERM */);
Keun-young Park8d01f632017-03-13 11:54:47 -0700715 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100716 // Send SIGKILL to ones that didn't terminate cleanly.
717 StopServicesAndLogViolations(stop_first, 0ms, false /* SIGKILL */);
Luis Hector Chavez92c49bc2018-07-27 11:19:25 -0700718 SubcontextTerminate();
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100719 // Reap subcontext pids.
Tom Cherryeeee8312017-07-28 15:22:23 -0700720 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700721
Martijn Coenen860ba642020-05-28 16:42:10 +0200722 // 3. send volume abort_fuse and volume shutdown to vold
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100723 Service* vold_service = ServiceList::GetInstance().FindService("vold");
724 if (vold_service != nullptr && vold_service->IsRunning()) {
Martijn Coenen860ba642020-05-28 16:42:10 +0200725 // Manually abort FUSE connections, since the FUSE daemon is already dead
726 // at this point, and unmounting it might hang.
727 CallVdc("volume", "abort_fuse");
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000728 CallVdc("volume", "shutdown");
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100729 vold_service->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700730 } else {
731 LOG(INFO) << "vold not running, skipping vold shutdown";
732 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700733 // logcat stopped here
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000734 StopServices(kDebuggingServices, 0ms, false /* SIGKILL */);
Keun-young Park8d01f632017-03-13 11:54:47 -0700735 // 4. sync, try umount, and optionally run fsck for user shutdown
Tom Cherry1f9d5402018-03-15 10:22:40 -0700736 {
737 Timer sync_timer;
738 LOG(INFO) << "sync() before umount...";
739 sync();
740 LOG(INFO) << "sync() before umount took" << sync_timer;
741 }
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800742 // 5. drop caches and disable zram backing device, if exist
743 KillZramBackingDevice();
744
Nikita Ioffe91a98482020-06-10 00:53:59 +0100745 LOG(INFO) << "Ready to unmount apexes. So far shutdown sequence took " << t;
746 // 6. unmount active apexes, otherwise they might prevent clean unmount of /data.
747 if (auto ret = UnmountAllApexes(); !ret.ok()) {
748 LOG(ERROR) << ret.error();
749 }
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100750 UmountStat stat =
751 TryUmountAndFsck(cmd, run_fsck, shutdown_timeout - t.duration(), &reboot_semaphore);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700752 // Follow what linux shutdown is doing: one more sync with little bit delay
Tom Cherry1f9d5402018-03-15 10:22:40 -0700753 {
754 Timer sync_timer;
755 LOG(INFO) << "sync() after umount...";
756 sync();
757 LOG(INFO) << "sync() after umount took" << sync_timer;
758 }
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700759 if (!is_thermal_shutdown) std::this_thread::sleep_for(100ms);
Keun-young Park8d01f632017-03-13 11:54:47 -0700760 LogShutdownTime(stat, &t);
josephjangaaddf282019-04-16 18:46:24 +0800761
762 // Send signal to terminate reboot monitor thread.
763 reboot_monitor_run = false;
764 sem_post(&reboot_semaphore);
765
Keun-young Park8d01f632017-03-13 11:54:47 -0700766 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
Jaegeuk Kim3e595d52022-04-15 12:31:46 -0700767 if (IsDataMounted("f2fs")) {
768 uint32_t flag = F2FS_GOING_DOWN_FULLSYNC;
769 unique_fd fd(TEMP_FAILURE_RETRY(open("/data", O_RDONLY)));
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800770 int ret = ioctl(fd.get(), F2FS_IOC_SHUTDOWN, &flag);
Jaegeuk Kim3e595d52022-04-15 12:31:46 -0700771 if (ret) {
772 PLOG(ERROR) << "Shutdown /data: ";
773 } else {
774 LOG(INFO) << "Shutdown /data";
775 }
776 }
Sayanna Chandula5754b5a2022-10-04 15:06:05 -0700777 RebootSystem(cmd, reboot_target, reason);
Keun-young Park8d01f632017-03-13 11:54:47 -0700778 abort();
779}
Tom Cherry98ad32a2017-04-17 16:34:20 -0700780
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100781static void EnterShutdown() {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100782 LOG(INFO) << "Entering shutdown mode";
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100783 shutting_down = true;
784 // Skip wait for prop if it is in progress
785 ResetWaitForProp();
786 // Clear EXEC flag if there is one pending
787 for (const auto& s : ServiceList::GetInstance()) {
788 s->UnSetExec();
789 }
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100790}
791
792static void LeaveShutdown() {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100793 LOG(INFO) << "Leaving shutdown mode";
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100794 shutting_down = false;
Tom Cherry802864c2020-03-12 14:29:25 -0700795 StartSendingMessages();
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100796}
797
Nikita Ioffe7b41a152020-03-25 00:06:51 +0000798static std::chrono::milliseconds GetMillisProperty(const std::string& name,
799 std::chrono::milliseconds default_value) {
800 auto value = GetUintProperty(name, static_cast<uint64_t>(default_value.count()));
801 return std::chrono::milliseconds(std::move(value));
802}
803
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100804static Result<void> DoUserspaceReboot() {
805 LOG(INFO) << "Userspace reboot initiated";
Nikita Ioffe39d45532020-04-30 22:37:15 +0100806 // An ugly way to pass a more precise reason on why fallback to hard reboot was triggered.
807 std::string sub_reason = "";
808 auto guard = android::base::make_scope_guard([&sub_reason] {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100809 // Leave shutdown so that we can handle a full reboot.
810 LeaveShutdown();
Nikita Ioffe39d45532020-04-30 22:37:15 +0100811 trigger_shutdown("reboot,userspace_failed,shutdown_aborted," + sub_reason);
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100812 });
Nikita Ioffec0df1872019-11-13 21:47:06 +0000813 // Triggering userspace-reboot-requested will result in a bunch of setprop
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100814 // actions. We should make sure, that all of them are propagated before
Nikita Ioffe764c1ac2020-01-27 17:14:46 +0000815 // proceeding with userspace reboot. Synchronously setting sys.init.userspace_reboot.in_progress
816 // property is not perfect, but it should do the trick.
Nikita Ioffe23dbd6d2019-11-14 01:21:24 +0000817 if (!android::sysprop::InitProperties::userspace_reboot_in_progress(true)) {
Nikita Ioffe39d45532020-04-30 22:37:15 +0100818 sub_reason = "setprop";
Nikita Ioffe23dbd6d2019-11-14 01:21:24 +0000819 return Error() << "Failed to set sys.init.userspace_reboot.in_progress property";
Nikita Ioffec0df1872019-11-13 21:47:06 +0000820 }
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100821 EnterShutdown();
Nikita Ioffe764c1ac2020-01-27 17:14:46 +0000822 if (!SetProperty("sys.powerctl", "")) {
Nikita Ioffe39d45532020-04-30 22:37:15 +0100823 sub_reason = "resetprop";
Nikita Ioffe764c1ac2020-01-27 17:14:46 +0000824 return Error() << "Failed to reset sys.powerctl property";
825 }
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000826 std::set<std::string> stop_first;
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100827 // Remember the services that were enabled. We will need to manually enable them again otherwise
828 // triggers like class_start won't restart them.
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000829 std::set<std::string> were_enabled;
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100830 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
831 if (s->is_post_data() && !kDebuggingServices.count(s->name())) {
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000832 stop_first.insert(s->name());
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100833 }
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000834 // TODO(ioffe): we should also filter out temporary services here.
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100835 if (s->is_post_data() && s->IsEnabled()) {
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000836 were_enabled.insert(s->name());
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100837 }
838 }
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000839 {
840 Timer sync_timer;
841 LOG(INFO) << "sync() before terminating services...";
842 sync();
843 LOG(INFO) << "sync() took " << sync_timer;
844 }
Nikita Ioffe7b41a152020-03-25 00:06:51 +0000845 auto sigterm_timeout = GetMillisProperty("init.userspace_reboot.sigterm.timeoutmillis", 5s);
846 auto sigkill_timeout = GetMillisProperty("init.userspace_reboot.sigkill.timeoutmillis", 10s);
Nikita Ioffea3be9962020-04-16 21:37:03 +0100847 LOG(INFO) << "Timeout to terminate services: " << sigterm_timeout.count() << "ms "
Nikita Ioffe7b41a152020-03-25 00:06:51 +0000848 << "Timeout to kill services: " << sigkill_timeout.count() << "ms";
Gavin Corkery8c922562020-05-11 14:10:09 +0100849 std::string services_file_name = "/metadata/userspacereboot/services.txt";
850 const int flags = O_RDWR | O_CREAT | O_SYNC | O_APPEND | O_CLOEXEC;
Nikita Ioffe7b41a152020-03-25 00:06:51 +0000851 StopServicesAndLogViolations(stop_first, sigterm_timeout, true /* SIGTERM */);
852 if (int r = StopServicesAndLogViolations(stop_first, sigkill_timeout, false /* SIGKILL */);
853 r > 0) {
Gavin Corkery8c922562020-05-11 14:10:09 +0100854 auto fd = unique_fd(TEMP_FAILURE_RETRY(open(services_file_name.c_str(), flags, 0666)));
855 android::base::WriteStringToFd("Post-data services still running: \n", fd);
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000856 for (const auto& s : ServiceList::GetInstance()) {
857 if (s->IsRunning() && stop_first.count(s->name())) {
Gavin Corkery8c922562020-05-11 14:10:09 +0100858 android::base::WriteStringToFd(s->name() + "\n", fd);
859 }
860 }
Nikita Ioffe39d45532020-04-30 22:37:15 +0100861 sub_reason = "sigkill";
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100862 return Error() << r << " post-data services are still running";
863 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900864 if (auto result = KillZramBackingDevice(); !result.ok()) {
Nikita Ioffe39d45532020-04-30 22:37:15 +0100865 sub_reason = "zram";
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000866 return result;
867 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900868 if (auto result = CallVdc("volume", "reset"); !result.ok()) {
Nikita Ioffe39d45532020-04-30 22:37:15 +0100869 sub_reason = "vold_reset";
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000870 return result;
871 }
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000872 const auto& debugging_services = GetPostDataDebuggingServices();
873 if (int r = StopServicesAndLogViolations(debugging_services, sigkill_timeout,
874 false /* SIGKILL */);
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100875 r > 0) {
Gavin Corkery8c922562020-05-11 14:10:09 +0100876 auto fd = unique_fd(TEMP_FAILURE_RETRY(open(services_file_name.c_str(), flags, 0666)));
877 android::base::WriteStringToFd("Debugging services still running: \n", fd);
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000878 for (const auto& s : ServiceList::GetInstance()) {
879 if (s->IsRunning() && debugging_services.count(s->name())) {
Gavin Corkery8c922562020-05-11 14:10:09 +0100880 android::base::WriteStringToFd(s->name() + "\n", fd);
881 }
882 }
Nikita Ioffe39d45532020-04-30 22:37:15 +0100883 sub_reason = "sigkill_debug";
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100884 return Error() << r << " debugging services are still running";
885 }
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000886 {
887 Timer sync_timer;
888 LOG(INFO) << "sync() after stopping services...";
889 sync();
890 LOG(INFO) << "sync() took " << sync_timer;
891 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900892 if (auto result = UnmountAllApexes(); !result.ok()) {
Nikita Ioffe39d45532020-04-30 22:37:15 +0100893 sub_reason = "apex";
Nikita Ioffeab91ee92019-11-06 21:40:31 +0000894 return result;
895 }
Bernie Innocenti062ef532020-02-07 23:20:54 +0900896 if (!SwitchToMountNamespaceIfNeeded(NS_BOOTSTRAP).ok()) {
Nikita Ioffe39d45532020-04-30 22:37:15 +0100897 sub_reason = "ns_switch";
Nikita Ioffeab91ee92019-11-06 21:40:31 +0000898 return Error() << "Failed to switch to bootstrap namespace";
899 }
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900900 ActionManager::GetInstance().RemoveActionIf([](const auto& action) -> bool {
901 if (action->IsFromApex()) {
902 std::string trigger_name = action->BuildTriggersString();
903 LOG(INFO) << "Removing action (" << trigger_name << ") from (" << action->filename()
904 << ":" << action->line() << ")";
905 return true;
906 }
907 return false;
908 });
909 // Remove services that were defined in an APEX
Nikita Ioffe091c4d12019-12-05 12:35:19 +0000910 ServiceList::GetInstance().RemoveServiceIf([](const std::unique_ptr<Service>& s) -> bool {
911 if (s->is_from_apex()) {
912 LOG(INFO) << "Removing service '" << s->name() << "' because it's defined in an APEX";
913 return true;
914 }
915 return false;
916 });
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100917 // Re-enable services
Nikita Ioffe7ba50302020-11-27 18:57:44 +0000918 for (const auto& s : ServiceList::GetInstance()) {
919 if (were_enabled.count(s->name())) {
920 LOG(INFO) << "Re-enabling service '" << s->name() << "'";
921 s->Enable();
922 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100923 }
Nikita Ioffe3ad29202020-02-27 20:46:27 +0000924 ServiceList::GetInstance().ResetState();
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100925 LeaveShutdown();
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100926 ActionManager::GetInstance().QueueEventTrigger("userspace-reboot-resume");
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100927 guard.Disable(); // Go on with userspace reboot.
928 return {};
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100929}
930
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000931static void UserspaceRebootWatchdogThread() {
Nikita Ioffed0553542020-04-11 01:55:24 +0100932 auto started_timeout = GetMillisProperty("init.userspace_reboot.started.timeoutmillis", 10s);
933 if (!WaitForProperty("sys.init.userspace_reboot.in_progress", "1", started_timeout)) {
934 LOG(ERROR) << "Userspace reboot didn't start in " << started_timeout.count()
935 << "ms. Switching to full reboot";
936 // Init might be wedged, don't try to write reboot reason into a persistent property and do
937 // a dirty reboot.
938 PersistRebootReason("userspace_failed,watchdog_triggered,failed_to_start", false);
939 RebootSystem(ANDROID_RB_RESTART2, "userspace_failed,watchdog_triggered,failed_to_start");
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000940 }
941 LOG(INFO) << "Starting userspace reboot watchdog";
Nikita Ioffed0553542020-04-11 01:55:24 +0100942 auto watchdog_timeout = GetMillisProperty("init.userspace_reboot.watchdog.timeoutmillis", 5min);
943 LOG(INFO) << "UserspaceRebootWatchdog timeout: " << watchdog_timeout.count() << "ms";
944 if (!WaitForProperty("sys.boot_completed", "1", watchdog_timeout)) {
945 LOG(ERROR) << "Failed to boot in " << watchdog_timeout.count()
946 << "ms. Switching to full reboot";
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000947 // In this case device is in a boot loop. Only way to recover is to do dirty reboot.
Nikita Ioffed485bbb2020-02-26 15:18:56 +0000948 // Since init might be wedged, don't try to write reboot reason into a persistent property.
Nikita Ioffed0553542020-04-11 01:55:24 +0100949 PersistRebootReason("userspace_failed,watchdog_triggered,failed_to_boot", false);
950 RebootSystem(ANDROID_RB_RESTART2, "userspace_failed,watchdog_triggered,failed_to_boot");
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000951 }
952 LOG(INFO) << "Device booted, stopping userspace reboot watchdog";
953}
954
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100955static void HandleUserspaceReboot() {
Nikita Ioffe018ddd72019-12-20 16:34:48 +0000956 if (!android::sysprop::InitProperties::is_userspace_reboot_supported().value_or(false)) {
Nikita Ioffe9f473c02019-12-18 13:31:42 +0000957 LOG(ERROR) << "Attempted a userspace reboot on a device that doesn't support it";
958 return;
959 }
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000960 // Spinnig up a separate thread will fail the setns call later in the boot sequence.
961 // Fork a new process to monitor userspace reboot while we are investigating a better solution.
962 pid_t pid = fork();
963 if (pid < 0) {
964 PLOG(ERROR) << "Failed to fork process for userspace reboot watchdog. Switching to full "
965 << "reboot";
Nikita Ioffe4a787d92020-01-15 23:23:13 +0000966 trigger_shutdown("reboot,userspace_failed,watchdog_fork");
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000967 return;
968 }
969 if (pid == 0) {
970 // Child
971 UserspaceRebootWatchdogThread();
972 _exit(EXIT_SUCCESS);
973 }
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100974 LOG(INFO) << "Clearing queue and starting userspace-reboot-requested trigger";
975 auto& am = ActionManager::GetInstance();
976 am.ClearQueue();
977 am.QueueEventTrigger("userspace-reboot-requested");
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100978 auto handler = [](const BuiltinArguments&) { return DoUserspaceReboot(); };
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100979 am.QueueBuiltinAction(handler, "userspace-reboot");
980}
981
Sam Protsenko2c7c3c72019-12-26 21:55:08 +0200982/**
983 * Check if "command" field is set in bootloader message.
984 *
985 * If "command" field is broken (contains non-printable characters prior to
986 * terminating zero), it will be zeroed.
987 *
988 * @param[in,out] boot Bootloader message (BCB) structure
989 * @return true if "command" field is already set, and false if it's empty
990 */
991static bool CommandIsPresent(bootloader_message* boot) {
992 if (boot->command[0] == '\0')
993 return false;
994
995 for (size_t i = 0; i < arraysize(boot->command); ++i) {
996 if (boot->command[i] == '\0')
997 return true;
998 if (!isprint(boot->command[i]))
999 break;
1000 }
1001
1002 memset(boot->command, 0, sizeof(boot->command));
1003 return false;
1004}
1005
Nikita Ioffeba6968e2019-10-07 16:26:33 +01001006void HandlePowerctlMessage(const std::string& command) {
Tom Cherry98ad32a2017-04-17 16:34:20 -07001007 unsigned int cmd = 0;
Mark Salyzyn62909822017-10-09 09:27:16 -07001008 std::vector<std::string> cmd_params = Split(command, ",");
Tom Cherry98ad32a2017-04-17 16:34:20 -07001009 std::string reboot_target = "";
1010 bool run_fsck = false;
1011 bool command_invalid = false;
Nikita Ioffeba6968e2019-10-07 16:26:33 +01001012 bool userspace_reboot = false;
Tom Cherry98ad32a2017-04-17 16:34:20 -07001013
Mark Salyzynd7931f12019-07-10 10:33:09 -07001014 if (cmd_params[0] == "shutdown") {
Tom Cherry98ad32a2017-04-17 16:34:20 -07001015 cmd = ANDROID_RB_POWEROFF;
Mark Salyzynd7931f12019-07-10 10:33:09 -07001016 if (cmd_params.size() >= 2) {
Mark Salyzyn73e6b492017-08-14 15:56:53 -07001017 if (cmd_params[1] == "userrequested") {
1018 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
1019 // Run fsck once the file system is remounted in read-only mode.
1020 run_fsck = true;
1021 } else if (cmd_params[1] == "thermal") {
Mark Salyzynbfd05b62017-09-26 11:10:12 -07001022 // Turn off sources of heat immediately.
1023 TurnOffBacklight();
Mark Salyzyn73e6b492017-08-14 15:56:53 -07001024 // run_fsck is false to avoid delay
1025 cmd = ANDROID_RB_THERMOFF;
1026 }
Tom Cherry98ad32a2017-04-17 16:34:20 -07001027 }
1028 } else if (cmd_params[0] == "reboot") {
1029 cmd = ANDROID_RB_RESTART2;
1030 if (cmd_params.size() >= 2) {
1031 reboot_target = cmd_params[1];
Nikita Ioffeba6968e2019-10-07 16:26:33 +01001032 if (reboot_target == "userspace") {
1033 LOG(INFO) << "Userspace reboot requested";
1034 userspace_reboot = true;
1035 }
Hridya Valsaraju54258262018-09-19 21:14:18 -07001036 // adb reboot fastboot should boot into bootloader for devices not
1037 // supporting logical partitions.
1038 if (reboot_target == "fastboot" &&
Yifan Hong0e0f8182018-11-16 12:49:06 -08001039 !android::base::GetBoolProperty("ro.boot.dynamic_partitions", false)) {
Hridya Valsaraju54258262018-09-19 21:14:18 -07001040 reboot_target = "bootloader";
1041 }
Tom Cherry98ad32a2017-04-17 16:34:20 -07001042 // When rebooting to the bootloader notify the bootloader writing
1043 // also the BCB.
1044 if (reboot_target == "bootloader") {
1045 std::string err;
1046 if (!write_reboot_bootloader(&err)) {
1047 LOG(ERROR) << "reboot-bootloader: Error writing "
1048 "bootloader_message: "
1049 << err;
1050 }
Tianjie Xu5e98b632019-07-18 12:48:28 -07001051 } else if (reboot_target == "recovery") {
1052 bootloader_message boot = {};
1053 if (std::string err; !read_bootloader_message(&boot, &err)) {
1054 LOG(ERROR) << "Failed to read bootloader message: " << err;
1055 }
1056 // Update the boot command field if it's empty, and preserve
1057 // the other arguments in the bootloader message.
Sam Protsenko2c7c3c72019-12-26 21:55:08 +02001058 if (!CommandIsPresent(&boot)) {
Tianjie Xu5e98b632019-07-18 12:48:28 -07001059 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
1060 if (std::string err; !write_bootloader_message(boot, &err)) {
1061 LOG(ERROR) << "Failed to set bootloader message: " << err;
Nikita Ioffeba6968e2019-10-07 16:26:33 +01001062 return;
Tianjie Xu5e98b632019-07-18 12:48:28 -07001063 }
1064 }
Chenfu.Liaod672e472021-06-29 15:41:22 +08001065 } else if (reboot_target == "quiescent") {
1066 bootloader_message boot = {};
1067 if (std::string err; !read_bootloader_message(&boot, &err)) {
1068 LOG(ERROR) << "Failed to read bootloader message: " << err;
1069 }
1070 // Update the boot command field if it's empty, and preserve
1071 // the other arguments in the bootloader message.
1072 if (!CommandIsPresent(&boot)) {
1073 strlcpy(boot.command, "boot-quiescent", sizeof(boot.command));
1074 if (std::string err; !write_bootloader_message(boot, &err)) {
1075 LOG(ERROR) << "Failed to set bootloader message: " << err;
1076 return;
1077 }
1078 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -07001079 } else if (reboot_target == "sideload" || reboot_target == "sideload-auto-reboot" ||
1080 reboot_target == "fastboot") {
1081 std::string arg = reboot_target == "sideload-auto-reboot" ? "sideload_auto_reboot"
1082 : reboot_target;
1083 const std::vector<std::string> options = {
1084 "--" + arg,
1085 };
1086 std::string err;
1087 if (!write_bootloader_message(options, &err)) {
1088 LOG(ERROR) << "Failed to set bootloader message: " << err;
Nikita Ioffeba6968e2019-10-07 16:26:33 +01001089 return;
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -07001090 }
1091 reboot_target = "recovery";
Tom Cherry98ad32a2017-04-17 16:34:20 -07001092 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -07001093
Mark Salyzynd7931f12019-07-10 10:33:09 -07001094 // If there are additional parameter, pass them along
1095 for (size_t i = 2; (cmd_params.size() > i) && cmd_params[i].size(); ++i) {
1096 reboot_target += "," + cmd_params[i];
Tom Cherry98ad32a2017-04-17 16:34:20 -07001097 }
1098 }
Tom Cherry98ad32a2017-04-17 16:34:20 -07001099 } else {
1100 command_invalid = true;
1101 }
1102 if (command_invalid) {
1103 LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
Nikita Ioffeba6968e2019-10-07 16:26:33 +01001104 return;
1105 }
1106
Tom Cherry802864c2020-03-12 14:29:25 -07001107 // We do not want to process any messages (queue'ing triggers, shutdown messages, control
1108 // messages, etc) from properties during reboot.
1109 StopSendingMessages();
1110
Nikita Ioffeba6968e2019-10-07 16:26:33 +01001111 if (userspace_reboot) {
1112 HandleUserspaceReboot();
1113 return;
Tom Cherry98ad32a2017-04-17 16:34:20 -07001114 }
1115
Wei Wangeeab4912017-06-27 22:08:45 -07001116 LOG(INFO) << "Clear action queue and start shutdown trigger";
1117 ActionManager::GetInstance().ClearQueue();
1118 // Queue shutdown trigger first
1119 ActionManager::GetInstance().QueueEventTrigger("shutdown");
1120 // Queue built-in shutdown_done
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001121 auto shutdown_handler = [cmd, command, reboot_target, run_fsck](const BuiltinArguments&) {
Wei Wangeeab4912017-06-27 22:08:45 -07001122 DoReboot(cmd, command, reboot_target, run_fsck);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001123 return Result<void>{};
Wei Wangeeab4912017-06-27 22:08:45 -07001124 };
1125 ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
1126
Nikita Ioffeba6968e2019-10-07 16:26:33 +01001127 EnterShutdown();
1128}
Wei Wangeeab4912017-06-27 22:08:45 -07001129
Nikita Ioffeba6968e2019-10-07 16:26:33 +01001130bool IsShuttingDown() {
1131 return shutting_down;
Tom Cherry98ad32a2017-04-17 16:34:20 -07001132}
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001133
1134} // namespace init
1135} // namespace android