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);
84 vsyslog(priority, format, args);
90 static void asmlinkage udev_event_sig_handler(int signum)
92 if (signum == SIGALRM)
96 static int udev_event_process(struct udevd_uevent_msg *msg)
103 /* set signal handlers */
104 memset(&act, 0x00, sizeof(act));
105 act.sa_handler = (void (*)(int)) udev_event_sig_handler;
106 sigemptyset (&act.sa_mask);
108 sigaction(SIGALRM, &act, NULL);
110 /* reset to default */
111 act.sa_handler = SIG_DFL;
112 sigaction(SIGINT, &act, NULL);
113 sigaction(SIGTERM, &act, NULL);
114 sigaction(SIGCHLD, &act, NULL);
115 sigaction(SIGHUP, &act, NULL);
117 /* trigger timeout to prevent hanging processes */
118 alarm(UDEV_ALARM_TIMEOUT);
120 /* reconstruct event environment from message */
121 for (i = 0; msg->envp[i]; i++)
122 putenv(msg->envp[i]);
124 udev = udev_device_init(NULL);
127 strlcpy(udev->action, msg->action, sizeof(udev->action));
128 sysfs_device_set_values(udev->dev, msg->devpath, msg->subsystem, msg->driver);
129 udev->devpath_old = msg->devpath_old;
130 udev->devt = msg->devt;
132 retval = udev_device_event(&rules, udev);
134 /* run programs collected by RUN-key*/
135 if (retval == 0 && !udev->ignore_device && udev_run)
136 retval = udev_rules_run(udev);
138 udev_device_cleanup(udev);
148 static void export_event_state(struct udevd_uevent_msg *msg, enum event_state state)
150 char filename[PATH_SIZE];
151 char filename_failed[PATH_SIZE];
154 /* location of queue file */
155 snprintf(filename, sizeof(filename), "%s/"EVENT_QUEUE_DIR"/%llu", udev_root, msg->seqnum);
157 /* location of failed file */
158 strlcpy(filename_failed, udev_root, sizeof(filename_failed));
159 strlcat(filename_failed, "/", sizeof(filename_failed));
160 start = strlcat(filename_failed, EVENT_FAILED_DIR"/", sizeof(filename_failed));
161 strlcat(filename_failed, msg->devpath, sizeof(filename_failed));
162 path_encode(&filename_failed[start], sizeof(filename_failed) - start);
166 unlink(filename_failed);
167 delete_path(filename_failed);
169 create_path(filename);
170 selinux_setfscreatecon(filename, NULL, S_IFLNK);
171 symlink(msg->devpath, filename);
172 selinux_resetfscreatecon();
175 if (msg->devpath_old != NULL) {
176 /* "move" event - rename failed file to current name, do not delete failed */
177 char filename_failed_old[PATH_SIZE];
179 strlcpy(filename_failed_old, udev_root, sizeof(filename_failed_old));
180 strlcat(filename_failed_old, "/", sizeof(filename_failed_old));
181 start = strlcat(filename_failed_old, EVENT_FAILED_DIR"/", sizeof(filename_failed_old));
182 strlcat(filename_failed_old, msg->devpath_old, sizeof(filename_failed_old));
183 path_encode(&filename_failed_old[start], sizeof(filename) - start);
185 if (rename(filename_failed_old, filename_failed) == 0)
186 info("renamed devpath, moved failed state of '%s' to %s'\n",
187 msg->devpath_old, msg->devpath);
189 unlink(filename_failed);
190 delete_path(filename_failed);
194 delete_path(filename);
197 /* move failed event to the failed directory */
198 create_path(filename_failed);
199 rename(filename, filename_failed);
201 /* clean up possibly empty queue directory */
202 delete_path(filename);
209 static void msg_queue_delete(struct udevd_uevent_msg *msg)
211 list_del(&msg->node);
213 /* mark as failed, if "add" event returns non-zero */
214 if (msg->exitstatus && strcmp(msg->action, "add") == 0)
215 export_event_state(msg, EVENT_FAILED);
217 export_event_state(msg, EVENT_FINISHED);
222 static void udev_event_run(struct udevd_uevent_msg *msg)
231 close(uevent_netlink_sock);
235 close(signal_pipe[READ_END]);
236 close(signal_pipe[WRITE_END]);
239 logging_init("udevd-event");
240 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
242 retval = udev_event_process(msg);
243 info("seq %llu finished with %i\n", msg->seqnum, retval);
250 err("fork of child failed: %s\n", strerror(errno));
251 msg_queue_delete(msg);
254 /* get SIGCHLD in main loop */
255 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old\n",
256 msg->seqnum, pid, msg->action, msg->subsystem, time(NULL) - msg->queue_time);
261 static void msg_queue_insert(struct udevd_uevent_msg *msg)
263 char filename[PATH_SIZE];
266 msg->queue_time = time(NULL);
268 strlcpy(filename, udev_root, sizeof(filename));
269 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
270 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
275 len = sprintf(str, "%llu\n", msg->seqnum);
280 export_event_state(msg, EVENT_QUEUED);
281 info("seq %llu queued, '%s' '%s'\n", msg->seqnum, msg->action, msg->subsystem);
283 /* run one event after the other in debug mode */
285 list_add_tail(&msg->node, &running_list);
287 waitpid(msg->pid, NULL, 0);
288 msg_queue_delete(msg);
292 /* run all events with a timeout set immediately */
293 if (msg->timeout != 0) {
294 list_add_tail(&msg->node, &running_list);
299 list_add_tail(&msg->node, &exec_list);
303 static int mem_size_mb(void)
307 long int memsize = -1;
309 f = fopen("/proc/meminfo", "r");
313 while (fgets(buf, sizeof(buf), f) != NULL) {
316 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
317 memsize = value / 1024;
326 static int cpu_count(void)
332 f = fopen("/proc/stat", "r");
336 while (fgets(buf, sizeof(buf), f) != NULL) {
337 if (strncmp(buf, "cpu", 3) == 0 && isdigit(buf[3]))
347 static int running_processes(void)
353 f = fopen("/proc/stat", "r");
357 while (fgets(buf, sizeof(buf), f) != NULL) {
360 if (sscanf(buf, "procs_running %u", &value) == 1) {
370 /* return the number of process es in our session, count only until limit */
371 static int running_processes_in_session(pid_t session, int limit)
377 dir = opendir("/proc");
381 /* read process info from /proc */
382 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
388 pid_t ppid, pgrp, sess;
391 if (!isdigit(dent->d_name[0]))
394 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
395 procdir[sizeof(procdir)-1] = '\0';
397 f = open(procdir, O_RDONLY);
401 len = read(f, line, sizeof(line)-1);
409 /* skip ugly program name */
410 pos = strrchr(line, ')') + 2;
414 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
417 /* count only processes in our session */
421 /* count only running, no sleeping processes */
426 if (limit > 0 && running >= limit)
434 static int compare_devpath(const char *running, const char *waiting)
438 for (i = 0; i < PATH_SIZE; i++) {
439 /* identical device event found */
440 if (running[i] == '\0' && waiting[i] == '\0')
443 /* parent device event found */
444 if (running[i] == '\0' && waiting[i] == '/')
447 /* child device event found */
448 if (running[i] == '/' && waiting[i] == '\0')
451 /* no matching event */
452 if (running[i] != waiting[i])
459 /* lookup event for identical, parent, child, or physical device */
460 static int devpath_busy(struct udevd_uevent_msg *msg, int limit)
462 struct udevd_uevent_msg *loop_msg;
463 int childs_count = 0;
465 /* check exec-queue which may still contain delayed events we depend on */
466 list_for_each_entry(loop_msg, &exec_list, node) {
467 /* skip ourself and all later events */
468 if (loop_msg->seqnum >= msg->seqnum)
471 /* check our old name */
472 if (msg->devpath_old != NULL)
473 if (strcmp(loop_msg->devpath , msg->devpath_old) == 0)
476 /* check identical, parent, or child device event */
477 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
478 dbg("%llu, device event still pending %llu (%s)\n",
479 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
483 /* check for our major:minor number */
484 if (msg->devt && loop_msg->devt == msg->devt &&
485 strcmp(msg->subsystem, loop_msg->subsystem) == 0) {
486 dbg("%llu, device event still pending %llu (%d:%d)\n", msg->seqnum,
487 loop_msg->seqnum, major(loop_msg->devt), minor(loop_msg->devt));
491 /* check physical device event (special case of parent) */
492 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
493 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
494 dbg("%llu, physical device event still pending %llu (%s)\n",
495 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
500 /* check run queue for still running events */
501 list_for_each_entry(loop_msg, &running_list, node) {
502 if (limit && childs_count++ > limit) {
503 dbg("%llu, maximum number (%i) of childs reached\n", msg->seqnum, childs_count);
507 /* check our old name */
508 if (msg->devpath_old != NULL)
509 if (strcmp(loop_msg->devpath , msg->devpath_old) == 0)
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)\n",
515 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
519 /* check for our major:minor number */
520 if (msg->devt && loop_msg->devt == msg->devt &&
521 strcmp(msg->subsystem, loop_msg->subsystem) == 0) {
522 dbg("%llu, device event still running %llu (%d:%d)\n", msg->seqnum,
523 loop_msg->seqnum, major(loop_msg->devt), minor(loop_msg->devt));
527 /* check physical device event (special case of parent) */
528 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
529 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
530 dbg("%llu, physical device event still running %llu (%s)\n",
531 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
538 /* serializes events for the identical and parent and child devices */
539 static void msg_queue_manager(void)
541 struct udevd_uevent_msg *loop_msg;
542 struct udevd_uevent_msg *tmp_msg;
545 if (list_empty(&exec_list))
548 running = running_processes();
549 dbg("%d processes runnning on system\n", running);
551 running = max_childs_running;
553 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
554 /* check running processes in our session and possibly throttle */
555 if (running >= max_childs_running) {
556 running = running_processes_in_session(sid, max_childs_running+10);
557 dbg("at least %d processes running in session\n", running);
558 if (running >= max_childs_running) {
559 dbg("delay seq %llu, too many processes already running\n", loop_msg->seqnum);
564 /* serialize and wait for parent or child events */
565 if (devpath_busy(loop_msg, max_childs) != 0) {
566 dbg("delay seq %llu (%s)\n", loop_msg->seqnum, loop_msg->devpath);
570 /* move event to run list */
571 list_move_tail(&loop_msg->node, &running_list);
572 udev_event_run(loop_msg);
574 dbg("moved seq %llu to running list\n", loop_msg->seqnum);
578 static struct udevd_uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
582 struct udevd_uevent_msg *msg;
583 char *physdevdriver_key = NULL;
587 msg = malloc(sizeof(struct udevd_uevent_msg) + buf_size);
590 memset(msg, 0x00, sizeof(struct udevd_uevent_msg) + buf_size);
592 /* copy environment buffer and reconstruct envp */
593 memcpy(msg->envbuf, buf, buf_size);
595 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
599 key = &msg->envbuf[bufpos];
600 keylen = strlen(key);
602 bufpos += keylen + 1;
603 dbg("add '%s' to msg.envp[%i]\n", msg->envp[i], i);
605 /* remember some keys for further processing */
606 if (strncmp(key, "ACTION=", 7) == 0)
607 msg->action = &key[7];
608 else if (strncmp(key, "DEVPATH=", 8) == 0)
609 msg->devpath = &key[8];
610 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
611 msg->subsystem = &key[10];
612 else if (strncmp(key, "DRIVER=", 7) == 0)
613 msg->driver = &key[7];
614 else if (strncmp(key, "SEQNUM=", 7) == 0)
615 msg->seqnum = strtoull(&key[7], NULL, 10);
616 else if (strncmp(key, "DEVPATH_OLD=", 12) == 0)
617 msg->devpath_old = &key[12];
618 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
619 msg->physdevpath = &key[12];
620 else if (strncmp(key, "PHYSDEVDRIVER=", 14) == 0)
621 physdevdriver_key = key;
622 else if (strncmp(key, "MAJOR=", 6) == 0)
623 maj = strtoull(&key[6], NULL, 10);
624 else if (strncmp(key, "MINOR=", 6) == 0)
625 min = strtoull(&key[6], NULL, 10);
626 else if (strncmp(key, "TIMEOUT=", 8) == 0)
627 msg->timeout = strtoull(&key[8], NULL, 10);
629 msg->devt = makedev(maj, min);
630 msg->envp[i++] = "UDEVD_EVENT=1";
632 if (msg->driver == NULL && msg->physdevpath == NULL && physdevdriver_key != NULL) {
633 /* for older kernels DRIVER is empty for a bus device, export PHYSDEVDRIVER as DRIVER */
634 msg->envp[i++] = &physdevdriver_key[7];
635 msg->driver = &physdevdriver_key[14];
640 if (msg->devpath == NULL || msg->action == NULL) {
641 info("DEVPATH or ACTION missing, ignore message\n");
648 /* receive the udevd message from userspace */
649 static void get_ctrl_msg(void)
651 struct udevd_ctrl_msg ctrl_msg;
654 struct cmsghdr *cmsg;
657 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
661 memset(&ctrl_msg, 0x00, sizeof(struct udevd_ctrl_msg));
662 iov.iov_base = &ctrl_msg;
663 iov.iov_len = sizeof(struct udevd_ctrl_msg);
665 memset(&smsg, 0x00, sizeof(struct msghdr));
668 smsg.msg_control = cred_msg;
669 smsg.msg_controllen = sizeof(cred_msg);
671 size = recvmsg(udevd_sock, &smsg, 0);
674 err("unable to receive user udevd message: %s\n", strerror(errno));
677 cmsg = CMSG_FIRSTHDR(&smsg);
678 cred = (struct ucred *) CMSG_DATA(cmsg);
680 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
681 err("no sender credentials received, message ignored\n");
685 if (cred->uid != 0) {
686 err("sender uid=%i, message ignored\n", cred->uid);
690 if (strncmp(ctrl_msg.magic, UDEVD_CTRL_MAGIC, sizeof(UDEVD_CTRL_MAGIC)) != 0 ) {
691 err("message magic '%s' doesn't match, ignore it\n", ctrl_msg.magic);
695 switch (ctrl_msg.type) {
697 pos = strchr(ctrl_msg.buf, '=');
699 err("wrong key format '%s'\n", ctrl_msg.buf);
703 if (pos[1] == '\0') {
704 info("udevd message (ENV) received, unset '%s'\n", ctrl_msg.buf);
705 unsetenv(ctrl_msg.buf);
707 info("udevd message (ENV) received, set '%s=%s'\n", ctrl_msg.buf, &pos[1]);
708 setenv(ctrl_msg.buf, &pos[1], 1);
711 case UDEVD_CTRL_STOP_EXEC_QUEUE:
712 info("udevd message (STOP_EXEC_QUEUE) received\n");
715 case UDEVD_CTRL_START_EXEC_QUEUE:
716 info("udevd message (START_EXEC_QUEUE) received\n");
720 case UDEVD_CTRL_SET_LOG_LEVEL:
721 intval = (int *) ctrl_msg.buf;
722 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i\n", *intval);
723 udev_log_priority = *intval;
724 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
727 case UDEVD_CTRL_SET_MAX_CHILDS:
728 intval = (int *) ctrl_msg.buf;
729 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i\n", *intval);
730 max_childs = *intval;
732 case UDEVD_CTRL_SET_MAX_CHILDS_RUNNING:
733 intval = (int *) ctrl_msg.buf;
734 info("udevd message (UDEVD_SET_MAX_CHILDS_RUNNING) received, max_childs=%i\n", *intval);
735 max_childs_running = *intval;
737 case UDEVD_CTRL_RELOAD_RULES:
738 info("udevd message (RELOAD_RULES) received\n");
742 err("unknown control message type\n");
746 /* receive the kernel user event message and do some sanity checks */
747 static struct udevd_uevent_msg *get_netlink_msg(void)
749 struct udevd_uevent_msg *msg;
752 static char buffer[UEVENT_BUFFER_SIZE+512];
755 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
758 err("unable to receive kernel netlink message: %s\n", strerror(errno));
762 if ((size_t)size > sizeof(buffer)-1)
763 size = sizeof(buffer)-1;
765 dbg("uevent_size=%zi\n", size);
767 /* start of event payload */
768 bufpos = strlen(buffer)+1;
769 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
773 /* validate message */
774 pos = strchr(buffer, '@');
776 err("invalid uevent '%s'\n", buffer);
782 if (msg->action == NULL) {
783 info("no ACTION in payload found, skip event '%s'\n", buffer);
788 if (strcmp(msg->action, buffer) != 0) {
789 err("ACTION in payload does not match uevent, skip event '%s'\n", buffer);
797 static void asmlinkage sig_handler(int signum)
805 /* set flag, then write to pipe if needed */
806 sigchilds_waiting = 1;
813 /* write to pipe, which will wakeup select() in our mainloop */
814 write(signal_pipe[WRITE_END], "", 1);
817 static void udev_done(int pid, int exitstatus)
819 /* find msg associated with pid and delete it */
820 struct udevd_uevent_msg *msg;
822 list_for_each_entry(msg, &running_list, node) {
823 if (msg->pid == pid) {
824 info("seq %llu, pid [%d] exit with %i, %ld seconds old\n", msg->seqnum, msg->pid,
825 exitstatus, time(NULL) - msg->queue_time);
826 msg->exitstatus = exitstatus;
827 msg_queue_delete(msg);
829 /* there may be events waiting with the same devpath */
836 static void reap_sigchilds(void)
842 pid = waitpid(-1, &status, WNOHANG);
845 if (WIFEXITED(status))
846 status = WEXITSTATUS(status);
847 else if (WIFSIGNALED(status))
848 status = WTERMSIG(status) + 128;
851 udev_done(pid, status);
855 static int init_udevd_socket(void)
857 struct sockaddr_un saddr;
859 const int feature_on = 1;
862 memset(&saddr, 0x00, sizeof(saddr));
863 saddr.sun_family = AF_LOCAL;
864 /* use abstract namespace for socket path */
865 strcpy(&saddr.sun_path[1], UDEVD_CTRL_SOCK_PATH);
866 addrlen = offsetof(struct sockaddr_un, sun_path) + 1 + strlen(&saddr.sun_path[1]);
868 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
869 if (udevd_sock == -1) {
870 err("error getting socket: %s\n", strerror(errno));
874 /* the bind takes care of ensuring only one copy running */
875 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
877 err("bind failed: %s\n", strerror(errno));
883 /* enable receiving of the sender credentials */
884 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
889 static int init_uevent_netlink_sock(void)
891 struct sockaddr_nl snl;
892 const int buffersize = 16 * 1024 * 1024;
895 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
896 snl.nl_family = AF_NETLINK;
897 snl.nl_pid = getpid();
900 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
901 if (uevent_netlink_sock == -1) {
902 err("error getting socket: %s\n", strerror(errno));
906 /* set receive buffersize */
907 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
909 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
911 err("bind failed: %s\n", strerror(errno));
912 close(uevent_netlink_sock);
913 uevent_netlink_sock = -1;
919 static void export_initial_seqnum(void)
921 char filename[PATH_SIZE];
926 strlcpy(filename, sysfs_path, sizeof(filename));
927 strlcat(filename, "/kernel/uevent_seqnum", sizeof(filename));
928 fd = open(filename, O_RDONLY);
930 len = read(fd, seqnum, sizeof(seqnum)-1);
934 strcpy(seqnum, "0\n");
937 strlcpy(filename, udev_root, sizeof(filename));
938 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
939 create_path(filename);
940 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
942 write(fd, seqnum, len);
947 int main(int argc, char *argv[], char *envp[])
951 struct sigaction act;
956 static const struct option options[] = {
957 { "daemon", 0, NULL, 'd' },
958 { "debug-trace", 0, NULL, 't' },
959 { "debug", 0, NULL, 'D' },
960 { "help", 0, NULL, 'h' },
961 { "version", 0, NULL, 'V' },
967 logging_init("udevd");
970 dbg("version %s\n", UDEV_VERSION);
973 option = getopt_long(argc, argv, "dDthV", options, NULL);
986 if (udev_log_priority < LOG_INFO)
987 udev_log_priority = LOG_INFO;
990 printf("Usage: udevd [--help] [--daemon] [--debug-trace] [--debug] [--version]\n");
993 printf("%s\n", UDEV_VERSION);
1000 if (getuid() != 0) {
1001 fprintf(stderr, "root privileges required\n");
1002 err("root privileges required\n");
1006 /* make sure std{in,out,err} fd's are in a sane state */
1007 fd = open("/dev/null", O_RDWR);
1009 fprintf(stderr, "cannot open /dev/null\n");
1010 err("cannot open /dev/null\n");
1012 if (fd > STDIN_FILENO)
1013 dup2(fd, STDIN_FILENO);
1014 if (write(STDOUT_FILENO, 0, 0) < 0)
1015 dup2(fd, STDOUT_FILENO);
1016 if (write(STDERR_FILENO, 0, 0) < 0)
1017 dup2(fd, STDERR_FILENO);
1019 /* init sockets to receive events */
1020 if (init_udevd_socket() < 0) {
1021 if (errno == EADDRINUSE) {
1022 fprintf(stderr, "another udev daemon already running\n");
1023 err("another udev daemon already running\n");
1026 fprintf(stderr, "error initializing udevd socket\n");
1027 err("error initializing udevd socket\n");
1033 if (init_uevent_netlink_sock() < 0) {
1034 fprintf(stderr, "error initializing netlink socket\n");
1035 err("error initializing netlink socket\n");
1040 /* setup signal handler pipe */
1041 retval = pipe(signal_pipe);
1043 err("error getting pipes: %s\n", strerror(errno));
1047 retval = fcntl(signal_pipe[READ_END], F_GETFL, 0);
1049 err("error fcntl on read pipe: %s\n", strerror(errno));
1052 retval = fcntl(signal_pipe[READ_END], F_SETFL, retval | O_NONBLOCK);
1054 err("error fcntl on read pipe: %s\n", strerror(errno));
1058 retval = fcntl(signal_pipe[WRITE_END], F_GETFL, 0);
1060 err("error fcntl on write pipe: %s\n", strerror(errno));
1063 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, retval | O_NONBLOCK);
1065 err("error fcntl on write pipe: %s\n", strerror(errno));
1069 /* parse the rules and keep them in memory */
1071 udev_rules_init(&rules, 1);
1073 export_initial_seqnum();
1081 dbg("daemonized fork running\n");
1084 err("fork of daemon failed: %s\n", strerror(errno));
1088 dbg("child [%u] running, parent exits\n", pid);
1094 /* redirect std{out,err} fd's */
1096 dup2(fd, STDOUT_FILENO);
1097 dup2(fd, STDERR_FILENO);
1098 if (fd > STDERR_FILENO)
1101 /* set scheduling priority for the daemon */
1102 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
1107 /* become session leader */
1109 dbg("our session is %d\n", sid);
1111 /* OOM_DISABLE == -17 */
1112 fd = open("/proc/self/oom_adj", O_RDWR);
1114 err("error disabling OOM: %s\n", strerror(errno));
1116 write(fd, "-17", 3);
1120 fd = open("/dev/kmsg", O_WRONLY);
1122 const char *str = "<6>udevd version " UDEV_VERSION " started\n";
1124 write(fd, str, strlen(str));
1128 /* set signal handlers */
1129 memset(&act, 0x00, sizeof(struct sigaction));
1130 act.sa_handler = (void (*)(int)) sig_handler;
1131 sigemptyset(&act.sa_mask);
1132 act.sa_flags = SA_RESTART;
1133 sigaction(SIGINT, &act, NULL);
1134 sigaction(SIGTERM, &act, NULL);
1135 sigaction(SIGCHLD, &act, NULL);
1136 sigaction(SIGHUP, &act, NULL);
1138 /* watch rules directory */
1139 inotify_fd = inotify_init();
1140 if (inotify_fd >= 0) {
1141 char filename[PATH_MAX];
1143 inotify_add_watch(inotify_fd, udev_rules_dir, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1145 /* watch dynamic rules directory */
1146 strlcpy(filename, udev_root, sizeof(filename));
1147 strlcat(filename, "/"RULES_DYN_DIR, sizeof(filename));
1148 inotify_add_watch(inotify_fd, filename, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1149 } else if (errno == ENOSYS)
1150 err("the kernel does not support inotify, udevd can't monitor rules file changes\n");
1152 err("inotify_init failed: %s\n", strerror(errno));
1154 /* maximum limit of forked childs */
1155 value = getenv("UDEVD_MAX_CHILDS");
1157 max_childs = strtoul(value, NULL, 10);
1159 int memsize = mem_size_mb();
1161 max_childs = 128 + (memsize / 4);
1163 max_childs = UDEVD_MAX_CHILDS;
1165 info("initialize max_childs to %u\n", max_childs);
1167 /* start to throttle forking if maximum number of _running_ childs is reached */
1168 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
1170 max_childs_running = strtoull(value, NULL, 10);
1172 int cpus = cpu_count();
1174 max_childs_running = 8 + (8 * cpus);
1176 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
1178 info("initialize max_childs_running to %u\n", max_childs_running);
1180 /* clear environment for forked event processes */
1183 /* export log_priority , as called programs may want to follow that setting */
1184 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
1190 maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
1191 maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
1192 maxfd = UDEV_MAX(maxfd, inotify_fd);
1194 while (!udev_exit) {
1195 struct udevd_uevent_msg *msg;
1199 FD_SET(signal_pipe[READ_END], &readfds);
1200 FD_SET(udevd_sock, &readfds);
1201 FD_SET(uevent_netlink_sock, &readfds);
1202 if (inotify_fd >= 0)
1203 FD_SET(inotify_fd, &readfds);
1205 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
1208 err("error in select: %s\n", strerror(errno));
1212 /* get control message */
1213 if (FD_ISSET(udevd_sock, &readfds))
1216 /* get netlink message */
1217 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
1218 msg = get_netlink_msg();
1220 msg_queue_insert(msg);
1223 /* received a signal, clear our notification pipe */
1224 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
1227 read(signal_pipe[READ_END], &buf, sizeof(buf));
1230 /* rules directory inotify watch */
1231 if ((inotify_fd >= 0) && FD_ISSET(inotify_fd, &readfds)) {
1234 /* discard all possible events, we can just reload the config */
1235 if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes > 0) {
1239 buf = malloc(nbytes);
1241 err("error getting buffer for inotify, disable watching\n");
1245 read(inotify_fd, buf, nbytes);
1250 /* rules changed, set by inotify or a HUP signal */
1251 if (reload_config) {
1253 udev_rules_cleanup(&rules);
1254 udev_rules_init(&rules, 1);
1257 /* forked child has returned */
1258 if (sigchilds_waiting) {
1259 sigchilds_waiting = 0;
1266 msg_queue_manager();
1272 udev_rules_cleanup(&rules);
1276 if (signal_pipe[READ_END] >= 0)
1277 close(signal_pipe[READ_END]);
1278 if (signal_pipe[WRITE_END] >= 0)
1279 close(signal_pipe[WRITE_END]);
1281 if (udevd_sock >= 0)
1283 if (inotify_fd >= 0)
1285 if (uevent_netlink_sock >= 0)
1286 close(uevent_netlink_sock);