Commit 6a8ffb09a1 for frr

commit 6a8ffb09a1423bd94a6619da6c63936ff9d9d325
Author: Nick Bouliane <nbouliane@coreweave.com>
Date:   Fri Nov 27 14:30:16 2026 -0500

    bgpd: stop the tier-2 deferral timer of a deleted BGP instance

    A BGP instance that restarts gracefully and has both directly connected
    and multihop peers defers its path selection in two stages. When the
    directly connected peers are done, bgp_start_tier2_deferral_timer()
    starts a second timer, t_select_deferral_tier2, to wait for the
    End-of-RIB of the multihop peers. The argument of the timer is
    allocated, and has a pointer to the BGP instance.

    bgp_delete() cancels the two other timers of the graceful restart info,
    t_select_deferral and t_route_select, and frees their arguments, but
    not this one. When a BGP instance is deleted while the timer is
    running:

    - with "no router bgp", the timer expires for an instance that is not
      there anymore, and bgpd crashes:

        BGP: Received signal 11 at 1795826973 (si_addr 0x40, PC 0x244dc0)
        [...]
        BGP: /usr/lib/frr/bgpd(bgp_deferred_path_selection+0x41)
        BGP: /usr/lib/frr/bgpd(bgp_do_deferred_path_selection+0x3cb)
        BGP: /usr/lib/frr/bgpd(+0x18f80d)
        BGP: /lib/libfrr.so.0(event_call+0x1ac)
        [...]
        BGP: in thread bgp_graceful_deferral_timer_expire scheduled from
             bgpd/bgp_fsm.c:983 bgp_start_tier2_deferral_timer()

    - when bgpd is terminated, the argument of the timer is not freed, and
      is in the memory report at exit:

        Temporary memory              :      1 * (variably sized)

    Cancel the timer and free its argument in bgp_delete(), like it is
    done for the two other timers.

    Add a topotest, bgp_gr_tier2_timer_instance_delete. r1 restarts
    gracefully with a directly connected peer, r2, and a multihop neighbor
    that there is no router for, so that the tier-2 timer runs until it
    expires. While it is running, the test terminates bgpd, which must not
    report anything in the memory statistics that it writes to its stderr
    at exit. Then it removes the BGP instance from the configuration: bgpd
    must not have a selection deferral timer in "show event timers"
    anymore.

    The test stops bgpd with Router.stopRouterDaemons(), new in the
    topotest library: it sends SIGTERM to the given daemons and waits until
    they are gone. killRouterDaemons() cannot be used here, it sends
    SIGKILL and bgpd would not write its memory statistics.

    Without the fix the first check fails with the line of the memory
    report that is above. The second one is then skipped; when it is run
    alone, with -k test_instance_deleted, it fails because the timer is
    still scheduled:

        bgp_graceful_deferral_timer_expire                00:00:19.900

    Fixes: 72f2e6da60 ("bgpd: GR handling for multihop BGP peers")
    Signed-off-by: Nick Bouliane <nbouliane@coreweave.com>

diff --git a/bgpd/bgpd.c b/bgpd/bgpd.c
index 9bc8fafa76..d50d9de337 100644
--- a/bgpd/bgpd.c
+++ b/bgpd/bgpd.c
@@ -4787,6 +4787,14 @@ int bgp_delete(struct bgp *bgp)
 		}
 		event_cancel(&gr_info->t_select_deferral);

