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;
341 static int cpu_count(void)
347 f = fopen("/proc/stat", "r");
351 while (fgets(buf, sizeof(buf), f) != NULL) {
352 if (strncmp(buf, "cpu", 3) == 0 && isdigit(buf[3]))
362 static int running_processes(void)
368 f = fopen("/proc/stat", "r");
372 while (fgets(buf, sizeof(buf), f) != NULL) {
375 if (sscanf(buf, "procs_running %u", &value) == 1) {
385 /* return the number of process es in our session, count only until limit */
386 static int running_processes_in_session(pid_t session, int limit)
392 dir = opendir("/proc");
396 /* read process info from /proc */
397 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
403 pid_t ppid, pgrp, sess;
406 if (!isdigit(dent->d_name[0]))
409 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
410 procdir[sizeof(procdir)-1] = '\0';
412 f = open(procdir, O_RDONLY);
416 len = read(f, line, sizeof(line)-1);
424 /* skip ugly program name */
425 pos = strrchr(line, ')') + 2;
429 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
432 /* count only processes in our session */
436 /* count only running, no sleeping processes */
441 if (limit > 0 && running >= limit)
449 static int compare_devpath(const char *running, const char *waiting)
453 for (i = 0; i < PATH_SIZE; i++) {
454 /* identical device event found */
455 if (running[i] == '\0' && waiting[i] == '\0')
458 /* parent device event found */
459 if (running[i] == '\0' && waiting[i] == '/')
462 /* child device event found */
463 if (running[i] == '/' && waiting[i] == '\0')
466 /* no matching event */
467 if (running[i] != waiting[i])
474 /* lookup event for identical, parent, child, or physical device */
475 static int devpath_busy(struct udevd_uevent_msg *msg, int limit)
477 struct udevd_uevent_msg *loop_msg;
478 int childs_count = 0;
480 /* check exec-queue which may still contain delayed events we depend on */
481 list_for_each_entry(loop_msg, &exec_list, node) {
482 /* skip ourself and all later events */
483 if (loop_msg->seqnum >= msg->seqnum)
486 /* check identical, parent, or child device event */
487 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
488 dbg("%llu, device event still pending %llu (%s)",
489 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
493 /* check physical device event (special case of parent) */
494 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
495 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
496 dbg("%llu, physical device event still pending %llu (%s)",
497 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
502 /* check runing-queue for still running events */
503 list_for_each_entry(loop_msg, &running_list, node) {
504 if (limit && childs_count++ > limit) {
505 dbg("%llu, maximum number (%i) of childs reached", msg->seqnum, childs_count);
509 /* check identical, parent, or child device event */
510 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
511 dbg("%llu, device event still running %llu (%s)",
512 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
516 /* check physical device event (special case of parent) */
517 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
518 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
519 dbg("%llu, physical device event still running %llu (%s)",
520 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
527 /* serializes events for the identical and parent and child devices */
528 static void msg_queue_manager(void)
530 struct udevd_uevent_msg *loop_msg;
531 struct udevd_uevent_msg *tmp_msg;
534 if (list_empty(&exec_list))
537 running = running_processes();
538 dbg("%d processes runnning on system", running);
540 running = max_childs_running;
542 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
543 /* check running processes in our session and possibly throttle */
544 if (running >= max_childs_running) {
545 running = running_processes_in_session(sid, max_childs_running+10);
546 dbg("at least %d processes running in session", running);
547 if (running >= max_childs_running) {
548 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
553 /* serialize and wait for parent or child events */
554 if (devpath_busy(loop_msg, max_childs) != 0) {
555 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
559 /* move event to run list */
560 list_move_tail(&loop_msg->node, &running_list);
561 udev_event_run(loop_msg);
563 dbg("moved seq %llu to running list", loop_msg->seqnum);
567 static struct udevd_uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
571 struct udevd_uevent_msg *msg;
572 char *physdevdriver_key = NULL;
576 msg = malloc(sizeof(struct udevd_uevent_msg) + buf_size);
579 memset(msg, 0x00, sizeof(struct udevd_uevent_msg) + buf_size);
581 /* copy environment buffer and reconstruct envp */
582 memcpy(msg->envbuf, buf, buf_size);
584 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
588 key = &msg->envbuf[bufpos];
589 keylen = strlen(key);
591 bufpos += keylen + 1;
592 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
594 /* remember some keys for further processing */
595 if (strncmp(key, "ACTION=", 7) == 0)
596 msg->action = &key[7];
597 else if (strncmp(key, "DEVPATH=", 8) == 0)
598 msg->devpath = &key[8];
599 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
600 msg->subsystem = &key[10];
601 else if (strncmp(key, "DRIVER=", 7) == 0)
602 msg->driver = &key[7];
603 else if (strncmp(key, "SEQNUM=", 7) == 0)
604 msg->seqnum = strtoull(&key[7], NULL, 10);
605 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
606 msg->physdevpath = &key[12];
607 else if (strncmp(key, "PHYSDEVDRIVER=", 14) == 0)
608 physdevdriver_key = key;
609 else if (strncmp(key, "MAJOR=", 6) == 0)
610 maj = strtoull(&key[6], NULL, 10);
611 else if (strncmp(key, "MINOR=", 6) == 0)
612 min = strtoull(&key[6], NULL, 10);
613 else if (strncmp(key, "TIMEOUT=", 8) == 0)
614 msg->timeout = strtoull(&key[8], NULL, 10);
616 msg->devt = makedev(maj, min);
617 msg->envp[i++] = "UDEVD_EVENT=1";
619 if (msg->driver == NULL && msg->physdevpath == NULL && physdevdriver_key != NULL) {
620 /* for older kernels DRIVER is empty for a bus device, export PHYSDEVDRIVER as DRIVER */
621 msg->envp[i++] = &physdevdriver_key[7];
622 msg->driver = &physdevdriver_key[14];
627 if (msg->devpath == NULL || msg->action == NULL) {
628 info("DEVPATH or ACTION missing, ignore message");
635 /* receive the udevd message from userspace */
636 static void get_ctrl_msg(void)
638 struct udevd_ctrl_msg ctrl_msg;
641 struct cmsghdr *cmsg;
644 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
648 memset(&ctrl_msg, 0x00, sizeof(struct udevd_ctrl_msg));
649 iov.iov_base = &ctrl_msg;
650 iov.iov_len = sizeof(struct udevd_ctrl_msg);
652 memset(&smsg, 0x00, sizeof(struct msghdr));
655 smsg.msg_control = cred_msg;
656 smsg.msg_controllen = sizeof(cred_msg);
658 size = recvmsg(udevd_sock, &smsg, 0);
661 err("unable to receive user udevd message: %s", strerror(errno));
664 cmsg = CMSG_FIRSTHDR(&smsg);
665 cred = (struct ucred *) CMSG_DATA(cmsg);
667 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
668 err("no sender credentials received, message ignored");
672 if (cred->uid != 0) {
673 err("sender uid=%i, message ignored", cred->uid);
677 if (strncmp(ctrl_msg.magic, UDEVD_CTRL_MAGIC, sizeof(UDEVD_CTRL_MAGIC)) != 0 ) {
678 err("message magic '%s' doesn't match, ignore it", ctrl_msg.magic);
682 switch (ctrl_msg.type) {
684 pos = strchr(ctrl_msg.buf, '=');
686 err("wrong key format '%s'", ctrl_msg.buf);
690 if (pos[1] == '\0') {
691 info("udevd message (ENV) received, unset '%s'", ctrl_msg.buf);
692 unsetenv(ctrl_msg.buf);
694 info("udevd message (ENV) received, set '%s=%s'", ctrl_msg.buf, &pos[1]);
695 setenv(ctrl_msg.buf, &pos[1], 1);
698 case UDEVD_CTRL_STOP_EXEC_QUEUE:
699 info("udevd message (STOP_EXEC_QUEUE) received");
702 case UDEVD_CTRL_START_EXEC_QUEUE:
703 info("udevd message (START_EXEC_QUEUE) received");
707 case UDEVD_CTRL_SET_LOG_LEVEL:
708 intval = (int *) ctrl_msg.buf;
709 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
710 udev_log_priority = *intval;
711 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
714 case UDEVD_CTRL_SET_MAX_CHILDS:
715 intval = (int *) ctrl_msg.buf;
716 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
717 max_childs = *intval;
719 case UDEVD_CTRL_SET_MAX_CHILDS_RUNNING:
720 intval = (int *) ctrl_msg.buf;
721 info("udevd message (UDEVD_SET_MAX_CHILDS_RUNNING) received, max_childs=%i", *intval);
722 max_childs_running = *intval;
724 case UDEVD_CTRL_RELOAD_RULES:
725 info("udevd message (RELOAD_RULES) received");
729 err("unknown control message type");
733 /* receive the kernel user event message and do some sanity checks */
734 static struct udevd_uevent_msg *get_netlink_msg(void)
736 struct udevd_uevent_msg *msg;
739 static char buffer[UEVENT_BUFFER_SIZE+512];
742 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
745 err("unable to receive kernel netlink message: %s", strerror(errno));
749 if ((size_t)size > sizeof(buffer)-1)
750 size = sizeof(buffer)-1;
752 dbg("uevent_size=%zi", size);
754 /* start of event payload */
755 bufpos = strlen(buffer)+1;
756 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
760 /* validate message */
761 pos = strchr(buffer, '@');
763 err("invalid uevent '%s'", buffer);
769 if (msg->action == NULL) {
770 info("no ACTION in payload found, skip event '%s'", buffer);
775 if (strcmp(msg->action, buffer) != 0) {
776 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
784 static void asmlinkage sig_handler(int signum)
792 /* set flag, then write to pipe if needed */
793 sigchilds_waiting = 1;
800 /* write to pipe, which will wakeup select() in our mainloop */
801 write(signal_pipe[WRITE_END], "", 1);
804 static void udev_done(int pid, int exitstatus)
806 /* find msg associated with pid and delete it */
807 struct udevd_uevent_msg *msg;
809 list_for_each_entry(msg, &running_list, node) {
810 if (msg->pid == pid) {
811 info("seq %llu, pid [%d] exit with %i, %ld seconds old", msg->seqnum, msg->pid,
812 exitstatus, time(NULL) - msg->queue_time);
813 msg->exitstatus = exitstatus;
814 msg_queue_delete(msg);
816 /* there may be events waiting with the same devpath */
823 static void reap_sigchilds(void)
829 pid = waitpid(-1, &status, WNOHANG);
832 if (WIFEXITED(status))
833 status = WEXITSTATUS(status);
834 else if (WIFSIGNALED(status))
835 status = WTERMSIG(status) + 128;
838 udev_done(pid, status);
842 static int init_udevd_socket(void)
844 struct sockaddr_un saddr;
846 const int feature_on = 1;
849 memset(&saddr, 0x00, sizeof(saddr));
850 saddr.sun_family = AF_LOCAL;
851 /* use abstract namespace for socket path */
852 strcpy(&saddr.sun_path[1], UDEVD_CTRL_SOCK_PATH);
853 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
855 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
856 if (udevd_sock == -1) {
857 err("error getting socket: %s", strerror(errno));
861 /* the bind takes care of ensuring only one copy running */
862 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
864 err("bind failed: %s", strerror(errno));
870 /* enable receiving of the sender credentials */
871 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
876 static int init_uevent_netlink_sock(void)
878 struct sockaddr_nl snl;
879 const int buffersize = 16 * 1024 * 1024;
882 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
883 snl.nl_family = AF_NETLINK;
884 snl.nl_pid = getpid();
887 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
888 if (uevent_netlink_sock == -1) {
889 err("error getting socket: %s", strerror(errno));
893 /* set receive buffersize */
894 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
896 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
898 err("bind failed: %s", strerror(errno));
899 close(uevent_netlink_sock);
900 uevent_netlink_sock = -1;
906 static void export_initial_seqnum(void)
908 char filename[PATH_SIZE];
913 strlcpy(filename, sysfs_path, sizeof(filename));
914 strlcat(filename, "/kernel/uevent_seqnum", sizeof(filename));
915 fd = open(filename, O_RDONLY);
917 len = read(fd, seqnum, sizeof(seqnum)-1);
921 strcpy(seqnum, "0\n");
924 strlcpy(filename, udev_root, sizeof(filename));
925 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
926 create_path(filename);
927 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
929 write(fd, seqnum, len);
934 int main(int argc, char *argv[], char *envp[])
938 struct sigaction act;
943 static const struct option options[] = {
944 { "daemon", 0, NULL, 'd' },
945 { "debug-trace", 0, NULL, 't' },
946 { "verbose", 0, NULL, 'v' },
947 { "help", 0, NULL, 'h' },
948 { "version", 0, NULL, 'V' },
954 logging_init("udevd");
957 dbg("version %s", UDEV_VERSION);
959 /* parse commandline options */
961 option = getopt_long(argc, argv, "dtvhV", options, NULL);
974 if (udev_log_priority < LOG_INFO)
975 udev_log_priority = LOG_INFO;
978 printf("Usage: udevd [--help] [--daemon] [--debug-trace] [--verbose] [--version]\n");
981 printf("%s\n", UDEV_VERSION);
989 fprintf(stderr, "root privileges required\n");
990 err("root privileges required");
994 /* make sure std{in,out,err} fd's are in a sane state */
995 fd = open("/dev/null", O_RDWR);
997 fprintf(stderr, "cannot open /dev/null\n");
998 err("cannot open /dev/null");
1000 if (fd > STDIN_FILENO)
1001 dup2(fd, STDIN_FILENO);
1002 if (write(STDOUT_FILENO, 0, 0) < 0)
1003 dup2(fd, STDOUT_FILENO);
1004 if (write(STDERR_FILENO, 0, 0) < 0)
1005 dup2(fd, STDERR_FILENO);
1007 /* init sockets to receive events */
1008 if (init_udevd_socket() < 0) {
1009 if (errno == EADDRINUSE) {
1010 fprintf(stderr, "another udev daemon already running\n");
1011 err("another udev daemon already running");
1014 fprintf(stderr, "error initializing udevd socket\n");
1015 err("error initializing udevd socket");
1021 if (init_uevent_netlink_sock() < 0) {
1022 fprintf(stderr, "error initializing netlink socket\n");
1023 err("error initializing netlink socket");
1028 /* setup signal handler pipe */
1029 retval = pipe(signal_pipe);
1031 err("error getting pipes: %s", strerror(errno));
1035 retval = fcntl(signal_pipe[READ_END], F_GETFL, 0);
1037 err("error fcntl on read pipe: %s", strerror(errno));
1040 retval = fcntl(signal_pipe[READ_END], F_SETFL, retval | O_NONBLOCK);
1042 err("error fcntl on read pipe: %s", strerror(errno));
1046 retval = fcntl(signal_pipe[WRITE_END], F_GETFL, 0);
1048 err("error fcntl on write pipe: %s", strerror(errno));
1051 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, retval | O_NONBLOCK);
1053 err("error fcntl on write pipe: %s", strerror(errno));
1057 /* parse the rules and keep them in memory */
1059 udev_rules_init(&rules, 1);
1061 export_initial_seqnum();
1069 dbg("daemonized fork running");
1072 err("fork of daemon failed: %s", strerror(errno));
1076 dbg("child [%u] running, parent exits", pid);
1082 /* redirect std{out,err} fd's */
1084 dup2(fd, STDOUT_FILENO);
1085 dup2(fd, STDERR_FILENO);
1086 if (fd > STDERR_FILENO)
1089 /* set scheduling priority for the daemon */
1090 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
1095 /* become session leader */
1097 dbg("our session is %d", sid);
1099 /* OOM_DISABLE == -17 */
1100 fd = open("/proc/self/oom_adj", O_RDWR);
1102 err("error disabling OOM: %s", strerror(errno));
1104 write(fd, "-17", 3);
1108 /* set signal handlers */
1109 memset(&act, 0x00, sizeof(struct sigaction));
1110 act.sa_handler = (void (*)(int)) sig_handler;
1111 sigemptyset(&act.sa_mask);
1112 act.sa_flags = SA_RESTART;
1113 sigaction(SIGINT, &act, NULL);
1114 sigaction(SIGTERM, &act, NULL);
1115 sigaction(SIGCHLD, &act, NULL);
1116 sigaction(SIGHUP, &act, NULL);
1118 /* watch rules directory */
1119 inotify_fd = inotify_init();
1120 if (inotify_fd >= 0)
1121 inotify_add_watch(inotify_fd, udev_rules_dir, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1122 else if (errno == ENOSYS)
1123 err("the kernel does not support inotify, udevd can't monitor configuration file changes");
1125 err("inotify_init failed: %s", strerror(errno));
1127 /* maximum limit of forked childs */
1128 value = getenv("UDEVD_MAX_CHILDS");
1130 max_childs = strtoul(value, NULL, 10);
1132 int memsize = mem_size_mb();
1134 max_childs = 128 + (memsize / 4);
1136 max_childs = UDEVD_MAX_CHILDS;
1138 info("initialize max_childs to %u", max_childs);
1140 /* start to throttle forking if maximum number of _running_ childs is reached */
1141 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
1143 max_childs_running = strtoull(value, NULL, 10);
1145 int cpus = cpu_count();
1147 max_childs_running = 8 + (8 * cpus);
1149 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
1151 info("initialize max_childs_running to %u", max_childs_running);
1153 /* clear environment for forked event processes */
1156 /* export log_priority , as called programs may want to follow that setting */
1157 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
1163 maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
1164 maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
1165 maxfd = UDEV_MAX(maxfd, inotify_fd);
1167 while (!udev_exit) {
1168 struct udevd_uevent_msg *msg;
1172 FD_SET(signal_pipe[READ_END], &readfds);
1173 FD_SET(udevd_sock, &readfds);
1174 FD_SET(uevent_netlink_sock, &readfds);
1175 if (inotify_fd >= 0)
1176 FD_SET(inotify_fd, &readfds);
1178 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
1181 err("error in select: %s", strerror(errno));
1185 /* get control message */
1186 if (FD_ISSET(udevd_sock, &readfds))
1189 /* get netlink message */
1190 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
1191 msg = get_netlink_msg();
1193 msg_queue_insert(msg);
1196 /* received a signal, clear our notification pipe */
1197 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
1200 read(signal_pipe[READ_END], &buf, sizeof(buf));
1203 /* rules directory inotify watch */
1204 if ((inotify_fd >= 0) && FD_ISSET(inotify_fd, &readfds)) {
1207 /* discard all possible events, we can just reload the config */
1208 if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes) {
1212 buf = malloc(nbytes);
1214 err("error getting buffer for inotify, disable watching");
1218 read(inotify_fd, buf, nbytes);
1223 /* rules changed, set by inotify or a HUP signal */
1224 if (reload_config) {
1226 udev_rules_cleanup(&rules);
1227 udev_rules_init(&rules, 1);
1230 /* forked child has returned */
1231 if (sigchilds_waiting) {
1232 sigchilds_waiting = 0;
1239 msg_queue_manager();
1245 udev_rules_cleanup(&rules);
1249 if (signal_pipe[READ_END] >= 0)
1250 close(signal_pipe[READ_END]);
1251 if (signal_pipe[WRITE_END] >= 0)
1252 close(signal_pipe[WRITE_END]);
1254 if (udevd_sock >= 0)
1256 if (inotify_fd >= 0)
1258 if (uevent_netlink_sock >= 0)
1259 close(uevent_netlink_sock);