blob: 54f68bb8ffc820a402cc9a3991361f030b30b510 [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/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"
Wei Wangeeab4912017-06-27 22:08:45 -070055#include "init.h"
Keun-young Park7830d592017-03-27 16:07:02 -070056#include "property_service.h"
Tom Cherry44aceed2018-08-03 13:36:18 -070057#include "reboot_utils.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
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;
Keun-young Park8d01f632017-03-13 11:54:47 -070065using android::base::StringPrintf;
Tom Cherryede0d532017-07-06 14:20:11 -070066using android::base::Timer;
Jaegeuk Kim2aedc822018-11-20 13:27:06 -080067using android::base::unique_fd;
josephjangaaddf282019-04-16 18:46:24 +080068using android::base::WriteStringToFile;
Keun-young Park8d01f632017-03-13 11:54:47 -070069
Tom Cherry81f5d3e2017-06-22 12:53:17 -070070namespace android {
71namespace init {
72
Keun-young Park8d01f632017-03-13 11:54:47 -070073// represents umount status during reboot / shutdown.
74enum UmountStat {
75 /* umount succeeded. */
76 UMOUNT_STAT_SUCCESS = 0,
77 /* umount was not run. */
78 UMOUNT_STAT_SKIPPED = 1,
79 /* umount failed with timeout. */
80 UMOUNT_STAT_TIMEOUT = 2,
81 /* could not run due to error */
82 UMOUNT_STAT_ERROR = 3,
83 /* not used by init but reserved for other part to use this to represent the
84 the state where umount status before reboot is not found / available. */
85 UMOUNT_STAT_NOT_AVAILABLE = 4,
86};
87
88// Utility for struct mntent
89class MountEntry {
90 public:
Keun-young Park2ba5c812017-03-29 12:54:40 -070091 explicit MountEntry(const mntent& entry)
Keun-young Park8d01f632017-03-13 11:54:47 -070092 : mnt_fsname_(entry.mnt_fsname),
93 mnt_dir_(entry.mnt_dir),
94 mnt_type_(entry.mnt_type),
Keun-young Park2ba5c812017-03-29 12:54:40 -070095 mnt_opts_(entry.mnt_opts) {}
Keun-young Park8d01f632017-03-13 11:54:47 -070096
Jaegeuk Kim0f04f722017-09-25 10:55:39 -070097 bool Umount(bool force) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -080098 LOG(INFO) << "Unmounting " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Jaegeuk Kim0f04f722017-09-25 10:55:39 -070099 int r = umount2(mnt_dir_.c_str(), force ? MNT_FORCE : 0);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700100 if (r == 0) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800101 LOG(INFO) << "Umounted " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700102 return true;
103 } else {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800104 PLOG(WARNING) << "Cannot umount " << mnt_fsname_ << ":" << mnt_dir_ << " opts "
Keun-young Park2ba5c812017-03-29 12:54:40 -0700105 << mnt_opts_;
106 return false;
107 }
108 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700109
Keun-young Park2ba5c812017-03-29 12:54:40 -0700110 void DoFsck() {
111 int st;
112 if (IsF2Fs()) {
113 const char* f2fs_argv[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800114 "/system/bin/fsck.f2fs",
115 "-a",
116 mnt_fsname_.c_str(),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700117 };
118 android_fork_execvp_ext(arraysize(f2fs_argv), (char**)f2fs_argv, &st, true, LOG_KLOG,
119 true, nullptr, nullptr, 0);
120 } else if (IsExt4()) {
121 const char* ext4_argv[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800122 "/system/bin/e2fsck",
123 "-y",
124 mnt_fsname_.c_str(),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700125 };
126 android_fork_execvp_ext(arraysize(ext4_argv), (char**)ext4_argv, &st, true, LOG_KLOG,
127 true, nullptr, nullptr, 0);
128 }
129 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700130
131 static bool IsBlockDevice(const struct mntent& mntent) {
132 return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
133 }
134
135 static bool IsEmulatedDevice(const struct mntent& mntent) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700136 return android::base::StartsWith(mntent.mnt_fsname, "/data/");
Keun-young Park8d01f632017-03-13 11:54:47 -0700137 }
138
139 private:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700140 bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
141
142 bool IsExt4() const { return mnt_type_ == "ext4"; }
143
Keun-young Park8d01f632017-03-13 11:54:47 -0700144 std::string mnt_fsname_;
145 std::string mnt_dir_;
146 std::string mnt_type_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700147 std::string mnt_opts_;
Keun-young Park8d01f632017-03-13 11:54:47 -0700148};
149
150// Turn off backlight while we are performing power down cleanup activities.
151static void TurnOffBacklight() {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800152 Service* service = ServiceList::GetInstance().FindService("blank_screen");
153 if (service == nullptr) {
154 LOG(WARNING) << "cannot find blank_screen in TurnOffBacklight";
Keun-young Park8d01f632017-03-13 11:54:47 -0700155 return;
156 }
Tom Cherryd9872642018-10-11 10:38:05 -0700157 if (auto result = service->Start(); !result) {
158 LOG(WARNING) << "Could not start blank_screen service: " << result.error();
159 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700160}
161
Keun-young Park8d01f632017-03-13 11:54:47 -0700162static void ShutdownVold() {
163 const char* vdc_argv[] = {"/system/bin/vdc", "volume", "shutdown"};
164 int status;
165 android_fork_execvp_ext(arraysize(vdc_argv), (char**)vdc_argv, &status, true, LOG_KLOG, true,
166 nullptr, nullptr, 0);
167}
168
169static void LogShutdownTime(UmountStat stat, Timer* t) {
Tom Cherryede0d532017-07-06 14:20:11 -0700170 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration().count()) << ":"
171 << stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700172}
173
Keun-young Park8d01f632017-03-13 11:54:47 -0700174/* Find all read+write block devices and emulated devices in /proc/mounts
175 * and add them to correpsponding list.
176 */
177static bool FindPartitionsToUmount(std::vector<MountEntry>* blockDevPartitions,
Keun-young Park2ba5c812017-03-29 12:54:40 -0700178 std::vector<MountEntry>* emulatedPartitions, bool dump) {
Tom Cherryf274e782018-10-03 13:13:41 -0700179 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
Keun-young Park8d01f632017-03-13 11:54:47 -0700180 if (fp == nullptr) {
181 PLOG(ERROR) << "Failed to open /proc/mounts";
182 return false;
183 }
184 mntent* mentry;
185 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700186 if (dump) {
187 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
188 << mentry->mnt_opts << " type " << mentry->mnt_type;
189 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
Keun-young Park6e12b382017-07-17 12:20:33 -0700190 std::string mount_dir(mentry->mnt_dir);
191 // These are R/O partitions changed to R/W after adb remount.
192 // Do not umount them as shutdown critical services may rely on them.
Wei Wanga01c27e2017-07-25 10:52:08 -0700193 if (mount_dir != "/" && mount_dir != "/system" && mount_dir != "/vendor" &&
194 mount_dir != "/oem") {
Keun-young Park6e12b382017-07-17 12:20:33 -0700195 blockDevPartitions->emplace(blockDevPartitions->begin(), *mentry);
196 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700197 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700198 emulatedPartitions->emplace(emulatedPartitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700199 }
200 }
201 return true;
202}
203
Jonglin Lee28a2c922019-01-15 16:38:44 -0800204static void DumpUmountDebuggingInfo() {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700205 int status;
206 if (!security_getenforce()) {
207 LOG(INFO) << "Run lsof";
208 const char* lsof_argv[] = {"/system/bin/lsof"};
209 android_fork_execvp_ext(arraysize(lsof_argv), (char**)lsof_argv, &status, true, LOG_KLOG,
210 true, nullptr, nullptr, 0);
Keun-young Park8d01f632017-03-13 11:54:47 -0700211 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700212 FindPartitionsToUmount(nullptr, nullptr, true);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800213 // dump current CPU stack traces and uninterruptible tasks
josephjangaaddf282019-04-16 18:46:24 +0800214 WriteStringToFile("l", PROC_SYSRQ);
215 WriteStringToFile("w", PROC_SYSRQ);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700216}
217
Tom Cherryede0d532017-07-06 14:20:11 -0700218static UmountStat UmountPartitions(std::chrono::milliseconds timeout) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700219 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700220 /* data partition needs all pending writes to be completed and all emulated partitions
221 * umounted.If the current waiting is not good enough, give
222 * up and leave it to e2fsck after reboot to fix it.
223 */
224 while (true) {
225 std::vector<MountEntry> block_devices;
226 std::vector<MountEntry> emulated_devices;
227 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
228 return UMOUNT_STAT_ERROR;
229 }
230 if (block_devices.size() == 0) {
Wei Wang8c00e422017-08-16 14:01:46 -0700231 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700232 }
Wei Wang8c00e422017-08-16 14:01:46 -0700233 bool unmount_done = true;
234 if (emulated_devices.size() > 0) {
Wei Wang25dc30f2017-10-23 15:32:03 -0700235 for (auto& entry : emulated_devices) {
236 if (!entry.Umount(false)) unmount_done = false;
237 }
Wei Wang8c00e422017-08-16 14:01:46 -0700238 if (unmount_done) {
239 sync();
240 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700241 }
Wei Wang25dc30f2017-10-23 15:32:03 -0700242 for (auto& entry : block_devices) {
243 if (!entry.Umount(timeout == 0ms)) unmount_done = false;
244 }
Wei Wang8c00e422017-08-16 14:01:46 -0700245 if (unmount_done) {
246 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700247 }
Wei Wang8c00e422017-08-16 14:01:46 -0700248 if ((timeout < t.duration())) { // try umount at least once
249 return UMOUNT_STAT_TIMEOUT;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700250 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700251 std::this_thread::sleep_for(100ms);
252 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700253}
254
josephjangaaddf282019-04-16 18:46:24 +0800255static void KillAllProcesses() {
256 WriteStringToFile("i", PROC_SYSRQ);
257}
258
259// Create reboot/shutdwon monitor thread
260void RebootMonitorThread(unsigned int cmd, const std::string& rebootTarget, sem_t* reboot_semaphore,
261 std::chrono::milliseconds shutdown_timeout, bool* reboot_monitor_run) {
262 unsigned int remaining_shutdown_time = 0;
263
264 // 30 seconds more than the timeout passed to the thread as there is a final Umount pass
265 // after the timeout is reached.
266 constexpr unsigned int shutdown_watchdog_timeout_default = 30;
267 auto shutdown_watchdog_timeout = android::base::GetUintProperty(
268 "ro.build.shutdown.watchdog.timeout", shutdown_watchdog_timeout_default);
269 remaining_shutdown_time = shutdown_watchdog_timeout + shutdown_timeout.count() / 1000;
270
271 while (*reboot_monitor_run == true) {
272 if (TEMP_FAILURE_RETRY(sem_wait(reboot_semaphore)) == -1) {
273 LOG(ERROR) << "sem_wait failed and exit RebootMonitorThread()";
274 return;
275 }
276
277 timespec shutdown_timeout_timespec;
278 if (clock_gettime(CLOCK_MONOTONIC, &shutdown_timeout_timespec) == -1) {
279 LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
280 return;
281 }
282
283 // If there are some remaining shutdown time left from previous round, we use
284 // remaining time here.
285 shutdown_timeout_timespec.tv_sec += remaining_shutdown_time;
286
287 LOG(INFO) << "shutdown_timeout_timespec.tv_sec: " << shutdown_timeout_timespec.tv_sec;
288
289 int sem_return = 0;
290 while ((sem_return = sem_timedwait_monotonic_np(reboot_semaphore,
291 &shutdown_timeout_timespec)) == -1 &&
292 errno == EINTR) {
293 }
294
295 if (sem_return == -1) {
296 LOG(ERROR) << "Reboot thread timed out";
297
298 if (android::base::GetBoolProperty("ro.debuggable", false) == true) {
299 LOG(INFO) << "Try to dump init process call trace:";
300 const char* vdc_argv[] = {"/system/bin/debuggerd", "-b", "1"};
301 int status;
302 android_fork_execvp_ext(arraysize(vdc_argv), (char**)vdc_argv, &status, true,
303 LOG_KLOG, true, nullptr, nullptr, 0);
304
305 LOG(INFO) << "Show stack for all active CPU:";
306 WriteStringToFile("l", PROC_SYSRQ);
307
308 LOG(INFO) << "Show tasks that are in disk sleep(uninterruptable sleep), which are "
309 "like "
310 "blocked in mutex or hardware register access:";
311 WriteStringToFile("w", PROC_SYSRQ);
312 }
313
314 // In shutdown case,notify kernel to sync and umount fs to read-only before shutdown.
315 if (cmd == ANDROID_RB_POWEROFF || cmd == ANDROID_RB_THERMOFF) {
316 WriteStringToFile("s", PROC_SYSRQ);
317
318 WriteStringToFile("u", PROC_SYSRQ);
319
320 RebootSystem(cmd, rebootTarget);
321 }
322
323 LOG(ERROR) << "Trigger crash at last!";
324 WriteStringToFile("c", PROC_SYSRQ);
325 } else {
326 timespec current_time_timespec;
327
328 if (clock_gettime(CLOCK_MONOTONIC, &current_time_timespec) == -1) {
329 LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
330 return;
331 }
332
333 remaining_shutdown_time =
334 shutdown_timeout_timespec.tv_sec - current_time_timespec.tv_sec;
335
336 LOG(INFO) << "remaining_shutdown_time: " << remaining_shutdown_time;
337 }
338 }
339}
Keun-young Park3ee0df92017-03-27 11:21:09 -0700340
Keun-young Park8d01f632017-03-13 11:54:47 -0700341/* Try umounting all emulated file systems R/W block device cfile systems.
342 * This will just try umount and give it up if it fails.
343 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
344 * and necessary check can be done at the next reboot.
345 * For safer shutdown, caller needs to make sure that
346 * all processes / emulated partition for the target fs are all cleaned-up.
347 *
348 * return true when umount was successful. false when timed out.
349 */
josephjangaaddf282019-04-16 18:46:24 +0800350static UmountStat TryUmountAndFsck(unsigned int cmd, const std::string& rebootTarget, bool runFsck,
351 std::chrono::milliseconds timeout, sem_t* reboot_semaphore) {
Keun-young Park3ee0df92017-03-27 11:21:09 -0700352 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700353 std::vector<MountEntry> block_devices;
354 std::vector<MountEntry> emulated_devices;
Keun-young Park8d01f632017-03-13 11:54:47 -0700355
Keun-young Park2ba5c812017-03-29 12:54:40 -0700356 if (runFsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700357 return UMOUNT_STAT_ERROR;
358 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700359
Tom Cherryede0d532017-07-06 14:20:11 -0700360 UmountStat stat = UmountPartitions(timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700361 if (stat != UMOUNT_STAT_SUCCESS) {
362 LOG(INFO) << "umount timeout, last resort, kill all and try";
Jonglin Lee28a2c922019-01-15 16:38:44 -0800363 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park3ee0df92017-03-27 11:21:09 -0700364 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700365 // 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 -0700366 UmountStat st = UmountPartitions(0ms);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800367 if ((st != UMOUNT_STAT_SUCCESS) && DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park8d01f632017-03-13 11:54:47 -0700368 }
369
Keun-young Park2ba5c812017-03-29 12:54:40 -0700370 if (stat == UMOUNT_STAT_SUCCESS && runFsck) {
josephjangaaddf282019-04-16 18:46:24 +0800371 LOG(INFO) << "Pause reboot monitor thread before fsck";
372 sem_post(reboot_semaphore);
373
Keun-young Park2ba5c812017-03-29 12:54:40 -0700374 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
375 // and should not affect reboot time.
376 for (auto& entry : block_devices) {
377 entry.DoFsck();
378 }
josephjangaaddf282019-04-16 18:46:24 +0800379
380 LOG(INFO) << "Resume reboot monitor thread after fsck";
381 sem_post(reboot_semaphore);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700382 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700383 return stat;
384}
385
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800386// zram is able to use backing device on top of a loopback device.
387// In order to unmount /data successfully, we have to kill the loopback device first
388#define ZRAM_DEVICE "/dev/block/zram0"
389#define ZRAM_RESET "/sys/block/zram0/reset"
390#define ZRAM_BACK_DEV "/sys/block/zram0/backing_dev"
391static void KillZramBackingDevice() {
392 std::string backing_dev;
393 if (!android::base::ReadFileToString(ZRAM_BACK_DEV, &backing_dev)) return;
394
395 if (!android::base::StartsWith(backing_dev, "/dev/block/loop")) return;
396
397 // cut the last "\n"
398 backing_dev.erase(backing_dev.length() - 1);
399
400 // shutdown zram handle
401 Timer swap_timer;
402 LOG(INFO) << "swapoff() start...";
403 if (swapoff(ZRAM_DEVICE) == -1) {
404 LOG(ERROR) << "zram_backing_dev: swapoff (" << backing_dev << ")" << " failed";
405 return;
406 }
407 LOG(INFO) << "swapoff() took " << swap_timer;;
408
josephjangaaddf282019-04-16 18:46:24 +0800409 if (!WriteStringToFile("1", ZRAM_RESET)) {
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800410 LOG(ERROR) << "zram_backing_dev: reset (" << backing_dev << ")" << " failed";
411 return;
412 }
413
414 // clear loopback device
415 unique_fd loop(TEMP_FAILURE_RETRY(open(backing_dev.c_str(), O_RDWR | O_CLOEXEC)));
416 if (loop.get() < 0) {
417 LOG(ERROR) << "zram_backing_dev: open(" << backing_dev << ")" << " failed";
418 return;
419 }
420
421 if (ioctl(loop.get(), LOOP_CLR_FD, 0) < 0) {
422 LOG(ERROR) << "zram_backing_dev: loop_clear (" << backing_dev << ")" << " failed";
423 return;
424 }
425 LOG(INFO) << "zram_backing_dev: `" << backing_dev << "` is cleared successfully.";
426}
427
Tom Cherry44aceed2018-08-03 13:36:18 -0700428//* Reboot / shutdown the system.
429// cmd ANDROID_RB_* as defined in android_reboot.h
430// reason Reason string like "reboot", "shutdown,userrequested"
431// rebootTarget Reboot target string like "bootloader". Otherwise, it should be an
432// empty string.
433// runFsck Whether to run fsck after umount is done.
434//
435static void DoReboot(unsigned int cmd, const std::string& reason, const std::string& rebootTarget,
436 bool runFsck) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700437 Timer t;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700438 LOG(INFO) << "Reboot start, reason: " << reason << ", rebootTarget: " << rebootTarget;
439
440 // Ensure last reboot reason is reduced to canonical
441 // alias reported in bootloader or system boot reason.
442 size_t skip = 0;
443 std::vector<std::string> reasons = Split(reason, ",");
444 if (reasons.size() >= 2 && reasons[0] == "reboot" &&
445 (reasons[1] == "recovery" || reasons[1] == "bootloader" || reasons[1] == "cold" ||
446 reasons[1] == "hard" || reasons[1] == "warm")) {
447 skip = strlen("reboot,");
448 }
449 property_set(LAST_REBOOT_REASON_PROPERTY, reason.c_str() + skip);
450 sync();
451
452 bool is_thermal_shutdown = cmd == ANDROID_RB_THERMOFF;
453
454 auto shutdown_timeout = 0ms;
455 if (!SHUTDOWN_ZERO_TIMEOUT) {
Wei Wangb5de0882018-10-09 12:42:06 -0700456 constexpr unsigned int shutdown_timeout_default = 6;
457 constexpr unsigned int max_thermal_shutdown_timeout = 3;
458 auto shutdown_timeout_final = android::base::GetUintProperty("ro.build.shutdown_timeout",
459 shutdown_timeout_default);
460 if (is_thermal_shutdown && shutdown_timeout_final > max_thermal_shutdown_timeout) {
461 shutdown_timeout_final = max_thermal_shutdown_timeout;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700462 }
Wei Wangb5de0882018-10-09 12:42:06 -0700463 shutdown_timeout = std::chrono::seconds(shutdown_timeout_final);
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700464 }
465 LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " ms";
466
josephjangaaddf282019-04-16 18:46:24 +0800467 sem_t reboot_semaphore;
468 if (sem_init(&reboot_semaphore, false, 0) == -1) {
469 // These should never fail, but if they do, skip the graceful reboot and reboot immediately.
470 LOG(ERROR) << "sem_init() fail and RebootSystem() return!";
471 RebootSystem(cmd, rebootTarget);
472 }
473
474 // Start a thread to monitor init shutdown process
475 LOG(INFO) << "Create reboot monitor thread.";
476 bool reboot_monitor_run = true;
477 std::thread reboot_monitor_thread(&RebootMonitorThread, cmd, rebootTarget, &reboot_semaphore,
478 shutdown_timeout, &reboot_monitor_run);
479 reboot_monitor_thread.detach();
480
481 // Start reboot monitor thread
482 sem_post(&reboot_semaphore);
483
Keun-young Park7830d592017-03-27 16:07:02 -0700484 // keep debugging tools until non critical ones are all gone.
485 const std::set<std::string> kill_after_apps{"tombstoned", "logd", "adbd"};
486 // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700487 const std::set<std::string> to_starts{"watchdogd"};
Tom Cherry911b9b12017-07-27 16:20:58 -0700488 for (const auto& s : ServiceList::GetInstance()) {
Keun-young Park7830d592017-03-27 16:07:02 -0700489 if (kill_after_apps.count(s->name())) {
490 s->SetShutdownCritical();
491 } else if (to_starts.count(s->name())) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700492 if (auto result = s->Start(); !result) {
493 LOG(ERROR) << "Could not start shutdown 'to_start' service '" << s->name()
494 << "': " << result.error();
495 }
Keun-young Park7830d592017-03-27 16:07:02 -0700496 s->SetShutdownCritical();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700497 } else if (s->IsShutdownCritical()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700498 // Start shutdown critical service if not started.
499 if (auto result = s->Start(); !result) {
500 LOG(ERROR) << "Could not start shutdown critical service '" << s->name()
501 << "': " << result.error();
502 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700503 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700504 }
Keun-young Park7830d592017-03-27 16:07:02 -0700505
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800506 // remaining operations (specifically fsck) may take a substantial duration
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700507 if (cmd == ANDROID_RB_POWEROFF || is_thermal_shutdown) {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800508 TurnOffBacklight();
509 }
510
Tom Cherry911b9b12017-07-27 16:20:58 -0700511 Service* bootAnim = ServiceList::GetInstance().FindService("bootanim");
512 Service* surfaceFlinger = ServiceList::GetInstance().FindService("surfaceflinger");
Keun-young Park7830d592017-03-27 16:07:02 -0700513 if (bootAnim != nullptr && surfaceFlinger != nullptr && surfaceFlinger->IsRunning()) {
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800514 bool do_shutdown_animation = GetBoolProperty("ro.init.shutdown_animation", false);
515
516 if (do_shutdown_animation) {
517 property_set("service.bootanim.exit", "0");
518 // Could be in the middle of animation. Stop and start so that it can pick
519 // up the right mode.
520 bootAnim->Stop();
521 }
522
Tom Cherry911b9b12017-07-27 16:20:58 -0700523 for (const auto& service : ServiceList::GetInstance()) {
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800524 if (service->classnames().count("animation") == 0) {
525 continue;
526 }
527
528 // start all animation classes if stopped.
529 if (do_shutdown_animation) {
Tom Cherry9949ec52019-05-16 16:54:49 -0700530 service->Start();
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800531 }
532 service->SetShutdownCritical(); // will not check animation class separately
533 }
534
535 if (do_shutdown_animation) {
Tom Cherry9949ec52019-05-16 16:54:49 -0700536 bootAnim->Start();
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800537 surfaceFlinger->SetShutdownCritical();
538 bootAnim->SetShutdownCritical();
Tom Cherry911b9b12017-07-27 16:20:58 -0700539 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700540 }
Keun-young Park7830d592017-03-27 16:07:02 -0700541
Keun-young Park8d01f632017-03-13 11:54:47 -0700542 // optional shutdown step
543 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Keun-young Park30173872017-07-18 10:58:28 -0700544 if (shutdown_timeout > 0ms) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700545 LOG(INFO) << "terminating init services";
Keun-young Park8d01f632017-03-13 11:54:47 -0700546
547 // Ask all services to terminate except shutdown critical ones.
Tom Cherry911b9b12017-07-27 16:20:58 -0700548 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700549 if (!s->IsShutdownCritical()) s->Terminate();
Tom Cherry911b9b12017-07-27 16:20:58 -0700550 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700551
552 int service_count = 0;
Keun-young Park30173872017-07-18 10:58:28 -0700553 // Only wait up to half of timeout here
554 auto termination_wait_timeout = shutdown_timeout / 2;
Tom Cherryede0d532017-07-06 14:20:11 -0700555 while (t.duration() < termination_wait_timeout) {
Tom Cherryeeee8312017-07-28 15:22:23 -0700556 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700557
558 service_count = 0;
Tom Cherry911b9b12017-07-27 16:20:58 -0700559 for (const auto& s : ServiceList::GetInstance()) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700560 // Count the number of services running except shutdown critical.
561 // Exclude the console as it will ignore the SIGTERM signal
562 // and not exit.
563 // Note: SVC_CONSOLE actually means "requires console" but
564 // it is only used by the shell.
565 if (!s->IsShutdownCritical() && s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
566 service_count++;
567 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700568 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700569
570 if (service_count == 0) {
571 // All terminable services terminated. We can exit early.
572 break;
573 }
574
575 // Wait a bit before recounting the number or running services.
576 std::this_thread::sleep_for(50ms);
577 }
578 LOG(INFO) << "Terminating running services took " << t
579 << " with remaining services:" << service_count;
580 }
581
582 // minimum safety steps before restarting
583 // 2. kill all services except ones that are necessary for the shutdown sequence.
Tom Cherry911b9b12017-07-27 16:20:58 -0700584 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700585 if (!s->IsShutdownCritical()) s->Stop();
Tom Cherry911b9b12017-07-27 16:20:58 -0700586 }
Luis Hector Chavez92c49bc2018-07-27 11:19:25 -0700587 SubcontextTerminate();
Tom Cherryeeee8312017-07-28 15:22:23 -0700588 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700589
590 // 3. send volume shutdown to vold
Tom Cherry911b9b12017-07-27 16:20:58 -0700591 Service* voldService = ServiceList::GetInstance().FindService("vold");
Keun-young Park8d01f632017-03-13 11:54:47 -0700592 if (voldService != nullptr && voldService->IsRunning()) {
593 ShutdownVold();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700594 voldService->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700595 } else {
596 LOG(INFO) << "vold not running, skipping vold shutdown";
597 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700598 // logcat stopped here
Tom Cherry911b9b12017-07-27 16:20:58 -0700599 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700600 if (kill_after_apps.count(s->name())) s->Stop();
Tom Cherry911b9b12017-07-27 16:20:58 -0700601 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700602 // 4. sync, try umount, and optionally run fsck for user shutdown
Tom Cherry1f9d5402018-03-15 10:22:40 -0700603 {
604 Timer sync_timer;
605 LOG(INFO) << "sync() before umount...";
606 sync();
607 LOG(INFO) << "sync() before umount took" << sync_timer;
608 }
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800609 // 5. drop caches and disable zram backing device, if exist
610 KillZramBackingDevice();
611
josephjangaaddf282019-04-16 18:46:24 +0800612 UmountStat stat = TryUmountAndFsck(cmd, rebootTarget, runFsck, shutdown_timeout - t.duration(),
613 &reboot_semaphore);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700614 // Follow what linux shutdown is doing: one more sync with little bit delay
Tom Cherry1f9d5402018-03-15 10:22:40 -0700615 {
616 Timer sync_timer;
617 LOG(INFO) << "sync() after umount...";
618 sync();
619 LOG(INFO) << "sync() after umount took" << sync_timer;
620 }
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700621 if (!is_thermal_shutdown) std::this_thread::sleep_for(100ms);
Keun-young Park8d01f632017-03-13 11:54:47 -0700622 LogShutdownTime(stat, &t);
josephjangaaddf282019-04-16 18:46:24 +0800623
624 // Send signal to terminate reboot monitor thread.
625 reboot_monitor_run = false;
626 sem_post(&reboot_semaphore);
627
Keun-young Park8d01f632017-03-13 11:54:47 -0700628 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
629 RebootSystem(cmd, rebootTarget);
630 abort();
631}
Tom Cherry98ad32a2017-04-17 16:34:20 -0700632
633bool HandlePowerctlMessage(const std::string& command) {
634 unsigned int cmd = 0;
Mark Salyzyn62909822017-10-09 09:27:16 -0700635 std::vector<std::string> cmd_params = Split(command, ",");
Tom Cherry98ad32a2017-04-17 16:34:20 -0700636 std::string reboot_target = "";
637 bool run_fsck = false;
638 bool command_invalid = false;
639
640 if (cmd_params.size() > 3) {
641 command_invalid = true;
642 } else if (cmd_params[0] == "shutdown") {
643 cmd = ANDROID_RB_POWEROFF;
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700644 if (cmd_params.size() == 2) {
645 if (cmd_params[1] == "userrequested") {
646 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
647 // Run fsck once the file system is remounted in read-only mode.
648 run_fsck = true;
649 } else if (cmd_params[1] == "thermal") {
Mark Salyzynbfd05b62017-09-26 11:10:12 -0700650 // Turn off sources of heat immediately.
651 TurnOffBacklight();
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700652 // run_fsck is false to avoid delay
653 cmd = ANDROID_RB_THERMOFF;
654 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700655 }
656 } else if (cmd_params[0] == "reboot") {
657 cmd = ANDROID_RB_RESTART2;
658 if (cmd_params.size() >= 2) {
659 reboot_target = cmd_params[1];
Hridya Valsaraju54258262018-09-19 21:14:18 -0700660 // adb reboot fastboot should boot into bootloader for devices not
661 // supporting logical partitions.
662 if (reboot_target == "fastboot" &&
Yifan Hong0e0f8182018-11-16 12:49:06 -0800663 !android::base::GetBoolProperty("ro.boot.dynamic_partitions", false)) {
Hridya Valsaraju54258262018-09-19 21:14:18 -0700664 reboot_target = "bootloader";
665 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700666 // When rebooting to the bootloader notify the bootloader writing
667 // also the BCB.
668 if (reboot_target == "bootloader") {
669 std::string err;
670 if (!write_reboot_bootloader(&err)) {
671 LOG(ERROR) << "reboot-bootloader: Error writing "
672 "bootloader_message: "
673 << err;
674 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700675 } else if (reboot_target == "sideload" || reboot_target == "sideload-auto-reboot" ||
676 reboot_target == "fastboot") {
677 std::string arg = reboot_target == "sideload-auto-reboot" ? "sideload_auto_reboot"
678 : reboot_target;
679 const std::vector<std::string> options = {
680 "--" + arg,
681 };
682 std::string err;
683 if (!write_bootloader_message(options, &err)) {
684 LOG(ERROR) << "Failed to set bootloader message: " << err;
685 return false;
686 }
687 reboot_target = "recovery";
Tom Cherry98ad32a2017-04-17 16:34:20 -0700688 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700689
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700690 // If there is an additional parameter, pass it along
691 if ((cmd_params.size() == 3) && cmd_params[2].size()) {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700692 reboot_target += "," + cmd_params[2];
693 }
694 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700695 } else {
696 command_invalid = true;
697 }
698 if (command_invalid) {
699 LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
700 return false;
701 }
702
Wei Wangeeab4912017-06-27 22:08:45 -0700703 LOG(INFO) << "Clear action queue and start shutdown trigger";
704 ActionManager::GetInstance().ClearQueue();
705 // Queue shutdown trigger first
706 ActionManager::GetInstance().QueueEventTrigger("shutdown");
707 // Queue built-in shutdown_done
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700708 auto shutdown_handler = [cmd, command, reboot_target, run_fsck](const BuiltinArguments&) {
Wei Wangeeab4912017-06-27 22:08:45 -0700709 DoReboot(cmd, command, reboot_target, run_fsck);
Tom Cherry557946e2017-08-01 13:50:23 -0700710 return Success();
Wei Wangeeab4912017-06-27 22:08:45 -0700711 };
712 ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
713
714 // Skip wait for prop if it is in progress
715 ResetWaitForProp();
716
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700717 // Clear EXEC flag if there is one pending
Tom Cherry911b9b12017-07-27 16:20:58 -0700718 for (const auto& s : ServiceList::GetInstance()) {
719 s->UnSetExec();
720 }
Wei Wangeeab4912017-06-27 22:08:45 -0700721
Tom Cherry98ad32a2017-04-17 16:34:20 -0700722 return true;
723}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700724
725} // namespace init
726} // namespace android