bitmap.c 33 KB

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