1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Secure VM platform
4  *
5  * Copyright 2018 IBM Corporation
6  * Author: Anshuman Khandual <khandual@linux.vnet.ibm.com>
7  */
8 
9 #include <linux/mm.h>
10 #include <asm/machdep.h>
11 #include <asm/svm.h>
12 #include <asm/swiotlb.h>
13 #include <asm/ultravisor.h>
14 #include <asm/dtl.h>
15 
16 static int __init init_svm(void)
17 {
18 	if (!is_secure_guest())
19 		return 0;
20 
21 	/* Don't release the SWIOTLB buffer. */
22 	ppc_swiotlb_enable = 1;
23 
24 	/*
25 	 * Since the guest memory is inaccessible to the host, devices always
26 	 * need to use the SWIOTLB buffer for DMA even if dma_capable() says
27 	 * otherwise.
28 	 */
29 	swiotlb_force = SWIOTLB_FORCE;
30 
31 	/* Share the SWIOTLB buffer with the host. */
32 	swiotlb_update_mem_attributes();
33 
34 	return 0;
35 }
36 machine_early_initcall(pseries, init_svm);
37 
38 int set_memory_encrypted(unsigned long addr, int numpages)
39 {
40 	if (!PAGE_ALIGNED(addr))
41 		return -EINVAL;
42 
43 	uv_unshare_page(PHYS_PFN(__pa(addr)), numpages);
44 
45 	return 0;
46 }
47 
48 int set_memory_decrypted(unsigned long addr, int numpages)
49 {
50 	if (!PAGE_ALIGNED(addr))
51 		return -EINVAL;
52 
53 	uv_share_page(PHYS_PFN(__pa(addr)), numpages);
54 
55 	return 0;
56 }
57 
58 /* There's one dispatch log per CPU. */
59 #define NR_DTL_PAGE (DISPATCH_LOG_BYTES * CONFIG_NR_CPUS / PAGE_SIZE)
60 
61 static struct page *dtl_page_store[NR_DTL_PAGE];
62 static long dtl_nr_pages;
63 
64 static bool is_dtl_page_shared(struct page *page)
65 {
66 	long i;
67 
68 	for (i = 0; i < dtl_nr_pages; i++)
69 		if (dtl_page_store[i] == page)
70 			return true;
71 
72 	return false;
73 }
74 
75 void dtl_cache_ctor(void *addr)
76 {
77 	unsigned long pfn = PHYS_PFN(__pa(addr));
78 	struct page *page = pfn_to_page(pfn);
79 
80 	if (!is_dtl_page_shared(page)) {
81 		dtl_page_store[dtl_nr_pages] = page;
82 		dtl_nr_pages++;
83 		WARN_ON(dtl_nr_pages >= NR_DTL_PAGE);
84 		uv_share_page(pfn, 1);
85 	}
86 }
87