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