blob: 2844d78bbb4d5f48e9fe23741292862c6df855e3 [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 */
16#include <dirent.h>
17#include <fcntl.h>
18#include <mntent.h>
19#include <sys/cdefs.h>
20#include <sys/mount.h>
21#include <sys/quota.h>
22#include <sys/reboot.h>
23#include <sys/stat.h>
24#include <sys/syscall.h>
25#include <sys/types.h>
26#include <sys/wait.h>
27
28#include <memory>
29#include <string>
30#include <thread>
31#include <vector>
32
33#include <android-base/file.h>
34#include <android-base/macros.h>
Tom Cherryccf23532017-03-28 16:40:41 -070035#include <android-base/properties.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070036#include <android-base/stringprintf.h>
37#include <android-base/strings.h>
38#include <bootloader_message/bootloader_message.h>
39#include <cutils/android_reboot.h>
Keun-young Park8d01f632017-03-13 11:54:47 -070040#include <fs_mgr.h>
41#include <logwrap/logwrap.h>
42
43#include "log.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070044#include "reboot.h"
45#include "service.h"
46#include "util.h"
47
48using android::base::StringPrintf;
49
50// represents umount status during reboot / shutdown.
51enum UmountStat {
52 /* umount succeeded. */
53 UMOUNT_STAT_SUCCESS = 0,
54 /* umount was not run. */
55 UMOUNT_STAT_SKIPPED = 1,
56 /* umount failed with timeout. */
57 UMOUNT_STAT_TIMEOUT = 2,
58 /* could not run due to error */
59 UMOUNT_STAT_ERROR = 3,
60 /* not used by init but reserved for other part to use this to represent the
61 the state where umount status before reboot is not found / available. */
62 UMOUNT_STAT_NOT_AVAILABLE = 4,
63};
64
65// Utility for struct mntent
66class MountEntry {
67 public:
68 explicit MountEntry(const mntent& entry, bool isMounted = true)
69 : mnt_fsname_(entry.mnt_fsname),
70 mnt_dir_(entry.mnt_dir),
71 mnt_type_(entry.mnt_type),
72 is_mounted_(isMounted) {}
73
74 bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
75
76 bool IsExt4() const { return mnt_type_ == "ext4"; }
77
78 bool is_mounted() const { return is_mounted_; }
79
80 void set_is_mounted() { is_mounted_ = false; }
81
82 const std::string& mnt_fsname() const { return mnt_fsname_; }
83
84 const std::string& mnt_dir() const { return mnt_dir_; }
85
86 static bool IsBlockDevice(const struct mntent& mntent) {
87 return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
88 }
89
90 static bool IsEmulatedDevice(const struct mntent& mntent) {
91 static const std::string SDCARDFS_NAME = "sdcardfs";
92 return android::base::StartsWith(mntent.mnt_fsname, "/data/") &&
93 SDCARDFS_NAME == mntent.mnt_type;
94 }
95
96 private:
97 std::string mnt_fsname_;
98 std::string mnt_dir_;
99 std::string mnt_type_;
100 bool is_mounted_;
101};
102
103// Turn off backlight while we are performing power down cleanup activities.
104static void TurnOffBacklight() {
105 static constexpr char OFF[] = "0";
106
107 android::base::WriteStringToFile(OFF, "/sys/class/leds/lcd-backlight/brightness");
108
109 static const char backlightDir[] = "/sys/class/backlight";
110 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(backlightDir), closedir);
111 if (!dir) {
112 return;
113 }
114
115 struct dirent* dp;
116 while ((dp = readdir(dir.get())) != nullptr) {
117 if (((dp->d_type != DT_DIR) && (dp->d_type != DT_LNK)) || (dp->d_name[0] == '.')) {
118 continue;
119 }
120
121 std::string fileName = StringPrintf("%s/%s/brightness", backlightDir, dp->d_name);
122 android::base::WriteStringToFile(OFF, fileName);
123 }
124}
125
126static void DoFsck(const MountEntry& entry) {
127 static constexpr int UNMOUNT_CHECK_TIMES = 10;
128
129 if (!entry.IsF2Fs() && !entry.IsExt4()) return;
130
131 int count = 0;
132 while (count++ < UNMOUNT_CHECK_TIMES) {
133 int fd = TEMP_FAILURE_RETRY(open(entry.mnt_fsname().c_str(), O_RDONLY | O_EXCL));
134 if (fd >= 0) {
135 /* |entry->mnt_dir| has sucessfully been unmounted. */
136 close(fd);
137 break;
138 } else if (errno == EBUSY) {
139 // Some processes using |entry->mnt_dir| are still alive. Wait for a
140 // while then retry.
141 std::this_thread::sleep_for(5000ms / UNMOUNT_CHECK_TIMES);
142 continue;
143 } else {
144 /* Cannot open the device. Give up. */
145 return;
146 }
147 }
148
149 // NB: With watchdog still running, there is no cap on the time it takes
150 // to complete the fsck, from the users perspective the device graphics
151 // and responses are locked-up and they may choose to hold the power
152 // button in frustration if it drags out.
153
154 int st;
155 if (entry.IsF2Fs()) {
156 const char* f2fs_argv[] = {
157 "/system/bin/fsck.f2fs", "-f", entry.mnt_fsname().c_str(),
158 };
159 android_fork_execvp_ext(arraysize(f2fs_argv), (char**)f2fs_argv, &st, true, LOG_KLOG, true,
160 nullptr, nullptr, 0);
161 } else if (entry.IsExt4()) {
162 const char* ext4_argv[] = {
163 "/system/bin/e2fsck", "-f", "-y", entry.mnt_fsname().c_str(),
164 };
165 android_fork_execvp_ext(arraysize(ext4_argv), (char**)ext4_argv, &st, true, LOG_KLOG, true,
166 nullptr, nullptr, 0);
167 }
168}
169
170static void ShutdownVold() {
171 const char* vdc_argv[] = {"/system/bin/vdc", "volume", "shutdown"};
172 int status;
173 android_fork_execvp_ext(arraysize(vdc_argv), (char**)vdc_argv, &status, true, LOG_KLOG, true,
174 nullptr, nullptr, 0);
175}
176
177static void LogShutdownTime(UmountStat stat, Timer* t) {
178 LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration_ms()) << ":" << stat;
179}
180
181static void __attribute__((noreturn))
182RebootSystem(unsigned int cmd, const std::string& rebootTarget) {
Keun-young Park3cd8c6f2017-03-23 15:33:16 -0700183 LOG(INFO) << "Reboot ending, jumping to kernel";
Keun-young Park8d01f632017-03-13 11:54:47 -0700184 switch (cmd) {
185 case ANDROID_RB_POWEROFF:
186 reboot(RB_POWER_OFF);
187 break;
188
189 case ANDROID_RB_RESTART2:
190 syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2,
191 LINUX_REBOOT_CMD_RESTART2, rebootTarget.c_str());
192 break;
193
194 case ANDROID_RB_THERMOFF:
195 reboot(RB_POWER_OFF);
196 break;
197 }
198 // In normal case, reboot should not return.
199 PLOG(FATAL) << "reboot call returned";
200 abort();
201}
202
Keun-young Parkaa08ea42017-03-23 13:27:28 -0700203static void DoSync() {
204 // quota sync is not done by sync call, so should be done separately.
205 // quota sync is in VFS level, so do it before sync, which goes down to fs level.
206 int r = quotactl(QCMD(Q_SYNC, 0), nullptr, 0 /* do not care */, 0 /* do not care */);
207 if (r < 0) {
208 PLOG(ERROR) << "quotactl failed";
209 }
210 sync();
211}
212
Keun-young Park8d01f632017-03-13 11:54:47 -0700213/* Find all read+write block devices and emulated devices in /proc/mounts
214 * and add them to correpsponding list.
215 */
216static bool FindPartitionsToUmount(std::vector<MountEntry>* blockDevPartitions,
217 std::vector<MountEntry>* emulatedPartitions) {
218 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "r"), endmntent);
219 if (fp == nullptr) {
220 PLOG(ERROR) << "Failed to open /proc/mounts";
221 return false;
222 }
223 mntent* mentry;
224 while ((mentry = getmntent(fp.get())) != nullptr) {
225 if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
226 blockDevPartitions->emplace_back(*mentry);
227 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
228 emulatedPartitions->emplace_back(*mentry);
229 }
230 }
231 return true;
232}
233
234static bool UmountPartitions(std::vector<MountEntry>* partitions, int maxRetry, int flags) {
235 static constexpr int SLEEP_AFTER_RETRY_US = 100000;
236
237 bool umountDone;
238 int retryCounter = 0;
239
240 while (true) {
241 umountDone = true;
242 for (auto& entry : *partitions) {
243 if (entry.is_mounted()) {
244 int r = umount2(entry.mnt_dir().c_str(), flags);
245 if (r == 0) {
246 entry.set_is_mounted();
247 LOG(INFO) << StringPrintf("umounted %s, flags:0x%x", entry.mnt_fsname().c_str(),
248 flags);
249 } else {
250 umountDone = false;
251 PLOG(WARNING) << StringPrintf("cannot umount %s, flags:0x%x",
252 entry.mnt_fsname().c_str(), flags);
253 }
254 }
255 }
256 if (umountDone) break;
257 retryCounter++;
258 if (retryCounter >= maxRetry) break;
259 usleep(SLEEP_AFTER_RETRY_US);
260 }
261 return umountDone;
262}
263
Keun-young Park3ee0df92017-03-27 11:21:09 -0700264static void KillAllProcesses() { android::base::WriteStringToFile("i", "/proc/sysrq-trigger"); }
265
Keun-young Park8d01f632017-03-13 11:54:47 -0700266/* Try umounting all emulated file systems R/W block device cfile systems.
267 * This will just try umount and give it up if it fails.
268 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
269 * and necessary check can be done at the next reboot.
270 * For safer shutdown, caller needs to make sure that
271 * all processes / emulated partition for the target fs are all cleaned-up.
272 *
273 * return true when umount was successful. false when timed out.
274 */
Keun-young Park3ee0df92017-03-27 11:21:09 -0700275static UmountStat TryUmountAndFsck(bool runFsck, int timeoutMs) {
276 Timer t;
Keun-young Park8d01f632017-03-13 11:54:47 -0700277 std::vector<MountEntry> emulatedPartitions;
278 std::vector<MountEntry> blockDevRwPartitions;
279
280 TurnOffBacklight(); // this part can take time. save power.
281
282 if (!FindPartitionsToUmount(&blockDevRwPartitions, &emulatedPartitions)) {
283 return UMOUNT_STAT_ERROR;
284 }
285 if (emulatedPartitions.size() > 0) {
286 LOG(WARNING) << "emulated partitions still exist, will umount";
287 /* Pending writes in emulated partitions can fail umount. After a few trials, detach
288 * it so that it can be umounted when all writes are done.
289 */
290 if (!UmountPartitions(&emulatedPartitions, 1, 0)) {
291 UmountPartitions(&emulatedPartitions, 1, MNT_DETACH);
292 }
293 }
Keun-young Parkaa08ea42017-03-23 13:27:28 -0700294 DoSync(); // emulated partition change can lead to update
Keun-young Park8d01f632017-03-13 11:54:47 -0700295 UmountStat stat = UMOUNT_STAT_SUCCESS;
296 /* data partition needs all pending writes to be completed and all emulated partitions
297 * umounted. If umount failed in the above step, it DETACH is requested, so umount can
298 * still happen while waiting for /data. If the current waiting is not good enough, give
299 * up and leave it to e2fsck after reboot to fix it.
300 */
Keun-young Park3ee0df92017-03-27 11:21:09 -0700301 int remainingTimeMs = timeoutMs - t.duration_ms();
302 // each retry takes 100ms, and run at least once.
303 int retry = std::max(remainingTimeMs / 100, 1);
304 if (!UmountPartitions(&blockDevRwPartitions, retry, 0)) {
305 /* Last resort, kill all and try again */
306 LOG(WARNING) << "umount still failing, trying kill all";
307 KillAllProcesses();
308 DoSync();
309 if (!UmountPartitions(&blockDevRwPartitions, 1, 0)) {
310 stat = UMOUNT_STAT_TIMEOUT;
311 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700312 }
Keun-young Park3ee0df92017-03-27 11:21:09 -0700313 // fsck part is excluded from timeout check. It only runs for user initiated shutdown
314 // and should not affect reboot time.
Keun-young Park8d01f632017-03-13 11:54:47 -0700315 if (stat == UMOUNT_STAT_SUCCESS && runFsck) {
316 for (auto& entry : blockDevRwPartitions) {
317 DoFsck(entry);
318 }
319 }
320
321 return stat;
322}
323
Keun-young Park8d01f632017-03-13 11:54:47 -0700324static void __attribute__((noreturn)) DoThermalOff() {
325 LOG(WARNING) << "Thermal system shutdown";
326 DoSync();
327 RebootSystem(ANDROID_RB_THERMOFF, "");
328 abort();
329}
330
331void DoReboot(unsigned int cmd, const std::string& reason, const std::string& rebootTarget,
332 bool runFsck) {
333 Timer t;
Keun-young Park3cd8c6f2017-03-23 15:33:16 -0700334 LOG(INFO) << "Reboot start, reason: " << reason << ", rebootTarget: " << rebootTarget;
Keun-young Park8d01f632017-03-13 11:54:47 -0700335
336 android::base::WriteStringToFile(StringPrintf("%s\n", reason.c_str()), LAST_REBOOT_REASON_FILE);
337
338 if (cmd == ANDROID_RB_THERMOFF) { // do not wait if it is thermal
339 DoThermalOff();
340 abort();
341 }
Keun-young Parkaa08ea42017-03-23 13:27:28 -0700342
Keun-young Park3ee0df92017-03-27 11:21:09 -0700343 /* TODO update default waiting time based on usage data */
Tom Cherryccf23532017-03-28 16:40:41 -0700344 unsigned int shutdownTimeout = android::base::GetUintProperty("ro.build.shutdown_timeout", 10u);
345 LOG(INFO) << "Shutdown timeout: " << shutdownTimeout;
Keun-young Parkaa08ea42017-03-23 13:27:28 -0700346
Keun-young Park8d01f632017-03-13 11:54:47 -0700347 static const constexpr char* shutdown_critical_services[] = {"vold", "watchdogd"};
348 for (const char* name : shutdown_critical_services) {
349 Service* s = ServiceManager::GetInstance().FindServiceByName(name);
350 if (s == nullptr) {
351 LOG(WARNING) << "Shutdown critical service not found:" << name;
352 continue;
353 }
354 s->Start(); // make sure that it is running.
355 s->SetShutdownCritical();
356 }
357 // optional shutdown step
358 // 1. terminate all services except shutdown critical ones. wait for delay to finish
Keun-young Park3ee0df92017-03-27 11:21:09 -0700359 if (shutdownTimeout > 0) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700360 LOG(INFO) << "terminating init services";
361 // tombstoned can write to data when other services are killed. so finish it first.
362 static const constexpr char* first_to_kill[] = {"tombstoned"};
363 for (const char* name : first_to_kill) {
364 Service* s = ServiceManager::GetInstance().FindServiceByName(name);
365 if (s != nullptr) s->Stop();
366 }
367
368 // Ask all services to terminate except shutdown critical ones.
369 ServiceManager::GetInstance().ForEachService([](Service* s) {
370 if (!s->IsShutdownCritical()) s->Terminate();
371 });
372
373 int service_count = 0;
Keun-young Park3ee0df92017-03-27 11:21:09 -0700374 // Up to half as long as shutdownTimeout or 3 seconds, whichever is lower.
375 unsigned int terminationWaitTimeout = std::min<unsigned int>((shutdownTimeout + 1) / 2, 3);
376 while (t.duration_s() < terminationWaitTimeout) {
Keun-young Park8d01f632017-03-13 11:54:47 -0700377 ServiceManager::GetInstance().ReapAnyOutstandingChildren();
378
379 service_count = 0;
380 ServiceManager::GetInstance().ForEachService([&service_count](Service* s) {
381 // Count the number of services running except shutdown critical.
382 // Exclude the console as it will ignore the SIGTERM signal
383 // and not exit.
384 // Note: SVC_CONSOLE actually means "requires console" but
385 // it is only used by the shell.
386 if (!s->IsShutdownCritical() && s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
387 service_count++;
388 }
389 });
390
391 if (service_count == 0) {
392 // All terminable services terminated. We can exit early.
393 break;
394 }
395
396 // Wait a bit before recounting the number or running services.
397 std::this_thread::sleep_for(50ms);
398 }
399 LOG(INFO) << "Terminating running services took " << t
400 << " with remaining services:" << service_count;
401 }
402
403 // minimum safety steps before restarting
404 // 2. kill all services except ones that are necessary for the shutdown sequence.
405 ServiceManager::GetInstance().ForEachService([](Service* s) {
406 if (!s->IsShutdownCritical()) s->Stop();
407 });
408 ServiceManager::GetInstance().ReapAnyOutstandingChildren();
409
410 // 3. send volume shutdown to vold
411 Service* voldService = ServiceManager::GetInstance().FindServiceByName("vold");
412 if (voldService != nullptr && voldService->IsRunning()) {
413 ShutdownVold();
Keun-young Park8d01f632017-03-13 11:54:47 -0700414 } else {
415 LOG(INFO) << "vold not running, skipping vold shutdown";
416 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700417 // 4. sync, try umount, and optionally run fsck for user shutdown
418 DoSync();
Keun-young Park3ee0df92017-03-27 11:21:09 -0700419 UmountStat stat = TryUmountAndFsck(runFsck, shutdownTimeout * 1000 - t.duration_ms());
Keun-young Park8d01f632017-03-13 11:54:47 -0700420 LogShutdownTime(stat, &t);
421 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
422 RebootSystem(cmd, rebootTarget);
423 abort();
424}