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.
35 #include <sys/select.h>
37 #include <sys/types.h>
38 #include <sys/socket.h>
41 #include <sys/ioctl.h>
42 #include <linux/types.h>
43 #include <linux/netlink.h>
45 #include <sys/inotify.h>
49 #include "udev_rules.h"
51 #include "udev_selinux.h"
53 static int debug_trace;
56 static struct udev_rules rules;
57 static int udevd_sock = -1;
58 static int uevent_netlink_sock = -1;
59 static int inotify_fd = -1;
62 static int signal_pipe[2] = {-1, -1};
63 static volatile int sigchilds_waiting;
64 static volatile int udev_exit;
65 static volatile int reload_config;
66 static int run_exec_q;
67 static int stop_exec_q;
68 static int max_childs;
69 static int max_childs_running;
70 static char udev_log[32];
72 static LIST_HEAD(exec_list);
73 static LIST_HEAD(running_list);
77 void log_message(int priority, const char *format, ...)
81 if (priority > udev_log_priority)
84 va_start(args, format);
86 printf("[%d] ", (int) getpid());
87 vprintf(format, args);
89 vsyslog(priority, format, args);
95 static void asmlinkage udev_event_sig_handler(int signum)
97 if (signum == SIGALRM)
101 static int udev_event_process(struct udevd_uevent_msg *msg)
103 struct sigaction act;
104 struct udevice *udev;
108 /* set signal handlers */
109 memset(&act, 0x00, sizeof(act));
110 act.sa_handler = (void (*)(int)) udev_event_sig_handler;
111 sigemptyset (&act.sa_mask);
113 sigaction(SIGALRM, &act, NULL);
115 /* reset to default */
116 act.sa_handler = SIG_DFL;
117 sigaction(SIGINT, &act, NULL);
118 sigaction(SIGTERM, &act, NULL);
119 sigaction(SIGCHLD, &act, NULL);
120 sigaction(SIGHUP, &act, NULL);
122 /* trigger timeout to prevent hanging processes */
123 alarm(UDEV_EVENT_TIMEOUT);
125 /* reconstruct event environment from message */
126 for (i = 0; msg->envp[i]; i++)
127 putenv(msg->envp[i]);
129 udev = udev_device_init();
132 strlcpy(udev->action, msg->action, sizeof(udev->action));
133 sysfs_device_set_values(udev->dev, msg->devpath, msg->subsystem, msg->driver);
134 udev->devpath_old = msg->devpath_old;
135 udev->devt = msg->devt;
137 retval = udev_device_event(&rules, udev);
139 /* rules may change/disable the timeout */
140 if (udev->event_timeout >= 0)
141 alarm(udev->event_timeout);
143 /* run programs collected by RUN-key*/
144 if (retval == 0 && !udev->ignore_device && udev_run)
145 retval = udev_rules_run(udev);
147 udev_device_cleanup(udev);
157 static void export_event_state(struct udevd_uevent_msg *msg, enum event_state state)
159 char filename[PATH_SIZE];
160 char filename_failed[PATH_SIZE];
163 /* location of queue file */
164 snprintf(filename, sizeof(filename), "%s/.udev/queue/%llu", udev_root, msg->seqnum);
166 /* location of failed file */
167 strlcpy(filename_failed, udev_root, sizeof(filename_failed));
168 strlcat(filename_failed, "/", sizeof(filename_failed));
169 start = strlcat(filename_failed, ".udev/failed/", sizeof(filename_failed));
170 strlcat(filename_failed, msg->devpath, sizeof(filename_failed));
171 path_encode(&filename_failed[start], sizeof(filename_failed) - start);
175 unlink(filename_failed);
176 delete_path(filename_failed);
178 create_path(filename);
179 selinux_setfscreatecon(filename, NULL, S_IFLNK);
180 symlink(msg->devpath, filename);
181 selinux_resetfscreatecon();
184 if (msg->devpath_old != NULL) {
185 /* "move" event - rename failed file to current name, do not delete failed */
186 char filename_failed_old[PATH_SIZE];
188 strlcpy(filename_failed_old, udev_root, sizeof(filename_failed_old));
189 strlcat(filename_failed_old, "/", sizeof(filename_failed_old));
190 start = strlcat(filename_failed_old, ".udev/failed/", sizeof(filename_failed_old));
191 strlcat(filename_failed_old, msg->devpath_old, sizeof(filename_failed_old));
192 path_encode(&filename_failed_old[start], sizeof(filename) - start);
194 if (rename(filename_failed_old, filename_failed) == 0)
195 info("renamed devpath, moved failed state of '%s' to %s'\n",
196 msg->devpath_old, msg->devpath);
198 unlink(filename_failed);
199 delete_path(filename_failed);
203 delete_path(filename);
206 /* move failed event to the failed directory */
207 create_path(filename_failed);
208 rename(filename, filename_failed);
210 /* clean up possibly empty queue directory */
211 delete_path(filename);
218 static void msg_queue_delete(struct udevd_uevent_msg *msg)
220 list_del(&msg->node);
222 /* mark as failed, if "add" event returns non-zero */
223 if (msg->exitstatus && strcmp(msg->action, "add") == 0)
224 export_event_state(msg, EVENT_FAILED);
226 export_event_state(msg, EVENT_FINISHED);
231 static void udev_event_run(struct udevd_uevent_msg *msg)
240 close(uevent_netlink_sock);
244 close(signal_pipe[READ_END]);
245 close(signal_pipe[WRITE_END]);
248 logging_init("udevd-event");
249 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
251 retval = udev_event_process(msg);
252 info("seq %llu finished with %i\n", msg->seqnum, retval);
259 err("fork of child failed: %s\n", strerror(errno));
260 msg_queue_delete(msg);
263 /* get SIGCHLD in main loop */
264 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old\n",
265 msg->seqnum, pid, msg->action, msg->subsystem, time(NULL) - msg->queue_time);
270 static void msg_queue_insert(struct udevd_uevent_msg *msg)
272 char filename[PATH_SIZE];
275 msg->queue_time = time(NULL);
277 export_event_state(msg, EVENT_QUEUED);
278 info("seq %llu queued, '%s' '%s'\n", msg->seqnum, msg->action, msg->subsystem);
280 strlcpy(filename, udev_root, sizeof(filename));
281 strlcat(filename, "/.udev/uevent_seqnum", sizeof(filename));
282 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
287 len = sprintf(str, "%llu\n", msg->seqnum);
292 /* run one event after the other in debug mode */
294 list_add_tail(&msg->node, &running_list);
296 waitpid(msg->pid, NULL, 0);
297 msg_queue_delete(msg);
301 /* run all events with a timeout set immediately */
302 if (msg->timeout != 0) {
303 list_add_tail(&msg->node, &running_list);
308 list_add_tail(&msg->node, &exec_list);
312 static int mem_size_mb(void)
316 long int memsize = -1;
318 f = fopen("/proc/meminfo", "r");
322 while (fgets(buf, sizeof(buf), f) != NULL) {
325 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
326 memsize = value / 1024;
335 static int cpu_count(void)
341 f = fopen("/proc/stat", "r");
345 while (fgets(buf, sizeof(buf), f) != NULL) {
346 if (strncmp(buf, "cpu", 3) == 0 && isdigit(buf[3]))
356 static int running_processes(void)
362 f = fopen("/proc/stat", "r");
366 while (fgets(buf, sizeof(buf), f) != NULL) {
369 if (sscanf(buf, "procs_running %u", &value) == 1) {
379 /* return the number of process es in our session, count only until limit */
380 static int running_processes_in_session(pid_t session, int limit)
386 dir = opendir("/proc");
390 /* read process info from /proc */
391 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
397 pid_t ppid, pgrp, sess;
400 if (!isdigit(dent->d_name[0]))
403 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
404 procdir[sizeof(procdir)-1] = '\0';
406 f = open(procdir, O_RDONLY);
410 len = read(f, line, sizeof(line)-1);
418 /* skip ugly program name */
419 pos = strrchr(line, ')') + 2;
423 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
426 /* count only processes in our session */
430 /* count only running, no sleeping processes */
435 if (limit > 0 && running >= limit)
443 static int compare_devpath(const char *running, const char *waiting)
447 for (i = 0; i < PATH_SIZE; i++) {
448 /* identical device event found */
449 if (running[i] == '\0' && waiting[i] == '\0')
452 /* parent device event found */
453 if (running[i] == '\0' && waiting[i] == '/')
456 /* child device event found */
457 if (running[i] == '/' && waiting[i] == '\0')
460 /* no matching event */
461 if (running[i] != waiting[i])
468 /* lookup event for identical, parent, child, or physical device */
469 static int devpath_busy(struct udevd_uevent_msg *msg, int limit)
471 struct udevd_uevent_msg *loop_msg;
472 int childs_count = 0;
474 /* check exec-queue which may still contain delayed events we depend on */
475 list_for_each_entry(loop_msg, &exec_list, node) {
476 /* skip ourself and all later events */
477 if (loop_msg->seqnum >= msg->seqnum)
480 /* check our old name */
481 if (msg->devpath_old != NULL)
482 if (strcmp(loop_msg->devpath , msg->devpath_old) == 0)
485 /* check identical, parent, or child device event */
486 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
487 dbg("%llu, device event still pending %llu (%s)\n",
488 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
492 /* check for our major:minor number */
493 if (msg->devt && loop_msg->devt == msg->devt &&
494 strcmp(msg->subsystem, loop_msg->subsystem) == 0) {
495 dbg("%llu, device event still pending %llu (%d:%d)\n", msg->seqnum,
496 loop_msg->seqnum, major(loop_msg->devt), minor(loop_msg->devt));
500 /* check physical device event (special case of parent) */
501 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
502 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
503 dbg("%llu, physical device event still pending %llu (%s)\n",
504 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
509 /* check run queue for still running events */
510 list_for_each_entry(loop_msg, &running_list, node) {
511 if (limit && childs_count++ > limit) {
512 dbg("%llu, maximum number (%i) of childs reached\n", msg->seqnum, childs_count);
516 /* check our old name */
517 if (msg->devpath_old != NULL)
518 if (strcmp(loop_msg->devpath , msg->devpath_old) == 0)
521 /* check identical, parent, or child device event */
522 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
523 dbg("%llu, device event still running %llu (%s)\n",
524 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
528 /* check for our major:minor number */
529 if (msg->devt && loop_msg->devt == msg->devt &&
530 strcmp(msg->subsystem, loop_msg->subsystem) == 0) {
531 dbg("%llu, device event still running %llu (%d:%d)\n", msg->seqnum,
532 loop_msg->seqnum, major(loop_msg->devt), minor(loop_msg->devt));
536 /* check physical device event (special case of parent) */
537 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
538 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
539 dbg("%llu, physical device event still running %llu (%s)\n",
540 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
547 /* serializes events for the identical and parent and child devices */
548 static void msg_queue_manager(void)
550 struct udevd_uevent_msg *loop_msg;
551 struct udevd_uevent_msg *tmp_msg;
554 if (list_empty(&exec_list))
557 running = running_processes();
558 dbg("%d processes runnning on system\n", running);
560 running = max_childs_running;
562 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
563 /* check running processes in our session and possibly throttle */
564 if (running >= max_childs_running) {
565 running = running_processes_in_session(sid, max_childs_running+10);
566 dbg("at least %d processes running in session\n", running);
567 if (running >= max_childs_running) {
568 dbg("delay seq %llu, too many processes already running\n", loop_msg->seqnum);
573 /* serialize and wait for parent or child events */
574 if (devpath_busy(loop_msg, max_childs) != 0) {
575 dbg("delay seq %llu (%s)\n", loop_msg->seqnum, loop_msg->devpath);
579 /* move event to run list */
580 list_move_tail(&loop_msg->node, &running_list);
581 udev_event_run(loop_msg);
583 dbg("moved seq %llu to running list\n", loop_msg->seqnum);
587 static struct udevd_uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
591 struct udevd_uevent_msg *msg;
592 char *physdevdriver_key = NULL;
596 msg = malloc(sizeof(struct udevd_uevent_msg) + buf_size);
599 memset(msg, 0x00, sizeof(struct udevd_uevent_msg) + buf_size);
601 /* copy environment buffer and reconstruct envp */
602 memcpy(msg->envbuf, buf, buf_size);
604 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
608 key = &msg->envbuf[bufpos];
609 keylen = strlen(key);
611 bufpos += keylen + 1;
612 dbg("add '%s' to msg.envp[%i]\n", msg->envp[i], i);
614 /* remember some keys for further processing */
615 if (strncmp(key, "ACTION=", 7) == 0)
616 msg->action = &key[7];
617 else if (strncmp(key, "DEVPATH=", 8) == 0)
618 msg->devpath = &key[8];
619 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
620 msg->subsystem = &key[10];
621 else if (strncmp(key, "DRIVER=", 7) == 0)
622 msg->driver = &key[7];
623 else if (strncmp(key, "SEQNUM=", 7) == 0)
624 msg->seqnum = strtoull(&key[7], NULL, 10);
625 else if (strncmp(key, "DEVPATH_OLD=", 12) == 0)
626 msg->devpath_old = &key[12];
627 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
628 msg->physdevpath = &key[12];
629 else if (strncmp(key, "PHYSDEVDRIVER=", 14) == 0)
630 physdevdriver_key = key;
631 else if (strncmp(key, "MAJOR=", 6) == 0)
632 maj = strtoull(&key[6], NULL, 10);
633 else if (strncmp(key, "MINOR=", 6) == 0)
634 min = strtoull(&key[6], NULL, 10);
635 else if (strncmp(key, "TIMEOUT=", 8) == 0)
636 msg->timeout = strtoull(&key[8], NULL, 10);
638 msg->devt = makedev(maj, min);
639 msg->envp[i++] = "UDEVD_EVENT=1";
641 if (msg->driver == NULL && msg->physdevpath == NULL && physdevdriver_key != NULL) {
642 /* for older kernels DRIVER is empty for a bus device, export PHYSDEVDRIVER as DRIVER */
643 msg->envp[i++] = &physdevdriver_key[7];
644 msg->driver = &physdevdriver_key[14];
649 if (msg->devpath == NULL || msg->action == NULL) {
650 info("DEVPATH or ACTION missing, ignore message\n");
657 /* receive the udevd message from userspace */
658 static void get_ctrl_msg(void)
660 struct udevd_ctrl_msg ctrl_msg;
663 struct cmsghdr *cmsg;
666 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
669 memset(&ctrl_msg, 0x00, sizeof(struct udevd_ctrl_msg));
670 iov.iov_base = &ctrl_msg;
671 iov.iov_len = sizeof(struct udevd_ctrl_msg);
673 memset(&smsg, 0x00, sizeof(struct msghdr));
676 smsg.msg_control = cred_msg;
677 smsg.msg_controllen = sizeof(cred_msg);
679 size = recvmsg(udevd_sock, &smsg, 0);
682 err("unable to receive user udevd message: %s\n", strerror(errno));
685 cmsg = CMSG_FIRSTHDR(&smsg);
686 cred = (struct ucred *) CMSG_DATA(cmsg);
688 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
689 err("no sender credentials received, message ignored\n");
693 if (cred->uid != 0) {
694 err("sender uid=%i, message ignored\n", cred->uid);
698 if (strncmp(ctrl_msg.magic, UDEVD_CTRL_MAGIC, sizeof(UDEVD_CTRL_MAGIC)) != 0 ) {
699 err("message magic '%s' doesn't match, ignore it\n", ctrl_msg.magic);
703 switch (ctrl_msg.type) {
705 pos = strchr(ctrl_msg.buf, '=');
707 err("wrong key format '%s'\n", ctrl_msg.buf);
711 if (pos[1] == '\0') {
712 info("udevd message (ENV) received, unset '%s'\n", ctrl_msg.buf);
713 unsetenv(ctrl_msg.buf);
715 info("udevd message (ENV) received, set '%s=%s'\n", ctrl_msg.buf, &pos[1]);
716 setenv(ctrl_msg.buf, &pos[1], 1);
719 case UDEVD_CTRL_STOP_EXEC_QUEUE:
720 info("udevd message (STOP_EXEC_QUEUE) received\n");
723 case UDEVD_CTRL_START_EXEC_QUEUE:
724 info("udevd message (START_EXEC_QUEUE) received\n");
728 case UDEVD_CTRL_SET_LOG_LEVEL:
729 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i\n", ctrl_msg.intval);
730 udev_log_priority = ctrl_msg.intval;
731 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
734 case UDEVD_CTRL_SET_MAX_CHILDS:
735 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i\n", ctrl_msg.intval);
736 max_childs = ctrl_msg.intval;
738 case UDEVD_CTRL_SET_MAX_CHILDS_RUNNING:
739 info("udevd message (UDEVD_SET_MAX_CHILDS_RUNNING) received, max_childs_running=%i\n", ctrl_msg.intval);
740 max_childs_running = ctrl_msg.intval;
742 case UDEVD_CTRL_RELOAD_RULES:
743 info("udevd message (RELOAD_RULES) received\n");
747 err("unknown control message type\n");
751 /* receive the kernel user event message and do some sanity checks */
752 static struct udevd_uevent_msg *get_netlink_msg(void)
754 struct udevd_uevent_msg *msg;
757 static char buffer[UEVENT_BUFFER_SIZE+512];
760 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
763 err("unable to receive kernel netlink message: %s\n", strerror(errno));
767 if ((size_t)size > sizeof(buffer)-1)
768 size = sizeof(buffer)-1;
770 dbg("uevent_size=%zi\n", size);
772 /* start of event payload */
773 bufpos = strlen(buffer)+1;
774 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
778 /* validate message */
779 pos = strchr(buffer, '@');
781 err("invalid uevent '%s'\n", buffer);
787 if (msg->action == NULL) {
788 info("no ACTION in payload found, skip event '%s'\n", buffer);
793 if (strcmp(msg->action, buffer) != 0) {
794 err("ACTION in payload does not match uevent, skip event '%s'\n", buffer);
802 static void asmlinkage sig_handler(int signum)
810 /* set flag, then write to pipe if needed */
811 sigchilds_waiting = 1;
818 /* write to pipe, which will wakeup select() in our mainloop */
819 write(signal_pipe[WRITE_END], "", 1);
822 static void udev_done(int pid, int exitstatus)
824 /* find msg associated with pid and delete it */
825 struct udevd_uevent_msg *msg;
827 list_for_each_entry(msg, &running_list, node) {
828 if (msg->pid == pid) {
829 info("seq %llu, pid [%d] exit with %i, %ld seconds old\n", msg->seqnum, msg->pid,
830 exitstatus, time(NULL) - msg->queue_time);
831 msg->exitstatus = exitstatus;
832 msg_queue_delete(msg);
834 /* there may be events waiting with the same devpath */
841 static void reap_sigchilds(void)
847 pid = waitpid(-1, &status, WNOHANG);
850 if (WIFEXITED(status))
851 status = WEXITSTATUS(status);
852 else if (WIFSIGNALED(status))
853 status = WTERMSIG(status) + 128;
856 udev_done(pid, status);
860 static int init_udevd_socket(void)
862 struct sockaddr_un saddr;
864 const int feature_on = 1;
867 memset(&saddr, 0x00, sizeof(saddr));
868 saddr.sun_family = AF_LOCAL;
869 strcpy(saddr.sun_path, UDEVD_CTRL_SOCK_PATH);
870 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path);
871 /* translate leading '@' to abstract namespace */
872 if (saddr.sun_path[0] == '@')
873 saddr.sun_path[0] = '\0';
875 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
876 if (udevd_sock == -1) {
877 err("error getting socket: %s\n", strerror(errno));
881 /* the bind takes care of ensuring only one copy running */
882 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
884 err("bind failed: %s\n", strerror(errno));
890 /* enable receiving of the sender credentials */
891 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
896 static int init_uevent_netlink_sock(void)
898 struct sockaddr_nl snl;
899 const int buffersize = 16 * 1024 * 1024;
902 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
903 snl.nl_family = AF_NETLINK;
904 snl.nl_pid = getpid();
907 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
908 if (uevent_netlink_sock == -1) {
909 err("error getting socket: %s\n", strerror(errno));
913 /* set receive buffersize */
914 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
916 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
918 err("bind failed: %s\n", strerror(errno));
919 close(uevent_netlink_sock);
920 uevent_netlink_sock = -1;
926 static void export_initial_seqnum(void)
928 char filename[PATH_SIZE];
933 strlcpy(filename, sysfs_path, sizeof(filename));
934 strlcat(filename, "/kernel/uevent_seqnum", sizeof(filename));
935 fd = open(filename, O_RDONLY);
937 len = read(fd, seqnum, sizeof(seqnum)-1);
941 strcpy(seqnum, "0\n");
944 strlcpy(filename, udev_root, sizeof(filename));
945 strlcat(filename, "/.udev/uevent_seqnum", sizeof(filename));
946 create_path(filename);
947 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
949 write(fd, seqnum, len);
954 int main(int argc, char *argv[])
958 struct sigaction act;
963 static const struct option options[] = {
964 { "daemon", 0, NULL, 'd' },
965 { "debug-trace", 0, NULL, 't' },
966 { "debug", 0, NULL, 'D' },
967 { "help", 0, NULL, 'h' },
968 { "version", 0, NULL, 'V' },
974 logging_init("udevd");
977 dbg("version %s\n", VERSION);
980 option = getopt_long(argc, argv, "dDthV", options, NULL);
993 if (udev_log_priority < LOG_INFO)
994 udev_log_priority = LOG_INFO;
997 printf("Usage: udevd [--help] [--daemon] [--debug-trace] [--debug] [--version]\n");
1000 printf("%s\n", VERSION);
1007 if (getuid() != 0) {
1008 fprintf(stderr, "root privileges required\n");
1009 err("root privileges required\n");
1013 /* make sure std{in,out,err} fd's are in a sane state */
1014 fd = open("/dev/null", O_RDWR);
1016 fprintf(stderr, "cannot open /dev/null\n");
1017 err("cannot open /dev/null\n");
1019 if (fd > STDIN_FILENO)
1020 dup2(fd, STDIN_FILENO);
1021 if (write(STDOUT_FILENO, 0, 0) < 0)
1022 dup2(fd, STDOUT_FILENO);
1023 if (write(STDERR_FILENO, 0, 0) < 0)
1024 dup2(fd, STDERR_FILENO);
1026 /* init sockets to receive events */
1027 if (init_udevd_socket() < 0) {
1028 if (errno == EADDRINUSE) {
1029 fprintf(stderr, "another udev daemon already running\n");
1030 err("another udev daemon already running\n");
1033 fprintf(stderr, "error initializing udevd socket\n");
1034 err("error initializing udevd socket\n");
1040 if (init_uevent_netlink_sock() < 0) {
1041 fprintf(stderr, "error initializing netlink socket\n");
1042 err("error initializing netlink socket\n");
1047 /* setup signal handler pipe */
1048 retval = pipe(signal_pipe);
1050 err("error getting pipes: %s\n", strerror(errno));
1054 retval = fcntl(signal_pipe[READ_END], F_GETFL, 0);
1056 err("error fcntl on read pipe: %s\n", strerror(errno));
1059 retval = fcntl(signal_pipe[READ_END], F_SETFL, retval | O_NONBLOCK);
1061 err("error fcntl on read pipe: %s\n", strerror(errno));
1065 retval = fcntl(signal_pipe[WRITE_END], F_GETFL, 0);
1067 err("error fcntl on write pipe: %s\n", strerror(errno));
1070 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, retval | O_NONBLOCK);
1072 err("error fcntl on write pipe: %s\n", strerror(errno));
1076 /* parse the rules and keep them in memory */
1078 udev_rules_init(&rules, 1);
1080 export_initial_seqnum();
1088 dbg("daemonized fork running\n");
1091 err("fork of daemon failed: %s\n", strerror(errno));
1095 dbg("child [%u] running, parent exits\n", pid);
1101 /* redirect std{out,err} fd's */
1103 dup2(fd, STDOUT_FILENO);
1104 dup2(fd, STDERR_FILENO);
1105 if (fd > STDERR_FILENO)
1108 /* set scheduling priority for the daemon */
1109 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
1114 /* become session leader */
1116 dbg("our session is %d\n", sid);
1118 /* OOM_DISABLE == -17 */
1119 fd = open("/proc/self/oom_adj", O_RDWR);
1121 err("error disabling OOM: %s\n", strerror(errno));
1123 write(fd, "-17", 3);
1127 fd = open("/dev/kmsg", O_WRONLY);
1129 const char *str = "<6>udevd version " VERSION " started\n";
1131 write(fd, str, strlen(str));
1135 /* set signal handlers */
1136 memset(&act, 0x00, sizeof(struct sigaction));
1137 act.sa_handler = (void (*)(int)) sig_handler;
1138 sigemptyset(&act.sa_mask);
1139 act.sa_flags = SA_RESTART;
1140 sigaction(SIGINT, &act, NULL);
1141 sigaction(SIGTERM, &act, NULL);
1142 sigaction(SIGCHLD, &act, NULL);
1143 sigaction(SIGHUP, &act, NULL);
1145 /* watch rules directory */
1146 inotify_fd = inotify_init();
1147 if (inotify_fd >= 0) {
1148 if (udev_rules_dir[0] != '\0') {
1149 inotify_add_watch(inotify_fd, udev_rules_dir,
1150 IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1152 char filename[PATH_MAX];
1154 inotify_add_watch(inotify_fd, UDEV_PREFIX "/lib/udev/rules.d",
1155 IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1156 inotify_add_watch(inotify_fd, SYSCONFDIR "/udev/rules.d",
1157 IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1159 /* watch dynamic rules directory */
1160 strlcpy(filename, udev_root, sizeof(filename));
1161 strlcat(filename, "/.udev/rules.d", sizeof(filename));
1162 inotify_add_watch(inotify_fd, filename,
1163 IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1165 } else if (errno == ENOSYS)
1166 err("the kernel does not support inotify, udevd can't monitor rules file changes\n");
1168 err("inotify_init failed: %s\n", strerror(errno));
1170 /* maximum limit of forked childs */
1171 value = getenv("UDEVD_MAX_CHILDS");
1173 max_childs = strtoul(value, NULL, 10);
1175 int memsize = mem_size_mb();
1177 max_childs = 128 + (memsize / 4);
1179 max_childs = UDEVD_MAX_CHILDS;
1181 info("initialize max_childs to %u\n", max_childs);
1183 /* start to throttle forking if maximum number of _running_ childs is reached */
1184 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
1186 max_childs_running = strtoull(value, NULL, 10);
1188 int cpus = cpu_count();
1190 max_childs_running = 8 + (8 * cpus);
1192 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
1194 info("initialize max_childs_running to %u\n", max_childs_running);
1196 /* clear environment for forked event processes */
1199 /* export log_priority , as called programs may want to follow that setting */
1200 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
1206 maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
1207 maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
1208 maxfd = UDEV_MAX(maxfd, inotify_fd);
1210 while (!udev_exit) {
1211 struct udevd_uevent_msg *msg;
1215 FD_SET(signal_pipe[READ_END], &readfds);
1216 FD_SET(udevd_sock, &readfds);
1217 FD_SET(uevent_netlink_sock, &readfds);
1218 if (inotify_fd >= 0)
1219 FD_SET(inotify_fd, &readfds);
1221 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
1224 err("error in select: %s\n", strerror(errno));
1228 /* get control message */
1229 if (FD_ISSET(udevd_sock, &readfds))
1232 /* get netlink message */
1233 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
1234 msg = get_netlink_msg();
1236 msg_queue_insert(msg);
1239 /* received a signal, clear our notification pipe */
1240 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
1243 read(signal_pipe[READ_END], &buf, sizeof(buf));
1246 /* rules directory inotify watch */
1247 if ((inotify_fd >= 0) && FD_ISSET(inotify_fd, &readfds)) {
1250 /* discard all possible events, we can just reload the config */
1251 if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes > 0) {
1255 buf = malloc(nbytes);
1257 err("error getting buffer for inotify, disable watching\n");
1261 read(inotify_fd, buf, nbytes);
1266 /* rules changed, set by inotify or a HUP signal */
1267 if (reload_config) {
1269 udev_rules_cleanup(&rules);
1270 udev_rules_init(&rules, 1);
1273 /* forked child has returned */
1274 if (sigchilds_waiting) {
1275 sigchilds_waiting = 0;
1282 msg_queue_manager();
1288 udev_rules_cleanup(&rules);
1292 if (signal_pipe[READ_END] >= 0)
1293 close(signal_pipe[READ_END]);
1294 if (signal_pipe[WRITE_END] >= 0)
1295 close(signal_pipe[WRITE_END]);
1297 if (udevd_sock >= 0)
1299 if (inotify_fd >= 0)
1301 if (uevent_netlink_sock >= 0)
1302 close(uevent_netlink_sock);