diff mbox series

bcachefs: Prefer struct_size over open coded arithmetic

Message ID 20240224151658.8272-1-erick.archer@gmx.com (mailing list archive)
State Superseded
Headers show
Series bcachefs: Prefer struct_size over open coded arithmetic | expand

Commit Message

Erick Archer Feb. 24, 2024, 3:16 p.m. UTC
This is an effort to get rid of all multiplications from allocation
functions in order to prevent integer overflows [1][2].

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

struct journal_seq_blacklist_table {
	[...]
	struct journal_seq_blacklist_table_entry {
		u64		start;
		u64		end;
		bool		dirty;
	}			entries[];
};

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.

Link: https://www.kernel.org/doc/html/latest/process/deprecated.html#open-coded-arithmetic-in-allocator-arguments [1]
Link: https://github.com/KSPP/linux/issues/160 [2]
Signed-off-by: Erick Archer <erick.archer@gmx.com>
---
 fs/bcachefs/journal_seq_blacklist.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

--
2.25.1

Comments

Kent Overstreet Feb. 25, 2024, 12:52 a.m. UTC | #1
On Sat, Feb 24, 2024 at 04:16:58PM +0100, Erick Archer wrote:
> This is an effort to get rid of all multiplications from allocation
> functions in order to prevent integer overflows [1][2].
> 
> As the "t" variable is a pointer to "struct journal_seq_blacklist_table"
> and this structure ends in a flexible array:

there's no reason to break these out into multiple patches, just send me
a single patch when you're done - thanks!
diff mbox series

Patch

diff --git a/fs/bcachefs/journal_seq_blacklist.c b/fs/bcachefs/journal_seq_blacklist.c
index 024c9b1b323f..2c2490aa15fe 100644
--- a/fs/bcachefs/journal_seq_blacklist.c
+++ b/fs/bcachefs/journal_seq_blacklist.c
@@ -165,8 +165,7 @@  int bch2_blacklist_table_initialize(struct bch_fs *c)
 	if (!bl)
 		return 0;

-	t = kzalloc(sizeof(*t) + sizeof(t->entries[0]) * nr,
-		    GFP_KERNEL);
+	t = kzalloc(struct_size(t, entries, nr), GFP_KERNEL);
 	if (!t)
 		return -BCH_ERR_ENOMEM_blacklist_table_init;