* [PATCH net 1/3] rtnetlink: look the device up under RTNL in full rtnl_getlink() requests
2026-11-29 22:36 [PATCH net 0/3] rtnetlink: build full rtnl_getlink() replies in one RTNL section again Chris Bannister
@ 2026-11-29 22:36 ` Chris Bannister
2026-11-29 22:36 ` [PATCH net 2/3] rtnetlink: queue the rtnl_getlink() reply before releasing RTNL Chris Bannister
2026-11-29 22:36 ` [PATCH net 3/3] selftests: net: test that RTM_GETLINK answers from the target netns Chris Bannister
2 siblings, 0 replies; 4+ messages in thread
From: Chris Bannister @ 2026-11-29 22:36 UTC (permalink / raw)
To: Eric Dumazet, Jakub Kicinski, Paolo Abeni, David S. Miller,
netdev
Cc: Willem de Bruijn, Simon Horman, Kuniyuki Iwashima, Shuah Khan,
linux-kselftest, regressions, linux-kernel, stable
Until commit e896e5c0734b ("rtnetlink: do not acquire RTNL in
rtnl_getlink() with RTEXT_FILTER_NAME_ONLY"), rtnetlink_rcv_msg()
held RTNL around the whole of rtnl_getlink(), so the device lookup
in the target netns and rtnl_fill_ifinfo() shared one RTNL critical
section. Unregistering a device, renaming it and moving it to another
netns all require RTNL, so a successful reply always described the
device that the requested ifindex or name resolved to in the target
netns at the time the reply was built.
That commit made the handler run without RTNL and moved the
lookup, for every request, into an RCU section that ends before
rtnl_lock(). A request without RTEXT_FILTER_NAME_ONLY now sleeps on
RTNL holding only a reference to the device. That commit checked
nothing once it owned the lock. Commit f3c496105472 ("rtnetlink:
use dev_isalive() in rtnl_getlink()") then added dev_isalive()
there, since renamed netif_is_alive(), which tests reg_state alone.
__dev_change_net_namespace() leaves reg_state at NETREG_REGISTERED,
so when the device was moved to another netns in the meantime, the
reply is built for a device that is no longer in the target netns. It
carries the ifindex and name the device has in its new netns, along
with its addresses, statistics and remaining attributes, and the link
netnsids are computed against the requester's netns. In the same way,
a request by name can be answered with a device that was renamed while
the request waited and no longer has that name. The rename case was
found by reading the code and has not been reproduced.
Do the lookup under RTNL again whenever the reply is built under RTNL,
which restores the previous guarantee for every reply built under RTNL
without enumerating what may have changed across the lock. The RCU
lookup and the device reference remain for RTEXT_FILTER_NAME_ONLY
requests, which are the ones that avoid RTNL, and the reference is
dropped as soon as the reply is filled.
This makes the netif_is_alive() check unnecessary: a device found in
the netns tables under RTNL is registered, since
unregister_netdevice_many_notify() unlists a device before it marks
it NETREG_UNREGISTERING, without releasing RTNL in between.
A RTEXT_FILTER_NAME_ONLY reply that is built without RTNL still comes
from a device that can be moved or renamed after the lookup, and this
patch does not change that. It does change a name-only request that
falls back to RTNL after -EMSGSIZE: the retry looks the device up again
like any other locked request, so it describes the device that the
ifindex or name resolves to at that point, or returns -ENODEV.
The netns case was discovered by an AI code review agent reading the
series that contains e896e5c0734b, and was then reproduced on
unmodified kernel.org builds in a VM, with no kernel change and no
error injection. The reproducer sends RTM_GETLINK by name in one
netns while a dummy device moves between that netns and another, and
counts successful replies that carry the ifindex the device has in the
other netns. It counted 6 such replies in 5,000 iterations on
the regressing commit and none in 5,000 on its parent. The
reproducer is at [1].
Testing: on v7.4-rc4 the reproducer counted 47 such replies in 20,000
iterations, and none in 20,000 with this series applied, with the same
config, host and binary. A build of the series with lockdep,
PROVE_RCU, KASAN and DEBUG_ATOMIC_SLEEP ran the same reproducers with
no lockdep, KASAN, RCU or might-sleep report and stayed untainted. The
selftest added in 3/3 failed in each of 20 runs on the regressing
commit and on v7.4-rc4, and passed in each of 20 runs with this series
applied. No other kernel selftests were run.
AI assistance: the investigation, the reproducers, the fix, the
selftest and these commit messages were produced by AI tools directed
by the submitter: Claude Opus 5.5, Claude Fable 5.2 and Claude Sonnet
5.5 (Anthropic), and OpenAI gpt-6.2-sol and gpt-6.2-astra via Codex.
Claude Fable 5.2 found this bug in its review of the series and
designed the fix, and gpt-6.2-astra reviewed it.
I read rtnl_getlink() and __dev_change_net_namespace(), reproduced the
regression on a bare-metal machine with a separate C reproducer, and
reviewed this patch.
Link: https://github.com/zariel/linux-rtnetlink-getlink-regressions/tree/main/nlrace/go-netns [1]
Fixes: e896e5c0734b ("rtnetlink: do not acquire RTNL in rtnl_getlink() with RTEXT_FILTER_NAME_ONLY")
Cc: stable@vger.kernel.org
Closes: https://lore.kernel.org/all/20261129215752.251291-1-kernel@cbannister.uk/
Signed-off-by: Chris Bannister <kernel@cbannister.uk>
---
net/core/rtnetlink.c | 41 +++++++++++++++++++++++++----------------
1 file changed, 25 insertions(+), 16 deletions(-)
diff --git a/net/core/rtnetlink.c b/net/core/rtnetlink.c
index e141340172ce..985cb3b51bc5 100644
--- a/net/core/rtnetlink.c
+++ b/net/core/rtnetlink.c
@@ -4316,9 +4316,9 @@ static int rtnl_getlink(struct sk_buff *skb, struct nlmsghdr *nlh,
struct net *net = sock_net(skb->sk);
struct nlattr *tb[IFLA_MAX + 1];
netdevice_tracker dev_tracker;
- struct net_device *dev = NULL;
struct net *tgt_net = net;
u32 ext_filter_mask = 0;
+ struct net_device *dev;
struct ifinfomsg *ifm;
struct sk_buff *nskb;
int netnsid = -1;
@@ -4344,29 +4344,25 @@ static int rtnl_getlink(struct sk_buff *skb, struct nlmsghdr *nlh,
ext_filter_mask = nla_get_u32(tb[IFLA_EXT_MASK]);
ifm = nlmsg_data(nlh);
- rcu_read_lock();
- if (ifm->ifi_index > 0) {
- dev = dev_get_by_index_rcu(tgt_net, ifm->ifi_index);
- } else if (tb[IFLA_IFNAME] || tb[IFLA_ALT_IFNAME]) {
- dev = rtnl_dev_get_rcu(tgt_net, tb);
- } else {
- rcu_read_unlock();
+ if (ifm->ifi_index <= 0 && !tb[IFLA_IFNAME] && !tb[IFLA_ALT_IFNAME]) {
err = -EINVAL;
goto out;
}
- netdev_hold(dev, &dev_tracker, GFP_ATOMIC);
- rcu_read_unlock();
-
- err = -ENODEV;
- if (dev == NULL)
- goto out;
need_rtnl = !(ext_filter_mask & RTEXT_FILTER_NAME_ONLY);
retry:
if (need_rtnl) {
+ /* Look the device up under the lock the reply is built under:
+ * RTNL keeps it registered in tgt_net, with the requested
+ * ifindex or name, until the reply is complete.
+ */
rtnl_lock();
- if (!netif_is_alive(dev)) {
+ if (ifm->ifi_index > 0)
+ dev = __dev_get_by_index(tgt_net, ifm->ifi_index);
+ else
+ dev = rtnl_dev_get(tgt_net, tb);
+ if (!dev) {
err = -ENODEV;
nskb = NULL;
goto unlock;
@@ -4378,6 +4374,18 @@ static int rtnl_getlink(struct sk_buff *skb, struct nlmsghdr *nlh,
* already report carrier on, even if it doesn't work yet.
*/
linkwatch_sync_dev(dev);
+ } else {
+ rcu_read_lock();
+ if (ifm->ifi_index > 0)
+ dev = dev_get_by_index_rcu(tgt_net, ifm->ifi_index);
+ else
+ dev = rtnl_dev_get_rcu(tgt_net, tb);
+ netdev_hold(dev, &dev_tracker, GFP_ATOMIC);
+ rcu_read_unlock();
+ if (!dev) {
+ err = -ENODEV;
+ goto out;
+ }
}
err = -ENOBUFS;
@@ -4387,6 +4395,8 @@ static int rtnl_getlink(struct sk_buff *skb, struct nlmsghdr *nlh,
RTM_NEWLINK, NETLINK_CB(skb).portid,
nlh->nlmsg_seq, 0, 0, ext_filter_mask,
0, NULL, 0, netnsid, GFP_KERNEL);
+ if (!need_rtnl)
+ netdev_put(dev, &dev_tracker);
unlock:
if (need_rtnl)
@@ -4407,7 +4417,6 @@ static int rtnl_getlink(struct sk_buff *skb, struct nlmsghdr *nlh,
err = rtnl_unicast(nskb, net, NETLINK_CB(skb).portid);
}
out:
- netdev_put(dev, &dev_tracker);
if (netnsid >= 0)
put_net(tgt_net);
--
2.56.0
^ permalink raw reply related [flat|nested] 4+ messages in thread* [PATCH net 2/3] rtnetlink: queue the rtnl_getlink() reply before releasing RTNL
2026-11-29 22:36 [PATCH net 0/3] rtnetlink: build full rtnl_getlink() replies in one RTNL section again Chris Bannister
2026-11-29 22:36 ` [PATCH net 1/3] rtnetlink: look the device up under RTNL in full rtnl_getlink() requests Chris Bannister
@ 2026-11-29 22:36 ` Chris Bannister
2026-11-29 22:36 ` [PATCH net 3/3] selftests: net: test that RTM_GETLINK answers from the target netns Chris Bannister
2 siblings, 0 replies; 4+ messages in thread
From: Chris Bannister @ 2026-11-29 22:36 UTC (permalink / raw)
To: Eric Dumazet, Jakub Kicinski, Paolo Abeni, David S. Miller,
netdev
Cc: Willem de Bruijn, Simon Horman, Kuniyuki Iwashima, Shuah Khan,
linux-kselftest, regressions, linux-kernel, stable
A socket that is subscribed to RTNLGRP_LINK and also sends RTM_GETLINK
requests for a single link can be sent a reply built from older link
state after a notification built from newer state. systemd-networkd
uses RTM_GETLINK during link initialisation to catch up with pending
RTM_NEWLINK messages (src/network/networkd-link.c) and applies the
reply as the current state, so such a reply can leave it recording a
link as having no carrier although the preceding notification reported
carrier. That is consistent with the VM boots where this was found:
the console showed the link gain carrier and then lose it, and DHCP
did not start. That networkd acted on a stale reply is inferred from
the networkd source, since no failing boot was traced. The
reply-after-notification order itself is shown by the reproducer and
the delayed-kernel comparison described below.
rtmsg_ifinfo() and its callers build and send link notifications in
one RTNL hold. Until the commit below, RTM_GETLINK was an RTNL-locked
doit, so rtnl_getlink() built its reply and passed it to
rtnl_unicast() inside the RTNL hold taken by rtnetlink_rcv_msg(). A
reply and such notifications addressed to the same socket were
therefore enqueued in the order in which they were built.
That commit made the handler RTNL_FLAG_DOIT_UNLOCKED so that
RTEXT_FILTER_NAME_ONLY requests could skip RTNL. Requests which still
need RTNL now take it inside rtnl_getlink(), but drop it between
rtnl_fill_ifinfo() and rtnl_unicast():
CPU0 (RTM_GETLINK) CPU1 (linkwatch or RTM_SETLINK)
rtnl_lock()
rtnl_fill_ifinfo() [carrier off]
rtnl_unlock()
rtnl_lock()
netif_state_change()
rtmsg_ifinfo() [carrier on]
rtnl_unlock()
rtnl_unicast() [carrier off]
Send the reply before releasing RTNL, as the handler did before.
nlmsg_unicast() passes MSG_DONTWAIT, so it does not wait for space in
the receive buffer, and the reply skb is new and unshared. The send
adds the netlink trim, socket filter, tap, enqueue and wakeup to the
RTNL hold of a successful request. rtnl_stats_get() is an existing
RTNL-locked doit that calls rtnl_unicast() in the same way.
What this restores is the enqueue order, on one socket, between a
single-link reply built under RTNL and notifications that are built and
sent in one RTNL hold. It does not make the content of a message
atomic: a driver changes the carrier bit without RTNL, also between the
reads of ifi_flags and IFLA_CARRIER. Notifications sent without RTNL,
such as the bridge port state changes sent from the STP timers and
wireless extension events, were not ordered against replies before the
commit below and are not now. Multipart dumps are not ordered either,
since netlink_dump() queues each skb after the dump callback has
released RTNL.
RTEXT_FILTER_NAME_ONLY requests remain lockless and their replies
remain unordered. Such a reply contains ifi_flags, so it can report a
carrier state older than a notification already received. No mainline
release has ordered these replies. A name-only request that falls back
to RTNL after -EMSGSIZE is sent before unlocking like any other reply
built under RTNL, and is still a name-only reply.
This was triggered in CI testing: VM boots of a 7.3 kernel under
systemd-networkd intermittently lost carrier just after gaining it and
got no DHCP lease. Source analysis pointed at the unlocked window
before rtnl_unicast(), and a reproducer confirmed it. On unmodified
kernel.org builds in a VM, with no kernel change and no error
injection, the reproducer bisects to e896e5c0734b: it shows the
inversion there and not on its parent, 00888feb6014. The reproducer,
nlrace.c [1], uses one socket subscribed to
RTNLGRP_LINK that sends RTM_GETLINK for a dummy device whose carrier
another thread toggles, and counts replies queued after a notification
built from newer state.
The effect on networkd was checked with modified kernels that widen
the window. v7.3.6 with msleep(50) inserted between rtnl_unlock() and
rtnl_unicast() lost DHCP on 17 of 100 boots of a stock Ubuntu 24.04
guest (systemd-networkd 255.4). The same kernel with the v7.3 backport
of this series and the same delay, which then follows the send, lost
DHCP on none of 100 boots.
Testing: on v7.4-rc4, nlrace.c saw 8 to 20 inversions in each of five
60-second runs, and none in any of five runs with this series applied,
with the same config, host and binary. A build of the series with
lockdep, PROVE_RCU, KASAN and DEBUG_ATOMIC_SLEEP ran the same
reproducers with no lockdep, KASAN, RCU or might-sleep report and
stayed untainted. There is no deterministic selftest for this
ordering; the selftest in 3/3 covers the netns case fixed by 1/3. No
other kernel selftests were run.
AI assistance: the investigation, the reproducers, the fix, the
selftest and these commit messages were produced by AI tools directed
by the submitter: Claude Opus 5.5, Claude Fable 5.2 and Claude Sonnet
5.5 (Anthropic), and OpenAI gpt-6.2-sol and gpt-6.2-astra via Codex.
Claude Fable 5.2 designed the fix and gpt-6.2-astra reviewed it.
The submitter reproduced the inversion with nlrace.c on a bare-metal
machine, reviewed nlrace.c, read rtnl_getlink() and reviewed this
patch.
Link: https://github.com/zariel/linux-rtnetlink-getlink-regressions/blob/main/nlrace/c/nlrace.c [1]
Fixes: e896e5c0734b ("rtnetlink: do not acquire RTNL in rtnl_getlink() with RTEXT_FILTER_NAME_ONLY")
Cc: stable@vger.kernel.org
Closes: https://lore.kernel.org/all/20261129214529.4059732-1-kernel@cbannister.uk/
Signed-off-by: Chris Bannister <kernel@cbannister.uk>
---
net/core/rtnetlink.c | 32 ++++++++++++++++++++------------
1 file changed, 20 insertions(+), 12 deletions(-)
diff --git a/net/core/rtnetlink.c b/net/core/rtnetlink.c
index 985cb3b51bc5..bdb054211c3e 100644
--- a/net/core/rtnetlink.c
+++ b/net/core/rtnetlink.c
@@ -4397,24 +4397,32 @@ static int rtnl_getlink(struct sk_buff *skb, struct nlmsghdr *nlh,
0, NULL, 0, netnsid, GFP_KERNEL);
if (!need_rtnl)
netdev_put(dev, &dev_tracker);
+ if (!err) {
+ /* rtmsg_ifinfo() builds and queues link notifications in one
+ * RTNL hold. A reply built under RTNL is queued before the
+ * lock is released, so that it cannot reach a socket listening
+ * to RTNLGRP_LINK after such a notification that was built
+ * later.
+ */
+ err = rtnl_unicast(nskb, net, NETLINK_CB(skb).portid);
+ if (need_rtnl)
+ rtnl_unlock();
+ goto out;
+ }
unlock:
if (need_rtnl)
rtnl_unlock();
- if (err < 0) {
- kfree_skb(nskb);
- if (err == -EMSGSIZE) {
- if (!need_rtnl) {
- /* Some altnames were added, retry with RTNL. */
- need_rtnl = true;
- goto retry;
- }
- /* -EMSGSIZE implies BUG in if_nlmsg_size */
- WARN_ON_ONCE(1);
+ kfree_skb(nskb);
+ if (err == -EMSGSIZE) {
+ if (!need_rtnl) {
+ /* Some altnames were added, retry with RTNL. */
+ need_rtnl = true;
+ goto retry;
}
- } else {
- err = rtnl_unicast(nskb, net, NETLINK_CB(skb).portid);
+ /* -EMSGSIZE implies BUG in if_nlmsg_size */
+ WARN_ON_ONCE(1);
}
out:
if (netnsid >= 0)
--
2.56.0
^ permalink raw reply related [flat|nested] 4+ messages in thread* [PATCH net 3/3] selftests: net: test that RTM_GETLINK answers from the target netns
2026-11-29 22:36 [PATCH net 0/3] rtnetlink: build full rtnl_getlink() replies in one RTNL section again Chris Bannister
2026-11-29 22:36 ` [PATCH net 1/3] rtnetlink: look the device up under RTNL in full rtnl_getlink() requests Chris Bannister
2026-11-29 22:36 ` [PATCH net 2/3] rtnetlink: queue the rtnl_getlink() reply before releasing RTNL Chris Bannister
@ 2026-11-29 22:36 ` Chris Bannister
2 siblings, 0 replies; 4+ messages in thread
From: Chris Bannister @ 2026-11-29 22:36 UTC (permalink / raw)
To: Eric Dumazet, Jakub Kicinski, Paolo Abeni, David S. Miller,
netdev
Cc: Willem de Bruijn, Simon Horman, Kuniyuki Iwashima, Shuah Khan,
linux-kselftest, regressions, linux-kernel
Add a test for a property that RTM_GETLINK replies built under RTNL
lost in commit e896e5c0734b ("rtnetlink: do not acquire RTNL in
rtnl_getlink() with RTEXT_FILTER_NAME_ONLY"): a request by ifindex
is not answered with a device that has left the netns.
The test does not need to win a race. It holds RTNL, queues the netns
move and the request behind it in that order, and goes on only when
it has seen each of them wait for the lock, so a kernel that looks
the device up before taking RTNL fails on every run.
A SIOCGIFCONF ioctl holds RTNL for the test: dev_ifconf() copies to
the user buffer under RTNL, and the buffer is a userfaultfd page,
so the ioctl sleeps there until the test resolves the fault. The test
then sends the RTM_SETLINK that moves a dummy device to another netns
under another ifindex, waits until that thread sleeps uninterruptibly,
sends the RTM_GETLINK and waits for it in the same way. Both are then
on the wait list of the RTNL mutex in this order, and the request has
done any lookup it does before taking RTNL. Once the fault is resolved
the device moves first, and the request must fail with -ENODEV. With
a lookup before RTNL it succeeds, and carries the ifindex the device
has in the other netns.
The order relies on the mutex waking its waiters in the order in which
they slept, and on RTNL being the only place where the two requests
sleep uninterruptibly. If the request is nevertheless answered with
the device as it was before the move, the test is skipped.
The test needs CONFIG_USERFAULTFD, which is added to the config,
and is skipped without it.
Testing: on vanilla kernel.org builds in a VM with CONFIG_USERFAULTFD=y,
the test failed in each of 20 runs on that commit and on v7.4-rc4,
and passed in each of 20 runs on its parent and on
v7.4-rc4 with 1/3 and 2/3 applied. None of the 80 runs was skipped.
AI assistance: this test and this commit message were produced by AI
tools directed by the submitter: Claude Opus 5.5, Claude Fable 5.2 and
Claude Sonnet 5.5 (Anthropic), and OpenAI gpt-6.2-sol and
gpt-6.2-astra via Codex. Claude Fable 5.2 designed the test.
The submitter read the test and follows its method, and has not run
it.
Signed-off-by: Chris Bannister <kernel@cbannister.uk>
---
tools/testing/selftests/net/.gitignore | 1 +
tools/testing/selftests/net/Makefile | 2 +
tools/testing/selftests/net/config | 1 +
tools/testing/selftests/net/rtnl_getlink.c | 356 +++++++++++++++++++++
4 files changed, 360 insertions(+)
create mode 100644 tools/testing/selftests/net/rtnl_getlink.c
diff --git a/tools/testing/selftests/net/.gitignore b/tools/testing/selftests/net/.gitignore
index 27761239d069..78dc4b9c9c9a 100644
--- a/tools/testing/selftests/net/.gitignore
+++ b/tools/testing/selftests/net/.gitignore
@@ -33,6 +33,7 @@ reuseport_bpf
reuseport_bpf_cpu
reuseport_bpf_numa
reuseport_dualstack
+rtnl_getlink
rxtimestamp
sctp_hello
sctp_ifwdtsn
diff --git a/tools/testing/selftests/net/Makefile b/tools/testing/selftests/net/Makefile
index baea3e7f0f8f..ea5cea74c649 100644
--- a/tools/testing/selftests/net/Makefile
+++ b/tools/testing/selftests/net/Makefile
@@ -198,6 +198,7 @@ TEST_GEN_PROGS := \
reuseport_bpf_cpu \
reuseport_bpf_numa \
reuseport_dualstack \
+ rtnl_getlink \
sk_bind_sendto_listen \
sk_connect_zero_addr \
sk_so_peek_off \
@@ -245,6 +246,7 @@ include ynl.mk
$(OUTPUT)/epoll_busy_poll: LDLIBS += -lcap
$(OUTPUT)/reuseport_bpf_numa: LDLIBS += -lnuma
+$(OUTPUT)/rtnl_getlink: LDLIBS += -lpthread
$(OUTPUT)/tcp_mmap: LDLIBS += -lpthread -lcrypto
$(OUTPUT)/tcp_inq: LDLIBS += -lpthread
$(OUTPUT)/bind_bhash: LDLIBS += -lpthread
diff --git a/tools/testing/selftests/net/config b/tools/testing/selftests/net/config
index 3e7ce41bd64d..a10c6e7220d4 100644
--- a/tools/testing/selftests/net/config
+++ b/tools/testing/selftests/net/config
@@ -134,6 +134,7 @@ CONFIG_TEST_BLACKHOLE_DEV=m
CONFIG_TLS=m
CONFIG_TRACEPOINTS=y
CONFIG_TUN=y
+CONFIG_USERFAULTFD=y
CONFIG_USER_NS=y
CONFIG_VETH=y
CONFIG_VLAN_8021Q=y
diff --git a/tools/testing/selftests/net/rtnl_getlink.c b/tools/testing/selftests/net/rtnl_getlink.c
new file mode 100644
index 000000000000..03d578870673
--- /dev/null
+++ b/tools/testing/selftests/net/rtnl_getlink.c
@@ -0,0 +1,356 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * An RTM_GETLINK request without RTEXT_FILTER_NAME_ONLY is answered under
+ * RTNL, with a device that is in the target netns when the reply is built.
+ *
+ * The test does not depend on winning a race. It holds RTNL in a SIOCGIFCONF
+ * ioctl whose copy_to_user() is stopped by userfaultfd, queues a netns move
+ * and then the request behind it, and goes on only after it has seen each of
+ * them wait for the lock.
+ */
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <poll.h>
+#include <pthread.h>
+#include <sched.h>
+#include <stdio.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+#include <net/if.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <sys/socket.h>
+#include <sys/syscall.h>
+#include <linux/netlink.h>
+#include <linux/rtnetlink.h>
+#include <linux/userfaultfd.h>
+
+#include "kselftest_harness.h"
+
+#define DEV_NAME "getlink0"
+#define WAIT_MS 10000
+
+struct req {
+ struct nlmsghdr nlh;
+ struct ifinfomsg ifm;
+ char attrs[128];
+};
+
+static void req_init(struct req *req, int type, int flags, __u32 seq,
+ int ifindex)
+{
+ memset(req, 0, sizeof(*req));
+ req->nlh.nlmsg_len = NLMSG_LENGTH(sizeof(req->ifm));
+ req->nlh.nlmsg_type = type;
+ req->nlh.nlmsg_flags = NLM_F_REQUEST | flags;
+ req->nlh.nlmsg_seq = seq;
+ req->ifm.ifi_family = AF_UNSPEC;
+ req->ifm.ifi_index = ifindex;
+}
+
+static struct rtattr *req_put(struct req *req, int type, const void *data,
+ int len)
+{
+ struct rtattr *rta;
+
+ rta = (void *)req + NLMSG_ALIGN(req->nlh.nlmsg_len);
+ rta->rta_type = type;
+ rta->rta_len = RTA_LENGTH(len);
+ if (len)
+ memcpy(RTA_DATA(rta), data, len);
+ req->nlh.nlmsg_len = NLMSG_ALIGN(req->nlh.nlmsg_len) +
+ RTA_ALIGN(rta->rta_len);
+ return rta;
+}
+
+static int rtnl_open(__u32 groups)
+{
+ struct sockaddr_nl addr = {
+ .nl_family = AF_NETLINK,
+ .nl_groups = groups,
+ };
+ int fd;
+
+ fd = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE);
+ if (fd < 0)
+ return -1;
+ if (bind(fd, (struct sockaddr *)&addr, sizeof(addr))) {
+ close(fd);
+ return -1;
+ }
+ return fd;
+}
+
+/* Returns 0 or the negative errno carried by the kernel's ack. */
+static int rtnl_ack(int fd)
+{
+ char buf[4096];
+ struct nlmsghdr *nlh = (void *)buf;
+ int len;
+
+ len = recv(fd, buf, sizeof(buf), 0);
+ if (len < 0)
+ return -errno;
+ if (!NLMSG_OK(nlh, len) || nlh->nlmsg_type != NLMSG_ERROR)
+ return -EPROTO;
+ return ((struct nlmsgerr *)NLMSG_DATA(nlh))->error;
+}
+
+static int rtnl_talk(int fd, struct req *req)
+{
+ req->nlh.nlmsg_flags |= NLM_F_ACK;
+ if (send(fd, req, req->nlh.nlmsg_len, 0) < 0)
+ return -errno;
+ return rtnl_ack(fd);
+}
+
+static int dummy_add(int fd)
+{
+ struct rtattr *linkinfo;
+ struct req req;
+
+ req_init(&req, RTM_NEWLINK, NLM_F_CREATE | NLM_F_EXCL, 1, 0);
+ req_put(&req, IFLA_IFNAME, DEV_NAME, sizeof(DEV_NAME));
+ linkinfo = req_put(&req, IFLA_LINKINFO, NULL, 0);
+ req_put(&req, IFLA_INFO_KIND, "dummy", sizeof("dummy"));
+ linkinfo->rta_len = (void *)&req + req.nlh.nlmsg_len - (void *)linkinfo;
+
+ return rtnl_talk(fd, &req);
+}
+
+static long now_ms(void)
+{
+ struct timespec ts;
+
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
+}
+
+static void sleep_ms(int ms)
+{
+ struct timespec ts = { .tv_nsec = ms * 1000000 };
+
+ nanosleep(&ts, NULL);
+}
+
+struct sender {
+ int fd;
+ struct req req;
+ pid_t tid;
+ int err;
+ char reply[8192];
+ int reply_len;
+};
+
+/* Sends one request, which blocks in the kernel for as long as the request
+ * is being handled, and reads the answer.
+ */
+static void *sender_thread(void *arg)
+{
+ struct sender *s = arg;
+
+ __atomic_store_n(&s->tid, syscall(SYS_gettid), __ATOMIC_RELEASE);
+ if (send(s->fd, &s->req, s->req.nlh.nlmsg_len, 0) < 0) {
+ s->err = errno;
+ return NULL;
+ }
+ s->reply_len = recv(s->fd, s->reply, sizeof(s->reply), 0);
+ if (s->reply_len < 0)
+ s->err = errno;
+ return NULL;
+}
+
+static int netns_open(void)
+{
+ return open("/proc/thread-self/ns/net", O_RDONLY | O_CLOEXEC);
+}
+
+static int lo_up(int fd)
+{
+ struct ifreq ifr = { .ifr_name = "lo" };
+
+ if (ioctl(fd, SIOCGIFFLAGS, &ifr))
+ return -1;
+ ifr.ifr_flags |= IFF_UP;
+ return ioctl(fd, SIOCSIFFLAGS, &ifr);
+}
+
+struct gifconf {
+ int fd;
+ struct ifconf ifc;
+ int ret;
+};
+
+/* dev_ifconf() copies one ifreq per IPv4 address to ifc_buf under RTNL. */
+static void *gifconf_thread(void *arg)
+{
+ struct gifconf *g = arg;
+
+ g->ret = ioctl(g->fd, SIOCGIFCONF, &g->ifc);
+ return NULL;
+}
+
+static char task_state(pid_t tid)
+{
+ char path[64], buf[512], *p;
+ int fd, len;
+
+ snprintf(path, sizeof(path), "/proc/self/task/%d/stat", tid);
+ fd = open(path, O_RDONLY | O_CLOEXEC);
+ if (fd < 0)
+ return 0;
+ len = read(fd, buf, sizeof(buf) - 1);
+ close(fd);
+ if (len <= 0)
+ return 0;
+ buf[len] = 0;
+ p = strrchr(buf, ')');
+ return p && p[1] == ' ' ? p[2] : 0;
+}
+
+/* Waits until the thread sleeps uninterruptibly, as a task waiting for RTNL
+ * does once the lock's owner is itself asleep.
+ */
+static int wait_blocked(struct sender *s)
+{
+ long start = now_ms();
+ pid_t tid;
+
+ while (now_ms() - start < WAIT_MS) {
+ tid = __atomic_load_n(&s->tid, __ATOMIC_ACQUIRE);
+ if (tid && task_state(tid) == 'D')
+ return 0;
+ sleep_ms(1);
+ }
+ return -1;
+}
+
+TEST(reply_from_target_netns)
+{
+ long page_size = sysconf(_SC_PAGESIZE);
+ struct uffdio_api api = { .api = UFFD_API };
+ struct sender move = {}, get = {};
+ struct pollfd pfd = { .events = POLLIN };
+ pthread_t gifconf_t, move_t, get_t;
+ struct uffdio_register reg = {};
+ struct uffdio_copy copy = {};
+ struct gifconf gifconf = {};
+ int ifindex, new_ifindex;
+ int other_ns, inet;
+ struct nlmsghdr *nlh;
+ struct uffd_msg msg;
+ void *page, *zeroes;
+ int uffd;
+
+ if (unshare(CLONE_NEWNET))
+ SKIP(return, "unshare(CLONE_NEWNET): %s", strerror(errno));
+ other_ns = netns_open();
+ ASSERT_LE(0, other_ns);
+ ASSERT_EQ(0, unshare(CLONE_NEWNET));
+
+ move.fd = rtnl_open(0);
+ ASSERT_LE(0, move.fd);
+ get.fd = rtnl_open(0);
+ ASSERT_LE(0, get.fd);
+ if (dummy_add(move.fd))
+ SKIP(return, "cannot create a dummy device");
+ ifindex = if_nametoindex(DEV_NAME);
+ ASSERT_LT(0, ifindex);
+ new_ifindex = ifindex + 1000;
+
+ /* SIOCGIFCONF needs an address to report: 127.0.0.1 on lo. */
+ inet = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
+ ASSERT_LE(0, inet);
+ ASSERT_EQ(0, lo_up(inet));
+ gifconf.fd = inet;
+ ASSERT_EQ(0, ioctl(inet, SIOCGIFCONF, &gifconf.ifc));
+ ASSERT_LE(sizeof(struct ifreq), gifconf.ifc.ifc_len);
+
+ uffd = syscall(SYS_userfaultfd, O_CLOEXEC);
+ if (uffd < 0)
+ SKIP(return, "userfaultfd: %s", strerror(errno));
+ ASSERT_EQ(0, ioctl(uffd, UFFDIO_API, &api));
+ page = mmap(NULL, page_size, PROT_READ | PROT_WRITE,
+ MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+ ASSERT_NE(MAP_FAILED, page);
+ zeroes = mmap(NULL, page_size, PROT_READ | PROT_WRITE,
+ MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE, -1, 0);
+ ASSERT_NE(MAP_FAILED, zeroes);
+ reg.range.start = (unsigned long)page;
+ reg.range.len = page_size;
+ reg.mode = UFFDIO_REGISTER_MODE_MISSING;
+ ASSERT_EQ(0, ioctl(uffd, UFFDIO_REGISTER, ®));
+
+ /* Hold RTNL: the ioctl faults on the page in copy_to_user(), and
+ * sleeps there until the fault is resolved.
+ */
+ gifconf.ifc.ifc_len = page_size;
+ gifconf.ifc.ifc_buf = page;
+ ASSERT_EQ(0, pthread_create(&gifconf_t, NULL, gifconf_thread,
+ &gifconf));
+ pfd.fd = uffd;
+ ASSERT_EQ(1, poll(&pfd, 1, WAIT_MS));
+ ASSERT_EQ(sizeof(msg), read(uffd, &msg, sizeof(msg)));
+ ASSERT_EQ(UFFD_EVENT_PAGEFAULT, msg.event);
+
+ /* Queue the move to the other netns, where the device gets another
+ * ifindex, as the first waiter for RTNL.
+ */
+ req_init(&move.req, RTM_SETLINK, NLM_F_ACK, 2, ifindex);
+ req_put(&move.req, IFLA_NET_NS_FD, &other_ns, sizeof(other_ns));
+ req_put(&move.req, IFLA_NEW_IFINDEX, &new_ifindex,
+ sizeof(new_ifindex));
+ ASSERT_EQ(0, pthread_create(&move_t, NULL, sender_thread, &move));
+ ASSERT_EQ(0, wait_blocked(&move)) {
+ TH_LOG("the move never waited for RTNL");
+ }
+
+ /* Queue the request behind it. The device is still in this netns,
+ * so a lookup done before taking RTNL finds it.
+ */
+ req_init(&get.req, RTM_GETLINK, 0, 3, ifindex);
+ ASSERT_EQ(0, pthread_create(&get_t, NULL, sender_thread, &get));
+ ASSERT_EQ(0, wait_blocked(&get)) {
+ TH_LOG("the request never waited for RTNL");
+ }
+
+ /* Release RTNL. The mutex wakes its waiters in the order in which
+ * they arrived: the device moves, then the request is answered.
+ */
+ copy.dst = (unsigned long)page;
+ copy.src = (unsigned long)zeroes;
+ copy.len = page_size;
+ ASSERT_EQ(0, ioctl(uffd, UFFDIO_COPY, ©));
+
+ ASSERT_EQ(0, pthread_join(gifconf_t, NULL));
+ ASSERT_EQ(0, pthread_join(move_t, NULL));
+ ASSERT_EQ(0, pthread_join(get_t, NULL));
+ ASSERT_EQ(0, gifconf.ret);
+ ASSERT_EQ(0, move.err);
+ ASSERT_EQ(0, get.err);
+
+ nlh = (void *)move.reply;
+ ASSERT_TRUE(NLMSG_OK(nlh, move.reply_len));
+ ASSERT_EQ(NLMSG_ERROR, nlh->nlmsg_type);
+ ASSERT_EQ(0, ((struct nlmsgerr *)NLMSG_DATA(nlh))->error);
+ ASSERT_EQ(0, if_nametoindex(DEV_NAME));
+
+ nlh = (void *)get.reply;
+ ASSERT_TRUE(NLMSG_OK(nlh, get.reply_len));
+ if (nlh->nlmsg_type == RTM_NEWLINK) {
+ struct ifinfomsg *ifm = NLMSG_DATA(nlh);
+
+ if (ifm->ifi_index == ifindex)
+ SKIP(return, "the request was answered before the move");
+ ASSERT_EQ(ifindex, ifm->ifi_index) {
+ TH_LOG("ifindex %d answered with the device in the other netns, ifindex %d",
+ ifindex, ifm->ifi_index);
+ }
+ }
+ ASSERT_EQ(NLMSG_ERROR, nlh->nlmsg_type);
+ EXPECT_EQ(-ENODEV, ((struct nlmsgerr *)NLMSG_DATA(nlh))->error);
+}
+
+TEST_HARNESS_MAIN
--
2.56.0
^ permalink raw reply related [flat|nested] 4+ messages in thread