blob: 081f6953aaa31709e0b55b957dde5cb46ca462fe [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 }
Nikita Ioffed0bc0b62020-02-19 16:21:11 +0000105 WriteStringToFile(reason, LAST_REBOOT_REASON_FILE);
106}
107
Keun-young Park8d01f632017-03-13 11:54:47 -0700108// represents umount status during reboot / shutdown.
109enum UmountStat {
110 /* umount succeeded. */
111 UMOUNT_STAT_SUCCESS = 0,
112 /* umount was not run. */
113 UMOUNT_STAT_SKIPPED = 1,
114 /* umount failed with timeout. */
115 UMOUNT_STAT_TIMEOUT = 2,
116 /* could not run due to error */
117 UMOUNT_STAT_ERROR = 3,
118 /* not used by init but reserved for other part to use this to represent the
119 the state where umount status before reboot is not found / available. */
120 UMOUNT_STAT_NOT_AVAILABLE = 4,
121};
122
123// Utility for struct mntent
124class MountEntry {
125 public:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700126 explicit MountEntry(const mntent& entry)
Keun-young Park8d01f632017-03-13 11:54:47 -0700127 : mnt_fsname_(entry.mnt_fsname),
128 mnt_dir_(entry.mnt_dir),
129 mnt_type_(entry.mnt_type),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700130 mnt_opts_(entry.mnt_opts) {}
Keun-young Park8d01f632017-03-13 11:54:47 -0700131
Jaegeuk Kim0f04f722017-09-25 10:55:39 -0700132 bool Umount(bool force) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800133 LOG(INFO) << "Unmounting " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Jaegeuk Kim0f04f722017-09-25 10:55:39 -0700134 int r = umount2(mnt_dir_.c_str(), force ? MNT_FORCE : 0);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700135 if (r == 0) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800136 LOG(INFO) << "Umounted " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700137 return true;
138 } else {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800139 PLOG(WARNING) << "Cannot umount " << mnt_fsname_ << ":" << mnt_dir_ << " opts "
Keun-young Park2ba5c812017-03-29 12:54:40 -0700140 << mnt_opts_;
141 return false;
142 }
143 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700144
Keun-young Park2ba5c812017-03-29 12:54:40 -0700145 void DoFsck() {
146 int st;
147 if (IsF2Fs()) {
148 const char* f2fs_argv[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800149 "/system/bin/fsck.f2fs",
150 "-a",
151 mnt_fsname_.c_str(),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700152 };
Tom Cherry3a803eb2019-09-25 16:23:50 -0700153 logwrap_fork_execvp(arraysize(f2fs_argv), f2fs_argv, &st, false, LOG_KLOG, true,
154 nullptr);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700155 } else if (IsExt4()) {
156 const char* ext4_argv[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800157 "/system/bin/e2fsck",
158 "-y",
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(ext4_argv), ext4_argv, &st, false, LOG_KLOG, true,
162 nullptr);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700163 }
164 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700165
166 static bool IsBlockDevice(const struct mntent& mntent) {
167 return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
168 }
169
170 static bool IsEmulatedDevice(const struct mntent& mntent) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700171 return android::base::StartsWith(mntent.mnt_fsname, "/data/");
Keun-young Park8d01f632017-03-13 11:54:47 -0700172 }
173
174 private:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700175 bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
176
177 bool IsExt4() const { return mnt_type_ == "ext4"; }
178
Keun-young Park8d01f632017-03-13 11:54:47 -0700179 std::string mnt_fsname_;
180 std::string mnt_dir_;
181 std::string mnt_type_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700182 std::string mnt_opts_;
Keun-young Park8d01f632017-03-13 11:54:47 -0700183};
184
185// Turn off backlight while we are performing power down cleanup activities.
Tom Cherry832f9f12020-03-10 11:47:24 -0700186static void TurnOffBacklight() {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800187 Service* service = ServiceList::GetInstance().FindService("blank_screen");
188 if (service == nullptr) {
189 LOG(WARNING) << "cannot find blank_screen in TurnOffBacklight";
Keun-young Park8d01f632017-03-13 11:54:47 -0700190 return;
191 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900192 if (auto result = service->Start(); !result.ok()) {
Tom Cherryd9872642018-10-11 10:38:05 -0700193 LOG(WARNING) << "Could not start blank_screen service: " << result.error();
194 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700195}
196
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000197static Result<void> CallVdc(const std::string& system, const std::string& cmd) {
198 const char* vdc_argv[] = {"/system/bin/vdc", system.c_str(), cmd.c_str()};
Keun-young Park8d01f632017-03-13 11:54:47 -0700199 int status;
Nikita Ioffe12a36072019-10-23 20:11:32 +0100200 if (logwrap_fork_execvp(arraysize(vdc_argv), vdc_argv, &status, false, LOG_KLOG, true,
201 nullptr) != 0) {
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000202 return ErrnoError() << "Failed to call '/system/bin/vdc " << system << " " << cmd << "'";
Nikita Ioffe12a36072019-10-23 20:11:32 +0100203 }
204 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
205 return {};
206 }
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000207 return Error() << "'/system/bin/vdc " << system << " " << cmd << "' failed : " << status;
Keun-young Park8d01f632017-03-13 11:54:47 -0700208}
209
210static void LogShutdownTime(UmountStat stat, Timer* t) {
Tom Cherryede0d532017-07-06 14:20:11 -0700211 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration().count()) << ":"
212 << stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700213}
214
Tom Cherry2436e6b2019-09-19 11:16:19 -0700215static bool IsDataMounted() {
216 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
217 if (fp == nullptr) {
218 PLOG(ERROR) << "Failed to open /proc/mounts";
219 return false;
220 }
221 mntent* mentry;
222 while ((mentry = getmntent(fp.get())) != nullptr) {
223 if (mentry->mnt_dir == "/data"s) {
224 return true;
225 }
226 }
227 return false;
228}
229
230// Find all read+write block devices and emulated devices in /proc/mounts and add them to
231// the correpsponding list.
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100232static bool FindPartitionsToUmount(std::vector<MountEntry>* block_dev_partitions,
233 std::vector<MountEntry>* emulated_partitions, bool dump) {
Tom Cherryf274e782018-10-03 13:13:41 -0700234 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
Keun-young Park8d01f632017-03-13 11:54:47 -0700235 if (fp == nullptr) {
236 PLOG(ERROR) << "Failed to open /proc/mounts";
237 return false;
238 }
239 mntent* mentry;
240 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700241 if (dump) {
242 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
243 << mentry->mnt_opts << " type " << mentry->mnt_type;
244 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
Keun-young Park6e12b382017-07-17 12:20:33 -0700245 std::string mount_dir(mentry->mnt_dir);
246 // These are R/O partitions changed to R/W after adb remount.
247 // Do not umount them as shutdown critical services may rely on them.
Wei Wanga01c27e2017-07-25 10:52:08 -0700248 if (mount_dir != "/" && mount_dir != "/system" && mount_dir != "/vendor" &&
249 mount_dir != "/oem") {
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100250 block_dev_partitions->emplace(block_dev_partitions->begin(), *mentry);
Keun-young Park6e12b382017-07-17 12:20:33 -0700251 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700252 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100253 emulated_partitions->emplace(emulated_partitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700254 }
255 }
256 return true;
257}
258
Jonglin Lee28a2c922019-01-15 16:38:44 -0800259static void DumpUmountDebuggingInfo() {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700260 int status;
261 if (!security_getenforce()) {
262 LOG(INFO) << "Run lsof";
263 const char* lsof_argv[] = {"/system/bin/lsof"};
Tom Cherry3a803eb2019-09-25 16:23:50 -0700264 logwrap_fork_execvp(arraysize(lsof_argv), lsof_argv, &status, false, LOG_KLOG, true,
265 nullptr);
Keun-young Park8d01f632017-03-13 11:54:47 -0700266 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700267 FindPartitionsToUmount(nullptr, nullptr, true);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800268 // dump current CPU stack traces and uninterruptible tasks
josephjangaaddf282019-04-16 18:46:24 +0800269 WriteStringToFile("l", PROC_SYSRQ);
270 WriteStringToFile("w", PROC_SYSRQ);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700271}
272
Tom Cherryede0d532017-07-06 14:20:11 -0700273static UmountStat UmountPartitions(std::chrono::milliseconds timeout) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700274 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700275 /* data partition needs all pending writes to be completed and all emulated partitions
276 * umounted.If the current waiting is not good enough, give
277 * up and leave it to e2fsck after reboot to fix it.
278 */
279 while (true) {
280 std::vector<MountEntry> block_devices;
281 std::vector<MountEntry> emulated_devices;
282 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
283 return UMOUNT_STAT_ERROR;
284 }
285 if (block_devices.size() == 0) {
Wei Wang8c00e422017-08-16 14:01:46 -0700286 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700287 }
Wei Wang8c00e422017-08-16 14:01:46 -0700288 bool unmount_done = true;
289 if (emulated_devices.size() > 0) {
Wei Wang25dc30f2017-10-23 15:32:03 -0700290 for (auto& entry : emulated_devices) {
291 if (!entry.Umount(false)) unmount_done = false;
292 }
Wei Wang8c00e422017-08-16 14:01:46 -0700293 if (unmount_done) {
294 sync();
295 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700296 }
Wei Wang25dc30f2017-10-23 15:32:03 -0700297 for (auto& entry : block_devices) {
298 if (!entry.Umount(timeout == 0ms)) unmount_done = false;
299 }
Wei Wang8c00e422017-08-16 14:01:46 -0700300 if (unmount_done) {
301 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700302 }
Wei Wang8c00e422017-08-16 14:01:46 -0700303 if ((timeout < t.duration())) { // try umount at least once
304 return UMOUNT_STAT_TIMEOUT;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700305 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700306 std::this_thread::sleep_for(100ms);
307 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700308}
309
josephjangaaddf282019-04-16 18:46:24 +0800310static void KillAllProcesses() {
311 WriteStringToFile("i", PROC_SYSRQ);
312}
313
314// Create reboot/shutdwon monitor thread
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100315void RebootMonitorThread(unsigned int cmd, const std::string& reboot_target,
316 sem_t* reboot_semaphore, std::chrono::milliseconds shutdown_timeout,
317 bool* reboot_monitor_run) {
josephjangaaddf282019-04-16 18:46:24 +0800318 unsigned int remaining_shutdown_time = 0;
319
320 // 30 seconds more than the timeout passed to the thread as there is a final Umount pass
321 // after the timeout is reached.
322 constexpr unsigned int shutdown_watchdog_timeout_default = 30;
323 auto shutdown_watchdog_timeout = android::base::GetUintProperty(
324 "ro.build.shutdown.watchdog.timeout", shutdown_watchdog_timeout_default);
325 remaining_shutdown_time = shutdown_watchdog_timeout + shutdown_timeout.count() / 1000;
326
327 while (*reboot_monitor_run == true) {
328 if (TEMP_FAILURE_RETRY(sem_wait(reboot_semaphore)) == -1) {
329 LOG(ERROR) << "sem_wait failed and exit RebootMonitorThread()";
330 return;
331 }
332
333 timespec shutdown_timeout_timespec;
334 if (clock_gettime(CLOCK_MONOTONIC, &shutdown_timeout_timespec) == -1) {
335 LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
336 return;
337 }
338
339 // If there are some remaining shutdown time left from previous round, we use
340 // remaining time here.
341 shutdown_timeout_timespec.tv_sec += remaining_shutdown_time;
342
343 LOG(INFO) << "shutdown_timeout_timespec.tv_sec: " << shutdown_timeout_timespec.tv_sec;
344
345 int sem_return = 0;
346 while ((sem_return = sem_timedwait_monotonic_np(reboot_semaphore,
347 &shutdown_timeout_timespec)) == -1 &&
348 errno == EINTR) {
349 }
350
351 if (sem_return == -1) {
352 LOG(ERROR) << "Reboot thread timed out";
353
354 if (android::base::GetBoolProperty("ro.debuggable", false) == true) {
Tom Cherry2436e6b2019-09-19 11:16:19 -0700355 if (false) {
356 // SEPolicy will block debuggerd from running and this is intentional.
357 // But these lines are left to be enabled during debugging.
358 LOG(INFO) << "Try to dump init process call trace:";
359 const char* vdc_argv[] = {"/system/bin/debuggerd", "-b", "1"};
360 int status;
Tom Cherry3a803eb2019-09-25 16:23:50 -0700361 logwrap_fork_execvp(arraysize(vdc_argv), vdc_argv, &status, false, LOG_KLOG,
362 true, nullptr);
Tom Cherry2436e6b2019-09-19 11:16:19 -0700363 }
josephjangaaddf282019-04-16 18:46:24 +0800364 LOG(INFO) << "Show stack for all active CPU:";
365 WriteStringToFile("l", PROC_SYSRQ);
366
367 LOG(INFO) << "Show tasks that are in disk sleep(uninterruptable sleep), which are "
368 "like "
369 "blocked in mutex or hardware register access:";
370 WriteStringToFile("w", PROC_SYSRQ);
371 }
372
373 // In shutdown case,notify kernel to sync and umount fs to read-only before shutdown.
374 if (cmd == ANDROID_RB_POWEROFF || cmd == ANDROID_RB_THERMOFF) {
375 WriteStringToFile("s", PROC_SYSRQ);
376
377 WriteStringToFile("u", PROC_SYSRQ);
378
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100379 RebootSystem(cmd, reboot_target);
josephjangaaddf282019-04-16 18:46:24 +0800380 }
381
382 LOG(ERROR) << "Trigger crash at last!";
383 WriteStringToFile("c", PROC_SYSRQ);
384 } else {
385 timespec current_time_timespec;
386
387 if (clock_gettime(CLOCK_MONOTONIC, &current_time_timespec) == -1) {
388 LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
389 return;
390 }
391
392 remaining_shutdown_time =
393 shutdown_timeout_timespec.tv_sec - current_time_timespec.tv_sec;
394
395 LOG(INFO) << "remaining_shutdown_time: " << remaining_shutdown_time;
396 }
397 }
398}
Keun-young Park3ee0df92017-03-27 11:21:09 -0700399
Keun-young Park8d01f632017-03-13 11:54:47 -0700400/* Try umounting all emulated file systems R/W block device cfile systems.
401 * This will just try umount and give it up if it fails.
402 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
403 * and necessary check can be done at the next reboot.
404 * For safer shutdown, caller needs to make sure that
405 * all processes / emulated partition for the target fs are all cleaned-up.
406 *
407 * return true when umount was successful. false when timed out.
408 */
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100409static UmountStat TryUmountAndFsck(unsigned int cmd, bool run_fsck,
josephjangaaddf282019-04-16 18:46:24 +0800410 std::chrono::milliseconds timeout, sem_t* reboot_semaphore) {
Keun-young Park3ee0df92017-03-27 11:21:09 -0700411 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700412 std::vector<MountEntry> block_devices;
413 std::vector<MountEntry> emulated_devices;
Keun-young Park8d01f632017-03-13 11:54:47 -0700414
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100415 if (run_fsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700416 return UMOUNT_STAT_ERROR;
417 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700418
Tom Cherryede0d532017-07-06 14:20:11 -0700419 UmountStat stat = UmountPartitions(timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700420 if (stat != UMOUNT_STAT_SUCCESS) {
421 LOG(INFO) << "umount timeout, last resort, kill all and try";
Jonglin Lee28a2c922019-01-15 16:38:44 -0800422 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park3ee0df92017-03-27 11:21:09 -0700423 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700424 // 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 -0700425 UmountStat st = UmountPartitions(0ms);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800426 if ((st != UMOUNT_STAT_SUCCESS) && DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park8d01f632017-03-13 11:54:47 -0700427 }
428
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100429 if (stat == UMOUNT_STAT_SUCCESS && run_fsck) {
josephjangaaddf282019-04-16 18:46:24 +0800430 LOG(INFO) << "Pause reboot monitor thread before fsck";
431 sem_post(reboot_semaphore);
432
Keun-young Park2ba5c812017-03-29 12:54:40 -0700433 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
434 // and should not affect reboot time.
435 for (auto& entry : block_devices) {
436 entry.DoFsck();
437 }
josephjangaaddf282019-04-16 18:46:24 +0800438
439 LOG(INFO) << "Resume reboot monitor thread after fsck";
440 sem_post(reboot_semaphore);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700441 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700442 return stat;
443}
444
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800445// zram is able to use backing device on top of a loopback device.
446// In order to unmount /data successfully, we have to kill the loopback device first
447#define ZRAM_DEVICE "/dev/block/zram0"
448#define ZRAM_RESET "/sys/block/zram0/reset"
449#define ZRAM_BACK_DEV "/sys/block/zram0/backing_dev"
Nikita Ioffe12a36072019-10-23 20:11:32 +0100450static Result<void> KillZramBackingDevice() {
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800451 std::string backing_dev;
Nikita Ioffe12a36072019-10-23 20:11:32 +0100452 if (!android::base::ReadFileToString(ZRAM_BACK_DEV, &backing_dev)) return {};
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800453
Nikita Ioffe12a36072019-10-23 20:11:32 +0100454 if (!android::base::StartsWith(backing_dev, "/dev/block/loop")) return {};
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800455
456 // cut the last "\n"
457 backing_dev.erase(backing_dev.length() - 1);
458
459 // shutdown zram handle
460 Timer swap_timer;
461 LOG(INFO) << "swapoff() start...";
462 if (swapoff(ZRAM_DEVICE) == -1) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100463 return ErrnoError() << "zram_backing_dev: swapoff (" << backing_dev << ")"
464 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800465 }
466 LOG(INFO) << "swapoff() took " << swap_timer;;
467
josephjangaaddf282019-04-16 18:46:24 +0800468 if (!WriteStringToFile("1", ZRAM_RESET)) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100469 return Error() << "zram_backing_dev: reset (" << backing_dev << ")"
470 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800471 }
472
473 // clear loopback device
474 unique_fd loop(TEMP_FAILURE_RETRY(open(backing_dev.c_str(), O_RDWR | O_CLOEXEC)));
475 if (loop.get() < 0) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100476 return ErrnoError() << "zram_backing_dev: open(" << backing_dev << ")"
477 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800478 }
479
480 if (ioctl(loop.get(), LOOP_CLR_FD, 0) < 0) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100481 return ErrnoError() << "zram_backing_dev: loop_clear (" << backing_dev << ")"
482 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800483 }
484 LOG(INFO) << "zram_backing_dev: `" << backing_dev << "` is cleared successfully.";
Nikita Ioffe12a36072019-10-23 20:11:32 +0100485 return {};
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800486}
487
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100488// Stops given services, waits for them to be stopped for |timeout| ms.
489// If terminate is true, then SIGTERM is sent to services, otherwise SIGKILL is sent.
490static void StopServices(const std::vector<Service*>& services, std::chrono::milliseconds timeout,
491 bool terminate) {
492 LOG(INFO) << "Stopping " << services.size() << " services by sending "
493 << (terminate ? "SIGTERM" : "SIGKILL");
494 std::vector<pid_t> pids;
495 pids.reserve(services.size());
496 for (const auto& s : services) {
497 if (s->pid() > 0) {
498 pids.push_back(s->pid());
499 }
500 if (terminate) {
501 s->Terminate();
502 } else {
503 s->Stop();
504 }
505 }
506 if (timeout > 0ms) {
507 WaitToBeReaped(pids, timeout);
508 } else {
509 // Even if we don't to wait for services to stop, we still optimistically reap zombies.
510 ReapAnyOutstandingChildren();
511 }
512}
513
514// Like StopServices, but also logs all the services that failed to stop after the provided timeout.
515// Returns number of violators.
516static int StopServicesAndLogViolations(const std::vector<Service*>& services,
517 std::chrono::milliseconds timeout, bool terminate) {
518 StopServices(services, timeout, terminate);
519 int still_running = 0;
520 for (const auto& s : services) {
521 if (s->IsRunning()) {
522 LOG(ERROR) << "[service-misbehaving] : service '" << s->name() << "' is still running "
523 << timeout.count() << "ms after receiving "
524 << (terminate ? "SIGTERM" : "SIGKILL");
525 still_running++;
526 }
527 }
528 return still_running;
529}
530
Tom Cherry44aceed2018-08-03 13:36:18 -0700531//* Reboot / shutdown the system.
532// cmd ANDROID_RB_* as defined in android_reboot.h
533// reason Reason string like "reboot", "shutdown,userrequested"
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100534// reboot_target Reboot target string like "bootloader". Otherwise, it should be an empty string.
535// run_fsck Whether to run fsck after umount is done.
Tom Cherry44aceed2018-08-03 13:36:18 -0700536//
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100537static void DoReboot(unsigned int cmd, const std::string& reason, const std::string& reboot_target,
538 bool run_fsck) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700539 Timer t;
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100540 LOG(INFO) << "Reboot start, reason: " << reason << ", reboot_target: " << reboot_target;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700541
542 // Ensure last reboot reason is reduced to canonical
543 // alias reported in bootloader or system boot reason.
544 size_t skip = 0;
545 std::vector<std::string> reasons = Split(reason, ",");
546 if (reasons.size() >= 2 && reasons[0] == "reboot" &&
547 (reasons[1] == "recovery" || reasons[1] == "bootloader" || reasons[1] == "cold" ||
548 reasons[1] == "hard" || reasons[1] == "warm")) {
549 skip = strlen("reboot,");
550 }
Nikita Ioffed485bbb2020-02-26 15:18:56 +0000551 PersistRebootReason(reason.c_str() + skip, true);
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700552 sync();
553
Nikita Ioffed485bbb2020-02-26 15:18:56 +0000554 // If /data isn't mounted then we can skip the extra reboot steps below, since we don't need to
555 // worry about unmounting it.
556 if (!IsDataMounted()) {
557 sync();
558 RebootSystem(cmd, reboot_target);
559 abort();
560 }
561
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700562 bool is_thermal_shutdown = cmd == ANDROID_RB_THERMOFF;
563
564 auto shutdown_timeout = 0ms;
565 if (!SHUTDOWN_ZERO_TIMEOUT) {
Wei Wangb5de0882018-10-09 12:42:06 -0700566 constexpr unsigned int shutdown_timeout_default = 6;
567 constexpr unsigned int max_thermal_shutdown_timeout = 3;
568 auto shutdown_timeout_final = android::base::GetUintProperty("ro.build.shutdown_timeout",
569 shutdown_timeout_default);
570 if (is_thermal_shutdown && shutdown_timeout_final > max_thermal_shutdown_timeout) {
571 shutdown_timeout_final = max_thermal_shutdown_timeout;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700572 }
Wei Wangb5de0882018-10-09 12:42:06 -0700573 shutdown_timeout = std::chrono::seconds(shutdown_timeout_final);
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700574 }
575 LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " ms";
576
josephjangaaddf282019-04-16 18:46:24 +0800577 sem_t reboot_semaphore;
578 if (sem_init(&reboot_semaphore, false, 0) == -1) {
579 // These should never fail, but if they do, skip the graceful reboot and reboot immediately.
580 LOG(ERROR) << "sem_init() fail and RebootSystem() return!";
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100581 RebootSystem(cmd, reboot_target);
josephjangaaddf282019-04-16 18:46:24 +0800582 }
583
584 // Start a thread to monitor init shutdown process
585 LOG(INFO) << "Create reboot monitor thread.";
586 bool reboot_monitor_run = true;
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100587 std::thread reboot_monitor_thread(&RebootMonitorThread, cmd, reboot_target, &reboot_semaphore,
josephjangaaddf282019-04-16 18:46:24 +0800588 shutdown_timeout, &reboot_monitor_run);
589 reboot_monitor_thread.detach();
590
591 // Start reboot monitor thread
592 sem_post(&reboot_semaphore);
593
Keun-young Park7830d592017-03-27 16:07:02 -0700594 // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700595 const std::set<std::string> to_starts{"watchdogd"};
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100596 std::vector<Service*> stop_first;
597 stop_first.reserve(ServiceList::GetInstance().services().size());
Tom Cherry911b9b12017-07-27 16:20:58 -0700598 for (const auto& s : ServiceList::GetInstance()) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100599 if (kDebuggingServices.count(s->name())) {
600 // keep debugging tools until non critical ones are all gone.
Keun-young Park7830d592017-03-27 16:07:02 -0700601 s->SetShutdownCritical();
602 } else if (to_starts.count(s->name())) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900603 if (auto result = s->Start(); !result.ok()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700604 LOG(ERROR) << "Could not start shutdown 'to_start' service '" << s->name()
605 << "': " << result.error();
606 }
Keun-young Park7830d592017-03-27 16:07:02 -0700607 s->SetShutdownCritical();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700608 } else if (s->IsShutdownCritical()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700609 // Start shutdown critical service if not started.
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 critical service '" << s->name()
612 << "': " << result.error();
613 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100614 } else {
615 stop_first.push_back(s.get());
Keun-young Park8d01f632017-03-13 11:54:47 -0700616 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700617 }
Keun-young Park7830d592017-03-27 16:07:02 -0700618
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800619 // remaining operations (specifically fsck) may take a substantial duration
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700620 if (cmd == ANDROID_RB_POWEROFF || is_thermal_shutdown) {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800621 TurnOffBacklight();
622 }
623
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100624 Service* boot_anim = ServiceList::GetInstance().FindService("bootanim");
625 Service* surface_flinger = ServiceList::GetInstance().FindService("surfaceflinger");
626 if (boot_anim != nullptr && surface_flinger != nullptr && surface_flinger->IsRunning()) {
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800627 bool do_shutdown_animation = GetBoolProperty("ro.init.shutdown_animation", false);
628
629 if (do_shutdown_animation) {
Tom Cherryc88d8f92019-08-19 15:21:25 -0700630 SetProperty("service.bootanim.exit", "0");
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800631 // Could be in the middle of animation. Stop and start so that it can pick
632 // up the right mode.
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100633 boot_anim->Stop();
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800634 }
635
Tom Cherry911b9b12017-07-27 16:20:58 -0700636 for (const auto& service : ServiceList::GetInstance()) {
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800637 if (service->classnames().count("animation") == 0) {
638 continue;
639 }
640
641 // start all animation classes if stopped.
642 if (do_shutdown_animation) {
Tom Cherry9949ec52019-05-16 16:54:49 -0700643 service->Start();
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800644 }
645 service->SetShutdownCritical(); // will not check animation class separately
646 }
647
648 if (do_shutdown_animation) {
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100649 boot_anim->Start();
650 surface_flinger->SetShutdownCritical();
651 boot_anim->SetShutdownCritical();
Tom Cherry911b9b12017-07-27 16:20:58 -0700652 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700653 }
Keun-young Park7830d592017-03-27 16:07:02 -0700654
Keun-young Park8d01f632017-03-13 11:54:47 -0700655 // optional shutdown step
656 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Keun-young Park30173872017-07-18 10:58:28 -0700657 if (shutdown_timeout > 0ms) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100658 StopServicesAndLogViolations(stop_first, shutdown_timeout / 2, true /* SIGTERM */);
Keun-young Park8d01f632017-03-13 11:54:47 -0700659 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100660 // Send SIGKILL to ones that didn't terminate cleanly.
661 StopServicesAndLogViolations(stop_first, 0ms, false /* SIGKILL */);
Luis Hector Chavez92c49bc2018-07-27 11:19:25 -0700662 SubcontextTerminate();
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100663 // Reap subcontext pids.
Tom Cherryeeee8312017-07-28 15:22:23 -0700664 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700665
666 // 3. send volume shutdown to vold
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100667 Service* vold_service = ServiceList::GetInstance().FindService("vold");
668 if (vold_service != nullptr && vold_service->IsRunning()) {
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000669 CallVdc("volume", "shutdown");
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100670 vold_service->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700671 } else {
672 LOG(INFO) << "vold not running, skipping vold shutdown";
673 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700674 // logcat stopped here
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100675 StopServices(GetDebuggingServices(false /* only_post_data */), 0ms, false /* SIGKILL */);
Keun-young Park8d01f632017-03-13 11:54:47 -0700676 // 4. sync, try umount, and optionally run fsck for user shutdown
Tom Cherry1f9d5402018-03-15 10:22:40 -0700677 {
678 Timer sync_timer;
679 LOG(INFO) << "sync() before umount...";
680 sync();
681 LOG(INFO) << "sync() before umount took" << sync_timer;
682 }
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800683 // 5. drop caches and disable zram backing device, if exist
684 KillZramBackingDevice();
685
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100686 UmountStat stat =
687 TryUmountAndFsck(cmd, run_fsck, shutdown_timeout - t.duration(), &reboot_semaphore);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700688 // Follow what linux shutdown is doing: one more sync with little bit delay
Tom Cherry1f9d5402018-03-15 10:22:40 -0700689 {
690 Timer sync_timer;
691 LOG(INFO) << "sync() after umount...";
692 sync();
693 LOG(INFO) << "sync() after umount took" << sync_timer;
694 }
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700695 if (!is_thermal_shutdown) std::this_thread::sleep_for(100ms);
Keun-young Park8d01f632017-03-13 11:54:47 -0700696 LogShutdownTime(stat, &t);
josephjangaaddf282019-04-16 18:46:24 +0800697
698 // Send signal to terminate reboot monitor thread.
699 reboot_monitor_run = false;
700 sem_post(&reboot_semaphore);
701
Keun-young Park8d01f632017-03-13 11:54:47 -0700702 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100703 RebootSystem(cmd, reboot_target);
Keun-young Park8d01f632017-03-13 11:54:47 -0700704 abort();
705}
Tom Cherry98ad32a2017-04-17 16:34:20 -0700706
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100707static void EnterShutdown() {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100708 LOG(INFO) << "Entering shutdown mode";
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100709 shutting_down = true;
710 // Skip wait for prop if it is in progress
711 ResetWaitForProp();
712 // Clear EXEC flag if there is one pending
713 for (const auto& s : ServiceList::GetInstance()) {
714 s->UnSetExec();
715 }
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100716}
717
718static void LeaveShutdown() {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100719 LOG(INFO) << "Leaving shutdown mode";
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100720 shutting_down = false;
Tom Cherry802864c2020-03-12 14:29:25 -0700721 StartSendingMessages();
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100722}
723
Nikita Ioffeab91ee92019-11-06 21:40:31 +0000724static Result<void> UnmountAllApexes() {
725 const char* args[] = {"/system/bin/apexd", "--unmount-all"};
726 int status;
727 if (logwrap_fork_execvp(arraysize(args), args, &status, false, LOG_KLOG, true, nullptr) != 0) {
728 return ErrnoError() << "Failed to call '/system/bin/apexd --unmount-all'";
729 }
730 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
731 return {};
732 }
733 return Error() << "'/system/bin/apexd --unmount-all' failed : " << status;
734}
735
Nikita Ioffe7b41a152020-03-25 00:06:51 +0000736static std::chrono::milliseconds GetMillisProperty(const std::string& name,
737 std::chrono::milliseconds default_value) {
738 auto value = GetUintProperty(name, static_cast<uint64_t>(default_value.count()));
739 return std::chrono::milliseconds(std::move(value));
740}
741
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100742static Result<void> DoUserspaceReboot() {
743 LOG(INFO) << "Userspace reboot initiated";
744 auto guard = android::base::make_scope_guard([] {
745 // Leave shutdown so that we can handle a full reboot.
746 LeaveShutdown();
Nikita Ioffe4a787d92020-01-15 23:23:13 +0000747 trigger_shutdown("reboot,userspace_failed,shutdown_aborted");
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100748 });
Nikita Ioffec0df1872019-11-13 21:47:06 +0000749 // Triggering userspace-reboot-requested will result in a bunch of setprop
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100750 // actions. We should make sure, that all of them are propagated before
Nikita Ioffe764c1ac2020-01-27 17:14:46 +0000751 // proceeding with userspace reboot. Synchronously setting sys.init.userspace_reboot.in_progress
752 // property is not perfect, but it should do the trick.
Nikita Ioffe23dbd6d2019-11-14 01:21:24 +0000753 if (!android::sysprop::InitProperties::userspace_reboot_in_progress(true)) {
754 return Error() << "Failed to set sys.init.userspace_reboot.in_progress property";
Nikita Ioffec0df1872019-11-13 21:47:06 +0000755 }
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100756 EnterShutdown();
Nikita Ioffe764c1ac2020-01-27 17:14:46 +0000757 if (!SetProperty("sys.powerctl", "")) {
758 return Error() << "Failed to reset sys.powerctl property";
759 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100760 std::vector<Service*> stop_first;
761 // Remember the services that were enabled. We will need to manually enable them again otherwise
762 // triggers like class_start won't restart them.
763 std::vector<Service*> were_enabled;
764 stop_first.reserve(ServiceList::GetInstance().services().size());
765 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
766 if (s->is_post_data() && !kDebuggingServices.count(s->name())) {
767 stop_first.push_back(s);
768 }
769 if (s->is_post_data() && s->IsEnabled()) {
770 were_enabled.push_back(s);
771 }
772 }
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000773 {
774 Timer sync_timer;
775 LOG(INFO) << "sync() before terminating services...";
776 sync();
777 LOG(INFO) << "sync() took " << sync_timer;
778 }
Nikita Ioffe7b41a152020-03-25 00:06:51 +0000779 auto sigterm_timeout = GetMillisProperty("init.userspace_reboot.sigterm.timeoutmillis", 5s);
780 auto sigkill_timeout = GetMillisProperty("init.userspace_reboot.sigkill.timeoutmillis", 10s);
781 LOG(INFO) << "Timeout to terminate services : " << sigterm_timeout.count() << "ms"
782 << "Timeout to kill services: " << sigkill_timeout.count() << "ms";
783 StopServicesAndLogViolations(stop_first, sigterm_timeout, true /* SIGTERM */);
784 if (int r = StopServicesAndLogViolations(stop_first, sigkill_timeout, false /* SIGKILL */);
785 r > 0) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100786 // TODO(b/135984674): store information about offending services for debugging.
787 return Error() << r << " post-data services are still running";
788 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900789 if (auto result = KillZramBackingDevice(); !result.ok()) {
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000790 return result;
791 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900792 if (auto result = CallVdc("volume", "reset"); !result.ok()) {
Nikita Ioffebee7b8c2019-12-02 11:51:39 +0000793 return result;
794 }
Nikita Ioffe7b41a152020-03-25 00:06:51 +0000795 if (int r = StopServicesAndLogViolations(GetDebuggingServices(true /* only_post_data */),
796 sigkill_timeout, false /* SIGKILL */);
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100797 r > 0) {
798 // TODO(b/135984674): store information about offending services for debugging.
799 return Error() << r << " debugging services are still running";
800 }
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000801 {
802 Timer sync_timer;
803 LOG(INFO) << "sync() after stopping services...";
804 sync();
805 LOG(INFO) << "sync() took " << sync_timer;
806 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900807 if (auto result = UnmountAllApexes(); !result.ok()) {
Nikita Ioffeab91ee92019-11-06 21:40:31 +0000808 return result;
809 }
810 if (!SwitchToBootstrapMountNamespaceIfNeeded()) {
811 return Error() << "Failed to switch to bootstrap namespace";
812 }
Nikita Ioffe091c4d12019-12-05 12:35:19 +0000813 // Remove services that were defined in an APEX.
814 ServiceList::GetInstance().RemoveServiceIf([](const std::unique_ptr<Service>& s) -> bool {
815 if (s->is_from_apex()) {
816 LOG(INFO) << "Removing service '" << s->name() << "' because it's defined in an APEX";
817 return true;
818 }
819 return false;
820 });
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100821 // Re-enable services
822 for (const auto& s : were_enabled) {
823 LOG(INFO) << "Re-enabling service '" << s->name() << "'";
824 s->Enable();
825 }
Nikita Ioffe3ad29202020-02-27 20:46:27 +0000826 ServiceList::GetInstance().ResetState();
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100827 LeaveShutdown();
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100828 ActionManager::GetInstance().QueueEventTrigger("userspace-reboot-resume");
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100829 guard.Disable(); // Go on with userspace reboot.
830 return {};
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100831}
832
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000833static void UserspaceRebootWatchdogThread() {
Nikita Ioffe57d7bb62019-11-28 18:25:24 +0000834 if (!WaitForProperty("sys.init.userspace_reboot.in_progress", "1", 20s)) {
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000835 // TODO(b/135984674): should we reboot instead?
836 LOG(WARNING) << "Userspace reboot didn't start in 20 seconds. Stopping watchdog";
837 return;
838 }
839 LOG(INFO) << "Starting userspace reboot watchdog";
Nikita Ioffe7b41a152020-03-25 00:06:51 +0000840 auto timeout = GetMillisProperty("init.userspace_reboot.watchdog.timeoutmillis", 5min);
841 LOG(INFO) << "UserspaceRebootWatchdog timeout: " << timeout.count() << "ms";
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000842 if (!WaitForProperty("sys.boot_completed", "1", timeout)) {
843 LOG(ERROR) << "Failed to boot in " << timeout.count() << "ms. Switching to full reboot";
844 // 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 +0000845 // Since init might be wedged, don't try to write reboot reason into a persistent property.
846 PersistRebootReason("userspace_failed,watchdog_triggered", false);
Nikita Ioffe4a787d92020-01-15 23:23:13 +0000847 RebootSystem(ANDROID_RB_RESTART2, "userspace_failed,watchdog_triggered");
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000848 }
849 LOG(INFO) << "Device booted, stopping userspace reboot watchdog";
850}
851
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100852static void HandleUserspaceReboot() {
Nikita Ioffe018ddd72019-12-20 16:34:48 +0000853 if (!android::sysprop::InitProperties::is_userspace_reboot_supported().value_or(false)) {
Nikita Ioffe9f473c02019-12-18 13:31:42 +0000854 LOG(ERROR) << "Attempted a userspace reboot on a device that doesn't support it";
855 return;
856 }
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000857 // Spinnig up a separate thread will fail the setns call later in the boot sequence.
858 // Fork a new process to monitor userspace reboot while we are investigating a better solution.
859 pid_t pid = fork();
860 if (pid < 0) {
861 PLOG(ERROR) << "Failed to fork process for userspace reboot watchdog. Switching to full "
862 << "reboot";
Nikita Ioffe4a787d92020-01-15 23:23:13 +0000863 trigger_shutdown("reboot,userspace_failed,watchdog_fork");
Nikita Ioffe82a431e2019-11-07 15:37:38 +0000864 return;
865 }
866 if (pid == 0) {
867 // Child
868 UserspaceRebootWatchdogThread();
869 _exit(EXIT_SUCCESS);
870 }
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100871 LOG(INFO) << "Clearing queue and starting userspace-reboot-requested trigger";
872 auto& am = ActionManager::GetInstance();
873 am.ClearQueue();
874 am.QueueEventTrigger("userspace-reboot-requested");
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100875 auto handler = [](const BuiltinArguments&) { return DoUserspaceReboot(); };
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100876 am.QueueBuiltinAction(handler, "userspace-reboot");
877}
878
Sam Protsenko2c7c3c72019-12-26 21:55:08 +0200879/**
880 * Check if "command" field is set in bootloader message.
881 *
882 * If "command" field is broken (contains non-printable characters prior to
883 * terminating zero), it will be zeroed.
884 *
885 * @param[in,out] boot Bootloader message (BCB) structure
886 * @return true if "command" field is already set, and false if it's empty
887 */
888static bool CommandIsPresent(bootloader_message* boot) {
889 if (boot->command[0] == '\0')
890 return false;
891
892 for (size_t i = 0; i < arraysize(boot->command); ++i) {
893 if (boot->command[i] == '\0')
894 return true;
895 if (!isprint(boot->command[i]))
896 break;
897 }
898
899 memset(boot->command, 0, sizeof(boot->command));
900 return false;
901}
902
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100903void HandlePowerctlMessage(const std::string& command) {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700904 unsigned int cmd = 0;
Mark Salyzyn62909822017-10-09 09:27:16 -0700905 std::vector<std::string> cmd_params = Split(command, ",");
Tom Cherry98ad32a2017-04-17 16:34:20 -0700906 std::string reboot_target = "";
907 bool run_fsck = false;
908 bool command_invalid = false;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100909 bool userspace_reboot = false;
Tom Cherry98ad32a2017-04-17 16:34:20 -0700910
Mark Salyzynd7931f12019-07-10 10:33:09 -0700911 if (cmd_params[0] == "shutdown") {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700912 cmd = ANDROID_RB_POWEROFF;
Mark Salyzynd7931f12019-07-10 10:33:09 -0700913 if (cmd_params.size() >= 2) {
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700914 if (cmd_params[1] == "userrequested") {
915 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
916 // Run fsck once the file system is remounted in read-only mode.
917 run_fsck = true;
918 } else if (cmd_params[1] == "thermal") {
Mark Salyzynbfd05b62017-09-26 11:10:12 -0700919 // Turn off sources of heat immediately.
920 TurnOffBacklight();
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700921 // run_fsck is false to avoid delay
922 cmd = ANDROID_RB_THERMOFF;
923 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700924 }
925 } else if (cmd_params[0] == "reboot") {
926 cmd = ANDROID_RB_RESTART2;
927 if (cmd_params.size() >= 2) {
928 reboot_target = cmd_params[1];
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100929 if (reboot_target == "userspace") {
930 LOG(INFO) << "Userspace reboot requested";
931 userspace_reboot = true;
932 }
Hridya Valsaraju54258262018-09-19 21:14:18 -0700933 // adb reboot fastboot should boot into bootloader for devices not
934 // supporting logical partitions.
935 if (reboot_target == "fastboot" &&
Yifan Hong0e0f8182018-11-16 12:49:06 -0800936 !android::base::GetBoolProperty("ro.boot.dynamic_partitions", false)) {
Hridya Valsaraju54258262018-09-19 21:14:18 -0700937 reboot_target = "bootloader";
938 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700939 // When rebooting to the bootloader notify the bootloader writing
940 // also the BCB.
941 if (reboot_target == "bootloader") {
942 std::string err;
943 if (!write_reboot_bootloader(&err)) {
944 LOG(ERROR) << "reboot-bootloader: Error writing "
945 "bootloader_message: "
946 << err;
947 }
Tianjie Xu5e98b632019-07-18 12:48:28 -0700948 } else if (reboot_target == "recovery") {
949 bootloader_message boot = {};
950 if (std::string err; !read_bootloader_message(&boot, &err)) {
951 LOG(ERROR) << "Failed to read bootloader message: " << err;
952 }
953 // Update the boot command field if it's empty, and preserve
954 // the other arguments in the bootloader message.
Sam Protsenko2c7c3c72019-12-26 21:55:08 +0200955 if (!CommandIsPresent(&boot)) {
Tianjie Xu5e98b632019-07-18 12:48:28 -0700956 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
957 if (std::string err; !write_bootloader_message(boot, &err)) {
958 LOG(ERROR) << "Failed to set bootloader message: " << err;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100959 return;
Tianjie Xu5e98b632019-07-18 12:48:28 -0700960 }
961 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700962 } else if (reboot_target == "sideload" || reboot_target == "sideload-auto-reboot" ||
963 reboot_target == "fastboot") {
964 std::string arg = reboot_target == "sideload-auto-reboot" ? "sideload_auto_reboot"
965 : reboot_target;
966 const std::vector<std::string> options = {
967 "--" + arg,
968 };
969 std::string err;
970 if (!write_bootloader_message(options, &err)) {
971 LOG(ERROR) << "Failed to set bootloader message: " << err;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100972 return;
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700973 }
974 reboot_target = "recovery";
Tom Cherry98ad32a2017-04-17 16:34:20 -0700975 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700976
Mark Salyzynd7931f12019-07-10 10:33:09 -0700977 // If there are additional parameter, pass them along
978 for (size_t i = 2; (cmd_params.size() > i) && cmd_params[i].size(); ++i) {
979 reboot_target += "," + cmd_params[i];
Tom Cherry98ad32a2017-04-17 16:34:20 -0700980 }
981 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700982 } else {
983 command_invalid = true;
984 }
985 if (command_invalid) {
986 LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100987 return;
988 }
989
Tom Cherry802864c2020-03-12 14:29:25 -0700990 // We do not want to process any messages (queue'ing triggers, shutdown messages, control
991 // messages, etc) from properties during reboot.
992 StopSendingMessages();
993
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100994 if (userspace_reboot) {
995 HandleUserspaceReboot();
996 return;
Tom Cherry98ad32a2017-04-17 16:34:20 -0700997 }
998
Wei Wangeeab4912017-06-27 22:08:45 -0700999 LOG(INFO) << "Clear action queue and start shutdown trigger";
1000 ActionManager::GetInstance().ClearQueue();
1001 // Queue shutdown trigger first
1002 ActionManager::GetInstance().QueueEventTrigger("shutdown");
1003 // Queue built-in shutdown_done
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001004 auto shutdown_handler = [cmd, command, reboot_target, run_fsck](const BuiltinArguments&) {
Wei Wangeeab4912017-06-27 22:08:45 -07001005 DoReboot(cmd, command, reboot_target, run_fsck);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001006 return Result<void>{};
Wei Wangeeab4912017-06-27 22:08:45 -07001007 };
1008 ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
1009
Nikita Ioffeba6968e2019-10-07 16:26:33 +01001010 EnterShutdown();
1011}
Wei Wangeeab4912017-06-27 22:08:45 -07001012
Nikita Ioffeba6968e2019-10-07 16:26:33 +01001013bool IsShuttingDown() {
1014 return shutting_down;
Tom Cherry98ad32a2017-04-17 16:34:20 -07001015}
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001016
1017} // namespace init
1018} // namespace android