2 * Copyright (C) 2004-2012 Kay Sievers <kay@vrfy.org>
3 * Copyright (C) 2004 Chris Friesen <chris_friesen@sympatico.ca>
4 * Copyright (C) 2009 Canonical Ltd.
5 * Copyright (C) 2009 Scott James Remnant <scott@netsplit.com>
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
36 #include <sys/prctl.h>
37 #include <sys/socket.h>
39 #include <sys/signalfd.h>
40 #include <sys/epoll.h>
41 #include <sys/mount.h>
45 #include <sys/ioctl.h>
46 #include <sys/inotify.h>
47 #include <sys/utsname.h>
50 #include "udev-util.h"
51 #include "sd-daemon.h"
52 #include "cgroup-util.h"
53 #include "dev-setup.h"
58 void udev_main_log(struct udev
*udev
, int priority
,
59 const char *file
, int line
, const char *fn
,
60 const char *format
, va_list args
)
62 log_metav(priority
, file
, line
, fn
, format
, args
);
65 static struct udev_rules
*rules
;
66 static struct udev_ctrl
*udev_ctrl
;
67 static struct udev_monitor
*monitor
;
68 static int worker_watch
[2] = { -1, -1 };
69 static int fd_signal
= -1;
70 static int fd_ep
= -1;
71 static int fd_inotify
= -1;
72 static bool stop_exec_queue
;
75 static int children_max
;
76 static int exec_delay
;
77 static sigset_t sigmask_orig
;
78 static UDEV_LIST(event_list
);
79 static UDEV_LIST(worker_list
);
80 static char *udev_cgroup
;
81 static bool udev_exit
;
90 struct udev_list_node node
;
92 struct udev_device
*dev
;
93 enum event_state state
;
95 unsigned long long int delaying_seqnum
;
96 unsigned long long int seqnum
;
99 const char *devpath_old
;
108 static inline struct event
*node_to_event(struct udev_list_node
*node
)
110 return container_of(node
, struct event
, node
);
113 static void event_queue_cleanup(struct udev
*udev
, enum event_state type
);
123 struct udev_list_node node
;
127 struct udev_monitor
*monitor
;
128 enum worker_state state
;
130 usec_t event_start_usec
;
133 /* passed from worker to main process */
134 struct worker_message
{
139 static inline struct worker
*node_to_worker(struct udev_list_node
*node
)
141 return container_of(node
, struct worker
, node
);
144 static void event_queue_delete(struct event
*event
)
146 udev_list_node_remove(&event
->node
);
147 udev_device_unref(event
->dev
);
151 static struct worker
*worker_ref(struct worker
*worker
)
157 static void worker_cleanup(struct worker
*worker
)
159 udev_list_node_remove(&worker
->node
);
160 udev_monitor_unref(worker
->monitor
);
165 static void worker_unref(struct worker
*worker
)
168 if (worker
->refcount
> 0)
170 log_debug("worker [%u] cleaned up", worker
->pid
);
171 worker_cleanup(worker
);
174 static void worker_list_cleanup(struct udev
*udev
)
176 struct udev_list_node
*loop
, *tmp
;
178 udev_list_node_foreach_safe(loop
, tmp
, &worker_list
) {
179 struct worker
*worker
= node_to_worker(loop
);
181 worker_cleanup(worker
);
185 static void worker_new(struct event
*event
)
187 struct udev
*udev
= event
->udev
;
188 struct worker
*worker
;
189 struct udev_monitor
*worker_monitor
;
192 /* listen for new events */
193 worker_monitor
= udev_monitor_new_from_netlink(udev
, NULL
);
194 if (worker_monitor
== NULL
)
196 /* allow the main daemon netlink address to send devices to the worker */
197 udev_monitor_allow_unicast_sender(worker_monitor
, monitor
);
198 udev_monitor_enable_receiving(worker_monitor
);
200 worker
= new0(struct worker
, 1);
201 if (worker
== NULL
) {
202 udev_monitor_unref(worker_monitor
);
205 /* worker + event reference */
206 worker
->refcount
= 2;
212 struct udev_device
*dev
= NULL
;
214 struct epoll_event ep_signal
, ep_monitor
;
216 int rc
= EXIT_SUCCESS
;
218 /* take initial device from queue */
223 worker_list_cleanup(udev
);
224 event_queue_cleanup(udev
, EVENT_UNDEF
);
225 udev_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");
239 fd_ep
= epoll_create1(EPOLL_CLOEXEC
);
241 log_error("error creating epoll fd: %m");
246 memzero(&ep_signal
, 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 memzero(&ep_monitor
, 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");
262 /* request TERM signal if parent exits */
263 prctl(PR_SET_PDEATHSIG
, SIGTERM
);
265 /* reset OOM score, we only protect the main daemon */
266 write_string_file("/proc/self/oom_score_adj", "0");
269 struct udev_event
*udev_event
;
270 struct worker_message msg
;
274 log_debug("seq %llu running", udev_device_get_seqnum(dev
));
275 udev_event
= udev_event_new(dev
);
276 if (udev_event
== NULL
) {
281 /* needed for SIGCHLD/SIGTERM in spawn() */
282 udev_event
->fd_signal
= fd_signal
;
285 udev_event
->exec_delay
= exec_delay
;
288 * Take a "read lock" on the device node; this establishes
289 * a concept of device "ownership" to serialize device
290 * access. External processes holding a "write lock" will
291 * cause udev to skip the event handling; in the case udev
292 * acquired the lock, the external process will block until
293 * udev has finished its event handling.
297 * <kabi_> since we make check - device seems unused - we try
298 * ioctl to deactivate - and device is found to be opened
299 * <kay> sure, you try to take a write lock
300 * <kay> if you get it udev is out
301 * <kay> if you can't get it, udev is busy
302 * <kabi_> we cannot deactivate openned device (as it is in-use)
303 * <kay> maybe we should just exclude dm from that thing entirely
304 * <kabi_> IMHO this sounds like a good plan for this moment
306 if (streq_ptr("block", udev_device_get_subsystem(dev
)) &&
307 !startswith(udev_device_get_sysname(dev
), "dm-")) {
308 struct udev_device
*d
= dev
;
310 if (streq_ptr("partition", udev_device_get_devtype(d
)))
311 d
= udev_device_get_parent(d
);
314 fd_lock
= open(udev_device_get_devnode(d
), O_RDONLY
|O_CLOEXEC
|O_NOFOLLOW
|O_NONBLOCK
);
315 if (fd_lock
>= 0 && flock(fd_lock
, LOCK_SH
|LOCK_NB
) < 0) {
316 log_debug("Unable to flock(%s), skipping event handling: %m", udev_device_get_devnode(d
));
318 fd_lock
= safe_close(fd_lock
);
324 /* apply rules, create node, symlinks */
325 udev_event_execute_rules(udev_event
, rules
, &sigmask_orig
);
327 udev_event_execute_run(udev_event
, &sigmask_orig
);
329 /* apply/restore inotify watch */
330 if (udev_event
->inotify_watch
) {
331 udev_watch_begin(udev
, dev
);
332 udev_device_update_db(dev
);
337 /* send processed event back to libudev listeners */
338 udev_monitor_send_device(worker_monitor
, NULL
, dev
);
341 /* send udevd the result of the event execution */
342 memzero(&msg
, sizeof(struct worker_message
));
345 send(worker_watch
[WRITE_END
], &msg
, sizeof(struct worker_message
), 0);
347 log_debug("seq %llu processed with %i", udev_device_get_seqnum(dev
), err
);
349 udev_device_unref(dev
);
352 if (udev_event
->sigterm
) {
353 udev_event_unref(udev_event
);
357 udev_event_unref(udev_event
);
359 /* wait for more device messages from main udevd, or term signal */
360 while (dev
== NULL
) {
361 struct epoll_event ev
[4];
365 fdcount
= epoll_wait(fd_ep
, ev
, ELEMENTSOF(ev
), -1);
369 log_error("failed to poll: %m");
373 for (i
= 0; i
< fdcount
; i
++) {
374 if (ev
[i
].data
.fd
== fd_monitor
&& ev
[i
].events
& EPOLLIN
) {
375 dev
= udev_monitor_receive_device(worker_monitor
);
377 } else if (ev
[i
].data
.fd
== fd_signal
&& ev
[i
].events
& EPOLLIN
) {
378 struct signalfd_siginfo fdsi
;
381 size
= read(fd_signal
, &fdsi
, sizeof(struct signalfd_siginfo
));
382 if (size
!= sizeof(struct signalfd_siginfo
))
384 switch (fdsi
.ssi_signo
) {
393 udev_device_unref(dev
);
394 safe_close(fd_signal
);
397 close(worker_watch
[WRITE_END
]);
398 udev_rules_unref(rules
);
399 udev_builtin_exit(udev
);
400 udev_monitor_unref(worker_monitor
);
406 udev_monitor_unref(worker_monitor
);
407 event
->state
= EVENT_QUEUED
;
409 log_error("fork of child failed: %m");
412 /* close monitor, but keep address around */
413 udev_monitor_disconnect(worker_monitor
);
414 worker
->monitor
= worker_monitor
;
416 worker
->state
= WORKER_RUNNING
;
417 worker
->event_start_usec
= now(CLOCK_MONOTONIC
);
418 worker
->event
= event
;
419 event
->state
= EVENT_RUNNING
;
420 udev_list_node_append(&worker
->node
, &worker_list
);
422 log_debug("seq %llu forked new worker [%u]", udev_device_get_seqnum(event
->dev
), pid
);
427 static void event_run(struct event
*event
)
429 struct udev_list_node
*loop
;
431 udev_list_node_foreach(loop
, &worker_list
) {
432 struct worker
*worker
= node_to_worker(loop
);
435 if (worker
->state
!= WORKER_IDLE
)
438 count
= udev_monitor_send_device(monitor
, worker
->monitor
, event
->dev
);
440 log_error("worker [%u] did not accept message %zi (%m), kill it", worker
->pid
, count
);
441 kill(worker
->pid
, SIGKILL
);
442 worker
->state
= WORKER_KILLED
;
446 worker
->event
= event
;
447 worker
->state
= WORKER_RUNNING
;
448 worker
->event_start_usec
= now(CLOCK_MONOTONIC
);
449 event
->state
= EVENT_RUNNING
;
453 if (children
>= children_max
) {
454 if (children_max
> 1)
455 log_debug("maximum number (%i) of children reached", children
);
459 /* start new worker and pass initial device */
463 static int event_queue_insert(struct udev_device
*dev
)
467 event
= new0(struct event
, 1);
471 event
->udev
= udev_device_get_udev(dev
);
473 event
->seqnum
= udev_device_get_seqnum(dev
);
474 event
->devpath
= udev_device_get_devpath(dev
);
475 event
->devpath_len
= strlen(event
->devpath
);
476 event
->devpath_old
= udev_device_get_devpath_old(dev
);
477 event
->devnum
= udev_device_get_devnum(dev
);
478 event
->is_block
= streq("block", udev_device_get_subsystem(dev
));
479 event
->ifindex
= udev_device_get_ifindex(dev
);
481 if (streq(udev_device_get_subsystem(dev
), "firmware"))
482 event
->nodelay
= true;
485 log_debug("seq %llu queued, '%s' '%s'", udev_device_get_seqnum(dev
),
486 udev_device_get_action(dev
), udev_device_get_subsystem(dev
));
488 event
->state
= EVENT_QUEUED
;
489 udev_list_node_append(&event
->node
, &event_list
);
493 static void worker_kill(struct udev
*udev
)
495 struct udev_list_node
*loop
;
497 udev_list_node_foreach(loop
, &worker_list
) {
498 struct worker
*worker
= node_to_worker(loop
);
500 if (worker
->state
== WORKER_KILLED
)
503 worker
->state
= WORKER_KILLED
;
504 kill(worker
->pid
, SIGTERM
);
508 /* lookup event for identical, parent, child device */
509 static bool is_devpath_busy(struct event
*event
)
511 struct udev_list_node
*loop
;
514 /* check if queue contains events we depend on */
515 udev_list_node_foreach(loop
, &event_list
) {
516 struct event
*loop_event
= node_to_event(loop
);
518 /* we already found a later event, earlier can not block us, no need to check again */
519 if (loop_event
->seqnum
< event
->delaying_seqnum
)
522 /* event we checked earlier still exists, no need to check again */
523 if (loop_event
->seqnum
== event
->delaying_seqnum
)
526 /* found ourself, no later event can block us */
527 if (loop_event
->seqnum
>= event
->seqnum
)
530 /* check major/minor */
531 if (major(event
->devnum
) != 0 && event
->devnum
== loop_event
->devnum
&& event
->is_block
== loop_event
->is_block
)
534 /* check network device ifindex */
535 if (event
->ifindex
!= 0 && event
->ifindex
== loop_event
->ifindex
)
538 /* check our old name */
539 if (event
->devpath_old
!= NULL
&& streq(loop_event
->devpath
, event
->devpath_old
)) {
540 event
->delaying_seqnum
= loop_event
->seqnum
;
544 /* compare devpath */
545 common
= MIN(loop_event
->devpath_len
, event
->devpath_len
);
547 /* one devpath is contained in the other? */
548 if (memcmp(loop_event
->devpath
, event
->devpath
, common
) != 0)
551 /* identical device event found */
552 if (loop_event
->devpath_len
== event
->devpath_len
) {
553 /* devices names might have changed/swapped in the meantime */
554 if (major(event
->devnum
) != 0 && (event
->devnum
!= loop_event
->devnum
|| event
->is_block
!= loop_event
->is_block
))
556 if (event
->ifindex
!= 0 && event
->ifindex
!= loop_event
->ifindex
)
558 event
->delaying_seqnum
= loop_event
->seqnum
;
563 /* allow to bypass the dependency tracking */
568 /* parent device event found */
569 if (event
->devpath
[common
] == '/') {
570 event
->delaying_seqnum
= loop_event
->seqnum
;
574 /* child device event found */
575 if (loop_event
->devpath
[common
] == '/') {
576 event
->delaying_seqnum
= loop_event
->seqnum
;
580 /* no matching device */
587 static void event_queue_start(struct udev
*udev
)
589 struct udev_list_node
*loop
;
591 udev_list_node_foreach(loop
, &event_list
) {
592 struct event
*event
= node_to_event(loop
);
594 if (event
->state
!= EVENT_QUEUED
)
597 /* do not start event if parent or child event is still running */
598 if (is_devpath_busy(event
))
605 static void event_queue_cleanup(struct udev
*udev
, enum event_state match_type
)
607 struct udev_list_node
*loop
, *tmp
;
609 udev_list_node_foreach_safe(loop
, tmp
, &event_list
) {
610 struct event
*event
= node_to_event(loop
);
612 if (match_type
!= EVENT_UNDEF
&& match_type
!= event
->state
)
615 event_queue_delete(event
);
619 static void worker_returned(int fd_worker
)
622 struct worker_message msg
;
624 struct udev_list_node
*loop
;
626 size
= recv(fd_worker
, &msg
, sizeof(struct worker_message
), MSG_DONTWAIT
);
627 if (size
!= sizeof(struct worker_message
))
630 /* lookup worker who sent the signal */
631 udev_list_node_foreach(loop
, &worker_list
) {
632 struct worker
*worker
= node_to_worker(loop
);
634 if (worker
->pid
!= msg
.pid
)
637 /* worker returned */
639 worker
->event
->exitcode
= msg
.exitcode
;
640 event_queue_delete(worker
->event
);
641 worker
->event
= NULL
;
643 if (worker
->state
!= WORKER_KILLED
)
644 worker
->state
= WORKER_IDLE
;
645 worker_unref(worker
);
651 /* receive the udevd message from userspace */
652 static struct udev_ctrl_connection
*handle_ctrl_msg(struct udev_ctrl
*uctrl
)
654 struct udev
*udev
= udev_ctrl_get_udev(uctrl
);
655 struct udev_ctrl_connection
*ctrl_conn
;
656 struct udev_ctrl_msg
*ctrl_msg
= NULL
;
660 ctrl_conn
= udev_ctrl_get_connection(uctrl
);
661 if (ctrl_conn
== NULL
)
664 ctrl_msg
= udev_ctrl_receive_msg(ctrl_conn
);
665 if (ctrl_msg
== NULL
)
668 i
= udev_ctrl_get_set_log_level(ctrl_msg
);
670 log_debug("udevd message (SET_LOG_LEVEL) received, log_priority=%i", i
);
671 log_set_max_level(i
);
672 udev_set_log_priority(udev
, i
);
676 if (udev_ctrl_get_stop_exec_queue(ctrl_msg
) > 0) {
677 log_debug("udevd message (STOP_EXEC_QUEUE) received");
678 stop_exec_queue
= true;
681 if (udev_ctrl_get_start_exec_queue(ctrl_msg
) > 0) {
682 log_debug("udevd message (START_EXEC_QUEUE) received");
683 stop_exec_queue
= false;
686 if (udev_ctrl_get_reload(ctrl_msg
) > 0) {
687 log_debug("udevd message (RELOAD) received");
691 str
= udev_ctrl_get_set_env(ctrl_msg
);
699 val
= strchr(key
, '=');
703 if (val
[0] == '\0') {
704 log_debug("udevd message (ENV) received, unset '%s'", key
);
705 udev_add_property(udev
, key
, NULL
);
707 log_debug("udevd message (ENV) received, set '%s=%s'", key
, val
);
708 udev_add_property(udev
, key
, val
);
711 log_error("wrong key format '%s'", key
);
718 i
= udev_ctrl_get_set_children_max(ctrl_msg
);
720 log_debug("udevd message (SET_MAX_CHILDREN) received, children_max=%i", i
);
724 if (udev_ctrl_get_ping(ctrl_msg
) > 0)
725 log_debug("udevd message (SYNC) received");
727 if (udev_ctrl_get_exit(ctrl_msg
) > 0) {
728 log_debug("udevd message (EXIT) received");
730 /* keep reference to block the client until we exit */
731 udev_ctrl_connection_ref(ctrl_conn
);
734 udev_ctrl_msg_unref(ctrl_msg
);
735 return udev_ctrl_connection_unref(ctrl_conn
);
738 static int synthesize_change(struct udev_device
*dev
) {
739 char filename
[UTIL_PATH_SIZE
];
742 if (streq_ptr("block", udev_device_get_subsystem(dev
)) &&
743 streq_ptr("disk", udev_device_get_devtype(dev
)) &&
744 !startswith(udev_device_get_sysname(dev
), "dm-")) {
745 bool part_table_read
= false;
746 bool has_partitions
= false;
748 struct udev
*udev
= udev_device_get_udev(dev
);
749 _cleanup_udev_enumerate_unref_
struct udev_enumerate
*e
= NULL
;
750 struct udev_list_entry
*item
;
753 * Try to re-read the partition table. This only succeeds if
754 * none of the devices is busy. The kernel returns 0 if no
755 * partition table is found, and we will not get an event for
758 fd
= open(udev_device_get_devnode(dev
), O_RDONLY
|O_CLOEXEC
|O_NOFOLLOW
|O_NONBLOCK
);
760 r
= flock(fd
, LOCK_EX
|LOCK_NB
);
762 r
= ioctl(fd
, BLKRRPART
, 0);
766 part_table_read
= true;
769 /* search for partitions */
770 e
= udev_enumerate_new(udev
);
774 r
= udev_enumerate_add_match_parent(e
, dev
);
778 r
= udev_enumerate_add_match_subsystem(e
, "block");
782 r
= udev_enumerate_scan_devices(e
);
786 udev_list_entry_foreach(item
, udev_enumerate_get_list_entry(e
)) {
787 _cleanup_udev_device_unref_
struct udev_device
*d
= NULL
;
789 d
= udev_device_new_from_syspath(udev
, udev_list_entry_get_name(item
));
793 if (!streq_ptr("partition", udev_device_get_devtype(d
)))
796 has_partitions
= true;
801 * We have partitions and re-read the table, the kernel already sent
802 * out a "change" event for the disk, and "remove/add" for all
805 if (part_table_read
&& has_partitions
)
809 * We have partitions but re-reading the partition table did not
810 * work, synthesize "change" for the disk and all partitions.
812 log_debug("device %s closed, synthesising 'change'", udev_device_get_devnode(dev
));
813 strscpyl(filename
, sizeof(filename
), udev_device_get_syspath(dev
), "/uevent", NULL
);
814 write_string_file(filename
, "change");
816 udev_list_entry_foreach(item
, udev_enumerate_get_list_entry(e
)) {
817 _cleanup_udev_device_unref_
struct udev_device
*d
= NULL
;
819 d
= udev_device_new_from_syspath(udev
, udev_list_entry_get_name(item
));
823 if (!streq_ptr("partition", udev_device_get_devtype(d
)))
826 log_debug("device %s closed, synthesising partition '%s' 'change'",
827 udev_device_get_devnode(dev
), udev_device_get_devnode(d
));
828 strscpyl(filename
, sizeof(filename
), udev_device_get_syspath(d
), "/uevent", NULL
);
829 write_string_file(filename
, "change");
835 log_debug("device %s closed, synthesising 'change'", udev_device_get_devnode(dev
));
836 strscpyl(filename
, sizeof(filename
), udev_device_get_syspath(dev
), "/uevent", NULL
);
837 write_string_file(filename
, "change");
842 static int handle_inotify(struct udev
*udev
)
846 struct inotify_event
*ev
;
849 r
= ioctl(fd_inotify
, FIONREAD
, &nbytes
);
850 if (r
< 0 || nbytes
<= 0)
853 buf
= malloc(nbytes
);
855 log_error("error getting buffer for inotify");
859 nbytes
= read(fd_inotify
, buf
, nbytes
);
861 for (pos
= 0; pos
< nbytes
; pos
+= sizeof(struct inotify_event
) + ev
->len
) {
862 struct udev_device
*dev
;
864 ev
= (struct inotify_event
*)(buf
+ pos
);
865 dev
= udev_watch_lookup(udev
, ev
->wd
);
869 log_debug("inotify event: %x for %s", ev
->mask
, udev_device_get_devnode(dev
));
870 if (ev
->mask
& IN_CLOSE_WRITE
)
871 synthesize_change(dev
);
872 else if (ev
->mask
& IN_IGNORED
)
873 udev_watch_end(udev
, dev
);
875 udev_device_unref(dev
);
882 static void handle_signal(struct udev
*udev
, int signo
)
893 struct udev_list_node
*loop
, *tmp
;
895 pid
= waitpid(-1, &status
, WNOHANG
);
899 udev_list_node_foreach_safe(loop
, tmp
, &worker_list
) {
900 struct worker
*worker
= node_to_worker(loop
);
902 if (worker
->pid
!= pid
)
904 log_debug("worker [%u] exit", pid
);
906 if (WIFEXITED(status
)) {
907 if (WEXITSTATUS(status
) != 0)
908 log_error("worker [%u] exit with return code %i",
909 pid
, WEXITSTATUS(status
));
910 } else if (WIFSIGNALED(status
)) {
911 log_error("worker [%u] terminated by signal %i (%s)",
912 pid
, WTERMSIG(status
), strsignal(WTERMSIG(status
)));
913 } else if (WIFSTOPPED(status
)) {
914 log_error("worker [%u] stopped", pid
);
915 } else if (WIFCONTINUED(status
)) {
916 log_error("worker [%u] continued", pid
);
918 log_error("worker [%u] exit with status 0x%04x", pid
, status
);
921 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0) {
923 log_error("worker [%u] failed while handling '%s'",
924 pid
, worker
->event
->devpath
);
925 worker
->event
->exitcode
= -32;
926 event_queue_delete(worker
->event
);
928 /* drop reference taken for state 'running' */
929 worker_unref(worker
);
932 worker_unref(worker
);
943 static int systemd_fds(struct udev
*udev
, int *rctrl
, int *rnetlink
)
945 int ctrl
= -1, netlink
= -1;
948 n
= sd_listen_fds(true);
952 for (fd
= SD_LISTEN_FDS_START
; fd
< n
+ SD_LISTEN_FDS_START
; fd
++) {
953 if (sd_is_socket(fd
, AF_LOCAL
, SOCK_SEQPACKET
, -1)) {
960 if (sd_is_socket(fd
, AF_NETLINK
, SOCK_RAW
, -1)) {
970 if (ctrl
< 0 || netlink
< 0)
973 log_debug("ctrl=%i netlink=%i", ctrl
, netlink
);
980 * read the kernel commandline, in case we need to get into debug mode
981 * udev.log-priority=<level> syslog priority
982 * udev.children-max=<number of workers> events are fully serialized if set to 1
983 * udev.exec-delay=<number of seconds> delay execution of every executed program
985 static void kernel_cmdline_options(struct udev
*udev
)
987 _cleanup_free_
char *line
= NULL
;
992 r
= proc_cmdline(&line
);
994 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r
));
998 FOREACH_WORD_QUOTED(w
, l
, line
, state
) {
1005 /* accept the same options for the initrd, prefixed with "rd." */
1006 if (in_initrd() && startswith(s
, "rd."))
1011 if (startswith(opt
, "udev.log-priority=")) {
1014 prio
= util_log_priority(opt
+ 18);
1015 log_set_max_level(prio
);
1016 udev_set_log_priority(udev
, prio
);
1017 } else if (startswith(opt
, "udev.children-max=")) {
1018 children_max
= strtoul(opt
+ 18, NULL
, 0);
1019 } else if (startswith(opt
, "udev.exec-delay=")) {
1020 exec_delay
= strtoul(opt
+ 16, NULL
, 0);
1027 int main(int argc
, char *argv
[])
1031 int daemonize
= false;
1032 int resolve_names
= 1;
1033 static const struct option options
[] = {
1034 { "daemon", no_argument
, NULL
, 'd' },
1035 { "debug", no_argument
, NULL
, 'D' },
1036 { "children-max", required_argument
, NULL
, 'c' },
1037 { "exec-delay", required_argument
, NULL
, 'e' },
1038 { "resolve-names", required_argument
, NULL
, 'N' },
1039 { "help", no_argument
, NULL
, 'h' },
1040 { "version", no_argument
, NULL
, 'V' },
1044 int fd_netlink
= -1;
1046 struct epoll_event ep_ctrl
, ep_inotify
, ep_signal
, ep_netlink
, ep_worker
;
1047 struct udev_ctrl_connection
*ctrl_conn
= NULL
;
1054 log_set_target(LOG_TARGET_AUTO
);
1055 log_parse_environment();
1058 udev_set_log_fn(udev
, udev_main_log
);
1059 log_set_max_level(udev_get_log_priority(udev
));
1061 log_debug("version %s", VERSION
);
1067 option
= getopt_long(argc
, argv
, "c:de:DtN:hV", options
, NULL
);
1076 children_max
= strtoul(optarg
, NULL
, 0);
1079 exec_delay
= strtoul(optarg
, NULL
, 0);
1083 log_set_max_level(LOG_DEBUG
);
1084 udev_set_log_priority(udev
, LOG_DEBUG
);
1087 if (streq(optarg
, "early")) {
1089 } else if (streq(optarg
, "late")) {
1091 } else if (streq(optarg
, "never")) {
1094 fprintf(stderr
, "resolve-names must be early, late or never\n");
1095 log_error("resolve-names must be early, late or never");
1100 printf("Usage: udevd OPTIONS\n"
1103 " --children-max=<maximum number of workers>\n"
1104 " --exec-delay=<seconds to wait before executing RUN=>\n"
1105 " --resolve-names=early|late|never\n"
1111 printf("%s\n", VERSION
);
1118 kernel_cmdline_options(udev
);
1120 if (getuid() != 0) {
1121 fprintf(stderr
, "root privileges required\n");
1122 log_error("root privileges required");
1126 /* set umask before creating any file/directory */
1130 mkdir("/run/udev", 0755);
1134 /* before opening new files, make sure std{in,out,err} fds are in a sane state */
1138 fd
= open("/dev/null", O_RDWR
);
1140 if (write(STDOUT_FILENO
, 0, 0) < 0)
1141 dup2(fd
, STDOUT_FILENO
);
1142 if (write(STDERR_FILENO
, 0, 0) < 0)
1143 dup2(fd
, STDERR_FILENO
);
1144 if (fd
> STDERR_FILENO
)
1147 fprintf(stderr
, "cannot open /dev/null\n");
1148 log_error("cannot open /dev/null");
1152 if (systemd_fds(udev
, &fd_ctrl
, &fd_netlink
) >= 0) {
1153 /* get control and netlink socket from systemd */
1154 udev_ctrl
= udev_ctrl_new_from_fd(udev
, fd_ctrl
);
1155 if (udev_ctrl
== NULL
) {
1156 log_error("error taking over udev control socket");
1161 monitor
= udev_monitor_new_from_netlink_fd(udev
, "kernel", fd_netlink
);
1162 if (monitor
== NULL
) {
1163 log_error("error taking over netlink socket");
1168 /* get our own cgroup, we regularly kill everything udev has left behind */
1169 if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, 0, &udev_cgroup
) < 0)
1172 /* open control and netlink socket */
1173 udev_ctrl
= udev_ctrl_new(udev
);
1174 if (udev_ctrl
== NULL
) {
1175 fprintf(stderr
, "error initializing udev control socket");
1176 log_error("error initializing udev control socket");
1180 fd_ctrl
= udev_ctrl_get_fd(udev_ctrl
);
1182 monitor
= udev_monitor_new_from_netlink(udev
, "kernel");
1183 if (monitor
== NULL
) {
1184 fprintf(stderr
, "error initializing netlink socket\n");
1185 log_error("error initializing netlink socket");
1189 fd_netlink
= udev_monitor_get_fd(monitor
);
1192 if (udev_monitor_enable_receiving(monitor
) < 0) {
1193 fprintf(stderr
, "error binding netlink socket\n");
1194 log_error("error binding netlink socket");
1199 if (udev_ctrl_enable_receiving(udev_ctrl
) < 0) {
1200 fprintf(stderr
, "error binding udev control socket\n");
1201 log_error("error binding udev control socket");
1206 udev_monitor_set_receive_buffer_size(monitor
, 128 * 1024 * 1024);
1216 log_error("fork of daemon failed: %m");
1221 goto exit_daemonize
;
1226 write_string_file("/proc/self/oom_score_adj", "-1000");
1228 sd_notify(1, "READY=1");
1231 print_kmsg("starting version " VERSION
"\n");
1236 fd
= open("/dev/null", O_RDWR
);
1238 dup2(fd
, STDIN_FILENO
);
1239 dup2(fd
, STDOUT_FILENO
);
1240 dup2(fd
, STDERR_FILENO
);
1245 fd_inotify
= udev_watch_init(udev
);
1246 if (fd_inotify
< 0) {
1247 fprintf(stderr
, "error initializing inotify\n");
1248 log_error("error initializing inotify");
1252 udev_watch_restore(udev
);
1254 /* block and listen to all signals on signalfd */
1256 sigprocmask(SIG_SETMASK
, &mask
, &sigmask_orig
);
1257 fd_signal
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
);
1258 if (fd_signal
< 0) {
1259 fprintf(stderr
, "error creating signalfd\n");
1260 log_error("error creating signalfd");
1265 /* unnamed socket from workers to the main daemon */
1266 if (socketpair(AF_LOCAL
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0, worker_watch
) < 0) {
1267 fprintf(stderr
, "error creating socketpair\n");
1268 log_error("error creating socketpair");
1272 fd_worker
= worker_watch
[READ_END
];
1274 udev_builtin_init(udev
);
1276 rules
= udev_rules_new(udev
, resolve_names
);
1277 if (rules
== NULL
) {
1278 log_error("error reading rules");
1282 memzero(&ep_ctrl
, sizeof(struct epoll_event
));
1283 ep_ctrl
.events
= EPOLLIN
;
1284 ep_ctrl
.data
.fd
= fd_ctrl
;
1286 memzero(&ep_inotify
, sizeof(struct epoll_event
));
1287 ep_inotify
.events
= EPOLLIN
;
1288 ep_inotify
.data
.fd
= fd_inotify
;
1290 memzero(&ep_signal
, sizeof(struct epoll_event
));
1291 ep_signal
.events
= EPOLLIN
;
1292 ep_signal
.data
.fd
= fd_signal
;
1294 memzero(&ep_netlink
, sizeof(struct epoll_event
));
1295 ep_netlink
.events
= EPOLLIN
;
1296 ep_netlink
.data
.fd
= fd_netlink
;
1298 memzero(&ep_worker
, sizeof(struct epoll_event
));
1299 ep_worker
.events
= EPOLLIN
;
1300 ep_worker
.data
.fd
= fd_worker
;
1302 fd_ep
= epoll_create1(EPOLL_CLOEXEC
);
1304 log_error("error creating epoll fd: %m");
1307 if (epoll_ctl(fd_ep
, EPOLL_CTL_ADD
, fd_ctrl
, &ep_ctrl
) < 0 ||
1308 epoll_ctl(fd_ep
, EPOLL_CTL_ADD
, fd_inotify
, &ep_inotify
) < 0 ||
1309 epoll_ctl(fd_ep
, EPOLL_CTL_ADD
, fd_signal
, &ep_signal
) < 0 ||
1310 epoll_ctl(fd_ep
, EPOLL_CTL_ADD
, fd_netlink
, &ep_netlink
) < 0 ||
1311 epoll_ctl(fd_ep
, EPOLL_CTL_ADD
, fd_worker
, &ep_worker
) < 0) {
1312 log_error("fail to add fds to epoll: %m");
1316 if (children_max
<= 0) {
1321 if (sched_getaffinity(0, sizeof (cpu_set
), &cpu_set
) == 0) {
1322 children_max
+= CPU_COUNT(&cpu_set
) * 2;
1325 log_debug("set children_max to %u", children_max
);
1327 rc
= udev_rules_apply_static_dev_perms(rules
);
1329 log_error("failed to apply permissions on static device nodes - %s", strerror(-rc
));
1331 udev_list_node_init(&event_list
);
1332 udev_list_node_init(&worker_list
);
1335 static usec_t last_usec
;
1336 struct epoll_event ev
[8];
1339 bool is_worker
, is_signal
, is_inotify
, is_netlink
, is_ctrl
;
1343 /* close sources of new events and discard buffered events */
1345 epoll_ctl(fd_ep
, EPOLL_CTL_DEL
, fd_ctrl
, NULL
);
1348 if (monitor
!= NULL
) {
1349 epoll_ctl(fd_ep
, EPOLL_CTL_DEL
, fd_netlink
, NULL
);
1350 udev_monitor_unref(monitor
);
1353 if (fd_inotify
>= 0) {
1354 epoll_ctl(fd_ep
, EPOLL_CTL_DEL
, fd_inotify
, NULL
);
1359 /* discard queued events and kill workers */
1360 event_queue_cleanup(udev
, EVENT_QUEUED
);
1363 /* exit after all has cleaned up */
1364 if (udev_list_node_is_empty(&event_list
) && children
== 0)
1367 /* timeout at exit for workers to finish */
1368 timeout
= 30 * MSEC_PER_SEC
;
1369 } else if (udev_list_node_is_empty(&event_list
) && children
== 0) {
1373 /* cleanup possible left-over processes in our cgroup */
1375 cg_kill(SYSTEMD_CGROUP_CONTROLLER
, udev_cgroup
, SIGKILL
, false, true, NULL
);
1377 /* kill idle or hanging workers */
1378 timeout
= 3 * MSEC_PER_SEC
;
1381 /* tell settle that we are busy or idle */
1382 if (!udev_list_node_is_empty(&event_list
)) {
1385 fd
= open("/run/udev/queue", O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_TRUNC
|O_NOFOLLOW
, 0444);
1389 unlink("/run/udev/queue");
1392 fdcount
= epoll_wait(fd_ep
, ev
, ELEMENTSOF(ev
), timeout
);
1397 struct udev_list_node
*loop
;
1401 log_error("timeout, giving up waiting for workers to finish");
1405 /* kill idle workers */
1406 if (udev_list_node_is_empty(&event_list
)) {
1407 log_debug("cleanup idle workers");
1411 /* check for hanging events */
1412 udev_list_node_foreach(loop
, &worker_list
) {
1413 struct worker
*worker
= node_to_worker(loop
);
1415 if (worker
->state
!= WORKER_RUNNING
)
1418 if ((now(CLOCK_MONOTONIC
) - worker
->event_start_usec
) > 30 * USEC_PER_SEC
) {
1419 log_error("worker [%u] %s timeout; kill it", worker
->pid
,
1420 worker
->event
? worker
->event
->devpath
: "<idle>");
1421 kill(worker
->pid
, SIGKILL
);
1422 worker
->state
= WORKER_KILLED
;
1424 /* drop reference taken for state 'running' */
1425 worker_unref(worker
);
1426 if (worker
->event
) {
1427 log_error("seq %llu '%s' killed", udev_device_get_seqnum(worker
->event
->dev
), worker
->event
->devpath
);
1428 worker
->event
->exitcode
= -64;
1429 event_queue_delete(worker
->event
);
1430 worker
->event
= NULL
;
1437 is_worker
= is_signal
= is_inotify
= is_netlink
= is_ctrl
= false;
1438 for (i
= 0; i
< fdcount
; i
++) {
1439 if (ev
[i
].data
.fd
== fd_worker
&& ev
[i
].events
& EPOLLIN
)
1441 else if (ev
[i
].data
.fd
== fd_netlink
&& ev
[i
].events
& EPOLLIN
)
1443 else if (ev
[i
].data
.fd
== fd_signal
&& ev
[i
].events
& EPOLLIN
)
1445 else if (ev
[i
].data
.fd
== fd_inotify
&& ev
[i
].events
& EPOLLIN
)
1447 else if (ev
[i
].data
.fd
== fd_ctrl
&& ev
[i
].events
& EPOLLIN
)
1451 /* check for changed config, every 3 seconds at most */
1452 if ((now(CLOCK_MONOTONIC
) - last_usec
) > 3 * USEC_PER_SEC
) {
1453 if (udev_rules_check_timestamp(rules
))
1455 if (udev_builtin_validate(udev
))
1458 last_usec
= now(CLOCK_MONOTONIC
);
1461 /* reload requested, HUP signal received, rules changed, builtin changed */
1464 rules
= udev_rules_unref(rules
);
1465 udev_builtin_exit(udev
);
1469 /* event has finished */
1471 worker_returned(fd_worker
);
1474 struct udev_device
*dev
;
1476 dev
= udev_monitor_receive_device(monitor
);
1478 udev_device_set_usec_initialized(dev
, now(CLOCK_MONOTONIC
));
1479 if (event_queue_insert(dev
) < 0)
1480 udev_device_unref(dev
);
1484 /* start new events */
1485 if (!udev_list_node_is_empty(&event_list
) && !udev_exit
&& !stop_exec_queue
) {
1486 udev_builtin_init(udev
);
1488 rules
= udev_rules_new(udev
, resolve_names
);
1490 event_queue_start(udev
);
1494 struct signalfd_siginfo fdsi
;
1497 size
= read(fd_signal
, &fdsi
, sizeof(struct signalfd_siginfo
));
1498 if (size
== sizeof(struct signalfd_siginfo
))
1499 handle_signal(udev
, fdsi
.ssi_signo
);
1502 /* we are shutting down, the events below are not handled anymore */
1506 /* device node watch */
1508 handle_inotify(udev
);
1511 * This needs to be after the inotify handling, to make sure,
1512 * that the ping is send back after the possibly generated
1513 * "change" events by the inotify device node watch.
1515 * A single time we may receive a client connection which we need to
1516 * keep open to block the client. It will be closed right before we
1520 ctrl_conn
= handle_ctrl_msg(udev_ctrl
);
1525 udev_ctrl_cleanup(udev_ctrl
);
1526 unlink("/run/udev/queue");
1530 worker_list_cleanup(udev
);
1531 event_queue_cleanup(udev
, EVENT_UNDEF
);
1532 udev_rules_unref(rules
);
1533 udev_builtin_exit(udev
);
1536 if (worker_watch
[READ_END
] >= 0)
1537 close(worker_watch
[READ_END
]);
1538 if (worker_watch
[WRITE_END
] >= 0)
1539 close(worker_watch
[WRITE_END
]);
1540 udev_monitor_unref(monitor
);
1541 udev_ctrl_connection_unref(ctrl_conn
);
1542 udev_ctrl_unref(udev_ctrl
);