memweight.c 999 B

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