1 // SPDX-License-Identifier: GPL-2.0-only
3 * Memory Encryption Support Common Code
5 * Copyright (C) 2016 Advanced Micro Devices, Inc.
7 * Author: Tom Lendacky <thomas.lendacky@amd.com>
10 #include <linux/dma-direct.h>
11 #include <linux/dma-mapping.h>
12 #include <linux/swiotlb.h>
13 #include <linux/cc_platform.h>
14 #include <linux/mem_encrypt.h>
15 #include <linux/virtio_anchor.h>
17 /* Override for DMA direct allocation check - ARCH_HAS_FORCE_DMA_UNENCRYPTED */
18 bool force_dma_unencrypted(struct device *dev)
21 * For SEV, all DMA must be to unencrypted addresses.
23 if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT))
27 * For SME, all DMA must be to unencrypted addresses if the
28 * device does not support DMA to addresses that include the
31 if (cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT)) {
32 u64 dma_enc_mask = DMA_BIT_MASK(__ffs64(sme_me_mask));
33 u64 dma_dev_mask = min_not_zero(dev->coherent_dma_mask,
36 if (dma_dev_mask <= dma_enc_mask)
43 static void print_mem_encrypt_feature_info(void)
45 pr_info("Memory Encryption Features active: ");
49 pr_cont("Intel TDX\n");
54 /* Secure Memory Encryption */
55 if (cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT)) {
57 * SME is mutually exclusive with any of the SEV
64 /* Secure Encrypted Virtualization */
65 if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT))
68 /* Encrypted Register State */
69 if (cc_platform_has(CC_ATTR_GUEST_STATE_ENCRYPT))
72 /* Secure Nested Paging */
73 if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
83 /* Architecture __weak replacement functions */
84 void __init mem_encrypt_init(void)
86 if (!cc_platform_has(CC_ATTR_MEM_ENCRYPT))
89 /* Call into SWIOTLB to update the SWIOTLB DMA buffers */
90 swiotlb_update_mem_attributes();
92 print_mem_encrypt_feature_info();
95 void __init mem_encrypt_setup_arch(void)
97 phys_addr_t total_mem = memblock_phys_mem_size();
100 if (!cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT))
104 * For SEV and TDX, all DMA has to occur via shared/unencrypted pages.
105 * Kernel uses SWIOTLB to make this happen without changing device
106 * drivers. However, depending on the workload being run, the
107 * default 64MB of SWIOTLB may not be enough and SWIOTLB may
108 * run out of buffers for DMA, resulting in I/O errors and/or
109 * performance degradation especially with high I/O workloads.
111 * Adjust the default size of SWIOTLB using a percentage of guest
112 * memory for SWIOTLB buffers. Also, as the SWIOTLB bounce buffer
113 * memory is allocated from low memory, ensure that the adjusted size
114 * is within the limits of low available memory.
116 * The percentage of guest memory used here for SWIOTLB buffers
117 * is more of an approximation of the static adjustment which
118 * 64MB for <1G, and ~128M to 256M for 1G-to-4G, i.e., the 6%
120 size = total_mem * 6 / 100;
121 size = clamp_val(size, IO_TLB_DEFAULT_SIZE, SZ_1G);
122 swiotlb_adjust_size(size);
124 /* Set restricted memory access for virtio. */
125 virtio_set_mem_acc_cb(virtio_require_restricted_mem_acc);