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 udevsendsock;
53 static int ueventsock;
56 static int pipefds[2];
57 static long startup_time;
58 static unsigned long long expected_seqnum = 0;
59 static volatile int sigchilds_waiting;
60 static volatile int run_msg_q;
61 static volatile int sig_flag;
62 static int run_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);
75 void log_message (int priority, const char *format, ...)
79 if (priority > udev_log_priority)
82 va_start(args, format);
83 vsyslog(priority, format, args);
88 static void msg_dump_queue(void)
91 struct hotplug_msg *msg;
93 list_for_each_entry(msg, &msg_list, node)
94 dbg("sequence %llu in queue", msg->seqnum);
98 static void run_queue_delete(struct hotplug_msg *msg)
100 list_del(&msg->node);
104 /* orders the message in the queue by sequence number */
105 static void msg_queue_insert(struct hotplug_msg *msg)
107 struct hotplug_msg *loop_msg;
110 if (msg->seqnum == 0) {
111 dbg("no SEQNUM, move straight to the exec queue");
112 list_add(&msg->node, &exec_list);
117 /* don't delay messages with timeout set */
119 dbg("move seq %llu with timeout %u to exec queue", msg->seqnum, msg->timeout);
120 list_add(&msg->node, &exec_list);
125 /* sort message by sequence number into list */
126 list_for_each_entry_reverse(loop_msg, &msg_list, node) {
127 if (loop_msg->seqnum < msg->seqnum)
130 if (loop_msg->seqnum == msg->seqnum) {
131 dbg("ignoring duplicate message seq %llu", msg->seqnum);
137 /* store timestamp of queuing */
139 msg->queue_time = info.uptime;
141 list_add(&msg->node, &loop_msg->node);
142 dbg("queued message seq %llu", msg->seqnum);
144 /* run msg queue manager */
150 /* forks event and removes event from run queue when finished */
151 static void execute_udev(struct hotplug_msg *msg)
153 char *const argv[] = { "udev", msg->subsystem, NULL };
160 if (ueventsock != -1)
165 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
166 execve(udev_bin, argv, msg->envp);
167 err("exec of child failed");
171 err("fork of child failed");
172 run_queue_delete(msg);
175 /* get SIGCHLD in main loop */
176 dbg("==> exec seq %llu [%d] working at '%s'", msg->seqnum, pid, msg->devpath);
181 static int running_processes(void)
184 static char buf[4096];
189 f = open("/proc/stat", O_RDONLY);
193 len = read(f, buf, sizeof(buf));
201 pos = strstr(buf, "procs_running ");
205 if (sscanf(pos, "procs_running %u", &running) != 1)
211 /* return the number of process es in our session, count only until limit */
212 static int running_processes_in_session(pid_t session, int limit)
218 dir = opendir("/proc");
222 /* read process info from /proc */
223 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
229 pid_t ppid, pgrp, sess;
232 if (!isdigit(dent->d_name[0]))
235 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
236 procdir[sizeof(procdir)-1] = '\0';
238 f = open(procdir, O_RDONLY);
242 len = read(f, line, sizeof(line));
250 /* skip ugly program name */
251 pos = strrchr(line, ')') + 2;
255 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
258 /* count only processes in our session */
262 /* count only running, no sleeping processes */
267 if (limit > 0 && running >= limit)
275 static int compare_devpath(const char *running, const char *waiting)
279 for (i = 0; i < PATH_SIZE; i++) {
280 /* identical device event found */
281 if (running[i] == '\0' && waiting[i] == '\0')
284 /* parent device event found */
285 if (running[i] == '\0' && waiting[i] == '/')
288 /* child device event found */
289 if (running[i] == '/' && waiting[i] == '\0')
292 /* no matching event */
293 if (running[i] != waiting[i])
300 /* returns still running task for the same device, its parent or its physical device */
301 static struct hotplug_msg *running_with_devpath(struct hotplug_msg *msg)
303 struct hotplug_msg *loop_msg;
305 if (msg->devpath == NULL)
308 /* skip any events with a timeout set */
312 list_for_each_entry(loop_msg, &running_list, node) {
313 if (loop_msg->devpath == NULL)
316 /* return running parent/child device event */
317 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0)
320 /* return running physical device event */
321 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
322 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0)
329 /* exec queue management routine executes the events and serializes events in the same sequence */
330 static void exec_queue_manager(void)
332 struct hotplug_msg *loop_msg;
333 struct hotplug_msg *tmp_msg;
334 struct hotplug_msg *msg;
337 running = running_processes();
338 dbg("%d processes runnning on system", running);
340 running = THROTTLE_MAX_RUNNING_CHILDS;
342 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
343 /* check running processes in our session and possibly throttle */
344 if (running >= THROTTLE_MAX_RUNNING_CHILDS) {
345 running = running_processes_in_session(sid, THROTTLE_MAX_RUNNING_CHILDS+10);
346 dbg("%d processes running in session", running);
347 if (running >= THROTTLE_MAX_RUNNING_CHILDS) {
348 dbg("delay seq %llu, cause too many processes already running", loop_msg->seqnum);
353 msg = running_with_devpath(loop_msg);
355 /* move event to run list */
356 list_move_tail(&loop_msg->node, &running_list);
357 execute_udev(loop_msg);
359 dbg("moved seq %llu to running list", loop_msg->seqnum);
361 dbg("delay seq %llu (%s), cause seq %llu (%s) is still running",
362 loop_msg->seqnum, loop_msg->devpath, msg->seqnum, msg->devpath);
367 static void msg_move_exec(struct hotplug_msg *msg)
369 list_move_tail(&msg->node, &exec_list);
371 expected_seqnum = msg->seqnum+1;
372 dbg("moved seq %llu to exec, next expected is %llu",
373 msg->seqnum, expected_seqnum);
376 /* msg queue management routine handles the timeouts and dispatches the events */
377 static void msg_queue_manager(void)
379 struct hotplug_msg *loop_msg;
380 struct hotplug_msg *tmp_msg;
383 static int timeout = EVENT_INIT_TIMEOUT_SEC;
386 dbg("msg queue manager, next expected is %llu", expected_seqnum);
388 list_for_each_entry_safe(loop_msg, tmp_msg, &msg_list, node) {
389 /* move event with expected sequence to the exec list */
390 if (loop_msg->seqnum == expected_seqnum) {
391 msg_move_exec(loop_msg);
395 /* see if we are in the initialization phase and wait for the very first events */
396 if (init && (info.uptime - startup_time >= INIT_TIME_SEC)) {
398 timeout = EVENT_TIMEOUT_SEC;
399 dbg("initialization phase passed, set timeout to %i seconds", EVENT_TIMEOUT_SEC);
402 /* move event with expired timeout to the exec list */
404 msg_age = info.uptime - loop_msg->queue_time;
405 dbg("seq %llu is %li seconds old", loop_msg->seqnum, msg_age);
406 if (msg_age >= timeout) {
407 msg_move_exec(loop_msg);
416 /* set timeout for remaining queued events */
417 if (list_empty(&msg_list) == 0) {
418 struct itimerval itv = {{0, 0}, {timeout - msg_age, 0}};
419 dbg("next event expires in %li seconds", timeout - msg_age);
420 setitimer(ITIMER_REAL, &itv, NULL);
424 static struct hotplug_msg *get_msg_from_envbuf(const char *buf, int buf_size)
428 struct hotplug_msg *msg;
430 msg = malloc(sizeof(struct hotplug_msg) + buf_size);
433 memset(msg, 0x00, sizeof(struct hotplug_msg) + buf_size);
435 /* copy environment buffer and reconstruct envp */
436 memcpy(msg->envbuf, buf, buf_size);
438 for (i = 0; (bufpos < buf_size) && (i < HOTPLUG_NUM_ENVP-2); i++) {
442 key = &msg->envbuf[bufpos];
443 keylen = strlen(key);
445 bufpos += keylen + 1;
446 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
448 /* remember some keys for further processing */
449 if (strncmp(key, "ACTION=", 7) == 0)
450 msg->action = &key[7];
452 if (strncmp(key, "DEVPATH=", 8) == 0)
453 msg->devpath = &key[8];
455 if (strncmp(key, "SUBSYSTEM=", 10) == 0)
456 msg->subsystem = &key[10];
458 if (strncmp(key, "SEQNUM=", 7) == 0)
459 msg->seqnum = strtoull(&key[7], NULL, 10);
461 if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
462 msg->physdevpath = &key[12];
464 if (strncmp(key, "TIMEOUT=", 8) == 0)
465 msg->timeout = strtoull(&key[8], NULL, 10);
467 msg->envp[i++] = "UDEVD_EVENT=1";
473 /* receive the udevsend message and do some sanity checks */
474 static struct hotplug_msg *get_udevsend_msg(void)
476 static struct udevsend_msg usend_msg;
477 struct hotplug_msg *msg;
480 struct cmsghdr *cmsg;
483 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
486 memset(&usend_msg, 0x00, sizeof(struct udevsend_msg));
487 iov.iov_base = &usend_msg;
488 iov.iov_len = sizeof(struct udevsend_msg);
490 memset(&smsg, 0x00, sizeof(struct msghdr));
493 smsg.msg_control = cred_msg;
494 smsg.msg_controllen = sizeof(cred_msg);
496 size = recvmsg(udevsendsock, &smsg, 0);
499 dbg("unable to receive udevsend message");
502 cmsg = CMSG_FIRSTHDR(&smsg);
503 cred = (struct ucred *) CMSG_DATA(cmsg);
505 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
506 info("no sender credentials received, message ignored");
510 if (cred->uid != 0) {
511 info("sender uid=%i, message ignored", cred->uid);
515 if (strncmp(usend_msg.magic, UDEV_MAGIC, sizeof(UDEV_MAGIC)) != 0 ) {
516 info("message magic '%s' doesn't match, ignore it", usend_msg.magic);
520 envbuf_size = size - offsetof(struct udevsend_msg, envbuf);
521 dbg("envbuf_size=%i", envbuf_size);
522 msg = get_msg_from_envbuf(usend_msg.envbuf, envbuf_size);
529 /* receive the kernel user event message and do some sanity checks */
530 static struct hotplug_msg *get_uevent_msg(void)
532 struct hotplug_msg *msg;
535 static char buffer[HOTPLUG_BUFFER_SIZE + 512];
538 size = recv(ueventsock, &buffer, sizeof(buffer), 0);
541 dbg("unable to receive udevsend message");
545 if ((size_t)size > sizeof(buffer)-1)
546 size = sizeof(buffer)-1;
548 dbg("uevent_size=%i", size);
550 /* start of event payload */
551 bufpos = strlen(buffer)+1;
552 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
556 /* validate message */
557 pos = strchr(buffer, '@');
559 dbg("invalid uevent '%s'", buffer);
565 if (msg->action == NULL) {
566 dbg("no ACTION in payload found, skip event '%s'", buffer);
571 if (strcmp(msg->action, buffer) != 0) {
572 dbg("ACTION in payload does not match uevent, skip event '%s'", buffer);
580 static void asmlinkage sig_handler(int signum)
590 /* set flag, then write to pipe if needed */
595 /* set flag, then write to pipe if needed */
596 sigchilds_waiting = 1;
602 /* if pipe is empty, write to pipe to force select to return
603 * immediately when it gets called
606 rc = write(pipefds[1],&signum,sizeof(signum));
612 static void udev_done(int pid)
614 /* find msg associated with pid and delete it */
615 struct hotplug_msg *msg;
617 list_for_each_entry(msg, &running_list, node) {
618 if (msg->pid == pid) {
619 dbg("<== exec seq %llu came back", msg->seqnum);
620 run_queue_delete(msg);
622 /* we want to run the exec queue manager since there may
623 * be events waiting with the devpath of the one that
632 static void reap_sigchilds(void)
635 int pid = waitpid(-1, NULL, WNOHANG);
636 if ((pid == -1) || (pid == 0))
642 /* just read everything from the pipe and clear the flag,
643 * the flags was set in the signal handler
645 static void user_sighandler(void)
650 int rc = read(pipefds[0], &sig, sizeof(sig));
658 static int init_udevsend_socket(void)
660 struct sockaddr_un saddr;
662 const int feature_on = 1;
665 memset(&saddr, 0x00, sizeof(saddr));
666 saddr.sun_family = AF_LOCAL;
667 /* use abstract namespace for socket path */
668 strcpy(&saddr.sun_path[1], UDEVD_SOCK_PATH);
669 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
671 udevsendsock = socket(AF_LOCAL, SOCK_DGRAM, 0);
672 if (udevsendsock == -1) {
673 err("error getting socket, %s", strerror(errno));
677 /* the bind takes care of ensuring only one copy running */
678 retval = bind(udevsendsock, (struct sockaddr *) &saddr, addrlen);
680 err("bind failed, %s", strerror(errno));
685 /* enable receiving of the sender credentials */
686 setsockopt(udevsendsock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
691 static int init_uevent_socket(void)
693 struct sockaddr_nl snl;
696 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
697 snl.nl_family = AF_NETLINK;
698 snl.nl_pid = getpid();
699 snl.nl_groups = 0xffffffff;
701 ueventsock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
702 if (ueventsock == -1) {
703 dbg("error getting socket, %s", strerror(errno));
707 retval = bind(ueventsock, (struct sockaddr *) &snl,
708 sizeof(struct sockaddr_nl));
710 dbg("bind failed, %s", strerror(errno));
719 int main(int argc, char *argv[], char *envp[])
725 struct sigaction act;
727 const char *udevd_expected_seqnum;
728 int uevent_active = 0;
730 logging_init("udevd");
732 dbg("version %s", UDEV_VERSION);
735 err("need to be root, exit");
739 /* daemonize on request */
740 if (argc == 2 && strcmp(argv[1], "-d") == 0) {
746 dbg("damonized fork running");
749 err("fork of daemon failed");
757 /* become session leader */
759 dbg("our session is %d", sid);
761 /* make sure we don't lock any path */
763 umask(umask(077) | 022);
765 /*set a reasonable scheduling priority for the daemon */
766 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
768 /* Set fds to dev/null */
769 fd = open( "/dev/null", O_RDWR );
777 err("error opening /dev/null %s", strerror(errno));
779 /* setup signal handler pipe */
780 retval = pipe(pipefds);
782 err("error getting pipes: %s", strerror(errno));
786 retval = fcntl(pipefds[0], F_SETFL, O_NONBLOCK);
788 err("error fcntl on read pipe: %s", strerror(errno));
791 retval = fcntl(pipefds[0], F_SETFD, FD_CLOEXEC);
793 err("error fcntl on read pipe: %s", strerror(errno));
795 retval = fcntl(pipefds[1], F_SETFL, O_NONBLOCK);
797 err("error fcntl on write pipe: %s", strerror(errno));
800 retval = fcntl(pipefds[1], F_SETFD, FD_CLOEXEC);
802 err("error fcntl on write pipe: %s", strerror(errno));
804 /* set signal handlers */
805 memset(&act, 0x00, sizeof(struct sigaction));
806 act.sa_handler = (void (*)(int)) sig_handler;
807 sigemptyset(&act.sa_mask);
808 act.sa_flags = SA_RESTART;
809 sigaction(SIGINT, &act, NULL);
810 sigaction(SIGTERM, &act, NULL);
811 sigaction(SIGALRM, &act, NULL);
812 sigaction(SIGCHLD, &act, NULL);
814 if (init_uevent_socket() < 0) {
815 dbg("uevent socket not available");
818 if (init_udevsend_socket() < 0) {
819 if (errno == EADDRINUSE)
820 dbg("another udevd running, exit");
822 dbg("error initialising udevsend socket: %s", strerror(errno));
827 /* possible override of udev binary, used for testing */
828 udev_bin = getenv("UDEV_BIN");
829 if (udev_bin != NULL)
830 info("udev binary is set to '%s'", udev_bin);
834 /* possible init of expected_seqnum value */
835 udevd_expected_seqnum = getenv("UDEVD_EXPECTED_SEQNUM");
836 if (udevd_expected_seqnum != NULL) {
837 expected_seqnum = strtoull(udevd_expected_seqnum, NULL, 10);
838 info("initialize expected_seqnum to %llu", expected_seqnum);
841 /* get current time to provide shorter timeout on startup */
843 startup_time = info.uptime;
846 FD_SET(udevsendsock, &readfds);
847 if (ueventsock != -1)
848 FD_SET(ueventsock, &readfds);
849 FD_SET(pipefds[0], &readfds);
850 maxsockplus = udevsendsock+1;
852 struct hotplug_msg *msg;
854 fd_set workreadfds = readfds;
855 retval = select(maxsockplus, &workreadfds, NULL, NULL, NULL);
859 dbg("error in select: %s", strerror(errno));
863 if (FD_ISSET(udevsendsock, &workreadfds)) {
864 msg = get_udevsend_msg();
866 /* discard kernel messages if netlink is active */
867 if (uevent_active && msg->seqnum != 0) {
868 dbg("skip kernel udevsend message, netlink is active");
872 msg_queue_insert(msg);
876 if (FD_ISSET(ueventsock, &workreadfds)) {
877 msg = get_uevent_msg();
879 msg_queue_insert(msg);
880 /* disable udevsend with first netlink message */
881 if (!uevent_active) {
882 info("netlink message received, disable kernel udevsend messages");
888 if (FD_ISSET(pipefds[0], &workreadfds))
891 if (sigchilds_waiting) {
892 sigchilds_waiting = 0;
902 /* clean up running_list before calling exec_queue_manager() */
903 if (sigchilds_waiting) {
904 sigchilds_waiting = 0;
909 exec_queue_manager();