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>
50 #include "udev-util.h"
51 #include "rtnl-util.h"
52 #include "sd-daemon.h"
53 #include "cgroup-util.h"
54 #include "dev-setup.h"
57 static struct udev_rules *rules;
58 static struct udev_ctrl *udev_ctrl;
59 static struct udev_monitor *monitor;
60 static int worker_watch[2] = { -1, -1 };
61 static int fd_signal = -1;
62 static int fd_ep = -1;
63 static int fd_inotify = -1;
64 static bool stop_exec_queue;
67 static bool arg_debug = false;
68 static int arg_daemonize = false;
69 static int arg_resolve_names = 1;
70 static int arg_children_max;
71 static int arg_exec_delay;
72 static usec_t arg_event_timeout_usec = 180 * USEC_PER_SEC;
73 static usec_t arg_event_timeout_warn_usec = 180 * USEC_PER_SEC / 3;
74 static sigset_t sigmask_orig;
75 static UDEV_LIST(event_list);
76 static UDEV_LIST(worker_list);
77 static char *udev_cgroup;
78 static bool udev_exit;
79 static struct udev_list properties_list;
88 struct udev_list_node node;
90 struct udev_device *dev;
91 enum event_state state;
93 unsigned long long int delaying_seqnum;
94 unsigned long long int seqnum;
97 const char *devpath_old;
103 static inline struct event *node_to_event(struct udev_list_node *node) {
104 return container_of(node, struct event, node);
107 static void event_queue_cleanup(struct udev *udev, enum event_state type);
117 struct udev_list_node node;
121 struct udev_monitor *monitor;
122 enum worker_state state;
124 usec_t event_start_usec;
128 /* passed from worker to main process */
129 struct worker_message {
134 static inline struct worker *node_to_worker(struct udev_list_node *node) {
135 return container_of(node, struct worker, node);
138 static void event_queue_delete(struct event *event) {
139 udev_list_node_remove(&event->node);
140 udev_device_unref(event->dev);
144 static struct worker *worker_ref(struct worker *worker) {
149 static void worker_cleanup(struct worker *worker) {
150 udev_list_node_remove(&worker->node);
151 udev_monitor_unref(worker->monitor);
156 static void worker_unref(struct worker *worker) {
158 if (worker->refcount > 0)
160 log_debug("worker [%u] cleaned up", worker->pid);
161 worker_cleanup(worker);
164 static void worker_list_cleanup(struct udev *udev) {
165 struct udev_list_node *loop, *tmp;
167 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
168 struct worker *worker = node_to_worker(loop);
170 worker_cleanup(worker);
174 static void worker_new(struct event *event) {
175 struct udev *udev = event->udev;
176 struct worker *worker;
177 struct udev_monitor *worker_monitor;
180 /* listen for new events */
181 worker_monitor = udev_monitor_new_from_netlink(udev, NULL);
182 if (worker_monitor == NULL)
184 /* allow the main daemon netlink address to send devices to the worker */
185 udev_monitor_allow_unicast_sender(worker_monitor, monitor);
186 udev_monitor_enable_receiving(worker_monitor);
188 worker = new0(struct worker, 1);
189 if (worker == NULL) {
190 udev_monitor_unref(worker_monitor);
193 /* worker + event reference */
194 worker->refcount = 2;
200 struct udev_device *dev = NULL;
202 _cleanup_rtnl_unref_ sd_rtnl *rtnl = NULL;
203 struct epoll_event ep_signal, ep_monitor;
205 int rc = EXIT_SUCCESS;
207 /* take initial device from queue */
212 worker_list_cleanup(udev);
213 event_queue_cleanup(udev, EVENT_UNDEF);
214 udev_monitor_unref(monitor);
215 udev_ctrl_unref(udev_ctrl);
218 close(worker_watch[READ_END]);
221 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
223 log_error("error creating signalfd %m");
228 fd_ep = epoll_create1(EPOLL_CLOEXEC);
230 log_error("error creating epoll fd: %m");
235 memzero(&ep_signal, sizeof(struct epoll_event));
236 ep_signal.events = EPOLLIN;
237 ep_signal.data.fd = fd_signal;
239 fd_monitor = udev_monitor_get_fd(worker_monitor);
240 memzero(&ep_monitor, sizeof(struct epoll_event));
241 ep_monitor.events = EPOLLIN;
242 ep_monitor.data.fd = fd_monitor;
244 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
245 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_monitor, &ep_monitor) < 0) {
246 log_error("fail to add fds to epoll: %m");
251 /* request TERM signal if parent exits */
252 prctl(PR_SET_PDEATHSIG, SIGTERM);
254 /* reset OOM score, we only protect the main daemon */
255 write_string_file("/proc/self/oom_score_adj", "0");
258 struct udev_event *udev_event;
259 struct worker_message msg;
263 log_debug("seq %llu running", udev_device_get_seqnum(dev));
264 udev_event = udev_event_new(dev);
265 if (udev_event == NULL) {
270 /* needed for SIGCHLD/SIGTERM in spawn() */
271 udev_event->fd_signal = fd_signal;
273 if (arg_exec_delay > 0)
274 udev_event->exec_delay = arg_exec_delay;
277 * Take a shared lock on the device node; this establishes
278 * a concept of device "ownership" to serialize device
279 * access. External processes holding an exclusive lock will
280 * cause udev to skip the event handling; in the case udev
281 * acquired the lock, the external process can block until
282 * udev has finished its event handling.
284 if (!streq_ptr(udev_device_get_action(dev), "remove") &&
285 streq_ptr("block", udev_device_get_subsystem(dev)) &&
286 !startswith(udev_device_get_sysname(dev), "dm-") &&
287 !startswith(udev_device_get_sysname(dev), "md")) {
288 struct udev_device *d = dev;
290 if (streq_ptr("partition", udev_device_get_devtype(d)))
291 d = udev_device_get_parent(d);
294 fd_lock = open(udev_device_get_devnode(d), O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
295 if (fd_lock >= 0 && flock(fd_lock, LOCK_SH|LOCK_NB) < 0) {
296 log_debug("Unable to flock(%s), skipping event handling: %m", udev_device_get_devnode(d));
298 fd_lock = safe_close(fd_lock);
304 /* needed for renaming netifs */
305 udev_event->rtnl = rtnl;
307 /* apply rules, create node, symlinks */
308 udev_event_execute_rules(udev_event, arg_event_timeout_usec, arg_event_timeout_warn_usec, rules, &sigmask_orig);
310 udev_event_execute_run(udev_event, arg_event_timeout_usec, arg_event_timeout_warn_usec, &sigmask_orig);
312 /* in case rtnl was initialized */
313 rtnl = sd_rtnl_ref(udev_event->rtnl);
315 /* apply/restore inotify watch */
316 if (udev_event->inotify_watch) {
317 udev_watch_begin(udev, dev);
318 udev_device_update_db(dev);
323 /* send processed event back to libudev listeners */
324 udev_monitor_send_device(worker_monitor, NULL, dev);
327 /* send udevd the result of the event execution */
328 memzero(&msg, sizeof(struct worker_message));
331 send(worker_watch[WRITE_END], &msg, sizeof(struct worker_message), 0);
333 log_debug("seq %llu processed with %i", udev_device_get_seqnum(dev), err);
335 udev_device_unref(dev);
338 if (udev_event->sigterm) {
339 udev_event_unref(udev_event);
343 udev_event_unref(udev_event);
345 /* wait for more device messages from main udevd, or term signal */
346 while (dev == NULL) {
347 struct epoll_event ev[4];
351 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), -1);
355 log_error("failed to poll: %m");
359 for (i = 0; i < fdcount; i++) {
360 if (ev[i].data.fd == fd_monitor && ev[i].events & EPOLLIN) {
361 dev = udev_monitor_receive_device(worker_monitor);
363 } else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN) {
364 struct signalfd_siginfo fdsi;
367 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
368 if (size != sizeof(struct signalfd_siginfo))
370 switch (fdsi.ssi_signo) {
379 udev_device_unref(dev);
380 safe_close(fd_signal);
383 close(worker_watch[WRITE_END]);
384 udev_rules_unref(rules);
385 udev_builtin_exit(udev);
386 udev_monitor_unref(worker_monitor);
392 udev_monitor_unref(worker_monitor);
393 event->state = EVENT_QUEUED;
395 log_error("fork of child failed: %m");
398 /* close monitor, but keep address around */
399 udev_monitor_disconnect(worker_monitor);
400 worker->monitor = worker_monitor;
402 worker->state = WORKER_RUNNING;
403 worker->event_start_usec = now(CLOCK_MONOTONIC);
404 worker->event_warned = false;
405 worker->event = event;
406 event->state = EVENT_RUNNING;
407 udev_list_node_append(&worker->node, &worker_list);
409 log_debug("seq %llu forked new worker [%u]", udev_device_get_seqnum(event->dev), pid);
414 static void event_run(struct event *event) {
415 struct udev_list_node *loop;
417 udev_list_node_foreach(loop, &worker_list) {
418 struct worker *worker = node_to_worker(loop);
421 if (worker->state != WORKER_IDLE)
424 count = udev_monitor_send_device(monitor, worker->monitor, event->dev);
426 log_error("worker [%u] did not accept message %zi (%m), kill it", worker->pid, count);
427 kill(worker->pid, SIGKILL);
428 worker->state = WORKER_KILLED;
432 worker->event = event;
433 worker->state = WORKER_RUNNING;
434 worker->event_start_usec = now(CLOCK_MONOTONIC);
435 worker->event_warned = false;
436 event->state = EVENT_RUNNING;
440 if (children >= arg_children_max) {
441 if (arg_children_max > 1)
442 log_debug("maximum number (%i) of children reached", children);
446 /* start new worker and pass initial device */
450 static int event_queue_insert(struct udev_device *dev) {
453 event = new0(struct event, 1);
457 event->udev = udev_device_get_udev(dev);
459 event->seqnum = udev_device_get_seqnum(dev);
460 event->devpath = udev_device_get_devpath(dev);
461 event->devpath_len = strlen(event->devpath);
462 event->devpath_old = udev_device_get_devpath_old(dev);
463 event->devnum = udev_device_get_devnum(dev);
464 event->is_block = streq("block", udev_device_get_subsystem(dev));
465 event->ifindex = udev_device_get_ifindex(dev);
467 log_debug("seq %llu queued, '%s' '%s'", udev_device_get_seqnum(dev),
468 udev_device_get_action(dev), udev_device_get_subsystem(dev));
470 event->state = EVENT_QUEUED;
471 udev_list_node_append(&event->node, &event_list);
475 static void worker_kill(struct udev *udev) {
476 struct udev_list_node *loop;
478 udev_list_node_foreach(loop, &worker_list) {
479 struct worker *worker = node_to_worker(loop);
481 if (worker->state == WORKER_KILLED)
484 worker->state = WORKER_KILLED;
485 kill(worker->pid, SIGTERM);
489 /* lookup event for identical, parent, child device */
490 static bool is_devpath_busy(struct event *event) {
491 struct udev_list_node *loop;
494 /* check if queue contains events we depend on */
495 udev_list_node_foreach(loop, &event_list) {
496 struct event *loop_event = node_to_event(loop);
498 /* we already found a later event, earlier can not block us, no need to check again */
499 if (loop_event->seqnum < event->delaying_seqnum)
502 /* event we checked earlier still exists, no need to check again */
503 if (loop_event->seqnum == event->delaying_seqnum)
506 /* found ourself, no later event can block us */
507 if (loop_event->seqnum >= event->seqnum)
510 /* check major/minor */
511 if (major(event->devnum) != 0 && event->devnum == loop_event->devnum && event->is_block == loop_event->is_block)
514 /* check network device ifindex */
515 if (event->ifindex != 0 && event->ifindex == loop_event->ifindex)
518 /* check our old name */
519 if (event->devpath_old != NULL && streq(loop_event->devpath, event->devpath_old)) {
520 event->delaying_seqnum = loop_event->seqnum;
524 /* compare devpath */
525 common = MIN(loop_event->devpath_len, event->devpath_len);
527 /* one devpath is contained in the other? */
528 if (memcmp(loop_event->devpath, event->devpath, common) != 0)
531 /* identical device event found */
532 if (loop_event->devpath_len == event->devpath_len) {
533 /* devices names might have changed/swapped in the meantime */
534 if (major(event->devnum) != 0 && (event->devnum != loop_event->devnum || event->is_block != loop_event->is_block))
536 if (event->ifindex != 0 && event->ifindex != loop_event->ifindex)
538 event->delaying_seqnum = loop_event->seqnum;
542 /* parent device event found */
543 if (event->devpath[common] == '/') {
544 event->delaying_seqnum = loop_event->seqnum;
548 /* child device event found */
549 if (loop_event->devpath[common] == '/') {
550 event->delaying_seqnum = loop_event->seqnum;
554 /* no matching device */
561 static void event_queue_start(struct udev *udev) {
562 struct udev_list_node *loop;
564 udev_list_node_foreach(loop, &event_list) {
565 struct event *event = node_to_event(loop);
567 if (event->state != EVENT_QUEUED)
570 /* do not start event if parent or child event is still running */
571 if (is_devpath_busy(event))
578 static void event_queue_cleanup(struct udev *udev, enum event_state match_type) {
579 struct udev_list_node *loop, *tmp;
581 udev_list_node_foreach_safe(loop, tmp, &event_list) {
582 struct event *event = node_to_event(loop);
584 if (match_type != EVENT_UNDEF && match_type != event->state)
587 event_queue_delete(event);
591 static void worker_returned(int fd_worker) {
593 struct worker_message msg;
595 struct udev_list_node *loop;
597 size = recv(fd_worker, &msg, sizeof(struct worker_message), MSG_DONTWAIT);
598 if (size != sizeof(struct worker_message))
601 /* lookup worker who sent the signal */
602 udev_list_node_foreach(loop, &worker_list) {
603 struct worker *worker = node_to_worker(loop);
605 if (worker->pid != msg.pid)
608 /* worker returned */
610 worker->event->exitcode = msg.exitcode;
611 event_queue_delete(worker->event);
612 worker->event = NULL;
614 if (worker->state != WORKER_KILLED)
615 worker->state = WORKER_IDLE;
616 worker_unref(worker);
622 /* receive the udevd message from userspace */
623 static struct udev_ctrl_connection *handle_ctrl_msg(struct udev_ctrl *uctrl) {
624 struct udev *udev = udev_ctrl_get_udev(uctrl);
625 struct udev_ctrl_connection *ctrl_conn;
626 struct udev_ctrl_msg *ctrl_msg = NULL;
630 ctrl_conn = udev_ctrl_get_connection(uctrl);
631 if (ctrl_conn == NULL)
634 ctrl_msg = udev_ctrl_receive_msg(ctrl_conn);
635 if (ctrl_msg == NULL)
638 i = udev_ctrl_get_set_log_level(ctrl_msg);
640 log_debug("udevd message (SET_LOG_LEVEL) received, log_priority=%i", i);
641 log_set_max_level(i);
645 if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
646 log_debug("udevd message (STOP_EXEC_QUEUE) received");
647 stop_exec_queue = true;
650 if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
651 log_debug("udevd message (START_EXEC_QUEUE) received");
652 stop_exec_queue = false;
655 if (udev_ctrl_get_reload(ctrl_msg) > 0) {
656 log_debug("udevd message (RELOAD) received");
660 str = udev_ctrl_get_set_env(ctrl_msg);
668 val = strchr(key, '=');
672 if (val[0] == '\0') {
673 log_debug("udevd message (ENV) received, unset '%s'", key);
674 udev_list_entry_add(&properties_list, key, NULL);
676 log_debug("udevd message (ENV) received, set '%s=%s'", key, val);
677 udev_list_entry_add(&properties_list, key, val);
680 log_error("wrong key format '%s'", key);
687 i = udev_ctrl_get_set_children_max(ctrl_msg);
689 log_debug("udevd message (SET_MAX_CHILDREN) received, children_max=%i", i);
690 arg_children_max = i;
693 if (udev_ctrl_get_ping(ctrl_msg) > 0)
694 log_debug("udevd message (SYNC) received");
696 if (udev_ctrl_get_exit(ctrl_msg) > 0) {
697 log_debug("udevd message (EXIT) received");
699 /* keep reference to block the client until we exit */
700 udev_ctrl_connection_ref(ctrl_conn);
703 udev_ctrl_msg_unref(ctrl_msg);
704 return udev_ctrl_connection_unref(ctrl_conn);
707 static int synthesize_change(struct udev_device *dev) {
708 char filename[UTIL_PATH_SIZE];
711 if (streq_ptr("block", udev_device_get_subsystem(dev)) &&
712 streq_ptr("disk", udev_device_get_devtype(dev)) &&
713 !startswith(udev_device_get_sysname(dev), "dm-")) {
714 bool part_table_read = false;
715 bool has_partitions = false;
717 struct udev *udev = udev_device_get_udev(dev);
718 _cleanup_udev_enumerate_unref_ struct udev_enumerate *e = NULL;
719 struct udev_list_entry *item;
722 * Try to re-read the partition table. This only succeeds if
723 * none of the devices is busy. The kernel returns 0 if no
724 * partition table is found, and we will not get an event for
727 fd = open(udev_device_get_devnode(dev), O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
729 r = flock(fd, LOCK_EX|LOCK_NB);
731 r = ioctl(fd, BLKRRPART, 0);
735 part_table_read = true;
738 /* search for partitions */
739 e = udev_enumerate_new(udev);
743 r = udev_enumerate_add_match_parent(e, dev);
747 r = udev_enumerate_add_match_subsystem(e, "block");
751 r = udev_enumerate_scan_devices(e);
755 udev_list_entry_foreach(item, udev_enumerate_get_list_entry(e)) {
756 _cleanup_udev_device_unref_ struct udev_device *d = NULL;
758 d = udev_device_new_from_syspath(udev, udev_list_entry_get_name(item));
762 if (!streq_ptr("partition", udev_device_get_devtype(d)))
765 has_partitions = true;
770 * We have partitions and re-read the table, the kernel already sent
771 * out a "change" event for the disk, and "remove/add" for all
774 if (part_table_read && has_partitions)
778 * We have partitions but re-reading the partition table did not
779 * work, synthesize "change" for the disk and all partitions.
781 log_debug("device %s closed, synthesising 'change'", udev_device_get_devnode(dev));
782 strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
783 write_string_file(filename, "change");
785 udev_list_entry_foreach(item, udev_enumerate_get_list_entry(e)) {
786 _cleanup_udev_device_unref_ struct udev_device *d = NULL;
788 d = udev_device_new_from_syspath(udev, udev_list_entry_get_name(item));
792 if (!streq_ptr("partition", udev_device_get_devtype(d)))
795 log_debug("device %s closed, synthesising partition '%s' 'change'",
796 udev_device_get_devnode(dev), udev_device_get_devnode(d));
797 strscpyl(filename, sizeof(filename), udev_device_get_syspath(d), "/uevent", NULL);
798 write_string_file(filename, "change");
804 log_debug("device %s closed, synthesising 'change'", udev_device_get_devnode(dev));
805 strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
806 write_string_file(filename, "change");
811 static int handle_inotify(struct udev *udev) {
814 struct inotify_event *ev;
817 r = ioctl(fd_inotify, FIONREAD, &nbytes);
818 if (r < 0 || nbytes <= 0)
821 buf = malloc(nbytes);
823 log_error("error getting buffer for inotify");
827 nbytes = read(fd_inotify, buf, nbytes);
829 for (pos = 0; pos < nbytes; pos += sizeof(struct inotify_event) + ev->len) {
830 struct udev_device *dev;
832 ev = (struct inotify_event *)(buf + pos);
833 dev = udev_watch_lookup(udev, ev->wd);
837 log_debug("inotify event: %x for %s", ev->mask, udev_device_get_devnode(dev));
838 if (ev->mask & IN_CLOSE_WRITE)
839 synthesize_change(dev);
840 else if (ev->mask & IN_IGNORED)
841 udev_watch_end(udev, dev);
843 udev_device_unref(dev);
850 static void handle_signal(struct udev *udev, int signo) {
860 struct udev_list_node *loop, *tmp;
862 pid = waitpid(-1, &status, WNOHANG);
866 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
867 struct worker *worker = node_to_worker(loop);
869 if (worker->pid != pid)
871 log_debug("worker [%u] exit", pid);
873 if (WIFEXITED(status)) {
874 if (WEXITSTATUS(status) != 0)
875 log_error("worker [%u] exit with return code %i",
876 pid, WEXITSTATUS(status));
877 } else if (WIFSIGNALED(status)) {
878 log_error("worker [%u] terminated by signal %i (%s)",
879 pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
880 } else if (WIFSTOPPED(status)) {
881 log_error("worker [%u] stopped", pid);
882 } else if (WIFCONTINUED(status)) {
883 log_error("worker [%u] continued", pid);
885 log_error("worker [%u] exit with status 0x%04x", pid, status);
888 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
890 log_error("worker [%u] failed while handling '%s'",
891 pid, worker->event->devpath);
892 worker->event->exitcode = -32;
893 event_queue_delete(worker->event);
895 /* drop reference taken for state 'running' */
896 worker_unref(worker);
899 worker_unref(worker);
910 static int systemd_fds(struct udev *udev, int *rctrl, int *rnetlink) {
911 int ctrl = -1, netlink = -1;
914 n = sd_listen_fds(true);
918 for (fd = SD_LISTEN_FDS_START; fd < n + SD_LISTEN_FDS_START; fd++) {
919 if (sd_is_socket(fd, AF_LOCAL, SOCK_SEQPACKET, -1)) {
926 if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1)) {
936 if (ctrl < 0 || netlink < 0)
939 log_debug("ctrl=%i netlink=%i", ctrl, netlink);
946 * read the kernel command line, in case we need to get into debug mode
947 * udev.log-priority=<level> syslog priority
948 * udev.children-max=<number of workers> events are fully serialized if set to 1
949 * udev.exec-delay=<number of seconds> delay execution of every executed program
951 static void kernel_cmdline_options(struct udev *udev) {
952 _cleanup_free_ char *line = NULL;
953 const char *word, *state;
957 r = proc_cmdline(&line);
959 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
963 FOREACH_WORD_QUOTED(word, l, line, state) {
964 char *s, *opt, *value;
966 s = strndup(word, l);
970 /* accept the same options for the initrd, prefixed with "rd." */
971 if (in_initrd() && startswith(s, "rd."))
976 if ((value = startswith(opt, "udev.log-priority="))) {
979 prio = util_log_priority(value);
980 log_set_max_level(prio);
981 } else if ((value = startswith(opt, "udev.children-max="))) {
982 r = safe_atoi(value, &arg_children_max);
984 log_warning("Invalid udev.children-max ignored: %s", value);
985 } else if ((value = startswith(opt, "udev.exec-delay="))) {
986 r = safe_atoi(value, &arg_exec_delay);
988 log_warning("Invalid udev.exec-delay ignored: %s", value);
989 } else if ((value = startswith(opt, "udev.event-timeout="))) {
990 r = safe_atou64(value, &arg_event_timeout_usec);
992 log_warning("Invalid udev.event-timeout ignored: %s", value);
995 arg_event_timeout_usec *= USEC_PER_SEC;
996 arg_event_timeout_warn_usec = (arg_event_timeout_usec / 3) ? : 1;
1003 static void help(void) {
1004 printf("%s [OPTIONS...]\n\n"
1005 "Manages devices.\n\n"
1008 " --children-max=<maximum number of workers>\n"
1009 " --exec-delay=<seconds to wait before executing RUN=>\n"
1010 " --event-timeout=<seconds to wait before terminating an event>\n"
1011 " --resolve-names=early|late|never\n"
1014 , program_invocation_short_name);
1017 static int parse_argv(int argc, char *argv[]) {
1018 static const struct option options[] = {
1019 { "daemon", no_argument, NULL, 'd' },
1020 { "debug", no_argument, NULL, 'D' },
1021 { "children-max", required_argument, NULL, 'c' },
1022 { "exec-delay", required_argument, NULL, 'e' },
1023 { "event-timeout", required_argument, NULL, 't' },
1024 { "resolve-names", required_argument, NULL, 'N' },
1025 { "help", no_argument, NULL, 'h' },
1026 { "version", no_argument, NULL, 'V' },
1035 while ((c = getopt_long(argc, argv, "c:de:DtN:hV", options, NULL)) >= 0) {
1041 arg_daemonize = true;
1044 r = safe_atoi(optarg, &arg_children_max);
1046 log_warning("Invalid --children-max ignored: %s", optarg);
1049 r = safe_atoi(optarg, &arg_exec_delay);
1051 log_warning("Invalid --exec-delay ignored: %s", optarg);
1054 r = safe_atou64(optarg, &arg_event_timeout_usec);
1056 log_warning("Invalid --event-timeout ignored: %s", optarg);
1058 arg_event_timeout_usec *= USEC_PER_SEC;
1059 arg_event_timeout_warn_usec = (arg_event_timeout_usec / 3) ? : 1;
1066 if (streq(optarg, "early")) {
1067 arg_resolve_names = 1;
1068 } else if (streq(optarg, "late")) {
1069 arg_resolve_names = 0;
1070 } else if (streq(optarg, "never")) {
1071 arg_resolve_names = -1;
1073 log_error("resolve-names must be early, late or never");
1081 printf("%s\n", VERSION);
1086 assert_not_reached("Unhandled option");
1094 int main(int argc, char *argv[]) {
1098 int fd_netlink = -1;
1100 struct epoll_event ep_ctrl = { .events = EPOLLIN };
1101 struct epoll_event ep_inotify = { .events = EPOLLIN };
1102 struct epoll_event ep_signal = { .events = EPOLLIN };
1103 struct epoll_event ep_netlink = { .events = EPOLLIN };
1104 struct epoll_event ep_worker = { .events = EPOLLIN };
1105 struct udev_ctrl_connection *ctrl_conn = NULL;
1112 log_set_target(LOG_TARGET_AUTO);
1113 log_parse_environment();
1116 r = parse_argv(argc, argv);
1120 kernel_cmdline_options(udev);
1123 log_set_max_level(LOG_DEBUG);
1125 if (getuid() != 0) {
1126 log_error("root privileges required");
1130 r = mac_selinux_init("/dev");
1132 log_error("could not initialize labelling: %s", strerror(-r));
1136 /* set umask before creating any file/directory */
1139 log_error("could not change dir to /: %m");
1145 udev_list_init(udev, &properties_list, true);
1147 r = mkdir("/run/udev", 0755);
1148 if (r < 0 && errno != EEXIST) {
1149 log_error("could not create /run/udev: %m");
1155 /* before opening new files, make sure std{in,out,err} fds are in a sane state */
1156 if (arg_daemonize) {
1159 fd = open("/dev/null", O_RDWR);
1161 if (write(STDOUT_FILENO, 0, 0) < 0)
1162 dup2(fd, STDOUT_FILENO);
1163 if (write(STDERR_FILENO, 0, 0) < 0)
1164 dup2(fd, STDERR_FILENO);
1165 if (fd > STDERR_FILENO)
1168 log_error("cannot open /dev/null");
1172 if (systemd_fds(udev, &fd_ctrl, &fd_netlink) >= 0) {
1173 /* get control and netlink socket from systemd */
1174 udev_ctrl = udev_ctrl_new_from_fd(udev, fd_ctrl);
1175 if (udev_ctrl == NULL) {
1176 log_error("error taking over udev control socket");
1181 monitor = udev_monitor_new_from_netlink_fd(udev, "kernel", fd_netlink);
1182 if (monitor == NULL) {
1183 log_error("error taking over netlink socket");
1188 /* get our own cgroup, we regularly kill everything udev has left behind */
1189 if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &udev_cgroup) < 0)
1192 /* open control and netlink socket */
1193 udev_ctrl = udev_ctrl_new(udev);
1194 if (udev_ctrl == NULL) {
1195 log_error("error initializing udev control socket");
1199 fd_ctrl = udev_ctrl_get_fd(udev_ctrl);
1201 monitor = udev_monitor_new_from_netlink(udev, "kernel");
1202 if (monitor == NULL) {
1203 log_error("error initializing netlink socket");
1207 fd_netlink = udev_monitor_get_fd(monitor);
1210 if (udev_monitor_enable_receiving(monitor) < 0) {
1211 log_error("error binding netlink socket");
1216 if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
1217 log_error("error binding udev control socket");
1222 udev_monitor_set_receive_buffer_size(monitor, 128 * 1024 * 1024);
1224 log_info("starting version " VERSION "\n");
1226 udev_builtin_init(udev);
1228 rules = udev_rules_new(udev, arg_resolve_names);
1229 if (rules == NULL) {
1230 log_error("error reading rules");
1234 rc = udev_rules_apply_static_dev_perms(rules);
1236 log_error("failed to apply permissions on static device nodes - %s", strerror(-rc));
1238 if (arg_daemonize) {
1246 log_error("fork of daemon failed: %m");
1251 goto exit_daemonize;
1256 write_string_file("/proc/self/oom_score_adj", "-1000");
1258 sd_notify(1, "READY=1");
1261 if (arg_children_max <= 0) {
1264 arg_children_max = 8;
1266 if (sched_getaffinity(0, sizeof (cpu_set), &cpu_set) == 0) {
1267 arg_children_max += CPU_COUNT(&cpu_set) * 2;
1270 log_debug("set children_max to %u", arg_children_max);
1272 udev_list_node_init(&event_list);
1273 udev_list_node_init(&worker_list);
1275 fd_inotify = udev_watch_init(udev);
1276 if (fd_inotify < 0) {
1277 log_error("error initializing inotify");
1281 udev_watch_restore(udev);
1283 /* block and listen to all signals on signalfd */
1285 sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
1286 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
1287 if (fd_signal < 0) {
1288 log_error("error creating signalfd");
1293 /* unnamed socket from workers to the main daemon */
1294 if (socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, worker_watch) < 0) {
1295 log_error("error creating socketpair");
1299 fd_worker = worker_watch[READ_END];
1301 ep_ctrl.data.fd = fd_ctrl;
1302 ep_inotify.data.fd = fd_inotify;
1303 ep_signal.data.fd = fd_signal;
1304 ep_netlink.data.fd = fd_netlink;
1305 ep_worker.data.fd = fd_worker;
1307 fd_ep = epoll_create1(EPOLL_CLOEXEC);
1309 log_error("error creating epoll fd: %m");
1312 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_ctrl, &ep_ctrl) < 0 ||
1313 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_inotify, &ep_inotify) < 0 ||
1314 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
1315 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_netlink, &ep_netlink) < 0 ||
1316 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_worker, &ep_worker) < 0) {
1317 log_error("fail to add fds to epoll: %m");
1322 static usec_t last_usec;
1323 struct epoll_event ev[8];
1326 bool is_worker, is_signal, is_inotify, is_netlink, is_ctrl;
1330 /* close sources of new events and discard buffered events */
1332 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_ctrl, NULL);
1335 if (monitor != NULL) {
1336 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_netlink, NULL);
1337 udev_monitor_unref(monitor);
1340 if (fd_inotify >= 0) {
1341 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_inotify, NULL);
1346 /* discard queued events and kill workers */
1347 event_queue_cleanup(udev, EVENT_QUEUED);
1350 /* exit after all has cleaned up */
1351 if (udev_list_node_is_empty(&event_list) && children == 0)
1354 /* timeout at exit for workers to finish */
1355 timeout = 30 * MSEC_PER_SEC;
1356 } else if (udev_list_node_is_empty(&event_list) && children == 0) {
1360 /* cleanup possible left-over processes in our cgroup */
1362 cg_kill(SYSTEMD_CGROUP_CONTROLLER, udev_cgroup, SIGKILL, false, true, NULL);
1364 /* kill idle or hanging workers */
1365 timeout = 3 * MSEC_PER_SEC;
1368 /* tell settle that we are busy or idle */
1369 if (!udev_list_node_is_empty(&event_list)) {
1372 fd = open("/run/udev/queue", O_WRONLY|O_CREAT|O_CLOEXEC|O_TRUNC|O_NOFOLLOW, 0444);
1376 unlink("/run/udev/queue");
1379 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
1384 struct udev_list_node *loop;
1388 log_error("timeout, giving up waiting for workers to finish");
1392 /* kill idle workers */
1393 if (udev_list_node_is_empty(&event_list)) {
1394 log_debug("cleanup idle workers");
1398 /* check for hanging events */
1399 udev_list_node_foreach(loop, &worker_list) {
1400 struct worker *worker = node_to_worker(loop);
1403 if (worker->state != WORKER_RUNNING)
1406 ts = now(CLOCK_MONOTONIC);
1408 if ((ts - worker->event_start_usec) > arg_event_timeout_warn_usec) {
1409 if ((ts - worker->event_start_usec) > arg_event_timeout_usec) {
1410 log_error("worker [%u] %s timeout; kill it", worker->pid, worker->event->devpath);
1411 kill(worker->pid, SIGKILL);
1412 worker->state = WORKER_KILLED;
1414 /* drop reference taken for state 'running' */
1415 worker_unref(worker);
1416 log_error("seq %llu '%s' killed", udev_device_get_seqnum(worker->event->dev), worker->event->devpath);
1417 worker->event->exitcode = -64;
1418 event_queue_delete(worker->event);
1419 worker->event = NULL;
1420 } else if (!worker->event_warned) {
1421 log_warning("worker [%u] %s is taking a long time", worker->pid, worker->event->devpath);
1422 worker->event_warned = true;
1429 is_worker = is_signal = is_inotify = is_netlink = is_ctrl = false;
1430 for (i = 0; i < fdcount; i++) {
1431 if (ev[i].data.fd == fd_worker && ev[i].events & EPOLLIN)
1433 else if (ev[i].data.fd == fd_netlink && ev[i].events & EPOLLIN)
1435 else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN)
1437 else if (ev[i].data.fd == fd_inotify && ev[i].events & EPOLLIN)
1439 else if (ev[i].data.fd == fd_ctrl && ev[i].events & EPOLLIN)
1443 /* check for changed config, every 3 seconds at most */
1444 if ((now(CLOCK_MONOTONIC) - last_usec) > 3 * USEC_PER_SEC) {
1445 if (udev_rules_check_timestamp(rules))
1447 if (udev_builtin_validate(udev))
1450 last_usec = now(CLOCK_MONOTONIC);
1453 /* reload requested, HUP signal received, rules changed, builtin changed */
1456 rules = udev_rules_unref(rules);
1457 udev_builtin_exit(udev);
1461 /* event has finished */
1463 worker_returned(fd_worker);
1466 struct udev_device *dev;
1468 dev = udev_monitor_receive_device(monitor);
1470 udev_device_set_usec_initialized(dev, now(CLOCK_MONOTONIC));
1471 if (event_queue_insert(dev) < 0)
1472 udev_device_unref(dev);
1476 /* start new events */
1477 if (!udev_list_node_is_empty(&event_list) && !udev_exit && !stop_exec_queue) {
1478 udev_builtin_init(udev);
1480 rules = udev_rules_new(udev, arg_resolve_names);
1482 event_queue_start(udev);
1486 struct signalfd_siginfo fdsi;
1489 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
1490 if (size == sizeof(struct signalfd_siginfo))
1491 handle_signal(udev, fdsi.ssi_signo);
1494 /* we are shutting down, the events below are not handled anymore */
1498 /* device node watch */
1500 handle_inotify(udev);
1503 * This needs to be after the inotify handling, to make sure,
1504 * that the ping is send back after the possibly generated
1505 * "change" events by the inotify device node watch.
1507 * A single time we may receive a client connection which we need to
1508 * keep open to block the client. It will be closed right before we
1512 ctrl_conn = handle_ctrl_msg(udev_ctrl);
1517 udev_ctrl_cleanup(udev_ctrl);
1518 unlink("/run/udev/queue");
1522 worker_list_cleanup(udev);
1523 event_queue_cleanup(udev, EVENT_UNDEF);
1524 udev_rules_unref(rules);
1525 udev_builtin_exit(udev);
1528 if (worker_watch[READ_END] >= 0)
1529 close(worker_watch[READ_END]);
1530 if (worker_watch[WRITE_END] >= 0)
1531 close(worker_watch[WRITE_END]);
1532 udev_monitor_unref(monitor);
1533 udev_ctrl_connection_unref(ctrl_conn);
1534 udev_ctrl_unref(udev_ctrl);
1535 udev_list_cleanup(&properties_list);
1536 mac_selinux_finish();