utils.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * Crypto library utility functions
  4. *
  5. * Copyright (c) 2006 Herbert Xu <[email protected]>
  6. */
  7. #include <asm/unaligned.h>
  8. #include <crypto/algapi.h>
  9. #include <linux/module.h>
  10. /*
  11. * XOR @len bytes from @src1 and @src2 together, writing the result to @dst
  12. * (which may alias one of the sources). Don't call this directly; call
  13. * crypto_xor() or crypto_xor_cpy() instead.
  14. */
  15. void __crypto_xor(u8 *dst, const u8 *src1, const u8 *src2, unsigned int len)
  16. {
  17. int relalign = 0;
  18. if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) {
  19. int size = sizeof(unsigned long);
  20. int d = (((unsigned long)dst ^ (unsigned long)src1) |
  21. ((unsigned long)dst ^ (unsigned long)src2)) &
  22. (size - 1);
  23. relalign = d ? 1 << __ffs(d) : size;
  24. /*
  25. * If we care about alignment, process as many bytes as
  26. * needed to advance dst and src to values whose alignments
  27. * equal their relative alignment. This will allow us to
  28. * process the remainder of the input using optimal strides.
  29. */
  30. while (((unsigned long)dst & (relalign - 1)) && len > 0) {
  31. *dst++ = *src1++ ^ *src2++;
  32. len--;
  33. }
  34. }
  35. while (IS_ENABLED(CONFIG_64BIT) && len >= 8 && !(relalign & 7)) {
  36. if (IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) {
  37. u64 l = get_unaligned((u64 *)src1) ^
  38. get_unaligned((u64 *)src2);
  39. put_unaligned(l, (u64 *)dst);
  40. } else {
  41. *(u64 *)dst = *(u64 *)src1 ^ *(u64 *)src2;
  42. }
  43. dst += 8;
  44. src1 += 8;
  45. src2 += 8;
  46. len -= 8;
  47. }
  48. while (len >= 4 && !(relalign & 3)) {
  49. if (IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) {
  50. u32 l = get_unaligned((u32 *)src1) ^
  51. get_unaligned((u32 *)src2);
  52. put_unaligned(l, (u32 *)dst);
  53. } else {
  54. *(u32 *)dst = *(u32 *)src1 ^ *(u32 *)src2;
  55. }
  56. dst += 4;
  57. src1 += 4;
  58. src2 += 4;
  59. len -= 4;
  60. }
  61. while (len >= 2 && !(relalign & 1)) {
  62. if (IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) {
  63. u16 l = get_unaligned((u16 *)src1) ^
  64. get_unaligned((u16 *)src2);
  65. put_unaligned(l, (u16 *)dst);
  66. } else {
  67. *(u16 *)dst = *(u16 *)src1 ^ *(u16 *)src2;
  68. }
  69. dst += 2;
  70. src1 += 2;
  71. src2 += 2;
  72. len -= 2;
  73. }
  74. while (len--)
  75. *dst++ = *src1++ ^ *src2++;
  76. }
  77. EXPORT_SYMBOL_GPL(__crypto_xor);
  78. MODULE_LICENSE("GPL");