2 * udevd.c - hotplug event serializer
4 * Copyright (C) 2004 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>
43 #include "udev_version.h"
44 #include "udev_utils.h"
49 static int udevsendsock;
52 static int pipefds[2];
53 static long startup_time;
54 static unsigned long long expected_seqnum = 0;
55 static volatile int sigchilds_waiting;
56 static volatile int run_msg_q;
57 static volatile int sig_flag;
58 static int run_exec_q;
60 static LIST_HEAD(msg_list);
61 static LIST_HEAD(exec_list);
62 static LIST_HEAD(running_list);
64 static void exec_queue_manager(void);
65 static void msg_queue_manager(void);
66 static void user_sighandler(void);
67 static void reap_sigchilds(void);
71 void log_message (int level, const char *format, ...)
75 va_start(args, format);
76 vsyslog(level, format, args);
81 #define msg_dump(msg) \
82 dbg("msg_dump: sequence %llu, '%s', '%s', '%s'", \
83 msg->seqnum, msg->action, msg->devpath, msg->subsystem);
85 static void msg_dump_queue(void)
88 struct hotplug_msg *msg;
90 list_for_each_entry(msg, &msg_list, list)
91 dbg("sequence %llu in queue", msg->seqnum);
95 static void run_queue_delete(struct hotplug_msg *msg)
101 /* orders the message in the queue by sequence number */
102 static void msg_queue_insert(struct hotplug_msg *msg)
104 struct hotplug_msg *loop_msg;
107 if (msg->seqnum == 0) {
108 dbg("no SEQNUM, move straight to the exec queue");
109 list_add(&msg->list, &exec_list);
114 /* sort message by sequence number into list */
115 list_for_each_entry_reverse(loop_msg, &msg_list, list) {
116 if (loop_msg->seqnum < msg->seqnum)
119 if (loop_msg->seqnum == msg->seqnum) {
120 dbg("ignoring duplicate message seq %llu", msg->seqnum);
125 /* store timestamp of queuing */
127 msg->queue_time = info.uptime;
129 list_add(&msg->list, &loop_msg->list);
130 dbg("queued message seq %llu", msg->seqnum);
132 /* run msg queue manager */
138 /* forks event and removes event from run queue when finished */
139 static void udev_run(struct hotplug_msg *msg)
141 char *const argv[] = { "udev", msg->subsystem, NULL };
151 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
152 execve(udev_bin, argv, msg->envp);
153 dbg("exec of child failed");
157 dbg("fork of child failed");
158 run_queue_delete(msg);
161 /* get SIGCHLD in main loop */
162 dbg("==> exec seq %llu [%d] working at '%s'", msg->seqnum, pid, msg->devpath);
167 static int running_processes(void)
170 static char buf[4096];
175 f = open("/proc/stat", O_RDONLY);
179 len = read(f, buf, sizeof(buf));
187 pos = strstr(buf, "procs_running ");
191 if (sscanf(pos, "procs_running %u", &running) != 1)
197 /* return the number of process es in our session, count only until limit */
198 static int running_processes_in_session(pid_t session, int limit)
204 dir = opendir("/proc");
208 /* read process info from /proc */
209 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
215 pid_t ppid, pgrp, sess;
218 if (!isdigit(dent->d_name[0]))
221 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
222 procdir[sizeof(procdir)-1] = '\0';
224 f = open(procdir, O_RDONLY);
228 len = read(f, line, sizeof(line));
236 /* skip ugly program name */
237 pos = strrchr(line, ')') + 2;
241 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
244 /* count only processes in our session */
248 /* count only running, no sleeping processes */
253 if (limit > 0 && running >= limit)
261 static int compare_devpath(const char *running, const char *waiting)
265 for (i = 0; i < DEVPATH_SIZE; i++) {
266 /* identical device event found */
267 if (running[i] == '\0' && waiting[i] == '\0')
270 /* parent device event found */
271 if (running[i] == '\0' && waiting[i] == '/')
274 /* child device event found */
275 if (running[i] == '/' && waiting[i] == '\0')
278 /* no matching event */
279 if (running[i] != waiting[i])
286 /* returns still running task for the same device, its parent or its physical device */
287 static struct hotplug_msg *running_with_devpath(struct hotplug_msg *msg)
289 struct hotplug_msg *loop_msg;
291 if (msg->devpath == NULL)
294 list_for_each_entry(loop_msg, &running_list, list) {
295 if (loop_msg->devpath == NULL)
298 /* return running parent/child device event */
299 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0)
302 /* return running physical device event */
303 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
304 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0)
311 /* exec queue management routine executes the events and serializes events in the same sequence */
312 static void exec_queue_manager(void)
314 struct hotplug_msg *loop_msg;
315 struct hotplug_msg *tmp_msg;
316 struct hotplug_msg *msg;
319 running = running_processes();
320 dbg("%d processes runnning on system", running);
322 running = THROTTLE_MAX_RUNNING_CHILDS;
324 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, list) {
325 /* check running processes in our session and possibly throttle */
326 if (running >= THROTTLE_MAX_RUNNING_CHILDS) {
327 running = running_processes_in_session(sid, THROTTLE_MAX_RUNNING_CHILDS+10);
328 dbg("%d processes running in session", running);
329 if (running >= THROTTLE_MAX_RUNNING_CHILDS) {
330 dbg("delay seq %llu, cause too many processes already running", loop_msg->seqnum);
335 msg = running_with_devpath(loop_msg);
337 /* move event to run list */
338 list_move_tail(&loop_msg->list, &running_list);
341 dbg("moved seq %llu to running list", loop_msg->seqnum);
343 dbg("delay seq %llu (%s), cause seq %llu (%s) is still running",
344 loop_msg->seqnum, loop_msg->devpath, msg->seqnum, msg->devpath);
349 static void msg_move_exec(struct hotplug_msg *msg)
351 list_move_tail(&msg->list, &exec_list);
353 expected_seqnum = msg->seqnum+1;
354 dbg("moved seq %llu to exec, next expected is %llu",
355 msg->seqnum, expected_seqnum);
358 /* msg queue management routine handles the timeouts and dispatches the events */
359 static void msg_queue_manager(void)
361 struct hotplug_msg *loop_msg;
362 struct hotplug_msg *tmp_msg;
365 static int timeout = EVENT_INIT_TIMEOUT_SEC;
368 dbg("msg queue manager, next expected is %llu", expected_seqnum);
370 list_for_each_entry_safe(loop_msg, tmp_msg, &msg_list, list) {
371 /* move event with expected sequence to the exec list */
372 if (loop_msg->seqnum == expected_seqnum) {
373 msg_move_exec(loop_msg);
377 /* see if we are in the initialization phase and wait for the very first events */
378 if (init && (info.uptime - startup_time >= INIT_TIME_SEC)) {
380 timeout = EVENT_TIMEOUT_SEC;
381 dbg("initialization phase passed, set timeout to %i seconds", EVENT_TIMEOUT_SEC);
384 /* move event with expired timeout to the exec list */
386 msg_age = info.uptime - loop_msg->queue_time;
387 dbg("seq %llu is %li seconds old", loop_msg->seqnum, msg_age);
388 if (msg_age >= timeout) {
389 msg_move_exec(loop_msg);
398 /* set timeout for remaining queued events */
399 if (list_empty(&msg_list) == 0) {
400 struct itimerval itv = {{0, 0}, {timeout - msg_age, 0}};
401 dbg("next event expires in %li seconds", timeout - msg_age);
402 setitimer(ITIMER_REAL, &itv, NULL);
406 /* receive the udevsend message and do some sanity checks */
407 static struct hotplug_msg *get_udevsend_msg(void)
409 static struct udevsend_msg usend_msg;
410 struct hotplug_msg *msg;
415 struct cmsghdr *cmsg;
418 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
421 memset(&usend_msg, 0x00, sizeof(struct udevsend_msg));
422 iov.iov_base = &usend_msg;
423 iov.iov_len = sizeof(struct udevsend_msg);
425 memset(&smsg, 0x00, sizeof(struct msghdr));
428 smsg.msg_control = cred_msg;
429 smsg.msg_controllen = sizeof(cred_msg);
431 size = recvmsg(udevsendsock, &smsg, 0);
434 dbg("unable to receive udevsend message");
437 cmsg = CMSG_FIRSTHDR(&smsg);
438 cred = (struct ucred *) CMSG_DATA(cmsg);
440 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
441 dbg("no sender credentials received, message ignored");
445 if (cred->uid != 0) {
446 dbg("sender uid=%i, message ignored", cred->uid);
450 if (strncmp(usend_msg.magic, UDEV_MAGIC, sizeof(UDEV_MAGIC)) != 0 ) {
451 dbg("message magic '%s' doesn't match, ignore it", usend_msg.magic);
455 envbuf_size = size - offsetof(struct udevsend_msg, envbuf);
456 dbg("envbuf_size=%i", envbuf_size);
457 msg = malloc(sizeof(struct hotplug_msg) + envbuf_size);
461 memset(msg, 0x00, sizeof(struct hotplug_msg) + envbuf_size);
463 /* copy environment buffer and reconstruct envp */
464 memcpy(msg->envbuf, usend_msg.envbuf, envbuf_size);
466 for (i = 0; (bufpos < envbuf_size) && (i < HOTPLUG_NUM_ENVP-2); i++) {
470 key = &msg->envbuf[bufpos];
471 keylen = strlen(key);
473 bufpos += keylen + 1;
474 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
476 /* remember some keys for further processing */
477 if (strncmp(key, "ACTION=", 7) == 0)
478 msg->action = &key[7];
480 if (strncmp(key, "DEVPATH=", 8) == 0)
481 msg->devpath = &key[8];
483 if (strncmp(key, "SUBSYSTEM=", 10) == 0)
484 msg->subsystem = &key[10];
486 if (strncmp(key, "SEQNUM=", 7) == 0)
487 msg->seqnum = strtoull(&key[7], NULL, 10);
489 if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
490 msg->physdevpath = &key[12];
492 msg->envp[i++] = "UDEVD_EVENT=1";
498 static void asmlinkage sig_handler(int signum)
508 /* set flag, then write to pipe if needed */
513 /* set flag, then write to pipe if needed */
514 sigchilds_waiting = 1;
520 /* if pipe is empty, write to pipe to force select to return
521 * immediately when it gets called
524 rc = write(pipefds[1],&signum,sizeof(signum));
530 static void udev_done(int pid)
532 /* find msg associated with pid and delete it */
533 struct hotplug_msg *msg;
535 list_for_each_entry(msg, &running_list, list) {
536 if (msg->pid == pid) {
537 dbg("<== exec seq %llu came back", msg->seqnum);
538 run_queue_delete(msg);
540 /* we want to run the exec queue manager since there may
541 * be events waiting with the devpath of the one that
550 static void reap_sigchilds(void)
553 int pid = waitpid(-1, NULL, WNOHANG);
554 if ((pid == -1) || (pid == 0))
560 /* just read everything from the pipe and clear the flag,
561 * the flags was set in the signal handler
563 static void user_sighandler(void)
568 int rc = read(pipefds[0], &sig, sizeof(sig));
576 static int init_udevsend_socket(void)
578 struct sockaddr_un saddr;
580 const int feature_on = 1;
583 memset(&saddr, 0x00, sizeof(saddr));
584 saddr.sun_family = AF_LOCAL;
585 /* use abstract namespace for socket path */
586 strcpy(&saddr.sun_path[1], UDEVD_SOCK_PATH);
587 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
589 udevsendsock = socket(AF_LOCAL, SOCK_DGRAM, 0);
590 if (udevsendsock == -1) {
591 dbg("error getting socket, %s", strerror(errno));
595 /* the bind takes care of ensuring only one copy running */
596 retval = bind(udevsendsock, (struct sockaddr *) &saddr, addrlen);
598 dbg("bind failed, %s", strerror(errno));
603 /* enable receiving of the sender credentials */
604 setsockopt(udevsendsock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
609 int main(int argc, char *argv[], char *envp[])
615 struct sigaction act;
617 const char *udevd_expected_seqnum;
619 logging_init("udevd");
620 dbg("version %s", UDEV_VERSION);
623 dbg("need to be root, exit");
627 /* daemonize on request */
628 if (argc == 2 && strcmp(argv[1], "-d") == 0) {
634 dbg("damonized fork running");
637 dbg("fork of daemon failed");
645 /* become session leader */
647 dbg("our session is %d", sid);
649 /* make sure we don't lock any path */
651 umask(umask(077) | 022);
653 /*set a reasonable scheduling priority for the daemon */
654 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
656 /* Set fds to dev/null */
657 fd = open( "/dev/null", O_RDWR );
665 dbg("error opening /dev/null %s", strerror(errno));
667 /* setup signal handler pipe */
668 retval = pipe(pipefds);
670 dbg("error getting pipes: %s", strerror(errno));
674 retval = fcntl(pipefds[0], F_SETFL, O_NONBLOCK);
676 dbg("error fcntl on read pipe: %s", strerror(errno));
679 retval = fcntl(pipefds[0], F_SETFD, FD_CLOEXEC);
681 dbg("error fcntl on read pipe: %s", strerror(errno));
683 retval = fcntl(pipefds[1], F_SETFL, O_NONBLOCK);
685 dbg("error fcntl on write pipe: %s", strerror(errno));
688 retval = fcntl(pipefds[1], F_SETFD, FD_CLOEXEC);
690 dbg("error fcntl on write pipe: %s", strerror(errno));
692 /* set signal handlers */
693 act.sa_handler = (void (*) (int))sig_handler;
694 sigemptyset(&act.sa_mask);
695 act.sa_flags = SA_RESTART;
696 sigaction(SIGINT, &act, NULL);
697 sigaction(SIGTERM, &act, NULL);
698 sigaction(SIGALRM, &act, NULL);
699 sigaction(SIGCHLD, &act, NULL);
701 if (init_udevsend_socket() < 0) {
702 if (errno == EADDRINUSE)
703 dbg("another udevd running, exit");
705 dbg("error initialising udevsend socket: %s", strerror(errno));
710 /* possible override of udev binary, used for testing */
711 udev_bin = getenv("UDEV_BIN");
712 if (udev_bin != NULL)
713 dbg("udev binary is set to '%s'", udev_bin);
717 /* possible init of expected_seqnum value */
718 udevd_expected_seqnum = getenv("UDEVD_EXPECTED_SEQNUM");
719 if (udevd_expected_seqnum != NULL) {
720 expected_seqnum = strtoull(udevd_expected_seqnum, NULL, 10);
721 dbg("initialize expected_seqnum to %llu", expected_seqnum);
724 /* get current time to provide shorter timeout on startup */
726 startup_time = info.uptime;
729 FD_SET(udevsendsock, &readfds);
730 FD_SET(pipefds[0], &readfds);
731 maxsockplus = udevsendsock+1;
733 struct hotplug_msg *msg;
735 fd_set workreadfds = readfds;
736 retval = select(maxsockplus, &workreadfds, NULL, NULL, NULL);
740 dbg("error in select: %s", strerror(errno));
744 if (FD_ISSET(udevsendsock, &workreadfds)) {
745 msg = get_udevsend_msg();
747 msg_queue_insert(msg);
750 if (FD_ISSET(pipefds[0], &workreadfds))
753 if (sigchilds_waiting) {
754 sigchilds_waiting = 0;
764 /* clean up running_list before calling exec_queue_manager() */
765 if (sigchilds_waiting) {
766 sigchilds_waiting = 0;
771 exec_queue_manager();