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"
52 void udev_main_log(struct udev *udev, int priority,
53 const char *file, int line, const char *fn,
54 const char *format, va_list args)
56 log_metav(priority, file, line, fn, format, args);
59 static struct udev_rules *rules;
60 static struct udev_queue_export *udev_queue_export;
61 static struct udev_ctrl *udev_ctrl;
62 static struct udev_monitor *monitor;
63 static int worker_watch[2] = { -1, -1 };
64 static int fd_signal = -1;
65 static int fd_ep = -1;
66 static int fd_inotify = -1;
67 static bool stop_exec_queue;
70 static int children_max;
71 static int exec_delay;
72 static sigset_t sigmask_orig;
73 static UDEV_LIST(event_list);
74 static UDEV_LIST(worker_list);
75 static bool udev_exit;
84 struct udev_list_node node;
86 struct udev_device *dev;
87 enum event_state state;
89 unsigned long long int delaying_seqnum;
90 unsigned long long int seqnum;
93 const char *devpath_old;
99 static struct event *node_to_event(struct udev_list_node *node)
103 event = (char *)node;
104 event -= offsetof(struct event, node);
105 return (struct event *)event;
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 unsigned long long event_start_usec;
128 /* passed from worker to main process */
129 struct worker_message {
134 static struct worker *node_to_worker(struct udev_list_node *node)
138 worker = (char *)node;
139 worker -= offsetof(struct worker, node);
140 return (struct worker *)worker;
143 static void event_queue_delete(struct event *event, bool export)
145 udev_list_node_remove(&event->node);
148 udev_queue_export_device_finished(udev_queue_export, event->dev);
149 log_debug("seq %llu done with %i\n", udev_device_get_seqnum(event->dev), event->exitcode);
151 udev_device_unref(event->dev);
155 static struct worker *worker_ref(struct worker *worker)
161 static void worker_cleanup(struct worker *worker)
163 udev_list_node_remove(&worker->node);
164 udev_monitor_unref(worker->monitor);
169 static void worker_unref(struct worker *worker)
172 if (worker->refcount > 0)
174 log_debug("worker [%u] cleaned up\n", worker->pid);
175 worker_cleanup(worker);
178 static void worker_list_cleanup(struct udev *udev)
180 struct udev_list_node *loop, *tmp;
182 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
183 struct worker *worker = node_to_worker(loop);
185 worker_cleanup(worker);
189 static void worker_new(struct event *event)
191 struct udev *udev = event->udev;
192 struct worker *worker;
193 struct udev_monitor *worker_monitor;
196 /* listen for new events */
197 worker_monitor = udev_monitor_new_from_netlink(udev, NULL);
198 if (worker_monitor == NULL)
200 /* allow the main daemon netlink address to send devices to the worker */
201 udev_monitor_allow_unicast_sender(worker_monitor, monitor);
202 udev_monitor_enable_receiving(worker_monitor);
204 worker = calloc(1, sizeof(struct worker));
205 if (worker == NULL) {
206 udev_monitor_unref(worker_monitor);
209 /* worker + event reference */
210 worker->refcount = 2;
216 struct udev_device *dev = NULL;
218 struct epoll_event ep_signal, ep_monitor;
220 int rc = EXIT_SUCCESS;
222 /* take initial device from queue */
227 worker_list_cleanup(udev);
228 event_queue_cleanup(udev, EVENT_UNDEF);
229 udev_queue_export_unref(udev_queue_export);
230 udev_monitor_unref(monitor);
231 udev_ctrl_unref(udev_ctrl);
234 close(worker_watch[READ_END]);
237 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
239 log_error("error creating signalfd %m\n");
244 fd_ep = epoll_create1(EPOLL_CLOEXEC);
246 log_error("error creating epoll fd: %m\n");
251 memset(&ep_signal, 0, sizeof(struct epoll_event));
252 ep_signal.events = EPOLLIN;
253 ep_signal.data.fd = fd_signal;
255 fd_monitor = udev_monitor_get_fd(worker_monitor);
256 memset(&ep_monitor, 0, sizeof(struct epoll_event));
257 ep_monitor.events = EPOLLIN;
258 ep_monitor.data.fd = fd_monitor;
260 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
261 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_monitor, &ep_monitor) < 0) {
262 log_error("fail to add fds to epoll: %m\n");
267 /* request TERM signal if parent exits */
268 prctl(PR_SET_PDEATHSIG, SIGTERM);
271 struct udev_event *udev_event;
272 struct worker_message msg;
275 log_debug("seq %llu running\n", udev_device_get_seqnum(dev));
276 udev_event = udev_event_new(dev);
277 if (udev_event == NULL) {
282 /* needed for SIGCHLD/SIGTERM in spawn() */
283 udev_event->fd_signal = fd_signal;
286 udev_event->exec_delay = exec_delay;
288 /* apply rules, create node, symlinks */
289 err = udev_event_execute_rules(udev_event, rules, &sigmask_orig);
292 udev_event_execute_run(udev_event, &sigmask_orig);
294 /* apply/restore inotify watch */
295 if (err == 0 && udev_event->inotify_watch) {
296 udev_watch_begin(udev, dev);
297 udev_device_update_db(dev);
300 /* send processed event back to libudev listeners */
301 udev_monitor_send_device(worker_monitor, NULL, dev);
303 /* send udevd the result of the event execution */
304 memset(&msg, 0, sizeof(struct worker_message));
308 send(worker_watch[WRITE_END], &msg, sizeof(struct worker_message), 0);
310 log_debug("seq %llu processed with %i\n", udev_device_get_seqnum(dev), err);
312 udev_device_unref(dev);
315 if (udev_event->sigterm) {
316 udev_event_unref(udev_event);
320 udev_event_unref(udev_event);
322 /* wait for more device messages from main udevd, or term signal */
323 while (dev == NULL) {
324 struct epoll_event ev[4];
328 fdcount = epoll_wait(fd_ep, ev, ARRAY_SIZE(ev), -1);
332 log_error("failed to poll: %m\n");
336 for (i = 0; i < fdcount; i++) {
337 if (ev[i].data.fd == fd_monitor && ev[i].events & EPOLLIN) {
338 dev = udev_monitor_receive_device(worker_monitor);
340 } else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN) {
341 struct signalfd_siginfo fdsi;
344 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
345 if (size != sizeof(struct signalfd_siginfo))
347 switch (fdsi.ssi_signo) {
356 udev_device_unref(dev);
362 close(worker_watch[WRITE_END]);
363 udev_rules_unref(rules);
364 udev_builtin_exit(udev);
365 udev_monitor_unref(worker_monitor);
371 udev_monitor_unref(worker_monitor);
372 event->state = EVENT_QUEUED;
374 log_error("fork of child failed: %m\n");
377 /* close monitor, but keep address around */
378 udev_monitor_disconnect(worker_monitor);
379 worker->monitor = worker_monitor;
381 worker->state = WORKER_RUNNING;
382 worker->event_start_usec = now_usec();
383 worker->event = event;
384 event->state = EVENT_RUNNING;
385 udev_list_node_append(&worker->node, &worker_list);
387 log_debug("seq %llu forked new worker [%u]\n", udev_device_get_seqnum(event->dev), pid);
392 static void event_run(struct event *event)
394 struct udev_list_node *loop;
396 udev_list_node_foreach(loop, &worker_list) {
397 struct worker *worker = node_to_worker(loop);
400 if (worker->state != WORKER_IDLE)
403 count = udev_monitor_send_device(monitor, worker->monitor, event->dev);
405 log_error("worker [%u] did not accept message %zi (%m), kill it\n", worker->pid, count);
406 kill(worker->pid, SIGKILL);
407 worker->state = WORKER_KILLED;
411 worker->event = event;
412 worker->state = WORKER_RUNNING;
413 worker->event_start_usec = now_usec();
414 event->state = EVENT_RUNNING;
418 if (children >= children_max) {
419 if (children_max > 1)
420 log_debug("maximum number (%i) of children reached\n", children);
424 /* start new worker and pass initial device */
428 static int event_queue_insert(struct udev_device *dev)
432 event = calloc(1, sizeof(struct event));
436 event->udev = udev_device_get_udev(dev);
438 event->seqnum = udev_device_get_seqnum(dev);
439 event->devpath = udev_device_get_devpath(dev);
440 event->devpath_len = strlen(event->devpath);
441 event->devpath_old = udev_device_get_devpath_old(dev);
442 event->devnum = udev_device_get_devnum(dev);
443 event->is_block = (strcmp("block", udev_device_get_subsystem(dev)) == 0);
444 event->ifindex = udev_device_get_ifindex(dev);
446 udev_queue_export_device_queued(udev_queue_export, dev);
447 log_debug("seq %llu queued, '%s' '%s'\n", udev_device_get_seqnum(dev),
448 udev_device_get_action(dev), udev_device_get_subsystem(dev));
450 event->state = EVENT_QUEUED;
451 udev_list_node_append(&event->node, &event_list);
455 static void worker_kill(struct udev *udev, int retain)
457 struct udev_list_node *loop;
460 if (children <= retain)
463 max = children - retain;
465 udev_list_node_foreach(loop, &worker_list) {
466 struct worker *worker = node_to_worker(loop);
471 if (worker->state == WORKER_KILLED)
474 worker->state = WORKER_KILLED;
475 kill(worker->pid, SIGTERM);
479 /* lookup event for identical, parent, child device */
480 static bool is_devpath_busy(struct event *event)
482 struct udev_list_node *loop;
485 /* check if queue contains events we depend on */
486 udev_list_node_foreach(loop, &event_list) {
487 struct event *loop_event = node_to_event(loop);
489 /* we already found a later event, earlier can not block us, no need to check again */
490 if (loop_event->seqnum < event->delaying_seqnum)
493 /* event we checked earlier still exists, no need to check again */
494 if (loop_event->seqnum == event->delaying_seqnum)
497 /* found ourself, no later event can block us */
498 if (loop_event->seqnum >= event->seqnum)
501 /* check major/minor */
502 if (major(event->devnum) != 0 && event->devnum == loop_event->devnum && event->is_block == loop_event->is_block)
505 /* check network device ifindex */
506 if (event->ifindex != 0 && event->ifindex == loop_event->ifindex)
509 /* check our old name */
510 if (event->devpath_old != NULL && strcmp(loop_event->devpath, event->devpath_old) == 0) {
511 event->delaying_seqnum = loop_event->seqnum;
515 /* compare devpath */
516 common = MIN(loop_event->devpath_len, event->devpath_len);
518 /* one devpath is contained in the other? */
519 if (memcmp(loop_event->devpath, event->devpath, common) != 0)
522 /* identical device event found */
523 if (loop_event->devpath_len == event->devpath_len) {
524 /* devices names might have changed/swapped in the meantime */
525 if (major(event->devnum) != 0 && (event->devnum != loop_event->devnum || event->is_block != loop_event->is_block))
527 if (event->ifindex != 0 && event->ifindex != loop_event->ifindex)
529 event->delaying_seqnum = loop_event->seqnum;
533 /* parent device event found */
534 if (event->devpath[common] == '/') {
535 event->delaying_seqnum = loop_event->seqnum;
539 /* child device event found */
540 if (loop_event->devpath[common] == '/') {
541 event->delaying_seqnum = loop_event->seqnum;
545 /* no matching device */
552 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)
572 struct udev_list_node *loop, *tmp;
574 udev_list_node_foreach_safe(loop, tmp, &event_list) {
575 struct event *event = node_to_event(loop);
577 if (match_type != EVENT_UNDEF && match_type != event->state)
580 event_queue_delete(event, false);
584 static void worker_returned(int fd_worker)
587 struct worker_message msg;
589 struct udev_list_node *loop;
591 size = recv(fd_worker, &msg, sizeof(struct worker_message), MSG_DONTWAIT);
592 if (size != sizeof(struct worker_message))
595 /* lookup worker who sent the signal */
596 udev_list_node_foreach(loop, &worker_list) {
597 struct worker *worker = node_to_worker(loop);
599 if (worker->pid != msg.pid)
602 /* worker returned */
604 worker->event->exitcode = msg.exitcode;
605 event_queue_delete(worker->event, true);
606 worker->event = NULL;
608 if (worker->state != WORKER_KILLED)
609 worker->state = WORKER_IDLE;
610 worker_unref(worker);
616 /* receive the udevd message from userspace */
617 static struct udev_ctrl_connection *handle_ctrl_msg(struct udev_ctrl *uctrl)
619 struct udev *udev = udev_ctrl_get_udev(uctrl);
620 struct udev_ctrl_connection *ctrl_conn;
621 struct udev_ctrl_msg *ctrl_msg = NULL;
625 ctrl_conn = udev_ctrl_get_connection(uctrl);
626 if (ctrl_conn == NULL)
629 ctrl_msg = udev_ctrl_receive_msg(ctrl_conn);
630 if (ctrl_msg == NULL)
633 i = udev_ctrl_get_set_log_level(ctrl_msg);
635 log_debug("udevd message (SET_LOG_PRIORITY) received, log_priority=%i\n", i);
636 log_set_max_level(i);
637 udev_set_log_priority(udev, i);
638 worker_kill(udev, 0);
641 if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
642 log_debug("udevd message (STOP_EXEC_QUEUE) received\n");
643 stop_exec_queue = true;
646 if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
647 log_debug("udevd message (START_EXEC_QUEUE) received\n");
648 stop_exec_queue = false;
651 if (udev_ctrl_get_reload(ctrl_msg) > 0) {
652 log_debug("udevd message (RELOAD) received\n");
656 str = udev_ctrl_get_set_env(ctrl_msg);
664 val = strchr(key, '=');
668 if (val[0] == '\0') {
669 log_debug("udevd message (ENV) received, unset '%s'\n", key);
670 udev_add_property(udev, key, NULL);
672 log_debug("udevd message (ENV) received, set '%s=%s'\n", key, val);
673 udev_add_property(udev, key, val);
676 log_error("wrong key format '%s'\n", key);
680 worker_kill(udev, 0);
683 i = udev_ctrl_get_set_children_max(ctrl_msg);
685 log_debug("udevd message (SET_MAX_CHILDREN) received, children_max=%i\n", i);
689 if (udev_ctrl_get_ping(ctrl_msg) > 0)
690 log_debug("udevd message (SYNC) received\n");
692 if (udev_ctrl_get_exit(ctrl_msg) > 0) {
693 log_debug("udevd message (EXIT) received\n");
695 /* keep reference to block the client until we exit */
696 udev_ctrl_connection_ref(ctrl_conn);
699 udev_ctrl_msg_unref(ctrl_msg);
700 return udev_ctrl_connection_unref(ctrl_conn);
703 /* read inotify messages */
704 static int handle_inotify(struct udev *udev)
708 struct inotify_event *ev;
710 if ((ioctl(fd_inotify, FIONREAD, &nbytes) < 0) || (nbytes <= 0))
713 buf = malloc(nbytes);
715 log_error("error getting buffer for inotify\n");
719 nbytes = read(fd_inotify, buf, nbytes);
721 for (pos = 0; pos < nbytes; pos += sizeof(struct inotify_event) + ev->len) {
722 struct udev_device *dev;
724 ev = (struct inotify_event *)(buf + pos);
725 dev = udev_watch_lookup(udev, ev->wd);
727 log_debug("inotify event: %x for %s\n", ev->mask, udev_device_get_devnode(dev));
728 if (ev->mask & IN_CLOSE_WRITE) {
729 char filename[UTIL_PATH_SIZE];
732 log_debug("device %s closed, synthesising 'change'\n", udev_device_get_devnode(dev));
733 util_strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
734 fd = open(filename, O_WRONLY);
736 if (write(fd, "change", 6) < 0)
737 log_debug("error writing uevent: %m\n");
741 if (ev->mask & IN_IGNORED)
742 udev_watch_end(udev, dev);
744 udev_device_unref(dev);
753 static void handle_signal(struct udev *udev, int signo)
764 struct udev_list_node *loop, *tmp;
766 pid = waitpid(-1, &status, WNOHANG);
770 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
771 struct worker *worker = node_to_worker(loop);
773 if (worker->pid != pid)
775 log_debug("worker [%u] exit\n", pid);
777 if (WIFEXITED(status)) {
778 if (WEXITSTATUS(status) != 0)
779 log_error("worker [%u] exit with return code %i\n", pid, WEXITSTATUS(status));
780 } else if (WIFSIGNALED(status)) {
781 log_error("worker [%u] terminated by signal %i (%s)\n",
782 pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
783 } else if (WIFSTOPPED(status)) {
784 log_error("worker [%u] stopped\n", pid);
785 } else if (WIFCONTINUED(status)) {
786 log_error("worker [%u] continued\n", pid);
788 log_error("worker [%u] exit with status 0x%04x\n", pid, status);
791 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
793 log_error("worker [%u] failed while handling '%s'\n",
794 pid, worker->event->devpath);
795 worker->event->exitcode = -32;
796 event_queue_delete(worker->event, true);
797 /* drop reference taken for state 'running' */
798 worker_unref(worker);
801 worker_unref(worker);
812 static void static_dev_create_from_modules(struct udev *udev)
814 struct utsname kernel;
815 char modules[UTIL_PATH_SIZE];
820 util_strscpyl(modules, sizeof(modules), "/lib/modules/", kernel.release, "/modules.devname", NULL);
821 f = fopen(modules, "r");
825 while (fgets(buf, sizeof(buf), f) != NULL) {
833 char filename[UTIL_PATH_SIZE];
839 s = strchr(modname, ' ');
845 s = strchr(devname, ' ');
851 s = strchr(devno, ' ');
853 s = strchr(devno, '\n');
856 if (sscanf(devno, "%c%u:%u", &type, &maj, &min) != 3)
861 else if (type == 'b')
866 util_strscpyl(filename, sizeof(filename), udev_get_dev_path(udev), "/", devname, NULL);
867 util_create_path_selinux(udev, filename);
868 udev_selinux_setfscreatecon(udev, filename, mode);
869 log_debug("mknod '%s' %c%u:%u\n", filename, type, maj, min);
870 if (mknod(filename, mode, makedev(maj, min)) < 0 && errno == EEXIST)
871 utimensat(AT_FDCWD, filename, NULL, 0);
872 udev_selinux_resetfscreatecon(udev);
878 /* needed for standalone udev operations */
879 static void static_dev_create_links(struct udev *udev)
886 static const struct stdlinks stdlinks[] = {
887 { "core", "/proc/kcore" },
888 { "fd", "/proc/self/fd" },
889 { "stdin", "/proc/self/fd/0" },
890 { "stdout", "/proc/self/fd/1" },
891 { "stderr", "/proc/self/fd/2" },
895 dir = opendir(udev_get_dev_path(udev));
899 for (i = 0; i < ARRAY_SIZE(stdlinks); i++) {
902 if (stat(stdlinks[i].target, &sb) == 0) {
903 udev_selinux_setfscreateconat(udev, dirfd(dir), stdlinks[i].link, S_IFLNK);
904 if (symlinkat(stdlinks[i].target, dirfd(dir), stdlinks[i].link) < 0 && errno == EEXIST)
905 utimensat(dirfd(dir), stdlinks[i].link, NULL, AT_SYMLINK_NOFOLLOW);
906 udev_selinux_resetfscreatecon(udev);
913 static int mem_size_mb(void)
917 long int memsize = -1;
919 f = fopen("/proc/meminfo", "r");
923 while (fgets(buf, sizeof(buf), f) != NULL) {
926 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
927 memsize = value / 1024;
936 static int convert_db(struct udev *udev)
938 char filename[UTIL_PATH_SIZE];
940 struct udev_enumerate *udev_enumerate;
941 struct udev_list_entry *list_entry;
943 /* current database */
944 util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/data", NULL);
945 if (access(filename, F_OK) >= 0)
948 /* make sure we do not get here again */
949 util_create_path(udev, filename);
950 mkdir(filename, 0755);
953 util_strscpyl(filename, sizeof(filename), udev_get_dev_path(udev), "/.udev/db", NULL);
954 if (access(filename, F_OK) < 0)
957 f = fopen("/dev/kmsg", "w");
959 fprintf(f, "<30>udevd[%u]: converting old udev database\n", getpid());
963 udev_enumerate = udev_enumerate_new(udev);
964 if (udev_enumerate == NULL)
966 udev_enumerate_scan_devices(udev_enumerate);
967 udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(udev_enumerate)) {
968 struct udev_device *device;
970 device = udev_device_new_from_syspath(udev, udev_list_entry_get_name(list_entry));
974 /* try to find the old database for devices without a current one */
975 if (udev_device_read_db(device, NULL) < 0) {
979 char devpath[UTIL_PATH_SIZE];
980 char from[UTIL_PATH_SIZE];
984 /* find database in old location */
985 id = udev_device_get_id_filename(device);
986 util_strscpyl(from, sizeof(from), udev_get_dev_path(udev), "/.udev/db/", id, NULL);
987 if (lstat(from, &stats) == 0) {
989 udev_device_read_db(device, from);
995 /* find old database with $subsys:$sysname name */
996 util_strscpyl(from, sizeof(from), udev_get_dev_path(udev),
997 "/.udev/db/", udev_device_get_subsystem(device), ":",
998 udev_device_get_sysname(device), NULL);
999 if (lstat(from, &stats) == 0) {
1001 udev_device_read_db(device, from);
1007 /* find old database with the encoded devpath name */
1008 util_path_encode(udev_device_get_devpath(device), devpath, sizeof(devpath));
1009 util_strscpyl(from, sizeof(from), udev_get_dev_path(udev), "/.udev/db/", devpath, NULL);
1010 if (lstat(from, &stats) == 0) {
1012 udev_device_read_db(device, from);
1018 /* write out new database */
1020 udev_device_update_db(device);
1022 udev_device_unref(device);
1024 udev_enumerate_unref(udev_enumerate);
1028 static int systemd_fds(struct udev *udev, int *rctrl, int *rnetlink)
1030 int ctrl = -1, netlink = -1;
1033 n = sd_listen_fds(true);
1037 for (fd = SD_LISTEN_FDS_START; fd < n + SD_LISTEN_FDS_START; fd++) {
1038 if (sd_is_socket(fd, AF_LOCAL, SOCK_SEQPACKET, -1)) {
1045 if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1)) {
1055 if (ctrl < 0 || netlink < 0)
1058 log_debug("ctrl=%i netlink=%i\n", ctrl, netlink);
1060 *rnetlink = netlink;
1064 static bool check_rules_timestamp(struct udev *udev)
1067 unsigned long long *stamp_usec;
1069 bool changed = false;
1071 n = udev_get_rules_path(udev, &p, &stamp_usec);
1072 for (i = 0; i < n; i++) {
1075 if (stat(p[i], &stats) < 0)
1078 if (stamp_usec[i] == ts_usec(&stats.st_mtim))
1082 if (stamp_usec[i] != 0) {
1083 log_debug("reload - timestamp of '%s' changed\n", p[i]);
1087 /* update timestamp */
1088 stamp_usec[i] = ts_usec(&stats.st_mtim);
1094 int main(int argc, char *argv[])
1099 int daemonize = false;
1100 int resolve_names = 1;
1101 static const struct option options[] = {
1102 { "daemon", no_argument, NULL, 'd' },
1103 { "debug", no_argument, NULL, 'D' },
1104 { "children-max", required_argument, NULL, 'c' },
1105 { "exec-delay", required_argument, NULL, 'e' },
1106 { "resolve-names", required_argument, NULL, 'N' },
1107 { "help", no_argument, NULL, 'h' },
1108 { "version", no_argument, NULL, 'V' },
1112 int fd_netlink = -1;
1114 struct epoll_event ep_ctrl, ep_inotify, ep_signal, ep_netlink, ep_worker;
1115 struct udev_ctrl_connection *ctrl_conn = NULL;
1123 log_parse_environment();
1124 udev_set_log_fn(udev, udev_main_log);
1125 log_debug("version %s\n", VERSION);
1126 udev_selinux_init(udev);
1131 option = getopt_long(argc, argv, "c:deDtN:hV", options, NULL);
1140 children_max = strtoul(optarg, NULL, 0);
1143 exec_delay = strtoul(optarg, NULL, 0);
1147 if (udev_get_log_priority(udev) < LOG_INFO)
1148 udev_set_log_priority(udev, LOG_INFO);
1151 if (strcmp (optarg, "early") == 0) {
1153 } else if (strcmp (optarg, "late") == 0) {
1155 } else if (strcmp (optarg, "never") == 0) {
1158 fprintf(stderr, "resolve-names must be early, late or never\n");
1159 log_error("resolve-names must be early, late or never\n");
1164 printf("Usage: udevd OPTIONS\n"
1167 " --children-max=<maximum number of workers>\n"
1168 " --exec-delay=<seconds to wait before executing RUN=>\n"
1169 " --resolve-names=early|late|never\n"
1175 printf("%s\n", VERSION);
1183 * read the kernel commandline, in case we need to get into debug mode
1184 * udev.log-priority=<level> syslog priority
1185 * udev.children-max=<number of workers> events are fully serialized if set to 1
1188 f = fopen("/proc/cmdline", "r");
1192 if (fgets(cmdline, sizeof(cmdline), f) != NULL) {
1195 pos = strstr(cmdline, "udev.log-priority=");
1197 pos += strlen("udev.log-priority=");
1198 udev_set_log_priority(udev, util_log_priority(pos));
1201 pos = strstr(cmdline, "udev.children-max=");
1203 pos += strlen("udev.children-max=");
1204 children_max = strtoul(pos, NULL, 0);
1207 pos = strstr(cmdline, "udev.exec-delay=");
1209 pos += strlen("udev.exec-delay=");
1210 exec_delay = strtoul(pos, NULL, 0);
1216 if (getuid() != 0) {
1217 fprintf(stderr, "root privileges required\n");
1218 log_error("root privileges required\n");
1222 /* set umask before creating any file/directory */
1227 mkdir(udev_get_run_path(udev), 0755);
1229 /* create standard links, copy static nodes, create nodes from modules */
1230 static_dev_create_links(udev);
1231 static_dev_create_from_modules(udev);
1233 /* before opening new files, make sure std{in,out,err} fds are in a sane state */
1237 fd = open("/dev/null", O_RDWR);
1239 if (write(STDOUT_FILENO, 0, 0) < 0)
1240 dup2(fd, STDOUT_FILENO);
1241 if (write(STDERR_FILENO, 0, 0) < 0)
1242 dup2(fd, STDERR_FILENO);
1243 if (fd > STDERR_FILENO)
1246 fprintf(stderr, "cannot open /dev/null\n");
1247 log_error("cannot open /dev/null\n");
1251 if (systemd_fds(udev, &fd_ctrl, &fd_netlink) >= 0) {
1252 /* get control and netlink socket from from systemd */
1253 udev_ctrl = udev_ctrl_new_from_fd(udev, fd_ctrl);
1254 if (udev_ctrl == NULL) {
1255 log_error("error taking over udev control socket");
1260 monitor = udev_monitor_new_from_netlink_fd(udev, "kernel", fd_netlink);
1261 if (monitor == NULL) {
1262 log_error("error taking over netlink socket\n");
1267 /* open control and netlink socket */
1268 udev_ctrl = udev_ctrl_new(udev);
1269 if (udev_ctrl == NULL) {
1270 fprintf(stderr, "error initializing udev control socket");
1271 log_error("error initializing udev control socket");
1275 fd_ctrl = udev_ctrl_get_fd(udev_ctrl);
1277 monitor = udev_monitor_new_from_netlink(udev, "kernel");
1278 if (monitor == NULL) {
1279 fprintf(stderr, "error initializing netlink socket\n");
1280 log_error("error initializing netlink socket\n");
1284 fd_netlink = udev_monitor_get_fd(monitor);
1287 if (udev_monitor_enable_receiving(monitor) < 0) {
1288 fprintf(stderr, "error binding netlink socket\n");
1289 log_error("error binding netlink socket\n");
1294 if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
1295 fprintf(stderr, "error binding udev control socket\n");
1296 log_error("error binding udev control socket\n");
1301 udev_monitor_set_receive_buffer_size(monitor, 128*1024*1024);
1303 /* create queue file before signalling 'ready', to make sure we block 'settle' */
1304 udev_queue_export = udev_queue_export_new(udev);
1305 if (udev_queue_export == NULL) {
1306 log_error("error creating queue file\n");
1319 log_error("fork of daemon failed: %m\n");
1324 goto exit_daemonize;
1329 fd = open("/proc/self/oom_score_adj", O_RDWR);
1331 /* Fallback to old interface */
1332 fd = open("/proc/self/oom_adj", O_RDWR);
1334 log_error("error disabling OOM: %m\n");
1336 /* OOM_DISABLE == -17 */
1337 write(fd, "-17", 3);
1341 write(fd, "-1000", 5);
1345 sd_notify(1, "READY=1");
1348 f = fopen("/dev/kmsg", "w");
1350 fprintf(f, "<30>udevd[%u]: starting version " VERSION "\n", getpid());
1357 fd = open("/dev/null", O_RDWR);
1359 dup2(fd, STDIN_FILENO);
1360 dup2(fd, STDOUT_FILENO);
1361 dup2(fd, STDERR_FILENO);
1366 fd_inotify = udev_watch_init(udev);
1367 if (fd_inotify < 0) {
1368 fprintf(stderr, "error initializing inotify\n");
1369 log_error("error initializing inotify\n");
1373 udev_watch_restore(udev);
1375 /* block and listen to all signals on signalfd */
1377 sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
1378 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
1379 if (fd_signal < 0) {
1380 fprintf(stderr, "error creating signalfd\n");
1381 log_error("error creating signalfd\n");
1386 /* unnamed socket from workers to the main daemon */
1387 if (socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, worker_watch) < 0) {
1388 fprintf(stderr, "error creating socketpair\n");
1389 log_error("error creating socketpair\n");
1393 fd_worker = worker_watch[READ_END];
1395 udev_builtin_init(udev);
1397 rules = udev_rules_new(udev, resolve_names);
1398 if (rules == NULL) {
1399 log_error("error reading rules\n");
1403 memset(&ep_ctrl, 0, sizeof(struct epoll_event));
1404 ep_ctrl.events = EPOLLIN;
1405 ep_ctrl.data.fd = fd_ctrl;
1407 memset(&ep_inotify, 0, sizeof(struct epoll_event));
1408 ep_inotify.events = EPOLLIN;
1409 ep_inotify.data.fd = fd_inotify;
1411 memset(&ep_signal, 0, sizeof(struct epoll_event));
1412 ep_signal.events = EPOLLIN;
1413 ep_signal.data.fd = fd_signal;
1415 memset(&ep_netlink, 0, sizeof(struct epoll_event));
1416 ep_netlink.events = EPOLLIN;
1417 ep_netlink.data.fd = fd_netlink;
1419 memset(&ep_worker, 0, sizeof(struct epoll_event));
1420 ep_worker.events = EPOLLIN;
1421 ep_worker.data.fd = fd_worker;
1423 fd_ep = epoll_create1(EPOLL_CLOEXEC);
1425 log_error("error creating epoll fd: %m\n");
1428 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_ctrl, &ep_ctrl) < 0 ||
1429 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_inotify, &ep_inotify) < 0 ||
1430 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
1431 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_netlink, &ep_netlink) < 0 ||
1432 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_worker, &ep_worker) < 0) {
1433 log_error("fail to add fds to epoll: %m\n");
1437 /* if needed, convert old database from earlier udev version */
1440 if (children_max <= 0) {
1441 int memsize = mem_size_mb();
1443 /* set value depending on the amount of RAM */
1445 children_max = 128 + (memsize / 8);
1449 log_debug("set children_max to %u\n", children_max);
1451 udev_rules_apply_static_dev_perms(rules);
1453 udev_list_node_init(&event_list);
1454 udev_list_node_init(&worker_list);
1457 static unsigned long long last_usec;
1458 struct epoll_event ev[8];
1461 bool is_worker, is_signal, is_inotify, is_netlink, is_ctrl;
1465 /* close sources of new events and discard buffered events */
1467 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_ctrl, NULL);
1470 if (monitor != NULL) {
1471 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_netlink, NULL);
1472 udev_monitor_unref(monitor);
1475 if (fd_inotify >= 0) {
1476 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_inotify, NULL);
1481 /* discard queued events and kill workers */
1482 event_queue_cleanup(udev, EVENT_QUEUED);
1483 worker_kill(udev, 0);
1485 /* exit after all has cleaned up */
1486 if (udev_list_node_is_empty(&event_list) && udev_list_node_is_empty(&worker_list))
1489 /* timeout at exit for workers to finish */
1490 timeout = 30 * 1000;
1491 } else if (udev_list_node_is_empty(&event_list) && children <= 2) {
1495 /* kill idle or hanging workers */
1498 fdcount = epoll_wait(fd_ep, ev, ARRAY_SIZE(ev), timeout);
1503 struct udev_list_node *loop;
1507 log_error("timeout, giving up waiting for workers to finish\n");
1511 /* kill idle workers */
1512 if (udev_list_node_is_empty(&event_list)) {
1513 log_debug("cleanup idle workers\n");
1514 worker_kill(udev, 2);
1517 /* check for hanging events */
1518 udev_list_node_foreach(loop, &worker_list) {
1519 struct worker *worker = node_to_worker(loop);
1521 if (worker->state != WORKER_RUNNING)
1524 if ((now_usec() - worker->event_start_usec) > 30 * 1000 * 1000) {
1525 log_error("worker [%u] %s timeout; kill it\n", worker->pid,
1526 worker->event ? worker->event->devpath : "<idle>");
1527 kill(worker->pid, SIGKILL);
1528 worker->state = WORKER_KILLED;
1529 /* drop reference taken for state 'running' */
1530 worker_unref(worker);
1531 if (worker->event) {
1532 log_error("seq %llu '%s' killed\n",
1533 udev_device_get_seqnum(worker->event->dev), worker->event->devpath);
1534 worker->event->exitcode = -64;
1535 event_queue_delete(worker->event, true);
1536 worker->event = NULL;
1543 is_worker = is_signal = is_inotify = is_netlink = is_ctrl = false;
1544 for (i = 0; i < fdcount; i++) {
1545 if (ev[i].data.fd == fd_worker && ev[i].events & EPOLLIN)
1547 else if (ev[i].data.fd == fd_netlink && ev[i].events & EPOLLIN)
1549 else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN)
1551 else if (ev[i].data.fd == fd_inotify && ev[i].events & EPOLLIN)
1553 else if (ev[i].data.fd == fd_ctrl && ev[i].events & EPOLLIN)
1557 /* check for changed config, every 3 seconds at most */
1558 if ((now_usec() - last_usec) > 3 * 1000 * 1000) {
1559 if (check_rules_timestamp(udev))
1561 if (udev_builtin_validate(udev))
1564 last_usec = now_usec();
1567 /* reload requested, HUP signal received, rules changed, builtin changed */
1569 worker_kill(udev, 0);
1570 rules = udev_rules_unref(rules);
1571 udev_builtin_exit(udev);
1575 /* event has finished */
1577 worker_returned(fd_worker);
1580 struct udev_device *dev;
1582 dev = udev_monitor_receive_device(monitor);
1584 udev_device_set_usec_initialized(dev, now_usec());
1585 if (event_queue_insert(dev) < 0)
1586 udev_device_unref(dev);
1590 /* start new events */
1591 if (!udev_list_node_is_empty(&event_list) && !udev_exit && !stop_exec_queue) {
1593 rules = udev_rules_new(udev, resolve_names);
1595 event_queue_start(udev);
1599 struct signalfd_siginfo fdsi;
1602 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
1603 if (size == sizeof(struct signalfd_siginfo))
1604 handle_signal(udev, fdsi.ssi_signo);
1607 /* we are shutting down, the events below are not handled anymore */
1611 /* device node watch */
1613 handle_inotify(udev);
1616 * This needs to be after the inotify handling, to make sure,
1617 * that the ping is send back after the possibly generated
1618 * "change" events by the inotify device node watch.
1620 * A single time we may receive a client connection which we need to
1621 * keep open to block the client. It will be closed right before we
1625 ctrl_conn = handle_ctrl_msg(udev_ctrl);
1630 udev_queue_export_cleanup(udev_queue_export);
1631 udev_ctrl_cleanup(udev_ctrl);
1635 worker_list_cleanup(udev);
1636 event_queue_cleanup(udev, EVENT_UNDEF);
1637 udev_rules_unref(rules);
1638 udev_builtin_exit(udev);
1641 if (worker_watch[READ_END] >= 0)
1642 close(worker_watch[READ_END]);
1643 if (worker_watch[WRITE_END] >= 0)
1644 close(worker_watch[WRITE_END]);
1645 udev_monitor_unref(monitor);
1646 udev_queue_export_unref(udev_queue_export);
1647 udev_ctrl_connection_unref(ctrl_conn);
1648 udev_ctrl_unref(udev_ctrl);
1649 udev_selinux_exit(udev);