+		t = gr_info->t_select_deferral_tier2;
+		if (t) {
+			void *info = EVENT_ARG(t);
+
+			XFREE(MTYPE_TMP, info);
+		}
+		event_cancel(&gr_info->t_select_deferral_tier2);
+
 		t = gr_info->t_route_select;
 		if (t) {
 			void *info = EVENT_ARG(t);
diff --git a/tests/topotests/bgp_gr_tier2_timer_instance_delete/__init__.py b/tests/topotests/bgp_gr_tier2_timer_instance_delete/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/topotests/bgp_gr_tier2_timer_instance_delete/r1/frr.conf b/tests/topotests/bgp_gr_tier2_timer_instance_delete/r1/frr.conf
new file mode 100644
index 0000000000..d226816e4e
--- /dev/null
+++ b/tests/topotests/bgp_gr_tier2_timer_instance_delete/r1/frr.conf
@@ -0,0 +1,17 @@
+!
+! r1 starts with graceful restart and defers its path selection: until it
+! has the End-of-RIB of r2, then until it has the one of its multihop peer,
+! which is not there.
+!
+interface r1-eth0
+ ip address 192.168.1.1/24
+!
+router bgp 65001
+ no bgp ebgp-requires-policy
+ bgp graceful-restart
+ bgp graceful-restart select-defer-time 20
+ neighbor 192.168.1.2 remote-as external
+ neighbor 192.168.1.2 timers connect 1
+ neighbor 192.168.1.3 remote-as external
+ neighbor 192.168.1.3 ebgp-multihop 2
+!
diff --git a/tests/topotests/bgp_gr_tier2_timer_instance_delete/r2/frr.conf b/tests/topotests/bgp_gr_tier2_timer_instance_delete/r2/frr.conf
new file mode 100644
index 0000000000..83322d89e8
--- /dev/null
+++ b/tests/topotests/bgp_gr_tier2_timer_instance_delete/r2/frr.conf
@@ -0,0 +1,11 @@
+!
+! r2 is directly connected to r1.
+!
+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
+!
diff --git a/tests/topotests/bgp_gr_tier2_timer_instance_delete/test_bgp_gr_tier2_timer_instance_delete.py b/tests/topotests/bgp_gr_tier2_timer_instance_delete/test_bgp_gr_tier2_timer_instance_delete.py
new file mode 100644
index 0000000000..160dc70ca9
--- /dev/null
+++ b/tests/topotests/bgp_gr_tier2_timer_instance_delete/test_bgp_gr_tier2_timer_instance_delete.py
@@ -0,0 +1,184 @@
+#!/usr/bin/env python
+# SPDX-License-Identifier: ISC
+
+#
+# Copyright (c) 2026 by Nick Bouliane <nbouliane@coreweave.com>
+#
+
+"""
+bgpd must stop the tier-2 selection deferral timer of a BGP instance that it
+deletes.
+
+r1 starts with graceful restart and defers its path selection. It has a
+directly connected peer, r2, and a multihop peer, so it does this in two
+stages: once r2 is done, it starts the tier-2 selection deferral timer and
+waits for the End-of-RIB of the multihop peer.
+
+There is no router at the address of the multihop peer, so the tier-2 timer
+runs until it expires, after 20 seconds. The test deletes the BGP instance
+while the timer is running, in two ways:
+
+- it terminates bgpd. bgpd writes the memory that it did not free at exit to
+  its stderr, which must be empty. Without the fix it has the argument of the
+  timer:
+
+    bgpd: memstats:  Temporary memory              :      1 * (variably sized)
+
+- it removes the instance from the configuration. bgpd must not have the
+  timer anymore: "show event timers" must not have a timer that calls
+  bgp_graceful_deferral_timer_expire(). Without the fix the timer is still
+  there, and bgpd crashes in that function when it expires.
+"""
+
+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]
+
+R2_IP = "192.168.1.2"
+
+# What the selection deferral timers call when they expire
+DEFERRAL_TIMER_FUNC = "bgp_graceful_deferral_timer_expire"
+
+
+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():
+        router.load_frr_config(os.path.join(CWD, "{}/frr.conf".format(rname)))
+
+    tgen.start_router()
+
+
+def teardown_module(mod):
+    tgen = get_topogen()
+    tgen.stop_topology()
+
+
+def _has_key(node, key):
+    "Tell if key is somewhere in the JSON output node."
+    if isinstance(node, dict):
+        return key in node or any(_has_key(value, key) for value in node.values())
+    if isinstance(node, list):
+        return any(_has_key(value, key) for value in node)
+    return False
+
+
+def _wait_tier2_timer(router):
+    "Wait until router has started the tier-2 selection deferral timer."
+
+    def _tier2_timer_running():
+        try:
+            output = json.loads(
+                router.vtysh_cmd(
+                    "show bgp neighbors {} graceful-restart json".format(R2_IP)
+                )
+            )
+        except ValueError:
+            return "bgpd does not answer"
+        if not _has_key(output, "selectionDeferralTier2TimerRemaining"):
+            return "the tier-2 selection deferral timer is not running"
+        return None
+
+    _, result = topotest.run_and_expect(_tier2_timer_running, None, count=60, wait=1)
+    assert result is None, result
+
+
+def _deferral_timers(router):
+    "The selection deferral timers that the bgpd of router has scheduled."
+    output = router.vtysh_cmd("show event timers", daemon="bgpd")
+    return [line for line in output.splitlines() if DEFERRAL_TIMER_FUNC in line]
+
+
+def test_nothing_left_at_exit():
+    "bgpd frees everything when it exits while the tier-2 timer is running."
+    tgen = get_topogen()
+    if tgen.routers_have_failure():
+        pytest.skip(tgen.errors)
+
+    r1 = tgen.gears["r1"]
+
+    _wait_tier2_timer(r1)
+
+    running = r1.net.stopRouterDaemons(["bgpd"])
+    assert not running, "bgpd is still running"
+
+    left = [
+        line
+        for line in r1.net.getStdErr("bgpd").splitlines()
+        if "memstats:" in line or "showing active allocations" in line
+    ]
+
+    # The next test needs bgpd, with its configuration
+    r1.startDaemons(["bgpd"])
+
+    assert not left, "bgpd did not free everything at exit:\n{}".format(
+        "\n".join(left)
+    )
+
+
+def test_instance_deleted():
+    "bgpd keeps running when its instance is deleted with the tier-2 timer running."
+    tgen = get_topogen()
+    if tgen.routers_have_failure():
+        pytest.skip(tgen.errors)
+
+    r1 = tgen.gears["r1"]
+
+    _wait_tier2_timer(r1)
+
+    # What is checked below must be there before the instance is deleted
+    assert _deferral_timers(r1), "bgpd has no selection deferral timer scheduled"
+
+    pid = r1.net.getDaemonPid("bgpd")
+    assert pid is not None, "bgpd is not running on r1"
+
+    r1.vtysh_cmd(
+        """
+        configure terminal
+        no router bgp 65001
+        """
+    )
+
+    # Not waiting for the timer to expire: how long that takes depends on how
+    # busy bgpd is, and a timer that is late would go unnoticed.
+    left = _deferral_timers(r1)
+    assert not left, "bgpd still has a timer of the deleted instance:\n{}".format(
+        "\n".join(left)
+    )
+
+    assert r1.net.pid_exists(pid), "bgpd is not running anymore"
+
+
+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 630cb2a6ee..c5d6787a56 100644
--- a/tests/topotests/lib/topotest.py
+++ b/tests/topotests/lib/topotest.py
@@ -2825,6 +2825,43 @@ class Router(Node):
         rc, o, e = self.cmd_status("kill -0 " + str(pid), warn=False)
         return rc == 0 or "No such process" not in e

