bitmap.c 33 KB

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