git: 6f68483d3f72 - releng/13.2 - netlink: simplify temporary address allocation in rtnl_handle_getlink().

From: Ed Maste <emaste_at_FreeBSD.org>
Date: Mon, 06 Mar 2023 19:38:21 UTC
The branch releng/13.2 has been updated by emaste:

URL: https://cgit.FreeBSD.org/src/commit/?id=6f68483d3f725052dba22b7c6bdebb71b482760d

commit 6f68483d3f725052dba22b7c6bdebb71b482760d
Author:     Alexander V. Chernikov <melifaro@FreeBSD.org>
AuthorDate: 2023-02-17 17:57:44 +0000
Commit:     Ed Maste <emaste@FreeBSD.org>
CommitDate: 2023-03-06 19:37:56 +0000

    netlink: simplify temporary address allocation in rtnl_handle_getlink().
    
    Approved by:    re (cperciva)
    
    (cherry picked from commit 45356a1864c79680c6911b48a18b14a88a7d07fa)
    (cherry picked from commit 4c1ef49999c6687905664eecd73ea9473ffe5fda)
---
 sys/netlink/route/iface.c | 13 ++++++-------
 1 file changed, 6 insertions(+), 7 deletions(-)

diff --git a/sys/netlink/route/iface.c b/sys/netlink/route/iface.c
index 0eafacff4775..96f21a79a369 100644
--- a/sys/netlink/route/iface.c
+++ b/sys/netlink/route/iface.c
@@ -439,9 +439,8 @@ rtnl_handle_getlink(struct nlmsghdr *hdr, struct nlpcb *nlp, struct nl_pstate *n
 
 	NL_LOG(LOG_DEBUG2, "Start dump");
 
-	struct ifnet **match_array;
-	int offset = 0, base_count = 16; /* start with 128 bytes */
-	match_array = malloc(base_count * sizeof(void *), M_TEMP, M_NOWAIT);
+	struct ifnet **match_array = NULL;
+	int offset = 0, base_count = 0;
 
 	NLP_LOG(LOG_DEBUG3, nlp, "MATCHING: index=%u type=%d name=%s",
 	    attrs.ifi_index, attrs.ifi_type, attrs.ifla_ifname);
@@ -452,14 +451,14 @@ rtnl_handle_getlink(struct nlmsghdr *hdr, struct nlpcb *nlp, struct nl_pstate *n
 			if (offset >= base_count) {
 				/* Too many matches, need to reallocate */
 				struct ifnet **new_array;
-				int sz = base_count * sizeof(void *);
-				base_count *= 2;
-				new_array = malloc(sz * 2, M_TEMP, M_NOWAIT);
+				/* Start with 128 bytes, do 2x increase on each realloc */
+				base_count = (base_count != 0) ? base_count * 2 : 16;
+				new_array = malloc(base_count * sizeof(void *), M_TEMP, M_NOWAIT);
 				if (new_array == NULL) {
 					error = ENOMEM;
 					break;
 				}
-				memcpy(new_array, match_array, sz);
+				memcpy(new_array, match_array, offset * sizeof(void *));
 				free(match_array, M_TEMP);
 				match_array = new_array;
 			}