+    def stopRouterDaemons(self, daemons, timeout=60):
+        """
+        Stop the given daemons of this router with SIGTERM, so that they exit
+        cleanly, and wait until they are gone. killRouterDaemons() uses SIGKILL.
+
+        Returns the daemons that are still running after timeout seconds.
+        """
+        pids = {}
+        for daemon in daemons:
+            pid = self.getDaemonPid(daemon)
+            if pid is None:
+                continue
+            logger.info("%s: stopping %s", self.name, daemon)
+            self.cmd_status("kill -TERM {}".format(pid), warn=False)
+            pids[daemon] = pid
+
+        stopped = list(pids)
+        for _ in range(0, timeout * 2):
+            pids = {d: pid for d, pid in pids.items() if self.pid_exists(pid)}
+            if not pids:
+                break
+            sleep(
+                0.5,
+                "{}: waiting for daemons stopping: {}".format(
+                    self.name, ", ".join(pids)
+                ),
+            )
+
+        for daemon in stopped:
+            if daemon not in pids:
+                self.cmd_status(
+                    "rm -f /var/run/{}/{}.pid".format(self.routertype, daemon),
+                    warn=False,
+                )
+
+        return list(pids)
+
     def killRouterDaemons(self, daemons, wait=True, assertOnError=True):
         # Kill Running FRR
         # Daemons(user specified daemon only) using SIGKILL