init.c revision a866695ebe3a396a0ec411c0f99e0921c74c0fd2
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <stdio.h>
18#include <stdlib.h>
19#include <string.h>
20#include <unistd.h>
21#include <fcntl.h>
22#include <ctype.h>
23#include <signal.h>
24#include <sys/wait.h>
25#include <sys/mount.h>
26#include <sys/stat.h>
27#include <sys/poll.h>
28#include <time.h>
29#include <errno.h>
30#include <stdarg.h>
31#include <mtd/mtd-user.h>
32#include <sys/types.h>
33#include <sys/socket.h>
34#include <sys/un.h>
35#include <sys/reboot.h>
36
37#include <cutils/sockets.h>
38#include <cutils/iosched_policy.h>
39#include <termios.h>
40
41#include <sys/system_properties.h>
42
43#include "devices.h"
44#include "init.h"
45#include "property_service.h"
46#include "bootchart.h"
47#include "keychords.h"
48
49static int property_triggers_enabled = 0;
50
51#if BOOTCHART
52static int   bootchart_count;
53#endif
54
55static char console[32];
56static char serialno[32];
57static char bootmode[32];
58static char baseband[32];
59static char carrier[32];
60static char bootloader[32];
61static char hardware[32];
62static unsigned revision = 0;
63static char qemu[32];
64
65static void notify_service_state(const char *name, const char *state)
66{
67    char pname[PROP_NAME_MAX];
68    int len = strlen(name);
69    if ((len + 10) > PROP_NAME_MAX)
70        return;
71    snprintf(pname, sizeof(pname), "init.svc.%s", name);
72    property_set(pname, state);
73}
74
75static int have_console;
76static char *console_name = "/dev/console";
77static time_t process_needs_restart;
78
79static const char *ENV[32];
80
81/* add_environment - add "key=value" to the current environment */
82int add_environment(const char *key, const char *val)
83{
84    int n;
85
86    for (n = 0; n < 31; n++) {
87        if (!ENV[n]) {
88            size_t len = strlen(key) + strlen(val) + 2;
89            char *entry = malloc(len);
90            snprintf(entry, len, "%s=%s", key, val);
91            ENV[n] = entry;
92            return 0;
93        }
94    }
95
96    return 1;
97}
98
99static void zap_stdio(void)
100{
101    int fd;
102    fd = open("/dev/null", O_RDWR);
103    dup2(fd, 0);
104    dup2(fd, 1);
105    dup2(fd, 2);
106    close(fd);
107}
108
109static void open_console()
110{
111    int fd;
112    if ((fd = open(console_name, O_RDWR)) < 0) {
113        fd = open("/dev/null", O_RDWR);
114    }
115    dup2(fd, 0);
116    dup2(fd, 1);
117    dup2(fd, 2);
118    close(fd);
119}
120
121/*
122 * gettime() - returns the time in seconds of the system's monotonic clock or
123 * zero on error.
124 */
125static time_t gettime(void)
126{
127    struct timespec ts;
128    int ret;
129
130    ret = clock_gettime(CLOCK_MONOTONIC, &ts);
131    if (ret < 0) {
132        ERROR("clock_gettime(CLOCK_MONOTONIC) failed: %s\n", strerror(errno));
133        return 0;
134    }
135
136    return ts.tv_sec;
137}
138
139static void publish_socket(const char *name, int fd)
140{
141    char key[64] = ANDROID_SOCKET_ENV_PREFIX;
142    char val[64];
143
144    strlcpy(key + sizeof(ANDROID_SOCKET_ENV_PREFIX) - 1,
145            name,
146            sizeof(key) - sizeof(ANDROID_SOCKET_ENV_PREFIX));
147    snprintf(val, sizeof(val), "%d", fd);
148    add_environment(key, val);
149
150    /* make sure we don't close-on-exec */
151    fcntl(fd, F_SETFD, 0);
152}
153
154void service_start(struct service *svc, const char *dynamic_args)
155{
156    struct stat s;
157    pid_t pid;
158    int needs_console;
159    int n;
160
161        /* starting a service removes it from the disabled
162         * state and immediately takes it out of the restarting
163         * state if it was in there
164         */
165    svc->flags &= (~(SVC_DISABLED|SVC_RESTARTING));
166    svc->time_started = 0;
167
168        /* running processes require no additional work -- if
169         * they're in the process of exiting, we've ensured
170         * that they will immediately restart on exit, unless
171         * they are ONESHOT
172         */
173    if (svc->flags & SVC_RUNNING) {
174        return;
175    }
176
177    needs_console = (svc->flags & SVC_CONSOLE) ? 1 : 0;
178    if (needs_console && (!have_console)) {
179        ERROR("service '%s' requires console\n", svc->name);
180        svc->flags |= SVC_DISABLED;
181        return;
182    }
183
184    if (stat(svc->args[0], &s) != 0) {
185        ERROR("cannot find '%s', disabling '%s'\n", svc->args[0], svc->name);
186        svc->flags |= SVC_DISABLED;
187        return;
188    }
189
190    if ((!(svc->flags & SVC_ONESHOT)) && dynamic_args) {
191        ERROR("service '%s' must be one-shot to use dynamic args, disabling\n",
192               svc->args[0]);
193        svc->flags |= SVC_DISABLED;
194        return;
195    }
196
197    NOTICE("starting '%s'\n", svc->name);
198
199    pid = fork();
200
201    if (pid == 0) {
202        struct socketinfo *si;
203        struct svcenvinfo *ei;
204        char tmp[32];
205        int fd, sz;
206
207        get_property_workspace(&fd, &sz);
208        sprintf(tmp, "%d,%d", dup(fd), sz);
209        add_environment("ANDROID_PROPERTY_WORKSPACE", tmp);
210
211        for (ei = svc->envvars; ei; ei = ei->next)
212            add_environment(ei->name, ei->value);
213
214        for (si = svc->sockets; si; si = si->next) {
215            int s = create_socket(si->name,
216                                  !strcmp(si->type, "dgram") ?
217                                  SOCK_DGRAM : SOCK_STREAM,
218                                  si->perm, si->uid, si->gid);
219            if (s >= 0) {
220                publish_socket(si->name, s);
221            }
222        }
223
224        if (svc->ioprio_class != IoSchedClass_NONE) {
225            if (android_set_ioprio(getpid(), svc->ioprio_class, svc->ioprio_pri)) {
226                ERROR("Failed to set pid %d ioprio = %d,%d: %s\n",
227                      getpid(), svc->ioprio_class, svc->ioprio_pri, strerror(errno));
228            }
229        }
230
231        if (needs_console) {
232            setsid();
233            open_console();
234        } else {
235            zap_stdio();
236        }
237
238#if 0
239        for (n = 0; svc->args[n]; n++) {
240            INFO("args[%d] = '%s'\n", n, svc->args[n]);
241        }
242        for (n = 0; ENV[n]; n++) {
243            INFO("env[%d] = '%s'\n", n, ENV[n]);
244        }
245#endif
246
247        setpgid(0, getpid());
248
249    /* as requested, set our gid, supplemental gids, and uid */
250        if (svc->gid) {
251            setgid(svc->gid);
252        }
253        if (svc->nr_supp_gids) {
254            setgroups(svc->nr_supp_gids, svc->supp_gids);
255        }
256        if (svc->uid) {
257            setuid(svc->uid);
258        }
259
260        if (!dynamic_args) {
261            if (execve(svc->args[0], (char**) svc->args, (char**) ENV) < 0) {
262                ERROR("cannot execve('%s'): %s\n", svc->args[0], strerror(errno));
263            }
264        } else {
265            char *arg_ptrs[SVC_MAXARGS+1];
266            int arg_idx = svc->nargs;
267            char *tmp = strdup(dynamic_args);
268            char *next = tmp;
269            char *bword;
270
271            /* Copy the static arguments */
272            memcpy(arg_ptrs, svc->args, (svc->nargs * sizeof(char *)));
273
274            while((bword = strsep(&next, " "))) {
275                arg_ptrs[arg_idx++] = bword;
276                if (arg_idx == SVC_MAXARGS)
277                    break;
278            }
279            arg_ptrs[arg_idx] = '\0';
280            execve(svc->args[0], (char**) arg_ptrs, (char**) ENV);
281        }
282        _exit(127);
283    }
284
285    if (pid < 0) {
286        ERROR("failed to start '%s'\n", svc->name);
287        svc->pid = 0;
288        return;
289    }
290
291    svc->time_started = gettime();
292    svc->pid = pid;
293    svc->flags |= SVC_RUNNING;
294
295    notify_service_state(svc->name, "running");
296}
297
298void service_stop(struct service *svc)
299{
300        /* we are no longer running, nor should we
301         * attempt to restart
302         */
303    svc->flags &= (~(SVC_RUNNING|SVC_RESTARTING));
304
305        /* if the service has not yet started, prevent
306         * it from auto-starting with its class
307         */
308    svc->flags |= SVC_DISABLED;
309
310    if (svc->pid) {
311        NOTICE("service '%s' is being killed\n", svc->name);
312        kill(-svc->pid, SIGTERM);
313        notify_service_state(svc->name, "stopping");
314    } else {
315        notify_service_state(svc->name, "stopped");
316    }
317}
318
319void property_changed(const char *name, const char *value)
320{
321    if (property_triggers_enabled) {
322        queue_property_triggers(name, value);
323        drain_action_queue();
324    }
325}
326
327#define CRITICAL_CRASH_THRESHOLD    4       /* if we crash >4 times ... */
328#define CRITICAL_CRASH_WINDOW       (4*60)  /* ... in 4 minutes, goto recovery*/
329
330static int wait_for_one_process(int block)
331{
332    pid_t pid;
333    int status;
334    struct service *svc;
335    struct socketinfo *si;
336    time_t now;
337    struct listnode *node;
338    struct command *cmd;
339
340    while ( (pid = waitpid(-1, &status, block ? 0 : WNOHANG)) == -1 && errno == EINTR );
341    if (pid <= 0) return -1;
342    INFO("waitpid returned pid %d, status = %08x\n", pid, status);
343
344    svc = service_find_by_pid(pid);
345    if (!svc) {
346        ERROR("untracked pid %d exited\n", pid);
347        return 0;
348    }
349
350    NOTICE("process '%s', pid %d exited\n", svc->name, pid);
351
352    if (!(svc->flags & SVC_ONESHOT)) {
353        kill(-pid, SIGKILL);
354        NOTICE("process '%s' killing any children in process group\n", svc->name);
355    }
356
357    /* remove any sockets we may have created */
358    for (si = svc->sockets; si; si = si->next) {
359        char tmp[128];
360        snprintf(tmp, sizeof(tmp), ANDROID_SOCKET_DIR"/%s", si->name);
361        unlink(tmp);
362    }
363
364    svc->pid = 0;
365    svc->flags &= (~SVC_RUNNING);
366
367        /* oneshot processes go into the disabled state on exit */
368    if (svc->flags & SVC_ONESHOT) {
369        svc->flags |= SVC_DISABLED;
370    }
371
372        /* disabled processes do not get restarted automatically */
373    if (svc->flags & SVC_DISABLED) {
374        notify_service_state(svc->name, "stopped");
375        return 0;
376    }
377
378    now = gettime();
379    if (svc->flags & SVC_CRITICAL) {
380        if (svc->time_crashed + CRITICAL_CRASH_WINDOW >= now) {
381            if (++svc->nr_crashed > CRITICAL_CRASH_THRESHOLD) {
382                ERROR("critical process '%s' exited %d times in %d minutes; "
383                      "rebooting into recovery mode\n", svc->name,
384                      CRITICAL_CRASH_THRESHOLD, CRITICAL_CRASH_WINDOW / 60);
385                sync();
386                __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2,
387                         LINUX_REBOOT_CMD_RESTART2, "recovery");
388                return 0;
389            }
390        } else {
391            svc->time_crashed = now;
392            svc->nr_crashed = 1;
393        }
394    }
395
396    svc->flags |= SVC_RESTARTING;
397
398    /* Execute all onrestart commands for this service. */
399    list_for_each(node, &svc->onrestart.commands) {
400        cmd = node_to_item(node, struct command, clist);
401        cmd->func(cmd->nargs, cmd->args);
402    }
403    notify_service_state(svc->name, "restarting");
404    return 0;
405}
406
407static void restart_service_if_needed(struct service *svc)
408{
409    time_t next_start_time = svc->time_started + 5;
410
411    if (next_start_time <= gettime()) {
412        svc->flags &= (~SVC_RESTARTING);
413        service_start(svc, NULL);
414        return;
415    }
416
417    if ((next_start_time < process_needs_restart) ||
418        (process_needs_restart == 0)) {
419        process_needs_restart = next_start_time;
420    }
421}
422
423static void restart_processes()
424{
425    process_needs_restart = 0;
426    service_for_each_flags(SVC_RESTARTING,
427                           restart_service_if_needed);
428}
429
430static int signal_fd = -1;
431
432static void sigchld_handler(int s)
433{
434    write(signal_fd, &s, 1);
435}
436
437static void msg_start(const char *name)
438{
439    struct service *svc;
440    char *tmp = NULL;
441    char *args = NULL;
442
443    if (!strchr(name, ':'))
444        svc = service_find_by_name(name);
445    else {
446        tmp = strdup(name);
447        args = strchr(tmp, ':');
448        *args = '\0';
449        args++;
450
451        svc = service_find_by_name(tmp);
452    }
453
454    if (svc) {
455        service_start(svc, args);
456    } else {
457        ERROR("no such service '%s'\n", name);
458    }
459    if (tmp)
460        free(tmp);
461}
462
463static void msg_stop(const char *name)
464{
465    struct service *svc = service_find_by_name(name);
466
467    if (svc) {
468        service_stop(svc);
469    } else {
470        ERROR("no such service '%s'\n", name);
471    }
472}
473
474void handle_control_message(const char *msg, const char *arg)
475{
476    if (!strcmp(msg,"start")) {
477        msg_start(arg);
478    } else if (!strcmp(msg,"stop")) {
479        msg_stop(arg);
480    } else {
481        ERROR("unknown control msg '%s'\n", msg);
482    }
483}
484
485static void import_kernel_nv(char *name, int in_qemu)
486{
487    char *value = strchr(name, '=');
488
489    if (value == 0) return;
490    *value++ = 0;
491    if (*name == 0) return;
492
493    if (!in_qemu)
494    {
495        /* on a real device, white-list the kernel options */
496        if (!strcmp(name,"qemu")) {
497            strlcpy(qemu, value, sizeof(qemu));
498        } else if (!strcmp(name,"androidboot.console")) {
499            strlcpy(console, value, sizeof(console));
500        } else if (!strcmp(name,"androidboot.mode")) {
501            strlcpy(bootmode, value, sizeof(bootmode));
502        } else if (!strcmp(name,"androidboot.serialno")) {
503            strlcpy(serialno, value, sizeof(serialno));
504        } else if (!strcmp(name,"androidboot.baseband")) {
505            strlcpy(baseband, value, sizeof(baseband));
506        } else if (!strcmp(name,"androidboot.carrier")) {
507            strlcpy(carrier, value, sizeof(carrier));
508        } else if (!strcmp(name,"androidboot.bootloader")) {
509            strlcpy(bootloader, value, sizeof(bootloader));
510        } else if (!strcmp(name,"androidboot.hardware")) {
511            strlcpy(hardware, value, sizeof(hardware));
512        } else {
513            qemu_cmdline(name, value);
514        }
515    } else {
516        /* in the emulator, export any kernel option with the
517         * ro.kernel. prefix */
518        char  buff[32];
519        int   len = snprintf( buff, sizeof(buff), "ro.kernel.%s", name );
520        if (len < (int)sizeof(buff)) {
521            property_set( buff, value );
522        }
523    }
524}
525
526static void import_kernel_cmdline(int in_qemu)
527{
528    char cmdline[1024];
529    char *ptr;
530    int fd;
531
532    fd = open("/proc/cmdline", O_RDONLY);
533    if (fd >= 0) {
534        int n = read(fd, cmdline, 1023);
535        if (n < 0) n = 0;
536
537        /* get rid of trailing newline, it happens */
538        if (n > 0 && cmdline[n-1] == '\n') n--;
539
540        cmdline[n] = 0;
541        close(fd);
542    } else {
543        cmdline[0] = 0;
544    }
545
546    ptr = cmdline;
547    while (ptr && *ptr) {
548        char *x = strchr(ptr, ' ');
549        if (x != 0) *x++ = 0;
550        import_kernel_nv(ptr, in_qemu);
551        ptr = x;
552    }
553
554        /* don't expose the raw commandline to nonpriv processes */
555    chmod("/proc/cmdline", 0440);
556}
557
558static void get_hardware_name(void)
559{
560    char data[1024];
561    int fd, n;
562    char *x, *hw, *rev;
563
564    /* Hardware string was provided on kernel command line */
565    if (hardware[0])
566        return;
567
568    fd = open("/proc/cpuinfo", O_RDONLY);
569    if (fd < 0) return;
570
571    n = read(fd, data, 1023);
572    close(fd);
573    if (n < 0) return;
574
575    data[n] = 0;
576    hw = strstr(data, "\nHardware");
577    rev = strstr(data, "\nRevision");
578
579    if (hw) {
580        x = strstr(hw, ": ");
581        if (x) {
582            x += 2;
583            n = 0;
584            while (*x && !isspace(*x)) {
585                hardware[n++] = tolower(*x);
586                x++;
587                if (n == 31) break;
588            }
589            hardware[n] = 0;
590        }
591    }
592
593    if (rev) {
594        x = strstr(rev, ": ");
595        if (x) {
596            revision = strtoul(x + 2, 0, 16);
597        }
598    }
599}
600
601void drain_action_queue(void)
602{
603    struct listnode *node;
604    struct command *cmd;
605    struct action *act;
606    int ret;
607
608    while ((act = action_remove_queue_head())) {
609        INFO("processing action %p (%s)\n", act, act->name);
610        list_for_each(node, &act->commands) {
611            cmd = node_to_item(node, struct command, clist);
612            ret = cmd->func(cmd->nargs, cmd->args);
613            INFO("command '%s' r=%d\n", cmd->args[0], ret);
614        }
615    }
616}
617
618void open_devnull_stdio(void)
619{
620    int fd;
621    static const char *name = "/dev/__null__";
622    if (mknod(name, S_IFCHR | 0600, (1 << 8) | 3) == 0) {
623        fd = open(name, O_RDWR);
624        unlink(name);
625        if (fd >= 0) {
626            dup2(fd, 0);
627            dup2(fd, 1);
628            dup2(fd, 2);
629            if (fd > 2) {
630                close(fd);
631            }
632            return;
633        }
634    }
635
636    exit(1);
637}
638
639int main(int argc, char **argv)
640{
641    int device_fd = -1;
642    int property_set_fd = -1;
643    int signal_recv_fd = -1;
644    int fd_count;
645    int s[2];
646    int fd;
647    struct sigaction act;
648    char tmp[PROP_VALUE_MAX];
649    struct pollfd ufds[4];
650    char *tmpdev;
651    char* debuggable;
652
653    act.sa_handler = sigchld_handler;
654    act.sa_flags = SA_NOCLDSTOP;
655    act.sa_mask = 0;
656    act.sa_restorer = NULL;
657    sigaction(SIGCHLD, &act, 0);
658
659    /* clear the umask */
660    umask(0);
661
662        /* Get the basic filesystem setup we need put
663         * together in the initramdisk on / and then we'll
664         * let the rc file figure out the rest.
665         */
666    mkdir("/dev", 0755);
667    mkdir("/proc", 0755);
668    mkdir("/sys", 0755);
669
670    mount("tmpfs", "/dev", "tmpfs", 0, "mode=0755");
671    mkdir("/dev/pts", 0755);
672    mkdir("/dev/socket", 0755);
673    mount("devpts", "/dev/pts", "devpts", 0, NULL);
674    mount("proc", "/proc", "proc", 0, NULL);
675    mount("sysfs", "/sys", "sysfs", 0, NULL);
676
677        /* We must have some place other than / to create the
678         * device nodes for kmsg and null, otherwise we won't
679         * be able to remount / read-only later on.
680         * Now that tmpfs is mounted on /dev, we can actually
681         * talk to the outside world.
682         */
683    open_devnull_stdio();
684    log_init();
685
686    INFO("reading config file\n");
687    parse_config_file("/init.rc");
688
689    /* pull the kernel commandline and ramdisk properties file in */
690    qemu_init();
691    import_kernel_cmdline(0);
692
693    get_hardware_name();
694    snprintf(tmp, sizeof(tmp), "/init.%s.rc", hardware);
695    parse_config_file(tmp);
696
697    action_for_each_trigger("early-init", action_add_queue_tail);
698    drain_action_queue();
699
700    INFO("device init\n");
701    device_fd = device_init();
702
703    property_init();
704
705    // only listen for keychords if ro.debuggable is true
706    keychord_init();
707
708    if (console[0]) {
709        snprintf(tmp, sizeof(tmp), "/dev/%s", console);
710        console_name = strdup(tmp);
711    }
712
713    fd = open(console_name, O_RDWR);
714    if (fd >= 0)
715        have_console = 1;
716    close(fd);
717
718    if( load_565rle_image(INIT_IMAGE_FILE) ) {
719    fd = open("/dev/tty0", O_WRONLY);
720    if (fd >= 0) {
721        const char *msg;
722            msg = "\n"
723        "\n"
724        "\n"
725        "\n"
726        "\n"
727        "\n"
728        "\n"  // console is 40 cols x 30 lines
729        "\n"
730        "\n"
731        "\n"
732        "\n"
733        "\n"
734        "\n"
735        "\n"
736        "             A N D R O I D ";
737        write(fd, msg, strlen(msg));
738        close(fd);
739    }
740    }
741
742    if (qemu[0])
743        import_kernel_cmdline(1);
744
745    if (!strcmp(bootmode,"factory"))
746        property_set("ro.factorytest", "1");
747    else if (!strcmp(bootmode,"factory2"))
748        property_set("ro.factorytest", "2");
749    else
750        property_set("ro.factorytest", "0");
751
752    property_set("ro.serialno", serialno[0] ? serialno : "");
753    property_set("ro.bootmode", bootmode[0] ? bootmode : "unknown");
754    property_set("ro.baseband", baseband[0] ? baseband : "unknown");
755    property_set("ro.carrier", carrier[0] ? carrier : "unknown");
756    property_set("ro.bootloader", bootloader[0] ? bootloader : "unknown");
757
758    property_set("ro.hardware", hardware);
759    snprintf(tmp, PROP_VALUE_MAX, "%d", revision);
760    property_set("ro.revision", tmp);
761
762        /* execute all the boot actions to get us started */
763    action_for_each_trigger("init", action_add_queue_tail);
764    action_for_each_trigger("early-fs", action_add_queue_tail);
765    action_for_each_trigger("fs", action_add_queue_tail);
766    action_for_each_trigger("post-fs", action_add_queue_tail);
767    drain_action_queue();
768
769        /* read any property files on system or data and
770         * fire up the property service.  This must happen
771         * after the ro.foo properties are set above so
772         * that /data/local.prop cannot interfere with them.
773         */
774    property_set_fd = start_property_service();
775
776    /* create a signalling mechanism for the sigchld handler */
777    if (socketpair(AF_UNIX, SOCK_STREAM, 0, s) == 0) {
778        signal_fd = s[0];
779        signal_recv_fd = s[1];
780        fcntl(s[0], F_SETFD, FD_CLOEXEC);
781        fcntl(s[0], F_SETFL, O_NONBLOCK);
782        fcntl(s[1], F_SETFD, FD_CLOEXEC);
783        fcntl(s[1], F_SETFL, O_NONBLOCK);
784    }
785
786    /* make sure we actually have all the pieces we need */
787    if ((device_fd < 0) ||
788        (property_set_fd < 0) ||
789        (signal_recv_fd < 0)) {
790        ERROR("init startup failure\n");
791        return 1;
792    }
793
794    /* execute all the boot actions to get us started */
795    action_for_each_trigger("early-boot", action_add_queue_tail);
796    action_for_each_trigger("boot", action_add_queue_tail);
797    drain_action_queue();
798
799        /* run all property triggers based on current state of the properties */
800    queue_all_property_triggers();
801    drain_action_queue();
802
803        /* enable property triggers */
804    property_triggers_enabled = 1;
805
806    ufds[0].fd = device_fd;
807    ufds[0].events = POLLIN;
808    ufds[1].fd = property_set_fd;
809    ufds[1].events = POLLIN;
810    ufds[2].fd = signal_recv_fd;
811    ufds[2].events = POLLIN;
812    fd_count = 3;
813
814    if (get_keychord_fd() > 0) {
815        ufds[3].fd = get_keychord_fd();
816        ufds[3].events = POLLIN;
817        fd_count++;
818    } else {
819        ufds[3].events = 0;
820        ufds[3].revents = 0;
821    }
822
823#if BOOTCHART
824    bootchart_count = bootchart_init();
825    if (bootchart_count < 0) {
826        ERROR("bootcharting init failure\n");
827    } else if (bootchart_count > 0) {
828        NOTICE("bootcharting started (period=%d ms)\n", bootchart_count*BOOTCHART_POLLING_MS);
829    } else {
830        NOTICE("bootcharting ignored\n");
831    }
832#endif
833
834    for(;;) {
835        int nr, i, timeout = -1;
836
837        for (i = 0; i < fd_count; i++)
838            ufds[i].revents = 0;
839
840        drain_action_queue();
841        restart_processes();
842
843        if (process_needs_restart) {
844            timeout = (process_needs_restart - gettime()) * 1000;
845            if (timeout < 0)
846                timeout = 0;
847        }
848
849#if BOOTCHART
850        if (bootchart_count > 0) {
851            if (timeout < 0 || timeout > BOOTCHART_POLLING_MS)
852                timeout = BOOTCHART_POLLING_MS;
853            if (bootchart_step() < 0 || --bootchart_count == 0) {
854                bootchart_finish();
855                bootchart_count = 0;
856            }
857        }
858#endif
859        nr = poll(ufds, fd_count, timeout);
860        if (nr <= 0)
861            continue;
862
863        if (ufds[2].revents == POLLIN) {
864            /* we got a SIGCHLD - reap and restart as needed */
865            read(signal_recv_fd, tmp, sizeof(tmp));
866            while (!wait_for_one_process(0))
867                ;
868            continue;
869        }
870
871        if (ufds[0].revents == POLLIN)
872            handle_device_fd(device_fd);
873
874        if (ufds[1].revents == POLLIN)
875            handle_property_set_fd(property_set_fd);
876        if (ufds[3].revents == POLLIN)
877            handle_keychord();
878    }
879
880    return 0;
881}
882