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