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