blob: 331255b1e767a0e7a28345e8677bcc2ac93255d5 [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
Tom Cherry71dd7062020-12-11 09:26:55 -080019#include <android/api-level.h>
Colin Cross44b65d02010-04-20 14:32:50 -070020#include <ctype.h>
Bongkyu Kim5aa61972019-01-30 19:59:53 +090021#include <dirent.h>
Elliott Hughesda40c002015-03-27 23:20:44 -070022#include <fcntl.h>
Brian Swetland8d48c8e2011-03-24 15:45:30 -070023#include <signal.h>
Elliott Hughesda40c002015-03-27 23:20:44 -070024#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
Bongkyu Kim5aa61972019-01-30 19:59:53 +090027#include <sys/stat.h>
Tom Cherryc5833052017-05-16 15:35:41 -070028#include <sys/wait.h>
Bongkyu Kim5aa61972019-01-30 19:59:53 +090029#include <unistd.h>
Tom Cherryc5833052017-05-16 15:35:41 -070030
31#include <set>
32#include <thread>
Brian Swetland8d48c8e2011-03-24 15:45:30 -070033
Tom Cherryede0d532017-07-06 14:20:11 -070034#include <android-base/chrono_utils.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070035#include <android-base/logging.h>
Tom Cherryccf23532017-03-28 16:40:41 -070036#include <android-base/properties.h>
Bowgo Tsai8eec38f2018-05-16 18:33:44 +080037#include <fstab/fstab.h>
Tom Cherryc5833052017-05-16 15:35:41 -070038#include <selinux/android.h>
Elliott Hughesda40c002015-03-27 23:20:44 -070039#include <selinux/selinux.h>
Colin Crossf83d0b92010-04-21 12:04:20 -070040
Colin Crossf83d0b92010-04-21 12:04:20 -070041#include "devices.h"
Tom Cherryed506f72017-05-25 15:58:59 -070042#include "firmware_handler.h"
Andrew F. Davis99638472018-07-09 13:12:00 -050043#include "modalias_handler.h"
Vic Yang92c236e2019-05-28 15:58:35 -070044#include "selabel.h"
Tom Cherryc3692b32017-08-10 12:22:44 -070045#include "selinux.h"
Tom Cherry457e28f2018-08-01 13:12:20 -070046#include "uevent_handler.h"
Tom Cherryed506f72017-05-25 15:58:59 -070047#include "uevent_listener.h"
48#include "ueventd_parser.h"
Tom Cherry3f5eaae52017-04-06 16:30:22 -070049#include "util.h"
Vladimir Chtchetkine2b995432011-09-28 09:55:31 -070050
Tom Cherryc5833052017-05-16 15:35:41 -070051// At a high level, ueventd listens for uevent messages generated by the kernel through a netlink
52// socket. When ueventd receives such a message it handles it by taking appropriate actions,
53// which can typically be creating a device node in /dev, setting file permissions, setting selinux
54// labels, etc.
55// Ueventd also handles loading of firmware that the kernel requests, and creates symlinks for block
56// and character devices.
57
58// When ueventd starts, it regenerates uevents for all currently registered devices by traversing
59// /sys and writing 'add' to each 'uevent' file that it finds. This causes the kernel to generate
60// and resend uevent messages for all of the currently registered devices. This is done, because
61// ueventd would not have been running when these devices were registered and therefore was unable
62// to receive their uevent messages and handle them appropriately. This process is known as
63// 'cold boot'.
64
65// 'init' currently waits synchronously on the cold boot process of ueventd before it continues
66// its boot process. For this reason, cold boot should be as quick as possible. One way to achieve
67// a speed up here is to parallelize the handling of ueventd messages, which consume the bulk of the
68// time during cold boot.
69
70// Handling of uevent messages has two unique properties:
71// 1) It can be done in isolation; it doesn't need to read or write any status once it is started.
72// 2) It uses setegid() and setfscreatecon() so either care (aka locking) must be taken to ensure
73// that no file system operations are done while the uevent process has an abnormal egid or
74// fscreatecon or this handling must happen in a separate process.
75// Given the above two properties, it is best to fork() subprocesses to handle the uevents. This
76// reduces the overhead and complexity that would be required in a solution with threads and locks.
77// In testing, a racy multithreaded solution has the same performance as the fork() solution, so
78// there is no reason to deal with the complexity of the former.
79
80// One other important caveat during the boot process is the handling of SELinux restorecon.
81// Since many devices have child devices, calling selinux_android_restorecon() recursively for each
82// device when its uevent is handled, results in multiple restorecon operations being done on a
83// given file. It is more efficient to simply do restorecon recursively on /sys during cold boot,
84// than to do restorecon on each device as its uevent is handled. This only applies to cold boot;
85// once that has completed, restorecon is done for each device as its uevent is handled.
86
87// With all of the above considered, the cold boot process has the below steps:
88// 1) ueventd regenerates uevents by doing the /sys traversal and listens to the netlink socket for
89// the generated uevents. It writes these uevents into a queue represented by a vector.
90//
91// 2) ueventd forks 'n' separate uevent handler subprocesses and has each of them to handle the
92// uevents in the queue based on a starting offset (their process number) and a stride (the total
93// number of processes). Note that no IPC happens at this point and only const functions from
94// DeviceHandler should be called from this context.
95//
96// 3) In parallel to the subprocesses handling the uevents, the main thread of ueventd calls
97// selinux_android_restorecon() recursively on /sys/class, /sys/block, and /sys/devices.
98//
99// 4) Once the restorecon operation finishes, the main thread calls waitpid() to wait for all
100// subprocess handlers to complete and exit. Once this happens, it marks coldboot as having
101// completed.
102//
103// At this point, ueventd is single threaded, poll()'s and then handles any future uevents.
104
105// Lastly, it should be noted that uevents that occur during the coldboot process are handled
106// without issue after the coldboot process completes. This is because the uevent listener is
107// paused while the uevent handler and restorecon actions take place. Once coldboot completes,
108// the uevent listener resumes in polling mode and will handle the uevents that occurred during
109// coldboot.
110
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700111namespace android {
112namespace init {
113
Tom Cherryc5833052017-05-16 15:35:41 -0700114class ColdBoot {
115 public:
Tom Cherry457e28f2018-08-01 13:12:20 -0700116 ColdBoot(UeventListener& uevent_listener,
Tom Cherry4233ec72019-09-06 10:52:31 -0700117 std::vector<std::unique_ptr<UeventHandler>>& uevent_handlers,
118 bool enable_parallel_restorecon)
Tom Cherryc5833052017-05-16 15:35:41 -0700119 : uevent_listener_(uevent_listener),
Tom Cherry457e28f2018-08-01 13:12:20 -0700120 uevent_handlers_(uevent_handlers),
Tom Cherry4233ec72019-09-06 10:52:31 -0700121 num_handler_subprocesses_(std::thread::hardware_concurrency() ?: 4),
122 enable_parallel_restorecon_(enable_parallel_restorecon) {}
Tom Cherryc5833052017-05-16 15:35:41 -0700123
124 void Run();
125
126 private:
127 void UeventHandlerMain(unsigned int process_num, unsigned int total_processes);
128 void RegenerateUevents();
129 void ForkSubProcesses();
Tom Cherryc5833052017-05-16 15:35:41 -0700130 void WaitForSubProcesses();
Bongkyu Kim5aa61972019-01-30 19:59:53 +0900131 void RestoreConHandler(unsigned int process_num, unsigned int total_processes);
132 void GenerateRestoreCon(const std::string& directory);
Tom Cherryc5833052017-05-16 15:35:41 -0700133
134 UeventListener& uevent_listener_;
Tom Cherry457e28f2018-08-01 13:12:20 -0700135 std::vector<std::unique_ptr<UeventHandler>>& uevent_handlers_;
Tom Cherryc5833052017-05-16 15:35:41 -0700136
137 unsigned int num_handler_subprocesses_;
Tom Cherry4233ec72019-09-06 10:52:31 -0700138 bool enable_parallel_restorecon_;
139
Tom Cherryc5833052017-05-16 15:35:41 -0700140 std::vector<Uevent> uevent_queue_;
141
142 std::set<pid_t> subprocess_pids_;
Bongkyu Kim5aa61972019-01-30 19:59:53 +0900143
144 std::vector<std::string> restorecon_queue_;
Tom Cherryc5833052017-05-16 15:35:41 -0700145};
146
147void ColdBoot::UeventHandlerMain(unsigned int process_num, unsigned int total_processes) {
148 for (unsigned int i = process_num; i < uevent_queue_.size(); i += total_processes) {
149 auto& uevent = uevent_queue_[i];
Tom Cherry457e28f2018-08-01 13:12:20 -0700150
151 for (auto& uevent_handler : uevent_handlers_) {
152 uevent_handler->HandleUevent(uevent);
153 }
Tom Cherryc5833052017-05-16 15:35:41 -0700154 }
Bongkyu Kim5aa61972019-01-30 19:59:53 +0900155}
156
157void ColdBoot::RestoreConHandler(unsigned int process_num, unsigned int total_processes) {
158 for (unsigned int i = process_num; i < restorecon_queue_.size(); i += total_processes) {
159 auto& dir = restorecon_queue_[i];
160
161 selinux_android_restorecon(dir.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE);
162 }
Tom Cherryc5833052017-05-16 15:35:41 -0700163}
164
Bongkyu Kim5aa61972019-01-30 19:59:53 +0900165void ColdBoot::GenerateRestoreCon(const std::string& directory) {
166 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(directory.c_str()), &closedir);
167
168 if (!dir) return;
169
170 struct dirent* dent;
171 while ((dent = readdir(dir.get())) != NULL) {
172 if (strcmp(dent->d_name, ".") == 0 || strcmp(dent->d_name, "..") == 0) continue;
173
174 struct stat st;
175 if (fstatat(dirfd(dir.get()), dent->d_name, &st, 0) == -1) continue;
176
177 if (S_ISDIR(st.st_mode)) {
178 std::string fullpath = directory + "/" + dent->d_name;
179 if (fullpath != "/sys/devices") {
180 restorecon_queue_.emplace_back(fullpath);
181 }
182 }
183 }
184}
185
Tom Cherryc5833052017-05-16 15:35:41 -0700186void ColdBoot::RegenerateUevents() {
187 uevent_listener_.RegenerateUevents([this](const Uevent& uevent) {
Tom Cherry7c1d87e2019-07-10 11:18:24 -0700188 uevent_queue_.emplace_back(uevent);
Sandeep Patil4cbedee2017-06-21 13:02:57 -0700189 return ListenerAction::kContinue;
Tom Cherryc5833052017-05-16 15:35:41 -0700190 });
191}
192
193void ColdBoot::ForkSubProcesses() {
194 for (unsigned int i = 0; i < num_handler_subprocesses_; ++i) {
195 auto pid = fork();
196 if (pid < 0) {
197 PLOG(FATAL) << "fork() failed!";
198 }
199
200 if (pid == 0) {
201 UeventHandlerMain(i, num_handler_subprocesses_);
Tom Cherry4233ec72019-09-06 10:52:31 -0700202 if (enable_parallel_restorecon_) {
203 RestoreConHandler(i, num_handler_subprocesses_);
204 }
205 _exit(EXIT_SUCCESS);
Tom Cherryc5833052017-05-16 15:35:41 -0700206 }
207
208 subprocess_pids_.emplace(pid);
209 }
210}
211
Tom Cherryc5833052017-05-16 15:35:41 -0700212void ColdBoot::WaitForSubProcesses() {
213 // Treat subprocesses that crash or get stuck the same as if ueventd itself has crashed or gets
214 // stuck.
215 //
216 // When a subprocess crashes, we fatally abort from ueventd. init will restart ueventd when
217 // init reaps it, and the cold boot process will start again. If this continues to fail, then
Tom Cherryad9e7ea2018-10-15 17:21:48 -0700218 // since ueventd is marked as a critical service, init will reboot to bootloader.
Tom Cherryc5833052017-05-16 15:35:41 -0700219 //
220 // When a subprocess gets stuck, keep ueventd spinning waiting for it. init has a timeout for
221 // cold boot and will reboot to the bootloader if ueventd does not complete in time.
222 while (!subprocess_pids_.empty()) {
223 int status;
224 pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, 0));
225 if (pid == -1) {
226 PLOG(ERROR) << "waitpid() failed";
227 continue;
228 }
229
230 auto it = std::find(subprocess_pids_.begin(), subprocess_pids_.end(), pid);
231 if (it == subprocess_pids_.end()) continue;
232
233 if (WIFEXITED(status)) {
234 if (WEXITSTATUS(status) == EXIT_SUCCESS) {
235 subprocess_pids_.erase(it);
236 } else {
237 LOG(FATAL) << "subprocess exited with status " << WEXITSTATUS(status);
238 }
239 } else if (WIFSIGNALED(status)) {
240 LOG(FATAL) << "subprocess killed by signal " << WTERMSIG(status);
241 }
242 }
243}
244
245void ColdBoot::Run() {
Tom Cherryede0d532017-07-06 14:20:11 -0700246 android::base::Timer cold_boot_timer;
Tom Cherryc5833052017-05-16 15:35:41 -0700247
248 RegenerateUevents();
249
Tom Cherry4233ec72019-09-06 10:52:31 -0700250 if (enable_parallel_restorecon_) {
251 selinux_android_restorecon("/sys", 0);
252 selinux_android_restorecon("/sys/devices", 0);
253 GenerateRestoreCon("/sys");
254 // takes long time for /sys/devices, parallelize it
255 GenerateRestoreCon("/sys/devices");
256 }
Tom Cherryc5833052017-05-16 15:35:41 -0700257
Bongkyu Kim5aa61972019-01-30 19:59:53 +0900258 ForkSubProcesses();
Tom Cherryc5833052017-05-16 15:35:41 -0700259
Tom Cherry4233ec72019-09-06 10:52:31 -0700260 if (!enable_parallel_restorecon_) {
261 selinux_android_restorecon("/sys", SELINUX_ANDROID_RESTORECON_RECURSE);
262 }
263
Tom Cherryc5833052017-05-16 15:35:41 -0700264 WaitForSubProcesses();
265
Tom Cherry39fafed2019-06-10 17:49:59 -0700266 android::base::SetProperty(kColdBootDoneProp, "true");
Tom Cherryede0d532017-07-06 14:20:11 -0700267 LOG(INFO) << "Coldboot took " << cold_boot_timer.duration().count() / 1000.0f << " seconds";
Tom Cherryc5833052017-05-16 15:35:41 -0700268}
269
Tom Cherry71dd7062020-12-11 09:26:55 -0800270static UeventdConfiguration GetConfiguration() {
271 // TODO: Remove these legacy paths once Android S is no longer supported.
272 if (android::base::GetIntProperty("ro.product.first_api_level", 10000) <= __ANDROID_API_S__) {
273 auto hardware = android::base::GetProperty("ro.hardware", "");
274 return ParseConfig({"/system/etc/ueventd.rc", "/vendor/ueventd.rc", "/odm/ueventd.rc",
275 "/ueventd." + hardware + ".rc"});
276 }
277
278 return ParseConfig({"/system/etc/ueventd.rc"});
279}
280
Tom Cherryc5833052017-05-16 15:35:41 -0700281int ueventd_main(int argc, char** argv) {
Nick Kralevich6ebf12f2012-03-26 09:09:11 -0700282 /*
283 * init sets the umask to 077 for forked processes. We need to
284 * create files with exact permissions, without modification by
285 * the umask.
286 */
287 umask(000);
288
Tom Cherry74069d12018-07-20 15:26:25 -0700289 android::base::InitLogging(argv, &android::base::KernelLogger);
Colin Crossf83d0b92010-04-21 12:04:20 -0700290
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700291 LOG(INFO) << "ueventd started!";
Elliott Hughesda40c002015-03-27 23:20:44 -0700292
Tom Cherryc3692b32017-08-10 12:22:44 -0700293 SelinuxSetupKernelLogging();
294 SelabelInitialize();
Stephen Smalley439224e2014-06-24 13:45:43 -0400295
Tom Cherry457e28f2018-08-01 13:12:20 -0700296 std::vector<std::unique_ptr<UeventHandler>> uevent_handlers;
Sandeep Patilbf298e62017-02-03 07:18:36 -0800297
Tom Cherry71dd7062020-12-11 09:26:55 -0800298 auto ueventd_configuration = GetConfiguration();
Tom Cherry7421fa12018-07-13 15:32:02 -0700299
Tom Cherrye2910102018-12-06 13:29:30 -0800300 uevent_handlers.emplace_back(std::make_unique<DeviceHandler>(
301 std::move(ueventd_configuration.dev_permissions),
302 std::move(ueventd_configuration.sysfs_permissions),
Tom Cherrya3530e62019-01-30 13:25:35 -0800303 std::move(ueventd_configuration.subsystems), android::fs_mgr::GetBootDevices(), true));
Tom Cherrye2910102018-12-06 13:29:30 -0800304 uevent_handlers.emplace_back(std::make_unique<FirmwareHandler>(
Tom Cherrydcb3d152019-08-07 16:02:28 -0700305 std::move(ueventd_configuration.firmware_directories),
306 std::move(ueventd_configuration.external_firmware_handlers)));
Tom Cherry7421fa12018-07-13 15:32:02 -0700307
Tom Cherrye2910102018-12-06 13:29:30 -0800308 if (ueventd_configuration.enable_modalias_handling) {
Steve Muckle18b981e2019-04-15 17:43:02 -0700309 std::vector<std::string> base_paths = {"/odm/lib/modules", "/vendor/lib/modules"};
310 uevent_handlers.emplace_back(std::make_unique<ModaliasHandler>(base_paths));
Tom Cherry7421fa12018-07-13 15:32:02 -0700311 }
Tom Cherrye2910102018-12-06 13:29:30 -0800312 UeventListener uevent_listener(ueventd_configuration.uevent_socket_rcvbuf_size);
Tom Cherry7421fa12018-07-13 15:32:02 -0700313
Tom Cherry39fafed2019-06-10 17:49:59 -0700314 if (!android::base::GetBoolProperty(kColdBootDoneProp, false)) {
Tom Cherry4233ec72019-09-06 10:52:31 -0700315 ColdBoot cold_boot(uevent_listener, uevent_handlers,
316 ueventd_configuration.enable_parallel_restorecon);
Tom Cherryc5833052017-05-16 15:35:41 -0700317 cold_boot.Run();
Colin Crossf83d0b92010-04-21 12:04:20 -0700318 }
Elliott Hughes21457792015-02-04 10:19:50 -0800319
Tom Cherry457e28f2018-08-01 13:12:20 -0700320 for (auto& uevent_handler : uevent_handlers) {
321 uevent_handler->ColdbootDone();
322 }
323
Tom Cherry0f296e02017-06-30 12:58:39 -0700324 // We use waitpid() in ColdBoot, so we can't ignore SIGCHLD until now.
325 signal(SIGCHLD, SIG_IGN);
326 // Reap and pending children that exited between the last call to waitpid() and setting SIG_IGN
327 // for SIGCHLD above.
328 while (waitpid(-1, nullptr, WNOHANG) > 0) {
329 }
330
Wei Wang30bbf7d2020-07-06 15:26:49 -0700331 // Restore prio before main loop
332 setpriority(PRIO_PROCESS, 0, 0);
Tom Cherry457e28f2018-08-01 13:12:20 -0700333 uevent_listener.Poll([&uevent_handlers](const Uevent& uevent) {
334 for (auto& uevent_handler : uevent_handlers) {
335 uevent_handler->HandleUevent(uevent);
336 }
Sandeep Patil4cbedee2017-06-21 13:02:57 -0700337 return ListenerAction::kContinue;
Tom Cherryed506f72017-05-25 15:58:59 -0700338 });
339
Elliott Hughes21457792015-02-04 10:19:50 -0800340 return 0;
Colin Crossf83d0b92010-04-21 12:04:20 -0700341}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700342
343} // namespace init
344} // namespace android