2 * Copyright (C) 2004-2011 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)
60 vsnprintf(buf, sizeof(buf), format, args);
61 clock_gettime(CLOCK_MONOTONIC, &ts);
62 fprintf(stderr, "[%llu.%06u] [%u] %s: %s",
63 (unsigned long long) ts.tv_sec, (unsigned int) ts.tv_nsec/1000,
64 (int) getpid(), fn, buf);
66 vsyslog(priority, format, args);
70 static struct udev_rules *rules;
71 static struct udev_queue_export *udev_queue_export;
72 static struct udev_ctrl *udev_ctrl;
73 static struct udev_monitor *monitor;
74 static int worker_watch[2] = { -1, -1 };
75 static int fd_signal = -1;
76 static int fd_ep = -1;
77 static int fd_inotify = -1;
78 static bool stop_exec_queue;
81 static int children_max;
82 static int exec_delay;
83 static sigset_t sigmask_orig;
84 static UDEV_LIST(event_list);
85 static UDEV_LIST(worker_list);
86 static bool udev_exit;
95 struct udev_list_node node;
97 struct udev_device *dev;
98 enum event_state state;
100 unsigned long long int delaying_seqnum;
101 unsigned long long int seqnum;
104 const char *devpath_old;
110 static struct event *node_to_event(struct udev_list_node *node)
114 event = (char *)node;
115 event -= offsetof(struct event, node);
116 return (struct event *)event;
119 static void event_queue_cleanup(struct udev *udev, enum event_state type);
129 struct udev_list_node node;
133 struct udev_monitor *monitor;
134 enum worker_state state;
138 /* passed from worker to main process */
139 struct worker_message {
144 static struct worker *node_to_worker(struct udev_list_node *node)
148 worker = (char *)node;
149 worker -= offsetof(struct worker, node);
150 return (struct worker *)worker;
153 static void event_queue_delete(struct event *event, bool export)
155 udev_list_node_remove(&event->node);
158 udev_queue_export_device_finished(udev_queue_export, event->dev);
159 info(event->udev, "seq %llu done with %i\n", udev_device_get_seqnum(event->dev), event->exitcode);
161 udev_device_unref(event->dev);
165 static struct worker *worker_ref(struct worker *worker)
171 static void worker_cleanup(struct worker *worker)
173 udev_list_node_remove(&worker->node);
174 udev_monitor_unref(worker->monitor);
179 static void worker_unref(struct worker *worker)
182 if (worker->refcount > 0)
184 info(worker->udev, "worker [%u] cleaned up\n", worker->pid);
185 worker_cleanup(worker);
188 static void worker_list_cleanup(struct udev *udev)
190 struct udev_list_node *loop, *tmp;
192 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
193 struct worker *worker = node_to_worker(loop);
195 worker_cleanup(worker);
199 static void worker_new(struct event *event)
201 struct udev *udev = event->udev;
202 struct worker *worker;
203 struct udev_monitor *worker_monitor;
206 /* listen for new events */
207 worker_monitor = udev_monitor_new_from_netlink(udev, NULL);
208 if (worker_monitor == NULL)
210 /* allow the main daemon netlink address to send devices to the worker */
211 udev_monitor_allow_unicast_sender(worker_monitor, monitor);
212 udev_monitor_enable_receiving(worker_monitor);
214 worker = calloc(1, sizeof(struct worker));
215 if (worker == NULL) {
216 udev_monitor_unref(worker_monitor);
219 /* worker + event reference */
220 worker->refcount = 2;
226 struct udev_device *dev = NULL;
228 struct epoll_event ep_signal, ep_monitor;
230 int rc = EXIT_SUCCESS;
232 /* move initial device from queue */
237 worker_list_cleanup(udev);
238 event_queue_cleanup(udev, EVENT_UNDEF);
239 udev_queue_export_unref(udev_queue_export);
240 udev_monitor_unref(monitor);
241 udev_ctrl_unref(udev_ctrl);
244 close(worker_watch[READ_END]);
247 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
249 err(udev, "error creating signalfd %m\n");
254 fd_ep = epoll_create1(EPOLL_CLOEXEC);
256 err(udev, "error creating epoll fd: %m\n");
261 memset(&ep_signal, 0, sizeof(struct epoll_event));
262 ep_signal.events = EPOLLIN;
263 ep_signal.data.fd = fd_signal;
265 fd_monitor = udev_monitor_get_fd(worker_monitor);
266 memset(&ep_monitor, 0, sizeof(struct epoll_event));
267 ep_monitor.events = EPOLLIN;
268 ep_monitor.data.fd = fd_monitor;
270 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
271 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_monitor, &ep_monitor) < 0) {
272 err(udev, "fail to add fds to epoll: %m\n");
277 /* request TERM signal if parent exits */
278 prctl(PR_SET_PDEATHSIG, SIGTERM);
281 struct udev_event *udev_event;
282 struct worker_message msg;
285 info(udev, "seq %llu running\n", udev_device_get_seqnum(dev));
286 udev_event = udev_event_new(dev);
287 if (udev_event == NULL) {
292 /* needed for SIGCHLD/SIGTERM in spawn() */
293 udev_event->fd_signal = fd_signal;
296 udev_event->exec_delay = exec_delay;
298 /* apply rules, create node, symlinks */
299 err = udev_event_execute_rules(udev_event, rules, &sigmask_orig);
302 udev_event_execute_run(udev_event, &sigmask_orig);
304 /* apply/restore inotify watch */
305 if (err == 0 && udev_event->inotify_watch) {
306 udev_watch_begin(udev, dev);
307 udev_device_update_db(dev);
310 /* send processed event back to libudev listeners */
311 udev_monitor_send_device(worker_monitor, NULL, dev);
313 /* send udevd the result of the event execution */
314 memset(&msg, 0, sizeof(struct worker_message));
318 send(worker_watch[WRITE_END], &msg, sizeof(struct worker_message), 0);
320 info(udev, "seq %llu processed with %i\n", udev_device_get_seqnum(dev), err);
322 udev_device_unref(dev);
325 if (udev_event->sigterm) {
326 udev_event_unref(udev_event);
330 udev_event_unref(udev_event);
332 /* wait for more device messages from main udevd, or term signal */
333 while (dev == NULL) {
334 struct epoll_event ev[4];
338 fdcount = epoll_wait(fd_ep, ev, ARRAY_SIZE(ev), -1);
343 err(udev, "failed to poll: %m\n");
347 for (i = 0; i < fdcount; i++) {
348 if (ev[i].data.fd == fd_monitor && ev[i].events & EPOLLIN) {
349 dev = udev_monitor_receive_device(worker_monitor);
351 } else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN) {
352 struct signalfd_siginfo fdsi;
355 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
356 if (size != sizeof(struct signalfd_siginfo))
358 switch (fdsi.ssi_signo) {
367 udev_device_unref(dev);
373 close(worker_watch[WRITE_END]);
374 udev_rules_unref(rules);
375 udev_monitor_unref(worker_monitor);
381 udev_monitor_unref(worker_monitor);
382 event->state = EVENT_QUEUED;
384 err(udev, "fork of child failed: %m\n");
387 /* close monitor, but keep address around */
388 udev_monitor_disconnect(worker_monitor);
389 worker->monitor = worker_monitor;
391 worker->state = WORKER_RUNNING;
392 worker->event = event;
393 event->state = EVENT_RUNNING;
394 udev_list_node_append(&worker->node, &worker_list);
396 info(udev, "seq %llu forked new worker [%u]\n", udev_device_get_seqnum(event->dev), pid);
401 static void event_run(struct event *event, bool force)
403 struct udev_list_node *loop;
405 udev_list_node_foreach(loop, &worker_list) {
406 struct worker *worker = node_to_worker(loop);
409 if (worker->state != WORKER_IDLE)
412 count = udev_monitor_send_device(monitor, worker->monitor, event->dev);
414 err(event->udev, "worker [%u] did not accept message %zi (%m), kill it\n", worker->pid, count);
415 kill(worker->pid, SIGKILL);
416 worker->state = WORKER_KILLED;
420 worker->event = event;
421 worker->state = WORKER_RUNNING;
422 event->state = EVENT_RUNNING;
426 if (!force && children >= children_max) {
427 if (children_max > 1)
428 info(event->udev, "maximum number (%i) of children reached\n", children);
432 /* start new worker and pass initial device */
436 static int event_queue_insert(struct udev_device *dev)
440 event = calloc(1, sizeof(struct event));
444 event->udev = udev_device_get_udev(dev);
446 event->seqnum = udev_device_get_seqnum(dev);
447 event->devpath = udev_device_get_devpath(dev);
448 event->devpath_len = strlen(event->devpath);
449 event->devpath_old = udev_device_get_devpath_old(dev);
450 event->devnum = udev_device_get_devnum(dev);
451 event->is_block = (strcmp("block", udev_device_get_subsystem(dev)) == 0);
452 event->ifindex = udev_device_get_ifindex(dev);
454 udev_queue_export_device_queued(udev_queue_export, dev);
455 info(event->udev, "seq %llu queued, '%s' '%s'\n", udev_device_get_seqnum(dev),
456 udev_device_get_action(dev), udev_device_get_subsystem(dev));
458 event->state = EVENT_QUEUED;
459 udev_list_node_append(&event->node, &event_list);
461 /* run all events with a timeout set immediately */
462 if (udev_device_get_timeout(dev) > 0) {
463 event_run(event, true);
470 static void worker_kill(struct udev *udev, int retain)
472 struct udev_list_node *loop;
475 if (children <= retain)
478 max = children - retain;
480 udev_list_node_foreach(loop, &worker_list) {
481 struct worker *worker = node_to_worker(loop);
486 if (worker->state == WORKER_KILLED)
489 worker->state = WORKER_KILLED;
490 kill(worker->pid, SIGTERM);
494 /* lookup event for identical, parent, child device */
495 static bool is_devpath_busy(struct event *event)
497 struct udev_list_node *loop;
500 /* check if queue contains events we depend on */
501 udev_list_node_foreach(loop, &event_list) {
502 struct event *loop_event = node_to_event(loop);
504 /* we already found a later event, earlier can not block us, no need to check again */
505 if (loop_event->seqnum < event->delaying_seqnum)
508 /* event we checked earlier still exists, no need to check again */
509 if (loop_event->seqnum == event->delaying_seqnum)
512 /* found ourself, no later event can block us */
513 if (loop_event->seqnum >= event->seqnum)
516 /* check major/minor */
517 if (major(event->devnum) != 0 && event->devnum == loop_event->devnum && event->is_block == loop_event->is_block)
520 /* check network device ifindex */
521 if (event->ifindex != 0 && event->ifindex == loop_event->ifindex)
524 /* check our old name */
525 if (event->devpath_old != NULL && strcmp(loop_event->devpath, event->devpath_old) == 0) {
526 event->delaying_seqnum = loop_event->seqnum;
530 /* compare devpath */
531 common = MIN(loop_event->devpath_len, event->devpath_len);
533 /* one devpath is contained in the other? */
534 if (memcmp(loop_event->devpath, event->devpath, common) != 0)
537 /* identical device event found */
538 if (loop_event->devpath_len == event->devpath_len) {
539 /* devices names might have changed/swapped in the meantime */
540 if (major(event->devnum) != 0 && (event->devnum != loop_event->devnum || event->is_block != loop_event->is_block))
542 if (event->ifindex != 0 && event->ifindex != loop_event->ifindex)
544 event->delaying_seqnum = loop_event->seqnum;
548 /* parent device event found */
549 if (event->devpath[common] == '/') {
550 event->delaying_seqnum = loop_event->seqnum;
554 /* child device event found */
555 if (loop_event->devpath[common] == '/') {
556 event->delaying_seqnum = loop_event->seqnum;
560 /* no matching device */
567 static void event_queue_start(struct udev *udev)
569 struct udev_list_node *loop;
571 udev_list_node_foreach(loop, &event_list) {
572 struct event *event = node_to_event(loop);
574 if (event->state != EVENT_QUEUED)
577 /* do not start event if parent or child event is still running */
578 if (is_devpath_busy(event)) {
579 dbg(udev, "delay seq %llu (%s)\n", event->seqnum, event->devpath);
583 event_run(event, false);
587 static void event_queue_cleanup(struct udev *udev, enum event_state match_type)
589 struct udev_list_node *loop, *tmp;
591 udev_list_node_foreach_safe(loop, tmp, &event_list) {
592 struct event *event = node_to_event(loop);
594 if (match_type != EVENT_UNDEF && match_type != event->state)
597 event_queue_delete(event, false);
601 static void worker_returned(int fd_worker)
604 struct worker_message msg;
606 struct udev_list_node *loop;
608 size = recv(fd_worker, &msg, sizeof(struct worker_message), MSG_DONTWAIT);
609 if (size != sizeof(struct worker_message))
612 /* lookup worker who sent the signal */
613 udev_list_node_foreach(loop, &worker_list) {
614 struct worker *worker = node_to_worker(loop);
616 if (worker->pid != msg.pid)
619 /* worker returned */
620 worker->event->exitcode = msg.exitcode;
621 event_queue_delete(worker->event, true);
622 worker->event = NULL;
623 if (worker->state != WORKER_KILLED)
624 worker->state = WORKER_IDLE;
625 worker_unref(worker);
631 /* receive the udevd message from userspace */
632 static struct udev_ctrl_connection *handle_ctrl_msg(struct udev_ctrl *uctrl)
634 struct udev *udev = udev_ctrl_get_udev(uctrl);
635 struct udev_ctrl_connection *ctrl_conn;
636 struct udev_ctrl_msg *ctrl_msg = NULL;
640 ctrl_conn = udev_ctrl_get_connection(uctrl);
641 if (ctrl_conn == NULL)
644 ctrl_msg = udev_ctrl_receive_msg(ctrl_conn);
645 if (ctrl_msg == NULL)
648 i = udev_ctrl_get_set_log_level(ctrl_msg);
650 info(udev, "udevd message (SET_LOG_PRIORITY) received, log_priority=%i\n", i);
651 udev_set_log_priority(udev, i);
652 worker_kill(udev, 0);
655 if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
656 info(udev, "udevd message (STOP_EXEC_QUEUE) received\n");
657 stop_exec_queue = true;
660 if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
661 info(udev, "udevd message (START_EXEC_QUEUE) received\n");
662 stop_exec_queue = false;
665 if (udev_ctrl_get_reload(ctrl_msg) > 0) {
666 info(udev, "udevd message (RELOAD) received\n");
670 str = udev_ctrl_get_set_env(ctrl_msg);
678 val = strchr(key, '=');
682 if (val[0] == '\0') {
683 info(udev, "udevd message (ENV) received, unset '%s'\n", key);
684 udev_add_property(udev, key, NULL);
686 info(udev, "udevd message (ENV) received, set '%s=%s'\n", key, val);
687 udev_add_property(udev, key, val);
690 err(udev, "wrong key format '%s'\n", key);
694 worker_kill(udev, 0);
697 i = udev_ctrl_get_set_children_max(ctrl_msg);
699 info(udev, "udevd message (SET_MAX_CHILDREN) received, children_max=%i\n", i);
703 if (udev_ctrl_get_ping(ctrl_msg) > 0)
704 info(udev, "udevd message (SYNC) received\n");
706 if (udev_ctrl_get_exit(ctrl_msg) > 0) {
707 info(udev, "udevd message (EXIT) received\n");
709 /* keep reference to block the client until we exit */
710 udev_ctrl_connection_ref(ctrl_conn);
713 udev_ctrl_msg_unref(ctrl_msg);
714 return udev_ctrl_connection_unref(ctrl_conn);
717 /* read inotify messages */
718 static int handle_inotify(struct udev *udev)
722 struct inotify_event *ev;
724 if ((ioctl(fd_inotify, FIONREAD, &nbytes) < 0) || (nbytes <= 0))
727 buf = malloc(nbytes);
729 err(udev, "error getting buffer for inotify\n");
733 nbytes = read(fd_inotify, buf, nbytes);
735 for (pos = 0; pos < nbytes; pos += sizeof(struct inotify_event) + ev->len) {
736 struct udev_device *dev;
738 ev = (struct inotify_event *)(buf + pos);
739 dev = udev_watch_lookup(udev, ev->wd);
741 info(udev, "inotify event: %x for %s\n", ev->mask, udev_device_get_devnode(dev));
742 if (ev->mask & IN_CLOSE_WRITE) {
743 char filename[UTIL_PATH_SIZE];
746 info(udev, "device %s closed, synthesising 'change'\n", udev_device_get_devnode(dev));
747 util_strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
748 fd = open(filename, O_WRONLY);
750 if (write(fd, "change", 6) < 0)
751 info(udev, "error writing uevent: %m\n");
755 if (ev->mask & IN_IGNORED)
756 udev_watch_end(udev, dev);
758 udev_device_unref(dev);
767 static void handle_signal(struct udev *udev, int signo)
778 struct udev_list_node *loop, *tmp;
780 pid = waitpid(-1, &status, WNOHANG);
784 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
785 struct worker *worker = node_to_worker(loop);
787 if (worker->pid != pid)
789 info(udev, "worker [%u] exit\n", pid);
791 if (WIFEXITED(status)) {
792 if (WEXITSTATUS(status) != 0)
793 err(udev, "worker [%u] exit with return code %i\n", pid, WEXITSTATUS(status));
794 } else if (WIFSIGNALED(status)) {
795 err(udev, "worker [%u] terminated by signal %i (%s)\n",
796 pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
797 } else if (WIFSTOPPED(status)) {
798 err(udev, "worker [%u] stopped\n", pid);
799 } else if (WIFCONTINUED(status)) {
800 err(udev, "worker [%u] continued\n", pid);
802 err(udev, "worker [%u] exit with status 0x%04x\n", pid, status);
805 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
806 if (worker->event != NULL) {
807 err(udev, "worker [%u] failed while handling '%s'\n",
808 pid, worker->event->devpath);
809 worker->event->exitcode = -32;
810 event_queue_delete(worker->event, true);
811 /* drop reference taken for state 'running' */
812 worker_unref(worker);
815 worker_unref(worker);
826 static void static_dev_create_from_modules(struct udev *udev)
828 struct utsname kernel;
829 char modules[UTIL_PATH_SIZE];
834 util_strscpyl(modules, sizeof(modules), "/lib/modules/", kernel.release, "/modules.devname", NULL);
835 f = fopen(modules, "r");
839 while (fgets(buf, sizeof(buf), f) != NULL) {
847 char filename[UTIL_PATH_SIZE];
853 s = strchr(modname, ' ');
859 s = strchr(devname, ' ');
865 s = strchr(devno, ' ');
867 s = strchr(devno, '\n');
870 if (sscanf(devno, "%c%u:%u", &type, &maj, &min) != 3)
873 /* set sticky bit, so we do not remove the node on module unload */
875 mode = 01600|S_IFCHR;
876 else if (type == 'b')
877 mode = 01600|S_IFBLK;
881 util_strscpyl(filename, sizeof(filename), udev_get_dev_path(udev), "/", devname, NULL);
882 util_create_path_selinux(udev, filename);
883 udev_selinux_setfscreatecon(udev, filename, mode);
884 info(udev, "mknod '%s' %c%u:%u\n", filename, type, maj, min);
885 if (mknod(filename, mode, makedev(maj, min)) < 0 && errno == EEXIST)
886 utimensat(AT_FDCWD, filename, NULL, 0);
887 udev_selinux_resetfscreatecon(udev);
893 static int copy_dev_dir(struct udev *udev, DIR *dir_from, DIR *dir_to, int maxdepth)
897 for (dent = readdir(dir_from); dent != NULL; dent = readdir(dir_from)) {
900 if (dent->d_name[0] == '.')
902 if (fstatat(dirfd(dir_from), dent->d_name, &stats, AT_SYMLINK_NOFOLLOW) != 0)
905 if (S_ISBLK(stats.st_mode) || S_ISCHR(stats.st_mode)) {
906 udev_selinux_setfscreateconat(udev, dirfd(dir_to), dent->d_name, stats.st_mode & 0777);
907 if (mknodat(dirfd(dir_to), dent->d_name, stats.st_mode, stats.st_rdev) == 0) {
908 fchmodat(dirfd(dir_to), dent->d_name, stats.st_mode & 0777, 0);
909 fchownat(dirfd(dir_to), dent->d_name, stats.st_uid, stats.st_gid, 0);
911 utimensat(dirfd(dir_to), dent->d_name, NULL, 0);
913 udev_selinux_resetfscreatecon(udev);
914 } else if (S_ISLNK(stats.st_mode)) {
915 char target[UTIL_PATH_SIZE];
918 len = readlinkat(dirfd(dir_from), dent->d_name, target, sizeof(target));
919 if (len <= 0 || len == (ssize_t)sizeof(target))
922 udev_selinux_setfscreateconat(udev, dirfd(dir_to), dent->d_name, S_IFLNK);
923 if (symlinkat(target, dirfd(dir_to), dent->d_name) < 0 && errno == EEXIST)
924 utimensat(dirfd(dir_to), dent->d_name, NULL, AT_SYMLINK_NOFOLLOW);
925 udev_selinux_resetfscreatecon(udev);
926 } else if (S_ISDIR(stats.st_mode)) {
927 DIR *dir2_from, *dir2_to;
932 udev_selinux_setfscreateconat(udev, dirfd(dir_to), dent->d_name, S_IFDIR|0755);
933 mkdirat(dirfd(dir_to), dent->d_name, 0755);
934 udev_selinux_resetfscreatecon(udev);
936 dir2_to = fdopendir(openat(dirfd(dir_to), dent->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC));
940 dir2_from = fdopendir(openat(dirfd(dir_from), dent->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC));
941 if (dir2_from == NULL) {
946 copy_dev_dir(udev, dir2_from, dir2_to, maxdepth-1);
956 static void static_dev_create_links(struct udev *udev, DIR *dir)
962 static const struct stdlinks stdlinks[] = {
963 { "core", "/proc/kcore" },
964 { "fd", "/proc/self/fd" },
965 { "stdin", "/proc/self/fd/0" },
966 { "stdout", "/proc/self/fd/1" },
967 { "stderr", "/proc/self/fd/2" },
971 for (i = 0; i < ARRAY_SIZE(stdlinks); i++) {
974 if (stat(stdlinks[i].target, &sb) == 0) {
975 udev_selinux_setfscreateconat(udev, dirfd(dir), stdlinks[i].link, S_IFLNK);
976 if (symlinkat(stdlinks[i].target, dirfd(dir), stdlinks[i].link) < 0 && errno == EEXIST)
977 utimensat(dirfd(dir), stdlinks[i].link, NULL, AT_SYMLINK_NOFOLLOW);
978 udev_selinux_resetfscreatecon(udev);
983 static void static_dev_create_from_devices(struct udev *udev, DIR *dir)
987 dir_from = opendir(LIBEXECDIR "/devices");
988 if (dir_from == NULL)
990 copy_dev_dir(udev, dir_from, dir, 8);
994 static void static_dev_create(struct udev *udev)
998 dir = opendir(udev_get_dev_path(udev));
1002 static_dev_create_links(udev, dir);
1003 static_dev_create_from_devices(udev, dir);
1008 static int mem_size_mb(void)
1012 long int memsize = -1;
1014 f = fopen("/proc/meminfo", "r");
1018 while (fgets(buf, sizeof(buf), f) != NULL) {
1021 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
1022 memsize = value / 1024;
1031 static int convert_db(struct udev *udev)
1033 char filename[UTIL_PATH_SIZE];
1035 struct udev_enumerate *udev_enumerate;
1036 struct udev_list_entry *list_entry;
1038 /* current database */
1039 util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/data", NULL);
1040 if (access(filename, F_OK) >= 0)
1043 /* make sure we do not get here again */
1044 util_create_path(udev, filename);
1045 mkdir(filename, 0755);
1048 util_strscpyl(filename, sizeof(filename), udev_get_dev_path(udev), "/.udev/db", NULL);
1049 if (access(filename, F_OK) < 0)
1052 f = fopen("/dev/kmsg", "w");
1054 fprintf(f, "<30>udevd[%u]: converting old udev database\n", getpid());
1058 udev_enumerate = udev_enumerate_new(udev);
1059 if (udev_enumerate == NULL)
1061 udev_enumerate_scan_devices(udev_enumerate);
1062 udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(udev_enumerate)) {
1063 struct udev_device *device;
1065 device = udev_device_new_from_syspath(udev, udev_list_entry_get_name(list_entry));
1069 /* try to find the old database for devices without a current one */
1070 if (udev_device_read_db(device, NULL) < 0) {
1074 char devpath[UTIL_PATH_SIZE];
1075 char from[UTIL_PATH_SIZE];
1079 /* find database in old location */
1080 id = udev_device_get_id_filename(device);
1081 util_strscpyl(from, sizeof(from), udev_get_dev_path(udev), "/.udev/db/", id, NULL);
1082 if (lstat(from, &stats) == 0) {
1084 udev_device_read_db(device, from);
1090 /* find old database with $subsys:$sysname name */
1091 util_strscpyl(from, sizeof(from), udev_get_dev_path(udev),
1092 "/.udev/db/", udev_device_get_subsystem(device), ":",
1093 udev_device_get_sysname(device), NULL);
1094 if (lstat(from, &stats) == 0) {
1096 udev_device_read_db(device, from);
1102 /* find old database with the encoded devpath name */
1103 util_path_encode(udev_device_get_devpath(device), devpath, sizeof(devpath));
1104 util_strscpyl(from, sizeof(from), udev_get_dev_path(udev), "/.udev/db/", devpath, NULL);
1105 if (lstat(from, &stats) == 0) {
1107 udev_device_read_db(device, from);
1113 /* write out new database */
1115 udev_device_update_db(device);
1117 udev_device_unref(device);
1119 udev_enumerate_unref(udev_enumerate);
1123 static int systemd_fds(struct udev *udev, int *rctrl, int *rnetlink)
1125 int ctrl = -1, netlink = -1;
1128 n = sd_listen_fds(true);
1132 for (fd = SD_LISTEN_FDS_START; fd < n + SD_LISTEN_FDS_START; fd++) {
1133 if (sd_is_socket(fd, AF_LOCAL, SOCK_SEQPACKET, -1)) {
1140 if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1)) {
1150 if (ctrl < 0 || netlink < 0)
1153 info(udev, "ctrl=%i netlink=%i\n", ctrl, netlink);
1155 *rnetlink = netlink;
1159 static bool check_rules_timestamp(struct udev *udev)
1162 unsigned long long *stamp_usec;
1164 bool changed = false;
1166 n = udev_get_rules_path(udev, &p, &stamp_usec);
1167 for (i = 0; i < n; i++) {
1170 if (stat(p[i], &stats) < 0)
1173 if (stamp_usec[i] == ts_usec(&stats.st_mtim))
1177 if (stamp_usec[i] != 0) {
1178 info(udev, "reload - timestamp of '%s' changed\n", p[i]);
1182 /* update timestamp */
1183 stamp_usec[i] = ts_usec(&stats.st_mtim);
1189 int main(int argc, char *argv[])
1194 int daemonize = false;
1195 int resolve_names = 1;
1196 static const struct option options[] = {
1197 { "daemon", no_argument, NULL, 'd' },
1198 { "debug", no_argument, NULL, 'D' },
1199 { "children-max", required_argument, NULL, 'c' },
1200 { "exec-delay", required_argument, NULL, 'e' },
1201 { "resolve-names", required_argument, NULL, 'N' },
1202 { "help", no_argument, NULL, 'h' },
1203 { "version", no_argument, NULL, 'V' },
1207 int fd_netlink = -1;
1209 struct epoll_event ep_ctrl, ep_inotify, ep_signal, ep_netlink, ep_worker;
1210 struct udev_ctrl_connection *ctrl_conn = NULL;
1218 udev_log_init("udevd");
1219 udev_set_log_fn(udev, udev_main_log);
1220 info(udev, "version %s\n", VERSION);
1221 udev_selinux_init(udev);
1226 option = getopt_long(argc, argv, "c:deDtN:hV", options, NULL);
1235 children_max = strtoul(optarg, NULL, 0);
1238 exec_delay = strtoul(optarg, NULL, 0);
1242 if (udev_get_log_priority(udev) < LOG_INFO)
1243 udev_set_log_priority(udev, LOG_INFO);
1246 if (strcmp (optarg, "early") == 0) {
1248 } else if (strcmp (optarg, "late") == 0) {
1250 } else if (strcmp (optarg, "never") == 0) {
1253 fprintf(stderr, "resolve-names must be early, late or never\n");
1254 err(udev, "resolve-names must be early, late or never\n");
1259 printf("Usage: udevd OPTIONS\n"
1262 " --children-max=<maximum number of workers>\n"
1263 " --exec-delay=<seconds to wait before executing RUN=>\n"
1264 " --resolve-names=early|late|never\n"
1270 printf("%s\n", VERSION);
1278 * read the kernel commandline, in case we need to get into debug mode
1279 * udev.log-priority=<level> syslog priority
1280 * udev.children-max=<number of workers> events are fully serialized if set to 1
1283 f = fopen("/proc/cmdline", "r");
1287 if (fgets(cmdline, sizeof(cmdline), f) != NULL) {
1290 pos = strstr(cmdline, "udev.log-priority=");
1292 pos += strlen("udev.log-priority=");
1293 udev_set_log_priority(udev, util_log_priority(pos));
1296 pos = strstr(cmdline, "udev.children-max=");
1298 pos += strlen("udev.children-max=");
1299 children_max = strtoul(pos, NULL, 0);
1302 pos = strstr(cmdline, "udev.exec-delay=");
1304 pos += strlen("udev.exec-delay=");
1305 exec_delay = strtoul(pos, NULL, 0);
1311 if (getuid() != 0) {
1312 fprintf(stderr, "root privileges required\n");
1313 err(udev, "root privileges required\n");
1317 /* set umask before creating any file/directory */
1322 mkdir(udev_get_run_path(udev), 0755);
1324 /* create standard links, copy static nodes, create nodes from modules */
1325 static_dev_create(udev);
1326 static_dev_create_from_modules(udev);
1328 /* before opening new files, make sure std{in,out,err} fds are in a sane state */
1332 fd = open("/dev/null", O_RDWR);
1334 if (write(STDOUT_FILENO, 0, 0) < 0)
1335 dup2(fd, STDOUT_FILENO);
1336 if (write(STDERR_FILENO, 0, 0) < 0)
1337 dup2(fd, STDERR_FILENO);
1338 if (fd > STDERR_FILENO)
1341 fprintf(stderr, "cannot open /dev/null\n");
1342 err(udev, "cannot open /dev/null\n");
1346 if (systemd_fds(udev, &fd_ctrl, &fd_netlink) >= 0) {
1347 /* get control and netlink socket from from systemd */
1348 udev_ctrl = udev_ctrl_new_from_fd(udev, fd_ctrl);
1349 if (udev_ctrl == NULL) {
1350 err(udev, "error taking over udev control socket");
1355 monitor = udev_monitor_new_from_netlink_fd(udev, "kernel", fd_netlink);
1356 if (monitor == NULL) {
1357 err(udev, "error taking over netlink socket\n");
1362 /* open control and netlink socket */
1363 udev_ctrl = udev_ctrl_new(udev);
1364 if (udev_ctrl == NULL) {
1365 fprintf(stderr, "error initializing udev control socket");
1366 err(udev, "error initializing udev control socket");
1370 fd_ctrl = udev_ctrl_get_fd(udev_ctrl);
1372 monitor = udev_monitor_new_from_netlink(udev, "kernel");
1373 if (monitor == NULL) {
1374 fprintf(stderr, "error initializing netlink socket\n");
1375 err(udev, "error initializing netlink socket\n");
1379 fd_netlink = udev_monitor_get_fd(monitor);
1382 if (udev_monitor_enable_receiving(monitor) < 0) {
1383 fprintf(stderr, "error binding netlink socket\n");
1384 err(udev, "error binding netlink socket\n");
1389 if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
1390 fprintf(stderr, "error binding udev control socket\n");
1391 err(udev, "error binding udev control socket\n");
1396 udev_monitor_set_receive_buffer_size(monitor, 128*1024*1024);
1398 /* create queue file before signalling 'ready', to make sure we block 'settle' */
1399 udev_queue_export = udev_queue_export_new(udev);
1400 if (udev_queue_export == NULL) {
1401 err(udev, "error creating queue file\n");
1414 err(udev, "fork of daemon failed: %m\n");
1419 goto exit_daemonize;
1424 fd = open("/proc/self/oom_score_adj", O_RDWR);
1426 /* Fallback to old interface */
1427 fd = open("/proc/self/oom_adj", O_RDWR);
1429 err(udev, "error disabling OOM: %m\n");
1431 /* OOM_DISABLE == -17 */
1432 write(fd, "-17", 3);
1436 write(fd, "-1000", 5);
1440 sd_notify(1, "READY=1");
1443 f = fopen("/dev/kmsg", "w");
1445 fprintf(f, "<30>udevd[%u]: starting version " VERSION "\n", getpid());
1452 fd = open("/dev/null", O_RDWR);
1454 dup2(fd, STDIN_FILENO);
1455 dup2(fd, STDOUT_FILENO);
1456 dup2(fd, STDERR_FILENO);
1461 fd_inotify = udev_watch_init(udev);
1462 if (fd_inotify < 0) {
1463 fprintf(stderr, "error initializing inotify\n");
1464 err(udev, "error initializing inotify\n");
1468 udev_watch_restore(udev);
1470 /* block and listen to all signals on signalfd */
1472 sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
1473 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
1474 if (fd_signal < 0) {
1475 fprintf(stderr, "error creating signalfd\n");
1476 err(udev, "error creating signalfd\n");
1481 /* unnamed socket from workers to the main daemon */
1482 if (socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, worker_watch) < 0) {
1483 fprintf(stderr, "error creating socketpair\n");
1484 err(udev, "error creating socketpair\n");
1488 fd_worker = worker_watch[READ_END];
1490 udev_builtin_init(udev);
1492 rules = udev_rules_new(udev, resolve_names);
1493 if (rules == NULL) {
1494 err(udev, "error reading rules\n");
1498 memset(&ep_ctrl, 0, sizeof(struct epoll_event));
1499 ep_ctrl.events = EPOLLIN;
1500 ep_ctrl.data.fd = fd_ctrl;
1502 memset(&ep_inotify, 0, sizeof(struct epoll_event));
1503 ep_inotify.events = EPOLLIN;
1504 ep_inotify.data.fd = fd_inotify;
1506 memset(&ep_signal, 0, sizeof(struct epoll_event));
1507 ep_signal.events = EPOLLIN;
1508 ep_signal.data.fd = fd_signal;
1510 memset(&ep_netlink, 0, sizeof(struct epoll_event));
1511 ep_netlink.events = EPOLLIN;
1512 ep_netlink.data.fd = fd_netlink;
1514 memset(&ep_worker, 0, sizeof(struct epoll_event));
1515 ep_worker.events = EPOLLIN;
1516 ep_worker.data.fd = fd_worker;
1518 fd_ep = epoll_create1(EPOLL_CLOEXEC);
1520 err(udev, "error creating epoll fd: %m\n");
1523 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_ctrl, &ep_ctrl) < 0 ||
1524 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_inotify, &ep_inotify) < 0 ||
1525 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
1526 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_netlink, &ep_netlink) < 0 ||
1527 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_worker, &ep_worker) < 0) {
1528 err(udev, "fail to add fds to epoll: %m\n");
1532 /* if needed, convert old database from earlier udev version */
1535 if (children_max <= 0) {
1536 int memsize = mem_size_mb();
1538 /* set value depending on the amount of RAM */
1540 children_max = 128 + (memsize / 8);
1544 info(udev, "set children_max to %u\n", children_max);
1546 udev_rules_apply_static_dev_perms(rules);
1548 udev_list_node_init(&event_list);
1549 udev_list_node_init(&worker_list);
1552 static unsigned long long last_usec;
1553 struct epoll_event ev[8];
1556 bool is_worker, is_signal, is_inotify, is_netlink, is_ctrl;
1560 /* close sources of new events and discard buffered events */
1562 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_ctrl, NULL);
1565 if (monitor != NULL) {
1566 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_netlink, NULL);
1567 udev_monitor_unref(monitor);
1570 if (fd_inotify >= 0) {
1571 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_inotify, NULL);
1576 /* discard queued events and kill workers */
1577 event_queue_cleanup(udev, EVENT_QUEUED);
1578 worker_kill(udev, 0);
1580 /* exit after all has cleaned up */
1581 if (udev_list_node_is_empty(&event_list) && udev_list_node_is_empty(&worker_list))
1584 /* timeout at exit for workers to finish */
1585 timeout = 60 * 1000;
1586 } else if (udev_list_node_is_empty(&event_list) && children > 2) {
1587 /* set timeout to kill idle workers */
1592 fdcount = epoll_wait(fd_ep, ev, ARRAY_SIZE(ev), timeout);
1598 info(udev, "timeout, giving up waiting for workers to finish\n");
1602 /* timeout - kill idle workers */
1603 worker_kill(udev, 2);
1606 is_worker = is_signal = is_inotify = is_netlink = is_ctrl = false;
1607 for (i = 0; i < fdcount; i++) {
1608 if (ev[i].data.fd == fd_worker && ev[i].events & EPOLLIN)
1610 else if (ev[i].data.fd == fd_netlink && ev[i].events & EPOLLIN)
1612 else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN)
1614 else if (ev[i].data.fd == fd_inotify && ev[i].events & EPOLLIN)
1616 else if (ev[i].data.fd == fd_ctrl && ev[i].events & EPOLLIN)
1620 /* check for changed config, every 3 seconds at most */
1621 if ((now_usec() - last_usec) > 3 * 1000 * 1000) {
1622 if (check_rules_timestamp(udev))
1624 if (udev_builtin_validate(udev))
1627 last_usec = now_usec();
1630 /* reload requested, HUP signal received, rules changed, builtin changed */
1632 worker_kill(udev, 0);
1633 rules = udev_rules_unref(rules);
1634 udev_builtin_exit(udev);
1638 /* event has finished */
1640 worker_returned(fd_worker);
1643 struct udev_device *dev;
1645 dev = udev_monitor_receive_device(monitor);
1647 udev_device_set_usec_initialized(dev, now_usec());
1648 if (event_queue_insert(dev) < 0)
1649 udev_device_unref(dev);
1653 /* start new events */
1654 if (!udev_list_node_is_empty(&event_list) && !udev_exit && !stop_exec_queue) {
1656 rules = udev_rules_new(udev, resolve_names);
1658 event_queue_start(udev);
1662 struct signalfd_siginfo fdsi;
1665 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
1666 if (size == sizeof(struct signalfd_siginfo))
1667 handle_signal(udev, fdsi.ssi_signo);
1670 /* we are shutting down, the events below are not handled anymore */
1674 /* device node watch */
1676 handle_inotify(udev);
1679 * This needs to be after the inotify handling, to make sure,
1680 * that the ping is send back after the possibly generated
1681 * "change" events by the inotify device node watch.
1683 * A single time we may receive a client connection which we need to
1684 * keep open to block the client. It will be closed right before we
1688 ctrl_conn = handle_ctrl_msg(udev_ctrl);
1693 udev_queue_export_cleanup(udev_queue_export);
1694 udev_ctrl_cleanup(udev_ctrl);
1698 worker_list_cleanup(udev);
1699 event_queue_cleanup(udev, EVENT_UNDEF);
1700 udev_rules_unref(rules);
1701 udev_builtin_exit(udev);
1704 if (worker_watch[READ_END] >= 0)
1705 close(worker_watch[READ_END]);
1706 if (worker_watch[WRITE_END] >= 0)
1707 close(worker_watch[WRITE_END]);
1708 udev_monitor_unref(monitor);
1709 udev_queue_export_unref(udev_queue_export);
1710 udev_ctrl_connection_unref(ctrl_conn);
1711 udev_ctrl_unref(udev_ctrl);
1712 udev_selinux_exit(udev);