linux/arch/x86/mm/mem_encrypt.c
<<
>>
Prefs
   1/*
   2 * AMD Memory Encryption Support
   3 *
   4 * Copyright (C) 2016 Advanced Micro Devices, Inc.
   5 *
   6 * Author: Tom Lendacky <thomas.lendacky@amd.com>
   7 *
   8 * This program is free software; you can redistribute it and/or modify
   9 * it under the terms of the GNU General Public License version 2 as
  10 * published by the Free Software Foundation.
  11 */
  12
  13#define DISABLE_BRANCH_PROFILING
  14
  15#include <linux/linkage.h>
  16#include <linux/init.h>
  17#include <linux/mm.h>
  18#include <linux/dma-direct.h>
  19#include <linux/swiotlb.h>
  20#include <linux/mem_encrypt.h>
  21#include <linux/device.h>
  22#include <linux/kernel.h>
  23#include <linux/bitops.h>
  24#include <linux/dma-mapping.h>
  25
  26#include <asm/tlbflush.h>
  27#include <asm/fixmap.h>
  28#include <asm/setup.h>
  29#include <asm/bootparam.h>
  30#include <asm/set_memory.h>
  31#include <asm/cacheflush.h>
  32#include <asm/processor-flags.h>
  33#include <asm/msr.h>
  34#include <asm/cmdline.h>
  35
  36#include "mm_internal.h"
  37
  38/*
  39 * Since SME related variables are set early in the boot process they must
  40 * reside in the .data section so as not to be zeroed out when the .bss
  41 * section is later cleared.
  42 */
  43u64 sme_me_mask __section(.data) = 0;
  44u64 sev_status __section(.data) = 0;
  45u64 sev_check_data __section(.data) = 0;
  46EXPORT_SYMBOL(sme_me_mask);
  47DEFINE_STATIC_KEY_FALSE(sev_enable_key);
  48EXPORT_SYMBOL_GPL(sev_enable_key);
  49
  50/* Buffer used for early in-place encryption by BSP, no locking needed */
  51static char sme_early_buffer[PAGE_SIZE] __aligned(PAGE_SIZE);
  52
  53/*
  54 * This routine does not change the underlying encryption setting of the
  55 * page(s) that map this memory. It assumes that eventually the memory is
  56 * meant to be accessed as either encrypted or decrypted but the contents
  57 * are currently not in the desired state.
  58 *
  59 * This routine follows the steps outlined in the AMD64 Architecture
  60 * Programmer's Manual Volume 2, Section 7.10.8 Encrypt-in-Place.
  61 */
  62static void __init __sme_early_enc_dec(resource_size_t paddr,
  63                                       unsigned long size, bool enc)
  64{
  65        void *src, *dst;
  66        size_t len;
  67
  68        if (!sme_me_mask)
  69                return;
  70
  71        wbinvd();
  72
  73        /*
  74         * There are limited number of early mapping slots, so map (at most)
  75         * one page at time.
  76         */
  77        while (size) {
  78                len = min_t(size_t, sizeof(sme_early_buffer), size);
  79
  80                /*
  81                 * Create mappings for the current and desired format of
  82                 * the memory. Use a write-protected mapping for the source.
  83                 */
  84                src = enc ? early_memremap_decrypted_wp(paddr, len) :
  85                            early_memremap_encrypted_wp(paddr, len);
  86
  87                dst = enc ? early_memremap_encrypted(paddr, len) :
  88                            early_memremap_decrypted(paddr, len);
  89
  90                /*
  91                 * If a mapping can't be obtained to perform the operation,
  92                 * then eventual access of that area in the desired mode
  93                 * will cause a crash.
  94                 */
  95                BUG_ON(!src || !dst);
  96
  97                /*
  98                 * Use a temporary buffer, of cache-line multiple size, to
  99                 * avoid data corruption as documented in the APM.
 100                 */
 101                memcpy(sme_early_buffer, src, len);
 102                memcpy(dst, sme_early_buffer, len);
 103
 104                early_memunmap(dst, len);
 105                early_memunmap(src, len);
 106
 107                paddr += len;
 108                size -= len;
 109        }
 110}
 111
 112void __init sme_early_encrypt(resource_size_t paddr, unsigned long size)
 113{
 114        __sme_early_enc_dec(paddr, size, true);
 115}
 116
 117void __init sme_early_decrypt(resource_size_t paddr, unsigned long size)
 118{
 119        __sme_early_enc_dec(paddr, size, false);
 120}
 121
 122static void __init __sme_early_map_unmap_mem(void *vaddr, unsigned long size,
 123                                             bool map)
 124{
 125        unsigned long paddr = (unsigned long)vaddr - __PAGE_OFFSET;
 126        pmdval_t pmd_flags, pmd;
 127
 128        /* Use early_pmd_flags but remove the encryption mask */
 129        pmd_flags = __sme_clr(early_pmd_flags);
 130
 131        do {
 132                pmd = map ? (paddr & PMD_MASK) + pmd_flags : 0;
 133                __early_make_pgtable((unsigned long)vaddr, pmd);
 134
 135                vaddr += PMD_SIZE;
 136                paddr += PMD_SIZE;
 137                size = (size <= PMD_SIZE) ? 0 : size - PMD_SIZE;
 138        } while (size);
 139
 140        __native_flush_tlb();
 141}
 142
 143void __init sme_unmap_bootdata(char *real_mode_data)
 144{
 145        struct boot_params *boot_data;
 146        unsigned long cmdline_paddr;
 147
 148        if (!sme_active())
 149                return;
 150
 151        /* Get the command line address before unmapping the real_mode_data */
 152        boot_data = (struct boot_params *)real_mode_data;
 153        cmdline_paddr = boot_data->hdr.cmd_line_ptr | ((u64)boot_data->ext_cmd_line_ptr << 32);
 154
 155        __sme_early_map_unmap_mem(real_mode_data, sizeof(boot_params), false);
 156
 157        if (!cmdline_paddr)
 158                return;
 159
 160        __sme_early_map_unmap_mem(__va(cmdline_paddr), COMMAND_LINE_SIZE, false);
 161}
 162
 163void __init sme_map_bootdata(char *real_mode_data)
 164{
 165        struct boot_params *boot_data;
 166        unsigned long cmdline_paddr;
 167
 168        if (!sme_active())
 169                return;
 170
 171        __sme_early_map_unmap_mem(real_mode_data, sizeof(boot_params), true);
 172
 173        /* Get the command line address after mapping the real_mode_data */
 174        boot_data = (struct boot_params *)real_mode_data;
 175        cmdline_paddr = boot_data->hdr.cmd_line_ptr | ((u64)boot_data->ext_cmd_line_ptr << 32);
 176
 177        if (!cmdline_paddr)
 178                return;
 179
 180        __sme_early_map_unmap_mem(__va(cmdline_paddr), COMMAND_LINE_SIZE, true);
 181}
 182
 183void __init sme_early_init(void)
 184{
 185        unsigned int i;
 186
 187        if (!sme_me_mask)
 188                return;
 189
 190        early_pmd_flags = __sme_set(early_pmd_flags);
 191
 192        __supported_pte_mask = __sme_set(__supported_pte_mask);
 193
 194        /* Update the protection map with memory encryption mask */
 195        for (i = 0; i < ARRAY_SIZE(protection_map); i++)
 196                protection_map[i] = pgprot_encrypted(protection_map[i]);
 197
 198        if (sev_active())
 199                swiotlb_force = SWIOTLB_FORCE;
 200}
 201
 202void __init sev_setup_arch(void)
 203{
 204        phys_addr_t total_mem = memblock_phys_mem_size();
 205        unsigned long size;
 206
 207        if (!sev_active())
 208                return;
 209
 210        /*
 211         * For SEV, all DMA has to occur via shared/unencrypted pages.
 212         * SEV uses SWIOTLB to make this happen without changing device
 213         * drivers. However, depending on the workload being run, the
 214         * default 64MB of SWIOTLB may not be enough and SWIOTLB may
 215         * run out of buffers for DMA, resulting in I/O errors and/or
 216         * performance degradation especially with high I/O workloads.
 217         *
 218         * Adjust the default size of SWIOTLB for SEV guests using
 219         * a percentage of guest memory for SWIOTLB buffers.
 220         * Also, as the SWIOTLB bounce buffer memory is allocated
 221         * from low memory, ensure that the adjusted size is within
 222         * the limits of low available memory.
 223         *
 224         * The percentage of guest memory used here for SWIOTLB buffers
 225         * is more of an approximation of the static adjustment which
 226         * 64MB for <1G, and ~128M to 256M for 1G-to-4G, i.e., the 6%
 227         */
 228        size = total_mem * 6 / 100;
 229        size = clamp_val(size, IO_TLB_DEFAULT_SIZE, SZ_1G);
 230        swiotlb_adjust_size(size);
 231}
 232
 233static void __init __set_clr_pte_enc(pte_t *kpte, int level, bool enc)
 234{
 235        pgprot_t old_prot, new_prot;
 236        unsigned long pfn, pa, size;
 237        pte_t new_pte;
 238
 239        switch (level) {
 240        case PG_LEVEL_4K:
 241                pfn = pte_pfn(*kpte);
 242                old_prot = pte_pgprot(*kpte);
 243                break;
 244        case PG_LEVEL_2M:
 245                pfn = pmd_pfn(*(pmd_t *)kpte);
 246                old_prot = pmd_pgprot(*(pmd_t *)kpte);
 247                break;
 248        case PG_LEVEL_1G:
 249                pfn = pud_pfn(*(pud_t *)kpte);
 250                old_prot = pud_pgprot(*(pud_t *)kpte);
 251                break;
 252        default:
 253                return;
 254        }
 255
 256        new_prot = old_prot;
 257        if (enc)
 258                pgprot_val(new_prot) |= _PAGE_ENC;
 259        else
 260                pgprot_val(new_prot) &= ~_PAGE_ENC;
 261
 262        /* If prot is same then do nothing. */
 263        if (pgprot_val(old_prot) == pgprot_val(new_prot))
 264                return;
 265
 266        pa = pfn << PAGE_SHIFT;
 267        size = page_level_size(level);
 268
 269        /*
 270         * We are going to perform in-place en-/decryption and change the
 271         * physical page attribute from C=1 to C=0 or vice versa. Flush the
 272         * caches to ensure that data gets accessed with the correct C-bit.
 273         */
 274        clflush_cache_range(__va(pa), size);
 275
 276        /* Encrypt/decrypt the contents in-place */
 277        if (enc)
 278                sme_early_encrypt(pa, size);
 279        else
 280                sme_early_decrypt(pa, size);
 281
 282        /* Change the page encryption mask. */
 283        new_pte = pfn_pte(pfn, new_prot);
 284        set_pte_atomic(kpte, new_pte);
 285}
 286
 287static int __init early_set_memory_enc_dec(unsigned long vaddr,
 288                                           unsigned long size, bool enc)
 289{
 290        unsigned long vaddr_end, vaddr_next;
 291        unsigned long psize, pmask;
 292        int split_page_size_mask;
 293        int level, ret;
 294        pte_t *kpte;
 295
 296        vaddr_next = vaddr;
 297        vaddr_end = vaddr + size;
 298
 299        for (; vaddr < vaddr_end; vaddr = vaddr_next) {
 300                kpte = lookup_address(vaddr, &level);
 301                if (!kpte || pte_none(*kpte)) {
 302                        ret = 1;
 303                        goto out;
 304                }
 305
 306                if (level == PG_LEVEL_4K) {
 307                        __set_clr_pte_enc(kpte, level, enc);
 308                        vaddr_next = (vaddr & PAGE_MASK) + PAGE_SIZE;
 309                        continue;
 310                }
 311
 312                psize = page_level_size(level);
 313                pmask = page_level_mask(level);
 314
 315                /*
 316                 * Check whether we can change the large page in one go.
 317                 * We request a split when the address is not aligned and
 318                 * the number of pages to set/clear encryption bit is smaller
 319                 * than the number of pages in the large page.
 320                 */
 321                if (vaddr == (vaddr & pmask) &&
 322                    ((vaddr_end - vaddr) >= psize)) {
 323                        __set_clr_pte_enc(kpte, level, enc);
 324                        vaddr_next = (vaddr & pmask) + psize;
 325                        continue;
 326                }
 327
 328                /*
 329                 * The virtual address is part of a larger page, create the next
 330                 * level page table mapping (4K or 2M). If it is part of a 2M
 331                 * page then we request a split of the large page into 4K
 332                 * chunks. A 1GB large page is split into 2M pages, resp.
 333                 */
 334                if (level == PG_LEVEL_2M)
 335                        split_page_size_mask = 0;
 336                else
 337                        split_page_size_mask = 1 << PG_LEVEL_2M;
 338
 339                /*
 340                 * kernel_physical_mapping_change() does not flush the TLBs, so
 341                 * a TLB flush is required after we exit from the for loop.
 342                 */
 343                kernel_physical_mapping_change(__pa(vaddr & pmask),
 344                                               __pa((vaddr_end & pmask) + psize),
 345                                               split_page_size_mask);
 346        }
 347
 348        ret = 0;
 349
 350out:
 351        __flush_tlb_all();
 352        return ret;
 353}
 354
 355int __init early_set_memory_decrypted(unsigned long vaddr, unsigned long size)
 356{
 357        return early_set_memory_enc_dec(vaddr, size, false);
 358}
 359
 360int __init early_set_memory_encrypted(unsigned long vaddr, unsigned long size)
 361{
 362        return early_set_memory_enc_dec(vaddr, size, true);
 363}
 364
 365/*
 366 * SME and SEV are very similar but they are not the same, so there are
 367 * times that the kernel will need to distinguish between SME and SEV. The
 368 * sme_active() and sev_active() functions are used for this.  When a
 369 * distinction isn't needed, the mem_encrypt_active() function can be used.
 370 *
 371 * The trampoline code is a good example for this requirement.  Before
 372 * paging is activated, SME will access all memory as decrypted, but SEV
 373 * will access all memory as encrypted.  So, when APs are being brought
 374 * up under SME the trampoline area cannot be encrypted, whereas under SEV
 375 * the trampoline area must be encrypted.
 376 */
 377bool sev_active(void)
 378{
 379        return sev_status & MSR_AMD64_SEV_ENABLED;
 380}
 381EXPORT_SYMBOL(sme_active);
 382
 383bool sme_active(void)
 384{
 385        return sme_me_mask && !sev_active();
 386}
 387EXPORT_SYMBOL_GPL(sev_active);
 388
 389/* Needs to be called from non-instrumentable code */
 390bool noinstr sev_es_active(void)
 391{
 392        return sev_status & MSR_AMD64_SEV_ES_ENABLED;
 393}
 394
 395/* Override for DMA direct allocation check - ARCH_HAS_FORCE_DMA_UNENCRYPTED */
 396bool force_dma_unencrypted(struct device *dev)
 397{
 398        /*
 399         * For SEV, all DMA must be to unencrypted addresses.
 400         */
 401        if (sev_active())
 402                return true;
 403
 404        /*
 405         * For SME, all DMA must be to unencrypted addresses if the
 406         * device does not support DMA to addresses that include the
 407         * encryption mask.
 408         */
 409        if (sme_active()) {
 410                u64 dma_enc_mask = DMA_BIT_MASK(__ffs64(sme_me_mask));
 411                u64 dma_dev_mask = min_not_zero(dev->coherent_dma_mask,
 412                                                dev->bus_dma_limit);
 413
 414                if (dma_dev_mask <= dma_enc_mask)
 415                        return true;
 416        }
 417
 418        return false;
 419}
 420
 421/* Architecture __weak replacement functions */
 422void __init mem_encrypt_free_decrypted_mem(void)
 423{
 424        unsigned long vaddr, vaddr_end, npages;
 425        int r;
 426
 427        vaddr = (unsigned long)__start_bss_decrypted_unused;
 428        vaddr_end = (unsigned long)__end_bss_decrypted;
 429        npages = (vaddr_end - vaddr) >> PAGE_SHIFT;
 430
 431        /*
 432         * The unused memory range was mapped decrypted, change the encryption
 433         * attribute from decrypted to encrypted before freeing it.
 434         */
 435        if (mem_encrypt_active()) {
 436                r = set_memory_encrypted(vaddr, npages);
 437                if (r) {
 438                        pr_warn("failed to free unused decrypted pages\n");
 439                        return;
 440                }
 441        }
 442
 443        free_init_pages("unused decrypted", vaddr, vaddr_end);
 444}
 445
 446static void print_mem_encrypt_feature_info(void)
 447{
 448        pr_info("AMD Memory Encryption Features active:");
 449
 450        /* Secure Memory Encryption */
 451        if (sme_active()) {
 452                /*
 453                 * SME is mutually exclusive with any of the SEV
 454                 * features below.
 455                 */
 456                pr_cont(" SME\n");
 457                return;
 458        }
 459
 460        /* Secure Encrypted Virtualization */
 461        if (sev_active())
 462                pr_cont(" SEV");
 463
 464        /* Encrypted Register State */
 465        if (sev_es_active())
 466                pr_cont(" SEV-ES");
 467
 468        pr_cont("\n");
 469}
 470
 471void __init mem_encrypt_init(void)
 472{
 473        if (!sme_me_mask)
 474                return;
 475
 476        /* Call into SWIOTLB to update the SWIOTLB DMA buffers */
 477        swiotlb_update_mem_attributes();
 478
 479        /*
 480         * With SEV, we need to unroll the rep string I/O instructions.
 481         */
 482        if (sev_active())
 483                static_branch_enable(&sev_enable_key);
 484
 485        print_mem_encrypt_feature_info();
 486}
 487
 488