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.
32 #include <sys/select.h>
34 #include <sys/types.h>
35 #include <sys/socket.h>
38 #include <sys/ioctl.h>
39 #include <linux/types.h>
40 #include <linux/netlink.h>
43 #include "udev_rules.h"
45 #include "udev_selinux.h"
47 static struct udev_rules rules;
48 static int udevd_sock = -1;
49 static int uevent_netlink_sock = -1;
50 static int inotify_fd = -1;
53 static int signal_pipe[2] = {-1, -1};
54 static volatile int sigchilds_waiting;
55 static volatile int udev_exit;
56 static volatile int reload_config;
57 static int run_exec_q;
58 static int stop_exec_q;
59 static int max_childs;
60 static int max_childs_running;
61 static char udev_log[32];
63 static LIST_HEAD(exec_list);
64 static LIST_HEAD(running_list);
68 void log_message(int priority, const char *format, ...)
72 if (priority > udev_log_priority)
75 va_start(args, format);
76 vsyslog(priority, format, args);
81 static void asmlinkage udev_event_sig_handler(int signum)
83 if (signum == SIGALRM)
87 static int udev_event_process(struct udevd_uevent_msg *msg)
94 /* set signal handlers */
95 memset(&act, 0x00, sizeof(act));
96 act.sa_handler = (void (*)(int)) udev_event_sig_handler;
97 sigemptyset (&act.sa_mask);
99 sigaction(SIGALRM, &act, NULL);
101 /* reset to default */
102 act.sa_handler = SIG_DFL;
103 sigaction(SIGINT, &act, NULL);
104 sigaction(SIGTERM, &act, NULL);
105 sigaction(SIGCHLD, &act, NULL);
106 sigaction(SIGHUP, &act, NULL);
108 /* trigger timeout to prevent hanging processes */
109 alarm(UDEV_ALARM_TIMEOUT);
111 /* reconstruct event environment from message */
112 for (i = 0; msg->envp[i]; i++)
113 putenv(msg->envp[i]);
115 udev = udev_device_init();
118 strlcpy(udev->action, msg->action, sizeof(udev->action));
119 sysfs_device_set_values(udev->dev, msg->devpath, msg->subsystem, msg->driver);
120 udev->devt = msg->devt;
122 retval = udev_device_event(&rules, udev);
124 /* run programs collected by RUN-key*/
125 if (retval == 0 && !udev->ignore_device && udev_run) {
126 struct name_entry *name_loop;
128 dbg("executing run list");
129 list_for_each_entry(name_loop, &udev->run_list, node) {
130 if (strncmp(name_loop->name, "socket:", strlen("socket:")) == 0)
131 pass_env_to_socket(&name_loop->name[strlen("socket:")], udev->dev->devpath, udev->action);
133 char program[PATH_SIZE];
135 strlcpy(program, name_loop->name, sizeof(program));
136 udev_rules_apply_format(udev, program, sizeof(program));
137 if (run_program(program, udev->dev->subsystem, NULL, 0, NULL,
138 (udev_log_priority >= LOG_INFO)))
144 udev_device_cleanup(udev);
154 static void export_event_state(struct udevd_uevent_msg *msg, enum event_state state)
156 char filename[PATH_SIZE];
157 char filename_failed[PATH_SIZE];
158 size_t start, end, i;
159 struct udevd_uevent_msg *loop_msg;
162 /* add location of queue files */
163 strlcpy(filename, udev_root, sizeof(filename));
164 strlcat(filename, "/", sizeof(filename));
165 start = strlcat(filename, EVENT_QUEUE_DIR, sizeof(filename));
166 end = strlcat(filename, msg->devpath, sizeof(filename));
167 if (end > sizeof(filename))
168 end = sizeof(filename);
170 /* replace '/' to transform path into a filename */
171 for (i = start+1; i < end; i++)
172 if (filename[i] == '/')
173 filename[i] = PATH_TO_NAME_CHAR;
175 /* add location of failed files */
176 strlcpy(filename_failed, udev_root, sizeof(filename_failed));
177 strlcat(filename_failed, "/", sizeof(filename_failed));
178 start = strlcat(filename_failed, EVENT_FAILED_DIR, sizeof(filename_failed));
179 end = strlcat(filename_failed, msg->devpath, sizeof(filename_failed));
180 if (end > sizeof(filename_failed))
181 end = sizeof(filename_failed);
183 /* replace '/' to transform path into a filename */
184 for (i = start+1; i < end; i++)
185 if (filename_failed[i] == '/')
186 filename_failed[i] = PATH_TO_NAME_CHAR;
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 all events with a timeout set immediately */
300 if (msg->timeout != 0) {
301 list_add_tail(&msg->node, &running_list);
306 list_add_tail(&msg->node, &exec_list);
310 static int mem_size_mb(void)
318 f = open("/proc/meminfo", O_RDONLY);
322 len = read(f, buf, sizeof(buf)-1);
329 pos = strstr(buf, "MemTotal: ");
333 if (sscanf(pos, "MemTotal: %ld kB", &memsize) != 1)
336 return memsize / 1024;
339 static int cpu_count(void)
347 f = open("/proc/stat", O_RDONLY);
351 len = read(f, buf, sizeof(buf)-1);
357 pos = strstr(buf, "cpu");
361 while (pos != NULL) {
362 if (strncmp(pos, "cpu", 3) == 0 &&isdigit(pos[3]))
364 pos = strstr(&pos[3], "cpu");
372 static int running_processes(void)
380 f = open("/proc/stat", O_RDONLY);
384 len = read(f, buf, sizeof(buf)-1);
390 pos = strstr(buf, "procs_running ");
394 if (sscanf(pos, "procs_running %u", &running) != 1)
400 /* return the number of process es in our session, count only until limit */
401 static int running_processes_in_session(pid_t session, int limit)
407 dir = opendir("/proc");
411 /* read process info from /proc */
412 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
418 pid_t ppid, pgrp, sess;
421 if (!isdigit(dent->d_name[0]))
424 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
425 procdir[sizeof(procdir)-1] = '\0';
427 f = open(procdir, O_RDONLY);
431 len = read(f, line, sizeof(line)-1);
439 /* skip ugly program name */
440 pos = strrchr(line, ')') + 2;
444 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
447 /* count only processes in our session */
451 /* count only running, no sleeping processes */
456 if (limit > 0 && running >= limit)
464 static int compare_devpath(const char *running, const char *waiting)
468 for (i = 0; i < PATH_SIZE; i++) {
469 /* identical device event found */
470 if (running[i] == '\0' && waiting[i] == '\0')
473 /* parent device event found */
474 if (running[i] == '\0' && waiting[i] == '/')
477 /* child device event found */
478 if (running[i] == '/' && waiting[i] == '\0')
481 /* no matching event */
482 if (running[i] != waiting[i])
489 /* returns still running task for the same device, its parent or its physical device */
490 static int running_with_devpath(struct udevd_uevent_msg *msg, int limit)
492 struct udevd_uevent_msg *loop_msg;
493 int childs_count = 0;
495 list_for_each_entry(loop_msg, &running_list, node) {
496 if (limit && childs_count++ > limit) {
497 dbg("%llu, maximum number (%i) of child reached", msg->seqnum, childs_count);
501 /* return running parent/child device event */
502 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
503 dbg("%llu, child device event still running %llu (%s)",
504 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
508 /* return running physical device event */
509 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
510 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
511 dbg("%llu, physical device event still running %llu (%s)",
512 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
520 /* exec queue management routine executes the events and serializes events in the same sequence */
521 static void msg_queue_manager(void)
523 struct udevd_uevent_msg *loop_msg;
524 struct udevd_uevent_msg *tmp_msg;
527 if (list_empty(&exec_list))
530 running = running_processes();
531 dbg("%d processes runnning on system", running);
533 running = max_childs_running;
535 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
536 /* check running processes in our session and possibly throttle */
537 if (running >= max_childs_running) {
538 running = running_processes_in_session(sid, max_childs_running+10);
539 dbg("at least %d processes running in session", running);
540 if (running >= max_childs_running) {
541 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
546 /* don't run two processes for the same devpath and wait for the parent*/
547 if (running_with_devpath(loop_msg, max_childs)) {
548 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
552 /* move event to run list */
553 list_move_tail(&loop_msg->node, &running_list);
554 udev_event_run(loop_msg);
556 dbg("moved seq %llu to running list", loop_msg->seqnum);
560 static struct udevd_uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
564 struct udevd_uevent_msg *msg;
565 char *physdevdriver_key = NULL;
569 msg = malloc(sizeof(struct udevd_uevent_msg) + buf_size);
572 memset(msg, 0x00, sizeof(struct udevd_uevent_msg) + buf_size);
574 /* copy environment buffer and reconstruct envp */
575 memcpy(msg->envbuf, buf, buf_size);
577 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
581 key = &msg->envbuf[bufpos];
582 keylen = strlen(key);
584 bufpos += keylen + 1;
585 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
587 /* remember some keys for further processing */
588 if (strncmp(key, "ACTION=", 7) == 0)
589 msg->action = &key[7];
590 else if (strncmp(key, "DEVPATH=", 8) == 0)
591 msg->devpath = &key[8];
592 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
593 msg->subsystem = &key[10];
594 else if (strncmp(key, "DRIVER=", 7) == 0)
595 msg->driver = &key[7];
596 else if (strncmp(key, "SEQNUM=", 7) == 0)
597 msg->seqnum = strtoull(&key[7], NULL, 10);
598 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
599 msg->physdevpath = &key[12];
600 else if (strncmp(key, "PHYSDEVDRIVER=", 14) == 0)
601 physdevdriver_key = key;
602 else if (strncmp(key, "MAJOR=", 6) == 0)
603 maj = strtoull(&key[6], NULL, 10);
604 else if (strncmp(key, "MINOR=", 6) == 0)
605 min = 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(maj, min);
610 msg->envp[i++] = "UDEVD_EVENT=1";
612 if (msg->driver == NULL && msg->physdevpath == NULL && physdevdriver_key != NULL) {
613 /* for older kernels DRIVER is empty for a bus device, export PHYSDEVDRIVER as DRIVER */
614 msg->envp[i++] = &physdevdriver_key[7];
615 msg->driver = &physdevdriver_key[14];
620 if (msg->devpath == NULL || msg->action == NULL) {
621 info("DEVPATH or ACTION missing, ignore message");
628 /* receive the udevd message from userspace */
629 static void get_ctrl_msg(void)
631 struct udevd_ctrl_msg ctrl_msg;
634 struct cmsghdr *cmsg;
637 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
640 memset(&ctrl_msg, 0x00, sizeof(struct udevd_ctrl_msg));
641 iov.iov_base = &ctrl_msg;
642 iov.iov_len = sizeof(struct udevd_ctrl_msg);
644 memset(&smsg, 0x00, sizeof(struct msghdr));
647 smsg.msg_control = cred_msg;
648 smsg.msg_controllen = sizeof(cred_msg);
650 size = recvmsg(udevd_sock, &smsg, 0);
653 err("unable to receive user udevd message: %s", strerror(errno));
656 cmsg = CMSG_FIRSTHDR(&smsg);
657 cred = (struct ucred *) CMSG_DATA(cmsg);
659 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
660 err("no sender credentials received, message ignored");
664 if (cred->uid != 0) {
665 err("sender uid=%i, message ignored", cred->uid);
669 if (strncmp(ctrl_msg.magic, UDEVD_CTRL_MAGIC, sizeof(UDEVD_CTRL_MAGIC)) != 0 ) {
670 err("message magic '%s' doesn't match, ignore it", ctrl_msg.magic);
674 switch (ctrl_msg.type) {
675 case UDEVD_CTRL_STOP_EXEC_QUEUE:
676 info("udevd message (STOP_EXEC_QUEUE) received");
679 case UDEVD_CTRL_START_EXEC_QUEUE:
680 info("udevd message (START_EXEC_QUEUE) received");
684 case UDEVD_CTRL_SET_LOG_LEVEL:
685 intval = (int *) ctrl_msg.buf;
686 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
687 udev_log_priority = *intval;
688 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
691 case UDEVD_CTRL_SET_MAX_CHILDS:
692 intval = (int *) ctrl_msg.buf;
693 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
694 max_childs = *intval;
696 case UDEVD_CTRL_SET_MAX_CHILDS_RUNNING:
697 intval = (int *) ctrl_msg.buf;
698 info("udevd message (UDEVD_SET_MAX_CHILDS_RUNNING) received, max_childs=%i", *intval);
699 max_childs_running = *intval;
701 case UDEVD_CTRL_RELOAD_RULES:
702 info("udevd message (RELOAD_RULES) received");
706 err("unknown control message type");
710 /* receive the kernel user event message and do some sanity checks */
711 static struct udevd_uevent_msg *get_netlink_msg(void)
713 struct udevd_uevent_msg *msg;
716 static char buffer[UEVENT_BUFFER_SIZE+512];
719 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
722 err("unable to receive kernel netlink message: %s", strerror(errno));
726 if ((size_t)size > sizeof(buffer)-1)
727 size = sizeof(buffer)-1;
729 dbg("uevent_size=%zi", size);
731 /* start of event payload */
732 bufpos = strlen(buffer)+1;
733 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
737 /* validate message */
738 pos = strchr(buffer, '@');
740 err("invalid uevent '%s'", buffer);
746 if (msg->action == NULL) {
747 info("no ACTION in payload found, skip event '%s'", buffer);
752 if (strcmp(msg->action, buffer) != 0) {
753 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
761 static void asmlinkage sig_handler(int signum)
769 /* set flag, then write to pipe if needed */
770 sigchilds_waiting = 1;
777 /* write to pipe, which will wakeup select() in our mainloop */
778 write(signal_pipe[WRITE_END], "", 1);
781 static void udev_done(int pid, int exitstatus)
783 /* find msg associated with pid and delete it */
784 struct udevd_uevent_msg *msg;
786 list_for_each_entry(msg, &running_list, node) {
787 if (msg->pid == pid) {
788 info("seq %llu, pid [%d] exit with %i, %ld seconds old", msg->seqnum, msg->pid,
789 exitstatus, time(NULL) - msg->queue_time);
790 msg->exitstatus = exitstatus;
791 msg_queue_delete(msg);
793 /* there may be events waiting with the same devpath */
800 static void reap_sigchilds(void)
806 pid = waitpid(-1, &status, WNOHANG);
809 if (WIFEXITED(status))
810 status = WEXITSTATUS(status);
811 else if (WIFSIGNALED(status))
812 status = WTERMSIG(status) + 128;
815 udev_done(pid, status);
819 static int init_udevd_socket(void)
821 struct sockaddr_un saddr;
823 const int feature_on = 1;
826 memset(&saddr, 0x00, sizeof(saddr));
827 saddr.sun_family = AF_LOCAL;
828 /* use abstract namespace for socket path */
829 strcpy(&saddr.sun_path[1], UDEVD_CTRL_SOCK_PATH);
830 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
832 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
833 if (udevd_sock == -1) {
834 err("error getting socket: %s", strerror(errno));
838 /* the bind takes care of ensuring only one copy running */
839 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
841 err("bind failed: %s", strerror(errno));
847 /* enable receiving of the sender credentials */
848 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
853 static int init_uevent_netlink_sock(void)
855 struct sockaddr_nl snl;
856 const int buffersize = 16 * 1024 * 1024;
859 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
860 snl.nl_family = AF_NETLINK;
861 snl.nl_pid = getpid();
864 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
865 if (uevent_netlink_sock == -1) {
866 err("error getting socket: %s", strerror(errno));
870 /* set receive buffersize */
871 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
873 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
875 err("bind failed: %s", strerror(errno));
876 close(uevent_netlink_sock);
877 uevent_netlink_sock = -1;
883 static void export_initial_seqnum(void)
885 char filename[PATH_SIZE];
890 strlcpy(filename, sysfs_path, sizeof(filename));
891 strlcat(filename, "/kernel/uevent_seqnum", sizeof(filename));
892 fd = open(filename, O_RDONLY);
894 len = read(fd, seqnum, sizeof(seqnum)-1);
898 strcpy(seqnum, "0\n");
901 strlcpy(filename, udev_root, sizeof(filename));
902 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
903 create_path(filename);
904 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
906 write(fd, seqnum, len);
911 int main(int argc, char *argv[], char *envp[])
915 struct sigaction act;
923 logging_init("udevd");
926 dbg("version %s", UDEV_VERSION);
928 /* parse commandline options */
929 for (i = 1 ; i < argc; i++) {
931 if (strcmp(arg, "--daemon") == 0 || strcmp(arg, "-d") == 0)
933 else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
934 printf("Usage: udevd [--help] [--daemon]\n");
937 fprintf(stderr, "unrecognized option '%s'\n", arg);
938 err("unrecognized option '%s'\n", arg);
943 fprintf(stderr, "root privileges required\n");
944 err("root privileges required");
948 /* init sockets to receive events */
949 if (init_udevd_socket() < 0) {
950 if (errno == EADDRINUSE) {
951 fprintf(stderr, "another udev daemon already running\n");
952 err("another udev daemon already running");
955 fprintf(stderr, "error initializing udevd socket\n");
956 err("error initializing udevd socket");
962 if (init_uevent_netlink_sock() < 0) {
963 fprintf(stderr, "error initializing netlink socket\n");
964 err("error initializing netlink socket");
969 /* parse the rules and keep them in memory */
971 udev_rules_init(&rules, 1);
973 export_initial_seqnum();
981 dbg("daemonized fork running");
984 err("fork of daemon failed: %s", strerror(errno));
988 dbg("child [%u] running, parent exits", pid);
994 /* redirect std fd's */
995 fd = open("/dev/null", O_RDWR);
997 dup2(fd, STDIN_FILENO);
998 dup2(fd, STDOUT_FILENO);
999 dup2(fd, STDERR_FILENO);
1000 if (fd > STDERR_FILENO)
1003 err("error opening /dev/null: %s", strerror(errno));
1005 /* set scheduling priority for the daemon */
1006 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
1011 /* become session leader */
1013 dbg("our session is %d", sid);
1015 /* OOM_DISABLE == -17 */
1016 fd = open("/proc/self/oom_adj", O_RDWR);
1018 err("error disabling OOM: %s", strerror(errno));
1020 write(fd, "-17", 3);
1024 /* setup signal handler pipe */
1025 retval = pipe(signal_pipe);
1027 err("error getting pipes: %s", strerror(errno));
1031 retval = fcntl(signal_pipe[READ_END], F_GETFL, 0);
1033 err("error fcntl on read pipe: %s", strerror(errno));
1036 retval = fcntl(signal_pipe[READ_END], F_SETFL, retval | O_NONBLOCK);
1038 err("error fcntl on read pipe: %s", strerror(errno));
1042 retval = fcntl(signal_pipe[WRITE_END], F_GETFL, 0);
1044 err("error fcntl on write pipe: %s", strerror(errno));
1047 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, retval | O_NONBLOCK);
1049 err("error fcntl on write pipe: %s", strerror(errno));
1053 /* set signal handlers */
1054 memset(&act, 0x00, sizeof(struct sigaction));
1055 act.sa_handler = (void (*)(int)) sig_handler;
1056 sigemptyset(&act.sa_mask);
1057 act.sa_flags = SA_RESTART;
1058 sigaction(SIGINT, &act, NULL);
1059 sigaction(SIGTERM, &act, NULL);
1060 sigaction(SIGCHLD, &act, NULL);
1061 sigaction(SIGHUP, &act, NULL);
1063 /* watch rules directory */
1064 inotify_fd = inotify_init();
1065 if (inotify_fd >= 0)
1066 inotify_add_watch(inotify_fd, udev_rules_filename, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1067 else if (errno == ENOSYS)
1068 err("the kernel does not support inotify, udevd can't monitor configuration file changes");
1070 err("inotify_init failed: %s", strerror(errno));
1072 /* maximum limit of forked childs */
1073 value = getenv("UDEVD_MAX_CHILDS");
1075 max_childs = strtoul(value, NULL, 10);
1077 int memsize = mem_size_mb();
1079 max_childs = 128 + (memsize / 4);
1081 max_childs = UDEVD_MAX_CHILDS;
1083 info("initialize max_childs to %u", max_childs);
1085 /* start to throttle forking if maximum number of _running_ childs is reached */
1086 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
1088 max_childs_running = strtoull(value, NULL, 10);
1090 int cpus = cpu_count();
1092 max_childs_running = 8 + (8 * cpus);
1094 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
1096 info("initialize max_childs_running to %u", max_childs_running);
1098 /* clear environment for forked event processes */
1101 /* export log_priority , as called programs may want to follow that setting */
1102 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
1106 maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
1107 maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
1108 maxfd = UDEV_MAX(maxfd, inotify_fd);
1110 while (!udev_exit) {
1111 struct udevd_uevent_msg *msg;
1115 FD_SET(signal_pipe[READ_END], &readfds);
1116 FD_SET(udevd_sock, &readfds);
1117 FD_SET(uevent_netlink_sock, &readfds);
1118 if (inotify_fd >= 0)
1119 FD_SET(inotify_fd, &readfds);
1121 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
1124 err("error in select: %s", strerror(errno));
1128 /* get control message */
1129 if (FD_ISSET(udevd_sock, &readfds))
1132 /* get netlink message */
1133 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
1134 msg = get_netlink_msg();
1136 msg_queue_insert(msg);
1139 /* received a signal, clear our notification pipe */
1140 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
1143 read(signal_pipe[READ_END], &buf, sizeof(buf));
1146 /* rules directory inotify watch */
1147 if ((inotify_fd >= 0) && FD_ISSET(inotify_fd, &readfds)) {
1150 /* discard all possible events, we can just reload the config */
1151 if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes) {
1155 buf = malloc(nbytes);
1157 err("error getting buffer for inotify, disable watching");
1161 read(inotify_fd, buf, nbytes);
1166 /* rules changed, set by inotify or a HUP signal */
1167 if (reload_config) {
1169 udev_rules_cleanup(&rules);
1170 udev_rules_init(&rules, 1);
1173 /* forked child has returned */
1174 if (sigchilds_waiting) {
1175 sigchilds_waiting = 0;
1182 msg_queue_manager();
1188 udev_rules_cleanup(&rules);
1191 if (signal_pipe[READ_END] >= 0)
1192 close(signal_pipe[READ_END]);
1193 if (signal_pipe[WRITE_END] >= 0)
1194 close(signal_pipe[WRITE_END]);
1196 if (udevd_sock >= 0)
1198 if (inotify_fd >= 0)
1200 if (uevent_netlink_sock >= 0)
1201 close(uevent_netlink_sock);