[Dnsmasq-discuss] [PATCH 1/3] Avoid O(n^2) lease scan in do_script_run() when nothing consumes lease events.

Axel Jacquet axel.jacquet at infomaniak.com
Wed Nov 25 09:50:12 UTC 2026


After SIGHUP, rerun_scripts() marks every lease as changed. do_script_run()
then handles one lease per call and restarts the scan of the lease list
from the beginning each time, which is O(n^2) in the number of leases.
That is needed when events go to a lease-change script or DBus, so the
caller can flush them one at a time, but without either of them all that
is done is clearing flags. In that case, do all the work in a single pass.

With 35000 leases this took about half of the 18s CPU time of a SIGHUP.
---
 src/lease.c | 27 ++++++++++++++++++++++-----
 1 file changed, 22 insertions(+), 5 deletions(-)

diff --git a/src/lease.c b/src/lease.c
index 6766151..99c6009 100644
--- a/src/lease.c
+++ b/src/lease.c
@@ -1235,6 +1235,7 @@ void rerun_scripts(void)
 int do_script_run(time_t now)
 {
   struct dhcp_lease *lease;
+  int one_at_a_time = 0;
 
   (void)now;
 
@@ -1243,9 +1244,21 @@ int do_script_run(time_t now)
      delay everything until it is. */
   if (option_bool(OPT_DBUS) && !daemon->dbus)
     return 0;
+
+  if (option_bool(OPT_DBUS))
+    one_at_a_time = 1;
+#endif
+
+#ifdef HAVE_SCRIPT
+  if (daemon->helperfd != -1)
+    one_at_a_time = 1;
 #endif
 
-  if (old_leases)
+  /* When events go to a script or DBus, handle one per call so that the
+     caller can flush them in between. Otherwise there is nobody to tell,
+     so do all the work in one pass: restarting the scan of the lease list
+     for each lease is O(n^2), and a SIGHUP marks every lease as changed. */
+  while (old_leases)
     {
       lease = old_leases;
                   
@@ -1257,7 +1270,8 @@ int do_script_run(time_t now)
 #endif
 	  free(lease->old_hostname);
 	  lease->old_hostname = NULL;
-	  return 1;
+	  if (one_at_a_time)
+	    return 1;
 	}
       else 
 	{
@@ -1276,7 +1290,8 @@ int do_script_run(time_t now)
 	  free(lease->vendorclass);
 	  free(lease);
 	    
-	  return 1; 
+	  if (one_at_a_time)
+	    return 1;
 	}
     }
   
@@ -1289,7 +1304,8 @@ int do_script_run(time_t now)
 #endif
 	free(lease->old_hostname);
 	lease->old_hostname = NULL;
-	return 1;
+	if (one_at_a_time)
+	  return 1;
       }
   
   for (lease = leases; lease; lease = lease->next)
@@ -1311,7 +1327,8 @@ int do_script_run(time_t now)
 	free(lease->extradata);
 	lease->extradata = NULL;
 	
-	return 1;
+	if (one_at_a_time)
+	  return 1;
       }
 
   return 0; /* nothing to do */
-- 
2.47.0




More information about the Dnsmasq-discuss mailing list