blob: 908c67ff05199b72482f5b78499f0f34cf53bcdc [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 }
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800145 service->Start();
Keun-young Park8d01f632017-03-13 11:54:47 -0700146}
147
Keun-young Park8d01f632017-03-13 11:54:47 -0700148static void ShutdownVold() {
149 const char* vdc_argv[] = {"/system/bin/vdc", "volume", "shutdown"};
150 int status;
151 android_fork_execvp_ext(arraysize(vdc_argv), (char**)vdc_argv, &status, true, LOG_KLOG, true,
152 nullptr, nullptr, 0);
153}
154
155static void LogShutdownTime(UmountStat stat, Timer* t) {
Tom Cherryede0d532017-07-06 14:20:11 -0700156 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration().count()) << ":"
157 << stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700158}
159
Keun-young Park8d01f632017-03-13 11:54:47 -0700160/* Find all read+write block devices and emulated devices in /proc/mounts
161 * and add them to correpsponding list.
162 */
163static bool FindPartitionsToUmount(std::vector<MountEntry>* blockDevPartitions,
Keun-young Park2ba5c812017-03-29 12:54:40 -0700164 std::vector<MountEntry>* emulatedPartitions, bool dump) {
Tom Cherryf274e782018-10-03 13:13:41 -0700165 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
Keun-young Park8d01f632017-03-13 11:54:47 -0700166 if (fp == nullptr) {
167 PLOG(ERROR) << "Failed to open /proc/mounts";
168 return false;
169 }
170 mntent* mentry;
171 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700172 if (dump) {
173 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
174 << mentry->mnt_opts << " type " << mentry->mnt_type;
175 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
Keun-young Park6e12b382017-07-17 12:20:33 -0700176 std::string mount_dir(mentry->mnt_dir);
177 // These are R/O partitions changed to R/W after adb remount.
178 // Do not umount them as shutdown critical services may rely on them.
Wei Wanga01c27e2017-07-25 10:52:08 -0700179 if (mount_dir != "/" && mount_dir != "/system" && mount_dir != "/vendor" &&
180 mount_dir != "/oem") {
Keun-young Park6e12b382017-07-17 12:20:33 -0700181 blockDevPartitions->emplace(blockDevPartitions->begin(), *mentry);
182 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700183 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700184 emulatedPartitions->emplace(emulatedPartitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700185 }
186 }
187 return true;
188}
189
Keun-young Park1663e972017-04-21 17:29:26 -0700190static void DumpUmountDebuggingInfo(bool dump_all) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700191 int status;
192 if (!security_getenforce()) {
193 LOG(INFO) << "Run lsof";
194 const char* lsof_argv[] = {"/system/bin/lsof"};
195 android_fork_execvp_ext(arraysize(lsof_argv), (char**)lsof_argv, &status, true, LOG_KLOG,
196 true, nullptr, nullptr, 0);
Keun-young Park8d01f632017-03-13 11:54:47 -0700197 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700198 FindPartitionsToUmount(nullptr, nullptr, true);
Keun-young Park1663e972017-04-21 17:29:26 -0700199 if (dump_all) {
200 // dump current tasks, this log can be lengthy, so only dump with dump_all
201 android::base::WriteStringToFile("t", "/proc/sysrq-trigger");
202 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700203}
204
Tom Cherryede0d532017-07-06 14:20:11 -0700205static UmountStat UmountPartitions(std::chrono::milliseconds timeout) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700206 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700207 /* data partition needs all pending writes to be completed and all emulated partitions
208 * umounted.If the current waiting is not good enough, give
209 * up and leave it to e2fsck after reboot to fix it.
210 */
211 while (true) {
212 std::vector<MountEntry> block_devices;
213 std::vector<MountEntry> emulated_devices;
214 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
215 return UMOUNT_STAT_ERROR;
216 }
217 if (block_devices.size() == 0) {
Wei Wang8c00e422017-08-16 14:01:46 -0700218 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700219 }
Wei Wang8c00e422017-08-16 14:01:46 -0700220 bool unmount_done = true;
221 if (emulated_devices.size() > 0) {
Wei Wang25dc30f2017-10-23 15:32:03 -0700222 for (auto& entry : emulated_devices) {
223 if (!entry.Umount(false)) unmount_done = false;
224 }
Wei Wang8c00e422017-08-16 14:01:46 -0700225 if (unmount_done) {
226 sync();
227 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700228 }
Wei Wang25dc30f2017-10-23 15:32:03 -0700229 for (auto& entry : block_devices) {
230 if (!entry.Umount(timeout == 0ms)) unmount_done = false;
231 }
Wei Wang8c00e422017-08-16 14:01:46 -0700232 if (unmount_done) {
233 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700234 }
Wei Wang8c00e422017-08-16 14:01:46 -0700235 if ((timeout < t.duration())) { // try umount at least once
236 return UMOUNT_STAT_TIMEOUT;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700237 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700238 std::this_thread::sleep_for(100ms);
239 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700240}
241
Keun-young Park3ee0df92017-03-27 11:21:09 -0700242static void KillAllProcesses() { android::base::WriteStringToFile("i", "/proc/sysrq-trigger"); }
243
Keun-young Park8d01f632017-03-13 11:54:47 -0700244/* Try umounting all emulated file systems R/W block device cfile systems.
245 * This will just try umount and give it up if it fails.
246 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
247 * and necessary check can be done at the next reboot.
248 * For safer shutdown, caller needs to make sure that
249 * all processes / emulated partition for the target fs are all cleaned-up.
250 *
251 * return true when umount was successful. false when timed out.
252 */
Tom Cherryede0d532017-07-06 14:20:11 -0700253static UmountStat TryUmountAndFsck(bool runFsck, std::chrono::milliseconds timeout) {
Keun-young Park3ee0df92017-03-27 11:21:09 -0700254 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700255 std::vector<MountEntry> block_devices;
256 std::vector<MountEntry> emulated_devices;
Keun-young Park8d01f632017-03-13 11:54:47 -0700257
Keun-young Park2ba5c812017-03-29 12:54:40 -0700258 if (runFsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700259 return UMOUNT_STAT_ERROR;
260 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700261
Tom Cherryede0d532017-07-06 14:20:11 -0700262 UmountStat stat = UmountPartitions(timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700263 if (stat != UMOUNT_STAT_SUCCESS) {
264 LOG(INFO) << "umount timeout, last resort, kill all and try";
Keun-young Parkc59b8222017-07-18 18:52:25 -0700265 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(true);
Keun-young Park3ee0df92017-03-27 11:21:09 -0700266 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700267 // 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 -0700268 UmountStat st = UmountPartitions(0ms);
269 if ((st != UMOUNT_STAT_SUCCESS) && DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(false);
Keun-young Park8d01f632017-03-13 11:54:47 -0700270 }
271
Keun-young Park2ba5c812017-03-29 12:54:40 -0700272 if (stat == UMOUNT_STAT_SUCCESS && runFsck) {
273 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
274 // and should not affect reboot time.
275 for (auto& entry : block_devices) {
276 entry.DoFsck();
277 }
278 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700279 return stat;
280}
281
Tom Cherry44aceed2018-08-03 13:36:18 -0700282//* Reboot / shutdown the system.
283// cmd ANDROID_RB_* as defined in android_reboot.h
284// reason Reason string like "reboot", "shutdown,userrequested"
285// rebootTarget Reboot target string like "bootloader". Otherwise, it should be an
286// empty string.
287// runFsck Whether to run fsck after umount is done.
288//
289static void DoReboot(unsigned int cmd, const std::string& reason, const std::string& rebootTarget,
290 bool runFsck) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700291 Timer t;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700292 LOG(INFO) << "Reboot start, reason: " << reason << ", rebootTarget: " << rebootTarget;
293
294 // Ensure last reboot reason is reduced to canonical
295 // alias reported in bootloader or system boot reason.
296 size_t skip = 0;
297 std::vector<std::string> reasons = Split(reason, ",");
298 if (reasons.size() >= 2 && reasons[0] == "reboot" &&
299 (reasons[1] == "recovery" || reasons[1] == "bootloader" || reasons[1] == "cold" ||
300 reasons[1] == "hard" || reasons[1] == "warm")) {
301 skip = strlen("reboot,");
302 }
303 property_set(LAST_REBOOT_REASON_PROPERTY, reason.c_str() + skip);
304 sync();
305
306 bool is_thermal_shutdown = cmd == ANDROID_RB_THERMOFF;
307
308 auto shutdown_timeout = 0ms;
309 if (!SHUTDOWN_ZERO_TIMEOUT) {
310 if (is_thermal_shutdown) {
311 constexpr unsigned int thermal_shutdown_timeout = 1;
312 shutdown_timeout = std::chrono::seconds(thermal_shutdown_timeout);
313 } else {
314 constexpr unsigned int shutdown_timeout_default = 6;
315 auto shutdown_timeout_property = android::base::GetUintProperty(
316 "ro.build.shutdown_timeout", shutdown_timeout_default);
317 shutdown_timeout = std::chrono::seconds(shutdown_timeout_property);
318 }
319 }
320 LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " ms";
321
Keun-young Park7830d592017-03-27 16:07:02 -0700322 // keep debugging tools until non critical ones are all gone.
323 const std::set<std::string> kill_after_apps{"tombstoned", "logd", "adbd"};
324 // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700325 const std::set<std::string> to_starts{"watchdogd"};
Tom Cherry911b9b12017-07-27 16:20:58 -0700326 for (const auto& s : ServiceList::GetInstance()) {
Keun-young Park7830d592017-03-27 16:07:02 -0700327 if (kill_after_apps.count(s->name())) {
328 s->SetShutdownCritical();
329 } else if (to_starts.count(s->name())) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700330 if (auto result = s->Start(); !result) {
331 LOG(ERROR) << "Could not start shutdown 'to_start' service '" << s->name()
332 << "': " << result.error();
333 }
Keun-young Park7830d592017-03-27 16:07:02 -0700334 s->SetShutdownCritical();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700335 } else if (s->IsShutdownCritical()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700336 // Start shutdown critical service if not started.
337 if (auto result = s->Start(); !result) {
338 LOG(ERROR) << "Could not start shutdown critical service '" << s->name()
339 << "': " << result.error();
340 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700341 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700342 }
Keun-young Park7830d592017-03-27 16:07:02 -0700343
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800344 // remaining operations (specifically fsck) may take a substantial duration
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700345 if (cmd == ANDROID_RB_POWEROFF || is_thermal_shutdown) {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800346 TurnOffBacklight();
347 }
348
Tom Cherry911b9b12017-07-27 16:20:58 -0700349 Service* bootAnim = ServiceList::GetInstance().FindService("bootanim");
350 Service* surfaceFlinger = ServiceList::GetInstance().FindService("surfaceflinger");
Keun-young Park7830d592017-03-27 16:07:02 -0700351 if (bootAnim != nullptr && surfaceFlinger != nullptr && surfaceFlinger->IsRunning()) {
Tom Cherry911b9b12017-07-27 16:20:58 -0700352 // will not check animation class separately
353 for (const auto& service : ServiceList::GetInstance()) {
354 if (service->classnames().count("animation")) service->SetShutdownCritical();
355 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700356 }
Keun-young Park7830d592017-03-27 16:07:02 -0700357
Keun-young Park8d01f632017-03-13 11:54:47 -0700358 // optional shutdown step
359 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Keun-young Park30173872017-07-18 10:58:28 -0700360 if (shutdown_timeout > 0ms) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700361 LOG(INFO) << "terminating init services";
Keun-young Park8d01f632017-03-13 11:54:47 -0700362
363 // Ask all services to terminate except shutdown critical ones.
Tom Cherry911b9b12017-07-27 16:20:58 -0700364 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700365 if (!s->IsShutdownCritical()) s->Terminate();
Tom Cherry911b9b12017-07-27 16:20:58 -0700366 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700367
368 int service_count = 0;
Keun-young Park30173872017-07-18 10:58:28 -0700369 // Only wait up to half of timeout here
370 auto termination_wait_timeout = shutdown_timeout / 2;
Tom Cherryede0d532017-07-06 14:20:11 -0700371 while (t.duration() < termination_wait_timeout) {
Tom Cherryeeee8312017-07-28 15:22:23 -0700372 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700373
374 service_count = 0;
Tom Cherry911b9b12017-07-27 16:20:58 -0700375 for (const auto& s : ServiceList::GetInstance()) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700376 // Count the number of services running except shutdown critical.
377 // Exclude the console as it will ignore the SIGTERM signal
378 // and not exit.
379 // Note: SVC_CONSOLE actually means "requires console" but
380 // it is only used by the shell.
381 if (!s->IsShutdownCritical() && s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
382 service_count++;
383 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700384 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700385
386 if (service_count == 0) {
387 // All terminable services terminated. We can exit early.
388 break;
389 }
390
391 // Wait a bit before recounting the number or running services.
392 std::this_thread::sleep_for(50ms);
393 }
394 LOG(INFO) << "Terminating running services took " << t
395 << " with remaining services:" << service_count;
396 }
397
398 // minimum safety steps before restarting
399 // 2. kill all services except ones that are necessary for the shutdown sequence.
Tom Cherry911b9b12017-07-27 16:20:58 -0700400 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700401 if (!s->IsShutdownCritical()) s->Stop();
Tom Cherry911b9b12017-07-27 16:20:58 -0700402 }
Luis Hector Chavez92c49bc2018-07-27 11:19:25 -0700403 SubcontextTerminate();
Tom Cherryeeee8312017-07-28 15:22:23 -0700404 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700405
406 // 3. send volume shutdown to vold
Tom Cherry911b9b12017-07-27 16:20:58 -0700407 Service* voldService = ServiceList::GetInstance().FindService("vold");
Keun-young Park8d01f632017-03-13 11:54:47 -0700408 if (voldService != nullptr && voldService->IsRunning()) {
409 ShutdownVold();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700410 voldService->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700411 } else {
412 LOG(INFO) << "vold not running, skipping vold shutdown";
413 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700414 // logcat stopped here
Tom Cherry911b9b12017-07-27 16:20:58 -0700415 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700416 if (kill_after_apps.count(s->name())) s->Stop();
Tom Cherry911b9b12017-07-27 16:20:58 -0700417 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700418 // 4. sync, try umount, and optionally run fsck for user shutdown
Tom Cherry1f9d5402018-03-15 10:22:40 -0700419 {
420 Timer sync_timer;
421 LOG(INFO) << "sync() before umount...";
422 sync();
423 LOG(INFO) << "sync() before umount took" << sync_timer;
424 }
Tom Cherryede0d532017-07-06 14:20:11 -0700425 UmountStat stat = TryUmountAndFsck(runFsck, shutdown_timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700426 // Follow what linux shutdown is doing: one more sync with little bit delay
Tom Cherry1f9d5402018-03-15 10:22:40 -0700427 {
428 Timer sync_timer;
429 LOG(INFO) << "sync() after umount...";
430 sync();
431 LOG(INFO) << "sync() after umount took" << sync_timer;
432 }
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700433 if (!is_thermal_shutdown) std::this_thread::sleep_for(100ms);
Keun-young Park8d01f632017-03-13 11:54:47 -0700434 LogShutdownTime(stat, &t);
435 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
436 RebootSystem(cmd, rebootTarget);
437 abort();
438}
Tom Cherry98ad32a2017-04-17 16:34:20 -0700439
440bool HandlePowerctlMessage(const std::string& command) {
441 unsigned int cmd = 0;
Mark Salyzyn62909822017-10-09 09:27:16 -0700442 std::vector<std::string> cmd_params = Split(command, ",");
Tom Cherry98ad32a2017-04-17 16:34:20 -0700443 std::string reboot_target = "";
444 bool run_fsck = false;
445 bool command_invalid = false;
446
447 if (cmd_params.size() > 3) {
448 command_invalid = true;
449 } else if (cmd_params[0] == "shutdown") {
450 cmd = ANDROID_RB_POWEROFF;
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700451 if (cmd_params.size() == 2) {
452 if (cmd_params[1] == "userrequested") {
453 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
454 // Run fsck once the file system is remounted in read-only mode.
455 run_fsck = true;
456 } else if (cmd_params[1] == "thermal") {
Mark Salyzynbfd05b62017-09-26 11:10:12 -0700457 // Turn off sources of heat immediately.
458 TurnOffBacklight();
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700459 // run_fsck is false to avoid delay
460 cmd = ANDROID_RB_THERMOFF;
461 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700462 }
463 } else if (cmd_params[0] == "reboot") {
464 cmd = ANDROID_RB_RESTART2;
465 if (cmd_params.size() >= 2) {
466 reboot_target = cmd_params[1];
467 // When rebooting to the bootloader notify the bootloader writing
468 // also the BCB.
469 if (reboot_target == "bootloader") {
470 std::string err;
471 if (!write_reboot_bootloader(&err)) {
472 LOG(ERROR) << "reboot-bootloader: Error writing "
473 "bootloader_message: "
474 << err;
475 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700476 } else if (reboot_target == "sideload" || reboot_target == "sideload-auto-reboot" ||
477 reboot_target == "fastboot") {
478 std::string arg = reboot_target == "sideload-auto-reboot" ? "sideload_auto_reboot"
479 : reboot_target;
480 const std::vector<std::string> options = {
481 "--" + arg,
482 };
483 std::string err;
484 if (!write_bootloader_message(options, &err)) {
485 LOG(ERROR) << "Failed to set bootloader message: " << err;
486 return false;
487 }
488 reboot_target = "recovery";
Tom Cherry98ad32a2017-04-17 16:34:20 -0700489 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700490
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700491 // If there is an additional parameter, pass it along
492 if ((cmd_params.size() == 3) && cmd_params[2].size()) {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700493 reboot_target += "," + cmd_params[2];
494 }
495 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700496 } else {
497 command_invalid = true;
498 }
499 if (command_invalid) {
500 LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
501 return false;
502 }
503
Wei Wangeeab4912017-06-27 22:08:45 -0700504 LOG(INFO) << "Clear action queue and start shutdown trigger";
505 ActionManager::GetInstance().ClearQueue();
506 // Queue shutdown trigger first
507 ActionManager::GetInstance().QueueEventTrigger("shutdown");
508 // Queue built-in shutdown_done
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700509 auto shutdown_handler = [cmd, command, reboot_target, run_fsck](const BuiltinArguments&) {
Wei Wangeeab4912017-06-27 22:08:45 -0700510 DoReboot(cmd, command, reboot_target, run_fsck);
Tom Cherry557946e2017-08-01 13:50:23 -0700511 return Success();
Wei Wangeeab4912017-06-27 22:08:45 -0700512 };
513 ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
514
515 // Skip wait for prop if it is in progress
516 ResetWaitForProp();
517
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700518 // Clear EXEC flag if there is one pending
Tom Cherry911b9b12017-07-27 16:20:58 -0700519 for (const auto& s : ServiceList::GetInstance()) {
520 s->UnSetExec();
521 }
Wei Wangeeab4912017-06-27 22:08:45 -0700522
Tom Cherry98ad32a2017-04-17 16:34:20 -0700523 return true;
524}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700525
526} // namespace init
527} // namespace android