blob: 24ccdfc6a02c93dd27ad5a74c289b7434d33d9ea [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>
Luis Hector Chavez519e5f02017-06-29 09:50:30 -070023#include <sys/capability.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070024#include <sys/cdefs.h>
Keun-young Park2ba5c812017-03-29 12:54:40 -070025#include <sys/ioctl.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070026#include <sys/mount.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070027#include <sys/reboot.h>
28#include <sys/stat.h>
29#include <sys/syscall.h>
30#include <sys/types.h>
31#include <sys/wait.h>
32
33#include <memory>
Keun-young Park7830d592017-03-27 16:07:02 -070034#include <set>
Keun-young Park8d01f632017-03-13 11:54:47 -070035#include <thread>
36#include <vector>
37
Tom Cherryede0d532017-07-06 14:20:11 -070038#include <android-base/chrono_utils.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070039#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070040#include <android-base/logging.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070041#include <android-base/macros.h>
Tom Cherryccf23532017-03-28 16:40:41 -070042#include <android-base/properties.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070043#include <android-base/stringprintf.h>
44#include <android-base/strings.h>
Keun-young Park2ba5c812017-03-29 12:54:40 -070045#include <android-base/unique_fd.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070046#include <bootloader_message/bootloader_message.h>
47#include <cutils/android_reboot.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070048#include <fs_mgr.h>
49#include <logwrap/logwrap.h>
Todd Poynorfc827be2017-04-13 15:17:24 -070050#include <private/android_filesystem_config.h>
Tom Cherry0c8d6d22017-08-10 12:22:44 -070051#include <selinux/selinux.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070052
Luis Hector Chavez519e5f02017-06-29 09:50:30 -070053#include "capabilities.h"
Wei Wangeeab4912017-06-27 22:08:45 -070054#include "init.h"
Keun-young Park7830d592017-03-27 16:07:02 -070055#include "property_service.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070056#include "service.h"
Tom Cherryeeee8312017-07-28 15:22:23 -070057#include "signal_handler.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070058
59using 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
Keun-young Park2ba5c812017-03-29 12:54:40 -070089 bool Umount() {
90 int r = umount2(mnt_dir_.c_str(), 0);
91 if (r == 0) {
92 LOG(INFO) << "umounted " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
93 return true;
94 } else {
95 PLOG(WARNING) << "cannot umount " << mnt_fsname_ << ":" << mnt_dir_ << " opts "
96 << mnt_opts_;
97 return false;
98 }
99 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700100
Keun-young Park2ba5c812017-03-29 12:54:40 -0700101 void DoFsck() {
102 int st;
103 if (IsF2Fs()) {
104 const char* f2fs_argv[] = {
105 "/system/bin/fsck.f2fs", "-f", mnt_fsname_.c_str(),
106 };
107 android_fork_execvp_ext(arraysize(f2fs_argv), (char**)f2fs_argv, &st, true, LOG_KLOG,
108 true, nullptr, nullptr, 0);
109 } else if (IsExt4()) {
110 const char* ext4_argv[] = {
111 "/system/bin/e2fsck", "-f", "-y", mnt_fsname_.c_str(),
112 };
113 android_fork_execvp_ext(arraysize(ext4_argv), (char**)ext4_argv, &st, true, LOG_KLOG,
114 true, nullptr, nullptr, 0);
115 }
116 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700117
118 static bool IsBlockDevice(const struct mntent& mntent) {
119 return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
120 }
121
122 static bool IsEmulatedDevice(const struct mntent& mntent) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700123 return android::base::StartsWith(mntent.mnt_fsname, "/data/");
Keun-young Park8d01f632017-03-13 11:54:47 -0700124 }
125
126 private:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700127 bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
128
129 bool IsExt4() const { return mnt_type_ == "ext4"; }
130
Keun-young Park8d01f632017-03-13 11:54:47 -0700131 std::string mnt_fsname_;
132 std::string mnt_dir_;
133 std::string mnt_type_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700134 std::string mnt_opts_;
Keun-young Park8d01f632017-03-13 11:54:47 -0700135};
136
137// Turn off backlight while we are performing power down cleanup activities.
138static void TurnOffBacklight() {
139 static constexpr char OFF[] = "0";
140
141 android::base::WriteStringToFile(OFF, "/sys/class/leds/lcd-backlight/brightness");
142
143 static const char backlightDir[] = "/sys/class/backlight";
144 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(backlightDir), closedir);
145 if (!dir) {
146 return;
147 }
148
149 struct dirent* dp;
150 while ((dp = readdir(dir.get())) != nullptr) {
151 if (((dp->d_type != DT_DIR) && (dp->d_type != DT_LNK)) || (dp->d_name[0] == '.')) {
152 continue;
153 }
154
155 std::string fileName = StringPrintf("%s/%s/brightness", backlightDir, dp->d_name);
156 android::base::WriteStringToFile(OFF, fileName);
157 }
158}
159
Keun-young Park8d01f632017-03-13 11:54:47 -0700160static void ShutdownVold() {
161 const char* vdc_argv[] = {"/system/bin/vdc", "volume", "shutdown"};
162 int status;
163 android_fork_execvp_ext(arraysize(vdc_argv), (char**)vdc_argv, &status, true, LOG_KLOG, true,
164 nullptr, nullptr, 0);
165}
166
167static void LogShutdownTime(UmountStat stat, Timer* t) {
Tom Cherryede0d532017-07-06 14:20:11 -0700168 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration().count()) << ":"
169 << stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700170}
171
Luis Hector Chavez519e5f02017-06-29 09:50:30 -0700172// Determines whether the system is capable of rebooting. This is conservative,
173// so if any of the attempts to determine this fail, it will still return true.
174static bool IsRebootCapable() {
175 if (!CAP_IS_SUPPORTED(CAP_SYS_BOOT)) {
176 PLOG(WARNING) << "CAP_SYS_BOOT is not supported";
177 return true;
178 }
179
180 ScopedCaps caps(cap_get_proc());
181 if (!caps) {
182 PLOG(WARNING) << "cap_get_proc() failed";
183 return true;
184 }
185
186 cap_flag_value_t value = CAP_SET;
187 if (cap_get_flag(caps.get(), CAP_SYS_BOOT, CAP_EFFECTIVE, &value) != 0) {
188 PLOG(WARNING) << "cap_get_flag(CAP_SYS_BOOT, EFFECTIVE) failed";
189 return true;
190 }
191 return value == CAP_SET;
192}
193
Keun-young Park8d01f632017-03-13 11:54:47 -0700194static void __attribute__((noreturn))
195RebootSystem(unsigned int cmd, const std::string& rebootTarget) {
Keun-young Park3cd8c6f2017-03-23 15:33:16 -0700196 LOG(INFO) << "Reboot ending, jumping to kernel";
Luis Hector Chavez519e5f02017-06-29 09:50:30 -0700197
198 if (!IsRebootCapable()) {
199 // On systems where init does not have the capability of rebooting the
200 // device, just exit cleanly.
201 exit(0);
202 }
203
Keun-young Park8d01f632017-03-13 11:54:47 -0700204 switch (cmd) {
205 case ANDROID_RB_POWEROFF:
206 reboot(RB_POWER_OFF);
207 break;
208
209 case ANDROID_RB_RESTART2:
210 syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2,
211 LINUX_REBOOT_CMD_RESTART2, rebootTarget.c_str());
212 break;
213
214 case ANDROID_RB_THERMOFF:
215 reboot(RB_POWER_OFF);
216 break;
217 }
218 // In normal case, reboot should not return.
219 PLOG(FATAL) << "reboot call returned";
220 abort();
221}
222
223/* Find all read+write block devices and emulated devices in /proc/mounts
224 * and add them to correpsponding list.
225 */
226static bool FindPartitionsToUmount(std::vector<MountEntry>* blockDevPartitions,
Keun-young Park2ba5c812017-03-29 12:54:40 -0700227 std::vector<MountEntry>* emulatedPartitions, bool dump) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700228 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "r"), endmntent);
229 if (fp == nullptr) {
230 PLOG(ERROR) << "Failed to open /proc/mounts";
231 return false;
232 }
233 mntent* mentry;
234 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700235 if (dump) {
236 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
237 << mentry->mnt_opts << " type " << mentry->mnt_type;
238 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
Keun-young Park6e12b382017-07-17 12:20:33 -0700239 std::string mount_dir(mentry->mnt_dir);
240 // These are R/O partitions changed to R/W after adb remount.
241 // Do not umount them as shutdown critical services may rely on them.
Wei Wanga01c27e2017-07-25 10:52:08 -0700242 if (mount_dir != "/" && mount_dir != "/system" && mount_dir != "/vendor" &&
243 mount_dir != "/oem") {
Keun-young Park6e12b382017-07-17 12:20:33 -0700244 blockDevPartitions->emplace(blockDevPartitions->begin(), *mentry);
245 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700246 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700247 emulatedPartitions->emplace(emulatedPartitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700248 }
249 }
250 return true;
251}
252
Keun-young Park1663e972017-04-21 17:29:26 -0700253static void DumpUmountDebuggingInfo(bool dump_all) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700254 int status;
255 if (!security_getenforce()) {
256 LOG(INFO) << "Run lsof";
257 const char* lsof_argv[] = {"/system/bin/lsof"};
258 android_fork_execvp_ext(arraysize(lsof_argv), (char**)lsof_argv, &status, true, LOG_KLOG,
259 true, nullptr, nullptr, 0);
Keun-young Park8d01f632017-03-13 11:54:47 -0700260 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700261 FindPartitionsToUmount(nullptr, nullptr, true);
Keun-young Park1663e972017-04-21 17:29:26 -0700262 if (dump_all) {
263 // dump current tasks, this log can be lengthy, so only dump with dump_all
264 android::base::WriteStringToFile("t", "/proc/sysrq-trigger");
265 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700266}
267
Tom Cherryede0d532017-07-06 14:20:11 -0700268static UmountStat UmountPartitions(std::chrono::milliseconds timeout) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700269 Timer t;
270 UmountStat stat = UMOUNT_STAT_TIMEOUT;
271 int retry = 0;
272 /* data partition needs all pending writes to be completed and all emulated partitions
273 * umounted.If the current waiting is not good enough, give
274 * up and leave it to e2fsck after reboot to fix it.
275 */
276 while (true) {
277 std::vector<MountEntry> block_devices;
278 std::vector<MountEntry> emulated_devices;
279 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
280 return UMOUNT_STAT_ERROR;
281 }
282 if (block_devices.size() == 0) {
283 stat = UMOUNT_STAT_SUCCESS;
284 break;
285 }
Tom Cherryede0d532017-07-06 14:20:11 -0700286 if ((timeout < t.duration()) && retry > 0) { // try umount at least once
Keun-young Park2ba5c812017-03-29 12:54:40 -0700287 stat = UMOUNT_STAT_TIMEOUT;
288 break;
289 }
290 if (emulated_devices.size() > 0 &&
291 std::all_of(emulated_devices.begin(), emulated_devices.end(),
292 [](auto& entry) { return entry.Umount(); })) {
293 sync();
294 }
295 for (auto& entry : block_devices) {
296 entry.Umount();
297 }
298 retry++;
299 std::this_thread::sleep_for(100ms);
300 }
301 return stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700302}
303
Keun-young Park3ee0df92017-03-27 11:21:09 -0700304static void KillAllProcesses() { android::base::WriteStringToFile("i", "/proc/sysrq-trigger"); }
305
Keun-young Park8d01f632017-03-13 11:54:47 -0700306/* Try umounting all emulated file systems R/W block device cfile systems.
307 * This will just try umount and give it up if it fails.
308 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
309 * and necessary check can be done at the next reboot.
310 * For safer shutdown, caller needs to make sure that
311 * all processes / emulated partition for the target fs are all cleaned-up.
312 *
313 * return true when umount was successful. false when timed out.
314 */
Tom Cherryede0d532017-07-06 14:20:11 -0700315static UmountStat TryUmountAndFsck(bool runFsck, std::chrono::milliseconds timeout) {
Keun-young Park3ee0df92017-03-27 11:21:09 -0700316 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700317 std::vector<MountEntry> block_devices;
318 std::vector<MountEntry> emulated_devices;
Keun-young Park8d01f632017-03-13 11:54:47 -0700319
320 TurnOffBacklight(); // this part can take time. save power.
321
Keun-young Park2ba5c812017-03-29 12:54:40 -0700322 if (runFsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700323 return UMOUNT_STAT_ERROR;
324 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700325
Tom Cherryede0d532017-07-06 14:20:11 -0700326 UmountStat stat = UmountPartitions(timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700327 if (stat != UMOUNT_STAT_SUCCESS) {
328 LOG(INFO) << "umount timeout, last resort, kill all and try";
Keun-young Parkc59b8222017-07-18 18:52:25 -0700329 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(true);
Keun-young Park3ee0df92017-03-27 11:21:09 -0700330 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700331 // 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 -0700332 UmountStat st = UmountPartitions(0ms);
333 if ((st != UMOUNT_STAT_SUCCESS) && DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(false);
Keun-young Park8d01f632017-03-13 11:54:47 -0700334 }
335
Keun-young Park2ba5c812017-03-29 12:54:40 -0700336 if (stat == UMOUNT_STAT_SUCCESS && runFsck) {
337 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
338 // and should not affect reboot time.
339 for (auto& entry : block_devices) {
340 entry.DoFsck();
341 }
342 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700343 return stat;
344}
345
Keun-young Park8d01f632017-03-13 11:54:47 -0700346void DoReboot(unsigned int cmd, const std::string& reason, const std::string& rebootTarget,
347 bool runFsck) {
348 Timer t;
Keun-young Park3cd8c6f2017-03-23 15:33:16 -0700349 LOG(INFO) << "Reboot start, reason: " << reason << ", rebootTarget: " << rebootTarget;
Keun-young Park8d01f632017-03-13 11:54:47 -0700350
Todd Poynorfc827be2017-04-13 15:17:24 -0700351 android::base::WriteStringToFile(StringPrintf("%s\n", reason.c_str()), LAST_REBOOT_REASON_FILE,
352 S_IRUSR | S_IWUSR, AID_SYSTEM, AID_SYSTEM);
Keun-young Park8d01f632017-03-13 11:54:47 -0700353
Keun-young Park30173872017-07-18 10:58:28 -0700354 bool is_thermal_shutdown = false;
355 if (cmd == ANDROID_RB_THERMOFF) {
356 is_thermal_shutdown = true;
357 runFsck = false;
Keun-young Park8d01f632017-03-13 11:54:47 -0700358 }
Keun-young Parkaa08ea42017-03-23 13:27:28 -0700359
Keun-young Park30173872017-07-18 10:58:28 -0700360 auto shutdown_timeout = 0ms;
Tom Cherryede0d532017-07-06 14:20:11 -0700361 if (!SHUTDOWN_ZERO_TIMEOUT) {
Keun-young Park30173872017-07-18 10:58:28 -0700362 if (is_thermal_shutdown) {
363 constexpr unsigned int thermal_shutdown_timeout = 1;
364 shutdown_timeout = std::chrono::seconds(thermal_shutdown_timeout);
365 } else {
366 constexpr unsigned int shutdown_timeout_default = 6;
367 auto shutdown_timeout_property = android::base::GetUintProperty(
368 "ro.build.shutdown_timeout", shutdown_timeout_default);
369 shutdown_timeout = std::chrono::seconds(shutdown_timeout_property);
370 }
Keun-young Parkc4ffa5c2017-03-28 09:41:36 -0700371 }
Keun-young Park30173872017-07-18 10:58:28 -0700372 LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " ms";
Keun-young Parkaa08ea42017-03-23 13:27:28 -0700373
Keun-young Park7830d592017-03-27 16:07:02 -0700374 // keep debugging tools until non critical ones are all gone.
375 const std::set<std::string> kill_after_apps{"tombstoned", "logd", "adbd"};
376 // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700377 const std::set<std::string> to_starts{"watchdogd"};
Tom Cherry911b9b12017-07-27 16:20:58 -0700378 for (const auto& s : ServiceList::GetInstance()) {
Keun-young Park7830d592017-03-27 16:07:02 -0700379 if (kill_after_apps.count(s->name())) {
380 s->SetShutdownCritical();
381 } else if (to_starts.count(s->name())) {
382 s->Start();
383 s->SetShutdownCritical();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700384 } else if (s->IsShutdownCritical()) {
385 s->Start(); // start shutdown critical service if not started
Keun-young Park8d01f632017-03-13 11:54:47 -0700386 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700387 }
Keun-young Park7830d592017-03-27 16:07:02 -0700388
Tom Cherry911b9b12017-07-27 16:20:58 -0700389 Service* bootAnim = ServiceList::GetInstance().FindService("bootanim");
390 Service* surfaceFlinger = ServiceList::GetInstance().FindService("surfaceflinger");
Keun-young Park7830d592017-03-27 16:07:02 -0700391 if (bootAnim != nullptr && surfaceFlinger != nullptr && surfaceFlinger->IsRunning()) {
Tom Cherry911b9b12017-07-27 16:20:58 -0700392 // will not check animation class separately
393 for (const auto& service : ServiceList::GetInstance()) {
394 if (service->classnames().count("animation")) service->SetShutdownCritical();
395 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700396 }
Keun-young Park7830d592017-03-27 16:07:02 -0700397
Keun-young Park8d01f632017-03-13 11:54:47 -0700398 // optional shutdown step
399 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Keun-young Park30173872017-07-18 10:58:28 -0700400 if (shutdown_timeout > 0ms) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700401 LOG(INFO) << "terminating init services";
Keun-young Park8d01f632017-03-13 11:54:47 -0700402
403 // Ask all services to terminate except shutdown critical ones.
Tom Cherry911b9b12017-07-27 16:20:58 -0700404 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700405 if (!s->IsShutdownCritical()) s->Terminate();
Tom Cherry911b9b12017-07-27 16:20:58 -0700406 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700407
408 int service_count = 0;
Keun-young Park30173872017-07-18 10:58:28 -0700409 // Only wait up to half of timeout here
410 auto termination_wait_timeout = shutdown_timeout / 2;
Tom Cherryede0d532017-07-06 14:20:11 -0700411 while (t.duration() < termination_wait_timeout) {
Tom Cherryeeee8312017-07-28 15:22:23 -0700412 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700413
414 service_count = 0;
Tom Cherry911b9b12017-07-27 16:20:58 -0700415 for (const auto& s : ServiceList::GetInstance()) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700416 // Count the number of services running except shutdown critical.
417 // Exclude the console as it will ignore the SIGTERM signal
418 // and not exit.
419 // Note: SVC_CONSOLE actually means "requires console" but
420 // it is only used by the shell.
421 if (!s->IsShutdownCritical() && s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
422 service_count++;
423 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700424 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700425
426 if (service_count == 0) {
427 // All terminable services terminated. We can exit early.
428 break;
429 }
430
431 // Wait a bit before recounting the number or running services.
432 std::this_thread::sleep_for(50ms);
433 }
434 LOG(INFO) << "Terminating running services took " << t
435 << " with remaining services:" << service_count;
436 }
437
438 // minimum safety steps before restarting
439 // 2. kill all services except ones that are necessary for the shutdown sequence.
Tom Cherry911b9b12017-07-27 16:20:58 -0700440 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700441 if (!s->IsShutdownCritical()) s->Stop();
Tom Cherry911b9b12017-07-27 16:20:58 -0700442 }
Tom Cherryeeee8312017-07-28 15:22:23 -0700443 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700444
445 // 3. send volume shutdown to vold
Tom Cherry911b9b12017-07-27 16:20:58 -0700446 Service* voldService = ServiceList::GetInstance().FindService("vold");
Keun-young Park8d01f632017-03-13 11:54:47 -0700447 if (voldService != nullptr && voldService->IsRunning()) {
448 ShutdownVold();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700449 voldService->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700450 } else {
451 LOG(INFO) << "vold not running, skipping vold shutdown";
452 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700453 // logcat stopped here
Tom Cherry911b9b12017-07-27 16:20:58 -0700454 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700455 if (kill_after_apps.count(s->name())) s->Stop();
Tom Cherry911b9b12017-07-27 16:20:58 -0700456 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700457 // 4. sync, try umount, and optionally run fsck for user shutdown
Keun-young Park2ba5c812017-03-29 12:54:40 -0700458 sync();
Tom Cherryede0d532017-07-06 14:20:11 -0700459 UmountStat stat = TryUmountAndFsck(runFsck, shutdown_timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700460 // Follow what linux shutdown is doing: one more sync with little bit delay
461 sync();
Keun-young Park30173872017-07-18 10:58:28 -0700462 if (!is_thermal_shutdown) std::this_thread::sleep_for(100ms);
Keun-young Park8d01f632017-03-13 11:54:47 -0700463 LogShutdownTime(stat, &t);
464 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
465 RebootSystem(cmd, rebootTarget);
466 abort();
467}
Tom Cherry98ad32a2017-04-17 16:34:20 -0700468
469bool HandlePowerctlMessage(const std::string& command) {
470 unsigned int cmd = 0;
471 std::vector<std::string> cmd_params = android::base::Split(command, ",");
Tom Cherry98ad32a2017-04-17 16:34:20 -0700472 std::string reboot_target = "";
473 bool run_fsck = false;
474 bool command_invalid = false;
475
476 if (cmd_params.size() > 3) {
477 command_invalid = true;
478 } else if (cmd_params[0] == "shutdown") {
479 cmd = ANDROID_RB_POWEROFF;
480 if (cmd_params.size() == 2 && cmd_params[1] == "userrequested") {
481 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
482 // Run fsck once the file system is remounted in read-only mode.
483 run_fsck = true;
Tom Cherry98ad32a2017-04-17 16:34:20 -0700484 }
485 } else if (cmd_params[0] == "reboot") {
486 cmd = ANDROID_RB_RESTART2;
487 if (cmd_params.size() >= 2) {
488 reboot_target = cmd_params[1];
489 // When rebooting to the bootloader notify the bootloader writing
490 // also the BCB.
491 if (reboot_target == "bootloader") {
492 std::string err;
493 if (!write_reboot_bootloader(&err)) {
494 LOG(ERROR) << "reboot-bootloader: Error writing "
495 "bootloader_message: "
496 << err;
497 }
498 }
499 // If there is an additional bootloader parameter, pass it along
500 if (cmd_params.size() == 3) {
501 reboot_target += "," + cmd_params[2];
502 }
503 }
504 } else if (command == "thermal-shutdown") { // no additional parameter allowed
Wei Wang1be22122017-07-24 13:08:41 -0700505 // run_fsck is false to avoid delay
Tom Cherry98ad32a2017-04-17 16:34:20 -0700506 cmd = ANDROID_RB_THERMOFF;
507 } else {
508 command_invalid = true;
509 }
510 if (command_invalid) {
511 LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
512 return false;
513 }
514
Wei Wangeeab4912017-06-27 22:08:45 -0700515 LOG(INFO) << "Clear action queue and start shutdown trigger";
516 ActionManager::GetInstance().ClearQueue();
517 // Queue shutdown trigger first
518 ActionManager::GetInstance().QueueEventTrigger("shutdown");
519 // Queue built-in shutdown_done
520 auto shutdown_handler = [cmd, command, reboot_target,
521 run_fsck](const std::vector<std::string>&) {
522 DoReboot(cmd, command, reboot_target, run_fsck);
Tom Cherry557946e2017-08-01 13:50:23 -0700523 return Success();
Wei Wangeeab4912017-06-27 22:08:45 -0700524 };
525 ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
526
527 // Skip wait for prop if it is in progress
528 ResetWaitForProp();
529
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700530 // Clear EXEC flag if there is one pending
Tom Cherry911b9b12017-07-27 16:20:58 -0700531 for (const auto& s : ServiceList::GetInstance()) {
532 s->UnSetExec();
533 }
Wei Wangeeab4912017-06-27 22:08:45 -0700534
Tom Cherry98ad32a2017-04-17 16:34:20 -0700535 return true;
536}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700537
538} // namespace init
539} // namespace android