blob: 03ed55a1b7c6ef7799f2f18071815eccb4e643b1 [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>
Tom Cherryc9fec9d2018-02-15 14:26:58 -080023#include <semaphore.h>
Luis Hector Chavez519e5f02017-06-29 09:50:30 -070024#include <sys/capability.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070025#include <sys/cdefs.h>
Keun-young Park2ba5c812017-03-29 12:54:40 -070026#include <sys/ioctl.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070027#include <sys/mount.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070028#include <sys/reboot.h>
29#include <sys/stat.h>
30#include <sys/syscall.h>
31#include <sys/types.h>
32#include <sys/wait.h>
33
34#include <memory>
Keun-young Park7830d592017-03-27 16:07:02 -070035#include <set>
Keun-young Park8d01f632017-03-13 11:54:47 -070036#include <thread>
37#include <vector>
38
Tom Cherryede0d532017-07-06 14:20:11 -070039#include <android-base/chrono_utils.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070040#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070041#include <android-base/logging.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070042#include <android-base/macros.h>
Tom Cherryccf23532017-03-28 16:40:41 -070043#include <android-base/properties.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070044#include <android-base/stringprintf.h>
45#include <android-base/strings.h>
Keun-young Park2ba5c812017-03-29 12:54:40 -070046#include <android-base/unique_fd.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070047#include <bootloader_message/bootloader_message.h>
48#include <cutils/android_reboot.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070049#include <fs_mgr.h>
50#include <logwrap/logwrap.h>
Todd Poynorfc827be2017-04-13 15:17:24 -070051#include <private/android_filesystem_config.h>
Tom Cherry0c8d6d22017-08-10 12:22:44 -070052#include <selinux/selinux.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070053
Tom Cherry7fd3bc22018-02-13 15:36:14 -080054#include "action_manager.h"
Luis Hector Chavez519e5f02017-06-29 09:50:30 -070055#include "capabilities.h"
Wei Wangeeab4912017-06-27 22:08:45 -070056#include "init.h"
Keun-young Park7830d592017-03-27 16:07:02 -070057#include "property_service.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070058#include "service.h"
Luis Hector Chavez9f97f472017-09-06 13:43:57 -070059#include "sigchld_handler.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070060
Mark Salyzyn62909822017-10-09 09:27:16 -070061using android::base::Split;
Keun-young Park8d01f632017-03-13 11:54:47 -070062using android::base::StringPrintf;
Tom Cherryede0d532017-07-06 14:20:11 -070063using android::base::Timer;
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 }
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800148 service->Start();
Keun-young Park8d01f632017-03-13 11:54:47 -0700149}
150
Keun-young Park8d01f632017-03-13 11:54:47 -0700151static void ShutdownVold() {
152 const char* vdc_argv[] = {"/system/bin/vdc", "volume", "shutdown"};
153 int status;
154 android_fork_execvp_ext(arraysize(vdc_argv), (char**)vdc_argv, &status, true, LOG_KLOG, true,
155 nullptr, nullptr, 0);
156}
157
158static void LogShutdownTime(UmountStat stat, Timer* t) {
Tom Cherryede0d532017-07-06 14:20:11 -0700159 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration().count()) << ":"
160 << stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700161}
162
Luis Hector Chavez9f97f472017-09-06 13:43:57 -0700163bool IsRebootCapable() {
Luis Hector Chavez519e5f02017-06-29 09:50:30 -0700164 if (!CAP_IS_SUPPORTED(CAP_SYS_BOOT)) {
165 PLOG(WARNING) << "CAP_SYS_BOOT is not supported";
166 return true;
167 }
168
169 ScopedCaps caps(cap_get_proc());
170 if (!caps) {
171 PLOG(WARNING) << "cap_get_proc() failed";
172 return true;
173 }
174
175 cap_flag_value_t value = CAP_SET;
176 if (cap_get_flag(caps.get(), CAP_SYS_BOOT, CAP_EFFECTIVE, &value) != 0) {
177 PLOG(WARNING) << "cap_get_flag(CAP_SYS_BOOT, EFFECTIVE) failed";
178 return true;
179 }
180 return value == CAP_SET;
181}
182
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700183void __attribute__((noreturn)) RebootSystem(unsigned int cmd, const std::string& rebootTarget) {
Keun-young Park3cd8c6f2017-03-23 15:33:16 -0700184 LOG(INFO) << "Reboot ending, jumping to kernel";
Luis Hector Chavez519e5f02017-06-29 09:50:30 -0700185
186 if (!IsRebootCapable()) {
187 // On systems where init does not have the capability of rebooting the
188 // device, just exit cleanly.
189 exit(0);
190 }
191
Keun-young Park8d01f632017-03-13 11:54:47 -0700192 switch (cmd) {
193 case ANDROID_RB_POWEROFF:
194 reboot(RB_POWER_OFF);
195 break;
196
197 case ANDROID_RB_RESTART2:
198 syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2,
199 LINUX_REBOOT_CMD_RESTART2, rebootTarget.c_str());
200 break;
201
202 case ANDROID_RB_THERMOFF:
203 reboot(RB_POWER_OFF);
204 break;
205 }
206 // In normal case, reboot should not return.
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700207 PLOG(ERROR) << "reboot call returned";
Keun-young Park8d01f632017-03-13 11:54:47 -0700208 abort();
209}
210
211/* Find all read+write block devices and emulated devices in /proc/mounts
212 * and add them to correpsponding list.
213 */
214static bool FindPartitionsToUmount(std::vector<MountEntry>* blockDevPartitions,
Keun-young Park2ba5c812017-03-29 12:54:40 -0700215 std::vector<MountEntry>* emulatedPartitions, bool dump) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700216 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "r"), endmntent);
217 if (fp == nullptr) {
218 PLOG(ERROR) << "Failed to open /proc/mounts";
219 return false;
220 }
221 mntent* mentry;
222 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700223 if (dump) {
224 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
225 << mentry->mnt_opts << " type " << mentry->mnt_type;
226 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
Keun-young Park6e12b382017-07-17 12:20:33 -0700227 std::string mount_dir(mentry->mnt_dir);
228 // These are R/O partitions changed to R/W after adb remount.
229 // Do not umount them as shutdown critical services may rely on them.
Wei Wanga01c27e2017-07-25 10:52:08 -0700230 if (mount_dir != "/" && mount_dir != "/system" && mount_dir != "/vendor" &&
231 mount_dir != "/oem") {
Keun-young Park6e12b382017-07-17 12:20:33 -0700232 blockDevPartitions->emplace(blockDevPartitions->begin(), *mentry);
233 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700234 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700235 emulatedPartitions->emplace(emulatedPartitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700236 }
237 }
238 return true;
239}
240
Keun-young Park1663e972017-04-21 17:29:26 -0700241static void DumpUmountDebuggingInfo(bool dump_all) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700242 int status;
243 if (!security_getenforce()) {
244 LOG(INFO) << "Run lsof";
245 const char* lsof_argv[] = {"/system/bin/lsof"};
246 android_fork_execvp_ext(arraysize(lsof_argv), (char**)lsof_argv, &status, true, LOG_KLOG,
247 true, nullptr, nullptr, 0);
Keun-young Park8d01f632017-03-13 11:54:47 -0700248 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700249 FindPartitionsToUmount(nullptr, nullptr, true);
Keun-young Park1663e972017-04-21 17:29:26 -0700250 if (dump_all) {
251 // dump current tasks, this log can be lengthy, so only dump with dump_all
252 android::base::WriteStringToFile("t", "/proc/sysrq-trigger");
253 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700254}
255
Tom Cherryede0d532017-07-06 14:20:11 -0700256static UmountStat UmountPartitions(std::chrono::milliseconds timeout) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700257 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700258 /* data partition needs all pending writes to be completed and all emulated partitions
259 * umounted.If the current waiting is not good enough, give
260 * up and leave it to e2fsck after reboot to fix it.
261 */
262 while (true) {
263 std::vector<MountEntry> block_devices;
264 std::vector<MountEntry> emulated_devices;
265 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
266 return UMOUNT_STAT_ERROR;
267 }
268 if (block_devices.size() == 0) {
Wei Wang8c00e422017-08-16 14:01:46 -0700269 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700270 }
Wei Wang8c00e422017-08-16 14:01:46 -0700271 bool unmount_done = true;
272 if (emulated_devices.size() > 0) {
Wei Wang25dc30f2017-10-23 15:32:03 -0700273 for (auto& entry : emulated_devices) {
274 if (!entry.Umount(false)) unmount_done = false;
275 }
Wei Wang8c00e422017-08-16 14:01:46 -0700276 if (unmount_done) {
277 sync();
278 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700279 }
Wei Wang25dc30f2017-10-23 15:32:03 -0700280 for (auto& entry : block_devices) {
281 if (!entry.Umount(timeout == 0ms)) unmount_done = false;
282 }
Wei Wang8c00e422017-08-16 14:01:46 -0700283 if (unmount_done) {
284 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700285 }
Wei Wang8c00e422017-08-16 14:01:46 -0700286 if ((timeout < t.duration())) { // try umount at least once
287 return UMOUNT_STAT_TIMEOUT;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700288 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700289 std::this_thread::sleep_for(100ms);
290 }
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 */
Tom Cherryede0d532017-07-06 14:20:11 -0700304static UmountStat TryUmountAndFsck(bool runFsck, std::chrono::milliseconds timeout) {
Keun-young Park3ee0df92017-03-27 11:21:09 -0700305 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
Keun-young Park2ba5c812017-03-29 12:54:40 -0700309 if (runFsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700310 return UMOUNT_STAT_ERROR;
311 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700312
Tom Cherryede0d532017-07-06 14:20:11 -0700313 UmountStat stat = UmountPartitions(timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700314 if (stat != UMOUNT_STAT_SUCCESS) {
315 LOG(INFO) << "umount timeout, last resort, kill all and try";
Keun-young Parkc59b8222017-07-18 18:52:25 -0700316 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(true);
Keun-young Park3ee0df92017-03-27 11:21:09 -0700317 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700318 // 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 -0700319 UmountStat st = UmountPartitions(0ms);
320 if ((st != UMOUNT_STAT_SUCCESS) && DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(false);
Keun-young Park8d01f632017-03-13 11:54:47 -0700321 }
322
Keun-young Park2ba5c812017-03-29 12:54:40 -0700323 if (stat == UMOUNT_STAT_SUCCESS && runFsck) {
324 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
325 // and should not affect reboot time.
326 for (auto& entry : block_devices) {
327 entry.DoFsck();
328 }
329 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700330 return stat;
331}
332
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800333void RebootThread(unsigned int cmd, std::chrono::milliseconds shutdown_timeout, bool runFsck,
334 sem_t* reboot_semaphore) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700335 Timer t;
Keun-young Park7830d592017-03-27 16:07:02 -0700336 // keep debugging tools until non critical ones are all gone.
337 const std::set<std::string> kill_after_apps{"tombstoned", "logd", "adbd"};
338 // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700339 const std::set<std::string> to_starts{"watchdogd"};
Tom Cherry911b9b12017-07-27 16:20:58 -0700340 for (const auto& s : ServiceList::GetInstance()) {
Keun-young Park7830d592017-03-27 16:07:02 -0700341 if (kill_after_apps.count(s->name())) {
342 s->SetShutdownCritical();
343 } else if (to_starts.count(s->name())) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700344 if (auto result = s->Start(); !result) {
345 LOG(ERROR) << "Could not start shutdown 'to_start' service '" << s->name()
346 << "': " << result.error();
347 }
Keun-young Park7830d592017-03-27 16:07:02 -0700348 s->SetShutdownCritical();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700349 } else if (s->IsShutdownCritical()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700350 // Start shutdown critical service if not started.
351 if (auto result = s->Start(); !result) {
352 LOG(ERROR) << "Could not start shutdown critical service '" << s->name()
353 << "': " << result.error();
354 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700355 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700356 }
Keun-young Park7830d592017-03-27 16:07:02 -0700357
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800358 // remaining operations (specifically fsck) may take a substantial duration
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800359 if (cmd == ANDROID_RB_POWEROFF || cmd == ANDROID_RB_THERMOFF) {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800360 TurnOffBacklight();
361 }
362
Tom Cherry911b9b12017-07-27 16:20:58 -0700363 Service* bootAnim = ServiceList::GetInstance().FindService("bootanim");
364 Service* surfaceFlinger = ServiceList::GetInstance().FindService("surfaceflinger");
Keun-young Park7830d592017-03-27 16:07:02 -0700365 if (bootAnim != nullptr && surfaceFlinger != nullptr && surfaceFlinger->IsRunning()) {
Tom Cherry911b9b12017-07-27 16:20:58 -0700366 // will not check animation class separately
367 for (const auto& service : ServiceList::GetInstance()) {
368 if (service->classnames().count("animation")) service->SetShutdownCritical();
369 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700370 }
Keun-young Park7830d592017-03-27 16:07:02 -0700371
Keun-young Park8d01f632017-03-13 11:54:47 -0700372 // optional shutdown step
373 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Keun-young Park30173872017-07-18 10:58:28 -0700374 if (shutdown_timeout > 0ms) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700375 LOG(INFO) << "terminating init services";
Keun-young Park8d01f632017-03-13 11:54:47 -0700376
377 // Ask all services to terminate except shutdown critical ones.
Tom Cherry911b9b12017-07-27 16:20:58 -0700378 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700379 if (!s->IsShutdownCritical()) s->Terminate();
Tom Cherry911b9b12017-07-27 16:20:58 -0700380 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700381
382 int service_count = 0;
Keun-young Park30173872017-07-18 10:58:28 -0700383 // Only wait up to half of timeout here
384 auto termination_wait_timeout = shutdown_timeout / 2;
Tom Cherryede0d532017-07-06 14:20:11 -0700385 while (t.duration() < termination_wait_timeout) {
Tom Cherryeeee8312017-07-28 15:22:23 -0700386 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700387
388 service_count = 0;
Tom Cherry911b9b12017-07-27 16:20:58 -0700389 for (const auto& s : ServiceList::GetInstance()) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700390 // Count the number of services running except shutdown critical.
391 // Exclude the console as it will ignore the SIGTERM signal
392 // and not exit.
393 // Note: SVC_CONSOLE actually means "requires console" but
394 // it is only used by the shell.
395 if (!s->IsShutdownCritical() && s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
396 service_count++;
397 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700398 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700399
400 if (service_count == 0) {
401 // All terminable services terminated. We can exit early.
402 break;
403 }
404
405 // Wait a bit before recounting the number or running services.
406 std::this_thread::sleep_for(50ms);
407 }
408 LOG(INFO) << "Terminating running services took " << t
409 << " with remaining services:" << service_count;
410 }
411
412 // minimum safety steps before restarting
413 // 2. kill all services except ones that are necessary for the shutdown sequence.
Tom Cherry911b9b12017-07-27 16:20:58 -0700414 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700415 if (!s->IsShutdownCritical()) s->Stop();
Tom Cherry911b9b12017-07-27 16:20:58 -0700416 }
Tom Cherryeeee8312017-07-28 15:22:23 -0700417 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700418
419 // 3. send volume shutdown to vold
Tom Cherry911b9b12017-07-27 16:20:58 -0700420 Service* voldService = ServiceList::GetInstance().FindService("vold");
Keun-young Park8d01f632017-03-13 11:54:47 -0700421 if (voldService != nullptr && voldService->IsRunning()) {
422 ShutdownVold();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700423 voldService->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700424 } else {
425 LOG(INFO) << "vold not running, skipping vold shutdown";
426 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700427 // logcat stopped here
Tom Cherry911b9b12017-07-27 16:20:58 -0700428 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700429 if (kill_after_apps.count(s->name())) s->Stop();
Tom Cherry911b9b12017-07-27 16:20:58 -0700430 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700431 // 4. sync, try umount, and optionally run fsck for user shutdown
Keun-young Park2ba5c812017-03-29 12:54:40 -0700432 sync();
Tom Cherryede0d532017-07-06 14:20:11 -0700433 UmountStat stat = TryUmountAndFsck(runFsck, shutdown_timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700434 // Follow what linux shutdown is doing: one more sync with little bit delay
435 sync();
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800436 if (cmd != ANDROID_RB_THERMOFF) std::this_thread::sleep_for(100ms);
Keun-young Park8d01f632017-03-13 11:54:47 -0700437 LogShutdownTime(stat, &t);
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800438
439 if (reboot_semaphore != nullptr) {
440 sem_post(reboot_semaphore);
441 }
442}
443
444void RunRebootThread(unsigned int cmd, std::chrono::milliseconds shutdown_timeout) {
445 sem_t reboot_semaphore;
446 timespec shutdown_timeout_timespec;
447
448 if (sem_init(&reboot_semaphore, false, 0) == -1 ||
449 clock_gettime(CLOCK_REALTIME, &shutdown_timeout_timespec) == -1) {
450 // These should never fail, but if they do, skip the graceful reboot and reboot immediately.
451 return;
452 }
453
454 std::thread reboot_thread(&RebootThread, cmd, shutdown_timeout, false, &reboot_semaphore);
455 reboot_thread.detach();
456
457 // One extra second than the timeout passed to the thread as there is a final Umount pass
458 // after the timeout is reached.
459 shutdown_timeout_timespec.tv_sec += 1 + shutdown_timeout.count() / 1000;
460
461 int sem_return = 0;
462 while ((sem_return = sem_timedwait(&reboot_semaphore, &shutdown_timeout_timespec)) == -1 &&
463 errno == EINTR) {
464 }
465
466 if (sem_return == -1) {
467 LOG(ERROR) << "Reboot thread timed out";
468 }
469}
470
471void DoReboot(unsigned int cmd, const std::string& reason, const std::string& rebootTarget,
472 bool runFsck) {
473 LOG(INFO) << "Reboot start, reason: " << reason << ", rebootTarget: " << rebootTarget;
474
475 // Ensure last reboot reason is reduced to canonical
476 // alias reported in bootloader or system boot reason.
477 size_t skip = 0;
478 std::vector<std::string> reasons = Split(reason, ",");
479 if (reasons.size() >= 2 && reasons[0] == "reboot" &&
480 (reasons[1] == "recovery" || reasons[1] == "bootloader" || reasons[1] == "cold" ||
481 reasons[1] == "hard" || reasons[1] == "warm")) {
482 skip = strlen("reboot,");
483 }
484 property_set(LAST_REBOOT_REASON_PROPERTY, reason.c_str() + skip);
485 sync();
486
487 auto shutdown_timeout = 0ms;
488 if (!SHUTDOWN_ZERO_TIMEOUT) {
489 if (cmd == ANDROID_RB_THERMOFF) {
490 constexpr auto kThermalShutdownTimeout = 1s;
491 shutdown_timeout = kThermalShutdownTimeout;
492 } else {
493 constexpr unsigned int kShutdownTimeoutDefault = 6;
494 auto shutdown_timeout_property = android::base::GetUintProperty(
495 "ro.build.shutdown_timeout", kShutdownTimeoutDefault);
496 shutdown_timeout = std::chrono::seconds(shutdown_timeout_property);
497 }
498 }
499 LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " ms";
500
501 if (runFsck) {
502 RebootThread(cmd, shutdown_timeout, true, nullptr);
503 } else {
504 RunRebootThread(cmd, shutdown_timeout);
505 }
506
Keun-young Park8d01f632017-03-13 11:54:47 -0700507 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
508 RebootSystem(cmd, rebootTarget);
509 abort();
510}
Tom Cherry98ad32a2017-04-17 16:34:20 -0700511
512bool HandlePowerctlMessage(const std::string& command) {
513 unsigned int cmd = 0;
Mark Salyzyn62909822017-10-09 09:27:16 -0700514 std::vector<std::string> cmd_params = Split(command, ",");
Tom Cherry98ad32a2017-04-17 16:34:20 -0700515 std::string reboot_target = "";
516 bool run_fsck = false;
517 bool command_invalid = false;
518
519 if (cmd_params.size() > 3) {
520 command_invalid = true;
521 } else if (cmd_params[0] == "shutdown") {
522 cmd = ANDROID_RB_POWEROFF;
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700523 if (cmd_params.size() == 2) {
524 if (cmd_params[1] == "userrequested") {
525 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
526 // Run fsck once the file system is remounted in read-only mode.
527 run_fsck = true;
528 } else if (cmd_params[1] == "thermal") {
Mark Salyzynbfd05b62017-09-26 11:10:12 -0700529 // Turn off sources of heat immediately.
530 TurnOffBacklight();
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700531 // run_fsck is false to avoid delay
532 cmd = ANDROID_RB_THERMOFF;
533 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700534 }
535 } else if (cmd_params[0] == "reboot") {
536 cmd = ANDROID_RB_RESTART2;
537 if (cmd_params.size() >= 2) {
538 reboot_target = cmd_params[1];
539 // When rebooting to the bootloader notify the bootloader writing
540 // also the BCB.
541 if (reboot_target == "bootloader") {
542 std::string err;
543 if (!write_reboot_bootloader(&err)) {
544 LOG(ERROR) << "reboot-bootloader: Error writing "
545 "bootloader_message: "
546 << err;
547 }
548 }
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