blob: d700c461c5278c84f7e3d7c6933286410886f022 [file] [log] [blame]
Colin Crossf83d0b92010-04-21 12:04:20 -07001/*
2 * Copyright (C) 2010 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
Tom Cherry3f5eaae52017-04-06 16:30:22 -070017#include "ueventd.h"
18
Colin Cross44b65d02010-04-20 14:32:50 -070019#include <ctype.h>
Elliott Hughesda40c002015-03-27 23:20:44 -070020#include <fcntl.h>
Brian Swetland8d48c8e2011-03-24 15:45:30 -070021#include <signal.h>
Elliott Hughesda40c002015-03-27 23:20:44 -070022#include <stdio.h>
23#include <stdlib.h>
24#include <string.h>
Tom Cherryc5833052017-05-16 15:35:41 -070025#include <sys/wait.h>
26
27#include <set>
28#include <thread>
Brian Swetland8d48c8e2011-03-24 15:45:30 -070029
Tom Cherryede0d532017-07-06 14:20:11 -070030#include <android-base/chrono_utils.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070031#include <android-base/logging.h>
Tom Cherryccf23532017-03-28 16:40:41 -070032#include <android-base/properties.h>
Bowgo Tsai8eec38f2018-05-16 18:33:44 +080033#include <fstab/fstab.h>
Tom Cherryc5833052017-05-16 15:35:41 -070034#include <selinux/android.h>
Elliott Hughesda40c002015-03-27 23:20:44 -070035#include <selinux/selinux.h>
Colin Crossf83d0b92010-04-21 12:04:20 -070036
Colin Crossf83d0b92010-04-21 12:04:20 -070037#include "devices.h"
Tom Cherryed506f72017-05-25 15:58:59 -070038#include "firmware_handler.h"
Andrew F. Davis99638472018-07-09 13:12:00 -050039#include "modalias_handler.h"
Vic Yang92c236e2019-05-28 15:58:35 -070040#include "selabel.h"
Tom Cherryc3692b32017-08-10 12:22:44 -070041#include "selinux.h"
Tom Cherry457e28f2018-08-01 13:12:20 -070042#include "uevent_handler.h"
Tom Cherryed506f72017-05-25 15:58:59 -070043#include "uevent_listener.h"
44#include "ueventd_parser.h"
Tom Cherry3f5eaae52017-04-06 16:30:22 -070045#include "util.h"
Vladimir Chtchetkine2b995432011-09-28 09:55:31 -070046
Tom Cherryc5833052017-05-16 15:35:41 -070047// At a high level, ueventd listens for uevent messages generated by the kernel through a netlink
48// socket. When ueventd receives such a message it handles it by taking appropriate actions,
49// which can typically be creating a device node in /dev, setting file permissions, setting selinux
50// labels, etc.
51// Ueventd also handles loading of firmware that the kernel requests, and creates symlinks for block
52// and character devices.
53
54// When ueventd starts, it regenerates uevents for all currently registered devices by traversing
55// /sys and writing 'add' to each 'uevent' file that it finds. This causes the kernel to generate
56// and resend uevent messages for all of the currently registered devices. This is done, because
57// ueventd would not have been running when these devices were registered and therefore was unable
58// to receive their uevent messages and handle them appropriately. This process is known as
59// 'cold boot'.
60
61// 'init' currently waits synchronously on the cold boot process of ueventd before it continues
62// its boot process. For this reason, cold boot should be as quick as possible. One way to achieve
63// a speed up here is to parallelize the handling of ueventd messages, which consume the bulk of the
64// time during cold boot.
65
66// Handling of uevent messages has two unique properties:
67// 1) It can be done in isolation; it doesn't need to read or write any status once it is started.
68// 2) It uses setegid() and setfscreatecon() so either care (aka locking) must be taken to ensure
69// that no file system operations are done while the uevent process has an abnormal egid or
70// fscreatecon or this handling must happen in a separate process.
71// Given the above two properties, it is best to fork() subprocesses to handle the uevents. This
72// reduces the overhead and complexity that would be required in a solution with threads and locks.
73// In testing, a racy multithreaded solution has the same performance as the fork() solution, so
74// there is no reason to deal with the complexity of the former.
75
76// One other important caveat during the boot process is the handling of SELinux restorecon.
77// Since many devices have child devices, calling selinux_android_restorecon() recursively for each
78// device when its uevent is handled, results in multiple restorecon operations being done on a
79// given file. It is more efficient to simply do restorecon recursively on /sys during cold boot,
80// than to do restorecon on each device as its uevent is handled. This only applies to cold boot;
81// once that has completed, restorecon is done for each device as its uevent is handled.
82
83// With all of the above considered, the cold boot process has the below steps:
84// 1) ueventd regenerates uevents by doing the /sys traversal and listens to the netlink socket for
85// the generated uevents. It writes these uevents into a queue represented by a vector.
86//
87// 2) ueventd forks 'n' separate uevent handler subprocesses and has each of them to handle the
88// uevents in the queue based on a starting offset (their process number) and a stride (the total
89// number of processes). Note that no IPC happens at this point and only const functions from
90// DeviceHandler should be called from this context.
91//
92// 3) In parallel to the subprocesses handling the uevents, the main thread of ueventd calls
93// selinux_android_restorecon() recursively on /sys/class, /sys/block, and /sys/devices.
94//
95// 4) Once the restorecon operation finishes, the main thread calls waitpid() to wait for all
96// subprocess handlers to complete and exit. Once this happens, it marks coldboot as having
97// completed.
98//
99// At this point, ueventd is single threaded, poll()'s and then handles any future uevents.
100
101// Lastly, it should be noted that uevents that occur during the coldboot process are handled
102// without issue after the coldboot process completes. This is because the uevent listener is
103// paused while the uevent handler and restorecon actions take place. Once coldboot completes,
104// the uevent listener resumes in polling mode and will handle the uevents that occurred during
105// coldboot.
106
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700107namespace android {
108namespace init {
109
Tom Cherryc5833052017-05-16 15:35:41 -0700110class ColdBoot {
111 public:
Tom Cherry457e28f2018-08-01 13:12:20 -0700112 ColdBoot(UeventListener& uevent_listener,
113 std::vector<std::unique_ptr<UeventHandler>>& uevent_handlers)
Tom Cherryc5833052017-05-16 15:35:41 -0700114 : uevent_listener_(uevent_listener),
Tom Cherry457e28f2018-08-01 13:12:20 -0700115 uevent_handlers_(uevent_handlers),
Tom Cherryc5833052017-05-16 15:35:41 -0700116 num_handler_subprocesses_(std::thread::hardware_concurrency() ?: 4) {}
117
118 void Run();
119
120 private:
121 void UeventHandlerMain(unsigned int process_num, unsigned int total_processes);
122 void RegenerateUevents();
123 void ForkSubProcesses();
124 void DoRestoreCon();
125 void WaitForSubProcesses();
126
127 UeventListener& uevent_listener_;
Tom Cherry457e28f2018-08-01 13:12:20 -0700128 std::vector<std::unique_ptr<UeventHandler>>& uevent_handlers_;
Tom Cherryc5833052017-05-16 15:35:41 -0700129
130 unsigned int num_handler_subprocesses_;
131 std::vector<Uevent> uevent_queue_;
132
133 std::set<pid_t> subprocess_pids_;
134};
135
136void ColdBoot::UeventHandlerMain(unsigned int process_num, unsigned int total_processes) {
137 for (unsigned int i = process_num; i < uevent_queue_.size(); i += total_processes) {
138 auto& uevent = uevent_queue_[i];
Tom Cherry457e28f2018-08-01 13:12:20 -0700139
140 for (auto& uevent_handler : uevent_handlers_) {
141 uevent_handler->HandleUevent(uevent);
142 }
Tom Cherryc5833052017-05-16 15:35:41 -0700143 }
144 _exit(EXIT_SUCCESS);
145}
146
147void ColdBoot::RegenerateUevents() {
148 uevent_listener_.RegenerateUevents([this](const Uevent& uevent) {
Tom Cherryc5833052017-05-16 15:35:41 -0700149 uevent_queue_.emplace_back(std::move(uevent));
Sandeep Patil4cbedee2017-06-21 13:02:57 -0700150 return ListenerAction::kContinue;
Tom Cherryc5833052017-05-16 15:35:41 -0700151 });
152}
153
154void ColdBoot::ForkSubProcesses() {
155 for (unsigned int i = 0; i < num_handler_subprocesses_; ++i) {
156 auto pid = fork();
157 if (pid < 0) {
158 PLOG(FATAL) << "fork() failed!";
159 }
160
161 if (pid == 0) {
162 UeventHandlerMain(i, num_handler_subprocesses_);
163 }
164
165 subprocess_pids_.emplace(pid);
166 }
167}
168
169void ColdBoot::DoRestoreCon() {
Tom Cherryd2fd54e2017-06-07 14:32:30 -0700170 selinux_android_restorecon("/sys", SELINUX_ANDROID_RESTORECON_RECURSE);
Tom Cherryc5833052017-05-16 15:35:41 -0700171}
172
173void ColdBoot::WaitForSubProcesses() {
174 // Treat subprocesses that crash or get stuck the same as if ueventd itself has crashed or gets
175 // stuck.
176 //
177 // When a subprocess crashes, we fatally abort from ueventd. init will restart ueventd when
178 // init reaps it, and the cold boot process will start again. If this continues to fail, then
Tom Cherryad9e7ea2018-10-15 17:21:48 -0700179 // since ueventd is marked as a critical service, init will reboot to bootloader.
Tom Cherryc5833052017-05-16 15:35:41 -0700180 //
181 // When a subprocess gets stuck, keep ueventd spinning waiting for it. init has a timeout for
182 // cold boot and will reboot to the bootloader if ueventd does not complete in time.
183 while (!subprocess_pids_.empty()) {
184 int status;
185 pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, 0));
186 if (pid == -1) {
187 PLOG(ERROR) << "waitpid() failed";
188 continue;
189 }
190
191 auto it = std::find(subprocess_pids_.begin(), subprocess_pids_.end(), pid);
192 if (it == subprocess_pids_.end()) continue;
193
194 if (WIFEXITED(status)) {
195 if (WEXITSTATUS(status) == EXIT_SUCCESS) {
196 subprocess_pids_.erase(it);
197 } else {
198 LOG(FATAL) << "subprocess exited with status " << WEXITSTATUS(status);
199 }
200 } else if (WIFSIGNALED(status)) {
201 LOG(FATAL) << "subprocess killed by signal " << WTERMSIG(status);
202 }
203 }
204}
205
206void ColdBoot::Run() {
Tom Cherryede0d532017-07-06 14:20:11 -0700207 android::base::Timer cold_boot_timer;
Tom Cherryc5833052017-05-16 15:35:41 -0700208
209 RegenerateUevents();
210
211 ForkSubProcesses();
212
213 DoRestoreCon();
214
215 WaitForSubProcesses();
216
217 close(open(COLDBOOT_DONE, O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
Tom Cherryede0d532017-07-06 14:20:11 -0700218 LOG(INFO) << "Coldboot took " << cold_boot_timer.duration().count() / 1000.0f << " seconds";
Tom Cherryc5833052017-05-16 15:35:41 -0700219}
220
Tom Cherryc5833052017-05-16 15:35:41 -0700221int ueventd_main(int argc, char** argv) {
Nick Kralevich6ebf12f2012-03-26 09:09:11 -0700222 /*
223 * init sets the umask to 077 for forked processes. We need to
224 * create files with exact permissions, without modification by
225 * the umask.
226 */
227 umask(000);
228
Tom Cherry74069d12018-07-20 15:26:25 -0700229 android::base::InitLogging(argv, &android::base::KernelLogger);
Colin Crossf83d0b92010-04-21 12:04:20 -0700230
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700231 LOG(INFO) << "ueventd started!";
Elliott Hughesda40c002015-03-27 23:20:44 -0700232
Tom Cherryc3692b32017-08-10 12:22:44 -0700233 SelinuxSetupKernelLogging();
234 SelabelInitialize();
Stephen Smalley439224e2014-06-24 13:45:43 -0400235
Tom Cherry457e28f2018-08-01 13:12:20 -0700236 std::vector<std::unique_ptr<UeventHandler>> uevent_handlers;
Sandeep Patilbf298e62017-02-03 07:18:36 -0800237
Tom Cherrye2910102018-12-06 13:29:30 -0800238 // Keep the current product name base configuration so we remain backwards compatible and
239 // allow it to override everything.
240 // TODO: cleanup platform ueventd.rc to remove vendor specific device node entries (b/34968103)
241 auto hardware = android::base::GetProperty("ro.hardware", "");
Tom Cherry7421fa12018-07-13 15:32:02 -0700242
Tom Cherrye2910102018-12-06 13:29:30 -0800243 auto ueventd_configuration = ParseConfig({"/ueventd.rc", "/vendor/ueventd.rc",
244 "/odm/ueventd.rc", "/ueventd." + hardware + ".rc"});
Tom Cherry7421fa12018-07-13 15:32:02 -0700245
Tom Cherrye2910102018-12-06 13:29:30 -0800246 uevent_handlers.emplace_back(std::make_unique<DeviceHandler>(
247 std::move(ueventd_configuration.dev_permissions),
248 std::move(ueventd_configuration.sysfs_permissions),
Tom Cherrya3530e62019-01-30 13:25:35 -0800249 std::move(ueventd_configuration.subsystems), android::fs_mgr::GetBootDevices(), true));
Tom Cherrye2910102018-12-06 13:29:30 -0800250 uevent_handlers.emplace_back(std::make_unique<FirmwareHandler>(
251 std::move(ueventd_configuration.firmware_directories)));
Tom Cherry7421fa12018-07-13 15:32:02 -0700252
Tom Cherrye2910102018-12-06 13:29:30 -0800253 if (ueventd_configuration.enable_modalias_handling) {
254 uevent_handlers.emplace_back(std::make_unique<ModaliasHandler>());
Tom Cherry7421fa12018-07-13 15:32:02 -0700255 }
Tom Cherrye2910102018-12-06 13:29:30 -0800256 UeventListener uevent_listener(ueventd_configuration.uevent_socket_rcvbuf_size);
Tom Cherry7421fa12018-07-13 15:32:02 -0700257
Tom Cherryed506f72017-05-25 15:58:59 -0700258 if (access(COLDBOOT_DONE, F_OK) != 0) {
Tom Cherry457e28f2018-08-01 13:12:20 -0700259 ColdBoot cold_boot(uevent_listener, uevent_handlers);
Tom Cherryc5833052017-05-16 15:35:41 -0700260 cold_boot.Run();
Colin Crossf83d0b92010-04-21 12:04:20 -0700261 }
Elliott Hughes21457792015-02-04 10:19:50 -0800262
Tom Cherry457e28f2018-08-01 13:12:20 -0700263 for (auto& uevent_handler : uevent_handlers) {
264 uevent_handler->ColdbootDone();
265 }
266
Tom Cherry0f296e02017-06-30 12:58:39 -0700267 // We use waitpid() in ColdBoot, so we can't ignore SIGCHLD until now.
268 signal(SIGCHLD, SIG_IGN);
269 // Reap and pending children that exited between the last call to waitpid() and setting SIG_IGN
270 // for SIGCHLD above.
271 while (waitpid(-1, nullptr, WNOHANG) > 0) {
272 }
273
Tom Cherry457e28f2018-08-01 13:12:20 -0700274 uevent_listener.Poll([&uevent_handlers](const Uevent& uevent) {
275 for (auto& uevent_handler : uevent_handlers) {
276 uevent_handler->HandleUevent(uevent);
277 }
Sandeep Patil4cbedee2017-06-21 13:02:57 -0700278 return ListenerAction::kContinue;
Tom Cherryed506f72017-05-25 15:58:59 -0700279 });
280
Elliott Hughes21457792015-02-04 10:19:50 -0800281 return 0;
Colin Crossf83d0b92010-04-21 12:04:20 -0700282}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700283
284} // namespace init
285} // namespace android