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