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"
48 #include "udev_selinux.h"
50 static struct udev_rules rules;
51 static int udevd_sock = -1;
52 static int uevent_netlink_sock = -1;
53 static int inotify_fd = -1;
56 static int signal_pipe[2] = {-1, -1};
57 static volatile int sigchilds_waiting;
58 static volatile int udev_exit;
59 static volatile int reload_config;
60 static int run_exec_q;
61 static int stop_exec_q;
62 static int max_childs;
63 static int max_childs_running;
64 static char udev_log[32];
66 static LIST_HEAD(exec_list);
67 static LIST_HEAD(running_list);
71 void log_message(int priority, const char *format, ...)
75 if (priority > udev_log_priority)
78 va_start(args, format);
79 vsyslog(priority, format, args);
84 static void asmlinkage udev_event_sig_handler(int signum)
86 if (signum == SIGALRM)
90 static int udev_event_process(struct udevd_uevent_msg *msg)
97 /* set signal handlers */
98 memset(&act, 0x00, sizeof(act));
99 act.sa_handler = (void (*)(int)) udev_event_sig_handler;
100 sigemptyset (&act.sa_mask);
102 sigaction(SIGALRM, &act, NULL);
104 /* reset to default */
105 act.sa_handler = SIG_DFL;
106 sigaction(SIGINT, &act, NULL);
107 sigaction(SIGTERM, &act, NULL);
108 sigaction(SIGCHLD, &act, NULL);
109 sigaction(SIGHUP, &act, NULL);
111 /* trigger timeout to prevent hanging processes */
112 alarm(UDEV_ALARM_TIMEOUT);
114 /* reconstruct event environment from message */
115 for (i = 0; msg->envp[i]; i++)
116 putenv(msg->envp[i]);
118 udev = udev_device_init();
121 strlcpy(udev->action, msg->action, sizeof(udev->action));
122 sysfs_device_set_values(udev->dev, msg->devpath, msg->subsystem, msg->driver);
123 udev->devt = msg->devt;
125 retval = udev_device_event(&rules, udev);
127 /* run programs collected by RUN-key*/
128 if (retval == 0 && !udev->ignore_device && udev_run) {
129 struct name_entry *name_loop;
131 dbg("executing run list");
132 list_for_each_entry(name_loop, &udev->run_list, node) {
133 if (strncmp(name_loop->name, "socket:", strlen("socket:")) == 0)
134 pass_env_to_socket(&name_loop->name[strlen("socket:")], udev->dev->devpath, udev->action);
136 char program[PATH_SIZE];
138 strlcpy(program, name_loop->name, sizeof(program));
139 udev_rules_apply_format(udev, program, sizeof(program));
140 if (run_program(program, udev->dev->subsystem, NULL, 0, NULL,
141 (udev_log_priority >= LOG_INFO)))
147 udev_device_cleanup(udev);
157 static void export_event_state(struct udevd_uevent_msg *msg, enum event_state state)
159 char filename[PATH_SIZE];
160 char filename_failed[PATH_SIZE];
161 char target[PATH_SIZE];
162 size_t start, end, i;
163 struct udevd_uevent_msg *loop_msg;
165 /* add location of queue files */
166 strlcpy(filename, udev_root, sizeof(filename));
167 strlcat(filename, "/", sizeof(filename));
168 start = strlcat(filename, EVENT_QUEUE_DIR, sizeof(filename));
169 end = strlcat(filename, msg->devpath, sizeof(filename));
170 if (end > sizeof(filename))
171 end = sizeof(filename);
173 /* replace '/' to transform path into a filename */
174 for (i = start+1; i < end; i++)
175 if (filename[i] == '/')
176 filename[i] = PATH_TO_NAME_CHAR;
178 /* add location of failed files */
179 strlcpy(filename_failed, udev_root, sizeof(filename_failed));
180 strlcat(filename_failed, "/", sizeof(filename_failed));
181 start = strlcat(filename_failed, EVENT_FAILED_DIR, sizeof(filename_failed));
182 end = strlcat(filename_failed, msg->devpath, sizeof(filename_failed));
183 if (end > sizeof(filename_failed))
184 end = sizeof(filename_failed);
186 /* replace '/' to transform path into a filename */
187 for (i = start+1; i < end; i++)
188 if (filename_failed[i] == '/')
189 filename_failed[i] = PATH_TO_NAME_CHAR;
193 unlink(filename_failed);
194 delete_path(filename_failed);
196 strlcpy(target, sysfs_path, sizeof(target));
197 strlcat(target, msg->devpath, sizeof(target));
198 create_path(filename);
199 symlink(target, filename);
203 unlink(filename_failed);
204 delete_path(filename_failed);
206 /* don't remove, if events for the same path are still pending */
207 list_for_each_entry(loop_msg, &running_list, node)
208 if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
211 list_for_each_entry(loop_msg, &exec_list, node)
212 if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
215 /* move failed events to the failed directory */
216 if (state == EVENT_FAILED) {
217 create_path(filename_failed);
218 rename(filename, filename_failed);
223 /* clean up the queue directory */
224 delete_path(filename);
230 static void msg_queue_delete(struct udevd_uevent_msg *msg)
232 list_del(&msg->node);
234 /* mark as failed, if add event returns non-zero */
235 if (msg->exitstatus && strcmp(msg->action, "add") == 0)
236 export_event_state(msg, EVENT_FAILED);
238 export_event_state(msg, EVENT_FINISHED);
243 static void udev_event_run(struct udevd_uevent_msg *msg)
252 close(uevent_netlink_sock);
256 close(signal_pipe[READ_END]);
257 close(signal_pipe[WRITE_END]);
260 logging_init("udevd-event");
261 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
263 retval = udev_event_process(msg);
264 info("seq %llu finished", msg->seqnum);
271 err("fork of child failed: %s", strerror(errno));
272 msg_queue_delete(msg);
275 /* get SIGCHLD in main loop */
276 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
277 msg->seqnum, pid, msg->action, msg->subsystem, time(NULL) - msg->queue_time);
282 static void msg_queue_insert(struct udevd_uevent_msg *msg)
284 char filename[PATH_SIZE];
287 msg->queue_time = time(NULL);
289 strlcpy(filename, udev_root, sizeof(filename));
290 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
291 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
296 len = sprintf(str, "%llu\n", msg->seqnum);
301 export_event_state(msg, EVENT_QUEUED);
303 /* run all events with a timeout set immediately */
304 if (msg->timeout != 0) {
305 list_add_tail(&msg->node, &running_list);
310 list_add_tail(&msg->node, &exec_list);
314 static int mem_size_mb(void)
322 f = open("/proc/meminfo", O_RDONLY);
326 len = read(f, buf, sizeof(buf)-1);
333 pos = strstr(buf, "MemTotal: ");
337 if (sscanf(pos, "MemTotal: %ld kB", &memsize) != 1)
340 return memsize / 1024;
343 static int cpu_count(void)
351 f = open("/proc/stat", O_RDONLY);
355 len = read(f, buf, sizeof(buf)-1);
361 pos = strstr(buf, "cpu");
365 while (pos != NULL) {
366 if (strncmp(pos, "cpu", 3) == 0 &&isdigit(pos[3]))
368 pos = strstr(&pos[3], "cpu");
376 static int running_processes(void)
384 f = open("/proc/stat", O_RDONLY);
388 len = read(f, buf, sizeof(buf)-1);
394 pos = strstr(buf, "procs_running ");
398 if (sscanf(pos, "procs_running %u", &running) != 1)
404 /* return the number of process es in our session, count only until limit */
405 static int running_processes_in_session(pid_t session, int limit)
411 dir = opendir("/proc");
415 /* read process info from /proc */
416 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
422 pid_t ppid, pgrp, sess;
425 if (!isdigit(dent->d_name[0]))
428 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
429 procdir[sizeof(procdir)-1] = '\0';
431 f = open(procdir, O_RDONLY);
435 len = read(f, line, sizeof(line)-1);
443 /* skip ugly program name */
444 pos = strrchr(line, ')') + 2;
448 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
451 /* count only processes in our session */
455 /* count only running, no sleeping processes */
460 if (limit > 0 && running >= limit)
468 static int compare_devpath(const char *running, const char *waiting)
472 for (i = 0; i < PATH_SIZE; i++) {
473 /* identical device event found */
474 if (running[i] == '\0' && waiting[i] == '\0')
477 /* parent device event found */
478 if (running[i] == '\0' && waiting[i] == '/')
481 /* child device event found */
482 if (running[i] == '/' && waiting[i] == '\0')
485 /* no matching event */
486 if (running[i] != waiting[i])
493 /* returns still running task for the same device, its parent or its physical device */
494 static int running_with_devpath(struct udevd_uevent_msg *msg, int limit)
496 struct udevd_uevent_msg *loop_msg;
497 int childs_count = 0;
499 list_for_each_entry(loop_msg, &running_list, node) {
500 if (limit && childs_count++ > limit) {
501 dbg("%llu, maximum number (%i) of child reached", msg->seqnum, childs_count);
505 /* return running parent/child device event */
506 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
507 dbg("%llu, child device event still running %llu (%s)",
508 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
512 /* return running physical device event */
513 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
514 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
515 dbg("%llu, physical device event still running %llu (%s)",
516 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
524 /* exec queue management routine executes the events and serializes events in the same sequence */
525 static void msg_queue_manager(void)
527 struct udevd_uevent_msg *loop_msg;
528 struct udevd_uevent_msg *tmp_msg;
531 if (list_empty(&exec_list))
534 running = running_processes();
535 dbg("%d processes runnning on system", running);
537 running = max_childs_running;
539 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
540 /* check running processes in our session and possibly throttle */
541 if (running >= max_childs_running) {
542 running = running_processes_in_session(sid, max_childs_running+10);
543 dbg("at least %d processes running in session", running);
544 if (running >= max_childs_running) {
545 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
550 /* don't run two processes for the same devpath and wait for the parent*/
551 if (running_with_devpath(loop_msg, max_childs)) {
552 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
556 /* move event to run list */
557 list_move_tail(&loop_msg->node, &running_list);
558 udev_event_run(loop_msg);
560 dbg("moved seq %llu to running list", loop_msg->seqnum);
564 static struct udevd_uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
568 struct udevd_uevent_msg *msg;
569 char *physdevdriver_key = NULL;
573 msg = malloc(sizeof(struct udevd_uevent_msg) + buf_size);
576 memset(msg, 0x00, sizeof(struct udevd_uevent_msg) + buf_size);
578 /* copy environment buffer and reconstruct envp */
579 memcpy(msg->envbuf, buf, buf_size);
581 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
585 key = &msg->envbuf[bufpos];
586 keylen = strlen(key);
588 bufpos += keylen + 1;
589 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
591 /* remember some keys for further processing */
592 if (strncmp(key, "ACTION=", 7) == 0)
593 msg->action = &key[7];
594 else if (strncmp(key, "DEVPATH=", 8) == 0)
595 msg->devpath = &key[8];
596 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
597 msg->subsystem = &key[10];
598 else if (strncmp(key, "DRIVER=", 7) == 0)
599 msg->driver = &key[7];
600 else if (strncmp(key, "SEQNUM=", 7) == 0)
601 msg->seqnum = strtoull(&key[7], NULL, 10);
602 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
603 msg->physdevpath = &key[12];
604 else if (strncmp(key, "PHYSDEVDRIVER=", 14) == 0)
605 physdevdriver_key = key;
606 else if (strncmp(key, "MAJOR=", 6) == 0)
607 major = strtoull(&key[6], NULL, 10);
608 else if (strncmp(key, "MINOR=", 6) == 0)
609 minor = strtoull(&key[6], NULL, 10);
610 else if (strncmp(key, "TIMEOUT=", 8) == 0)
611 msg->timeout = strtoull(&key[8], NULL, 10);
613 msg->devt = makedev(major, minor);
614 msg->envp[i++] = "UDEVD_EVENT=1";
616 if (msg->driver == NULL && msg->physdevpath == NULL && physdevdriver_key != NULL) {
617 /* for older kernels DRIVER is empty for a bus device, export PHYSDEVDRIVER as DRIVER */
618 msg->envp[i++] = &physdevdriver_key[7];
619 msg->driver = &physdevdriver_key[14];
624 if (msg->devpath == NULL || msg->action == NULL) {
625 info("DEVPATH or ACTION missing, ignore message");
632 /* receive the udevd message from userspace */
633 static void get_ctrl_msg(void)
635 struct udevd_ctrl_msg ctrl_msg;
638 struct cmsghdr *cmsg;
641 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
644 memset(&ctrl_msg, 0x00, sizeof(struct udevd_ctrl_msg));
645 iov.iov_base = &ctrl_msg;
646 iov.iov_len = sizeof(struct udevd_ctrl_msg);
648 memset(&smsg, 0x00, sizeof(struct msghdr));
651 smsg.msg_control = cred_msg;
652 smsg.msg_controllen = sizeof(cred_msg);
654 size = recvmsg(udevd_sock, &smsg, 0);
657 err("unable to receive user udevd message: %s", strerror(errno));
660 cmsg = CMSG_FIRSTHDR(&smsg);
661 cred = (struct ucred *) CMSG_DATA(cmsg);
663 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
664 err("no sender credentials received, message ignored");
668 if (cred->uid != 0) {
669 err("sender uid=%i, message ignored", cred->uid);
673 if (strncmp(ctrl_msg.magic, UDEVD_CTRL_MAGIC, sizeof(UDEVD_CTRL_MAGIC)) != 0 ) {
674 err("message magic '%s' doesn't match, ignore it", ctrl_msg.magic);
678 switch (ctrl_msg.type) {
679 case UDEVD_CTRL_STOP_EXEC_QUEUE:
680 info("udevd message (STOP_EXEC_QUEUE) received");
683 case UDEVD_CTRL_START_EXEC_QUEUE:
684 info("udevd message (START_EXEC_QUEUE) received");
688 case UDEVD_CTRL_SET_LOG_LEVEL:
689 intval = (int *) ctrl_msg.buf;
690 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
691 udev_log_priority = *intval;
692 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
695 case UDEVD_CTRL_SET_MAX_CHILDS:
696 intval = (int *) ctrl_msg.buf;
697 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
698 max_childs = *intval;
700 case UDEVD_CTRL_SET_MAX_CHILDS_RUNNING:
701 intval = (int *) ctrl_msg.buf;
702 info("udevd message (UDEVD_SET_MAX_CHILDS_RUNNING) received, max_childs=%i", *intval);
703 max_childs_running = *intval;
705 case UDEVD_CTRL_RELOAD_RULES:
706 info("udevd message (RELOAD_RULES) received");
710 err("unknown control message type");
714 /* receive the kernel user event message and do some sanity checks */
715 static struct udevd_uevent_msg *get_netlink_msg(void)
717 struct udevd_uevent_msg *msg;
720 static char buffer[UEVENT_BUFFER_SIZE+512];
723 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
726 err("unable to receive kernel netlink message: %s", strerror(errno));
730 if ((size_t)size > sizeof(buffer)-1)
731 size = sizeof(buffer)-1;
733 dbg("uevent_size=%zi", size);
735 /* start of event payload */
736 bufpos = strlen(buffer)+1;
737 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
741 /* validate message */
742 pos = strchr(buffer, '@');
744 err("invalid uevent '%s'", buffer);
750 if (msg->action == NULL) {
751 info("no ACTION in payload found, skip event '%s'", buffer);
756 if (strcmp(msg->action, buffer) != 0) {
757 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
765 static void asmlinkage sig_handler(int signum)
773 /* set flag, then write to pipe if needed */
774 sigchilds_waiting = 1;
781 /* write to pipe, which will wakeup select() in our mainloop */
782 write(signal_pipe[WRITE_END], "", 1);
785 static void udev_done(int pid, int exitstatus)
787 /* find msg associated with pid and delete it */
788 struct udevd_uevent_msg *msg;
790 list_for_each_entry(msg, &running_list, node) {
791 if (msg->pid == pid) {
792 info("seq %llu, pid [%d] exit with %i, %ld seconds old", msg->seqnum, msg->pid,
793 exitstatus, time(NULL) - msg->queue_time);
794 msg->exitstatus = exitstatus;
795 msg_queue_delete(msg);
797 /* there may be events waiting with the same devpath */
804 static void reap_sigchilds(void)
810 pid = waitpid(-1, &status, WNOHANG);
813 if (WIFEXITED(status))
814 status = WEXITSTATUS(status);
815 else if (WIFSIGNALED(status))
816 status = WTERMSIG(status) + 128;
819 udev_done(pid, status);
823 static int init_udevd_socket(void)
825 struct sockaddr_un saddr;
827 const int feature_on = 1;
830 memset(&saddr, 0x00, sizeof(saddr));
831 saddr.sun_family = AF_LOCAL;
832 /* use abstract namespace for socket path */
833 strcpy(&saddr.sun_path[1], UDEVD_CTRL_SOCK_PATH);
834 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
836 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
837 if (udevd_sock == -1) {
838 err("error getting socket: %s", strerror(errno));
842 /* the bind takes care of ensuring only one copy running */
843 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
845 err("bind failed: %s", strerror(errno));
851 /* enable receiving of the sender credentials */
852 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
857 static int init_uevent_netlink_sock(void)
859 struct sockaddr_nl snl;
860 const int buffersize = 16 * 1024 * 1024;
863 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
864 snl.nl_family = AF_NETLINK;
865 snl.nl_pid = getpid();
868 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
869 if (uevent_netlink_sock == -1) {
870 err("error getting socket: %s", strerror(errno));
874 /* set receive buffersize */
875 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
877 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
879 err("bind failed: %s", strerror(errno));
880 close(uevent_netlink_sock);
881 uevent_netlink_sock = -1;
887 static void export_initial_seqnum(void)
889 char filename[PATH_SIZE];
894 strlcpy(filename, sysfs_path, sizeof(filename));
895 strlcat(filename, "/kernel/uevent_seqnum", sizeof(filename));
896 fd = open(filename, O_RDONLY);
898 len = read(fd, seqnum, sizeof(seqnum)-1);
902 strcpy(seqnum, "0\n");
905 strlcpy(filename, udev_root, sizeof(filename));
906 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
907 create_path(filename);
908 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
910 write(fd, seqnum, len);
915 int main(int argc, char *argv[], char *envp[])
919 struct sigaction act;
927 logging_init("udevd");
930 dbg("version %s", UDEV_VERSION);
933 fprintf(stderr, "root privileges required\n");
934 err("root privileges required");
938 /* parse commandline options */
939 for (i = 1 ; i < argc; i++) {
941 if (strcmp(arg, "--daemon") == 0 || strcmp(arg, "-d") == 0)
943 else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
944 printf("Usage: udevd [--help] [--daemon]\n");
947 fprintf(stderr, "unrecognized option '%s'\n", arg);
948 err("unrecognized option '%s'\n", arg);
952 /* init sockets to receive events */
953 if (init_udevd_socket() < 0) {
954 if (errno == EADDRINUSE) {
955 fprintf(stderr, "another udev daemon already running\n");
956 err("another udev daemon already running");
959 fprintf(stderr, "error initializing udevd socket\n");
960 err("error initializing udevd socket");
966 if (init_uevent_netlink_sock() < 0) {
967 fprintf(stderr, "error initializing netlink socket\n");
968 err("error initializing netlink socket");
973 /* parse the rules and keep them in memory */
975 udev_rules_init(&rules, 1);
977 export_initial_seqnum();
985 dbg("daemonized fork running");
988 err("fork of daemon failed: %s", strerror(errno));
992 dbg("child [%u] running, parent exits", pid);
998 /* redirect std fd's */
999 fd = open("/dev/null", O_RDWR);
1001 dup2(fd, STDIN_FILENO);
1002 dup2(fd, STDOUT_FILENO);
1003 dup2(fd, STDERR_FILENO);
1004 if (fd > STDERR_FILENO)
1007 err("error opening /dev/null: %s", strerror(errno));
1009 /* set scheduling priority for the daemon */
1010 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
1015 /* become session leader */
1017 dbg("our session is %d", sid);
1019 /* OOM_DISABLE == -17 */
1020 fd = open("/proc/self/oom_adj", O_RDWR);
1022 err("error disabling OOM: %s", strerror(errno));
1024 write(fd, "-17", 3);
1028 /* setup signal handler pipe */
1029 retval = pipe(signal_pipe);
1031 err("error getting pipes: %s", strerror(errno));
1035 retval = fcntl(signal_pipe[READ_END], F_GETFL, 0);
1037 err("error fcntl on read pipe: %s", strerror(errno));
1040 retval = fcntl(signal_pipe[READ_END], F_SETFL, retval | O_NONBLOCK);
1042 err("error fcntl on read pipe: %s", strerror(errno));
1046 retval = fcntl(signal_pipe[WRITE_END], F_GETFL, 0);
1048 err("error fcntl on write pipe: %s", strerror(errno));
1051 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, retval | O_NONBLOCK);
1053 err("error fcntl on write pipe: %s", strerror(errno));
1057 /* set signal handlers */
1058 memset(&act, 0x00, sizeof(struct sigaction));
1059 act.sa_handler = (void (*)(int)) sig_handler;
1060 sigemptyset(&act.sa_mask);
1061 act.sa_flags = SA_RESTART;
1062 sigaction(SIGINT, &act, NULL);
1063 sigaction(SIGTERM, &act, NULL);
1064 sigaction(SIGCHLD, &act, NULL);
1065 sigaction(SIGHUP, &act, NULL);
1067 /* watch rules directory */
1068 inotify_fd = inotify_init();
1069 if (inotify_fd >= 0)
1070 inotify_add_watch(inotify_fd, udev_rules_filename, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1071 else if (errno == ENOSYS)
1072 err("the kernel does not support inotify, udevd can't monitor configuration file changes");
1074 err("inotify_init failed: %s", strerror(errno));
1076 /* maximum limit of forked childs */
1077 value = getenv("UDEVD_MAX_CHILDS");
1079 max_childs = strtoul(value, NULL, 10);
1081 int memsize = mem_size_mb();
1083 max_childs = 128 + (memsize / 4);
1085 max_childs = UDEVD_MAX_CHILDS;
1087 info("initialize max_childs to %u", max_childs);
1089 /* start to throttle forking if maximum number of _running_ childs is reached */
1090 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
1092 max_childs_running = strtoull(value, NULL, 10);
1094 int cpus = cpu_count();
1096 max_childs_running = 8 + (8 * cpus);
1098 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
1100 info("initialize max_childs_running to %u", max_childs_running);
1102 /* clear environment for forked event processes */
1105 /* export log_priority , as called programs may want to follow that setting */
1106 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
1110 maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
1111 maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
1112 maxfd = UDEV_MAX(maxfd, inotify_fd);
1114 while (!udev_exit) {
1115 struct udevd_uevent_msg *msg;
1119 FD_SET(signal_pipe[READ_END], &readfds);
1120 FD_SET(udevd_sock, &readfds);
1121 FD_SET(uevent_netlink_sock, &readfds);
1122 if (inotify_fd >= 0)
1123 FD_SET(inotify_fd, &readfds);
1125 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
1128 err("error in select: %s", strerror(errno));
1132 /* get control message */
1133 if (FD_ISSET(udevd_sock, &readfds))
1136 /* get netlink message */
1137 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
1138 msg = get_netlink_msg();
1140 msg_queue_insert(msg);
1143 /* received a signal, clear our notification pipe */
1144 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
1147 read(signal_pipe[READ_END], &buf, sizeof(buf));
1150 /* rules directory inotify watch */
1151 if ((inotify_fd >= 0) && FD_ISSET(inotify_fd, &readfds)) {
1154 /* discard all possible events, we can just reload the config */
1155 if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes) {
1159 buf = malloc(nbytes);
1161 err("error getting buffer for inotify, disable watching");
1165 read(inotify_fd, buf, nbytes);
1170 /* rules changed, set by inotify or a HUP signal */
1171 if (reload_config) {
1173 udev_rules_cleanup(&rules);
1174 udev_rules_init(&rules, 1);
1177 /* forked child has returned */
1178 if (sigchilds_waiting) {
1179 sigchilds_waiting = 0;
1186 msg_queue_manager();
1192 udev_rules_cleanup(&rules);
1195 if (signal_pipe[READ_END] >= 0)
1196 close(signal_pipe[READ_END]);
1197 if (signal_pipe[WRITE_END] >= 0)
1198 close(signal_pipe[WRITE_END]);
1200 if (udevd_sock >= 0)
1202 if (inotify_fd >= 0)
1204 if (uevent_netlink_sock >= 0)
1205 close(uevent_netlink_sock);