memweight.c 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <linux/export.h>
  3. #include <linux/bug.h>
  4. #include <linux/bitmap.h>
  5. /**
  6. * memweight - count the total number of bits set in memory area
  7. * @ptr: pointer to the start of the area
  8. * @bytes: the size of the area
  9. */
  10. size_t memweight(const void *ptr, size_t bytes)
  11. {
  12. size_t ret = 0;
  13. size_t longs;
  14. const unsigned char *bitmap = ptr;
  15. for (; bytes > 0 && ((unsigned long)bitmap) % sizeof(long);
  16. bytes--, bitmap++)
  17. ret += hweight8(*bitmap);
  18. longs = bytes / sizeof(long);
  19. if (longs) {
  20. BUG_ON(longs >= INT_MAX / BITS_PER_LONG);
  21. ret += bitmap_weight((unsigned long *)bitmap,
  22. longs * BITS_PER_LONG);
  23. bytes -= longs * sizeof(long);
  24. bitmap += longs * sizeof(long);
  25. }
  26. /*
  27. * The reason that this last loop is distinct from the preceding
  28. * bitmap_weight() call is to compute 1-bits in the last region smaller
  29. * than sizeof(long) properly on big-endian systems.
  30. */
  31. for (; bytes > 0; bytes--, bitmap++)
  32. ret += hweight8(*bitmap);
  33. return ret;
  34. }
  35. EXPORT_SYMBOL(memweight);