PSA: BITS_TO_LONGS() most likely returns size_t, not what you think

Message ID bc0958d7-385f-49b5-97e9-6355b29a2502@p183
State New
Headers
Series PSA: BITS_TO_LONGS() most likely returns size_t, not what you think |

Commit Message

Alexey Dobriyan Oct. 22, 2023, 7:39 p.m. UTC
  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.


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

Patch

--- 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))