1 /*
2  * Accelerated CRC-T10DIF using ARM NEON and Crypto Extensions instructions
3  *
4  * Copyright (C) 2016 Linaro Ltd <ard.biesheuvel@linaro.org>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 as
8  * published by the Free Software Foundation.
9  */
10 
11 #include <linux/crc-t10dif.h>
12 #include <linux/init.h>
13 #include <linux/kernel.h>
14 #include <linux/module.h>
15 #include <linux/string.h>
16 
17 #include <crypto/internal/hash.h>
18 
19 #include <asm/neon.h>
20 #include <asm/simd.h>
21 
22 #define CRC_T10DIF_PMULL_CHUNK_SIZE	16U
23 
24 asmlinkage u16 crc_t10dif_pmull(u16 init_crc, const u8 buf[], u32 len);
25 
26 static int crct10dif_init(struct shash_desc *desc)
27 {
28 	u16 *crc = shash_desc_ctx(desc);
29 
30 	*crc = 0;
31 	return 0;
32 }
33 
34 static int crct10dif_update(struct shash_desc *desc, const u8 *data,
35 			    unsigned int length)
36 {
37 	u16 *crc = shash_desc_ctx(desc);
38 	unsigned int l;
39 
40 	if (!may_use_simd()) {
41 		*crc = crc_t10dif_generic(*crc, data, length);
42 	} else {
43 		if (unlikely((u32)data % CRC_T10DIF_PMULL_CHUNK_SIZE)) {
44 			l = min_t(u32, length, CRC_T10DIF_PMULL_CHUNK_SIZE -
45 				  ((u32)data % CRC_T10DIF_PMULL_CHUNK_SIZE));
46 
47 			*crc = crc_t10dif_generic(*crc, data, l);
48 
49 			length -= l;
50 			data += l;
51 		}
52 		if (length > 0) {
53 			kernel_neon_begin();
54 			*crc = crc_t10dif_pmull(*crc, data, length);
55 			kernel_neon_end();
56 		}
57 	}
58 	return 0;
59 }
60 
61 static int crct10dif_final(struct shash_desc *desc, u8 *out)
62 {
63 	u16 *crc = shash_desc_ctx(desc);
64 
65 	*(u16 *)out = *crc;
66 	return 0;
67 }
68 
69 static struct shash_alg crc_t10dif_alg = {
70 	.digestsize		= CRC_T10DIF_DIGEST_SIZE,
71 	.init			= crct10dif_init,
72 	.update			= crct10dif_update,
73 	.final			= crct10dif_final,
74 	.descsize		= CRC_T10DIF_DIGEST_SIZE,
75 
76 	.base.cra_name		= "crct10dif",
77 	.base.cra_driver_name	= "crct10dif-arm-ce",
78 	.base.cra_priority	= 200,
79 	.base.cra_blocksize	= CRC_T10DIF_BLOCK_SIZE,
80 	.base.cra_module	= THIS_MODULE,
81 };
82 
83 static int __init crc_t10dif_mod_init(void)
84 {
85 	if (!(elf_hwcap2 & HWCAP2_PMULL))
86 		return -ENODEV;
87 
88 	return crypto_register_shash(&crc_t10dif_alg);
89 }
90 
91 static void __exit crc_t10dif_mod_exit(void)
92 {
93 	crypto_unregister_shash(&crc_t10dif_alg);
94 }
95 
96 module_init(crc_t10dif_mod_init);
97 module_exit(crc_t10dif_mod_exit);
98 
99 MODULE_AUTHOR("Ard Biesheuvel <ard.biesheuvel@linaro.org>");
100 MODULE_LICENSE("GPL v2");
101 MODULE_ALIAS_CRYPTO("crct10dif");
102