2 * udevd.c - hotplug event serializer
4 * Copyright (C) 2004-2005 Kay Sievers <kay.sievers@vrfy.org>
5 * Copyright (C) 2004 Chris Friesen <chris_friesen@sympatico.ca>
8 * This program is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License as published by the
10 * Free Software Foundation version 2 of the License.
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 675 Mass Ave, Cambridge, MA 02139, USA.
33 #include <sys/select.h>
36 #include <sys/types.h>
37 #include <sys/socket.h>
39 #include <sys/sysinfo.h>
41 #include <linux/types.h>
42 #include <linux/netlink.h>
45 #include "udev_libc_wrapper.h"
47 #include "udev_version.h"
48 #include "udev_utils.h"
53 static int udevd_sock;
54 static int uevent_netlink_sock;
57 static int pipefds[2];
58 static volatile int sigchilds_waiting;
59 static volatile int run_msg_q;
60 static volatile int sig_flag;
61 static int init_phase = 1;
62 static int run_exec_q;
63 static int stop_exec_q;
65 static LIST_HEAD(msg_list);
66 static LIST_HEAD(exec_list);
67 static LIST_HEAD(running_list);
69 static void exec_queue_manager(void);
70 static void msg_queue_manager(void);
71 static void user_sighandler(void);
72 static void reap_sigchilds(void);
74 static char *udev_bin;
75 static unsigned long long expected_seqnum;
76 static int event_timeout;
77 static int max_childs;
78 static int max_childs_running;
82 void log_message (int priority, const char *format, ...)
86 if (priority > udev_log_priority)
89 va_start(args, format);
90 vsyslog(priority, format, args);
95 static void msg_dump_queue(void)
98 struct uevent_msg *msg;
100 list_for_each_entry(msg, &msg_list, node)
101 dbg("sequence %llu in queue", msg->seqnum);
105 static void msg_queue_delete(struct uevent_msg *msg)
107 list_del(&msg->node);
111 /* orders the message in the queue by sequence number */
112 static void msg_queue_insert(struct uevent_msg *msg)
114 struct uevent_msg *loop_msg;
117 if (msg->seqnum == 0) {
118 dbg("no SEQNUM, move straight to the exec queue");
119 list_add(&msg->node, &exec_list);
124 /* store timestamp of queuing */
126 msg->queue_time = info.uptime;
128 /* with the first event we provide a phase of shorter timeout */
130 static long init_time;
133 init_time = info.uptime;
134 if (info.uptime - init_time >= UDEVD_INIT_TIME)
138 /* don't delay messages with timeout set */
140 dbg("move seq %llu with timeout %u to exec queue", msg->seqnum, msg->timeout);
141 list_add(&msg->node, &exec_list);
146 /* sort message by sequence number into list */
147 list_for_each_entry_reverse(loop_msg, &msg_list, node) {
148 if (loop_msg->seqnum < msg->seqnum)
151 if (loop_msg->seqnum == msg->seqnum) {
152 dbg("ignoring duplicate message seq %llu", msg->seqnum);
157 list_add(&msg->node, &loop_msg->node);
158 info("seq %llu queued, devpath '%s'", msg->seqnum, msg->devpath);
160 /* run msg queue manager */
166 /* forks event and removes event from run queue when finished */
167 static void udev_event_fork(struct uevent_msg *msg)
169 char *const argv[] = { "udev", msg->subsystem, NULL };
177 if (uevent_netlink_sock != -1)
178 close(uevent_netlink_sock);
181 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
182 execve(udev_bin, argv, msg->envp);
183 err("exec of child failed");
186 err("fork of child failed");
187 msg_queue_delete(msg);
190 /* get SIGCHLD in main loop */
192 info("seq %llu forked, pid %d, %ld seconds old",
193 msg->seqnum, pid, info.uptime - msg->queue_time);
198 static int running_processes(void)
201 static char buf[4096];
206 f = open("/proc/stat", O_RDONLY);
210 len = read(f, buf, sizeof(buf));
218 pos = strstr(buf, "procs_running ");
222 if (sscanf(pos, "procs_running %u", &running) != 1)
228 /* return the number of process es in our session, count only until limit */
229 static int running_processes_in_session(pid_t session, int limit)
235 dir = opendir("/proc");
239 /* read process info from /proc */
240 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
246 pid_t ppid, pgrp, sess;
249 if (!isdigit(dent->d_name[0]))
252 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
253 procdir[sizeof(procdir)-1] = '\0';
255 f = open(procdir, O_RDONLY);
259 len = read(f, line, sizeof(line));
267 /* skip ugly program name */
268 pos = strrchr(line, ')') + 2;
272 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
275 /* count only processes in our session */
279 /* count only running, no sleeping processes */
284 if (limit > 0 && running >= limit)
292 static int compare_devpath(const char *running, const char *waiting)
296 for (i = 0; i < PATH_SIZE; i++) {
297 /* identical device event found */
298 if (running[i] == '\0' && waiting[i] == '\0')
301 /* parent device event found */
302 if (running[i] == '\0' && waiting[i] == '/')
305 /* child device event found */
306 if (running[i] == '/' && waiting[i] == '\0')
309 /* no matching event */
310 if (running[i] != waiting[i])
317 /* returns still running task for the same device, its parent or its physical device */
318 static int running_with_devpath(struct uevent_msg *msg, int limit)
320 struct uevent_msg *loop_msg;
321 int childs_count = 0;
323 if (msg->devpath == NULL)
326 /* skip any events with a timeout set */
327 if (msg->timeout != 0)
330 list_for_each_entry(loop_msg, &running_list, node) {
331 if (limit && childs_count++ > limit) {
332 dbg("%llu, maximum number (%i) of child reached", msg->seqnum, childs_count);
335 if (loop_msg->devpath == NULL)
338 /* return running parent/child device event */
339 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
340 dbg("%llu, child device event still running %llu (%s)",
341 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
345 /* return running physical device event */
346 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
347 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
348 dbg("%llu, physical device event still running %llu (%s)",
349 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
357 /* exec queue management routine executes the events and serializes events in the same sequence */
358 static void exec_queue_manager(void)
360 struct uevent_msg *loop_msg;
361 struct uevent_msg *tmp_msg;
364 if (list_empty(&exec_list))
367 running = running_processes();
368 dbg("%d processes runnning on system", running);
370 running = max_childs_running;
372 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
373 /* check running processes in our session and possibly throttle */
374 if (running >= max_childs_running) {
375 running = running_processes_in_session(sid, max_childs_running+10);
376 dbg("at least %d processes running in session", running);
377 if (running >= max_childs_running) {
378 dbg("delay seq %llu, cause too many processes already running",
384 if (running_with_devpath(loop_msg, max_childs) == 0) {
385 /* move event to run list */
386 list_move_tail(&loop_msg->node, &running_list);
387 udev_event_fork(loop_msg);
389 dbg("moved seq %llu to running list", loop_msg->seqnum);
391 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
395 static void msg_move_exec(struct uevent_msg *msg)
397 list_move_tail(&msg->node, &exec_list);
399 expected_seqnum = msg->seqnum+1;
400 dbg("moved seq %llu to exec, next expected is %llu",
401 msg->seqnum, expected_seqnum);
404 /* msg queue management routine handles the timeouts and dispatches the events */
405 static void msg_queue_manager(void)
407 struct uevent_msg *loop_msg;
408 struct uevent_msg *tmp_msg;
411 int timeout = event_timeout;
413 dbg("msg queue manager, next expected is %llu", expected_seqnum);
416 list_for_each_entry_safe(loop_msg, tmp_msg, &msg_list, node) {
417 /* move event with expected sequence to the exec list */
418 if (loop_msg->seqnum == expected_seqnum) {
419 msg_move_exec(loop_msg);
423 /* limit timeout during initialization phase */
425 timeout = UDEVD_INIT_EVENT_TIMEOUT;
426 dbg("initialization phase, limit timeout to %i seconds", UDEVD_INIT_EVENT_TIMEOUT);
429 /* move event with expired timeout to the exec list */
430 msg_age = info.uptime - loop_msg->queue_time;
431 dbg("seq %llu is %li seconds old", loop_msg->seqnum, msg_age);
432 if (msg_age >= timeout) {
433 msg_move_exec(loop_msg);
442 /* set timeout for remaining queued events */
443 if (list_empty(&msg_list) == 0) {
444 struct itimerval itv = {{0, 0}, {timeout - msg_age, 0}};
445 dbg("next event expires in %li seconds", timeout - msg_age);
446 setitimer(ITIMER_REAL, &itv, NULL);
450 static struct uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
454 struct uevent_msg *msg;
458 msg = malloc(sizeof(struct uevent_msg) + buf_size);
461 memset(msg, 0x00, sizeof(struct uevent_msg) + buf_size);
463 /* copy environment buffer and reconstruct envp */
464 memcpy(msg->envbuf, buf, buf_size);
466 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
470 key = &msg->envbuf[bufpos];
471 keylen = strlen(key);
473 bufpos += keylen + 1;
474 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
476 /* remember some keys for further processing */
477 if (strncmp(key, "ACTION=", 7) == 0)
478 msg->action = &key[7];
479 else if (strncmp(key, "DEVPATH=", 8) == 0)
480 msg->devpath = &key[8];
481 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
482 msg->subsystem = &key[10];
483 else if (strncmp(key, "SEQNUM=", 7) == 0)
484 msg->seqnum = strtoull(&key[7], NULL, 10);
485 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
486 msg->physdevpath = &key[12];
487 else if (strncmp(key, "MAJOR=", 6) == 0)
488 major = strtoull(&key[6], NULL, 10);
489 else if (strncmp(key, "MINOR=", 6) == 0)
490 minor = strtoull(&key[6], NULL, 10);
491 else if (strncmp(key, "TIMEOUT=", 8) == 0)
492 msg->timeout = strtoull(&key[8], NULL, 10);
494 msg->devt = makedev(major, minor);
495 msg->envp[i++] = "UDEVD_EVENT=1";
501 /* receive the udevd message from userspace */
502 static struct uevent_msg *get_udevd_msg(void)
504 static struct udevd_msg usend_msg;
505 struct uevent_msg *msg;
508 struct cmsghdr *cmsg;
511 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
515 memset(&usend_msg, 0x00, sizeof(struct udevd_msg));
516 iov.iov_base = &usend_msg;
517 iov.iov_len = sizeof(struct udevd_msg);
519 memset(&smsg, 0x00, sizeof(struct msghdr));
522 smsg.msg_control = cred_msg;
523 smsg.msg_controllen = sizeof(cred_msg);
525 size = recvmsg(udevd_sock, &smsg, 0);
528 dbg("unable to receive udevd message");
531 cmsg = CMSG_FIRSTHDR(&smsg);
532 cred = (struct ucred *) CMSG_DATA(cmsg);
534 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
535 info("no sender credentials received, message ignored");
539 if (cred->uid != 0) {
540 info("sender uid=%i, message ignored", cred->uid);
544 if (strncmp(usend_msg.magic, UDEV_MAGIC, sizeof(UDEV_MAGIC)) != 0 ) {
545 info("message magic '%s' doesn't match, ignore it", usend_msg.magic);
549 switch (usend_msg.type) {
550 case UDEVD_UEVENT_UDEVSEND:
551 case UDEVD_UEVENT_INITSEND:
552 info("udevd event message received");
553 envbuf_size = size - offsetof(struct udevd_msg, envbuf);
554 dbg("envbuf_size=%i", envbuf_size);
555 msg = get_msg_from_envbuf(usend_msg.envbuf, envbuf_size);
558 msg->type = usend_msg.type;
560 case UDEVD_STOP_EXEC_QUEUE:
561 info("udevd message (STOP_EXEC_QUEUE) received");
564 case UDEVD_START_EXEC_QUEUE:
565 info("udevd message (START_EXEC_QUEUE) received");
567 exec_queue_manager();
569 case UDEVD_SET_LOG_LEVEL:
570 intval = (int *) usend_msg.envbuf;
571 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
572 udev_log_priority = *intval;
574 case UDEVD_SET_MAX_CHILDS:
575 intval = (int *) usend_msg.envbuf;
576 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
577 max_childs = *intval;
580 dbg("unknown message type");
585 /* receive the kernel user event message and do some sanity checks */
586 static struct uevent_msg *get_netlink_msg(void)
588 struct uevent_msg *msg;
591 static char buffer[UEVENT_BUFFER_SIZE + 512];
594 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
597 dbg("unable to receive udevd message");
601 if ((size_t)size > sizeof(buffer)-1)
602 size = sizeof(buffer)-1;
604 dbg("uevent_size=%zi", size);
606 /* start of event payload */
607 bufpos = strlen(buffer)+1;
608 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
611 msg->type = UDEVD_UEVENT_NETLINK;
613 /* validate message */
614 pos = strchr(buffer, '@');
616 dbg("invalid uevent '%s'", buffer);
622 if (msg->action == NULL) {
623 dbg("no ACTION in payload found, skip event '%s'", buffer);
628 if (strcmp(msg->action, buffer) != 0) {
629 dbg("ACTION in payload does not match uevent, skip event '%s'", buffer);
637 static void asmlinkage sig_handler(int signum)
647 /* set flag, then write to pipe if needed */
652 /* set flag, then write to pipe if needed */
653 sigchilds_waiting = 1;
659 /* if pipe is empty, write to pipe to force select to return
660 * immediately when it gets called
663 rc = write(pipefds[1],&signum,sizeof(signum));
669 static void udev_done(int pid)
671 /* find msg associated with pid and delete it */
672 struct uevent_msg *msg;
675 list_for_each_entry(msg, &running_list, node) {
676 if (msg->pid == pid) {
678 info("seq %llu exit, %ld seconds old", msg->seqnum, info.uptime - msg->queue_time);
679 msg_queue_delete(msg);
681 /* we want to run the exec queue manager since there may
682 * be events waiting with the devpath of the one that
691 static void reap_sigchilds(void)
694 int pid = waitpid(-1, NULL, WNOHANG);
695 if ((pid == -1) || (pid == 0))
701 /* just read everything from the pipe and clear the flag,
702 * the flags was set in the signal handler
704 static void user_sighandler(void)
709 int rc = read(pipefds[0], &sig, sizeof(sig));
717 static int init_udevd_socket(void)
719 struct sockaddr_un saddr;
720 const int buffersize = 1024 * 1024;
722 const int feature_on = 1;
725 memset(&saddr, 0x00, sizeof(saddr));
726 saddr.sun_family = AF_LOCAL;
727 /* use abstract namespace for socket path */
728 strcpy(&saddr.sun_path[1], UDEVD_SOCK_PATH);
729 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
731 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
732 if (udevd_sock == -1) {
733 err("error getting socket, %s", strerror(errno));
737 /* set receive buffersize */
738 setsockopt(udevd_sock, SOL_SOCKET, SO_RCVBUF, &buffersize, sizeof(buffersize));
740 /* the bind takes care of ensuring only one copy running */
741 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
743 err("bind failed, %s", strerror(errno));
748 /* enable receiving of the sender credentials */
749 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
754 static int init_uevent_netlink_sock(void)
756 struct sockaddr_nl snl;
757 const int buffersize = 1024 * 1024;
760 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
761 snl.nl_family = AF_NETLINK;
762 snl.nl_pid = getpid();
763 snl.nl_groups = 0xffffffff;
765 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
766 if (uevent_netlink_sock == -1) {
767 dbg("error getting socket, %s", strerror(errno));
771 /* set receive buffersize */
772 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUF, &buffersize, sizeof(buffersize));
774 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl,
775 sizeof(struct sockaddr_nl));
777 dbg("bind failed, %s", strerror(errno));
778 close(uevent_netlink_sock);
779 uevent_netlink_sock = -1;
786 int main(int argc, char *argv[], char *envp[])
791 struct sigaction act;
794 int uevent_netlink_active = 0;
798 logging_init("udevd");
800 dbg("version %s", UDEV_VERSION);
803 err("need to be root, exit");
807 for (i = 1 ; i < argc; i++) {
809 if (strcmp(arg, "--daemon") == 0 || strcmp(arg, "-d") == 0) {
810 info("will daemonize");
813 if (strcmp(arg, "--stop-exec-queue") == 0) {
814 info("will not execute events until START_EXEC_QUEUE is received");
824 dbg("damonized fork running");
827 err("fork of daemon failed");
835 /* become session leader */
837 dbg("our session is %d", sid);
840 umask(umask(077) | 022);
842 /*set a reasonable scheduling priority for the daemon */
843 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
845 /* Set fds to dev/null */
846 fd = open( "/dev/null", O_RDWR );
854 err("error opening /dev/null %s", strerror(errno));
856 /* setup signal handler pipe */
857 retval = pipe(pipefds);
859 err("error getting pipes: %s", strerror(errno));
863 retval = fcntl(pipefds[0], F_SETFL, O_NONBLOCK);
865 err("error fcntl on read pipe: %s", strerror(errno));
868 retval = fcntl(pipefds[0], F_SETFD, FD_CLOEXEC);
870 err("error fcntl on read pipe: %s", strerror(errno));
872 retval = fcntl(pipefds[1], F_SETFL, O_NONBLOCK);
874 err("error fcntl on write pipe: %s", strerror(errno));
877 retval = fcntl(pipefds[1], F_SETFD, FD_CLOEXEC);
879 err("error fcntl on write pipe: %s", strerror(errno));
881 /* set signal handlers */
882 memset(&act, 0x00, sizeof(struct sigaction));
883 act.sa_handler = (void (*)(int)) sig_handler;
884 sigemptyset(&act.sa_mask);
885 act.sa_flags = SA_RESTART;
886 sigaction(SIGINT, &act, NULL);
887 sigaction(SIGTERM, &act, NULL);
888 sigaction(SIGALRM, &act, NULL);
889 sigaction(SIGCHLD, &act, NULL);
891 if (init_uevent_netlink_sock() < 0) {
892 dbg("uevent socket not available");
895 if (init_udevd_socket() < 0) {
896 if (errno == EADDRINUSE)
897 dbg("another udevd running, exit");
899 dbg("error initialising udevd socket: %s", strerror(errno));
904 /* override of forked udev binary, used for testing */
905 udev_bin = getenv("UDEV_BIN");
906 if (udev_bin != NULL)
907 info("udev binary is set to '%s'", udev_bin);
911 /* init of expected_seqnum value */
912 value = getenv("UDEVD_EXPECTED_SEQNUM");
914 expected_seqnum = strtoull(value, NULL, 10);
915 info("initialize expected_seqnum to %llu", expected_seqnum);
918 /* timeout to wait for missing events */
919 value = getenv("UDEVD_EVENT_TIMEOUT");
921 event_timeout = strtoul(value, NULL, 10);
923 event_timeout = UDEVD_EVENT_TIMEOUT;
924 info("initialize event_timeout to %u", event_timeout);
926 /* maximum limit of forked childs */
927 value = getenv("UDEVD_MAX_CHILDS");
929 max_childs = strtoul(value, NULL, 10);
931 max_childs = UDEVD_MAX_CHILDS;
932 info("initialize max_childs to %u", max_childs);
934 /* start to throttle forking if maximum number of _running_ childs is reached */
935 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
937 max_childs_running = strtoull(value, NULL, 10);
939 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
940 info("initialize max_childs_running to %u", max_childs_running);
943 FD_SET(udevd_sock, &readfds);
944 if (uevent_netlink_sock != -1)
945 FD_SET(uevent_netlink_sock, &readfds);
946 FD_SET(pipefds[0], &readfds);
947 maxsockplus = udevd_sock+1;
949 struct uevent_msg *msg;
951 fd_set workreadfds = readfds;
952 retval = select(maxsockplus, &workreadfds, NULL, NULL, NULL);
956 dbg("error in select: %s", strerror(errno));
960 if (FD_ISSET(udevd_sock, &workreadfds)) {
961 msg = get_udevd_msg();
963 /* discard kernel messages if netlink is active */
964 if (uevent_netlink_active && msg->type == UDEVD_UEVENT_UDEVSEND && msg->seqnum != 0) {
965 dbg("skip uevent_helper message, netlink is active");
969 msg_queue_insert(msg);
973 if (FD_ISSET(uevent_netlink_sock, &workreadfds)) {
974 msg = get_netlink_msg();
976 msg_queue_insert(msg);
977 /* disable udevsend with first netlink message */
978 if (!uevent_netlink_active) {
979 info("uevent_nl message received, disable udevsend messages");
980 uevent_netlink_active = 1;
985 if (FD_ISSET(pipefds[0], &workreadfds))
988 if (sigchilds_waiting) {
989 sigchilds_waiting = 0;
999 /* clean up running_list before calling exec_queue_manager() */
1000 if (sigchilds_waiting) {
1001 sigchilds_waiting = 0;
1007 exec_queue_manager();