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 /* don't delay messages with timeout set */
136 info("seq %llu with timeout %u seconds will be execute without queuing, '%s' '%s'",
137 msg->seqnum, msg->timeout, msg->action, msg->devpath);
138 list_add(&msg->node, &exec_list);
143 /* sort message by sequence number into list */
144 list_for_each_entry_reverse(loop_msg, &msg_list, node) {
145 if (loop_msg->seqnum < msg->seqnum)
148 if (loop_msg->seqnum == msg->seqnum) {
149 dbg("ignoring duplicate message seq %llu", msg->seqnum);
154 list_add(&msg->node, &loop_msg->node);
155 info("seq %llu queued, '%s' '%s'", msg->seqnum, msg->action, msg->devpath);
157 /* run msg queue manager */
163 /* forks event and removes event from run queue when finished */
164 static void udev_event_run(struct uevent_msg *msg)
166 char *const argv[] = { "udev", msg->subsystem, NULL };
174 if (uevent_netlink_sock != -1)
175 close(uevent_netlink_sock);
178 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
179 execve(udev_bin, argv, msg->envp);
180 err("exec of child failed");
183 err("fork of child failed");
184 msg_queue_delete(msg);
187 /* get SIGCHLD in main loop */
189 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
190 msg->seqnum, pid, msg->action, msg->subsystem, info.uptime - msg->queue_time);
195 static int running_processes(void)
198 static char buf[4096];
203 f = open("/proc/stat", O_RDONLY);
207 len = read(f, buf, sizeof(buf));
215 pos = strstr(buf, "procs_running ");
219 if (sscanf(pos, "procs_running %u", &running) != 1)
225 /* return the number of process es in our session, count only until limit */
226 static int running_processes_in_session(pid_t session, int limit)
232 dir = opendir("/proc");
236 /* read process info from /proc */
237 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
243 pid_t ppid, pgrp, sess;
246 if (!isdigit(dent->d_name[0]))
249 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
250 procdir[sizeof(procdir)-1] = '\0';
252 f = open(procdir, O_RDONLY);
256 len = read(f, line, sizeof(line));
264 /* skip ugly program name */
265 pos = strrchr(line, ')') + 2;
269 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
272 /* count only processes in our session */
276 /* count only running, no sleeping processes */
281 if (limit > 0 && running >= limit)
289 static int compare_devpath(const char *running, const char *waiting)
293 for (i = 0; i < PATH_SIZE; i++) {
294 /* identical device event found */
295 if (running[i] == '\0' && waiting[i] == '\0')
298 /* parent device event found */
299 if (running[i] == '\0' && waiting[i] == '/')
302 /* child device event found */
303 if (running[i] == '/' && waiting[i] == '\0')
306 /* no matching event */
307 if (running[i] != waiting[i])
314 /* returns still running task for the same device, its parent or its physical device */
315 static int running_with_devpath(struct uevent_msg *msg, int limit)
317 struct uevent_msg *loop_msg;
318 int childs_count = 0;
320 if (msg->devpath == NULL)
323 /* skip any events with a timeout set */
324 if (msg->timeout != 0)
327 list_for_each_entry(loop_msg, &running_list, node) {
328 if (limit && childs_count++ > limit) {
329 dbg("%llu, maximum number (%i) of child reached", msg->seqnum, childs_count);
332 if (loop_msg->devpath == NULL)
335 /* return running parent/child device event */
336 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
337 dbg("%llu, child device event still running %llu (%s)",
338 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
342 /* return running physical device event */
343 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
344 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
345 dbg("%llu, physical device event still running %llu (%s)",
346 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
354 /* exec queue management routine executes the events and serializes events in the same sequence */
355 static void exec_queue_manager(void)
357 struct uevent_msg *loop_msg;
358 struct uevent_msg *tmp_msg;
361 if (list_empty(&exec_list))
364 running = running_processes();
365 dbg("%d processes runnning on system", running);
367 running = max_childs_running;
369 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
370 /* check running processes in our session and possibly throttle */
371 if (running >= max_childs_running) {
372 running = running_processes_in_session(sid, max_childs_running+10);
373 dbg("at least %d processes running in session", running);
374 if (running >= max_childs_running) {
375 dbg("delay seq %llu, cause too many processes already running",
381 if (running_with_devpath(loop_msg, max_childs) == 0) {
382 /* move event to run list */
383 list_move_tail(&loop_msg->node, &running_list);
384 udev_event_run(loop_msg);
386 dbg("moved seq %llu to running list", loop_msg->seqnum);
388 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
392 static void msg_move_exec(struct uevent_msg *msg)
394 list_move_tail(&msg->node, &exec_list);
396 expected_seqnum = msg->seqnum+1;
397 dbg("moved seq %llu to exec, next expected is %llu",
398 msg->seqnum, expected_seqnum);
401 /* msg queue management routine handles the timeouts and dispatches the events */
402 static void msg_queue_manager(void)
404 struct uevent_msg *loop_msg;
405 struct uevent_msg *tmp_msg;
408 int timeout = event_timeout;
410 dbg("msg queue manager, next expected is %llu", expected_seqnum);
413 list_for_each_entry_safe(loop_msg, tmp_msg, &msg_list, node) {
414 /* move event with expected sequence to the exec list */
415 if (loop_msg->seqnum == expected_seqnum) {
416 msg_move_exec(loop_msg);
420 /* limit timeout during initialization phase */
422 timeout = UDEVD_INIT_EVENT_TIMEOUT;
423 dbg("initialization phase, limit timeout to %i seconds", UDEVD_INIT_EVENT_TIMEOUT);
426 /* move event with expired timeout to the exec list */
427 msg_age = info.uptime - loop_msg->queue_time;
428 dbg("seq %llu is %li seconds old", loop_msg->seqnum, msg_age);
429 if (msg_age >= timeout) {
430 msg_move_exec(loop_msg);
439 /* set timeout for remaining queued events */
440 if (!list_empty(&msg_list)) {
441 struct itimerval itv = {{0, 0}, {timeout - msg_age, 0}};
442 info("next event expires in %li seconds", timeout - msg_age);
443 setitimer(ITIMER_REAL, &itv, NULL);
447 static struct uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
451 struct uevent_msg *msg;
455 msg = malloc(sizeof(struct uevent_msg) + buf_size);
458 memset(msg, 0x00, sizeof(struct uevent_msg) + buf_size);
460 /* copy environment buffer and reconstruct envp */
461 memcpy(msg->envbuf, buf, buf_size);
463 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
467 key = &msg->envbuf[bufpos];
468 keylen = strlen(key);
470 bufpos += keylen + 1;
471 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
473 /* remember some keys for further processing */
474 if (strncmp(key, "ACTION=", 7) == 0)
475 msg->action = &key[7];
476 else if (strncmp(key, "DEVPATH=", 8) == 0)
477 msg->devpath = &key[8];
478 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
479 msg->subsystem = &key[10];
480 else if (strncmp(key, "SEQNUM=", 7) == 0)
481 msg->seqnum = strtoull(&key[7], NULL, 10);
482 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
483 msg->physdevpath = &key[12];
484 else if (strncmp(key, "MAJOR=", 6) == 0)
485 major = strtoull(&key[6], NULL, 10);
486 else if (strncmp(key, "MINOR=", 6) == 0)
487 minor = strtoull(&key[6], NULL, 10);
488 else if (strncmp(key, "TIMEOUT=", 8) == 0)
489 msg->timeout = strtoull(&key[8], NULL, 10);
491 msg->devt = makedev(major, minor);
492 msg->envp[i++] = "UDEVD_EVENT=1";
498 /* receive the udevd message from userspace */
499 static struct uevent_msg *get_udevd_msg(void)
501 static struct udevd_msg usend_msg;
502 struct uevent_msg *msg;
505 struct cmsghdr *cmsg;
508 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
512 memset(&usend_msg, 0x00, sizeof(struct udevd_msg));
513 iov.iov_base = &usend_msg;
514 iov.iov_len = sizeof(struct udevd_msg);
516 memset(&smsg, 0x00, sizeof(struct msghdr));
519 smsg.msg_control = cred_msg;
520 smsg.msg_controllen = sizeof(cred_msg);
522 size = recvmsg(udevd_sock, &smsg, 0);
525 err("unable to receive udevd message");
528 cmsg = CMSG_FIRSTHDR(&smsg);
529 cred = (struct ucred *) CMSG_DATA(cmsg);
531 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
532 err("no sender credentials received, message ignored");
536 if (cred->uid != 0) {
537 err("sender uid=%i, message ignored", cred->uid);
541 if (strncmp(usend_msg.magic, UDEV_MAGIC, sizeof(UDEV_MAGIC)) != 0 ) {
542 err("message magic '%s' doesn't match, ignore it", usend_msg.magic);
546 switch (usend_msg.type) {
547 case UDEVD_UEVENT_UDEVSEND:
548 case UDEVD_UEVENT_INITSEND:
549 info("udevd event message received");
550 envbuf_size = size - offsetof(struct udevd_msg, envbuf);
551 dbg("envbuf_size=%i", envbuf_size);
552 msg = get_msg_from_envbuf(usend_msg.envbuf, envbuf_size);
555 msg->type = usend_msg.type;
557 case UDEVD_STOP_EXEC_QUEUE:
558 info("udevd message (STOP_EXEC_QUEUE) received");
561 case UDEVD_START_EXEC_QUEUE:
562 info("udevd message (START_EXEC_QUEUE) received");
564 exec_queue_manager();
566 case UDEVD_SET_LOG_LEVEL:
567 intval = (int *) usend_msg.envbuf;
568 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
569 udev_log_priority = *intval;
570 sprintf(log, "UDEV_LOG=%i", udev_log_priority);
573 case UDEVD_SET_MAX_CHILDS:
574 intval = (int *) usend_msg.envbuf;
575 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
576 max_childs = *intval;
579 dbg("unknown message type");
584 /* receive the kernel user event message and do some sanity checks */
585 static struct uevent_msg *get_netlink_msg(void)
587 struct uevent_msg *msg;
590 static char buffer[UEVENT_BUFFER_SIZE + 512];
593 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
596 err("unable to receive udevd message");
600 if ((size_t)size > sizeof(buffer)-1)
601 size = sizeof(buffer)-1;
603 dbg("uevent_size=%zi", size);
605 /* start of event payload */
606 bufpos = strlen(buffer)+1;
607 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
610 msg->type = UDEVD_UEVENT_NETLINK;
612 /* validate message */
613 pos = strchr(buffer, '@');
615 err("invalid uevent '%s'", buffer);
621 if (msg->action == NULL) {
622 err("no ACTION in payload found, skip event '%s'", buffer);
627 if (strcmp(msg->action, buffer) != 0) {
628 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
636 static void asmlinkage sig_handler(int signum)
644 /* set flag, then write to pipe if needed */
648 /* set flag, then write to pipe if needed */
649 sigchilds_waiting = 1;
653 /* write to pipe, which will wakeup select() in our mainloop */
654 write(signal_pipe[WRITE_END], "", 1);
657 static void udev_done(int pid)
659 /* find msg associated with pid and delete it */
660 struct uevent_msg *msg;
663 list_for_each_entry(msg, &running_list, node) {
664 if (msg->pid == pid) {
667 info("seq %llu, pid [%d] exit, %ld seconds old", msg->seqnum, msg->pid, info.uptime - msg->queue_time);
669 info("seq 0, pid [%d] exit", msg->pid);
670 msg_queue_delete(msg);
672 /* we want to run the exec queue manager since there may
673 * be events waiting with the devpath of the one that
682 static void reap_sigchilds(void)
687 pid = waitpid(-1, NULL, WNOHANG);
694 static int init_udevd_socket(void)
696 struct sockaddr_un saddr;
697 const int buffersize = 1024 * 1024;
699 const int feature_on = 1;
702 memset(&saddr, 0x00, sizeof(saddr));
703 saddr.sun_family = AF_LOCAL;
704 /* use abstract namespace for socket path */
705 strcpy(&saddr.sun_path[1], UDEVD_SOCK_PATH);
706 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
708 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
709 if (udevd_sock == -1) {
710 err("error getting socket, %s", strerror(errno));
714 /* set receive buffersize */
715 setsockopt(udevd_sock, SOL_SOCKET, SO_RCVBUF, &buffersize, sizeof(buffersize));
717 /* the bind takes care of ensuring only one copy running */
718 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
720 err("bind failed, %s", strerror(errno));
725 /* enable receiving of the sender credentials */
726 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
731 static int init_uevent_netlink_sock(void)
733 struct sockaddr_nl snl;
734 const int buffersize = 1024 * 1024;
737 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
738 snl.nl_family = AF_NETLINK;
739 snl.nl_pid = getpid();
740 snl.nl_groups = 0xffffffff;
742 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
743 if (uevent_netlink_sock == -1) {
744 err("error getting socket, %s", strerror(errno));
748 /* set receive buffersize */
749 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUF, &buffersize, sizeof(buffersize));
751 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl,
752 sizeof(struct sockaddr_nl));
754 err("bind failed, %s", strerror(errno));
755 close(uevent_netlink_sock);
756 uevent_netlink_sock = -1;
763 int main(int argc, char *argv[], char *envp[])
767 struct sigaction act;
770 int uevent_netlink_active = 0;
774 /* set std fd's to /dev/null, if the kernel forks us, we don't have them at all */
775 devnull = open("/dev/null", O_RDWR);
777 if (devnull != STDIN_FILENO)
778 dup2(devnull, STDIN_FILENO);
779 if (devnull != STDOUT_FILENO)
780 dup2(devnull, STDOUT_FILENO);
781 if (devnull != STDERR_FILENO)
782 dup2(devnull, STDERR_FILENO);
783 if (devnull > STDERR_FILENO)
787 logging_init("udevd");
789 err("fatal, could not open /dev/null");
792 dbg("version %s", UDEV_VERSION);
795 err("need to be root, exit");
799 for (i = 1 ; i < argc; i++) {
801 if (strcmp(arg, "--daemon") == 0 || strcmp(arg, "-d") == 0) {
802 info("will daemonize");
805 if (strcmp(arg, "--stop-exec-queue") == 0) {
806 info("will not execute events until START_EXEC_QUEUE is received");
817 dbg("damonized fork running");
820 err("fork of daemon failed");
828 /* become session leader */
830 dbg("our session is %d", sid);
833 umask(umask(077) | 022);
835 /* set a reasonable scheduling priority for the daemon */
836 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
838 /* setup signal handler pipe */
839 retval = pipe(signal_pipe);
841 err("error getting pipes: %s", strerror(errno));
844 retval = fcntl(signal_pipe[READ_END], F_SETFL, O_NONBLOCK);
846 err("error fcntl on read pipe: %s", strerror(errno));
849 retval = fcntl(signal_pipe[READ_END], F_SETFD, FD_CLOEXEC);
851 err("error fcntl on read pipe: %s", strerror(errno));
852 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, O_NONBLOCK);
854 err("error fcntl on write pipe: %s", strerror(errno));
857 retval = fcntl(signal_pipe[WRITE_END], F_SETFD, FD_CLOEXEC);
859 err("error fcntl on write pipe: %s", strerror(errno));
861 /* set signal handlers */
862 memset(&act, 0x00, sizeof(struct sigaction));
863 act.sa_handler = (void (*)(int)) sig_handler;
864 sigemptyset(&act.sa_mask);
865 act.sa_flags = SA_RESTART;
866 sigaction(SIGINT, &act, NULL);
867 sigaction(SIGTERM, &act, NULL);
868 sigaction(SIGALRM, &act, NULL);
869 sigaction(SIGCHLD, &act, NULL);
870 sigaction(SIGHUP, &act, NULL);
872 if (init_udevd_socket() < 0) {
873 if (errno == EADDRINUSE)
874 dbg("another udevd running, exit");
876 dbg("error initialising udevd socket: %s", strerror(errno));
881 if (init_uevent_netlink_sock() < 0)
882 info("uevent socket not available");
884 /* override of forked udev binary, used for testing */
885 udev_bin = getenv("UDEV_BIN");
886 if (udev_bin != NULL)
887 info("udev binary is set to '%s'", udev_bin);
891 /* init of expected_seqnum value */
892 value = getenv("UDEVD_EXPECTED_SEQNUM");
894 expected_seqnum = strtoull(value, NULL, 10);
895 info("initialize expected_seqnum to %llu", expected_seqnum);
898 /* timeout to wait for missing events */
899 value = getenv("UDEVD_EVENT_TIMEOUT");
901 event_timeout = strtoul(value, NULL, 10);
903 event_timeout = UDEVD_EVENT_TIMEOUT;
904 info("initialize event_timeout to %u", event_timeout);
906 /* maximum limit of forked childs */
907 value = getenv("UDEVD_MAX_CHILDS");
909 max_childs = strtoul(value, NULL, 10);
911 max_childs = UDEVD_MAX_CHILDS;
912 info("initialize max_childs to %u", max_childs);
914 /* start to throttle forking if maximum number of _running_ childs is reached */
915 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
917 max_childs_running = strtoull(value, NULL, 10);
919 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
920 info("initialize max_childs_running to %u", max_childs_running);
922 /* export log_priority , as called programs may want to follow that setting */
923 sprintf(log, "UDEV_LOG=%i", udev_log_priority);
927 struct uevent_msg *msg;
931 FD_SET(signal_pipe[READ_END], &readfds);
932 FD_SET(udevd_sock, &readfds);
933 if (uevent_netlink_sock > 0)
934 FD_SET(uevent_netlink_sock, &readfds);
936 fdcount = select(UDEV_MAX(udevd_sock, uevent_netlink_sock)+1, &readfds, NULL, NULL, NULL);
939 dbg("error in select: %s", strerror(errno));
943 /* get user socket message */
944 if (FD_ISSET(udevd_sock, &readfds)) {
945 msg = get_udevd_msg();
947 /* discard kernel messages if netlink is active */
948 if (uevent_netlink_active && msg->type == UDEVD_UEVENT_UDEVSEND && msg->seqnum != 0) {
949 info("skip uevent_helper message with SEQNUM, netlink is active");
952 msg_queue_insert(msg);
956 /* get kernel netlink message */
957 if ((uevent_netlink_sock > 0) && FD_ISSET(uevent_netlink_sock, &readfds)) {
958 msg = get_netlink_msg();
960 msg_queue_insert(msg);
961 /* disable udevsend with first netlink message */
962 if (!uevent_netlink_active) {
963 info("uevent_nl message received, disable udevsend messages");
964 uevent_netlink_active = 1;
969 /* received a signal, clear our notification pipe */
970 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
973 read(signal_pipe[READ_END], &buf, sizeof(buf));
976 /* forked child have returned */
977 if (sigchilds_waiting) {
978 sigchilds_waiting = 0;
988 /* clean up running_list before calling exec_queue_manager() */
989 if (sigchilds_waiting) {
990 sigchilds_waiting = 0;
996 exec_queue_manager();
1001 if (signal_pipe[READ_END] > 0)
1002 close(signal_pipe[READ_END]);
1003 if (signal_pipe[WRITE_END] > 0)
1004 close(signal_pipe[WRITE_END]);
1008 if (uevent_netlink_sock > 0)
1009 close(uevent_netlink_sock);