]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/udev/udevd.c
bus-proxy: drop priviliges if we can
[thirdparty/systemd.git] / src / udev / udevd.c
CommitLineData
7fafc032 1/*
1298001e 2 * Copyright (C) 2004-2012 Kay Sievers <kay@vrfy.org>
2f6cbd19 3 * Copyright (C) 2004 Chris Friesen <chris_friesen@sympatico.ca>
bb38678e
SJR
4 * Copyright (C) 2009 Canonical Ltd.
5 * Copyright (C) 2009 Scott James Remnant <scott@netsplit.com>
7fafc032 6 *
55e9959b
KS
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 2 of the License, or
10 * (at your option) any later version.
7fafc032 11 *
55e9959b
KS
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
7fafc032 16 *
55e9959b
KS
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
7fafc032
KS
19 */
20
a695feae 21#include <stddef.h>
7fafc032
KS
22#include <signal.h>
23#include <unistd.h>
24#include <errno.h>
25#include <stdio.h>
26#include <stdlib.h>
c3804728 27#include <stdbool.h>
7fafc032 28#include <string.h>
085cce37 29#include <ctype.h>
085cce37 30#include <fcntl.h>
0b3dfb3d 31#include <time.h>
b52a01ee 32#include <getopt.h>
78230c0d 33#include <dirent.h>
3ebdb81e 34#include <sys/file.h>
820fc48f 35#include <sys/time.h>
1e03b754
KS
36#include <sys/prctl.h>
37#include <sys/socket.h>
a65aa40f 38#include <sys/un.h>
1e03b754 39#include <sys/signalfd.h>
ff2c503d 40#include <sys/epoll.h>
3210a72b 41#include <sys/poll.h>
138068d6 42#include <sys/wait.h>
dc117daa 43#include <sys/stat.h>
c895fd00 44#include <sys/ioctl.h>
01618658 45#include <sys/inotify.h>
761dfddc 46#include <sys/utsname.h>
7fafc032
KS
47
48#include "udev.h"
392ef7a2 49#include "sd-daemon.h"
194bbe33 50#include "cgroup-util.h"
5ba2dc25 51#include "dev-setup.h"
a5c32cff 52#include "fileio.h"
7fafc032 53
c3804728 54static bool debug;
9e8fe79b 55
80df994c 56void udev_main_log(struct udev *udev, int priority,
912541b0
KS
57 const char *file, int line, const char *fn,
58 const char *format, va_list args)
7d563a17 59{
baa30fbc 60 log_metav(priority, file, line, fn, format, args);
7d563a17
KS
61}
62
d7ddce18 63static struct udev_rules *rules;
d59f11e1 64static struct udev_ctrl *udev_ctrl;
1e03b754 65static struct udev_monitor *monitor;
3c6ee190 66static int worker_watch[2] = { -1, -1 };
ff2c503d
KS
67static int fd_signal = -1;
68static int fd_ep = -1;
69static int fd_inotify = -1;
c3804728 70static bool stop_exec_queue;
7c85d636 71static bool reload;
87d55ff6
KS
72static int children;
73static int children_max;
c830e98d 74static int exec_delay;
2181d30a 75static sigset_t sigmask_orig;
ff2c503d
KS
76static UDEV_LIST(event_list);
77static UDEV_LIST(worker_list);
e3dc56a2 78static char *udev_cgroup;
c3804728 79static bool udev_exit;
1e03b754 80
1e03b754 81enum event_state {
912541b0
KS
82 EVENT_UNDEF,
83 EVENT_QUEUED,
84 EVENT_RUNNING,
1e03b754
KS
85};
86
87struct event {
912541b0
KS
88 struct udev_list_node node;
89 struct udev *udev;
90 struct udev_device *dev;
91 enum event_state state;
92 int exitcode;
93 unsigned long long int delaying_seqnum;
94 unsigned long long int seqnum;
95 const char *devpath;
96 size_t devpath_len;
97 const char *devpath_old;
98 dev_t devnum;
912541b0 99 int ifindex;
ea6039a3 100 bool is_block;
d8d4bee7 101#ifdef HAVE_FIRMWARE
ea6039a3 102 bool nodelay;
61e536e1 103#endif
1e03b754
KS
104};
105
b27ee00b 106static inline struct event *node_to_event(struct udev_list_node *node)
7e027927 107{
b27ee00b 108 return container_of(node, struct event, node);
1e03b754
KS
109}
110
ff2c503d
KS
111static void event_queue_cleanup(struct udev *udev, enum event_state type);
112
1e03b754 113enum worker_state {
912541b0
KS
114 WORKER_UNDEF,
115 WORKER_RUNNING,
116 WORKER_IDLE,
117 WORKER_KILLED,
1e03b754
KS
118};
119
120struct worker {
912541b0
KS
121 struct udev_list_node node;
122 struct udev *udev;
123 int refcount;
124 pid_t pid;
125 struct udev_monitor *monitor;
126 enum worker_state state;
127 struct event *event;
40fe8b11 128 usec_t event_start_usec;
1e03b754
KS
129};
130
131/* passed from worker to main process */
132struct worker_message {
912541b0
KS
133 pid_t pid;
134 int exitcode;
1e03b754
KS
135};
136
b27ee00b 137static inline struct worker *node_to_worker(struct udev_list_node *node)
1e03b754 138{
b27ee00b 139 return container_of(node, struct worker, node);
7e027927
KS
140}
141
9ea28c55 142static void event_queue_delete(struct event *event)
fc465079 143{
912541b0 144 udev_list_node_remove(&event->node);
912541b0
KS
145 udev_device_unref(event->dev);
146 free(event);
aa8734ff 147}
7a770250 148
bc113de9
KS
149static struct worker *worker_ref(struct worker *worker)
150{
912541b0
KS
151 worker->refcount++;
152 return worker;
bc113de9
KS
153}
154
ff2c503d
KS
155static void worker_cleanup(struct worker *worker)
156{
912541b0
KS
157 udev_list_node_remove(&worker->node);
158 udev_monitor_unref(worker->monitor);
159 children--;
160 free(worker);
ff2c503d
KS
161}
162
1e03b754
KS
163static void worker_unref(struct worker *worker)
164{
912541b0
KS
165 worker->refcount--;
166 if (worker->refcount > 0)
167 return;
9f6445e3 168 log_debug("worker [%u] cleaned up", worker->pid);
912541b0 169 worker_cleanup(worker);
ff2c503d
KS
170}
171
172static void worker_list_cleanup(struct udev *udev)
173{
912541b0 174 struct udev_list_node *loop, *tmp;
ff2c503d 175
912541b0
KS
176 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
177 struct worker *worker = node_to_worker(loop);
ff2c503d 178
912541b0
KS
179 worker_cleanup(worker);
180 }
fc465079
KS
181}
182
1e03b754 183static void worker_new(struct event *event)
7fafc032 184{
912541b0
KS
185 struct udev *udev = event->udev;
186 struct worker *worker;
187 struct udev_monitor *worker_monitor;
188 pid_t pid;
189
190 /* listen for new events */
191 worker_monitor = udev_monitor_new_from_netlink(udev, NULL);
192 if (worker_monitor == NULL)
193 return;
194 /* allow the main daemon netlink address to send devices to the worker */
195 udev_monitor_allow_unicast_sender(worker_monitor, monitor);
196 udev_monitor_enable_receiving(worker_monitor);
197
955d98c9 198 worker = new0(struct worker, 1);
912541b0
KS
199 if (worker == NULL) {
200 udev_monitor_unref(worker_monitor);
201 return;
202 }
203 /* worker + event reference */
204 worker->refcount = 2;
205 worker->udev = udev;
206
207 pid = fork();
208 switch (pid) {
209 case 0: {
210 struct udev_device *dev = NULL;
211 int fd_monitor;
212 struct epoll_event ep_signal, ep_monitor;
213 sigset_t mask;
214 int rc = EXIT_SUCCESS;
215
43095991 216 /* take initial device from queue */
912541b0
KS
217 dev = event->dev;
218 event->dev = NULL;
219
220 free(worker);
221 worker_list_cleanup(udev);
222 event_queue_cleanup(udev, EVENT_UNDEF);
912541b0
KS
223 udev_monitor_unref(monitor);
224 udev_ctrl_unref(udev_ctrl);
225 close(fd_signal);
226 close(fd_ep);
227 close(worker_watch[READ_END]);
228
229 sigfillset(&mask);
230 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
231 if (fd_signal < 0) {
9f6445e3 232 log_error("error creating signalfd %m");
912541b0
KS
233 rc = 2;
234 goto out;
235 }
236
237 fd_ep = epoll_create1(EPOLL_CLOEXEC);
238 if (fd_ep < 0) {
9f6445e3 239 log_error("error creating epoll fd: %m");
912541b0
KS
240 rc = 3;
241 goto out;
242 }
243
29804cc1 244 memzero(&ep_signal, sizeof(struct epoll_event));
912541b0
KS
245 ep_signal.events = EPOLLIN;
246 ep_signal.data.fd = fd_signal;
247
248 fd_monitor = udev_monitor_get_fd(worker_monitor);
29804cc1 249 memzero(&ep_monitor, sizeof(struct epoll_event));
912541b0
KS
250 ep_monitor.events = EPOLLIN;
251 ep_monitor.data.fd = fd_monitor;
252
253 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
254 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_monitor, &ep_monitor) < 0) {
9f6445e3 255 log_error("fail to add fds to epoll: %m");
912541b0
KS
256 rc = 4;
257 goto out;
258 }
259
260 /* request TERM signal if parent exits */
261 prctl(PR_SET_PDEATHSIG, SIGTERM);
262
145dae7e 263 /* reset OOM score, we only protect the main daemon */
574d5f2d 264 write_string_file("/proc/self/oom_score_adj", "0");
145dae7e 265
912541b0
KS
266 for (;;) {
267 struct udev_event *udev_event;
268 struct worker_message msg;
3ebdb81e 269 int fd_lock = -1;
bf9bead1 270 int err = 0;
912541b0 271
9f6445e3 272 log_debug("seq %llu running", udev_device_get_seqnum(dev));
912541b0
KS
273 udev_event = udev_event_new(dev);
274 if (udev_event == NULL) {
275 rc = 5;
276 goto out;
277 }
278
279 /* needed for SIGCHLD/SIGTERM in spawn() */
280 udev_event->fd_signal = fd_signal;
281
282 if (exec_delay > 0)
283 udev_event->exec_delay = exec_delay;
284
3ebdb81e
KS
285 /*
286 * Take a "read lock" on the device node; this establishes
287 * a concept of device "ownership" to serialize device
288 * access. External processes holding a "write lock" will
289 * cause udev to skip the event handling; in the case udev
290 * acquired the lock, the external process will block until
291 * udev has finished its event handling.
292 */
e918a1b5
KS
293
294 /*
295 * <kabi_> since we make check - device seems unused - we try
296 * ioctl to deactivate - and device is found to be opened
297 * <kay> sure, you try to take a write lock
298 * <kay> if you get it udev is out
299 * <kay> if you can't get it, udev is busy
300 * <kabi_> we cannot deactivate openned device (as it is in-use)
301 * <kay> maybe we should just exclude dm from that thing entirely
302 * <kabi_> IMHO this sounds like a good plan for this moment
303 */
304 if (streq_ptr("block", udev_device_get_subsystem(dev)) &&
305 !startswith("dm-", udev_device_get_sysname(dev))) {
3ebdb81e
KS
306 struct udev_device *d = dev;
307
308 if (streq_ptr("partition", udev_device_get_devtype(d)))
309 d = udev_device_get_parent(d);
310
311 if (d) {
312 fd_lock = open(udev_device_get_devnode(d), O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
313 if (fd_lock >= 0 && flock(fd_lock, LOCK_SH|LOCK_NB) < 0) {
314 log_debug("Unable to flock(%s), skipping event handling: %m", udev_device_get_devnode(d));
315 err = -EWOULDBLOCK;
3d06f418 316 fd_lock = safe_close(fd_lock);
3ebdb81e
KS
317 goto skip;
318 }
319 }
320 }
321
912541b0 322 /* apply rules, create node, symlinks */
1ea97217 323 udev_event_execute_rules(udev_event, rules, &sigmask_orig);
912541b0 324
1ea97217 325 udev_event_execute_run(udev_event, &sigmask_orig);
912541b0
KS
326
327 /* apply/restore inotify watch */
bf9bead1 328 if (udev_event->inotify_watch) {
912541b0
KS
329 udev_watch_begin(udev, dev);
330 udev_device_update_db(dev);
331 }
332
3d06f418 333 safe_close(fd_lock);
3ebdb81e 334
912541b0
KS
335 /* send processed event back to libudev listeners */
336 udev_monitor_send_device(worker_monitor, NULL, dev);
337
3ebdb81e 338skip:
912541b0 339 /* send udevd the result of the event execution */
29804cc1 340 memzero(&msg, sizeof(struct worker_message));
3ebdb81e 341 msg.exitcode = err;
912541b0
KS
342 msg.pid = getpid();
343 send(worker_watch[WRITE_END], &msg, sizeof(struct worker_message), 0);
344
9f6445e3 345 log_debug("seq %llu processed with %i", udev_device_get_seqnum(dev), err);
912541b0
KS
346
347 udev_device_unref(dev);
348 dev = NULL;
349
73814ca2
CW
350 if (udev_event->sigterm) {
351 udev_event_unref(udev_event);
47e737dc 352 goto out;
73814ca2
CW
353 }
354
355 udev_event_unref(udev_event);
47e737dc 356
912541b0
KS
357 /* wait for more device messages from main udevd, or term signal */
358 while (dev == NULL) {
359 struct epoll_event ev[4];
360 int fdcount;
361 int i;
362
8fef0ff2 363 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), -1);
912541b0
KS
364 if (fdcount < 0) {
365 if (errno == EINTR)
366 continue;
9f6445e3 367 log_error("failed to poll: %m");
912541b0
KS
368 goto out;
369 }
370
371 for (i = 0; i < fdcount; i++) {
372 if (ev[i].data.fd == fd_monitor && ev[i].events & EPOLLIN) {
373 dev = udev_monitor_receive_device(worker_monitor);
374 break;
375 } else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN) {
376 struct signalfd_siginfo fdsi;
377 ssize_t size;
378
379 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
380 if (size != sizeof(struct signalfd_siginfo))
381 continue;
382 switch (fdsi.ssi_signo) {
383 case SIGTERM:
384 goto out;
385 }
386 }
387 }
388 }
389 }
82063a88 390out:
912541b0 391 udev_device_unref(dev);
3d06f418
KS
392 safe_close(fd_signal);
393 safe_close(fd_ep);
912541b0
KS
394 close(fd_inotify);
395 close(worker_watch[WRITE_END]);
396 udev_rules_unref(rules);
e64fae55 397 udev_builtin_exit(udev);
912541b0
KS
398 udev_monitor_unref(worker_monitor);
399 udev_unref(udev);
baa30fbc 400 log_close();
912541b0
KS
401 exit(rc);
402 }
403 case -1:
404 udev_monitor_unref(worker_monitor);
405 event->state = EVENT_QUEUED;
406 free(worker);
9f6445e3 407 log_error("fork of child failed: %m");
912541b0
KS
408 break;
409 default:
410 /* close monitor, but keep address around */
411 udev_monitor_disconnect(worker_monitor);
412 worker->monitor = worker_monitor;
413 worker->pid = pid;
414 worker->state = WORKER_RUNNING;
40fe8b11 415 worker->event_start_usec = now(CLOCK_MONOTONIC);
912541b0
KS
416 worker->event = event;
417 event->state = EVENT_RUNNING;
418 udev_list_node_append(&worker->node, &worker_list);
419 children++;
9f6445e3 420 log_debug("seq %llu forked new worker [%u]", udev_device_get_seqnum(event->dev), pid);
912541b0
KS
421 break;
422 }
7fafc032
KS
423}
424
57c6f8ae 425static void event_run(struct event *event)
fc465079 426{
912541b0
KS
427 struct udev_list_node *loop;
428
429 udev_list_node_foreach(loop, &worker_list) {
430 struct worker *worker = node_to_worker(loop);
431 ssize_t count;
432
433 if (worker->state != WORKER_IDLE)
434 continue;
435
436 count = udev_monitor_send_device(monitor, worker->monitor, event->dev);
437 if (count < 0) {
9f6445e3 438 log_error("worker [%u] did not accept message %zi (%m), kill it", worker->pid, count);
912541b0
KS
439 kill(worker->pid, SIGKILL);
440 worker->state = WORKER_KILLED;
441 continue;
442 }
443 worker_ref(worker);
444 worker->event = event;
445 worker->state = WORKER_RUNNING;
40fe8b11 446 worker->event_start_usec = now(CLOCK_MONOTONIC);
912541b0
KS
447 event->state = EVENT_RUNNING;
448 return;
449 }
450
451 if (children >= children_max) {
452 if (children_max > 1)
9f6445e3 453 log_debug("maximum number (%i) of children reached", children);
912541b0
KS
454 return;
455 }
456
457 /* start new worker and pass initial device */
458 worker_new(event);
1e03b754
KS
459}
460
40929a02 461static int event_queue_insert(struct udev_device *dev)
1e03b754 462{
912541b0
KS
463 struct event *event;
464
955d98c9 465 event = new0(struct event, 1);
912541b0
KS
466 if (event == NULL)
467 return -1;
468
469 event->udev = udev_device_get_udev(dev);
470 event->dev = dev;
471 event->seqnum = udev_device_get_seqnum(dev);
472 event->devpath = udev_device_get_devpath(dev);
473 event->devpath_len = strlen(event->devpath);
474 event->devpath_old = udev_device_get_devpath_old(dev);
475 event->devnum = udev_device_get_devnum(dev);
ea6039a3 476 event->is_block = streq("block", udev_device_get_subsystem(dev));
912541b0 477 event->ifindex = udev_device_get_ifindex(dev);
d8d4bee7 478#ifdef HAVE_FIRMWARE
ea6039a3
KS
479 if (streq(udev_device_get_subsystem(dev), "firmware"))
480 event->nodelay = true;
61e536e1 481#endif
912541b0 482
9f6445e3 483 log_debug("seq %llu queued, '%s' '%s'", udev_device_get_seqnum(dev),
912541b0
KS
484 udev_device_get_action(dev), udev_device_get_subsystem(dev));
485
486 event->state = EVENT_QUEUED;
487 udev_list_node_append(&event->node, &event_list);
488 return 0;
fc465079
KS
489}
490
194bbe33 491static void worker_kill(struct udev *udev)
1e03b754 492{
912541b0 493 struct udev_list_node *loop;
1e03b754 494
912541b0
KS
495 udev_list_node_foreach(loop, &worker_list) {
496 struct worker *worker = node_to_worker(loop);
1e03b754 497
912541b0
KS
498 if (worker->state == WORKER_KILLED)
499 continue;
1e03b754 500
912541b0
KS
501 worker->state = WORKER_KILLED;
502 kill(worker->pid, SIGTERM);
503 }
1e03b754
KS
504}
505
e3196993 506/* lookup event for identical, parent, child device */
19711e19 507static bool is_devpath_busy(struct event *event)
7fafc032 508{
912541b0
KS
509 struct udev_list_node *loop;
510 size_t common;
511
512 /* check if queue contains events we depend on */
513 udev_list_node_foreach(loop, &event_list) {
514 struct event *loop_event = node_to_event(loop);
515
516 /* we already found a later event, earlier can not block us, no need to check again */
517 if (loop_event->seqnum < event->delaying_seqnum)
518 continue;
519
520 /* event we checked earlier still exists, no need to check again */
521 if (loop_event->seqnum == event->delaying_seqnum)
522 return true;
523
524 /* found ourself, no later event can block us */
525 if (loop_event->seqnum >= event->seqnum)
526 break;
527
528 /* check major/minor */
529 if (major(event->devnum) != 0 && event->devnum == loop_event->devnum && event->is_block == loop_event->is_block)
530 return true;
531
532 /* check network device ifindex */
533 if (event->ifindex != 0 && event->ifindex == loop_event->ifindex)
534 return true;
535
536 /* check our old name */
090be865 537 if (event->devpath_old != NULL && streq(loop_event->devpath, event->devpath_old)) {
912541b0
KS
538 event->delaying_seqnum = loop_event->seqnum;
539 return true;
540 }
541
542 /* compare devpath */
543 common = MIN(loop_event->devpath_len, event->devpath_len);
544
545 /* one devpath is contained in the other? */
546 if (memcmp(loop_event->devpath, event->devpath, common) != 0)
547 continue;
548
549 /* identical device event found */
550 if (loop_event->devpath_len == event->devpath_len) {
551 /* devices names might have changed/swapped in the meantime */
552 if (major(event->devnum) != 0 && (event->devnum != loop_event->devnum || event->is_block != loop_event->is_block))
553 continue;
554 if (event->ifindex != 0 && event->ifindex != loop_event->ifindex)
555 continue;
556 event->delaying_seqnum = loop_event->seqnum;
557 return true;
558 }
559
d8d4bee7 560#ifdef HAVE_FIRMWARE
ea6039a3
KS
561 /* allow to bypass the dependency tracking */
562 if (event->nodelay)
563 continue;
61e536e1 564#endif
ea6039a3 565
912541b0
KS
566 /* parent device event found */
567 if (event->devpath[common] == '/') {
568 event->delaying_seqnum = loop_event->seqnum;
569 return true;
570 }
571
572 /* child device event found */
573 if (loop_event->devpath[common] == '/') {
574 event->delaying_seqnum = loop_event->seqnum;
575 return true;
576 }
577
578 /* no matching device */
579 continue;
580 }
581
582 return false;
7fafc032
KS
583}
584
ff2c503d 585static void event_queue_start(struct udev *udev)
7fafc032 586{
912541b0 587 struct udev_list_node *loop;
8ab44e3f 588
912541b0
KS
589 udev_list_node_foreach(loop, &event_list) {
590 struct event *event = node_to_event(loop);
0bc74ea7 591
912541b0
KS
592 if (event->state != EVENT_QUEUED)
593 continue;
0bc74ea7 594
912541b0 595 /* do not start event if parent or child event is still running */
baa30fbc 596 if (is_devpath_busy(event))
912541b0 597 continue;
fc465079 598
912541b0
KS
599 event_run(event);
600 }
1e03b754
KS
601}
602
ff2c503d
KS
603static void event_queue_cleanup(struct udev *udev, enum event_state match_type)
604{
912541b0 605 struct udev_list_node *loop, *tmp;
ff2c503d 606
912541b0
KS
607 udev_list_node_foreach_safe(loop, tmp, &event_list) {
608 struct event *event = node_to_event(loop);
ff2c503d 609
912541b0
KS
610 if (match_type != EVENT_UNDEF && match_type != event->state)
611 continue;
ff2c503d 612
9ea28c55 613 event_queue_delete(event);
912541b0 614 }
ff2c503d
KS
615}
616
617static void worker_returned(int fd_worker)
1e03b754 618{
912541b0
KS
619 for (;;) {
620 struct worker_message msg;
621 ssize_t size;
622 struct udev_list_node *loop;
623
624 size = recv(fd_worker, &msg, sizeof(struct worker_message), MSG_DONTWAIT);
625 if (size != sizeof(struct worker_message))
626 break;
627
628 /* lookup worker who sent the signal */
629 udev_list_node_foreach(loop, &worker_list) {
630 struct worker *worker = node_to_worker(loop);
631
632 if (worker->pid != msg.pid)
633 continue;
634
635 /* worker returned */
e64fae55
KS
636 if (worker->event) {
637 worker->event->exitcode = msg.exitcode;
9ea28c55 638 event_queue_delete(worker->event);
e64fae55
KS
639 worker->event = NULL;
640 }
912541b0
KS
641 if (worker->state != WORKER_KILLED)
642 worker->state = WORKER_IDLE;
643 worker_unref(worker);
644 break;
645 }
646 }
88f4b648
KS
647}
648
3b47c739 649/* receive the udevd message from userspace */
ff2c503d 650static struct udev_ctrl_connection *handle_ctrl_msg(struct udev_ctrl *uctrl)
7fafc032 651{
912541b0
KS
652 struct udev *udev = udev_ctrl_get_udev(uctrl);
653 struct udev_ctrl_connection *ctrl_conn;
654 struct udev_ctrl_msg *ctrl_msg = NULL;
655 const char *str;
656 int i;
657
658 ctrl_conn = udev_ctrl_get_connection(uctrl);
659 if (ctrl_conn == NULL)
660 goto out;
661
662 ctrl_msg = udev_ctrl_receive_msg(ctrl_conn);
663 if (ctrl_msg == NULL)
664 goto out;
665
666 i = udev_ctrl_get_set_log_level(ctrl_msg);
667 if (i >= 0) {
ed14edc0 668 log_debug("udevd message (SET_LOG_LEVEL) received, log_priority=%i", i);
baa30fbc 669 log_set_max_level(i);
912541b0 670 udev_set_log_priority(udev, i);
194bbe33 671 worker_kill(udev);
912541b0
KS
672 }
673
674 if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
9f6445e3 675 log_debug("udevd message (STOP_EXEC_QUEUE) received");
912541b0
KS
676 stop_exec_queue = true;
677 }
678
679 if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
9f6445e3 680 log_debug("udevd message (START_EXEC_QUEUE) received");
912541b0
KS
681 stop_exec_queue = false;
682 }
683
684 if (udev_ctrl_get_reload(ctrl_msg) > 0) {
9f6445e3 685 log_debug("udevd message (RELOAD) received");
912541b0
KS
686 reload = true;
687 }
688
689 str = udev_ctrl_get_set_env(ctrl_msg);
690 if (str != NULL) {
691 char *key;
692
693 key = strdup(str);
694 if (key != NULL) {
695 char *val;
696
697 val = strchr(key, '=');
698 if (val != NULL) {
699 val[0] = '\0';
700 val = &val[1];
701 if (val[0] == '\0') {
9f6445e3 702 log_debug("udevd message (ENV) received, unset '%s'", key);
912541b0
KS
703 udev_add_property(udev, key, NULL);
704 } else {
9f6445e3 705 log_debug("udevd message (ENV) received, set '%s=%s'", key, val);
912541b0
KS
706 udev_add_property(udev, key, val);
707 }
708 } else {
9f6445e3 709 log_error("wrong key format '%s'", key);
912541b0
KS
710 }
711 free(key);
712 }
194bbe33 713 worker_kill(udev);
912541b0
KS
714 }
715
716 i = udev_ctrl_get_set_children_max(ctrl_msg);
717 if (i >= 0) {
9f6445e3 718 log_debug("udevd message (SET_MAX_CHILDREN) received, children_max=%i", i);
912541b0
KS
719 children_max = i;
720 }
721
722 if (udev_ctrl_get_ping(ctrl_msg) > 0)
9f6445e3 723 log_debug("udevd message (SYNC) received");
912541b0
KS
724
725 if (udev_ctrl_get_exit(ctrl_msg) > 0) {
9f6445e3 726 log_debug("udevd message (EXIT) received");
912541b0
KS
727 udev_exit = true;
728 /* keep reference to block the client until we exit */
729 udev_ctrl_connection_ref(ctrl_conn);
730 }
ff2c503d 731out:
912541b0
KS
732 udev_ctrl_msg_unref(ctrl_msg);
733 return udev_ctrl_connection_unref(ctrl_conn);
88f4b648 734}
4a231017 735
bd284db1
SJR
736/* read inotify messages */
737static int handle_inotify(struct udev *udev)
738{
912541b0
KS
739 int nbytes, pos;
740 char *buf;
741 struct inotify_event *ev;
742
743 if ((ioctl(fd_inotify, FIONREAD, &nbytes) < 0) || (nbytes <= 0))
744 return 0;
745
746 buf = malloc(nbytes);
747 if (buf == NULL) {
9f6445e3 748 log_error("error getting buffer for inotify");
912541b0
KS
749 return -1;
750 }
751
752 nbytes = read(fd_inotify, buf, nbytes);
753
754 for (pos = 0; pos < nbytes; pos += sizeof(struct inotify_event) + ev->len) {
755 struct udev_device *dev;
756
757 ev = (struct inotify_event *)(buf + pos);
758 dev = udev_watch_lookup(udev, ev->wd);
759 if (dev != NULL) {
9f6445e3 760 log_debug("inotify event: %x for %s", ev->mask, udev_device_get_devnode(dev));
912541b0
KS
761 if (ev->mask & IN_CLOSE_WRITE) {
762 char filename[UTIL_PATH_SIZE];
763 int fd;
764
9f6445e3 765 log_debug("device %s closed, synthesising 'change'", udev_device_get_devnode(dev));
d5a89d7d 766 strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
c8a202b7 767 fd = open(filename, O_WRONLY|O_CLOEXEC);
912541b0
KS
768 if (fd >= 0) {
769 if (write(fd, "change", 6) < 0)
9f6445e3 770 log_debug("error writing uevent: %m");
912541b0
KS
771 close(fd);
772 }
773 }
774 if (ev->mask & IN_IGNORED)
775 udev_watch_end(udev, dev);
776
777 udev_device_unref(dev);
778 }
779
780 }
781
782 free(buf);
783 return 0;
bd284db1
SJR
784}
785
45798927 786static void handle_signal(struct udev *udev, int signo)
7fafc032 787{
912541b0
KS
788 switch (signo) {
789 case SIGINT:
790 case SIGTERM:
791 udev_exit = true;
792 break;
793 case SIGCHLD:
794 for (;;) {
795 pid_t pid;
796 int status;
797 struct udev_list_node *loop, *tmp;
798
799 pid = waitpid(-1, &status, WNOHANG);
800 if (pid <= 0)
801 break;
802
803 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
804 struct worker *worker = node_to_worker(loop);
805
806 if (worker->pid != pid)
807 continue;
9f6445e3 808 log_debug("worker [%u] exit", pid);
912541b0
KS
809
810 if (WIFEXITED(status)) {
811 if (WEXITSTATUS(status) != 0)
9f6445e3 812 log_error("worker [%u] exit with return code %i",
97fec53e 813 pid, WEXITSTATUS(status));
912541b0 814 } else if (WIFSIGNALED(status)) {
9f6445e3 815 log_error("worker [%u] terminated by signal %i (%s)",
97fec53e 816 pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
912541b0 817 } else if (WIFSTOPPED(status)) {
9f6445e3 818 log_error("worker [%u] stopped", pid);
912541b0 819 } else if (WIFCONTINUED(status)) {
9f6445e3 820 log_error("worker [%u] continued", pid);
912541b0 821 } else {
9f6445e3 822 log_error("worker [%u] exit with status 0x%04x", pid, status);
912541b0
KS
823 }
824
825 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
e64fae55 826 if (worker->event) {
9f6445e3 827 log_error("worker [%u] failed while handling '%s'",
baa30fbc 828 pid, worker->event->devpath);
912541b0 829 worker->event->exitcode = -32;
9ea28c55
KS
830 event_queue_delete(worker->event);
831
912541b0
KS
832 /* drop reference taken for state 'running' */
833 worker_unref(worker);
834 }
835 }
836 worker_unref(worker);
837 break;
838 }
839 }
840 break;
841 case SIGHUP:
842 reload = true;
843 break;
844 }
f27125f9 845}
846
7459bcdc
KS
847static int systemd_fds(struct udev *udev, int *rctrl, int *rnetlink)
848{
912541b0
KS
849 int ctrl = -1, netlink = -1;
850 int fd, n;
851
852 n = sd_listen_fds(true);
853 if (n <= 0)
854 return -1;
855
856 for (fd = SD_LISTEN_FDS_START; fd < n + SD_LISTEN_FDS_START; fd++) {
857 if (sd_is_socket(fd, AF_LOCAL, SOCK_SEQPACKET, -1)) {
858 if (ctrl >= 0)
859 return -1;
860 ctrl = fd;
861 continue;
862 }
863
864 if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1)) {
865 if (netlink >= 0)
866 return -1;
867 netlink = fd;
868 continue;
869 }
870
871 return -1;
872 }
873
874 if (ctrl < 0 || netlink < 0)
875 return -1;
876
9f6445e3 877 log_debug("ctrl=%i netlink=%i", ctrl, netlink);
912541b0
KS
878 *rctrl = ctrl;
879 *rnetlink = netlink;
880 return 0;
7459bcdc
KS
881}
882
e6f86cac
KS
883/*
884 * read the kernel commandline, in case we need to get into debug mode
885 * udev.log-priority=<level> syslog priority
886 * udev.children-max=<number of workers> events are fully serialized if set to 1
887 * udev.exec-delay=<number of seconds> delay execution of every executed program
888 */
889static void kernel_cmdline_options(struct udev *udev)
890{
74df0fca
LP
891 _cleanup_free_ char *line = NULL;
892 char *w, *state;
e6f86cac 893 size_t l;
74df0fca 894 int r;
e6f86cac 895
74df0fca
LP
896 r = proc_cmdline(&line);
897 if (r < 0)
898 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
899 if (r <= 0)
e6f86cac
KS
900 return;
901
902 FOREACH_WORD_QUOTED(w, l, line, state) {
903 char *s, *opt;
904
905 s = strndup(w, l);
906 if (!s)
907 break;
908
909 /* accept the same options for the initrd, prefixed with "rd." */
910 if (in_initrd() && startswith(s, "rd."))
911 opt = s + 3;
912 else
913 opt = s;
914
023b9d33
KS
915 if (startswith(opt, "udev.log-priority=")) {
916 int prio;
e6f86cac 917
023b9d33
KS
918 prio = util_log_priority(opt + 18);
919 log_set_max_level(prio);
920 udev_set_log_priority(udev, prio);
921 } else if (startswith(opt, "udev.children-max=")) {
e6f86cac 922 children_max = strtoul(opt + 18, NULL, 0);
023b9d33 923 } else if (startswith(opt, "udev.exec-delay=")) {
e6f86cac 924 exec_delay = strtoul(opt + 16, NULL, 0);
023b9d33 925 }
e6f86cac
KS
926
927 free(s);
928 }
e6f86cac
KS
929}
930
59345311 931int main(int argc, char *argv[])
c2cf4012 932{
912541b0 933 struct udev *udev;
912541b0
KS
934 sigset_t mask;
935 int daemonize = false;
936 int resolve_names = 1;
937 static const struct option options[] = {
938 { "daemon", no_argument, NULL, 'd' },
939 { "debug", no_argument, NULL, 'D' },
940 { "children-max", required_argument, NULL, 'c' },
941 { "exec-delay", required_argument, NULL, 'e' },
942 { "resolve-names", required_argument, NULL, 'N' },
943 { "help", no_argument, NULL, 'h' },
944 { "version", no_argument, NULL, 'V' },
945 {}
946 };
947 int fd_ctrl = -1;
948 int fd_netlink = -1;
949 int fd_worker = -1;
950 struct epoll_event ep_ctrl, ep_inotify, ep_signal, ep_netlink, ep_worker;
951 struct udev_ctrl_connection *ctrl_conn = NULL;
912541b0
KS
952 int rc = 1;
953
954 udev = udev_new();
955 if (udev == NULL)
956 goto exit;
957
4b261568 958 log_set_target(LOG_TARGET_AUTO);
baa30fbc 959 log_parse_environment();
4b261568 960 log_open();
689a97f5 961
912541b0 962 udev_set_log_fn(udev, udev_main_log);
689a97f5
TG
963 log_set_max_level(udev_get_log_priority(udev));
964
9f6445e3 965 log_debug("version %s", VERSION);
0f9963a8 966 label_init("/dev");
912541b0
KS
967
968 for (;;) {
969 int option;
970
5bbbe461 971 option = getopt_long(argc, argv, "c:de:DtN:hV", options, NULL);
912541b0
KS
972 if (option == -1)
973 break;
974
975 switch (option) {
976 case 'd':
977 daemonize = true;
978 break;
979 case 'c':
980 children_max = strtoul(optarg, NULL, 0);
981 break;
982 case 'e':
983 exec_delay = strtoul(optarg, NULL, 0);
984 break;
985 case 'D':
986 debug = true;
194bbe33 987 log_set_max_level(LOG_DEBUG);
7781e063 988 udev_set_log_priority(udev, LOG_DEBUG);
912541b0
KS
989 break;
990 case 'N':
090be865 991 if (streq(optarg, "early")) {
912541b0 992 resolve_names = 1;
090be865 993 } else if (streq(optarg, "late")) {
912541b0 994 resolve_names = 0;
090be865 995 } else if (streq(optarg, "never")) {
912541b0
KS
996 resolve_names = -1;
997 } else {
998 fprintf(stderr, "resolve-names must be early, late or never\n");
9f6445e3 999 log_error("resolve-names must be early, late or never");
912541b0
KS
1000 goto exit;
1001 }
1002 break;
1003 case 'h':
1004 printf("Usage: udevd OPTIONS\n"
1005 " --daemon\n"
1006 " --debug\n"
1007 " --children-max=<maximum number of workers>\n"
1008 " --exec-delay=<seconds to wait before executing RUN=>\n"
1009 " --resolve-names=early|late|never\n"
1010 " --version\n"
1011 " --help\n"
1012 "\n");
1013 goto exit;
1014 case 'V':
1015 printf("%s\n", VERSION);
1016 goto exit;
1017 default:
1018 goto exit;
1019 }
1020 }
1021
e6f86cac 1022 kernel_cmdline_options(udev);
912541b0
KS
1023
1024 if (getuid() != 0) {
1025 fprintf(stderr, "root privileges required\n");
9f6445e3 1026 log_error("root privileges required");
912541b0
KS
1027 goto exit;
1028 }
1029
1030 /* set umask before creating any file/directory */
1031 chdir("/");
1032 umask(022);
1033
6ada823a 1034 mkdir("/run/udev", 0755);
912541b0 1035
01ed0e23 1036 dev_setup(NULL);
912541b0
KS
1037
1038 /* before opening new files, make sure std{in,out,err} fds are in a sane state */
1039 if (daemonize) {
1040 int fd;
1041
1042 fd = open("/dev/null", O_RDWR);
1043 if (fd >= 0) {
1044 if (write(STDOUT_FILENO, 0, 0) < 0)
1045 dup2(fd, STDOUT_FILENO);
1046 if (write(STDERR_FILENO, 0, 0) < 0)
1047 dup2(fd, STDERR_FILENO);
1048 if (fd > STDERR_FILENO)
1049 close(fd);
1050 } else {
1051 fprintf(stderr, "cannot open /dev/null\n");
9f6445e3 1052 log_error("cannot open /dev/null");
912541b0
KS
1053 }
1054 }
1055
1056 if (systemd_fds(udev, &fd_ctrl, &fd_netlink) >= 0) {
c5315881 1057 /* get control and netlink socket from systemd */
912541b0
KS
1058 udev_ctrl = udev_ctrl_new_from_fd(udev, fd_ctrl);
1059 if (udev_ctrl == NULL) {
baa30fbc 1060 log_error("error taking over udev control socket");
912541b0
KS
1061 rc = 1;
1062 goto exit;
1063 }
1064
1065 monitor = udev_monitor_new_from_netlink_fd(udev, "kernel", fd_netlink);
1066 if (monitor == NULL) {
9f6445e3 1067 log_error("error taking over netlink socket");
912541b0
KS
1068 rc = 3;
1069 goto exit;
1070 }
194bbe33
KS
1071
1072 /* get our own cgroup, we regularly kill everything udev has left behind */
7027ff61 1073 if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &udev_cgroup) < 0)
194bbe33 1074 udev_cgroup = NULL;
912541b0
KS
1075 } else {
1076 /* open control and netlink socket */
1077 udev_ctrl = udev_ctrl_new(udev);
1078 if (udev_ctrl == NULL) {
1079 fprintf(stderr, "error initializing udev control socket");
baa30fbc 1080 log_error("error initializing udev control socket");
912541b0
KS
1081 rc = 1;
1082 goto exit;
1083 }
1084 fd_ctrl = udev_ctrl_get_fd(udev_ctrl);
1085
1086 monitor = udev_monitor_new_from_netlink(udev, "kernel");
1087 if (monitor == NULL) {
1088 fprintf(stderr, "error initializing netlink socket\n");
9f6445e3 1089 log_error("error initializing netlink socket");
912541b0
KS
1090 rc = 3;
1091 goto exit;
1092 }
1093 fd_netlink = udev_monitor_get_fd(monitor);
1094 }
1095
1096 if (udev_monitor_enable_receiving(monitor) < 0) {
1097 fprintf(stderr, "error binding netlink socket\n");
9f6445e3 1098 log_error("error binding netlink socket");
912541b0
KS
1099 rc = 3;
1100 goto exit;
1101 }
1102
1103 if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
1104 fprintf(stderr, "error binding udev control socket\n");
9f6445e3 1105 log_error("error binding udev control socket");
912541b0
KS
1106 rc = 1;
1107 goto exit;
1108 }
1109
9ea28c55 1110 udev_monitor_set_receive_buffer_size(monitor, 128 * 1024 * 1024);
912541b0
KS
1111
1112 if (daemonize) {
1113 pid_t pid;
912541b0
KS
1114
1115 pid = fork();
1116 switch (pid) {
1117 case 0:
1118 break;
1119 case -1:
9f6445e3 1120 log_error("fork of daemon failed: %m");
912541b0
KS
1121 rc = 4;
1122 goto exit;
1123 default:
1124 rc = EXIT_SUCCESS;
1125 goto exit_daemonize;
1126 }
1127
1128 setsid();
1129
574d5f2d 1130 write_string_file("/proc/self/oom_score_adj", "-1000");
912541b0
KS
1131 } else {
1132 sd_notify(1, "READY=1");
1133 }
1134
c6eefe36 1135 print_kmsg("starting version " VERSION "\n");
912541b0
KS
1136
1137 if (!debug) {
1138 int fd;
1139
1140 fd = open("/dev/null", O_RDWR);
1141 if (fd >= 0) {
1142 dup2(fd, STDIN_FILENO);
1143 dup2(fd, STDOUT_FILENO);
1144 dup2(fd, STDERR_FILENO);
1145 close(fd);
1146 }
1147 }
1148
1149 fd_inotify = udev_watch_init(udev);
1150 if (fd_inotify < 0) {
1151 fprintf(stderr, "error initializing inotify\n");
9f6445e3 1152 log_error("error initializing inotify");
912541b0
KS
1153 rc = 4;
1154 goto exit;
1155 }
1156 udev_watch_restore(udev);
1157
1158 /* block and listen to all signals on signalfd */
1159 sigfillset(&mask);
1160 sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
1161 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
1162 if (fd_signal < 0) {
1163 fprintf(stderr, "error creating signalfd\n");
9f6445e3 1164 log_error("error creating signalfd");
912541b0
KS
1165 rc = 5;
1166 goto exit;
1167 }
1168
1169 /* unnamed socket from workers to the main daemon */
1170 if (socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, worker_watch) < 0) {
1171 fprintf(stderr, "error creating socketpair\n");
9f6445e3 1172 log_error("error creating socketpair");
912541b0
KS
1173 rc = 6;
1174 goto exit;
1175 }
1176 fd_worker = worker_watch[READ_END];
1177
1178 udev_builtin_init(udev);
1179
1180 rules = udev_rules_new(udev, resolve_names);
1181 if (rules == NULL) {
9f6445e3 1182 log_error("error reading rules");
912541b0
KS
1183 goto exit;
1184 }
1185
29804cc1 1186 memzero(&ep_ctrl, sizeof(struct epoll_event));
912541b0
KS
1187 ep_ctrl.events = EPOLLIN;
1188 ep_ctrl.data.fd = fd_ctrl;
1189
29804cc1 1190 memzero(&ep_inotify, sizeof(struct epoll_event));
912541b0
KS
1191 ep_inotify.events = EPOLLIN;
1192 ep_inotify.data.fd = fd_inotify;
1193
29804cc1 1194 memzero(&ep_signal, sizeof(struct epoll_event));
912541b0
KS
1195 ep_signal.events = EPOLLIN;
1196 ep_signal.data.fd = fd_signal;
1197
29804cc1 1198 memzero(&ep_netlink, sizeof(struct epoll_event));
912541b0
KS
1199 ep_netlink.events = EPOLLIN;
1200 ep_netlink.data.fd = fd_netlink;
1201
29804cc1 1202 memzero(&ep_worker, sizeof(struct epoll_event));
912541b0
KS
1203 ep_worker.events = EPOLLIN;
1204 ep_worker.data.fd = fd_worker;
1205
1206 fd_ep = epoll_create1(EPOLL_CLOEXEC);
1207 if (fd_ep < 0) {
9f6445e3 1208 log_error("error creating epoll fd: %m");
912541b0
KS
1209 goto exit;
1210 }
1211 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_ctrl, &ep_ctrl) < 0 ||
1212 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_inotify, &ep_inotify) < 0 ||
1213 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
1214 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_netlink, &ep_netlink) < 0 ||
1215 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_worker, &ep_worker) < 0) {
9f6445e3 1216 log_error("fail to add fds to epoll: %m");
912541b0
KS
1217 goto exit;
1218 }
1219
912541b0 1220 if (children_max <= 0) {
8cc3f8c0 1221 cpu_set_t cpu_set;
912541b0 1222
8cc3f8c0
HH
1223 children_max = 8;
1224
1225 if (sched_getaffinity(0, sizeof (cpu_set), &cpu_set) == 0) {
1226 children_max += CPU_COUNT(&cpu_set) * 2;
1227 }
912541b0 1228 }
9f6445e3 1229 log_debug("set children_max to %u", children_max);
912541b0 1230
84b6ad70
TG
1231 rc = udev_rules_apply_static_dev_perms(rules);
1232 if (rc < 0)
9f6445e3 1233 log_error("failed to apply permissions on static device nodes - %s", strerror(-rc));
912541b0
KS
1234
1235 udev_list_node_init(&event_list);
1236 udev_list_node_init(&worker_list);
1237
1238 for (;;) {
40fe8b11 1239 static usec_t last_usec;
912541b0
KS
1240 struct epoll_event ev[8];
1241 int fdcount;
1242 int timeout;
1243 bool is_worker, is_signal, is_inotify, is_netlink, is_ctrl;
1244 int i;
1245
1246 if (udev_exit) {
1247 /* close sources of new events and discard buffered events */
1248 if (fd_ctrl >= 0) {
1249 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_ctrl, NULL);
1250 fd_ctrl = -1;
1251 }
1252 if (monitor != NULL) {
1253 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_netlink, NULL);
1254 udev_monitor_unref(monitor);
1255 monitor = NULL;
1256 }
1257 if (fd_inotify >= 0) {
1258 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_inotify, NULL);
1259 close(fd_inotify);
1260 fd_inotify = -1;
1261 }
1262
1263 /* discard queued events and kill workers */
1264 event_queue_cleanup(udev, EVENT_QUEUED);
194bbe33 1265 worker_kill(udev);
912541b0
KS
1266
1267 /* exit after all has cleaned up */
9ea28c55 1268 if (udev_list_node_is_empty(&event_list) && children == 0)
912541b0
KS
1269 break;
1270
1271 /* timeout at exit for workers to finish */
9ea28c55
KS
1272 timeout = 30 * MSEC_PER_SEC;
1273 } else if (udev_list_node_is_empty(&event_list) && children == 0) {
e64fae55 1274 /* we are idle */
912541b0 1275 timeout = -1;
194bbe33
KS
1276
1277 /* cleanup possible left-over processes in our cgroup */
1278 if (udev_cgroup)
1279 cg_kill(SYSTEMD_CGROUP_CONTROLLER, udev_cgroup, SIGKILL, false, true, NULL);
e64fae55
KS
1280 } else {
1281 /* kill idle or hanging workers */
9ea28c55 1282 timeout = 3 * MSEC_PER_SEC;
912541b0 1283 }
9ea28c55
KS
1284
1285 /* tell settle that we are busy or idle */
1286 if (!udev_list_node_is_empty(&event_list)) {
1287 int fd;
1288
1289 fd = open("/run/udev/queue", O_WRONLY|O_CREAT|O_CLOEXEC|O_TRUNC|O_NOFOLLOW, 0444);
1290 if (fd >= 0)
1291 close(fd);
1292 } else {
1293 unlink("/run/udev/queue");
1294 }
1295
8fef0ff2 1296 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
912541b0
KS
1297 if (fdcount < 0)
1298 continue;
1299
1300 if (fdcount == 0) {
e64fae55
KS
1301 struct udev_list_node *loop;
1302
1303 /* timeout */
912541b0 1304 if (udev_exit) {
9f6445e3 1305 log_error("timeout, giving up waiting for workers to finish");
912541b0
KS
1306 break;
1307 }
1308
e64fae55
KS
1309 /* kill idle workers */
1310 if (udev_list_node_is_empty(&event_list)) {
9f6445e3 1311 log_debug("cleanup idle workers");
194bbe33 1312 worker_kill(udev);
e64fae55
KS
1313 }
1314
1315 /* check for hanging events */
1316 udev_list_node_foreach(loop, &worker_list) {
1317 struct worker *worker = node_to_worker(loop);
1318
1319 if (worker->state != WORKER_RUNNING)
1320 continue;
1321
9ea28c55 1322 if ((now(CLOCK_MONOTONIC) - worker->event_start_usec) > 30 * USEC_PER_SEC) {
9f6445e3 1323 log_error("worker [%u] %s timeout; kill it", worker->pid,
e64fae55
KS
1324 worker->event ? worker->event->devpath : "<idle>");
1325 kill(worker->pid, SIGKILL);
1326 worker->state = WORKER_KILLED;
9ea28c55 1327
e64fae55
KS
1328 /* drop reference taken for state 'running' */
1329 worker_unref(worker);
1330 if (worker->event) {
9ea28c55 1331 log_error("seq %llu '%s' killed", udev_device_get_seqnum(worker->event->dev), worker->event->devpath);
e64fae55 1332 worker->event->exitcode = -64;
9ea28c55 1333 event_queue_delete(worker->event);
e64fae55
KS
1334 worker->event = NULL;
1335 }
1336 }
1337 }
1338
912541b0
KS
1339 }
1340
1341 is_worker = is_signal = is_inotify = is_netlink = is_ctrl = false;
1342 for (i = 0; i < fdcount; i++) {
1343 if (ev[i].data.fd == fd_worker && ev[i].events & EPOLLIN)
1344 is_worker = true;
1345 else if (ev[i].data.fd == fd_netlink && ev[i].events & EPOLLIN)
1346 is_netlink = true;
1347 else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN)
1348 is_signal = true;
1349 else if (ev[i].data.fd == fd_inotify && ev[i].events & EPOLLIN)
1350 is_inotify = true;
1351 else if (ev[i].data.fd == fd_ctrl && ev[i].events & EPOLLIN)
1352 is_ctrl = true;
1353 }
1354
1355 /* check for changed config, every 3 seconds at most */
9ea28c55 1356 if ((now(CLOCK_MONOTONIC) - last_usec) > 3 * USEC_PER_SEC) {
6ada823a 1357 if (udev_rules_check_timestamp(rules))
912541b0
KS
1358 reload = true;
1359 if (udev_builtin_validate(udev))
1360 reload = true;
1361
40fe8b11 1362 last_usec = now(CLOCK_MONOTONIC);
912541b0
KS
1363 }
1364
1365 /* reload requested, HUP signal received, rules changed, builtin changed */
1366 if (reload) {
194bbe33 1367 worker_kill(udev);
912541b0
KS
1368 rules = udev_rules_unref(rules);
1369 udev_builtin_exit(udev);
7781e063 1370 reload = false;
912541b0
KS
1371 }
1372
1373 /* event has finished */
1374 if (is_worker)
1375 worker_returned(fd_worker);
1376
1377 if (is_netlink) {
1378 struct udev_device *dev;
1379
1380 dev = udev_monitor_receive_device(monitor);
1381 if (dev != NULL) {
40fe8b11 1382 udev_device_set_usec_initialized(dev, now(CLOCK_MONOTONIC));
912541b0
KS
1383 if (event_queue_insert(dev) < 0)
1384 udev_device_unref(dev);
1385 }
1386 }
1387
1388 /* start new events */
1389 if (!udev_list_node_is_empty(&event_list) && !udev_exit && !stop_exec_queue) {
7781e063 1390 udev_builtin_init(udev);
912541b0
KS
1391 if (rules == NULL)
1392 rules = udev_rules_new(udev, resolve_names);
1393 if (rules != NULL)
1394 event_queue_start(udev);
1395 }
1396
1397 if (is_signal) {
1398 struct signalfd_siginfo fdsi;
1399 ssize_t size;
1400
1401 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
1402 if (size == sizeof(struct signalfd_siginfo))
1403 handle_signal(udev, fdsi.ssi_signo);
1404 }
1405
1406 /* we are shutting down, the events below are not handled anymore */
1407 if (udev_exit)
1408 continue;
1409
1410 /* device node watch */
1411 if (is_inotify)
1412 handle_inotify(udev);
1413
1414 /*
1415 * This needs to be after the inotify handling, to make sure,
1416 * that the ping is send back after the possibly generated
1417 * "change" events by the inotify device node watch.
1418 *
1419 * A single time we may receive a client connection which we need to
1420 * keep open to block the client. It will be closed right before we
1421 * exit.
1422 */
1423 if (is_ctrl)
1424 ctrl_conn = handle_ctrl_msg(udev_ctrl);
1425 }
1426
1427 rc = EXIT_SUCCESS;
53921bfa 1428exit:
912541b0 1429 udev_ctrl_cleanup(udev_ctrl);
9ea28c55 1430 unlink("/run/udev/queue");
1f5a5100 1431exit_daemonize:
912541b0
KS
1432 if (fd_ep >= 0)
1433 close(fd_ep);
1434 worker_list_cleanup(udev);
1435 event_queue_cleanup(udev, EVENT_UNDEF);
1436 udev_rules_unref(rules);
1437 udev_builtin_exit(udev);
1438 if (fd_signal >= 0)
1439 close(fd_signal);
1440 if (worker_watch[READ_END] >= 0)
1441 close(worker_watch[READ_END]);
1442 if (worker_watch[WRITE_END] >= 0)
1443 close(worker_watch[WRITE_END]);
1444 udev_monitor_unref(monitor);
912541b0
KS
1445 udev_ctrl_connection_unref(ctrl_conn);
1446 udev_ctrl_unref(udev_ctrl);
e9a5ef7c 1447 label_finish();
912541b0 1448 udev_unref(udev);
baa30fbc 1449 log_close();
912541b0 1450 return rc;
7fafc032 1451}