chiark / gitweb /
5ee61d2e23c296c853a453b97729741e973da6f5
[elogind.git] / udev / udevd.c
1 /*
2  * Copyright (C) 2004-2008 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 <string.h>
28 #include <ctype.h>
29 #include <fcntl.h>
30 #include <time.h>
31 #include <getopt.h>
32 #include <dirent.h>
33 #include <sys/select.h>
34 #include <sys/poll.h>
35 #include <sys/wait.h>
36 #include <sys/stat.h>
37 #include <sys/ioctl.h>
38 #ifdef HAVE_INOTIFY
39 #include <sys/inotify.h>
40 #endif
41
42 #include "udev.h"
43
44 #define UDEVD_PRIORITY                  -4
45 #define UDEV_PRIORITY                   -2
46
47 /* maximum limit of forked childs */
48 #define UDEVD_MAX_CHILDS                256
49
50 static int debug;
51
52 static void log_fn(struct udev *udev, int priority,
53                    const char *file, int line, const char *fn,
54                    const char *format, va_list args)
55 {
56         if (debug) {
57                 fprintf(stderr, "[%d] %s: ", (int) getpid(), fn);
58                 vfprintf(stderr, format, args);
59         } else {
60                 vsyslog(priority, format, args);
61         }
62 }
63
64 static void reap_sigchilds(void);
65
66 static int debug_trace;
67 static struct udev_rules *rules;
68 static struct udev_queue_export *udev_queue_export;
69 static struct udev_ctrl *udev_ctrl;
70 static struct udev_monitor *kernel_monitor;
71 static volatile sig_atomic_t sigchilds_waiting;
72 static volatile sig_atomic_t udev_exit;
73 static volatile sig_atomic_t reload_config;
74 static volatile sig_atomic_t signal_received;
75 static volatile pid_t settle_pid;
76 static int run_exec_q;
77 static int stop_exec_q;
78 static int max_childs;
79 static int childs;
80 static struct udev_list_node event_list;
81
82 static struct udev_event *node_to_event(struct udev_list_node *node)
83 {
84         char *event;
85
86         event = (char *)node;
87         event -= offsetof(struct udev_event, node);
88         return (struct udev_event *)event;
89 }
90
91 static void event_queue_delete(struct udev_event *event)
92 {
93         udev_list_node_remove(&event->node);
94
95         /* mark as failed, if "add" event returns non-zero */
96         if (event->exitstatus && strcmp(udev_device_get_action(event->dev), "add") == 0)
97                 udev_queue_export_device_failed(udev_queue_export, event->dev);
98         else
99                 udev_queue_export_device_finished(udev_queue_export, event->dev);
100
101         udev_device_unref(event->dev);
102         udev_event_unref(event);
103 }
104
105 static void event_sig_handler(int signum)
106 {
107         if (signum == SIGALRM)
108                 _exit(1);
109 }
110
111 static void event_fork(struct udev_event *event)
112 {
113         pid_t pid;
114         struct sigaction act;
115         int err;
116
117 #if 0
118         /* single process, no forking, just for testing/profiling */
119         err = udev_event_execute_rules(event, rules);
120         if (err == 0 && !event->ignore_device && udev_get_run(event->udev))
121                 udev_event_execute_run(event);
122         info(event->udev, "seq %llu exit with %i\n", udev_device_get_seqnum(event->dev), err);
123         event_queue_delete(event);
124         return;
125 #endif
126
127         if (debug_trace) {
128                 event->trace = 1;
129                 fprintf(stderr, "fork %s (%llu)\n",
130                        udev_device_get_syspath(event->dev),
131                        udev_device_get_seqnum(event->dev));
132         }
133
134         pid = fork();
135         switch (pid) {
136         case 0:
137                 /* child */
138                 udev_queue_export_unref(udev_queue_export);
139                 udev_ctrl_unref(udev_ctrl);
140                 logging_close();
141                 logging_init("udevd-event");
142                 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
143
144                 /* set signal handlers */
145                 memset(&act, 0x00, sizeof(act));
146                 act.sa_handler = event_sig_handler;
147                 sigemptyset (&act.sa_mask);
148                 act.sa_flags = 0;
149                 sigaction(SIGALRM, &act, NULL);
150
151                 /* reset to default */
152                 act.sa_handler = SIG_DFL;
153                 sigaction(SIGINT, &act, NULL);
154                 sigaction(SIGTERM, &act, NULL);
155                 sigaction(SIGCHLD, &act, NULL);
156                 sigaction(SIGHUP, &act, NULL);
157
158                 /* set timeout to prevent hanging processes */
159                 alarm(UDEV_EVENT_TIMEOUT);
160
161                 /* apply rules, create node, symlinks */
162                 err = udev_event_execute_rules(event, rules);
163
164                 /* rules may change/disable the timeout */
165                 if (udev_device_get_event_timeout(event->dev) >= 0)
166                         alarm(udev_device_get_event_timeout(event->dev));
167
168                 /* execute RUN= */
169                 if (err == 0 && !event->ignore_device && udev_get_run(event->udev))
170                         udev_event_execute_run(event);
171
172                 /* apply/restore inotify watch */
173                 if (err == 0 && event->inotify_watch) {
174                         udev_watch_begin(event->udev, event->dev);
175                         udev_device_update_db(event->dev);
176                 }
177
178                 /* send processed event back to the kernel netlink socket */
179                 udev_monitor_send_device(kernel_monitor, event->dev);
180
181                 info(event->udev, "seq %llu exit with %i\n", udev_device_get_seqnum(event->dev), err);
182                 logging_close();
183                 if (err != 0)
184                         exit(1);
185                 exit(0);
186         case -1:
187                 err(event->udev, "fork of child failed: %m\n");
188                 event_queue_delete(event);
189                 break;
190         default:
191                 /* get SIGCHLD in main loop */
192                 info(event->udev, "seq %llu forked, pid [%d], '%s' '%s', %ld seconds old\n",
193                      udev_device_get_seqnum(event->dev),
194                      pid,
195                      udev_device_get_action(event->dev),
196                      udev_device_get_subsystem(event->dev),
197                      time(NULL) - event->queue_time);
198                 event->pid = pid;
199                 childs++;
200         }
201 }
202
203 static void event_queue_insert(struct udev_event *event)
204 {
205         event->queue_time = time(NULL);
206
207         udev_queue_export_device_queued(udev_queue_export, event->dev);
208         info(event->udev, "seq %llu queued, '%s' '%s'\n", udev_device_get_seqnum(event->dev),
209              udev_device_get_action(event->dev), udev_device_get_subsystem(event->dev));
210
211         udev_list_node_append(&event->node, &event_list);
212         run_exec_q = 1;
213
214         /* run all events with a timeout set immediately */
215         if (udev_device_get_timeout(event->dev) > 0) {
216                 event_fork(event);
217                 return;
218         }
219 }
220
221 static int mem_size_mb(void)
222 {
223         FILE *f;
224         char buf[4096];
225         long int memsize = -1;
226
227         f = fopen("/proc/meminfo", "r");
228         if (f == NULL)
229                 return -1;
230
231         while (fgets(buf, sizeof(buf), f) != NULL) {
232                 long int value;
233
234                 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
235                         memsize = value / 1024;
236                         break;
237                 }
238         }
239
240         fclose(f);
241         return memsize;
242 }
243
244 static int compare_devpath(const char *running, const char *waiting)
245 {
246         int i = 0;
247
248         while (running[i] != '\0' && running[i] == waiting[i])
249                 i++;
250
251         /* identical device event found */
252         if (running[i] == '\0' && waiting[i] == '\0')
253                 return 1;
254
255         /* parent device event found */
256         if (running[i] == '\0' && waiting[i] == '/')
257                 return 2;
258
259         /* child device event found */
260         if (running[i] == '/' && waiting[i] == '\0')
261                 return 3;
262
263         /* no matching event */
264         return 0;
265 }
266
267 /* lookup event for identical, parent, child device */
268 static int devpath_busy(struct udev_event *event)
269 {
270         struct udev_list_node *loop;
271
272         /* check if queue contains events we depend on */
273         udev_list_node_foreach(loop, &event_list) {
274                 struct udev_event *loop_event = node_to_event(loop);
275
276                 /* we already found a later event, earlier can not block us, no need to check again */
277                 if (udev_device_get_seqnum(loop_event->dev) < event->delaying_seqnum)
278                         continue;
279
280                 /* event we checked earlier still exists, no need to check again */
281                 if (udev_device_get_seqnum(loop_event->dev) == event->delaying_seqnum)
282                         return 2;
283
284                 /* found ourself, no later event can block us */
285                 if (udev_device_get_seqnum(loop_event->dev) >= udev_device_get_seqnum(event->dev))
286                         break;
287
288                 /* check our old name */
289                 if (udev_device_get_devpath_old(event->dev) != NULL)
290                         if (strcmp(udev_device_get_devpath(loop_event->dev), udev_device_get_devpath_old(event->dev)) == 0) {
291                                 event->delaying_seqnum = udev_device_get_seqnum(loop_event->dev);
292                                 return 3;
293                         }
294
295                 /* check identical, parent, or child device event */
296                 if (compare_devpath(udev_device_get_devpath(loop_event->dev), udev_device_get_devpath(event->dev)) != 0) {
297                         dbg(event->udev, "%llu, device event still pending %llu (%s)\n",
298                             udev_device_get_seqnum(event->dev),
299                             udev_device_get_seqnum(loop_event->dev),
300                             udev_device_get_devpath(loop_event->dev));
301                         event->delaying_seqnum = udev_device_get_seqnum(loop_event->dev);
302                         return 4;
303                 }
304
305                 /* check for our major:minor number */
306                 if (major(udev_device_get_devnum(event->dev)) > 0 &&
307                     udev_device_get_devnum(loop_event->dev) == udev_device_get_devnum(event->dev) &&
308                     strcmp(udev_device_get_subsystem(event->dev), udev_device_get_subsystem(loop_event->dev)) == 0) {
309                         dbg(event->udev, "%llu, device event still pending %llu (%d:%d)\n",
310                             udev_device_get_seqnum(event->dev),
311                             udev_device_get_seqnum(loop_event->dev),
312                             major(udev_device_get_devnum(loop_event->dev)), minor(udev_device_get_devnum(loop_event->dev)));
313                         event->delaying_seqnum = udev_device_get_seqnum(loop_event->dev);
314                         return 5;
315                 }
316         }
317         return 0;
318 }
319
320 /* serializes events for the identical and parent and child devices */
321 static void event_queue_manager(struct udev *udev)
322 {
323         struct udev_list_node *loop;
324         struct udev_list_node *tmp;
325
326 start_over:
327         if (udev_list_is_empty(&event_list)) {
328                 if (childs > 0) {
329                         err(udev, "event list empty, but childs count is %i", childs);
330                         childs = 0;
331                 }
332                 return;
333         }
334
335         udev_list_node_foreach_safe(loop, tmp, &event_list) {
336                 struct udev_event *loop_event = node_to_event(loop);
337
338                 if (childs >= max_childs) {
339                         info(udev, "maximum number (%i) of childs reached\n", childs);
340                         break;
341                 }
342
343                 if (loop_event->pid != 0)
344                         continue;
345
346                 /* do not start event if parent or child event is still running */
347                 if (devpath_busy(loop_event) != 0) {
348                         dbg(udev, "delay seq %llu (%s)\n",
349                             udev_device_get_seqnum(loop_event->dev),
350                             udev_device_get_devpath(loop_event->dev));
351                         continue;
352                 }
353
354                 event_fork(loop_event);
355                 dbg(udev, "moved seq %llu to running list\n", udev_device_get_seqnum(loop_event->dev));
356
357                 /* retry if events finished in the meantime */
358                 if (sigchilds_waiting) {
359                         sigchilds_waiting = 0;
360                         reap_sigchilds();
361                         goto start_over;
362                 }
363         }
364 }
365
366 /* receive the udevd message from userspace */
367 static void handle_ctrl_msg(struct udev_ctrl *uctrl)
368 {
369         struct udev *udev = udev_ctrl_get_udev(uctrl);
370         struct udev_ctrl_msg *ctrl_msg;
371         const char *str;
372         int i;
373
374         ctrl_msg = udev_ctrl_receive_msg(uctrl);
375         if (ctrl_msg == NULL)
376                 return;
377
378         i = udev_ctrl_get_set_log_level(ctrl_msg);
379         if (i >= 0) {
380                 info(udev, "udevd message (SET_LOG_PRIORITY) received, log_priority=%i\n", i);
381                 udev_set_log_priority(udev, i);
382         }
383
384         if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
385                 info(udev, "udevd message (STOP_EXEC_QUEUE) received\n");
386                 stop_exec_q = 1;
387         }
388
389         if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
390                 info(udev, "udevd message (START_EXEC_QUEUE) received\n");
391                 stop_exec_q = 0;
392                 event_queue_manager(udev);
393         }
394
395         if (udev_ctrl_get_reload_rules(ctrl_msg) > 0) {
396                 info(udev, "udevd message (RELOAD_RULES) received\n");
397                 reload_config = 1;
398         }
399
400         str = udev_ctrl_get_set_env(ctrl_msg);
401         if (str != NULL) {
402                 char *key;
403
404                 key = strdup(str);
405                 if (key != NULL) {
406                         char *val;
407
408                         val = strchr(key, '=');
409                         if (val != NULL) {
410                                 val[0] = '\0';
411                                 val = &val[1];
412                                 if (val[0] == '\0') {
413                                         info(udev, "udevd message (ENV) received, unset '%s'\n", key);
414                                         udev_add_property(udev, key, NULL);
415                                 } else {
416                                         info(udev, "udevd message (ENV) received, set '%s=%s'\n", key, val);
417                                         udev_add_property(udev, key, val);
418                                 }
419                         } else {
420                                 err(udev, "wrong key format '%s'\n", key);
421                         }
422                         free(key);
423                 }
424         }
425
426         i = udev_ctrl_get_set_max_childs(ctrl_msg);
427         if (i >= 0) {
428                 info(udev, "udevd message (SET_MAX_CHILDS) received, max_childs=%i\n", i);
429                 max_childs = i;
430         }
431
432         settle_pid = udev_ctrl_get_settle(ctrl_msg);
433         if (settle_pid > 0) {
434                 info(udev, "udevd message (SETTLE) received\n");
435         }
436         udev_ctrl_msg_unref(ctrl_msg);
437 }
438
439 /* read inotify messages */
440 static int handle_inotify(struct udev *udev)
441 {
442         int nbytes, pos;
443         char *buf;
444         struct inotify_event *ev;
445
446         if ((ioctl(inotify_fd, FIONREAD, &nbytes) < 0) || (nbytes <= 0))
447                 return 0;
448
449         buf = malloc(nbytes);
450         if (buf == NULL) {
451                 err(udev, "error getting buffer for inotify, disable watching\n");
452                 close(inotify_fd);
453                 inotify_fd = -1;
454                 return 0;
455         }
456
457         read(inotify_fd, buf, nbytes);
458
459         for (pos = 0; pos < nbytes; pos += sizeof(struct inotify_event) + ev->len) {
460                 struct udev_device *dev;
461
462                 ev = (struct inotify_event *)(buf + pos);
463                 if (ev->len) {
464                         dbg(udev, "inotify event: %x for %s\n", ev->mask, ev->name);
465                         reload_config = 1;
466                         continue;
467                 }
468
469                 dev = udev_watch_lookup(udev, ev->wd);
470                 if (dev != NULL) {
471                         dbg(udev, "inotify event: %x for %s\n", ev->mask, udev_device_get_devnode(dev));
472                         if (ev->mask & IN_CLOSE_WRITE) {
473                                 char filename[UTIL_PATH_SIZE];
474                                 int fd;
475
476                                 info(udev, "device %s closed, synthesising 'change'\n", udev_device_get_devnode(dev));
477                                 util_strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
478                                 fd = open(filename, O_WRONLY);
479                                 if (fd < 0 || write(fd, "change", 6) < 0)
480                                         info(udev, "error writing uevent: %m\n");
481                                 close(fd);
482                         }
483                         if (ev->mask & IN_IGNORED)
484                                 udev_watch_end(udev, dev);
485
486                         udev_device_unref(dev);
487                 }
488
489         }
490
491         free (buf);
492         return 0;
493 }
494
495 static void sig_handler(int signum)
496 {
497         switch (signum) {
498                 case SIGINT:
499                 case SIGTERM:
500                         udev_exit = 1;
501                         break;
502                 case SIGCHLD:
503                         /* set flag, then write to pipe if needed */
504                         sigchilds_waiting = 1;
505                         break;
506                 case SIGHUP:
507                         reload_config = 1;
508                         break;
509         }
510
511         signal_received = 1;
512 }
513
514 static void udev_done(int pid, int exitstatus)
515 {
516         struct udev_list_node *loop;
517
518         /* find event associated with pid and delete it */
519         udev_list_node_foreach(loop, &event_list) {
520                 struct udev_event *loop_event = node_to_event(loop);
521
522                 if (loop_event->pid == pid) {
523                         info(loop_event->udev, "seq %llu cleanup, pid [%d], status %i, %ld seconds old\n",
524                              udev_device_get_seqnum(loop_event->dev), loop_event->pid,
525                              exitstatus, time(NULL) - loop_event->queue_time);
526                         loop_event->exitstatus = exitstatus;
527                         if (debug_trace)
528                                 fprintf(stderr, "exit %s (%llu)\n",
529                                        udev_device_get_syspath(loop_event->dev),
530                                        udev_device_get_seqnum(loop_event->dev));
531                         event_queue_delete(loop_event);
532                         childs--;
533
534                         /* there may be dependent events waiting */
535                         run_exec_q = 1;
536                         return;
537                 }
538         }
539 }
540
541 static void reap_sigchilds(void)
542 {
543         pid_t pid;
544         int status;
545
546         while (1) {
547                 pid = waitpid(-1, &status, WNOHANG);
548                 if (pid <= 0)
549                         break;
550                 if (WIFEXITED(status))
551                         status = WEXITSTATUS(status);
552                 else if (WIFSIGNALED(status))
553                         status = WTERMSIG(status) + 128;
554                 else
555                         status = 0;
556                 udev_done(pid, status);
557         }
558 }
559
560 static void startup_log(struct udev *udev)
561 {
562         FILE *f;
563         char path[UTIL_PATH_SIZE];
564         struct stat statbuf;
565
566         f = fopen("/dev/kmsg", "w");
567         if (f != NULL)
568                 fprintf(f, "<6>udev: starting version " VERSION "\n");
569
570         util_strscpyl(path, sizeof(path), udev_get_sys_path(udev), "/class/mem/null", NULL);
571         if (lstat(path, &statbuf) == 0 && S_ISDIR(statbuf.st_mode)) {
572                 const char *depr_str =
573                         "udev: missing sysfs features; please update the kernel "
574                         "or disable the kernel's CONFIG_SYSFS_DEPRECATED option; "
575                         "udev may fail to work correctly";
576
577                 if (f != NULL)
578                         fprintf(f, "<3>%s\n", depr_str);
579                 err(udev, "%s\n", depr_str);
580                 sleep(3);
581         }
582
583         if (f != NULL)
584                 fclose(f);
585 }
586
587 int main(int argc, char *argv[])
588 {
589         struct udev *udev;
590         int fd;
591         struct sigaction act;
592         const char *value;
593         int daemonize = 0;
594         int resolve_names = 1;
595         static const struct option options[] = {
596                 { "daemon", no_argument, NULL, 'd' },
597                 { "debug-trace", no_argument, NULL, 't' },
598                 { "debug", no_argument, NULL, 'D' },
599                 { "help", no_argument, NULL, 'h' },
600                 { "version", no_argument, NULL, 'V' },
601                 { "resolve-names", required_argument, NULL, 'N' },
602                 {}
603         };
604         int rc = 1;
605
606         udev = udev_new();
607         if (udev == NULL)
608                 goto exit;
609
610         logging_init("udevd");
611         udev_set_log_fn(udev, log_fn);
612         info(udev, "version %s\n", VERSION);
613         udev_selinux_init(udev);
614
615         while (1) {
616                 int option;
617
618                 option = getopt_long(argc, argv, "dDthV", options, NULL);
619                 if (option == -1)
620                         break;
621
622                 switch (option) {
623                 case 'd':
624                         daemonize = 1;
625                         break;
626                 case 't':
627                         debug_trace = 1;
628                         break;
629                 case 'D':
630                         debug = 1;
631                         if (udev_get_log_priority(udev) < LOG_INFO)
632                                 udev_set_log_priority(udev, LOG_INFO);
633                         break;
634                 case 'N':
635                         if (strcmp (optarg, "early") == 0) {
636                                 resolve_names = 1;
637                         } else if (strcmp (optarg, "late") == 0) {
638                                 resolve_names = 0;
639                         } else if (strcmp (optarg, "never") == 0) {
640                                 resolve_names = -1;
641                         } else {
642                                 fprintf(stderr, "resolve-names must be early, late or never\n");
643                                 err(udev, "resolve-names must be early, late or never\n");
644                                 goto exit;
645                         }
646                         break;
647                 case 'h':
648                         printf("Usage: udevd [--help] [--daemon] [--debug-trace] [--debug] "
649                                "[--resolve-names=early|late|never] [--version]\n");
650                         goto exit;
651                 case 'V':
652                         printf("%s\n", VERSION);
653                         goto exit;
654                 default:
655                         goto exit;
656                 }
657         }
658
659         if (getuid() != 0) {
660                 fprintf(stderr, "root privileges required\n");
661                 err(udev, "root privileges required\n");
662                 goto exit;
663         }
664
665         /* make sure std{in,out,err} fd's are in a sane state */
666         fd = open("/dev/null", O_RDWR);
667         if (fd < 0) {
668                 fprintf(stderr, "cannot open /dev/null\n");
669                 err(udev, "cannot open /dev/null\n");
670         }
671         if (write(STDOUT_FILENO, 0, 0) < 0)
672                 dup2(fd, STDOUT_FILENO);
673         if (write(STDERR_FILENO, 0, 0) < 0)
674                 dup2(fd, STDERR_FILENO);
675
676         /* init control socket, bind() ensures, that only one udevd instance is running */
677         udev_ctrl = udev_ctrl_new_from_socket(udev, UDEV_CTRL_SOCK_PATH);
678         if (udev_ctrl == NULL) {
679                 fprintf(stderr, "error initializing control socket");
680                 err(udev, "error initializing udevd socket");
681                 rc = 1;
682                 goto exit;
683         }
684
685         if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
686                 fprintf(stderr, "error binding control socket, seems udevd is already running\n");
687                 err(udev, "error binding control socket, seems udevd is already running\n");
688                 rc = 1;
689                 goto exit;
690         }
691
692         kernel_monitor = udev_monitor_new_from_netlink(udev, "kernel");
693         if (kernel_monitor == NULL || udev_monitor_enable_receiving(kernel_monitor) < 0) {
694                 fprintf(stderr, "error initializing netlink socket\n");
695                 err(udev, "error initializing netlink socket\n");
696                 rc = 3;
697                 goto exit;
698         }
699         udev_monitor_set_receive_buffer_size(kernel_monitor, 128*1024*1024);
700
701         rules = udev_rules_new(udev, resolve_names);
702         if (rules == NULL) {
703                 err(udev, "error reading rules\n");
704                 goto exit;
705         }
706         udev_list_init(&event_list);
707         udev_queue_export = udev_queue_export_new(udev);
708         if (udev_queue_export == NULL) {
709                 err(udev, "error creating queue file\n");
710                 goto exit;
711         }
712
713         if (daemonize) {
714                 pid_t pid;
715
716                 pid = fork();
717                 switch (pid) {
718                 case 0:
719                         dbg(udev, "daemonized fork running\n");
720                         break;
721                 case -1:
722                         err(udev, "fork of daemon failed: %m\n");
723                         rc = 4;
724                         goto exit;
725                 default:
726                         dbg(udev, "child [%u] running, parent exits\n", pid);
727                         rc = 0;
728                         goto exit;
729                 }
730         }
731
732         /* redirect std{out,err} */
733         if (!debug && !debug_trace) {
734                 dup2(fd, STDIN_FILENO);
735                 dup2(fd, STDOUT_FILENO);
736                 dup2(fd, STDERR_FILENO);
737         }
738         if (fd > STDERR_FILENO)
739                 close(fd);
740
741         /* set scheduling priority for the daemon */
742         setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
743
744         chdir("/");
745         umask(022);
746         setsid();
747
748         /* OOM_DISABLE == -17 */
749         fd = open("/proc/self/oom_adj", O_RDWR);
750         if (fd < 0)
751                 err(udev, "error disabling OOM: %m\n");
752         else {
753                 write(fd, "-17", 3);
754                 close(fd);
755         }
756
757         startup_log(udev);
758
759         /* set signal handlers */
760         memset(&act, 0x00, sizeof(struct sigaction));
761         act.sa_handler = sig_handler;
762         sigemptyset(&act.sa_mask);
763         act.sa_flags = SA_RESTART;
764         sigaction(SIGINT, &act, NULL);
765         sigaction(SIGTERM, &act, NULL);
766         sigaction(SIGCHLD, &act, NULL);
767         sigaction(SIGHUP, &act, NULL);
768
769         /* watch rules directory */
770         udev_watch_init(udev);
771         if (inotify_fd >= 0) {
772                 if (udev_get_rules_path(udev) != NULL) {
773                         inotify_add_watch(inotify_fd, udev_get_rules_path(udev),
774                                           IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
775                 } else {
776                         char filename[UTIL_PATH_SIZE];
777
778                         inotify_add_watch(inotify_fd, UDEV_PREFIX "/lib/udev/rules.d",
779                                           IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
780                         inotify_add_watch(inotify_fd, SYSCONFDIR "/udev/rules.d",
781                                           IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
782
783                         /* watch dynamic rules directory */
784                         util_strscpyl(filename, sizeof(filename), udev_get_dev_path(udev), "/.udev/rules.d", NULL);
785                         inotify_add_watch(inotify_fd, filename,
786                                           IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
787                 }
788
789                 udev_watch_restore(udev);
790         }
791
792         /* in trace mode run one event after the other */
793         if (debug_trace) {
794                 max_childs = 1;
795         } else {
796                 int memsize = mem_size_mb();
797                 if (memsize > 0)
798                         max_childs = 128 + (memsize / 4);
799                 else
800                         max_childs = UDEVD_MAX_CHILDS;
801         }
802         /* possibly overwrite maximum limit of executed events */
803         value = getenv("UDEVD_MAX_CHILDS");
804         if (value)
805                 max_childs = strtoul(value, NULL, 10);
806         info(udev, "initialize max_childs to %u\n", max_childs);
807
808         while (!udev_exit) {
809                 sigset_t blocked_mask, orig_mask;
810                 struct pollfd pfd[4];
811                 struct pollfd *ctrl_poll, *monitor_poll, *inotify_poll = NULL;
812                 int nfds = 0;
813                 int fdcount;
814
815                 sigfillset(&blocked_mask);
816                 sigprocmask(SIG_SETMASK, &blocked_mask, &orig_mask);
817                 if (signal_received) {
818                         sigprocmask(SIG_SETMASK, &orig_mask, NULL);
819                         goto handle_signals;
820                 }
821
822                 ctrl_poll = &pfd[nfds++];
823                 ctrl_poll->fd = udev_ctrl_get_fd(udev_ctrl);
824                 ctrl_poll->events = POLLIN;
825
826                 monitor_poll = &pfd[nfds++];
827                 monitor_poll->fd = udev_monitor_get_fd(kernel_monitor);
828                 monitor_poll->events = POLLIN;
829
830                 if (inotify_fd >= 0) {
831                         inotify_poll = &pfd[nfds++];
832                         inotify_poll->fd = inotify_fd;
833                         inotify_poll->events = POLLIN;
834                 }
835
836                 fdcount = ppoll(pfd, nfds, NULL, &orig_mask);
837                 sigprocmask(SIG_SETMASK, &orig_mask, NULL);
838                 if (fdcount < 0) {
839                         if (errno == EINTR)
840                                 goto handle_signals;
841                         err(udev, "error in select: %m\n");
842                         continue;
843                 }
844
845                 /* get control message */
846                 if (ctrl_poll->revents & POLLIN)
847                         handle_ctrl_msg(udev_ctrl);
848
849                 /* get kernel uevent */
850                 if (monitor_poll->revents & POLLIN) {
851                         struct udev_device *dev;
852
853                         dev = udev_monitor_receive_device(kernel_monitor);
854                         if (dev != NULL) {
855                                 struct udev_event *event;
856
857                                 event = udev_event_new(dev);
858                                 if (event != NULL)
859                                         event_queue_insert(event);
860                                 else
861                                         udev_device_unref(dev);
862                         }
863                 }
864
865                 /* rules directory inotify watch */
866                 if (inotify_poll && (inotify_poll->revents & POLLIN))
867                         handle_inotify(udev);
868
869 handle_signals:
870                 signal_received = 0;
871
872                 /* rules changed, set by inotify or a HUP signal */
873                 if (reload_config) {
874                         struct udev_rules *rules_new;
875
876                         reload_config = 0;
877                         rules_new = udev_rules_new(udev, resolve_names);
878                         if (rules_new != NULL) {
879                                 udev_rules_unref(rules);
880                                 rules = rules_new;
881                         }
882                 }
883
884                 if (sigchilds_waiting) {
885                         sigchilds_waiting = 0;
886                         reap_sigchilds();
887                 }
888
889                 if (run_exec_q) {
890                         run_exec_q = 0;
891                         if (!stop_exec_q)
892                                 event_queue_manager(udev);
893                 }
894
895                 if (settle_pid > 0) {
896                         kill(settle_pid, SIGUSR1);
897                         settle_pid = 0;
898                 }
899         }
900         udev_queue_export_cleanup(udev_queue_export);
901         rc = 0;
902 exit:
903
904         udev_queue_export_unref(udev_queue_export);
905         udev_rules_unref(rules);
906         udev_ctrl_unref(udev_ctrl);
907         if (inotify_fd >= 0)
908                 close(inotify_fd);
909         udev_monitor_unref(kernel_monitor);
910         udev_selinux_exit(udev);
911         udev_unref(udev);
912         logging_close();
913         return rc;
914 }