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