blob: cfd703ec1e0c376e1e2d129fcab7c74f07b72ae4 [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>
Keun-young Park8d01f632017-03-13 11:54:47 -070051
Luis Hector Chavez519e5f02017-06-29 09:50:30 -070052#include "capabilities.h"
Wei Wangeeab4912017-06-27 22:08:45 -070053#include "init.h"
Keun-young Park7830d592017-03-27 16:07:02 -070054#include "property_service.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070055#include "service.h"
Tom Cherryeeee8312017-07-28 15:22:23 -070056#include "signal_handler.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070057
58using android::base::StringPrintf;
Tom Cherryede0d532017-07-06 14:20:11 -070059using android::base::Timer;
Keun-young Park8d01f632017-03-13 11:54:47 -070060
Tom Cherry81f5d3e2017-06-22 12:53:17 -070061namespace android {
62namespace init {
63
Keun-young Park8d01f632017-03-13 11:54:47 -070064// represents umount status during reboot / shutdown.
65enum UmountStat {
66 /* umount succeeded. */
67 UMOUNT_STAT_SUCCESS = 0,
68 /* umount was not run. */
69 UMOUNT_STAT_SKIPPED = 1,
70 /* umount failed with timeout. */
71 UMOUNT_STAT_TIMEOUT = 2,
72 /* could not run due to error */
73 UMOUNT_STAT_ERROR = 3,
74 /* not used by init but reserved for other part to use this to represent the
75 the state where umount status before reboot is not found / available. */
76 UMOUNT_STAT_NOT_AVAILABLE = 4,
77};
78
79// Utility for struct mntent
80class MountEntry {
81 public:
Keun-young Park2ba5c812017-03-29 12:54:40 -070082 explicit MountEntry(const mntent& entry)
Keun-young Park8d01f632017-03-13 11:54:47 -070083 : mnt_fsname_(entry.mnt_fsname),
84 mnt_dir_(entry.mnt_dir),
85 mnt_type_(entry.mnt_type),
Keun-young Park2ba5c812017-03-29 12:54:40 -070086 mnt_opts_(entry.mnt_opts) {}
Keun-young Park8d01f632017-03-13 11:54:47 -070087
Keun-young Park2ba5c812017-03-29 12:54:40 -070088 bool Umount() {
89 int r = umount2(mnt_dir_.c_str(), 0);
90 if (r == 0) {
91 LOG(INFO) << "umounted " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
92 return true;
93 } else {
94 PLOG(WARNING) << "cannot umount " << mnt_fsname_ << ":" << mnt_dir_ << " opts "
95 << mnt_opts_;
96 return false;
97 }
98 }
Keun-young Park8d01f632017-03-13 11:54:47 -070099
Keun-young Park2ba5c812017-03-29 12:54:40 -0700100 void DoFsck() {
101 int st;
102 if (IsF2Fs()) {
103 const char* f2fs_argv[] = {
104 "/system/bin/fsck.f2fs", "-f", mnt_fsname_.c_str(),
105 };
106 android_fork_execvp_ext(arraysize(f2fs_argv), (char**)f2fs_argv, &st, true, LOG_KLOG,
107 true, nullptr, nullptr, 0);
108 } else if (IsExt4()) {
109 const char* ext4_argv[] = {
110 "/system/bin/e2fsck", "-f", "-y", mnt_fsname_.c_str(),
111 };
112 android_fork_execvp_ext(arraysize(ext4_argv), (char**)ext4_argv, &st, true, LOG_KLOG,
113 true, nullptr, nullptr, 0);
114 }
115 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700116
117 static bool IsBlockDevice(const struct mntent& mntent) {
118 return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
119 }
120
121 static bool IsEmulatedDevice(const struct mntent& mntent) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700122 return android::base::StartsWith(mntent.mnt_fsname, "/data/");
Keun-young Park8d01f632017-03-13 11:54:47 -0700123 }
124
125 private:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700126 bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
127
128 bool IsExt4() const { return mnt_type_ == "ext4"; }
129
Keun-young Park8d01f632017-03-13 11:54:47 -0700130 std::string mnt_fsname_;
131 std::string mnt_dir_;
132 std::string mnt_type_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700133 std::string mnt_opts_;
Keun-young Park8d01f632017-03-13 11:54:47 -0700134};
135
136// Turn off backlight while we are performing power down cleanup activities.
137static void TurnOffBacklight() {
138 static constexpr char OFF[] = "0";
139
140 android::base::WriteStringToFile(OFF, "/sys/class/leds/lcd-backlight/brightness");
141
142 static const char backlightDir[] = "/sys/class/backlight";
143 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(backlightDir), closedir);
144 if (!dir) {
145 return;
146 }
147
148 struct dirent* dp;
149 while ((dp = readdir(dir.get())) != nullptr) {
150 if (((dp->d_type != DT_DIR) && (dp->d_type != DT_LNK)) || (dp->d_name[0] == '.')) {
151 continue;
152 }
153
154 std::string fileName = StringPrintf("%s/%s/brightness", backlightDir, dp->d_name);
155 android::base::WriteStringToFile(OFF, fileName);
156 }
157}
158
Keun-young Park8d01f632017-03-13 11:54:47 -0700159static void ShutdownVold() {
160 const char* vdc_argv[] = {"/system/bin/vdc", "volume", "shutdown"};
161 int status;
162 android_fork_execvp_ext(arraysize(vdc_argv), (char**)vdc_argv, &status, true, LOG_KLOG, true,
163 nullptr, nullptr, 0);
164}
165
166static void LogShutdownTime(UmountStat stat, Timer* t) {
Tom Cherryede0d532017-07-06 14:20:11 -0700167 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration().count()) << ":"
168 << stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700169}
170
Luis Hector Chavez519e5f02017-06-29 09:50:30 -0700171// Determines whether the system is capable of rebooting. This is conservative,
172// so if any of the attempts to determine this fail, it will still return true.
173static bool IsRebootCapable() {
174 if (!CAP_IS_SUPPORTED(CAP_SYS_BOOT)) {
175 PLOG(WARNING) << "CAP_SYS_BOOT is not supported";
176 return true;
177 }
178
179 ScopedCaps caps(cap_get_proc());
180 if (!caps) {
181 PLOG(WARNING) << "cap_get_proc() failed";
182 return true;
183 }
184
185 cap_flag_value_t value = CAP_SET;
186 if (cap_get_flag(caps.get(), CAP_SYS_BOOT, CAP_EFFECTIVE, &value) != 0) {
187 PLOG(WARNING) << "cap_get_flag(CAP_SYS_BOOT, EFFECTIVE) failed";
188 return true;
189 }
190 return value == CAP_SET;
191}
192
Keun-young Park8d01f632017-03-13 11:54:47 -0700193static void __attribute__((noreturn))
194RebootSystem(unsigned int cmd, const std::string& rebootTarget) {
Keun-young Park3cd8c6f2017-03-23 15:33:16 -0700195 LOG(INFO) << "Reboot ending, jumping to kernel";
Luis Hector Chavez519e5f02017-06-29 09:50:30 -0700196
197 if (!IsRebootCapable()) {
198 // On systems where init does not have the capability of rebooting the
199 // device, just exit cleanly.
200 exit(0);
201 }
202
Keun-young Park8d01f632017-03-13 11:54:47 -0700203 switch (cmd) {
204 case ANDROID_RB_POWEROFF:
205 reboot(RB_POWER_OFF);
206 break;
207
208 case ANDROID_RB_RESTART2:
209 syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2,
210 LINUX_REBOOT_CMD_RESTART2, rebootTarget.c_str());
211 break;
212
213 case ANDROID_RB_THERMOFF:
214 reboot(RB_POWER_OFF);
215 break;
216 }
217 // In normal case, reboot should not return.
218 PLOG(FATAL) << "reboot call returned";
219 abort();
220}
221
222/* Find all read+write block devices and emulated devices in /proc/mounts
223 * and add them to correpsponding list.
224 */
225static bool FindPartitionsToUmount(std::vector<MountEntry>* blockDevPartitions,
Keun-young Park2ba5c812017-03-29 12:54:40 -0700226 std::vector<MountEntry>* emulatedPartitions, bool dump) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700227 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "r"), endmntent);
228 if (fp == nullptr) {
229 PLOG(ERROR) << "Failed to open /proc/mounts";
230 return false;
231 }
232 mntent* mentry;
233 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700234 if (dump) {
235 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
236 << mentry->mnt_opts << " type " << mentry->mnt_type;
237 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
Keun-young Park6e12b382017-07-17 12:20:33 -0700238 std::string mount_dir(mentry->mnt_dir);
239 // These are R/O partitions changed to R/W after adb remount.
240 // Do not umount them as shutdown critical services may rely on them.
Wei Wanga01c27e2017-07-25 10:52:08 -0700241 if (mount_dir != "/" && mount_dir != "/system" && mount_dir != "/vendor" &&
242 mount_dir != "/oem") {
Keun-young Park6e12b382017-07-17 12:20:33 -0700243 blockDevPartitions->emplace(blockDevPartitions->begin(), *mentry);
244 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700245 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700246 emulatedPartitions->emplace(emulatedPartitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700247 }
248 }
249 return true;
250}
251
Keun-young Park1663e972017-04-21 17:29:26 -0700252static void DumpUmountDebuggingInfo(bool dump_all) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700253 int status;
254 if (!security_getenforce()) {
255 LOG(INFO) << "Run lsof";
256 const char* lsof_argv[] = {"/system/bin/lsof"};
257 android_fork_execvp_ext(arraysize(lsof_argv), (char**)lsof_argv, &status, true, LOG_KLOG,
258 true, nullptr, nullptr, 0);
Keun-young Park8d01f632017-03-13 11:54:47 -0700259 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700260 FindPartitionsToUmount(nullptr, nullptr, true);
Keun-young Park1663e972017-04-21 17:29:26 -0700261 if (dump_all) {
262 // dump current tasks, this log can be lengthy, so only dump with dump_all
263 android::base::WriteStringToFile("t", "/proc/sysrq-trigger");
264 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700265}
266
Tom Cherryede0d532017-07-06 14:20:11 -0700267static UmountStat UmountPartitions(std::chrono::milliseconds timeout) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700268 Timer t;
269 UmountStat stat = UMOUNT_STAT_TIMEOUT;
270 int retry = 0;
271 /* data partition needs all pending writes to be completed and all emulated partitions
272 * umounted.If the current waiting is not good enough, give
273 * up and leave it to e2fsck after reboot to fix it.
274 */
275 while (true) {
276 std::vector<MountEntry> block_devices;
277 std::vector<MountEntry> emulated_devices;
278 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
279 return UMOUNT_STAT_ERROR;
280 }
281 if (block_devices.size() == 0) {
282 stat = UMOUNT_STAT_SUCCESS;
283 break;
284 }
Tom Cherryede0d532017-07-06 14:20:11 -0700285 if ((timeout < t.duration()) && retry > 0) { // try umount at least once
Keun-young Park2ba5c812017-03-29 12:54:40 -0700286 stat = UMOUNT_STAT_TIMEOUT;
287 break;
288 }
289 if (emulated_devices.size() > 0 &&
290 std::all_of(emulated_devices.begin(), emulated_devices.end(),
291 [](auto& entry) { return entry.Umount(); })) {
292 sync();
293 }
294 for (auto& entry : block_devices) {
295 entry.Umount();
296 }
297 retry++;
298 std::this_thread::sleep_for(100ms);
299 }
300 return stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700301}
302
Keun-young Park3ee0df92017-03-27 11:21:09 -0700303static void KillAllProcesses() { android::base::WriteStringToFile("i", "/proc/sysrq-trigger"); }
304
Keun-young Park8d01f632017-03-13 11:54:47 -0700305/* Try umounting all emulated file systems R/W block device cfile systems.
306 * This will just try umount and give it up if it fails.
307 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
308 * and necessary check can be done at the next reboot.
309 * For safer shutdown, caller needs to make sure that
310 * all processes / emulated partition for the target fs are all cleaned-up.
311 *
312 * return true when umount was successful. false when timed out.
313 */
Tom Cherryede0d532017-07-06 14:20:11 -0700314static UmountStat TryUmountAndFsck(bool runFsck, std::chrono::milliseconds timeout) {
Keun-young Park3ee0df92017-03-27 11:21:09 -0700315 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700316 std::vector<MountEntry> block_devices;
317 std::vector<MountEntry> emulated_devices;
Keun-young Park8d01f632017-03-13 11:54:47 -0700318
319 TurnOffBacklight(); // this part can take time. save power.
320
Keun-young Park2ba5c812017-03-29 12:54:40 -0700321 if (runFsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700322 return UMOUNT_STAT_ERROR;
323 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700324
Tom Cherryede0d532017-07-06 14:20:11 -0700325 UmountStat stat = UmountPartitions(timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700326 if (stat != UMOUNT_STAT_SUCCESS) {
327 LOG(INFO) << "umount timeout, last resort, kill all and try";
Keun-young Parkc59b8222017-07-18 18:52:25 -0700328 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(true);
Keun-young Park3ee0df92017-03-27 11:21:09 -0700329 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700330 // 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 -0700331 UmountStat st = UmountPartitions(0ms);
332 if ((st != UMOUNT_STAT_SUCCESS) && DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(false);
Keun-young Park8d01f632017-03-13 11:54:47 -0700333 }
334
Keun-young Park2ba5c812017-03-29 12:54:40 -0700335 if (stat == UMOUNT_STAT_SUCCESS && runFsck) {
336 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
337 // and should not affect reboot time.
338 for (auto& entry : block_devices) {
339 entry.DoFsck();
340 }
341 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700342 return stat;
343}
344
Keun-young Park8d01f632017-03-13 11:54:47 -0700345void DoReboot(unsigned int cmd, const std::string& reason, const std::string& rebootTarget,
346 bool runFsck) {
347 Timer t;
Keun-young Park3cd8c6f2017-03-23 15:33:16 -0700348 LOG(INFO) << "Reboot start, reason: " << reason << ", rebootTarget: " << rebootTarget;
Keun-young Park8d01f632017-03-13 11:54:47 -0700349
Todd Poynorfc827be2017-04-13 15:17:24 -0700350 android::base::WriteStringToFile(StringPrintf("%s\n", reason.c_str()), LAST_REBOOT_REASON_FILE,
351 S_IRUSR | S_IWUSR, AID_SYSTEM, AID_SYSTEM);
Keun-young Park8d01f632017-03-13 11:54:47 -0700352
Keun-young Park30173872017-07-18 10:58:28 -0700353 bool is_thermal_shutdown = false;
354 if (cmd == ANDROID_RB_THERMOFF) {
355 is_thermal_shutdown = true;
356 runFsck = false;
Keun-young Park8d01f632017-03-13 11:54:47 -0700357 }
Keun-young Parkaa08ea42017-03-23 13:27:28 -0700358
Keun-young Park30173872017-07-18 10:58:28 -0700359 auto shutdown_timeout = 0ms;
Tom Cherryede0d532017-07-06 14:20:11 -0700360 if (!SHUTDOWN_ZERO_TIMEOUT) {
Keun-young Park30173872017-07-18 10:58:28 -0700361 if (is_thermal_shutdown) {
362 constexpr unsigned int thermal_shutdown_timeout = 1;
363 shutdown_timeout = std::chrono::seconds(thermal_shutdown_timeout);
364 } else {
365 constexpr unsigned int shutdown_timeout_default = 6;
366 auto shutdown_timeout_property = android::base::GetUintProperty(
367 "ro.build.shutdown_timeout", shutdown_timeout_default);
368 shutdown_timeout = std::chrono::seconds(shutdown_timeout_property);
369 }
Keun-young Parkc4ffa5c2017-03-28 09:41:36 -0700370 }
Keun-young Park30173872017-07-18 10:58:28 -0700371 LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " ms";
Keun-young Parkaa08ea42017-03-23 13:27:28 -0700372
Keun-young Park7830d592017-03-27 16:07:02 -0700373 // keep debugging tools until non critical ones are all gone.
374 const std::set<std::string> kill_after_apps{"tombstoned", "logd", "adbd"};
375 // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700376 const std::set<std::string> to_starts{"watchdogd"};
Tom Cherry911b9b12017-07-27 16:20:58 -0700377 for (const auto& s : ServiceList::GetInstance()) {
Keun-young Park7830d592017-03-27 16:07:02 -0700378 if (kill_after_apps.count(s->name())) {
379 s->SetShutdownCritical();
380 } else if (to_starts.count(s->name())) {
381 s->Start();
382 s->SetShutdownCritical();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700383 } else if (s->IsShutdownCritical()) {
384 s->Start(); // start shutdown critical service if not started
Keun-young Park8d01f632017-03-13 11:54:47 -0700385 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700386 }
Keun-young Park7830d592017-03-27 16:07:02 -0700387
Tom Cherry911b9b12017-07-27 16:20:58 -0700388 Service* bootAnim = ServiceList::GetInstance().FindService("bootanim");
389 Service* surfaceFlinger = ServiceList::GetInstance().FindService("surfaceflinger");
Keun-young Park7830d592017-03-27 16:07:02 -0700390 if (bootAnim != nullptr && surfaceFlinger != nullptr && surfaceFlinger->IsRunning()) {
Tom Cherry911b9b12017-07-27 16:20:58 -0700391 // will not check animation class separately
392 for (const auto& service : ServiceList::GetInstance()) {
393 if (service->classnames().count("animation")) service->SetShutdownCritical();
394 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700395 }
Keun-young Park7830d592017-03-27 16:07:02 -0700396
Keun-young Park8d01f632017-03-13 11:54:47 -0700397 // optional shutdown step
398 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Keun-young Park30173872017-07-18 10:58:28 -0700399 if (shutdown_timeout > 0ms) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700400 LOG(INFO) << "terminating init services";
Keun-young Park8d01f632017-03-13 11:54:47 -0700401
402 // Ask all services to terminate except shutdown critical ones.
Tom Cherry911b9b12017-07-27 16:20:58 -0700403 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700404 if (!s->IsShutdownCritical()) s->Terminate();
Tom Cherry911b9b12017-07-27 16:20:58 -0700405 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700406
407 int service_count = 0;
Keun-young Park30173872017-07-18 10:58:28 -0700408 // Only wait up to half of timeout here
409 auto termination_wait_timeout = shutdown_timeout / 2;
Tom Cherryede0d532017-07-06 14:20:11 -0700410 while (t.duration() < termination_wait_timeout) {
Tom Cherryeeee8312017-07-28 15:22:23 -0700411 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700412
413 service_count = 0;
Tom Cherry911b9b12017-07-27 16:20:58 -0700414 for (const auto& s : ServiceList::GetInstance()) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700415 // Count the number of services running except shutdown critical.
416 // Exclude the console as it will ignore the SIGTERM signal
417 // and not exit.
418 // Note: SVC_CONSOLE actually means "requires console" but
419 // it is only used by the shell.
420 if (!s->IsShutdownCritical() && s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
421 service_count++;
422 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700423 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700424
425 if (service_count == 0) {
426 // All terminable services terminated. We can exit early.
427 break;
428 }
429
430 // Wait a bit before recounting the number or running services.
431 std::this_thread::sleep_for(50ms);
432 }
433 LOG(INFO) << "Terminating running services took " << t
434 << " with remaining services:" << service_count;
435 }
436
437 // minimum safety steps before restarting
438 // 2. kill all services except ones that are necessary for the shutdown sequence.
Tom Cherry911b9b12017-07-27 16:20:58 -0700439 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700440 if (!s->IsShutdownCritical()) s->Stop();
Tom Cherry911b9b12017-07-27 16:20:58 -0700441 }
Tom Cherryeeee8312017-07-28 15:22:23 -0700442 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700443
444 // 3. send volume shutdown to vold
Tom Cherry911b9b12017-07-27 16:20:58 -0700445 Service* voldService = ServiceList::GetInstance().FindService("vold");
Keun-young Park8d01f632017-03-13 11:54:47 -0700446 if (voldService != nullptr && voldService->IsRunning()) {
447 ShutdownVold();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700448 voldService->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700449 } else {
450 LOG(INFO) << "vold not running, skipping vold shutdown";
451 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700452 // logcat stopped here
Tom Cherry911b9b12017-07-27 16:20:58 -0700453 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700454 if (kill_after_apps.count(s->name())) s->Stop();
Tom Cherry911b9b12017-07-27 16:20:58 -0700455 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700456 // 4. sync, try umount, and optionally run fsck for user shutdown
Keun-young Park2ba5c812017-03-29 12:54:40 -0700457 sync();
Tom Cherryede0d532017-07-06 14:20:11 -0700458 UmountStat stat = TryUmountAndFsck(runFsck, shutdown_timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700459 // Follow what linux shutdown is doing: one more sync with little bit delay
460 sync();
Keun-young Park30173872017-07-18 10:58:28 -0700461 if (!is_thermal_shutdown) std::this_thread::sleep_for(100ms);
Keun-young Park8d01f632017-03-13 11:54:47 -0700462 LogShutdownTime(stat, &t);
463 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
464 RebootSystem(cmd, rebootTarget);
465 abort();
466}
Tom Cherry98ad32a2017-04-17 16:34:20 -0700467
468bool HandlePowerctlMessage(const std::string& command) {
469 unsigned int cmd = 0;
470 std::vector<std::string> cmd_params = android::base::Split(command, ",");
Tom Cherry98ad32a2017-04-17 16:34:20 -0700471 std::string reboot_target = "";
472 bool run_fsck = false;
473 bool command_invalid = false;
474
475 if (cmd_params.size() > 3) {
476 command_invalid = true;
477 } else if (cmd_params[0] == "shutdown") {
478 cmd = ANDROID_RB_POWEROFF;
479 if (cmd_params.size() == 2 && cmd_params[1] == "userrequested") {
480 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
481 // Run fsck once the file system is remounted in read-only mode.
482 run_fsck = true;
Tom Cherry98ad32a2017-04-17 16:34:20 -0700483 }
484 } else if (cmd_params[0] == "reboot") {
485 cmd = ANDROID_RB_RESTART2;
486 if (cmd_params.size() >= 2) {
487 reboot_target = cmd_params[1];
488 // When rebooting to the bootloader notify the bootloader writing
489 // also the BCB.
490 if (reboot_target == "bootloader") {
491 std::string err;
492 if (!write_reboot_bootloader(&err)) {
493 LOG(ERROR) << "reboot-bootloader: Error writing "
494 "bootloader_message: "
495 << err;
496 }
497 }
498 // If there is an additional bootloader parameter, pass it along
499 if (cmd_params.size() == 3) {
500 reboot_target += "," + cmd_params[2];
501 }
502 }
503 } else if (command == "thermal-shutdown") { // no additional parameter allowed
Wei Wang1be22122017-07-24 13:08:41 -0700504 // run_fsck is false to avoid delay
Tom Cherry98ad32a2017-04-17 16:34:20 -0700505 cmd = ANDROID_RB_THERMOFF;
506 } else {
507 command_invalid = true;
508 }
509 if (command_invalid) {
510 LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
511 return false;
512 }
513
Wei Wangeeab4912017-06-27 22:08:45 -0700514 LOG(INFO) << "Clear action queue and start shutdown trigger";
515 ActionManager::GetInstance().ClearQueue();
516 // Queue shutdown trigger first
517 ActionManager::GetInstance().QueueEventTrigger("shutdown");
518 // Queue built-in shutdown_done
519 auto shutdown_handler = [cmd, command, reboot_target,
520 run_fsck](const std::vector<std::string>&) {
521 DoReboot(cmd, command, reboot_target, run_fsck);
522 return 0;
523 };
524 ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
525
526 // Skip wait for prop if it is in progress
527 ResetWaitForProp();
528
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700529 // Clear EXEC flag if there is one pending
Tom Cherry911b9b12017-07-27 16:20:58 -0700530 for (const auto& s : ServiceList::GetInstance()) {
531 s->UnSetExec();
532 }
Wei Wangeeab4912017-06-27 22:08:45 -0700533
Tom Cherry98ad32a2017-04-17 16:34:20 -0700534 return true;
535}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700536
537} // namespace init
538} // namespace android