• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/f2fs.h>
22 #include <linux/fs.h>
23 #include <linux/loop.h>
24 #include <mntent.h>
25 #include <semaphore.h>
26 #include <stdlib.h>
27 #include <sys/cdefs.h>
28 #include <sys/ioctl.h>
29 #include <sys/mount.h>
30 #include <sys/stat.h>
31 #include <sys/swap.h>
32 #include <sys/syscall.h>
33 #include <sys/types.h>
34 #include <sys/wait.h>
35 
36 #include <chrono>
37 #include <memory>
38 #include <set>
39 #include <thread>
40 #include <vector>
41 
42 #include <android-base/chrono_utils.h>
43 #include <android-base/file.h>
44 #include <android-base/logging.h>
45 #include <android-base/macros.h>
46 #include <android-base/properties.h>
47 #include <android-base/scopeguard.h>
48 #include <android-base/strings.h>
49 #include <android-base/unique_fd.h>
50 #include <bootloader_message/bootloader_message.h>
51 #include <cutils/android_reboot.h>
52 #include <fs_mgr.h>
53 #include <libsnapshot/snapshot.h>
54 #include <logwrap/logwrap.h>
55 #include <private/android_filesystem_config.h>
56 #include <selinux/selinux.h>
57 
58 #include "action.h"
59 #include "action_manager.h"
60 #include "builtin_arguments.h"
61 #include "init.h"
62 #include "mount_namespace.h"
63 #include "property_service.h"
64 #include "reboot_utils.h"
65 #include "service.h"
66 #include "service_list.h"
67 #include "sigchld_handler.h"
68 #include "util.h"
69 
70 using namespace std::literals;
71 
72 using android::base::boot_clock;
73 using android::base::GetBoolProperty;
74 using android::base::GetUintProperty;
75 using android::base::SetProperty;
76 using android::base::Split;
77 using android::base::Timer;
78 using android::base::unique_fd;
79 using android::base::WaitForProperty;
80 using android::base::WriteStringToFile;
81 
82 namespace android {
83 namespace init {
84 
85 static bool shutting_down = false;
86 
87 static const std::set<std::string> kDebuggingServices{"tombstoned", "logd", "adbd", "console"};
88 
PersistRebootReason(const char * reason,bool write_to_property)89 static void PersistRebootReason(const char* reason, bool write_to_property) {
90     if (write_to_property) {
91         SetProperty(LAST_REBOOT_REASON_PROPERTY, reason);
92     }
93     auto fd = unique_fd(TEMP_FAILURE_RETRY(open(
94             LAST_REBOOT_REASON_FILE, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY, 0666)));
95     if (!fd.ok()) {
96         PLOG(ERROR) << "Could not open '" << LAST_REBOOT_REASON_FILE
97                     << "' to persist reboot reason";
98         return;
99     }
100     WriteStringToFd(reason, fd);
101     fsync(fd.get());
102 }
103 
104 // represents umount status during reboot / shutdown.
105 enum UmountStat {
106     /* umount succeeded. */
107     UMOUNT_STAT_SUCCESS = 0,
108     /* umount was not run. */
109     UMOUNT_STAT_SKIPPED = 1,
110     /* umount failed with timeout. */
111     UMOUNT_STAT_TIMEOUT = 2,
112     /* could not run due to error */
113     UMOUNT_STAT_ERROR = 3,
114     /* not used by init but reserved for other part to use this to represent the
115        the state where umount status before reboot is not found / available. */
116     UMOUNT_STAT_NOT_AVAILABLE = 4,
117 };
118 
119 // Utility for struct mntent
120 class MountEntry {
121   public:
MountEntry(const mntent & entry)122     explicit MountEntry(const mntent& entry)
123         : mnt_fsname_(entry.mnt_fsname),
124           mnt_dir_(entry.mnt_dir),
125           mnt_type_(entry.mnt_type),
126           mnt_opts_(entry.mnt_opts) {}
127 
Umount(bool force)128     bool Umount(bool force) {
129         LOG(INFO) << "Unmounting " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
130         int r = umount2(mnt_dir_.c_str(), force ? MNT_FORCE : 0);
131         if (r == 0) {
132             LOG(INFO) << "Umounted " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
133             return true;
134         } else {
135             PLOG(WARNING) << "Cannot umount " << mnt_fsname_ << ":" << mnt_dir_ << " opts "
136                           << mnt_opts_;
137             return false;
138         }
139     }
140 
DoFsck()141     void DoFsck() {
142         int st;
143         if (IsF2Fs()) {
144             const char* f2fs_argv[] = {
145                     "/system/bin/fsck.f2fs",
146                     "-a",
147                     mnt_fsname_.c_str(),
148             };
149             logwrap_fork_execvp(arraysize(f2fs_argv), f2fs_argv, &st, false, LOG_KLOG, true,
150                                 nullptr);
151         } else if (IsExt4()) {
152             const char* ext4_argv[] = {
153                     "/system/bin/e2fsck",
154                     "-y",
155                     mnt_fsname_.c_str(),
156             };
157             logwrap_fork_execvp(arraysize(ext4_argv), ext4_argv, &st, false, LOG_KLOG, true,
158                                 nullptr);
159         }
160     }
161 
IsBlockDevice(const struct mntent & mntent)162     static bool IsBlockDevice(const struct mntent& mntent) {
163         return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
164     }
165 
IsEmulatedDevice(const struct mntent & mntent)166     static bool IsEmulatedDevice(const struct mntent& mntent) {
167         return android::base::StartsWith(mntent.mnt_fsname, "/data/");
168     }
169 
170   private:
IsF2Fs() const171     bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
172 
IsExt4() const173     bool IsExt4() const { return mnt_type_ == "ext4"; }
174 
175     std::string mnt_fsname_;
176     std::string mnt_dir_;
177     std::string mnt_type_;
178     std::string mnt_opts_;
179 };
180 
181 // Turn off backlight while we are performing power down cleanup activities.
TurnOffBacklight()182 static void TurnOffBacklight() {
183     Service* service = ServiceList::GetInstance().FindService("blank_screen");
184     if (service == nullptr) {
185         LOG(WARNING) << "cannot find blank_screen in TurnOffBacklight";
186         return;
187     }
188     if (auto result = service->Start(); !result.ok()) {
189         LOG(WARNING) << "Could not start blank_screen service: " << result.error();
190     }
191 }
192 
CallVdc(const std::string & system,const std::string & cmd)193 static Result<void> CallVdc(const std::string& system, const std::string& cmd) {
194     LOG(INFO) << "Calling /system/bin/vdc " << system << " " << cmd;
195     const char* vdc_argv[] = {"/system/bin/vdc", system.c_str(), cmd.c_str()};
196     int status;
197     if (logwrap_fork_execvp(arraysize(vdc_argv), vdc_argv, &status, false, LOG_KLOG, true,
198                             nullptr) != 0) {
199         return ErrnoError() << "Failed to call '/system/bin/vdc " << system << " " << cmd << "'";
200     }
201     if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
202         return {};
203     }
204     return Error() << "'/system/bin/vdc " << system << " " << cmd << "' failed : " << status;
205 }
206 
LogShutdownTime(UmountStat stat,Timer * t)207 static void LogShutdownTime(UmountStat stat, Timer* t) {
208     LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration().count()) << ":"
209                  << stat;
210 }
211 
IsDataMounted(const std::string & fstype)212 static bool IsDataMounted(const std::string& fstype) {
213     std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
214     if (fp == nullptr) {
215         PLOG(ERROR) << "Failed to open /proc/mounts";
216         return false;
217     }
218     mntent* mentry;
219     while ((mentry = getmntent(fp.get())) != nullptr) {
220         if (mentry->mnt_dir == "/data"s) {
221             return fstype == "*" || mentry->mnt_type == fstype;
222         }
223     }
224     return false;
225 }
226 
227 // Find all read+write block devices and emulated devices in /proc/mounts and add them to
228 // the correpsponding list.
FindPartitionsToUmount(std::vector<MountEntry> * block_dev_partitions,std::vector<MountEntry> * emulated_partitions,bool dump)229 static bool FindPartitionsToUmount(std::vector<MountEntry>* block_dev_partitions,
230                                    std::vector<MountEntry>* emulated_partitions, bool dump) {
231     std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "re"), endmntent);
232     if (fp == nullptr) {
233         PLOG(ERROR) << "Failed to open /proc/mounts";
234         return false;
235     }
236     mntent* mentry;
237     while ((mentry = getmntent(fp.get())) != nullptr) {
238         if (dump) {
239             LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
240                       << mentry->mnt_opts << " type " << mentry->mnt_type;
241         } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
242             std::string mount_dir(mentry->mnt_dir);
243             // These are R/O partitions changed to R/W after adb remount.
244             // Do not umount them as shutdown critical services may rely on them.
245             if (mount_dir != "/" && mount_dir != "/system" && mount_dir != "/vendor" &&
246                 mount_dir != "/oem") {
247                 block_dev_partitions->emplace(block_dev_partitions->begin(), *mentry);
248             }
249         } else if (MountEntry::IsEmulatedDevice(*mentry)) {
250             emulated_partitions->emplace(emulated_partitions->begin(), *mentry);
251         }
252     }
253     return true;
254 }
255 
DumpUmountDebuggingInfo()256 static void DumpUmountDebuggingInfo() {
257     int status;
258     if (!security_getenforce()) {
259         LOG(INFO) << "Run lsof";
260         const char* lsof_argv[] = {"/system/bin/lsof"};
261         logwrap_fork_execvp(arraysize(lsof_argv), lsof_argv, &status, false, LOG_KLOG, true,
262                             nullptr);
263     }
264     FindPartitionsToUmount(nullptr, nullptr, true);
265     // dump current CPU stack traces and uninterruptible tasks
266     WriteStringToFile("l", PROC_SYSRQ);
267     WriteStringToFile("w", PROC_SYSRQ);
268 }
269 
UmountPartitions(std::chrono::milliseconds timeout)270 static UmountStat UmountPartitions(std::chrono::milliseconds timeout) {
271     // Terminate (SIGTERM) the services before unmounting partitions.
272     // If the processes block the signal, then partitions will eventually fail
273     // to unmount and then we fallback to SIGKILL the services.
274     //
275     // Hence, give the services a chance for a graceful shutdown before sending SIGKILL.
276     for (const auto& s : ServiceList::GetInstance()) {
277         if (s->IsShutdownCritical()) {
278             LOG(INFO) << "Shutdown service: " << s->name();
279             s->Terminate();
280         }
281     }
282     ReapAnyOutstandingChildren();
283 
284     Timer t;
285     /* data partition needs all pending writes to be completed and all emulated partitions
286      * umounted.If the current waiting is not good enough, give
287      * up and leave it to e2fsck after reboot to fix it.
288      */
289     while (true) {
290         std::vector<MountEntry> block_devices;
291         std::vector<MountEntry> emulated_devices;
292         if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
293             return UMOUNT_STAT_ERROR;
294         }
295         if (block_devices.size() == 0) {
296             return UMOUNT_STAT_SUCCESS;
297         }
298         bool unmount_done = true;
299         if (emulated_devices.size() > 0) {
300             for (auto& entry : emulated_devices) {
301                 if (!entry.Umount(false)) unmount_done = false;
302             }
303             if (unmount_done) {
304                 sync();
305             }
306         }
307         for (auto& entry : block_devices) {
308             if (!entry.Umount(timeout == 0ms)) unmount_done = false;
309         }
310         if (unmount_done) {
311             return UMOUNT_STAT_SUCCESS;
312         }
313         if ((timeout < t.duration())) {  // try umount at least once
314             return UMOUNT_STAT_TIMEOUT;
315         }
316         std::this_thread::sleep_for(100ms);
317     }
318 }
319 
KillAllProcesses()320 static void KillAllProcesses() {
321     WriteStringToFile("i", PROC_SYSRQ);
322 }
323 
324 // Create reboot/shutdwon monitor thread
RebootMonitorThread(unsigned int cmd,const std::string & reboot_target,sem_t * reboot_semaphore,std::chrono::milliseconds shutdown_timeout,bool * reboot_monitor_run)325 void RebootMonitorThread(unsigned int cmd, const std::string& reboot_target,
326                          sem_t* reboot_semaphore, std::chrono::milliseconds shutdown_timeout,
327                          bool* reboot_monitor_run) {
328     unsigned int remaining_shutdown_time = 0;
329 
330     // 300 seconds more than the timeout passed to the thread as there is a final Umount pass
331     // after the timeout is reached.
332     constexpr unsigned int shutdown_watchdog_timeout_default = 300;
333     auto shutdown_watchdog_timeout = android::base::GetUintProperty(
334             "ro.build.shutdown.watchdog.timeout", shutdown_watchdog_timeout_default);
335     remaining_shutdown_time = shutdown_watchdog_timeout + shutdown_timeout.count() / 1000;
336 
337     while (*reboot_monitor_run == true) {
338         if (TEMP_FAILURE_RETRY(sem_wait(reboot_semaphore)) == -1) {
339             LOG(ERROR) << "sem_wait failed and exit RebootMonitorThread()";
340             return;
341         }
342 
343         timespec shutdown_timeout_timespec;
344         if (clock_gettime(CLOCK_MONOTONIC, &shutdown_timeout_timespec) == -1) {
345             LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
346             return;
347         }
348 
349         // If there are some remaining shutdown time left from previous round, we use
350         // remaining time here.
351         shutdown_timeout_timespec.tv_sec += remaining_shutdown_time;
352 
353         LOG(INFO) << "shutdown_timeout_timespec.tv_sec: " << shutdown_timeout_timespec.tv_sec;
354 
355         int sem_return = 0;
356         while ((sem_return = sem_timedwait_monotonic_np(reboot_semaphore,
357                                                         &shutdown_timeout_timespec)) == -1 &&
358                errno == EINTR) {
359         }
360 
361         if (sem_return == -1) {
362             LOG(ERROR) << "Reboot thread timed out";
363 
364             if (android::base::GetBoolProperty("ro.debuggable", false) == true) {
365                 if (false) {
366                     // SEPolicy will block debuggerd from running and this is intentional.
367                     // But these lines are left to be enabled during debugging.
368                     LOG(INFO) << "Try to dump init process call trace:";
369                     const char* vdc_argv[] = {"/system/bin/debuggerd", "-b", "1"};
370                     int status;
371                     logwrap_fork_execvp(arraysize(vdc_argv), vdc_argv, &status, false, LOG_KLOG,
372                                         true, nullptr);
373                 }
374                 LOG(INFO) << "Show stack for all active CPU:";
375                 WriteStringToFile("l", PROC_SYSRQ);
376 
377                 LOG(INFO) << "Show tasks that are in disk sleep(uninterruptable sleep), which are "
378                              "like "
379                              "blocked in mutex or hardware register access:";
380                 WriteStringToFile("w", PROC_SYSRQ);
381             }
382 
383             // In shutdown case,notify kernel to sync and umount fs to read-only before shutdown.
384             if (cmd == ANDROID_RB_POWEROFF || cmd == ANDROID_RB_THERMOFF) {
385                 WriteStringToFile("s", PROC_SYSRQ);
386 
387                 WriteStringToFile("u", PROC_SYSRQ);
388 
389                 RebootSystem(cmd, reboot_target);
390             }
391 
392             LOG(ERROR) << "Trigger crash at last!";
393             WriteStringToFile("c", PROC_SYSRQ);
394         } else {
395             timespec current_time_timespec;
396 
397             if (clock_gettime(CLOCK_MONOTONIC, &current_time_timespec) == -1) {
398                 LOG(ERROR) << "clock_gettime() fail! exit RebootMonitorThread()";
399                 return;
400             }
401 
402             remaining_shutdown_time =
403                     shutdown_timeout_timespec.tv_sec - current_time_timespec.tv_sec;
404 
405             LOG(INFO) << "remaining_shutdown_time: " << remaining_shutdown_time;
406         }
407     }
408 }
409 
UmountDynamicPartitions(const std::vector<std::string> & dynamic_partitions)410 static bool UmountDynamicPartitions(const std::vector<std::string>& dynamic_partitions) {
411     bool ret = true;
412     for (auto device : dynamic_partitions) {
413         // Cannot unmount /system
414         if (device == "/system") {
415             continue;
416         }
417         int r = umount2(device.c_str(), MNT_FORCE);
418         if (r == 0) {
419             LOG(INFO) << "Umounted success: " << device;
420         } else {
421             PLOG(WARNING) << "Cannot umount: " << device;
422             ret = false;
423         }
424     }
425     return ret;
426 }
427 
428 /* Try umounting all emulated file systems R/W block device cfile systems.
429  * This will just try umount and give it up if it fails.
430  * For fs like ext4, this is ok as file system will be marked as unclean shutdown
431  * and necessary check can be done at the next reboot.
432  * For safer shutdown, caller needs to make sure that
433  * all processes / emulated partition for the target fs are all cleaned-up.
434  *
435  * return true when umount was successful. false when timed out.
436  */
TryUmountAndFsck(unsigned int cmd,bool run_fsck,std::chrono::milliseconds timeout,sem_t * reboot_semaphore)437 static UmountStat TryUmountAndFsck(unsigned int cmd, bool run_fsck,
438                                    std::chrono::milliseconds timeout, sem_t* reboot_semaphore) {
439     Timer t;
440     std::vector<MountEntry> block_devices;
441     std::vector<MountEntry> emulated_devices;
442     std::vector<std::string> dynamic_partitions;
443 
444     if (run_fsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
445         return UMOUNT_STAT_ERROR;
446     }
447     auto sm = snapshot::SnapshotManager::New();
448     bool ota_update_in_progress = false;
449     if (sm->IsUserspaceSnapshotUpdateInProgress(dynamic_partitions)) {
450         LOG(INFO) << "OTA update in progress. Pause snapshot merge";
451         if (!sm->PauseSnapshotMerge()) {
452             LOG(ERROR) << "Snapshot-merge pause failed";
453         }
454         ota_update_in_progress = true;
455     }
456     UmountStat stat = UmountPartitions(timeout - t.duration());
457     if (stat != UMOUNT_STAT_SUCCESS) {
458         LOG(INFO) << "umount timeout, last resort, kill all and try";
459         if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
460         // Since umount timedout, we will try to kill all processes
461         // and do one more attempt to umount the partitions.
462         //
463         // However, if OTA update is in progress, we don't want
464         // to kill the snapuserd daemon as the daemon will
465         // be serving I/O requests. Killing the daemon will
466         // end up with I/O failures. If the update is in progress,
467         // we will just return the umount failure status immediately.
468         // This is ok, given the fact that killing the processes
469         // and doing an umount is just a last effort. We are
470         // still not doing fsck when all processes are killed.
471         //
472         if (ota_update_in_progress) {
473             bool umount_dynamic_partitions = UmountDynamicPartitions(dynamic_partitions);
474             LOG(INFO) << "Sending SIGTERM to all process";
475             // Send SIGTERM to all processes except init
476             WriteStringToFile("e", PROC_SYSRQ);
477             // Wait for processes to terminate
478             std::this_thread::sleep_for(1s);
479             // Try one more attempt to umount other partitions which failed
480             // earlier
481             if (!umount_dynamic_partitions) {
482                 UmountDynamicPartitions(dynamic_partitions);
483             }
484             return stat;
485         }
486         KillAllProcesses();
487         // even if it succeeds, still it is timeout and do not run fsck with all processes killed
488         UmountStat st = UmountPartitions(0ms);
489         if ((st != UMOUNT_STAT_SUCCESS) && DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo();
490     }
491 
492     if (stat == UMOUNT_STAT_SUCCESS && run_fsck) {
493         LOG(INFO) << "Pause reboot monitor thread before fsck";
494         sem_post(reboot_semaphore);
495 
496         // fsck part is excluded from timeout check. It only runs for user initiated shutdown
497         // and should not affect reboot time.
498         for (auto& entry : block_devices) {
499             entry.DoFsck();
500         }
501 
502         LOG(INFO) << "Resume reboot monitor thread after fsck";
503         sem_post(reboot_semaphore);
504     }
505     return stat;
506 }
507 
508 // zram is able to use backing device on top of a loopback device.
509 // In order to unmount /data successfully, we have to kill the loopback device first
510 #define ZRAM_DEVICE       "/dev/block/zram0"
511 #define ZRAM_RESET        "/sys/block/zram0/reset"
512 #define ZRAM_BACK_DEV     "/sys/block/zram0/backing_dev"
513 #define ZRAM_INITSTATE    "/sys/block/zram0/initstate"
KillZramBackingDevice()514 static Result<void> KillZramBackingDevice() {
515     std::string zram_initstate;
516     if (!android::base::ReadFileToString(ZRAM_INITSTATE, &zram_initstate)) {
517         return ErrnoError() << "Failed to read " << ZRAM_INITSTATE;
518     }
519 
520     zram_initstate.erase(zram_initstate.length() - 1);
521     if (zram_initstate == "0") {
522         LOG(INFO) << "Zram has not been swapped on";
523         return {};
524     }
525 
526     if (access(ZRAM_BACK_DEV, F_OK) != 0 && errno == ENOENT) {
527         LOG(INFO) << "No zram backing device configured";
528         return {};
529     }
530     std::string backing_dev;
531     if (!android::base::ReadFileToString(ZRAM_BACK_DEV, &backing_dev)) {
532         return ErrnoError() << "Failed to read " << ZRAM_BACK_DEV;
533     }
534 
535     android::base::Trim(backing_dev);
536 
537     if (android::base::StartsWith(backing_dev, "none")) {
538         LOG(INFO) << "No zram backing device configured";
539         return {};
540     }
541 
542     // shutdown zram handle
543     Timer swap_timer;
544     LOG(INFO) << "swapoff() start...";
545     if (swapoff(ZRAM_DEVICE) == -1) {
546         return ErrnoError() << "zram_backing_dev: swapoff (" << backing_dev << ")"
547                             << " failed";
548     }
549     LOG(INFO) << "swapoff() took " << swap_timer;
550 
551     if (!WriteStringToFile("1", ZRAM_RESET)) {
552         return Error() << "zram_backing_dev: reset (" << backing_dev << ")"
553                        << " failed";
554     }
555 
556     if (!android::base::ReadFileToString(ZRAM_BACK_DEV, &backing_dev)) {
557         return ErrnoError() << "Failed to read " << ZRAM_BACK_DEV;
558     }
559 
560     android::base::Trim(backing_dev);
561 
562     if (!android::base::StartsWith(backing_dev, "/dev/block/loop")) {
563         LOG(INFO) << backing_dev << " is not a loop device. Exiting early";
564         return {};
565     }
566 
567     // clear loopback device
568     unique_fd loop(TEMP_FAILURE_RETRY(open(backing_dev.c_str(), O_RDWR | O_CLOEXEC)));
569     if (loop.get() < 0) {
570         return ErrnoError() << "zram_backing_dev: open(" << backing_dev << ")"
571                             << " failed";
572     }
573 
574     if (ioctl(loop.get(), LOOP_CLR_FD, 0) < 0) {
575         return ErrnoError() << "zram_backing_dev: loop_clear (" << backing_dev << ")"
576                             << " failed";
577     }
578     LOG(INFO) << "zram_backing_dev: `" << backing_dev << "` is cleared successfully.";
579     return {};
580 }
581 
582 // Stops given services, waits for them to be stopped for |timeout| ms.
583 // If terminate is true, then SIGTERM is sent to services, otherwise SIGKILL is sent.
584 // Note that services are stopped in order given by |ServiceList::services_in_shutdown_order|
585 // function.
StopServices(const std::set<std::string> & services,std::chrono::milliseconds timeout,bool terminate)586 static void StopServices(const std::set<std::string>& services, std::chrono::milliseconds timeout,
587                          bool terminate) {
588     LOG(INFO) << "Stopping " << services.size() << " services by sending "
589               << (terminate ? "SIGTERM" : "SIGKILL");
590     std::vector<pid_t> pids;
591     pids.reserve(services.size());
592     for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
593         if (services.count(s->name()) == 0) {
594             continue;
595         }
596         if (s->pid() > 0) {
597             pids.push_back(s->pid());
598         }
599         if (terminate) {
600             s->Terminate();
601         } else {
602             s->Stop();
603         }
604     }
605     if (timeout > 0ms) {
606         WaitToBeReaped(Service::GetSigchldFd(), pids, timeout);
607     } else {
608         // Even if we don't to wait for services to stop, we still optimistically reap zombies.
609         ReapAnyOutstandingChildren();
610     }
611 }
612 
613 // Like StopServices, but also logs all the services that failed to stop after the provided timeout.
614 // Returns number of violators.
StopServicesAndLogViolations(const std::set<std::string> & services,std::chrono::milliseconds timeout,bool terminate)615 int StopServicesAndLogViolations(const std::set<std::string>& services,
616                                  std::chrono::milliseconds timeout, bool terminate) {
617     StopServices(services, timeout, terminate);
618     int still_running = 0;
619     for (const auto& s : ServiceList::GetInstance()) {
620         if (s->IsRunning() && services.count(s->name())) {
621             LOG(ERROR) << "[service-misbehaving] : service '" << s->name() << "' is still running "
622                        << timeout.count() << "ms after receiving "
623                        << (terminate ? "SIGTERM" : "SIGKILL");
624             still_running++;
625         }
626     }
627     return still_running;
628 }
629 
UnmountAllApexes()630 static Result<void> UnmountAllApexes() {
631     // don't need to unmount because apexd doesn't use /data in Microdroid
632     if (IsMicrodroid()) {
633         return {};
634     }
635 
636     const char* args[] = {"/system/bin/apexd", "--unmount-all"};
637     int status;
638     if (logwrap_fork_execvp(arraysize(args), args, &status, false, LOG_KLOG, true, nullptr) != 0) {
639         return ErrnoError() << "Failed to call '/system/bin/apexd --unmount-all'";
640     }
641     if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
642         return {};
643     }
644     return Error() << "'/system/bin/apexd --unmount-all' failed : " << status;
645 }
646 
647 //* Reboot / shutdown the system.
648 // cmd ANDROID_RB_* as defined in android_reboot.h
649 // reason Reason string like "reboot", "shutdown,userrequested"
650 // reboot_target Reboot target string like "bootloader". Otherwise, it should be an empty string.
651 // run_fsck Whether to run fsck after umount is done.
652 //
DoReboot(unsigned int cmd,const std::string & reason,const std::string & reboot_target,bool run_fsck)653 static void DoReboot(unsigned int cmd, const std::string& reason, const std::string& reboot_target,
654                      bool run_fsck) {
655     Timer t;
656     LOG(INFO) << "Reboot start, reason: " << reason << ", reboot_target: " << reboot_target;
657 
658     bool is_thermal_shutdown = cmd == ANDROID_RB_THERMOFF;
659 
660     auto shutdown_timeout = 0ms;
661     if (!SHUTDOWN_ZERO_TIMEOUT) {
662         constexpr unsigned int shutdown_timeout_default = 6;
663         constexpr unsigned int max_thermal_shutdown_timeout = 3;
664         auto shutdown_timeout_final = android::base::GetUintProperty("ro.build.shutdown_timeout",
665                                                                      shutdown_timeout_default);
666         if (is_thermal_shutdown && shutdown_timeout_final > max_thermal_shutdown_timeout) {
667             shutdown_timeout_final = max_thermal_shutdown_timeout;
668         }
669         shutdown_timeout = std::chrono::seconds(shutdown_timeout_final);
670     }
671     LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " ms";
672 
673     sem_t reboot_semaphore;
674     if (sem_init(&reboot_semaphore, false, 0) == -1) {
675         // These should never fail, but if they do, skip the graceful reboot and reboot immediately.
676         LOG(ERROR) << "sem_init() fail and RebootSystem() return!";
677         RebootSystem(cmd, reboot_target, reason);
678     }
679 
680     // Start a thread to monitor init shutdown process
681     LOG(INFO) << "Create reboot monitor thread.";
682     bool reboot_monitor_run = true;
683     std::thread reboot_monitor_thread(&RebootMonitorThread, cmd, reboot_target, &reboot_semaphore,
684                                       shutdown_timeout, &reboot_monitor_run);
685     reboot_monitor_thread.detach();
686 
687     // Start reboot monitor thread
688     sem_post(&reboot_semaphore);
689 
690     // Ensure last reboot reason is reduced to canonical
691     // alias reported in bootloader or system boot reason.
692     size_t skip = 0;
693     std::vector<std::string> reasons = Split(reason, ",");
694     if (reasons.size() >= 2 && reasons[0] == "reboot" &&
695         (reasons[1] == "recovery" || reasons[1] == "bootloader" || reasons[1] == "cold" ||
696          reasons[1] == "hard" || reasons[1] == "warm")) {
697         skip = strlen("reboot,");
698     }
699     PersistRebootReason(reason.c_str() + skip, true);
700 
701     // If /data isn't mounted then we can skip the extra reboot steps below, since we don't need to
702     // worry about unmounting it.
703     if (!IsDataMounted("*")) {
704         sync();
705         RebootSystem(cmd, reboot_target, reason);
706         abort();
707     }
708 
709     bool do_shutdown_animation = GetBoolProperty("ro.init.shutdown_animation", false);
710     // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
711     const std::set<std::string> to_starts{"watchdogd"};
712     std::set<std::string> stop_first;
713     for (const auto& s : ServiceList::GetInstance()) {
714         if (kDebuggingServices.count(s->name())) {
715             // keep debugging tools until non critical ones are all gone.
716             s->SetShutdownCritical();
717         } else if (to_starts.count(s->name())) {
718             if (auto result = s->Start(); !result.ok()) {
719                 LOG(ERROR) << "Could not start shutdown 'to_start' service '" << s->name()
720                            << "': " << result.error();
721             }
722             s->SetShutdownCritical();
723         } else if (do_shutdown_animation && s->classnames().count("animation") > 0) {
724             // Need these for shutdown animations.
725         } else if (s->IsShutdownCritical()) {
726             // Start shutdown critical service if not started.
727             if (auto result = s->Start(); !result.ok()) {
728                 LOG(ERROR) << "Could not start shutdown critical service '" << s->name()
729                            << "': " << result.error();
730             }
731         } else {
732             stop_first.insert(s->name());
733         }
734     }
735 
736     // remaining operations (specifically fsck) may take a substantial duration
737     if (!do_shutdown_animation && (cmd == ANDROID_RB_POWEROFF || is_thermal_shutdown)) {
738         TurnOffBacklight();
739     }
740 
741     Service* boot_anim = ServiceList::GetInstance().FindService("bootanim");
742     Service* surface_flinger = ServiceList::GetInstance().FindService("surfaceflinger");
743     if (boot_anim != nullptr && surface_flinger != nullptr && surface_flinger->IsRunning()) {
744 
745         if (do_shutdown_animation) {
746             SetProperty("service.bootanim.exit", "0");
747             SetProperty("service.bootanim.progress", "0");
748             // Could be in the middle of animation. Stop and start so that it can pick
749             // up the right mode.
750             boot_anim->Stop();
751         }
752 
753         for (const auto& service : ServiceList::GetInstance()) {
754             if (service->classnames().count("animation") == 0) {
755                 continue;
756             }
757 
758             // start all animation classes if stopped.
759             if (do_shutdown_animation) {
760                 service->Start();
761             }
762             service->SetShutdownCritical();  // will not check animation class separately
763         }
764 
765         if (do_shutdown_animation) {
766             boot_anim->Start();
767             surface_flinger->SetShutdownCritical();
768             boot_anim->SetShutdownCritical();
769         }
770     }
771 
772     // optional shutdown step
773     // 1. terminate all services except shutdown critical ones. wait for delay to finish
774     if (shutdown_timeout > 0ms) {
775         StopServicesAndLogViolations(stop_first, shutdown_timeout / 2, true /* SIGTERM */);
776     }
777     // Send SIGKILL to ones that didn't terminate cleanly.
778     StopServicesAndLogViolations(stop_first, 0ms, false /* SIGKILL */);
779     SubcontextTerminate();
780     // Reap subcontext pids.
781     ReapAnyOutstandingChildren();
782 
783     // 3. send volume abort_fuse and volume shutdown to vold
784     Service* vold_service = ServiceList::GetInstance().FindService("vold");
785     if (vold_service != nullptr && vold_service->IsRunning()) {
786         // Manually abort FUSE connections, since the FUSE daemon is already dead
787         // at this point, and unmounting it might hang.
788         CallVdc("volume", "abort_fuse");
789         CallVdc("volume", "shutdown");
790         vold_service->Stop();
791     } else {
792         LOG(INFO) << "vold not running, skipping vold shutdown";
793     }
794     // logcat stopped here
795     StopServices(kDebuggingServices, 0ms, false /* SIGKILL */);
796     // 4. sync, try umount, and optionally run fsck for user shutdown
797     {
798         Timer sync_timer;
799         LOG(INFO) << "sync() before umount...";
800         sync();
801         LOG(INFO) << "sync() before umount took" << sync_timer;
802     }
803     // 5. drop caches and disable zram backing device, if exist
804     KillZramBackingDevice();
805 
806     LOG(INFO) << "Ready to unmount apexes. So far shutdown sequence took " << t;
807     // 6. unmount active apexes, otherwise they might prevent clean unmount of /data.
808     if (auto ret = UnmountAllApexes(); !ret.ok()) {
809         LOG(ERROR) << ret.error();
810     }
811     UmountStat stat =
812             TryUmountAndFsck(cmd, run_fsck, shutdown_timeout - t.duration(), &reboot_semaphore);
813     // Follow what linux shutdown is doing: one more sync with little bit delay
814     {
815         Timer sync_timer;
816         LOG(INFO) << "sync() after umount...";
817         sync();
818         LOG(INFO) << "sync() after umount took" << sync_timer;
819     }
820     if (!is_thermal_shutdown) std::this_thread::sleep_for(100ms);
821     LogShutdownTime(stat, &t);
822 
823     // Send signal to terminate reboot monitor thread.
824     reboot_monitor_run = false;
825     sem_post(&reboot_semaphore);
826 
827     // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
828     if (IsDataMounted("f2fs")) {
829         uint32_t flag = F2FS_GOING_DOWN_FULLSYNC;
830         unique_fd fd(TEMP_FAILURE_RETRY(open("/data", O_RDONLY)));
831         LOG(INFO) << "Invoking F2FS_IOC_SHUTDOWN during shutdown";
832         int ret = ioctl(fd.get(), F2FS_IOC_SHUTDOWN, &flag);
833         if (ret) {
834             PLOG(ERROR) << "Shutdown /data: ";
835         } else {
836             LOG(INFO) << "Shutdown /data";
837         }
838     }
839     RebootSystem(cmd, reboot_target, reason);
840     abort();
841 }
842 
EnterShutdown()843 static void EnterShutdown() {
844     LOG(INFO) << "Entering shutdown mode";
845     shutting_down = true;
846     // Skip wait for prop if it is in progress
847     ResetWaitForProp();
848     // Clear EXEC flag if there is one pending
849     for (const auto& s : ServiceList::GetInstance()) {
850         s->UnSetExec();
851     }
852 }
853 
854 /**
855  * Check if "command" field is set in bootloader message.
856  *
857  * If "command" field is broken (contains non-printable characters prior to
858  * terminating zero), it will be zeroed.
859  *
860  * @param[in,out] boot Bootloader message (BCB) structure
861  * @return true if "command" field is already set, and false if it's empty
862  */
CommandIsPresent(bootloader_message * boot)863 static bool CommandIsPresent(bootloader_message* boot) {
864     if (boot->command[0] == '\0')
865         return false;
866 
867     for (size_t i = 0; i < arraysize(boot->command); ++i) {
868         if (boot->command[i] == '\0')
869             return true;
870         if (!isprint(boot->command[i]))
871             break;
872     }
873 
874     memset(boot->command, 0, sizeof(boot->command));
875     return false;
876 }
877 
HandlePowerctlMessage(const std::string & command)878 void HandlePowerctlMessage(const std::string& command) {
879     unsigned int cmd = 0;
880     std::vector<std::string> cmd_params = Split(command, ",");
881     std::string reboot_target = "";
882     bool run_fsck = false;
883     bool command_invalid = false;
884 
885     if (cmd_params[0] == "shutdown") {
886         cmd = ANDROID_RB_POWEROFF;
887         if (cmd_params.size() >= 2) {
888             if (cmd_params[1] == "userrequested") {
889                 // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
890                 // Run fsck once the file system is remounted in read-only mode.
891                 run_fsck = true;
892             } else if (cmd_params[1] == "thermal") {
893                 // Turn off sources of heat immediately.
894                 TurnOffBacklight();
895                 // run_fsck is false to avoid delay
896                 cmd = ANDROID_RB_THERMOFF;
897             }
898         }
899     } else if (cmd_params[0] == "reboot") {
900         cmd = ANDROID_RB_RESTART2;
901         if (cmd_params.size() >= 2) {
902             reboot_target = cmd_params[1];
903             if (reboot_target == "userspace") {
904                 LOG(ERROR) << "Userspace reboot is deprecated.";
905                 return;
906             }
907             // adb reboot fastboot should boot into bootloader for devices not
908             // supporting logical partitions.
909             if (reboot_target == "fastboot" &&
910                 !android::base::GetBoolProperty("ro.boot.dynamic_partitions", false)) {
911                 reboot_target = "bootloader";
912             }
913             // When rebooting to the bootloader notify the bootloader writing
914             // also the BCB.
915             if (reboot_target == "bootloader") {
916                 std::string err;
917                 if (!write_reboot_bootloader(&err)) {
918                     LOG(ERROR) << "reboot-bootloader: Error writing "
919                                   "bootloader_message: "
920                                << err;
921                 }
922             } else if (reboot_target == "recovery") {
923                 bootloader_message boot = {};
924                 if (std::string err; !read_bootloader_message(&boot, &err)) {
925                     LOG(ERROR) << "Failed to read bootloader message: " << err;
926                 }
927                 // Update the boot command field if it's empty, and preserve
928                 // the other arguments in the bootloader message.
929                 if (!CommandIsPresent(&boot)) {
930                     strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
931                     if (std::string err; !write_bootloader_message(boot, &err)) {
932                         LOG(ERROR) << "Failed to set bootloader message: " << err;
933                         return;
934                     }
935                 }
936             } else if (std::find(cmd_params.begin(), cmd_params.end(), "quiescent")
937                     != cmd_params.end()) { // Quiescent can be either subreason or details.
938                 bootloader_message boot = {};
939                 if (std::string err; !read_bootloader_message(&boot, &err)) {
940                     LOG(ERROR) << "Failed to read bootloader message: " << err;
941                 }
942                 // Update the boot command field if it's empty, and preserve
943                 // the other arguments in the bootloader message.
944                 if (!CommandIsPresent(&boot)) {
945                     strlcpy(boot.command, "boot-quiescent", sizeof(boot.command));
946                     if (std::string err; !write_bootloader_message(boot, &err)) {
947                         LOG(ERROR) << "Failed to set bootloader message: " << err;
948                         return;
949                     }
950                 }
951             } else if (reboot_target == "sideload" || reboot_target == "sideload-auto-reboot" ||
952                        reboot_target == "fastboot") {
953                 std::string arg = reboot_target == "sideload-auto-reboot" ? "sideload_auto_reboot"
954                                                                           : reboot_target;
955                 const std::vector<std::string> options = {
956                         "--" + arg,
957                 };
958                 std::string err;
959                 if (!write_bootloader_message(options, &err)) {
960                     LOG(ERROR) << "Failed to set bootloader message: " << err;
961                     return;
962                 }
963                 reboot_target = "recovery";
964             }
965 
966             // If there are additional parameter, pass them along
967             for (size_t i = 2; (cmd_params.size() > i) && cmd_params[i].size(); ++i) {
968                 reboot_target += "," + cmd_params[i];
969             }
970         }
971     } else {
972         command_invalid = true;
973     }
974     if (command_invalid) {
975         LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
976         return;
977     }
978 
979     // We do not want to process any messages (queue'ing triggers, shutdown messages, control
980     // messages, etc) from properties during reboot.
981     StopSendingMessages();
982 
983     LOG(INFO) << "Clear action queue and start shutdown trigger";
984     ActionManager::GetInstance().ClearQueue();
985     // Queue shutdown trigger first
986     ActionManager::GetInstance().QueueEventTrigger("shutdown");
987     // Queue built-in shutdown_done
988     auto shutdown_handler = [cmd, command, reboot_target, run_fsck](const BuiltinArguments&) {
989         DoReboot(cmd, command, reboot_target, run_fsck);
990         return Result<void>{};
991     };
992     ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
993 
994     EnterShutdown();
995 }
996 
IsShuttingDown()997 bool IsShuttingDown() {
998     return shutting_down;
999 }
1000 
1001 }  // namespace init
1002 }  // namespace android
1003