xfs_bit.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Copyright (c) 2000-2005 Silicon Graphics, Inc.
  4. * All Rights Reserved.
  5. */
  6. #include "xfs.h"
  7. #include "xfs_log_format.h"
  8. #include "xfs_bit.h"
  9. /*
  10. * XFS bit manipulation routines, used in non-realtime code.
  11. */
  12. /*
  13. * Return whether bitmap is empty.
  14. * Size is number of words in the bitmap, which is padded to word boundary
  15. * Returns 1 for empty, 0 for non-empty.
  16. */
  17. int
  18. xfs_bitmap_empty(uint *map, uint size)
  19. {
  20. uint i;
  21. for (i = 0; i < size; i++) {
  22. if (map[i] != 0)
  23. return 0;
  24. }
  25. return 1;
  26. }
  27. /*
  28. * Count the number of contiguous bits set in the bitmap starting with bit
  29. * start_bit. Size is the size of the bitmap in words.
  30. */
  31. int
  32. xfs_contig_bits(uint *map, uint size, uint start_bit)
  33. {
  34. uint * p = ((unsigned int *) map) + (start_bit >> BIT_TO_WORD_SHIFT);
  35. uint result = 0;
  36. uint tmp;
  37. size <<= BIT_TO_WORD_SHIFT;
  38. ASSERT(start_bit < size);
  39. size -= start_bit & ~(NBWORD - 1);
  40. start_bit &= (NBWORD - 1);
  41. if (start_bit) {
  42. tmp = *p++;
  43. /* set to one first offset bits prior to start */
  44. tmp |= (~0U >> (NBWORD-start_bit));
  45. if (tmp != ~0U)
  46. goto found;
  47. result += NBWORD;
  48. size -= NBWORD;
  49. }
  50. while (size) {
  51. if ((tmp = *p++) != ~0U)
  52. goto found;
  53. result += NBWORD;
  54. size -= NBWORD;
  55. }
  56. return result - start_bit;
  57. found:
  58. return result + ffz(tmp) - start_bit;
  59. }
  60. /*
  61. * This takes the bit number to start looking from and
  62. * returns the next set bit from there. It returns -1
  63. * if there are no more bits set or the start bit is
  64. * beyond the end of the bitmap.
  65. *
  66. * Size is the number of words, not bytes, in the bitmap.
  67. */
  68. int xfs_next_bit(uint *map, uint size, uint start_bit)
  69. {
  70. uint * p = ((unsigned int *) map) + (start_bit >> BIT_TO_WORD_SHIFT);
  71. uint result = start_bit & ~(NBWORD - 1);
  72. uint tmp;
  73. size <<= BIT_TO_WORD_SHIFT;
  74. if (start_bit >= size)
  75. return -1;
  76. size -= result;
  77. start_bit &= (NBWORD - 1);
  78. if (start_bit) {
  79. tmp = *p++;
  80. /* set to zero first offset bits prior to start */
  81. tmp &= (~0U << start_bit);
  82. if (tmp != 0U)
  83. goto found;
  84. result += NBWORD;
  85. size -= NBWORD;
  86. }
  87. while (size) {
  88. if ((tmp = *p++) != 0U)
  89. goto found;
  90. result += NBWORD;
  91. size -= NBWORD;
  92. }
  93. return -1;
  94. found:
  95. return result + ffs(tmp) - 1;
  96. }