Merge tag 'drm-next-2018-06-15' of git://anongit.freedesktop.org/drm/drm
[linux.git] / lib / bitmap.c
1 /*
2  * lib/bitmap.c
3  * Helper functions for bitmap.h.
4  *
5  * This source code is licensed under the GNU General Public License,
6  * Version 2.  See the file COPYING for more details.
7  */
8 #include <linux/export.h>
9 #include <linux/thread_info.h>
10 #include <linux/ctype.h>
11 #include <linux/errno.h>
12 #include <linux/bitmap.h>
13 #include <linux/bitops.h>
14 #include <linux/bug.h>
15 #include <linux/kernel.h>
16 #include <linux/string.h>
17 #include <linux/uaccess.h>
18
19 #include <asm/page.h>
20
21 /**
22  * DOC: bitmap introduction
23  *
24  * bitmaps provide an array of bits, implemented using an an
25  * array of unsigned longs.  The number of valid bits in a
26  * given bitmap does _not_ need to be an exact multiple of
27  * BITS_PER_LONG.
28  *
29  * The possible unused bits in the last, partially used word
30  * of a bitmap are 'don't care'.  The implementation makes
31  * no particular effort to keep them zero.  It ensures that
32  * their value will not affect the results of any operation.
33  * The bitmap operations that return Boolean (bitmap_empty,
34  * for example) or scalar (bitmap_weight, for example) results
35  * carefully filter out these unused bits from impacting their
36  * results.
37  *
38  * These operations actually hold to a slightly stronger rule:
39  * if you don't input any bitmaps to these ops that have some
40  * unused bits set, then they won't output any set unused bits
41  * in output bitmaps.
42  *
43  * The byte ordering of bitmaps is more natural on little
44  * endian architectures.  See the big-endian headers
45  * include/asm-ppc64/bitops.h and include/asm-s390/bitops.h
46  * for the best explanations of this ordering.
47  */
48
49 int __bitmap_equal(const unsigned long *bitmap1,
50                 const unsigned long *bitmap2, unsigned int bits)
51 {
52         unsigned int k, lim = bits/BITS_PER_LONG;
53         for (k = 0; k < lim; ++k)
54                 if (bitmap1[k] != bitmap2[k])
55                         return 0;
56
57         if (bits % BITS_PER_LONG)
58                 if ((bitmap1[k] ^ bitmap2[k]) & BITMAP_LAST_WORD_MASK(bits))
59                         return 0;
60
61         return 1;
62 }
63 EXPORT_SYMBOL(__bitmap_equal);
64
65 void __bitmap_complement(unsigned long *dst, const unsigned long *src, unsigned int bits)
66 {
67         unsigned int k, lim = BITS_TO_LONGS(bits);
68         for (k = 0; k < lim; ++k)
69                 dst[k] = ~src[k];
70 }
71 EXPORT_SYMBOL(__bitmap_complement);
72
73 /**
74  * __bitmap_shift_right - logical right shift of the bits in a bitmap
75  *   @dst : destination bitmap
76  *   @src : source bitmap
77  *   @shift : shift by this many bits
78  *   @nbits : bitmap size, in bits
79  *
80  * Shifting right (dividing) means moving bits in the MS -> LS bit
81  * direction.  Zeros are fed into the vacated MS positions and the
82  * LS bits shifted off the bottom are lost.
83  */
84 void __bitmap_shift_right(unsigned long *dst, const unsigned long *src,
85                         unsigned shift, unsigned nbits)
86 {
87         unsigned k, lim = BITS_TO_LONGS(nbits);
88         unsigned off = shift/BITS_PER_LONG, rem = shift % BITS_PER_LONG;
89         unsigned long mask = BITMAP_LAST_WORD_MASK(nbits);
90         for (k = 0; off + k < lim; ++k) {
91                 unsigned long upper, lower;
92
93                 /*
94                  * If shift is not word aligned, take lower rem bits of
95                  * word above and make them the top rem bits of result.
96                  */
97                 if (!rem || off + k + 1 >= lim)
98                         upper = 0;
99                 else {
100                         upper = src[off + k + 1];
101                         if (off + k + 1 == lim - 1)
102                                 upper &= mask;
103                         upper <<= (BITS_PER_LONG - rem);
104                 }
105                 lower = src[off + k];
106                 if (off + k == lim - 1)
107                         lower &= mask;
108                 lower >>= rem;
109                 dst[k] = lower | upper;
110         }
111         if (off)
112                 memset(&dst[lim - off], 0, off*sizeof(unsigned long));
113 }
114 EXPORT_SYMBOL(__bitmap_shift_right);
115
116
117 /**
118  * __bitmap_shift_left - logical left shift of the bits in a bitmap
119  *   @dst : destination bitmap
120  *   @src : source bitmap
121  *   @shift : shift by this many bits
122  *   @nbits : bitmap size, in bits
123  *
124  * Shifting left (multiplying) means moving bits in the LS -> MS
125  * direction.  Zeros are fed into the vacated LS bit positions
126  * and those MS bits shifted off the top are lost.
127  */
128
129 void __bitmap_shift_left(unsigned long *dst, const unsigned long *src,
130                         unsigned int shift, unsigned int nbits)
131 {
132         int k;
133         unsigned int lim = BITS_TO_LONGS(nbits);
134         unsigned int off = shift/BITS_PER_LONG, rem = shift % BITS_PER_LONG;
135         for (k = lim - off - 1; k >= 0; --k) {
136                 unsigned long upper, lower;
137
138                 /*
139                  * If shift is not word aligned, take upper rem bits of
140                  * word below and make them the bottom rem bits of result.
141                  */
142                 if (rem && k > 0)
143                         lower = src[k - 1] >> (BITS_PER_LONG - rem);
144                 else
145                         lower = 0;
146                 upper = src[k] << rem;
147                 dst[k + off] = lower | upper;
148         }
149         if (off)
150                 memset(dst, 0, off*sizeof(unsigned long));
151 }
152 EXPORT_SYMBOL(__bitmap_shift_left);
153
154 int __bitmap_and(unsigned long *dst, const unsigned long *bitmap1,
155                                 const unsigned long *bitmap2, unsigned int bits)
156 {
157         unsigned int k;
158         unsigned int lim = bits/BITS_PER_LONG;
159         unsigned long result = 0;
160
161         for (k = 0; k < lim; k++)
162                 result |= (dst[k] = bitmap1[k] & bitmap2[k]);
163         if (bits % BITS_PER_LONG)
164                 result |= (dst[k] = bitmap1[k] & bitmap2[k] &
165                            BITMAP_LAST_WORD_MASK(bits));
166         return result != 0;
167 }
168 EXPORT_SYMBOL(__bitmap_and);
169
170 void __bitmap_or(unsigned long *dst, const unsigned long *bitmap1,
171                                 const unsigned long *bitmap2, unsigned int bits)
172 {
173         unsigned int k;
174         unsigned int nr = BITS_TO_LONGS(bits);
175
176         for (k = 0; k < nr; k++)
177                 dst[k] = bitmap1[k] | bitmap2[k];
178 }
179 EXPORT_SYMBOL(__bitmap_or);
180
181 void __bitmap_xor(unsigned long *dst, const unsigned long *bitmap1,
182                                 const unsigned long *bitmap2, unsigned int bits)
183 {
184         unsigned int k;
185         unsigned int nr = BITS_TO_LONGS(bits);
186
187         for (k = 0; k < nr; k++)
188                 dst[k] = bitmap1[k] ^ bitmap2[k];
189 }
190 EXPORT_SYMBOL(__bitmap_xor);
191
192 int __bitmap_andnot(unsigned long *dst, const unsigned long *bitmap1,
193                                 const unsigned long *bitmap2, unsigned int bits)
194 {
195         unsigned int k;
196         unsigned int lim = bits/BITS_PER_LONG;
197         unsigned long result = 0;
198
199         for (k = 0; k < lim; k++)
200                 result |= (dst[k] = bitmap1[k] & ~bitmap2[k]);
201         if (bits % BITS_PER_LONG)
202                 result |= (dst[k] = bitmap1[k] & ~bitmap2[k] &
203                            BITMAP_LAST_WORD_MASK(bits));
204         return result != 0;
205 }
206 EXPORT_SYMBOL(__bitmap_andnot);
207
208 int __bitmap_intersects(const unsigned long *bitmap1,
209                         const unsigned long *bitmap2, unsigned int bits)
210 {
211         unsigned int k, lim = bits/BITS_PER_LONG;
212         for (k = 0; k < lim; ++k)
213                 if (bitmap1[k] & bitmap2[k])
214                         return 1;
215
216         if (bits % BITS_PER_LONG)
217                 if ((bitmap1[k] & bitmap2[k]) & BITMAP_LAST_WORD_MASK(bits))
218                         return 1;
219         return 0;
220 }
221 EXPORT_SYMBOL(__bitmap_intersects);
222
223 int __bitmap_subset(const unsigned long *bitmap1,
224                     const unsigned long *bitmap2, unsigned int bits)
225 {
226         unsigned int k, lim = bits/BITS_PER_LONG;
227         for (k = 0; k < lim; ++k)
228                 if (bitmap1[k] & ~bitmap2[k])
229                         return 0;
230
231         if (bits % BITS_PER_LONG)
232                 if ((bitmap1[k] & ~bitmap2[k]) & BITMAP_LAST_WORD_MASK(bits))
233                         return 0;
234         return 1;
235 }
236 EXPORT_SYMBOL(__bitmap_subset);
237
238 int __bitmap_weight(const unsigned long *bitmap, unsigned int bits)
239 {
240         unsigned int k, lim = bits/BITS_PER_LONG;
241         int w = 0;
242
243         for (k = 0; k < lim; k++)
244                 w += hweight_long(bitmap[k]);
245
246         if (bits % BITS_PER_LONG)
247                 w += hweight_long(bitmap[k] & BITMAP_LAST_WORD_MASK(bits));
248
249         return w;
250 }
251 EXPORT_SYMBOL(__bitmap_weight);
252
253 void __bitmap_set(unsigned long *map, unsigned int start, int len)
254 {
255         unsigned long *p = map + BIT_WORD(start);
256         const unsigned int size = start + len;
257         int bits_to_set = BITS_PER_LONG - (start % BITS_PER_LONG);
258         unsigned long mask_to_set = BITMAP_FIRST_WORD_MASK(start);
259
260         while (len - bits_to_set >= 0) {
261                 *p |= mask_to_set;
262                 len -= bits_to_set;
263                 bits_to_set = BITS_PER_LONG;
264                 mask_to_set = ~0UL;
265                 p++;
266         }
267         if (len) {
268                 mask_to_set &= BITMAP_LAST_WORD_MASK(size);
269                 *p |= mask_to_set;
270         }
271 }
272 EXPORT_SYMBOL(__bitmap_set);
273
274 void __bitmap_clear(unsigned long *map, unsigned int start, int len)
275 {
276         unsigned long *p = map + BIT_WORD(start);
277         const unsigned int size = start + len;
278         int bits_to_clear = BITS_PER_LONG - (start % BITS_PER_LONG);
279         unsigned long mask_to_clear = BITMAP_FIRST_WORD_MASK(start);
280
281         while (len - bits_to_clear >= 0) {
282                 *p &= ~mask_to_clear;
283                 len -= bits_to_clear;
284                 bits_to_clear = BITS_PER_LONG;
285                 mask_to_clear = ~0UL;
286                 p++;
287         }
288         if (len) {
289                 mask_to_clear &= BITMAP_LAST_WORD_MASK(size);
290                 *p &= ~mask_to_clear;
291         }
292 }
293 EXPORT_SYMBOL(__bitmap_clear);
294
295 /**
296  * bitmap_find_next_zero_area_off - find a contiguous aligned zero area
297  * @map: The address to base the search on
298  * @size: The bitmap size in bits
299  * @start: The bitnumber to start searching at
300  * @nr: The number of zeroed bits we're looking for
301  * @align_mask: Alignment mask for zero area
302  * @align_offset: Alignment offset for zero area.
303  *
304  * The @align_mask should be one less than a power of 2; the effect is that
305  * the bit offset of all zero areas this function finds plus @align_offset
306  * is multiple of that power of 2.
307  */
308 unsigned long bitmap_find_next_zero_area_off(unsigned long *map,
309                                              unsigned long size,
310                                              unsigned long start,
311                                              unsigned int nr,
312                                              unsigned long align_mask,
313                                              unsigned long align_offset)
314 {
315         unsigned long index, end, i;
316 again:
317         index = find_next_zero_bit(map, size, start);
318
319         /* Align allocation */
320         index = __ALIGN_MASK(index + align_offset, align_mask) - align_offset;
321
322         end = index + nr;
323         if (end > size)
324                 return end;
325         i = find_next_bit(map, end, index);
326         if (i < end) {
327                 start = i + 1;
328                 goto again;
329         }
330         return index;
331 }
332 EXPORT_SYMBOL(bitmap_find_next_zero_area_off);
333
334 /*
335  * Bitmap printing & parsing functions: first version by Nadia Yvette Chambers,
336  * second version by Paul Jackson, third by Joe Korty.
337  */
338
339 #define CHUNKSZ                         32
340 #define nbits_to_hold_value(val)        fls(val)
341 #define BASEDEC 10              /* fancier cpuset lists input in decimal */
342
343 /**
344  * __bitmap_parse - convert an ASCII hex string into a bitmap.
345  * @buf: pointer to buffer containing string.
346  * @buflen: buffer size in bytes.  If string is smaller than this
347  *    then it must be terminated with a \0.
348  * @is_user: location of buffer, 0 indicates kernel space
349  * @maskp: pointer to bitmap array that will contain result.
350  * @nmaskbits: size of bitmap, in bits.
351  *
352  * Commas group hex digits into chunks.  Each chunk defines exactly 32
353  * bits of the resultant bitmask.  No chunk may specify a value larger
354  * than 32 bits (%-EOVERFLOW), and if a chunk specifies a smaller value
355  * then leading 0-bits are prepended.  %-EINVAL is returned for illegal
356  * characters and for grouping errors such as "1,,5", ",44", "," and "".
357  * Leading and trailing whitespace accepted, but not embedded whitespace.
358  */
359 int __bitmap_parse(const char *buf, unsigned int buflen,
360                 int is_user, unsigned long *maskp,
361                 int nmaskbits)
362 {
363         int c, old_c, totaldigits, ndigits, nchunks, nbits;
364         u32 chunk;
365         const char __user __force *ubuf = (const char __user __force *)buf;
366
367         bitmap_zero(maskp, nmaskbits);
368
369         nchunks = nbits = totaldigits = c = 0;
370         do {
371                 chunk = 0;
372                 ndigits = totaldigits;
373
374                 /* Get the next chunk of the bitmap */
375                 while (buflen) {
376                         old_c = c;
377                         if (is_user) {
378                                 if (__get_user(c, ubuf++))
379                                         return -EFAULT;
380                         }
381                         else
382                                 c = *buf++;
383                         buflen--;
384                         if (isspace(c))
385                                 continue;
386
387                         /*
388                          * If the last character was a space and the current
389                          * character isn't '\0', we've got embedded whitespace.
390                          * This is a no-no, so throw an error.
391                          */
392                         if (totaldigits && c && isspace(old_c))
393                                 return -EINVAL;
394
395                         /* A '\0' or a ',' signal the end of the chunk */
396                         if (c == '\0' || c == ',')
397                                 break;
398
399                         if (!isxdigit(c))
400                                 return -EINVAL;
401
402                         /*
403                          * Make sure there are at least 4 free bits in 'chunk'.
404                          * If not, this hexdigit will overflow 'chunk', so
405                          * throw an error.
406                          */
407                         if (chunk & ~((1UL << (CHUNKSZ - 4)) - 1))
408                                 return -EOVERFLOW;
409
410                         chunk = (chunk << 4) | hex_to_bin(c);
411                         totaldigits++;
412                 }
413                 if (ndigits == totaldigits)
414                         return -EINVAL;
415                 if (nchunks == 0 && chunk == 0)
416                         continue;
417
418                 __bitmap_shift_left(maskp, maskp, CHUNKSZ, nmaskbits);
419                 *maskp |= chunk;
420                 nchunks++;
421                 nbits += (nchunks == 1) ? nbits_to_hold_value(chunk) : CHUNKSZ;
422                 if (nbits > nmaskbits)
423                         return -EOVERFLOW;
424         } while (buflen && c == ',');
425
426         return 0;
427 }
428 EXPORT_SYMBOL(__bitmap_parse);
429
430 /**
431  * bitmap_parse_user - convert an ASCII hex string in a user buffer into a bitmap
432  *
433  * @ubuf: pointer to user buffer containing string.
434  * @ulen: buffer size in bytes.  If string is smaller than this
435  *    then it must be terminated with a \0.
436  * @maskp: pointer to bitmap array that will contain result.
437  * @nmaskbits: size of bitmap, in bits.
438  *
439  * Wrapper for __bitmap_parse(), providing it with user buffer.
440  *
441  * We cannot have this as an inline function in bitmap.h because it needs
442  * linux/uaccess.h to get the access_ok() declaration and this causes
443  * cyclic dependencies.
444  */
445 int bitmap_parse_user(const char __user *ubuf,
446                         unsigned int ulen, unsigned long *maskp,
447                         int nmaskbits)
448 {
449         if (!access_ok(VERIFY_READ, ubuf, ulen))
450                 return -EFAULT;
451         return __bitmap_parse((const char __force *)ubuf,
452                                 ulen, 1, maskp, nmaskbits);
453
454 }
455 EXPORT_SYMBOL(bitmap_parse_user);
456
457 /**
458  * bitmap_print_to_pagebuf - convert bitmap to list or hex format ASCII string
459  * @list: indicates whether the bitmap must be list
460  * @buf: page aligned buffer into which string is placed
461  * @maskp: pointer to bitmap to convert
462  * @nmaskbits: size of bitmap, in bits
463  *
464  * Output format is a comma-separated list of decimal numbers and
465  * ranges if list is specified or hex digits grouped into comma-separated
466  * sets of 8 digits/set. Returns the number of characters written to buf.
467  *
468  * It is assumed that @buf is a pointer into a PAGE_SIZE area and that
469  * sufficient storage remains at @buf to accommodate the
470  * bitmap_print_to_pagebuf() output.
471  */
472 int bitmap_print_to_pagebuf(bool list, char *buf, const unsigned long *maskp,
473                             int nmaskbits)
474 {
475         ptrdiff_t len = PTR_ALIGN(buf + PAGE_SIZE - 1, PAGE_SIZE) - buf;
476         int n = 0;
477
478         if (len > 1)
479                 n = list ? scnprintf(buf, len, "%*pbl\n", nmaskbits, maskp) :
480                            scnprintf(buf, len, "%*pb\n", nmaskbits, maskp);
481         return n;
482 }
483 EXPORT_SYMBOL(bitmap_print_to_pagebuf);
484
485 /**
486  * __bitmap_parselist - convert list format ASCII string to bitmap
487  * @buf: read nul-terminated user string from this buffer
488  * @buflen: buffer size in bytes.  If string is smaller than this
489  *    then it must be terminated with a \0.
490  * @is_user: location of buffer, 0 indicates kernel space
491  * @maskp: write resulting mask here
492  * @nmaskbits: number of bits in mask to be written
493  *
494  * Input format is a comma-separated list of decimal numbers and
495  * ranges.  Consecutively set bits are shown as two hyphen-separated
496  * decimal numbers, the smallest and largest bit numbers set in
497  * the range.
498  * Optionally each range can be postfixed to denote that only parts of it
499  * should be set. The range will divided to groups of specific size.
500  * From each group will be used only defined amount of bits.
501  * Syntax: range:used_size/group_size
502  * Example: 0-1023:2/256 ==> 0,1,256,257,512,513,768,769
503  *
504  * Returns: 0 on success, -errno on invalid input strings. Error values:
505  *
506  *   - ``-EINVAL``: second number in range smaller than first
507  *   - ``-EINVAL``: invalid character in string
508  *   - ``-ERANGE``: bit number specified too large for mask
509  */
510 static int __bitmap_parselist(const char *buf, unsigned int buflen,
511                 int is_user, unsigned long *maskp,
512                 int nmaskbits)
513 {
514         unsigned int a, b, old_a, old_b;
515         unsigned int group_size, used_size, off;
516         int c, old_c, totaldigits, ndigits;
517         const char __user __force *ubuf = (const char __user __force *)buf;
518         int at_start, in_range, in_partial_range;
519
520         totaldigits = c = 0;
521         old_a = old_b = 0;
522         group_size = used_size = 0;
523         bitmap_zero(maskp, nmaskbits);
524         do {
525                 at_start = 1;
526                 in_range = 0;
527                 in_partial_range = 0;
528                 a = b = 0;
529                 ndigits = totaldigits;
530
531                 /* Get the next cpu# or a range of cpu#'s */
532                 while (buflen) {
533                         old_c = c;
534                         if (is_user) {
535                                 if (__get_user(c, ubuf++))
536                                         return -EFAULT;
537                         } else
538                                 c = *buf++;
539                         buflen--;
540                         if (isspace(c))
541                                 continue;
542
543                         /* A '\0' or a ',' signal the end of a cpu# or range */
544                         if (c == '\0' || c == ',')
545                                 break;
546                         /*
547                         * whitespaces between digits are not allowed,
548                         * but it's ok if whitespaces are on head or tail.
549                         * when old_c is whilespace,
550                         * if totaldigits == ndigits, whitespace is on head.
551                         * if whitespace is on tail, it should not run here.
552                         * as c was ',' or '\0',
553                         * the last code line has broken the current loop.
554                         */
555                         if ((totaldigits != ndigits) && isspace(old_c))
556                                 return -EINVAL;
557
558                         if (c == '/') {
559                                 used_size = a;
560                                 at_start = 1;
561                                 in_range = 0;
562                                 a = b = 0;
563                                 continue;
564                         }
565
566                         if (c == ':') {
567                                 old_a = a;
568                                 old_b = b;
569                                 at_start = 1;
570                                 in_range = 0;
571                                 in_partial_range = 1;
572                                 a = b = 0;
573                                 continue;
574                         }
575
576                         if (c == '-') {
577                                 if (at_start || in_range)
578                                         return -EINVAL;
579                                 b = 0;
580                                 in_range = 1;
581                                 at_start = 1;
582                                 continue;
583                         }
584
585                         if (!isdigit(c))
586                                 return -EINVAL;
587
588                         b = b * 10 + (c - '0');
589                         if (!in_range)
590                                 a = b;
591                         at_start = 0;
592                         totaldigits++;
593                 }
594                 if (ndigits == totaldigits)
595                         continue;
596                 if (in_partial_range) {
597                         group_size = a;
598                         a = old_a;
599                         b = old_b;
600                         old_a = old_b = 0;
601                 } else {
602                         used_size = group_size = b - a + 1;
603                 }
604                 /* if no digit is after '-', it's wrong*/
605                 if (at_start && in_range)
606                         return -EINVAL;
607                 if (!(a <= b) || group_size == 0 || !(used_size <= group_size))
608                         return -EINVAL;
609                 if (b >= nmaskbits)
610                         return -ERANGE;
611                 while (a <= b) {
612                         off = min(b - a + 1, used_size);
613                         bitmap_set(maskp, a, off);
614                         a += group_size;
615                 }
616         } while (buflen && c == ',');
617         return 0;
618 }
619
620 int bitmap_parselist(const char *bp, unsigned long *maskp, int nmaskbits)
621 {
622         char *nl  = strchrnul(bp, '\n');
623         int len = nl - bp;
624
625         return __bitmap_parselist(bp, len, 0, maskp, nmaskbits);
626 }
627 EXPORT_SYMBOL(bitmap_parselist);
628
629
630 /**
631  * bitmap_parselist_user()
632  *
633  * @ubuf: pointer to user buffer containing string.
634  * @ulen: buffer size in bytes.  If string is smaller than this
635  *    then it must be terminated with a \0.
636  * @maskp: pointer to bitmap array that will contain result.
637  * @nmaskbits: size of bitmap, in bits.
638  *
639  * Wrapper for bitmap_parselist(), providing it with user buffer.
640  *
641  * We cannot have this as an inline function in bitmap.h because it needs
642  * linux/uaccess.h to get the access_ok() declaration and this causes
643  * cyclic dependencies.
644  */
645 int bitmap_parselist_user(const char __user *ubuf,
646                         unsigned int ulen, unsigned long *maskp,
647                         int nmaskbits)
648 {
649         if (!access_ok(VERIFY_READ, ubuf, ulen))
650                 return -EFAULT;
651         return __bitmap_parselist((const char __force *)ubuf,
652                                         ulen, 1, maskp, nmaskbits);
653 }
654 EXPORT_SYMBOL(bitmap_parselist_user);
655
656
657 /**
658  * bitmap_pos_to_ord - find ordinal of set bit at given position in bitmap
659  *      @buf: pointer to a bitmap
660  *      @pos: a bit position in @buf (0 <= @pos < @nbits)
661  *      @nbits: number of valid bit positions in @buf
662  *
663  * Map the bit at position @pos in @buf (of length @nbits) to the
664  * ordinal of which set bit it is.  If it is not set or if @pos
665  * is not a valid bit position, map to -1.
666  *
667  * If for example, just bits 4 through 7 are set in @buf, then @pos
668  * values 4 through 7 will get mapped to 0 through 3, respectively,
669  * and other @pos values will get mapped to -1.  When @pos value 7
670  * gets mapped to (returns) @ord value 3 in this example, that means
671  * that bit 7 is the 3rd (starting with 0th) set bit in @buf.
672  *
673  * The bit positions 0 through @bits are valid positions in @buf.
674  */
675 static int bitmap_pos_to_ord(const unsigned long *buf, unsigned int pos, unsigned int nbits)
676 {
677         if (pos >= nbits || !test_bit(pos, buf))
678                 return -1;
679
680         return __bitmap_weight(buf, pos);
681 }
682
683 /**
684  * bitmap_ord_to_pos - find position of n-th set bit in bitmap
685  *      @buf: pointer to bitmap
686  *      @ord: ordinal bit position (n-th set bit, n >= 0)
687  *      @nbits: number of valid bit positions in @buf
688  *
689  * Map the ordinal offset of bit @ord in @buf to its position in @buf.
690  * Value of @ord should be in range 0 <= @ord < weight(buf). If @ord
691  * >= weight(buf), returns @nbits.
692  *
693  * If for example, just bits 4 through 7 are set in @buf, then @ord
694  * values 0 through 3 will get mapped to 4 through 7, respectively,
695  * and all other @ord values returns @nbits.  When @ord value 3
696  * gets mapped to (returns) @pos value 7 in this example, that means
697  * that the 3rd set bit (starting with 0th) is at position 7 in @buf.
698  *
699  * The bit positions 0 through @nbits-1 are valid positions in @buf.
700  */
701 unsigned int bitmap_ord_to_pos(const unsigned long *buf, unsigned int ord, unsigned int nbits)
702 {
703         unsigned int pos;
704
705         for (pos = find_first_bit(buf, nbits);
706              pos < nbits && ord;
707              pos = find_next_bit(buf, nbits, pos + 1))
708                 ord--;
709
710         return pos;
711 }
712
713 /**
714  * bitmap_remap - Apply map defined by a pair of bitmaps to another bitmap
715  *      @dst: remapped result
716  *      @src: subset to be remapped
717  *      @old: defines domain of map
718  *      @new: defines range of map
719  *      @nbits: number of bits in each of these bitmaps
720  *
721  * Let @old and @new define a mapping of bit positions, such that
722  * whatever position is held by the n-th set bit in @old is mapped
723  * to the n-th set bit in @new.  In the more general case, allowing
724  * for the possibility that the weight 'w' of @new is less than the
725  * weight of @old, map the position of the n-th set bit in @old to
726  * the position of the m-th set bit in @new, where m == n % w.
727  *
728  * If either of the @old and @new bitmaps are empty, or if @src and
729  * @dst point to the same location, then this routine copies @src
730  * to @dst.
731  *
732  * The positions of unset bits in @old are mapped to themselves
733  * (the identify map).
734  *
735  * Apply the above specified mapping to @src, placing the result in
736  * @dst, clearing any bits previously set in @dst.
737  *
738  * For example, lets say that @old has bits 4 through 7 set, and
739  * @new has bits 12 through 15 set.  This defines the mapping of bit
740  * position 4 to 12, 5 to 13, 6 to 14 and 7 to 15, and of all other
741  * bit positions unchanged.  So if say @src comes into this routine
742  * with bits 1, 5 and 7 set, then @dst should leave with bits 1,
743  * 13 and 15 set.
744  */
745 void bitmap_remap(unsigned long *dst, const unsigned long *src,
746                 const unsigned long *old, const unsigned long *new,
747                 unsigned int nbits)
748 {
749         unsigned int oldbit, w;
750
751         if (dst == src)         /* following doesn't handle inplace remaps */
752                 return;
753         bitmap_zero(dst, nbits);
754
755         w = bitmap_weight(new, nbits);
756         for_each_set_bit(oldbit, src, nbits) {
757                 int n = bitmap_pos_to_ord(old, oldbit, nbits);
758
759                 if (n < 0 || w == 0)
760                         set_bit(oldbit, dst);   /* identity map */
761                 else
762                         set_bit(bitmap_ord_to_pos(new, n % w, nbits), dst);
763         }
764 }
765 EXPORT_SYMBOL(bitmap_remap);
766
767 /**
768  * bitmap_bitremap - Apply map defined by a pair of bitmaps to a single bit
769  *      @oldbit: bit position to be mapped
770  *      @old: defines domain of map
771  *      @new: defines range of map
772  *      @bits: number of bits in each of these bitmaps
773  *
774  * Let @old and @new define a mapping of bit positions, such that
775  * whatever position is held by the n-th set bit in @old is mapped
776  * to the n-th set bit in @new.  In the more general case, allowing
777  * for the possibility that the weight 'w' of @new is less than the
778  * weight of @old, map the position of the n-th set bit in @old to
779  * the position of the m-th set bit in @new, where m == n % w.
780  *
781  * The positions of unset bits in @old are mapped to themselves
782  * (the identify map).
783  *
784  * Apply the above specified mapping to bit position @oldbit, returning
785  * the new bit position.
786  *
787  * For example, lets say that @old has bits 4 through 7 set, and
788  * @new has bits 12 through 15 set.  This defines the mapping of bit
789  * position 4 to 12, 5 to 13, 6 to 14 and 7 to 15, and of all other
790  * bit positions unchanged.  So if say @oldbit is 5, then this routine
791  * returns 13.
792  */
793 int bitmap_bitremap(int oldbit, const unsigned long *old,
794                                 const unsigned long *new, int bits)
795 {
796         int w = bitmap_weight(new, bits);
797         int n = bitmap_pos_to_ord(old, oldbit, bits);
798         if (n < 0 || w == 0)
799                 return oldbit;
800         else
801                 return bitmap_ord_to_pos(new, n % w, bits);
802 }
803 EXPORT_SYMBOL(bitmap_bitremap);
804
805 /**
806  * bitmap_onto - translate one bitmap relative to another
807  *      @dst: resulting translated bitmap
808  *      @orig: original untranslated bitmap
809  *      @relmap: bitmap relative to which translated
810  *      @bits: number of bits in each of these bitmaps
811  *
812  * Set the n-th bit of @dst iff there exists some m such that the
813  * n-th bit of @relmap is set, the m-th bit of @orig is set, and
814  * the n-th bit of @relmap is also the m-th _set_ bit of @relmap.
815  * (If you understood the previous sentence the first time your
816  * read it, you're overqualified for your current job.)
817  *
818  * In other words, @orig is mapped onto (surjectively) @dst,
819  * using the map { <n, m> | the n-th bit of @relmap is the
820  * m-th set bit of @relmap }.
821  *
822  * Any set bits in @orig above bit number W, where W is the
823  * weight of (number of set bits in) @relmap are mapped nowhere.
824  * In particular, if for all bits m set in @orig, m >= W, then
825  * @dst will end up empty.  In situations where the possibility
826  * of such an empty result is not desired, one way to avoid it is
827  * to use the bitmap_fold() operator, below, to first fold the
828  * @orig bitmap over itself so that all its set bits x are in the
829  * range 0 <= x < W.  The bitmap_fold() operator does this by
830  * setting the bit (m % W) in @dst, for each bit (m) set in @orig.
831  *
832  * Example [1] for bitmap_onto():
833  *  Let's say @relmap has bits 30-39 set, and @orig has bits
834  *  1, 3, 5, 7, 9 and 11 set.  Then on return from this routine,
835  *  @dst will have bits 31, 33, 35, 37 and 39 set.
836  *
837  *  When bit 0 is set in @orig, it means turn on the bit in
838  *  @dst corresponding to whatever is the first bit (if any)
839  *  that is turned on in @relmap.  Since bit 0 was off in the
840  *  above example, we leave off that bit (bit 30) in @dst.
841  *
842  *  When bit 1 is set in @orig (as in the above example), it
843  *  means turn on the bit in @dst corresponding to whatever
844  *  is the second bit that is turned on in @relmap.  The second
845  *  bit in @relmap that was turned on in the above example was
846  *  bit 31, so we turned on bit 31 in @dst.
847  *
848  *  Similarly, we turned on bits 33, 35, 37 and 39 in @dst,
849  *  because they were the 4th, 6th, 8th and 10th set bits
850  *  set in @relmap, and the 4th, 6th, 8th and 10th bits of
851  *  @orig (i.e. bits 3, 5, 7 and 9) were also set.
852  *
853  *  When bit 11 is set in @orig, it means turn on the bit in
854  *  @dst corresponding to whatever is the twelfth bit that is
855  *  turned on in @relmap.  In the above example, there were
856  *  only ten bits turned on in @relmap (30..39), so that bit
857  *  11 was set in @orig had no affect on @dst.
858  *
859  * Example [2] for bitmap_fold() + bitmap_onto():
860  *  Let's say @relmap has these ten bits set::
861  *
862  *              40 41 42 43 45 48 53 61 74 95
863  *
864  *  (for the curious, that's 40 plus the first ten terms of the
865  *  Fibonacci sequence.)
866  *
867  *  Further lets say we use the following code, invoking
868  *  bitmap_fold() then bitmap_onto, as suggested above to
869  *  avoid the possibility of an empty @dst result::
870  *
871  *      unsigned long *tmp;     // a temporary bitmap's bits
872  *
873  *      bitmap_fold(tmp, orig, bitmap_weight(relmap, bits), bits);
874  *      bitmap_onto(dst, tmp, relmap, bits);
875  *
876  *  Then this table shows what various values of @dst would be, for
877  *  various @orig's.  I list the zero-based positions of each set bit.
878  *  The tmp column shows the intermediate result, as computed by
879  *  using bitmap_fold() to fold the @orig bitmap modulo ten
880  *  (the weight of @relmap):
881  *
882  *      =============== ============== =================
883  *      @orig           tmp            @dst
884  *      0                0             40
885  *      1                1             41
886  *      9                9             95
887  *      10               0             40 [#f1]_
888  *      1 3 5 7          1 3 5 7       41 43 48 61
889  *      0 1 2 3 4        0 1 2 3 4     40 41 42 43 45
890  *      0 9 18 27        0 9 8 7       40 61 74 95
891  *      0 10 20 30       0             40
892  *      0 11 22 33       0 1 2 3       40 41 42 43
893  *      0 12 24 36       0 2 4 6       40 42 45 53
894  *      78 102 211       1 2 8         41 42 74 [#f1]_
895  *      =============== ============== =================
896  *
897  * .. [#f1]
898  *
899  *     For these marked lines, if we hadn't first done bitmap_fold()
900  *     into tmp, then the @dst result would have been empty.
901  *
902  * If either of @orig or @relmap is empty (no set bits), then @dst
903  * will be returned empty.
904  *
905  * If (as explained above) the only set bits in @orig are in positions
906  * m where m >= W, (where W is the weight of @relmap) then @dst will
907  * once again be returned empty.
908  *
909  * All bits in @dst not set by the above rule are cleared.
910  */
911 void bitmap_onto(unsigned long *dst, const unsigned long *orig,
912                         const unsigned long *relmap, unsigned int bits)
913 {
914         unsigned int n, m;      /* same meaning as in above comment */
915
916         if (dst == orig)        /* following doesn't handle inplace mappings */
917                 return;
918         bitmap_zero(dst, bits);
919
920         /*
921          * The following code is a more efficient, but less
922          * obvious, equivalent to the loop:
923          *      for (m = 0; m < bitmap_weight(relmap, bits); m++) {
924          *              n = bitmap_ord_to_pos(orig, m, bits);
925          *              if (test_bit(m, orig))
926          *                      set_bit(n, dst);
927          *      }
928          */
929
930         m = 0;
931         for_each_set_bit(n, relmap, bits) {
932                 /* m == bitmap_pos_to_ord(relmap, n, bits) */
933                 if (test_bit(m, orig))
934                         set_bit(n, dst);
935                 m++;
936         }
937 }
938 EXPORT_SYMBOL(bitmap_onto);
939
940 /**
941  * bitmap_fold - fold larger bitmap into smaller, modulo specified size
942  *      @dst: resulting smaller bitmap
943  *      @orig: original larger bitmap
944  *      @sz: specified size
945  *      @nbits: number of bits in each of these bitmaps
946  *
947  * For each bit oldbit in @orig, set bit oldbit mod @sz in @dst.
948  * Clear all other bits in @dst.  See further the comment and
949  * Example [2] for bitmap_onto() for why and how to use this.
950  */
951 void bitmap_fold(unsigned long *dst, const unsigned long *orig,
952                         unsigned int sz, unsigned int nbits)
953 {
954         unsigned int oldbit;
955
956         if (dst == orig)        /* following doesn't handle inplace mappings */
957                 return;
958         bitmap_zero(dst, nbits);
959
960         for_each_set_bit(oldbit, orig, nbits)
961                 set_bit(oldbit % sz, dst);
962 }
963 EXPORT_SYMBOL(bitmap_fold);
964
965 /*
966  * Common code for bitmap_*_region() routines.
967  *      bitmap: array of unsigned longs corresponding to the bitmap
968  *      pos: the beginning of the region
969  *      order: region size (log base 2 of number of bits)
970  *      reg_op: operation(s) to perform on that region of bitmap
971  *
972  * Can set, verify and/or release a region of bits in a bitmap,
973  * depending on which combination of REG_OP_* flag bits is set.
974  *
975  * A region of a bitmap is a sequence of bits in the bitmap, of
976  * some size '1 << order' (a power of two), aligned to that same
977  * '1 << order' power of two.
978  *
979  * Returns 1 if REG_OP_ISFREE succeeds (region is all zero bits).
980  * Returns 0 in all other cases and reg_ops.
981  */
982
983 enum {
984         REG_OP_ISFREE,          /* true if region is all zero bits */
985         REG_OP_ALLOC,           /* set all bits in region */
986         REG_OP_RELEASE,         /* clear all bits in region */
987 };
988
989 static int __reg_op(unsigned long *bitmap, unsigned int pos, int order, int reg_op)
990 {
991         int nbits_reg;          /* number of bits in region */
992         int index;              /* index first long of region in bitmap */
993         int offset;             /* bit offset region in bitmap[index] */
994         int nlongs_reg;         /* num longs spanned by region in bitmap */
995         int nbitsinlong;        /* num bits of region in each spanned long */
996         unsigned long mask;     /* bitmask for one long of region */
997         int i;                  /* scans bitmap by longs */
998         int ret = 0;            /* return value */
999
1000         /*
1001          * Either nlongs_reg == 1 (for small orders that fit in one long)
1002          * or (offset == 0 && mask == ~0UL) (for larger multiword orders.)
1003          */
1004         nbits_reg = 1 << order;
1005         index = pos / BITS_PER_LONG;
1006         offset = pos - (index * BITS_PER_LONG);
1007         nlongs_reg = BITS_TO_LONGS(nbits_reg);
1008         nbitsinlong = min(nbits_reg,  BITS_PER_LONG);
1009
1010         /*
1011          * Can't do "mask = (1UL << nbitsinlong) - 1", as that
1012          * overflows if nbitsinlong == BITS_PER_LONG.
1013          */
1014         mask = (1UL << (nbitsinlong - 1));
1015         mask += mask - 1;
1016         mask <<= offset;
1017
1018         switch (reg_op) {
1019         case REG_OP_ISFREE:
1020                 for (i = 0; i < nlongs_reg; i++) {
1021                         if (bitmap[index + i] & mask)
1022                                 goto done;
1023                 }
1024                 ret = 1;        /* all bits in region free (zero) */
1025                 break;
1026
1027         case REG_OP_ALLOC:
1028                 for (i = 0; i < nlongs_reg; i++)
1029                         bitmap[index + i] |= mask;
1030                 break;
1031
1032         case REG_OP_RELEASE:
1033                 for (i = 0; i < nlongs_reg; i++)
1034                         bitmap[index + i] &= ~mask;
1035                 break;
1036         }
1037 done:
1038         return ret;
1039 }
1040
1041 /**
1042  * bitmap_find_free_region - find a contiguous aligned mem region
1043  *      @bitmap: array of unsigned longs corresponding to the bitmap
1044  *      @bits: number of bits in the bitmap
1045  *      @order: region size (log base 2 of number of bits) to find
1046  *
1047  * Find a region of free (zero) bits in a @bitmap of @bits bits and
1048  * allocate them (set them to one).  Only consider regions of length
1049  * a power (@order) of two, aligned to that power of two, which
1050  * makes the search algorithm much faster.
1051  *
1052  * Return the bit offset in bitmap of the allocated region,
1053  * or -errno on failure.
1054  */
1055 int bitmap_find_free_region(unsigned long *bitmap, unsigned int bits, int order)
1056 {
1057         unsigned int pos, end;          /* scans bitmap by regions of size order */
1058
1059         for (pos = 0 ; (end = pos + (1U << order)) <= bits; pos = end) {
1060                 if (!__reg_op(bitmap, pos, order, REG_OP_ISFREE))
1061                         continue;
1062                 __reg_op(bitmap, pos, order, REG_OP_ALLOC);
1063                 return pos;
1064         }
1065         return -ENOMEM;
1066 }
1067 EXPORT_SYMBOL(bitmap_find_free_region);
1068
1069 /**
1070  * bitmap_release_region - release allocated bitmap region
1071  *      @bitmap: array of unsigned longs corresponding to the bitmap
1072  *      @pos: beginning of bit region to release
1073  *      @order: region size (log base 2 of number of bits) to release
1074  *
1075  * This is the complement to __bitmap_find_free_region() and releases
1076  * the found region (by clearing it in the bitmap).
1077  *
1078  * No return value.
1079  */
1080 void bitmap_release_region(unsigned long *bitmap, unsigned int pos, int order)
1081 {
1082         __reg_op(bitmap, pos, order, REG_OP_RELEASE);
1083 }
1084 EXPORT_SYMBOL(bitmap_release_region);
1085
1086 /**
1087  * bitmap_allocate_region - allocate bitmap region
1088  *      @bitmap: array of unsigned longs corresponding to the bitmap
1089  *      @pos: beginning of bit region to allocate
1090  *      @order: region size (log base 2 of number of bits) to allocate
1091  *
1092  * Allocate (set bits in) a specified region of a bitmap.
1093  *
1094  * Return 0 on success, or %-EBUSY if specified region wasn't
1095  * free (not all bits were zero).
1096  */
1097 int bitmap_allocate_region(unsigned long *bitmap, unsigned int pos, int order)
1098 {
1099         if (!__reg_op(bitmap, pos, order, REG_OP_ISFREE))
1100                 return -EBUSY;
1101         return __reg_op(bitmap, pos, order, REG_OP_ALLOC);
1102 }
1103 EXPORT_SYMBOL(bitmap_allocate_region);
1104
1105 /**
1106  * bitmap_copy_le - copy a bitmap, putting the bits into little-endian order.
1107  * @dst:   destination buffer
1108  * @src:   bitmap to copy
1109  * @nbits: number of bits in the bitmap
1110  *
1111  * Require nbits % BITS_PER_LONG == 0.
1112  */
1113 #ifdef __BIG_ENDIAN
1114 void bitmap_copy_le(unsigned long *dst, const unsigned long *src, unsigned int nbits)
1115 {
1116         unsigned int i;
1117
1118         for (i = 0; i < nbits/BITS_PER_LONG; i++) {
1119                 if (BITS_PER_LONG == 64)
1120                         dst[i] = cpu_to_le64(src[i]);
1121                 else
1122                         dst[i] = cpu_to_le32(src[i]);
1123         }
1124 }
1125 EXPORT_SYMBOL(bitmap_copy_le);
1126 #endif
1127
1128 #if BITS_PER_LONG == 64
1129 /**
1130  * bitmap_from_arr32 - copy the contents of u32 array of bits to bitmap
1131  *      @bitmap: array of unsigned longs, the destination bitmap
1132  *      @buf: array of u32 (in host byte order), the source bitmap
1133  *      @nbits: number of bits in @bitmap
1134  */
1135 void bitmap_from_arr32(unsigned long *bitmap, const u32 *buf,
1136                                                 unsigned int nbits)
1137 {
1138         unsigned int i, halfwords;
1139
1140         if (!nbits)
1141                 return;
1142
1143         halfwords = DIV_ROUND_UP(nbits, 32);
1144         for (i = 0; i < halfwords; i++) {
1145                 bitmap[i/2] = (unsigned long) buf[i];
1146                 if (++i < halfwords)
1147                         bitmap[i/2] |= ((unsigned long) buf[i]) << 32;
1148         }
1149
1150         /* Clear tail bits in last word beyond nbits. */
1151         if (nbits % BITS_PER_LONG)
1152                 bitmap[(halfwords - 1) / 2] &= BITMAP_LAST_WORD_MASK(nbits);
1153 }
1154 EXPORT_SYMBOL(bitmap_from_arr32);
1155
1156 /**
1157  * bitmap_to_arr32 - copy the contents of bitmap to a u32 array of bits
1158  *      @buf: array of u32 (in host byte order), the dest bitmap
1159  *      @bitmap: array of unsigned longs, the source bitmap
1160  *      @nbits: number of bits in @bitmap
1161  */
1162 void bitmap_to_arr32(u32 *buf, const unsigned long *bitmap, unsigned int nbits)
1163 {
1164         unsigned int i, halfwords;
1165
1166         if (!nbits)
1167                 return;
1168
1169         halfwords = DIV_ROUND_UP(nbits, 32);
1170         for (i = 0; i < halfwords; i++) {
1171                 buf[i] = (u32) (bitmap[i/2] & UINT_MAX);
1172                 if (++i < halfwords)
1173                         buf[i] = (u32) (bitmap[i/2] >> 32);
1174         }
1175
1176         /* Clear tail bits in last element of array beyond nbits. */
1177         if (nbits % BITS_PER_LONG)
1178                 buf[halfwords - 1] &= (u32) (UINT_MAX >> ((-nbits) & 31));
1179 }
1180 EXPORT_SYMBOL(bitmap_to_arr32);
1181
1182 #endif