ipv6: validate cached dsts against the netns route generation
Subsystems (4)
David Ahern
maintainerv2 cover ipv6: validate cached dsts against the netns route generation
From: David Ahern <[email protected]>
IPv6 dsts are validated through a cookie that a holder (socket, dst_cache, xfrm bundle, IPVS, ...) captures from the fn_sernum of the route's node at the time it stores the dst. A route change that lands between the route lookup and that capture is folded into the cookie, and the stale dst then looks valid. Only nexthop object pcpu routes carried a generation of their own, and a pcpu dst that failed its check could be re-stamped and made valid again for every holder (Fixes: 8f34e53b60b3). The reported result is a dst that keeps bypassing a route change, or a learned PMTU, for as long as it is held.
This series stamps every dst with the netns route generation when it is built and validates it with a plain comparison in ip6_dst_check(), the way IPv4 does with rt_genid. A dst is never re-stamped: holders keep seeing a stale dst as stale, and a new one is built for the next lookup. Learned PMTUs and redirects survive a generation change, because a stale exception is replaced by a current copy, not dropped.
1-3: exception insert fixes needed before the exception table is
touched more often: allocate the new entry before the old one is removed, keep a superseded pcpu dst working until its holders notice it is stale (it is put on the uncached list, so device unregister still detaches it), and do not insert an exception whose MTU could not be stored.
4: ip6_link_failure() invalidates the failing dst only, with a stale
mark in its sernum, instead of the whole node.
5: route dumps notice exception inserts on the root through a table
sequence, tb6_excp_seq, rather than through fn_sernum.
6: the core change: stamp and validate dsts against the netns
generation, and refresh stale exceptions. An exception insert invalidates only the pcpu dsts of its own nexthop, tracked with a per-nexthop cpumask, and ip6_dst_check() also fails an uncached RTF_CACHE dst (the FLOWI_FLAG_KNOWN_NH clone, which IPVS keeps in dest->dst_cache) once an exception exists for its destination on any nexthop group member it can have come from.
7: rt_genid_bump_ipv6() becomes a plain counter increment instead of
a walk over every node of every table.
8-9: nexthop object changes that did not bump the generation now do. 10: stamp a dst with the generation sampled before the FIB lookup, not
the one current when it is allocated, so a change that lands during the lookup cannot be folded in.
11-13: selftests: a deleted exception stays deleted after a FIB
change (pmtu.sh), a stale pcpu dst after a nexthop change (fib_tests.sh), and a PMTU learned after IPVS cached its DR route (ipvs.sh).
Known costs and limits:
- Every FIB change bumps the generation of the netns, so every exception becomes stale and is replaced by a copy the next time traffic uses it. That is an allocation per exception revisited, and the replacement takes rt6_exception_lock, which is global. The entry and the writable metrics are allocated before taking it.
- An exception insert still scans the nexthop's whole dirty cpumask, nr_cpu_ids bits, though it only touches the dsts of CPUs that built one.
Changes since non RFC v1
- rebased to top of tree
- added Ralf's reported-by to a few patches
- Patch 6: the stale-clone check for uncached RTF_CACHE dsts, the allocations done before taking rt6_exception_lock, and corrected wording about the cpumask scan.
- New selftest for IPVS DR mode.
David Ahern (13):
ipv6: allocate the exception entry before removing the one it replaces
ipv6: keep a superseded pcpu dst working until its holders notice
ipv6: don't insert a PMTU exception whose MTU could not be stored
ipv6: invalidate the failing dst in ip6_link_failure()
ipv6: tell route dumps about exception inserts with a table sequence
ipv6: validate dsts against the netns route generation
ipv6: make rt_genid_bump_ipv6() a plain counter increment
nexthop: factor out nh_has_f6i()
nexthop: bump the IPv6 route generation on group changes
ipv6: stamp dsts with the generation sampled before the FIB lookup
selftests: net: pmtu: check that a deleted cached exception stays
deleted
selftests: net: fib_tests: Add stale pcpu test
selftests: net: ipvs: check a PMTU learned after the DR route was
cached
include/net/ip6_fib.h | 70 +- include/net/net_namespace.h | 36 +- net/ipv4/nexthop.c | 42 +- net/ipv6/addrconf_core.c | 7 - net/ipv6/fib6_rules.c | 33 +- net/ipv6/ip6_fib.c | 76 +- net/ipv6/route.c | 720 ++++++++++++++++-- tools/testing/selftests/net/fib_tests.sh | 53 +- tools/testing/selftests/net/netfilter/config | 2 + tools/testing/selftests/net/netfilter/ipvs.sh | 81 ++ tools/testing/selftests/net/pmtu.sh | 90 +++ 11 files changed, 1035 insertions(+), 175 deletions(-)
Signature · 1 line
2.54.0 (Apple Git-157)
David Ahern
maintainerPATCH v2 1/13 ipv6: allocate the exception entry before removing the one it replaces
From: David Ahern <[email protected]>
rt6_insert_exception() unlinks the existing exception for a destination before it allocates, with GFP_ATOMIC, the table entry for its replacement. If that allocation fails, what was learned (a reduced PMTU or a redirect gateway) is already gone and the caller gets -ENOMEM, so traffic falls back to the route's own MTU and gateway.
Allocate the entry first. If that fails nothing has been touched and the exception stays as it was.
--- net/ipv6/route.c | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-)
net/ipv6/route.c +14 -9
@@ -1721,8 +1721,8 @@ static int rt6_insert_exception(struct rt6_info *nrt,struct net *net =dev_net (nrt->dst.dev);struct rt6_exception_bucket *bucket;struct fib6_info *f6i = res->f6i; +struct rt6_exception *rt6_ex, *new_ex;struct in6_addr *src_key =NULL ; -struct rt6_exception *rt6_ex;struct fib6_nh *nh = res->nh;int max_depth;int err =0 ;
@@ -1765,19 +1765,24 @@ static int rt6_insert_exception(struct rt6_info *nrt, goto out; } +/* Allocate the new entry before the one it replaces is touched, so +* that running out of memory leaves what was learned in place. +*/ + new_ex =kzalloc_obj (*new_ex,GFP_ATOMIC ); +if (!new_ex) { + err = -ENOMEM ; + goto out; + } + + new_ex->rt6i = nrt; + new_ex->stamp = jiffies; + rt6_ex =__rt6_find_exception_spinlock (&bucket, &nrt->rt6i_dst.addr, src_key);if (rt6_ex)rt6_remove_exception (bucket, rt6_ex); - rt6_ex =kzalloc_obj (*rt6_ex,GFP_ATOMIC ); -if (!rt6_ex) { - err = -ENOMEM ; - goto out; - } - rt6_ex->rt6i = nrt; - rt6_ex->stamp = jiffies; -hlist_add_head_rcu (&rt6_ex->hlist, &bucket->chain); +hlist_add_head_rcu (&new_ex->hlist, &bucket->chain); bucket->depth++;rt6_exception_net (nrt)->ipv6.rt6_stats->fib_rt_cache++;
Signature · 1 line
2.54.0 (Apple Git-157)
David Ahern
maintainerPATCH v2 2/13 ipv6: keep a superseded pcpu dst working until its holders notice
In reply to David AhernFrom: David Ahern <[email protected]>
When rt6_get_pcpu_route() finds that a pcpu dst of a route using a nexthop object has been invalidated, it takes the dst out of its slot and calls dst_dev_put() on it. That points the dst at the blackhole device and makes its output a discard, although the dst may still be
held: by a socket, a tunnel dst_cache, an xfrm bundle, or an skb that has not reached dst_output() yet (a queued or NFQUEUE reinjected packet, async crypto). Those packets are dropped, where the holder would have noticed that the dst is stale at its next check and looked the route up again.
The dst does have to be detached from its device when the device is
unregistered: it is no longer reachable from the FIB, and a holder such as an idle socket can keep it indefinitely, which would hold the device. Put it on the uncached list instead. It keeps working until its holders let go, and rt6_uncached_list_flush_dev() detaches it on unregister like any other uncached dst.
--- net/ipv6/route.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
net/ipv6/route.c +7 -1
@@ -1483,7 +1483,13 @@ static struct rt6_info *rt6_get_pcpu_route(const struct fib6_result *res)/* Paired with READ_ONCE() in __fib6_drop_pcpu_from() */ prev =xchg (p,NULL );if (prev) { -dst_dev_put (&prev->dst); +/* Holders may still be using it until they notice it +* is stale, so keep it working rather than dst_dev_put() +* it, which would turn the packets of anyone who has +* not rechecked yet into drops. Device unregister +* detaches it like any other uncached dst. +*/ +rt6_uncached_list_add (prev);dst_release (&prev->dst); }
Signature · 1 line
2.54.0 (Apple Git-157)
David Ahern
maintainerPATCH v2 3/13 ipv6: don't insert a PMTU exception whose MTU could not be stored
In reply to David AhernFrom: David Ahern <[email protected]>
rt6_do_update_pmtu() sets the MTU of a dst with dst_metric_set(). A dst shares the read-only metrics of its route until it needs its own, and dst_metric_set() allocates writable ones with GFP_ATOMIC on first use, doing nothing if that fails, without telling the caller.
For a PMTU update on a new exception the caller then goes on to insert an exception that has no learned MTU, which lowers nothing, replaces any exception for that destination that was there, and invalidates the cached dsts of the nexthop. For an update on an existing exception the reduction is lost while the stamp that keeps the exception alive is refreshed.
Allocate the writable metrics in rt6_do_update_pmtu() and return an error if that fails. Do not insert the new exception then, and release it. For an exception that is already in use there is nothing to fall back on, but nothing is claimed either: the next packet too big that exceeds its MTU makes the update again.
The handlers that update a dst in place do not take a lock either, and each one decides to lower the MTU from a value it read before. Storing it unconditionally lets a handler that decided on 1400 overwrite a 1280 that another one stored in between. Lower the MTU with a compare and exchange, so that it only ever goes down and a smaller value stored meanwhile is kept.
--- net/ipv6/route.c | 52 +++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 47 insertions(+), 5 deletions(-)
net/ipv6/route.c +47 -5
@@ -1546,6 +1546,34 @@ static struct net *rt6_exception_net(const struct rt6_info *rt) return container_of(rt->dst.ops, struct net, ipv6.ip6_dst_ops); } +/* Lower the MTU in the metrics of @rt to @mtu. +* +* A dst shares the read-only metrics of its route until it needs its own. +* Allocating them can fail, and dst_metric_set() does not say: the PMTU would +* be lost. +* +* Only ever lower it, and with a compare and exchange: PMTU handlers update a +* dst in place without a lock, and each decides to lower the MTU from a value +* it read earlier, so storing unconditionally could overwrite a smaller value +* that another handler stored in between. +*/ +static int rt6_lower_mtu (struct rt6_info *rt,u32 mtu) +{ +u32 *metrics =dst_metrics_write_ptr (&rt->dst); +u32 old; + +if (!metrics) +return -ENOMEM ; + + old =READ_ONCE (metrics[RTAX_MTU -1 ]); +do { +if (old && old <= mtu) +break ; + }while (!try_cmpxchg (&metrics[RTAX_MTU -1 ], &old, mtu)); + +return 0 ; +} +/* Remove rt6_ex from hash table and free the memory * Caller must hold rt6_exception_lock */
@@ -2913,13 +2941,23 @@ static void rt6_update_expires(struct rt6_info *rt0, int timeout) rt0->rt6i_flags |=RTF_EXPIRES ; } -static void rt6_do_update_pmtu (struct rt6_info *rt,u32 mtu) +static int rt6_do_update_pmtu (struct rt6_info *rt,u32 mtu) {struct net *net =dev_net (rt->dst.dev); +int err; + +/* If the MTU cannot be stored the PMTU would be lost and, for a new +* exception, an exception would be inserted that does not lower +* anything. +*/ + err =rt6_lower_mtu (rt, mtu); +if (err) +return err; -dst_metric_set (&rt->dst,RTAX_MTU , mtu); rt->rt6i_flags |=RTF_MODIFIED ;rt6_update_expires (rt,READ_ONCE (net->ipv6.sysctl.ip6_rt_mtu_expires)); + +return 0 ; }static bool rt6_cache_allowed_for_pmtu (const struct rt6_info *rt)
@@ -2960,7 +2998,11 @@ static void __ip6_rt_update_pmtu(struct dst_entry *dst, const struct sock *sk,return ;if (!rt6_cache_allowed_for_pmtu (rt6)) { -rt6_do_update_pmtu (rt6, mtu); +/* If the update cannot be made, the next packet too big that +* exceeds this dst's MTU triggers it again +*/ +if (rt6_do_update_pmtu (rt6, mtu)) +return ;/* update rt6_ex->stamp for cache */ if (rt6->rt6i_flags &RTF_CACHE )rt6_update_exception_stamp_rt (rt6);
@@ -2998,8 +3040,8 @@ static void __ip6_rt_update_pmtu(struct dst_entry *dst, const struct sock *sk, nrt6 =ip6_rt_cache_alloc (&res, daddr, saddr);if (nrt6) { -rt6_do_update_pmtu (nrt6, mtu); -if (rt6_insert_exception (nrt6, &res)) +if (rt6_do_update_pmtu (nrt6, mtu) || +rt6_insert_exception (nrt6, &res))dst_release_immediate (&nrt6->dst); } out_unlock:
Signature · 1 line
2.54.0 (Apple Git-157)
David Ahern
maintainerPATCH v2 4/13 ipv6: invalidate the failing dst in ip6_link_failure()
In reply to David AhernFrom: David Ahern <[email protected]>
When a default route's neighbour fails, ip6_link_failure() writes -1 to the fn_sernum of the route's node so that users of dsts under that node look the route up again and let router selection pick another default router. That invalidates every dst under the node, which for a failing router that can trigger this for every packet sent through it is far more than needed.
Invalidate the failing dst only, which for a pcpu dst is one CPU's copy. Do it by setting the top bit of its sernum: the netns route generation, which a dst with a non-zero sernum is compared against, is always positive, so the dst fails the check and its users do the lookup again, and a pcpu dst that fails it is dropped from its slot and rebuilt. The rest of sernum is left as it was, and setting the bit is idempotent, so concurrent invalidators need no lock.
sernum of a published dst can now change under its readers, so read it with READ_ONCE(), and in rt6_get_cookie() test and return a single sample. A reader that sees the value before the mark and one that sees it after both get a non-zero sernum: setting the bit never makes it zero.
--- include/net/ip6_fib.h | 27 +++++++++++++++++++++++++-- net/ipv6/route.c | 18 +++++++++--------- 2 files changed, 34 insertions(+), 11 deletions(-)
include/net/ip6_fib.h +25 -2
@@ -300,9 +300,14 @@ static inline u32 rt6_get_cookie(const struct rt6_info *rt) {struct fib6_info *from;u32 cookie =0 ; +int sernum; -if (rt->sernum) -return rt->sernum; +/* Can be stale-marked concurrently (rt6_dst_invalidate()): test and +* return one sample. +*/ + sernum =READ_ONCE (rt->sernum); +if (sernum) +return sernum;rcu_read_lock ();
@@ -315,6 +320,24 @@ static inline u32 rt6_get_cookie(const struct rt6_info *rt)return cookie; } +/* An invalidated dst keeps the generation it was built under in the low +* bits, so state derived from it (exceptions) can be stamped with the FIB +* state it actually came from. The top bit makes it fail rt6_is_valid(): +* the netns generation is always positive. +*/ +#define RT6_SERNUM_STALE INT_MIN + +static inline void rt6_dst_invalidate (struct rt6_info *rt) +{ +int sernum =READ_ONCE (rt->sernum); + +/* Do not dirty the cache line of a dst that other CPUs read on the +* fast path when it is already stale. +*/ +if (!(sernum &RT6_SERNUM_STALE )) +WRITE_ONCE (rt->sernum, sernum |RT6_SERNUM_STALE ); +} +static inline void ip6_rt_put (struct rt6_info *rt) {/* dst_release() accepts a NULL parameter.
net/ipv6/route.c +9 -9
@@ -1466,7 +1466,7 @@ static struct rt6_info *ip6_rt_pcpu_alloc(const struct fib6_result *res)static bool rt6_is_valid (const struct rt6_info *rt6) { -return rt6->sernum ==rt_genid_ipv6 (dev_net (rt6->dst.dev)); +return READ_ONCE (rt6->sernum) ==rt_genid_ipv6 (dev_net (rt6->dst.dev)); }/* It should be called with rcu_read_lock() acquired */
@@ -1476,7 +1476,7 @@ static struct rt6_info *rt6_get_pcpu_route(const struct fib6_result *res) pcpu_rt =this_cpu_read (*res->nh->rt6i_pcpu); -if (pcpu_rt && pcpu_rt->sernum && !rt6_is_valid (pcpu_rt)) { +if (pcpu_rt &&READ_ONCE (pcpu_rt->sernum) && !rt6_is_valid (pcpu_rt)) {struct rt6_info *prev, **p; p =this_cpu_ptr (res->nh->rt6i_pcpu);
@@ -2855,7 +2855,7 @@ INDIRECT_CALLABLE_SCOPE struct dst_entry *ip6_dst_check(struct dst_entry *dst, rt =dst_rt6_info (dst); -if (rt->sernum) +if (READ_ONCE (rt->sernum))return rt6_is_valid (rt) ? dst :NULL ;rcu_read_lock ();
@@ -2912,14 +2912,14 @@ static void ip6_link_failure(struct sk_buff *skb)rt6_remove_exception_rt (rt); }else {struct fib6_info *from; -struct fib6_node *fn; +/* Force sockets using this dst to look the route up +* again; a stale-marked sernum never matches the +* netns generation. +*/ from =rcu_dereference (rt->from); -if (from) { - fn =rcu_dereference (from->fib6_node); -if (fn && (rt->rt6i_flags &RTF_DEFAULT )) -WRITE_ONCE (fn->fn_sernum,-1 ); - } +if (from && (rt->rt6i_flags &RTF_DEFAULT )) +rt6_dst_invalidate (rt); }rcu_read_unlock (); }
Signature · 1 line
2.54.0 (Apple Git-157)
David Ahern
maintainerPATCH v2 5/13 ipv6: tell route dumps about exception inserts with a table sequence
In reply to David AhernFrom: David Ahern <[email protected]>
A route dump that is suspended and later resumed restarts from the root if the root node's fn_sernum changed, and the exception dump relies on that happening when an exception is inserted on the root:rt6_insert_exception() calls fib6_update_sernum(), which among other things gives the node a new fn_sernum.
That ties dump consistency to what a change to fn_sernum otherwise means. A fresh fn_sernum can only come from the netns counter, and a locally made-up value could later be issued by the counter to the same node and go unnoticed. Add a per-table tb6_excp_seq, bumped under tb6_lock when an exception is inserted on the root node, and have fib6_dump_table() restart when either it or the root's fn_sernum has changed. The set of inserts a dump notices is the same as before.
Also correct the comment in rt6_nh_dump_exceptions(): only changes to the root's exceptions are noticed, not those under other nodes, where a dump suspended in the middle of a route's exceptions can skip or repeat some of them.
--- include/net/ip6_fib.h | 3 +++ net/ipv6/ip6_fib.c | 25 ++++++++++++++++++++++++- net/ipv6/route.c | 15 ++++++++++----- 3 files changed, 37 insertions(+), 6 deletions(-)
include/net/ip6_fib.h +3 -0
@@ -386,6 +386,7 @@ struct fib6_walker {unsigned int skip;unsigned int count;unsigned int skip_in_node; +unsigned int excp_seq;/* tb6_excp_seq seen by a partial dump */ int (*func)(struct fib6_walker *);void *args; };
@@ -419,6 +420,7 @@ struct fib6_table {struct inet_peer_base tb6_peers;unsigned int flags;unsigned int fib_seq;/* writes protected by rtnl_mutex */ +unsigned int tb6_excp_seq;/* writes under tb6_lock */ struct hlist_head tb6_gc_hlist;/* GC candidates */ #define RT6_TABLE_HAS_DFLT_ROUTER BIT(0) };
@@ -640,6 +642,7 @@ int fib6_tables_dump(struct net *net, struct notifier_block *nb, struct netlink_ext_ack *extack);void fib6_update_sernum (struct net *net,struct fib6_info *rt); +void fib6_update_excp_seq (struct fib6_info *rt);#if IS_ENABLED (CONFIG_IPV6 )void fib6_update_sernum_upto_root (struct net *net,struct fib6_info *rt);#else
net/ipv6/ip6_fib.c +24 -1
@@ -148,6 +148,25 @@ void fib6_update_sernum(struct net *net, struct fib6_info *f6i)WRITE_ONCE (fn->fn_sernum,fib6_new_sernum (net)); } +/* Tell route dumps that an exception was added under @f6i. A dump notices +* a changed tree through the root node, so only an exception on the root +* needs to be visible. Use a table sequence for that, rather than a fresh +* fn_sernum, so that it does not depend on what else a change to fn_sernum +* does: fresh values can only come from the netns counter, and a made-up +* one could later be issued by the counter to the same node. +* Caller holds tb6_lock. +*/ +void fib6_update_excp_seq (struct fib6_info *f6i) +{ +struct fib6_table *table = f6i->fib6_table; +struct fib6_node *fn; + + fn =rcu_dereference_protected (f6i->fib6_node, +lockdep_is_held (&table->tb6_lock)); +if (fn == &table->tb6_root) +WRITE_ONCE (table->tb6_excp_seq, table->tb6_excp_seq +1 ); +} +/* * Auxiliary address test functions for the radix tree. *
@@ -637,12 +656,16 @@ static int fib6_dump_table(struct fib6_table *table, struct sk_buff *skb,if (res >0 ) { cb->args[4 ] =1 ; cb->args[5 ] =READ_ONCE (w->root->fn_sernum); + w->excp_seq =READ_ONCE (table->tb6_excp_seq); } }else {int sernum =READ_ONCE (w->root->fn_sernum); -if (cb->args[5 ] != sernum) { +unsigned int excp_seq =READ_ONCE (table->tb6_excp_seq); + +if (cb->args[5 ] != sernum || w->excp_seq != excp_seq) {/* Begin at the root if the tree changed */ cb->args[5 ] = sernum; + w->excp_seq = excp_seq; w->state =FWS_INIT ; w->node = w->root; w->skip = w->count;
net/ipv6/route.c +10 -5
@@ -1832,6 +1832,7 @@ static int rt6_insert_exception(struct rt6_info *nrt,if (!err) {spin_lock_bh (&f6i->fib6_table->tb6_lock);fib6_update_sernum (net, f6i); +fib6_update_excp_seq (f6i);fib6_add_gc_list (f6i);spin_unlock_bh (&f6i->fib6_table->tb6_lock);fib6_force_start_gc (net);
@@ -6122,11 +6123,15 @@ static int rt6_nh_dump_exceptions(struct fib6_nh *nh, void *arg)continue ; } -/* Expiration of entries doesn't bump sernum, insertion -* does. Removal is triggered by insertion, so we can -* rely on the fact that if entries change between two -* partial dumps, this node is scanned again completely, -* see rt6_insert_exception() and fib6_dump_table(). +/* Expiration of entries doesn't bump anything. An +* insertion on the root node changes the root's +* fn_sernum or tb6_excp_seq, and removal is triggered +* by insertion, so if entries of the root change +* between two partial dumps, the table is scanned +* again, see rt6_insert_exception() and +* fib6_dump_table(). A change under any other node is +* not noticed: a dump suspended in the middle of that +* route's exceptions can skip or repeat some of them. * * Count expired entries we go through as handled * entries that we'll skip next time, in case of partial
Signature · 1 line
2.54.0 (Apple Git-157)
David Ahern
maintainerPATCH v2 6/13 ipv6: validate dsts against the netns route generation
In reply to David AhernFrom: David Ahern <[email protected]>
An rt6_info never carried the fib6 serial number it was created under. rt6_get_cookie() read fn->fn_sernum through rt->from at the time a socket, dst_cache or xfrm bundle stored its cookie, so a change that landed between route lookup and cookie capture was folded into the cookie and a stale dst looked valid. Only nexthop-object pcpu routes were stamped at creation, with the same counter.
net->ipv6.fib6_sernum is already the counter that rt_genid_ipv6() reads and that every FIB change bumps. Stamp every dst with it in ip6_dst_alloc() and validate with a plain comparison in ip6_dst_check(); the remaining checks are that the fib6_info is still in the tree and not expired. rt6_get_cookie() now returns rt->sernum and fib6_get_cookie_safe() goes away. fn_sernum stays for route dump consistency.
This covers every holder. Every IPv6 route dst is allocated with DST_OBSOLETE_FORCE_CHK and stamped at allocation, and holders that cache a dst (sockets, early demux, dst_cache users, xfrm bundles, SCTP, IPVS, nf_flowtable) revalidate it through ip6_dst_check(), whose first test is the generation. The comparison uses the dst's own stamp, not the cookie the holder captured, so a cookie captured late cannot make a stale dst look current.
Validity lives in the dst, so a long-lived dst is never re-stamped by a later lookup: pcpu and exception dsts are shared by every socket and dst_cache that holds them, and re-stamping would make a stale dst valid again for all of them. IPv4 does the same: a stale cached route fails rt_cache_valid() and a new one is allocated, while holders of the old one keep seeing it as stale. Likewise here:
- a pcpu dst that fails the check is dropped from the pcpu slot and rebuilt by rt6_make_pcpu_route().
- an exception dst that fails the check is not handed to users as their dst. The lookup paths that do that then replace it with a current copy that keeps the learned MTU, expiry, redirect gateway and flags, so that a FIB change in the netns does not discard every learned PMTU and redirect. The copy is stamped like any other dst built from the lookup. Callers that only read an exception, not hand it out as a dst, still find it whatever its generation: the MTU of a FIB lookup in ip6_mtu_from_fib6(), which bpf_fib_lookup() uses and which never goes through a dst lookup that would refresh it, deleting an exception, and matching a redirect gateway. Hiding it from them would make a learned PMTU or redirect disappear from those until some packet to that destination refreshed it.
With source-prefix routes an exception can be keyed by the flow's own source address or by the route's source prefix. The exact one is found first, and a stale exact one is refreshed in preference to a current one under the prefix key, as the exact one would be returned if nothing were stale.
The stale exception is found without rt6_exception_lock, so the replacement only goes ahead if it is still the exception for that destination once the lock is held, and the state is copied under the lock. If another CPU has installed a newer exception, or the exception was removed on purpose (aged out, link failure, route delete), the copy is dropped and the lookup uses whatever is there
now: a replacement from an older snapshot must not overwrite the newer exception or bring back a deleted one. If the replacement cannot be made for lack of memory the stale exception stays, and the lookup misses; the next one tries again.
The replacement is swapped in with hlist_replace_rcu(), not unlinked and re-added: nothing invalidates pcpu dsts for a refresh, so a lockless lookup that ran in a gap between the two would miss the exception and build a pcpu dst that ignores it. The swap also keeps the entry's place in its chain, which route dumps count, and the bucket depth. A new dst shares the read-only metrics of its route and writable ones are allocated on first use, with dst_metric_set() silently doing nothing if that fails. The copy gets writable metrics up front, so that failing to is treated like any other allocation failure instead of replacing the exception with a copy that lost its PMTU, and a later merge into it does not have to allocate. A stale exception whose MTU is no longer below the route's is dropped rather than failing every refresh, unless it is a redirect:
its PMTU may have been lowered in place and then caught up with by a device MTU change, and the gateway is still worth keeping, so only the PMTU is forgotten and the copy carries the route's own MTU, as a new redirect exception does. The old exception is put
on the uncached list, not dst_dev_put(): its holders keep a working dst until they notice it is stale, and device unregister detaches it.
If the replacement cannot be made for lack of memory, the lookup returns some other dst: a pcpu dst or a clone stamped with the current generation, which would bypass the stale exception until the next PMTU update, since nothing invalidates pcpu dsts for a refresh. The lookup marks the dst it returns stale in that case, so its users look the route up, and try the replacement, again.
An in-place PMTU update of a held exception does not take rt6_exception_lock, so it can land on the old dst while a replacement is being made, or after it. The identity check cannot see that. __ip6_rt_update_pmtu() already follows such an update with an update of the exception's stamp, which stays lockless, as before, while the updated dst is still the exception in the table, the common case. When it is not, that step now takes the lock and merges the update into the exception currently in the table (smaller PMTU wins, earlier expiry wins, as for an in-place update), so the lock orders it against any replacement in progress. A replacement that swaps in its copy while the update sees the old dst in the table is caught by a barrier pairing: the updater does smp_mb() between the update and its lookup, the replacement does smp_mb() after the swap and merges into the copy whatever changed on the old dst since it was copied. Either the updater finds the copy or the replacement sees the update, so the lower PMTU is not lost. Neither path orders the merge against a handler updating the current exception in place. Both only ever lower the MTU, the merge and rt6_do_update_pmtu(), with the same compare and exchange (rt6_lower_mtu()), and the merge lowers the expiry the same way: a smaller value stored by one is kept whichever order they run in.
The device MTU change path, which runs under the lock and can also raise an exception's PMTU, is not covered by that.
Creating a PMTU or redirect exception must not invalidate every dst in the namespace, which bumping the netns generation would do: a burst of packet-too-big messages would make all sockets and dst_caches look their routes up again. IPv4 limits this to the nexthop:update_or_create_fnhe() marks only that nexthop's cached dsts stale. Do the same here. rt6_insert_exception() marks the sernum of the fib6_nh's pcpu dsts stale, with rt6_dst_invalidate() as ip6_link_failure() does, instead of calling fib6_update_sernum(), so their users look the route up once and find the exception. The top bit, not zero, means the low bits still say which generation the dst was built under, so that state derived from it can be stamped with that instead of the generation current at allocation.
That only reaches pcpu slots that are already populated, and the lookup checks the exception table before it builds a pcpu dst. A lookup that missed the exception can install its pcpu dst after the writer scanned the slots, and that dst, stamped with the still-current generation, would ignore the exception until the next PMTU update. Close this the way the fib6_destroying handshake in fib6_purge_rt() does: the writer issues smp_mb() between publishing the exception and reading the slots, and ip6_pol_route() looks the exception up again for its own flow after the fully ordered cmpxchg() that installs the pcpu dst. Whichever side runs second sees the other. The re-check runs only when a pcpu dst has to be built.
The pcpu invalidation does not reach the RTF_CACHE clone that ip6_pol_route() makes for FLOWI_FLAG_KNOWN_NH: it is not in rt6i_pcpu and holders such as the IPVS dest->dst_cache keep it. ip6_dst_check() therefore also fails an uncached RTF_CACHE dst when its nexthop has an exception for the dst's destination, so that its holders look the route up and find the learned PMTU.
Visiting every possible CPU on each exception insert would make a burst of packet-too-big messages cost the possible CPU count each, on large systems. Each fib6_nh therefore keeps a cpumask of the CPUs that installed a pcpu dst since the last invalidation: rt6_make_pcpu_route() sets its CPU's bit after the install, and the invalidation visits, tests and clears only those. The per-CPU dst accesses and invalidations of an insert follow the dsts created rather than the number of possible CPUs, and a burst of exceptions invalidates each dst once. Finding the set bits still scans the whole mask, nr_cpu_ids bits, on every insert that does not replace an exception, which is a few words even on large systems. The mask is allocated and freed with the pcpu array, and the handshake above covers it: the installer orders its mark before the re-check, the writer orders the publish before reading the mask.
An exception insert no longer changes any fn_sernum, so route dumps depend on tb6_excp_seq alone for exceptions on the root node, as the dump patch before this one arranged.
The smp_wmb() in __fib6_update_sernum_upto_root() paired with the smp_rmb() in fib6_get_cookie_safe(), so that a lockless reader that saw a new fn_sernum also saw the route inserted before it. That reader is gone. The remaining fn_sernum readers, the route dumps, take tb6_lock after reading it and the writers hold it, so drop the barrier.
--- include/net/ip6_fib.h | 51 +--- net/ipv6/ip6_fib.c | 14 +- net/ipv6/route.c | 600 ++++++++++++++++++++++++++++++++++++++---- 3 files changed, 559 insertions(+), 106 deletions(-)
include/net/ip6_fib.h +9 -42
@@ -9,6 +9,7 @@#ifndef _IP6_FIB_H#define _IP6_FIB_H +#include <linux/cpumask.h> #include <linux/ipv6_route.h> #include <linux/rtnetlink.h> #include <linux/spinlock.h>
@@ -152,6 +153,11 @@ struct fib6_nh {#endif struct rt6_info *__percpu *rt6i_pcpu; +/* CPUs that installed a dst in rt6i_pcpu since the last time an +* exception insert invalidated them, so that it does not have to +* look at every possible CPU. +*/ +cpumask_var_t rt6i_pcpu_dirty;struct rt6_exception_bucket __rcu *rt6i_exception_bucket; };
@@ -273,51 +279,12 @@ static inline bool fib6_check_expired(const struct fib6_info *f6i)return false; } -/* Function to safely get fn->fn_sernum for passed in rt -* and store result in passed in cookie. -* Return true if we can get cookie safely -* Return false if not -*/ -static inline bool fib6_get_cookie_safe (const struct fib6_info *f6i, -u32 *cookie) -{ -struct fib6_node *fn; -bool status = false; - - fn =rcu_dereference (f6i->fib6_node); - -if (fn) { - *cookie =READ_ONCE (fn->fn_sernum); -/* pairs with smp_wmb() in __fib6_update_sernum_upto_root() */ -smp_rmb (); - status = true; - } - -return status; -} -static inline u32 rt6_get_cookie (const struct rt6_info *rt) { -struct fib6_info *from; -u32 cookie =0 ; -int sernum; - -/* Can be stale-marked concurrently (rt6_dst_invalidate()): test and -* return one sample. +/* sernum is the netns route generation the dst was created under; +* ip6_dst_check() compares it to the current one. */ - sernum =READ_ONCE (rt->sernum); -if (sernum) -return sernum; - -rcu_read_lock (); - - from =rcu_dereference (rt->from); -if (from) -fib6_get_cookie_safe (from, &cookie); - -rcu_read_unlock (); - -return cookie; +return READ_ONCE (rt->sernum); }/* An invalidated dst keeps the generation it was built under in the low
net/ipv6/ip6_fib.c +6 -8
@@ -148,12 +148,12 @@ void fib6_update_sernum(struct net *net, struct fib6_info *f6i)WRITE_ONCE (fn->fn_sernum,fib6_new_sernum (net)); } -/* Tell route dumps that an exception was added under @f6i. A dump notices -* a changed tree through the root node, so only an exception on the root -* needs to be visible. Use a table sequence for that, rather than a fresh -* fn_sernum, so that it does not depend on what else a change to fn_sernum -* does: fresh values can only come from the netns counter, and a made-up -* one could later be issued by the counter to the same node. +/* Tell route dumps that an exception was added under @f6i without +* invalidating cached dsts: those follow the netns generation, which this +* leaves alone. A dump notices a changed tree through the root node, so +* only an exception on the root needs to be visible. Fresh fn_sernum values +* can only come from the netns counter, so use a table sequence rather than +* a made-up fn_sernum that the counter could later issue again. * Caller holds tb6_lock. */ void fib6_update_excp_seq (struct fib6_info *f6i)
@@ -1455,8 +1455,6 @@ static void __fib6_update_sernum_upto_root(struct fib6_info *rt,struct fib6_node *fn =rcu_dereference_protected (rt->fib6_node,lockdep_is_held (&rt->fib6_table->tb6_lock)); -/* paired with smp_rmb() in fib6_get_cookie_safe() */ -smp_wmb ();while (fn) {WRITE_ONCE (fn->fn_sernum, sernum); fn = rcu_dereference_protected(fn->parent,
net/ipv6/route.c +544 -56
816 lines not on this page · raw message
Signature · 1 line
2.54.0 (Apple Git-157)
David Ahern
maintainerPATCH v2 7/13 ipv6: make rt_genid_bump_ipv6() a plain counter increment
In reply to David AhernFrom: David Ahern <[email protected]>
rt_genid_bump_ipv6() called fib6_flush_trees() through a function pointer. That walked every node of every table to write a new fn_sernum, so that cookies derived from fn_sernum would mismatch.
Cached dsts are now validated against net->ipv6.fib6_sernum itself, so the walk no longer invalidates anything. Do what rt_genid_bump_ipv4() does and increment the counter, keeping fib6_new_sernum()'s wrap to 1 so the value is never 0.
This makes nexthop, address and FIB rule changes cheap, and stops them from touching fn_sernum, which route dumps use to detect that a tree changed: a dump is no longer restarted by events that do not change the tree.
With the walk gone, drop the __fib6_flush_trees pointer and its export, fib6_new_sernum() in favour of the new helper, and the sernum handling in fib6_cleaner that only the walk used.
--- include/net/net_namespace.h | 26 ++++++++++++++----- net/ipv6/addrconf_core.c | 7 ----- net/ipv6/ip6_fib.c | 51 ++++++------------------------------- 3 files changed, 27 insertions(+), 57 deletions(-)
include/net/net_namespace.h +19 -7
@@ -556,18 +556,30 @@ static inline int rt_genid_ipv6(const struct net *net) {return atomic_read (&net->ipv6.fib6_sernum); } -#endif -static inline void rt_genid_bump_ipv4 (struct net *net) +/* Invalidate every cached IPv6 dst in @net. Returns the new generation, +* which is never 0. +*/ +static inline int rt_genid_bump_ipv6 (struct net *net) { -atomic_inc (&net->ipv4.rt_genid); +int new, old =atomic_read (&net->ipv6.fib6_sernum); + +do { + new = old <INT_MAX ? old +1 :1 ; + }while (!atomic_try_cmpxchg (&net->ipv6.fib6_sernum, &old, new)); + +return new; } +#else +static inline int rt_genid_bump_ipv6 (struct net *net) +{ +return 0 ; +} +#endif -extern void (*__fib6_flush_trees)(struct net *net); -static inline void rt_genid_bump_ipv6 (struct net *net) +static inline void rt_genid_bump_ipv4 (struct net *net) { -if (__fib6_flush_trees) -__fib6_flush_trees (net); +atomic_inc (&net->ipv4.rt_genid); }#if IS_ENABLED (CONFIG_IEEE802154_6LOWPAN )
net/ipv6/addrconf_core.c +0 -7
@@ -9,13 +9,6 @@#include <net/addrconf.h> #include <net/ip.h> -/* if ipv6 module registers this function is used by xfrm to force all -* sockets to relookup their nodes - this is fairly expensive, be -* careful -*/ -void (*__fib6_flush_trees)(struct net *); -EXPORT_SYMBOL (__fib6_flush_trees); -#define IPV6_ADDR_SCOPE_TYPE (scope) ((scope) << 16)static inline unsigned int ipv6_addr_scope2type (unsigned int scope)
net/ipv6/ip6_fib.c +8 -43
129 lines not on this page · raw message
Signature · 1 line
2.54.0 (Apple Git-157)
David Ahern
maintainerPATCH v2 8/13 nexthop: factor out nh_has_f6i()
In reply to David AhernFrom: David Ahern <[email protected]>
nh_rt_cache_flush() open codes a locked check of whether any IPv6 routes use a nexthop. Move it into a helper, placed ahead of remove_nexthop_from_groups(), so the next patch can use it there as well.
No functional change.
--- net/ipv4/nexthop.c | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-)
net/ipv4/nexthop.c +12 -5
@@ -2109,6 +2109,17 @@ remove_nh_grp_entry(struct net *net, struct nh_grp_entry *nhge,return false; } +static bool nh_has_f6i (struct nexthop *nh) +{ +bool have_f6i; + +spin_lock_bh (&nh->lock); + have_f6i = !list_empty (&nh->f6i_list); +spin_unlock_bh (&nh->lock); + +return have_f6i; +} +static bool __must_check remove_nexthop_from_groups (struct net *net,struct nexthop *nh,struct nl_info *nlinfo)
@@ -2248,16 +2259,12 @@ static void nh_rt_cache_flush(struct net *net, struct nexthop *nh, struct nexthop *replaced_nh) {struct nh_group *nhg; -bool have_f6i;int i;if (!list_empty (&nh->fi_list))rt_cache_flush (net); -spin_lock_bh (&nh->lock); - have_f6i = !list_empty (&nh->f6i_list); -spin_unlock_bh (&nh->lock); -if (have_f6i) +if (nh_has_f6i (nh))rt_genid_bump_ipv6 (net);/* if an IPv6 group was replaced, we have to release all old
Signature · 1 line
2.54.0 (Apple Git-157)
David Ahern
maintainerPATCH v2 9/13 nexthop: bump the IPv6 route generation on group changes
In reply to David AhernFrom: David Ahern <[email protected]>
IPv6 dsts are invalidated by bumping the netns route generation, but two nexthop object changes did not do so:
- Replacing a nexthop that is a member of a group only bumped if the member itself had IPv6 routes, not when routes used a group containing it.
- Removing a member from a group republishes the group array without any bump, so dsts built from the old group stayed valid.
Bump in both cases when IPv6 routes use the nexthop, directly or through a group.
--- net/ipv4/nexthop.c | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-)
net/ipv4/nexthop.c +25 -2
@@ -2120,6 +2120,21 @@ static bool nh_has_f6i(struct nexthop *nh)return have_f6i; } +/* true if IPv6 routes use @nh directly or through a group containing it */ +static bool nh_used_by_f6i (struct nexthop *nh) +{ +struct nh_grp_entry *nhge; + +if (nh_has_f6i (nh)) +return true; + +list_for_each_entry (nhge, &nh->grp_list, nh_list) +if (nh_has_f6i (nhge->nh_parent)) +return true; + +return false; +} +static bool __must_check remove_nexthop_from_groups (struct net *net,struct nexthop *nh,struct nl_info *nlinfo)
@@ -2127,6 +2142,7 @@ remove_nexthop_from_groups(struct net *net, struct nexthop *nh,struct nh_grp_entry *nhge, *tmp;LIST_HEAD (deferred_free);bool need_flush = false; +bool have_f6i = false;/* If there is nothing to do, let's avoid the costly call to * synchronize_net()
@@ -2134,13 +2150,19 @@ remove_nexthop_from_groups(struct net *net, struct nexthop *nh,if (list_empty (&nh->grp_list))return false; -list_for_each_entry_safe (nhge, tmp, &nh->grp_list, nh_list) +list_for_each_entry_safe (nhge, tmp, &nh->grp_list, nh_list) { + have_f6i |=nh_has_f6i (nhge->nh_parent); need_flush |=remove_nh_grp_entry (net, nhge, nlinfo, &deferred_free); + }/* make sure all see the newly published array before releasing rtnl */ synchronize_net (); +/* a group lost a member: dsts built from the old group are stale */ +if (have_f6i) +rt_genid_bump_ipv6 (net); +/* Now safe to free percpu stats — all RCU readers have finished */ list_for_each_entry_safe (nhge, tmp, &deferred_free, nh_list) {list_del (&nhge->nh_list);
@@ -2264,7 +2286,8 @@ static void nh_rt_cache_flush(struct net *net, struct nexthop *nh,if (!list_empty (&nh->fi_list))rt_cache_flush (net); -if (nh_has_f6i (nh)) +/* dsts are validated against the netns route generation */ +if (nh_used_by_f6i (nh))rt_genid_bump_ipv6 (net);/* if an IPv6 group was replaced, we have to release all old
Signature · 1 line
2.54.0 (Apple Git-157)
David Ahern
maintainerPATCH v2 10/13 ipv6: stamp dsts with the generation sampled before the FIB lookup
In reply to David AhernFrom: David Ahern <[email protected]>
A dst is stamped with the netns route generation in ip6_dst_alloc(), which runs after the FIB has been read. A route change that lands between the lookup and the allocation is folded into the stamp: the dst was built from the old tree but carries the new generation, so ip6_dst_check() accepts it and it can keep bypassing the new route indefinitely.
Sample the generation before the FIB is walked, carry it in struct fib6_result and stamp every dst built from that result with it. Writers bump the generation after the route change is visible, so a lookup that read the old tree cannot have sampled the new generation; the resulting dst fails ip6_dst_check() as soon as the change is published. Use an acquire read for the sample so the FIB reads are not reordered before it.
The sample is taken in fib6_table_lookup(), ip6_pol_route_lookup() and __ip6_route_redirect(). Exceptions created from an existing dst in __ip6_rt_update_pmtu() and rt6_do_redirect() inherit that dst's stamp instead of the current generation, taken with rt6_dst_sernum() so that a dst already marked stale still passes on the generation it was built under. The copy that replaces a stale exception in rt6_refresh_exception() is stamped from the lookup result too; every caller samples, and a debug warning catches one that does not. Dsts allocated without a lookup result keep the stamp taken in ip6_dst_alloc().
A lookup can also return a cached dst that a later lookup built:
between the sample and reading the pcpu slot, a lookup on the same CPU (softirq, preemption, migration) can run after a FIB change and install a pcpu dst stamped with the newer generation for the route this lookup selected, and an exception can be refreshed by another CPU in the same way. Such a dst passes the validity checks, but the decision it is returned for predates the change. ip6_pol_route() makes a dst whose stamp differs from its sample fail ip6_dst_check(), so its users look the route up again. This also covers callers that use ip6_pol_route() directly, such as seg6, which caches the result in a dst_cache.
The sample is taken for one table. A lookup that reads several, the local table and then the main one, or those the rules select, decides from all of them: a route that is added to a table that was already read, and missed, while a later one is read is not part of the decision, but the dst of the later table is stamped after the change and would look current. fib6_rule_lookup() therefore samples before the first table, and if the dst it returns carries a newer stamp, a change landed in between and the dst is made to fail ip6_dst_check() so that its users look the route up again. That only happens when the generation moved during the lookup.
--- include/net/ip6_fib.h | 11 +++++++++++ include/net/net_namespace.h | 10 ++++++++++ net/ipv6/fib6_rules.c | 33 ++++++++++++++++++++++++++++++--- net/ipv6/route.c | 30 +++++++++++++++++++++++++++++- 4 files changed, 80 insertions(+), 4 deletions(-)
include/net/ip6_fib.h +11 -0
@@ -231,6 +231,11 @@ struct fib6_result {u32 fib6_flags;u8 fib6_type;struct rt6_info *rt6; +/* Route generation sampled before the FIB was read. Dsts built +* from this result are stamped with it, not with the generation +* at allocation time. 0 means not sampled. +*/ +int sernum; };#define for_each_fib6_node_rt_rcu (fn) \
@@ -305,6 +310,12 @@ static inline void rt6_dst_invalidate(struct rt6_info *rt)WRITE_ONCE (rt->sernum, sernum |RT6_SERNUM_STALE ); } +/* The generation @rt was built under, whether or not it is still valid */ +static inline int rt6_dst_sernum (const struct rt6_info *rt) +{ +return READ_ONCE (rt->sernum) & ~RT6_SERNUM_STALE ; +} +static inline void ip6_rt_put (struct rt6_info *rt) {/* dst_release() accepts a NULL parameter.
include/net/net_namespace.h +10 -0
@@ -557,6 +557,16 @@ static inline int rt_genid_ipv6(const struct net *net)return atomic_read (&net->ipv6.fib6_sernum); } +/* Sample the generation before walking the FIB. Writers bump it after the +* route change is visible, so a lookup that sees the old tree cannot sample +* the new generation: whatever dst it builds carries a generation that +* fails ip6_dst_check() once the change lands. +*/ +static inline int rt_genid_ipv6_sample (const struct net *net) +{ +return atomic_read_acquire (&net->ipv6.fib6_sernum); +} +/* Invalidate every cached IPv6 dst in @net. Returns the new generation, * which is never 0. */
net/ipv6/fib6_rules.c +30 -3
@@ -96,10 +96,37 @@ int fib6_lookup(struct net *net, int oif, struct flowi6 *fl6,EXPORT_SYMBOL_GPL (fib6_lookup);#endif +/* A dst that a table lookup returns is stamped with the generation sampled +* before that table was read, so a change that lands after the read cannot +* be folded into the stamp. A lookup that reads several tables, the local +* one and then the main one, or those the rules select, makes its decision +* from all of them. A route that is added to a table that was already read, +* and missed, while a later one is being read is not part of that decision, +* but the dst of the later table is stamped after the change and would look +* current. Sample before the first table, and if the dst carries a newer +* stamp a change landed in between: make it fail ip6_dst_check(), so that +* its users look the route up again. +*/ +static struct dst_entry *fib6_rule_lookup_done (struct dst_entry *dst, +int sernum) +{ +struct rt6_info *rt =dst_rt6_info (dst); + +/* The static null, prohibit and blackhole entries are not made from a +* route and not stamped +*/ +if (rcu_access_pointer (rt->from) &&rt6_dst_sernum (rt) != sernum) +rt6_dst_invalidate (rt); + +return dst; +} +struct dst_entry *fib6_rule_lookup (struct net *net,struct flowi6 *fl6,const struct sk_buff *skb,int flags,pol_lookup_t lookup) { +int sernum =rt_genid_ipv6_sample (net); +if (net->ipv6.fib6_has_custom_rules) {struct fib6_result res = {}; struct fib_lookup_arg arg = {
@@ -116,19 +143,19 @@ struct dst_entry *fib6_rule_lookup(struct net *net, struct flowi6 *fl6, flowi6_to_flowi(fl6), flags, &arg);if (res.rt6) -return &res.rt6->dst; +return fib6_rule_lookup_done (&res.rt6->dst, sernum); }else {struct rt6_info *rt; rt =pol_lookup_func (lookup, net, net->ipv6.fib6_local_tbl, fl6, skb, flags);if (rt != net->ipv6.ip6_null_entry && rt->dst.error != -EAGAIN ) -return &rt->dst; +return fib6_rule_lookup_done (&rt->dst, sernum);ip6_rt_put_flags (rt, flags); rt =pol_lookup_func (lookup, net, net->ipv6.fib6_main_tbl, fl6, skb, flags);if (rt->dst.error != -EAGAIN ) -return &rt->dst; +return fib6_rule_lookup_done (&rt->dst, sernum);ip6_rt_put_flags (rt, flags); }
net/ipv6/route.c +29 -1
@@ -1214,6 +1214,12 @@ static void ip6_rt_copy_init(struct rt6_info *rt, const struct fib6_result *res) rt->rt6i_idev = dev ?in6_dev_get (dev) :NULL ;ip6_rt_init_dst (rt, res); +/* Pair the dst with the generation the FIB was read under, so a +* change between the lookup and this allocation is not folded in. +*/ +if (res->sernum) + rt->sernum = res->sernum; + rt->rt6i_dst = f6i->fib6_dst; rt->rt6i_flags = res->fib6_flags;if (nh->fib_nh_gw_family) {
@@ -1299,6 +1305,7 @@ INDIRECT_CALLABLE_SCOPE struct rt6_info *ip6_pol_route_lookup(struct net *net,bool retry = false;rcu_read_lock (); + res.sernum =rt_genid_ipv6_sample (net); fn =fib6_node_lookup (&table->tb6_root, &fl6->daddr, &fl6->saddr); restart: res.f6i =rcu_dereference (fn->leaf);
@@ -2207,7 +2214,10 @@ static struct rt6_info *rt6_find_cached_rt(const struct fib6_result *res,* Dropping it instead would make every FIB change in the netns discard all * learned PMTUs and redirects. * -* The copy is stamped like any dst built from this result. Caller holds +* The copy is stamped with the generation sampled before the FIB was read, +* like any dst built from this result, so @res must carry that sample: +* without it the copy would be stamped when it is allocated and could look +* current although the FIB changed after the lookup. Caller holds * rcu_read_lock(). */ static struct rt6_info *rt6_refresh_exception(const struct fib6_result *res,
@@ -2218,6 +2228,8 @@ static struct rt6_info *rt6_refresh_exception(const struct fib6_result *res,struct rt6_info *nrt;int err; +DEBUG_NET_WARN_ON_ONCE (!res->sernum); +#ifdef CONFIG_IPV6_SUBTREES if (old->rt6i_src.plen) saddr = &old->rt6i_src.addr;
@@ -2662,6 +2674,7 @@ int fib6_table_lookup(struct net *net, struct fib6_table *table, int oif, {struct fib6_node *fn, *saved_fn; + res->sernum =rt_genid_ipv6_sample (net); fn =fib6_node_lookup (&table->tb6_root, &fl6->daddr, &fl6->saddr); saved_fn = fn;
@@ -2777,6 +2790,17 @@ struct rt6_info *ip6_pol_route(struct net *net, struct fib6_table *table,local_bh_enable (); } out: +/* A cached dst, pcpu or exception, can have been built or refreshed +* by a lookup that ran after a FIB change landed behind our sample: +* it is stamped with the newer generation and passes +* rt6_get_pcpu_route() and the exception lookup, but our decision +* predates that change. Make it fail ip6_dst_check() so that its +* users look the route up again, as fib6_rule_lookup_done() does +* across tables; this also covers callers that bypass that wrapper. +*/ +if (rt &&rt6_dst_sernum (rt) != res.sernum) +rt6_dst_invalidate (rt); +if (!rt) rt = net->ipv6.ip6_null_entry;if (!(flags &RT6_LOOKUP_F_DST_NOREF ))
@@ -3498,6 +3522,8 @@ static void __ip6_rt_update_pmtu(struct dst_entry *dst, const struct sock *sk, res.fib6_flags = res.f6i->fib6_flags; res.fib6_type = res.f6i->fib6_type; +/* derived from @rt6: it is only as current as that dst */ + res.sernum =rt6_dst_sernum (rt6);if (res.f6i->nh) {struct fib6_nh_match_arg arg = {
@@ -3677,6 +3703,7 @@ INDIRECT_CALLABLE_SCOPE struct rt6_info *__ip6_route_redirect(struct net *net,*/ rcu_read_lock (); + res.sernum =rt_genid_ipv6_sample (net); fn =fib6_node_lookup (&table->tb6_root, &fl6->daddr, &fl6->saddr); restart:for_each_fib6_node_rt_rcu (fn) {
@@ -4902,6 +4929,7 @@ static void rt6_do_redirect(struct dst_entry *dst, struct sock *sk, struct sk_bu res.fib6_flags = res.f6i->fib6_flags; res.fib6_type = res.f6i->fib6_type; + res.sernum =rt6_dst_sernum (rt); nrt =ip6_rt_cache_alloc (&res, &msg->dest,NULL );if (!nrt) goto out;
Signature · 1 line
2.54.0 (Apple Git-157)
David Ahern
maintainerPATCH v2 11/13 selftests: net: pmtu: check that a deleted cached exception stays deleted
In reply to David AhernFrom: David Ahern <[email protected]>
Add a test that learns a PMTU from a packet too big message, changes the FIB with a route that has nothing to do with the destination, and deletes the cached exception without looking the destination up in between. After a FIB change the exception's dst is stale, and a lookup that handed it out would replace it with a current copy: deleting it must work on a stale exception too, and nothing may then bring it back.
Check that neither a route lookup nor a packet that fits, which looks the route up as well, creates the exception again, and that a packet that exceeds the PMTU does, through a new packet too big message. The cache is dumped to see the exception, as that does not look the destination up and so does not refresh it.
The test is run again with nexthop objects like the other exception tests, which takes the deletion through the nexthop path.
--- tools/testing/selftests/net/pmtu.sh | 90 +++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+)
tools/testing/selftests/net/pmtu.sh +90 -0
@@ -198,6 +198,14 @@ # - pmtu_ipv6_route_change # Same as above but with IPv6 # +# - pmtu_ipv6_cached_del +# Use the same topology as in pmtu_ipv6. Learn a PMTU from a packet too big +# message, change the FIB with an unrelated route add and, without looking +# the destination up in between, delete the cached exception. Check that +# neither a route lookup nor a packet that does not exceed the PMTU +# brings the exception back, and that a packet that does exceed it +# creates a new one +# # - pmtu_ipv4_mp_exceptions # Use the same topology as in pmtu_ipv4, but add routeable addresses # on host A and B on lo reachable via both routers. Host A and B
@@ -272,6 +280,7 @@ tests=" list_flush_ipv6_exception ipv6: list and flush cached exceptions 1 pmtu_ipv4_route_change ipv4: PMTU exception w/route replace 1 pmtu_ipv6_route_change ipv6: PMTU exception w/route replace 1 + pmtu_ipv6_cached_del ipv6: delete a cached PMTU exception after a FIB change 1 pmtu_ipv4_mp_exceptions ipv4: PMTU multipath nh exceptions 1" # Addressing and routing for tests with routers: four network segments, with
@@ -2377,6 +2386,87 @@ test_pmtu_ipv6_route_change() { test_pmtu_ipvX_route_change 6 } +# Is there a cached exception for ${2} in the namespace ${1}? Dumping the cache +# does not look the destination up, so it does not touch the exception +cached_exception_exists() { + ns_cmd="${1}" + dst="${2}" + + ${ns_cmd} ip -oneline -6 route list cache | grep -qw -- "${dst}" +} + +test_pmtu_ipv6_cached_del() { + setup namespaces routing || return $ksft_skip + trace "${ns_a}" veth_A-R1 "${ns_r1}" veth_R1-A \ + "${ns_r1}" veth_R1-B "${ns_b}" veth_B-R1 \ + "${ns_a}" veth_A-R2 "${ns_r2}" veth_R2-A \ + "${ns_r2}" veth_R2-B "${ns_b}" veth_B-R2 + + dst="${prefix6}:${b_r1}::1" + + # Set up initial MTU values + mtu "${ns_a}" veth_A-R1 2000 + mtu "${ns_r1}" veth_R1-A 2000 + mtu "${ns_r1}" veth_R1-B 1400 + mtu "${ns_b}" veth_B-R1 1400 + + mtu "${ns_a}" veth_A-R2 2000 + mtu "${ns_r2}" veth_R2-A 2000 + mtu "${ns_r2}" veth_R2-B 1500 + mtu "${ns_b}" veth_B-R2 1500 + + # Learn a PMTU from a packet too big message + run_cmd ${ns_a} ${ping6} -q -M want -i 0.1 -w 1 -s 1800 ${dst} + + pmtu="$(route_get_dst_pmtu_from_exception "${ns_a}" ${dst})" + check_pmtu_value "1400" "${pmtu}" "exceeding MTU" || return 1 + + # Change the FIB with a route that has nothing to do with ${dst}. Any + # FIB change makes the cached dsts of the namespace stale. Do not look + # ${dst} up from here to the deletion: that would refresh the + # exception + run_cmd ${ns_a} ip -6 route add unreachable "${prefix6}:ff::/64" + + if ! cached_exception_exists "${ns_a}" ${dst}; then + err " PMTU exception disappeared after an unrelated route add" + return 1 + fi + + # Delete the cached exception + run_cmd ${ns_a} ip -6 route flush cached ${dst} + + if cached_exception_exists "${ns_a}" ${dst}; then + err " PMTU exception still there after deleting it" + return 1 + fi + + # A lookup must not bring it back + run_cmd ${ns_a} ip -6 route get ${dst} + + if cached_exception_exists "${ns_a}" ${dst}; then + err " PMTU exception came back after a route lookup" + return 1 + fi + + # Neither must a packet that fits, which looks the route up as well + run_cmd ${ns_a} ${ping6} -q -c 1 -w 1 -s 1000 ${dst} + + pmtu="$(route_get_dst_pmtu_from_exception "${ns_a}" ${dst})" + check_pmtu_value "" "${pmtu}" "deleting the exception and a lookup" || return 1 + + if cached_exception_exists "${ns_a}" ${dst}; then + err " PMTU exception came back after a packet that fits" + return 1 + fi + + # A packet that exceeds the PMTU does, through a new packet too big + # message. This is what learning it again looks like + run_cmd ${ns_a} ${ping6} -q -M want -i 0.1 -w 1 -s 1800 ${dst} + + pmtu="$(route_get_dst_pmtu_from_exception "${ns_a}" ${dst})" + check_pmtu_value "1400" "${pmtu}" "exceeding MTU after the deletion" || return 1 +} + test_pmtu_ipv4_mp_exceptions() { setup namespaces routing multipath || return $ksft_skip
Signature · 1 line
2.54.0 (Apple Git-157)
David Ahern
maintainerPATCH v2 12/13 selftests: net: fib_tests: Add stale pcpu test
In reply to David AhernFrom: David Ahern <[email protected]>
Avoid regression with stale pcpu route entries and add a selftest
that covers the regression fixed by
8f34e53b60b3 ("ipv6: Use global sernum for dst validation with nexthop objects")
--- tools/testing/selftests/net/fib_tests.sh | 53 +++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-)
tools/testing/selftests/net/fib_tests.sh +52 -1
@@ -14,7 +14,7 @@ TESTS="unregister down carrier nexthop suppress ipv6_notify ipv4_notify \ ipv4_mpath_list ipv6_mpath_list ipv4_mpath_balance ipv6_mpath_balance \ ipv4_mpath_balance_preferred ipv4_mpath_oif ipv4_mpath_oif_nh \ ipv4_mpath_oif_vrf ipv6_mpath_oif ipv6_mpath_oif_nh ipv6_mpath_oif_vrf \ - fib6_ra_to_static fib6_temp_addr_renewal" + fib6_ra_to_static fib6_temp_addr_renewal ipv6_nh_pcpu_stale" VERBOSE=0 PAUSE_ON_FAIL=no
@@ -3228,6 +3228,56 @@ ipv6_mpath_oif_vrf_test() cleanup } +ipv6_nh_pcpu_stale_test() +{ + local cpu + + echo + echo "IPv6 nexthop object stale pcpu dst test" + + if [ ! -x "$(command -v taskset)" ]; then + echo "SKIP: taskset not installed" + return $ksft_skip + fi + + if [ $(nproc) -lt 2 ]; then + echo "SKIP: pcpu test requires multiple cpus" + return $ksft_skip + fi + + setup + + set -e + setup_ns ns2 + $IP link add veth1 type veth peer name veth2 netns $ns2 + $IP link set veth1 up + $IP -6 address add 2001:db8:10::1/64 dev veth1 nodad + ip -netns $ns2 link set lo up + ip -netns $ns2 address add 2001:db8:11::1/128 dev lo + ip netns exec $ns2 sysctl -qw net.ipv6.conf.all.forwarding=1 + ip -netns $ns2 link set veth2 up + ip -netns $ns2 -6 address add 2001:db8:10::2/64 dev veth2 nodad + + $IP -6 nexthop add id 100 via 2001:db8:10::2 dev veth1 + $IP -6 route add 2001:db8:11::1/128 nhid 100 + set +e + + # create a pcpu dst entry on cpu 0 + taskset -a -c 0 $IP -6 route get 2001:db8:11::1 &> /dev/null + + # re-add the route entry + $IP -6 route del 2001:db8:11::1 + $IP -6 route add 2001:db8:11::1/128 nhid 100 + + # cached dst on cpu 0 must have been invalidated + for cpu in 0 1; do + taskset -a -c $cpu $IP -6 route get 2001:db8:11::1 &> /dev/null + log_test $? 0 "Route get on cpu $cpu after route re-add" + done + + cleanup +} + ################################################################################ # usage
@@ -3322,6 +3372,7 @@ do ipv6_mpath_oif_vrf) ipv6_mpath_oif_vrf_test;; fib6_ra_to_static) fib6_ra_to_static;; fib6_temp_addr_renewal) fib6_temp_addr_renewal;; + ipv6_nh_pcpu_stale) ipv6_nh_pcpu_stale_test;; help) echo "Test names: $TESTS"; exit 0;; esac
Signature · 1 line
2.54.0 (Apple Git-157)
I ran my reproducers on this series (on net-next eb6d6c80d354, VM with lockdep and PROVE_RCU). The races are widened with debug-only delays after the lookup, between route selection and the pcpu dst lookup, and before xfrm bundle creation:
- an xfrm policy inserted while a TCP or UDP lookup is in flight: no plaintext once the policy is in place
- a blackhole added while a lookup is in flight, with and without nexthop objects, and a pcpu dst rebuilt by another socket in that
window: nothing sent past the blackhole
- a block policy inserted between policy selection and bundle creation:
nothing sent
- a PMTU exception across a route change in its subtree and elsewhere:
the learned MTU is kept
- a corked UDP datagram across a pcpu dst replacement: sent
The issues I reported on the RFC no longer reproduce. fib_tests ipv6_nh_pcpu_stale and pmtu_ipv6_cached_del pass, no warnings in dmesg.
The reproducers don't cover one lifetime issue in 06/13, which I'll describe there.
Signature · 2 lines
Ralf Lici Mandelbit Srl
Re: [PATCH net-next v2 06/13] ipv6: validate dsts against the netns route generation
In reply to David Ahernnet/ipv6/route.c static struct rt6_info *rt6_get_pcpu_route(const struct fib6_result *res) · line 1491
Quoted 11 lines · David Ahern
net/ipv6/route.c +5
-1@@ -1476,7 +1483,11 @@ static struct rt6_info *rt6_get_pcpu_route(const struct fib6_result *res) pcpu_rt =this_cpu_read (*res->nh->rt6i_pcpu); -if (pcpu_rt &&READ_ONCE (pcpu_rt->sernum) && !rt6_is_valid (pcpu_rt)) { +/* A dst stamped with an older genid stays stale for everyone still +* holding it, as in IPv4. Never re-stamp it; drop it and build a +* new one. +*/ +if (pcpu_rt && !rt6_is_valid (pcpu_rt)) {struct rt6_info *prev, **p;
This now evicts the pcpu dst of every route after any generation change, and the eviction still drops the slot's reference right away (rt6_uncached_list_add and dst_release from 02/13). A reader that took the dst from the slot without a reference can then see it freed, when the only other reference is the child reference of an xfrm bundle:
1. Bundle X, whose child is the pcpu dst P of CPU0, drops its last reference, and dst_release queues dst_destroy_rcu.
2. After that grace period has started, a lookup with RT6_LOOKUP_F_DST_NOREF on CPU0 gets P from the slot inside its RCU section, and is preempted (PREEMPT_RCU) before dst_hold_safe.
3. A lookup on CPU0 after a generation change evicts P and drops the slot's reference, so X's child reference is the last one.
4. X's grace period ends without waiting for the first lookup, and dst_destroy(X) frees P with dst_release_immediate.
Mainline only evicts nexthop-object dsts this way, and fib6_nh_release_dsts has the same pattern, as Sashiko pointed out on my v5:
https://netdev-ai.bots.linux.dev/sashiko/#/patchset/cover.1795537128.git.ralf%40mandelbit.com
Signature · 2 lines
Ralf Lici Mandelbit Srl
David Ahern
maintainerRe: [PATCH net-next v2 06/13] ipv6: validate dsts against the netns route generation
Quoted 29 lines · Ralf Lici
net/ipv6/route.c static struct rt6_info *rt6_get_pcpu_route(const struct fib6_result *res) · line 1491
Quoted 11 lines · David Ahern
net/ipv6/route.c +5
-1@@ -1476,7 +1483,11 @@ static struct rt6_info *rt6_get_pcpu_route(const struct fib6_result *res) pcpu_rt =this_cpu_read (*res->nh->rt6i_pcpu); -if (pcpu_rt &&READ_ONCE (pcpu_rt->sernum) && !rt6_is_valid (pcpu_rt)) { +/* A dst stamped with an older genid stays stale for everyone still +* holding it, as in IPv4. Never re-stamp it; drop it and build a +* new one. +*/ +if (pcpu_rt && !rt6_is_valid (pcpu_rt)) {struct rt6_info *prev, **p;This now evicts the pcpu dst of every route after any generation change, and the eviction still drops the slot's reference right away (
rt6_uncached_list_addanddst_releasefrom 02/13). A reader that took the dst from the slot without a reference can then see it freed, when the only other reference is the child reference of an xfrm bundle:1. Bundle X, whose child is the pcpu dst P of CPU0, drops its last reference, and
dst_releasequeuesdst_destroy_rcu.
2. After that grace period has started, a lookup withRT6_LOOKUP_F_DST_NOREFon CPU0 gets P from the slot inside its RCU section, and is preempted (PREEMPT_RCU) beforedst_hold_safe.
3. A lookup on CPU0 after a generation change evicts P and drops the slot's reference, so X's child reference is the last one.
4. X's grace period ends without waiting for the first lookup, anddst_destroy(X)frees P withdst_release_immediate.
Quoted 2 lines
Mainline only evicts nexthop-object dsts this way, and
fib6_nh_release_dstshas the same pattern, as Sashiko pointed out on my
I do not recall that being intentional. If anything we want consistency across built-in nexthops and separate nexthop objects.
Re: [PATCH net-next v2 06/13] ipv6: validate dsts against the netns route generation
Quoted 30 lines · David Ahern
Quoted 29 lines · Ralf Lici
net/ipv6/route.c static struct rt6_info *rt6_get_pcpu_route(const struct fib6_result *res) · line 1491
Quoted 11 lines · David Ahern
net/ipv6/route.c +5
-1@@ -1476,7 +1483,11 @@ static struct rt6_info *rt6_get_pcpu_route(const struct fib6_result *res) pcpu_rt =this_cpu_read (*res->nh->rt6i_pcpu); -if (pcpu_rt &&READ_ONCE (pcpu_rt->sernum) && !rt6_is_valid (pcpu_rt)) { +/* A dst stamped with an older genid stays stale for everyone still +* holding it, as in IPv4. Never re-stamp it; drop it and build a +* new one. +*/ +if (pcpu_rt && !rt6_is_valid (pcpu_rt)) {struct rt6_info *prev, **p;This now evicts the pcpu dst of every route after any generation change, and the eviction still drops the slot's reference right away (
rt6_uncached_list_addanddst_releasefrom 02/13). A reader that took the dst from the slot without a reference can then see it freed, when the only other reference is the child reference of an xfrm bundle:1. Bundle X, whose child is the pcpu dst P of CPU0, drops its last reference, and
dst_releasequeuesdst_destroy_rcu.
2. After that grace period has started, a lookup withRT6_LOOKUP_F_DST_NOREFon CPU0 gets P from the slot inside its RCU section, and is preempted (PREEMPT_RCU) beforedst_hold_safe.
3. A lookup on CPU0 after a generation change evicts P and drops the slot's reference, so X's child reference is the last one.
4. X's grace period ends without waiting for the first lookup, anddst_destroy(X)frees P withdst_release_immediate.
Quoted 6 lines
Quoted 2 lines
Mainline only evicts nexthop-object dsts this way, and
fib6_nh_release_dstshas the same pattern, as Sashiko pointed out on myI do not recall that being intentional. If anything we want consistency across built-in nexthops and separate nexthop objects.
Ok but the objection is not about the eviction itself. The issue is how the slot's reference is dropped: lookups with RT6_LOOKUP_F_DST_NOREF rely on RCU to keep the pcpu dst alive, and dropping the slot's reference right away breaks that when the only other reference is an xfrm bundle's child, since dst_destroy releases the child with dst_release_immediate. Dropping the slot's reference after a grace period, from a call_rcu callback, would fix it for both kinds of nexthops, and in fib6_nh_release_dsts as well.
Signature · 2 lines
Ralf Lici Mandelbit Srl