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)
79 va_start(args, format);
80 vsyslog(priority, format, args);
84 va_start(args, format);
85 vprintf(format, args);
93 static void asmlinkage udev_event_sig_handler(int signum)
95 if (signum == SIGALRM)
99 static int udev_event_process(struct udevd_uevent_msg *msg)
101 struct sigaction act;
102 struct udevice *udev;
106 /* set signal handlers */
107 memset(&act, 0x00, sizeof(act));
108 act.sa_handler = (void (*)(int)) udev_event_sig_handler;
109 sigemptyset (&act.sa_mask);
111 sigaction(SIGALRM, &act, NULL);
113 /* reset to default */
114 act.sa_handler = SIG_DFL;
115 sigaction(SIGINT, &act, NULL);
116 sigaction(SIGTERM, &act, NULL);
117 sigaction(SIGCHLD, &act, NULL);
118 sigaction(SIGHUP, &act, NULL);
120 /* trigger timeout to prevent hanging processes */
121 alarm(UDEV_ALARM_TIMEOUT);
123 /* reconstruct event environment from message */
124 for (i = 0; msg->envp[i]; i++)
125 putenv(msg->envp[i]);
127 udev = udev_device_init(NULL);
130 strlcpy(udev->action, msg->action, sizeof(udev->action));
131 sysfs_device_set_values(udev->dev, msg->devpath, msg->subsystem, msg->driver);
132 udev->devt = msg->devt;
134 retval = udev_device_event(&rules, udev);
136 /* run programs collected by RUN-key*/
137 if (retval == 0 && !udev->ignore_device && udev_run) {
138 struct name_entry *name_loop;
140 dbg("executing run list");
141 list_for_each_entry(name_loop, &udev->run_list, node) {
142 if (strncmp(name_loop->name, "socket:", strlen("socket:")) == 0)
143 pass_env_to_socket(&name_loop->name[strlen("socket:")], udev->dev->devpath, udev->action);
145 char program[PATH_SIZE];
147 strlcpy(program, name_loop->name, sizeof(program));
148 udev_rules_apply_format(udev, program, sizeof(program));
149 if (run_program(program, udev->dev->subsystem, NULL, 0, NULL,
150 (udev_log_priority >= LOG_INFO)))
156 udev_device_cleanup(udev);
166 static void export_event_state(struct udevd_uevent_msg *msg, enum event_state state)
168 char filename[PATH_SIZE];
169 char filename_failed[PATH_SIZE];
171 struct udevd_uevent_msg *loop_msg;
174 /* add location of queue files */
175 strlcpy(filename, udev_root, sizeof(filename));
176 strlcat(filename, "/", sizeof(filename));
177 start = strlcat(filename, EVENT_QUEUE_DIR"/", sizeof(filename));
178 strlcat(filename, msg->devpath, sizeof(filename));
179 path_encode(&filename[start], sizeof(filename) - start);
181 /* add location of failed files */
182 strlcpy(filename_failed, udev_root, sizeof(filename_failed));
183 strlcat(filename_failed, "/", sizeof(filename_failed));
184 start = strlcat(filename_failed, EVENT_FAILED_DIR"/", sizeof(filename_failed));
185 strlcat(filename_failed, msg->devpath, sizeof(filename_failed));
186 path_encode(&filename_failed[start], sizeof(filename) - start);
190 unlink(filename_failed);
191 delete_path(filename_failed);
192 create_path(filename);
193 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
199 unlink(filename_failed);
200 delete_path(filename_failed);
202 /* don't remove, if events for the same path are still pending */
203 list_for_each_entry(loop_msg, &running_list, node)
204 if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
207 list_for_each_entry(loop_msg, &exec_list, node)
208 if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
211 /* move failed events to the failed directory */
212 if (state == EVENT_FAILED) {
213 create_path(filename_failed);
214 rename(filename, filename_failed);
219 /* clean up the queue directory */
220 delete_path(filename);
226 static void msg_queue_delete(struct udevd_uevent_msg *msg)
228 list_del(&msg->node);
230 /* mark as failed, if add event returns non-zero */
231 if (msg->exitstatus && strcmp(msg->action, "add") == 0)
232 export_event_state(msg, EVENT_FAILED);
234 export_event_state(msg, EVENT_FINISHED);
239 static void udev_event_run(struct udevd_uevent_msg *msg)
248 close(uevent_netlink_sock);
252 close(signal_pipe[READ_END]);
253 close(signal_pipe[WRITE_END]);
256 logging_init("udevd-event");
257 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
259 retval = udev_event_process(msg);
260 info("seq %llu finished", msg->seqnum);
267 err("fork of child failed: %s", strerror(errno));
268 msg_queue_delete(msg);
271 /* get SIGCHLD in main loop */
272 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
273 msg->seqnum, pid, msg->action, msg->subsystem, time(NULL) - msg->queue_time);
278 static void msg_queue_insert(struct udevd_uevent_msg *msg)
280 char filename[PATH_SIZE];
283 msg->queue_time = time(NULL);
285 strlcpy(filename, udev_root, sizeof(filename));
286 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
287 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
292 len = sprintf(str, "%llu\n", msg->seqnum);
297 export_event_state(msg, EVENT_QUEUED);
299 /* run one event after the other in debug mode */
301 list_add_tail(&msg->node, &running_list);
303 waitpid(msg->pid, NULL, 0);
304 msg_queue_delete(msg);
308 /* run all events with a timeout set immediately */
309 if (msg->timeout != 0) {
310 list_add_tail(&msg->node, &running_list);
315 list_add_tail(&msg->node, &exec_list);
319 static int mem_size_mb(void)
327 f = open("/proc/meminfo", O_RDONLY);
331 len = read(f, buf, sizeof(buf)-1);
338 pos = strstr(buf, "MemTotal: ");
342 if (sscanf(pos, "MemTotal: %ld kB", &memsize) != 1)
345 return memsize / 1024;
348 static int cpu_count(void)
356 f = open("/proc/stat", O_RDONLY);
360 len = read(f, buf, sizeof(buf)-1);
366 pos = strstr(buf, "cpu");
370 while (pos != NULL) {
371 if (strncmp(pos, "cpu", 3) == 0 &&isdigit(pos[3]))
373 pos = strstr(&pos[3], "cpu");
381 static int running_processes(void)
389 f = open("/proc/stat", O_RDONLY);
393 len = read(f, buf, sizeof(buf)-1);
399 pos = strstr(buf, "procs_running ");
403 if (sscanf(pos, "procs_running %u", &running) != 1)
409 /* return the number of process es in our session, count only until limit */
410 static int running_processes_in_session(pid_t session, int limit)
416 dir = opendir("/proc");
420 /* read process info from /proc */
421 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
427 pid_t ppid, pgrp, sess;
430 if (!isdigit(dent->d_name[0]))
433 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
434 procdir[sizeof(procdir)-1] = '\0';
436 f = open(procdir, O_RDONLY);
440 len = read(f, line, sizeof(line)-1);
448 /* skip ugly program name */
449 pos = strrchr(line, ')') + 2;
453 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
456 /* count only processes in our session */
460 /* count only running, no sleeping processes */
465 if (limit > 0 && running >= limit)
473 static int compare_devpath(const char *running, const char *waiting)
477 for (i = 0; i < PATH_SIZE; i++) {
478 /* identical device event found */
479 if (running[i] == '\0' && waiting[i] == '\0')
482 /* parent device event found */
483 if (running[i] == '\0' && waiting[i] == '/')
486 /* child device event found */
487 if (running[i] == '/' && waiting[i] == '\0')
490 /* no matching event */
491 if (running[i] != waiting[i])
498 /* lookup event for identical, parent, child, or physical device */
499 static int devpath_busy(struct udevd_uevent_msg *msg, int limit)
501 struct udevd_uevent_msg *loop_msg;
502 int childs_count = 0;
504 /* check exec-queue which may still contain delayed events we depend on */
505 list_for_each_entry(loop_msg, &exec_list, node) {
506 /* skip ourself and all later events */
507 if (loop_msg->seqnum >= msg->seqnum)
510 /* check identical, parent, or child device event */
511 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
512 dbg("%llu, device event still pending %llu (%s)",
513 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
517 /* check physical device event (special case of parent) */
518 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
519 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
520 dbg("%llu, physical device event still pending %llu (%s)",
521 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
526 /* check runing-queue for still running events */
527 list_for_each_entry(loop_msg, &running_list, node) {
528 if (limit && childs_count++ > limit) {
529 dbg("%llu, maximum number (%i) of childs reached", msg->seqnum, childs_count);
533 /* check identical, parent, or child device event */
534 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
535 dbg("%llu, device event still running %llu (%s)",
536 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
540 /* check physical device event (special case of parent) */
541 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
542 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
543 dbg("%llu, physical device event still running %llu (%s)",
544 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
551 /* serializes events for the identical and parent and child devices */
552 static void msg_queue_manager(void)
554 struct udevd_uevent_msg *loop_msg;
555 struct udevd_uevent_msg *tmp_msg;
558 if (list_empty(&exec_list))
561 running = running_processes();
562 dbg("%d processes runnning on system", running);
564 running = max_childs_running;
566 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
567 /* check running processes in our session and possibly throttle */
568 if (running >= max_childs_running) {
569 running = running_processes_in_session(sid, max_childs_running+10);
570 dbg("at least %d processes running in session", running);
571 if (running >= max_childs_running) {
572 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
577 /* serialize and wait for parent or child events */
578 if (devpath_busy(loop_msg, max_childs) != 0) {
579 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
583 /* move event to run list */
584 list_move_tail(&loop_msg->node, &running_list);
585 udev_event_run(loop_msg);
587 dbg("moved seq %llu to running list", loop_msg->seqnum);
591 static struct udevd_uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
595 struct udevd_uevent_msg *msg;
596 char *physdevdriver_key = NULL;
600 msg = malloc(sizeof(struct udevd_uevent_msg) + buf_size);
603 memset(msg, 0x00, sizeof(struct udevd_uevent_msg) + buf_size);
605 /* copy environment buffer and reconstruct envp */
606 memcpy(msg->envbuf, buf, buf_size);
608 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
612 key = &msg->envbuf[bufpos];
613 keylen = strlen(key);
615 bufpos += keylen + 1;
616 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
618 /* remember some keys for further processing */
619 if (strncmp(key, "ACTION=", 7) == 0)
620 msg->action = &key[7];
621 else if (strncmp(key, "DEVPATH=", 8) == 0)
622 msg->devpath = &key[8];
623 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
624 msg->subsystem = &key[10];
625 else if (strncmp(key, "DRIVER=", 7) == 0)
626 msg->driver = &key[7];
627 else if (strncmp(key, "SEQNUM=", 7) == 0)
628 msg->seqnum = strtoull(&key[7], NULL, 10);
629 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
630 msg->physdevpath = &key[12];
631 else if (strncmp(key, "PHYSDEVDRIVER=", 14) == 0)
632 physdevdriver_key = key;
633 else if (strncmp(key, "MAJOR=", 6) == 0)
634 maj = strtoull(&key[6], NULL, 10);
635 else if (strncmp(key, "MINOR=", 6) == 0)
636 min = strtoull(&key[6], NULL, 10);
637 else if (strncmp(key, "TIMEOUT=", 8) == 0)
638 msg->timeout = strtoull(&key[8], NULL, 10);
640 msg->devt = makedev(maj, min);
641 msg->envp[i++] = "UDEVD_EVENT=1";
643 if (msg->driver == NULL && msg->physdevpath == NULL && physdevdriver_key != NULL) {
644 /* for older kernels DRIVER is empty for a bus device, export PHYSDEVDRIVER as DRIVER */
645 msg->envp[i++] = &physdevdriver_key[7];
646 msg->driver = &physdevdriver_key[14];
651 if (msg->devpath == NULL || msg->action == NULL) {
652 info("DEVPATH or ACTION missing, ignore message");
659 /* receive the udevd message from userspace */
660 static void get_ctrl_msg(void)
662 struct udevd_ctrl_msg ctrl_msg;
665 struct cmsghdr *cmsg;
668 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
672 memset(&ctrl_msg, 0x00, sizeof(struct udevd_ctrl_msg));
673 iov.iov_base = &ctrl_msg;
674 iov.iov_len = sizeof(struct udevd_ctrl_msg);
676 memset(&smsg, 0x00, sizeof(struct msghdr));
679 smsg.msg_control = cred_msg;
680 smsg.msg_controllen = sizeof(cred_msg);
682 size = recvmsg(udevd_sock, &smsg, 0);
685 err("unable to receive user udevd message: %s", strerror(errno));
688 cmsg = CMSG_FIRSTHDR(&smsg);
689 cred = (struct ucred *) CMSG_DATA(cmsg);
691 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
692 err("no sender credentials received, message ignored");
696 if (cred->uid != 0) {
697 err("sender uid=%i, message ignored", cred->uid);
701 if (strncmp(ctrl_msg.magic, UDEVD_CTRL_MAGIC, sizeof(UDEVD_CTRL_MAGIC)) != 0 ) {
702 err("message magic '%s' doesn't match, ignore it", ctrl_msg.magic);
706 switch (ctrl_msg.type) {
708 pos = strchr(ctrl_msg.buf, '=');
710 err("wrong key format '%s'", ctrl_msg.buf);
714 if (pos[1] == '\0') {
715 info("udevd message (ENV) received, unset '%s'", ctrl_msg.buf);
716 unsetenv(ctrl_msg.buf);
718 info("udevd message (ENV) received, set '%s=%s'", ctrl_msg.buf, &pos[1]);
719 setenv(ctrl_msg.buf, &pos[1], 1);
722 case UDEVD_CTRL_STOP_EXEC_QUEUE:
723 info("udevd message (STOP_EXEC_QUEUE) received");
726 case UDEVD_CTRL_START_EXEC_QUEUE:
727 info("udevd message (START_EXEC_QUEUE) received");
731 case UDEVD_CTRL_SET_LOG_LEVEL:
732 intval = (int *) ctrl_msg.buf;
733 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
734 udev_log_priority = *intval;
735 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
738 case UDEVD_CTRL_SET_MAX_CHILDS:
739 intval = (int *) ctrl_msg.buf;
740 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
741 max_childs = *intval;
743 case UDEVD_CTRL_SET_MAX_CHILDS_RUNNING:
744 intval = (int *) ctrl_msg.buf;
745 info("udevd message (UDEVD_SET_MAX_CHILDS_RUNNING) received, max_childs=%i", *intval);
746 max_childs_running = *intval;
748 case UDEVD_CTRL_RELOAD_RULES:
749 info("udevd message (RELOAD_RULES) received");
753 err("unknown control message type");
757 /* receive the kernel user event message and do some sanity checks */
758 static struct udevd_uevent_msg *get_netlink_msg(void)
760 struct udevd_uevent_msg *msg;
763 static char buffer[UEVENT_BUFFER_SIZE+512];
766 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
769 err("unable to receive kernel netlink message: %s", strerror(errno));
773 if ((size_t)size > sizeof(buffer)-1)
774 size = sizeof(buffer)-1;
776 dbg("uevent_size=%zi", size);
778 /* start of event payload */
779 bufpos = strlen(buffer)+1;
780 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
784 /* validate message */
785 pos = strchr(buffer, '@');
787 err("invalid uevent '%s'", buffer);
793 if (msg->action == NULL) {
794 info("no ACTION in payload found, skip event '%s'", buffer);
799 if (strcmp(msg->action, buffer) != 0) {
800 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
808 static void asmlinkage sig_handler(int signum)
816 /* set flag, then write to pipe if needed */
817 sigchilds_waiting = 1;
824 /* write to pipe, which will wakeup select() in our mainloop */
825 write(signal_pipe[WRITE_END], "", 1);
828 static void udev_done(int pid, int exitstatus)
830 /* find msg associated with pid and delete it */
831 struct udevd_uevent_msg *msg;
833 list_for_each_entry(msg, &running_list, node) {
834 if (msg->pid == pid) {
835 info("seq %llu, pid [%d] exit with %i, %ld seconds old", msg->seqnum, msg->pid,
836 exitstatus, time(NULL) - msg->queue_time);
837 msg->exitstatus = exitstatus;
838 msg_queue_delete(msg);
840 /* there may be events waiting with the same devpath */
847 static void reap_sigchilds(void)
853 pid = waitpid(-1, &status, WNOHANG);
856 if (WIFEXITED(status))
857 status = WEXITSTATUS(status);
858 else if (WIFSIGNALED(status))
859 status = WTERMSIG(status) + 128;
862 udev_done(pid, status);
866 static int init_udevd_socket(void)
868 struct sockaddr_un saddr;
870 const int feature_on = 1;
873 memset(&saddr, 0x00, sizeof(saddr));
874 saddr.sun_family = AF_LOCAL;
875 /* use abstract namespace for socket path */
876 strcpy(&saddr.sun_path[1], UDEVD_CTRL_SOCK_PATH);
877 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
879 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
880 if (udevd_sock == -1) {
881 err("error getting socket: %s", strerror(errno));
885 /* the bind takes care of ensuring only one copy running */
886 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
888 err("bind failed: %s", strerror(errno));
894 /* enable receiving of the sender credentials */
895 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
900 static int init_uevent_netlink_sock(void)
902 struct sockaddr_nl snl;
903 const int buffersize = 16 * 1024 * 1024;
906 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
907 snl.nl_family = AF_NETLINK;
908 snl.nl_pid = getpid();
911 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
912 if (uevent_netlink_sock == -1) {
913 err("error getting socket: %s", strerror(errno));
917 /* set receive buffersize */
918 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
920 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
922 err("bind failed: %s", strerror(errno));
923 close(uevent_netlink_sock);
924 uevent_netlink_sock = -1;
930 static void export_initial_seqnum(void)
932 char filename[PATH_SIZE];
937 strlcpy(filename, sysfs_path, sizeof(filename));
938 strlcat(filename, "/kernel/uevent_seqnum", sizeof(filename));
939 fd = open(filename, O_RDONLY);
941 len = read(fd, seqnum, sizeof(seqnum)-1);
945 strcpy(seqnum, "0\n");
948 strlcpy(filename, udev_root, sizeof(filename));
949 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
950 create_path(filename);
951 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
953 write(fd, seqnum, len);
958 int main(int argc, char *argv[], char *envp[])
962 struct sigaction act;
967 static const struct option options[] = {
968 { "daemon", 0, NULL, 'd' },
969 { "debug-trace", 0, NULL, 't' },
970 { "verbose", 0, NULL, 'v' },
971 { "help", 0, NULL, 'h' },
972 { "version", 0, NULL, 'V' },
978 logging_init("udevd");
981 dbg("version %s", UDEV_VERSION);
983 /* parse commandline options */
985 option = getopt_long(argc, argv, "dtvhV", options, NULL);
998 if (udev_log_priority < LOG_INFO)
999 udev_log_priority = LOG_INFO;
1002 printf("Usage: udevd [--help] [--daemon] [--debug-trace] [--verbose] [--version]\n");
1005 printf("%s\n", UDEV_VERSION);
1012 if (getuid() != 0) {
1013 fprintf(stderr, "root privileges required\n");
1014 err("root privileges required");
1018 /* make sure std{in,out,err} fd's are in a sane state */
1019 fd = open("/dev/null", O_RDWR);
1021 fprintf(stderr, "cannot open /dev/null\n");
1022 err("cannot open /dev/null");
1024 if (fd > STDIN_FILENO)
1025 dup2(fd, STDIN_FILENO);
1026 if (write(STDOUT_FILENO, 0, 0) < 0)
1027 dup2(fd, STDOUT_FILENO);
1028 if (write(STDERR_FILENO, 0, 0) < 0)
1029 dup2(fd, STDERR_FILENO);
1031 /* init sockets to receive events */
1032 if (init_udevd_socket() < 0) {
1033 if (errno == EADDRINUSE) {
1034 fprintf(stderr, "another udev daemon already running\n");
1035 err("another udev daemon already running");
1038 fprintf(stderr, "error initializing udevd socket\n");
1039 err("error initializing udevd socket");
1045 if (init_uevent_netlink_sock() < 0) {
1046 fprintf(stderr, "error initializing netlink socket\n");
1047 err("error initializing netlink socket");
1052 /* setup signal handler pipe */
1053 retval = pipe(signal_pipe);
1055 err("error getting pipes: %s", strerror(errno));
1059 retval = fcntl(signal_pipe[READ_END], F_GETFL, 0);
1061 err("error fcntl on read pipe: %s", strerror(errno));
1064 retval = fcntl(signal_pipe[READ_END], F_SETFL, retval | O_NONBLOCK);
1066 err("error fcntl on read pipe: %s", strerror(errno));
1070 retval = fcntl(signal_pipe[WRITE_END], F_GETFL, 0);
1072 err("error fcntl on write pipe: %s", strerror(errno));
1075 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, retval | O_NONBLOCK);
1077 err("error fcntl on write pipe: %s", strerror(errno));
1081 /* parse the rules and keep them in memory */
1083 udev_rules_init(&rules, 1);
1085 export_initial_seqnum();
1093 dbg("daemonized fork running");
1096 err("fork of daemon failed: %s", strerror(errno));
1100 dbg("child [%u] running, parent exits", pid);
1106 /* redirect std{out,err} fd's */
1108 dup2(fd, STDOUT_FILENO);
1109 dup2(fd, STDERR_FILENO);
1110 if (fd > STDERR_FILENO)
1113 /* set scheduling priority for the daemon */
1114 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
1119 /* become session leader */
1121 dbg("our session is %d", sid);
1123 /* OOM_DISABLE == -17 */
1124 fd = open("/proc/self/oom_adj", O_RDWR);
1126 err("error disabling OOM: %s", strerror(errno));
1128 write(fd, "-17", 3);
1132 /* set signal handlers */
1133 memset(&act, 0x00, sizeof(struct sigaction));
1134 act.sa_handler = (void (*)(int)) sig_handler;
1135 sigemptyset(&act.sa_mask);
1136 act.sa_flags = SA_RESTART;
1137 sigaction(SIGINT, &act, NULL);
1138 sigaction(SIGTERM, &act, NULL);
1139 sigaction(SIGCHLD, &act, NULL);
1140 sigaction(SIGHUP, &act, NULL);
1142 /* watch rules directory */
1143 inotify_fd = inotify_init();
1144 if (inotify_fd >= 0)
1145 inotify_add_watch(inotify_fd, udev_rules_dir, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1146 else if (errno == ENOSYS)
1147 err("the kernel does not support inotify, udevd can't monitor configuration file changes");
1149 err("inotify_init failed: %s", strerror(errno));
1151 /* maximum limit of forked childs */
1152 value = getenv("UDEVD_MAX_CHILDS");
1154 max_childs = strtoul(value, NULL, 10);
1156 int memsize = mem_size_mb();
1158 max_childs = 128 + (memsize / 4);
1160 max_childs = UDEVD_MAX_CHILDS;
1162 info("initialize max_childs to %u", max_childs);
1164 /* start to throttle forking if maximum number of _running_ childs is reached */
1165 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
1167 max_childs_running = strtoull(value, NULL, 10);
1169 int cpus = cpu_count();
1171 max_childs_running = 8 + (8 * cpus);
1173 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
1175 info("initialize max_childs_running to %u", max_childs_running);
1177 /* clear environment for forked event processes */
1180 /* export log_priority , as called programs may want to follow that setting */
1181 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
1187 maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
1188 maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
1189 maxfd = UDEV_MAX(maxfd, inotify_fd);
1191 while (!udev_exit) {
1192 struct udevd_uevent_msg *msg;
1196 FD_SET(signal_pipe[READ_END], &readfds);
1197 FD_SET(udevd_sock, &readfds);
1198 FD_SET(uevent_netlink_sock, &readfds);
1199 if (inotify_fd >= 0)
1200 FD_SET(inotify_fd, &readfds);
1202 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
1205 err("error in select: %s", strerror(errno));
1209 /* get control message */
1210 if (FD_ISSET(udevd_sock, &readfds))
1213 /* get netlink message */
1214 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
1215 msg = get_netlink_msg();
1217 msg_queue_insert(msg);
1220 /* received a signal, clear our notification pipe */
1221 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
1224 read(signal_pipe[READ_END], &buf, sizeof(buf));
1227 /* rules directory inotify watch */
1228 if ((inotify_fd >= 0) && FD_ISSET(inotify_fd, &readfds)) {
1231 /* discard all possible events, we can just reload the config */
1232 if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes) {
1236 buf = malloc(nbytes);
1238 err("error getting buffer for inotify, disable watching");
1242 read(inotify_fd, buf, nbytes);
1247 /* rules changed, set by inotify or a HUP signal */
1248 if (reload_config) {
1250 udev_rules_cleanup(&rules);
1251 udev_rules_init(&rules, 1);
1254 /* forked child has returned */
1255 if (sigchilds_waiting) {
1256 sigchilds_waiting = 0;
1263 msg_queue_manager();
1269 udev_rules_cleanup(&rules);
1273 if (signal_pipe[READ_END] >= 0)
1274 close(signal_pipe[READ_END]);
1275 if (signal_pipe[WRITE_END] >= 0)
1276 close(signal_pipe[WRITE_END]);
1278 if (udevd_sock >= 0)
1280 if (inotify_fd >= 0)
1282 if (uevent_netlink_sock >= 0)
1283 close(uevent_netlink_sock);