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];
157 struct udevd_uevent_msg *loop_msg;
160 /* location of queue file */
161 strlcpy(filename, udev_root, sizeof(filename));
162 strlcat(filename, "/", sizeof(filename));
163 start = strlcat(filename, EVENT_QUEUE_DIR"/", sizeof(filename));
164 strlcat(filename, msg->devpath, sizeof(filename));
165 path_encode(&filename[start], sizeof(filename) - start);
167 /* location of failed file */
168 strlcpy(filename_failed, udev_root, sizeof(filename_failed));
169 strlcat(filename_failed, "/", sizeof(filename_failed));
170 start = strlcat(filename_failed, EVENT_FAILED_DIR"/", sizeof(filename_failed));
171 strlcat(filename_failed, msg->devpath, sizeof(filename_failed));
172 path_encode(&filename_failed[start], sizeof(filename) - start);
176 unlink(filename_failed);
177 delete_path(filename_failed);
179 create_path(filename);
180 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
186 if (msg->devpath_old != NULL) {
187 /* "move" event - rename failed file to current name, do not delete failed */
188 char filename_failed_old[PATH_SIZE];
190 strlcpy(filename_failed_old, udev_root, sizeof(filename_failed_old));
191 strlcat(filename_failed_old, "/", sizeof(filename_failed_old));
192 start = strlcat(filename_failed_old, EVENT_FAILED_DIR"/", sizeof(filename_failed_old));
193 strlcat(filename_failed_old, msg->devpath_old, sizeof(filename_failed_old));
194 path_encode(&filename_failed_old[start], sizeof(filename) - start);
196 if (rename(filename_failed_old, filename_failed) == 0)
197 info("renamed devpath, moved failed state of '%s' to %s'",
198 msg->devpath_old, msg->devpath);
200 unlink(filename_failed);
201 delete_path(filename_failed);
204 /* skip 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 event to the failed directory */
214 if (state == EVENT_FAILED) {
215 create_path(filename_failed);
216 rename(filename, filename_failed);
221 /* clean up possibly empty 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);
300 info("seq %llu forked, '%s' '%s'", msg->seqnum, msg->action, msg->subsystem);
302 /* run one event after the other in debug mode */
304 list_add_tail(&msg->node, &running_list);
306 waitpid(msg->pid, NULL, 0);
307 msg_queue_delete(msg);
311 /* run all events with a timeout set immediately */
312 if (msg->timeout != 0) {
313 list_add_tail(&msg->node, &running_list);
318 list_add_tail(&msg->node, &exec_list);
322 static int mem_size_mb(void)
326 long int memsize = -1;
328 f = fopen("/proc/meminfo", "r");
332 while (fgets(buf, sizeof(buf), f) != NULL) {
335 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
336 memsize = value / 1024;
345 static int cpu_count(void)
351 f = fopen("/proc/stat", "r");
355 while (fgets(buf, sizeof(buf), f) != NULL) {
356 if (strncmp(buf, "cpu", 3) == 0 && isdigit(buf[3]))
366 static int running_processes(void)
372 f = fopen("/proc/stat", "r");
376 while (fgets(buf, sizeof(buf), f) != NULL) {
379 if (sscanf(buf, "procs_running %u", &value) == 1) {
389 /* return the number of process es in our session, count only until limit */
390 static int running_processes_in_session(pid_t session, int limit)
396 dir = opendir("/proc");
400 /* read process info from /proc */
401 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
407 pid_t ppid, pgrp, sess;
410 if (!isdigit(dent->d_name[0]))
413 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
414 procdir[sizeof(procdir)-1] = '\0';
416 f = open(procdir, O_RDONLY);
420 len = read(f, line, sizeof(line)-1);
428 /* skip ugly program name */
429 pos = strrchr(line, ')') + 2;
433 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
436 /* count only processes in our session */
440 /* count only running, no sleeping processes */
445 if (limit > 0 && running >= limit)
453 static int compare_devpath(const char *running, const char *waiting)
457 for (i = 0; i < PATH_SIZE; i++) {
458 /* identical device event found */
459 if (running[i] == '\0' && waiting[i] == '\0')
462 /* parent device event found */
463 if (running[i] == '\0' && waiting[i] == '/')
466 /* child device event found */
467 if (running[i] == '/' && waiting[i] == '\0')
470 /* no matching event */
471 if (running[i] != waiting[i])
478 /* lookup event for identical, parent, child, or physical device */
479 static int devpath_busy(struct udevd_uevent_msg *msg, int limit)
481 struct udevd_uevent_msg *loop_msg;
482 int childs_count = 0;
484 /* check exec-queue which may still contain delayed events we depend on */
485 list_for_each_entry(loop_msg, &exec_list, node) {
486 /* skip ourself and all later events */
487 if (loop_msg->seqnum >= msg->seqnum)
490 /* check our old name */
491 if (msg->devpath_old != NULL)
492 if (strcmp(loop_msg->devpath , msg->devpath_old) == 0)
495 /* check identical, parent, or child device event */
496 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
497 dbg("%llu, device event still pending %llu (%s)",
498 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
502 /* check physical device event (special case of parent) */
503 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
504 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
505 dbg("%llu, physical device event still pending %llu (%s)",
506 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
511 /* check run queue for still running events */
512 list_for_each_entry(loop_msg, &running_list, node) {
513 if (limit && childs_count++ > limit) {
514 dbg("%llu, maximum number (%i) of childs reached", msg->seqnum, childs_count);
518 /* check our old name */
519 if (msg->devpath_old != NULL)
520 if (strcmp(loop_msg->devpath , msg->devpath_old) == 0)
523 /* check identical, parent, or child device event */
524 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
525 dbg("%llu, device event still running %llu (%s)",
526 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
530 /* check physical device event (special case of parent) */
531 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
532 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
533 dbg("%llu, physical device event still running %llu (%s)",
534 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
541 /* serializes events for the identical and parent and child devices */
542 static void msg_queue_manager(void)
544 struct udevd_uevent_msg *loop_msg;
545 struct udevd_uevent_msg *tmp_msg;
548 if (list_empty(&exec_list))
551 running = running_processes();
552 dbg("%d processes runnning on system", running);
554 running = max_childs_running;
556 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
557 /* check running processes in our session and possibly throttle */
558 if (running >= max_childs_running) {
559 running = running_processes_in_session(sid, max_childs_running+10);
560 dbg("at least %d processes running in session", running);
561 if (running >= max_childs_running) {
562 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
567 /* serialize and wait for parent or child events */
568 if (devpath_busy(loop_msg, max_childs) != 0) {
569 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
573 /* move event to run list */
574 list_move_tail(&loop_msg->node, &running_list);
575 udev_event_run(loop_msg);
577 dbg("moved seq %llu to running list", loop_msg->seqnum);
581 static struct udevd_uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
585 struct udevd_uevent_msg *msg;
586 char *physdevdriver_key = NULL;
590 msg = malloc(sizeof(struct udevd_uevent_msg) + buf_size);
593 memset(msg, 0x00, sizeof(struct udevd_uevent_msg) + buf_size);
595 /* copy environment buffer and reconstruct envp */
596 memcpy(msg->envbuf, buf, buf_size);
598 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
602 key = &msg->envbuf[bufpos];
603 keylen = strlen(key);
605 bufpos += keylen + 1;
606 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
608 /* remember some keys for further processing */
609 if (strncmp(key, "ACTION=", 7) == 0)
610 msg->action = &key[7];
611 else if (strncmp(key, "DEVPATH=", 8) == 0)
612 msg->devpath = &key[8];
613 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
614 msg->subsystem = &key[10];
615 else if (strncmp(key, "DRIVER=", 7) == 0)
616 msg->driver = &key[7];
617 else if (strncmp(key, "SEQNUM=", 7) == 0)
618 msg->seqnum = strtoull(&key[7], NULL, 10);
619 else if (strncmp(key, "DEVPATH_OLD=", 12) == 0)
620 msg->devpath_old = &key[12];
621 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
622 msg->physdevpath = &key[12];
623 else if (strncmp(key, "PHYSDEVDRIVER=", 14) == 0)
624 physdevdriver_key = key;
625 else if (strncmp(key, "MAJOR=", 6) == 0)
626 maj = strtoull(&key[6], NULL, 10);
627 else if (strncmp(key, "MINOR=", 6) == 0)
628 min = strtoull(&key[6], NULL, 10);
629 else if (strncmp(key, "TIMEOUT=", 8) == 0)
630 msg->timeout = strtoull(&key[8], NULL, 10);
632 msg->devt = makedev(maj, min);
633 msg->envp[i++] = "UDEVD_EVENT=1";
635 if (msg->driver == NULL && msg->physdevpath == NULL && physdevdriver_key != NULL) {
636 /* for older kernels DRIVER is empty for a bus device, export PHYSDEVDRIVER as DRIVER */
637 msg->envp[i++] = &physdevdriver_key[7];
638 msg->driver = &physdevdriver_key[14];
643 if (msg->devpath == NULL || msg->action == NULL) {
644 info("DEVPATH or ACTION missing, ignore message");
651 /* receive the udevd message from userspace */
652 static void get_ctrl_msg(void)
654 struct udevd_ctrl_msg ctrl_msg;
657 struct cmsghdr *cmsg;
660 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
664 memset(&ctrl_msg, 0x00, sizeof(struct udevd_ctrl_msg));
665 iov.iov_base = &ctrl_msg;
666 iov.iov_len = sizeof(struct udevd_ctrl_msg);
668 memset(&smsg, 0x00, sizeof(struct msghdr));
671 smsg.msg_control = cred_msg;
672 smsg.msg_controllen = sizeof(cred_msg);
674 size = recvmsg(udevd_sock, &smsg, 0);
677 err("unable to receive user udevd message: %s", strerror(errno));
680 cmsg = CMSG_FIRSTHDR(&smsg);
681 cred = (struct ucred *) CMSG_DATA(cmsg);
683 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
684 err("no sender credentials received, message ignored");
688 if (cred->uid != 0) {
689 err("sender uid=%i, message ignored", cred->uid);
693 if (strncmp(ctrl_msg.magic, UDEVD_CTRL_MAGIC, sizeof(UDEVD_CTRL_MAGIC)) != 0 ) {
694 err("message magic '%s' doesn't match, ignore it", ctrl_msg.magic);
698 switch (ctrl_msg.type) {
700 pos = strchr(ctrl_msg.buf, '=');
702 err("wrong key format '%s'", ctrl_msg.buf);
706 if (pos[1] == '\0') {
707 info("udevd message (ENV) received, unset '%s'", ctrl_msg.buf);
708 unsetenv(ctrl_msg.buf);
710 info("udevd message (ENV) received, set '%s=%s'", ctrl_msg.buf, &pos[1]);
711 setenv(ctrl_msg.buf, &pos[1], 1);
714 case UDEVD_CTRL_STOP_EXEC_QUEUE:
715 info("udevd message (STOP_EXEC_QUEUE) received");
718 case UDEVD_CTRL_START_EXEC_QUEUE:
719 info("udevd message (START_EXEC_QUEUE) received");
723 case UDEVD_CTRL_SET_LOG_LEVEL:
724 intval = (int *) ctrl_msg.buf;
725 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
726 udev_log_priority = *intval;
727 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
730 case UDEVD_CTRL_SET_MAX_CHILDS:
731 intval = (int *) ctrl_msg.buf;
732 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
733 max_childs = *intval;
735 case UDEVD_CTRL_SET_MAX_CHILDS_RUNNING:
736 intval = (int *) ctrl_msg.buf;
737 info("udevd message (UDEVD_SET_MAX_CHILDS_RUNNING) received, max_childs=%i", *intval);
738 max_childs_running = *intval;
740 case UDEVD_CTRL_RELOAD_RULES:
741 info("udevd message (RELOAD_RULES) received");
745 err("unknown control message type");
749 /* receive the kernel user event message and do some sanity checks */
750 static struct udevd_uevent_msg *get_netlink_msg(void)
752 struct udevd_uevent_msg *msg;
755 static char buffer[UEVENT_BUFFER_SIZE+512];
758 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
761 err("unable to receive kernel netlink message: %s", strerror(errno));
765 if ((size_t)size > sizeof(buffer)-1)
766 size = sizeof(buffer)-1;
768 dbg("uevent_size=%zi", size);
770 /* start of event payload */
771 bufpos = strlen(buffer)+1;
772 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
776 /* validate message */
777 pos = strchr(buffer, '@');
779 err("invalid uevent '%s'", buffer);
785 if (msg->action == NULL) {
786 info("no ACTION in payload found, skip event '%s'", buffer);
791 if (strcmp(msg->action, buffer) != 0) {
792 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
800 static void asmlinkage sig_handler(int signum)
808 /* set flag, then write to pipe if needed */
809 sigchilds_waiting = 1;
816 /* write to pipe, which will wakeup select() in our mainloop */
817 write(signal_pipe[WRITE_END], "", 1);
820 static void udev_done(int pid, int exitstatus)
822 /* find msg associated with pid and delete it */
823 struct udevd_uevent_msg *msg;
825 list_for_each_entry(msg, &running_list, node) {
826 if (msg->pid == pid) {
827 info("seq %llu, pid [%d] exit with %i, %ld seconds old", msg->seqnum, msg->pid,
828 exitstatus, time(NULL) - msg->queue_time);
829 msg->exitstatus = exitstatus;
830 msg_queue_delete(msg);
832 /* there may be events waiting with the same devpath */
839 static void reap_sigchilds(void)
845 pid = waitpid(-1, &status, WNOHANG);
848 if (WIFEXITED(status))
849 status = WEXITSTATUS(status);
850 else if (WIFSIGNALED(status))
851 status = WTERMSIG(status) + 128;
854 udev_done(pid, status);
858 static int init_udevd_socket(void)
860 struct sockaddr_un saddr;
862 const int feature_on = 1;
865 memset(&saddr, 0x00, sizeof(saddr));
866 saddr.sun_family = AF_LOCAL;
867 /* use abstract namespace for socket path */
868 strcpy(&saddr.sun_path[1], UDEVD_CTRL_SOCK_PATH);
869 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
871 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
872 if (udevd_sock == -1) {
873 err("error getting socket: %s", strerror(errno));
877 /* the bind takes care of ensuring only one copy running */
878 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
880 err("bind failed: %s", strerror(errno));
886 /* enable receiving of the sender credentials */
887 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
892 static int init_uevent_netlink_sock(void)
894 struct sockaddr_nl snl;
895 const int buffersize = 16 * 1024 * 1024;
898 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
899 snl.nl_family = AF_NETLINK;
900 snl.nl_pid = getpid();
903 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
904 if (uevent_netlink_sock == -1) {
905 err("error getting socket: %s", strerror(errno));
909 /* set receive buffersize */
910 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
912 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
914 err("bind failed: %s", strerror(errno));
915 close(uevent_netlink_sock);
916 uevent_netlink_sock = -1;
922 static void export_initial_seqnum(void)
924 char filename[PATH_SIZE];
929 strlcpy(filename, sysfs_path, sizeof(filename));
930 strlcat(filename, "/kernel/uevent_seqnum", sizeof(filename));
931 fd = open(filename, O_RDONLY);
933 len = read(fd, seqnum, sizeof(seqnum)-1);
937 strcpy(seqnum, "0\n");
940 strlcpy(filename, udev_root, sizeof(filename));
941 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
942 create_path(filename);
943 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
945 write(fd, seqnum, len);
950 int main(int argc, char *argv[], char *envp[])
954 struct sigaction act;
959 static const struct option options[] = {
960 { "daemon", 0, NULL, 'd' },
961 { "debug-trace", 0, NULL, 't' },
962 { "verbose", 0, NULL, 'v' },
963 { "help", 0, NULL, 'h' },
964 { "version", 0, NULL, 'V' },
970 logging_init("udevd");
973 dbg("version %s", UDEV_VERSION);
976 option = getopt_long(argc, argv, "dtvhV", options, NULL);
989 if (udev_log_priority < LOG_INFO)
990 udev_log_priority = LOG_INFO;
993 printf("Usage: udevd [--help] [--daemon] [--debug-trace] [--verbose] [--version]\n");
996 printf("%s\n", UDEV_VERSION);
1003 if (getuid() != 0) {
1004 fprintf(stderr, "root privileges required\n");
1005 err("root privileges required");
1009 /* make sure std{in,out,err} fd's are in a sane state */
1010 fd = open("/dev/null", O_RDWR);
1012 fprintf(stderr, "cannot open /dev/null\n");
1013 err("cannot open /dev/null");
1015 if (fd > STDIN_FILENO)
1016 dup2(fd, STDIN_FILENO);
1017 if (write(STDOUT_FILENO, 0, 0) < 0)
1018 dup2(fd, STDOUT_FILENO);
1019 if (write(STDERR_FILENO, 0, 0) < 0)
1020 dup2(fd, STDERR_FILENO);
1022 /* init sockets to receive events */
1023 if (init_udevd_socket() < 0) {
1024 if (errno == EADDRINUSE) {
1025 fprintf(stderr, "another udev daemon already running\n");
1026 err("another udev daemon already running");
1029 fprintf(stderr, "error initializing udevd socket\n");
1030 err("error initializing udevd socket");
1036 if (init_uevent_netlink_sock() < 0) {
1037 fprintf(stderr, "error initializing netlink socket\n");
1038 err("error initializing netlink socket");
1043 /* setup signal handler pipe */
1044 retval = pipe(signal_pipe);
1046 err("error getting pipes: %s", strerror(errno));
1050 retval = fcntl(signal_pipe[READ_END], F_GETFL, 0);
1052 err("error fcntl on read pipe: %s", strerror(errno));
1055 retval = fcntl(signal_pipe[READ_END], F_SETFL, retval | O_NONBLOCK);
1057 err("error fcntl on read pipe: %s", strerror(errno));
1061 retval = fcntl(signal_pipe[WRITE_END], F_GETFL, 0);
1063 err("error fcntl on write pipe: %s", strerror(errno));
1066 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, retval | O_NONBLOCK);
1068 err("error fcntl on write pipe: %s", strerror(errno));
1072 /* parse the rules and keep them in memory */
1074 udev_rules_init(&rules, 1);
1076 export_initial_seqnum();
1084 dbg("daemonized fork running");
1087 err("fork of daemon failed: %s", strerror(errno));
1091 dbg("child [%u] running, parent exits", pid);
1097 /* redirect std{out,err} fd's */
1099 dup2(fd, STDOUT_FILENO);
1100 dup2(fd, STDERR_FILENO);
1101 if (fd > STDERR_FILENO)
1104 /* set scheduling priority for the daemon */
1105 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
1110 /* become session leader */
1112 dbg("our session is %d", sid);
1114 /* OOM_DISABLE == -17 */
1115 fd = open("/proc/self/oom_adj", O_RDWR);
1117 err("error disabling OOM: %s", strerror(errno));
1119 write(fd, "-17", 3);
1123 /* set signal handlers */
1124 memset(&act, 0x00, sizeof(struct sigaction));
1125 act.sa_handler = (void (*)(int)) sig_handler;
1126 sigemptyset(&act.sa_mask);
1127 act.sa_flags = SA_RESTART;
1128 sigaction(SIGINT, &act, NULL);
1129 sigaction(SIGTERM, &act, NULL);
1130 sigaction(SIGCHLD, &act, NULL);
1131 sigaction(SIGHUP, &act, NULL);
1133 /* watch rules directory */
1134 inotify_fd = inotify_init();
1135 if (inotify_fd >= 0) {
1136 char filename[PATH_MAX];
1138 inotify_add_watch(inotify_fd, udev_rules_dir, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1140 /* watch dynamic rules directory */
1141 strlcpy(filename, udev_root, sizeof(filename));
1142 strlcat(filename, "/"RULES_DYN_DIR, sizeof(filename));
1143 inotify_add_watch(inotify_fd, filename, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1144 } else if (errno == ENOSYS)
1145 err("the kernel does not support inotify, udevd can't monitor rules file changes");
1147 err("inotify_init failed: %s", strerror(errno));
1149 /* maximum limit of forked childs */
1150 value = getenv("UDEVD_MAX_CHILDS");
1152 max_childs = strtoul(value, NULL, 10);
1154 int memsize = mem_size_mb();
1156 max_childs = 128 + (memsize / 4);
1158 max_childs = UDEVD_MAX_CHILDS;
1160 info("initialize max_childs to %u", max_childs);
1162 /* start to throttle forking if maximum number of _running_ childs is reached */
1163 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
1165 max_childs_running = strtoull(value, NULL, 10);
1167 int cpus = cpu_count();
1169 max_childs_running = 8 + (8 * cpus);
1171 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
1173 info("initialize max_childs_running to %u", max_childs_running);
1175 /* clear environment for forked event processes */
1178 /* export log_priority , as called programs may want to follow that setting */
1179 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
1185 maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
1186 maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
1187 maxfd = UDEV_MAX(maxfd, inotify_fd);
1189 while (!udev_exit) {
1190 struct udevd_uevent_msg *msg;
1194 FD_SET(signal_pipe[READ_END], &readfds);
1195 FD_SET(udevd_sock, &readfds);
1196 FD_SET(uevent_netlink_sock, &readfds);
1197 if (inotify_fd >= 0)
1198 FD_SET(inotify_fd, &readfds);
1200 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
1203 err("error in select: %s", strerror(errno));
1207 /* get control message */
1208 if (FD_ISSET(udevd_sock, &readfds))
1211 /* get netlink message */
1212 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
1213 msg = get_netlink_msg();
1215 msg_queue_insert(msg);
1218 /* received a signal, clear our notification pipe */
1219 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
1222 read(signal_pipe[READ_END], &buf, sizeof(buf));
1225 /* rules directory inotify watch */
1226 if ((inotify_fd >= 0) && FD_ISSET(inotify_fd, &readfds)) {
1229 /* discard all possible events, we can just reload the config */
1230 if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes > 0) {
1234 buf = malloc(nbytes);
1236 err("error getting buffer for inotify, disable watching");
1240 read(inotify_fd, buf, nbytes);
1245 /* rules changed, set by inotify or a HUP signal */
1246 if (reload_config) {
1248 udev_rules_cleanup(&rules);
1249 udev_rules_init(&rules, 1);
1252 /* forked child has returned */
1253 if (sigchilds_waiting) {
1254 sigchilds_waiting = 0;
1261 msg_queue_manager();
1267 udev_rules_cleanup(&rules);
1271 if (signal_pipe[READ_END] >= 0)
1272 close(signal_pipe[READ_END]);
1273 if (signal_pipe[WRITE_END] >= 0)
1274 close(signal_pipe[WRITE_END]);
1276 if (udevd_sock >= 0)
1278 if (inotify_fd >= 0)
1280 if (uevent_netlink_sock >= 0)
1281 close(uevent_netlink_sock);