blob: f08d855df9e6ad0a558f56a0dc16458aaf4376da [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>
Jaegeuk Kim2aedc822018-11-20 13:27:06 -080023#include <linux/loop.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>
Jaegeuk Kim2aedc822018-11-20 13:27:06 -080027#include <sys/swap.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070028#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
Tom Cherry7fd3bc22018-02-13 15:36:14 -080053#include "action_manager.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"
Tom Cherry44aceed2018-08-03 13:36:18 -070056#include "reboot_utils.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070057#include "service.h"
Luis Hector Chavez9f97f472017-09-06 13:43:57 -070058#include "sigchld_handler.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070059
Mark Salyzyn62909822017-10-09 09:27:16 -070060using android::base::Split;
Keun-young Park8d01f632017-03-13 11:54:47 -070061using android::base::StringPrintf;
Tom Cherryede0d532017-07-06 14:20:11 -070062using android::base::Timer;
Jaegeuk Kim2aedc822018-11-20 13:27:06 -080063using android::base::unique_fd;
Keun-young Park8d01f632017-03-13 11:54:47 -070064
Tom Cherry81f5d3e2017-06-22 12:53:17 -070065namespace android {
66namespace init {
67
Keun-young Park8d01f632017-03-13 11:54:47 -070068// represents umount status during reboot / shutdown.
69enum UmountStat {
70 /* umount succeeded. */
71 UMOUNT_STAT_SUCCESS = 0,
72 /* umount was not run. */
73 UMOUNT_STAT_SKIPPED = 1,
74 /* umount failed with timeout. */
75 UMOUNT_STAT_TIMEOUT = 2,
76 /* could not run due to error */
77 UMOUNT_STAT_ERROR = 3,
78 /* not used by init but reserved for other part to use this to represent the
79 the state where umount status before reboot is not found / available. */
80 UMOUNT_STAT_NOT_AVAILABLE = 4,
81};
82
83// Utility for struct mntent
84class MountEntry {
85 public:
Keun-young Park2ba5c812017-03-29 12:54:40 -070086 explicit MountEntry(const mntent& entry)
Keun-young Park8d01f632017-03-13 11:54:47 -070087 : mnt_fsname_(entry.mnt_fsname),
88 mnt_dir_(entry.mnt_dir),
89 mnt_type_(entry.mnt_type),
Keun-young Park2ba5c812017-03-29 12:54:40 -070090 mnt_opts_(entry.mnt_opts) {}
Keun-young Park8d01f632017-03-13 11:54:47 -070091
Jaegeuk Kim0f04f722017-09-25 10:55:39 -070092 bool Umount(bool force) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -080093 LOG(INFO) << "Unmounting " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Jaegeuk Kim0f04f722017-09-25 10:55:39 -070094 int r = umount2(mnt_dir_.c_str(), force ? MNT_FORCE : 0);
Keun-young Park2ba5c812017-03-29 12:54:40 -070095 if (r == 0) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -080096 LOG(INFO) << "Umounted " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Keun-young Park2ba5c812017-03-29 12:54:40 -070097 return true;
98 } else {
Tom Cherryc9fec9d2018-02-15 14:26:58 -080099 PLOG(WARNING) << "Cannot umount " << mnt_fsname_ << ":" << mnt_dir_ << " opts "
Keun-young Park2ba5c812017-03-29 12:54:40 -0700100 << mnt_opts_;
101 return false;
102 }
103 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700104
Keun-young Park2ba5c812017-03-29 12:54:40 -0700105 void DoFsck() {
106 int st;
107 if (IsF2Fs()) {
108 const char* f2fs_argv[] = {
109 "/system/bin/fsck.f2fs", "-f", mnt_fsname_.c_str(),
110 };
111 android_fork_execvp_ext(arraysize(f2fs_argv), (char**)f2fs_argv, &st, true, LOG_KLOG,
112 true, nullptr, nullptr, 0);
113 } else if (IsExt4()) {
114 const char* ext4_argv[] = {
115 "/system/bin/e2fsck", "-f", "-y", mnt_fsname_.c_str(),
116 };
117 android_fork_execvp_ext(arraysize(ext4_argv), (char**)ext4_argv, &st, true, LOG_KLOG,
118 true, nullptr, nullptr, 0);
119 }
120 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700121
122 static bool IsBlockDevice(const struct mntent& mntent) {
123 return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
124 }
125
126 static bool IsEmulatedDevice(const struct mntent& mntent) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700127 return android::base::StartsWith(mntent.mnt_fsname, "/data/");
Keun-young Park8d01f632017-03-13 11:54:47 -0700128 }
129
130 private:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700131 bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
132
133 bool IsExt4() const { return mnt_type_ == "ext4"; }
134
Keun-young Park8d01f632017-03-13 11:54:47 -0700135 std::string mnt_fsname_;
136 std::string mnt_dir_;
137 std::string mnt_type_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700138 std::string mnt_opts_;
Keun-young Park8d01f632017-03-13 11:54:47 -0700139};
140
141// Turn off backlight while we are performing power down cleanup activities.
142static void TurnOffBacklight() {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800143 Service* service = ServiceList::GetInstance().FindService("blank_screen");
144 if (service == nullptr) {
145 LOG(WARNING) << "cannot find blank_screen in TurnOffBacklight";
Keun-young Park8d01f632017-03-13 11:54:47 -0700146 return;
147 }
Tom Cherryd9872642018-10-11 10:38:05 -0700148 if (auto result = service->Start(); !result) {
149 LOG(WARNING) << "Could not start blank_screen service: " << result.error();
150 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700151}
152
Keun-young Park8d01f632017-03-13 11:54:47 -0700153static void ShutdownVold() {
154 const char* vdc_argv[] = {"/system/bin/vdc", "volume", "shutdown"};
155 int status;
156 android_fork_execvp_ext(arraysize(vdc_argv), (char**)vdc_argv, &status, true, LOG_KLOG, true,
157 nullptr, nullptr, 0);
158}
159
160static void LogShutdownTime(UmountStat stat, Timer* t) {
Tom Cherryede0d532017-07-06 14:20:11 -0700161 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration().count()) << ":"
162 << stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700163}
164
Keun-young Park8d01f632017-03-13 11:54:47 -0700165/* Find all read+write block devices and emulated devices in /proc/mounts
166 * and add them to correpsponding list.
167 */
168static bool FindPartitionsToUmount(std::vector<MountEntry>* blockDevPartitions,
Keun-young Park2ba5c812017-03-29 12:54:40 -0700169 std::vector<MountEntry>* emulatedPartitions, bool dump) {
Tom Cherryf274e782018-10-03 13:13:41 -0700170 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
Keun-young Park8d01f632017-03-13 11:54:47 -0700171 if (fp == nullptr) {
172 PLOG(ERROR) << "Failed to open /proc/mounts";
173 return false;
174 }
175 mntent* mentry;
176 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700177 if (dump) {
178 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
179 << mentry->mnt_opts << " type " << mentry->mnt_type;
180 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
Keun-young Park6e12b382017-07-17 12:20:33 -0700181 std::string mount_dir(mentry->mnt_dir);
182 // These are R/O partitions changed to R/W after adb remount.
183 // Do not umount them as shutdown critical services may rely on them.
Wei Wanga01c27e2017-07-25 10:52:08 -0700184 if (mount_dir != "/" && mount_dir != "/system" && mount_dir != "/vendor" &&
185 mount_dir != "/oem") {
Keun-young Park6e12b382017-07-17 12:20:33 -0700186 blockDevPartitions->emplace(blockDevPartitions->begin(), *mentry);
187 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700188 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700189 emulatedPartitions->emplace(emulatedPartitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700190 }
191 }
192 return true;
193}
194
Keun-young Park1663e972017-04-21 17:29:26 -0700195static void DumpUmountDebuggingInfo(bool dump_all) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700196 int status;
197 if (!security_getenforce()) {
198 LOG(INFO) << "Run lsof";
199 const char* lsof_argv[] = {"/system/bin/lsof"};
200 android_fork_execvp_ext(arraysize(lsof_argv), (char**)lsof_argv, &status, true, LOG_KLOG,
201 true, nullptr, nullptr, 0);
Keun-young Park8d01f632017-03-13 11:54:47 -0700202 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700203 FindPartitionsToUmount(nullptr, nullptr, true);
Keun-young Park1663e972017-04-21 17:29:26 -0700204 if (dump_all) {
205 // dump current tasks, this log can be lengthy, so only dump with dump_all
206 android::base::WriteStringToFile("t", "/proc/sysrq-trigger");
207 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700208}
209
Tom Cherryede0d532017-07-06 14:20:11 -0700210static UmountStat UmountPartitions(std::chrono::milliseconds timeout) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700211 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700212 /* data partition needs all pending writes to be completed and all emulated partitions
213 * umounted.If the current waiting is not good enough, give
214 * up and leave it to e2fsck after reboot to fix it.
215 */
216 while (true) {
217 std::vector<MountEntry> block_devices;
218 std::vector<MountEntry> emulated_devices;
219 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
220 return UMOUNT_STAT_ERROR;
221 }
222 if (block_devices.size() == 0) {
Wei Wang8c00e422017-08-16 14:01:46 -0700223 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700224 }
Wei Wang8c00e422017-08-16 14:01:46 -0700225 bool unmount_done = true;
226 if (emulated_devices.size() > 0) {
Wei Wang25dc30f2017-10-23 15:32:03 -0700227 for (auto& entry : emulated_devices) {
228 if (!entry.Umount(false)) unmount_done = false;
229 }
Wei Wang8c00e422017-08-16 14:01:46 -0700230 if (unmount_done) {
231 sync();
232 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700233 }
Wei Wang25dc30f2017-10-23 15:32:03 -0700234 for (auto& entry : block_devices) {
235 if (!entry.Umount(timeout == 0ms)) unmount_done = false;
236 }
Wei Wang8c00e422017-08-16 14:01:46 -0700237 if (unmount_done) {
238 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700239 }
Wei Wang8c00e422017-08-16 14:01:46 -0700240 if ((timeout < t.duration())) { // try umount at least once
241 return UMOUNT_STAT_TIMEOUT;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700242 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700243 std::this_thread::sleep_for(100ms);
244 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700245}
246
Keun-young Park3ee0df92017-03-27 11:21:09 -0700247static void KillAllProcesses() { android::base::WriteStringToFile("i", "/proc/sysrq-trigger"); }
248
Keun-young Park8d01f632017-03-13 11:54:47 -0700249/* Try umounting all emulated file systems R/W block device cfile systems.
250 * This will just try umount and give it up if it fails.
251 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
252 * and necessary check can be done at the next reboot.
253 * For safer shutdown, caller needs to make sure that
254 * all processes / emulated partition for the target fs are all cleaned-up.
255 *
256 * return true when umount was successful. false when timed out.
257 */
Tom Cherryede0d532017-07-06 14:20:11 -0700258static UmountStat TryUmountAndFsck(bool runFsck, std::chrono::milliseconds timeout) {
Keun-young Park3ee0df92017-03-27 11:21:09 -0700259 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700260 std::vector<MountEntry> block_devices;
261 std::vector<MountEntry> emulated_devices;
Keun-young Park8d01f632017-03-13 11:54:47 -0700262
Keun-young Park2ba5c812017-03-29 12:54:40 -0700263 if (runFsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700264 return UMOUNT_STAT_ERROR;
265 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700266
Tom Cherryede0d532017-07-06 14:20:11 -0700267 UmountStat stat = UmountPartitions(timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700268 if (stat != UMOUNT_STAT_SUCCESS) {
269 LOG(INFO) << "umount timeout, last resort, kill all and try";
Keun-young Parkc59b8222017-07-18 18:52:25 -0700270 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(true);
Keun-young Park3ee0df92017-03-27 11:21:09 -0700271 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700272 // 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 -0700273 UmountStat st = UmountPartitions(0ms);
274 if ((st != UMOUNT_STAT_SUCCESS) && DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(false);
Keun-young Park8d01f632017-03-13 11:54:47 -0700275 }
276
Keun-young Park2ba5c812017-03-29 12:54:40 -0700277 if (stat == UMOUNT_STAT_SUCCESS && runFsck) {
278 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
279 // and should not affect reboot time.
280 for (auto& entry : block_devices) {
281 entry.DoFsck();
282 }
283 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700284 return stat;
285}
286
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800287// zram is able to use backing device on top of a loopback device.
288// In order to unmount /data successfully, we have to kill the loopback device first
289#define ZRAM_DEVICE "/dev/block/zram0"
290#define ZRAM_RESET "/sys/block/zram0/reset"
291#define ZRAM_BACK_DEV "/sys/block/zram0/backing_dev"
292static void KillZramBackingDevice() {
293 std::string backing_dev;
294 if (!android::base::ReadFileToString(ZRAM_BACK_DEV, &backing_dev)) return;
295
296 if (!android::base::StartsWith(backing_dev, "/dev/block/loop")) return;
297
298 // cut the last "\n"
299 backing_dev.erase(backing_dev.length() - 1);
300
301 // shutdown zram handle
302 Timer swap_timer;
303 LOG(INFO) << "swapoff() start...";
304 if (swapoff(ZRAM_DEVICE) == -1) {
305 LOG(ERROR) << "zram_backing_dev: swapoff (" << backing_dev << ")" << " failed";
306 return;
307 }
308 LOG(INFO) << "swapoff() took " << swap_timer;;
309
310 if (!android::base::WriteStringToFile("1", ZRAM_RESET)) {
311 LOG(ERROR) << "zram_backing_dev: reset (" << backing_dev << ")" << " failed";
312 return;
313 }
314
315 // clear loopback device
316 unique_fd loop(TEMP_FAILURE_RETRY(open(backing_dev.c_str(), O_RDWR | O_CLOEXEC)));
317 if (loop.get() < 0) {
318 LOG(ERROR) << "zram_backing_dev: open(" << backing_dev << ")" << " failed";
319 return;
320 }
321
322 if (ioctl(loop.get(), LOOP_CLR_FD, 0) < 0) {
323 LOG(ERROR) << "zram_backing_dev: loop_clear (" << backing_dev << ")" << " failed";
324 return;
325 }
326 LOG(INFO) << "zram_backing_dev: `" << backing_dev << "` is cleared successfully.";
327}
328
Tom Cherry44aceed2018-08-03 13:36:18 -0700329//* Reboot / shutdown the system.
330// cmd ANDROID_RB_* as defined in android_reboot.h
331// reason Reason string like "reboot", "shutdown,userrequested"
332// rebootTarget Reboot target string like "bootloader". Otherwise, it should be an
333// empty string.
334// runFsck Whether to run fsck after umount is done.
335//
336static void DoReboot(unsigned int cmd, const std::string& reason, const std::string& rebootTarget,
337 bool runFsck) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700338 Timer t;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700339 LOG(INFO) << "Reboot start, reason: " << reason << ", rebootTarget: " << rebootTarget;
340
341 // Ensure last reboot reason is reduced to canonical
342 // alias reported in bootloader or system boot reason.
343 size_t skip = 0;
344 std::vector<std::string> reasons = Split(reason, ",");
345 if (reasons.size() >= 2 && reasons[0] == "reboot" &&
346 (reasons[1] == "recovery" || reasons[1] == "bootloader" || reasons[1] == "cold" ||
347 reasons[1] == "hard" || reasons[1] == "warm")) {
348 skip = strlen("reboot,");
349 }
350 property_set(LAST_REBOOT_REASON_PROPERTY, reason.c_str() + skip);
351 sync();
352
353 bool is_thermal_shutdown = cmd == ANDROID_RB_THERMOFF;
354
355 auto shutdown_timeout = 0ms;
356 if (!SHUTDOWN_ZERO_TIMEOUT) {
Wei Wangb5de0882018-10-09 12:42:06 -0700357 constexpr unsigned int shutdown_timeout_default = 6;
358 constexpr unsigned int max_thermal_shutdown_timeout = 3;
359 auto shutdown_timeout_final = android::base::GetUintProperty("ro.build.shutdown_timeout",
360 shutdown_timeout_default);
361 if (is_thermal_shutdown && shutdown_timeout_final > max_thermal_shutdown_timeout) {
362 shutdown_timeout_final = max_thermal_shutdown_timeout;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700363 }
Wei Wangb5de0882018-10-09 12:42:06 -0700364 shutdown_timeout = std::chrono::seconds(shutdown_timeout_final);
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700365 }
366 LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " ms";
367
Keun-young Park7830d592017-03-27 16:07:02 -0700368 // keep debugging tools until non critical ones are all gone.
369 const std::set<std::string> kill_after_apps{"tombstoned", "logd", "adbd"};
370 // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700371 const std::set<std::string> to_starts{"watchdogd"};
Tom Cherry911b9b12017-07-27 16:20:58 -0700372 for (const auto& s : ServiceList::GetInstance()) {
Keun-young Park7830d592017-03-27 16:07:02 -0700373 if (kill_after_apps.count(s->name())) {
374 s->SetShutdownCritical();
375 } else if (to_starts.count(s->name())) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700376 if (auto result = s->Start(); !result) {
377 LOG(ERROR) << "Could not start shutdown 'to_start' service '" << s->name()
378 << "': " << result.error();
379 }
Keun-young Park7830d592017-03-27 16:07:02 -0700380 s->SetShutdownCritical();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700381 } else if (s->IsShutdownCritical()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700382 // Start shutdown critical service if not started.
383 if (auto result = s->Start(); !result) {
384 LOG(ERROR) << "Could not start shutdown critical service '" << s->name()
385 << "': " << result.error();
386 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700387 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700388 }
Keun-young Park7830d592017-03-27 16:07:02 -0700389
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800390 // remaining operations (specifically fsck) may take a substantial duration
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700391 if (cmd == ANDROID_RB_POWEROFF || is_thermal_shutdown) {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800392 TurnOffBacklight();
393 }
394
Tom Cherry911b9b12017-07-27 16:20:58 -0700395 Service* bootAnim = ServiceList::GetInstance().FindService("bootanim");
396 Service* surfaceFlinger = ServiceList::GetInstance().FindService("surfaceflinger");
Keun-young Park7830d592017-03-27 16:07:02 -0700397 if (bootAnim != nullptr && surfaceFlinger != nullptr && surfaceFlinger->IsRunning()) {
Tom Cherry911b9b12017-07-27 16:20:58 -0700398 // will not check animation class separately
399 for (const auto& service : ServiceList::GetInstance()) {
400 if (service->classnames().count("animation")) service->SetShutdownCritical();
401 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700402 }
Keun-young Park7830d592017-03-27 16:07:02 -0700403
Keun-young Park8d01f632017-03-13 11:54:47 -0700404 // optional shutdown step
405 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Keun-young Park30173872017-07-18 10:58:28 -0700406 if (shutdown_timeout > 0ms) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700407 LOG(INFO) << "terminating init services";
Keun-young Park8d01f632017-03-13 11:54:47 -0700408
409 // Ask all services to terminate except shutdown critical ones.
Tom Cherry911b9b12017-07-27 16:20:58 -0700410 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700411 if (!s->IsShutdownCritical()) s->Terminate();
Tom Cherry911b9b12017-07-27 16:20:58 -0700412 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700413
414 int service_count = 0;
Keun-young Park30173872017-07-18 10:58:28 -0700415 // Only wait up to half of timeout here
416 auto termination_wait_timeout = shutdown_timeout / 2;
Tom Cherryede0d532017-07-06 14:20:11 -0700417 while (t.duration() < termination_wait_timeout) {
Tom Cherryeeee8312017-07-28 15:22:23 -0700418 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700419
420 service_count = 0;
Tom Cherry911b9b12017-07-27 16:20:58 -0700421 for (const auto& s : ServiceList::GetInstance()) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700422 // Count the number of services running except shutdown critical.
423 // Exclude the console as it will ignore the SIGTERM signal
424 // and not exit.
425 // Note: SVC_CONSOLE actually means "requires console" but
426 // it is only used by the shell.
427 if (!s->IsShutdownCritical() && s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
428 service_count++;
429 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700430 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700431
432 if (service_count == 0) {
433 // All terminable services terminated. We can exit early.
434 break;
435 }
436
437 // Wait a bit before recounting the number or running services.
438 std::this_thread::sleep_for(50ms);
439 }
440 LOG(INFO) << "Terminating running services took " << t
441 << " with remaining services:" << service_count;
442 }
443
444 // minimum safety steps before restarting
445 // 2. kill all services except ones that are necessary for the shutdown sequence.
Tom Cherry911b9b12017-07-27 16:20:58 -0700446 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700447 if (!s->IsShutdownCritical()) s->Stop();
Tom Cherry911b9b12017-07-27 16:20:58 -0700448 }
Luis Hector Chavez92c49bc2018-07-27 11:19:25 -0700449 SubcontextTerminate();
Tom Cherryeeee8312017-07-28 15:22:23 -0700450 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700451
452 // 3. send volume shutdown to vold
Tom Cherry911b9b12017-07-27 16:20:58 -0700453 Service* voldService = ServiceList::GetInstance().FindService("vold");
Keun-young Park8d01f632017-03-13 11:54:47 -0700454 if (voldService != nullptr && voldService->IsRunning()) {
455 ShutdownVold();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700456 voldService->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700457 } else {
458 LOG(INFO) << "vold not running, skipping vold shutdown";
459 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700460 // logcat stopped here
Tom Cherry911b9b12017-07-27 16:20:58 -0700461 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700462 if (kill_after_apps.count(s->name())) s->Stop();
Tom Cherry911b9b12017-07-27 16:20:58 -0700463 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700464 // 4. sync, try umount, and optionally run fsck for user shutdown
Tom Cherry1f9d5402018-03-15 10:22:40 -0700465 {
466 Timer sync_timer;
467 LOG(INFO) << "sync() before umount...";
468 sync();
469 LOG(INFO) << "sync() before umount took" << sync_timer;
470 }
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800471 // 5. drop caches and disable zram backing device, if exist
472 KillZramBackingDevice();
473
Tom Cherryede0d532017-07-06 14:20:11 -0700474 UmountStat stat = TryUmountAndFsck(runFsck, shutdown_timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700475 // Follow what linux shutdown is doing: one more sync with little bit delay
Tom Cherry1f9d5402018-03-15 10:22:40 -0700476 {
477 Timer sync_timer;
478 LOG(INFO) << "sync() after umount...";
479 sync();
480 LOG(INFO) << "sync() after umount took" << sync_timer;
481 }
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700482 if (!is_thermal_shutdown) std::this_thread::sleep_for(100ms);
Keun-young Park8d01f632017-03-13 11:54:47 -0700483 LogShutdownTime(stat, &t);
484 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
485 RebootSystem(cmd, rebootTarget);
486 abort();
487}
Tom Cherry98ad32a2017-04-17 16:34:20 -0700488
489bool HandlePowerctlMessage(const std::string& command) {
490 unsigned int cmd = 0;
Mark Salyzyn62909822017-10-09 09:27:16 -0700491 std::vector<std::string> cmd_params = Split(command, ",");
Tom Cherry98ad32a2017-04-17 16:34:20 -0700492 std::string reboot_target = "";
493 bool run_fsck = false;
494 bool command_invalid = false;
495
496 if (cmd_params.size() > 3) {
497 command_invalid = true;
498 } else if (cmd_params[0] == "shutdown") {
499 cmd = ANDROID_RB_POWEROFF;
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700500 if (cmd_params.size() == 2) {
501 if (cmd_params[1] == "userrequested") {
502 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
503 // Run fsck once the file system is remounted in read-only mode.
504 run_fsck = true;
505 } else if (cmd_params[1] == "thermal") {
Mark Salyzynbfd05b62017-09-26 11:10:12 -0700506 // Turn off sources of heat immediately.
507 TurnOffBacklight();
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700508 // run_fsck is false to avoid delay
509 cmd = ANDROID_RB_THERMOFF;
510 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700511 }
512 } else if (cmd_params[0] == "reboot") {
513 cmd = ANDROID_RB_RESTART2;
514 if (cmd_params.size() >= 2) {
515 reboot_target = cmd_params[1];
Hridya Valsaraju54258262018-09-19 21:14:18 -0700516 // adb reboot fastboot should boot into bootloader for devices not
517 // supporting logical partitions.
518 if (reboot_target == "fastboot" &&
Yifan Hong0e0f8182018-11-16 12:49:06 -0800519 !android::base::GetBoolProperty("ro.boot.dynamic_partitions", false)) {
Hridya Valsaraju54258262018-09-19 21:14:18 -0700520 reboot_target = "bootloader";
521 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700522 // When rebooting to the bootloader notify the bootloader writing
523 // also the BCB.
524 if (reboot_target == "bootloader") {
525 std::string err;
526 if (!write_reboot_bootloader(&err)) {
527 LOG(ERROR) << "reboot-bootloader: Error writing "
528 "bootloader_message: "
529 << err;
530 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700531 } else if (reboot_target == "sideload" || reboot_target == "sideload-auto-reboot" ||
532 reboot_target == "fastboot") {
533 std::string arg = reboot_target == "sideload-auto-reboot" ? "sideload_auto_reboot"
534 : reboot_target;
535 const std::vector<std::string> options = {
536 "--" + arg,
537 };
538 std::string err;
539 if (!write_bootloader_message(options, &err)) {
540 LOG(ERROR) << "Failed to set bootloader message: " << err;
541 return false;
542 }
543 reboot_target = "recovery";
Tom Cherry98ad32a2017-04-17 16:34:20 -0700544 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700545
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700546 // If there is an additional parameter, pass it along
547 if ((cmd_params.size() == 3) && cmd_params[2].size()) {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700548 reboot_target += "," + cmd_params[2];
549 }
550 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700551 } else {
552 command_invalid = true;
553 }
554 if (command_invalid) {
555 LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
556 return false;
557 }
558
Wei Wangeeab4912017-06-27 22:08:45 -0700559 LOG(INFO) << "Clear action queue and start shutdown trigger";
560 ActionManager::GetInstance().ClearQueue();
561 // Queue shutdown trigger first
562 ActionManager::GetInstance().QueueEventTrigger("shutdown");
563 // Queue built-in shutdown_done
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700564 auto shutdown_handler = [cmd, command, reboot_target, run_fsck](const BuiltinArguments&) {
Wei Wangeeab4912017-06-27 22:08:45 -0700565 DoReboot(cmd, command, reboot_target, run_fsck);
Tom Cherry557946e2017-08-01 13:50:23 -0700566 return Success();
Wei Wangeeab4912017-06-27 22:08:45 -0700567 };
568 ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
569
570 // Skip wait for prop if it is in progress
571 ResetWaitForProp();
572
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700573 // Clear EXEC flag if there is one pending
Tom Cherry911b9b12017-07-27 16:20:58 -0700574 for (const auto& s : ServiceList::GetInstance()) {
575 s->UnSetExec();
576 }
Wei Wangeeab4912017-06-27 22:08:45 -0700577
Tom Cherry98ad32a2017-04-17 16:34:20 -0700578 return true;
579}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700580
581} // namespace init
582} // namespace android