Commit fa30bbd2fd for frr
commit fa30bbd2fd921acae7b8b8be3557aad2fc35509d
Author: Nick Bouliane <nbouliane@coreweave.com>
Date: Fri Nov 27 12:14:35 2026 -0500
bgpd: free the peers that are still clearing their routes at exit
When a peer is deleted, a dynamic neighbor whose session goes down for
example, peer_delete() takes it out of bgp->peer and its routes are
cleared in the background by its clear_node_queue. bgp_clear_route()
holds a reference on the peer until that work queue is done.
If bgpd is terminated before the work queue is done, nothing runs it
anymore. peer_delete() does drain the queue when bgpd is terminating,
but bgp_delete() only calls it for the peers that are in bgp->peer,
and those peers are not there anymore. They are never freed, and since
each of them holds a reference on the BGP instance, and each queued
item one on a route node and on its table, the instance and its tables
are not freed either.
This was found on 10.7.1, which has the same code, by stopping 204
dynamic neighbors with 10 routes each right before bgpd. The memory
report at exit had, among others:
BGP instance : 1
BGP peer : 204
BGP peer connection : 204
BGP node clear queue : 2040
Keep the peers that have work pending in their clear_node_queue in a
list of the BGP instance, and drain these queues in bgp_delete() when
bgpd is terminating, after the peers of bgp->peer are deleted.
Add a topotest, bgp_dynamic_peer_clearing_at_exit. r2 is a dynamic
neighbor of r1 and announces 20000 routes to it. The test resets the
session on r1, which deletes the peer and queues its routes for
clearing, and terminates bgpd right after, in the same shell command.
bgpd must not report anything in the memory statistics that it writes
to its stderr at exit.
The test gets the pid of bgpd from Router.getDaemonPid(), a new helper
of the topotest library.
Without the fix the test fails with, among others:
bgpd: memstats: BGP instance : 1 * 19920
bgpd: memstats: BGP peer : 1 * 19200
bgpd: memstats: BGP peer connection : 1 * 408
bgpd: memstats: BGP node clear queue : 20000 * 8
The clearing starts 10 ms after the peer is deleted. If bgpd were
terminated after it is done the test would pass with or without the
fix, it cannot fail because of the timing.
Signed-off-by: Nick Bouliane <nbouliane@coreweave.com>
diff --git a/bgpd/bgp_route.c b/bgpd/bgp_route.c
index 9825e12e64..84c1c7aacd 100644
--- a/bgpd/bgp_route.c
+++ b/bgpd/bgp_route.c
@@ -7897,6 +7897,9 @@ static void bgp_clear_node_complete(struct work_queue *wq)
if (!peer_established(peer->connection))
BGP_EVENT_ADD(peer->connection, Clearing_Completed);
+ if (bgp_clear_node_peers_anywhere(peer))
+ bgp_clear_node_peers_del(&peer->bgp->clear_node_peers, peer);
+
peer_unlock(peer); /* bgp_clear_route */
}
@@ -7931,6 +7934,9 @@ bool bgp_clear_node_queue_drain(struct peer *peer)
wq = peer->clear_node_queue;
need_peer_unlock = work_queue_is_scheduled(wq) || !work_queue_empty(wq);
+ if (bgp_clear_node_peers_anywhere(peer))
+ bgp_clear_node_peers_del(&peer->bgp->clear_node_peers, peer);
+
/*
* During daemon termination we need the clear-route work to run
* synchronously before queue teardown, otherwise we only drop refs.
@@ -7947,6 +7953,22 @@ bool bgp_clear_node_queue_drain(struct peer *peer)
return need_peer_unlock;
}
+/*
+ * Drain the clear-node queue of every peer of this instance that has work
+ * pending, including the peers that are already deleted and that only wait
+ * for this work to be freed.
+ */
+void bgp_clear_node_queue_drain_all(struct bgp *bgp)
+{
+ struct peer *peer;
+
+ /* bgp_clear_node_queue_drain() takes the peer out of the list */
+ while ((peer = bgp_clear_node_peers_first(&bgp->clear_node_peers)) != NULL) {
+ if (bgp_clear_node_queue_drain(peer))
+ peer_unlock(peer); /* bgp_clear_route */
+ }
+}
+
static void bgp_clear_route_table(struct peer *peer, afi_t afi, safi_t safi,
struct bgp_table *table)
{
@@ -8081,6 +8103,8 @@ void bgp_clear_route(struct peer *peer, afi_t afi, safi_t safi)
/* unlock if no nodes got added to the clear-node-queue. */
if (!event_is_scheduled(peer->clear_node_queue->event))
peer_unlock(peer);
+ else if (!bgp_clear_node_peers_anywhere(peer))
+ bgp_clear_node_peers_add_tail(&peer->bgp->clear_node_peers, peer);
}
/*
diff --git a/bgpd/bgp_route.h b/bgpd/bgp_route.h
index cce9c6608b..8d83d03b96 100644
--- a/bgpd/bgp_route.h
+++ b/bgpd/bgp_route.h
@@ -898,6 +898,7 @@ extern bool bgp_soft_reconfig_in(struct peer *peer, afi_t afi, safi_t safi);
extern void bgp_clear_route(struct peer *peer, afi_t afi, safi_t safi);
extern void bgp_clear_route_all(struct peer *peer);
extern bool bgp_clear_node_queue_drain(struct peer *peer);
+extern void bgp_clear_node_queue_drain_all(struct bgp *bgp);
/* Clear routes for a batch of peers */
void bgp_clear_route_batch(struct bgp_clearing_info *cinfo);
diff --git a/bgpd/bgpd.c b/bgpd/bgpd.c
index c99d8b70a1..9bc8fafa76 100644
--- a/bgpd/bgpd.c
+++ b/bgpd/bgpd.c
@@ -4247,6 +4247,10 @@ peer_init:
bgp_peer_conn_errlist_init(&bgp->peer_conn_errlist);
bgp_clearing_info_init(&bgp->clearing_list);
+ /* A hidden instance may still have deleted peers in this list */
+ if (!hidden)
+ bgp_clear_node_peers_init(&bgp->clear_node_peers);
+
/*
* The non-hidden path above records the first default instance as the
* EVPN instance (bm->bgp_evpn). That block is skipped on the hidden
@@ -4892,6 +4896,15 @@ int bgp_delete(struct bgp *bgp)
bgp->peer_self = NULL;
}
+ /*
+ * A peer deleted before the shutdown, a dynamic neighbor whose
+ * session went down for example, is no longer in bgp->peer. If its
+ * routes were still being cleared, the work queue holds a reference
+ * on it and nothing will run that queue anymore.
+ */
+ if (bm->terminating)
+ bgp_clear_node_queue_drain_all(bgp);
+
update_bgp_group_free(bgp);
/* Cancel peer connection errors event */
diff --git a/bgpd/bgpd.h b/bgpd/bgpd.h
index f64fee4714..045718a1f0 100644
--- a/bgpd/bgpd.h
+++ b/bgpd/bgpd.h
@@ -525,6 +525,9 @@ PREDECL_DLIST(bgp_clearing_info);
/* Hash of peers in clearing info object */
PREDECL_HASH(bgp_clearing_hash);
+/* List of peers that have work pending in their clear_node_queue */
+PREDECL_DLIST(bgp_clear_node_peers);
+
/* Info about a batch of peers that need to be cleared from the RIB.
* If many peers need to be cleared, we process them in batches, taking
* one walk through the RIB for each batch. This is only used for "all"
@@ -1178,6 +1181,11 @@ struct bgp {
/* List of batches of peers being cleared from BGP RIBs */
struct bgp_clearing_info_head clearing_list;
+ /* Peers that have work pending in their clear_node_queue; a peer
+ * stays here after peer_delete() took it out of the 'peer' list.
+ */
+ struct bgp_clear_node_peers_head clear_node_peers;
+
struct timeval ebgprequirespolicywarning;
#define FIFTEENMINUTE2USEC (int64_t)15 * 60 * 1000000
@@ -2381,10 +2389,15 @@ struct peer {
/* Linkage for hash of clearing peers being cleared in a batch */
struct bgp_clearing_hash_item clear_hash_link;
+ /* Linkage for the list of peers with a pending clear_node_queue */
+ struct bgp_clear_node_peers_item clear_node_link;
+
QOBJ_FIELDS;
};
DECLARE_QOBJ_TYPE(peer);
+DECLARE_DLIST(bgp_clear_node_peers, struct peer, clear_node_link);
+
/* Inherit peer attribute from peer-group. */
#define PEER_ATTR_INHERIT(peer, group, attr) \
((peer)->attr = (group)->conf->attr)
diff --git a/tests/topotests/bgp_dynamic_peer_clearing_at_exit/__init__.py b/tests/topotests/bgp_dynamic_peer_clearing_at_exit/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/topotests/bgp_dynamic_peer_clearing_at_exit/r1/frr.conf b/tests/topotests/bgp_dynamic_peer_clearing_at_exit/r1/frr.conf
new file mode 100644
index 0000000000..f46052d1ed
--- /dev/null
+++ b/tests/topotests/bgp_dynamic_peer_clearing_at_exit/r1/frr.conf
@@ -0,0 +1,12 @@
+!
+! r1 accepts r2 as a dynamic neighbor.
+!
+interface r1-eth0
+ ip address 192.168.1.1/24
+!
+router bgp 65001
+ no bgp ebgp-requires-policy
+ neighbor PG_DYN peer-group
+ neighbor PG_DYN remote-as external
+ bgp listen range 192.168.1.0/24 peer-group PG_DYN
+!
diff --git a/tests/topotests/bgp_dynamic_peer_clearing_at_exit/r2/frr.conf b/tests/topotests/bgp_dynamic_peer_clearing_at_exit/r2/frr.conf
new file mode 100644
index 0000000000..0f5742ebab
--- /dev/null
+++ b/tests/topotests/bgp_dynamic_peer_clearing_at_exit/r2/frr.conf
@@ -0,0 +1,15 @@
+!
+! r2 announces to r1 the routes that sharpd installs.
+!
+interface r2-eth0
+ ip address 192.168.1.2/24
+!
+router bgp 65002
+ no bgp ebgp-requires-policy
+ neighbor 192.168.1.1 remote-as external
+ neighbor 192.168.1.1 timers connect 1
+ !
+ address-family ipv4 unicast
+ redistribute sharp
+ exit-address-family
+!
diff --git a/tests/topotests/bgp_dynamic_peer_clearing_at_exit/test_bgp_dynamic_peer_clearing_at_exit.py b/tests/topotests/bgp_dynamic_peer_clearing_at_exit/test_bgp_dynamic_peer_clearing_at_exit.py
new file mode 100644
index 0000000000..7721590210
--- /dev/null
+++ b/tests/topotests/bgp_dynamic_peer_clearing_at_exit/test_bgp_dynamic_peer_clearing_at_exit.py
@@ -0,0 +1,156 @@
+#!/usr/bin/env python
+# SPDX-License-Identifier: ISC
+
+#
+# Copyright (c) 2026 by Nick Bouliane <nbouliane@coreweave.com>
+#
+
+"""
+bgpd must free a deleted peer whose routes are still being cleared at exit.
+
+r2 is a dynamic neighbor of r1 (bgp listen range) and announces ROUTE_COUNT
+routes to it. When the session of a dynamic neighbor goes down, r1 deletes
+the peer: it is taken out of the list of peers of the instance, and its
+routes are cleared in the background by a work queue that holds a reference
+on the peer and that starts 10 ms later.
+
+The test resets the session on r1 and terminates bgpd right after, in one
+shell command, so that bgpd exits while that work queue still has routes to
+clear. bgpd writes the memory that it did not free at exit to its stderr,
+which must be empty. Without the fix it has, among others:
+
+ bgpd: memstats: BGP instance : 1 * ...
+ bgpd: memstats: BGP peer : 1 * ...
+ bgpd: memstats: BGP node clear queue : ..... * ...
+
+If bgpd is terminated too late, after the routes are cleared, the test passes
+whether the fix is there or not: it cannot fail because of the timing.
+"""
+
+import json
+import os
+import sys
+
+import pytest
+
+CWD = os.path.dirname(os.path.realpath(__file__))
+sys.path.append(os.path.join(CWD, "../"))
+
+# pylint: disable=C0413
+from lib import topotest
+from lib.topogen import Topogen, get_topogen
+
+pytestmark = [pytest.mark.bgpd, pytest.mark.sharpd]
+
+R2_IP = "192.168.1.2"
+# Not the address of r1, which would not accept its own address as next hop
+NEXTHOP = "192.168.1.3"
+ROUTE_COUNT = 20000
+
+
+def build_topo(tgen):
+ r1 = tgen.add_router("r1")
+ r2 = tgen.add_router("r2")
+
+ switch = tgen.add_switch("s1")
+ switch.add_link(r1)
+ switch.add_link(r2)
+
+
+def setup_module(mod):
+ tgen = Topogen(build_topo, mod.__name__)
+ tgen.start_topology()
+
+ for rname, router in tgen.routers().items():
+ daemons = ["zebra", "bgpd"]
+ if rname == "r2":
+ daemons.append("sharpd")
+ router.load_frr_config(
+ os.path.join(CWD, "{}/frr.conf".format(rname)), daemons=daemons
+ )
+
+ tgen.start_router()
+
+
+def teardown_module(mod):
+ tgen = get_topogen()
+ tgen.stop_topology()
+
+
+def test_dynamic_neighbor_routes():
+ "r1 has ROUTE_COUNT routes from its dynamic neighbor r2."
+ tgen = get_topogen()
+ if tgen.routers_have_failure():
+ pytest.skip(tgen.errors)
+
+ r1 = tgen.gears["r1"]
+ r2 = tgen.gears["r2"]
+
+ r2.vtysh_cmd(
+ "sharp install routes 172.16.0.0 nexthop {} {}".format(NEXTHOP, ROUTE_COUNT)
+ )
+
+ def _routes_received():
+ output = json.loads(r1.vtysh_cmd("show bgp ipv4 unicast summary json"))
+ peer = output.get("ipv4Unicast", output).get("peers", {}).get(R2_IP, {})
+ if not peer.get("dynamicPeer"):
+ return "{} is not a dynamic neighbor of r1 (yet)".format(R2_IP)
+ if peer.get("state") != "Established":
+ return "state {}".format(peer.get("state"))
+ if peer.get("pfxRcd") != ROUTE_COUNT:
+ return "{} routes received".format(peer.get("pfxRcd"))
+ return None
+
+ _, result = topotest.run_and_expect(_routes_received, None, count=120, wait=1)
+ assert result is None, "r1 does not have {} routes from r2: {}".format(
+ ROUTE_COUNT, result
+ )
+
+
+def test_nothing_left_at_exit():
+ "bgpd frees everything when it exits right after the neighbor is deleted."
+ tgen = get_topogen()
+ if tgen.routers_have_failure():
+ pytest.skip(tgen.errors)
+
+ r1 = tgen.gears["r1"]
+
+ pid = r1.net.getDaemonPid("bgpd")
+ assert pid is not None, "bgpd is not running on r1"
+
+ # One shell command: the routes of the deleted neighbor are cleared a few
+ # milliseconds after the session is reset.
+ r1.cmd("vtysh -c 'clear bgp {}'; kill -TERM {}".format(R2_IP, pid))
+
+ def _bgpd_gone():
+ return "bgpd is still running" if r1.net.pid_exists(pid) else None
+
+ _, result = topotest.run_and_expect(_bgpd_gone, None, count=60, wait=1)
+ assert result is None, result
+
+ left = [
+ line
+ for line in r1.net.getStdErr("bgpd").splitlines()
+ if "memstats:" in line or "showing active allocations" in line
+ ]
+
+ # bgpd is expected to run when the topology is stopped
+ r1.startDaemons(["bgpd"])
+
+ assert not left, "bgpd did not free everything at exit:\n{}".format(
+ "\n".join(left)
+ )
+
+
+def test_memory_leak():
+ "Run the memory leak test and report results."
+ tgen = get_topogen()
+ if not tgen.is_memleak_enabled():
+ pytest.skip("Memory leak test/report is disabled")
+
+ tgen.report_memory_leaks()
+
+
+if __name__ == "__main__":
+ args = ["-s"] + sys.argv[1:]
+ sys.exit(pytest.main(args))
diff --git a/tests/topotests/lib/topotest.py b/tests/topotests/lib/topotest.py
index e465fb915f..630cb2a6ee 100644
--- a/tests/topotests/lib/topotest.py
+++ b/tests/topotests/lib/topotest.py
@@ -1830,6 +1830,13 @@ class Router(Node):
pass
return ret
+ def getDaemonPid(self, daemon):
+ "Return the pid of a running daemon of this router, None if it is not running."
+ for name, pid in self.listDaemons():
+ if name == daemon:
+ return pid
+ return None
+
def stopRouter(self, assertOnError=True):
# The listener helpers write their PID files to the gear log
# directory (next to their data dumps), not to /var/run/frr/, so