xfs_cksum.h 2.3 KB

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