blob: 34c98a74096fe5c8190c48b322408d5b33db9a8f [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
38#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070039#include <android-base/logging.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070040#include <android-base/macros.h>
Tom Cherryccf23532017-03-28 16:40:41 -070041#include <android-base/properties.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070042#include <android-base/stringprintf.h>
43#include <android-base/strings.h>
Keun-young Park2ba5c812017-03-29 12:54:40 -070044#include <android-base/unique_fd.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070045#include <bootloader_message/bootloader_message.h>
46#include <cutils/android_reboot.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070047#include <fs_mgr.h>
48#include <logwrap/logwrap.h>
Todd Poynorfc827be2017-04-13 15:17:24 -070049#include <private/android_filesystem_config.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070050
Luis Hector Chavez519e5f02017-06-29 09:50:30 -070051#include "capabilities.h"
Keun-young Park7830d592017-03-27 16:07:02 -070052#include "property_service.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070053#include "service.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070054
55using android::base::StringPrintf;
56
Tom Cherry81f5d3e2017-06-22 12:53:17 -070057namespace android {
58namespace init {
59
Keun-young Park8d01f632017-03-13 11:54:47 -070060// represents umount status during reboot / shutdown.
61enum UmountStat {
62 /* umount succeeded. */
63 UMOUNT_STAT_SUCCESS = 0,
64 /* umount was not run. */
65 UMOUNT_STAT_SKIPPED = 1,
66 /* umount failed with timeout. */
67 UMOUNT_STAT_TIMEOUT = 2,
68 /* could not run due to error */
69 UMOUNT_STAT_ERROR = 3,
70 /* not used by init but reserved for other part to use this to represent the
71 the state where umount status before reboot is not found / available. */
72 UMOUNT_STAT_NOT_AVAILABLE = 4,
73};
74
75// Utility for struct mntent
76class MountEntry {
77 public:
Keun-young Park2ba5c812017-03-29 12:54:40 -070078 explicit MountEntry(const mntent& entry)
Keun-young Park8d01f632017-03-13 11:54:47 -070079 : mnt_fsname_(entry.mnt_fsname),
80 mnt_dir_(entry.mnt_dir),
81 mnt_type_(entry.mnt_type),
Keun-young Park2ba5c812017-03-29 12:54:40 -070082 mnt_opts_(entry.mnt_opts) {}
Keun-young Park8d01f632017-03-13 11:54:47 -070083
Keun-young Park2ba5c812017-03-29 12:54:40 -070084 bool Umount() {
85 int r = umount2(mnt_dir_.c_str(), 0);
86 if (r == 0) {
87 LOG(INFO) << "umounted " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
88 return true;
89 } else {
90 PLOG(WARNING) << "cannot umount " << mnt_fsname_ << ":" << mnt_dir_ << " opts "
91 << mnt_opts_;
92 return false;
93 }
94 }
Keun-young Park8d01f632017-03-13 11:54:47 -070095
Keun-young Park2ba5c812017-03-29 12:54:40 -070096 void DoFsck() {
97 int st;
98 if (IsF2Fs()) {
99 const char* f2fs_argv[] = {
100 "/system/bin/fsck.f2fs", "-f", mnt_fsname_.c_str(),
101 };
102 android_fork_execvp_ext(arraysize(f2fs_argv), (char**)f2fs_argv, &st, true, LOG_KLOG,
103 true, nullptr, nullptr, 0);
104 } else if (IsExt4()) {
105 const char* ext4_argv[] = {
106 "/system/bin/e2fsck", "-f", "-y", mnt_fsname_.c_str(),
107 };
108 android_fork_execvp_ext(arraysize(ext4_argv), (char**)ext4_argv, &st, true, LOG_KLOG,
109 true, nullptr, nullptr, 0);
110 }
111 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700112
113 static bool IsBlockDevice(const struct mntent& mntent) {
114 return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
115 }
116
117 static bool IsEmulatedDevice(const struct mntent& mntent) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700118 return android::base::StartsWith(mntent.mnt_fsname, "/data/");
Keun-young Park8d01f632017-03-13 11:54:47 -0700119 }
120
121 private:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700122 bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
123
124 bool IsExt4() const { return mnt_type_ == "ext4"; }
125
Keun-young Park8d01f632017-03-13 11:54:47 -0700126 std::string mnt_fsname_;
127 std::string mnt_dir_;
128 std::string mnt_type_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700129 std::string mnt_opts_;
Keun-young Park8d01f632017-03-13 11:54:47 -0700130};
131
132// Turn off backlight while we are performing power down cleanup activities.
133static void TurnOffBacklight() {
134 static constexpr char OFF[] = "0";
135
136 android::base::WriteStringToFile(OFF, "/sys/class/leds/lcd-backlight/brightness");
137
138 static const char backlightDir[] = "/sys/class/backlight";
139 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(backlightDir), closedir);
140 if (!dir) {
141 return;
142 }
143
144 struct dirent* dp;
145 while ((dp = readdir(dir.get())) != nullptr) {
146 if (((dp->d_type != DT_DIR) && (dp->d_type != DT_LNK)) || (dp->d_name[0] == '.')) {
147 continue;
148 }
149
150 std::string fileName = StringPrintf("%s/%s/brightness", backlightDir, dp->d_name);
151 android::base::WriteStringToFile(OFF, fileName);
152 }
153}
154
Keun-young Park8d01f632017-03-13 11:54:47 -0700155static void ShutdownVold() {
156 const char* vdc_argv[] = {"/system/bin/vdc", "volume", "shutdown"};
157 int status;
158 android_fork_execvp_ext(arraysize(vdc_argv), (char**)vdc_argv, &status, true, LOG_KLOG, true,
159 nullptr, nullptr, 0);
160}
161
162static void LogShutdownTime(UmountStat stat, Timer* t) {
163 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration_ms()) << ":" << stat;
164}
165
Luis Hector Chavez519e5f02017-06-29 09:50:30 -0700166// Determines whether the system is capable of rebooting. This is conservative,
167// so if any of the attempts to determine this fail, it will still return true.
168static bool IsRebootCapable() {
169 if (!CAP_IS_SUPPORTED(CAP_SYS_BOOT)) {
170 PLOG(WARNING) << "CAP_SYS_BOOT is not supported";
171 return true;
172 }
173
174 ScopedCaps caps(cap_get_proc());
175 if (!caps) {
176 PLOG(WARNING) << "cap_get_proc() failed";
177 return true;
178 }
179
180 cap_flag_value_t value = CAP_SET;
181 if (cap_get_flag(caps.get(), CAP_SYS_BOOT, CAP_EFFECTIVE, &value) != 0) {
182 PLOG(WARNING) << "cap_get_flag(CAP_SYS_BOOT, EFFECTIVE) failed";
183 return true;
184 }
185 return value == CAP_SET;
186}
187
Keun-young Park8d01f632017-03-13 11:54:47 -0700188static void __attribute__((noreturn))
189RebootSystem(unsigned int cmd, const std::string& rebootTarget) {
Keun-young Park3cd8c6f2017-03-23 15:33:16 -0700190 LOG(INFO) << "Reboot ending, jumping to kernel";
Luis Hector Chavez519e5f02017-06-29 09:50:30 -0700191
192 if (!IsRebootCapable()) {
193 // On systems where init does not have the capability of rebooting the
194 // device, just exit cleanly.
195 exit(0);
196 }
197
Keun-young Park8d01f632017-03-13 11:54:47 -0700198 switch (cmd) {
199 case ANDROID_RB_POWEROFF:
200 reboot(RB_POWER_OFF);
201 break;
202
203 case ANDROID_RB_RESTART2:
204 syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2,
205 LINUX_REBOOT_CMD_RESTART2, rebootTarget.c_str());
206 break;
207
208 case ANDROID_RB_THERMOFF:
209 reboot(RB_POWER_OFF);
210 break;
211 }
212 // In normal case, reboot should not return.
213 PLOG(FATAL) << "reboot call returned";
214 abort();
215}
216
217/* Find all read+write block devices and emulated devices in /proc/mounts
218 * and add them to correpsponding list.
219 */
220static bool FindPartitionsToUmount(std::vector<MountEntry>* blockDevPartitions,
Keun-young Park2ba5c812017-03-29 12:54:40 -0700221 std::vector<MountEntry>* emulatedPartitions, bool dump) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700222 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "r"), endmntent);
223 if (fp == nullptr) {
224 PLOG(ERROR) << "Failed to open /proc/mounts";
225 return false;
226 }
227 mntent* mentry;
228 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700229 if (dump) {
230 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
231 << mentry->mnt_opts << " type " << mentry->mnt_type;
232 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
233 blockDevPartitions->emplace(blockDevPartitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700234 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700235 emulatedPartitions->emplace(emulatedPartitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700236 }
237 }
238 return true;
239}
240
Keun-young Park1663e972017-04-21 17:29:26 -0700241static void DumpUmountDebuggingInfo(bool dump_all) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700242 int status;
243 if (!security_getenforce()) {
244 LOG(INFO) << "Run lsof";
245 const char* lsof_argv[] = {"/system/bin/lsof"};
246 android_fork_execvp_ext(arraysize(lsof_argv), (char**)lsof_argv, &status, true, LOG_KLOG,
247 true, nullptr, nullptr, 0);
Keun-young Park8d01f632017-03-13 11:54:47 -0700248 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700249 FindPartitionsToUmount(nullptr, nullptr, true);
Keun-young Park1663e972017-04-21 17:29:26 -0700250 if (dump_all) {
251 // dump current tasks, this log can be lengthy, so only dump with dump_all
252 android::base::WriteStringToFile("t", "/proc/sysrq-trigger");
253 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700254}
255
256static UmountStat UmountPartitions(int timeoutMs) {
257 Timer t;
258 UmountStat stat = UMOUNT_STAT_TIMEOUT;
259 int retry = 0;
260 /* data partition needs all pending writes to be completed and all emulated partitions
261 * umounted.If the current waiting is not good enough, give
262 * up and leave it to e2fsck after reboot to fix it.
263 */
264 while (true) {
265 std::vector<MountEntry> block_devices;
266 std::vector<MountEntry> emulated_devices;
267 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
268 return UMOUNT_STAT_ERROR;
269 }
270 if (block_devices.size() == 0) {
271 stat = UMOUNT_STAT_SUCCESS;
272 break;
273 }
274 if ((timeoutMs < t.duration_ms()) && retry > 0) { // try umount at least once
275 stat = UMOUNT_STAT_TIMEOUT;
276 break;
277 }
278 if (emulated_devices.size() > 0 &&
279 std::all_of(emulated_devices.begin(), emulated_devices.end(),
280 [](auto& entry) { return entry.Umount(); })) {
281 sync();
282 }
283 for (auto& entry : block_devices) {
284 entry.Umount();
285 }
286 retry++;
287 std::this_thread::sleep_for(100ms);
288 }
289 return stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700290}
291
Keun-young Park3ee0df92017-03-27 11:21:09 -0700292static void KillAllProcesses() { android::base::WriteStringToFile("i", "/proc/sysrq-trigger"); }
293
Keun-young Park8d01f632017-03-13 11:54:47 -0700294/* Try umounting all emulated file systems R/W block device cfile systems.
295 * This will just try umount and give it up if it fails.
296 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
297 * and necessary check can be done at the next reboot.
298 * For safer shutdown, caller needs to make sure that
299 * all processes / emulated partition for the target fs are all cleaned-up.
300 *
301 * return true when umount was successful. false when timed out.
302 */
Keun-young Park3ee0df92017-03-27 11:21:09 -0700303static UmountStat TryUmountAndFsck(bool runFsck, int timeoutMs) {
304 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700305 std::vector<MountEntry> block_devices;
306 std::vector<MountEntry> emulated_devices;
Keun-young Park8d01f632017-03-13 11:54:47 -0700307
308 TurnOffBacklight(); // this part can take time. save power.
309
Keun-young Park2ba5c812017-03-29 12:54:40 -0700310 if (runFsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700311 return UMOUNT_STAT_ERROR;
312 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700313
314 UmountStat stat = UmountPartitions(timeoutMs - t.duration_ms());
315 if (stat != UMOUNT_STAT_SUCCESS) {
316 LOG(INFO) << "umount timeout, last resort, kill all and try";
Keun-young Park1663e972017-04-21 17:29:26 -0700317 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(false);
Keun-young Park3ee0df92017-03-27 11:21:09 -0700318 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700319 // even if it succeeds, still it is timeout and do not run fsck with all processes killed
320 UmountPartitions(0);
Keun-young Park1663e972017-04-21 17:29:26 -0700321 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(true);
Keun-young Park8d01f632017-03-13 11:54:47 -0700322 }
323
Keun-young Park2ba5c812017-03-29 12:54:40 -0700324 if (stat == UMOUNT_STAT_SUCCESS && runFsck) {
325 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
326 // and should not affect reboot time.
327 for (auto& entry : block_devices) {
328 entry.DoFsck();
329 }
330 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700331 return stat;
332}
333
Keun-young Park8d01f632017-03-13 11:54:47 -0700334static void __attribute__((noreturn)) DoThermalOff() {
335 LOG(WARNING) << "Thermal system shutdown";
Keun-young Park2ba5c812017-03-29 12:54:40 -0700336 sync();
Keun-young Park8d01f632017-03-13 11:54:47 -0700337 RebootSystem(ANDROID_RB_THERMOFF, "");
338 abort();
339}
340
341void DoReboot(unsigned int cmd, const std::string& reason, const std::string& rebootTarget,
342 bool runFsck) {
343 Timer t;
Keun-young Park3cd8c6f2017-03-23 15:33:16 -0700344 LOG(INFO) << "Reboot start, reason: " << reason << ", rebootTarget: " << rebootTarget;
Keun-young Park8d01f632017-03-13 11:54:47 -0700345
Todd Poynorfc827be2017-04-13 15:17:24 -0700346 android::base::WriteStringToFile(StringPrintf("%s\n", reason.c_str()), LAST_REBOOT_REASON_FILE,
347 S_IRUSR | S_IWUSR, AID_SYSTEM, AID_SYSTEM);
Keun-young Park8d01f632017-03-13 11:54:47 -0700348
349 if (cmd == ANDROID_RB_THERMOFF) { // do not wait if it is thermal
350 DoThermalOff();
351 abort();
352 }
Keun-young Parkaa08ea42017-03-23 13:27:28 -0700353
Keun-young Park7feab682017-04-26 12:36:14 -0700354 constexpr unsigned int shutdownTimeoutDefault = 6;
Keun-young Parkc4ffa5c2017-03-28 09:41:36 -0700355 unsigned int shutdownTimeout = shutdownTimeoutDefault;
356 if (SHUTDOWN_ZERO_TIMEOUT) { // eng build
357 shutdownTimeout = 0;
358 } else {
359 shutdownTimeout =
360 android::base::GetUintProperty("ro.build.shutdown_timeout", shutdownTimeoutDefault);
361 }
Tom Cherryccf23532017-03-28 16:40:41 -0700362 LOG(INFO) << "Shutdown timeout: " << shutdownTimeout;
Keun-young Parkaa08ea42017-03-23 13:27:28 -0700363
Keun-young Park7830d592017-03-27 16:07:02 -0700364 // keep debugging tools until non critical ones are all gone.
365 const std::set<std::string> kill_after_apps{"tombstoned", "logd", "adbd"};
366 // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
Keun-young Park7264bee2017-05-18 13:28:32 -0700367 const std::set<std::string> to_starts{"watchdogd", "vold", "ueventd"};
Keun-young Park7830d592017-03-27 16:07:02 -0700368 ServiceManager::GetInstance().ForEachService([&kill_after_apps, &to_starts](Service* s) {
369 if (kill_after_apps.count(s->name())) {
370 s->SetShutdownCritical();
371 } else if (to_starts.count(s->name())) {
372 s->Start();
373 s->SetShutdownCritical();
Keun-young Park8d01f632017-03-13 11:54:47 -0700374 }
Keun-young Park7830d592017-03-27 16:07:02 -0700375 });
376
377 Service* bootAnim = ServiceManager::GetInstance().FindServiceByName("bootanim");
378 Service* surfaceFlinger = ServiceManager::GetInstance().FindServiceByName("surfaceflinger");
379 if (bootAnim != nullptr && surfaceFlinger != nullptr && surfaceFlinger->IsRunning()) {
Keun-young Park7830d592017-03-27 16:07:02 -0700380 ServiceManager::GetInstance().ForEachServiceInClass("animation", [](Service* s) {
Keun-young Park7830d592017-03-27 16:07:02 -0700381 s->SetShutdownCritical(); // will not check animation class separately
382 });
Keun-young Park8d01f632017-03-13 11:54:47 -0700383 }
Keun-young Park7830d592017-03-27 16:07:02 -0700384
Keun-young Park8d01f632017-03-13 11:54:47 -0700385 // optional shutdown step
386 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Keun-young Park3ee0df92017-03-27 11:21:09 -0700387 if (shutdownTimeout > 0) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700388 LOG(INFO) << "terminating init services";
Keun-young Park8d01f632017-03-13 11:54:47 -0700389
390 // Ask all services to terminate except shutdown critical ones.
391 ServiceManager::GetInstance().ForEachService([](Service* s) {
392 if (!s->IsShutdownCritical()) s->Terminate();
393 });
394
395 int service_count = 0;
Keun-young Park3ee0df92017-03-27 11:21:09 -0700396 // Up to half as long as shutdownTimeout or 3 seconds, whichever is lower.
397 unsigned int terminationWaitTimeout = std::min<unsigned int>((shutdownTimeout + 1) / 2, 3);
398 while (t.duration_s() < terminationWaitTimeout) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700399 ServiceManager::GetInstance().ReapAnyOutstandingChildren();
400
401 service_count = 0;
402 ServiceManager::GetInstance().ForEachService([&service_count](Service* s) {
403 // Count the number of services running except shutdown critical.
404 // Exclude the console as it will ignore the SIGTERM signal
405 // and not exit.
406 // Note: SVC_CONSOLE actually means "requires console" but
407 // it is only used by the shell.
408 if (!s->IsShutdownCritical() && s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
409 service_count++;
410 }
411 });
412
413 if (service_count == 0) {
414 // All terminable services terminated. We can exit early.
415 break;
416 }
417
418 // Wait a bit before recounting the number or running services.
419 std::this_thread::sleep_for(50ms);
420 }
421 LOG(INFO) << "Terminating running services took " << t
422 << " with remaining services:" << service_count;
423 }
424
425 // minimum safety steps before restarting
426 // 2. kill all services except ones that are necessary for the shutdown sequence.
Keun-young Park2ba5c812017-03-29 12:54:40 -0700427 ServiceManager::GetInstance().ForEachService([](Service* s) {
428 if (!s->IsShutdownCritical()) s->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700429 });
430 ServiceManager::GetInstance().ReapAnyOutstandingChildren();
431
432 // 3. send volume shutdown to vold
433 Service* voldService = ServiceManager::GetInstance().FindServiceByName("vold");
434 if (voldService != nullptr && voldService->IsRunning()) {
435 ShutdownVold();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700436 voldService->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700437 } else {
438 LOG(INFO) << "vold not running, skipping vold shutdown";
439 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700440 // logcat stopped here
441 ServiceManager::GetInstance().ForEachService([&kill_after_apps](Service* s) {
442 if (kill_after_apps.count(s->name())) s->Stop();
443 });
Keun-young Park8d01f632017-03-13 11:54:47 -0700444 // 4. sync, try umount, and optionally run fsck for user shutdown
Keun-young Park2ba5c812017-03-29 12:54:40 -0700445 sync();
Keun-young Park3ee0df92017-03-27 11:21:09 -0700446 UmountStat stat = TryUmountAndFsck(runFsck, shutdownTimeout * 1000 - t.duration_ms());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700447 // Follow what linux shutdown is doing: one more sync with little bit delay
448 sync();
449 std::this_thread::sleep_for(100ms);
Keun-young Park8d01f632017-03-13 11:54:47 -0700450 LogShutdownTime(stat, &t);
451 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
452 RebootSystem(cmd, rebootTarget);
453 abort();
454}
Tom Cherry98ad32a2017-04-17 16:34:20 -0700455
456bool HandlePowerctlMessage(const std::string& command) {
457 unsigned int cmd = 0;
458 std::vector<std::string> cmd_params = android::base::Split(command, ",");
Tom Cherry98ad32a2017-04-17 16:34:20 -0700459 std::string reboot_target = "";
460 bool run_fsck = false;
461 bool command_invalid = false;
462
463 if (cmd_params.size() > 3) {
464 command_invalid = true;
465 } else if (cmd_params[0] == "shutdown") {
466 cmd = ANDROID_RB_POWEROFF;
467 if (cmd_params.size() == 2 && cmd_params[1] == "userrequested") {
468 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
469 // Run fsck once the file system is remounted in read-only mode.
470 run_fsck = true;
Tom Cherry98ad32a2017-04-17 16:34:20 -0700471 }
472 } else if (cmd_params[0] == "reboot") {
473 cmd = ANDROID_RB_RESTART2;
474 if (cmd_params.size() >= 2) {
475 reboot_target = cmd_params[1];
476 // When rebooting to the bootloader notify the bootloader writing
477 // also the BCB.
478 if (reboot_target == "bootloader") {
479 std::string err;
480 if (!write_reboot_bootloader(&err)) {
481 LOG(ERROR) << "reboot-bootloader: Error writing "
482 "bootloader_message: "
483 << err;
484 }
485 }
486 // If there is an additional bootloader parameter, pass it along
487 if (cmd_params.size() == 3) {
488 reboot_target += "," + cmd_params[2];
489 }
490 }
491 } else if (command == "thermal-shutdown") { // no additional parameter allowed
492 cmd = ANDROID_RB_THERMOFF;
493 } else {
494 command_invalid = true;
495 }
496 if (command_invalid) {
497 LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
498 return false;
499 }
500
Tom Cherry47336ce2017-04-20 16:38:54 -0700501 DoReboot(cmd, command, reboot_target, run_fsck);
Tom Cherry98ad32a2017-04-17 16:34:20 -0700502 return true;
503}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700504
505} // namespace init
506} // namespace android