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"
54 void udev_main_log(struct udev *udev, int priority,
55 const char *file, int line, const char *fn,
56 const char *format, va_list args)
58 log_metav(priority, file, line, fn, format, args);
61 static struct udev_rules *rules;
62 static struct udev_queue_export *udev_queue_export;
63 static struct udev_ctrl *udev_ctrl;
64 static struct udev_monitor *monitor;
65 static int worker_watch[2] = { -1, -1 };
66 static int fd_signal = -1;
67 static int fd_ep = -1;
68 static int fd_inotify = -1;
69 static bool stop_exec_queue;
72 static int children_max;
73 static int exec_delay;
74 static sigset_t sigmask_orig;
75 static UDEV_LIST(event_list);
76 static UDEV_LIST(worker_list);
78 static bool udev_exit;
87 struct udev_list_node node;
89 struct udev_device *dev;
90 enum event_state state;
92 unsigned long long int delaying_seqnum;
93 unsigned long long int seqnum;
96 const char *devpath_old;
103 static inline struct event *node_to_event(struct udev_list_node *node)
105 return container_of(node, struct event, node);
108 static void event_queue_cleanup(struct udev *udev, enum event_state type);
118 struct udev_list_node node;
122 struct udev_monitor *monitor;
123 enum worker_state state;
125 usec_t event_start_usec;
128 /* passed from worker to main process */
129 struct worker_message {
134 static inline struct worker *node_to_worker(struct udev_list_node *node)
136 return container_of(node, struct worker, node);
139 static void event_queue_delete(struct event *event, bool export)
141 udev_list_node_remove(&event->node);
144 udev_queue_export_device_finished(udev_queue_export, event->dev);
145 log_debug("seq %llu done with %i\n", udev_device_get_seqnum(event->dev), event->exitcode);
147 udev_device_unref(event->dev);
151 static struct worker *worker_ref(struct worker *worker)
157 static void worker_cleanup(struct worker *worker)
159 udev_list_node_remove(&worker->node);
160 udev_monitor_unref(worker->monitor);
165 static void worker_unref(struct worker *worker)
168 if (worker->refcount > 0)
170 log_debug("worker [%u] cleaned up\n", worker->pid);
171 worker_cleanup(worker);
174 static void worker_list_cleanup(struct udev *udev)
176 struct udev_list_node *loop, *tmp;
178 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
179 struct worker *worker = node_to_worker(loop);
181 worker_cleanup(worker);
185 static void worker_new(struct event *event)
187 struct udev *udev = event->udev;
188 struct worker *worker;
189 struct udev_monitor *worker_monitor;
192 /* listen for new events */
193 worker_monitor = udev_monitor_new_from_netlink(udev, NULL);
194 if (worker_monitor == NULL)
196 /* allow the main daemon netlink address to send devices to the worker */
197 udev_monitor_allow_unicast_sender(worker_monitor, monitor);
198 udev_monitor_enable_receiving(worker_monitor);
200 worker = calloc(1, sizeof(struct worker));
201 if (worker == NULL) {
202 udev_monitor_unref(worker_monitor);
205 /* worker + event reference */
206 worker->refcount = 2;
212 struct udev_device *dev = NULL;
214 struct epoll_event ep_signal, ep_monitor;
216 int rc = EXIT_SUCCESS;
218 /* take initial device from queue */
223 worker_list_cleanup(udev);
224 event_queue_cleanup(udev, EVENT_UNDEF);
225 udev_queue_export_unref(udev_queue_export);
226 udev_monitor_unref(monitor);
227 udev_ctrl_unref(udev_ctrl);
230 close(worker_watch[READ_END]);
233 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
235 log_error("error creating signalfd %m\n");
240 fd_ep = epoll_create1(EPOLL_CLOEXEC);
242 log_error("error creating epoll fd: %m\n");
247 memset(&ep_signal, 0, sizeof(struct epoll_event));
248 ep_signal.events = EPOLLIN;
249 ep_signal.data.fd = fd_signal;
251 fd_monitor = udev_monitor_get_fd(worker_monitor);
252 memset(&ep_monitor, 0, sizeof(struct epoll_event));
253 ep_monitor.events = EPOLLIN;
254 ep_monitor.data.fd = fd_monitor;
256 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
257 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_monitor, &ep_monitor) < 0) {
258 log_error("fail to add fds to epoll: %m\n");
263 /* request TERM signal if parent exits */
264 prctl(PR_SET_PDEATHSIG, SIGTERM);
266 /* reset OOM score, we only protect the main daemon */
267 write_one_line_file("/proc/self/oom_score_adj", "0");
270 struct udev_event *udev_event;
271 struct worker_message msg;
274 log_debug("seq %llu running\n", udev_device_get_seqnum(dev));
275 udev_event = udev_event_new(dev);
276 if (udev_event == NULL) {
281 /* needed for SIGCHLD/SIGTERM in spawn() */
282 udev_event->fd_signal = fd_signal;
285 udev_event->exec_delay = exec_delay;
287 /* apply rules, create node, symlinks */
288 err = udev_event_execute_rules(udev_event, rules, &sigmask_orig);
291 udev_event_execute_run(udev_event, &sigmask_orig);
293 /* apply/restore inotify watch */
294 if (err == 0 && udev_event->inotify_watch) {
295 udev_watch_begin(udev, dev);
296 udev_device_update_db(dev);
299 /* send processed event back to libudev listeners */
300 udev_monitor_send_device(worker_monitor, NULL, dev);
302 /* send udevd the result of the event execution */
303 memset(&msg, 0, sizeof(struct worker_message));
307 send(worker_watch[WRITE_END], &msg, sizeof(struct worker_message), 0);
309 log_debug("seq %llu processed with %i\n", udev_device_get_seqnum(dev), err);
311 udev_device_unref(dev);
314 if (udev_event->sigterm) {
315 udev_event_unref(udev_event);
319 udev_event_unref(udev_event);
321 /* wait for more device messages from main udevd, or term signal */
322 while (dev == NULL) {
323 struct epoll_event ev[4];
327 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), -1);
331 log_error("failed to poll: %m\n");
335 for (i = 0; i < fdcount; i++) {
336 if (ev[i].data.fd == fd_monitor && ev[i].events & EPOLLIN) {
337 dev = udev_monitor_receive_device(worker_monitor);
339 } else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN) {
340 struct signalfd_siginfo fdsi;
343 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
344 if (size != sizeof(struct signalfd_siginfo))
346 switch (fdsi.ssi_signo) {
355 udev_device_unref(dev);
361 close(worker_watch[WRITE_END]);
362 udev_rules_unref(rules);
363 udev_builtin_exit(udev);
364 udev_monitor_unref(worker_monitor);
370 udev_monitor_unref(worker_monitor);
371 event->state = EVENT_QUEUED;
373 log_error("fork of child failed: %m\n");
376 /* close monitor, but keep address around */
377 udev_monitor_disconnect(worker_monitor);
378 worker->monitor = worker_monitor;
380 worker->state = WORKER_RUNNING;
381 worker->event_start_usec = now(CLOCK_MONOTONIC);
382 worker->event = event;
383 event->state = EVENT_RUNNING;
384 udev_list_node_append(&worker->node, &worker_list);
386 log_debug("seq %llu forked new worker [%u]\n", udev_device_get_seqnum(event->dev), pid);
391 static void event_run(struct event *event)
393 struct udev_list_node *loop;
395 udev_list_node_foreach(loop, &worker_list) {
396 struct worker *worker = node_to_worker(loop);
399 if (worker->state != WORKER_IDLE)
402 count = udev_monitor_send_device(monitor, worker->monitor, event->dev);
404 log_error("worker [%u] did not accept message %zi (%m), kill it\n", worker->pid, count);
405 kill(worker->pid, SIGKILL);
406 worker->state = WORKER_KILLED;
410 worker->event = event;
411 worker->state = WORKER_RUNNING;
412 worker->event_start_usec = now(CLOCK_MONOTONIC);
413 event->state = EVENT_RUNNING;
417 if (children >= children_max) {
418 if (children_max > 1)
419 log_debug("maximum number (%i) of children reached\n", children);
423 /* start new worker and pass initial device */
427 static int event_queue_insert(struct udev_device *dev)
431 event = calloc(1, sizeof(struct event));
435 event->udev = udev_device_get_udev(dev);
437 event->seqnum = udev_device_get_seqnum(dev);
438 event->devpath = udev_device_get_devpath(dev);
439 event->devpath_len = strlen(event->devpath);
440 event->devpath_old = udev_device_get_devpath_old(dev);
441 event->devnum = udev_device_get_devnum(dev);
442 event->is_block = streq("block", udev_device_get_subsystem(dev));
443 event->ifindex = udev_device_get_ifindex(dev);
444 if (streq(udev_device_get_subsystem(dev), "firmware"))
445 event->nodelay = true;
447 udev_queue_export_device_queued(udev_queue_export, dev);
448 log_debug("seq %llu queued, '%s' '%s'\n", udev_device_get_seqnum(dev),
449 udev_device_get_action(dev), udev_device_get_subsystem(dev));
451 event->state = EVENT_QUEUED;
452 udev_list_node_append(&event->node, &event_list);
456 static void worker_kill(struct udev *udev)
458 struct udev_list_node *loop;
460 udev_list_node_foreach(loop, &worker_list) {
461 struct worker *worker = node_to_worker(loop);
463 if (worker->state == WORKER_KILLED)
466 worker->state = WORKER_KILLED;
467 kill(worker->pid, SIGTERM);
471 /* lookup event for identical, parent, child device */
472 static bool is_devpath_busy(struct event *event)
474 struct udev_list_node *loop;
477 /* check if queue contains events we depend on */
478 udev_list_node_foreach(loop, &event_list) {
479 struct event *loop_event = node_to_event(loop);
481 /* we already found a later event, earlier can not block us, no need to check again */
482 if (loop_event->seqnum < event->delaying_seqnum)
485 /* event we checked earlier still exists, no need to check again */
486 if (loop_event->seqnum == event->delaying_seqnum)
489 /* found ourself, no later event can block us */
490 if (loop_event->seqnum >= event->seqnum)
493 /* check major/minor */
494 if (major(event->devnum) != 0 && event->devnum == loop_event->devnum && event->is_block == loop_event->is_block)
497 /* check network device ifindex */
498 if (event->ifindex != 0 && event->ifindex == loop_event->ifindex)
501 /* check our old name */
502 if (event->devpath_old != NULL && strcmp(loop_event->devpath, event->devpath_old) == 0) {
503 event->delaying_seqnum = loop_event->seqnum;
507 /* compare devpath */
508 common = MIN(loop_event->devpath_len, event->devpath_len);
510 /* one devpath is contained in the other? */
511 if (memcmp(loop_event->devpath, event->devpath, common) != 0)
514 /* identical device event found */
515 if (loop_event->devpath_len == event->devpath_len) {
516 /* devices names might have changed/swapped in the meantime */
517 if (major(event->devnum) != 0 && (event->devnum != loop_event->devnum || event->is_block != loop_event->is_block))
519 if (event->ifindex != 0 && event->ifindex != loop_event->ifindex)
521 event->delaying_seqnum = loop_event->seqnum;
525 /* allow to bypass the dependency tracking */
529 /* parent device event found */
530 if (event->devpath[common] == '/') {
531 event->delaying_seqnum = loop_event->seqnum;
535 /* child device event found */
536 if (loop_event->devpath[common] == '/') {
537 event->delaying_seqnum = loop_event->seqnum;
541 /* no matching device */
548 static void event_queue_start(struct udev *udev)
550 struct udev_list_node *loop;
552 udev_list_node_foreach(loop, &event_list) {
553 struct event *event = node_to_event(loop);
555 if (event->state != EVENT_QUEUED)
558 /* do not start event if parent or child event is still running */
559 if (is_devpath_busy(event))
566 static void event_queue_cleanup(struct udev *udev, enum event_state match_type)
568 struct udev_list_node *loop, *tmp;
570 udev_list_node_foreach_safe(loop, tmp, &event_list) {
571 struct event *event = node_to_event(loop);
573 if (match_type != EVENT_UNDEF && match_type != event->state)
576 event_queue_delete(event, false);
580 static void worker_returned(int fd_worker)
583 struct worker_message msg;
585 struct udev_list_node *loop;
587 size = recv(fd_worker, &msg, sizeof(struct worker_message), MSG_DONTWAIT);
588 if (size != sizeof(struct worker_message))
591 /* lookup worker who sent the signal */
592 udev_list_node_foreach(loop, &worker_list) {
593 struct worker *worker = node_to_worker(loop);
595 if (worker->pid != msg.pid)
598 /* worker returned */
600 worker->event->exitcode = msg.exitcode;
601 event_queue_delete(worker->event, true);
602 worker->event = NULL;
604 if (worker->state != WORKER_KILLED)
605 worker->state = WORKER_IDLE;
606 worker_unref(worker);
612 /* receive the udevd message from userspace */
613 static struct udev_ctrl_connection *handle_ctrl_msg(struct udev_ctrl *uctrl)
615 struct udev *udev = udev_ctrl_get_udev(uctrl);
616 struct udev_ctrl_connection *ctrl_conn;
617 struct udev_ctrl_msg *ctrl_msg = NULL;
621 ctrl_conn = udev_ctrl_get_connection(uctrl);
622 if (ctrl_conn == NULL)
625 ctrl_msg = udev_ctrl_receive_msg(ctrl_conn);
626 if (ctrl_msg == NULL)
629 i = udev_ctrl_get_set_log_level(ctrl_msg);
631 log_debug("udevd message (SET_LOG_PRIORITY) received, log_priority=%i\n", i);
632 log_set_max_level(i);
633 udev_set_log_priority(udev, i);
637 if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
638 log_debug("udevd message (STOP_EXEC_QUEUE) received\n");
639 stop_exec_queue = true;
642 if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
643 log_debug("udevd message (START_EXEC_QUEUE) received\n");
644 stop_exec_queue = false;
647 if (udev_ctrl_get_reload(ctrl_msg) > 0) {
648 log_debug("udevd message (RELOAD) received\n");
652 str = udev_ctrl_get_set_env(ctrl_msg);
660 val = strchr(key, '=');
664 if (val[0] == '\0') {
665 log_debug("udevd message (ENV) received, unset '%s'\n", key);
666 udev_add_property(udev, key, NULL);
668 log_debug("udevd message (ENV) received, set '%s=%s'\n", key, val);
669 udev_add_property(udev, key, val);
672 log_error("wrong key format '%s'\n", key);
679 i = udev_ctrl_get_set_children_max(ctrl_msg);
681 log_debug("udevd message (SET_MAX_CHILDREN) received, children_max=%i\n", i);
685 if (udev_ctrl_get_ping(ctrl_msg) > 0)
686 log_debug("udevd message (SYNC) received\n");
688 if (udev_ctrl_get_exit(ctrl_msg) > 0) {
689 log_debug("udevd message (EXIT) received\n");
691 /* keep reference to block the client until we exit */
692 udev_ctrl_connection_ref(ctrl_conn);
695 udev_ctrl_msg_unref(ctrl_msg);
696 return udev_ctrl_connection_unref(ctrl_conn);
699 /* read inotify messages */
700 static int handle_inotify(struct udev *udev)
704 struct inotify_event *ev;
706 if ((ioctl(fd_inotify, FIONREAD, &nbytes) < 0) || (nbytes <= 0))
709 buf = malloc(nbytes);
711 log_error("error getting buffer for inotify\n");
715 nbytes = read(fd_inotify, buf, nbytes);
717 for (pos = 0; pos < nbytes; pos += sizeof(struct inotify_event) + ev->len) {
718 struct udev_device *dev;
720 ev = (struct inotify_event *)(buf + pos);
721 dev = udev_watch_lookup(udev, ev->wd);
723 log_debug("inotify event: %x for %s\n", ev->mask, udev_device_get_devnode(dev));
724 if (ev->mask & IN_CLOSE_WRITE) {
725 char filename[UTIL_PATH_SIZE];
728 log_debug("device %s closed, synthesising 'change'\n", udev_device_get_devnode(dev));
729 strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
730 fd = open(filename, O_WRONLY);
732 if (write(fd, "change", 6) < 0)
733 log_debug("error writing uevent: %m\n");
737 if (ev->mask & IN_IGNORED)
738 udev_watch_end(udev, dev);
740 udev_device_unref(dev);
749 static void handle_signal(struct udev *udev, int signo)
760 struct udev_list_node *loop, *tmp;
762 pid = waitpid(-1, &status, WNOHANG);
766 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
767 struct worker *worker = node_to_worker(loop);
769 if (worker->pid != pid)
771 log_debug("worker [%u] exit\n", pid);
773 if (WIFEXITED(status)) {
774 if (WEXITSTATUS(status) != 0)
775 log_error("worker [%u] exit with return code %i\n", pid, WEXITSTATUS(status));
776 } else if (WIFSIGNALED(status)) {
777 log_error("worker [%u] terminated by signal %i (%s)\n",
778 pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
779 } else if (WIFSTOPPED(status)) {
780 log_error("worker [%u] stopped\n", pid);
781 } else if (WIFCONTINUED(status)) {
782 log_error("worker [%u] continued\n", pid);
784 log_error("worker [%u] exit with status 0x%04x\n", pid, status);
787 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
789 log_error("worker [%u] failed while handling '%s'\n",
790 pid, worker->event->devpath);
791 worker->event->exitcode = -32;
792 event_queue_delete(worker->event, true);
793 /* drop reference taken for state 'running' */
794 worker_unref(worker);
797 worker_unref(worker);
808 static void static_dev_create_from_modules(struct udev *udev)
810 struct utsname kernel;
811 char modules[UTIL_PATH_SIZE];
816 strscpyl(modules, sizeof(modules), ROOTPREFIX "/lib/modules/", kernel.release, "/modules.devname", NULL);
817 f = fopen(modules, "re");
821 while (fgets(buf, sizeof(buf), f) != NULL) {
829 char filename[UTIL_PATH_SIZE];
835 s = strchr(modname, ' ');
841 s = strchr(devname, ' ');
847 s = strchr(devno, ' ');
849 s = strchr(devno, '\n');
852 if (sscanf(devno, "%c%u:%u", &type, &maj, &min) != 3)
858 else if (type == 'b')
863 strscpyl(filename, sizeof(filename), "/dev/", devname, NULL);
864 mkdir_parents_label(filename, 0755);
865 label_context_set(filename, mode);
866 log_debug("mknod '%s' %c%u:%u\n", filename, type, maj, min);
867 if (mknod(filename, mode, makedev(maj, min)) < 0 && errno == EEXIST)
868 utimensat(AT_FDCWD, filename, NULL, 0);
869 label_context_clear();
875 static int mem_size_mb(void)
879 long int memsize = -1;
881 f = fopen("/proc/meminfo", "re");
885 while (fgets(buf, sizeof(buf), f) != NULL) {
888 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
889 memsize = value / 1024;
898 static int convert_db(struct udev *udev)
900 char filename[UTIL_PATH_SIZE];
901 struct udev_enumerate *udev_enumerate;
902 struct udev_list_entry *list_entry;
904 /* current database */
905 if (access("/run/udev/data", F_OK) >= 0)
908 /* make sure we do not get here again */
909 mkdir_p("/run/udev/data", 0755);
912 strscpyl(filename, sizeof(filename), "/dev/.udev/db", NULL);
913 if (access(filename, F_OK) < 0)
916 print_kmsg("converting old udev database\n");
918 udev_enumerate = udev_enumerate_new(udev);
919 if (udev_enumerate == NULL)
921 udev_enumerate_scan_devices(udev_enumerate);
922 udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(udev_enumerate)) {
923 struct udev_device *device;
925 device = udev_device_new_from_syspath(udev, udev_list_entry_get_name(list_entry));
929 /* try to find the old database for devices without a current one */
930 if (udev_device_read_db(device, NULL) < 0) {
934 char devpath[UTIL_PATH_SIZE];
935 char from[UTIL_PATH_SIZE];
939 /* find database in old location */
940 id = udev_device_get_id_filename(device);
941 strscpyl(from, sizeof(from), "/dev/.udev/db/", id, NULL);
942 if (lstat(from, &stats) == 0) {
944 udev_device_read_db(device, from);
950 /* find old database with $subsys:$sysname name */
951 strscpyl(from, sizeof(from), "/dev/.udev/db/",
952 udev_device_get_subsystem(device), ":", udev_device_get_sysname(device), NULL);
953 if (lstat(from, &stats) == 0) {
955 udev_device_read_db(device, from);
961 /* find old database with the encoded devpath name */
962 util_path_encode(udev_device_get_devpath(device), devpath, sizeof(devpath));
963 strscpyl(from, sizeof(from), "/dev/.udev/db/", devpath, NULL);
964 if (lstat(from, &stats) == 0) {
966 udev_device_read_db(device, from);
972 /* write out new database */
974 udev_device_update_db(device);
976 udev_device_unref(device);
978 udev_enumerate_unref(udev_enumerate);
982 static int systemd_fds(struct udev *udev, int *rctrl, int *rnetlink)
984 int ctrl = -1, netlink = -1;
987 n = sd_listen_fds(true);
991 for (fd = SD_LISTEN_FDS_START; fd < n + SD_LISTEN_FDS_START; fd++) {
992 if (sd_is_socket(fd, AF_LOCAL, SOCK_SEQPACKET, -1)) {
999 if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1)) {
1009 if (ctrl < 0 || netlink < 0)
1012 log_debug("ctrl=%i netlink=%i\n", ctrl, netlink);
1014 *rnetlink = netlink;
1019 * read the kernel commandline, in case we need to get into debug mode
1020 * udev.log-priority=<level> syslog priority
1021 * udev.children-max=<number of workers> events are fully serialized if set to 1
1022 * udev.exec-delay=<number of seconds> delay execution of every executed program
1024 static void kernel_cmdline_options(struct udev *udev)
1026 char *line, *w, *state;
1029 if (read_one_line_file("/proc/cmdline", &line) < 0)
1032 FOREACH_WORD_QUOTED(w, l, line, state) {
1039 /* accept the same options for the initrd, prefixed with "rd." */
1040 if (in_initrd() && startswith(s, "rd."))
1045 if (startswith(opt, "udev.log-priority=")) {
1048 prio = util_log_priority(opt + 18);
1049 log_set_max_level(prio);
1050 udev_set_log_priority(udev, prio);
1051 } else if (startswith(opt, "udev.children-max=")) {
1052 children_max = strtoul(opt + 18, NULL, 0);
1053 } else if (startswith(opt, "udev.exec-delay=")) {
1054 exec_delay = strtoul(opt + 16, NULL, 0);
1063 int main(int argc, char *argv[])
1067 int daemonize = false;
1068 int resolve_names = 1;
1069 static const struct option options[] = {
1070 { "daemon", no_argument, NULL, 'd' },
1071 { "debug", no_argument, NULL, 'D' },
1072 { "children-max", required_argument, NULL, 'c' },
1073 { "exec-delay", required_argument, NULL, 'e' },
1074 { "resolve-names", required_argument, NULL, 'N' },
1075 { "help", no_argument, NULL, 'h' },
1076 { "version", no_argument, NULL, 'V' },
1080 int fd_netlink = -1;
1082 struct epoll_event ep_ctrl, ep_inotify, ep_signal, ep_netlink, ep_worker;
1083 struct udev_ctrl_connection *ctrl_conn = NULL;
1090 log_set_target(LOG_TARGET_AUTO);
1091 log_parse_environment();
1093 udev_set_log_fn(udev, udev_main_log);
1094 log_debug("version %s\n", VERSION);
1100 option = getopt_long(argc, argv, "c:de:DtN:hV", options, NULL);
1109 children_max = strtoul(optarg, NULL, 0);
1112 exec_delay = strtoul(optarg, NULL, 0);
1116 log_set_max_level(LOG_DEBUG);
1117 udev_set_log_priority(udev, LOG_DEBUG);
1120 if (strcmp (optarg, "early") == 0) {
1122 } else if (strcmp (optarg, "late") == 0) {
1124 } else if (strcmp (optarg, "never") == 0) {
1127 fprintf(stderr, "resolve-names must be early, late or never\n");
1128 log_error("resolve-names must be early, late or never\n");
1133 printf("Usage: udevd OPTIONS\n"
1136 " --children-max=<maximum number of workers>\n"
1137 " --exec-delay=<seconds to wait before executing RUN=>\n"
1138 " --resolve-names=early|late|never\n"
1144 printf("%s\n", VERSION);
1151 kernel_cmdline_options(udev);
1153 if (getuid() != 0) {
1154 fprintf(stderr, "root privileges required\n");
1155 log_error("root privileges required\n");
1159 /* set umask before creating any file/directory */
1163 mkdir("/run/udev", 0755);
1166 static_dev_create_from_modules(udev);
1168 /* before opening new files, make sure std{in,out,err} fds are in a sane state */
1172 fd = open("/dev/null", O_RDWR);
1174 if (write(STDOUT_FILENO, 0, 0) < 0)
1175 dup2(fd, STDOUT_FILENO);
1176 if (write(STDERR_FILENO, 0, 0) < 0)
1177 dup2(fd, STDERR_FILENO);
1178 if (fd > STDERR_FILENO)
1181 fprintf(stderr, "cannot open /dev/null\n");
1182 log_error("cannot open /dev/null\n");
1186 if (systemd_fds(udev, &fd_ctrl, &fd_netlink) >= 0) {
1187 /* get control and netlink socket from systemd */
1188 udev_ctrl = udev_ctrl_new_from_fd(udev, fd_ctrl);
1189 if (udev_ctrl == NULL) {
1190 log_error("error taking over udev control socket");
1195 monitor = udev_monitor_new_from_netlink_fd(udev, "kernel", fd_netlink);
1196 if (monitor == NULL) {
1197 log_error("error taking over netlink socket\n");
1202 /* get our own cgroup, we regularly kill everything udev has left behind */
1203 if (cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 0, &udev_cgroup) < 0)
1206 /* open control and netlink socket */
1207 udev_ctrl = udev_ctrl_new(udev);
1208 if (udev_ctrl == NULL) {
1209 fprintf(stderr, "error initializing udev control socket");
1210 log_error("error initializing udev control socket");
1214 fd_ctrl = udev_ctrl_get_fd(udev_ctrl);
1216 monitor = udev_monitor_new_from_netlink(udev, "kernel");
1217 if (monitor == NULL) {
1218 fprintf(stderr, "error initializing netlink socket\n");
1219 log_error("error initializing netlink socket\n");
1223 fd_netlink = udev_monitor_get_fd(monitor);
1226 if (udev_monitor_enable_receiving(monitor) < 0) {
1227 fprintf(stderr, "error binding netlink socket\n");
1228 log_error("error binding netlink socket\n");
1233 if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
1234 fprintf(stderr, "error binding udev control socket\n");
1235 log_error("error binding udev control socket\n");
1240 udev_monitor_set_receive_buffer_size(monitor, 128*1024*1024);
1242 /* create queue file before signalling 'ready', to make sure we block 'settle' */
1243 udev_queue_export = udev_queue_export_new(udev);
1244 if (udev_queue_export == NULL) {
1245 log_error("error creating queue file\n");
1257 log_error("fork of daemon failed: %m\n");
1262 goto exit_daemonize;
1267 write_one_line_file("/proc/self/oom_score_adj", "-1000");
1269 sd_notify(1, "READY=1");
1272 print_kmsg("starting version " VERSION "\n");
1277 fd = open("/dev/null", O_RDWR);
1279 dup2(fd, STDIN_FILENO);
1280 dup2(fd, STDOUT_FILENO);
1281 dup2(fd, STDERR_FILENO);
1286 fd_inotify = udev_watch_init(udev);
1287 if (fd_inotify < 0) {
1288 fprintf(stderr, "error initializing inotify\n");
1289 log_error("error initializing inotify\n");
1293 udev_watch_restore(udev);
1295 /* block and listen to all signals on signalfd */
1297 sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
1298 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
1299 if (fd_signal < 0) {
1300 fprintf(stderr, "error creating signalfd\n");
1301 log_error("error creating signalfd\n");
1306 /* unnamed socket from workers to the main daemon */
1307 if (socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, worker_watch) < 0) {
1308 fprintf(stderr, "error creating socketpair\n");
1309 log_error("error creating socketpair\n");
1313 fd_worker = worker_watch[READ_END];
1315 udev_builtin_init(udev);
1317 rules = udev_rules_new(udev, resolve_names);
1318 if (rules == NULL) {
1319 log_error("error reading rules\n");
1323 memset(&ep_ctrl, 0, sizeof(struct epoll_event));
1324 ep_ctrl.events = EPOLLIN;
1325 ep_ctrl.data.fd = fd_ctrl;
1327 memset(&ep_inotify, 0, sizeof(struct epoll_event));
1328 ep_inotify.events = EPOLLIN;
1329 ep_inotify.data.fd = fd_inotify;
1331 memset(&ep_signal, 0, sizeof(struct epoll_event));
1332 ep_signal.events = EPOLLIN;
1333 ep_signal.data.fd = fd_signal;
1335 memset(&ep_netlink, 0, sizeof(struct epoll_event));
1336 ep_netlink.events = EPOLLIN;
1337 ep_netlink.data.fd = fd_netlink;
1339 memset(&ep_worker, 0, sizeof(struct epoll_event));
1340 ep_worker.events = EPOLLIN;
1341 ep_worker.data.fd = fd_worker;
1343 fd_ep = epoll_create1(EPOLL_CLOEXEC);
1345 log_error("error creating epoll fd: %m\n");
1348 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_ctrl, &ep_ctrl) < 0 ||
1349 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_inotify, &ep_inotify) < 0 ||
1350 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
1351 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_netlink, &ep_netlink) < 0 ||
1352 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_worker, &ep_worker) < 0) {
1353 log_error("fail to add fds to epoll: %m\n");
1357 /* if needed, convert old database from earlier udev version */
1360 if (children_max <= 0) {
1361 int memsize = mem_size_mb();
1363 /* set value depending on the amount of RAM */
1365 children_max = 16 + (memsize / 8);
1369 log_debug("set children_max to %u\n", children_max);
1371 udev_rules_apply_static_dev_perms(rules);
1373 udev_list_node_init(&event_list);
1374 udev_list_node_init(&worker_list);
1377 static usec_t last_usec;
1378 struct epoll_event ev[8];
1381 bool is_worker, is_signal, is_inotify, is_netlink, is_ctrl;
1385 /* close sources of new events and discard buffered events */
1387 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_ctrl, NULL);
1390 if (monitor != NULL) {
1391 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_netlink, NULL);
1392 udev_monitor_unref(monitor);
1395 if (fd_inotify >= 0) {
1396 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_inotify, NULL);
1401 /* discard queued events and kill workers */
1402 event_queue_cleanup(udev, EVENT_QUEUED);
1405 /* exit after all has cleaned up */
1406 if (udev_list_node_is_empty(&event_list) && udev_list_node_is_empty(&worker_list))
1409 /* timeout at exit for workers to finish */
1410 timeout = 30 * 1000;
1411 } else if (udev_list_node_is_empty(&event_list) && !children) {
1415 /* cleanup possible left-over processes in our cgroup */
1417 cg_kill(SYSTEMD_CGROUP_CONTROLLER, udev_cgroup, SIGKILL, false, true, NULL);
1419 /* kill idle or hanging workers */
1422 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
1427 struct udev_list_node *loop;
1431 log_error("timeout, giving up waiting for workers to finish\n");
1435 /* kill idle workers */
1436 if (udev_list_node_is_empty(&event_list)) {
1437 log_debug("cleanup idle workers\n");
1441 /* check for hanging events */
1442 udev_list_node_foreach(loop, &worker_list) {
1443 struct worker *worker = node_to_worker(loop);
1445 if (worker->state != WORKER_RUNNING)
1448 if ((now(CLOCK_MONOTONIC) - worker->event_start_usec) > 30 * 1000 * 1000) {
1449 log_error("worker [%u] %s timeout; kill it\n", worker->pid,
1450 worker->event ? worker->event->devpath : "<idle>");
1451 kill(worker->pid, SIGKILL);
1452 worker->state = WORKER_KILLED;
1453 /* drop reference taken for state 'running' */
1454 worker_unref(worker);
1455 if (worker->event) {
1456 log_error("seq %llu '%s' killed\n",
1457 udev_device_get_seqnum(worker->event->dev), worker->event->devpath);
1458 worker->event->exitcode = -64;
1459 event_queue_delete(worker->event, true);
1460 worker->event = NULL;
1467 is_worker = is_signal = is_inotify = is_netlink = is_ctrl = false;
1468 for (i = 0; i < fdcount; i++) {
1469 if (ev[i].data.fd == fd_worker && ev[i].events & EPOLLIN)
1471 else if (ev[i].data.fd == fd_netlink && ev[i].events & EPOLLIN)
1473 else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN)
1475 else if (ev[i].data.fd == fd_inotify && ev[i].events & EPOLLIN)
1477 else if (ev[i].data.fd == fd_ctrl && ev[i].events & EPOLLIN)
1481 /* check for changed config, every 3 seconds at most */
1482 if ((now(CLOCK_MONOTONIC) - last_usec) > 3 * 1000 * 1000) {
1483 if (udev_rules_check_timestamp(rules))
1485 if (udev_builtin_validate(udev))
1488 last_usec = now(CLOCK_MONOTONIC);
1491 /* reload requested, HUP signal received, rules changed, builtin changed */
1494 rules = udev_rules_unref(rules);
1495 udev_builtin_exit(udev);
1499 /* event has finished */
1501 worker_returned(fd_worker);
1504 struct udev_device *dev;
1506 dev = udev_monitor_receive_device(monitor);
1508 udev_device_set_usec_initialized(dev, now(CLOCK_MONOTONIC));
1509 if (event_queue_insert(dev) < 0)
1510 udev_device_unref(dev);
1514 /* start new events */
1515 if (!udev_list_node_is_empty(&event_list) && !udev_exit && !stop_exec_queue) {
1516 udev_builtin_init(udev);
1518 rules = udev_rules_new(udev, resolve_names);
1520 event_queue_start(udev);
1524 struct signalfd_siginfo fdsi;
1527 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
1528 if (size == sizeof(struct signalfd_siginfo))
1529 handle_signal(udev, fdsi.ssi_signo);
1532 /* we are shutting down, the events below are not handled anymore */
1536 /* device node watch */
1538 handle_inotify(udev);
1541 * This needs to be after the inotify handling, to make sure,
1542 * that the ping is send back after the possibly generated
1543 * "change" events by the inotify device node watch.
1545 * A single time we may receive a client connection which we need to
1546 * keep open to block the client. It will be closed right before we
1550 ctrl_conn = handle_ctrl_msg(udev_ctrl);
1555 udev_queue_export_cleanup(udev_queue_export);
1556 udev_ctrl_cleanup(udev_ctrl);
1560 worker_list_cleanup(udev);
1561 event_queue_cleanup(udev, EVENT_UNDEF);
1562 udev_rules_unref(rules);
1563 udev_builtin_exit(udev);
1566 if (worker_watch[READ_END] >= 0)
1567 close(worker_watch[READ_END]);
1568 if (worker_watch[WRITE_END] >= 0)
1569 close(worker_watch[WRITE_END]);
1570 udev_monitor_unref(monitor);
1571 udev_queue_export_unref(udev_queue_export);
1572 udev_ctrl_connection_unref(ctrl_conn);
1573 udev_ctrl_unref(udev_ctrl);