2 * Copyright (C) 2004-2006 Kay Sievers <kay.sievers@vrfy.org>
3 * Copyright (C) 2004 Chris Friesen <chris_friesen@sympatico.ca>
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation version 2 of the License.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
33 #include <sys/select.h>
35 #include <sys/types.h>
36 #include <sys/socket.h>
39 #include <sys/ioctl.h>
40 #include <linux/types.h>
41 #include <linux/netlink.h>
44 #include "udev_rules.h"
46 #include "udev_selinux.h"
48 static int debug_trace;
51 static struct udev_rules rules;
52 static int udevd_sock = -1;
53 static int uevent_netlink_sock = -1;
54 static int inotify_fd = -1;
57 static int signal_pipe[2] = {-1, -1};
58 static volatile int sigchilds_waiting;
59 static volatile int udev_exit;
60 static volatile int reload_config;
61 static int run_exec_q;
62 static int stop_exec_q;
63 static int max_childs;
64 static int max_childs_running;
65 static char udev_log[32];
67 static LIST_HEAD(exec_list);
68 static LIST_HEAD(running_list);
72 void log_message(int priority, const char *format, ...)
76 if (priority > udev_log_priority)
80 printf("[%d] ", (int) getpid());
81 va_start(args, format);
82 vprintf(format, args);
86 va_start(args, format);
87 vsyslog(priority, format, args);
94 static void asmlinkage udev_event_sig_handler(int signum)
96 if (signum == SIGALRM)
100 static int udev_event_process(struct udevd_uevent_msg *msg)
102 struct sigaction act;
103 struct udevice *udev;
107 /* set signal handlers */
108 memset(&act, 0x00, sizeof(act));
109 act.sa_handler = (void (*)(int)) udev_event_sig_handler;
110 sigemptyset (&act.sa_mask);
112 sigaction(SIGALRM, &act, NULL);
114 /* reset to default */
115 act.sa_handler = SIG_DFL;
116 sigaction(SIGINT, &act, NULL);
117 sigaction(SIGTERM, &act, NULL);
118 sigaction(SIGCHLD, &act, NULL);
119 sigaction(SIGHUP, &act, NULL);
121 /* trigger timeout to prevent hanging processes */
122 alarm(UDEV_ALARM_TIMEOUT);
124 /* reconstruct event environment from message */
125 for (i = 0; msg->envp[i]; i++)
126 putenv(msg->envp[i]);
128 udev = udev_device_init(NULL);
131 strlcpy(udev->action, msg->action, sizeof(udev->action));
132 sysfs_device_set_values(udev->dev, msg->devpath, msg->subsystem, msg->driver);
133 udev->devt = msg->devt;
135 retval = udev_device_event(&rules, udev);
137 /* run programs collected by RUN-key*/
138 if (retval == 0 && !udev->ignore_device && udev_run)
139 retval = udev_rules_run(udev);
141 udev_device_cleanup(udev);
151 static void export_event_state(struct udevd_uevent_msg *msg, enum event_state state)
153 char filename[PATH_SIZE];
154 char filename_failed[PATH_SIZE];
156 struct udevd_uevent_msg *loop_msg;
159 /* add location of queue files */
160 strlcpy(filename, udev_root, sizeof(filename));
161 strlcat(filename, "/", sizeof(filename));
162 start = strlcat(filename, EVENT_QUEUE_DIR"/", sizeof(filename));
163 strlcat(filename, msg->devpath, sizeof(filename));
164 path_encode(&filename[start], sizeof(filename) - start);
166 /* add location of failed files */
167 strlcpy(filename_failed, udev_root, sizeof(filename_failed));
168 strlcat(filename_failed, "/", sizeof(filename_failed));
169 start = strlcat(filename_failed, EVENT_FAILED_DIR"/", sizeof(filename_failed));
170 strlcat(filename_failed, msg->devpath, sizeof(filename_failed));
171 path_encode(&filename_failed[start], sizeof(filename) - start);
175 unlink(filename_failed);
176 delete_path(filename_failed);
177 create_path(filename);
178 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
184 unlink(filename_failed);
185 delete_path(filename_failed);
187 /* don't remove, if events for the same path are still pending */
188 list_for_each_entry(loop_msg, &running_list, node)
189 if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
192 list_for_each_entry(loop_msg, &exec_list, node)
193 if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
196 /* move failed events to the failed directory */
197 if (state == EVENT_FAILED) {
198 create_path(filename_failed);
199 rename(filename, filename_failed);
204 /* clean up the queue directory */
205 delete_path(filename);
211 static void msg_queue_delete(struct udevd_uevent_msg *msg)
213 list_del(&msg->node);
215 /* mark as failed, if add event returns non-zero */
216 if (msg->exitstatus && strcmp(msg->action, "add") == 0)
217 export_event_state(msg, EVENT_FAILED);
219 export_event_state(msg, EVENT_FINISHED);
224 static void udev_event_run(struct udevd_uevent_msg *msg)
233 close(uevent_netlink_sock);
237 close(signal_pipe[READ_END]);
238 close(signal_pipe[WRITE_END]);
241 logging_init("udevd-event");
242 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
244 retval = udev_event_process(msg);
245 info("seq %llu finished with %i", msg->seqnum, retval);
252 err("fork of child failed: %s", strerror(errno));
253 msg_queue_delete(msg);
256 /* get SIGCHLD in main loop */
257 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
258 msg->seqnum, pid, msg->action, msg->subsystem, time(NULL) - msg->queue_time);
263 static void msg_queue_insert(struct udevd_uevent_msg *msg)
265 char filename[PATH_SIZE];
268 msg->queue_time = time(NULL);
270 strlcpy(filename, udev_root, sizeof(filename));
271 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
272 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
277 len = sprintf(str, "%llu\n", msg->seqnum);
282 export_event_state(msg, EVENT_QUEUED);
284 /* run one event after the other in debug mode */
286 list_add_tail(&msg->node, &running_list);
288 waitpid(msg->pid, NULL, 0);
289 msg_queue_delete(msg);
293 /* run all events with a timeout set immediately */
294 if (msg->timeout != 0) {
295 list_add_tail(&msg->node, &running_list);
300 list_add_tail(&msg->node, &exec_list);
304 static int mem_size_mb(void)
308 long int memsize = -1;
310 f = fopen("/proc/meminfo", "r");
314 while (fgets(buf, sizeof(buf), f) != NULL) {
317 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
318 memsize = value / 1024;
327 static int cpu_count(void)
333 f = fopen("/proc/stat", "r");
337 while (fgets(buf, sizeof(buf), f) != NULL) {
338 if (strncmp(buf, "cpu", 3) == 0 && isdigit(buf[3]))
348 static int running_processes(void)
354 f = fopen("/proc/stat", "r");
358 while (fgets(buf, sizeof(buf), f) != NULL) {
361 if (sscanf(buf, "procs_running %u", &value) == 1) {
371 /* return the number of process es in our session, count only until limit */
372 static int running_processes_in_session(pid_t session, int limit)
378 dir = opendir("/proc");
382 /* read process info from /proc */
383 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
389 pid_t ppid, pgrp, sess;
392 if (!isdigit(dent->d_name[0]))
395 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
396 procdir[sizeof(procdir)-1] = '\0';
398 f = open(procdir, O_RDONLY);
402 len = read(f, line, sizeof(line)-1);
410 /* skip ugly program name */
411 pos = strrchr(line, ')') + 2;
415 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
418 /* count only processes in our session */
422 /* count only running, no sleeping processes */
427 if (limit > 0 && running >= limit)
435 static int compare_devpath(const char *running, const char *waiting)
439 for (i = 0; i < PATH_SIZE; i++) {
440 /* identical device event found */
441 if (running[i] == '\0' && waiting[i] == '\0')
444 /* parent device event found */
445 if (running[i] == '\0' && waiting[i] == '/')
448 /* child device event found */
449 if (running[i] == '/' && waiting[i] == '\0')
452 /* no matching event */
453 if (running[i] != waiting[i])
460 /* lookup event for identical, parent, child, or physical device */
461 static int devpath_busy(struct udevd_uevent_msg *msg, int limit)
463 struct udevd_uevent_msg *loop_msg;
464 int childs_count = 0;
466 /* check exec-queue which may still contain delayed events we depend on */
467 list_for_each_entry(loop_msg, &exec_list, node) {
468 /* skip ourself and all later events */
469 if (loop_msg->seqnum >= msg->seqnum)
472 /* check identical, parent, or child device event */
473 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
474 dbg("%llu, device event still pending %llu (%s)",
475 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
479 /* check physical device event (special case of parent) */
480 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
481 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
482 dbg("%llu, physical device event still pending %llu (%s)",
483 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
488 /* check runing-queue for still running events */
489 list_for_each_entry(loop_msg, &running_list, node) {
490 if (limit && childs_count++ > limit) {
491 dbg("%llu, maximum number (%i) of childs reached", msg->seqnum, childs_count);
495 /* check identical, parent, or child device event */
496 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
497 dbg("%llu, device event still running %llu (%s)",
498 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
502 /* check physical device event (special case of parent) */
503 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
504 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
505 dbg("%llu, physical device event still running %llu (%s)",
506 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
513 /* serializes events for the identical and parent and child devices */
514 static void msg_queue_manager(void)
516 struct udevd_uevent_msg *loop_msg;
517 struct udevd_uevent_msg *tmp_msg;
520 if (list_empty(&exec_list))
523 running = running_processes();
524 dbg("%d processes runnning on system", running);
526 running = max_childs_running;
528 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
529 /* check running processes in our session and possibly throttle */
530 if (running >= max_childs_running) {
531 running = running_processes_in_session(sid, max_childs_running+10);
532 dbg("at least %d processes running in session", running);
533 if (running >= max_childs_running) {
534 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
539 /* serialize and wait for parent or child events */
540 if (devpath_busy(loop_msg, max_childs) != 0) {
541 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
545 /* move event to run list */
546 list_move_tail(&loop_msg->node, &running_list);
547 udev_event_run(loop_msg);
549 dbg("moved seq %llu to running list", loop_msg->seqnum);
553 static struct udevd_uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
557 struct udevd_uevent_msg *msg;
558 char *physdevdriver_key = NULL;
562 msg = malloc(sizeof(struct udevd_uevent_msg) + buf_size);
565 memset(msg, 0x00, sizeof(struct udevd_uevent_msg) + buf_size);
567 /* copy environment buffer and reconstruct envp */
568 memcpy(msg->envbuf, buf, buf_size);
570 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
574 key = &msg->envbuf[bufpos];
575 keylen = strlen(key);
577 bufpos += keylen + 1;
578 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
580 /* remember some keys for further processing */
581 if (strncmp(key, "ACTION=", 7) == 0)
582 msg->action = &key[7];
583 else if (strncmp(key, "DEVPATH=", 8) == 0)
584 msg->devpath = &key[8];
585 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
586 msg->subsystem = &key[10];
587 else if (strncmp(key, "DRIVER=", 7) == 0)
588 msg->driver = &key[7];
589 else if (strncmp(key, "SEQNUM=", 7) == 0)
590 msg->seqnum = strtoull(&key[7], NULL, 10);
591 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
592 msg->physdevpath = &key[12];
593 else if (strncmp(key, "PHYSDEVDRIVER=", 14) == 0)
594 physdevdriver_key = key;
595 else if (strncmp(key, "MAJOR=", 6) == 0)
596 maj = strtoull(&key[6], NULL, 10);
597 else if (strncmp(key, "MINOR=", 6) == 0)
598 min = strtoull(&key[6], NULL, 10);
599 else if (strncmp(key, "TIMEOUT=", 8) == 0)
600 msg->timeout = strtoull(&key[8], NULL, 10);
602 msg->devt = makedev(maj, min);
603 msg->envp[i++] = "UDEVD_EVENT=1";
605 if (msg->driver == NULL && msg->physdevpath == NULL && physdevdriver_key != NULL) {
606 /* for older kernels DRIVER is empty for a bus device, export PHYSDEVDRIVER as DRIVER */
607 msg->envp[i++] = &physdevdriver_key[7];
608 msg->driver = &physdevdriver_key[14];
613 if (msg->devpath == NULL || msg->action == NULL) {
614 info("DEVPATH or ACTION missing, ignore message");
621 /* receive the udevd message from userspace */
622 static void get_ctrl_msg(void)
624 struct udevd_ctrl_msg ctrl_msg;
627 struct cmsghdr *cmsg;
630 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
634 memset(&ctrl_msg, 0x00, sizeof(struct udevd_ctrl_msg));
635 iov.iov_base = &ctrl_msg;
636 iov.iov_len = sizeof(struct udevd_ctrl_msg);
638 memset(&smsg, 0x00, sizeof(struct msghdr));
641 smsg.msg_control = cred_msg;
642 smsg.msg_controllen = sizeof(cred_msg);
644 size = recvmsg(udevd_sock, &smsg, 0);
647 err("unable to receive user udevd message: %s", strerror(errno));
650 cmsg = CMSG_FIRSTHDR(&smsg);
651 cred = (struct ucred *) CMSG_DATA(cmsg);
653 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
654 err("no sender credentials received, message ignored");
658 if (cred->uid != 0) {
659 err("sender uid=%i, message ignored", cred->uid);
663 if (strncmp(ctrl_msg.magic, UDEVD_CTRL_MAGIC, sizeof(UDEVD_CTRL_MAGIC)) != 0 ) {
664 err("message magic '%s' doesn't match, ignore it", ctrl_msg.magic);
668 switch (ctrl_msg.type) {
670 pos = strchr(ctrl_msg.buf, '=');
672 err("wrong key format '%s'", ctrl_msg.buf);
676 if (pos[1] == '\0') {
677 info("udevd message (ENV) received, unset '%s'", ctrl_msg.buf);
678 unsetenv(ctrl_msg.buf);
680 info("udevd message (ENV) received, set '%s=%s'", ctrl_msg.buf, &pos[1]);
681 setenv(ctrl_msg.buf, &pos[1], 1);
684 case UDEVD_CTRL_STOP_EXEC_QUEUE:
685 info("udevd message (STOP_EXEC_QUEUE) received");
688 case UDEVD_CTRL_START_EXEC_QUEUE:
689 info("udevd message (START_EXEC_QUEUE) received");
693 case UDEVD_CTRL_SET_LOG_LEVEL:
694 intval = (int *) ctrl_msg.buf;
695 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
696 udev_log_priority = *intval;
697 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
700 case UDEVD_CTRL_SET_MAX_CHILDS:
701 intval = (int *) ctrl_msg.buf;
702 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
703 max_childs = *intval;
705 case UDEVD_CTRL_SET_MAX_CHILDS_RUNNING:
706 intval = (int *) ctrl_msg.buf;
707 info("udevd message (UDEVD_SET_MAX_CHILDS_RUNNING) received, max_childs=%i", *intval);
708 max_childs_running = *intval;
710 case UDEVD_CTRL_RELOAD_RULES:
711 info("udevd message (RELOAD_RULES) received");
715 err("unknown control message type");
719 /* receive the kernel user event message and do some sanity checks */
720 static struct udevd_uevent_msg *get_netlink_msg(void)
722 struct udevd_uevent_msg *msg;
725 static char buffer[UEVENT_BUFFER_SIZE+512];
728 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
731 err("unable to receive kernel netlink message: %s", strerror(errno));
735 if ((size_t)size > sizeof(buffer)-1)
736 size = sizeof(buffer)-1;
738 dbg("uevent_size=%zi", size);
740 /* start of event payload */
741 bufpos = strlen(buffer)+1;
742 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
746 /* validate message */
747 pos = strchr(buffer, '@');
749 err("invalid uevent '%s'", buffer);
755 if (msg->action == NULL) {
756 info("no ACTION in payload found, skip event '%s'", buffer);
761 if (strcmp(msg->action, buffer) != 0) {
762 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
770 static void asmlinkage sig_handler(int signum)
778 /* set flag, then write to pipe if needed */
779 sigchilds_waiting = 1;
786 /* write to pipe, which will wakeup select() in our mainloop */
787 write(signal_pipe[WRITE_END], "", 1);
790 static void udev_done(int pid, int exitstatus)
792 /* find msg associated with pid and delete it */
793 struct udevd_uevent_msg *msg;
795 list_for_each_entry(msg, &running_list, node) {
796 if (msg->pid == pid) {
797 info("seq %llu, pid [%d] exit with %i, %ld seconds old", msg->seqnum, msg->pid,
798 exitstatus, time(NULL) - msg->queue_time);
799 msg->exitstatus = exitstatus;
800 msg_queue_delete(msg);
802 /* there may be events waiting with the same devpath */
809 static void reap_sigchilds(void)
815 pid = waitpid(-1, &status, WNOHANG);
818 if (WIFEXITED(status))
819 status = WEXITSTATUS(status);
820 else if (WIFSIGNALED(status))
821 status = WTERMSIG(status) + 128;
824 udev_done(pid, status);
828 static int init_udevd_socket(void)
830 struct sockaddr_un saddr;
832 const int feature_on = 1;
835 memset(&saddr, 0x00, sizeof(saddr));
836 saddr.sun_family = AF_LOCAL;
837 /* use abstract namespace for socket path */
838 strcpy(&saddr.sun_path[1], UDEVD_CTRL_SOCK_PATH);
839 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
841 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
842 if (udevd_sock == -1) {
843 err("error getting socket: %s", strerror(errno));
847 /* the bind takes care of ensuring only one copy running */
848 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
850 err("bind failed: %s", strerror(errno));
856 /* enable receiving of the sender credentials */
857 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
862 static int init_uevent_netlink_sock(void)
864 struct sockaddr_nl snl;
865 const int buffersize = 16 * 1024 * 1024;
868 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
869 snl.nl_family = AF_NETLINK;
870 snl.nl_pid = getpid();
873 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
874 if (uevent_netlink_sock == -1) {
875 err("error getting socket: %s", strerror(errno));
879 /* set receive buffersize */
880 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
882 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
884 err("bind failed: %s", strerror(errno));
885 close(uevent_netlink_sock);
886 uevent_netlink_sock = -1;
892 static void export_initial_seqnum(void)
894 char filename[PATH_SIZE];
899 strlcpy(filename, sysfs_path, sizeof(filename));
900 strlcat(filename, "/kernel/uevent_seqnum", sizeof(filename));
901 fd = open(filename, O_RDONLY);
903 len = read(fd, seqnum, sizeof(seqnum)-1);
907 strcpy(seqnum, "0\n");
910 strlcpy(filename, udev_root, sizeof(filename));
911 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
912 create_path(filename);
913 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
915 write(fd, seqnum, len);
920 int main(int argc, char *argv[], char *envp[])
924 struct sigaction act;
929 static const struct option options[] = {
930 { "daemon", 0, NULL, 'd' },
931 { "debug-trace", 0, NULL, 't' },
932 { "verbose", 0, NULL, 'v' },
933 { "help", 0, NULL, 'h' },
934 { "version", 0, NULL, 'V' },
940 logging_init("udevd");
943 dbg("version %s", UDEV_VERSION);
946 option = getopt_long(argc, argv, "dtvhV", options, NULL);
959 if (udev_log_priority < LOG_INFO)
960 udev_log_priority = LOG_INFO;
963 printf("Usage: udevd [--help] [--daemon] [--debug-trace] [--verbose] [--version]\n");
966 printf("%s\n", UDEV_VERSION);
974 fprintf(stderr, "root privileges required\n");
975 err("root privileges required");
979 /* make sure std{in,out,err} fd's are in a sane state */
980 fd = open("/dev/null", O_RDWR);
982 fprintf(stderr, "cannot open /dev/null\n");
983 err("cannot open /dev/null");
985 if (fd > STDIN_FILENO)
986 dup2(fd, STDIN_FILENO);
987 if (write(STDOUT_FILENO, 0, 0) < 0)
988 dup2(fd, STDOUT_FILENO);
989 if (write(STDERR_FILENO, 0, 0) < 0)
990 dup2(fd, STDERR_FILENO);
992 /* init sockets to receive events */
993 if (init_udevd_socket() < 0) {
994 if (errno == EADDRINUSE) {
995 fprintf(stderr, "another udev daemon already running\n");
996 err("another udev daemon already running");
999 fprintf(stderr, "error initializing udevd socket\n");
1000 err("error initializing udevd socket");
1006 if (init_uevent_netlink_sock() < 0) {
1007 fprintf(stderr, "error initializing netlink socket\n");
1008 err("error initializing netlink socket");
1013 /* setup signal handler pipe */
1014 retval = pipe(signal_pipe);
1016 err("error getting pipes: %s", strerror(errno));
1020 retval = fcntl(signal_pipe[READ_END], F_GETFL, 0);
1022 err("error fcntl on read pipe: %s", strerror(errno));
1025 retval = fcntl(signal_pipe[READ_END], F_SETFL, retval | O_NONBLOCK);
1027 err("error fcntl on read pipe: %s", strerror(errno));
1031 retval = fcntl(signal_pipe[WRITE_END], F_GETFL, 0);
1033 err("error fcntl on write pipe: %s", strerror(errno));
1036 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, retval | O_NONBLOCK);
1038 err("error fcntl on write pipe: %s", strerror(errno));
1042 /* parse the rules and keep them in memory */
1044 udev_rules_init(&rules, 1);
1046 export_initial_seqnum();
1054 dbg("daemonized fork running");
1057 err("fork of daemon failed: %s", strerror(errno));
1061 dbg("child [%u] running, parent exits", pid);
1067 /* redirect std{out,err} fd's */
1069 dup2(fd, STDOUT_FILENO);
1070 dup2(fd, STDERR_FILENO);
1071 if (fd > STDERR_FILENO)
1074 /* set scheduling priority for the daemon */
1075 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
1080 /* become session leader */
1082 dbg("our session is %d", sid);
1084 /* OOM_DISABLE == -17 */
1085 fd = open("/proc/self/oom_adj", O_RDWR);
1087 err("error disabling OOM: %s", strerror(errno));
1089 write(fd, "-17", 3);
1093 /* set signal handlers */
1094 memset(&act, 0x00, sizeof(struct sigaction));
1095 act.sa_handler = (void (*)(int)) sig_handler;
1096 sigemptyset(&act.sa_mask);
1097 act.sa_flags = SA_RESTART;
1098 sigaction(SIGINT, &act, NULL);
1099 sigaction(SIGTERM, &act, NULL);
1100 sigaction(SIGCHLD, &act, NULL);
1101 sigaction(SIGHUP, &act, NULL);
1103 /* watch rules directory */
1104 inotify_fd = inotify_init();
1105 if (inotify_fd >= 0) {
1106 char filename[PATH_MAX];
1108 inotify_add_watch(inotify_fd, udev_rules_dir, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1110 /* watch dynamic rules directory */
1111 strlcpy(filename, udev_root, sizeof(filename));
1112 strlcat(filename, "/"RULES_DYN_DIR, sizeof(filename));
1113 inotify_add_watch(inotify_fd, filename, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1114 } else if (errno == ENOSYS)
1115 err("the kernel does not support inotify, udevd can't monitor rules file changes");
1117 err("inotify_init failed: %s", strerror(errno));
1119 /* maximum limit of forked childs */
1120 value = getenv("UDEVD_MAX_CHILDS");
1122 max_childs = strtoul(value, NULL, 10);
1124 int memsize = mem_size_mb();
1126 max_childs = 128 + (memsize / 4);
1128 max_childs = UDEVD_MAX_CHILDS;
1130 info("initialize max_childs to %u", max_childs);
1132 /* start to throttle forking if maximum number of _running_ childs is reached */
1133 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
1135 max_childs_running = strtoull(value, NULL, 10);
1137 int cpus = cpu_count();
1139 max_childs_running = 8 + (8 * cpus);
1141 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
1143 info("initialize max_childs_running to %u", max_childs_running);
1145 /* clear environment for forked event processes */
1148 /* export log_priority , as called programs may want to follow that setting */
1149 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
1155 maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
1156 maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
1157 maxfd = UDEV_MAX(maxfd, inotify_fd);
1159 while (!udev_exit) {
1160 struct udevd_uevent_msg *msg;
1164 FD_SET(signal_pipe[READ_END], &readfds);
1165 FD_SET(udevd_sock, &readfds);
1166 FD_SET(uevent_netlink_sock, &readfds);
1167 if (inotify_fd >= 0)
1168 FD_SET(inotify_fd, &readfds);
1170 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
1173 err("error in select: %s", strerror(errno));
1177 /* get control message */
1178 if (FD_ISSET(udevd_sock, &readfds))
1181 /* get netlink message */
1182 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
1183 msg = get_netlink_msg();
1185 msg_queue_insert(msg);
1188 /* received a signal, clear our notification pipe */
1189 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
1192 read(signal_pipe[READ_END], &buf, sizeof(buf));
1195 /* rules directory inotify watch */
1196 if ((inotify_fd >= 0) && FD_ISSET(inotify_fd, &readfds)) {
1199 /* discard all possible events, we can just reload the config */
1200 if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes > 0) {
1204 buf = malloc(nbytes);
1206 err("error getting buffer for inotify, disable watching");
1210 read(inotify_fd, buf, nbytes);
1215 /* rules changed, set by inotify or a HUP signal */
1216 if (reload_config) {
1218 udev_rules_cleanup(&rules);
1219 udev_rules_init(&rules, 1);
1222 /* forked child has returned */
1223 if (sigchilds_waiting) {
1224 sigchilds_waiting = 0;
1231 msg_queue_manager();
1237 udev_rules_cleanup(&rules);
1241 if (signal_pipe[READ_END] >= 0)
1242 close(signal_pipe[READ_END]);
1243 if (signal_pipe[WRITE_END] >= 0)
1244 close(signal_pipe[WRITE_END]);
1246 if (udevd_sock >= 0)
1248 if (inotify_fd >= 0)
1250 if (uevent_netlink_sock >= 0)
1251 close(uevent_netlink_sock);