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