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