2 * Copyright 2015 Denys Vlasenko
4 * Licensed under GPLv2, see file LICENSE in this source tree.
8 //config: bool "uevent"
10 //config: select PLATFORM_LINUX
12 //config: uevent is a netlink listener for kernel uevent notifications
13 //config: sent via netlink. It is usually used for dynamic device creation.
15 //applet:IF_UEVENT(APPLET(uevent, BB_DIR_SBIN, BB_SUID_DROP))
17 //kbuild:lib-$(CONFIG_UEVENT) += uevent.o
19 //usage:#define uevent_trivial_usage
20 //usage: "[PROG [ARGS]]"
21 //usage:#define uevent_full_usage "\n\n"
22 //usage: "uevent runs PROG for every netlink notification."
23 //usage: "\n""PROG's environment contains data passed from the kernel."
24 //usage: "\n""Typical usage (daemon for dynamic device node creation):"
25 //usage: "\n"" # uevent mdev & mdev -s"
28 #include <linux/netlink.h>
30 #define BUFFER_SIZE 16*1024
32 #define env ((char **)&bb_common_bufsiz1)
34 MAX_ENV = COMMON_BUFSIZE / sizeof(env[0]) - 1,
37 #ifndef SO_RCVBUFFORCE
38 #define SO_RCVBUFFORCE 33
40 enum { RCVBUF = 2 * 1024 * 1024 };
42 int uevent_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
43 int uevent_main(int argc UNUSED_PARAM, char **argv)
45 struct sockaddr_nl sa;
50 // Subscribe for UEVENT kernel messages
51 sa.nl_family = AF_NETLINK;
54 sa.nl_groups = 1 << 0;
55 fd = xsocket(AF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
56 xbind(fd, (struct sockaddr *) &sa, sizeof(sa));
59 // Without a sufficiently big RCVBUF, a ton of simultaneous events
60 // can trigger ENOBUFS on read, which is unrecoverable.
63 // find /sys -name uevent -exec sh -c 'echo add >"{}"' ';'
65 // SO_RCVBUFFORCE (root only) can go above net.core.rmem_max sysctl
66 setsockopt_SOL_SOCKET_int(fd, SO_RCVBUF, RCVBUF);
67 setsockopt_SOL_SOCKET_int(fd, SO_RCVBUFFORCE, RCVBUF);
70 socklen_t zl = sizeof(z);
71 getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &z, &zl);
72 bb_error_msg("SO_RCVBUF:%d", z);
81 // In many cases, a system sits for *days* waiting
82 // for a new uevent notification to come in.
83 // We use a fresh mmap so that buffer is not allocated
84 // until kernel actually starts filling it.
85 netbuf = mmap(NULL, BUFFER_SIZE,
86 PROT_READ | PROT_WRITE,
87 MAP_PRIVATE | MAP_ANON,
88 /* ignored: */ -1, 0);
89 if (netbuf == MAP_FAILED)
90 bb_perror_msg_and_die("mmap");
92 // Here we block, possibly for a very long time
93 len = safe_read(fd, netbuf, BUFFER_SIZE - 1);
95 bb_perror_msg_and_die("read");
99 // Each netlink message starts with "ACTION@/path"
100 // (which we currently ignore),
101 // followed by environment variables.
109 if (strchr(s, '=') && idx < MAX_ENV)
119 spawn_and_wait(argv);
122 bb_unsetenv(env[idx++]);
123 munmap(netbuf, BUFFER_SIZE);
126 return 0; // not reached