Skip to contentSkip to conversation

brcmfmac: Use struct_size() in kzalloc()

PATCH In review Gustavo A. R. Silva 2 participants 2 messages Apr 3, 2019 – Apr 13, 2019

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

PATCH 1/1 brcmfmac: Use struct_size() in 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[];
};

size = sizeof(struct foo) + count * sizeof(struct boo); instance = kzalloc(size, GFP_KERNEL)

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

instance = kzalloc(struct_size(instance, entry, count), GFP_KERNEL)

Notice that, in this case, variable reqsz is not necessary, hence it is removed.

This code was detected with the help of Coccinelle.

---
 drivers/net/wireless/broadcom/brcm80211/brcmfmac/firmware.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
drivers/net/wireless/broadcom/brcm80211/brcmfmac/firmware.c +1 -3
index 8209a42dea72..07b3ba949da5 100644
@@ -711,7 +711,6 @@ brcmf_fw_alloc_request(u32 chip, u32 chiprev,
 	size_t mp_path_len;
 	u32 i, j;
 	char end = '\0';
-	size_t reqsz;
 
 	for (i = 0; i < table_size; i++) {
 		if (mapping_table[i].chipid == chip &&
@@ -726,8 +725,7 @@ brcmf_fw_alloc_request(u32 chip, u32 chiprev,
 		return NULL;
 	}
 
-	reqsz = sizeof(*fwreq) + n_fwnames * sizeof(struct brcmf_fw_item);
-	fwreq = kzalloc(reqsz, GFP_KERNEL);
+	fwreq = kzalloc(struct_size(fwreq, items, n_fwnames), GFP_KERNEL);
 	if (!fwreq)
 		return NULL;
 
Signature · 1 line
2.21.0
#1 lore raw
Quoted 15 lines · Gustavo A. R. Silva

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[];
};

size = sizeof(struct foo) + count * sizeof(struct boo); instance = kzalloc(size, GFP_KERNEL)

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

Quoted 8 lines

instance = kzalloc(struct_size(instance, entry, count), GFP_KERNEL)

Notice that, in this case, variable reqsz is not necessary, hence it is removed.

This code was detected with the help of Coccinelle.

Patch applied to wireless-drivers-next.git, thanks.

0cf83903aad0 brcmfmac: Use struct_size() in kzalloc()

Signature · 3 lines
https://patchwork.kernel.org/patch/10884189/

https://wireless.wiki.kernel.org/en/developers/documentation/submittingpatches