bitmap.c 35 KB

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