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 /* returns still running task for the same device, its parent or its physical device */
499 static int running_with_devpath(struct udevd_uevent_msg *msg, int limit)
501 struct udevd_uevent_msg *loop_msg;
502 int childs_count = 0;
504 list_for_each_entry(loop_msg, &running_list, node) {
505 if (limit && childs_count++ > limit) {
506 dbg("%llu, maximum number (%i) of child reached", msg->seqnum, childs_count);
510 /* return running parent/child device event */
511 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
512 dbg("%llu, child device event still running %llu (%s)",
513 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
517 /* return running physical device event */
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 running %llu (%s)",
521 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
529 /* exec queue management routine executes the events and serializes events in the same sequence */
530 static void msg_queue_manager(void)
532 struct udevd_uevent_msg *loop_msg;
533 struct udevd_uevent_msg *tmp_msg;
536 if (list_empty(&exec_list))
539 running = running_processes();
540 dbg("%d processes runnning on system", running);
542 running = max_childs_running;
544 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
545 /* check running processes in our session and possibly throttle */
546 if (running >= max_childs_running) {
547 running = running_processes_in_session(sid, max_childs_running+10);
548 dbg("at least %d processes running in session", running);
549 if (running >= max_childs_running) {
550 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
555 /* don't run two processes for the same devpath and wait for the parent*/
556 if (running_with_devpath(loop_msg, max_childs)) {
557 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
561 /* move event to run list */
562 list_move_tail(&loop_msg->node, &running_list);
563 udev_event_run(loop_msg);
565 dbg("moved seq %llu to running list", loop_msg->seqnum);
569 static struct udevd_uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
573 struct udevd_uevent_msg *msg;
574 char *physdevdriver_key = NULL;
578 msg = malloc(sizeof(struct udevd_uevent_msg) + buf_size);
581 memset(msg, 0x00, sizeof(struct udevd_uevent_msg) + buf_size);
583 /* copy environment buffer and reconstruct envp */
584 memcpy(msg->envbuf, buf, buf_size);
586 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
590 key = &msg->envbuf[bufpos];
591 keylen = strlen(key);
593 bufpos += keylen + 1;
594 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
596 /* remember some keys for further processing */
597 if (strncmp(key, "ACTION=", 7) == 0)
598 msg->action = &key[7];
599 else if (strncmp(key, "DEVPATH=", 8) == 0)
600 msg->devpath = &key[8];
601 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
602 msg->subsystem = &key[10];
603 else if (strncmp(key, "DRIVER=", 7) == 0)
604 msg->driver = &key[7];
605 else if (strncmp(key, "SEQNUM=", 7) == 0)
606 msg->seqnum = strtoull(&key[7], NULL, 10);
607 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
608 msg->physdevpath = &key[12];
609 else if (strncmp(key, "PHYSDEVDRIVER=", 14) == 0)
610 physdevdriver_key = key;
611 else if (strncmp(key, "MAJOR=", 6) == 0)
612 maj = strtoull(&key[6], NULL, 10);
613 else if (strncmp(key, "MINOR=", 6) == 0)
614 min = strtoull(&key[6], NULL, 10);
615 else if (strncmp(key, "TIMEOUT=", 8) == 0)
616 msg->timeout = strtoull(&key[8], NULL, 10);
618 msg->devt = makedev(maj, min);
619 msg->envp[i++] = "UDEVD_EVENT=1";
621 if (msg->driver == NULL && msg->physdevpath == NULL && physdevdriver_key != NULL) {
622 /* for older kernels DRIVER is empty for a bus device, export PHYSDEVDRIVER as DRIVER */
623 msg->envp[i++] = &physdevdriver_key[7];
624 msg->driver = &physdevdriver_key[14];
629 if (msg->devpath == NULL || msg->action == NULL) {
630 info("DEVPATH or ACTION missing, ignore message");
637 /* receive the udevd message from userspace */
638 static void get_ctrl_msg(void)
640 struct udevd_ctrl_msg ctrl_msg;
643 struct cmsghdr *cmsg;
646 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
649 memset(&ctrl_msg, 0x00, sizeof(struct udevd_ctrl_msg));
650 iov.iov_base = &ctrl_msg;
651 iov.iov_len = sizeof(struct udevd_ctrl_msg);
653 memset(&smsg, 0x00, sizeof(struct msghdr));
656 smsg.msg_control = cred_msg;
657 smsg.msg_controllen = sizeof(cred_msg);
659 size = recvmsg(udevd_sock, &smsg, 0);
662 err("unable to receive user udevd message: %s", strerror(errno));
665 cmsg = CMSG_FIRSTHDR(&smsg);
666 cred = (struct ucred *) CMSG_DATA(cmsg);
668 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
669 err("no sender credentials received, message ignored");
673 if (cred->uid != 0) {
674 err("sender uid=%i, message ignored", cred->uid);
678 if (strncmp(ctrl_msg.magic, UDEVD_CTRL_MAGIC, sizeof(UDEVD_CTRL_MAGIC)) != 0 ) {
679 err("message magic '%s' doesn't match, ignore it", ctrl_msg.magic);
683 switch (ctrl_msg.type) {
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);
945 /* parse commandline options */
947 option = getopt_long(argc, argv, "dtvhV", options, NULL);
960 if (udev_log_priority < LOG_INFO)
961 udev_log_priority = LOG_INFO;
964 printf("Usage: udevd [--help] [--daemon] [--debug-trace] [--verbose] [--version]\n");
967 printf("%s\n", UDEV_VERSION);
975 fprintf(stderr, "root privileges required\n");
976 err("root privileges required");
980 /* make sure std{in,out,err} fd's are in a sane state */
981 fd = open("/dev/null", O_RDWR);
983 fprintf(stderr, "cannot open /dev/null\n");
984 err("cannot open /dev/null");
986 if (fd > STDIN_FILENO)
987 dup2(fd, STDIN_FILENO);
988 if (write(STDOUT_FILENO, 0, 0) < 0)
989 dup2(fd, STDOUT_FILENO);
990 if (write(STDERR_FILENO, 0, 0) < 0)
991 dup2(fd, STDERR_FILENO);
993 /* init sockets to receive events */
994 if (init_udevd_socket() < 0) {
995 if (errno == EADDRINUSE) {
996 fprintf(stderr, "another udev daemon already running\n");
997 err("another udev daemon already running");
1000 fprintf(stderr, "error initializing udevd socket\n");
1001 err("error initializing udevd socket");
1007 if (init_uevent_netlink_sock() < 0) {
1008 fprintf(stderr, "error initializing netlink socket\n");
1009 err("error initializing netlink socket");
1014 /* setup signal handler pipe */
1015 retval = pipe(signal_pipe);
1017 err("error getting pipes: %s", strerror(errno));
1021 retval = fcntl(signal_pipe[READ_END], F_GETFL, 0);
1023 err("error fcntl on read pipe: %s", strerror(errno));
1026 retval = fcntl(signal_pipe[READ_END], F_SETFL, retval | O_NONBLOCK);
1028 err("error fcntl on read pipe: %s", strerror(errno));
1032 retval = fcntl(signal_pipe[WRITE_END], F_GETFL, 0);
1034 err("error fcntl on write pipe: %s", strerror(errno));
1037 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, retval | O_NONBLOCK);
1039 err("error fcntl on write pipe: %s", strerror(errno));
1043 /* parse the rules and keep them in memory */
1045 udev_rules_init(&rules, 1);
1047 export_initial_seqnum();
1055 dbg("daemonized fork running");
1058 err("fork of daemon failed: %s", strerror(errno));
1062 dbg("child [%u] running, parent exits", pid);
1068 /* redirect std{out,err} fd's */
1070 dup2(fd, STDOUT_FILENO);
1071 dup2(fd, STDERR_FILENO);
1072 if (fd > STDERR_FILENO)
1075 /* set scheduling priority for the daemon */
1076 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
1081 /* become session leader */
1083 dbg("our session is %d", sid);
1085 /* OOM_DISABLE == -17 */
1086 fd = open("/proc/self/oom_adj", O_RDWR);
1088 err("error disabling OOM: %s", strerror(errno));
1090 write(fd, "-17", 3);
1094 /* set signal handlers */
1095 memset(&act, 0x00, sizeof(struct sigaction));
1096 act.sa_handler = (void (*)(int)) sig_handler;
1097 sigemptyset(&act.sa_mask);
1098 act.sa_flags = SA_RESTART;
1099 sigaction(SIGINT, &act, NULL);
1100 sigaction(SIGTERM, &act, NULL);
1101 sigaction(SIGCHLD, &act, NULL);
1102 sigaction(SIGHUP, &act, NULL);
1104 /* watch rules directory */
1105 inotify_fd = inotify_init();
1106 if (inotify_fd >= 0)
1107 inotify_add_watch(inotify_fd, udev_rules_dir, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1108 else if (errno == ENOSYS)
1109 err("the kernel does not support inotify, udevd can't monitor configuration file changes");
1111 err("inotify_init failed: %s", strerror(errno));
1113 /* maximum limit of forked childs */
1114 value = getenv("UDEVD_MAX_CHILDS");
1116 max_childs = strtoul(value, NULL, 10);
1118 int memsize = mem_size_mb();
1120 max_childs = 128 + (memsize / 4);
1122 max_childs = UDEVD_MAX_CHILDS;
1124 info("initialize max_childs to %u", max_childs);
1126 /* start to throttle forking if maximum number of _running_ childs is reached */
1127 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
1129 max_childs_running = strtoull(value, NULL, 10);
1131 int cpus = cpu_count();
1133 max_childs_running = 8 + (8 * cpus);
1135 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
1137 info("initialize max_childs_running to %u", max_childs_running);
1139 /* clear environment for forked event processes */
1142 /* export log_priority , as called programs may want to follow that setting */
1143 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
1149 maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
1150 maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
1151 maxfd = UDEV_MAX(maxfd, inotify_fd);
1153 while (!udev_exit) {
1154 struct udevd_uevent_msg *msg;
1158 FD_SET(signal_pipe[READ_END], &readfds);
1159 FD_SET(udevd_sock, &readfds);
1160 FD_SET(uevent_netlink_sock, &readfds);
1161 if (inotify_fd >= 0)
1162 FD_SET(inotify_fd, &readfds);
1164 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
1167 err("error in select: %s", strerror(errno));
1171 /* get control message */
1172 if (FD_ISSET(udevd_sock, &readfds))
1175 /* get netlink message */
1176 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
1177 msg = get_netlink_msg();
1179 msg_queue_insert(msg);
1182 /* received a signal, clear our notification pipe */
1183 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
1186 read(signal_pipe[READ_END], &buf, sizeof(buf));
1189 /* rules directory inotify watch */
1190 if ((inotify_fd >= 0) && FD_ISSET(inotify_fd, &readfds)) {
1193 /* discard all possible events, we can just reload the config */
1194 if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes) {
1198 buf = malloc(nbytes);
1200 err("error getting buffer for inotify, disable watching");
1204 read(inotify_fd, buf, nbytes);
1209 /* rules changed, set by inotify or a HUP signal */
1210 if (reload_config) {
1212 udev_rules_cleanup(&rules);
1213 udev_rules_init(&rules, 1);
1216 /* forked child has returned */
1217 if (sigchilds_waiting) {
1218 sigchilds_waiting = 0;
1225 msg_queue_manager();
1231 udev_rules_cleanup(&rules);
1235 if (signal_pipe[READ_END] >= 0)
1236 close(signal_pipe[READ_END]);
1237 if (signal_pipe[WRITE_END] >= 0)
1238 close(signal_pipe[WRITE_END]);
1240 if (udevd_sock >= 0)
1242 if (inotify_fd >= 0)
1244 if (uevent_netlink_sock >= 0)
1245 close(uevent_netlink_sock);