blob: b0b5b546d91070c7b00395d8a3d07e11ef145b54 [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>
Jaegeuk Kim2aedc822018-11-20 13:27:06 -080022#include <linux/loop.h>
josephjangaaddf282019-04-16 18:46:24 +080023#include <mntent.h>
24#include <semaphore.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/stat.h>
josephjangaaddf282019-04-16 18:46:24 +080029#include <sys/swap.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070030#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/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"
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070058#include "service_list.h"
Luis Hector Chavez9f97f472017-09-06 13:43:57 -070059#include "sigchld_handler.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070060
josephjangaaddf282019-04-16 18:46:24 +080061#define PROC_SYSRQ "/proc/sysrq-trigger"
62
Tom Cherry4f4cacc2019-01-08 10:39:00 -080063using android::base::GetBoolProperty;
Mark Salyzyn62909822017-10-09 09:27:16 -070064using android::base::Split;
Tom Cherryede0d532017-07-06 14:20:11 -070065using android::base::Timer;
Jaegeuk Kim2aedc822018-11-20 13:27:06 -080066using android::base::unique_fd;
josephjangaaddf282019-04-16 18:46:24 +080067using android::base::WriteStringToFile;
Keun-young Park8d01f632017-03-13 11:54:47 -070068
Tom Cherry81f5d3e2017-06-22 12:53:17 -070069namespace android {
70namespace init {
71
Keun-young Park8d01f632017-03-13 11:54:47 -070072// represents umount status during reboot / shutdown.
73enum UmountStat {
74 /* umount succeeded. */
75 UMOUNT_STAT_SUCCESS = 0,
76 /* umount was not run. */
77 UMOUNT_STAT_SKIPPED = 1,
78 /* umount failed with timeout. */
79 UMOUNT_STAT_TIMEOUT = 2,
80 /* could not run due to error */
81 UMOUNT_STAT_ERROR = 3,
82 /* not used by init but reserved for other part to use this to represent the
83 the state where umount status before reboot is not found / available. */
84 UMOUNT_STAT_NOT_AVAILABLE = 4,
85};
86
87// Utility for struct mntent
88class MountEntry {
89 public:
Keun-young Park2ba5c812017-03-29 12:54:40 -070090 explicit MountEntry(const mntent& entry)
Keun-young Park8d01f632017-03-13 11:54:47 -070091 : mnt_fsname_(entry.mnt_fsname),
92 mnt_dir_(entry.mnt_dir),
93 mnt_type_(entry.mnt_type),
Keun-young Park2ba5c812017-03-29 12:54:40 -070094 mnt_opts_(entry.mnt_opts) {}
Keun-young Park8d01f632017-03-13 11:54:47 -070095
Jaegeuk Kim0f04f722017-09-25 10:55:39 -070096 bool Umount(bool force) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -080097 LOG(INFO) << "Unmounting " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Jaegeuk Kim0f04f722017-09-25 10:55:39 -070098 int r = umount2(mnt_dir_.c_str(), force ? MNT_FORCE : 0);
Keun-young Park2ba5c812017-03-29 12:54:40 -070099 if (r == 0) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800100 LOG(INFO) << "Umounted " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700101 return true;
102 } else {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800103 PLOG(WARNING) << "Cannot umount " << mnt_fsname_ << ":" << mnt_dir_ << " opts "
Keun-young Park2ba5c812017-03-29 12:54:40 -0700104 << mnt_opts_;
105 return false;
106 }
107 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700108
Keun-young Park2ba5c812017-03-29 12:54:40 -0700109 void DoFsck() {
110 int st;
111 if (IsF2Fs()) {
112 const char* f2fs_argv[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800113 "/system/bin/fsck.f2fs",
114 "-a",
115 mnt_fsname_.c_str(),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700116 };
117 android_fork_execvp_ext(arraysize(f2fs_argv), (char**)f2fs_argv, &st, true, LOG_KLOG,
118 true, nullptr, nullptr, 0);
119 } else if (IsExt4()) {
120 const char* ext4_argv[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800121 "/system/bin/e2fsck",
122 "-y",
123 mnt_fsname_.c_str(),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700124 };
125 android_fork_execvp_ext(arraysize(ext4_argv), (char**)ext4_argv, &st, true, LOG_KLOG,
126 true, nullptr, nullptr, 0);
127 }
128 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700129
130 static bool IsBlockDevice(const struct mntent& mntent) {
131 return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
132 }
133
134 static bool IsEmulatedDevice(const struct mntent& mntent) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700135 return android::base::StartsWith(mntent.mnt_fsname, "/data/");
Keun-young Park8d01f632017-03-13 11:54:47 -0700136 }
137
138 private:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700139 bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
140
141 bool IsExt4() const { return mnt_type_ == "ext4"; }
142
Keun-young Park8d01f632017-03-13 11:54:47 -0700143 std::string mnt_fsname_;
144 std::string mnt_dir_;
145 std::string mnt_type_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700146 std::string mnt_opts_;
Keun-young Park8d01f632017-03-13 11:54:47 -0700147};
148
149// Turn off backlight while we are performing power down cleanup activities.
150static void TurnOffBacklight() {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800151 Service* service = ServiceList::GetInstance().FindService("blank_screen");
152 if (service == nullptr) {
153 LOG(WARNING) << "cannot find blank_screen in TurnOffBacklight";
Keun-young Park8d01f632017-03-13 11:54:47 -0700154 return;
155 }
Tom Cherryd9872642018-10-11 10:38:05 -0700156 if (auto result = service->Start(); !result) {
157 LOG(WARNING) << "Could not start blank_screen service: " << result.error();
158 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700159}
160
Keun-young Park8d01f632017-03-13 11:54:47 -0700161static void ShutdownVold() {
162 const char* vdc_argv[] = {"/system/bin/vdc", "volume", "shutdown"};
163 int status;
164 android_fork_execvp_ext(arraysize(vdc_argv), (char**)vdc_argv, &status, true, LOG_KLOG, true,
165 nullptr, nullptr, 0);
166}
167
168static void LogShutdownTime(UmountStat stat, Timer* t) {
Tom Cherryede0d532017-07-06 14:20:11 -0700169 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration().count()) << ":"
170 << stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700171}
172
Keun-young Park8d01f632017-03-13 11:54:47 -0700173/* Find all read+write block devices and emulated devices in /proc/mounts
174 * and add them to correpsponding list.
175 */
176static bool FindPartitionsToUmount(std::vector<MountEntry>* blockDevPartitions,
Keun-young Park2ba5c812017-03-29 12:54:40 -0700177 std::vector<MountEntry>* emulatedPartitions, bool dump) {
Tom Cherryf274e782018-10-03 13:13:41 -0700178 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
Keun-young Park8d01f632017-03-13 11:54:47 -0700179 if (fp == nullptr) {
180 PLOG(ERROR) << "Failed to open /proc/mounts";
181 return false;
182 }
183 mntent* mentry;
184 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700185 if (dump) {
186 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
187 << mentry->mnt_opts << " type " << mentry->mnt_type;
188 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
Keun-young Park6e12b382017-07-17 12:20:33 -0700189 std::string mount_dir(mentry->mnt_dir);
190 // These are R/O partitions changed to R/W after adb remount.
191 // Do not umount them as shutdown critical services may rely on them.
Wei Wanga01c27e2017-07-25 10:52:08 -0700192 if (mount_dir != "/" && mount_dir != "/system" && mount_dir != "/vendor" &&
193 mount_dir != "/oem") {
Keun-young Park6e12b382017-07-17 12:20:33 -0700194 blockDevPartitions->emplace(blockDevPartitions->begin(), *mentry);
195 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700196 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700197 emulatedPartitions->emplace(emulatedPartitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700198 }
199 }
200 return true;
201}
202
Jonglin Lee28a2c922019-01-15 16:38:44 -0800203static void DumpUmountDebuggingInfo() {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700204 int status;
205 if (!security_getenforce()) {
206 LOG(INFO) << "Run lsof";
207 const char* lsof_argv[] = {"/system/bin/lsof"};
208 android_fork_execvp_ext(arraysize(lsof_argv), (char**)lsof_argv, &status, true, LOG_KLOG,
209 true, nullptr, nullptr, 0);
Keun-young Park8d01f632017-03-13 11:54:47 -0700210 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700211 FindPartitionsToUmount(nullptr, nullptr, true);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800212 // dump current CPU stack traces and uninterruptible tasks
josephjangaaddf282019-04-16 18:46:24 +0800213 WriteStringToFile("l", PROC_SYSRQ);
214 WriteStringToFile("w", PROC_SYSRQ);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700215}
216
Tom Cherryede0d532017-07-06 14:20:11 -0700217static UmountStat UmountPartitions(std::chrono::milliseconds timeout) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700218 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700219 /* data partition needs all pending writes to be completed and all emulated partitions
220 * umounted.If the current waiting is not good enough, give
221 * up and leave it to e2fsck after reboot to fix it.
222 */
223 while (true) {
224 std::vector<MountEntry> block_devices;
225 std::vector<MountEntry> emulated_devices;
226 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
227 return UMOUNT_STAT_ERROR;
228 }
229 if (block_devices.size() == 0) {
Wei Wang8c00e422017-08-16 14:01:46 -0700230 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700231 }
Wei Wang8c00e422017-08-16 14:01:46 -0700232 bool unmount_done = true;
233 if (emulated_devices.size() > 0) {
Wei Wang25dc30f2017-10-23 15:32:03 -0700234 for (auto& entry : emulated_devices) {
235 if (!entry.Umount(false)) unmount_done = false;
236 }
Wei Wang8c00e422017-08-16 14:01:46 -0700237 if (unmount_done) {
238 sync();
239 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700240 }
Wei Wang25dc30f2017-10-23 15:32:03 -0700241 for (auto& entry : block_devices) {
242 if (!entry.Umount(timeout == 0ms)) unmount_done = false;
243 }
Wei Wang8c00e422017-08-16 14:01:46 -0700244 if (unmount_done) {
245 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700246 }
Wei Wang8c00e422017-08-16 14:01:46 -0700247 if ((timeout < t.duration())) { // try umount at least once
248 return UMOUNT_STAT_TIMEOUT;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700249 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700250 std::this_thread::sleep_for(100ms);
251 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700252}
253
josephjangaaddf282019-04-16 18:46:24 +0800254static void KillAllProcesses() {
255 WriteStringToFile("i", PROC_SYSRQ);
256}
257
258// Create reboot/shutdwon monitor thread
259void RebootMonitorThread(unsigned int cmd, const std::string& rebootTarget, sem_t* reboot_semaphore,
260 std::chrono::milliseconds shutdown_timeout, bool* reboot_monitor_run) {
261 unsigned int remaining_shutdown_time = 0;
262
263 // 30 seconds more than the timeout passed to the thread as there is a final Umount pass
264 // after the timeout is reached.
265 constexpr unsigned int shutdown_watchdog_timeout_default = 30;
266 auto shutdown_watchdog_timeout = android::base::GetUintProperty(
267 "ro.build.shutdown.watchdog.timeout", shutdown_watchdog_timeout_default);
268 remaining_shutdown_time = shutdown_watchdog_timeout + shutdown_timeout.count() / 1000;
269
270 while (*reboot_monitor_run == true) {
271 if (TEMP_FAILURE_RETRY(sem_wait(reboot_semaphore)) == -1) {
272 LOG(ERROR) << "sem_wait failed and exit RebootMonitorThread()";
273 return;
274 }
275
276 timespec shutdown_timeout_timespec;
277 if (clock_gettime(CLOCK_MONOTONIC, &shutdown_timeout_timespec) == -1) {
278 LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
279 return;
280 }
281
282 // If there are some remaining shutdown time left from previous round, we use
283 // remaining time here.
284 shutdown_timeout_timespec.tv_sec += remaining_shutdown_time;
285
286 LOG(INFO) << "shutdown_timeout_timespec.tv_sec: " << shutdown_timeout_timespec.tv_sec;
287
288 int sem_return = 0;
289 while ((sem_return = sem_timedwait_monotonic_np(reboot_semaphore,
290 &shutdown_timeout_timespec)) == -1 &&
291 errno == EINTR) {
292 }
293
294 if (sem_return == -1) {
295 LOG(ERROR) << "Reboot thread timed out";
296
297 if (android::base::GetBoolProperty("ro.debuggable", false) == true) {
298 LOG(INFO) << "Try to dump init process call trace:";
299 const char* vdc_argv[] = {"/system/bin/debuggerd", "-b", "1"};
300 int status;
301 android_fork_execvp_ext(arraysize(vdc_argv), (char**)vdc_argv, &status, true,
302 LOG_KLOG, true, nullptr, nullptr, 0);
303
304 LOG(INFO) << "Show stack for all active CPU:";
305 WriteStringToFile("l", PROC_SYSRQ);
306
307 LOG(INFO) << "Show tasks that are in disk sleep(uninterruptable sleep), which are "
308 "like "
309 "blocked in mutex or hardware register access:";
310 WriteStringToFile("w", PROC_SYSRQ);
311 }
312
313 // In shutdown case,notify kernel to sync and umount fs to read-only before shutdown.
314 if (cmd == ANDROID_RB_POWEROFF || cmd == ANDROID_RB_THERMOFF) {
315 WriteStringToFile("s", PROC_SYSRQ);
316
317 WriteStringToFile("u", PROC_SYSRQ);
318
319 RebootSystem(cmd, rebootTarget);
320 }
321
322 LOG(ERROR) << "Trigger crash at last!";
323 WriteStringToFile("c", PROC_SYSRQ);
324 } else {
325 timespec current_time_timespec;
326
327 if (clock_gettime(CLOCK_MONOTONIC, &current_time_timespec) == -1) {
328 LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
329 return;
330 }
331
332 remaining_shutdown_time =
333 shutdown_timeout_timespec.tv_sec - current_time_timespec.tv_sec;
334
335 LOG(INFO) << "remaining_shutdown_time: " << remaining_shutdown_time;
336 }
337 }
338}
Keun-young Park3ee0df92017-03-27 11:21:09 -0700339
Keun-young Park8d01f632017-03-13 11:54:47 -0700340/* Try umounting all emulated file systems R/W block device cfile systems.
341 * This will just try umount and give it up if it fails.
342 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
343 * and necessary check can be done at the next reboot.
344 * For safer shutdown, caller needs to make sure that
345 * all processes / emulated partition for the target fs are all cleaned-up.
346 *
347 * return true when umount was successful. false when timed out.
348 */
josephjangaaddf282019-04-16 18:46:24 +0800349static UmountStat TryUmountAndFsck(unsigned int cmd, const std::string& rebootTarget, bool runFsck,
350 std::chrono::milliseconds timeout, sem_t* reboot_semaphore) {
Keun-young Park3ee0df92017-03-27 11:21:09 -0700351 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700352 std::vector<MountEntry> block_devices;
353 std::vector<MountEntry> emulated_devices;
Keun-young Park8d01f632017-03-13 11:54:47 -0700354
Keun-young Park2ba5c812017-03-29 12:54:40 -0700355 if (runFsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700356 return UMOUNT_STAT_ERROR;
357 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700358
Tom Cherryede0d532017-07-06 14:20:11 -0700359 UmountStat stat = UmountPartitions(timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700360 if (stat != UMOUNT_STAT_SUCCESS) {
361 LOG(INFO) << "umount timeout, last resort, kill all and try";
Jonglin Lee28a2c922019-01-15 16:38:44 -0800362 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park3ee0df92017-03-27 11:21:09 -0700363 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700364 // 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 -0700365 UmountStat st = UmountPartitions(0ms);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800366 if ((st != UMOUNT_STAT_SUCCESS) && DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park8d01f632017-03-13 11:54:47 -0700367 }
368
Keun-young Park2ba5c812017-03-29 12:54:40 -0700369 if (stat == UMOUNT_STAT_SUCCESS && runFsck) {
josephjangaaddf282019-04-16 18:46:24 +0800370 LOG(INFO) << "Pause reboot monitor thread before fsck";
371 sem_post(reboot_semaphore);
372
Keun-young Park2ba5c812017-03-29 12:54:40 -0700373 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
374 // and should not affect reboot time.
375 for (auto& entry : block_devices) {
376 entry.DoFsck();
377 }
josephjangaaddf282019-04-16 18:46:24 +0800378
379 LOG(INFO) << "Resume reboot monitor thread after fsck";
380 sem_post(reboot_semaphore);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700381 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700382 return stat;
383}
384
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800385// zram is able to use backing device on top of a loopback device.
386// In order to unmount /data successfully, we have to kill the loopback device first
387#define ZRAM_DEVICE "/dev/block/zram0"
388#define ZRAM_RESET "/sys/block/zram0/reset"
389#define ZRAM_BACK_DEV "/sys/block/zram0/backing_dev"
390static void KillZramBackingDevice() {
391 std::string backing_dev;
392 if (!android::base::ReadFileToString(ZRAM_BACK_DEV, &backing_dev)) return;
393
394 if (!android::base::StartsWith(backing_dev, "/dev/block/loop")) return;
395
396 // cut the last "\n"
397 backing_dev.erase(backing_dev.length() - 1);
398
399 // shutdown zram handle
400 Timer swap_timer;
401 LOG(INFO) << "swapoff() start...";
402 if (swapoff(ZRAM_DEVICE) == -1) {
403 LOG(ERROR) << "zram_backing_dev: swapoff (" << backing_dev << ")" << " failed";
404 return;
405 }
406 LOG(INFO) << "swapoff() took " << swap_timer;;
407
josephjangaaddf282019-04-16 18:46:24 +0800408 if (!WriteStringToFile("1", ZRAM_RESET)) {
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800409 LOG(ERROR) << "zram_backing_dev: reset (" << backing_dev << ")" << " failed";
410 return;
411 }
412
413 // clear loopback device
414 unique_fd loop(TEMP_FAILURE_RETRY(open(backing_dev.c_str(), O_RDWR | O_CLOEXEC)));
415 if (loop.get() < 0) {
416 LOG(ERROR) << "zram_backing_dev: open(" << backing_dev << ")" << " failed";
417 return;
418 }
419
420 if (ioctl(loop.get(), LOOP_CLR_FD, 0) < 0) {
421 LOG(ERROR) << "zram_backing_dev: loop_clear (" << backing_dev << ")" << " failed";
422 return;
423 }
424 LOG(INFO) << "zram_backing_dev: `" << backing_dev << "` is cleared successfully.";
425}
426
Tom Cherry44aceed2018-08-03 13:36:18 -0700427//* Reboot / shutdown the system.
428// cmd ANDROID_RB_* as defined in android_reboot.h
429// reason Reason string like "reboot", "shutdown,userrequested"
430// rebootTarget Reboot target string like "bootloader". Otherwise, it should be an
431// empty string.
432// runFsck Whether to run fsck after umount is done.
433//
434static void DoReboot(unsigned int cmd, const std::string& reason, const std::string& rebootTarget,
435 bool runFsck) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700436 Timer t;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700437 LOG(INFO) << "Reboot start, reason: " << reason << ", rebootTarget: " << rebootTarget;
438
439 // Ensure last reboot reason is reduced to canonical
440 // alias reported in bootloader or system boot reason.
441 size_t skip = 0;
442 std::vector<std::string> reasons = Split(reason, ",");
443 if (reasons.size() >= 2 && reasons[0] == "reboot" &&
444 (reasons[1] == "recovery" || reasons[1] == "bootloader" || reasons[1] == "cold" ||
445 reasons[1] == "hard" || reasons[1] == "warm")) {
446 skip = strlen("reboot,");
447 }
448 property_set(LAST_REBOOT_REASON_PROPERTY, reason.c_str() + skip);
449 sync();
450
451 bool is_thermal_shutdown = cmd == ANDROID_RB_THERMOFF;
452
453 auto shutdown_timeout = 0ms;
454 if (!SHUTDOWN_ZERO_TIMEOUT) {
Wei Wangb5de0882018-10-09 12:42:06 -0700455 constexpr unsigned int shutdown_timeout_default = 6;
456 constexpr unsigned int max_thermal_shutdown_timeout = 3;
457 auto shutdown_timeout_final = android::base::GetUintProperty("ro.build.shutdown_timeout",
458 shutdown_timeout_default);
459 if (is_thermal_shutdown && shutdown_timeout_final > max_thermal_shutdown_timeout) {
460 shutdown_timeout_final = max_thermal_shutdown_timeout;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700461 }
Wei Wangb5de0882018-10-09 12:42:06 -0700462 shutdown_timeout = std::chrono::seconds(shutdown_timeout_final);
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700463 }
464 LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " ms";
465
josephjangaaddf282019-04-16 18:46:24 +0800466 sem_t reboot_semaphore;
467 if (sem_init(&reboot_semaphore, false, 0) == -1) {
468 // These should never fail, but if they do, skip the graceful reboot and reboot immediately.
469 LOG(ERROR) << "sem_init() fail and RebootSystem() return!";
470 RebootSystem(cmd, rebootTarget);
471 }
472
473 // Start a thread to monitor init shutdown process
474 LOG(INFO) << "Create reboot monitor thread.";
475 bool reboot_monitor_run = true;
476 std::thread reboot_monitor_thread(&RebootMonitorThread, cmd, rebootTarget, &reboot_semaphore,
477 shutdown_timeout, &reboot_monitor_run);
478 reboot_monitor_thread.detach();
479
480 // Start reboot monitor thread
481 sem_post(&reboot_semaphore);
482
Keun-young Park7830d592017-03-27 16:07:02 -0700483 // keep debugging tools until non critical ones are all gone.
484 const std::set<std::string> kill_after_apps{"tombstoned", "logd", "adbd"};
485 // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700486 const std::set<std::string> to_starts{"watchdogd"};
Tom Cherry911b9b12017-07-27 16:20:58 -0700487 for (const auto& s : ServiceList::GetInstance()) {
Keun-young Park7830d592017-03-27 16:07:02 -0700488 if (kill_after_apps.count(s->name())) {
489 s->SetShutdownCritical();
490 } else if (to_starts.count(s->name())) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700491 if (auto result = s->Start(); !result) {
492 LOG(ERROR) << "Could not start shutdown 'to_start' service '" << s->name()
493 << "': " << result.error();
494 }
Keun-young Park7830d592017-03-27 16:07:02 -0700495 s->SetShutdownCritical();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700496 } else if (s->IsShutdownCritical()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700497 // Start shutdown critical service if not started.
498 if (auto result = s->Start(); !result) {
499 LOG(ERROR) << "Could not start shutdown critical service '" << s->name()
500 << "': " << result.error();
501 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700502 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700503 }
Keun-young Park7830d592017-03-27 16:07:02 -0700504
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800505 // remaining operations (specifically fsck) may take a substantial duration
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700506 if (cmd == ANDROID_RB_POWEROFF || is_thermal_shutdown) {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800507 TurnOffBacklight();
508 }
509
Tom Cherry911b9b12017-07-27 16:20:58 -0700510 Service* bootAnim = ServiceList::GetInstance().FindService("bootanim");
511 Service* surfaceFlinger = ServiceList::GetInstance().FindService("surfaceflinger");
Keun-young Park7830d592017-03-27 16:07:02 -0700512 if (bootAnim != nullptr && surfaceFlinger != nullptr && surfaceFlinger->IsRunning()) {
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800513 bool do_shutdown_animation = GetBoolProperty("ro.init.shutdown_animation", false);
514
515 if (do_shutdown_animation) {
516 property_set("service.bootanim.exit", "0");
517 // Could be in the middle of animation. Stop and start so that it can pick
518 // up the right mode.
519 bootAnim->Stop();
520 }
521
Tom Cherry911b9b12017-07-27 16:20:58 -0700522 for (const auto& service : ServiceList::GetInstance()) {
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800523 if (service->classnames().count("animation") == 0) {
524 continue;
525 }
526
527 // start all animation classes if stopped.
528 if (do_shutdown_animation) {
Tom Cherry9949ec52019-05-16 16:54:49 -0700529 service->Start();
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800530 }
531 service->SetShutdownCritical(); // will not check animation class separately
532 }
533
534 if (do_shutdown_animation) {
Tom Cherry9949ec52019-05-16 16:54:49 -0700535 bootAnim->Start();
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800536 surfaceFlinger->SetShutdownCritical();
537 bootAnim->SetShutdownCritical();
Tom Cherry911b9b12017-07-27 16:20:58 -0700538 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700539 }
Keun-young Park7830d592017-03-27 16:07:02 -0700540
Keun-young Park8d01f632017-03-13 11:54:47 -0700541 // optional shutdown step
542 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Keun-young Park30173872017-07-18 10:58:28 -0700543 if (shutdown_timeout > 0ms) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700544 LOG(INFO) << "terminating init services";
Keun-young Park8d01f632017-03-13 11:54:47 -0700545
546 // Ask all services to terminate except shutdown critical ones.
Tom Cherry911b9b12017-07-27 16:20:58 -0700547 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700548 if (!s->IsShutdownCritical()) s->Terminate();
Tom Cherry911b9b12017-07-27 16:20:58 -0700549 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700550
551 int service_count = 0;
Keun-young Park30173872017-07-18 10:58:28 -0700552 // Only wait up to half of timeout here
553 auto termination_wait_timeout = shutdown_timeout / 2;
Tom Cherryede0d532017-07-06 14:20:11 -0700554 while (t.duration() < termination_wait_timeout) {
Tom Cherryeeee8312017-07-28 15:22:23 -0700555 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700556
557 service_count = 0;
Tom Cherry911b9b12017-07-27 16:20:58 -0700558 for (const auto& s : ServiceList::GetInstance()) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700559 // Count the number of services running except shutdown critical.
560 // Exclude the console as it will ignore the SIGTERM signal
561 // and not exit.
562 // Note: SVC_CONSOLE actually means "requires console" but
563 // it is only used by the shell.
564 if (!s->IsShutdownCritical() && s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
565 service_count++;
566 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700567 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700568
569 if (service_count == 0) {
570 // All terminable services terminated. We can exit early.
571 break;
572 }
573
574 // Wait a bit before recounting the number or running services.
575 std::this_thread::sleep_for(50ms);
576 }
577 LOG(INFO) << "Terminating running services took " << t
578 << " with remaining services:" << service_count;
579 }
580
581 // minimum safety steps before restarting
582 // 2. kill all services except ones that are necessary for the shutdown sequence.
Tom Cherry911b9b12017-07-27 16:20:58 -0700583 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700584 if (!s->IsShutdownCritical()) s->Stop();
Tom Cherry911b9b12017-07-27 16:20:58 -0700585 }
Luis Hector Chavez92c49bc2018-07-27 11:19:25 -0700586 SubcontextTerminate();
Tom Cherryeeee8312017-07-28 15:22:23 -0700587 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700588
589 // 3. send volume shutdown to vold
Tom Cherry911b9b12017-07-27 16:20:58 -0700590 Service* voldService = ServiceList::GetInstance().FindService("vold");
Keun-young Park8d01f632017-03-13 11:54:47 -0700591 if (voldService != nullptr && voldService->IsRunning()) {
592 ShutdownVold();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700593 voldService->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700594 } else {
595 LOG(INFO) << "vold not running, skipping vold shutdown";
596 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700597 // logcat stopped here
Tom Cherry911b9b12017-07-27 16:20:58 -0700598 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700599 if (kill_after_apps.count(s->name())) s->Stop();
Tom Cherry911b9b12017-07-27 16:20:58 -0700600 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700601 // 4. sync, try umount, and optionally run fsck for user shutdown
Tom Cherry1f9d5402018-03-15 10:22:40 -0700602 {
603 Timer sync_timer;
604 LOG(INFO) << "sync() before umount...";
605 sync();
606 LOG(INFO) << "sync() before umount took" << sync_timer;
607 }
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800608 // 5. drop caches and disable zram backing device, if exist
609 KillZramBackingDevice();
610
josephjangaaddf282019-04-16 18:46:24 +0800611 UmountStat stat = TryUmountAndFsck(cmd, rebootTarget, runFsck, shutdown_timeout - t.duration(),
612 &reboot_semaphore);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700613 // Follow what linux shutdown is doing: one more sync with little bit delay
Tom Cherry1f9d5402018-03-15 10:22:40 -0700614 {
615 Timer sync_timer;
616 LOG(INFO) << "sync() after umount...";
617 sync();
618 LOG(INFO) << "sync() after umount took" << sync_timer;
619 }
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700620 if (!is_thermal_shutdown) std::this_thread::sleep_for(100ms);
Keun-young Park8d01f632017-03-13 11:54:47 -0700621 LogShutdownTime(stat, &t);
josephjangaaddf282019-04-16 18:46:24 +0800622
623 // Send signal to terminate reboot monitor thread.
624 reboot_monitor_run = false;
625 sem_post(&reboot_semaphore);
626
Keun-young Park8d01f632017-03-13 11:54:47 -0700627 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
628 RebootSystem(cmd, rebootTarget);
629 abort();
630}
Tom Cherry98ad32a2017-04-17 16:34:20 -0700631
632bool HandlePowerctlMessage(const std::string& command) {
633 unsigned int cmd = 0;
Mark Salyzyn62909822017-10-09 09:27:16 -0700634 std::vector<std::string> cmd_params = Split(command, ",");
Tom Cherry98ad32a2017-04-17 16:34:20 -0700635 std::string reboot_target = "";
636 bool run_fsck = false;
637 bool command_invalid = false;
638
Mark Salyzynd7931f12019-07-10 10:33:09 -0700639 if (cmd_params[0] == "shutdown") {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700640 cmd = ANDROID_RB_POWEROFF;
Mark Salyzynd7931f12019-07-10 10:33:09 -0700641 if (cmd_params.size() >= 2) {
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700642 if (cmd_params[1] == "userrequested") {
643 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
644 // Run fsck once the file system is remounted in read-only mode.
645 run_fsck = true;
646 } else if (cmd_params[1] == "thermal") {
Mark Salyzynbfd05b62017-09-26 11:10:12 -0700647 // Turn off sources of heat immediately.
648 TurnOffBacklight();
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700649 // run_fsck is false to avoid delay
650 cmd = ANDROID_RB_THERMOFF;
651 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700652 }
653 } else if (cmd_params[0] == "reboot") {
654 cmd = ANDROID_RB_RESTART2;
655 if (cmd_params.size() >= 2) {
656 reboot_target = cmd_params[1];
Hridya Valsaraju54258262018-09-19 21:14:18 -0700657 // adb reboot fastboot should boot into bootloader for devices not
658 // supporting logical partitions.
659 if (reboot_target == "fastboot" &&
Yifan Hong0e0f8182018-11-16 12:49:06 -0800660 !android::base::GetBoolProperty("ro.boot.dynamic_partitions", false)) {
Hridya Valsaraju54258262018-09-19 21:14:18 -0700661 reboot_target = "bootloader";
662 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700663 // When rebooting to the bootloader notify the bootloader writing
664 // also the BCB.
665 if (reboot_target == "bootloader") {
666 std::string err;
667 if (!write_reboot_bootloader(&err)) {
668 LOG(ERROR) << "reboot-bootloader: Error writing "
669 "bootloader_message: "
670 << err;
671 }
Tianjie Xu5e98b632019-07-18 12:48:28 -0700672 } else if (reboot_target == "recovery") {
673 bootloader_message boot = {};
674 if (std::string err; !read_bootloader_message(&boot, &err)) {
675 LOG(ERROR) << "Failed to read bootloader message: " << err;
676 }
677 // Update the boot command field if it's empty, and preserve
678 // the other arguments in the bootloader message.
679 if (boot.command[0] == '\0') {
680 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
681 if (std::string err; !write_bootloader_message(boot, &err)) {
682 LOG(ERROR) << "Failed to set bootloader message: " << err;
683 return false;
684 }
685 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700686 } else if (reboot_target == "sideload" || reboot_target == "sideload-auto-reboot" ||
687 reboot_target == "fastboot") {
688 std::string arg = reboot_target == "sideload-auto-reboot" ? "sideload_auto_reboot"
689 : reboot_target;
690 const std::vector<std::string> options = {
691 "--" + arg,
692 };
693 std::string err;
694 if (!write_bootloader_message(options, &err)) {
695 LOG(ERROR) << "Failed to set bootloader message: " << err;
696 return false;
697 }
698 reboot_target = "recovery";
Tom Cherry98ad32a2017-04-17 16:34:20 -0700699 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700700
Mark Salyzynd7931f12019-07-10 10:33:09 -0700701 // If there are additional parameter, pass them along
702 for (size_t i = 2; (cmd_params.size() > i) && cmd_params[i].size(); ++i) {
703 reboot_target += "," + cmd_params[i];
Tom Cherry98ad32a2017-04-17 16:34:20 -0700704 }
705 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700706 } else {
707 command_invalid = true;
708 }
709 if (command_invalid) {
710 LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
711 return false;
712 }
713
Wei Wangeeab4912017-06-27 22:08:45 -0700714 LOG(INFO) << "Clear action queue and start shutdown trigger";
715 ActionManager::GetInstance().ClearQueue();
716 // Queue shutdown trigger first
717 ActionManager::GetInstance().QueueEventTrigger("shutdown");
718 // Queue built-in shutdown_done
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700719 auto shutdown_handler = [cmd, command, reboot_target, run_fsck](const BuiltinArguments&) {
Wei Wangeeab4912017-06-27 22:08:45 -0700720 DoReboot(cmd, command, reboot_target, run_fsck);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700721 return Result<void>{};
Wei Wangeeab4912017-06-27 22:08:45 -0700722 };
723 ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
724
725 // Skip wait for prop if it is in progress
726 ResetWaitForProp();
727
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700728 // Clear EXEC flag if there is one pending
Tom Cherry911b9b12017-07-27 16:20:58 -0700729 for (const auto& s : ServiceList::GetInstance()) {
730 s->UnSetExec();
731 }
Wei Wangeeab4912017-06-27 22:08:45 -0700732
Tom Cherry98ad32a2017-04-17 16:34:20 -0700733 return true;
734}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700735
736} // namespace init
737} // namespace android