1/*
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
17#include "reboot.h"
18
19#include <dirent.h>
20#include <fcntl.h>
21#include <linux/fs.h>
22#include <mntent.h>
23#include <sys/capability.h>
24#include <sys/cdefs.h>
25#include <sys/ioctl.h>
26#include <sys/mount.h>
27#include <sys/reboot.h>
28#include <sys/stat.h>
29#include <sys/syscall.h>
30#include <sys/types.h>
31#include <sys/wait.h>
32
33#include <memory>
34#include <set>
35#include <thread>
36#include <vector>
37
38#include <android-base/chrono_utils.h>
39#include <android-base/file.h>
40#include <android-base/logging.h>
41#include <android-base/macros.h>
42#include <android-base/properties.h>
43#include <android-base/stringprintf.h>
44#include <android-base/strings.h>
45#include <android-base/unique_fd.h>
46#include <bootloader_message/bootloader_message.h>
47#include <cutils/android_reboot.h>
48#include <fs_mgr.h>
49#include <logwrap/logwrap.h>
50#include <private/android_filesystem_config.h>
51#include <selinux/selinux.h>
52
53#include "action_manager.h"
54#include "capabilities.h"
55#include "init.h"
56#include "property_service.h"
57#include "service.h"
58#include "sigchld_handler.h"
59
60using android::base::Split;
61using android::base::StringPrintf;
62using android::base::Timer;
63
64namespace android {
65namespace init {
66
67// represents umount status during reboot / shutdown.
68enum UmountStat {
69    /* umount succeeded. */
70    UMOUNT_STAT_SUCCESS = 0,
71    /* umount was not run. */
72    UMOUNT_STAT_SKIPPED = 1,
73    /* umount failed with timeout. */
74    UMOUNT_STAT_TIMEOUT = 2,
75    /* could not run due to error */
76    UMOUNT_STAT_ERROR = 3,
77    /* not used by init but reserved for other part to use this to represent the
78       the state where umount status before reboot is not found / available. */
79    UMOUNT_STAT_NOT_AVAILABLE = 4,
80};
81
82// Utility for struct mntent
83class MountEntry {
84  public:
85    explicit MountEntry(const mntent& entry)
86        : mnt_fsname_(entry.mnt_fsname),
87          mnt_dir_(entry.mnt_dir),
88          mnt_type_(entry.mnt_type),
89          mnt_opts_(entry.mnt_opts) {}
90
91    bool Umount(bool force) {
92        LOG(INFO) << "Unmounting " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
93        int r = umount2(mnt_dir_.c_str(), force ? MNT_FORCE : 0);
94        if (r == 0) {
95            LOG(INFO) << "Umounted " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
96            return true;
97        } else {
98            PLOG(WARNING) << "Cannot umount " << mnt_fsname_ << ":" << mnt_dir_ << " opts "
99                          << mnt_opts_;
100            return false;
101        }
102    }
103
104    void DoFsck() {
105        int st;
106        if (IsF2Fs()) {
107            const char* f2fs_argv[] = {
108                "/system/bin/fsck.f2fs", "-f", mnt_fsname_.c_str(),
109            };
110            android_fork_execvp_ext(arraysize(f2fs_argv), (char**)f2fs_argv, &st, true, LOG_KLOG,
111                                    true, nullptr, nullptr, 0);
112        } else if (IsExt4()) {
113            const char* ext4_argv[] = {
114                "/system/bin/e2fsck", "-f", "-y", mnt_fsname_.c_str(),
115            };
116            android_fork_execvp_ext(arraysize(ext4_argv), (char**)ext4_argv, &st, true, LOG_KLOG,
117                                    true, nullptr, nullptr, 0);
118        }
119    }
120
121    static bool IsBlockDevice(const struct mntent& mntent) {
122        return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
123    }
124
125    static bool IsEmulatedDevice(const struct mntent& mntent) {
126        return android::base::StartsWith(mntent.mnt_fsname, "/data/");
127    }
128
129  private:
130    bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
131
132    bool IsExt4() const { return mnt_type_ == "ext4"; }
133
134    std::string mnt_fsname_;
135    std::string mnt_dir_;
136    std::string mnt_type_;
137    std::string mnt_opts_;
138};
139
140// Turn off backlight while we are performing power down cleanup activities.
141static void TurnOffBacklight() {
142    Service* service = ServiceList::GetInstance().FindService("blank_screen");
143    if (service == nullptr) {
144        LOG(WARNING) << "cannot find blank_screen in TurnOffBacklight";
145        return;
146    }
147    service->Start();
148}
149
150static void ShutdownVold() {
151    const char* vdc_argv[] = {"/system/bin/vdc", "volume", "shutdown"};
152    int status;
153    android_fork_execvp_ext(arraysize(vdc_argv), (char**)vdc_argv, &status, true, LOG_KLOG, true,
154                            nullptr, nullptr, 0);
155}
156
157static void LogShutdownTime(UmountStat stat, Timer* t) {
158    LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration().count()) << ":"
159                 << stat;
160}
161
162bool IsRebootCapable() {
163    if (!CAP_IS_SUPPORTED(CAP_SYS_BOOT)) {
164        PLOG(WARNING) << "CAP_SYS_BOOT is not supported";
165        return true;
166    }
167
168    ScopedCaps caps(cap_get_proc());
169    if (!caps) {
170        PLOG(WARNING) << "cap_get_proc() failed";
171        return true;
172    }
173
174    cap_flag_value_t value = CAP_SET;
175    if (cap_get_flag(caps.get(), CAP_SYS_BOOT, CAP_EFFECTIVE, &value) != 0) {
176        PLOG(WARNING) << "cap_get_flag(CAP_SYS_BOOT, EFFECTIVE) failed";
177        return true;
178    }
179    return value == CAP_SET;
180}
181
182void __attribute__((noreturn)) RebootSystem(unsigned int cmd, const std::string& rebootTarget) {
183    LOG(INFO) << "Reboot ending, jumping to kernel";
184
185    if (!IsRebootCapable()) {
186        // On systems where init does not have the capability of rebooting the
187        // device, just exit cleanly.
188        exit(0);
189    }
190
191    switch (cmd) {
192        case ANDROID_RB_POWEROFF:
193            reboot(RB_POWER_OFF);
194            break;
195
196        case ANDROID_RB_RESTART2:
197            syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2,
198                    LINUX_REBOOT_CMD_RESTART2, rebootTarget.c_str());
199            break;
200
201        case ANDROID_RB_THERMOFF:
202            reboot(RB_POWER_OFF);
203            break;
204    }
205    // In normal case, reboot should not return.
206    PLOG(ERROR) << "reboot call returned";
207    abort();
208}
209
210/* Find all read+write block devices and emulated devices in /proc/mounts
211 * and add them to correpsponding list.
212 */
213static bool FindPartitionsToUmount(std::vector<MountEntry>* blockDevPartitions,
214                                   std::vector<MountEntry>* emulatedPartitions, bool dump) {
215    std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "r"), endmntent);
216    if (fp == nullptr) {
217        PLOG(ERROR) << "Failed to open /proc/mounts";
218        return false;
219    }
220    mntent* mentry;
221    while ((mentry = getmntent(fp.get())) != nullptr) {
222        if (dump) {
223            LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
224                      << mentry->mnt_opts << " type " << mentry->mnt_type;
225        } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
226            std::string mount_dir(mentry->mnt_dir);
227            // These are R/O partitions changed to R/W after adb remount.
228            // Do not umount them as shutdown critical services may rely on them.
229            if (mount_dir != "/" && mount_dir != "/system" && mount_dir != "/vendor" &&
230                mount_dir != "/oem") {
231                blockDevPartitions->emplace(blockDevPartitions->begin(), *mentry);
232            }
233        } else if (MountEntry::IsEmulatedDevice(*mentry)) {
234            emulatedPartitions->emplace(emulatedPartitions->begin(), *mentry);
235        }
236    }
237    return true;
238}
239
240static void DumpUmountDebuggingInfo(bool dump_all) {
241    int status;
242    if (!security_getenforce()) {
243        LOG(INFO) << "Run lsof";
244        const char* lsof_argv[] = {"/system/bin/lsof"};
245        android_fork_execvp_ext(arraysize(lsof_argv), (char**)lsof_argv, &status, true, LOG_KLOG,
246                                true, nullptr, nullptr, 0);
247    }
248    FindPartitionsToUmount(nullptr, nullptr, true);
249    if (dump_all) {
250        // dump current tasks, this log can be lengthy, so only dump with dump_all
251        android::base::WriteStringToFile("t", "/proc/sysrq-trigger");
252    }
253}
254
255static UmountStat UmountPartitions(std::chrono::milliseconds timeout) {
256    Timer t;
257    /* data partition needs all pending writes to be completed and all emulated partitions
258     * umounted.If the current waiting is not good enough, give
259     * up and leave it to e2fsck after reboot to fix it.
260     */
261    while (true) {
262        std::vector<MountEntry> block_devices;
263        std::vector<MountEntry> emulated_devices;
264        if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
265            return UMOUNT_STAT_ERROR;
266        }
267        if (block_devices.size() == 0) {
268            return UMOUNT_STAT_SUCCESS;
269        }
270        bool unmount_done = true;
271        if (emulated_devices.size() > 0) {
272            for (auto& entry : emulated_devices) {
273                if (!entry.Umount(false)) unmount_done = false;
274            }
275            if (unmount_done) {
276                sync();
277            }
278        }
279        for (auto& entry : block_devices) {
280            if (!entry.Umount(timeout == 0ms)) unmount_done = false;
281        }
282        if (unmount_done) {
283            return UMOUNT_STAT_SUCCESS;
284        }
285        if ((timeout < t.duration())) {  // try umount at least once
286            return UMOUNT_STAT_TIMEOUT;
287        }
288        std::this_thread::sleep_for(100ms);
289    }
290}
291
292static void KillAllProcesses() { android::base::WriteStringToFile("i", "/proc/sysrq-trigger"); }
293
294/* Try umounting all emulated file systems R/W block device cfile systems.
295 * This will just try umount and give it up if it fails.
296 * For fs like ext4, this is ok as file system will be marked as unclean shutdown
297 * and necessary check can be done at the next reboot.
298 * For safer shutdown, caller needs to make sure that
299 * all processes / emulated partition for the target fs are all cleaned-up.
300 *
301 * return true when umount was successful. false when timed out.
302 */
303static UmountStat TryUmountAndFsck(bool runFsck, std::chrono::milliseconds timeout) {
304    Timer t;
305    std::vector<MountEntry> block_devices;
306    std::vector<MountEntry> emulated_devices;
307
308    if (runFsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
309        return UMOUNT_STAT_ERROR;
310    }
311
312    UmountStat stat = UmountPartitions(timeout - t.duration());
313    if (stat != UMOUNT_STAT_SUCCESS) {
314        LOG(INFO) << "umount timeout, last resort, kill all and try";
315        if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(true);
316        KillAllProcesses();
317        // even if it succeeds, still it is timeout and do not run fsck with all processes killed
318        UmountStat st = UmountPartitions(0ms);
319        if ((st != UMOUNT_STAT_SUCCESS) && DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(false);
320    }
321
322    if (stat == UMOUNT_STAT_SUCCESS && runFsck) {
323        // fsck part is excluded from timeout check. It only runs for user initiated shutdown
324        // and should not affect reboot time.
325        for (auto& entry : block_devices) {
326            entry.DoFsck();
327        }
328    }
329    return stat;
330}
331
332void DoReboot(unsigned int cmd, const std::string& reason, const std::string& rebootTarget,
333              bool runFsck) {
334    Timer t;
335    LOG(INFO) << "Reboot start, reason: " << reason << ", rebootTarget: " << rebootTarget;
336
337    // Ensure last reboot reason is reduced to canonical
338    // alias reported in bootloader or system boot reason.
339    size_t skip = 0;
340    std::vector<std::string> reasons = Split(reason, ",");
341    if (reasons.size() >= 2 && reasons[0] == "reboot" &&
342        (reasons[1] == "recovery" || reasons[1] == "bootloader" || reasons[1] == "cold" ||
343         reasons[1] == "hard" || reasons[1] == "warm")) {
344        skip = strlen("reboot,");
345    }
346    property_set(LAST_REBOOT_REASON_PROPERTY, reason.c_str() + skip);
347    sync();
348
349    bool is_thermal_shutdown = cmd == ANDROID_RB_THERMOFF;
350
351    auto shutdown_timeout = 0ms;
352    if (!SHUTDOWN_ZERO_TIMEOUT) {
353        if (is_thermal_shutdown) {
354            constexpr unsigned int thermal_shutdown_timeout = 1;
355            shutdown_timeout = std::chrono::seconds(thermal_shutdown_timeout);
356        } else {
357            constexpr unsigned int shutdown_timeout_default = 6;
358            auto shutdown_timeout_property = android::base::GetUintProperty(
359                "ro.build.shutdown_timeout", shutdown_timeout_default);
360            shutdown_timeout = std::chrono::seconds(shutdown_timeout_property);
361        }
362    }
363    LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " ms";
364
365    // keep debugging tools until non critical ones are all gone.
366    const std::set<std::string> kill_after_apps{"tombstoned", "logd", "adbd"};
367    // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
368    const std::set<std::string> to_starts{"watchdogd"};
369    for (const auto& s : ServiceList::GetInstance()) {
370        if (kill_after_apps.count(s->name())) {
371            s->SetShutdownCritical();
372        } else if (to_starts.count(s->name())) {
373            if (auto result = s->Start(); !result) {
374                LOG(ERROR) << "Could not start shutdown 'to_start' service '" << s->name()
375                           << "': " << result.error();
376            }
377            s->SetShutdownCritical();
378        } else if (s->IsShutdownCritical()) {
379            // Start shutdown critical service if not started.
380            if (auto result = s->Start(); !result) {
381                LOG(ERROR) << "Could not start shutdown critical service '" << s->name()
382                           << "': " << result.error();
383            }
384        }
385    }
386
387    // remaining operations (specifically fsck) may take a substantial duration
388    if (cmd == ANDROID_RB_POWEROFF || is_thermal_shutdown) {
389        TurnOffBacklight();
390    }
391
392    Service* bootAnim = ServiceList::GetInstance().FindService("bootanim");
393    Service* surfaceFlinger = ServiceList::GetInstance().FindService("surfaceflinger");
394    if (bootAnim != nullptr && surfaceFlinger != nullptr && surfaceFlinger->IsRunning()) {
395        // will not check animation class separately
396        for (const auto& service : ServiceList::GetInstance()) {
397            if (service->classnames().count("animation")) service->SetShutdownCritical();
398        }
399    }
400
401    // optional shutdown step
402    // 1. terminate all services except shutdown critical ones. wait for delay to finish
403    if (shutdown_timeout > 0ms) {
404        LOG(INFO) << "terminating init services";
405
406        // Ask all services to terminate except shutdown critical ones.
407        for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
408            if (!s->IsShutdownCritical()) s->Terminate();
409        }
410
411        int service_count = 0;
412        // Only wait up to half of timeout here
413        auto termination_wait_timeout = shutdown_timeout / 2;
414        while (t.duration() < termination_wait_timeout) {
415            ReapAnyOutstandingChildren();
416
417            service_count = 0;
418            for (const auto& s : ServiceList::GetInstance()) {
419                // Count the number of services running except shutdown critical.
420                // Exclude the console as it will ignore the SIGTERM signal
421                // and not exit.
422                // Note: SVC_CONSOLE actually means "requires console" but
423                // it is only used by the shell.
424                if (!s->IsShutdownCritical() && s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
425                    service_count++;
426                }
427            }
428
429            if (service_count == 0) {
430                // All terminable services terminated. We can exit early.
431                break;
432            }
433
434            // Wait a bit before recounting the number or running services.
435            std::this_thread::sleep_for(50ms);
436        }
437        LOG(INFO) << "Terminating running services took " << t
438                  << " with remaining services:" << service_count;
439    }
440
441    // minimum safety steps before restarting
442    // 2. kill all services except ones that are necessary for the shutdown sequence.
443    for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
444        if (!s->IsShutdownCritical()) s->Stop();
445    }
446    ReapAnyOutstandingChildren();
447
448    // 3. send volume shutdown to vold
449    Service* voldService = ServiceList::GetInstance().FindService("vold");
450    if (voldService != nullptr && voldService->IsRunning()) {
451        ShutdownVold();
452        voldService->Stop();
453    } else {
454        LOG(INFO) << "vold not running, skipping vold shutdown";
455    }
456    // logcat stopped here
457    for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
458        if (kill_after_apps.count(s->name())) s->Stop();
459    }
460    // 4. sync, try umount, and optionally run fsck for user shutdown
461    sync();
462    UmountStat stat = TryUmountAndFsck(runFsck, shutdown_timeout - t.duration());
463    // Follow what linux shutdown is doing: one more sync with little bit delay
464    sync();
465    if (!is_thermal_shutdown) std::this_thread::sleep_for(100ms);
466    LogShutdownTime(stat, &t);
467    // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
468    RebootSystem(cmd, rebootTarget);
469    abort();
470}
471
472bool HandlePowerctlMessage(const std::string& command) {
473    unsigned int cmd = 0;
474    std::vector<std::string> cmd_params = Split(command, ",");
475    std::string reboot_target = "";
476    bool run_fsck = false;
477    bool command_invalid = false;
478
479    if (cmd_params.size() > 3) {
480        command_invalid = true;
481    } else if (cmd_params[0] == "shutdown") {
482        cmd = ANDROID_RB_POWEROFF;
483        if (cmd_params.size() == 2) {
484            if (cmd_params[1] == "userrequested") {
485                // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
486                // Run fsck once the file system is remounted in read-only mode.
487                run_fsck = true;
488            } else if (cmd_params[1] == "thermal") {
489                // Turn off sources of heat immediately.
490                TurnOffBacklight();
491                // run_fsck is false to avoid delay
492                cmd = ANDROID_RB_THERMOFF;
493            }
494        }
495    } else if (cmd_params[0] == "reboot") {
496        cmd = ANDROID_RB_RESTART2;
497        if (cmd_params.size() >= 2) {
498            reboot_target = cmd_params[1];
499            // When rebooting to the bootloader notify the bootloader writing
500            // also the BCB.
501            if (reboot_target == "bootloader") {
502                std::string err;
503                if (!write_reboot_bootloader(&err)) {
504                    LOG(ERROR) << "reboot-bootloader: Error writing "
505                                  "bootloader_message: "
506                               << err;
507                }
508            }
509            // If there is an additional parameter, pass it along
510            if ((cmd_params.size() == 3) && cmd_params[2].size()) {
511                reboot_target += "," + cmd_params[2];
512            }
513        }
514    } else {
515        command_invalid = true;
516    }
517    if (command_invalid) {
518        LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
519        return false;
520    }
521
522    LOG(INFO) << "Clear action queue and start shutdown trigger";
523    ActionManager::GetInstance().ClearQueue();
524    // Queue shutdown trigger first
525    ActionManager::GetInstance().QueueEventTrigger("shutdown");
526    // Queue built-in shutdown_done
527    auto shutdown_handler = [cmd, command, reboot_target, run_fsck](const BuiltinArguments&) {
528        DoReboot(cmd, command, reboot_target, run_fsck);
529        return Success();
530    };
531    ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
532
533    // Skip wait for prop if it is in progress
534    ResetWaitForProp();
535
536    // Clear EXEC flag if there is one pending
537    for (const auto& s : ServiceList::GetInstance()) {
538        s->UnSetExec();
539    }
540
541    return true;
542}
543
544}  // namespace init
545}  // namespace android
546