1 /* SPDX-License-Identifier: GPL-2.0-or-later */ 2 /* 3 * AES block cipher using AES-NI instructions 4 * 5 * Copyright 2026 Google LLC 6 */ 7 8 #include <asm/fpu/api.h> 9 10 static __ro_after_init DEFINE_STATIC_KEY_FALSE(have_aes); 11 12 void aes128_expandkey_aesni(u32 rndkeys[], u32 *inv_rndkeys, 13 const u8 in_key[AES_KEYSIZE_128]); 14 void aes256_expandkey_aesni(u32 rndkeys[], u32 *inv_rndkeys, 15 const u8 in_key[AES_KEYSIZE_256]); 16 void aes_encrypt_aesni(const u32 rndkeys[], int nrounds, 17 u8 out[AES_BLOCK_SIZE], const u8 in[AES_BLOCK_SIZE]); 18 void aes_decrypt_aesni(const u32 inv_rndkeys[], int nrounds, 19 u8 out[AES_BLOCK_SIZE], const u8 in[AES_BLOCK_SIZE]); 20 21 /* 22 * Expand an AES key using AES-NI if supported and usable or generic code 23 * otherwise. The expanded key format is compatible between the two cases. The 24 * outputs are @k->rndkeys (required) and @inv_k->inv_rndkeys (optional). 25 * 26 * We could just always use the generic key expansion code. AES key expansion 27 * is usually less performance-critical than AES en/decryption. However, 28 * there's still *some* value in speed here, as well as in non-key-dependent 29 * execution time which AES-NI provides. So, do use AES-NI to expand AES-128 30 * and AES-256 keys. (Don't bother with AES-192, as it's almost never used.) 31 */ 32 static void aes_preparekey_arch(union aes_enckey_arch *k, 33 union aes_invkey_arch *inv_k, 34 const u8 *in_key, int key_len, int nrounds) 35 { 36 u32 *rndkeys = k->rndkeys; 37 u32 *inv_rndkeys = inv_k ? inv_k->inv_rndkeys : NULL; 38 39 if (static_branch_likely(&have_aes) && key_len != AES_KEYSIZE_192 && 40 irq_fpu_usable()) { 41 kernel_fpu_begin(); 42 if (key_len == AES_KEYSIZE_128) 43 aes128_expandkey_aesni(rndkeys, inv_rndkeys, in_key); 44 else 45 aes256_expandkey_aesni(rndkeys, inv_rndkeys, in_key); 46 kernel_fpu_end(); 47 } else { 48 aes_expandkey_generic(rndkeys, inv_rndkeys, in_key, key_len); 49 } 50 } 51 52 static void aes_encrypt_arch(const struct aes_enckey *key, 53 u8 out[AES_BLOCK_SIZE], 54 const u8 in[AES_BLOCK_SIZE]) 55 { 56 if (static_branch_likely(&have_aes) && irq_fpu_usable()) { 57 kernel_fpu_begin(); 58 aes_encrypt_aesni(key->k.rndkeys, key->nrounds, out, in); 59 kernel_fpu_end(); 60 } else { 61 aes_encrypt_generic(key->k.rndkeys, key->nrounds, out, in); 62 } 63 } 64 65 static void aes_decrypt_arch(const struct aes_key *key, 66 u8 out[AES_BLOCK_SIZE], 67 const u8 in[AES_BLOCK_SIZE]) 68 { 69 if (static_branch_likely(&have_aes) && irq_fpu_usable()) { 70 kernel_fpu_begin(); 71 aes_decrypt_aesni(key->inv_k.inv_rndkeys, key->nrounds, 72 out, in); 73 kernel_fpu_end(); 74 } else { 75 aes_decrypt_generic(key->inv_k.inv_rndkeys, key->nrounds, 76 out, in); 77 } 78 } 79 80 #define aes_mod_init_arch aes_mod_init_arch 81 static void aes_mod_init_arch(void) 82 { 83 if (boot_cpu_has(X86_FEATURE_AES)) 84 static_branch_enable(&have_aes); 85 } 86