bitmap.c 33 KB

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