Skip to contentSkip to conversation

net: hns: use struct_size() in devm_kzalloc()

PATCH Applied Gustavo A. R. Silva 2 participants 2 messages Feb 26, 2019 – Feb 28, 2019

Subsystems (3)
lore
Share & tools
lore
#0 lore raw

PATCH 1/1 net: hns: use struct_size() in devm_kzalloc()

One of the more common cases of allocation size calculations is finding the size of a structure that has a zero-sized array at the end, along with memory for some number of elements for that array. For example:

struct foo {
    int stuff;
    struct boo entry[];
};

instance = devm_kzalloc(dev, sizeof(struct foo) + sizeof(struct boo) * count, GFP_KERNEL);

Instead of leaving these open-coded and prone to type mistakes, we can now use the new struct_size() helper:

instance = devm_kzalloc(dev, struct_size(instance, entry, count), GFP_KERNEL);

This code was detected with the help of Coccinelle.

---
 drivers/net/ethernet/hisilicon/hns/hns_dsaf_ppe.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/net/ethernet/hisilicon/hns/hns_dsaf_ppe.c +3 -2
index 0942e4916d9d..3d07c8a7639d 100644
@@ -83,8 +83,9 @@ static int hns_ppe_common_get_cfg(struct dsaf_device *dsaf_dev, int comm_index)
 	else
 		ppe_num = HNS_PPE_DEBUG_NW_ENGINE_NUM;
 
-	ppe_common = devm_kzalloc(dsaf_dev->dev, sizeof(*ppe_common) +
-		ppe_num * sizeof(struct hns_ppe_cb), GFP_KERNEL);
+	ppe_common = devm_kzalloc(dsaf_dev->dev,
+				  struct_size(ppe_common, ppe_cb, ppe_num),
+				  GFP_KERNEL);
 	if (!ppe_common)
 		return -ENOMEM;
 
Signature · 1 line
2.20.1
maintainer Applied
#1 lore raw

From: "Gustavo A. R. Silva" <[email protected]>
Date: Mon, 25 Feb 2019 18:27:57 -0600

Quoted 11 lines

One of the more common cases of allocation size calculations is finding the size of a structure that has a zero-sized array at the end, along with memory for some number of elements for that array. For example:

struct foo {
    int stuff;
    struct boo entry[];
};

instance = devm_kzalloc(dev, sizeof(struct foo) + sizeof(struct boo) * count, GFP_KERNEL);

Quoted 8 lines

Instead of leaving these open-coded and prone to type mistakes, we can now use the new struct_size() helper:

instance = devm_kzalloc(dev, struct_size(instance, entry, count), GFP_KERNEL);

This code was detected with the help of Coccinelle.

Applied.