bitmap.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  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. * @buf: read nul-terminated user string from this buffer
  512. * @buflen: buffer size in bytes. If string is smaller than this
  513. * then it must be terminated with a \0.
  514. * @is_user: location of buffer, 0 indicates kernel space
  515. * @maskp: write resulting mask here
  516. * @nmaskbits: number of bits in mask to be written
  517. *
  518. * Input format is a comma-separated list of decimal numbers and
  519. * ranges. Consecutively set bits are shown as two hyphen-separated
  520. * decimal numbers, the smallest and largest bit numbers set in
  521. * the range.
  522. *
  523. * Returns 0 on success, -errno on invalid input strings.
  524. * Error values:
  525. * %-EINVAL: second number in range smaller than first
  526. * %-EINVAL: invalid character in string
  527. * %-ERANGE: bit number specified too large for mask
  528. */
  529. static int __bitmap_parselist(const char *buf, unsigned int buflen,
  530. int is_user, unsigned long *maskp,
  531. int nmaskbits)
  532. {
  533. unsigned a, b;
  534. int c, old_c, totaldigits;
  535. const char __user *ubuf = buf;
  536. int exp_digit, in_range;
  537. totaldigits = c = 0;
  538. bitmap_zero(maskp, nmaskbits);
  539. do {
  540. exp_digit = 1;
  541. in_range = 0;
  542. a = b = 0;
  543. /* Get the next cpu# or a range of cpu#'s */
  544. while (buflen) {
  545. old_c = c;
  546. if (is_user) {
  547. if (__get_user(c, ubuf++))
  548. return -EFAULT;
  549. } else
  550. c = *buf++;
  551. buflen--;
  552. if (isspace(c))
  553. continue;
  554. /*
  555. * If the last character was a space and the current
  556. * character isn't '\0', we've got embedded whitespace.
  557. * This is a no-no, so throw an error.
  558. */
  559. if (totaldigits && c && isspace(old_c))
  560. return -EINVAL;
  561. /* A '\0' or a ',' signal the end of a cpu# or range */
  562. if (c == '\0' || c == ',')
  563. break;
  564. if (c == '-') {
  565. if (exp_digit || in_range)
  566. return -EINVAL;
  567. b = 0;
  568. in_range = 1;
  569. exp_digit = 1;
  570. continue;
  571. }
  572. if (!isdigit(c))
  573. return -EINVAL;
  574. b = b * 10 + (c - '0');
  575. if (!in_range)
  576. a = b;
  577. exp_digit = 0;
  578. totaldigits++;
  579. }
  580. if (!(a <= b))
  581. return -EINVAL;
  582. if (b >= nmaskbits)
  583. return -ERANGE;
  584. while (a <= b) {
  585. set_bit(a, maskp);
  586. a++;
  587. }
  588. } while (buflen && c == ',');
  589. return 0;
  590. }
  591. int bitmap_parselist(const char *bp, unsigned long *maskp, int nmaskbits)
  592. {
  593. char *nl = strchr(bp, '\n');
  594. int len;
  595. if (nl)
  596. len = nl - bp;
  597. else
  598. len = strlen(bp);
  599. return __bitmap_parselist(bp, len, 0, maskp, nmaskbits);
  600. }
  601. EXPORT_SYMBOL(bitmap_parselist);
  602. /**
  603. * bitmap_parselist_user()
  604. *
  605. * @ubuf: pointer to user buffer containing string.
  606. * @ulen: buffer size in bytes. If string is smaller than this
  607. * then it must be terminated with a \0.
  608. * @maskp: pointer to bitmap array that will contain result.
  609. * @nmaskbits: size of bitmap, in bits.
  610. *
  611. * Wrapper for bitmap_parselist(), providing it with user buffer.
  612. *
  613. * We cannot have this as an inline function in bitmap.h because it needs
  614. * linux/uaccess.h to get the access_ok() declaration and this causes
  615. * cyclic dependencies.
  616. */
  617. int bitmap_parselist_user(const char __user *ubuf,
  618. unsigned int ulen, unsigned long *maskp,
  619. int nmaskbits)
  620. {
  621. if (!access_ok(VERIFY_READ, ubuf, ulen))
  622. return -EFAULT;
  623. return __bitmap_parselist((const char *)ubuf,
  624. ulen, 1, maskp, nmaskbits);
  625. }
  626. EXPORT_SYMBOL(bitmap_parselist_user);
  627. /**
  628. * bitmap_pos_to_ord - find ordinal of set bit at given position in bitmap
  629. * @buf: pointer to a bitmap
  630. * @pos: a bit position in @buf (0 <= @pos < @bits)
  631. * @bits: number of valid bit positions in @buf
  632. *
  633. * Map the bit at position @pos in @buf (of length @bits) to the
  634. * ordinal of which set bit it is. If it is not set or if @pos
  635. * is not a valid bit position, map to -1.
  636. *
  637. * If for example, just bits 4 through 7 are set in @buf, then @pos
  638. * values 4 through 7 will get mapped to 0 through 3, respectively,
  639. * and other @pos values will get mapped to 0. When @pos value 7
  640. * gets mapped to (returns) @ord value 3 in this example, that means
  641. * that bit 7 is the 3rd (starting with 0th) set bit in @buf.
  642. *
  643. * The bit positions 0 through @bits are valid positions in @buf.
  644. */
  645. static int bitmap_pos_to_ord(const unsigned long *buf, int pos, int bits)
  646. {
  647. int i, ord;
  648. if (pos < 0 || pos >= bits || !test_bit(pos, buf))
  649. return -1;
  650. i = find_first_bit(buf, bits);
  651. ord = 0;
  652. while (i < pos) {
  653. i = find_next_bit(buf, bits, i + 1);
  654. ord++;
  655. }
  656. BUG_ON(i != pos);
  657. return ord;
  658. }
  659. /**
  660. * bitmap_ord_to_pos - find position of n-th set bit in bitmap
  661. * @buf: pointer to bitmap
  662. * @ord: ordinal bit position (n-th set bit, n >= 0)
  663. * @bits: number of valid bit positions in @buf
  664. *
  665. * Map the ordinal offset of bit @ord in @buf to its position in @buf.
  666. * Value of @ord should be in range 0 <= @ord < weight(buf), else
  667. * results are undefined.
  668. *
  669. * If for example, just bits 4 through 7 are set in @buf, then @ord
  670. * values 0 through 3 will get mapped to 4 through 7, respectively,
  671. * and all other @ord values return undefined values. When @ord value 3
  672. * gets mapped to (returns) @pos value 7 in this example, that means
  673. * that the 3rd set bit (starting with 0th) is at position 7 in @buf.
  674. *
  675. * The bit positions 0 through @bits are valid positions in @buf.
  676. */
  677. static int bitmap_ord_to_pos(const unsigned long *buf, int ord, int bits)
  678. {
  679. int pos = 0;
  680. if (ord >= 0 && ord < bits) {
  681. int i;
  682. for (i = find_first_bit(buf, bits);
  683. i < bits && ord > 0;
  684. i = find_next_bit(buf, bits, i + 1))
  685. ord--;
  686. if (i < bits && ord == 0)
  687. pos = i;
  688. }
  689. return pos;
  690. }
  691. /**
  692. * bitmap_remap - Apply map defined by a pair of bitmaps to another bitmap
  693. * @dst: remapped result
  694. * @src: subset to be remapped
  695. * @old: defines domain of map
  696. * @new: defines range of map
  697. * @bits: number of bits in each of these bitmaps
  698. *
  699. * Let @old and @new define a mapping of bit positions, such that
  700. * whatever position is held by the n-th set bit in @old is mapped
  701. * to the n-th set bit in @new. In the more general case, allowing
  702. * for the possibility that the weight 'w' of @new is less than the
  703. * weight of @old, map the position of the n-th set bit in @old to
  704. * the position of the m-th set bit in @new, where m == n % w.
  705. *
  706. * If either of the @old and @new bitmaps are empty, or if @src and
  707. * @dst point to the same location, then this routine copies @src
  708. * to @dst.
  709. *
  710. * The positions of unset bits in @old are mapped to themselves
  711. * (the identify map).
  712. *
  713. * Apply the above specified mapping to @src, placing the result in
  714. * @dst, clearing any bits previously set in @dst.
  715. *
  716. * For example, lets say that @old has bits 4 through 7 set, and
  717. * @new has bits 12 through 15 set. This defines the mapping of bit
  718. * position 4 to 12, 5 to 13, 6 to 14 and 7 to 15, and of all other
  719. * bit positions unchanged. So if say @src comes into this routine
  720. * with bits 1, 5 and 7 set, then @dst should leave with bits 1,
  721. * 13 and 15 set.
  722. */
  723. void bitmap_remap(unsigned long *dst, const unsigned long *src,
  724. const unsigned long *old, const unsigned long *new,
  725. int bits)
  726. {
  727. int oldbit, w;
  728. if (dst == src) /* following doesn't handle inplace remaps */
  729. return;
  730. bitmap_zero(dst, bits);
  731. w = bitmap_weight(new, bits);
  732. for_each_set_bit(oldbit, src, bits) {
  733. int n = bitmap_pos_to_ord(old, oldbit, bits);
  734. if (n < 0 || w == 0)
  735. set_bit(oldbit, dst); /* identity map */
  736. else
  737. set_bit(bitmap_ord_to_pos(new, n % w, bits), dst);
  738. }
  739. }
  740. EXPORT_SYMBOL(bitmap_remap);
  741. /**
  742. * bitmap_bitremap - Apply map defined by a pair of bitmaps to a single bit
  743. * @oldbit: bit position to be mapped
  744. * @old: defines domain of map
  745. * @new: defines range of map
  746. * @bits: number of bits in each of these bitmaps
  747. *
  748. * Let @old and @new define a mapping of bit positions, such that
  749. * whatever position is held by the n-th set bit in @old is mapped
  750. * to the n-th set bit in @new. In the more general case, allowing
  751. * for the possibility that the weight 'w' of @new is less than the
  752. * weight of @old, map the position of the n-th set bit in @old to
  753. * the position of the m-th set bit in @new, where m == n % w.
  754. *
  755. * The positions of unset bits in @old are mapped to themselves
  756. * (the identify map).
  757. *
  758. * Apply the above specified mapping to bit position @oldbit, returning
  759. * the new bit position.
  760. *
  761. * For example, lets say that @old has bits 4 through 7 set, and
  762. * @new has bits 12 through 15 set. This defines the mapping of bit
  763. * position 4 to 12, 5 to 13, 6 to 14 and 7 to 15, and of all other
  764. * bit positions unchanged. So if say @oldbit is 5, then this routine
  765. * returns 13.
  766. */
  767. int bitmap_bitremap(int oldbit, const unsigned long *old,
  768. const unsigned long *new, int bits)
  769. {
  770. int w = bitmap_weight(new, bits);
  771. int n = bitmap_pos_to_ord(old, oldbit, bits);
  772. if (n < 0 || w == 0)
  773. return oldbit;
  774. else
  775. return bitmap_ord_to_pos(new, n % w, bits);
  776. }
  777. EXPORT_SYMBOL(bitmap_bitremap);
  778. /**
  779. * bitmap_onto - translate one bitmap relative to another
  780. * @dst: resulting translated bitmap
  781. * @orig: original untranslated bitmap
  782. * @relmap: bitmap relative to which translated
  783. * @bits: number of bits in each of these bitmaps
  784. *
  785. * Set the n-th bit of @dst iff there exists some m such that the
  786. * n-th bit of @relmap is set, the m-th bit of @orig is set, and
  787. * the n-th bit of @relmap is also the m-th _set_ bit of @relmap.
  788. * (If you understood the previous sentence the first time your
  789. * read it, you're overqualified for your current job.)
  790. *
  791. * In other words, @orig is mapped onto (surjectively) @dst,
  792. * using the the map { <n, m> | the n-th bit of @relmap is the
  793. * m-th set bit of @relmap }.
  794. *
  795. * Any set bits in @orig above bit number W, where W is the
  796. * weight of (number of set bits in) @relmap are mapped nowhere.
  797. * In particular, if for all bits m set in @orig, m >= W, then
  798. * @dst will end up empty. In situations where the possibility
  799. * of such an empty result is not desired, one way to avoid it is
  800. * to use the bitmap_fold() operator, below, to first fold the
  801. * @orig bitmap over itself so that all its set bits x are in the
  802. * range 0 <= x < W. The bitmap_fold() operator does this by
  803. * setting the bit (m % W) in @dst, for each bit (m) set in @orig.
  804. *
  805. * Example [1] for bitmap_onto():
  806. * Let's say @relmap has bits 30-39 set, and @orig has bits
  807. * 1, 3, 5, 7, 9 and 11 set. Then on return from this routine,
  808. * @dst will have bits 31, 33, 35, 37 and 39 set.
  809. *
  810. * When bit 0 is set in @orig, it means turn on the bit in
  811. * @dst corresponding to whatever is the first bit (if any)
  812. * that is turned on in @relmap. Since bit 0 was off in the
  813. * above example, we leave off that bit (bit 30) in @dst.
  814. *
  815. * When bit 1 is set in @orig (as in the above example), it
  816. * means turn on the bit in @dst corresponding to whatever
  817. * is the second bit that is turned on in @relmap. The second
  818. * bit in @relmap that was turned on in the above example was
  819. * bit 31, so we turned on bit 31 in @dst.
  820. *
  821. * Similarly, we turned on bits 33, 35, 37 and 39 in @dst,
  822. * because they were the 4th, 6th, 8th and 10th set bits
  823. * set in @relmap, and the 4th, 6th, 8th and 10th bits of
  824. * @orig (i.e. bits 3, 5, 7 and 9) were also set.
  825. *
  826. * When bit 11 is set in @orig, it means turn on the bit in
  827. * @dst corresponding to whatever is the twelfth bit that is
  828. * turned on in @relmap. In the above example, there were
  829. * only ten bits turned on in @relmap (30..39), so that bit
  830. * 11 was set in @orig had no affect on @dst.
  831. *
  832. * Example [2] for bitmap_fold() + bitmap_onto():
  833. * Let's say @relmap has these ten bits set:
  834. * 40 41 42 43 45 48 53 61 74 95
  835. * (for the curious, that's 40 plus the first ten terms of the
  836. * Fibonacci sequence.)
  837. *
  838. * Further lets say we use the following code, invoking
  839. * bitmap_fold() then bitmap_onto, as suggested above to
  840. * avoid the possitility of an empty @dst result:
  841. *
  842. * unsigned long *tmp; // a temporary bitmap's bits
  843. *
  844. * bitmap_fold(tmp, orig, bitmap_weight(relmap, bits), bits);
  845. * bitmap_onto(dst, tmp, relmap, bits);
  846. *
  847. * Then this table shows what various values of @dst would be, for
  848. * various @orig's. I list the zero-based positions of each set bit.
  849. * The tmp column shows the intermediate result, as computed by
  850. * using bitmap_fold() to fold the @orig bitmap modulo ten
  851. * (the weight of @relmap).
  852. *
  853. * @orig tmp @dst
  854. * 0 0 40
  855. * 1 1 41
  856. * 9 9 95
  857. * 10 0 40 (*)
  858. * 1 3 5 7 1 3 5 7 41 43 48 61
  859. * 0 1 2 3 4 0 1 2 3 4 40 41 42 43 45
  860. * 0 9 18 27 0 9 8 7 40 61 74 95
  861. * 0 10 20 30 0 40
  862. * 0 11 22 33 0 1 2 3 40 41 42 43
  863. * 0 12 24 36 0 2 4 6 40 42 45 53
  864. * 78 102 211 1 2 8 41 42 74 (*)
  865. *
  866. * (*) For these marked lines, if we hadn't first done bitmap_fold()
  867. * into tmp, then the @dst result would have been empty.
  868. *
  869. * If either of @orig or @relmap is empty (no set bits), then @dst
  870. * will be returned empty.
  871. *
  872. * If (as explained above) the only set bits in @orig are in positions
  873. * m where m >= W, (where W is the weight of @relmap) then @dst will
  874. * once again be returned empty.
  875. *
  876. * All bits in @dst not set by the above rule are cleared.
  877. */
  878. void bitmap_onto(unsigned long *dst, const unsigned long *orig,
  879. const unsigned long *relmap, int bits)
  880. {
  881. int n, m; /* same meaning as in above comment */
  882. if (dst == orig) /* following doesn't handle inplace mappings */
  883. return;
  884. bitmap_zero(dst, bits);
  885. /*
  886. * The following code is a more efficient, but less
  887. * obvious, equivalent to the loop:
  888. * for (m = 0; m < bitmap_weight(relmap, bits); m++) {
  889. * n = bitmap_ord_to_pos(orig, m, bits);
  890. * if (test_bit(m, orig))
  891. * set_bit(n, dst);
  892. * }
  893. */
  894. m = 0;
  895. for_each_set_bit(n, relmap, bits) {
  896. /* m == bitmap_pos_to_ord(relmap, n, bits) */
  897. if (test_bit(m, orig))
  898. set_bit(n, dst);
  899. m++;
  900. }
  901. }
  902. EXPORT_SYMBOL(bitmap_onto);
  903. /**
  904. * bitmap_fold - fold larger bitmap into smaller, modulo specified size
  905. * @dst: resulting smaller bitmap
  906. * @orig: original larger bitmap
  907. * @sz: specified size
  908. * @bits: number of bits in each of these bitmaps
  909. *
  910. * For each bit oldbit in @orig, set bit oldbit mod @sz in @dst.
  911. * Clear all other bits in @dst. See further the comment and
  912. * Example [2] for bitmap_onto() for why and how to use this.
  913. */
  914. void bitmap_fold(unsigned long *dst, const unsigned long *orig,
  915. int sz, int bits)
  916. {
  917. int oldbit;
  918. if (dst == orig) /* following doesn't handle inplace mappings */
  919. return;
  920. bitmap_zero(dst, bits);
  921. for_each_set_bit(oldbit, orig, bits)
  922. set_bit(oldbit % sz, dst);
  923. }
  924. EXPORT_SYMBOL(bitmap_fold);
  925. /*
  926. * Common code for bitmap_*_region() routines.
  927. * bitmap: array of unsigned longs corresponding to the bitmap
  928. * pos: the beginning of the region
  929. * order: region size (log base 2 of number of bits)
  930. * reg_op: operation(s) to perform on that region of bitmap
  931. *
  932. * Can set, verify and/or release a region of bits in a bitmap,
  933. * depending on which combination of REG_OP_* flag bits is set.
  934. *
  935. * A region of a bitmap is a sequence of bits in the bitmap, of
  936. * some size '1 << order' (a power of two), aligned to that same
  937. * '1 << order' power of two.
  938. *
  939. * Returns 1 if REG_OP_ISFREE succeeds (region is all zero bits).
  940. * Returns 0 in all other cases and reg_ops.
  941. */
  942. enum {
  943. REG_OP_ISFREE, /* true if region is all zero bits */
  944. REG_OP_ALLOC, /* set all bits in region */
  945. REG_OP_RELEASE, /* clear all bits in region */
  946. };
  947. static int __reg_op(unsigned long *bitmap, int pos, int order, int reg_op)
  948. {
  949. int nbits_reg; /* number of bits in region */
  950. int index; /* index first long of region in bitmap */
  951. int offset; /* bit offset region in bitmap[index] */
  952. int nlongs_reg; /* num longs spanned by region in bitmap */
  953. int nbitsinlong; /* num bits of region in each spanned long */
  954. unsigned long mask; /* bitmask for one long of region */
  955. int i; /* scans bitmap by longs */
  956. int ret = 0; /* return value */
  957. /*
  958. * Either nlongs_reg == 1 (for small orders that fit in one long)
  959. * or (offset == 0 && mask == ~0UL) (for larger multiword orders.)
  960. */
  961. nbits_reg = 1 << order;
  962. index = pos / BITS_PER_LONG;
  963. offset = pos - (index * BITS_PER_LONG);
  964. nlongs_reg = BITS_TO_LONGS(nbits_reg);
  965. nbitsinlong = min(nbits_reg, BITS_PER_LONG);
  966. /*
  967. * Can't do "mask = (1UL << nbitsinlong) - 1", as that
  968. * overflows if nbitsinlong == BITS_PER_LONG.
  969. */
  970. mask = (1UL << (nbitsinlong - 1));
  971. mask += mask - 1;
  972. mask <<= offset;
  973. switch (reg_op) {
  974. case REG_OP_ISFREE:
  975. for (i = 0; i < nlongs_reg; i++) {
  976. if (bitmap[index + i] & mask)
  977. goto done;
  978. }
  979. ret = 1; /* all bits in region free (zero) */
  980. break;
  981. case REG_OP_ALLOC:
  982. for (i = 0; i < nlongs_reg; i++)
  983. bitmap[index + i] |= mask;
  984. break;
  985. case REG_OP_RELEASE:
  986. for (i = 0; i < nlongs_reg; i++)
  987. bitmap[index + i] &= ~mask;
  988. break;
  989. }
  990. done:
  991. return ret;
  992. }
  993. /**
  994. * bitmap_find_free_region - find a contiguous aligned mem region
  995. * @bitmap: array of unsigned longs corresponding to the bitmap
  996. * @bits: number of bits in the bitmap
  997. * @order: region size (log base 2 of number of bits) to find
  998. *
  999. * Find a region of free (zero) bits in a @bitmap of @bits bits and
  1000. * allocate them (set them to one). Only consider regions of length
  1001. * a power (@order) of two, aligned to that power of two, which
  1002. * makes the search algorithm much faster.
  1003. *
  1004. * Return the bit offset in bitmap of the allocated region,
  1005. * or -errno on failure.
  1006. */
  1007. int bitmap_find_free_region(unsigned long *bitmap, int bits, int order)
  1008. {
  1009. int pos, end; /* scans bitmap by regions of size order */
  1010. for (pos = 0 ; (end = pos + (1 << order)) <= bits; pos = end) {
  1011. if (!__reg_op(bitmap, pos, order, REG_OP_ISFREE))
  1012. continue;
  1013. __reg_op(bitmap, pos, order, REG_OP_ALLOC);
  1014. return pos;
  1015. }
  1016. return -ENOMEM;
  1017. }
  1018. EXPORT_SYMBOL(bitmap_find_free_region);
  1019. /**
  1020. * bitmap_release_region - release allocated bitmap region
  1021. * @bitmap: array of unsigned longs corresponding to the bitmap
  1022. * @pos: beginning of bit region to release
  1023. * @order: region size (log base 2 of number of bits) to release
  1024. *
  1025. * This is the complement to __bitmap_find_free_region() and releases
  1026. * the found region (by clearing it in the bitmap).
  1027. *
  1028. * No return value.
  1029. */
  1030. void bitmap_release_region(unsigned long *bitmap, int pos, int order)
  1031. {
  1032. __reg_op(bitmap, pos, order, REG_OP_RELEASE);
  1033. }
  1034. EXPORT_SYMBOL(bitmap_release_region);
  1035. /**
  1036. * bitmap_allocate_region - allocate bitmap region
  1037. * @bitmap: array of unsigned longs corresponding to the bitmap
  1038. * @pos: beginning of bit region to allocate
  1039. * @order: region size (log base 2 of number of bits) to allocate
  1040. *
  1041. * Allocate (set bits in) a specified region of a bitmap.
  1042. *
  1043. * Return 0 on success, or %-EBUSY if specified region wasn't
  1044. * free (not all bits were zero).
  1045. */
  1046. int bitmap_allocate_region(unsigned long *bitmap, int pos, int order)
  1047. {
  1048. if (!__reg_op(bitmap, pos, order, REG_OP_ISFREE))
  1049. return -EBUSY;
  1050. __reg_op(bitmap, pos, order, REG_OP_ALLOC);
  1051. return 0;
  1052. }
  1053. EXPORT_SYMBOL(bitmap_allocate_region);
  1054. /**
  1055. * bitmap_copy_le - copy a bitmap, putting the bits into little-endian order.
  1056. * @dst: destination buffer
  1057. * @src: bitmap to copy
  1058. * @nbits: number of bits in the bitmap
  1059. *
  1060. * Require nbits % BITS_PER_LONG == 0.
  1061. */
  1062. void bitmap_copy_le(void *dst, const unsigned long *src, int nbits)
  1063. {
  1064. unsigned long *d = dst;
  1065. int i;
  1066. for (i = 0; i < nbits/BITS_PER_LONG; i++) {
  1067. if (BITS_PER_LONG == 64)
  1068. d[i] = cpu_to_le64(src[i]);
  1069. else
  1070. d[i] = cpu_to_le32(src[i]);
  1071. }
  1072. }
  1073. EXPORT_SYMBOL(bitmap_copy_le);