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