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/osdep.h"
15 #include "qemu/bitops.h"
18 * Find the next set bit in a memory region.
20 unsigned long find_next_bit(const unsigned long *addr, unsigned long size,
23 const unsigned long *p = addr + BIT_WORD(offset);
24 unsigned long result = offset & ~(BITS_PER_LONG-1);
31 offset %= BITS_PER_LONG;
34 tmp &= (~0UL << offset);
35 if (size < BITS_PER_LONG) {
41 size -= BITS_PER_LONG;
42 result += BITS_PER_LONG;
44 while (size >= 4*BITS_PER_LONG) {
45 unsigned long d1, d2, d3;
57 result += 4*BITS_PER_LONG;
58 size -= 4*BITS_PER_LONG;
60 while (size >= BITS_PER_LONG) {
64 result += BITS_PER_LONG;
65 size -= BITS_PER_LONG;
73 tmp &= (~0UL >> (BITS_PER_LONG - size));
74 if (tmp == 0UL) { /* Are any bits set? */
75 return result + size; /* Nope. */
78 return result + ctzl(tmp);
82 * This implementation of find_{first,next}_zero_bit was stolen from
83 * Linus' asm-alpha/bitops.h.
85 unsigned long find_next_zero_bit(const unsigned long *addr, unsigned long size,
88 const unsigned long *p = addr + BIT_WORD(offset);
89 unsigned long result = offset & ~(BITS_PER_LONG-1);
96 offset %= BITS_PER_LONG;
99 tmp |= ~0UL >> (BITS_PER_LONG - offset);
100 if (size < BITS_PER_LONG) {
106 size -= BITS_PER_LONG;
107 result += BITS_PER_LONG;
109 while (size & ~(BITS_PER_LONG-1)) {
110 if (~(tmp = *(p++))) {
113 result += BITS_PER_LONG;
114 size -= BITS_PER_LONG;
123 if (tmp == ~0UL) { /* Are any bits zero? */
124 return result + size; /* Nope. */
127 return result + ctzl(~tmp);
130 unsigned long find_last_bit(const unsigned long *addr, unsigned long size)
135 /* Start at final word. */
136 words = size / BITS_PER_LONG;
138 /* Partial final word? */
139 if (size & (BITS_PER_LONG-1)) {
140 tmp = (addr[words] & (~0UL >> (BITS_PER_LONG
141 - (size & (BITS_PER_LONG-1)))));
151 return words * BITS_PER_LONG + BITS_PER_LONG - 1 - clzl(tmp);