2 * Copyright (C) 2004-2006 Kay Sievers <kay.sievers@vrfy.org>
3 * Copyright (C) 2004 Chris Friesen <chris_friesen@sympatico.ca>
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation version 2 of the License.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
33 #include <sys/select.h>
35 #include <sys/types.h>
36 #include <sys/socket.h>
39 #include <sys/ioctl.h>
40 #include <linux/types.h>
41 #include <linux/netlink.h>
44 #include "udev_rules.h"
46 #include "udev_selinux.h"
48 static int debug_trace;
51 static struct udev_rules rules;
52 static int udevd_sock = -1;
53 static int uevent_netlink_sock = -1;
54 static int inotify_fd = -1;
57 static int signal_pipe[2] = {-1, -1};
58 static volatile int sigchilds_waiting;
59 static volatile int udev_exit;
60 static volatile int reload_config;
61 static int run_exec_q;
62 static int stop_exec_q;
63 static int max_childs;
64 static int max_childs_running;
65 static char udev_log[32];
67 static LIST_HEAD(exec_list);
68 static LIST_HEAD(running_list);
72 void log_message(int priority, const char *format, ...)
76 if (priority > udev_log_priority)
79 va_start(args, format);
80 vsyslog(priority, format, args);
84 va_start(args, format);
85 vprintf(format, args);
93 static void asmlinkage udev_event_sig_handler(int signum)
95 if (signum == SIGALRM)
99 static int udev_event_process(struct udevd_uevent_msg *msg)
101 struct sigaction act;
102 struct udevice *udev;
106 /* set signal handlers */
107 memset(&act, 0x00, sizeof(act));
108 act.sa_handler = (void (*)(int)) udev_event_sig_handler;
109 sigemptyset (&act.sa_mask);
111 sigaction(SIGALRM, &act, NULL);
113 /* reset to default */
114 act.sa_handler = SIG_DFL;
115 sigaction(SIGINT, &act, NULL);
116 sigaction(SIGTERM, &act, NULL);
117 sigaction(SIGCHLD, &act, NULL);
118 sigaction(SIGHUP, &act, NULL);
120 /* trigger timeout to prevent hanging processes */
121 alarm(UDEV_ALARM_TIMEOUT);
123 /* reconstruct event environment from message */
124 for (i = 0; msg->envp[i]; i++)
125 putenv(msg->envp[i]);
127 udev = udev_device_init(NULL);
130 strlcpy(udev->action, msg->action, sizeof(udev->action));
131 sysfs_device_set_values(udev->dev, msg->devpath, msg->subsystem, msg->driver);
132 udev->devt = msg->devt;
134 retval = udev_device_event(&rules, udev);
136 /* run programs collected by RUN-key*/
137 if (retval == 0 && !udev->ignore_device && udev_run) {
138 struct name_entry *name_loop;
140 dbg("executing run list");
141 list_for_each_entry(name_loop, &udev->run_list, node) {
142 if (strncmp(name_loop->name, "socket:", strlen("socket:")) == 0)
143 pass_env_to_socket(&name_loop->name[strlen("socket:")], udev->dev->devpath, udev->action);
145 char program[PATH_SIZE];
147 strlcpy(program, name_loop->name, sizeof(program));
148 udev_rules_apply_format(udev, program, sizeof(program));
149 if (run_program(program, udev->dev->subsystem, NULL, 0, NULL,
150 (udev_log_priority >= LOG_INFO)))
156 udev_device_cleanup(udev);
166 static void export_event_state(struct udevd_uevent_msg *msg, enum event_state state)
168 char filename[PATH_SIZE];
169 char filename_failed[PATH_SIZE];
171 struct udevd_uevent_msg *loop_msg;
174 /* add location of queue files */
175 strlcpy(filename, udev_root, sizeof(filename));
176 strlcat(filename, "/", sizeof(filename));
177 start = strlcat(filename, EVENT_QUEUE_DIR"/", sizeof(filename));
178 strlcat(filename, msg->devpath, sizeof(filename));
179 path_encode(&filename[start], sizeof(filename) - start);
181 /* add location of failed files */
182 strlcpy(filename_failed, udev_root, sizeof(filename_failed));
183 strlcat(filename_failed, "/", sizeof(filename_failed));
184 start = strlcat(filename_failed, EVENT_FAILED_DIR"/", sizeof(filename_failed));
185 strlcat(filename_failed, msg->devpath, sizeof(filename_failed));
186 path_encode(&filename_failed[start], sizeof(filename) - start);
190 unlink(filename_failed);
191 delete_path(filename_failed);
192 create_path(filename);
193 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
199 unlink(filename_failed);
200 delete_path(filename_failed);
202 /* don't remove, if events for the same path are still pending */
203 list_for_each_entry(loop_msg, &running_list, node)
204 if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
207 list_for_each_entry(loop_msg, &exec_list, node)
208 if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
211 /* move failed events to the failed directory */
212 if (state == EVENT_FAILED) {
213 create_path(filename_failed);
214 rename(filename, filename_failed);
219 /* clean up the queue directory */
220 delete_path(filename);
226 static void msg_queue_delete(struct udevd_uevent_msg *msg)
228 list_del(&msg->node);
230 /* mark as failed, if add event returns non-zero */
231 if (msg->exitstatus && strcmp(msg->action, "add") == 0)
232 export_event_state(msg, EVENT_FAILED);
234 export_event_state(msg, EVENT_FINISHED);
239 static void udev_event_run(struct udevd_uevent_msg *msg)
248 close(uevent_netlink_sock);
252 close(signal_pipe[READ_END]);
253 close(signal_pipe[WRITE_END]);
256 logging_init("udevd-event");
257 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
259 retval = udev_event_process(msg);
260 info("seq %llu finished", msg->seqnum);
267 err("fork of child failed: %s", strerror(errno));
268 msg_queue_delete(msg);
271 /* get SIGCHLD in main loop */
272 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
273 msg->seqnum, pid, msg->action, msg->subsystem, time(NULL) - msg->queue_time);
278 static void msg_queue_insert(struct udevd_uevent_msg *msg)
280 char filename[PATH_SIZE];
283 msg->queue_time = time(NULL);
285 strlcpy(filename, udev_root, sizeof(filename));
286 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
287 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
292 len = sprintf(str, "%llu\n", msg->seqnum);
297 export_event_state(msg, EVENT_QUEUED);
299 /* run one event after the other in debug mode */
301 list_add_tail(&msg->node, &running_list);
303 waitpid(msg->pid, NULL, 0);
304 msg_queue_delete(msg);
308 /* run all events with a timeout set immediately */
309 if (msg->timeout != 0) {
310 list_add_tail(&msg->node, &running_list);
315 list_add_tail(&msg->node, &exec_list);
319 static int mem_size_mb(void)
323 long int memsize = -1;
325 f = fopen("/proc/meminfo", "r");
329 while (fgets(buf, sizeof(buf), f) != NULL) {
332 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
333 memsize = value / 1024;
342 static int cpu_count(void)
348 f = fopen("/proc/stat", "r");
352 while (fgets(buf, sizeof(buf), f) != NULL) {
353 if (strncmp(buf, "cpu", 3) == 0 && isdigit(buf[3]))
363 static int running_processes(void)
369 f = fopen("/proc/stat", "r");
373 while (fgets(buf, sizeof(buf), f) != NULL) {
376 if (sscanf(buf, "procs_running %u", &value) == 1) {
386 /* return the number of process es in our session, count only until limit */
387 static int running_processes_in_session(pid_t session, int limit)
393 dir = opendir("/proc");
397 /* read process info from /proc */
398 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
404 pid_t ppid, pgrp, sess;
407 if (!isdigit(dent->d_name[0]))
410 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
411 procdir[sizeof(procdir)-1] = '\0';
413 f = open(procdir, O_RDONLY);
417 len = read(f, line, sizeof(line)-1);
425 /* skip ugly program name */
426 pos = strrchr(line, ')') + 2;
430 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
433 /* count only processes in our session */
437 /* count only running, no sleeping processes */
442 if (limit > 0 && running >= limit)
450 static int compare_devpath(const char *running, const char *waiting)
454 for (i = 0; i < PATH_SIZE; i++) {
455 /* identical device event found */
456 if (running[i] == '\0' && waiting[i] == '\0')
459 /* parent device event found */
460 if (running[i] == '\0' && waiting[i] == '/')
463 /* child device event found */
464 if (running[i] == '/' && waiting[i] == '\0')
467 /* no matching event */
468 if (running[i] != waiting[i])
475 /* lookup event for identical, parent, child, or physical device */
476 static int devpath_busy(struct udevd_uevent_msg *msg, int limit)
478 struct udevd_uevent_msg *loop_msg;
479 int childs_count = 0;
481 /* check exec-queue which may still contain delayed events we depend on */
482 list_for_each_entry(loop_msg, &exec_list, node) {
483 /* skip ourself and all later events */
484 if (loop_msg->seqnum >= msg->seqnum)
487 /* check identical, parent, or child device event */
488 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
489 dbg("%llu, device event still pending %llu (%s)",
490 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
494 /* check physical device event (special case of parent) */
495 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
496 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
497 dbg("%llu, physical device event still pending %llu (%s)",
498 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
503 /* check runing-queue for still running events */
504 list_for_each_entry(loop_msg, &running_list, node) {
505 if (limit && childs_count++ > limit) {
506 dbg("%llu, maximum number (%i) of childs reached", msg->seqnum, childs_count);
510 /* check identical, parent, or child device event */
511 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
512 dbg("%llu, device event still running %llu (%s)",
513 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
517 /* check physical device event (special case of parent) */
518 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
519 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
520 dbg("%llu, physical device event still running %llu (%s)",
521 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
528 /* serializes events for the identical and parent and child devices */
529 static void msg_queue_manager(void)
531 struct udevd_uevent_msg *loop_msg;
532 struct udevd_uevent_msg *tmp_msg;
535 if (list_empty(&exec_list))
538 running = running_processes();
539 dbg("%d processes runnning on system", running);
541 running = max_childs_running;
543 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
544 /* check running processes in our session and possibly throttle */
545 if (running >= max_childs_running) {
546 running = running_processes_in_session(sid, max_childs_running+10);
547 dbg("at least %d processes running in session", running);
548 if (running >= max_childs_running) {
549 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
554 /* serialize and wait for parent or child events */
555 if (devpath_busy(loop_msg, max_childs) != 0) {
556 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
560 /* move event to run list */
561 list_move_tail(&loop_msg->node, &running_list);
562 udev_event_run(loop_msg);
564 dbg("moved seq %llu to running list", loop_msg->seqnum);
568 static struct udevd_uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
572 struct udevd_uevent_msg *msg;
573 char *physdevdriver_key = NULL;
577 msg = malloc(sizeof(struct udevd_uevent_msg) + buf_size);
580 memset(msg, 0x00, sizeof(struct udevd_uevent_msg) + buf_size);
582 /* copy environment buffer and reconstruct envp */
583 memcpy(msg->envbuf, buf, buf_size);
585 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
589 key = &msg->envbuf[bufpos];
590 keylen = strlen(key);
592 bufpos += keylen + 1;
593 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
595 /* remember some keys for further processing */
596 if (strncmp(key, "ACTION=", 7) == 0)
597 msg->action = &key[7];
598 else if (strncmp(key, "DEVPATH=", 8) == 0)
599 msg->devpath = &key[8];
600 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
601 msg->subsystem = &key[10];
602 else if (strncmp(key, "DRIVER=", 7) == 0)
603 msg->driver = &key[7];
604 else if (strncmp(key, "SEQNUM=", 7) == 0)
605 msg->seqnum = strtoull(&key[7], NULL, 10);
606 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
607 msg->physdevpath = &key[12];
608 else if (strncmp(key, "PHYSDEVDRIVER=", 14) == 0)
609 physdevdriver_key = key;
610 else if (strncmp(key, "MAJOR=", 6) == 0)
611 maj = strtoull(&key[6], NULL, 10);
612 else if (strncmp(key, "MINOR=", 6) == 0)
613 min = strtoull(&key[6], NULL, 10);
614 else if (strncmp(key, "TIMEOUT=", 8) == 0)
615 msg->timeout = strtoull(&key[8], NULL, 10);
617 msg->devt = makedev(maj, min);
618 msg->envp[i++] = "UDEVD_EVENT=1";
620 if (msg->driver == NULL && msg->physdevpath == NULL && physdevdriver_key != NULL) {
621 /* for older kernels DRIVER is empty for a bus device, export PHYSDEVDRIVER as DRIVER */
622 msg->envp[i++] = &physdevdriver_key[7];
623 msg->driver = &physdevdriver_key[14];
628 if (msg->devpath == NULL || msg->action == NULL) {
629 info("DEVPATH or ACTION missing, ignore message");
636 /* receive the udevd message from userspace */
637 static void get_ctrl_msg(void)
639 struct udevd_ctrl_msg ctrl_msg;
642 struct cmsghdr *cmsg;
645 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
649 memset(&ctrl_msg, 0x00, sizeof(struct udevd_ctrl_msg));
650 iov.iov_base = &ctrl_msg;
651 iov.iov_len = sizeof(struct udevd_ctrl_msg);
653 memset(&smsg, 0x00, sizeof(struct msghdr));
656 smsg.msg_control = cred_msg;
657 smsg.msg_controllen = sizeof(cred_msg);
659 size = recvmsg(udevd_sock, &smsg, 0);
662 err("unable to receive user udevd message: %s", strerror(errno));
665 cmsg = CMSG_FIRSTHDR(&smsg);
666 cred = (struct ucred *) CMSG_DATA(cmsg);
668 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
669 err("no sender credentials received, message ignored");
673 if (cred->uid != 0) {
674 err("sender uid=%i, message ignored", cred->uid);
678 if (strncmp(ctrl_msg.magic, UDEVD_CTRL_MAGIC, sizeof(UDEVD_CTRL_MAGIC)) != 0 ) {
679 err("message magic '%s' doesn't match, ignore it", ctrl_msg.magic);
683 switch (ctrl_msg.type) {
685 pos = strchr(ctrl_msg.buf, '=');
687 err("wrong key format '%s'", ctrl_msg.buf);
691 if (pos[1] == '\0') {
692 info("udevd message (ENV) received, unset '%s'", ctrl_msg.buf);
693 unsetenv(ctrl_msg.buf);
695 info("udevd message (ENV) received, set '%s=%s'", ctrl_msg.buf, &pos[1]);
696 setenv(ctrl_msg.buf, &pos[1], 1);
699 case UDEVD_CTRL_STOP_EXEC_QUEUE:
700 info("udevd message (STOP_EXEC_QUEUE) received");
703 case UDEVD_CTRL_START_EXEC_QUEUE:
704 info("udevd message (START_EXEC_QUEUE) received");
708 case UDEVD_CTRL_SET_LOG_LEVEL:
709 intval = (int *) ctrl_msg.buf;
710 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
711 udev_log_priority = *intval;
712 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
715 case UDEVD_CTRL_SET_MAX_CHILDS:
716 intval = (int *) ctrl_msg.buf;
717 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
718 max_childs = *intval;
720 case UDEVD_CTRL_SET_MAX_CHILDS_RUNNING:
721 intval = (int *) ctrl_msg.buf;
722 info("udevd message (UDEVD_SET_MAX_CHILDS_RUNNING) received, max_childs=%i", *intval);
723 max_childs_running = *intval;
725 case UDEVD_CTRL_RELOAD_RULES:
726 info("udevd message (RELOAD_RULES) received");
730 err("unknown control message type");
734 /* receive the kernel user event message and do some sanity checks */
735 static struct udevd_uevent_msg *get_netlink_msg(void)
737 struct udevd_uevent_msg *msg;
740 static char buffer[UEVENT_BUFFER_SIZE+512];
743 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
746 err("unable to receive kernel netlink message: %s", strerror(errno));
750 if ((size_t)size > sizeof(buffer)-1)
751 size = sizeof(buffer)-1;
753 dbg("uevent_size=%zi", size);
755 /* start of event payload */
756 bufpos = strlen(buffer)+1;
757 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
761 /* validate message */
762 pos = strchr(buffer, '@');
764 err("invalid uevent '%s'", buffer);
770 if (msg->action == NULL) {
771 info("no ACTION in payload found, skip event '%s'", buffer);
776 if (strcmp(msg->action, buffer) != 0) {
777 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
785 static void asmlinkage sig_handler(int signum)
793 /* set flag, then write to pipe if needed */
794 sigchilds_waiting = 1;
801 /* write to pipe, which will wakeup select() in our mainloop */
802 write(signal_pipe[WRITE_END], "", 1);
805 static void udev_done(int pid, int exitstatus)
807 /* find msg associated with pid and delete it */
808 struct udevd_uevent_msg *msg;
810 list_for_each_entry(msg, &running_list, node) {
811 if (msg->pid == pid) {
812 info("seq %llu, pid [%d] exit with %i, %ld seconds old", msg->seqnum, msg->pid,
813 exitstatus, time(NULL) - msg->queue_time);
814 msg->exitstatus = exitstatus;
815 msg_queue_delete(msg);
817 /* there may be events waiting with the same devpath */
824 static void reap_sigchilds(void)
830 pid = waitpid(-1, &status, WNOHANG);
833 if (WIFEXITED(status))
834 status = WEXITSTATUS(status);
835 else if (WIFSIGNALED(status))
836 status = WTERMSIG(status) + 128;
839 udev_done(pid, status);
843 static int init_udevd_socket(void)
845 struct sockaddr_un saddr;
847 const int feature_on = 1;
850 memset(&saddr, 0x00, sizeof(saddr));
851 saddr.sun_family = AF_LOCAL;
852 /* use abstract namespace for socket path */
853 strcpy(&saddr.sun_path[1], UDEVD_CTRL_SOCK_PATH);
854 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
856 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
857 if (udevd_sock == -1) {
858 err("error getting socket: %s", strerror(errno));
862 /* the bind takes care of ensuring only one copy running */
863 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
865 err("bind failed: %s", strerror(errno));
871 /* enable receiving of the sender credentials */
872 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
877 static int init_uevent_netlink_sock(void)
879 struct sockaddr_nl snl;
880 const int buffersize = 16 * 1024 * 1024;
883 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
884 snl.nl_family = AF_NETLINK;
885 snl.nl_pid = getpid();
888 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
889 if (uevent_netlink_sock == -1) {
890 err("error getting socket: %s", strerror(errno));
894 /* set receive buffersize */
895 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
897 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
899 err("bind failed: %s", strerror(errno));
900 close(uevent_netlink_sock);
901 uevent_netlink_sock = -1;
907 static void export_initial_seqnum(void)
909 char filename[PATH_SIZE];
914 strlcpy(filename, sysfs_path, sizeof(filename));
915 strlcat(filename, "/kernel/uevent_seqnum", sizeof(filename));
916 fd = open(filename, O_RDONLY);
918 len = read(fd, seqnum, sizeof(seqnum)-1);
922 strcpy(seqnum, "0\n");
925 strlcpy(filename, udev_root, sizeof(filename));
926 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
927 create_path(filename);
928 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
930 write(fd, seqnum, len);
935 int main(int argc, char *argv[], char *envp[])
939 struct sigaction act;
944 static const struct option options[] = {
945 { "daemon", 0, NULL, 'd' },
946 { "debug-trace", 0, NULL, 't' },
947 { "verbose", 0, NULL, 'v' },
948 { "help", 0, NULL, 'h' },
949 { "version", 0, NULL, 'V' },
955 logging_init("udevd");
958 dbg("version %s", UDEV_VERSION);
960 /* parse commandline options */
962 option = getopt_long(argc, argv, "dtvhV", options, NULL);
975 if (udev_log_priority < LOG_INFO)
976 udev_log_priority = LOG_INFO;
979 printf("Usage: udevd [--help] [--daemon] [--debug-trace] [--verbose] [--version]\n");
982 printf("%s\n", UDEV_VERSION);
990 fprintf(stderr, "root privileges required\n");
991 err("root privileges required");
995 /* make sure std{in,out,err} fd's are in a sane state */
996 fd = open("/dev/null", O_RDWR);
998 fprintf(stderr, "cannot open /dev/null\n");
999 err("cannot open /dev/null");
1001 if (fd > STDIN_FILENO)
1002 dup2(fd, STDIN_FILENO);
1003 if (write(STDOUT_FILENO, 0, 0) < 0)
1004 dup2(fd, STDOUT_FILENO);
1005 if (write(STDERR_FILENO, 0, 0) < 0)
1006 dup2(fd, STDERR_FILENO);
1008 /* init sockets to receive events */
1009 if (init_udevd_socket() < 0) {
1010 if (errno == EADDRINUSE) {
1011 fprintf(stderr, "another udev daemon already running\n");
1012 err("another udev daemon already running");
1015 fprintf(stderr, "error initializing udevd socket\n");
1016 err("error initializing udevd socket");
1022 if (init_uevent_netlink_sock() < 0) {
1023 fprintf(stderr, "error initializing netlink socket\n");
1024 err("error initializing netlink socket");
1029 /* setup signal handler pipe */
1030 retval = pipe(signal_pipe);
1032 err("error getting pipes: %s", strerror(errno));
1036 retval = fcntl(signal_pipe[READ_END], F_GETFL, 0);
1038 err("error fcntl on read pipe: %s", strerror(errno));
1041 retval = fcntl(signal_pipe[READ_END], F_SETFL, retval | O_NONBLOCK);
1043 err("error fcntl on read pipe: %s", strerror(errno));
1047 retval = fcntl(signal_pipe[WRITE_END], F_GETFL, 0);
1049 err("error fcntl on write pipe: %s", strerror(errno));
1052 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, retval | O_NONBLOCK);
1054 err("error fcntl on write pipe: %s", strerror(errno));
1058 /* parse the rules and keep them in memory */
1060 udev_rules_init(&rules, 1);
1062 export_initial_seqnum();
1070 dbg("daemonized fork running");
1073 err("fork of daemon failed: %s", strerror(errno));
1077 dbg("child [%u] running, parent exits", pid);
1083 /* redirect std{out,err} fd's */
1085 dup2(fd, STDOUT_FILENO);
1086 dup2(fd, STDERR_FILENO);
1087 if (fd > STDERR_FILENO)
1090 /* set scheduling priority for the daemon */
1091 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
1096 /* become session leader */
1098 dbg("our session is %d", sid);
1100 /* OOM_DISABLE == -17 */
1101 fd = open("/proc/self/oom_adj", O_RDWR);
1103 err("error disabling OOM: %s", strerror(errno));
1105 write(fd, "-17", 3);
1109 /* set signal handlers */
1110 memset(&act, 0x00, sizeof(struct sigaction));
1111 act.sa_handler = (void (*)(int)) sig_handler;
1112 sigemptyset(&act.sa_mask);
1113 act.sa_flags = SA_RESTART;
1114 sigaction(SIGINT, &act, NULL);
1115 sigaction(SIGTERM, &act, NULL);
1116 sigaction(SIGCHLD, &act, NULL);
1117 sigaction(SIGHUP, &act, NULL);
1119 /* watch rules directory */
1120 inotify_fd = inotify_init();
1121 if (inotify_fd >= 0)
1122 inotify_add_watch(inotify_fd, udev_rules_dir, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1123 else if (errno == ENOSYS)
1124 err("the kernel does not support inotify, udevd can't monitor configuration file changes");
1126 err("inotify_init failed: %s", strerror(errno));
1128 /* maximum limit of forked childs */
1129 value = getenv("UDEVD_MAX_CHILDS");
1131 max_childs = strtoul(value, NULL, 10);
1133 int memsize = mem_size_mb();
1135 max_childs = 128 + (memsize / 4);
1137 max_childs = UDEVD_MAX_CHILDS;
1139 info("initialize max_childs to %u", max_childs);
1141 /* start to throttle forking if maximum number of _running_ childs is reached */
1142 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
1144 max_childs_running = strtoull(value, NULL, 10);
1146 int cpus = cpu_count();
1148 max_childs_running = 8 + (8 * cpus);
1150 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
1152 info("initialize max_childs_running to %u", max_childs_running);
1154 /* clear environment for forked event processes */
1157 /* export log_priority , as called programs may want to follow that setting */
1158 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
1164 maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
1165 maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
1166 maxfd = UDEV_MAX(maxfd, inotify_fd);
1168 while (!udev_exit) {
1169 struct udevd_uevent_msg *msg;
1173 FD_SET(signal_pipe[READ_END], &readfds);
1174 FD_SET(udevd_sock, &readfds);
1175 FD_SET(uevent_netlink_sock, &readfds);
1176 if (inotify_fd >= 0)
1177 FD_SET(inotify_fd, &readfds);
1179 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
1182 err("error in select: %s", strerror(errno));
1186 /* get control message */
1187 if (FD_ISSET(udevd_sock, &readfds))
1190 /* get netlink message */
1191 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
1192 msg = get_netlink_msg();
1194 msg_queue_insert(msg);
1197 /* received a signal, clear our notification pipe */
1198 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
1201 read(signal_pipe[READ_END], &buf, sizeof(buf));
1204 /* rules directory inotify watch */
1205 if ((inotify_fd >= 0) && FD_ISSET(inotify_fd, &readfds)) {
1208 /* discard all possible events, we can just reload the config */
1209 if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes) {
1213 buf = malloc(nbytes);
1215 err("error getting buffer for inotify, disable watching");
1219 read(inotify_fd, buf, nbytes);
1224 /* rules changed, set by inotify or a HUP signal */
1225 if (reload_config) {
1227 udev_rules_cleanup(&rules);
1228 udev_rules_init(&rules, 1);
1231 /* forked child has returned */
1232 if (sigchilds_waiting) {
1233 sigchilds_waiting = 0;
1240 msg_queue_manager();
1246 udev_rules_cleanup(&rules);
1250 if (signal_pipe[READ_END] >= 0)
1251 close(signal_pipe[READ_END]);
1252 if (signal_pipe[WRITE_END] >= 0)
1253 close(signal_pipe[WRITE_END]);
1255 if (udevd_sock >= 0)
1257 if (inotify_fd >= 0)
1259 if (uevent_netlink_sock >= 0)
1260 close(uevent_netlink_sock);