mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* PSA: BITS_TO_LONGS() most likely returns size_t, not what you think
@ 2023-10-22 19:39 Alexey Dobriyan
  0 siblings, 0 replies; only message in thread
From: Alexey Dobriyan @ 2023-10-22 19:39 UTC (permalink / raw)
  To: linux-kernel; +Cc: torvalds

I wrote the following code today (don't ask):

	for (int i = 0; i <= BITS_TO_LONGS(NR_CPUS) - 2; i += 1) {	
	}

only to get near infinite loop. Note that NR_CPUS is "int".

This is because BITS_TO_LONGS() and __KERNEL_DIV_ROUND_UP() macros work
together to promote everything to "size_t". The loop essientially
becomes:

	for (int i = 0; i <= (size_t)-1; i += 1) {
	}

This is easily fixable by doing very sketchy and obvious thing.

--- a/include/linux/bitops.h
+++ b/include/linux/bitops.h
@@ -16,7 +16,7 @@
 #  define aligned_byte_mask(n) (~0xffUL << (BITS_PER_LONG - 8 - 8*(n)))
 #endif
 
-#define BITS_PER_TYPE(type)	(sizeof(type) * BITS_PER_BYTE)
+#define BITS_PER_TYPE(type)	((int)sizeof(type) * BITS_PER_BYTE)
 #define BITS_TO_LONGS(nr)	__KERNEL_DIV_ROUND_UP(nr, BITS_PER_TYPE(long))
 #define BITS_TO_U64(nr)		__KERNEL_DIV_ROUND_UP(nr, BITS_PER_TYPE(u64))
 #define BITS_TO_U32(nr)		__KERNEL_DIV_ROUND_UP(nr, BITS_PER_TYPE(u32))

Ideally __KERNEL_DIV_ROUND_UP() should return the type of the first
argument but this stuff is UAPI header which complicates things.

^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2023-10-22 19:40 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2023-10-22 19:39 PSA: BITS_TO_LONGS() most likely returns size_t, not what you think Alexey Dobriyan

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®