bitmap.c 35 KB

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