chiark / gitweb /
37b547ad656a5f57bd130e7be102995d8f20082e
[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         return 0;
306 }
307
308 /* serializes events for the identical and parent and child devices */
309 static void event_queue_manager(struct udev *udev)
310 {
311         struct udev_list_node *loop;
312         struct udev_list_node *tmp;
313
314 start_over:
315         if (udev_list_is_empty(&event_list)) {
316                 if (childs > 0) {
317                         err(udev, "event list empty, but childs count is %i", childs);
318                         childs = 0;
319                 }
320                 return;
321         }
322
323         udev_list_node_foreach_safe(loop, tmp, &event_list) {
324                 struct udev_event *loop_event = node_to_event(loop);
325
326                 if (childs >= max_childs) {
327                         info(udev, "maximum number (%i) of childs reached\n", childs);
328                         break;
329                 }
330
331                 if (loop_event->pid != 0)
332                         continue;
333
334                 /* do not start event if parent or child event is still running */
335                 if (devpath_busy(loop_event) != 0) {
336                         dbg(udev, "delay seq %llu (%s)\n",
337                             udev_device_get_seqnum(loop_event->dev),
338                             udev_device_get_devpath(loop_event->dev));
339                         continue;
340                 }
341
342                 event_fork(loop_event);
343                 dbg(udev, "moved seq %llu to running list\n", udev_device_get_seqnum(loop_event->dev));
344
345                 /* retry if events finished in the meantime */
346                 if (sigchilds_waiting) {
347                         sigchilds_waiting = 0;
348                         reap_sigchilds();
349                         goto start_over;
350                 }
351         }
352 }
353
354 /* receive the udevd message from userspace */
355 static void handle_ctrl_msg(struct udev_ctrl *uctrl)
356 {
357         struct udev *udev = udev_ctrl_get_udev(uctrl);
358         struct udev_ctrl_msg *ctrl_msg;
359         const char *str;
360         int i;
361
362         ctrl_msg = udev_ctrl_receive_msg(uctrl);
363         if (ctrl_msg == NULL)
364                 return;
365
366         i = udev_ctrl_get_set_log_level(ctrl_msg);
367         if (i >= 0) {
368                 info(udev, "udevd message (SET_LOG_PRIORITY) received, log_priority=%i\n", i);
369                 udev_set_log_priority(udev, i);
370         }
371
372         if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
373                 info(udev, "udevd message (STOP_EXEC_QUEUE) received\n");
374                 stop_exec_q = 1;
375         }
376
377         if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
378                 info(udev, "udevd message (START_EXEC_QUEUE) received\n");
379                 stop_exec_q = 0;
380                 event_queue_manager(udev);
381         }
382
383         if (udev_ctrl_get_reload_rules(ctrl_msg) > 0) {
384                 info(udev, "udevd message (RELOAD_RULES) received\n");
385                 reload_config = 1;
386         }
387
388         str = udev_ctrl_get_set_env(ctrl_msg);
389         if (str != NULL) {
390                 char *key;
391
392                 key = strdup(str);
393                 if (key != NULL) {
394                         char *val;
395
396                         val = strchr(key, '=');
397                         if (val != NULL) {
398                                 val[0] = '\0';
399                                 val = &val[1];
400                                 if (val[0] == '\0') {
401                                         info(udev, "udevd message (ENV) received, unset '%s'\n", key);
402                                         udev_add_property(udev, key, NULL);
403                                 } else {
404                                         info(udev, "udevd message (ENV) received, set '%s=%s'\n", key, val);
405                                         udev_add_property(udev, key, val);
406                                 }
407                         } else {
408                                 err(udev, "wrong key format '%s'\n", key);
409                         }
410                         free(key);
411                 }
412         }
413
414         i = udev_ctrl_get_set_max_childs(ctrl_msg);
415         if (i >= 0) {
416                 info(udev, "udevd message (SET_MAX_CHILDS) received, max_childs=%i\n", i);
417                 max_childs = i;
418         }
419
420         settle_pid = udev_ctrl_get_settle(ctrl_msg);
421         if (settle_pid > 0) {
422                 info(udev, "udevd message (SETTLE) received\n");
423         }
424         udev_ctrl_msg_unref(ctrl_msg);
425 }
426
427 /* read inotify messages */
428 static int handle_inotify(struct udev *udev)
429 {
430         int nbytes, pos;
431         char *buf;
432         struct inotify_event *ev;
433
434         if ((ioctl(inotify_fd, FIONREAD, &nbytes) < 0) || (nbytes <= 0))
435                 return 0;
436
437         buf = malloc(nbytes);
438         if (buf == NULL) {
439                 err(udev, "error getting buffer for inotify, disable watching\n");
440                 close(inotify_fd);
441                 inotify_fd = -1;
442                 return 0;
443         }
444
445         read(inotify_fd, buf, nbytes);
446
447         for (pos = 0; pos < nbytes; pos += sizeof(struct inotify_event) + ev->len) {
448                 struct udev_device *dev;
449
450                 ev = (struct inotify_event *)(buf + pos);
451                 if (ev->len) {
452                         dbg(udev, "inotify event: %x for %s\n", ev->mask, ev->name);
453                         reload_config = 1;
454                         continue;
455                 }
456
457                 dev = udev_watch_lookup(udev, ev->wd);
458                 if (dev != NULL) {
459                         dbg(udev, "inotify event: %x for %s\n", ev->mask, udev_device_get_devnode(dev));
460                         if (ev->mask & IN_CLOSE_WRITE) {
461                                 char filename[UTIL_PATH_SIZE];
462                                 int fd;
463
464                                 info(udev, "device %s closed, synthesising 'change'\n", udev_device_get_devnode(dev));
465                                 util_strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
466                                 fd = open(filename, O_WRONLY);
467                                 if (fd < 0 || write(fd, "change", 6) < 0)
468                                         info(udev, "error writing uevent: %m\n");
469                                 close(fd);
470                         }
471                         if (ev->mask & IN_IGNORED)
472                                 udev_watch_end(udev, dev);
473
474                         udev_device_unref(dev);
475                 }
476
477         }
478
479         free (buf);
480         return 0;
481 }
482
483 static void sig_handler(int signum)
484 {
485         switch (signum) {
486                 case SIGINT:
487                 case SIGTERM:
488                         udev_exit = 1;
489                         break;
490                 case SIGCHLD:
491                         /* set flag, then write to pipe if needed */
492                         sigchilds_waiting = 1;
493                         break;
494                 case SIGHUP:
495                         reload_config = 1;
496                         break;
497         }
498
499         signal_received = 1;
500 }
501
502 static void udev_done(int pid, int exitstatus)
503 {
504         struct udev_list_node *loop;
505
506         /* find event associated with pid and delete it */
507         udev_list_node_foreach(loop, &event_list) {
508                 struct udev_event *loop_event = node_to_event(loop);
509
510                 if (loop_event->pid == pid) {
511                         info(loop_event->udev, "seq %llu cleanup, pid [%d], status %i, %ld seconds old\n",
512                              udev_device_get_seqnum(loop_event->dev), loop_event->pid,
513                              exitstatus, time(NULL) - loop_event->queue_time);
514                         loop_event->exitstatus = exitstatus;
515                         if (debug_trace)
516                                 fprintf(stderr, "exit %s (%llu)\n",
517                                        udev_device_get_syspath(loop_event->dev),
518                                        udev_device_get_seqnum(loop_event->dev));
519                         event_queue_delete(loop_event);
520                         childs--;
521
522                         /* there may be dependent events waiting */
523                         run_exec_q = 1;
524                         return;
525                 }
526         }
527 }
528
529 static void reap_sigchilds(void)
530 {
531         pid_t pid;
532         int status;
533
534         while (1) {
535                 pid = waitpid(-1, &status, WNOHANG);
536                 if (pid <= 0)
537                         break;
538                 if (WIFEXITED(status))
539                         status = WEXITSTATUS(status);
540                 else if (WIFSIGNALED(status))
541                         status = WTERMSIG(status) + 128;
542                 else
543                         status = 0;
544                 udev_done(pid, status);
545         }
546 }
547
548 static void startup_log(struct udev *udev)
549 {
550         FILE *f;
551         char path[UTIL_PATH_SIZE];
552         struct stat statbuf;
553
554         f = fopen("/dev/kmsg", "w");
555         if (f != NULL)
556                 fprintf(f, "<6>udev: starting version " VERSION "\n");
557
558         util_strscpyl(path, sizeof(path), udev_get_sys_path(udev), "/class/mem/null", NULL);
559         if (lstat(path, &statbuf) == 0 && S_ISDIR(statbuf.st_mode)) {
560                 const char *depr_str =
561                         "udev: missing sysfs features; please update the kernel "
562                         "or disable the kernel's CONFIG_SYSFS_DEPRECATED option; "
563                         "udev may fail to work correctly";
564
565                 if (f != NULL)
566                         fprintf(f, "<3>%s\n", depr_str);
567                 err(udev, "%s\n", depr_str);
568                 sleep(3);
569         }
570
571         if (f != NULL)
572                 fclose(f);
573 }
574
575 int main(int argc, char *argv[])
576 {
577         struct udev *udev;
578         int fd;
579         struct sigaction act;
580         const char *value;
581         int daemonize = 0;
582         int resolve_names = 1;
583         static const struct option options[] = {
584                 { "daemon", no_argument, NULL, 'd' },
585                 { "debug-trace", no_argument, NULL, 't' },
586                 { "debug", no_argument, NULL, 'D' },
587                 { "help", no_argument, NULL, 'h' },
588                 { "version", no_argument, NULL, 'V' },
589                 { "resolve-names", required_argument, NULL, 'N' },
590                 {}
591         };
592         int rc = 1;
593
594         udev = udev_new();
595         if (udev == NULL)
596                 goto exit;
597
598         logging_init("udevd");
599         udev_set_log_fn(udev, log_fn);
600         info(udev, "version %s\n", VERSION);
601         udev_selinux_init(udev);
602
603         while (1) {
604                 int option;
605
606                 option = getopt_long(argc, argv, "dDthV", options, NULL);
607                 if (option == -1)
608                         break;
609
610                 switch (option) {
611                 case 'd':
612                         daemonize = 1;
613                         break;
614                 case 't':
615                         debug_trace = 1;
616                         break;
617                 case 'D':
618                         debug = 1;
619                         if (udev_get_log_priority(udev) < LOG_INFO)
620                                 udev_set_log_priority(udev, LOG_INFO);
621                         break;
622                 case 'N':
623                         if (strcmp (optarg, "early") == 0) {
624                                 resolve_names = 1;
625                         } else if (strcmp (optarg, "late") == 0) {
626                                 resolve_names = 0;
627                         } else if (strcmp (optarg, "never") == 0) {
628                                 resolve_names = -1;
629                         } else {
630                                 fprintf(stderr, "resolve-names must be early, late or never\n");
631                                 err(udev, "resolve-names must be early, late or never\n");
632                                 goto exit;
633                         }
634                         break;
635                 case 'h':
636                         printf("Usage: udevd [--help] [--daemon] [--debug-trace] [--debug] "
637                                "[--resolve-names=early|late|never] [--version]\n");
638                         goto exit;
639                 case 'V':
640                         printf("%s\n", VERSION);
641                         goto exit;
642                 default:
643                         goto exit;
644                 }
645         }
646
647         if (getuid() != 0) {
648                 fprintf(stderr, "root privileges required\n");
649                 err(udev, "root privileges required\n");
650                 goto exit;
651         }
652
653         /* make sure std{in,out,err} fd's are in a sane state */
654         fd = open("/dev/null", O_RDWR);
655         if (fd < 0) {
656                 fprintf(stderr, "cannot open /dev/null\n");
657                 err(udev, "cannot open /dev/null\n");
658         }
659         if (write(STDOUT_FILENO, 0, 0) < 0)
660                 dup2(fd, STDOUT_FILENO);
661         if (write(STDERR_FILENO, 0, 0) < 0)
662                 dup2(fd, STDERR_FILENO);
663
664         /* init control socket, bind() ensures, that only one udevd instance is running */
665         udev_ctrl = udev_ctrl_new_from_socket(udev, UDEV_CTRL_SOCK_PATH);
666         if (udev_ctrl == NULL) {
667                 fprintf(stderr, "error initializing control socket");
668                 err(udev, "error initializing udevd socket");
669                 rc = 1;
670                 goto exit;
671         }
672
673         if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
674                 fprintf(stderr, "error binding control socket, seems udevd is already running\n");
675                 err(udev, "error binding control socket, seems udevd is already running\n");
676                 rc = 1;
677                 goto exit;
678         }
679
680         kernel_monitor = udev_monitor_new_from_netlink(udev, "kernel");
681         if (kernel_monitor == NULL || udev_monitor_enable_receiving(kernel_monitor) < 0) {
682                 fprintf(stderr, "error initializing netlink socket\n");
683                 err(udev, "error initializing netlink socket\n");
684                 rc = 3;
685                 goto exit;
686         }
687         udev_monitor_set_receive_buffer_size(kernel_monitor, 128*1024*1024);
688
689         rules = udev_rules_new(udev, resolve_names);
690         if (rules == NULL) {
691                 err(udev, "error reading rules\n");
692                 goto exit;
693         }
694         udev_list_init(&event_list);
695         udev_queue_export = udev_queue_export_new(udev);
696         if (udev_queue_export == NULL) {
697                 err(udev, "error creating queue file\n");
698                 goto exit;
699         }
700
701         if (daemonize) {
702                 pid_t pid;
703
704                 pid = fork();
705                 switch (pid) {
706                 case 0:
707                         dbg(udev, "daemonized fork running\n");
708                         break;
709                 case -1:
710                         err(udev, "fork of daemon failed: %m\n");
711                         rc = 4;
712                         goto exit;
713                 default:
714                         dbg(udev, "child [%u] running, parent exits\n", pid);
715                         rc = 0;
716                         goto exit;
717                 }
718         }
719
720         /* redirect std{out,err} */
721         if (!debug && !debug_trace) {
722                 dup2(fd, STDIN_FILENO);
723                 dup2(fd, STDOUT_FILENO);
724                 dup2(fd, STDERR_FILENO);
725         }
726         if (fd > STDERR_FILENO)
727                 close(fd);
728
729         /* set scheduling priority for the daemon */
730         setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
731
732         chdir("/");
733         umask(022);
734         setsid();
735
736         /* OOM_DISABLE == -17 */
737         fd = open("/proc/self/oom_adj", O_RDWR);
738         if (fd < 0)
739                 err(udev, "error disabling OOM: %m\n");
740         else {
741                 write(fd, "-17", 3);
742                 close(fd);
743         }
744
745         startup_log(udev);
746
747         /* set signal handlers */
748         memset(&act, 0x00, sizeof(struct sigaction));
749         act.sa_handler = sig_handler;
750         sigemptyset(&act.sa_mask);
751         act.sa_flags = SA_RESTART;
752         sigaction(SIGINT, &act, NULL);
753         sigaction(SIGTERM, &act, NULL);
754         sigaction(SIGCHLD, &act, NULL);
755         sigaction(SIGHUP, &act, NULL);
756
757         /* watch rules directory */
758         udev_watch_init(udev);
759         if (inotify_fd >= 0) {
760                 if (udev_get_rules_path(udev) != NULL) {
761                         inotify_add_watch(inotify_fd, udev_get_rules_path(udev),
762                                           IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
763                 } else {
764                         char filename[UTIL_PATH_SIZE];
765
766                         inotify_add_watch(inotify_fd, UDEV_PREFIX "/lib/udev/rules.d",
767                                           IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
768                         inotify_add_watch(inotify_fd, SYSCONFDIR "/udev/rules.d",
769                                           IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
770
771                         /* watch dynamic rules directory */
772                         util_strscpyl(filename, sizeof(filename), udev_get_dev_path(udev), "/.udev/rules.d", NULL);
773                         inotify_add_watch(inotify_fd, filename,
774                                           IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
775                 }
776
777                 udev_watch_restore(udev);
778         }
779
780         /* in trace mode run one event after the other */
781         if (debug_trace) {
782                 max_childs = 1;
783         } else {
784                 int memsize = mem_size_mb();
785                 if (memsize > 0)
786                         max_childs = 128 + (memsize / 4);
787                 else
788                         max_childs = UDEVD_MAX_CHILDS;
789         }
790         /* possibly overwrite maximum limit of executed events */
791         value = getenv("UDEVD_MAX_CHILDS");
792         if (value)
793                 max_childs = strtoul(value, NULL, 10);
794         info(udev, "initialize max_childs to %u\n", max_childs);
795
796         while (!udev_exit) {
797                 sigset_t blocked_mask, orig_mask;
798                 struct pollfd pfd[4];
799                 struct pollfd *ctrl_poll, *monitor_poll, *inotify_poll = NULL;
800                 int nfds = 0;
801                 int fdcount;
802
803                 sigfillset(&blocked_mask);
804                 sigprocmask(SIG_SETMASK, &blocked_mask, &orig_mask);
805                 if (signal_received) {
806                         sigprocmask(SIG_SETMASK, &orig_mask, NULL);
807                         goto handle_signals;
808                 }
809
810                 ctrl_poll = &pfd[nfds++];
811                 ctrl_poll->fd = udev_ctrl_get_fd(udev_ctrl);
812                 ctrl_poll->events = POLLIN;
813
814                 monitor_poll = &pfd[nfds++];
815                 monitor_poll->fd = udev_monitor_get_fd(kernel_monitor);
816                 monitor_poll->events = POLLIN;
817
818                 if (inotify_fd >= 0) {
819                         inotify_poll = &pfd[nfds++];
820                         inotify_poll->fd = inotify_fd;
821                         inotify_poll->events = POLLIN;
822                 }
823
824                 fdcount = ppoll(pfd, nfds, NULL, &orig_mask);
825                 sigprocmask(SIG_SETMASK, &orig_mask, NULL);
826                 if (fdcount < 0) {
827                         if (errno == EINTR)
828                                 goto handle_signals;
829                         err(udev, "error in select: %m\n");
830                         continue;
831                 }
832
833                 /* get control message */
834                 if (ctrl_poll->revents & POLLIN)
835                         handle_ctrl_msg(udev_ctrl);
836
837                 /* get kernel uevent */
838                 if (monitor_poll->revents & POLLIN) {
839                         struct udev_device *dev;
840
841                         dev = udev_monitor_receive_device(kernel_monitor);
842                         if (dev != NULL) {
843                                 struct udev_event *event;
844
845                                 event = udev_event_new(dev);
846                                 if (event != NULL)
847                                         event_queue_insert(event);
848                                 else
849                                         udev_device_unref(dev);
850                         }
851                 }
852
853                 /* rules directory inotify watch */
854                 if (inotify_poll && (inotify_poll->revents & POLLIN))
855                         handle_inotify(udev);
856
857 handle_signals:
858                 signal_received = 0;
859
860                 /* rules changed, set by inotify or a HUP signal */
861                 if (reload_config) {
862                         struct udev_rules *rules_new;
863
864                         reload_config = 0;
865                         rules_new = udev_rules_new(udev, resolve_names);
866                         if (rules_new != NULL) {
867                                 udev_rules_unref(rules);
868                                 rules = rules_new;
869                         }
870                 }
871
872                 if (sigchilds_waiting) {
873                         sigchilds_waiting = 0;
874                         reap_sigchilds();
875                 }
876
877                 if (run_exec_q) {
878                         run_exec_q = 0;
879                         if (!stop_exec_q)
880                                 event_queue_manager(udev);
881                 }
882
883                 if (settle_pid > 0) {
884                         kill(settle_pid, SIGUSR1);
885                         settle_pid = 0;
886                 }
887         }
888         udev_queue_export_cleanup(udev_queue_export);
889         rc = 0;
890 exit:
891
892         udev_queue_export_unref(udev_queue_export);
893         udev_rules_unref(rules);
894         udev_ctrl_unref(udev_ctrl);
895         if (inotify_fd >= 0)
896                 close(inotify_fd);
897         udev_monitor_unref(kernel_monitor);
898         udev_selinux_exit(udev);
899         udev_unref(udev);
900         logging_close();
901         return rc;
902 }