Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

s390: Add __attribute_const__ to ffs()-family implementations

While tracking down a problem where constant expressions used by
BUILD_BUG_ON() suddenly stopped working[1], we found that an added static
initializer was convincing the compiler that it couldn't track the state
of the prior statically initialized value. Tracing this down found that
ffs() was used in the initializer macro, but since it wasn't marked with
__attribute__const__, the compiler had to assume the function might
change variable states as a side-effect (which is not true for ffs(),
which provides deterministic math results).

Add missing __attribute_const__ annotations to S390's implementations of
ffs(), __ffs(), fls(), and __fls() functions. These are pure mathematical
functions that always return the same result for the same input with no
side effects, making them eligible for compiler optimization.

Build tested ARCH=s390 defconfig with GCC s390x-linux-gnu 14.2.0.

Link: https://github.com/KSPP/linux/issues/364 [1]
Acked-by: Heiko Carstens <hca@linux.ibm.com>
Acked-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Link: https://lore.kernel.org/r/20250804164417.1612371-14-kees@kernel.org
Signed-off-by: Kees Cook <kees@kernel.org>

Kees Cook b77fee88 28fc0972

+5 -5
+5 -5
arch/s390/include/asm/bitops.h
··· 179 179 * 180 180 * Undefined if no bit exists, so code should check against 0 first. 181 181 */ 182 - static inline unsigned long __ffs(unsigned long word) 182 + static inline __attribute_const__ unsigned long __ffs(unsigned long word) 183 183 { 184 184 return __flogr(-word & word) ^ (BITS_PER_LONG - 1); 185 185 } ··· 191 191 * This is defined the same way as the libc and 192 192 * compiler builtin ffs routines (man ffs). 193 193 */ 194 - static inline int ffs(int word) 194 + static inline __attribute_const__ int ffs(int word) 195 195 { 196 196 unsigned long mask = 2 * BITS_PER_LONG - 1; 197 197 unsigned int val = (unsigned int)word; ··· 205 205 * 206 206 * Undefined if no set bit exists, so code should check against 0 first. 207 207 */ 208 - static inline unsigned long __fls(unsigned long word) 208 + static inline __attribute_const__ unsigned long __fls(unsigned long word) 209 209 { 210 210 return __flogr(word) ^ (BITS_PER_LONG - 1); 211 211 } ··· 221 221 * set bit if value is nonzero. The last (most significant) bit is 222 222 * at position 64. 223 223 */ 224 - static inline int fls64(unsigned long word) 224 + static inline __attribute_const__ int fls64(unsigned long word) 225 225 { 226 226 unsigned long mask = 2 * BITS_PER_LONG - 1; 227 227 ··· 235 235 * This is defined the same way as ffs. 236 236 * Note fls(0) = 0, fls(1) = 1, fls(0x80000000) = 32. 237 237 */ 238 - static inline int fls(unsigned int word) 238 + static inline __attribute_const__ int fls(unsigned int word) 239 239 { 240 240 return fls64(word); 241 241 }