blob: f2e260eaa7bbe5446be298533b09cf0cfaad347f [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>
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010025#include <stdlib.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070026#include <sys/cdefs.h>
Keun-young Park2ba5c812017-03-29 12:54:40 -070027#include <sys/ioctl.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070028#include <sys/mount.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070029#include <sys/stat.h>
josephjangaaddf282019-04-16 18:46:24 +080030#include <sys/swap.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070031#include <sys/syscall.h>
32#include <sys/types.h>
33#include <sys/wait.h>
34
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010035#include <chrono>
Keun-young Park8d01f632017-03-13 11:54:47 -070036#include <memory>
Keun-young Park7830d592017-03-27 16:07:02 -070037#include <set>
Keun-young Park8d01f632017-03-13 11:54:47 -070038#include <thread>
39#include <vector>
40
Tom Cherryede0d532017-07-06 14:20:11 -070041#include <android-base/chrono_utils.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070042#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070043#include <android-base/logging.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070044#include <android-base/macros.h>
Tom Cherryccf23532017-03-28 16:40:41 -070045#include <android-base/properties.h>
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010046#include <android-base/scopeguard.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070047#include <android-base/strings.h>
Keun-young Park2ba5c812017-03-29 12:54:40 -070048#include <android-base/unique_fd.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070049#include <bootloader_message/bootloader_message.h>
50#include <cutils/android_reboot.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070051#include <fs_mgr.h>
52#include <logwrap/logwrap.h>
Todd Poynorfc827be2017-04-13 15:17:24 -070053#include <private/android_filesystem_config.h>
Tom Cherry0c8d6d22017-08-10 12:22:44 -070054#include <selinux/selinux.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070055
Nikita Ioffeba6968e2019-10-07 16:26:33 +010056#include "action.h"
Tom Cherry7fd3bc22018-02-13 15:36:14 -080057#include "action_manager.h"
Nikita Ioffeba6968e2019-10-07 16:26:33 +010058#include "builtin_arguments.h"
Wei Wangeeab4912017-06-27 22:08:45 -070059#include "init.h"
Keun-young Park7830d592017-03-27 16:07:02 -070060#include "property_service.h"
Tom Cherry44aceed2018-08-03 13:36:18 -070061#include "reboot_utils.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070062#include "service.h"
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070063#include "service_list.h"
Luis Hector Chavez9f97f472017-09-06 13:43:57 -070064#include "sigchld_handler.h"
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010065#include "util.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070066
josephjangaaddf282019-04-16 18:46:24 +080067#define PROC_SYSRQ "/proc/sysrq-trigger"
68
Tom Cherry2436e6b2019-09-19 11:16:19 -070069using namespace std::literals;
70
Tom Cherry4f4cacc2019-01-08 10:39:00 -080071using android::base::GetBoolProperty;
Mark Salyzyn62909822017-10-09 09:27:16 -070072using android::base::Split;
Tom Cherryede0d532017-07-06 14:20:11 -070073using android::base::Timer;
Jaegeuk Kim2aedc822018-11-20 13:27:06 -080074using android::base::unique_fd;
josephjangaaddf282019-04-16 18:46:24 +080075using android::base::WriteStringToFile;
Keun-young Park8d01f632017-03-13 11:54:47 -070076
Tom Cherry81f5d3e2017-06-22 12:53:17 -070077namespace android {
78namespace init {
79
Nikita Ioffeba6968e2019-10-07 16:26:33 +010080static bool shutting_down = false;
81
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +010082static const std::set<std::string> kDebuggingServices{"tombstoned", "logd", "adbd", "console"};
83
84static std::vector<Service*> GetDebuggingServices(bool only_post_data) {
85 std::vector<Service*> ret;
86 ret.reserve(kDebuggingServices.size());
87 for (const auto& s : ServiceList::GetInstance()) {
88 if (kDebuggingServices.count(s->name()) && (!only_post_data || s->is_post_data())) {
89 ret.push_back(s.get());
90 }
91 }
92 return ret;
93}
94
Keun-young Park8d01f632017-03-13 11:54:47 -070095// represents umount status during reboot / shutdown.
96enum UmountStat {
97 /* umount succeeded. */
98 UMOUNT_STAT_SUCCESS = 0,
99 /* umount was not run. */
100 UMOUNT_STAT_SKIPPED = 1,
101 /* umount failed with timeout. */
102 UMOUNT_STAT_TIMEOUT = 2,
103 /* could not run due to error */
104 UMOUNT_STAT_ERROR = 3,
105 /* not used by init but reserved for other part to use this to represent the
106 the state where umount status before reboot is not found / available. */
107 UMOUNT_STAT_NOT_AVAILABLE = 4,
108};
109
110// Utility for struct mntent
111class MountEntry {
112 public:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700113 explicit MountEntry(const mntent& entry)
Keun-young Park8d01f632017-03-13 11:54:47 -0700114 : mnt_fsname_(entry.mnt_fsname),
115 mnt_dir_(entry.mnt_dir),
116 mnt_type_(entry.mnt_type),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700117 mnt_opts_(entry.mnt_opts) {}
Keun-young Park8d01f632017-03-13 11:54:47 -0700118
Jaegeuk Kim0f04f722017-09-25 10:55:39 -0700119 bool Umount(bool force) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800120 LOG(INFO) << "Unmounting " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Jaegeuk Kim0f04f722017-09-25 10:55:39 -0700121 int r = umount2(mnt_dir_.c_str(), force ? MNT_FORCE : 0);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700122 if (r == 0) {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800123 LOG(INFO) << "Umounted " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700124 return true;
125 } else {
Tom Cherryc9fec9d2018-02-15 14:26:58 -0800126 PLOG(WARNING) << "Cannot umount " << mnt_fsname_ << ":" << mnt_dir_ << " opts "
Keun-young Park2ba5c812017-03-29 12:54:40 -0700127 << mnt_opts_;
128 return false;
129 }
130 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700131
Keun-young Park2ba5c812017-03-29 12:54:40 -0700132 void DoFsck() {
133 int st;
134 if (IsF2Fs()) {
135 const char* f2fs_argv[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800136 "/system/bin/fsck.f2fs",
137 "-a",
138 mnt_fsname_.c_str(),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700139 };
Tom Cherry3a803eb2019-09-25 16:23:50 -0700140 logwrap_fork_execvp(arraysize(f2fs_argv), f2fs_argv, &st, false, LOG_KLOG, true,
141 nullptr);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700142 } else if (IsExt4()) {
143 const char* ext4_argv[] = {
Randall Huangdf2faa42019-01-15 15:00:56 +0800144 "/system/bin/e2fsck",
145 "-y",
146 mnt_fsname_.c_str(),
Keun-young Park2ba5c812017-03-29 12:54:40 -0700147 };
Tom Cherry3a803eb2019-09-25 16:23:50 -0700148 logwrap_fork_execvp(arraysize(ext4_argv), ext4_argv, &st, false, LOG_KLOG, true,
149 nullptr);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700150 }
151 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700152
153 static bool IsBlockDevice(const struct mntent& mntent) {
154 return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
155 }
156
157 static bool IsEmulatedDevice(const struct mntent& mntent) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700158 return android::base::StartsWith(mntent.mnt_fsname, "/data/");
Keun-young Park8d01f632017-03-13 11:54:47 -0700159 }
160
161 private:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700162 bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
163
164 bool IsExt4() const { return mnt_type_ == "ext4"; }
165
Keun-young Park8d01f632017-03-13 11:54:47 -0700166 std::string mnt_fsname_;
167 std::string mnt_dir_;
168 std::string mnt_type_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700169 std::string mnt_opts_;
Keun-young Park8d01f632017-03-13 11:54:47 -0700170};
171
172// Turn off backlight while we are performing power down cleanup activities.
173static void TurnOffBacklight() {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800174 Service* service = ServiceList::GetInstance().FindService("blank_screen");
175 if (service == nullptr) {
176 LOG(WARNING) << "cannot find blank_screen in TurnOffBacklight";
Keun-young Park8d01f632017-03-13 11:54:47 -0700177 return;
178 }
Tom Cherryd9872642018-10-11 10:38:05 -0700179 if (auto result = service->Start(); !result) {
180 LOG(WARNING) << "Could not start blank_screen service: " << result.error();
181 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700182}
183
Nikita Ioffe12a36072019-10-23 20:11:32 +0100184static Result<void> ShutdownVold() {
Keun-young Park8d01f632017-03-13 11:54:47 -0700185 const char* vdc_argv[] = {"/system/bin/vdc", "volume", "shutdown"};
186 int status;
Nikita Ioffe12a36072019-10-23 20:11:32 +0100187 if (logwrap_fork_execvp(arraysize(vdc_argv), vdc_argv, &status, false, LOG_KLOG, true,
188 nullptr) != 0) {
189 return ErrnoError() << "Failed to call 'vdc volume shutdown'";
190 }
191 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
192 return {};
193 }
194 return Error() << "'vdc volume shutdown' failed : " << status;
Keun-young Park8d01f632017-03-13 11:54:47 -0700195}
196
197static void LogShutdownTime(UmountStat stat, Timer* t) {
Tom Cherryede0d532017-07-06 14:20:11 -0700198 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration().count()) << ":"
199 << stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700200}
201
Tom Cherry2436e6b2019-09-19 11:16:19 -0700202static bool IsDataMounted() {
203 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
204 if (fp == nullptr) {
205 PLOG(ERROR) << "Failed to open /proc/mounts";
206 return false;
207 }
208 mntent* mentry;
209 while ((mentry = getmntent(fp.get())) != nullptr) {
210 if (mentry->mnt_dir == "/data"s) {
211 return true;
212 }
213 }
214 return false;
215}
216
217// Find all read+write block devices and emulated devices in /proc/mounts and add them to
218// the correpsponding list.
Keun-young Park8d01f632017-03-13 11:54:47 -0700219static bool FindPartitionsToUmount(std::vector<MountEntry>* blockDevPartitions,
Keun-young Park2ba5c812017-03-29 12:54:40 -0700220 std::vector<MountEntry>* emulatedPartitions, bool dump) {
Tom Cherryf274e782018-10-03 13:13:41 -0700221 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
Keun-young Park8d01f632017-03-13 11:54:47 -0700222 if (fp == nullptr) {
223 PLOG(ERROR) << "Failed to open /proc/mounts";
224 return false;
225 }
226 mntent* mentry;
227 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700228 if (dump) {
229 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
230 << mentry->mnt_opts << " type " << mentry->mnt_type;
231 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
Keun-young Park6e12b382017-07-17 12:20:33 -0700232 std::string mount_dir(mentry->mnt_dir);
233 // These are R/O partitions changed to R/W after adb remount.
234 // Do not umount them as shutdown critical services may rely on them.
Wei Wanga01c27e2017-07-25 10:52:08 -0700235 if (mount_dir != "/" && mount_dir != "/system" && mount_dir != "/vendor" &&
236 mount_dir != "/oem") {
Keun-young Park6e12b382017-07-17 12:20:33 -0700237 blockDevPartitions->emplace(blockDevPartitions->begin(), *mentry);
238 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700239 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700240 emulatedPartitions->emplace(emulatedPartitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700241 }
242 }
243 return true;
244}
245
Jonglin Lee28a2c922019-01-15 16:38:44 -0800246static void DumpUmountDebuggingInfo() {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700247 int status;
248 if (!security_getenforce()) {
249 LOG(INFO) << "Run lsof";
250 const char* lsof_argv[] = {"/system/bin/lsof"};
Tom Cherry3a803eb2019-09-25 16:23:50 -0700251 logwrap_fork_execvp(arraysize(lsof_argv), lsof_argv, &status, false, LOG_KLOG, true,
252 nullptr);
Keun-young Park8d01f632017-03-13 11:54:47 -0700253 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700254 FindPartitionsToUmount(nullptr, nullptr, true);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800255 // dump current CPU stack traces and uninterruptible tasks
josephjangaaddf282019-04-16 18:46:24 +0800256 WriteStringToFile("l", PROC_SYSRQ);
257 WriteStringToFile("w", PROC_SYSRQ);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700258}
259
Tom Cherryede0d532017-07-06 14:20:11 -0700260static UmountStat UmountPartitions(std::chrono::milliseconds timeout) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700261 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700262 /* data partition needs all pending writes to be completed and all emulated partitions
263 * umounted.If the current waiting is not good enough, give
264 * up and leave it to e2fsck after reboot to fix it.
265 */
266 while (true) {
267 std::vector<MountEntry> block_devices;
268 std::vector<MountEntry> emulated_devices;
269 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
270 return UMOUNT_STAT_ERROR;
271 }
272 if (block_devices.size() == 0) {
Wei Wang8c00e422017-08-16 14:01:46 -0700273 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700274 }
Wei Wang8c00e422017-08-16 14:01:46 -0700275 bool unmount_done = true;
276 if (emulated_devices.size() > 0) {
Wei Wang25dc30f2017-10-23 15:32:03 -0700277 for (auto& entry : emulated_devices) {
278 if (!entry.Umount(false)) unmount_done = false;
279 }
Wei Wang8c00e422017-08-16 14:01:46 -0700280 if (unmount_done) {
281 sync();
282 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700283 }
Wei Wang25dc30f2017-10-23 15:32:03 -0700284 for (auto& entry : block_devices) {
285 if (!entry.Umount(timeout == 0ms)) unmount_done = false;
286 }
Wei Wang8c00e422017-08-16 14:01:46 -0700287 if (unmount_done) {
288 return UMOUNT_STAT_SUCCESS;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700289 }
Wei Wang8c00e422017-08-16 14:01:46 -0700290 if ((timeout < t.duration())) { // try umount at least once
291 return UMOUNT_STAT_TIMEOUT;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700292 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700293 std::this_thread::sleep_for(100ms);
294 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700295}
296
josephjangaaddf282019-04-16 18:46:24 +0800297static void KillAllProcesses() {
298 WriteStringToFile("i", PROC_SYSRQ);
299}
300
301// Create reboot/shutdwon monitor thread
302void RebootMonitorThread(unsigned int cmd, const std::string& rebootTarget, sem_t* reboot_semaphore,
303 std::chrono::milliseconds shutdown_timeout, bool* reboot_monitor_run) {
304 unsigned int remaining_shutdown_time = 0;
305
306 // 30 seconds more than the timeout passed to the thread as there is a final Umount pass
307 // after the timeout is reached.
308 constexpr unsigned int shutdown_watchdog_timeout_default = 30;
309 auto shutdown_watchdog_timeout = android::base::GetUintProperty(
310 "ro.build.shutdown.watchdog.timeout", shutdown_watchdog_timeout_default);
311 remaining_shutdown_time = shutdown_watchdog_timeout + shutdown_timeout.count() / 1000;
312
313 while (*reboot_monitor_run == true) {
314 if (TEMP_FAILURE_RETRY(sem_wait(reboot_semaphore)) == -1) {
315 LOG(ERROR) << "sem_wait failed and exit RebootMonitorThread()";
316 return;
317 }
318
319 timespec shutdown_timeout_timespec;
320 if (clock_gettime(CLOCK_MONOTONIC, &shutdown_timeout_timespec) == -1) {
321 LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
322 return;
323 }
324
325 // If there are some remaining shutdown time left from previous round, we use
326 // remaining time here.
327 shutdown_timeout_timespec.tv_sec += remaining_shutdown_time;
328
329 LOG(INFO) << "shutdown_timeout_timespec.tv_sec: " << shutdown_timeout_timespec.tv_sec;
330
331 int sem_return = 0;
332 while ((sem_return = sem_timedwait_monotonic_np(reboot_semaphore,
333 &shutdown_timeout_timespec)) == -1 &&
334 errno == EINTR) {
335 }
336
337 if (sem_return == -1) {
338 LOG(ERROR) << "Reboot thread timed out";
339
340 if (android::base::GetBoolProperty("ro.debuggable", false) == true) {
Tom Cherry2436e6b2019-09-19 11:16:19 -0700341 if (false) {
342 // SEPolicy will block debuggerd from running and this is intentional.
343 // But these lines are left to be enabled during debugging.
344 LOG(INFO) << "Try to dump init process call trace:";
345 const char* vdc_argv[] = {"/system/bin/debuggerd", "-b", "1"};
346 int status;
Tom Cherry3a803eb2019-09-25 16:23:50 -0700347 logwrap_fork_execvp(arraysize(vdc_argv), vdc_argv, &status, false, LOG_KLOG,
348 true, nullptr);
Tom Cherry2436e6b2019-09-19 11:16:19 -0700349 }
josephjangaaddf282019-04-16 18:46:24 +0800350 LOG(INFO) << "Show stack for all active CPU:";
351 WriteStringToFile("l", PROC_SYSRQ);
352
353 LOG(INFO) << "Show tasks that are in disk sleep(uninterruptable sleep), which are "
354 "like "
355 "blocked in mutex or hardware register access:";
356 WriteStringToFile("w", PROC_SYSRQ);
357 }
358
359 // In shutdown case,notify kernel to sync and umount fs to read-only before shutdown.
360 if (cmd == ANDROID_RB_POWEROFF || cmd == ANDROID_RB_THERMOFF) {
361 WriteStringToFile("s", PROC_SYSRQ);
362
363 WriteStringToFile("u", PROC_SYSRQ);
364
365 RebootSystem(cmd, rebootTarget);
366 }
367
368 LOG(ERROR) << "Trigger crash at last!";
369 WriteStringToFile("c", PROC_SYSRQ);
370 } else {
371 timespec current_time_timespec;
372
373 if (clock_gettime(CLOCK_MONOTONIC, &current_time_timespec) == -1) {
374 LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
375 return;
376 }
377
378 remaining_shutdown_time =
379 shutdown_timeout_timespec.tv_sec - current_time_timespec.tv_sec;
380
381 LOG(INFO) << "remaining_shutdown_time: " << remaining_shutdown_time;
382 }
383 }
384}
Keun-young Park3ee0df92017-03-27 11:21:09 -0700385
Keun-young Park8d01f632017-03-13 11:54:47 -0700386/* Try umounting all emulated file systems R/W block device cfile systems.
387 * This will just try umount and give it up if it fails.
388 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
389 * and necessary check can be done at the next reboot.
390 * For safer shutdown, caller needs to make sure that
391 * all processes / emulated partition for the target fs are all cleaned-up.
392 *
393 * return true when umount was successful. false when timed out.
394 */
josephjangaaddf282019-04-16 18:46:24 +0800395static UmountStat TryUmountAndFsck(unsigned int cmd, const std::string& rebootTarget, bool runFsck,
396 std::chrono::milliseconds timeout, sem_t* reboot_semaphore) {
Keun-young Park3ee0df92017-03-27 11:21:09 -0700397 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700398 std::vector<MountEntry> block_devices;
399 std::vector<MountEntry> emulated_devices;
Keun-young Park8d01f632017-03-13 11:54:47 -0700400
Keun-young Park2ba5c812017-03-29 12:54:40 -0700401 if (runFsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700402 return UMOUNT_STAT_ERROR;
403 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700404
Tom Cherryede0d532017-07-06 14:20:11 -0700405 UmountStat stat = UmountPartitions(timeout - t.duration());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700406 if (stat != UMOUNT_STAT_SUCCESS) {
407 LOG(INFO) << "umount timeout, last resort, kill all and try";
Jonglin Lee28a2c922019-01-15 16:38:44 -0800408 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park3ee0df92017-03-27 11:21:09 -0700409 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700410 // 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 -0700411 UmountStat st = UmountPartitions(0ms);
Jonglin Lee28a2c922019-01-15 16:38:44 -0800412 if ((st != UMOUNT_STAT_SUCCESS) && DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park8d01f632017-03-13 11:54:47 -0700413 }
414
Keun-young Park2ba5c812017-03-29 12:54:40 -0700415 if (stat == UMOUNT_STAT_SUCCESS && runFsck) {
josephjangaaddf282019-04-16 18:46:24 +0800416 LOG(INFO) << "Pause reboot monitor thread before fsck";
417 sem_post(reboot_semaphore);
418
Keun-young Park2ba5c812017-03-29 12:54:40 -0700419 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
420 // and should not affect reboot time.
421 for (auto& entry : block_devices) {
422 entry.DoFsck();
423 }
josephjangaaddf282019-04-16 18:46:24 +0800424
425 LOG(INFO) << "Resume reboot monitor thread after fsck";
426 sem_post(reboot_semaphore);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700427 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700428 return stat;
429}
430
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800431// zram is able to use backing device on top of a loopback device.
432// In order to unmount /data successfully, we have to kill the loopback device first
433#define ZRAM_DEVICE "/dev/block/zram0"
434#define ZRAM_RESET "/sys/block/zram0/reset"
435#define ZRAM_BACK_DEV "/sys/block/zram0/backing_dev"
Nikita Ioffe12a36072019-10-23 20:11:32 +0100436static Result<void> KillZramBackingDevice() {
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800437 std::string backing_dev;
Nikita Ioffe12a36072019-10-23 20:11:32 +0100438 if (!android::base::ReadFileToString(ZRAM_BACK_DEV, &backing_dev)) return {};
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800439
Nikita Ioffe12a36072019-10-23 20:11:32 +0100440 if (!android::base::StartsWith(backing_dev, "/dev/block/loop")) return {};
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800441
442 // cut the last "\n"
443 backing_dev.erase(backing_dev.length() - 1);
444
445 // shutdown zram handle
446 Timer swap_timer;
447 LOG(INFO) << "swapoff() start...";
448 if (swapoff(ZRAM_DEVICE) == -1) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100449 return ErrnoError() << "zram_backing_dev: swapoff (" << backing_dev << ")"
450 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800451 }
452 LOG(INFO) << "swapoff() took " << swap_timer;;
453
josephjangaaddf282019-04-16 18:46:24 +0800454 if (!WriteStringToFile("1", ZRAM_RESET)) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100455 return Error() << "zram_backing_dev: reset (" << backing_dev << ")"
456 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800457 }
458
459 // clear loopback device
460 unique_fd loop(TEMP_FAILURE_RETRY(open(backing_dev.c_str(), O_RDWR | O_CLOEXEC)));
461 if (loop.get() < 0) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100462 return ErrnoError() << "zram_backing_dev: open(" << backing_dev << ")"
463 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800464 }
465
466 if (ioctl(loop.get(), LOOP_CLR_FD, 0) < 0) {
Nikita Ioffe12a36072019-10-23 20:11:32 +0100467 return ErrnoError() << "zram_backing_dev: loop_clear (" << backing_dev << ")"
468 << " failed";
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800469 }
470 LOG(INFO) << "zram_backing_dev: `" << backing_dev << "` is cleared successfully.";
Nikita Ioffe12a36072019-10-23 20:11:32 +0100471 return {};
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800472}
473
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100474// Stops given services, waits for them to be stopped for |timeout| ms.
475// If terminate is true, then SIGTERM is sent to services, otherwise SIGKILL is sent.
476static void StopServices(const std::vector<Service*>& services, std::chrono::milliseconds timeout,
477 bool terminate) {
478 LOG(INFO) << "Stopping " << services.size() << " services by sending "
479 << (terminate ? "SIGTERM" : "SIGKILL");
480 std::vector<pid_t> pids;
481 pids.reserve(services.size());
482 for (const auto& s : services) {
483 if (s->pid() > 0) {
484 pids.push_back(s->pid());
485 }
486 if (terminate) {
487 s->Terminate();
488 } else {
489 s->Stop();
490 }
491 }
492 if (timeout > 0ms) {
493 WaitToBeReaped(pids, timeout);
494 } else {
495 // Even if we don't to wait for services to stop, we still optimistically reap zombies.
496 ReapAnyOutstandingChildren();
497 }
498}
499
500// Like StopServices, but also logs all the services that failed to stop after the provided timeout.
501// Returns number of violators.
502static int StopServicesAndLogViolations(const std::vector<Service*>& services,
503 std::chrono::milliseconds timeout, bool terminate) {
504 StopServices(services, timeout, terminate);
505 int still_running = 0;
506 for (const auto& s : services) {
507 if (s->IsRunning()) {
508 LOG(ERROR) << "[service-misbehaving] : service '" << s->name() << "' is still running "
509 << timeout.count() << "ms after receiving "
510 << (terminate ? "SIGTERM" : "SIGKILL");
511 still_running++;
512 }
513 }
514 return still_running;
515}
516
Tom Cherry44aceed2018-08-03 13:36:18 -0700517//* Reboot / shutdown the system.
518// cmd ANDROID_RB_* as defined in android_reboot.h
519// reason Reason string like "reboot", "shutdown,userrequested"
520// rebootTarget Reboot target string like "bootloader". Otherwise, it should be an
521// empty string.
522// runFsck Whether to run fsck after umount is done.
523//
524static void DoReboot(unsigned int cmd, const std::string& reason, const std::string& rebootTarget,
525 bool runFsck) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700526 Timer t;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700527 LOG(INFO) << "Reboot start, reason: " << reason << ", rebootTarget: " << rebootTarget;
528
Tom Cherry2436e6b2019-09-19 11:16:19 -0700529 // If /data isn't mounted then we can skip the extra reboot steps below, since we don't need to
530 // worry about unmounting it.
531 if (!IsDataMounted()) {
532 sync();
533 RebootSystem(cmd, rebootTarget);
534 abort();
535 }
536
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700537 // Ensure last reboot reason is reduced to canonical
538 // alias reported in bootloader or system boot reason.
539 size_t skip = 0;
540 std::vector<std::string> reasons = Split(reason, ",");
541 if (reasons.size() >= 2 && reasons[0] == "reboot" &&
542 (reasons[1] == "recovery" || reasons[1] == "bootloader" || reasons[1] == "cold" ||
543 reasons[1] == "hard" || reasons[1] == "warm")) {
544 skip = strlen("reboot,");
545 }
546 property_set(LAST_REBOOT_REASON_PROPERTY, reason.c_str() + skip);
547 sync();
548
549 bool is_thermal_shutdown = cmd == ANDROID_RB_THERMOFF;
550
551 auto shutdown_timeout = 0ms;
552 if (!SHUTDOWN_ZERO_TIMEOUT) {
Wei Wangb5de0882018-10-09 12:42:06 -0700553 constexpr unsigned int shutdown_timeout_default = 6;
554 constexpr unsigned int max_thermal_shutdown_timeout = 3;
555 auto shutdown_timeout_final = android::base::GetUintProperty("ro.build.shutdown_timeout",
556 shutdown_timeout_default);
557 if (is_thermal_shutdown && shutdown_timeout_final > max_thermal_shutdown_timeout) {
558 shutdown_timeout_final = max_thermal_shutdown_timeout;
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700559 }
Wei Wangb5de0882018-10-09 12:42:06 -0700560 shutdown_timeout = std::chrono::seconds(shutdown_timeout_final);
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700561 }
562 LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " ms";
563
josephjangaaddf282019-04-16 18:46:24 +0800564 sem_t reboot_semaphore;
565 if (sem_init(&reboot_semaphore, false, 0) == -1) {
566 // These should never fail, but if they do, skip the graceful reboot and reboot immediately.
567 LOG(ERROR) << "sem_init() fail and RebootSystem() return!";
568 RebootSystem(cmd, rebootTarget);
569 }
570
571 // Start a thread to monitor init shutdown process
572 LOG(INFO) << "Create reboot monitor thread.";
573 bool reboot_monitor_run = true;
574 std::thread reboot_monitor_thread(&RebootMonitorThread, cmd, rebootTarget, &reboot_semaphore,
575 shutdown_timeout, &reboot_monitor_run);
576 reboot_monitor_thread.detach();
577
578 // Start reboot monitor thread
579 sem_post(&reboot_semaphore);
580
Keun-young Park7830d592017-03-27 16:07:02 -0700581 // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700582 const std::set<std::string> to_starts{"watchdogd"};
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100583 std::vector<Service*> stop_first;
584 stop_first.reserve(ServiceList::GetInstance().services().size());
Tom Cherry911b9b12017-07-27 16:20:58 -0700585 for (const auto& s : ServiceList::GetInstance()) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100586 if (kDebuggingServices.count(s->name())) {
587 // keep debugging tools until non critical ones are all gone.
Keun-young Park7830d592017-03-27 16:07:02 -0700588 s->SetShutdownCritical();
589 } else if (to_starts.count(s->name())) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700590 if (auto result = s->Start(); !result) {
591 LOG(ERROR) << "Could not start shutdown 'to_start' service '" << s->name()
592 << "': " << result.error();
593 }
Keun-young Park7830d592017-03-27 16:07:02 -0700594 s->SetShutdownCritical();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700595 } else if (s->IsShutdownCritical()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700596 // Start shutdown critical service if not started.
597 if (auto result = s->Start(); !result) {
598 LOG(ERROR) << "Could not start shutdown critical service '" << s->name()
599 << "': " << result.error();
600 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100601 } else {
602 stop_first.push_back(s.get());
Keun-young Park8d01f632017-03-13 11:54:47 -0700603 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700604 }
Keun-young Park7830d592017-03-27 16:07:02 -0700605
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800606 // remaining operations (specifically fsck) may take a substantial duration
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700607 if (cmd == ANDROID_RB_POWEROFF || is_thermal_shutdown) {
Steven Morelandd5eccfd2018-01-19 13:01:53 -0800608 TurnOffBacklight();
609 }
610
Tom Cherry911b9b12017-07-27 16:20:58 -0700611 Service* bootAnim = ServiceList::GetInstance().FindService("bootanim");
612 Service* surfaceFlinger = ServiceList::GetInstance().FindService("surfaceflinger");
Keun-young Park7830d592017-03-27 16:07:02 -0700613 if (bootAnim != nullptr && surfaceFlinger != nullptr && surfaceFlinger->IsRunning()) {
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800614 bool do_shutdown_animation = GetBoolProperty("ro.init.shutdown_animation", false);
615
616 if (do_shutdown_animation) {
617 property_set("service.bootanim.exit", "0");
618 // Could be in the middle of animation. Stop and start so that it can pick
619 // up the right mode.
620 bootAnim->Stop();
621 }
622
Tom Cherry911b9b12017-07-27 16:20:58 -0700623 for (const auto& service : ServiceList::GetInstance()) {
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800624 if (service->classnames().count("animation") == 0) {
625 continue;
626 }
627
628 // start all animation classes if stopped.
629 if (do_shutdown_animation) {
Tom Cherry9949ec52019-05-16 16:54:49 -0700630 service->Start();
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800631 }
632 service->SetShutdownCritical(); // will not check animation class separately
633 }
634
635 if (do_shutdown_animation) {
Tom Cherry9949ec52019-05-16 16:54:49 -0700636 bootAnim->Start();
Tom Cherry4f4cacc2019-01-08 10:39:00 -0800637 surfaceFlinger->SetShutdownCritical();
638 bootAnim->SetShutdownCritical();
Tom Cherry911b9b12017-07-27 16:20:58 -0700639 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700640 }
Keun-young Park7830d592017-03-27 16:07:02 -0700641
Keun-young Park8d01f632017-03-13 11:54:47 -0700642 // optional shutdown step
643 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Keun-young Park30173872017-07-18 10:58:28 -0700644 if (shutdown_timeout > 0ms) {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100645 StopServicesAndLogViolations(stop_first, shutdown_timeout / 2, true /* SIGTERM */);
Keun-young Park8d01f632017-03-13 11:54:47 -0700646 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100647 // Send SIGKILL to ones that didn't terminate cleanly.
648 StopServicesAndLogViolations(stop_first, 0ms, false /* SIGKILL */);
Luis Hector Chavez92c49bc2018-07-27 11:19:25 -0700649 SubcontextTerminate();
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100650 // Reap subcontext pids.
Tom Cherryeeee8312017-07-28 15:22:23 -0700651 ReapAnyOutstandingChildren();
Keun-young Park8d01f632017-03-13 11:54:47 -0700652
653 // 3. send volume shutdown to vold
Tom Cherry911b9b12017-07-27 16:20:58 -0700654 Service* voldService = ServiceList::GetInstance().FindService("vold");
Keun-young Park8d01f632017-03-13 11:54:47 -0700655 if (voldService != nullptr && voldService->IsRunning()) {
656 ShutdownVold();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700657 voldService->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700658 } else {
659 LOG(INFO) << "vold not running, skipping vold shutdown";
660 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700661 // logcat stopped here
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100662 StopServices(GetDebuggingServices(false /* only_post_data */), 0ms, false /* SIGKILL */);
Keun-young Park8d01f632017-03-13 11:54:47 -0700663 // 4. sync, try umount, and optionally run fsck for user shutdown
Tom Cherry1f9d5402018-03-15 10:22:40 -0700664 {
665 Timer sync_timer;
666 LOG(INFO) << "sync() before umount...";
667 sync();
668 LOG(INFO) << "sync() before umount took" << sync_timer;
669 }
Jaegeuk Kim2aedc822018-11-20 13:27:06 -0800670 // 5. drop caches and disable zram backing device, if exist
671 KillZramBackingDevice();
672
josephjangaaddf282019-04-16 18:46:24 +0800673 UmountStat stat = TryUmountAndFsck(cmd, rebootTarget, runFsck, shutdown_timeout - t.duration(),
674 &reboot_semaphore);
Keun-young Park2ba5c812017-03-29 12:54:40 -0700675 // Follow what linux shutdown is doing: one more sync with little bit delay
Tom Cherry1f9d5402018-03-15 10:22:40 -0700676 {
677 Timer sync_timer;
678 LOG(INFO) << "sync() after umount...";
679 sync();
680 LOG(INFO) << "sync() after umount took" << sync_timer;
681 }
Tom Cherry0a72e6c2018-03-19 16:19:01 -0700682 if (!is_thermal_shutdown) std::this_thread::sleep_for(100ms);
Keun-young Park8d01f632017-03-13 11:54:47 -0700683 LogShutdownTime(stat, &t);
josephjangaaddf282019-04-16 18:46:24 +0800684
685 // Send signal to terminate reboot monitor thread.
686 reboot_monitor_run = false;
687 sem_post(&reboot_semaphore);
688
Keun-young Park8d01f632017-03-13 11:54:47 -0700689 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
690 RebootSystem(cmd, rebootTarget);
691 abort();
692}
Tom Cherry98ad32a2017-04-17 16:34:20 -0700693
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100694static void EnterShutdown() {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100695 LOG(INFO) << "Entering shutdown mode";
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100696 shutting_down = true;
697 // Skip wait for prop if it is in progress
698 ResetWaitForProp();
699 // Clear EXEC flag if there is one pending
700 for (const auto& s : ServiceList::GetInstance()) {
701 s->UnSetExec();
702 }
703 // We no longer process messages about properties changing coming from property service, so we
704 // need to tell property service to stop sending us these messages, otherwise it'll fill the
705 // buffers and block indefinitely, causing future property sets, including those that init makes
706 // during shutdown in Service::NotifyStateChange() to also block indefinitely.
707 SendStopSendingMessagesMessage();
708}
709
710static void LeaveShutdown() {
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100711 LOG(INFO) << "Leaving shutdown mode";
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100712 shutting_down = false;
713 SendStartSendingMessagesMessage();
714}
715
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100716static Result<void> DoUserspaceReboot() {
717 LOG(INFO) << "Userspace reboot initiated";
718 auto guard = android::base::make_scope_guard([] {
719 // Leave shutdown so that we can handle a full reboot.
720 LeaveShutdown();
Tom Cherry0dbfea72019-10-11 13:18:44 -0700721 TriggerShutdown("reboot,abort-userspace-reboot");
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100722 });
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100723 // Triggering userspace-reboot-requested will result in a bunch of set_prop
724 // actions. We should make sure, that all of them are propagated before
725 // proceeding with userspace reboot.
726 // TODO(b/135984674): implement proper synchronization logic.
727 std::this_thread::sleep_for(500ms);
728 EnterShutdown();
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100729 std::vector<Service*> stop_first;
730 // Remember the services that were enabled. We will need to manually enable them again otherwise
731 // triggers like class_start won't restart them.
732 std::vector<Service*> were_enabled;
733 stop_first.reserve(ServiceList::GetInstance().services().size());
734 for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
735 if (s->is_post_data() && !kDebuggingServices.count(s->name())) {
736 stop_first.push_back(s);
737 }
738 if (s->is_post_data() && s->IsEnabled()) {
739 were_enabled.push_back(s);
740 }
741 }
742 // TODO(b/135984674): do we need shutdown animation for userspace reboot?
743 // TODO(b/135984674): control userspace timeout via read-only property?
744 StopServicesAndLogViolations(stop_first, 10s, true /* SIGTERM */);
745 if (int r = StopServicesAndLogViolations(stop_first, 20s, false /* SIGKILL */); r > 0) {
746 // TODO(b/135984674): store information about offending services for debugging.
747 return Error() << r << " post-data services are still running";
748 }
Nikita Ioffe12a36072019-10-23 20:11:32 +0100749 // We only really need to restart vold if userdata is ext4 filesystem.
750 // TODO(b/135984674): get userdata fs type here, and do nothing in case of f2fs.
751 // First shutdown volumes managed by vold. They will be recreated by
752 // system_server.
753 Service* vold_service = ServiceList::GetInstance().FindService("vold");
754 if (vold_service != nullptr && vold_service->IsRunning()) {
755 if (auto result = ShutdownVold(); !result) {
756 return result;
757 }
758 LOG(INFO) << "Restarting vold";
759 vold_service->Restart();
760 }
761 // Again, we only need to kill zram backing device in case of ext4 userdata.
762 // TODO(b/135984674): get userdata fs type here, and do nothing in case of f2fs.
763 if (auto result = KillZramBackingDevice(); !result) {
764 return result;
765 }
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100766 if (int r = StopServicesAndLogViolations(GetDebuggingServices(true /* only_post_data */), 5s,
767 false /* SIGKILL */);
768 r > 0) {
769 // TODO(b/135984674): store information about offending services for debugging.
770 return Error() << r << " debugging services are still running";
771 }
772 // TODO(b/135984674): deactivate APEX modules and switch back to bootstrap namespace.
773 // Re-enable services
774 for (const auto& s : were_enabled) {
775 LOG(INFO) << "Re-enabling service '" << s->name() << "'";
776 s->Enable();
777 }
778 LeaveShutdown();
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100779 ActionManager::GetInstance().QueueEventTrigger("userspace-reboot-resume");
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100780 guard.Disable(); // Go on with userspace reboot.
781 return {};
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100782}
783
784static void HandleUserspaceReboot() {
785 LOG(INFO) << "Clearing queue and starting userspace-reboot-requested trigger";
786 auto& am = ActionManager::GetInstance();
787 am.ClearQueue();
788 am.QueueEventTrigger("userspace-reboot-requested");
Nikita Ioffe3f4b0d62019-10-09 15:23:02 +0100789 auto handler = [](const BuiltinArguments&) { return DoUserspaceReboot(); };
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100790 am.QueueBuiltinAction(handler, "userspace-reboot");
791}
792
793void HandlePowerctlMessage(const std::string& command) {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700794 unsigned int cmd = 0;
Mark Salyzyn62909822017-10-09 09:27:16 -0700795 std::vector<std::string> cmd_params = Split(command, ",");
Tom Cherry98ad32a2017-04-17 16:34:20 -0700796 std::string reboot_target = "";
797 bool run_fsck = false;
798 bool command_invalid = false;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100799 bool userspace_reboot = false;
Tom Cherry98ad32a2017-04-17 16:34:20 -0700800
Mark Salyzynd7931f12019-07-10 10:33:09 -0700801 if (cmd_params[0] == "shutdown") {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700802 cmd = ANDROID_RB_POWEROFF;
Mark Salyzynd7931f12019-07-10 10:33:09 -0700803 if (cmd_params.size() >= 2) {
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700804 if (cmd_params[1] == "userrequested") {
805 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
806 // Run fsck once the file system is remounted in read-only mode.
807 run_fsck = true;
808 } else if (cmd_params[1] == "thermal") {
Mark Salyzynbfd05b62017-09-26 11:10:12 -0700809 // Turn off sources of heat immediately.
810 TurnOffBacklight();
Mark Salyzyn73e6b492017-08-14 15:56:53 -0700811 // run_fsck is false to avoid delay
812 cmd = ANDROID_RB_THERMOFF;
813 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700814 }
815 } else if (cmd_params[0] == "reboot") {
816 cmd = ANDROID_RB_RESTART2;
817 if (cmd_params.size() >= 2) {
818 reboot_target = cmd_params[1];
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100819 if (reboot_target == "userspace") {
820 LOG(INFO) << "Userspace reboot requested";
821 userspace_reboot = true;
822 }
Hridya Valsaraju54258262018-09-19 21:14:18 -0700823 // adb reboot fastboot should boot into bootloader for devices not
824 // supporting logical partitions.
825 if (reboot_target == "fastboot" &&
Yifan Hong0e0f8182018-11-16 12:49:06 -0800826 !android::base::GetBoolProperty("ro.boot.dynamic_partitions", false)) {
Hridya Valsaraju54258262018-09-19 21:14:18 -0700827 reboot_target = "bootloader";
828 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700829 // When rebooting to the bootloader notify the bootloader writing
830 // also the BCB.
831 if (reboot_target == "bootloader") {
832 std::string err;
833 if (!write_reboot_bootloader(&err)) {
834 LOG(ERROR) << "reboot-bootloader: Error writing "
835 "bootloader_message: "
836 << err;
837 }
Tianjie Xu5e98b632019-07-18 12:48:28 -0700838 } else if (reboot_target == "recovery") {
839 bootloader_message boot = {};
840 if (std::string err; !read_bootloader_message(&boot, &err)) {
841 LOG(ERROR) << "Failed to read bootloader message: " << err;
842 }
843 // Update the boot command field if it's empty, and preserve
844 // the other arguments in the bootloader message.
845 if (boot.command[0] == '\0') {
846 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
847 if (std::string err; !write_bootloader_message(boot, &err)) {
848 LOG(ERROR) << "Failed to set bootloader message: " << err;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100849 return;
Tianjie Xu5e98b632019-07-18 12:48:28 -0700850 }
851 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700852 } else if (reboot_target == "sideload" || reboot_target == "sideload-auto-reboot" ||
853 reboot_target == "fastboot") {
854 std::string arg = reboot_target == "sideload-auto-reboot" ? "sideload_auto_reboot"
855 : reboot_target;
856 const std::vector<std::string> options = {
857 "--" + arg,
858 };
859 std::string err;
860 if (!write_bootloader_message(options, &err)) {
861 LOG(ERROR) << "Failed to set bootloader message: " << err;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100862 return;
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700863 }
864 reboot_target = "recovery";
Tom Cherry98ad32a2017-04-17 16:34:20 -0700865 }
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700866
Mark Salyzynd7931f12019-07-10 10:33:09 -0700867 // If there are additional parameter, pass them along
868 for (size_t i = 2; (cmd_params.size() > i) && cmd_params[i].size(); ++i) {
869 reboot_target += "," + cmd_params[i];
Tom Cherry98ad32a2017-04-17 16:34:20 -0700870 }
871 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700872 } else {
873 command_invalid = true;
874 }
875 if (command_invalid) {
876 LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100877 return;
878 }
879
880 if (userspace_reboot) {
881 HandleUserspaceReboot();
882 return;
Tom Cherry98ad32a2017-04-17 16:34:20 -0700883 }
884
Wei Wangeeab4912017-06-27 22:08:45 -0700885 LOG(INFO) << "Clear action queue and start shutdown trigger";
886 ActionManager::GetInstance().ClearQueue();
887 // Queue shutdown trigger first
888 ActionManager::GetInstance().QueueEventTrigger("shutdown");
889 // Queue built-in shutdown_done
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700890 auto shutdown_handler = [cmd, command, reboot_target, run_fsck](const BuiltinArguments&) {
Wei Wangeeab4912017-06-27 22:08:45 -0700891 DoReboot(cmd, command, reboot_target, run_fsck);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700892 return Result<void>{};
Wei Wangeeab4912017-06-27 22:08:45 -0700893 };
894 ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
895
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100896 EnterShutdown();
897}
Wei Wangeeab4912017-06-27 22:08:45 -0700898
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100899bool IsShuttingDown() {
900 return shutting_down;
Tom Cherry98ad32a2017-04-17 16:34:20 -0700901}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700902
903} // namespace init
904} // namespace android