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"
52 static int udevd_sock;
53 static int uevent_nl_sock;
56 static int pipefds[2];
57 static volatile int sigchilds_waiting;
58 static volatile int run_msg_q;
59 static volatile int sig_flag;
60 static int init_phase = 1;
61 static int run_exec_q;
62 static int stop_exec_q;
64 static LIST_HEAD(msg_list);
65 static LIST_HEAD(exec_list);
66 static LIST_HEAD(running_list);
68 static void exec_queue_manager(void);
69 static void msg_queue_manager(void);
70 static void user_sighandler(void);
71 static void reap_sigchilds(void);
73 static char *udev_bin;
74 static unsigned long long expected_seqnum;
75 static int event_timeout;
76 static int max_childs;
77 static int max_childs_running;
81 void log_message (int priority, const char *format, ...)
85 if (priority > udev_log_priority)
88 va_start(args, format);
89 vsyslog(priority, format, args);
94 static void msg_dump_queue(void)
97 struct uevent_msg *msg;
99 list_for_each_entry(msg, &msg_list, node)
100 dbg("sequence %llu in queue", msg->seqnum);
104 static void run_queue_delete(struct uevent_msg *msg)
106 list_del(&msg->node);
110 /* orders the message in the queue by sequence number */
111 static void msg_queue_insert(struct uevent_msg *msg)
113 struct uevent_msg *loop_msg;
116 if (msg->seqnum == 0) {
117 dbg("no SEQNUM, move straight to the exec queue");
118 list_add(&msg->node, &exec_list);
123 /* store timestamp of queuing */
125 msg->queue_time = info.uptime;
127 /* with the first event we provide a phase of shorter timeout */
129 static long init_time;
132 init_time = info.uptime;
133 if (info.uptime - init_time >= UDEVD_INIT_TIME)
137 /* don't delay messages with timeout set */
139 dbg("move seq %llu with timeout %u to exec queue", msg->seqnum, msg->timeout);
140 list_add(&msg->node, &exec_list);
145 /* sort message by sequence number into list */
146 list_for_each_entry_reverse(loop_msg, &msg_list, node) {
147 if (loop_msg->seqnum < msg->seqnum)
150 if (loop_msg->seqnum == msg->seqnum) {
151 dbg("ignoring duplicate message seq %llu", msg->seqnum);
156 list_add(&msg->node, &loop_msg->node);
157 info("seq %llu queued, devpath '%s'", msg->seqnum, msg->devpath);
159 /* run msg queue manager */
165 /* forks event and removes event from run queue when finished */
166 static void execute_udev(struct uevent_msg *msg)
168 char *const argv[] = { "udev", msg->subsystem, NULL };
176 if (uevent_nl_sock != -1)
177 close(uevent_nl_sock);
181 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
182 execve(udev_bin, argv, msg->envp);
183 err("exec of child failed");
187 err("fork of child failed");
188 run_queue_delete(msg);
191 /* get SIGCHLD in main loop */
193 info("seq %llu forked, pid %d, %ld seconds old",
194 msg->seqnum, pid, info.uptime - msg->queue_time);
199 static int running_processes(void)
202 static char buf[4096];
207 f = open("/proc/stat", O_RDONLY);
211 len = read(f, buf, sizeof(buf));
219 pos = strstr(buf, "procs_running ");
223 if (sscanf(pos, "procs_running %u", &running) != 1)
229 /* return the number of process es in our session, count only until limit */
230 static int running_processes_in_session(pid_t session, int limit)
236 dir = opendir("/proc");
240 /* read process info from /proc */
241 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
247 pid_t ppid, pgrp, sess;
250 if (!isdigit(dent->d_name[0]))
253 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
254 procdir[sizeof(procdir)-1] = '\0';
256 f = open(procdir, O_RDONLY);
260 len = read(f, line, sizeof(line));
268 /* skip ugly program name */
269 pos = strrchr(line, ')') + 2;
273 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
276 /* count only processes in our session */
280 /* count only running, no sleeping processes */
285 if (limit > 0 && running >= limit)
293 static int compare_devpath(const char *running, const char *waiting)
297 for (i = 0; i < PATH_SIZE; i++) {
298 /* identical device event found */
299 if (running[i] == '\0' && waiting[i] == '\0')
302 /* parent device event found */
303 if (running[i] == '\0' && waiting[i] == '/')
306 /* child device event found */
307 if (running[i] == '/' && waiting[i] == '\0')
310 /* no matching event */
311 if (running[i] != waiting[i])
318 /* returns still running task for the same device, its parent or its physical device */
319 static int running_with_devpath(struct uevent_msg *msg, int limit)
321 struct uevent_msg *loop_msg;
322 int childs_count = 0;
324 if (msg->devpath == NULL)
327 /* skip any events with a timeout set */
328 if (msg->timeout != 0)
331 list_for_each_entry(loop_msg, &running_list, node) {
332 if (limit && childs_count++ > limit) {
333 dbg("%llu, maximum number (%i) of child reached", msg->seqnum, childs_count);
336 if (loop_msg->devpath == NULL)
339 /* return running parent/child device event */
340 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
341 dbg("%llu, child device event still running %llu (%s)",
342 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
346 /* return running physical device event */
347 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
348 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
349 dbg("%llu, physical device event still running %llu (%s)",
350 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
358 /* exec queue management routine executes the events and serializes events in the same sequence */
359 static void exec_queue_manager(void)
361 struct uevent_msg *loop_msg;
362 struct uevent_msg *tmp_msg;
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 execute_udev(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) == 0) {
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;
454 msg = malloc(sizeof(struct uevent_msg) + buf_size);
457 memset(msg, 0x00, sizeof(struct uevent_msg) + buf_size);
459 /* copy environment buffer and reconstruct envp */
460 memcpy(msg->envbuf, buf, buf_size);
462 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
466 key = &msg->envbuf[bufpos];
467 keylen = strlen(key);
469 bufpos += keylen + 1;
470 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
472 /* remember some keys for further processing */
473 if (strncmp(key, "ACTION=", 7) == 0)
474 msg->action = &key[7];
476 if (strncmp(key, "DEVPATH=", 8) == 0)
477 msg->devpath = &key[8];
479 if (strncmp(key, "SUBSYSTEM=", 10) == 0)
480 msg->subsystem = &key[10];
482 if (strncmp(key, "SEQNUM=", 7) == 0)
483 msg->seqnum = strtoull(&key[7], NULL, 10);
485 if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
486 msg->physdevpath = &key[12];
488 if (strncmp(key, "TIMEOUT=", 8) == 0)
489 msg->timeout = strtoull(&key[8], NULL, 10);
491 msg->envp[i++] = "UDEVD_EVENT=1";
497 /* receive the udevd message from userspace */
498 static struct uevent_msg *get_udevd_msg(void)
500 static struct udevd_msg usend_msg;
501 struct uevent_msg *msg;
504 struct cmsghdr *cmsg;
507 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
510 memset(&usend_msg, 0x00, sizeof(struct udevd_msg));
511 iov.iov_base = &usend_msg;
512 iov.iov_len = sizeof(struct udevd_msg);
514 memset(&smsg, 0x00, sizeof(struct msghdr));
517 smsg.msg_control = cred_msg;
518 smsg.msg_controllen = sizeof(cred_msg);
520 size = recvmsg(udevd_sock, &smsg, 0);
523 dbg("unable to receive udevd message");
526 cmsg = CMSG_FIRSTHDR(&smsg);
527 cred = (struct ucred *) CMSG_DATA(cmsg);
529 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
530 info("no sender credentials received, message ignored");
534 if (cred->uid != 0) {
535 info("sender uid=%i, message ignored", cred->uid);
539 if (strncmp(usend_msg.magic, UDEV_MAGIC, sizeof(UDEV_MAGIC)) != 0 ) {
540 info("message magic '%s' doesn't match, ignore it", usend_msg.magic);
544 switch (usend_msg.type) {
546 dbg("udevd message (UEVENT) received");
547 envbuf_size = size - offsetof(struct udevd_msg, envbuf);
548 dbg("envbuf_size=%i", envbuf_size);
549 msg = get_msg_from_envbuf(usend_msg.envbuf, envbuf_size);
553 case UDEVD_STOP_EXEC_QUEUE:
554 dbg("udevd message (STOP_EXEC_QUEUE) received");
557 case UDEVD_START_EXEC_QUEUE:
558 dbg("udevd message (START_EXEC_QUEUE) received");
560 exec_queue_manager();
563 dbg("unknown message type");
568 /* receive the kernel user event message and do some sanity checks */
569 static struct uevent_msg *get_uevent_msg(void)
571 struct uevent_msg *msg;
574 static char buffer[UEVENT_BUFFER_SIZE + 512];
577 size = recv(uevent_nl_sock, &buffer, sizeof(buffer), 0);
580 dbg("unable to receive udevd message");
584 if ((size_t)size > sizeof(buffer)-1)
585 size = sizeof(buffer)-1;
587 dbg("uevent_size=%i", size);
589 /* start of event payload */
590 bufpos = strlen(buffer)+1;
591 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
595 /* validate message */
596 pos = strchr(buffer, '@');
598 dbg("invalid uevent '%s'", buffer);
604 if (msg->action == NULL) {
605 dbg("no ACTION in payload found, skip event '%s'", buffer);
610 if (strcmp(msg->action, buffer) != 0) {
611 dbg("ACTION in payload does not match uevent, skip event '%s'", buffer);
619 static void asmlinkage sig_handler(int signum)
629 /* set flag, then write to pipe if needed */
634 /* set flag, then write to pipe if needed */
635 sigchilds_waiting = 1;
641 /* if pipe is empty, write to pipe to force select to return
642 * immediately when it gets called
645 rc = write(pipefds[1],&signum,sizeof(signum));
651 static void udev_done(int pid)
653 /* find msg associated with pid and delete it */
654 struct uevent_msg *msg;
657 list_for_each_entry(msg, &running_list, node) {
658 if (msg->pid == pid) {
660 info("seq %llu exit, %ld sec old", msg->seqnum, info.uptime - msg->queue_time);
661 run_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)
676 int pid = waitpid(-1, NULL, WNOHANG);
677 if ((pid == -1) || (pid == 0))
683 /* just read everything from the pipe and clear the flag,
684 * the flags was set in the signal handler
686 static void user_sighandler(void)
691 int rc = read(pipefds[0], &sig, sizeof(sig));
699 static int init_udevd_socket(void)
701 struct sockaddr_un saddr;
703 const int feature_on = 1;
706 memset(&saddr, 0x00, sizeof(saddr));
707 saddr.sun_family = AF_LOCAL;
708 /* use abstract namespace for socket path */
709 strcpy(&saddr.sun_path[1], UDEVD_SOCK_PATH);
710 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
712 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
713 if (udevd_sock == -1) {
714 err("error getting socket, %s", strerror(errno));
718 /* the bind takes care of ensuring only one copy running */
719 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
721 err("bind failed, %s", strerror(errno));
726 /* enable receiving of the sender credentials */
727 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
732 static int init_uevent_nl_sock(void)
734 struct sockaddr_nl snl;
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_nl_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
743 if (uevent_nl_sock == -1) {
744 dbg("error getting socket, %s", strerror(errno));
748 retval = bind(uevent_nl_sock, (struct sockaddr *) &snl,
749 sizeof(struct sockaddr_nl));
751 dbg("bind failed, %s", strerror(errno));
752 close(uevent_nl_sock);
760 int main(int argc, char *argv[], char *envp[])
765 struct sigaction act;
768 int uevent_nl_active = 0;
770 logging_init("udevd");
772 dbg("version %s", UDEV_VERSION);
775 err("need to be root, exit");
779 /* daemonize on request */
780 if (argc == 2 && strcmp(argv[1], "-d") == 0) {
786 dbg("damonized fork running");
789 err("fork of daemon failed");
797 /* become session leader */
799 dbg("our session is %d", sid);
802 umask(umask(077) | 022);
804 /*set a reasonable scheduling priority for the daemon */
805 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
807 /* Set fds to dev/null */
808 fd = open( "/dev/null", O_RDWR );
816 err("error opening /dev/null %s", strerror(errno));
818 /* setup signal handler pipe */
819 retval = pipe(pipefds);
821 err("error getting pipes: %s", strerror(errno));
825 retval = fcntl(pipefds[0], F_SETFL, O_NONBLOCK);
827 err("error fcntl on read pipe: %s", strerror(errno));
830 retval = fcntl(pipefds[0], F_SETFD, FD_CLOEXEC);
832 err("error fcntl on read pipe: %s", strerror(errno));
834 retval = fcntl(pipefds[1], F_SETFL, O_NONBLOCK);
836 err("error fcntl on write pipe: %s", strerror(errno));
839 retval = fcntl(pipefds[1], F_SETFD, FD_CLOEXEC);
841 err("error fcntl on write pipe: %s", strerror(errno));
843 /* set signal handlers */
844 memset(&act, 0x00, sizeof(struct sigaction));
845 act.sa_handler = (void (*)(int)) sig_handler;
846 sigemptyset(&act.sa_mask);
847 act.sa_flags = SA_RESTART;
848 sigaction(SIGINT, &act, NULL);
849 sigaction(SIGTERM, &act, NULL);
850 sigaction(SIGALRM, &act, NULL);
851 sigaction(SIGCHLD, &act, NULL);
853 if (init_uevent_nl_sock() < 0) {
854 dbg("uevent socket not available");
857 if (init_udevd_socket() < 0) {
858 if (errno == EADDRINUSE)
859 dbg("another udevd running, exit");
861 dbg("error initialising udevd socket: %s", strerror(errno));
866 /* override of forked udev binary, used for testing */
867 udev_bin = getenv("UDEV_BIN");
868 if (udev_bin != NULL)
869 info("udev binary is set to '%s'", udev_bin);
873 /* init of expected_seqnum value */
874 value = getenv("UDEVD_EXPECTED_SEQNUM");
876 expected_seqnum = strtoull(value, NULL, 10);
877 info("initialize expected_seqnum to %llu", expected_seqnum);
880 /* timeout to wait for missing events */
881 value = getenv("UDEVD_EVENT_TIMEOUT");
883 event_timeout = strtoul(value, NULL, 10);
885 event_timeout = UDEVD_EVENT_TIMEOUT;
886 info("initialize event_timeout to %u", event_timeout);
888 /* maximum limit of forked childs */
889 value = getenv("UDEVD_MAX_CHILDS");
891 max_childs = strtoul(value, NULL, 10);
893 max_childs = UDEVD_MAX_CHILDS;
894 info("initialize max_childs to %u", max_childs);
896 /* start to throttle forking if maximum number of _running_ childs is reached */
897 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
899 max_childs_running = strtoull(value, NULL, 10);
901 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
902 info("initialize max_childs_running to %u", max_childs_running);
905 FD_SET(udevd_sock, &readfds);
906 if (uevent_nl_sock != -1)
907 FD_SET(uevent_nl_sock, &readfds);
908 FD_SET(pipefds[0], &readfds);
909 maxsockplus = udevd_sock+1;
911 struct uevent_msg *msg;
913 fd_set workreadfds = readfds;
914 retval = select(maxsockplus, &workreadfds, NULL, NULL, NULL);
918 dbg("error in select: %s", strerror(errno));
922 if (FD_ISSET(udevd_sock, &workreadfds)) {
923 msg = get_udevd_msg();
925 /* discard kernel messages if netlink is active */
926 if (uevent_nl_active && msg->seqnum != 0) {
927 dbg("skip uevent_helper message, netlink is active");
931 msg_queue_insert(msg);
935 if (FD_ISSET(uevent_nl_sock, &workreadfds)) {
936 msg = get_uevent_msg();
938 msg_queue_insert(msg);
939 /* disable kernel uevent_helper with first netlink message */
940 if (!uevent_nl_active) {
941 info("uevent_nl message received, disable uevent_helper messages");
942 uevent_nl_active = 1;
947 if (FD_ISSET(pipefds[0], &workreadfds))
950 if (sigchilds_waiting) {
951 sigchilds_waiting = 0;
961 /* clean up running_list before calling exec_queue_manager() */
962 if (sigchilds_waiting) {
963 sigchilds_waiting = 0;
969 exec_queue_manager();