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