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