bitmap.c 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * lib/bitmap.c
  4. * Helper functions for bitmap.h.
  5. */
  6. #include <linux/bitmap.h>
  7. #include <linux/bitops.h>
  8. #include <linux/bug.h>
  9. #include <linux/ctype.h>
  10. #include <linux/device.h>
  11. #include <linux/errno.h>
  12. #include <linux/export.h>
  13. #include <linux/kernel.h>
  14. #include <linux/mm.h>
  15. #include <linux/slab.h>
  16. #include <linux/string.h>
  17. #include <linux/thread_info.h>
  18. #include <linux/uaccess.h>
  19. #include <asm/page.h>
  20. #include "kstrtox.h"
  21. /**
  22. * DOC: bitmap introduction
  23. *
  24. * bitmaps provide an array of bits, implemented using an
  25. * array of unsigned longs. The number of valid bits in a
  26. * given bitmap does _not_ need to be an exact multiple of
  27. * BITS_PER_LONG.
  28. *
  29. * The possible unused bits in the last, partially used word
  30. * of a bitmap are 'don't care'. The implementation makes
  31. * no particular effort to keep them zero. It ensures that
  32. * their value will not affect the results of any operation.
  33. * The bitmap operations that return Boolean (bitmap_empty,
  34. * for example) or scalar (bitmap_weight, for example) results
  35. * carefully filter out these unused bits from impacting their
  36. * results.
  37. *
  38. * The byte ordering of bitmaps is more natural on little
  39. * endian architectures. See the big-endian headers
  40. * include/asm-ppc64/bitops.h and include/asm-s390/bitops.h
  41. * for the best explanations of this ordering.
  42. */
  43. bool __bitmap_equal(const unsigned long *bitmap1,
  44. const unsigned long *bitmap2, unsigned int bits)
  45. {
  46. unsigned int k, lim = bits/BITS_PER_LONG;
  47. for (k = 0; k < lim; ++k)
  48. if (bitmap1[k] != bitmap2[k])
  49. return false;
  50. if (bits % BITS_PER_LONG)
  51. if ((bitmap1[k] ^ bitmap2[k]) & BITMAP_LAST_WORD_MASK(bits))
  52. return false;
  53. return true;
  54. }
  55. EXPORT_SYMBOL(__bitmap_equal);
  56. bool __bitmap_or_equal(const unsigned long *bitmap1,
  57. const unsigned long *bitmap2,
  58. const unsigned long *bitmap3,
  59. unsigned int bits)
  60. {
  61. unsigned int k, lim = bits / BITS_PER_LONG;
  62. unsigned long tmp;
  63. for (k = 0; k < lim; ++k) {
  64. if ((bitmap1[k] | bitmap2[k]) != bitmap3[k])
  65. return false;
  66. }
  67. if (!(bits % BITS_PER_LONG))
  68. return true;
  69. tmp = (bitmap1[k] | bitmap2[k]) ^ bitmap3[k];
  70. return (tmp & BITMAP_LAST_WORD_MASK(bits)) == 0;
  71. }
  72. void __bitmap_complement(unsigned long *dst, const unsigned long *src, unsigned int bits)
  73. {
  74. unsigned int k, lim = BITS_TO_LONGS(bits);
  75. for (k = 0; k < lim; ++k)
  76. dst[k] = ~src[k];
  77. }
  78. EXPORT_SYMBOL(__bitmap_complement);
  79. /**
  80. * __bitmap_shift_right - logical right shift of the bits in a bitmap
  81. * @dst : destination bitmap
  82. * @src : source bitmap
  83. * @shift : shift by this many bits
  84. * @nbits : bitmap size, in bits
  85. *
  86. * Shifting right (dividing) means moving bits in the MS -> LS bit
  87. * direction. Zeros are fed into the vacated MS positions and the
  88. * LS bits shifted off the bottom are lost.
  89. */
  90. void __bitmap_shift_right(unsigned long *dst, const unsigned long *src,
  91. unsigned shift, unsigned nbits)
  92. {
  93. unsigned k, lim = BITS_TO_LONGS(nbits);
  94. unsigned off = shift/BITS_PER_LONG, rem = shift % BITS_PER_LONG;
  95. unsigned long mask = BITMAP_LAST_WORD_MASK(nbits);
  96. for (k = 0; off + k < lim; ++k) {
  97. unsigned long upper, lower;
  98. /*
  99. * If shift is not word aligned, take lower rem bits of
  100. * word above and make them the top rem bits of result.
  101. */
  102. if (!rem || off + k + 1 >= lim)
  103. upper = 0;
  104. else {
  105. upper = src[off + k + 1];
  106. if (off + k + 1 == lim - 1)
  107. upper &= mask;
  108. upper <<= (BITS_PER_LONG - rem);
  109. }
  110. lower = src[off + k];
  111. if (off + k == lim - 1)
  112. lower &= mask;
  113. lower >>= rem;
  114. dst[k] = lower | upper;
  115. }
  116. if (off)
  117. memset(&dst[lim - off], 0, off*sizeof(unsigned long));
  118. }
  119. EXPORT_SYMBOL(__bitmap_shift_right);
  120. /**
  121. * __bitmap_shift_left - logical left shift of the bits in a bitmap
  122. * @dst : destination bitmap
  123. * @src : source bitmap
  124. * @shift : shift by this many bits
  125. * @nbits : bitmap size, in bits
  126. *
  127. * Shifting left (multiplying) means moving bits in the LS -> MS
  128. * direction. Zeros are fed into the vacated LS bit positions
  129. * and those MS bits shifted off the top are lost.
  130. */
  131. void __bitmap_shift_left(unsigned long *dst, const unsigned long *src,
  132. unsigned int shift, unsigned int nbits)
  133. {
  134. int k;
  135. unsigned int lim = BITS_TO_LONGS(nbits);
  136. unsigned int off = shift/BITS_PER_LONG, rem = shift % BITS_PER_LONG;
  137. for (k = lim - off - 1; k >= 0; --k) {
  138. unsigned long upper, lower;
  139. /*
  140. * If shift is not word aligned, take upper rem bits of
  141. * word below and make them the bottom rem bits of result.
  142. */
  143. if (rem && k > 0)
  144. lower = src[k - 1] >> (BITS_PER_LONG - rem);
  145. else
  146. lower = 0;
  147. upper = src[k] << rem;
  148. dst[k + off] = lower | upper;
  149. }
  150. if (off)
  151. memset(dst, 0, off*sizeof(unsigned long));
  152. }
  153. EXPORT_SYMBOL(__bitmap_shift_left);
  154. /**
  155. * bitmap_cut() - remove bit region from bitmap and right shift remaining bits
  156. * @dst: destination bitmap, might overlap with src
  157. * @src: source bitmap
  158. * @first: start bit of region to be removed
  159. * @cut: number of bits to remove
  160. * @nbits: bitmap size, in bits
  161. *
  162. * Set the n-th bit of @dst iff the n-th bit of @src is set and
  163. * n is less than @first, or the m-th bit of @src is set for any
  164. * m such that @first <= n < nbits, and m = n + @cut.
  165. *
  166. * In pictures, example for a big-endian 32-bit architecture:
  167. *
  168. * The @src bitmap is::
  169. *
  170. * 31 63
  171. * | |
  172. * 10000000 11000001 11110010 00010101 10000000 11000001 01110010 00010101
  173. * | | | |
  174. * 16 14 0 32
  175. *
  176. * if @cut is 3, and @first is 14, bits 14-16 in @src are cut and @dst is::
  177. *
  178. * 31 63
  179. * | |
  180. * 10110000 00011000 00110010 00010101 00010000 00011000 00101110 01000010
  181. * | | |
  182. * 14 (bit 17 0 32
  183. * from @src)
  184. *
  185. * Note that @dst and @src might overlap partially or entirely.
  186. *
  187. * This is implemented in the obvious way, with a shift and carry
  188. * step for each moved bit. Optimisation is left as an exercise
  189. * for the compiler.
  190. */
  191. void bitmap_cut(unsigned long *dst, const unsigned long *src,
  192. unsigned int first, unsigned int cut, unsigned int nbits)
  193. {
  194. unsigned int len = BITS_TO_LONGS(nbits);
  195. unsigned long keep = 0, carry;
  196. int i;
  197. if (first % BITS_PER_LONG) {
  198. keep = src[first / BITS_PER_LONG] &
  199. (~0UL >> (BITS_PER_LONG - first % BITS_PER_LONG));
  200. }
  201. memmove(dst, src, len * sizeof(*dst));
  202. while (cut--) {
  203. for (i = first / BITS_PER_LONG; i < len; i++) {
  204. if (i < len - 1)
  205. carry = dst[i + 1] & 1UL;
  206. else
  207. carry = 0;
  208. dst[i] = (dst[i] >> 1) | (carry << (BITS_PER_LONG - 1));
  209. }
  210. }
  211. dst[first / BITS_PER_LONG] &= ~0UL << (first % BITS_PER_LONG);
  212. dst[first / BITS_PER_LONG] |= keep;
  213. }
  214. EXPORT_SYMBOL(bitmap_cut);
  215. bool __bitmap_and(unsigned long *dst, const unsigned long *bitmap1,
  216. const unsigned long *bitmap2, unsigned int bits)
  217. {
  218. unsigned int k;
  219. unsigned int lim = bits/BITS_PER_LONG;
  220. unsigned long result = 0;
  221. for (k = 0; k < lim; k++)
  222. result |= (dst[k] = bitmap1[k] & bitmap2[k]);
  223. if (bits % BITS_PER_LONG)
  224. result |= (dst[k] = bitmap1[k] & bitmap2[k] &
  225. BITMAP_LAST_WORD_MASK(bits));
  226. return result != 0;
  227. }
  228. EXPORT_SYMBOL(__bitmap_and);
  229. void __bitmap_or(unsigned long *dst, const unsigned long *bitmap1,
  230. const unsigned long *bitmap2, unsigned int bits)
  231. {
  232. unsigned int k;
  233. unsigned int nr = BITS_TO_LONGS(bits);
  234. for (k = 0; k < nr; k++)
  235. dst[k] = bitmap1[k] | bitmap2[k];
  236. }
  237. EXPORT_SYMBOL(__bitmap_or);
  238. void __bitmap_xor(unsigned long *dst, const unsigned long *bitmap1,
  239. const unsigned long *bitmap2, unsigned int bits)
  240. {
  241. unsigned int k;
  242. unsigned int nr = BITS_TO_LONGS(bits);
  243. for (k = 0; k < nr; k++)
  244. dst[k] = bitmap1[k] ^ bitmap2[k];
  245. }
  246. EXPORT_SYMBOL(__bitmap_xor);
  247. bool __bitmap_andnot(unsigned long *dst, const unsigned long *bitmap1,
  248. const unsigned long *bitmap2, unsigned int bits)
  249. {
  250. unsigned int k;
  251. unsigned int lim = bits/BITS_PER_LONG;
  252. unsigned long result = 0;
  253. for (k = 0; k < lim; k++)
  254. result |= (dst[k] = bitmap1[k] & ~bitmap2[k]);
  255. if (bits % BITS_PER_LONG)
  256. result |= (dst[k] = bitmap1[k] & ~bitmap2[k] &
  257. BITMAP_LAST_WORD_MASK(bits));
  258. return result != 0;
  259. }
  260. EXPORT_SYMBOL(__bitmap_andnot);
  261. void __bitmap_replace(unsigned long *dst,
  262. const unsigned long *old, const unsigned long *new,
  263. const unsigned long *mask, unsigned int nbits)
  264. {
  265. unsigned int k;
  266. unsigned int nr = BITS_TO_LONGS(nbits);
  267. for (k = 0; k < nr; k++)
  268. dst[k] = (old[k] & ~mask[k]) | (new[k] & mask[k]);
  269. }
  270. EXPORT_SYMBOL(__bitmap_replace);
  271. bool __bitmap_intersects(const unsigned long *bitmap1,
  272. const unsigned long *bitmap2, unsigned int bits)
  273. {
  274. unsigned int k, lim = bits/BITS_PER_LONG;
  275. for (k = 0; k < lim; ++k)
  276. if (bitmap1[k] & bitmap2[k])
  277. return true;
  278. if (bits % BITS_PER_LONG)
  279. if ((bitmap1[k] & bitmap2[k]) & BITMAP_LAST_WORD_MASK(bits))
  280. return true;
  281. return false;
  282. }
  283. EXPORT_SYMBOL(__bitmap_intersects);
  284. bool __bitmap_subset(const unsigned long *bitmap1,
  285. const unsigned long *bitmap2, unsigned int bits)
  286. {
  287. unsigned int k, lim = bits/BITS_PER_LONG;
  288. for (k = 0; k < lim; ++k)
  289. if (bitmap1[k] & ~bitmap2[k])
  290. return false;
  291. if (bits % BITS_PER_LONG)
  292. if ((bitmap1[k] & ~bitmap2[k]) & BITMAP_LAST_WORD_MASK(bits))
  293. return false;
  294. return true;
  295. }
  296. EXPORT_SYMBOL(__bitmap_subset);
  297. #define BITMAP_WEIGHT(FETCH, bits) \
  298. ({ \
  299. unsigned int __bits = (bits), idx, w = 0; \
  300. \
  301. for (idx = 0; idx < __bits / BITS_PER_LONG; idx++) \
  302. w += hweight_long(FETCH); \
  303. \
  304. if (__bits % BITS_PER_LONG) \
  305. w += hweight_long((FETCH) & BITMAP_LAST_WORD_MASK(__bits)); \
  306. \
  307. w; \
  308. })
  309. unsigned int __bitmap_weight(const unsigned long *bitmap, unsigned int bits)
  310. {
  311. return BITMAP_WEIGHT(bitmap[idx], bits);
  312. }
  313. EXPORT_SYMBOL(__bitmap_weight);
  314. unsigned int __bitmap_weight_and(const unsigned long *bitmap1,
  315. const unsigned long *bitmap2, unsigned int bits)
  316. {
  317. return BITMAP_WEIGHT(bitmap1[idx] & bitmap2[idx], bits);
  318. }
  319. EXPORT_SYMBOL(__bitmap_weight_and);
  320. void __bitmap_set(unsigned long *map, unsigned int start, int len)
  321. {
  322. unsigned long *p = map + BIT_WORD(start);
  323. const unsigned int size = start + len;
  324. int bits_to_set = BITS_PER_LONG - (start % BITS_PER_LONG);
  325. unsigned long mask_to_set = BITMAP_FIRST_WORD_MASK(start);
  326. while (len - bits_to_set >= 0) {
  327. *p |= mask_to_set;
  328. len -= bits_to_set;
  329. bits_to_set = BITS_PER_LONG;
  330. mask_to_set = ~0UL;
  331. p++;
  332. }
  333. if (len) {
  334. mask_to_set &= BITMAP_LAST_WORD_MASK(size);
  335. *p |= mask_to_set;
  336. }
  337. }
  338. EXPORT_SYMBOL(__bitmap_set);
  339. void __bitmap_clear(unsigned long *map, unsigned int start, int len)
  340. {
  341. unsigned long *p = map + BIT_WORD(start);
  342. const unsigned int size = start + len;
  343. int bits_to_clear = BITS_PER_LONG - (start % BITS_PER_LONG);
  344. unsigned long mask_to_clear = BITMAP_FIRST_WORD_MASK(start);
  345. while (len - bits_to_clear >= 0) {
  346. *p &= ~mask_to_clear;
  347. len -= bits_to_clear;
  348. bits_to_clear = BITS_PER_LONG;
  349. mask_to_clear = ~0UL;
  350. p++;
  351. }
  352. if (len) {
  353. mask_to_clear &= BITMAP_LAST_WORD_MASK(size);
  354. *p &= ~mask_to_clear;
  355. }
  356. }
  357. EXPORT_SYMBOL(__bitmap_clear);
  358. /**
  359. * bitmap_find_next_zero_area_off - find a contiguous aligned zero area
  360. * @map: The address to base the search on
  361. * @size: The bitmap size in bits
  362. * @start: The bitnumber to start searching at
  363. * @nr: The number of zeroed bits we're looking for
  364. * @align_mask: Alignment mask for zero area
  365. * @align_offset: Alignment offset for zero area.
  366. *
  367. * The @align_mask should be one less than a power of 2; the effect is that
  368. * the bit offset of all zero areas this function finds plus @align_offset
  369. * is multiple of that power of 2.
  370. */
  371. unsigned long bitmap_find_next_zero_area_off(unsigned long *map,
  372. unsigned long size,
  373. unsigned long start,
  374. unsigned int nr,
  375. unsigned long align_mask,
  376. unsigned long align_offset)
  377. {
  378. unsigned long index, end, i;
  379. again:
  380. index = find_next_zero_bit(map, size, start);
  381. /* Align allocation */
  382. index = __ALIGN_MASK(index + align_offset, align_mask) - align_offset;
  383. end = index + nr;
  384. if (end > size)
  385. return end;
  386. i = find_next_bit(map, end, index);
  387. if (i < end) {
  388. start = i + 1;
  389. goto again;
  390. }
  391. return index;
  392. }
  393. EXPORT_SYMBOL(bitmap_find_next_zero_area_off);
  394. /*
  395. * Bitmap printing & parsing functions: first version by Nadia Yvette Chambers,
  396. * second version by Paul Jackson, third by Joe Korty.
  397. */
  398. /**
  399. * bitmap_parse_user - convert an ASCII hex string in a user buffer into a bitmap
  400. *
  401. * @ubuf: pointer to user buffer containing string.
  402. * @ulen: buffer size in bytes. If string is smaller than this
  403. * then it must be terminated with a \0.
  404. * @maskp: pointer to bitmap array that will contain result.
  405. * @nmaskbits: size of bitmap, in bits.
  406. */
  407. int bitmap_parse_user(const char __user *ubuf,
  408. unsigned int ulen, unsigned long *maskp,
  409. int nmaskbits)
  410. {
  411. char *buf;
  412. int ret;
  413. buf = memdup_user_nul(ubuf, ulen);
  414. if (IS_ERR(buf))
  415. return PTR_ERR(buf);
  416. ret = bitmap_parse(buf, UINT_MAX, maskp, nmaskbits);
  417. kfree(buf);
  418. return ret;
  419. }
  420. EXPORT_SYMBOL(bitmap_parse_user);
  421. /**
  422. * bitmap_print_to_pagebuf - convert bitmap to list or hex format ASCII string
  423. * @list: indicates whether the bitmap must be list
  424. * @buf: page aligned buffer into which string is placed
  425. * @maskp: pointer to bitmap to convert
  426. * @nmaskbits: size of bitmap, in bits
  427. *
  428. * Output format is a comma-separated list of decimal numbers and
  429. * ranges if list is specified or hex digits grouped into comma-separated
  430. * sets of 8 digits/set. Returns the number of characters written to buf.
  431. *
  432. * It is assumed that @buf is a pointer into a PAGE_SIZE, page-aligned
  433. * area and that sufficient storage remains at @buf to accommodate the
  434. * bitmap_print_to_pagebuf() output. Returns the number of characters
  435. * actually printed to @buf, excluding terminating '\0'.
  436. */
  437. int bitmap_print_to_pagebuf(bool list, char *buf, const unsigned long *maskp,
  438. int nmaskbits)
  439. {
  440. ptrdiff_t len = PAGE_SIZE - offset_in_page(buf);
  441. return list ? scnprintf(buf, len, "%*pbl\n", nmaskbits, maskp) :
  442. scnprintf(buf, len, "%*pb\n", nmaskbits, maskp);
  443. }
  444. EXPORT_SYMBOL(bitmap_print_to_pagebuf);
  445. /**
  446. * bitmap_print_to_buf - convert bitmap to list or hex format ASCII string
  447. * @list: indicates whether the bitmap must be list
  448. * true: print in decimal list format
  449. * false: print in hexadecimal bitmask format
  450. * @buf: buffer into which string is placed
  451. * @maskp: pointer to bitmap to convert
  452. * @nmaskbits: size of bitmap, in bits
  453. * @off: in the string from which we are copying, We copy to @buf
  454. * @count: the maximum number of bytes to print
  455. */
  456. static int bitmap_print_to_buf(bool list, char *buf, const unsigned long *maskp,
  457. int nmaskbits, loff_t off, size_t count)
  458. {
  459. const char *fmt = list ? "%*pbl\n" : "%*pb\n";
  460. ssize_t size;
  461. void *data;
  462. data = kasprintf(GFP_KERNEL, fmt, nmaskbits, maskp);
  463. if (!data)
  464. return -ENOMEM;
  465. size = memory_read_from_buffer(buf, count, &off, data, strlen(data) + 1);
  466. kfree(data);
  467. return size;
  468. }
  469. /**
  470. * bitmap_print_bitmask_to_buf - convert bitmap to hex bitmask format ASCII string
  471. * @buf: buffer into which string is placed
  472. * @maskp: pointer to bitmap to convert
  473. * @nmaskbits: size of bitmap, in bits
  474. * @off: in the string from which we are copying, We copy to @buf
  475. * @count: the maximum number of bytes to print
  476. *
  477. * The bitmap_print_to_pagebuf() is used indirectly via its cpumap wrapper
  478. * cpumap_print_to_pagebuf() or directly by drivers to export hexadecimal
  479. * bitmask and decimal list to userspace by sysfs ABI.
  480. * Drivers might be using a normal attribute for this kind of ABIs. A
  481. * normal attribute typically has show entry as below::
  482. *
  483. * static ssize_t example_attribute_show(struct device *dev,
  484. * struct device_attribute *attr, char *buf)
  485. * {
  486. * ...
  487. * return bitmap_print_to_pagebuf(true, buf, &mask, nr_trig_max);
  488. * }
  489. *
  490. * show entry of attribute has no offset and count parameters and this
  491. * means the file is limited to one page only.
  492. * bitmap_print_to_pagebuf() API works terribly well for this kind of
  493. * normal attribute with buf parameter and without offset, count::
  494. *
  495. * bitmap_print_to_pagebuf(bool list, char *buf, const unsigned long *maskp,
  496. * int nmaskbits)
  497. * {
  498. * }
  499. *
  500. * The problem is once we have a large bitmap, we have a chance to get a
  501. * bitmask or list more than one page. Especially for list, it could be
  502. * as complex as 0,3,5,7,9,... We have no simple way to know it exact size.
  503. * It turns out bin_attribute is a way to break this limit. bin_attribute
  504. * has show entry as below::
  505. *
  506. * static ssize_t
  507. * example_bin_attribute_show(struct file *filp, struct kobject *kobj,
  508. * struct bin_attribute *attr, char *buf,
  509. * loff_t offset, size_t count)
  510. * {
  511. * ...
  512. * }
  513. *
  514. * With the new offset and count parameters, this makes sysfs ABI be able
  515. * to support file size more than one page. For example, offset could be
  516. * >= 4096.
  517. * bitmap_print_bitmask_to_buf(), bitmap_print_list_to_buf() wit their
  518. * cpumap wrapper cpumap_print_bitmask_to_buf(), cpumap_print_list_to_buf()
  519. * make those drivers be able to support large bitmask and list after they
  520. * move to use bin_attribute. In result, we have to pass the corresponding
  521. * parameters such as off, count from bin_attribute show entry to this API.
  522. *
  523. * The role of cpumap_print_bitmask_to_buf() and cpumap_print_list_to_buf()
  524. * is similar with cpumap_print_to_pagebuf(), the difference is that
  525. * bitmap_print_to_pagebuf() mainly serves sysfs attribute with the assumption
  526. * the destination buffer is exactly one page and won't be more than one page.
  527. * cpumap_print_bitmask_to_buf() and cpumap_print_list_to_buf(), on the other
  528. * hand, mainly serves bin_attribute which doesn't work with exact one page,
  529. * and it can break the size limit of converted decimal list and hexadecimal
  530. * bitmask.
  531. *
  532. * WARNING!
  533. *
  534. * This function is not a replacement for sprintf() or bitmap_print_to_pagebuf().
  535. * It is intended to workaround sysfs limitations discussed above and should be
  536. * used carefully in general case for the following reasons:
  537. *
  538. * - Time complexity is O(nbits^2/count), comparing to O(nbits) for snprintf().
  539. * - Memory complexity is O(nbits), comparing to O(1) for snprintf().
  540. * - @off and @count are NOT offset and number of bits to print.
  541. * - If printing part of bitmap as list, the resulting string is not a correct
  542. * list representation of bitmap. Particularly, some bits within or out of
  543. * related interval may be erroneously set or unset. The format of the string
  544. * may be broken, so bitmap_parselist-like parser may fail parsing it.
  545. * - If printing the whole bitmap as list by parts, user must ensure the order
  546. * of calls of the function such that the offset is incremented linearly.
  547. * - If printing the whole bitmap as list by parts, user must keep bitmap
  548. * unchanged between the very first and very last call. Otherwise concatenated
  549. * result may be incorrect, and format may be broken.
  550. *
  551. * Returns the number of characters actually printed to @buf
  552. */
  553. int bitmap_print_bitmask_to_buf(char *buf, const unsigned long *maskp,
  554. int nmaskbits, loff_t off, size_t count)
  555. {
  556. return bitmap_print_to_buf(false, buf, maskp, nmaskbits, off, count);
  557. }
  558. EXPORT_SYMBOL(bitmap_print_bitmask_to_buf);
  559. /**
  560. * bitmap_print_list_to_buf - convert bitmap to decimal list format ASCII string
  561. * @buf: buffer into which string is placed
  562. * @maskp: pointer to bitmap to convert
  563. * @nmaskbits: size of bitmap, in bits
  564. * @off: in the string from which we are copying, We copy to @buf
  565. * @count: the maximum number of bytes to print
  566. *
  567. * Everything is same with the above bitmap_print_bitmask_to_buf() except
  568. * the print format.
  569. */
  570. int bitmap_print_list_to_buf(char *buf, const unsigned long *maskp,
  571. int nmaskbits, loff_t off, size_t count)
  572. {
  573. return bitmap_print_to_buf(true, buf, maskp, nmaskbits, off, count);
  574. }
  575. EXPORT_SYMBOL(bitmap_print_list_to_buf);
  576. /*
  577. * Region 9-38:4/10 describes the following bitmap structure:
  578. * 0 9 12 18 38 N
  579. * .........****......****......****..................
  580. * ^ ^ ^ ^ ^
  581. * start off group_len end nbits
  582. */
  583. struct region {
  584. unsigned int start;
  585. unsigned int off;
  586. unsigned int group_len;
  587. unsigned int end;
  588. unsigned int nbits;
  589. };
  590. static void bitmap_set_region(const struct region *r, unsigned long *bitmap)
  591. {
  592. unsigned int start;
  593. for (start = r->start; start <= r->end; start += r->group_len)
  594. bitmap_set(bitmap, start, min(r->end - start + 1, r->off));
  595. }
  596. static int bitmap_check_region(const struct region *r)
  597. {
  598. if (r->start > r->end || r->group_len == 0 || r->off > r->group_len)
  599. return -EINVAL;
  600. if (r->end >= r->nbits)
  601. return -ERANGE;
  602. return 0;
  603. }
  604. static const char *bitmap_getnum(const char *str, unsigned int *num,
  605. unsigned int lastbit)
  606. {
  607. unsigned long long n;
  608. unsigned int len;
  609. if (str[0] == 'N') {
  610. *num = lastbit;
  611. return str + 1;
  612. }
  613. len = _parse_integer(str, 10, &n);
  614. if (!len)
  615. return ERR_PTR(-EINVAL);
  616. if (len & KSTRTOX_OVERFLOW || n != (unsigned int)n)
  617. return ERR_PTR(-EOVERFLOW);
  618. *num = n;
  619. return str + len;
  620. }
  621. static inline bool end_of_str(char c)
  622. {
  623. return c == '\0' || c == '\n';
  624. }
  625. static inline bool __end_of_region(char c)
  626. {
  627. return isspace(c) || c == ',';
  628. }
  629. static inline bool end_of_region(char c)
  630. {
  631. return __end_of_region(c) || end_of_str(c);
  632. }
  633. /*
  634. * The format allows commas and whitespaces at the beginning
  635. * of the region.
  636. */
  637. static const char *bitmap_find_region(const char *str)
  638. {
  639. while (__end_of_region(*str))
  640. str++;
  641. return end_of_str(*str) ? NULL : str;
  642. }
  643. static const char *bitmap_find_region_reverse(const char *start, const char *end)
  644. {
  645. while (start <= end && __end_of_region(*end))
  646. end--;
  647. return end;
  648. }
  649. static const char *bitmap_parse_region(const char *str, struct region *r)
  650. {
  651. unsigned int lastbit = r->nbits - 1;
  652. if (!strncasecmp(str, "all", 3)) {
  653. r->start = 0;
  654. r->end = lastbit;
  655. str += 3;
  656. goto check_pattern;
  657. }
  658. str = bitmap_getnum(str, &r->start, lastbit);
  659. if (IS_ERR(str))
  660. return str;
  661. if (end_of_region(*str))
  662. goto no_end;
  663. if (*str != '-')
  664. return ERR_PTR(-EINVAL);
  665. str = bitmap_getnum(str + 1, &r->end, lastbit);
  666. if (IS_ERR(str))
  667. return str;
  668. check_pattern:
  669. if (end_of_region(*str))
  670. goto no_pattern;
  671. if (*str != ':')
  672. return ERR_PTR(-EINVAL);
  673. str = bitmap_getnum(str + 1, &r->off, lastbit);
  674. if (IS_ERR(str))
  675. return str;
  676. if (*str != '/')
  677. return ERR_PTR(-EINVAL);
  678. return bitmap_getnum(str + 1, &r->group_len, lastbit);
  679. no_end:
  680. r->end = r->start;
  681. no_pattern:
  682. r->off = r->end + 1;
  683. r->group_len = r->end + 1;
  684. return end_of_str(*str) ? NULL : str;
  685. }
  686. /**
  687. * bitmap_parselist - convert list format ASCII string to bitmap
  688. * @buf: read user string from this buffer; must be terminated
  689. * with a \0 or \n.
  690. * @maskp: write resulting mask here
  691. * @nmaskbits: number of bits in mask to be written
  692. *
  693. * Input format is a comma-separated list of decimal numbers and
  694. * ranges. Consecutively set bits are shown as two hyphen-separated
  695. * decimal numbers, the smallest and largest bit numbers set in
  696. * the range.
  697. * Optionally each range can be postfixed to denote that only parts of it
  698. * should be set. The range will divided to groups of specific size.
  699. * From each group will be used only defined amount of bits.
  700. * Syntax: range:used_size/group_size
  701. * Example: 0-1023:2/256 ==> 0,1,256,257,512,513,768,769
  702. * The value 'N' can be used as a dynamically substituted token for the
  703. * maximum allowed value; i.e (nmaskbits - 1). Keep in mind that it is
  704. * dynamic, so if system changes cause the bitmap width to change, such
  705. * as more cores in a CPU list, then any ranges using N will also change.
  706. *
  707. * Returns: 0 on success, -errno on invalid input strings. Error values:
  708. *
  709. * - ``-EINVAL``: wrong region format
  710. * - ``-EINVAL``: invalid character in string
  711. * - ``-ERANGE``: bit number specified too large for mask
  712. * - ``-EOVERFLOW``: integer overflow in the input parameters
  713. */
  714. int bitmap_parselist(const char *buf, unsigned long *maskp, int nmaskbits)
  715. {
  716. struct region r;
  717. long ret;
  718. r.nbits = nmaskbits;
  719. bitmap_zero(maskp, r.nbits);
  720. while (buf) {
  721. buf = bitmap_find_region(buf);
  722. if (buf == NULL)
  723. return 0;
  724. buf = bitmap_parse_region(buf, &r);
  725. if (IS_ERR(buf))
  726. return PTR_ERR(buf);
  727. ret = bitmap_check_region(&r);
  728. if (ret)
  729. return ret;
  730. bitmap_set_region(&r, maskp);
  731. }
  732. return 0;
  733. }
  734. EXPORT_SYMBOL(bitmap_parselist);
  735. /**
  736. * bitmap_parselist_user() - convert user buffer's list format ASCII
  737. * string to bitmap
  738. *
  739. * @ubuf: pointer to user buffer containing string.
  740. * @ulen: buffer size in bytes. If string is smaller than this
  741. * then it must be terminated with a \0.
  742. * @maskp: pointer to bitmap array that will contain result.
  743. * @nmaskbits: size of bitmap, in bits.
  744. *
  745. * Wrapper for bitmap_parselist(), providing it with user buffer.
  746. */
  747. int bitmap_parselist_user(const char __user *ubuf,
  748. unsigned int ulen, unsigned long *maskp,
  749. int nmaskbits)
  750. {
  751. char *buf;
  752. int ret;
  753. buf = memdup_user_nul(ubuf, ulen);
  754. if (IS_ERR(buf))
  755. return PTR_ERR(buf);
  756. ret = bitmap_parselist(buf, maskp, nmaskbits);
  757. kfree(buf);
  758. return ret;
  759. }
  760. EXPORT_SYMBOL(bitmap_parselist_user);
  761. static const char *bitmap_get_x32_reverse(const char *start,
  762. const char *end, u32 *num)
  763. {
  764. u32 ret = 0;
  765. int c, i;
  766. for (i = 0; i < 32; i += 4) {
  767. c = hex_to_bin(*end--);
  768. if (c < 0)
  769. return ERR_PTR(-EINVAL);
  770. ret |= c << i;
  771. if (start > end || __end_of_region(*end))
  772. goto out;
  773. }
  774. if (hex_to_bin(*end--) >= 0)
  775. return ERR_PTR(-EOVERFLOW);
  776. out:
  777. *num = ret;
  778. return end;
  779. }
  780. /**
  781. * bitmap_parse - convert an ASCII hex string into a bitmap.
  782. * @start: pointer to buffer containing string.
  783. * @buflen: buffer size in bytes. If string is smaller than this
  784. * then it must be terminated with a \0 or \n. In that case,
  785. * UINT_MAX may be provided instead of string length.
  786. * @maskp: pointer to bitmap array that will contain result.
  787. * @nmaskbits: size of bitmap, in bits.
  788. *
  789. * Commas group hex digits into chunks. Each chunk defines exactly 32
  790. * bits of the resultant bitmask. No chunk may specify a value larger
  791. * than 32 bits (%-EOVERFLOW), and if a chunk specifies a smaller value
  792. * then leading 0-bits are prepended. %-EINVAL is returned for illegal
  793. * characters. Grouping such as "1,,5", ",44", "," or "" is allowed.
  794. * Leading, embedded and trailing whitespace accepted.
  795. */
  796. int bitmap_parse(const char *start, unsigned int buflen,
  797. unsigned long *maskp, int nmaskbits)
  798. {
  799. const char *end = strnchrnul(start, buflen, '\n') - 1;
  800. int chunks = BITS_TO_U32(nmaskbits);
  801. u32 *bitmap = (u32 *)maskp;
  802. int unset_bit;
  803. int chunk;
  804. for (chunk = 0; ; chunk++) {
  805. end = bitmap_find_region_reverse(start, end);
  806. if (start > end)
  807. break;
  808. if (!chunks--)
  809. return -EOVERFLOW;
  810. #if defined(CONFIG_64BIT) && defined(__BIG_ENDIAN)
  811. end = bitmap_get_x32_reverse(start, end, &bitmap[chunk ^ 1]);
  812. #else
  813. end = bitmap_get_x32_reverse(start, end, &bitmap[chunk]);
  814. #endif
  815. if (IS_ERR(end))
  816. return PTR_ERR(end);
  817. }
  818. unset_bit = (BITS_TO_U32(nmaskbits) - chunks) * 32;
  819. if (unset_bit < nmaskbits) {
  820. bitmap_clear(maskp, unset_bit, nmaskbits - unset_bit);
  821. return 0;
  822. }
  823. if (find_next_bit(maskp, unset_bit, nmaskbits) != unset_bit)
  824. return -EOVERFLOW;
  825. return 0;
  826. }
  827. EXPORT_SYMBOL(bitmap_parse);
  828. /**
  829. * bitmap_pos_to_ord - find ordinal of set bit at given position in bitmap
  830. * @buf: pointer to a bitmap
  831. * @pos: a bit position in @buf (0 <= @pos < @nbits)
  832. * @nbits: number of valid bit positions in @buf
  833. *
  834. * Map the bit at position @pos in @buf (of length @nbits) to the
  835. * ordinal of which set bit it is. If it is not set or if @pos
  836. * is not a valid bit position, map to -1.
  837. *
  838. * If for example, just bits 4 through 7 are set in @buf, then @pos
  839. * values 4 through 7 will get mapped to 0 through 3, respectively,
  840. * and other @pos values will get mapped to -1. When @pos value 7
  841. * gets mapped to (returns) @ord value 3 in this example, that means
  842. * that bit 7 is the 3rd (starting with 0th) set bit in @buf.
  843. *
  844. * The bit positions 0 through @bits are valid positions in @buf.
  845. */
  846. static int bitmap_pos_to_ord(const unsigned long *buf, unsigned int pos, unsigned int nbits)
  847. {
  848. if (pos >= nbits || !test_bit(pos, buf))
  849. return -1;
  850. return bitmap_weight(buf, pos);
  851. }
  852. /**
  853. * bitmap_remap - Apply map defined by a pair of bitmaps to another bitmap
  854. * @dst: remapped result
  855. * @src: subset to be remapped
  856. * @old: defines domain of map
  857. * @new: defines range of map
  858. * @nbits: number of bits in each of these bitmaps
  859. *
  860. * Let @old and @new define a mapping of bit positions, such that
  861. * whatever position is held by the n-th set bit in @old is mapped
  862. * to the n-th set bit in @new. In the more general case, allowing
  863. * for the possibility that the weight 'w' of @new is less than the
  864. * weight of @old, map the position of the n-th set bit in @old to
  865. * the position of the m-th set bit in @new, where m == n % w.
  866. *
  867. * If either of the @old and @new bitmaps are empty, or if @src and
  868. * @dst point to the same location, then this routine copies @src
  869. * to @dst.
  870. *
  871. * The positions of unset bits in @old are mapped to themselves
  872. * (the identify map).
  873. *
  874. * Apply the above specified mapping to @src, placing the result in
  875. * @dst, clearing any bits previously set in @dst.
  876. *
  877. * For example, lets say that @old has bits 4 through 7 set, and
  878. * @new has bits 12 through 15 set. This defines the mapping of bit
  879. * position 4 to 12, 5 to 13, 6 to 14 and 7 to 15, and of all other
  880. * bit positions unchanged. So if say @src comes into this routine
  881. * with bits 1, 5 and 7 set, then @dst should leave with bits 1,
  882. * 13 and 15 set.
  883. */
  884. void bitmap_remap(unsigned long *dst, const unsigned long *src,
  885. const unsigned long *old, const unsigned long *new,
  886. unsigned int nbits)
  887. {
  888. unsigned int oldbit, w;
  889. if (dst == src) /* following doesn't handle inplace remaps */
  890. return;
  891. bitmap_zero(dst, nbits);
  892. w = bitmap_weight(new, nbits);
  893. for_each_set_bit(oldbit, src, nbits) {
  894. int n = bitmap_pos_to_ord(old, oldbit, nbits);
  895. if (n < 0 || w == 0)
  896. set_bit(oldbit, dst); /* identity map */
  897. else
  898. set_bit(find_nth_bit(new, nbits, n % w), dst);
  899. }
  900. }
  901. EXPORT_SYMBOL(bitmap_remap);
  902. /**
  903. * bitmap_bitremap - Apply map defined by a pair of bitmaps to a single bit
  904. * @oldbit: bit position to be mapped
  905. * @old: defines domain of map
  906. * @new: defines range of map
  907. * @bits: number of bits in each of these bitmaps
  908. *
  909. * Let @old and @new define a mapping of bit positions, such that
  910. * whatever position is held by the n-th set bit in @old is mapped
  911. * to the n-th set bit in @new. In the more general case, allowing
  912. * for the possibility that the weight 'w' of @new is less than the
  913. * weight of @old, map the position of the n-th set bit in @old to
  914. * the position of the m-th set bit in @new, where m == n % w.
  915. *
  916. * The positions of unset bits in @old are mapped to themselves
  917. * (the identify map).
  918. *
  919. * Apply the above specified mapping to bit position @oldbit, returning
  920. * the new bit position.
  921. *
  922. * For example, lets say that @old has bits 4 through 7 set, and
  923. * @new has bits 12 through 15 set. This defines the mapping of bit
  924. * position 4 to 12, 5 to 13, 6 to 14 and 7 to 15, and of all other
  925. * bit positions unchanged. So if say @oldbit is 5, then this routine
  926. * returns 13.
  927. */
  928. int bitmap_bitremap(int oldbit, const unsigned long *old,
  929. const unsigned long *new, int bits)
  930. {
  931. int w = bitmap_weight(new, bits);
  932. int n = bitmap_pos_to_ord(old, oldbit, bits);
  933. if (n < 0 || w == 0)
  934. return oldbit;
  935. else
  936. return find_nth_bit(new, bits, n % w);
  937. }
  938. EXPORT_SYMBOL(bitmap_bitremap);
  939. #ifdef CONFIG_NUMA
  940. /**
  941. * bitmap_onto - translate one bitmap relative to another
  942. * @dst: resulting translated bitmap
  943. * @orig: original untranslated bitmap
  944. * @relmap: bitmap relative to which translated
  945. * @bits: number of bits in each of these bitmaps
  946. *
  947. * Set the n-th bit of @dst iff there exists some m such that the
  948. * n-th bit of @relmap is set, the m-th bit of @orig is set, and
  949. * the n-th bit of @relmap is also the m-th _set_ bit of @relmap.
  950. * (If you understood the previous sentence the first time your
  951. * read it, you're overqualified for your current job.)
  952. *
  953. * In other words, @orig is mapped onto (surjectively) @dst,
  954. * using the map { <n, m> | the n-th bit of @relmap is the
  955. * m-th set bit of @relmap }.
  956. *
  957. * Any set bits in @orig above bit number W, where W is the
  958. * weight of (number of set bits in) @relmap are mapped nowhere.
  959. * In particular, if for all bits m set in @orig, m >= W, then
  960. * @dst will end up empty. In situations where the possibility
  961. * of such an empty result is not desired, one way to avoid it is
  962. * to use the bitmap_fold() operator, below, to first fold the
  963. * @orig bitmap over itself so that all its set bits x are in the
  964. * range 0 <= x < W. The bitmap_fold() operator does this by
  965. * setting the bit (m % W) in @dst, for each bit (m) set in @orig.
  966. *
  967. * Example [1] for bitmap_onto():
  968. * Let's say @relmap has bits 30-39 set, and @orig has bits
  969. * 1, 3, 5, 7, 9 and 11 set. Then on return from this routine,
  970. * @dst will have bits 31, 33, 35, 37 and 39 set.
  971. *
  972. * When bit 0 is set in @orig, it means turn on the bit in
  973. * @dst corresponding to whatever is the first bit (if any)
  974. * that is turned on in @relmap. Since bit 0 was off in the
  975. * above example, we leave off that bit (bit 30) in @dst.
  976. *
  977. * When bit 1 is set in @orig (as in the above example), it
  978. * means turn on the bit in @dst corresponding to whatever
  979. * is the second bit that is turned on in @relmap. The second
  980. * bit in @relmap that was turned on in the above example was
  981. * bit 31, so we turned on bit 31 in @dst.
  982. *
  983. * Similarly, we turned on bits 33, 35, 37 and 39 in @dst,
  984. * because they were the 4th, 6th, 8th and 10th set bits
  985. * set in @relmap, and the 4th, 6th, 8th and 10th bits of
  986. * @orig (i.e. bits 3, 5, 7 and 9) were also set.
  987. *
  988. * When bit 11 is set in @orig, it means turn on the bit in
  989. * @dst corresponding to whatever is the twelfth bit that is
  990. * turned on in @relmap. In the above example, there were
  991. * only ten bits turned on in @relmap (30..39), so that bit
  992. * 11 was set in @orig had no affect on @dst.
  993. *
  994. * Example [2] for bitmap_fold() + bitmap_onto():
  995. * Let's say @relmap has these ten bits set::
  996. *
  997. * 40 41 42 43 45 48 53 61 74 95
  998. *
  999. * (for the curious, that's 40 plus the first ten terms of the
  1000. * Fibonacci sequence.)
  1001. *
  1002. * Further lets say we use the following code, invoking
  1003. * bitmap_fold() then bitmap_onto, as suggested above to
  1004. * avoid the possibility of an empty @dst result::
  1005. *
  1006. * unsigned long *tmp; // a temporary bitmap's bits
  1007. *
  1008. * bitmap_fold(tmp, orig, bitmap_weight(relmap, bits), bits);
  1009. * bitmap_onto(dst, tmp, relmap, bits);
  1010. *
  1011. * Then this table shows what various values of @dst would be, for
  1012. * various @orig's. I list the zero-based positions of each set bit.
  1013. * The tmp column shows the intermediate result, as computed by
  1014. * using bitmap_fold() to fold the @orig bitmap modulo ten
  1015. * (the weight of @relmap):
  1016. *
  1017. * =============== ============== =================
  1018. * @orig tmp @dst
  1019. * 0 0 40
  1020. * 1 1 41
  1021. * 9 9 95
  1022. * 10 0 40 [#f1]_
  1023. * 1 3 5 7 1 3 5 7 41 43 48 61
  1024. * 0 1 2 3 4 0 1 2 3 4 40 41 42 43 45
  1025. * 0 9 18 27 0 9 8 7 40 61 74 95
  1026. * 0 10 20 30 0 40
  1027. * 0 11 22 33 0 1 2 3 40 41 42 43
  1028. * 0 12 24 36 0 2 4 6 40 42 45 53
  1029. * 78 102 211 1 2 8 41 42 74 [#f1]_
  1030. * =============== ============== =================
  1031. *
  1032. * .. [#f1]
  1033. *
  1034. * For these marked lines, if we hadn't first done bitmap_fold()
  1035. * into tmp, then the @dst result would have been empty.
  1036. *
  1037. * If either of @orig or @relmap is empty (no set bits), then @dst
  1038. * will be returned empty.
  1039. *
  1040. * If (as explained above) the only set bits in @orig are in positions
  1041. * m where m >= W, (where W is the weight of @relmap) then @dst will
  1042. * once again be returned empty.
  1043. *
  1044. * All bits in @dst not set by the above rule are cleared.
  1045. */
  1046. void bitmap_onto(unsigned long *dst, const unsigned long *orig,
  1047. const unsigned long *relmap, unsigned int bits)
  1048. {
  1049. unsigned int n, m; /* same meaning as in above comment */
  1050. if (dst == orig) /* following doesn't handle inplace mappings */
  1051. return;
  1052. bitmap_zero(dst, bits);
  1053. /*
  1054. * The following code is a more efficient, but less
  1055. * obvious, equivalent to the loop:
  1056. * for (m = 0; m < bitmap_weight(relmap, bits); m++) {
  1057. * n = find_nth_bit(orig, bits, m);
  1058. * if (test_bit(m, orig))
  1059. * set_bit(n, dst);
  1060. * }
  1061. */
  1062. m = 0;
  1063. for_each_set_bit(n, relmap, bits) {
  1064. /* m == bitmap_pos_to_ord(relmap, n, bits) */
  1065. if (test_bit(m, orig))
  1066. set_bit(n, dst);
  1067. m++;
  1068. }
  1069. }
  1070. /**
  1071. * bitmap_fold - fold larger bitmap into smaller, modulo specified size
  1072. * @dst: resulting smaller bitmap
  1073. * @orig: original larger bitmap
  1074. * @sz: specified size
  1075. * @nbits: number of bits in each of these bitmaps
  1076. *
  1077. * For each bit oldbit in @orig, set bit oldbit mod @sz in @dst.
  1078. * Clear all other bits in @dst. See further the comment and
  1079. * Example [2] for bitmap_onto() for why and how to use this.
  1080. */
  1081. void bitmap_fold(unsigned long *dst, const unsigned long *orig,
  1082. unsigned int sz, unsigned int nbits)
  1083. {
  1084. unsigned int oldbit;
  1085. if (dst == orig) /* following doesn't handle inplace mappings */
  1086. return;
  1087. bitmap_zero(dst, nbits);
  1088. for_each_set_bit(oldbit, orig, nbits)
  1089. set_bit(oldbit % sz, dst);
  1090. }
  1091. #endif /* CONFIG_NUMA */
  1092. /*
  1093. * Common code for bitmap_*_region() routines.
  1094. * bitmap: array of unsigned longs corresponding to the bitmap
  1095. * pos: the beginning of the region
  1096. * order: region size (log base 2 of number of bits)
  1097. * reg_op: operation(s) to perform on that region of bitmap
  1098. *
  1099. * Can set, verify and/or release a region of bits in a bitmap,
  1100. * depending on which combination of REG_OP_* flag bits is set.
  1101. *
  1102. * A region of a bitmap is a sequence of bits in the bitmap, of
  1103. * some size '1 << order' (a power of two), aligned to that same
  1104. * '1 << order' power of two.
  1105. *
  1106. * Returns 1 if REG_OP_ISFREE succeeds (region is all zero bits).
  1107. * Returns 0 in all other cases and reg_ops.
  1108. */
  1109. enum {
  1110. REG_OP_ISFREE, /* true if region is all zero bits */
  1111. REG_OP_ALLOC, /* set all bits in region */
  1112. REG_OP_RELEASE, /* clear all bits in region */
  1113. };
  1114. static int __reg_op(unsigned long *bitmap, unsigned int pos, int order, int reg_op)
  1115. {
  1116. int nbits_reg; /* number of bits in region */
  1117. int index; /* index first long of region in bitmap */
  1118. int offset; /* bit offset region in bitmap[index] */
  1119. int nlongs_reg; /* num longs spanned by region in bitmap */
  1120. int nbitsinlong; /* num bits of region in each spanned long */
  1121. unsigned long mask; /* bitmask for one long of region */
  1122. int i; /* scans bitmap by longs */
  1123. int ret = 0; /* return value */
  1124. /*
  1125. * Either nlongs_reg == 1 (for small orders that fit in one long)
  1126. * or (offset == 0 && mask == ~0UL) (for larger multiword orders.)
  1127. */
  1128. nbits_reg = 1 << order;
  1129. index = pos / BITS_PER_LONG;
  1130. offset = pos - (index * BITS_PER_LONG);
  1131. nlongs_reg = BITS_TO_LONGS(nbits_reg);
  1132. nbitsinlong = min(nbits_reg, BITS_PER_LONG);
  1133. /*
  1134. * Can't do "mask = (1UL << nbitsinlong) - 1", as that
  1135. * overflows if nbitsinlong == BITS_PER_LONG.
  1136. */
  1137. mask = (1UL << (nbitsinlong - 1));
  1138. mask += mask - 1;
  1139. mask <<= offset;
  1140. switch (reg_op) {
  1141. case REG_OP_ISFREE:
  1142. for (i = 0; i < nlongs_reg; i++) {
  1143. if (bitmap[index + i] & mask)
  1144. goto done;
  1145. }
  1146. ret = 1; /* all bits in region free (zero) */
  1147. break;
  1148. case REG_OP_ALLOC:
  1149. for (i = 0; i < nlongs_reg; i++)
  1150. bitmap[index + i] |= mask;
  1151. break;
  1152. case REG_OP_RELEASE:
  1153. for (i = 0; i < nlongs_reg; i++)
  1154. bitmap[index + i] &= ~mask;
  1155. break;
  1156. }
  1157. done:
  1158. return ret;
  1159. }
  1160. /**
  1161. * bitmap_find_free_region - find a contiguous aligned mem region
  1162. * @bitmap: array of unsigned longs corresponding to the bitmap
  1163. * @bits: number of bits in the bitmap
  1164. * @order: region size (log base 2 of number of bits) to find
  1165. *
  1166. * Find a region of free (zero) bits in a @bitmap of @bits bits and
  1167. * allocate them (set them to one). Only consider regions of length
  1168. * a power (@order) of two, aligned to that power of two, which
  1169. * makes the search algorithm much faster.
  1170. *
  1171. * Return the bit offset in bitmap of the allocated region,
  1172. * or -errno on failure.
  1173. */
  1174. int bitmap_find_free_region(unsigned long *bitmap, unsigned int bits, int order)
  1175. {
  1176. unsigned int pos, end; /* scans bitmap by regions of size order */
  1177. for (pos = 0 ; (end = pos + (1U << order)) <= bits; pos = end) {
  1178. if (!__reg_op(bitmap, pos, order, REG_OP_ISFREE))
  1179. continue;
  1180. __reg_op(bitmap, pos, order, REG_OP_ALLOC);
  1181. return pos;
  1182. }
  1183. return -ENOMEM;
  1184. }
  1185. EXPORT_SYMBOL(bitmap_find_free_region);
  1186. /**
  1187. * bitmap_release_region - release allocated bitmap region
  1188. * @bitmap: array of unsigned longs corresponding to the bitmap
  1189. * @pos: beginning of bit region to release
  1190. * @order: region size (log base 2 of number of bits) to release
  1191. *
  1192. * This is the complement to __bitmap_find_free_region() and releases
  1193. * the found region (by clearing it in the bitmap).
  1194. *
  1195. * No return value.
  1196. */
  1197. void bitmap_release_region(unsigned long *bitmap, unsigned int pos, int order)
  1198. {
  1199. __reg_op(bitmap, pos, order, REG_OP_RELEASE);
  1200. }
  1201. EXPORT_SYMBOL(bitmap_release_region);
  1202. /**
  1203. * bitmap_allocate_region - allocate bitmap region
  1204. * @bitmap: array of unsigned longs corresponding to the bitmap
  1205. * @pos: beginning of bit region to allocate
  1206. * @order: region size (log base 2 of number of bits) to allocate
  1207. *
  1208. * Allocate (set bits in) a specified region of a bitmap.
  1209. *
  1210. * Return 0 on success, or %-EBUSY if specified region wasn't
  1211. * free (not all bits were zero).
  1212. */
  1213. int bitmap_allocate_region(unsigned long *bitmap, unsigned int pos, int order)
  1214. {
  1215. if (!__reg_op(bitmap, pos, order, REG_OP_ISFREE))
  1216. return -EBUSY;
  1217. return __reg_op(bitmap, pos, order, REG_OP_ALLOC);
  1218. }
  1219. EXPORT_SYMBOL(bitmap_allocate_region);
  1220. /**
  1221. * bitmap_copy_le - copy a bitmap, putting the bits into little-endian order.
  1222. * @dst: destination buffer
  1223. * @src: bitmap to copy
  1224. * @nbits: number of bits in the bitmap
  1225. *
  1226. * Require nbits % BITS_PER_LONG == 0.
  1227. */
  1228. #ifdef __BIG_ENDIAN
  1229. void bitmap_copy_le(unsigned long *dst, const unsigned long *src, unsigned int nbits)
  1230. {
  1231. unsigned int i;
  1232. for (i = 0; i < nbits/BITS_PER_LONG; i++) {
  1233. if (BITS_PER_LONG == 64)
  1234. dst[i] = cpu_to_le64(src[i]);
  1235. else
  1236. dst[i] = cpu_to_le32(src[i]);
  1237. }
  1238. }
  1239. EXPORT_SYMBOL(bitmap_copy_le);
  1240. #endif
  1241. unsigned long *bitmap_alloc(unsigned int nbits, gfp_t flags)
  1242. {
  1243. return kmalloc_array(BITS_TO_LONGS(nbits), sizeof(unsigned long),
  1244. flags);
  1245. }
  1246. EXPORT_SYMBOL(bitmap_alloc);
  1247. unsigned long *bitmap_zalloc(unsigned int nbits, gfp_t flags)
  1248. {
  1249. return bitmap_alloc(nbits, flags | __GFP_ZERO);
  1250. }
  1251. EXPORT_SYMBOL(bitmap_zalloc);
  1252. unsigned long *bitmap_alloc_node(unsigned int nbits, gfp_t flags, int node)
  1253. {
  1254. return kmalloc_array_node(BITS_TO_LONGS(nbits), sizeof(unsigned long),
  1255. flags, node);
  1256. }
  1257. EXPORT_SYMBOL(bitmap_alloc_node);
  1258. unsigned long *bitmap_zalloc_node(unsigned int nbits, gfp_t flags, int node)
  1259. {
  1260. return bitmap_alloc_node(nbits, flags | __GFP_ZERO, node);
  1261. }
  1262. EXPORT_SYMBOL(bitmap_zalloc_node);
  1263. void bitmap_free(const unsigned long *bitmap)
  1264. {
  1265. kfree(bitmap);
  1266. }
  1267. EXPORT_SYMBOL(bitmap_free);
  1268. static void devm_bitmap_free(void *data)
  1269. {
  1270. unsigned long *bitmap = data;
  1271. bitmap_free(bitmap);
  1272. }
  1273. unsigned long *devm_bitmap_alloc(struct device *dev,
  1274. unsigned int nbits, gfp_t flags)
  1275. {
  1276. unsigned long *bitmap;
  1277. int ret;
  1278. bitmap = bitmap_alloc(nbits, flags);
  1279. if (!bitmap)
  1280. return NULL;
  1281. ret = devm_add_action_or_reset(dev, devm_bitmap_free, bitmap);
  1282. if (ret)
  1283. return NULL;
  1284. return bitmap;
  1285. }
  1286. EXPORT_SYMBOL_GPL(devm_bitmap_alloc);
  1287. unsigned long *devm_bitmap_zalloc(struct device *dev,
  1288. unsigned int nbits, gfp_t flags)
  1289. {
  1290. return devm_bitmap_alloc(dev, nbits, flags | __GFP_ZERO);
  1291. }
  1292. EXPORT_SYMBOL_GPL(devm_bitmap_zalloc);
  1293. #if BITS_PER_LONG == 64
  1294. /**
  1295. * bitmap_from_arr32 - copy the contents of u32 array of bits to bitmap
  1296. * @bitmap: array of unsigned longs, the destination bitmap
  1297. * @buf: array of u32 (in host byte order), the source bitmap
  1298. * @nbits: number of bits in @bitmap
  1299. */
  1300. void bitmap_from_arr32(unsigned long *bitmap, const u32 *buf, unsigned int nbits)
  1301. {
  1302. unsigned int i, halfwords;
  1303. halfwords = DIV_ROUND_UP(nbits, 32);
  1304. for (i = 0; i < halfwords; i++) {
  1305. bitmap[i/2] = (unsigned long) buf[i];
  1306. if (++i < halfwords)
  1307. bitmap[i/2] |= ((unsigned long) buf[i]) << 32;
  1308. }
  1309. /* Clear tail bits in last word beyond nbits. */
  1310. if (nbits % BITS_PER_LONG)
  1311. bitmap[(halfwords - 1) / 2] &= BITMAP_LAST_WORD_MASK(nbits);
  1312. }
  1313. EXPORT_SYMBOL(bitmap_from_arr32);
  1314. /**
  1315. * bitmap_to_arr32 - copy the contents of bitmap to a u32 array of bits
  1316. * @buf: array of u32 (in host byte order), the dest bitmap
  1317. * @bitmap: array of unsigned longs, the source bitmap
  1318. * @nbits: number of bits in @bitmap
  1319. */
  1320. void bitmap_to_arr32(u32 *buf, const unsigned long *bitmap, unsigned int nbits)
  1321. {
  1322. unsigned int i, halfwords;
  1323. halfwords = DIV_ROUND_UP(nbits, 32);
  1324. for (i = 0; i < halfwords; i++) {
  1325. buf[i] = (u32) (bitmap[i/2] & UINT_MAX);
  1326. if (++i < halfwords)
  1327. buf[i] = (u32) (bitmap[i/2] >> 32);
  1328. }
  1329. /* Clear tail bits in last element of array beyond nbits. */
  1330. if (nbits % BITS_PER_LONG)
  1331. buf[halfwords - 1] &= (u32) (UINT_MAX >> ((-nbits) & 31));
  1332. }
  1333. EXPORT_SYMBOL(bitmap_to_arr32);
  1334. #endif
  1335. #if BITS_PER_LONG == 32
  1336. /**
  1337. * bitmap_from_arr64 - copy the contents of u64 array of bits to bitmap
  1338. * @bitmap: array of unsigned longs, the destination bitmap
  1339. * @buf: array of u64 (in host byte order), the source bitmap
  1340. * @nbits: number of bits in @bitmap
  1341. */
  1342. void bitmap_from_arr64(unsigned long *bitmap, const u64 *buf, unsigned int nbits)
  1343. {
  1344. int n;
  1345. for (n = nbits; n > 0; n -= 64) {
  1346. u64 val = *buf++;
  1347. *bitmap++ = val;
  1348. if (n > 32)
  1349. *bitmap++ = val >> 32;
  1350. }
  1351. /*
  1352. * Clear tail bits in the last word beyond nbits.
  1353. *
  1354. * Negative index is OK because here we point to the word next
  1355. * to the last word of the bitmap, except for nbits == 0, which
  1356. * is tested implicitly.
  1357. */
  1358. if (nbits % BITS_PER_LONG)
  1359. bitmap[-1] &= BITMAP_LAST_WORD_MASK(nbits);
  1360. }
  1361. EXPORT_SYMBOL(bitmap_from_arr64);
  1362. /**
  1363. * bitmap_to_arr64 - copy the contents of bitmap to a u64 array of bits
  1364. * @buf: array of u64 (in host byte order), the dest bitmap
  1365. * @bitmap: array of unsigned longs, the source bitmap
  1366. * @nbits: number of bits in @bitmap
  1367. */
  1368. void bitmap_to_arr64(u64 *buf, const unsigned long *bitmap, unsigned int nbits)
  1369. {
  1370. const unsigned long *end = bitmap + BITS_TO_LONGS(nbits);
  1371. while (bitmap < end) {
  1372. *buf = *bitmap++;
  1373. if (bitmap < end)
  1374. *buf |= (u64)(*bitmap++) << 32;
  1375. buf++;
  1376. }
  1377. /* Clear tail bits in the last element of array beyond nbits. */
  1378. if (nbits % 64)
  1379. buf[-1] &= GENMASK_ULL((nbits - 1) % 64, 0);
  1380. }
  1381. EXPORT_SYMBOL(bitmap_to_arr64);
  1382. #endif