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>
43 #include "udev_libc_wrapper.h"
45 #include "udev_version.h"
46 #include "udev_utils.h"
51 static int udevsendsock;
54 static int pipefds[2];
55 static long startup_time;
56 static unsigned long long expected_seqnum = 0;
57 static volatile int sigchilds_waiting;
58 static volatile int run_msg_q;
59 static volatile int sig_flag;
60 static int run_exec_q;
62 static LIST_HEAD(msg_list);
63 static LIST_HEAD(exec_list);
64 static LIST_HEAD(running_list);
66 static void exec_queue_manager(void);
67 static void msg_queue_manager(void);
68 static void user_sighandler(void);
69 static void reap_sigchilds(void);
73 void log_message (int level, const char *format, ...)
77 va_start(args, format);
78 vsyslog(level, format, args);
83 #define msg_dump(msg) \
84 dbg("msg_dump: sequence %llu, '%s', '%s', '%s'", \
85 msg->seqnum, msg->action, msg->devpath, msg->subsystem);
87 static void msg_dump_queue(void)
90 struct hotplug_msg *msg;
92 list_for_each_entry(msg, &msg_list, node)
93 dbg("sequence %llu in queue", msg->seqnum);
97 static void run_queue_delete(struct hotplug_msg *msg)
103 /* orders the message in the queue by sequence number */
104 static void msg_queue_insert(struct hotplug_msg *msg)
106 struct hotplug_msg *loop_msg;
109 if (msg->seqnum == 0) {
110 dbg("no SEQNUM, move straight to the exec queue");
111 list_add(&msg->node, &exec_list);
116 /* don't delay messages with timeout set */
118 dbg("move seq %llu with timeout %u to exec queue", msg->seqnum, msg->timeout);
119 list_add(&msg->node, &exec_list);
124 /* sort message by sequence number into list */
125 list_for_each_entry_reverse(loop_msg, &msg_list, node) {
126 if (loop_msg->seqnum < msg->seqnum)
129 if (loop_msg->seqnum == msg->seqnum) {
130 dbg("ignoring duplicate message seq %llu", msg->seqnum);
135 /* store timestamp of queuing */
137 msg->queue_time = info.uptime;
139 list_add(&msg->node, &loop_msg->node);
140 dbg("queued message seq %llu", msg->seqnum);
142 /* run msg queue manager */
148 /* forks event and removes event from run queue when finished */
149 static void udev_run(struct hotplug_msg *msg)
151 char *const argv[] = { "udev", msg->subsystem, NULL };
161 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
162 execve(udev_bin, argv, msg->envp);
163 dbg("exec of child failed");
167 dbg("fork of child failed");
168 run_queue_delete(msg);
171 /* get SIGCHLD in main loop */
172 dbg("==> exec seq %llu [%d] working at '%s'", msg->seqnum, pid, msg->devpath);
177 static int running_processes(void)
180 static char buf[4096];
185 f = open("/proc/stat", O_RDONLY);
189 len = read(f, buf, sizeof(buf));
197 pos = strstr(buf, "procs_running ");
201 if (sscanf(pos, "procs_running %u", &running) != 1)
207 /* return the number of process es in our session, count only until limit */
208 static int running_processes_in_session(pid_t session, int limit)
214 dir = opendir("/proc");
218 /* read process info from /proc */
219 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
225 pid_t ppid, pgrp, sess;
228 if (!isdigit(dent->d_name[0]))
231 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
232 procdir[sizeof(procdir)-1] = '\0';
234 f = open(procdir, O_RDONLY);
238 len = read(f, line, sizeof(line));
246 /* skip ugly program name */
247 pos = strrchr(line, ')') + 2;
251 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
254 /* count only processes in our session */
258 /* count only running, no sleeping processes */
263 if (limit > 0 && running >= limit)
271 static int compare_devpath(const char *running, const char *waiting)
275 for (i = 0; i < PATH_SIZE; i++) {
276 /* identical device event found */
277 if (running[i] == '\0' && waiting[i] == '\0')
280 /* parent device event found */
281 if (running[i] == '\0' && waiting[i] == '/')
284 /* child device event found */
285 if (running[i] == '/' && waiting[i] == '\0')
288 /* no matching event */
289 if (running[i] != waiting[i])
296 /* returns still running task for the same device, its parent or its physical device */
297 static struct hotplug_msg *running_with_devpath(struct hotplug_msg *msg)
299 struct hotplug_msg *loop_msg;
301 if (msg->devpath == NULL)
304 /* skip any events with a timeout set */
308 list_for_each_entry(loop_msg, &running_list, node) {
309 if (loop_msg->devpath == NULL)
312 /* return running parent/child device event */
313 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0)
316 /* return running physical device event */
317 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
318 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0)
325 /* exec queue management routine executes the events and serializes events in the same sequence */
326 static void exec_queue_manager(void)
328 struct hotplug_msg *loop_msg;
329 struct hotplug_msg *tmp_msg;
330 struct hotplug_msg *msg;
333 running = running_processes();
334 dbg("%d processes runnning on system", running);
336 running = THROTTLE_MAX_RUNNING_CHILDS;
338 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
339 /* check running processes in our session and possibly throttle */
340 if (running >= THROTTLE_MAX_RUNNING_CHILDS) {
341 running = running_processes_in_session(sid, THROTTLE_MAX_RUNNING_CHILDS+10);
342 dbg("%d processes running in session", running);
343 if (running >= THROTTLE_MAX_RUNNING_CHILDS) {
344 dbg("delay seq %llu, cause too many processes already running", loop_msg->seqnum);
349 msg = running_with_devpath(loop_msg);
351 /* move event to run list */
352 list_move_tail(&loop_msg->node, &running_list);
355 dbg("moved seq %llu to running list", loop_msg->seqnum);
357 dbg("delay seq %llu (%s), cause seq %llu (%s) is still running",
358 loop_msg->seqnum, loop_msg->devpath, msg->seqnum, msg->devpath);
363 static void msg_move_exec(struct hotplug_msg *msg)
365 list_move_tail(&msg->node, &exec_list);
367 expected_seqnum = msg->seqnum+1;
368 dbg("moved seq %llu to exec, next expected is %llu",
369 msg->seqnum, expected_seqnum);
372 /* msg queue management routine handles the timeouts and dispatches the events */
373 static void msg_queue_manager(void)
375 struct hotplug_msg *loop_msg;
376 struct hotplug_msg *tmp_msg;
379 static int timeout = EVENT_INIT_TIMEOUT_SEC;
382 dbg("msg queue manager, next expected is %llu", expected_seqnum);
384 list_for_each_entry_safe(loop_msg, tmp_msg, &msg_list, node) {
385 /* move event with expected sequence to the exec list */
386 if (loop_msg->seqnum == expected_seqnum) {
387 msg_move_exec(loop_msg);
391 /* see if we are in the initialization phase and wait for the very first events */
392 if (init && (info.uptime - startup_time >= INIT_TIME_SEC)) {
394 timeout = EVENT_TIMEOUT_SEC;
395 dbg("initialization phase passed, set timeout to %i seconds", EVENT_TIMEOUT_SEC);
398 /* move event with expired timeout to the exec list */
400 msg_age = info.uptime - loop_msg->queue_time;
401 dbg("seq %llu is %li seconds old", loop_msg->seqnum, msg_age);
402 if (msg_age >= timeout) {
403 msg_move_exec(loop_msg);
412 /* set timeout for remaining queued events */
413 if (list_empty(&msg_list) == 0) {
414 struct itimerval itv = {{0, 0}, {timeout - msg_age, 0}};
415 dbg("next event expires in %li seconds", timeout - msg_age);
416 setitimer(ITIMER_REAL, &itv, NULL);
420 /* receive the udevsend message and do some sanity checks */
421 static struct hotplug_msg *get_udevsend_msg(void)
423 static struct udevsend_msg usend_msg;
424 struct hotplug_msg *msg;
429 struct cmsghdr *cmsg;
432 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
435 memset(&usend_msg, 0x00, sizeof(struct udevsend_msg));
436 iov.iov_base = &usend_msg;
437 iov.iov_len = sizeof(struct udevsend_msg);
439 memset(&smsg, 0x00, sizeof(struct msghdr));
442 smsg.msg_control = cred_msg;
443 smsg.msg_controllen = sizeof(cred_msg);
445 size = recvmsg(udevsendsock, &smsg, 0);
448 dbg("unable to receive udevsend message");
451 cmsg = CMSG_FIRSTHDR(&smsg);
452 cred = (struct ucred *) CMSG_DATA(cmsg);
454 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
455 dbg("no sender credentials received, message ignored");
459 if (cred->uid != 0) {
460 dbg("sender uid=%i, message ignored", cred->uid);
464 if (strncmp(usend_msg.magic, UDEV_MAGIC, sizeof(UDEV_MAGIC)) != 0 ) {
465 dbg("message magic '%s' doesn't match, ignore it", usend_msg.magic);
469 envbuf_size = size - offsetof(struct udevsend_msg, envbuf);
470 dbg("envbuf_size=%i", envbuf_size);
471 msg = malloc(sizeof(struct hotplug_msg) + envbuf_size);
475 memset(msg, 0x00, sizeof(struct hotplug_msg) + envbuf_size);
477 /* copy environment buffer and reconstruct envp */
478 memcpy(msg->envbuf, usend_msg.envbuf, envbuf_size);
480 for (i = 0; (bufpos < envbuf_size) && (i < HOTPLUG_NUM_ENVP-2); i++) {
484 key = &msg->envbuf[bufpos];
485 keylen = strlen(key);
487 bufpos += keylen + 1;
488 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
490 /* remember some keys for further processing */
491 if (strncmp(key, "ACTION=", 7) == 0)
492 msg->action = &key[7];
494 if (strncmp(key, "DEVPATH=", 8) == 0)
495 msg->devpath = &key[8];
497 if (strncmp(key, "SUBSYSTEM=", 10) == 0)
498 msg->subsystem = &key[10];
500 if (strncmp(key, "SEQNUM=", 7) == 0)
501 msg->seqnum = strtoull(&key[7], NULL, 10);
503 if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
504 msg->physdevpath = &key[12];
506 if (strncmp(key, "TIMEOUT=", 8) == 0)
507 msg->timeout = strtoull(&key[8], NULL, 10);
509 msg->envp[i++] = "UDEVD_EVENT=1";
515 static void asmlinkage sig_handler(int signum)
525 /* set flag, then write to pipe if needed */
530 /* set flag, then write to pipe if needed */
531 sigchilds_waiting = 1;
537 /* if pipe is empty, write to pipe to force select to return
538 * immediately when it gets called
541 rc = write(pipefds[1],&signum,sizeof(signum));
547 static void udev_done(int pid)
549 /* find msg associated with pid and delete it */
550 struct hotplug_msg *msg;
552 list_for_each_entry(msg, &running_list, node) {
553 if (msg->pid == pid) {
554 dbg("<== exec seq %llu came back", msg->seqnum);
555 run_queue_delete(msg);
557 /* we want to run the exec queue manager since there may
558 * be events waiting with the devpath of the one that
567 static void reap_sigchilds(void)
570 int pid = waitpid(-1, NULL, WNOHANG);
571 if ((pid == -1) || (pid == 0))
577 /* just read everything from the pipe and clear the flag,
578 * the flags was set in the signal handler
580 static void user_sighandler(void)
585 int rc = read(pipefds[0], &sig, sizeof(sig));
593 static int init_udevsend_socket(void)
595 struct sockaddr_un saddr;
597 const int feature_on = 1;
600 memset(&saddr, 0x00, sizeof(saddr));
601 saddr.sun_family = AF_LOCAL;
602 /* use abstract namespace for socket path */
603 strcpy(&saddr.sun_path[1], UDEVD_SOCK_PATH);
604 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
606 udevsendsock = socket(AF_LOCAL, SOCK_DGRAM, 0);
607 if (udevsendsock == -1) {
608 dbg("error getting socket, %s", strerror(errno));
612 /* the bind takes care of ensuring only one copy running */
613 retval = bind(udevsendsock, (struct sockaddr *) &saddr, addrlen);
615 dbg("bind failed, %s", strerror(errno));
620 /* enable receiving of the sender credentials */
621 setsockopt(udevsendsock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
626 int main(int argc, char *argv[], char *envp[])
632 struct sigaction act;
634 const char *udevd_expected_seqnum;
636 logging_init("udevd");
637 dbg("version %s", UDEV_VERSION);
640 dbg("need to be root, exit");
644 /* daemonize on request */
645 if (argc == 2 && strcmp(argv[1], "-d") == 0) {
651 dbg("damonized fork running");
654 dbg("fork of daemon failed");
662 /* become session leader */
664 dbg("our session is %d", sid);
666 /* make sure we don't lock any path */
668 umask(umask(077) | 022);
670 /*set a reasonable scheduling priority for the daemon */
671 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
673 /* Set fds to dev/null */
674 fd = open( "/dev/null", O_RDWR );
682 dbg("error opening /dev/null %s", strerror(errno));
684 /* setup signal handler pipe */
685 retval = pipe(pipefds);
687 dbg("error getting pipes: %s", strerror(errno));
691 retval = fcntl(pipefds[0], F_SETFL, O_NONBLOCK);
693 dbg("error fcntl on read pipe: %s", strerror(errno));
696 retval = fcntl(pipefds[0], F_SETFD, FD_CLOEXEC);
698 dbg("error fcntl on read pipe: %s", strerror(errno));
700 retval = fcntl(pipefds[1], F_SETFL, O_NONBLOCK);
702 dbg("error fcntl on write pipe: %s", strerror(errno));
705 retval = fcntl(pipefds[1], F_SETFD, FD_CLOEXEC);
707 dbg("error fcntl on write pipe: %s", strerror(errno));
709 /* set signal handlers */
710 memset(&act, 0x00, sizeof(struct sigaction));
711 act.sa_handler = (void (*) (int))sig_handler;
712 sigemptyset(&act.sa_mask);
713 act.sa_flags = SA_RESTART;
714 sigaction(SIGINT, &act, NULL);
715 sigaction(SIGTERM, &act, NULL);
716 sigaction(SIGALRM, &act, NULL);
717 sigaction(SIGCHLD, &act, NULL);
719 if (init_udevsend_socket() < 0) {
720 if (errno == EADDRINUSE)
721 dbg("another udevd running, exit");
723 dbg("error initialising udevsend socket: %s", strerror(errno));
728 /* possible override of udev binary, used for testing */
729 udev_bin = getenv("UDEV_BIN");
730 if (udev_bin != NULL)
731 dbg("udev binary is set to '%s'", udev_bin);
735 /* possible init of expected_seqnum value */
736 udevd_expected_seqnum = getenv("UDEVD_EXPECTED_SEQNUM");
737 if (udevd_expected_seqnum != NULL) {
738 expected_seqnum = strtoull(udevd_expected_seqnum, NULL, 10);
739 dbg("initialize expected_seqnum to %llu", expected_seqnum);
742 /* get current time to provide shorter timeout on startup */
744 startup_time = info.uptime;
747 FD_SET(udevsendsock, &readfds);
748 FD_SET(pipefds[0], &readfds);
749 maxsockplus = udevsendsock+1;
751 struct hotplug_msg *msg;
753 fd_set workreadfds = readfds;
754 retval = select(maxsockplus, &workreadfds, NULL, NULL, NULL);
758 dbg("error in select: %s", strerror(errno));
762 if (FD_ISSET(udevsendsock, &workreadfds)) {
763 msg = get_udevsend_msg();
765 msg_queue_insert(msg);
768 if (FD_ISSET(pipefds[0], &workreadfds))
771 if (sigchilds_waiting) {
772 sigchilds_waiting = 0;
782 /* clean up running_list before calling exec_queue_manager() */
783 if (sigchilds_waiting) {
784 sigchilds_waiting = 0;
789 exec_queue_manager();