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>
44 #include <sys/ioctl.h>
45 #include <sys/inotify.h>
46 #include <sys/utsname.h>
49 #include "sd-daemon.h"
50 #include "cgroup-util.h"
51 #include "dev-setup.h"
56 void udev_main_log(struct udev *udev, int priority,
57 const char *file, int line, const char *fn,
58 const char *format, va_list args)
60 log_metav(priority, file, line, fn, format, args);
63 static struct udev_rules *rules;
64 static struct udev_ctrl *udev_ctrl;
65 static struct udev_monitor *monitor;
66 static int worker_watch[2] = { -1, -1 };
67 static int fd_signal = -1;
68 static int fd_ep = -1;
69 static int fd_inotify = -1;
70 static bool stop_exec_queue;
73 static int children_max;
74 static int exec_delay;
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 bool udev_exit;
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;
106 static inline struct event *node_to_event(struct udev_list_node *node)
108 return container_of(node, struct event, node);
111 static void event_queue_cleanup(struct udev *udev, enum event_state type);
121 struct udev_list_node node;
125 struct udev_monitor *monitor;
126 enum worker_state state;
128 usec_t event_start_usec;
131 /* passed from worker to main process */
132 struct worker_message {
137 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)
144 udev_list_node_remove(&event->node);
145 udev_device_unref(event->dev);
149 static struct worker *worker_ref(struct worker *worker)
155 static void worker_cleanup(struct worker *worker)
157 udev_list_node_remove(&worker->node);
158 udev_monitor_unref(worker->monitor);
163 static void worker_unref(struct worker *worker)
166 if (worker->refcount > 0)
168 log_debug("worker [%u] cleaned up", worker->pid);
169 worker_cleanup(worker);
172 static void worker_list_cleanup(struct udev *udev)
174 struct udev_list_node *loop, *tmp;
176 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
177 struct worker *worker = node_to_worker(loop);
179 worker_cleanup(worker);
183 static void worker_new(struct event *event)
185 struct udev *udev = event->udev;
186 struct worker *worker;
187 struct udev_monitor *worker_monitor;
190 /* listen for new events */
191 worker_monitor = udev_monitor_new_from_netlink(udev, NULL);
192 if (worker_monitor == NULL)
194 /* allow the main daemon netlink address to send devices to the worker */
195 udev_monitor_allow_unicast_sender(worker_monitor, monitor);
196 udev_monitor_enable_receiving(worker_monitor);
198 worker = new0(struct worker, 1);
199 if (worker == NULL) {
200 udev_monitor_unref(worker_monitor);
203 /* worker + event reference */
204 worker->refcount = 2;
210 struct udev_device *dev = NULL;
212 struct epoll_event ep_signal, ep_monitor;
214 int rc = EXIT_SUCCESS;
216 /* take initial device from queue */
221 worker_list_cleanup(udev);
222 event_queue_cleanup(udev, EVENT_UNDEF);
223 udev_monitor_unref(monitor);
224 udev_ctrl_unref(udev_ctrl);
227 close(worker_watch[READ_END]);
230 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
232 log_error("error creating signalfd %m");
237 fd_ep = epoll_create1(EPOLL_CLOEXEC);
239 log_error("error creating epoll fd: %m");
244 memzero(&ep_signal, sizeof(struct epoll_event));
245 ep_signal.events = EPOLLIN;
246 ep_signal.data.fd = fd_signal;
248 fd_monitor = udev_monitor_get_fd(worker_monitor);
249 memzero(&ep_monitor, sizeof(struct epoll_event));
250 ep_monitor.events = EPOLLIN;
251 ep_monitor.data.fd = fd_monitor;
253 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
254 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_monitor, &ep_monitor) < 0) {
255 log_error("fail to add fds to epoll: %m");
260 /* request TERM signal if parent exits */
261 prctl(PR_SET_PDEATHSIG, SIGTERM);
263 /* reset OOM score, we only protect the main daemon */
264 write_string_file("/proc/self/oom_score_adj", "0");
267 struct udev_event *udev_event;
268 struct worker_message msg;
272 log_debug("seq %llu running", udev_device_get_seqnum(dev));
273 udev_event = udev_event_new(dev);
274 if (udev_event == NULL) {
279 /* needed for SIGCHLD/SIGTERM in spawn() */
280 udev_event->fd_signal = fd_signal;
283 udev_event->exec_delay = exec_delay;
286 * Take a "read lock" on the device node; this establishes
287 * a concept of device "ownership" to serialize device
288 * access. External processes holding a "write lock" will
289 * cause udev to skip the event handling; in the case udev
290 * acquired the lock, the external process will block until
291 * udev has finished its event handling.
293 if (streq_ptr("block", udev_device_get_subsystem(dev))) {
294 struct udev_device *d = dev;
296 if (streq_ptr("partition", udev_device_get_devtype(d)))
297 d = udev_device_get_parent(d);
300 fd_lock = open(udev_device_get_devnode(d), O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
301 if (fd_lock >= 0 && flock(fd_lock, LOCK_SH|LOCK_NB) < 0) {
302 log_debug("Unable to flock(%s), skipping event handling: %m", udev_device_get_devnode(d));
309 /* apply rules, create node, symlinks */
310 err = udev_event_execute_rules(udev_event, rules, &sigmask_orig);
313 udev_event_execute_run(udev_event, &sigmask_orig);
315 /* apply/restore inotify watch */
316 if (err == 0 && udev_event->inotify_watch) {
317 udev_watch_begin(udev, dev);
318 udev_device_update_db(dev);
324 /* send processed event back to libudev listeners */
325 udev_monitor_send_device(worker_monitor, NULL, dev);
328 /* send udevd the result of the event execution */
329 memzero(&msg, sizeof(struct worker_message));
332 send(worker_watch[WRITE_END], &msg, sizeof(struct worker_message), 0);
334 log_debug("seq %llu processed with %i", udev_device_get_seqnum(dev), err);
336 udev_device_unref(dev);
339 if (udev_event->sigterm) {
340 udev_event_unref(udev_event);
344 udev_event_unref(udev_event);
346 /* wait for more device messages from main udevd, or term signal */
347 while (dev == NULL) {
348 struct epoll_event ev[4];
352 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), -1);
356 log_error("failed to poll: %m");
360 for (i = 0; i < fdcount; i++) {
361 if (ev[i].data.fd == fd_monitor && ev[i].events & EPOLLIN) {
362 dev = udev_monitor_receive_device(worker_monitor);
364 } else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN) {
365 struct signalfd_siginfo fdsi;
368 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
369 if (size != sizeof(struct signalfd_siginfo))
371 switch (fdsi.ssi_signo) {
380 udev_device_unref(dev);
386 close(worker_watch[WRITE_END]);
387 udev_rules_unref(rules);
388 udev_builtin_exit(udev);
389 udev_monitor_unref(worker_monitor);
395 udev_monitor_unref(worker_monitor);
396 event->state = EVENT_QUEUED;
398 log_error("fork of child failed: %m");
401 /* close monitor, but keep address around */
402 udev_monitor_disconnect(worker_monitor);
403 worker->monitor = worker_monitor;
405 worker->state = WORKER_RUNNING;
406 worker->event_start_usec = now(CLOCK_MONOTONIC);
407 worker->event = event;
408 event->state = EVENT_RUNNING;
409 udev_list_node_append(&worker->node, &worker_list);
411 log_debug("seq %llu forked new worker [%u]", udev_device_get_seqnum(event->dev), pid);
416 static void event_run(struct event *event)
418 struct udev_list_node *loop;
420 udev_list_node_foreach(loop, &worker_list) {
421 struct worker *worker = node_to_worker(loop);
424 if (worker->state != WORKER_IDLE)
427 count = udev_monitor_send_device(monitor, worker->monitor, event->dev);
429 log_error("worker [%u] did not accept message %zi (%m), kill it", worker->pid, count);
430 kill(worker->pid, SIGKILL);
431 worker->state = WORKER_KILLED;
435 worker->event = event;
436 worker->state = WORKER_RUNNING;
437 worker->event_start_usec = now(CLOCK_MONOTONIC);
438 event->state = EVENT_RUNNING;
442 if (children >= children_max) {
443 if (children_max > 1)
444 log_debug("maximum number (%i) of children reached", children);
448 /* start new worker and pass initial device */
452 static int event_queue_insert(struct udev_device *dev)
456 event = new0(struct event, 1);
460 event->udev = udev_device_get_udev(dev);
462 event->seqnum = udev_device_get_seqnum(dev);
463 event->devpath = udev_device_get_devpath(dev);
464 event->devpath_len = strlen(event->devpath);
465 event->devpath_old = udev_device_get_devpath_old(dev);
466 event->devnum = udev_device_get_devnum(dev);
467 event->is_block = streq("block", udev_device_get_subsystem(dev));
468 event->ifindex = udev_device_get_ifindex(dev);
470 if (streq(udev_device_get_subsystem(dev), "firmware"))
471 event->nodelay = true;
474 log_debug("seq %llu queued, '%s' '%s'", udev_device_get_seqnum(dev),
475 udev_device_get_action(dev), udev_device_get_subsystem(dev));
477 event->state = EVENT_QUEUED;
478 udev_list_node_append(&event->node, &event_list);
482 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)
500 struct udev_list_node *loop;
503 /* check if queue contains events we depend on */
504 udev_list_node_foreach(loop, &event_list) {
505 struct event *loop_event = node_to_event(loop);
507 /* we already found a later event, earlier can not block us, no need to check again */
508 if (loop_event->seqnum < event->delaying_seqnum)
511 /* event we checked earlier still exists, no need to check again */
512 if (loop_event->seqnum == event->delaying_seqnum)
515 /* found ourself, no later event can block us */
516 if (loop_event->seqnum >= event->seqnum)
519 /* check major/minor */
520 if (major(event->devnum) != 0 && event->devnum == loop_event->devnum && event->is_block == loop_event->is_block)
523 /* check network device ifindex */
524 if (event->ifindex != 0 && event->ifindex == loop_event->ifindex)
527 /* check our old name */
528 if (event->devpath_old != NULL && streq(loop_event->devpath, event->devpath_old)) {
529 event->delaying_seqnum = loop_event->seqnum;
533 /* compare devpath */
534 common = MIN(loop_event->devpath_len, event->devpath_len);
536 /* one devpath is contained in the other? */
537 if (memcmp(loop_event->devpath, event->devpath, common) != 0)
540 /* identical device event found */
541 if (loop_event->devpath_len == event->devpath_len) {
542 /* devices names might have changed/swapped in the meantime */
543 if (major(event->devnum) != 0 && (event->devnum != loop_event->devnum || event->is_block != loop_event->is_block))
545 if (event->ifindex != 0 && event->ifindex != loop_event->ifindex)
547 event->delaying_seqnum = loop_event->seqnum;
552 /* allow to bypass the dependency tracking */
557 /* parent device event found */
558 if (event->devpath[common] == '/') {
559 event->delaying_seqnum = loop_event->seqnum;
563 /* child device event found */
564 if (loop_event->devpath[common] == '/') {
565 event->delaying_seqnum = loop_event->seqnum;
569 /* no matching device */
576 static void event_queue_start(struct udev *udev)
578 struct udev_list_node *loop;
580 udev_list_node_foreach(loop, &event_list) {
581 struct event *event = node_to_event(loop);
583 if (event->state != EVENT_QUEUED)
586 /* do not start event if parent or child event is still running */
587 if (is_devpath_busy(event))
594 static void event_queue_cleanup(struct udev *udev, enum event_state match_type)
596 struct udev_list_node *loop, *tmp;
598 udev_list_node_foreach_safe(loop, tmp, &event_list) {
599 struct event *event = node_to_event(loop);
601 if (match_type != EVENT_UNDEF && match_type != event->state)
604 event_queue_delete(event);
608 static void worker_returned(int fd_worker)
611 struct worker_message msg;
613 struct udev_list_node *loop;
615 size = recv(fd_worker, &msg, sizeof(struct worker_message), MSG_DONTWAIT);
616 if (size != sizeof(struct worker_message))
619 /* lookup worker who sent the signal */
620 udev_list_node_foreach(loop, &worker_list) {
621 struct worker *worker = node_to_worker(loop);
623 if (worker->pid != msg.pid)
626 /* worker returned */
628 worker->event->exitcode = msg.exitcode;
629 event_queue_delete(worker->event);
630 worker->event = NULL;
632 if (worker->state != WORKER_KILLED)
633 worker->state = WORKER_IDLE;
634 worker_unref(worker);
640 /* receive the udevd message from userspace */
641 static struct udev_ctrl_connection *handle_ctrl_msg(struct udev_ctrl *uctrl)
643 struct udev *udev = udev_ctrl_get_udev(uctrl);
644 struct udev_ctrl_connection *ctrl_conn;
645 struct udev_ctrl_msg *ctrl_msg = NULL;
649 ctrl_conn = udev_ctrl_get_connection(uctrl);
650 if (ctrl_conn == NULL)
653 ctrl_msg = udev_ctrl_receive_msg(ctrl_conn);
654 if (ctrl_msg == NULL)
657 i = udev_ctrl_get_set_log_level(ctrl_msg);
659 log_debug("udevd message (SET_LOG_LEVEL) received, log_priority=%i", i);
660 log_set_max_level(i);
661 udev_set_log_priority(udev, i);
665 if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
666 log_debug("udevd message (STOP_EXEC_QUEUE) received");
667 stop_exec_queue = true;
670 if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
671 log_debug("udevd message (START_EXEC_QUEUE) received");
672 stop_exec_queue = false;
675 if (udev_ctrl_get_reload(ctrl_msg) > 0) {
676 log_debug("udevd message (RELOAD) received");
680 str = udev_ctrl_get_set_env(ctrl_msg);
688 val = strchr(key, '=');
692 if (val[0] == '\0') {
693 log_debug("udevd message (ENV) received, unset '%s'", key);
694 udev_add_property(udev, key, NULL);
696 log_debug("udevd message (ENV) received, set '%s=%s'", key, val);
697 udev_add_property(udev, key, val);
700 log_error("wrong key format '%s'", key);
707 i = udev_ctrl_get_set_children_max(ctrl_msg);
709 log_debug("udevd message (SET_MAX_CHILDREN) received, children_max=%i", i);
713 if (udev_ctrl_get_ping(ctrl_msg) > 0)
714 log_debug("udevd message (SYNC) received");
716 if (udev_ctrl_get_exit(ctrl_msg) > 0) {
717 log_debug("udevd message (EXIT) received");
719 /* keep reference to block the client until we exit */
720 udev_ctrl_connection_ref(ctrl_conn);
723 udev_ctrl_msg_unref(ctrl_msg);
724 return udev_ctrl_connection_unref(ctrl_conn);
727 /* read inotify messages */
728 static int handle_inotify(struct udev *udev)
732 struct inotify_event *ev;
734 if ((ioctl(fd_inotify, FIONREAD, &nbytes) < 0) || (nbytes <= 0))
737 buf = malloc(nbytes);
739 log_error("error getting buffer for inotify");
743 nbytes = read(fd_inotify, buf, nbytes);
745 for (pos = 0; pos < nbytes; pos += sizeof(struct inotify_event) + ev->len) {
746 struct udev_device *dev;
748 ev = (struct inotify_event *)(buf + pos);
749 dev = udev_watch_lookup(udev, ev->wd);
751 log_debug("inotify event: %x for %s", ev->mask, udev_device_get_devnode(dev));
752 if (ev->mask & IN_CLOSE_WRITE) {
753 char filename[UTIL_PATH_SIZE];
756 log_debug("device %s closed, synthesising 'change'", udev_device_get_devnode(dev));
757 strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
758 fd = open(filename, O_WRONLY|O_CLOEXEC);
760 if (write(fd, "change", 6) < 0)
761 log_debug("error writing uevent: %m");
765 if (ev->mask & IN_IGNORED)
766 udev_watch_end(udev, dev);
768 udev_device_unref(dev);
777 static void handle_signal(struct udev *udev, int signo)
788 struct udev_list_node *loop, *tmp;
790 pid = waitpid(-1, &status, WNOHANG);
794 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
795 struct worker *worker = node_to_worker(loop);
797 if (worker->pid != pid)
799 log_debug("worker [%u] exit", pid);
801 if (WIFEXITED(status)) {
802 if (WEXITSTATUS(status) != 0)
803 log_error("worker [%u] exit with return code %i",
804 pid, WEXITSTATUS(status));
805 } else if (WIFSIGNALED(status)) {
806 log_error("worker [%u] terminated by signal %i (%s)",
807 pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
808 } else if (WIFSTOPPED(status)) {
809 log_error("worker [%u] stopped", pid);
810 } else if (WIFCONTINUED(status)) {
811 log_error("worker [%u] continued", pid);
813 log_error("worker [%u] exit with status 0x%04x", pid, status);
816 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
818 log_error("worker [%u] failed while handling '%s'",
819 pid, worker->event->devpath);
820 worker->event->exitcode = -32;
821 event_queue_delete(worker->event);
823 /* drop reference taken for state 'running' */
824 worker_unref(worker);
827 worker_unref(worker);
838 static int systemd_fds(struct udev *udev, int *rctrl, int *rnetlink)
840 int ctrl = -1, netlink = -1;
843 n = sd_listen_fds(true);
847 for (fd = SD_LISTEN_FDS_START; fd < n + SD_LISTEN_FDS_START; fd++) {
848 if (sd_is_socket(fd, AF_LOCAL, SOCK_SEQPACKET, -1)) {
855 if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1)) {
865 if (ctrl < 0 || netlink < 0)
868 log_debug("ctrl=%i netlink=%i", ctrl, netlink);
875 * read the kernel commandline, in case we need to get into debug mode
876 * udev.log-priority=<level> syslog priority
877 * udev.children-max=<number of workers> events are fully serialized if set to 1
878 * udev.exec-delay=<number of seconds> delay execution of every executed program
880 static void kernel_cmdline_options(struct udev *udev)
882 _cleanup_free_ char *line = NULL;
887 r = proc_cmdline(&line);
889 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
893 FOREACH_WORD_QUOTED(w, l, line, state) {
900 /* accept the same options for the initrd, prefixed with "rd." */
901 if (in_initrd() && startswith(s, "rd."))
906 if (startswith(opt, "udev.log-priority=")) {
909 prio = util_log_priority(opt + 18);
910 log_set_max_level(prio);
911 udev_set_log_priority(udev, prio);
912 } else if (startswith(opt, "udev.children-max=")) {
913 children_max = strtoul(opt + 18, NULL, 0);
914 } else if (startswith(opt, "udev.exec-delay=")) {
915 exec_delay = strtoul(opt + 16, NULL, 0);
922 int main(int argc, char *argv[])
926 int daemonize = false;
927 int resolve_names = 1;
928 static const struct option options[] = {
929 { "daemon", no_argument, NULL, 'd' },
930 { "debug", no_argument, NULL, 'D' },
931 { "children-max", required_argument, NULL, 'c' },
932 { "exec-delay", required_argument, NULL, 'e' },
933 { "resolve-names", required_argument, NULL, 'N' },
934 { "help", no_argument, NULL, 'h' },
935 { "version", no_argument, NULL, 'V' },
941 struct epoll_event ep_ctrl, ep_inotify, ep_signal, ep_netlink, ep_worker;
942 struct udev_ctrl_connection *ctrl_conn = NULL;
949 log_set_target(LOG_TARGET_AUTO);
950 log_parse_environment();
953 udev_set_log_fn(udev, udev_main_log);
954 log_set_max_level(udev_get_log_priority(udev));
956 log_debug("version %s", VERSION);
962 option = getopt_long(argc, argv, "c:de:DtN:hV", options, NULL);
971 children_max = strtoul(optarg, NULL, 0);
974 exec_delay = strtoul(optarg, NULL, 0);
978 log_set_max_level(LOG_DEBUG);
979 udev_set_log_priority(udev, LOG_DEBUG);
982 if (streq(optarg, "early")) {
984 } else if (streq(optarg, "late")) {
986 } else if (streq(optarg, "never")) {
989 fprintf(stderr, "resolve-names must be early, late or never\n");
990 log_error("resolve-names must be early, late or never");
995 printf("Usage: udevd OPTIONS\n"
998 " --children-max=<maximum number of workers>\n"
999 " --exec-delay=<seconds to wait before executing RUN=>\n"
1000 " --resolve-names=early|late|never\n"
1006 printf("%s\n", VERSION);
1013 kernel_cmdline_options(udev);
1015 if (getuid() != 0) {
1016 fprintf(stderr, "root privileges required\n");
1017 log_error("root privileges required");
1021 /* set umask before creating any file/directory */
1025 mkdir("/run/udev", 0755);
1029 /* before opening new files, make sure std{in,out,err} fds are in a sane state */
1033 fd = open("/dev/null", O_RDWR);
1035 if (write(STDOUT_FILENO, 0, 0) < 0)
1036 dup2(fd, STDOUT_FILENO);
1037 if (write(STDERR_FILENO, 0, 0) < 0)
1038 dup2(fd, STDERR_FILENO);
1039 if (fd > STDERR_FILENO)
1042 fprintf(stderr, "cannot open /dev/null\n");
1043 log_error("cannot open /dev/null");
1047 if (systemd_fds(udev, &fd_ctrl, &fd_netlink) >= 0) {
1048 /* get control and netlink socket from systemd */
1049 udev_ctrl = udev_ctrl_new_from_fd(udev, fd_ctrl);
1050 if (udev_ctrl == NULL) {
1051 log_error("error taking over udev control socket");
1056 monitor = udev_monitor_new_from_netlink_fd(udev, "kernel", fd_netlink);
1057 if (monitor == NULL) {
1058 log_error("error taking over netlink socket");
1063 /* get our own cgroup, we regularly kill everything udev has left behind */
1064 if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &udev_cgroup) < 0)
1067 /* open control and netlink socket */
1068 udev_ctrl = udev_ctrl_new(udev);
1069 if (udev_ctrl == NULL) {
1070 fprintf(stderr, "error initializing udev control socket");
1071 log_error("error initializing udev control socket");
1075 fd_ctrl = udev_ctrl_get_fd(udev_ctrl);
1077 monitor = udev_monitor_new_from_netlink(udev, "kernel");
1078 if (monitor == NULL) {
1079 fprintf(stderr, "error initializing netlink socket\n");
1080 log_error("error initializing netlink socket");
1084 fd_netlink = udev_monitor_get_fd(monitor);
1087 if (udev_monitor_enable_receiving(monitor) < 0) {
1088 fprintf(stderr, "error binding netlink socket\n");
1089 log_error("error binding netlink socket");
1094 if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
1095 fprintf(stderr, "error binding udev control socket\n");
1096 log_error("error binding udev control socket");
1101 udev_monitor_set_receive_buffer_size(monitor, 128 * 1024 * 1024);
1111 log_error("fork of daemon failed: %m");
1116 goto exit_daemonize;
1121 write_string_file("/proc/self/oom_score_adj", "-1000");
1123 sd_notify(1, "READY=1");
1126 print_kmsg("starting version " VERSION "\n");
1131 fd = open("/dev/null", O_RDWR);
1133 dup2(fd, STDIN_FILENO);
1134 dup2(fd, STDOUT_FILENO);
1135 dup2(fd, STDERR_FILENO);
1140 fd_inotify = udev_watch_init(udev);
1141 if (fd_inotify < 0) {
1142 fprintf(stderr, "error initializing inotify\n");
1143 log_error("error initializing inotify");
1147 udev_watch_restore(udev);
1149 /* block and listen to all signals on signalfd */
1151 sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
1152 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
1153 if (fd_signal < 0) {
1154 fprintf(stderr, "error creating signalfd\n");
1155 log_error("error creating signalfd");
1160 /* unnamed socket from workers to the main daemon */
1161 if (socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, worker_watch) < 0) {
1162 fprintf(stderr, "error creating socketpair\n");
1163 log_error("error creating socketpair");
1167 fd_worker = worker_watch[READ_END];
1169 udev_builtin_init(udev);
1171 rules = udev_rules_new(udev, resolve_names);
1172 if (rules == NULL) {
1173 log_error("error reading rules");
1177 memzero(&ep_ctrl, sizeof(struct epoll_event));
1178 ep_ctrl.events = EPOLLIN;
1179 ep_ctrl.data.fd = fd_ctrl;
1181 memzero(&ep_inotify, sizeof(struct epoll_event));
1182 ep_inotify.events = EPOLLIN;
1183 ep_inotify.data.fd = fd_inotify;
1185 memzero(&ep_signal, sizeof(struct epoll_event));
1186 ep_signal.events = EPOLLIN;
1187 ep_signal.data.fd = fd_signal;
1189 memzero(&ep_netlink, sizeof(struct epoll_event));
1190 ep_netlink.events = EPOLLIN;
1191 ep_netlink.data.fd = fd_netlink;
1193 memzero(&ep_worker, sizeof(struct epoll_event));
1194 ep_worker.events = EPOLLIN;
1195 ep_worker.data.fd = fd_worker;
1197 fd_ep = epoll_create1(EPOLL_CLOEXEC);
1199 log_error("error creating epoll fd: %m");
1202 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_ctrl, &ep_ctrl) < 0 ||
1203 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_inotify, &ep_inotify) < 0 ||
1204 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
1205 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_netlink, &ep_netlink) < 0 ||
1206 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_worker, &ep_worker) < 0) {
1207 log_error("fail to add fds to epoll: %m");
1211 if (children_max <= 0) {
1216 if (sched_getaffinity(0, sizeof (cpu_set), &cpu_set) == 0) {
1217 children_max += CPU_COUNT(&cpu_set) * 2;
1220 log_debug("set children_max to %u", children_max);
1222 rc = udev_rules_apply_static_dev_perms(rules);
1224 log_error("failed to apply permissions on static device nodes - %s", strerror(-rc));
1226 udev_list_node_init(&event_list);
1227 udev_list_node_init(&worker_list);
1230 static usec_t last_usec;
1231 struct epoll_event ev[8];
1234 bool is_worker, is_signal, is_inotify, is_netlink, is_ctrl;
1238 /* close sources of new events and discard buffered events */
1240 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_ctrl, NULL);
1243 if (monitor != NULL) {
1244 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_netlink, NULL);
1245 udev_monitor_unref(monitor);
1248 if (fd_inotify >= 0) {
1249 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_inotify, NULL);
1254 /* discard queued events and kill workers */
1255 event_queue_cleanup(udev, EVENT_QUEUED);
1258 /* exit after all has cleaned up */
1259 if (udev_list_node_is_empty(&event_list) && children == 0)
1262 /* timeout at exit for workers to finish */
1263 timeout = 30 * MSEC_PER_SEC;
1264 } else if (udev_list_node_is_empty(&event_list) && children == 0) {
1268 /* cleanup possible left-over processes in our cgroup */
1270 cg_kill(SYSTEMD_CGROUP_CONTROLLER, udev_cgroup, SIGKILL, false, true, NULL);
1272 /* kill idle or hanging workers */
1273 timeout = 3 * MSEC_PER_SEC;
1276 /* tell settle that we are busy or idle */
1277 if (!udev_list_node_is_empty(&event_list)) {
1280 fd = open("/run/udev/queue", O_WRONLY|O_CREAT|O_CLOEXEC|O_TRUNC|O_NOFOLLOW, 0444);
1284 unlink("/run/udev/queue");
1287 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
1292 struct udev_list_node *loop;
1296 log_error("timeout, giving up waiting for workers to finish");
1300 /* kill idle workers */
1301 if (udev_list_node_is_empty(&event_list)) {
1302 log_debug("cleanup idle workers");
1306 /* check for hanging events */
1307 udev_list_node_foreach(loop, &worker_list) {
1308 struct worker *worker = node_to_worker(loop);
1310 if (worker->state != WORKER_RUNNING)
1313 if ((now(CLOCK_MONOTONIC) - worker->event_start_usec) > 30 * USEC_PER_SEC) {
1314 log_error("worker [%u] %s timeout; kill it", worker->pid,
1315 worker->event ? worker->event->devpath : "<idle>");
1316 kill(worker->pid, SIGKILL);
1317 worker->state = WORKER_KILLED;
1319 /* drop reference taken for state 'running' */
1320 worker_unref(worker);
1321 if (worker->event) {
1322 log_error("seq %llu '%s' killed", udev_device_get_seqnum(worker->event->dev), worker->event->devpath);
1323 worker->event->exitcode = -64;
1324 event_queue_delete(worker->event);
1325 worker->event = NULL;
1332 is_worker = is_signal = is_inotify = is_netlink = is_ctrl = false;
1333 for (i = 0; i < fdcount; i++) {
1334 if (ev[i].data.fd == fd_worker && ev[i].events & EPOLLIN)
1336 else if (ev[i].data.fd == fd_netlink && ev[i].events & EPOLLIN)
1338 else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN)
1340 else if (ev[i].data.fd == fd_inotify && ev[i].events & EPOLLIN)
1342 else if (ev[i].data.fd == fd_ctrl && ev[i].events & EPOLLIN)
1346 /* check for changed config, every 3 seconds at most */
1347 if ((now(CLOCK_MONOTONIC) - last_usec) > 3 * USEC_PER_SEC) {
1348 if (udev_rules_check_timestamp(rules))
1350 if (udev_builtin_validate(udev))
1353 last_usec = now(CLOCK_MONOTONIC);
1356 /* reload requested, HUP signal received, rules changed, builtin changed */
1359 rules = udev_rules_unref(rules);
1360 udev_builtin_exit(udev);
1364 /* event has finished */
1366 worker_returned(fd_worker);
1369 struct udev_device *dev;
1371 dev = udev_monitor_receive_device(monitor);
1373 udev_device_set_usec_initialized(dev, now(CLOCK_MONOTONIC));
1374 if (event_queue_insert(dev) < 0)
1375 udev_device_unref(dev);
1379 /* start new events */
1380 if (!udev_list_node_is_empty(&event_list) && !udev_exit && !stop_exec_queue) {
1381 udev_builtin_init(udev);
1383 rules = udev_rules_new(udev, resolve_names);
1385 event_queue_start(udev);
1389 struct signalfd_siginfo fdsi;
1392 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
1393 if (size == sizeof(struct signalfd_siginfo))
1394 handle_signal(udev, fdsi.ssi_signo);
1397 /* we are shutting down, the events below are not handled anymore */
1401 /* device node watch */
1403 handle_inotify(udev);
1406 * This needs to be after the inotify handling, to make sure,
1407 * that the ping is send back after the possibly generated
1408 * "change" events by the inotify device node watch.
1410 * A single time we may receive a client connection which we need to
1411 * keep open to block the client. It will be closed right before we
1415 ctrl_conn = handle_ctrl_msg(udev_ctrl);
1420 udev_ctrl_cleanup(udev_ctrl);
1421 unlink("/run/udev/queue");
1425 worker_list_cleanup(udev);
1426 event_queue_cleanup(udev, EVENT_UNDEF);
1427 udev_rules_unref(rules);
1428 udev_builtin_exit(udev);
1431 if (worker_watch[READ_END] >= 0)
1432 close(worker_watch[READ_END]);
1433 if (worker_watch[WRITE_END] >= 0)
1434 close(worker_watch[WRITE_END]);
1435 udev_monitor_unref(monitor);
1436 udev_ctrl_connection_unref(ctrl_conn);
1437 udev_ctrl_unref(udev_ctrl);