2 * Copyright (C) 2004 Red Hat, Inc. All Rights Reserved.
3 * Written by David Howells (dhowells@redhat.com)
4 * Copyright (C) 2008 IBM Corporation
5 * Written by Rusty Russell <rusty@rustcorp.com.au>
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"
17 #define BITOP_WORD(nr) ((nr) / BITS_PER_LONG)
20 * Find the next set bit in a memory region.
22 unsigned long find_next_bit(const unsigned long *addr
, unsigned long size
,
25 const unsigned long *p
= addr
+ BITOP_WORD(offset
);
26 unsigned long result
= offset
& ~(BITS_PER_LONG
-1);
33 offset
%= BITS_PER_LONG
;
36 tmp
&= (~0UL << offset
);
37 if (size
< BITS_PER_LONG
) {
43 size
-= BITS_PER_LONG
;
44 result
+= BITS_PER_LONG
;
46 while (size
>= 4*BITS_PER_LONG
) {
47 unsigned long d1
, d2
, d3
;
59 result
+= 4*BITS_PER_LONG
;
60 size
-= 4*BITS_PER_LONG
;
62 while (size
>= BITS_PER_LONG
) {
66 result
+= BITS_PER_LONG
;
67 size
-= BITS_PER_LONG
;
75 tmp
&= (~0UL >> (BITS_PER_LONG
- size
));
76 if (tmp
== 0UL) { /* Are any bits set? */
77 return result
+ size
; /* Nope. */
80 return result
+ ctzl(tmp
);
84 * This implementation of find_{first,next}_zero_bit was stolen from
85 * Linus' asm-alpha/bitops.h.
87 unsigned long find_next_zero_bit(const unsigned long *addr
, unsigned long size
,
90 const unsigned long *p
= addr
+ BITOP_WORD(offset
);
91 unsigned long result
= offset
& ~(BITS_PER_LONG
-1);
98 offset
%= BITS_PER_LONG
;
101 tmp
|= ~0UL >> (BITS_PER_LONG
- offset
);
102 if (size
< BITS_PER_LONG
) {
108 size
-= BITS_PER_LONG
;
109 result
+= BITS_PER_LONG
;
111 while (size
& ~(BITS_PER_LONG
-1)) {
112 if (~(tmp
= *(p
++))) {
115 result
+= BITS_PER_LONG
;
116 size
-= BITS_PER_LONG
;
125 if (tmp
== ~0UL) { /* Are any bits zero? */
126 return result
+ size
; /* Nope. */
129 return result
+ ctzl(~tmp
);
132 unsigned long find_last_bit(const unsigned long *addr
, unsigned long size
)
137 /* Start at final word. */
138 words
= size
/ BITS_PER_LONG
;
140 /* Partial final word? */
141 if (size
& (BITS_PER_LONG
-1)) {
142 tmp
= (addr
[words
] & (~0UL >> (BITS_PER_LONG
143 - (size
& (BITS_PER_LONG
-1)))));
153 return words
* BITS_PER_LONG
+ BITS_PER_LONG
- 1 - clzl(tmp
);