xref: /OK3568_Linux_fs/kernel/include/linux/count_zeros.h (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1*4882a593Smuzhiyun /* SPDX-License-Identifier: GPL-2.0-or-later */
2*4882a593Smuzhiyun /* Count leading and trailing zeros functions
3*4882a593Smuzhiyun  *
4*4882a593Smuzhiyun  * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved.
5*4882a593Smuzhiyun  * Written by David Howells (dhowells@redhat.com)
6*4882a593Smuzhiyun  */
7*4882a593Smuzhiyun 
8*4882a593Smuzhiyun #ifndef _LINUX_BITOPS_COUNT_ZEROS_H_
9*4882a593Smuzhiyun #define _LINUX_BITOPS_COUNT_ZEROS_H_
10*4882a593Smuzhiyun 
11*4882a593Smuzhiyun #include <asm/bitops.h>
12*4882a593Smuzhiyun 
13*4882a593Smuzhiyun /**
14*4882a593Smuzhiyun  * count_leading_zeros - Count the number of zeros from the MSB back
15*4882a593Smuzhiyun  * @x: The value
16*4882a593Smuzhiyun  *
17*4882a593Smuzhiyun  * Count the number of leading zeros from the MSB going towards the LSB in @x.
18*4882a593Smuzhiyun  *
19*4882a593Smuzhiyun  * If the MSB of @x is set, the result is 0.
20*4882a593Smuzhiyun  * If only the LSB of @x is set, then the result is BITS_PER_LONG-1.
21*4882a593Smuzhiyun  * If @x is 0 then the result is COUNT_LEADING_ZEROS_0.
22*4882a593Smuzhiyun  */
count_leading_zeros(unsigned long x)23*4882a593Smuzhiyun static inline int count_leading_zeros(unsigned long x)
24*4882a593Smuzhiyun {
25*4882a593Smuzhiyun 	if (sizeof(x) == 4)
26*4882a593Smuzhiyun 		return BITS_PER_LONG - fls(x);
27*4882a593Smuzhiyun 	else
28*4882a593Smuzhiyun 		return BITS_PER_LONG - fls64(x);
29*4882a593Smuzhiyun }
30*4882a593Smuzhiyun 
31*4882a593Smuzhiyun #define COUNT_LEADING_ZEROS_0 BITS_PER_LONG
32*4882a593Smuzhiyun 
33*4882a593Smuzhiyun /**
34*4882a593Smuzhiyun  * count_trailing_zeros - Count the number of zeros from the LSB forwards
35*4882a593Smuzhiyun  * @x: The value
36*4882a593Smuzhiyun  *
37*4882a593Smuzhiyun  * Count the number of trailing zeros from the LSB going towards the MSB in @x.
38*4882a593Smuzhiyun  *
39*4882a593Smuzhiyun  * If the LSB of @x is set, the result is 0.
40*4882a593Smuzhiyun  * If only the MSB of @x is set, then the result is BITS_PER_LONG-1.
41*4882a593Smuzhiyun  * If @x is 0 then the result is COUNT_TRAILING_ZEROS_0.
42*4882a593Smuzhiyun  */
count_trailing_zeros(unsigned long x)43*4882a593Smuzhiyun static inline int count_trailing_zeros(unsigned long x)
44*4882a593Smuzhiyun {
45*4882a593Smuzhiyun #define COUNT_TRAILING_ZEROS_0 (-1)
46*4882a593Smuzhiyun 
47*4882a593Smuzhiyun 	if (sizeof(x) == 4)
48*4882a593Smuzhiyun 		return ffs(x);
49*4882a593Smuzhiyun 	else
50*4882a593Smuzhiyun 		return (x != 0) ? __ffs(x) : COUNT_TRAILING_ZEROS_0;
51*4882a593Smuzhiyun }
52*4882a593Smuzhiyun 
53*4882a593Smuzhiyun #endif /* _LINUX_BITOPS_COUNT_ZEROS_H_ */
54