2 * Copyright (C) 2004-2012 Kay Sievers <kay@vrfy.org>
3 * Copyright (C) 2004 Chris Friesen <chris_friesen@sympatico.ca>
4 * Copyright (C) 2009 Canonical Ltd.
5 * Copyright (C) 2009 Scott James Remnant <scott@netsplit.com>
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
36 #include <sys/prctl.h>
37 #include <sys/socket.h>
39 #include <sys/signalfd.h>
40 #include <sys/epoll.h>
41 #include <sys/mount.h>
45 #include <sys/ioctl.h>
46 #include <sys/inotify.h>
47 #include <sys/utsname.h>
50 #include "udev-util.h"
51 #include "sd-daemon.h"
52 #include "cgroup-util.h"
53 #include "dev-setup.h"
58 void udev_main_log(struct udev *udev, int priority,
59 const char *file, int line, const char *fn,
60 const char *format, va_list args) {
61 log_metav(priority, file, line, fn, format, args);
64 static struct udev_rules *rules;
65 static struct udev_ctrl *udev_ctrl;
66 static struct udev_monitor *monitor;
67 static int worker_watch[2] = { -1, -1 };
68 static int fd_signal = -1;
69 static int fd_ep = -1;
70 static int fd_inotify = -1;
71 static bool stop_exec_queue;
74 static int children_max;
75 static int exec_delay;
76 static usec_t event_timeout_usec = 60 * USEC_PER_SEC;
77 static sigset_t sigmask_orig;
78 static UDEV_LIST(event_list);
79 static UDEV_LIST(worker_list);
80 static char *udev_cgroup;
81 static bool udev_exit;
90 struct udev_list_node node;
92 struct udev_device *dev;
93 enum event_state state;
95 unsigned long long int delaying_seqnum;
96 unsigned long long int seqnum;
99 const char *devpath_old;
105 static inline struct event *node_to_event(struct udev_list_node *node) {
106 return container_of(node, struct event, node);
109 static void event_queue_cleanup(struct udev *udev, enum event_state type);
119 struct udev_list_node node;
123 struct udev_monitor *monitor;
124 enum worker_state state;
126 usec_t event_start_usec;
129 /* passed from worker to main process */
130 struct worker_message {
135 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) {
140 udev_list_node_remove(&event->node);
141 udev_device_unref(event->dev);
145 static struct worker *worker_ref(struct worker *worker) {
150 static void worker_cleanup(struct worker *worker) {
151 udev_list_node_remove(&worker->node);
152 udev_monitor_unref(worker->monitor);
157 static void worker_unref(struct worker *worker) {
159 if (worker->refcount > 0)
161 log_debug("worker [%u] cleaned up", worker->pid);
162 worker_cleanup(worker);
165 static void worker_list_cleanup(struct udev *udev) {
166 struct udev_list_node *loop, *tmp;
168 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
169 struct worker *worker = node_to_worker(loop);
171 worker_cleanup(worker);
175 static void worker_new(struct event *event) {
176 struct udev *udev = event->udev;
177 struct worker *worker;
178 struct udev_monitor *worker_monitor;
181 /* listen for new events */
182 worker_monitor = udev_monitor_new_from_netlink(udev, NULL);
183 if (worker_monitor == NULL)
185 /* allow the main daemon netlink address to send devices to the worker */
186 udev_monitor_allow_unicast_sender(worker_monitor, monitor);
187 udev_monitor_enable_receiving(worker_monitor);
189 worker = new0(struct worker, 1);
190 if (worker == NULL) {
191 udev_monitor_unref(worker_monitor);
194 /* worker + event reference */
195 worker->refcount = 2;
201 struct udev_device *dev = NULL;
203 struct epoll_event ep_signal, ep_monitor;
205 int rc = EXIT_SUCCESS;
207 /* take initial device from queue */
212 worker_list_cleanup(udev);
213 event_queue_cleanup(udev, EVENT_UNDEF);
214 udev_monitor_unref(monitor);
215 udev_ctrl_unref(udev_ctrl);
218 close(worker_watch[READ_END]);
221 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
223 log_error("error creating signalfd %m");
228 fd_ep = epoll_create1(EPOLL_CLOEXEC);
230 log_error("error creating epoll fd: %m");
235 memzero(&ep_signal, sizeof(struct epoll_event));
236 ep_signal.events = EPOLLIN;
237 ep_signal.data.fd = fd_signal;
239 fd_monitor = udev_monitor_get_fd(worker_monitor);
240 memzero(&ep_monitor, sizeof(struct epoll_event));
241 ep_monitor.events = EPOLLIN;
242 ep_monitor.data.fd = fd_monitor;
244 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
245 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_monitor, &ep_monitor) < 0) {
246 log_error("fail to add fds to epoll: %m");
251 /* request TERM signal if parent exits */
252 prctl(PR_SET_PDEATHSIG, SIGTERM);
254 /* reset OOM score, we only protect the main daemon */
255 write_string_file("/proc/self/oom_score_adj", "0");
258 struct udev_event *udev_event;
259 struct worker_message msg;
263 log_debug("seq %llu running", udev_device_get_seqnum(dev));
264 udev_event = udev_event_new(dev);
265 if (udev_event == NULL) {
270 /* needed for SIGCHLD/SIGTERM in spawn() */
271 udev_event->fd_signal = fd_signal;
274 udev_event->exec_delay = exec_delay;
277 * Take a shared lock on the device node; this establishes
278 * a concept of device "ownership" to serialize device
279 * access. External processes holding an exclusive lock will
280 * cause udev to skip the event handling; in the case udev
281 * acquired the lock, the external process can block until
282 * udev has finished its event handling.
284 if (!streq_ptr(udev_device_get_action(dev), "remove") &&
285 streq_ptr("block", udev_device_get_subsystem(dev)) &&
286 !startswith(udev_device_get_sysname(dev), "dm-") &&
287 !startswith(udev_device_get_sysname(dev), "md")) {
288 struct udev_device *d = dev;
290 if (streq_ptr("partition", udev_device_get_devtype(d)))
291 d = udev_device_get_parent(d);
294 fd_lock = open(udev_device_get_devnode(d), O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
295 if (fd_lock >= 0 && flock(fd_lock, LOCK_SH|LOCK_NB) < 0) {
296 log_debug("Unable to flock(%s), skipping event handling: %m", udev_device_get_devnode(d));
298 fd_lock = safe_close(fd_lock);
304 /* apply rules, create node, symlinks */
305 udev_event_execute_rules(udev_event, event_timeout_usec, rules, &sigmask_orig);
307 udev_event_execute_run(udev_event, event_timeout_usec, &sigmask_orig);
309 /* apply/restore inotify watch */
310 if (udev_event->inotify_watch) {
311 udev_watch_begin(udev, dev);
312 udev_device_update_db(dev);
317 /* send processed event back to libudev listeners */
318 udev_monitor_send_device(worker_monitor, NULL, dev);
321 /* send udevd the result of the event execution */
322 memzero(&msg, sizeof(struct worker_message));
325 send(worker_watch[WRITE_END], &msg, sizeof(struct worker_message), 0);
327 log_debug("seq %llu processed with %i", udev_device_get_seqnum(dev), err);
329 udev_device_unref(dev);
332 if (udev_event->sigterm) {
333 udev_event_unref(udev_event);
337 udev_event_unref(udev_event);
339 /* wait for more device messages from main udevd, or term signal */
340 while (dev == NULL) {
341 struct epoll_event ev[4];
345 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), -1);
349 log_error("failed to poll: %m");
353 for (i = 0; i < fdcount; i++) {
354 if (ev[i].data.fd == fd_monitor && ev[i].events & EPOLLIN) {
355 dev = udev_monitor_receive_device(worker_monitor);
357 } else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN) {
358 struct signalfd_siginfo fdsi;
361 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
362 if (size != sizeof(struct signalfd_siginfo))
364 switch (fdsi.ssi_signo) {
373 udev_device_unref(dev);
374 safe_close(fd_signal);
377 close(worker_watch[WRITE_END]);
378 udev_rules_unref(rules);
379 udev_builtin_exit(udev);
380 udev_monitor_unref(worker_monitor);
386 udev_monitor_unref(worker_monitor);
387 event->state = EVENT_QUEUED;
389 log_error("fork of child failed: %m");
392 /* close monitor, but keep address around */
393 udev_monitor_disconnect(worker_monitor);
394 worker->monitor = worker_monitor;
396 worker->state = WORKER_RUNNING;
397 worker->event_start_usec = now(CLOCK_MONOTONIC);
398 worker->event = event;
399 event->state = EVENT_RUNNING;
400 udev_list_node_append(&worker->node, &worker_list);
402 log_debug("seq %llu forked new worker [%u]", udev_device_get_seqnum(event->dev), pid);
407 static void event_run(struct event *event) {
408 struct udev_list_node *loop;
410 udev_list_node_foreach(loop, &worker_list) {
411 struct worker *worker = node_to_worker(loop);
414 if (worker->state != WORKER_IDLE)
417 count = udev_monitor_send_device(monitor, worker->monitor, event->dev);
419 log_error("worker [%u] did not accept message %zi (%m), kill it", worker->pid, count);
420 kill(worker->pid, SIGKILL);
421 worker->state = WORKER_KILLED;
425 worker->event = event;
426 worker->state = WORKER_RUNNING;
427 worker->event_start_usec = now(CLOCK_MONOTONIC);
428 event->state = EVENT_RUNNING;
432 if (children >= children_max) {
433 if (children_max > 1)
434 log_debug("maximum number (%i) of children reached", children);
438 /* start new worker and pass initial device */
442 static int event_queue_insert(struct udev_device *dev) {
445 event = new0(struct event, 1);
449 event->udev = udev_device_get_udev(dev);
451 event->seqnum = udev_device_get_seqnum(dev);
452 event->devpath = udev_device_get_devpath(dev);
453 event->devpath_len = strlen(event->devpath);
454 event->devpath_old = udev_device_get_devpath_old(dev);
455 event->devnum = udev_device_get_devnum(dev);
456 event->is_block = streq("block", udev_device_get_subsystem(dev));
457 event->ifindex = udev_device_get_ifindex(dev);
459 log_debug("seq %llu queued, '%s' '%s'", udev_device_get_seqnum(dev),
460 udev_device_get_action(dev), udev_device_get_subsystem(dev));
462 event->state = EVENT_QUEUED;
463 udev_list_node_append(&event->node, &event_list);
467 static void worker_kill(struct udev *udev) {
468 struct udev_list_node *loop;
470 udev_list_node_foreach(loop, &worker_list) {
471 struct worker *worker = node_to_worker(loop);
473 if (worker->state == WORKER_KILLED)
476 worker->state = WORKER_KILLED;
477 kill(worker->pid, SIGTERM);
481 /* lookup event for identical, parent, child device */
482 static bool is_devpath_busy(struct event *event) {
483 struct udev_list_node *loop;
486 /* check if queue contains events we depend on */
487 udev_list_node_foreach(loop, &event_list) {
488 struct event *loop_event = node_to_event(loop);
490 /* we already found a later event, earlier can not block us, no need to check again */
491 if (loop_event->seqnum < event->delaying_seqnum)
494 /* event we checked earlier still exists, no need to check again */
495 if (loop_event->seqnum == event->delaying_seqnum)
498 /* found ourself, no later event can block us */
499 if (loop_event->seqnum >= event->seqnum)
502 /* check major/minor */
503 if (major(event->devnum) != 0 && event->devnum == loop_event->devnum && event->is_block == loop_event->is_block)
506 /* check network device ifindex */
507 if (event->ifindex != 0 && event->ifindex == loop_event->ifindex)
510 /* check our old name */
511 if (event->devpath_old != NULL && streq(loop_event->devpath, event->devpath_old)) {
512 event->delaying_seqnum = loop_event->seqnum;
516 /* compare devpath */
517 common = MIN(loop_event->devpath_len, event->devpath_len);
519 /* one devpath is contained in the other? */
520 if (memcmp(loop_event->devpath, event->devpath, common) != 0)
523 /* identical device event found */
524 if (loop_event->devpath_len == event->devpath_len) {
525 /* devices names might have changed/swapped in the meantime */
526 if (major(event->devnum) != 0 && (event->devnum != loop_event->devnum || event->is_block != loop_event->is_block))
528 if (event->ifindex != 0 && event->ifindex != loop_event->ifindex)
530 event->delaying_seqnum = loop_event->seqnum;
534 /* parent device event found */
535 if (event->devpath[common] == '/') {
536 event->delaying_seqnum = loop_event->seqnum;
540 /* child device event found */
541 if (loop_event->devpath[common] == '/') {
542 event->delaying_seqnum = loop_event->seqnum;
546 /* no matching device */
553 static void event_queue_start(struct udev *udev) {
554 struct udev_list_node *loop;
556 udev_list_node_foreach(loop, &event_list) {
557 struct event *event = node_to_event(loop);
559 if (event->state != EVENT_QUEUED)
562 /* do not start event if parent or child event is still running */
563 if (is_devpath_busy(event))
570 static void event_queue_cleanup(struct udev *udev, enum event_state match_type) {
571 struct udev_list_node *loop, *tmp;
573 udev_list_node_foreach_safe(loop, tmp, &event_list) {
574 struct event *event = node_to_event(loop);
576 if (match_type != EVENT_UNDEF && match_type != event->state)
579 event_queue_delete(event);
583 static void worker_returned(int fd_worker) {
585 struct worker_message msg;
587 struct udev_list_node *loop;
589 size = recv(fd_worker, &msg, sizeof(struct worker_message), MSG_DONTWAIT);
590 if (size != sizeof(struct worker_message))
593 /* lookup worker who sent the signal */
594 udev_list_node_foreach(loop, &worker_list) {
595 struct worker *worker = node_to_worker(loop);
597 if (worker->pid != msg.pid)
600 /* worker returned */
602 worker->event->exitcode = msg.exitcode;
603 event_queue_delete(worker->event);
604 worker->event = NULL;
606 if (worker->state != WORKER_KILLED)
607 worker->state = WORKER_IDLE;
608 worker_unref(worker);
614 /* receive the udevd message from userspace */
615 static struct udev_ctrl_connection *handle_ctrl_msg(struct udev_ctrl *uctrl) {
616 struct udev *udev = udev_ctrl_get_udev(uctrl);
617 struct udev_ctrl_connection *ctrl_conn;
618 struct udev_ctrl_msg *ctrl_msg = NULL;
622 ctrl_conn = udev_ctrl_get_connection(uctrl);
623 if (ctrl_conn == NULL)
626 ctrl_msg = udev_ctrl_receive_msg(ctrl_conn);
627 if (ctrl_msg == NULL)
630 i = udev_ctrl_get_set_log_level(ctrl_msg);
632 log_debug("udevd message (SET_LOG_LEVEL) received, log_priority=%i", i);
633 log_set_max_level(i);
634 udev_set_log_priority(udev, i);
638 if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
639 log_debug("udevd message (STOP_EXEC_QUEUE) received");
640 stop_exec_queue = true;
643 if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
644 log_debug("udevd message (START_EXEC_QUEUE) received");
645 stop_exec_queue = false;
648 if (udev_ctrl_get_reload(ctrl_msg) > 0) {
649 log_debug("udevd message (RELOAD) received");
653 str = udev_ctrl_get_set_env(ctrl_msg);
661 val = strchr(key, '=');
665 if (val[0] == '\0') {
666 log_debug("udevd message (ENV) received, unset '%s'", key);
667 udev_add_property(udev, key, NULL);
669 log_debug("udevd message (ENV) received, set '%s=%s'", key, val);
670 udev_add_property(udev, key, val);
673 log_error("wrong key format '%s'", key);
680 i = udev_ctrl_get_set_children_max(ctrl_msg);
682 log_debug("udevd message (SET_MAX_CHILDREN) received, children_max=%i", i);
686 if (udev_ctrl_get_ping(ctrl_msg) > 0)
687 log_debug("udevd message (SYNC) received");
689 if (udev_ctrl_get_exit(ctrl_msg) > 0) {
690 log_debug("udevd message (EXIT) received");
692 /* keep reference to block the client until we exit */
693 udev_ctrl_connection_ref(ctrl_conn);
696 udev_ctrl_msg_unref(ctrl_msg);
697 return udev_ctrl_connection_unref(ctrl_conn);
700 static int synthesize_change(struct udev_device *dev) {
701 char filename[UTIL_PATH_SIZE];
704 if (streq_ptr("block", udev_device_get_subsystem(dev)) &&
705 streq_ptr("disk", udev_device_get_devtype(dev)) &&
706 !startswith(udev_device_get_sysname(dev), "dm-")) {
707 bool part_table_read = false;
708 bool has_partitions = false;
710 struct udev *udev = udev_device_get_udev(dev);
711 _cleanup_udev_enumerate_unref_ struct udev_enumerate *e = NULL;
712 struct udev_list_entry *item;
715 * Try to re-read the partition table. This only succeeds if
716 * none of the devices is busy. The kernel returns 0 if no
717 * partition table is found, and we will not get an event for
720 fd = open(udev_device_get_devnode(dev), O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
722 r = flock(fd, LOCK_EX|LOCK_NB);
724 r = ioctl(fd, BLKRRPART, 0);
728 part_table_read = true;
731 /* search for partitions */
732 e = udev_enumerate_new(udev);
736 r = udev_enumerate_add_match_parent(e, dev);
740 r = udev_enumerate_add_match_subsystem(e, "block");
744 r = udev_enumerate_scan_devices(e);
748 udev_list_entry_foreach(item, udev_enumerate_get_list_entry(e)) {
749 _cleanup_udev_device_unref_ struct udev_device *d = NULL;
751 d = udev_device_new_from_syspath(udev, udev_list_entry_get_name(item));
755 if (!streq_ptr("partition", udev_device_get_devtype(d)))
758 has_partitions = true;
763 * We have partitions and re-read the table, the kernel already sent
764 * out a "change" event for the disk, and "remove/add" for all
767 if (part_table_read && has_partitions)
771 * We have partitions but re-reading the partition table did not
772 * work, synthesize "change" for the disk and all partitions.
774 log_debug("device %s closed, synthesising 'change'", udev_device_get_devnode(dev));
775 strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
776 write_string_file(filename, "change");
778 udev_list_entry_foreach(item, udev_enumerate_get_list_entry(e)) {
779 _cleanup_udev_device_unref_ struct udev_device *d = NULL;
781 d = udev_device_new_from_syspath(udev, udev_list_entry_get_name(item));
785 if (!streq_ptr("partition", udev_device_get_devtype(d)))
788 log_debug("device %s closed, synthesising partition '%s' 'change'",
789 udev_device_get_devnode(dev), udev_device_get_devnode(d));
790 strscpyl(filename, sizeof(filename), udev_device_get_syspath(d), "/uevent", NULL);
791 write_string_file(filename, "change");
797 log_debug("device %s closed, synthesising 'change'", udev_device_get_devnode(dev));
798 strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
799 write_string_file(filename, "change");
804 static int handle_inotify(struct udev *udev) {
807 struct inotify_event *ev;
810 r = ioctl(fd_inotify, FIONREAD, &nbytes);
811 if (r < 0 || nbytes <= 0)
814 buf = malloc(nbytes);
816 log_error("error getting buffer for inotify");
820 nbytes = read(fd_inotify, buf, nbytes);
822 for (pos = 0; pos < nbytes; pos += sizeof(struct inotify_event) + ev->len) {
823 struct udev_device *dev;
825 ev = (struct inotify_event *)(buf + pos);
826 dev = udev_watch_lookup(udev, ev->wd);
830 log_debug("inotify event: %x for %s", ev->mask, udev_device_get_devnode(dev));
831 if (ev->mask & IN_CLOSE_WRITE)
832 synthesize_change(dev);
833 else if (ev->mask & IN_IGNORED)
834 udev_watch_end(udev, dev);
836 udev_device_unref(dev);
843 static void handle_signal(struct udev *udev, int signo) {
853 struct udev_list_node *loop, *tmp;
855 pid = waitpid(-1, &status, WNOHANG);
859 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
860 struct worker *worker = node_to_worker(loop);
862 if (worker->pid != pid)
864 log_debug("worker [%u] exit", pid);
866 if (WIFEXITED(status)) {
867 if (WEXITSTATUS(status) != 0)
868 log_error("worker [%u] exit with return code %i",
869 pid, WEXITSTATUS(status));
870 } else if (WIFSIGNALED(status)) {
871 log_error("worker [%u] terminated by signal %i (%s)",
872 pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
873 } else if (WIFSTOPPED(status)) {
874 log_error("worker [%u] stopped", pid);
875 } else if (WIFCONTINUED(status)) {
876 log_error("worker [%u] continued", pid);
878 log_error("worker [%u] exit with status 0x%04x", pid, status);
881 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
883 log_error("worker [%u] failed while handling '%s'",
884 pid, worker->event->devpath);
885 worker->event->exitcode = -32;
886 event_queue_delete(worker->event);
888 /* drop reference taken for state 'running' */
889 worker_unref(worker);
892 worker_unref(worker);
903 static int systemd_fds(struct udev *udev, int *rctrl, int *rnetlink) {
904 int ctrl = -1, netlink = -1;
907 n = sd_listen_fds(true);
911 for (fd = SD_LISTEN_FDS_START; fd < n + SD_LISTEN_FDS_START; fd++) {
912 if (sd_is_socket(fd, AF_LOCAL, SOCK_SEQPACKET, -1)) {
919 if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1)) {
929 if (ctrl < 0 || netlink < 0)
932 log_debug("ctrl=%i netlink=%i", ctrl, netlink);
939 * read the kernel commandline, in case we need to get into debug mode
940 * udev.log-priority=<level> syslog priority
941 * udev.children-max=<number of workers> events are fully serialized if set to 1
942 * udev.exec-delay=<number of seconds> delay execution of every executed program
944 static void kernel_cmdline_options(struct udev *udev) {
945 _cleanup_free_ char *line = NULL;
946 const char *word, *state;
950 r = proc_cmdline(&line);
952 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
956 FOREACH_WORD_QUOTED(word, l, line, state) {
959 s = strndup(word, l);
963 /* accept the same options for the initrd, prefixed with "rd." */
964 if (in_initrd() && startswith(s, "rd."))
969 if (startswith(opt, "udev.log-priority=")) {
972 prio = util_log_priority(opt + 18);
973 log_set_max_level(prio);
974 udev_set_log_priority(udev, prio);
975 } else if (startswith(opt, "udev.children-max=")) {
976 children_max = strtoul(opt + 18, NULL, 0);
977 } else if (startswith(opt, "udev.exec-delay=")) {
978 exec_delay = strtoul(opt + 16, NULL, 0);
979 } else if (startswith(opt, "udev.event-timeout=")) {
980 event_timeout_usec = strtoul(opt + 16, NULL, 0) * USEC_PER_SEC;
987 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 { "event-timeout", required_argument, NULL, 't' },
998 { "resolve-names", required_argument, NULL, 'N' },
999 { "help", no_argument, NULL, 'h' },
1000 { "version", no_argument, NULL, 'V' },
1004 int fd_netlink = -1;
1006 struct epoll_event ep_ctrl, ep_inotify, ep_signal, ep_netlink, ep_worker;
1007 struct udev_ctrl_connection *ctrl_conn = NULL;
1014 log_set_target(LOG_TARGET_AUTO);
1015 log_parse_environment();
1018 udev_set_log_fn(udev, udev_main_log);
1019 log_set_max_level(udev_get_log_priority(udev));
1021 log_debug("version %s", VERSION);
1027 option = getopt_long(argc, argv, "c:de:DtN:hV", options, NULL);
1036 children_max = strtoul(optarg, NULL, 0);
1039 exec_delay = strtoul(optarg, NULL, 0);
1042 event_timeout_usec = strtoul(optarg, NULL, 0) * USEC_PER_SEC;
1046 log_set_max_level(LOG_DEBUG);
1047 udev_set_log_priority(udev, LOG_DEBUG);
1050 if (streq(optarg, "early")) {
1052 } else if (streq(optarg, "late")) {
1054 } else if (streq(optarg, "never")) {
1057 fprintf(stderr, "resolve-names must be early, late or never\n");
1058 log_error("resolve-names must be early, late or never");
1063 printf("Usage: udevd OPTIONS\n"
1066 " --children-max=<maximum number of workers>\n"
1067 " --exec-delay=<seconds to wait before executing RUN=>\n"
1068 " --event-timeout=<seconds to wait before terminating an event>\n"
1069 " --resolve-names=early|late|never\n"
1075 printf("%s\n", VERSION);
1082 kernel_cmdline_options(udev);
1084 if (getuid() != 0) {
1085 fprintf(stderr, "root privileges required\n");
1086 log_error("root privileges required");
1090 /* set umask before creating any file/directory */
1094 mkdir("/run/udev", 0755);
1098 /* before opening new files, make sure std{in,out,err} fds are in a sane state */
1102 fd = open("/dev/null", O_RDWR);
1104 if (write(STDOUT_FILENO, 0, 0) < 0)
1105 dup2(fd, STDOUT_FILENO);
1106 if (write(STDERR_FILENO, 0, 0) < 0)
1107 dup2(fd, STDERR_FILENO);
1108 if (fd > STDERR_FILENO)
1111 fprintf(stderr, "cannot open /dev/null\n");
1112 log_error("cannot open /dev/null");
1116 if (systemd_fds(udev, &fd_ctrl, &fd_netlink) >= 0) {
1117 /* get control and netlink socket from systemd */
1118 udev_ctrl = udev_ctrl_new_from_fd(udev, fd_ctrl);
1119 if (udev_ctrl == NULL) {
1120 log_error("error taking over udev control socket");
1125 monitor = udev_monitor_new_from_netlink_fd(udev, "kernel", fd_netlink);
1126 if (monitor == NULL) {
1127 log_error("error taking over netlink socket");
1132 /* get our own cgroup, we regularly kill everything udev has left behind */
1133 if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &udev_cgroup) < 0)
1136 /* open control and netlink socket */
1137 udev_ctrl = udev_ctrl_new(udev);
1138 if (udev_ctrl == NULL) {
1139 fprintf(stderr, "error initializing udev control socket");
1140 log_error("error initializing udev control socket");
1144 fd_ctrl = udev_ctrl_get_fd(udev_ctrl);
1146 monitor = udev_monitor_new_from_netlink(udev, "kernel");
1147 if (monitor == NULL) {
1148 fprintf(stderr, "error initializing netlink socket\n");
1149 log_error("error initializing netlink socket");
1153 fd_netlink = udev_monitor_get_fd(monitor);
1156 if (udev_monitor_enable_receiving(monitor) < 0) {
1157 fprintf(stderr, "error binding netlink socket\n");
1158 log_error("error binding netlink socket");
1163 if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
1164 fprintf(stderr, "error binding udev control socket\n");
1165 log_error("error binding udev control socket");
1170 udev_monitor_set_receive_buffer_size(monitor, 128 * 1024 * 1024);
1180 log_error("fork of daemon failed: %m");
1185 goto exit_daemonize;
1190 write_string_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");
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");
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");
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");
1246 memzero(&ep_ctrl, sizeof(struct epoll_event));
1247 ep_ctrl.events = EPOLLIN;
1248 ep_ctrl.data.fd = fd_ctrl;
1250 memzero(&ep_inotify, sizeof(struct epoll_event));
1251 ep_inotify.events = EPOLLIN;
1252 ep_inotify.data.fd = fd_inotify;
1254 memzero(&ep_signal, sizeof(struct epoll_event));
1255 ep_signal.events = EPOLLIN;
1256 ep_signal.data.fd = fd_signal;
1258 memzero(&ep_netlink, sizeof(struct epoll_event));
1259 ep_netlink.events = EPOLLIN;
1260 ep_netlink.data.fd = fd_netlink;
1262 memzero(&ep_worker, 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");
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");
1280 if (children_max <= 0) {
1285 if (sched_getaffinity(0, sizeof (cpu_set), &cpu_set) == 0) {
1286 children_max += CPU_COUNT(&cpu_set) * 2;
1289 log_debug("set children_max to %u", children_max);
1291 rc = udev_rules_apply_static_dev_perms(rules);
1293 log_error("failed to apply permissions on static device nodes - %s", strerror(-rc));
1295 udev_list_node_init(&event_list);
1296 udev_list_node_init(&worker_list);
1299 static usec_t last_usec;
1300 struct epoll_event ev[8];
1303 bool is_worker, is_signal, is_inotify, is_netlink, is_ctrl;
1307 /* close sources of new events and discard buffered events */
1309 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_ctrl, NULL);
1312 if (monitor != NULL) {
1313 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_netlink, NULL);
1314 udev_monitor_unref(monitor);
1317 if (fd_inotify >= 0) {
1318 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_inotify, NULL);
1323 /* discard queued events and kill workers */
1324 event_queue_cleanup(udev, EVENT_QUEUED);
1327 /* exit after all has cleaned up */
1328 if (udev_list_node_is_empty(&event_list) && children == 0)
1331 /* timeout at exit for workers to finish */
1332 timeout = 30 * MSEC_PER_SEC;
1333 } else if (udev_list_node_is_empty(&event_list) && children == 0) {
1337 /* cleanup possible left-over processes in our cgroup */
1339 cg_kill(SYSTEMD_CGROUP_CONTROLLER, udev_cgroup, SIGKILL, false, true, NULL);
1341 /* kill idle or hanging workers */
1342 timeout = 3 * MSEC_PER_SEC;
1345 /* tell settle that we are busy or idle */
1346 if (!udev_list_node_is_empty(&event_list)) {
1349 fd = open("/run/udev/queue", O_WRONLY|O_CREAT|O_CLOEXEC|O_TRUNC|O_NOFOLLOW, 0444);
1353 unlink("/run/udev/queue");
1356 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
1361 struct udev_list_node *loop;
1365 log_error("timeout, giving up waiting for workers to finish");
1369 /* kill idle workers */
1370 if (udev_list_node_is_empty(&event_list)) {
1371 log_debug("cleanup idle workers");
1375 /* check for hanging events */
1376 udev_list_node_foreach(loop, &worker_list) {
1377 struct worker *worker = node_to_worker(loop);
1379 if (worker->state != WORKER_RUNNING)
1382 if ((now(CLOCK_MONOTONIC) - worker->event_start_usec) > event_timeout_usec) {
1383 log_error("worker [%u] %s timeout; kill it", worker->pid, worker->event->devpath);
1384 kill(worker->pid, SIGKILL);
1385 worker->state = WORKER_KILLED;
1387 /* drop reference taken for state 'running' */
1388 worker_unref(worker);
1389 log_error("seq %llu '%s' killed", udev_device_get_seqnum(worker->event->dev), worker->event->devpath);
1390 worker->event->exitcode = -64;
1391 event_queue_delete(worker->event);
1392 worker->event = NULL;
1398 is_worker = is_signal = is_inotify = is_netlink = is_ctrl = false;
1399 for (i = 0; i < fdcount; i++) {
1400 if (ev[i].data.fd == fd_worker && ev[i].events & EPOLLIN)
1402 else if (ev[i].data.fd == fd_netlink && ev[i].events & EPOLLIN)
1404 else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN)
1406 else if (ev[i].data.fd == fd_inotify && ev[i].events & EPOLLIN)
1408 else if (ev[i].data.fd == fd_ctrl && ev[i].events & EPOLLIN)
1412 /* check for changed config, every 3 seconds at most */
1413 if ((now(CLOCK_MONOTONIC) - last_usec) > 3 * USEC_PER_SEC) {
1414 if (udev_rules_check_timestamp(rules))
1416 if (udev_builtin_validate(udev))
1419 last_usec = now(CLOCK_MONOTONIC);
1422 /* reload requested, HUP signal received, rules changed, builtin changed */
1425 rules = udev_rules_unref(rules);
1426 udev_builtin_exit(udev);
1430 /* event has finished */
1432 worker_returned(fd_worker);
1435 struct udev_device *dev;
1437 dev = udev_monitor_receive_device(monitor);
1439 udev_device_set_usec_initialized(dev, now(CLOCK_MONOTONIC));
1440 if (event_queue_insert(dev) < 0)
1441 udev_device_unref(dev);
1445 /* start new events */
1446 if (!udev_list_node_is_empty(&event_list) && !udev_exit && !stop_exec_queue) {
1447 udev_builtin_init(udev);
1449 rules = udev_rules_new(udev, resolve_names);
1451 event_queue_start(udev);
1455 struct signalfd_siginfo fdsi;
1458 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
1459 if (size == sizeof(struct signalfd_siginfo))
1460 handle_signal(udev, fdsi.ssi_signo);
1463 /* we are shutting down, the events below are not handled anymore */
1467 /* device node watch */
1469 handle_inotify(udev);
1472 * This needs to be after the inotify handling, to make sure,
1473 * that the ping is send back after the possibly generated
1474 * "change" events by the inotify device node watch.
1476 * A single time we may receive a client connection which we need to
1477 * keep open to block the client. It will be closed right before we
1481 ctrl_conn = handle_ctrl_msg(udev_ctrl);
1486 udev_ctrl_cleanup(udev_ctrl);
1487 unlink("/run/udev/queue");
1491 worker_list_cleanup(udev);
1492 event_queue_cleanup(udev, EVENT_UNDEF);
1493 udev_rules_unref(rules);
1494 udev_builtin_exit(udev);
1497 if (worker_watch[READ_END] >= 0)
1498 close(worker_watch[READ_END]);
1499 if (worker_watch[WRITE_END] >= 0)
1500 close(worker_watch[WRITE_END]);
1501 udev_monitor_unref(monitor);
1502 udev_ctrl_connection_unref(ctrl_conn);
1503 udev_ctrl_unref(udev_ctrl);