1 /*
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
17 #include "ueventd.h"
18
19 #include <android/api-level.h>
20 #include <ctype.h>
21 #include <dirent.h>
22 #include <fcntl.h>
23 #include <signal.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sys/stat.h>
28 #include <sys/wait.h>
29 #include <unistd.h>
30
31 #include <set>
32 #include <thread>
33
34 #include <android-base/chrono_utils.h>
35 #include <android-base/logging.h>
36 #include <android-base/properties.h>
37 #include <fstab/fstab.h>
38 #include <selinux/android.h>
39 #include <selinux/selinux.h>
40
41 #include "devices.h"
42 #include "firmware_handler.h"
43 #include "modalias_handler.h"
44 #include "selabel.h"
45 #include "selinux.h"
46 #include "uevent_handler.h"
47 #include "uevent_listener.h"
48 #include "ueventd_parser.h"
49 #include "util.h"
50
51 // 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
111 namespace android {
112 namespace init {
113
114 class ColdBoot {
115 public:
ColdBoot(UeventListener & uevent_listener,std::vector<std::unique_ptr<UeventHandler>> & uevent_handlers,bool enable_parallel_restorecon,std::vector<std::string> parallel_restorecon_queue)116 ColdBoot(UeventListener& uevent_listener,
117 std::vector<std::unique_ptr<UeventHandler>>& uevent_handlers,
118 bool enable_parallel_restorecon,
119 std::vector<std::string> parallel_restorecon_queue)
120 : uevent_listener_(uevent_listener),
121 uevent_handlers_(uevent_handlers),
122 num_handler_subprocesses_(std::thread::hardware_concurrency() ?: 4),
123 enable_parallel_restorecon_(enable_parallel_restorecon),
124 parallel_restorecon_queue_(parallel_restorecon_queue) {}
125
126 void Run();
127
128 private:
129 void UeventHandlerMain(unsigned int process_num, unsigned int total_processes);
130 void RegenerateUevents();
131 void ForkSubProcesses();
132 void WaitForSubProcesses();
133 void RestoreConHandler(unsigned int process_num, unsigned int total_processes);
134 void GenerateRestoreCon(const std::string& directory);
135
136 UeventListener& uevent_listener_;
137 std::vector<std::unique_ptr<UeventHandler>>& uevent_handlers_;
138
139 unsigned int num_handler_subprocesses_;
140 bool enable_parallel_restorecon_;
141
142 std::vector<Uevent> uevent_queue_;
143
144 std::set<pid_t> subprocess_pids_;
145
146 std::vector<std::string> restorecon_queue_;
147
148 std::vector<std::string> parallel_restorecon_queue_;
149 };
150
UeventHandlerMain(unsigned int process_num,unsigned int total_processes)151 void ColdBoot::UeventHandlerMain(unsigned int process_num, unsigned int total_processes) {
152 for (unsigned int i = process_num; i < uevent_queue_.size(); i += total_processes) {
153 auto& uevent = uevent_queue_[i];
154
155 for (auto& uevent_handler : uevent_handlers_) {
156 uevent_handler->HandleUevent(uevent);
157 }
158 }
159 }
160
RestoreConHandler(unsigned int process_num,unsigned int total_processes)161 void ColdBoot::RestoreConHandler(unsigned int process_num, unsigned int total_processes) {
162 android::base::Timer t_process;
163
164 for (unsigned int i = process_num; i < restorecon_queue_.size(); i += total_processes) {
165 android::base::Timer t;
166 auto& dir = restorecon_queue_[i];
167
168 selinux_android_restorecon(dir.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE);
169
170 //Mark a dir restorecon operation for 50ms,
171 //Maybe you can add this dir to the ueventd.rc script to parallel processing
172 if (t.duration() > 50ms) {
173 LOG(INFO) << "took " << t.duration().count() <<"ms restorecon '"
174 << dir.c_str() << "' on process '" << process_num <<"'";
175 }
176 }
177
178 //Calculate process restorecon time
179 LOG(VERBOSE) << "took " << t_process.duration().count() << "ms on process '"
180 << process_num << "'";
181 }
182
GenerateRestoreCon(const std::string & directory)183 void ColdBoot::GenerateRestoreCon(const std::string& directory) {
184 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(directory.c_str()), &closedir);
185
186 if (!dir) {
187 PLOG(WARNING) << "opendir " << directory.c_str();
188 return;
189 }
190
191 struct dirent* dent;
192 while ((dent = readdir(dir.get())) != NULL) {
193 if (strcmp(dent->d_name, ".") == 0 || strcmp(dent->d_name, "..") == 0) continue;
194
195 struct stat st;
196 if (fstatat(dirfd(dir.get()), dent->d_name, &st, 0) == -1) continue;
197
198 if (S_ISDIR(st.st_mode)) {
199 std::string fullpath = directory + "/" + dent->d_name;
200 auto parallel_restorecon =
201 std::find(parallel_restorecon_queue_.begin(),
202 parallel_restorecon_queue_.end(), fullpath);
203 if (parallel_restorecon == parallel_restorecon_queue_.end()) {
204 restorecon_queue_.emplace_back(fullpath);
205 }
206 }
207 }
208 }
209
RegenerateUevents()210 void ColdBoot::RegenerateUevents() {
211 uevent_listener_.RegenerateUevents([this](const Uevent& uevent) {
212 uevent_queue_.emplace_back(uevent);
213 return ListenerAction::kContinue;
214 });
215 }
216
ForkSubProcesses()217 void ColdBoot::ForkSubProcesses() {
218 for (unsigned int i = 0; i < num_handler_subprocesses_; ++i) {
219 auto pid = fork();
220 if (pid < 0) {
221 PLOG(FATAL) << "fork() failed!";
222 }
223
224 if (pid == 0) {
225 UeventHandlerMain(i, num_handler_subprocesses_);
226 if (enable_parallel_restorecon_) {
227 RestoreConHandler(i, num_handler_subprocesses_);
228 }
229 _exit(EXIT_SUCCESS);
230 }
231
232 subprocess_pids_.emplace(pid);
233 }
234 }
235
WaitForSubProcesses()236 void ColdBoot::WaitForSubProcesses() {
237 // Treat subprocesses that crash or get stuck the same as if ueventd itself has crashed or gets
238 // stuck.
239 //
240 // When a subprocess crashes, we fatally abort from ueventd. init will restart ueventd when
241 // init reaps it, and the cold boot process will start again. If this continues to fail, then
242 // since ueventd is marked as a critical service, init will reboot to bootloader.
243 //
244 // When a subprocess gets stuck, keep ueventd spinning waiting for it. init has a timeout for
245 // cold boot and will reboot to the bootloader if ueventd does not complete in time.
246 while (!subprocess_pids_.empty()) {
247 int status;
248 pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, 0));
249 if (pid == -1) {
250 PLOG(ERROR) << "waitpid() failed";
251 continue;
252 }
253
254 auto it = std::find(subprocess_pids_.begin(), subprocess_pids_.end(), pid);
255 if (it == subprocess_pids_.end()) continue;
256
257 if (WIFEXITED(status)) {
258 if (WEXITSTATUS(status) == EXIT_SUCCESS) {
259 subprocess_pids_.erase(it);
260 } else {
261 LOG(FATAL) << "subprocess exited with status " << WEXITSTATUS(status);
262 }
263 } else if (WIFSIGNALED(status)) {
264 LOG(FATAL) << "subprocess killed by signal " << WTERMSIG(status);
265 }
266 }
267 }
268
Run()269 void ColdBoot::Run() {
270 android::base::Timer cold_boot_timer;
271
272 RegenerateUevents();
273
274 if (enable_parallel_restorecon_) {
275 if (parallel_restorecon_queue_.empty()) {
276 parallel_restorecon_queue_.emplace_back("/sys");
277 // takes long time for /sys/devices, parallelize it
278 parallel_restorecon_queue_.emplace_back("/sys/devices");
279 LOG(INFO) << "Parallel processing directory is not set, set the default";
280 }
281 for (const auto& dir : parallel_restorecon_queue_) {
282 selinux_android_restorecon(dir.c_str(), 0);
283 GenerateRestoreCon(dir);
284 }
285 }
286
287 ForkSubProcesses();
288
289 if (!enable_parallel_restorecon_) {
290 selinux_android_restorecon("/sys", SELINUX_ANDROID_RESTORECON_RECURSE);
291 }
292
293 WaitForSubProcesses();
294
295 android::base::SetProperty(kColdBootDoneProp, "true");
296 LOG(INFO) << "Coldboot took " << cold_boot_timer.duration().count() / 1000.0f << " seconds";
297 }
298
GetConfiguration()299 static UeventdConfiguration GetConfiguration() {
300 if (IsMicrodroid()) {
301 return ParseConfig({"/system/etc/ueventd.rc", "/vendor/etc/ueventd.rc"});
302 }
303
304 auto hardware = android::base::GetProperty("ro.hardware", "");
305
306 struct LegacyPathInfo {
307 std::string legacy_path;
308 std::string preferred;
309 };
310 std::vector<LegacyPathInfo> legacy_paths{
311 {"/vendor/ueventd.rc", "/vendor/etc/ueventd.rc"},
312 {"/odm/ueventd.rc", "/odm/etc/ueventd.rc"},
313 {"/ueventd." + hardware + ".rc", "another ueventd.rc file"}};
314
315 std::vector<std::string> canonical{"/system/etc/ueventd.rc"};
316
317 if (android::base::GetIntProperty("ro.product.first_api_level", 10000) < __ANDROID_API_T__) {
318 // TODO: Remove these legacy paths once Android S is no longer supported.
319 for (const auto& info : legacy_paths) {
320 canonical.push_back(info.legacy_path);
321 }
322 } else {
323 // Warn if newer device is using legacy paths.
324 for (const auto& info : legacy_paths) {
325 if (access(info.legacy_path.c_str(), F_OK) == 0) {
326 LOG(FATAL_WITHOUT_ABORT)
327 << "Legacy ueventd configuration file detected and will not be parsed: "
328 << info.legacy_path << ". Please move your configuration to "
329 << info.preferred << " instead.";
330 }
331 }
332 }
333
334 return ParseConfig(canonical);
335 }
336
ueventd_main(int argc,char ** argv)337 int ueventd_main(int argc, char** argv) {
338 /*
339 * init sets the umask to 077 for forked processes. We need to
340 * create files with exact permissions, without modification by
341 * the umask.
342 */
343 umask(000);
344
345 android::base::InitLogging(argv, &android::base::KernelLogger);
346
347 LOG(INFO) << "ueventd started!";
348
349 SelinuxSetupKernelLogging();
350 SelabelInitialize();
351
352 std::vector<std::unique_ptr<UeventHandler>> uevent_handlers;
353
354 auto ueventd_configuration = GetConfiguration();
355
356 uevent_handlers.emplace_back(std::make_unique<DeviceHandler>(
357 std::move(ueventd_configuration.dev_permissions),
358 std::move(ueventd_configuration.sysfs_permissions),
359 std::move(ueventd_configuration.subsystems), android::fs_mgr::GetBootDevices(), true));
360 uevent_handlers.emplace_back(std::make_unique<FirmwareHandler>(
361 std::move(ueventd_configuration.firmware_directories),
362 std::move(ueventd_configuration.external_firmware_handlers)));
363
364 if (ueventd_configuration.enable_modalias_handling) {
365 std::vector<std::string> base_paths = {"/odm/lib/modules", "/vendor/lib/modules"};
366 uevent_handlers.emplace_back(std::make_unique<ModaliasHandler>(base_paths));
367 }
368 UeventListener uevent_listener(ueventd_configuration.uevent_socket_rcvbuf_size);
369
370 if (!android::base::GetBoolProperty(kColdBootDoneProp, false)) {
371 ColdBoot cold_boot(uevent_listener, uevent_handlers,
372 ueventd_configuration.enable_parallel_restorecon,
373 ueventd_configuration.parallel_restorecon_dirs);
374 cold_boot.Run();
375 }
376
377 for (auto& uevent_handler : uevent_handlers) {
378 uevent_handler->ColdbootDone();
379 }
380
381 // We use waitpid() in ColdBoot, so we can't ignore SIGCHLD until now.
382 signal(SIGCHLD, SIG_IGN);
383 // Reap and pending children that exited between the last call to waitpid() and setting SIG_IGN
384 // for SIGCHLD above.
385 while (waitpid(-1, nullptr, WNOHANG) > 0) {
386 }
387
388 // Restore prio before main loop
389 setpriority(PRIO_PROCESS, 0, 0);
390 uevent_listener.Poll([&uevent_handlers](const Uevent& uevent) {
391 for (auto& uevent_handler : uevent_handlers) {
392 uevent_handler->HandleUevent(uevent);
393 }
394 return ListenerAction::kContinue;
395 });
396
397 return 0;
398 }
399
400 } // namespace init
401 } // namespace android
402