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)
80 printf("[%d] ", (int) getpid());
81 va_start(args, format);
82 vprintf(format, args);
86 va_start(args, format);
87 vsyslog(priority, format, args);
94 static void asmlinkage udev_event_sig_handler(int signum)
96 if (signum == SIGALRM)
100 static int udev_event_process(struct udevd_uevent_msg *msg)
102 struct sigaction act;
103 struct udevice *udev;
107 /* set signal handlers */
108 memset(&act, 0x00, sizeof(act));
109 act.sa_handler = (void (*)(int)) udev_event_sig_handler;
110 sigemptyset (&act.sa_mask);
112 sigaction(SIGALRM, &act, NULL);
114 /* reset to default */
115 act.sa_handler = SIG_DFL;
116 sigaction(SIGINT, &act, NULL);
117 sigaction(SIGTERM, &act, NULL);
118 sigaction(SIGCHLD, &act, NULL);
119 sigaction(SIGHUP, &act, NULL);
121 /* trigger timeout to prevent hanging processes */
122 alarm(UDEV_ALARM_TIMEOUT);
124 /* reconstruct event environment from message */
125 for (i = 0; msg->envp[i]; i++)
126 putenv(msg->envp[i]);
128 udev = udev_device_init(NULL);
131 strlcpy(udev->action, msg->action, sizeof(udev->action));
132 sysfs_device_set_values(udev->dev, msg->devpath, msg->subsystem, msg->driver);
133 udev->devt = msg->devt;
135 retval = udev_device_event(&rules, udev);
137 /* run programs collected by RUN-key*/
138 if (retval == 0 && !udev->ignore_device && udev_run) {
139 struct name_entry *name_loop;
141 dbg("executing run list");
142 list_for_each_entry(name_loop, &udev->run_list, node) {
143 if (strncmp(name_loop->name, "socket:", strlen("socket:")) == 0)
144 pass_env_to_socket(&name_loop->name[strlen("socket:")], udev->dev->devpath, udev->action);
146 char program[PATH_SIZE];
148 strlcpy(program, name_loop->name, sizeof(program));
149 udev_rules_apply_format(udev, program, sizeof(program));
150 if (run_program(program, udev->dev->subsystem, NULL, 0, NULL,
151 (udev_log_priority >= LOG_INFO)))
157 udev_device_cleanup(udev);
167 static void export_event_state(struct udevd_uevent_msg *msg, enum event_state state)
169 char filename[PATH_SIZE];
170 char filename_failed[PATH_SIZE];
172 struct udevd_uevent_msg *loop_msg;
175 /* add location of queue files */
176 strlcpy(filename, udev_root, sizeof(filename));
177 strlcat(filename, "/", sizeof(filename));
178 start = strlcat(filename, EVENT_QUEUE_DIR"/", sizeof(filename));
179 strlcat(filename, msg->devpath, sizeof(filename));
180 path_encode(&filename[start], sizeof(filename) - start);
182 /* add location of failed files */
183 strlcpy(filename_failed, udev_root, sizeof(filename_failed));
184 strlcat(filename_failed, "/", sizeof(filename_failed));
185 start = strlcat(filename_failed, EVENT_FAILED_DIR"/", sizeof(filename_failed));
186 strlcat(filename_failed, msg->devpath, sizeof(filename_failed));
187 path_encode(&filename_failed[start], sizeof(filename) - start);
191 unlink(filename_failed);
192 delete_path(filename_failed);
193 create_path(filename);
194 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
200 unlink(filename_failed);
201 delete_path(filename_failed);
203 /* don't remove, if events for the same path are still pending */
204 list_for_each_entry(loop_msg, &running_list, node)
205 if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
208 list_for_each_entry(loop_msg, &exec_list, node)
209 if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
212 /* move failed events to the failed directory */
213 if (state == EVENT_FAILED) {
214 create_path(filename_failed);
215 rename(filename, filename_failed);
220 /* clean up the queue directory */
221 delete_path(filename);
227 static void msg_queue_delete(struct udevd_uevent_msg *msg)
229 list_del(&msg->node);
231 /* mark as failed, if add event returns non-zero */
232 if (msg->exitstatus && strcmp(msg->action, "add") == 0)
233 export_event_state(msg, EVENT_FAILED);
235 export_event_state(msg, EVENT_FINISHED);
240 static void udev_event_run(struct udevd_uevent_msg *msg)
249 close(uevent_netlink_sock);
253 close(signal_pipe[READ_END]);
254 close(signal_pipe[WRITE_END]);
257 logging_init("udevd-event");
258 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
260 retval = udev_event_process(msg);
261 info("seq %llu finished", msg->seqnum);
268 err("fork of child failed: %s", strerror(errno));
269 msg_queue_delete(msg);
272 /* get SIGCHLD in main loop */
273 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
274 msg->seqnum, pid, msg->action, msg->subsystem, time(NULL) - msg->queue_time);
279 static void msg_queue_insert(struct udevd_uevent_msg *msg)
281 char filename[PATH_SIZE];
284 msg->queue_time = time(NULL);
286 strlcpy(filename, udev_root, sizeof(filename));
287 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
288 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
293 len = sprintf(str, "%llu\n", msg->seqnum);
298 export_event_state(msg, EVENT_QUEUED);
300 /* run one event after the other in debug mode */
302 list_add_tail(&msg->node, &running_list);
304 waitpid(msg->pid, NULL, 0);
305 msg_queue_delete(msg);
309 /* run all events with a timeout set immediately */
310 if (msg->timeout != 0) {
311 list_add_tail(&msg->node, &running_list);
316 list_add_tail(&msg->node, &exec_list);
320 static int mem_size_mb(void)
324 long int memsize = -1;
326 f = fopen("/proc/meminfo", "r");
330 while (fgets(buf, sizeof(buf), f) != NULL) {
333 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
334 memsize = value / 1024;
343 static int cpu_count(void)
349 f = fopen("/proc/stat", "r");
353 while (fgets(buf, sizeof(buf), f) != NULL) {
354 if (strncmp(buf, "cpu", 3) == 0 && isdigit(buf[3]))
364 static int running_processes(void)
370 f = fopen("/proc/stat", "r");
374 while (fgets(buf, sizeof(buf), f) != NULL) {
377 if (sscanf(buf, "procs_running %u", &value) == 1) {
387 /* return the number of process es in our session, count only until limit */
388 static int running_processes_in_session(pid_t session, int limit)
394 dir = opendir("/proc");
398 /* read process info from /proc */
399 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
405 pid_t ppid, pgrp, sess;
408 if (!isdigit(dent->d_name[0]))
411 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
412 procdir[sizeof(procdir)-1] = '\0';
414 f = open(procdir, O_RDONLY);
418 len = read(f, line, sizeof(line)-1);
426 /* skip ugly program name */
427 pos = strrchr(line, ')') + 2;
431 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
434 /* count only processes in our session */
438 /* count only running, no sleeping processes */
443 if (limit > 0 && running >= limit)
451 static int compare_devpath(const char *running, const char *waiting)
455 for (i = 0; i < PATH_SIZE; i++) {
456 /* identical device event found */
457 if (running[i] == '\0' && waiting[i] == '\0')
460 /* parent device event found */
461 if (running[i] == '\0' && waiting[i] == '/')
464 /* child device event found */
465 if (running[i] == '/' && waiting[i] == '\0')
468 /* no matching event */
469 if (running[i] != waiting[i])
476 /* lookup event for identical, parent, child, or physical device */
477 static int devpath_busy(struct udevd_uevent_msg *msg, int limit)
479 struct udevd_uevent_msg *loop_msg;
480 int childs_count = 0;
482 /* check exec-queue which may still contain delayed events we depend on */
483 list_for_each_entry(loop_msg, &exec_list, node) {
484 /* skip ourself and all later events */
485 if (loop_msg->seqnum >= msg->seqnum)
488 /* check identical, parent, or child device event */
489 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
490 dbg("%llu, device event still pending %llu (%s)",
491 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
495 /* check physical device event (special case of parent) */
496 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
497 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
498 dbg("%llu, physical device event still pending %llu (%s)",
499 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
504 /* check runing-queue for still running events */
505 list_for_each_entry(loop_msg, &running_list, node) {
506 if (limit && childs_count++ > limit) {
507 dbg("%llu, maximum number (%i) of childs reached", msg->seqnum, childs_count);
511 /* check identical, parent, or child device event */
512 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
513 dbg("%llu, device event still running %llu (%s)",
514 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
518 /* check physical device event (special case of parent) */
519 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
520 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
521 dbg("%llu, physical device event still running %llu (%s)",
522 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
529 /* serializes events for the identical and parent and child devices */
530 static void msg_queue_manager(void)
532 struct udevd_uevent_msg *loop_msg;
533 struct udevd_uevent_msg *tmp_msg;
536 if (list_empty(&exec_list))
539 running = running_processes();
540 dbg("%d processes runnning on system", running);
542 running = max_childs_running;
544 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
545 /* check running processes in our session and possibly throttle */
546 if (running >= max_childs_running) {
547 running = running_processes_in_session(sid, max_childs_running+10);
548 dbg("at least %d processes running in session", running);
549 if (running >= max_childs_running) {
550 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
555 /* serialize and wait for parent or child events */
556 if (devpath_busy(loop_msg, max_childs) != 0) {
557 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
561 /* move event to run list */
562 list_move_tail(&loop_msg->node, &running_list);
563 udev_event_run(loop_msg);
565 dbg("moved seq %llu to running list", loop_msg->seqnum);
569 static struct udevd_uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
573 struct udevd_uevent_msg *msg;
574 char *physdevdriver_key = NULL;
578 msg = malloc(sizeof(struct udevd_uevent_msg) + buf_size);
581 memset(msg, 0x00, sizeof(struct udevd_uevent_msg) + buf_size);
583 /* copy environment buffer and reconstruct envp */
584 memcpy(msg->envbuf, buf, buf_size);
586 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
590 key = &msg->envbuf[bufpos];
591 keylen = strlen(key);
593 bufpos += keylen + 1;
594 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
596 /* remember some keys for further processing */
597 if (strncmp(key, "ACTION=", 7) == 0)
598 msg->action = &key[7];
599 else if (strncmp(key, "DEVPATH=", 8) == 0)
600 msg->devpath = &key[8];
601 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
602 msg->subsystem = &key[10];
603 else if (strncmp(key, "DRIVER=", 7) == 0)
604 msg->driver = &key[7];
605 else if (strncmp(key, "SEQNUM=", 7) == 0)
606 msg->seqnum = strtoull(&key[7], NULL, 10);
607 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
608 msg->physdevpath = &key[12];
609 else if (strncmp(key, "PHYSDEVDRIVER=", 14) == 0)
610 physdevdriver_key = key;
611 else if (strncmp(key, "MAJOR=", 6) == 0)
612 maj = strtoull(&key[6], NULL, 10);
613 else if (strncmp(key, "MINOR=", 6) == 0)
614 min = strtoull(&key[6], NULL, 10);
615 else if (strncmp(key, "TIMEOUT=", 8) == 0)
616 msg->timeout = strtoull(&key[8], NULL, 10);
618 msg->devt = makedev(maj, min);
619 msg->envp[i++] = "UDEVD_EVENT=1";
621 if (msg->driver == NULL && msg->physdevpath == NULL && physdevdriver_key != NULL) {
622 /* for older kernels DRIVER is empty for a bus device, export PHYSDEVDRIVER as DRIVER */
623 msg->envp[i++] = &physdevdriver_key[7];
624 msg->driver = &physdevdriver_key[14];
629 if (msg->devpath == NULL || msg->action == NULL) {
630 info("DEVPATH or ACTION missing, ignore message");
637 /* receive the udevd message from userspace */
638 static void get_ctrl_msg(void)
640 struct udevd_ctrl_msg ctrl_msg;
643 struct cmsghdr *cmsg;
646 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
650 memset(&ctrl_msg, 0x00, sizeof(struct udevd_ctrl_msg));
651 iov.iov_base = &ctrl_msg;
652 iov.iov_len = sizeof(struct udevd_ctrl_msg);
654 memset(&smsg, 0x00, sizeof(struct msghdr));
657 smsg.msg_control = cred_msg;
658 smsg.msg_controllen = sizeof(cred_msg);
660 size = recvmsg(udevd_sock, &smsg, 0);
663 err("unable to receive user udevd message: %s", strerror(errno));
666 cmsg = CMSG_FIRSTHDR(&smsg);
667 cred = (struct ucred *) CMSG_DATA(cmsg);
669 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
670 err("no sender credentials received, message ignored");
674 if (cred->uid != 0) {
675 err("sender uid=%i, message ignored", cred->uid);
679 if (strncmp(ctrl_msg.magic, UDEVD_CTRL_MAGIC, sizeof(UDEVD_CTRL_MAGIC)) != 0 ) {
680 err("message magic '%s' doesn't match, ignore it", ctrl_msg.magic);
684 switch (ctrl_msg.type) {
686 pos = strchr(ctrl_msg.buf, '=');
688 err("wrong key format '%s'", ctrl_msg.buf);
692 if (pos[1] == '\0') {
693 info("udevd message (ENV) received, unset '%s'", ctrl_msg.buf);
694 unsetenv(ctrl_msg.buf);
696 info("udevd message (ENV) received, set '%s=%s'", ctrl_msg.buf, &pos[1]);
697 setenv(ctrl_msg.buf, &pos[1], 1);
700 case UDEVD_CTRL_STOP_EXEC_QUEUE:
701 info("udevd message (STOP_EXEC_QUEUE) received");
704 case UDEVD_CTRL_START_EXEC_QUEUE:
705 info("udevd message (START_EXEC_QUEUE) received");
709 case UDEVD_CTRL_SET_LOG_LEVEL:
710 intval = (int *) ctrl_msg.buf;
711 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
712 udev_log_priority = *intval;
713 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
716 case UDEVD_CTRL_SET_MAX_CHILDS:
717 intval = (int *) ctrl_msg.buf;
718 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
719 max_childs = *intval;
721 case UDEVD_CTRL_SET_MAX_CHILDS_RUNNING:
722 intval = (int *) ctrl_msg.buf;
723 info("udevd message (UDEVD_SET_MAX_CHILDS_RUNNING) received, max_childs=%i", *intval);
724 max_childs_running = *intval;
726 case UDEVD_CTRL_RELOAD_RULES:
727 info("udevd message (RELOAD_RULES) received");
731 err("unknown control message type");
735 /* receive the kernel user event message and do some sanity checks */
736 static struct udevd_uevent_msg *get_netlink_msg(void)
738 struct udevd_uevent_msg *msg;
741 static char buffer[UEVENT_BUFFER_SIZE+512];
744 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
747 err("unable to receive kernel netlink message: %s", strerror(errno));
751 if ((size_t)size > sizeof(buffer)-1)
752 size = sizeof(buffer)-1;
754 dbg("uevent_size=%zi", size);
756 /* start of event payload */
757 bufpos = strlen(buffer)+1;
758 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
762 /* validate message */
763 pos = strchr(buffer, '@');
765 err("invalid uevent '%s'", buffer);
771 if (msg->action == NULL) {
772 info("no ACTION in payload found, skip event '%s'", buffer);
777 if (strcmp(msg->action, buffer) != 0) {
778 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
786 static void asmlinkage sig_handler(int signum)
794 /* set flag, then write to pipe if needed */
795 sigchilds_waiting = 1;
802 /* write to pipe, which will wakeup select() in our mainloop */
803 write(signal_pipe[WRITE_END], "", 1);
806 static void udev_done(int pid, int exitstatus)
808 /* find msg associated with pid and delete it */
809 struct udevd_uevent_msg *msg;
811 list_for_each_entry(msg, &running_list, node) {
812 if (msg->pid == pid) {
813 info("seq %llu, pid [%d] exit with %i, %ld seconds old", msg->seqnum, msg->pid,
814 exitstatus, time(NULL) - msg->queue_time);
815 msg->exitstatus = exitstatus;
816 msg_queue_delete(msg);
818 /* there may be events waiting with the same devpath */
825 static void reap_sigchilds(void)
831 pid = waitpid(-1, &status, WNOHANG);
834 if (WIFEXITED(status))
835 status = WEXITSTATUS(status);
836 else if (WIFSIGNALED(status))
837 status = WTERMSIG(status) + 128;
840 udev_done(pid, status);
844 static int init_udevd_socket(void)
846 struct sockaddr_un saddr;
848 const int feature_on = 1;
851 memset(&saddr, 0x00, sizeof(saddr));
852 saddr.sun_family = AF_LOCAL;
853 /* use abstract namespace for socket path */
854 strcpy(&saddr.sun_path[1], UDEVD_CTRL_SOCK_PATH);
855 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
857 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
858 if (udevd_sock == -1) {
859 err("error getting socket: %s", strerror(errno));
863 /* the bind takes care of ensuring only one copy running */
864 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
866 err("bind failed: %s", strerror(errno));
872 /* enable receiving of the sender credentials */
873 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
878 static int init_uevent_netlink_sock(void)
880 struct sockaddr_nl snl;
881 const int buffersize = 16 * 1024 * 1024;
884 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
885 snl.nl_family = AF_NETLINK;
886 snl.nl_pid = getpid();
889 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
890 if (uevent_netlink_sock == -1) {
891 err("error getting socket: %s", strerror(errno));
895 /* set receive buffersize */
896 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
898 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
900 err("bind failed: %s", strerror(errno));
901 close(uevent_netlink_sock);
902 uevent_netlink_sock = -1;
908 static void export_initial_seqnum(void)
910 char filename[PATH_SIZE];
915 strlcpy(filename, sysfs_path, sizeof(filename));
916 strlcat(filename, "/kernel/uevent_seqnum", sizeof(filename));
917 fd = open(filename, O_RDONLY);
919 len = read(fd, seqnum, sizeof(seqnum)-1);
923 strcpy(seqnum, "0\n");
926 strlcpy(filename, udev_root, sizeof(filename));
927 strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
928 create_path(filename);
929 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
931 write(fd, seqnum, len);
936 int main(int argc, char *argv[], char *envp[])
940 struct sigaction act;
945 static const struct option options[] = {
946 { "daemon", 0, NULL, 'd' },
947 { "debug-trace", 0, NULL, 't' },
948 { "verbose", 0, NULL, 'v' },
949 { "help", 0, NULL, 'h' },
950 { "version", 0, NULL, 'V' },
956 logging_init("udevd");
959 dbg("version %s", UDEV_VERSION);
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);