blob: 2fd805873e765ca4cb8cf7c19406f24567953c7c [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 Cherry3f5eaae52017-04-06 16:30:22 -070030#include <android-base/logging.h>
Tom Cherryccf23532017-03-28 16:40:41 -070031#include <android-base/properties.h>
Tom Cherryc5833052017-05-16 15:35:41 -070032#include <selinux/android.h>
Elliott Hughesda40c002015-03-27 23:20:44 -070033#include <selinux/selinux.h>
Colin Crossf83d0b92010-04-21 12:04:20 -070034
Colin Crossf83d0b92010-04-21 12:04:20 -070035#include "devices.h"
Tom Cherryed506f72017-05-25 15:58:59 -070036#include "firmware_handler.h"
Tom Cherry3f5eaae52017-04-06 16:30:22 -070037#include "log.h"
Tom Cherryed506f72017-05-25 15:58:59 -070038#include "uevent_listener.h"
39#include "ueventd_parser.h"
Tom Cherry3f5eaae52017-04-06 16:30:22 -070040#include "util.h"
Vladimir Chtchetkine2b995432011-09-28 09:55:31 -070041
Tom Cherryc5833052017-05-16 15:35:41 -070042// At a high level, ueventd listens for uevent messages generated by the kernel through a netlink
43// socket. When ueventd receives such a message it handles it by taking appropriate actions,
44// which can typically be creating a device node in /dev, setting file permissions, setting selinux
45// labels, etc.
46// Ueventd also handles loading of firmware that the kernel requests, and creates symlinks for block
47// and character devices.
48
49// When ueventd starts, it regenerates uevents for all currently registered devices by traversing
50// /sys and writing 'add' to each 'uevent' file that it finds. This causes the kernel to generate
51// and resend uevent messages for all of the currently registered devices. This is done, because
52// ueventd would not have been running when these devices were registered and therefore was unable
53// to receive their uevent messages and handle them appropriately. This process is known as
54// 'cold boot'.
55
56// 'init' currently waits synchronously on the cold boot process of ueventd before it continues
57// its boot process. For this reason, cold boot should be as quick as possible. One way to achieve
58// a speed up here is to parallelize the handling of ueventd messages, which consume the bulk of the
59// time during cold boot.
60
61// Handling of uevent messages has two unique properties:
62// 1) It can be done in isolation; it doesn't need to read or write any status once it is started.
63// 2) It uses setegid() and setfscreatecon() so either care (aka locking) must be taken to ensure
64// that no file system operations are done while the uevent process has an abnormal egid or
65// fscreatecon or this handling must happen in a separate process.
66// Given the above two properties, it is best to fork() subprocesses to handle the uevents. This
67// reduces the overhead and complexity that would be required in a solution with threads and locks.
68// In testing, a racy multithreaded solution has the same performance as the fork() solution, so
69// there is no reason to deal with the complexity of the former.
70
71// One other important caveat during the boot process is the handling of SELinux restorecon.
72// Since many devices have child devices, calling selinux_android_restorecon() recursively for each
73// device when its uevent is handled, results in multiple restorecon operations being done on a
74// given file. It is more efficient to simply do restorecon recursively on /sys during cold boot,
75// than to do restorecon on each device as its uevent is handled. This only applies to cold boot;
76// once that has completed, restorecon is done for each device as its uevent is handled.
77
78// With all of the above considered, the cold boot process has the below steps:
79// 1) ueventd regenerates uevents by doing the /sys traversal and listens to the netlink socket for
80// the generated uevents. It writes these uevents into a queue represented by a vector.
81//
82// 2) ueventd forks 'n' separate uevent handler subprocesses and has each of them to handle the
83// uevents in the queue based on a starting offset (their process number) and a stride (the total
84// number of processes). Note that no IPC happens at this point and only const functions from
85// DeviceHandler should be called from this context.
86//
87// 3) In parallel to the subprocesses handling the uevents, the main thread of ueventd calls
88// selinux_android_restorecon() recursively on /sys/class, /sys/block, and /sys/devices.
89//
90// 4) Once the restorecon operation finishes, the main thread calls waitpid() to wait for all
91// subprocess handlers to complete and exit. Once this happens, it marks coldboot as having
92// completed.
93//
94// At this point, ueventd is single threaded, poll()'s and then handles any future uevents.
95
96// Lastly, it should be noted that uevents that occur during the coldboot process are handled
97// without issue after the coldboot process completes. This is because the uevent listener is
98// paused while the uevent handler and restorecon actions take place. Once coldboot completes,
99// the uevent listener resumes in polling mode and will handle the uevents that occurred during
100// coldboot.
101
102class ColdBoot {
103 public:
104 ColdBoot(UeventListener& uevent_listener, DeviceHandler& device_handler)
105 : uevent_listener_(uevent_listener),
106 device_handler_(device_handler),
107 num_handler_subprocesses_(std::thread::hardware_concurrency() ?: 4) {}
108
109 void Run();
110
111 private:
112 void UeventHandlerMain(unsigned int process_num, unsigned int total_processes);
113 void RegenerateUevents();
114 void ForkSubProcesses();
115 void DoRestoreCon();
116 void WaitForSubProcesses();
117
118 UeventListener& uevent_listener_;
119 DeviceHandler& device_handler_;
120
121 unsigned int num_handler_subprocesses_;
122 std::vector<Uevent> uevent_queue_;
123
124 std::set<pid_t> subprocess_pids_;
125};
126
127void ColdBoot::UeventHandlerMain(unsigned int process_num, unsigned int total_processes) {
128 for (unsigned int i = process_num; i < uevent_queue_.size(); i += total_processes) {
129 auto& uevent = uevent_queue_[i];
Sandeep Patilcd2ba0d2017-06-21 12:46:41 -0700130 device_handler_.HandleDeviceEvent(uevent);
Tom Cherryc5833052017-05-16 15:35:41 -0700131 }
132 _exit(EXIT_SUCCESS);
133}
134
135void ColdBoot::RegenerateUevents() {
136 uevent_listener_.RegenerateUevents([this](const Uevent& uevent) {
137 HandleFirmwareEvent(uevent);
138
Tom Cherryc5833052017-05-16 15:35:41 -0700139 uevent_queue_.emplace_back(std::move(uevent));
Sandeep Patil4cbedee2017-06-21 13:02:57 -0700140 return ListenerAction::kContinue;
Tom Cherryc5833052017-05-16 15:35:41 -0700141 });
142}
143
144void ColdBoot::ForkSubProcesses() {
145 for (unsigned int i = 0; i < num_handler_subprocesses_; ++i) {
146 auto pid = fork();
147 if (pid < 0) {
148 PLOG(FATAL) << "fork() failed!";
149 }
150
151 if (pid == 0) {
152 UeventHandlerMain(i, num_handler_subprocesses_);
153 }
154
155 subprocess_pids_.emplace(pid);
156 }
157}
158
159void ColdBoot::DoRestoreCon() {
Tom Cherryd2fd54e2017-06-07 14:32:30 -0700160 selinux_android_restorecon("/sys", SELINUX_ANDROID_RESTORECON_RECURSE);
Tom Cherryc5833052017-05-16 15:35:41 -0700161 device_handler_.set_skip_restorecon(false);
162}
163
164void ColdBoot::WaitForSubProcesses() {
165 // Treat subprocesses that crash or get stuck the same as if ueventd itself has crashed or gets
166 // stuck.
167 //
168 // When a subprocess crashes, we fatally abort from ueventd. init will restart ueventd when
169 // init reaps it, and the cold boot process will start again. If this continues to fail, then
170 // since ueventd is marked as a critical service, init will reboot to recovery.
171 //
172 // When a subprocess gets stuck, keep ueventd spinning waiting for it. init has a timeout for
173 // cold boot and will reboot to the bootloader if ueventd does not complete in time.
174 while (!subprocess_pids_.empty()) {
175 int status;
176 pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, 0));
177 if (pid == -1) {
178 PLOG(ERROR) << "waitpid() failed";
179 continue;
180 }
181
182 auto it = std::find(subprocess_pids_.begin(), subprocess_pids_.end(), pid);
183 if (it == subprocess_pids_.end()) continue;
184
185 if (WIFEXITED(status)) {
186 if (WEXITSTATUS(status) == EXIT_SUCCESS) {
187 subprocess_pids_.erase(it);
188 } else {
189 LOG(FATAL) << "subprocess exited with status " << WEXITSTATUS(status);
190 }
191 } else if (WIFSIGNALED(status)) {
192 LOG(FATAL) << "subprocess killed by signal " << WTERMSIG(status);
193 }
194 }
195}
196
197void ColdBoot::Run() {
198 Timer cold_boot_timer;
199
200 RegenerateUevents();
201
202 ForkSubProcesses();
203
204 DoRestoreCon();
205
206 WaitForSubProcesses();
207
208 close(open(COLDBOOT_DONE, O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
209 LOG(INFO) << "Coldboot took " << cold_boot_timer;
210}
211
Tom Cherryed506f72017-05-25 15:58:59 -0700212DeviceHandler CreateDeviceHandler() {
213 Parser parser;
214
215 std::vector<Subsystem> subsystems;
216 parser.AddSectionParser("subsystem", std::make_unique<SubsystemParser>(&subsystems));
217
218 using namespace std::placeholders;
219 std::vector<SysfsPermissions> sysfs_permissions;
220 std::vector<Permissions> dev_permissions;
221 parser.AddSingleLineParser(
222 "/sys/", std::bind(ParsePermissionsLine, _1, _2, &sysfs_permissions, nullptr));
223 parser.AddSingleLineParser("/dev/",
224 std::bind(ParsePermissionsLine, _1, _2, nullptr, &dev_permissions));
225
226 parser.ParseConfig("/ueventd.rc");
227 parser.ParseConfig("/vendor/ueventd.rc");
228 parser.ParseConfig("/odm/ueventd.rc");
229
230 /*
231 * keep the current product name base configuration so
232 * we remain backwards compatible and allow it to override
233 * everything
234 * TODO: cleanup platform ueventd.rc to remove vendor specific
235 * device node entries (b/34968103)
236 */
237 std::string hardware = android::base::GetProperty("ro.hardware", "");
238 parser.ParseConfig("/ueventd." + hardware + ".rc");
239
240 return DeviceHandler(std::move(dev_permissions), std::move(sysfs_permissions),
Tom Cherryc5833052017-05-16 15:35:41 -0700241 std::move(subsystems), true);
Tom Cherryed506f72017-05-25 15:58:59 -0700242}
243
Tom Cherryc5833052017-05-16 15:35:41 -0700244int ueventd_main(int argc, char** argv) {
Nick Kralevich6ebf12f2012-03-26 09:09:11 -0700245 /*
246 * init sets the umask to 077 for forked processes. We need to
247 * create files with exact permissions, without modification by
248 * the umask.
249 */
250 umask(000);
251
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700252 InitKernelLogging(argv);
Colin Crossf83d0b92010-04-21 12:04:20 -0700253
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700254 LOG(INFO) << "ueventd started!";
Elliott Hughesda40c002015-03-27 23:20:44 -0700255
256 selinux_callback cb;
257 cb.func_log = selinux_klog_callback;
Stephen Smalley439224e2014-06-24 13:45:43 -0400258 selinux_set_callback(SELINUX_CB_LOG, cb);
259
Tom Cherryed506f72017-05-25 15:58:59 -0700260 DeviceHandler device_handler = CreateDeviceHandler();
261 UeventListener uevent_listener;
Sandeep Patilbf298e62017-02-03 07:18:36 -0800262
Tom Cherryed506f72017-05-25 15:58:59 -0700263 if (access(COLDBOOT_DONE, F_OK) != 0) {
Tom Cherryc5833052017-05-16 15:35:41 -0700264 ColdBoot cold_boot(uevent_listener, device_handler);
265 cold_boot.Run();
Colin Crossf83d0b92010-04-21 12:04:20 -0700266 }
Elliott Hughes21457792015-02-04 10:19:50 -0800267
Sandeep Patil4cbedee2017-06-21 13:02:57 -0700268 uevent_listener.Poll([&device_handler](const Uevent& uevent) {
Tom Cherryed506f72017-05-25 15:58:59 -0700269 HandleFirmwareEvent(uevent);
270 device_handler.HandleDeviceEvent(uevent);
Sandeep Patil4cbedee2017-06-21 13:02:57 -0700271 return ListenerAction::kContinue;
Tom Cherryed506f72017-05-25 15:58:59 -0700272 });
273
Elliott Hughes21457792015-02-04 10:19:50 -0800274 return 0;
Colin Crossf83d0b92010-04-21 12:04:20 -0700275}