]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/udev/udevd.c
sd-event: make inotify event work after the process is forked
[thirdparty/systemd.git] / src / udev / udevd.c
CommitLineData
f13467ec 1/* SPDX-License-Identifier: GPL-2.0-or-later */
7fafc032 2/*
810adae9
LP
3 * Copyright © 2004 Chris Friesen <chris_friesen@sympatico.ca>
4 * Copyright © 2009 Canonical Ltd.
5 * Copyright © 2009 Scott James Remnant <scott@netsplit.com>
7fafc032
KS
6 */
7
7fafc032 8#include <errno.h>
618234a5
LP
9#include <fcntl.h>
10#include <getopt.h>
618234a5
LP
11#include <stdbool.h>
12#include <stddef.h>
7fafc032
KS
13#include <stdio.h>
14#include <stdlib.h>
618234a5 15#include <sys/epoll.h>
3ebdb81e 16#include <sys/file.h>
618234a5
LP
17#include <sys/inotify.h>
18#include <sys/ioctl.h>
19#include <sys/mount.h>
1e03b754 20#include <sys/prctl.h>
1e03b754 21#include <sys/signalfd.h>
dc117daa 22#include <sys/stat.h>
618234a5
LP
23#include <sys/time.h>
24#include <sys/wait.h>
25#include <unistd.h>
7fafc032 26
392ef7a2 27#include "sd-daemon.h"
693d371d 28#include "sd-event.h"
8314de1d 29
b5efdb8a 30#include "alloc-util.h"
a1f4fd38 31#include "cgroup-setup.h"
194bbe33 32#include "cgroup-util.h"
618234a5 33#include "cpu-set-util.h"
5ba2dc25 34#include "dev-setup.h"
7f2e3a14 35#include "device-monitor-private.h"
abde5ea8 36#include "device-private.h"
70068602 37#include "device-util.h"
6467bda5 38#include "errno-list.h"
6d63048a 39#include "event-util.h"
3ffd4af2 40#include "fd-util.h"
a5c32cff 41#include "fileio.h"
f97b34a6 42#include "format-util.h"
f4f15635 43#include "fs-util.h"
a505965d 44#include "hashmap.h"
9e5fd717 45#include "inotify-util.h"
c004493c 46#include "io-util.h"
eefc66aa 47#include "limits-util.h"
40a57716 48#include "list.h"
0c5a109a 49#include "main-func.h"
5ea78a39 50#include "mkdir.h"
618234a5 51#include "netlink-util.h"
6bedfcbb 52#include "parse-util.h"
a1f4fd38 53#include "path-util.h"
294bf0c3 54#include "pretty-print.h"
4e731273 55#include "proc-cmdline.h"
618234a5
LP
56#include "process-util.h"
57#include "selinux-util.h"
58#include "signal-util.h"
8f328d36 59#include "socket-util.h"
07630cea 60#include "string-util.h"
49fe5c09 61#include "strv.h"
5ea78a39 62#include "strxcpyx.h"
46f0fbd8 63#include "syslog-util.h"
63e2d171 64#include "udevd.h"
07a26e42 65#include "udev-builtin.h"
7d68eb1b 66#include "udev-ctrl.h"
25de7aa7 67#include "udev-event.h"
618234a5 68#include "udev-util.h"
70068602 69#include "udev-watch.h"
ee104e11 70#include "user-util.h"
47350c5f 71#include "version.h"
7fafc032 72
88bd5a32 73#define WORKER_NUM_MAX 2048U
5d354e52
YW
74#define EVENT_RETRY_INTERVAL_USEC (200 * USEC_PER_MSEC)
75#define EVENT_RETRY_TIMEOUT_USEC (3 * USEC_PER_MINUTE)
88bd5a32 76
bba7a484
TG
77static bool arg_debug = false;
78static int arg_daemonize = false;
c4d44cba 79static ResolveNameTiming arg_resolve_name_timing = RESOLVE_NAME_EARLY;
216e8bbe 80static unsigned arg_children_max = 0;
6b92f429 81static usec_t arg_exec_delay_usec = 0;
bba7a484 82static usec_t arg_event_timeout_usec = 180 * USEC_PER_SEC;
e2099267 83static int arg_timeout_signal = SIGKILL;
95ac5230 84static bool arg_blockdev_read_only = false;
c0c6806b 85
d9239923
YW
86typedef struct Event Event;
87typedef struct Worker Worker;
88
c0c6806b 89typedef struct Manager {
693d371d 90 sd_event *event;
c0c6806b 91 Hashmap *workers;
d9239923 92 LIST_HEAD(Event, events);
a1f4fd38 93 char *cgroup;
cb49a4f2 94 pid_t pid; /* the process that originally allocated the manager object */
1a0bd015 95 int log_level;
c0c6806b 96
9a07157d 97 UdevRules *rules;
9b5150b6 98 Hashmap *properties;
c0c6806b 99
0bed242c
YW
100 sd_netlink *rtnl;
101
7f2e3a14 102 sd_device_monitor *monitor;
e0d61dac 103 UdevCtrl *ctrl;
e237d8cb
TG
104 int worker_watch[2];
105
df7ee959
YW
106 /* used by udev-watch */
107 int inotify_fd;
693d371d 108 sd_event_source *inotify_event;
df7ee959 109
eca195ec 110 sd_event_source *kill_workers_event;
693d371d 111
7c4c7e89
TG
112 usec_t last_usec;
113
481f24d1
YW
114 bool stop_exec_queue;
115 bool exit;
c0c6806b 116} Manager;
1e03b754 117
d9239923 118typedef enum EventState {
912541b0
KS
119 EVENT_UNDEF,
120 EVENT_QUEUED,
121 EVENT_RUNNING,
d9239923 122} EventState;
1e03b754 123
d9239923 124typedef struct Event {
cb49a4f2 125 Manager *manager;
d9239923
YW
126 Worker *worker;
127 EventState state;
eb546b35
YW
128
129 sd_device *dev;
eb546b35 130
0c3d8182 131 sd_device_action_t action;
eb546b35 132 uint64_t seqnum;
a1fa99d8 133 uint64_t blocker_seqnum;
5d354e52
YW
134 usec_t retry_again_next_usec;
135 usec_t retry_again_timeout_usec;
d8f462b4
YW
136
137 sd_event_source *timeout_warning_event;
138 sd_event_source *timeout_event;
eb546b35 139
d9239923
YW
140 LIST_FIELDS(Event, event);
141} Event;
1e03b754 142
d9239923 143typedef enum WorkerState {
912541b0
KS
144 WORKER_UNDEF,
145 WORKER_RUNNING,
146 WORKER_IDLE,
147 WORKER_KILLED,
f257a8fc 148 WORKER_KILLING,
d9239923 149} WorkerState;
1e03b754 150
d9239923 151typedef struct Worker {
c0c6806b 152 Manager *manager;
912541b0 153 pid_t pid;
7f2e3a14 154 sd_device_monitor *monitor;
d9239923
YW
155 WorkerState state;
156 Event *event;
157} Worker;
1e03b754
KS
158
159/* passed from worker to main process */
5d354e52 160typedef enum EventResult {
6467bda5
YW
161 EVENT_RESULT_NERRNO_MIN = -ERRNO_MAX,
162 EVENT_RESULT_NERRNO_MAX = -1,
163 EVENT_RESULT_EXIT_STATUS_BASE = 0,
164 EVENT_RESULT_EXIT_STATUS_MAX = 255,
165 EVENT_RESULT_TRY_AGAIN = 256, /* when the block device is locked by another process. */
166 EVENT_RESULT_SIGNAL_BASE = 257,
167 EVENT_RESULT_SIGNAL_MAX = EVENT_RESULT_SIGNAL_BASE + _NSIG,
5d354e52 168 _EVENT_RESULT_MAX,
6467bda5 169 _EVENT_RESULT_INVALID = -EINVAL,
5d354e52 170} EventResult;
1e03b754 171
5393c528 172static Event *event_free(Event *event) {
c6aa11f2 173 if (!event)
5393c528 174 return NULL;
ba47b71c 175
40a57716 176 assert(event->manager);
c6aa11f2 177
40a57716 178 LIST_REMOVE(event, event->manager->events, event);
eb546b35 179 sd_device_unref(event->dev);
c6aa11f2 180
72151060
YW
181 /* Do not use sd_event_source_disable_unref() here, as this is called by both workers and the
182 * main process. */
183 sd_event_source_unref(event->timeout_warning_event);
184 sd_event_source_unref(event->timeout_event);
693d371d 185
c6aa11f2
TG
186 if (event->worker)
187 event->worker->event = NULL;
188
5393c528 189 return mfree(event);
aa8734ff 190}
7a770250 191
419ec631 192static void event_queue_cleanup(Manager *manager, EventState match_state) {
80a226b2 193 LIST_FOREACH(event, event, manager->events) {
419ec631
YW
194 if (match_state != EVENT_UNDEF && match_state != event->state)
195 continue;
196
197 event_free(event);
198 }
199}
200
d9239923 201static Worker *worker_free(Worker *worker) {
c6aa11f2 202 if (!worker)
75db809a 203 return NULL;
bc113de9 204
c0c6806b
TG
205 assert(worker->manager);
206
4a0b58c4 207 hashmap_remove(worker->manager->workers, PID_TO_PTR(worker->pid));
7f2e3a14 208 sd_device_monitor_unref(worker->monitor);
c6aa11f2
TG
209 event_free(worker->event);
210
75db809a 211 return mfree(worker);
ff2c503d
KS
212}
213
d9239923
YW
214DEFINE_TRIVIAL_CLEANUP_FUNC(Worker*, worker_free);
215DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(worker_hash_op, void, trivial_hash_func, trivial_compare_func, Worker, worker_free);
fc465079 216
419ec631
YW
217static void manager_clear_for_worker(Manager *manager) {
218 assert(manager);
219
f777e745
YW
220 /* Do not use sd_event_source_disable_unref() here, as this is called by both workers and the
221 * main process. */
222 manager->inotify_event = sd_event_source_unref(manager->inotify_event);
223 manager->kill_workers_event = sd_event_source_unref(manager->kill_workers_event);
419ec631
YW
224
225 manager->event = sd_event_unref(manager->event);
226
227 manager->workers = hashmap_free(manager->workers);
228 event_queue_cleanup(manager, EVENT_UNDEF);
229
230 manager->monitor = sd_device_monitor_unref(manager->monitor);
231 manager->ctrl = udev_ctrl_unref(manager->ctrl);
232
233 manager->worker_watch[READ_END] = safe_close(manager->worker_watch[READ_END]);
234}
235
236static Manager* manager_free(Manager *manager) {
237 if (!manager)
238 return NULL;
239
240 udev_builtin_exit();
241
419ec631
YW
242 manager_clear_for_worker(manager);
243
244 sd_netlink_unref(manager->rtnl);
245
246 hashmap_free_free_free(manager->properties);
247 udev_rules_free(manager->rules);
248
249 safe_close(manager->inotify_fd);
250 safe_close_pair(manager->worker_watch);
251
a1f4fd38 252 free(manager->cgroup);
419ec631
YW
253 return mfree(manager);
254}
255
256DEFINE_TRIVIAL_CLEANUP_FUNC(Manager*, manager_free);
257
d9239923
YW
258static int worker_new(Worker **ret, Manager *manager, sd_device_monitor *worker_monitor, pid_t pid) {
259 _cleanup_(worker_freep) Worker *worker = NULL;
a505965d 260 int r;
3a19b32a
TG
261
262 assert(ret);
c0c6806b 263 assert(manager);
3a19b32a
TG
264 assert(worker_monitor);
265 assert(pid > 1);
266
d4053464
YW
267 /* close monitor, but keep address around */
268 device_monitor_disconnect(worker_monitor);
269
d9239923 270 worker = new(Worker, 1);
3a19b32a
TG
271 if (!worker)
272 return -ENOMEM;
273
d9239923 274 *worker = (Worker) {
d4053464
YW
275 .manager = manager,
276 .monitor = sd_device_monitor_ref(worker_monitor),
277 .pid = pid,
278 };
a505965d 279
92a74c47 280 r = hashmap_ensure_put(&manager->workers, &worker_hash_op, PID_TO_PTR(pid), worker);
a505965d
TG
281 if (r < 0)
282 return r;
283
ae2a15bc 284 *ret = TAKE_PTR(worker);
3a19b32a
TG
285
286 return 0;
287}
288
419ec631
YW
289static void manager_kill_workers(Manager *manager, bool force) {
290 Worker *worker;
4fa4d885 291
419ec631 292 assert(manager);
4fa4d885 293
419ec631
YW
294 HASHMAP_FOREACH(worker, manager->workers) {
295 if (worker->state == WORKER_KILLED)
296 continue;
4fa4d885 297
419ec631
YW
298 if (worker->state == WORKER_RUNNING && !force) {
299 worker->state = WORKER_KILLING;
300 continue;
301 }
4fa4d885 302
419ec631
YW
303 worker->state = WORKER_KILLED;
304 (void) kill(worker->pid, SIGTERM);
305 }
4fa4d885
TG
306}
307
419ec631
YW
308static void manager_exit(Manager *manager) {
309 assert(manager);
693d371d 310
419ec631 311 manager->exit = true;
693d371d 312
419ec631
YW
313 sd_notify(false,
314 "STOPPING=1\n"
315 "STATUS=Starting shutdown...");
39c19cf1 316
419ec631
YW
317 /* close sources of new events and discard buffered events */
318 manager->ctrl = udev_ctrl_unref(manager->ctrl);
0bed242c 319
9612da36 320 manager->inotify_event = sd_event_source_disable_unref(manager->inotify_event);
419ec631 321 manager->inotify_fd = safe_close(manager->inotify_fd);
0bed242c 322
7f2e3a14 323 manager->monitor = sd_device_monitor_unref(manager->monitor);
0bed242c 324
419ec631
YW
325 /* discard queued events and kill workers */
326 event_queue_cleanup(manager, EVENT_QUEUED);
327 manager_kill_workers(manager, true);
0bed242c
YW
328}
329
4bf4f50f
ZJS
330static void notify_ready(void) {
331 int r;
332
333 r = sd_notifyf(false,
334 "READY=1\n"
335 "STATUS=Processing with %u children at max", arg_children_max);
336 if (r < 0)
337 log_warning_errno(r, "Failed to send readiness notification, ignoring: %m");
338}
339
419ec631
YW
340/* reload requested, HUP signal received, rules changed, builtin changed */
341static void manager_reload(Manager *manager) {
419ec631 342 assert(manager);
b2d21d93 343
419ec631
YW
344 sd_notify(false,
345 "RELOADING=1\n"
346 "STATUS=Flushing configuration...");
76e62a4d 347
419ec631
YW
348 manager_kill_workers(manager, false);
349 manager->rules = udev_rules_free(manager->rules);
350 udev_builtin_exit();
693d371d 351
4bf4f50f 352 notify_ready();
419ec631 353}
e237d8cb 354
419ec631
YW
355static int on_kill_workers_event(sd_event_source *s, uint64_t usec, void *userdata) {
356 Manager *manager = userdata;
e237d8cb 357
419ec631 358 assert(manager);
e237d8cb 359
419ec631
YW
360 log_debug("Cleanup idle workers");
361 manager_kill_workers(manager, false);
e237d8cb 362
419ec631
YW
363 return 1;
364}
e237d8cb 365
6467bda5 366static void device_broadcast(sd_device_monitor *monitor, sd_device *dev, int result) {
c17ab900
YW
367 int r;
368
369 assert(dev);
370
371 /* On exit, manager->monitor is already NULL. */
372 if (!monitor)
373 return;
374
6467bda5
YW
375 if (result != 0) {
376 (void) device_add_property(dev, "UDEV_WORKER_FAILED", "1");
377
378 switch (result) {
fb544617
YW
379 case EVENT_RESULT_NERRNO_MIN ... EVENT_RESULT_NERRNO_MAX: {
380 const char *str;
381
6467bda5 382 (void) device_add_propertyf(dev, "UDEV_WORKER_ERRNO", "%i", -result);
6467bda5 383
fb544617
YW
384 str = errno_to_name(result);
385 if (str)
386 (void) device_add_property(dev, "UDEV_WORKER_ERRNO_NAME", str);
387 break;
388 }
6467bda5
YW
389 case EVENT_RESULT_EXIT_STATUS_BASE ... EVENT_RESULT_EXIT_STATUS_MAX:
390 (void) device_add_propertyf(dev, "UDEV_WORKER_EXIT_STATUS", "%i", result - EVENT_RESULT_EXIT_STATUS_BASE);
391 break;
392
393 case EVENT_RESULT_TRY_AGAIN:
394 assert_not_reached();
395 break;
396
fb544617
YW
397 case EVENT_RESULT_SIGNAL_BASE ... EVENT_RESULT_SIGNAL_MAX: {
398 const char *str;
399
6467bda5 400 (void) device_add_propertyf(dev, "UDEV_WORKER_SIGNAL", "%i", result - EVENT_RESULT_SIGNAL_BASE);
6467bda5 401
fb544617
YW
402 str = signal_to_string(result - EVENT_RESULT_SIGNAL_BASE);
403 if (str)
404 (void) device_add_property(dev, "UDEV_WORKER_SIGNAL_NAME", str);
405 break;
406 }
6467bda5
YW
407 default:
408 log_device_warning(dev, "Unknown event result \"%i\", ignoring.", result);
409 }
410 }
411
c17ab900
YW
412 r = device_monitor_send_device(monitor, NULL, dev);
413 if (r < 0)
414 log_device_warning_errno(dev, r,
415 "Failed to broadcast event to libudev listeners, ignoring: %m");
416}
417
6467bda5 418static int worker_send_result(Manager *manager, int result) {
5d354e52
YW
419 assert(manager);
420 assert(manager->worker_watch[WRITE_END] >= 0);
9a73bd7c 421
5d354e52 422 return loop_write(manager->worker_watch[WRITE_END], &result, sizeof(result), false);
9a73bd7c
TG
423}
424
78e278ad 425static int device_get_whole_disk(sd_device *dev, sd_device **ret_device, const char **ret_devname) {
b97897e3
YW
426 const char *val;
427 int r;
fee854ee 428
0bed242c 429 assert(dev);
a1130022
LP
430
431 if (device_for_action(dev, SD_DEVICE_REMOVE))
7b7959fb 432 goto irrelevant;
0bed242c 433
b97897e3
YW
434 r = sd_device_get_subsystem(dev, &val);
435 if (r < 0)
436 return log_device_debug_errno(dev, r, "Failed to get subsystem: %m");
437
438 if (!streq(val, "block"))
7b7959fb 439 goto irrelevant;
fee854ee 440
b97897e3
YW
441 r = sd_device_get_sysname(dev, &val);
442 if (r < 0)
443 return log_device_debug_errno(dev, r, "Failed to get sysname: %m");
444
a9e83209
YW
445 /* Exclude the following devices:
446 * For "dm-", see the comment added by e918a1b5a94f270186dca59156354acd2a596494.
447 * For "md", see the commit message of 2e5b17d01347d3c3118be2b8ad63d20415dbb1f0,
448 * but not sure the assumption is still valid even when partitions are created on the md
449 * devices, surprisingly which seems to be possible, see PR #22973.
450 * For "drbd", see the commit message of fee854ee8ccde0cd28e0f925dea18cce35f3993d. */
49fe5c09 451 if (STARTSWITH_SET(val, "dm-", "md", "drbd"))
7b7959fb 452 goto irrelevant;
0bed242c 453
b97897e3
YW
454 r = sd_device_get_devtype(dev, &val);
455 if (r < 0 && r != -ENOENT)
456 return log_device_debug_errno(dev, r, "Failed to get devtype: %m");
457 if (r >= 0 && streq(val, "partition")) {
458 r = sd_device_get_parent(dev, &dev);
20ba5a3f
YW
459 if (r == -ENOENT) /* The device may be already removed. */
460 goto irrelevant;
b97897e3
YW
461 if (r < 0)
462 return log_device_debug_errno(dev, r, "Failed to get parent device: %m");
463 }
0bed242c 464
b97897e3
YW
465 r = sd_device_get_devname(dev, &val);
466 if (r == -ENOENT)
7b7959fb 467 goto irrelevant;
b97897e3
YW
468 if (r < 0)
469 return log_device_debug_errno(dev, r, "Failed to get devname: %m");
0bed242c 470
78e278ad
YW
471 if (ret_device)
472 *ret_device = dev;
473 if (ret_devname)
474 *ret_devname = val;
7b7959fb
YW
475 return 1;
476
477irrelevant:
78e278ad
YW
478 if (ret_device)
479 *ret_device = NULL;
480 if (ret_devname)
481 *ret_devname = NULL;
7b7959fb
YW
482 return 0;
483}
484
03a24ce7 485static int worker_lock_whole_disk(sd_device *dev, int *ret_fd) {
7b7959fb 486 _cleanup_close_ int fd = -1;
78e278ad 487 sd_device *dev_whole_disk;
7b7959fb
YW
488 const char *val;
489 int r;
490
491 assert(dev);
492 assert(ret_fd);
493
494 /* Take a shared lock on the device node; this establishes a concept of device "ownership" to
495 * serialize device access. External processes holding an exclusive lock will cause udev to skip the
496 * event handling; in the case udev acquired the lock, the external process can block until udev has
497 * finished its event handling. */
498
78e278ad 499 r = device_get_whole_disk(dev, &dev_whole_disk, &val);
7b7959fb
YW
500 if (r < 0)
501 return r;
502 if (r == 0)
503 goto nolock;
504
78e278ad 505 fd = sd_device_open(dev_whole_disk, O_RDONLY|O_CLOEXEC|O_NONBLOCK);
b97897e3 506 if (fd < 0) {
78e278ad 507 bool ignore = ERRNO_IS_DEVICE_ABSENT(fd);
ef400c38 508
78e278ad 509 log_device_debug_errno(dev, fd, "Failed to open '%s'%s: %m", val, ignore ? ", ignoring" : "");
7b7959fb 510 if (!ignore)
78e278ad 511 return fd;
7b7959fb
YW
512
513 goto nolock;
b97897e3 514 }
0bed242c
YW
515
516 if (flock(fd, LOCK_SH|LOCK_NB) < 0)
b97897e3 517 return log_device_debug_errno(dev, errno, "Failed to flock(%s): %m", val);
0bed242c
YW
518
519 *ret_fd = TAKE_FD(fd);
520 return 1;
7b7959fb
YW
521
522nolock:
523 *ret_fd = -1;
524 return 0;
fee854ee
RK
525}
526
95ac5230
LP
527static int worker_mark_block_device_read_only(sd_device *dev) {
528 _cleanup_close_ int fd = -1;
529 const char *val;
530 int state = 1, r;
531
532 assert(dev);
533
534 if (!arg_blockdev_read_only)
535 return 0;
536
537 /* Do this only once, when the block device is new. If the device is later retriggered let's not
538 * toggle the bit again, so that people can boot up with full read-only mode and then unset the bit
539 * for specific devices only. */
a1130022 540 if (!device_for_action(dev, SD_DEVICE_ADD))
95ac5230
LP
541 return 0;
542
543 r = sd_device_get_subsystem(dev, &val);
544 if (r < 0)
545 return log_device_debug_errno(dev, r, "Failed to get subsystem: %m");
546
547 if (!streq(val, "block"))
548 return 0;
549
550 r = sd_device_get_sysname(dev, &val);
551 if (r < 0)
552 return log_device_debug_errno(dev, r, "Failed to get sysname: %m");
553
554 /* Exclude synthetic devices for now, this is supposed to be a safety feature to avoid modification
555 * of physical devices, and what sits on top of those doesn't really matter if we don't allow the
cb713f16 556 * underlying block devices to receive changes. */
95ac5230
LP
557 if (STARTSWITH_SET(val, "dm-", "md", "drbd", "loop", "nbd", "zram"))
558 return 0;
559
78e278ad 560 fd = sd_device_open(dev, O_RDONLY|O_CLOEXEC|O_NONBLOCK);
95ac5230 561 if (fd < 0)
78e278ad 562 return log_device_debug_errno(dev, fd, "Failed to open '%s', ignoring: %m", val);
95ac5230
LP
563
564 if (ioctl(fd, BLKROSET, &state) < 0)
565 return log_device_warning_errno(dev, errno, "Failed to mark block device '%s' read-only: %m", val);
566
567 log_device_info(dev, "Successfully marked block device '%s' read-only.", val);
568 return 0;
569}
570
abde5ea8 571static int worker_process_device(Manager *manager, sd_device *dev) {
2e088715 572 _cleanup_(udev_event_freep) UdevEvent *udev_event = NULL;
0bed242c
YW
573 _cleanup_close_ int fd_lock = -1;
574 int r;
912541b0 575
0bed242c
YW
576 assert(manager);
577 assert(dev);
578
b2d9e58f 579 log_device_uevent(dev, "Processing device");
abde5ea8 580
1a0bd015 581 udev_event = udev_event_new(dev, arg_exec_delay_usec, manager->rtnl, manager->log_level);
0bed242c
YW
582 if (!udev_event)
583 return -ENOMEM;
584
5d354e52
YW
585 /* If this is a block device and the device is locked currently via the BSD advisory locks,
586 * someone else is using it exclusively. We don't run our udev rules now to not interfere.
587 * Instead of processing the event, we requeue the event and will try again after a delay.
588 *
589 * The user-facing side of this: https://systemd.io/BLOCK_DEVICE_LOCKING */
03a24ce7 590 r = worker_lock_whole_disk(dev, &fd_lock);
6467bda5
YW
591 if (r == -EAGAIN)
592 return EVENT_RESULT_TRY_AGAIN;
b6aab8ef 593 if (r < 0)
0bed242c 594 return r;
912541b0 595
95ac5230
LP
596 (void) worker_mark_block_device_read_only(dev);
597
0bed242c 598 /* apply rules, create node, symlinks */
df7ee959
YW
599 r = udev_event_execute_rules(
600 udev_event,
601 manager->inotify_fd,
602 arg_event_timeout_usec,
603 arg_timeout_signal,
604 manager->properties,
605 manager->rules);
99058cd6
YW
606 if (r < 0)
607 return r;
608
e2099267 609 udev_event_execute_run(udev_event, arg_event_timeout_usec, arg_timeout_signal);
2dd9f98d 610
0bed242c
YW
611 if (!manager->rtnl)
612 /* in case rtnl was initialized */
613 manager->rtnl = sd_netlink_ref(udev_event->rtnl);
912541b0 614
0d77bc4a
YW
615 r = udev_event_process_inotify_watch(udev_event, manager->inotify_fd);
616 if (r < 0)
617 return r;
912541b0 618
b2d9e58f 619 log_device_uevent(dev, "Device processed");
0bed242c
YW
620 return 0;
621}
912541b0 622
e2130348
YW
623static int worker_device_monitor_handler(sd_device_monitor *monitor, sd_device *dev, void *userdata) {
624 Manager *manager = userdata;
625 int r;
626
627 assert(dev);
628 assert(manager);
629
630 r = worker_process_device(manager, dev);
6467bda5 631 if (r == EVENT_RESULT_TRY_AGAIN)
5d354e52 632 /* if we couldn't acquire the flock(), then requeue the event */
6467bda5
YW
633 log_device_debug(dev, "Block device is currently locked, requeueing the event.");
634 else {
635 if (r < 0)
636 log_device_warning_errno(dev, r, "Failed to process device, ignoring: %m");
e2130348 637
5abee64e 638 /* send processed event back to libudev listeners */
6467bda5
YW
639 device_broadcast(monitor, dev, r);
640 }
e2130348
YW
641
642 /* send udevd the result of the event execution */
6467bda5 643 r = worker_send_result(manager, r);
e2130348
YW
644 if (r < 0)
645 log_device_warning_errno(dev, r, "Failed to send signal to main daemon, ignoring: %m");
646
1a0bd015 647 /* Reset the log level, as it might be changed by "OPTIONS=log_level=". */
3cc6b14a 648 log_set_max_level(manager->log_level);
1a0bd015 649
e2130348
YW
650 return 1;
651}
652
7f2e3a14
YW
653static int worker_main(Manager *_manager, sd_device_monitor *monitor, sd_device *first_device) {
654 _cleanup_(sd_device_unrefp) sd_device *dev = first_device;
0bed242c 655 _cleanup_(manager_freep) Manager *manager = _manager;
44dcf454 656 int r;
145dae7e 657
0bed242c
YW
658 assert(manager);
659 assert(monitor);
660 assert(dev);
912541b0 661
44ee03d1 662 assert_se(unsetenv("NOTIFY_SOCKET") == 0);
3b64e4d4 663
e2130348
YW
664 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, -1) >= 0);
665
666 /* Reset OOM score, we only protect the main daemon. */
667 r = set_oom_score_adjust(0);
668 if (r < 0)
669 log_debug_errno(r, "Failed to reset OOM score, ignoring: %m");
912541b0 670
7802194a 671 /* Clear unnecessary data in Manager object. */
e2130348 672 manager_clear_for_worker(manager);
3ebdb81e 673
e2130348
YW
674 r = sd_event_new(&manager->event);
675 if (r < 0)
676 return log_error_errno(r, "Failed to allocate event loop: %m");
912541b0 677
e2130348
YW
678 r = sd_event_add_signal(manager->event, NULL, SIGTERM, NULL, NULL);
679 if (r < 0)
680 return log_error_errno(r, "Failed to set SIGTERM event: %m");
4c83d994 681
e2130348
YW
682 r = sd_device_monitor_attach_event(monitor, manager->event);
683 if (r < 0)
684 return log_error_errno(r, "Failed to attach event loop to device monitor: %m");
912541b0 685
e2130348 686 r = sd_device_monitor_start(monitor, worker_device_monitor_handler, manager);
0bed242c 687 if (r < 0)
e2130348 688 return log_error_errno(r, "Failed to start device monitor: %m");
912541b0 689
e2130348 690 (void) sd_event_source_set_description(sd_device_monitor_get_event_source(monitor), "worker-device-monitor");
b66f29a1 691
e2130348
YW
692 /* Process first device */
693 (void) worker_device_monitor_handler(monitor, dev, manager);
912541b0 694
e2130348
YW
695 r = sd_event_loop(manager->event);
696 if (r < 0)
697 return log_error_errno(r, "Event loop failed: %m");
698
44dcf454 699 return 0;
0bed242c
YW
700}
701
419ec631
YW
702static int on_event_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
703 Event *event = userdata;
704
705 assert(event);
706 assert(event->worker);
707
708 kill_and_sigcont(event->worker->pid, arg_timeout_signal);
709 event->worker->state = WORKER_KILLED;
710
711 log_device_error(event->dev, "Worker ["PID_FMT"] processing SEQNUM=%"PRIu64" killed", event->worker->pid, event->seqnum);
712
713 return 1;
714}
715
716static int on_event_timeout_warning(sd_event_source *s, uint64_t usec, void *userdata) {
717 Event *event = userdata;
718
719 assert(event);
720 assert(event->worker);
721
722 log_device_warning(event->dev, "Worker ["PID_FMT"] processing SEQNUM=%"PRIu64" is taking a long time", event->worker->pid, event->seqnum);
723
724 return 1;
725}
726
727static void worker_attach_event(Worker *worker, Event *event) {
728 sd_event *e;
729
730 assert(worker);
731 assert(worker->manager);
732 assert(event);
733 assert(!event->worker);
734 assert(!worker->event);
735
736 worker->state = WORKER_RUNNING;
737 worker->event = event;
738 event->state = EVENT_RUNNING;
739 event->worker = worker;
740
741 e = worker->manager->event;
742
743 (void) sd_event_add_time_relative(e, &event->timeout_warning_event, CLOCK_MONOTONIC,
744 udev_warn_timeout(arg_event_timeout_usec), USEC_PER_SEC,
745 on_event_timeout_warning, event);
746
747 (void) sd_event_add_time_relative(e, &event->timeout_event, CLOCK_MONOTONIC,
748 arg_event_timeout_usec, USEC_PER_SEC,
749 on_event_timeout, event);
750}
751
d9239923 752static int worker_spawn(Manager *manager, Event *event) {
7f2e3a14 753 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *worker_monitor = NULL;
d9239923 754 Worker *worker;
0bed242c 755 pid_t pid;
7443654e 756 int r;
0bed242c
YW
757
758 /* listen for new events */
7f2e3a14
YW
759 r = device_monitor_new_full(&worker_monitor, MONITOR_GROUP_NONE, -1);
760 if (r < 0)
761 return r;
7443654e 762
0bed242c 763 /* allow the main daemon netlink address to send devices to the worker */
7f2e3a14
YW
764 r = device_monitor_allow_unicast_sender(worker_monitor, manager->monitor);
765 if (r < 0)
766 return log_error_errno(r, "Worker: Failed to set unicast sender: %m");
767
768 r = device_monitor_enable_receiving(worker_monitor);
0bed242c 769 if (r < 0)
7f2e3a14 770 return log_error_errno(r, "Worker: Failed to enable receiving of device: %m");
0bed242c 771
ff86c92e 772 r = safe_fork(NULL, FORK_DEATHSIG, &pid);
7443654e
YW
773 if (r < 0) {
774 event->state = EVENT_QUEUED;
775 return log_error_errno(r, "Failed to fork() worker: %m");
776 }
777 if (r == 0) {
b428efa5
MS
778 DEVICE_TRACE_POINT(worker_spawned, event->dev, getpid());
779
7443654e 780 /* Worker process */
eb546b35 781 r = worker_main(manager, worker_monitor, sd_device_ref(event->dev));
baa30fbc 782 log_close();
8b46c3fc 783 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
912541b0 784 }
e03c7cc2 785
7443654e
YW
786 r = worker_new(&worker, manager, worker_monitor, pid);
787 if (r < 0)
788 return log_error_errno(r, "Failed to create worker object: %m");
e03c7cc2 789
7443654e 790 worker_attach_event(worker, event);
39c19cf1 791
eb546b35 792 log_device_debug(event->dev, "Worker ["PID_FMT"] is forked for processing SEQNUM=%"PRIu64".", pid, event->seqnum);
7443654e 793 return 0;
7fafc032
KS
794}
795
f2a5412b 796static int event_run(Event *event) {
5406c368 797 static bool log_children_max_reached = true;
f2a5412b 798 Manager *manager;
d9239923 799 Worker *worker;
7f2e3a14 800 int r;
912541b0 801
c0c6806b 802 assert(event);
f2a5412b 803 assert(event->manager);
c0c6806b 804
b2d9e58f 805 log_device_uevent(event->dev, "Device ready for processing");
7600dbb8 806
f2a5412b 807 manager = event->manager;
90e74a66 808 HASHMAP_FOREACH(worker, manager->workers) {
912541b0
KS
809 if (worker->state != WORKER_IDLE)
810 continue;
811
eb546b35 812 r = device_monitor_send_device(manager->monitor, worker->monitor, event->dev);
7f2e3a14 813 if (r < 0) {
eb546b35 814 log_device_error_errno(event->dev, r, "Worker ["PID_FMT"] did not accept message, killing the worker: %m",
7f2e3a14 815 worker->pid);
cb542e84 816 (void) kill(worker->pid, SIGKILL);
912541b0
KS
817 worker->state = WORKER_KILLED;
818 continue;
819 }
39c19cf1 820 worker_attach_event(worker, event);
f2a5412b 821 return 1; /* event is now processing. */
912541b0
KS
822 }
823
c0c6806b 824 if (hashmap_size(manager->workers) >= arg_children_max) {
5406c368
FB
825 /* Avoid spamming the debug logs if the limit is already reached and
826 * many events still need to be processed */
827 if (log_children_max_reached && arg_children_max > 1) {
044497e2 828 log_debug("Maximum number (%u) of children reached.", hashmap_size(manager->workers));
5406c368
FB
829 log_children_max_reached = false;
830 }
f2a5412b 831 return 0; /* no free worker */
912541b0
KS
832 }
833
5406c368
FB
834 /* Re-enable the debug message for the next batch of events */
835 log_children_max_reached = true;
836
912541b0 837 /* start new worker and pass initial device */
f2a5412b
YW
838 r = worker_spawn(manager, event);
839 if (r < 0)
840 return r;
841
842 return 1; /* event is now processing. */
1e03b754
KS
843}
844
a1fa99d8 845static int event_is_blocked(Event *event) {
eb546b35
YW
846 const char *subsystem, *devpath, *devpath_old = NULL;
847 dev_t devnum = makedev(0, 0);
03677889 848 Event *loop_event = NULL;
eb546b35
YW
849 size_t devpath_len;
850 int r, ifindex = 0;
851 bool is_block;
852
a1fa99d8
YW
853 /* lookup event for identical, parent, child device */
854
044ac33c
YW
855 assert(event);
856 assert(event->manager);
857 assert(event->blocker_seqnum <= event->seqnum);
858
5d354e52
YW
859 if (event->retry_again_next_usec > 0) {
860 usec_t now_usec;
861
ba4e0427 862 r = sd_event_now(event->manager->event, CLOCK_BOOTTIME, &now_usec);
5d354e52
YW
863 if (r < 0)
864 return r;
865
866 if (event->retry_again_next_usec <= now_usec)
867 return true;
868 }
869
044ac33c
YW
870 if (event->blocker_seqnum == event->seqnum)
871 /* we have checked previously and no blocker found */
872 return false;
873
03677889
YW
874 LIST_FOREACH(event, e, event->manager->events) {
875 loop_event = e;
876
044ac33c
YW
877 /* we already found a later event, earlier cannot block us, no need to check again */
878 if (loop_event->seqnum < event->blocker_seqnum)
879 continue;
880
881 /* event we checked earlier still exists, no need to check again */
882 if (loop_event->seqnum == event->blocker_seqnum)
883 return true;
884
885 /* found ourself, no later event can block us */
886 if (loop_event->seqnum >= event->seqnum)
887 goto no_blocker;
888
889 /* found event we have not checked */
890 break;
891 }
892
893 assert(loop_event);
894 assert(loop_event->seqnum > event->blocker_seqnum &&
895 loop_event->seqnum < event->seqnum);
896
eb546b35
YW
897 r = sd_device_get_subsystem(event->dev, &subsystem);
898 if (r < 0)
899 return r;
900
901 is_block = streq(subsystem, "block");
902
903 r = sd_device_get_devpath(event->dev, &devpath);
904 if (r < 0)
905 return r;
906
907 devpath_len = strlen(devpath);
908
909 r = sd_device_get_property_value(event->dev, "DEVPATH_OLD", &devpath_old);
910 if (r < 0 && r != -ENOENT)
911 return r;
912
913 r = sd_device_get_devnum(event->dev, &devnum);
914 if (r < 0 && r != -ENOENT)
915 return r;
916
917 r = sd_device_get_ifindex(event->dev, &ifindex);
918 if (r < 0 && r != -ENOENT)
919 return r;
912541b0
KS
920
921 /* check if queue contains events we depend on */
03677889 922 LIST_FOREACH(event, e, loop_event) {
eb546b35
YW
923 size_t loop_devpath_len, common;
924 const char *loop_devpath;
925
03677889
YW
926 loop_event = e;
927
912541b0
KS
928 /* found ourself, no later event can block us */
929 if (loop_event->seqnum >= event->seqnum)
044ac33c 930 goto no_blocker;
912541b0
KS
931
932 /* check major/minor */
eb546b35
YW
933 if (major(devnum) != 0) {
934 const char *s;
935 dev_t d;
936
937 if (sd_device_get_subsystem(loop_event->dev, &s) < 0)
938 continue;
939
940 if (sd_device_get_devnum(loop_event->dev, &d) >= 0 &&
941 devnum == d && is_block == streq(s, "block"))
a1fa99d8 942 break;
eb546b35 943 }
912541b0
KS
944
945 /* check network device ifindex */
eb546b35
YW
946 if (ifindex > 0) {
947 int i;
948
949 if (sd_device_get_ifindex(loop_event->dev, &i) >= 0 &&
950 ifindex == i)
a1fa99d8 951 break;
eb546b35
YW
952 }
953
954 if (sd_device_get_devpath(loop_event->dev, &loop_devpath) < 0)
955 continue;
912541b0
KS
956
957 /* check our old name */
0bd0407e 958 if (devpath_old && streq(devpath_old, loop_devpath))
a1fa99d8 959 break;
912541b0 960
eb546b35
YW
961 loop_devpath_len = strlen(loop_devpath);
962
912541b0 963 /* compare devpath */
eb546b35 964 common = MIN(devpath_len, loop_devpath_len);
912541b0
KS
965
966 /* one devpath is contained in the other? */
eb546b35 967 if (!strneq(devpath, loop_devpath, common))
912541b0
KS
968 continue;
969
970 /* identical device event found */
baa461fc 971 if (devpath_len == loop_devpath_len)
a1fa99d8 972 break;
912541b0
KS
973
974 /* parent device event found */
0bd0407e 975 if (devpath[common] == '/')
a1fa99d8 976 break;
912541b0
KS
977
978 /* child device event found */
0bd0407e 979 if (loop_devpath[common] == '/')
a1fa99d8 980 break;
912541b0
KS
981 }
982
a1fa99d8 983 assert(loop_event);
0bd0407e 984
7600dbb8
UKK
985 log_device_debug(event->dev, "SEQNUM=%" PRIu64 " blocked by SEQNUM=%" PRIu64,
986 event->seqnum, loop_event->seqnum);
987
a1fa99d8 988 event->blocker_seqnum = loop_event->seqnum;
0bd0407e 989 return true;
044ac33c
YW
990
991no_blocker:
992 event->blocker_seqnum = event->seqnum;
993 return false;
7fafc032
KS
994}
995
0744e74c 996static int event_queue_start(Manager *manager) {
693d371d 997 usec_t usec;
0725c4b9 998 int r;
8ab44e3f 999
c0c6806b
TG
1000 assert(manager);
1001
40a57716 1002 if (LIST_IS_EMPTY(manager->events) ||
7c4c7e89 1003 manager->exit || manager->stop_exec_queue)
0744e74c 1004 return 0;
7c4c7e89 1005
3285baa8 1006 assert_se(sd_event_now(manager->event, CLOCK_MONOTONIC, &usec) >= 0);
38a03f06
LP
1007 /* check for changed config, every 3 seconds at most */
1008 if (manager->last_usec == 0 ||
92fd70ad 1009 usec > usec_add(manager->last_usec, 3 * USEC_PER_SEC)) {
38a03f06 1010 if (udev_rules_check_timestamp(manager->rules) ||
2024ed61 1011 udev_builtin_validate())
38a03f06 1012 manager_reload(manager);
693d371d 1013
38a03f06 1014 manager->last_usec = usec;
7c4c7e89
TG
1015 }
1016
0725c4b9
YW
1017 r = event_source_disable(manager->kill_workers_event);
1018 if (r < 0)
1019 log_warning_errno(r, "Failed to disable event source for cleaning up idle workers, ignoring: %m");
eca195ec 1020
2024ed61 1021 udev_builtin_init();
7c4c7e89
TG
1022
1023 if (!manager->rules) {
c238a1f5 1024 r = udev_rules_load(&manager->rules, arg_resolve_name_timing);
0744e74c
YW
1025 if (r < 0)
1026 return log_warning_errno(r, "Failed to read udev rules: %m");
7c4c7e89
TG
1027 }
1028
c02fb804
YW
1029 /* fork with up-to-date SELinux label database, so the child inherits the up-to-date db
1030 * and, until the next SELinux policy changes, we safe further reloads in future children */
1031 mac_selinux_maybe_reload();
1032
80a226b2 1033 LIST_FOREACH(event, event, manager->events) {
912541b0
KS
1034 if (event->state != EVENT_QUEUED)
1035 continue;
0bc74ea7 1036
c6f78234
YW
1037 /* do not start event if parent or child event is still running or queued */
1038 r = event_is_blocked(event);
2d40f02e
YW
1039 if (r > 0)
1040 continue;
0c3d8182 1041 if (r < 0)
c6f78234 1042 log_device_warning_errno(event->dev, r,
2d40f02e
YW
1043 "Failed to check dependencies for event (SEQNUM=%"PRIu64", ACTION=%s), "
1044 "assuming there is no blocking event, ignoring: %m",
c6f78234 1045 event->seqnum,
0c3d8182 1046 strna(device_action_to_string(event->action)));
fc465079 1047
f2a5412b 1048 r = event_run(event);
2d40f02e 1049 if (r <= 0) /* 0 means there are no idle workers. Let's escape from the loop. */
f2a5412b 1050 return r;
912541b0 1051 }
0744e74c
YW
1052
1053 return 0;
1e03b754
KS
1054}
1055
5d354e52
YW
1056static int event_requeue(Event *event) {
1057 usec_t now_usec;
1058 int r;
1059
1060 assert(event);
1061 assert(event->manager);
1062 assert(event->manager->event);
1063
1064 event->timeout_warning_event = sd_event_source_disable_unref(event->timeout_warning_event);
1065 event->timeout_event = sd_event_source_disable_unref(event->timeout_event);
1066
1067 /* add a short delay to suppress busy loop */
ba4e0427 1068 r = sd_event_now(event->manager->event, CLOCK_BOOTTIME, &now_usec);
5d354e52
YW
1069 if (r < 0)
1070 return log_device_warning_errno(event->dev, r,
1071 "Failed to get current time, "
1072 "skipping event (SEQNUM=%"PRIu64", ACTION=%s): %m",
1073 event->seqnum, strna(device_action_to_string(event->action)));
1074
1075 if (event->retry_again_timeout_usec > 0 && event->retry_again_timeout_usec <= now_usec)
1076 return log_device_warning_errno(event->dev, SYNTHETIC_ERRNO(ETIMEDOUT),
1077 "The underlying block device is locked by a process more than %s, "
1078 "skipping event (SEQNUM=%"PRIu64", ACTION=%s).",
1079 FORMAT_TIMESPAN(EVENT_RETRY_TIMEOUT_USEC, USEC_PER_MINUTE),
1080 event->seqnum, strna(device_action_to_string(event->action)));
1081
1082 event->retry_again_next_usec = usec_add(now_usec, EVENT_RETRY_INTERVAL_USEC);
1083 if (event->retry_again_timeout_usec == 0)
1084 event->retry_again_timeout_usec = usec_add(now_usec, EVENT_RETRY_TIMEOUT_USEC);
1085
1086 if (event->worker && event->worker->event == event)
1087 event->worker->event = NULL;
1088 event->worker = NULL;
1089
1090 event->state = EVENT_QUEUED;
1091 return 0;
1092}
1093
82a5de9f
YW
1094static int event_queue_assume_block_device_unlocked(Manager *manager, sd_device *dev) {
1095 const char *devname;
1096 int r;
1097
1098 /* When a new event for a block device is queued or we get an inotify event, assume that the
1099 * device is not locked anymore. The assumption may not be true, but that should not cause any
1100 * issues, as in that case events will be requeued soon. */
1101
78e278ad 1102 r = device_get_whole_disk(dev, NULL, &devname);
82a5de9f
YW
1103 if (r <= 0)
1104 return r;
1105
1106 LIST_FOREACH(event, event, manager->events) {
1107 const char *event_devname;
1108
1109 if (event->state != EVENT_QUEUED)
1110 continue;
1111
1112 if (event->retry_again_next_usec == 0)
1113 continue;
1114
78e278ad 1115 if (device_get_whole_disk(event->dev, NULL, &event_devname) <= 0)
82a5de9f
YW
1116 continue;
1117
1118 if (!streq(devname, event_devname))
1119 continue;
1120
1121 event->retry_again_next_usec = 0;
1122 }
1123
1124 return 0;
1125}
1126
419ec631 1127static int event_queue_insert(Manager *manager, sd_device *dev) {
0c3d8182 1128 sd_device_action_t action;
419ec631 1129 uint64_t seqnum;
c9473aaa 1130 Event *event;
419ec631 1131 int r;
ff2c503d 1132
419ec631
YW
1133 assert(manager);
1134 assert(dev);
ff2c503d 1135
419ec631
YW
1136 /* only one process can add events to the queue */
1137 assert(manager->pid == getpid_cached());
1138
1139 /* We only accepts devices received by device monitor. */
1140 r = sd_device_get_seqnum(dev, &seqnum);
1141 if (r < 0)
1142 return r;
1143
0c3d8182
YW
1144 r = sd_device_get_action(dev, &action);
1145 if (r < 0)
1146 return r;
1147
419ec631
YW
1148 event = new(Event, 1);
1149 if (!event)
1150 return -ENOMEM;
1151
1152 *event = (Event) {
1153 .manager = manager,
1154 .dev = sd_device_ref(dev),
419ec631 1155 .seqnum = seqnum,
0c3d8182 1156 .action = action,
419ec631
YW
1157 .state = EVENT_QUEUED,
1158 };
1159
1160 if (LIST_IS_EMPTY(manager->events)) {
1161 r = touch("/run/udev/queue");
1162 if (r < 0)
6be97d67 1163 log_warning_errno(r, "Failed to touch /run/udev/queue, ignoring: %m");
912541b0 1164 }
419ec631
YW
1165
1166 LIST_APPEND(event, manager->events, event);
1167
1168 log_device_uevent(dev, "Device is queued");
1169
1170 return 0;
1171}
1172
1173static int on_uevent(sd_device_monitor *monitor, sd_device *dev, void *userdata) {
1174 Manager *manager = userdata;
1175 int r;
1176
1177 assert(manager);
1178
1179 DEVICE_TRACE_POINT(kernel_uevent_received, dev);
1180
1181 device_ensure_usec_initialized(dev, NULL);
1182
1183 r = event_queue_insert(manager, dev);
1184 if (r < 0) {
1185 log_device_error_errno(dev, r, "Failed to insert device into event queue: %m");
1186 return 1;
1187 }
1188
82a5de9f
YW
1189 (void) event_queue_assume_block_device_unlocked(manager, dev);
1190
419ec631
YW
1191 /* we have fresh events, try to schedule them */
1192 event_queue_start(manager);
1193
1194 return 1;
ff2c503d
KS
1195}
1196
e82e8fa5 1197static int on_worker(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
c0c6806b
TG
1198 Manager *manager = userdata;
1199
1200 assert(manager);
1201
912541b0 1202 for (;;) {
6467bda5 1203 int result;
5d354e52 1204 struct iovec iovec = IOVEC_MAKE(&result, sizeof(result));
fb29cdbe 1205 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred))) control;
979558f3
TG
1206 struct msghdr msghdr = {
1207 .msg_iov = &iovec,
1208 .msg_iovlen = 1,
1209 .msg_control = &control,
1210 .msg_controllen = sizeof(control),
1211 };
912541b0 1212 ssize_t size;
371d72e0 1213 struct ucred *ucred;
d9239923 1214 Worker *worker;
912541b0 1215
3691bcf3
LP
1216 size = recvmsg_safe(fd, &msghdr, MSG_DONTWAIT);
1217 if (size == -EINTR)
1218 continue;
1219 if (size == -EAGAIN)
1220 /* nothing more to read */
1221 break;
1222 if (size < 0)
1223 return log_error_errno(size, "Failed to receive message: %m");
1224
1225 cmsg_close_all(&msghdr);
979558f3 1226
6467bda5 1227 if (size != sizeof(result)) {
d4e98880 1228 log_warning("Ignoring worker message with invalid size %zi bytes", size);
e82e8fa5 1229 continue;
979558f3
TG
1230 }
1231
371d72e0 1232 ucred = CMSG_FIND_DATA(&msghdr, SOL_SOCKET, SCM_CREDENTIALS, struct ucred);
979558f3 1233 if (!ucred || ucred->pid <= 0) {
d4e98880 1234 log_warning("Ignoring worker message without valid PID");
979558f3
TG
1235 continue;
1236 }
912541b0
KS
1237
1238 /* lookup worker who sent the signal */
4a0b58c4 1239 worker = hashmap_get(manager->workers, PID_TO_PTR(ucred->pid));
a505965d 1240 if (!worker) {
044497e2 1241 log_debug("Worker ["PID_FMT"] returned, but is no longer tracked", ucred->pid);
a505965d 1242 continue;
912541b0 1243 }
c0bbfd72 1244
f257a8fc
YG
1245 if (worker->state == WORKER_KILLING) {
1246 worker->state = WORKER_KILLED;
1247 (void) kill(worker->pid, SIGTERM);
1248 } else if (worker->state != WORKER_KILLED)
a505965d
TG
1249 worker->state = WORKER_IDLE;
1250
1251 /* worker returned */
5d354e52
YW
1252 if (result == EVENT_RESULT_TRY_AGAIN &&
1253 event_requeue(worker->event) < 0)
6467bda5 1254 device_broadcast(manager->monitor, worker->event->dev, -ETIMEDOUT);
5d354e52
YW
1255
1256 /* When event_requeue() succeeds, worker->event is NULL, and event_free() handles NULL gracefully. */
a505965d 1257 event_free(worker->event);
912541b0 1258 }
e82e8fa5 1259
8302fe5a
TG
1260 /* we have free workers, try to schedule events */
1261 event_queue_start(manager);
1262
e82e8fa5
TG
1263 return 1;
1264}
1265
3b47c739 1266/* receive the udevd message from userspace */
e0d61dac 1267static int on_ctrl_msg(UdevCtrl *uctrl, UdevCtrlMessageType type, const UdevCtrlMessageValue *value, void *userdata) {
c0c6806b 1268 Manager *manager = userdata;
d02c6f54 1269 int r;
912541b0 1270
d02c6f54 1271 assert(value);
c0c6806b 1272 assert(manager);
e4f66b77 1273
d02c6f54
YW
1274 switch (type) {
1275 case UDEV_CTRL_SET_LOG_LEVEL:
64a3494c 1276 log_debug("Received udev control message (SET_LOG_LEVEL), setting log_level=%i", value->intval);
3cc6b14a 1277 log_set_max_level(value->intval);
1a0bd015 1278 manager->log_level = value->intval;
f257a8fc 1279 manager_kill_workers(manager, false);
d02c6f54
YW
1280 break;
1281 case UDEV_CTRL_STOP_EXEC_QUEUE:
044497e2 1282 log_debug("Received udev control message (STOP_EXEC_QUEUE)");
c0c6806b 1283 manager->stop_exec_queue = true;
d02c6f54
YW
1284 break;
1285 case UDEV_CTRL_START_EXEC_QUEUE:
044497e2 1286 log_debug("Received udev control message (START_EXEC_QUEUE)");
c0c6806b 1287 manager->stop_exec_queue = false;
8302fe5a 1288 event_queue_start(manager);
d02c6f54
YW
1289 break;
1290 case UDEV_CTRL_RELOAD:
044497e2 1291 log_debug("Received udev control message (RELOAD)");
62d43dac 1292 manager_reload(manager);
d02c6f54
YW
1293 break;
1294 case UDEV_CTRL_SET_ENV: {
d7ac0952
FS
1295 _unused_ _cleanup_free_ char *old_val = NULL;
1296 _cleanup_free_ char *key = NULL, *val = NULL, *old_key = NULL;
d02c6f54 1297 const char *eq;
9b5150b6 1298
d02c6f54 1299 eq = strchr(value->buf, '=');
9b5150b6 1300 if (!eq) {
d02c6f54 1301 log_error("Invalid key format '%s'", value->buf);
9b5150b6
YW
1302 return 1;
1303 }
1304
d02c6f54 1305 key = strndup(value->buf, eq - value->buf);
9b5150b6
YW
1306 if (!key) {
1307 log_oom();
1308 return 1;
1309 }
1310
1311 old_val = hashmap_remove2(manager->properties, key, (void **) &old_key);
1312
1313 r = hashmap_ensure_allocated(&manager->properties, &string_hash_ops);
1314 if (r < 0) {
1315 log_oom();
1316 return 1;
912541b0 1317 }
9b5150b6
YW
1318
1319 eq++;
f053fc33 1320 if (isempty(eq)) {
044497e2 1321 log_debug("Received udev control message (ENV), unsetting '%s'", key);
9b5150b6
YW
1322
1323 r = hashmap_put(manager->properties, key, NULL);
1324 if (r < 0) {
1325 log_oom();
1326 return 1;
1327 }
1328 } else {
1329 val = strdup(eq);
1330 if (!val) {
1331 log_oom();
1332 return 1;
1333 }
1334
044497e2 1335 log_debug("Received udev control message (ENV), setting '%s=%s'", key, val);
9b5150b6
YW
1336
1337 r = hashmap_put(manager->properties, key, val);
1338 if (r < 0) {
1339 log_oom();
1340 return 1;
1341 }
1342 }
1343
1344 key = val = NULL;
f257a8fc 1345 manager_kill_workers(manager, false);
d02c6f54 1346 break;
912541b0 1347 }
d02c6f54
YW
1348 case UDEV_CTRL_SET_CHILDREN_MAX:
1349 if (value->intval <= 0) {
1350 log_debug("Received invalid udev control message (SET_MAX_CHILDREN, %i), ignoring.", value->intval);
1351 return 0;
1352 }
912541b0 1353
d02c6f54
YW
1354 log_debug("Received udev control message (SET_MAX_CHILDREN), setting children_max=%i", value->intval);
1355 arg_children_max = value->intval;
1ef72b55 1356
4bf4f50f 1357 notify_ready();
d02c6f54
YW
1358 break;
1359 case UDEV_CTRL_PING:
d30f43ee 1360 log_debug("Received udev control message (PING)");
d02c6f54
YW
1361 break;
1362 case UDEV_CTRL_EXIT:
044497e2 1363 log_debug("Received udev control message (EXIT)");
62d43dac 1364 manager_exit(manager);
d02c6f54
YW
1365 break;
1366 default:
1367 log_debug("Received unknown udev control message, ignoring");
912541b0 1368 }
e4f66b77 1369
e82e8fa5 1370 return 1;
88f4b648 1371}
4a231017 1372
25677a05 1373static int synthesize_change_one(sd_device *dev, sd_device *target) {
0584b17a
ZJS
1374 int r;
1375
25677a05
YW
1376 if (DEBUG_LOGGING) {
1377 const char *syspath = NULL;
1378 (void) sd_device_get_syspath(target, &syspath);
1379 log_device_debug(dev, "device is closed, synthesising 'change' on %s", strna(syspath));
1380 }
1381
1382 r = sd_device_trigger(target, SD_DEVICE_CHANGE);
0584b17a 1383 if (r < 0)
25677a05
YW
1384 return log_device_debug_errno(target, r, "Failed to trigger 'change' uevent: %m");
1385
b428efa5
MS
1386 DEVICE_TRACE_POINT(synthetic_change_event, dev);
1387
0584b17a
ZJS
1388 return 0;
1389}
1390
70068602 1391static int synthesize_change(sd_device *dev) {
25677a05 1392 const char *subsystem, *sysname, *devtype;
f3a740a5 1393 int r;
edd32000 1394
70068602
YW
1395 r = sd_device_get_subsystem(dev, &subsystem);
1396 if (r < 0)
1397 return r;
1398
25677a05 1399 r = sd_device_get_devtype(dev, &devtype);
70068602
YW
1400 if (r < 0)
1401 return r;
1402
25677a05 1403 r = sd_device_get_sysname(dev, &sysname);
70068602
YW
1404 if (r < 0)
1405 return r;
1406
25677a05
YW
1407 if (streq_ptr(subsystem, "block") &&
1408 streq_ptr(devtype, "disk") &&
70068602
YW
1409 !startswith(sysname, "dm-")) {
1410 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
1411 bool part_table_read = false, has_partitions = false;
1412 sd_device *d;
ede34445 1413 int fd;
f3a740a5 1414
25677a05
YW
1415 /* Try to re-read the partition table. This only succeeds if none of the devices is
1416 * busy. The kernel returns 0 if no partition table is found, and we will not get an
1417 * event for the disk. */
78e278ad 1418 fd = sd_device_open(dev, O_RDONLY|O_CLOEXEC|O_NONBLOCK);
ede34445 1419 if (fd >= 0) {
02ba8fb3
KS
1420 r = flock(fd, LOCK_EX|LOCK_NB);
1421 if (r >= 0)
1422 r = ioctl(fd, BLKRRPART, 0);
1423
ede34445
KS
1424 close(fd);
1425 if (r >= 0)
e9fc29f4 1426 part_table_read = true;
ede34445
KS
1427 }
1428
e9fc29f4 1429 /* search for partitions */
70068602 1430 r = sd_device_enumerator_new(&e);
f3a740a5
KS
1431 if (r < 0)
1432 return r;
1433
70068602 1434 r = sd_device_enumerator_allow_uninitialized(e);
f3a740a5
KS
1435 if (r < 0)
1436 return r;
1437
70068602 1438 r = sd_device_enumerator_add_match_parent(e, dev);
47a3fa0f
TA
1439 if (r < 0)
1440 return r;
e9fc29f4 1441
70068602
YW
1442 r = sd_device_enumerator_add_match_subsystem(e, "block", true);
1443 if (r < 0)
1444 return r;
e9fc29f4 1445
70068602
YW
1446 FOREACH_DEVICE(e, d) {
1447 const char *t;
e9fc29f4 1448
25677a05 1449 if (sd_device_get_devtype(d, &t) < 0 || !streq(t, "partition"))
e9fc29f4
KS
1450 continue;
1451
1452 has_partitions = true;
1453 break;
1454 }
1455
25677a05
YW
1456 /* We have partitions and re-read the table, the kernel already sent out a "change"
1457 * event for the disk, and "remove/add" for all partitions. */
e9fc29f4
KS
1458 if (part_table_read && has_partitions)
1459 return 0;
1460
25677a05
YW
1461 /* We have partitions but re-reading the partition table did not work, synthesize
1462 * "change" for the disk and all partitions. */
1463 (void) synthesize_change_one(dev, dev);
e9fc29f4 1464
70068602 1465 FOREACH_DEVICE(e, d) {
25677a05 1466 const char *t;
f3a740a5 1467
25677a05 1468 if (sd_device_get_devtype(d, &t) < 0 || !streq(t, "partition"))
f3a740a5
KS
1469 continue;
1470
25677a05 1471 (void) synthesize_change_one(dev, d);
f3a740a5 1472 }
ede34445 1473
0584b17a 1474 } else
25677a05 1475 (void) synthesize_change_one(dev, dev);
ede34445 1476
f3a740a5 1477 return 0;
edd32000
KS
1478}
1479
e82e8fa5 1480static int on_inotify(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
c0c6806b 1481 Manager *manager = userdata;
0254e944 1482 union inotify_event_buffer buffer;
f7c1ad4f 1483 ssize_t l;
0725c4b9 1484 int r;
912541b0 1485
c0c6806b 1486 assert(manager);
e82e8fa5 1487
0725c4b9
YW
1488 r = event_source_disable(manager->kill_workers_event);
1489 if (r < 0)
1490 log_warning_errno(r, "Failed to disable event source for cleaning up idle workers, ignoring: %m");
eca195ec 1491
e82e8fa5 1492 l = read(fd, &buffer, sizeof(buffer));
f7c1ad4f 1493 if (l < 0) {
8add30a0 1494 if (ERRNO_IS_TRANSIENT(errno))
e82e8fa5 1495 return 1;
912541b0 1496
f7c1ad4f 1497 return log_error_errno(errno, "Failed to read inotify fd: %m");
912541b0
KS
1498 }
1499
00adc340 1500 FOREACH_INOTIFY_EVENT_WARN(e, buffer, l) {
70068602
YW
1501 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
1502 const char *devnode;
1503
e7f781e4
YW
1504 r = device_new_from_watch_handle(&dev, e->wd);
1505 if (r < 0) {
1506 log_debug_errno(r, "Failed to create sd_device object from watch handle, ignoring: %m");
70068602 1507 continue;
e7f781e4 1508 }
912541b0 1509
70068602 1510 if (sd_device_get_devname(dev, &devnode) < 0)
edd32000 1511 continue;
912541b0 1512
7fe3324c 1513 log_device_debug(dev, "Inotify event: %x for %s", e->mask, devnode);
82a5de9f
YW
1514 if (e->mask & IN_CLOSE_WRITE) {
1515 (void) event_queue_assume_block_device_unlocked(manager, dev);
e7f781e4 1516 (void) synthesize_change(dev);
82a5de9f 1517 }
e7f781e4
YW
1518
1519 /* Do not handle IN_IGNORED here. It should be handled by worker in 'remove' uevent;
1520 * udev_event_execute_rules() -> event_execute_rules_on_remove() -> udev_watch_end(). */
912541b0
KS
1521 }
1522
e82e8fa5 1523 return 1;
bd284db1
SJR
1524}
1525
0561329d 1526static int on_sigterm(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
c0c6806b
TG
1527 Manager *manager = userdata;
1528
1529 assert(manager);
1530
62d43dac 1531 manager_exit(manager);
912541b0 1532
e82e8fa5
TG
1533 return 1;
1534}
912541b0 1535
0561329d 1536static int on_sighup(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
c0c6806b
TG
1537 Manager *manager = userdata;
1538
1539 assert(manager);
1540
62d43dac 1541 manager_reload(manager);
912541b0 1542
e82e8fa5
TG
1543 return 1;
1544}
912541b0 1545
e82e8fa5 1546static int on_sigchld(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
c0c6806b 1547 Manager *manager = userdata;
0725c4b9 1548 int r;
c0c6806b
TG
1549
1550 assert(manager);
1551
e82e8fa5
TG
1552 for (;;) {
1553 pid_t pid;
1554 int status;
d9239923 1555 Worker *worker;
d1317d02 1556
e82e8fa5
TG
1557 pid = waitpid(-1, &status, WNOHANG);
1558 if (pid <= 0)
f29328d6 1559 break;
e82e8fa5 1560
4a0b58c4 1561 worker = hashmap_get(manager->workers, PID_TO_PTR(pid));
e82e8fa5 1562 if (!worker) {
dc7faf2a 1563 log_warning("Worker ["PID_FMT"] is unknown, ignoring", pid);
f29328d6 1564 continue;
912541b0 1565 }
e82e8fa5
TG
1566
1567 if (WIFEXITED(status)) {
1568 if (WEXITSTATUS(status) == 0)
dc7faf2a 1569 log_debug("Worker ["PID_FMT"] exited", pid);
e82e8fa5 1570 else
dc7faf2a 1571 log_warning("Worker ["PID_FMT"] exited with return code %i", pid, WEXITSTATUS(status));
33ad742a 1572 } else if (WIFSIGNALED(status))
dc7faf2a 1573 log_warning("Worker ["PID_FMT"] terminated by signal %i (%s)", pid, WTERMSIG(status), signal_to_string(WTERMSIG(status)));
33ad742a 1574 else if (WIFSTOPPED(status)) {
dc7faf2a 1575 log_info("Worker ["PID_FMT"] stopped", pid);
f29328d6 1576 continue;
e82e8fa5 1577 } else if (WIFCONTINUED(status)) {
dc7faf2a 1578 log_info("Worker ["PID_FMT"] continued", pid);
f29328d6 1579 continue;
e82e8fa5 1580 } else
dc7faf2a 1581 log_warning("Worker ["PID_FMT"] exit with status 0x%04x", pid, status);
e82e8fa5 1582
05e6d9c6 1583 if ((!WIFEXITED(status) || WEXITSTATUS(status) != 0) && worker->event) {
eb546b35 1584 log_device_error(worker->event->dev, "Worker ["PID_FMT"] failed", pid);
dc7faf2a 1585
05e6d9c6 1586 /* delete state from disk */
eb546b35
YW
1587 device_delete_db(worker->event->dev);
1588 device_tag_index(worker->event->dev, NULL, false);
dc7faf2a 1589
c17ab900 1590 /* Forward kernel event to libudev listeners */
6467bda5
YW
1591 device_broadcast(manager->monitor, worker->event->dev,
1592 WIFEXITED(status) ? EVENT_RESULT_EXIT_STATUS_BASE + WEXITSTATUS(status):
1593 WIFSIGNALED(status) ? EVENT_RESULT_SIGNAL_BASE + WTERMSIG(status) : 0);
e82e8fa5
TG
1594 }
1595
1596 worker_free(worker);
912541b0 1597 }
e82e8fa5 1598
8302fe5a
TG
1599 /* we can start new workers, try to schedule events */
1600 event_queue_start(manager);
1601
eca195ec 1602 /* Disable unnecessary cleanup event */
0725c4b9
YW
1603 if (hashmap_isempty(manager->workers)) {
1604 r = event_source_disable(manager->kill_workers_event);
1605 if (r < 0)
1606 log_warning_errno(r, "Failed to disable event source for cleaning up idle workers, ignoring: %m");
1607 }
eca195ec 1608
e82e8fa5 1609 return 1;
f27125f9 1610}
1611
693d371d
TG
1612static int on_post(sd_event_source *s, void *userdata) {
1613 Manager *manager = userdata;
693d371d
TG
1614
1615 assert(manager);
1616
5d354e52
YW
1617 if (!LIST_IS_EMPTY(manager->events)) {
1618 /* Try to process pending events if idle workers exist. Why is this necessary?
1619 * When a worker finished an event and became idle, even if there was a pending event,
1620 * the corresponding device might have been locked and the processing of the event
1621 * delayed for a while, preventing the worker from processing the event immediately.
1622 * Now, the device may be unlocked. Let's try again! */
1623 event_queue_start(manager);
b6107f01 1624 return 1;
5d354e52 1625 }
b6107f01 1626
40293280
YW
1627 /* There are no queued events. Let's remove /run/udev/queue and clean up the idle processes. */
1628
1629 if (unlink("/run/udev/queue") < 0) {
1630 if (errno != ENOENT)
1631 log_warning_errno(errno, "Failed to unlink /run/udev/queue, ignoring: %m");
1632 } else
1633 log_debug("No events are queued, removing /run/udev/queue.");
b6107f01
YW
1634
1635 if (!hashmap_isempty(manager->workers)) {
1636 /* There are idle workers */
6d63048a
YW
1637 (void) event_reset_time(manager->event, &manager->kill_workers_event, CLOCK_MONOTONIC,
1638 now(CLOCK_MONOTONIC) + 3 * USEC_PER_SEC, USEC_PER_SEC,
1639 on_kill_workers_event, manager, 0, "kill-workers-event", false);
b6107f01 1640 return 1;
693d371d
TG
1641 }
1642
b6107f01
YW
1643 /* There are no idle workers. */
1644
1645 if (manager->exit)
1646 return sd_event_exit(manager->event, 0);
1647
42670846
YW
1648 if (manager->cgroup)
1649 /* cleanup possible left-over processes in our cgroup */
1650 (void) cg_kill(SYSTEMD_CGROUP_CONTROLLER, manager->cgroup, SIGKILL, CGROUP_IGNORE_SELF, NULL, NULL, NULL);
b6107f01 1651
693d371d
TG
1652 return 1;
1653}
1654
c4b69e99 1655static int listen_fds(int *ret_ctrl, int *ret_netlink) {
fcff1e72 1656 int ctrl_fd = -1, netlink_fd = -1;
c4b69e99 1657 int fd, n;
912541b0 1658
c4b69e99
YW
1659 assert(ret_ctrl);
1660 assert(ret_netlink);
fcff1e72 1661
912541b0 1662 n = sd_listen_fds(true);
fcff1e72
TG
1663 if (n < 0)
1664 return n;
912541b0
KS
1665
1666 for (fd = SD_LISTEN_FDS_START; fd < n + SD_LISTEN_FDS_START; fd++) {
c52cff07 1667 if (sd_is_socket(fd, AF_LOCAL, SOCK_SEQPACKET, -1) > 0) {
fcff1e72
TG
1668 if (ctrl_fd >= 0)
1669 return -EINVAL;
1670 ctrl_fd = fd;
912541b0
KS
1671 continue;
1672 }
1673
c52cff07 1674 if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1) > 0) {
fcff1e72
TG
1675 if (netlink_fd >= 0)
1676 return -EINVAL;
1677 netlink_fd = fd;
912541b0
KS
1678 continue;
1679 }
1680
fcff1e72 1681 return -EINVAL;
912541b0
KS
1682 }
1683
c4b69e99
YW
1684 *ret_ctrl = ctrl_fd;
1685 *ret_netlink = netlink_fd;
912541b0 1686
912541b0 1687 return 0;
7459bcdc
KS
1688}
1689
e6f86cac 1690/*
3f85ef0f 1691 * read the kernel command line, in case we need to get into debug mode
64a3494c 1692 * udev.log_level=<level> syslog priority
1d84ad94
LP
1693 * udev.children_max=<number of workers> events are fully serialized if set to 1
1694 * udev.exec_delay=<number of seconds> delay execution of every executed program
1695 * udev.event_timeout=<number of seconds> seconds to wait before terminating an event
95ac5230 1696 * udev.blockdev_read_only<=bool> mark all block devices read-only when they appear
e6f86cac 1697 */
96287a49 1698static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
95ac5230 1699 int r;
e6f86cac 1700
614a823c 1701 assert(key);
e6f86cac 1702
64a3494c
FB
1703 if (proc_cmdline_key_streq(key, "udev.log_level") ||
1704 proc_cmdline_key_streq(key, "udev.log_priority")) { /* kept for backward compatibility */
1d84ad94
LP
1705
1706 if (proc_cmdline_value_missing(key, value))
1707 return 0;
1708
46f0fbd8 1709 r = log_level_from_string(value);
92e72467
ZJS
1710 if (r >= 0)
1711 log_set_max_level(r);
1d84ad94
LP
1712
1713 } else if (proc_cmdline_key_streq(key, "udev.event_timeout")) {
1714
1715 if (proc_cmdline_value_missing(key, value))
1716 return 0;
1717
9d9264ba 1718 r = parse_sec(value, &arg_event_timeout_usec);
1d84ad94
LP
1719
1720 } else if (proc_cmdline_key_streq(key, "udev.children_max")) {
1721
1722 if (proc_cmdline_value_missing(key, value))
1723 return 0;
1724
020328e1 1725 r = safe_atou(value, &arg_children_max);
1d84ad94
LP
1726
1727 } else if (proc_cmdline_key_streq(key, "udev.exec_delay")) {
1728
1729 if (proc_cmdline_value_missing(key, value))
1730 return 0;
1731
6b92f429 1732 r = parse_sec(value, &arg_exec_delay_usec);
1d84ad94 1733
e2099267 1734 } else if (proc_cmdline_key_streq(key, "udev.timeout_signal")) {
95ac5230 1735
e2099267
MS
1736 if (proc_cmdline_value_missing(key, value))
1737 return 0;
1738
1739 r = signal_from_string(value);
1740 if (r > 0)
1741 arg_timeout_signal = r;
95ac5230
LP
1742
1743 } else if (proc_cmdline_key_streq(key, "udev.blockdev_read_only")) {
1744
1745 if (!value)
1746 arg_blockdev_read_only = true;
1747 else {
1748 r = parse_boolean(value);
1749 if (r < 0)
1750 log_warning_errno(r, "Failed to parse udev.blockdev-read-only argument, ignoring: %s", value);
1751 else
1752 arg_blockdev_read_only = r;
1753 }
1754
1755 if (arg_blockdev_read_only)
1756 log_notice("All physical block devices will be marked read-only.");
1757
1758 return 0;
1759
1760 } else {
1761 if (startswith(key, "udev."))
1762 log_warning("Unknown udev kernel command line option \"%s\", ignoring.", key);
1763
1764 return 0;
1765 }
614a823c 1766
92e72467
ZJS
1767 if (r < 0)
1768 log_warning_errno(r, "Failed to parse \"%s=%s\", ignoring: %m", key, value);
1d84ad94 1769
614a823c 1770 return 0;
e6f86cac
KS
1771}
1772
37ec0fdd
LP
1773static int help(void) {
1774 _cleanup_free_ char *link = NULL;
1775 int r;
1776
1777 r = terminal_urlify_man("systemd-udevd.service", "8", &link);
1778 if (r < 0)
1779 return log_oom();
1780
ed216e1f 1781 printf("%s [OPTIONS...]\n\n"
d1109e12 1782 "Rule-based manager for device events and files.\n\n"
5ac0162c 1783 " -h --help Print this message\n"
2d19c17e
MF
1784 " -V --version Print version of the program\n"
1785 " -d --daemon Detach and run in the background\n"
1786 " -D --debug Enable debug output\n"
1787 " -c --children-max=INT Set maximum number of workers\n"
1788 " -e --exec-delay=SECONDS Seconds to wait before executing RUN=\n"
1789 " -t --event-timeout=SECONDS Seconds to wait before terminating an event\n"
1790 " -N --resolve-names=early|late|never\n"
5ac0162c 1791 " When to resolve users and groups\n"
bc556335
DDM
1792 "\nSee the %s for details.\n",
1793 program_invocation_short_name,
1794 link);
37ec0fdd
LP
1795
1796 return 0;
ed216e1f
TG
1797}
1798
bba7a484 1799static int parse_argv(int argc, char *argv[]) {
e2099267
MS
1800 enum {
1801 ARG_TIMEOUT_SIGNAL,
1802 };
1803
912541b0 1804 static const struct option options[] = {
e2099267
MS
1805 { "daemon", no_argument, NULL, 'd' },
1806 { "debug", no_argument, NULL, 'D' },
1807 { "children-max", required_argument, NULL, 'c' },
1808 { "exec-delay", required_argument, NULL, 'e' },
1809 { "event-timeout", required_argument, NULL, 't' },
1810 { "resolve-names", required_argument, NULL, 'N' },
1811 { "help", no_argument, NULL, 'h' },
1812 { "version", no_argument, NULL, 'V' },
1813 { "timeout-signal", required_argument, NULL, ARG_TIMEOUT_SIGNAL },
912541b0
KS
1814 {}
1815 };
689a97f5 1816
044497e2 1817 int c, r;
689a97f5 1818
bba7a484
TG
1819 assert(argc >= 0);
1820 assert(argv);
912541b0 1821
e14b6f21 1822 while ((c = getopt_long(argc, argv, "c:de:Dt:N:hV", options, NULL)) >= 0) {
bba7a484 1823 switch (c) {
912541b0 1824
912541b0 1825 case 'd':
bba7a484 1826 arg_daemonize = true;
912541b0
KS
1827 break;
1828 case 'c':
020328e1 1829 r = safe_atou(optarg, &arg_children_max);
6f5cf8a8 1830 if (r < 0)
389f9bf2 1831 log_warning_errno(r, "Failed to parse --children-max= value '%s', ignoring: %m", optarg);
912541b0
KS
1832 break;
1833 case 'e':
6b92f429 1834 r = parse_sec(optarg, &arg_exec_delay_usec);
6f5cf8a8 1835 if (r < 0)
6b92f429 1836 log_warning_errno(r, "Failed to parse --exec-delay= value '%s', ignoring: %m", optarg);
912541b0 1837 break;
e2099267
MS
1838 case ARG_TIMEOUT_SIGNAL:
1839 r = signal_from_string(optarg);
1840 if (r <= 0)
1841 log_warning_errno(r, "Failed to parse --timeout-signal= value '%s', ignoring: %m", optarg);
1842 else
1843 arg_timeout_signal = r;
1844
1845 break;
9719859c 1846 case 't':
9d9264ba 1847 r = parse_sec(optarg, &arg_event_timeout_usec);
f1e8664e 1848 if (r < 0)
9d9264ba 1849 log_warning_errno(r, "Failed to parse --event-timeout= value '%s', ignoring: %m", optarg);
9719859c 1850 break;
912541b0 1851 case 'D':
bba7a484 1852 arg_debug = true;
912541b0 1853 break;
c4d44cba
YW
1854 case 'N': {
1855 ResolveNameTiming t;
1856
1857 t = resolve_name_timing_from_string(optarg);
1858 if (t < 0)
1859 log_warning("Invalid --resolve-names= value '%s', ignoring.", optarg);
1860 else
1861 arg_resolve_name_timing = t;
912541b0 1862 break;
c4d44cba 1863 }
912541b0 1864 case 'h':
37ec0fdd 1865 return help();
912541b0 1866 case 'V':
681bd2c5 1867 printf("%s\n", GIT_VERSION);
bba7a484
TG
1868 return 0;
1869 case '?':
1870 return -EINVAL;
912541b0 1871 default:
04499a70 1872 assert_not_reached();
bba7a484 1873
912541b0
KS
1874 }
1875 }
1876
bba7a484
TG
1877 return 1;
1878}
1879
a1f4fd38
YW
1880static int create_subcgroup(char **ret) {
1881 _cleanup_free_ char *cgroup = NULL, *subcgroup = NULL;
1882 int r;
1883
1884 if (getppid() != 1)
1885 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Not invoked by PID1.");
1886
1887 r = sd_booted();
1888 if (r < 0)
1889 return log_debug_errno(r, "Failed to check if systemd is running: %m");
1890 if (r == 0)
1891 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "systemd is not running.");
1892
1893 /* Get our own cgroup, we regularly kill everything udev has left behind.
1894 * We only do this on systemd systems, and only if we are directly spawned
1895 * by PID1. Otherwise we are not guaranteed to have a dedicated cgroup. */
1896
1897 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &cgroup);
1898 if (r < 0) {
1899 if (IN_SET(r, -ENOENT, -ENOMEDIUM))
1900 return log_debug_errno(r, "Dedicated cgroup not found: %m");
1901 return log_debug_errno(r, "Failed to get cgroup: %m");
1902 }
1903
1904 r = cg_get_xattr_bool(SYSTEMD_CGROUP_CONTROLLER, cgroup, "trusted.delegate");
1905 if (IN_SET(r, 0, -ENODATA))
1906 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "The cgroup %s is not delegated to us.", cgroup);
1907 if (r < 0)
1908 return log_debug_errno(r, "Failed to read trusted.delegate attribute: %m");
1909
1910 /* We are invoked with our own delegated cgroup tree, let's move us one level down, so that we
1911 * don't collide with the "no processes in inner nodes" rule of cgroups, when the service
1912 * manager invokes the ExecReload= job in the .control/ subcgroup. */
1913
1914 subcgroup = path_join(cgroup, "/udev");
1915 if (!subcgroup)
1916 return log_oom_debug();
1917
1918 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, subcgroup, 0);
1919 if (r < 0)
1920 return log_debug_errno(r, "Failed to create %s subcgroup: %m", subcgroup);
1921
1922 log_debug("Created %s subcgroup.", subcgroup);
1923 if (ret)
1924 *ret = TAKE_PTR(subcgroup);
1925 return 0;
1926}
1927
1928static int manager_new(Manager **ret, int fd_ctrl, int fd_uevent) {
c0c6806b 1929 _cleanup_(manager_freep) Manager *manager = NULL;
a1f4fd38 1930 _cleanup_free_ char *cgroup = NULL;
b5af8c8c 1931 int r;
c0c6806b
TG
1932
1933 assert(ret);
1934
a1f4fd38
YW
1935 (void) create_subcgroup(&cgroup);
1936
6f19b42f 1937 manager = new(Manager, 1);
c0c6806b
TG
1938 if (!manager)
1939 return log_oom();
1940
6f19b42f 1941 *manager = (Manager) {
df7ee959 1942 .inotify_fd = -1,
6f19b42f 1943 .worker_watch = { -1, -1 },
a1f4fd38 1944 .cgroup = TAKE_PTR(cgroup),
6f19b42f 1945 };
e237d8cb 1946
100bc5bf
YW
1947 r = udev_ctrl_new_from_fd(&manager->ctrl, fd_ctrl);
1948 if (r < 0)
1949 return log_error_errno(r, "Failed to initialize udev control socket: %m");
e237d8cb 1950
b5af8c8c
ZJS
1951 r = udev_ctrl_enable_receiving(manager->ctrl);
1952 if (r < 0)
1953 return log_error_errno(r, "Failed to bind udev control socket: %m");
c4b69e99 1954
7f2e3a14
YW
1955 r = device_monitor_new_full(&manager->monitor, MONITOR_GROUP_KERNEL, fd_uevent);
1956 if (r < 0)
1957 return log_error_errno(r, "Failed to initialize device monitor: %m");
e237d8cb 1958
1ffadeaa
FB
1959 /* Bump receiver buffer, but only if we are not called via socket activation, as in that
1960 * case systemd sets the receive buffer size for us, and the value in the .socket unit
1961 * should take full effect. */
e77f52e5
YW
1962 if (fd_uevent < 0) {
1963 r = sd_device_monitor_set_receive_buffer_size(manager->monitor, 128 * 1024 * 1024);
1964 if (r < 0)
1965 log_warning_errno(r, "Failed to set receive buffer size for device monitor, ignoring: %m");
1966 }
c4b69e99 1967
b5af8c8c
ZJS
1968 r = device_monitor_enable_receiving(manager->monitor);
1969 if (r < 0)
1970 return log_error_errno(r, "Failed to bind netlink socket: %m");
1971
1a0bd015
YW
1972 manager->log_level = log_get_max_level();
1973
b5af8c8c
ZJS
1974 *ret = TAKE_PTR(manager);
1975
1976 return 0;
1977}
1978
1979static int main_loop(Manager *manager) {
d02c6f54 1980 int fd_worker, r;
b5af8c8c 1981
76e62a4d
YW
1982 manager->pid = getpid_cached();
1983
e237d8cb
TG
1984 /* unnamed socket from workers to the main daemon */
1985 r = socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, manager->worker_watch);
1986 if (r < 0)
044497e2 1987 return log_error_errno(errno, "Failed to create socketpair for communicating with workers: %m");
e237d8cb 1988
693d371d 1989 fd_worker = manager->worker_watch[READ_END];
e237d8cb 1990
2ff48e98 1991 r = setsockopt_int(fd_worker, SOL_SOCKET, SO_PASSCRED, true);
e237d8cb 1992 if (r < 0)
044497e2 1993 return log_error_errno(r, "Failed to enable SO_PASSCRED: %m");
e237d8cb 1994
df7ee959
YW
1995 manager->inotify_fd = inotify_init1(IN_CLOEXEC);
1996 if (manager->inotify_fd < 0)
1997 return log_error_errno(errno, "Failed to create inotify descriptor: %m");
e237d8cb 1998
df7ee959 1999 udev_watch_restore(manager->inotify_fd);
e237d8cb
TG
2000
2001 /* block and listen to all signals on signalfd */
72c0a2c2 2002 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, SIGINT, SIGHUP, SIGCHLD, -1) >= 0);
693d371d 2003
49f997f3
TG
2004 r = sd_event_default(&manager->event);
2005 if (r < 0)
044497e2 2006 return log_error_errno(r, "Failed to allocate event loop: %m");
49f997f3 2007
693d371d
TG
2008 r = sd_event_add_signal(manager->event, NULL, SIGINT, on_sigterm, manager);
2009 if (r < 0)
044497e2 2010 return log_error_errno(r, "Failed to create SIGINT event source: %m");
693d371d
TG
2011
2012 r = sd_event_add_signal(manager->event, NULL, SIGTERM, on_sigterm, manager);
2013 if (r < 0)
044497e2 2014 return log_error_errno(r, "Failed to create SIGTERM event source: %m");
693d371d
TG
2015
2016 r = sd_event_add_signal(manager->event, NULL, SIGHUP, on_sighup, manager);
2017 if (r < 0)
044497e2 2018 return log_error_errno(r, "Failed to create SIGHUP event source: %m");
693d371d
TG
2019
2020 r = sd_event_add_signal(manager->event, NULL, SIGCHLD, on_sigchld, manager);
2021 if (r < 0)
044497e2 2022 return log_error_errno(r, "Failed to create SIGCHLD event source: %m");
693d371d
TG
2023
2024 r = sd_event_set_watchdog(manager->event, true);
2025 if (r < 0)
044497e2 2026 return log_error_errno(r, "Failed to create watchdog event source: %m");
693d371d 2027
d02c6f54
YW
2028 r = udev_ctrl_attach_event(manager->ctrl, manager->event);
2029 if (r < 0)
2030 return log_error_errno(r, "Failed to attach event to udev control: %m");
b5af8c8c 2031
d02c6f54 2032 r = udev_ctrl_start(manager->ctrl, on_ctrl_msg, manager);
693d371d 2033 if (r < 0)
d02c6f54 2034 return log_error_errno(r, "Failed to start device monitor: %m");
693d371d
TG
2035
2036 /* This needs to be after the inotify and uevent handling, to make sure
2037 * that the ping is send back after fully processing the pending uevents
2038 * (including the synthetic ones we may create due to inotify events).
2039 */
d02c6f54 2040 r = sd_event_source_set_priority(udev_ctrl_get_event_source(manager->ctrl), SD_EVENT_PRIORITY_IDLE);
693d371d 2041 if (r < 0)
044497e2 2042 return log_error_errno(r, "Failed to set IDLE event priority for udev control event source: %m");
693d371d 2043
df7ee959 2044 r = sd_event_add_io(manager->event, &manager->inotify_event, manager->inotify_fd, EPOLLIN, on_inotify, manager);
693d371d 2045 if (r < 0)
044497e2 2046 return log_error_errno(r, "Failed to create inotify event source: %m");
693d371d 2047
f00d2b6d
YW
2048 r = sd_device_monitor_attach_event(manager->monitor, manager->event);
2049 if (r < 0)
2050 return log_error_errno(r, "Failed to attach event to device monitor: %m");
2051
2052 r = sd_device_monitor_start(manager->monitor, on_uevent, manager);
693d371d 2053 if (r < 0)
f00d2b6d
YW
2054 return log_error_errno(r, "Failed to start device monitor: %m");
2055
2056 (void) sd_event_source_set_description(sd_device_monitor_get_event_source(manager->monitor), "device-monitor");
693d371d
TG
2057
2058 r = sd_event_add_io(manager->event, NULL, fd_worker, EPOLLIN, on_worker, manager);
2059 if (r < 0)
044497e2 2060 return log_error_errno(r, "Failed to create worker event source: %m");
693d371d
TG
2061
2062 r = sd_event_add_post(manager->event, NULL, on_post, manager);
2063 if (r < 0)
044497e2 2064 return log_error_errno(r, "Failed to create post event source: %m");
e237d8cb 2065
b5af8c8c 2066 udev_builtin_init();
077fc5e2 2067
c238a1f5 2068 r = udev_rules_load(&manager->rules, arg_resolve_name_timing);
b5af8c8c
ZJS
2069 if (!manager->rules)
2070 return log_error_errno(r, "Failed to read udev rules: %m");
077fc5e2
DH
2071
2072 r = udev_rules_apply_static_dev_perms(manager->rules);
2073 if (r < 0)
044497e2 2074 log_error_errno(r, "Failed to apply permissions on static device nodes: %m");
077fc5e2 2075
4bf4f50f 2076 notify_ready();
077fc5e2
DH
2077
2078 r = sd_event_loop(manager->event);
44dcf454 2079 if (r < 0)
044497e2 2080 log_error_errno(r, "Event loop failed: %m");
077fc5e2 2081
077fc5e2
DH
2082 sd_notify(false,
2083 "STOPPING=1\n"
2084 "STATUS=Shutting down...");
077fc5e2
DH
2085 return r;
2086}
2087
63e2d171 2088int run_udevd(int argc, char *argv[]) {
b5af8c8c 2089 _cleanup_(manager_freep) Manager *manager = NULL;
efa1606e 2090 int fd_ctrl = -1, fd_uevent = -1;
e5d7bce1 2091 int r;
bba7a484 2092
bba7a484 2093 log_set_target(LOG_TARGET_AUTO);
6b413782 2094 log_open();
e2099267 2095 udev_parse_config_full(&arg_children_max, &arg_exec_delay_usec, &arg_event_timeout_usec, &arg_resolve_name_timing, &arg_timeout_signal);
bba7a484 2096 log_parse_environment();
6b413782 2097 log_open(); /* Done again to update after reading configuration. */
bba7a484 2098
bba7a484
TG
2099 r = parse_argv(argc, argv);
2100 if (r <= 0)
0c5a109a 2101 return r;
bba7a484 2102
1d84ad94 2103 r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, PROC_CMDLINE_STRIP_RD_PREFIX);
614a823c 2104 if (r < 0)
044497e2 2105 log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
912541b0 2106
78d3e041
KS
2107 if (arg_debug) {
2108 log_set_target(LOG_TARGET_CONSOLE);
bba7a484 2109 log_set_max_level(LOG_DEBUG);
78d3e041 2110 }
bba7a484 2111
fba868fa
LP
2112 r = must_be_root();
2113 if (r < 0)
0c5a109a 2114 return r;
912541b0 2115
712cebf1 2116 if (arg_children_max == 0) {
fe56acd8 2117 unsigned long cpu_limit, mem_limit, cpu_count = 1;
d457ff83 2118
fe56acd8
LP
2119 r = cpus_in_affinity_mask();
2120 if (r < 0)
2121 log_warning_errno(r, "Failed to determine number of local CPUs, ignoring: %m");
2122 else
2123 cpu_count = r;
88bd5a32
FB
2124
2125 cpu_limit = cpu_count * 2 + 16;
2126 mem_limit = MAX(physical_memory() / (128UL*1024*1024), 10U);
912541b0 2127
88bd5a32
FB
2128 arg_children_max = MIN(cpu_limit, mem_limit);
2129 arg_children_max = MIN(WORKER_NUM_MAX, arg_children_max);
e438c57a 2130
044497e2 2131 log_debug("Set children_max to %u", arg_children_max);
d457ff83 2132 }
912541b0 2133
712cebf1 2134 /* set umask before creating any file/directory */
712cebf1 2135 umask(022);
912541b0 2136
c3dacc8b 2137 r = mac_selinux_init();
0c5a109a 2138 if (r < 0)
a9ba0e32 2139 return r;
912541b0 2140
3f692e2e 2141 r = RET_NERRNO(mkdir("/run/udev", 0755));
0c5a109a
ZJS
2142 if (r < 0 && r != -EEXIST)
2143 return log_error_errno(r, "Failed to create /run/udev: %m");
712cebf1 2144
b7f74dd4 2145 r = listen_fds(&fd_ctrl, &fd_uevent);
0c5a109a
ZJS
2146 if (r < 0)
2147 return log_error_errno(r, "Failed to listen on fds: %m");
b7f74dd4 2148
a1f4fd38 2149 r = manager_new(&manager, fd_ctrl, fd_uevent);
b5af8c8c
ZJS
2150 if (r < 0)
2151 return log_error_errno(r, "Failed to create manager: %m");
2152
bba7a484 2153 if (arg_daemonize) {
912541b0 2154 pid_t pid;
912541b0 2155
b5af8c8c 2156 log_info("Starting version " GIT_VERSION);
3cbb2057 2157
40e749b5 2158 /* connect /dev/null to stdin, stdout, stderr */
c76cf844
AK
2159 if (log_get_max_level() < LOG_DEBUG) {
2160 r = make_null_stdio();
2161 if (r < 0)
2162 log_warning_errno(r, "Failed to redirect standard streams to /dev/null: %m");
2163 }
2164
912541b0 2165 pid = fork();
0c5a109a
ZJS
2166 if (pid < 0)
2167 return log_error_errno(errno, "Failed to fork daemon: %m");
2168 if (pid > 0)
2169 /* parent */
2170 return 0;
912541b0 2171
0c5a109a 2172 /* child */
ece0fe12 2173 (void) setsid();
7500cd5e 2174 }
912541b0 2175
76e62a4d 2176 return main_loop(manager);
7fafc032 2177}