2 * udevd.c - event listener and 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.
34 #include <sys/select.h>
37 #include <sys/types.h>
38 #include <sys/socket.h>
40 #include <sys/sysinfo.h>
42 #include <linux/types.h>
43 #include <linux/netlink.h>
46 #include "udev_libc_wrapper.h"
48 #include "udev_version.h"
49 #include "udev_utils.h"
54 static int udevd_sock;
55 static int uevent_netlink_sock;
58 static int pipefds[2] = {-1, -1};
59 static volatile int sigchilds_waiting;
60 static volatile int run_msg_q;
61 static volatile int sig_flag;
62 static volatile int udev_exit;
63 static int init_phase = 1;
64 static int run_exec_q;
65 static int stop_exec_q;
66 static char *udev_bin;
67 static int event_timeout;
68 static int max_childs;
69 static int max_childs_running;
70 static unsigned long long expected_seqnum;
73 static LIST_HEAD(msg_list);
74 static LIST_HEAD(exec_list);
75 static LIST_HEAD(running_list);
79 void log_message (int priority, const char *format, ...)
83 if (priority > udev_log_priority)
86 va_start(args, format);
87 vsyslog(priority, format, args);
92 static void msg_dump_queue(void)
95 struct uevent_msg *msg;
97 list_for_each_entry(msg, &msg_list, node)
98 dbg("sequence %llu in queue", msg->seqnum);
102 static void msg_queue_delete(struct uevent_msg *msg)
104 list_del(&msg->node);
108 /* orders the message in the queue by sequence number */
109 static void msg_queue_insert(struct uevent_msg *msg)
111 struct uevent_msg *loop_msg;
114 if (msg->seqnum == 0) {
115 dbg("no SEQNUM, move straight to the exec queue");
116 list_add(&msg->node, &exec_list);
121 /* store timestamp of queuing */
123 msg->queue_time = info.uptime;
125 /* with the first event we provide a phase of shorter timeout */
127 static long init_time;
130 init_time = info.uptime;
131 if (info.uptime - init_time >= UDEVD_INIT_TIME)
135 /* don't delay messages with timeout set */
137 info("seq %llu with timeout %u seconds will be execute without queuing, '%s' '%s'",
138 msg->seqnum, msg->timeout, msg->action, msg->devpath);
139 list_add(&msg->node, &exec_list);
144 /* sort message by sequence number into list */
145 list_for_each_entry_reverse(loop_msg, &msg_list, node) {
146 if (loop_msg->seqnum < msg->seqnum)
149 if (loop_msg->seqnum == msg->seqnum) {
150 dbg("ignoring duplicate message seq %llu", msg->seqnum);
155 list_add(&msg->node, &loop_msg->node);
156 info("seq %llu queued, '%s' '%s'", msg->seqnum, msg->action, msg->devpath);
158 /* run msg queue manager */
164 /* forks event and removes event from run queue when finished */
165 static void udev_event_run(struct uevent_msg *msg)
167 char *const argv[] = { "udev", msg->subsystem, NULL };
175 if (uevent_netlink_sock != -1)
176 close(uevent_netlink_sock);
179 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
180 execve(udev_bin, argv, msg->envp);
181 err("exec of child failed");
184 err("fork of child failed");
185 msg_queue_delete(msg);
188 /* get SIGCHLD in main loop */
190 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
191 msg->seqnum, pid, msg->action, msg->subsystem, info.uptime - msg->queue_time);
196 static int running_processes(void)
199 static char buf[4096];
204 f = open("/proc/stat", O_RDONLY);
208 len = read(f, buf, sizeof(buf));
216 pos = strstr(buf, "procs_running ");
220 if (sscanf(pos, "procs_running %u", &running) != 1)
226 /* return the number of process es in our session, count only until limit */
227 static int running_processes_in_session(pid_t session, int limit)
233 dir = opendir("/proc");
237 /* read process info from /proc */
238 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
244 pid_t ppid, pgrp, sess;
247 if (!isdigit(dent->d_name[0]))
250 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
251 procdir[sizeof(procdir)-1] = '\0';
253 f = open(procdir, O_RDONLY);
257 len = read(f, line, sizeof(line));
265 /* skip ugly program name */
266 pos = strrchr(line, ')') + 2;
270 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
273 /* count only processes in our session */
277 /* count only running, no sleeping processes */
282 if (limit > 0 && running >= limit)
290 static int compare_devpath(const char *running, const char *waiting)
294 for (i = 0; i < PATH_SIZE; i++) {
295 /* identical device event found */
296 if (running[i] == '\0' && waiting[i] == '\0')
299 /* parent device event found */
300 if (running[i] == '\0' && waiting[i] == '/')
303 /* child device event found */
304 if (running[i] == '/' && waiting[i] == '\0')
307 /* no matching event */
308 if (running[i] != waiting[i])
315 /* returns still running task for the same device, its parent or its physical device */
316 static int running_with_devpath(struct uevent_msg *msg, int limit)
318 struct uevent_msg *loop_msg;
319 int childs_count = 0;
321 if (msg->devpath == NULL)
324 /* skip any events with a timeout set */
325 if (msg->timeout != 0)
328 list_for_each_entry(loop_msg, &running_list, node) {
329 if (limit && childs_count++ > limit) {
330 dbg("%llu, maximum number (%i) of child reached", msg->seqnum, childs_count);
333 if (loop_msg->devpath == NULL)
336 /* return running parent/child device event */
337 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
338 dbg("%llu, child device event still running %llu (%s)",
339 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
343 /* return running physical device event */
344 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
345 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
346 dbg("%llu, physical device event still running %llu (%s)",
347 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
355 /* exec queue management routine executes the events and serializes events in the same sequence */
356 static void exec_queue_manager(void)
358 struct uevent_msg *loop_msg;
359 struct uevent_msg *tmp_msg;
362 if (list_empty(&exec_list))
365 running = running_processes();
366 dbg("%d processes runnning on system", running);
368 running = max_childs_running;
370 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
371 /* check running processes in our session and possibly throttle */
372 if (running >= max_childs_running) {
373 running = running_processes_in_session(sid, max_childs_running+10);
374 dbg("at least %d processes running in session", running);
375 if (running >= max_childs_running) {
376 dbg("delay seq %llu, cause too many processes already running",
382 if (running_with_devpath(loop_msg, max_childs) == 0) {
383 /* move event to run list */
384 list_move_tail(&loop_msg->node, &running_list);
385 udev_event_run(loop_msg);
387 dbg("moved seq %llu to running list", loop_msg->seqnum);
389 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
393 static void msg_move_exec(struct uevent_msg *msg)
395 list_move_tail(&msg->node, &exec_list);
397 expected_seqnum = msg->seqnum+1;
398 dbg("moved seq %llu to exec, next expected is %llu",
399 msg->seqnum, expected_seqnum);
402 /* msg queue management routine handles the timeouts and dispatches the events */
403 static void msg_queue_manager(void)
405 struct uevent_msg *loop_msg;
406 struct uevent_msg *tmp_msg;
409 int timeout = event_timeout;
411 dbg("msg queue manager, next expected is %llu", expected_seqnum);
414 list_for_each_entry_safe(loop_msg, tmp_msg, &msg_list, node) {
415 /* move event with expected sequence to the exec list */
416 if (loop_msg->seqnum == expected_seqnum) {
417 msg_move_exec(loop_msg);
421 /* limit timeout during initialization phase */
423 timeout = UDEVD_INIT_EVENT_TIMEOUT;
424 dbg("initialization phase, limit timeout to %i seconds", UDEVD_INIT_EVENT_TIMEOUT);
427 /* move event with expired timeout to the exec list */
428 msg_age = info.uptime - loop_msg->queue_time;
429 dbg("seq %llu is %li seconds old", loop_msg->seqnum, msg_age);
430 if (msg_age >= timeout) {
431 msg_move_exec(loop_msg);
440 /* set timeout for remaining queued events */
441 if (!list_empty(&msg_list)) {
442 struct itimerval itv = {{0, 0}, {timeout - msg_age, 0}};
443 dbg("next event expires in %li seconds", timeout - msg_age);
444 setitimer(ITIMER_REAL, &itv, NULL);
448 static struct uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
452 struct uevent_msg *msg;
456 msg = malloc(sizeof(struct uevent_msg) + buf_size);
459 memset(msg, 0x00, sizeof(struct uevent_msg) + buf_size);
461 /* copy environment buffer and reconstruct envp */
462 memcpy(msg->envbuf, buf, buf_size);
464 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
468 key = &msg->envbuf[bufpos];
469 keylen = strlen(key);
471 bufpos += keylen + 1;
472 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
474 /* remember some keys for further processing */
475 if (strncmp(key, "ACTION=", 7) == 0)
476 msg->action = &key[7];
477 else if (strncmp(key, "DEVPATH=", 8) == 0)
478 msg->devpath = &key[8];
479 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
480 msg->subsystem = &key[10];
481 else if (strncmp(key, "SEQNUM=", 7) == 0)
482 msg->seqnum = strtoull(&key[7], NULL, 10);
483 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
484 msg->physdevpath = &key[12];
485 else if (strncmp(key, "MAJOR=", 6) == 0)
486 major = strtoull(&key[6], NULL, 10);
487 else if (strncmp(key, "MINOR=", 6) == 0)
488 minor = strtoull(&key[6], NULL, 10);
489 else if (strncmp(key, "TIMEOUT=", 8) == 0)
490 msg->timeout = strtoull(&key[8], NULL, 10);
492 msg->devt = makedev(major, minor);
493 msg->envp[i++] = "UDEVD_EVENT=1";
499 /* receive the udevd message from userspace */
500 static struct uevent_msg *get_udevd_msg(void)
502 static struct udevd_msg usend_msg;
503 struct uevent_msg *msg;
506 struct cmsghdr *cmsg;
509 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
513 memset(&usend_msg, 0x00, sizeof(struct udevd_msg));
514 iov.iov_base = &usend_msg;
515 iov.iov_len = sizeof(struct udevd_msg);
517 memset(&smsg, 0x00, sizeof(struct msghdr));
520 smsg.msg_control = cred_msg;
521 smsg.msg_controllen = sizeof(cred_msg);
523 size = recvmsg(udevd_sock, &smsg, 0);
526 dbg("unable to receive udevd message");
529 cmsg = CMSG_FIRSTHDR(&smsg);
530 cred = (struct ucred *) CMSG_DATA(cmsg);
532 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
533 info("no sender credentials received, message ignored");
537 if (cred->uid != 0) {
538 info("sender uid=%i, message ignored", cred->uid);
542 if (strncmp(usend_msg.magic, UDEV_MAGIC, sizeof(UDEV_MAGIC)) != 0 ) {
543 info("message magic '%s' doesn't match, ignore it", usend_msg.magic);
547 switch (usend_msg.type) {
548 case UDEVD_UEVENT_UDEVSEND:
549 case UDEVD_UEVENT_INITSEND:
550 dbg("udevd event message received");
551 envbuf_size = size - offsetof(struct udevd_msg, envbuf);
552 dbg("envbuf_size=%i", envbuf_size);
553 msg = get_msg_from_envbuf(usend_msg.envbuf, envbuf_size);
556 msg->type = usend_msg.type;
558 case UDEVD_STOP_EXEC_QUEUE:
559 info("udevd message (STOP_EXEC_QUEUE) received");
562 case UDEVD_START_EXEC_QUEUE:
563 info("udevd message (START_EXEC_QUEUE) received");
565 exec_queue_manager();
567 case UDEVD_SET_LOG_LEVEL:
568 intval = (int *) usend_msg.envbuf;
569 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
570 udev_log_priority = *intval;
571 sprintf(log, "UDEV_LOG=%i", udev_log_priority);
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 */
651 /* set flag, then write to pipe if needed */
652 sigchilds_waiting = 1;
656 /* if pipe is empty, write to pipe to force select to return,
657 * which will wakeup our mainloop
660 rc = write(pipefds[1], &signum, sizeof(signum));
666 static void udev_done(int pid)
668 /* find msg associated with pid and delete it */
669 struct uevent_msg *msg;
672 list_for_each_entry(msg, &running_list, node) {
673 if (msg->pid == pid) {
675 info("seq %llu exit, %ld seconds old", msg->seqnum, info.uptime - msg->queue_time);
676 msg_queue_delete(msg);
678 /* we want to run the exec queue manager since there may
679 * be events waiting with the devpath of the one that
688 static void reap_sigchilds(void)
693 pid = waitpid(-1, NULL, WNOHANG);
700 static int init_udevd_socket(void)
702 struct sockaddr_un saddr;
703 const int buffersize = 1024 * 1024;
705 const int feature_on = 1;
708 memset(&saddr, 0x00, sizeof(saddr));
709 saddr.sun_family = AF_LOCAL;
710 /* use abstract namespace for socket path */
711 strcpy(&saddr.sun_path[1], UDEVD_SOCK_PATH);
712 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
714 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
715 if (udevd_sock == -1) {
716 err("error getting socket, %s", strerror(errno));
720 /* set receive buffersize */
721 setsockopt(udevd_sock, SOL_SOCKET, SO_RCVBUF, &buffersize, sizeof(buffersize));
723 /* the bind takes care of ensuring only one copy running */
724 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
726 err("bind failed, %s", strerror(errno));
731 /* enable receiving of the sender credentials */
732 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
737 static int init_uevent_netlink_sock(void)
739 struct sockaddr_nl snl;
740 const int buffersize = 1024 * 1024;
743 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
744 snl.nl_family = AF_NETLINK;
745 snl.nl_pid = getpid();
746 snl.nl_groups = 0xffffffff;
748 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
749 if (uevent_netlink_sock == -1) {
750 dbg("error getting socket, %s", strerror(errno));
754 /* set receive buffersize */
755 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUF, &buffersize, sizeof(buffersize));
757 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl,
758 sizeof(struct sockaddr_nl));
760 dbg("bind failed, %s", strerror(errno));
761 close(uevent_netlink_sock);
762 uevent_netlink_sock = -1;
769 int main(int argc, char *argv[], char *envp[])
773 struct sigaction act;
776 int uevent_netlink_active = 0;
780 /* set std fd's to /dev/null, if the kernel forks us, we don't have them at all */
781 devnull = open("/dev/null", O_RDWR);
783 if (devnull != STDIN_FILENO)
784 dup2(devnull, STDIN_FILENO);
785 if (devnull != STDOUT_FILENO)
786 dup2(devnull, STDOUT_FILENO);
787 if (devnull != STDERR_FILENO)
788 dup2(devnull, STDERR_FILENO);
789 if (devnull > STDERR_FILENO)
793 logging_init("udevd");
795 err("fatal, could not open /dev/null");
798 dbg("version %s", UDEV_VERSION);
801 err("need to be root, exit");
805 for (i = 1 ; i < argc; i++) {
807 if (strcmp(arg, "--daemon") == 0 || strcmp(arg, "-d") == 0) {
808 info("will daemonize");
811 if (strcmp(arg, "--stop-exec-queue") == 0) {
812 info("will not execute events until START_EXEC_QUEUE is received");
823 dbg("damonized fork running");
826 err("fork of daemon failed");
834 /* become session leader */
836 dbg("our session is %d", sid);
839 umask(umask(077) | 022);
841 /* set a reasonable scheduling priority for the daemon */
842 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
844 /* setup signal handler pipe */
845 retval = pipe(pipefds);
847 err("error getting pipes: %s", strerror(errno));
850 retval = fcntl(pipefds[0], F_SETFL, O_NONBLOCK);
852 err("error fcntl on read pipe: %s", strerror(errno));
855 retval = fcntl(pipefds[0], F_SETFD, FD_CLOEXEC);
857 err("error fcntl on read pipe: %s", strerror(errno));
858 retval = fcntl(pipefds[1], F_SETFL, O_NONBLOCK);
860 err("error fcntl on write pipe: %s", strerror(errno));
863 retval = fcntl(pipefds[1], F_SETFD, FD_CLOEXEC);
865 err("error fcntl on write pipe: %s", strerror(errno));
867 /* set signal handlers */
868 memset(&act, 0x00, sizeof(struct sigaction));
869 act.sa_handler = (void (*)(int)) sig_handler;
870 sigemptyset(&act.sa_mask);
871 act.sa_flags = SA_RESTART;
872 sigaction(SIGINT, &act, NULL);
873 sigaction(SIGTERM, &act, NULL);
874 sigaction(SIGALRM, &act, NULL);
875 sigaction(SIGCHLD, &act, NULL);
876 sigaction(SIGHUP, &act, NULL);
878 if (init_udevd_socket() < 0) {
879 if (errno == EADDRINUSE)
880 dbg("another udevd running, exit");
882 dbg("error initialising udevd socket: %s", strerror(errno));
887 if (init_uevent_netlink_sock() < 0)
888 info("uevent socket not available");
890 /* override of forked udev binary, used for testing */
891 udev_bin = getenv("UDEV_BIN");
892 if (udev_bin != NULL)
893 info("udev binary is set to '%s'", udev_bin);
897 /* init of expected_seqnum value */
898 value = getenv("UDEVD_EXPECTED_SEQNUM");
900 expected_seqnum = strtoull(value, NULL, 10);
901 info("initialize expected_seqnum to %llu", expected_seqnum);
904 /* timeout to wait for missing events */
905 value = getenv("UDEVD_EVENT_TIMEOUT");
907 event_timeout = strtoul(value, NULL, 10);
909 event_timeout = UDEVD_EVENT_TIMEOUT;
910 info("initialize event_timeout to %u", event_timeout);
912 /* maximum limit of forked childs */
913 value = getenv("UDEVD_MAX_CHILDS");
915 max_childs = strtoul(value, NULL, 10);
917 max_childs = UDEVD_MAX_CHILDS;
918 info("initialize max_childs to %u", max_childs);
920 /* start to throttle forking if maximum number of _running_ childs is reached */
921 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
923 max_childs_running = strtoull(value, NULL, 10);
925 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
926 info("initialize max_childs_running to %u", max_childs_running);
928 /* export log_priority , as called programs may want to follow that setting */
929 sprintf(log, "UDEV_LOG=%i", udev_log_priority);
933 struct uevent_msg *msg;
937 FD_SET(pipefds[0], &readfds);
938 FD_SET(udevd_sock, &readfds);
939 if (uevent_netlink_sock > 0)
940 FD_SET(uevent_netlink_sock, &readfds);
942 fdcount = select(UDEV_MAX(udevd_sock, uevent_netlink_sock)+1, &readfds, NULL, NULL, NULL);
945 dbg("error in select: %s", strerror(errno));
949 /* get user socket message */
950 if (FD_ISSET(udevd_sock, &readfds)) {
951 msg = get_udevd_msg();
953 /* discard kernel messages if netlink is active */
954 if (uevent_netlink_active && msg->type == UDEVD_UEVENT_UDEVSEND && msg->seqnum != 0) {
955 dbg("skip uevent_helper message, netlink is active");
959 msg_queue_insert(msg);
963 /* get kernel netlink message */
964 if ((uevent_netlink_sock > 0) && FD_ISSET(uevent_netlink_sock, &readfds)) {
965 msg = get_netlink_msg();
967 msg_queue_insert(msg);
968 /* disable udevsend with first netlink message */
969 if (!uevent_netlink_active) {
970 info("uevent_nl message received, disable udevsend messages");
971 uevent_netlink_active = 1;
976 /* received a signal, clear our notification pipe */
977 if (FD_ISSET(pipefds[0], &readfds)) {
982 rlen = read(pipefds[0], &sig, sizeof(sig));
989 /* forked child have returned */
990 if (sigchilds_waiting) {
991 sigchilds_waiting = 0;
1001 /* clean up running_list before calling exec_queue_manager() */
1002 if (sigchilds_waiting) {
1003 sigchilds_waiting = 0;
1009 exec_queue_manager();
1021 if (uevent_netlink_sock > 0)
1022 close(uevent_netlink_sock);