blob: 2f916632579ca28bef077e07ad7798882b9af6c6 [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>
Keun-young Park2ba5c812017-03-29 12:54:40 -070021#include <linux/fs.h>
Jaegeuk Kim2aedc822018-11-20 13:27:06 -080022#include <linux/loop.h>
josephjangaaddf282019-04-16 18:46:24 +080023#include <mntent.h>
24#include <semaphore.h>
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010025#include <stdlib.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070026#include <sys/cdefs.h>
Keun-young Park2ba5c812017-03-29 12:54:40 -070027#include <sys/ioctl.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070028#include <sys/mount.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070029#include <sys/stat.h>
josephjangaaddf282019-04-16 18:46:24 +080030#include <sys/swap.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070031#include <sys/syscall.h>
32#include <sys/types.h>
33#include <sys/wait.h>
34
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010035#include <chrono>
Keun-young Park8d01f632017-03-13 11:54:47 -070036#include <memory>
Keun-young Park7830d592017-03-27 16:07:02 -070037#include <set>
Keun-young Park8d01f632017-03-13 11:54:47 -070038#include <thread>
39#include <vector>
40
Nikita Ioffe23dbd6d2019-11-14 01:21:24 +000041#include <InitProperties.sysprop.h>
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>
53#include <logwrap/logwrap.h>
Todd Poynorfc827be2017-04-13 15:17:24 -070054#include <private/android_filesystem_config.h>
Tom Cherry0c8d6d22017-08-10 12:22:44 -070055#include <selinux/selinux.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070056
Nikita Ioffeba6968e2019-10-07 16:26:33 +010057#include "action.h"
Tom Cherry7fd3bc22018-02-13 15:36:14 -080058#include "action_manager.h"
Nikita Ioffeba6968e2019-10-07 16:26:33 +010059#include "builtin_arguments.h"
Wei Wangeeab4912017-06-27 22:08:45 -070060#include "init.h"
Nikita Ioffeab91ee92019-11-06 21:40:31 +000061#include "mount_namespace.h"
Tom Cherry802864c2020-03-12 14:29:25 -070062#include "property_service.h"
Tom Cherry44aceed2018-08-03 13:36:18 -070063#include "reboot_utils.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070064#include "service.h"
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070065#include "service_list.h"
Luis Hector Chavez9f97f472017-09-06 13:43:57 -070066#include "sigchld_handler.h"
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010067#include "util.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070068
josephjangaaddf282019-04-16 18:46:24 +080069#define PROC_SYSRQ "/proc/sysrq-trigger"
70
Tom Cherry2436e6b2019-09-19 11:16:19 -070071using namespace std::literals;
72
Nikita Ioffec0df1872019-11-13 21:47:06 +000073using android::base::boot_clock;
Tom Cherry4f4cacc2019-01-08 10:39:00 -080074using android::base::GetBoolProperty;
Nikita Ioffe7b41a152020-03-25 00:06:51 +000075using android::base::GetUintProperty;
Nikita Ioffec0df1872019-11-13 21:47:06 +000076using android::base::SetProperty;
Mark Salyzyn62909822017-10-09 09:27:16 -070077using android::base::Split;
Tom Cherryede0d532017-07-06 14:20:11 -070078using android::base::Timer;
Jaegeuk Kim2aedc822018-11-20 13:27:06 -080079using android::base::unique_fd;
Nikita Ioffec0df1872019-11-13 21:47:06 +000080using android::base::WaitForProperty;
josephjangaaddf282019-04-16 18:46:24 +080081using android::base::WriteStringToFile;
Keun-young Park8d01f632017-03-13 11:54:47 -070082
Tom Cherry81f5d3e2017-06-22 12:53:17 -070083namespace android {
84namespace init {
85
Nikita Ioffeba6968e2019-10-07 16:26:33 +010086static bool shutting_down = false;
87
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010088static const std::set<std::string> kDebuggingServices{"tombstoned", "logd", "adbd", "console"};
89
Tom Cherry832f9f12020-03-10 11:47:24 -070090static std::vector<Service*> GetDebuggingServices(bool only_post_data) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010091 std::vector<Service*> ret;
92 ret.reserve(kDebuggingServices.size());
93 for (const auto& s : ServiceList::GetInstance()) {
94 if (kDebuggingServices.count(s->name()) && (!only_post_data || s->is_post_data())) {
95 ret.push_back(s.get());
96 }
97 }
98 return ret;
99}
100
Nikita Ioffed485bbb2020-02-26 15:18:56 +0000101static void PersistRebootReason(const char* reason, bool write_to_property) {
102 if (write_to_property) {
103 SetProperty(LAST_REBOOT_REASON_PROPERTY, reason);
104 }
Tom Cherry10615eb2020-03-31 16:31:37 -0700105 auto fd = unique_fd(TEMP_FAILURE_RETRY(open(
106 LAST_REBOOT_REASON_FILE, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY, 0666)));
107 if (!fd.ok()) {
108 PLOG(ERROR) << "Could not open '" << LAST_REBOOT_REASON_FILE
109 << "' to persist reboot reason";
110 return;
111 }
112 WriteStringToFd(reason, fd);
113 fsync(fd.get());
Nikita Ioffed0bc0b62020-02-19 16:21:11 +0000114}
115
Keun-young Park8d01f632017-03-13 11:54:47 -0700116// represents umount status during reboot / shutdown.
117enum UmountStat {
118 /* umount succeeded. */
119 UMOUNT_STAT_SUCCESS = 0,
120 /* umount was not run. */
121 UMOUNT_STAT_SKIPPED = 1,
122 /* umount failed with timeout. */
123 UMOUNT_STAT_TIMEOUT = 2,
124 /* could not run due to error */
125 UMOUNT_STAT_ERROR = 3,
126 /* not used by init but reserved for other part to use this to represent the
127 the state where umount status before reboot is not found / available. */
128 UMOUNT_STAT_NOT_AVAILABLE = 4,
129};
130
131// Utility for struct mntent
132class MountEntry {
133 public:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700134 explicit MountEntry(const mntent& entry)
Keun-young Park8d01f632017-03-13 11:54:47 -0700135 : mnt_fsname_(entry.mnt_fsname),
136 mnt_dir_(entry.mnt_dir),
137 mnt_type_(entry.mnt_type),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700138 mnt_opts_(entry.mnt_opts) {}
Keun-young Park8d01f632017-03-13 11:54:47 -0700139
Jaegeuk Kim0f04f722017-09-25 10:55:39 -0700140 bool Umount(bool force) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800141 LOG(INFO) << "Unmounting " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Jaegeuk Kim0f04f722017-09-25 10:55:39 -0700142 int r = umount2(mnt_dir_.c_str(), force ? MNT_FORCE : 0);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700143 if (r == 0) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800144 LOG(INFO) << "Umounted " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700145 return true;
146 } else {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800147 PLOG(WARNING) << "Cannot umount " << mnt_fsname_ << ":" << mnt_dir_ << " opts "
Keun-young Park2ba5c812017-03-29 12:54:40 -0700148 << mnt_opts_;
149 return false;
150 }
151 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700152
Keun-young Park2ba5c812017-03-29 12:54:40 -0700153 void DoFsck() {
154 int st;
155 if (IsF2Fs()) {
156 const char* f2fs_argv[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800157 "/system/bin/fsck.f2fs",
158 "-a",
159 mnt_fsname_.c_str(),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700160 };
Tom Cherry3a803eb2019-09-25 16:23:50 -0700161 logwrap_fork_execvp(arraysize(f2fs_argv), f2fs_argv, &st, false, LOG_KLOG, true,
162 nullptr);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700163 } else if (IsExt4()) {
164 const char* ext4_argv[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800165 "/system/bin/e2fsck",
166 "-y",
167 mnt_fsname_.c_str(),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700168 };
Tom Cherry3a803eb2019-09-25 16:23:50 -0700169 logwrap_fork_execvp(arraysize(ext4_argv), ext4_argv, &st, false, LOG_KLOG, true,
170 nullptr);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700171 }
172 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700173
174 static bool IsBlockDevice(const struct mntent& mntent) {
175 return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
176 }
177
178 static bool IsEmulatedDevice(const struct mntent& mntent) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700179 return android::base::StartsWith(mntent.mnt_fsname, "/data/");
Keun-young Park8d01f632017-03-13 11:54:47 -0700180 }
181
182 private:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700183 bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
184
185 bool IsExt4() const { return mnt_type_ == "ext4"; }
186
Keun-young Park8d01f632017-03-13 11:54:47 -0700187 std::string mnt_fsname_;
188 std::string mnt_dir_;
189 std::string mnt_type_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700190 std::string mnt_opts_;
Keun-young Park8d01f632017-03-13 11:54:47 -0700191};
192
193// Turn off backlight while we are performing power down cleanup activities.
Tom Cherry832f9f12020-03-10 11:47:24 -0700194static void TurnOffBacklight() {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800195 Service* service = ServiceList::GetInstance().FindService("blank_screen");
196 if (service == nullptr) {
197 LOG(WARNING) << "cannot find blank_screen in TurnOffBacklight";
Keun-young Park8d01f632017-03-13 11:54:47 -0700198 return;
199 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900200 if (auto result = service->Start(); !result.ok()) {
Tom Cherryd9872642018-10-11 10:38:05 -0700201 LOG(WARNING) << "Could not start blank_screen service: " << result.error();
202 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700203}
204
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000205static Result<void> CallVdc(const std::string& system, const std::string& cmd) {
206 const char* vdc_argv[] = {"/system/bin/vdc", system.c_str(), cmd.c_str()};
Keun-young Park8d01f632017-03-13 11:54:47 -0700207 int status;
Nikita Ioffe12a36072019-10-23 20:11:32 +0100208 if (logwrap_fork_execvp(arraysize(vdc_argv), vdc_argv, &status, false, LOG_KLOG, true,
209 nullptr) != 0) {
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000210 return ErrnoError() << "Failed to call '/system/bin/vdc " << system << " " << cmd << "'";
Nikita Ioffe12a36072019-10-23 20:11:32 +0100211 }
212 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
213 return {};
214 }
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000215 return Error() << "'/system/bin/vdc " << system << " " << cmd << "' failed : " << status;
Keun-young Park8d01f632017-03-13 11:54:47 -0700216}
217
218static void LogShutdownTime(UmountStat stat, Timer* t) {
Tom Cherryede0d532017-07-06 14:20:11 -0700219 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration().count()) << ":"
220 << stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700221}
222
Tom Cherry2436e6b2019-09-19 11:16:19 -0700223static bool IsDataMounted() {
224 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
225 if (fp == nullptr) {
226 PLOG(ERROR) << "Failed to open /proc/mounts";
227 return false;
228 }
229 mntent* mentry;
230 while ((mentry = getmntent(fp.get())) != nullptr) {
231 if (mentry->mnt_dir == "/data"s) {
232 return true;
233 }
234 }
235 return false;
236}
237
238// Find all read+write block devices and emulated devices in /proc/mounts and add them to
239// the correpsponding list.
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100240static bool FindPartitionsToUmount(std::vector<MountEntry>* block_dev_partitions,
241 std::vector<MountEntry>* emulated_partitions, bool dump) {
Tom Cherryf274e782018-10-03 13:13:41 -0700242 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
Keun-young Park8d01f632017-03-13 11:54:47 -0700243 if (fp == nullptr) {
244 PLOG(ERROR) << "Failed to open /proc/mounts";
245 return false;
246 }
247 mntent* mentry;
248 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700249 if (dump) {
250 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
251 << mentry->mnt_opts << " type " << mentry->mnt_type;
252 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
Keun-young Park6e12b382017-07-17 12:20:33 -0700253 std::string mount_dir(mentry->mnt_dir);
254 // These are R/O partitions changed to R/W after adb remount.
255 // Do not umount them as shutdown critical services may rely on them.
Wei Wanga01c27e2017-07-25 10:52:08 -0700256 if (mount_dir != "/" && mount_dir != "/system" && mount_dir != "/vendor" &&
257 mount_dir != "/oem") {
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100258 block_dev_partitions->emplace(block_dev_partitions->begin(), *mentry);
Keun-young Park6e12b382017-07-17 12:20:33 -0700259 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700260 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100261 emulated_partitions->emplace(emulated_partitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700262 }
263 }
264 return true;
265}
266
Jonglin Lee28a2c922019-01-15 16:38:44 -0800267static void DumpUmountDebuggingInfo() {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700268 int status;
269 if (!security_getenforce()) {
270 LOG(INFO) << "Run lsof";
271 const char* lsof_argv[] = {"/system/bin/lsof"};
Tom Cherry3a803eb2019-09-25 16:23:50 -0700272 logwrap_fork_execvp(arraysize(lsof_argv), lsof_argv, &status, false, LOG_KLOG, true,
273 nullptr);
Keun-young Park8d01f632017-03-13 11:54:47 -0700274 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700275 FindPartitionsToUmount(nullptr, nullptr, true);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800276 // dump current CPU stack traces and uninterruptible tasks
josephjangaaddf282019-04-16 18:46:24 +0800277 WriteStringToFile("l", PROC_SYSRQ);
278 WriteStringToFile("w", PROC_SYSRQ);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700279}
280
Tom Cherryede0d532017-07-06 14:20:11 -0700281static UmountStat UmountPartitions(std::chrono::milliseconds timeout) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700282 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700283 /* data partition needs all pending writes to be completed and all emulated partitions
284 * umounted.If the current waiting is not good enough, give
285 * up and leave it to e2fsck after reboot to fix it.
286 */
287 while (true) {
288 std::vector<MountEntry> block_devices;
289 std::vector<MountEntry> emulated_devices;
290 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
291 return UMOUNT_STAT_ERROR;
292 }
293 if (block_devices.size() == 0) {
Wei Wang8c00e422017-08-16 14:01:46 -0700294 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700295 }
Wei Wang8c00e422017-08-16 14:01:46 -0700296 bool unmount_done = true;
297 if (emulated_devices.size() > 0) {
Wei Wang25dc30f2017-10-23 15:32:03 -0700298 for (auto& entry : emulated_devices) {
299 if (!entry.Umount(false)) unmount_done = false;
300 }
Wei Wang8c00e422017-08-16 14:01:46 -0700301 if (unmount_done) {
302 sync();
303 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700304 }
Wei Wang25dc30f2017-10-23 15:32:03 -0700305 for (auto& entry : block_devices) {
306 if (!entry.Umount(timeout == 0ms)) unmount_done = false;
307 }
Wei Wang8c00e422017-08-16 14:01:46 -0700308 if (unmount_done) {
309 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700310 }
Wei Wang8c00e422017-08-16 14:01:46 -0700311 if ((timeout < t.duration())) { // try umount at least once
312 return UMOUNT_STAT_TIMEOUT;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700313 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700314 std::this_thread::sleep_for(100ms);
315 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700316}
317
josephjangaaddf282019-04-16 18:46:24 +0800318static void KillAllProcesses() {
319 WriteStringToFile("i", PROC_SYSRQ);
320}
321
322// Create reboot/shutdwon monitor thread
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100323void RebootMonitorThread(unsigned int cmd, const std::string& reboot_target,
324 sem_t* reboot_semaphore, std::chrono::milliseconds shutdown_timeout,
325 bool* reboot_monitor_run) {
josephjangaaddf282019-04-16 18:46:24 +0800326 unsigned int remaining_shutdown_time = 0;
327
Tom Cherry10615eb2020-03-31 16:31:37 -0700328 // 300 seconds more than the timeout passed to the thread as there is a final Umount pass
josephjangaaddf282019-04-16 18:46:24 +0800329 // after the timeout is reached.
Tom Cherry10615eb2020-03-31 16:31:37 -0700330 constexpr unsigned int shutdown_watchdog_timeout_default = 300;
josephjangaaddf282019-04-16 18:46:24 +0800331 auto shutdown_watchdog_timeout = android::base::GetUintProperty(
332 "ro.build.shutdown.watchdog.timeout", shutdown_watchdog_timeout_default);
333 remaining_shutdown_time = shutdown_watchdog_timeout + shutdown_timeout.count() / 1000;
334
335 while (*reboot_monitor_run == true) {
336 if (TEMP_FAILURE_RETRY(sem_wait(reboot_semaphore)) == -1) {
337 LOG(ERROR) << "sem_wait failed and exit RebootMonitorThread()";
338 return;
339 }
340
341 timespec shutdown_timeout_timespec;
342 if (clock_gettime(CLOCK_MONOTONIC, &shutdown_timeout_timespec) == -1) {
343 LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
344 return;
345 }
346
347 // If there are some remaining shutdown time left from previous round, we use
348 // remaining time here.
349 shutdown_timeout_timespec.tv_sec += remaining_shutdown_time;
350
351 LOG(INFO) << "shutdown_timeout_timespec.tv_sec: " << shutdown_timeout_timespec.tv_sec;
352
353 int sem_return = 0;
354 while ((sem_return = sem_timedwait_monotonic_np(reboot_semaphore,
355 &shutdown_timeout_timespec)) == -1 &&
356 errno == EINTR) {
357 }
358
359 if (sem_return == -1) {
360 LOG(ERROR) << "Reboot thread timed out";
361
362 if (android::base::GetBoolProperty("ro.debuggable", false) == true) {
Tom Cherry2436e6b2019-09-19 11:16:19 -0700363 if (false) {
364 // SEPolicy will block debuggerd from running and this is intentional.
365 // But these lines are left to be enabled during debugging.
366 LOG(INFO) << "Try to dump init process call trace:";
367 const char* vdc_argv[] = {"/system/bin/debuggerd", "-b", "1"};
368 int status;
Tom Cherry3a803eb2019-09-25 16:23:50 -0700369 logwrap_fork_execvp(arraysize(vdc_argv), vdc_argv, &status, false, LOG_KLOG,
370 true, nullptr);
Tom Cherry2436e6b2019-09-19 11:16:19 -0700371 }
josephjangaaddf282019-04-16 18:46:24 +0800372 LOG(INFO) << "Show stack for all active CPU:";
373 WriteStringToFile("l", PROC_SYSRQ);
374
375 LOG(INFO) << "Show tasks that are in disk sleep(uninterruptable sleep), which are "
376 "like "
377 "blocked in mutex or hardware register access:";
378 WriteStringToFile("w", PROC_SYSRQ);
379 }
380
381 // In shutdown case,notify kernel to sync and umount fs to read-only before shutdown.
382 if (cmd == ANDROID_RB_POWEROFF || cmd == ANDROID_RB_THERMOFF) {
383 WriteStringToFile("s", PROC_SYSRQ);
384
385 WriteStringToFile("u", PROC_SYSRQ);
386
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100387 RebootSystem(cmd, reboot_target);
josephjangaaddf282019-04-16 18:46:24 +0800388 }
389
390 LOG(ERROR) << "Trigger crash at last!";
391 WriteStringToFile("c", PROC_SYSRQ);
392 } else {
393 timespec current_time_timespec;
394
395 if (clock_gettime(CLOCK_MONOTONIC, &current_time_timespec) == -1) {
396 LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
397 return;
398 }
399
400 remaining_shutdown_time =
401 shutdown_timeout_timespec.tv_sec - current_time_timespec.tv_sec;
402
403 LOG(INFO) << "remaining_shutdown_time: " << remaining_shutdown_time;
404 }
405 }
406}
Keun-young Park3ee0df92017-03-27 11:21:09 -0700407
Keun-young Park8d01f632017-03-13 11:54:47 -0700408/* Try umounting all emulated file systems R/W block device cfile systems.
409 * This will just try umount and give it up if it fails.
410 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
411 * and necessary check can be done at the next reboot.
412 * For safer shutdown, caller needs to make sure that
413 * all processes / emulated partition for the target fs are all cleaned-up.
414 *
415 * return true when umount was successful. false when timed out.
416 */
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100417static UmountStat TryUmountAndFsck(unsigned int cmd, bool run_fsck,
josephjangaaddf282019-04-16 18:46:24 +0800418 std::chrono::milliseconds timeout, sem_t* reboot_semaphore) {
Keun-young Park3ee0df92017-03-27 11:21:09 -0700419 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700420 std::vector<MountEntry> block_devices;
421 std::vector<MountEntry> emulated_devices;
Keun-young Park8d01f632017-03-13 11:54:47 -0700422
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100423 if (run_fsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700424 return UMOUNT_STAT_ERROR;
425 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700426
Tom Cherryede0d532017-07-06 14:20:11 -0700427 UmountStat stat = UmountPartitions(timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700428 if (stat != UMOUNT_STAT_SUCCESS) {
429 LOG(INFO) << "umount timeout, last resort, kill all and try";
Jonglin Lee28a2c922019-01-15 16:38:44 -0800430 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park3ee0df92017-03-27 11:21:09 -0700431 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700432 // 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 -0700433 UmountStat st = UmountPartitions(0ms);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800434 if ((st != UMOUNT_STAT_SUCCESS) && DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park8d01f632017-03-13 11:54:47 -0700435 }
436
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100437 if (stat == UMOUNT_STAT_SUCCESS && run_fsck) {
josephjangaaddf282019-04-16 18:46:24 +0800438 LOG(INFO) << "Pause reboot monitor thread before fsck";
439 sem_post(reboot_semaphore);
440
Keun-young Park2ba5c812017-03-29 12:54:40 -0700441 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
442 // and should not affect reboot time.
443 for (auto& entry : block_devices) {
444 entry.DoFsck();
445 }
josephjangaaddf282019-04-16 18:46:24 +0800446
447 LOG(INFO) << "Resume reboot monitor thread after fsck";
448 sem_post(reboot_semaphore);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700449 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700450 return stat;
451}
452
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800453// zram is able to use backing device on top of a loopback device.
454// In order to unmount /data successfully, we have to kill the loopback device first
455#define ZRAM_DEVICE "/dev/block/zram0"
456#define ZRAM_RESET "/sys/block/zram0/reset"
457#define ZRAM_BACK_DEV "/sys/block/zram0/backing_dev"
Nikita Ioffe12a36072019-10-23 20:11:32 +0100458static Result<void> KillZramBackingDevice() {
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800459 std::string backing_dev;
Nikita Ioffe12a36072019-10-23 20:11:32 +0100460 if (!android::base::ReadFileToString(ZRAM_BACK_DEV, &backing_dev)) return {};
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800461
Nikita Ioffe12a36072019-10-23 20:11:32 +0100462 if (!android::base::StartsWith(backing_dev, "/dev/block/loop")) return {};
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800463
464 // cut the last "\n"
465 backing_dev.erase(backing_dev.length() - 1);
466
467 // shutdown zram handle
468 Timer swap_timer;
469 LOG(INFO) << "swapoff() start...";
470 if (swapoff(ZRAM_DEVICE) == -1) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100471 return ErrnoError() << "zram_backing_dev: swapoff (" << backing_dev << ")"
472 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800473 }
474 LOG(INFO) << "swapoff() took " << swap_timer;;
475
josephjangaaddf282019-04-16 18:46:24 +0800476 if (!WriteStringToFile("1", ZRAM_RESET)) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100477 return Error() << "zram_backing_dev: reset (" << backing_dev << ")"
478 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800479 }
480
481 // clear loopback device
482 unique_fd loop(TEMP_FAILURE_RETRY(open(backing_dev.c_str(), O_RDWR | O_CLOEXEC)));
483 if (loop.get() < 0) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100484 return ErrnoError() << "zram_backing_dev: open(" << backing_dev << ")"
485 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800486 }
487
488 if (ioctl(loop.get(), LOOP_CLR_FD, 0) < 0) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100489 return ErrnoError() << "zram_backing_dev: loop_clear (" << backing_dev << ")"
490 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800491 }
492 LOG(INFO) << "zram_backing_dev: `" << backing_dev << "` is cleared successfully.";
Nikita Ioffe12a36072019-10-23 20:11:32 +0100493 return {};
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800494}
495
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100496// Stops given services, waits for them to be stopped for |timeout| ms.
497// If terminate is true, then SIGTERM is sent to services, otherwise SIGKILL is sent.
498static void StopServices(const std::vector<Service*>& services, std::chrono::milliseconds timeout,
499 bool terminate) {
500 LOG(INFO) << "Stopping " << services.size() << " services by sending "
501 << (terminate ? "SIGTERM" : "SIGKILL");
502 std::vector<pid_t> pids;
503 pids.reserve(services.size());
504 for (const auto& s : services) {
505 if (s->pid() > 0) {
506 pids.push_back(s->pid());
507 }
508 if (terminate) {
509 s->Terminate();
510 } else {
511 s->Stop();
512 }
513 }
514 if (timeout > 0ms) {
515 WaitToBeReaped(pids, timeout);
516 } else {
517 // Even if we don't to wait for services to stop, we still optimistically reap zombies.
518 ReapAnyOutstandingChildren();
519 }
520}
521
522// Like StopServices, but also logs all the services that failed to stop after the provided timeout.
523// Returns number of violators.
524static int StopServicesAndLogViolations(const std::vector<Service*>& services,
525 std::chrono::milliseconds timeout, bool terminate) {
526 StopServices(services, timeout, terminate);
527 int still_running = 0;
528 for (const auto& s : services) {
529 if (s->IsRunning()) {
530 LOG(ERROR) << "[service-misbehaving] : service '" << s->name() << "' is still running "
531 << timeout.count() << "ms after receiving "
532 << (terminate ? "SIGTERM" : "SIGKILL");
533 still_running++;
534 }
535 }
536 return still_running;
537}
538
Tom Cherry44aceed2018-08-03 13:36:18 -0700539//* Reboot / shutdown the system.
540// cmd ANDROID_RB_* as defined in android_reboot.h
541// reason Reason string like "reboot", "shutdown,userrequested"
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100542// reboot_target Reboot target string like "bootloader". Otherwise, it should be an empty string.
543// run_fsck Whether to run fsck after umount is done.
Tom Cherry44aceed2018-08-03 13:36:18 -0700544//
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100545static void DoReboot(unsigned int cmd, const std::string& reason, const std::string& reboot_target,
546 bool run_fsck) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700547 Timer t;
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100548 LOG(INFO) << "Reboot start, reason: " << reason << ", reboot_target: " << reboot_target;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700549
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700550 bool is_thermal_shutdown = cmd == ANDROID_RB_THERMOFF;
551
552 auto shutdown_timeout = 0ms;
553 if (!SHUTDOWN_ZERO_TIMEOUT) {
Wei Wangb5de0882018-10-09 12:42:06 -0700554 constexpr unsigned int shutdown_timeout_default = 6;
555 constexpr unsigned int max_thermal_shutdown_timeout = 3;
556 auto shutdown_timeout_final = android::base::GetUintProperty("ro.build.shutdown_timeout",
557 shutdown_timeout_default);
558 if (is_thermal_shutdown && shutdown_timeout_final > max_thermal_shutdown_timeout) {
559 shutdown_timeout_final = max_thermal_shutdown_timeout;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700560 }
Wei Wangb5de0882018-10-09 12:42:06 -0700561 shutdown_timeout = std::chrono::seconds(shutdown_timeout_final);
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700562 }
563 LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " ms";
564
josephjangaaddf282019-04-16 18:46:24 +0800565 sem_t reboot_semaphore;
566 if (sem_init(&reboot_semaphore, false, 0) == -1) {
567 // These should never fail, but if they do, skip the graceful reboot and reboot immediately.
568 LOG(ERROR) << "sem_init() fail and RebootSystem() return!";
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100569 RebootSystem(cmd, reboot_target);
josephjangaaddf282019-04-16 18:46:24 +0800570 }
571
572 // Start a thread to monitor init shutdown process
573 LOG(INFO) << "Create reboot monitor thread.";
574 bool reboot_monitor_run = true;
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100575 std::thread reboot_monitor_thread(&RebootMonitorThread, cmd, reboot_target, &reboot_semaphore,
josephjangaaddf282019-04-16 18:46:24 +0800576 shutdown_timeout, &reboot_monitor_run);
577 reboot_monitor_thread.detach();
578
579 // Start reboot monitor thread
580 sem_post(&reboot_semaphore);
581
Tom Cherry10615eb2020-03-31 16:31:37 -0700582 // Ensure last reboot reason is reduced to canonical
583 // alias reported in bootloader or system boot reason.
584 size_t skip = 0;
585 std::vector<std::string> reasons = Split(reason, ",");
586 if (reasons.size() >= 2 && reasons[0] == "reboot" &&
587 (reasons[1] == "recovery" || reasons[1] == "bootloader" || reasons[1] == "cold" ||
588 reasons[1] == "hard" || reasons[1] == "warm")) {
589 skip = strlen("reboot,");
590 }
591 PersistRebootReason(reason.c_str() + skip, true);
592
593 // If /data isn't mounted then we can skip the extra reboot steps below, since we don't need to
594 // worry about unmounting it.
595 if (!IsDataMounted()) {
596 sync();
597 RebootSystem(cmd, reboot_target);
598 abort();
599 }
600
Keun-young Park7830d592017-03-27 16:07:02 -0700601 // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700602 const std::set<std::string> to_starts{"watchdogd"};
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100603 std::vector<Service*> stop_first;
604 stop_first.reserve(ServiceList::GetInstance().services().size());
Tom Cherry911b9b12017-07-27 16:20:58 -0700605 for (const auto& s : ServiceList::GetInstance()) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100606 if (kDebuggingServices.count(s->name())) {
607 // keep debugging tools until non critical ones are all gone.
Keun-young Park7830d592017-03-27 16:07:02 -0700608 s->SetShutdownCritical();
609 } else if (to_starts.count(s->name())) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900610 if (auto result = s->Start(); !result.ok()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700611 LOG(ERROR) << "Could not start shutdown 'to_start' service '" << s->name()
612 << "': " << result.error();
613 }
Keun-young Park7830d592017-03-27 16:07:02 -0700614 s->SetShutdownCritical();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700615 } else if (s->IsShutdownCritical()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700616 // Start shutdown critical service if not started.
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900617 if (auto result = s->Start(); !result.ok()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700618 LOG(ERROR) << "Could not start shutdown critical service '" << s->name()
619 << "': " << result.error();
620 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100621 } else {
622 stop_first.push_back(s.get());
Keun-young Park8d01f632017-03-13 11:54:47 -0700623 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700624 }
Keun-young Park7830d592017-03-27 16:07:02 -0700625
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800626 // remaining operations (specifically fsck) may take a substantial duration
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700627 if (cmd == ANDROID_RB_POWEROFF || is_thermal_shutdown) {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800628 TurnOffBacklight();
629 }
630
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100631 Service* boot_anim = ServiceList::GetInstance().FindService("bootanim");
632 Service* surface_flinger = ServiceList::GetInstance().FindService("surfaceflinger");
633 if (boot_anim != nullptr && surface_flinger != nullptr && surface_flinger->IsRunning()) {
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800634 bool do_shutdown_animation = GetBoolProperty("ro.init.shutdown_animation", false);
635
636 if (do_shutdown_animation) {
Tom Cherryc88d8f92019-08-19 15:21:25 -0700637 SetProperty("service.bootanim.exit", "0");
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800638 // Could be in the middle of animation. Stop and start so that it can pick
639 // up the right mode.
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100640 boot_anim->Stop();
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800641 }
642
Tom Cherry911b9b12017-07-27 16:20:58 -0700643 for (const auto& service : ServiceList::GetInstance()) {
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800644 if (service->classnames().count("animation") == 0) {
645 continue;
646 }
647
648 // start all animation classes if stopped.
649 if (do_shutdown_animation) {
Tom Cherry9949ec52019-05-16 16:54:49 -0700650 service->Start();
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800651 }
652 service->SetShutdownCritical(); // will not check animation class separately
653 }
654
655 if (do_shutdown_animation) {
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100656 boot_anim->Start();
657 surface_flinger->SetShutdownCritical();
658 boot_anim->SetShutdownCritical();
Tom Cherry911b9b12017-07-27 16:20:58 -0700659 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700660 }
Keun-young Park7830d592017-03-27 16:07:02 -0700661
Keun-young Park8d01f632017-03-13 11:54:47 -0700662 // optional shutdown step
663 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Keun-young Park30173872017-07-18 10:58:28 -0700664 if (shutdown_timeout > 0ms) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100665 StopServicesAndLogViolations(stop_first, shutdown_timeout / 2, true /* SIGTERM */);
Keun-young Park8d01f632017-03-13 11:54:47 -0700666 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100667 // Send SIGKILL to ones that didn't terminate cleanly.
668 StopServicesAndLogViolations(stop_first, 0ms, false /* SIGKILL */);
Luis Hector Chavez92c49bc2018-07-27 11:19:25 -0700669 SubcontextTerminate();
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100670 // Reap subcontext pids.
Tom Cherryeeee8312017-07-28 15:22:23 -0700671 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700672
673 // 3. send volume shutdown to vold
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100674 Service* vold_service = ServiceList::GetInstance().FindService("vold");
675 if (vold_service != nullptr && vold_service->IsRunning()) {
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000676 CallVdc("volume", "shutdown");
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100677 vold_service->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700678 } else {
679 LOG(INFO) << "vold not running, skipping vold shutdown";
680 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700681 // logcat stopped here
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100682 StopServices(GetDebuggingServices(false /* only_post_data */), 0ms, false /* SIGKILL */);
Keun-young Park8d01f632017-03-13 11:54:47 -0700683 // 4. sync, try umount, and optionally run fsck for user shutdown
Tom Cherry1f9d5402018-03-15 10:22:40 -0700684 {
685 Timer sync_timer;
686 LOG(INFO) << "sync() before umount...";
687 sync();
688 LOG(INFO) << "sync() before umount took" << sync_timer;
689 }
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800690 // 5. drop caches and disable zram backing device, if exist
691 KillZramBackingDevice();
692
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100693 UmountStat stat =
694 TryUmountAndFsck(cmd, run_fsck, shutdown_timeout - t.duration(), &reboot_semaphore);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700695 // Follow what linux shutdown is doing: one more sync with little bit delay
Tom Cherry1f9d5402018-03-15 10:22:40 -0700696 {
697 Timer sync_timer;
698 LOG(INFO) << "sync() after umount...";
699 sync();
700 LOG(INFO) << "sync() after umount took" << sync_timer;
701 }
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700702 if (!is_thermal_shutdown) std::this_thread::sleep_for(100ms);
Keun-young Park8d01f632017-03-13 11:54:47 -0700703 LogShutdownTime(stat, &t);
josephjangaaddf282019-04-16 18:46:24 +0800704
705 // Send signal to terminate reboot monitor thread.
706 reboot_monitor_run = false;
707 sem_post(&reboot_semaphore);
708
Keun-young Park8d01f632017-03-13 11:54:47 -0700709 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100710 RebootSystem(cmd, reboot_target);
Keun-young Park8d01f632017-03-13 11:54:47 -0700711 abort();
712}
Tom Cherry98ad32a2017-04-17 16:34:20 -0700713
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100714static void EnterShutdown() {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100715 LOG(INFO) << "Entering shutdown mode";
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100716 shutting_down = true;
717 // Skip wait for prop if it is in progress
718 ResetWaitForProp();
719 // Clear EXEC flag if there is one pending
720 for (const auto& s : ServiceList::GetInstance()) {
721 s->UnSetExec();
722 }
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100723}
724
725static void LeaveShutdown() {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100726 LOG(INFO) << "Leaving shutdown mode";
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100727 shutting_down = false;
Tom Cherry802864c2020-03-12 14:29:25 -0700728 StartSendingMessages();
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100729}
730
Nikita Ioffeab91ee92019-11-06 21:40:31 +0000731static Result<void> UnmountAllApexes() {
732 const char* args[] = {"/system/bin/apexd", "--unmount-all"};
733 int status;
734 if (logwrap_fork_execvp(arraysize(args), args, &status, false, LOG_KLOG, true, nullptr) != 0) {
735 return ErrnoError() << "Failed to call '/system/bin/apexd --unmount-all'";
736 }
737 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
738 return {};
739 }
740 return Error() << "'/system/bin/apexd --unmount-all' failed : " << status;
741}
742
Nikita Ioffe7b41a152020-03-25 00:06:51 +0000743static std::chrono::milliseconds GetMillisProperty(const std::string& name,
744 std::chrono::milliseconds default_value) {
745 auto value = GetUintProperty(name, static_cast<uint64_t>(default_value.count()));
746 return std::chrono::milliseconds(std::move(value));
747}
748
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100749static Result<void> DoUserspaceReboot() {
750 LOG(INFO) << "Userspace reboot initiated";
751 auto guard = android::base::make_scope_guard([] {
752 // Leave shutdown so that we can handle a full reboot.
753 LeaveShutdown();
Nikita Ioffe4a787d92020-01-15 23:23:13 +0000754 trigger_shutdown("reboot,userspace_failed,shutdown_aborted");
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100755 });
Nikita Ioffec0df1872019-11-13 21:47:06 +0000756 // Triggering userspace-reboot-requested will result in a bunch of setprop
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100757 // actions. We should make sure, that all of them are propagated before
Nikita Ioffe764c1ac2020-01-27 17:14:46 +0000758 // proceeding with userspace reboot. Synchronously setting sys.init.userspace_reboot.in_progress
759 // property is not perfect, but it should do the trick.
Nikita Ioffe23dbd6d2019-11-14 01:21:24 +0000760 if (!android::sysprop::InitProperties::userspace_reboot_in_progress(true)) {
761 return Error() << "Failed to set sys.init.userspace_reboot.in_progress property";
Nikita Ioffec0df1872019-11-13 21:47:06 +0000762 }
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100763 EnterShutdown();
Nikita Ioffe764c1ac2020-01-27 17:14:46 +0000764 if (!SetProperty("sys.powerctl", "")) {
765 return Error() << "Failed to reset sys.powerctl property";
766 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100767 std::vector<Service*> stop_first;
768 // Remember the services that were enabled. We will need to manually enable them again otherwise
769 // triggers like class_start won't restart them.
770 std::vector<Service*> were_enabled;
771 stop_first.reserve(ServiceList::GetInstance().services().size());
772 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
773 if (s->is_post_data() && !kDebuggingServices.count(s->name())) {
774 stop_first.push_back(s);
775 }
776 if (s->is_post_data() && s->IsEnabled()) {
777 were_enabled.push_back(s);
778 }
779 }
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000780 {
781 Timer sync_timer;
782 LOG(INFO) << "sync() before terminating services...";
783 sync();
784 LOG(INFO) << "sync() took " << sync_timer;
785 }
Nikita Ioffe7b41a152020-03-25 00:06:51 +0000786 auto sigterm_timeout = GetMillisProperty("init.userspace_reboot.sigterm.timeoutmillis", 5s);
787 auto sigkill_timeout = GetMillisProperty("init.userspace_reboot.sigkill.timeoutmillis", 10s);
788 LOG(INFO) << "Timeout to terminate services : " << sigterm_timeout.count() << "ms"
789 << "Timeout to kill services: " << sigkill_timeout.count() << "ms";
790 StopServicesAndLogViolations(stop_first, sigterm_timeout, true /* SIGTERM */);
791 if (int r = StopServicesAndLogViolations(stop_first, sigkill_timeout, false /* SIGKILL */);
792 r > 0) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100793 // TODO(b/135984674): store information about offending services for debugging.
794 return Error() << r << " post-data services are still running";
795 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900796 if (auto result = KillZramBackingDevice(); !result.ok()) {
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000797 return result;
798 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900799 if (auto result = CallVdc("volume", "reset"); !result.ok()) {
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000800 return result;
801 }
Nikita Ioffe7b41a152020-03-25 00:06:51 +0000802 if (int r = StopServicesAndLogViolations(GetDebuggingServices(true /* only_post_data */),
803 sigkill_timeout, false /* SIGKILL */);
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100804 r > 0) {
805 // TODO(b/135984674): store information about offending services for debugging.
806 return Error() << r << " debugging services are still running";
807 }
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000808 {
809 Timer sync_timer;
810 LOG(INFO) << "sync() after stopping services...";
811 sync();
812 LOG(INFO) << "sync() took " << sync_timer;
813 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900814 if (auto result = UnmountAllApexes(); !result.ok()) {
Nikita Ioffeab91ee92019-11-06 21:40:31 +0000815 return result;
816 }
817 if (!SwitchToBootstrapMountNamespaceIfNeeded()) {
818 return Error() << "Failed to switch to bootstrap namespace";
819 }
Nikita Ioffe091c4d12019-12-05 12:35:19 +0000820 // Remove services that were defined in an APEX.
821 ServiceList::GetInstance().RemoveServiceIf([](const std::unique_ptr<Service>& s) -> bool {
822 if (s->is_from_apex()) {
823 LOG(INFO) << "Removing service '" << s->name() << "' because it's defined in an APEX";
824 return true;
825 }
826 return false;
827 });
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100828 // Re-enable services
829 for (const auto& s : were_enabled) {
830 LOG(INFO) << "Re-enabling service '" << s->name() << "'";
831 s->Enable();
832 }
Nikita Ioffe3ad29202020-02-27 20:46:27 +0000833 ServiceList::GetInstance().ResetState();
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100834 LeaveShutdown();
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100835 ActionManager::GetInstance().QueueEventTrigger("userspace-reboot-resume");
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100836 guard.Disable(); // Go on with userspace reboot.
837 return {};
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100838}
839
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000840static void UserspaceRebootWatchdogThread() {
Nikita Ioffed0553542020-04-11 01:55:24 +0100841 auto started_timeout = GetMillisProperty("init.userspace_reboot.started.timeoutmillis", 10s);
842 if (!WaitForProperty("sys.init.userspace_reboot.in_progress", "1", started_timeout)) {
843 LOG(ERROR) << "Userspace reboot didn't start in " << started_timeout.count()
844 << "ms. Switching to full reboot";
845 // Init might be wedged, don't try to write reboot reason into a persistent property and do
846 // a dirty reboot.
847 PersistRebootReason("userspace_failed,watchdog_triggered,failed_to_start", false);
848 RebootSystem(ANDROID_RB_RESTART2, "userspace_failed,watchdog_triggered,failed_to_start");
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000849 }
850 LOG(INFO) << "Starting userspace reboot watchdog";
Nikita Ioffed0553542020-04-11 01:55:24 +0100851 auto watchdog_timeout = GetMillisProperty("init.userspace_reboot.watchdog.timeoutmillis", 5min);
852 LOG(INFO) << "UserspaceRebootWatchdog timeout: " << watchdog_timeout.count() << "ms";
853 if (!WaitForProperty("sys.boot_completed", "1", watchdog_timeout)) {
854 LOG(ERROR) << "Failed to boot in " << watchdog_timeout.count()
855 << "ms. Switching to full reboot";
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000856 // 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 +0000857 // Since init might be wedged, don't try to write reboot reason into a persistent property.
Nikita Ioffed0553542020-04-11 01:55:24 +0100858 PersistRebootReason("userspace_failed,watchdog_triggered,failed_to_boot", false);
859 RebootSystem(ANDROID_RB_RESTART2, "userspace_failed,watchdog_triggered,failed_to_boot");
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000860 }
861 LOG(INFO) << "Device booted, stopping userspace reboot watchdog";
862}
863
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100864static void HandleUserspaceReboot() {
Nikita Ioffe018ddd72019-12-20 16:34:48 +0000865 if (!android::sysprop::InitProperties::is_userspace_reboot_supported().value_or(false)) {
Nikita Ioffe9f473c02019-12-18 13:31:42 +0000866 LOG(ERROR) << "Attempted a userspace reboot on a device that doesn't support it";
867 return;
868 }
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000869 // Spinnig up a separate thread will fail the setns call later in the boot sequence.
870 // Fork a new process to monitor userspace reboot while we are investigating a better solution.
871 pid_t pid = fork();
872 if (pid < 0) {
873 PLOG(ERROR) << "Failed to fork process for userspace reboot watchdog. Switching to full "
874 << "reboot";
Nikita Ioffe4a787d92020-01-15 23:23:13 +0000875 trigger_shutdown("reboot,userspace_failed,watchdog_fork");
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000876 return;
877 }
878 if (pid == 0) {
879 // Child
880 UserspaceRebootWatchdogThread();
881 _exit(EXIT_SUCCESS);
882 }
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100883 LOG(INFO) << "Clearing queue and starting userspace-reboot-requested trigger";
884 auto& am = ActionManager::GetInstance();
885 am.ClearQueue();
886 am.QueueEventTrigger("userspace-reboot-requested");
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100887 auto handler = [](const BuiltinArguments&) { return DoUserspaceReboot(); };
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100888 am.QueueBuiltinAction(handler, "userspace-reboot");
889}
890
Sam Protsenko2c7c3c72019-12-26 21:55:08 +0200891/**
892 * Check if "command" field is set in bootloader message.
893 *
894 * If "command" field is broken (contains non-printable characters prior to
895 * terminating zero), it will be zeroed.
896 *
897 * @param[in,out] boot Bootloader message (BCB) structure
898 * @return true if "command" field is already set, and false if it's empty
899 */
900static bool CommandIsPresent(bootloader_message* boot) {
901 if (boot->command[0] == '\0')
902 return false;
903
904 for (size_t i = 0; i < arraysize(boot->command); ++i) {
905 if (boot->command[i] == '\0')
906 return true;
907 if (!isprint(boot->command[i]))
908 break;
909 }
910
911 memset(boot->command, 0, sizeof(boot->command));
912 return false;
913}
914
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100915void HandlePowerctlMessage(const std::string& command) {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700916 unsigned int cmd = 0;
Mark Salyzyn62909822017-10-09 09:27:16 -0700917 std::vector<std::string> cmd_params = Split(command, ",");
Tom Cherry98ad32a2017-04-17 16:34:20 -0700918 std::string reboot_target = "";
919 bool run_fsck = false;
920 bool command_invalid = false;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100921 bool userspace_reboot = false;
Tom Cherry98ad32a2017-04-17 16:34:20 -0700922
Mark Salyzynd7931f12019-07-10 10:33:09 -0700923 if (cmd_params[0] == "shutdown") {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700924 cmd = ANDROID_RB_POWEROFF;
Mark Salyzynd7931f12019-07-10 10:33:09 -0700925 if (cmd_params.size() >= 2) {
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700926 if (cmd_params[1] == "userrequested") {
927 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
928 // Run fsck once the file system is remounted in read-only mode.
929 run_fsck = true;
930 } else if (cmd_params[1] == "thermal") {
Mark Salyzynbfd05b62017-09-26 11:10:12 -0700931 // Turn off sources of heat immediately.
932 TurnOffBacklight();
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700933 // run_fsck is false to avoid delay
934 cmd = ANDROID_RB_THERMOFF;
935 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700936 }
937 } else if (cmd_params[0] == "reboot") {
938 cmd = ANDROID_RB_RESTART2;
939 if (cmd_params.size() >= 2) {
940 reboot_target = cmd_params[1];
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100941 if (reboot_target == "userspace") {
942 LOG(INFO) << "Userspace reboot requested";
943 userspace_reboot = true;
944 }
Hridya Valsaraju54258262018-09-19 21:14:18 -0700945 // adb reboot fastboot should boot into bootloader for devices not
946 // supporting logical partitions.
947 if (reboot_target == "fastboot" &&
Yifan Hong0e0f8182018-11-16 12:49:06 -0800948 !android::base::GetBoolProperty("ro.boot.dynamic_partitions", false)) {
Hridya Valsaraju54258262018-09-19 21:14:18 -0700949 reboot_target = "bootloader";
950 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700951 // When rebooting to the bootloader notify the bootloader writing
952 // also the BCB.
953 if (reboot_target == "bootloader") {
954 std::string err;
955 if (!write_reboot_bootloader(&err)) {
956 LOG(ERROR) << "reboot-bootloader: Error writing "
957 "bootloader_message: "
958 << err;
959 }
Tianjie Xu5e98b632019-07-18 12:48:28 -0700960 } else if (reboot_target == "recovery") {
961 bootloader_message boot = {};
962 if (std::string err; !read_bootloader_message(&boot, &err)) {
963 LOG(ERROR) << "Failed to read bootloader message: " << err;
964 }
965 // Update the boot command field if it's empty, and preserve
966 // the other arguments in the bootloader message.
Sam Protsenko2c7c3c72019-12-26 21:55:08 +0200967 if (!CommandIsPresent(&boot)) {
Tianjie Xu5e98b632019-07-18 12:48:28 -0700968 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
969 if (std::string err; !write_bootloader_message(boot, &err)) {
970 LOG(ERROR) << "Failed to set bootloader message: " << err;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100971 return;
Tianjie Xu5e98b632019-07-18 12:48:28 -0700972 }
973 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700974 } else if (reboot_target == "sideload" || reboot_target == "sideload-auto-reboot" ||
975 reboot_target == "fastboot") {
976 std::string arg = reboot_target == "sideload-auto-reboot" ? "sideload_auto_reboot"
977 : reboot_target;
978 const std::vector<std::string> options = {
979 "--" + arg,
980 };
981 std::string err;
982 if (!write_bootloader_message(options, &err)) {
983 LOG(ERROR) << "Failed to set bootloader message: " << err;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100984 return;
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700985 }
986 reboot_target = "recovery";
Tom Cherry98ad32a2017-04-17 16:34:20 -0700987 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700988
Mark Salyzynd7931f12019-07-10 10:33:09 -0700989 // If there are additional parameter, pass them along
990 for (size_t i = 2; (cmd_params.size() > i) && cmd_params[i].size(); ++i) {
991 reboot_target += "," + cmd_params[i];
Tom Cherry98ad32a2017-04-17 16:34:20 -0700992 }
993 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700994 } else {
995 command_invalid = true;
996 }
997 if (command_invalid) {
998 LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100999 return;
1000 }
1001
Tom Cherry802864c2020-03-12 14:29:25 -07001002 // We do not want to process any messages (queue'ing triggers, shutdown messages, control
1003 // messages, etc) from properties during reboot.
1004 StopSendingMessages();
1005
Nikita Ioffeba6968e2019-10-07 16:26:33 +01001006 if (userspace_reboot) {
1007 HandleUserspaceReboot();
1008 return;
Tom Cherry98ad32a2017-04-17 16:34:20 -07001009 }
1010
Wei Wangeeab4912017-06-27 22:08:45 -07001011 LOG(INFO) << "Clear action queue and start shutdown trigger";
1012 ActionManager::GetInstance().ClearQueue();
1013 // Queue shutdown trigger first
1014 ActionManager::GetInstance().QueueEventTrigger("shutdown");
1015 // Queue built-in shutdown_done
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001016 auto shutdown_handler = [cmd, command, reboot_target, run_fsck](const BuiltinArguments&) {
Wei Wangeeab4912017-06-27 22:08:45 -07001017 DoReboot(cmd, command, reboot_target, run_fsck);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001018 return Result<void>{};
Wei Wangeeab4912017-06-27 22:08:45 -07001019 };
1020 ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
1021
Nikita Ioffeba6968e2019-10-07 16:26:33 +01001022 EnterShutdown();
1023}
Wei Wangeeab4912017-06-27 22:08:45 -07001024
Nikita Ioffeba6968e2019-10-07 16:26:33 +01001025bool IsShuttingDown() {
1026 return shutting_down;
Tom Cherry98ad32a2017-04-17 16:34:20 -07001027}
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001028
1029} // namespace init
1030} // namespace android