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