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