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)
79 va_start(args, format);
81 printf("[%d] ", (int) getpid());
82 vprintf(format, args);
85 vsyslog(priority, format, args);
91 static void asmlinkage udev_event_sig_handler(int signum)
93 if (signum == SIGALRM)
97 static int udev_event_process(struct udevd_uevent_msg *msg)
100 struct udevice *udev;
104 /* set signal handlers */
105 memset(&act, 0x00, sizeof(act));
106 act.sa_handler = (void (*)(int)) udev_event_sig_handler;
107 sigemptyset (&act.sa_mask);
109 sigaction(SIGALRM, &act, NULL);
111 /* reset to default */
112 act.sa_handler = SIG_DFL;
113 sigaction(SIGINT, &act, NULL);
114 sigaction(SIGTERM, &act, NULL);
115 sigaction(SIGCHLD, &act, NULL);
116 sigaction(SIGHUP, &act, NULL);
118 /* trigger timeout to prevent hanging processes */
119 alarm(UDEV_ALARM_TIMEOUT);
121 /* reconstruct event environment from message */
122 for (i = 0; msg->envp[i]; i++)
123 putenv(msg->envp[i]);
125 udev = udev_device_init(NULL);
128 strlcpy(udev->action, msg->action, sizeof(udev->action));
129 sysfs_device_set_values(udev->dev, msg->devpath, msg->subsystem, msg->driver);
130 udev->devpath_old = msg->devpath_old;
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 retval = udev_rules_run(udev);
139 udev_device_cleanup(udev);
149 static void export_event_state(struct udevd_uevent_msg *msg, enum event_state state)
151 char filename[PATH_SIZE];
152 char filename_failed[PATH_SIZE];
155 /* location of queue file */
156 snprintf(filename, sizeof(filename), "%s/"EVENT_QUEUE_DIR"/%llu", udev_root, msg->seqnum);
158 /* location of failed file */
159 strlcpy(filename_failed, udev_root, sizeof(filename_failed));
160 strlcat(filename_failed, "/", sizeof(filename_failed));
161 start = strlcat(filename_failed, EVENT_FAILED_DIR"/", sizeof(filename_failed));
162 strlcat(filename_failed, msg->devpath, sizeof(filename_failed));
163 path_encode(&filename_failed[start], sizeof(filename_failed) - start);
167 unlink(filename_failed);
168 delete_path(filename_failed);
170 create_path(filename);
171 symlink(msg->devpath, filename);
174 if (msg->devpath_old != NULL) {
175 /* "move" event - rename failed file to current name, do not delete failed */
176 char filename_failed_old[PATH_SIZE];
178 strlcpy(filename_failed_old, udev_root, sizeof(filename_failed_old));
179 strlcat(filename_failed_old, "/", sizeof(filename_failed_old));
180 start = strlcat(filename_failed_old, EVENT_FAILED_DIR"/", sizeof(filename_failed_old));
181 strlcat(filename_failed_old, msg->devpath_old, sizeof(filename_failed_old));
182 path_encode(&filename_failed_old[start], sizeof(filename) - start);
184 if (rename(filename_failed_old, filename_failed) == 0)
185 info("renamed devpath, moved failed state of '%s' to %s'",
186 msg->devpath_old, msg->devpath);
188 unlink(filename_failed);
189 delete_path(filename_failed);
193 delete_path(filename);
196 /* move failed event to the failed directory */
197 create_path(filename_failed);
198 rename(filename, filename_failed);
200 /* clean up possibly empty queue directory */
201 delete_path(filename);
208 static void msg_queue_delete(struct udevd_uevent_msg *msg)
210 list_del(&msg->node);
212 /* mark as failed, if "add" event returns non-zero */
213 if (msg->exitstatus && strcmp(msg->action, "add") == 0)
214 export_event_state(msg, EVENT_FAILED);
216 export_event_state(msg, EVENT_FINISHED);
221 static void udev_event_run(struct udevd_uevent_msg *msg)
230 close(uevent_netlink_sock);
234 close(signal_pipe[READ_END]);
235 close(signal_pipe[WRITE_END]);
238 logging_init("udevd-event");
239 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
241 retval = udev_event_process(msg);
242 info("seq %llu finished with %i", msg->seqnum, retval);
249 err("fork of child failed: %s", strerror(errno));
250 msg_queue_delete(msg);
253 /* get SIGCHLD in main loop */
254 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
255 msg->seqnum, pid, msg->action, msg->subsystem, time(NULL) - msg->queue_time);
260 static void msg_queue_insert(struct udevd_uevent_msg *msg)
262 char filename[PATH_SIZE];
265 msg->queue_time = time(NULL);
267 strlcpy(filename, udev_root, sizeof(filename));
268 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
269 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
274 len = sprintf(str, "%llu\n", msg->seqnum);
279 export_event_state(msg, EVENT_QUEUED);
280 info("seq %llu queued, '%s' '%s'", msg->seqnum, msg->action, msg->subsystem);
282 /* run one event after the other in debug mode */
284 list_add_tail(&msg->node, &running_list);
286 waitpid(msg->pid, NULL, 0);
287 msg_queue_delete(msg);
291 /* run all events with a timeout set immediately */
292 if (msg->timeout != 0) {
293 list_add_tail(&msg->node, &running_list);
298 list_add_tail(&msg->node, &exec_list);
302 static int mem_size_mb(void)
306 long int memsize = -1;
308 f = fopen("/proc/meminfo", "r");
312 while (fgets(buf, sizeof(buf), f) != NULL) {
315 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
316 memsize = value / 1024;
325 static int cpu_count(void)
331 f = fopen("/proc/stat", "r");
335 while (fgets(buf, sizeof(buf), f) != NULL) {
336 if (strncmp(buf, "cpu", 3) == 0 && isdigit(buf[3]))
346 static int running_processes(void)
352 f = fopen("/proc/stat", "r");
356 while (fgets(buf, sizeof(buf), f) != NULL) {
359 if (sscanf(buf, "procs_running %u", &value) == 1) {
369 /* return the number of process es in our session, count only until limit */
370 static int running_processes_in_session(pid_t session, int limit)
376 dir = opendir("/proc");
380 /* read process info from /proc */
381 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
387 pid_t ppid, pgrp, sess;
390 if (!isdigit(dent->d_name[0]))
393 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
394 procdir[sizeof(procdir)-1] = '\0';
396 f = open(procdir, O_RDONLY);
400 len = read(f, line, sizeof(line)-1);
408 /* skip ugly program name */
409 pos = strrchr(line, ')') + 2;
413 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
416 /* count only processes in our session */
420 /* count only running, no sleeping processes */
425 if (limit > 0 && running >= limit)
433 static int compare_devpath(const char *running, const char *waiting)
437 for (i = 0; i < PATH_SIZE; i++) {
438 /* identical device event found */
439 if (running[i] == '\0' && waiting[i] == '\0')
442 /* parent device event found */
443 if (running[i] == '\0' && waiting[i] == '/')
446 /* child device event found */
447 if (running[i] == '/' && waiting[i] == '\0')
450 /* no matching event */
451 if (running[i] != waiting[i])
458 /* lookup event for identical, parent, child, or physical device */
459 static int devpath_busy(struct udevd_uevent_msg *msg, int limit)
461 struct udevd_uevent_msg *loop_msg;
462 int childs_count = 0;
464 /* check exec-queue which may still contain delayed events we depend on */
465 list_for_each_entry(loop_msg, &exec_list, node) {
466 /* skip ourself and all later events */
467 if (loop_msg->seqnum >= msg->seqnum)
470 /* check our old name */
471 if (msg->devpath_old != NULL)
472 if (strcmp(loop_msg->devpath , msg->devpath_old) == 0)
475 /* check identical, parent, or child device event */
476 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
477 dbg("%llu, device event still pending %llu (%s)",
478 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
482 /* check physical device event (special case of parent) */
483 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
484 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
485 dbg("%llu, physical device event still pending %llu (%s)",
486 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
491 /* check run queue for still running events */
492 list_for_each_entry(loop_msg, &running_list, node) {
493 if (limit && childs_count++ > limit) {
494 dbg("%llu, maximum number (%i) of childs reached", msg->seqnum, childs_count);
498 /* check our old name */
499 if (msg->devpath_old != NULL)
500 if (strcmp(loop_msg->devpath , msg->devpath_old) == 0)
503 /* check identical, parent, or child device event */
504 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
505 dbg("%llu, device event still running %llu (%s)",
506 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
510 /* check physical device event (special case of parent) */
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);
521 /* serializes events for the identical and parent and child devices */
522 static void msg_queue_manager(void)
524 struct udevd_uevent_msg *loop_msg;
525 struct udevd_uevent_msg *tmp_msg;
528 if (list_empty(&exec_list))
531 running = running_processes();
532 dbg("%d processes runnning on system", running);
534 running = max_childs_running;
536 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
537 /* check running processes in our session and possibly throttle */
538 if (running >= max_childs_running) {
539 running = running_processes_in_session(sid, max_childs_running+10);
540 dbg("at least %d processes running in session", running);
541 if (running >= max_childs_running) {
542 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
547 /* serialize and wait for parent or child events */
548 if (devpath_busy(loop_msg, max_childs) != 0) {
549 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
553 /* move event to run list */
554 list_move_tail(&loop_msg->node, &running_list);
555 udev_event_run(loop_msg);
557 dbg("moved seq %llu to running list", loop_msg->seqnum);
561 static struct udevd_uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
565 struct udevd_uevent_msg *msg;
566 char *physdevdriver_key = NULL;
570 msg = malloc(sizeof(struct udevd_uevent_msg) + buf_size);
573 memset(msg, 0x00, sizeof(struct udevd_uevent_msg) + buf_size);
575 /* copy environment buffer and reconstruct envp */
576 memcpy(msg->envbuf, buf, buf_size);
578 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
582 key = &msg->envbuf[bufpos];
583 keylen = strlen(key);
585 bufpos += keylen + 1;
586 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
588 /* remember some keys for further processing */
589 if (strncmp(key, "ACTION=", 7) == 0)
590 msg->action = &key[7];
591 else if (strncmp(key, "DEVPATH=", 8) == 0)
592 msg->devpath = &key[8];
593 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
594 msg->subsystem = &key[10];
595 else if (strncmp(key, "DRIVER=", 7) == 0)
596 msg->driver = &key[7];
597 else if (strncmp(key, "SEQNUM=", 7) == 0)
598 msg->seqnum = strtoull(&key[7], NULL, 10);
599 else if (strncmp(key, "DEVPATH_OLD=", 12) == 0)
600 msg->devpath_old = &key[12];
601 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
602 msg->physdevpath = &key[12];
603 else if (strncmp(key, "PHYSDEVDRIVER=", 14) == 0)
604 physdevdriver_key = key;
605 else if (strncmp(key, "MAJOR=", 6) == 0)
606 maj = strtoull(&key[6], NULL, 10);
607 else if (strncmp(key, "MINOR=", 6) == 0)
608 min = strtoull(&key[6], NULL, 10);
609 else if (strncmp(key, "TIMEOUT=", 8) == 0)
610 msg->timeout = strtoull(&key[8], NULL, 10);
612 msg->devt = makedev(maj, min);
613 msg->envp[i++] = "UDEVD_EVENT=1";
615 if (msg->driver == NULL && msg->physdevpath == NULL && physdevdriver_key != NULL) {
616 /* for older kernels DRIVER is empty for a bus device, export PHYSDEVDRIVER as DRIVER */
617 msg->envp[i++] = &physdevdriver_key[7];
618 msg->driver = &physdevdriver_key[14];
623 if (msg->devpath == NULL || msg->action == NULL) {
624 info("DEVPATH or ACTION missing, ignore message");
631 /* receive the udevd message from userspace */
632 static void get_ctrl_msg(void)
634 struct udevd_ctrl_msg ctrl_msg;
637 struct cmsghdr *cmsg;
640 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) {
680 pos = strchr(ctrl_msg.buf, '=');
682 err("wrong key format '%s'", ctrl_msg.buf);
686 if (pos[1] == '\0') {
687 info("udevd message (ENV) received, unset '%s'", ctrl_msg.buf);
688 unsetenv(ctrl_msg.buf);
690 info("udevd message (ENV) received, set '%s=%s'", ctrl_msg.buf, &pos[1]);
691 setenv(ctrl_msg.buf, &pos[1], 1);
694 case UDEVD_CTRL_STOP_EXEC_QUEUE:
695 info("udevd message (STOP_EXEC_QUEUE) received");
698 case UDEVD_CTRL_START_EXEC_QUEUE:
699 info("udevd message (START_EXEC_QUEUE) received");
703 case UDEVD_CTRL_SET_LOG_LEVEL:
704 intval = (int *) ctrl_msg.buf;
705 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
706 udev_log_priority = *intval;
707 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
710 case UDEVD_CTRL_SET_MAX_CHILDS:
711 intval = (int *) ctrl_msg.buf;
712 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
713 max_childs = *intval;
715 case UDEVD_CTRL_SET_MAX_CHILDS_RUNNING:
716 intval = (int *) ctrl_msg.buf;
717 info("udevd message (UDEVD_SET_MAX_CHILDS_RUNNING) received, max_childs=%i", *intval);
718 max_childs_running = *intval;
720 case UDEVD_CTRL_RELOAD_RULES:
721 info("udevd message (RELOAD_RULES) received");
725 err("unknown control message type");
729 /* receive the kernel user event message and do some sanity checks */
730 static struct udevd_uevent_msg *get_netlink_msg(void)
732 struct udevd_uevent_msg *msg;
735 static char buffer[UEVENT_BUFFER_SIZE+512];
738 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
741 err("unable to receive kernel netlink message: %s", strerror(errno));
745 if ((size_t)size > sizeof(buffer)-1)
746 size = sizeof(buffer)-1;
748 dbg("uevent_size=%zi", size);
750 /* start of event payload */
751 bufpos = strlen(buffer)+1;
752 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
756 /* validate message */
757 pos = strchr(buffer, '@');
759 err("invalid uevent '%s'", buffer);
765 if (msg->action == NULL) {
766 info("no ACTION in payload found, skip event '%s'", buffer);
771 if (strcmp(msg->action, buffer) != 0) {
772 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
780 static void asmlinkage sig_handler(int signum)
788 /* set flag, then write to pipe if needed */
789 sigchilds_waiting = 1;
796 /* write to pipe, which will wakeup select() in our mainloop */
797 write(signal_pipe[WRITE_END], "", 1);
800 static void udev_done(int pid, int exitstatus)
802 /* find msg associated with pid and delete it */
803 struct udevd_uevent_msg *msg;
805 list_for_each_entry(msg, &running_list, node) {
806 if (msg->pid == pid) {
807 info("seq %llu, pid [%d] exit with %i, %ld seconds old", msg->seqnum, msg->pid,
808 exitstatus, time(NULL) - msg->queue_time);
809 msg->exitstatus = exitstatus;
810 msg_queue_delete(msg);
812 /* there may be events waiting with the same devpath */
819 static void reap_sigchilds(void)
825 pid = waitpid(-1, &status, WNOHANG);
828 if (WIFEXITED(status))
829 status = WEXITSTATUS(status);
830 else if (WIFSIGNALED(status))
831 status = WTERMSIG(status) + 128;
834 udev_done(pid, status);
838 static int init_udevd_socket(void)
840 struct sockaddr_un saddr;
842 const int feature_on = 1;
845 memset(&saddr, 0x00, sizeof(saddr));
846 saddr.sun_family = AF_LOCAL;
847 /* use abstract namespace for socket path */
848 strcpy(&saddr.sun_path[1], UDEVD_CTRL_SOCK_PATH);
849 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
851 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
852 if (udevd_sock == -1) {
853 err("error getting socket: %s", strerror(errno));
857 /* the bind takes care of ensuring only one copy running */
858 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
860 err("bind failed: %s", strerror(errno));
866 /* enable receiving of the sender credentials */
867 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
872 static int init_uevent_netlink_sock(void)
874 struct sockaddr_nl snl;
875 const int buffersize = 16 * 1024 * 1024;
878 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
879 snl.nl_family = AF_NETLINK;
880 snl.nl_pid = getpid();
883 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
884 if (uevent_netlink_sock == -1) {
885 err("error getting socket: %s", strerror(errno));
889 /* set receive buffersize */
890 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
892 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
894 err("bind failed: %s", strerror(errno));
895 close(uevent_netlink_sock);
896 uevent_netlink_sock = -1;
902 static void export_initial_seqnum(void)
904 char filename[PATH_SIZE];
909 strlcpy(filename, sysfs_path, sizeof(filename));
910 strlcat(filename, "/kernel/uevent_seqnum", sizeof(filename));
911 fd = open(filename, O_RDONLY);
913 len = read(fd, seqnum, sizeof(seqnum)-1);
917 strcpy(seqnum, "0\n");
920 strlcpy(filename, udev_root, sizeof(filename));
921 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
922 create_path(filename);
923 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
925 write(fd, seqnum, len);
930 int main(int argc, char *argv[], char *envp[])
934 struct sigaction act;
939 static const struct option options[] = {
940 { "daemon", 0, NULL, 'd' },
941 { "debug-trace", 0, NULL, 't' },
942 { "verbose", 0, NULL, 'v' },
943 { "help", 0, NULL, 'h' },
944 { "version", 0, NULL, 'V' },
950 logging_init("udevd");
953 dbg("version %s", UDEV_VERSION);
956 option = getopt_long(argc, argv, "dtvhV", options, NULL);
969 if (udev_log_priority < LOG_INFO)
970 udev_log_priority = LOG_INFO;
973 printf("Usage: udevd [--help] [--daemon] [--debug-trace] [--verbose] [--version]\n");
976 printf("%s\n", UDEV_VERSION);
984 fprintf(stderr, "root privileges required\n");
985 err("root privileges required");
989 /* make sure std{in,out,err} fd's are in a sane state */
990 fd = open("/dev/null", O_RDWR);
992 fprintf(stderr, "cannot open /dev/null\n");
993 err("cannot open /dev/null");
995 if (fd > STDIN_FILENO)
996 dup2(fd, STDIN_FILENO);
997 if (write(STDOUT_FILENO, 0, 0) < 0)
998 dup2(fd, STDOUT_FILENO);
999 if (write(STDERR_FILENO, 0, 0) < 0)
1000 dup2(fd, STDERR_FILENO);
1002 /* init sockets to receive events */
1003 if (init_udevd_socket() < 0) {
1004 if (errno == EADDRINUSE) {
1005 fprintf(stderr, "another udev daemon already running\n");
1006 err("another udev daemon already running");
1009 fprintf(stderr, "error initializing udevd socket\n");
1010 err("error initializing udevd socket");
1016 if (init_uevent_netlink_sock() < 0) {
1017 fprintf(stderr, "error initializing netlink socket\n");
1018 err("error initializing netlink socket");
1023 /* setup signal handler pipe */
1024 retval = pipe(signal_pipe);
1026 err("error getting pipes: %s", strerror(errno));
1030 retval = fcntl(signal_pipe[READ_END], F_GETFL, 0);
1032 err("error fcntl on read pipe: %s", strerror(errno));
1035 retval = fcntl(signal_pipe[READ_END], F_SETFL, retval | O_NONBLOCK);
1037 err("error fcntl on read pipe: %s", strerror(errno));
1041 retval = fcntl(signal_pipe[WRITE_END], F_GETFL, 0);
1043 err("error fcntl on write pipe: %s", strerror(errno));
1046 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, retval | O_NONBLOCK);
1048 err("error fcntl on write pipe: %s", strerror(errno));
1052 /* parse the rules and keep them in memory */
1054 udev_rules_init(&rules, 1);
1056 export_initial_seqnum();
1064 dbg("daemonized fork running");
1067 err("fork of daemon failed: %s", strerror(errno));
1071 dbg("child [%u] running, parent exits", pid);
1077 /* redirect std{out,err} fd's */
1079 dup2(fd, STDOUT_FILENO);
1080 dup2(fd, STDERR_FILENO);
1081 if (fd > STDERR_FILENO)
1084 /* set scheduling priority for the daemon */
1085 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
1090 /* become session leader */
1092 dbg("our session is %d", sid);
1094 /* OOM_DISABLE == -17 */
1095 fd = open("/proc/self/oom_adj", O_RDWR);
1097 err("error disabling OOM: %s", strerror(errno));
1099 write(fd, "-17", 3);
1103 /* set signal handlers */
1104 memset(&act, 0x00, sizeof(struct sigaction));
1105 act.sa_handler = (void (*)(int)) sig_handler;
1106 sigemptyset(&act.sa_mask);
1107 act.sa_flags = SA_RESTART;
1108 sigaction(SIGINT, &act, NULL);
1109 sigaction(SIGTERM, &act, NULL);
1110 sigaction(SIGCHLD, &act, NULL);
1111 sigaction(SIGHUP, &act, NULL);
1113 /* watch rules directory */
1114 inotify_fd = inotify_init();
1115 if (inotify_fd >= 0) {
1116 char filename[PATH_MAX];
1118 inotify_add_watch(inotify_fd, udev_rules_dir, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1120 /* watch dynamic rules directory */
1121 strlcpy(filename, udev_root, sizeof(filename));
1122 strlcat(filename, "/"RULES_DYN_DIR, sizeof(filename));
1123 inotify_add_watch(inotify_fd, filename, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1124 } else if (errno == ENOSYS)
1125 err("the kernel does not support inotify, udevd can't monitor rules file changes");
1127 err("inotify_init failed: %s", strerror(errno));
1129 /* maximum limit of forked childs */
1130 value = getenv("UDEVD_MAX_CHILDS");
1132 max_childs = strtoul(value, NULL, 10);
1134 int memsize = mem_size_mb();
1136 max_childs = 128 + (memsize / 4);
1138 max_childs = UDEVD_MAX_CHILDS;
1140 info("initialize max_childs to %u", max_childs);
1142 /* start to throttle forking if maximum number of _running_ childs is reached */
1143 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
1145 max_childs_running = strtoull(value, NULL, 10);
1147 int cpus = cpu_count();
1149 max_childs_running = 8 + (8 * cpus);
1151 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
1153 info("initialize max_childs_running to %u", max_childs_running);
1155 /* clear environment for forked event processes */
1158 /* export log_priority , as called programs may want to follow that setting */
1159 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
1165 maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
1166 maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
1167 maxfd = UDEV_MAX(maxfd, inotify_fd);
1169 while (!udev_exit) {
1170 struct udevd_uevent_msg *msg;
1174 FD_SET(signal_pipe[READ_END], &readfds);
1175 FD_SET(udevd_sock, &readfds);
1176 FD_SET(uevent_netlink_sock, &readfds);
1177 if (inotify_fd >= 0)
1178 FD_SET(inotify_fd, &readfds);
1180 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
1183 err("error in select: %s", strerror(errno));
1187 /* get control message */
1188 if (FD_ISSET(udevd_sock, &readfds))
1191 /* get netlink message */
1192 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
1193 msg = get_netlink_msg();
1195 msg_queue_insert(msg);
1198 /* received a signal, clear our notification pipe */
1199 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
1202 read(signal_pipe[READ_END], &buf, sizeof(buf));
1205 /* rules directory inotify watch */
1206 if ((inotify_fd >= 0) && FD_ISSET(inotify_fd, &readfds)) {
1209 /* discard all possible events, we can just reload the config */
1210 if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes > 0) {
1214 buf = malloc(nbytes);
1216 err("error getting buffer for inotify, disable watching");
1220 read(inotify_fd, buf, nbytes);
1225 /* rules changed, set by inotify or a HUP signal */
1226 if (reload_config) {
1228 udev_rules_cleanup(&rules);
1229 udev_rules_init(&rules, 1);
1232 /* forked child has returned */
1233 if (sigchilds_waiting) {
1234 sigchilds_waiting = 0;
1241 msg_queue_manager();
1247 udev_rules_cleanup(&rules);
1251 if (signal_pipe[READ_END] >= 0)
1252 close(signal_pipe[READ_END]);
1253 if (signal_pipe[WRITE_END] >= 0)
1254 close(signal_pipe[WRITE_END]);
1256 if (udevd_sock >= 0)
1258 if (inotify_fd >= 0)
1260 if (uevent_netlink_sock >= 0)
1261 close(uevent_netlink_sock);