2 * Copyright (C) 2004-2012 Kay Sievers <kay@vrfy.org>
3 * Copyright (C) 2004 Chris Friesen <chris_friesen@sympatico.ca>
4 * Copyright (C) 2009 Canonical Ltd.
5 * Copyright (C) 2009 Scott James Remnant <scott@netsplit.com>
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.
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.
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/>.
36 #include <sys/prctl.h>
37 #include <sys/socket.h>
39 #include <sys/signalfd.h>
40 #include <sys/epoll.h>
41 #include <sys/mount.h>
45 #include <sys/ioctl.h>
46 #include <sys/inotify.h>
47 #include <sys/utsname.h>
49 #include "sd-daemon.h"
50 #include "rtnl-util.h"
51 #include "cgroup-util.h"
52 #include "dev-setup.h"
54 #include "selinux-util.h"
56 #include "udev-util.h"
58 static struct udev_rules *rules;
59 static struct udev_ctrl *udev_ctrl;
60 static struct udev_monitor *monitor;
61 static int worker_watch[2] = { -1, -1 };
62 static int fd_signal = -1;
63 static int fd_ep = -1;
64 static int fd_inotify = -1;
65 static bool stop_exec_queue;
68 static bool arg_debug = false;
69 static int arg_daemonize = false;
70 static int arg_resolve_names = 1;
71 static int arg_children_max;
72 static int arg_exec_delay;
73 static usec_t arg_event_timeout_usec = 180 * USEC_PER_SEC;
74 static usec_t arg_event_timeout_warn_usec = 180 * USEC_PER_SEC / 3;
75 static sigset_t sigmask_orig;
76 static UDEV_LIST(event_list);
77 static UDEV_LIST(worker_list);
78 static char *udev_cgroup;
79 static struct udev_list properties_list;
80 static bool udev_exit;
89 struct udev_list_node node;
91 struct udev_device *dev;
92 enum event_state state;
94 unsigned long long int delaying_seqnum;
95 unsigned long long int seqnum;
98 const char *devpath_old;
104 static inline struct event *node_to_event(struct udev_list_node *node) {
105 return container_of(node, struct event, node);
108 static void event_queue_cleanup(struct udev *udev, enum event_state type);
118 struct udev_list_node node;
122 struct udev_monitor *monitor;
123 enum worker_state state;
125 usec_t event_start_usec;
129 /* passed from worker to main process */
130 struct worker_message {
135 static inline struct worker *node_to_worker(struct udev_list_node *node) {
136 return container_of(node, struct worker, node);
139 static void event_queue_delete(struct event *event) {
140 udev_list_node_remove(&event->node);
141 udev_device_unref(event->dev);
145 static struct worker *worker_ref(struct worker *worker) {
150 static void worker_cleanup(struct worker *worker) {
151 udev_list_node_remove(&worker->node);
152 udev_monitor_unref(worker->monitor);
157 static void worker_unref(struct worker *worker) {
159 if (worker->refcount > 0)
161 log_debug("worker [%u] cleaned up", worker->pid);
162 worker_cleanup(worker);
165 static void worker_list_cleanup(struct udev *udev) {
166 struct udev_list_node *loop, *tmp;
168 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
169 struct worker *worker = node_to_worker(loop);
171 worker_cleanup(worker);
175 static void worker_new(struct event *event) {
176 struct udev *udev = event->udev;
177 struct worker *worker;
178 struct udev_monitor *worker_monitor;
181 /* listen for new events */
182 worker_monitor = udev_monitor_new_from_netlink(udev, NULL);
183 if (worker_monitor == NULL)
185 /* allow the main daemon netlink address to send devices to the worker */
186 udev_monitor_allow_unicast_sender(worker_monitor, monitor);
187 udev_monitor_enable_receiving(worker_monitor);
189 worker = new0(struct worker, 1);
190 if (worker == NULL) {
191 udev_monitor_unref(worker_monitor);
194 /* worker + event reference */
195 worker->refcount = 2;
201 struct udev_device *dev = NULL;
203 _cleanup_rtnl_unref_ sd_rtnl *rtnl = NULL;
204 struct epoll_event ep_signal, ep_monitor;
206 int rc = EXIT_SUCCESS;
208 /* take initial device from queue */
213 worker_list_cleanup(udev);
214 event_queue_cleanup(udev, EVENT_UNDEF);
215 udev_monitor_unref(monitor);
216 udev_ctrl_unref(udev_ctrl);
219 close(worker_watch[READ_END]);
222 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
224 log_error_errno(errno, "error creating signalfd %m");
229 fd_ep = epoll_create1(EPOLL_CLOEXEC);
231 log_error_errno(errno, "error creating epoll fd: %m");
236 memzero(&ep_signal, sizeof(struct epoll_event));
237 ep_signal.events = EPOLLIN;
238 ep_signal.data.fd = fd_signal;
240 fd_monitor = udev_monitor_get_fd(worker_monitor);
241 memzero(&ep_monitor, sizeof(struct epoll_event));
242 ep_monitor.events = EPOLLIN;
243 ep_monitor.data.fd = fd_monitor;
245 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
246 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_monitor, &ep_monitor) < 0) {
247 log_error_errno(errno, "fail to add fds to epoll: %m");
252 /* request TERM signal if parent exits */
253 prctl(PR_SET_PDEATHSIG, SIGTERM);
255 /* reset OOM score, we only protect the main daemon */
256 write_string_file("/proc/self/oom_score_adj", "0");
259 struct udev_event *udev_event;
260 struct worker_message msg;
264 log_debug("seq %llu running", udev_device_get_seqnum(dev));
265 udev_event = udev_event_new(dev);
266 if (udev_event == NULL) {
271 /* needed for SIGCHLD/SIGTERM in spawn() */
272 udev_event->fd_signal = fd_signal;
274 if (arg_exec_delay > 0)
275 udev_event->exec_delay = arg_exec_delay;
278 * Take a shared lock on the device node; this establishes
279 * a concept of device "ownership" to serialize device
280 * access. External processes holding an exclusive lock will
281 * cause udev to skip the event handling; in the case udev
282 * acquired the lock, the external process can block until
283 * udev has finished its event handling.
285 if (!streq_ptr(udev_device_get_action(dev), "remove") &&
286 streq_ptr("block", udev_device_get_subsystem(dev)) &&
287 !startswith(udev_device_get_sysname(dev), "dm-") &&
288 !startswith(udev_device_get_sysname(dev), "md")) {
289 struct udev_device *d = dev;
291 if (streq_ptr("partition", udev_device_get_devtype(d)))
292 d = udev_device_get_parent(d);
295 fd_lock = open(udev_device_get_devnode(d), O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
296 if (fd_lock >= 0 && flock(fd_lock, LOCK_SH|LOCK_NB) < 0) {
297 log_debug_errno(errno, "Unable to flock(%s), skipping event handling: %m", udev_device_get_devnode(d));
299 fd_lock = safe_close(fd_lock);
305 /* needed for renaming netifs */
306 udev_event->rtnl = rtnl;
308 /* apply rules, create node, symlinks */
309 udev_event_execute_rules(udev_event,
310 arg_event_timeout_usec, arg_event_timeout_warn_usec,
315 udev_event_execute_run(udev_event,
316 arg_event_timeout_usec, arg_event_timeout_warn_usec,
319 if (udev_event->rtnl)
320 /* in case rtnl was initialized */
321 rtnl = sd_rtnl_ref(udev_event->rtnl);
323 /* apply/restore inotify watch */
324 if (udev_event->inotify_watch) {
325 udev_watch_begin(udev, dev);
326 udev_device_update_db(dev);
331 /* send processed event back to libudev listeners */
332 udev_monitor_send_device(worker_monitor, NULL, dev);
335 /* send udevd the result of the event execution */
336 memzero(&msg, sizeof(struct worker_message));
339 send(worker_watch[WRITE_END], &msg, sizeof(struct worker_message), 0);
341 log_debug("seq %llu processed with %i", udev_device_get_seqnum(dev), err);
343 udev_device_unref(dev);
346 if (udev_event->sigterm) {
347 udev_event_unref(udev_event);
351 udev_event_unref(udev_event);
353 /* wait for more device messages from main udevd, or term signal */
354 while (dev == NULL) {
355 struct epoll_event ev[4];
359 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), -1);
363 log_error_errno(errno, "failed to poll: %m");
367 for (i = 0; i < fdcount; i++) {
368 if (ev[i].data.fd == fd_monitor && ev[i].events & EPOLLIN) {
369 dev = udev_monitor_receive_device(worker_monitor);
371 } else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN) {
372 struct signalfd_siginfo fdsi;
375 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
376 if (size != sizeof(struct signalfd_siginfo))
378 switch (fdsi.ssi_signo) {
387 udev_device_unref(dev);
388 safe_close(fd_signal);
391 close(worker_watch[WRITE_END]);
392 udev_rules_unref(rules);
393 udev_builtin_exit(udev);
394 udev_monitor_unref(worker_monitor);
400 udev_monitor_unref(worker_monitor);
401 event->state = EVENT_QUEUED;
403 log_error_errno(errno, "fork of child failed: %m");
406 /* close monitor, but keep address around */
407 udev_monitor_disconnect(worker_monitor);
408 worker->monitor = worker_monitor;
410 worker->state = WORKER_RUNNING;
411 worker->event_start_usec = now(CLOCK_MONOTONIC);
412 worker->event_warned = false;
413 worker->event = event;
414 event->state = EVENT_RUNNING;
415 udev_list_node_append(&worker->node, &worker_list);
417 log_debug("seq %llu forked new worker [%u]", udev_device_get_seqnum(event->dev), pid);
422 static void event_run(struct event *event) {
423 struct udev_list_node *loop;
425 udev_list_node_foreach(loop, &worker_list) {
426 struct worker *worker = node_to_worker(loop);
429 if (worker->state != WORKER_IDLE)
432 count = udev_monitor_send_device(monitor, worker->monitor, event->dev);
434 log_error_errno(errno, "worker [%u] did not accept message %zi (%m), kill it", worker->pid, count);
435 kill(worker->pid, SIGKILL);
436 worker->state = WORKER_KILLED;
440 worker->event = event;
441 worker->state = WORKER_RUNNING;
442 worker->event_start_usec = now(CLOCK_MONOTONIC);
443 worker->event_warned = false;
444 event->state = EVENT_RUNNING;
448 if (children >= arg_children_max) {
449 if (arg_children_max > 1)
450 log_debug("maximum number (%i) of children reached", children);
454 /* start new worker and pass initial device */
458 static int event_queue_insert(struct udev_device *dev) {
461 event = new0(struct event, 1);
465 event->udev = udev_device_get_udev(dev);
467 event->seqnum = udev_device_get_seqnum(dev);
468 event->devpath = udev_device_get_devpath(dev);
469 event->devpath_len = strlen(event->devpath);
470 event->devpath_old = udev_device_get_devpath_old(dev);
471 event->devnum = udev_device_get_devnum(dev);
472 event->is_block = streq("block", udev_device_get_subsystem(dev));
473 event->ifindex = udev_device_get_ifindex(dev);
475 log_debug("seq %llu queued, '%s' '%s'", udev_device_get_seqnum(dev),
476 udev_device_get_action(dev), udev_device_get_subsystem(dev));
478 event->state = EVENT_QUEUED;
479 udev_list_node_append(&event->node, &event_list);
483 static void worker_kill(struct udev *udev) {
484 struct udev_list_node *loop;
486 udev_list_node_foreach(loop, &worker_list) {
487 struct worker *worker = node_to_worker(loop);
489 if (worker->state == WORKER_KILLED)
492 worker->state = WORKER_KILLED;
493 kill(worker->pid, SIGTERM);
497 /* lookup event for identical, parent, child device */
498 static bool is_devpath_busy(struct event *event) {
499 struct udev_list_node *loop;
502 /* check if queue contains events we depend on */
503 udev_list_node_foreach(loop, &event_list) {
504 struct event *loop_event = node_to_event(loop);
506 /* we already found a later event, earlier can not block us, no need to check again */
507 if (loop_event->seqnum < event->delaying_seqnum)
510 /* event we checked earlier still exists, no need to check again */
511 if (loop_event->seqnum == event->delaying_seqnum)
514 /* found ourself, no later event can block us */
515 if (loop_event->seqnum >= event->seqnum)
518 /* check major/minor */
519 if (major(event->devnum) != 0 && event->devnum == loop_event->devnum && event->is_block == loop_event->is_block)
522 /* check network device ifindex */
523 if (event->ifindex != 0 && event->ifindex == loop_event->ifindex)
526 /* check our old name */
527 if (event->devpath_old != NULL && streq(loop_event->devpath, event->devpath_old)) {
528 event->delaying_seqnum = loop_event->seqnum;
532 /* compare devpath */
533 common = MIN(loop_event->devpath_len, event->devpath_len);
535 /* one devpath is contained in the other? */
536 if (memcmp(loop_event->devpath, event->devpath, common) != 0)
539 /* identical device event found */
540 if (loop_event->devpath_len == event->devpath_len) {
541 /* devices names might have changed/swapped in the meantime */
542 if (major(event->devnum) != 0 && (event->devnum != loop_event->devnum || event->is_block != loop_event->is_block))
544 if (event->ifindex != 0 && event->ifindex != loop_event->ifindex)
546 event->delaying_seqnum = loop_event->seqnum;
550 /* parent device event found */
551 if (event->devpath[common] == '/') {
552 event->delaying_seqnum = loop_event->seqnum;
556 /* child device event found */
557 if (loop_event->devpath[common] == '/') {
558 event->delaying_seqnum = loop_event->seqnum;
562 /* no matching device */
569 static void event_queue_start(struct udev *udev) {
570 struct udev_list_node *loop;
572 udev_list_node_foreach(loop, &event_list) {
573 struct event *event = node_to_event(loop);
575 if (event->state != EVENT_QUEUED)
578 /* do not start event if parent or child event is still running */
579 if (is_devpath_busy(event))
586 static void event_queue_cleanup(struct udev *udev, enum event_state match_type) {
587 struct udev_list_node *loop, *tmp;
589 udev_list_node_foreach_safe(loop, tmp, &event_list) {
590 struct event *event = node_to_event(loop);
592 if (match_type != EVENT_UNDEF && match_type != event->state)
595 event_queue_delete(event);
599 static void worker_returned(int fd_worker) {
601 struct worker_message msg;
603 struct udev_list_node *loop;
605 size = recv(fd_worker, &msg, sizeof(struct worker_message), MSG_DONTWAIT);
606 if (size != sizeof(struct worker_message))
609 /* lookup worker who sent the signal */
610 udev_list_node_foreach(loop, &worker_list) {
611 struct worker *worker = node_to_worker(loop);
613 if (worker->pid != msg.pid)
616 /* worker returned */
618 worker->event->exitcode = msg.exitcode;
619 event_queue_delete(worker->event);
620 worker->event = NULL;
622 if (worker->state != WORKER_KILLED)
623 worker->state = WORKER_IDLE;
624 worker_unref(worker);
630 /* receive the udevd message from userspace */
631 static struct udev_ctrl_connection *handle_ctrl_msg(struct udev_ctrl *uctrl) {
632 struct udev *udev = udev_ctrl_get_udev(uctrl);
633 struct udev_ctrl_connection *ctrl_conn;
634 struct udev_ctrl_msg *ctrl_msg = NULL;
638 ctrl_conn = udev_ctrl_get_connection(uctrl);
639 if (ctrl_conn == NULL)
642 ctrl_msg = udev_ctrl_receive_msg(ctrl_conn);
643 if (ctrl_msg == NULL)
646 i = udev_ctrl_get_set_log_level(ctrl_msg);
648 log_debug("udevd message (SET_LOG_LEVEL) received, log_priority=%i", i);
649 log_set_max_level(i);
653 if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
654 log_debug("udevd message (STOP_EXEC_QUEUE) received");
655 stop_exec_queue = true;
658 if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
659 log_debug("udevd message (START_EXEC_QUEUE) received");
660 stop_exec_queue = false;
663 if (udev_ctrl_get_reload(ctrl_msg) > 0) {
664 log_debug("udevd message (RELOAD) received");
668 str = udev_ctrl_get_set_env(ctrl_msg);
676 val = strchr(key, '=');
680 if (val[0] == '\0') {
681 log_debug("udevd message (ENV) received, unset '%s'", key);
682 udev_list_entry_add(&properties_list, key, NULL);
684 log_debug("udevd message (ENV) received, set '%s=%s'", key, val);
685 udev_list_entry_add(&properties_list, key, val);
688 log_error("wrong key format '%s'", key);
695 i = udev_ctrl_get_set_children_max(ctrl_msg);
697 log_debug("udevd message (SET_MAX_CHILDREN) received, children_max=%i", i);
698 arg_children_max = i;
701 if (udev_ctrl_get_ping(ctrl_msg) > 0)
702 log_debug("udevd message (SYNC) received");
704 if (udev_ctrl_get_exit(ctrl_msg) > 0) {
705 log_debug("udevd message (EXIT) received");
707 /* keep reference to block the client until we exit */
708 udev_ctrl_connection_ref(ctrl_conn);
711 udev_ctrl_msg_unref(ctrl_msg);
712 return udev_ctrl_connection_unref(ctrl_conn);
715 static int synthesize_change(struct udev_device *dev) {
716 char filename[UTIL_PATH_SIZE];
719 if (streq_ptr("block", udev_device_get_subsystem(dev)) &&
720 streq_ptr("disk", udev_device_get_devtype(dev)) &&
721 !startswith(udev_device_get_sysname(dev), "dm-")) {
722 bool part_table_read = false;
723 bool has_partitions = false;
725 struct udev *udev = udev_device_get_udev(dev);
726 _cleanup_udev_enumerate_unref_ struct udev_enumerate *e = NULL;
727 struct udev_list_entry *item;
730 * Try to re-read the partition table. This only succeeds if
731 * none of the devices is busy. The kernel returns 0 if no
732 * partition table is found, and we will not get an event for
735 fd = open(udev_device_get_devnode(dev), O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
737 r = flock(fd, LOCK_EX|LOCK_NB);
739 r = ioctl(fd, BLKRRPART, 0);
743 part_table_read = true;
746 /* search for partitions */
747 e = udev_enumerate_new(udev);
751 r = udev_enumerate_add_match_parent(e, dev);
755 r = udev_enumerate_add_match_subsystem(e, "block");
759 r = udev_enumerate_scan_devices(e);
763 udev_list_entry_foreach(item, udev_enumerate_get_list_entry(e)) {
764 _cleanup_udev_device_unref_ struct udev_device *d = NULL;
766 d = udev_device_new_from_syspath(udev, udev_list_entry_get_name(item));
770 if (!streq_ptr("partition", udev_device_get_devtype(d)))
773 has_partitions = true;
778 * We have partitions and re-read the table, the kernel already sent
779 * out a "change" event for the disk, and "remove/add" for all
782 if (part_table_read && has_partitions)
786 * We have partitions but re-reading the partition table did not
787 * work, synthesize "change" for the disk and all partitions.
789 log_debug("device %s closed, synthesising 'change'", udev_device_get_devnode(dev));
790 strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
791 write_string_file(filename, "change");
793 udev_list_entry_foreach(item, udev_enumerate_get_list_entry(e)) {
794 _cleanup_udev_device_unref_ struct udev_device *d = NULL;
796 d = udev_device_new_from_syspath(udev, udev_list_entry_get_name(item));
800 if (!streq_ptr("partition", udev_device_get_devtype(d)))
803 log_debug("device %s closed, synthesising partition '%s' 'change'",
804 udev_device_get_devnode(dev), udev_device_get_devnode(d));
805 strscpyl(filename, sizeof(filename), udev_device_get_syspath(d), "/uevent", NULL);
806 write_string_file(filename, "change");
812 log_debug("device %s closed, synthesising 'change'", udev_device_get_devnode(dev));
813 strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
814 write_string_file(filename, "change");
819 static int handle_inotify(struct udev *udev) {
820 union inotify_event_buffer buffer;
821 struct inotify_event *e;
824 l = read(fd_inotify, &buffer, sizeof(buffer));
826 if (errno == EAGAIN || errno == EINTR)
829 return log_error_errno(errno, "Failed to read inotify fd: %m");
832 FOREACH_INOTIFY_EVENT(e, buffer, l) {
833 struct udev_device *dev;
835 dev = udev_watch_lookup(udev, e->wd);
839 log_debug("inotify event: %x for %s", e->mask, udev_device_get_devnode(dev));
840 if (e->mask & IN_CLOSE_WRITE)
841 synthesize_change(dev);
842 else if (e->mask & IN_IGNORED)
843 udev_watch_end(udev, dev);
845 udev_device_unref(dev);
851 static void handle_signal(struct udev *udev, int signo) {
861 struct udev_list_node *loop, *tmp;
863 pid = waitpid(-1, &status, WNOHANG);
867 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
868 struct worker *worker = node_to_worker(loop);
870 if (worker->pid != pid)
872 log_debug("worker [%u] exit", pid);
874 if (WIFEXITED(status)) {
875 if (WEXITSTATUS(status) != 0)
876 log_error("worker [%u] exit with return code %i",
877 pid, WEXITSTATUS(status));
878 } else if (WIFSIGNALED(status)) {
879 log_error("worker [%u] terminated by signal %i (%s)",
880 pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
881 } else if (WIFSTOPPED(status)) {
882 log_error("worker [%u] stopped", pid);
883 } else if (WIFCONTINUED(status)) {
884 log_error("worker [%u] continued", pid);
886 log_error("worker [%u] exit with status 0x%04x", pid, status);
889 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
891 log_error("worker [%u] failed while handling '%s'",
892 pid, worker->event->devpath);
893 worker->event->exitcode = -32;
894 event_queue_delete(worker->event);
896 /* drop reference taken for state 'running' */
897 worker_unref(worker);
900 worker_unref(worker);
911 static int systemd_fds(struct udev *udev, int *rctrl, int *rnetlink) {
912 int ctrl = -1, netlink = -1;
915 n = sd_listen_fds(true);
919 for (fd = SD_LISTEN_FDS_START; fd < n + SD_LISTEN_FDS_START; fd++) {
920 if (sd_is_socket(fd, AF_LOCAL, SOCK_SEQPACKET, -1)) {
927 if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1)) {
937 if (ctrl < 0 || netlink < 0)
940 log_debug("ctrl=%i netlink=%i", ctrl, netlink);
947 * read the kernel command line, in case we need to get into debug mode
948 * udev.log-priority=<level> syslog priority
949 * udev.children-max=<number of workers> events are fully serialized if set to 1
950 * udev.exec-delay=<number of seconds> delay execution of every executed program
952 static void kernel_cmdline_options(struct udev *udev) {
953 _cleanup_free_ char *line = NULL;
954 const char *word, *state;
958 r = proc_cmdline(&line);
960 log_warning_errno(r, "Failed to read /proc/cmdline, ignoring: %m");
964 FOREACH_WORD_QUOTED(word, l, line, state) {
965 char *s, *opt, *value;
967 s = strndup(word, l);
971 /* accept the same options for the initrd, prefixed with "rd." */
972 if (in_initrd() && startswith(s, "rd."))
977 if ((value = startswith(opt, "udev.log-priority="))) {
980 prio = util_log_priority(value);
981 log_set_max_level(prio);
982 } else if ((value = startswith(opt, "udev.children-max="))) {
983 r = safe_atoi(value, &arg_children_max);
985 log_warning("Invalid udev.children-max ignored: %s", value);
986 } else if ((value = startswith(opt, "udev.exec-delay="))) {
987 r = safe_atoi(value, &arg_exec_delay);
989 log_warning("Invalid udev.exec-delay ignored: %s", value);
990 } else if ((value = startswith(opt, "udev.event-timeout="))) {
991 r = safe_atou64(value, &arg_event_timeout_usec);
993 log_warning("Invalid udev.event-timeout ignored: %s", value);
996 arg_event_timeout_usec *= USEC_PER_SEC;
997 arg_event_timeout_warn_usec = (arg_event_timeout_usec / 3) ? : 1;
1004 static void help(void) {
1005 printf("%s [OPTIONS...]\n\n"
1006 "Manages devices.\n\n"
1007 " -h --help Print this message\n"
1008 " --version Print version of the program\n"
1009 " --daemon Detach and run in the background\n"
1010 " --debug Enable debug output\n"
1011 " --children-max=INT Set maximum number of workers\n"
1012 " --exec-delay=SECONDS Seconds to wait before executing RUN=\n"
1013 " --event-timeout=SECONDS Seconds to wait before terminating an event\n"
1014 " --resolve-names=early|late|never\n"
1015 " When to resolve users and groups\n"
1016 , program_invocation_short_name);
1019 static int parse_argv(int argc, char *argv[]) {
1020 static const struct option options[] = {
1021 { "daemon", no_argument, NULL, 'd' },
1022 { "debug", no_argument, NULL, 'D' },
1023 { "children-max", required_argument, NULL, 'c' },
1024 { "exec-delay", required_argument, NULL, 'e' },
1025 { "event-timeout", required_argument, NULL, 't' },
1026 { "resolve-names", required_argument, NULL, 'N' },
1027 { "help", no_argument, NULL, 'h' },
1028 { "version", no_argument, NULL, 'V' },
1037 while ((c = getopt_long(argc, argv, "c:de:DtN:hV", options, NULL)) >= 0) {
1043 arg_daemonize = true;
1046 r = safe_atoi(optarg, &arg_children_max);
1048 log_warning("Invalid --children-max ignored: %s", optarg);
1051 r = safe_atoi(optarg, &arg_exec_delay);
1053 log_warning("Invalid --exec-delay ignored: %s", optarg);
1056 r = safe_atou64(optarg, &arg_event_timeout_usec);
1058 log_warning("Invalid --event-timeout ignored: %s", optarg);
1060 arg_event_timeout_usec *= USEC_PER_SEC;
1061 arg_event_timeout_warn_usec = (arg_event_timeout_usec / 3) ? : 1;
1068 if (streq(optarg, "early")) {
1069 arg_resolve_names = 1;
1070 } else if (streq(optarg, "late")) {
1071 arg_resolve_names = 0;
1072 } else if (streq(optarg, "never")) {
1073 arg_resolve_names = -1;
1075 log_error("resolve-names must be early, late or never");
1083 printf("%s\n", VERSION);
1088 assert_not_reached("Unhandled option");
1096 int main(int argc, char *argv[]) {
1100 int fd_netlink = -1;
1102 struct epoll_event ep_ctrl = { .events = EPOLLIN };
1103 struct epoll_event ep_inotify = { .events = EPOLLIN };
1104 struct epoll_event ep_signal = { .events = EPOLLIN };
1105 struct epoll_event ep_netlink = { .events = EPOLLIN };
1106 struct epoll_event ep_worker = { .events = EPOLLIN };
1107 struct udev_ctrl_connection *ctrl_conn = NULL;
1114 log_set_target(LOG_TARGET_AUTO);
1115 log_parse_environment();
1118 r = parse_argv(argc, argv);
1122 kernel_cmdline_options(udev);
1125 log_set_max_level(LOG_DEBUG);
1127 if (getuid() != 0) {
1128 log_error("root privileges required");
1132 r = mac_selinux_init("/dev");
1134 log_error_errno(r, "could not initialize labelling: %m");
1138 /* set umask before creating any file/directory */
1141 log_error_errno(errno, "could not change dir to /: %m");
1147 udev_list_init(udev, &properties_list, true);
1149 r = mkdir("/run/udev", 0755);
1150 if (r < 0 && errno != EEXIST) {
1151 log_error_errno(errno, "could not create /run/udev: %m");
1157 /* before opening new files, make sure std{in,out,err} fds are in a sane state */
1158 if (arg_daemonize) {
1161 fd = open("/dev/null", O_RDWR);
1163 if (write(STDOUT_FILENO, 0, 0) < 0)
1164 dup2(fd, STDOUT_FILENO);
1165 if (write(STDERR_FILENO, 0, 0) < 0)
1166 dup2(fd, STDERR_FILENO);
1167 if (fd > STDERR_FILENO)
1170 log_error("cannot open /dev/null");
1174 if (systemd_fds(udev, &fd_ctrl, &fd_netlink) >= 0) {
1175 /* get control and netlink socket from systemd */
1176 udev_ctrl = udev_ctrl_new_from_fd(udev, fd_ctrl);
1177 if (udev_ctrl == NULL) {
1178 log_error("error taking over udev control socket");
1183 monitor = udev_monitor_new_from_netlink_fd(udev, "kernel", fd_netlink);
1184 if (monitor == NULL) {
1185 log_error("error taking over netlink socket");
1190 /* get our own cgroup, we regularly kill everything udev has left behind */
1191 if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &udev_cgroup) < 0)
1194 /* open control and netlink socket */
1195 udev_ctrl = udev_ctrl_new(udev);
1196 if (udev_ctrl == NULL) {
1197 log_error("error initializing udev control socket");
1201 fd_ctrl = udev_ctrl_get_fd(udev_ctrl);
1203 monitor = udev_monitor_new_from_netlink(udev, "kernel");
1204 if (monitor == NULL) {
1205 log_error("error initializing netlink socket");
1209 fd_netlink = udev_monitor_get_fd(monitor);
1211 udev_monitor_set_receive_buffer_size(monitor, 128 * 1024 * 1024);
1214 if (udev_monitor_enable_receiving(monitor) < 0) {
1215 log_error("error binding netlink socket");
1220 if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
1221 log_error("error binding udev control socket");
1226 log_info("starting version " VERSION);
1228 udev_builtin_init(udev);
1230 rules = udev_rules_new(udev, arg_resolve_names);
1231 if (rules == NULL) {
1232 log_error("error reading rules");
1236 rc = udev_rules_apply_static_dev_perms(rules);
1238 log_error_errno(rc, "failed to apply permissions on static device nodes - %m");
1240 if (arg_daemonize) {
1248 log_error_errno(errno, "fork of daemon failed: %m");
1253 goto exit_daemonize;
1258 write_string_file("/proc/self/oom_score_adj", "-1000");
1260 sd_notify(1, "READY=1");
1263 if (arg_children_max <= 0) {
1266 arg_children_max = 8;
1268 if (sched_getaffinity(0, sizeof (cpu_set), &cpu_set) == 0) {
1269 arg_children_max += CPU_COUNT(&cpu_set) * 2;
1272 log_debug("set children_max to %u", arg_children_max);
1274 udev_list_node_init(&event_list);
1275 udev_list_node_init(&worker_list);
1277 fd_inotify = udev_watch_init(udev);
1278 if (fd_inotify < 0) {
1279 log_error("error initializing inotify");
1283 udev_watch_restore(udev);
1285 /* block and listen to all signals on signalfd */
1287 sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
1288 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
1289 if (fd_signal < 0) {
1290 log_error("error creating signalfd");
1295 /* unnamed socket from workers to the main daemon */
1296 if (socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, worker_watch) < 0) {
1297 log_error("error creating socketpair");
1301 fd_worker = worker_watch[READ_END];
1303 ep_ctrl.data.fd = fd_ctrl;
1304 ep_inotify.data.fd = fd_inotify;
1305 ep_signal.data.fd = fd_signal;
1306 ep_netlink.data.fd = fd_netlink;
1307 ep_worker.data.fd = fd_worker;
1309 fd_ep = epoll_create1(EPOLL_CLOEXEC);
1311 log_error_errno(errno, "error creating epoll fd: %m");
1314 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_ctrl, &ep_ctrl) < 0 ||
1315 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_inotify, &ep_inotify) < 0 ||
1316 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
1317 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_netlink, &ep_netlink) < 0 ||
1318 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_worker, &ep_worker) < 0) {
1319 log_error_errno(errno, "fail to add fds to epoll: %m");
1324 static usec_t last_usec;
1325 struct epoll_event ev[8];
1328 bool is_worker, is_signal, is_inotify, is_netlink, is_ctrl;
1332 /* close sources of new events and discard buffered events */
1334 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_ctrl, NULL);
1337 if (monitor != NULL) {
1338 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_netlink, NULL);
1339 udev_monitor_unref(monitor);
1342 if (fd_inotify >= 0) {
1343 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_inotify, NULL);
1348 /* discard queued events and kill workers */
1349 event_queue_cleanup(udev, EVENT_QUEUED);
1352 /* exit after all has cleaned up */
1353 if (udev_list_node_is_empty(&event_list) && children == 0)
1356 /* timeout at exit for workers to finish */
1357 timeout = 30 * MSEC_PER_SEC;
1358 } else if (udev_list_node_is_empty(&event_list) && children == 0) {
1362 /* cleanup possible left-over processes in our cgroup */
1364 cg_kill(SYSTEMD_CGROUP_CONTROLLER, udev_cgroup, SIGKILL, false, true, NULL);
1366 /* kill idle or hanging workers */
1367 timeout = 3 * MSEC_PER_SEC;
1370 /* tell settle that we are busy or idle */
1371 if (!udev_list_node_is_empty(&event_list)) {
1374 fd = open("/run/udev/queue", O_WRONLY|O_CREAT|O_CLOEXEC|O_TRUNC|O_NOFOLLOW, 0444);
1378 unlink("/run/udev/queue");
1381 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
1386 struct udev_list_node *loop;
1390 log_error("timeout, giving up waiting for workers to finish");
1394 /* kill idle workers */
1395 if (udev_list_node_is_empty(&event_list)) {
1396 log_debug("cleanup idle workers");
1400 /* check for hanging events */
1401 udev_list_node_foreach(loop, &worker_list) {
1402 struct worker *worker = node_to_worker(loop);
1405 if (worker->state != WORKER_RUNNING)
1408 ts = now(CLOCK_MONOTONIC);
1410 if ((ts - worker->event_start_usec) > arg_event_timeout_warn_usec) {
1411 if ((ts - worker->event_start_usec) > arg_event_timeout_usec) {
1412 log_error("worker [%u] %s timeout; kill it", worker->pid, worker->event->devpath);
1413 kill(worker->pid, SIGKILL);
1414 worker->state = WORKER_KILLED;
1416 /* drop reference taken for state 'running' */
1417 worker_unref(worker);
1418 log_error("seq %llu '%s' killed", udev_device_get_seqnum(worker->event->dev), worker->event->devpath);
1419 worker->event->exitcode = -64;
1420 event_queue_delete(worker->event);
1421 worker->event = NULL;
1422 } else if (!worker->event_warned) {
1423 log_warning("worker [%u] %s is taking a long time", worker->pid, worker->event->devpath);
1424 worker->event_warned = true;
1431 is_worker = is_signal = is_inotify = is_netlink = is_ctrl = false;
1432 for (i = 0; i < fdcount; i++) {
1433 if (ev[i].data.fd == fd_worker && ev[i].events & EPOLLIN)
1435 else if (ev[i].data.fd == fd_netlink && ev[i].events & EPOLLIN)
1437 else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN)
1439 else if (ev[i].data.fd == fd_inotify && ev[i].events & EPOLLIN)
1441 else if (ev[i].data.fd == fd_ctrl && ev[i].events & EPOLLIN)
1445 /* check for changed config, every 3 seconds at most */
1446 if ((now(CLOCK_MONOTONIC) - last_usec) > 3 * USEC_PER_SEC) {
1447 if (udev_rules_check_timestamp(rules))
1449 if (udev_builtin_validate(udev))
1452 last_usec = now(CLOCK_MONOTONIC);
1455 /* reload requested, HUP signal received, rules changed, builtin changed */
1458 rules = udev_rules_unref(rules);
1459 udev_builtin_exit(udev);
1463 /* event has finished */
1465 worker_returned(fd_worker);
1468 struct udev_device *dev;
1470 dev = udev_monitor_receive_device(monitor);
1472 udev_device_set_usec_initialized(dev, now(CLOCK_MONOTONIC));
1473 if (event_queue_insert(dev) < 0)
1474 udev_device_unref(dev);
1478 /* start new events */
1479 if (!udev_list_node_is_empty(&event_list) && !udev_exit && !stop_exec_queue) {
1480 udev_builtin_init(udev);
1482 rules = udev_rules_new(udev, arg_resolve_names);
1484 event_queue_start(udev);
1488 struct signalfd_siginfo fdsi;
1491 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
1492 if (size == sizeof(struct signalfd_siginfo))
1493 handle_signal(udev, fdsi.ssi_signo);
1496 /* we are shutting down, the events below are not handled anymore */
1500 /* device node watch */
1502 handle_inotify(udev);
1505 * This needs to be after the inotify handling, to make sure,
1506 * that the ping is send back after the possibly generated
1507 * "change" events by the inotify device node watch.
1509 * A single time we may receive a client connection which we need to
1510 * keep open to block the client. It will be closed right before we
1514 ctrl_conn = handle_ctrl_msg(udev_ctrl);
1519 udev_ctrl_cleanup(udev_ctrl);
1520 unlink("/run/udev/queue");
1524 worker_list_cleanup(udev);
1525 event_queue_cleanup(udev, EVENT_UNDEF);
1526 udev_rules_unref(rules);
1527 udev_builtin_exit(udev);
1530 if (worker_watch[READ_END] >= 0)
1531 close(worker_watch[READ_END]);
1532 if (worker_watch[WRITE_END] >= 0)
1533 close(worker_watch[WRITE_END]);
1534 udev_monitor_unref(monitor);
1535 udev_ctrl_connection_unref(ctrl_conn);
1536 udev_ctrl_unref(udev_ctrl);
1537 udev_list_cleanup(&properties_list);
1538 mac_selinux_finish();