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 signal_pipe[2] = {-1, -1};
59 static volatile int sigchilds_waiting;
60 static volatile int run_msg_q;
61 static volatile int udev_exit;
62 static int init_phase = 1;
63 static int run_exec_q;
64 static int stop_exec_q;
65 static char *udev_bin;
66 static int event_timeout;
67 static int max_childs;
68 static int max_childs_running;
69 static unsigned long long expected_seqnum;
72 static LIST_HEAD(msg_list);
73 static LIST_HEAD(exec_list);
74 static LIST_HEAD(running_list);
78 void log_message (int priority, const char *format, ...)
82 if (priority > udev_log_priority)
85 va_start(args, format);
86 vsyslog(priority, format, args);
91 static void msg_dump_queue(void)
94 struct uevent_msg *msg;
96 list_for_each_entry(msg, &msg_list, node)
97 dbg("sequence %llu in queue", msg->seqnum);
101 static void msg_queue_delete(struct uevent_msg *msg)
103 list_del(&msg->node);
107 /* orders the message in the queue by sequence number */
108 static void msg_queue_insert(struct uevent_msg *msg)
110 struct uevent_msg *loop_msg;
113 if (msg->seqnum == 0) {
114 dbg("no SEQNUM, move straight to the exec queue");
115 list_add_tail(&msg->node, &exec_list);
120 /* store timestamp of queuing */
122 msg->queue_time = info.uptime;
124 /* with the first event we provide a phase of shorter timeout */
126 static long init_time;
129 init_time = info.uptime;
130 if (info.uptime - init_time >= UDEVD_INIT_TIME)
134 /* sort message by sequence number into list */
135 list_for_each_entry_reverse(loop_msg, &msg_list, node) {
136 if (loop_msg->seqnum < msg->seqnum)
139 if (loop_msg->seqnum == msg->seqnum) {
140 dbg("ignoring duplicate message seq %llu", msg->seqnum);
145 list_add(&msg->node, &loop_msg->node);
146 info("seq %llu queued, '%s' '%s'", msg->seqnum, msg->action, msg->devpath);
148 /* run msg queue manager */
154 /* forks event and removes event from run queue when finished */
155 static void udev_event_run(struct uevent_msg *msg)
157 char *const argv[] = { "udev", msg->subsystem, NULL };
165 if (uevent_netlink_sock != -1)
166 close(uevent_netlink_sock);
169 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
170 execve(udev_bin, argv, msg->envp);
171 err("exec of child failed");
174 err("fork of child failed");
175 msg_queue_delete(msg);
178 /* get SIGCHLD in main loop */
180 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
181 msg->seqnum, pid, msg->action, msg->subsystem, info.uptime - msg->queue_time);
186 static int running_processes(void)
189 static char buf[4096];
194 f = open("/proc/stat", O_RDONLY);
198 len = read(f, buf, sizeof(buf)-1);
206 pos = strstr(buf, "procs_running ");
210 if (sscanf(pos, "procs_running %u", &running) != 1)
216 /* return the number of process es in our session, count only until limit */
217 static int running_processes_in_session(pid_t session, int limit)
223 dir = opendir("/proc");
227 /* read process info from /proc */
228 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
234 pid_t ppid, pgrp, sess;
237 if (!isdigit(dent->d_name[0]))
240 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
241 procdir[sizeof(procdir)-1] = '\0';
243 f = open(procdir, O_RDONLY);
247 len = read(f, line, sizeof(line)-1);
255 /* skip ugly program name */
256 pos = strrchr(line, ')') + 2;
260 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
263 /* count only processes in our session */
267 /* count only running, no sleeping processes */
272 if (limit > 0 && running >= limit)
280 static int compare_devpath(const char *running, const char *waiting)
284 for (i = 0; i < PATH_SIZE; i++) {
285 /* identical device event found */
286 if (running[i] == '\0' && waiting[i] == '\0')
289 /* parent device event found */
290 if (running[i] == '\0' && waiting[i] == '/')
293 /* child device event found */
294 if (running[i] == '/' && waiting[i] == '\0')
297 /* no matching event */
298 if (running[i] != waiting[i])
305 /* returns still running task for the same device, its parent or its physical device */
306 static int running_with_devpath(struct uevent_msg *msg, int limit)
308 struct uevent_msg *loop_msg;
309 int childs_count = 0;
311 if (msg->devpath == NULL)
314 /* skip any events with a timeout set */
315 if (msg->timeout != 0)
318 list_for_each_entry(loop_msg, &running_list, node) {
319 if (limit && childs_count++ > limit) {
320 dbg("%llu, maximum number (%i) of child reached", msg->seqnum, childs_count);
323 if (loop_msg->devpath == NULL)
326 /* return running parent/child device event */
327 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
328 dbg("%llu, child device event still running %llu (%s)",
329 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
333 /* return running physical device event */
334 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
335 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
336 dbg("%llu, physical device event still running %llu (%s)",
337 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
345 /* exec queue management routine executes the events and serializes events in the same sequence */
346 static void exec_queue_manager(void)
348 struct uevent_msg *loop_msg;
349 struct uevent_msg *tmp_msg;
352 if (list_empty(&exec_list))
355 running = running_processes();
356 dbg("%d processes runnning on system", running);
358 running = max_childs_running;
360 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
361 /* check running processes in our session and possibly throttle */
362 if (running >= max_childs_running) {
363 running = running_processes_in_session(sid, max_childs_running+10);
364 dbg("at least %d processes running in session", running);
365 if (running >= max_childs_running) {
366 dbg("delay seq %llu, cause too many processes already running",
372 if (running_with_devpath(loop_msg, max_childs) == 0) {
373 /* move event to run list */
374 list_move_tail(&loop_msg->node, &running_list);
375 udev_event_run(loop_msg);
377 dbg("moved seq %llu to running list", loop_msg->seqnum);
379 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
383 static void msg_move_exec(struct uevent_msg *msg)
385 list_move_tail(&msg->node, &exec_list);
387 expected_seqnum = msg->seqnum+1;
388 dbg("moved seq %llu to exec, next expected is %llu",
389 msg->seqnum, expected_seqnum);
392 /* msg queue management routine handles the timeouts and dispatches the events */
393 static void msg_queue_manager(void)
395 struct uevent_msg *loop_msg;
396 struct uevent_msg *tmp_msg;
399 int timeout = event_timeout;
401 dbg("msg queue manager, next expected is %llu", expected_seqnum);
404 list_for_each_entry_safe(loop_msg, tmp_msg, &msg_list, node) {
405 /* move event with expected sequence to the exec list */
406 if (loop_msg->seqnum == expected_seqnum) {
407 msg_move_exec(loop_msg);
411 /* limit timeout during initialization phase */
413 timeout = UDEVD_INIT_EVENT_TIMEOUT;
414 dbg("initialization phase, limit timeout to %i seconds", UDEVD_INIT_EVENT_TIMEOUT);
417 /* move event with expired timeout to the exec list */
418 msg_age = info.uptime - loop_msg->queue_time;
419 dbg("seq %llu is %li seconds old", loop_msg->seqnum, msg_age);
420 if (msg_age >= timeout) {
421 msg_move_exec(loop_msg);
430 /* set timeout for remaining queued events */
431 if (!list_empty(&msg_list)) {
432 struct itimerval itv = {{0, 0}, {timeout - msg_age, 0}};
433 info("next event expires in %li seconds", timeout - msg_age);
434 setitimer(ITIMER_REAL, &itv, NULL);
438 static struct uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
442 struct uevent_msg *msg;
446 msg = malloc(sizeof(struct uevent_msg) + buf_size);
449 memset(msg, 0x00, sizeof(struct uevent_msg) + buf_size);
451 /* copy environment buffer and reconstruct envp */
452 memcpy(msg->envbuf, buf, buf_size);
454 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
458 key = &msg->envbuf[bufpos];
459 keylen = strlen(key);
461 bufpos += keylen + 1;
462 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
464 /* remember some keys for further processing */
465 if (strncmp(key, "ACTION=", 7) == 0)
466 msg->action = &key[7];
467 else if (strncmp(key, "DEVPATH=", 8) == 0)
468 msg->devpath = &key[8];
469 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
470 msg->subsystem = &key[10];
471 else if (strncmp(key, "SEQNUM=", 7) == 0)
472 msg->seqnum = strtoull(&key[7], NULL, 10);
473 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
474 msg->physdevpath = &key[12];
475 else if (strncmp(key, "MAJOR=", 6) == 0)
476 major = strtoull(&key[6], NULL, 10);
477 else if (strncmp(key, "MINOR=", 6) == 0)
478 minor = strtoull(&key[6], NULL, 10);
479 else if (strncmp(key, "TIMEOUT=", 8) == 0)
480 msg->timeout = strtoull(&key[8], NULL, 10);
482 msg->devt = makedev(major, minor);
483 msg->envp[i++] = "UDEVD_EVENT=1";
489 /* receive the udevd message from userspace */
490 static struct uevent_msg *get_udevd_msg(void)
492 static struct udevd_msg usend_msg;
493 struct uevent_msg *msg;
496 struct cmsghdr *cmsg;
499 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
503 memset(&usend_msg, 0x00, sizeof(struct udevd_msg));
504 iov.iov_base = &usend_msg;
505 iov.iov_len = sizeof(struct udevd_msg);
507 memset(&smsg, 0x00, sizeof(struct msghdr));
510 smsg.msg_control = cred_msg;
511 smsg.msg_controllen = sizeof(cred_msg);
513 size = recvmsg(udevd_sock, &smsg, 0);
516 err("unable to receive udevd message");
519 cmsg = CMSG_FIRSTHDR(&smsg);
520 cred = (struct ucred *) CMSG_DATA(cmsg);
522 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
523 err("no sender credentials received, message ignored");
527 if (cred->uid != 0) {
528 err("sender uid=%i, message ignored", cred->uid);
532 if (strncmp(usend_msg.magic, UDEV_MAGIC, sizeof(UDEV_MAGIC)) != 0 ) {
533 err("message magic '%s' doesn't match, ignore it", usend_msg.magic);
537 switch (usend_msg.type) {
538 case UDEVD_UEVENT_UDEVSEND:
539 case UDEVD_UEVENT_INITSEND:
540 info("udevd event message received");
541 envbuf_size = size - offsetof(struct udevd_msg, envbuf);
542 dbg("envbuf_size=%i", envbuf_size);
543 msg = get_msg_from_envbuf(usend_msg.envbuf, envbuf_size);
546 msg->type = usend_msg.type;
548 case UDEVD_STOP_EXEC_QUEUE:
549 info("udevd message (STOP_EXEC_QUEUE) received");
552 case UDEVD_START_EXEC_QUEUE:
553 info("udevd message (START_EXEC_QUEUE) received");
555 exec_queue_manager();
557 case UDEVD_SET_LOG_LEVEL:
558 intval = (int *) usend_msg.envbuf;
559 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
560 udev_log_priority = *intval;
561 sprintf(log, "UDEV_LOG=%i", udev_log_priority);
564 case UDEVD_SET_MAX_CHILDS:
565 intval = (int *) usend_msg.envbuf;
566 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
567 max_childs = *intval;
570 dbg("unknown message type");
575 /* receive the kernel user event message and do some sanity checks */
576 static struct uevent_msg *get_netlink_msg(void)
578 struct uevent_msg *msg;
581 static char buffer[UEVENT_BUFFER_SIZE + 512];
584 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
587 err("unable to receive udevd message");
591 if ((size_t)size > sizeof(buffer)-1)
592 size = sizeof(buffer)-1;
594 dbg("uevent_size=%zi", size);
596 /* start of event payload */
597 bufpos = strlen(buffer)+1;
598 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
601 msg->type = UDEVD_UEVENT_NETLINK;
603 /* validate message */
604 pos = strchr(buffer, '@');
606 err("invalid uevent '%s'", buffer);
612 if (msg->action == NULL) {
613 err("no ACTION in payload found, skip event '%s'", buffer);
618 if (strcmp(msg->action, buffer) != 0) {
619 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
627 static void asmlinkage sig_handler(int signum)
635 /* set flag, then write to pipe if needed */
639 /* set flag, then write to pipe if needed */
640 sigchilds_waiting = 1;
644 /* write to pipe, which will wakeup select() in our mainloop */
645 write(signal_pipe[WRITE_END], "", 1);
648 static void udev_done(int pid)
650 /* find msg associated with pid and delete it */
651 struct uevent_msg *msg;
654 list_for_each_entry(msg, &running_list, node) {
655 if (msg->pid == pid) {
658 info("seq %llu, pid [%d] exit, %ld seconds old", msg->seqnum, msg->pid, info.uptime - msg->queue_time);
660 info("seq 0, pid [%d] exit", msg->pid);
661 msg_queue_delete(msg);
663 /* we want to run the exec queue manager since there may
664 * be events waiting with the devpath of the one that
673 static void reap_sigchilds(void)
678 pid = waitpid(-1, NULL, WNOHANG);
685 static int init_udevd_socket(void)
687 struct sockaddr_un saddr;
688 const int buffersize = 1024 * 1024;
690 const int feature_on = 1;
693 memset(&saddr, 0x00, sizeof(saddr));
694 saddr.sun_family = AF_LOCAL;
695 /* use abstract namespace for socket path */
696 strcpy(&saddr.sun_path[1], UDEVD_SOCK_PATH);
697 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
699 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
700 if (udevd_sock == -1) {
701 err("error getting socket, %s", strerror(errno));
705 /* set receive buffersize */
706 setsockopt(udevd_sock, SOL_SOCKET, SO_RCVBUF, &buffersize, sizeof(buffersize));
708 /* the bind takes care of ensuring only one copy running */
709 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
711 err("bind failed, %s", strerror(errno));
716 /* enable receiving of the sender credentials */
717 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
722 static int init_uevent_netlink_sock(void)
724 struct sockaddr_nl snl;
725 const int buffersize = 1024 * 1024;
728 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
729 snl.nl_family = AF_NETLINK;
730 snl.nl_pid = getpid();
731 snl.nl_groups = 0xffffffff;
733 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
734 if (uevent_netlink_sock == -1) {
735 err("error getting socket, %s", strerror(errno));
739 /* set receive buffersize */
740 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUF, &buffersize, sizeof(buffersize));
742 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl,
743 sizeof(struct sockaddr_nl));
745 err("bind failed, %s", strerror(errno));
746 close(uevent_netlink_sock);
747 uevent_netlink_sock = -1;
754 int main(int argc, char *argv[], char *envp[])
758 struct sigaction act;
761 int uevent_netlink_active = 0;
765 /* set std fd's to /dev/null, if the kernel forks us, we don't have them at all */
766 devnull = open("/dev/null", O_RDWR);
768 if (devnull != STDIN_FILENO)
769 dup2(devnull, STDIN_FILENO);
770 if (devnull != STDOUT_FILENO)
771 dup2(devnull, STDOUT_FILENO);
772 if (devnull != STDERR_FILENO)
773 dup2(devnull, STDERR_FILENO);
774 if (devnull > STDERR_FILENO)
778 logging_init("udevd");
780 err("fatal, could not open /dev/null");
783 dbg("version %s", UDEV_VERSION);
786 err("need to be root, exit");
790 for (i = 1 ; i < argc; i++) {
792 if (strcmp(arg, "--daemon") == 0 || strcmp(arg, "-d") == 0) {
793 info("will daemonize");
796 if (strcmp(arg, "--stop-exec-queue") == 0) {
797 info("will not execute events until START_EXEC_QUEUE is received");
808 dbg("damonized fork running");
811 err("fork of daemon failed");
819 /* become session leader */
821 dbg("our session is %d", sid);
824 umask(umask(077) | 022);
826 /* set a reasonable scheduling priority for the daemon */
827 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
829 /* setup signal handler pipe */
830 retval = pipe(signal_pipe);
832 err("error getting pipes: %s", strerror(errno));
835 retval = fcntl(signal_pipe[READ_END], F_SETFL, O_NONBLOCK);
837 err("error fcntl on read pipe: %s", strerror(errno));
840 retval = fcntl(signal_pipe[READ_END], F_SETFD, FD_CLOEXEC);
842 err("error fcntl on read pipe: %s", strerror(errno));
843 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, O_NONBLOCK);
845 err("error fcntl on write pipe: %s", strerror(errno));
848 retval = fcntl(signal_pipe[WRITE_END], F_SETFD, FD_CLOEXEC);
850 err("error fcntl on write pipe: %s", strerror(errno));
852 /* set signal handlers */
853 memset(&act, 0x00, sizeof(struct sigaction));
854 act.sa_handler = (void (*)(int)) sig_handler;
855 sigemptyset(&act.sa_mask);
856 act.sa_flags = SA_RESTART;
857 sigaction(SIGINT, &act, NULL);
858 sigaction(SIGTERM, &act, NULL);
859 sigaction(SIGALRM, &act, NULL);
860 sigaction(SIGCHLD, &act, NULL);
861 sigaction(SIGHUP, &act, NULL);
863 if (init_udevd_socket() < 0) {
864 if (errno == EADDRINUSE)
865 dbg("another udevd running, exit");
867 dbg("error initialising udevd socket: %s", strerror(errno));
872 if (init_uevent_netlink_sock() < 0)
873 info("uevent socket not available");
875 /* override of forked udev binary, used for testing */
876 udev_bin = getenv("UDEV_BIN");
877 if (udev_bin != NULL)
878 info("udev binary is set to '%s'", udev_bin);
882 /* init of expected_seqnum value */
883 value = getenv("UDEVD_EXPECTED_SEQNUM");
885 expected_seqnum = strtoull(value, NULL, 10);
886 info("initialize expected_seqnum to %llu", expected_seqnum);
889 /* timeout to wait for missing events */
890 value = getenv("UDEVD_EVENT_TIMEOUT");
892 event_timeout = strtoul(value, NULL, 10);
894 event_timeout = UDEVD_EVENT_TIMEOUT;
895 info("initialize event_timeout to %u", event_timeout);
897 /* maximum limit of forked childs */
898 value = getenv("UDEVD_MAX_CHILDS");
900 max_childs = strtoul(value, NULL, 10);
902 max_childs = UDEVD_MAX_CHILDS;
903 info("initialize max_childs to %u", max_childs);
905 /* start to throttle forking if maximum number of _running_ childs is reached */
906 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
908 max_childs_running = strtoull(value, NULL, 10);
910 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
911 info("initialize max_childs_running to %u", max_childs_running);
913 /* export log_priority , as called programs may want to follow that setting */
914 sprintf(log, "UDEV_LOG=%i", udev_log_priority);
918 struct uevent_msg *msg;
922 FD_SET(signal_pipe[READ_END], &readfds);
923 FD_SET(udevd_sock, &readfds);
924 if (uevent_netlink_sock > 0)
925 FD_SET(uevent_netlink_sock, &readfds);
927 fdcount = select(UDEV_MAX(udevd_sock, uevent_netlink_sock)+1, &readfds, NULL, NULL, NULL);
930 dbg("error in select: %s", strerror(errno));
934 /* get user socket message */
935 if (FD_ISSET(udevd_sock, &readfds)) {
936 msg = get_udevd_msg();
938 /* discard kernel messages if netlink is active */
939 if (uevent_netlink_active && msg->type == UDEVD_UEVENT_UDEVSEND && msg->seqnum != 0) {
940 info("skip uevent_helper message with SEQNUM, netlink is active");
943 msg_queue_insert(msg);
947 /* get kernel netlink message */
948 if ((uevent_netlink_sock > 0) && FD_ISSET(uevent_netlink_sock, &readfds)) {
949 msg = get_netlink_msg();
951 msg_queue_insert(msg);
952 /* disable udevsend with first netlink message */
953 if (!uevent_netlink_active) {
954 info("uevent_nl message received, disable udevsend messages");
955 uevent_netlink_active = 1;
960 /* received a signal, clear our notification pipe */
961 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
964 read(signal_pipe[READ_END], &buf, sizeof(buf));
967 /* forked child have returned */
968 if (sigchilds_waiting) {
969 sigchilds_waiting = 0;
979 /* clean up running_list before calling exec_queue_manager() */
980 if (sigchilds_waiting) {
981 sigchilds_waiting = 0;
987 exec_queue_manager();
992 if (signal_pipe[READ_END] > 0)
993 close(signal_pipe[READ_END]);
994 if (signal_pipe[WRITE_END] > 0)
995 close(signal_pipe[WRITE_END]);
999 if (uevent_netlink_sock > 0)
1000 close(uevent_netlink_sock);