]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/udev/udevd.c
udevd: inotify - modernizations
[thirdparty/systemd.git] / src / udev / udevd.c
1 /*
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>
6 *
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.
11 *
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.
16 *
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/>.
19 */
20
21 #include <stddef.h>
22 #include <signal.h>
23 #include <unistd.h>
24 #include <errno.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <stdbool.h>
28 #include <string.h>
29 #include <ctype.h>
30 #include <fcntl.h>
31 #include <time.h>
32 #include <getopt.h>
33 #include <dirent.h>
34 #include <sys/file.h>
35 #include <sys/time.h>
36 #include <sys/prctl.h>
37 #include <sys/socket.h>
38 #include <sys/un.h>
39 #include <sys/signalfd.h>
40 #include <sys/epoll.h>
41 #include <sys/poll.h>
42 #include <sys/wait.h>
43 #include <sys/stat.h>
44 #include <sys/ioctl.h>
45 #include <sys/inotify.h>
46 #include <sys/utsname.h>
47
48 #include "udev.h"
49 #include "sd-daemon.h"
50 #include "cgroup-util.h"
51 #include "dev-setup.h"
52 #include "fileio.h"
53
54 static bool debug;
55
56 void udev_main_log(struct udev *udev, int priority,
57 const char *file, int line, const char *fn,
58 const char *format, va_list args)
59 {
60 log_metav(priority, file, line, fn, format, args);
61 }
62
63 static struct udev_rules *rules;
64 static struct udev_ctrl *udev_ctrl;
65 static struct udev_monitor *monitor;
66 static int worker_watch[2] = { -1, -1 };
67 static int fd_signal = -1;
68 static int fd_ep = -1;
69 static int fd_inotify = -1;
70 static bool stop_exec_queue;
71 static bool reload;
72 static int children;
73 static int children_max;
74 static int exec_delay;
75 static sigset_t sigmask_orig;
76 static UDEV_LIST(event_list);
77 static UDEV_LIST(worker_list);
78 static char *udev_cgroup;
79 static bool udev_exit;
80
81 enum event_state {
82 EVENT_UNDEF,
83 EVENT_QUEUED,
84 EVENT_RUNNING,
85 };
86
87 struct event {
88 struct udev_list_node node;
89 struct udev *udev;
90 struct udev_device *dev;
91 enum event_state state;
92 int exitcode;
93 unsigned long long int delaying_seqnum;
94 unsigned long long int seqnum;
95 const char *devpath;
96 size_t devpath_len;
97 const char *devpath_old;
98 dev_t devnum;
99 int ifindex;
100 bool is_block;
101 #ifdef HAVE_FIRMWARE
102 bool nodelay;
103 #endif
104 };
105
106 static inline struct event *node_to_event(struct udev_list_node *node)
107 {
108 return container_of(node, struct event, node);
109 }
110
111 static void event_queue_cleanup(struct udev *udev, enum event_state type);
112
113 enum worker_state {
114 WORKER_UNDEF,
115 WORKER_RUNNING,
116 WORKER_IDLE,
117 WORKER_KILLED,
118 };
119
120 struct worker {
121 struct udev_list_node node;
122 struct udev *udev;
123 int refcount;
124 pid_t pid;
125 struct udev_monitor *monitor;
126 enum worker_state state;
127 struct event *event;
128 usec_t event_start_usec;
129 };
130
131 /* passed from worker to main process */
132 struct worker_message {
133 pid_t pid;
134 int exitcode;
135 };
136
137 static inline struct worker *node_to_worker(struct udev_list_node *node)
138 {
139 return container_of(node, struct worker, node);
140 }
141
142 static void event_queue_delete(struct event *event)
143 {
144 udev_list_node_remove(&event->node);
145 udev_device_unref(event->dev);
146 free(event);
147 }
148
149 static struct worker *worker_ref(struct worker *worker)
150 {
151 worker->refcount++;
152 return worker;
153 }
154
155 static void worker_cleanup(struct worker *worker)
156 {
157 udev_list_node_remove(&worker->node);
158 udev_monitor_unref(worker->monitor);
159 children--;
160 free(worker);
161 }
162
163 static void worker_unref(struct worker *worker)
164 {
165 worker->refcount--;
166 if (worker->refcount > 0)
167 return;
168 log_debug("worker [%u] cleaned up", worker->pid);
169 worker_cleanup(worker);
170 }
171
172 static void worker_list_cleanup(struct udev *udev)
173 {
174 struct udev_list_node *loop, *tmp;
175
176 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
177 struct worker *worker = node_to_worker(loop);
178
179 worker_cleanup(worker);
180 }
181 }
182
183 static void worker_new(struct event *event)
184 {
185 struct udev *udev = event->udev;
186 struct worker *worker;
187 struct udev_monitor *worker_monitor;
188 pid_t pid;
189
190 /* listen for new events */
191 worker_monitor = udev_monitor_new_from_netlink(udev, NULL);
192 if (worker_monitor == NULL)
193 return;
194 /* allow the main daemon netlink address to send devices to the worker */
195 udev_monitor_allow_unicast_sender(worker_monitor, monitor);
196 udev_monitor_enable_receiving(worker_monitor);
197
198 worker = new0(struct worker, 1);
199 if (worker == NULL) {
200 udev_monitor_unref(worker_monitor);
201 return;
202 }
203 /* worker + event reference */
204 worker->refcount = 2;
205 worker->udev = udev;
206
207 pid = fork();
208 switch (pid) {
209 case 0: {
210 struct udev_device *dev = NULL;
211 int fd_monitor;
212 struct epoll_event ep_signal, ep_monitor;
213 sigset_t mask;
214 int rc = EXIT_SUCCESS;
215
216 /* take initial device from queue */
217 dev = event->dev;
218 event->dev = NULL;
219
220 free(worker);
221 worker_list_cleanup(udev);
222 event_queue_cleanup(udev, EVENT_UNDEF);
223 udev_monitor_unref(monitor);
224 udev_ctrl_unref(udev_ctrl);
225 close(fd_signal);
226 close(fd_ep);
227 close(worker_watch[READ_END]);
228
229 sigfillset(&mask);
230 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
231 if (fd_signal < 0) {
232 log_error("error creating signalfd %m");
233 rc = 2;
234 goto out;
235 }
236
237 fd_ep = epoll_create1(EPOLL_CLOEXEC);
238 if (fd_ep < 0) {
239 log_error("error creating epoll fd: %m");
240 rc = 3;
241 goto out;
242 }
243
244 memzero(&ep_signal, sizeof(struct epoll_event));
245 ep_signal.events = EPOLLIN;
246 ep_signal.data.fd = fd_signal;
247
248 fd_monitor = udev_monitor_get_fd(worker_monitor);
249 memzero(&ep_monitor, sizeof(struct epoll_event));
250 ep_monitor.events = EPOLLIN;
251 ep_monitor.data.fd = fd_monitor;
252
253 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
254 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_monitor, &ep_monitor) < 0) {
255 log_error("fail to add fds to epoll: %m");
256 rc = 4;
257 goto out;
258 }
259
260 /* request TERM signal if parent exits */
261 prctl(PR_SET_PDEATHSIG, SIGTERM);
262
263 /* reset OOM score, we only protect the main daemon */
264 write_string_file("/proc/self/oom_score_adj", "0");
265
266 for (;;) {
267 struct udev_event *udev_event;
268 struct worker_message msg;
269 int fd_lock = -1;
270 int err = 0;
271
272 log_debug("seq %llu running", udev_device_get_seqnum(dev));
273 udev_event = udev_event_new(dev);
274 if (udev_event == NULL) {
275 rc = 5;
276 goto out;
277 }
278
279 /* needed for SIGCHLD/SIGTERM in spawn() */
280 udev_event->fd_signal = fd_signal;
281
282 if (exec_delay > 0)
283 udev_event->exec_delay = exec_delay;
284
285 /*
286 * Take a "read lock" on the device node; this establishes
287 * a concept of device "ownership" to serialize device
288 * access. External processes holding a "write lock" will
289 * cause udev to skip the event handling; in the case udev
290 * acquired the lock, the external process will block until
291 * udev has finished its event handling.
292 */
293
294 /*
295 * <kabi_> since we make check - device seems unused - we try
296 * ioctl to deactivate - and device is found to be opened
297 * <kay> sure, you try to take a write lock
298 * <kay> if you get it udev is out
299 * <kay> if you can't get it, udev is busy
300 * <kabi_> we cannot deactivate openned device (as it is in-use)
301 * <kay> maybe we should just exclude dm from that thing entirely
302 * <kabi_> IMHO this sounds like a good plan for this moment
303 */
304 if (streq_ptr("block", udev_device_get_subsystem(dev)) &&
305 !startswith("dm-", udev_device_get_sysname(dev))) {
306 struct udev_device *d = dev;
307
308 if (streq_ptr("partition", udev_device_get_devtype(d)))
309 d = udev_device_get_parent(d);
310
311 if (d) {
312 fd_lock = open(udev_device_get_devnode(d), O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
313 if (fd_lock >= 0 && flock(fd_lock, LOCK_SH|LOCK_NB) < 0) {
314 log_debug("Unable to flock(%s), skipping event handling: %m", udev_device_get_devnode(d));
315 err = -EWOULDBLOCK;
316 fd_lock = safe_close(fd_lock);
317 goto skip;
318 }
319 }
320 }
321
322 /* apply rules, create node, symlinks */
323 udev_event_execute_rules(udev_event, rules, &sigmask_orig);
324
325 udev_event_execute_run(udev_event, &sigmask_orig);
326
327 /* apply/restore inotify watch */
328 if (udev_event->inotify_watch) {
329 udev_watch_begin(udev, dev);
330 udev_device_update_db(dev);
331 }
332
333 safe_close(fd_lock);
334
335 /* send processed event back to libudev listeners */
336 udev_monitor_send_device(worker_monitor, NULL, dev);
337
338 skip:
339 /* send udevd the result of the event execution */
340 memzero(&msg, sizeof(struct worker_message));
341 msg.exitcode = err;
342 msg.pid = getpid();
343 send(worker_watch[WRITE_END], &msg, sizeof(struct worker_message), 0);
344
345 log_debug("seq %llu processed with %i", udev_device_get_seqnum(dev), err);
346
347 udev_device_unref(dev);
348 dev = NULL;
349
350 if (udev_event->sigterm) {
351 udev_event_unref(udev_event);
352 goto out;
353 }
354
355 udev_event_unref(udev_event);
356
357 /* wait for more device messages from main udevd, or term signal */
358 while (dev == NULL) {
359 struct epoll_event ev[4];
360 int fdcount;
361 int i;
362
363 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), -1);
364 if (fdcount < 0) {
365 if (errno == EINTR)
366 continue;
367 log_error("failed to poll: %m");
368 goto out;
369 }
370
371 for (i = 0; i < fdcount; i++) {
372 if (ev[i].data.fd == fd_monitor && ev[i].events & EPOLLIN) {
373 dev = udev_monitor_receive_device(worker_monitor);
374 break;
375 } else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN) {
376 struct signalfd_siginfo fdsi;
377 ssize_t size;
378
379 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
380 if (size != sizeof(struct signalfd_siginfo))
381 continue;
382 switch (fdsi.ssi_signo) {
383 case SIGTERM:
384 goto out;
385 }
386 }
387 }
388 }
389 }
390 out:
391 udev_device_unref(dev);
392 safe_close(fd_signal);
393 safe_close(fd_ep);
394 close(fd_inotify);
395 close(worker_watch[WRITE_END]);
396 udev_rules_unref(rules);
397 udev_builtin_exit(udev);
398 udev_monitor_unref(worker_monitor);
399 udev_unref(udev);
400 log_close();
401 exit(rc);
402 }
403 case -1:
404 udev_monitor_unref(worker_monitor);
405 event->state = EVENT_QUEUED;
406 free(worker);
407 log_error("fork of child failed: %m");
408 break;
409 default:
410 /* close monitor, but keep address around */
411 udev_monitor_disconnect(worker_monitor);
412 worker->monitor = worker_monitor;
413 worker->pid = pid;
414 worker->state = WORKER_RUNNING;
415 worker->event_start_usec = now(CLOCK_MONOTONIC);
416 worker->event = event;
417 event->state = EVENT_RUNNING;
418 udev_list_node_append(&worker->node, &worker_list);
419 children++;
420 log_debug("seq %llu forked new worker [%u]", udev_device_get_seqnum(event->dev), pid);
421 break;
422 }
423 }
424
425 static void event_run(struct event *event)
426 {
427 struct udev_list_node *loop;
428
429 udev_list_node_foreach(loop, &worker_list) {
430 struct worker *worker = node_to_worker(loop);
431 ssize_t count;
432
433 if (worker->state != WORKER_IDLE)
434 continue;
435
436 count = udev_monitor_send_device(monitor, worker->monitor, event->dev);
437 if (count < 0) {
438 log_error("worker [%u] did not accept message %zi (%m), kill it", worker->pid, count);
439 kill(worker->pid, SIGKILL);
440 worker->state = WORKER_KILLED;
441 continue;
442 }
443 worker_ref(worker);
444 worker->event = event;
445 worker->state = WORKER_RUNNING;
446 worker->event_start_usec = now(CLOCK_MONOTONIC);
447 event->state = EVENT_RUNNING;
448 return;
449 }
450
451 if (children >= children_max) {
452 if (children_max > 1)
453 log_debug("maximum number (%i) of children reached", children);
454 return;
455 }
456
457 /* start new worker and pass initial device */
458 worker_new(event);
459 }
460
461 static int event_queue_insert(struct udev_device *dev)
462 {
463 struct event *event;
464
465 event = new0(struct event, 1);
466 if (event == NULL)
467 return -1;
468
469 event->udev = udev_device_get_udev(dev);
470 event->dev = dev;
471 event->seqnum = udev_device_get_seqnum(dev);
472 event->devpath = udev_device_get_devpath(dev);
473 event->devpath_len = strlen(event->devpath);
474 event->devpath_old = udev_device_get_devpath_old(dev);
475 event->devnum = udev_device_get_devnum(dev);
476 event->is_block = streq("block", udev_device_get_subsystem(dev));
477 event->ifindex = udev_device_get_ifindex(dev);
478 #ifdef HAVE_FIRMWARE
479 if (streq(udev_device_get_subsystem(dev), "firmware"))
480 event->nodelay = true;
481 #endif
482
483 log_debug("seq %llu queued, '%s' '%s'", udev_device_get_seqnum(dev),
484 udev_device_get_action(dev), udev_device_get_subsystem(dev));
485
486 event->state = EVENT_QUEUED;
487 udev_list_node_append(&event->node, &event_list);
488 return 0;
489 }
490
491 static void worker_kill(struct udev *udev)
492 {
493 struct udev_list_node *loop;
494
495 udev_list_node_foreach(loop, &worker_list) {
496 struct worker *worker = node_to_worker(loop);
497
498 if (worker->state == WORKER_KILLED)
499 continue;
500
501 worker->state = WORKER_KILLED;
502 kill(worker->pid, SIGTERM);
503 }
504 }
505
506 /* lookup event for identical, parent, child device */
507 static bool is_devpath_busy(struct event *event)
508 {
509 struct udev_list_node *loop;
510 size_t common;
511
512 /* check if queue contains events we depend on */
513 udev_list_node_foreach(loop, &event_list) {
514 struct event *loop_event = node_to_event(loop);
515
516 /* we already found a later event, earlier can not block us, no need to check again */
517 if (loop_event->seqnum < event->delaying_seqnum)
518 continue;
519
520 /* event we checked earlier still exists, no need to check again */
521 if (loop_event->seqnum == event->delaying_seqnum)
522 return true;
523
524 /* found ourself, no later event can block us */
525 if (loop_event->seqnum >= event->seqnum)
526 break;
527
528 /* check major/minor */
529 if (major(event->devnum) != 0 && event->devnum == loop_event->devnum && event->is_block == loop_event->is_block)
530 return true;
531
532 /* check network device ifindex */
533 if (event->ifindex != 0 && event->ifindex == loop_event->ifindex)
534 return true;
535
536 /* check our old name */
537 if (event->devpath_old != NULL && streq(loop_event->devpath, event->devpath_old)) {
538 event->delaying_seqnum = loop_event->seqnum;
539 return true;
540 }
541
542 /* compare devpath */
543 common = MIN(loop_event->devpath_len, event->devpath_len);
544
545 /* one devpath is contained in the other? */
546 if (memcmp(loop_event->devpath, event->devpath, common) != 0)
547 continue;
548
549 /* identical device event found */
550 if (loop_event->devpath_len == event->devpath_len) {
551 /* devices names might have changed/swapped in the meantime */
552 if (major(event->devnum) != 0 && (event->devnum != loop_event->devnum || event->is_block != loop_event->is_block))
553 continue;
554 if (event->ifindex != 0 && event->ifindex != loop_event->ifindex)
555 continue;
556 event->delaying_seqnum = loop_event->seqnum;
557 return true;
558 }
559
560 #ifdef HAVE_FIRMWARE
561 /* allow to bypass the dependency tracking */
562 if (event->nodelay)
563 continue;
564 #endif
565
566 /* parent device event found */
567 if (event->devpath[common] == '/') {
568 event->delaying_seqnum = loop_event->seqnum;
569 return true;
570 }
571
572 /* child device event found */
573 if (loop_event->devpath[common] == '/') {
574 event->delaying_seqnum = loop_event->seqnum;
575 return true;
576 }
577
578 /* no matching device */
579 continue;
580 }
581
582 return false;
583 }
584
585 static void event_queue_start(struct udev *udev)
586 {
587 struct udev_list_node *loop;
588
589 udev_list_node_foreach(loop, &event_list) {
590 struct event *event = node_to_event(loop);
591
592 if (event->state != EVENT_QUEUED)
593 continue;
594
595 /* do not start event if parent or child event is still running */
596 if (is_devpath_busy(event))
597 continue;
598
599 event_run(event);
600 }
601 }
602
603 static void event_queue_cleanup(struct udev *udev, enum event_state match_type)
604 {
605 struct udev_list_node *loop, *tmp;
606
607 udev_list_node_foreach_safe(loop, tmp, &event_list) {
608 struct event *event = node_to_event(loop);
609
610 if (match_type != EVENT_UNDEF && match_type != event->state)
611 continue;
612
613 event_queue_delete(event);
614 }
615 }
616
617 static void worker_returned(int fd_worker)
618 {
619 for (;;) {
620 struct worker_message msg;
621 ssize_t size;
622 struct udev_list_node *loop;
623
624 size = recv(fd_worker, &msg, sizeof(struct worker_message), MSG_DONTWAIT);
625 if (size != sizeof(struct worker_message))
626 break;
627
628 /* lookup worker who sent the signal */
629 udev_list_node_foreach(loop, &worker_list) {
630 struct worker *worker = node_to_worker(loop);
631
632 if (worker->pid != msg.pid)
633 continue;
634
635 /* worker returned */
636 if (worker->event) {
637 worker->event->exitcode = msg.exitcode;
638 event_queue_delete(worker->event);
639 worker->event = NULL;
640 }
641 if (worker->state != WORKER_KILLED)
642 worker->state = WORKER_IDLE;
643 worker_unref(worker);
644 break;
645 }
646 }
647 }
648
649 /* receive the udevd message from userspace */
650 static struct udev_ctrl_connection *handle_ctrl_msg(struct udev_ctrl *uctrl)
651 {
652 struct udev *udev = udev_ctrl_get_udev(uctrl);
653 struct udev_ctrl_connection *ctrl_conn;
654 struct udev_ctrl_msg *ctrl_msg = NULL;
655 const char *str;
656 int i;
657
658 ctrl_conn = udev_ctrl_get_connection(uctrl);
659 if (ctrl_conn == NULL)
660 goto out;
661
662 ctrl_msg = udev_ctrl_receive_msg(ctrl_conn);
663 if (ctrl_msg == NULL)
664 goto out;
665
666 i = udev_ctrl_get_set_log_level(ctrl_msg);
667 if (i >= 0) {
668 log_debug("udevd message (SET_LOG_LEVEL) received, log_priority=%i", i);
669 log_set_max_level(i);
670 udev_set_log_priority(udev, i);
671 worker_kill(udev);
672 }
673
674 if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
675 log_debug("udevd message (STOP_EXEC_QUEUE) received");
676 stop_exec_queue = true;
677 }
678
679 if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
680 log_debug("udevd message (START_EXEC_QUEUE) received");
681 stop_exec_queue = false;
682 }
683
684 if (udev_ctrl_get_reload(ctrl_msg) > 0) {
685 log_debug("udevd message (RELOAD) received");
686 reload = true;
687 }
688
689 str = udev_ctrl_get_set_env(ctrl_msg);
690 if (str != NULL) {
691 char *key;
692
693 key = strdup(str);
694 if (key != NULL) {
695 char *val;
696
697 val = strchr(key, '=');
698 if (val != NULL) {
699 val[0] = '\0';
700 val = &val[1];
701 if (val[0] == '\0') {
702 log_debug("udevd message (ENV) received, unset '%s'", key);
703 udev_add_property(udev, key, NULL);
704 } else {
705 log_debug("udevd message (ENV) received, set '%s=%s'", key, val);
706 udev_add_property(udev, key, val);
707 }
708 } else {
709 log_error("wrong key format '%s'", key);
710 }
711 free(key);
712 }
713 worker_kill(udev);
714 }
715
716 i = udev_ctrl_get_set_children_max(ctrl_msg);
717 if (i >= 0) {
718 log_debug("udevd message (SET_MAX_CHILDREN) received, children_max=%i", i);
719 children_max = i;
720 }
721
722 if (udev_ctrl_get_ping(ctrl_msg) > 0)
723 log_debug("udevd message (SYNC) received");
724
725 if (udev_ctrl_get_exit(ctrl_msg) > 0) {
726 log_debug("udevd message (EXIT) received");
727 udev_exit = true;
728 /* keep reference to block the client until we exit */
729 udev_ctrl_connection_ref(ctrl_conn);
730 }
731 out:
732 udev_ctrl_msg_unref(ctrl_msg);
733 return udev_ctrl_connection_unref(ctrl_conn);
734 }
735
736 static void synthesize_change(struct udev_device *dev) {
737 char filename[UTIL_PATH_SIZE];
738
739 log_debug("device %s closed, synthesising 'change'", udev_device_get_devnode(dev));
740 strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
741 write_string_file(filename, "change");
742 }
743
744 /* read inotify messages */
745 static int handle_inotify(struct udev *udev)
746 {
747 int nbytes, pos;
748 char *buf;
749 struct inotify_event *ev;
750 int r;
751
752 r = ioctl(fd_inotify, FIONREAD, &nbytes);
753 if (r < 0 || nbytes <= 0)
754 return -errno;
755
756 buf = malloc(nbytes);
757 if (!buf) {
758 log_error("error getting buffer for inotify");
759 return -ENOMEM;
760 }
761
762 nbytes = read(fd_inotify, buf, nbytes);
763
764 for (pos = 0; pos < nbytes; pos += sizeof(struct inotify_event) + ev->len) {
765 struct udev_device *dev;
766
767 ev = (struct inotify_event *)(buf + pos);
768 dev = udev_watch_lookup(udev, ev->wd);
769 if (!dev)
770 continue;
771
772 log_debug("inotify event: %x for %s", ev->mask, udev_device_get_devnode(dev));
773 if (ev->mask & IN_CLOSE_WRITE)
774 synthesize_change(dev);
775 else if (ev->mask & IN_IGNORED)
776 udev_watch_end(udev, dev);
777
778 udev_device_unref(dev);
779 }
780
781 free(buf);
782 return 0;
783 }
784
785 static void handle_signal(struct udev *udev, int signo)
786 {
787 switch (signo) {
788 case SIGINT:
789 case SIGTERM:
790 udev_exit = true;
791 break;
792 case SIGCHLD:
793 for (;;) {
794 pid_t pid;
795 int status;
796 struct udev_list_node *loop, *tmp;
797
798 pid = waitpid(-1, &status, WNOHANG);
799 if (pid <= 0)
800 break;
801
802 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
803 struct worker *worker = node_to_worker(loop);
804
805 if (worker->pid != pid)
806 continue;
807 log_debug("worker [%u] exit", pid);
808
809 if (WIFEXITED(status)) {
810 if (WEXITSTATUS(status) != 0)
811 log_error("worker [%u] exit with return code %i",
812 pid, WEXITSTATUS(status));
813 } else if (WIFSIGNALED(status)) {
814 log_error("worker [%u] terminated by signal %i (%s)",
815 pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
816 } else if (WIFSTOPPED(status)) {
817 log_error("worker [%u] stopped", pid);
818 } else if (WIFCONTINUED(status)) {
819 log_error("worker [%u] continued", pid);
820 } else {
821 log_error("worker [%u] exit with status 0x%04x", pid, status);
822 }
823
824 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
825 if (worker->event) {
826 log_error("worker [%u] failed while handling '%s'",
827 pid, worker->event->devpath);
828 worker->event->exitcode = -32;
829 event_queue_delete(worker->event);
830
831 /* drop reference taken for state 'running' */
832 worker_unref(worker);
833 }
834 }
835 worker_unref(worker);
836 break;
837 }
838 }
839 break;
840 case SIGHUP:
841 reload = true;
842 break;
843 }
844 }
845
846 static int systemd_fds(struct udev *udev, int *rctrl, int *rnetlink)
847 {
848 int ctrl = -1, netlink = -1;
849 int fd, n;
850
851 n = sd_listen_fds(true);
852 if (n <= 0)
853 return -1;
854
855 for (fd = SD_LISTEN_FDS_START; fd < n + SD_LISTEN_FDS_START; fd++) {
856 if (sd_is_socket(fd, AF_LOCAL, SOCK_SEQPACKET, -1)) {
857 if (ctrl >= 0)
858 return -1;
859 ctrl = fd;
860 continue;
861 }
862
863 if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1)) {
864 if (netlink >= 0)
865 return -1;
866 netlink = fd;
867 continue;
868 }
869
870 return -1;
871 }
872
873 if (ctrl < 0 || netlink < 0)
874 return -1;
875
876 log_debug("ctrl=%i netlink=%i", ctrl, netlink);
877 *rctrl = ctrl;
878 *rnetlink = netlink;
879 return 0;
880 }
881
882 /*
883 * read the kernel commandline, in case we need to get into debug mode
884 * udev.log-priority=<level> syslog priority
885 * udev.children-max=<number of workers> events are fully serialized if set to 1
886 * udev.exec-delay=<number of seconds> delay execution of every executed program
887 */
888 static void kernel_cmdline_options(struct udev *udev)
889 {
890 _cleanup_free_ char *line = NULL;
891 char *w, *state;
892 size_t l;
893 int r;
894
895 r = proc_cmdline(&line);
896 if (r < 0)
897 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
898 if (r <= 0)
899 return;
900
901 FOREACH_WORD_QUOTED(w, l, line, state) {
902 char *s, *opt;
903
904 s = strndup(w, l);
905 if (!s)
906 break;
907
908 /* accept the same options for the initrd, prefixed with "rd." */
909 if (in_initrd() && startswith(s, "rd."))
910 opt = s + 3;
911 else
912 opt = s;
913
914 if (startswith(opt, "udev.log-priority=")) {
915 int prio;
916
917 prio = util_log_priority(opt + 18);
918 log_set_max_level(prio);
919 udev_set_log_priority(udev, prio);
920 } else if (startswith(opt, "udev.children-max=")) {
921 children_max = strtoul(opt + 18, NULL, 0);
922 } else if (startswith(opt, "udev.exec-delay=")) {
923 exec_delay = strtoul(opt + 16, NULL, 0);
924 }
925
926 free(s);
927 }
928 }
929
930 int main(int argc, char *argv[])
931 {
932 struct udev *udev;
933 sigset_t mask;
934 int daemonize = false;
935 int resolve_names = 1;
936 static const struct option options[] = {
937 { "daemon", no_argument, NULL, 'd' },
938 { "debug", no_argument, NULL, 'D' },
939 { "children-max", required_argument, NULL, 'c' },
940 { "exec-delay", required_argument, NULL, 'e' },
941 { "resolve-names", required_argument, NULL, 'N' },
942 { "help", no_argument, NULL, 'h' },
943 { "version", no_argument, NULL, 'V' },
944 {}
945 };
946 int fd_ctrl = -1;
947 int fd_netlink = -1;
948 int fd_worker = -1;
949 struct epoll_event ep_ctrl, ep_inotify, ep_signal, ep_netlink, ep_worker;
950 struct udev_ctrl_connection *ctrl_conn = NULL;
951 int rc = 1;
952
953 udev = udev_new();
954 if (udev == NULL)
955 goto exit;
956
957 log_set_target(LOG_TARGET_AUTO);
958 log_parse_environment();
959 log_open();
960
961 udev_set_log_fn(udev, udev_main_log);
962 log_set_max_level(udev_get_log_priority(udev));
963
964 log_debug("version %s", VERSION);
965 label_init("/dev");
966
967 for (;;) {
968 int option;
969
970 option = getopt_long(argc, argv, "c:de:DtN:hV", options, NULL);
971 if (option == -1)
972 break;
973
974 switch (option) {
975 case 'd':
976 daemonize = true;
977 break;
978 case 'c':
979 children_max = strtoul(optarg, NULL, 0);
980 break;
981 case 'e':
982 exec_delay = strtoul(optarg, NULL, 0);
983 break;
984 case 'D':
985 debug = true;
986 log_set_max_level(LOG_DEBUG);
987 udev_set_log_priority(udev, LOG_DEBUG);
988 break;
989 case 'N':
990 if (streq(optarg, "early")) {
991 resolve_names = 1;
992 } else if (streq(optarg, "late")) {
993 resolve_names = 0;
994 } else if (streq(optarg, "never")) {
995 resolve_names = -1;
996 } else {
997 fprintf(stderr, "resolve-names must be early, late or never\n");
998 log_error("resolve-names must be early, late or never");
999 goto exit;
1000 }
1001 break;
1002 case 'h':
1003 printf("Usage: udevd OPTIONS\n"
1004 " --daemon\n"
1005 " --debug\n"
1006 " --children-max=<maximum number of workers>\n"
1007 " --exec-delay=<seconds to wait before executing RUN=>\n"
1008 " --resolve-names=early|late|never\n"
1009 " --version\n"
1010 " --help\n"
1011 "\n");
1012 goto exit;
1013 case 'V':
1014 printf("%s\n", VERSION);
1015 goto exit;
1016 default:
1017 goto exit;
1018 }
1019 }
1020
1021 kernel_cmdline_options(udev);
1022
1023 if (getuid() != 0) {
1024 fprintf(stderr, "root privileges required\n");
1025 log_error("root privileges required");
1026 goto exit;
1027 }
1028
1029 /* set umask before creating any file/directory */
1030 chdir("/");
1031 umask(022);
1032
1033 mkdir("/run/udev", 0755);
1034
1035 dev_setup(NULL);
1036
1037 /* before opening new files, make sure std{in,out,err} fds are in a sane state */
1038 if (daemonize) {
1039 int fd;
1040
1041 fd = open("/dev/null", O_RDWR);
1042 if (fd >= 0) {
1043 if (write(STDOUT_FILENO, 0, 0) < 0)
1044 dup2(fd, STDOUT_FILENO);
1045 if (write(STDERR_FILENO, 0, 0) < 0)
1046 dup2(fd, STDERR_FILENO);
1047 if (fd > STDERR_FILENO)
1048 close(fd);
1049 } else {
1050 fprintf(stderr, "cannot open /dev/null\n");
1051 log_error("cannot open /dev/null");
1052 }
1053 }
1054
1055 if (systemd_fds(udev, &fd_ctrl, &fd_netlink) >= 0) {
1056 /* get control and netlink socket from systemd */
1057 udev_ctrl = udev_ctrl_new_from_fd(udev, fd_ctrl);
1058 if (udev_ctrl == NULL) {
1059 log_error("error taking over udev control socket");
1060 rc = 1;
1061 goto exit;
1062 }
1063
1064 monitor = udev_monitor_new_from_netlink_fd(udev, "kernel", fd_netlink);
1065 if (monitor == NULL) {
1066 log_error("error taking over netlink socket");
1067 rc = 3;
1068 goto exit;
1069 }
1070
1071 /* get our own cgroup, we regularly kill everything udev has left behind */
1072 if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &udev_cgroup) < 0)
1073 udev_cgroup = NULL;
1074 } else {
1075 /* open control and netlink socket */
1076 udev_ctrl = udev_ctrl_new(udev);
1077 if (udev_ctrl == NULL) {
1078 fprintf(stderr, "error initializing udev control socket");
1079 log_error("error initializing udev control socket");
1080 rc = 1;
1081 goto exit;
1082 }
1083 fd_ctrl = udev_ctrl_get_fd(udev_ctrl);
1084
1085 monitor = udev_monitor_new_from_netlink(udev, "kernel");
1086 if (monitor == NULL) {
1087 fprintf(stderr, "error initializing netlink socket\n");
1088 log_error("error initializing netlink socket");
1089 rc = 3;
1090 goto exit;
1091 }
1092 fd_netlink = udev_monitor_get_fd(monitor);
1093 }
1094
1095 if (udev_monitor_enable_receiving(monitor) < 0) {
1096 fprintf(stderr, "error binding netlink socket\n");
1097 log_error("error binding netlink socket");
1098 rc = 3;
1099 goto exit;
1100 }
1101
1102 if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
1103 fprintf(stderr, "error binding udev control socket\n");
1104 log_error("error binding udev control socket");
1105 rc = 1;
1106 goto exit;
1107 }
1108
1109 udev_monitor_set_receive_buffer_size(monitor, 128 * 1024 * 1024);
1110
1111 if (daemonize) {
1112 pid_t pid;
1113
1114 pid = fork();
1115 switch (pid) {
1116 case 0:
1117 break;
1118 case -1:
1119 log_error("fork of daemon failed: %m");
1120 rc = 4;
1121 goto exit;
1122 default:
1123 rc = EXIT_SUCCESS;
1124 goto exit_daemonize;
1125 }
1126
1127 setsid();
1128
1129 write_string_file("/proc/self/oom_score_adj", "-1000");
1130 } else {
1131 sd_notify(1, "READY=1");
1132 }
1133
1134 print_kmsg("starting version " VERSION "\n");
1135
1136 if (!debug) {
1137 int fd;
1138
1139 fd = open("/dev/null", O_RDWR);
1140 if (fd >= 0) {
1141 dup2(fd, STDIN_FILENO);
1142 dup2(fd, STDOUT_FILENO);
1143 dup2(fd, STDERR_FILENO);
1144 close(fd);
1145 }
1146 }
1147
1148 fd_inotify = udev_watch_init(udev);
1149 if (fd_inotify < 0) {
1150 fprintf(stderr, "error initializing inotify\n");
1151 log_error("error initializing inotify");
1152 rc = 4;
1153 goto exit;
1154 }
1155 udev_watch_restore(udev);
1156
1157 /* block and listen to all signals on signalfd */
1158 sigfillset(&mask);
1159 sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
1160 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
1161 if (fd_signal < 0) {
1162 fprintf(stderr, "error creating signalfd\n");
1163 log_error("error creating signalfd");
1164 rc = 5;
1165 goto exit;
1166 }
1167
1168 /* unnamed socket from workers to the main daemon */
1169 if (socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, worker_watch) < 0) {
1170 fprintf(stderr, "error creating socketpair\n");
1171 log_error("error creating socketpair");
1172 rc = 6;
1173 goto exit;
1174 }
1175 fd_worker = worker_watch[READ_END];
1176
1177 udev_builtin_init(udev);
1178
1179 rules = udev_rules_new(udev, resolve_names);
1180 if (rules == NULL) {
1181 log_error("error reading rules");
1182 goto exit;
1183 }
1184
1185 memzero(&ep_ctrl, sizeof(struct epoll_event));
1186 ep_ctrl.events = EPOLLIN;
1187 ep_ctrl.data.fd = fd_ctrl;
1188
1189 memzero(&ep_inotify, sizeof(struct epoll_event));
1190 ep_inotify.events = EPOLLIN;
1191 ep_inotify.data.fd = fd_inotify;
1192
1193 memzero(&ep_signal, sizeof(struct epoll_event));
1194 ep_signal.events = EPOLLIN;
1195 ep_signal.data.fd = fd_signal;
1196
1197 memzero(&ep_netlink, sizeof(struct epoll_event));
1198 ep_netlink.events = EPOLLIN;
1199 ep_netlink.data.fd = fd_netlink;
1200
1201 memzero(&ep_worker, sizeof(struct epoll_event));
1202 ep_worker.events = EPOLLIN;
1203 ep_worker.data.fd = fd_worker;
1204
1205 fd_ep = epoll_create1(EPOLL_CLOEXEC);
1206 if (fd_ep < 0) {
1207 log_error("error creating epoll fd: %m");
1208 goto exit;
1209 }
1210 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_ctrl, &ep_ctrl) < 0 ||
1211 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_inotify, &ep_inotify) < 0 ||
1212 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
1213 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_netlink, &ep_netlink) < 0 ||
1214 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_worker, &ep_worker) < 0) {
1215 log_error("fail to add fds to epoll: %m");
1216 goto exit;
1217 }
1218
1219 if (children_max <= 0) {
1220 cpu_set_t cpu_set;
1221
1222 children_max = 8;
1223
1224 if (sched_getaffinity(0, sizeof (cpu_set), &cpu_set) == 0) {
1225 children_max += CPU_COUNT(&cpu_set) * 2;
1226 }
1227 }
1228 log_debug("set children_max to %u", children_max);
1229
1230 rc = udev_rules_apply_static_dev_perms(rules);
1231 if (rc < 0)
1232 log_error("failed to apply permissions on static device nodes - %s", strerror(-rc));
1233
1234 udev_list_node_init(&event_list);
1235 udev_list_node_init(&worker_list);
1236
1237 for (;;) {
1238 static usec_t last_usec;
1239 struct epoll_event ev[8];
1240 int fdcount;
1241 int timeout;
1242 bool is_worker, is_signal, is_inotify, is_netlink, is_ctrl;
1243 int i;
1244
1245 if (udev_exit) {
1246 /* close sources of new events and discard buffered events */
1247 if (fd_ctrl >= 0) {
1248 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_ctrl, NULL);
1249 fd_ctrl = -1;
1250 }
1251 if (monitor != NULL) {
1252 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_netlink, NULL);
1253 udev_monitor_unref(monitor);
1254 monitor = NULL;
1255 }
1256 if (fd_inotify >= 0) {
1257 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_inotify, NULL);
1258 close(fd_inotify);
1259 fd_inotify = -1;
1260 }
1261
1262 /* discard queued events and kill workers */
1263 event_queue_cleanup(udev, EVENT_QUEUED);
1264 worker_kill(udev);
1265
1266 /* exit after all has cleaned up */
1267 if (udev_list_node_is_empty(&event_list) && children == 0)
1268 break;
1269
1270 /* timeout at exit for workers to finish */
1271 timeout = 30 * MSEC_PER_SEC;
1272 } else if (udev_list_node_is_empty(&event_list) && children == 0) {
1273 /* we are idle */
1274 timeout = -1;
1275
1276 /* cleanup possible left-over processes in our cgroup */
1277 if (udev_cgroup)
1278 cg_kill(SYSTEMD_CGROUP_CONTROLLER, udev_cgroup, SIGKILL, false, true, NULL);
1279 } else {
1280 /* kill idle or hanging workers */
1281 timeout = 3 * MSEC_PER_SEC;
1282 }
1283
1284 /* tell settle that we are busy or idle */
1285 if (!udev_list_node_is_empty(&event_list)) {
1286 int fd;
1287
1288 fd = open("/run/udev/queue", O_WRONLY|O_CREAT|O_CLOEXEC|O_TRUNC|O_NOFOLLOW, 0444);
1289 if (fd >= 0)
1290 close(fd);
1291 } else {
1292 unlink("/run/udev/queue");
1293 }
1294
1295 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
1296 if (fdcount < 0)
1297 continue;
1298
1299 if (fdcount == 0) {
1300 struct udev_list_node *loop;
1301
1302 /* timeout */
1303 if (udev_exit) {
1304 log_error("timeout, giving up waiting for workers to finish");
1305 break;
1306 }
1307
1308 /* kill idle workers */
1309 if (udev_list_node_is_empty(&event_list)) {
1310 log_debug("cleanup idle workers");
1311 worker_kill(udev);
1312 }
1313
1314 /* check for hanging events */
1315 udev_list_node_foreach(loop, &worker_list) {
1316 struct worker *worker = node_to_worker(loop);
1317
1318 if (worker->state != WORKER_RUNNING)
1319 continue;
1320
1321 if ((now(CLOCK_MONOTONIC) - worker->event_start_usec) > 30 * USEC_PER_SEC) {
1322 log_error("worker [%u] %s timeout; kill it", worker->pid,
1323 worker->event ? worker->event->devpath : "<idle>");
1324 kill(worker->pid, SIGKILL);
1325 worker->state = WORKER_KILLED;
1326
1327 /* drop reference taken for state 'running' */
1328 worker_unref(worker);
1329 if (worker->event) {
1330 log_error("seq %llu '%s' killed", udev_device_get_seqnum(worker->event->dev), worker->event->devpath);
1331 worker->event->exitcode = -64;
1332 event_queue_delete(worker->event);
1333 worker->event = NULL;
1334 }
1335 }
1336 }
1337
1338 }
1339
1340 is_worker = is_signal = is_inotify = is_netlink = is_ctrl = false;
1341 for (i = 0; i < fdcount; i++) {
1342 if (ev[i].data.fd == fd_worker && ev[i].events & EPOLLIN)
1343 is_worker = true;
1344 else if (ev[i].data.fd == fd_netlink && ev[i].events & EPOLLIN)
1345 is_netlink = true;
1346 else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN)
1347 is_signal = true;
1348 else if (ev[i].data.fd == fd_inotify && ev[i].events & EPOLLIN)
1349 is_inotify = true;
1350 else if (ev[i].data.fd == fd_ctrl && ev[i].events & EPOLLIN)
1351 is_ctrl = true;
1352 }
1353
1354 /* check for changed config, every 3 seconds at most */
1355 if ((now(CLOCK_MONOTONIC) - last_usec) > 3 * USEC_PER_SEC) {
1356 if (udev_rules_check_timestamp(rules))
1357 reload = true;
1358 if (udev_builtin_validate(udev))
1359 reload = true;
1360
1361 last_usec = now(CLOCK_MONOTONIC);
1362 }
1363
1364 /* reload requested, HUP signal received, rules changed, builtin changed */
1365 if (reload) {
1366 worker_kill(udev);
1367 rules = udev_rules_unref(rules);
1368 udev_builtin_exit(udev);
1369 reload = false;
1370 }
1371
1372 /* event has finished */
1373 if (is_worker)
1374 worker_returned(fd_worker);
1375
1376 if (is_netlink) {
1377 struct udev_device *dev;
1378
1379 dev = udev_monitor_receive_device(monitor);
1380 if (dev != NULL) {
1381 udev_device_set_usec_initialized(dev, now(CLOCK_MONOTONIC));
1382 if (event_queue_insert(dev) < 0)
1383 udev_device_unref(dev);
1384 }
1385 }
1386
1387 /* start new events */
1388 if (!udev_list_node_is_empty(&event_list) && !udev_exit && !stop_exec_queue) {
1389 udev_builtin_init(udev);
1390 if (rules == NULL)
1391 rules = udev_rules_new(udev, resolve_names);
1392 if (rules != NULL)
1393 event_queue_start(udev);
1394 }
1395
1396 if (is_signal) {
1397 struct signalfd_siginfo fdsi;
1398 ssize_t size;
1399
1400 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
1401 if (size == sizeof(struct signalfd_siginfo))
1402 handle_signal(udev, fdsi.ssi_signo);
1403 }
1404
1405 /* we are shutting down, the events below are not handled anymore */
1406 if (udev_exit)
1407 continue;
1408
1409 /* device node watch */
1410 if (is_inotify)
1411 handle_inotify(udev);
1412
1413 /*
1414 * This needs to be after the inotify handling, to make sure,
1415 * that the ping is send back after the possibly generated
1416 * "change" events by the inotify device node watch.
1417 *
1418 * A single time we may receive a client connection which we need to
1419 * keep open to block the client. It will be closed right before we
1420 * exit.
1421 */
1422 if (is_ctrl)
1423 ctrl_conn = handle_ctrl_msg(udev_ctrl);
1424 }
1425
1426 rc = EXIT_SUCCESS;
1427 exit:
1428 udev_ctrl_cleanup(udev_ctrl);
1429 unlink("/run/udev/queue");
1430 exit_daemonize:
1431 if (fd_ep >= 0)
1432 close(fd_ep);
1433 worker_list_cleanup(udev);
1434 event_queue_cleanup(udev, EVENT_UNDEF);
1435 udev_rules_unref(rules);
1436 udev_builtin_exit(udev);
1437 if (fd_signal >= 0)
1438 close(fd_signal);
1439 if (worker_watch[READ_END] >= 0)
1440 close(worker_watch[READ_END]);
1441 if (worker_watch[WRITE_END] >= 0)
1442 close(worker_watch[WRITE_END]);
1443 udev_monitor_unref(monitor);
1444 udev_ctrl_connection_unref(ctrl_conn);
1445 udev_ctrl_unref(udev_ctrl);
1446 label_finish();
1447 udev_unref(udev);
1448 log_close();
1449 return rc;
1450 }