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->devt = msg->devt;
135 retval = udev_device_event(&rules, udev);
137 /* run programs collected by RUN-key*/
138 if (retval == 0 && !udev->ignore_device && udev_run) {
139 struct name_entry *name_loop;
141 dbg("executing run list");
142 list_for_each_entry(name_loop, &udev->run_list, node) {
143 if (strncmp(name_loop->name, "socket:", strlen("socket:")) == 0)
144 pass_env_to_socket(&name_loop->name[strlen("socket:")], udev->dev->devpath, udev->action);
146 char program[PATH_SIZE];
148 strlcpy(program, name_loop->name, sizeof(program));
149 udev_rules_apply_format(udev, program, sizeof(program));
150 if (run_program(program, udev->dev->subsystem, NULL, 0, NULL,
151 (udev_log_priority >= LOG_INFO)) != 0)
152 if (!name_loop->ignore_error)
158 udev_device_cleanup(udev);
168 static void export_event_state(struct udevd_uevent_msg *msg, enum event_state state)
170 char filename[PATH_SIZE];
171 char filename_failed[PATH_SIZE];
173 struct udevd_uevent_msg *loop_msg;
176 /* add location of queue files */
177 strlcpy(filename, udev_root, sizeof(filename));
178 strlcat(filename, "/", sizeof(filename));
179 start = strlcat(filename, EVENT_QUEUE_DIR"/", sizeof(filename));
180 strlcat(filename, msg->devpath, sizeof(filename));
181 path_encode(&filename[start], sizeof(filename) - start);
183 /* add location of failed files */
184 strlcpy(filename_failed, udev_root, sizeof(filename_failed));
185 strlcat(filename_failed, "/", sizeof(filename_failed));
186 start = strlcat(filename_failed, EVENT_FAILED_DIR"/", sizeof(filename_failed));
187 strlcat(filename_failed, msg->devpath, sizeof(filename_failed));
188 path_encode(&filename_failed[start], sizeof(filename) - start);
192 unlink(filename_failed);
193 delete_path(filename_failed);
194 create_path(filename);
195 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
201 unlink(filename_failed);
202 delete_path(filename_failed);
204 /* don't remove, if events for the same path are still pending */
205 list_for_each_entry(loop_msg, &running_list, node)
206 if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
209 list_for_each_entry(loop_msg, &exec_list, node)
210 if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
213 /* move failed events to the failed directory */
214 if (state == EVENT_FAILED) {
215 create_path(filename_failed);
216 rename(filename, filename_failed);
221 /* clean up the queue directory */
222 delete_path(filename);
228 static void msg_queue_delete(struct udevd_uevent_msg *msg)
230 list_del(&msg->node);
232 /* mark as failed, if add event returns non-zero */
233 if (msg->exitstatus && strcmp(msg->action, "add") == 0)
234 export_event_state(msg, EVENT_FAILED);
236 export_event_state(msg, EVENT_FINISHED);
241 static void udev_event_run(struct udevd_uevent_msg *msg)
250 close(uevent_netlink_sock);
254 close(signal_pipe[READ_END]);
255 close(signal_pipe[WRITE_END]);
258 logging_init("udevd-event");
259 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
261 retval = udev_event_process(msg);
262 info("seq %llu finished with %i", msg->seqnum, retval);
269 err("fork of child failed: %s", strerror(errno));
270 msg_queue_delete(msg);
273 /* get SIGCHLD in main loop */
274 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
275 msg->seqnum, pid, msg->action, msg->subsystem, time(NULL) - msg->queue_time);
280 static void msg_queue_insert(struct udevd_uevent_msg *msg)
282 char filename[PATH_SIZE];
285 msg->queue_time = time(NULL);
287 strlcpy(filename, udev_root, sizeof(filename));
288 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
289 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
294 len = sprintf(str, "%llu\n", msg->seqnum);
299 export_event_state(msg, EVENT_QUEUED);
301 /* run one event after the other in debug mode */
303 list_add_tail(&msg->node, &running_list);
305 waitpid(msg->pid, NULL, 0);
306 msg_queue_delete(msg);
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)
325 long int memsize = -1;
327 f = fopen("/proc/meminfo", "r");
331 while (fgets(buf, sizeof(buf), f) != NULL) {
334 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
335 memsize = value / 1024;
344 static int cpu_count(void)
350 f = fopen("/proc/stat", "r");
354 while (fgets(buf, sizeof(buf), f) != NULL) {
355 if (strncmp(buf, "cpu", 3) == 0 && isdigit(buf[3]))
365 static int running_processes(void)
371 f = fopen("/proc/stat", "r");
375 while (fgets(buf, sizeof(buf), f) != NULL) {
378 if (sscanf(buf, "procs_running %u", &value) == 1) {
388 /* return the number of process es in our session, count only until limit */
389 static int running_processes_in_session(pid_t session, int limit)
395 dir = opendir("/proc");
399 /* read process info from /proc */
400 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
406 pid_t ppid, pgrp, sess;
409 if (!isdigit(dent->d_name[0]))
412 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
413 procdir[sizeof(procdir)-1] = '\0';
415 f = open(procdir, O_RDONLY);
419 len = read(f, line, sizeof(line)-1);
427 /* skip ugly program name */
428 pos = strrchr(line, ')') + 2;
432 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
435 /* count only processes in our session */
439 /* count only running, no sleeping processes */
444 if (limit > 0 && running >= limit)
452 static int compare_devpath(const char *running, const char *waiting)
456 for (i = 0; i < PATH_SIZE; i++) {
457 /* identical device event found */
458 if (running[i] == '\0' && waiting[i] == '\0')
461 /* parent device event found */
462 if (running[i] == '\0' && waiting[i] == '/')
465 /* child device event found */
466 if (running[i] == '/' && waiting[i] == '\0')
469 /* no matching event */
470 if (running[i] != waiting[i])
477 /* lookup event for identical, parent, child, or physical device */
478 static int devpath_busy(struct udevd_uevent_msg *msg, int limit)
480 struct udevd_uevent_msg *loop_msg;
481 int childs_count = 0;
483 /* check exec-queue which may still contain delayed events we depend on */
484 list_for_each_entry(loop_msg, &exec_list, node) {
485 /* skip ourself and all later events */
486 if (loop_msg->seqnum >= msg->seqnum)
489 /* check identical, parent, or child device event */
490 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
491 dbg("%llu, device event still pending %llu (%s)",
492 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
496 /* check physical device event (special case of parent) */
497 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
498 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
499 dbg("%llu, physical device event still pending %llu (%s)",
500 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
505 /* check runing-queue for still running events */
506 list_for_each_entry(loop_msg, &running_list, node) {
507 if (limit && childs_count++ > limit) {
508 dbg("%llu, maximum number (%i) of childs reached", msg->seqnum, childs_count);
512 /* check identical, parent, or child device event */
513 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
514 dbg("%llu, device event still running %llu (%s)",
515 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
519 /* check physical device event (special case of parent) */
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);
530 /* serializes events for the identical and parent and child devices */
531 static void msg_queue_manager(void)
533 struct udevd_uevent_msg *loop_msg;
534 struct udevd_uevent_msg *tmp_msg;
537 if (list_empty(&exec_list))
540 running = running_processes();
541 dbg("%d processes runnning on system", running);
543 running = max_childs_running;
545 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
546 /* check running processes in our session and possibly throttle */
547 if (running >= max_childs_running) {
548 running = running_processes_in_session(sid, max_childs_running+10);
549 dbg("at least %d processes running in session", running);
550 if (running >= max_childs_running) {
551 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
556 /* serialize and wait for parent or child events */
557 if (devpath_busy(loop_msg, max_childs) != 0) {
558 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
562 /* move event to run list */
563 list_move_tail(&loop_msg->node, &running_list);
564 udev_event_run(loop_msg);
566 dbg("moved seq %llu to running list", loop_msg->seqnum);
570 static struct udevd_uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
574 struct udevd_uevent_msg *msg;
575 char *physdevdriver_key = NULL;
579 msg = malloc(sizeof(struct udevd_uevent_msg) + buf_size);
582 memset(msg, 0x00, sizeof(struct udevd_uevent_msg) + buf_size);
584 /* copy environment buffer and reconstruct envp */
585 memcpy(msg->envbuf, buf, buf_size);
587 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
591 key = &msg->envbuf[bufpos];
592 keylen = strlen(key);
594 bufpos += keylen + 1;
595 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
597 /* remember some keys for further processing */
598 if (strncmp(key, "ACTION=", 7) == 0)
599 msg->action = &key[7];
600 else if (strncmp(key, "DEVPATH=", 8) == 0)
601 msg->devpath = &key[8];
602 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
603 msg->subsystem = &key[10];
604 else if (strncmp(key, "DRIVER=", 7) == 0)
605 msg->driver = &key[7];
606 else if (strncmp(key, "SEQNUM=", 7) == 0)
607 msg->seqnum = strtoull(&key[7], NULL, 10);
608 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
609 msg->physdevpath = &key[12];
610 else if (strncmp(key, "PHYSDEVDRIVER=", 14) == 0)
611 physdevdriver_key = key;
612 else if (strncmp(key, "MAJOR=", 6) == 0)
613 maj = strtoull(&key[6], NULL, 10);
614 else if (strncmp(key, "MINOR=", 6) == 0)
615 min = strtoull(&key[6], NULL, 10);
616 else if (strncmp(key, "TIMEOUT=", 8) == 0)
617 msg->timeout = strtoull(&key[8], NULL, 10);
619 msg->devt = makedev(maj, min);
620 msg->envp[i++] = "UDEVD_EVENT=1";
622 if (msg->driver == NULL && msg->physdevpath == NULL && physdevdriver_key != NULL) {
623 /* for older kernels DRIVER is empty for a bus device, export PHYSDEVDRIVER as DRIVER */
624 msg->envp[i++] = &physdevdriver_key[7];
625 msg->driver = &physdevdriver_key[14];
630 if (msg->devpath == NULL || msg->action == NULL) {
631 info("DEVPATH or ACTION missing, ignore message");
638 /* receive the udevd message from userspace */
639 static void get_ctrl_msg(void)
641 struct udevd_ctrl_msg ctrl_msg;
644 struct cmsghdr *cmsg;
647 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) {
687 pos = strchr(ctrl_msg.buf, '=');
689 err("wrong key format '%s'", ctrl_msg.buf);
693 if (pos[1] == '\0') {
694 info("udevd message (ENV) received, unset '%s'", ctrl_msg.buf);
695 unsetenv(ctrl_msg.buf);
697 info("udevd message (ENV) received, set '%s=%s'", ctrl_msg.buf, &pos[1]);
698 setenv(ctrl_msg.buf, &pos[1], 1);
701 case UDEVD_CTRL_STOP_EXEC_QUEUE:
702 info("udevd message (STOP_EXEC_QUEUE) received");
705 case UDEVD_CTRL_START_EXEC_QUEUE:
706 info("udevd message (START_EXEC_QUEUE) received");
710 case UDEVD_CTRL_SET_LOG_LEVEL:
711 intval = (int *) ctrl_msg.buf;
712 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
713 udev_log_priority = *intval;
714 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
717 case UDEVD_CTRL_SET_MAX_CHILDS:
718 intval = (int *) ctrl_msg.buf;
719 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
720 max_childs = *intval;
722 case UDEVD_CTRL_SET_MAX_CHILDS_RUNNING:
723 intval = (int *) ctrl_msg.buf;
724 info("udevd message (UDEVD_SET_MAX_CHILDS_RUNNING) received, max_childs=%i", *intval);
725 max_childs_running = *intval;
727 case UDEVD_CTRL_RELOAD_RULES:
728 info("udevd message (RELOAD_RULES) received");
732 err("unknown control message type");
736 /* receive the kernel user event message and do some sanity checks */
737 static struct udevd_uevent_msg *get_netlink_msg(void)
739 struct udevd_uevent_msg *msg;
742 static char buffer[UEVENT_BUFFER_SIZE+512];
745 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
748 err("unable to receive kernel netlink message: %s", strerror(errno));
752 if ((size_t)size > sizeof(buffer)-1)
753 size = sizeof(buffer)-1;
755 dbg("uevent_size=%zi", size);
757 /* start of event payload */
758 bufpos = strlen(buffer)+1;
759 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
763 /* validate message */
764 pos = strchr(buffer, '@');
766 err("invalid uevent '%s'", buffer);
772 if (msg->action == NULL) {
773 info("no ACTION in payload found, skip event '%s'", buffer);
778 if (strcmp(msg->action, buffer) != 0) {
779 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
787 static void asmlinkage sig_handler(int signum)
795 /* set flag, then write to pipe if needed */
796 sigchilds_waiting = 1;
803 /* write to pipe, which will wakeup select() in our mainloop */
804 write(signal_pipe[WRITE_END], "", 1);
807 static void udev_done(int pid, int exitstatus)
809 /* find msg associated with pid and delete it */
810 struct udevd_uevent_msg *msg;
812 list_for_each_entry(msg, &running_list, node) {
813 if (msg->pid == pid) {
814 info("seq %llu, pid [%d] exit with %i, %ld seconds old", msg->seqnum, msg->pid,
815 exitstatus, time(NULL) - msg->queue_time);
816 msg->exitstatus = exitstatus;
817 msg_queue_delete(msg);
819 /* there may be events waiting with the same devpath */
826 static void reap_sigchilds(void)
832 pid = waitpid(-1, &status, WNOHANG);
835 if (WIFEXITED(status))
836 status = WEXITSTATUS(status);
837 else if (WIFSIGNALED(status))
838 status = WTERMSIG(status) + 128;
841 udev_done(pid, status);
845 static int init_udevd_socket(void)
847 struct sockaddr_un saddr;
849 const int feature_on = 1;
852 memset(&saddr, 0x00, sizeof(saddr));
853 saddr.sun_family = AF_LOCAL;
854 /* use abstract namespace for socket path */
855 strcpy(&saddr.sun_path[1], UDEVD_CTRL_SOCK_PATH);
856 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
858 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
859 if (udevd_sock == -1) {
860 err("error getting socket: %s", strerror(errno));
864 /* the bind takes care of ensuring only one copy running */
865 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
867 err("bind failed: %s", strerror(errno));
873 /* enable receiving of the sender credentials */
874 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
879 static int init_uevent_netlink_sock(void)
881 struct sockaddr_nl snl;
882 const int buffersize = 16 * 1024 * 1024;
885 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
886 snl.nl_family = AF_NETLINK;
887 snl.nl_pid = getpid();
890 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
891 if (uevent_netlink_sock == -1) {
892 err("error getting socket: %s", strerror(errno));
896 /* set receive buffersize */
897 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
899 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
901 err("bind failed: %s", strerror(errno));
902 close(uevent_netlink_sock);
903 uevent_netlink_sock = -1;
909 static void export_initial_seqnum(void)
911 char filename[PATH_SIZE];
916 strlcpy(filename, sysfs_path, sizeof(filename));
917 strlcat(filename, "/kernel/uevent_seqnum", sizeof(filename));
918 fd = open(filename, O_RDONLY);
920 len = read(fd, seqnum, sizeof(seqnum)-1);
924 strcpy(seqnum, "0\n");
927 strlcpy(filename, udev_root, sizeof(filename));
928 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
929 create_path(filename);
930 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
932 write(fd, seqnum, len);
937 int main(int argc, char *argv[], char *envp[])
941 struct sigaction act;
946 static const struct option options[] = {
947 { "daemon", 0, NULL, 'd' },
948 { "debug-trace", 0, NULL, 't' },
949 { "verbose", 0, NULL, 'v' },
950 { "help", 0, NULL, 'h' },
951 { "version", 0, NULL, 'V' },
957 logging_init("udevd");
960 dbg("version %s", UDEV_VERSION);
963 option = getopt_long(argc, argv, "dtvhV", options, NULL);
976 if (udev_log_priority < LOG_INFO)
977 udev_log_priority = LOG_INFO;
980 printf("Usage: udevd [--help] [--daemon] [--debug-trace] [--verbose] [--version]\n");
983 printf("%s\n", UDEV_VERSION);
991 fprintf(stderr, "root privileges required\n");
992 err("root privileges required");
996 /* make sure std{in,out,err} fd's are in a sane state */
997 fd = open("/dev/null", O_RDWR);
999 fprintf(stderr, "cannot open /dev/null\n");
1000 err("cannot open /dev/null");
1002 if (fd > STDIN_FILENO)
1003 dup2(fd, STDIN_FILENO);
1004 if (write(STDOUT_FILENO, 0, 0) < 0)
1005 dup2(fd, STDOUT_FILENO);
1006 if (write(STDERR_FILENO, 0, 0) < 0)
1007 dup2(fd, STDERR_FILENO);
1009 /* init sockets to receive events */
1010 if (init_udevd_socket() < 0) {
1011 if (errno == EADDRINUSE) {
1012 fprintf(stderr, "another udev daemon already running\n");
1013 err("another udev daemon already running");
1016 fprintf(stderr, "error initializing udevd socket\n");
1017 err("error initializing udevd socket");
1023 if (init_uevent_netlink_sock() < 0) {
1024 fprintf(stderr, "error initializing netlink socket\n");
1025 err("error initializing netlink socket");
1030 /* setup signal handler pipe */
1031 retval = pipe(signal_pipe);
1033 err("error getting pipes: %s", strerror(errno));
1037 retval = fcntl(signal_pipe[READ_END], F_GETFL, 0);
1039 err("error fcntl on read pipe: %s", strerror(errno));
1042 retval = fcntl(signal_pipe[READ_END], F_SETFL, retval | O_NONBLOCK);
1044 err("error fcntl on read pipe: %s", strerror(errno));
1048 retval = fcntl(signal_pipe[WRITE_END], F_GETFL, 0);
1050 err("error fcntl on write pipe: %s", strerror(errno));
1053 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, retval | O_NONBLOCK);
1055 err("error fcntl on write pipe: %s", strerror(errno));
1059 /* parse the rules and keep them in memory */
1061 udev_rules_init(&rules, 1);
1063 export_initial_seqnum();
1071 dbg("daemonized fork running");
1074 err("fork of daemon failed: %s", strerror(errno));
1078 dbg("child [%u] running, parent exits", pid);
1084 /* redirect std{out,err} fd's */
1086 dup2(fd, STDOUT_FILENO);
1087 dup2(fd, STDERR_FILENO);
1088 if (fd > STDERR_FILENO)
1091 /* set scheduling priority for the daemon */
1092 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
1097 /* become session leader */
1099 dbg("our session is %d", sid);
1101 /* OOM_DISABLE == -17 */
1102 fd = open("/proc/self/oom_adj", O_RDWR);
1104 err("error disabling OOM: %s", strerror(errno));
1106 write(fd, "-17", 3);
1110 /* set signal handlers */
1111 memset(&act, 0x00, sizeof(struct sigaction));
1112 act.sa_handler = (void (*)(int)) sig_handler;
1113 sigemptyset(&act.sa_mask);
1114 act.sa_flags = SA_RESTART;
1115 sigaction(SIGINT, &act, NULL);
1116 sigaction(SIGTERM, &act, NULL);
1117 sigaction(SIGCHLD, &act, NULL);
1118 sigaction(SIGHUP, &act, NULL);
1120 /* watch rules directory */
1121 inotify_fd = inotify_init();
1122 if (inotify_fd >= 0)
1123 inotify_add_watch(inotify_fd, udev_rules_dir, 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 configuration 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) {
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);