2 * udevd.c - event listener and serializer
4 * Copyright (C) 2004-2006 Kay Sievers <kay.sievers@vrfy.org>
5 * Copyright (C) 2004 Chris Friesen <chris_friesen@sympatico.ca>
8 * This program is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License as published by the
10 * Free Software Foundation version 2 of the License.
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 675 Mass Ave, Cambridge, MA 02139, USA.
35 #include <sys/select.h>
37 #include <sys/types.h>
38 #include <sys/socket.h>
41 #include <sys/ioctl.h>
42 #include <linux/types.h>
43 #include <linux/netlink.h>
46 #include "udev_rules.h"
49 static struct udev_rules rules;
50 static int udevd_sock = -1;
51 static int uevent_netlink_sock = -1;
52 static int inotify_fd = -1;
55 static int signal_pipe[2] = {-1, -1};
56 static volatile int sigchilds_waiting;
57 static volatile int udev_exit;
58 static volatile int reload_config;
59 static int run_exec_q;
60 static int stop_exec_q;
61 static int max_childs;
62 static int max_childs_running;
63 static char udev_log[32];
65 static LIST_HEAD(exec_list);
66 static LIST_HEAD(running_list);
70 void log_message(int priority, const char *format, ...)
74 if (priority > udev_log_priority)
77 va_start(args, format);
78 vsyslog(priority, format, args);
83 static void asmlinkage udev_event_sig_handler(int signum)
85 if (signum == SIGALRM)
89 static int udev_event_process(struct udevd_uevent_msg *msg)
96 /* set signal handlers */
97 memset(&act, 0x00, sizeof(act));
98 act.sa_handler = (void (*)(int)) udev_event_sig_handler;
99 sigemptyset (&act.sa_mask);
101 sigaction(SIGALRM, &act, NULL);
103 /* reset to default */
104 act.sa_handler = SIG_DFL;
105 sigaction(SIGINT, &act, NULL);
106 sigaction(SIGTERM, &act, NULL);
107 sigaction(SIGCHLD, &act, NULL);
108 sigaction(SIGHUP, &act, NULL);
110 /* trigger timeout to prevent hanging processes */
111 alarm(UDEV_ALARM_TIMEOUT);
113 /* reconstruct event environment from message */
114 for (i = 0; msg->envp[i]; i++)
115 putenv(msg->envp[i]);
117 udev = udev_device_init();
120 strlcpy(udev->action, msg->action, sizeof(udev->action));
121 sysfs_device_set_values(udev->dev, msg->devpath, msg->subsystem, msg->driver);
122 udev->devt = msg->devt;
124 retval = udev_device_event(&rules, udev);
126 /* run programs collected by RUN-key*/
127 if (retval == 0 && !udev->ignore_device && udev_run) {
128 struct name_entry *name_loop;
130 dbg("executing run list");
131 list_for_each_entry(name_loop, &udev->run_list, node) {
132 if (strncmp(name_loop->name, "socket:", strlen("socket:")) == 0)
133 pass_env_to_socket(&name_loop->name[strlen("socket:")], udev->dev->devpath, udev->action);
135 char program[PATH_SIZE];
137 strlcpy(program, name_loop->name, sizeof(program));
138 udev_rules_apply_format(udev, program, sizeof(program));
139 if (run_program(program, udev->dev->subsystem, NULL, 0, NULL,
140 (udev_log_priority >= LOG_INFO)))
146 udev_device_cleanup(udev);
156 static void export_event_state(struct udevd_uevent_msg *msg, enum event_state state)
158 char filename[PATH_SIZE];
159 char filename_failed[PATH_SIZE];
160 char target[PATH_SIZE];
161 size_t start, end, i;
162 struct udevd_uevent_msg *loop_msg;
164 /* add location of queue files */
165 strlcpy(filename, udev_root, sizeof(filename));
166 strlcat(filename, "/", sizeof(filename));
167 start = strlcat(filename, EVENT_QUEUE_DIR, sizeof(filename));
168 end = strlcat(filename, msg->devpath, sizeof(filename));
169 if (end > sizeof(filename))
170 end = sizeof(filename);
172 /* replace '/' to transform path into a filename */
173 for (i = start+1; i < end; i++)
174 if (filename[i] == '/')
175 filename[i] = PATH_TO_NAME_CHAR;
177 /* add location of failed files */
178 strlcpy(filename_failed, udev_root, sizeof(filename_failed));
179 strlcat(filename_failed, "/", sizeof(filename_failed));
180 start = strlcat(filename_failed, EVENT_FAILED_DIR, sizeof(filename_failed));
181 end = strlcat(filename_failed, msg->devpath, sizeof(filename_failed));
182 if (end > sizeof(filename_failed))
183 end = sizeof(filename_failed);
185 /* replace '/' to transform path into a filename */
186 for (i = start+1; i < end; i++)
187 if (filename_failed[i] == '/')
188 filename_failed[i] = PATH_TO_NAME_CHAR;
192 unlink(filename_failed);
193 delete_path(filename_failed);
195 strlcpy(target, sysfs_path, sizeof(target));
196 strlcat(target, msg->devpath, sizeof(target));
197 create_path(filename);
198 symlink(target, filename);
202 unlink(filename_failed);
203 delete_path(filename_failed);
205 /* don't remove, if events for the same path are still pending */
206 list_for_each_entry(loop_msg, &running_list, node)
207 if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
210 list_for_each_entry(loop_msg, &exec_list, node)
211 if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
214 /* move failed events to the failed directory */
215 if (state == EVENT_FAILED) {
216 create_path(filename_failed);
217 rename(filename, filename_failed);
222 /* clean up the queue directory */
223 delete_path(filename);
229 static void msg_queue_delete(struct udevd_uevent_msg *msg)
231 list_del(&msg->node);
233 /* mark as failed, if add event returns non-zero */
234 if (msg->exitstatus && strcmp(msg->action, "add") == 0)
235 export_event_state(msg, EVENT_FAILED);
237 export_event_state(msg, EVENT_FINISHED);
242 static void udev_event_run(struct udevd_uevent_msg *msg)
251 close(uevent_netlink_sock);
255 close(signal_pipe[READ_END]);
256 close(signal_pipe[WRITE_END]);
259 logging_init("udevd-event");
260 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
262 retval = udev_event_process(msg);
263 info("seq %llu finished", msg->seqnum);
270 err("fork of child failed: %s", strerror(errno));
271 msg_queue_delete(msg);
274 /* get SIGCHLD in main loop */
275 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
276 msg->seqnum, pid, msg->action, msg->subsystem, time(NULL) - msg->queue_time);
281 static void msg_queue_insert(struct udevd_uevent_msg *msg)
283 char filename[PATH_SIZE];
286 msg->queue_time = time(NULL);
288 strlcpy(filename, udev_root, sizeof(filename));
289 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
290 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
295 len = sprintf(str, "%llu\n", msg->seqnum);
300 export_event_state(msg, EVENT_QUEUED);
302 /* run all events with a timeout set immediately */
303 if (msg->timeout != 0) {
304 list_add_tail(&msg->node, &running_list);
309 list_add_tail(&msg->node, &exec_list);
313 static int mem_size_mb(void)
321 f = open("/proc/meminfo", O_RDONLY);
325 len = read(f, buf, sizeof(buf)-1);
332 pos = strstr(buf, "MemTotal: ");
336 if (sscanf(pos, "MemTotal: %ld kB", &memsize) != 1)
339 return memsize / 1024;
342 static int cpu_count(void)
350 f = open("/proc/stat", O_RDONLY);
354 len = read(f, buf, sizeof(buf)-1);
360 pos = strstr(buf, "cpu");
364 while (pos != NULL) {
365 if (strncmp(pos, "cpu", 3) == 0 &&isdigit(pos[3]))
367 pos = strstr(&pos[3], "cpu");
375 static int running_processes(void)
383 f = open("/proc/stat", O_RDONLY);
387 len = read(f, buf, sizeof(buf)-1);
393 pos = strstr(buf, "procs_running ");
397 if (sscanf(pos, "procs_running %u", &running) != 1)
403 /* return the number of process es in our session, count only until limit */
404 static int running_processes_in_session(pid_t session, int limit)
410 dir = opendir("/proc");
414 /* read process info from /proc */
415 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
421 pid_t ppid, pgrp, sess;
424 if (!isdigit(dent->d_name[0]))
427 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
428 procdir[sizeof(procdir)-1] = '\0';
430 f = open(procdir, O_RDONLY);
434 len = read(f, line, sizeof(line)-1);
442 /* skip ugly program name */
443 pos = strrchr(line, ')') + 2;
447 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
450 /* count only processes in our session */
454 /* count only running, no sleeping processes */
459 if (limit > 0 && running >= limit)
467 static int compare_devpath(const char *running, const char *waiting)
471 for (i = 0; i < PATH_SIZE; i++) {
472 /* identical device event found */
473 if (running[i] == '\0' && waiting[i] == '\0')
476 /* parent device event found */
477 if (running[i] == '\0' && waiting[i] == '/')
480 /* child device event found */
481 if (running[i] == '/' && waiting[i] == '\0')
484 /* no matching event */
485 if (running[i] != waiting[i])
492 /* returns still running task for the same device, its parent or its physical device */
493 static int running_with_devpath(struct udevd_uevent_msg *msg, int limit)
495 struct udevd_uevent_msg *loop_msg;
496 int childs_count = 0;
498 list_for_each_entry(loop_msg, &running_list, node) {
499 if (limit && childs_count++ > limit) {
500 dbg("%llu, maximum number (%i) of child reached", msg->seqnum, childs_count);
504 /* return running parent/child device event */
505 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
506 dbg("%llu, child device event still running %llu (%s)",
507 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
511 /* return running physical device event */
512 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
513 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
514 dbg("%llu, physical device event still running %llu (%s)",
515 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
523 /* exec queue management routine executes the events and serializes events in the same sequence */
524 static void msg_queue_manager(void)
526 struct udevd_uevent_msg *loop_msg;
527 struct udevd_uevent_msg *tmp_msg;
530 if (list_empty(&exec_list))
533 running = running_processes();
534 dbg("%d processes runnning on system", running);
536 running = max_childs_running;
538 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
539 /* check running processes in our session and possibly throttle */
540 if (running >= max_childs_running) {
541 running = running_processes_in_session(sid, max_childs_running+10);
542 dbg("at least %d processes running in session", running);
543 if (running >= max_childs_running) {
544 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
549 /* don't run two processes for the same devpath and wait for the parent*/
550 if (running_with_devpath(loop_msg, max_childs)) {
551 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
555 /* move event to run list */
556 list_move_tail(&loop_msg->node, &running_list);
557 udev_event_run(loop_msg);
559 dbg("moved seq %llu to running list", loop_msg->seqnum);
563 static struct udevd_uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
567 struct udevd_uevent_msg *msg;
571 msg = malloc(sizeof(struct udevd_uevent_msg) + buf_size);
574 memset(msg, 0x00, sizeof(struct udevd_uevent_msg) + buf_size);
576 /* copy environment buffer and reconstruct envp */
577 memcpy(msg->envbuf, buf, buf_size);
579 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
583 key = &msg->envbuf[bufpos];
584 keylen = strlen(key);
586 bufpos += keylen + 1;
587 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
589 /* remember some keys for further processing */
590 if (strncmp(key, "ACTION=", 7) == 0)
591 msg->action = &key[7];
592 else if (strncmp(key, "DEVPATH=", 8) == 0)
593 msg->devpath = &key[8];
594 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
595 msg->subsystem = &key[10];
596 else if (strncmp(key, "DRIVER=", 7) == 0)
597 msg->driver = &key[7];
598 else if (strncmp(key, "SEQNUM=", 7) == 0)
599 msg->seqnum = strtoull(&key[7], NULL, 10);
600 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
601 msg->physdevpath = &key[12];
602 else if (strncmp(key, "MAJOR=", 6) == 0)
603 major = strtoull(&key[6], NULL, 10);
604 else if (strncmp(key, "MINOR=", 6) == 0)
605 minor = strtoull(&key[6], NULL, 10);
606 else if (strncmp(key, "TIMEOUT=", 8) == 0)
607 msg->timeout = strtoull(&key[8], NULL, 10);
609 msg->devt = makedev(major, minor);
610 msg->envp[i++] = "UDEVD_EVENT=1";
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))];
633 memset(&ctrl_msg, 0x00, sizeof(struct udevd_ctrl_msg));
634 iov.iov_base = &ctrl_msg;
635 iov.iov_len = sizeof(struct udevd_ctrl_msg);
637 memset(&smsg, 0x00, sizeof(struct msghdr));
640 smsg.msg_control = cred_msg;
641 smsg.msg_controllen = sizeof(cred_msg);
643 size = recvmsg(udevd_sock, &smsg, 0);
646 err("unable to receive user udevd message: %s", strerror(errno));
649 cmsg = CMSG_FIRSTHDR(&smsg);
650 cred = (struct ucred *) CMSG_DATA(cmsg);
652 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
653 err("no sender credentials received, message ignored");
657 if (cred->uid != 0) {
658 err("sender uid=%i, message ignored", cred->uid);
662 if (strncmp(ctrl_msg.magic, UDEVD_CTRL_MAGIC, sizeof(UDEVD_CTRL_MAGIC)) != 0 ) {
663 err("message magic '%s' doesn't match, ignore it", ctrl_msg.magic);
667 switch (ctrl_msg.type) {
668 case UDEVD_CTRL_STOP_EXEC_QUEUE:
669 info("udevd message (STOP_EXEC_QUEUE) received");
672 case UDEVD_CTRL_START_EXEC_QUEUE:
673 info("udevd message (START_EXEC_QUEUE) received");
677 case UDEVD_CTRL_SET_LOG_LEVEL:
678 intval = (int *) ctrl_msg.buf;
679 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
680 udev_log_priority = *intval;
681 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
684 case UDEVD_CTRL_SET_MAX_CHILDS:
685 intval = (int *) ctrl_msg.buf;
686 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
687 max_childs = *intval;
689 case UDEVD_CTRL_SET_MAX_CHILDS_RUNNING:
690 intval = (int *) ctrl_msg.buf;
691 info("udevd message (UDEVD_SET_MAX_CHILDS_RUNNING) received, max_childs=%i", *intval);
692 max_childs_running = *intval;
694 case UDEVD_CTRL_RELOAD_RULES:
695 info("udevd message (RELOAD_RULES) received");
699 err("unknown control message type");
703 /* receive the kernel user event message and do some sanity checks */
704 static struct udevd_uevent_msg *get_netlink_msg(void)
706 struct udevd_uevent_msg *msg;
709 static char buffer[UEVENT_BUFFER_SIZE+512];
712 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
715 err("unable to receive kernel netlink message: %s", strerror(errno));
719 if ((size_t)size > sizeof(buffer)-1)
720 size = sizeof(buffer)-1;
722 dbg("uevent_size=%zi", size);
724 /* start of event payload */
725 bufpos = strlen(buffer)+1;
726 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
730 /* validate message */
731 pos = strchr(buffer, '@');
733 err("invalid uevent '%s'", buffer);
739 if (msg->action == NULL) {
740 info("no ACTION in payload found, skip event '%s'", buffer);
745 if (strcmp(msg->action, buffer) != 0) {
746 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
754 static void asmlinkage sig_handler(int signum)
762 /* set flag, then write to pipe if needed */
763 sigchilds_waiting = 1;
770 /* write to pipe, which will wakeup select() in our mainloop */
771 write(signal_pipe[WRITE_END], "", 1);
774 static void udev_done(int pid, int exitstatus)
776 /* find msg associated with pid and delete it */
777 struct udevd_uevent_msg *msg;
779 list_for_each_entry(msg, &running_list, node) {
780 if (msg->pid == pid) {
781 info("seq %llu, pid [%d] exit with %i, %ld seconds old", msg->seqnum, msg->pid,
782 exitstatus, time(NULL) - msg->queue_time);
783 msg->exitstatus = exitstatus;
784 msg_queue_delete(msg);
786 /* there may be events waiting with the same devpath */
793 static void reap_sigchilds(void)
799 pid = waitpid(-1, &status, WNOHANG);
802 if (WIFEXITED(status))
803 status = WEXITSTATUS(status);
804 else if (WIFSIGNALED(status))
805 status = WTERMSIG(status) + 128;
808 udev_done(pid, status);
812 static int init_udevd_socket(void)
814 struct sockaddr_un saddr;
815 const int buffersize = 16 * 1024 * 1024;
817 const int feature_on = 1;
820 memset(&saddr, 0x00, sizeof(saddr));
821 saddr.sun_family = AF_LOCAL;
822 /* use abstract namespace for socket path */
823 strcpy(&saddr.sun_path[1], UDEVD_CTRL_SOCK_PATH);
824 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
826 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
827 if (udevd_sock == -1) {
828 err("error getting socket: %s", strerror(errno));
832 /* set receive buffersize */
833 setsockopt(udevd_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
835 /* the bind takes care of ensuring only one copy running */
836 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
838 err("bind failed: %s", strerror(errno));
844 /* enable receiving of the sender credentials */
845 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
850 static int init_uevent_netlink_sock(void)
852 struct sockaddr_nl snl;
853 const int buffersize = 16 * 1024 * 1024;
856 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
857 snl.nl_family = AF_NETLINK;
858 snl.nl_pid = getpid();
861 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
862 if (uevent_netlink_sock == -1) {
863 err("error getting socket: %s", strerror(errno));
867 /* set receive buffersize */
868 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
870 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
872 err("bind failed: %s", strerror(errno));
873 close(uevent_netlink_sock);
874 uevent_netlink_sock = -1;
880 static void export_initial_seqnum(void)
882 char filename[PATH_SIZE];
887 strlcpy(filename, sysfs_path, sizeof(filename));
888 strlcat(filename, "/kernel/uevent_seqnum", sizeof(filename));
889 fd = open(filename, O_RDONLY);
891 len = read(fd, seqnum, sizeof(seqnum)-1);
895 strcpy(seqnum, "0\n");
898 strlcpy(filename, udev_root, sizeof(filename));
899 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
900 create_path(filename);
901 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
903 write(fd, seqnum, len);
908 int main(int argc, char *argv[], char *envp[])
912 struct sigaction act;
920 /* redirect std fd's, if the kernel forks us, we don't have them at all */
921 fd = open("/dev/null", O_RDWR);
923 if (fd != STDIN_FILENO)
924 dup2(fd, STDIN_FILENO);
925 if (fd != STDOUT_FILENO)
926 dup2(fd, STDOUT_FILENO);
927 if (fd != STDERR_FILENO)
928 dup2(fd, STDERR_FILENO);
929 if (fd > STDERR_FILENO)
933 logging_init("udevd");
935 err("fatal, could not open /dev/null: %s", strerror(errno));
938 dbg("version %s", UDEV_VERSION);
941 err("need to be root, exit");
945 /* parse commandline options */
946 for (i = 1 ; i < argc; i++) {
948 if (strcmp(arg, "--daemon") == 0 || strcmp(arg, "-d") == 0) {
949 info("will daemonize");
954 /* init sockets to receive events */
955 if (init_udevd_socket() < 0) {
956 if (errno == EADDRINUSE) {
957 err("another udevd running, exit");
960 err("error initializing udevd socket: %s", strerror(errno));
966 if (init_uevent_netlink_sock() < 0) {
967 err("uevent socket not available");
972 /* parse the rules and keep it in memory */
974 udev_rules_init(&rules, 1);
976 export_initial_seqnum();
984 dbg("daemonized fork running");
987 err("fork of daemon failed: %s", strerror(errno));
991 dbg("child [%u] running, parent exits", pid);
996 /* set scheduling priority for the daemon */
997 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
1002 /* become session leader */
1004 dbg("our session is %d", sid);
1006 /* OOM_DISABLE == -17 */
1007 fd = open("/proc/self/oom_adj", O_RDWR);
1009 err("error disabling OOM: %s", strerror(errno));
1011 write(fd, "-17", 3);
1015 /* setup signal handler pipe */
1016 retval = pipe(signal_pipe);
1018 err("error getting pipes: %s", strerror(errno));
1022 retval = fcntl(signal_pipe[READ_END], F_GETFL, 0);
1024 err("error fcntl on read pipe: %s", strerror(errno));
1027 retval = fcntl(signal_pipe[READ_END], F_SETFL, retval | O_NONBLOCK);
1029 err("error fcntl on read pipe: %s", strerror(errno));
1033 retval = fcntl(signal_pipe[WRITE_END], F_GETFL, 0);
1035 err("error fcntl on write pipe: %s", strerror(errno));
1038 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, retval | O_NONBLOCK);
1040 err("error fcntl on write pipe: %s", strerror(errno));
1044 /* set signal handlers */
1045 memset(&act, 0x00, sizeof(struct sigaction));
1046 act.sa_handler = (void (*)(int)) sig_handler;
1047 sigemptyset(&act.sa_mask);
1048 act.sa_flags = SA_RESTART;
1049 sigaction(SIGINT, &act, NULL);
1050 sigaction(SIGTERM, &act, NULL);
1051 sigaction(SIGCHLD, &act, NULL);
1052 sigaction(SIGHUP, &act, NULL);
1054 /* watch rules directory */
1055 inotify_fd = inotify_init();
1056 if (inotify_fd >= 0)
1057 inotify_add_watch(inotify_fd, udev_rules_filename, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1058 else if (errno == ENOSYS)
1059 err("the kernel does not support inotify, udevd can't monitor configuration file changes");
1061 err("inotify_init failed: %s", strerror(errno));
1063 /* maximum limit of forked childs */
1064 value = getenv("UDEVD_MAX_CHILDS");
1066 max_childs = strtoul(value, NULL, 10);
1068 int memsize = mem_size_mb();
1070 max_childs = 128 + (memsize / 4);
1072 max_childs = UDEVD_MAX_CHILDS;
1074 info("initialize max_childs to %u", max_childs);
1076 /* start to throttle forking if maximum number of _running_ childs is reached */
1077 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
1079 max_childs_running = strtoull(value, NULL, 10);
1081 int cpus = cpu_count();
1083 max_childs_running = 8 + (8 * cpus);
1085 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
1087 info("initialize max_childs_running to %u", max_childs_running);
1089 /* clear environment for forked event processes */
1092 /* export log_priority , as called programs may want to follow that setting */
1093 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
1097 maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
1098 maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
1099 maxfd = UDEV_MAX(maxfd, inotify_fd);
1101 while (!udev_exit) {
1102 struct udevd_uevent_msg *msg;
1106 FD_SET(signal_pipe[READ_END], &readfds);
1107 FD_SET(udevd_sock, &readfds);
1108 FD_SET(uevent_netlink_sock, &readfds);
1109 if (inotify_fd >= 0)
1110 FD_SET(inotify_fd, &readfds);
1112 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
1115 err("error in select: %s", strerror(errno));
1119 /* get control message */
1120 if (FD_ISSET(udevd_sock, &readfds))
1123 /* get netlink message */
1124 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
1125 msg = get_netlink_msg();
1127 msg_queue_insert(msg);
1130 /* received a signal, clear our notification pipe */
1131 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
1134 read(signal_pipe[READ_END], &buf, sizeof(buf));
1137 /* rules directory inotify watch */
1138 if ((inotify_fd >= 0) && FD_ISSET(inotify_fd, &readfds)) {
1141 /* discard all possible events, we can just reload the config */
1142 if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes) {
1146 buf = malloc(nbytes);
1148 err("error getting buffer for inotify, disable watching");
1152 read(inotify_fd, buf, nbytes);
1157 /* rules changed, set by inotify or a signal*/
1158 if (reload_config) {
1160 udev_rules_cleanup(&rules);
1161 udev_rules_init(&rules, 1);
1164 /* forked child has returned */
1165 if (sigchilds_waiting) {
1166 sigchilds_waiting = 0;
1173 msg_queue_manager();
1178 udev_rules_cleanup(&rules);
1181 if (signal_pipe[READ_END] >= 0)
1182 close(signal_pipe[READ_END]);
1183 if (signal_pipe[WRITE_END] >= 0)
1184 close(signal_pipe[WRITE_END]);
1186 if (udevd_sock >= 0)
1188 if (inotify_fd >= 0)
1190 if (uevent_netlink_sock >= 0)
1191 close(uevent_netlink_sock);