bitmap.c 30 KB

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