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 for our major:minor number */
483 if (msg->devt && loop_msg->devt == msg->devt &&
484 strcmp(msg->subsystem, loop_msg->subsystem) == 0) {
485 dbg("%llu, device event still pending %llu (%d:%d)", msg->seqnum,
486 loop_msg->seqnum, major(loop_msg->devt), minor(loop_msg->devt));
490 /* check physical device event (special case of parent) */
491 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
492 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
493 dbg("%llu, physical device event still pending %llu (%s)",
494 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
499 /* check run queue for still running events */
500 list_for_each_entry(loop_msg, &running_list, node) {
501 if (limit && childs_count++ > limit) {
502 dbg("%llu, maximum number (%i) of childs reached", msg->seqnum, childs_count);
506 /* check our old name */
507 if (msg->devpath_old != NULL)
508 if (strcmp(loop_msg->devpath , msg->devpath_old) == 0)
511 /* check identical, parent, or child device event */
512 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
513 dbg("%llu, device event still running %llu (%s)",
514 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
518 /* check for our major:minor number */
519 if (msg->devt && loop_msg->devt == msg->devt &&
520 strcmp(msg->subsystem, loop_msg->subsystem) == 0) {
521 dbg("%llu, device event still running %llu (%d:%d)", msg->seqnum,
522 loop_msg->seqnum, major(loop_msg->devt), minor(loop_msg->devt));
526 /* check physical device event (special case of parent) */
527 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
528 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
529 dbg("%llu, physical device event still running %llu (%s)",
530 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
537 /* serializes events for the identical and parent and child devices */
538 static void msg_queue_manager(void)
540 struct udevd_uevent_msg *loop_msg;
541 struct udevd_uevent_msg *tmp_msg;
544 if (list_empty(&exec_list))
547 running = running_processes();
548 dbg("%d processes runnning on system", running);
550 running = max_childs_running;
552 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
553 /* check running processes in our session and possibly throttle */
554 if (running >= max_childs_running) {
555 running = running_processes_in_session(sid, max_childs_running+10);
556 dbg("at least %d processes running in session", running);
557 if (running >= max_childs_running) {
558 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
563 /* serialize and wait for parent or child events */
564 if (devpath_busy(loop_msg, max_childs) != 0) {
565 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
569 /* move event to run list */
570 list_move_tail(&loop_msg->node, &running_list);
571 udev_event_run(loop_msg);
573 dbg("moved seq %llu to running list", loop_msg->seqnum);
577 static struct udevd_uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
581 struct udevd_uevent_msg *msg;
582 char *physdevdriver_key = NULL;
586 msg = malloc(sizeof(struct udevd_uevent_msg) + buf_size);
589 memset(msg, 0x00, sizeof(struct udevd_uevent_msg) + buf_size);
591 /* copy environment buffer and reconstruct envp */
592 memcpy(msg->envbuf, buf, buf_size);
594 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
598 key = &msg->envbuf[bufpos];
599 keylen = strlen(key);
601 bufpos += keylen + 1;
602 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
604 /* remember some keys for further processing */
605 if (strncmp(key, "ACTION=", 7) == 0)
606 msg->action = &key[7];
607 else if (strncmp(key, "DEVPATH=", 8) == 0)
608 msg->devpath = &key[8];
609 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
610 msg->subsystem = &key[10];
611 else if (strncmp(key, "DRIVER=", 7) == 0)
612 msg->driver = &key[7];
613 else if (strncmp(key, "SEQNUM=", 7) == 0)
614 msg->seqnum = strtoull(&key[7], NULL, 10);
615 else if (strncmp(key, "DEVPATH_OLD=", 12) == 0)
616 msg->devpath_old = &key[12];
617 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
618 msg->physdevpath = &key[12];
619 else if (strncmp(key, "PHYSDEVDRIVER=", 14) == 0)
620 physdevdriver_key = key;
621 else if (strncmp(key, "MAJOR=", 6) == 0)
622 maj = strtoull(&key[6], NULL, 10);
623 else if (strncmp(key, "MINOR=", 6) == 0)
624 min = strtoull(&key[6], NULL, 10);
625 else if (strncmp(key, "TIMEOUT=", 8) == 0)
626 msg->timeout = strtoull(&key[8], NULL, 10);
628 msg->devt = makedev(maj, min);
629 msg->envp[i++] = "UDEVD_EVENT=1";
631 if (msg->driver == NULL && msg->physdevpath == NULL && physdevdriver_key != NULL) {
632 /* for older kernels DRIVER is empty for a bus device, export PHYSDEVDRIVER as DRIVER */
633 msg->envp[i++] = &physdevdriver_key[7];
634 msg->driver = &physdevdriver_key[14];
639 if (msg->devpath == NULL || msg->action == NULL) {
640 info("DEVPATH or ACTION missing, ignore message");
647 /* receive the udevd message from userspace */
648 static void get_ctrl_msg(void)
650 struct udevd_ctrl_msg ctrl_msg;
653 struct cmsghdr *cmsg;
656 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
660 memset(&ctrl_msg, 0x00, sizeof(struct udevd_ctrl_msg));
661 iov.iov_base = &ctrl_msg;
662 iov.iov_len = sizeof(struct udevd_ctrl_msg);
664 memset(&smsg, 0x00, sizeof(struct msghdr));
667 smsg.msg_control = cred_msg;
668 smsg.msg_controllen = sizeof(cred_msg);
670 size = recvmsg(udevd_sock, &smsg, 0);
673 err("unable to receive user udevd message: %s", strerror(errno));
676 cmsg = CMSG_FIRSTHDR(&smsg);
677 cred = (struct ucred *) CMSG_DATA(cmsg);
679 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
680 err("no sender credentials received, message ignored");
684 if (cred->uid != 0) {
685 err("sender uid=%i, message ignored", cred->uid);
689 if (strncmp(ctrl_msg.magic, UDEVD_CTRL_MAGIC, sizeof(UDEVD_CTRL_MAGIC)) != 0 ) {
690 err("message magic '%s' doesn't match, ignore it", ctrl_msg.magic);
694 switch (ctrl_msg.type) {
696 pos = strchr(ctrl_msg.buf, '=');
698 err("wrong key format '%s'", ctrl_msg.buf);
702 if (pos[1] == '\0') {
703 info("udevd message (ENV) received, unset '%s'", ctrl_msg.buf);
704 unsetenv(ctrl_msg.buf);
706 info("udevd message (ENV) received, set '%s=%s'", ctrl_msg.buf, &pos[1]);
707 setenv(ctrl_msg.buf, &pos[1], 1);
710 case UDEVD_CTRL_STOP_EXEC_QUEUE:
711 info("udevd message (STOP_EXEC_QUEUE) received");
714 case UDEVD_CTRL_START_EXEC_QUEUE:
715 info("udevd message (START_EXEC_QUEUE) received");
719 case UDEVD_CTRL_SET_LOG_LEVEL:
720 intval = (int *) ctrl_msg.buf;
721 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
722 udev_log_priority = *intval;
723 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
726 case UDEVD_CTRL_SET_MAX_CHILDS:
727 intval = (int *) ctrl_msg.buf;
728 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
729 max_childs = *intval;
731 case UDEVD_CTRL_SET_MAX_CHILDS_RUNNING:
732 intval = (int *) ctrl_msg.buf;
733 info("udevd message (UDEVD_SET_MAX_CHILDS_RUNNING) received, max_childs=%i", *intval);
734 max_childs_running = *intval;
736 case UDEVD_CTRL_RELOAD_RULES:
737 info("udevd message (RELOAD_RULES) received");
741 err("unknown control message type");
745 /* receive the kernel user event message and do some sanity checks */
746 static struct udevd_uevent_msg *get_netlink_msg(void)
748 struct udevd_uevent_msg *msg;
751 static char buffer[UEVENT_BUFFER_SIZE+512];
754 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
757 err("unable to receive kernel netlink message: %s", strerror(errno));
761 if ((size_t)size > sizeof(buffer)-1)
762 size = sizeof(buffer)-1;
764 dbg("uevent_size=%zi", size);
766 /* start of event payload */
767 bufpos = strlen(buffer)+1;
768 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
772 /* validate message */
773 pos = strchr(buffer, '@');
775 err("invalid uevent '%s'", buffer);
781 if (msg->action == NULL) {
782 info("no ACTION in payload found, skip event '%s'", buffer);
787 if (strcmp(msg->action, buffer) != 0) {
788 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
796 static void asmlinkage sig_handler(int signum)
804 /* set flag, then write to pipe if needed */
805 sigchilds_waiting = 1;
812 /* write to pipe, which will wakeup select() in our mainloop */
813 write(signal_pipe[WRITE_END], "", 1);
816 static void udev_done(int pid, int exitstatus)
818 /* find msg associated with pid and delete it */
819 struct udevd_uevent_msg *msg;
821 list_for_each_entry(msg, &running_list, node) {
822 if (msg->pid == pid) {
823 info("seq %llu, pid [%d] exit with %i, %ld seconds old", msg->seqnum, msg->pid,
824 exitstatus, time(NULL) - msg->queue_time);
825 msg->exitstatus = exitstatus;
826 msg_queue_delete(msg);
828 /* there may be events waiting with the same devpath */
835 static void reap_sigchilds(void)
841 pid = waitpid(-1, &status, WNOHANG);
844 if (WIFEXITED(status))
845 status = WEXITSTATUS(status);
846 else if (WIFSIGNALED(status))
847 status = WTERMSIG(status) + 128;
850 udev_done(pid, status);
854 static int init_udevd_socket(void)
856 struct sockaddr_un saddr;
858 const int feature_on = 1;
861 memset(&saddr, 0x00, sizeof(saddr));
862 saddr.sun_family = AF_LOCAL;
863 /* use abstract namespace for socket path */
864 strcpy(&saddr.sun_path[1], UDEVD_CTRL_SOCK_PATH);
865 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
867 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
868 if (udevd_sock == -1) {
869 err("error getting socket: %s", strerror(errno));
873 /* the bind takes care of ensuring only one copy running */
874 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
876 err("bind failed: %s", strerror(errno));
882 /* enable receiving of the sender credentials */
883 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
888 static int init_uevent_netlink_sock(void)
890 struct sockaddr_nl snl;
891 const int buffersize = 16 * 1024 * 1024;
894 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
895 snl.nl_family = AF_NETLINK;
896 snl.nl_pid = getpid();
899 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
900 if (uevent_netlink_sock == -1) {
901 err("error getting socket: %s", strerror(errno));
905 /* set receive buffersize */
906 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
908 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
910 err("bind failed: %s", strerror(errno));
911 close(uevent_netlink_sock);
912 uevent_netlink_sock = -1;
918 static void export_initial_seqnum(void)
920 char filename[PATH_SIZE];
925 strlcpy(filename, sysfs_path, sizeof(filename));
926 strlcat(filename, "/kernel/uevent_seqnum", sizeof(filename));
927 fd = open(filename, O_RDONLY);
929 len = read(fd, seqnum, sizeof(seqnum)-1);
933 strcpy(seqnum, "0\n");
936 strlcpy(filename, udev_root, sizeof(filename));
937 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
938 create_path(filename);
939 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
941 write(fd, seqnum, len);
946 int main(int argc, char *argv[], char *envp[])
950 struct sigaction act;
955 static const struct option options[] = {
956 { "daemon", 0, NULL, 'd' },
957 { "debug-trace", 0, NULL, 't' },
958 { "verbose", 0, NULL, 'v' },
959 { "help", 0, NULL, 'h' },
960 { "version", 0, NULL, 'V' },
966 logging_init("udevd");
969 dbg("version %s", UDEV_VERSION);
972 option = getopt_long(argc, argv, "dtvhV", options, NULL);
985 if (udev_log_priority < LOG_INFO)
986 udev_log_priority = LOG_INFO;
989 printf("Usage: udevd [--help] [--daemon] [--debug-trace] [--verbose] [--version]\n");
992 printf("%s\n", UDEV_VERSION);
1000 fprintf(stderr, "root privileges required\n");
1001 err("root privileges required");
1005 /* make sure std{in,out,err} fd's are in a sane state */
1006 fd = open("/dev/null", O_RDWR);
1008 fprintf(stderr, "cannot open /dev/null\n");
1009 err("cannot open /dev/null");
1011 if (fd > STDIN_FILENO)
1012 dup2(fd, STDIN_FILENO);
1013 if (write(STDOUT_FILENO, 0, 0) < 0)
1014 dup2(fd, STDOUT_FILENO);
1015 if (write(STDERR_FILENO, 0, 0) < 0)
1016 dup2(fd, STDERR_FILENO);
1018 /* init sockets to receive events */
1019 if (init_udevd_socket() < 0) {
1020 if (errno == EADDRINUSE) {
1021 fprintf(stderr, "another udev daemon already running\n");
1022 err("another udev daemon already running");
1025 fprintf(stderr, "error initializing udevd socket\n");
1026 err("error initializing udevd socket");
1032 if (init_uevent_netlink_sock() < 0) {
1033 fprintf(stderr, "error initializing netlink socket\n");
1034 err("error initializing netlink socket");
1039 /* setup signal handler pipe */
1040 retval = pipe(signal_pipe);
1042 err("error getting pipes: %s", strerror(errno));
1046 retval = fcntl(signal_pipe[READ_END], F_GETFL, 0);
1048 err("error fcntl on read pipe: %s", strerror(errno));
1051 retval = fcntl(signal_pipe[READ_END], F_SETFL, retval | O_NONBLOCK);
1053 err("error fcntl on read pipe: %s", strerror(errno));
1057 retval = fcntl(signal_pipe[WRITE_END], F_GETFL, 0);
1059 err("error fcntl on write pipe: %s", strerror(errno));
1062 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, retval | O_NONBLOCK);
1064 err("error fcntl on write pipe: %s", strerror(errno));
1068 /* parse the rules and keep them in memory */
1070 udev_rules_init(&rules, 1);
1072 export_initial_seqnum();
1080 dbg("daemonized fork running");
1083 err("fork of daemon failed: %s", strerror(errno));
1087 dbg("child [%u] running, parent exits", pid);
1093 /* redirect std{out,err} fd's */
1095 dup2(fd, STDOUT_FILENO);
1096 dup2(fd, STDERR_FILENO);
1097 if (fd > STDERR_FILENO)
1100 /* set scheduling priority for the daemon */
1101 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
1106 /* become session leader */
1108 dbg("our session is %d", sid);
1110 /* OOM_DISABLE == -17 */
1111 fd = open("/proc/self/oom_adj", O_RDWR);
1113 err("error disabling OOM: %s", strerror(errno));
1115 write(fd, "-17", 3);
1119 /* set signal handlers */
1120 memset(&act, 0x00, sizeof(struct sigaction));
1121 act.sa_handler = (void (*)(int)) sig_handler;
1122 sigemptyset(&act.sa_mask);
1123 act.sa_flags = SA_RESTART;
1124 sigaction(SIGINT, &act, NULL);
1125 sigaction(SIGTERM, &act, NULL);
1126 sigaction(SIGCHLD, &act, NULL);
1127 sigaction(SIGHUP, &act, NULL);
1129 /* watch rules directory */
1130 inotify_fd = inotify_init();
1131 if (inotify_fd >= 0) {
1132 char filename[PATH_MAX];
1134 inotify_add_watch(inotify_fd, udev_rules_dir, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1136 /* watch dynamic rules directory */
1137 strlcpy(filename, udev_root, sizeof(filename));
1138 strlcat(filename, "/"RULES_DYN_DIR, sizeof(filename));
1139 inotify_add_watch(inotify_fd, filename, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1140 } else if (errno == ENOSYS)
1141 err("the kernel does not support inotify, udevd can't monitor rules file changes");
1143 err("inotify_init failed: %s", strerror(errno));
1145 /* maximum limit of forked childs */
1146 value = getenv("UDEVD_MAX_CHILDS");
1148 max_childs = strtoul(value, NULL, 10);
1150 int memsize = mem_size_mb();
1152 max_childs = 128 + (memsize / 4);
1154 max_childs = UDEVD_MAX_CHILDS;
1156 info("initialize max_childs to %u", max_childs);
1158 /* start to throttle forking if maximum number of _running_ childs is reached */
1159 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
1161 max_childs_running = strtoull(value, NULL, 10);
1163 int cpus = cpu_count();
1165 max_childs_running = 8 + (8 * cpus);
1167 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
1169 info("initialize max_childs_running to %u", max_childs_running);
1171 /* clear environment for forked event processes */
1174 /* export log_priority , as called programs may want to follow that setting */
1175 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
1181 maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
1182 maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
1183 maxfd = UDEV_MAX(maxfd, inotify_fd);
1185 while (!udev_exit) {
1186 struct udevd_uevent_msg *msg;
1190 FD_SET(signal_pipe[READ_END], &readfds);
1191 FD_SET(udevd_sock, &readfds);
1192 FD_SET(uevent_netlink_sock, &readfds);
1193 if (inotify_fd >= 0)
1194 FD_SET(inotify_fd, &readfds);
1196 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
1199 err("error in select: %s", strerror(errno));
1203 /* get control message */
1204 if (FD_ISSET(udevd_sock, &readfds))
1207 /* get netlink message */
1208 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
1209 msg = get_netlink_msg();
1211 msg_queue_insert(msg);
1214 /* received a signal, clear our notification pipe */
1215 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
1218 read(signal_pipe[READ_END], &buf, sizeof(buf));
1221 /* rules directory inotify watch */
1222 if ((inotify_fd >= 0) && FD_ISSET(inotify_fd, &readfds)) {
1225 /* discard all possible events, we can just reload the config */
1226 if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes > 0) {
1230 buf = malloc(nbytes);
1232 err("error getting buffer for inotify, disable watching");
1236 read(inotify_fd, buf, nbytes);
1241 /* rules changed, set by inotify or a HUP signal */
1242 if (reload_config) {
1244 udev_rules_cleanup(&rules);
1245 udev_rules_init(&rules, 1);
1248 /* forked child has returned */
1249 if (sigchilds_waiting) {
1250 sigchilds_waiting = 0;
1257 msg_queue_manager();
1263 udev_rules_cleanup(&rules);
1267 if (signal_pipe[READ_END] >= 0)
1268 close(signal_pipe[READ_END]);
1269 if (signal_pipe[WRITE_END] >= 0)
1270 close(signal_pipe[WRITE_END]);
1272 if (udevd_sock >= 0)
1274 if (inotify_fd >= 0)
1276 if (uevent_netlink_sock >= 0)
1277 close(uevent_netlink_sock);