[PATCH] net: macvlan: fix memory leaks of macvlan_common_newlink

From: Chuang Wang
Date: Wed Nov 09 2022 - 04:09:00 EST


kmemleak reports memory leaks in macvlan_common_newlink, as follows:

ip link add link eth0 name .. type macvlan mode source macaddr add
<MAC-ADDR>

kmemleak reports:

unreferenced object 0xffff8880109bb140 (size 64):
comm "ip", pid 284, jiffies 4294986150 (age 430.108s)
hex dump (first 32 bytes):
00 00 00 00 00 00 00 00 b8 aa 5a 12 80 88 ff ff ..........Z.....
80 1b fa 0d 80 88 ff ff 1e ff ac af c7 c1 6b 6b ..............kk
backtrace:
[<ffffffff813e06a7>] kmem_cache_alloc_trace+0x1c7/0x300
[<ffffffff81b66025>] macvlan_hash_add_source+0x45/0xc0
[<ffffffff81b66a67>] macvlan_changelink_sources+0xd7/0x170
[<ffffffff81b6775c>] macvlan_common_newlink+0x38c/0x5a0
[<ffffffff81b6797e>] macvlan_newlink+0xe/0x20
[<ffffffff81d97f8f>] __rtnl_newlink+0x7af/0xa50
[<ffffffff81d98278>] rtnl_newlink+0x48/0x70
...

In the scenario where the macvlan mode is configured as 'source',
macvlan_changelink_sources() will be execured to reconfigure list of
remote source mac addresses, at the same time, if register_netdevice()
return an error, the resource generated by macvlan_changelink_sources()
is not cleaned up.

Using this patch, in the case of an error, it will execute
macvlan_flush_sources() to ensure that the resource is cleaned up.

Fixes: aa5fd0fb7748 ("driver: macvlan: Destroy new macvlan port if macvlan_common_newlink failed.")
Signed-off-by: Chuang Wang <nashuiliang@xxxxxxxxx>
---
drivers/net/macvlan.c | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/drivers/net/macvlan.c b/drivers/net/macvlan.c
index c58fea63be7d..28f9f917ff54 100644
--- a/drivers/net/macvlan.c
+++ b/drivers/net/macvlan.c
@@ -1533,8 +1533,10 @@ int macvlan_common_newlink(struct net *src_net, struct net_device *dev,
/* the macvlan port may be freed by macvlan_uninit when fail to register.
* so we destroy the macvlan port only when it's valid.
*/
- if (create && macvlan_port_get_rtnl(lowerdev))
+ if (create && macvlan_port_get_rtnl(lowerdev)) {
+ macvlan_flush_sources(port, vlan);
macvlan_port_destroy(port->dev);
+ }
return err;
}
EXPORT_SYMBOL_GPL(macvlan_common_newlink);
--
2.37.2