blob: f006df3a348d8ecd828469ce29ffc2034e46534d [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 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
Tom Cherry832f9f12020-03-10 11:47:24 -070089static std::vector<Service*> GetDebuggingServices(bool only_post_data) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010090 std::vector<Service*> ret;
91 ret.reserve(kDebuggingServices.size());
92 for (const auto& s : ServiceList::GetInstance()) {
93 if (kDebuggingServices.count(s->name()) && (!only_post_data || s->is_post_data())) {
94 ret.push_back(s.get());
95 }
96 }
97 return ret;
98}
99
Nikita Ioffed485bbb2020-02-26 15:18:56 +0000100static void PersistRebootReason(const char* reason, bool write_to_property) {
101 if (write_to_property) {
102 SetProperty(LAST_REBOOT_REASON_PROPERTY, reason);
103 }
Nikita Ioffed0bc0b62020-02-19 16:21:11 +0000104 WriteStringToFile(reason, LAST_REBOOT_REASON_FILE);
105}
106
Keun-young Park8d01f632017-03-13 11:54:47 -0700107// represents umount status during reboot / shutdown.
108enum UmountStat {
109 /* umount succeeded. */
110 UMOUNT_STAT_SUCCESS = 0,
111 /* umount was not run. */
112 UMOUNT_STAT_SKIPPED = 1,
113 /* umount failed with timeout. */
114 UMOUNT_STAT_TIMEOUT = 2,
115 /* could not run due to error */
116 UMOUNT_STAT_ERROR = 3,
117 /* not used by init but reserved for other part to use this to represent the
118 the state where umount status before reboot is not found / available. */
119 UMOUNT_STAT_NOT_AVAILABLE = 4,
120};
121
122// Utility for struct mntent
123class MountEntry {
124 public:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700125 explicit MountEntry(const mntent& entry)
Keun-young Park8d01f632017-03-13 11:54:47 -0700126 : mnt_fsname_(entry.mnt_fsname),
127 mnt_dir_(entry.mnt_dir),
128 mnt_type_(entry.mnt_type),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700129 mnt_opts_(entry.mnt_opts) {}
Keun-young Park8d01f632017-03-13 11:54:47 -0700130
Jaegeuk Kim0f04f722017-09-25 10:55:39 -0700131 bool Umount(bool force) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800132 LOG(INFO) << "Unmounting " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Jaegeuk Kim0f04f722017-09-25 10:55:39 -0700133 int r = umount2(mnt_dir_.c_str(), force ? MNT_FORCE : 0);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700134 if (r == 0) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800135 LOG(INFO) << "Umounted " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700136 return true;
137 } else {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800138 PLOG(WARNING) << "Cannot umount " << mnt_fsname_ << ":" << mnt_dir_ << " opts "
Keun-young Park2ba5c812017-03-29 12:54:40 -0700139 << mnt_opts_;
140 return false;
141 }
142 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700143
Keun-young Park2ba5c812017-03-29 12:54:40 -0700144 void DoFsck() {
145 int st;
146 if (IsF2Fs()) {
147 const char* f2fs_argv[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800148 "/system/bin/fsck.f2fs",
149 "-a",
150 mnt_fsname_.c_str(),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700151 };
Tom Cherry3a803eb2019-09-25 16:23:50 -0700152 logwrap_fork_execvp(arraysize(f2fs_argv), f2fs_argv, &st, false, LOG_KLOG, true,
153 nullptr);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700154 } else if (IsExt4()) {
155 const char* ext4_argv[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800156 "/system/bin/e2fsck",
157 "-y",
158 mnt_fsname_.c_str(),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700159 };
Tom Cherry3a803eb2019-09-25 16:23:50 -0700160 logwrap_fork_execvp(arraysize(ext4_argv), ext4_argv, &st, false, LOG_KLOG, true,
161 nullptr);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700162 }
163 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700164
165 static bool IsBlockDevice(const struct mntent& mntent) {
166 return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
167 }
168
169 static bool IsEmulatedDevice(const struct mntent& mntent) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700170 return android::base::StartsWith(mntent.mnt_fsname, "/data/");
Keun-young Park8d01f632017-03-13 11:54:47 -0700171 }
172
173 private:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700174 bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
175
176 bool IsExt4() const { return mnt_type_ == "ext4"; }
177
Keun-young Park8d01f632017-03-13 11:54:47 -0700178 std::string mnt_fsname_;
179 std::string mnt_dir_;
180 std::string mnt_type_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700181 std::string mnt_opts_;
Keun-young Park8d01f632017-03-13 11:54:47 -0700182};
183
184// Turn off backlight while we are performing power down cleanup activities.
Tom Cherry832f9f12020-03-10 11:47:24 -0700185static void TurnOffBacklight() {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800186 Service* service = ServiceList::GetInstance().FindService("blank_screen");
187 if (service == nullptr) {
188 LOG(WARNING) << "cannot find blank_screen in TurnOffBacklight";
Keun-young Park8d01f632017-03-13 11:54:47 -0700189 return;
190 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900191 if (auto result = service->Start(); !result.ok()) {
Tom Cherryd9872642018-10-11 10:38:05 -0700192 LOG(WARNING) << "Could not start blank_screen service: " << result.error();
193 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700194}
195
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000196static Result<void> CallVdc(const std::string& system, const std::string& cmd) {
197 const char* vdc_argv[] = {"/system/bin/vdc", system.c_str(), cmd.c_str()};
Keun-young Park8d01f632017-03-13 11:54:47 -0700198 int status;
Nikita Ioffe12a36072019-10-23 20:11:32 +0100199 if (logwrap_fork_execvp(arraysize(vdc_argv), vdc_argv, &status, false, LOG_KLOG, true,
200 nullptr) != 0) {
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000201 return ErrnoError() << "Failed to call '/system/bin/vdc " << system << " " << cmd << "'";
Nikita Ioffe12a36072019-10-23 20:11:32 +0100202 }
203 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
204 return {};
205 }
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000206 return Error() << "'/system/bin/vdc " << system << " " << cmd << "' failed : " << status;
Keun-young Park8d01f632017-03-13 11:54:47 -0700207}
208
209static void LogShutdownTime(UmountStat stat, Timer* t) {
Tom Cherryede0d532017-07-06 14:20:11 -0700210 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration().count()) << ":"
211 << stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700212}
213
Tom Cherry2436e6b2019-09-19 11:16:19 -0700214static bool IsDataMounted() {
215 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
216 if (fp == nullptr) {
217 PLOG(ERROR) << "Failed to open /proc/mounts";
218 return false;
219 }
220 mntent* mentry;
221 while ((mentry = getmntent(fp.get())) != nullptr) {
222 if (mentry->mnt_dir == "/data"s) {
223 return true;
224 }
225 }
226 return false;
227}
228
229// Find all read+write block devices and emulated devices in /proc/mounts and add them to
230// the correpsponding list.
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100231static bool FindPartitionsToUmount(std::vector<MountEntry>* block_dev_partitions,
232 std::vector<MountEntry>* emulated_partitions, bool dump) {
Tom Cherryf274e782018-10-03 13:13:41 -0700233 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
Keun-young Park8d01f632017-03-13 11:54:47 -0700234 if (fp == nullptr) {
235 PLOG(ERROR) << "Failed to open /proc/mounts";
236 return false;
237 }
238 mntent* mentry;
239 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700240 if (dump) {
241 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
242 << mentry->mnt_opts << " type " << mentry->mnt_type;
243 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
Keun-young Park6e12b382017-07-17 12:20:33 -0700244 std::string mount_dir(mentry->mnt_dir);
245 // These are R/O partitions changed to R/W after adb remount.
246 // Do not umount them as shutdown critical services may rely on them.
Wei Wanga01c27e2017-07-25 10:52:08 -0700247 if (mount_dir != "/" && mount_dir != "/system" && mount_dir != "/vendor" &&
248 mount_dir != "/oem") {
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100249 block_dev_partitions->emplace(block_dev_partitions->begin(), *mentry);
Keun-young Park6e12b382017-07-17 12:20:33 -0700250 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700251 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100252 emulated_partitions->emplace(emulated_partitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700253 }
254 }
255 return true;
256}
257
Jonglin Lee28a2c922019-01-15 16:38:44 -0800258static void DumpUmountDebuggingInfo() {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700259 int status;
260 if (!security_getenforce()) {
261 LOG(INFO) << "Run lsof";
262 const char* lsof_argv[] = {"/system/bin/lsof"};
Tom Cherry3a803eb2019-09-25 16:23:50 -0700263 logwrap_fork_execvp(arraysize(lsof_argv), lsof_argv, &status, false, LOG_KLOG, true,
264 nullptr);
Keun-young Park8d01f632017-03-13 11:54:47 -0700265 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700266 FindPartitionsToUmount(nullptr, nullptr, true);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800267 // dump current CPU stack traces and uninterruptible tasks
josephjangaaddf282019-04-16 18:46:24 +0800268 WriteStringToFile("l", PROC_SYSRQ);
269 WriteStringToFile("w", PROC_SYSRQ);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700270}
271
Tom Cherryede0d532017-07-06 14:20:11 -0700272static UmountStat UmountPartitions(std::chrono::milliseconds timeout) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700273 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700274 /* data partition needs all pending writes to be completed and all emulated partitions
275 * umounted.If the current waiting is not good enough, give
276 * up and leave it to e2fsck after reboot to fix it.
277 */
278 while (true) {
279 std::vector<MountEntry> block_devices;
280 std::vector<MountEntry> emulated_devices;
281 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
282 return UMOUNT_STAT_ERROR;
283 }
284 if (block_devices.size() == 0) {
Wei Wang8c00e422017-08-16 14:01:46 -0700285 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700286 }
Wei Wang8c00e422017-08-16 14:01:46 -0700287 bool unmount_done = true;
288 if (emulated_devices.size() > 0) {
Wei Wang25dc30f2017-10-23 15:32:03 -0700289 for (auto& entry : emulated_devices) {
290 if (!entry.Umount(false)) unmount_done = false;
291 }
Wei Wang8c00e422017-08-16 14:01:46 -0700292 if (unmount_done) {
293 sync();
294 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700295 }
Wei Wang25dc30f2017-10-23 15:32:03 -0700296 for (auto& entry : block_devices) {
297 if (!entry.Umount(timeout == 0ms)) unmount_done = false;
298 }
Wei Wang8c00e422017-08-16 14:01:46 -0700299 if (unmount_done) {
300 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700301 }
Wei Wang8c00e422017-08-16 14:01:46 -0700302 if ((timeout < t.duration())) { // try umount at least once
303 return UMOUNT_STAT_TIMEOUT;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700304 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700305 std::this_thread::sleep_for(100ms);
306 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700307}
308
josephjangaaddf282019-04-16 18:46:24 +0800309static void KillAllProcesses() {
310 WriteStringToFile("i", PROC_SYSRQ);
311}
312
313// Create reboot/shutdwon monitor thread
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100314void RebootMonitorThread(unsigned int cmd, const std::string& reboot_target,
315 sem_t* reboot_semaphore, std::chrono::milliseconds shutdown_timeout,
316 bool* reboot_monitor_run) {
josephjangaaddf282019-04-16 18:46:24 +0800317 unsigned int remaining_shutdown_time = 0;
318
319 // 30 seconds more than the timeout passed to the thread as there is a final Umount pass
320 // after the timeout is reached.
321 constexpr unsigned int shutdown_watchdog_timeout_default = 30;
322 auto shutdown_watchdog_timeout = android::base::GetUintProperty(
323 "ro.build.shutdown.watchdog.timeout", shutdown_watchdog_timeout_default);
324 remaining_shutdown_time = shutdown_watchdog_timeout + shutdown_timeout.count() / 1000;
325
326 while (*reboot_monitor_run == true) {
327 if (TEMP_FAILURE_RETRY(sem_wait(reboot_semaphore)) == -1) {
328 LOG(ERROR) << "sem_wait failed and exit RebootMonitorThread()";
329 return;
330 }
331
332 timespec shutdown_timeout_timespec;
333 if (clock_gettime(CLOCK_MONOTONIC, &shutdown_timeout_timespec) == -1) {
334 LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
335 return;
336 }
337
338 // If there are some remaining shutdown time left from previous round, we use
339 // remaining time here.
340 shutdown_timeout_timespec.tv_sec += remaining_shutdown_time;
341
342 LOG(INFO) << "shutdown_timeout_timespec.tv_sec: " << shutdown_timeout_timespec.tv_sec;
343
344 int sem_return = 0;
345 while ((sem_return = sem_timedwait_monotonic_np(reboot_semaphore,
346 &shutdown_timeout_timespec)) == -1 &&
347 errno == EINTR) {
348 }
349
350 if (sem_return == -1) {
351 LOG(ERROR) << "Reboot thread timed out";
352
353 if (android::base::GetBoolProperty("ro.debuggable", false) == true) {
Tom Cherry2436e6b2019-09-19 11:16:19 -0700354 if (false) {
355 // SEPolicy will block debuggerd from running and this is intentional.
356 // But these lines are left to be enabled during debugging.
357 LOG(INFO) << "Try to dump init process call trace:";
358 const char* vdc_argv[] = {"/system/bin/debuggerd", "-b", "1"};
359 int status;
Tom Cherry3a803eb2019-09-25 16:23:50 -0700360 logwrap_fork_execvp(arraysize(vdc_argv), vdc_argv, &status, false, LOG_KLOG,
361 true, nullptr);
Tom Cherry2436e6b2019-09-19 11:16:19 -0700362 }
josephjangaaddf282019-04-16 18:46:24 +0800363 LOG(INFO) << "Show stack for all active CPU:";
364 WriteStringToFile("l", PROC_SYSRQ);
365
366 LOG(INFO) << "Show tasks that are in disk sleep(uninterruptable sleep), which are "
367 "like "
368 "blocked in mutex or hardware register access:";
369 WriteStringToFile("w", PROC_SYSRQ);
370 }
371
372 // In shutdown case,notify kernel to sync and umount fs to read-only before shutdown.
373 if (cmd == ANDROID_RB_POWEROFF || cmd == ANDROID_RB_THERMOFF) {
374 WriteStringToFile("s", PROC_SYSRQ);
375
376 WriteStringToFile("u", PROC_SYSRQ);
377
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100378 RebootSystem(cmd, reboot_target);
josephjangaaddf282019-04-16 18:46:24 +0800379 }
380
381 LOG(ERROR) << "Trigger crash at last!";
382 WriteStringToFile("c", PROC_SYSRQ);
383 } else {
384 timespec current_time_timespec;
385
386 if (clock_gettime(CLOCK_MONOTONIC, &current_time_timespec) == -1) {
387 LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
388 return;
389 }
390
391 remaining_shutdown_time =
392 shutdown_timeout_timespec.tv_sec - current_time_timespec.tv_sec;
393
394 LOG(INFO) << "remaining_shutdown_time: " << remaining_shutdown_time;
395 }
396 }
397}
Keun-young Park3ee0df92017-03-27 11:21:09 -0700398
Keun-young Park8d01f632017-03-13 11:54:47 -0700399/* Try umounting all emulated file systems R/W block device cfile systems.
400 * This will just try umount and give it up if it fails.
401 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
402 * and necessary check can be done at the next reboot.
403 * For safer shutdown, caller needs to make sure that
404 * all processes / emulated partition for the target fs are all cleaned-up.
405 *
406 * return true when umount was successful. false when timed out.
407 */
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100408static UmountStat TryUmountAndFsck(unsigned int cmd, bool run_fsck,
josephjangaaddf282019-04-16 18:46:24 +0800409 std::chrono::milliseconds timeout, sem_t* reboot_semaphore) {
Keun-young Park3ee0df92017-03-27 11:21:09 -0700410 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700411 std::vector<MountEntry> block_devices;
412 std::vector<MountEntry> emulated_devices;
Keun-young Park8d01f632017-03-13 11:54:47 -0700413
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100414 if (run_fsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700415 return UMOUNT_STAT_ERROR;
416 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700417
Tom Cherryede0d532017-07-06 14:20:11 -0700418 UmountStat stat = UmountPartitions(timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700419 if (stat != UMOUNT_STAT_SUCCESS) {
420 LOG(INFO) << "umount timeout, last resort, kill all and try";
Jonglin Lee28a2c922019-01-15 16:38:44 -0800421 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park3ee0df92017-03-27 11:21:09 -0700422 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700423 // 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 -0700424 UmountStat st = UmountPartitions(0ms);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800425 if ((st != UMOUNT_STAT_SUCCESS) && DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park8d01f632017-03-13 11:54:47 -0700426 }
427
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100428 if (stat == UMOUNT_STAT_SUCCESS && run_fsck) {
josephjangaaddf282019-04-16 18:46:24 +0800429 LOG(INFO) << "Pause reboot monitor thread before fsck";
430 sem_post(reboot_semaphore);
431
Keun-young Park2ba5c812017-03-29 12:54:40 -0700432 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
433 // and should not affect reboot time.
434 for (auto& entry : block_devices) {
435 entry.DoFsck();
436 }
josephjangaaddf282019-04-16 18:46:24 +0800437
438 LOG(INFO) << "Resume reboot monitor thread after fsck";
439 sem_post(reboot_semaphore);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700440 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700441 return stat;
442}
443
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800444// zram is able to use backing device on top of a loopback device.
445// In order to unmount /data successfully, we have to kill the loopback device first
446#define ZRAM_DEVICE "/dev/block/zram0"
447#define ZRAM_RESET "/sys/block/zram0/reset"
448#define ZRAM_BACK_DEV "/sys/block/zram0/backing_dev"
Nikita Ioffe12a36072019-10-23 20:11:32 +0100449static Result<void> KillZramBackingDevice() {
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800450 std::string backing_dev;
Nikita Ioffe12a36072019-10-23 20:11:32 +0100451 if (!android::base::ReadFileToString(ZRAM_BACK_DEV, &backing_dev)) return {};
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800452
Nikita Ioffe12a36072019-10-23 20:11:32 +0100453 if (!android::base::StartsWith(backing_dev, "/dev/block/loop")) return {};
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800454
455 // cut the last "\n"
456 backing_dev.erase(backing_dev.length() - 1);
457
458 // shutdown zram handle
459 Timer swap_timer;
460 LOG(INFO) << "swapoff() start...";
461 if (swapoff(ZRAM_DEVICE) == -1) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100462 return ErrnoError() << "zram_backing_dev: swapoff (" << backing_dev << ")"
463 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800464 }
465 LOG(INFO) << "swapoff() took " << swap_timer;;
466
josephjangaaddf282019-04-16 18:46:24 +0800467 if (!WriteStringToFile("1", ZRAM_RESET)) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100468 return Error() << "zram_backing_dev: reset (" << backing_dev << ")"
469 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800470 }
471
472 // clear loopback device
473 unique_fd loop(TEMP_FAILURE_RETRY(open(backing_dev.c_str(), O_RDWR | O_CLOEXEC)));
474 if (loop.get() < 0) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100475 return ErrnoError() << "zram_backing_dev: open(" << backing_dev << ")"
476 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800477 }
478
479 if (ioctl(loop.get(), LOOP_CLR_FD, 0) < 0) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100480 return ErrnoError() << "zram_backing_dev: loop_clear (" << backing_dev << ")"
481 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800482 }
483 LOG(INFO) << "zram_backing_dev: `" << backing_dev << "` is cleared successfully.";
Nikita Ioffe12a36072019-10-23 20:11:32 +0100484 return {};
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800485}
486
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100487// Stops given services, waits for them to be stopped for |timeout| ms.
488// If terminate is true, then SIGTERM is sent to services, otherwise SIGKILL is sent.
489static void StopServices(const std::vector<Service*>& services, std::chrono::milliseconds timeout,
490 bool terminate) {
491 LOG(INFO) << "Stopping " << services.size() << " services by sending "
492 << (terminate ? "SIGTERM" : "SIGKILL");
493 std::vector<pid_t> pids;
494 pids.reserve(services.size());
495 for (const auto& s : services) {
496 if (s->pid() > 0) {
497 pids.push_back(s->pid());
498 }
499 if (terminate) {
500 s->Terminate();
501 } else {
502 s->Stop();
503 }
504 }
505 if (timeout > 0ms) {
506 WaitToBeReaped(pids, timeout);
507 } else {
508 // Even if we don't to wait for services to stop, we still optimistically reap zombies.
509 ReapAnyOutstandingChildren();
510 }
511}
512
513// Like StopServices, but also logs all the services that failed to stop after the provided timeout.
514// Returns number of violators.
515static int StopServicesAndLogViolations(const std::vector<Service*>& services,
516 std::chrono::milliseconds timeout, bool terminate) {
517 StopServices(services, timeout, terminate);
518 int still_running = 0;
519 for (const auto& s : services) {
520 if (s->IsRunning()) {
521 LOG(ERROR) << "[service-misbehaving] : service '" << s->name() << "' is still running "
522 << timeout.count() << "ms after receiving "
523 << (terminate ? "SIGTERM" : "SIGKILL");
524 still_running++;
525 }
526 }
527 return still_running;
528}
529
Tom Cherry44aceed2018-08-03 13:36:18 -0700530//* Reboot / shutdown the system.
531// cmd ANDROID_RB_* as defined in android_reboot.h
532// reason Reason string like "reboot", "shutdown,userrequested"
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100533// reboot_target Reboot target string like "bootloader". Otherwise, it should be an empty string.
534// run_fsck Whether to run fsck after umount is done.
Tom Cherry44aceed2018-08-03 13:36:18 -0700535//
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100536static void DoReboot(unsigned int cmd, const std::string& reason, const std::string& reboot_target,
537 bool run_fsck) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700538 Timer t;
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100539 LOG(INFO) << "Reboot start, reason: " << reason << ", reboot_target: " << reboot_target;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700540
541 // Ensure last reboot reason is reduced to canonical
542 // alias reported in bootloader or system boot reason.
543 size_t skip = 0;
544 std::vector<std::string> reasons = Split(reason, ",");
545 if (reasons.size() >= 2 && reasons[0] == "reboot" &&
546 (reasons[1] == "recovery" || reasons[1] == "bootloader" || reasons[1] == "cold" ||
547 reasons[1] == "hard" || reasons[1] == "warm")) {
548 skip = strlen("reboot,");
549 }
Nikita Ioffed485bbb2020-02-26 15:18:56 +0000550 PersistRebootReason(reason.c_str() + skip, true);
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700551 sync();
552
Nikita Ioffed485bbb2020-02-26 15:18:56 +0000553 // If /data isn't mounted then we can skip the extra reboot steps below, since we don't need to
554 // worry about unmounting it.
555 if (!IsDataMounted()) {
556 sync();
557 RebootSystem(cmd, reboot_target);
558 abort();
559 }
560
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700561 bool is_thermal_shutdown = cmd == ANDROID_RB_THERMOFF;
562
563 auto shutdown_timeout = 0ms;
564 if (!SHUTDOWN_ZERO_TIMEOUT) {
Wei Wangb5de0882018-10-09 12:42:06 -0700565 constexpr unsigned int shutdown_timeout_default = 6;
566 constexpr unsigned int max_thermal_shutdown_timeout = 3;
567 auto shutdown_timeout_final = android::base::GetUintProperty("ro.build.shutdown_timeout",
568 shutdown_timeout_default);
569 if (is_thermal_shutdown && shutdown_timeout_final > max_thermal_shutdown_timeout) {
570 shutdown_timeout_final = max_thermal_shutdown_timeout;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700571 }
Wei Wangb5de0882018-10-09 12:42:06 -0700572 shutdown_timeout = std::chrono::seconds(shutdown_timeout_final);
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700573 }
574 LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " ms";
575
josephjangaaddf282019-04-16 18:46:24 +0800576 sem_t reboot_semaphore;
577 if (sem_init(&reboot_semaphore, false, 0) == -1) {
578 // These should never fail, but if they do, skip the graceful reboot and reboot immediately.
579 LOG(ERROR) << "sem_init() fail and RebootSystem() return!";
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100580 RebootSystem(cmd, reboot_target);
josephjangaaddf282019-04-16 18:46:24 +0800581 }
582
583 // Start a thread to monitor init shutdown process
584 LOG(INFO) << "Create reboot monitor thread.";
585 bool reboot_monitor_run = true;
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100586 std::thread reboot_monitor_thread(&RebootMonitorThread, cmd, reboot_target, &reboot_semaphore,
josephjangaaddf282019-04-16 18:46:24 +0800587 shutdown_timeout, &reboot_monitor_run);
588 reboot_monitor_thread.detach();
589
590 // Start reboot monitor thread
591 sem_post(&reboot_semaphore);
592
Keun-young Park7830d592017-03-27 16:07:02 -0700593 // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700594 const std::set<std::string> to_starts{"watchdogd"};
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100595 std::vector<Service*> stop_first;
596 stop_first.reserve(ServiceList::GetInstance().services().size());
Tom Cherry911b9b12017-07-27 16:20:58 -0700597 for (const auto& s : ServiceList::GetInstance()) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100598 if (kDebuggingServices.count(s->name())) {
599 // keep debugging tools until non critical ones are all gone.
Keun-young Park7830d592017-03-27 16:07:02 -0700600 s->SetShutdownCritical();
601 } else if (to_starts.count(s->name())) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900602 if (auto result = s->Start(); !result.ok()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700603 LOG(ERROR) << "Could not start shutdown 'to_start' service '" << s->name()
604 << "': " << result.error();
605 }
Keun-young Park7830d592017-03-27 16:07:02 -0700606 s->SetShutdownCritical();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700607 } else if (s->IsShutdownCritical()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700608 // Start shutdown critical service if not started.
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900609 if (auto result = s->Start(); !result.ok()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700610 LOG(ERROR) << "Could not start shutdown critical service '" << s->name()
611 << "': " << result.error();
612 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100613 } else {
614 stop_first.push_back(s.get());
Keun-young Park8d01f632017-03-13 11:54:47 -0700615 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700616 }
Keun-young Park7830d592017-03-27 16:07:02 -0700617
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800618 // remaining operations (specifically fsck) may take a substantial duration
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700619 if (cmd == ANDROID_RB_POWEROFF || is_thermal_shutdown) {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800620 TurnOffBacklight();
621 }
622
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100623 Service* boot_anim = ServiceList::GetInstance().FindService("bootanim");
624 Service* surface_flinger = ServiceList::GetInstance().FindService("surfaceflinger");
625 if (boot_anim != nullptr && surface_flinger != nullptr && surface_flinger->IsRunning()) {
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800626 bool do_shutdown_animation = GetBoolProperty("ro.init.shutdown_animation", false);
627
628 if (do_shutdown_animation) {
Tom Cherryc88d8f92019-08-19 15:21:25 -0700629 SetProperty("service.bootanim.exit", "0");
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800630 // Could be in the middle of animation. Stop and start so that it can pick
631 // up the right mode.
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100632 boot_anim->Stop();
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800633 }
634
Tom Cherry911b9b12017-07-27 16:20:58 -0700635 for (const auto& service : ServiceList::GetInstance()) {
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800636 if (service->classnames().count("animation") == 0) {
637 continue;
638 }
639
640 // start all animation classes if stopped.
641 if (do_shutdown_animation) {
Tom Cherry9949ec52019-05-16 16:54:49 -0700642 service->Start();
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800643 }
644 service->SetShutdownCritical(); // will not check animation class separately
645 }
646
647 if (do_shutdown_animation) {
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100648 boot_anim->Start();
649 surface_flinger->SetShutdownCritical();
650 boot_anim->SetShutdownCritical();
Tom Cherry911b9b12017-07-27 16:20:58 -0700651 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700652 }
Keun-young Park7830d592017-03-27 16:07:02 -0700653
Keun-young Park8d01f632017-03-13 11:54:47 -0700654 // optional shutdown step
655 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Keun-young Park30173872017-07-18 10:58:28 -0700656 if (shutdown_timeout > 0ms) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100657 StopServicesAndLogViolations(stop_first, shutdown_timeout / 2, true /* SIGTERM */);
Keun-young Park8d01f632017-03-13 11:54:47 -0700658 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100659 // Send SIGKILL to ones that didn't terminate cleanly.
660 StopServicesAndLogViolations(stop_first, 0ms, false /* SIGKILL */);
Luis Hector Chavez92c49bc2018-07-27 11:19:25 -0700661 SubcontextTerminate();
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100662 // Reap subcontext pids.
Tom Cherryeeee8312017-07-28 15:22:23 -0700663 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700664
665 // 3. send volume shutdown to vold
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100666 Service* vold_service = ServiceList::GetInstance().FindService("vold");
667 if (vold_service != nullptr && vold_service->IsRunning()) {
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000668 CallVdc("volume", "shutdown");
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100669 vold_service->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700670 } else {
671 LOG(INFO) << "vold not running, skipping vold shutdown";
672 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700673 // logcat stopped here
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100674 StopServices(GetDebuggingServices(false /* only_post_data */), 0ms, false /* SIGKILL */);
Keun-young Park8d01f632017-03-13 11:54:47 -0700675 // 4. sync, try umount, and optionally run fsck for user shutdown
Tom Cherry1f9d5402018-03-15 10:22:40 -0700676 {
677 Timer sync_timer;
678 LOG(INFO) << "sync() before umount...";
679 sync();
680 LOG(INFO) << "sync() before umount took" << sync_timer;
681 }
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800682 // 5. drop caches and disable zram backing device, if exist
683 KillZramBackingDevice();
684
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100685 UmountStat stat =
686 TryUmountAndFsck(cmd, run_fsck, shutdown_timeout - t.duration(), &reboot_semaphore);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700687 // Follow what linux shutdown is doing: one more sync with little bit delay
Tom Cherry1f9d5402018-03-15 10:22:40 -0700688 {
689 Timer sync_timer;
690 LOG(INFO) << "sync() after umount...";
691 sync();
692 LOG(INFO) << "sync() after umount took" << sync_timer;
693 }
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700694 if (!is_thermal_shutdown) std::this_thread::sleep_for(100ms);
Keun-young Park8d01f632017-03-13 11:54:47 -0700695 LogShutdownTime(stat, &t);
josephjangaaddf282019-04-16 18:46:24 +0800696
697 // Send signal to terminate reboot monitor thread.
698 reboot_monitor_run = false;
699 sem_post(&reboot_semaphore);
700
Keun-young Park8d01f632017-03-13 11:54:47 -0700701 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100702 RebootSystem(cmd, reboot_target);
Keun-young Park8d01f632017-03-13 11:54:47 -0700703 abort();
704}
Tom Cherry98ad32a2017-04-17 16:34:20 -0700705
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100706static void EnterShutdown() {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100707 LOG(INFO) << "Entering shutdown mode";
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100708 shutting_down = true;
709 // Skip wait for prop if it is in progress
710 ResetWaitForProp();
711 // Clear EXEC flag if there is one pending
712 for (const auto& s : ServiceList::GetInstance()) {
713 s->UnSetExec();
714 }
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100715}
716
717static void LeaveShutdown() {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100718 LOG(INFO) << "Leaving shutdown mode";
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100719 shutting_down = false;
Tom Cherry802864c2020-03-12 14:29:25 -0700720 StartSendingMessages();
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100721}
722
Nikita Ioffeab91ee92019-11-06 21:40:31 +0000723static Result<void> UnmountAllApexes() {
724 const char* args[] = {"/system/bin/apexd", "--unmount-all"};
725 int status;
726 if (logwrap_fork_execvp(arraysize(args), args, &status, false, LOG_KLOG, true, nullptr) != 0) {
727 return ErrnoError() << "Failed to call '/system/bin/apexd --unmount-all'";
728 }
729 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
730 return {};
731 }
732 return Error() << "'/system/bin/apexd --unmount-all' failed : " << status;
733}
734
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100735static Result<void> DoUserspaceReboot() {
736 LOG(INFO) << "Userspace reboot initiated";
737 auto guard = android::base::make_scope_guard([] {
738 // Leave shutdown so that we can handle a full reboot.
739 LeaveShutdown();
Nikita Ioffe4a787d92020-01-15 23:23:13 +0000740 trigger_shutdown("reboot,userspace_failed,shutdown_aborted");
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100741 });
Nikita Ioffec0df1872019-11-13 21:47:06 +0000742 // Triggering userspace-reboot-requested will result in a bunch of setprop
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100743 // actions. We should make sure, that all of them are propagated before
Nikita Ioffe764c1ac2020-01-27 17:14:46 +0000744 // proceeding with userspace reboot. Synchronously setting sys.init.userspace_reboot.in_progress
745 // property is not perfect, but it should do the trick.
Nikita Ioffe23dbd6d2019-11-14 01:21:24 +0000746 if (!android::sysprop::InitProperties::userspace_reboot_in_progress(true)) {
747 return Error() << "Failed to set sys.init.userspace_reboot.in_progress property";
Nikita Ioffec0df1872019-11-13 21:47:06 +0000748 }
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100749 EnterShutdown();
Nikita Ioffe764c1ac2020-01-27 17:14:46 +0000750 if (!SetProperty("sys.powerctl", "")) {
751 return Error() << "Failed to reset sys.powerctl property";
752 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100753 std::vector<Service*> stop_first;
754 // Remember the services that were enabled. We will need to manually enable them again otherwise
755 // triggers like class_start won't restart them.
756 std::vector<Service*> were_enabled;
757 stop_first.reserve(ServiceList::GetInstance().services().size());
758 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
759 if (s->is_post_data() && !kDebuggingServices.count(s->name())) {
760 stop_first.push_back(s);
761 }
762 if (s->is_post_data() && s->IsEnabled()) {
763 were_enabled.push_back(s);
764 }
765 }
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000766 {
767 Timer sync_timer;
768 LOG(INFO) << "sync() before terminating services...";
769 sync();
770 LOG(INFO) << "sync() took " << sync_timer;
771 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100772 // TODO(b/135984674): do we need shutdown animation for userspace reboot?
773 // TODO(b/135984674): control userspace timeout via read-only property?
774 StopServicesAndLogViolations(stop_first, 10s, true /* SIGTERM */);
775 if (int r = StopServicesAndLogViolations(stop_first, 20s, false /* SIGKILL */); r > 0) {
776 // TODO(b/135984674): store information about offending services for debugging.
777 return Error() << r << " post-data services are still running";
778 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900779 if (auto result = KillZramBackingDevice(); !result.ok()) {
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000780 return result;
781 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900782 if (auto result = CallVdc("volume", "reset"); !result.ok()) {
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000783 return result;
784 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100785 if (int r = StopServicesAndLogViolations(GetDebuggingServices(true /* only_post_data */), 5s,
786 false /* SIGKILL */);
787 r > 0) {
788 // TODO(b/135984674): store information about offending services for debugging.
789 return Error() << r << " debugging services are still running";
790 }
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000791 {
792 Timer sync_timer;
793 LOG(INFO) << "sync() after stopping services...";
794 sync();
795 LOG(INFO) << "sync() took " << sync_timer;
796 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900797 if (auto result = UnmountAllApexes(); !result.ok()) {
Nikita Ioffeab91ee92019-11-06 21:40:31 +0000798 return result;
799 }
800 if (!SwitchToBootstrapMountNamespaceIfNeeded()) {
801 return Error() << "Failed to switch to bootstrap namespace";
802 }
Nikita Ioffe091c4d12019-12-05 12:35:19 +0000803 // Remove services that were defined in an APEX.
804 ServiceList::GetInstance().RemoveServiceIf([](const std::unique_ptr<Service>& s) -> bool {
805 if (s->is_from_apex()) {
806 LOG(INFO) << "Removing service '" << s->name() << "' because it's defined in an APEX";
807 return true;
808 }
809 return false;
810 });
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100811 // Re-enable services
812 for (const auto& s : were_enabled) {
813 LOG(INFO) << "Re-enabling service '" << s->name() << "'";
814 s->Enable();
815 }
Nikita Ioffe3ad29202020-02-27 20:46:27 +0000816 ServiceList::GetInstance().ResetState();
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100817 LeaveShutdown();
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100818 ActionManager::GetInstance().QueueEventTrigger("userspace-reboot-resume");
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100819 guard.Disable(); // Go on with userspace reboot.
820 return {};
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100821}
822
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000823static void UserspaceRebootWatchdogThread() {
Nikita Ioffe57d7bb62019-11-28 18:25:24 +0000824 if (!WaitForProperty("sys.init.userspace_reboot.in_progress", "1", 20s)) {
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000825 // TODO(b/135984674): should we reboot instead?
826 LOG(WARNING) << "Userspace reboot didn't start in 20 seconds. Stopping watchdog";
827 return;
828 }
829 LOG(INFO) << "Starting userspace reboot watchdog";
830 // TODO(b/135984674): this should be configured via a read-only sysprop.
831 std::chrono::milliseconds timeout = 60s;
832 if (!WaitForProperty("sys.boot_completed", "1", timeout)) {
833 LOG(ERROR) << "Failed to boot in " << timeout.count() << "ms. Switching to full reboot";
834 // 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 +0000835 // Since init might be wedged, don't try to write reboot reason into a persistent property.
836 PersistRebootReason("userspace_failed,watchdog_triggered", false);
Nikita Ioffe4a787d92020-01-15 23:23:13 +0000837 RebootSystem(ANDROID_RB_RESTART2, "userspace_failed,watchdog_triggered");
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000838 }
839 LOG(INFO) << "Device booted, stopping userspace reboot watchdog";
840}
841
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100842static void HandleUserspaceReboot() {
Nikita Ioffe018ddd72019-12-20 16:34:48 +0000843 if (!android::sysprop::InitProperties::is_userspace_reboot_supported().value_or(false)) {
Nikita Ioffe9f473c02019-12-18 13:31:42 +0000844 LOG(ERROR) << "Attempted a userspace reboot on a device that doesn't support it";
845 return;
846 }
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000847 // Spinnig up a separate thread will fail the setns call later in the boot sequence.
848 // Fork a new process to monitor userspace reboot while we are investigating a better solution.
849 pid_t pid = fork();
850 if (pid < 0) {
851 PLOG(ERROR) << "Failed to fork process for userspace reboot watchdog. Switching to full "
852 << "reboot";
Nikita Ioffe4a787d92020-01-15 23:23:13 +0000853 trigger_shutdown("reboot,userspace_failed,watchdog_fork");
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000854 return;
855 }
856 if (pid == 0) {
857 // Child
858 UserspaceRebootWatchdogThread();
859 _exit(EXIT_SUCCESS);
860 }
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100861 LOG(INFO) << "Clearing queue and starting userspace-reboot-requested trigger";
862 auto& am = ActionManager::GetInstance();
863 am.ClearQueue();
864 am.QueueEventTrigger("userspace-reboot-requested");
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100865 auto handler = [](const BuiltinArguments&) { return DoUserspaceReboot(); };
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100866 am.QueueBuiltinAction(handler, "userspace-reboot");
867}
868
Sam Protsenko2c7c3c72019-12-26 21:55:08 +0200869/**
870 * Check if "command" field is set in bootloader message.
871 *
872 * If "command" field is broken (contains non-printable characters prior to
873 * terminating zero), it will be zeroed.
874 *
875 * @param[in,out] boot Bootloader message (BCB) structure
876 * @return true if "command" field is already set, and false if it's empty
877 */
878static bool CommandIsPresent(bootloader_message* boot) {
879 if (boot->command[0] == '\0')
880 return false;
881
882 for (size_t i = 0; i < arraysize(boot->command); ++i) {
883 if (boot->command[i] == '\0')
884 return true;
885 if (!isprint(boot->command[i]))
886 break;
887 }
888
889 memset(boot->command, 0, sizeof(boot->command));
890 return false;
891}
892
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100893void HandlePowerctlMessage(const std::string& command) {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700894 unsigned int cmd = 0;
Mark Salyzyn62909822017-10-09 09:27:16 -0700895 std::vector<std::string> cmd_params = Split(command, ",");
Tom Cherry98ad32a2017-04-17 16:34:20 -0700896 std::string reboot_target = "";
897 bool run_fsck = false;
898 bool command_invalid = false;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100899 bool userspace_reboot = false;
Tom Cherry98ad32a2017-04-17 16:34:20 -0700900
Mark Salyzynd7931f12019-07-10 10:33:09 -0700901 if (cmd_params[0] == "shutdown") {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700902 cmd = ANDROID_RB_POWEROFF;
Mark Salyzynd7931f12019-07-10 10:33:09 -0700903 if (cmd_params.size() >= 2) {
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700904 if (cmd_params[1] == "userrequested") {
905 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
906 // Run fsck once the file system is remounted in read-only mode.
907 run_fsck = true;
908 } else if (cmd_params[1] == "thermal") {
Mark Salyzynbfd05b62017-09-26 11:10:12 -0700909 // Turn off sources of heat immediately.
910 TurnOffBacklight();
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700911 // run_fsck is false to avoid delay
912 cmd = ANDROID_RB_THERMOFF;
913 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700914 }
915 } else if (cmd_params[0] == "reboot") {
916 cmd = ANDROID_RB_RESTART2;
917 if (cmd_params.size() >= 2) {
918 reboot_target = cmd_params[1];
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100919 if (reboot_target == "userspace") {
920 LOG(INFO) << "Userspace reboot requested";
921 userspace_reboot = true;
922 }
Hridya Valsaraju54258262018-09-19 21:14:18 -0700923 // adb reboot fastboot should boot into bootloader for devices not
924 // supporting logical partitions.
925 if (reboot_target == "fastboot" &&
Yifan Hong0e0f8182018-11-16 12:49:06 -0800926 !android::base::GetBoolProperty("ro.boot.dynamic_partitions", false)) {
Hridya Valsaraju54258262018-09-19 21:14:18 -0700927 reboot_target = "bootloader";
928 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700929 // When rebooting to the bootloader notify the bootloader writing
930 // also the BCB.
931 if (reboot_target == "bootloader") {
932 std::string err;
933 if (!write_reboot_bootloader(&err)) {
934 LOG(ERROR) << "reboot-bootloader: Error writing "
935 "bootloader_message: "
936 << err;
937 }
Tianjie Xu5e98b632019-07-18 12:48:28 -0700938 } else if (reboot_target == "recovery") {
939 bootloader_message boot = {};
940 if (std::string err; !read_bootloader_message(&boot, &err)) {
941 LOG(ERROR) << "Failed to read bootloader message: " << err;
942 }
943 // Update the boot command field if it's empty, and preserve
944 // the other arguments in the bootloader message.
Sam Protsenko2c7c3c72019-12-26 21:55:08 +0200945 if (!CommandIsPresent(&boot)) {
Tianjie Xu5e98b632019-07-18 12:48:28 -0700946 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
947 if (std::string err; !write_bootloader_message(boot, &err)) {
948 LOG(ERROR) << "Failed to set bootloader message: " << err;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100949 return;
Tianjie Xu5e98b632019-07-18 12:48:28 -0700950 }
951 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700952 } else if (reboot_target == "sideload" || reboot_target == "sideload-auto-reboot" ||
953 reboot_target == "fastboot") {
954 std::string arg = reboot_target == "sideload-auto-reboot" ? "sideload_auto_reboot"
955 : reboot_target;
956 const std::vector<std::string> options = {
957 "--" + arg,
958 };
959 std::string err;
960 if (!write_bootloader_message(options, &err)) {
961 LOG(ERROR) << "Failed to set bootloader message: " << err;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100962 return;
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700963 }
964 reboot_target = "recovery";
Tom Cherry98ad32a2017-04-17 16:34:20 -0700965 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700966
Mark Salyzynd7931f12019-07-10 10:33:09 -0700967 // If there are additional parameter, pass them along
968 for (size_t i = 2; (cmd_params.size() > i) && cmd_params[i].size(); ++i) {
969 reboot_target += "," + cmd_params[i];
Tom Cherry98ad32a2017-04-17 16:34:20 -0700970 }
971 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700972 } else {
973 command_invalid = true;
974 }
975 if (command_invalid) {
976 LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100977 return;
978 }
979
Tom Cherry802864c2020-03-12 14:29:25 -0700980 // We do not want to process any messages (queue'ing triggers, shutdown messages, control
981 // messages, etc) from properties during reboot.
982 StopSendingMessages();
983
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100984 if (userspace_reboot) {
985 HandleUserspaceReboot();
986 return;
Tom Cherry98ad32a2017-04-17 16:34:20 -0700987 }
988
Wei Wangeeab4912017-06-27 22:08:45 -0700989 LOG(INFO) << "Clear action queue and start shutdown trigger";
990 ActionManager::GetInstance().ClearQueue();
991 // Queue shutdown trigger first
992 ActionManager::GetInstance().QueueEventTrigger("shutdown");
993 // Queue built-in shutdown_done
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700994 auto shutdown_handler = [cmd, command, reboot_target, run_fsck](const BuiltinArguments&) {
Wei Wangeeab4912017-06-27 22:08:45 -0700995 DoReboot(cmd, command, reboot_target, run_fsck);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700996 return Result<void>{};
Wei Wangeeab4912017-06-27 22:08:45 -0700997 };
998 ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
999
Nikita Ioffeba6968e2019-10-07 16:26:33 +01001000 EnterShutdown();
1001}
Wei Wangeeab4912017-06-27 22:08:45 -07001002
Nikita Ioffeba6968e2019-10-07 16:26:33 +01001003bool IsShuttingDown() {
1004 return shutting_down;
Tom Cherry98ad32a2017-04-17 16:34:20 -07001005}
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001006
1007} // namespace init
1008} // namespace android