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/netlink.h>
44 #include "udev_libc_wrapper.h"
46 #include "udev_version.h"
47 #include "udev_utils.h"
51 #ifndef NETLINK_KOBJECT_UEVENT
52 #define NETLINK_KOBJECT_UEVENT 15
56 static int udevd_sock;
57 static int uevent_netlink_sock;
60 static int pipefds[2];
61 static volatile int sigchilds_waiting;
62 static volatile int run_msg_q;
63 static volatile int sig_flag;
64 static int init_phase = 1;
65 static int run_exec_q;
66 static int stop_exec_q;
68 static LIST_HEAD(msg_list);
69 static LIST_HEAD(exec_list);
70 static LIST_HEAD(running_list);
72 static void exec_queue_manager(void);
73 static void msg_queue_manager(void);
74 static void user_sighandler(void);
75 static void reap_sigchilds(void);
77 static char *udev_bin;
78 static unsigned long long expected_seqnum;
79 static int event_timeout;
80 static int max_childs;
81 static int max_childs_running;
85 void log_message (int priority, const char *format, ...)
89 if (priority > udev_log_priority)
92 va_start(args, format);
93 vsyslog(priority, format, args);
98 static void msg_dump_queue(void)
101 struct uevent_msg *msg;
103 list_for_each_entry(msg, &msg_list, node)
104 dbg("sequence %llu in queue", msg->seqnum);
108 static void run_queue_delete(struct uevent_msg *msg)
110 list_del(&msg->node);
114 /* orders the message in the queue by sequence number */
115 static void msg_queue_insert(struct uevent_msg *msg)
117 struct uevent_msg *loop_msg;
120 if (msg->seqnum == 0) {
121 dbg("no SEQNUM, move straight to the exec queue");
122 list_add(&msg->node, &exec_list);
127 /* store timestamp of queuing */
129 msg->queue_time = info.uptime;
131 /* with the first event we provide a phase of shorter timeout */
133 static long init_time;
136 init_time = info.uptime;
137 if (info.uptime - init_time >= UDEVD_INIT_TIME)
141 /* don't delay messages with timeout set */
143 dbg("move seq %llu with timeout %u to exec queue", msg->seqnum, msg->timeout);
144 list_add(&msg->node, &exec_list);
149 /* sort message by sequence number into list */
150 list_for_each_entry_reverse(loop_msg, &msg_list, node) {
151 if (loop_msg->seqnum < msg->seqnum)
154 if (loop_msg->seqnum == msg->seqnum) {
155 dbg("ignoring duplicate message seq %llu", msg->seqnum);
160 list_add(&msg->node, &loop_msg->node);
161 info("seq %llu queued, devpath '%s'", msg->seqnum, msg->devpath);
163 /* run msg queue manager */
169 /* forks event and removes event from run queue when finished */
170 static void execute_udev(struct uevent_msg *msg)
172 char *const argv[] = { "udev", msg->subsystem, NULL };
180 if (uevent_netlink_sock != -1)
181 close(uevent_netlink_sock);
185 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
186 execve(udev_bin, argv, msg->envp);
187 err("exec of child failed");
191 err("fork of child failed");
192 run_queue_delete(msg);
195 /* get SIGCHLD in main loop */
197 info("seq %llu forked, pid %d, %ld seconds old",
198 msg->seqnum, pid, info.uptime - msg->queue_time);
203 static int running_processes(void)
206 static char buf[4096];
211 f = open("/proc/stat", O_RDONLY);
215 len = read(f, buf, sizeof(buf));
223 pos = strstr(buf, "procs_running ");
227 if (sscanf(pos, "procs_running %u", &running) != 1)
233 /* return the number of process es in our session, count only until limit */
234 static int running_processes_in_session(pid_t session, int limit)
240 dir = opendir("/proc");
244 /* read process info from /proc */
245 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
251 pid_t ppid, pgrp, sess;
254 if (!isdigit(dent->d_name[0]))
257 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
258 procdir[sizeof(procdir)-1] = '\0';
260 f = open(procdir, O_RDONLY);
264 len = read(f, line, sizeof(line));
272 /* skip ugly program name */
273 pos = strrchr(line, ')') + 2;
277 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
280 /* count only processes in our session */
284 /* count only running, no sleeping processes */
289 if (limit > 0 && running >= limit)
297 static int compare_devpath(const char *running, const char *waiting)
301 for (i = 0; i < PATH_SIZE; i++) {
302 /* identical device event found */
303 if (running[i] == '\0' && waiting[i] == '\0')
306 /* parent device event found */
307 if (running[i] == '\0' && waiting[i] == '/')
310 /* child device event found */
311 if (running[i] == '/' && waiting[i] == '\0')
314 /* no matching event */
315 if (running[i] != waiting[i])
322 /* returns still running task for the same device, its parent or its physical device */
323 static int running_with_devpath(struct uevent_msg *msg, int limit)
325 struct uevent_msg *loop_msg;
326 int childs_count = 0;
328 if (msg->devpath == NULL)
331 /* skip any events with a timeout set */
332 if (msg->timeout != 0)
335 list_for_each_entry(loop_msg, &running_list, node) {
336 if (limit && childs_count++ > limit) {
337 dbg("%llu, maximum number (%i) of child reached", msg->seqnum, childs_count);
340 if (loop_msg->devpath == NULL)
343 /* return running parent/child device event */
344 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
345 dbg("%llu, child device event still running %llu (%s)",
346 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
350 /* return running physical device event */
351 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
352 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
353 dbg("%llu, physical device event still running %llu (%s)",
354 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
362 /* exec queue management routine executes the events and serializes events in the same sequence */
363 static void exec_queue_manager(void)
365 struct uevent_msg *loop_msg;
366 struct uevent_msg *tmp_msg;
369 if (list_empty(&exec_list))
372 running = running_processes();
373 dbg("%d processes runnning on system", running);
375 running = max_childs_running;
377 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
378 /* check running processes in our session and possibly throttle */
379 if (running >= max_childs_running) {
380 running = running_processes_in_session(sid, max_childs_running+10);
381 dbg("at least %d processes running in session", running);
382 if (running >= max_childs_running) {
383 dbg("delay seq %llu, cause too many processes already running",
389 if (running_with_devpath(loop_msg, max_childs) == 0) {
390 /* move event to run list */
391 list_move_tail(&loop_msg->node, &running_list);
392 execute_udev(loop_msg);
394 dbg("moved seq %llu to running list", loop_msg->seqnum);
396 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
400 static void msg_move_exec(struct uevent_msg *msg)
402 list_move_tail(&msg->node, &exec_list);
404 expected_seqnum = msg->seqnum+1;
405 dbg("moved seq %llu to exec, next expected is %llu",
406 msg->seqnum, expected_seqnum);
409 /* msg queue management routine handles the timeouts and dispatches the events */
410 static void msg_queue_manager(void)
412 struct uevent_msg *loop_msg;
413 struct uevent_msg *tmp_msg;
416 int timeout = event_timeout;
418 dbg("msg queue manager, next expected is %llu", expected_seqnum);
421 list_for_each_entry_safe(loop_msg, tmp_msg, &msg_list, node) {
422 /* move event with expected sequence to the exec list */
423 if (loop_msg->seqnum == expected_seqnum) {
424 msg_move_exec(loop_msg);
428 /* limit timeout during initialization phase */
430 timeout = UDEVD_INIT_EVENT_TIMEOUT;
431 dbg("initialization phase, limit timeout to %i seconds", UDEVD_INIT_EVENT_TIMEOUT);
434 /* move event with expired timeout to the exec list */
435 msg_age = info.uptime - loop_msg->queue_time;
436 dbg("seq %llu is %li seconds old", loop_msg->seqnum, msg_age);
437 if (msg_age >= timeout) {
438 msg_move_exec(loop_msg);
447 /* set timeout for remaining queued events */
448 if (list_empty(&msg_list) == 0) {
449 struct itimerval itv = {{0, 0}, {timeout - msg_age, 0}};
450 dbg("next event expires in %li seconds", timeout - msg_age);
451 setitimer(ITIMER_REAL, &itv, NULL);
455 static struct uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
459 struct uevent_msg *msg;
461 msg = malloc(sizeof(struct uevent_msg) + buf_size);
464 memset(msg, 0x00, sizeof(struct uevent_msg) + buf_size);
466 /* copy environment buffer and reconstruct envp */
467 memcpy(msg->envbuf, buf, buf_size);
469 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
473 key = &msg->envbuf[bufpos];
474 keylen = strlen(key);
476 bufpos += keylen + 1;
477 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
479 /* remember some keys for further processing */
480 if (strncmp(key, "ACTION=", 7) == 0)
481 msg->action = &key[7];
483 if (strncmp(key, "DEVPATH=", 8) == 0)
484 msg->devpath = &key[8];
486 if (strncmp(key, "SUBSYSTEM=", 10) == 0)
487 msg->subsystem = &key[10];
489 if (strncmp(key, "SEQNUM=", 7) == 0)
490 msg->seqnum = strtoull(&key[7], NULL, 10);
492 if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
493 msg->physdevpath = &key[12];
495 if (strncmp(key, "TIMEOUT=", 8) == 0)
496 msg->timeout = strtoull(&key[8], NULL, 10);
498 msg->envp[i++] = "UDEVD_EVENT=1";
504 /* receive the udevd message from userspace */
505 static struct uevent_msg *get_udevd_msg(void)
507 static struct udevd_msg usend_msg;
508 struct uevent_msg *msg;
511 struct cmsghdr *cmsg;
514 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
518 memset(&usend_msg, 0x00, sizeof(struct udevd_msg));
519 iov.iov_base = &usend_msg;
520 iov.iov_len = sizeof(struct udevd_msg);
522 memset(&smsg, 0x00, sizeof(struct msghdr));
525 smsg.msg_control = cred_msg;
526 smsg.msg_controllen = sizeof(cred_msg);
528 size = recvmsg(udevd_sock, &smsg, 0);
531 dbg("unable to receive udevd message");
534 cmsg = CMSG_FIRSTHDR(&smsg);
535 cred = (struct ucred *) CMSG_DATA(cmsg);
537 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
538 info("no sender credentials received, message ignored");
542 if (cred->uid != 0) {
543 info("sender uid=%i, message ignored", cred->uid);
547 if (strncmp(usend_msg.magic, UDEV_MAGIC, sizeof(UDEV_MAGIC)) != 0 ) {
548 info("message magic '%s' doesn't match, ignore it", usend_msg.magic);
552 switch (usend_msg.type) {
553 case UDEVD_UEVENT_UDEVSEND:
554 case UDEVD_UEVENT_INITSEND:
555 info("udevd event message received");
556 envbuf_size = size - offsetof(struct udevd_msg, envbuf);
557 dbg("envbuf_size=%i", envbuf_size);
558 msg = get_msg_from_envbuf(usend_msg.envbuf, envbuf_size);
561 msg->type = usend_msg.type;
563 case UDEVD_STOP_EXEC_QUEUE:
564 info("udevd message (STOP_EXEC_QUEUE) received");
567 case UDEVD_START_EXEC_QUEUE:
568 info("udevd message (START_EXEC_QUEUE) received");
570 exec_queue_manager();
572 case UDEVD_SET_LOG_LEVEL:
573 intval = (int *) usend_msg.envbuf;
574 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
575 udev_log_priority = *intval;
577 case UDEVD_SET_MAX_CHILDS:
578 intval = (int *) usend_msg.envbuf;
579 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
580 max_childs = *intval;
583 dbg("unknown message type");
588 /* receive the kernel user event message and do some sanity checks */
589 static struct uevent_msg *get_netlink_msg(void)
591 struct uevent_msg *msg;
594 static char buffer[UEVENT_BUFFER_SIZE + 512];
597 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
600 dbg("unable to receive udevd message");
604 if ((size_t)size > sizeof(buffer)-1)
605 size = sizeof(buffer)-1;
607 dbg("uevent_size=%li", (long)size);
609 /* start of event payload */
610 bufpos = strlen(buffer)+1;
611 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
614 msg->type = UDEVD_UEVENT_NETLINK;
616 /* validate message */
617 pos = strchr(buffer, '@');
619 dbg("invalid uevent '%s'", buffer);
625 if (msg->action == NULL) {
626 dbg("no ACTION in payload found, skip event '%s'", buffer);
631 if (strcmp(msg->action, buffer) != 0) {
632 dbg("ACTION in payload does not match uevent, skip event '%s'", buffer);
640 static void asmlinkage sig_handler(int signum)
650 /* set flag, then write to pipe if needed */
655 /* set flag, then write to pipe if needed */
656 sigchilds_waiting = 1;
662 /* if pipe is empty, write to pipe to force select to return
663 * immediately when it gets called
666 rc = write(pipefds[1],&signum,sizeof(signum));
672 static void udev_done(int pid)
674 /* find msg associated with pid and delete it */
675 struct uevent_msg *msg;
678 list_for_each_entry(msg, &running_list, node) {
679 if (msg->pid == pid) {
681 info("seq %llu exit, %ld seconds old", msg->seqnum, info.uptime - msg->queue_time);
682 run_queue_delete(msg);
684 /* we want to run the exec queue manager since there may
685 * be events waiting with the devpath of the one that
694 static void reap_sigchilds(void)
697 int pid = waitpid(-1, NULL, WNOHANG);
698 if ((pid == -1) || (pid == 0))
704 /* just read everything from the pipe and clear the flag,
705 * the flags was set in the signal handler
707 static void user_sighandler(void)
712 int rc = read(pipefds[0], &sig, sizeof(sig));
720 static int init_udevd_socket(void)
722 struct sockaddr_un saddr;
724 const int feature_on = 1;
727 memset(&saddr, 0x00, sizeof(saddr));
728 saddr.sun_family = AF_LOCAL;
729 /* use abstract namespace for socket path */
730 strcpy(&saddr.sun_path[1], UDEVD_SOCK_PATH);
731 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
733 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
734 if (udevd_sock == -1) {
735 err("error getting socket, %s", strerror(errno));
739 /* the bind takes care of ensuring only one copy running */
740 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
742 err("bind failed, %s", strerror(errno));
747 /* enable receiving of the sender credentials */
748 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
753 static int init_uevent_netlink_sock(void)
755 struct sockaddr_nl snl;
758 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
759 snl.nl_family = AF_NETLINK;
760 snl.nl_pid = getpid();
761 snl.nl_groups = 0xffffffff;
763 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
764 if (uevent_netlink_sock == -1) {
765 dbg("error getting socket, %s", strerror(errno));
769 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl,
770 sizeof(struct sockaddr_nl));
772 dbg("bind failed, %s", strerror(errno));
773 close(uevent_netlink_sock);
774 uevent_netlink_sock = -1;
781 int main(int argc, char *argv[], char *envp[])
786 struct sigaction act;
789 int uevent_netlink_active = 0;
793 logging_init("udevd");
795 dbg("version %s", UDEV_VERSION);
798 err("need to be root, exit");
802 for (i = 1 ; i < argc; i++) {
804 if (strcmp(arg, "--daemon") == 0 || strcmp(arg, "-d") == 0) {
805 info("will daemonize");
808 if (strcmp(arg, "--stop-exec-queue") == 0) {
809 info("will not execute events until START_EXEC_QUEUE is received");
819 dbg("damonized fork running");
822 err("fork of daemon failed");
830 /* become session leader */
832 dbg("our session is %d", sid);
835 umask(umask(077) | 022);
837 /*set a reasonable scheduling priority for the daemon */
838 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
840 /* Set fds to dev/null */
841 fd = open( "/dev/null", O_RDWR );
849 err("error opening /dev/null %s", strerror(errno));
851 /* setup signal handler pipe */
852 retval = pipe(pipefds);
854 err("error getting pipes: %s", strerror(errno));
858 retval = fcntl(pipefds[0], F_SETFL, O_NONBLOCK);
860 err("error fcntl on read pipe: %s", strerror(errno));
863 retval = fcntl(pipefds[0], F_SETFD, FD_CLOEXEC);
865 err("error fcntl on read pipe: %s", strerror(errno));
867 retval = fcntl(pipefds[1], F_SETFL, O_NONBLOCK);
869 err("error fcntl on write pipe: %s", strerror(errno));
872 retval = fcntl(pipefds[1], F_SETFD, FD_CLOEXEC);
874 err("error fcntl on write pipe: %s", strerror(errno));
876 /* set signal handlers */
877 memset(&act, 0x00, sizeof(struct sigaction));
878 act.sa_handler = (void (*)(int)) sig_handler;
879 sigemptyset(&act.sa_mask);
880 act.sa_flags = SA_RESTART;
881 sigaction(SIGINT, &act, NULL);
882 sigaction(SIGTERM, &act, NULL);
883 sigaction(SIGALRM, &act, NULL);
884 sigaction(SIGCHLD, &act, NULL);
886 if (init_uevent_netlink_sock() < 0) {
887 dbg("uevent socket not available");
890 if (init_udevd_socket() < 0) {
891 if (errno == EADDRINUSE)
892 dbg("another udevd running, exit");
894 dbg("error initialising udevd socket: %s", strerror(errno));
899 /* override of forked udev binary, used for testing */
900 udev_bin = getenv("UDEV_BIN");
901 if (udev_bin != NULL)
902 info("udev binary is set to '%s'", udev_bin);
906 /* init of expected_seqnum value */
907 value = getenv("UDEVD_EXPECTED_SEQNUM");
909 expected_seqnum = strtoull(value, NULL, 10);
910 info("initialize expected_seqnum to %llu", expected_seqnum);
913 /* timeout to wait for missing events */
914 value = getenv("UDEVD_EVENT_TIMEOUT");
916 event_timeout = strtoul(value, NULL, 10);
918 event_timeout = UDEVD_EVENT_TIMEOUT;
919 info("initialize event_timeout to %u", event_timeout);
921 /* maximum limit of forked childs */
922 value = getenv("UDEVD_MAX_CHILDS");
924 max_childs = strtoul(value, NULL, 10);
926 max_childs = UDEVD_MAX_CHILDS;
927 info("initialize max_childs to %u", max_childs);
929 /* start to throttle forking if maximum number of _running_ childs is reached */
930 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
932 max_childs_running = strtoull(value, NULL, 10);
934 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
935 info("initialize max_childs_running to %u", max_childs_running);
938 FD_SET(udevd_sock, &readfds);
939 if (uevent_netlink_sock != -1)
940 FD_SET(uevent_netlink_sock, &readfds);
941 FD_SET(pipefds[0], &readfds);
942 maxsockplus = udevd_sock+1;
944 struct uevent_msg *msg;
946 fd_set workreadfds = readfds;
947 retval = select(maxsockplus, &workreadfds, NULL, NULL, NULL);
951 dbg("error in select: %s", strerror(errno));
955 if (FD_ISSET(udevd_sock, &workreadfds)) {
956 msg = get_udevd_msg();
958 /* discard kernel messages if netlink is active */
959 if (uevent_netlink_active && msg->type == UDEVD_UEVENT_UDEVSEND && msg->seqnum != 0) {
960 dbg("skip uevent_helper message, netlink is active");
964 msg_queue_insert(msg);
968 if (FD_ISSET(uevent_netlink_sock, &workreadfds)) {
969 msg = get_netlink_msg();
971 msg_queue_insert(msg);
972 /* disable udevsend with first netlink message */
973 if (!uevent_netlink_active) {
974 info("uevent_nl message received, disable udevsend messages");
975 uevent_netlink_active = 1;
980 if (FD_ISSET(pipefds[0], &workreadfds))
983 if (sigchilds_waiting) {
984 sigchilds_waiting = 0;
994 /* clean up running_list before calling exec_queue_manager() */
995 if (sigchilds_waiting) {
996 sigchilds_waiting = 0;
1002 exec_queue_manager();