From: Alexey Dobriyan <adobriyan@gmail.com>
To: linux-kernel@vger.kernel.org
Cc: torvalds@vger.kernel.org
Subject: PSA: BITS_TO_LONGS() most likely returns size_t, not what you think
Date: Sun, 22 Oct 2023 22:39:54 +0300 [thread overview]
Message-ID: <bc0958d7-385f-49b5-97e9-6355b29a2502@p183> (raw)
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.
reply other threads:[~2023-10-22 19:40 UTC|newest]
Thread overview: [no followups] expand[flat|nested] mbox.gz Atom feed
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=bc0958d7-385f-49b5-97e9-6355b29a2502@p183 \
--to=adobriyan@gmail.com \
--cc=linux-kernel@vger.kernel.org \
--cc=torvalds@vger.kernel.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
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®