xref: /linux/include/linux/bitmap.h (revision cb95904b470d2d347012d5e360303cf478ca5362)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef __LINUX_BITMAP_H
3 #define __LINUX_BITMAP_H
4 
5 #ifndef __ASSEMBLER__
6 
7 #include <linux/align.h>
8 #include <linux/bitops.h>
9 #include <linux/cleanup.h>
10 #include <linux/errno.h>
11 #include <linux/find.h>
12 #include <linux/limits.h>
13 #include <linux/string.h>
14 #include <linux/types.h>
15 #include <linux/bitmap-str.h>
16 
17 struct device;
18 
19 /*
20  * bitmaps provide bit arrays that consume one or more unsigned
21  * longs.  The bitmap interface and available operations are listed
22  * here, in bitmap.h
23  *
24  * Function implementations generic to all architectures are in
25  * lib/bitmap.c.  Functions implementations that are architecture
26  * specific are in various arch/<arch>/include/asm/bitops.h headers
27  * and other arch/<arch> specific files.
28  *
29  * See lib/bitmap.c for more details.
30  */
31 
32 /**
33  * DOC: bitmap overview
34  *
35  * The available bitmap operations and their rough meaning in the
36  * case that the bitmap is a single unsigned long are thus:
37  *
38  * The generated code is more efficient when nbits is known at
39  * compile-time and at most BITS_PER_LONG.
40  *
41  * ::
42  *
43  *  bitmap_zero(dst, nbits)                     *dst = 0UL
44  *  bitmap_fill(dst, nbits)                     *dst = ~0UL
45  *  bitmap_copy(dst, src, nbits)                *dst = *src
46  *  bitmap_and(dst, src1, src2, nbits)          *dst = *src1 & *src2
47  *  bitmap_or(dst, src1, src2, nbits)           *dst = *src1 | *src2
48  *  bitmap_weighted_or(dst, src1, src2, nbits)	*dst = *src1 | *src2. Returns Hamming Weight of dst
49  *  bitmap_weighted_xor(dst, src1, src2, nbits)	*dst = *src1 ^ *src2. Returns Hamming Weight of dst
50  *  bitmap_xor(dst, src1, src2, nbits)          *dst = *src1 ^ *src2
51  *  bitmap_andnot(dst, src1, src2, nbits)       *dst = *src1 & ~(*src2)
52  *  bitmap_complement(dst, src, nbits)          *dst = ~(*src)
53  *  bitmap_equal(src1, src2, nbits)             Are *src1 and *src2 equal?
54  *  bitmap_intersects(src1, src2, nbits)        Do *src1 and *src2 overlap?
55  *  bitmap_intersects_and(src1, src2, src3, nbits) Do *src1, *src2 and *src3 overlap?
56  *  bitmap_subset(src1, src2, nbits)            Is *src1 a subset of *src2?
57  *  bitmap_empty(src, nbits)                    Are all bits zero in *src?
58  *  bitmap_full(src, nbits)                     Are all bits set in *src?
59  *  bitmap_weight(src, nbits)                   Hamming Weight: number set bits
60  *  bitmap_weight_and(src1, src2, nbits)        Hamming Weight of and'ed bitmap
61  *  bitmap_weight_andnot(src1, src2, nbits)     Hamming Weight of andnot'ed bitmap
62  *  bitmap_weight_from(src, start, end)         Hamming Weight starting from @start
63  *  bitmap_set(dst, pos, nbits)                 Set specified bit area
64  *  bitmap_clear(dst, pos, nbits)               Clear specified bit area
65  *  bitmap_find_next_zero_area(buf, len, pos, n, mask)  Find bit free area
66  *  bitmap_find_next_zero_area_off(buf, len, pos, n, mask, mask_off)  as above
67  *  bitmap_shift_right(dst, src, n, nbits)      *dst = *src >> n
68  *  bitmap_shift_left(dst, src, n, nbits)       *dst = *src << n
69  *  bitmap_cut(dst, src, first, n, nbits)       Cut n bits from first, copy rest
70  *  bitmap_replace(dst, old, new, mask, nbits)  *dst = (*old & ~(*mask)) | (*new & *mask)
71  *  bitmap_scatter(dst, src, mask, nbits)	*dst = map(dense, sparse)(src)
72  *  bitmap_gather(dst, src, mask, nbits)	*dst = map(sparse, dense)(src)
73  *  bitmap_remap(dst, src, old, new, nbits)     *dst = map(old, new)(src)
74  *  bitmap_bitremap(oldbit, old, new, nbits)    newbit = map(old, new)(oldbit)
75  *  bitmap_onto(dst, orig, relmap, nbits)       *dst = orig relative to relmap
76  *  bitmap_fold(dst, orig, sz, nbits)           dst bits = orig bits mod sz
77  *  bitmap_parse(buf, buflen, dst, nbits)       Parse bitmap dst from kernel buf
78  *  bitmap_parse_user(ubuf, ulen, dst, nbits)   Parse bitmap dst from user buf
79  *  bitmap_parselist(buf, dst, nbits)           Parse bitmap dst from kernel buf
80  *  bitmap_parselist_user(buf, dst, nbits)      Parse bitmap dst from user buf
81  *  bitmap_find_free_region(bitmap, bits, order)  Find and allocate bit region
82  *  bitmap_release_region(bitmap, pos, order)   Free specified bit region
83  *  bitmap_allocate_region(bitmap, pos, order)  Allocate specified bit region
84  *  bitmap_from_arr32(dst, buf, nbits)          Copy nbits from u32[] buf to dst
85  *  bitmap_from_arr64(dst, buf, nbits)          Copy nbits from u64[] buf to dst
86  *  bitmap_to_arr32(buf, src, nbits)            Copy nbits from buf to u32[] dst
87  *  bitmap_to_arr64(buf, src, nbits)            Copy nbits from buf to u64[] dst
88  *  bitmap_get_value8(map, start)               Get 8bit value from map at start
89  *  bitmap_set_value8(map, value, start)        Set 8bit value to map at start
90  *  bitmap_read(map, start, nbits)              Read an nbits-sized value from
91  *                                              map at start
92  *  bitmap_write(map, value, start, nbits)      Write an nbits-sized value to
93  *                                              map at start
94  *
95  * Note, bitmap_zero() and bitmap_fill() operate over the region of
96  * unsigned longs, that is, bits behind bitmap till the unsigned long
97  * boundary will be zeroed or filled as well. Consider to use
98  * bitmap_clear() or bitmap_set() to make explicit zeroing or filling
99  * respectively.
100  */
101 
102 /**
103  * DOC: bitmap bitops
104  *
105  * Also the following operations in asm/bitops.h apply to bitmaps.::
106  *
107  *  set_bit(bit, addr)                  *addr |= bit
108  *  clear_bit(bit, addr)                *addr &= ~bit
109  *  change_bit(bit, addr)               *addr ^= bit
110  *  test_bit(bit, addr)                 Is bit set in *addr?
111  *  test_and_set_bit(bit, addr)         Set bit and return old value
112  *  test_and_clear_bit(bit, addr)       Clear bit and return old value
113  *  test_and_change_bit(bit, addr)      Change bit and return old value
114  *  find_first_zero_bit(addr, nbits)    Position first zero bit in *addr
115  *  find_first_bit(addr, nbits)         Position first set bit in *addr
116  *  find_next_zero_bit(addr, nbits, bit)
117  *                                      Position next zero bit in *addr >= bit
118  *  find_next_bit(addr, nbits, bit)     Position next set bit in *addr >= bit
119  *  find_next_and_bit(addr1, addr2, nbits, bit)
120  *                                      Same as find_next_bit, but in
121  *                                      (*addr1 & *addr2)
122  *
123  */
124 
125 /**
126  * DOC: declare bitmap
127  * The DECLARE_BITMAP(name,bits) macro, in linux/types.h, can be used
128  * to declare an array named 'name' of just enough unsigned longs to
129  * contain all bit positions from 0 to 'bits' - 1.
130  */
131 
132 /*
133  * Allocation and deallocation of bitmap.
134  * Provided in lib/bitmap.c to avoid circular dependency.
135  */
136 unsigned long *bitmap_alloc(unsigned int nbits, gfp_t flags);
137 unsigned long *bitmap_zalloc(unsigned int nbits, gfp_t flags);
138 unsigned long *bitmap_alloc_node(unsigned int nbits, gfp_t flags, int node);
139 unsigned long *bitmap_zalloc_node(unsigned int nbits, gfp_t flags, int node);
140 void bitmap_free(const unsigned long *bitmap);
141 
142 DEFINE_FREE(bitmap, unsigned long *, if (_T) bitmap_free(_T))
143 
144 /* Managed variants of the above. */
145 unsigned long *devm_bitmap_alloc(struct device *dev,
146 				 unsigned int nbits, gfp_t flags);
147 unsigned long *devm_bitmap_zalloc(struct device *dev,
148 				  unsigned int nbits, gfp_t flags);
149 
150 /*
151  * lib/bitmap.c provides these functions:
152  */
153 
154 bool __bitmap_equal(const unsigned long *bitmap1,
155 		    const unsigned long *bitmap2, unsigned int nbits);
156 bool __pure __bitmap_or_equal(const unsigned long *src1,
157 			      const unsigned long *src2,
158 			      const unsigned long *src3,
159 			      unsigned int nbits);
160 void __bitmap_complement(unsigned long *dst, const unsigned long *src,
161 			 unsigned int nbits);
162 void __bitmap_shift_right(unsigned long *dst, const unsigned long *src,
163 			  unsigned int shift, unsigned int nbits);
164 void __bitmap_shift_left(unsigned long *dst, const unsigned long *src,
165 			 unsigned int shift, unsigned int nbits);
166 void bitmap_cut(unsigned long *dst, const unsigned long *src,
167 		unsigned int first, unsigned int cut, unsigned int nbits);
168 bool __bitmap_and(unsigned long *dst, const unsigned long *bitmap1,
169 		 const unsigned long *bitmap2, unsigned int nbits);
170 void __bitmap_or(unsigned long *dst, const unsigned long *bitmap1,
171 		 const unsigned long *bitmap2, unsigned int nbits);
172 unsigned int __bitmap_weighted_or(unsigned long *dst, const unsigned long *bitmap1,
173 				  const unsigned long *bitmap2, unsigned int nbits);
174 unsigned int __bitmap_weighted_xor(unsigned long *dst, const unsigned long *bitmap1,
175 				  const unsigned long *bitmap2, unsigned int nbits);
176 void __bitmap_xor(unsigned long *dst, const unsigned long *bitmap1,
177 		  const unsigned long *bitmap2, unsigned int nbits);
178 bool __bitmap_andnot(unsigned long *dst, const unsigned long *bitmap1,
179 		    const unsigned long *bitmap2, unsigned int nbits);
180 void __bitmap_replace(unsigned long *dst,
181 		      const unsigned long *old, const unsigned long *new,
182 		      const unsigned long *mask, unsigned int nbits);
183 bool __bitmap_intersects(const unsigned long *bitmap1,
184 			 const unsigned long *bitmap2, unsigned int nbits);
185 bool __bitmap_intersects_and(const unsigned long *bitmap1,
186 			     const unsigned long *bitmap2,
187 			     const unsigned long *bitmap3, unsigned int nbits);
188 bool __bitmap_subset(const unsigned long *bitmap1,
189 		     const unsigned long *bitmap2, unsigned int nbits);
190 unsigned int __bitmap_weight(const unsigned long *bitmap, unsigned int nbits);
191 unsigned int __bitmap_weight_and(const unsigned long *bitmap1,
192 				 const unsigned long *bitmap2, unsigned int nbits);
193 unsigned int __bitmap_weight_andnot(const unsigned long *bitmap1,
194 				    const unsigned long *bitmap2, unsigned int nbits);
195 void __bitmap_set(unsigned long *map, unsigned int start, int len);
196 void __bitmap_clear(unsigned long *map, unsigned int start, int len);
197 
198 unsigned long bitmap_find_next_zero_area_off(unsigned long *map,
199 					     unsigned long size,
200 					     unsigned long start,
201 					     unsigned int nr,
202 					     unsigned long align_mask,
203 					     unsigned long align_offset);
204 
205 /**
206  * bitmap_find_next_zero_area - find a contiguous aligned zero area
207  * @map: The address to base the search on
208  * @size: The bitmap size in bits
209  * @start: The bitnumber to start searching at
210  * @nr: The number of zeroed bits we're looking for
211  * @align_mask: Alignment mask for zero area
212  *
213  * The @align_mask should be one less than a power of 2; the effect is that
214  * the bit offset of all zero areas this function finds is multiples of that
215  * power of 2. A @align_mask of 0 means no alignment is required.
216  *
217  * Return: The bit offset of the found area or a value >= @size
218  * if no area is found.
219  */
220 static __always_inline
bitmap_find_next_zero_area(unsigned long * map,unsigned long size,unsigned long start,unsigned int nr,unsigned long align_mask)221 unsigned long bitmap_find_next_zero_area(unsigned long *map,
222 					 unsigned long size,
223 					 unsigned long start,
224 					 unsigned int nr,
225 					 unsigned long align_mask)
226 {
227 	return bitmap_find_next_zero_area_off(map, size, start, nr,
228 					      align_mask, 0);
229 }
230 
231 void bitmap_remap(unsigned long *dst, const unsigned long *src,
232 		const unsigned long *old, const unsigned long *new, unsigned int nbits);
233 int bitmap_bitremap(int oldbit,
234 		const unsigned long *old, const unsigned long *new, int bits);
235 void bitmap_onto(unsigned long *dst, const unsigned long *orig,
236 		const unsigned long *relmap, unsigned int bits);
237 void bitmap_fold(unsigned long *dst, const unsigned long *orig,
238 		unsigned int sz, unsigned int nbits);
239 
240 #define BITMAP_FIRST_WORD_MASK(start) (~0UL << ((start) & (BITS_PER_LONG - 1)))
241 #define BITMAP_LAST_WORD_MASK(nbits) (~0UL >> (-(nbits) & (BITS_PER_LONG - 1)))
242 
243 #define bitmap_size(nbits)	(ALIGN(nbits, BITS_PER_LONG) / BITS_PER_BYTE)
244 
bitmap_zero(unsigned long * dst,unsigned int nbits)245 static __always_inline void bitmap_zero(unsigned long *dst, unsigned int nbits)
246 {
247 	unsigned int len = bitmap_size(nbits);
248 
249 	if (small_const_nbits(nbits))
250 		*dst = 0;
251 	else
252 		memset(dst, 0, len);
253 }
254 
bitmap_fill(unsigned long * dst,unsigned int nbits)255 static __always_inline void bitmap_fill(unsigned long *dst, unsigned int nbits)
256 {
257 	unsigned int len = bitmap_size(nbits);
258 
259 	if (small_const_nbits(nbits))
260 		*dst = ~0UL;
261 	else
262 		memset(dst, 0xff, len);
263 }
264 
265 static __always_inline
bitmap_copy(unsigned long * dst,const unsigned long * src,unsigned int nbits)266 void bitmap_copy(unsigned long *dst, const unsigned long *src, unsigned int nbits)
267 {
268 	unsigned int len = bitmap_size(nbits);
269 
270 	if (small_const_nbits(nbits))
271 		*dst = *src;
272 	else
273 		memcpy(dst, src, len);
274 }
275 
276 /*
277  * Copy bitmap and clear tail bits in last word.
278  */
279 static __always_inline
bitmap_copy_clear_tail(unsigned long * dst,const unsigned long * src,unsigned int nbits)280 void bitmap_copy_clear_tail(unsigned long *dst, const unsigned long *src, unsigned int nbits)
281 {
282 	bitmap_copy(dst, src, nbits);
283 	if (nbits % BITS_PER_LONG)
284 		dst[nbits / BITS_PER_LONG] &= BITMAP_LAST_WORD_MASK(nbits);
285 }
286 
bitmap_copy_and_extend(unsigned long * to,const unsigned long * from,unsigned int count,unsigned int size)287 static inline void bitmap_copy_and_extend(unsigned long *to,
288 					  const unsigned long *from,
289 					  unsigned int count, unsigned int size)
290 {
291 	unsigned int copy = BITS_TO_LONGS(count);
292 
293 	memcpy(to, from, copy * sizeof(long));
294 	if (count % BITS_PER_LONG)
295 		to[copy - 1] &= BITMAP_LAST_WORD_MASK(count);
296 	memset(to + copy, 0, bitmap_size(size) - copy * sizeof(long));
297 }
298 
299 /*
300  * On 32-bit systems bitmaps are represented as u32 arrays internally. On LE64
301  * machines the order of hi and lo parts of numbers match the bitmap structure.
302  * In both cases conversion is not needed when copying data from/to arrays of
303  * u32. But in LE64 case, typecast in bitmap_copy_clear_tail() may lead
304  * to out-of-bound access. To avoid that, both LE and BE variants of 64-bit
305  * architectures are not using bitmap_copy_clear_tail().
306  */
307 #if BITS_PER_LONG == 64
308 void bitmap_from_arr32(unsigned long *bitmap, const u32 *buf,
309 							unsigned int nbits);
310 void bitmap_to_arr32(u32 *buf, const unsigned long *bitmap,
311 							unsigned int nbits);
312 #else
313 #define bitmap_from_arr32(bitmap, buf, nbits)			\
314 	bitmap_copy_clear_tail((unsigned long *) (bitmap),	\
315 			(const unsigned long *) (buf), (nbits))
316 #define bitmap_to_arr32(buf, bitmap, nbits)			\
317 	bitmap_copy_clear_tail((unsigned long *) (buf),		\
318 			(const unsigned long *) (bitmap), (nbits))
319 #endif
320 
321 /*
322  * On 64-bit systems bitmaps are represented as u64 arrays internally. So,
323  * the conversion is not needed when copying data from/to arrays of u64.
324  */
325 #if BITS_PER_LONG == 32
326 void bitmap_from_arr64(unsigned long *bitmap, const u64 *buf, unsigned int nbits);
327 void bitmap_to_arr64(u64 *buf, const unsigned long *bitmap, unsigned int nbits);
328 #else
329 #define bitmap_from_arr64(bitmap, buf, nbits)			\
330 	bitmap_copy_clear_tail((unsigned long *)(bitmap), (const unsigned long *)(buf), (nbits))
331 #define bitmap_to_arr64(buf, bitmap, nbits)			\
332 	bitmap_copy_clear_tail((unsigned long *)(buf), (const unsigned long *)(bitmap), (nbits))
333 #endif
334 
335 static __always_inline
bitmap_and(unsigned long * dst,const unsigned long * src1,const unsigned long * src2,unsigned int nbits)336 bool bitmap_and(unsigned long *dst, const unsigned long *src1,
337 		const unsigned long *src2, unsigned int nbits)
338 {
339 	if (small_const_nbits(nbits))
340 		return (*dst = *src1 & *src2 & BITMAP_LAST_WORD_MASK(nbits)) != 0;
341 	return __bitmap_and(dst, src1, src2, nbits);
342 }
343 
344 static __always_inline
bitmap_or(unsigned long * dst,const unsigned long * src1,const unsigned long * src2,unsigned int nbits)345 void bitmap_or(unsigned long *dst, const unsigned long *src1,
346 	       const unsigned long *src2, unsigned int nbits)
347 {
348 	if (small_const_nbits(nbits))
349 		*dst = *src1 | *src2;
350 	else
351 		__bitmap_or(dst, src1, src2, nbits);
352 }
353 
354 static __always_inline
bitmap_weighted_or(unsigned long * dst,const unsigned long * src1,const unsigned long * src2,unsigned int nbits)355 unsigned int bitmap_weighted_or(unsigned long *dst, const unsigned long *src1,
356 				const unsigned long *src2, unsigned int nbits)
357 {
358 	if (small_const_nbits(nbits)) {
359 		*dst = *src1 | *src2;
360 		return hweight_long(*dst & BITMAP_LAST_WORD_MASK(nbits));
361 	} else {
362 		return __bitmap_weighted_or(dst, src1, src2, nbits);
363 	}
364 }
365 
366 static __always_inline
bitmap_weighted_xor(unsigned long * dst,const unsigned long * src1,const unsigned long * src2,unsigned int nbits)367 unsigned int bitmap_weighted_xor(unsigned long *dst, const unsigned long *src1,
368 				const unsigned long *src2, unsigned int nbits)
369 {
370 	if (small_const_nbits(nbits)) {
371 		*dst = *src1 ^ *src2;
372 		return hweight_long(*dst & BITMAP_LAST_WORD_MASK(nbits));
373 	} else {
374 		return __bitmap_weighted_xor(dst, src1, src2, nbits);
375 	}
376 }
377 
378 static __always_inline
bitmap_xor(unsigned long * dst,const unsigned long * src1,const unsigned long * src2,unsigned int nbits)379 void bitmap_xor(unsigned long *dst, const unsigned long *src1,
380 		const unsigned long *src2, unsigned int nbits)
381 {
382 	if (small_const_nbits(nbits))
383 		*dst = *src1 ^ *src2;
384 	else
385 		__bitmap_xor(dst, src1, src2, nbits);
386 }
387 
388 static __always_inline
bitmap_andnot(unsigned long * dst,const unsigned long * src1,const unsigned long * src2,unsigned int nbits)389 bool bitmap_andnot(unsigned long *dst, const unsigned long *src1,
390 		   const unsigned long *src2, unsigned int nbits)
391 {
392 	if (small_const_nbits(nbits))
393 		return (*dst = *src1 & ~(*src2) & BITMAP_LAST_WORD_MASK(nbits)) != 0;
394 	return __bitmap_andnot(dst, src1, src2, nbits);
395 }
396 
397 static __always_inline
bitmap_complement(unsigned long * dst,const unsigned long * src,unsigned int nbits)398 void bitmap_complement(unsigned long *dst, const unsigned long *src, unsigned int nbits)
399 {
400 	if (small_const_nbits(nbits))
401 		*dst = ~(*src);
402 	else
403 		__bitmap_complement(dst, src, nbits);
404 }
405 
406 #ifdef __LITTLE_ENDIAN
407 #define BITMAP_MEM_ALIGNMENT 8
408 #else
409 #define BITMAP_MEM_ALIGNMENT (8 * sizeof(unsigned long))
410 #endif
411 #define BITMAP_MEM_MASK (BITMAP_MEM_ALIGNMENT - 1)
412 
413 static __always_inline
bitmap_equal(const unsigned long * src1,const unsigned long * src2,unsigned int nbits)414 bool bitmap_equal(const unsigned long *src1, const unsigned long *src2, unsigned int nbits)
415 {
416 	if (small_const_nbits(nbits))
417 		return !((*src1 ^ *src2) & BITMAP_LAST_WORD_MASK(nbits));
418 	if (__builtin_constant_p(nbits & BITMAP_MEM_MASK) &&
419 	    IS_ALIGNED(nbits, BITMAP_MEM_ALIGNMENT))
420 		return !memcmp(src1, src2, nbits / 8);
421 	return __bitmap_equal(src1, src2, nbits);
422 }
423 
424 /**
425  * bitmap_or_equal - Check whether the or of two bitmaps is equal to a third
426  * @src1:	Pointer to bitmap 1
427  * @src2:	Pointer to bitmap 2 will be or'ed with bitmap 1
428  * @src3:	Pointer to bitmap 3. Compare to the result of *@src1 | *@src2
429  * @nbits:	number of bits in each of these bitmaps
430  *
431  * Returns: True if (*@src1 | *@src2) == *@src3, false otherwise
432  */
433 static __always_inline
bitmap_or_equal(const unsigned long * src1,const unsigned long * src2,const unsigned long * src3,unsigned int nbits)434 bool bitmap_or_equal(const unsigned long *src1, const unsigned long *src2,
435 		     const unsigned long *src3, unsigned int nbits)
436 {
437 	if (!small_const_nbits(nbits))
438 		return __bitmap_or_equal(src1, src2, src3, nbits);
439 
440 	return !(((*src1 | *src2) ^ *src3) & BITMAP_LAST_WORD_MASK(nbits));
441 }
442 
443 static __always_inline
bitmap_intersects(const unsigned long * src1,const unsigned long * src2,unsigned int nbits)444 bool bitmap_intersects(const unsigned long *src1, const unsigned long *src2, unsigned int nbits)
445 {
446 	if (small_const_nbits(nbits))
447 		return ((*src1 & *src2) & BITMAP_LAST_WORD_MASK(nbits)) != 0;
448 	else
449 		return __bitmap_intersects(src1, src2, nbits);
450 }
451 
452 static __always_inline
bitmap_intersects_and(const unsigned long * src1,const unsigned long * src2,const unsigned long * src3,unsigned int nbits)453 bool bitmap_intersects_and(const unsigned long *src1, const unsigned long *src2,
454 			   const unsigned long *src3, unsigned int nbits)
455 {
456 	if (small_const_nbits(nbits))
457 		return ((*src1 & *src2 & *src3) & BITMAP_LAST_WORD_MASK(nbits)) != 0;
458 	else
459 		return __bitmap_intersects_and(src1, src2, src3, nbits);
460 }
461 
462 static __always_inline
bitmap_subset(const unsigned long * src1,const unsigned long * src2,unsigned int nbits)463 bool bitmap_subset(const unsigned long *src1, const unsigned long *src2, unsigned int nbits)
464 {
465 	if (small_const_nbits(nbits))
466 		return ! ((*src1 & ~(*src2)) & BITMAP_LAST_WORD_MASK(nbits));
467 	else
468 		return __bitmap_subset(src1, src2, nbits);
469 }
470 
471 static __always_inline
bitmap_empty(const unsigned long * src,unsigned nbits)472 bool bitmap_empty(const unsigned long *src, unsigned nbits)
473 {
474 	if (small_const_nbits(nbits))
475 		return ! (*src & BITMAP_LAST_WORD_MASK(nbits));
476 
477 	return find_first_bit(src, nbits) == nbits;
478 }
479 
480 static __always_inline
bitmap_full(const unsigned long * src,unsigned int nbits)481 bool bitmap_full(const unsigned long *src, unsigned int nbits)
482 {
483 	if (small_const_nbits(nbits))
484 		return ! (~(*src) & BITMAP_LAST_WORD_MASK(nbits));
485 
486 	return find_first_zero_bit(src, nbits) == nbits;
487 }
488 
489 static __always_inline
bitmap_weight(const unsigned long * src,unsigned int nbits)490 unsigned int bitmap_weight(const unsigned long *src, unsigned int nbits)
491 {
492 	if (small_const_nbits(nbits))
493 		return hweight_long(*src & BITMAP_LAST_WORD_MASK(nbits));
494 	return __bitmap_weight(src, nbits);
495 }
496 
497 static __always_inline
bitmap_weight_and(const unsigned long * src1,const unsigned long * src2,unsigned int nbits)498 unsigned long bitmap_weight_and(const unsigned long *src1,
499 				const unsigned long *src2, unsigned int nbits)
500 {
501 	if (small_const_nbits(nbits))
502 		return hweight_long(*src1 & *src2 & BITMAP_LAST_WORD_MASK(nbits));
503 	return __bitmap_weight_and(src1, src2, nbits);
504 }
505 
506 static __always_inline
bitmap_weight_andnot(const unsigned long * src1,const unsigned long * src2,unsigned int nbits)507 unsigned long bitmap_weight_andnot(const unsigned long *src1,
508 				   const unsigned long *src2, unsigned int nbits)
509 {
510 	if (small_const_nbits(nbits))
511 		return hweight_long(*src1 & ~(*src2) & BITMAP_LAST_WORD_MASK(nbits));
512 	return __bitmap_weight_andnot(src1, src2, nbits);
513 }
514 
515 /**
516  * bitmap_weight_from - Hamming weight for a memory region
517  * @bitmap: The base address
518  * @start: The bitnumber to starts weighting
519  * @end: the bitmap size in bits
520  *
521  * Returns the number of set bits in the region. If @start >= @end,
522  * return >= end.
523  */
524 static __always_inline
bitmap_weight_from(const unsigned long * bitmap,unsigned int start,unsigned int end)525 unsigned long bitmap_weight_from(const unsigned long *bitmap,
526 				   unsigned int start, unsigned int end)
527 {
528 	unsigned long w;
529 
530 	if (unlikely(start >= end))
531 		return end;
532 
533 	if (small_const_nbits(end))
534 		return hweight_long(*bitmap & GENMASK(end - 1, start));
535 
536 	bitmap += start / BITS_PER_LONG;
537 	/* Opencode round_down() to not include math.h */
538 	end -= start & ~(BITS_PER_LONG - 1);
539 	start %= BITS_PER_LONG;
540 	w = bitmap_weight(bitmap, end);
541 	if (start)
542 		w -= hweight_long(*bitmap & BITMAP_LAST_WORD_MASK(start));
543 
544 	return w;
545 }
546 
547 static __always_inline
bitmap_set(unsigned long * map,unsigned int start,unsigned int nbits)548 void bitmap_set(unsigned long *map, unsigned int start, unsigned int nbits)
549 {
550 	if (__builtin_constant_p(nbits) && nbits == 1)
551 		__set_bit(start, map);
552 	else if (small_const_nbits(start + nbits))
553 		*map |= GENMASK(start + nbits - 1, start);
554 	else if (__builtin_constant_p(start & BITMAP_MEM_MASK) &&
555 		 IS_ALIGNED(start, BITMAP_MEM_ALIGNMENT) &&
556 		 __builtin_constant_p(nbits & BITMAP_MEM_MASK) &&
557 		 IS_ALIGNED(nbits, BITMAP_MEM_ALIGNMENT))
558 		memset((char *)map + start / 8, 0xff, nbits / 8);
559 	else
560 		__bitmap_set(map, start, nbits);
561 }
562 
563 static __always_inline
bitmap_clear(unsigned long * map,unsigned int start,unsigned int nbits)564 void bitmap_clear(unsigned long *map, unsigned int start, unsigned int nbits)
565 {
566 	if (__builtin_constant_p(nbits) && nbits == 1)
567 		__clear_bit(start, map);
568 	else if (small_const_nbits(start + nbits))
569 		*map &= ~GENMASK(start + nbits - 1, start);
570 	else if (__builtin_constant_p(start & BITMAP_MEM_MASK) &&
571 		 IS_ALIGNED(start, BITMAP_MEM_ALIGNMENT) &&
572 		 __builtin_constant_p(nbits & BITMAP_MEM_MASK) &&
573 		 IS_ALIGNED(nbits, BITMAP_MEM_ALIGNMENT))
574 		memset((char *)map + start / 8, 0, nbits / 8);
575 	else
576 		__bitmap_clear(map, start, nbits);
577 }
578 
579 static __always_inline
bitmap_shift_right(unsigned long * dst,const unsigned long * src,unsigned int shift,unsigned int nbits)580 void bitmap_shift_right(unsigned long *dst, const unsigned long *src,
581 			unsigned int shift, unsigned int nbits)
582 {
583 	if (small_const_nbits(nbits))
584 		*dst = (*src & BITMAP_LAST_WORD_MASK(nbits)) >> shift;
585 	else
586 		__bitmap_shift_right(dst, src, shift, nbits);
587 }
588 
589 static __always_inline
bitmap_shift_left(unsigned long * dst,const unsigned long * src,unsigned int shift,unsigned int nbits)590 void bitmap_shift_left(unsigned long *dst, const unsigned long *src,
591 		       unsigned int shift, unsigned int nbits)
592 {
593 	if (small_const_nbits(nbits))
594 		*dst = (*src << shift) & BITMAP_LAST_WORD_MASK(nbits);
595 	else
596 		__bitmap_shift_left(dst, src, shift, nbits);
597 }
598 
599 static __always_inline
bitmap_replace(unsigned long * dst,const unsigned long * old,const unsigned long * new,const unsigned long * mask,unsigned int nbits)600 void bitmap_replace(unsigned long *dst,
601 		    const unsigned long *old,
602 		    const unsigned long *new,
603 		    const unsigned long *mask,
604 		    unsigned int nbits)
605 {
606 	if (small_const_nbits(nbits))
607 		*dst = (*old & ~(*mask)) | (*new & *mask);
608 	else
609 		__bitmap_replace(dst, old, new, mask, nbits);
610 }
611 
612 /**
613  * bitmap_scatter - Scatter a bitmap according to the given mask
614  * @dst: scattered bitmap
615  * @src: gathered bitmap
616  * @mask: mask representing bits to assign to in the scattered bitmap
617  * @nbits: number of bits in each of these bitmaps
618  *
619  * Scatters bitmap with sequential bits according to the given @mask.
620  *
621  * Example:
622  * If @src bitmap = 0x005a, with @mask = 0x1313, @dst will be 0x0302.
623  *
624  * Or in binary form
625  * @src			@mask			@dst
626  * 0000000001011010	0001001100010011	0000001100000010
627  *
628  * (Bits 0, 1, 2, 3, 4, 5 are copied to the bits 0, 1, 4, 8, 9, 12)
629  *
630  * A more 'visual' description of the operation::
631  *
632  *	src:  0000000001011010
633  *	                ||||||
634  *	         +------+|||||
635  *	         |  +----+||||
636  *	         |  |+----+|||
637  *	         |  ||   +-+||
638  *	         |  ||   |  ||
639  *	mask: ...v..vv...v..vv
640  *	      ...0..11...0..10
641  *	dst:  0000001100000010
642  *
643  * A relationship exists between bitmap_scatter() and bitmap_gather(). See
644  * bitmap_gather() for the bitmap gather detailed operations. TL;DR:
645  * bitmap_gather() can be seen as the 'reverse' bitmap_scatter() operation.
646  */
647 static __always_inline
bitmap_scatter(unsigned long * dst,const unsigned long * src,const unsigned long * mask,unsigned int nbits)648 void bitmap_scatter(unsigned long *dst, const unsigned long *src,
649 		    const unsigned long *mask, unsigned int nbits)
650 {
651 	unsigned int n = 0;
652 	unsigned int bit;
653 
654 	bitmap_zero(dst, nbits);
655 
656 	for_each_set_bit(bit, mask, nbits)
657 		__assign_bit(bit, dst, test_bit(n++, src));
658 }
659 
660 /**
661  * bitmap_gather - Gather a bitmap according to given mask
662  * @dst: gathered bitmap
663  * @src: scattered bitmap
664  * @mask: mask representing bits to extract from in the scattered bitmap
665  * @nbits: number of bits in each of these bitmaps
666  *
667  * Gathers bitmap with sparse bits according to the given @mask.
668  *
669  * Example:
670  * If @src bitmap = 0x0302, with @mask = 0x1313, @dst will be 0x001a.
671  *
672  * Or in binary form
673  * @src			@mask			@dst
674  * 0000001100000010	0001001100010011	0000000000011010
675  *
676  * (Bits 0, 1, 4, 8, 9, 12 are copied to the bits 0, 1, 2, 3, 4, 5)
677  *
678  * A more 'visual' description of the operation::
679  *
680  *	mask: ...v..vv...v..vv
681  *	src:  0000001100000010
682  *	         ^  ^^   ^   0
683  *	         |  ||   |  10
684  *	         |  ||   > 010
685  *	         |  |+--> 1010
686  *	         |  +--> 11010
687  *	         +----> 011010
688  *	dst:  0000000000011010
689  *
690  * A relationship exists between bitmap_gather() and bitmap_scatter(). See
691  * bitmap_scatter() for the bitmap scatter detailed operations. TL;DR:
692  * bitmap_scatter() can be seen as the 'reverse' bitmap_gather() operation.
693  *
694  * Suppose scattered computed using bitmap_scatter(scattered, src, mask, n).
695  * The operation bitmap_gather(result, scattered, mask, n) leads to a result
696  * equal or equivalent to src.
697  *
698  * The result can be 'equivalent' because bitmap_scatter() and bitmap_gather()
699  * are not bijective.
700  * The result and src values are equivalent in that sense that a call to
701  * bitmap_scatter(res, src, mask, n) and a call to
702  * bitmap_scatter(res, result, mask, n) will lead to the same res value.
703  */
704 static __always_inline
bitmap_gather(unsigned long * dst,const unsigned long * src,const unsigned long * mask,unsigned int nbits)705 void bitmap_gather(unsigned long *dst, const unsigned long *src,
706 		   const unsigned long *mask, unsigned int nbits)
707 {
708 	unsigned int n = 0;
709 	unsigned int bit;
710 
711 	bitmap_zero(dst, nbits);
712 
713 	for_each_set_bit(bit, mask, nbits)
714 		__assign_bit(n++, dst, test_bit(bit, src));
715 }
716 
717 /**
718  * bitmap_release_region - release allocated bitmap region
719  *	@bitmap: array of unsigned longs corresponding to the bitmap
720  *	@pos: beginning of bit region to release
721  *	@order: region size (log base 2 of number of bits) to release
722  *
723  * This is the complement to __bitmap_find_free_region() and releases
724  * the found region (by clearing it in the bitmap).
725  */
726 static __always_inline
bitmap_release_region(unsigned long * bitmap,unsigned int pos,int order)727 void bitmap_release_region(unsigned long *bitmap, unsigned int pos, int order)
728 {
729 	bitmap_clear(bitmap, pos, BIT(order));
730 }
731 
732 /**
733  * bitmap_allocate_region - allocate bitmap region
734  *	@bitmap: array of unsigned longs corresponding to the bitmap
735  *	@pos: beginning of bit region to allocate
736  *	@order: region size (log base 2 of number of bits) to allocate
737  *
738  * Allocate (set bits in) a specified region of a bitmap.
739  *
740  * Returns: 0 on success, or %-EBUSY if specified region wasn't
741  * free (not all bits were zero).
742  */
743 static __always_inline
bitmap_allocate_region(unsigned long * bitmap,unsigned int pos,int order)744 int bitmap_allocate_region(unsigned long *bitmap, unsigned int pos, int order)
745 {
746 	unsigned int len = BIT(order);
747 
748 	if (find_next_bit(bitmap, pos + len, pos) < pos + len)
749 		return -EBUSY;
750 	bitmap_set(bitmap, pos, len);
751 	return 0;
752 }
753 
754 /**
755  * bitmap_find_free_region - find a contiguous aligned mem region
756  *	@bitmap: array of unsigned longs corresponding to the bitmap
757  *	@bits: number of bits in the bitmap
758  *	@order: region size (log base 2 of number of bits) to find
759  *
760  * Find a region of free (zero) bits in a @bitmap of @bits bits and
761  * allocate them (set them to one).  Only consider regions of length
762  * a power (@order) of two, aligned to that power of two, which
763  * makes the search algorithm much faster.
764  *
765  * Returns: the bit offset in bitmap of the allocated region,
766  * or -errno on failure.
767  */
768 static __always_inline
bitmap_find_free_region(unsigned long * bitmap,unsigned int bits,int order)769 int bitmap_find_free_region(unsigned long *bitmap, unsigned int bits, int order)
770 {
771 	unsigned int pos, end;		/* scans bitmap by regions of size order */
772 
773 	for (pos = 0; (end = pos + BIT(order)) <= bits; pos = end) {
774 		if (!bitmap_allocate_region(bitmap, pos, order))
775 			return pos;
776 	}
777 	return -ENOMEM;
778 }
779 
780 /**
781  * BITMAP_FROM_U64() - Represent u64 value in the format suitable for bitmap.
782  * @n: u64 value
783  *
784  * Linux bitmaps are internally arrays of unsigned longs, i.e. 32-bit
785  * integers in 32-bit environment, and 64-bit integers in 64-bit one.
786  *
787  * There are four combinations of endianness and length of the word in linux
788  * ABIs: LE64, BE64, LE32 and BE32.
789  *
790  * On 64-bit kernels 64-bit LE and BE numbers are naturally ordered in
791  * bitmaps and therefore don't require any special handling.
792  *
793  * On 32-bit kernels 32-bit LE ABI orders lo word of 64-bit number in memory
794  * prior to hi, and 32-bit BE orders hi word prior to lo. The bitmap on the
795  * other hand is represented as an array of 32-bit words and the position of
796  * bit N may therefore be calculated as: word #(N/32) and bit #(N%32) in that
797  * word.  For example, bit #42 is located at 10th position of 2nd word.
798  * It matches 32-bit LE ABI, and we can simply let the compiler store 64-bit
799  * values in memory as it usually does. But for BE we need to swap hi and lo
800  * words manually.
801  *
802  * With all that, the macro BITMAP_FROM_U64() does explicit reordering of hi and
803  * lo parts of u64.  For LE32 it does nothing, and for BE environment it swaps
804  * hi and lo words, as is expected by bitmap.
805  */
806 #if __BITS_PER_LONG == 64
807 #define BITMAP_FROM_U64(n) (n)
808 #else
809 #define BITMAP_FROM_U64(n) ((unsigned long) ((u64)(n) & ULONG_MAX)), \
810 				((unsigned long) ((u64)(n) >> 32))
811 #endif
812 
813 /**
814  * bitmap_from_u64 - Check and swap words within u64.
815  *  @mask: source bitmap
816  *  @dst:  destination bitmap
817  *
818  * In 32-bit Big Endian kernel, when using ``(u32 *)(&val)[*]``
819  * to read u64 mask, we will get the wrong word.
820  * That is ``(u32 *)(&val)[0]`` gets the upper 32 bits,
821  * but we expect the lower 32-bits of u64.
822  */
bitmap_from_u64(unsigned long * dst,u64 mask)823 static __always_inline void bitmap_from_u64(unsigned long *dst, u64 mask)
824 {
825 	bitmap_from_arr64(dst, &mask, 64);
826 }
827 
828 /**
829  * bitmap_read - read a value of n-bits from the memory region
830  * @map: address to the bitmap memory region
831  * @start: bit offset of the n-bit value
832  * @nbits: size of value in bits, nonzero, up to BITS_PER_LONG
833  *
834  * Returns: value of @nbits bits located at the @start bit offset within the
835  * @map memory region. For @nbits = 0 and @nbits > BITS_PER_LONG the return
836  * value is undefined.
837  */
838 static __always_inline
bitmap_read(const unsigned long * map,unsigned long start,unsigned long nbits)839 unsigned long bitmap_read(const unsigned long *map, unsigned long start, unsigned long nbits)
840 {
841 	size_t index = BIT_WORD(start);
842 	unsigned long offset = start % BITS_PER_LONG;
843 	unsigned long space = BITS_PER_LONG - offset;
844 	unsigned long value_low, value_high;
845 
846 	if (unlikely(!nbits || nbits > BITS_PER_LONG))
847 		return 0;
848 
849 	if (space >= nbits)
850 		return (map[index] >> offset) & BITMAP_LAST_WORD_MASK(nbits);
851 
852 	value_low = map[index] & BITMAP_FIRST_WORD_MASK(start);
853 	value_high = map[index + 1] & BITMAP_LAST_WORD_MASK(start + nbits);
854 	return (value_low >> offset) | (value_high << space);
855 }
856 
857 /**
858  * bitmap_write - write n-bit value within a memory region
859  * @map: address to the bitmap memory region
860  * @value: value to write, clamped to nbits
861  * @start: bit offset of the n-bit value
862  * @nbits: size of value in bits, nonzero, up to BITS_PER_LONG.
863  *
864  * bitmap_write() behaves as-if implemented as @nbits calls of __assign_bit(),
865  * i.e. bits beyond @nbits are ignored:
866  *
867  *   for (bit = 0; bit < nbits; bit++)
868  *           __assign_bit(start + bit, bitmap, val & BIT(bit));
869  *
870  * For @nbits == 0 and @nbits > BITS_PER_LONG no writes are performed.
871  */
872 static __always_inline
bitmap_write(unsigned long * map,unsigned long value,unsigned long start,unsigned long nbits)873 void bitmap_write(unsigned long *map, unsigned long value,
874 		  unsigned long start, unsigned long nbits)
875 {
876 	size_t index;
877 	unsigned long offset;
878 	unsigned long space;
879 	unsigned long mask;
880 	bool fit;
881 
882 	if (unlikely(!nbits || nbits > BITS_PER_LONG))
883 		return;
884 
885 	mask = BITMAP_LAST_WORD_MASK(nbits);
886 	value &= mask;
887 	offset = start % BITS_PER_LONG;
888 	space = BITS_PER_LONG - offset;
889 	fit = space >= nbits;
890 	index = BIT_WORD(start);
891 
892 	map[index] &= (fit ? (~(mask << offset)) : ~BITMAP_FIRST_WORD_MASK(start));
893 	map[index] |= value << offset;
894 	if (fit)
895 		return;
896 
897 	map[index + 1] &= BITMAP_FIRST_WORD_MASK(start + nbits);
898 	map[index + 1] |= (value >> space);
899 }
900 
901 #define bitmap_get_value8(map, start)			\
902 	bitmap_read(map, start, BITS_PER_BYTE)
903 #define bitmap_set_value8(map, value, start)		\
904 	bitmap_write(map, value, start, BITS_PER_BYTE)
905 
906 #endif /* __ASSEMBLER__ */
907 
908 #endif /* __LINUX_BITMAP_H */
909