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.
7 * Written by David Howells (dhowells@redhat.com)
9 * Copyright (C) 2008 IBM Corporation
10 * 'find_last_bit' is written by Rusty Russell <rusty@rustcorp.com.au>
11 * (Inspired by David Howell's find_next_bit implementation)
13 * Rewritten by Yury Norov <yury.norov@gmail.com> to decrease
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 unsigned long _find_next_bit(const unsigned long *addr1,
32 const unsigned long *addr2, unsigned long nbits,
33 unsigned long start, unsigned long invert, unsigned long le)
35 unsigned long tmp, mask;
38 if (unlikely(start >= nbits))
41 tmp = addr1[start / BITS_PER_LONG];
43 tmp &= addr2[start / BITS_PER_LONG];
46 /* Handle 1st word. */
47 mask = BITMAP_FIRST_WORD_MASK(start);
50 * Due to the lack of swab() in tools, and the fact that it doesn't
51 * need little-endian support, just comment it out
60 start = round_down(start, BITS_PER_LONG);
63 start += BITS_PER_LONG;
67 tmp = addr1[start / BITS_PER_LONG];
69 tmp &= addr2[start / BITS_PER_LONG];
78 return min(start + __ffs(tmp), nbits);
82 #ifndef find_first_bit
84 * Find the first set bit in a memory region.
86 unsigned long _find_first_bit(const unsigned long *addr, unsigned long size)
90 for (idx = 0; idx * BITS_PER_LONG < size; idx++) {
92 return min(idx * BITS_PER_LONG + __ffs(addr[idx]), size);
99 #ifndef find_first_and_bit
101 * Find the first set bit in two memory regions.
103 unsigned long _find_first_and_bit(const unsigned long *addr1,
104 const unsigned long *addr2,
107 unsigned long idx, val;
109 for (idx = 0; idx * BITS_PER_LONG < size; idx++) {
110 val = addr1[idx] & addr2[idx];
112 return min(idx * BITS_PER_LONG + __ffs(val), size);
119 #ifndef find_first_zero_bit
121 * Find the first cleared bit in a memory region.
123 unsigned long _find_first_zero_bit(const unsigned long *addr, unsigned long size)
127 for (idx = 0; idx * BITS_PER_LONG < size; idx++) {
128 if (addr[idx] != ~0UL)
129 return min(idx * BITS_PER_LONG + ffz(addr[idx]), size);