blob: 4a169692b618764fc0224fac65191293ebaad533 [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
Tom Cherryede0d532017-07-06 14:20:11 -070041#include <android-base/chrono_utils.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070042#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070043#include <android-base/logging.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070044#include <android-base/macros.h>
Tom Cherryccf23532017-03-28 16:40:41 -070045#include <android-base/properties.h>
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010046#include <android-base/scopeguard.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070047#include <android-base/strings.h>
Keun-young Park2ba5c812017-03-29 12:54:40 -070048#include <android-base/unique_fd.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070049#include <bootloader_message/bootloader_message.h>
50#include <cutils/android_reboot.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070051#include <fs_mgr.h>
52#include <logwrap/logwrap.h>
Todd Poynorfc827be2017-04-13 15:17:24 -070053#include <private/android_filesystem_config.h>
Tom Cherry0c8d6d22017-08-10 12:22:44 -070054#include <selinux/selinux.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070055
Nikita Ioffeba6968e2019-10-07 16:26:33 +010056#include "action.h"
Tom Cherry7fd3bc22018-02-13 15:36:14 -080057#include "action_manager.h"
Nikita Ioffeba6968e2019-10-07 16:26:33 +010058#include "builtin_arguments.h"
Wei Wangeeab4912017-06-27 22:08:45 -070059#include "init.h"
Nikita Ioffeab91ee92019-11-06 21:40:31 +000060#include "mount_namespace.h"
Keun-young Park7830d592017-03-27 16:07:02 -070061#include "property_service.h"
Tom Cherry44aceed2018-08-03 13:36:18 -070062#include "reboot_utils.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070063#include "service.h"
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070064#include "service_list.h"
Luis Hector Chavez9f97f472017-09-06 13:43:57 -070065#include "sigchld_handler.h"
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010066#include "util.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070067
josephjangaaddf282019-04-16 18:46:24 +080068#define PROC_SYSRQ "/proc/sysrq-trigger"
69
Tom Cherry2436e6b2019-09-19 11:16:19 -070070using namespace std::literals;
71
Tom Cherry4f4cacc2019-01-08 10:39:00 -080072using android::base::GetBoolProperty;
Mark Salyzyn62909822017-10-09 09:27:16 -070073using android::base::Split;
Tom Cherryede0d532017-07-06 14:20:11 -070074using android::base::Timer;
Jaegeuk Kim2aedc822018-11-20 13:27:06 -080075using android::base::unique_fd;
josephjangaaddf282019-04-16 18:46:24 +080076using android::base::WriteStringToFile;
Keun-young Park8d01f632017-03-13 11:54:47 -070077
Tom Cherry81f5d3e2017-06-22 12:53:17 -070078namespace android {
79namespace init {
80
Nikita Ioffeba6968e2019-10-07 16:26:33 +010081static bool shutting_down = false;
82
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010083static const std::set<std::string> kDebuggingServices{"tombstoned", "logd", "adbd", "console"};
84
85static std::vector<Service*> GetDebuggingServices(bool only_post_data) {
86 std::vector<Service*> ret;
87 ret.reserve(kDebuggingServices.size());
88 for (const auto& s : ServiceList::GetInstance()) {
89 if (kDebuggingServices.count(s->name()) && (!only_post_data || s->is_post_data())) {
90 ret.push_back(s.get());
91 }
92 }
93 return ret;
94}
95
Keun-young Park8d01f632017-03-13 11:54:47 -070096// represents umount status during reboot / shutdown.
97enum UmountStat {
98 /* umount succeeded. */
99 UMOUNT_STAT_SUCCESS = 0,
100 /* umount was not run. */
101 UMOUNT_STAT_SKIPPED = 1,
102 /* umount failed with timeout. */
103 UMOUNT_STAT_TIMEOUT = 2,
104 /* could not run due to error */
105 UMOUNT_STAT_ERROR = 3,
106 /* not used by init but reserved for other part to use this to represent the
107 the state where umount status before reboot is not found / available. */
108 UMOUNT_STAT_NOT_AVAILABLE = 4,
109};
110
111// Utility for struct mntent
112class MountEntry {
113 public:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700114 explicit MountEntry(const mntent& entry)
Keun-young Park8d01f632017-03-13 11:54:47 -0700115 : mnt_fsname_(entry.mnt_fsname),
116 mnt_dir_(entry.mnt_dir),
117 mnt_type_(entry.mnt_type),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700118 mnt_opts_(entry.mnt_opts) {}
Keun-young Park8d01f632017-03-13 11:54:47 -0700119
Jaegeuk Kim0f04f722017-09-25 10:55:39 -0700120 bool Umount(bool force) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800121 LOG(INFO) << "Unmounting " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Jaegeuk Kim0f04f722017-09-25 10:55:39 -0700122 int r = umount2(mnt_dir_.c_str(), force ? MNT_FORCE : 0);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700123 if (r == 0) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800124 LOG(INFO) << "Umounted " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700125 return true;
126 } else {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800127 PLOG(WARNING) << "Cannot umount " << mnt_fsname_ << ":" << mnt_dir_ << " opts "
Keun-young Park2ba5c812017-03-29 12:54:40 -0700128 << mnt_opts_;
129 return false;
130 }
131 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700132
Keun-young Park2ba5c812017-03-29 12:54:40 -0700133 void DoFsck() {
134 int st;
135 if (IsF2Fs()) {
136 const char* f2fs_argv[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800137 "/system/bin/fsck.f2fs",
138 "-a",
139 mnt_fsname_.c_str(),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700140 };
Tom Cherry3a803eb2019-09-25 16:23:50 -0700141 logwrap_fork_execvp(arraysize(f2fs_argv), f2fs_argv, &st, false, LOG_KLOG, true,
142 nullptr);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700143 } else if (IsExt4()) {
144 const char* ext4_argv[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800145 "/system/bin/e2fsck",
146 "-y",
147 mnt_fsname_.c_str(),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700148 };
Tom Cherry3a803eb2019-09-25 16:23:50 -0700149 logwrap_fork_execvp(arraysize(ext4_argv), ext4_argv, &st, false, LOG_KLOG, true,
150 nullptr);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700151 }
152 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700153
154 static bool IsBlockDevice(const struct mntent& mntent) {
155 return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
156 }
157
158 static bool IsEmulatedDevice(const struct mntent& mntent) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700159 return android::base::StartsWith(mntent.mnt_fsname, "/data/");
Keun-young Park8d01f632017-03-13 11:54:47 -0700160 }
161
162 private:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700163 bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
164
165 bool IsExt4() const { return mnt_type_ == "ext4"; }
166
Keun-young Park8d01f632017-03-13 11:54:47 -0700167 std::string mnt_fsname_;
168 std::string mnt_dir_;
169 std::string mnt_type_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700170 std::string mnt_opts_;
Keun-young Park8d01f632017-03-13 11:54:47 -0700171};
172
173// Turn off backlight while we are performing power down cleanup activities.
174static void TurnOffBacklight() {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800175 Service* service = ServiceList::GetInstance().FindService("blank_screen");
176 if (service == nullptr) {
177 LOG(WARNING) << "cannot find blank_screen in TurnOffBacklight";
Keun-young Park8d01f632017-03-13 11:54:47 -0700178 return;
179 }
Tom Cherryd9872642018-10-11 10:38:05 -0700180 if (auto result = service->Start(); !result) {
181 LOG(WARNING) << "Could not start blank_screen service: " << result.error();
182 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700183}
184
Nikita Ioffe12a36072019-10-23 20:11:32 +0100185static Result<void> ShutdownVold() {
Keun-young Park8d01f632017-03-13 11:54:47 -0700186 const char* vdc_argv[] = {"/system/bin/vdc", "volume", "shutdown"};
187 int status;
Nikita Ioffe12a36072019-10-23 20:11:32 +0100188 if (logwrap_fork_execvp(arraysize(vdc_argv), vdc_argv, &status, false, LOG_KLOG, true,
189 nullptr) != 0) {
190 return ErrnoError() << "Failed to call 'vdc volume shutdown'";
191 }
192 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
193 return {};
194 }
195 return Error() << "'vdc volume shutdown' failed : " << status;
Keun-young Park8d01f632017-03-13 11:54:47 -0700196}
197
198static void LogShutdownTime(UmountStat stat, Timer* t) {
Tom Cherryede0d532017-07-06 14:20:11 -0700199 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration().count()) << ":"
200 << stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700201}
202
Tom Cherry2436e6b2019-09-19 11:16:19 -0700203static bool IsDataMounted() {
204 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
205 if (fp == nullptr) {
206 PLOG(ERROR) << "Failed to open /proc/mounts";
207 return false;
208 }
209 mntent* mentry;
210 while ((mentry = getmntent(fp.get())) != nullptr) {
211 if (mentry->mnt_dir == "/data"s) {
212 return true;
213 }
214 }
215 return false;
216}
217
218// Find all read+write block devices and emulated devices in /proc/mounts and add them to
219// the correpsponding list.
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100220static bool FindPartitionsToUmount(std::vector<MountEntry>* block_dev_partitions,
221 std::vector<MountEntry>* emulated_partitions, bool dump) {
Tom Cherryf274e782018-10-03 13:13:41 -0700222 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
Keun-young Park8d01f632017-03-13 11:54:47 -0700223 if (fp == nullptr) {
224 PLOG(ERROR) << "Failed to open /proc/mounts";
225 return false;
226 }
227 mntent* mentry;
228 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700229 if (dump) {
230 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
231 << mentry->mnt_opts << " type " << mentry->mnt_type;
232 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
Keun-young Park6e12b382017-07-17 12:20:33 -0700233 std::string mount_dir(mentry->mnt_dir);
234 // These are R/O partitions changed to R/W after adb remount.
235 // Do not umount them as shutdown critical services may rely on them.
Wei Wanga01c27e2017-07-25 10:52:08 -0700236 if (mount_dir != "/" && mount_dir != "/system" && mount_dir != "/vendor" &&
237 mount_dir != "/oem") {
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100238 block_dev_partitions->emplace(block_dev_partitions->begin(), *mentry);
Keun-young Park6e12b382017-07-17 12:20:33 -0700239 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700240 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100241 emulated_partitions->emplace(emulated_partitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700242 }
243 }
244 return true;
245}
246
Jonglin Lee28a2c922019-01-15 16:38:44 -0800247static void DumpUmountDebuggingInfo() {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700248 int status;
249 if (!security_getenforce()) {
250 LOG(INFO) << "Run lsof";
251 const char* lsof_argv[] = {"/system/bin/lsof"};
Tom Cherry3a803eb2019-09-25 16:23:50 -0700252 logwrap_fork_execvp(arraysize(lsof_argv), lsof_argv, &status, false, LOG_KLOG, true,
253 nullptr);
Keun-young Park8d01f632017-03-13 11:54:47 -0700254 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700255 FindPartitionsToUmount(nullptr, nullptr, true);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800256 // dump current CPU stack traces and uninterruptible tasks
josephjangaaddf282019-04-16 18:46:24 +0800257 WriteStringToFile("l", PROC_SYSRQ);
258 WriteStringToFile("w", PROC_SYSRQ);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700259}
260
Tom Cherryede0d532017-07-06 14:20:11 -0700261static UmountStat UmountPartitions(std::chrono::milliseconds timeout) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700262 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700263 /* data partition needs all pending writes to be completed and all emulated partitions
264 * umounted.If the current waiting is not good enough, give
265 * up and leave it to e2fsck after reboot to fix it.
266 */
267 while (true) {
268 std::vector<MountEntry> block_devices;
269 std::vector<MountEntry> emulated_devices;
270 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
271 return UMOUNT_STAT_ERROR;
272 }
273 if (block_devices.size() == 0) {
Wei Wang8c00e422017-08-16 14:01:46 -0700274 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700275 }
Wei Wang8c00e422017-08-16 14:01:46 -0700276 bool unmount_done = true;
277 if (emulated_devices.size() > 0) {
Wei Wang25dc30f2017-10-23 15:32:03 -0700278 for (auto& entry : emulated_devices) {
279 if (!entry.Umount(false)) unmount_done = false;
280 }
Wei Wang8c00e422017-08-16 14:01:46 -0700281 if (unmount_done) {
282 sync();
283 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700284 }
Wei Wang25dc30f2017-10-23 15:32:03 -0700285 for (auto& entry : block_devices) {
286 if (!entry.Umount(timeout == 0ms)) unmount_done = false;
287 }
Wei Wang8c00e422017-08-16 14:01:46 -0700288 if (unmount_done) {
289 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700290 }
Wei Wang8c00e422017-08-16 14:01:46 -0700291 if ((timeout < t.duration())) { // try umount at least once
292 return UMOUNT_STAT_TIMEOUT;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700293 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700294 std::this_thread::sleep_for(100ms);
295 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700296}
297
josephjangaaddf282019-04-16 18:46:24 +0800298static void KillAllProcesses() {
299 WriteStringToFile("i", PROC_SYSRQ);
300}
301
302// Create reboot/shutdwon monitor thread
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100303void RebootMonitorThread(unsigned int cmd, const std::string& reboot_target,
304 sem_t* reboot_semaphore, std::chrono::milliseconds shutdown_timeout,
305 bool* reboot_monitor_run) {
josephjangaaddf282019-04-16 18:46:24 +0800306 unsigned int remaining_shutdown_time = 0;
307
308 // 30 seconds more than the timeout passed to the thread as there is a final Umount pass
309 // after the timeout is reached.
310 constexpr unsigned int shutdown_watchdog_timeout_default = 30;
311 auto shutdown_watchdog_timeout = android::base::GetUintProperty(
312 "ro.build.shutdown.watchdog.timeout", shutdown_watchdog_timeout_default);
313 remaining_shutdown_time = shutdown_watchdog_timeout + shutdown_timeout.count() / 1000;
314
315 while (*reboot_monitor_run == true) {
316 if (TEMP_FAILURE_RETRY(sem_wait(reboot_semaphore)) == -1) {
317 LOG(ERROR) << "sem_wait failed and exit RebootMonitorThread()";
318 return;
319 }
320
321 timespec shutdown_timeout_timespec;
322 if (clock_gettime(CLOCK_MONOTONIC, &shutdown_timeout_timespec) == -1) {
323 LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
324 return;
325 }
326
327 // If there are some remaining shutdown time left from previous round, we use
328 // remaining time here.
329 shutdown_timeout_timespec.tv_sec += remaining_shutdown_time;
330
331 LOG(INFO) << "shutdown_timeout_timespec.tv_sec: " << shutdown_timeout_timespec.tv_sec;
332
333 int sem_return = 0;
334 while ((sem_return = sem_timedwait_monotonic_np(reboot_semaphore,
335 &shutdown_timeout_timespec)) == -1 &&
336 errno == EINTR) {
337 }
338
339 if (sem_return == -1) {
340 LOG(ERROR) << "Reboot thread timed out";
341
342 if (android::base::GetBoolProperty("ro.debuggable", false) == true) {
Tom Cherry2436e6b2019-09-19 11:16:19 -0700343 if (false) {
344 // SEPolicy will block debuggerd from running and this is intentional.
345 // But these lines are left to be enabled during debugging.
346 LOG(INFO) << "Try to dump init process call trace:";
347 const char* vdc_argv[] = {"/system/bin/debuggerd", "-b", "1"};
348 int status;
Tom Cherry3a803eb2019-09-25 16:23:50 -0700349 logwrap_fork_execvp(arraysize(vdc_argv), vdc_argv, &status, false, LOG_KLOG,
350 true, nullptr);
Tom Cherry2436e6b2019-09-19 11:16:19 -0700351 }
josephjangaaddf282019-04-16 18:46:24 +0800352 LOG(INFO) << "Show stack for all active CPU:";
353 WriteStringToFile("l", PROC_SYSRQ);
354
355 LOG(INFO) << "Show tasks that are in disk sleep(uninterruptable sleep), which are "
356 "like "
357 "blocked in mutex or hardware register access:";
358 WriteStringToFile("w", PROC_SYSRQ);
359 }
360
361 // In shutdown case,notify kernel to sync and umount fs to read-only before shutdown.
362 if (cmd == ANDROID_RB_POWEROFF || cmd == ANDROID_RB_THERMOFF) {
363 WriteStringToFile("s", PROC_SYSRQ);
364
365 WriteStringToFile("u", PROC_SYSRQ);
366
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100367 RebootSystem(cmd, reboot_target);
josephjangaaddf282019-04-16 18:46:24 +0800368 }
369
370 LOG(ERROR) << "Trigger crash at last!";
371 WriteStringToFile("c", PROC_SYSRQ);
372 } else {
373 timespec current_time_timespec;
374
375 if (clock_gettime(CLOCK_MONOTONIC, &current_time_timespec) == -1) {
376 LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
377 return;
378 }
379
380 remaining_shutdown_time =
381 shutdown_timeout_timespec.tv_sec - current_time_timespec.tv_sec;
382
383 LOG(INFO) << "remaining_shutdown_time: " << remaining_shutdown_time;
384 }
385 }
386}
Keun-young Park3ee0df92017-03-27 11:21:09 -0700387
Keun-young Park8d01f632017-03-13 11:54:47 -0700388/* Try umounting all emulated file systems R/W block device cfile systems.
389 * This will just try umount and give it up if it fails.
390 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
391 * and necessary check can be done at the next reboot.
392 * For safer shutdown, caller needs to make sure that
393 * all processes / emulated partition for the target fs are all cleaned-up.
394 *
395 * return true when umount was successful. false when timed out.
396 */
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100397static UmountStat TryUmountAndFsck(unsigned int cmd, bool run_fsck,
josephjangaaddf282019-04-16 18:46:24 +0800398 std::chrono::milliseconds timeout, sem_t* reboot_semaphore) {
Keun-young Park3ee0df92017-03-27 11:21:09 -0700399 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700400 std::vector<MountEntry> block_devices;
401 std::vector<MountEntry> emulated_devices;
Keun-young Park8d01f632017-03-13 11:54:47 -0700402
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100403 if (run_fsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700404 return UMOUNT_STAT_ERROR;
405 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700406
Tom Cherryede0d532017-07-06 14:20:11 -0700407 UmountStat stat = UmountPartitions(timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700408 if (stat != UMOUNT_STAT_SUCCESS) {
409 LOG(INFO) << "umount timeout, last resort, kill all and try";
Jonglin Lee28a2c922019-01-15 16:38:44 -0800410 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park3ee0df92017-03-27 11:21:09 -0700411 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700412 // 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 -0700413 UmountStat st = UmountPartitions(0ms);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800414 if ((st != UMOUNT_STAT_SUCCESS) && DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park8d01f632017-03-13 11:54:47 -0700415 }
416
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100417 if (stat == UMOUNT_STAT_SUCCESS && run_fsck) {
josephjangaaddf282019-04-16 18:46:24 +0800418 LOG(INFO) << "Pause reboot monitor thread before fsck";
419 sem_post(reboot_semaphore);
420
Keun-young Park2ba5c812017-03-29 12:54:40 -0700421 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
422 // and should not affect reboot time.
423 for (auto& entry : block_devices) {
424 entry.DoFsck();
425 }
josephjangaaddf282019-04-16 18:46:24 +0800426
427 LOG(INFO) << "Resume reboot monitor thread after fsck";
428 sem_post(reboot_semaphore);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700429 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700430 return stat;
431}
432
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800433// zram is able to use backing device on top of a loopback device.
434// In order to unmount /data successfully, we have to kill the loopback device first
435#define ZRAM_DEVICE "/dev/block/zram0"
436#define ZRAM_RESET "/sys/block/zram0/reset"
437#define ZRAM_BACK_DEV "/sys/block/zram0/backing_dev"
Nikita Ioffe12a36072019-10-23 20:11:32 +0100438static Result<void> KillZramBackingDevice() {
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800439 std::string backing_dev;
Nikita Ioffe12a36072019-10-23 20:11:32 +0100440 if (!android::base::ReadFileToString(ZRAM_BACK_DEV, &backing_dev)) return {};
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800441
Nikita Ioffe12a36072019-10-23 20:11:32 +0100442 if (!android::base::StartsWith(backing_dev, "/dev/block/loop")) return {};
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800443
444 // cut the last "\n"
445 backing_dev.erase(backing_dev.length() - 1);
446
447 // shutdown zram handle
448 Timer swap_timer;
449 LOG(INFO) << "swapoff() start...";
450 if (swapoff(ZRAM_DEVICE) == -1) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100451 return ErrnoError() << "zram_backing_dev: swapoff (" << backing_dev << ")"
452 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800453 }
454 LOG(INFO) << "swapoff() took " << swap_timer;;
455
josephjangaaddf282019-04-16 18:46:24 +0800456 if (!WriteStringToFile("1", ZRAM_RESET)) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100457 return Error() << "zram_backing_dev: reset (" << backing_dev << ")"
458 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800459 }
460
461 // clear loopback device
462 unique_fd loop(TEMP_FAILURE_RETRY(open(backing_dev.c_str(), O_RDWR | O_CLOEXEC)));
463 if (loop.get() < 0) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100464 return ErrnoError() << "zram_backing_dev: open(" << backing_dev << ")"
465 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800466 }
467
468 if (ioctl(loop.get(), LOOP_CLR_FD, 0) < 0) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100469 return ErrnoError() << "zram_backing_dev: loop_clear (" << backing_dev << ")"
470 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800471 }
472 LOG(INFO) << "zram_backing_dev: `" << backing_dev << "` is cleared successfully.";
Nikita Ioffe12a36072019-10-23 20:11:32 +0100473 return {};
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800474}
475
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100476// Stops given services, waits for them to be stopped for |timeout| ms.
477// If terminate is true, then SIGTERM is sent to services, otherwise SIGKILL is sent.
478static void StopServices(const std::vector<Service*>& services, std::chrono::milliseconds timeout,
479 bool terminate) {
480 LOG(INFO) << "Stopping " << services.size() << " services by sending "
481 << (terminate ? "SIGTERM" : "SIGKILL");
482 std::vector<pid_t> pids;
483 pids.reserve(services.size());
484 for (const auto& s : services) {
485 if (s->pid() > 0) {
486 pids.push_back(s->pid());
487 }
488 if (terminate) {
489 s->Terminate();
490 } else {
491 s->Stop();
492 }
493 }
494 if (timeout > 0ms) {
495 WaitToBeReaped(pids, timeout);
496 } else {
497 // Even if we don't to wait for services to stop, we still optimistically reap zombies.
498 ReapAnyOutstandingChildren();
499 }
500}
501
502// Like StopServices, but also logs all the services that failed to stop after the provided timeout.
503// Returns number of violators.
504static int StopServicesAndLogViolations(const std::vector<Service*>& services,
505 std::chrono::milliseconds timeout, bool terminate) {
506 StopServices(services, timeout, terminate);
507 int still_running = 0;
508 for (const auto& s : services) {
509 if (s->IsRunning()) {
510 LOG(ERROR) << "[service-misbehaving] : service '" << s->name() << "' is still running "
511 << timeout.count() << "ms after receiving "
512 << (terminate ? "SIGTERM" : "SIGKILL");
513 still_running++;
514 }
515 }
516 return still_running;
517}
518
Tom Cherry44aceed2018-08-03 13:36:18 -0700519//* Reboot / shutdown the system.
520// cmd ANDROID_RB_* as defined in android_reboot.h
521// reason Reason string like "reboot", "shutdown,userrequested"
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100522// reboot_target Reboot target string like "bootloader". Otherwise, it should be an empty string.
523// run_fsck Whether to run fsck after umount is done.
Tom Cherry44aceed2018-08-03 13:36:18 -0700524//
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100525static void DoReboot(unsigned int cmd, const std::string& reason, const std::string& reboot_target,
526 bool run_fsck) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700527 Timer t;
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100528 LOG(INFO) << "Reboot start, reason: " << reason << ", reboot_target: " << reboot_target;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700529
Tom Cherry2436e6b2019-09-19 11:16:19 -0700530 // If /data isn't mounted then we can skip the extra reboot steps below, since we don't need to
531 // worry about unmounting it.
532 if (!IsDataMounted()) {
533 sync();
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100534 RebootSystem(cmd, reboot_target);
Tom Cherry2436e6b2019-09-19 11:16:19 -0700535 abort();
536 }
537
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700538 // Ensure last reboot reason is reduced to canonical
539 // alias reported in bootloader or system boot reason.
540 size_t skip = 0;
541 std::vector<std::string> reasons = Split(reason, ",");
542 if (reasons.size() >= 2 && reasons[0] == "reboot" &&
543 (reasons[1] == "recovery" || reasons[1] == "bootloader" || reasons[1] == "cold" ||
544 reasons[1] == "hard" || reasons[1] == "warm")) {
545 skip = strlen("reboot,");
546 }
547 property_set(LAST_REBOOT_REASON_PROPERTY, reason.c_str() + skip);
548 sync();
549
550 bool is_thermal_shutdown = cmd == ANDROID_RB_THERMOFF;
551
552 auto shutdown_timeout = 0ms;
553 if (!SHUTDOWN_ZERO_TIMEOUT) {
Wei Wangb5de0882018-10-09 12:42:06 -0700554 constexpr unsigned int shutdown_timeout_default = 6;
555 constexpr unsigned int max_thermal_shutdown_timeout = 3;
556 auto shutdown_timeout_final = android::base::GetUintProperty("ro.build.shutdown_timeout",
557 shutdown_timeout_default);
558 if (is_thermal_shutdown && shutdown_timeout_final > max_thermal_shutdown_timeout) {
559 shutdown_timeout_final = max_thermal_shutdown_timeout;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700560 }
Wei Wangb5de0882018-10-09 12:42:06 -0700561 shutdown_timeout = std::chrono::seconds(shutdown_timeout_final);
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700562 }
563 LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " ms";
564
josephjangaaddf282019-04-16 18:46:24 +0800565 sem_t reboot_semaphore;
566 if (sem_init(&reboot_semaphore, false, 0) == -1) {
567 // These should never fail, but if they do, skip the graceful reboot and reboot immediately.
568 LOG(ERROR) << "sem_init() fail and RebootSystem() return!";
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100569 RebootSystem(cmd, reboot_target);
josephjangaaddf282019-04-16 18:46:24 +0800570 }
571
572 // Start a thread to monitor init shutdown process
573 LOG(INFO) << "Create reboot monitor thread.";
574 bool reboot_monitor_run = true;
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100575 std::thread reboot_monitor_thread(&RebootMonitorThread, cmd, reboot_target, &reboot_semaphore,
josephjangaaddf282019-04-16 18:46:24 +0800576 shutdown_timeout, &reboot_monitor_run);
577 reboot_monitor_thread.detach();
578
579 // Start reboot monitor thread
580 sem_post(&reboot_semaphore);
581
Keun-young Park7830d592017-03-27 16:07:02 -0700582 // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700583 const std::set<std::string> to_starts{"watchdogd"};
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100584 std::vector<Service*> stop_first;
585 stop_first.reserve(ServiceList::GetInstance().services().size());
Tom Cherry911b9b12017-07-27 16:20:58 -0700586 for (const auto& s : ServiceList::GetInstance()) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100587 if (kDebuggingServices.count(s->name())) {
588 // keep debugging tools until non critical ones are all gone.
Keun-young Park7830d592017-03-27 16:07:02 -0700589 s->SetShutdownCritical();
590 } else if (to_starts.count(s->name())) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700591 if (auto result = s->Start(); !result) {
592 LOG(ERROR) << "Could not start shutdown 'to_start' service '" << s->name()
593 << "': " << result.error();
594 }
Keun-young Park7830d592017-03-27 16:07:02 -0700595 s->SetShutdownCritical();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700596 } else if (s->IsShutdownCritical()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700597 // Start shutdown critical service if not started.
598 if (auto result = s->Start(); !result) {
599 LOG(ERROR) << "Could not start shutdown critical service '" << s->name()
600 << "': " << result.error();
601 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100602 } else {
603 stop_first.push_back(s.get());
Keun-young Park8d01f632017-03-13 11:54:47 -0700604 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700605 }
Keun-young Park7830d592017-03-27 16:07:02 -0700606
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800607 // remaining operations (specifically fsck) may take a substantial duration
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700608 if (cmd == ANDROID_RB_POWEROFF || is_thermal_shutdown) {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800609 TurnOffBacklight();
610 }
611
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100612 Service* boot_anim = ServiceList::GetInstance().FindService("bootanim");
613 Service* surface_flinger = ServiceList::GetInstance().FindService("surfaceflinger");
614 if (boot_anim != nullptr && surface_flinger != nullptr && surface_flinger->IsRunning()) {
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800615 bool do_shutdown_animation = GetBoolProperty("ro.init.shutdown_animation", false);
616
617 if (do_shutdown_animation) {
618 property_set("service.bootanim.exit", "0");
619 // Could be in the middle of animation. Stop and start so that it can pick
620 // up the right mode.
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100621 boot_anim->Stop();
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800622 }
623
Tom Cherry911b9b12017-07-27 16:20:58 -0700624 for (const auto& service : ServiceList::GetInstance()) {
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800625 if (service->classnames().count("animation") == 0) {
626 continue;
627 }
628
629 // start all animation classes if stopped.
630 if (do_shutdown_animation) {
Tom Cherry9949ec52019-05-16 16:54:49 -0700631 service->Start();
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800632 }
633 service->SetShutdownCritical(); // will not check animation class separately
634 }
635
636 if (do_shutdown_animation) {
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100637 boot_anim->Start();
638 surface_flinger->SetShutdownCritical();
639 boot_anim->SetShutdownCritical();
Tom Cherry911b9b12017-07-27 16:20:58 -0700640 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700641 }
Keun-young Park7830d592017-03-27 16:07:02 -0700642
Keun-young Park8d01f632017-03-13 11:54:47 -0700643 // optional shutdown step
644 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Keun-young Park30173872017-07-18 10:58:28 -0700645 if (shutdown_timeout > 0ms) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100646 StopServicesAndLogViolations(stop_first, shutdown_timeout / 2, true /* SIGTERM */);
Keun-young Park8d01f632017-03-13 11:54:47 -0700647 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100648 // Send SIGKILL to ones that didn't terminate cleanly.
649 StopServicesAndLogViolations(stop_first, 0ms, false /* SIGKILL */);
Luis Hector Chavez92c49bc2018-07-27 11:19:25 -0700650 SubcontextTerminate();
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100651 // Reap subcontext pids.
Tom Cherryeeee8312017-07-28 15:22:23 -0700652 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700653
654 // 3. send volume shutdown to vold
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100655 Service* vold_service = ServiceList::GetInstance().FindService("vold");
656 if (vold_service != nullptr && vold_service->IsRunning()) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700657 ShutdownVold();
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100658 vold_service->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700659 } else {
660 LOG(INFO) << "vold not running, skipping vold shutdown";
661 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700662 // logcat stopped here
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100663 StopServices(GetDebuggingServices(false /* only_post_data */), 0ms, false /* SIGKILL */);
Keun-young Park8d01f632017-03-13 11:54:47 -0700664 // 4. sync, try umount, and optionally run fsck for user shutdown
Tom Cherry1f9d5402018-03-15 10:22:40 -0700665 {
666 Timer sync_timer;
667 LOG(INFO) << "sync() before umount...";
668 sync();
669 LOG(INFO) << "sync() before umount took" << sync_timer;
670 }
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800671 // 5. drop caches and disable zram backing device, if exist
672 KillZramBackingDevice();
673
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100674 UmountStat stat =
675 TryUmountAndFsck(cmd, run_fsck, shutdown_timeout - t.duration(), &reboot_semaphore);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700676 // Follow what linux shutdown is doing: one more sync with little bit delay
Tom Cherry1f9d5402018-03-15 10:22:40 -0700677 {
678 Timer sync_timer;
679 LOG(INFO) << "sync() after umount...";
680 sync();
681 LOG(INFO) << "sync() after umount took" << sync_timer;
682 }
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700683 if (!is_thermal_shutdown) std::this_thread::sleep_for(100ms);
Keun-young Park8d01f632017-03-13 11:54:47 -0700684 LogShutdownTime(stat, &t);
josephjangaaddf282019-04-16 18:46:24 +0800685
686 // Send signal to terminate reboot monitor thread.
687 reboot_monitor_run = false;
688 sem_post(&reboot_semaphore);
689
Keun-young Park8d01f632017-03-13 11:54:47 -0700690 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
Nikita Ioffee7ec8c82019-10-24 23:18:39 +0100691 RebootSystem(cmd, reboot_target);
Keun-young Park8d01f632017-03-13 11:54:47 -0700692 abort();
693}
Tom Cherry98ad32a2017-04-17 16:34:20 -0700694
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100695static void EnterShutdown() {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100696 LOG(INFO) << "Entering shutdown mode";
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100697 shutting_down = true;
698 // Skip wait for prop if it is in progress
699 ResetWaitForProp();
700 // Clear EXEC flag if there is one pending
701 for (const auto& s : ServiceList::GetInstance()) {
702 s->UnSetExec();
703 }
704 // We no longer process messages about properties changing coming from property service, so we
705 // need to tell property service to stop sending us these messages, otherwise it'll fill the
706 // buffers and block indefinitely, causing future property sets, including those that init makes
707 // during shutdown in Service::NotifyStateChange() to also block indefinitely.
708 SendStopSendingMessagesMessage();
709}
710
711static void LeaveShutdown() {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100712 LOG(INFO) << "Leaving shutdown mode";
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100713 shutting_down = false;
714 SendStartSendingMessagesMessage();
715}
716
Nikita Ioffeab91ee92019-11-06 21:40:31 +0000717static Result<void> UnmountAllApexes() {
718 const char* args[] = {"/system/bin/apexd", "--unmount-all"};
719 int status;
720 if (logwrap_fork_execvp(arraysize(args), args, &status, false, LOG_KLOG, true, nullptr) != 0) {
721 return ErrnoError() << "Failed to call '/system/bin/apexd --unmount-all'";
722 }
723 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
724 return {};
725 }
726 return Error() << "'/system/bin/apexd --unmount-all' failed : " << status;
727}
728
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100729static Result<void> DoUserspaceReboot() {
730 LOG(INFO) << "Userspace reboot initiated";
731 auto guard = android::base::make_scope_guard([] {
732 // Leave shutdown so that we can handle a full reboot.
733 LeaveShutdown();
Tom Cherry0dbfea72019-10-11 13:18:44 -0700734 TriggerShutdown("reboot,abort-userspace-reboot");
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100735 });
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100736 // Triggering userspace-reboot-requested will result in a bunch of set_prop
737 // actions. We should make sure, that all of them are propagated before
738 // proceeding with userspace reboot.
739 // TODO(b/135984674): implement proper synchronization logic.
740 std::this_thread::sleep_for(500ms);
741 EnterShutdown();
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100742 std::vector<Service*> stop_first;
743 // Remember the services that were enabled. We will need to manually enable them again otherwise
744 // triggers like class_start won't restart them.
745 std::vector<Service*> were_enabled;
746 stop_first.reserve(ServiceList::GetInstance().services().size());
747 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
748 if (s->is_post_data() && !kDebuggingServices.count(s->name())) {
749 stop_first.push_back(s);
750 }
751 if (s->is_post_data() && s->IsEnabled()) {
752 were_enabled.push_back(s);
753 }
754 }
755 // TODO(b/135984674): do we need shutdown animation for userspace reboot?
756 // TODO(b/135984674): control userspace timeout via read-only property?
757 StopServicesAndLogViolations(stop_first, 10s, true /* SIGTERM */);
758 if (int r = StopServicesAndLogViolations(stop_first, 20s, false /* SIGKILL */); r > 0) {
759 // TODO(b/135984674): store information about offending services for debugging.
760 return Error() << r << " post-data services are still running";
761 }
Nikita Ioffe42697d32019-11-05 23:04:17 +0000762 // TODO(b/143970043): in case of ext4 we probably we will need to restart vold and kill zram
763 // backing device.
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100764 if (int r = StopServicesAndLogViolations(GetDebuggingServices(true /* only_post_data */), 5s,
765 false /* SIGKILL */);
766 r > 0) {
767 // TODO(b/135984674): store information about offending services for debugging.
768 return Error() << r << " debugging services are still running";
769 }
Nikita Ioffeab91ee92019-11-06 21:40:31 +0000770 if (auto result = UnmountAllApexes(); !result) {
771 return result;
772 }
773 if (!SwitchToBootstrapMountNamespaceIfNeeded()) {
774 return Error() << "Failed to switch to bootstrap namespace";
775 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100776 // Re-enable services
777 for (const auto& s : were_enabled) {
778 LOG(INFO) << "Re-enabling service '" << s->name() << "'";
779 s->Enable();
780 }
781 LeaveShutdown();
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100782 ActionManager::GetInstance().QueueEventTrigger("userspace-reboot-resume");
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100783 guard.Disable(); // Go on with userspace reboot.
784 return {};
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100785}
786
787static void HandleUserspaceReboot() {
788 LOG(INFO) << "Clearing queue and starting userspace-reboot-requested trigger";
789 auto& am = ActionManager::GetInstance();
790 am.ClearQueue();
791 am.QueueEventTrigger("userspace-reboot-requested");
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100792 auto handler = [](const BuiltinArguments&) { return DoUserspaceReboot(); };
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100793 am.QueueBuiltinAction(handler, "userspace-reboot");
794}
795
796void HandlePowerctlMessage(const std::string& command) {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700797 unsigned int cmd = 0;
Mark Salyzyn62909822017-10-09 09:27:16 -0700798 std::vector<std::string> cmd_params = Split(command, ",");
Tom Cherry98ad32a2017-04-17 16:34:20 -0700799 std::string reboot_target = "";
800 bool run_fsck = false;
801 bool command_invalid = false;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100802 bool userspace_reboot = false;
Tom Cherry98ad32a2017-04-17 16:34:20 -0700803
Mark Salyzynd7931f12019-07-10 10:33:09 -0700804 if (cmd_params[0] == "shutdown") {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700805 cmd = ANDROID_RB_POWEROFF;
Mark Salyzynd7931f12019-07-10 10:33:09 -0700806 if (cmd_params.size() >= 2) {
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700807 if (cmd_params[1] == "userrequested") {
808 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
809 // Run fsck once the file system is remounted in read-only mode.
810 run_fsck = true;
811 } else if (cmd_params[1] == "thermal") {
Mark Salyzynbfd05b62017-09-26 11:10:12 -0700812 // Turn off sources of heat immediately.
813 TurnOffBacklight();
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700814 // run_fsck is false to avoid delay
815 cmd = ANDROID_RB_THERMOFF;
816 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700817 }
818 } else if (cmd_params[0] == "reboot") {
819 cmd = ANDROID_RB_RESTART2;
820 if (cmd_params.size() >= 2) {
821 reboot_target = cmd_params[1];
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100822 if (reboot_target == "userspace") {
823 LOG(INFO) << "Userspace reboot requested";
824 userspace_reboot = true;
825 }
Hridya Valsaraju54258262018-09-19 21:14:18 -0700826 // adb reboot fastboot should boot into bootloader for devices not
827 // supporting logical partitions.
828 if (reboot_target == "fastboot" &&
Yifan Hong0e0f8182018-11-16 12:49:06 -0800829 !android::base::GetBoolProperty("ro.boot.dynamic_partitions", false)) {
Hridya Valsaraju54258262018-09-19 21:14:18 -0700830 reboot_target = "bootloader";
831 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700832 // When rebooting to the bootloader notify the bootloader writing
833 // also the BCB.
834 if (reboot_target == "bootloader") {
835 std::string err;
836 if (!write_reboot_bootloader(&err)) {
837 LOG(ERROR) << "reboot-bootloader: Error writing "
838 "bootloader_message: "
839 << err;
840 }
Tianjie Xu5e98b632019-07-18 12:48:28 -0700841 } else if (reboot_target == "recovery") {
842 bootloader_message boot = {};
843 if (std::string err; !read_bootloader_message(&boot, &err)) {
844 LOG(ERROR) << "Failed to read bootloader message: " << err;
845 }
846 // Update the boot command field if it's empty, and preserve
847 // the other arguments in the bootloader message.
848 if (boot.command[0] == '\0') {
849 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
850 if (std::string err; !write_bootloader_message(boot, &err)) {
851 LOG(ERROR) << "Failed to set bootloader message: " << err;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100852 return;
Tianjie Xu5e98b632019-07-18 12:48:28 -0700853 }
854 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700855 } else if (reboot_target == "sideload" || reboot_target == "sideload-auto-reboot" ||
856 reboot_target == "fastboot") {
857 std::string arg = reboot_target == "sideload-auto-reboot" ? "sideload_auto_reboot"
858 : reboot_target;
859 const std::vector<std::string> options = {
860 "--" + arg,
861 };
862 std::string err;
863 if (!write_bootloader_message(options, &err)) {
864 LOG(ERROR) << "Failed to set bootloader message: " << err;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100865 return;
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700866 }
867 reboot_target = "recovery";
Tom Cherry98ad32a2017-04-17 16:34:20 -0700868 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700869
Mark Salyzynd7931f12019-07-10 10:33:09 -0700870 // If there are additional parameter, pass them along
871 for (size_t i = 2; (cmd_params.size() > i) && cmd_params[i].size(); ++i) {
872 reboot_target += "," + cmd_params[i];
Tom Cherry98ad32a2017-04-17 16:34:20 -0700873 }
874 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700875 } else {
876 command_invalid = true;
877 }
878 if (command_invalid) {
879 LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100880 return;
881 }
882
883 if (userspace_reboot) {
884 HandleUserspaceReboot();
885 return;
Tom Cherry98ad32a2017-04-17 16:34:20 -0700886 }
887
Wei Wangeeab4912017-06-27 22:08:45 -0700888 LOG(INFO) << "Clear action queue and start shutdown trigger";
889 ActionManager::GetInstance().ClearQueue();
890 // Queue shutdown trigger first
891 ActionManager::GetInstance().QueueEventTrigger("shutdown");
892 // Queue built-in shutdown_done
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700893 auto shutdown_handler = [cmd, command, reboot_target, run_fsck](const BuiltinArguments&) {
Wei Wangeeab4912017-06-27 22:08:45 -0700894 DoReboot(cmd, command, reboot_target, run_fsck);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700895 return Result<void>{};
Wei Wangeeab4912017-06-27 22:08:45 -0700896 };
897 ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
898
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100899 EnterShutdown();
900}
Wei Wangeeab4912017-06-27 22:08:45 -0700901
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100902bool IsShuttingDown() {
903 return shutting_down;
Tom Cherry98ad32a2017-04-17 16:34:20 -0700904}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700905
906} // namespace init
907} // namespace android