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 int debug_trace;
51 static struct udev_rules rules;
52 static int udevd_sock = -1;
53 static int uevent_netlink_sock = -1;
54 static int inotify_fd = -1;
57 static int signal_pipe[2] = {-1, -1};
58 static volatile int sigchilds_waiting;
59 static volatile int udev_exit;
60 static volatile int reload_config;
61 static int run_exec_q;
62 static int stop_exec_q;
63 static int max_childs;
64 static int max_childs_running;
65 static char udev_log[32];
67 static LIST_HEAD(exec_list);
68 static LIST_HEAD(running_list);
72 void log_message(int priority, const char *format, ...)
76 if (priority > udev_log_priority)
80 printf("[%d] ", (int) getpid());
81 va_start(args, format);
82 vprintf(format, args);
86 va_start(args, format);
87 vsyslog(priority, format, args);
94 static void asmlinkage udev_event_sig_handler(int signum)
96 if (signum == SIGALRM)
100 static int udev_event_process(struct udevd_uevent_msg *msg)
102 struct sigaction act;
103 struct udevice *udev;
107 /* set signal handlers */
108 memset(&act, 0x00, sizeof(act));
109 act.sa_handler = (void (*)(int)) udev_event_sig_handler;
110 sigemptyset (&act.sa_mask);
112 sigaction(SIGALRM, &act, NULL);
114 /* reset to default */
115 act.sa_handler = SIG_DFL;
116 sigaction(SIGINT, &act, NULL);
117 sigaction(SIGTERM, &act, NULL);
118 sigaction(SIGCHLD, &act, NULL);
119 sigaction(SIGHUP, &act, NULL);
121 /* trigger timeout to prevent hanging processes */
122 alarm(UDEV_ALARM_TIMEOUT);
124 /* reconstruct event environment from message */
125 for (i = 0; msg->envp[i]; i++)
126 putenv(msg->envp[i]);
128 udev = udev_device_init(NULL);
131 strlcpy(udev->action, msg->action, sizeof(udev->action));
132 sysfs_device_set_values(udev->dev, msg->devpath, msg->subsystem, msg->driver);
133 udev->devpath_old = msg->devpath_old;
134 udev->devt = msg->devt;
136 retval = udev_device_event(&rules, udev);
138 /* run programs collected by RUN-key*/
139 if (retval == 0 && !udev->ignore_device && udev_run)
140 retval = udev_rules_run(udev);
142 udev_device_cleanup(udev);
152 static void export_event_state(struct udevd_uevent_msg *msg, enum event_state state)
154 char filename[PATH_SIZE];
155 char filename_failed[PATH_SIZE];
158 /* location of queue file */
159 snprintf(filename, sizeof(filename), "%s/"EVENT_QUEUE_DIR"/%llu", udev_root, msg->seqnum);
161 /* location of failed file */
162 strlcpy(filename_failed, udev_root, sizeof(filename_failed));
163 strlcat(filename_failed, "/", sizeof(filename_failed));
164 start = strlcat(filename_failed, EVENT_FAILED_DIR"/", sizeof(filename_failed));
165 strlcat(filename_failed, msg->devpath, sizeof(filename_failed));
166 path_encode(&filename_failed[start], sizeof(filename_failed) - start);
170 unlink(filename_failed);
171 delete_path(filename_failed);
173 create_path(filename);
174 symlink(msg->devpath, filename);
177 if (msg->devpath_old != NULL) {
178 /* "move" event - rename failed file to current name, do not delete failed */
179 char filename_failed_old[PATH_SIZE];
181 strlcpy(filename_failed_old, udev_root, sizeof(filename_failed_old));
182 strlcat(filename_failed_old, "/", sizeof(filename_failed_old));
183 start = strlcat(filename_failed_old, EVENT_FAILED_DIR"/", sizeof(filename_failed_old));
184 strlcat(filename_failed_old, msg->devpath_old, sizeof(filename_failed_old));
185 path_encode(&filename_failed_old[start], sizeof(filename) - start);
187 if (rename(filename_failed_old, filename_failed) == 0)
188 info("renamed devpath, moved failed state of '%s' to %s'",
189 msg->devpath_old, msg->devpath);
191 unlink(filename_failed);
192 delete_path(filename_failed);
196 delete_path(filename);
199 /* move failed event to the failed directory */
200 create_path(filename_failed);
201 rename(filename, filename_failed);
203 /* clean up possibly empty queue directory */
204 delete_path(filename);
211 static void msg_queue_delete(struct udevd_uevent_msg *msg)
213 list_del(&msg->node);
215 /* mark as failed, if "add" event returns non-zero */
216 if (msg->exitstatus && strcmp(msg->action, "add") == 0)
217 export_event_state(msg, EVENT_FAILED);
219 export_event_state(msg, EVENT_FINISHED);
224 static void udev_event_run(struct udevd_uevent_msg *msg)
233 close(uevent_netlink_sock);
237 close(signal_pipe[READ_END]);
238 close(signal_pipe[WRITE_END]);
241 logging_init("udevd-event");
242 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
244 retval = udev_event_process(msg);
245 info("seq %llu finished with %i", msg->seqnum, retval);
252 err("fork of child failed: %s", strerror(errno));
253 msg_queue_delete(msg);
256 /* get SIGCHLD in main loop */
257 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
258 msg->seqnum, pid, msg->action, msg->subsystem, time(NULL) - msg->queue_time);
263 static void msg_queue_insert(struct udevd_uevent_msg *msg)
265 char filename[PATH_SIZE];
268 msg->queue_time = time(NULL);
270 strlcpy(filename, udev_root, sizeof(filename));
271 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
272 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
277 len = sprintf(str, "%llu\n", msg->seqnum);
282 export_event_state(msg, EVENT_QUEUED);
283 info("seq %llu queued, '%s' '%s'", msg->seqnum, msg->action, msg->subsystem);
285 /* run one event after the other in debug mode */
287 list_add_tail(&msg->node, &running_list);
289 waitpid(msg->pid, NULL, 0);
290 msg_queue_delete(msg);
294 /* run all events with a timeout set immediately */
295 if (msg->timeout != 0) {
296 list_add_tail(&msg->node, &running_list);
301 list_add_tail(&msg->node, &exec_list);
305 static int mem_size_mb(void)
309 long int memsize = -1;
311 f = fopen("/proc/meminfo", "r");
315 while (fgets(buf, sizeof(buf), f) != NULL) {
318 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
319 memsize = value / 1024;
328 static int cpu_count(void)
334 f = fopen("/proc/stat", "r");
338 while (fgets(buf, sizeof(buf), f) != NULL) {
339 if (strncmp(buf, "cpu", 3) == 0 && isdigit(buf[3]))
349 static int running_processes(void)
355 f = fopen("/proc/stat", "r");
359 while (fgets(buf, sizeof(buf), f) != NULL) {
362 if (sscanf(buf, "procs_running %u", &value) == 1) {
372 /* return the number of process es in our session, count only until limit */
373 static int running_processes_in_session(pid_t session, int limit)
379 dir = opendir("/proc");
383 /* read process info from /proc */
384 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
390 pid_t ppid, pgrp, sess;
393 if (!isdigit(dent->d_name[0]))
396 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
397 procdir[sizeof(procdir)-1] = '\0';
399 f = open(procdir, O_RDONLY);
403 len = read(f, line, sizeof(line)-1);
411 /* skip ugly program name */
412 pos = strrchr(line, ')') + 2;
416 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
419 /* count only processes in our session */
423 /* count only running, no sleeping processes */
428 if (limit > 0 && running >= limit)
436 static int compare_devpath(const char *running, const char *waiting)
440 for (i = 0; i < PATH_SIZE; i++) {
441 /* identical device event found */
442 if (running[i] == '\0' && waiting[i] == '\0')
445 /* parent device event found */
446 if (running[i] == '\0' && waiting[i] == '/')
449 /* child device event found */
450 if (running[i] == '/' && waiting[i] == '\0')
453 /* no matching event */
454 if (running[i] != waiting[i])
461 /* lookup event for identical, parent, child, or physical device */
462 static int devpath_busy(struct udevd_uevent_msg *msg, int limit)
464 struct udevd_uevent_msg *loop_msg;
465 int childs_count = 0;
467 /* check exec-queue which may still contain delayed events we depend on */
468 list_for_each_entry(loop_msg, &exec_list, node) {
469 /* skip ourself and all later events */
470 if (loop_msg->seqnum >= msg->seqnum)
473 /* check our old name */
474 if (msg->devpath_old != NULL)
475 if (strcmp(loop_msg->devpath , msg->devpath_old) == 0)
478 /* check identical, parent, or child device event */
479 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
480 dbg("%llu, device event still pending %llu (%s)",
481 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
485 /* check physical device event (special case of parent) */
486 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
487 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
488 dbg("%llu, physical device event still pending %llu (%s)",
489 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
494 /* check run queue for still running events */
495 list_for_each_entry(loop_msg, &running_list, node) {
496 if (limit && childs_count++ > limit) {
497 dbg("%llu, maximum number (%i) of childs reached", msg->seqnum, childs_count);
501 /* check our old name */
502 if (msg->devpath_old != NULL)
503 if (strcmp(loop_msg->devpath , msg->devpath_old) == 0)
506 /* check identical, parent, or child device event */
507 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
508 dbg("%llu, device event still running %llu (%s)",
509 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
513 /* check physical device event (special case of parent) */
514 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
515 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
516 dbg("%llu, physical device event still running %llu (%s)",
517 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
524 /* serializes events for the identical and parent and child devices */
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 /* serialize and wait for parent or child events */
551 if (devpath_busy(loop_msg, max_childs) != 0) {
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, "DEVPATH_OLD=", 12) == 0)
603 msg->devpath_old = &key[12];
604 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
605 msg->physdevpath = &key[12];
606 else if (strncmp(key, "PHYSDEVDRIVER=", 14) == 0)
607 physdevdriver_key = key;
608 else if (strncmp(key, "MAJOR=", 6) == 0)
609 maj = strtoull(&key[6], NULL, 10);
610 else if (strncmp(key, "MINOR=", 6) == 0)
611 min = strtoull(&key[6], NULL, 10);
612 else if (strncmp(key, "TIMEOUT=", 8) == 0)
613 msg->timeout = strtoull(&key[8], NULL, 10);
615 msg->devt = makedev(maj, min);
616 msg->envp[i++] = "UDEVD_EVENT=1";
618 if (msg->driver == NULL && msg->physdevpath == NULL && physdevdriver_key != NULL) {
619 /* for older kernels DRIVER is empty for a bus device, export PHYSDEVDRIVER as DRIVER */
620 msg->envp[i++] = &physdevdriver_key[7];
621 msg->driver = &physdevdriver_key[14];
626 if (msg->devpath == NULL || msg->action == NULL) {
627 info("DEVPATH or ACTION missing, ignore message");
634 /* receive the udevd message from userspace */
635 static void get_ctrl_msg(void)
637 struct udevd_ctrl_msg ctrl_msg;
640 struct cmsghdr *cmsg;
643 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
647 memset(&ctrl_msg, 0x00, sizeof(struct udevd_ctrl_msg));
648 iov.iov_base = &ctrl_msg;
649 iov.iov_len = sizeof(struct udevd_ctrl_msg);
651 memset(&smsg, 0x00, sizeof(struct msghdr));
654 smsg.msg_control = cred_msg;
655 smsg.msg_controllen = sizeof(cred_msg);
657 size = recvmsg(udevd_sock, &smsg, 0);
660 err("unable to receive user udevd message: %s", strerror(errno));
663 cmsg = CMSG_FIRSTHDR(&smsg);
664 cred = (struct ucred *) CMSG_DATA(cmsg);
666 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
667 err("no sender credentials received, message ignored");
671 if (cred->uid != 0) {
672 err("sender uid=%i, message ignored", cred->uid);
676 if (strncmp(ctrl_msg.magic, UDEVD_CTRL_MAGIC, sizeof(UDEVD_CTRL_MAGIC)) != 0 ) {
677 err("message magic '%s' doesn't match, ignore it", ctrl_msg.magic);
681 switch (ctrl_msg.type) {
683 pos = strchr(ctrl_msg.buf, '=');
685 err("wrong key format '%s'", ctrl_msg.buf);
689 if (pos[1] == '\0') {
690 info("udevd message (ENV) received, unset '%s'", ctrl_msg.buf);
691 unsetenv(ctrl_msg.buf);
693 info("udevd message (ENV) received, set '%s=%s'", ctrl_msg.buf, &pos[1]);
694 setenv(ctrl_msg.buf, &pos[1], 1);
697 case UDEVD_CTRL_STOP_EXEC_QUEUE:
698 info("udevd message (STOP_EXEC_QUEUE) received");
701 case UDEVD_CTRL_START_EXEC_QUEUE:
702 info("udevd message (START_EXEC_QUEUE) received");
706 case UDEVD_CTRL_SET_LOG_LEVEL:
707 intval = (int *) ctrl_msg.buf;
708 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
709 udev_log_priority = *intval;
710 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
713 case UDEVD_CTRL_SET_MAX_CHILDS:
714 intval = (int *) ctrl_msg.buf;
715 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
716 max_childs = *intval;
718 case UDEVD_CTRL_SET_MAX_CHILDS_RUNNING:
719 intval = (int *) ctrl_msg.buf;
720 info("udevd message (UDEVD_SET_MAX_CHILDS_RUNNING) received, max_childs=%i", *intval);
721 max_childs_running = *intval;
723 case UDEVD_CTRL_RELOAD_RULES:
724 info("udevd message (RELOAD_RULES) received");
728 err("unknown control message type");
732 /* receive the kernel user event message and do some sanity checks */
733 static struct udevd_uevent_msg *get_netlink_msg(void)
735 struct udevd_uevent_msg *msg;
738 static char buffer[UEVENT_BUFFER_SIZE+512];
741 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
744 err("unable to receive kernel netlink message: %s", strerror(errno));
748 if ((size_t)size > sizeof(buffer)-1)
749 size = sizeof(buffer)-1;
751 dbg("uevent_size=%zi", size);
753 /* start of event payload */
754 bufpos = strlen(buffer)+1;
755 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
759 /* validate message */
760 pos = strchr(buffer, '@');
762 err("invalid uevent '%s'", buffer);
768 if (msg->action == NULL) {
769 info("no ACTION in payload found, skip event '%s'", buffer);
774 if (strcmp(msg->action, buffer) != 0) {
775 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
783 static void asmlinkage sig_handler(int signum)
791 /* set flag, then write to pipe if needed */
792 sigchilds_waiting = 1;
799 /* write to pipe, which will wakeup select() in our mainloop */
800 write(signal_pipe[WRITE_END], "", 1);
803 static void udev_done(int pid, int exitstatus)
805 /* find msg associated with pid and delete it */
806 struct udevd_uevent_msg *msg;
808 list_for_each_entry(msg, &running_list, node) {
809 if (msg->pid == pid) {
810 info("seq %llu, pid [%d] exit with %i, %ld seconds old", msg->seqnum, msg->pid,
811 exitstatus, time(NULL) - msg->queue_time);
812 msg->exitstatus = exitstatus;
813 msg_queue_delete(msg);
815 /* there may be events waiting with the same devpath */
822 static void reap_sigchilds(void)
828 pid = waitpid(-1, &status, WNOHANG);
831 if (WIFEXITED(status))
832 status = WEXITSTATUS(status);
833 else if (WIFSIGNALED(status))
834 status = WTERMSIG(status) + 128;
837 udev_done(pid, status);
841 static int init_udevd_socket(void)
843 struct sockaddr_un saddr;
845 const int feature_on = 1;
848 memset(&saddr, 0x00, sizeof(saddr));
849 saddr.sun_family = AF_LOCAL;
850 /* use abstract namespace for socket path */
851 strcpy(&saddr.sun_path[1], UDEVD_CTRL_SOCK_PATH);
852 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
854 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
855 if (udevd_sock == -1) {
856 err("error getting socket: %s", strerror(errno));
860 /* the bind takes care of ensuring only one copy running */
861 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
863 err("bind failed: %s", strerror(errno));
869 /* enable receiving of the sender credentials */
870 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
875 static int init_uevent_netlink_sock(void)
877 struct sockaddr_nl snl;
878 const int buffersize = 16 * 1024 * 1024;
881 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
882 snl.nl_family = AF_NETLINK;
883 snl.nl_pid = getpid();
886 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
887 if (uevent_netlink_sock == -1) {
888 err("error getting socket: %s", strerror(errno));
892 /* set receive buffersize */
893 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
895 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
897 err("bind failed: %s", strerror(errno));
898 close(uevent_netlink_sock);
899 uevent_netlink_sock = -1;
905 static void export_initial_seqnum(void)
907 char filename[PATH_SIZE];
912 strlcpy(filename, sysfs_path, sizeof(filename));
913 strlcat(filename, "/kernel/uevent_seqnum", sizeof(filename));
914 fd = open(filename, O_RDONLY);
916 len = read(fd, seqnum, sizeof(seqnum)-1);
920 strcpy(seqnum, "0\n");
923 strlcpy(filename, udev_root, sizeof(filename));
924 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
925 create_path(filename);
926 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
928 write(fd, seqnum, len);
933 int main(int argc, char *argv[], char *envp[])
937 struct sigaction act;
942 static const struct option options[] = {
943 { "daemon", 0, NULL, 'd' },
944 { "debug-trace", 0, NULL, 't' },
945 { "verbose", 0, NULL, 'v' },
946 { "help", 0, NULL, 'h' },
947 { "version", 0, NULL, 'V' },
953 logging_init("udevd");
956 dbg("version %s", UDEV_VERSION);
959 option = getopt_long(argc, argv, "dtvhV", options, NULL);
972 if (udev_log_priority < LOG_INFO)
973 udev_log_priority = LOG_INFO;
976 printf("Usage: udevd [--help] [--daemon] [--debug-trace] [--verbose] [--version]\n");
979 printf("%s\n", UDEV_VERSION);
987 fprintf(stderr, "root privileges required\n");
988 err("root privileges required");
992 /* make sure std{in,out,err} fd's are in a sane state */
993 fd = open("/dev/null", O_RDWR);
995 fprintf(stderr, "cannot open /dev/null\n");
996 err("cannot open /dev/null");
998 if (fd > STDIN_FILENO)
999 dup2(fd, STDIN_FILENO);
1000 if (write(STDOUT_FILENO, 0, 0) < 0)
1001 dup2(fd, STDOUT_FILENO);
1002 if (write(STDERR_FILENO, 0, 0) < 0)
1003 dup2(fd, STDERR_FILENO);
1005 /* init sockets to receive events */
1006 if (init_udevd_socket() < 0) {
1007 if (errno == EADDRINUSE) {
1008 fprintf(stderr, "another udev daemon already running\n");
1009 err("another udev daemon already running");
1012 fprintf(stderr, "error initializing udevd socket\n");
1013 err("error initializing udevd socket");
1019 if (init_uevent_netlink_sock() < 0) {
1020 fprintf(stderr, "error initializing netlink socket\n");
1021 err("error initializing netlink socket");
1026 /* setup signal handler pipe */
1027 retval = pipe(signal_pipe);
1029 err("error getting pipes: %s", strerror(errno));
1033 retval = fcntl(signal_pipe[READ_END], F_GETFL, 0);
1035 err("error fcntl on read pipe: %s", strerror(errno));
1038 retval = fcntl(signal_pipe[READ_END], F_SETFL, retval | O_NONBLOCK);
1040 err("error fcntl on read pipe: %s", strerror(errno));
1044 retval = fcntl(signal_pipe[WRITE_END], F_GETFL, 0);
1046 err("error fcntl on write pipe: %s", strerror(errno));
1049 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, retval | O_NONBLOCK);
1051 err("error fcntl on write pipe: %s", strerror(errno));
1055 /* parse the rules and keep them in memory */
1057 udev_rules_init(&rules, 1);
1059 export_initial_seqnum();
1067 dbg("daemonized fork running");
1070 err("fork of daemon failed: %s", strerror(errno));
1074 dbg("child [%u] running, parent exits", pid);
1080 /* redirect std{out,err} fd's */
1082 dup2(fd, STDOUT_FILENO);
1083 dup2(fd, STDERR_FILENO);
1084 if (fd > STDERR_FILENO)
1087 /* set scheduling priority for the daemon */
1088 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
1093 /* become session leader */
1095 dbg("our session is %d", sid);
1097 /* OOM_DISABLE == -17 */
1098 fd = open("/proc/self/oom_adj", O_RDWR);
1100 err("error disabling OOM: %s", strerror(errno));
1102 write(fd, "-17", 3);
1106 /* set signal handlers */
1107 memset(&act, 0x00, sizeof(struct sigaction));
1108 act.sa_handler = (void (*)(int)) sig_handler;
1109 sigemptyset(&act.sa_mask);
1110 act.sa_flags = SA_RESTART;
1111 sigaction(SIGINT, &act, NULL);
1112 sigaction(SIGTERM, &act, NULL);
1113 sigaction(SIGCHLD, &act, NULL);
1114 sigaction(SIGHUP, &act, NULL);
1116 /* watch rules directory */
1117 inotify_fd = inotify_init();
1118 if (inotify_fd >= 0) {
1119 char filename[PATH_MAX];
1121 inotify_add_watch(inotify_fd, udev_rules_dir, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1123 /* watch dynamic rules directory */
1124 strlcpy(filename, udev_root, sizeof(filename));
1125 strlcat(filename, "/"RULES_DYN_DIR, sizeof(filename));
1126 inotify_add_watch(inotify_fd, filename, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1127 } else if (errno == ENOSYS)
1128 err("the kernel does not support inotify, udevd can't monitor rules file changes");
1130 err("inotify_init failed: %s", strerror(errno));
1132 /* maximum limit of forked childs */
1133 value = getenv("UDEVD_MAX_CHILDS");
1135 max_childs = strtoul(value, NULL, 10);
1137 int memsize = mem_size_mb();
1139 max_childs = 128 + (memsize / 4);
1141 max_childs = UDEVD_MAX_CHILDS;
1143 info("initialize max_childs to %u", max_childs);
1145 /* start to throttle forking if maximum number of _running_ childs is reached */
1146 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
1148 max_childs_running = strtoull(value, NULL, 10);
1150 int cpus = cpu_count();
1152 max_childs_running = 8 + (8 * cpus);
1154 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
1156 info("initialize max_childs_running to %u", max_childs_running);
1158 /* clear environment for forked event processes */
1161 /* export log_priority , as called programs may want to follow that setting */
1162 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
1168 maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
1169 maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
1170 maxfd = UDEV_MAX(maxfd, inotify_fd);
1172 while (!udev_exit) {
1173 struct udevd_uevent_msg *msg;
1177 FD_SET(signal_pipe[READ_END], &readfds);
1178 FD_SET(udevd_sock, &readfds);
1179 FD_SET(uevent_netlink_sock, &readfds);
1180 if (inotify_fd >= 0)
1181 FD_SET(inotify_fd, &readfds);
1183 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
1186 err("error in select: %s", strerror(errno));
1190 /* get control message */
1191 if (FD_ISSET(udevd_sock, &readfds))
1194 /* get netlink message */
1195 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
1196 msg = get_netlink_msg();
1198 msg_queue_insert(msg);
1201 /* received a signal, clear our notification pipe */
1202 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
1205 read(signal_pipe[READ_END], &buf, sizeof(buf));
1208 /* rules directory inotify watch */
1209 if ((inotify_fd >= 0) && FD_ISSET(inotify_fd, &readfds)) {
1212 /* discard all possible events, we can just reload the config */
1213 if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes > 0) {
1217 buf = malloc(nbytes);
1219 err("error getting buffer for inotify, disable watching");
1223 read(inotify_fd, buf, nbytes);
1228 /* rules changed, set by inotify or a HUP signal */
1229 if (reload_config) {
1231 udev_rules_cleanup(&rules);
1232 udev_rules_init(&rules, 1);
1235 /* forked child has returned */
1236 if (sigchilds_waiting) {
1237 sigchilds_waiting = 0;
1244 msg_queue_manager();
1250 udev_rules_cleanup(&rules);
1254 if (signal_pipe[READ_END] >= 0)
1255 close(signal_pipe[READ_END]);
1256 if (signal_pipe[WRITE_END] >= 0)
1257 close(signal_pipe[WRITE_END]);
1259 if (udevd_sock >= 0)
1261 if (inotify_fd >= 0)
1263 if (uevent_netlink_sock >= 0)
1264 close(uevent_netlink_sock);