2 * Copyright (C) 2004-2012 Kay Sievers <kay.sievers@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;
102 static inline struct event *node_to_event(struct udev_list_node *node)
104 return container_of(node, struct event, node);
107 static void event_queue_cleanup(struct udev *udev, enum event_state type);
117 struct udev_list_node node;
121 struct udev_monitor *monitor;
122 enum worker_state state;
124 unsigned long long event_start_usec;
127 /* passed from worker to main process */
128 struct worker_message {
133 static inline struct worker *node_to_worker(struct udev_list_node *node)
135 return container_of(node, struct worker, node);
138 static void event_queue_delete(struct event *event, bool export)
140 udev_list_node_remove(&event->node);
143 udev_queue_export_device_finished(udev_queue_export, event->dev);
144 log_debug("seq %llu done with %i\n", udev_device_get_seqnum(event->dev), event->exitcode);
146 udev_device_unref(event->dev);
150 static struct worker *worker_ref(struct worker *worker)
156 static void worker_cleanup(struct worker *worker)
158 udev_list_node_remove(&worker->node);
159 udev_monitor_unref(worker->monitor);
164 static void worker_unref(struct worker *worker)
167 if (worker->refcount > 0)
169 log_debug("worker [%u] cleaned up\n", worker->pid);
170 worker_cleanup(worker);
173 static void worker_list_cleanup(struct udev *udev)
175 struct udev_list_node *loop, *tmp;
177 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
178 struct worker *worker = node_to_worker(loop);
180 worker_cleanup(worker);
184 static void worker_new(struct event *event)
186 struct udev *udev = event->udev;
187 struct worker *worker;
188 struct udev_monitor *worker_monitor;
191 /* listen for new events */
192 worker_monitor = udev_monitor_new_from_netlink(udev, NULL);
193 if (worker_monitor == NULL)
195 /* allow the main daemon netlink address to send devices to the worker */
196 udev_monitor_allow_unicast_sender(worker_monitor, monitor);
197 udev_monitor_enable_receiving(worker_monitor);
199 worker = calloc(1, sizeof(struct worker));
200 if (worker == NULL) {
201 udev_monitor_unref(worker_monitor);
204 /* worker + event reference */
205 worker->refcount = 2;
211 struct udev_device *dev = NULL;
213 struct epoll_event ep_signal, ep_monitor;
215 int rc = EXIT_SUCCESS;
217 /* take initial device from queue */
222 worker_list_cleanup(udev);
223 event_queue_cleanup(udev, EVENT_UNDEF);
224 udev_queue_export_unref(udev_queue_export);
225 udev_monitor_unref(monitor);
226 udev_ctrl_unref(udev_ctrl);
229 close(worker_watch[READ_END]);
232 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
234 log_error("error creating signalfd %m\n");
239 fd_ep = epoll_create1(EPOLL_CLOEXEC);
241 log_error("error creating epoll fd: %m\n");
246 memset(&ep_signal, 0, sizeof(struct epoll_event));
247 ep_signal.events = EPOLLIN;
248 ep_signal.data.fd = fd_signal;
250 fd_monitor = udev_monitor_get_fd(worker_monitor);
251 memset(&ep_monitor, 0, sizeof(struct epoll_event));
252 ep_monitor.events = EPOLLIN;
253 ep_monitor.data.fd = fd_monitor;
255 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
256 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_monitor, &ep_monitor) < 0) {
257 log_error("fail to add fds to epoll: %m\n");
262 /* request TERM signal if parent exits */
263 prctl(PR_SET_PDEATHSIG, SIGTERM);
266 struct udev_event *udev_event;
267 struct worker_message msg;
270 log_debug("seq %llu running\n", udev_device_get_seqnum(dev));
271 udev_event = udev_event_new(dev);
272 if (udev_event == NULL) {
277 /* needed for SIGCHLD/SIGTERM in spawn() */
278 udev_event->fd_signal = fd_signal;
281 udev_event->exec_delay = exec_delay;
283 /* apply rules, create node, symlinks */
284 err = udev_event_execute_rules(udev_event, rules, &sigmask_orig);
287 udev_event_execute_run(udev_event, &sigmask_orig);
289 /* apply/restore inotify watch */
290 if (err == 0 && udev_event->inotify_watch) {
291 udev_watch_begin(udev, dev);
292 udev_device_update_db(dev);
295 /* send processed event back to libudev listeners */
296 udev_monitor_send_device(worker_monitor, NULL, dev);
298 /* send udevd the result of the event execution */
299 memset(&msg, 0, sizeof(struct worker_message));
303 send(worker_watch[WRITE_END], &msg, sizeof(struct worker_message), 0);
305 log_debug("seq %llu processed with %i\n", udev_device_get_seqnum(dev), err);
307 udev_device_unref(dev);
310 if (udev_event->sigterm) {
311 udev_event_unref(udev_event);
315 udev_event_unref(udev_event);
317 /* wait for more device messages from main udevd, or term signal */
318 while (dev == NULL) {
319 struct epoll_event ev[4];
323 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), -1);
327 log_error("failed to poll: %m\n");
331 for (i = 0; i < fdcount; i++) {
332 if (ev[i].data.fd == fd_monitor && ev[i].events & EPOLLIN) {
333 dev = udev_monitor_receive_device(worker_monitor);
335 } else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN) {
336 struct signalfd_siginfo fdsi;
339 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
340 if (size != sizeof(struct signalfd_siginfo))
342 switch (fdsi.ssi_signo) {
351 udev_device_unref(dev);
357 close(worker_watch[WRITE_END]);
358 udev_rules_unref(rules);
359 udev_builtin_exit(udev);
360 udev_monitor_unref(worker_monitor);
366 udev_monitor_unref(worker_monitor);
367 event->state = EVENT_QUEUED;
369 log_error("fork of child failed: %m\n");
372 /* close monitor, but keep address around */
373 udev_monitor_disconnect(worker_monitor);
374 worker->monitor = worker_monitor;
376 worker->state = WORKER_RUNNING;
377 worker->event_start_usec = now_usec();
378 worker->event = event;
379 event->state = EVENT_RUNNING;
380 udev_list_node_append(&worker->node, &worker_list);
382 log_debug("seq %llu forked new worker [%u]\n", udev_device_get_seqnum(event->dev), pid);
387 static void event_run(struct event *event)
389 struct udev_list_node *loop;
391 udev_list_node_foreach(loop, &worker_list) {
392 struct worker *worker = node_to_worker(loop);
395 if (worker->state != WORKER_IDLE)
398 count = udev_monitor_send_device(monitor, worker->monitor, event->dev);
400 log_error("worker [%u] did not accept message %zi (%m), kill it\n", worker->pid, count);
401 kill(worker->pid, SIGKILL);
402 worker->state = WORKER_KILLED;
406 worker->event = event;
407 worker->state = WORKER_RUNNING;
408 worker->event_start_usec = now_usec();
409 event->state = EVENT_RUNNING;
413 if (children >= children_max) {
414 if (children_max > 1)
415 log_debug("maximum number (%i) of children reached\n", children);
419 /* start new worker and pass initial device */
423 static int event_queue_insert(struct udev_device *dev)
427 event = calloc(1, sizeof(struct event));
431 event->udev = udev_device_get_udev(dev);
433 event->seqnum = udev_device_get_seqnum(dev);
434 event->devpath = udev_device_get_devpath(dev);
435 event->devpath_len = strlen(event->devpath);
436 event->devpath_old = udev_device_get_devpath_old(dev);
437 event->devnum = udev_device_get_devnum(dev);
438 event->is_block = (strcmp("block", udev_device_get_subsystem(dev)) == 0);
439 event->ifindex = udev_device_get_ifindex(dev);
441 udev_queue_export_device_queued(udev_queue_export, dev);
442 log_debug("seq %llu queued, '%s' '%s'\n", udev_device_get_seqnum(dev),
443 udev_device_get_action(dev), udev_device_get_subsystem(dev));
445 event->state = EVENT_QUEUED;
446 udev_list_node_append(&event->node, &event_list);
450 static void worker_kill(struct udev *udev)
452 struct udev_list_node *loop;
454 udev_list_node_foreach(loop, &worker_list) {
455 struct worker *worker = node_to_worker(loop);
457 if (worker->state == WORKER_KILLED)
460 worker->state = WORKER_KILLED;
461 kill(worker->pid, SIGTERM);
465 /* lookup event for identical, parent, child device */
466 static bool is_devpath_busy(struct event *event)
468 struct udev_list_node *loop;
471 /* check if queue contains events we depend on */
472 udev_list_node_foreach(loop, &event_list) {
473 struct event *loop_event = node_to_event(loop);
475 /* we already found a later event, earlier can not block us, no need to check again */
476 if (loop_event->seqnum < event->delaying_seqnum)
479 /* event we checked earlier still exists, no need to check again */
480 if (loop_event->seqnum == event->delaying_seqnum)
483 /* found ourself, no later event can block us */
484 if (loop_event->seqnum >= event->seqnum)
487 /* check major/minor */
488 if (major(event->devnum) != 0 && event->devnum == loop_event->devnum && event->is_block == loop_event->is_block)
491 /* check network device ifindex */
492 if (event->ifindex != 0 && event->ifindex == loop_event->ifindex)
495 /* check our old name */
496 if (event->devpath_old != NULL && strcmp(loop_event->devpath, event->devpath_old) == 0) {
497 event->delaying_seqnum = loop_event->seqnum;
501 /* compare devpath */
502 common = MIN(loop_event->devpath_len, event->devpath_len);
504 /* one devpath is contained in the other? */
505 if (memcmp(loop_event->devpath, event->devpath, common) != 0)
508 /* identical device event found */
509 if (loop_event->devpath_len == event->devpath_len) {
510 /* devices names might have changed/swapped in the meantime */
511 if (major(event->devnum) != 0 && (event->devnum != loop_event->devnum || event->is_block != loop_event->is_block))
513 if (event->ifindex != 0 && event->ifindex != loop_event->ifindex)
515 event->delaying_seqnum = loop_event->seqnum;
519 /* parent device event found */
520 if (event->devpath[common] == '/') {
521 event->delaying_seqnum = loop_event->seqnum;
525 /* child device event found */
526 if (loop_event->devpath[common] == '/') {
527 event->delaying_seqnum = loop_event->seqnum;
531 /* no matching device */
538 static void event_queue_start(struct udev *udev)
540 struct udev_list_node *loop;
542 udev_list_node_foreach(loop, &event_list) {
543 struct event *event = node_to_event(loop);
545 if (event->state != EVENT_QUEUED)
548 /* do not start event if parent or child event is still running */
549 if (is_devpath_busy(event))
556 static void event_queue_cleanup(struct udev *udev, enum event_state match_type)
558 struct udev_list_node *loop, *tmp;
560 udev_list_node_foreach_safe(loop, tmp, &event_list) {
561 struct event *event = node_to_event(loop);
563 if (match_type != EVENT_UNDEF && match_type != event->state)
566 event_queue_delete(event, false);
570 static void worker_returned(int fd_worker)
573 struct worker_message msg;
575 struct udev_list_node *loop;
577 size = recv(fd_worker, &msg, sizeof(struct worker_message), MSG_DONTWAIT);
578 if (size != sizeof(struct worker_message))
581 /* lookup worker who sent the signal */
582 udev_list_node_foreach(loop, &worker_list) {
583 struct worker *worker = node_to_worker(loop);
585 if (worker->pid != msg.pid)
588 /* worker returned */
590 worker->event->exitcode = msg.exitcode;
591 event_queue_delete(worker->event, true);
592 worker->event = NULL;
594 if (worker->state != WORKER_KILLED)
595 worker->state = WORKER_IDLE;
596 worker_unref(worker);
602 /* receive the udevd message from userspace */
603 static struct udev_ctrl_connection *handle_ctrl_msg(struct udev_ctrl *uctrl)
605 struct udev *udev = udev_ctrl_get_udev(uctrl);
606 struct udev_ctrl_connection *ctrl_conn;
607 struct udev_ctrl_msg *ctrl_msg = NULL;
611 ctrl_conn = udev_ctrl_get_connection(uctrl);
612 if (ctrl_conn == NULL)
615 ctrl_msg = udev_ctrl_receive_msg(ctrl_conn);
616 if (ctrl_msg == NULL)
619 i = udev_ctrl_get_set_log_level(ctrl_msg);
621 log_debug("udevd message (SET_LOG_PRIORITY) received, log_priority=%i\n", i);
622 log_set_max_level(i);
623 udev_set_log_priority(udev, i);
627 if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
628 log_debug("udevd message (STOP_EXEC_QUEUE) received\n");
629 stop_exec_queue = true;
632 if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
633 log_debug("udevd message (START_EXEC_QUEUE) received\n");
634 stop_exec_queue = false;
637 if (udev_ctrl_get_reload(ctrl_msg) > 0) {
638 log_debug("udevd message (RELOAD) received\n");
642 str = udev_ctrl_get_set_env(ctrl_msg);
650 val = strchr(key, '=');
654 if (val[0] == '\0') {
655 log_debug("udevd message (ENV) received, unset '%s'\n", key);
656 udev_add_property(udev, key, NULL);
658 log_debug("udevd message (ENV) received, set '%s=%s'\n", key, val);
659 udev_add_property(udev, key, val);
662 log_error("wrong key format '%s'\n", key);
669 i = udev_ctrl_get_set_children_max(ctrl_msg);
671 log_debug("udevd message (SET_MAX_CHILDREN) received, children_max=%i\n", i);
675 if (udev_ctrl_get_ping(ctrl_msg) > 0)
676 log_debug("udevd message (SYNC) received\n");
678 if (udev_ctrl_get_exit(ctrl_msg) > 0) {
679 log_debug("udevd message (EXIT) received\n");
681 /* keep reference to block the client until we exit */
682 udev_ctrl_connection_ref(ctrl_conn);
685 udev_ctrl_msg_unref(ctrl_msg);
686 return udev_ctrl_connection_unref(ctrl_conn);
689 /* read inotify messages */
690 static int handle_inotify(struct udev *udev)
694 struct inotify_event *ev;
696 if ((ioctl(fd_inotify, FIONREAD, &nbytes) < 0) || (nbytes <= 0))
699 buf = malloc(nbytes);
701 log_error("error getting buffer for inotify\n");
705 nbytes = read(fd_inotify, buf, nbytes);
707 for (pos = 0; pos < nbytes; pos += sizeof(struct inotify_event) + ev->len) {
708 struct udev_device *dev;
710 ev = (struct inotify_event *)(buf + pos);
711 dev = udev_watch_lookup(udev, ev->wd);
713 log_debug("inotify event: %x for %s\n", ev->mask, udev_device_get_devnode(dev));
714 if (ev->mask & IN_CLOSE_WRITE) {
715 char filename[UTIL_PATH_SIZE];
718 log_debug("device %s closed, synthesising 'change'\n", udev_device_get_devnode(dev));
719 util_strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
720 fd = open(filename, O_WRONLY);
722 if (write(fd, "change", 6) < 0)
723 log_debug("error writing uevent: %m\n");
727 if (ev->mask & IN_IGNORED)
728 udev_watch_end(udev, dev);
730 udev_device_unref(dev);
739 static void handle_signal(struct udev *udev, int signo)
750 struct udev_list_node *loop, *tmp;
752 pid = waitpid(-1, &status, WNOHANG);
756 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
757 struct worker *worker = node_to_worker(loop);
759 if (worker->pid != pid)
761 log_debug("worker [%u] exit\n", pid);
763 if (WIFEXITED(status)) {
764 if (WEXITSTATUS(status) != 0)
765 log_error("worker [%u] exit with return code %i\n", pid, WEXITSTATUS(status));
766 } else if (WIFSIGNALED(status)) {
767 log_error("worker [%u] terminated by signal %i (%s)\n",
768 pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
769 } else if (WIFSTOPPED(status)) {
770 log_error("worker [%u] stopped\n", pid);
771 } else if (WIFCONTINUED(status)) {
772 log_error("worker [%u] continued\n", pid);
774 log_error("worker [%u] exit with status 0x%04x\n", pid, status);
777 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
779 log_error("worker [%u] failed while handling '%s'\n",
780 pid, worker->event->devpath);
781 worker->event->exitcode = -32;
782 event_queue_delete(worker->event, true);
783 /* drop reference taken for state 'running' */
784 worker_unref(worker);
787 worker_unref(worker);
798 static void static_dev_create_from_modules(struct udev *udev)
800 struct utsname kernel;
801 char modules[UTIL_PATH_SIZE];
806 util_strscpyl(modules, sizeof(modules), "/lib/modules/", kernel.release, "/modules.devname", NULL);
807 f = fopen(modules, "r");
811 while (fgets(buf, sizeof(buf), f) != NULL) {
819 char filename[UTIL_PATH_SIZE];
825 s = strchr(modname, ' ');
831 s = strchr(devname, ' ');
837 s = strchr(devno, ' ');
839 s = strchr(devno, '\n');
842 if (sscanf(devno, "%c%u:%u", &type, &maj, &min) != 3)
847 else if (type == 'b')
852 util_strscpyl(filename, sizeof(filename), "/dev/", devname, NULL);
853 mkdir_parents(filename, 0755);
854 label_context_set(filename, mode);
855 log_debug("mknod '%s' %c%u:%u\n", filename, type, maj, min);
856 if (mknod(filename, mode, makedev(maj, min)) < 0 && errno == EEXIST)
857 utimensat(AT_FDCWD, filename, NULL, 0);
858 label_context_clear();
864 static int mem_size_mb(void)
868 long int memsize = -1;
870 f = fopen("/proc/meminfo", "r");
874 while (fgets(buf, sizeof(buf), f) != NULL) {
877 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
878 memsize = value / 1024;
887 static int convert_db(struct udev *udev)
889 char filename[UTIL_PATH_SIZE];
891 struct udev_enumerate *udev_enumerate;
892 struct udev_list_entry *list_entry;
894 /* current database */
895 if (access("/run/udev/data", F_OK) >= 0)
898 /* make sure we do not get here again */
899 mkdir_parents("/run/udev/data", 0755);
900 mkdir(filename, 0755);
903 util_strscpyl(filename, sizeof(filename), "/dev/.udev/db", NULL);
904 if (access(filename, F_OK) < 0)
907 f = fopen("/dev/kmsg", "w");
909 fprintf(f, "<30>udevd[%u]: converting old udev database\n", getpid());
913 udev_enumerate = udev_enumerate_new(udev);
914 if (udev_enumerate == NULL)
916 udev_enumerate_scan_devices(udev_enumerate);
917 udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(udev_enumerate)) {
918 struct udev_device *device;
920 device = udev_device_new_from_syspath(udev, udev_list_entry_get_name(list_entry));
924 /* try to find the old database for devices without a current one */
925 if (udev_device_read_db(device, NULL) < 0) {
929 char devpath[UTIL_PATH_SIZE];
930 char from[UTIL_PATH_SIZE];
934 /* find database in old location */
935 id = udev_device_get_id_filename(device);
936 util_strscpyl(from, sizeof(from), "/dev/.udev/db/", id, NULL);
937 if (lstat(from, &stats) == 0) {
939 udev_device_read_db(device, from);
945 /* find old database with $subsys:$sysname name */
946 util_strscpyl(from, sizeof(from), "/dev/.udev/db/",
947 udev_device_get_subsystem(device), ":", udev_device_get_sysname(device), NULL);
948 if (lstat(from, &stats) == 0) {
950 udev_device_read_db(device, from);
956 /* find old database with the encoded devpath name */
957 util_path_encode(udev_device_get_devpath(device), devpath, sizeof(devpath));
958 util_strscpyl(from, sizeof(from), "/dev/.udev/db/", devpath, NULL);
959 if (lstat(from, &stats) == 0) {
961 udev_device_read_db(device, from);
967 /* write out new database */
969 udev_device_update_db(device);
971 udev_device_unref(device);
973 udev_enumerate_unref(udev_enumerate);
977 static int systemd_fds(struct udev *udev, int *rctrl, int *rnetlink)
979 int ctrl = -1, netlink = -1;
982 n = sd_listen_fds(true);
986 for (fd = SD_LISTEN_FDS_START; fd < n + SD_LISTEN_FDS_START; fd++) {
987 if (sd_is_socket(fd, AF_LOCAL, SOCK_SEQPACKET, -1)) {
994 if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1)) {
1004 if (ctrl < 0 || netlink < 0)
1007 log_debug("ctrl=%i netlink=%i\n", ctrl, netlink);
1009 *rnetlink = netlink;
1013 int main(int argc, char *argv[])
1018 int daemonize = false;
1019 int resolve_names = 1;
1020 static const struct option options[] = {
1021 { "daemon", no_argument, NULL, 'd' },
1022 { "debug", no_argument, NULL, 'D' },
1023 { "children-max", required_argument, NULL, 'c' },
1024 { "exec-delay", required_argument, NULL, 'e' },
1025 { "resolve-names", required_argument, NULL, 'N' },
1026 { "help", no_argument, NULL, 'h' },
1027 { "version", no_argument, NULL, 'V' },
1031 int fd_netlink = -1;
1033 const char *prefixes[] = { "/dev", "/run", NULL };
1034 struct epoll_event ep_ctrl, ep_inotify, ep_signal, ep_netlink, ep_worker;
1035 struct udev_ctrl_connection *ctrl_conn = NULL;
1043 log_parse_environment();
1044 udev_set_log_fn(udev, udev_main_log);
1045 log_debug("version %s\n", VERSION);
1046 label_init(prefixes);
1051 option = getopt_long(argc, argv, "c:deDtN:hV", options, NULL);
1060 children_max = strtoul(optarg, NULL, 0);
1063 exec_delay = strtoul(optarg, NULL, 0);
1067 log_set_max_level(LOG_DEBUG);
1068 udev_set_log_priority(udev, LOG_INFO);
1071 if (strcmp (optarg, "early") == 0) {
1073 } else if (strcmp (optarg, "late") == 0) {
1075 } else if (strcmp (optarg, "never") == 0) {
1078 fprintf(stderr, "resolve-names must be early, late or never\n");
1079 log_error("resolve-names must be early, late or never\n");
1084 printf("Usage: udevd OPTIONS\n"
1087 " --children-max=<maximum number of workers>\n"
1088 " --exec-delay=<seconds to wait before executing RUN=>\n"
1089 " --resolve-names=early|late|never\n"
1095 printf("%s\n", VERSION);
1103 * read the kernel commandline, in case we need to get into debug mode
1104 * udev.log-priority=<level> syslog priority
1105 * udev.children-max=<number of workers> events are fully serialized if set to 1
1108 f = fopen("/proc/cmdline", "r");
1112 if (fgets(cmdline, sizeof(cmdline), f) != NULL) {
1115 pos = strstr(cmdline, "udev.log-priority=");
1117 pos += strlen("udev.log-priority=");
1118 udev_set_log_priority(udev, util_log_priority(pos));
1121 pos = strstr(cmdline, "udev.children-max=");
1123 pos += strlen("udev.children-max=");
1124 children_max = strtoul(pos, NULL, 0);
1127 pos = strstr(cmdline, "udev.exec-delay=");
1129 pos += strlen("udev.exec-delay=");
1130 exec_delay = strtoul(pos, NULL, 0);
1136 if (getuid() != 0) {
1137 fprintf(stderr, "root privileges required\n");
1138 log_error("root privileges required\n");
1142 /* set umask before creating any file/directory */
1146 mkdir("/run/udev", 0755);
1149 static_dev_create_from_modules(udev);
1151 /* before opening new files, make sure std{in,out,err} fds are in a sane state */
1155 fd = open("/dev/null", O_RDWR);
1157 if (write(STDOUT_FILENO, 0, 0) < 0)
1158 dup2(fd, STDOUT_FILENO);
1159 if (write(STDERR_FILENO, 0, 0) < 0)
1160 dup2(fd, STDERR_FILENO);
1161 if (fd > STDERR_FILENO)
1164 fprintf(stderr, "cannot open /dev/null\n");
1165 log_error("cannot open /dev/null\n");
1169 if (systemd_fds(udev, &fd_ctrl, &fd_netlink) >= 0) {
1170 /* get control and netlink socket from from systemd */
1171 udev_ctrl = udev_ctrl_new_from_fd(udev, fd_ctrl);
1172 if (udev_ctrl == NULL) {
1173 log_error("error taking over udev control socket");
1178 monitor = udev_monitor_new_from_netlink_fd(udev, "kernel", fd_netlink);
1179 if (monitor == NULL) {
1180 log_error("error taking over netlink socket\n");
1185 /* get our own cgroup, we regularly kill everything udev has left behind */
1186 if (cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 0, &udev_cgroup) < 0)
1189 /* open control and netlink socket */
1190 udev_ctrl = udev_ctrl_new(udev);
1191 if (udev_ctrl == NULL) {
1192 fprintf(stderr, "error initializing udev control socket");
1193 log_error("error initializing udev control socket");
1197 fd_ctrl = udev_ctrl_get_fd(udev_ctrl);
1199 monitor = udev_monitor_new_from_netlink(udev, "kernel");
1200 if (monitor == NULL) {
1201 fprintf(stderr, "error initializing netlink socket\n");
1202 log_error("error initializing netlink socket\n");
1206 fd_netlink = udev_monitor_get_fd(monitor);
1209 if (udev_monitor_enable_receiving(monitor) < 0) {
1210 fprintf(stderr, "error binding netlink socket\n");
1211 log_error("error binding netlink socket\n");
1216 if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
1217 fprintf(stderr, "error binding udev control socket\n");
1218 log_error("error binding udev control socket\n");
1223 udev_monitor_set_receive_buffer_size(monitor, 128*1024*1024);
1225 /* create queue file before signalling 'ready', to make sure we block 'settle' */
1226 udev_queue_export = udev_queue_export_new(udev);
1227 if (udev_queue_export == NULL) {
1228 log_error("error creating queue file\n");
1241 log_error("fork of daemon failed: %m\n");
1246 goto exit_daemonize;
1251 fd = open("/proc/self/oom_score_adj", O_RDWR|O_CLOEXEC);
1253 write(fd, "-1000", 5);
1257 sd_notify(1, "READY=1");
1260 f = fopen("/dev/kmsg", "w");
1262 fprintf(f, "<30>udevd[%u]: starting version " VERSION "\n", getpid());
1269 fd = open("/dev/null", O_RDWR);
1271 dup2(fd, STDIN_FILENO);
1272 dup2(fd, STDOUT_FILENO);
1273 dup2(fd, STDERR_FILENO);
1278 fd_inotify = udev_watch_init(udev);
1279 if (fd_inotify < 0) {
1280 fprintf(stderr, "error initializing inotify\n");
1281 log_error("error initializing inotify\n");
1285 udev_watch_restore(udev);
1287 /* block and listen to all signals on signalfd */
1289 sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
1290 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
1291 if (fd_signal < 0) {
1292 fprintf(stderr, "error creating signalfd\n");
1293 log_error("error creating signalfd\n");
1298 /* unnamed socket from workers to the main daemon */
1299 if (socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, worker_watch) < 0) {
1300 fprintf(stderr, "error creating socketpair\n");
1301 log_error("error creating socketpair\n");
1305 fd_worker = worker_watch[READ_END];
1307 udev_builtin_init(udev);
1309 rules = udev_rules_new(udev, resolve_names);
1310 if (rules == NULL) {
1311 log_error("error reading rules\n");
1315 memset(&ep_ctrl, 0, sizeof(struct epoll_event));
1316 ep_ctrl.events = EPOLLIN;
1317 ep_ctrl.data.fd = fd_ctrl;
1319 memset(&ep_inotify, 0, sizeof(struct epoll_event));
1320 ep_inotify.events = EPOLLIN;
1321 ep_inotify.data.fd = fd_inotify;
1323 memset(&ep_signal, 0, sizeof(struct epoll_event));
1324 ep_signal.events = EPOLLIN;
1325 ep_signal.data.fd = fd_signal;
1327 memset(&ep_netlink, 0, sizeof(struct epoll_event));
1328 ep_netlink.events = EPOLLIN;
1329 ep_netlink.data.fd = fd_netlink;
1331 memset(&ep_worker, 0, sizeof(struct epoll_event));
1332 ep_worker.events = EPOLLIN;
1333 ep_worker.data.fd = fd_worker;
1335 fd_ep = epoll_create1(EPOLL_CLOEXEC);
1337 log_error("error creating epoll fd: %m\n");
1340 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_ctrl, &ep_ctrl) < 0 ||
1341 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_inotify, &ep_inotify) < 0 ||
1342 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
1343 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_netlink, &ep_netlink) < 0 ||
1344 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_worker, &ep_worker) < 0) {
1345 log_error("fail to add fds to epoll: %m\n");
1349 /* if needed, convert old database from earlier udev version */
1352 if (children_max <= 0) {
1353 int memsize = mem_size_mb();
1355 /* set value depending on the amount of RAM */
1357 children_max = 128 + (memsize / 8);
1361 log_debug("set children_max to %u\n", children_max);
1363 udev_rules_apply_static_dev_perms(rules);
1365 udev_list_node_init(&event_list);
1366 udev_list_node_init(&worker_list);
1369 static unsigned long long last_usec;
1370 struct epoll_event ev[8];
1373 bool is_worker, is_signal, is_inotify, is_netlink, is_ctrl;
1377 /* close sources of new events and discard buffered events */
1379 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_ctrl, NULL);
1382 if (monitor != NULL) {
1383 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_netlink, NULL);
1384 udev_monitor_unref(monitor);
1387 if (fd_inotify >= 0) {
1388 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_inotify, NULL);
1393 /* discard queued events and kill workers */
1394 event_queue_cleanup(udev, EVENT_QUEUED);
1397 /* exit after all has cleaned up */
1398 if (udev_list_node_is_empty(&event_list) && udev_list_node_is_empty(&worker_list))
1401 /* timeout at exit for workers to finish */
1402 timeout = 30 * 1000;
1403 } else if (udev_list_node_is_empty(&event_list) && !children) {
1407 /* cleanup possible left-over processes in our cgroup */
1409 cg_kill(SYSTEMD_CGROUP_CONTROLLER, udev_cgroup, SIGKILL, false, true, NULL);
1411 /* kill idle or hanging workers */
1414 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
1419 struct udev_list_node *loop;
1423 log_error("timeout, giving up waiting for workers to finish\n");
1427 /* kill idle workers */
1428 if (udev_list_node_is_empty(&event_list)) {
1429 log_debug("cleanup idle workers\n");
1433 /* check for hanging events */
1434 udev_list_node_foreach(loop, &worker_list) {
1435 struct worker *worker = node_to_worker(loop);
1437 if (worker->state != WORKER_RUNNING)
1440 if ((now_usec() - worker->event_start_usec) > 30 * 1000 * 1000) {
1441 log_error("worker [%u] %s timeout; kill it\n", worker->pid,
1442 worker->event ? worker->event->devpath : "<idle>");
1443 kill(worker->pid, SIGKILL);
1444 worker->state = WORKER_KILLED;
1445 /* drop reference taken for state 'running' */
1446 worker_unref(worker);
1447 if (worker->event) {
1448 log_error("seq %llu '%s' killed\n",
1449 udev_device_get_seqnum(worker->event->dev), worker->event->devpath);
1450 worker->event->exitcode = -64;
1451 event_queue_delete(worker->event, true);
1452 worker->event = NULL;
1459 is_worker = is_signal = is_inotify = is_netlink = is_ctrl = false;
1460 for (i = 0; i < fdcount; i++) {
1461 if (ev[i].data.fd == fd_worker && ev[i].events & EPOLLIN)
1463 else if (ev[i].data.fd == fd_netlink && ev[i].events & EPOLLIN)
1465 else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN)
1467 else if (ev[i].data.fd == fd_inotify && ev[i].events & EPOLLIN)
1469 else if (ev[i].data.fd == fd_ctrl && ev[i].events & EPOLLIN)
1473 /* check for changed config, every 3 seconds at most */
1474 if ((now_usec() - last_usec) > 3 * 1000 * 1000) {
1475 if (udev_rules_check_timestamp(rules))
1477 if (udev_builtin_validate(udev))
1480 last_usec = now_usec();
1483 /* reload requested, HUP signal received, rules changed, builtin changed */
1486 rules = udev_rules_unref(rules);
1487 udev_builtin_exit(udev);
1491 /* event has finished */
1493 worker_returned(fd_worker);
1496 struct udev_device *dev;
1498 dev = udev_monitor_receive_device(monitor);
1500 udev_device_set_usec_initialized(dev, now_usec());
1501 if (event_queue_insert(dev) < 0)
1502 udev_device_unref(dev);
1506 /* start new events */
1507 if (!udev_list_node_is_empty(&event_list) && !udev_exit && !stop_exec_queue) {
1509 rules = udev_rules_new(udev, resolve_names);
1511 event_queue_start(udev);
1515 struct signalfd_siginfo fdsi;
1518 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
1519 if (size == sizeof(struct signalfd_siginfo))
1520 handle_signal(udev, fdsi.ssi_signo);
1523 /* we are shutting down, the events below are not handled anymore */
1527 /* device node watch */
1529 handle_inotify(udev);
1532 * This needs to be after the inotify handling, to make sure,
1533 * that the ping is send back after the possibly generated
1534 * "change" events by the inotify device node watch.
1536 * A single time we may receive a client connection which we need to
1537 * keep open to block the client. It will be closed right before we
1541 ctrl_conn = handle_ctrl_msg(udev_ctrl);
1546 udev_queue_export_cleanup(udev_queue_export);
1547 udev_ctrl_cleanup(udev_ctrl);
1551 worker_list_cleanup(udev);
1552 event_queue_cleanup(udev, EVENT_UNDEF);
1553 udev_rules_unref(rules);
1554 udev_builtin_exit(udev);
1557 if (worker_watch[READ_END] >= 0)
1558 close(worker_watch[READ_END]);
1559 if (worker_watch[WRITE_END] >= 0)
1560 close(worker_watch[WRITE_END]);
1561 udev_monitor_unref(monitor);
1562 udev_queue_export_unref(udev_queue_export);
1563 udev_ctrl_connection_unref(ctrl_conn);
1564 udev_ctrl_unref(udev_ctrl);