xfs_cksum.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. We do not modify the buffer during verification,
  8. * hence we have to split the CRC calculation across the cksum_offset.
  9. */
  10. static inline __uint32_t
  11. xfs_start_cksum_safe(char *buffer, size_t length, unsigned long cksum_offset)
  12. {
  13. __uint32_t zero = 0;
  14. __uint32_t crc;
  15. /* Calculate CRC up to the checksum. */
  16. crc = crc32c(XFS_CRC_SEED, buffer, cksum_offset);
  17. /* Skip checksum field */
  18. crc = crc32c(crc, &zero, sizeof(__u32));
  19. /* Calculate the rest of the CRC. */
  20. return crc32c(crc, &buffer[cksum_offset + sizeof(__be32)],
  21. length - (cksum_offset + sizeof(__be32)));
  22. }
  23. /*
  24. * Fast CRC method where the buffer is modified. Callers must have exclusive
  25. * access to the buffer while the calculation takes place.
  26. */
  27. static inline __uint32_t
  28. xfs_start_cksum_update(char *buffer, size_t length, unsigned long cksum_offset)
  29. {
  30. /* zero the CRC field */
  31. *(__le32 *)(buffer + cksum_offset) = 0;
  32. /* single pass CRC calculation for the entire buffer */
  33. return crc32c(XFS_CRC_SEED, buffer, length);
  34. }
  35. /*
  36. * Convert the intermediate checksum to the final ondisk format.
  37. *
  38. * The CRC32c calculation uses LE format even on BE machines, but returns the
  39. * result in host endian format. Hence we need to byte swap it back to LE format
  40. * so that it is consistent on disk.
  41. */
  42. static inline __le32
  43. xfs_end_cksum(__uint32_t crc)
  44. {
  45. return ~cpu_to_le32(crc);
  46. }
  47. /*
  48. * Helper to generate the checksum for a buffer.
  49. *
  50. * This modifies the buffer temporarily - callers must have exclusive
  51. * access to the buffer while the calculation takes place.
  52. */
  53. static inline void
  54. xfs_update_cksum(char *buffer, size_t length, unsigned long cksum_offset)
  55. {
  56. __uint32_t crc = xfs_start_cksum_update(buffer, length, cksum_offset);
  57. *(__le32 *)(buffer + cksum_offset) = xfs_end_cksum(crc);
  58. }
  59. /*
  60. * Helper to verify the checksum for a buffer.
  61. */
  62. static inline int
  63. xfs_verify_cksum(char *buffer, size_t length, unsigned long cksum_offset)
  64. {
  65. __uint32_t crc = xfs_start_cksum_safe(buffer, length, cksum_offset);
  66. return *(__le32 *)(buffer + cksum_offset) == xfs_end_cksum(crc);
  67. }
  68. #endif /* _XFS_CKSUM_H */