blob: ec1ddd6f36c9bdb192ec98a073a729da042dd8a6 [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"
Wei Wangeeab4912017-06-27 22:08:45 -070052#include "init.h"
Keun-young Park7830d592017-03-27 16:07:02 -070053#include "property_service.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070054#include "service.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070055
56using android::base::StringPrintf;
57
Tom Cherry81f5d3e2017-06-22 12:53:17 -070058namespace android {
59namespace init {
60
Keun-young Park8d01f632017-03-13 11:54:47 -070061// represents umount status during reboot / shutdown.
62enum UmountStat {
63 /* umount succeeded. */
64 UMOUNT_STAT_SUCCESS = 0,
65 /* umount was not run. */
66 UMOUNT_STAT_SKIPPED = 1,
67 /* umount failed with timeout. */
68 UMOUNT_STAT_TIMEOUT = 2,
69 /* could not run due to error */
70 UMOUNT_STAT_ERROR = 3,
71 /* not used by init but reserved for other part to use this to represent the
72 the state where umount status before reboot is not found / available. */
73 UMOUNT_STAT_NOT_AVAILABLE = 4,
74};
75
76// Utility for struct mntent
77class MountEntry {
78 public:
Keun-young Park2ba5c812017-03-29 12:54:40 -070079 explicit MountEntry(const mntent& entry)
Keun-young Park8d01f632017-03-13 11:54:47 -070080 : mnt_fsname_(entry.mnt_fsname),
81 mnt_dir_(entry.mnt_dir),
82 mnt_type_(entry.mnt_type),
Keun-young Park2ba5c812017-03-29 12:54:40 -070083 mnt_opts_(entry.mnt_opts) {}
Keun-young Park8d01f632017-03-13 11:54:47 -070084
Keun-young Park2ba5c812017-03-29 12:54:40 -070085 bool Umount() {
86 int r = umount2(mnt_dir_.c_str(), 0);
87 if (r == 0) {
88 LOG(INFO) << "umounted " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
89 return true;
90 } else {
91 PLOG(WARNING) << "cannot umount " << mnt_fsname_ << ":" << mnt_dir_ << " opts "
92 << mnt_opts_;
93 return false;
94 }
95 }
Keun-young Park8d01f632017-03-13 11:54:47 -070096
Keun-young Park2ba5c812017-03-29 12:54:40 -070097 void DoFsck() {
98 int st;
99 if (IsF2Fs()) {
100 const char* f2fs_argv[] = {
101 "/system/bin/fsck.f2fs", "-f", mnt_fsname_.c_str(),
102 };
103 android_fork_execvp_ext(arraysize(f2fs_argv), (char**)f2fs_argv, &st, true, LOG_KLOG,
104 true, nullptr, nullptr, 0);
105 } else if (IsExt4()) {
106 const char* ext4_argv[] = {
107 "/system/bin/e2fsck", "-f", "-y", mnt_fsname_.c_str(),
108 };
109 android_fork_execvp_ext(arraysize(ext4_argv), (char**)ext4_argv, &st, true, LOG_KLOG,
110 true, nullptr, nullptr, 0);
111 }
112 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700113
114 static bool IsBlockDevice(const struct mntent& mntent) {
115 return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
116 }
117
118 static bool IsEmulatedDevice(const struct mntent& mntent) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700119 return android::base::StartsWith(mntent.mnt_fsname, "/data/");
Keun-young Park8d01f632017-03-13 11:54:47 -0700120 }
121
122 private:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700123 bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
124
125 bool IsExt4() const { return mnt_type_ == "ext4"; }
126
Keun-young Park8d01f632017-03-13 11:54:47 -0700127 std::string mnt_fsname_;
128 std::string mnt_dir_;
129 std::string mnt_type_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700130 std::string mnt_opts_;
Keun-young Park8d01f632017-03-13 11:54:47 -0700131};
132
133// Turn off backlight while we are performing power down cleanup activities.
134static void TurnOffBacklight() {
135 static constexpr char OFF[] = "0";
136
137 android::base::WriteStringToFile(OFF, "/sys/class/leds/lcd-backlight/brightness");
138
139 static const char backlightDir[] = "/sys/class/backlight";
140 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(backlightDir), closedir);
141 if (!dir) {
142 return;
143 }
144
145 struct dirent* dp;
146 while ((dp = readdir(dir.get())) != nullptr) {
147 if (((dp->d_type != DT_DIR) && (dp->d_type != DT_LNK)) || (dp->d_name[0] == '.')) {
148 continue;
149 }
150
151 std::string fileName = StringPrintf("%s/%s/brightness", backlightDir, dp->d_name);
152 android::base::WriteStringToFile(OFF, fileName);
153 }
154}
155
Keun-young Park8d01f632017-03-13 11:54:47 -0700156static void ShutdownVold() {
157 const char* vdc_argv[] = {"/system/bin/vdc", "volume", "shutdown"};
158 int status;
159 android_fork_execvp_ext(arraysize(vdc_argv), (char**)vdc_argv, &status, true, LOG_KLOG, true,
160 nullptr, nullptr, 0);
161}
162
163static void LogShutdownTime(UmountStat stat, Timer* t) {
164 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration_ms()) << ":" << stat;
165}
166
Luis Hector Chavez519e5f02017-06-29 09:50:30 -0700167// Determines whether the system is capable of rebooting. This is conservative,
168// so if any of the attempts to determine this fail, it will still return true.
169static bool IsRebootCapable() {
170 if (!CAP_IS_SUPPORTED(CAP_SYS_BOOT)) {
171 PLOG(WARNING) << "CAP_SYS_BOOT is not supported";
172 return true;
173 }
174
175 ScopedCaps caps(cap_get_proc());
176 if (!caps) {
177 PLOG(WARNING) << "cap_get_proc() failed";
178 return true;
179 }
180
181 cap_flag_value_t value = CAP_SET;
182 if (cap_get_flag(caps.get(), CAP_SYS_BOOT, CAP_EFFECTIVE, &value) != 0) {
183 PLOG(WARNING) << "cap_get_flag(CAP_SYS_BOOT, EFFECTIVE) failed";
184 return true;
185 }
186 return value == CAP_SET;
187}
188
Keun-young Park8d01f632017-03-13 11:54:47 -0700189static void __attribute__((noreturn))
190RebootSystem(unsigned int cmd, const std::string& rebootTarget) {
Keun-young Park3cd8c6f2017-03-23 15:33:16 -0700191 LOG(INFO) << "Reboot ending, jumping to kernel";
Luis Hector Chavez519e5f02017-06-29 09:50:30 -0700192
193 if (!IsRebootCapable()) {
194 // On systems where init does not have the capability of rebooting the
195 // device, just exit cleanly.
196 exit(0);
197 }
198
Keun-young Park8d01f632017-03-13 11:54:47 -0700199 switch (cmd) {
200 case ANDROID_RB_POWEROFF:
201 reboot(RB_POWER_OFF);
202 break;
203
204 case ANDROID_RB_RESTART2:
205 syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2,
206 LINUX_REBOOT_CMD_RESTART2, rebootTarget.c_str());
207 break;
208
209 case ANDROID_RB_THERMOFF:
210 reboot(RB_POWER_OFF);
211 break;
212 }
213 // In normal case, reboot should not return.
214 PLOG(FATAL) << "reboot call returned";
215 abort();
216}
217
218/* Find all read+write block devices and emulated devices in /proc/mounts
219 * and add them to correpsponding list.
220 */
221static bool FindPartitionsToUmount(std::vector<MountEntry>* blockDevPartitions,
Keun-young Park2ba5c812017-03-29 12:54:40 -0700222 std::vector<MountEntry>* emulatedPartitions, bool dump) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700223 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "r"), endmntent);
224 if (fp == nullptr) {
225 PLOG(ERROR) << "Failed to open /proc/mounts";
226 return false;
227 }
228 mntent* mentry;
229 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700230 if (dump) {
231 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
232 << mentry->mnt_opts << " type " << mentry->mnt_type;
233 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
234 blockDevPartitions->emplace(blockDevPartitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700235 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700236 emulatedPartitions->emplace(emulatedPartitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700237 }
238 }
239 return true;
240}
241
Keun-young Park1663e972017-04-21 17:29:26 -0700242static void DumpUmountDebuggingInfo(bool dump_all) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700243 int status;
244 if (!security_getenforce()) {
245 LOG(INFO) << "Run lsof";
246 const char* lsof_argv[] = {"/system/bin/lsof"};
247 android_fork_execvp_ext(arraysize(lsof_argv), (char**)lsof_argv, &status, true, LOG_KLOG,
248 true, nullptr, nullptr, 0);
Keun-young Park8d01f632017-03-13 11:54:47 -0700249 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700250 FindPartitionsToUmount(nullptr, nullptr, true);
Keun-young Park1663e972017-04-21 17:29:26 -0700251 if (dump_all) {
252 // dump current tasks, this log can be lengthy, so only dump with dump_all
253 android::base::WriteStringToFile("t", "/proc/sysrq-trigger");
254 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700255}
256
257static UmountStat UmountPartitions(int timeoutMs) {
258 Timer t;
259 UmountStat stat = UMOUNT_STAT_TIMEOUT;
260 int retry = 0;
261 /* data partition needs all pending writes to be completed and all emulated partitions
262 * umounted.If the current waiting is not good enough, give
263 * up and leave it to e2fsck after reboot to fix it.
264 */
265 while (true) {
266 std::vector<MountEntry> block_devices;
267 std::vector<MountEntry> emulated_devices;
268 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
269 return UMOUNT_STAT_ERROR;
270 }
271 if (block_devices.size() == 0) {
272 stat = UMOUNT_STAT_SUCCESS;
273 break;
274 }
275 if ((timeoutMs < t.duration_ms()) && retry > 0) { // try umount at least once
276 stat = UMOUNT_STAT_TIMEOUT;
277 break;
278 }
279 if (emulated_devices.size() > 0 &&
280 std::all_of(emulated_devices.begin(), emulated_devices.end(),
281 [](auto& entry) { return entry.Umount(); })) {
282 sync();
283 }
284 for (auto& entry : block_devices) {
285 entry.Umount();
286 }
287 retry++;
288 std::this_thread::sleep_for(100ms);
289 }
290 return stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700291}
292
Keun-young Park3ee0df92017-03-27 11:21:09 -0700293static void KillAllProcesses() { android::base::WriteStringToFile("i", "/proc/sysrq-trigger"); }
294
Keun-young Park8d01f632017-03-13 11:54:47 -0700295/* Try umounting all emulated file systems R/W block device cfile systems.
296 * This will just try umount and give it up if it fails.
297 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
298 * and necessary check can be done at the next reboot.
299 * For safer shutdown, caller needs to make sure that
300 * all processes / emulated partition for the target fs are all cleaned-up.
301 *
302 * return true when umount was successful. false when timed out.
303 */
Keun-young Park3ee0df92017-03-27 11:21:09 -0700304static UmountStat TryUmountAndFsck(bool runFsck, int timeoutMs) {
305 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700306 std::vector<MountEntry> block_devices;
307 std::vector<MountEntry> emulated_devices;
Keun-young Park8d01f632017-03-13 11:54:47 -0700308
309 TurnOffBacklight(); // this part can take time. save power.
310
Keun-young Park2ba5c812017-03-29 12:54:40 -0700311 if (runFsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700312 return UMOUNT_STAT_ERROR;
313 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700314
315 UmountStat stat = UmountPartitions(timeoutMs - t.duration_ms());
316 if (stat != UMOUNT_STAT_SUCCESS) {
317 LOG(INFO) << "umount timeout, last resort, kill all and try";
Keun-young Park1663e972017-04-21 17:29:26 -0700318 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(false);
Keun-young Park3ee0df92017-03-27 11:21:09 -0700319 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700320 // even if it succeeds, still it is timeout and do not run fsck with all processes killed
321 UmountPartitions(0);
Keun-young Park1663e972017-04-21 17:29:26 -0700322 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(true);
Keun-young Park8d01f632017-03-13 11:54:47 -0700323 }
324
Keun-young Park2ba5c812017-03-29 12:54:40 -0700325 if (stat == UMOUNT_STAT_SUCCESS && runFsck) {
326 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
327 // and should not affect reboot time.
328 for (auto& entry : block_devices) {
329 entry.DoFsck();
330 }
331 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700332 return stat;
333}
334
Keun-young Park8d01f632017-03-13 11:54:47 -0700335static void __attribute__((noreturn)) DoThermalOff() {
336 LOG(WARNING) << "Thermal system shutdown";
Keun-young Park2ba5c812017-03-29 12:54:40 -0700337 sync();
Keun-young Park8d01f632017-03-13 11:54:47 -0700338 RebootSystem(ANDROID_RB_THERMOFF, "");
339 abort();
340}
341
342void DoReboot(unsigned int cmd, const std::string& reason, const std::string& rebootTarget,
343 bool runFsck) {
344 Timer t;
Keun-young Park3cd8c6f2017-03-23 15:33:16 -0700345 LOG(INFO) << "Reboot start, reason: " << reason << ", rebootTarget: " << rebootTarget;
Keun-young Park8d01f632017-03-13 11:54:47 -0700346
Todd Poynorfc827be2017-04-13 15:17:24 -0700347 android::base::WriteStringToFile(StringPrintf("%s\n", reason.c_str()), LAST_REBOOT_REASON_FILE,
348 S_IRUSR | S_IWUSR, AID_SYSTEM, AID_SYSTEM);
Keun-young Park8d01f632017-03-13 11:54:47 -0700349
350 if (cmd == ANDROID_RB_THERMOFF) { // do not wait if it is thermal
351 DoThermalOff();
352 abort();
353 }
Keun-young Parkaa08ea42017-03-23 13:27:28 -0700354
Keun-young Park7feab682017-04-26 12:36:14 -0700355 constexpr unsigned int shutdownTimeoutDefault = 6;
Keun-young Parkc4ffa5c2017-03-28 09:41:36 -0700356 unsigned int shutdownTimeout = shutdownTimeoutDefault;
357 if (SHUTDOWN_ZERO_TIMEOUT) { // eng build
358 shutdownTimeout = 0;
359 } else {
360 shutdownTimeout =
361 android::base::GetUintProperty("ro.build.shutdown_timeout", shutdownTimeoutDefault);
362 }
Tom Cherryccf23532017-03-28 16:40:41 -0700363 LOG(INFO) << "Shutdown timeout: " << shutdownTimeout;
Keun-young Parkaa08ea42017-03-23 13:27:28 -0700364
Keun-young Park7830d592017-03-27 16:07:02 -0700365 // keep debugging tools until non critical ones are all gone.
366 const std::set<std::string> kill_after_apps{"tombstoned", "logd", "adbd"};
367 // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
Keun-young Park7264bee2017-05-18 13:28:32 -0700368 const std::set<std::string> to_starts{"watchdogd", "vold", "ueventd"};
Keun-young Park7830d592017-03-27 16:07:02 -0700369 ServiceManager::GetInstance().ForEachService([&kill_after_apps, &to_starts](Service* s) {
370 if (kill_after_apps.count(s->name())) {
371 s->SetShutdownCritical();
372 } else if (to_starts.count(s->name())) {
373 s->Start();
374 s->SetShutdownCritical();
Keun-young Park8d01f632017-03-13 11:54:47 -0700375 }
Keun-young Park7830d592017-03-27 16:07:02 -0700376 });
377
378 Service* bootAnim = ServiceManager::GetInstance().FindServiceByName("bootanim");
379 Service* surfaceFlinger = ServiceManager::GetInstance().FindServiceByName("surfaceflinger");
380 if (bootAnim != nullptr && surfaceFlinger != nullptr && surfaceFlinger->IsRunning()) {
Keun-young Park7830d592017-03-27 16:07:02 -0700381 ServiceManager::GetInstance().ForEachServiceInClass("animation", [](Service* s) {
Keun-young Park7830d592017-03-27 16:07:02 -0700382 s->SetShutdownCritical(); // will not check animation class separately
383 });
Keun-young Park8d01f632017-03-13 11:54:47 -0700384 }
Keun-young Park7830d592017-03-27 16:07:02 -0700385
Keun-young Park8d01f632017-03-13 11:54:47 -0700386 // optional shutdown step
387 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Keun-young Park3ee0df92017-03-27 11:21:09 -0700388 if (shutdownTimeout > 0) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700389 LOG(INFO) << "terminating init services";
Keun-young Park8d01f632017-03-13 11:54:47 -0700390
391 // Ask all services to terminate except shutdown critical ones.
392 ServiceManager::GetInstance().ForEachService([](Service* s) {
393 if (!s->IsShutdownCritical()) s->Terminate();
394 });
395
396 int service_count = 0;
Keun-young Park3ee0df92017-03-27 11:21:09 -0700397 // Up to half as long as shutdownTimeout or 3 seconds, whichever is lower.
398 unsigned int terminationWaitTimeout = std::min<unsigned int>((shutdownTimeout + 1) / 2, 3);
399 while (t.duration_s() < terminationWaitTimeout) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700400 ServiceManager::GetInstance().ReapAnyOutstandingChildren();
401
402 service_count = 0;
403 ServiceManager::GetInstance().ForEachService([&service_count](Service* s) {
404 // Count the number of services running except shutdown critical.
405 // Exclude the console as it will ignore the SIGTERM signal
406 // and not exit.
407 // Note: SVC_CONSOLE actually means "requires console" but
408 // it is only used by the shell.
409 if (!s->IsShutdownCritical() && s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
410 service_count++;
411 }
412 });
413
414 if (service_count == 0) {
415 // All terminable services terminated. We can exit early.
416 break;
417 }
418
419 // Wait a bit before recounting the number or running services.
420 std::this_thread::sleep_for(50ms);
421 }
422 LOG(INFO) << "Terminating running services took " << t
423 << " with remaining services:" << service_count;
424 }
425
426 // minimum safety steps before restarting
427 // 2. kill all services except ones that are necessary for the shutdown sequence.
Keun-young Park2ba5c812017-03-29 12:54:40 -0700428 ServiceManager::GetInstance().ForEachService([](Service* s) {
429 if (!s->IsShutdownCritical()) s->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700430 });
431 ServiceManager::GetInstance().ReapAnyOutstandingChildren();
432
433 // 3. send volume shutdown to vold
434 Service* voldService = ServiceManager::GetInstance().FindServiceByName("vold");
435 if (voldService != nullptr && voldService->IsRunning()) {
436 ShutdownVold();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700437 voldService->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700438 } else {
439 LOG(INFO) << "vold not running, skipping vold shutdown";
440 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700441 // logcat stopped here
442 ServiceManager::GetInstance().ForEachService([&kill_after_apps](Service* s) {
443 if (kill_after_apps.count(s->name())) s->Stop();
444 });
Keun-young Park8d01f632017-03-13 11:54:47 -0700445 // 4. sync, try umount, and optionally run fsck for user shutdown
Keun-young Park2ba5c812017-03-29 12:54:40 -0700446 sync();
Keun-young Park3ee0df92017-03-27 11:21:09 -0700447 UmountStat stat = TryUmountAndFsck(runFsck, shutdownTimeout * 1000 - t.duration_ms());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700448 // Follow what linux shutdown is doing: one more sync with little bit delay
449 sync();
450 std::this_thread::sleep_for(100ms);
Keun-young Park8d01f632017-03-13 11:54:47 -0700451 LogShutdownTime(stat, &t);
452 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
453 RebootSystem(cmd, rebootTarget);
454 abort();
455}
Tom Cherry98ad32a2017-04-17 16:34:20 -0700456
457bool HandlePowerctlMessage(const std::string& command) {
458 unsigned int cmd = 0;
459 std::vector<std::string> cmd_params = android::base::Split(command, ",");
Tom Cherry98ad32a2017-04-17 16:34:20 -0700460 std::string reboot_target = "";
461 bool run_fsck = false;
462 bool command_invalid = false;
463
464 if (cmd_params.size() > 3) {
465 command_invalid = true;
466 } else if (cmd_params[0] == "shutdown") {
467 cmd = ANDROID_RB_POWEROFF;
468 if (cmd_params.size() == 2 && cmd_params[1] == "userrequested") {
469 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
470 // Run fsck once the file system is remounted in read-only mode.
471 run_fsck = true;
Tom Cherry98ad32a2017-04-17 16:34:20 -0700472 }
473 } else if (cmd_params[0] == "reboot") {
474 cmd = ANDROID_RB_RESTART2;
475 if (cmd_params.size() >= 2) {
476 reboot_target = cmd_params[1];
477 // When rebooting to the bootloader notify the bootloader writing
478 // also the BCB.
479 if (reboot_target == "bootloader") {
480 std::string err;
481 if (!write_reboot_bootloader(&err)) {
482 LOG(ERROR) << "reboot-bootloader: Error writing "
483 "bootloader_message: "
484 << err;
485 }
486 }
487 // If there is an additional bootloader parameter, pass it along
488 if (cmd_params.size() == 3) {
489 reboot_target += "," + cmd_params[2];
490 }
491 }
492 } else if (command == "thermal-shutdown") { // no additional parameter allowed
493 cmd = ANDROID_RB_THERMOFF;
Wei Wangeeab4912017-06-27 22:08:45 -0700494 // Do not queue "shutdown" trigger since we want to shutdown immediately
495 DoReboot(cmd, command, reboot_target, run_fsck);
496 return true;
Tom Cherry98ad32a2017-04-17 16:34:20 -0700497 } else {
498 command_invalid = true;
499 }
500 if (command_invalid) {
501 LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
502 return false;
503 }
504
Wei Wangeeab4912017-06-27 22:08:45 -0700505 LOG(INFO) << "Clear action queue and start shutdown trigger";
506 ActionManager::GetInstance().ClearQueue();
507 // Queue shutdown trigger first
508 ActionManager::GetInstance().QueueEventTrigger("shutdown");
509 // Queue built-in shutdown_done
510 auto shutdown_handler = [cmd, command, reboot_target,
511 run_fsck](const std::vector<std::string>&) {
512 DoReboot(cmd, command, reboot_target, run_fsck);
513 return 0;
514 };
515 ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
516
517 // Skip wait for prop if it is in progress
518 ResetWaitForProp();
519
520 // Skip wait for exec if it is in progress
521 if (ServiceManager::GetInstance().IsWaitingForExec()) {
522 ServiceManager::GetInstance().ClearExecWait();
523 }
524
Tom Cherry98ad32a2017-04-17 16:34:20 -0700525 return true;
526}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700527
528} // namespace init
529} // namespace android