find_next_bit.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /* find_next_bit.c: fallback find next bit implementation
  2. *
  3. * Copyright (C) 2004 Red Hat, Inc. All Rights Reserved.
  4. * Written by David Howells (dhowells@redhat.com)
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version
  9. * 2 of the License, or (at your option) any later version.
  10. */
  11. #include <linux/types.h>
  12. #include <linux/bitops.h>
  13. #define BITOP_WORD(nr) ((nr) / BITS_PER_LONG)
  14. /*
  15. * Find the next set bit in a memory region.
  16. */
  17. unsigned long find_next_bit(const unsigned long *addr, unsigned long size,
  18. unsigned long offset)
  19. {
  20. const unsigned long *p = addr + BITOP_WORD(offset);
  21. unsigned long result = offset & ~(BITS_PER_LONG-1);
  22. unsigned long tmp;
  23. if (offset >= size)
  24. return size;
  25. size -= result;
  26. offset %= BITS_PER_LONG;
  27. if (offset) {
  28. tmp = *(p++);
  29. tmp &= (~0UL << offset);
  30. if (size < BITS_PER_LONG)
  31. goto found_first;
  32. if (tmp)
  33. goto found_middle;
  34. size -= BITS_PER_LONG;
  35. result += BITS_PER_LONG;
  36. }
  37. while (size & ~(BITS_PER_LONG-1)) {
  38. if ((tmp = *(p++)))
  39. goto found_middle;
  40. result += BITS_PER_LONG;
  41. size -= BITS_PER_LONG;
  42. }
  43. if (!size)
  44. return result;
  45. tmp = *p;
  46. found_first:
  47. tmp &= (~0UL >> (BITS_PER_LONG - size));
  48. if (tmp == 0UL) /* Are any bits set? */
  49. return result + size; /* Nope. */
  50. found_middle:
  51. return result + __ffs(tmp);
  52. }