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