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 "sd-daemon.h"
52 #include "cgroup-util.h"
53 #include "dev-setup.h"
58 void udev_main_log(struct udev *udev, int priority,
59 const char *file, int line, const char *fn,
60 const char *format, va_list args) {
61 log_metav(priority, file, line, fn, format, args);
64 static struct udev_rules *rules;
65 static struct udev_ctrl *udev_ctrl;
66 static struct udev_monitor *monitor;
67 static int worker_watch[2] = { -1, -1 };
68 static int fd_signal = -1;
69 static int fd_ep = -1;
70 static int fd_inotify = -1;
71 static bool stop_exec_queue;
74 static int children_max;
75 static int exec_delay;
76 static usec_t event_timeout_usec = 30 * USEC_PER_SEC;
77 static sigset_t sigmask_orig;
78 static UDEV_LIST(event_list);
79 static UDEV_LIST(worker_list);
80 static char *udev_cgroup;
81 static bool udev_exit;
90 struct udev_list_node node;
92 struct udev_device *dev;
93 enum event_state state;
95 unsigned long long int delaying_seqnum;
96 unsigned long long int seqnum;
99 const char *devpath_old;
108 static inline struct event *node_to_event(struct udev_list_node *node) {
109 return container_of(node, struct event, node);
112 static void event_queue_cleanup(struct udev *udev, enum event_state type);
122 struct udev_list_node node;
126 struct udev_monitor *monitor;
127 enum worker_state state;
129 usec_t event_start_usec;
132 /* passed from worker to main process */
133 struct worker_message {
138 static inline struct worker *node_to_worker(struct udev_list_node *node) {
139 return container_of(node, struct worker, node);
142 static void event_queue_delete(struct event *event) {
143 udev_list_node_remove(&event->node);
144 udev_device_unref(event->dev);
148 static struct worker *worker_ref(struct worker *worker) {
153 static void worker_cleanup(struct worker *worker) {
154 udev_list_node_remove(&worker->node);
155 udev_monitor_unref(worker->monitor);
160 static void worker_unref(struct worker *worker) {
162 if (worker->refcount > 0)
164 log_debug("worker [%u] cleaned up", worker->pid);
165 worker_cleanup(worker);
168 static void worker_list_cleanup(struct udev *udev) {
169 struct udev_list_node *loop, *tmp;
171 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
172 struct worker *worker = node_to_worker(loop);
174 worker_cleanup(worker);
178 static void worker_new(struct event *event) {
179 struct udev *udev = event->udev;
180 struct worker *worker;
181 struct udev_monitor *worker_monitor;
184 /* listen for new events */
185 worker_monitor = udev_monitor_new_from_netlink(udev, NULL);
186 if (worker_monitor == NULL)
188 /* allow the main daemon netlink address to send devices to the worker */
189 udev_monitor_allow_unicast_sender(worker_monitor, monitor);
190 udev_monitor_enable_receiving(worker_monitor);
192 worker = new0(struct worker, 1);
193 if (worker == NULL) {
194 udev_monitor_unref(worker_monitor);
197 /* worker + event reference */
198 worker->refcount = 2;
204 struct udev_device *dev = NULL;
206 struct epoll_event ep_signal, ep_monitor;
208 int rc = EXIT_SUCCESS;
210 /* take initial device from queue */
215 worker_list_cleanup(udev);
216 event_queue_cleanup(udev, EVENT_UNDEF);
217 udev_monitor_unref(monitor);
218 udev_ctrl_unref(udev_ctrl);
221 close(worker_watch[READ_END]);
224 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
226 log_error("error creating signalfd %m");
231 fd_ep = epoll_create1(EPOLL_CLOEXEC);
233 log_error("error creating epoll fd: %m");
238 memzero(&ep_signal, sizeof(struct epoll_event));
239 ep_signal.events = EPOLLIN;
240 ep_signal.data.fd = fd_signal;
242 fd_monitor = udev_monitor_get_fd(worker_monitor);
243 memzero(&ep_monitor, sizeof(struct epoll_event));
244 ep_monitor.events = EPOLLIN;
245 ep_monitor.data.fd = fd_monitor;
247 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
248 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_monitor, &ep_monitor) < 0) {
249 log_error("fail to add fds to epoll: %m");
254 /* request TERM signal if parent exits */
255 prctl(PR_SET_PDEATHSIG, SIGTERM);
257 /* reset OOM score, we only protect the main daemon */
258 write_string_file("/proc/self/oom_score_adj", "0");
261 struct udev_event *udev_event;
262 struct worker_message msg;
266 log_debug("seq %llu running", udev_device_get_seqnum(dev));
267 udev_event = udev_event_new(dev);
268 if (udev_event == NULL) {
273 /* needed for SIGCHLD/SIGTERM in spawn() */
274 udev_event->fd_signal = fd_signal;
277 udev_event->exec_delay = exec_delay;
280 * Take a shared lock on the device node; this establishes
281 * a concept of device "ownership" to serialize device
282 * access. External processes holding an exclusive lock will
283 * cause udev to skip the event handling; in the case udev
284 * acquired the lock, the external process can block until
285 * udev has finished its event handling.
287 if (!streq_ptr(udev_device_get_action(dev), "remove") &&
288 streq_ptr("block", udev_device_get_subsystem(dev)) &&
289 !startswith(udev_device_get_sysname(dev), "dm-") &&
290 !startswith(udev_device_get_sysname(dev), "md")) {
291 struct udev_device *d = dev;
293 if (streq_ptr("partition", udev_device_get_devtype(d)))
294 d = udev_device_get_parent(d);
297 fd_lock = open(udev_device_get_devnode(d), O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
298 if (fd_lock >= 0 && flock(fd_lock, LOCK_SH|LOCK_NB) < 0) {
299 log_debug("Unable to flock(%s), skipping event handling: %m", udev_device_get_devnode(d));
301 fd_lock = safe_close(fd_lock);
307 /* apply rules, create node, symlinks */
308 udev_event_execute_rules(udev_event, event_timeout_usec, rules, &sigmask_orig);
310 udev_event_execute_run(udev_event, event_timeout_usec, &sigmask_orig);
312 /* apply/restore inotify watch */
313 if (udev_event->inotify_watch) {
314 udev_watch_begin(udev, dev);
315 udev_device_update_db(dev);
320 /* send processed event back to libudev listeners */
321 udev_monitor_send_device(worker_monitor, NULL, dev);
324 /* send udevd the result of the event execution */
325 memzero(&msg, sizeof(struct worker_message));
328 send(worker_watch[WRITE_END], &msg, sizeof(struct worker_message), 0);
330 log_debug("seq %llu processed with %i", udev_device_get_seqnum(dev), err);
332 udev_device_unref(dev);
335 if (udev_event->sigterm) {
336 udev_event_unref(udev_event);
340 udev_event_unref(udev_event);
342 /* wait for more device messages from main udevd, or term signal */
343 while (dev == NULL) {
344 struct epoll_event ev[4];
348 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), -1);
352 log_error("failed to poll: %m");
356 for (i = 0; i < fdcount; i++) {
357 if (ev[i].data.fd == fd_monitor && ev[i].events & EPOLLIN) {
358 dev = udev_monitor_receive_device(worker_monitor);
360 } else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN) {
361 struct signalfd_siginfo fdsi;
364 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
365 if (size != sizeof(struct signalfd_siginfo))
367 switch (fdsi.ssi_signo) {
376 udev_device_unref(dev);
377 safe_close(fd_signal);
380 close(worker_watch[WRITE_END]);
381 udev_rules_unref(rules);
382 udev_builtin_exit(udev);
383 udev_monitor_unref(worker_monitor);
389 udev_monitor_unref(worker_monitor);
390 event->state = EVENT_QUEUED;
392 log_error("fork of child failed: %m");
395 /* close monitor, but keep address around */
396 udev_monitor_disconnect(worker_monitor);
397 worker->monitor = worker_monitor;
399 worker->state = WORKER_RUNNING;
400 worker->event_start_usec = now(CLOCK_MONOTONIC);
401 worker->event = event;
402 event->state = EVENT_RUNNING;
403 udev_list_node_append(&worker->node, &worker_list);
405 log_debug("seq %llu forked new worker [%u]", udev_device_get_seqnum(event->dev), pid);
410 static void event_run(struct event *event) {
411 struct udev_list_node *loop;
413 udev_list_node_foreach(loop, &worker_list) {
414 struct worker *worker = node_to_worker(loop);
417 if (worker->state != WORKER_IDLE)
420 count = udev_monitor_send_device(monitor, worker->monitor, event->dev);
422 log_error("worker [%u] did not accept message %zi (%m), kill it", worker->pid, count);
423 kill(worker->pid, SIGKILL);
424 worker->state = WORKER_KILLED;
428 worker->event = event;
429 worker->state = WORKER_RUNNING;
430 worker->event_start_usec = now(CLOCK_MONOTONIC);
431 event->state = EVENT_RUNNING;
435 if (children >= children_max) {
436 if (children_max > 1)
437 log_debug("maximum number (%i) of children reached", children);
441 /* start new worker and pass initial device */
445 static int event_queue_insert(struct udev_device *dev) {
448 event = new0(struct event, 1);
452 event->udev = udev_device_get_udev(dev);
454 event->seqnum = udev_device_get_seqnum(dev);
455 event->devpath = udev_device_get_devpath(dev);
456 event->devpath_len = strlen(event->devpath);
457 event->devpath_old = udev_device_get_devpath_old(dev);
458 event->devnum = udev_device_get_devnum(dev);
459 event->is_block = streq("block", udev_device_get_subsystem(dev));
460 event->ifindex = udev_device_get_ifindex(dev);
462 if (streq(udev_device_get_subsystem(dev), "firmware"))
463 event->nodelay = true;
466 log_debug("seq %llu queued, '%s' '%s'", udev_device_get_seqnum(dev),
467 udev_device_get_action(dev), udev_device_get_subsystem(dev));
469 event->state = EVENT_QUEUED;
470 udev_list_node_append(&event->node, &event_list);
474 static void worker_kill(struct udev *udev) {
475 struct udev_list_node *loop;
477 udev_list_node_foreach(loop, &worker_list) {
478 struct worker *worker = node_to_worker(loop);
480 if (worker->state == WORKER_KILLED)
483 worker->state = WORKER_KILLED;
484 kill(worker->pid, SIGTERM);
488 /* lookup event for identical, parent, child device */
489 static bool is_devpath_busy(struct event *event) {
490 struct udev_list_node *loop;
493 /* check if queue contains events we depend on */
494 udev_list_node_foreach(loop, &event_list) {
495 struct event *loop_event = node_to_event(loop);
497 /* we already found a later event, earlier can not block us, no need to check again */
498 if (loop_event->seqnum < event->delaying_seqnum)
501 /* event we checked earlier still exists, no need to check again */
502 if (loop_event->seqnum == event->delaying_seqnum)
505 /* found ourself, no later event can block us */
506 if (loop_event->seqnum >= event->seqnum)
509 /* check major/minor */
510 if (major(event->devnum) != 0 && event->devnum == loop_event->devnum && event->is_block == loop_event->is_block)
513 /* check network device ifindex */
514 if (event->ifindex != 0 && event->ifindex == loop_event->ifindex)
517 /* check our old name */
518 if (event->devpath_old != NULL && streq(loop_event->devpath, event->devpath_old)) {
519 event->delaying_seqnum = loop_event->seqnum;
523 /* compare devpath */
524 common = MIN(loop_event->devpath_len, event->devpath_len);
526 /* one devpath is contained in the other? */
527 if (memcmp(loop_event->devpath, event->devpath, common) != 0)
530 /* identical device event found */
531 if (loop_event->devpath_len == event->devpath_len) {
532 /* devices names might have changed/swapped in the meantime */
533 if (major(event->devnum) != 0 && (event->devnum != loop_event->devnum || event->is_block != loop_event->is_block))
535 if (event->ifindex != 0 && event->ifindex != loop_event->ifindex)
537 event->delaying_seqnum = loop_event->seqnum;
542 /* allow to bypass the dependency tracking */
547 /* parent device event found */
548 if (event->devpath[common] == '/') {
549 event->delaying_seqnum = loop_event->seqnum;
553 /* child device event found */
554 if (loop_event->devpath[common] == '/') {
555 event->delaying_seqnum = loop_event->seqnum;
559 /* no matching device */
566 static void event_queue_start(struct udev *udev) {
567 struct udev_list_node *loop;
569 udev_list_node_foreach(loop, &event_list) {
570 struct event *event = node_to_event(loop);
572 if (event->state != EVENT_QUEUED)
575 /* do not start event if parent or child event is still running */
576 if (is_devpath_busy(event))
583 static void event_queue_cleanup(struct udev *udev, enum event_state match_type) {
584 struct udev_list_node *loop, *tmp;
586 udev_list_node_foreach_safe(loop, tmp, &event_list) {
587 struct event *event = node_to_event(loop);
589 if (match_type != EVENT_UNDEF && match_type != event->state)
592 event_queue_delete(event);
596 static void worker_returned(int fd_worker) {
598 struct worker_message msg;
600 struct udev_list_node *loop;
602 size = recv(fd_worker, &msg, sizeof(struct worker_message), MSG_DONTWAIT);
603 if (size != sizeof(struct worker_message))
606 /* lookup worker who sent the signal */
607 udev_list_node_foreach(loop, &worker_list) {
608 struct worker *worker = node_to_worker(loop);
610 if (worker->pid != msg.pid)
613 /* worker returned */
615 worker->event->exitcode = msg.exitcode;
616 event_queue_delete(worker->event);
617 worker->event = NULL;
619 if (worker->state != WORKER_KILLED)
620 worker->state = WORKER_IDLE;
621 worker_unref(worker);
627 /* receive the udevd message from userspace */
628 static struct udev_ctrl_connection *handle_ctrl_msg(struct udev_ctrl *uctrl) {
629 struct udev *udev = udev_ctrl_get_udev(uctrl);
630 struct udev_ctrl_connection *ctrl_conn;
631 struct udev_ctrl_msg *ctrl_msg = NULL;
635 ctrl_conn = udev_ctrl_get_connection(uctrl);
636 if (ctrl_conn == NULL)
639 ctrl_msg = udev_ctrl_receive_msg(ctrl_conn);
640 if (ctrl_msg == NULL)
643 i = udev_ctrl_get_set_log_level(ctrl_msg);
645 log_debug("udevd message (SET_LOG_LEVEL) received, log_priority=%i", i);
646 log_set_max_level(i);
647 udev_set_log_priority(udev, i);
651 if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
652 log_debug("udevd message (STOP_EXEC_QUEUE) received");
653 stop_exec_queue = true;
656 if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
657 log_debug("udevd message (START_EXEC_QUEUE) received");
658 stop_exec_queue = false;
661 if (udev_ctrl_get_reload(ctrl_msg) > 0) {
662 log_debug("udevd message (RELOAD) received");
666 str = udev_ctrl_get_set_env(ctrl_msg);
674 val = strchr(key, '=');
678 if (val[0] == '\0') {
679 log_debug("udevd message (ENV) received, unset '%s'", key);
680 udev_add_property(udev, key, NULL);
682 log_debug("udevd message (ENV) received, set '%s=%s'", key, val);
683 udev_add_property(udev, key, val);
686 log_error("wrong key format '%s'", key);
693 i = udev_ctrl_get_set_children_max(ctrl_msg);
695 log_debug("udevd message (SET_MAX_CHILDREN) received, children_max=%i", i);
699 if (udev_ctrl_get_ping(ctrl_msg) > 0)
700 log_debug("udevd message (SYNC) received");
702 if (udev_ctrl_get_exit(ctrl_msg) > 0) {
703 log_debug("udevd message (EXIT) received");
705 /* keep reference to block the client until we exit */
706 udev_ctrl_connection_ref(ctrl_conn);
709 udev_ctrl_msg_unref(ctrl_msg);
710 return udev_ctrl_connection_unref(ctrl_conn);
713 static int synthesize_change(struct udev_device *dev) {
714 char filename[UTIL_PATH_SIZE];
717 if (streq_ptr("block", udev_device_get_subsystem(dev)) &&
718 streq_ptr("disk", udev_device_get_devtype(dev)) &&
719 !startswith(udev_device_get_sysname(dev), "dm-")) {
720 bool part_table_read = false;
721 bool has_partitions = false;
723 struct udev *udev = udev_device_get_udev(dev);
724 _cleanup_udev_enumerate_unref_ struct udev_enumerate *e = NULL;
725 struct udev_list_entry *item;
728 * Try to re-read the partition table. This only succeeds if
729 * none of the devices is busy. The kernel returns 0 if no
730 * partition table is found, and we will not get an event for
733 fd = open(udev_device_get_devnode(dev), O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
735 r = flock(fd, LOCK_EX|LOCK_NB);
737 r = ioctl(fd, BLKRRPART, 0);
741 part_table_read = true;
744 /* search for partitions */
745 e = udev_enumerate_new(udev);
749 r = udev_enumerate_add_match_parent(e, dev);
753 r = udev_enumerate_add_match_subsystem(e, "block");
757 r = udev_enumerate_scan_devices(e);
761 udev_list_entry_foreach(item, udev_enumerate_get_list_entry(e)) {
762 _cleanup_udev_device_unref_ struct udev_device *d = NULL;
764 d = udev_device_new_from_syspath(udev, udev_list_entry_get_name(item));
768 if (!streq_ptr("partition", udev_device_get_devtype(d)))
771 has_partitions = true;
776 * We have partitions and re-read the table, the kernel already sent
777 * out a "change" event for the disk, and "remove/add" for all
780 if (part_table_read && has_partitions)
784 * We have partitions but re-reading the partition table did not
785 * work, synthesize "change" for the disk and all partitions.
787 log_debug("device %s closed, synthesising 'change'", udev_device_get_devnode(dev));
788 strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
789 write_string_file(filename, "change");
791 udev_list_entry_foreach(item, udev_enumerate_get_list_entry(e)) {
792 _cleanup_udev_device_unref_ struct udev_device *d = NULL;
794 d = udev_device_new_from_syspath(udev, udev_list_entry_get_name(item));
798 if (!streq_ptr("partition", udev_device_get_devtype(d)))
801 log_debug("device %s closed, synthesising partition '%s' 'change'",
802 udev_device_get_devnode(dev), udev_device_get_devnode(d));
803 strscpyl(filename, sizeof(filename), udev_device_get_syspath(d), "/uevent", NULL);
804 write_string_file(filename, "change");
810 log_debug("device %s closed, synthesising 'change'", udev_device_get_devnode(dev));
811 strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
812 write_string_file(filename, "change");
817 static int handle_inotify(struct udev *udev) {
820 struct inotify_event *ev;
823 r = ioctl(fd_inotify, FIONREAD, &nbytes);
824 if (r < 0 || nbytes <= 0)
827 buf = malloc(nbytes);
829 log_error("error getting buffer for inotify");
833 nbytes = read(fd_inotify, buf, nbytes);
835 for (pos = 0; pos < nbytes; pos += sizeof(struct inotify_event) + ev->len) {
836 struct udev_device *dev;
838 ev = (struct inotify_event *)(buf + pos);
839 dev = udev_watch_lookup(udev, ev->wd);
843 log_debug("inotify event: %x for %s", ev->mask, udev_device_get_devnode(dev));
844 if (ev->mask & IN_CLOSE_WRITE)
845 synthesize_change(dev);
846 else if (ev->mask & IN_IGNORED)
847 udev_watch_end(udev, dev);
849 udev_device_unref(dev);
856 static void handle_signal(struct udev *udev, int signo) {
866 struct udev_list_node *loop, *tmp;
868 pid = waitpid(-1, &status, WNOHANG);
872 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
873 struct worker *worker = node_to_worker(loop);
875 if (worker->pid != pid)
877 log_debug("worker [%u] exit", pid);
879 if (WIFEXITED(status)) {
880 if (WEXITSTATUS(status) != 0)
881 log_error("worker [%u] exit with return code %i",
882 pid, WEXITSTATUS(status));
883 } else if (WIFSIGNALED(status)) {
884 log_error("worker [%u] terminated by signal %i (%s)",
885 pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
886 } else if (WIFSTOPPED(status)) {
887 log_error("worker [%u] stopped", pid);
888 } else if (WIFCONTINUED(status)) {
889 log_error("worker [%u] continued", pid);
891 log_error("worker [%u] exit with status 0x%04x", pid, status);
894 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
896 log_error("worker [%u] failed while handling '%s'",
897 pid, worker->event->devpath);
898 worker->event->exitcode = -32;
899 event_queue_delete(worker->event);
901 /* drop reference taken for state 'running' */
902 worker_unref(worker);
905 worker_unref(worker);
916 static int systemd_fds(struct udev *udev, int *rctrl, int *rnetlink) {
917 int ctrl = -1, netlink = -1;
920 n = sd_listen_fds(true);
924 for (fd = SD_LISTEN_FDS_START; fd < n + SD_LISTEN_FDS_START; fd++) {
925 if (sd_is_socket(fd, AF_LOCAL, SOCK_SEQPACKET, -1)) {
932 if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1)) {
942 if (ctrl < 0 || netlink < 0)
945 log_debug("ctrl=%i netlink=%i", ctrl, netlink);
952 * read the kernel commandline, in case we need to get into debug mode
953 * udev.log-priority=<level> syslog priority
954 * udev.children-max=<number of workers> events are fully serialized if set to 1
955 * udev.exec-delay=<number of seconds> delay execution of every executed program
957 static void kernel_cmdline_options(struct udev *udev) {
958 _cleanup_free_ char *line = NULL;
959 const char *word, *state;
963 r = proc_cmdline(&line);
965 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
969 FOREACH_WORD_QUOTED(word, l, line, state) {
972 s = strndup(word, l);
976 /* accept the same options for the initrd, prefixed with "rd." */
977 if (in_initrd() && startswith(s, "rd."))
982 if (startswith(opt, "udev.log-priority=")) {
985 prio = util_log_priority(opt + 18);
986 log_set_max_level(prio);
987 udev_set_log_priority(udev, prio);
988 } else if (startswith(opt, "udev.children-max=")) {
989 children_max = strtoul(opt + 18, NULL, 0);
990 } else if (startswith(opt, "udev.exec-delay=")) {
991 exec_delay = strtoul(opt + 16, NULL, 0);
992 } else if (startswith(opt, "udev.event-timeout=")) {
993 event_timeout_usec = strtoul(opt + 16, NULL, 0) * USEC_PER_SEC;
1000 int main(int argc, char *argv[]) {
1003 int daemonize = false;
1004 int resolve_names = 1;
1005 static const struct option options[] = {
1006 { "daemon", no_argument, NULL, 'd' },
1007 { "debug", no_argument, NULL, 'D' },
1008 { "children-max", required_argument, NULL, 'c' },
1009 { "exec-delay", required_argument, NULL, 'e' },
1010 { "event-timeout", required_argument, NULL, 't' },
1011 { "resolve-names", required_argument, NULL, 'N' },
1012 { "help", no_argument, NULL, 'h' },
1013 { "version", no_argument, NULL, 'V' },
1017 int fd_netlink = -1;
1019 struct epoll_event ep_ctrl, ep_inotify, ep_signal, ep_netlink, ep_worker;
1020 struct udev_ctrl_connection *ctrl_conn = NULL;
1027 log_set_target(LOG_TARGET_AUTO);
1028 log_parse_environment();
1031 udev_set_log_fn(udev, udev_main_log);
1032 log_set_max_level(udev_get_log_priority(udev));
1034 log_debug("version %s", VERSION);
1040 option = getopt_long(argc, argv, "c:de:DtN:hV", options, NULL);
1049 children_max = strtoul(optarg, NULL, 0);
1052 exec_delay = strtoul(optarg, NULL, 0);
1055 event_timeout_usec = strtoul(optarg, NULL, 0) * USEC_PER_SEC;
1059 log_set_max_level(LOG_DEBUG);
1060 udev_set_log_priority(udev, LOG_DEBUG);
1063 if (streq(optarg, "early")) {
1065 } else if (streq(optarg, "late")) {
1067 } else if (streq(optarg, "never")) {
1070 fprintf(stderr, "resolve-names must be early, late or never\n");
1071 log_error("resolve-names must be early, late or never");
1076 printf("Usage: udevd OPTIONS\n"
1079 " --children-max=<maximum number of workers>\n"
1080 " --exec-delay=<seconds to wait before executing RUN=>\n"
1081 " --event-timeout=<seconds to wait before terminating an event>\n"
1082 " --resolve-names=early|late|never\n"
1088 printf("%s\n", VERSION);
1095 kernel_cmdline_options(udev);
1097 if (getuid() != 0) {
1098 fprintf(stderr, "root privileges required\n");
1099 log_error("root privileges required");
1103 /* set umask before creating any file/directory */
1107 mkdir("/run/udev", 0755);
1111 /* before opening new files, make sure std{in,out,err} fds are in a sane state */
1115 fd = open("/dev/null", O_RDWR);
1117 if (write(STDOUT_FILENO, 0, 0) < 0)
1118 dup2(fd, STDOUT_FILENO);
1119 if (write(STDERR_FILENO, 0, 0) < 0)
1120 dup2(fd, STDERR_FILENO);
1121 if (fd > STDERR_FILENO)
1124 fprintf(stderr, "cannot open /dev/null\n");
1125 log_error("cannot open /dev/null");
1129 if (systemd_fds(udev, &fd_ctrl, &fd_netlink) >= 0) {
1130 /* get control and netlink socket from systemd */
1131 udev_ctrl = udev_ctrl_new_from_fd(udev, fd_ctrl);
1132 if (udev_ctrl == NULL) {
1133 log_error("error taking over udev control socket");
1138 monitor = udev_monitor_new_from_netlink_fd(udev, "kernel", fd_netlink);
1139 if (monitor == NULL) {
1140 log_error("error taking over netlink socket");
1145 /* get our own cgroup, we regularly kill everything udev has left behind */
1146 if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &udev_cgroup) < 0)
1149 /* open control and netlink socket */
1150 udev_ctrl = udev_ctrl_new(udev);
1151 if (udev_ctrl == NULL) {
1152 fprintf(stderr, "error initializing udev control socket");
1153 log_error("error initializing udev control socket");
1157 fd_ctrl = udev_ctrl_get_fd(udev_ctrl);
1159 monitor = udev_monitor_new_from_netlink(udev, "kernel");
1160 if (monitor == NULL) {
1161 fprintf(stderr, "error initializing netlink socket\n");
1162 log_error("error initializing netlink socket");
1166 fd_netlink = udev_monitor_get_fd(monitor);
1169 if (udev_monitor_enable_receiving(monitor) < 0) {
1170 fprintf(stderr, "error binding netlink socket\n");
1171 log_error("error binding netlink socket");
1176 if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
1177 fprintf(stderr, "error binding udev control socket\n");
1178 log_error("error binding udev control socket");
1183 udev_monitor_set_receive_buffer_size(monitor, 128 * 1024 * 1024);
1193 log_error("fork of daemon failed: %m");
1198 goto exit_daemonize;
1203 write_string_file("/proc/self/oom_score_adj", "-1000");
1205 sd_notify(1, "READY=1");
1208 print_kmsg("starting version " VERSION "\n");
1213 fd = open("/dev/null", O_RDWR);
1215 dup2(fd, STDIN_FILENO);
1216 dup2(fd, STDOUT_FILENO);
1217 dup2(fd, STDERR_FILENO);
1222 fd_inotify = udev_watch_init(udev);
1223 if (fd_inotify < 0) {
1224 fprintf(stderr, "error initializing inotify\n");
1225 log_error("error initializing inotify");
1229 udev_watch_restore(udev);
1231 /* block and listen to all signals on signalfd */
1233 sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
1234 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
1235 if (fd_signal < 0) {
1236 fprintf(stderr, "error creating signalfd\n");
1237 log_error("error creating signalfd");
1242 /* unnamed socket from workers to the main daemon */
1243 if (socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, worker_watch) < 0) {
1244 fprintf(stderr, "error creating socketpair\n");
1245 log_error("error creating socketpair");
1249 fd_worker = worker_watch[READ_END];
1251 udev_builtin_init(udev);
1253 rules = udev_rules_new(udev, resolve_names);
1254 if (rules == NULL) {
1255 log_error("error reading rules");
1259 memzero(&ep_ctrl, sizeof(struct epoll_event));
1260 ep_ctrl.events = EPOLLIN;
1261 ep_ctrl.data.fd = fd_ctrl;
1263 memzero(&ep_inotify, sizeof(struct epoll_event));
1264 ep_inotify.events = EPOLLIN;
1265 ep_inotify.data.fd = fd_inotify;
1267 memzero(&ep_signal, sizeof(struct epoll_event));
1268 ep_signal.events = EPOLLIN;
1269 ep_signal.data.fd = fd_signal;
1271 memzero(&ep_netlink, sizeof(struct epoll_event));
1272 ep_netlink.events = EPOLLIN;
1273 ep_netlink.data.fd = fd_netlink;
1275 memzero(&ep_worker, sizeof(struct epoll_event));
1276 ep_worker.events = EPOLLIN;
1277 ep_worker.data.fd = fd_worker;
1279 fd_ep = epoll_create1(EPOLL_CLOEXEC);
1281 log_error("error creating epoll fd: %m");
1284 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_ctrl, &ep_ctrl) < 0 ||
1285 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_inotify, &ep_inotify) < 0 ||
1286 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
1287 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_netlink, &ep_netlink) < 0 ||
1288 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_worker, &ep_worker) < 0) {
1289 log_error("fail to add fds to epoll: %m");
1293 if (children_max <= 0) {
1298 if (sched_getaffinity(0, sizeof (cpu_set), &cpu_set) == 0) {
1299 children_max += CPU_COUNT(&cpu_set) * 2;
1302 log_debug("set children_max to %u", children_max);
1304 rc = udev_rules_apply_static_dev_perms(rules);
1306 log_error("failed to apply permissions on static device nodes - %s", strerror(-rc));
1308 udev_list_node_init(&event_list);
1309 udev_list_node_init(&worker_list);
1312 static usec_t last_usec;
1313 struct epoll_event ev[8];
1316 bool is_worker, is_signal, is_inotify, is_netlink, is_ctrl;
1320 /* close sources of new events and discard buffered events */
1322 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_ctrl, NULL);
1325 if (monitor != NULL) {
1326 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_netlink, NULL);
1327 udev_monitor_unref(monitor);
1330 if (fd_inotify >= 0) {
1331 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_inotify, NULL);
1336 /* discard queued events and kill workers */
1337 event_queue_cleanup(udev, EVENT_QUEUED);
1340 /* exit after all has cleaned up */
1341 if (udev_list_node_is_empty(&event_list) && children == 0)
1344 /* timeout at exit for workers to finish */
1345 timeout = 30 * MSEC_PER_SEC;
1346 } else if (udev_list_node_is_empty(&event_list) && children == 0) {
1350 /* cleanup possible left-over processes in our cgroup */
1352 cg_kill(SYSTEMD_CGROUP_CONTROLLER, udev_cgroup, SIGKILL, false, true, NULL);
1354 /* kill idle or hanging workers */
1355 timeout = 3 * MSEC_PER_SEC;
1358 /* tell settle that we are busy or idle */
1359 if (!udev_list_node_is_empty(&event_list)) {
1362 fd = open("/run/udev/queue", O_WRONLY|O_CREAT|O_CLOEXEC|O_TRUNC|O_NOFOLLOW, 0444);
1366 unlink("/run/udev/queue");
1369 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
1374 struct udev_list_node *loop;
1378 log_error("timeout, giving up waiting for workers to finish");
1382 /* kill idle workers */
1383 if (udev_list_node_is_empty(&event_list)) {
1384 log_debug("cleanup idle workers");
1388 /* check for hanging events */
1389 udev_list_node_foreach(loop, &worker_list) {
1390 struct worker *worker = node_to_worker(loop);
1392 if (worker->state != WORKER_RUNNING)
1395 if ((now(CLOCK_MONOTONIC) - worker->event_start_usec) > event_timeout_usec) {
1396 log_error("worker [%u] %s timeout; kill it", worker->pid, worker->event->devpath);
1397 kill(worker->pid, SIGKILL);
1398 worker->state = WORKER_KILLED;
1400 /* drop reference taken for state 'running' */
1401 worker_unref(worker);
1402 log_error("seq %llu '%s' killed", udev_device_get_seqnum(worker->event->dev), worker->event->devpath);
1403 worker->event->exitcode = -64;
1404 event_queue_delete(worker->event);
1405 worker->event = NULL;
1411 is_worker = is_signal = is_inotify = is_netlink = is_ctrl = false;
1412 for (i = 0; i < fdcount; i++) {
1413 if (ev[i].data.fd == fd_worker && ev[i].events & EPOLLIN)
1415 else if (ev[i].data.fd == fd_netlink && ev[i].events & EPOLLIN)
1417 else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN)
1419 else if (ev[i].data.fd == fd_inotify && ev[i].events & EPOLLIN)
1421 else if (ev[i].data.fd == fd_ctrl && ev[i].events & EPOLLIN)
1425 /* check for changed config, every 3 seconds at most */
1426 if ((now(CLOCK_MONOTONIC) - last_usec) > 3 * USEC_PER_SEC) {
1427 if (udev_rules_check_timestamp(rules))
1429 if (udev_builtin_validate(udev))
1432 last_usec = now(CLOCK_MONOTONIC);
1435 /* reload requested, HUP signal received, rules changed, builtin changed */
1438 rules = udev_rules_unref(rules);
1439 udev_builtin_exit(udev);
1443 /* event has finished */
1445 worker_returned(fd_worker);
1448 struct udev_device *dev;
1450 dev = udev_monitor_receive_device(monitor);
1452 udev_device_set_usec_initialized(dev, now(CLOCK_MONOTONIC));
1453 if (event_queue_insert(dev) < 0)
1454 udev_device_unref(dev);
1458 /* start new events */
1459 if (!udev_list_node_is_empty(&event_list) && !udev_exit && !stop_exec_queue) {
1460 udev_builtin_init(udev);
1462 rules = udev_rules_new(udev, resolve_names);
1464 event_queue_start(udev);
1468 struct signalfd_siginfo fdsi;
1471 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
1472 if (size == sizeof(struct signalfd_siginfo))
1473 handle_signal(udev, fdsi.ssi_signo);
1476 /* we are shutting down, the events below are not handled anymore */
1480 /* device node watch */
1482 handle_inotify(udev);
1485 * This needs to be after the inotify handling, to make sure,
1486 * that the ping is send back after the possibly generated
1487 * "change" events by the inotify device node watch.
1489 * A single time we may receive a client connection which we need to
1490 * keep open to block the client. It will be closed right before we
1494 ctrl_conn = handle_ctrl_msg(udev_ctrl);
1499 udev_ctrl_cleanup(udev_ctrl);
1500 unlink("/run/udev/queue");
1504 worker_list_cleanup(udev);
1505 event_queue_cleanup(udev, EVENT_UNDEF);
1506 udev_rules_unref(rules);
1507 udev_builtin_exit(udev);
1510 if (worker_watch[READ_END] >= 0)
1511 close(worker_watch[READ_END]);
1512 if (worker_watch[WRITE_END] >= 0)
1513 close(worker_watch[WRITE_END]);
1514 udev_monitor_unref(monitor);
1515 udev_ctrl_connection_unref(ctrl_conn);
1516 udev_ctrl_unref(udev_ctrl);