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