blob: 18f493a470e9c0fa137685496aba265972a7638f [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"
Luis Hector Chavez9f97f472017-09-06 13:43:57 -070057#include "sigchld_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 Chavez9f97f472017-09-06 13:43:57 -0700172bool IsRebootCapable() {
Luis Hector Chavez519e5f02017-06-29 09:50:30 -0700173 if (!CAP_IS_SUPPORTED(CAP_SYS_BOOT)) {
174 PLOG(WARNING) << "CAP_SYS_BOOT is not supported";
175 return true;
176 }
177
178 ScopedCaps caps(cap_get_proc());
179 if (!caps) {
180 PLOG(WARNING) << "cap_get_proc() failed";
181 return true;
182 }
183
184 cap_flag_value_t value = CAP_SET;
185 if (cap_get_flag(caps.get(), CAP_SYS_BOOT, CAP_EFFECTIVE, &value) != 0) {
186 PLOG(WARNING) << "cap_get_flag(CAP_SYS_BOOT, EFFECTIVE) failed";
187 return true;
188 }
189 return value == CAP_SET;
190}
191
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700192void __attribute__((noreturn)) RebootSystem(unsigned int cmd, const std::string& rebootTarget) {
Keun-young Park3cd8c6f2017-03-23 15:33:16 -0700193 LOG(INFO) << "Reboot ending, jumping to kernel";
Luis Hector Chavez519e5f02017-06-29 09:50:30 -0700194
195 if (!IsRebootCapable()) {
196 // On systems where init does not have the capability of rebooting the
197 // device, just exit cleanly.
198 exit(0);
199 }
200
Keun-young Park8d01f632017-03-13 11:54:47 -0700201 switch (cmd) {
202 case ANDROID_RB_POWEROFF:
203 reboot(RB_POWER_OFF);
204 break;
205
206 case ANDROID_RB_RESTART2:
207 syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2,
208 LINUX_REBOOT_CMD_RESTART2, rebootTarget.c_str());
209 break;
210
211 case ANDROID_RB_THERMOFF:
212 reboot(RB_POWER_OFF);
213 break;
214 }
215 // In normal case, reboot should not return.
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700216 PLOG(ERROR) << "reboot call returned";
Keun-young Park8d01f632017-03-13 11:54:47 -0700217 abort();
218}
219
220/* Find all read+write block devices and emulated devices in /proc/mounts
221 * and add them to correpsponding list.
222 */
223static bool FindPartitionsToUmount(std::vector<MountEntry>* blockDevPartitions,
Keun-young Park2ba5c812017-03-29 12:54:40 -0700224 std::vector<MountEntry>* emulatedPartitions, bool dump) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700225 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "r"), endmntent);
226 if (fp == nullptr) {
227 PLOG(ERROR) << "Failed to open /proc/mounts";
228 return false;
229 }
230 mntent* mentry;
231 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700232 if (dump) {
233 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
234 << mentry->mnt_opts << " type " << mentry->mnt_type;
235 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
Keun-young Park6e12b382017-07-17 12:20:33 -0700236 std::string mount_dir(mentry->mnt_dir);
237 // These are R/O partitions changed to R/W after adb remount.
238 // Do not umount them as shutdown critical services may rely on them.
Wei Wanga01c27e2017-07-25 10:52:08 -0700239 if (mount_dir != "/" && mount_dir != "/system" && mount_dir != "/vendor" &&
240 mount_dir != "/oem") {
Keun-young Park6e12b382017-07-17 12:20:33 -0700241 blockDevPartitions->emplace(blockDevPartitions->begin(), *mentry);
242 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700243 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700244 emulatedPartitions->emplace(emulatedPartitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700245 }
246 }
247 return true;
248}
249
Keun-young Park1663e972017-04-21 17:29:26 -0700250static void DumpUmountDebuggingInfo(bool dump_all) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700251 int status;
252 if (!security_getenforce()) {
253 LOG(INFO) << "Run lsof";
254 const char* lsof_argv[] = {"/system/bin/lsof"};
255 android_fork_execvp_ext(arraysize(lsof_argv), (char**)lsof_argv, &status, true, LOG_KLOG,
256 true, nullptr, nullptr, 0);
Keun-young Park8d01f632017-03-13 11:54:47 -0700257 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700258 FindPartitionsToUmount(nullptr, nullptr, true);
Keun-young Park1663e972017-04-21 17:29:26 -0700259 if (dump_all) {
260 // dump current tasks, this log can be lengthy, so only dump with dump_all
261 android::base::WriteStringToFile("t", "/proc/sysrq-trigger");
262 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700263}
264
Tom Cherryede0d532017-07-06 14:20:11 -0700265static UmountStat UmountPartitions(std::chrono::milliseconds timeout) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700266 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700267 /* data partition needs all pending writes to be completed and all emulated partitions
268 * umounted.If the current waiting is not good enough, give
269 * up and leave it to e2fsck after reboot to fix it.
270 */
271 while (true) {
272 std::vector<MountEntry> block_devices;
273 std::vector<MountEntry> emulated_devices;
274 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
275 return UMOUNT_STAT_ERROR;
276 }
277 if (block_devices.size() == 0) {
Wei Wang8c00e422017-08-16 14:01:46 -0700278 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700279 }
Wei Wang8c00e422017-08-16 14:01:46 -0700280 bool unmount_done = true;
281 if (emulated_devices.size() > 0) {
282 unmount_done = std::all_of(emulated_devices.begin(), emulated_devices.end(),
283 [](auto& entry) { return entry.Umount(); });
284 if (unmount_done) {
285 sync();
286 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700287 }
Wei Wang8c00e422017-08-16 14:01:46 -0700288 unmount_done = std::all_of(block_devices.begin(), block_devices.end(),
289 [](auto& entry) { return entry.Umount(); }) &&
290 unmount_done;
291 if (unmount_done) {
292 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700293 }
Wei Wang8c00e422017-08-16 14:01:46 -0700294 if ((timeout < t.duration())) { // try umount at least once
295 return UMOUNT_STAT_TIMEOUT;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700296 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700297 std::this_thread::sleep_for(100ms);
298 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700299}
300
Keun-young Park3ee0df92017-03-27 11:21:09 -0700301static void KillAllProcesses() { android::base::WriteStringToFile("i", "/proc/sysrq-trigger"); }
302
Keun-young Park8d01f632017-03-13 11:54:47 -0700303/* Try umounting all emulated file systems R/W block device cfile systems.
304 * This will just try umount and give it up if it fails.
305 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
306 * and necessary check can be done at the next reboot.
307 * For safer shutdown, caller needs to make sure that
308 * all processes / emulated partition for the target fs are all cleaned-up.
309 *
310 * return true when umount was successful. false when timed out.
311 */
Tom Cherryede0d532017-07-06 14:20:11 -0700312static UmountStat TryUmountAndFsck(bool runFsck, std::chrono::milliseconds timeout) {
Keun-young Park3ee0df92017-03-27 11:21:09 -0700313 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700314 std::vector<MountEntry> block_devices;
315 std::vector<MountEntry> emulated_devices;
Keun-young Park8d01f632017-03-13 11:54:47 -0700316
317 TurnOffBacklight(); // this part can take time. save power.
318
Keun-young Park2ba5c812017-03-29 12:54:40 -0700319 if (runFsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700320 return UMOUNT_STAT_ERROR;
321 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700322
Tom Cherryede0d532017-07-06 14:20:11 -0700323 UmountStat stat = UmountPartitions(timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700324 if (stat != UMOUNT_STAT_SUCCESS) {
325 LOG(INFO) << "umount timeout, last resort, kill all and try";
Keun-young Parkc59b8222017-07-18 18:52:25 -0700326 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(true);
Keun-young Park3ee0df92017-03-27 11:21:09 -0700327 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700328 // 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 -0700329 UmountStat st = UmountPartitions(0ms);
330 if ((st != UMOUNT_STAT_SUCCESS) && DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(false);
Keun-young Park8d01f632017-03-13 11:54:47 -0700331 }
332
Keun-young Park2ba5c812017-03-29 12:54:40 -0700333 if (stat == UMOUNT_STAT_SUCCESS && runFsck) {
334 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
335 // and should not affect reboot time.
336 for (auto& entry : block_devices) {
337 entry.DoFsck();
338 }
339 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700340 return stat;
341}
342
Keun-young Park8d01f632017-03-13 11:54:47 -0700343void DoReboot(unsigned int cmd, const std::string& reason, const std::string& rebootTarget,
344 bool runFsck) {
345 Timer t;
Keun-young Park3cd8c6f2017-03-23 15:33:16 -0700346 LOG(INFO) << "Reboot start, reason: " << reason << ", rebootTarget: " << rebootTarget;
Keun-young Park8d01f632017-03-13 11:54:47 -0700347
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700348 property_set(LAST_REBOOT_REASON_PROPERTY, reason.c_str());
349 sync();
Keun-young Park8d01f632017-03-13 11:54:47 -0700350
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700351 bool is_thermal_shutdown = cmd == ANDROID_RB_THERMOFF;
Keun-young Parkaa08ea42017-03-23 13:27:28 -0700352
Keun-young Park30173872017-07-18 10:58:28 -0700353 auto shutdown_timeout = 0ms;
Tom Cherryede0d532017-07-06 14:20:11 -0700354 if (!SHUTDOWN_ZERO_TIMEOUT) {
Keun-young Park30173872017-07-18 10:58:28 -0700355 if (is_thermal_shutdown) {
356 constexpr unsigned int thermal_shutdown_timeout = 1;
357 shutdown_timeout = std::chrono::seconds(thermal_shutdown_timeout);
358 } else {
359 constexpr unsigned int shutdown_timeout_default = 6;
360 auto shutdown_timeout_property = android::base::GetUintProperty(
361 "ro.build.shutdown_timeout", shutdown_timeout_default);
362 shutdown_timeout = std::chrono::seconds(shutdown_timeout_property);
363 }
Keun-young Parkc4ffa5c2017-03-28 09:41:36 -0700364 }
Keun-young Park30173872017-07-18 10:58:28 -0700365 LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " ms";
Keun-young Parkaa08ea42017-03-23 13:27:28 -0700366
Keun-young Park7830d592017-03-27 16:07:02 -0700367 // keep debugging tools until non critical ones are all gone.
368 const std::set<std::string> kill_after_apps{"tombstoned", "logd", "adbd"};
369 // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700370 const std::set<std::string> to_starts{"watchdogd"};
Tom Cherry911b9b12017-07-27 16:20:58 -0700371 for (const auto& s : ServiceList::GetInstance()) {
Keun-young Park7830d592017-03-27 16:07:02 -0700372 if (kill_after_apps.count(s->name())) {
373 s->SetShutdownCritical();
374 } else if (to_starts.count(s->name())) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700375 if (auto result = s->Start(); !result) {
376 LOG(ERROR) << "Could not start shutdown 'to_start' service '" << s->name()
377 << "': " << result.error();
378 }
Keun-young Park7830d592017-03-27 16:07:02 -0700379 s->SetShutdownCritical();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700380 } else if (s->IsShutdownCritical()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700381 // Start shutdown critical service if not started.
382 if (auto result = s->Start(); !result) {
383 LOG(ERROR) << "Could not start shutdown critical service '" << s->name()
384 << "': " << result.error();
385 }
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;
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700480 if (cmd_params.size() == 2) {
481 if (cmd_params[1] == "userrequested") {
482 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
483 // Run fsck once the file system is remounted in read-only mode.
484 run_fsck = true;
485 } else if (cmd_params[1] == "thermal") {
Mark Salyzynbfd05b62017-09-26 11:10:12 -0700486 // Turn off sources of heat immediately.
487 TurnOffBacklight();
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700488 // run_fsck is false to avoid delay
489 cmd = ANDROID_RB_THERMOFF;
490 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700491 }
492 } else if (cmd_params[0] == "reboot") {
493 cmd = ANDROID_RB_RESTART2;
494 if (cmd_params.size() >= 2) {
495 reboot_target = cmd_params[1];
496 // When rebooting to the bootloader notify the bootloader writing
497 // also the BCB.
498 if (reboot_target == "bootloader") {
499 std::string err;
500 if (!write_reboot_bootloader(&err)) {
501 LOG(ERROR) << "reboot-bootloader: Error writing "
502 "bootloader_message: "
503 << err;
504 }
505 }
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700506 // If there is an additional parameter, pass it along
507 if ((cmd_params.size() == 3) && cmd_params[2].size()) {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700508 reboot_target += "," + cmd_params[2];
509 }
510 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700511 } else {
512 command_invalid = true;
513 }
514 if (command_invalid) {
515 LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
516 return false;
517 }
518
Wei Wangeeab4912017-06-27 22:08:45 -0700519 LOG(INFO) << "Clear action queue and start shutdown trigger";
520 ActionManager::GetInstance().ClearQueue();
521 // Queue shutdown trigger first
522 ActionManager::GetInstance().QueueEventTrigger("shutdown");
523 // Queue built-in shutdown_done
524 auto shutdown_handler = [cmd, command, reboot_target,
525 run_fsck](const std::vector<std::string>&) {
526 DoReboot(cmd, command, reboot_target, run_fsck);
Tom Cherry557946e2017-08-01 13:50:23 -0700527 return Success();
Wei Wangeeab4912017-06-27 22:08:45 -0700528 };
529 ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
530
531 // Skip wait for prop if it is in progress
532 ResetWaitForProp();
533
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700534 // Clear EXEC flag if there is one pending
Tom Cherry911b9b12017-07-27 16:20:58 -0700535 for (const auto& s : ServiceList::GetInstance()) {
536 s->UnSetExec();
537 }
Wei Wangeeab4912017-06-27 22:08:45 -0700538
Tom Cherry98ad32a2017-04-17 16:34:20 -0700539 return true;
540}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700541
542} // namespace init
543} // namespace android