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