Commit 9f8c7136 authored by Gustavo A. R. Silva's avatar Gustavo A. R. Silva Committed by Johannes Berg
Browse files

cfg80211: 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 size_of_regd is not necessary,
hence it is removed.

This code was detected with the help of Coccinelle.

Signed-off-by: default avatarGustavo A. R. Silva <gustavo@embeddedor.com>
Signed-off-by: default avatarJohannes Berg <johannes.berg@intel.com>
parent 276d9e82
Loading
Loading
Loading
Loading
+7 −16
Original line number Diff line number Diff line
@@ -427,14 +427,10 @@ static const struct ieee80211_regdomain *
reg_copy_regd(const struct ieee80211_regdomain *src_regd)
{
	struct ieee80211_regdomain *regd;
	int size_of_regd;
	unsigned int i;

	size_of_regd =
		sizeof(struct ieee80211_regdomain) +
		src_regd->n_reg_rules * sizeof(struct ieee80211_reg_rule);

	regd = kzalloc(size_of_regd, GFP_KERNEL);
	regd = kzalloc(struct_size(regd, reg_rules, src_regd->n_reg_rules),
		       GFP_KERNEL);
	if (!regd)
		return ERR_PTR(-ENOMEM);

@@ -948,12 +944,10 @@ static int regdb_query_country(const struct fwdb_header *db,
	unsigned int ptr = be16_to_cpu(country->coll_ptr) << 2;
	struct fwdb_collection *coll = (void *)((u8 *)db + ptr);
	struct ieee80211_regdomain *regdom;
	unsigned int size_of_regd, i;

	size_of_regd = sizeof(struct ieee80211_regdomain) +
		coll->n_rules * sizeof(struct ieee80211_reg_rule);
	unsigned int i;

	regdom = kzalloc(size_of_regd, GFP_KERNEL);
	regdom = kzalloc(struct_size(regdom, reg_rules, coll->n_rules),
			 GFP_KERNEL);
	if (!regdom)
		return -ENOMEM;

@@ -1450,7 +1444,7 @@ static struct ieee80211_regdomain *
regdom_intersect(const struct ieee80211_regdomain *rd1,
		 const struct ieee80211_regdomain *rd2)
{
	int r, size_of_regd;
	int r;
	unsigned int x, y;
	unsigned int num_rules = 0;
	const struct ieee80211_reg_rule *rule1, *rule2;
@@ -1481,10 +1475,7 @@ regdom_intersect(const struct ieee80211_regdomain *rd1,
	if (!num_rules)
		return NULL;

	size_of_regd = sizeof(struct ieee80211_regdomain) +
		       num_rules * sizeof(struct ieee80211_reg_rule);

	rd = kzalloc(size_of_regd, GFP_KERNEL);
	rd = kzalloc(struct_size(rd, reg_rules, num_rules), GFP_KERNEL);
	if (!rd)
		return NULL;