blob: 969caec9da046da81a36f5d491b77ef7a20f971f [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"
Keun-young Park8d01f632017-03-13 11:54:47 -070056
57using android::base::StringPrintf;
Tom Cherryede0d532017-07-06 14:20:11 -070058using android::base::Timer;
Keun-young Park8d01f632017-03-13 11:54:47 -070059
Tom Cherry81f5d3e2017-06-22 12:53:17 -070060namespace android {
61namespace init {
62
Keun-young Park8d01f632017-03-13 11:54:47 -070063// represents umount status during reboot / shutdown.
64enum UmountStat {
65 /* umount succeeded. */
66 UMOUNT_STAT_SUCCESS = 0,
67 /* umount was not run. */
68 UMOUNT_STAT_SKIPPED = 1,
69 /* umount failed with timeout. */
70 UMOUNT_STAT_TIMEOUT = 2,
71 /* could not run due to error */
72 UMOUNT_STAT_ERROR = 3,
73 /* not used by init but reserved for other part to use this to represent the
74 the state where umount status before reboot is not found / available. */
75 UMOUNT_STAT_NOT_AVAILABLE = 4,
76};
77
78// Utility for struct mntent
79class MountEntry {
80 public:
Keun-young Park2ba5c812017-03-29 12:54:40 -070081 explicit MountEntry(const mntent& entry)
Keun-young Park8d01f632017-03-13 11:54:47 -070082 : mnt_fsname_(entry.mnt_fsname),
83 mnt_dir_(entry.mnt_dir),
84 mnt_type_(entry.mnt_type),
Keun-young Park2ba5c812017-03-29 12:54:40 -070085 mnt_opts_(entry.mnt_opts) {}
Keun-young Park8d01f632017-03-13 11:54:47 -070086
Keun-young Park2ba5c812017-03-29 12:54:40 -070087 bool Umount() {
88 int r = umount2(mnt_dir_.c_str(), 0);
89 if (r == 0) {
90 LOG(INFO) << "umounted " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
91 return true;
92 } else {
93 PLOG(WARNING) << "cannot umount " << mnt_fsname_ << ":" << mnt_dir_ << " opts "
94 << mnt_opts_;
95 return false;
96 }
97 }
Keun-young Park8d01f632017-03-13 11:54:47 -070098
Keun-young Park2ba5c812017-03-29 12:54:40 -070099 void DoFsck() {
100 int st;
101 if (IsF2Fs()) {
102 const char* f2fs_argv[] = {
103 "/system/bin/fsck.f2fs", "-f", mnt_fsname_.c_str(),
104 };
105 android_fork_execvp_ext(arraysize(f2fs_argv), (char**)f2fs_argv, &st, true, LOG_KLOG,
106 true, nullptr, nullptr, 0);
107 } else if (IsExt4()) {
108 const char* ext4_argv[] = {
109 "/system/bin/e2fsck", "-f", "-y", mnt_fsname_.c_str(),
110 };
111 android_fork_execvp_ext(arraysize(ext4_argv), (char**)ext4_argv, &st, true, LOG_KLOG,
112 true, nullptr, nullptr, 0);
113 }
114 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700115
116 static bool IsBlockDevice(const struct mntent& mntent) {
117 return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
118 }
119
120 static bool IsEmulatedDevice(const struct mntent& mntent) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700121 return android::base::StartsWith(mntent.mnt_fsname, "/data/");
Keun-young Park8d01f632017-03-13 11:54:47 -0700122 }
123
124 private:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700125 bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
126
127 bool IsExt4() const { return mnt_type_ == "ext4"; }
128
Keun-young Park8d01f632017-03-13 11:54:47 -0700129 std::string mnt_fsname_;
130 std::string mnt_dir_;
131 std::string mnt_type_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700132 std::string mnt_opts_;
Keun-young Park8d01f632017-03-13 11:54:47 -0700133};
134
135// Turn off backlight while we are performing power down cleanup activities.
136static void TurnOffBacklight() {
137 static constexpr char OFF[] = "0";
138
139 android::base::WriteStringToFile(OFF, "/sys/class/leds/lcd-backlight/brightness");
140
141 static const char backlightDir[] = "/sys/class/backlight";
142 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(backlightDir), closedir);
143 if (!dir) {
144 return;
145 }
146
147 struct dirent* dp;
148 while ((dp = readdir(dir.get())) != nullptr) {
149 if (((dp->d_type != DT_DIR) && (dp->d_type != DT_LNK)) || (dp->d_name[0] == '.')) {
150 continue;
151 }
152
153 std::string fileName = StringPrintf("%s/%s/brightness", backlightDir, dp->d_name);
154 android::base::WriteStringToFile(OFF, fileName);
155 }
156}
157
Keun-young Park8d01f632017-03-13 11:54:47 -0700158static void ShutdownVold() {
159 const char* vdc_argv[] = {"/system/bin/vdc", "volume", "shutdown"};
160 int status;
161 android_fork_execvp_ext(arraysize(vdc_argv), (char**)vdc_argv, &status, true, LOG_KLOG, true,
162 nullptr, nullptr, 0);
163}
164
165static void LogShutdownTime(UmountStat stat, Timer* t) {
Tom Cherryede0d532017-07-06 14:20:11 -0700166 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration().count()) << ":"
167 << stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700168}
169
Luis Hector Chavez519e5f02017-06-29 09:50:30 -0700170// Determines whether the system is capable of rebooting. This is conservative,
171// so if any of the attempts to determine this fail, it will still return true.
172static bool IsRebootCapable() {
173 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
Keun-young Park8d01f632017-03-13 11:54:47 -0700192static void __attribute__((noreturn))
193RebootSystem(unsigned int cmd, const std::string& rebootTarget) {
Keun-young Park3cd8c6f2017-03-23 15:33:16 -0700194 LOG(INFO) << "Reboot ending, jumping to kernel";
Luis Hector Chavez519e5f02017-06-29 09:50:30 -0700195
196 if (!IsRebootCapable()) {
197 // On systems where init does not have the capability of rebooting the
198 // device, just exit cleanly.
199 exit(0);
200 }
201
Keun-young Park8d01f632017-03-13 11:54:47 -0700202 switch (cmd) {
203 case ANDROID_RB_POWEROFF:
204 reboot(RB_POWER_OFF);
205 break;
206
207 case ANDROID_RB_RESTART2:
208 syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2,
209 LINUX_REBOOT_CMD_RESTART2, rebootTarget.c_str());
210 break;
211
212 case ANDROID_RB_THERMOFF:
213 reboot(RB_POWER_OFF);
214 break;
215 }
216 // In normal case, reboot should not return.
217 PLOG(FATAL) << "reboot call returned";
218 abort();
219}
220
221/* Find all read+write block devices and emulated devices in /proc/mounts
222 * and add them to correpsponding list.
223 */
224static bool FindPartitionsToUmount(std::vector<MountEntry>* blockDevPartitions,
Keun-young Park2ba5c812017-03-29 12:54:40 -0700225 std::vector<MountEntry>* emulatedPartitions, bool dump) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700226 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "r"), endmntent);
227 if (fp == nullptr) {
228 PLOG(ERROR) << "Failed to open /proc/mounts";
229 return false;
230 }
231 mntent* mentry;
232 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700233 if (dump) {
234 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
235 << mentry->mnt_opts << " type " << mentry->mnt_type;
236 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
237 blockDevPartitions->emplace(blockDevPartitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700238 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700239 emulatedPartitions->emplace(emulatedPartitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700240 }
241 }
242 return true;
243}
244
Keun-young Park1663e972017-04-21 17:29:26 -0700245static void DumpUmountDebuggingInfo(bool dump_all) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700246 int status;
247 if (!security_getenforce()) {
248 LOG(INFO) << "Run lsof";
249 const char* lsof_argv[] = {"/system/bin/lsof"};
250 android_fork_execvp_ext(arraysize(lsof_argv), (char**)lsof_argv, &status, true, LOG_KLOG,
251 true, nullptr, nullptr, 0);
Keun-young Park8d01f632017-03-13 11:54:47 -0700252 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700253 FindPartitionsToUmount(nullptr, nullptr, true);
Keun-young Park1663e972017-04-21 17:29:26 -0700254 if (dump_all) {
255 // dump current tasks, this log can be lengthy, so only dump with dump_all
256 android::base::WriteStringToFile("t", "/proc/sysrq-trigger");
257 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700258}
259
Tom Cherryede0d532017-07-06 14:20:11 -0700260static UmountStat UmountPartitions(std::chrono::milliseconds timeout) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700261 Timer t;
262 UmountStat stat = UMOUNT_STAT_TIMEOUT;
263 int retry = 0;
264 /* data partition needs all pending writes to be completed and all emulated partitions
265 * umounted.If the current waiting is not good enough, give
266 * up and leave it to e2fsck after reboot to fix it.
267 */
268 while (true) {
269 std::vector<MountEntry> block_devices;
270 std::vector<MountEntry> emulated_devices;
271 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
272 return UMOUNT_STAT_ERROR;
273 }
274 if (block_devices.size() == 0) {
275 stat = UMOUNT_STAT_SUCCESS;
276 break;
277 }
Tom Cherryede0d532017-07-06 14:20:11 -0700278 if ((timeout < t.duration()) && retry > 0) { // try umount at least once
Keun-young Park2ba5c812017-03-29 12:54:40 -0700279 stat = UMOUNT_STAT_TIMEOUT;
280 break;
281 }
282 if (emulated_devices.size() > 0 &&
283 std::all_of(emulated_devices.begin(), emulated_devices.end(),
284 [](auto& entry) { return entry.Umount(); })) {
285 sync();
286 }
287 for (auto& entry : block_devices) {
288 entry.Umount();
289 }
290 retry++;
291 std::this_thread::sleep_for(100ms);
292 }
293 return stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700294}
295
Keun-young Park3ee0df92017-03-27 11:21:09 -0700296static void KillAllProcesses() { android::base::WriteStringToFile("i", "/proc/sysrq-trigger"); }
297
Keun-young Park8d01f632017-03-13 11:54:47 -0700298/* Try umounting all emulated file systems R/W block device cfile systems.
299 * This will just try umount and give it up if it fails.
300 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
301 * and necessary check can be done at the next reboot.
302 * For safer shutdown, caller needs to make sure that
303 * all processes / emulated partition for the target fs are all cleaned-up.
304 *
305 * return true when umount was successful. false when timed out.
306 */
Tom Cherryede0d532017-07-06 14:20:11 -0700307static UmountStat TryUmountAndFsck(bool runFsck, std::chrono::milliseconds timeout) {
Keun-young Park3ee0df92017-03-27 11:21:09 -0700308 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700309 std::vector<MountEntry> block_devices;
310 std::vector<MountEntry> emulated_devices;
Keun-young Park8d01f632017-03-13 11:54:47 -0700311
312 TurnOffBacklight(); // this part can take time. save power.
313
Keun-young Park2ba5c812017-03-29 12:54:40 -0700314 if (runFsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700315 return UMOUNT_STAT_ERROR;
316 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700317
Tom Cherryede0d532017-07-06 14:20:11 -0700318 UmountStat stat = UmountPartitions(timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700319 if (stat != UMOUNT_STAT_SUCCESS) {
320 LOG(INFO) << "umount timeout, last resort, kill all and try";
Keun-young Park1663e972017-04-21 17:29:26 -0700321 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(false);
Keun-young Park3ee0df92017-03-27 11:21:09 -0700322 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700323 // even if it succeeds, still it is timeout and do not run fsck with all processes killed
Tom Cherryede0d532017-07-06 14:20:11 -0700324 UmountPartitions(0ms);
Keun-young Park1663e972017-04-21 17:29:26 -0700325 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(true);
Keun-young Park8d01f632017-03-13 11:54:47 -0700326 }
327
Keun-young Park2ba5c812017-03-29 12:54:40 -0700328 if (stat == UMOUNT_STAT_SUCCESS && runFsck) {
329 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
330 // and should not affect reboot time.
331 for (auto& entry : block_devices) {
332 entry.DoFsck();
333 }
334 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700335 return stat;
336}
337
Keun-young Park8d01f632017-03-13 11:54:47 -0700338static void __attribute__((noreturn)) DoThermalOff() {
339 LOG(WARNING) << "Thermal system shutdown";
Keun-young Park2ba5c812017-03-29 12:54:40 -0700340 sync();
Keun-young Park8d01f632017-03-13 11:54:47 -0700341 RebootSystem(ANDROID_RB_THERMOFF, "");
342 abort();
343}
344
345void 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
353 if (cmd == ANDROID_RB_THERMOFF) { // do not wait if it is thermal
354 DoThermalOff();
355 abort();
356 }
Keun-young Parkaa08ea42017-03-23 13:27:28 -0700357
Tom Cherryede0d532017-07-06 14:20:11 -0700358 auto shutdown_timeout = 0s;
359 if (!SHUTDOWN_ZERO_TIMEOUT) {
360 constexpr unsigned int shutdown_timeout_default = 6;
361 auto shutdown_timeout_property =
362 android::base::GetUintProperty("ro.build.shutdown_timeout", shutdown_timeout_default);
363 shutdown_timeout = std::chrono::seconds(shutdown_timeout_property);
Keun-young Parkc4ffa5c2017-03-28 09:41:36 -0700364 }
Tom Cherryede0d532017-07-06 14:20:11 -0700365 LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " seconds";
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"};
Keun-young Park7830d592017-03-27 16:07:02 -0700371 ServiceManager::GetInstance().ForEachService([&kill_after_apps, &to_starts](Service* s) {
372 if (kill_after_apps.count(s->name())) {
373 s->SetShutdownCritical();
374 } else if (to_starts.count(s->name())) {
375 s->Start();
376 s->SetShutdownCritical();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700377 } else if (s->IsShutdownCritical()) {
378 s->Start(); // start shutdown critical service if not started
Keun-young Park8d01f632017-03-13 11:54:47 -0700379 }
Keun-young Park7830d592017-03-27 16:07:02 -0700380 });
381
382 Service* bootAnim = ServiceManager::GetInstance().FindServiceByName("bootanim");
383 Service* surfaceFlinger = ServiceManager::GetInstance().FindServiceByName("surfaceflinger");
384 if (bootAnim != nullptr && surfaceFlinger != nullptr && surfaceFlinger->IsRunning()) {
Keun-young Park7830d592017-03-27 16:07:02 -0700385 ServiceManager::GetInstance().ForEachServiceInClass("animation", [](Service* s) {
Keun-young Park7830d592017-03-27 16:07:02 -0700386 s->SetShutdownCritical(); // will not check animation class separately
387 });
Keun-young Park8d01f632017-03-13 11:54:47 -0700388 }
Keun-young Park7830d592017-03-27 16:07:02 -0700389
Keun-young Park8d01f632017-03-13 11:54:47 -0700390 // optional shutdown step
391 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Tom Cherryede0d532017-07-06 14:20:11 -0700392 if (shutdown_timeout > 0s) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700393 LOG(INFO) << "terminating init services";
Keun-young Park8d01f632017-03-13 11:54:47 -0700394
395 // Ask all services to terminate except shutdown critical ones.
396 ServiceManager::GetInstance().ForEachService([](Service* s) {
397 if (!s->IsShutdownCritical()) s->Terminate();
398 });
399
400 int service_count = 0;
Tom Cherryede0d532017-07-06 14:20:11 -0700401 // Up to half as long as shutdown_timeout or 3 seconds, whichever is lower.
402 auto termination_wait_timeout = std::min((shutdown_timeout + 1s) / 2, 3s);
403 while (t.duration() < termination_wait_timeout) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700404 ServiceManager::GetInstance().ReapAnyOutstandingChildren();
405
406 service_count = 0;
407 ServiceManager::GetInstance().ForEachService([&service_count](Service* s) {
408 // Count the number of services running except shutdown critical.
409 // Exclude the console as it will ignore the SIGTERM signal
410 // and not exit.
411 // Note: SVC_CONSOLE actually means "requires console" but
412 // it is only used by the shell.
413 if (!s->IsShutdownCritical() && s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
414 service_count++;
415 }
416 });
417
418 if (service_count == 0) {
419 // All terminable services terminated. We can exit early.
420 break;
421 }
422
423 // Wait a bit before recounting the number or running services.
424 std::this_thread::sleep_for(50ms);
425 }
426 LOG(INFO) << "Terminating running services took " << t
427 << " with remaining services:" << service_count;
428 }
429
430 // minimum safety steps before restarting
431 // 2. kill all services except ones that are necessary for the shutdown sequence.
Keun-young Park2ba5c812017-03-29 12:54:40 -0700432 ServiceManager::GetInstance().ForEachService([](Service* s) {
433 if (!s->IsShutdownCritical()) s->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700434 });
435 ServiceManager::GetInstance().ReapAnyOutstandingChildren();
436
437 // 3. send volume shutdown to vold
438 Service* voldService = ServiceManager::GetInstance().FindServiceByName("vold");
439 if (voldService != nullptr && voldService->IsRunning()) {
440 ShutdownVold();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700441 voldService->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700442 } else {
443 LOG(INFO) << "vold not running, skipping vold shutdown";
444 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700445 // logcat stopped here
446 ServiceManager::GetInstance().ForEachService([&kill_after_apps](Service* s) {
447 if (kill_after_apps.count(s->name())) s->Stop();
448 });
Keun-young Park8d01f632017-03-13 11:54:47 -0700449 // 4. sync, try umount, and optionally run fsck for user shutdown
Keun-young Park2ba5c812017-03-29 12:54:40 -0700450 sync();
Tom Cherryede0d532017-07-06 14:20:11 -0700451 UmountStat stat = TryUmountAndFsck(runFsck, shutdown_timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700452 // Follow what linux shutdown is doing: one more sync with little bit delay
453 sync();
454 std::this_thread::sleep_for(100ms);
Keun-young Park8d01f632017-03-13 11:54:47 -0700455 LogShutdownTime(stat, &t);
456 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
457 RebootSystem(cmd, rebootTarget);
458 abort();
459}
Tom Cherry98ad32a2017-04-17 16:34:20 -0700460
461bool HandlePowerctlMessage(const std::string& command) {
462 unsigned int cmd = 0;
463 std::vector<std::string> cmd_params = android::base::Split(command, ",");
Tom Cherry98ad32a2017-04-17 16:34:20 -0700464 std::string reboot_target = "";
465 bool run_fsck = false;
466 bool command_invalid = false;
467
468 if (cmd_params.size() > 3) {
469 command_invalid = true;
470 } else if (cmd_params[0] == "shutdown") {
471 cmd = ANDROID_RB_POWEROFF;
472 if (cmd_params.size() == 2 && cmd_params[1] == "userrequested") {
473 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
474 // Run fsck once the file system is remounted in read-only mode.
475 run_fsck = true;
Tom Cherry98ad32a2017-04-17 16:34:20 -0700476 }
477 } else if (cmd_params[0] == "reboot") {
478 cmd = ANDROID_RB_RESTART2;
479 if (cmd_params.size() >= 2) {
480 reboot_target = cmd_params[1];
481 // When rebooting to the bootloader notify the bootloader writing
482 // also the BCB.
483 if (reboot_target == "bootloader") {
484 std::string err;
485 if (!write_reboot_bootloader(&err)) {
486 LOG(ERROR) << "reboot-bootloader: Error writing "
487 "bootloader_message: "
488 << err;
489 }
490 }
491 // If there is an additional bootloader parameter, pass it along
492 if (cmd_params.size() == 3) {
493 reboot_target += "," + cmd_params[2];
494 }
495 }
496 } else if (command == "thermal-shutdown") { // no additional parameter allowed
497 cmd = ANDROID_RB_THERMOFF;
Wei Wangeeab4912017-06-27 22:08:45 -0700498 // Do not queue "shutdown" trigger since we want to shutdown immediately
499 DoReboot(cmd, command, reboot_target, run_fsck);
500 return true;
Tom Cherry98ad32a2017-04-17 16:34:20 -0700501 } else {
502 command_invalid = true;
503 }
504 if (command_invalid) {
505 LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
506 return false;
507 }
508
Wei Wangeeab4912017-06-27 22:08:45 -0700509 LOG(INFO) << "Clear action queue and start shutdown trigger";
510 ActionManager::GetInstance().ClearQueue();
511 // Queue shutdown trigger first
512 ActionManager::GetInstance().QueueEventTrigger("shutdown");
513 // Queue built-in shutdown_done
514 auto shutdown_handler = [cmd, command, reboot_target,
515 run_fsck](const std::vector<std::string>&) {
516 DoReboot(cmd, command, reboot_target, run_fsck);
517 return 0;
518 };
519 ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
520
521 // Skip wait for prop if it is in progress
522 ResetWaitForProp();
523
524 // Skip wait for exec if it is in progress
525 if (ServiceManager::GetInstance().IsWaitingForExec()) {
526 ServiceManager::GetInstance().ClearExecWait();
527 }
528
Tom Cherry98ad32a2017-04-17 16:34:20 -0700529 return true;
530}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700531
532} // namespace init
533} // namespace android