2 * Copyright (C) 2004 Red Hat, Inc. All Rights Reserved.
4 * Copyright (C) 2008 IBM Corporation
6 * (Inspired by David Howell's find_next_bit implementation)
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version
11 * 2 of the License, or (at your option) any later version.
14 #include "qemu/bitops.h"
16 #define BITOP_WORD(nr) ((nr) / BITS_PER_LONG)
19 * Find the next set bit in a memory region.
21 unsigned long find_next_bit(const unsigned long *addr, unsigned long size,
24 const unsigned long *p = addr + BITOP_WORD(offset);
25 unsigned long result = offset & ~(BITS_PER_LONG-1);
32 offset %= BITS_PER_LONG;
35 tmp &= (~0UL << offset);
36 if (size < BITS_PER_LONG) {
42 size -= BITS_PER_LONG;
43 result += BITS_PER_LONG;
45 while (size >= 4*BITS_PER_LONG) {
46 unsigned long d1, d2, d3;
58 result += 4*BITS_PER_LONG;
59 size -= 4*BITS_PER_LONG;
61 while (size >= BITS_PER_LONG) {
65 result += BITS_PER_LONG;
66 size -= BITS_PER_LONG;
74 tmp &= (~0UL >> (BITS_PER_LONG - size));
75 if (tmp == 0UL) { /* Are any bits set? */
76 return result + size; /* Nope. */
79 return result + ctzl(tmp);
83 * This implementation of find_{first,next}_zero_bit was stolen from
84 * Linus' asm-alpha/bitops.h.
86 unsigned long find_next_zero_bit(const unsigned long *addr, unsigned long size,
89 const unsigned long *p = addr + BITOP_WORD(offset);
90 unsigned long result = offset & ~(BITS_PER_LONG-1);
97 offset %= BITS_PER_LONG;
100 tmp |= ~0UL >> (BITS_PER_LONG - offset);
101 if (size < BITS_PER_LONG) {
107 size -= BITS_PER_LONG;
108 result += BITS_PER_LONG;
110 while (size & ~(BITS_PER_LONG-1)) {
111 if (~(tmp = *(p++))) {
114 result += BITS_PER_LONG;
115 size -= BITS_PER_LONG;
124 if (tmp == ~0UL) { /* Are any bits zero? */
125 return result + size; /* Nope. */
128 return result + ctzl(~tmp);
131 unsigned long find_last_bit(const unsigned long *addr, unsigned long size)
136 /* Start at final word. */
137 words = size / BITS_PER_LONG;
139 /* Partial final word? */
140 if (size & (BITS_PER_LONG-1)) {
141 tmp = (addr[words] & (~0UL >> (BITS_PER_LONG
142 - (size & (BITS_PER_LONG-1)))));
152 return words * BITS_PER_LONG + BITS_PER_LONG - 1 - clzl(tmp);