1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Poly1305 authenticator algorithm, RFC7539. 4 * 5 * Copyright 2023- IBM Corp. All rights reserved. 6 */ 7 #include <asm/switch_to.h> 8 #include <crypto/internal/poly1305.h> 9 #include <linux/cpufeature.h> 10 #include <linux/jump_label.h> 11 #include <linux/kernel.h> 12 #include <linux/module.h> 13 #include <linux/unaligned.h> 14 15 asmlinkage void poly1305_p10le_4blocks(struct poly1305_block_state *state, const u8 *m, u32 mlen); 16 asmlinkage void poly1305_64s(struct poly1305_block_state *state, const u8 *m, u32 mlen, int highbit); 17 asmlinkage void poly1305_emit_64(const struct poly1305_state *state, const u32 nonce[4], u8 digest[POLY1305_DIGEST_SIZE]); 18 19 static __ro_after_init DEFINE_STATIC_KEY_FALSE(have_p10); 20 21 static void vsx_begin(void) 22 { 23 preempt_disable(); 24 enable_kernel_vsx(); 25 } 26 27 static void vsx_end(void) 28 { 29 disable_kernel_vsx(); 30 preempt_enable(); 31 } 32 33 void poly1305_block_init_arch(struct poly1305_block_state *dctx, 34 const u8 raw_key[POLY1305_BLOCK_SIZE]) 35 { 36 if (!static_key_enabled(&have_p10)) 37 return poly1305_block_init_generic(dctx, raw_key); 38 39 dctx->h = (struct poly1305_state){}; 40 dctx->core_r.key.r64[0] = get_unaligned_le64(raw_key + 0); 41 dctx->core_r.key.r64[1] = get_unaligned_le64(raw_key + 8); 42 } 43 EXPORT_SYMBOL_GPL(poly1305_block_init_arch); 44 45 void poly1305_blocks_arch(struct poly1305_block_state *state, const u8 *src, 46 unsigned int len, u32 padbit) 47 { 48 if (!static_key_enabled(&have_p10)) 49 return poly1305_blocks_generic(state, src, len, padbit); 50 vsx_begin(); 51 if (len >= POLY1305_BLOCK_SIZE * 4) { 52 poly1305_p10le_4blocks(state, src, len); 53 src += len - (len % (POLY1305_BLOCK_SIZE * 4)); 54 len %= POLY1305_BLOCK_SIZE * 4; 55 } 56 while (len >= POLY1305_BLOCK_SIZE) { 57 poly1305_64s(state, src, POLY1305_BLOCK_SIZE, padbit); 58 len -= POLY1305_BLOCK_SIZE; 59 src += POLY1305_BLOCK_SIZE; 60 } 61 vsx_end(); 62 } 63 EXPORT_SYMBOL_GPL(poly1305_blocks_arch); 64 65 void poly1305_emit_arch(const struct poly1305_state *state, 66 u8 digest[POLY1305_DIGEST_SIZE], 67 const u32 nonce[4]) 68 { 69 if (!static_key_enabled(&have_p10)) 70 return poly1305_emit_generic(state, digest, nonce); 71 poly1305_emit_64(state, nonce, digest); 72 } 73 EXPORT_SYMBOL_GPL(poly1305_emit_arch); 74 75 bool poly1305_is_arch_optimized(void) 76 { 77 return static_key_enabled(&have_p10); 78 } 79 EXPORT_SYMBOL(poly1305_is_arch_optimized); 80 81 static int __init poly1305_p10_init(void) 82 { 83 if (cpu_has_feature(CPU_FTR_ARCH_31)) 84 static_branch_enable(&have_p10); 85 return 0; 86 } 87 subsys_initcall(poly1305_p10_init); 88 89 static void __exit poly1305_p10_exit(void) 90 { 91 } 92 module_exit(poly1305_p10_exit); 93 94 MODULE_LICENSE("GPL"); 95 MODULE_AUTHOR("Danny Tsen <dtsen@linux.ibm.com>"); 96 MODULE_DESCRIPTION("Optimized Poly1305 for P10"); 97