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