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.
35 #include <sys/types.h>
36 #include <sys/socket.h>
38 #include <sys/sysinfo.h>
42 #include "udev_libc_wrapper.h"
44 #include "udev_version.h"
45 #include "udev_utils.h"
50 static int udevsendsock;
53 static int pipefds[2];
54 static long startup_time;
55 static unsigned long long expected_seqnum = 0;
56 static volatile int sigchilds_waiting;
57 static volatile int run_msg_q;
58 static volatile int sig_flag;
59 static int run_exec_q;
61 static LIST_HEAD(msg_list);
62 static LIST_HEAD(exec_list);
63 static LIST_HEAD(running_list);
65 static void exec_queue_manager(void);
66 static void msg_queue_manager(void);
67 static void user_sighandler(void);
68 static void reap_sigchilds(void);
72 void log_message (int level, const char *format, ...)
76 va_start(args, format);
77 vsyslog(level, format, args);
82 #define msg_dump(msg) \
83 dbg("msg_dump: sequence %llu, '%s', '%s', '%s'", \
84 msg->seqnum, msg->action, msg->devpath, msg->subsystem);
86 static void msg_dump_queue(void)
89 struct hotplug_msg *msg;
91 list_for_each_entry(msg, &msg_list, node)
92 dbg("sequence %llu in queue", msg->seqnum);
96 static void run_queue_delete(struct hotplug_msg *msg)
102 /* orders the message in the queue by sequence number */
103 static void msg_queue_insert(struct hotplug_msg *msg)
105 struct hotplug_msg *loop_msg;
108 if (msg->seqnum == 0) {
109 dbg("no SEQNUM, move straight to the exec queue");
110 list_add(&msg->node, &exec_list);
115 /* sort message by sequence number into list */
116 list_for_each_entry_reverse(loop_msg, &msg_list, node) {
117 if (loop_msg->seqnum < msg->seqnum)
120 if (loop_msg->seqnum == msg->seqnum) {
121 dbg("ignoring duplicate message seq %llu", msg->seqnum);
126 /* store timestamp of queuing */
128 msg->queue_time = info.uptime;
130 list_add(&msg->node, &loop_msg->node);
131 dbg("queued message seq %llu", msg->seqnum);
133 /* run msg queue manager */
139 /* forks event and removes event from run queue when finished */
140 static void udev_run(struct hotplug_msg *msg)
142 char *const argv[] = { "udev", msg->subsystem, NULL };
152 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
153 execve(udev_bin, argv, msg->envp);
154 dbg("exec of child failed");
158 dbg("fork of child failed");
159 run_queue_delete(msg);
162 /* get SIGCHLD in main loop */
163 dbg("==> exec seq %llu [%d] working at '%s'", msg->seqnum, pid, msg->devpath);
168 static int running_processes(void)
171 static char buf[4096];
176 f = open("/proc/stat", O_RDONLY);
180 len = read(f, buf, sizeof(buf));
188 pos = strstr(buf, "procs_running ");
192 if (sscanf(pos, "procs_running %u", &running) != 1)
198 /* return the number of process es in our session, count only until limit */
199 static int running_processes_in_session(pid_t session, int limit)
205 dir = opendir("/proc");
209 /* read process info from /proc */
210 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
216 pid_t ppid, pgrp, sess;
219 if (!isdigit(dent->d_name[0]))
222 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
223 procdir[sizeof(procdir)-1] = '\0';
225 f = open(procdir, O_RDONLY);
229 len = read(f, line, sizeof(line));
237 /* skip ugly program name */
238 pos = strrchr(line, ')') + 2;
242 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
245 /* count only processes in our session */
249 /* count only running, no sleeping processes */
254 if (limit > 0 && running >= limit)
262 static int compare_devpath(const char *running, const char *waiting)
266 for (i = 0; i < PATH_SIZE; i++) {
267 /* identical device event found */
268 if (running[i] == '\0' && waiting[i] == '\0')
271 /* parent device event found */
272 if (running[i] == '\0' && waiting[i] == '/')
275 /* child device event found */
276 if (running[i] == '/' && waiting[i] == '\0')
279 /* no matching event */
280 if (running[i] != waiting[i])
287 /* returns still running task for the same device, its parent or its physical device */
288 static struct hotplug_msg *running_with_devpath(struct hotplug_msg *msg)
290 struct hotplug_msg *loop_msg;
292 if (msg->devpath == NULL)
295 list_for_each_entry(loop_msg, &running_list, node) {
296 if (loop_msg->devpath == NULL)
299 /* return running parent/child device event */
300 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0)
303 /* return running physical device event */
304 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
305 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0)
312 /* exec queue management routine executes the events and serializes events in the same sequence */
313 static void exec_queue_manager(void)
315 struct hotplug_msg *loop_msg;
316 struct hotplug_msg *tmp_msg;
317 struct hotplug_msg *msg;
320 running = running_processes();
321 dbg("%d processes runnning on system", running);
323 running = THROTTLE_MAX_RUNNING_CHILDS;
325 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
326 /* check running processes in our session and possibly throttle */
327 if (running >= THROTTLE_MAX_RUNNING_CHILDS) {
328 running = running_processes_in_session(sid, THROTTLE_MAX_RUNNING_CHILDS+10);
329 dbg("%d processes running in session", running);
330 if (running >= THROTTLE_MAX_RUNNING_CHILDS) {
331 dbg("delay seq %llu, cause too many processes already running", loop_msg->seqnum);
336 msg = running_with_devpath(loop_msg);
338 /* move event to run list */
339 list_move_tail(&loop_msg->node, &running_list);
342 dbg("moved seq %llu to running list", loop_msg->seqnum);
344 dbg("delay seq %llu (%s), cause seq %llu (%s) is still running",
345 loop_msg->seqnum, loop_msg->devpath, msg->seqnum, msg->devpath);
350 static void msg_move_exec(struct hotplug_msg *msg)
352 list_move_tail(&msg->node, &exec_list);
354 expected_seqnum = msg->seqnum+1;
355 dbg("moved seq %llu to exec, next expected is %llu",
356 msg->seqnum, expected_seqnum);
359 /* msg queue management routine handles the timeouts and dispatches the events */
360 static void msg_queue_manager(void)
362 struct hotplug_msg *loop_msg;
363 struct hotplug_msg *tmp_msg;
366 static int timeout = EVENT_INIT_TIMEOUT_SEC;
369 dbg("msg queue manager, next expected is %llu", expected_seqnum);
371 list_for_each_entry_safe(loop_msg, tmp_msg, &msg_list, node) {
372 /* move event with expected sequence to the exec list */
373 if (loop_msg->seqnum == expected_seqnum) {
374 msg_move_exec(loop_msg);
378 /* see if we are in the initialization phase and wait for the very first events */
379 if (init && (info.uptime - startup_time >= INIT_TIME_SEC)) {
381 timeout = EVENT_TIMEOUT_SEC;
382 dbg("initialization phase passed, set timeout to %i seconds", EVENT_TIMEOUT_SEC);
385 /* move event with expired timeout to the exec list */
387 msg_age = info.uptime - loop_msg->queue_time;
388 dbg("seq %llu is %li seconds old", loop_msg->seqnum, msg_age);
389 if (msg_age >= timeout) {
390 msg_move_exec(loop_msg);
399 /* set timeout for remaining queued events */
400 if (list_empty(&msg_list) == 0) {
401 struct itimerval itv = {{0, 0}, {timeout - msg_age, 0}};
402 dbg("next event expires in %li seconds", timeout - msg_age);
403 setitimer(ITIMER_REAL, &itv, NULL);
407 /* receive the udevsend message and do some sanity checks */
408 static struct hotplug_msg *get_udevsend_msg(void)
410 static struct udevsend_msg usend_msg;
411 struct hotplug_msg *msg;
416 struct cmsghdr *cmsg;
419 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
422 memset(&usend_msg, 0x00, sizeof(struct udevsend_msg));
423 iov.iov_base = &usend_msg;
424 iov.iov_len = sizeof(struct udevsend_msg);
426 memset(&smsg, 0x00, sizeof(struct msghdr));
429 smsg.msg_control = cred_msg;
430 smsg.msg_controllen = sizeof(cred_msg);
432 size = recvmsg(udevsendsock, &smsg, 0);
435 dbg("unable to receive udevsend message");
438 cmsg = CMSG_FIRSTHDR(&smsg);
439 cred = (struct ucred *) CMSG_DATA(cmsg);
441 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
442 dbg("no sender credentials received, message ignored");
446 if (cred->uid != 0) {
447 dbg("sender uid=%i, message ignored", cred->uid);
451 if (strncmp(usend_msg.magic, UDEV_MAGIC, sizeof(UDEV_MAGIC)) != 0 ) {
452 dbg("message magic '%s' doesn't match, ignore it", usend_msg.magic);
456 envbuf_size = size - offsetof(struct udevsend_msg, envbuf);
457 dbg("envbuf_size=%i", envbuf_size);
458 msg = malloc(sizeof(struct hotplug_msg) + envbuf_size);
462 memset(msg, 0x00, sizeof(struct hotplug_msg) + envbuf_size);
464 /* copy environment buffer and reconstruct envp */
465 memcpy(msg->envbuf, usend_msg.envbuf, envbuf_size);
467 for (i = 0; (bufpos < envbuf_size) && (i < HOTPLUG_NUM_ENVP-2); i++) {
471 key = &msg->envbuf[bufpos];
472 keylen = strlen(key);
474 bufpos += keylen + 1;
475 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
477 /* remember some keys for further processing */
478 if (strncmp(key, "ACTION=", 7) == 0)
479 msg->action = &key[7];
481 if (strncmp(key, "DEVPATH=", 8) == 0)
482 msg->devpath = &key[8];
484 if (strncmp(key, "SUBSYSTEM=", 10) == 0)
485 msg->subsystem = &key[10];
487 if (strncmp(key, "SEQNUM=", 7) == 0)
488 msg->seqnum = strtoull(&key[7], NULL, 10);
490 if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
491 msg->physdevpath = &key[12];
493 msg->envp[i++] = "UDEVD_EVENT=1";
499 static void asmlinkage sig_handler(int signum)
509 /* set flag, then write to pipe if needed */
514 /* set flag, then write to pipe if needed */
515 sigchilds_waiting = 1;
521 /* if pipe is empty, write to pipe to force select to return
522 * immediately when it gets called
525 rc = write(pipefds[1],&signum,sizeof(signum));
531 static void udev_done(int pid)
533 /* find msg associated with pid and delete it */
534 struct hotplug_msg *msg;
536 list_for_each_entry(msg, &running_list, node) {
537 if (msg->pid == pid) {
538 dbg("<== exec seq %llu came back", msg->seqnum);
539 run_queue_delete(msg);
541 /* we want to run the exec queue manager since there may
542 * be events waiting with the devpath of the one that
551 static void reap_sigchilds(void)
554 int pid = waitpid(-1, NULL, WNOHANG);
555 if ((pid == -1) || (pid == 0))
561 /* just read everything from the pipe and clear the flag,
562 * the flags was set in the signal handler
564 static void user_sighandler(void)
569 int rc = read(pipefds[0], &sig, sizeof(sig));
577 static int init_udevsend_socket(void)
579 struct sockaddr_un saddr;
581 const int feature_on = 1;
584 memset(&saddr, 0x00, sizeof(saddr));
585 saddr.sun_family = AF_LOCAL;
586 /* use abstract namespace for socket path */
587 strcpy(&saddr.sun_path[1], UDEVD_SOCK_PATH);
588 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
590 udevsendsock = socket(AF_LOCAL, SOCK_DGRAM, 0);
591 if (udevsendsock == -1) {
592 dbg("error getting socket, %s", strerror(errno));
596 /* the bind takes care of ensuring only one copy running */
597 retval = bind(udevsendsock, (struct sockaddr *) &saddr, addrlen);
599 dbg("bind failed, %s", strerror(errno));
604 /* enable receiving of the sender credentials */
605 setsockopt(udevsendsock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
610 int main(int argc, char *argv[], char *envp[])
616 struct sigaction act;
618 const char *udevd_expected_seqnum;
620 logging_init("udevd");
621 dbg("version %s", UDEV_VERSION);
624 dbg("need to be root, exit");
628 /* daemonize on request */
629 if (argc == 2 && strcmp(argv[1], "-d") == 0) {
635 dbg("damonized fork running");
638 dbg("fork of daemon failed");
646 /* become session leader */
648 dbg("our session is %d", sid);
650 /* make sure we don't lock any path */
652 umask(umask(077) | 022);
654 /*set a reasonable scheduling priority for the daemon */
655 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
657 /* Set fds to dev/null */
658 fd = open( "/dev/null", O_RDWR );
666 dbg("error opening /dev/null %s", strerror(errno));
668 /* setup signal handler pipe */
669 retval = pipe(pipefds);
671 dbg("error getting pipes: %s", strerror(errno));
675 retval = fcntl(pipefds[0], F_SETFL, O_NONBLOCK);
677 dbg("error fcntl on read pipe: %s", strerror(errno));
680 retval = fcntl(pipefds[0], F_SETFD, FD_CLOEXEC);
682 dbg("error fcntl on read pipe: %s", strerror(errno));
684 retval = fcntl(pipefds[1], F_SETFL, O_NONBLOCK);
686 dbg("error fcntl on write pipe: %s", strerror(errno));
689 retval = fcntl(pipefds[1], F_SETFD, FD_CLOEXEC);
691 dbg("error fcntl on write pipe: %s", strerror(errno));
693 /* set signal handlers */
694 memset(&act, 0x00, sizeof(struct sigaction));
695 act.sa_handler = (void (*) (int))sig_handler;
696 sigemptyset(&act.sa_mask);
697 act.sa_flags = SA_RESTART;
698 sigaction(SIGINT, &act, NULL);
699 sigaction(SIGTERM, &act, NULL);
700 sigaction(SIGALRM, &act, NULL);
701 sigaction(SIGCHLD, &act, NULL);
703 if (init_udevsend_socket() < 0) {
704 if (errno == EADDRINUSE)
705 dbg("another udevd running, exit");
707 dbg("error initialising udevsend socket: %s", strerror(errno));
712 /* possible override of udev binary, used for testing */
713 udev_bin = getenv("UDEV_BIN");
714 if (udev_bin != NULL)
715 dbg("udev binary is set to '%s'", udev_bin);
719 /* possible init of expected_seqnum value */
720 udevd_expected_seqnum = getenv("UDEVD_EXPECTED_SEQNUM");
721 if (udevd_expected_seqnum != NULL) {
722 expected_seqnum = strtoull(udevd_expected_seqnum, NULL, 10);
723 dbg("initialize expected_seqnum to %llu", expected_seqnum);
726 /* get current time to provide shorter timeout on startup */
728 startup_time = info.uptime;
731 FD_SET(udevsendsock, &readfds);
732 FD_SET(pipefds[0], &readfds);
733 maxsockplus = udevsendsock+1;
735 struct hotplug_msg *msg;
737 fd_set workreadfds = readfds;
738 retval = select(maxsockplus, &workreadfds, NULL, NULL, NULL);
742 dbg("error in select: %s", strerror(errno));
746 if (FD_ISSET(udevsendsock, &workreadfds)) {
747 msg = get_udevsend_msg();
749 msg_queue_insert(msg);
752 if (FD_ISSET(pipefds[0], &workreadfds))
755 if (sigchilds_waiting) {
756 sigchilds_waiting = 0;
766 /* clean up running_list before calling exec_queue_manager() */
767 if (sigchilds_waiting) {
768 sigchilds_waiting = 0;
773 exec_queue_manager();