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/>.
35 #include <sys/prctl.h>
36 #include <sys/socket.h>
38 #include <sys/signalfd.h>
39 #include <sys/epoll.h>
43 #include <sys/ioctl.h>
44 #include <sys/inotify.h>
45 #include <sys/utsname.h>
48 #include "sd-daemon.h"
49 #include "cgroup-util.h"
50 #include "dev-setup.h"
55 void udev_main_log(struct udev *udev, int priority,
56 const char *file, int line, const char *fn,
57 const char *format, va_list args)
59 log_metav(priority, file, line, fn, format, args);
62 static struct udev_rules *rules;
63 static struct udev_queue_export *udev_queue_export;
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);
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;
101 #ifdef ENABLE_FIRMWARE
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, bool export)
144 udev_list_node_remove(&event->node);
147 udev_queue_export_device_finished(udev_queue_export, event->dev);
148 log_debug("seq %llu done with %i\n", udev_device_get_seqnum(event->dev), event->exitcode);
150 udev_device_unref(event->dev);
154 static struct worker *worker_ref(struct worker *worker)
160 static void worker_cleanup(struct worker *worker)
162 udev_list_node_remove(&worker->node);
163 udev_monitor_unref(worker->monitor);
168 static void worker_unref(struct worker *worker)
171 if (worker->refcount > 0)
173 log_debug("worker [%u] cleaned up\n", worker->pid);
174 worker_cleanup(worker);
177 static void worker_list_cleanup(struct udev *udev)
179 struct udev_list_node *loop, *tmp;
181 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
182 struct worker *worker = node_to_worker(loop);
184 worker_cleanup(worker);
188 static void worker_new(struct event *event)
190 struct udev *udev = event->udev;
191 struct worker *worker;
192 struct udev_monitor *worker_monitor;
195 /* listen for new events */
196 worker_monitor = udev_monitor_new_from_netlink(udev, NULL);
197 if (worker_monitor == NULL)
199 /* allow the main daemon netlink address to send devices to the worker */
200 udev_monitor_allow_unicast_sender(worker_monitor, monitor);
201 udev_monitor_enable_receiving(worker_monitor);
203 worker = calloc(1, sizeof(struct worker));
204 if (worker == NULL) {
205 udev_monitor_unref(worker_monitor);
208 /* worker + event reference */
209 worker->refcount = 2;
215 struct udev_device *dev = NULL;
217 struct epoll_event ep_signal, ep_monitor;
219 int rc = EXIT_SUCCESS;
221 /* take initial device from queue */
226 worker_list_cleanup(udev);
227 event_queue_cleanup(udev, EVENT_UNDEF);
228 udev_queue_export_unref(udev_queue_export);
229 udev_monitor_unref(monitor);
230 udev_ctrl_unref(udev_ctrl);
233 close(worker_watch[READ_END]);
236 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
238 log_error("error creating signalfd %m\n");
243 fd_ep = epoll_create1(EPOLL_CLOEXEC);
245 log_error("error creating epoll fd: %m\n");
250 memset(&ep_signal, 0, sizeof(struct epoll_event));
251 ep_signal.events = EPOLLIN;
252 ep_signal.data.fd = fd_signal;
254 fd_monitor = udev_monitor_get_fd(worker_monitor);
255 memset(&ep_monitor, 0, sizeof(struct epoll_event));
256 ep_monitor.events = EPOLLIN;
257 ep_monitor.data.fd = fd_monitor;
259 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
260 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_monitor, &ep_monitor) < 0) {
261 log_error("fail to add fds to epoll: %m\n");
266 /* request TERM signal if parent exits */
267 prctl(PR_SET_PDEATHSIG, SIGTERM);
269 /* reset OOM score, we only protect the main daemon */
270 write_one_line_file("/proc/self/oom_score_adj", "0");
273 struct udev_event *udev_event;
274 struct worker_message msg;
277 log_debug("seq %llu running\n", udev_device_get_seqnum(dev));
278 udev_event = udev_event_new(dev);
279 if (udev_event == NULL) {
284 /* needed for SIGCHLD/SIGTERM in spawn() */
285 udev_event->fd_signal = fd_signal;
288 udev_event->exec_delay = exec_delay;
290 /* apply rules, create node, symlinks */
291 err = udev_event_execute_rules(udev_event, rules, &sigmask_orig);
294 udev_event_execute_run(udev_event, &sigmask_orig);
296 /* apply/restore inotify watch */
297 if (err == 0 && udev_event->inotify_watch) {
298 udev_watch_begin(udev, dev);
299 udev_device_update_db(dev);
302 /* send processed event back to libudev listeners */
303 udev_monitor_send_device(worker_monitor, NULL, dev);
305 /* send udevd the result of the event execution */
306 memset(&msg, 0, sizeof(struct worker_message));
310 send(worker_watch[WRITE_END], &msg, sizeof(struct worker_message), 0);
312 log_debug("seq %llu processed with %i\n", udev_device_get_seqnum(dev), err);
314 udev_device_unref(dev);
317 if (udev_event->sigterm) {
318 udev_event_unref(udev_event);
322 udev_event_unref(udev_event);
324 /* wait for more device messages from main udevd, or term signal */
325 while (dev == NULL) {
326 struct epoll_event ev[4];
330 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), -1);
334 log_error("failed to poll: %m\n");
338 for (i = 0; i < fdcount; i++) {
339 if (ev[i].data.fd == fd_monitor && ev[i].events & EPOLLIN) {
340 dev = udev_monitor_receive_device(worker_monitor);
342 } else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN) {
343 struct signalfd_siginfo fdsi;
346 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
347 if (size != sizeof(struct signalfd_siginfo))
349 switch (fdsi.ssi_signo) {
358 udev_device_unref(dev);
364 close(worker_watch[WRITE_END]);
365 udev_rules_unref(rules);
366 udev_builtin_exit(udev);
367 udev_monitor_unref(worker_monitor);
373 udev_monitor_unref(worker_monitor);
374 event->state = EVENT_QUEUED;
376 log_error("fork of child failed: %m\n");
379 /* close monitor, but keep address around */
380 udev_monitor_disconnect(worker_monitor);
381 worker->monitor = worker_monitor;
383 worker->state = WORKER_RUNNING;
384 worker->event_start_usec = now(CLOCK_MONOTONIC);
385 worker->event = event;
386 event->state = EVENT_RUNNING;
387 udev_list_node_append(&worker->node, &worker_list);
389 log_debug("seq %llu forked new worker [%u]\n", udev_device_get_seqnum(event->dev), pid);
394 static void event_run(struct event *event)
396 struct udev_list_node *loop;
398 udev_list_node_foreach(loop, &worker_list) {
399 struct worker *worker = node_to_worker(loop);
402 if (worker->state != WORKER_IDLE)
405 count = udev_monitor_send_device(monitor, worker->monitor, event->dev);
407 log_error("worker [%u] did not accept message %zi (%m), kill it\n", worker->pid, count);
408 kill(worker->pid, SIGKILL);
409 worker->state = WORKER_KILLED;
413 worker->event = event;
414 worker->state = WORKER_RUNNING;
415 worker->event_start_usec = now(CLOCK_MONOTONIC);
416 event->state = EVENT_RUNNING;
420 if (children >= children_max) {
421 if (children_max > 1)
422 log_debug("maximum number (%i) of children reached\n", children);
426 /* start new worker and pass initial device */
430 static int event_queue_insert(struct udev_device *dev)
434 event = calloc(1, sizeof(struct event));
438 event->udev = udev_device_get_udev(dev);
440 event->seqnum = udev_device_get_seqnum(dev);
441 event->devpath = udev_device_get_devpath(dev);
442 event->devpath_len = strlen(event->devpath);
443 event->devpath_old = udev_device_get_devpath_old(dev);
444 event->devnum = udev_device_get_devnum(dev);
445 event->is_block = streq("block", udev_device_get_subsystem(dev));
446 event->ifindex = udev_device_get_ifindex(dev);
447 #ifdef ENABLE_FIRMWARE
448 if (streq(udev_device_get_subsystem(dev), "firmware"))
449 event->nodelay = true;
452 udev_queue_export_device_queued(udev_queue_export, dev);
453 log_debug("seq %llu queued, '%s' '%s'\n", udev_device_get_seqnum(dev),
454 udev_device_get_action(dev), udev_device_get_subsystem(dev));
456 event->state = EVENT_QUEUED;
457 udev_list_node_append(&event->node, &event_list);
461 static void worker_kill(struct udev *udev)
463 struct udev_list_node *loop;
465 udev_list_node_foreach(loop, &worker_list) {
466 struct worker *worker = node_to_worker(loop);
468 if (worker->state == WORKER_KILLED)
471 worker->state = WORKER_KILLED;
472 kill(worker->pid, SIGTERM);
476 /* lookup event for identical, parent, child device */
477 static bool is_devpath_busy(struct event *event)
479 struct udev_list_node *loop;
482 /* check if queue contains events we depend on */
483 udev_list_node_foreach(loop, &event_list) {
484 struct event *loop_event = node_to_event(loop);
486 /* we already found a later event, earlier can not block us, no need to check again */
487 if (loop_event->seqnum < event->delaying_seqnum)
490 /* event we checked earlier still exists, no need to check again */
491 if (loop_event->seqnum == event->delaying_seqnum)
494 /* found ourself, no later event can block us */
495 if (loop_event->seqnum >= event->seqnum)
498 /* check major/minor */
499 if (major(event->devnum) != 0 && event->devnum == loop_event->devnum && event->is_block == loop_event->is_block)
502 /* check network device ifindex */
503 if (event->ifindex != 0 && event->ifindex == loop_event->ifindex)
506 /* check our old name */
507 if (event->devpath_old != NULL && streq(loop_event->devpath, event->devpath_old)) {
508 event->delaying_seqnum = loop_event->seqnum;
512 /* compare devpath */
513 common = MIN(loop_event->devpath_len, event->devpath_len);
515 /* one devpath is contained in the other? */
516 if (memcmp(loop_event->devpath, event->devpath, common) != 0)
519 /* identical device event found */
520 if (loop_event->devpath_len == event->devpath_len) {
521 /* devices names might have changed/swapped in the meantime */
522 if (major(event->devnum) != 0 && (event->devnum != loop_event->devnum || event->is_block != loop_event->is_block))
524 if (event->ifindex != 0 && event->ifindex != loop_event->ifindex)
526 event->delaying_seqnum = loop_event->seqnum;
530 #ifdef ENABLE_FIRMWARE
531 /* allow to bypass the dependency tracking */
536 /* parent device event found */
537 if (event->devpath[common] == '/') {
538 event->delaying_seqnum = loop_event->seqnum;
542 /* child device event found */
543 if (loop_event->devpath[common] == '/') {
544 event->delaying_seqnum = loop_event->seqnum;
548 /* no matching device */
555 static void event_queue_start(struct udev *udev)
557 struct udev_list_node *loop;
559 udev_list_node_foreach(loop, &event_list) {
560 struct event *event = node_to_event(loop);
562 if (event->state != EVENT_QUEUED)
565 /* do not start event if parent or child event is still running */
566 if (is_devpath_busy(event))
573 static void event_queue_cleanup(struct udev *udev, enum event_state match_type)
575 struct udev_list_node *loop, *tmp;
577 udev_list_node_foreach_safe(loop, tmp, &event_list) {
578 struct event *event = node_to_event(loop);
580 if (match_type != EVENT_UNDEF && match_type != event->state)
583 event_queue_delete(event, false);
587 static void worker_returned(int fd_worker)
590 struct worker_message msg;
592 struct udev_list_node *loop;
594 size = recv(fd_worker, &msg, sizeof(struct worker_message), MSG_DONTWAIT);
595 if (size != sizeof(struct worker_message))
598 /* lookup worker who sent the signal */
599 udev_list_node_foreach(loop, &worker_list) {
600 struct worker *worker = node_to_worker(loop);
602 if (worker->pid != msg.pid)
605 /* worker returned */
607 worker->event->exitcode = msg.exitcode;
608 event_queue_delete(worker->event, true);
609 worker->event = NULL;
611 if (worker->state != WORKER_KILLED)
612 worker->state = WORKER_IDLE;
613 worker_unref(worker);
619 /* receive the udevd message from userspace */
620 static struct udev_ctrl_connection *handle_ctrl_msg(struct udev_ctrl *uctrl)
622 struct udev *udev = udev_ctrl_get_udev(uctrl);
623 struct udev_ctrl_connection *ctrl_conn;
624 struct udev_ctrl_msg *ctrl_msg = NULL;
628 ctrl_conn = udev_ctrl_get_connection(uctrl);
629 if (ctrl_conn == NULL)
632 ctrl_msg = udev_ctrl_receive_msg(ctrl_conn);
633 if (ctrl_msg == NULL)
636 i = udev_ctrl_get_set_log_level(ctrl_msg);
638 log_debug("udevd message (SET_LOG_PRIORITY) received, log_priority=%i\n", i);
639 log_set_max_level(i);
640 udev_set_log_priority(udev, i);
644 if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
645 log_debug("udevd message (STOP_EXEC_QUEUE) received\n");
646 stop_exec_queue = true;
649 if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
650 log_debug("udevd message (START_EXEC_QUEUE) received\n");
651 stop_exec_queue = false;
654 if (udev_ctrl_get_reload(ctrl_msg) > 0) {
655 log_debug("udevd message (RELOAD) received\n");
659 str = udev_ctrl_get_set_env(ctrl_msg);
667 val = strchr(key, '=');
671 if (val[0] == '\0') {
672 log_debug("udevd message (ENV) received, unset '%s'\n", key);
673 udev_add_property(udev, key, NULL);
675 log_debug("udevd message (ENV) received, set '%s=%s'\n", key, val);
676 udev_add_property(udev, key, val);
679 log_error("wrong key format '%s'\n", key);
686 i = udev_ctrl_get_set_children_max(ctrl_msg);
688 log_debug("udevd message (SET_MAX_CHILDREN) received, children_max=%i\n", i);
692 if (udev_ctrl_get_ping(ctrl_msg) > 0)
693 log_debug("udevd message (SYNC) received\n");
695 if (udev_ctrl_get_exit(ctrl_msg) > 0) {
696 log_debug("udevd message (EXIT) received\n");
698 /* keep reference to block the client until we exit */
699 udev_ctrl_connection_ref(ctrl_conn);
702 udev_ctrl_msg_unref(ctrl_msg);
703 return udev_ctrl_connection_unref(ctrl_conn);
706 /* read inotify messages */
707 static int handle_inotify(struct udev *udev)
711 struct inotify_event *ev;
713 if ((ioctl(fd_inotify, FIONREAD, &nbytes) < 0) || (nbytes <= 0))
716 buf = malloc(nbytes);
718 log_error("error getting buffer for inotify\n");
722 nbytes = read(fd_inotify, buf, nbytes);
724 for (pos = 0; pos < nbytes; pos += sizeof(struct inotify_event) + ev->len) {
725 struct udev_device *dev;
727 ev = (struct inotify_event *)(buf + pos);
728 dev = udev_watch_lookup(udev, ev->wd);
730 log_debug("inotify event: %x for %s\n", ev->mask, udev_device_get_devnode(dev));
731 if (ev->mask & IN_CLOSE_WRITE) {
732 char filename[UTIL_PATH_SIZE];
735 log_debug("device %s closed, synthesising 'change'\n", udev_device_get_devnode(dev));
736 strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
737 fd = open(filename, O_WRONLY);
739 if (write(fd, "change", 6) < 0)
740 log_debug("error writing uevent: %m\n");
744 if (ev->mask & IN_IGNORED)
745 udev_watch_end(udev, dev);
747 udev_device_unref(dev);
756 static void handle_signal(struct udev *udev, int signo)
767 struct udev_list_node *loop, *tmp;
769 pid = waitpid(-1, &status, WNOHANG);
773 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
774 struct worker *worker = node_to_worker(loop);
776 if (worker->pid != pid)
778 log_debug("worker [%u] exit\n", pid);
780 if (WIFEXITED(status)) {
781 if (WEXITSTATUS(status) != 0)
782 log_error("worker [%u] exit with return code %i\n", pid, WEXITSTATUS(status));
783 } else if (WIFSIGNALED(status)) {
784 log_error("worker [%u] terminated by signal %i (%s)\n",
785 pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
786 } else if (WIFSTOPPED(status)) {
787 log_error("worker [%u] stopped\n", pid);
788 } else if (WIFCONTINUED(status)) {
789 log_error("worker [%u] continued\n", pid);
791 log_error("worker [%u] exit with status 0x%04x\n", pid, status);
794 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
796 log_error("worker [%u] failed while handling '%s'\n",
797 pid, worker->event->devpath);
798 worker->event->exitcode = -32;
799 event_queue_delete(worker->event, true);
800 /* drop reference taken for state 'running' */
801 worker_unref(worker);
804 worker_unref(worker);
815 static void static_dev_create_from_modules(struct udev *udev)
817 struct utsname kernel;
818 char modules[UTIL_PATH_SIZE];
823 strscpyl(modules, sizeof(modules), ROOTPREFIX "/lib/modules/", kernel.release, "/modules.devname", NULL);
824 f = fopen(modules, "re");
828 while (fgets(buf, sizeof(buf), f) != NULL) {
836 char filename[UTIL_PATH_SIZE];
842 s = strchr(modname, ' ');
848 s = strchr(devname, ' ');
854 s = strchr(devno, ' ');
856 s = strchr(devno, '\n');
859 if (sscanf(devno, "%c%u:%u", &type, &maj, &min) != 3)
865 else if (type == 'b')
870 strscpyl(filename, sizeof(filename), "/dev/", devname, NULL);
871 mkdir_parents_label(filename, 0755);
872 label_context_set(filename, mode);
873 log_debug("mknod '%s' %c%u:%u\n", filename, type, maj, min);
874 if (mknod(filename, mode, makedev(maj, min)) < 0 && errno == EEXIST)
875 utimensat(AT_FDCWD, filename, NULL, 0);
876 label_context_clear();
882 static int mem_size_mb(void)
886 long int memsize = -1;
888 f = fopen("/proc/meminfo", "re");
892 while (fgets(buf, sizeof(buf), f) != NULL) {
895 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
896 memsize = value / 1024;
905 static int systemd_fds(struct udev *udev, int *rctrl, int *rnetlink)
907 int ctrl = -1, netlink = -1;
910 n = sd_listen_fds(true);
914 for (fd = SD_LISTEN_FDS_START; fd < n + SD_LISTEN_FDS_START; fd++) {
915 if (sd_is_socket(fd, AF_LOCAL, SOCK_SEQPACKET, -1)) {
922 if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1)) {
932 if (ctrl < 0 || netlink < 0)
935 log_debug("ctrl=%i netlink=%i\n", ctrl, netlink);
942 * read the kernel commandline, in case we need to get into debug mode
943 * udev.log-priority=<level> syslog priority
944 * udev.children-max=<number of workers> events are fully serialized if set to 1
945 * udev.exec-delay=<number of seconds> delay execution of every executed program
947 static void kernel_cmdline_options(struct udev *udev)
949 char *line, *w, *state;
952 if (read_one_line_file("/proc/cmdline", &line) < 0)
955 FOREACH_WORD_QUOTED(w, l, line, state) {
962 /* accept the same options for the initrd, prefixed with "rd." */
963 if (in_initrd() && startswith(s, "rd."))
968 if (startswith(opt, "udev.log-priority=")) {
971 prio = util_log_priority(opt + 18);
972 log_set_max_level(prio);
973 udev_set_log_priority(udev, prio);
974 } else if (startswith(opt, "udev.children-max=")) {
975 children_max = strtoul(opt + 18, NULL, 0);
976 } else if (startswith(opt, "udev.exec-delay=")) {
977 exec_delay = strtoul(opt + 16, NULL, 0);
986 int main(int argc, char *argv[])
990 int daemonize = false;
991 int resolve_names = 1;
992 static const struct option options[] = {
993 { "daemon", no_argument, NULL, 'd' },
994 { "debug", no_argument, NULL, 'D' },
995 { "children-max", required_argument, NULL, 'c' },
996 { "exec-delay", required_argument, NULL, 'e' },
997 { "resolve-names", required_argument, NULL, 'N' },
998 { "help", no_argument, NULL, 'h' },
999 { "version", no_argument, NULL, 'V' },
1003 int fd_netlink = -1;
1005 struct epoll_event ep_ctrl, ep_inotify, ep_signal, ep_netlink, ep_worker;
1006 struct udev_ctrl_connection *ctrl_conn = NULL;
1013 log_set_target(LOG_TARGET_AUTO);
1014 log_parse_environment();
1016 udev_set_log_fn(udev, udev_main_log);
1017 log_debug("version %s\n", VERSION);
1023 option = getopt_long(argc, argv, "c:de:DtN:hV", options, NULL);
1032 children_max = strtoul(optarg, NULL, 0);
1035 exec_delay = strtoul(optarg, NULL, 0);
1039 log_set_max_level(LOG_DEBUG);
1040 udev_set_log_priority(udev, LOG_DEBUG);
1043 if (streq(optarg, "early")) {
1045 } else if (streq(optarg, "late")) {
1047 } else if (streq(optarg, "never")) {
1050 fprintf(stderr, "resolve-names must be early, late or never\n");
1051 log_error("resolve-names must be early, late or never\n");
1056 printf("Usage: udevd OPTIONS\n"
1059 " --children-max=<maximum number of workers>\n"
1060 " --exec-delay=<seconds to wait before executing RUN=>\n"
1061 " --resolve-names=early|late|never\n"
1067 printf("%s\n", VERSION);
1074 kernel_cmdline_options(udev);
1076 if (getuid() != 0) {
1077 fprintf(stderr, "root privileges required\n");
1078 log_error("root privileges required\n");
1082 /* set umask before creating any file/directory */
1086 mkdir("/run/udev", 0755);
1089 static_dev_create_from_modules(udev);
1091 /* before opening new files, make sure std{in,out,err} fds are in a sane state */
1095 fd = open("/dev/null", O_RDWR);
1097 if (write(STDOUT_FILENO, 0, 0) < 0)
1098 dup2(fd, STDOUT_FILENO);
1099 if (write(STDERR_FILENO, 0, 0) < 0)
1100 dup2(fd, STDERR_FILENO);
1101 if (fd > STDERR_FILENO)
1104 fprintf(stderr, "cannot open /dev/null\n");
1105 log_error("cannot open /dev/null\n");
1109 if (systemd_fds(udev, &fd_ctrl, &fd_netlink) >= 0) {
1110 /* get control and netlink socket from systemd */
1111 udev_ctrl = udev_ctrl_new_from_fd(udev, fd_ctrl);
1112 if (udev_ctrl == NULL) {
1113 log_error("error taking over udev control socket");
1118 monitor = udev_monitor_new_from_netlink_fd(udev, "kernel", fd_netlink);
1119 if (monitor == NULL) {
1120 log_error("error taking over netlink socket\n");
1125 /* get our own cgroup, we regularly kill everything udev has left behind */
1126 if (cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 0, &udev_cgroup) < 0)
1129 /* open control and netlink socket */
1130 udev_ctrl = udev_ctrl_new(udev);
1131 if (udev_ctrl == NULL) {
1132 fprintf(stderr, "error initializing udev control socket");
1133 log_error("error initializing udev control socket");
1137 fd_ctrl = udev_ctrl_get_fd(udev_ctrl);
1139 monitor = udev_monitor_new_from_netlink(udev, "kernel");
1140 if (monitor == NULL) {
1141 fprintf(stderr, "error initializing netlink socket\n");
1142 log_error("error initializing netlink socket\n");
1146 fd_netlink = udev_monitor_get_fd(monitor);
1149 if (udev_monitor_enable_receiving(monitor) < 0) {
1150 fprintf(stderr, "error binding netlink socket\n");
1151 log_error("error binding netlink socket\n");
1156 if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
1157 fprintf(stderr, "error binding udev control socket\n");
1158 log_error("error binding udev control socket\n");
1163 udev_monitor_set_receive_buffer_size(monitor, 128*1024*1024);
1165 /* create queue file before signalling 'ready', to make sure we block 'settle' */
1166 udev_queue_export = udev_queue_export_new(udev);
1167 if (udev_queue_export == NULL) {
1168 log_error("error creating queue file\n");
1180 log_error("fork of daemon failed: %m\n");
1185 goto exit_daemonize;
1190 write_one_line_file("/proc/self/oom_score_adj", "-1000");
1192 sd_notify(1, "READY=1");
1195 print_kmsg("starting version " VERSION "\n");
1200 fd = open("/dev/null", O_RDWR);
1202 dup2(fd, STDIN_FILENO);
1203 dup2(fd, STDOUT_FILENO);
1204 dup2(fd, STDERR_FILENO);
1209 fd_inotify = udev_watch_init(udev);
1210 if (fd_inotify < 0) {
1211 fprintf(stderr, "error initializing inotify\n");
1212 log_error("error initializing inotify\n");
1216 udev_watch_restore(udev);
1218 /* block and listen to all signals on signalfd */
1220 sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
1221 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
1222 if (fd_signal < 0) {
1223 fprintf(stderr, "error creating signalfd\n");
1224 log_error("error creating signalfd\n");
1229 /* unnamed socket from workers to the main daemon */
1230 if (socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, worker_watch) < 0) {
1231 fprintf(stderr, "error creating socketpair\n");
1232 log_error("error creating socketpair\n");
1236 fd_worker = worker_watch[READ_END];
1238 udev_builtin_init(udev);
1240 rules = udev_rules_new(udev, resolve_names);
1241 if (rules == NULL) {
1242 log_error("error reading rules\n");
1246 memset(&ep_ctrl, 0, sizeof(struct epoll_event));
1247 ep_ctrl.events = EPOLLIN;
1248 ep_ctrl.data.fd = fd_ctrl;
1250 memset(&ep_inotify, 0, sizeof(struct epoll_event));
1251 ep_inotify.events = EPOLLIN;
1252 ep_inotify.data.fd = fd_inotify;
1254 memset(&ep_signal, 0, sizeof(struct epoll_event));
1255 ep_signal.events = EPOLLIN;
1256 ep_signal.data.fd = fd_signal;
1258 memset(&ep_netlink, 0, sizeof(struct epoll_event));
1259 ep_netlink.events = EPOLLIN;
1260 ep_netlink.data.fd = fd_netlink;
1262 memset(&ep_worker, 0, sizeof(struct epoll_event));
1263 ep_worker.events = EPOLLIN;
1264 ep_worker.data.fd = fd_worker;
1266 fd_ep = epoll_create1(EPOLL_CLOEXEC);
1268 log_error("error creating epoll fd: %m\n");
1271 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_ctrl, &ep_ctrl) < 0 ||
1272 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_inotify, &ep_inotify) < 0 ||
1273 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
1274 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_netlink, &ep_netlink) < 0 ||
1275 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_worker, &ep_worker) < 0) {
1276 log_error("fail to add fds to epoll: %m\n");
1280 if (children_max <= 0) {
1281 int memsize = mem_size_mb();
1283 /* set value depending on the amount of RAM */
1285 children_max = 16 + (memsize / 8);
1289 log_debug("set children_max to %u\n", children_max);
1291 udev_rules_apply_static_dev_perms(rules);
1293 udev_list_node_init(&event_list);
1294 udev_list_node_init(&worker_list);
1297 static usec_t last_usec;
1298 struct epoll_event ev[8];
1301 bool is_worker, is_signal, is_inotify, is_netlink, is_ctrl;
1305 /* close sources of new events and discard buffered events */
1307 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_ctrl, NULL);
1310 if (monitor != NULL) {
1311 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_netlink, NULL);
1312 udev_monitor_unref(monitor);
1315 if (fd_inotify >= 0) {
1316 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_inotify, NULL);
1321 /* discard queued events and kill workers */
1322 event_queue_cleanup(udev, EVENT_QUEUED);
1325 /* exit after all has cleaned up */
1326 if (udev_list_node_is_empty(&event_list) && udev_list_node_is_empty(&worker_list))
1329 /* timeout at exit for workers to finish */
1330 timeout = 30 * 1000;
1331 } else if (udev_list_node_is_empty(&event_list) && !children) {
1335 /* cleanup possible left-over processes in our cgroup */
1337 cg_kill(SYSTEMD_CGROUP_CONTROLLER, udev_cgroup, SIGKILL, false, true, NULL);
1339 /* kill idle or hanging workers */
1342 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
1347 struct udev_list_node *loop;
1351 log_error("timeout, giving up waiting for workers to finish\n");
1355 /* kill idle workers */
1356 if (udev_list_node_is_empty(&event_list)) {
1357 log_debug("cleanup idle workers\n");
1361 /* check for hanging events */
1362 udev_list_node_foreach(loop, &worker_list) {
1363 struct worker *worker = node_to_worker(loop);
1365 if (worker->state != WORKER_RUNNING)
1368 if ((now(CLOCK_MONOTONIC) - worker->event_start_usec) > 30 * 1000 * 1000) {
1369 log_error("worker [%u] %s timeout; kill it\n", worker->pid,
1370 worker->event ? worker->event->devpath : "<idle>");
1371 kill(worker->pid, SIGKILL);
1372 worker->state = WORKER_KILLED;
1373 /* drop reference taken for state 'running' */
1374 worker_unref(worker);
1375 if (worker->event) {
1376 log_error("seq %llu '%s' killed\n",
1377 udev_device_get_seqnum(worker->event->dev), worker->event->devpath);
1378 worker->event->exitcode = -64;
1379 event_queue_delete(worker->event, true);
1380 worker->event = NULL;
1387 is_worker = is_signal = is_inotify = is_netlink = is_ctrl = false;
1388 for (i = 0; i < fdcount; i++) {
1389 if (ev[i].data.fd == fd_worker && ev[i].events & EPOLLIN)
1391 else if (ev[i].data.fd == fd_netlink && ev[i].events & EPOLLIN)
1393 else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN)
1395 else if (ev[i].data.fd == fd_inotify && ev[i].events & EPOLLIN)
1397 else if (ev[i].data.fd == fd_ctrl && ev[i].events & EPOLLIN)
1401 /* check for changed config, every 3 seconds at most */
1402 if ((now(CLOCK_MONOTONIC) - last_usec) > 3 * 1000 * 1000) {
1403 if (udev_rules_check_timestamp(rules))
1405 if (udev_builtin_validate(udev))
1408 last_usec = now(CLOCK_MONOTONIC);
1411 /* reload requested, HUP signal received, rules changed, builtin changed */
1414 rules = udev_rules_unref(rules);
1415 udev_builtin_exit(udev);
1419 /* event has finished */
1421 worker_returned(fd_worker);
1424 struct udev_device *dev;
1426 dev = udev_monitor_receive_device(monitor);
1428 udev_device_set_usec_initialized(dev, now(CLOCK_MONOTONIC));
1429 if (event_queue_insert(dev) < 0)
1430 udev_device_unref(dev);
1434 /* start new events */
1435 if (!udev_list_node_is_empty(&event_list) && !udev_exit && !stop_exec_queue) {
1436 udev_builtin_init(udev);
1438 rules = udev_rules_new(udev, resolve_names);
1440 event_queue_start(udev);
1444 struct signalfd_siginfo fdsi;
1447 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
1448 if (size == sizeof(struct signalfd_siginfo))
1449 handle_signal(udev, fdsi.ssi_signo);
1452 /* we are shutting down, the events below are not handled anymore */
1456 /* device node watch */
1458 handle_inotify(udev);
1461 * This needs to be after the inotify handling, to make sure,
1462 * that the ping is send back after the possibly generated
1463 * "change" events by the inotify device node watch.
1465 * A single time we may receive a client connection which we need to
1466 * keep open to block the client. It will be closed right before we
1470 ctrl_conn = handle_ctrl_msg(udev_ctrl);
1475 udev_queue_export_cleanup(udev_queue_export);
1476 udev_ctrl_cleanup(udev_ctrl);
1480 worker_list_cleanup(udev);
1481 event_queue_cleanup(udev, EVENT_UNDEF);
1482 udev_rules_unref(rules);
1483 udev_builtin_exit(udev);
1486 if (worker_watch[READ_END] >= 0)
1487 close(worker_watch[READ_END]);
1488 if (worker_watch[WRITE_END] >= 0)
1489 close(worker_watch[WRITE_END]);
1490 udev_monitor_unref(monitor);
1491 udev_queue_export_unref(udev_queue_export);
1492 udev_ctrl_connection_unref(ctrl_conn);
1493 udev_ctrl_unref(udev_ctrl);