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