blob: 1e538c5b8f08a345bbca14a71e53e019a7316ee2 [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
205/* Find all read+write block devices and emulated devices in /proc/mounts
206 * and add them to correpsponding list.
207 */
208static bool FindPartitionsToUmount(std::vector<MountEntry>* blockDevPartitions,
209 std::vector<MountEntry>* emulatedPartitions) {
210 std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "r"), endmntent);
211 if (fp == nullptr) {
212 PLOG(ERROR) << "Failed to open /proc/mounts";
213 return false;
214 }
215 mntent* mentry;
216 while ((mentry = getmntent(fp.get())) != nullptr) {
217 if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
218 blockDevPartitions->emplace_back(*mentry);
219 } else if (MountEntry::IsEmulatedDevice(*mentry)) {
220 emulatedPartitions->emplace_back(*mentry);
221 }
222 }
223 return true;
224}
225
226static bool UmountPartitions(std::vector<MountEntry>* partitions, int maxRetry, int flags) {
227 static constexpr int SLEEP_AFTER_RETRY_US = 100000;
228
229 bool umountDone;
230 int retryCounter = 0;
231
232 while (true) {
233 umountDone = true;
234 for (auto& entry : *partitions) {
235 if (entry.is_mounted()) {
236 int r = umount2(entry.mnt_dir().c_str(), flags);
237 if (r == 0) {
238 entry.set_is_mounted();
239 LOG(INFO) << StringPrintf("umounted %s, flags:0x%x", entry.mnt_fsname().c_str(),
240 flags);
241 } else {
242 umountDone = false;
243 PLOG(WARNING) << StringPrintf("cannot umount %s, flags:0x%x",
244 entry.mnt_fsname().c_str(), flags);
245 }
246 }
247 }
248 if (umountDone) break;
249 retryCounter++;
250 if (retryCounter >= maxRetry) break;
251 usleep(SLEEP_AFTER_RETRY_US);
252 }
253 return umountDone;
254}
255
256/* 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 */
265static UmountStat TryUmountAndFsck(bool runFsck) {
266 std::vector<MountEntry> emulatedPartitions;
267 std::vector<MountEntry> blockDevRwPartitions;
268
269 TurnOffBacklight(); // this part can take time. save power.
270
271 if (!FindPartitionsToUmount(&blockDevRwPartitions, &emulatedPartitions)) {
272 return UMOUNT_STAT_ERROR;
273 }
274 if (emulatedPartitions.size() > 0) {
275 LOG(WARNING) << "emulated partitions still exist, will umount";
276 /* Pending writes in emulated partitions can fail umount. After a few trials, detach
277 * it so that it can be umounted when all writes are done.
278 */
279 if (!UmountPartitions(&emulatedPartitions, 1, 0)) {
280 UmountPartitions(&emulatedPartitions, 1, MNT_DETACH);
281 }
282 }
283 UmountStat stat = UMOUNT_STAT_SUCCESS;
284 /* data partition needs all pending writes to be completed and all emulated partitions
285 * umounted. If umount failed in the above step, it DETACH is requested, so umount can
286 * still happen while waiting for /data. If the current waiting is not good enough, give
287 * up and leave it to e2fsck after reboot to fix it.
288 */
289 /* TODO update max waiting time based on usage data */
290 if (!UmountPartitions(&blockDevRwPartitions, 100, 0)) {
291 /* Last resort, detach and hope it finish before shutdown. */
292 UmountPartitions(&blockDevRwPartitions, 1, MNT_DETACH);
293 stat = UMOUNT_STAT_TIMEOUT;
294 }
295 if (stat == UMOUNT_STAT_SUCCESS && runFsck) {
296 for (auto& entry : blockDevRwPartitions) {
297 DoFsck(entry);
298 }
299 }
300
301 return stat;
302}
303
304static void DoSync() {
305 // quota sync is not done by sync cal, so should be done separately.
306 // quota sync is in VFS level, so do it before sync, which goes down to fs level.
307 int r = quotactl(QCMD(Q_SYNC, 0), nullptr, 0 /* do not care */, 0 /* do not care */);
308 if (r < 0) {
309 PLOG(ERROR) << "quotactl failed";
310 }
311 sync();
312}
313
314static void __attribute__((noreturn)) DoThermalOff() {
315 LOG(WARNING) << "Thermal system shutdown";
316 DoSync();
317 RebootSystem(ANDROID_RB_THERMOFF, "");
318 abort();
319}
320
321void DoReboot(unsigned int cmd, const std::string& reason, const std::string& rebootTarget,
322 bool runFsck) {
323 Timer t;
Keun-young Park3cd8c6f2017-03-23 15:33:16 -0700324 LOG(INFO) << "Reboot start, reason: " << reason << ", rebootTarget: " << rebootTarget;
Keun-young Park8d01f632017-03-13 11:54:47 -0700325 std::string timeout = property_get("ro.build.shutdown_timeout");
326 unsigned int delay = 0;
327
328 if (!android::base::ParseUint(timeout, &delay)) {
329 delay = 3; // force service termination by default
330 }
331
332 android::base::WriteStringToFile(StringPrintf("%s\n", reason.c_str()), LAST_REBOOT_REASON_FILE);
333
334 if (cmd == ANDROID_RB_THERMOFF) { // do not wait if it is thermal
335 DoThermalOff();
336 abort();
337 }
338 static const constexpr char* shutdown_critical_services[] = {"vold", "watchdogd"};
339 for (const char* name : shutdown_critical_services) {
340 Service* s = ServiceManager::GetInstance().FindServiceByName(name);
341 if (s == nullptr) {
342 LOG(WARNING) << "Shutdown critical service not found:" << name;
343 continue;
344 }
345 s->Start(); // make sure that it is running.
346 s->SetShutdownCritical();
347 }
348 // optional shutdown step
349 // 1. terminate all services except shutdown critical ones. wait for delay to finish
350 if (delay > 0) {
351 LOG(INFO) << "terminating init services";
352 // tombstoned can write to data when other services are killed. so finish it first.
353 static const constexpr char* first_to_kill[] = {"tombstoned"};
354 for (const char* name : first_to_kill) {
355 Service* s = ServiceManager::GetInstance().FindServiceByName(name);
356 if (s != nullptr) s->Stop();
357 }
358
359 // Ask all services to terminate except shutdown critical ones.
360 ServiceManager::GetInstance().ForEachService([](Service* s) {
361 if (!s->IsShutdownCritical()) s->Terminate();
362 });
363
364 int service_count = 0;
365 while (t.duration_s() < delay) {
366 ServiceManager::GetInstance().ReapAnyOutstandingChildren();
367
368 service_count = 0;
369 ServiceManager::GetInstance().ForEachService([&service_count](Service* s) {
370 // Count the number of services running except shutdown critical.
371 // Exclude the console as it will ignore the SIGTERM signal
372 // and not exit.
373 // Note: SVC_CONSOLE actually means "requires console" but
374 // it is only used by the shell.
375 if (!s->IsShutdownCritical() && s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
376 service_count++;
377 }
378 });
379
380 if (service_count == 0) {
381 // All terminable services terminated. We can exit early.
382 break;
383 }
384
385 // Wait a bit before recounting the number or running services.
386 std::this_thread::sleep_for(50ms);
387 }
388 LOG(INFO) << "Terminating running services took " << t
389 << " with remaining services:" << service_count;
390 }
391
392 // minimum safety steps before restarting
393 // 2. kill all services except ones that are necessary for the shutdown sequence.
394 ServiceManager::GetInstance().ForEachService([](Service* s) {
395 if (!s->IsShutdownCritical()) s->Stop();
396 });
397 ServiceManager::GetInstance().ReapAnyOutstandingChildren();
398
399 // 3. send volume shutdown to vold
400 Service* voldService = ServiceManager::GetInstance().FindServiceByName("vold");
401 if (voldService != nullptr && voldService->IsRunning()) {
402 ShutdownVold();
403 voldService->Terminate();
404 } else {
405 LOG(INFO) << "vold not running, skipping vold shutdown";
406 }
407
408 // 4. sync, try umount, and optionally run fsck for user shutdown
409 DoSync();
410 UmountStat stat = TryUmountAndFsck(runFsck);
411 LogShutdownTime(stat, &t);
412 // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
413 RebootSystem(cmd, rebootTarget);
414 abort();
415}