]> git.ipfire.org Git - thirdparty/kernel/linux.git/commitdiff
lib: count_zeros: fix 32/64-bit inconsistency in count_trailing_zeros()
authorYury Norov <ynorov@nvidia.com>
Thu, 12 Mar 2026 23:08:16 +0000 (19:08 -0400)
committerYury Norov <ynorov@nvidia.com>
Mon, 23 Mar 2026 17:33:51 +0000 (13:33 -0400)
Based on 'sizeof(x) == 4' condition, in 32-bit case the function is wired
to ffs(), while in 64-bit case to __ffs(). The difference is substantial:
ffs(x) == __ffs(x) + 1. Also, ffs(0) == 0, while __ffs(0) is undefined.

The 32-bit behaviour is inconsistent with the function description, so it
needs to get fixed.

There are 9 individual users for the function in 6 different subsystems.
Some arches and drivers are 64-bit only:
 - arch/loongarch/kvm/intc/eiointc.c;
 - drivers/hv/mshv_vtl_main.c;
 - kernel/liveupdate/kexec_handover.c;

The others are:
 - ib_umem_find_best_pgsz(): as per comment, __ffs() should be correct;
 - rzv2m_csi_reg_write_bit(): ARCH_RENESAS only, unclear;
 - lz77_match_len(): CIFS_COMPRESSION only, unclear, experimental;

IB and CIFS are explicitly OK with the change.

The attached patch gets rid of 32-bit explicit support, so that both
32- and 64-bit versions rely on __ffs().

CC: K. Y. Srinivasan <kys@microsoft.com>
CC: Haiyang Zhang <haiyangz@microsoft.com>
CC: Mark Brown <broonie@kernel.org>
CC: Steve French <sfrench@samba.org>
CC: Alexander Graf <graf@amazon.com>
CC: Mike Rapoport <rppt@kernel.org>
CC: Pasha Tatashin <pasha.tatashin@soleen.com>
Acked-by: Leon Romanovsky <leon@kernel.org>
Signed-off-by: Yury Norov <ynorov@nvidia.com>
include/linux/count_zeros.h

index 4e5680327ece808c9dce5fd2cdaff86dff6bd2e0..5034a30b5c7c76d39bccf83e4e8fda4ce5592d36 100644 (file)
@@ -10,6 +10,8 @@
 
 #include <asm/bitops.h>
 
+#define COUNT_TRAILING_ZEROS_0 (-1)
+
 /**
  * count_leading_zeros - Count the number of zeros from the MSB back
  * @x: The value
@@ -40,12 +42,7 @@ static inline int count_leading_zeros(unsigned long x)
  */
 static inline int count_trailing_zeros(unsigned long x)
 {
-#define COUNT_TRAILING_ZEROS_0 (-1)
-
-       if (sizeof(x) == 4)
-               return ffs(x);
-       else
-               return (x != 0) ? __ffs(x) : COUNT_TRAILING_ZEROS_0;
+       return (x != 0) ? __ffs(x) : COUNT_TRAILING_ZEROS_0;
 }
 
 #endif /* _LINUX_BITOPS_COUNT_ZEROS_H_ */