bitmap.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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. * @nbits - 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. * @nbits - 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. #if BITS_PER_LONG == 32
  226. int __bitmap_weight(const unsigned long *bitmap, int bits)
  227. {
  228. int k, w = 0, lim = bits/BITS_PER_LONG;
  229. for (k = 0; k < lim; k++)
  230. w += hweight32(bitmap[k]);
  231. if (bits % BITS_PER_LONG)
  232. w += hweight32(bitmap[k] & BITMAP_LAST_WORD_MASK(bits));
  233. return w;
  234. }
  235. #else
  236. int __bitmap_weight(const unsigned long *bitmap, int bits)
  237. {
  238. int k, w = 0, lim = bits/BITS_PER_LONG;
  239. for (k = 0; k < lim; k++)
  240. w += hweight64(bitmap[k]);
  241. if (bits % BITS_PER_LONG)
  242. w += hweight64(bitmap[k] & BITMAP_LAST_WORD_MASK(bits));
  243. return w;
  244. }
  245. #endif
  246. EXPORT_SYMBOL(__bitmap_weight);
  247. /*
  248. * Bitmap printing & parsing functions: first version by Bill Irwin,
  249. * second version by Paul Jackson, third by Joe Korty.
  250. */
  251. #define CHUNKSZ 32
  252. #define nbits_to_hold_value(val) fls(val)
  253. #define roundup_power2(val,modulus) (((val) + (modulus) - 1) & ~((modulus) - 1))
  254. #define unhex(c) (isdigit(c) ? (c - '0') : (toupper(c) - 'A' + 10))
  255. #define BASEDEC 10 /* fancier cpuset lists input in decimal */
  256. /**
  257. * bitmap_scnprintf - convert bitmap to an ASCII hex string.
  258. * @buf: byte buffer into which string is placed
  259. * @buflen: reserved size of @buf, in bytes
  260. * @maskp: pointer to bitmap to convert
  261. * @nmaskbits: size of bitmap, in bits
  262. *
  263. * Exactly @nmaskbits bits are displayed. Hex digits are grouped into
  264. * comma-separated sets of eight digits per set.
  265. */
  266. int bitmap_scnprintf(char *buf, unsigned int buflen,
  267. const unsigned long *maskp, int nmaskbits)
  268. {
  269. int i, word, bit, len = 0;
  270. unsigned long val;
  271. const char *sep = "";
  272. int chunksz;
  273. u32 chunkmask;
  274. chunksz = nmaskbits & (CHUNKSZ - 1);
  275. if (chunksz == 0)
  276. chunksz = CHUNKSZ;
  277. i = roundup_power2(nmaskbits, CHUNKSZ) - CHUNKSZ;
  278. for (; i >= 0; i -= CHUNKSZ) {
  279. chunkmask = ((1ULL << chunksz) - 1);
  280. word = i / BITS_PER_LONG;
  281. bit = i % BITS_PER_LONG;
  282. val = (maskp[word] >> bit) & chunkmask;
  283. len += scnprintf(buf+len, buflen-len, "%s%0*lx", sep,
  284. (chunksz+3)/4, val);
  285. chunksz = CHUNKSZ;
  286. sep = ",";
  287. }
  288. return len;
  289. }
  290. EXPORT_SYMBOL(bitmap_scnprintf);
  291. /**
  292. * bitmap_parse - convert an ASCII hex string into a bitmap.
  293. * @buf: pointer to buffer in user space containing string.
  294. * @buflen: buffer size in bytes. If string is smaller than this
  295. * then it must be terminated with a \0.
  296. * @maskp: pointer to bitmap array that will contain result.
  297. * @nmaskbits: size of bitmap, in bits.
  298. *
  299. * Commas group hex digits into chunks. Each chunk defines exactly 32
  300. * bits of the resultant bitmask. No chunk may specify a value larger
  301. * than 32 bits (-EOVERFLOW), and if a chunk specifies a smaller value
  302. * then leading 0-bits are prepended. -EINVAL is returned for illegal
  303. * characters and for grouping errors such as "1,,5", ",44", "," and "".
  304. * Leading and trailing whitespace accepted, but not embedded whitespace.
  305. */
  306. int bitmap_parse(const char __user *ubuf, unsigned int ubuflen,
  307. unsigned long *maskp, int nmaskbits)
  308. {
  309. int c, old_c, totaldigits, ndigits, nchunks, nbits;
  310. u32 chunk;
  311. bitmap_zero(maskp, nmaskbits);
  312. nchunks = nbits = totaldigits = c = 0;
  313. do {
  314. chunk = ndigits = 0;
  315. /* Get the next chunk of the bitmap */
  316. while (ubuflen) {
  317. old_c = c;
  318. if (get_user(c, ubuf++))
  319. return -EFAULT;
  320. ubuflen--;
  321. if (isspace(c))
  322. continue;
  323. /*
  324. * If the last character was a space and the current
  325. * character isn't '\0', we've got embedded whitespace.
  326. * This is a no-no, so throw an error.
  327. */
  328. if (totaldigits && c && isspace(old_c))
  329. return -EINVAL;
  330. /* A '\0' or a ',' signal the end of the chunk */
  331. if (c == '\0' || c == ',')
  332. break;
  333. if (!isxdigit(c))
  334. return -EINVAL;
  335. /*
  336. * Make sure there are at least 4 free bits in 'chunk'.
  337. * If not, this hexdigit will overflow 'chunk', so
  338. * throw an error.
  339. */
  340. if (chunk & ~((1UL << (CHUNKSZ - 4)) - 1))
  341. return -EOVERFLOW;
  342. chunk = (chunk << 4) | unhex(c);
  343. ndigits++; totaldigits++;
  344. }
  345. if (ndigits == 0)
  346. return -EINVAL;
  347. if (nchunks == 0 && chunk == 0)
  348. continue;
  349. __bitmap_shift_left(maskp, maskp, CHUNKSZ, nmaskbits);
  350. *maskp |= chunk;
  351. nchunks++;
  352. nbits += (nchunks == 1) ? nbits_to_hold_value(chunk) : CHUNKSZ;
  353. if (nbits > nmaskbits)
  354. return -EOVERFLOW;
  355. } while (ubuflen && c == ',');
  356. return 0;
  357. }
  358. EXPORT_SYMBOL(bitmap_parse);
  359. /*
  360. * bscnl_emit(buf, buflen, rbot, rtop, bp)
  361. *
  362. * Helper routine for bitmap_scnlistprintf(). Write decimal number
  363. * or range to buf, suppressing output past buf+buflen, with optional
  364. * comma-prefix. Return len of what would be written to buf, if it
  365. * all fit.
  366. */
  367. static inline int bscnl_emit(char *buf, int buflen, int rbot, int rtop, int len)
  368. {
  369. if (len > 0)
  370. len += scnprintf(buf + len, buflen - len, ",");
  371. if (rbot == rtop)
  372. len += scnprintf(buf + len, buflen - len, "%d", rbot);
  373. else
  374. len += scnprintf(buf + len, buflen - len, "%d-%d", rbot, rtop);
  375. return len;
  376. }
  377. /**
  378. * bitmap_scnlistprintf - convert bitmap to list format ASCII string
  379. * @buf: byte buffer into which string is placed
  380. * @buflen: reserved size of @buf, in bytes
  381. * @maskp: pointer to bitmap to convert
  382. * @nmaskbits: size of bitmap, in bits
  383. *
  384. * Output format is a comma-separated list of decimal numbers and
  385. * ranges. Consecutively set bits are shown as two hyphen-separated
  386. * decimal numbers, the smallest and largest bit numbers set in
  387. * the range. Output format is compatible with the format
  388. * accepted as input by bitmap_parselist().
  389. *
  390. * The return value is the number of characters which would be
  391. * generated for the given input, excluding the trailing '\0', as
  392. * per ISO C99.
  393. */
  394. int bitmap_scnlistprintf(char *buf, unsigned int buflen,
  395. const unsigned long *maskp, int nmaskbits)
  396. {
  397. int len = 0;
  398. /* current bit is 'cur', most recently seen range is [rbot, rtop] */
  399. int cur, rbot, rtop;
  400. rbot = cur = find_first_bit(maskp, nmaskbits);
  401. while (cur < nmaskbits) {
  402. rtop = cur;
  403. cur = find_next_bit(maskp, nmaskbits, cur+1);
  404. if (cur >= nmaskbits || cur > rtop + 1) {
  405. len = bscnl_emit(buf, buflen, rbot, rtop, len);
  406. rbot = cur;
  407. }
  408. }
  409. return len;
  410. }
  411. EXPORT_SYMBOL(bitmap_scnlistprintf);
  412. /**
  413. * bitmap_parselist - convert list format ASCII string to bitmap
  414. * @buf: read nul-terminated user string from this buffer
  415. * @mask: write resulting mask here
  416. * @nmaskbits: number of bits in mask to be written
  417. *
  418. * Input format is a comma-separated list of decimal numbers and
  419. * ranges. Consecutively set bits are shown as two hyphen-separated
  420. * decimal numbers, the smallest and largest bit numbers set in
  421. * the range.
  422. *
  423. * Returns 0 on success, -errno on invalid input strings:
  424. * -EINVAL: second number in range smaller than first
  425. * -EINVAL: invalid character in string
  426. * -ERANGE: bit number specified too large for mask
  427. */
  428. int bitmap_parselist(const char *bp, unsigned long *maskp, int nmaskbits)
  429. {
  430. unsigned a, b;
  431. bitmap_zero(maskp, nmaskbits);
  432. do {
  433. if (!isdigit(*bp))
  434. return -EINVAL;
  435. b = a = simple_strtoul(bp, (char **)&bp, BASEDEC);
  436. if (*bp == '-') {
  437. bp++;
  438. if (!isdigit(*bp))
  439. return -EINVAL;
  440. b = simple_strtoul(bp, (char **)&bp, BASEDEC);
  441. }
  442. if (!(a <= b))
  443. return -EINVAL;
  444. if (b >= nmaskbits)
  445. return -ERANGE;
  446. while (a <= b) {
  447. set_bit(a, maskp);
  448. a++;
  449. }
  450. if (*bp == ',')
  451. bp++;
  452. } while (*bp != '\0' && *bp != '\n');
  453. return 0;
  454. }
  455. EXPORT_SYMBOL(bitmap_parselist);
  456. /**
  457. * bitmap_find_free_region - find a contiguous aligned mem region
  458. * @bitmap: an array of unsigned longs corresponding to the bitmap
  459. * @bits: number of bits in the bitmap
  460. * @order: region size to find (size is actually 1<<order)
  461. *
  462. * This is used to allocate a memory region from a bitmap. The idea is
  463. * that the region has to be 1<<order sized and 1<<order aligned (this
  464. * makes the search algorithm much faster).
  465. *
  466. * The region is marked as set bits in the bitmap if a free one is
  467. * found.
  468. *
  469. * Returns either beginning of region or negative error
  470. */
  471. int bitmap_find_free_region(unsigned long *bitmap, int bits, int order)
  472. {
  473. unsigned long mask;
  474. int pages = 1 << order;
  475. int i;
  476. if(pages > BITS_PER_LONG)
  477. return -EINVAL;
  478. /* make a mask of the order */
  479. mask = (1ul << (pages - 1));
  480. mask += mask - 1;
  481. /* run up the bitmap pages bits at a time */
  482. for (i = 0; i < bits; i += pages) {
  483. int index = i/BITS_PER_LONG;
  484. int offset = i - (index * BITS_PER_LONG);
  485. if((bitmap[index] & (mask << offset)) == 0) {
  486. /* set region in bimap */
  487. bitmap[index] |= (mask << offset);
  488. return i;
  489. }
  490. }
  491. return -ENOMEM;
  492. }
  493. EXPORT_SYMBOL(bitmap_find_free_region);
  494. /**
  495. * bitmap_release_region - release allocated bitmap region
  496. * @bitmap: a pointer to the bitmap
  497. * @pos: the beginning of the region
  498. * @order: the order of the bits to release (number is 1<<order)
  499. *
  500. * This is the complement to __bitmap_find_free_region and releases
  501. * the found region (by clearing it in the bitmap).
  502. */
  503. void bitmap_release_region(unsigned long *bitmap, int pos, int order)
  504. {
  505. int pages = 1 << order;
  506. unsigned long mask = (1ul << (pages - 1));
  507. int index = pos/BITS_PER_LONG;
  508. int offset = pos - (index * BITS_PER_LONG);
  509. mask += mask - 1;
  510. bitmap[index] &= ~(mask << offset);
  511. }
  512. EXPORT_SYMBOL(bitmap_release_region);
  513. int bitmap_allocate_region(unsigned long *bitmap, int pos, int order)
  514. {
  515. int pages = 1 << order;
  516. unsigned long mask = (1ul << (pages - 1));
  517. int index = pos/BITS_PER_LONG;
  518. int offset = pos - (index * BITS_PER_LONG);
  519. /* We don't do regions of pages > BITS_PER_LONG. The
  520. * algorithm would be a simple look for multiple zeros in the
  521. * array, but there's no driver today that needs this. If you
  522. * trip this BUG(), you get to code it... */
  523. BUG_ON(pages > BITS_PER_LONG);
  524. mask += mask - 1;
  525. if (bitmap[index] & (mask << offset))
  526. return -EBUSY;
  527. bitmap[index] |= (mask << offset);
  528. return 0;
  529. }
  530. EXPORT_SYMBOL(bitmap_allocate_region);