xfs_cksum.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #ifndef _XFS_CKSUM_H
  2. #define _XFS_CKSUM_H 1
  3. #define XFS_CRC_SEED (~(__uint32_t)0)
  4. /*
  5. * Calculate the intermediate checksum for a buffer that has the CRC field
  6. * inside it. The offset of the 32bit crc fields is passed as the
  7. * cksum_offset parameter.
  8. */
  9. static inline __uint32_t
  10. xfs_start_cksum(char *buffer, size_t length, unsigned long cksum_offset)
  11. {
  12. __uint32_t zero = 0;
  13. __uint32_t crc;
  14. /* Calculate CRC up to the checksum. */
  15. crc = crc32c(XFS_CRC_SEED, buffer, cksum_offset);
  16. /* Skip checksum field */
  17. crc = crc32c(crc, &zero, sizeof(__u32));
  18. /* Calculate the rest of the CRC. */
  19. return crc32c(crc, &buffer[cksum_offset + sizeof(__be32)],
  20. length - (cksum_offset + sizeof(__be32)));
  21. }
  22. /*
  23. * Convert the intermediate checksum to the final ondisk format.
  24. *
  25. * The CRC32c calculation uses LE format even on BE machines, but returns the
  26. * result in host endian format. Hence we need to byte swap it back to LE format
  27. * so that it is consistent on disk.
  28. */
  29. static inline __le32
  30. xfs_end_cksum(__uint32_t crc)
  31. {
  32. return ~cpu_to_le32(crc);
  33. }
  34. /*
  35. * Helper to generate the checksum for a buffer.
  36. */
  37. static inline void
  38. xfs_update_cksum(char *buffer, size_t length, unsigned long cksum_offset)
  39. {
  40. __uint32_t crc = xfs_start_cksum(buffer, length, cksum_offset);
  41. *(__le32 *)(buffer + cksum_offset) = xfs_end_cksum(crc);
  42. }
  43. /*
  44. * Helper to verify the checksum for a buffer.
  45. */
  46. static inline int
  47. xfs_verify_cksum(char *buffer, size_t length, unsigned long cksum_offset)
  48. {
  49. __uint32_t crc = xfs_start_cksum(buffer, length, cksum_offset);
  50. return *(__le32 *)(buffer + cksum_offset) == xfs_end_cksum(crc);
  51. }
  52. #endif /* _XFS_CKSUM_H */