blob: 0aa7810cfe1fd78cd66e4b3943965c50bf987ade [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[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800109 "/system/bin/fsck.f2fs",
110 "-a",
111 mnt_fsname_.c_str(),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700112 };
113 android_fork_execvp_ext(arraysize(f2fs_argv), (char**)f2fs_argv, &st, true, LOG_KLOG,
114 true, nullptr, nullptr, 0);
115 } else if (IsExt4()) {
116 const char* ext4_argv[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800117 "/system/bin/e2fsck",
118 "-y",
119 mnt_fsname_.c_str(),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700120 };
121 android_fork_execvp_ext(arraysize(ext4_argv), (char**)ext4_argv, &st, true, LOG_KLOG,
122 true, nullptr, nullptr, 0);
123 }
124 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700125
126 static bool IsBlockDevice(const struct mntent& mntent) {
127 return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
128 }
129
130 static bool IsEmulatedDevice(const struct mntent& mntent) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700131 return android::base::StartsWith(mntent.mnt_fsname, "/data/");
Keun-young Park8d01f632017-03-13 11:54:47 -0700132 }
133
134 private:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700135 bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
136
137 bool IsExt4() const { return mnt_type_ == "ext4"; }
138
Keun-young Park8d01f632017-03-13 11:54:47 -0700139 std::string mnt_fsname_;
140 std::string mnt_dir_;
141 std::string mnt_type_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700142 std::string mnt_opts_;
Keun-young Park8d01f632017-03-13 11:54:47 -0700143};
144
145// Turn off backlight while we are performing power down cleanup activities.
146static void TurnOffBacklight() {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800147 Service* service = ServiceList::GetInstance().FindService("blank_screen");
148 if (service == nullptr) {
149 LOG(WARNING) << "cannot find blank_screen in TurnOffBacklight";
Keun-young Park8d01f632017-03-13 11:54:47 -0700150 return;
151 }
Tom Cherryd9872642018-10-11 10:38:05 -0700152 if (auto result = service->Start(); !result) {
153 LOG(WARNING) << "Could not start blank_screen service: " << result.error();
154 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700155}
156
Keun-young Park8d01f632017-03-13 11:54:47 -0700157static void ShutdownVold() {
158 const char* vdc_argv[] = {"/system/bin/vdc", "volume", "shutdown"};
159 int status;
160 android_fork_execvp_ext(arraysize(vdc_argv), (char**)vdc_argv, &status, true, LOG_KLOG, true,
161 nullptr, nullptr, 0);
162}
163
164static void LogShutdownTime(UmountStat stat, Timer* t) {
Tom Cherryede0d532017-07-06 14:20:11 -0700165 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration().count()) << ":"
166 << stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700167}
168
Keun-young Park8d01f632017-03-13 11:54:47 -0700169/* Find all read+write block devices and emulated devices in /proc/mounts
170 * and add them to correpsponding list.
171 */
172static bool FindPartitionsToUmount(std::vector<MountEntry>* blockDevPartitions,
Keun-young Park2ba5c812017-03-29 12:54:40 -0700173 std::vector<MountEntry>* emulatedPartitions, bool dump) {
Tom Cherryf274e782018-10-03 13:13:41 -0700174 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
Keun-young Park8d01f632017-03-13 11:54:47 -0700175 if (fp == nullptr) {
176 PLOG(ERROR) << "Failed to open /proc/mounts";
177 return false;
178 }
179 mntent* mentry;
180 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700181 if (dump) {
182 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
183 << mentry->mnt_opts << " type " << mentry->mnt_type;
184 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
Keun-young Park6e12b382017-07-17 12:20:33 -0700185 std::string mount_dir(mentry->mnt_dir);
186 // These are R/O partitions changed to R/W after adb remount.
187 // Do not umount them as shutdown critical services may rely on them.
Wei Wanga01c27e2017-07-25 10:52:08 -0700188 if (mount_dir != "/" && mount_dir != "/system" && mount_dir != "/vendor" &&
189 mount_dir != "/oem") {
Keun-young Park6e12b382017-07-17 12:20:33 -0700190 blockDevPartitions->emplace(blockDevPartitions->begin(), *mentry);
191 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700192 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700193 emulatedPartitions->emplace(emulatedPartitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700194 }
195 }
196 return true;
197}
198
Jonglin Lee28a2c922019-01-15 16:38:44 -0800199static void DumpUmountDebuggingInfo() {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700200 int status;
201 if (!security_getenforce()) {
202 LOG(INFO) << "Run lsof";
203 const char* lsof_argv[] = {"/system/bin/lsof"};
204 android_fork_execvp_ext(arraysize(lsof_argv), (char**)lsof_argv, &status, true, LOG_KLOG,
205 true, nullptr, nullptr, 0);
Keun-young Park8d01f632017-03-13 11:54:47 -0700206 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700207 FindPartitionsToUmount(nullptr, nullptr, true);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800208 // dump current CPU stack traces and uninterruptible tasks
209 android::base::WriteStringToFile("l", "/proc/sysrq-trigger");
210 android::base::WriteStringToFile("w", "/proc/sysrq-trigger");
Keun-young Park2ba5c812017-03-29 12:54:40 -0700211}
212
Tom Cherryede0d532017-07-06 14:20:11 -0700213static UmountStat UmountPartitions(std::chrono::milliseconds timeout) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700214 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700215 /* data partition needs all pending writes to be completed and all emulated partitions
216 * umounted.If the current waiting is not good enough, give
217 * up and leave it to e2fsck after reboot to fix it.
218 */
219 while (true) {
220 std::vector<MountEntry> block_devices;
221 std::vector<MountEntry> emulated_devices;
222 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
223 return UMOUNT_STAT_ERROR;
224 }
225 if (block_devices.size() == 0) {
Wei Wang8c00e422017-08-16 14:01:46 -0700226 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700227 }
Wei Wang8c00e422017-08-16 14:01:46 -0700228 bool unmount_done = true;
229 if (emulated_devices.size() > 0) {
Wei Wang25dc30f2017-10-23 15:32:03 -0700230 for (auto& entry : emulated_devices) {
231 if (!entry.Umount(false)) unmount_done = false;
232 }
Wei Wang8c00e422017-08-16 14:01:46 -0700233 if (unmount_done) {
234 sync();
235 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700236 }
Wei Wang25dc30f2017-10-23 15:32:03 -0700237 for (auto& entry : block_devices) {
238 if (!entry.Umount(timeout == 0ms)) unmount_done = false;
239 }
Wei Wang8c00e422017-08-16 14:01:46 -0700240 if (unmount_done) {
241 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700242 }
Wei Wang8c00e422017-08-16 14:01:46 -0700243 if ((timeout < t.duration())) { // try umount at least once
244 return UMOUNT_STAT_TIMEOUT;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700245 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700246 std::this_thread::sleep_for(100ms);
247 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700248}
249
Keun-young Park3ee0df92017-03-27 11:21:09 -0700250static void KillAllProcesses() { android::base::WriteStringToFile("i", "/proc/sysrq-trigger"); }
251
Keun-young Park8d01f632017-03-13 11:54:47 -0700252/* Try umounting all emulated file systems R/W block device cfile systems.
253 * This will just try umount and give it up if it fails.
254 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
255 * and necessary check can be done at the next reboot.
256 * For safer shutdown, caller needs to make sure that
257 * all processes / emulated partition for the target fs are all cleaned-up.
258 *
259 * return true when umount was successful. false when timed out.
260 */
Tom Cherryede0d532017-07-06 14:20:11 -0700261static UmountStat TryUmountAndFsck(bool runFsck, std::chrono::milliseconds timeout) {
Keun-young Park3ee0df92017-03-27 11:21:09 -0700262 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700263 std::vector<MountEntry> block_devices;
264 std::vector<MountEntry> emulated_devices;
Keun-young Park8d01f632017-03-13 11:54:47 -0700265
Keun-young Park2ba5c812017-03-29 12:54:40 -0700266 if (runFsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700267 return UMOUNT_STAT_ERROR;
268 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700269
Tom Cherryede0d532017-07-06 14:20:11 -0700270 UmountStat stat = UmountPartitions(timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700271 if (stat != UMOUNT_STAT_SUCCESS) {
272 LOG(INFO) << "umount timeout, last resort, kill all and try";
Jonglin Lee28a2c922019-01-15 16:38:44 -0800273 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park3ee0df92017-03-27 11:21:09 -0700274 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700275 // 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 -0700276 UmountStat st = UmountPartitions(0ms);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800277 if ((st != UMOUNT_STAT_SUCCESS) && DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park8d01f632017-03-13 11:54:47 -0700278 }
279
Keun-young Park2ba5c812017-03-29 12:54:40 -0700280 if (stat == UMOUNT_STAT_SUCCESS && runFsck) {
281 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
282 // and should not affect reboot time.
283 for (auto& entry : block_devices) {
284 entry.DoFsck();
285 }
286 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700287 return stat;
288}
289
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800290// zram is able to use backing device on top of a loopback device.
291// In order to unmount /data successfully, we have to kill the loopback device first
292#define ZRAM_DEVICE "/dev/block/zram0"
293#define ZRAM_RESET "/sys/block/zram0/reset"
294#define ZRAM_BACK_DEV "/sys/block/zram0/backing_dev"
295static void KillZramBackingDevice() {
296 std::string backing_dev;
297 if (!android::base::ReadFileToString(ZRAM_BACK_DEV, &backing_dev)) return;
298
299 if (!android::base::StartsWith(backing_dev, "/dev/block/loop")) return;
300
301 // cut the last "\n"
302 backing_dev.erase(backing_dev.length() - 1);
303
304 // shutdown zram handle
305 Timer swap_timer;
306 LOG(INFO) << "swapoff() start...";
307 if (swapoff(ZRAM_DEVICE) == -1) {
308 LOG(ERROR) << "zram_backing_dev: swapoff (" << backing_dev << ")" << " failed";
309 return;
310 }
311 LOG(INFO) << "swapoff() took " << swap_timer;;
312
313 if (!android::base::WriteStringToFile("1", ZRAM_RESET)) {
314 LOG(ERROR) << "zram_backing_dev: reset (" << backing_dev << ")" << " failed";
315 return;
316 }
317
318 // clear loopback device
319 unique_fd loop(TEMP_FAILURE_RETRY(open(backing_dev.c_str(), O_RDWR | O_CLOEXEC)));
320 if (loop.get() < 0) {
321 LOG(ERROR) << "zram_backing_dev: open(" << backing_dev << ")" << " failed";
322 return;
323 }
324
325 if (ioctl(loop.get(), LOOP_CLR_FD, 0) < 0) {
326 LOG(ERROR) << "zram_backing_dev: loop_clear (" << backing_dev << ")" << " failed";
327 return;
328 }
329 LOG(INFO) << "zram_backing_dev: `" << backing_dev << "` is cleared successfully.";
330}
331
Tom Cherry44aceed2018-08-03 13:36:18 -0700332//* Reboot / shutdown the system.
333// cmd ANDROID_RB_* as defined in android_reboot.h
334// reason Reason string like "reboot", "shutdown,userrequested"
335// rebootTarget Reboot target string like "bootloader". Otherwise, it should be an
336// empty string.
337// runFsck Whether to run fsck after umount is done.
338//
339static void DoReboot(unsigned int cmd, const std::string& reason, const std::string& rebootTarget,
340 bool runFsck) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700341 Timer t;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700342 LOG(INFO) << "Reboot start, reason: " << reason << ", rebootTarget: " << rebootTarget;
343
344 // Ensure last reboot reason is reduced to canonical
345 // alias reported in bootloader or system boot reason.
346 size_t skip = 0;
347 std::vector<std::string> reasons = Split(reason, ",");
348 if (reasons.size() >= 2 && reasons[0] == "reboot" &&
349 (reasons[1] == "recovery" || reasons[1] == "bootloader" || reasons[1] == "cold" ||
350 reasons[1] == "hard" || reasons[1] == "warm")) {
351 skip = strlen("reboot,");
352 }
353 property_set(LAST_REBOOT_REASON_PROPERTY, reason.c_str() + skip);
354 sync();
355
356 bool is_thermal_shutdown = cmd == ANDROID_RB_THERMOFF;
357
358 auto shutdown_timeout = 0ms;
359 if (!SHUTDOWN_ZERO_TIMEOUT) {
Wei Wangb5de0882018-10-09 12:42:06 -0700360 constexpr unsigned int shutdown_timeout_default = 6;
361 constexpr unsigned int max_thermal_shutdown_timeout = 3;
362 auto shutdown_timeout_final = android::base::GetUintProperty("ro.build.shutdown_timeout",
363 shutdown_timeout_default);
364 if (is_thermal_shutdown && shutdown_timeout_final > max_thermal_shutdown_timeout) {
365 shutdown_timeout_final = max_thermal_shutdown_timeout;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700366 }
Wei Wangb5de0882018-10-09 12:42:06 -0700367 shutdown_timeout = std::chrono::seconds(shutdown_timeout_final);
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700368 }
369 LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " ms";
370
Keun-young Park7830d592017-03-27 16:07:02 -0700371 // keep debugging tools until non critical ones are all gone.
372 const std::set<std::string> kill_after_apps{"tombstoned", "logd", "adbd"};
373 // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700374 const std::set<std::string> to_starts{"watchdogd"};
Tom Cherry911b9b12017-07-27 16:20:58 -0700375 for (const auto& s : ServiceList::GetInstance()) {
Keun-young Park7830d592017-03-27 16:07:02 -0700376 if (kill_after_apps.count(s->name())) {
377 s->SetShutdownCritical();
378 } else if (to_starts.count(s->name())) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700379 if (auto result = s->Start(); !result) {
380 LOG(ERROR) << "Could not start shutdown 'to_start' service '" << s->name()
381 << "': " << result.error();
382 }
Keun-young Park7830d592017-03-27 16:07:02 -0700383 s->SetShutdownCritical();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700384 } else if (s->IsShutdownCritical()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700385 // Start shutdown critical service if not started.
386 if (auto result = s->Start(); !result) {
387 LOG(ERROR) << "Could not start shutdown critical service '" << s->name()
388 << "': " << result.error();
389 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700390 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700391 }
Keun-young Park7830d592017-03-27 16:07:02 -0700392
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800393 // remaining operations (specifically fsck) may take a substantial duration
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700394 if (cmd == ANDROID_RB_POWEROFF || is_thermal_shutdown) {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800395 TurnOffBacklight();
396 }
397
Tom Cherry911b9b12017-07-27 16:20:58 -0700398 Service* bootAnim = ServiceList::GetInstance().FindService("bootanim");
399 Service* surfaceFlinger = ServiceList::GetInstance().FindService("surfaceflinger");
Keun-young Park7830d592017-03-27 16:07:02 -0700400 if (bootAnim != nullptr && surfaceFlinger != nullptr && surfaceFlinger->IsRunning()) {
Tom Cherry911b9b12017-07-27 16:20:58 -0700401 // will not check animation class separately
402 for (const auto& service : ServiceList::GetInstance()) {
403 if (service->classnames().count("animation")) service->SetShutdownCritical();
404 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700405 }
Keun-young Park7830d592017-03-27 16:07:02 -0700406
Keun-young Park8d01f632017-03-13 11:54:47 -0700407 // optional shutdown step
408 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Keun-young Park30173872017-07-18 10:58:28 -0700409 if (shutdown_timeout > 0ms) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700410 LOG(INFO) << "terminating init services";
Keun-young Park8d01f632017-03-13 11:54:47 -0700411
412 // Ask all services to terminate except shutdown critical ones.
Tom Cherry911b9b12017-07-27 16:20:58 -0700413 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700414 if (!s->IsShutdownCritical()) s->Terminate();
Tom Cherry911b9b12017-07-27 16:20:58 -0700415 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700416
417 int service_count = 0;
Keun-young Park30173872017-07-18 10:58:28 -0700418 // Only wait up to half of timeout here
419 auto termination_wait_timeout = shutdown_timeout / 2;
Tom Cherryede0d532017-07-06 14:20:11 -0700420 while (t.duration() < termination_wait_timeout) {
Tom Cherryeeee8312017-07-28 15:22:23 -0700421 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700422
423 service_count = 0;
Tom Cherry911b9b12017-07-27 16:20:58 -0700424 for (const auto& s : ServiceList::GetInstance()) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700425 // Count the number of services running except shutdown critical.
426 // Exclude the console as it will ignore the SIGTERM signal
427 // and not exit.
428 // Note: SVC_CONSOLE actually means "requires console" but
429 // it is only used by the shell.
430 if (!s->IsShutdownCritical() && s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
431 service_count++;
432 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700433 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700434
435 if (service_count == 0) {
436 // All terminable services terminated. We can exit early.
437 break;
438 }
439
440 // Wait a bit before recounting the number or running services.
441 std::this_thread::sleep_for(50ms);
442 }
443 LOG(INFO) << "Terminating running services took " << t
444 << " with remaining services:" << service_count;
445 }
446
447 // minimum safety steps before restarting
448 // 2. kill all services except ones that are necessary for the shutdown sequence.
Tom Cherry911b9b12017-07-27 16:20:58 -0700449 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700450 if (!s->IsShutdownCritical()) s->Stop();
Tom Cherry911b9b12017-07-27 16:20:58 -0700451 }
Luis Hector Chavez92c49bc2018-07-27 11:19:25 -0700452 SubcontextTerminate();
Tom Cherryeeee8312017-07-28 15:22:23 -0700453 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700454
455 // 3. send volume shutdown to vold
Tom Cherry911b9b12017-07-27 16:20:58 -0700456 Service* voldService = ServiceList::GetInstance().FindService("vold");
Keun-young Park8d01f632017-03-13 11:54:47 -0700457 if (voldService != nullptr && voldService->IsRunning()) {
458 ShutdownVold();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700459 voldService->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700460 } else {
461 LOG(INFO) << "vold not running, skipping vold shutdown";
462 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700463 // logcat stopped here
Tom Cherry911b9b12017-07-27 16:20:58 -0700464 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700465 if (kill_after_apps.count(s->name())) s->Stop();
Tom Cherry911b9b12017-07-27 16:20:58 -0700466 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700467 // 4. sync, try umount, and optionally run fsck for user shutdown
Tom Cherry1f9d5402018-03-15 10:22:40 -0700468 {
469 Timer sync_timer;
470 LOG(INFO) << "sync() before umount...";
471 sync();
472 LOG(INFO) << "sync() before umount took" << sync_timer;
473 }
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800474 // 5. drop caches and disable zram backing device, if exist
475 KillZramBackingDevice();
476
Tom Cherryede0d532017-07-06 14:20:11 -0700477 UmountStat stat = TryUmountAndFsck(runFsck, shutdown_timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700478 // Follow what linux shutdown is doing: one more sync with little bit delay
Tom Cherry1f9d5402018-03-15 10:22:40 -0700479 {
480 Timer sync_timer;
481 LOG(INFO) << "sync() after umount...";
482 sync();
483 LOG(INFO) << "sync() after umount took" << sync_timer;
484 }
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700485 if (!is_thermal_shutdown) std::this_thread::sleep_for(100ms);
Keun-young Park8d01f632017-03-13 11:54:47 -0700486 LogShutdownTime(stat, &t);
487 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
488 RebootSystem(cmd, rebootTarget);
489 abort();
490}
Tom Cherry98ad32a2017-04-17 16:34:20 -0700491
492bool HandlePowerctlMessage(const std::string& command) {
493 unsigned int cmd = 0;
Mark Salyzyn62909822017-10-09 09:27:16 -0700494 std::vector<std::string> cmd_params = Split(command, ",");
Tom Cherry98ad32a2017-04-17 16:34:20 -0700495 std::string reboot_target = "";
496 bool run_fsck = false;
497 bool command_invalid = false;
498
499 if (cmd_params.size() > 3) {
500 command_invalid = true;
501 } else if (cmd_params[0] == "shutdown") {
502 cmd = ANDROID_RB_POWEROFF;
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700503 if (cmd_params.size() == 2) {
504 if (cmd_params[1] == "userrequested") {
505 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
506 // Run fsck once the file system is remounted in read-only mode.
507 run_fsck = true;
508 } else if (cmd_params[1] == "thermal") {
Mark Salyzynbfd05b62017-09-26 11:10:12 -0700509 // Turn off sources of heat immediately.
510 TurnOffBacklight();
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700511 // run_fsck is false to avoid delay
512 cmd = ANDROID_RB_THERMOFF;
513 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700514 }
515 } else if (cmd_params[0] == "reboot") {
516 cmd = ANDROID_RB_RESTART2;
517 if (cmd_params.size() >= 2) {
518 reboot_target = cmd_params[1];
Hridya Valsaraju54258262018-09-19 21:14:18 -0700519 // adb reboot fastboot should boot into bootloader for devices not
520 // supporting logical partitions.
521 if (reboot_target == "fastboot" &&
Yifan Hong0e0f8182018-11-16 12:49:06 -0800522 !android::base::GetBoolProperty("ro.boot.dynamic_partitions", false)) {
Hridya Valsaraju54258262018-09-19 21:14:18 -0700523 reboot_target = "bootloader";
524 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700525 // When rebooting to the bootloader notify the bootloader writing
526 // also the BCB.
527 if (reboot_target == "bootloader") {
528 std::string err;
529 if (!write_reboot_bootloader(&err)) {
530 LOG(ERROR) << "reboot-bootloader: Error writing "
531 "bootloader_message: "
532 << err;
533 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700534 } else if (reboot_target == "sideload" || reboot_target == "sideload-auto-reboot" ||
535 reboot_target == "fastboot") {
536 std::string arg = reboot_target == "sideload-auto-reboot" ? "sideload_auto_reboot"
537 : reboot_target;
538 const std::vector<std::string> options = {
539 "--" + arg,
540 };
541 std::string err;
542 if (!write_bootloader_message(options, &err)) {
543 LOG(ERROR) << "Failed to set bootloader message: " << err;
544 return false;
545 }
546 reboot_target = "recovery";
Tom Cherry98ad32a2017-04-17 16:34:20 -0700547 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700548
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700549 // If there is an additional parameter, pass it along
550 if ((cmd_params.size() == 3) && cmd_params[2].size()) {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700551 reboot_target += "," + cmd_params[2];
552 }
553 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700554 } else {
555 command_invalid = true;
556 }
557 if (command_invalid) {
558 LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
559 return false;
560 }
561
Wei Wangeeab4912017-06-27 22:08:45 -0700562 LOG(INFO) << "Clear action queue and start shutdown trigger";
563 ActionManager::GetInstance().ClearQueue();
564 // Queue shutdown trigger first
565 ActionManager::GetInstance().QueueEventTrigger("shutdown");
566 // Queue built-in shutdown_done
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700567 auto shutdown_handler = [cmd, command, reboot_target, run_fsck](const BuiltinArguments&) {
Wei Wangeeab4912017-06-27 22:08:45 -0700568 DoReboot(cmd, command, reboot_target, run_fsck);
Tom Cherry557946e2017-08-01 13:50:23 -0700569 return Success();
Wei Wangeeab4912017-06-27 22:08:45 -0700570 };
571 ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
572
573 // Skip wait for prop if it is in progress
574 ResetWaitForProp();
575
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700576 // Clear EXEC flag if there is one pending
Tom Cherry911b9b12017-07-27 16:20:58 -0700577 for (const auto& s : ServiceList::GetInstance()) {
578 s->UnSetExec();
579 }
Wei Wangeeab4912017-06-27 22:08:45 -0700580
Tom Cherry98ad32a2017-04-17 16:34:20 -0700581 return true;
582}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700583
584} // namespace init
585} // namespace android