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