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 struct udev_rules rules;
49 static int udevd_sock = -1;
50 static int uevent_netlink_sock = -1;
51 static int inotify_fd = -1;
54 static int signal_pipe[2] = {-1, -1};
55 static volatile int sigchilds_waiting;
56 static volatile int udev_exit;
57 static volatile int reload_config;
58 static int run_exec_q;
59 static int stop_exec_q;
60 static int max_childs;
61 static int max_childs_running;
62 static char udev_log[32];
64 static LIST_HEAD(exec_list);
65 static LIST_HEAD(running_list);
69 void log_message(int priority, const char *format, ...)
73 if (priority > udev_log_priority)
76 va_start(args, format);
77 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 size_t start, end, i;
161 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);
194 create_path(filename);
195 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
201 unlink(filename_failed);
202 delete_path(filename_failed);
204 /* don't remove, if events for the same path are still pending */
205 list_for_each_entry(loop_msg, &running_list, node)
206 if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
209 list_for_each_entry(loop_msg, &exec_list, node)
210 if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
213 /* move failed events to the failed directory */
214 if (state == EVENT_FAILED) {
215 create_path(filename_failed);
216 rename(filename, filename_failed);
221 /* clean up the queue directory */
222 delete_path(filename);
228 static void msg_queue_delete(struct udevd_uevent_msg *msg)
230 list_del(&msg->node);
232 /* mark as failed, if add event returns non-zero */
233 if (msg->exitstatus && strcmp(msg->action, "add") == 0)
234 export_event_state(msg, EVENT_FAILED);
236 export_event_state(msg, EVENT_FINISHED);
241 static void udev_event_run(struct udevd_uevent_msg *msg)
250 close(uevent_netlink_sock);
254 close(signal_pipe[READ_END]);
255 close(signal_pipe[WRITE_END]);
258 logging_init("udevd-event");
259 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
261 retval = udev_event_process(msg);
262 info("seq %llu finished", msg->seqnum);
269 err("fork of child failed: %s", strerror(errno));
270 msg_queue_delete(msg);
273 /* get SIGCHLD in main loop */
274 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
275 msg->seqnum, pid, msg->action, msg->subsystem, time(NULL) - msg->queue_time);
280 static void msg_queue_insert(struct udevd_uevent_msg *msg)
282 char filename[PATH_SIZE];
285 msg->queue_time = time(NULL);
287 strlcpy(filename, udev_root, sizeof(filename));
288 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
289 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
294 len = sprintf(str, "%llu\n", msg->seqnum);
299 export_event_state(msg, EVENT_QUEUED);
301 /* run all events with a timeout set immediately */
302 if (msg->timeout != 0) {
303 list_add_tail(&msg->node, &running_list);
308 list_add_tail(&msg->node, &exec_list);
312 static int mem_size_mb(void)
320 f = open("/proc/meminfo", O_RDONLY);
324 len = read(f, buf, sizeof(buf)-1);
331 pos = strstr(buf, "MemTotal: ");
335 if (sscanf(pos, "MemTotal: %ld kB", &memsize) != 1)
338 return memsize / 1024;
341 static int cpu_count(void)
349 f = open("/proc/stat", O_RDONLY);
353 len = read(f, buf, sizeof(buf)-1);
359 pos = strstr(buf, "cpu");
363 while (pos != NULL) {
364 if (strncmp(pos, "cpu", 3) == 0 &&isdigit(pos[3]))
366 pos = strstr(&pos[3], "cpu");
374 static int running_processes(void)
382 f = open("/proc/stat", O_RDONLY);
386 len = read(f, buf, sizeof(buf)-1);
392 pos = strstr(buf, "procs_running ");
396 if (sscanf(pos, "procs_running %u", &running) != 1)
402 /* return the number of process es in our session, count only until limit */
403 static int running_processes_in_session(pid_t session, int limit)
409 dir = opendir("/proc");
413 /* read process info from /proc */
414 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
420 pid_t ppid, pgrp, sess;
423 if (!isdigit(dent->d_name[0]))
426 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
427 procdir[sizeof(procdir)-1] = '\0';
429 f = open(procdir, O_RDONLY);
433 len = read(f, line, sizeof(line)-1);
441 /* skip ugly program name */
442 pos = strrchr(line, ')') + 2;
446 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
449 /* count only processes in our session */
453 /* count only running, no sleeping processes */
458 if (limit > 0 && running >= limit)
466 static int compare_devpath(const char *running, const char *waiting)
470 for (i = 0; i < PATH_SIZE; i++) {
471 /* identical device event found */
472 if (running[i] == '\0' && waiting[i] == '\0')
475 /* parent device event found */
476 if (running[i] == '\0' && waiting[i] == '/')
479 /* child device event found */
480 if (running[i] == '/' && waiting[i] == '\0')
483 /* no matching event */
484 if (running[i] != waiting[i])
491 /* returns still running task for the same device, its parent or its physical device */
492 static int running_with_devpath(struct udevd_uevent_msg *msg, int limit)
494 struct udevd_uevent_msg *loop_msg;
495 int childs_count = 0;
497 list_for_each_entry(loop_msg, &running_list, node) {
498 if (limit && childs_count++ > limit) {
499 dbg("%llu, maximum number (%i) of child reached", msg->seqnum, childs_count);
503 /* return running parent/child device event */
504 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
505 dbg("%llu, child device event still running %llu (%s)",
506 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
510 /* return running physical device event */
511 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
512 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
513 dbg("%llu, physical device event still running %llu (%s)",
514 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
522 /* exec queue management routine executes the events and serializes events in the same sequence */
523 static void msg_queue_manager(void)
525 struct udevd_uevent_msg *loop_msg;
526 struct udevd_uevent_msg *tmp_msg;
529 if (list_empty(&exec_list))
532 running = running_processes();
533 dbg("%d processes runnning on system", running);
535 running = max_childs_running;
537 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
538 /* check running processes in our session and possibly throttle */
539 if (running >= max_childs_running) {
540 running = running_processes_in_session(sid, max_childs_running+10);
541 dbg("at least %d processes running in session", running);
542 if (running >= max_childs_running) {
543 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
548 /* don't run two processes for the same devpath and wait for the parent*/
549 if (running_with_devpath(loop_msg, max_childs)) {
550 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
554 /* move event to run list */
555 list_move_tail(&loop_msg->node, &running_list);
556 udev_event_run(loop_msg);
558 dbg("moved seq %llu to running list", loop_msg->seqnum);
562 static struct udevd_uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
566 struct udevd_uevent_msg *msg;
567 char *physdevdriver_key = NULL;
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, "PHYSDEVDRIVER=", 14) == 0)
603 physdevdriver_key = key;
604 else if (strncmp(key, "MAJOR=", 6) == 0)
605 maj = strtoull(&key[6], NULL, 10);
606 else if (strncmp(key, "MINOR=", 6) == 0)
607 min = strtoull(&key[6], NULL, 10);
608 else if (strncmp(key, "TIMEOUT=", 8) == 0)
609 msg->timeout = strtoull(&key[8], NULL, 10);
611 msg->devt = makedev(maj, min);
612 msg->envp[i++] = "UDEVD_EVENT=1";
614 if (msg->driver == NULL && msg->physdevpath == NULL && physdevdriver_key != NULL) {
615 /* for older kernels DRIVER is empty for a bus device, export PHYSDEVDRIVER as DRIVER */
616 msg->envp[i++] = &physdevdriver_key[7];
617 msg->driver = &physdevdriver_key[14];
622 if (msg->devpath == NULL || msg->action == NULL) {
623 info("DEVPATH or ACTION missing, ignore message");
630 /* receive the udevd message from userspace */
631 static void get_ctrl_msg(void)
633 struct udevd_ctrl_msg ctrl_msg;
636 struct cmsghdr *cmsg;
639 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
642 memset(&ctrl_msg, 0x00, sizeof(struct udevd_ctrl_msg));
643 iov.iov_base = &ctrl_msg;
644 iov.iov_len = sizeof(struct udevd_ctrl_msg);
646 memset(&smsg, 0x00, sizeof(struct msghdr));
649 smsg.msg_control = cred_msg;
650 smsg.msg_controllen = sizeof(cred_msg);
652 size = recvmsg(udevd_sock, &smsg, 0);
655 err("unable to receive user udevd message: %s", strerror(errno));
658 cmsg = CMSG_FIRSTHDR(&smsg);
659 cred = (struct ucred *) CMSG_DATA(cmsg);
661 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
662 err("no sender credentials received, message ignored");
666 if (cred->uid != 0) {
667 err("sender uid=%i, message ignored", cred->uid);
671 if (strncmp(ctrl_msg.magic, UDEVD_CTRL_MAGIC, sizeof(UDEVD_CTRL_MAGIC)) != 0 ) {
672 err("message magic '%s' doesn't match, ignore it", ctrl_msg.magic);
676 switch (ctrl_msg.type) {
677 case UDEVD_CTRL_STOP_EXEC_QUEUE:
678 info("udevd message (STOP_EXEC_QUEUE) received");
681 case UDEVD_CTRL_START_EXEC_QUEUE:
682 info("udevd message (START_EXEC_QUEUE) received");
686 case UDEVD_CTRL_SET_LOG_LEVEL:
687 intval = (int *) ctrl_msg.buf;
688 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
689 udev_log_priority = *intval;
690 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
693 case UDEVD_CTRL_SET_MAX_CHILDS:
694 intval = (int *) ctrl_msg.buf;
695 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
696 max_childs = *intval;
698 case UDEVD_CTRL_SET_MAX_CHILDS_RUNNING:
699 intval = (int *) ctrl_msg.buf;
700 info("udevd message (UDEVD_SET_MAX_CHILDS_RUNNING) received, max_childs=%i", *intval);
701 max_childs_running = *intval;
703 case UDEVD_CTRL_RELOAD_RULES:
704 info("udevd message (RELOAD_RULES) received");
708 err("unknown control message type");
712 /* receive the kernel user event message and do some sanity checks */
713 static struct udevd_uevent_msg *get_netlink_msg(void)
715 struct udevd_uevent_msg *msg;
718 static char buffer[UEVENT_BUFFER_SIZE+512];
721 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
724 err("unable to receive kernel netlink message: %s", strerror(errno));
728 if ((size_t)size > sizeof(buffer)-1)
729 size = sizeof(buffer)-1;
731 dbg("uevent_size=%zi", size);
733 /* start of event payload */
734 bufpos = strlen(buffer)+1;
735 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
739 /* validate message */
740 pos = strchr(buffer, '@');
742 err("invalid uevent '%s'", buffer);
748 if (msg->action == NULL) {
749 info("no ACTION in payload found, skip event '%s'", buffer);
754 if (strcmp(msg->action, buffer) != 0) {
755 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
763 static void asmlinkage sig_handler(int signum)
771 /* set flag, then write to pipe if needed */
772 sigchilds_waiting = 1;
779 /* write to pipe, which will wakeup select() in our mainloop */
780 write(signal_pipe[WRITE_END], "", 1);
783 static void udev_done(int pid, int exitstatus)
785 /* find msg associated with pid and delete it */
786 struct udevd_uevent_msg *msg;
788 list_for_each_entry(msg, &running_list, node) {
789 if (msg->pid == pid) {
790 info("seq %llu, pid [%d] exit with %i, %ld seconds old", msg->seqnum, msg->pid,
791 exitstatus, time(NULL) - msg->queue_time);
792 msg->exitstatus = exitstatus;
793 msg_queue_delete(msg);
795 /* there may be events waiting with the same devpath */
802 static void reap_sigchilds(void)
808 pid = waitpid(-1, &status, WNOHANG);
811 if (WIFEXITED(status))
812 status = WEXITSTATUS(status);
813 else if (WIFSIGNALED(status))
814 status = WTERMSIG(status) + 128;
817 udev_done(pid, status);
821 static int init_udevd_socket(void)
823 struct sockaddr_un saddr;
825 const int feature_on = 1;
828 memset(&saddr, 0x00, sizeof(saddr));
829 saddr.sun_family = AF_LOCAL;
830 /* use abstract namespace for socket path */
831 strcpy(&saddr.sun_path[1], UDEVD_CTRL_SOCK_PATH);
832 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
834 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
835 if (udevd_sock == -1) {
836 err("error getting socket: %s", strerror(errno));
840 /* the bind takes care of ensuring only one copy running */
841 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
843 err("bind failed: %s", strerror(errno));
849 /* enable receiving of the sender credentials */
850 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
855 static int init_uevent_netlink_sock(void)
857 struct sockaddr_nl snl;
858 const int buffersize = 16 * 1024 * 1024;
861 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
862 snl.nl_family = AF_NETLINK;
863 snl.nl_pid = getpid();
866 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
867 if (uevent_netlink_sock == -1) {
868 err("error getting socket: %s", strerror(errno));
872 /* set receive buffersize */
873 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
875 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
877 err("bind failed: %s", strerror(errno));
878 close(uevent_netlink_sock);
879 uevent_netlink_sock = -1;
885 static void export_initial_seqnum(void)
887 char filename[PATH_SIZE];
892 strlcpy(filename, sysfs_path, sizeof(filename));
893 strlcat(filename, "/kernel/uevent_seqnum", sizeof(filename));
894 fd = open(filename, O_RDONLY);
896 len = read(fd, seqnum, sizeof(seqnum)-1);
900 strcpy(seqnum, "0\n");
903 strlcpy(filename, udev_root, sizeof(filename));
904 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
905 create_path(filename);
906 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
908 write(fd, seqnum, len);
913 int main(int argc, char *argv[], char *envp[])
917 struct sigaction act;
922 static const struct option options[] = {
923 { "daemon", 0, NULL, 'd' },
924 { "help", 0, NULL, 'h' },
930 logging_init("udevd");
933 dbg("version %s", UDEV_VERSION);
935 /* parse commandline options */
937 option = getopt_long(argc, argv, "dtvh", options, NULL);
946 printf("Usage: udevd [--help] [--daemon]\n");
954 fprintf(stderr, "root privileges required\n");
955 err("root privileges required");
959 /* init sockets to receive events */
960 if (init_udevd_socket() < 0) {
961 if (errno == EADDRINUSE) {
962 fprintf(stderr, "another udev daemon already running\n");
963 err("another udev daemon already running");
966 fprintf(stderr, "error initializing udevd socket\n");
967 err("error initializing udevd socket");
973 if (init_uevent_netlink_sock() < 0) {
974 fprintf(stderr, "error initializing netlink socket\n");
975 err("error initializing netlink socket");
980 /* parse the rules and keep them in memory */
982 udev_rules_init(&rules, 1);
984 export_initial_seqnum();
992 dbg("daemonized fork running");
995 err("fork of daemon failed: %s", strerror(errno));
999 dbg("child [%u] running, parent exits", pid);
1005 /* redirect std fd's */
1006 fd = open("/dev/null", O_RDWR);
1008 dup2(fd, STDIN_FILENO);
1009 dup2(fd, STDOUT_FILENO);
1010 dup2(fd, STDERR_FILENO);
1011 if (fd > STDERR_FILENO)
1014 err("error opening /dev/null: %s", strerror(errno));
1016 /* set scheduling priority for the daemon */
1017 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
1022 /* become session leader */
1024 dbg("our session is %d", sid);
1026 /* OOM_DISABLE == -17 */
1027 fd = open("/proc/self/oom_adj", O_RDWR);
1029 err("error disabling OOM: %s", strerror(errno));
1031 write(fd, "-17", 3);
1035 /* setup signal handler pipe */
1036 retval = pipe(signal_pipe);
1038 err("error getting pipes: %s", strerror(errno));
1042 retval = fcntl(signal_pipe[READ_END], F_GETFL, 0);
1044 err("error fcntl on read pipe: %s", strerror(errno));
1047 retval = fcntl(signal_pipe[READ_END], F_SETFL, retval | O_NONBLOCK);
1049 err("error fcntl on read pipe: %s", strerror(errno));
1053 retval = fcntl(signal_pipe[WRITE_END], F_GETFL, 0);
1055 err("error fcntl on write pipe: %s", strerror(errno));
1058 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, retval | O_NONBLOCK);
1060 err("error fcntl on write pipe: %s", strerror(errno));
1064 /* set signal handlers */
1065 memset(&act, 0x00, sizeof(struct sigaction));
1066 act.sa_handler = (void (*)(int)) sig_handler;
1067 sigemptyset(&act.sa_mask);
1068 act.sa_flags = SA_RESTART;
1069 sigaction(SIGINT, &act, NULL);
1070 sigaction(SIGTERM, &act, NULL);
1071 sigaction(SIGCHLD, &act, NULL);
1072 sigaction(SIGHUP, &act, NULL);
1074 /* watch rules directory */
1075 inotify_fd = inotify_init();
1076 if (inotify_fd >= 0)
1077 inotify_add_watch(inotify_fd, udev_rules_filename, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1078 else if (errno == ENOSYS)
1079 err("the kernel does not support inotify, udevd can't monitor configuration file changes");
1081 err("inotify_init failed: %s", strerror(errno));
1083 /* maximum limit of forked childs */
1084 value = getenv("UDEVD_MAX_CHILDS");
1086 max_childs = strtoul(value, NULL, 10);
1088 int memsize = mem_size_mb();
1090 max_childs = 128 + (memsize / 4);
1092 max_childs = UDEVD_MAX_CHILDS;
1094 info("initialize max_childs to %u", max_childs);
1096 /* start to throttle forking if maximum number of _running_ childs is reached */
1097 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
1099 max_childs_running = strtoull(value, NULL, 10);
1101 int cpus = cpu_count();
1103 max_childs_running = 8 + (8 * cpus);
1105 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
1107 info("initialize max_childs_running to %u", max_childs_running);
1109 /* clear environment for forked event processes */
1112 /* export log_priority , as called programs may want to follow that setting */
1113 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
1117 maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
1118 maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
1119 maxfd = UDEV_MAX(maxfd, inotify_fd);
1121 while (!udev_exit) {
1122 struct udevd_uevent_msg *msg;
1126 FD_SET(signal_pipe[READ_END], &readfds);
1127 FD_SET(udevd_sock, &readfds);
1128 FD_SET(uevent_netlink_sock, &readfds);
1129 if (inotify_fd >= 0)
1130 FD_SET(inotify_fd, &readfds);
1132 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
1135 err("error in select: %s", strerror(errno));
1139 /* get control message */
1140 if (FD_ISSET(udevd_sock, &readfds))
1143 /* get netlink message */
1144 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
1145 msg = get_netlink_msg();
1147 msg_queue_insert(msg);
1150 /* received a signal, clear our notification pipe */
1151 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
1154 read(signal_pipe[READ_END], &buf, sizeof(buf));
1157 /* rules directory inotify watch */
1158 if ((inotify_fd >= 0) && FD_ISSET(inotify_fd, &readfds)) {
1161 /* discard all possible events, we can just reload the config */
1162 if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes) {
1166 buf = malloc(nbytes);
1168 err("error getting buffer for inotify, disable watching");
1172 read(inotify_fd, buf, nbytes);
1177 /* rules changed, set by inotify or a HUP signal */
1178 if (reload_config) {
1180 udev_rules_cleanup(&rules);
1181 udev_rules_init(&rules, 1);
1184 /* forked child has returned */
1185 if (sigchilds_waiting) {
1186 sigchilds_waiting = 0;
1193 msg_queue_manager();
1199 udev_rules_cleanup(&rules);
1202 if (signal_pipe[READ_END] >= 0)
1203 close(signal_pipe[READ_END]);
1204 if (signal_pipe[WRITE_END] >= 0)
1205 close(signal_pipe[WRITE_END]);
1207 if (udevd_sock >= 0)
1209 if (inotify_fd >= 0)
1211 if (uevent_netlink_sock >= 0)
1212 close(uevent_netlink_sock);