ipvs: new connection on a reused port goes to the previous real server during conn_tab resize
Subsystems (5)
Hello Julian, Simon,
Since the connection table became resizable (v7.1), a new TCP connection that reuses the client port of a connection in TIME_WAIT can have its first packets after the SYN sent to the real server of the previous connection, when the SYN arrives while conn_tab is being resized. The SYN goes to the newly scheduled real server and the handshake completes with it; the final ACK and the request then go to the old real server.
Seen on 7.3.3 (Fedora 7.3.3-300.fc45.x86_64, CONFIG_HZ=1000). The code involved is unchanged in current mainline. All sysctls at their defaults (conn_reuse_mode=1, expire_nodest_conn=0, conntrack=0); NAT forwarding, rr scheduler.
We have not run 7.0; going by the code, the window does not exist before the resizable table (see below), so this looks like a regression from:
#regzbot introduced: 2fa7cc9c7025
Example (capture on the director, packets from client port 43002 leaving towards the real servers):
+0.0 ms [S] -> 10.2.3.2 (scheduled; SYN-ACK from 10.2.3.2)
+0.0 ms [.] -> 10.2.4.2 <- real server of the previous
+0.1 ms [P.] -> 10.2.4.2 connection on this port
+201.3 ms [P.] -> 10.2.4.2 (client retransmission)
+409.3 ms [P.] -> 10.2.4.2 (client retransmission)
+818.2 ms [P.] -> 10.2.3.2
+818.6 ms [.] -> 10.2.3.2
+818.7 ms [F.] -> 10.2.3.2The old real server still has the 4-tuple in TIME_WAIT and answers with an ACK of the old connection; the new one never gets the request until the misrouting stops. The client sees a delay of one or more RTOs, and some connections are reset or time out.
Analysis (v7.3)
---------------
1. ip_vs_in(): a SYN that finds a connection in TIME_WAIT (is_new_conn_expected()) calls ip_vs_conn_expire_now() on it and schedules a new connection. The old entry stays hashed until its timer runs.
2. Before 7.1 there was one table and ip_vs_conn_hash() added at the bucket head, so lookups always found the new entry before the old one. With the resizable table:
- while a resize is in progress, ip_vs_conn_hash() adds new entries
to t->new_tbl, but __ip_vs_conn_in_get() walks the tables with
ip_vs_rht_for_each_table_rcu(), the current (old) table first; - conn_resize_work_handler() moves each entry of the old table to the head of its bucket in the new table, so an old entry moved after the new entry was added ends up before it.
In both cases the lookup for the packets that follow the SYN returns the old connection, and ip_vs_in() transmits them to its real server.
3. ip_vs_conn_put() on that path re-arms the old entry's timer with cp->timeout (TIME_WAIT: 2 minutes), cancelling the effect of ip_vs_conn_expire_now(), so the old entry stays in the table. In the runs below the misrouting of a connection stopped after 200 to 800 ms; we have not established what ends it in each case.
The window is the time between the SYN and the moment the old entry no longer comes first in the lookup, and it only exists around a resize. Resizes happen whenever the connection count crosses a threshold, in either direction (the resize work checks every 2 s).
Reproduction
------------
The script below (network namespaces and veth, needs ip, ipvsadm, tcpdump, python3) runs a client that reuses 8 source ports in a loop against a 4-server service, plus background connections from ephemeral ports. Each real server answers one request and closes. A capture on the director checks that every packet after a connection's SYN goes to the real server that got the SYN. Three modes:
force write conn_lfactor every 100 ms, alternating between two
values: each write starts a resize
grow no change: the table grows with the connection count
noresize conn_lfactor=8: no resize under this load (control)
Results, 60 s each, 7.3.3, i7-13700:
mode reused-port misrouted client: answered client:
connections connections after > 100 ms failed
force 11909 566 519 21 reset
grow 13697 9 8 1 timeoutnoresize 15745 0 0 0
(In grow mode the port of the timed-out connection stayed unusable for a while, hence fewer connections than in noresize. The numbers vary between runs; grow mode had between 4 and 12 misrouted connections in the runs we did.)
To relate the misrouting to resizes, we recorded each resize with kprobes on ip_vs_conn_tab_alloc() and on the return of conn_resize_work_handler(), sampling the hit counts every 2 ms (same setup, separate script). In two 60 s runs of the grow mode (4 resizes each, about 25 ms of resizing per run), all 13 misrouted connections started inside a resize or less than 1 ms before its sampled start. With forced resizes, 409 of 422 started within 2 ms of one.
---8<--- repro.sh ---8<---
#!/bin/bash
# IPVS: packets of a new connection on a reused client port go to the real
# server of the previous connection when the SYN arrives during a conn_tab
# resize (Linux >= 7.1).
#
# Topology (network namespaces, veth): client 10.1.0.2 -> director
# (VIP 10.96.0.10:80, rr, masquerading) -> real servers 10.2.{1..4}.2:8080.
# The client reuses 8 source ports in a loop; each real server answers one
# request and closes, so the director keeps the previous connection of the
# port in TIME_WAIT when the next SYN arrives (conn_reuse_mode=1 path).
# A capture on the director checks that every packet after the SYN of a
# connection goes to the real server that got the SYN.
#
# usage: sudo ./repro.sh [force|grow|noresize] [seconds]
# force switch conn_lfactor every 100 ms: one resize each time (default)
# grow kernel defaults; the table grows with the connection count
# noresize conn_lfactor=8: no resize under this load (control)
# needs: ip, ipvsadm, tcpdump, python3. All sysctls keep their defaults
# except conn_lfactor.
set -euo pipefail
MODE=${1:-force}
SECS=${2:-60}
VIP=10.96.0.10
NS="rr-cli rr-lb rr-rs1 rr-rs2 rr-rs3 rr-rs4"
DIR=$(mktemp -d)
PIDS=()cleanup() {
for p in "${PIDS[@]}"; do kill "$p" 2>/dev/null || true; done
wait 2>/dev/null || true
for n in $NS; do ip netns del "$n" 2>/dev/null || true; done
}trap cleanup EXITlb() { ip netns exec rr-lb "$@"; }
for n in $NS; do ip netns add "$n"; ip -n "$n" link set lo up; done link() { # link NS1 IF1 ADDR1 NS2 IF2 ADDR2
ip link add "$2" netns "$1" type veth peer name "$5" netns "$4" ip -n "$1" addr add "$3/24" dev "$2"; ip -n "$1" link set "$2" up ip -n "$4" addr add "$6/24" dev "$5"; ip -n "$4" link set "$5" up }
link rr-lb cli 10.1.0.1 rr-cli eth0 10.1.0.2
ip -n rr-cli route add default via 10.1.0.1
for i in 1 2 3 4; do
link rr-lb rs$i 10.2.$i.1 rr-rs$i eth0 10.2.$i.2
ip -n rr-rs$i route add default via 10.2.$i.1
ip netns exec rr-rs$i python3 -c '
import socket, sys, threading
s = socket.socket(); s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((sys.argv[1], 8080)); s.listen(512)
def serve(c):
try:
c.settimeout(10)
if c.recv(64):
c.sendall(sys.argv[1].encode())
except OSError:
pass
c.close() # the real server closes first
while True:
threading.Thread(target=serve, args=(s.accept()[0],), daemon=True).start()
' 10.2.$i.2 &
PIDS+=($!)done
lb sysctl -qw net.ipv4.ip_forward=1
ip -n rr-lb link add ipvs0 type dummy
ip -n rr-lb addr add $VIP/32 dev ipvs0
lb ipvsadm -A -t $VIP:80 -s rr
for i in 1 2 3 4; do
lb ipvsadm -a -t $VIP:80 -r 10.2.$i.2:8080 -m done LF=$(lb sysctl -n net.ipv4.vs.conn_lfactor) if [ "$MODE" = noresize ]; then LF=8 lb sysctl -qw net.ipv4.vs.conn_lfactor=8
fi
sleep 3
lb tcpdump -i any -nn -s 96 -U -w "$DIR/lb.pcap" \ 'tcp and src host 10.1.0.2 and src portrange 43000-43007' 2>/dev/null &
PIDS+=($!)
sleep 1
if [ "$MODE" = force ]; then
( v=$LF; while :; do v=$(( v == LF ? LF + 1 : LF )) lb sysctl -qw net.ipv4.vs.conn_lfactor=$v sleep 0.1 done ) & PIDS+=($!)
fi
# Client: 8 threads reuse ports 43000-43007; 4 threads open connections
# from ephemeral ports so that the table holds a few thousand entries.
ip netns exec rr-cli python3 -c '
import errno, socket, sys, threading, time
vip, stop = sys.argv[1], time.monotonic() + float(sys.argv[2])
ok, fail, slow = 0, {}, 0
lock = threading.Lock()
def one(port):
"""None: the local port is still in use;
else (answered, error, seconds)."""
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.settimeout(2)
t = time.monotonic()
try:
if port:
try:
s.bind(("0.0.0.0", port))
except OSError:
return None
s.connect((vip, 80)); s.sendall(b"x")
if not s.recv(64):
return False, "closed", 0
return True, None, time.monotonic() - t
except OSError as e:
if e.errno == errno.EADDRNOTAVAIL:
return None # the last connection on the port is not closed
return False, errno.errorcode.get(e.errno, type(e).__name__), 0
finally:
s.close()
def reuse(port):
global ok, slow
while time.monotonic() < stop:
r = one(port)
if r is None:
time.sleep(0.05)
continue
with lock:
if r[0]:
ok += 1
slow += r[2] > 0.1
else:
fail[r[1]] = fail.get(r[1], 0) + 1
time.sleep(0.03)
def background():
while time.monotonic() < stop:
one(0); time.sleep(0.02)
th = [threading.Thread(target=reuse, args=(43000 + i,)) for i in range(8)]
th += [threading.Thread(target=background) for _ in range(4)]
[t.start() for t in th]; [t.join() for t in th]
print(f"client (reused ports): {ok} answered, {slow} of them after "
f"more than 100 ms; failed: {fail or 0}")
' $VIP "$SECS"sleep 1
kill "${PIDS[@]}" 2>/dev/null || true
wait 2>/dev/null || true
echo "mode $MODE, conn_lfactor $LF, $(uname -r)" tcpdump -nn -tt -r "$DIR/lb.pcap" 2>/dev/null | python3 -c ' import sys
conns, cur = [], {}
for line in sys.stdin:
f = line.split()
# TIME IFACE Out IP 10.1.0.2.PORT > 10.2.X.2.8080: Flags [..], ...
if len(f) < 9 or f[2] != "Out" or not f[6].endswith(".8080:"):
continue
port, rs = f[4].rsplit(".", 1)[1], f[6][:-6]
flags, t = f[8].strip("[],"), float(f[0])
if flags == "S":
seq = f[10].rstrip(",")
if port in cur and cur[port]["seq"] == seq:
continue # SYN retransmission
cur[port] = c = {"port": port, "rs": rs, "t": t, "seq": seq, "pkts": []}
conns.append(c)
elif port in cur:
cur[port]["pkts"].append((t, rs, flags))bad = [c for c in conns if any(rs != c["rs"] for _, rs, _ in c["pkts"])] print(f"connections on reused ports: {len(conns)}; with packets sent "
f"to another real server than their SYN: {len(bad)}")
for c in bad[:2]:
port, syn_rs, t0 = c["port"], c["rs"], c["t"]
print(f" port {port}: SYN -> {syn_rs}")
for t, rs, flags in c["pkts"][:8]:
mark = "" if rs == syn_rs else " <-- other real server"
print(f" {(t - t0) * 1e3:+9.1f} ms [{flags:3}] -> {rs}{mark}")'
rm -rf "$DIR"
---8<--- end of repro.sh ---8<---
Possible directions (untested)
------------------------------
- Do not let lookups return a connection that a SYN has just expired for reuse, e.g. unhash it immediately in the conn_reuse_mode path when it has no other users, or mark it so that __ip_vs_conn_in_get() skips it.
- Or keep the "new entries first" order across a resize: look up t->new_tbl before the current table, and add moved entries at the tail of the new bucket.
The first seems more robust since it does not depend on how entries are ordered.
Xing Feng, Peng Zhang (Cc'd) and I found this while testing a passive runtime checker for L4 load balancers, which reports a TCP connection whose packets leave towards a different backend than its SYN.
Thanks,
Zhenrong (Daniel) Gu
Julian Anastasov
maintainerHello,
Quoted 288 lines · Zhenrong (Daniel) Gu
Hello Julian, Simon,
Since the connection table became resizable (v7.1), a new TCP connection that reuses the client port of a connection in
TIME_WAITcan have its first packets after the SYN sent to the real server of the previous connection, when the SYN arrives whileconn_tabis being resized. The SYN goes to the newly scheduled real server and the handshake completes with it; the final ACK and the request then go to the old real server.Seen on 7.3.3 (Fedora 7.3.3-300.fc45.x86_64,
CONFIG_HZ=1000). The code involved is unchanged in current mainline. All sysctls at their defaults (conn_reuse_mode=1, expire_nodest_conn=0, conntrack=0); NAT forwarding, rr scheduler.We have not run 7.0; going by the code, the window does not exist before the resizable table (see below), so this looks like a regression from:
#regzbot introduced:
2fa7cc9c7025Example (capture on the director, packets from client port 43002 leaving towards the real servers):
+0.0 ms [S] -> 10.2.3.2 (scheduled; SYN-ACK from 10.2.3.2) +0.0 ms [.] -> 10.2.4.2 <- real server of the previous +0.1 ms [P.] -> 10.2.4.2 connection on this port +201.3 ms [P.] -> 10.2.4.2 (client retransmission) +409.3 ms [P.] -> 10.2.4.2 (client retransmission) +818.2 ms [P.] -> 10.2.3.2 +818.6 ms [.] -> 10.2.3.2 +818.7 ms [F.] -> 10.2.3.2The old real server still has the 4-tuple in
TIME_WAITand answers with an ACK of the old connection; the new one never gets the request until the misrouting stops. The client sees a delay of one or more RTOs, and some connections are reset or time out.Analysis (v7.3)
---------------1.
ip_vs_in(): a SYN that finds a connection inTIME_WAIT(is_new_conn_expected()) callsip_vs_conn_expire_now()on it and schedules a new connection. The old entry stays hashed until its timer runs.2. Before 7.1 there was one table and
ip_vs_conn_hash()added at the bucket head, so lookups always found the new entry before the old one. With the resizable table:
- while a resize is in progress,ip_vs_conn_hash()adds new entriesto t->new_tbl, but __ip_vs_conn_in_get() walks the tables with ip_vs_rht_for_each_table_rcu(), the current (old) table first;-
conn_resize_work_handler()moves each entry of the old table to the head of its bucket in the new table, so an old entry moved after the new entry was added ends up before it.
In both cases the lookup for the packets that follow the SYN returns the old connection, andip_vs_in()transmits them to its real server.3.
ip_vs_conn_put()on that path re-arms the old entry's timer withcp->timeout(TIME_WAIT: 2 minutes), cancelling the effect ofip_vs_conn_expire_now(), so the old entry stays in the table. In the runs below the misrouting of a connection stopped after 200 to 800 ms; we have not established what ends it in each case.The window is the time between the SYN and the moment the old entry no longer comes first in the lookup, and it only exists around a resize. Resizes happen whenever the connection count crosses a threshold, in either direction (the resize work checks every 2 s).
Reproduction
------------The script below (network namespaces and veth, needs ip, ipvsadm, tcpdump, python3) runs a client that reuses 8 source ports in a loop against a 4-server service, plus background connections from ephemeral ports. Each real server answers one request and closes. A capture on the director checks that every packet after a connection's SYN goes to the real server that got the SYN. Three modes:
force write
conn_lfactorevery 100 ms, alternating between two
values: each write starts a resize
grow no change: the table grows with the connection count
noresize conn_lfactor=8: no resize under this load (control)Results, 60 s each, 7.3.3, i7-13700:
mode reused-port misrouted client: answered client: connections connections after > 100 ms failed force 11909 566 519 21 reset grow 13697 9 8 1 timeoutnoresize 15745 0 0 0
(In grow mode the port of the timed-out connection stayed unusable for a while, hence fewer connections than in noresize. The numbers vary between runs; grow mode had between 4 and 12 misrouted connections in the runs we did.)
To relate the misrouting to resizes, we recorded each resize with kprobes on
ip_vs_conn_tab_alloc()and on the return ofconn_resize_work_handler(), sampling the hit counts every 2 ms (same setup, separate script). In two 60 s runs of the grow mode (4 resizes each, about 25 ms of resizing per run), all 13 misrouted connections started inside a resize or less than 1 ms before its sampled start. With forced resizes, 409 of 422 started within 2 ms of one.---8<---
repro.sh---8<---
#!/bin/bash
# IPVS: packets of a new connection on a reused client port go to the real# server of the previous connection when the SYN arrives during a conn_tab # resize (Linux >= 7.1). # # Topology (network namespaces, veth): client 10.1.0.2 -> director # (VIP 10.96.0.10:80, rr, masquerading) -> real servers 10.2.{1..4}.2:8080. # The client reuses 8 source ports in a loop; each real server answers one # request and closes, so the director keeps the previous connection of the # port in TIME_WAIT when the next SYN arrives (conn_reuse_mode=1 path). # A capture on the director checks that every packet after the SYN of a # connection goes to the real server that got the SYN. # # usage: sudo ./repro.sh [force|grow|noresize] [seconds] # force switch conn_lfactor every 100 ms: one resize each time (default) # grow kernel defaults; the table grows with the connection count # noresize conn_lfactor=8: no resize under this load (control) # needs: ip, ipvsadm, tcpdump, python3. All sysctls keep their defaults # except conn_lfactor. set -euo pipefail MODE=${1:-force} SECS=${2:-60} VIP=10.96.0.10 NS="rr-cli rr-lb rr-rs1 rr-rs2 rr-rs3 rr-rs4" DIR=$(mktemp -d) PIDS=()cleanup() { for p in "${PIDS[@]}"; do kill "$p" 2>/dev/null || true; done wait 2>/dev/null || true for n in $NS; do ip netns del "$n" 2>/dev/null || true; done }trap cleanup EXIT
lb(){ ip netns exec rr-lb "$@"; }for n in $NS; do ip netns add "$n"; ip -n "$n" link set lo up; done
link(){ # link NS1 IF1 ADDR1 NS2 IF2 ADDR2ip link add "$2" netns "$1" type veth peer name "$5" netns "$4" ip -n "$1" addr add "$3/24" dev "$2"; ip -n "$1" link set "$2" up ip -n "$4" addr add "$6/24" dev "$5"; ip -n "$4" link set "$5" up }link rr-lb cli 10.1.0.1 rr-cli eth0 10.1.0.2
ip -n rr-cli route add default via 10.1.0.1
for i in 1 2 3 4; do
link rr-lb rs$i 10.2.$i.1 rr-rs$i eth0 10.2.$i.2
ip -n rr-rs$i route add default via 10.2.$i.1
ip netns exec rr-rs$i python3 -c '
import socket, sys, threading
s =socket.socket();s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)s.bind((sys.argv[1], 8080));s.listen(512)
def serve(c):try: c.settimeout(10) if c.recv(64): c.sendall(sys.argv[1].encode()) except OSError: pass c.close() # the real server closes first while True: threading.Thread(target=serve, args=(s.accept()[0],), daemon=True).start() ' 10.2.$i.2 & PIDS+=($!)done
lb sysctl -qw net.ipv4.ip_forward=1
ip -n rr-lb link add ipvs0 type dummy
ip -n rr-lb addr add $VIP/32 dev ipvs0
lb ipvsadm -A -t $VIP:80 -s rr
for i in 1 2 3 4; dolb ipvsadm -a -t $VIP:80 -r 10.2.$i.2:8080 -m done LF=$(lb sysctl -n net.ipv4.vs.conn_lfactor) if [ "$MODE" = noresize ]; then LF=8 lb sysctl -qw net.ipv4.vs.conn_lfactor=8fi
sleep 3lb tcpdump -i any -nn -s 96 -U -w "$DIR/lb.pcap" \ 'tcp and src host 10.1.0.2 and src portrange 43000-43007' 2>/dev/null &PIDS+=($!)
sleep 1if [ "$MODE" = force ]; then
( v=$LF; while :; do v=$(( v == LF ? LF + 1 : LF )) lb sysctl -qw net.ipv4.vs.conn_lfactor=$v sleep 0.1 done ) & PIDS+=($!)fi
# Client: 8 threads reuse ports 43000-43007; 4 threads open connections
# from ephemeral ports so that the table holds a few thousand entries. ip netns exec rr-cli python3 -c ' import errno, socket, sys, threading, time vip, stop = sys.argv[1], time.monotonic() + float(sys.argv[2]) ok, fail, slow = 0, {}, 0 lock = threading.Lock() def one(port): """None: the local port is still in use; else (answered, error, seconds).""" s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.settimeout(2) t = time.monotonic() try: if port: try: s.bind(("0.0.0.0", port)) except OSError: return None s.connect((vip, 80)); s.sendall(b"x") if not s.recv(64): return False, "closed", 0 return True, None, time.monotonic() - t except OSError as e: if e.errno == errno.EADDRNOTAVAIL: return None # the last connection on the port is not closed return False, errno.errorcode.get(e.errno, type(e).__name__), 0 finally: s.close() def reuse(port): global ok, slow while time.monotonic() < stop: r = one(port) if r is None: time.sleep(0.05) continue with lock: if r[0]: ok += 1 slow += r[2] > 0.1 else: fail[r[1]] = fail.get(r[1], 0) + 1 time.sleep(0.03) def background(): while time.monotonic() < stop: one(0); time.sleep(0.02) th = [threading.Thread(target=reuse, args=(43000 + i,)) for i in range(8)] th += [threading.Thread(target=background) for _ in range(4)] [t.start() for t in th]; [t.join() for t in th] print(f"client (reused ports): {ok} answered, {slow} of them after " f"more than 100 ms; failed: {fail or 0}") ' $VIP "$SECS"sleep 1
kill "${PIDS[@]}" 2>/dev/null || true
wait 2>/dev/null || true
echo "mode $MODE,conn_lfactor$LF, $(uname -r)" tcpdump -nn -tt -r "$DIR/lb.pcap" 2>/dev/null | python3 -c ' import sys
conns, cur = [], {}
for line in sys.stdin:f = line.split() # TIME IFACE Out IP 10.1.0.2.PORT > 10.2.X.2.8080: Flags [..], ... if len(f) < 9 or f[2] != "Out" or not f[6].endswith(".8080:"): continue port, rs = f[4].rsplit(".", 1)[1], f[6][:-6] flags, t = f[8].strip("[],"), float(f[0]) if flags == "S": seq = f[10].rstrip(",") if port in cur and cur[port]["seq"] == seq: continue # SYN retransmission cur[port] = c = {"port": port, "rs": rs, "t": t, "seq": seq, "pkts": []} conns.append(c) elif port in cur: cur[port]["pkts"].append((t, rs, flags))bad = [c for c in conns if
any(rs != c["rs"] for _, rs, _ in c["pkts"])] print(f"connections on reused ports: {len(conns)}; with packets sent "
f"to another real server than their SYN: {len(bad)}")
for c in bad[:2]:port, syn_rs, t0 = c["port"], c["rs"], c["t"] print(f" port {port}: SYN -> {syn_rs}") for t, rs, flags in c["pkts"][:8]: mark = "" if rs == syn_rs else " <-- other real server" print(f" {(t - t0) * 1e3:+9.1f} ms [{flags:3}] -> {rs}{mark}")'
rm -rf "$DIR"
---8<--- end ofrepro.sh---8<---
Quoted 7 lines
Possible directions (untested)
------------------------------- Do not let lookups return a connection that a SYN has just expired for reuse, e.g. unhash it immediately in the
conn_reuse_modepath when it has no other users, or mark it so that__ip_vs_conn_in_get()skips it.
We prefer not to unhash such connections because they will
go out of our control, eg. we may want to delete them immediately on netns cleanup. May be we should add some check to make them invisible to packets, such as adding new bit in the cp->flags, not depending on the cp->timeout being 0 or not. I can prepare some patch to fix this problem.
Quoted 3 lines
- Or keep the "new entries first" order across a resize: look up
t->new_tblbefore the current table, and add moved entries at the tail of the new bucket.
They end up in the same table but in reverse order. The
old table is freed after RCU grace period, so it should not matter which table is checked first.
Quoted 2 lines
The first seems more robust since it does not depend on how entries are ordered.
Agreed
Quoted 3 lines
Xing Feng, Peng Zhang (Cc'd) and I found this while testing a passive runtime checker for L4 load balancers, which reports a TCP connection whose packets leave towards a different backend than its SYN.
Thanks for the report, it is clear side effect of the
reversing the order of the reused connections during rehashing.
Regards
--
Julian Anastasov <[email protected]>
Hello Julian,
Quoted 7 lines · Julian Anastasov
We prefer not to unhash such connections because they will
go out of our control, eg. we may want to delete them immediately on netns cleanup. May be we should add some check to make them invisible to packets, such as adding new bit in thecp->flags, not depending on thecp->timeoutbeing 0 or not. I can prepare some patch to fix this problem.
Thanks, a flag that hides the entry from packet lookups makes sense to us, and it also keeps ip_vs_conn_put() from re-arming the old entry's timer. We would be glad to test the patch: we can run the reproducer (force, grow and noresize modes) on 7.3.3 and report back.
Quoted 3 lines
They end up in the same table but in reverse order. The
old table is freed after RCU grace period, so it should not matter which table is checked first.
Understood, thanks for the explanation.
Best regards,
Zhenrong (Daniel) Gu
Julian Anastasov
maintainerHello,
Quoted 9 lines · Zhenrong (Daniel) Gu
Quoted 7 lines · Julian Anastasov
We prefer not to unhash such connections because they will
go out of our control, eg. we may want to delete them immediately on netns cleanup. May be we should add some check to make them invisible to packets, such as adding new bit in thecp->flags, not depending on thecp->timeoutbeing 0 or not. I can prepare some patch to fix this problem.
Quoted 4 lines
Thanks, a flag that hides the entry from packet lookups makes sense to us, and it also keeps
ip_vs_conn_put()from re-arming the old entry's timer. We would be glad to test the patch: we can run the reproducer (force, grow and noresize modes) on 7.3.3 and report back.
Appending a RFC version for testing. It is for the net
tree because it contains all recent fixes for IPVS.
[PATCH RFC net] ipvs: fix connection reuse with the resizable hash tables
Zhenrong (Daniel) Gu, Xing Feng and Peng Zhang report for a problem with the reused connections while testing a passive runtime checker for L4 load balancers.
When connection is reused, we create new connection and put it first in the list. By this way all packets hit the new connection leaving the reused one to expire. This order worked before the the introduction of resizable connection hash table which started to reverse the order of connections each time the table is resized. If the table is resized while the reused connection is still present, the next packets will not hit the new connection.
To fix that we prefer not to rely on the order of connections, now we will just mark the reused connection with a new flag IP_VS_CONN_F_REUSED, so that it can be skipped when the list is traversed on received packet. As the reused connection is still hashed while waiting its timer to expire, it is visible to the procedures that delete connections on memory pressure or netns cleanup. Also, when the reused connections are now marked, we can exclude them from the synchronization process.
--- include/net/ip_vs.h | 1 + include/uapi/linux/ip_vs.h | 7 +++++++ net/netfilter/ipvs/ip_vs_conn.c | 16 ++++++++++++++++ net/netfilter/ipvs/ip_vs_core.c | 13 ++----------- net/netfilter/ipvs/ip_vs_sync.c | 9 ++++----- 5 files changed, 30 insertions(+), 16 deletions(-)
include/net/ip_vs.h +1 -0
@@ -1714,6 +1714,7 @@ struct ip_vs_conn *ip_vs_conn_new(const struct ip_vs_conn_param *p, int dest_af, __be16 dport, unsigned int flags, struct ip_vs_dest *dest, __u32 fwmark);void ip_vs_conn_expire_now (struct ip_vs_conn *cp); +void ip_vs_conn_mark_reused (struct ip_vs_conn *cp,bool old_ct);const char *ip_vs_state_name (const struct ip_vs_conn *cp);
include/uapi/linux/ip_vs.h +7 -0
@@ -112,6 +112,13 @@ IP_VS_CONN_F_NFCT | \ 0) +#define IP_VS_CONN_F_REUSED (1 << 30)/* replaced from new one */ + +/* Connections with any of these flags are not synced */ +#define IP_VS_CONN_F_MASTER_NOSYNC (IP_VS_CONN_F_ONE_PACKET | \ + IP_VS_CONN_F_REUSED | \ + 0) +#define IP_VS_SCHEDNAME_MAXLEN 16#define IP_VS_PENAME_MAXLEN 16#define IP_VS_IFNAME_MAXLEN 16
net/netfilter/ipvs/ip_vs_conn.c +16 -0
@@ -405,6 +405,7 @@ __ip_vs_conn_in_get(const struct ip_vs_conn_param *p) &cp->vaddr) && (!p->cport ^ (!(cp->flags &IP_VS_CONN_F_NO_CPORT ))) && + !(cp->flags &IP_VS_CONN_F_REUSED ) && p->protocol == cp->protocol) { if (__ip_vs_conn_get(cp)) {/* HIT */
@@ -592,6 +593,7 @@ struct ip_vs_conn *ip_vs_conn_out_get(const struct ip_vs_conn_param *p)ip_vs_addr_equal (p->af, p->caddr, saddr) && (!p->vport ^ (!(cp->flags &IP_VS_CONN_F_NO_CPORT ))) && + !(cp->flags &IP_VS_CONN_F_REUSED ) && p->protocol == cp->protocol) { if (__ip_vs_conn_get(cp)) goto out;
@@ -1468,6 +1470,20 @@ void ip_vs_conn_expire_now(struct ip_vs_conn *cp)mod_timer_pending (&cp->timer, jiffies); } +/* Mark connection as reused: +* - it is still hashed +* - but it is not hit by packets +* - it is replaced by new connection with same addresses and ports +* - it is not synced anymore +*/ +void ip_vs_conn_mark_reused (struct ip_vs_conn *cp,bool old_ct) +{ +spin_lock_bh (&cp->lock); +if (!old_ct) + cp->flags &= ~IP_VS_CONN_F_NFCT ; + cp->flags |=IP_VS_CONN_F_REUSED ; +spin_unlock_bh (&cp->lock); +}/* * Create a new connection entry and hash it into the conn_tab
net/netfilter/ipvs/ip_vs_core.c +2 -11
@@ -2209,11 +2209,7 @@ ip_vs_in_hook(void *priv, struct sk_buff *skb, const struct nf_hook_state *state }if (resched) { -if (!old_ct) { -spin_lock_bh (&cp->lock); - cp->flags &= ~IP_VS_CONN_F_NFCT ; -spin_unlock_bh (&cp->lock); - } +ip_vs_conn_mark_reused (cp, old_ct);if (!atomic_read (&cp->n_control))ip_vs_conn_expire_now (cp);__ip_vs_conn_put (cp);
@@ -2229,12 +2225,7 @@ ip_vs_in_hook(void *priv, struct sk_buff *skb, const struct nf_hook_state *stateif (sysctl_expire_nodest_conn (ipvs)) {bool old_ct =ip_vs_conn_uses_old_conntrack (cp, skb); -if (!old_ct) { -spin_lock_bh (&cp->lock); - cp->flags &= ~IP_VS_CONN_F_NFCT ; -spin_unlock_bh (&cp->lock); - } - +ip_vs_conn_mark_reused (cp, old_ct);ip_vs_conn_expire_now (cp);__ip_vs_conn_put (cp);if (old_ct)
net/netfilter/ipvs/ip_vs_sync.c +4 -5
@@ -551,8 +551,7 @@ static void ip_vs_sync_conn_v0(struct netns_ipvs *ipvs, struct ip_vs_conn *cp,if (unlikely (cp->af !=AF_INET ))return ; flags =READ_ONCE (cp->flags); -/* Do not sync ONE PACKET */ -if (flags &IP_VS_CONN_F_ONE_PACKET ) +if (flags &IP_VS_CONN_F_MASTER_NOSYNC )return ;if (!ip_vs_sync_conn_needed (ipvs, cp, pkts))
@@ -654,8 +653,7 @@ void ip_vs_sync_conn(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts)ip_vs_sync_conn_v0 (ipvs, cp, pkts);return ; } -/* Do not sync ONE PACKET */ -if (cp->flags &IP_VS_CONN_F_ONE_PACKET ) +if (cp->flags &IP_VS_CONN_F_MASTER_NOSYNC ) goto control; sloop:if (!ip_vs_sync_conn_needed (ipvs, cp, pkts))
@@ -895,6 +893,7 @@ static void ip_vs_proc_conn(struct netns_ipvs *ipvs, struct ip_vs_conn_param *paif (cp && ((cp->dport != dport) || !ip_vs_addr_equal (cp->daf, &cp->daddr, daddr))) {if (!(flags &IP_VS_CONN_F_INACTIVE )) { +ip_vs_conn_mark_reused (cp, false);ip_vs_conn_expire_now (cp);__ip_vs_conn_put (cp); cp =NULL ;
@@ -1003,7 +1002,7 @@ static bool ip_vs_sync_validate_flags(u32 flags)if (flags &IP_VS_CONN_F_TEMPLATE )return false; } -if (flags &IP_VS_CONN_F_ONE_PACKET ) +if (flags &IP_VS_CONN_F_MASTER_NOSYNC )return false;return true; }
Signature · 7 lines
2.56.1 Regards -- Julian Anastasov <[email protected]>
Zhenrong (Daniel) Gu
Tested-byHello Julian,
Quoted 4 lines · Julian Anastasov
Appending a RFC version for testing. It is for the net
tree because it contains all recent fixes for IPVS.[PATCH RFC net] ipvs: fix connection reuse with the resizable hash tables
Thanks for the patch. We tested it on the net tree (af6737b90, 7.4.0-rc3) in a KVM guest with 8 vCPUs, using the reproducer from the report:
mode kernel reused-port misrouted answered failed
connections connections > 100 ms
force net 13289 413 333 35 reset
force net+RFC 15634 0 0 0
grow net 15584 7 5 1 reset
grow net+RFC 15678 0 0 0
noresize net 7841 0 0 0
noresize net+RFC 7834 0 0 0(force: 60 s, conn_lfactor written every 100 ms; grow: 60 s, all defaults; noresize: 30 s, conn_lfactor=8.)
With the patch no packet of a reused-port connection went to another real server than its SYN, and the client saw no delayed or failed exchanges.
To check for regressions we also ran, on both kernels:
- tools/testing/selftests/net/netfilter/ipvs.sh: PASS on both.
- Rolling updates with drained and deleted real servers, and reused ports with conn_reuse_mode=0, in a NAT setup with kube-proxy's
sysctls: same results on both kernels.
- Master/backup sync with reused-port traffic and forced resizes: the backup's entries for the reused ports matched the master's on 20 of 20 ports with the patch, 22 of 30 without.
- Persistent service (-p 60) with reused ports and forced resizes:
every connection reached the same real server, on both kernels.
We did not construct the case of a late packet from the old real server (e.g. a retransmitted FIN) after its connection was marked reused.
Thanks,
Zhenrong Gu