1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* bit search implementation
4 * Copied from lib/find_bit.c to tools/lib/find_bit.c
6 * Copyright (C) 2004 Red Hat, Inc. All Rights Reserved.
9 * Copyright (C) 2008 IBM Corporation
11 * (Inspired by David Howell's find_next_bit implementation)
14 * size and improve performance, 2015.
17 #include <linux/bitops.h>
18 #include <linux/bitmap.h>
19 #include <linux/kernel.h>
21 #if !defined(find_next_bit) || !defined(find_next_zero_bit) || \
22 !defined(find_next_and_bit)
25 * This is a common helper function for find_next_bit, find_next_zero_bit, and
26 * find_next_and_bit. The differences are:
27 * - The "invert" argument, which is XORed with each fetched word before
28 * searching it for one bits.
29 * - The optional "addr2", which is anded with "addr1" if present.
31 static inline unsigned long _find_next_bit(const unsigned long *addr1,
32 const unsigned long *addr2, unsigned long nbits,
33 unsigned long start, unsigned long invert)
37 if (unlikely(start >= nbits))
40 tmp = addr1[start / BITS_PER_LONG];
42 tmp &= addr2[start / BITS_PER_LONG];
45 /* Handle 1st word. */
46 tmp &= BITMAP_FIRST_WORD_MASK(start);
47 start = round_down(start, BITS_PER_LONG);
50 start += BITS_PER_LONG;
54 tmp = addr1[start / BITS_PER_LONG];
56 tmp &= addr2[start / BITS_PER_LONG];
60 return min(start + __ffs(tmp), nbits);
66 * Find the next set bit in a memory region.
68 unsigned long find_next_bit(const unsigned long *addr, unsigned long size,
71 return _find_next_bit(addr, NULL, size, offset, 0UL);
75 #ifndef find_first_bit
77 * Find the first set bit in a memory region.
79 unsigned long find_first_bit(const unsigned long *addr, unsigned long size)
83 for (idx = 0; idx * BITS_PER_LONG < size; idx++) {
85 return min(idx * BITS_PER_LONG + __ffs(addr[idx]), size);
92 #ifndef find_first_zero_bit
94 * Find the first cleared bit in a memory region.
96 unsigned long find_first_zero_bit(const unsigned long *addr, unsigned long size)
100 for (idx = 0; idx * BITS_PER_LONG < size; idx++) {
101 if (addr[idx] != ~0UL)
102 return min(idx * BITS_PER_LONG + ffz(addr[idx]), size);
109 #ifndef find_next_zero_bit
110 unsigned long find_next_zero_bit(const unsigned long *addr, unsigned long size,
111 unsigned long offset)
113 return _find_next_bit(addr, NULL, size, offset, ~0UL);
117 #ifndef find_next_and_bit
118 unsigned long find_next_and_bit(const unsigned long *addr1,
119 const unsigned long *addr2, unsigned long size,
120 unsigned long offset)
122 return _find_next_bit(addr1, addr2, size, offset, 0UL);