]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/udev/udevd.c
Merge pull request #16504 from poettering/read-file-ipc
[thirdparty/systemd.git] / src / udev / udevd.c
1 /* SPDX-License-Identifier: GPL-2.0+ */
2 /*
3 * Copyright © 2004 Chris Friesen <chris_friesen@sympatico.ca>
4 * Copyright © 2009 Canonical Ltd.
5 * Copyright © 2009 Scott James Remnant <scott@netsplit.com>
6 */
7
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <getopt.h>
11 #include <stdbool.h>
12 #include <stddef.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <sys/epoll.h>
16 #include <sys/file.h>
17 #include <sys/inotify.h>
18 #include <sys/ioctl.h>
19 #include <sys/mount.h>
20 #include <sys/prctl.h>
21 #include <sys/signalfd.h>
22 #include <sys/stat.h>
23 #include <sys/time.h>
24 #include <sys/wait.h>
25 #include <unistd.h>
26
27 #include "sd-daemon.h"
28 #include "sd-event.h"
29
30 #include "alloc-util.h"
31 #include "build.h"
32 #include "cgroup-util.h"
33 #include "cpu-set-util.h"
34 #include "dev-setup.h"
35 #include "device-monitor-private.h"
36 #include "device-private.h"
37 #include "device-util.h"
38 #include "event-util.h"
39 #include "fd-util.h"
40 #include "fileio.h"
41 #include "format-util.h"
42 #include "fs-util.h"
43 #include "hashmap.h"
44 #include "io-util.h"
45 #include "libudev-device-internal.h"
46 #include "limits-util.h"
47 #include "list.h"
48 #include "main-func.h"
49 #include "mkdir.h"
50 #include "netlink-util.h"
51 #include "parse-util.h"
52 #include "pretty-print.h"
53 #include "proc-cmdline.h"
54 #include "process-util.h"
55 #include "selinux-util.h"
56 #include "signal-util.h"
57 #include "socket-util.h"
58 #include "string-util.h"
59 #include "strv.h"
60 #include "strxcpyx.h"
61 #include "syslog-util.h"
62 #include "udevd.h"
63 #include "udev-builtin.h"
64 #include "udev-ctrl.h"
65 #include "udev-event.h"
66 #include "udev-util.h"
67 #include "udev-watch.h"
68 #include "user-util.h"
69
70 #define WORKER_NUM_MAX 2048U
71
72 static bool arg_debug = false;
73 static int arg_daemonize = false;
74 static ResolveNameTiming arg_resolve_name_timing = RESOLVE_NAME_EARLY;
75 static unsigned arg_children_max = 0;
76 static usec_t arg_exec_delay_usec = 0;
77 static usec_t arg_event_timeout_usec = 180 * USEC_PER_SEC;
78 static int arg_timeout_signal = SIGKILL;
79 static bool arg_blockdev_read_only = false;
80
81 typedef struct Manager {
82 sd_event *event;
83 Hashmap *workers;
84 LIST_HEAD(struct event, events);
85 const char *cgroup;
86 pid_t pid; /* the process that originally allocated the manager object */
87
88 UdevRules *rules;
89 Hashmap *properties;
90
91 sd_netlink *rtnl;
92
93 sd_device_monitor *monitor;
94 struct udev_ctrl *ctrl;
95 int fd_inotify;
96 int worker_watch[2];
97
98 sd_event_source *inotify_event;
99 sd_event_source *kill_workers_event;
100
101 usec_t last_usec;
102
103 bool stop_exec_queue:1;
104 bool exit:1;
105 } Manager;
106
107 enum event_state {
108 EVENT_UNDEF,
109 EVENT_QUEUED,
110 EVENT_RUNNING,
111 };
112
113 struct event {
114 Manager *manager;
115 struct worker *worker;
116 enum event_state state;
117
118 sd_device *dev;
119 sd_device *dev_kernel; /* clone of originally received device */
120
121 uint64_t seqnum;
122 uint64_t delaying_seqnum;
123
124 sd_event_source *timeout_warning_event;
125 sd_event_source *timeout_event;
126
127 LIST_FIELDS(struct event, event);
128 };
129
130 static void event_queue_cleanup(Manager *manager, enum event_state type);
131
132 enum worker_state {
133 WORKER_UNDEF,
134 WORKER_RUNNING,
135 WORKER_IDLE,
136 WORKER_KILLED,
137 };
138
139 struct worker {
140 Manager *manager;
141 pid_t pid;
142 sd_device_monitor *monitor;
143 enum worker_state state;
144 struct event *event;
145 };
146
147 /* passed from worker to main process */
148 struct worker_message {
149 };
150
151 static void event_free(struct event *event) {
152 if (!event)
153 return;
154
155 assert(event->manager);
156
157 LIST_REMOVE(event, event->manager->events, event);
158 sd_device_unref(event->dev);
159 sd_device_unref(event->dev_kernel);
160
161 sd_event_source_unref(event->timeout_warning_event);
162 sd_event_source_unref(event->timeout_event);
163
164 if (event->worker)
165 event->worker->event = NULL;
166
167 /* only clean up the queue from the process that created it */
168 if (LIST_IS_EMPTY(event->manager->events) &&
169 event->manager->pid == getpid_cached())
170 if (unlink("/run/udev/queue") < 0)
171 log_warning_errno(errno, "Failed to unlink /run/udev/queue: %m");
172
173 free(event);
174 }
175
176 static void worker_free(struct worker *worker) {
177 if (!worker)
178 return;
179
180 assert(worker->manager);
181
182 hashmap_remove(worker->manager->workers, PID_TO_PTR(worker->pid));
183 sd_device_monitor_unref(worker->monitor);
184 event_free(worker->event);
185
186 free(worker);
187 }
188
189 DEFINE_TRIVIAL_CLEANUP_FUNC(struct worker *, worker_free);
190 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(worker_hash_op, void, trivial_hash_func, trivial_compare_func, struct worker, worker_free);
191
192 static int worker_new(struct worker **ret, Manager *manager, sd_device_monitor *worker_monitor, pid_t pid) {
193 _cleanup_(worker_freep) struct worker *worker = NULL;
194 int r;
195
196 assert(ret);
197 assert(manager);
198 assert(worker_monitor);
199 assert(pid > 1);
200
201 /* close monitor, but keep address around */
202 device_monitor_disconnect(worker_monitor);
203
204 worker = new(struct worker, 1);
205 if (!worker)
206 return -ENOMEM;
207
208 *worker = (struct worker) {
209 .manager = manager,
210 .monitor = sd_device_monitor_ref(worker_monitor),
211 .pid = pid,
212 };
213
214 r = hashmap_ensure_allocated(&manager->workers, &worker_hash_op);
215 if (r < 0)
216 return r;
217
218 r = hashmap_put(manager->workers, PID_TO_PTR(pid), worker);
219 if (r < 0)
220 return r;
221
222 *ret = TAKE_PTR(worker);
223
224 return 0;
225 }
226
227 static int on_event_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
228 struct event *event = userdata;
229
230 assert(event);
231 assert(event->worker);
232
233 kill_and_sigcont(event->worker->pid, arg_timeout_signal);
234 event->worker->state = WORKER_KILLED;
235
236 log_device_error(event->dev, "Worker ["PID_FMT"] processing SEQNUM=%"PRIu64" killed", event->worker->pid, event->seqnum);
237
238 return 1;
239 }
240
241 static int on_event_timeout_warning(sd_event_source *s, uint64_t usec, void *userdata) {
242 struct event *event = userdata;
243
244 assert(event);
245 assert(event->worker);
246
247 log_device_warning(event->dev, "Worker ["PID_FMT"] processing SEQNUM=%"PRIu64" is taking a long time", event->worker->pid, event->seqnum);
248
249 return 1;
250 }
251
252 static void worker_attach_event(struct worker *worker, struct event *event) {
253 sd_event *e;
254 uint64_t usec;
255
256 assert(worker);
257 assert(worker->manager);
258 assert(event);
259 assert(!event->worker);
260 assert(!worker->event);
261
262 worker->state = WORKER_RUNNING;
263 worker->event = event;
264 event->state = EVENT_RUNNING;
265 event->worker = worker;
266
267 e = worker->manager->event;
268
269 assert_se(sd_event_now(e, CLOCK_MONOTONIC, &usec) >= 0);
270
271 (void) sd_event_add_time(e, &event->timeout_warning_event, CLOCK_MONOTONIC,
272 usec + udev_warn_timeout(arg_event_timeout_usec), USEC_PER_SEC, on_event_timeout_warning, event);
273
274 (void) sd_event_add_time(e, &event->timeout_event, CLOCK_MONOTONIC,
275 usec + arg_event_timeout_usec, USEC_PER_SEC, on_event_timeout, event);
276 }
277
278 static void manager_clear_for_worker(Manager *manager) {
279 assert(manager);
280
281 manager->inotify_event = sd_event_source_unref(manager->inotify_event);
282 manager->kill_workers_event = sd_event_source_unref(manager->kill_workers_event);
283
284 manager->event = sd_event_unref(manager->event);
285
286 manager->workers = hashmap_free(manager->workers);
287 event_queue_cleanup(manager, EVENT_UNDEF);
288
289 manager->monitor = sd_device_monitor_unref(manager->monitor);
290 manager->ctrl = udev_ctrl_unref(manager->ctrl);
291
292 manager->worker_watch[READ_END] = safe_close(manager->worker_watch[READ_END]);
293 }
294
295 static void manager_free(Manager *manager) {
296 if (!manager)
297 return;
298
299 udev_builtin_exit();
300
301 if (manager->pid == getpid_cached())
302 udev_ctrl_cleanup(manager->ctrl);
303
304 manager_clear_for_worker(manager);
305
306 sd_netlink_unref(manager->rtnl);
307
308 hashmap_free_free_free(manager->properties);
309 udev_rules_free(manager->rules);
310
311 safe_close(manager->fd_inotify);
312 safe_close_pair(manager->worker_watch);
313
314 free(manager);
315 }
316
317 DEFINE_TRIVIAL_CLEANUP_FUNC(Manager*, manager_free);
318
319 static int worker_send_message(int fd) {
320 struct worker_message message = {};
321
322 return loop_write(fd, &message, sizeof(message), false);
323 }
324
325 static int worker_lock_block_device(sd_device *dev, int *ret_fd) {
326 _cleanup_close_ int fd = -1;
327 const char *val;
328 int r;
329
330 assert(dev);
331 assert(ret_fd);
332
333 /*
334 * Take a shared lock on the device node; this establishes
335 * a concept of device "ownership" to serialize device
336 * access. External processes holding an exclusive lock will
337 * cause udev to skip the event handling; in the case udev
338 * acquired the lock, the external process can block until
339 * udev has finished its event handling.
340 */
341
342 if (device_for_action(dev, DEVICE_ACTION_REMOVE))
343 return 0;
344
345 r = sd_device_get_subsystem(dev, &val);
346 if (r < 0)
347 return log_device_debug_errno(dev, r, "Failed to get subsystem: %m");
348
349 if (!streq(val, "block"))
350 return 0;
351
352 r = sd_device_get_sysname(dev, &val);
353 if (r < 0)
354 return log_device_debug_errno(dev, r, "Failed to get sysname: %m");
355
356 if (STARTSWITH_SET(val, "dm-", "md", "drbd"))
357 return 0;
358
359 r = sd_device_get_devtype(dev, &val);
360 if (r < 0 && r != -ENOENT)
361 return log_device_debug_errno(dev, r, "Failed to get devtype: %m");
362 if (r >= 0 && streq(val, "partition")) {
363 r = sd_device_get_parent(dev, &dev);
364 if (r < 0)
365 return log_device_debug_errno(dev, r, "Failed to get parent device: %m");
366 }
367
368 r = sd_device_get_devname(dev, &val);
369 if (r == -ENOENT)
370 return 0;
371 if (r < 0)
372 return log_device_debug_errno(dev, r, "Failed to get devname: %m");
373
374 fd = open(val, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
375 if (fd < 0) {
376 log_device_debug_errno(dev, errno, "Failed to open '%s', ignoring: %m", val);
377 return 0;
378 }
379
380 if (flock(fd, LOCK_SH|LOCK_NB) < 0)
381 return log_device_debug_errno(dev, errno, "Failed to flock(%s): %m", val);
382
383 *ret_fd = TAKE_FD(fd);
384 return 1;
385 }
386
387 static int worker_mark_block_device_read_only(sd_device *dev) {
388 _cleanup_close_ int fd = -1;
389 const char *val;
390 int state = 1, r;
391
392 assert(dev);
393
394 if (!arg_blockdev_read_only)
395 return 0;
396
397 /* Do this only once, when the block device is new. If the device is later retriggered let's not
398 * toggle the bit again, so that people can boot up with full read-only mode and then unset the bit
399 * for specific devices only. */
400 if (!device_for_action(dev, DEVICE_ACTION_ADD))
401 return 0;
402
403 r = sd_device_get_subsystem(dev, &val);
404 if (r < 0)
405 return log_device_debug_errno(dev, r, "Failed to get subsystem: %m");
406
407 if (!streq(val, "block"))
408 return 0;
409
410 r = sd_device_get_sysname(dev, &val);
411 if (r < 0)
412 return log_device_debug_errno(dev, r, "Failed to get sysname: %m");
413
414 /* Exclude synthetic devices for now, this is supposed to be a safety feature to avoid modification
415 * of physical devices, and what sits on top of those doesn't really matter if we don't allow the
416 * underlying block devices to receive changes. */
417 if (STARTSWITH_SET(val, "dm-", "md", "drbd", "loop", "nbd", "zram"))
418 return 0;
419
420 r = sd_device_get_devname(dev, &val);
421 if (r == -ENOENT)
422 return 0;
423 if (r < 0)
424 return log_device_debug_errno(dev, r, "Failed to get devname: %m");
425
426 fd = open(val, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
427 if (fd < 0)
428 return log_device_debug_errno(dev, errno, "Failed to open '%s', ignoring: %m", val);
429
430 if (ioctl(fd, BLKROSET, &state) < 0)
431 return log_device_warning_errno(dev, errno, "Failed to mark block device '%s' read-only: %m", val);
432
433 log_device_info(dev, "Successfully marked block device '%s' read-only.", val);
434 return 0;
435 }
436
437 static int worker_process_device(Manager *manager, sd_device *dev) {
438 _cleanup_(udev_event_freep) UdevEvent *udev_event = NULL;
439 _cleanup_close_ int fd_lock = -1;
440 DeviceAction action;
441 uint64_t seqnum;
442 int r;
443
444 assert(manager);
445 assert(dev);
446
447 r = device_get_seqnum(dev, &seqnum);
448 if (r < 0)
449 return log_device_debug_errno(dev, r, "Failed to get SEQNUM: %m");
450
451 r = device_get_action(dev, &action);
452 if (r < 0)
453 return log_device_debug_errno(dev, r, "Failed to get ACTION: %m");
454
455 log_device_debug(dev, "Processing device (SEQNUM=%"PRIu64", ACTION=%s)",
456 seqnum, device_action_to_string(action));
457
458 udev_event = udev_event_new(dev, arg_exec_delay_usec, manager->rtnl);
459 if (!udev_event)
460 return -ENOMEM;
461
462 r = worker_lock_block_device(dev, &fd_lock);
463 if (r < 0)
464 return r;
465
466 (void) worker_mark_block_device_read_only(dev);
467
468 /* apply rules, create node, symlinks */
469 r = udev_event_execute_rules(udev_event, arg_event_timeout_usec, arg_timeout_signal, manager->properties, manager->rules);
470 if (r < 0)
471 return r;
472
473 udev_event_execute_run(udev_event, arg_event_timeout_usec, arg_timeout_signal);
474
475 if (!manager->rtnl)
476 /* in case rtnl was initialized */
477 manager->rtnl = sd_netlink_ref(udev_event->rtnl);
478
479 /* apply/restore inotify watch */
480 if (udev_event->inotify_watch) {
481 (void) udev_watch_begin(dev);
482 r = device_update_db(dev);
483 if (r < 0)
484 return log_device_debug_errno(dev, r, "Failed to update database under /run/udev/data/: %m");
485 }
486
487 log_device_debug(dev, "Device (SEQNUM=%"PRIu64", ACTION=%s) processed",
488 seqnum, device_action_to_string(action));
489
490 return 0;
491 }
492
493 static int worker_device_monitor_handler(sd_device_monitor *monitor, sd_device *dev, void *userdata) {
494 Manager *manager = userdata;
495 int r;
496
497 assert(dev);
498 assert(manager);
499
500 r = worker_process_device(manager, dev);
501 if (r == -EAGAIN)
502 /* if we couldn't acquire the flock(), then proceed quietly */
503 log_device_debug_errno(dev, r, "Device currently locked, not processing.");
504 else {
505 if (r < 0)
506 log_device_warning_errno(dev, r, "Failed to process device, ignoring: %m");
507
508 /* send processed event back to libudev listeners */
509 r = device_monitor_send_device(monitor, NULL, dev);
510 if (r < 0)
511 log_device_warning_errno(dev, r, "Failed to send device, ignoring: %m");
512 }
513
514 /* send udevd the result of the event execution */
515 r = worker_send_message(manager->worker_watch[WRITE_END]);
516 if (r < 0)
517 log_device_warning_errno(dev, r, "Failed to send signal to main daemon, ignoring: %m");
518
519 return 1;
520 }
521
522 static int worker_main(Manager *_manager, sd_device_monitor *monitor, sd_device *first_device) {
523 _cleanup_(sd_device_unrefp) sd_device *dev = first_device;
524 _cleanup_(manager_freep) Manager *manager = _manager;
525 int r;
526
527 assert(manager);
528 assert(monitor);
529 assert(dev);
530
531 unsetenv("NOTIFY_SOCKET");
532
533 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, -1) >= 0);
534
535 /* Reset OOM score, we only protect the main daemon. */
536 r = set_oom_score_adjust(0);
537 if (r < 0)
538 log_debug_errno(r, "Failed to reset OOM score, ignoring: %m");
539
540 /* Clear unnecessary data in Manager object.*/
541 manager_clear_for_worker(manager);
542
543 r = sd_event_new(&manager->event);
544 if (r < 0)
545 return log_error_errno(r, "Failed to allocate event loop: %m");
546
547 r = sd_event_add_signal(manager->event, NULL, SIGTERM, NULL, NULL);
548 if (r < 0)
549 return log_error_errno(r, "Failed to set SIGTERM event: %m");
550
551 r = sd_device_monitor_attach_event(monitor, manager->event);
552 if (r < 0)
553 return log_error_errno(r, "Failed to attach event loop to device monitor: %m");
554
555 r = sd_device_monitor_start(monitor, worker_device_monitor_handler, manager);
556 if (r < 0)
557 return log_error_errno(r, "Failed to start device monitor: %m");
558
559 (void) sd_event_source_set_description(sd_device_monitor_get_event_source(monitor), "worker-device-monitor");
560
561 /* Process first device */
562 (void) worker_device_monitor_handler(monitor, dev, manager);
563
564 r = sd_event_loop(manager->event);
565 if (r < 0)
566 return log_error_errno(r, "Event loop failed: %m");
567
568 return 0;
569 }
570
571 static int worker_spawn(Manager *manager, struct event *event) {
572 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *worker_monitor = NULL;
573 struct worker *worker;
574 pid_t pid;
575 int r;
576
577 /* listen for new events */
578 r = device_monitor_new_full(&worker_monitor, MONITOR_GROUP_NONE, -1);
579 if (r < 0)
580 return r;
581
582 /* allow the main daemon netlink address to send devices to the worker */
583 r = device_monitor_allow_unicast_sender(worker_monitor, manager->monitor);
584 if (r < 0)
585 return log_error_errno(r, "Worker: Failed to set unicast sender: %m");
586
587 r = device_monitor_enable_receiving(worker_monitor);
588 if (r < 0)
589 return log_error_errno(r, "Worker: Failed to enable receiving of device: %m");
590
591 r = safe_fork(NULL, FORK_DEATHSIG, &pid);
592 if (r < 0) {
593 event->state = EVENT_QUEUED;
594 return log_error_errno(r, "Failed to fork() worker: %m");
595 }
596 if (r == 0) {
597 /* Worker process */
598 r = worker_main(manager, worker_monitor, sd_device_ref(event->dev));
599 log_close();
600 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
601 }
602
603 r = worker_new(&worker, manager, worker_monitor, pid);
604 if (r < 0)
605 return log_error_errno(r, "Failed to create worker object: %m");
606
607 worker_attach_event(worker, event);
608
609 log_device_debug(event->dev, "Worker ["PID_FMT"] is forked for processing SEQNUM=%"PRIu64".", pid, event->seqnum);
610 return 0;
611 }
612
613 static void event_run(Manager *manager, struct event *event) {
614 static bool log_children_max_reached = true;
615 struct worker *worker;
616 Iterator i;
617 int r;
618
619 assert(manager);
620 assert(event);
621
622 if (DEBUG_LOGGING) {
623 DeviceAction action;
624
625 r = device_get_action(event->dev, &action);
626 log_device_debug(event->dev, "Device (SEQNUM=%"PRIu64", ACTION=%s) ready for processing",
627 event->seqnum, r >= 0 ? device_action_to_string(action) : "<unknown>");
628 }
629
630 HASHMAP_FOREACH(worker, manager->workers, i) {
631 if (worker->state != WORKER_IDLE)
632 continue;
633
634 r = device_monitor_send_device(manager->monitor, worker->monitor, event->dev);
635 if (r < 0) {
636 log_device_error_errno(event->dev, r, "Worker ["PID_FMT"] did not accept message, killing the worker: %m",
637 worker->pid);
638 (void) kill(worker->pid, SIGKILL);
639 worker->state = WORKER_KILLED;
640 continue;
641 }
642 worker_attach_event(worker, event);
643 return;
644 }
645
646 if (hashmap_size(manager->workers) >= arg_children_max) {
647
648 /* Avoid spamming the debug logs if the limit is already reached and
649 * many events still need to be processed */
650 if (log_children_max_reached && arg_children_max > 1) {
651 log_debug("Maximum number (%u) of children reached.", hashmap_size(manager->workers));
652 log_children_max_reached = false;
653 }
654 return;
655 }
656
657 /* Re-enable the debug message for the next batch of events */
658 log_children_max_reached = true;
659
660 /* start new worker and pass initial device */
661 worker_spawn(manager, event);
662 }
663
664 static int event_queue_insert(Manager *manager, sd_device *dev) {
665 _cleanup_(sd_device_unrefp) sd_device *clone = NULL;
666 struct event *event;
667 DeviceAction action;
668 uint64_t seqnum;
669 int r;
670
671 assert(manager);
672 assert(dev);
673
674 /* only one process can add events to the queue */
675 assert(manager->pid == getpid_cached());
676
677 /* We only accepts devices received by device monitor. */
678 r = device_get_seqnum(dev, &seqnum);
679 if (r < 0)
680 return r;
681
682 /* Refuse devices do not have ACTION property. */
683 r = device_get_action(dev, &action);
684 if (r < 0)
685 return r;
686
687 /* Save original device to restore the state on failures. */
688 r = device_shallow_clone(dev, &clone);
689 if (r < 0)
690 return r;
691
692 r = device_copy_properties(clone, dev);
693 if (r < 0)
694 return r;
695
696 event = new(struct event, 1);
697 if (!event)
698 return -ENOMEM;
699
700 *event = (struct event) {
701 .manager = manager,
702 .dev = sd_device_ref(dev),
703 .dev_kernel = TAKE_PTR(clone),
704 .seqnum = seqnum,
705 .state = EVENT_QUEUED,
706 };
707
708 if (LIST_IS_EMPTY(manager->events)) {
709 r = touch("/run/udev/queue");
710 if (r < 0)
711 log_warning_errno(r, "Failed to touch /run/udev/queue: %m");
712 }
713
714 LIST_APPEND(event, manager->events, event);
715
716 log_device_debug(dev, "Device (SEQNUM=%"PRIu64", ACTION=%s) is queued",
717 seqnum, device_action_to_string(action));
718
719 return 0;
720 }
721
722 static void manager_kill_workers(Manager *manager) {
723 struct worker *worker;
724 Iterator i;
725
726 assert(manager);
727
728 HASHMAP_FOREACH(worker, manager->workers, i) {
729 if (worker->state == WORKER_KILLED)
730 continue;
731
732 worker->state = WORKER_KILLED;
733 (void) kill(worker->pid, SIGTERM);
734 }
735 }
736
737 /* lookup event for identical, parent, child device */
738 static int is_device_busy(Manager *manager, struct event *event) {
739 const char *subsystem, *devpath, *devpath_old = NULL;
740 dev_t devnum = makedev(0, 0);
741 struct event *loop_event;
742 size_t devpath_len;
743 int r, ifindex = 0;
744 bool is_block;
745
746 r = sd_device_get_subsystem(event->dev, &subsystem);
747 if (r < 0)
748 return r;
749
750 is_block = streq(subsystem, "block");
751
752 r = sd_device_get_devpath(event->dev, &devpath);
753 if (r < 0)
754 return r;
755
756 devpath_len = strlen(devpath);
757
758 r = sd_device_get_property_value(event->dev, "DEVPATH_OLD", &devpath_old);
759 if (r < 0 && r != -ENOENT)
760 return r;
761
762 r = sd_device_get_devnum(event->dev, &devnum);
763 if (r < 0 && r != -ENOENT)
764 return r;
765
766 r = sd_device_get_ifindex(event->dev, &ifindex);
767 if (r < 0 && r != -ENOENT)
768 return r;
769
770 /* check if queue contains events we depend on */
771 LIST_FOREACH(event, loop_event, manager->events) {
772 size_t loop_devpath_len, common;
773 const char *loop_devpath;
774
775 /* we already found a later event, earlier cannot block us, no need to check again */
776 if (loop_event->seqnum < event->delaying_seqnum)
777 continue;
778
779 /* event we checked earlier still exists, no need to check again */
780 if (loop_event->seqnum == event->delaying_seqnum)
781 return true;
782
783 /* found ourself, no later event can block us */
784 if (loop_event->seqnum >= event->seqnum)
785 break;
786
787 /* check major/minor */
788 if (major(devnum) != 0) {
789 const char *s;
790 dev_t d;
791
792 if (sd_device_get_subsystem(loop_event->dev, &s) < 0)
793 continue;
794
795 if (sd_device_get_devnum(loop_event->dev, &d) >= 0 &&
796 devnum == d && is_block == streq(s, "block"))
797 goto set_delaying_seqnum;
798 }
799
800 /* check network device ifindex */
801 if (ifindex > 0) {
802 int i;
803
804 if (sd_device_get_ifindex(loop_event->dev, &i) >= 0 &&
805 ifindex == i)
806 goto set_delaying_seqnum;
807 }
808
809 if (sd_device_get_devpath(loop_event->dev, &loop_devpath) < 0)
810 continue;
811
812 /* check our old name */
813 if (devpath_old && streq(devpath_old, loop_devpath))
814 goto set_delaying_seqnum;
815
816 loop_devpath_len = strlen(loop_devpath);
817
818 /* compare devpath */
819 common = MIN(devpath_len, loop_devpath_len);
820
821 /* one devpath is contained in the other? */
822 if (!strneq(devpath, loop_devpath, common))
823 continue;
824
825 /* identical device event found */
826 if (devpath_len == loop_devpath_len)
827 goto set_delaying_seqnum;
828
829 /* parent device event found */
830 if (devpath[common] == '/')
831 goto set_delaying_seqnum;
832
833 /* child device event found */
834 if (loop_devpath[common] == '/')
835 goto set_delaying_seqnum;
836 }
837
838 return false;
839
840 set_delaying_seqnum:
841 log_device_debug(event->dev, "SEQNUM=%" PRIu64 " blocked by SEQNUM=%" PRIu64,
842 event->seqnum, loop_event->seqnum);
843
844 event->delaying_seqnum = loop_event->seqnum;
845 return true;
846 }
847
848 static void manager_exit(Manager *manager) {
849 assert(manager);
850
851 manager->exit = true;
852
853 sd_notify(false,
854 "STOPPING=1\n"
855 "STATUS=Starting shutdown...");
856
857 /* close sources of new events and discard buffered events */
858 manager->ctrl = udev_ctrl_unref(manager->ctrl);
859
860 manager->inotify_event = sd_event_source_unref(manager->inotify_event);
861 manager->fd_inotify = safe_close(manager->fd_inotify);
862
863 manager->monitor = sd_device_monitor_unref(manager->monitor);
864
865 /* discard queued events and kill workers */
866 event_queue_cleanup(manager, EVENT_QUEUED);
867 manager_kill_workers(manager);
868 }
869
870 /* reload requested, HUP signal received, rules changed, builtin changed */
871 static void manager_reload(Manager *manager) {
872
873 assert(manager);
874
875 sd_notify(false,
876 "RELOADING=1\n"
877 "STATUS=Flushing configuration...");
878
879 manager_kill_workers(manager);
880 manager->rules = udev_rules_free(manager->rules);
881 udev_builtin_exit();
882
883 sd_notifyf(false,
884 "READY=1\n"
885 "STATUS=Processing with %u children at max", arg_children_max);
886 }
887
888 static int on_kill_workers_event(sd_event_source *s, uint64_t usec, void *userdata) {
889 Manager *manager = userdata;
890
891 assert(manager);
892
893 log_debug("Cleanup idle workers");
894 manager_kill_workers(manager);
895
896 return 1;
897 }
898
899 static void event_queue_start(Manager *manager) {
900 struct event *event;
901 usec_t usec;
902 int r;
903
904 assert(manager);
905
906 if (LIST_IS_EMPTY(manager->events) ||
907 manager->exit || manager->stop_exec_queue)
908 return;
909
910 assert_se(sd_event_now(manager->event, CLOCK_MONOTONIC, &usec) >= 0);
911 /* check for changed config, every 3 seconds at most */
912 if (manager->last_usec == 0 ||
913 usec - manager->last_usec > 3 * USEC_PER_SEC) {
914 if (udev_rules_check_timestamp(manager->rules) ||
915 udev_builtin_validate())
916 manager_reload(manager);
917
918 manager->last_usec = usec;
919 }
920
921 r = event_source_disable(manager->kill_workers_event);
922 if (r < 0)
923 log_warning_errno(r, "Failed to disable event source for cleaning up idle workers, ignoring: %m");
924
925 udev_builtin_init();
926
927 if (!manager->rules) {
928 r = udev_rules_load(&manager->rules, arg_resolve_name_timing);
929 if (r < 0) {
930 log_warning_errno(r, "Failed to read udev rules: %m");
931 return;
932 }
933 }
934
935 LIST_FOREACH(event, event, manager->events) {
936 if (event->state != EVENT_QUEUED)
937 continue;
938
939 /* do not start event if parent or child event is still running */
940 if (is_device_busy(manager, event) != 0)
941 continue;
942
943 event_run(manager, event);
944 }
945 }
946
947 static void event_queue_cleanup(Manager *manager, enum event_state match_type) {
948 struct event *event, *tmp;
949
950 LIST_FOREACH_SAFE(event, event, tmp, manager->events) {
951 if (match_type != EVENT_UNDEF && match_type != event->state)
952 continue;
953
954 event_free(event);
955 }
956 }
957
958 static int on_worker(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
959 Manager *manager = userdata;
960
961 assert(manager);
962
963 for (;;) {
964 struct worker_message msg;
965 struct iovec iovec = {
966 .iov_base = &msg,
967 .iov_len = sizeof(msg),
968 };
969 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred))) control;
970 struct msghdr msghdr = {
971 .msg_iov = &iovec,
972 .msg_iovlen = 1,
973 .msg_control = &control,
974 .msg_controllen = sizeof(control),
975 };
976 ssize_t size;
977 struct ucred *ucred;
978 struct worker *worker;
979
980 size = recvmsg_safe(fd, &msghdr, MSG_DONTWAIT);
981 if (size == -EINTR)
982 continue;
983 if (size == -EAGAIN)
984 /* nothing more to read */
985 break;
986 if (size < 0)
987 return log_error_errno(size, "Failed to receive message: %m");
988
989 cmsg_close_all(&msghdr);
990
991 if (size != sizeof(struct worker_message)) {
992 log_warning("Ignoring worker message with invalid size %zi bytes", size);
993 continue;
994 }
995
996 ucred = CMSG_FIND_DATA(&msghdr, SOL_SOCKET, SCM_CREDENTIALS, struct ucred);
997 if (!ucred || ucred->pid <= 0) {
998 log_warning("Ignoring worker message without valid PID");
999 continue;
1000 }
1001
1002 /* lookup worker who sent the signal */
1003 worker = hashmap_get(manager->workers, PID_TO_PTR(ucred->pid));
1004 if (!worker) {
1005 log_debug("Worker ["PID_FMT"] returned, but is no longer tracked", ucred->pid);
1006 continue;
1007 }
1008
1009 if (worker->state != WORKER_KILLED)
1010 worker->state = WORKER_IDLE;
1011
1012 /* worker returned */
1013 event_free(worker->event);
1014 }
1015
1016 /* we have free workers, try to schedule events */
1017 event_queue_start(manager);
1018
1019 return 1;
1020 }
1021
1022 static int on_uevent(sd_device_monitor *monitor, sd_device *dev, void *userdata) {
1023 Manager *manager = userdata;
1024 int r;
1025
1026 assert(manager);
1027
1028 device_ensure_usec_initialized(dev, NULL);
1029
1030 r = event_queue_insert(manager, dev);
1031 if (r < 0) {
1032 log_device_error_errno(dev, r, "Failed to insert device into event queue: %m");
1033 return 1;
1034 }
1035
1036 /* we have fresh events, try to schedule them */
1037 event_queue_start(manager);
1038
1039 return 1;
1040 }
1041
1042 /* receive the udevd message from userspace */
1043 static int on_ctrl_msg(struct udev_ctrl *uctrl, enum udev_ctrl_msg_type type, const union udev_ctrl_msg_value *value, void *userdata) {
1044 Manager *manager = userdata;
1045 int r;
1046
1047 assert(value);
1048 assert(manager);
1049
1050 switch (type) {
1051 case UDEV_CTRL_SET_LOG_LEVEL:
1052 log_debug("Received udev control message (SET_LOG_LEVEL), setting log_priority=%i", value->intval);
1053 log_set_max_level_realm(LOG_REALM_UDEV, value->intval);
1054 log_set_max_level_realm(LOG_REALM_SYSTEMD, value->intval);
1055 manager_kill_workers(manager);
1056 break;
1057 case UDEV_CTRL_STOP_EXEC_QUEUE:
1058 log_debug("Received udev control message (STOP_EXEC_QUEUE)");
1059 manager->stop_exec_queue = true;
1060 break;
1061 case UDEV_CTRL_START_EXEC_QUEUE:
1062 log_debug("Received udev control message (START_EXEC_QUEUE)");
1063 manager->stop_exec_queue = false;
1064 event_queue_start(manager);
1065 break;
1066 case UDEV_CTRL_RELOAD:
1067 log_debug("Received udev control message (RELOAD)");
1068 manager_reload(manager);
1069 break;
1070 case UDEV_CTRL_SET_ENV: {
1071 _cleanup_free_ char *key = NULL, *val = NULL, *old_key = NULL, *old_val = NULL;
1072 const char *eq;
1073
1074 eq = strchr(value->buf, '=');
1075 if (!eq) {
1076 log_error("Invalid key format '%s'", value->buf);
1077 return 1;
1078 }
1079
1080 key = strndup(value->buf, eq - value->buf);
1081 if (!key) {
1082 log_oom();
1083 return 1;
1084 }
1085
1086 old_val = hashmap_remove2(manager->properties, key, (void **) &old_key);
1087
1088 r = hashmap_ensure_allocated(&manager->properties, &string_hash_ops);
1089 if (r < 0) {
1090 log_oom();
1091 return 1;
1092 }
1093
1094 eq++;
1095 if (isempty(eq)) {
1096 log_debug("Received udev control message (ENV), unsetting '%s'", key);
1097
1098 r = hashmap_put(manager->properties, key, NULL);
1099 if (r < 0) {
1100 log_oom();
1101 return 1;
1102 }
1103 } else {
1104 val = strdup(eq);
1105 if (!val) {
1106 log_oom();
1107 return 1;
1108 }
1109
1110 log_debug("Received udev control message (ENV), setting '%s=%s'", key, val);
1111
1112 r = hashmap_put(manager->properties, key, val);
1113 if (r < 0) {
1114 log_oom();
1115 return 1;
1116 }
1117 }
1118
1119 key = val = NULL;
1120 manager_kill_workers(manager);
1121 break;
1122 }
1123 case UDEV_CTRL_SET_CHILDREN_MAX:
1124 if (value->intval <= 0) {
1125 log_debug("Received invalid udev control message (SET_MAX_CHILDREN, %i), ignoring.", value->intval);
1126 return 0;
1127 }
1128
1129 log_debug("Received udev control message (SET_MAX_CHILDREN), setting children_max=%i", value->intval);
1130 arg_children_max = value->intval;
1131
1132 (void) sd_notifyf(false,
1133 "READY=1\n"
1134 "STATUS=Processing with %u children at max", arg_children_max);
1135 break;
1136 case UDEV_CTRL_PING:
1137 log_debug("Received udev control message (PING)");
1138 break;
1139 case UDEV_CTRL_EXIT:
1140 log_debug("Received udev control message (EXIT)");
1141 manager_exit(manager);
1142 break;
1143 default:
1144 log_debug("Received unknown udev control message, ignoring");
1145 }
1146
1147 return 1;
1148 }
1149
1150 static int synthesize_change_one(sd_device *dev, const char *syspath) {
1151 const char *filename;
1152 int r;
1153
1154 filename = strjoina(syspath, "/uevent");
1155 log_device_debug(dev, "device is closed, synthesising 'change' on %s", syspath);
1156 r = write_string_file(filename, "change", WRITE_STRING_FILE_DISABLE_BUFFER);
1157 if (r < 0)
1158 return log_device_debug_errno(dev, r, "Failed to write 'change' to %s: %m", filename);
1159 return 0;
1160 }
1161
1162 static int synthesize_change(sd_device *dev) {
1163 const char *subsystem, *sysname, *devname, *syspath, *devtype;
1164 int r;
1165
1166 r = sd_device_get_subsystem(dev, &subsystem);
1167 if (r < 0)
1168 return r;
1169
1170 r = sd_device_get_sysname(dev, &sysname);
1171 if (r < 0)
1172 return r;
1173
1174 r = sd_device_get_devname(dev, &devname);
1175 if (r < 0)
1176 return r;
1177
1178 r = sd_device_get_syspath(dev, &syspath);
1179 if (r < 0)
1180 return r;
1181
1182 r = sd_device_get_devtype(dev, &devtype);
1183 if (r < 0)
1184 return r;
1185
1186 if (streq_ptr("block", subsystem) &&
1187 streq_ptr("disk", devtype) &&
1188 !startswith(sysname, "dm-")) {
1189 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
1190 bool part_table_read = false, has_partitions = false;
1191 sd_device *d;
1192 int fd;
1193
1194 /*
1195 * Try to re-read the partition table. This only succeeds if
1196 * none of the devices is busy. The kernel returns 0 if no
1197 * partition table is found, and we will not get an event for
1198 * the disk.
1199 */
1200 fd = open(devname, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
1201 if (fd >= 0) {
1202 r = flock(fd, LOCK_EX|LOCK_NB);
1203 if (r >= 0)
1204 r = ioctl(fd, BLKRRPART, 0);
1205
1206 close(fd);
1207 if (r >= 0)
1208 part_table_read = true;
1209 }
1210
1211 /* search for partitions */
1212 r = sd_device_enumerator_new(&e);
1213 if (r < 0)
1214 return r;
1215
1216 r = sd_device_enumerator_allow_uninitialized(e);
1217 if (r < 0)
1218 return r;
1219
1220 r = sd_device_enumerator_add_match_parent(e, dev);
1221 if (r < 0)
1222 return r;
1223
1224 r = sd_device_enumerator_add_match_subsystem(e, "block", true);
1225 if (r < 0)
1226 return r;
1227
1228 FOREACH_DEVICE(e, d) {
1229 const char *t;
1230
1231 if (sd_device_get_devtype(d, &t) < 0 ||
1232 !streq("partition", t))
1233 continue;
1234
1235 has_partitions = true;
1236 break;
1237 }
1238
1239 /*
1240 * We have partitions and re-read the table, the kernel already sent
1241 * out a "change" event for the disk, and "remove/add" for all
1242 * partitions.
1243 */
1244 if (part_table_read && has_partitions)
1245 return 0;
1246
1247 /*
1248 * We have partitions but re-reading the partition table did not
1249 * work, synthesize "change" for the disk and all partitions.
1250 */
1251 (void) synthesize_change_one(dev, syspath);
1252
1253 FOREACH_DEVICE(e, d) {
1254 const char *t, *n, *s;
1255
1256 if (sd_device_get_devtype(d, &t) < 0 ||
1257 !streq("partition", t))
1258 continue;
1259
1260 if (sd_device_get_devname(d, &n) < 0 ||
1261 sd_device_get_syspath(d, &s) < 0)
1262 continue;
1263
1264 (void) synthesize_change_one(dev, s);
1265 }
1266
1267 } else
1268 (void) synthesize_change_one(dev, syspath);
1269
1270 return 0;
1271 }
1272
1273 static int on_inotify(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
1274 Manager *manager = userdata;
1275 union inotify_event_buffer buffer;
1276 struct inotify_event *e;
1277 ssize_t l;
1278 int r;
1279
1280 assert(manager);
1281
1282 r = event_source_disable(manager->kill_workers_event);
1283 if (r < 0)
1284 log_warning_errno(r, "Failed to disable event source for cleaning up idle workers, ignoring: %m");
1285
1286 l = read(fd, &buffer, sizeof(buffer));
1287 if (l < 0) {
1288 if (IN_SET(errno, EAGAIN, EINTR))
1289 return 1;
1290
1291 return log_error_errno(errno, "Failed to read inotify fd: %m");
1292 }
1293
1294 FOREACH_INOTIFY_EVENT(e, buffer, l) {
1295 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
1296 const char *devnode;
1297
1298 if (udev_watch_lookup(e->wd, &dev) <= 0)
1299 continue;
1300
1301 if (sd_device_get_devname(dev, &devnode) < 0)
1302 continue;
1303
1304 log_device_debug(dev, "Inotify event: %x for %s", e->mask, devnode);
1305 if (e->mask & IN_CLOSE_WRITE)
1306 synthesize_change(dev);
1307 else if (e->mask & IN_IGNORED)
1308 udev_watch_end(dev);
1309 }
1310
1311 return 1;
1312 }
1313
1314 static int on_sigterm(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
1315 Manager *manager = userdata;
1316
1317 assert(manager);
1318
1319 manager_exit(manager);
1320
1321 return 1;
1322 }
1323
1324 static int on_sighup(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
1325 Manager *manager = userdata;
1326
1327 assert(manager);
1328
1329 manager_reload(manager);
1330
1331 return 1;
1332 }
1333
1334 static int on_sigchld(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
1335 Manager *manager = userdata;
1336 int r;
1337
1338 assert(manager);
1339
1340 for (;;) {
1341 pid_t pid;
1342 int status;
1343 struct worker *worker;
1344
1345 pid = waitpid(-1, &status, WNOHANG);
1346 if (pid <= 0)
1347 break;
1348
1349 worker = hashmap_get(manager->workers, PID_TO_PTR(pid));
1350 if (!worker) {
1351 log_warning("Worker ["PID_FMT"] is unknown, ignoring", pid);
1352 continue;
1353 }
1354
1355 if (WIFEXITED(status)) {
1356 if (WEXITSTATUS(status) == 0)
1357 log_debug("Worker ["PID_FMT"] exited", pid);
1358 else
1359 log_warning("Worker ["PID_FMT"] exited with return code %i", pid, WEXITSTATUS(status));
1360 } else if (WIFSIGNALED(status))
1361 log_warning("Worker ["PID_FMT"] terminated by signal %i (%s)", pid, WTERMSIG(status), signal_to_string(WTERMSIG(status)));
1362 else if (WIFSTOPPED(status)) {
1363 log_info("Worker ["PID_FMT"] stopped", pid);
1364 continue;
1365 } else if (WIFCONTINUED(status)) {
1366 log_info("Worker ["PID_FMT"] continued", pid);
1367 continue;
1368 } else
1369 log_warning("Worker ["PID_FMT"] exit with status 0x%04x", pid, status);
1370
1371 if ((!WIFEXITED(status) || WEXITSTATUS(status) != 0) && worker->event) {
1372 log_device_error(worker->event->dev, "Worker ["PID_FMT"] failed", pid);
1373
1374 /* delete state from disk */
1375 device_delete_db(worker->event->dev);
1376 device_tag_index(worker->event->dev, NULL, false);
1377
1378 if (manager->monitor) {
1379 /* forward kernel event without amending it */
1380 r = device_monitor_send_device(manager->monitor, NULL, worker->event->dev_kernel);
1381 if (r < 0)
1382 log_device_error_errno(worker->event->dev_kernel, r, "Failed to send back device to kernel: %m");
1383 }
1384 }
1385
1386 worker_free(worker);
1387 }
1388
1389 /* we can start new workers, try to schedule events */
1390 event_queue_start(manager);
1391
1392 /* Disable unnecessary cleanup event */
1393 if (hashmap_isempty(manager->workers)) {
1394 r = event_source_disable(manager->kill_workers_event);
1395 if (r < 0)
1396 log_warning_errno(r, "Failed to disable event source for cleaning up idle workers, ignoring: %m");
1397 }
1398
1399 return 1;
1400 }
1401
1402 static int on_post(sd_event_source *s, void *userdata) {
1403 Manager *manager = userdata;
1404
1405 assert(manager);
1406
1407 if (!LIST_IS_EMPTY(manager->events))
1408 return 1;
1409
1410 /* There are no pending events. Let's cleanup idle process. */
1411
1412 if (!hashmap_isempty(manager->workers)) {
1413 /* There are idle workers */
1414 (void) event_reset_time(manager->event, &manager->kill_workers_event, CLOCK_MONOTONIC,
1415 now(CLOCK_MONOTONIC) + 3 * USEC_PER_SEC, USEC_PER_SEC,
1416 on_kill_workers_event, manager, 0, "kill-workers-event", false);
1417 return 1;
1418 }
1419
1420 /* There are no idle workers. */
1421
1422 if (manager->exit)
1423 return sd_event_exit(manager->event, 0);
1424
1425 if (manager->cgroup)
1426 /* cleanup possible left-over processes in our cgroup */
1427 (void) cg_kill(SYSTEMD_CGROUP_CONTROLLER, manager->cgroup, SIGKILL, CGROUP_IGNORE_SELF, NULL, NULL, NULL);
1428
1429 return 1;
1430 }
1431
1432 static int listen_fds(int *ret_ctrl, int *ret_netlink) {
1433 int ctrl_fd = -1, netlink_fd = -1;
1434 int fd, n;
1435
1436 assert(ret_ctrl);
1437 assert(ret_netlink);
1438
1439 n = sd_listen_fds(true);
1440 if (n < 0)
1441 return n;
1442
1443 for (fd = SD_LISTEN_FDS_START; fd < n + SD_LISTEN_FDS_START; fd++) {
1444 if (sd_is_socket(fd, AF_LOCAL, SOCK_SEQPACKET, -1) > 0) {
1445 if (ctrl_fd >= 0)
1446 return -EINVAL;
1447 ctrl_fd = fd;
1448 continue;
1449 }
1450
1451 if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1) > 0) {
1452 if (netlink_fd >= 0)
1453 return -EINVAL;
1454 netlink_fd = fd;
1455 continue;
1456 }
1457
1458 return -EINVAL;
1459 }
1460
1461 *ret_ctrl = ctrl_fd;
1462 *ret_netlink = netlink_fd;
1463
1464 return 0;
1465 }
1466
1467 /*
1468 * read the kernel command line, in case we need to get into debug mode
1469 * udev.log_priority=<level> syslog priority
1470 * udev.children_max=<number of workers> events are fully serialized if set to 1
1471 * udev.exec_delay=<number of seconds> delay execution of every executed program
1472 * udev.event_timeout=<number of seconds> seconds to wait before terminating an event
1473 * udev.blockdev_read_only<=bool> mark all block devices read-only when they appear
1474 */
1475 static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
1476 int r;
1477
1478 assert(key);
1479
1480 if (proc_cmdline_key_streq(key, "udev.log_priority")) {
1481
1482 if (proc_cmdline_value_missing(key, value))
1483 return 0;
1484
1485 r = log_level_from_string(value);
1486 if (r >= 0)
1487 log_set_max_level(r);
1488
1489 } else if (proc_cmdline_key_streq(key, "udev.event_timeout")) {
1490
1491 if (proc_cmdline_value_missing(key, value))
1492 return 0;
1493
1494 r = parse_sec(value, &arg_event_timeout_usec);
1495
1496 } else if (proc_cmdline_key_streq(key, "udev.children_max")) {
1497
1498 if (proc_cmdline_value_missing(key, value))
1499 return 0;
1500
1501 r = safe_atou(value, &arg_children_max);
1502
1503 } else if (proc_cmdline_key_streq(key, "udev.exec_delay")) {
1504
1505 if (proc_cmdline_value_missing(key, value))
1506 return 0;
1507
1508 r = parse_sec(value, &arg_exec_delay_usec);
1509
1510 } else if (proc_cmdline_key_streq(key, "udev.timeout_signal")) {
1511
1512 if (proc_cmdline_value_missing(key, value))
1513 return 0;
1514
1515 r = signal_from_string(value);
1516 if (r > 0)
1517 arg_timeout_signal = r;
1518
1519 } else if (proc_cmdline_key_streq(key, "udev.blockdev_read_only")) {
1520
1521 if (!value)
1522 arg_blockdev_read_only = true;
1523 else {
1524 r = parse_boolean(value);
1525 if (r < 0)
1526 log_warning_errno(r, "Failed to parse udev.blockdev-read-only argument, ignoring: %s", value);
1527 else
1528 arg_blockdev_read_only = r;
1529 }
1530
1531 if (arg_blockdev_read_only)
1532 log_notice("All physical block devices will be marked read-only.");
1533
1534 return 0;
1535
1536 } else {
1537 if (startswith(key, "udev."))
1538 log_warning("Unknown udev kernel command line option \"%s\", ignoring.", key);
1539
1540 return 0;
1541 }
1542
1543 if (r < 0)
1544 log_warning_errno(r, "Failed to parse \"%s=%s\", ignoring: %m", key, value);
1545
1546 return 0;
1547 }
1548
1549 static int help(void) {
1550 _cleanup_free_ char *link = NULL;
1551 int r;
1552
1553 r = terminal_urlify_man("systemd-udevd.service", "8", &link);
1554 if (r < 0)
1555 return log_oom();
1556
1557 printf("%s [OPTIONS...]\n\n"
1558 "Rule-based manager for device events and files.\n\n"
1559 " -h --help Print this message\n"
1560 " -V --version Print version of the program\n"
1561 " -d --daemon Detach and run in the background\n"
1562 " -D --debug Enable debug output\n"
1563 " -c --children-max=INT Set maximum number of workers\n"
1564 " -e --exec-delay=SECONDS Seconds to wait before executing RUN=\n"
1565 " -t --event-timeout=SECONDS Seconds to wait before terminating an event\n"
1566 " -N --resolve-names=early|late|never\n"
1567 " When to resolve users and groups\n"
1568 "\nSee the %s for details.\n"
1569 , program_invocation_short_name
1570 , link
1571 );
1572
1573 return 0;
1574 }
1575
1576 static int parse_argv(int argc, char *argv[]) {
1577 enum {
1578 ARG_TIMEOUT_SIGNAL,
1579 };
1580
1581 static const struct option options[] = {
1582 { "daemon", no_argument, NULL, 'd' },
1583 { "debug", no_argument, NULL, 'D' },
1584 { "children-max", required_argument, NULL, 'c' },
1585 { "exec-delay", required_argument, NULL, 'e' },
1586 { "event-timeout", required_argument, NULL, 't' },
1587 { "resolve-names", required_argument, NULL, 'N' },
1588 { "help", no_argument, NULL, 'h' },
1589 { "version", no_argument, NULL, 'V' },
1590 { "timeout-signal", required_argument, NULL, ARG_TIMEOUT_SIGNAL },
1591 {}
1592 };
1593
1594 int c, r;
1595
1596 assert(argc >= 0);
1597 assert(argv);
1598
1599 while ((c = getopt_long(argc, argv, "c:de:Dt:N:hV", options, NULL)) >= 0) {
1600 switch (c) {
1601
1602 case 'd':
1603 arg_daemonize = true;
1604 break;
1605 case 'c':
1606 r = safe_atou(optarg, &arg_children_max);
1607 if (r < 0)
1608 log_warning_errno(r, "Failed to parse --children-max= value '%s', ignoring: %m", optarg);
1609 break;
1610 case 'e':
1611 r = parse_sec(optarg, &arg_exec_delay_usec);
1612 if (r < 0)
1613 log_warning_errno(r, "Failed to parse --exec-delay= value '%s', ignoring: %m", optarg);
1614 break;
1615 case ARG_TIMEOUT_SIGNAL:
1616 r = signal_from_string(optarg);
1617 if (r <= 0)
1618 log_warning_errno(r, "Failed to parse --timeout-signal= value '%s', ignoring: %m", optarg);
1619 else
1620 arg_timeout_signal = r;
1621
1622 break;
1623 case 't':
1624 r = parse_sec(optarg, &arg_event_timeout_usec);
1625 if (r < 0)
1626 log_warning_errno(r, "Failed to parse --event-timeout= value '%s', ignoring: %m", optarg);
1627 break;
1628 case 'D':
1629 arg_debug = true;
1630 break;
1631 case 'N': {
1632 ResolveNameTiming t;
1633
1634 t = resolve_name_timing_from_string(optarg);
1635 if (t < 0)
1636 log_warning("Invalid --resolve-names= value '%s', ignoring.", optarg);
1637 else
1638 arg_resolve_name_timing = t;
1639 break;
1640 }
1641 case 'h':
1642 return help();
1643 case 'V':
1644 printf("%s\n", GIT_VERSION);
1645 return 0;
1646 case '?':
1647 return -EINVAL;
1648 default:
1649 assert_not_reached("Unhandled option");
1650
1651 }
1652 }
1653
1654 return 1;
1655 }
1656
1657 static int manager_new(Manager **ret, int fd_ctrl, int fd_uevent, const char *cgroup) {
1658 _cleanup_(manager_freep) Manager *manager = NULL;
1659 int r;
1660
1661 assert(ret);
1662
1663 manager = new(Manager, 1);
1664 if (!manager)
1665 return log_oom();
1666
1667 *manager = (Manager) {
1668 .fd_inotify = -1,
1669 .worker_watch = { -1, -1 },
1670 .cgroup = cgroup,
1671 };
1672
1673 r = udev_ctrl_new_from_fd(&manager->ctrl, fd_ctrl);
1674 if (r < 0)
1675 return log_error_errno(r, "Failed to initialize udev control socket: %m");
1676
1677 r = udev_ctrl_enable_receiving(manager->ctrl);
1678 if (r < 0)
1679 return log_error_errno(r, "Failed to bind udev control socket: %m");
1680
1681 r = device_monitor_new_full(&manager->monitor, MONITOR_GROUP_KERNEL, fd_uevent);
1682 if (r < 0)
1683 return log_error_errno(r, "Failed to initialize device monitor: %m");
1684
1685 /* Bump receiver buffer, but only if we are not called via socket activation, as in that
1686 * case systemd sets the receive buffer size for us, and the value in the .socket unit
1687 * should take full effect. */
1688 if (fd_uevent < 0)
1689 (void) sd_device_monitor_set_receive_buffer_size(manager->monitor, 128 * 1024 * 1024);
1690
1691 r = device_monitor_enable_receiving(manager->monitor);
1692 if (r < 0)
1693 return log_error_errno(r, "Failed to bind netlink socket: %m");
1694
1695 *ret = TAKE_PTR(manager);
1696
1697 return 0;
1698 }
1699
1700 static int main_loop(Manager *manager) {
1701 int fd_worker, r;
1702
1703 manager->pid = getpid_cached();
1704
1705 /* unnamed socket from workers to the main daemon */
1706 r = socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, manager->worker_watch);
1707 if (r < 0)
1708 return log_error_errno(errno, "Failed to create socketpair for communicating with workers: %m");
1709
1710 fd_worker = manager->worker_watch[READ_END];
1711
1712 r = setsockopt_int(fd_worker, SOL_SOCKET, SO_PASSCRED, true);
1713 if (r < 0)
1714 return log_error_errno(r, "Failed to enable SO_PASSCRED: %m");
1715
1716 r = udev_watch_init();
1717 if (r < 0)
1718 return log_error_errno(r, "Failed to create inotify descriptor: %m");
1719 manager->fd_inotify = r;
1720
1721 udev_watch_restore();
1722
1723 /* block and listen to all signals on signalfd */
1724 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, SIGINT, SIGHUP, SIGCHLD, -1) >= 0);
1725
1726 r = sd_event_default(&manager->event);
1727 if (r < 0)
1728 return log_error_errno(r, "Failed to allocate event loop: %m");
1729
1730 r = sd_event_add_signal(manager->event, NULL, SIGINT, on_sigterm, manager);
1731 if (r < 0)
1732 return log_error_errno(r, "Failed to create SIGINT event source: %m");
1733
1734 r = sd_event_add_signal(manager->event, NULL, SIGTERM, on_sigterm, manager);
1735 if (r < 0)
1736 return log_error_errno(r, "Failed to create SIGTERM event source: %m");
1737
1738 r = sd_event_add_signal(manager->event, NULL, SIGHUP, on_sighup, manager);
1739 if (r < 0)
1740 return log_error_errno(r, "Failed to create SIGHUP event source: %m");
1741
1742 r = sd_event_add_signal(manager->event, NULL, SIGCHLD, on_sigchld, manager);
1743 if (r < 0)
1744 return log_error_errno(r, "Failed to create SIGCHLD event source: %m");
1745
1746 r = sd_event_set_watchdog(manager->event, true);
1747 if (r < 0)
1748 return log_error_errno(r, "Failed to create watchdog event source: %m");
1749
1750 r = udev_ctrl_attach_event(manager->ctrl, manager->event);
1751 if (r < 0)
1752 return log_error_errno(r, "Failed to attach event to udev control: %m");
1753
1754 r = udev_ctrl_start(manager->ctrl, on_ctrl_msg, manager);
1755 if (r < 0)
1756 return log_error_errno(r, "Failed to start device monitor: %m");
1757
1758 /* This needs to be after the inotify and uevent handling, to make sure
1759 * that the ping is send back after fully processing the pending uevents
1760 * (including the synthetic ones we may create due to inotify events).
1761 */
1762 r = sd_event_source_set_priority(udev_ctrl_get_event_source(manager->ctrl), SD_EVENT_PRIORITY_IDLE);
1763 if (r < 0)
1764 return log_error_errno(r, "Failed to set IDLE event priority for udev control event source: %m");
1765
1766 r = sd_event_add_io(manager->event, &manager->inotify_event, manager->fd_inotify, EPOLLIN, on_inotify, manager);
1767 if (r < 0)
1768 return log_error_errno(r, "Failed to create inotify event source: %m");
1769
1770 r = sd_device_monitor_attach_event(manager->monitor, manager->event);
1771 if (r < 0)
1772 return log_error_errno(r, "Failed to attach event to device monitor: %m");
1773
1774 r = sd_device_monitor_start(manager->monitor, on_uevent, manager);
1775 if (r < 0)
1776 return log_error_errno(r, "Failed to start device monitor: %m");
1777
1778 (void) sd_event_source_set_description(sd_device_monitor_get_event_source(manager->monitor), "device-monitor");
1779
1780 r = sd_event_add_io(manager->event, NULL, fd_worker, EPOLLIN, on_worker, manager);
1781 if (r < 0)
1782 return log_error_errno(r, "Failed to create worker event source: %m");
1783
1784 r = sd_event_add_post(manager->event, NULL, on_post, manager);
1785 if (r < 0)
1786 return log_error_errno(r, "Failed to create post event source: %m");
1787
1788 udev_builtin_init();
1789
1790 r = udev_rules_load(&manager->rules, arg_resolve_name_timing);
1791 if (!manager->rules)
1792 return log_error_errno(r, "Failed to read udev rules: %m");
1793
1794 r = udev_rules_apply_static_dev_perms(manager->rules);
1795 if (r < 0)
1796 log_error_errno(r, "Failed to apply permissions on static device nodes: %m");
1797
1798 (void) sd_notifyf(false,
1799 "READY=1\n"
1800 "STATUS=Processing with %u children at max", arg_children_max);
1801
1802 r = sd_event_loop(manager->event);
1803 if (r < 0)
1804 log_error_errno(r, "Event loop failed: %m");
1805
1806 sd_notify(false,
1807 "STOPPING=1\n"
1808 "STATUS=Shutting down...");
1809 return r;
1810 }
1811
1812 int run_udevd(int argc, char *argv[]) {
1813 _cleanup_free_ char *cgroup = NULL;
1814 _cleanup_(manager_freep) Manager *manager = NULL;
1815 int fd_ctrl = -1, fd_uevent = -1;
1816 int r;
1817
1818 log_set_target(LOG_TARGET_AUTO);
1819 log_open();
1820 udev_parse_config_full(&arg_children_max, &arg_exec_delay_usec, &arg_event_timeout_usec, &arg_resolve_name_timing, &arg_timeout_signal);
1821 log_parse_environment();
1822 log_open(); /* Done again to update after reading configuration. */
1823
1824 r = parse_argv(argc, argv);
1825 if (r <= 0)
1826 return r;
1827
1828 r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, PROC_CMDLINE_STRIP_RD_PREFIX);
1829 if (r < 0)
1830 log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
1831
1832 if (arg_debug) {
1833 log_set_target(LOG_TARGET_CONSOLE);
1834 log_set_max_level(LOG_DEBUG);
1835 }
1836
1837 log_set_max_level_realm(LOG_REALM_SYSTEMD, log_get_max_level());
1838
1839 r = must_be_root();
1840 if (r < 0)
1841 return r;
1842
1843 if (arg_children_max == 0) {
1844 unsigned long cpu_limit, mem_limit, cpu_count = 1;
1845
1846 r = cpus_in_affinity_mask();
1847 if (r < 0)
1848 log_warning_errno(r, "Failed to determine number of local CPUs, ignoring: %m");
1849 else
1850 cpu_count = r;
1851
1852 cpu_limit = cpu_count * 2 + 16;
1853 mem_limit = MAX(physical_memory() / (128UL*1024*1024), 10U);
1854
1855 arg_children_max = MIN(cpu_limit, mem_limit);
1856 arg_children_max = MIN(WORKER_NUM_MAX, arg_children_max);
1857
1858 log_debug("Set children_max to %u", arg_children_max);
1859 }
1860
1861 /* set umask before creating any file/directory */
1862 umask(022);
1863
1864 r = mac_selinux_init();
1865 if (r < 0)
1866 return r;
1867
1868 r = mkdir_errno_wrapper("/run/udev", 0755);
1869 if (r < 0 && r != -EEXIST)
1870 return log_error_errno(r, "Failed to create /run/udev: %m");
1871
1872 if (getppid() == 1 && sd_booted() > 0) {
1873 /* Get our own cgroup, we regularly kill everything udev has left behind.
1874 * We only do this on systemd systems, and only if we are directly spawned
1875 * by PID1. Otherwise we are not guaranteed to have a dedicated cgroup. */
1876 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &cgroup);
1877 if (r < 0) {
1878 if (IN_SET(r, -ENOENT, -ENOMEDIUM))
1879 log_debug_errno(r, "Dedicated cgroup not found: %m");
1880 else
1881 log_warning_errno(r, "Failed to get cgroup: %m");
1882 }
1883 }
1884
1885 r = listen_fds(&fd_ctrl, &fd_uevent);
1886 if (r < 0)
1887 return log_error_errno(r, "Failed to listen on fds: %m");
1888
1889 r = manager_new(&manager, fd_ctrl, fd_uevent, cgroup);
1890 if (r < 0)
1891 return log_error_errno(r, "Failed to create manager: %m");
1892
1893 if (arg_daemonize) {
1894 pid_t pid;
1895
1896 log_info("Starting version " GIT_VERSION);
1897
1898 /* connect /dev/null to stdin, stdout, stderr */
1899 if (log_get_max_level() < LOG_DEBUG) {
1900 r = make_null_stdio();
1901 if (r < 0)
1902 log_warning_errno(r, "Failed to redirect standard streams to /dev/null: %m");
1903 }
1904
1905 pid = fork();
1906 if (pid < 0)
1907 return log_error_errno(errno, "Failed to fork daemon: %m");
1908 if (pid > 0)
1909 /* parent */
1910 return 0;
1911
1912 /* child */
1913 (void) setsid();
1914 }
1915
1916 return main_loop(manager);
1917 }