Skip to contentSkip to conversation

bcachefs: Prefer struct_size over open coded arithmetic

PATCH New Erick Archer 1 participant 1 message Feb 24, 2024

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 bcachefs: Prefer struct_size over open coded arithmetic

This is an effort to get rid of all multiplications from allocation functions in order to prevent integer overflows [1][2].

As the "op" variable is a pointer to "struct promote_op" and this structure ends in a flexible array:

struct promote_op {
	[...]
	struct bio_vec bi_inline_vecs[];
};

the preferred way in the kernel is to use the struct_size() helper to do the arithmetic instead of the argument "size + size * count" in the kzalloc() function.

This way, the code is more readable and safer.

---
 fs/bcachefs/io_read.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/bcachefs/io_read.c +1 -1
index dce136cd2271..01beab55c6b3 100644
@@ -174,7 +174,7 @@ static struct promote_op *__promote_alloc(struct btree_trans *trans,
 	if (!bch2_write_ref_tryget(c, BCH_WRITE_REF_promote))
 		return ERR_PTR(-BCH_ERR_nopromote_no_writes);
 
-	op = kzalloc(sizeof(*op) + sizeof(struct bio_vec) * pages, GFP_KERNEL);
+	op = kzalloc(struct_size(op, bi_inline_vecs, pages), GFP_KERNEL);
 	if (!op) {
 		ret = -BCH_ERR_nopromote_enomem;
 		goto err;

--
2.25.1