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