blob: 1559b6f678b02eb90a0d8575c29832a5d278de1a [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
266/* 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 */
275static UmountStat TryUmountAndFsck(bool runFsck) {
276 std::vector<MountEntry> emulatedPartitions;
277 std::vector<MountEntry> blockDevRwPartitions;
278
279 TurnOffBacklight(); // this part can take time. save power.
280
281 if (!FindPartitionsToUmount(&blockDevRwPartitions, &emulatedPartitions)) {
282 return UMOUNT_STAT_ERROR;
283 }
284 if (emulatedPartitions.size() > 0) {
285 LOG(WARNING) << "emulated partitions still exist, will umount";
286 /* Pending writes in emulated partitions can fail umount. After a few trials, detach
287 * it so that it can be umounted when all writes are done.
288 */
289 if (!UmountPartitions(&emulatedPartitions, 1, 0)) {
290 UmountPartitions(&emulatedPartitions, 1, MNT_DETACH);
291 }
292 }
Keun-young Parkaa08ea42017-03-23 13:27:28 -0700293 DoSync(); // emulated partition change can lead to update
Keun-young Park8d01f632017-03-13 11:54:47 -0700294 UmountStat stat = UMOUNT_STAT_SUCCESS;
295 /* data partition needs all pending writes to be completed and all emulated partitions
296 * umounted. If umount failed in the above step, it DETACH is requested, so umount can
297 * still happen while waiting for /data. If the current waiting is not good enough, give
298 * up and leave it to e2fsck after reboot to fix it.
299 */
300 /* TODO update max waiting time based on usage data */
301 if (!UmountPartitions(&blockDevRwPartitions, 100, 0)) {
302 /* Last resort, detach and hope it finish before shutdown. */
303 UmountPartitions(&blockDevRwPartitions, 1, MNT_DETACH);
304 stat = UMOUNT_STAT_TIMEOUT;
305 }
306 if (stat == UMOUNT_STAT_SUCCESS && runFsck) {
307 for (auto& entry : blockDevRwPartitions) {
308 DoFsck(entry);
309 }
310 }
311
312 return stat;
313}
314
Keun-young Parkaa08ea42017-03-23 13:27:28 -0700315static void KillAllProcesses() { android::base::WriteStringToFile("i", "/proc/sysrq-trigger"); }
Keun-young Park8d01f632017-03-13 11:54:47 -0700316
317static void __attribute__((noreturn)) DoThermalOff() {
318 LOG(WARNING) << "Thermal system shutdown";
319 DoSync();
320 RebootSystem(ANDROID_RB_THERMOFF, "");
321 abort();
322}
323
324void DoReboot(unsigned int cmd, const std::string& reason, const std::string& rebootTarget,
325 bool runFsck) {
326 Timer t;
Keun-young Park3cd8c6f2017-03-23 15:33:16 -0700327 LOG(INFO) << "Reboot start, reason: " << reason << ", rebootTarget: " << rebootTarget;
Keun-young Park8d01f632017-03-13 11:54:47 -0700328
329 android::base::WriteStringToFile(StringPrintf("%s\n", reason.c_str()), LAST_REBOOT_REASON_FILE);
330
331 if (cmd == ANDROID_RB_THERMOFF) { // do not wait if it is thermal
332 DoThermalOff();
333 abort();
334 }
Keun-young Parkaa08ea42017-03-23 13:27:28 -0700335
336 std::string timeout = property_get("ro.build.shutdown_timeout");
337 unsigned int delay = 0;
338 if (!android::base::ParseUint(timeout, &delay)) {
339 delay = 3; // force service termination by default
340 } else {
341 LOG(INFO) << "ro.build.shutdown_timeout set:" << delay;
342 }
343
Keun-young Park8d01f632017-03-13 11:54:47 -0700344 static const constexpr char* shutdown_critical_services[] = {"vold", "watchdogd"};
345 for (const char* name : shutdown_critical_services) {
346 Service* s = ServiceManager::GetInstance().FindServiceByName(name);
347 if (s == nullptr) {
348 LOG(WARNING) << "Shutdown critical service not found:" << name;
349 continue;
350 }
351 s->Start(); // make sure that it is running.
352 s->SetShutdownCritical();
353 }
354 // optional shutdown step
355 // 1. terminate all services except shutdown critical ones. wait for delay to finish
356 if (delay > 0) {
357 LOG(INFO) << "terminating init services";
358 // tombstoned can write to data when other services are killed. so finish it first.
359 static const constexpr char* first_to_kill[] = {"tombstoned"};
360 for (const char* name : first_to_kill) {
361 Service* s = ServiceManager::GetInstance().FindServiceByName(name);
362 if (s != nullptr) s->Stop();
363 }
364
365 // Ask all services to terminate except shutdown critical ones.
366 ServiceManager::GetInstance().ForEachService([](Service* s) {
367 if (!s->IsShutdownCritical()) s->Terminate();
368 });
369
370 int service_count = 0;
371 while (t.duration_s() < delay) {
372 ServiceManager::GetInstance().ReapAnyOutstandingChildren();
373
374 service_count = 0;
375 ServiceManager::GetInstance().ForEachService([&service_count](Service* s) {
376 // Count the number of services running except shutdown critical.
377 // Exclude the console as it will ignore the SIGTERM signal
378 // and not exit.
379 // Note: SVC_CONSOLE actually means "requires console" but
380 // it is only used by the shell.
381 if (!s->IsShutdownCritical() && s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
382 service_count++;
383 }
384 });
385
386 if (service_count == 0) {
387 // All terminable services terminated. We can exit early.
388 break;
389 }
390
391 // Wait a bit before recounting the number or running services.
392 std::this_thread::sleep_for(50ms);
393 }
394 LOG(INFO) << "Terminating running services took " << t
395 << " with remaining services:" << service_count;
396 }
397
398 // minimum safety steps before restarting
399 // 2. kill all services except ones that are necessary for the shutdown sequence.
400 ServiceManager::GetInstance().ForEachService([](Service* s) {
401 if (!s->IsShutdownCritical()) s->Stop();
402 });
403 ServiceManager::GetInstance().ReapAnyOutstandingChildren();
404
405 // 3. send volume shutdown to vold
406 Service* voldService = ServiceManager::GetInstance().FindServiceByName("vold");
407 if (voldService != nullptr && voldService->IsRunning()) {
408 ShutdownVold();
Keun-young Park8d01f632017-03-13 11:54:47 -0700409 } else {
410 LOG(INFO) << "vold not running, skipping vold shutdown";
411 }
Keun-young Parkaa08ea42017-03-23 13:27:28 -0700412 if (delay == 0) { // no processes terminated. kill all instead.
413 KillAllProcesses();
414 }
Keun-young Park8d01f632017-03-13 11:54:47 -0700415 // 4. sync, try umount, and optionally run fsck for user shutdown
416 DoSync();
417 UmountStat stat = TryUmountAndFsck(runFsck);
418 LogShutdownTime(stat, &t);
419 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
420 RebootSystem(cmd, rebootTarget);
421 abort();
422}