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"
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);
83 va_start(args, format);
84 vprintf(format, args);
92 static void asmlinkage udev_event_sig_handler(int signum)
94 if (signum == SIGALRM)
98 static int udev_event_process(struct udevd_uevent_msg *msg)
100 struct sigaction act;
101 struct udevice *udev;
105 /* set signal handlers */
106 memset(&act, 0x00, sizeof(act));
107 act.sa_handler = (void (*)(int)) udev_event_sig_handler;
108 sigemptyset (&act.sa_mask);
110 sigaction(SIGALRM, &act, NULL);
112 /* reset to default */
113 act.sa_handler = SIG_DFL;
114 sigaction(SIGINT, &act, NULL);
115 sigaction(SIGTERM, &act, NULL);
116 sigaction(SIGCHLD, &act, NULL);
117 sigaction(SIGHUP, &act, NULL);
119 /* trigger timeout to prevent hanging processes */
120 alarm(UDEV_ALARM_TIMEOUT);
122 /* reconstruct event environment from message */
123 for (i = 0; msg->envp[i]; i++)
124 putenv(msg->envp[i]);
126 udev = udev_device_init();
129 strlcpy(udev->action, msg->action, sizeof(udev->action));
130 sysfs_device_set_values(udev->dev, msg->devpath, msg->subsystem, msg->driver);
131 udev->devt = msg->devt;
133 retval = udev_device_event(&rules, udev);
135 /* run programs collected by RUN-key*/
136 if (retval == 0 && !udev->ignore_device && udev_run) {
137 struct name_entry *name_loop;
139 dbg("executing run list");
140 list_for_each_entry(name_loop, &udev->run_list, node) {
141 if (strncmp(name_loop->name, "socket:", strlen("socket:")) == 0)
142 pass_env_to_socket(&name_loop->name[strlen("socket:")], udev->dev->devpath, udev->action);
144 char program[PATH_SIZE];
146 strlcpy(program, name_loop->name, sizeof(program));
147 udev_rules_apply_format(udev, program, sizeof(program));
148 if (run_program(program, udev->dev->subsystem, NULL, 0, NULL,
149 (udev_log_priority >= LOG_INFO)))
155 udev_device_cleanup(udev);
165 static void export_event_state(struct udevd_uevent_msg *msg, enum event_state state)
167 char filename[PATH_SIZE];
168 char filename_failed[PATH_SIZE];
169 size_t start, end, i;
170 struct udevd_uevent_msg *loop_msg;
173 /* add location of queue files */
174 strlcpy(filename, udev_root, sizeof(filename));
175 strlcat(filename, "/", sizeof(filename));
176 start = strlcat(filename, EVENT_QUEUE_DIR, sizeof(filename));
177 end = strlcat(filename, msg->devpath, sizeof(filename));
178 if (end > sizeof(filename))
179 end = sizeof(filename);
181 /* replace '/' to transform path into a filename */
182 for (i = start+1; i < end; i++)
183 if (filename[i] == '/')
184 filename[i] = PATH_TO_NAME_CHAR;
186 /* add location of failed files */
187 strlcpy(filename_failed, udev_root, sizeof(filename_failed));
188 strlcat(filename_failed, "/", sizeof(filename_failed));
189 start = strlcat(filename_failed, EVENT_FAILED_DIR, sizeof(filename_failed));
190 end = strlcat(filename_failed, msg->devpath, sizeof(filename_failed));
191 if (end > sizeof(filename_failed))
192 end = sizeof(filename_failed);
194 /* replace '/' to transform path into a filename */
195 for (i = start+1; i < end; i++)
196 if (filename_failed[i] == '/')
197 filename_failed[i] = PATH_TO_NAME_CHAR;
201 unlink(filename_failed);
202 delete_path(filename_failed);
203 create_path(filename);
204 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
210 unlink(filename_failed);
211 delete_path(filename_failed);
213 /* don't remove, if events for the same path are still pending */
214 list_for_each_entry(loop_msg, &running_list, node)
215 if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
218 list_for_each_entry(loop_msg, &exec_list, node)
219 if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
222 /* move failed events to the failed directory */
223 if (state == EVENT_FAILED) {
224 create_path(filename_failed);
225 rename(filename, filename_failed);
230 /* clean up the queue directory */
231 delete_path(filename);
237 static void msg_queue_delete(struct udevd_uevent_msg *msg)
239 list_del(&msg->node);
241 /* mark as failed, if add event returns non-zero */
242 if (msg->exitstatus && strcmp(msg->action, "add") == 0)
243 export_event_state(msg, EVENT_FAILED);
245 export_event_state(msg, EVENT_FINISHED);
250 static void udev_event_run(struct udevd_uevent_msg *msg)
259 close(uevent_netlink_sock);
263 close(signal_pipe[READ_END]);
264 close(signal_pipe[WRITE_END]);
267 logging_init("udevd-event");
268 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
270 retval = udev_event_process(msg);
271 info("seq %llu finished", msg->seqnum);
278 err("fork of child failed: %s", strerror(errno));
279 msg_queue_delete(msg);
282 /* get SIGCHLD in main loop */
283 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
284 msg->seqnum, pid, msg->action, msg->subsystem, time(NULL) - msg->queue_time);
289 static void msg_queue_insert(struct udevd_uevent_msg *msg)
291 char filename[PATH_SIZE];
294 msg->queue_time = time(NULL);
296 strlcpy(filename, udev_root, sizeof(filename));
297 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
298 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
303 len = sprintf(str, "%llu\n", msg->seqnum);
308 export_event_state(msg, EVENT_QUEUED);
310 /* run all events with a timeout set immediately */
311 if (msg->timeout != 0) {
312 list_add_tail(&msg->node, &running_list);
317 list_add_tail(&msg->node, &exec_list);
321 static int mem_size_mb(void)
329 f = open("/proc/meminfo", O_RDONLY);
333 len = read(f, buf, sizeof(buf)-1);
340 pos = strstr(buf, "MemTotal: ");
344 if (sscanf(pos, "MemTotal: %ld kB", &memsize) != 1)
347 return memsize / 1024;
350 static int cpu_count(void)
358 f = open("/proc/stat", O_RDONLY);
362 len = read(f, buf, sizeof(buf)-1);
368 pos = strstr(buf, "cpu");
372 while (pos != NULL) {
373 if (strncmp(pos, "cpu", 3) == 0 &&isdigit(pos[3]))
375 pos = strstr(&pos[3], "cpu");
383 static int running_processes(void)
391 f = open("/proc/stat", O_RDONLY);
395 len = read(f, buf, sizeof(buf)-1);
401 pos = strstr(buf, "procs_running ");
405 if (sscanf(pos, "procs_running %u", &running) != 1)
411 /* return the number of process es in our session, count only until limit */
412 static int running_processes_in_session(pid_t session, int limit)
418 dir = opendir("/proc");
422 /* read process info from /proc */
423 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
429 pid_t ppid, pgrp, sess;
432 if (!isdigit(dent->d_name[0]))
435 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
436 procdir[sizeof(procdir)-1] = '\0';
438 f = open(procdir, O_RDONLY);
442 len = read(f, line, sizeof(line)-1);
450 /* skip ugly program name */
451 pos = strrchr(line, ')') + 2;
455 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
458 /* count only processes in our session */
462 /* count only running, no sleeping processes */
467 if (limit > 0 && running >= limit)
475 static int compare_devpath(const char *running, const char *waiting)
479 for (i = 0; i < PATH_SIZE; i++) {
480 /* identical device event found */
481 if (running[i] == '\0' && waiting[i] == '\0')
484 /* parent device event found */
485 if (running[i] == '\0' && waiting[i] == '/')
488 /* child device event found */
489 if (running[i] == '/' && waiting[i] == '\0')
492 /* no matching event */
493 if (running[i] != waiting[i])
500 /* returns still running task for the same device, its parent or its physical device */
501 static int running_with_devpath(struct udevd_uevent_msg *msg, int limit)
503 struct udevd_uevent_msg *loop_msg;
504 int childs_count = 0;
506 list_for_each_entry(loop_msg, &running_list, node) {
507 if (limit && childs_count++ > limit) {
508 dbg("%llu, maximum number (%i) of child reached", msg->seqnum, childs_count);
512 /* return running parent/child device event */
513 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
514 dbg("%llu, child device event still running %llu (%s)",
515 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
519 /* return running physical device event */
520 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
521 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
522 dbg("%llu, physical device event still running %llu (%s)",
523 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
531 /* exec queue management routine executes the events and serializes events in the same sequence */
532 static void msg_queue_manager(void)
534 struct udevd_uevent_msg *loop_msg;
535 struct udevd_uevent_msg *tmp_msg;
538 if (list_empty(&exec_list))
541 running = running_processes();
542 dbg("%d processes runnning on system", running);
544 running = max_childs_running;
546 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
547 /* check running processes in our session and possibly throttle */
548 if (running >= max_childs_running) {
549 running = running_processes_in_session(sid, max_childs_running+10);
550 dbg("at least %d processes running in session", running);
551 if (running >= max_childs_running) {
552 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
557 /* don't run two processes for the same devpath and wait for the parent*/
558 if (running_with_devpath(loop_msg, max_childs)) {
559 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
563 /* move event to run list */
564 list_move_tail(&loop_msg->node, &running_list);
565 udev_event_run(loop_msg);
567 dbg("moved seq %llu to running list", loop_msg->seqnum);
571 static struct udevd_uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
575 struct udevd_uevent_msg *msg;
576 char *physdevdriver_key = NULL;
580 msg = malloc(sizeof(struct udevd_uevent_msg) + buf_size);
583 memset(msg, 0x00, sizeof(struct udevd_uevent_msg) + buf_size);
585 /* copy environment buffer and reconstruct envp */
586 memcpy(msg->envbuf, buf, buf_size);
588 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
592 key = &msg->envbuf[bufpos];
593 keylen = strlen(key);
595 bufpos += keylen + 1;
596 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
598 /* remember some keys for further processing */
599 if (strncmp(key, "ACTION=", 7) == 0)
600 msg->action = &key[7];
601 else if (strncmp(key, "DEVPATH=", 8) == 0)
602 msg->devpath = &key[8];
603 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
604 msg->subsystem = &key[10];
605 else if (strncmp(key, "DRIVER=", 7) == 0)
606 msg->driver = &key[7];
607 else if (strncmp(key, "SEQNUM=", 7) == 0)
608 msg->seqnum = strtoull(&key[7], NULL, 10);
609 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
610 msg->physdevpath = &key[12];
611 else if (strncmp(key, "PHYSDEVDRIVER=", 14) == 0)
612 physdevdriver_key = key;
613 else if (strncmp(key, "MAJOR=", 6) == 0)
614 maj = strtoull(&key[6], NULL, 10);
615 else if (strncmp(key, "MINOR=", 6) == 0)
616 min = strtoull(&key[6], NULL, 10);
617 else if (strncmp(key, "TIMEOUT=", 8) == 0)
618 msg->timeout = strtoull(&key[8], NULL, 10);
620 msg->devt = makedev(maj, min);
621 msg->envp[i++] = "UDEVD_EVENT=1";
623 if (msg->driver == NULL && msg->physdevpath == NULL && physdevdriver_key != NULL) {
624 /* for older kernels DRIVER is empty for a bus device, export PHYSDEVDRIVER as DRIVER */
625 msg->envp[i++] = &physdevdriver_key[7];
626 msg->driver = &physdevdriver_key[14];
631 if (msg->devpath == NULL || msg->action == NULL) {
632 info("DEVPATH or ACTION missing, ignore message");
639 /* receive the udevd message from userspace */
640 static void get_ctrl_msg(void)
642 struct udevd_ctrl_msg ctrl_msg;
645 struct cmsghdr *cmsg;
648 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
651 memset(&ctrl_msg, 0x00, sizeof(struct udevd_ctrl_msg));
652 iov.iov_base = &ctrl_msg;
653 iov.iov_len = sizeof(struct udevd_ctrl_msg);
655 memset(&smsg, 0x00, sizeof(struct msghdr));
658 smsg.msg_control = cred_msg;
659 smsg.msg_controllen = sizeof(cred_msg);
661 size = recvmsg(udevd_sock, &smsg, 0);
664 err("unable to receive user udevd message: %s", strerror(errno));
667 cmsg = CMSG_FIRSTHDR(&smsg);
668 cred = (struct ucred *) CMSG_DATA(cmsg);
670 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
671 err("no sender credentials received, message ignored");
675 if (cred->uid != 0) {
676 err("sender uid=%i, message ignored", cred->uid);
680 if (strncmp(ctrl_msg.magic, UDEVD_CTRL_MAGIC, sizeof(UDEVD_CTRL_MAGIC)) != 0 ) {
681 err("message magic '%s' doesn't match, ignore it", ctrl_msg.magic);
685 switch (ctrl_msg.type) {
686 case UDEVD_CTRL_STOP_EXEC_QUEUE:
687 info("udevd message (STOP_EXEC_QUEUE) received");
690 case UDEVD_CTRL_START_EXEC_QUEUE:
691 info("udevd message (START_EXEC_QUEUE) received");
695 case UDEVD_CTRL_SET_LOG_LEVEL:
696 intval = (int *) ctrl_msg.buf;
697 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
698 udev_log_priority = *intval;
699 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
702 case UDEVD_CTRL_SET_MAX_CHILDS:
703 intval = (int *) ctrl_msg.buf;
704 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
705 max_childs = *intval;
707 case UDEVD_CTRL_SET_MAX_CHILDS_RUNNING:
708 intval = (int *) ctrl_msg.buf;
709 info("udevd message (UDEVD_SET_MAX_CHILDS_RUNNING) received, max_childs=%i", *intval);
710 max_childs_running = *intval;
712 case UDEVD_CTRL_RELOAD_RULES:
713 info("udevd message (RELOAD_RULES) received");
717 err("unknown control message type");
721 /* receive the kernel user event message and do some sanity checks */
722 static struct udevd_uevent_msg *get_netlink_msg(void)
724 struct udevd_uevent_msg *msg;
727 static char buffer[UEVENT_BUFFER_SIZE+512];
730 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
733 err("unable to receive kernel netlink message: %s", strerror(errno));
737 if ((size_t)size > sizeof(buffer)-1)
738 size = sizeof(buffer)-1;
740 dbg("uevent_size=%zi", size);
742 /* start of event payload */
743 bufpos = strlen(buffer)+1;
744 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
748 /* validate message */
749 pos = strchr(buffer, '@');
751 err("invalid uevent '%s'", buffer);
757 if (msg->action == NULL) {
758 info("no ACTION in payload found, skip event '%s'", buffer);
763 if (strcmp(msg->action, buffer) != 0) {
764 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
772 static void asmlinkage sig_handler(int signum)
780 /* set flag, then write to pipe if needed */
781 sigchilds_waiting = 1;
788 /* write to pipe, which will wakeup select() in our mainloop */
789 write(signal_pipe[WRITE_END], "", 1);
792 static void udev_done(int pid, int exitstatus)
794 /* find msg associated with pid and delete it */
795 struct udevd_uevent_msg *msg;
797 list_for_each_entry(msg, &running_list, node) {
798 if (msg->pid == pid) {
799 info("seq %llu, pid [%d] exit with %i, %ld seconds old", msg->seqnum, msg->pid,
800 exitstatus, time(NULL) - msg->queue_time);
801 msg->exitstatus = exitstatus;
802 msg_queue_delete(msg);
804 /* there may be events waiting with the same devpath */
811 static void reap_sigchilds(void)
817 pid = waitpid(-1, &status, WNOHANG);
820 if (WIFEXITED(status))
821 status = WEXITSTATUS(status);
822 else if (WIFSIGNALED(status))
823 status = WTERMSIG(status) + 128;
826 udev_done(pid, status);
830 static int init_udevd_socket(void)
832 struct sockaddr_un saddr;
834 const int feature_on = 1;
837 memset(&saddr, 0x00, sizeof(saddr));
838 saddr.sun_family = AF_LOCAL;
839 /* use abstract namespace for socket path */
840 strcpy(&saddr.sun_path[1], UDEVD_CTRL_SOCK_PATH);
841 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
843 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
844 if (udevd_sock == -1) {
845 err("error getting socket: %s", strerror(errno));
849 /* the bind takes care of ensuring only one copy running */
850 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
852 err("bind failed: %s", strerror(errno));
858 /* enable receiving of the sender credentials */
859 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
864 static int init_uevent_netlink_sock(void)
866 struct sockaddr_nl snl;
867 const int buffersize = 16 * 1024 * 1024;
870 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
871 snl.nl_family = AF_NETLINK;
872 snl.nl_pid = getpid();
875 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
876 if (uevent_netlink_sock == -1) {
877 err("error getting socket: %s", strerror(errno));
881 /* set receive buffersize */
882 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
884 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
886 err("bind failed: %s", strerror(errno));
887 close(uevent_netlink_sock);
888 uevent_netlink_sock = -1;
894 static void export_initial_seqnum(void)
896 char filename[PATH_SIZE];
901 strlcpy(filename, sysfs_path, sizeof(filename));
902 strlcat(filename, "/kernel/uevent_seqnum", sizeof(filename));
903 fd = open(filename, O_RDONLY);
905 len = read(fd, seqnum, sizeof(seqnum)-1);
909 strcpy(seqnum, "0\n");
912 strlcpy(filename, udev_root, sizeof(filename));
913 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
914 create_path(filename);
915 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
917 write(fd, seqnum, len);
922 int main(int argc, char *argv[], char *envp[])
926 struct sigaction act;
931 static const struct option options[] = {
932 { "daemon", 0, NULL, 'd' },
933 { "verbose", 0, NULL, 'v' },
934 { "help", 0, NULL, 'h' },
940 logging_init("udevd");
943 dbg("version %s", UDEV_VERSION);
945 /* parse commandline options */
947 option = getopt_long(argc, argv, "dtvh", options, NULL);
957 if (udev_log_priority < LOG_INFO)
958 udev_log_priority = LOG_INFO;
961 printf("Usage: udevd [--help] [--daemon] [--verbose]\n");
969 fprintf(stderr, "root privileges required\n");
970 err("root privileges required");
974 /* init sockets to receive events */
975 if (init_udevd_socket() < 0) {
976 if (errno == EADDRINUSE) {
977 fprintf(stderr, "another udev daemon already running\n");
978 err("another udev daemon already running");
981 fprintf(stderr, "error initializing udevd socket\n");
982 err("error initializing udevd socket");
988 if (init_uevent_netlink_sock() < 0) {
989 fprintf(stderr, "error initializing netlink socket\n");
990 err("error initializing netlink socket");
995 /* parse the rules and keep them in memory */
997 udev_rules_init(&rules, 1);
999 export_initial_seqnum();
1007 dbg("daemonized fork running");
1010 err("fork of daemon failed: %s", strerror(errno));
1014 dbg("child [%u] running, parent exits", pid);
1020 /* redirect std fd's */
1021 fd = open("/dev/null", O_RDWR);
1023 dup2(fd, STDIN_FILENO);
1025 dup2(fd, STDOUT_FILENO);
1026 dup2(fd, STDERR_FILENO);
1027 if (fd > STDERR_FILENO)
1030 err("error opening /dev/null: %s", strerror(errno));
1032 /* set scheduling priority for the daemon */
1033 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
1038 /* become session leader */
1040 dbg("our session is %d", sid);
1042 /* OOM_DISABLE == -17 */
1043 fd = open("/proc/self/oom_adj", O_RDWR);
1045 err("error disabling OOM: %s", strerror(errno));
1047 write(fd, "-17", 3);
1051 /* setup signal handler pipe */
1052 retval = pipe(signal_pipe);
1054 err("error getting pipes: %s", strerror(errno));
1058 retval = fcntl(signal_pipe[READ_END], F_GETFL, 0);
1060 err("error fcntl on read pipe: %s", strerror(errno));
1063 retval = fcntl(signal_pipe[READ_END], F_SETFL, retval | O_NONBLOCK);
1065 err("error fcntl on read pipe: %s", strerror(errno));
1069 retval = fcntl(signal_pipe[WRITE_END], F_GETFL, 0);
1071 err("error fcntl on write pipe: %s", strerror(errno));
1074 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, retval | O_NONBLOCK);
1076 err("error fcntl on write pipe: %s", strerror(errno));
1080 /* set signal handlers */
1081 memset(&act, 0x00, sizeof(struct sigaction));
1082 act.sa_handler = (void (*)(int)) sig_handler;
1083 sigemptyset(&act.sa_mask);
1084 act.sa_flags = SA_RESTART;
1085 sigaction(SIGINT, &act, NULL);
1086 sigaction(SIGTERM, &act, NULL);
1087 sigaction(SIGCHLD, &act, NULL);
1088 sigaction(SIGHUP, &act, NULL);
1090 /* watch rules directory */
1091 inotify_fd = inotify_init();
1092 if (inotify_fd >= 0)
1093 inotify_add_watch(inotify_fd, udev_rules_filename, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1094 else if (errno == ENOSYS)
1095 err("the kernel does not support inotify, udevd can't monitor configuration file changes");
1097 err("inotify_init failed: %s", strerror(errno));
1099 /* maximum limit of forked childs */
1100 value = getenv("UDEVD_MAX_CHILDS");
1102 max_childs = strtoul(value, NULL, 10);
1104 int memsize = mem_size_mb();
1106 max_childs = 128 + (memsize / 4);
1108 max_childs = UDEVD_MAX_CHILDS;
1110 info("initialize max_childs to %u", max_childs);
1112 /* start to throttle forking if maximum number of _running_ childs is reached */
1113 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
1115 max_childs_running = strtoull(value, NULL, 10);
1117 int cpus = cpu_count();
1119 max_childs_running = 8 + (8 * cpus);
1121 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
1123 info("initialize max_childs_running to %u", max_childs_running);
1125 /* clear environment for forked event processes */
1128 /* export log_priority , as called programs may want to follow that setting */
1129 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
1133 maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
1134 maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
1135 maxfd = UDEV_MAX(maxfd, inotify_fd);
1137 while (!udev_exit) {
1138 struct udevd_uevent_msg *msg;
1142 FD_SET(signal_pipe[READ_END], &readfds);
1143 FD_SET(udevd_sock, &readfds);
1144 FD_SET(uevent_netlink_sock, &readfds);
1145 if (inotify_fd >= 0)
1146 FD_SET(inotify_fd, &readfds);
1148 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
1151 err("error in select: %s", strerror(errno));
1155 /* get control message */
1156 if (FD_ISSET(udevd_sock, &readfds))
1159 /* get netlink message */
1160 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
1161 msg = get_netlink_msg();
1163 msg_queue_insert(msg);
1166 /* received a signal, clear our notification pipe */
1167 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
1170 read(signal_pipe[READ_END], &buf, sizeof(buf));
1173 /* rules directory inotify watch */
1174 if ((inotify_fd >= 0) && FD_ISSET(inotify_fd, &readfds)) {
1177 /* discard all possible events, we can just reload the config */
1178 if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes) {
1182 buf = malloc(nbytes);
1184 err("error getting buffer for inotify, disable watching");
1188 read(inotify_fd, buf, nbytes);
1193 /* rules changed, set by inotify or a HUP signal */
1194 if (reload_config) {
1196 udev_rules_cleanup(&rules);
1197 udev_rules_init(&rules, 1);
1200 /* forked child has returned */
1201 if (sigchilds_waiting) {
1202 sigchilds_waiting = 0;
1209 msg_queue_manager();
1215 udev_rules_cleanup(&rules);
1218 if (signal_pipe[READ_END] >= 0)
1219 close(signal_pipe[READ_END]);
1220 if (signal_pipe[WRITE_END] >= 0)
1221 close(signal_pipe[WRITE_END]);
1223 if (udevd_sock >= 0)
1225 if (inotify_fd >= 0)
1227 if (uevent_netlink_sock >= 0)
1228 close(uevent_netlink_sock);