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