/*1* lib/bitmap.c2* Helper functions for bitmap.h.3*4* This source code is licensed under the GNU General Public License,5* Version 2. See the file COPYING for more details.6*/7#include <linux/module.h>8#include <linux/ctype.h>9#include <linux/errno.h>10#include <linux/bitmap.h>11#include <linux/bitops.h>12#include <asm/uaccess.h>1314/*15* bitmaps provide an array of bits, implemented using an an16* array of unsigned longs. The number of valid bits in a17* given bitmap does _not_ need to be an exact multiple of18* BITS_PER_LONG.19*20* The possible unused bits in the last, partially used word21* of a bitmap are 'don't care'. The implementation makes22* no particular effort to keep them zero. It ensures that23* their value will not affect the results of any operation.24* The bitmap operations that return Boolean (bitmap_empty,25* for example) or scalar (bitmap_weight, for example) results26* carefully filter out these unused bits from impacting their27* results.28*29* These operations actually hold to a slightly stronger rule:30* if you don't input any bitmaps to these ops that have some31* unused bits set, then they won't output any set unused bits32* in output bitmaps.33*34* The byte ordering of bitmaps is more natural on little35* endian architectures. See the big-endian headers36* include/asm-ppc64/bitops.h and include/asm-s390/bitops.h37* for the best explanations of this ordering.38*/3940int __bitmap_empty(const unsigned long *bitmap, int bits)41{42int k, lim = bits/BITS_PER_LONG;43for (k = 0; k < lim; ++k)44if (bitmap[k])45return 0;4647if (bits % BITS_PER_LONG)48if (bitmap[k] & BITMAP_LAST_WORD_MASK(bits))49return 0;5051return 1;52}53EXPORT_SYMBOL(__bitmap_empty);5455int __bitmap_full(const unsigned long *bitmap, int bits)56{57int k, lim = bits/BITS_PER_LONG;58for (k = 0; k < lim; ++k)59if (~bitmap[k])60return 0;6162if (bits % BITS_PER_LONG)63if (~bitmap[k] & BITMAP_LAST_WORD_MASK(bits))64return 0;6566return 1;67}68EXPORT_SYMBOL(__bitmap_full);6970int __bitmap_equal(const unsigned long *bitmap1,71const unsigned long *bitmap2, int bits)72{73int k, lim = bits/BITS_PER_LONG;74for (k = 0; k < lim; ++k)75if (bitmap1[k] != bitmap2[k])76return 0;7778if (bits % BITS_PER_LONG)79if ((bitmap1[k] ^ bitmap2[k]) & BITMAP_LAST_WORD_MASK(bits))80return 0;8182return 1;83}84EXPORT_SYMBOL(__bitmap_equal);8586void __bitmap_complement(unsigned long *dst, const unsigned long *src, int bits)87{88int k, lim = bits/BITS_PER_LONG;89for (k = 0; k < lim; ++k)90dst[k] = ~src[k];9192if (bits % BITS_PER_LONG)93dst[k] = ~src[k] & BITMAP_LAST_WORD_MASK(bits);94}95EXPORT_SYMBOL(__bitmap_complement);9697/**98* __bitmap_shift_right - logical right shift of the bits in a bitmap99* @dst : destination bitmap100* @src : source bitmap101* @shift : shift by this many bits102* @bits : bitmap size, in bits103*104* Shifting right (dividing) means moving bits in the MS -> LS bit105* direction. Zeros are fed into the vacated MS positions and the106* LS bits shifted off the bottom are lost.107*/108void __bitmap_shift_right(unsigned long *dst,109const unsigned long *src, int shift, int bits)110{111int k, lim = BITS_TO_LONGS(bits), left = bits % BITS_PER_LONG;112int off = shift/BITS_PER_LONG, rem = shift % BITS_PER_LONG;113unsigned long mask = (1UL << left) - 1;114for (k = 0; off + k < lim; ++k) {115unsigned long upper, lower;116117/*118* If shift is not word aligned, take lower rem bits of119* word above and make them the top rem bits of result.120*/121if (!rem || off + k + 1 >= lim)122upper = 0;123else {124upper = src[off + k + 1];125if (off + k + 1 == lim - 1 && left)126upper &= mask;127}128lower = src[off + k];129if (left && off + k == lim - 1)130lower &= mask;131dst[k] = upper << (BITS_PER_LONG - rem) | lower >> rem;132if (left && k == lim - 1)133dst[k] &= mask;134}135if (off)136memset(&dst[lim - off], 0, off*sizeof(unsigned long));137}138EXPORT_SYMBOL(__bitmap_shift_right);139140141/**142* __bitmap_shift_left - logical left shift of the bits in a bitmap143* @dst : destination bitmap144* @src : source bitmap145* @shift : shift by this many bits146* @bits : bitmap size, in bits147*148* Shifting left (multiplying) means moving bits in the LS -> MS149* direction. Zeros are fed into the vacated LS bit positions150* and those MS bits shifted off the top are lost.151*/152153void __bitmap_shift_left(unsigned long *dst,154const unsigned long *src, int shift, int bits)155{156int k, lim = BITS_TO_LONGS(bits), left = bits % BITS_PER_LONG;157int off = shift/BITS_PER_LONG, rem = shift % BITS_PER_LONG;158for (k = lim - off - 1; k >= 0; --k) {159unsigned long upper, lower;160161/*162* If shift is not word aligned, take upper rem bits of163* word below and make them the bottom rem bits of result.164*/165if (rem && k > 0)166lower = src[k - 1];167else168lower = 0;169upper = src[k];170if (left && k == lim - 1)171upper &= (1UL << left) - 1;172dst[k + off] = lower >> (BITS_PER_LONG - rem) | upper << rem;173if (left && k + off == lim - 1)174dst[k + off] &= (1UL << left) - 1;175}176if (off)177memset(dst, 0, off*sizeof(unsigned long));178}179EXPORT_SYMBOL(__bitmap_shift_left);180181int __bitmap_and(unsigned long *dst, const unsigned long *bitmap1,182const unsigned long *bitmap2, int bits)183{184int k;185int nr = BITS_TO_LONGS(bits);186unsigned long result = 0;187188for (k = 0; k < nr; k++)189result |= (dst[k] = bitmap1[k] & bitmap2[k]);190return result != 0;191}192EXPORT_SYMBOL(__bitmap_and);193194void __bitmap_or(unsigned long *dst, const unsigned long *bitmap1,195const unsigned long *bitmap2, int bits)196{197int k;198int nr = BITS_TO_LONGS(bits);199200for (k = 0; k < nr; k++)201dst[k] = bitmap1[k] | bitmap2[k];202}203EXPORT_SYMBOL(__bitmap_or);204205void __bitmap_xor(unsigned long *dst, const unsigned long *bitmap1,206const unsigned long *bitmap2, int bits)207{208int k;209int nr = BITS_TO_LONGS(bits);210211for (k = 0; k < nr; k++)212dst[k] = bitmap1[k] ^ bitmap2[k];213}214EXPORT_SYMBOL(__bitmap_xor);215216int __bitmap_andnot(unsigned long *dst, const unsigned long *bitmap1,217const unsigned long *bitmap2, int bits)218{219int k;220int nr = BITS_TO_LONGS(bits);221unsigned long result = 0;222223for (k = 0; k < nr; k++)224result |= (dst[k] = bitmap1[k] & ~bitmap2[k]);225return result != 0;226}227EXPORT_SYMBOL(__bitmap_andnot);228229int __bitmap_intersects(const unsigned long *bitmap1,230const unsigned long *bitmap2, int bits)231{232int k, lim = bits/BITS_PER_LONG;233for (k = 0; k < lim; ++k)234if (bitmap1[k] & bitmap2[k])235return 1;236237if (bits % BITS_PER_LONG)238if ((bitmap1[k] & bitmap2[k]) & BITMAP_LAST_WORD_MASK(bits))239return 1;240return 0;241}242EXPORT_SYMBOL(__bitmap_intersects);243244int __bitmap_subset(const unsigned long *bitmap1,245const unsigned long *bitmap2, int bits)246{247int k, lim = bits/BITS_PER_LONG;248for (k = 0; k < lim; ++k)249if (bitmap1[k] & ~bitmap2[k])250return 0;251252if (bits % BITS_PER_LONG)253if ((bitmap1[k] & ~bitmap2[k]) & BITMAP_LAST_WORD_MASK(bits))254return 0;255return 1;256}257EXPORT_SYMBOL(__bitmap_subset);258259int __bitmap_weight(const unsigned long *bitmap, int bits)260{261int k, w = 0, lim = bits/BITS_PER_LONG;262263for (k = 0; k < lim; k++)264w += hweight_long(bitmap[k]);265266if (bits % BITS_PER_LONG)267w += hweight_long(bitmap[k] & BITMAP_LAST_WORD_MASK(bits));268269return w;270}271EXPORT_SYMBOL(__bitmap_weight);272273#define BITMAP_FIRST_WORD_MASK(start) (~0UL << ((start) % BITS_PER_LONG))274275void bitmap_set(unsigned long *map, int start, int nr)276{277unsigned long *p = map + BIT_WORD(start);278const int size = start + nr;279int bits_to_set = BITS_PER_LONG - (start % BITS_PER_LONG);280unsigned long mask_to_set = BITMAP_FIRST_WORD_MASK(start);281282while (nr - bits_to_set >= 0) {283*p |= mask_to_set;284nr -= bits_to_set;285bits_to_set = BITS_PER_LONG;286mask_to_set = ~0UL;287p++;288}289if (nr) {290mask_to_set &= BITMAP_LAST_WORD_MASK(size);291*p |= mask_to_set;292}293}294EXPORT_SYMBOL(bitmap_set);295296void bitmap_clear(unsigned long *map, int start, int nr)297{298unsigned long *p = map + BIT_WORD(start);299const int size = start + nr;300int bits_to_clear = BITS_PER_LONG - (start % BITS_PER_LONG);301unsigned long mask_to_clear = BITMAP_FIRST_WORD_MASK(start);302303while (nr - bits_to_clear >= 0) {304*p &= ~mask_to_clear;305nr -= bits_to_clear;306bits_to_clear = BITS_PER_LONG;307mask_to_clear = ~0UL;308p++;309}310if (nr) {311mask_to_clear &= BITMAP_LAST_WORD_MASK(size);312*p &= ~mask_to_clear;313}314}315EXPORT_SYMBOL(bitmap_clear);316317/*318* bitmap_find_next_zero_area - find a contiguous aligned zero area319* @map: The address to base the search on320* @size: The bitmap size in bits321* @start: The bitnumber to start searching at322* @nr: The number of zeroed bits we're looking for323* @align_mask: Alignment mask for zero area324*325* The @align_mask should be one less than a power of 2; the effect is that326* the bit offset of all zero areas this function finds is multiples of that327* power of 2. A @align_mask of 0 means no alignment is required.328*/329unsigned long bitmap_find_next_zero_area(unsigned long *map,330unsigned long size,331unsigned long start,332unsigned int nr,333unsigned long align_mask)334{335unsigned long index, end, i;336again:337index = find_next_zero_bit(map, size, start);338339/* Align allocation */340index = __ALIGN_MASK(index, align_mask);341342end = index + nr;343if (end > size)344return end;345i = find_next_bit(map, end, index);346if (i < end) {347start = i + 1;348goto again;349}350return index;351}352EXPORT_SYMBOL(bitmap_find_next_zero_area);353354/*355* Bitmap printing & parsing functions: first version by Bill Irwin,356* second version by Paul Jackson, third by Joe Korty.357*/358359#define CHUNKSZ 32360#define nbits_to_hold_value(val) fls(val)361#define BASEDEC 10 /* fancier cpuset lists input in decimal */362363/**364* bitmap_scnprintf - convert bitmap to an ASCII hex string.365* @buf: byte buffer into which string is placed366* @buflen: reserved size of @buf, in bytes367* @maskp: pointer to bitmap to convert368* @nmaskbits: size of bitmap, in bits369*370* Exactly @nmaskbits bits are displayed. Hex digits are grouped into371* comma-separated sets of eight digits per set.372*/373int bitmap_scnprintf(char *buf, unsigned int buflen,374const unsigned long *maskp, int nmaskbits)375{376int i, word, bit, len = 0;377unsigned long val;378const char *sep = "";379int chunksz;380u32 chunkmask;381382chunksz = nmaskbits & (CHUNKSZ - 1);383if (chunksz == 0)384chunksz = CHUNKSZ;385386i = ALIGN(nmaskbits, CHUNKSZ) - CHUNKSZ;387for (; i >= 0; i -= CHUNKSZ) {388chunkmask = ((1ULL << chunksz) - 1);389word = i / BITS_PER_LONG;390bit = i % BITS_PER_LONG;391val = (maskp[word] >> bit) & chunkmask;392len += scnprintf(buf+len, buflen-len, "%s%0*lx", sep,393(chunksz+3)/4, val);394chunksz = CHUNKSZ;395sep = ",";396}397return len;398}399EXPORT_SYMBOL(bitmap_scnprintf);400401/**402* __bitmap_parse - convert an ASCII hex string into a bitmap.403* @buf: pointer to buffer containing string.404* @buflen: buffer size in bytes. If string is smaller than this405* then it must be terminated with a \0.406* @is_user: location of buffer, 0 indicates kernel space407* @maskp: pointer to bitmap array that will contain result.408* @nmaskbits: size of bitmap, in bits.409*410* Commas group hex digits into chunks. Each chunk defines exactly 32411* bits of the resultant bitmask. No chunk may specify a value larger412* than 32 bits (%-EOVERFLOW), and if a chunk specifies a smaller value413* then leading 0-bits are prepended. %-EINVAL is returned for illegal414* characters and for grouping errors such as "1,,5", ",44", "," and "".415* Leading and trailing whitespace accepted, but not embedded whitespace.416*/417int __bitmap_parse(const char *buf, unsigned int buflen,418int is_user, unsigned long *maskp,419int nmaskbits)420{421int c, old_c, totaldigits, ndigits, nchunks, nbits;422u32 chunk;423const char __user *ubuf = buf;424425bitmap_zero(maskp, nmaskbits);426427nchunks = nbits = totaldigits = c = 0;428do {429chunk = ndigits = 0;430431/* Get the next chunk of the bitmap */432while (buflen) {433old_c = c;434if (is_user) {435if (__get_user(c, ubuf++))436return -EFAULT;437}438else439c = *buf++;440buflen--;441if (isspace(c))442continue;443444/*445* If the last character was a space and the current446* character isn't '\0', we've got embedded whitespace.447* This is a no-no, so throw an error.448*/449if (totaldigits && c && isspace(old_c))450return -EINVAL;451452/* A '\0' or a ',' signal the end of the chunk */453if (c == '\0' || c == ',')454break;455456if (!isxdigit(c))457return -EINVAL;458459/*460* Make sure there are at least 4 free bits in 'chunk'.461* If not, this hexdigit will overflow 'chunk', so462* throw an error.463*/464if (chunk & ~((1UL << (CHUNKSZ - 4)) - 1))465return -EOVERFLOW;466467chunk = (chunk << 4) | hex_to_bin(c);468ndigits++; totaldigits++;469}470if (ndigits == 0)471return -EINVAL;472if (nchunks == 0 && chunk == 0)473continue;474475__bitmap_shift_left(maskp, maskp, CHUNKSZ, nmaskbits);476*maskp |= chunk;477nchunks++;478nbits += (nchunks == 1) ? nbits_to_hold_value(chunk) : CHUNKSZ;479if (nbits > nmaskbits)480return -EOVERFLOW;481} while (buflen && c == ',');482483return 0;484}485EXPORT_SYMBOL(__bitmap_parse);486487/**488* bitmap_parse_user - convert an ASCII hex string in a user buffer into a bitmap489*490* @ubuf: pointer to user buffer containing string.491* @ulen: buffer size in bytes. If string is smaller than this492* then it must be terminated with a \0.493* @maskp: pointer to bitmap array that will contain result.494* @nmaskbits: size of bitmap, in bits.495*496* Wrapper for __bitmap_parse(), providing it with user buffer.497*498* We cannot have this as an inline function in bitmap.h because it needs499* linux/uaccess.h to get the access_ok() declaration and this causes500* cyclic dependencies.501*/502int bitmap_parse_user(const char __user *ubuf,503unsigned int ulen, unsigned long *maskp,504int nmaskbits)505{506if (!access_ok(VERIFY_READ, ubuf, ulen))507return -EFAULT;508return __bitmap_parse((const char *)ubuf, ulen, 1, maskp, nmaskbits);509}510EXPORT_SYMBOL(bitmap_parse_user);511512/*513* bscnl_emit(buf, buflen, rbot, rtop, bp)514*515* Helper routine for bitmap_scnlistprintf(). Write decimal number516* or range to buf, suppressing output past buf+buflen, with optional517* comma-prefix. Return len of what would be written to buf, if it518* all fit.519*/520static inline int bscnl_emit(char *buf, int buflen, int rbot, int rtop, int len)521{522if (len > 0)523len += scnprintf(buf + len, buflen - len, ",");524if (rbot == rtop)525len += scnprintf(buf + len, buflen - len, "%d", rbot);526else527len += scnprintf(buf + len, buflen - len, "%d-%d", rbot, rtop);528return len;529}530531/**532* bitmap_scnlistprintf - convert bitmap to list format ASCII string533* @buf: byte buffer into which string is placed534* @buflen: reserved size of @buf, in bytes535* @maskp: pointer to bitmap to convert536* @nmaskbits: size of bitmap, in bits537*538* Output format is a comma-separated list of decimal numbers and539* ranges. Consecutively set bits are shown as two hyphen-separated540* decimal numbers, the smallest and largest bit numbers set in541* the range. Output format is compatible with the format542* accepted as input by bitmap_parselist().543*544* The return value is the number of characters which would be545* generated for the given input, excluding the trailing '\0', as546* per ISO C99.547*/548int bitmap_scnlistprintf(char *buf, unsigned int buflen,549const unsigned long *maskp, int nmaskbits)550{551int len = 0;552/* current bit is 'cur', most recently seen range is [rbot, rtop] */553int cur, rbot, rtop;554555if (buflen == 0)556return 0;557buf[0] = 0;558559rbot = cur = find_first_bit(maskp, nmaskbits);560while (cur < nmaskbits) {561rtop = cur;562cur = find_next_bit(maskp, nmaskbits, cur+1);563if (cur >= nmaskbits || cur > rtop + 1) {564len = bscnl_emit(buf, buflen, rbot, rtop, len);565rbot = cur;566}567}568return len;569}570EXPORT_SYMBOL(bitmap_scnlistprintf);571572/**573* __bitmap_parselist - convert list format ASCII string to bitmap574* @buf: read nul-terminated user string from this buffer575* @buflen: buffer size in bytes. If string is smaller than this576* then it must be terminated with a \0.577* @is_user: location of buffer, 0 indicates kernel space578* @maskp: write resulting mask here579* @nmaskbits: number of bits in mask to be written580*581* Input format is a comma-separated list of decimal numbers and582* ranges. Consecutively set bits are shown as two hyphen-separated583* decimal numbers, the smallest and largest bit numbers set in584* the range.585*586* Returns 0 on success, -errno on invalid input strings.587* Error values:588* %-EINVAL: second number in range smaller than first589* %-EINVAL: invalid character in string590* %-ERANGE: bit number specified too large for mask591*/592static int __bitmap_parselist(const char *buf, unsigned int buflen,593int is_user, unsigned long *maskp,594int nmaskbits)595{596unsigned a, b;597int c, old_c, totaldigits;598const char __user *ubuf = buf;599int exp_digit, in_range;600601totaldigits = c = 0;602bitmap_zero(maskp, nmaskbits);603do {604exp_digit = 1;605in_range = 0;606a = b = 0;607608/* Get the next cpu# or a range of cpu#'s */609while (buflen) {610old_c = c;611if (is_user) {612if (__get_user(c, ubuf++))613return -EFAULT;614} else615c = *buf++;616buflen--;617if (isspace(c))618continue;619620/*621* If the last character was a space and the current622* character isn't '\0', we've got embedded whitespace.623* This is a no-no, so throw an error.624*/625if (totaldigits && c && isspace(old_c))626return -EINVAL;627628/* A '\0' or a ',' signal the end of a cpu# or range */629if (c == '\0' || c == ',')630break;631632if (c == '-') {633if (exp_digit || in_range)634return -EINVAL;635b = 0;636in_range = 1;637exp_digit = 1;638continue;639}640641if (!isdigit(c))642return -EINVAL;643644b = b * 10 + (c - '0');645if (!in_range)646a = b;647exp_digit = 0;648totaldigits++;649}650if (!(a <= b))651return -EINVAL;652if (b >= nmaskbits)653return -ERANGE;654while (a <= b) {655set_bit(a, maskp);656a++;657}658} while (buflen && c == ',');659return 0;660}661662int bitmap_parselist(const char *bp, unsigned long *maskp, int nmaskbits)663{664char *nl = strchr(bp, '\n');665int len;666667if (nl)668len = nl - bp;669else670len = strlen(bp);671672return __bitmap_parselist(bp, len, 0, maskp, nmaskbits);673}674EXPORT_SYMBOL(bitmap_parselist);675676677/**678* bitmap_parselist_user()679*680* @ubuf: pointer to user buffer containing string.681* @ulen: buffer size in bytes. If string is smaller than this682* then it must be terminated with a \0.683* @maskp: pointer to bitmap array that will contain result.684* @nmaskbits: size of bitmap, in bits.685*686* Wrapper for bitmap_parselist(), providing it with user buffer.687*688* We cannot have this as an inline function in bitmap.h because it needs689* linux/uaccess.h to get the access_ok() declaration and this causes690* cyclic dependencies.691*/692int bitmap_parselist_user(const char __user *ubuf,693unsigned int ulen, unsigned long *maskp,694int nmaskbits)695{696if (!access_ok(VERIFY_READ, ubuf, ulen))697return -EFAULT;698return __bitmap_parselist((const char *)ubuf,699ulen, 1, maskp, nmaskbits);700}701EXPORT_SYMBOL(bitmap_parselist_user);702703704/**705* bitmap_pos_to_ord - find ordinal of set bit at given position in bitmap706* @buf: pointer to a bitmap707* @pos: a bit position in @buf (0 <= @pos < @bits)708* @bits: number of valid bit positions in @buf709*710* Map the bit at position @pos in @buf (of length @bits) to the711* ordinal of which set bit it is. If it is not set or if @pos712* is not a valid bit position, map to -1.713*714* If for example, just bits 4 through 7 are set in @buf, then @pos715* values 4 through 7 will get mapped to 0 through 3, respectively,716* and other @pos values will get mapped to 0. When @pos value 7717* gets mapped to (returns) @ord value 3 in this example, that means718* that bit 7 is the 3rd (starting with 0th) set bit in @buf.719*720* The bit positions 0 through @bits are valid positions in @buf.721*/722static int bitmap_pos_to_ord(const unsigned long *buf, int pos, int bits)723{724int i, ord;725726if (pos < 0 || pos >= bits || !test_bit(pos, buf))727return -1;728729i = find_first_bit(buf, bits);730ord = 0;731while (i < pos) {732i = find_next_bit(buf, bits, i + 1);733ord++;734}735BUG_ON(i != pos);736737return ord;738}739740/**741* bitmap_ord_to_pos - find position of n-th set bit in bitmap742* @buf: pointer to bitmap743* @ord: ordinal bit position (n-th set bit, n >= 0)744* @bits: number of valid bit positions in @buf745*746* Map the ordinal offset of bit @ord in @buf to its position in @buf.747* Value of @ord should be in range 0 <= @ord < weight(buf), else748* results are undefined.749*750* If for example, just bits 4 through 7 are set in @buf, then @ord751* values 0 through 3 will get mapped to 4 through 7, respectively,752* and all other @ord values return undefined values. When @ord value 3753* gets mapped to (returns) @pos value 7 in this example, that means754* that the 3rd set bit (starting with 0th) is at position 7 in @buf.755*756* The bit positions 0 through @bits are valid positions in @buf.757*/758static int bitmap_ord_to_pos(const unsigned long *buf, int ord, int bits)759{760int pos = 0;761762if (ord >= 0 && ord < bits) {763int i;764765for (i = find_first_bit(buf, bits);766i < bits && ord > 0;767i = find_next_bit(buf, bits, i + 1))768ord--;769if (i < bits && ord == 0)770pos = i;771}772773return pos;774}775776/**777* bitmap_remap - Apply map defined by a pair of bitmaps to another bitmap778* @dst: remapped result779* @src: subset to be remapped780* @old: defines domain of map781* @new: defines range of map782* @bits: number of bits in each of these bitmaps783*784* Let @old and @new define a mapping of bit positions, such that785* whatever position is held by the n-th set bit in @old is mapped786* to the n-th set bit in @new. In the more general case, allowing787* for the possibility that the weight 'w' of @new is less than the788* weight of @old, map the position of the n-th set bit in @old to789* the position of the m-th set bit in @new, where m == n % w.790*791* If either of the @old and @new bitmaps are empty, or if @src and792* @dst point to the same location, then this routine copies @src793* to @dst.794*795* The positions of unset bits in @old are mapped to themselves796* (the identify map).797*798* Apply the above specified mapping to @src, placing the result in799* @dst, clearing any bits previously set in @dst.800*801* For example, lets say that @old has bits 4 through 7 set, and802* @new has bits 12 through 15 set. This defines the mapping of bit803* position 4 to 12, 5 to 13, 6 to 14 and 7 to 15, and of all other804* bit positions unchanged. So if say @src comes into this routine805* with bits 1, 5 and 7 set, then @dst should leave with bits 1,806* 13 and 15 set.807*/808void bitmap_remap(unsigned long *dst, const unsigned long *src,809const unsigned long *old, const unsigned long *new,810int bits)811{812int oldbit, w;813814if (dst == src) /* following doesn't handle inplace remaps */815return;816bitmap_zero(dst, bits);817818w = bitmap_weight(new, bits);819for_each_set_bit(oldbit, src, bits) {820int n = bitmap_pos_to_ord(old, oldbit, bits);821822if (n < 0 || w == 0)823set_bit(oldbit, dst); /* identity map */824else825set_bit(bitmap_ord_to_pos(new, n % w, bits), dst);826}827}828EXPORT_SYMBOL(bitmap_remap);829830/**831* bitmap_bitremap - Apply map defined by a pair of bitmaps to a single bit832* @oldbit: bit position to be mapped833* @old: defines domain of map834* @new: defines range of map835* @bits: number of bits in each of these bitmaps836*837* Let @old and @new define a mapping of bit positions, such that838* whatever position is held by the n-th set bit in @old is mapped839* to the n-th set bit in @new. In the more general case, allowing840* for the possibility that the weight 'w' of @new is less than the841* weight of @old, map the position of the n-th set bit in @old to842* the position of the m-th set bit in @new, where m == n % w.843*844* The positions of unset bits in @old are mapped to themselves845* (the identify map).846*847* Apply the above specified mapping to bit position @oldbit, returning848* the new bit position.849*850* For example, lets say that @old has bits 4 through 7 set, and851* @new has bits 12 through 15 set. This defines the mapping of bit852* position 4 to 12, 5 to 13, 6 to 14 and 7 to 15, and of all other853* bit positions unchanged. So if say @oldbit is 5, then this routine854* returns 13.855*/856int bitmap_bitremap(int oldbit, const unsigned long *old,857const unsigned long *new, int bits)858{859int w = bitmap_weight(new, bits);860int n = bitmap_pos_to_ord(old, oldbit, bits);861if (n < 0 || w == 0)862return oldbit;863else864return bitmap_ord_to_pos(new, n % w, bits);865}866EXPORT_SYMBOL(bitmap_bitremap);867868/**869* bitmap_onto - translate one bitmap relative to another870* @dst: resulting translated bitmap871* @orig: original untranslated bitmap872* @relmap: bitmap relative to which translated873* @bits: number of bits in each of these bitmaps874*875* Set the n-th bit of @dst iff there exists some m such that the876* n-th bit of @relmap is set, the m-th bit of @orig is set, and877* the n-th bit of @relmap is also the m-th _set_ bit of @relmap.878* (If you understood the previous sentence the first time your879* read it, you're overqualified for your current job.)880*881* In other words, @orig is mapped onto (surjectively) @dst,882* using the the map { <n, m> | the n-th bit of @relmap is the883* m-th set bit of @relmap }.884*885* Any set bits in @orig above bit number W, where W is the886* weight of (number of set bits in) @relmap are mapped nowhere.887* In particular, if for all bits m set in @orig, m >= W, then888* @dst will end up empty. In situations where the possibility889* of such an empty result is not desired, one way to avoid it is890* to use the bitmap_fold() operator, below, to first fold the891* @orig bitmap over itself so that all its set bits x are in the892* range 0 <= x < W. The bitmap_fold() operator does this by893* setting the bit (m % W) in @dst, for each bit (m) set in @orig.894*895* Example [1] for bitmap_onto():896* Let's say @relmap has bits 30-39 set, and @orig has bits897* 1, 3, 5, 7, 9 and 11 set. Then on return from this routine,898* @dst will have bits 31, 33, 35, 37 and 39 set.899*900* When bit 0 is set in @orig, it means turn on the bit in901* @dst corresponding to whatever is the first bit (if any)902* that is turned on in @relmap. Since bit 0 was off in the903* above example, we leave off that bit (bit 30) in @dst.904*905* When bit 1 is set in @orig (as in the above example), it906* means turn on the bit in @dst corresponding to whatever907* is the second bit that is turned on in @relmap. The second908* bit in @relmap that was turned on in the above example was909* bit 31, so we turned on bit 31 in @dst.910*911* Similarly, we turned on bits 33, 35, 37 and 39 in @dst,912* because they were the 4th, 6th, 8th and 10th set bits913* set in @relmap, and the 4th, 6th, 8th and 10th bits of914* @orig (i.e. bits 3, 5, 7 and 9) were also set.915*916* When bit 11 is set in @orig, it means turn on the bit in917* @dst corresponding to whatever is the twelfth bit that is918* turned on in @relmap. In the above example, there were919* only ten bits turned on in @relmap (30..39), so that bit920* 11 was set in @orig had no affect on @dst.921*922* Example [2] for bitmap_fold() + bitmap_onto():923* Let's say @relmap has these ten bits set:924* 40 41 42 43 45 48 53 61 74 95925* (for the curious, that's 40 plus the first ten terms of the926* Fibonacci sequence.)927*928* Further lets say we use the following code, invoking929* bitmap_fold() then bitmap_onto, as suggested above to930* avoid the possitility of an empty @dst result:931*932* unsigned long *tmp; // a temporary bitmap's bits933*934* bitmap_fold(tmp, orig, bitmap_weight(relmap, bits), bits);935* bitmap_onto(dst, tmp, relmap, bits);936*937* Then this table shows what various values of @dst would be, for938* various @orig's. I list the zero-based positions of each set bit.939* The tmp column shows the intermediate result, as computed by940* using bitmap_fold() to fold the @orig bitmap modulo ten941* (the weight of @relmap).942*943* @orig tmp @dst944* 0 0 40945* 1 1 41946* 9 9 95947* 10 0 40 (*)948* 1 3 5 7 1 3 5 7 41 43 48 61949* 0 1 2 3 4 0 1 2 3 4 40 41 42 43 45950* 0 9 18 27 0 9 8 7 40 61 74 95951* 0 10 20 30 0 40952* 0 11 22 33 0 1 2 3 40 41 42 43953* 0 12 24 36 0 2 4 6 40 42 45 53954* 78 102 211 1 2 8 41 42 74 (*)955*956* (*) For these marked lines, if we hadn't first done bitmap_fold()957* into tmp, then the @dst result would have been empty.958*959* If either of @orig or @relmap is empty (no set bits), then @dst960* will be returned empty.961*962* If (as explained above) the only set bits in @orig are in positions963* m where m >= W, (where W is the weight of @relmap) then @dst will964* once again be returned empty.965*966* All bits in @dst not set by the above rule are cleared.967*/968void bitmap_onto(unsigned long *dst, const unsigned long *orig,969const unsigned long *relmap, int bits)970{971int n, m; /* same meaning as in above comment */972973if (dst == orig) /* following doesn't handle inplace mappings */974return;975bitmap_zero(dst, bits);976977/*978* The following code is a more efficient, but less979* obvious, equivalent to the loop:980* for (m = 0; m < bitmap_weight(relmap, bits); m++) {981* n = bitmap_ord_to_pos(orig, m, bits);982* if (test_bit(m, orig))983* set_bit(n, dst);984* }985*/986987m = 0;988for_each_set_bit(n, relmap, bits) {989/* m == bitmap_pos_to_ord(relmap, n, bits) */990if (test_bit(m, orig))991set_bit(n, dst);992m++;993}994}995EXPORT_SYMBOL(bitmap_onto);996997/**998* bitmap_fold - fold larger bitmap into smaller, modulo specified size999* @dst: resulting smaller bitmap1000* @orig: original larger bitmap1001* @sz: specified size1002* @bits: number of bits in each of these bitmaps1003*1004* For each bit oldbit in @orig, set bit oldbit mod @sz in @dst.1005* Clear all other bits in @dst. See further the comment and1006* Example [2] for bitmap_onto() for why and how to use this.1007*/1008void bitmap_fold(unsigned long *dst, const unsigned long *orig,1009int sz, int bits)1010{1011int oldbit;10121013if (dst == orig) /* following doesn't handle inplace mappings */1014return;1015bitmap_zero(dst, bits);10161017for_each_set_bit(oldbit, orig, bits)1018set_bit(oldbit % sz, dst);1019}1020EXPORT_SYMBOL(bitmap_fold);10211022/*1023* Common code for bitmap_*_region() routines.1024* bitmap: array of unsigned longs corresponding to the bitmap1025* pos: the beginning of the region1026* order: region size (log base 2 of number of bits)1027* reg_op: operation(s) to perform on that region of bitmap1028*1029* Can set, verify and/or release a region of bits in a bitmap,1030* depending on which combination of REG_OP_* flag bits is set.1031*1032* A region of a bitmap is a sequence of bits in the bitmap, of1033* some size '1 << order' (a power of two), aligned to that same1034* '1 << order' power of two.1035*1036* Returns 1 if REG_OP_ISFREE succeeds (region is all zero bits).1037* Returns 0 in all other cases and reg_ops.1038*/10391040enum {1041REG_OP_ISFREE, /* true if region is all zero bits */1042REG_OP_ALLOC, /* set all bits in region */1043REG_OP_RELEASE, /* clear all bits in region */1044};10451046static int __reg_op(unsigned long *bitmap, int pos, int order, int reg_op)1047{1048int nbits_reg; /* number of bits in region */1049int index; /* index first long of region in bitmap */1050int offset; /* bit offset region in bitmap[index] */1051int nlongs_reg; /* num longs spanned by region in bitmap */1052int nbitsinlong; /* num bits of region in each spanned long */1053unsigned long mask; /* bitmask for one long of region */1054int i; /* scans bitmap by longs */1055int ret = 0; /* return value */10561057/*1058* Either nlongs_reg == 1 (for small orders that fit in one long)1059* or (offset == 0 && mask == ~0UL) (for larger multiword orders.)1060*/1061nbits_reg = 1 << order;1062index = pos / BITS_PER_LONG;1063offset = pos - (index * BITS_PER_LONG);1064nlongs_reg = BITS_TO_LONGS(nbits_reg);1065nbitsinlong = min(nbits_reg, BITS_PER_LONG);10661067/*1068* Can't do "mask = (1UL << nbitsinlong) - 1", as that1069* overflows if nbitsinlong == BITS_PER_LONG.1070*/1071mask = (1UL << (nbitsinlong - 1));1072mask += mask - 1;1073mask <<= offset;10741075switch (reg_op) {1076case REG_OP_ISFREE:1077for (i = 0; i < nlongs_reg; i++) {1078if (bitmap[index + i] & mask)1079goto done;1080}1081ret = 1; /* all bits in region free (zero) */1082break;10831084case REG_OP_ALLOC:1085for (i = 0; i < nlongs_reg; i++)1086bitmap[index + i] |= mask;1087break;10881089case REG_OP_RELEASE:1090for (i = 0; i < nlongs_reg; i++)1091bitmap[index + i] &= ~mask;1092break;1093}1094done:1095return ret;1096}10971098/**1099* bitmap_find_free_region - find a contiguous aligned mem region1100* @bitmap: array of unsigned longs corresponding to the bitmap1101* @bits: number of bits in the bitmap1102* @order: region size (log base 2 of number of bits) to find1103*1104* Find a region of free (zero) bits in a @bitmap of @bits bits and1105* allocate them (set them to one). Only consider regions of length1106* a power (@order) of two, aligned to that power of two, which1107* makes the search algorithm much faster.1108*1109* Return the bit offset in bitmap of the allocated region,1110* or -errno on failure.1111*/1112int bitmap_find_free_region(unsigned long *bitmap, int bits, int order)1113{1114int pos, end; /* scans bitmap by regions of size order */11151116for (pos = 0 ; (end = pos + (1 << order)) <= bits; pos = end) {1117if (!__reg_op(bitmap, pos, order, REG_OP_ISFREE))1118continue;1119__reg_op(bitmap, pos, order, REG_OP_ALLOC);1120return pos;1121}1122return -ENOMEM;1123}1124EXPORT_SYMBOL(bitmap_find_free_region);11251126/**1127* bitmap_release_region - release allocated bitmap region1128* @bitmap: array of unsigned longs corresponding to the bitmap1129* @pos: beginning of bit region to release1130* @order: region size (log base 2 of number of bits) to release1131*1132* This is the complement to __bitmap_find_free_region() and releases1133* the found region (by clearing it in the bitmap).1134*1135* No return value.1136*/1137void bitmap_release_region(unsigned long *bitmap, int pos, int order)1138{1139__reg_op(bitmap, pos, order, REG_OP_RELEASE);1140}1141EXPORT_SYMBOL(bitmap_release_region);11421143/**1144* bitmap_allocate_region - allocate bitmap region1145* @bitmap: array of unsigned longs corresponding to the bitmap1146* @pos: beginning of bit region to allocate1147* @order: region size (log base 2 of number of bits) to allocate1148*1149* Allocate (set bits in) a specified region of a bitmap.1150*1151* Return 0 on success, or %-EBUSY if specified region wasn't1152* free (not all bits were zero).1153*/1154int bitmap_allocate_region(unsigned long *bitmap, int pos, int order)1155{1156if (!__reg_op(bitmap, pos, order, REG_OP_ISFREE))1157return -EBUSY;1158__reg_op(bitmap, pos, order, REG_OP_ALLOC);1159return 0;1160}1161EXPORT_SYMBOL(bitmap_allocate_region);11621163/**1164* bitmap_copy_le - copy a bitmap, putting the bits into little-endian order.1165* @dst: destination buffer1166* @src: bitmap to copy1167* @nbits: number of bits in the bitmap1168*1169* Require nbits % BITS_PER_LONG == 0.1170*/1171void bitmap_copy_le(void *dst, const unsigned long *src, int nbits)1172{1173unsigned long *d = dst;1174int i;11751176for (i = 0; i < nbits/BITS_PER_LONG; i++) {1177if (BITS_PER_LONG == 64)1178d[i] = cpu_to_le64(src[i]);1179else1180d[i] = cpu_to_le32(src[i]);1181}1182}1183EXPORT_SYMBOL(bitmap_copy_le);118411851186