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