blob: d6c5b9415f8cbb7efabf506bb33473a92b1c7b93 [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>
Keun-young Park8d01f632017-03-13 11:54:47 -070022#include <mntent.h>
23#include <sys/cdefs.h>
Keun-young Park2ba5c812017-03-29 12:54:40 -070024#include <sys/ioctl.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070025#include <sys/mount.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070026#include <sys/stat.h>
27#include <sys/syscall.h>
28#include <sys/types.h>
29#include <sys/wait.h>
30
31#include <memory>
Keun-young Park7830d592017-03-27 16:07:02 -070032#include <set>
Keun-young Park8d01f632017-03-13 11:54:47 -070033#include <thread>
34#include <vector>
35
Tom Cherryede0d532017-07-06 14:20:11 -070036#include <android-base/chrono_utils.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070037#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070038#include <android-base/logging.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070039#include <android-base/macros.h>
Tom Cherryccf23532017-03-28 16:40:41 -070040#include <android-base/properties.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070041#include <android-base/stringprintf.h>
42#include <android-base/strings.h>
Keun-young Park2ba5c812017-03-29 12:54:40 -070043#include <android-base/unique_fd.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070044#include <bootloader_message/bootloader_message.h>
45#include <cutils/android_reboot.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070046#include <fs_mgr.h>
47#include <logwrap/logwrap.h>
Todd Poynorfc827be2017-04-13 15:17:24 -070048#include <private/android_filesystem_config.h>
Tom Cherry0c8d6d22017-08-10 12:22:44 -070049#include <selinux/selinux.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070050
Tom Cherry7fd3bc22018-02-13 15:36:14 -080051#include "action_manager.h"
Wei Wangeeab4912017-06-27 22:08:45 -070052#include "init.h"
Keun-young Park7830d592017-03-27 16:07:02 -070053#include "property_service.h"
Tom Cherry44aceed2018-08-03 13:36:18 -070054#include "reboot_utils.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070055#include "service.h"
Luis Hector Chavez9f97f472017-09-06 13:43:57 -070056#include "sigchld_handler.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070057
Mark Salyzyn62909822017-10-09 09:27:16 -070058using android::base::Split;
Keun-young Park8d01f632017-03-13 11:54:47 -070059using android::base::StringPrintf;
Tom Cherryede0d532017-07-06 14:20:11 -070060using android::base::Timer;
Keun-young Park8d01f632017-03-13 11:54:47 -070061
Tom Cherry81f5d3e2017-06-22 12:53:17 -070062namespace android {
63namespace init {
64
Keun-young Park8d01f632017-03-13 11:54:47 -070065// represents umount status during reboot / shutdown.
66enum UmountStat {
67 /* umount succeeded. */
68 UMOUNT_STAT_SUCCESS = 0,
69 /* umount was not run. */
70 UMOUNT_STAT_SKIPPED = 1,
71 /* umount failed with timeout. */
72 UMOUNT_STAT_TIMEOUT = 2,
73 /* could not run due to error */
74 UMOUNT_STAT_ERROR = 3,
75 /* not used by init but reserved for other part to use this to represent the
76 the state where umount status before reboot is not found / available. */
77 UMOUNT_STAT_NOT_AVAILABLE = 4,
78};
79
80// Utility for struct mntent
81class MountEntry {
82 public:
Keun-young Park2ba5c812017-03-29 12:54:40 -070083 explicit MountEntry(const mntent& entry)
Keun-young Park8d01f632017-03-13 11:54:47 -070084 : mnt_fsname_(entry.mnt_fsname),
85 mnt_dir_(entry.mnt_dir),
86 mnt_type_(entry.mnt_type),
Keun-young Park2ba5c812017-03-29 12:54:40 -070087 mnt_opts_(entry.mnt_opts) {}
Keun-young Park8d01f632017-03-13 11:54:47 -070088
Jaegeuk Kim0f04f722017-09-25 10:55:39 -070089 bool Umount(bool force) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -080090 LOG(INFO) << "Unmounting " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Jaegeuk Kim0f04f722017-09-25 10:55:39 -070091 int r = umount2(mnt_dir_.c_str(), force ? MNT_FORCE : 0);
Keun-young Park2ba5c812017-03-29 12:54:40 -070092 if (r == 0) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -080093 LOG(INFO) << "Umounted " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Keun-young Park2ba5c812017-03-29 12:54:40 -070094 return true;
95 } else {
Tom Cherryc9fec9d2018-02-15 14:26:58 -080096 PLOG(WARNING) << "Cannot umount " << mnt_fsname_ << ":" << mnt_dir_ << " opts "
Keun-young Park2ba5c812017-03-29 12:54:40 -070097 << mnt_opts_;
98 return false;
99 }
100 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700101
Keun-young Park2ba5c812017-03-29 12:54:40 -0700102 void DoFsck() {
103 int st;
104 if (IsF2Fs()) {
105 const char* f2fs_argv[] = {
106 "/system/bin/fsck.f2fs", "-f", mnt_fsname_.c_str(),
107 };
108 android_fork_execvp_ext(arraysize(f2fs_argv), (char**)f2fs_argv, &st, true, LOG_KLOG,
109 true, nullptr, nullptr, 0);
110 } else if (IsExt4()) {
111 const char* ext4_argv[] = {
112 "/system/bin/e2fsck", "-f", "-y", mnt_fsname_.c_str(),
113 };
114 android_fork_execvp_ext(arraysize(ext4_argv), (char**)ext4_argv, &st, true, LOG_KLOG,
115 true, nullptr, nullptr, 0);
116 }
117 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700118
119 static bool IsBlockDevice(const struct mntent& mntent) {
120 return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
121 }
122
123 static bool IsEmulatedDevice(const struct mntent& mntent) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700124 return android::base::StartsWith(mntent.mnt_fsname, "/data/");
Keun-young Park8d01f632017-03-13 11:54:47 -0700125 }
126
127 private:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700128 bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
129
130 bool IsExt4() const { return mnt_type_ == "ext4"; }
131
Keun-young Park8d01f632017-03-13 11:54:47 -0700132 std::string mnt_fsname_;
133 std::string mnt_dir_;
134 std::string mnt_type_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700135 std::string mnt_opts_;
Keun-young Park8d01f632017-03-13 11:54:47 -0700136};
137
138// Turn off backlight while we are performing power down cleanup activities.
139static void TurnOffBacklight() {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800140 Service* service = ServiceList::GetInstance().FindService("blank_screen");
141 if (service == nullptr) {
142 LOG(WARNING) << "cannot find blank_screen in TurnOffBacklight";
Keun-young Park8d01f632017-03-13 11:54:47 -0700143 return;
144 }
Tom Cherryd9872642018-10-11 10:38:05 -0700145 if (auto result = service->Start(); !result) {
146 LOG(WARNING) << "Could not start blank_screen service: " << result.error();
147 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700148}
149
Keun-young Park8d01f632017-03-13 11:54:47 -0700150static void ShutdownVold() {
151 const char* vdc_argv[] = {"/system/bin/vdc", "volume", "shutdown"};
152 int status;
153 android_fork_execvp_ext(arraysize(vdc_argv), (char**)vdc_argv, &status, true, LOG_KLOG, true,
154 nullptr, nullptr, 0);
155}
156
157static void LogShutdownTime(UmountStat stat, Timer* t) {
Tom Cherryede0d532017-07-06 14:20:11 -0700158 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration().count()) << ":"
159 << stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700160}
161
Keun-young Park8d01f632017-03-13 11:54:47 -0700162/* Find all read+write block devices and emulated devices in /proc/mounts
163 * and add them to correpsponding list.
164 */
165static bool FindPartitionsToUmount(std::vector<MountEntry>* blockDevPartitions,
Keun-young Park2ba5c812017-03-29 12:54:40 -0700166 std::vector<MountEntry>* emulatedPartitions, bool dump) {
Tom Cherryf274e782018-10-03 13:13:41 -0700167 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
Keun-young Park8d01f632017-03-13 11:54:47 -0700168 if (fp == nullptr) {
169 PLOG(ERROR) << "Failed to open /proc/mounts";
170 return false;
171 }
172 mntent* mentry;
173 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700174 if (dump) {
175 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
176 << mentry->mnt_opts << " type " << mentry->mnt_type;
177 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
Keun-young Park6e12b382017-07-17 12:20:33 -0700178 std::string mount_dir(mentry->mnt_dir);
179 // These are R/O partitions changed to R/W after adb remount.
180 // Do not umount them as shutdown critical services may rely on them.
Wei Wanga01c27e2017-07-25 10:52:08 -0700181 if (mount_dir != "/" && mount_dir != "/system" && mount_dir != "/vendor" &&
182 mount_dir != "/oem") {
Keun-young Park6e12b382017-07-17 12:20:33 -0700183 blockDevPartitions->emplace(blockDevPartitions->begin(), *mentry);
184 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700185 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700186 emulatedPartitions->emplace(emulatedPartitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700187 }
188 }
189 return true;
190}
191
Keun-young Park1663e972017-04-21 17:29:26 -0700192static void DumpUmountDebuggingInfo(bool dump_all) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700193 int status;
194 if (!security_getenforce()) {
195 LOG(INFO) << "Run lsof";
196 const char* lsof_argv[] = {"/system/bin/lsof"};
197 android_fork_execvp_ext(arraysize(lsof_argv), (char**)lsof_argv, &status, true, LOG_KLOG,
198 true, nullptr, nullptr, 0);
Keun-young Park8d01f632017-03-13 11:54:47 -0700199 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700200 FindPartitionsToUmount(nullptr, nullptr, true);
Keun-young Park1663e972017-04-21 17:29:26 -0700201 if (dump_all) {
202 // dump current tasks, this log can be lengthy, so only dump with dump_all
203 android::base::WriteStringToFile("t", "/proc/sysrq-trigger");
204 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700205}
206
Tom Cherryede0d532017-07-06 14:20:11 -0700207static UmountStat UmountPartitions(std::chrono::milliseconds timeout) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700208 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700209 /* data partition needs all pending writes to be completed and all emulated partitions
210 * umounted.If the current waiting is not good enough, give
211 * up and leave it to e2fsck after reboot to fix it.
212 */
213 while (true) {
214 std::vector<MountEntry> block_devices;
215 std::vector<MountEntry> emulated_devices;
216 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
217 return UMOUNT_STAT_ERROR;
218 }
219 if (block_devices.size() == 0) {
Wei Wang8c00e422017-08-16 14:01:46 -0700220 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700221 }
Wei Wang8c00e422017-08-16 14:01:46 -0700222 bool unmount_done = true;
223 if (emulated_devices.size() > 0) {
Wei Wang25dc30f2017-10-23 15:32:03 -0700224 for (auto& entry : emulated_devices) {
225 if (!entry.Umount(false)) unmount_done = false;
226 }
Wei Wang8c00e422017-08-16 14:01:46 -0700227 if (unmount_done) {
228 sync();
229 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700230 }
Wei Wang25dc30f2017-10-23 15:32:03 -0700231 for (auto& entry : block_devices) {
232 if (!entry.Umount(timeout == 0ms)) unmount_done = false;
233 }
Wei Wang8c00e422017-08-16 14:01:46 -0700234 if (unmount_done) {
235 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700236 }
Wei Wang8c00e422017-08-16 14:01:46 -0700237 if ((timeout < t.duration())) { // try umount at least once
238 return UMOUNT_STAT_TIMEOUT;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700239 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700240 std::this_thread::sleep_for(100ms);
241 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700242}
243
Keun-young Park3ee0df92017-03-27 11:21:09 -0700244static void KillAllProcesses() { android::base::WriteStringToFile("i", "/proc/sysrq-trigger"); }
245
Keun-young Park8d01f632017-03-13 11:54:47 -0700246/* Try umounting all emulated file systems R/W block device cfile systems.
247 * This will just try umount and give it up if it fails.
248 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
249 * and necessary check can be done at the next reboot.
250 * For safer shutdown, caller needs to make sure that
251 * all processes / emulated partition for the target fs are all cleaned-up.
252 *
253 * return true when umount was successful. false when timed out.
254 */
Tom Cherryede0d532017-07-06 14:20:11 -0700255static UmountStat TryUmountAndFsck(bool runFsck, std::chrono::milliseconds timeout) {
Keun-young Park3ee0df92017-03-27 11:21:09 -0700256 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700257 std::vector<MountEntry> block_devices;
258 std::vector<MountEntry> emulated_devices;
Keun-young Park8d01f632017-03-13 11:54:47 -0700259
Keun-young Park2ba5c812017-03-29 12:54:40 -0700260 if (runFsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700261 return UMOUNT_STAT_ERROR;
262 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700263
Tom Cherryede0d532017-07-06 14:20:11 -0700264 UmountStat stat = UmountPartitions(timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700265 if (stat != UMOUNT_STAT_SUCCESS) {
266 LOG(INFO) << "umount timeout, last resort, kill all and try";
Keun-young Parkc59b8222017-07-18 18:52:25 -0700267 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(true);
Keun-young Park3ee0df92017-03-27 11:21:09 -0700268 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700269 // 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 -0700270 UmountStat st = UmountPartitions(0ms);
271 if ((st != UMOUNT_STAT_SUCCESS) && DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(false);
Keun-young Park8d01f632017-03-13 11:54:47 -0700272 }
273
Keun-young Park2ba5c812017-03-29 12:54:40 -0700274 if (stat == UMOUNT_STAT_SUCCESS && runFsck) {
275 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
276 // and should not affect reboot time.
277 for (auto& entry : block_devices) {
278 entry.DoFsck();
279 }
280 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700281 return stat;
282}
283
Tom Cherry44aceed2018-08-03 13:36:18 -0700284//* Reboot / shutdown the system.
285// cmd ANDROID_RB_* as defined in android_reboot.h
286// reason Reason string like "reboot", "shutdown,userrequested"
287// rebootTarget Reboot target string like "bootloader". Otherwise, it should be an
288// empty string.
289// runFsck Whether to run fsck after umount is done.
290//
291static void DoReboot(unsigned int cmd, const std::string& reason, const std::string& rebootTarget,
292 bool runFsck) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700293 Timer t;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700294 LOG(INFO) << "Reboot start, reason: " << reason << ", rebootTarget: " << rebootTarget;
295
296 // Ensure last reboot reason is reduced to canonical
297 // alias reported in bootloader or system boot reason.
298 size_t skip = 0;
299 std::vector<std::string> reasons = Split(reason, ",");
300 if (reasons.size() >= 2 && reasons[0] == "reboot" &&
301 (reasons[1] == "recovery" || reasons[1] == "bootloader" || reasons[1] == "cold" ||
302 reasons[1] == "hard" || reasons[1] == "warm")) {
303 skip = strlen("reboot,");
304 }
305 property_set(LAST_REBOOT_REASON_PROPERTY, reason.c_str() + skip);
306 sync();
307
308 bool is_thermal_shutdown = cmd == ANDROID_RB_THERMOFF;
309
310 auto shutdown_timeout = 0ms;
311 if (!SHUTDOWN_ZERO_TIMEOUT) {
312 if (is_thermal_shutdown) {
313 constexpr unsigned int thermal_shutdown_timeout = 1;
314 shutdown_timeout = std::chrono::seconds(thermal_shutdown_timeout);
315 } else {
316 constexpr unsigned int shutdown_timeout_default = 6;
317 auto shutdown_timeout_property = android::base::GetUintProperty(
318 "ro.build.shutdown_timeout", shutdown_timeout_default);
319 shutdown_timeout = std::chrono::seconds(shutdown_timeout_property);
320 }
321 }
322 LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " ms";
323
Keun-young Park7830d592017-03-27 16:07:02 -0700324 // keep debugging tools until non critical ones are all gone.
325 const std::set<std::string> kill_after_apps{"tombstoned", "logd", "adbd"};
326 // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700327 const std::set<std::string> to_starts{"watchdogd"};
Tom Cherry911b9b12017-07-27 16:20:58 -0700328 for (const auto& s : ServiceList::GetInstance()) {
Keun-young Park7830d592017-03-27 16:07:02 -0700329 if (kill_after_apps.count(s->name())) {
330 s->SetShutdownCritical();
331 } else if (to_starts.count(s->name())) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700332 if (auto result = s->Start(); !result) {
333 LOG(ERROR) << "Could not start shutdown 'to_start' service '" << s->name()
334 << "': " << result.error();
335 }
Keun-young Park7830d592017-03-27 16:07:02 -0700336 s->SetShutdownCritical();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700337 } else if (s->IsShutdownCritical()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700338 // Start shutdown critical service if not started.
339 if (auto result = s->Start(); !result) {
340 LOG(ERROR) << "Could not start shutdown critical service '" << s->name()
341 << "': " << result.error();
342 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700343 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700344 }
Keun-young Park7830d592017-03-27 16:07:02 -0700345
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800346 // remaining operations (specifically fsck) may take a substantial duration
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700347 if (cmd == ANDROID_RB_POWEROFF || is_thermal_shutdown) {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800348 TurnOffBacklight();
349 }
350
Tom Cherry911b9b12017-07-27 16:20:58 -0700351 Service* bootAnim = ServiceList::GetInstance().FindService("bootanim");
352 Service* surfaceFlinger = ServiceList::GetInstance().FindService("surfaceflinger");
Keun-young Park7830d592017-03-27 16:07:02 -0700353 if (bootAnim != nullptr && surfaceFlinger != nullptr && surfaceFlinger->IsRunning()) {
Tom Cherry911b9b12017-07-27 16:20:58 -0700354 // will not check animation class separately
355 for (const auto& service : ServiceList::GetInstance()) {
356 if (service->classnames().count("animation")) service->SetShutdownCritical();
357 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700358 }
Keun-young Park7830d592017-03-27 16:07:02 -0700359
Keun-young Park8d01f632017-03-13 11:54:47 -0700360 // optional shutdown step
361 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Keun-young Park30173872017-07-18 10:58:28 -0700362 if (shutdown_timeout > 0ms) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700363 LOG(INFO) << "terminating init services";
Keun-young Park8d01f632017-03-13 11:54:47 -0700364
365 // Ask all services to terminate except shutdown critical ones.
Tom Cherry911b9b12017-07-27 16:20:58 -0700366 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700367 if (!s->IsShutdownCritical()) s->Terminate();
Tom Cherry911b9b12017-07-27 16:20:58 -0700368 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700369
370 int service_count = 0;
Keun-young Park30173872017-07-18 10:58:28 -0700371 // Only wait up to half of timeout here
372 auto termination_wait_timeout = shutdown_timeout / 2;
Tom Cherryede0d532017-07-06 14:20:11 -0700373 while (t.duration() < termination_wait_timeout) {
Tom Cherryeeee8312017-07-28 15:22:23 -0700374 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700375
376 service_count = 0;
Tom Cherry911b9b12017-07-27 16:20:58 -0700377 for (const auto& s : ServiceList::GetInstance()) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700378 // Count the number of services running except shutdown critical.
379 // Exclude the console as it will ignore the SIGTERM signal
380 // and not exit.
381 // Note: SVC_CONSOLE actually means "requires console" but
382 // it is only used by the shell.
383 if (!s->IsShutdownCritical() && s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
384 service_count++;
385 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700386 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700387
388 if (service_count == 0) {
389 // All terminable services terminated. We can exit early.
390 break;
391 }
392
393 // Wait a bit before recounting the number or running services.
394 std::this_thread::sleep_for(50ms);
395 }
396 LOG(INFO) << "Terminating running services took " << t
397 << " with remaining services:" << service_count;
398 }
399
400 // minimum safety steps before restarting
401 // 2. kill all services except ones that are necessary for the shutdown sequence.
Tom Cherry911b9b12017-07-27 16:20:58 -0700402 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700403 if (!s->IsShutdownCritical()) s->Stop();
Tom Cherry911b9b12017-07-27 16:20:58 -0700404 }
Luis Hector Chavez92c49bc2018-07-27 11:19:25 -0700405 SubcontextTerminate();
Tom Cherryeeee8312017-07-28 15:22:23 -0700406 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700407
408 // 3. send volume shutdown to vold
Tom Cherry911b9b12017-07-27 16:20:58 -0700409 Service* voldService = ServiceList::GetInstance().FindService("vold");
Keun-young Park8d01f632017-03-13 11:54:47 -0700410 if (voldService != nullptr && voldService->IsRunning()) {
411 ShutdownVold();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700412 voldService->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700413 } else {
414 LOG(INFO) << "vold not running, skipping vold shutdown";
415 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700416 // logcat stopped here
Tom Cherry911b9b12017-07-27 16:20:58 -0700417 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700418 if (kill_after_apps.count(s->name())) s->Stop();
Tom Cherry911b9b12017-07-27 16:20:58 -0700419 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700420 // 4. sync, try umount, and optionally run fsck for user shutdown
Tom Cherry1f9d5402018-03-15 10:22:40 -0700421 {
422 Timer sync_timer;
423 LOG(INFO) << "sync() before umount...";
424 sync();
425 LOG(INFO) << "sync() before umount took" << sync_timer;
426 }
Tom Cherryede0d532017-07-06 14:20:11 -0700427 UmountStat stat = TryUmountAndFsck(runFsck, shutdown_timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700428 // Follow what linux shutdown is doing: one more sync with little bit delay
Tom Cherry1f9d5402018-03-15 10:22:40 -0700429 {
430 Timer sync_timer;
431 LOG(INFO) << "sync() after umount...";
432 sync();
433 LOG(INFO) << "sync() after umount took" << sync_timer;
434 }
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700435 if (!is_thermal_shutdown) std::this_thread::sleep_for(100ms);
Keun-young Park8d01f632017-03-13 11:54:47 -0700436 LogShutdownTime(stat, &t);
437 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
438 RebootSystem(cmd, rebootTarget);
439 abort();
440}
Tom Cherry98ad32a2017-04-17 16:34:20 -0700441
442bool HandlePowerctlMessage(const std::string& command) {
443 unsigned int cmd = 0;
Mark Salyzyn62909822017-10-09 09:27:16 -0700444 std::vector<std::string> cmd_params = Split(command, ",");
Tom Cherry98ad32a2017-04-17 16:34:20 -0700445 std::string reboot_target = "";
446 bool run_fsck = false;
447 bool command_invalid = false;
448
449 if (cmd_params.size() > 3) {
450 command_invalid = true;
451 } else if (cmd_params[0] == "shutdown") {
452 cmd = ANDROID_RB_POWEROFF;
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700453 if (cmd_params.size() == 2) {
454 if (cmd_params[1] == "userrequested") {
455 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
456 // Run fsck once the file system is remounted in read-only mode.
457 run_fsck = true;
458 } else if (cmd_params[1] == "thermal") {
Mark Salyzynbfd05b62017-09-26 11:10:12 -0700459 // Turn off sources of heat immediately.
460 TurnOffBacklight();
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700461 // run_fsck is false to avoid delay
462 cmd = ANDROID_RB_THERMOFF;
463 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700464 }
465 } else if (cmd_params[0] == "reboot") {
466 cmd = ANDROID_RB_RESTART2;
467 if (cmd_params.size() >= 2) {
468 reboot_target = cmd_params[1];
Hridya Valsaraju54258262018-09-19 21:14:18 -0700469 // adb reboot fastboot should boot into bootloader for devices not
470 // supporting logical partitions.
471 if (reboot_target == "fastboot" &&
472 !android::base::GetBoolProperty("ro.boot.logical_partitions", false)) {
473 reboot_target = "bootloader";
474 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700475 // When rebooting to the bootloader notify the bootloader writing
476 // also the BCB.
477 if (reboot_target == "bootloader") {
478 std::string err;
479 if (!write_reboot_bootloader(&err)) {
480 LOG(ERROR) << "reboot-bootloader: Error writing "
481 "bootloader_message: "
482 << err;
483 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700484 } else if (reboot_target == "sideload" || reboot_target == "sideload-auto-reboot" ||
485 reboot_target == "fastboot") {
486 std::string arg = reboot_target == "sideload-auto-reboot" ? "sideload_auto_reboot"
487 : reboot_target;
488 const std::vector<std::string> options = {
489 "--" + arg,
490 };
491 std::string err;
492 if (!write_bootloader_message(options, &err)) {
493 LOG(ERROR) << "Failed to set bootloader message: " << err;
494 return false;
495 }
496 reboot_target = "recovery";
Tom Cherry98ad32a2017-04-17 16:34:20 -0700497 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700498
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700499 // If there is an additional parameter, pass it along
500 if ((cmd_params.size() == 3) && cmd_params[2].size()) {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700501 reboot_target += "," + cmd_params[2];
502 }
503 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700504 } else {
505 command_invalid = true;
506 }
507 if (command_invalid) {
508 LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
509 return false;
510 }
511
Wei Wangeeab4912017-06-27 22:08:45 -0700512 LOG(INFO) << "Clear action queue and start shutdown trigger";
513 ActionManager::GetInstance().ClearQueue();
514 // Queue shutdown trigger first
515 ActionManager::GetInstance().QueueEventTrigger("shutdown");
516 // Queue built-in shutdown_done
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700517 auto shutdown_handler = [cmd, command, reboot_target, run_fsck](const BuiltinArguments&) {
Wei Wangeeab4912017-06-27 22:08:45 -0700518 DoReboot(cmd, command, reboot_target, run_fsck);
Tom Cherry557946e2017-08-01 13:50:23 -0700519 return Success();
Wei Wangeeab4912017-06-27 22:08:45 -0700520 };
521 ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
522
523 // Skip wait for prop if it is in progress
524 ResetWaitForProp();
525
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700526 // Clear EXEC flag if there is one pending
Tom Cherry911b9b12017-07-27 16:20:58 -0700527 for (const auto& s : ServiceList::GetInstance()) {
528 s->UnSetExec();
529 }
Wei Wangeeab4912017-06-27 22:08:45 -0700530
Tom Cherry98ad32a2017-04-17 16:34:20 -0700531 return true;
532}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700533
534} // namespace init
535} // namespace android