blob: 8de3c785a017eb177f024b7acdea965764180ed0 [file] [log] [blame]
Keun-young Park8d01f632017-03-13 11:54:47 -07001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Tom Cherry3f5eaae52017-04-06 16:30:22 -070016
17#include "reboot.h"
18
Keun-young Park8d01f632017-03-13 11:54:47 -070019#include <dirent.h>
20#include <fcntl.h>
Keun-young Park2ba5c812017-03-29 12:54:40 -070021#include <linux/fs.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070022#include <mntent.h>
Keun-young Park2ba5c812017-03-29 12:54:40 -070023#include <selinux/selinux.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070024#include <sys/cdefs.h>
Keun-young Park2ba5c812017-03-29 12:54:40 -070025#include <sys/ioctl.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070026#include <sys/mount.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070027#include <sys/reboot.h>
28#include <sys/stat.h>
29#include <sys/syscall.h>
30#include <sys/types.h>
31#include <sys/wait.h>
32
33#include <memory>
Keun-young Park7830d592017-03-27 16:07:02 -070034#include <set>
Keun-young Park8d01f632017-03-13 11:54:47 -070035#include <thread>
36#include <vector>
37
38#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070039#include <android-base/logging.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070040#include <android-base/macros.h>
Tom Cherryccf23532017-03-28 16:40:41 -070041#include <android-base/properties.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070042#include <android-base/stringprintf.h>
43#include <android-base/strings.h>
Keun-young Park2ba5c812017-03-29 12:54:40 -070044#include <android-base/unique_fd.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070045#include <bootloader_message/bootloader_message.h>
46#include <cutils/android_reboot.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070047#include <fs_mgr.h>
48#include <logwrap/logwrap.h>
49
Keun-young Park7830d592017-03-27 16:07:02 -070050#include "property_service.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070051#include "service.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070052
53using android::base::StringPrintf;
54
55// represents umount status during reboot / shutdown.
56enum UmountStat {
57 /* umount succeeded. */
58 UMOUNT_STAT_SUCCESS = 0,
59 /* umount was not run. */
60 UMOUNT_STAT_SKIPPED = 1,
61 /* umount failed with timeout. */
62 UMOUNT_STAT_TIMEOUT = 2,
63 /* could not run due to error */
64 UMOUNT_STAT_ERROR = 3,
65 /* not used by init but reserved for other part to use this to represent the
66 the state where umount status before reboot is not found / available. */
67 UMOUNT_STAT_NOT_AVAILABLE = 4,
68};
69
70// Utility for struct mntent
71class MountEntry {
72 public:
Keun-young Park2ba5c812017-03-29 12:54:40 -070073 explicit MountEntry(const mntent& entry)
Keun-young Park8d01f632017-03-13 11:54:47 -070074 : mnt_fsname_(entry.mnt_fsname),
75 mnt_dir_(entry.mnt_dir),
76 mnt_type_(entry.mnt_type),
Keun-young Park2ba5c812017-03-29 12:54:40 -070077 mnt_opts_(entry.mnt_opts) {}
Keun-young Park8d01f632017-03-13 11:54:47 -070078
Keun-young Park2ba5c812017-03-29 12:54:40 -070079 bool Umount() {
80 int r = umount2(mnt_dir_.c_str(), 0);
81 if (r == 0) {
82 LOG(INFO) << "umounted " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
83 return true;
84 } else {
85 PLOG(WARNING) << "cannot umount " << mnt_fsname_ << ":" << mnt_dir_ << " opts "
86 << mnt_opts_;
87 return false;
88 }
89 }
Keun-young Park8d01f632017-03-13 11:54:47 -070090
Keun-young Park2ba5c812017-03-29 12:54:40 -070091 void DoFsck() {
92 int st;
93 if (IsF2Fs()) {
94 const char* f2fs_argv[] = {
95 "/system/bin/fsck.f2fs", "-f", mnt_fsname_.c_str(),
96 };
97 android_fork_execvp_ext(arraysize(f2fs_argv), (char**)f2fs_argv, &st, true, LOG_KLOG,
98 true, nullptr, nullptr, 0);
99 } else if (IsExt4()) {
100 const char* ext4_argv[] = {
101 "/system/bin/e2fsck", "-f", "-y", mnt_fsname_.c_str(),
102 };
103 android_fork_execvp_ext(arraysize(ext4_argv), (char**)ext4_argv, &st, true, LOG_KLOG,
104 true, nullptr, nullptr, 0);
105 }
106 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700107
108 static bool IsBlockDevice(const struct mntent& mntent) {
109 return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
110 }
111
112 static bool IsEmulatedDevice(const struct mntent& mntent) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700113 return android::base::StartsWith(mntent.mnt_fsname, "/data/");
Keun-young Park8d01f632017-03-13 11:54:47 -0700114 }
115
116 private:
Keun-young Park2ba5c812017-03-29 12:54:40 -0700117 bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
118
119 bool IsExt4() const { return mnt_type_ == "ext4"; }
120
Keun-young Park8d01f632017-03-13 11:54:47 -0700121 std::string mnt_fsname_;
122 std::string mnt_dir_;
123 std::string mnt_type_;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700124 std::string mnt_opts_;
Keun-young Park8d01f632017-03-13 11:54:47 -0700125};
126
127// Turn off backlight while we are performing power down cleanup activities.
128static void TurnOffBacklight() {
129 static constexpr char OFF[] = "0";
130
131 android::base::WriteStringToFile(OFF, "/sys/class/leds/lcd-backlight/brightness");
132
133 static const char backlightDir[] = "/sys/class/backlight";
134 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(backlightDir), closedir);
135 if (!dir) {
136 return;
137 }
138
139 struct dirent* dp;
140 while ((dp = readdir(dir.get())) != nullptr) {
141 if (((dp->d_type != DT_DIR) && (dp->d_type != DT_LNK)) || (dp->d_name[0] == '.')) {
142 continue;
143 }
144
145 std::string fileName = StringPrintf("%s/%s/brightness", backlightDir, dp->d_name);
146 android::base::WriteStringToFile(OFF, fileName);
147 }
148}
149
Keun-young Park8d01f632017-03-13 11:54:47 -0700150static void ShutdownVold() {
151 const char* vdc_argv[] = {"/system/bin/vdc", "volume", "shutdown"};
152 int status;
153 android_fork_execvp_ext(arraysize(vdc_argv), (char**)vdc_argv, &status, true, LOG_KLOG, true,
154 nullptr, nullptr, 0);
155}
156
157static void LogShutdownTime(UmountStat stat, Timer* t) {
158 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration_ms()) << ":" << stat;
159}
160
161static void __attribute__((noreturn))
162RebootSystem(unsigned int cmd, const std::string& rebootTarget) {
Keun-young Park3cd8c6f2017-03-23 15:33:16 -0700163 LOG(INFO) << "Reboot ending, jumping to kernel";
Keun-young Park8d01f632017-03-13 11:54:47 -0700164 switch (cmd) {
165 case ANDROID_RB_POWEROFF:
166 reboot(RB_POWER_OFF);
167 break;
168
169 case ANDROID_RB_RESTART2:
170 syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2,
171 LINUX_REBOOT_CMD_RESTART2, rebootTarget.c_str());
172 break;
173
174 case ANDROID_RB_THERMOFF:
175 reboot(RB_POWER_OFF);
176 break;
177 }
178 // In normal case, reboot should not return.
179 PLOG(FATAL) << "reboot call returned";
180 abort();
181}
182
183/* Find all read+write block devices and emulated devices in /proc/mounts
184 * and add them to correpsponding list.
185 */
186static bool FindPartitionsToUmount(std::vector<MountEntry>* blockDevPartitions,
Keun-young Park2ba5c812017-03-29 12:54:40 -0700187 std::vector<MountEntry>* emulatedPartitions, bool dump) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700188 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "r"), endmntent);
189 if (fp == nullptr) {
190 PLOG(ERROR) << "Failed to open /proc/mounts";
191 return false;
192 }
193 mntent* mentry;
194 while ((mentry = getmntent(fp.get())) != nullptr) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700195 if (dump) {
196 LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
197 << mentry->mnt_opts << " type " << mentry->mnt_type;
198 } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
199 blockDevPartitions->emplace(blockDevPartitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700200 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
Keun-young Park2ba5c812017-03-29 12:54:40 -0700201 emulatedPartitions->emplace(emulatedPartitions->begin(), *mentry);
Keun-young Park8d01f632017-03-13 11:54:47 -0700202 }
203 }
204 return true;
205}
206
Keun-young Park2ba5c812017-03-29 12:54:40 -0700207static void DumpUmountDebuggingInfo() {
208 int status;
209 if (!security_getenforce()) {
210 LOG(INFO) << "Run lsof";
211 const char* lsof_argv[] = {"/system/bin/lsof"};
212 android_fork_execvp_ext(arraysize(lsof_argv), (char**)lsof_argv, &status, true, LOG_KLOG,
213 true, nullptr, nullptr, 0);
Keun-young Park8d01f632017-03-13 11:54:47 -0700214 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700215 FindPartitionsToUmount(nullptr, nullptr, true);
216}
217
218static UmountStat UmountPartitions(int timeoutMs) {
219 Timer t;
220 UmountStat stat = UMOUNT_STAT_TIMEOUT;
221 int retry = 0;
222 /* data partition needs all pending writes to be completed and all emulated partitions
223 * umounted.If the current waiting is not good enough, give
224 * up and leave it to e2fsck after reboot to fix it.
225 */
226 while (true) {
227 std::vector<MountEntry> block_devices;
228 std::vector<MountEntry> emulated_devices;
229 if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
230 return UMOUNT_STAT_ERROR;
231 }
232 if (block_devices.size() == 0) {
233 stat = UMOUNT_STAT_SUCCESS;
234 break;
235 }
236 if ((timeoutMs < t.duration_ms()) && retry > 0) { // try umount at least once
237 stat = UMOUNT_STAT_TIMEOUT;
238 break;
239 }
240 if (emulated_devices.size() > 0 &&
241 std::all_of(emulated_devices.begin(), emulated_devices.end(),
242 [](auto& entry) { return entry.Umount(); })) {
243 sync();
244 }
245 for (auto& entry : block_devices) {
246 entry.Umount();
247 }
248 retry++;
249 std::this_thread::sleep_for(100ms);
250 }
251 return stat;
Keun-young Park8d01f632017-03-13 11:54:47 -0700252}
253
Keun-young Park3ee0df92017-03-27 11:21:09 -0700254static void KillAllProcesses() { android::base::WriteStringToFile("i", "/proc/sysrq-trigger"); }
255
Keun-young Park8d01f632017-03-13 11:54:47 -0700256/* Try umounting all emulated file systems R/W block device cfile systems.
257 * This will just try umount and give it up if it fails.
258 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
259 * and necessary check can be done at the next reboot.
260 * For safer shutdown, caller needs to make sure that
261 * all processes / emulated partition for the target fs are all cleaned-up.
262 *
263 * return true when umount was successful. false when timed out.
264 */
Keun-young Park3ee0df92017-03-27 11:21:09 -0700265static UmountStat TryUmountAndFsck(bool runFsck, int timeoutMs) {
266 Timer t;
Keun-young Park2ba5c812017-03-29 12:54:40 -0700267 std::vector<MountEntry> block_devices;
268 std::vector<MountEntry> emulated_devices;
Keun-young Park8d01f632017-03-13 11:54:47 -0700269
270 TurnOffBacklight(); // this part can take time. save power.
271
Keun-young Park2ba5c812017-03-29 12:54:40 -0700272 if (runFsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700273 return UMOUNT_STAT_ERROR;
274 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700275
276 UmountStat stat = UmountPartitions(timeoutMs - t.duration_ms());
277 if (stat != UMOUNT_STAT_SUCCESS) {
278 LOG(INFO) << "umount timeout, last resort, kill all and try";
279 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park3ee0df92017-03-27 11:21:09 -0700280 KillAllProcesses();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700281 // even if it succeeds, still it is timeout and do not run fsck with all processes killed
282 UmountPartitions(0);
283 if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
Keun-young Park8d01f632017-03-13 11:54:47 -0700284 }
285
Keun-young Park2ba5c812017-03-29 12:54:40 -0700286 if (stat == UMOUNT_STAT_SUCCESS && runFsck) {
287 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
288 // and should not affect reboot time.
289 for (auto& entry : block_devices) {
290 entry.DoFsck();
291 }
292 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700293 return stat;
294}
295
Keun-young Park8d01f632017-03-13 11:54:47 -0700296static void __attribute__((noreturn)) DoThermalOff() {
297 LOG(WARNING) << "Thermal system shutdown";
Keun-young Park2ba5c812017-03-29 12:54:40 -0700298 sync();
Keun-young Park8d01f632017-03-13 11:54:47 -0700299 RebootSystem(ANDROID_RB_THERMOFF, "");
300 abort();
301}
302
303void DoReboot(unsigned int cmd, const std::string& reason, const std::string& rebootTarget,
304 bool runFsck) {
305 Timer t;
Keun-young Park3cd8c6f2017-03-23 15:33:16 -0700306 LOG(INFO) << "Reboot start, reason: " << reason << ", rebootTarget: " << rebootTarget;
Keun-young Park8d01f632017-03-13 11:54:47 -0700307
308 android::base::WriteStringToFile(StringPrintf("%s\n", reason.c_str()), LAST_REBOOT_REASON_FILE);
309
310 if (cmd == ANDROID_RB_THERMOFF) { // do not wait if it is thermal
311 DoThermalOff();
312 abort();
313 }
Keun-young Parkaa08ea42017-03-23 13:27:28 -0700314
Keun-young Park3ee0df92017-03-27 11:21:09 -0700315 /* TODO update default waiting time based on usage data */
Keun-young Parkc4ffa5c2017-03-28 09:41:36 -0700316 constexpr unsigned int shutdownTimeoutDefault = 10;
317 unsigned int shutdownTimeout = shutdownTimeoutDefault;
318 if (SHUTDOWN_ZERO_TIMEOUT) { // eng build
319 shutdownTimeout = 0;
320 } else {
321 shutdownTimeout =
322 android::base::GetUintProperty("ro.build.shutdown_timeout", shutdownTimeoutDefault);
323 }
Tom Cherryccf23532017-03-28 16:40:41 -0700324 LOG(INFO) << "Shutdown timeout: " << shutdownTimeout;
Keun-young Parkaa08ea42017-03-23 13:27:28 -0700325
Keun-young Park7830d592017-03-27 16:07:02 -0700326 // keep debugging tools until non critical ones are all gone.
327 const std::set<std::string> kill_after_apps{"tombstoned", "logd", "adbd"};
328 // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
329 const std::set<std::string> to_starts{"watchdogd", "vold"};
330 ServiceManager::GetInstance().ForEachService([&kill_after_apps, &to_starts](Service* s) {
331 if (kill_after_apps.count(s->name())) {
332 s->SetShutdownCritical();
333 } else if (to_starts.count(s->name())) {
334 s->Start();
335 s->SetShutdownCritical();
Keun-young Park8d01f632017-03-13 11:54:47 -0700336 }
Keun-young Park7830d592017-03-27 16:07:02 -0700337 });
338
339 Service* bootAnim = ServiceManager::GetInstance().FindServiceByName("bootanim");
340 Service* surfaceFlinger = ServiceManager::GetInstance().FindServiceByName("surfaceflinger");
341 if (bootAnim != nullptr && surfaceFlinger != nullptr && surfaceFlinger->IsRunning()) {
342 property_set("service.bootanim.exit", "0");
343 // Could be in the middle of animation. Stop and start so that it can pick
344 // up the right mode.
345 bootAnim->Stop();
346 // start all animation classes if stopped.
347 ServiceManager::GetInstance().ForEachServiceInClass("animation", [](Service* s) {
348 s->Start();
349 s->SetShutdownCritical(); // will not check animation class separately
350 });
351 bootAnim->Start();
352 surfaceFlinger->SetShutdownCritical();
353 bootAnim->SetShutdownCritical();
Keun-young Park8d01f632017-03-13 11:54:47 -0700354 }
Keun-young Park7830d592017-03-27 16:07:02 -0700355
Keun-young Park8d01f632017-03-13 11:54:47 -0700356 // optional shutdown step
357 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Keun-young Park3ee0df92017-03-27 11:21:09 -0700358 if (shutdownTimeout > 0) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700359 LOG(INFO) << "terminating init services";
Keun-young Park8d01f632017-03-13 11:54:47 -0700360
361 // Ask all services to terminate except shutdown critical ones.
362 ServiceManager::GetInstance().ForEachService([](Service* s) {
363 if (!s->IsShutdownCritical()) s->Terminate();
364 });
365
366 int service_count = 0;
Keun-young Park3ee0df92017-03-27 11:21:09 -0700367 // Up to half as long as shutdownTimeout or 3 seconds, whichever is lower.
368 unsigned int terminationWaitTimeout = std::min<unsigned int>((shutdownTimeout + 1) / 2, 3);
369 while (t.duration_s() < terminationWaitTimeout) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700370 ServiceManager::GetInstance().ReapAnyOutstandingChildren();
371
372 service_count = 0;
373 ServiceManager::GetInstance().ForEachService([&service_count](Service* s) {
374 // Count the number of services running except shutdown critical.
375 // Exclude the console as it will ignore the SIGTERM signal
376 // and not exit.
377 // Note: SVC_CONSOLE actually means "requires console" but
378 // it is only used by the shell.
379 if (!s->IsShutdownCritical() && s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
380 service_count++;
381 }
382 });
383
384 if (service_count == 0) {
385 // All terminable services terminated. We can exit early.
386 break;
387 }
388
389 // Wait a bit before recounting the number or running services.
390 std::this_thread::sleep_for(50ms);
391 }
392 LOG(INFO) << "Terminating running services took " << t
393 << " with remaining services:" << service_count;
394 }
395
396 // minimum safety steps before restarting
397 // 2. kill all services except ones that are necessary for the shutdown sequence.
Keun-young Park2ba5c812017-03-29 12:54:40 -0700398 ServiceManager::GetInstance().ForEachService([](Service* s) {
399 if (!s->IsShutdownCritical()) s->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700400 });
401 ServiceManager::GetInstance().ReapAnyOutstandingChildren();
402
403 // 3. send volume shutdown to vold
404 Service* voldService = ServiceManager::GetInstance().FindServiceByName("vold");
405 if (voldService != nullptr && voldService->IsRunning()) {
406 ShutdownVold();
Keun-young Park2ba5c812017-03-29 12:54:40 -0700407 voldService->Stop();
Keun-young Park8d01f632017-03-13 11:54:47 -0700408 } else {
409 LOG(INFO) << "vold not running, skipping vold shutdown";
410 }
Keun-young Park2ba5c812017-03-29 12:54:40 -0700411 // logcat stopped here
412 ServiceManager::GetInstance().ForEachService([&kill_after_apps](Service* s) {
413 if (kill_after_apps.count(s->name())) s->Stop();
414 });
Keun-young Park8d01f632017-03-13 11:54:47 -0700415 // 4. sync, try umount, and optionally run fsck for user shutdown
Keun-young Park2ba5c812017-03-29 12:54:40 -0700416 sync();
Keun-young Park3ee0df92017-03-27 11:21:09 -0700417 UmountStat stat = TryUmountAndFsck(runFsck, shutdownTimeout * 1000 - t.duration_ms());
Keun-young Park2ba5c812017-03-29 12:54:40 -0700418 // Follow what linux shutdown is doing: one more sync with little bit delay
419 sync();
420 std::this_thread::sleep_for(100ms);
Keun-young Park8d01f632017-03-13 11:54:47 -0700421 LogShutdownTime(stat, &t);
422 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
423 RebootSystem(cmd, rebootTarget);
424 abort();
425}