aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorLinus Torvalds <torvalds@linux-foundation.org>2018-10-25 20:57:35 -0400
committerLinus Torvalds <torvalds@linux-foundation.org>2018-10-25 20:57:35 -0400
commit0d1e8b8d2bcd3150d51754d8d0fdbf44dc88b0d3 (patch)
tree2794cb2347daa76b00160a6ffb68663f4138dcc7
parent83c4087ce468601501ecde4d0ec5b2abd5f57c31 (diff)
parent22a7cdcae6a4a3c8974899e62851d270956f58ce (diff)
Merge tag 'kvm-4.20-1' of git://git.kernel.org/pub/scm/virt/kvm/kvm
Pull KVM updates from Radim Krčmář: "ARM: - Improved guest IPA space support (32 to 52 bits) - RAS event delivery for 32bit - PMU fixes - Guest entry hardening - Various cleanups - Port of dirty_log_test selftest PPC: - Nested HV KVM support for radix guests on POWER9. The performance is much better than with PR KVM. Migration and arbitrary level of nesting is supported. - Disable nested HV-KVM on early POWER9 chips that need a particular hardware bug workaround - One VM per core mode to prevent potential data leaks - PCI pass-through optimization - merge ppc-kvm topic branch and kvm-ppc-fixes to get a better base s390: - Initial version of AP crypto virtualization via vfio-mdev - Improvement for vfio-ap - Set the host program identifier - Optimize page table locking x86: - Enable nested virtualization by default - Implement Hyper-V IPI hypercalls - Improve #PF and #DB handling - Allow guests to use Enlightened VMCS - Add migration selftests for VMCS and Enlightened VMCS - Allow coalesced PIO accesses - Add an option to perform nested VMCS host state consistency check through hardware - Automatic tuning of lapic_timer_advance_ns - Many fixes, minor improvements, and cleanups" * tag 'kvm-4.20-1' of git://git.kernel.org/pub/scm/virt/kvm/kvm: (204 commits) KVM/nVMX: Do not validate that posted_intr_desc_addr is page aligned Revert "kvm: x86: optimize dr6 restore" KVM: PPC: Optimize clearing TCEs for sparse tables x86/kvm/nVMX: tweak shadow fields selftests/kvm: add missing executables to .gitignore KVM: arm64: Safety check PSTATE when entering guest and handle IL KVM: PPC: Book3S HV: Don't use streamlined entry path on early POWER9 chips arm/arm64: KVM: Enable 32 bits kvm vcpu events support arm/arm64: KVM: Rename function kvm_arch_dev_ioctl_check_extension() KVM: arm64: Fix caching of host MDCR_EL2 value KVM: VMX: enable nested virtualization by default KVM/x86: Use 32bit xor to clear registers in svm.c kvm: x86: Introduce KVM_CAP_EXCEPTION_PAYLOAD kvm: vmx: Defer setting of DR6 until #DB delivery kvm: x86: Defer setting of CR2 until #PF delivery kvm: x86: Add payload operands to kvm_multiple_exception kvm: x86: Add exception payload fields to kvm_vcpu_events kvm: x86: Add has_payload and payload to kvm_queued_exception KVM: Documentation: Fix omission in struct kvm_vcpu_events KVM: selftests: add Enlightened VMCS test ...
-rw-r--r--Documentation/s390/vfio-ap.txt837
-rw-r--r--Documentation/virtual/kvm/api.txt135
-rw-r--r--MAINTAINERS12
-rw-r--r--arch/arm/include/asm/kvm_arm.h3
-rw-r--r--arch/arm/include/asm/kvm_host.h13
-rw-r--r--arch/arm/include/asm/kvm_mmu.h15
-rw-r--r--arch/arm/include/asm/stage2_pgtable.h54
-rw-r--r--arch/arm64/include/asm/cpufeature.h21
-rw-r--r--arch/arm64/include/asm/kvm_arm.h155
-rw-r--r--arch/arm64/include/asm/kvm_asm.h3
-rw-r--r--arch/arm64/include/asm/kvm_host.h18
-rw-r--r--arch/arm64/include/asm/kvm_hyp.h10
-rw-r--r--arch/arm64/include/asm/kvm_mmu.h42
-rw-r--r--arch/arm64/include/asm/ptrace.h3
-rw-r--r--arch/arm64/include/asm/stage2_pgtable-nopmd.h42
-rw-r--r--arch/arm64/include/asm/stage2_pgtable-nopud.h39
-rw-r--r--arch/arm64/include/asm/stage2_pgtable.h236
-rw-r--r--arch/arm64/kvm/guest.c6
-rw-r--r--arch/arm64/kvm/handle_exit.c7
-rw-r--r--arch/arm64/kvm/hyp/Makefile1
-rw-r--r--arch/arm64/kvm/hyp/hyp-entry.S16
-rw-r--r--arch/arm64/kvm/hyp/s2-setup.c90
-rw-r--r--arch/arm64/kvm/hyp/switch.c4
-rw-r--r--arch/arm64/kvm/hyp/sysreg-sr.c19
-rw-r--r--arch/arm64/kvm/hyp/tlb.c4
-rw-r--r--arch/arm64/kvm/reset.c108
-rw-r--r--arch/powerpc/include/asm/asm-prototypes.h21
-rw-r--r--arch/powerpc/include/asm/book3s/64/mmu-hash.h12
-rw-r--r--arch/powerpc/include/asm/book3s/64/tlbflush-radix.h1
-rw-r--r--arch/powerpc/include/asm/hvcall.h41
-rw-r--r--arch/powerpc/include/asm/iommu.h2
-rw-r--r--arch/powerpc/include/asm/kvm_asm.h4
-rw-r--r--arch/powerpc/include/asm/kvm_book3s.h45
-rw-r--r--arch/powerpc/include/asm/kvm_book3s_64.h118
-rw-r--r--arch/powerpc/include/asm/kvm_book3s_asm.h3
-rw-r--r--arch/powerpc/include/asm/kvm_booke.h4
-rw-r--r--arch/powerpc/include/asm/kvm_host.h16
-rw-r--r--arch/powerpc/include/asm/kvm_ppc.h8
-rw-r--r--arch/powerpc/include/asm/ppc-opcode.h1
-rw-r--r--arch/powerpc/include/asm/reg.h2
-rw-r--r--arch/powerpc/include/uapi/asm/kvm.h1
-rw-r--r--arch/powerpc/kernel/asm-offsets.c5
-rw-r--r--arch/powerpc/kernel/cpu_setup_power.S4
-rw-r--r--arch/powerpc/kvm/Makefile3
-rw-r--r--arch/powerpc/kvm/book3s.c46
-rw-r--r--arch/powerpc/kvm/book3s_64_mmu_hv.c7
-rw-r--r--arch/powerpc/kvm/book3s_64_mmu_radix.c718
-rw-r--r--arch/powerpc/kvm/book3s_64_vio.c94
-rw-r--r--arch/powerpc/kvm/book3s_64_vio_hv.c87
-rw-r--r--arch/powerpc/kvm/book3s_emulate.c13
-rw-r--r--arch/powerpc/kvm/book3s_hv.c873
-rw-r--r--arch/powerpc/kvm/book3s_hv_builtin.c92
-rw-r--r--arch/powerpc/kvm/book3s_hv_interrupts.S95
-rw-r--r--arch/powerpc/kvm/book3s_hv_nested.c1291
-rw-r--r--arch/powerpc/kvm/book3s_hv_ras.c10
-rw-r--r--arch/powerpc/kvm/book3s_hv_rm_xics.c13
-rw-r--r--arch/powerpc/kvm/book3s_hv_rmhandlers.S809
-rw-r--r--arch/powerpc/kvm/book3s_hv_tm.c6
-rw-r--r--arch/powerpc/kvm/book3s_hv_tm_builtin.c5
-rw-r--r--arch/powerpc/kvm/book3s_pr.c5
-rw-r--r--arch/powerpc/kvm/book3s_xics.c14
-rw-r--r--arch/powerpc/kvm/book3s_xive.c63
-rw-r--r--arch/powerpc/kvm/book3s_xive_template.c8
-rw-r--r--arch/powerpc/kvm/bookehv_interrupts.S8
-rw-r--r--arch/powerpc/kvm/emulate_loadstore.c1
-rw-r--r--arch/powerpc/kvm/powerpc.c15
-rw-r--r--arch/powerpc/kvm/tm.S250
-rw-r--r--arch/powerpc/kvm/trace_book3s.h1
-rw-r--r--arch/powerpc/mm/tlb-radix.c9
-rw-r--r--arch/s390/Kconfig11
-rw-r--r--arch/s390/include/asm/kvm_host.h15
-rw-r--r--arch/s390/include/uapi/asm/kvm.h2
-rw-r--r--arch/s390/kvm/kvm-s390.c184
-rw-r--r--arch/s390/kvm/kvm-s390.h1
-rw-r--r--arch/s390/kvm/vsie.c210
-rw-r--r--arch/s390/mm/gmap.c10
-rw-r--r--arch/s390/tools/gen_facilities.c2
-rw-r--r--arch/x86/include/asm/kvm_host.h70
-rw-r--r--arch/x86/include/asm/virtext.h2
-rw-r--r--arch/x86/include/asm/vmx.h13
-rw-r--r--arch/x86/include/uapi/asm/kvm.h8
-rw-r--r--arch/x86/kvm/hyperv.c280
-rw-r--r--arch/x86/kvm/hyperv.h4
-rw-r--r--arch/x86/kvm/lapic.c45
-rw-r--r--arch/x86/kvm/lapic.h2
-rw-r--r--arch/x86/kvm/mmu.c393
-rw-r--r--arch/x86/kvm/mmu.h13
-rw-r--r--arch/x86/kvm/mmu_audit.c12
-rw-r--r--arch/x86/kvm/paging_tmpl.h15
-rw-r--r--arch/x86/kvm/svm.c64
-rw-r--r--arch/x86/kvm/trace.h42
-rw-r--r--arch/x86/kvm/vmx.c2287
-rw-r--r--arch/x86/kvm/vmx_shadow_fields.h5
-rw-r--r--arch/x86/kvm/x86.c244
-rw-r--r--arch/x86/kvm/x86.h2
-rw-r--r--drivers/iommu/Kconfig8
-rw-r--r--drivers/s390/crypto/Makefile4
-rw-r--r--drivers/s390/crypto/vfio_ap_drv.c157
-rw-r--r--drivers/s390/crypto/vfio_ap_ops.c939
-rw-r--r--drivers/s390/crypto/vfio_ap_private.h88
-rw-r--r--drivers/vfio/vfio_iommu_spapr_tce.c23
-rw-r--r--include/linux/irqchip/arm-gic-v3.h5
-rw-r--r--include/uapi/linux/kvm.h26
-rw-r--r--include/uapi/linux/vfio.h2
-rw-r--r--tools/arch/x86/include/uapi/asm/kvm.h10
-rw-r--r--tools/include/uapi/linux/kvm.h5
-rw-r--r--tools/perf/arch/powerpc/util/book3s_hv_exits.h1
-rw-r--r--tools/testing/selftests/kvm/.gitignore14
-rw-r--r--tools/testing/selftests/kvm/Makefile39
-rw-r--r--tools/testing/selftests/kvm/dirty_log_test.c374
-rw-r--r--tools/testing/selftests/kvm/include/aarch64/processor.h55
-rw-r--r--tools/testing/selftests/kvm/include/evmcs.h1098
-rw-r--r--tools/testing/selftests/kvm/include/kvm_util.h169
-rw-r--r--tools/testing/selftests/kvm/include/sparsebit.h6
-rw-r--r--tools/testing/selftests/kvm/include/test_util.h6
-rw-r--r--tools/testing/selftests/kvm/include/x86_64/processor.h (renamed from tools/testing/selftests/kvm/include/x86.h)28
-rw-r--r--tools/testing/selftests/kvm/include/x86_64/vmx.h (renamed from tools/testing/selftests/kvm/include/vmx.h)35
-rw-r--r--tools/testing/selftests/kvm/lib/aarch64/processor.c311
-rw-r--r--tools/testing/selftests/kvm/lib/assert.c2
-rw-r--r--tools/testing/selftests/kvm/lib/kvm_util.c564
-rw-r--r--tools/testing/selftests/kvm/lib/kvm_util_internal.h33
-rw-r--r--tools/testing/selftests/kvm/lib/ucall.c144
-rw-r--r--tools/testing/selftests/kvm/lib/x86_64/processor.c (renamed from tools/testing/selftests/kvm/lib/x86.c)263
-rw-r--r--tools/testing/selftests/kvm/lib/x86_64/vmx.c (renamed from tools/testing/selftests/kvm/lib/vmx.c)55
-rw-r--r--tools/testing/selftests/kvm/x86_64/cr4_cpuid_sync_test.c (renamed from tools/testing/selftests/kvm/cr4_cpuid_sync_test.c)14
-rw-r--r--tools/testing/selftests/kvm/x86_64/evmcs_test.c160
-rw-r--r--tools/testing/selftests/kvm/x86_64/platform_info_test.c (renamed from tools/testing/selftests/kvm/platform_info_test.c)14
-rw-r--r--tools/testing/selftests/kvm/x86_64/set_sregs_test.c (renamed from tools/testing/selftests/kvm/set_sregs_test.c)2
-rw-r--r--tools/testing/selftests/kvm/x86_64/state_test.c (renamed from tools/testing/selftests/kvm/state_test.c)47
-rw-r--r--tools/testing/selftests/kvm/x86_64/sync_regs_test.c (renamed from tools/testing/selftests/kvm/sync_regs_test.c)2
-rw-r--r--tools/testing/selftests/kvm/x86_64/vmx_tsc_adjust_test.c (renamed from tools/testing/selftests/kvm/vmx_tsc_adjust_test.c)24
-rw-r--r--virt/kvm/arm/arm.c26
-rw-r--r--virt/kvm/arm/mmu.c128
-rw-r--r--virt/kvm/arm/vgic/vgic-its.c36
-rw-r--r--virt/kvm/arm/vgic/vgic-kvm-device.c2
-rw-r--r--virt/kvm/arm/vgic/vgic-mmio-v3.c2
-rw-r--r--virt/kvm/coalesced_mmio.c12
-rw-r--r--virt/kvm/kvm_main.c39
138 files changed, 12411 insertions, 3214 deletions
diff --git a/Documentation/s390/vfio-ap.txt b/Documentation/s390/vfio-ap.txt
new file mode 100644
index 000000000000..65167cfe4485
--- /dev/null
+++ b/Documentation/s390/vfio-ap.txt
@@ -0,0 +1,837 @@
1Introduction:
2============
3The Adjunct Processor (AP) facility is an IBM Z cryptographic facility comprised
4of three AP instructions and from 1 up to 256 PCIe cryptographic adapter cards.
5The AP devices provide cryptographic functions to all CPUs assigned to a
6linux system running in an IBM Z system LPAR.
7
8The AP adapter cards are exposed via the AP bus. The motivation for vfio-ap
9is to make AP cards available to KVM guests using the VFIO mediated device
10framework. This implementation relies considerably on the s390 virtualization
11facilities which do most of the hard work of providing direct access to AP
12devices.
13
14AP Architectural Overview:
15=========================
16To facilitate the comprehension of the design, let's start with some
17definitions:
18
19* AP adapter
20
21 An AP adapter is an IBM Z adapter card that can perform cryptographic
22 functions. There can be from 0 to 256 adapters assigned to an LPAR. Adapters
23 assigned to the LPAR in which a linux host is running will be available to
24 the linux host. Each adapter is identified by a number from 0 to 255; however,
25 the maximum adapter number is determined by machine model and/or adapter type.
26 When installed, an AP adapter is accessed by AP instructions executed by any
27 CPU.
28
29 The AP adapter cards are assigned to a given LPAR via the system's Activation
30 Profile which can be edited via the HMC. When the linux host system is IPL'd
31 in the LPAR, the AP bus detects the AP adapter cards assigned to the LPAR and
32 creates a sysfs device for each assigned adapter. For example, if AP adapters
33 4 and 10 (0x0a) are assigned to the LPAR, the AP bus will create the following
34 sysfs device entries:
35
36 /sys/devices/ap/card04
37 /sys/devices/ap/card0a
38
39 Symbolic links to these devices will also be created in the AP bus devices
40 sub-directory:
41
42 /sys/bus/ap/devices/[card04]
43 /sys/bus/ap/devices/[card04]
44
45* AP domain
46
47 An adapter is partitioned into domains. An adapter can hold up to 256 domains
48 depending upon the adapter type and hardware configuration. A domain is
49 identified by a number from 0 to 255; however, the maximum domain number is
50 determined by machine model and/or adapter type.. A domain can be thought of
51 as a set of hardware registers and memory used for processing AP commands. A
52 domain can be configured with a secure private key used for clear key
53 encryption. A domain is classified in one of two ways depending upon how it
54 may be accessed:
55
56 * Usage domains are domains that are targeted by an AP instruction to
57 process an AP command.
58
59 * Control domains are domains that are changed by an AP command sent to a
60 usage domain; for example, to set the secure private key for the control
61 domain.
62
63 The AP usage and control domains are assigned to a given LPAR via the system's
64 Activation Profile which can be edited via the HMC. When a linux host system
65 is IPL'd in the LPAR, the AP bus module detects the AP usage and control
66 domains assigned to the LPAR. The domain number of each usage domain and
67 adapter number of each AP adapter are combined to create AP queue devices
68 (see AP Queue section below). The domain number of each control domain will be
69 represented in a bitmask and stored in a sysfs file
70 /sys/bus/ap/ap_control_domain_mask. The bits in the mask, from most to least
71 significant bit, correspond to domains 0-255.
72
73* AP Queue
74
75 An AP queue is the means by which an AP command is sent to a usage domain
76 inside a specific adapter. An AP queue is identified by a tuple
77 comprised of an AP adapter ID (APID) and an AP queue index (APQI). The
78 APQI corresponds to a given usage domain number within the adapter. This tuple
79 forms an AP Queue Number (APQN) uniquely identifying an AP queue. AP
80 instructions include a field containing the APQN to identify the AP queue to
81 which the AP command is to be sent for processing.
82
83 The AP bus will create a sysfs device for each APQN that can be derived from
84 the cross product of the AP adapter and usage domain numbers detected when the
85 AP bus module is loaded. For example, if adapters 4 and 10 (0x0a) and usage
86 domains 6 and 71 (0x47) are assigned to the LPAR, the AP bus will create the
87 following sysfs entries:
88
89 /sys/devices/ap/card04/04.0006
90 /sys/devices/ap/card04/04.0047
91 /sys/devices/ap/card0a/0a.0006
92 /sys/devices/ap/card0a/0a.0047
93
94 The following symbolic links to these devices will be created in the AP bus
95 devices subdirectory:
96
97 /sys/bus/ap/devices/[04.0006]
98 /sys/bus/ap/devices/[04.0047]
99 /sys/bus/ap/devices/[0a.0006]
100 /sys/bus/ap/devices/[0a.0047]
101
102* AP Instructions:
103
104 There are three AP instructions:
105
106 * NQAP: to enqueue an AP command-request message to a queue
107 * DQAP: to dequeue an AP command-reply message from a queue
108 * PQAP: to administer the queues
109
110 AP instructions identify the domain that is targeted to process the AP
111 command; this must be one of the usage domains. An AP command may modify a
112 domain that is not one of the usage domains, but the modified domain
113 must be one of the control domains.
114
115AP and SIE:
116==========
117Let's now take a look at how AP instructions executed on a guest are interpreted
118by the hardware.
119
120A satellite control block called the Crypto Control Block (CRYCB) is attached to
121our main hardware virtualization control block. The CRYCB contains three fields
122to identify the adapters, usage domains and control domains assigned to the KVM
123guest:
124
125* The AP Mask (APM) field is a bit mask that identifies the AP adapters assigned
126 to the KVM guest. Each bit in the mask, from left to right (i.e. from most
127 significant to least significant bit in big endian order), corresponds to
128 an APID from 0-255. If a bit is set, the corresponding adapter is valid for
129 use by the KVM guest.
130
131* The AP Queue Mask (AQM) field is a bit mask identifying the AP usage domains
132 assigned to the KVM guest. Each bit in the mask, from left to right (i.e. from
133 most significant to least significant bit in big endian order), corresponds to
134 an AP queue index (APQI) from 0-255. If a bit is set, the corresponding queue
135 is valid for use by the KVM guest.
136
137* The AP Domain Mask field is a bit mask that identifies the AP control domains
138 assigned to the KVM guest. The ADM bit mask controls which domains can be
139 changed by an AP command-request message sent to a usage domain from the
140 guest. Each bit in the mask, from left to right (i.e. from most significant to
141 least significant bit in big endian order), corresponds to a domain from
142 0-255. If a bit is set, the corresponding domain can be modified by an AP
143 command-request message sent to a usage domain.
144
145If you recall from the description of an AP Queue, AP instructions include
146an APQN to identify the AP queue to which an AP command-request message is to be
147sent (NQAP and PQAP instructions), or from which a command-reply message is to
148be received (DQAP instruction). The validity of an APQN is defined by the matrix
149calculated from the APM and AQM; it is the cross product of all assigned adapter
150numbers (APM) with all assigned queue indexes (AQM). For example, if adapters 1
151and 2 and usage domains 5 and 6 are assigned to a guest, the APQNs (1,5), (1,6),
152(2,5) and (2,6) will be valid for the guest.
153
154The APQNs can provide secure key functionality - i.e., a private key is stored
155on the adapter card for each of its domains - so each APQN must be assigned to
156at most one guest or to the linux host.
157
158 Example 1: Valid configuration:
159 ------------------------------
160 Guest1: adapters 1,2 domains 5,6
161 Guest2: adapter 1,2 domain 7
162
163 This is valid because both guests have a unique set of APQNs:
164 Guest1 has APQNs (1,5), (1,6), (2,5), (2,6);
165 Guest2 has APQNs (1,7), (2,7)
166
167 Example 2: Valid configuration:
168 ------------------------------
169 Guest1: adapters 1,2 domains 5,6
170 Guest2: adapters 3,4 domains 5,6
171
172 This is also valid because both guests have a unique set of APQNs:
173 Guest1 has APQNs (1,5), (1,6), (2,5), (2,6);
174 Guest2 has APQNs (3,5), (3,6), (4,5), (4,6)
175
176 Example 3: Invalid configuration:
177 --------------------------------
178 Guest1: adapters 1,2 domains 5,6
179 Guest2: adapter 1 domains 6,7
180
181 This is an invalid configuration because both guests have access to
182 APQN (1,6).
183
184The Design:
185===========
186The design introduces three new objects:
187
1881. AP matrix device
1892. VFIO AP device driver (vfio_ap.ko)
1903. VFIO AP mediated matrix pass-through device
191
192The VFIO AP device driver
193-------------------------
194The VFIO AP (vfio_ap) device driver serves the following purposes:
195
1961. Provides the interfaces to secure APQNs for exclusive use of KVM guests.
197
1982. Sets up the VFIO mediated device interfaces to manage a mediated matrix
199 device and creates the sysfs interfaces for assigning adapters, usage
200 domains, and control domains comprising the matrix for a KVM guest.
201
2023. Configures the APM, AQM and ADM in the CRYCB referenced by a KVM guest's
203 SIE state description to grant the guest access to a matrix of AP devices
204
205Reserve APQNs for exclusive use of KVM guests
206---------------------------------------------
207The following block diagram illustrates the mechanism by which APQNs are
208reserved:
209
210 +------------------+
211 7 remove | |
212 +--------------------> cex4queue driver |
213 | | |
214 | +------------------+
215 |
216 |
217 | +------------------+ +-----------------+
218 | 5 register driver | | 3 create | |
219 | +----------------> Device core +----------> matrix device |
220 | | | | | |
221 | | +--------^---------+ +-----------------+
222 | | |
223 | | +-------------------+
224 | | +-----------------------------------+ |
225 | | | 4 register AP driver | | 2 register device
226 | | | | |
227+--------+---+-v---+ +--------+-------+-+
228| | | |
229| ap_bus +--------------------- > vfio_ap driver |
230| | 8 probe | |
231+--------^---------+ +--^--^------------+
2326 edit | | |
233 apmask | +-----------------------------+ | 9 mdev create
234 aqmask | | 1 modprobe |
235+--------+-----+---+ +----------------+-+ +------------------+
236| | | |8 create | mediated |
237| admin | | VFIO device core |---------> matrix |
238| + | | | device |
239+------+-+---------+ +--------^---------+ +--------^---------+
240 | | | |
241 | | 9 create vfio_ap-passthrough | |
242 | +------------------------------+ |
243 +-------------------------------------------------------------+
244 10 assign adapter/domain/control domain
245
246The process for reserving an AP queue for use by a KVM guest is:
247
2481. The administrator loads the vfio_ap device driver
2492. The vfio-ap driver during its initialization will register a single 'matrix'
250 device with the device core. This will serve as the parent device for
251 all mediated matrix devices used to configure an AP matrix for a guest.
2523. The /sys/devices/vfio_ap/matrix device is created by the device core
2534 The vfio_ap device driver will register with the AP bus for AP queue devices
254 of type 10 and higher (CEX4 and newer). The driver will provide the vfio_ap
255 driver's probe and remove callback interfaces. Devices older than CEX4 queues
256 are not supported to simplify the implementation by not needlessly
257 complicating the design by supporting older devices that will go out of
258 service in the relatively near future, and for which there are few older
259 systems around on which to test.
2605. The AP bus registers the vfio_ap device driver with the device core
2616. The administrator edits the AP adapter and queue masks to reserve AP queues
262 for use by the vfio_ap device driver.
2637. The AP bus removes the AP queues reserved for the vfio_ap driver from the
264 default zcrypt cex4queue driver.
2658. The AP bus probes the vfio_ap device driver to bind the queues reserved for
266 it.
2679. The administrator creates a passthrough type mediated matrix device to be
268 used by a guest
26910 The administrator assigns the adapters, usage domains and control domains
270 to be exclusively used by a guest.
271
272Set up the VFIO mediated device interfaces
273------------------------------------------
274The VFIO AP device driver utilizes the common interface of the VFIO mediated
275device core driver to:
276* Register an AP mediated bus driver to add a mediated matrix device to and
277 remove it from a VFIO group.
278* Create and destroy a mediated matrix device
279* Add a mediated matrix device to and remove it from the AP mediated bus driver
280* Add a mediated matrix device to and remove it from an IOMMU group
281
282The following high-level block diagram shows the main components and interfaces
283of the VFIO AP mediated matrix device driver:
284
285 +-------------+
286 | |
287 | +---------+ | mdev_register_driver() +--------------+
288 | | Mdev | +<-----------------------+ |
289 | | bus | | | vfio_mdev.ko |
290 | | driver | +----------------------->+ |<-> VFIO user
291 | +---------+ | probe()/remove() +--------------+ APIs
292 | |
293 | MDEV CORE |
294 | MODULE |
295 | mdev.ko |
296 | +---------+ | mdev_register_device() +--------------+
297 | |Physical | +<-----------------------+ |
298 | | device | | | vfio_ap.ko |<-> matrix
299 | |interface| +----------------------->+ | device
300 | +---------+ | callback +--------------+
301 +-------------+
302
303During initialization of the vfio_ap module, the matrix device is registered
304with an 'mdev_parent_ops' structure that provides the sysfs attribute
305structures, mdev functions and callback interfaces for managing the mediated
306matrix device.
307
308* sysfs attribute structures:
309 * supported_type_groups
310 The VFIO mediated device framework supports creation of user-defined
311 mediated device types. These mediated device types are specified
312 via the 'supported_type_groups' structure when a device is registered
313 with the mediated device framework. The registration process creates the
314 sysfs structures for each mediated device type specified in the
315 'mdev_supported_types' sub-directory of the device being registered. Along
316 with the device type, the sysfs attributes of the mediated device type are
317 provided.
318
319 The VFIO AP device driver will register one mediated device type for
320 passthrough devices:
321 /sys/devices/vfio_ap/matrix/mdev_supported_types/vfio_ap-passthrough
322 Only the read-only attributes required by the VFIO mdev framework will
323 be provided:
324 ... name
325 ... device_api
326 ... available_instances
327 ... device_api
328 Where:
329 * name: specifies the name of the mediated device type
330 * device_api: the mediated device type's API
331 * available_instances: the number of mediated matrix passthrough devices
332 that can be created
333 * device_api: specifies the VFIO API
334 * mdev_attr_groups
335 This attribute group identifies the user-defined sysfs attributes of the
336 mediated device. When a device is registered with the VFIO mediated device
337 framework, the sysfs attribute files identified in the 'mdev_attr_groups'
338 structure will be created in the mediated matrix device's directory. The
339 sysfs attributes for a mediated matrix device are:
340 * assign_adapter:
341 * unassign_adapter:
342 Write-only attributes for assigning/unassigning an AP adapter to/from the
343 mediated matrix device. To assign/unassign an adapter, the APID of the
344 adapter is echoed to the respective attribute file.
345 * assign_domain:
346 * unassign_domain:
347 Write-only attributes for assigning/unassigning an AP usage domain to/from
348 the mediated matrix device. To assign/unassign a domain, the domain
349 number of the the usage domain is echoed to the respective attribute
350 file.
351 * matrix:
352 A read-only file for displaying the APQNs derived from the cross product
353 of the adapter and domain numbers assigned to the mediated matrix device.
354 * assign_control_domain:
355 * unassign_control_domain:
356 Write-only attributes for assigning/unassigning an AP control domain
357 to/from the mediated matrix device. To assign/unassign a control domain,
358 the ID of the domain to be assigned/unassigned is echoed to the respective
359 attribute file.
360 * control_domains:
361 A read-only file for displaying the control domain numbers assigned to the
362 mediated matrix device.
363
364* functions:
365 * create:
366 allocates the ap_matrix_mdev structure used by the vfio_ap driver to:
367 * Store the reference to the KVM structure for the guest using the mdev
368 * Store the AP matrix configuration for the adapters, domains, and control
369 domains assigned via the corresponding sysfs attributes files
370 * remove:
371 deallocates the mediated matrix device's ap_matrix_mdev structure. This will
372 be allowed only if a running guest is not using the mdev.
373
374* callback interfaces
375 * open:
376 The vfio_ap driver uses this callback to register a
377 VFIO_GROUP_NOTIFY_SET_KVM notifier callback function for the mdev matrix
378 device. The open is invoked when QEMU connects the VFIO iommu group
379 for the mdev matrix device to the MDEV bus. Access to the KVM structure used
380 to configure the KVM guest is provided via this callback. The KVM structure,
381 is used to configure the guest's access to the AP matrix defined via the
382 mediated matrix device's sysfs attribute files.
383 * release:
384 unregisters the VFIO_GROUP_NOTIFY_SET_KVM notifier callback function for the
385 mdev matrix device and deconfigures the guest's AP matrix.
386
387Configure the APM, AQM and ADM in the CRYCB:
388-------------------------------------------
389Configuring the AP matrix for a KVM guest will be performed when the
390VFIO_GROUP_NOTIFY_SET_KVM notifier callback is invoked. The notifier
391function is called when QEMU connects to KVM. The guest's AP matrix is
392configured via it's CRYCB by:
393* Setting the bits in the APM corresponding to the APIDs assigned to the
394 mediated matrix device via its 'assign_adapter' interface.
395* Setting the bits in the AQM corresponding to the domains assigned to the
396 mediated matrix device via its 'assign_domain' interface.
397* Setting the bits in the ADM corresponding to the domain dIDs assigned to the
398 mediated matrix device via its 'assign_control_domains' interface.
399
400The CPU model features for AP
401-----------------------------
402The AP stack relies on the presence of the AP instructions as well as two
403facilities: The AP Facilities Test (APFT) facility; and the AP Query
404Configuration Information (QCI) facility. These features/facilities are made
405available to a KVM guest via the following CPU model features:
406
4071. ap: Indicates whether the AP instructions are installed on the guest. This
408 feature will be enabled by KVM only if the AP instructions are installed
409 on the host.
410
4112. apft: Indicates the APFT facility is available on the guest. This facility
412 can be made available to the guest only if it is available on the host (i.e.,
413 facility bit 15 is set).
414
4153. apqci: Indicates the AP QCI facility is available on the guest. This facility
416 can be made available to the guest only if it is available on the host (i.e.,
417 facility bit 12 is set).
418
419Note: If the user chooses to specify a CPU model different than the 'host'
420model to QEMU, the CPU model features and facilities need to be turned on
421explicitly; for example:
422
423 /usr/bin/qemu-system-s390x ... -cpu z13,ap=on,apqci=on,apft=on
424
425A guest can be precluded from using AP features/facilities by turning them off
426explicitly; for example:
427
428 /usr/bin/qemu-system-s390x ... -cpu host,ap=off,apqci=off,apft=off
429
430Note: If the APFT facility is turned off (apft=off) for the guest, the guest
431will not see any AP devices. The zcrypt device drivers that register for type 10
432and newer AP devices - i.e., the cex4card and cex4queue device drivers - need
433the APFT facility to ascertain the facilities installed on a given AP device. If
434the APFT facility is not installed on the guest, then the probe of device
435drivers will fail since only type 10 and newer devices can be configured for
436guest use.
437
438Example:
439=======
440Let's now provide an example to illustrate how KVM guests may be given
441access to AP facilities. For this example, we will show how to configure
442three guests such that executing the lszcrypt command on the guests would
443look like this:
444
445Guest1
446------
447CARD.DOMAIN TYPE MODE
448------------------------------
44905 CEX5C CCA-Coproc
45005.0004 CEX5C CCA-Coproc
45105.00ab CEX5C CCA-Coproc
45206 CEX5A Accelerator
45306.0004 CEX5A Accelerator
45406.00ab CEX5C CCA-Coproc
455
456Guest2
457------
458CARD.DOMAIN TYPE MODE
459------------------------------
46005 CEX5A Accelerator
46105.0047 CEX5A Accelerator
46205.00ff CEX5A Accelerator
463
464Guest2
465------
466CARD.DOMAIN TYPE MODE
467------------------------------
46806 CEX5A Accelerator
46906.0047 CEX5A Accelerator
47006.00ff CEX5A Accelerator
471
472These are the steps:
473
4741. Install the vfio_ap module on the linux host. The dependency chain for the
475 vfio_ap module is:
476 * iommu
477 * s390
478 * zcrypt
479 * vfio
480 * vfio_mdev
481 * vfio_mdev_device
482 * KVM
483
484 To build the vfio_ap module, the kernel build must be configured with the
485 following Kconfig elements selected:
486 * IOMMU_SUPPORT
487 * S390
488 * ZCRYPT
489 * S390_AP_IOMMU
490 * VFIO
491 * VFIO_MDEV
492 * VFIO_MDEV_DEVICE
493 * KVM
494
495 If using make menuconfig select the following to build the vfio_ap module:
496 -> Device Drivers
497 -> IOMMU Hardware Support
498 select S390 AP IOMMU Support
499 -> VFIO Non-Privileged userspace driver framework
500 -> Mediated device driver frramework
501 -> VFIO driver for Mediated devices
502 -> I/O subsystem
503 -> VFIO support for AP devices
504
5052. Secure the AP queues to be used by the three guests so that the host can not
506 access them. To secure them, there are two sysfs files that specify
507 bitmasks marking a subset of the APQN range as 'usable by the default AP
508 queue device drivers' or 'not usable by the default device drivers' and thus
509 available for use by the vfio_ap device driver'. The location of the sysfs
510 files containing the masks are:
511
512 /sys/bus/ap/apmask
513 /sys/bus/ap/aqmask
514
515 The 'apmask' is a 256-bit mask that identifies a set of AP adapter IDs
516 (APID). Each bit in the mask, from left to right (i.e., from most significant
517 to least significant bit in big endian order), corresponds to an APID from
518 0-255. If a bit is set, the APID is marked as usable only by the default AP
519 queue device drivers; otherwise, the APID is usable by the vfio_ap
520 device driver.
521
522 The 'aqmask' is a 256-bit mask that identifies a set of AP queue indexes
523 (APQI). Each bit in the mask, from left to right (i.e., from most significant
524 to least significant bit in big endian order), corresponds to an APQI from
525 0-255. If a bit is set, the APQI is marked as usable only by the default AP
526 queue device drivers; otherwise, the APQI is usable by the vfio_ap device
527 driver.
528
529 Take, for example, the following mask:
530
531 0x7dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
532
533 It indicates:
534
535 1, 2, 3, 4, 5, and 7-255 belong to the default drivers' pool, and 0 and 6
536 belong to the vfio_ap device driver's pool.
537
538 The APQN of each AP queue device assigned to the linux host is checked by the
539 AP bus against the set of APQNs derived from the cross product of APIDs
540 and APQIs marked as usable only by the default AP queue device drivers. If a
541 match is detected, only the default AP queue device drivers will be probed;
542 otherwise, the vfio_ap device driver will be probed.
543
544 By default, the two masks are set to reserve all APQNs for use by the default
545 AP queue device drivers. There are two ways the default masks can be changed:
546
547 1. The sysfs mask files can be edited by echoing a string into the
548 respective sysfs mask file in one of two formats:
549
550 * An absolute hex string starting with 0x - like "0x12345678" - sets
551 the mask. If the given string is shorter than the mask, it is padded
552 with 0s on the right; for example, specifying a mask value of 0x41 is
553 the same as specifying:
554
555 0x4100000000000000000000000000000000000000000000000000000000000000
556
557 Keep in mind that the mask reads from left to right (i.e., most
558 significant to least significant bit in big endian order), so the mask
559 above identifies device numbers 1 and 7 (01000001).
560
561 If the string is longer than the mask, the operation is terminated with
562 an error (EINVAL).
563
564 * Individual bits in the mask can be switched on and off by specifying
565 each bit number to be switched in a comma separated list. Each bit
566 number string must be prepended with a ('+') or minus ('-') to indicate
567 the corresponding bit is to be switched on ('+') or off ('-'). Some
568 valid values are:
569
570 "+0" switches bit 0 on
571 "-13" switches bit 13 off
572 "+0x41" switches bit 65 on
573 "-0xff" switches bit 255 off
574
575 The following example:
576 +0,-6,+0x47,-0xf0
577
578 Switches bits 0 and 71 (0x47) on
579 Switches bits 6 and 240 (0xf0) off
580
581 Note that the bits not specified in the list remain as they were before
582 the operation.
583
584 2. The masks can also be changed at boot time via parameters on the kernel
585 command line like this:
586
587 ap.apmask=0xffff ap.aqmask=0x40
588
589 This would create the following masks:
590
591 apmask:
592 0xffff000000000000000000000000000000000000000000000000000000000000
593
594 aqmask:
595 0x4000000000000000000000000000000000000000000000000000000000000000
596
597 Resulting in these two pools:
598
599 default drivers pool: adapter 0-15, domain 1
600 alternate drivers pool: adapter 16-255, domains 0, 2-255
601
602 Securing the APQNs for our example:
603 ----------------------------------
604 To secure the AP queues 05.0004, 05.0047, 05.00ab, 05.00ff, 06.0004, 06.0047,
605 06.00ab, and 06.00ff for use by the vfio_ap device driver, the corresponding
606 APQNs can either be removed from the default masks:
607
608 echo -5,-6 > /sys/bus/ap/apmask
609
610 echo -4,-0x47,-0xab,-0xff > /sys/bus/ap/aqmask
611
612 Or the masks can be set as follows:
613
614 echo 0xf9ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff \
615 > apmask
616
617 echo 0xf7fffffffffffffffeffffffffffffffffffffffffeffffffffffffffffffffe \
618 > aqmask
619
620 This will result in AP queues 05.0004, 05.0047, 05.00ab, 05.00ff, 06.0004,
621 06.0047, 06.00ab, and 06.00ff getting bound to the vfio_ap device driver. The
622 sysfs directory for the vfio_ap device driver will now contain symbolic links
623 to the AP queue devices bound to it:
624
625 /sys/bus/ap
626 ... [drivers]
627 ...... [vfio_ap]
628 ......... [05.0004]
629 ......... [05.0047]
630 ......... [05.00ab]
631 ......... [05.00ff]
632 ......... [06.0004]
633 ......... [06.0047]
634 ......... [06.00ab]
635 ......... [06.00ff]
636
637 Keep in mind that only type 10 and newer adapters (i.e., CEX4 and later)
638 can be bound to the vfio_ap device driver. The reason for this is to
639 simplify the implementation by not needlessly complicating the design by
640 supporting older devices that will go out of service in the relatively near
641 future and for which there are few older systems on which to test.
642
643 The administrator, therefore, must take care to secure only AP queues that
644 can be bound to the vfio_ap device driver. The device type for a given AP
645 queue device can be read from the parent card's sysfs directory. For example,
646 to see the hardware type of the queue 05.0004:
647
648 cat /sys/bus/ap/devices/card05/hwtype
649
650 The hwtype must be 10 or higher (CEX4 or newer) in order to be bound to the
651 vfio_ap device driver.
652
6533. Create the mediated devices needed to configure the AP matrixes for the
654 three guests and to provide an interface to the vfio_ap driver for
655 use by the guests:
656
657 /sys/devices/vfio_ap/matrix/
658 --- [mdev_supported_types]
659 ------ [vfio_ap-passthrough] (passthrough mediated matrix device type)
660 --------- create
661 --------- [devices]
662
663 To create the mediated devices for the three guests:
664
665 uuidgen > create
666 uuidgen > create
667 uuidgen > create
668
669 or
670
671 echo $uuid1 > create
672 echo $uuid2 > create
673 echo $uuid3 > create
674
675 This will create three mediated devices in the [devices] subdirectory named
676 after the UUID written to the create attribute file. We call them $uuid1,
677 $uuid2 and $uuid3 and this is the sysfs directory structure after creation:
678
679 /sys/devices/vfio_ap/matrix/
680 --- [mdev_supported_types]
681 ------ [vfio_ap-passthrough]
682 --------- [devices]
683 ------------ [$uuid1]
684 --------------- assign_adapter
685 --------------- assign_control_domain
686 --------------- assign_domain
687 --------------- matrix
688 --------------- unassign_adapter
689 --------------- unassign_control_domain
690 --------------- unassign_domain
691
692 ------------ [$uuid2]
693 --------------- assign_adapter
694 --------------- assign_control_domain
695 --------------- assign_domain
696 --------------- matrix
697 --------------- unassign_adapter
698 ----------------unassign_control_domain
699 ----------------unassign_domain
700
701 ------------ [$uuid3]
702 --------------- assign_adapter
703 --------------- assign_control_domain
704 --------------- assign_domain
705 --------------- matrix
706 --------------- unassign_adapter
707 ----------------unassign_control_domain
708 ----------------unassign_domain
709
7104. The administrator now needs to configure the matrixes for the mediated
711 devices $uuid1 (for Guest1), $uuid2 (for Guest2) and $uuid3 (for Guest3).
712
713 This is how the matrix is configured for Guest1:
714
715 echo 5 > assign_adapter
716 echo 6 > assign_adapter
717 echo 4 > assign_domain
718 echo 0xab > assign_domain
719
720 Control domains can similarly be assigned using the assign_control_domain
721 sysfs file.
722
723 If a mistake is made configuring an adapter, domain or control domain,
724 you can use the unassign_xxx files to unassign the adapter, domain or
725 control domain.
726
727 To display the matrix configuration for Guest1:
728
729 cat matrix
730
731 This is how the matrix is configured for Guest2:
732
733 echo 5 > assign_adapter
734 echo 0x47 > assign_domain
735 echo 0xff > assign_domain
736
737 This is how the matrix is configured for Guest3:
738
739 echo 6 > assign_adapter
740 echo 0x47 > assign_domain
741 echo 0xff > assign_domain
742
743 In order to successfully assign an adapter:
744
745 * The adapter number specified must represent a value from 0 up to the
746 maximum adapter number configured for the system. If an adapter number
747 higher than the maximum is specified, the operation will terminate with
748 an error (ENODEV).
749
750 * All APQNs that can be derived from the adapter ID and the IDs of
751 the previously assigned domains must be bound to the vfio_ap device
752 driver. If no domains have yet been assigned, then there must be at least
753 one APQN with the specified APID bound to the vfio_ap driver. If no such
754 APQNs are bound to the driver, the operation will terminate with an
755 error (EADDRNOTAVAIL).
756
757 No APQN that can be derived from the adapter ID and the IDs of the
758 previously assigned domains can be assigned to another mediated matrix
759 device. If an APQN is assigned to another mediated matrix device, the
760 operation will terminate with an error (EADDRINUSE).
761
762 In order to successfully assign a domain:
763
764 * The domain number specified must represent a value from 0 up to the
765 maximum domain number configured for the system. If a domain number
766 higher than the maximum is specified, the operation will terminate with
767 an error (ENODEV).
768
769 * All APQNs that can be derived from the domain ID and the IDs of
770 the previously assigned adapters must be bound to the vfio_ap device
771 driver. If no domains have yet been assigned, then there must be at least
772 one APQN with the specified APQI bound to the vfio_ap driver. If no such
773 APQNs are bound to the driver, the operation will terminate with an
774 error (EADDRNOTAVAIL).
775
776 No APQN that can be derived from the domain ID and the IDs of the
777 previously assigned adapters can be assigned to another mediated matrix
778 device. If an APQN is assigned to another mediated matrix device, the
779 operation will terminate with an error (EADDRINUSE).
780
781 In order to successfully assign a control domain, the domain number
782 specified must represent a value from 0 up to the maximum domain number
783 configured for the system. If a control domain number higher than the maximum
784 is specified, the operation will terminate with an error (ENODEV).
785
7865. Start Guest1:
787
788 /usr/bin/qemu-system-s390x ... -cpu host,ap=on,apqci=on,apft=on \
789 -device vfio-ap,sysfsdev=/sys/devices/vfio_ap/matrix/$uuid1 ...
790
7917. Start Guest2:
792
793 /usr/bin/qemu-system-s390x ... -cpu host,ap=on,apqci=on,apft=on \
794 -device vfio-ap,sysfsdev=/sys/devices/vfio_ap/matrix/$uuid2 ...
795
7967. Start Guest3:
797
798 /usr/bin/qemu-system-s390x ... -cpu host,ap=on,apqci=on,apft=on \
799 -device vfio-ap,sysfsdev=/sys/devices/vfio_ap/matrix/$uuid3 ...
800
801When the guest is shut down, the mediated matrix devices may be removed.
802
803Using our example again, to remove the mediated matrix device $uuid1:
804
805 /sys/devices/vfio_ap/matrix/
806 --- [mdev_supported_types]
807 ------ [vfio_ap-passthrough]
808 --------- [devices]
809 ------------ [$uuid1]
810 --------------- remove
811
812
813 echo 1 > remove
814
815 This will remove all of the mdev matrix device's sysfs structures including
816 the mdev device itself. To recreate and reconfigure the mdev matrix device,
817 all of the steps starting with step 3 will have to be performed again. Note
818 that the remove will fail if a guest using the mdev is still running.
819
820 It is not necessary to remove an mdev matrix device, but one may want to
821 remove it if no guest will use it during the remaining lifetime of the linux
822 host. If the mdev matrix device is removed, one may want to also reconfigure
823 the pool of adapters and queues reserved for use by the default drivers.
824
825Limitations
826===========
827* The KVM/kernel interfaces do not provide a way to prevent restoring an APQN
828 to the default drivers pool of a queue that is still assigned to a mediated
829 device in use by a guest. It is incumbent upon the administrator to
830 ensure there is no mediated device in use by a guest to which the APQN is
831 assigned lest the host be given access to the private data of the AP queue
832 device such as a private key configured specifically for the guest.
833
834* Dynamically modifying the AP matrix for a running guest (which would amount to
835 hot(un)plug of AP devices for the guest) is currently not supported
836
837* Live guest migration is not supported for guests using AP devices.
diff --git a/Documentation/virtual/kvm/api.txt b/Documentation/virtual/kvm/api.txt
index 647f94128a85..cd209f7730af 100644
--- a/Documentation/virtual/kvm/api.txt
+++ b/Documentation/virtual/kvm/api.txt
@@ -123,6 +123,37 @@ memory layout to fit in user mode), check KVM_CAP_MIPS_VZ and use the
123flag KVM_VM_MIPS_VZ. 123flag KVM_VM_MIPS_VZ.
124 124
125 125
126On arm64, the physical address size for a VM (IPA Size limit) is limited
127to 40bits by default. The limit can be configured if the host supports the
128extension KVM_CAP_ARM_VM_IPA_SIZE. When supported, use
129KVM_VM_TYPE_ARM_IPA_SIZE(IPA_Bits) to set the size in the machine type
130identifier, where IPA_Bits is the maximum width of any physical
131address used by the VM. The IPA_Bits is encoded in bits[7-0] of the
132machine type identifier.
133
134e.g, to configure a guest to use 48bit physical address size :
135
136 vm_fd = ioctl(dev_fd, KVM_CREATE_VM, KVM_VM_TYPE_ARM_IPA_SIZE(48));
137
138The requested size (IPA_Bits) must be :
139 0 - Implies default size, 40bits (for backward compatibility)
140
141 or
142
143 N - Implies N bits, where N is a positive integer such that,
144 32 <= N <= Host_IPA_Limit
145
146Host_IPA_Limit is the maximum possible value for IPA_Bits on the host and
147is dependent on the CPU capability and the kernel configuration. The limit can
148be retrieved using KVM_CAP_ARM_VM_IPA_SIZE of the KVM_CHECK_EXTENSION
149ioctl() at run-time.
150
151Please note that configuring the IPA size does not affect the capability
152exposed by the guest CPUs in ID_AA64MMFR0_EL1[PARange]. It only affects
153size of the address translated by the stage2 level (guest physical to
154host physical address translations).
155
156
1264.3 KVM_GET_MSR_INDEX_LIST, KVM_GET_MSR_FEATURE_INDEX_LIST 1574.3 KVM_GET_MSR_INDEX_LIST, KVM_GET_MSR_FEATURE_INDEX_LIST
127 158
128Capability: basic, KVM_CAP_GET_MSR_FEATURES for KVM_GET_MSR_FEATURE_INDEX_LIST 159Capability: basic, KVM_CAP_GET_MSR_FEATURES for KVM_GET_MSR_FEATURE_INDEX_LIST
@@ -850,7 +881,7 @@ struct kvm_vcpu_events {
850 __u8 injected; 881 __u8 injected;
851 __u8 nr; 882 __u8 nr;
852 __u8 has_error_code; 883 __u8 has_error_code;
853 __u8 pad; 884 __u8 pending;
854 __u32 error_code; 885 __u32 error_code;
855 } exception; 886 } exception;
856 struct { 887 struct {
@@ -873,15 +904,23 @@ struct kvm_vcpu_events {
873 __u8 smm_inside_nmi; 904 __u8 smm_inside_nmi;
874 __u8 latched_init; 905 __u8 latched_init;
875 } smi; 906 } smi;
907 __u8 reserved[27];
908 __u8 exception_has_payload;
909 __u64 exception_payload;
876}; 910};
877 911
878Only two fields are defined in the flags field: 912The following bits are defined in the flags field:
879 913
880- KVM_VCPUEVENT_VALID_SHADOW may be set in the flags field to signal that 914- KVM_VCPUEVENT_VALID_SHADOW may be set to signal that
881 interrupt.shadow contains a valid state. 915 interrupt.shadow contains a valid state.
882 916
883- KVM_VCPUEVENT_VALID_SMM may be set in the flags field to signal that 917- KVM_VCPUEVENT_VALID_SMM may be set to signal that smi contains a
884 smi contains a valid state. 918 valid state.
919
920- KVM_VCPUEVENT_VALID_PAYLOAD may be set to signal that the
921 exception_has_payload, exception_payload, and exception.pending
922 fields contain a valid state. This bit will be set whenever
923 KVM_CAP_EXCEPTION_PAYLOAD is enabled.
885 924
886ARM/ARM64: 925ARM/ARM64:
887 926
@@ -961,6 +1000,11 @@ shall be written into the VCPU.
961 1000
962KVM_VCPUEVENT_VALID_SMM can only be set if KVM_CAP_X86_SMM is available. 1001KVM_VCPUEVENT_VALID_SMM can only be set if KVM_CAP_X86_SMM is available.
963 1002
1003If KVM_CAP_EXCEPTION_PAYLOAD is enabled, KVM_VCPUEVENT_VALID_PAYLOAD
1004can be set in the flags field to signal that the
1005exception_has_payload, exception_payload, and exception.pending fields
1006contain a valid state and shall be written into the VCPU.
1007
964ARM/ARM64: 1008ARM/ARM64:
965 1009
966Set the pending SError exception state for this VCPU. It is not possible to 1010Set the pending SError exception state for this VCPU. It is not possible to
@@ -1922,6 +1966,7 @@ registers, find a list below:
1922 PPC | KVM_REG_PPC_TIDR | 64 1966 PPC | KVM_REG_PPC_TIDR | 64
1923 PPC | KVM_REG_PPC_PSSCR | 64 1967 PPC | KVM_REG_PPC_PSSCR | 64
1924 PPC | KVM_REG_PPC_DEC_EXPIRY | 64 1968 PPC | KVM_REG_PPC_DEC_EXPIRY | 64
1969 PPC | KVM_REG_PPC_PTCR | 64
1925 PPC | KVM_REG_PPC_TM_GPR0 | 64 1970 PPC | KVM_REG_PPC_TM_GPR0 | 64
1926 ... 1971 ...
1927 PPC | KVM_REG_PPC_TM_GPR31 | 64 1972 PPC | KVM_REG_PPC_TM_GPR31 | 64
@@ -2269,6 +2314,10 @@ The supported flags are:
2269 The emulated MMU supports 1T segments in addition to the 2314 The emulated MMU supports 1T segments in addition to the
2270 standard 256M ones. 2315 standard 256M ones.
2271 2316
2317 - KVM_PPC_NO_HASH
2318 This flag indicates that HPT guests are not supported by KVM,
2319 thus all guests must use radix MMU mode.
2320
2272The "slb_size" field indicates how many SLB entries are supported 2321The "slb_size" field indicates how many SLB entries are supported
2273 2322
2274The "sps" array contains 8 entries indicating the supported base 2323The "sps" array contains 8 entries indicating the supported base
@@ -3676,6 +3725,34 @@ Returns: 0 on success, -1 on error
3676This copies the vcpu's kvm_nested_state struct from userspace to the kernel. For 3725This copies the vcpu's kvm_nested_state struct from userspace to the kernel. For
3677the definition of struct kvm_nested_state, see KVM_GET_NESTED_STATE. 3726the definition of struct kvm_nested_state, see KVM_GET_NESTED_STATE.
3678 3727
37284.116 KVM_(UN)REGISTER_COALESCED_MMIO
3729
3730Capability: KVM_CAP_COALESCED_MMIO (for coalesced mmio)
3731 KVM_CAP_COALESCED_PIO (for coalesced pio)
3732Architectures: all
3733Type: vm ioctl
3734Parameters: struct kvm_coalesced_mmio_zone
3735Returns: 0 on success, < 0 on error
3736
3737Coalesced I/O is a performance optimization that defers hardware
3738register write emulation so that userspace exits are avoided. It is
3739typically used to reduce the overhead of emulating frequently accessed
3740hardware registers.
3741
3742When a hardware register is configured for coalesced I/O, write accesses
3743do not exit to userspace and their value is recorded in a ring buffer
3744that is shared between kernel and userspace.
3745
3746Coalesced I/O is used if one or more write accesses to a hardware
3747register can be deferred until a read or a write to another hardware
3748register on the same device. This last access will cause a vmexit and
3749userspace will process accesses from the ring buffer before emulating
3750it. That will avoid exiting to userspace on repeated writes.
3751
3752Coalesced pio is based on coalesced mmio. There is little difference
3753between coalesced mmio and pio except that coalesced pio records accesses
3754to I/O ports.
3755
36795. The kvm_run structure 37565. The kvm_run structure
3680------------------------ 3757------------------------
3681 3758
@@ -4522,7 +4599,7 @@ hpage module parameter is not set to 1, -EINVAL is returned.
4522While it is generally possible to create a huge page backed VM without 4599While it is generally possible to create a huge page backed VM without
4523this capability, the VM will not be able to run. 4600this capability, the VM will not be able to run.
4524 4601
45257.14 KVM_CAP_MSR_PLATFORM_INFO 46027.15 KVM_CAP_MSR_PLATFORM_INFO
4526 4603
4527Architectures: x86 4604Architectures: x86
4528Parameters: args[0] whether feature should be enabled or not 4605Parameters: args[0] whether feature should be enabled or not
@@ -4531,6 +4608,45 @@ With this capability, a guest may read the MSR_PLATFORM_INFO MSR. Otherwise,
4531a #GP would be raised when the guest tries to access. Currently, this 4608a #GP would be raised when the guest tries to access. Currently, this
4532capability does not enable write permissions of this MSR for the guest. 4609capability does not enable write permissions of this MSR for the guest.
4533 4610
46117.16 KVM_CAP_PPC_NESTED_HV
4612
4613Architectures: ppc
4614Parameters: none
4615Returns: 0 on success, -EINVAL when the implementation doesn't support
4616 nested-HV virtualization.
4617
4618HV-KVM on POWER9 and later systems allows for "nested-HV"
4619virtualization, which provides a way for a guest VM to run guests that
4620can run using the CPU's supervisor mode (privileged non-hypervisor
4621state). Enabling this capability on a VM depends on the CPU having
4622the necessary functionality and on the facility being enabled with a
4623kvm-hv module parameter.
4624
46257.17 KVM_CAP_EXCEPTION_PAYLOAD
4626
4627Architectures: x86
4628Parameters: args[0] whether feature should be enabled or not
4629
4630With this capability enabled, CR2 will not be modified prior to the
4631emulated VM-exit when L1 intercepts a #PF exception that occurs in
4632L2. Similarly, for kvm-intel only, DR6 will not be modified prior to
4633the emulated VM-exit when L1 intercepts a #DB exception that occurs in
4634L2. As a result, when KVM_GET_VCPU_EVENTS reports a pending #PF (or
4635#DB) exception for L2, exception.has_payload will be set and the
4636faulting address (or the new DR6 bits*) will be reported in the
4637exception_payload field. Similarly, when userspace injects a #PF (or
4638#DB) into L2 using KVM_SET_VCPU_EVENTS, it is expected to set
4639exception.has_payload and to put the faulting address (or the new DR6
4640bits*) in the exception_payload field.
4641
4642This capability also enables exception.pending in struct
4643kvm_vcpu_events, which allows userspace to distinguish between pending
4644and injected exceptions.
4645
4646
4647* For the new DR6 bits, note that bit 16 is set iff the #DB exception
4648 will clear DR6.RTM.
4649
45348. Other capabilities. 46508. Other capabilities.
4535---------------------- 4651----------------------
4536 4652
@@ -4772,3 +4888,10 @@ CPU when the exception is taken. If this virtual SError is taken to EL1 using
4772AArch64, this value will be reported in the ISS field of ESR_ELx. 4888AArch64, this value will be reported in the ISS field of ESR_ELx.
4773 4889
4774See KVM_CAP_VCPU_EVENTS for more details. 4890See KVM_CAP_VCPU_EVENTS for more details.
48918.20 KVM_CAP_HYPERV_SEND_IPI
4892
4893Architectures: x86
4894
4895This capability indicates that KVM supports paravirtualized Hyper-V IPI send
4896hypercalls:
4897HvCallSendSyntheticClusterIpi, HvCallSendSyntheticClusterIpiEx.
diff --git a/MAINTAINERS b/MAINTAINERS
index 8f22f6af3782..bd702ad56c7f 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -12800,6 +12800,18 @@ W: http://www.ibm.com/developerworks/linux/linux390/
12800S: Supported 12800S: Supported
12801F: drivers/s390/crypto/ 12801F: drivers/s390/crypto/
12802 12802
12803S390 VFIO AP DRIVER
12804M: Tony Krowiak <akrowiak@linux.ibm.com>
12805M: Pierre Morel <pmorel@linux.ibm.com>
12806M: Halil Pasic <pasic@linux.ibm.com>
12807L: linux-s390@vger.kernel.org
12808W: http://www.ibm.com/developerworks/linux/linux390/
12809S: Supported
12810F: drivers/s390/crypto/vfio_ap_drv.c
12811F: drivers/s390/crypto/vfio_ap_private.h
12812F: drivers/s390/crypto/vfio_ap_ops.c
12813F: Documentation/s390/vfio-ap.txt
12814
12803S390 ZFCP DRIVER 12815S390 ZFCP DRIVER
12804M: Steffen Maier <maier@linux.ibm.com> 12816M: Steffen Maier <maier@linux.ibm.com>
12805M: Benjamin Block <bblock@linux.ibm.com> 12817M: Benjamin Block <bblock@linux.ibm.com>
diff --git a/arch/arm/include/asm/kvm_arm.h b/arch/arm/include/asm/kvm_arm.h
index 2d43dca29c72..b95f8d0d9f17 100644
--- a/arch/arm/include/asm/kvm_arm.h
+++ b/arch/arm/include/asm/kvm_arm.h
@@ -133,8 +133,7 @@
133 * space. 133 * space.
134 */ 134 */
135#define KVM_PHYS_SHIFT (40) 135#define KVM_PHYS_SHIFT (40)
136#define KVM_PHYS_SIZE (_AC(1, ULL) << KVM_PHYS_SHIFT) 136
137#define KVM_PHYS_MASK (KVM_PHYS_SIZE - _AC(1, ULL))
138#define PTRS_PER_S2_PGD (_AC(1, ULL) << (KVM_PHYS_SHIFT - 30)) 137#define PTRS_PER_S2_PGD (_AC(1, ULL) << (KVM_PHYS_SHIFT - 30))
139 138
140/* Virtualization Translation Control Register (VTCR) bits */ 139/* Virtualization Translation Control Register (VTCR) bits */
diff --git a/arch/arm/include/asm/kvm_host.h b/arch/arm/include/asm/kvm_host.h
index 3ad482d2f1eb..5ca5d9af0c26 100644
--- a/arch/arm/include/asm/kvm_host.h
+++ b/arch/arm/include/asm/kvm_host.h
@@ -273,7 +273,7 @@ static inline void __cpu_init_stage2(void)
273 kvm_call_hyp(__init_stage2_translation); 273 kvm_call_hyp(__init_stage2_translation);
274} 274}
275 275
276static inline int kvm_arch_dev_ioctl_check_extension(struct kvm *kvm, long ext) 276static inline int kvm_arch_vm_ioctl_check_extension(struct kvm *kvm, long ext)
277{ 277{
278 return 0; 278 return 0;
279} 279}
@@ -354,4 +354,15 @@ static inline void kvm_vcpu_put_sysregs(struct kvm_vcpu *vcpu) {}
354struct kvm *kvm_arch_alloc_vm(void); 354struct kvm *kvm_arch_alloc_vm(void);
355void kvm_arch_free_vm(struct kvm *kvm); 355void kvm_arch_free_vm(struct kvm *kvm);
356 356
357static inline int kvm_arm_setup_stage2(struct kvm *kvm, unsigned long type)
358{
359 /*
360 * On 32bit ARM, VMs get a static 40bit IPA stage2 setup,
361 * so any non-zero value used as type is illegal.
362 */
363 if (type)
364 return -EINVAL;
365 return 0;
366}
367
357#endif /* __ARM_KVM_HOST_H__ */ 368#endif /* __ARM_KVM_HOST_H__ */
diff --git a/arch/arm/include/asm/kvm_mmu.h b/arch/arm/include/asm/kvm_mmu.h
index 847f01fa429d..1098ffc3d54b 100644
--- a/arch/arm/include/asm/kvm_mmu.h
+++ b/arch/arm/include/asm/kvm_mmu.h
@@ -35,16 +35,12 @@
35 addr; \ 35 addr; \
36 }) 36 })
37 37
38/*
39 * KVM_MMU_CACHE_MIN_PAGES is the number of stage2 page table translation levels.
40 */
41#define KVM_MMU_CACHE_MIN_PAGES 2
42
43#ifndef __ASSEMBLY__ 38#ifndef __ASSEMBLY__
44 39
45#include <linux/highmem.h> 40#include <linux/highmem.h>
46#include <asm/cacheflush.h> 41#include <asm/cacheflush.h>
47#include <asm/cputype.h> 42#include <asm/cputype.h>
43#include <asm/kvm_arm.h>
48#include <asm/kvm_hyp.h> 44#include <asm/kvm_hyp.h>
49#include <asm/pgalloc.h> 45#include <asm/pgalloc.h>
50#include <asm/stage2_pgtable.h> 46#include <asm/stage2_pgtable.h>
@@ -52,6 +48,13 @@
52/* Ensure compatibility with arm64 */ 48/* Ensure compatibility with arm64 */
53#define VA_BITS 32 49#define VA_BITS 32
54 50
51#define kvm_phys_shift(kvm) KVM_PHYS_SHIFT
52#define kvm_phys_size(kvm) (1ULL << kvm_phys_shift(kvm))
53#define kvm_phys_mask(kvm) (kvm_phys_size(kvm) - 1ULL)
54#define kvm_vttbr_baddr_mask(kvm) VTTBR_BADDR_MASK
55
56#define stage2_pgd_size(kvm) (PTRS_PER_S2_PGD * sizeof(pgd_t))
57
55int create_hyp_mappings(void *from, void *to, pgprot_t prot); 58int create_hyp_mappings(void *from, void *to, pgprot_t prot);
56int create_hyp_io_mappings(phys_addr_t phys_addr, size_t size, 59int create_hyp_io_mappings(phys_addr_t phys_addr, size_t size,
57 void __iomem **kaddr, 60 void __iomem **kaddr,
@@ -355,6 +358,8 @@ static inline int hyp_map_aux_data(void)
355 358
356#define kvm_phys_to_vttbr(addr) (addr) 359#define kvm_phys_to_vttbr(addr) (addr)
357 360
361static inline void kvm_set_ipa_limit(void) {}
362
358static inline bool kvm_cpu_has_cnp(void) 363static inline bool kvm_cpu_has_cnp(void)
359{ 364{
360 return false; 365 return false;
diff --git a/arch/arm/include/asm/stage2_pgtable.h b/arch/arm/include/asm/stage2_pgtable.h
index 460d616bb2d6..f6a7ea805232 100644
--- a/arch/arm/include/asm/stage2_pgtable.h
+++ b/arch/arm/include/asm/stage2_pgtable.h
@@ -19,43 +19,53 @@
19#ifndef __ARM_S2_PGTABLE_H_ 19#ifndef __ARM_S2_PGTABLE_H_
20#define __ARM_S2_PGTABLE_H_ 20#define __ARM_S2_PGTABLE_H_
21 21
22#define stage2_pgd_none(pgd) pgd_none(pgd) 22/*
23#define stage2_pgd_clear(pgd) pgd_clear(pgd) 23 * kvm_mmu_cache_min_pages() is the number of pages required
24#define stage2_pgd_present(pgd) pgd_present(pgd) 24 * to install a stage-2 translation. We pre-allocate the entry
25#define stage2_pgd_populate(pgd, pud) pgd_populate(NULL, pgd, pud) 25 * level table at VM creation. Since we have a 3 level page-table,
26#define stage2_pud_offset(pgd, address) pud_offset(pgd, address) 26 * we need only two pages to add a new mapping.
27#define stage2_pud_free(pud) pud_free(NULL, pud) 27 */
28 28#define kvm_mmu_cache_min_pages(kvm) 2
29#define stage2_pud_none(pud) pud_none(pud) 29
30#define stage2_pud_clear(pud) pud_clear(pud) 30#define stage2_pgd_none(kvm, pgd) pgd_none(pgd)
31#define stage2_pud_present(pud) pud_present(pud) 31#define stage2_pgd_clear(kvm, pgd) pgd_clear(pgd)
32#define stage2_pud_populate(pud, pmd) pud_populate(NULL, pud, pmd) 32#define stage2_pgd_present(kvm, pgd) pgd_present(pgd)
33#define stage2_pmd_offset(pud, address) pmd_offset(pud, address) 33#define stage2_pgd_populate(kvm, pgd, pud) pgd_populate(NULL, pgd, pud)
34#define stage2_pmd_free(pmd) pmd_free(NULL, pmd) 34#define stage2_pud_offset(kvm, pgd, address) pud_offset(pgd, address)
35 35#define stage2_pud_free(kvm, pud) pud_free(NULL, pud)
36#define stage2_pud_huge(pud) pud_huge(pud) 36
37#define stage2_pud_none(kvm, pud) pud_none(pud)
38#define stage2_pud_clear(kvm, pud) pud_clear(pud)
39#define stage2_pud_present(kvm, pud) pud_present(pud)
40#define stage2_pud_populate(kvm, pud, pmd) pud_populate(NULL, pud, pmd)
41#define stage2_pmd_offset(kvm, pud, address) pmd_offset(pud, address)
42#define stage2_pmd_free(kvm, pmd) pmd_free(NULL, pmd)
43
44#define stage2_pud_huge(kvm, pud) pud_huge(pud)
37 45
38/* Open coded p*d_addr_end that can deal with 64bit addresses */ 46/* Open coded p*d_addr_end that can deal with 64bit addresses */
39static inline phys_addr_t stage2_pgd_addr_end(phys_addr_t addr, phys_addr_t end) 47static inline phys_addr_t
48stage2_pgd_addr_end(struct kvm *kvm, phys_addr_t addr, phys_addr_t end)
40{ 49{
41 phys_addr_t boundary = (addr + PGDIR_SIZE) & PGDIR_MASK; 50 phys_addr_t boundary = (addr + PGDIR_SIZE) & PGDIR_MASK;
42 51
43 return (boundary - 1 < end - 1) ? boundary : end; 52 return (boundary - 1 < end - 1) ? boundary : end;
44} 53}
45 54
46#define stage2_pud_addr_end(addr, end) (end) 55#define stage2_pud_addr_end(kvm, addr, end) (end)
47 56
48static inline phys_addr_t stage2_pmd_addr_end(phys_addr_t addr, phys_addr_t end) 57static inline phys_addr_t
58stage2_pmd_addr_end(struct kvm *kvm, phys_addr_t addr, phys_addr_t end)
49{ 59{
50 phys_addr_t boundary = (addr + PMD_SIZE) & PMD_MASK; 60 phys_addr_t boundary = (addr + PMD_SIZE) & PMD_MASK;
51 61
52 return (boundary - 1 < end - 1) ? boundary : end; 62 return (boundary - 1 < end - 1) ? boundary : end;
53} 63}
54 64
55#define stage2_pgd_index(addr) pgd_index(addr) 65#define stage2_pgd_index(kvm, addr) pgd_index(addr)
56 66
57#define stage2_pte_table_empty(ptep) kvm_page_empty(ptep) 67#define stage2_pte_table_empty(kvm, ptep) kvm_page_empty(ptep)
58#define stage2_pmd_table_empty(pmdp) kvm_page_empty(pmdp) 68#define stage2_pmd_table_empty(kvm, pmdp) kvm_page_empty(pmdp)
59#define stage2_pud_table_empty(pudp) false 69#define stage2_pud_table_empty(kvm, pudp) false
60 70
61#endif /* __ARM_S2_PGTABLE_H_ */ 71#endif /* __ARM_S2_PGTABLE_H_ */
diff --git a/arch/arm64/include/asm/cpufeature.h b/arch/arm64/include/asm/cpufeature.h
index 6db48d90ad63..7e2ec64aa414 100644
--- a/arch/arm64/include/asm/cpufeature.h
+++ b/arch/arm64/include/asm/cpufeature.h
@@ -537,6 +537,27 @@ static inline void arm64_set_ssbd_mitigation(bool state) {}
537#endif 537#endif
538 538
539extern int do_emulate_mrs(struct pt_regs *regs, u32 sys_reg, u32 rt); 539extern int do_emulate_mrs(struct pt_regs *regs, u32 sys_reg, u32 rt);
540
541static inline u32 id_aa64mmfr0_parange_to_phys_shift(int parange)
542{
543 switch (parange) {
544 case 0: return 32;
545 case 1: return 36;
546 case 2: return 40;
547 case 3: return 42;
548 case 4: return 44;
549 case 5: return 48;
550 case 6: return 52;
551 /*
552 * A future PE could use a value unknown to the kernel.
553 * However, by the "D10.1.4 Principles of the ID scheme
554 * for fields in ID registers", ARM DDI 0487C.a, any new
555 * value is guaranteed to be higher than what we know already.
556 * As a safe limit, we return the limit supported by the kernel.
557 */
558 default: return CONFIG_ARM64_PA_BITS;
559 }
560}
540#endif /* __ASSEMBLY__ */ 561#endif /* __ASSEMBLY__ */
541 562
542#endif 563#endif
diff --git a/arch/arm64/include/asm/kvm_arm.h b/arch/arm64/include/asm/kvm_arm.h
index b476bc46f0ab..6f602af5263c 100644
--- a/arch/arm64/include/asm/kvm_arm.h
+++ b/arch/arm64/include/asm/kvm_arm.h
@@ -107,6 +107,7 @@
107#define VTCR_EL2_RES1 (1 << 31) 107#define VTCR_EL2_RES1 (1 << 31)
108#define VTCR_EL2_HD (1 << 22) 108#define VTCR_EL2_HD (1 << 22)
109#define VTCR_EL2_HA (1 << 21) 109#define VTCR_EL2_HA (1 << 21)
110#define VTCR_EL2_PS_SHIFT TCR_EL2_PS_SHIFT
110#define VTCR_EL2_PS_MASK TCR_EL2_PS_MASK 111#define VTCR_EL2_PS_MASK TCR_EL2_PS_MASK
111#define VTCR_EL2_TG0_MASK TCR_TG0_MASK 112#define VTCR_EL2_TG0_MASK TCR_TG0_MASK
112#define VTCR_EL2_TG0_4K TCR_TG0_4K 113#define VTCR_EL2_TG0_4K TCR_TG0_4K
@@ -120,63 +121,150 @@
120#define VTCR_EL2_IRGN0_WBWA TCR_IRGN0_WBWA 121#define VTCR_EL2_IRGN0_WBWA TCR_IRGN0_WBWA
121#define VTCR_EL2_SL0_SHIFT 6 122#define VTCR_EL2_SL0_SHIFT 6
122#define VTCR_EL2_SL0_MASK (3 << VTCR_EL2_SL0_SHIFT) 123#define VTCR_EL2_SL0_MASK (3 << VTCR_EL2_SL0_SHIFT)
123#define VTCR_EL2_SL0_LVL1 (1 << VTCR_EL2_SL0_SHIFT)
124#define VTCR_EL2_T0SZ_MASK 0x3f 124#define VTCR_EL2_T0SZ_MASK 0x3f
125#define VTCR_EL2_T0SZ_40B 24
126#define VTCR_EL2_VS_SHIFT 19 125#define VTCR_EL2_VS_SHIFT 19
127#define VTCR_EL2_VS_8BIT (0 << VTCR_EL2_VS_SHIFT) 126#define VTCR_EL2_VS_8BIT (0 << VTCR_EL2_VS_SHIFT)
128#define VTCR_EL2_VS_16BIT (1 << VTCR_EL2_VS_SHIFT) 127#define VTCR_EL2_VS_16BIT (1 << VTCR_EL2_VS_SHIFT)
129 128
129#define VTCR_EL2_T0SZ(x) TCR_T0SZ(x)
130
130/* 131/*
131 * We configure the Stage-2 page tables to always restrict the IPA space to be 132 * We configure the Stage-2 page tables to always restrict the IPA space to be
132 * 40 bits wide (T0SZ = 24). Systems with a PARange smaller than 40 bits are 133 * 40 bits wide (T0SZ = 24). Systems with a PARange smaller than 40 bits are
133 * not known to exist and will break with this configuration. 134 * not known to exist and will break with this configuration.
134 * 135 *
135 * VTCR_EL2.PS is extracted from ID_AA64MMFR0_EL1.PARange at boot time 136 * The VTCR_EL2 is configured per VM and is initialised in kvm_arm_setup_stage2().
136 * (see hyp-init.S).
137 * 137 *
138 * Note that when using 4K pages, we concatenate two first level page tables 138 * Note that when using 4K pages, we concatenate two first level page tables
139 * together. With 16K pages, we concatenate 16 first level page tables. 139 * together. With 16K pages, we concatenate 16 first level page tables.
140 * 140 *
141 * The magic numbers used for VTTBR_X in this patch can be found in Tables
142 * D4-23 and D4-25 in ARM DDI 0487A.b.
143 */ 141 */
144 142
145#define VTCR_EL2_T0SZ_IPA VTCR_EL2_T0SZ_40B
146#define VTCR_EL2_COMMON_BITS (VTCR_EL2_SH0_INNER | VTCR_EL2_ORGN0_WBWA | \ 143#define VTCR_EL2_COMMON_BITS (VTCR_EL2_SH0_INNER | VTCR_EL2_ORGN0_WBWA | \
147 VTCR_EL2_IRGN0_WBWA | VTCR_EL2_RES1) 144 VTCR_EL2_IRGN0_WBWA | VTCR_EL2_RES1)
148 145
149#ifdef CONFIG_ARM64_64K_PAGES
150/* 146/*
151 * Stage2 translation configuration: 147 * VTCR_EL2:SL0 indicates the entry level for Stage2 translation.
152 * 64kB pages (TG0 = 1) 148 * Interestingly, it depends on the page size.
153 * 2 level page tables (SL = 1) 149 * See D.10.2.121, VTCR_EL2, in ARM DDI 0487C.a
150 *
151 * -----------------------------------------
152 * | Entry level | 4K | 16K/64K |
153 * ------------------------------------------
154 * | Level: 0 | 2 | - |
155 * ------------------------------------------
156 * | Level: 1 | 1 | 2 |
157 * ------------------------------------------
158 * | Level: 2 | 0 | 1 |
159 * ------------------------------------------
160 * | Level: 3 | - | 0 |
161 * ------------------------------------------
162 *
163 * The table roughly translates to :
164 *
165 * SL0(PAGE_SIZE, Entry_level) = TGRAN_SL0_BASE - Entry_Level
166 *
167 * Where TGRAN_SL0_BASE is a magic number depending on the page size:
168 * TGRAN_SL0_BASE(4K) = 2
169 * TGRAN_SL0_BASE(16K) = 3
170 * TGRAN_SL0_BASE(64K) = 3
171 * provided we take care of ruling out the unsupported cases and
172 * Entry_Level = 4 - Number_of_levels.
173 *
154 */ 174 */
155#define VTCR_EL2_TGRAN_FLAGS (VTCR_EL2_TG0_64K | VTCR_EL2_SL0_LVL1) 175#ifdef CONFIG_ARM64_64K_PAGES
156#define VTTBR_X_TGRAN_MAGIC 38 176
177#define VTCR_EL2_TGRAN VTCR_EL2_TG0_64K
178#define VTCR_EL2_TGRAN_SL0_BASE 3UL
179
157#elif defined(CONFIG_ARM64_16K_PAGES) 180#elif defined(CONFIG_ARM64_16K_PAGES)
158/* 181
159 * Stage2 translation configuration: 182#define VTCR_EL2_TGRAN VTCR_EL2_TG0_16K
160 * 16kB pages (TG0 = 2) 183#define VTCR_EL2_TGRAN_SL0_BASE 3UL
161 * 2 level page tables (SL = 1) 184
162 */
163#define VTCR_EL2_TGRAN_FLAGS (VTCR_EL2_TG0_16K | VTCR_EL2_SL0_LVL1)
164#define VTTBR_X_TGRAN_MAGIC 42
165#else /* 4K */ 185#else /* 4K */
166/* 186
167 * Stage2 translation configuration: 187#define VTCR_EL2_TGRAN VTCR_EL2_TG0_4K
168 * 4kB pages (TG0 = 0) 188#define VTCR_EL2_TGRAN_SL0_BASE 2UL
169 * 3 level page tables (SL = 1) 189
170 */
171#define VTCR_EL2_TGRAN_FLAGS (VTCR_EL2_TG0_4K | VTCR_EL2_SL0_LVL1)
172#define VTTBR_X_TGRAN_MAGIC 37
173#endif 190#endif
174 191
175#define VTCR_EL2_FLAGS (VTCR_EL2_COMMON_BITS | VTCR_EL2_TGRAN_FLAGS) 192#define VTCR_EL2_LVLS_TO_SL0(levels) \
176#define VTTBR_X (VTTBR_X_TGRAN_MAGIC - VTCR_EL2_T0SZ_IPA) 193 ((VTCR_EL2_TGRAN_SL0_BASE - (4 - (levels))) << VTCR_EL2_SL0_SHIFT)
194#define VTCR_EL2_SL0_TO_LVLS(sl0) \
195 ((sl0) + 4 - VTCR_EL2_TGRAN_SL0_BASE)
196#define VTCR_EL2_LVLS(vtcr) \
197 VTCR_EL2_SL0_TO_LVLS(((vtcr) & VTCR_EL2_SL0_MASK) >> VTCR_EL2_SL0_SHIFT)
198
199#define VTCR_EL2_FLAGS (VTCR_EL2_COMMON_BITS | VTCR_EL2_TGRAN)
200#define VTCR_EL2_IPA(vtcr) (64 - ((vtcr) & VTCR_EL2_T0SZ_MASK))
201
202/*
203 * ARM VMSAv8-64 defines an algorithm for finding the translation table
204 * descriptors in section D4.2.8 in ARM DDI 0487C.a.
205 *
206 * The algorithm defines the expectations on the translation table
207 * addresses for each level, based on PAGE_SIZE, entry level
208 * and the translation table size (T0SZ). The variable "x" in the
209 * algorithm determines the alignment of a table base address at a given
210 * level and thus determines the alignment of VTTBR:BADDR for stage2
211 * page table entry level.
212 * Since the number of bits resolved at the entry level could vary
213 * depending on the T0SZ, the value of "x" is defined based on a
214 * Magic constant for a given PAGE_SIZE and Entry Level. The
215 * intermediate levels must be always aligned to the PAGE_SIZE (i.e,
216 * x = PAGE_SHIFT).
217 *
218 * The value of "x" for entry level is calculated as :
219 * x = Magic_N - T0SZ
220 *
221 * where Magic_N is an integer depending on the page size and the entry
222 * level of the page table as below:
223 *
224 * --------------------------------------------
225 * | Entry level | 4K 16K 64K |
226 * --------------------------------------------
227 * | Level: 0 (4 levels) | 28 | - | - |
228 * --------------------------------------------
229 * | Level: 1 (3 levels) | 37 | 31 | 25 |
230 * --------------------------------------------
231 * | Level: 2 (2 levels) | 46 | 42 | 38 |
232 * --------------------------------------------
233 * | Level: 3 (1 level) | - | 53 | 51 |
234 * --------------------------------------------
235 *
236 * We have a magic formula for the Magic_N below:
237 *
238 * Magic_N(PAGE_SIZE, Level) = 64 - ((PAGE_SHIFT - 3) * Number_of_levels)
239 *
240 * where Number_of_levels = (4 - Level). We are only interested in the
241 * value for Entry_Level for the stage2 page table.
242 *
243 * So, given that T0SZ = (64 - IPA_SHIFT), we can compute 'x' as follows:
244 *
245 * x = (64 - ((PAGE_SHIFT - 3) * Number_of_levels)) - (64 - IPA_SHIFT)
246 * = IPA_SHIFT - ((PAGE_SHIFT - 3) * Number of levels)
247 *
248 * Here is one way to explain the Magic Formula:
249 *
250 * x = log2(Size_of_Entry_Level_Table)
251 *
252 * Since, we can resolve (PAGE_SHIFT - 3) bits at each level, and another
253 * PAGE_SHIFT bits in the PTE, we have :
254 *
255 * Bits_Entry_level = IPA_SHIFT - ((PAGE_SHIFT - 3) * (n - 1) + PAGE_SHIFT)
256 * = IPA_SHIFT - (PAGE_SHIFT - 3) * n - 3
257 * where n = number of levels, and since each pointer is 8bytes, we have:
258 *
259 * x = Bits_Entry_Level + 3
260 * = IPA_SHIFT - (PAGE_SHIFT - 3) * n
261 *
262 * The only constraint here is that, we have to find the number of page table
263 * levels for a given IPA size (which we do, see stage2_pt_levels())
264 */
265#define ARM64_VTTBR_X(ipa, levels) ((ipa) - ((levels) * (PAGE_SHIFT - 3)))
177 266
178#define VTTBR_CNP_BIT (UL(1)) 267#define VTTBR_CNP_BIT (UL(1))
179#define VTTBR_BADDR_MASK (((UL(1) << (PHYS_MASK_SHIFT - VTTBR_X)) - 1) << VTTBR_X)
180#define VTTBR_VMID_SHIFT (UL(48)) 268#define VTTBR_VMID_SHIFT (UL(48))
181#define VTTBR_VMID_MASK(size) (_AT(u64, (1 << size) - 1) << VTTBR_VMID_SHIFT) 269#define VTTBR_VMID_MASK(size) (_AT(u64, (1 << size) - 1) << VTTBR_VMID_SHIFT)
182 270
@@ -224,6 +312,13 @@
224 312
225/* Hyp Prefetch Fault Address Register (HPFAR/HDFAR) */ 313/* Hyp Prefetch Fault Address Register (HPFAR/HDFAR) */
226#define HPFAR_MASK (~UL(0xf)) 314#define HPFAR_MASK (~UL(0xf))
315/*
316 * We have
317 * PAR [PA_Shift - 1 : 12] = PA [PA_Shift - 1 : 12]
318 * HPFAR [PA_Shift - 9 : 4] = FIPA [PA_Shift - 1 : 12]
319 */
320#define PAR_TO_HPFAR(par) \
321 (((par) & GENMASK_ULL(PHYS_MASK_SHIFT - 1, 12)) >> 8)
227 322
228#define kvm_arm_exception_type \ 323#define kvm_arm_exception_type \
229 {0, "IRQ" }, \ 324 {0, "IRQ" }, \
diff --git a/arch/arm64/include/asm/kvm_asm.h b/arch/arm64/include/asm/kvm_asm.h
index 102b5a5c47b6..aea01a09eb94 100644
--- a/arch/arm64/include/asm/kvm_asm.h
+++ b/arch/arm64/include/asm/kvm_asm.h
@@ -30,6 +30,7 @@
30#define ARM_EXCEPTION_IRQ 0 30#define ARM_EXCEPTION_IRQ 0
31#define ARM_EXCEPTION_EL1_SERROR 1 31#define ARM_EXCEPTION_EL1_SERROR 1
32#define ARM_EXCEPTION_TRAP 2 32#define ARM_EXCEPTION_TRAP 2
33#define ARM_EXCEPTION_IL 3
33/* The hyp-stub will return this for any kvm_call_hyp() call */ 34/* The hyp-stub will return this for any kvm_call_hyp() call */
34#define ARM_EXCEPTION_HYP_GONE HVC_STUB_ERR 35#define ARM_EXCEPTION_HYP_GONE HVC_STUB_ERR
35 36
@@ -72,8 +73,6 @@ extern void __vgic_v3_init_lrs(void);
72 73
73extern u32 __kvm_get_mdcr_el2(void); 74extern u32 __kvm_get_mdcr_el2(void);
74 75
75extern u32 __init_stage2_translation(void);
76
77/* Home-grown __this_cpu_{ptr,read} variants that always work at HYP */ 76/* Home-grown __this_cpu_{ptr,read} variants that always work at HYP */
78#define __hyp_this_cpu_ptr(sym) \ 77#define __hyp_this_cpu_ptr(sym) \
79 ({ \ 78 ({ \
diff --git a/arch/arm64/include/asm/kvm_host.h b/arch/arm64/include/asm/kvm_host.h
index 2842bf149029..52fbc823ff8c 100644
--- a/arch/arm64/include/asm/kvm_host.h
+++ b/arch/arm64/include/asm/kvm_host.h
@@ -53,7 +53,7 @@ DECLARE_STATIC_KEY_FALSE(userspace_irqchip_in_use);
53 53
54int __attribute_const__ kvm_target_cpu(void); 54int __attribute_const__ kvm_target_cpu(void);
55int kvm_reset_vcpu(struct kvm_vcpu *vcpu); 55int kvm_reset_vcpu(struct kvm_vcpu *vcpu);
56int kvm_arch_dev_ioctl_check_extension(struct kvm *kvm, long ext); 56int kvm_arch_vm_ioctl_check_extension(struct kvm *kvm, long ext);
57void __extended_idmap_trampoline(phys_addr_t boot_pgd, phys_addr_t idmap_start); 57void __extended_idmap_trampoline(phys_addr_t boot_pgd, phys_addr_t idmap_start);
58 58
59struct kvm_arch { 59struct kvm_arch {
@@ -61,11 +61,13 @@ struct kvm_arch {
61 u64 vmid_gen; 61 u64 vmid_gen;
62 u32 vmid; 62 u32 vmid;
63 63
64 /* 1-level 2nd stage table, protected by kvm->mmu_lock */ 64 /* stage2 entry level table */
65 pgd_t *pgd; 65 pgd_t *pgd;
66 66
67 /* VTTBR value associated with above pgd and vmid */ 67 /* VTTBR value associated with above pgd and vmid */
68 u64 vttbr; 68 u64 vttbr;
69 /* VTCR_EL2 value for this VM */
70 u64 vtcr;
69 71
70 /* The last vcpu id that ran on each physical CPU */ 72 /* The last vcpu id that ran on each physical CPU */
71 int __percpu *last_vcpu_ran; 73 int __percpu *last_vcpu_ran;
@@ -451,13 +453,7 @@ int kvm_arm_vcpu_arch_get_attr(struct kvm_vcpu *vcpu,
451int kvm_arm_vcpu_arch_has_attr(struct kvm_vcpu *vcpu, 453int kvm_arm_vcpu_arch_has_attr(struct kvm_vcpu *vcpu,
452 struct kvm_device_attr *attr); 454 struct kvm_device_attr *attr);
453 455
454static inline void __cpu_init_stage2(void) 456static inline void __cpu_init_stage2(void) {}
455{
456 u32 parange = kvm_call_hyp(__init_stage2_translation);
457
458 WARN_ONCE(parange < 40,
459 "PARange is %d bits, unsupported configuration!", parange);
460}
461 457
462/* Guest/host FPSIMD coordination helpers */ 458/* Guest/host FPSIMD coordination helpers */
463int kvm_arch_vcpu_run_map_fp(struct kvm_vcpu *vcpu); 459int kvm_arch_vcpu_run_map_fp(struct kvm_vcpu *vcpu);
@@ -520,8 +516,12 @@ static inline int kvm_arm_have_ssbd(void)
520void kvm_vcpu_load_sysregs(struct kvm_vcpu *vcpu); 516void kvm_vcpu_load_sysregs(struct kvm_vcpu *vcpu);
521void kvm_vcpu_put_sysregs(struct kvm_vcpu *vcpu); 517void kvm_vcpu_put_sysregs(struct kvm_vcpu *vcpu);
522 518
519void kvm_set_ipa_limit(void);
520
523#define __KVM_HAVE_ARCH_VM_ALLOC 521#define __KVM_HAVE_ARCH_VM_ALLOC
524struct kvm *kvm_arch_alloc_vm(void); 522struct kvm *kvm_arch_alloc_vm(void);
525void kvm_arch_free_vm(struct kvm *kvm); 523void kvm_arch_free_vm(struct kvm *kvm);
526 524
525int kvm_arm_setup_stage2(struct kvm *kvm, unsigned long type);
526
527#endif /* __ARM64_KVM_HOST_H__ */ 527#endif /* __ARM64_KVM_HOST_H__ */
diff --git a/arch/arm64/include/asm/kvm_hyp.h b/arch/arm64/include/asm/kvm_hyp.h
index 384c34397619..23aca66767f9 100644
--- a/arch/arm64/include/asm/kvm_hyp.h
+++ b/arch/arm64/include/asm/kvm_hyp.h
@@ -155,5 +155,15 @@ void deactivate_traps_vhe_put(void);
155u64 __guest_enter(struct kvm_vcpu *vcpu, struct kvm_cpu_context *host_ctxt); 155u64 __guest_enter(struct kvm_vcpu *vcpu, struct kvm_cpu_context *host_ctxt);
156void __noreturn __hyp_do_panic(unsigned long, ...); 156void __noreturn __hyp_do_panic(unsigned long, ...);
157 157
158/*
159 * Must be called from hyp code running at EL2 with an updated VTTBR
160 * and interrupts disabled.
161 */
162static __always_inline void __hyp_text __load_guest_stage2(struct kvm *kvm)
163{
164 write_sysreg(kvm->arch.vtcr, vtcr_el2);
165 write_sysreg(kvm->arch.vttbr, vttbr_el2);
166}
167
158#endif /* __ARM64_KVM_HYP_H__ */ 168#endif /* __ARM64_KVM_HYP_H__ */
159 169
diff --git a/arch/arm64/include/asm/kvm_mmu.h b/arch/arm64/include/asm/kvm_mmu.h
index 64337afbf124..658657367f2f 100644
--- a/arch/arm64/include/asm/kvm_mmu.h
+++ b/arch/arm64/include/asm/kvm_mmu.h
@@ -141,8 +141,16 @@ static inline unsigned long __kern_hyp_va(unsigned long v)
141 * We currently only support a 40bit IPA. 141 * We currently only support a 40bit IPA.
142 */ 142 */
143#define KVM_PHYS_SHIFT (40) 143#define KVM_PHYS_SHIFT (40)
144#define KVM_PHYS_SIZE (1UL << KVM_PHYS_SHIFT) 144
145#define KVM_PHYS_MASK (KVM_PHYS_SIZE - 1UL) 145#define kvm_phys_shift(kvm) VTCR_EL2_IPA(kvm->arch.vtcr)
146#define kvm_phys_size(kvm) (_AC(1, ULL) << kvm_phys_shift(kvm))
147#define kvm_phys_mask(kvm) (kvm_phys_size(kvm) - _AC(1, ULL))
148
149static inline bool kvm_page_empty(void *ptr)
150{
151 struct page *ptr_page = virt_to_page(ptr);
152 return page_count(ptr_page) == 1;
153}
146 154
147#include <asm/stage2_pgtable.h> 155#include <asm/stage2_pgtable.h>
148 156
@@ -238,12 +246,6 @@ static inline bool kvm_s2pmd_exec(pmd_t *pmdp)
238 return !(READ_ONCE(pmd_val(*pmdp)) & PMD_S2_XN); 246 return !(READ_ONCE(pmd_val(*pmdp)) & PMD_S2_XN);
239} 247}
240 248
241static inline bool kvm_page_empty(void *ptr)
242{
243 struct page *ptr_page = virt_to_page(ptr);
244 return page_count(ptr_page) == 1;
245}
246
247#define hyp_pte_table_empty(ptep) kvm_page_empty(ptep) 249#define hyp_pte_table_empty(ptep) kvm_page_empty(ptep)
248 250
249#ifdef __PAGETABLE_PMD_FOLDED 251#ifdef __PAGETABLE_PMD_FOLDED
@@ -517,6 +519,30 @@ static inline int hyp_map_aux_data(void)
517 519
518#define kvm_phys_to_vttbr(addr) phys_to_ttbr(addr) 520#define kvm_phys_to_vttbr(addr) phys_to_ttbr(addr)
519 521
522/*
523 * Get the magic number 'x' for VTTBR:BADDR of this KVM instance.
524 * With v8.2 LVA extensions, 'x' should be a minimum of 6 with
525 * 52bit IPS.
526 */
527static inline int arm64_vttbr_x(u32 ipa_shift, u32 levels)
528{
529 int x = ARM64_VTTBR_X(ipa_shift, levels);
530
531 return (IS_ENABLED(CONFIG_ARM64_PA_BITS_52) && x < 6) ? 6 : x;
532}
533
534static inline u64 vttbr_baddr_mask(u32 ipa_shift, u32 levels)
535{
536 unsigned int x = arm64_vttbr_x(ipa_shift, levels);
537
538 return GENMASK_ULL(PHYS_MASK_SHIFT - 1, x);
539}
540
541static inline u64 kvm_vttbr_baddr_mask(struct kvm *kvm)
542{
543 return vttbr_baddr_mask(kvm_phys_shift(kvm), kvm_stage2_levels(kvm));
544}
545
520static inline bool kvm_cpu_has_cnp(void) 546static inline bool kvm_cpu_has_cnp(void)
521{ 547{
522 return system_supports_cnp(); 548 return system_supports_cnp();
diff --git a/arch/arm64/include/asm/ptrace.h b/arch/arm64/include/asm/ptrace.h
index 6bc43889d11e..fce22c4b2f73 100644
--- a/arch/arm64/include/asm/ptrace.h
+++ b/arch/arm64/include/asm/ptrace.h
@@ -25,6 +25,9 @@
25#define CurrentEL_EL1 (1 << 2) 25#define CurrentEL_EL1 (1 << 2)
26#define CurrentEL_EL2 (2 << 2) 26#define CurrentEL_EL2 (2 << 2)
27 27
28/* Additional SPSR bits not exposed in the UABI */
29#define PSR_IL_BIT (1 << 20)
30
28/* AArch32-specific ptrace requests */ 31/* AArch32-specific ptrace requests */
29#define COMPAT_PTRACE_GETREGS 12 32#define COMPAT_PTRACE_GETREGS 12
30#define COMPAT_PTRACE_SETREGS 13 33#define COMPAT_PTRACE_SETREGS 13
diff --git a/arch/arm64/include/asm/stage2_pgtable-nopmd.h b/arch/arm64/include/asm/stage2_pgtable-nopmd.h
deleted file mode 100644
index 2656a0fd05a6..000000000000
--- a/arch/arm64/include/asm/stage2_pgtable-nopmd.h
+++ /dev/null
@@ -1,42 +0,0 @@
1/*
2 * Copyright (C) 2016 - ARM Ltd
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16
17#ifndef __ARM64_S2_PGTABLE_NOPMD_H_
18#define __ARM64_S2_PGTABLE_NOPMD_H_
19
20#include <asm/stage2_pgtable-nopud.h>
21
22#define __S2_PGTABLE_PMD_FOLDED
23
24#define S2_PMD_SHIFT S2_PUD_SHIFT
25#define S2_PTRS_PER_PMD 1
26#define S2_PMD_SIZE (1UL << S2_PMD_SHIFT)
27#define S2_PMD_MASK (~(S2_PMD_SIZE-1))
28
29#define stage2_pud_none(pud) (0)
30#define stage2_pud_present(pud) (1)
31#define stage2_pud_clear(pud) do { } while (0)
32#define stage2_pud_populate(pud, pmd) do { } while (0)
33#define stage2_pmd_offset(pud, address) ((pmd_t *)(pud))
34
35#define stage2_pmd_free(pmd) do { } while (0)
36
37#define stage2_pmd_addr_end(addr, end) (end)
38
39#define stage2_pud_huge(pud) (0)
40#define stage2_pmd_table_empty(pmdp) (0)
41
42#endif
diff --git a/arch/arm64/include/asm/stage2_pgtable-nopud.h b/arch/arm64/include/asm/stage2_pgtable-nopud.h
deleted file mode 100644
index 5ee87b54ebf3..000000000000
--- a/arch/arm64/include/asm/stage2_pgtable-nopud.h
+++ /dev/null
@@ -1,39 +0,0 @@
1/*
2 * Copyright (C) 2016 - ARM Ltd
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16
17#ifndef __ARM64_S2_PGTABLE_NOPUD_H_
18#define __ARM64_S2_PGTABLE_NOPUD_H_
19
20#define __S2_PGTABLE_PUD_FOLDED
21
22#define S2_PUD_SHIFT S2_PGDIR_SHIFT
23#define S2_PTRS_PER_PUD 1
24#define S2_PUD_SIZE (_AC(1, UL) << S2_PUD_SHIFT)
25#define S2_PUD_MASK (~(S2_PUD_SIZE-1))
26
27#define stage2_pgd_none(pgd) (0)
28#define stage2_pgd_present(pgd) (1)
29#define stage2_pgd_clear(pgd) do { } while (0)
30#define stage2_pgd_populate(pgd, pud) do { } while (0)
31
32#define stage2_pud_offset(pgd, address) ((pud_t *)(pgd))
33
34#define stage2_pud_free(x) do { } while (0)
35
36#define stage2_pud_addr_end(addr, end) (end)
37#define stage2_pud_table_empty(pmdp) (0)
38
39#endif
diff --git a/arch/arm64/include/asm/stage2_pgtable.h b/arch/arm64/include/asm/stage2_pgtable.h
index 8b68099348e5..d352f6df8d2c 100644
--- a/arch/arm64/include/asm/stage2_pgtable.h
+++ b/arch/arm64/include/asm/stage2_pgtable.h
@@ -19,9 +19,17 @@
19#ifndef __ARM64_S2_PGTABLE_H_ 19#ifndef __ARM64_S2_PGTABLE_H_
20#define __ARM64_S2_PGTABLE_H_ 20#define __ARM64_S2_PGTABLE_H_
21 21
22#include <linux/hugetlb.h>
22#include <asm/pgtable.h> 23#include <asm/pgtable.h>
23 24
24/* 25/*
26 * PGDIR_SHIFT determines the size a top-level page table entry can map
27 * and depends on the number of levels in the page table. Compute the
28 * PGDIR_SHIFT for a given number of levels.
29 */
30#define pt_levels_pgdir_shift(lvls) ARM64_HW_PGTABLE_LEVEL_SHIFT(4 - (lvls))
31
32/*
25 * The hardware supports concatenation of up to 16 tables at stage2 entry level 33 * The hardware supports concatenation of up to 16 tables at stage2 entry level
26 * and we use the feature whenever possible. 34 * and we use the feature whenever possible.
27 * 35 *
@@ -29,112 +37,208 @@
29 * On arm64, the smallest PAGE_SIZE supported is 4k, which means 37 * On arm64, the smallest PAGE_SIZE supported is 4k, which means
30 * (PAGE_SHIFT - 3) > 4 holds for all page sizes. 38 * (PAGE_SHIFT - 3) > 4 holds for all page sizes.
31 * This implies, the total number of page table levels at stage2 expected 39 * This implies, the total number of page table levels at stage2 expected
32 * by the hardware is actually the number of levels required for (KVM_PHYS_SHIFT - 4) 40 * by the hardware is actually the number of levels required for (IPA_SHIFT - 4)
33 * in normal translations(e.g, stage1), since we cannot have another level in 41 * in normal translations(e.g, stage1), since we cannot have another level in
34 * the range (KVM_PHYS_SHIFT, KVM_PHYS_SHIFT - 4). 42 * the range (IPA_SHIFT, IPA_SHIFT - 4).
35 */ 43 */
36#define STAGE2_PGTABLE_LEVELS ARM64_HW_PGTABLE_LEVELS(KVM_PHYS_SHIFT - 4) 44#define stage2_pgtable_levels(ipa) ARM64_HW_PGTABLE_LEVELS((ipa) - 4)
45#define kvm_stage2_levels(kvm) VTCR_EL2_LVLS(kvm->arch.vtcr)
37 46
38/* 47/* stage2_pgdir_shift() is the size mapped by top-level stage2 entry for the VM */
39 * With all the supported VA_BITs and 40bit guest IPA, the following condition 48#define stage2_pgdir_shift(kvm) pt_levels_pgdir_shift(kvm_stage2_levels(kvm))
40 * is always true: 49#define stage2_pgdir_size(kvm) (1ULL << stage2_pgdir_shift(kvm))
41 * 50#define stage2_pgdir_mask(kvm) ~(stage2_pgdir_size(kvm) - 1)
42 * STAGE2_PGTABLE_LEVELS <= CONFIG_PGTABLE_LEVELS
43 *
44 * We base our stage-2 page table walker helpers on this assumption and
45 * fall back to using the host version of the helper wherever possible.
46 * i.e, if a particular level is not folded (e.g, PUD) at stage2, we fall back
47 * to using the host version, since it is guaranteed it is not folded at host.
48 *
49 * If the condition breaks in the future, we can rearrange the host level
50 * definitions and reuse them for stage2. Till then...
51 */
52#if STAGE2_PGTABLE_LEVELS > CONFIG_PGTABLE_LEVELS
53#error "Unsupported combination of guest IPA and host VA_BITS."
54#endif
55
56/* S2_PGDIR_SHIFT is the size mapped by top-level stage2 entry */
57#define S2_PGDIR_SHIFT ARM64_HW_PGTABLE_LEVEL_SHIFT(4 - STAGE2_PGTABLE_LEVELS)
58#define S2_PGDIR_SIZE (_AC(1, UL) << S2_PGDIR_SHIFT)
59#define S2_PGDIR_MASK (~(S2_PGDIR_SIZE - 1))
60 51
61/* 52/*
62 * The number of PTRS across all concatenated stage2 tables given by the 53 * The number of PTRS across all concatenated stage2 tables given by the
63 * number of bits resolved at the initial level. 54 * number of bits resolved at the initial level.
55 * If we force more levels than necessary, we may have (stage2_pgdir_shift > IPA),
56 * in which case, stage2_pgd_ptrs will have one entry.
64 */ 57 */
65#define PTRS_PER_S2_PGD (1 << (KVM_PHYS_SHIFT - S2_PGDIR_SHIFT)) 58#define pgd_ptrs_shift(ipa, pgdir_shift) \
59 ((ipa) > (pgdir_shift) ? ((ipa) - (pgdir_shift)) : 0)
60#define __s2_pgd_ptrs(ipa, lvls) \
61 (1 << (pgd_ptrs_shift((ipa), pt_levels_pgdir_shift(lvls))))
62#define __s2_pgd_size(ipa, lvls) (__s2_pgd_ptrs((ipa), (lvls)) * sizeof(pgd_t))
63
64#define stage2_pgd_ptrs(kvm) __s2_pgd_ptrs(kvm_phys_shift(kvm), kvm_stage2_levels(kvm))
65#define stage2_pgd_size(kvm) __s2_pgd_size(kvm_phys_shift(kvm), kvm_stage2_levels(kvm))
66 66
67/* 67/*
68 * KVM_MMU_CACHE_MIN_PAGES is the number of stage2 page table translation 68 * kvm_mmmu_cache_min_pages() is the number of pages required to install
69 * levels in addition to the PGD. 69 * a stage-2 translation. We pre-allocate the entry level page table at
70 * the VM creation.
70 */ 71 */
71#define KVM_MMU_CACHE_MIN_PAGES (STAGE2_PGTABLE_LEVELS - 1) 72#define kvm_mmu_cache_min_pages(kvm) (kvm_stage2_levels(kvm) - 1)
72 73
73 74/* Stage2 PUD definitions when the level is present */
74#if STAGE2_PGTABLE_LEVELS > 3 75static inline bool kvm_stage2_has_pud(struct kvm *kvm)
76{
77 return (CONFIG_PGTABLE_LEVELS > 3) && (kvm_stage2_levels(kvm) > 3);
78}
75 79
76#define S2_PUD_SHIFT ARM64_HW_PGTABLE_LEVEL_SHIFT(1) 80#define S2_PUD_SHIFT ARM64_HW_PGTABLE_LEVEL_SHIFT(1)
77#define S2_PUD_SIZE (_AC(1, UL) << S2_PUD_SHIFT) 81#define S2_PUD_SIZE (1UL << S2_PUD_SHIFT)
78#define S2_PUD_MASK (~(S2_PUD_SIZE - 1)) 82#define S2_PUD_MASK (~(S2_PUD_SIZE - 1))
79 83
80#define stage2_pgd_none(pgd) pgd_none(pgd) 84static inline bool stage2_pgd_none(struct kvm *kvm, pgd_t pgd)
81#define stage2_pgd_clear(pgd) pgd_clear(pgd) 85{
82#define stage2_pgd_present(pgd) pgd_present(pgd) 86 if (kvm_stage2_has_pud(kvm))
83#define stage2_pgd_populate(pgd, pud) pgd_populate(NULL, pgd, pud) 87 return pgd_none(pgd);
84#define stage2_pud_offset(pgd, address) pud_offset(pgd, address) 88 else
85#define stage2_pud_free(pud) pud_free(NULL, pud) 89 return 0;
90}
86 91
87#define stage2_pud_table_empty(pudp) kvm_page_empty(pudp) 92static inline void stage2_pgd_clear(struct kvm *kvm, pgd_t *pgdp)
93{
94 if (kvm_stage2_has_pud(kvm))
95 pgd_clear(pgdp);
96}
88 97
89static inline phys_addr_t stage2_pud_addr_end(phys_addr_t addr, phys_addr_t end) 98static inline bool stage2_pgd_present(struct kvm *kvm, pgd_t pgd)
90{ 99{
91 phys_addr_t boundary = (addr + S2_PUD_SIZE) & S2_PUD_MASK; 100 if (kvm_stage2_has_pud(kvm))
101 return pgd_present(pgd);
102 else
103 return 1;
104}
92 105
93 return (boundary - 1 < end - 1) ? boundary : end; 106static inline void stage2_pgd_populate(struct kvm *kvm, pgd_t *pgd, pud_t *pud)
107{
108 if (kvm_stage2_has_pud(kvm))
109 pgd_populate(NULL, pgd, pud);
110}
111
112static inline pud_t *stage2_pud_offset(struct kvm *kvm,
113 pgd_t *pgd, unsigned long address)
114{
115 if (kvm_stage2_has_pud(kvm))
116 return pud_offset(pgd, address);
117 else
118 return (pud_t *)pgd;
94} 119}
95 120
96#endif /* STAGE2_PGTABLE_LEVELS > 3 */ 121static inline void stage2_pud_free(struct kvm *kvm, pud_t *pud)
122{
123 if (kvm_stage2_has_pud(kvm))
124 pud_free(NULL, pud);
125}
97 126
127static inline bool stage2_pud_table_empty(struct kvm *kvm, pud_t *pudp)
128{
129 if (kvm_stage2_has_pud(kvm))
130 return kvm_page_empty(pudp);
131 else
132 return false;
133}
98 134
99#if STAGE2_PGTABLE_LEVELS > 2 135static inline phys_addr_t
136stage2_pud_addr_end(struct kvm *kvm, phys_addr_t addr, phys_addr_t end)
137{
138 if (kvm_stage2_has_pud(kvm)) {
139 phys_addr_t boundary = (addr + S2_PUD_SIZE) & S2_PUD_MASK;
140
141 return (boundary - 1 < end - 1) ? boundary : end;
142 } else {
143 return end;
144 }
145}
146
147/* Stage2 PMD definitions when the level is present */
148static inline bool kvm_stage2_has_pmd(struct kvm *kvm)
149{
150 return (CONFIG_PGTABLE_LEVELS > 2) && (kvm_stage2_levels(kvm) > 2);
151}
100 152
101#define S2_PMD_SHIFT ARM64_HW_PGTABLE_LEVEL_SHIFT(2) 153#define S2_PMD_SHIFT ARM64_HW_PGTABLE_LEVEL_SHIFT(2)
102#define S2_PMD_SIZE (_AC(1, UL) << S2_PMD_SHIFT) 154#define S2_PMD_SIZE (1UL << S2_PMD_SHIFT)
103#define S2_PMD_MASK (~(S2_PMD_SIZE - 1)) 155#define S2_PMD_MASK (~(S2_PMD_SIZE - 1))
104 156
105#define stage2_pud_none(pud) pud_none(pud) 157static inline bool stage2_pud_none(struct kvm *kvm, pud_t pud)
106#define stage2_pud_clear(pud) pud_clear(pud) 158{
107#define stage2_pud_present(pud) pud_present(pud) 159 if (kvm_stage2_has_pmd(kvm))
108#define stage2_pud_populate(pud, pmd) pud_populate(NULL, pud, pmd) 160 return pud_none(pud);
109#define stage2_pmd_offset(pud, address) pmd_offset(pud, address) 161 else
110#define stage2_pmd_free(pmd) pmd_free(NULL, pmd) 162 return 0;
163}
164
165static inline void stage2_pud_clear(struct kvm *kvm, pud_t *pud)
166{
167 if (kvm_stage2_has_pmd(kvm))
168 pud_clear(pud);
169}
111 170
112#define stage2_pud_huge(pud) pud_huge(pud) 171static inline bool stage2_pud_present(struct kvm *kvm, pud_t pud)
113#define stage2_pmd_table_empty(pmdp) kvm_page_empty(pmdp) 172{
173 if (kvm_stage2_has_pmd(kvm))
174 return pud_present(pud);
175 else
176 return 1;
177}
114 178
115static inline phys_addr_t stage2_pmd_addr_end(phys_addr_t addr, phys_addr_t end) 179static inline void stage2_pud_populate(struct kvm *kvm, pud_t *pud, pmd_t *pmd)
116{ 180{
117 phys_addr_t boundary = (addr + S2_PMD_SIZE) & S2_PMD_MASK; 181 if (kvm_stage2_has_pmd(kvm))
182 pud_populate(NULL, pud, pmd);
183}
118 184
119 return (boundary - 1 < end - 1) ? boundary : end; 185static inline pmd_t *stage2_pmd_offset(struct kvm *kvm,
186 pud_t *pud, unsigned long address)
187{
188 if (kvm_stage2_has_pmd(kvm))
189 return pmd_offset(pud, address);
190 else
191 return (pmd_t *)pud;
120} 192}
121 193
122#endif /* STAGE2_PGTABLE_LEVELS > 2 */ 194static inline void stage2_pmd_free(struct kvm *kvm, pmd_t *pmd)
195{
196 if (kvm_stage2_has_pmd(kvm))
197 pmd_free(NULL, pmd);
198}
199
200static inline bool stage2_pud_huge(struct kvm *kvm, pud_t pud)
201{
202 if (kvm_stage2_has_pmd(kvm))
203 return pud_huge(pud);
204 else
205 return 0;
206}
207
208static inline bool stage2_pmd_table_empty(struct kvm *kvm, pmd_t *pmdp)
209{
210 if (kvm_stage2_has_pmd(kvm))
211 return kvm_page_empty(pmdp);
212 else
213 return 0;
214}
123 215
124#define stage2_pte_table_empty(ptep) kvm_page_empty(ptep) 216static inline phys_addr_t
217stage2_pmd_addr_end(struct kvm *kvm, phys_addr_t addr, phys_addr_t end)
218{
219 if (kvm_stage2_has_pmd(kvm)) {
220 phys_addr_t boundary = (addr + S2_PMD_SIZE) & S2_PMD_MASK;
125 221
126#if STAGE2_PGTABLE_LEVELS == 2 222 return (boundary - 1 < end - 1) ? boundary : end;
127#include <asm/stage2_pgtable-nopmd.h> 223 } else {
128#elif STAGE2_PGTABLE_LEVELS == 3 224 return end;
129#include <asm/stage2_pgtable-nopud.h> 225 }
130#endif 226}
131 227
228static inline bool stage2_pte_table_empty(struct kvm *kvm, pte_t *ptep)
229{
230 return kvm_page_empty(ptep);
231}
132 232
133#define stage2_pgd_index(addr) (((addr) >> S2_PGDIR_SHIFT) & (PTRS_PER_S2_PGD - 1)) 233static inline unsigned long stage2_pgd_index(struct kvm *kvm, phys_addr_t addr)
234{
235 return (((addr) >> stage2_pgdir_shift(kvm)) & (stage2_pgd_ptrs(kvm) - 1));
236}
134 237
135static inline phys_addr_t stage2_pgd_addr_end(phys_addr_t addr, phys_addr_t end) 238static inline phys_addr_t
239stage2_pgd_addr_end(struct kvm *kvm, phys_addr_t addr, phys_addr_t end)
136{ 240{
137 phys_addr_t boundary = (addr + S2_PGDIR_SIZE) & S2_PGDIR_MASK; 241 phys_addr_t boundary = (addr + stage2_pgdir_size(kvm)) & stage2_pgdir_mask(kvm);
138 242
139 return (boundary - 1 < end - 1) ? boundary : end; 243 return (boundary - 1 < end - 1) ? boundary : end;
140} 244}
diff --git a/arch/arm64/kvm/guest.c b/arch/arm64/kvm/guest.c
index a6c9fbaeaefc..dd436a50fce7 100644
--- a/arch/arm64/kvm/guest.c
+++ b/arch/arm64/kvm/guest.c
@@ -391,15 +391,15 @@ int __attribute_const__ kvm_target_cpu(void)
391 return KVM_ARM_TARGET_CORTEX_A53; 391 return KVM_ARM_TARGET_CORTEX_A53;
392 case ARM_CPU_PART_CORTEX_A57: 392 case ARM_CPU_PART_CORTEX_A57:
393 return KVM_ARM_TARGET_CORTEX_A57; 393 return KVM_ARM_TARGET_CORTEX_A57;
394 }; 394 }
395 break; 395 break;
396 case ARM_CPU_IMP_APM: 396 case ARM_CPU_IMP_APM:
397 switch (part_number) { 397 switch (part_number) {
398 case APM_CPU_PART_POTENZA: 398 case APM_CPU_PART_POTENZA:
399 return KVM_ARM_TARGET_XGENE_POTENZA; 399 return KVM_ARM_TARGET_XGENE_POTENZA;
400 }; 400 }
401 break; 401 break;
402 }; 402 }
403 403
404 /* Return a default generic target */ 404 /* Return a default generic target */
405 return KVM_ARM_TARGET_GENERIC_V8; 405 return KVM_ARM_TARGET_GENERIC_V8;
diff --git a/arch/arm64/kvm/handle_exit.c b/arch/arm64/kvm/handle_exit.c
index e5e741bfffe1..35a81bebd02b 100644
--- a/arch/arm64/kvm/handle_exit.c
+++ b/arch/arm64/kvm/handle_exit.c
@@ -284,6 +284,13 @@ int handle_exit(struct kvm_vcpu *vcpu, struct kvm_run *run,
284 */ 284 */
285 run->exit_reason = KVM_EXIT_FAIL_ENTRY; 285 run->exit_reason = KVM_EXIT_FAIL_ENTRY;
286 return 0; 286 return 0;
287 case ARM_EXCEPTION_IL:
288 /*
289 * We attempted an illegal exception return. Guest state must
290 * have been corrupted somehow. Give up.
291 */
292 run->exit_reason = KVM_EXIT_FAIL_ENTRY;
293 return -EINVAL;
287 default: 294 default:
288 kvm_pr_unimpl("Unsupported exception type: %d", 295 kvm_pr_unimpl("Unsupported exception type: %d",
289 exception_index); 296 exception_index);
diff --git a/arch/arm64/kvm/hyp/Makefile b/arch/arm64/kvm/hyp/Makefile
index 2fabc2dc1966..82d1904328ad 100644
--- a/arch/arm64/kvm/hyp/Makefile
+++ b/arch/arm64/kvm/hyp/Makefile
@@ -19,7 +19,6 @@ obj-$(CONFIG_KVM_ARM_HOST) += switch.o
19obj-$(CONFIG_KVM_ARM_HOST) += fpsimd.o 19obj-$(CONFIG_KVM_ARM_HOST) += fpsimd.o
20obj-$(CONFIG_KVM_ARM_HOST) += tlb.o 20obj-$(CONFIG_KVM_ARM_HOST) += tlb.o
21obj-$(CONFIG_KVM_ARM_HOST) += hyp-entry.o 21obj-$(CONFIG_KVM_ARM_HOST) += hyp-entry.o
22obj-$(CONFIG_KVM_ARM_HOST) += s2-setup.o
23 22
24# KVM code is run at a different exception code with a different map, so 23# KVM code is run at a different exception code with a different map, so
25# compiler instrumentation that inserts callbacks or checks into the code may 24# compiler instrumentation that inserts callbacks or checks into the code may
diff --git a/arch/arm64/kvm/hyp/hyp-entry.S b/arch/arm64/kvm/hyp/hyp-entry.S
index 24b4fbafe3e4..b1f14f736962 100644
--- a/arch/arm64/kvm/hyp/hyp-entry.S
+++ b/arch/arm64/kvm/hyp/hyp-entry.S
@@ -162,6 +162,20 @@ el1_error:
162 mov x0, #ARM_EXCEPTION_EL1_SERROR 162 mov x0, #ARM_EXCEPTION_EL1_SERROR
163 b __guest_exit 163 b __guest_exit
164 164
165el2_sync:
166 /* Check for illegal exception return, otherwise panic */
167 mrs x0, spsr_el2
168
169 /* if this was something else, then panic! */
170 tst x0, #PSR_IL_BIT
171 b.eq __hyp_panic
172
173 /* Let's attempt a recovery from the illegal exception return */
174 get_vcpu_ptr x1, x0
175 mov x0, #ARM_EXCEPTION_IL
176 b __guest_exit
177
178
165el2_error: 179el2_error:
166 ldp x0, x1, [sp], #16 180 ldp x0, x1, [sp], #16
167 181
@@ -240,7 +254,7 @@ ENTRY(__kvm_hyp_vector)
240 invalid_vect el2t_fiq_invalid // FIQ EL2t 254 invalid_vect el2t_fiq_invalid // FIQ EL2t
241 invalid_vect el2t_error_invalid // Error EL2t 255 invalid_vect el2t_error_invalid // Error EL2t
242 256
243 invalid_vect el2h_sync_invalid // Synchronous EL2h 257 valid_vect el2_sync // Synchronous EL2h
244 invalid_vect el2h_irq_invalid // IRQ EL2h 258 invalid_vect el2h_irq_invalid // IRQ EL2h
245 invalid_vect el2h_fiq_invalid // FIQ EL2h 259 invalid_vect el2h_fiq_invalid // FIQ EL2h
246 valid_vect el2_error // Error EL2h 260 valid_vect el2_error // Error EL2h
diff --git a/arch/arm64/kvm/hyp/s2-setup.c b/arch/arm64/kvm/hyp/s2-setup.c
deleted file mode 100644
index 603e1ee83e89..000000000000
--- a/arch/arm64/kvm/hyp/s2-setup.c
+++ /dev/null
@@ -1,90 +0,0 @@
1/*
2 * Copyright (C) 2016 - ARM Ltd
3 * Author: Marc Zyngier <marc.zyngier@arm.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#include <linux/types.h>
19#include <asm/kvm_arm.h>
20#include <asm/kvm_asm.h>
21#include <asm/kvm_hyp.h>
22
23u32 __hyp_text __init_stage2_translation(void)
24{
25 u64 val = VTCR_EL2_FLAGS;
26 u64 parange;
27 u64 tmp;
28
29 /*
30 * Read the PARange bits from ID_AA64MMFR0_EL1 and set the PS
31 * bits in VTCR_EL2. Amusingly, the PARange is 4 bits, while
32 * PS is only 3. Fortunately, bit 19 is RES0 in VTCR_EL2...
33 */
34 parange = read_sysreg(id_aa64mmfr0_el1) & 7;
35 if (parange > ID_AA64MMFR0_PARANGE_MAX)
36 parange = ID_AA64MMFR0_PARANGE_MAX;
37 val |= parange << 16;
38
39 /* Compute the actual PARange... */
40 switch (parange) {
41 case 0:
42 parange = 32;
43 break;
44 case 1:
45 parange = 36;
46 break;
47 case 2:
48 parange = 40;
49 break;
50 case 3:
51 parange = 42;
52 break;
53 case 4:
54 parange = 44;
55 break;
56 case 5:
57 default:
58 parange = 48;
59 break;
60 }
61
62 /*
63 * ... and clamp it to 40 bits, unless we have some braindead
64 * HW that implements less than that. In all cases, we'll
65 * return that value for the rest of the kernel to decide what
66 * to do.
67 */
68 val |= 64 - (parange > 40 ? 40 : parange);
69
70 /*
71 * Check the availability of Hardware Access Flag / Dirty Bit
72 * Management in ID_AA64MMFR1_EL1 and enable the feature in VTCR_EL2.
73 */
74 tmp = (read_sysreg(id_aa64mmfr1_el1) >> ID_AA64MMFR1_HADBS_SHIFT) & 0xf;
75 if (tmp)
76 val |= VTCR_EL2_HA;
77
78 /*
79 * Read the VMIDBits bits from ID_AA64MMFR1_EL1 and set the VS
80 * bit in VTCR_EL2.
81 */
82 tmp = (read_sysreg(id_aa64mmfr1_el1) >> ID_AA64MMFR1_VMIDBITS_SHIFT) & 0xf;
83 val |= (tmp == ID_AA64MMFR1_VMIDBITS_16) ?
84 VTCR_EL2_VS_16BIT :
85 VTCR_EL2_VS_8BIT;
86
87 write_sysreg(val, vtcr_el2);
88
89 return parange;
90}
diff --git a/arch/arm64/kvm/hyp/switch.c b/arch/arm64/kvm/hyp/switch.c
index ca46153d7915..7cc175c88a37 100644
--- a/arch/arm64/kvm/hyp/switch.c
+++ b/arch/arm64/kvm/hyp/switch.c
@@ -198,7 +198,7 @@ void deactivate_traps_vhe_put(void)
198 198
199static void __hyp_text __activate_vm(struct kvm *kvm) 199static void __hyp_text __activate_vm(struct kvm *kvm)
200{ 200{
201 write_sysreg(kvm->arch.vttbr, vttbr_el2); 201 __load_guest_stage2(kvm);
202} 202}
203 203
204static void __hyp_text __deactivate_vm(struct kvm_vcpu *vcpu) 204static void __hyp_text __deactivate_vm(struct kvm_vcpu *vcpu)
@@ -263,7 +263,7 @@ static bool __hyp_text __translate_far_to_hpfar(u64 far, u64 *hpfar)
263 return false; /* Translation failed, back to guest */ 263 return false; /* Translation failed, back to guest */
264 264
265 /* Convert PAR to HPFAR format */ 265 /* Convert PAR to HPFAR format */
266 *hpfar = ((tmp >> 12) & ((1UL << 36) - 1)) << 4; 266 *hpfar = PAR_TO_HPFAR(tmp);
267 return true; 267 return true;
268} 268}
269 269
diff --git a/arch/arm64/kvm/hyp/sysreg-sr.c b/arch/arm64/kvm/hyp/sysreg-sr.c
index 76d016b446b2..68d6f7c3b237 100644
--- a/arch/arm64/kvm/hyp/sysreg-sr.c
+++ b/arch/arm64/kvm/hyp/sysreg-sr.c
@@ -152,8 +152,25 @@ static void __hyp_text __sysreg_restore_el1_state(struct kvm_cpu_context *ctxt)
152static void __hyp_text 152static void __hyp_text
153__sysreg_restore_el2_return_state(struct kvm_cpu_context *ctxt) 153__sysreg_restore_el2_return_state(struct kvm_cpu_context *ctxt)
154{ 154{
155 u64 pstate = ctxt->gp_regs.regs.pstate;
156 u64 mode = pstate & PSR_AA32_MODE_MASK;
157
158 /*
159 * Safety check to ensure we're setting the CPU up to enter the guest
160 * in a less privileged mode.
161 *
162 * If we are attempting a return to EL2 or higher in AArch64 state,
163 * program SPSR_EL2 with M=EL2h and the IL bit set which ensures that
164 * we'll take an illegal exception state exception immediately after
165 * the ERET to the guest. Attempts to return to AArch32 Hyp will
166 * result in an illegal exception return because EL2's execution state
167 * is determined by SCR_EL3.RW.
168 */
169 if (!(mode & PSR_MODE32_BIT) && mode >= PSR_MODE_EL2t)
170 pstate = PSR_MODE_EL2h | PSR_IL_BIT;
171
155 write_sysreg_el2(ctxt->gp_regs.regs.pc, elr); 172 write_sysreg_el2(ctxt->gp_regs.regs.pc, elr);
156 write_sysreg_el2(ctxt->gp_regs.regs.pstate, spsr); 173 write_sysreg_el2(pstate, spsr);
157 174
158 if (cpus_have_const_cap(ARM64_HAS_RAS_EXTN)) 175 if (cpus_have_const_cap(ARM64_HAS_RAS_EXTN))
159 write_sysreg_s(ctxt->sys_regs[DISR_EL1], SYS_VDISR_EL2); 176 write_sysreg_s(ctxt->sys_regs[DISR_EL1], SYS_VDISR_EL2);
diff --git a/arch/arm64/kvm/hyp/tlb.c b/arch/arm64/kvm/hyp/tlb.c
index 131c7772703c..4dbd9c69a96d 100644
--- a/arch/arm64/kvm/hyp/tlb.c
+++ b/arch/arm64/kvm/hyp/tlb.c
@@ -30,7 +30,7 @@ static void __hyp_text __tlb_switch_to_guest_vhe(struct kvm *kvm)
30 * bits. Changing E2H is impossible (goodbye TTBR1_EL2), so 30 * bits. Changing E2H is impossible (goodbye TTBR1_EL2), so
31 * let's flip TGE before executing the TLB operation. 31 * let's flip TGE before executing the TLB operation.
32 */ 32 */
33 write_sysreg(kvm->arch.vttbr, vttbr_el2); 33 __load_guest_stage2(kvm);
34 val = read_sysreg(hcr_el2); 34 val = read_sysreg(hcr_el2);
35 val &= ~HCR_TGE; 35 val &= ~HCR_TGE;
36 write_sysreg(val, hcr_el2); 36 write_sysreg(val, hcr_el2);
@@ -39,7 +39,7 @@ static void __hyp_text __tlb_switch_to_guest_vhe(struct kvm *kvm)
39 39
40static void __hyp_text __tlb_switch_to_guest_nvhe(struct kvm *kvm) 40static void __hyp_text __tlb_switch_to_guest_nvhe(struct kvm *kvm)
41{ 41{
42 write_sysreg(kvm->arch.vttbr, vttbr_el2); 42 __load_guest_stage2(kvm);
43 isb(); 43 isb();
44} 44}
45 45
diff --git a/arch/arm64/kvm/reset.c b/arch/arm64/kvm/reset.c
index e37c78bbe1ca..b72a3dd56204 100644
--- a/arch/arm64/kvm/reset.c
+++ b/arch/arm64/kvm/reset.c
@@ -26,6 +26,7 @@
26 26
27#include <kvm/arm_arch_timer.h> 27#include <kvm/arm_arch_timer.h>
28 28
29#include <asm/cpufeature.h>
29#include <asm/cputype.h> 30#include <asm/cputype.h>
30#include <asm/ptrace.h> 31#include <asm/ptrace.h>
31#include <asm/kvm_arm.h> 32#include <asm/kvm_arm.h>
@@ -33,6 +34,9 @@
33#include <asm/kvm_coproc.h> 34#include <asm/kvm_coproc.h>
34#include <asm/kvm_mmu.h> 35#include <asm/kvm_mmu.h>
35 36
37/* Maximum phys_shift supported for any VM on this host */
38static u32 kvm_ipa_limit;
39
36/* 40/*
37 * ARMv8 Reset Values 41 * ARMv8 Reset Values
38 */ 42 */
@@ -55,12 +59,12 @@ static bool cpu_has_32bit_el1(void)
55} 59}
56 60
57/** 61/**
58 * kvm_arch_dev_ioctl_check_extension 62 * kvm_arch_vm_ioctl_check_extension
59 * 63 *
60 * We currently assume that the number of HW registers is uniform 64 * We currently assume that the number of HW registers is uniform
61 * across all CPUs (see cpuinfo_sanity_check). 65 * across all CPUs (see cpuinfo_sanity_check).
62 */ 66 */
63int kvm_arch_dev_ioctl_check_extension(struct kvm *kvm, long ext) 67int kvm_arch_vm_ioctl_check_extension(struct kvm *kvm, long ext)
64{ 68{
65 int r; 69 int r;
66 70
@@ -82,9 +86,11 @@ int kvm_arch_dev_ioctl_check_extension(struct kvm *kvm, long ext)
82 break; 86 break;
83 case KVM_CAP_SET_GUEST_DEBUG: 87 case KVM_CAP_SET_GUEST_DEBUG:
84 case KVM_CAP_VCPU_ATTRIBUTES: 88 case KVM_CAP_VCPU_ATTRIBUTES:
85 case KVM_CAP_VCPU_EVENTS:
86 r = 1; 89 r = 1;
87 break; 90 break;
91 case KVM_CAP_ARM_VM_IPA_SIZE:
92 r = kvm_ipa_limit;
93 break;
88 default: 94 default:
89 r = 0; 95 r = 0;
90 } 96 }
@@ -133,3 +139,99 @@ int kvm_reset_vcpu(struct kvm_vcpu *vcpu)
133 /* Reset timer */ 139 /* Reset timer */
134 return kvm_timer_vcpu_reset(vcpu); 140 return kvm_timer_vcpu_reset(vcpu);
135} 141}
142
143void kvm_set_ipa_limit(void)
144{
145 unsigned int ipa_max, pa_max, va_max, parange;
146
147 parange = read_sanitised_ftr_reg(SYS_ID_AA64MMFR0_EL1) & 0x7;
148 pa_max = id_aa64mmfr0_parange_to_phys_shift(parange);
149
150 /* Clamp the IPA limit to the PA size supported by the kernel */
151 ipa_max = (pa_max > PHYS_MASK_SHIFT) ? PHYS_MASK_SHIFT : pa_max;
152 /*
153 * Since our stage2 table is dependent on the stage1 page table code,
154 * we must always honor the following condition:
155 *
156 * Number of levels in Stage1 >= Number of levels in Stage2.
157 *
158 * So clamp the ipa limit further down to limit the number of levels.
159 * Since we can concatenate upto 16 tables at entry level, we could
160 * go upto 4bits above the maximum VA addressible with the current
161 * number of levels.
162 */
163 va_max = PGDIR_SHIFT + PAGE_SHIFT - 3;
164 va_max += 4;
165
166 if (va_max < ipa_max)
167 ipa_max = va_max;
168
169 /*
170 * If the final limit is lower than the real physical address
171 * limit of the CPUs, report the reason.
172 */
173 if (ipa_max < pa_max)
174 pr_info("kvm: Limiting the IPA size due to kernel %s Address limit\n",
175 (va_max < pa_max) ? "Virtual" : "Physical");
176
177 WARN(ipa_max < KVM_PHYS_SHIFT,
178 "KVM IPA limit (%d bit) is smaller than default size\n", ipa_max);
179 kvm_ipa_limit = ipa_max;
180 kvm_info("IPA Size Limit: %dbits\n", kvm_ipa_limit);
181}
182
183/*
184 * Configure the VTCR_EL2 for this VM. The VTCR value is common
185 * across all the physical CPUs on the system. We use system wide
186 * sanitised values to fill in different fields, except for Hardware
187 * Management of Access Flags. HA Flag is set unconditionally on
188 * all CPUs, as it is safe to run with or without the feature and
189 * the bit is RES0 on CPUs that don't support it.
190 */
191int kvm_arm_setup_stage2(struct kvm *kvm, unsigned long type)
192{
193 u64 vtcr = VTCR_EL2_FLAGS;
194 u32 parange, phys_shift;
195 u8 lvls;
196
197 if (type & ~KVM_VM_TYPE_ARM_IPA_SIZE_MASK)
198 return -EINVAL;
199
200 phys_shift = KVM_VM_TYPE_ARM_IPA_SIZE(type);
201 if (phys_shift) {
202 if (phys_shift > kvm_ipa_limit ||
203 phys_shift < 32)
204 return -EINVAL;
205 } else {
206 phys_shift = KVM_PHYS_SHIFT;
207 }
208
209 parange = read_sanitised_ftr_reg(SYS_ID_AA64MMFR0_EL1) & 7;
210 if (parange > ID_AA64MMFR0_PARANGE_MAX)
211 parange = ID_AA64MMFR0_PARANGE_MAX;
212 vtcr |= parange << VTCR_EL2_PS_SHIFT;
213
214 vtcr |= VTCR_EL2_T0SZ(phys_shift);
215 /*
216 * Use a minimum 2 level page table to prevent splitting
217 * host PMD huge pages at stage2.
218 */
219 lvls = stage2_pgtable_levels(phys_shift);
220 if (lvls < 2)
221 lvls = 2;
222 vtcr |= VTCR_EL2_LVLS_TO_SL0(lvls);
223
224 /*
225 * Enable the Hardware Access Flag management, unconditionally
226 * on all CPUs. The features is RES0 on CPUs without the support
227 * and must be ignored by the CPUs.
228 */
229 vtcr |= VTCR_EL2_HA;
230
231 /* Set the vmid bits */
232 vtcr |= (kvm_get_vmid_bits() == 16) ?
233 VTCR_EL2_VS_16BIT :
234 VTCR_EL2_VS_8BIT;
235 kvm->arch.vtcr = vtcr;
236 return 0;
237}
diff --git a/arch/powerpc/include/asm/asm-prototypes.h b/arch/powerpc/include/asm/asm-prototypes.h
index 1f4691ce4126..c55ba3b4873b 100644
--- a/arch/powerpc/include/asm/asm-prototypes.h
+++ b/arch/powerpc/include/asm/asm-prototypes.h
@@ -150,4 +150,25 @@ extern s32 patch__memset_nocache, patch__memcpy_nocache;
150 150
151extern long flush_count_cache; 151extern long flush_count_cache;
152 152
153#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
154void kvmppc_save_tm_hv(struct kvm_vcpu *vcpu, u64 msr, bool preserve_nv);
155void kvmppc_restore_tm_hv(struct kvm_vcpu *vcpu, u64 msr, bool preserve_nv);
156#else
157static inline void kvmppc_save_tm_hv(struct kvm_vcpu *vcpu, u64 msr,
158 bool preserve_nv) { }
159static inline void kvmppc_restore_tm_hv(struct kvm_vcpu *vcpu, u64 msr,
160 bool preserve_nv) { }
161#endif /* CONFIG_PPC_TRANSACTIONAL_MEM */
162
163void kvmhv_save_host_pmu(void);
164void kvmhv_load_host_pmu(void);
165void kvmhv_save_guest_pmu(struct kvm_vcpu *vcpu, bool pmu_in_use);
166void kvmhv_load_guest_pmu(struct kvm_vcpu *vcpu);
167
168int __kvmhv_vcpu_entry_p9(struct kvm_vcpu *vcpu);
169
170long kvmppc_h_set_dabr(struct kvm_vcpu *vcpu, unsigned long dabr);
171long kvmppc_h_set_xdabr(struct kvm_vcpu *vcpu, unsigned long dabr,
172 unsigned long dabrx);
173
153#endif /* _ASM_POWERPC_ASM_PROTOTYPES_H */ 174#endif /* _ASM_POWERPC_ASM_PROTOTYPES_H */
diff --git a/arch/powerpc/include/asm/book3s/64/mmu-hash.h b/arch/powerpc/include/asm/book3s/64/mmu-hash.h
index b3520b549cba..66db23e2f4dc 100644
--- a/arch/powerpc/include/asm/book3s/64/mmu-hash.h
+++ b/arch/powerpc/include/asm/book3s/64/mmu-hash.h
@@ -203,6 +203,18 @@ static inline unsigned int mmu_psize_to_shift(unsigned int mmu_psize)
203 BUG(); 203 BUG();
204} 204}
205 205
206static inline unsigned int ap_to_shift(unsigned long ap)
207{
208 int psize;
209
210 for (psize = 0; psize < MMU_PAGE_COUNT; psize++) {
211 if (mmu_psize_defs[psize].ap == ap)
212 return mmu_psize_defs[psize].shift;
213 }
214
215 return -1;
216}
217
206static inline unsigned long get_sllp_encoding(int psize) 218static inline unsigned long get_sllp_encoding(int psize)
207{ 219{
208 unsigned long sllp; 220 unsigned long sllp;
diff --git a/arch/powerpc/include/asm/book3s/64/tlbflush-radix.h b/arch/powerpc/include/asm/book3s/64/tlbflush-radix.h
index 1154a6dc6d26..671316f9e95d 100644
--- a/arch/powerpc/include/asm/book3s/64/tlbflush-radix.h
+++ b/arch/powerpc/include/asm/book3s/64/tlbflush-radix.h
@@ -53,6 +53,7 @@ extern void radix__flush_tlb_lpid_page(unsigned int lpid,
53 unsigned long addr, 53 unsigned long addr,
54 unsigned long page_size); 54 unsigned long page_size);
55extern void radix__flush_pwc_lpid(unsigned int lpid); 55extern void radix__flush_pwc_lpid(unsigned int lpid);
56extern void radix__flush_tlb_lpid(unsigned int lpid);
56extern void radix__local_flush_tlb_lpid(unsigned int lpid); 57extern void radix__local_flush_tlb_lpid(unsigned int lpid);
57extern void radix__local_flush_tlb_lpid_guest(unsigned int lpid); 58extern void radix__local_flush_tlb_lpid_guest(unsigned int lpid);
58 59
diff --git a/arch/powerpc/include/asm/hvcall.h b/arch/powerpc/include/asm/hvcall.h
index a0b17f9f1ea4..45e8789bb770 100644
--- a/arch/powerpc/include/asm/hvcall.h
+++ b/arch/powerpc/include/asm/hvcall.h
@@ -322,6 +322,11 @@
322#define H_GET_24X7_DATA 0xF07C 322#define H_GET_24X7_DATA 0xF07C
323#define H_GET_PERF_COUNTER_INFO 0xF080 323#define H_GET_PERF_COUNTER_INFO 0xF080
324 324
325/* Platform-specific hcalls used for nested HV KVM */
326#define H_SET_PARTITION_TABLE 0xF800
327#define H_ENTER_NESTED 0xF804
328#define H_TLB_INVALIDATE 0xF808
329
325/* Values for 2nd argument to H_SET_MODE */ 330/* Values for 2nd argument to H_SET_MODE */
326#define H_SET_MODE_RESOURCE_SET_CIABR 1 331#define H_SET_MODE_RESOURCE_SET_CIABR 1
327#define H_SET_MODE_RESOURCE_SET_DAWR 2 332#define H_SET_MODE_RESOURCE_SET_DAWR 2
@@ -461,6 +466,42 @@ struct h_cpu_char_result {
461 u64 behaviour; 466 u64 behaviour;
462}; 467};
463 468
469/* Register state for entering a nested guest with H_ENTER_NESTED */
470struct hv_guest_state {
471 u64 version; /* version of this structure layout */
472 u32 lpid;
473 u32 vcpu_token;
474 /* These registers are hypervisor privileged (at least for writing) */
475 u64 lpcr;
476 u64 pcr;
477 u64 amor;
478 u64 dpdes;
479 u64 hfscr;
480 s64 tb_offset;
481 u64 dawr0;
482 u64 dawrx0;
483 u64 ciabr;
484 u64 hdec_expiry;
485 u64 purr;
486 u64 spurr;
487 u64 ic;
488 u64 vtb;
489 u64 hdar;
490 u64 hdsisr;
491 u64 heir;
492 u64 asdr;
493 /* These are OS privileged but need to be set late in guest entry */
494 u64 srr0;
495 u64 srr1;
496 u64 sprg[4];
497 u64 pidr;
498 u64 cfar;
499 u64 ppr;
500};
501
502/* Latest version of hv_guest_state structure */
503#define HV_GUEST_STATE_VERSION 1
504
464#endif /* __ASSEMBLY__ */ 505#endif /* __ASSEMBLY__ */
465#endif /* __KERNEL__ */ 506#endif /* __KERNEL__ */
466#endif /* _ASM_POWERPC_HVCALL_H */ 507#endif /* _ASM_POWERPC_HVCALL_H */
diff --git a/arch/powerpc/include/asm/iommu.h b/arch/powerpc/include/asm/iommu.h
index 3d4b88cb8599..35db0cbc9222 100644
--- a/arch/powerpc/include/asm/iommu.h
+++ b/arch/powerpc/include/asm/iommu.h
@@ -126,7 +126,7 @@ struct iommu_table {
126 int it_nid; 126 int it_nid;
127}; 127};
128 128
129#define IOMMU_TABLE_USERSPACE_ENTRY_RM(tbl, entry) \ 129#define IOMMU_TABLE_USERSPACE_ENTRY_RO(tbl, entry) \
130 ((tbl)->it_ops->useraddrptr((tbl), (entry), false)) 130 ((tbl)->it_ops->useraddrptr((tbl), (entry), false))
131#define IOMMU_TABLE_USERSPACE_ENTRY(tbl, entry) \ 131#define IOMMU_TABLE_USERSPACE_ENTRY(tbl, entry) \
132 ((tbl)->it_ops->useraddrptr((tbl), (entry), true)) 132 ((tbl)->it_ops->useraddrptr((tbl), (entry), true))
diff --git a/arch/powerpc/include/asm/kvm_asm.h b/arch/powerpc/include/asm/kvm_asm.h
index a790d5cf6ea3..1f321914676d 100644
--- a/arch/powerpc/include/asm/kvm_asm.h
+++ b/arch/powerpc/include/asm/kvm_asm.h
@@ -84,7 +84,6 @@
84#define BOOK3S_INTERRUPT_INST_STORAGE 0x400 84#define BOOK3S_INTERRUPT_INST_STORAGE 0x400
85#define BOOK3S_INTERRUPT_INST_SEGMENT 0x480 85#define BOOK3S_INTERRUPT_INST_SEGMENT 0x480
86#define BOOK3S_INTERRUPT_EXTERNAL 0x500 86#define BOOK3S_INTERRUPT_EXTERNAL 0x500
87#define BOOK3S_INTERRUPT_EXTERNAL_LEVEL 0x501
88#define BOOK3S_INTERRUPT_EXTERNAL_HV 0x502 87#define BOOK3S_INTERRUPT_EXTERNAL_HV 0x502
89#define BOOK3S_INTERRUPT_ALIGNMENT 0x600 88#define BOOK3S_INTERRUPT_ALIGNMENT 0x600
90#define BOOK3S_INTERRUPT_PROGRAM 0x700 89#define BOOK3S_INTERRUPT_PROGRAM 0x700
@@ -134,8 +133,7 @@
134#define BOOK3S_IRQPRIO_EXTERNAL 14 133#define BOOK3S_IRQPRIO_EXTERNAL 14
135#define BOOK3S_IRQPRIO_DECREMENTER 15 134#define BOOK3S_IRQPRIO_DECREMENTER 15
136#define BOOK3S_IRQPRIO_PERFORMANCE_MONITOR 16 135#define BOOK3S_IRQPRIO_PERFORMANCE_MONITOR 16
137#define BOOK3S_IRQPRIO_EXTERNAL_LEVEL 17 136#define BOOK3S_IRQPRIO_MAX 17
138#define BOOK3S_IRQPRIO_MAX 18
139 137
140#define BOOK3S_HFLAG_DCBZ32 0x1 138#define BOOK3S_HFLAG_DCBZ32 0x1
141#define BOOK3S_HFLAG_SLB 0x2 139#define BOOK3S_HFLAG_SLB 0x2
diff --git a/arch/powerpc/include/asm/kvm_book3s.h b/arch/powerpc/include/asm/kvm_book3s.h
index 83a9aa3cf689..09f8e9ba69bc 100644
--- a/arch/powerpc/include/asm/kvm_book3s.h
+++ b/arch/powerpc/include/asm/kvm_book3s.h
@@ -188,14 +188,37 @@ extern int kvmppc_book3s_hcall_implemented(struct kvm *kvm, unsigned long hc);
188extern int kvmppc_book3s_radix_page_fault(struct kvm_run *run, 188extern int kvmppc_book3s_radix_page_fault(struct kvm_run *run,
189 struct kvm_vcpu *vcpu, 189 struct kvm_vcpu *vcpu,
190 unsigned long ea, unsigned long dsisr); 190 unsigned long ea, unsigned long dsisr);
191extern int kvmppc_mmu_walk_radix_tree(struct kvm_vcpu *vcpu, gva_t eaddr,
192 struct kvmppc_pte *gpte, u64 root,
193 u64 *pte_ret_p);
194extern int kvmppc_mmu_radix_translate_table(struct kvm_vcpu *vcpu, gva_t eaddr,
195 struct kvmppc_pte *gpte, u64 table,
196 int table_index, u64 *pte_ret_p);
191extern int kvmppc_mmu_radix_xlate(struct kvm_vcpu *vcpu, gva_t eaddr, 197extern int kvmppc_mmu_radix_xlate(struct kvm_vcpu *vcpu, gva_t eaddr,
192 struct kvmppc_pte *gpte, bool data, bool iswrite); 198 struct kvmppc_pte *gpte, bool data, bool iswrite);
199extern void kvmppc_unmap_pte(struct kvm *kvm, pte_t *pte, unsigned long gpa,
200 unsigned int shift, struct kvm_memory_slot *memslot,
201 unsigned int lpid);
202extern bool kvmppc_hv_handle_set_rc(struct kvm *kvm, pgd_t *pgtable,
203 bool writing, unsigned long gpa,
204 unsigned int lpid);
205extern int kvmppc_book3s_instantiate_page(struct kvm_vcpu *vcpu,
206 unsigned long gpa,
207 struct kvm_memory_slot *memslot,
208 bool writing, bool kvm_ro,
209 pte_t *inserted_pte, unsigned int *levelp);
193extern int kvmppc_init_vm_radix(struct kvm *kvm); 210extern int kvmppc_init_vm_radix(struct kvm *kvm);
194extern void kvmppc_free_radix(struct kvm *kvm); 211extern void kvmppc_free_radix(struct kvm *kvm);
212extern void kvmppc_free_pgtable_radix(struct kvm *kvm, pgd_t *pgd,
213 unsigned int lpid);
195extern int kvmppc_radix_init(void); 214extern int kvmppc_radix_init(void);
196extern void kvmppc_radix_exit(void); 215extern void kvmppc_radix_exit(void);
197extern int kvm_unmap_radix(struct kvm *kvm, struct kvm_memory_slot *memslot, 216extern int kvm_unmap_radix(struct kvm *kvm, struct kvm_memory_slot *memslot,
198 unsigned long gfn); 217 unsigned long gfn);
218extern void kvmppc_unmap_pte(struct kvm *kvm, pte_t *pte,
219 unsigned long gpa, unsigned int shift,
220 struct kvm_memory_slot *memslot,
221 unsigned int lpid);
199extern int kvm_age_radix(struct kvm *kvm, struct kvm_memory_slot *memslot, 222extern int kvm_age_radix(struct kvm *kvm, struct kvm_memory_slot *memslot,
200 unsigned long gfn); 223 unsigned long gfn);
201extern int kvm_test_age_radix(struct kvm *kvm, struct kvm_memory_slot *memslot, 224extern int kvm_test_age_radix(struct kvm *kvm, struct kvm_memory_slot *memslot,
@@ -271,6 +294,21 @@ static inline void kvmppc_save_tm_sprs(struct kvm_vcpu *vcpu) {}
271static inline void kvmppc_restore_tm_sprs(struct kvm_vcpu *vcpu) {} 294static inline void kvmppc_restore_tm_sprs(struct kvm_vcpu *vcpu) {}
272#endif 295#endif
273 296
297long kvmhv_nested_init(void);
298void kvmhv_nested_exit(void);
299void kvmhv_vm_nested_init(struct kvm *kvm);
300long kvmhv_set_partition_table(struct kvm_vcpu *vcpu);
301void kvmhv_set_ptbl_entry(unsigned int lpid, u64 dw0, u64 dw1);
302void kvmhv_release_all_nested(struct kvm *kvm);
303long kvmhv_enter_nested_guest(struct kvm_vcpu *vcpu);
304long kvmhv_do_nested_tlbie(struct kvm_vcpu *vcpu);
305int kvmhv_run_single_vcpu(struct kvm_run *kvm_run, struct kvm_vcpu *vcpu,
306 u64 time_limit, unsigned long lpcr);
307void kvmhv_save_hv_regs(struct kvm_vcpu *vcpu, struct hv_guest_state *hr);
308void kvmhv_restore_hv_return_state(struct kvm_vcpu *vcpu,
309 struct hv_guest_state *hr);
310long int kvmhv_nested_page_fault(struct kvm_vcpu *vcpu);
311
274void kvmppc_giveup_fac(struct kvm_vcpu *vcpu, ulong fac); 312void kvmppc_giveup_fac(struct kvm_vcpu *vcpu, ulong fac);
275 313
276extern int kvm_irq_bypass; 314extern int kvm_irq_bypass;
@@ -301,12 +339,12 @@ static inline ulong kvmppc_get_gpr(struct kvm_vcpu *vcpu, int num)
301 339
302static inline void kvmppc_set_cr(struct kvm_vcpu *vcpu, u32 val) 340static inline void kvmppc_set_cr(struct kvm_vcpu *vcpu, u32 val)
303{ 341{
304 vcpu->arch.cr = val; 342 vcpu->arch.regs.ccr = val;
305} 343}
306 344
307static inline u32 kvmppc_get_cr(struct kvm_vcpu *vcpu) 345static inline u32 kvmppc_get_cr(struct kvm_vcpu *vcpu)
308{ 346{
309 return vcpu->arch.cr; 347 return vcpu->arch.regs.ccr;
310} 348}
311 349
312static inline void kvmppc_set_xer(struct kvm_vcpu *vcpu, ulong val) 350static inline void kvmppc_set_xer(struct kvm_vcpu *vcpu, ulong val)
@@ -384,9 +422,6 @@ extern int kvmppc_h_logical_ci_store(struct kvm_vcpu *vcpu);
384/* TO = 31 for unconditional trap */ 422/* TO = 31 for unconditional trap */
385#define INS_TW 0x7fe00008 423#define INS_TW 0x7fe00008
386 424
387/* LPIDs we support with this build -- runtime limit may be lower */
388#define KVMPPC_NR_LPIDS (LPID_RSVD + 1)
389
390#define SPLIT_HACK_MASK 0xff000000 425#define SPLIT_HACK_MASK 0xff000000
391#define SPLIT_HACK_OFFS 0xfb000000 426#define SPLIT_HACK_OFFS 0xfb000000
392 427
diff --git a/arch/powerpc/include/asm/kvm_book3s_64.h b/arch/powerpc/include/asm/kvm_book3s_64.h
index dc435a5af7d6..6d298145d564 100644
--- a/arch/powerpc/include/asm/kvm_book3s_64.h
+++ b/arch/powerpc/include/asm/kvm_book3s_64.h
@@ -23,6 +23,108 @@
23#include <linux/string.h> 23#include <linux/string.h>
24#include <asm/bitops.h> 24#include <asm/bitops.h>
25#include <asm/book3s/64/mmu-hash.h> 25#include <asm/book3s/64/mmu-hash.h>
26#include <asm/cpu_has_feature.h>
27#include <asm/ppc-opcode.h>
28
29#ifdef CONFIG_PPC_PSERIES
30static inline bool kvmhv_on_pseries(void)
31{
32 return !cpu_has_feature(CPU_FTR_HVMODE);
33}
34#else
35static inline bool kvmhv_on_pseries(void)
36{
37 return false;
38}
39#endif
40
41/*
42 * Structure for a nested guest, that is, for a guest that is managed by
43 * one of our guests.
44 */
45struct kvm_nested_guest {
46 struct kvm *l1_host; /* L1 VM that owns this nested guest */
47 int l1_lpid; /* lpid L1 guest thinks this guest is */
48 int shadow_lpid; /* real lpid of this nested guest */
49 pgd_t *shadow_pgtable; /* our page table for this guest */
50 u64 l1_gr_to_hr; /* L1's addr of part'n-scoped table */
51 u64 process_table; /* process table entry for this guest */
52 long refcnt; /* number of pointers to this struct */
53 struct mutex tlb_lock; /* serialize page faults and tlbies */
54 struct kvm_nested_guest *next;
55 cpumask_t need_tlb_flush;
56 cpumask_t cpu_in_guest;
57 short prev_cpu[NR_CPUS];
58};
59
60/*
61 * We define a nested rmap entry as a single 64-bit quantity
62 * 0xFFF0000000000000 12-bit lpid field
63 * 0x000FFFFFFFFFF000 40-bit guest 4k page frame number
64 * 0x0000000000000001 1-bit single entry flag
65 */
66#define RMAP_NESTED_LPID_MASK 0xFFF0000000000000UL
67#define RMAP_NESTED_LPID_SHIFT (52)
68#define RMAP_NESTED_GPA_MASK 0x000FFFFFFFFFF000UL
69#define RMAP_NESTED_IS_SINGLE_ENTRY 0x0000000000000001UL
70
71/* Structure for a nested guest rmap entry */
72struct rmap_nested {
73 struct llist_node list;
74 u64 rmap;
75};
76
77/*
78 * for_each_nest_rmap_safe - iterate over the list of nested rmap entries
79 * safe against removal of the list entry or NULL list
80 * @pos: a (struct rmap_nested *) to use as a loop cursor
81 * @node: pointer to the first entry
82 * NOTE: this can be NULL
83 * @rmapp: an (unsigned long *) in which to return the rmap entries on each
84 * iteration
85 * NOTE: this must point to already allocated memory
86 *
87 * The nested_rmap is a llist of (struct rmap_nested) entries pointed to by the
88 * rmap entry in the memslot. The list is always terminated by a "single entry"
89 * stored in the list element of the final entry of the llist. If there is ONLY
90 * a single entry then this is itself in the rmap entry of the memslot, not a
91 * llist head pointer.
92 *
93 * Note that the iterator below assumes that a nested rmap entry is always
94 * non-zero. This is true for our usage because the LPID field is always
95 * non-zero (zero is reserved for the host).
96 *
97 * This should be used to iterate over the list of rmap_nested entries with
98 * processing done on the u64 rmap value given by each iteration. This is safe
99 * against removal of list entries and it is always safe to call free on (pos).
100 *
101 * e.g.
102 * struct rmap_nested *cursor;
103 * struct llist_node *first;
104 * unsigned long rmap;
105 * for_each_nest_rmap_safe(cursor, first, &rmap) {
106 * do_something(rmap);
107 * free(cursor);
108 * }
109 */
110#define for_each_nest_rmap_safe(pos, node, rmapp) \
111 for ((pos) = llist_entry((node), typeof(*(pos)), list); \
112 (node) && \
113 (*(rmapp) = ((RMAP_NESTED_IS_SINGLE_ENTRY & ((u64) (node))) ? \
114 ((u64) (node)) : ((pos)->rmap))) && \
115 (((node) = ((RMAP_NESTED_IS_SINGLE_ENTRY & ((u64) (node))) ? \
116 ((struct llist_node *) ((pos) = NULL)) : \
117 (pos)->list.next)), true); \
118 (pos) = llist_entry((node), typeof(*(pos)), list))
119
120struct kvm_nested_guest *kvmhv_get_nested(struct kvm *kvm, int l1_lpid,
121 bool create);
122void kvmhv_put_nested(struct kvm_nested_guest *gp);
123int kvmhv_nested_next_lpid(struct kvm *kvm, int lpid);
124
125/* Encoding of first parameter for H_TLB_INVALIDATE */
126#define H_TLBIE_P1_ENC(ric, prs, r) (___PPC_RIC(ric) | ___PPC_PRS(prs) | \
127 ___PPC_R(r))
26 128
27/* Power architecture requires HPT is at least 256kiB, at most 64TiB */ 129/* Power architecture requires HPT is at least 256kiB, at most 64TiB */
28#define PPC_MIN_HPT_ORDER 18 130#define PPC_MIN_HPT_ORDER 18
@@ -435,6 +537,7 @@ static inline struct kvm_memslots *kvm_memslots_raw(struct kvm *kvm)
435} 537}
436 538
437extern void kvmppc_mmu_debugfs_init(struct kvm *kvm); 539extern void kvmppc_mmu_debugfs_init(struct kvm *kvm);
540extern void kvmhv_radix_debugfs_init(struct kvm *kvm);
438 541
439extern void kvmhv_rm_send_ipi(int cpu); 542extern void kvmhv_rm_send_ipi(int cpu);
440 543
@@ -482,7 +585,7 @@ static inline u64 sanitize_msr(u64 msr)
482#ifdef CONFIG_PPC_TRANSACTIONAL_MEM 585#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
483static inline void copy_from_checkpoint(struct kvm_vcpu *vcpu) 586static inline void copy_from_checkpoint(struct kvm_vcpu *vcpu)
484{ 587{
485 vcpu->arch.cr = vcpu->arch.cr_tm; 588 vcpu->arch.regs.ccr = vcpu->arch.cr_tm;
486 vcpu->arch.regs.xer = vcpu->arch.xer_tm; 589 vcpu->arch.regs.xer = vcpu->arch.xer_tm;
487 vcpu->arch.regs.link = vcpu->arch.lr_tm; 590 vcpu->arch.regs.link = vcpu->arch.lr_tm;
488 vcpu->arch.regs.ctr = vcpu->arch.ctr_tm; 591 vcpu->arch.regs.ctr = vcpu->arch.ctr_tm;
@@ -499,7 +602,7 @@ static inline void copy_from_checkpoint(struct kvm_vcpu *vcpu)
499 602
500static inline void copy_to_checkpoint(struct kvm_vcpu *vcpu) 603static inline void copy_to_checkpoint(struct kvm_vcpu *vcpu)
501{ 604{
502 vcpu->arch.cr_tm = vcpu->arch.cr; 605 vcpu->arch.cr_tm = vcpu->arch.regs.ccr;
503 vcpu->arch.xer_tm = vcpu->arch.regs.xer; 606 vcpu->arch.xer_tm = vcpu->arch.regs.xer;
504 vcpu->arch.lr_tm = vcpu->arch.regs.link; 607 vcpu->arch.lr_tm = vcpu->arch.regs.link;
505 vcpu->arch.ctr_tm = vcpu->arch.regs.ctr; 608 vcpu->arch.ctr_tm = vcpu->arch.regs.ctr;
@@ -515,6 +618,17 @@ static inline void copy_to_checkpoint(struct kvm_vcpu *vcpu)
515} 618}
516#endif /* CONFIG_PPC_TRANSACTIONAL_MEM */ 619#endif /* CONFIG_PPC_TRANSACTIONAL_MEM */
517 620
621extern int kvmppc_create_pte(struct kvm *kvm, pgd_t *pgtable, pte_t pte,
622 unsigned long gpa, unsigned int level,
623 unsigned long mmu_seq, unsigned int lpid,
624 unsigned long *rmapp, struct rmap_nested **n_rmap);
625extern void kvmhv_insert_nest_rmap(struct kvm *kvm, unsigned long *rmapp,
626 struct rmap_nested **n_rmap);
627extern void kvmhv_remove_nest_rmap_range(struct kvm *kvm,
628 struct kvm_memory_slot *memslot,
629 unsigned long gpa, unsigned long hpa,
630 unsigned long nbytes);
631
518#endif /* CONFIG_KVM_BOOK3S_HV_POSSIBLE */ 632#endif /* CONFIG_KVM_BOOK3S_HV_POSSIBLE */
519 633
520#endif /* __ASM_KVM_BOOK3S_64_H__ */ 634#endif /* __ASM_KVM_BOOK3S_64_H__ */
diff --git a/arch/powerpc/include/asm/kvm_book3s_asm.h b/arch/powerpc/include/asm/kvm_book3s_asm.h
index d978fdf698af..eb3ba6390108 100644
--- a/arch/powerpc/include/asm/kvm_book3s_asm.h
+++ b/arch/powerpc/include/asm/kvm_book3s_asm.h
@@ -25,6 +25,9 @@
25#define XICS_MFRR 0xc 25#define XICS_MFRR 0xc
26#define XICS_IPI 2 /* interrupt source # for IPIs */ 26#define XICS_IPI 2 /* interrupt source # for IPIs */
27 27
28/* LPIDs we support with this build -- runtime limit may be lower */
29#define KVMPPC_NR_LPIDS (LPID_RSVD + 1)
30
28/* Maximum number of threads per physical core */ 31/* Maximum number of threads per physical core */
29#define MAX_SMT_THREADS 8 32#define MAX_SMT_THREADS 8
30 33
diff --git a/arch/powerpc/include/asm/kvm_booke.h b/arch/powerpc/include/asm/kvm_booke.h
index d513e3ed1c65..f0cef625f17c 100644
--- a/arch/powerpc/include/asm/kvm_booke.h
+++ b/arch/powerpc/include/asm/kvm_booke.h
@@ -46,12 +46,12 @@ static inline ulong kvmppc_get_gpr(struct kvm_vcpu *vcpu, int num)
46 46
47static inline void kvmppc_set_cr(struct kvm_vcpu *vcpu, u32 val) 47static inline void kvmppc_set_cr(struct kvm_vcpu *vcpu, u32 val)
48{ 48{
49 vcpu->arch.cr = val; 49 vcpu->arch.regs.ccr = val;
50} 50}
51 51
52static inline u32 kvmppc_get_cr(struct kvm_vcpu *vcpu) 52static inline u32 kvmppc_get_cr(struct kvm_vcpu *vcpu)
53{ 53{
54 return vcpu->arch.cr; 54 return vcpu->arch.regs.ccr;
55} 55}
56 56
57static inline void kvmppc_set_xer(struct kvm_vcpu *vcpu, ulong val) 57static inline void kvmppc_set_xer(struct kvm_vcpu *vcpu, ulong val)
diff --git a/arch/powerpc/include/asm/kvm_host.h b/arch/powerpc/include/asm/kvm_host.h
index 906bcbdfd2a1..fac6f631ed29 100644
--- a/arch/powerpc/include/asm/kvm_host.h
+++ b/arch/powerpc/include/asm/kvm_host.h
@@ -46,6 +46,7 @@
46#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE 46#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
47#include <asm/kvm_book3s_asm.h> /* for MAX_SMT_THREADS */ 47#include <asm/kvm_book3s_asm.h> /* for MAX_SMT_THREADS */
48#define KVM_MAX_VCPU_ID (MAX_SMT_THREADS * KVM_MAX_VCORES) 48#define KVM_MAX_VCPU_ID (MAX_SMT_THREADS * KVM_MAX_VCORES)
49#define KVM_MAX_NESTED_GUESTS KVMPPC_NR_LPIDS
49 50
50#else 51#else
51#define KVM_MAX_VCPU_ID KVM_MAX_VCPUS 52#define KVM_MAX_VCPU_ID KVM_MAX_VCPUS
@@ -94,6 +95,7 @@ struct dtl_entry;
94 95
95struct kvmppc_vcpu_book3s; 96struct kvmppc_vcpu_book3s;
96struct kvmppc_book3s_shadow_vcpu; 97struct kvmppc_book3s_shadow_vcpu;
98struct kvm_nested_guest;
97 99
98struct kvm_vm_stat { 100struct kvm_vm_stat {
99 ulong remote_tlb_flush; 101 ulong remote_tlb_flush;
@@ -287,10 +289,12 @@ struct kvm_arch {
287 u8 radix; 289 u8 radix;
288 u8 fwnmi_enabled; 290 u8 fwnmi_enabled;
289 bool threads_indep; 291 bool threads_indep;
292 bool nested_enable;
290 pgd_t *pgtable; 293 pgd_t *pgtable;
291 u64 process_table; 294 u64 process_table;
292 struct dentry *debugfs_dir; 295 struct dentry *debugfs_dir;
293 struct dentry *htab_dentry; 296 struct dentry *htab_dentry;
297 struct dentry *radix_dentry;
294 struct kvm_resize_hpt *resize_hpt; /* protected by kvm->lock */ 298 struct kvm_resize_hpt *resize_hpt; /* protected by kvm->lock */
295#endif /* CONFIG_KVM_BOOK3S_HV_POSSIBLE */ 299#endif /* CONFIG_KVM_BOOK3S_HV_POSSIBLE */
296#ifdef CONFIG_KVM_BOOK3S_PR_POSSIBLE 300#ifdef CONFIG_KVM_BOOK3S_PR_POSSIBLE
@@ -311,6 +315,9 @@ struct kvm_arch {
311#endif 315#endif
312 struct kvmppc_ops *kvm_ops; 316 struct kvmppc_ops *kvm_ops;
313#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE 317#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
318 u64 l1_ptcr;
319 int max_nested_lpid;
320 struct kvm_nested_guest *nested_guests[KVM_MAX_NESTED_GUESTS];
314 /* This array can grow quite large, keep it at the end */ 321 /* This array can grow quite large, keep it at the end */
315 struct kvmppc_vcore *vcores[KVM_MAX_VCORES]; 322 struct kvmppc_vcore *vcores[KVM_MAX_VCORES];
316#endif 323#endif
@@ -360,7 +367,9 @@ struct kvmppc_pte {
360 bool may_write : 1; 367 bool may_write : 1;
361 bool may_execute : 1; 368 bool may_execute : 1;
362 unsigned long wimg; 369 unsigned long wimg;
370 unsigned long rc;
363 u8 page_size; /* MMU_PAGE_xxx */ 371 u8 page_size; /* MMU_PAGE_xxx */
372 u8 page_shift;
364}; 373};
365 374
366struct kvmppc_mmu { 375struct kvmppc_mmu {
@@ -537,8 +546,6 @@ struct kvm_vcpu_arch {
537 ulong tar; 546 ulong tar;
538#endif 547#endif
539 548
540 u32 cr;
541
542#ifdef CONFIG_PPC_BOOK3S 549#ifdef CONFIG_PPC_BOOK3S
543 ulong hflags; 550 ulong hflags;
544 ulong guest_owned_ext; 551 ulong guest_owned_ext;
@@ -707,6 +714,7 @@ struct kvm_vcpu_arch {
707 u8 hcall_needed; 714 u8 hcall_needed;
708 u8 epr_flags; /* KVMPPC_EPR_xxx */ 715 u8 epr_flags; /* KVMPPC_EPR_xxx */
709 u8 epr_needed; 716 u8 epr_needed;
717 u8 external_oneshot; /* clear external irq after delivery */
710 718
711 u32 cpr0_cfgaddr; /* holds the last set cpr0_cfgaddr */ 719 u32 cpr0_cfgaddr; /* holds the last set cpr0_cfgaddr */
712 720
@@ -781,6 +789,10 @@ struct kvm_vcpu_arch {
781 u32 emul_inst; 789 u32 emul_inst;
782 790
783 u32 online; 791 u32 online;
792
793 /* For support of nested guests */
794 struct kvm_nested_guest *nested;
795 u32 nested_vcpu_id;
784#endif 796#endif
785 797
786#ifdef CONFIG_KVM_BOOK3S_HV_EXIT_TIMING 798#ifdef CONFIG_KVM_BOOK3S_HV_EXIT_TIMING
diff --git a/arch/powerpc/include/asm/kvm_ppc.h b/arch/powerpc/include/asm/kvm_ppc.h
index e991821dd7fa..9b89b1918dfc 100644
--- a/arch/powerpc/include/asm/kvm_ppc.h
+++ b/arch/powerpc/include/asm/kvm_ppc.h
@@ -194,9 +194,7 @@ extern struct kvmppc_spapr_tce_table *kvmppc_find_table(
194 (iommu_tce_check_ioba((stt)->page_shift, (stt)->offset, \ 194 (iommu_tce_check_ioba((stt)->page_shift, (stt)->offset, \
195 (stt)->size, (ioba), (npages)) ? \ 195 (stt)->size, (ioba), (npages)) ? \
196 H_PARAMETER : H_SUCCESS) 196 H_PARAMETER : H_SUCCESS)
197extern long kvmppc_tce_validate(struct kvmppc_spapr_tce_table *tt, 197extern long kvmppc_tce_to_ua(struct kvm *kvm, unsigned long tce,
198 unsigned long tce);
199extern long kvmppc_gpa_to_ua(struct kvm *kvm, unsigned long gpa,
200 unsigned long *ua, unsigned long **prmap); 198 unsigned long *ua, unsigned long **prmap);
201extern void kvmppc_tce_put(struct kvmppc_spapr_tce_table *tt, 199extern void kvmppc_tce_put(struct kvmppc_spapr_tce_table *tt,
202 unsigned long idx, unsigned long tce); 200 unsigned long idx, unsigned long tce);
@@ -327,6 +325,7 @@ struct kvmppc_ops {
327 int (*set_smt_mode)(struct kvm *kvm, unsigned long mode, 325 int (*set_smt_mode)(struct kvm *kvm, unsigned long mode,
328 unsigned long flags); 326 unsigned long flags);
329 void (*giveup_ext)(struct kvm_vcpu *vcpu, ulong msr); 327 void (*giveup_ext)(struct kvm_vcpu *vcpu, ulong msr);
328 int (*enable_nested)(struct kvm *kvm);
330}; 329};
331 330
332extern struct kvmppc_ops *kvmppc_hv_ops; 331extern struct kvmppc_ops *kvmppc_hv_ops;
@@ -585,6 +584,7 @@ extern int kvmppc_xive_set_icp(struct kvm_vcpu *vcpu, u64 icpval);
585 584
586extern int kvmppc_xive_set_irq(struct kvm *kvm, int irq_source_id, u32 irq, 585extern int kvmppc_xive_set_irq(struct kvm *kvm, int irq_source_id, u32 irq,
587 int level, bool line_status); 586 int level, bool line_status);
587extern void kvmppc_xive_push_vcpu(struct kvm_vcpu *vcpu);
588#else 588#else
589static inline int kvmppc_xive_set_xive(struct kvm *kvm, u32 irq, u32 server, 589static inline int kvmppc_xive_set_xive(struct kvm *kvm, u32 irq, u32 server,
590 u32 priority) { return -1; } 590 u32 priority) { return -1; }
@@ -607,6 +607,7 @@ static inline int kvmppc_xive_set_icp(struct kvm_vcpu *vcpu, u64 icpval) { retur
607 607
608static inline int kvmppc_xive_set_irq(struct kvm *kvm, int irq_source_id, u32 irq, 608static inline int kvmppc_xive_set_irq(struct kvm *kvm, int irq_source_id, u32 irq,
609 int level, bool line_status) { return -ENODEV; } 609 int level, bool line_status) { return -ENODEV; }
610static inline void kvmppc_xive_push_vcpu(struct kvm_vcpu *vcpu) { }
610#endif /* CONFIG_KVM_XIVE */ 611#endif /* CONFIG_KVM_XIVE */
611 612
612/* 613/*
@@ -652,6 +653,7 @@ int kvmppc_rm_h_ipi(struct kvm_vcpu *vcpu, unsigned long server,
652 unsigned long mfrr); 653 unsigned long mfrr);
653int kvmppc_rm_h_cppr(struct kvm_vcpu *vcpu, unsigned long cppr); 654int kvmppc_rm_h_cppr(struct kvm_vcpu *vcpu, unsigned long cppr);
654int kvmppc_rm_h_eoi(struct kvm_vcpu *vcpu, unsigned long xirr); 655int kvmppc_rm_h_eoi(struct kvm_vcpu *vcpu, unsigned long xirr);
656void kvmppc_guest_entry_inject_int(struct kvm_vcpu *vcpu);
655 657
656/* 658/*
657 * Host-side operations we want to set up while running in real 659 * Host-side operations we want to set up while running in real
diff --git a/arch/powerpc/include/asm/ppc-opcode.h b/arch/powerpc/include/asm/ppc-opcode.h
index 665af14850e4..6093bc8f74e5 100644
--- a/arch/powerpc/include/asm/ppc-opcode.h
+++ b/arch/powerpc/include/asm/ppc-opcode.h
@@ -104,6 +104,7 @@
104#define OP_31_XOP_LHZUX 311 104#define OP_31_XOP_LHZUX 311
105#define OP_31_XOP_MSGSNDP 142 105#define OP_31_XOP_MSGSNDP 142
106#define OP_31_XOP_MSGCLRP 174 106#define OP_31_XOP_MSGCLRP 174
107#define OP_31_XOP_TLBIE 306
107#define OP_31_XOP_MFSPR 339 108#define OP_31_XOP_MFSPR 339
108#define OP_31_XOP_LWAX 341 109#define OP_31_XOP_LWAX 341
109#define OP_31_XOP_LHAX 343 110#define OP_31_XOP_LHAX 343
diff --git a/arch/powerpc/include/asm/reg.h b/arch/powerpc/include/asm/reg.h
index e5b314ed054e..c90698972f42 100644
--- a/arch/powerpc/include/asm/reg.h
+++ b/arch/powerpc/include/asm/reg.h
@@ -415,6 +415,7 @@
415#define HFSCR_DSCR __MASK(FSCR_DSCR_LG) 415#define HFSCR_DSCR __MASK(FSCR_DSCR_LG)
416#define HFSCR_VECVSX __MASK(FSCR_VECVSX_LG) 416#define HFSCR_VECVSX __MASK(FSCR_VECVSX_LG)
417#define HFSCR_FP __MASK(FSCR_FP_LG) 417#define HFSCR_FP __MASK(FSCR_FP_LG)
418#define HFSCR_INTR_CAUSE (ASM_CONST(0xFF) << 56) /* interrupt cause */
418#define SPRN_TAR 0x32f /* Target Address Register */ 419#define SPRN_TAR 0x32f /* Target Address Register */
419#define SPRN_LPCR 0x13E /* LPAR Control Register */ 420#define SPRN_LPCR 0x13E /* LPAR Control Register */
420#define LPCR_VPM0 ASM_CONST(0x8000000000000000) 421#define LPCR_VPM0 ASM_CONST(0x8000000000000000)
@@ -766,6 +767,7 @@
766#define SPRN_HSRR0 0x13A /* Save/Restore Register 0 */ 767#define SPRN_HSRR0 0x13A /* Save/Restore Register 0 */
767#define SPRN_HSRR1 0x13B /* Save/Restore Register 1 */ 768#define SPRN_HSRR1 0x13B /* Save/Restore Register 1 */
768#define HSRR1_DENORM 0x00100000 /* Denorm exception */ 769#define HSRR1_DENORM 0x00100000 /* Denorm exception */
770#define HSRR1_HISI_WRITE 0x00010000 /* HISI bcs couldn't update mem */
769 771
770#define SPRN_TBCTL 0x35f /* PA6T Timebase control register */ 772#define SPRN_TBCTL 0x35f /* PA6T Timebase control register */
771#define TBCTL_FREEZE 0x0000000000000000ull /* Freeze all tbs */ 773#define TBCTL_FREEZE 0x0000000000000000ull /* Freeze all tbs */
diff --git a/arch/powerpc/include/uapi/asm/kvm.h b/arch/powerpc/include/uapi/asm/kvm.h
index 1b32b56a03d3..8c876c166ef2 100644
--- a/arch/powerpc/include/uapi/asm/kvm.h
+++ b/arch/powerpc/include/uapi/asm/kvm.h
@@ -634,6 +634,7 @@ struct kvm_ppc_cpu_char {
634 634
635#define KVM_REG_PPC_DEC_EXPIRY (KVM_REG_PPC | KVM_REG_SIZE_U64 | 0xbe) 635#define KVM_REG_PPC_DEC_EXPIRY (KVM_REG_PPC | KVM_REG_SIZE_U64 | 0xbe)
636#define KVM_REG_PPC_ONLINE (KVM_REG_PPC | KVM_REG_SIZE_U32 | 0xbf) 636#define KVM_REG_PPC_ONLINE (KVM_REG_PPC | KVM_REG_SIZE_U32 | 0xbf)
637#define KVM_REG_PPC_PTCR (KVM_REG_PPC | KVM_REG_SIZE_U64 | 0xc0)
637 638
638/* Transactional Memory checkpointed state: 639/* Transactional Memory checkpointed state:
639 * This is all GPRs, all VSX regs and a subset of SPRs 640 * This is all GPRs, all VSX regs and a subset of SPRs
diff --git a/arch/powerpc/kernel/asm-offsets.c b/arch/powerpc/kernel/asm-offsets.c
index 041a115789a1..d68b9ef38328 100644
--- a/arch/powerpc/kernel/asm-offsets.c
+++ b/arch/powerpc/kernel/asm-offsets.c
@@ -438,7 +438,7 @@ int main(void)
438#ifdef CONFIG_PPC_BOOK3S 438#ifdef CONFIG_PPC_BOOK3S
439 OFFSET(VCPU_TAR, kvm_vcpu, arch.tar); 439 OFFSET(VCPU_TAR, kvm_vcpu, arch.tar);
440#endif 440#endif
441 OFFSET(VCPU_CR, kvm_vcpu, arch.cr); 441 OFFSET(VCPU_CR, kvm_vcpu, arch.regs.ccr);
442 OFFSET(VCPU_PC, kvm_vcpu, arch.regs.nip); 442 OFFSET(VCPU_PC, kvm_vcpu, arch.regs.nip);
443#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE 443#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
444 OFFSET(VCPU_MSR, kvm_vcpu, arch.shregs.msr); 444 OFFSET(VCPU_MSR, kvm_vcpu, arch.shregs.msr);
@@ -503,6 +503,7 @@ int main(void)
503 OFFSET(VCPU_VPA, kvm_vcpu, arch.vpa.pinned_addr); 503 OFFSET(VCPU_VPA, kvm_vcpu, arch.vpa.pinned_addr);
504 OFFSET(VCPU_VPA_DIRTY, kvm_vcpu, arch.vpa.dirty); 504 OFFSET(VCPU_VPA_DIRTY, kvm_vcpu, arch.vpa.dirty);
505 OFFSET(VCPU_HEIR, kvm_vcpu, arch.emul_inst); 505 OFFSET(VCPU_HEIR, kvm_vcpu, arch.emul_inst);
506 OFFSET(VCPU_NESTED, kvm_vcpu, arch.nested);
506 OFFSET(VCPU_CPU, kvm_vcpu, cpu); 507 OFFSET(VCPU_CPU, kvm_vcpu, cpu);
507 OFFSET(VCPU_THREAD_CPU, kvm_vcpu, arch.thread_cpu); 508 OFFSET(VCPU_THREAD_CPU, kvm_vcpu, arch.thread_cpu);
508#endif 509#endif
@@ -695,7 +696,7 @@ int main(void)
695#endif /* CONFIG_PPC_BOOK3S_64 */ 696#endif /* CONFIG_PPC_BOOK3S_64 */
696 697
697#else /* CONFIG_PPC_BOOK3S */ 698#else /* CONFIG_PPC_BOOK3S */
698 OFFSET(VCPU_CR, kvm_vcpu, arch.cr); 699 OFFSET(VCPU_CR, kvm_vcpu, arch.regs.ccr);
699 OFFSET(VCPU_XER, kvm_vcpu, arch.regs.xer); 700 OFFSET(VCPU_XER, kvm_vcpu, arch.regs.xer);
700 OFFSET(VCPU_LR, kvm_vcpu, arch.regs.link); 701 OFFSET(VCPU_LR, kvm_vcpu, arch.regs.link);
701 OFFSET(VCPU_CTR, kvm_vcpu, arch.regs.ctr); 702 OFFSET(VCPU_CTR, kvm_vcpu, arch.regs.ctr);
diff --git a/arch/powerpc/kernel/cpu_setup_power.S b/arch/powerpc/kernel/cpu_setup_power.S
index 458b928dbd84..c317080db771 100644
--- a/arch/powerpc/kernel/cpu_setup_power.S
+++ b/arch/powerpc/kernel/cpu_setup_power.S
@@ -147,8 +147,8 @@ __init_hvmode_206:
147 rldicl. r0,r3,4,63 147 rldicl. r0,r3,4,63
148 bnelr 148 bnelr
149 ld r5,CPU_SPEC_FEATURES(r4) 149 ld r5,CPU_SPEC_FEATURES(r4)
150 LOAD_REG_IMMEDIATE(r6,CPU_FTR_HVMODE) 150 LOAD_REG_IMMEDIATE(r6,CPU_FTR_HVMODE | CPU_FTR_P9_TM_HV_ASSIST)
151 xor r5,r5,r6 151 andc r5,r5,r6
152 std r5,CPU_SPEC_FEATURES(r4) 152 std r5,CPU_SPEC_FEATURES(r4)
153 blr 153 blr
154 154
diff --git a/arch/powerpc/kvm/Makefile b/arch/powerpc/kvm/Makefile
index f872c04bb5b1..e814f40ab836 100644
--- a/arch/powerpc/kvm/Makefile
+++ b/arch/powerpc/kvm/Makefile
@@ -75,7 +75,8 @@ kvm-hv-y += \
75 book3s_hv.o \ 75 book3s_hv.o \
76 book3s_hv_interrupts.o \ 76 book3s_hv_interrupts.o \
77 book3s_64_mmu_hv.o \ 77 book3s_64_mmu_hv.o \
78 book3s_64_mmu_radix.o 78 book3s_64_mmu_radix.o \
79 book3s_hv_nested.o
79 80
80kvm-hv-$(CONFIG_PPC_TRANSACTIONAL_MEM) += \ 81kvm-hv-$(CONFIG_PPC_TRANSACTIONAL_MEM) += \
81 book3s_hv_tm.o 82 book3s_hv_tm.o
diff --git a/arch/powerpc/kvm/book3s.c b/arch/powerpc/kvm/book3s.c
index 87348e498c89..fd9893bc7aa1 100644
--- a/arch/powerpc/kvm/book3s.c
+++ b/arch/powerpc/kvm/book3s.c
@@ -78,8 +78,11 @@ void kvmppc_unfixup_split_real(struct kvm_vcpu *vcpu)
78{ 78{
79 if (vcpu->arch.hflags & BOOK3S_HFLAG_SPLIT_HACK) { 79 if (vcpu->arch.hflags & BOOK3S_HFLAG_SPLIT_HACK) {
80 ulong pc = kvmppc_get_pc(vcpu); 80 ulong pc = kvmppc_get_pc(vcpu);
81 ulong lr = kvmppc_get_lr(vcpu);
81 if ((pc & SPLIT_HACK_MASK) == SPLIT_HACK_OFFS) 82 if ((pc & SPLIT_HACK_MASK) == SPLIT_HACK_OFFS)
82 kvmppc_set_pc(vcpu, pc & ~SPLIT_HACK_MASK); 83 kvmppc_set_pc(vcpu, pc & ~SPLIT_HACK_MASK);
84 if ((lr & SPLIT_HACK_MASK) == SPLIT_HACK_OFFS)
85 kvmppc_set_lr(vcpu, lr & ~SPLIT_HACK_MASK);
83 vcpu->arch.hflags &= ~BOOK3S_HFLAG_SPLIT_HACK; 86 vcpu->arch.hflags &= ~BOOK3S_HFLAG_SPLIT_HACK;
84 } 87 }
85} 88}
@@ -150,7 +153,6 @@ static int kvmppc_book3s_vec2irqprio(unsigned int vec)
150 case 0x400: prio = BOOK3S_IRQPRIO_INST_STORAGE; break; 153 case 0x400: prio = BOOK3S_IRQPRIO_INST_STORAGE; break;
151 case 0x480: prio = BOOK3S_IRQPRIO_INST_SEGMENT; break; 154 case 0x480: prio = BOOK3S_IRQPRIO_INST_SEGMENT; break;
152 case 0x500: prio = BOOK3S_IRQPRIO_EXTERNAL; break; 155 case 0x500: prio = BOOK3S_IRQPRIO_EXTERNAL; break;
153 case 0x501: prio = BOOK3S_IRQPRIO_EXTERNAL_LEVEL; break;
154 case 0x600: prio = BOOK3S_IRQPRIO_ALIGNMENT; break; 156 case 0x600: prio = BOOK3S_IRQPRIO_ALIGNMENT; break;
155 case 0x700: prio = BOOK3S_IRQPRIO_PROGRAM; break; 157 case 0x700: prio = BOOK3S_IRQPRIO_PROGRAM; break;
156 case 0x800: prio = BOOK3S_IRQPRIO_FP_UNAVAIL; break; 158 case 0x800: prio = BOOK3S_IRQPRIO_FP_UNAVAIL; break;
@@ -236,18 +238,35 @@ EXPORT_SYMBOL_GPL(kvmppc_core_dequeue_dec);
236void kvmppc_core_queue_external(struct kvm_vcpu *vcpu, 238void kvmppc_core_queue_external(struct kvm_vcpu *vcpu,
237 struct kvm_interrupt *irq) 239 struct kvm_interrupt *irq)
238{ 240{
239 unsigned int vec = BOOK3S_INTERRUPT_EXTERNAL; 241 /*
240 242 * This case (KVM_INTERRUPT_SET) should never actually arise for
241 if (irq->irq == KVM_INTERRUPT_SET_LEVEL) 243 * a pseries guest (because pseries guests expect their interrupt
242 vec = BOOK3S_INTERRUPT_EXTERNAL_LEVEL; 244 * controllers to continue asserting an external interrupt request
245 * until it is acknowledged at the interrupt controller), but is
246 * included to avoid ABI breakage and potentially for other
247 * sorts of guest.
248 *
249 * There is a subtlety here: HV KVM does not test the
250 * external_oneshot flag in the code that synthesizes
251 * external interrupts for the guest just before entering
252 * the guest. That is OK even if userspace did do a
253 * KVM_INTERRUPT_SET on a pseries guest vcpu, because the
254 * caller (kvm_vcpu_ioctl_interrupt) does a kvm_vcpu_kick()
255 * which ends up doing a smp_send_reschedule(), which will
256 * pull the guest all the way out to the host, meaning that
257 * we will call kvmppc_core_prepare_to_enter() before entering
258 * the guest again, and that will handle the external_oneshot
259 * flag correctly.
260 */
261 if (irq->irq == KVM_INTERRUPT_SET)
262 vcpu->arch.external_oneshot = 1;
243 263
244 kvmppc_book3s_queue_irqprio(vcpu, vec); 264 kvmppc_book3s_queue_irqprio(vcpu, BOOK3S_INTERRUPT_EXTERNAL);
245} 265}
246 266
247void kvmppc_core_dequeue_external(struct kvm_vcpu *vcpu) 267void kvmppc_core_dequeue_external(struct kvm_vcpu *vcpu)
248{ 268{
249 kvmppc_book3s_dequeue_irqprio(vcpu, BOOK3S_INTERRUPT_EXTERNAL); 269 kvmppc_book3s_dequeue_irqprio(vcpu, BOOK3S_INTERRUPT_EXTERNAL);
250 kvmppc_book3s_dequeue_irqprio(vcpu, BOOK3S_INTERRUPT_EXTERNAL_LEVEL);
251} 270}
252 271
253void kvmppc_core_queue_data_storage(struct kvm_vcpu *vcpu, ulong dar, 272void kvmppc_core_queue_data_storage(struct kvm_vcpu *vcpu, ulong dar,
@@ -278,7 +297,6 @@ static int kvmppc_book3s_irqprio_deliver(struct kvm_vcpu *vcpu,
278 vec = BOOK3S_INTERRUPT_DECREMENTER; 297 vec = BOOK3S_INTERRUPT_DECREMENTER;
279 break; 298 break;
280 case BOOK3S_IRQPRIO_EXTERNAL: 299 case BOOK3S_IRQPRIO_EXTERNAL:
281 case BOOK3S_IRQPRIO_EXTERNAL_LEVEL:
282 deliver = (kvmppc_get_msr(vcpu) & MSR_EE) && !crit; 300 deliver = (kvmppc_get_msr(vcpu) & MSR_EE) && !crit;
283 vec = BOOK3S_INTERRUPT_EXTERNAL; 301 vec = BOOK3S_INTERRUPT_EXTERNAL;
284 break; 302 break;
@@ -352,8 +370,16 @@ static bool clear_irqprio(struct kvm_vcpu *vcpu, unsigned int priority)
352 case BOOK3S_IRQPRIO_DECREMENTER: 370 case BOOK3S_IRQPRIO_DECREMENTER:
353 /* DEC interrupts get cleared by mtdec */ 371 /* DEC interrupts get cleared by mtdec */
354 return false; 372 return false;
355 case BOOK3S_IRQPRIO_EXTERNAL_LEVEL: 373 case BOOK3S_IRQPRIO_EXTERNAL:
356 /* External interrupts get cleared by userspace */ 374 /*
375 * External interrupts get cleared by userspace
376 * except when set by the KVM_INTERRUPT ioctl with
377 * KVM_INTERRUPT_SET (not KVM_INTERRUPT_SET_LEVEL).
378 */
379 if (vcpu->arch.external_oneshot) {
380 vcpu->arch.external_oneshot = 0;
381 return true;
382 }
357 return false; 383 return false;
358 } 384 }
359 385
diff --git a/arch/powerpc/kvm/book3s_64_mmu_hv.c b/arch/powerpc/kvm/book3s_64_mmu_hv.c
index 68e14afecac8..c615617e78ac 100644
--- a/arch/powerpc/kvm/book3s_64_mmu_hv.c
+++ b/arch/powerpc/kvm/book3s_64_mmu_hv.c
@@ -268,14 +268,13 @@ int kvmppc_mmu_hv_init(void)
268{ 268{
269 unsigned long host_lpid, rsvd_lpid; 269 unsigned long host_lpid, rsvd_lpid;
270 270
271 if (!cpu_has_feature(CPU_FTR_HVMODE))
272 return -EINVAL;
273
274 if (!mmu_has_feature(MMU_FTR_LOCKLESS_TLBIE)) 271 if (!mmu_has_feature(MMU_FTR_LOCKLESS_TLBIE))
275 return -EINVAL; 272 return -EINVAL;
276 273
277 /* POWER7 has 10-bit LPIDs (12-bit in POWER8) */ 274 /* POWER7 has 10-bit LPIDs (12-bit in POWER8) */
278 host_lpid = mfspr(SPRN_LPID); 275 host_lpid = 0;
276 if (cpu_has_feature(CPU_FTR_HVMODE))
277 host_lpid = mfspr(SPRN_LPID);
279 rsvd_lpid = LPID_RSVD; 278 rsvd_lpid = LPID_RSVD;
280 279
281 kvmppc_init_lpid(rsvd_lpid + 1); 280 kvmppc_init_lpid(rsvd_lpid + 1);
diff --git a/arch/powerpc/kvm/book3s_64_mmu_radix.c b/arch/powerpc/kvm/book3s_64_mmu_radix.c
index 998f8d089ac7..d68162ee159b 100644
--- a/arch/powerpc/kvm/book3s_64_mmu_radix.c
+++ b/arch/powerpc/kvm/book3s_64_mmu_radix.c
@@ -10,6 +10,9 @@
10#include <linux/string.h> 10#include <linux/string.h>
11#include <linux/kvm.h> 11#include <linux/kvm.h>
12#include <linux/kvm_host.h> 12#include <linux/kvm_host.h>
13#include <linux/anon_inodes.h>
14#include <linux/file.h>
15#include <linux/debugfs.h>
13 16
14#include <asm/kvm_ppc.h> 17#include <asm/kvm_ppc.h>
15#include <asm/kvm_book3s.h> 18#include <asm/kvm_book3s.h>
@@ -26,87 +29,74 @@
26 */ 29 */
27static int p9_supported_radix_bits[4] = { 5, 9, 9, 13 }; 30static int p9_supported_radix_bits[4] = { 5, 9, 9, 13 };
28 31
29int kvmppc_mmu_radix_xlate(struct kvm_vcpu *vcpu, gva_t eaddr, 32int kvmppc_mmu_walk_radix_tree(struct kvm_vcpu *vcpu, gva_t eaddr,
30 struct kvmppc_pte *gpte, bool data, bool iswrite) 33 struct kvmppc_pte *gpte, u64 root,
34 u64 *pte_ret_p)
31{ 35{
32 struct kvm *kvm = vcpu->kvm; 36 struct kvm *kvm = vcpu->kvm;
33 u32 pid;
34 int ret, level, ps; 37 int ret, level, ps;
35 __be64 prte, rpte; 38 unsigned long rts, bits, offset, index;
36 unsigned long ptbl; 39 u64 pte, base, gpa;
37 unsigned long root, pte, index; 40 __be64 rpte;
38 unsigned long rts, bits, offset;
39 unsigned long gpa;
40 unsigned long proc_tbl_size;
41
42 /* Work out effective PID */
43 switch (eaddr >> 62) {
44 case 0:
45 pid = vcpu->arch.pid;
46 break;
47 case 3:
48 pid = 0;
49 break;
50 default:
51 return -EINVAL;
52 }
53 proc_tbl_size = 1 << ((kvm->arch.process_table & PRTS_MASK) + 12);
54 if (pid * 16 >= proc_tbl_size)
55 return -EINVAL;
56
57 /* Read partition table to find root of tree for effective PID */
58 ptbl = (kvm->arch.process_table & PRTB_MASK) + (pid * 16);
59 ret = kvm_read_guest(kvm, ptbl, &prte, sizeof(prte));
60 if (ret)
61 return ret;
62 41
63 root = be64_to_cpu(prte);
64 rts = ((root & RTS1_MASK) >> (RTS1_SHIFT - 3)) | 42 rts = ((root & RTS1_MASK) >> (RTS1_SHIFT - 3)) |
65 ((root & RTS2_MASK) >> RTS2_SHIFT); 43 ((root & RTS2_MASK) >> RTS2_SHIFT);
66 bits = root & RPDS_MASK; 44 bits = root & RPDS_MASK;
67 root = root & RPDB_MASK; 45 base = root & RPDB_MASK;
68 46
69 offset = rts + 31; 47 offset = rts + 31;
70 48
71 /* current implementations only support 52-bit space */ 49 /* Current implementations only support 52-bit space */
72 if (offset != 52) 50 if (offset != 52)
73 return -EINVAL; 51 return -EINVAL;
74 52
53 /* Walk each level of the radix tree */
75 for (level = 3; level >= 0; --level) { 54 for (level = 3; level >= 0; --level) {
55 u64 addr;
56 /* Check a valid size */
76 if (level && bits != p9_supported_radix_bits[level]) 57 if (level && bits != p9_supported_radix_bits[level])
77 return -EINVAL; 58 return -EINVAL;
78 if (level == 0 && !(bits == 5 || bits == 9)) 59 if (level == 0 && !(bits == 5 || bits == 9))
79 return -EINVAL; 60 return -EINVAL;
80 offset -= bits; 61 offset -= bits;
81 index = (eaddr >> offset) & ((1UL << bits) - 1); 62 index = (eaddr >> offset) & ((1UL << bits) - 1);
82 /* check that low bits of page table base are zero */ 63 /* Check that low bits of page table base are zero */
83 if (root & ((1UL << (bits + 3)) - 1)) 64 if (base & ((1UL << (bits + 3)) - 1))
84 return -EINVAL; 65 return -EINVAL;
85 ret = kvm_read_guest(kvm, root + index * 8, 66 /* Read the entry from guest memory */
86 &rpte, sizeof(rpte)); 67 addr = base + (index * sizeof(rpte));
87 if (ret) 68 ret = kvm_read_guest(kvm, addr, &rpte, sizeof(rpte));
69 if (ret) {
70 if (pte_ret_p)
71 *pte_ret_p = addr;
88 return ret; 72 return ret;
73 }
89 pte = __be64_to_cpu(rpte); 74 pte = __be64_to_cpu(rpte);
90 if (!(pte & _PAGE_PRESENT)) 75 if (!(pte & _PAGE_PRESENT))
91 return -ENOENT; 76 return -ENOENT;
77 /* Check if a leaf entry */
92 if (pte & _PAGE_PTE) 78 if (pte & _PAGE_PTE)
93 break; 79 break;
94 bits = pte & 0x1f; 80 /* Get ready to walk the next level */
95 root = pte & 0x0fffffffffffff00ul; 81 base = pte & RPDB_MASK;
82 bits = pte & RPDS_MASK;
96 } 83 }
97 /* need a leaf at lowest level; 512GB pages not supported */ 84
85 /* Need a leaf at lowest level; 512GB pages not supported */
98 if (level < 0 || level == 3) 86 if (level < 0 || level == 3)
99 return -EINVAL; 87 return -EINVAL;
100 88
101 /* offset is now log base 2 of the page size */ 89 /* We found a valid leaf PTE */
90 /* Offset is now log base 2 of the page size */
102 gpa = pte & 0x01fffffffffff000ul; 91 gpa = pte & 0x01fffffffffff000ul;
103 if (gpa & ((1ul << offset) - 1)) 92 if (gpa & ((1ul << offset) - 1))
104 return -EINVAL; 93 return -EINVAL;
105 gpa += eaddr & ((1ul << offset) - 1); 94 gpa |= eaddr & ((1ul << offset) - 1);
106 for (ps = MMU_PAGE_4K; ps < MMU_PAGE_COUNT; ++ps) 95 for (ps = MMU_PAGE_4K; ps < MMU_PAGE_COUNT; ++ps)
107 if (offset == mmu_psize_defs[ps].shift) 96 if (offset == mmu_psize_defs[ps].shift)
108 break; 97 break;
109 gpte->page_size = ps; 98 gpte->page_size = ps;
99 gpte->page_shift = offset;
110 100
111 gpte->eaddr = eaddr; 101 gpte->eaddr = eaddr;
112 gpte->raddr = gpa; 102 gpte->raddr = gpa;
@@ -115,6 +105,77 @@ int kvmppc_mmu_radix_xlate(struct kvm_vcpu *vcpu, gva_t eaddr,
115 gpte->may_read = !!(pte & _PAGE_READ); 105 gpte->may_read = !!(pte & _PAGE_READ);
116 gpte->may_write = !!(pte & _PAGE_WRITE); 106 gpte->may_write = !!(pte & _PAGE_WRITE);
117 gpte->may_execute = !!(pte & _PAGE_EXEC); 107 gpte->may_execute = !!(pte & _PAGE_EXEC);
108
109 gpte->rc = pte & (_PAGE_ACCESSED | _PAGE_DIRTY);
110
111 if (pte_ret_p)
112 *pte_ret_p = pte;
113
114 return 0;
115}
116
117/*
118 * Used to walk a partition or process table radix tree in guest memory
119 * Note: We exploit the fact that a partition table and a process
120 * table have the same layout, a partition-scoped page table and a
121 * process-scoped page table have the same layout, and the 2nd
122 * doubleword of a partition table entry has the same layout as
123 * the PTCR register.
124 */
125int kvmppc_mmu_radix_translate_table(struct kvm_vcpu *vcpu, gva_t eaddr,
126 struct kvmppc_pte *gpte, u64 table,
127 int table_index, u64 *pte_ret_p)
128{
129 struct kvm *kvm = vcpu->kvm;
130 int ret;
131 unsigned long size, ptbl, root;
132 struct prtb_entry entry;
133
134 if ((table & PRTS_MASK) > 24)
135 return -EINVAL;
136 size = 1ul << ((table & PRTS_MASK) + 12);
137
138 /* Is the table big enough to contain this entry? */
139 if ((table_index * sizeof(entry)) >= size)
140 return -EINVAL;
141
142 /* Read the table to find the root of the radix tree */
143 ptbl = (table & PRTB_MASK) + (table_index * sizeof(entry));
144 ret = kvm_read_guest(kvm, ptbl, &entry, sizeof(entry));
145 if (ret)
146 return ret;
147
148 /* Root is stored in the first double word */
149 root = be64_to_cpu(entry.prtb0);
150
151 return kvmppc_mmu_walk_radix_tree(vcpu, eaddr, gpte, root, pte_ret_p);
152}
153
154int kvmppc_mmu_radix_xlate(struct kvm_vcpu *vcpu, gva_t eaddr,
155 struct kvmppc_pte *gpte, bool data, bool iswrite)
156{
157 u32 pid;
158 u64 pte;
159 int ret;
160
161 /* Work out effective PID */
162 switch (eaddr >> 62) {
163 case 0:
164 pid = vcpu->arch.pid;
165 break;
166 case 3:
167 pid = 0;
168 break;
169 default:
170 return -EINVAL;
171 }
172
173 ret = kvmppc_mmu_radix_translate_table(vcpu, eaddr, gpte,
174 vcpu->kvm->arch.process_table, pid, &pte);
175 if (ret)
176 return ret;
177
178 /* Check privilege (applies only to process scoped translations) */
118 if (kvmppc_get_msr(vcpu) & MSR_PR) { 179 if (kvmppc_get_msr(vcpu) & MSR_PR) {
119 if (pte & _PAGE_PRIVILEGED) { 180 if (pte & _PAGE_PRIVILEGED) {
120 gpte->may_read = 0; 181 gpte->may_read = 0;
@@ -137,20 +198,46 @@ int kvmppc_mmu_radix_xlate(struct kvm_vcpu *vcpu, gva_t eaddr,
137} 198}
138 199
139static void kvmppc_radix_tlbie_page(struct kvm *kvm, unsigned long addr, 200static void kvmppc_radix_tlbie_page(struct kvm *kvm, unsigned long addr,
140 unsigned int pshift) 201 unsigned int pshift, unsigned int lpid)
141{ 202{
142 unsigned long psize = PAGE_SIZE; 203 unsigned long psize = PAGE_SIZE;
204 int psi;
205 long rc;
206 unsigned long rb;
143 207
144 if (pshift) 208 if (pshift)
145 psize = 1UL << pshift; 209 psize = 1UL << pshift;
210 else
211 pshift = PAGE_SHIFT;
146 212
147 addr &= ~(psize - 1); 213 addr &= ~(psize - 1);
148 radix__flush_tlb_lpid_page(kvm->arch.lpid, addr, psize); 214
215 if (!kvmhv_on_pseries()) {
216 radix__flush_tlb_lpid_page(lpid, addr, psize);
217 return;
218 }
219
220 psi = shift_to_mmu_psize(pshift);
221 rb = addr | (mmu_get_ap(psi) << PPC_BITLSHIFT(58));
222 rc = plpar_hcall_norets(H_TLB_INVALIDATE, H_TLBIE_P1_ENC(0, 0, 1),
223 lpid, rb);
224 if (rc)
225 pr_err("KVM: TLB page invalidation hcall failed, rc=%ld\n", rc);
149} 226}
150 227
151static void kvmppc_radix_flush_pwc(struct kvm *kvm) 228static void kvmppc_radix_flush_pwc(struct kvm *kvm, unsigned int lpid)
152{ 229{
153 radix__flush_pwc_lpid(kvm->arch.lpid); 230 long rc;
231
232 if (!kvmhv_on_pseries()) {
233 radix__flush_pwc_lpid(lpid);
234 return;
235 }
236
237 rc = plpar_hcall_norets(H_TLB_INVALIDATE, H_TLBIE_P1_ENC(1, 0, 1),
238 lpid, TLBIEL_INVAL_SET_LPID);
239 if (rc)
240 pr_err("KVM: TLB PWC invalidation hcall failed, rc=%ld\n", rc);
154} 241}
155 242
156static unsigned long kvmppc_radix_update_pte(struct kvm *kvm, pte_t *ptep, 243static unsigned long kvmppc_radix_update_pte(struct kvm *kvm, pte_t *ptep,
@@ -195,23 +282,38 @@ static void kvmppc_pmd_free(pmd_t *pmdp)
195 kmem_cache_free(kvm_pmd_cache, pmdp); 282 kmem_cache_free(kvm_pmd_cache, pmdp);
196} 283}
197 284
198static void kvmppc_unmap_pte(struct kvm *kvm, pte_t *pte, 285/* Called with kvm->mmu_lock held */
199 unsigned long gpa, unsigned int shift) 286void kvmppc_unmap_pte(struct kvm *kvm, pte_t *pte, unsigned long gpa,
287 unsigned int shift, struct kvm_memory_slot *memslot,
288 unsigned int lpid)
200 289
201{ 290{
202 unsigned long page_size = 1ul << shift;
203 unsigned long old; 291 unsigned long old;
292 unsigned long gfn = gpa >> PAGE_SHIFT;
293 unsigned long page_size = PAGE_SIZE;
294 unsigned long hpa;
204 295
205 old = kvmppc_radix_update_pte(kvm, pte, ~0UL, 0, gpa, shift); 296 old = kvmppc_radix_update_pte(kvm, pte, ~0UL, 0, gpa, shift);
206 kvmppc_radix_tlbie_page(kvm, gpa, shift); 297 kvmppc_radix_tlbie_page(kvm, gpa, shift, lpid);
207 if (old & _PAGE_DIRTY) { 298
208 unsigned long gfn = gpa >> PAGE_SHIFT; 299 /* The following only applies to L1 entries */
209 struct kvm_memory_slot *memslot; 300 if (lpid != kvm->arch.lpid)
301 return;
210 302
303 if (!memslot) {
211 memslot = gfn_to_memslot(kvm, gfn); 304 memslot = gfn_to_memslot(kvm, gfn);
212 if (memslot && memslot->dirty_bitmap) 305 if (!memslot)
213 kvmppc_update_dirty_map(memslot, gfn, page_size); 306 return;
214 } 307 }
308 if (shift)
309 page_size = 1ul << shift;
310
311 gpa &= ~(page_size - 1);
312 hpa = old & PTE_RPN_MASK;
313 kvmhv_remove_nest_rmap_range(kvm, memslot, gpa, hpa, page_size);
314
315 if ((old & _PAGE_DIRTY) && memslot->dirty_bitmap)
316 kvmppc_update_dirty_map(memslot, gfn, page_size);
215} 317}
216 318
217/* 319/*
@@ -224,7 +326,8 @@ static void kvmppc_unmap_pte(struct kvm *kvm, pte_t *pte,
224 * and emit a warning if encountered, but there may already be data 326 * and emit a warning if encountered, but there may already be data
225 * corruption due to the unexpected mappings. 327 * corruption due to the unexpected mappings.
226 */ 328 */
227static void kvmppc_unmap_free_pte(struct kvm *kvm, pte_t *pte, bool full) 329static void kvmppc_unmap_free_pte(struct kvm *kvm, pte_t *pte, bool full,
330 unsigned int lpid)
228{ 331{
229 if (full) { 332 if (full) {
230 memset(pte, 0, sizeof(long) << PTE_INDEX_SIZE); 333 memset(pte, 0, sizeof(long) << PTE_INDEX_SIZE);
@@ -238,14 +341,15 @@ static void kvmppc_unmap_free_pte(struct kvm *kvm, pte_t *pte, bool full)
238 WARN_ON_ONCE(1); 341 WARN_ON_ONCE(1);
239 kvmppc_unmap_pte(kvm, p, 342 kvmppc_unmap_pte(kvm, p,
240 pte_pfn(*p) << PAGE_SHIFT, 343 pte_pfn(*p) << PAGE_SHIFT,
241 PAGE_SHIFT); 344 PAGE_SHIFT, NULL, lpid);
242 } 345 }
243 } 346 }
244 347
245 kvmppc_pte_free(pte); 348 kvmppc_pte_free(pte);
246} 349}
247 350
248static void kvmppc_unmap_free_pmd(struct kvm *kvm, pmd_t *pmd, bool full) 351static void kvmppc_unmap_free_pmd(struct kvm *kvm, pmd_t *pmd, bool full,
352 unsigned int lpid)
249{ 353{
250 unsigned long im; 354 unsigned long im;
251 pmd_t *p = pmd; 355 pmd_t *p = pmd;
@@ -260,20 +364,21 @@ static void kvmppc_unmap_free_pmd(struct kvm *kvm, pmd_t *pmd, bool full)
260 WARN_ON_ONCE(1); 364 WARN_ON_ONCE(1);
261 kvmppc_unmap_pte(kvm, (pte_t *)p, 365 kvmppc_unmap_pte(kvm, (pte_t *)p,
262 pte_pfn(*(pte_t *)p) << PAGE_SHIFT, 366 pte_pfn(*(pte_t *)p) << PAGE_SHIFT,
263 PMD_SHIFT); 367 PMD_SHIFT, NULL, lpid);
264 } 368 }
265 } else { 369 } else {
266 pte_t *pte; 370 pte_t *pte;
267 371
268 pte = pte_offset_map(p, 0); 372 pte = pte_offset_map(p, 0);
269 kvmppc_unmap_free_pte(kvm, pte, full); 373 kvmppc_unmap_free_pte(kvm, pte, full, lpid);
270 pmd_clear(p); 374 pmd_clear(p);
271 } 375 }
272 } 376 }
273 kvmppc_pmd_free(pmd); 377 kvmppc_pmd_free(pmd);
274} 378}
275 379
276static void kvmppc_unmap_free_pud(struct kvm *kvm, pud_t *pud) 380static void kvmppc_unmap_free_pud(struct kvm *kvm, pud_t *pud,
381 unsigned int lpid)
277{ 382{
278 unsigned long iu; 383 unsigned long iu;
279 pud_t *p = pud; 384 pud_t *p = pud;
@@ -287,36 +392,40 @@ static void kvmppc_unmap_free_pud(struct kvm *kvm, pud_t *pud)
287 pmd_t *pmd; 392 pmd_t *pmd;
288 393
289 pmd = pmd_offset(p, 0); 394 pmd = pmd_offset(p, 0);
290 kvmppc_unmap_free_pmd(kvm, pmd, true); 395 kvmppc_unmap_free_pmd(kvm, pmd, true, lpid);
291 pud_clear(p); 396 pud_clear(p);
292 } 397 }
293 } 398 }
294 pud_free(kvm->mm, pud); 399 pud_free(kvm->mm, pud);
295} 400}
296 401
297void kvmppc_free_radix(struct kvm *kvm) 402void kvmppc_free_pgtable_radix(struct kvm *kvm, pgd_t *pgd, unsigned int lpid)
298{ 403{
299 unsigned long ig; 404 unsigned long ig;
300 pgd_t *pgd;
301 405
302 if (!kvm->arch.pgtable)
303 return;
304 pgd = kvm->arch.pgtable;
305 for (ig = 0; ig < PTRS_PER_PGD; ++ig, ++pgd) { 406 for (ig = 0; ig < PTRS_PER_PGD; ++ig, ++pgd) {
306 pud_t *pud; 407 pud_t *pud;
307 408
308 if (!pgd_present(*pgd)) 409 if (!pgd_present(*pgd))
309 continue; 410 continue;
310 pud = pud_offset(pgd, 0); 411 pud = pud_offset(pgd, 0);
311 kvmppc_unmap_free_pud(kvm, pud); 412 kvmppc_unmap_free_pud(kvm, pud, lpid);
312 pgd_clear(pgd); 413 pgd_clear(pgd);
313 } 414 }
314 pgd_free(kvm->mm, kvm->arch.pgtable); 415}
315 kvm->arch.pgtable = NULL; 416
417void kvmppc_free_radix(struct kvm *kvm)
418{
419 if (kvm->arch.pgtable) {
420 kvmppc_free_pgtable_radix(kvm, kvm->arch.pgtable,
421 kvm->arch.lpid);
422 pgd_free(kvm->mm, kvm->arch.pgtable);
423 kvm->arch.pgtable = NULL;
424 }
316} 425}
317 426
318static void kvmppc_unmap_free_pmd_entry_table(struct kvm *kvm, pmd_t *pmd, 427static void kvmppc_unmap_free_pmd_entry_table(struct kvm *kvm, pmd_t *pmd,
319 unsigned long gpa) 428 unsigned long gpa, unsigned int lpid)
320{ 429{
321 pte_t *pte = pte_offset_kernel(pmd, 0); 430 pte_t *pte = pte_offset_kernel(pmd, 0);
322 431
@@ -326,13 +435,13 @@ static void kvmppc_unmap_free_pmd_entry_table(struct kvm *kvm, pmd_t *pmd,
326 * flushing the PWC again. 435 * flushing the PWC again.
327 */ 436 */
328 pmd_clear(pmd); 437 pmd_clear(pmd);
329 kvmppc_radix_flush_pwc(kvm); 438 kvmppc_radix_flush_pwc(kvm, lpid);
330 439
331 kvmppc_unmap_free_pte(kvm, pte, false); 440 kvmppc_unmap_free_pte(kvm, pte, false, lpid);
332} 441}
333 442
334static void kvmppc_unmap_free_pud_entry_table(struct kvm *kvm, pud_t *pud, 443static void kvmppc_unmap_free_pud_entry_table(struct kvm *kvm, pud_t *pud,
335 unsigned long gpa) 444 unsigned long gpa, unsigned int lpid)
336{ 445{
337 pmd_t *pmd = pmd_offset(pud, 0); 446 pmd_t *pmd = pmd_offset(pud, 0);
338 447
@@ -342,9 +451,9 @@ static void kvmppc_unmap_free_pud_entry_table(struct kvm *kvm, pud_t *pud,
342 * so can be freed without flushing the PWC again. 451 * so can be freed without flushing the PWC again.
343 */ 452 */
344 pud_clear(pud); 453 pud_clear(pud);
345 kvmppc_radix_flush_pwc(kvm); 454 kvmppc_radix_flush_pwc(kvm, lpid);
346 455
347 kvmppc_unmap_free_pmd(kvm, pmd, false); 456 kvmppc_unmap_free_pmd(kvm, pmd, false, lpid);
348} 457}
349 458
350/* 459/*
@@ -356,8 +465,10 @@ static void kvmppc_unmap_free_pud_entry_table(struct kvm *kvm, pud_t *pud,
356 */ 465 */
357#define PTE_BITS_MUST_MATCH (~(_PAGE_WRITE | _PAGE_DIRTY | _PAGE_ACCESSED)) 466#define PTE_BITS_MUST_MATCH (~(_PAGE_WRITE | _PAGE_DIRTY | _PAGE_ACCESSED))
358 467
359static int kvmppc_create_pte(struct kvm *kvm, pte_t pte, unsigned long gpa, 468int kvmppc_create_pte(struct kvm *kvm, pgd_t *pgtable, pte_t pte,
360 unsigned int level, unsigned long mmu_seq) 469 unsigned long gpa, unsigned int level,
470 unsigned long mmu_seq, unsigned int lpid,
471 unsigned long *rmapp, struct rmap_nested **n_rmap)
361{ 472{
362 pgd_t *pgd; 473 pgd_t *pgd;
363 pud_t *pud, *new_pud = NULL; 474 pud_t *pud, *new_pud = NULL;
@@ -366,7 +477,7 @@ static int kvmppc_create_pte(struct kvm *kvm, pte_t pte, unsigned long gpa,
366 int ret; 477 int ret;
367 478
368 /* Traverse the guest's 2nd-level tree, allocate new levels needed */ 479 /* Traverse the guest's 2nd-level tree, allocate new levels needed */
369 pgd = kvm->arch.pgtable + pgd_index(gpa); 480 pgd = pgtable + pgd_index(gpa);
370 pud = NULL; 481 pud = NULL;
371 if (pgd_present(*pgd)) 482 if (pgd_present(*pgd))
372 pud = pud_offset(pgd, gpa); 483 pud = pud_offset(pgd, gpa);
@@ -423,7 +534,8 @@ static int kvmppc_create_pte(struct kvm *kvm, pte_t pte, unsigned long gpa,
423 goto out_unlock; 534 goto out_unlock;
424 } 535 }
425 /* Valid 1GB page here already, remove it */ 536 /* Valid 1GB page here already, remove it */
426 kvmppc_unmap_pte(kvm, (pte_t *)pud, hgpa, PUD_SHIFT); 537 kvmppc_unmap_pte(kvm, (pte_t *)pud, hgpa, PUD_SHIFT, NULL,
538 lpid);
427 } 539 }
428 if (level == 2) { 540 if (level == 2) {
429 if (!pud_none(*pud)) { 541 if (!pud_none(*pud)) {
@@ -432,9 +544,11 @@ static int kvmppc_create_pte(struct kvm *kvm, pte_t pte, unsigned long gpa,
432 * install a large page, so remove and free the page 544 * install a large page, so remove and free the page
433 * table page. 545 * table page.
434 */ 546 */
435 kvmppc_unmap_free_pud_entry_table(kvm, pud, gpa); 547 kvmppc_unmap_free_pud_entry_table(kvm, pud, gpa, lpid);
436 } 548 }
437 kvmppc_radix_set_pte_at(kvm, gpa, (pte_t *)pud, pte); 549 kvmppc_radix_set_pte_at(kvm, gpa, (pte_t *)pud, pte);
550 if (rmapp && n_rmap)
551 kvmhv_insert_nest_rmap(kvm, rmapp, n_rmap);
438 ret = 0; 552 ret = 0;
439 goto out_unlock; 553 goto out_unlock;
440 } 554 }
@@ -458,7 +572,7 @@ static int kvmppc_create_pte(struct kvm *kvm, pte_t pte, unsigned long gpa,
458 WARN_ON_ONCE((pmd_val(*pmd) ^ pte_val(pte)) & 572 WARN_ON_ONCE((pmd_val(*pmd) ^ pte_val(pte)) &
459 PTE_BITS_MUST_MATCH); 573 PTE_BITS_MUST_MATCH);
460 kvmppc_radix_update_pte(kvm, pmdp_ptep(pmd), 574 kvmppc_radix_update_pte(kvm, pmdp_ptep(pmd),
461 0, pte_val(pte), lgpa, PMD_SHIFT); 575 0, pte_val(pte), lgpa, PMD_SHIFT);
462 ret = 0; 576 ret = 0;
463 goto out_unlock; 577 goto out_unlock;
464 } 578 }
@@ -472,7 +586,8 @@ static int kvmppc_create_pte(struct kvm *kvm, pte_t pte, unsigned long gpa,
472 goto out_unlock; 586 goto out_unlock;
473 } 587 }
474 /* Valid 2MB page here already, remove it */ 588 /* Valid 2MB page here already, remove it */
475 kvmppc_unmap_pte(kvm, pmdp_ptep(pmd), lgpa, PMD_SHIFT); 589 kvmppc_unmap_pte(kvm, pmdp_ptep(pmd), lgpa, PMD_SHIFT, NULL,
590 lpid);
476 } 591 }
477 if (level == 1) { 592 if (level == 1) {
478 if (!pmd_none(*pmd)) { 593 if (!pmd_none(*pmd)) {
@@ -481,9 +596,11 @@ static int kvmppc_create_pte(struct kvm *kvm, pte_t pte, unsigned long gpa,
481 * install a large page, so remove and free the page 596 * install a large page, so remove and free the page
482 * table page. 597 * table page.
483 */ 598 */
484 kvmppc_unmap_free_pmd_entry_table(kvm, pmd, gpa); 599 kvmppc_unmap_free_pmd_entry_table(kvm, pmd, gpa, lpid);
485 } 600 }
486 kvmppc_radix_set_pte_at(kvm, gpa, pmdp_ptep(pmd), pte); 601 kvmppc_radix_set_pte_at(kvm, gpa, pmdp_ptep(pmd), pte);
602 if (rmapp && n_rmap)
603 kvmhv_insert_nest_rmap(kvm, rmapp, n_rmap);
487 ret = 0; 604 ret = 0;
488 goto out_unlock; 605 goto out_unlock;
489 } 606 }
@@ -508,6 +625,8 @@ static int kvmppc_create_pte(struct kvm *kvm, pte_t pte, unsigned long gpa,
508 goto out_unlock; 625 goto out_unlock;
509 } 626 }
510 kvmppc_radix_set_pte_at(kvm, gpa, ptep, pte); 627 kvmppc_radix_set_pte_at(kvm, gpa, ptep, pte);
628 if (rmapp && n_rmap)
629 kvmhv_insert_nest_rmap(kvm, rmapp, n_rmap);
511 ret = 0; 630 ret = 0;
512 631
513 out_unlock: 632 out_unlock:
@@ -521,95 +640,49 @@ static int kvmppc_create_pte(struct kvm *kvm, pte_t pte, unsigned long gpa,
521 return ret; 640 return ret;
522} 641}
523 642
524int kvmppc_book3s_radix_page_fault(struct kvm_run *run, struct kvm_vcpu *vcpu, 643bool kvmppc_hv_handle_set_rc(struct kvm *kvm, pgd_t *pgtable, bool writing,
525 unsigned long ea, unsigned long dsisr) 644 unsigned long gpa, unsigned int lpid)
645{
646 unsigned long pgflags;
647 unsigned int shift;
648 pte_t *ptep;
649
650 /*
651 * Need to set an R or C bit in the 2nd-level tables;
652 * since we are just helping out the hardware here,
653 * it is sufficient to do what the hardware does.
654 */
655 pgflags = _PAGE_ACCESSED;
656 if (writing)
657 pgflags |= _PAGE_DIRTY;
658 /*
659 * We are walking the secondary (partition-scoped) page table here.
660 * We can do this without disabling irq because the Linux MM
661 * subsystem doesn't do THP splits and collapses on this tree.
662 */
663 ptep = __find_linux_pte(pgtable, gpa, NULL, &shift);
664 if (ptep && pte_present(*ptep) && (!writing || pte_write(*ptep))) {
665 kvmppc_radix_update_pte(kvm, ptep, 0, pgflags, gpa, shift);
666 return true;
667 }
668 return false;
669}
670
671int kvmppc_book3s_instantiate_page(struct kvm_vcpu *vcpu,
672 unsigned long gpa,
673 struct kvm_memory_slot *memslot,
674 bool writing, bool kvm_ro,
675 pte_t *inserted_pte, unsigned int *levelp)
526{ 676{
527 struct kvm *kvm = vcpu->kvm; 677 struct kvm *kvm = vcpu->kvm;
528 unsigned long mmu_seq;
529 unsigned long gpa, gfn, hva;
530 struct kvm_memory_slot *memslot;
531 struct page *page = NULL; 678 struct page *page = NULL;
532 long ret; 679 unsigned long mmu_seq;
533 bool writing; 680 unsigned long hva, gfn = gpa >> PAGE_SHIFT;
534 bool upgrade_write = false; 681 bool upgrade_write = false;
535 bool *upgrade_p = &upgrade_write; 682 bool *upgrade_p = &upgrade_write;
536 pte_t pte, *ptep; 683 pte_t pte, *ptep;
537 unsigned long pgflags;
538 unsigned int shift, level; 684 unsigned int shift, level;
539 685 int ret;
540 /* Check for unusual errors */
541 if (dsisr & DSISR_UNSUPP_MMU) {
542 pr_err("KVM: Got unsupported MMU fault\n");
543 return -EFAULT;
544 }
545 if (dsisr & DSISR_BADACCESS) {
546 /* Reflect to the guest as DSI */
547 pr_err("KVM: Got radix HV page fault with DSISR=%lx\n", dsisr);
548 kvmppc_core_queue_data_storage(vcpu, ea, dsisr);
549 return RESUME_GUEST;
550 }
551
552 /* Translate the logical address and get the page */
553 gpa = vcpu->arch.fault_gpa & ~0xfffUL;
554 gpa &= ~0xF000000000000000ul;
555 gfn = gpa >> PAGE_SHIFT;
556 if (!(dsisr & DSISR_PRTABLE_FAULT))
557 gpa |= ea & 0xfff;
558 memslot = gfn_to_memslot(kvm, gfn);
559
560 /* No memslot means it's an emulated MMIO region */
561 if (!memslot || (memslot->flags & KVM_MEMSLOT_INVALID)) {
562 if (dsisr & (DSISR_PRTABLE_FAULT | DSISR_BADACCESS |
563 DSISR_SET_RC)) {
564 /*
565 * Bad address in guest page table tree, or other
566 * unusual error - reflect it to the guest as DSI.
567 */
568 kvmppc_core_queue_data_storage(vcpu, ea, dsisr);
569 return RESUME_GUEST;
570 }
571 return kvmppc_hv_emulate_mmio(run, vcpu, gpa, ea,
572 dsisr & DSISR_ISSTORE);
573 }
574
575 writing = (dsisr & DSISR_ISSTORE) != 0;
576 if (memslot->flags & KVM_MEM_READONLY) {
577 if (writing) {
578 /* give the guest a DSI */
579 dsisr = DSISR_ISSTORE | DSISR_PROTFAULT;
580 kvmppc_core_queue_data_storage(vcpu, ea, dsisr);
581 return RESUME_GUEST;
582 }
583 upgrade_p = NULL;
584 }
585
586 if (dsisr & DSISR_SET_RC) {
587 /*
588 * Need to set an R or C bit in the 2nd-level tables;
589 * since we are just helping out the hardware here,
590 * it is sufficient to do what the hardware does.
591 */
592 pgflags = _PAGE_ACCESSED;
593 if (writing)
594 pgflags |= _PAGE_DIRTY;
595 /*
596 * We are walking the secondary page table here. We can do this
597 * without disabling irq.
598 */
599 spin_lock(&kvm->mmu_lock);
600 ptep = __find_linux_pte(kvm->arch.pgtable,
601 gpa, NULL, &shift);
602 if (ptep && pte_present(*ptep) &&
603 (!writing || pte_write(*ptep))) {
604 kvmppc_radix_update_pte(kvm, ptep, 0, pgflags,
605 gpa, shift);
606 dsisr &= ~DSISR_SET_RC;
607 }
608 spin_unlock(&kvm->mmu_lock);
609 if (!(dsisr & (DSISR_BAD_FAULT_64S | DSISR_NOHPTE |
610 DSISR_PROTFAULT | DSISR_SET_RC)))
611 return RESUME_GUEST;
612 }
613 686
614 /* used to check for invalidations in progress */ 687 /* used to check for invalidations in progress */
615 mmu_seq = kvm->mmu_notifier_seq; 688 mmu_seq = kvm->mmu_notifier_seq;
@@ -622,7 +695,7 @@ int kvmppc_book3s_radix_page_fault(struct kvm_run *run, struct kvm_vcpu *vcpu,
622 * is that the page is writable. 695 * is that the page is writable.
623 */ 696 */
624 hva = gfn_to_hva_memslot(memslot, gfn); 697 hva = gfn_to_hva_memslot(memslot, gfn);
625 if (upgrade_p && __get_user_pages_fast(hva, 1, 1, &page) == 1) { 698 if (!kvm_ro && __get_user_pages_fast(hva, 1, 1, &page) == 1) {
626 upgrade_write = true; 699 upgrade_write = true;
627 } else { 700 } else {
628 unsigned long pfn; 701 unsigned long pfn;
@@ -690,7 +763,12 @@ int kvmppc_book3s_radix_page_fault(struct kvm_run *run, struct kvm_vcpu *vcpu,
690 } 763 }
691 764
692 /* Allocate space in the tree and write the PTE */ 765 /* Allocate space in the tree and write the PTE */
693 ret = kvmppc_create_pte(kvm, pte, gpa, level, mmu_seq); 766 ret = kvmppc_create_pte(kvm, kvm->arch.pgtable, pte, gpa, level,
767 mmu_seq, kvm->arch.lpid, NULL, NULL);
768 if (inserted_pte)
769 *inserted_pte = pte;
770 if (levelp)
771 *levelp = level;
694 772
695 if (page) { 773 if (page) {
696 if (!ret && (pte_val(pte) & _PAGE_WRITE)) 774 if (!ret && (pte_val(pte) & _PAGE_WRITE))
@@ -698,6 +776,82 @@ int kvmppc_book3s_radix_page_fault(struct kvm_run *run, struct kvm_vcpu *vcpu,
698 put_page(page); 776 put_page(page);
699 } 777 }
700 778
779 return ret;
780}
781
782int kvmppc_book3s_radix_page_fault(struct kvm_run *run, struct kvm_vcpu *vcpu,
783 unsigned long ea, unsigned long dsisr)
784{
785 struct kvm *kvm = vcpu->kvm;
786 unsigned long gpa, gfn;
787 struct kvm_memory_slot *memslot;
788 long ret;
789 bool writing = !!(dsisr & DSISR_ISSTORE);
790 bool kvm_ro = false;
791
792 /* Check for unusual errors */
793 if (dsisr & DSISR_UNSUPP_MMU) {
794 pr_err("KVM: Got unsupported MMU fault\n");
795 return -EFAULT;
796 }
797 if (dsisr & DSISR_BADACCESS) {
798 /* Reflect to the guest as DSI */
799 pr_err("KVM: Got radix HV page fault with DSISR=%lx\n", dsisr);
800 kvmppc_core_queue_data_storage(vcpu, ea, dsisr);
801 return RESUME_GUEST;
802 }
803
804 /* Translate the logical address */
805 gpa = vcpu->arch.fault_gpa & ~0xfffUL;
806 gpa &= ~0xF000000000000000ul;
807 gfn = gpa >> PAGE_SHIFT;
808 if (!(dsisr & DSISR_PRTABLE_FAULT))
809 gpa |= ea & 0xfff;
810
811 /* Get the corresponding memslot */
812 memslot = gfn_to_memslot(kvm, gfn);
813
814 /* No memslot means it's an emulated MMIO region */
815 if (!memslot || (memslot->flags & KVM_MEMSLOT_INVALID)) {
816 if (dsisr & (DSISR_PRTABLE_FAULT | DSISR_BADACCESS |
817 DSISR_SET_RC)) {
818 /*
819 * Bad address in guest page table tree, or other
820 * unusual error - reflect it to the guest as DSI.
821 */
822 kvmppc_core_queue_data_storage(vcpu, ea, dsisr);
823 return RESUME_GUEST;
824 }
825 return kvmppc_hv_emulate_mmio(run, vcpu, gpa, ea, writing);
826 }
827
828 if (memslot->flags & KVM_MEM_READONLY) {
829 if (writing) {
830 /* give the guest a DSI */
831 kvmppc_core_queue_data_storage(vcpu, ea, DSISR_ISSTORE |
832 DSISR_PROTFAULT);
833 return RESUME_GUEST;
834 }
835 kvm_ro = true;
836 }
837
838 /* Failed to set the reference/change bits */
839 if (dsisr & DSISR_SET_RC) {
840 spin_lock(&kvm->mmu_lock);
841 if (kvmppc_hv_handle_set_rc(kvm, kvm->arch.pgtable,
842 writing, gpa, kvm->arch.lpid))
843 dsisr &= ~DSISR_SET_RC;
844 spin_unlock(&kvm->mmu_lock);
845
846 if (!(dsisr & (DSISR_BAD_FAULT_64S | DSISR_NOHPTE |
847 DSISR_PROTFAULT | DSISR_SET_RC)))
848 return RESUME_GUEST;
849 }
850
851 /* Try to insert a pte */
852 ret = kvmppc_book3s_instantiate_page(vcpu, gpa, memslot, writing,
853 kvm_ro, NULL, NULL);
854
701 if (ret == 0 || ret == -EAGAIN) 855 if (ret == 0 || ret == -EAGAIN)
702 ret = RESUME_GUEST; 856 ret = RESUME_GUEST;
703 return ret; 857 return ret;
@@ -710,20 +864,11 @@ int kvm_unmap_radix(struct kvm *kvm, struct kvm_memory_slot *memslot,
710 pte_t *ptep; 864 pte_t *ptep;
711 unsigned long gpa = gfn << PAGE_SHIFT; 865 unsigned long gpa = gfn << PAGE_SHIFT;
712 unsigned int shift; 866 unsigned int shift;
713 unsigned long old;
714 867
715 ptep = __find_linux_pte(kvm->arch.pgtable, gpa, NULL, &shift); 868 ptep = __find_linux_pte(kvm->arch.pgtable, gpa, NULL, &shift);
716 if (ptep && pte_present(*ptep)) { 869 if (ptep && pte_present(*ptep))
717 old = kvmppc_radix_update_pte(kvm, ptep, ~0UL, 0, 870 kvmppc_unmap_pte(kvm, ptep, gpa, shift, memslot,
718 gpa, shift); 871 kvm->arch.lpid);
719 kvmppc_radix_tlbie_page(kvm, gpa, shift);
720 if ((old & _PAGE_DIRTY) && memslot->dirty_bitmap) {
721 unsigned long psize = PAGE_SIZE;
722 if (shift)
723 psize = 1ul << shift;
724 kvmppc_update_dirty_map(memslot, gfn, psize);
725 }
726 }
727 return 0; 872 return 0;
728} 873}
729 874
@@ -778,7 +923,7 @@ static int kvm_radix_test_clear_dirty(struct kvm *kvm,
778 ret = 1 << (shift - PAGE_SHIFT); 923 ret = 1 << (shift - PAGE_SHIFT);
779 kvmppc_radix_update_pte(kvm, ptep, _PAGE_DIRTY, 0, 924 kvmppc_radix_update_pte(kvm, ptep, _PAGE_DIRTY, 0,
780 gpa, shift); 925 gpa, shift);
781 kvmppc_radix_tlbie_page(kvm, gpa, shift); 926 kvmppc_radix_tlbie_page(kvm, gpa, shift, kvm->arch.lpid);
782 } 927 }
783 return ret; 928 return ret;
784} 929}
@@ -863,6 +1008,215 @@ static void pmd_ctor(void *addr)
863 memset(addr, 0, RADIX_PMD_TABLE_SIZE); 1008 memset(addr, 0, RADIX_PMD_TABLE_SIZE);
864} 1009}
865 1010
1011struct debugfs_radix_state {
1012 struct kvm *kvm;
1013 struct mutex mutex;
1014 unsigned long gpa;
1015 int lpid;
1016 int chars_left;
1017 int buf_index;
1018 char buf[128];
1019 u8 hdr;
1020};
1021
1022static int debugfs_radix_open(struct inode *inode, struct file *file)
1023{
1024 struct kvm *kvm = inode->i_private;
1025 struct debugfs_radix_state *p;
1026
1027 p = kzalloc(sizeof(*p), GFP_KERNEL);
1028 if (!p)
1029 return -ENOMEM;
1030
1031 kvm_get_kvm(kvm);
1032 p->kvm = kvm;
1033 mutex_init(&p->mutex);
1034 file->private_data = p;
1035
1036 return nonseekable_open(inode, file);
1037}
1038
1039static int debugfs_radix_release(struct inode *inode, struct file *file)
1040{
1041 struct debugfs_radix_state *p = file->private_data;
1042
1043 kvm_put_kvm(p->kvm);
1044 kfree(p);
1045 return 0;
1046}
1047
1048static ssize_t debugfs_radix_read(struct file *file, char __user *buf,
1049 size_t len, loff_t *ppos)
1050{
1051 struct debugfs_radix_state *p = file->private_data;
1052 ssize_t ret, r;
1053 unsigned long n;
1054 struct kvm *kvm;
1055 unsigned long gpa;
1056 pgd_t *pgt;
1057 struct kvm_nested_guest *nested;
1058 pgd_t pgd, *pgdp;
1059 pud_t pud, *pudp;
1060 pmd_t pmd, *pmdp;
1061 pte_t *ptep;
1062 int shift;
1063 unsigned long pte;
1064
1065 kvm = p->kvm;
1066 if (!kvm_is_radix(kvm))
1067 return 0;
1068
1069 ret = mutex_lock_interruptible(&p->mutex);
1070 if (ret)
1071 return ret;
1072
1073 if (p->chars_left) {
1074 n = p->chars_left;
1075 if (n > len)
1076 n = len;
1077 r = copy_to_user(buf, p->buf + p->buf_index, n);
1078 n -= r;
1079 p->chars_left -= n;
1080 p->buf_index += n;
1081 buf += n;
1082 len -= n;
1083 ret = n;
1084 if (r) {
1085 if (!n)
1086 ret = -EFAULT;
1087 goto out;
1088 }
1089 }
1090
1091 gpa = p->gpa;
1092 nested = NULL;
1093 pgt = NULL;
1094 while (len != 0 && p->lpid >= 0) {
1095 if (gpa >= RADIX_PGTABLE_RANGE) {
1096 gpa = 0;
1097 pgt = NULL;
1098 if (nested) {
1099 kvmhv_put_nested(nested);
1100 nested = NULL;
1101 }
1102 p->lpid = kvmhv_nested_next_lpid(kvm, p->lpid);
1103 p->hdr = 0;
1104 if (p->lpid < 0)
1105 break;
1106 }
1107 if (!pgt) {
1108 if (p->lpid == 0) {
1109 pgt = kvm->arch.pgtable;
1110 } else {
1111 nested = kvmhv_get_nested(kvm, p->lpid, false);
1112 if (!nested) {
1113 gpa = RADIX_PGTABLE_RANGE;
1114 continue;
1115 }
1116 pgt = nested->shadow_pgtable;
1117 }
1118 }
1119 n = 0;
1120 if (!p->hdr) {
1121 if (p->lpid > 0)
1122 n = scnprintf(p->buf, sizeof(p->buf),
1123 "\nNested LPID %d: ", p->lpid);
1124 n += scnprintf(p->buf + n, sizeof(p->buf) - n,
1125 "pgdir: %lx\n", (unsigned long)pgt);
1126 p->hdr = 1;
1127 goto copy;
1128 }
1129
1130 pgdp = pgt + pgd_index(gpa);
1131 pgd = READ_ONCE(*pgdp);
1132 if (!(pgd_val(pgd) & _PAGE_PRESENT)) {
1133 gpa = (gpa & PGDIR_MASK) + PGDIR_SIZE;
1134 continue;
1135 }
1136
1137 pudp = pud_offset(&pgd, gpa);
1138 pud = READ_ONCE(*pudp);
1139 if (!(pud_val(pud) & _PAGE_PRESENT)) {
1140 gpa = (gpa & PUD_MASK) + PUD_SIZE;
1141 continue;
1142 }
1143 if (pud_val(pud) & _PAGE_PTE) {
1144 pte = pud_val(pud);
1145 shift = PUD_SHIFT;
1146 goto leaf;
1147 }
1148
1149 pmdp = pmd_offset(&pud, gpa);
1150 pmd = READ_ONCE(*pmdp);
1151 if (!(pmd_val(pmd) & _PAGE_PRESENT)) {
1152 gpa = (gpa & PMD_MASK) + PMD_SIZE;
1153 continue;
1154 }
1155 if (pmd_val(pmd) & _PAGE_PTE) {
1156 pte = pmd_val(pmd);
1157 shift = PMD_SHIFT;
1158 goto leaf;
1159 }
1160
1161 ptep = pte_offset_kernel(&pmd, gpa);
1162 pte = pte_val(READ_ONCE(*ptep));
1163 if (!(pte & _PAGE_PRESENT)) {
1164 gpa += PAGE_SIZE;
1165 continue;
1166 }
1167 shift = PAGE_SHIFT;
1168 leaf:
1169 n = scnprintf(p->buf, sizeof(p->buf),
1170 " %lx: %lx %d\n", gpa, pte, shift);
1171 gpa += 1ul << shift;
1172 copy:
1173 p->chars_left = n;
1174 if (n > len)
1175 n = len;
1176 r = copy_to_user(buf, p->buf, n);
1177 n -= r;
1178 p->chars_left -= n;
1179 p->buf_index = n;
1180 buf += n;
1181 len -= n;
1182 ret += n;
1183 if (r) {
1184 if (!ret)
1185 ret = -EFAULT;
1186 break;
1187 }
1188 }
1189 p->gpa = gpa;
1190 if (nested)
1191 kvmhv_put_nested(nested);
1192
1193 out:
1194 mutex_unlock(&p->mutex);
1195 return ret;
1196}
1197
1198static ssize_t debugfs_radix_write(struct file *file, const char __user *buf,
1199 size_t len, loff_t *ppos)
1200{
1201 return -EACCES;
1202}
1203
1204static const struct file_operations debugfs_radix_fops = {
1205 .owner = THIS_MODULE,
1206 .open = debugfs_radix_open,
1207 .release = debugfs_radix_release,
1208 .read = debugfs_radix_read,
1209 .write = debugfs_radix_write,
1210 .llseek = generic_file_llseek,
1211};
1212
1213void kvmhv_radix_debugfs_init(struct kvm *kvm)
1214{
1215 kvm->arch.radix_dentry = debugfs_create_file("radix", 0400,
1216 kvm->arch.debugfs_dir, kvm,
1217 &debugfs_radix_fops);
1218}
1219
866int kvmppc_radix_init(void) 1220int kvmppc_radix_init(void)
867{ 1221{
868 unsigned long size = sizeof(void *) << RADIX_PTE_INDEX_SIZE; 1222 unsigned long size = sizeof(void *) << RADIX_PTE_INDEX_SIZE;
diff --git a/arch/powerpc/kvm/book3s_64_vio.c b/arch/powerpc/kvm/book3s_64_vio.c
index 9a3f2646ecc7..62a8d03ba7e9 100644
--- a/arch/powerpc/kvm/book3s_64_vio.c
+++ b/arch/powerpc/kvm/book3s_64_vio.c
@@ -363,6 +363,40 @@ long kvm_vm_ioctl_create_spapr_tce(struct kvm *kvm,
363 return ret; 363 return ret;
364} 364}
365 365
366static long kvmppc_tce_validate(struct kvmppc_spapr_tce_table *stt,
367 unsigned long tce)
368{
369 unsigned long gpa = tce & ~(TCE_PCI_READ | TCE_PCI_WRITE);
370 enum dma_data_direction dir = iommu_tce_direction(tce);
371 struct kvmppc_spapr_tce_iommu_table *stit;
372 unsigned long ua = 0;
373
374 /* Allow userspace to poison TCE table */
375 if (dir == DMA_NONE)
376 return H_SUCCESS;
377
378 if (iommu_tce_check_gpa(stt->page_shift, gpa))
379 return H_TOO_HARD;
380
381 if (kvmppc_tce_to_ua(stt->kvm, tce, &ua, NULL))
382 return H_TOO_HARD;
383
384 list_for_each_entry_rcu(stit, &stt->iommu_tables, next) {
385 unsigned long hpa = 0;
386 struct mm_iommu_table_group_mem_t *mem;
387 long shift = stit->tbl->it_page_shift;
388
389 mem = mm_iommu_lookup(stt->kvm->mm, ua, 1ULL << shift);
390 if (!mem)
391 return H_TOO_HARD;
392
393 if (mm_iommu_ua_to_hpa(mem, ua, shift, &hpa))
394 return H_TOO_HARD;
395 }
396
397 return H_SUCCESS;
398}
399
366static void kvmppc_clear_tce(struct iommu_table *tbl, unsigned long entry) 400static void kvmppc_clear_tce(struct iommu_table *tbl, unsigned long entry)
367{ 401{
368 unsigned long hpa = 0; 402 unsigned long hpa = 0;
@@ -376,11 +410,10 @@ static long kvmppc_tce_iommu_mapped_dec(struct kvm *kvm,
376{ 410{
377 struct mm_iommu_table_group_mem_t *mem = NULL; 411 struct mm_iommu_table_group_mem_t *mem = NULL;
378 const unsigned long pgsize = 1ULL << tbl->it_page_shift; 412 const unsigned long pgsize = 1ULL << tbl->it_page_shift;
379 __be64 *pua = IOMMU_TABLE_USERSPACE_ENTRY(tbl, entry); 413 __be64 *pua = IOMMU_TABLE_USERSPACE_ENTRY_RO(tbl, entry);
380 414
381 if (!pua) 415 if (!pua)
382 /* it_userspace allocation might be delayed */ 416 return H_SUCCESS;
383 return H_TOO_HARD;
384 417
385 mem = mm_iommu_lookup(kvm->mm, be64_to_cpu(*pua), pgsize); 418 mem = mm_iommu_lookup(kvm->mm, be64_to_cpu(*pua), pgsize);
386 if (!mem) 419 if (!mem)
@@ -401,7 +434,7 @@ static long kvmppc_tce_iommu_do_unmap(struct kvm *kvm,
401 long ret; 434 long ret;
402 435
403 if (WARN_ON_ONCE(iommu_tce_xchg(tbl, entry, &hpa, &dir))) 436 if (WARN_ON_ONCE(iommu_tce_xchg(tbl, entry, &hpa, &dir)))
404 return H_HARDWARE; 437 return H_TOO_HARD;
405 438
406 if (dir == DMA_NONE) 439 if (dir == DMA_NONE)
407 return H_SUCCESS; 440 return H_SUCCESS;
@@ -449,15 +482,15 @@ long kvmppc_tce_iommu_do_map(struct kvm *kvm, struct iommu_table *tbl,
449 return H_TOO_HARD; 482 return H_TOO_HARD;
450 483
451 if (WARN_ON_ONCE(mm_iommu_ua_to_hpa(mem, ua, tbl->it_page_shift, &hpa))) 484 if (WARN_ON_ONCE(mm_iommu_ua_to_hpa(mem, ua, tbl->it_page_shift, &hpa)))
452 return H_HARDWARE; 485 return H_TOO_HARD;
453 486
454 if (mm_iommu_mapped_inc(mem)) 487 if (mm_iommu_mapped_inc(mem))
455 return H_CLOSED; 488 return H_TOO_HARD;
456 489
457 ret = iommu_tce_xchg(tbl, entry, &hpa, &dir); 490 ret = iommu_tce_xchg(tbl, entry, &hpa, &dir);
458 if (WARN_ON_ONCE(ret)) { 491 if (WARN_ON_ONCE(ret)) {
459 mm_iommu_mapped_dec(mem); 492 mm_iommu_mapped_dec(mem);
460 return H_HARDWARE; 493 return H_TOO_HARD;
461 } 494 }
462 495
463 if (dir != DMA_NONE) 496 if (dir != DMA_NONE)
@@ -517,8 +550,7 @@ long kvmppc_h_put_tce(struct kvm_vcpu *vcpu, unsigned long liobn,
517 550
518 idx = srcu_read_lock(&vcpu->kvm->srcu); 551 idx = srcu_read_lock(&vcpu->kvm->srcu);
519 552
520 if ((dir != DMA_NONE) && kvmppc_gpa_to_ua(vcpu->kvm, 553 if ((dir != DMA_NONE) && kvmppc_tce_to_ua(vcpu->kvm, tce, &ua, NULL)) {
521 tce & ~(TCE_PCI_READ | TCE_PCI_WRITE), &ua, NULL)) {
522 ret = H_PARAMETER; 554 ret = H_PARAMETER;
523 goto unlock_exit; 555 goto unlock_exit;
524 } 556 }
@@ -533,14 +565,10 @@ long kvmppc_h_put_tce(struct kvm_vcpu *vcpu, unsigned long liobn,
533 ret = kvmppc_tce_iommu_map(vcpu->kvm, stt, stit->tbl, 565 ret = kvmppc_tce_iommu_map(vcpu->kvm, stt, stit->tbl,
534 entry, ua, dir); 566 entry, ua, dir);
535 567
536 if (ret == H_SUCCESS) 568 if (ret != H_SUCCESS) {
537 continue; 569 kvmppc_clear_tce(stit->tbl, entry);
538
539 if (ret == H_TOO_HARD)
540 goto unlock_exit; 570 goto unlock_exit;
541 571 }
542 WARN_ON_ONCE(1);
543 kvmppc_clear_tce(stit->tbl, entry);
544 } 572 }
545 573
546 kvmppc_tce_put(stt, entry, tce); 574 kvmppc_tce_put(stt, entry, tce);
@@ -583,7 +611,7 @@ long kvmppc_h_put_tce_indirect(struct kvm_vcpu *vcpu,
583 return ret; 611 return ret;
584 612
585 idx = srcu_read_lock(&vcpu->kvm->srcu); 613 idx = srcu_read_lock(&vcpu->kvm->srcu);
586 if (kvmppc_gpa_to_ua(vcpu->kvm, tce_list, &ua, NULL)) { 614 if (kvmppc_tce_to_ua(vcpu->kvm, tce_list, &ua, NULL)) {
587 ret = H_TOO_HARD; 615 ret = H_TOO_HARD;
588 goto unlock_exit; 616 goto unlock_exit;
589 } 617 }
@@ -599,10 +627,26 @@ long kvmppc_h_put_tce_indirect(struct kvm_vcpu *vcpu,
599 ret = kvmppc_tce_validate(stt, tce); 627 ret = kvmppc_tce_validate(stt, tce);
600 if (ret != H_SUCCESS) 628 if (ret != H_SUCCESS)
601 goto unlock_exit; 629 goto unlock_exit;
630 }
631
632 for (i = 0; i < npages; ++i) {
633 /*
634 * This looks unsafe, because we validate, then regrab
635 * the TCE from userspace which could have been changed by
636 * another thread.
637 *
638 * But it actually is safe, because the relevant checks will be
639 * re-executed in the following code. If userspace tries to
640 * change this dodgily it will result in a messier failure mode
641 * but won't threaten the host.
642 */
643 if (get_user(tce, tces + i)) {
644 ret = H_TOO_HARD;
645 goto unlock_exit;
646 }
647 tce = be64_to_cpu(tce);
602 648
603 if (kvmppc_gpa_to_ua(vcpu->kvm, 649 if (kvmppc_tce_to_ua(vcpu->kvm, tce, &ua, NULL))
604 tce & ~(TCE_PCI_READ | TCE_PCI_WRITE),
605 &ua, NULL))
606 return H_PARAMETER; 650 return H_PARAMETER;
607 651
608 list_for_each_entry_lockless(stit, &stt->iommu_tables, next) { 652 list_for_each_entry_lockless(stit, &stt->iommu_tables, next) {
@@ -610,14 +654,10 @@ long kvmppc_h_put_tce_indirect(struct kvm_vcpu *vcpu,
610 stit->tbl, entry + i, ua, 654 stit->tbl, entry + i, ua,
611 iommu_tce_direction(tce)); 655 iommu_tce_direction(tce));
612 656
613 if (ret == H_SUCCESS) 657 if (ret != H_SUCCESS) {
614 continue; 658 kvmppc_clear_tce(stit->tbl, entry);
615
616 if (ret == H_TOO_HARD)
617 goto unlock_exit; 659 goto unlock_exit;
618 660 }
619 WARN_ON_ONCE(1);
620 kvmppc_clear_tce(stit->tbl, entry);
621 } 661 }
622 662
623 kvmppc_tce_put(stt, entry + i, tce); 663 kvmppc_tce_put(stt, entry + i, tce);
diff --git a/arch/powerpc/kvm/book3s_64_vio_hv.c b/arch/powerpc/kvm/book3s_64_vio_hv.c
index 6821ead4b4eb..2206bc729b9a 100644
--- a/arch/powerpc/kvm/book3s_64_vio_hv.c
+++ b/arch/powerpc/kvm/book3s_64_vio_hv.c
@@ -87,6 +87,7 @@ struct kvmppc_spapr_tce_table *kvmppc_find_table(struct kvm *kvm,
87} 87}
88EXPORT_SYMBOL_GPL(kvmppc_find_table); 88EXPORT_SYMBOL_GPL(kvmppc_find_table);
89 89
90#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
90/* 91/*
91 * Validates TCE address. 92 * Validates TCE address.
92 * At the moment flags and page mask are validated. 93 * At the moment flags and page mask are validated.
@@ -94,14 +95,14 @@ EXPORT_SYMBOL_GPL(kvmppc_find_table);
94 * to the table and user space is supposed to process them), we can skip 95 * to the table and user space is supposed to process them), we can skip
95 * checking other things (such as TCE is a guest RAM address or the page 96 * checking other things (such as TCE is a guest RAM address or the page
96 * was actually allocated). 97 * was actually allocated).
97 *
98 * WARNING: This will be called in real-mode on HV KVM and virtual
99 * mode on PR KVM
100 */ 98 */
101long kvmppc_tce_validate(struct kvmppc_spapr_tce_table *stt, unsigned long tce) 99static long kvmppc_rm_tce_validate(struct kvmppc_spapr_tce_table *stt,
100 unsigned long tce)
102{ 101{
103 unsigned long gpa = tce & ~(TCE_PCI_READ | TCE_PCI_WRITE); 102 unsigned long gpa = tce & ~(TCE_PCI_READ | TCE_PCI_WRITE);
104 enum dma_data_direction dir = iommu_tce_direction(tce); 103 enum dma_data_direction dir = iommu_tce_direction(tce);
104 struct kvmppc_spapr_tce_iommu_table *stit;
105 unsigned long ua = 0;
105 106
106 /* Allow userspace to poison TCE table */ 107 /* Allow userspace to poison TCE table */
107 if (dir == DMA_NONE) 108 if (dir == DMA_NONE)
@@ -110,9 +111,25 @@ long kvmppc_tce_validate(struct kvmppc_spapr_tce_table *stt, unsigned long tce)
110 if (iommu_tce_check_gpa(stt->page_shift, gpa)) 111 if (iommu_tce_check_gpa(stt->page_shift, gpa))
111 return H_PARAMETER; 112 return H_PARAMETER;
112 113
114 if (kvmppc_tce_to_ua(stt->kvm, tce, &ua, NULL))
115 return H_TOO_HARD;
116
117 list_for_each_entry_lockless(stit, &stt->iommu_tables, next) {
118 unsigned long hpa = 0;
119 struct mm_iommu_table_group_mem_t *mem;
120 long shift = stit->tbl->it_page_shift;
121
122 mem = mm_iommu_lookup_rm(stt->kvm->mm, ua, 1ULL << shift);
123 if (!mem)
124 return H_TOO_HARD;
125
126 if (mm_iommu_ua_to_hpa_rm(mem, ua, shift, &hpa))
127 return H_TOO_HARD;
128 }
129
113 return H_SUCCESS; 130 return H_SUCCESS;
114} 131}
115EXPORT_SYMBOL_GPL(kvmppc_tce_validate); 132#endif /* CONFIG_KVM_BOOK3S_HV_POSSIBLE */
116 133
117/* Note on the use of page_address() in real mode, 134/* Note on the use of page_address() in real mode,
118 * 135 *
@@ -164,10 +181,10 @@ void kvmppc_tce_put(struct kvmppc_spapr_tce_table *stt,
164} 181}
165EXPORT_SYMBOL_GPL(kvmppc_tce_put); 182EXPORT_SYMBOL_GPL(kvmppc_tce_put);
166 183
167long kvmppc_gpa_to_ua(struct kvm *kvm, unsigned long gpa, 184long kvmppc_tce_to_ua(struct kvm *kvm, unsigned long tce,
168 unsigned long *ua, unsigned long **prmap) 185 unsigned long *ua, unsigned long **prmap)
169{ 186{
170 unsigned long gfn = gpa >> PAGE_SHIFT; 187 unsigned long gfn = tce >> PAGE_SHIFT;
171 struct kvm_memory_slot *memslot; 188 struct kvm_memory_slot *memslot;
172 189
173 memslot = search_memslots(kvm_memslots(kvm), gfn); 190 memslot = search_memslots(kvm_memslots(kvm), gfn);
@@ -175,7 +192,7 @@ long kvmppc_gpa_to_ua(struct kvm *kvm, unsigned long gpa,
175 return -EINVAL; 192 return -EINVAL;
176 193
177 *ua = __gfn_to_hva_memslot(memslot, gfn) | 194 *ua = __gfn_to_hva_memslot(memslot, gfn) |
178 (gpa & ~(PAGE_MASK | TCE_PCI_READ | TCE_PCI_WRITE)); 195 (tce & ~(PAGE_MASK | TCE_PCI_READ | TCE_PCI_WRITE));
179 196
180#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE 197#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
181 if (prmap) 198 if (prmap)
@@ -184,7 +201,7 @@ long kvmppc_gpa_to_ua(struct kvm *kvm, unsigned long gpa,
184 201
185 return 0; 202 return 0;
186} 203}
187EXPORT_SYMBOL_GPL(kvmppc_gpa_to_ua); 204EXPORT_SYMBOL_GPL(kvmppc_tce_to_ua);
188 205
189#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE 206#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
190static long iommu_tce_xchg_rm(struct mm_struct *mm, struct iommu_table *tbl, 207static long iommu_tce_xchg_rm(struct mm_struct *mm, struct iommu_table *tbl,
@@ -197,7 +214,7 @@ static long iommu_tce_xchg_rm(struct mm_struct *mm, struct iommu_table *tbl,
197 214
198 if (!ret && ((*direction == DMA_FROM_DEVICE) || 215 if (!ret && ((*direction == DMA_FROM_DEVICE) ||
199 (*direction == DMA_BIDIRECTIONAL))) { 216 (*direction == DMA_BIDIRECTIONAL))) {
200 __be64 *pua = IOMMU_TABLE_USERSPACE_ENTRY_RM(tbl, entry); 217 __be64 *pua = IOMMU_TABLE_USERSPACE_ENTRY_RO(tbl, entry);
201 /* 218 /*
202 * kvmppc_rm_tce_iommu_do_map() updates the UA cache after 219 * kvmppc_rm_tce_iommu_do_map() updates the UA cache after
203 * calling this so we still get here a valid UA. 220 * calling this so we still get here a valid UA.
@@ -223,7 +240,7 @@ static long kvmppc_rm_tce_iommu_mapped_dec(struct kvm *kvm,
223{ 240{
224 struct mm_iommu_table_group_mem_t *mem = NULL; 241 struct mm_iommu_table_group_mem_t *mem = NULL;
225 const unsigned long pgsize = 1ULL << tbl->it_page_shift; 242 const unsigned long pgsize = 1ULL << tbl->it_page_shift;
226 __be64 *pua = IOMMU_TABLE_USERSPACE_ENTRY_RM(tbl, entry); 243 __be64 *pua = IOMMU_TABLE_USERSPACE_ENTRY_RO(tbl, entry);
227 244
228 if (!pua) 245 if (!pua)
229 /* it_userspace allocation might be delayed */ 246 /* it_userspace allocation might be delayed */
@@ -287,7 +304,7 @@ static long kvmppc_rm_tce_iommu_do_map(struct kvm *kvm, struct iommu_table *tbl,
287{ 304{
288 long ret; 305 long ret;
289 unsigned long hpa = 0; 306 unsigned long hpa = 0;
290 __be64 *pua = IOMMU_TABLE_USERSPACE_ENTRY_RM(tbl, entry); 307 __be64 *pua = IOMMU_TABLE_USERSPACE_ENTRY_RO(tbl, entry);
291 struct mm_iommu_table_group_mem_t *mem; 308 struct mm_iommu_table_group_mem_t *mem;
292 309
293 if (!pua) 310 if (!pua)
@@ -300,10 +317,10 @@ static long kvmppc_rm_tce_iommu_do_map(struct kvm *kvm, struct iommu_table *tbl,
300 317
301 if (WARN_ON_ONCE_RM(mm_iommu_ua_to_hpa_rm(mem, ua, tbl->it_page_shift, 318 if (WARN_ON_ONCE_RM(mm_iommu_ua_to_hpa_rm(mem, ua, tbl->it_page_shift,
302 &hpa))) 319 &hpa)))
303 return H_HARDWARE; 320 return H_TOO_HARD;
304 321
305 if (WARN_ON_ONCE_RM(mm_iommu_mapped_inc(mem))) 322 if (WARN_ON_ONCE_RM(mm_iommu_mapped_inc(mem)))
306 return H_CLOSED; 323 return H_TOO_HARD;
307 324
308 ret = iommu_tce_xchg_rm(kvm->mm, tbl, entry, &hpa, &dir); 325 ret = iommu_tce_xchg_rm(kvm->mm, tbl, entry, &hpa, &dir);
309 if (ret) { 326 if (ret) {
@@ -368,13 +385,12 @@ long kvmppc_rm_h_put_tce(struct kvm_vcpu *vcpu, unsigned long liobn,
368 if (ret != H_SUCCESS) 385 if (ret != H_SUCCESS)
369 return ret; 386 return ret;
370 387
371 ret = kvmppc_tce_validate(stt, tce); 388 ret = kvmppc_rm_tce_validate(stt, tce);
372 if (ret != H_SUCCESS) 389 if (ret != H_SUCCESS)
373 return ret; 390 return ret;
374 391
375 dir = iommu_tce_direction(tce); 392 dir = iommu_tce_direction(tce);
376 if ((dir != DMA_NONE) && kvmppc_gpa_to_ua(vcpu->kvm, 393 if ((dir != DMA_NONE) && kvmppc_tce_to_ua(vcpu->kvm, tce, &ua, NULL))
377 tce & ~(TCE_PCI_READ | TCE_PCI_WRITE), &ua, NULL))
378 return H_PARAMETER; 394 return H_PARAMETER;
379 395
380 entry = ioba >> stt->page_shift; 396 entry = ioba >> stt->page_shift;
@@ -387,14 +403,10 @@ long kvmppc_rm_h_put_tce(struct kvm_vcpu *vcpu, unsigned long liobn,
387 ret = kvmppc_rm_tce_iommu_map(vcpu->kvm, stt, 403 ret = kvmppc_rm_tce_iommu_map(vcpu->kvm, stt,
388 stit->tbl, entry, ua, dir); 404 stit->tbl, entry, ua, dir);
389 405
390 if (ret == H_SUCCESS) 406 if (ret != H_SUCCESS) {
391 continue; 407 kvmppc_rm_clear_tce(vcpu->kvm, stit->tbl, entry);
392
393 if (ret == H_TOO_HARD)
394 return ret; 408 return ret;
395 409 }
396 WARN_ON_ONCE_RM(1);
397 kvmppc_rm_clear_tce(vcpu->kvm, stit->tbl, entry);
398 } 410 }
399 411
400 kvmppc_tce_put(stt, entry, tce); 412 kvmppc_tce_put(stt, entry, tce);
@@ -480,7 +492,7 @@ long kvmppc_rm_h_put_tce_indirect(struct kvm_vcpu *vcpu,
480 */ 492 */
481 struct mm_iommu_table_group_mem_t *mem; 493 struct mm_iommu_table_group_mem_t *mem;
482 494
483 if (kvmppc_gpa_to_ua(vcpu->kvm, tce_list, &ua, NULL)) 495 if (kvmppc_tce_to_ua(vcpu->kvm, tce_list, &ua, NULL))
484 return H_TOO_HARD; 496 return H_TOO_HARD;
485 497
486 mem = mm_iommu_lookup_rm(vcpu->kvm->mm, ua, IOMMU_PAGE_SIZE_4K); 498 mem = mm_iommu_lookup_rm(vcpu->kvm->mm, ua, IOMMU_PAGE_SIZE_4K);
@@ -496,12 +508,12 @@ long kvmppc_rm_h_put_tce_indirect(struct kvm_vcpu *vcpu,
496 * We do not require memory to be preregistered in this case 508 * We do not require memory to be preregistered in this case
497 * so lock rmap and do __find_linux_pte_or_hugepte(). 509 * so lock rmap and do __find_linux_pte_or_hugepte().
498 */ 510 */
499 if (kvmppc_gpa_to_ua(vcpu->kvm, tce_list, &ua, &rmap)) 511 if (kvmppc_tce_to_ua(vcpu->kvm, tce_list, &ua, &rmap))
500 return H_TOO_HARD; 512 return H_TOO_HARD;
501 513
502 rmap = (void *) vmalloc_to_phys(rmap); 514 rmap = (void *) vmalloc_to_phys(rmap);
503 if (WARN_ON_ONCE_RM(!rmap)) 515 if (WARN_ON_ONCE_RM(!rmap))
504 return H_HARDWARE; 516 return H_TOO_HARD;
505 517
506 /* 518 /*
507 * Synchronize with the MMU notifier callbacks in 519 * Synchronize with the MMU notifier callbacks in
@@ -521,14 +533,16 @@ long kvmppc_rm_h_put_tce_indirect(struct kvm_vcpu *vcpu,
521 for (i = 0; i < npages; ++i) { 533 for (i = 0; i < npages; ++i) {
522 unsigned long tce = be64_to_cpu(((u64 *)tces)[i]); 534 unsigned long tce = be64_to_cpu(((u64 *)tces)[i]);
523 535
524 ret = kvmppc_tce_validate(stt, tce); 536 ret = kvmppc_rm_tce_validate(stt, tce);
525 if (ret != H_SUCCESS) 537 if (ret != H_SUCCESS)
526 goto unlock_exit; 538 goto unlock_exit;
539 }
540
541 for (i = 0; i < npages; ++i) {
542 unsigned long tce = be64_to_cpu(((u64 *)tces)[i]);
527 543
528 ua = 0; 544 ua = 0;
529 if (kvmppc_gpa_to_ua(vcpu->kvm, 545 if (kvmppc_tce_to_ua(vcpu->kvm, tce, &ua, NULL))
530 tce & ~(TCE_PCI_READ | TCE_PCI_WRITE),
531 &ua, NULL))
532 return H_PARAMETER; 546 return H_PARAMETER;
533 547
534 list_for_each_entry_lockless(stit, &stt->iommu_tables, next) { 548 list_for_each_entry_lockless(stit, &stt->iommu_tables, next) {
@@ -536,14 +550,11 @@ long kvmppc_rm_h_put_tce_indirect(struct kvm_vcpu *vcpu,
536 stit->tbl, entry + i, ua, 550 stit->tbl, entry + i, ua,
537 iommu_tce_direction(tce)); 551 iommu_tce_direction(tce));
538 552
539 if (ret == H_SUCCESS) 553 if (ret != H_SUCCESS) {
540 continue; 554 kvmppc_rm_clear_tce(vcpu->kvm, stit->tbl,
541 555 entry);
542 if (ret == H_TOO_HARD)
543 goto unlock_exit; 556 goto unlock_exit;
544 557 }
545 WARN_ON_ONCE_RM(1);
546 kvmppc_rm_clear_tce(vcpu->kvm, stit->tbl, entry);
547 } 558 }
548 559
549 kvmppc_tce_put(stt, entry + i, tce); 560 kvmppc_tce_put(stt, entry + i, tce);
diff --git a/arch/powerpc/kvm/book3s_emulate.c b/arch/powerpc/kvm/book3s_emulate.c
index 36b11c5a0dbb..8c7e933e942e 100644
--- a/arch/powerpc/kvm/book3s_emulate.c
+++ b/arch/powerpc/kvm/book3s_emulate.c
@@ -36,7 +36,6 @@
36#define OP_31_XOP_MTSR 210 36#define OP_31_XOP_MTSR 210
37#define OP_31_XOP_MTSRIN 242 37#define OP_31_XOP_MTSRIN 242
38#define OP_31_XOP_TLBIEL 274 38#define OP_31_XOP_TLBIEL 274
39#define OP_31_XOP_TLBIE 306
40/* Opcode is officially reserved, reuse it as sc 1 when sc 1 doesn't trap */ 39/* Opcode is officially reserved, reuse it as sc 1 when sc 1 doesn't trap */
41#define OP_31_XOP_FAKE_SC1 308 40#define OP_31_XOP_FAKE_SC1 308
42#define OP_31_XOP_SLBMTE 402 41#define OP_31_XOP_SLBMTE 402
@@ -110,7 +109,7 @@ static inline void kvmppc_copyto_vcpu_tm(struct kvm_vcpu *vcpu)
110 vcpu->arch.ctr_tm = vcpu->arch.regs.ctr; 109 vcpu->arch.ctr_tm = vcpu->arch.regs.ctr;
111 vcpu->arch.tar_tm = vcpu->arch.tar; 110 vcpu->arch.tar_tm = vcpu->arch.tar;
112 vcpu->arch.lr_tm = vcpu->arch.regs.link; 111 vcpu->arch.lr_tm = vcpu->arch.regs.link;
113 vcpu->arch.cr_tm = vcpu->arch.cr; 112 vcpu->arch.cr_tm = vcpu->arch.regs.ccr;
114 vcpu->arch.xer_tm = vcpu->arch.regs.xer; 113 vcpu->arch.xer_tm = vcpu->arch.regs.xer;
115 vcpu->arch.vrsave_tm = vcpu->arch.vrsave; 114 vcpu->arch.vrsave_tm = vcpu->arch.vrsave;
116} 115}
@@ -129,7 +128,7 @@ static inline void kvmppc_copyfrom_vcpu_tm(struct kvm_vcpu *vcpu)
129 vcpu->arch.regs.ctr = vcpu->arch.ctr_tm; 128 vcpu->arch.regs.ctr = vcpu->arch.ctr_tm;
130 vcpu->arch.tar = vcpu->arch.tar_tm; 129 vcpu->arch.tar = vcpu->arch.tar_tm;
131 vcpu->arch.regs.link = vcpu->arch.lr_tm; 130 vcpu->arch.regs.link = vcpu->arch.lr_tm;
132 vcpu->arch.cr = vcpu->arch.cr_tm; 131 vcpu->arch.regs.ccr = vcpu->arch.cr_tm;
133 vcpu->arch.regs.xer = vcpu->arch.xer_tm; 132 vcpu->arch.regs.xer = vcpu->arch.xer_tm;
134 vcpu->arch.vrsave = vcpu->arch.vrsave_tm; 133 vcpu->arch.vrsave = vcpu->arch.vrsave_tm;
135} 134}
@@ -141,7 +140,7 @@ static void kvmppc_emulate_treclaim(struct kvm_vcpu *vcpu, int ra_val)
141 uint64_t texasr; 140 uint64_t texasr;
142 141
143 /* CR0 = 0 | MSR[TS] | 0 */ 142 /* CR0 = 0 | MSR[TS] | 0 */
144 vcpu->arch.cr = (vcpu->arch.cr & ~(CR0_MASK << CR0_SHIFT)) | 143 vcpu->arch.regs.ccr = (vcpu->arch.regs.ccr & ~(CR0_MASK << CR0_SHIFT)) |
145 (((guest_msr & MSR_TS_MASK) >> (MSR_TS_S_LG - 1)) 144 (((guest_msr & MSR_TS_MASK) >> (MSR_TS_S_LG - 1))
146 << CR0_SHIFT); 145 << CR0_SHIFT);
147 146
@@ -220,7 +219,7 @@ void kvmppc_emulate_tabort(struct kvm_vcpu *vcpu, int ra_val)
220 tm_abort(ra_val); 219 tm_abort(ra_val);
221 220
222 /* CR0 = 0 | MSR[TS] | 0 */ 221 /* CR0 = 0 | MSR[TS] | 0 */
223 vcpu->arch.cr = (vcpu->arch.cr & ~(CR0_MASK << CR0_SHIFT)) | 222 vcpu->arch.regs.ccr = (vcpu->arch.regs.ccr & ~(CR0_MASK << CR0_SHIFT)) |
224 (((guest_msr & MSR_TS_MASK) >> (MSR_TS_S_LG - 1)) 223 (((guest_msr & MSR_TS_MASK) >> (MSR_TS_S_LG - 1))
225 << CR0_SHIFT); 224 << CR0_SHIFT);
226 225
@@ -494,8 +493,8 @@ int kvmppc_core_emulate_op_pr(struct kvm_run *run, struct kvm_vcpu *vcpu,
494 493
495 if (!(kvmppc_get_msr(vcpu) & MSR_PR)) { 494 if (!(kvmppc_get_msr(vcpu) & MSR_PR)) {
496 preempt_disable(); 495 preempt_disable();
497 vcpu->arch.cr = (CR0_TBEGIN_FAILURE | 496 vcpu->arch.regs.ccr = (CR0_TBEGIN_FAILURE |
498 (vcpu->arch.cr & ~(CR0_MASK << CR0_SHIFT))); 497 (vcpu->arch.regs.ccr & ~(CR0_MASK << CR0_SHIFT)));
499 498
500 vcpu->arch.texasr = (TEXASR_FS | TEXASR_EXACT | 499 vcpu->arch.texasr = (TEXASR_FS | TEXASR_EXACT |
501 (((u64)(TM_CAUSE_EMULATE | TM_CAUSE_PERSISTENT)) 500 (((u64)(TM_CAUSE_EMULATE | TM_CAUSE_PERSISTENT))
diff --git a/arch/powerpc/kvm/book3s_hv.c b/arch/powerpc/kvm/book3s_hv.c
index 3e3a71594e63..bf8def2159c3 100644
--- a/arch/powerpc/kvm/book3s_hv.c
+++ b/arch/powerpc/kvm/book3s_hv.c
@@ -50,6 +50,7 @@
50#include <asm/reg.h> 50#include <asm/reg.h>
51#include <asm/ppc-opcode.h> 51#include <asm/ppc-opcode.h>
52#include <asm/asm-prototypes.h> 52#include <asm/asm-prototypes.h>
53#include <asm/archrandom.h>
53#include <asm/debug.h> 54#include <asm/debug.h>
54#include <asm/disassemble.h> 55#include <asm/disassemble.h>
55#include <asm/cputable.h> 56#include <asm/cputable.h>
@@ -104,6 +105,10 @@ static bool indep_threads_mode = true;
104module_param(indep_threads_mode, bool, S_IRUGO | S_IWUSR); 105module_param(indep_threads_mode, bool, S_IRUGO | S_IWUSR);
105MODULE_PARM_DESC(indep_threads_mode, "Independent-threads mode (only on POWER9)"); 106MODULE_PARM_DESC(indep_threads_mode, "Independent-threads mode (only on POWER9)");
106 107
108static bool one_vm_per_core;
109module_param(one_vm_per_core, bool, S_IRUGO | S_IWUSR);
110MODULE_PARM_DESC(one_vm_per_core, "Only run vCPUs from the same VM on a core (requires indep_threads_mode=N)");
111
107#ifdef CONFIG_KVM_XICS 112#ifdef CONFIG_KVM_XICS
108static struct kernel_param_ops module_param_ops = { 113static struct kernel_param_ops module_param_ops = {
109 .set = param_set_int, 114 .set = param_set_int,
@@ -117,6 +122,16 @@ module_param_cb(h_ipi_redirect, &module_param_ops, &h_ipi_redirect, 0644);
117MODULE_PARM_DESC(h_ipi_redirect, "Redirect H_IPI wakeup to a free host core"); 122MODULE_PARM_DESC(h_ipi_redirect, "Redirect H_IPI wakeup to a free host core");
118#endif 123#endif
119 124
125/* If set, guests are allowed to create and control nested guests */
126static bool nested = true;
127module_param(nested, bool, S_IRUGO | S_IWUSR);
128MODULE_PARM_DESC(nested, "Enable nested virtualization (only on POWER9)");
129
130static inline bool nesting_enabled(struct kvm *kvm)
131{
132 return kvm->arch.nested_enable && kvm_is_radix(kvm);
133}
134
120/* If set, the threads on each CPU core have to be in the same MMU mode */ 135/* If set, the threads on each CPU core have to be in the same MMU mode */
121static bool no_mixing_hpt_and_radix; 136static bool no_mixing_hpt_and_radix;
122 137
@@ -173,6 +188,10 @@ static bool kvmppc_ipi_thread(int cpu)
173{ 188{
174 unsigned long msg = PPC_DBELL_TYPE(PPC_DBELL_SERVER); 189 unsigned long msg = PPC_DBELL_TYPE(PPC_DBELL_SERVER);
175 190
191 /* If we're a nested hypervisor, fall back to ordinary IPIs for now */
192 if (kvmhv_on_pseries())
193 return false;
194
176 /* On POWER9 we can use msgsnd to IPI any cpu */ 195 /* On POWER9 we can use msgsnd to IPI any cpu */
177 if (cpu_has_feature(CPU_FTR_ARCH_300)) { 196 if (cpu_has_feature(CPU_FTR_ARCH_300)) {
178 msg |= get_hard_smp_processor_id(cpu); 197 msg |= get_hard_smp_processor_id(cpu);
@@ -410,8 +429,8 @@ static void kvmppc_dump_regs(struct kvm_vcpu *vcpu)
410 vcpu->arch.shregs.sprg0, vcpu->arch.shregs.sprg1); 429 vcpu->arch.shregs.sprg0, vcpu->arch.shregs.sprg1);
411 pr_err("sprg2 = %.16llx sprg3 = %.16llx\n", 430 pr_err("sprg2 = %.16llx sprg3 = %.16llx\n",
412 vcpu->arch.shregs.sprg2, vcpu->arch.shregs.sprg3); 431 vcpu->arch.shregs.sprg2, vcpu->arch.shregs.sprg3);
413 pr_err("cr = %.8x xer = %.16lx dsisr = %.8x\n", 432 pr_err("cr = %.8lx xer = %.16lx dsisr = %.8x\n",
414 vcpu->arch.cr, vcpu->arch.regs.xer, vcpu->arch.shregs.dsisr); 433 vcpu->arch.regs.ccr, vcpu->arch.regs.xer, vcpu->arch.shregs.dsisr);
415 pr_err("dar = %.16llx\n", vcpu->arch.shregs.dar); 434 pr_err("dar = %.16llx\n", vcpu->arch.shregs.dar);
416 pr_err("fault dar = %.16lx dsisr = %.8x\n", 435 pr_err("fault dar = %.16lx dsisr = %.8x\n",
417 vcpu->arch.fault_dar, vcpu->arch.fault_dsisr); 436 vcpu->arch.fault_dar, vcpu->arch.fault_dsisr);
@@ -730,8 +749,7 @@ static bool kvmppc_doorbell_pending(struct kvm_vcpu *vcpu)
730 /* 749 /*
731 * Ensure that the read of vcore->dpdes comes after the read 750 * Ensure that the read of vcore->dpdes comes after the read
732 * of vcpu->doorbell_request. This barrier matches the 751 * of vcpu->doorbell_request. This barrier matches the
733 * lwsync in book3s_hv_rmhandlers.S just before the 752 * smb_wmb() in kvmppc_guest_entry_inject().
734 * fast_guest_return label.
735 */ 753 */
736 smp_rmb(); 754 smp_rmb();
737 vc = vcpu->arch.vcore; 755 vc = vcpu->arch.vcore;
@@ -912,6 +930,19 @@ int kvmppc_pseries_do_hcall(struct kvm_vcpu *vcpu)
912 break; 930 break;
913 } 931 }
914 return RESUME_HOST; 932 return RESUME_HOST;
933 case H_SET_DABR:
934 ret = kvmppc_h_set_dabr(vcpu, kvmppc_get_gpr(vcpu, 4));
935 break;
936 case H_SET_XDABR:
937 ret = kvmppc_h_set_xdabr(vcpu, kvmppc_get_gpr(vcpu, 4),
938 kvmppc_get_gpr(vcpu, 5));
939 break;
940 case H_GET_TCE:
941 ret = kvmppc_h_get_tce(vcpu, kvmppc_get_gpr(vcpu, 4),
942 kvmppc_get_gpr(vcpu, 5));
943 if (ret == H_TOO_HARD)
944 return RESUME_HOST;
945 break;
915 case H_PUT_TCE: 946 case H_PUT_TCE:
916 ret = kvmppc_h_put_tce(vcpu, kvmppc_get_gpr(vcpu, 4), 947 ret = kvmppc_h_put_tce(vcpu, kvmppc_get_gpr(vcpu, 4),
917 kvmppc_get_gpr(vcpu, 5), 948 kvmppc_get_gpr(vcpu, 5),
@@ -935,6 +966,32 @@ int kvmppc_pseries_do_hcall(struct kvm_vcpu *vcpu)
935 if (ret == H_TOO_HARD) 966 if (ret == H_TOO_HARD)
936 return RESUME_HOST; 967 return RESUME_HOST;
937 break; 968 break;
969 case H_RANDOM:
970 if (!powernv_get_random_long(&vcpu->arch.regs.gpr[4]))
971 ret = H_HARDWARE;
972 break;
973
974 case H_SET_PARTITION_TABLE:
975 ret = H_FUNCTION;
976 if (nesting_enabled(vcpu->kvm))
977 ret = kvmhv_set_partition_table(vcpu);
978 break;
979 case H_ENTER_NESTED:
980 ret = H_FUNCTION;
981 if (!nesting_enabled(vcpu->kvm))
982 break;
983 ret = kvmhv_enter_nested_guest(vcpu);
984 if (ret == H_INTERRUPT) {
985 kvmppc_set_gpr(vcpu, 3, 0);
986 return -EINTR;
987 }
988 break;
989 case H_TLB_INVALIDATE:
990 ret = H_FUNCTION;
991 if (nesting_enabled(vcpu->kvm))
992 ret = kvmhv_do_nested_tlbie(vcpu);
993 break;
994
938 default: 995 default:
939 return RESUME_HOST; 996 return RESUME_HOST;
940 } 997 }
@@ -943,6 +1000,24 @@ int kvmppc_pseries_do_hcall(struct kvm_vcpu *vcpu)
943 return RESUME_GUEST; 1000 return RESUME_GUEST;
944} 1001}
945 1002
1003/*
1004 * Handle H_CEDE in the nested virtualization case where we haven't
1005 * called the real-mode hcall handlers in book3s_hv_rmhandlers.S.
1006 * This has to be done early, not in kvmppc_pseries_do_hcall(), so
1007 * that the cede logic in kvmppc_run_single_vcpu() works properly.
1008 */
1009static void kvmppc_nested_cede(struct kvm_vcpu *vcpu)
1010{
1011 vcpu->arch.shregs.msr |= MSR_EE;
1012 vcpu->arch.ceded = 1;
1013 smp_mb();
1014 if (vcpu->arch.prodded) {
1015 vcpu->arch.prodded = 0;
1016 smp_mb();
1017 vcpu->arch.ceded = 0;
1018 }
1019}
1020
946static int kvmppc_hcall_impl_hv(unsigned long cmd) 1021static int kvmppc_hcall_impl_hv(unsigned long cmd)
947{ 1022{
948 switch (cmd) { 1023 switch (cmd) {
@@ -1085,7 +1160,6 @@ static int kvmppc_emulate_doorbell_instr(struct kvm_vcpu *vcpu)
1085 return RESUME_GUEST; 1160 return RESUME_GUEST;
1086} 1161}
1087 1162
1088/* Called with vcpu->arch.vcore->lock held */
1089static int kvmppc_handle_exit_hv(struct kvm_run *run, struct kvm_vcpu *vcpu, 1163static int kvmppc_handle_exit_hv(struct kvm_run *run, struct kvm_vcpu *vcpu,
1090 struct task_struct *tsk) 1164 struct task_struct *tsk)
1091{ 1165{
@@ -1190,7 +1264,10 @@ static int kvmppc_handle_exit_hv(struct kvm_run *run, struct kvm_vcpu *vcpu,
1190 break; 1264 break;
1191 case BOOK3S_INTERRUPT_H_INST_STORAGE: 1265 case BOOK3S_INTERRUPT_H_INST_STORAGE:
1192 vcpu->arch.fault_dar = kvmppc_get_pc(vcpu); 1266 vcpu->arch.fault_dar = kvmppc_get_pc(vcpu);
1193 vcpu->arch.fault_dsisr = 0; 1267 vcpu->arch.fault_dsisr = vcpu->arch.shregs.msr &
1268 DSISR_SRR1_MATCH_64S;
1269 if (vcpu->arch.shregs.msr & HSRR1_HISI_WRITE)
1270 vcpu->arch.fault_dsisr |= DSISR_ISSTORE;
1194 r = RESUME_PAGE_FAULT; 1271 r = RESUME_PAGE_FAULT;
1195 break; 1272 break;
1196 /* 1273 /*
@@ -1206,10 +1283,7 @@ static int kvmppc_handle_exit_hv(struct kvm_run *run, struct kvm_vcpu *vcpu,
1206 swab32(vcpu->arch.emul_inst) : 1283 swab32(vcpu->arch.emul_inst) :
1207 vcpu->arch.emul_inst; 1284 vcpu->arch.emul_inst;
1208 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP) { 1285 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP) {
1209 /* Need vcore unlocked to call kvmppc_get_last_inst */
1210 spin_unlock(&vcpu->arch.vcore->lock);
1211 r = kvmppc_emulate_debug_inst(run, vcpu); 1286 r = kvmppc_emulate_debug_inst(run, vcpu);
1212 spin_lock(&vcpu->arch.vcore->lock);
1213 } else { 1287 } else {
1214 kvmppc_core_queue_program(vcpu, SRR1_PROGILL); 1288 kvmppc_core_queue_program(vcpu, SRR1_PROGILL);
1215 r = RESUME_GUEST; 1289 r = RESUME_GUEST;
@@ -1225,12 +1299,8 @@ static int kvmppc_handle_exit_hv(struct kvm_run *run, struct kvm_vcpu *vcpu,
1225 case BOOK3S_INTERRUPT_H_FAC_UNAVAIL: 1299 case BOOK3S_INTERRUPT_H_FAC_UNAVAIL:
1226 r = EMULATE_FAIL; 1300 r = EMULATE_FAIL;
1227 if (((vcpu->arch.hfscr >> 56) == FSCR_MSGP_LG) && 1301 if (((vcpu->arch.hfscr >> 56) == FSCR_MSGP_LG) &&
1228 cpu_has_feature(CPU_FTR_ARCH_300)) { 1302 cpu_has_feature(CPU_FTR_ARCH_300))
1229 /* Need vcore unlocked to call kvmppc_get_last_inst */
1230 spin_unlock(&vcpu->arch.vcore->lock);
1231 r = kvmppc_emulate_doorbell_instr(vcpu); 1303 r = kvmppc_emulate_doorbell_instr(vcpu);
1232 spin_lock(&vcpu->arch.vcore->lock);
1233 }
1234 if (r == EMULATE_FAIL) { 1304 if (r == EMULATE_FAIL) {
1235 kvmppc_core_queue_program(vcpu, SRR1_PROGILL); 1305 kvmppc_core_queue_program(vcpu, SRR1_PROGILL);
1236 r = RESUME_GUEST; 1306 r = RESUME_GUEST;
@@ -1265,6 +1335,104 @@ static int kvmppc_handle_exit_hv(struct kvm_run *run, struct kvm_vcpu *vcpu,
1265 return r; 1335 return r;
1266} 1336}
1267 1337
1338static int kvmppc_handle_nested_exit(struct kvm_vcpu *vcpu)
1339{
1340 int r;
1341 int srcu_idx;
1342
1343 vcpu->stat.sum_exits++;
1344
1345 /*
1346 * This can happen if an interrupt occurs in the last stages
1347 * of guest entry or the first stages of guest exit (i.e. after
1348 * setting paca->kvm_hstate.in_guest to KVM_GUEST_MODE_GUEST_HV
1349 * and before setting it to KVM_GUEST_MODE_HOST_HV).
1350 * That can happen due to a bug, or due to a machine check
1351 * occurring at just the wrong time.
1352 */
1353 if (vcpu->arch.shregs.msr & MSR_HV) {
1354 pr_emerg("KVM trap in HV mode while nested!\n");
1355 pr_emerg("trap=0x%x | pc=0x%lx | msr=0x%llx\n",
1356 vcpu->arch.trap, kvmppc_get_pc(vcpu),
1357 vcpu->arch.shregs.msr);
1358 kvmppc_dump_regs(vcpu);
1359 return RESUME_HOST;
1360 }
1361 switch (vcpu->arch.trap) {
1362 /* We're good on these - the host merely wanted to get our attention */
1363 case BOOK3S_INTERRUPT_HV_DECREMENTER:
1364 vcpu->stat.dec_exits++;
1365 r = RESUME_GUEST;
1366 break;
1367 case BOOK3S_INTERRUPT_EXTERNAL:
1368 vcpu->stat.ext_intr_exits++;
1369 r = RESUME_HOST;
1370 break;
1371 case BOOK3S_INTERRUPT_H_DOORBELL:
1372 case BOOK3S_INTERRUPT_H_VIRT:
1373 vcpu->stat.ext_intr_exits++;
1374 r = RESUME_GUEST;
1375 break;
1376 /* SR/HMI/PMI are HV interrupts that host has handled. Resume guest.*/
1377 case BOOK3S_INTERRUPT_HMI:
1378 case BOOK3S_INTERRUPT_PERFMON:
1379 case BOOK3S_INTERRUPT_SYSTEM_RESET:
1380 r = RESUME_GUEST;
1381 break;
1382 case BOOK3S_INTERRUPT_MACHINE_CHECK:
1383 /* Pass the machine check to the L1 guest */
1384 r = RESUME_HOST;
1385 /* Print the MCE event to host console. */
1386 machine_check_print_event_info(&vcpu->arch.mce_evt, false);
1387 break;
1388 /*
1389 * We get these next two if the guest accesses a page which it thinks
1390 * it has mapped but which is not actually present, either because
1391 * it is for an emulated I/O device or because the corresonding
1392 * host page has been paged out.
1393 */
1394 case BOOK3S_INTERRUPT_H_DATA_STORAGE:
1395 srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
1396 r = kvmhv_nested_page_fault(vcpu);
1397 srcu_read_unlock(&vcpu->kvm->srcu, srcu_idx);
1398 break;
1399 case BOOK3S_INTERRUPT_H_INST_STORAGE:
1400 vcpu->arch.fault_dar = kvmppc_get_pc(vcpu);
1401 vcpu->arch.fault_dsisr = kvmppc_get_msr(vcpu) &
1402 DSISR_SRR1_MATCH_64S;
1403 if (vcpu->arch.shregs.msr & HSRR1_HISI_WRITE)
1404 vcpu->arch.fault_dsisr |= DSISR_ISSTORE;
1405 srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
1406 r = kvmhv_nested_page_fault(vcpu);
1407 srcu_read_unlock(&vcpu->kvm->srcu, srcu_idx);
1408 break;
1409
1410#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
1411 case BOOK3S_INTERRUPT_HV_SOFTPATCH:
1412 /*
1413 * This occurs for various TM-related instructions that
1414 * we need to emulate on POWER9 DD2.2. We have already
1415 * handled the cases where the guest was in real-suspend
1416 * mode and was transitioning to transactional state.
1417 */
1418 r = kvmhv_p9_tm_emulation(vcpu);
1419 break;
1420#endif
1421
1422 case BOOK3S_INTERRUPT_HV_RM_HARD:
1423 vcpu->arch.trap = 0;
1424 r = RESUME_GUEST;
1425 if (!xive_enabled())
1426 kvmppc_xics_rm_complete(vcpu, 0);
1427 break;
1428 default:
1429 r = RESUME_HOST;
1430 break;
1431 }
1432
1433 return r;
1434}
1435
1268static int kvm_arch_vcpu_ioctl_get_sregs_hv(struct kvm_vcpu *vcpu, 1436static int kvm_arch_vcpu_ioctl_get_sregs_hv(struct kvm_vcpu *vcpu,
1269 struct kvm_sregs *sregs) 1437 struct kvm_sregs *sregs)
1270{ 1438{
@@ -1555,6 +1723,9 @@ static int kvmppc_get_one_reg_hv(struct kvm_vcpu *vcpu, u64 id,
1555 case KVM_REG_PPC_ONLINE: 1723 case KVM_REG_PPC_ONLINE:
1556 *val = get_reg_val(id, vcpu->arch.online); 1724 *val = get_reg_val(id, vcpu->arch.online);
1557 break; 1725 break;
1726 case KVM_REG_PPC_PTCR:
1727 *val = get_reg_val(id, vcpu->kvm->arch.l1_ptcr);
1728 break;
1558 default: 1729 default:
1559 r = -EINVAL; 1730 r = -EINVAL;
1560 break; 1731 break;
@@ -1786,6 +1957,9 @@ static int kvmppc_set_one_reg_hv(struct kvm_vcpu *vcpu, u64 id,
1786 atomic_dec(&vcpu->arch.vcore->online_count); 1957 atomic_dec(&vcpu->arch.vcore->online_count);
1787 vcpu->arch.online = i; 1958 vcpu->arch.online = i;
1788 break; 1959 break;
1960 case KVM_REG_PPC_PTCR:
1961 vcpu->kvm->arch.l1_ptcr = set_reg_val(id, *val);
1962 break;
1789 default: 1963 default:
1790 r = -EINVAL; 1964 r = -EINVAL;
1791 break; 1965 break;
@@ -2019,15 +2193,18 @@ static struct kvm_vcpu *kvmppc_core_vcpu_create_hv(struct kvm *kvm,
2019 * Set the default HFSCR for the guest from the host value. 2193 * Set the default HFSCR for the guest from the host value.
2020 * This value is only used on POWER9. 2194 * This value is only used on POWER9.
2021 * On POWER9, we want to virtualize the doorbell facility, so we 2195 * On POWER9, we want to virtualize the doorbell facility, so we
2022 * turn off the HFSCR bit, which causes those instructions to trap. 2196 * don't set the HFSCR_MSGP bit, and that causes those instructions
2197 * to trap and then we emulate them.
2023 */ 2198 */
2024 vcpu->arch.hfscr = mfspr(SPRN_HFSCR); 2199 vcpu->arch.hfscr = HFSCR_TAR | HFSCR_EBB | HFSCR_PM | HFSCR_BHRB |
2025 if (cpu_has_feature(CPU_FTR_P9_TM_HV_ASSIST)) 2200 HFSCR_DSCR | HFSCR_VECVSX | HFSCR_FP;
2201 if (cpu_has_feature(CPU_FTR_HVMODE)) {
2202 vcpu->arch.hfscr &= mfspr(SPRN_HFSCR);
2203 if (cpu_has_feature(CPU_FTR_P9_TM_HV_ASSIST))
2204 vcpu->arch.hfscr |= HFSCR_TM;
2205 }
2206 if (cpu_has_feature(CPU_FTR_TM_COMP))
2026 vcpu->arch.hfscr |= HFSCR_TM; 2207 vcpu->arch.hfscr |= HFSCR_TM;
2027 else if (!cpu_has_feature(CPU_FTR_TM_COMP))
2028 vcpu->arch.hfscr &= ~HFSCR_TM;
2029 if (cpu_has_feature(CPU_FTR_ARCH_300))
2030 vcpu->arch.hfscr &= ~HFSCR_MSGP;
2031 2208
2032 kvmppc_mmu_book3s_hv_init(vcpu); 2209 kvmppc_mmu_book3s_hv_init(vcpu);
2033 2210
@@ -2242,10 +2419,18 @@ static void kvmppc_release_hwthread(int cpu)
2242 2419
2243static void radix_flush_cpu(struct kvm *kvm, int cpu, struct kvm_vcpu *vcpu) 2420static void radix_flush_cpu(struct kvm *kvm, int cpu, struct kvm_vcpu *vcpu)
2244{ 2421{
2422 struct kvm_nested_guest *nested = vcpu->arch.nested;
2423 cpumask_t *cpu_in_guest;
2245 int i; 2424 int i;
2246 2425
2247 cpu = cpu_first_thread_sibling(cpu); 2426 cpu = cpu_first_thread_sibling(cpu);
2248 cpumask_set_cpu(cpu, &kvm->arch.need_tlb_flush); 2427 if (nested) {
2428 cpumask_set_cpu(cpu, &nested->need_tlb_flush);
2429 cpu_in_guest = &nested->cpu_in_guest;
2430 } else {
2431 cpumask_set_cpu(cpu, &kvm->arch.need_tlb_flush);
2432 cpu_in_guest = &kvm->arch.cpu_in_guest;
2433 }
2249 /* 2434 /*
2250 * Make sure setting of bit in need_tlb_flush precedes 2435 * Make sure setting of bit in need_tlb_flush precedes
2251 * testing of cpu_in_guest bits. The matching barrier on 2436 * testing of cpu_in_guest bits. The matching barrier on
@@ -2253,13 +2438,23 @@ static void radix_flush_cpu(struct kvm *kvm, int cpu, struct kvm_vcpu *vcpu)
2253 */ 2438 */
2254 smp_mb(); 2439 smp_mb();
2255 for (i = 0; i < threads_per_core; ++i) 2440 for (i = 0; i < threads_per_core; ++i)
2256 if (cpumask_test_cpu(cpu + i, &kvm->arch.cpu_in_guest)) 2441 if (cpumask_test_cpu(cpu + i, cpu_in_guest))
2257 smp_call_function_single(cpu + i, do_nothing, NULL, 1); 2442 smp_call_function_single(cpu + i, do_nothing, NULL, 1);
2258} 2443}
2259 2444
2260static void kvmppc_prepare_radix_vcpu(struct kvm_vcpu *vcpu, int pcpu) 2445static void kvmppc_prepare_radix_vcpu(struct kvm_vcpu *vcpu, int pcpu)
2261{ 2446{
2447 struct kvm_nested_guest *nested = vcpu->arch.nested;
2262 struct kvm *kvm = vcpu->kvm; 2448 struct kvm *kvm = vcpu->kvm;
2449 int prev_cpu;
2450
2451 if (!cpu_has_feature(CPU_FTR_HVMODE))
2452 return;
2453
2454 if (nested)
2455 prev_cpu = nested->prev_cpu[vcpu->arch.nested_vcpu_id];
2456 else
2457 prev_cpu = vcpu->arch.prev_cpu;
2263 2458
2264 /* 2459 /*
2265 * With radix, the guest can do TLB invalidations itself, 2460 * With radix, the guest can do TLB invalidations itself,
@@ -2273,12 +2468,46 @@ static void kvmppc_prepare_radix_vcpu(struct kvm_vcpu *vcpu, int pcpu)
2273 * ran to flush the TLB. The TLB is shared between threads, 2468 * ran to flush the TLB. The TLB is shared between threads,
2274 * so we use a single bit in .need_tlb_flush for all 4 threads. 2469 * so we use a single bit in .need_tlb_flush for all 4 threads.
2275 */ 2470 */
2276 if (vcpu->arch.prev_cpu != pcpu) { 2471 if (prev_cpu != pcpu) {
2277 if (vcpu->arch.prev_cpu >= 0 && 2472 if (prev_cpu >= 0 &&
2278 cpu_first_thread_sibling(vcpu->arch.prev_cpu) != 2473 cpu_first_thread_sibling(prev_cpu) !=
2279 cpu_first_thread_sibling(pcpu)) 2474 cpu_first_thread_sibling(pcpu))
2280 radix_flush_cpu(kvm, vcpu->arch.prev_cpu, vcpu); 2475 radix_flush_cpu(kvm, prev_cpu, vcpu);
2281 vcpu->arch.prev_cpu = pcpu; 2476 if (nested)
2477 nested->prev_cpu[vcpu->arch.nested_vcpu_id] = pcpu;
2478 else
2479 vcpu->arch.prev_cpu = pcpu;
2480 }
2481}
2482
2483static void kvmppc_radix_check_need_tlb_flush(struct kvm *kvm, int pcpu,
2484 struct kvm_nested_guest *nested)
2485{
2486 cpumask_t *need_tlb_flush;
2487 int lpid;
2488
2489 if (!cpu_has_feature(CPU_FTR_HVMODE))
2490 return;
2491
2492 if (cpu_has_feature(CPU_FTR_ARCH_300))
2493 pcpu &= ~0x3UL;
2494
2495 if (nested) {
2496 lpid = nested->shadow_lpid;
2497 need_tlb_flush = &nested->need_tlb_flush;
2498 } else {
2499 lpid = kvm->arch.lpid;
2500 need_tlb_flush = &kvm->arch.need_tlb_flush;
2501 }
2502
2503 mtspr(SPRN_LPID, lpid);
2504 isync();
2505 smp_mb();
2506
2507 if (cpumask_test_cpu(pcpu, need_tlb_flush)) {
2508 radix__local_flush_tlb_lpid_guest(lpid);
2509 /* Clear the bit after the TLB flush */
2510 cpumask_clear_cpu(pcpu, need_tlb_flush);
2282 } 2511 }
2283} 2512}
2284 2513
@@ -2493,6 +2722,10 @@ static bool can_dynamic_split(struct kvmppc_vcore *vc, struct core_info *cip)
2493 if (!cpu_has_feature(CPU_FTR_ARCH_207S)) 2722 if (!cpu_has_feature(CPU_FTR_ARCH_207S))
2494 return false; 2723 return false;
2495 2724
2725 /* In one_vm_per_core mode, require all vcores to be from the same vm */
2726 if (one_vm_per_core && vc->kvm != cip->vc[0]->kvm)
2727 return false;
2728
2496 /* Some POWER9 chips require all threads to be in the same MMU mode */ 2729 /* Some POWER9 chips require all threads to be in the same MMU mode */
2497 if (no_mixing_hpt_and_radix && 2730 if (no_mixing_hpt_and_radix &&
2498 kvm_is_radix(vc->kvm) != kvm_is_radix(cip->vc[0]->kvm)) 2731 kvm_is_radix(vc->kvm) != kvm_is_radix(cip->vc[0]->kvm))
@@ -2600,6 +2833,14 @@ static void post_guest_process(struct kvmppc_vcore *vc, bool is_master)
2600 spin_lock(&vc->lock); 2833 spin_lock(&vc->lock);
2601 now = get_tb(); 2834 now = get_tb();
2602 for_each_runnable_thread(i, vcpu, vc) { 2835 for_each_runnable_thread(i, vcpu, vc) {
2836 /*
2837 * It's safe to unlock the vcore in the loop here, because
2838 * for_each_runnable_thread() is safe against removal of
2839 * the vcpu, and the vcore state is VCORE_EXITING here,
2840 * so any vcpus becoming runnable will have their arch.trap
2841 * set to zero and can't actually run in the guest.
2842 */
2843 spin_unlock(&vc->lock);
2603 /* cancel pending dec exception if dec is positive */ 2844 /* cancel pending dec exception if dec is positive */
2604 if (now < vcpu->arch.dec_expires && 2845 if (now < vcpu->arch.dec_expires &&
2605 kvmppc_core_pending_dec(vcpu)) 2846 kvmppc_core_pending_dec(vcpu))
@@ -2615,6 +2856,7 @@ static void post_guest_process(struct kvmppc_vcore *vc, bool is_master)
2615 vcpu->arch.ret = ret; 2856 vcpu->arch.ret = ret;
2616 vcpu->arch.trap = 0; 2857 vcpu->arch.trap = 0;
2617 2858
2859 spin_lock(&vc->lock);
2618 if (is_kvmppc_resume_guest(vcpu->arch.ret)) { 2860 if (is_kvmppc_resume_guest(vcpu->arch.ret)) {
2619 if (vcpu->arch.pending_exceptions) 2861 if (vcpu->arch.pending_exceptions)
2620 kvmppc_core_prepare_to_enter(vcpu); 2862 kvmppc_core_prepare_to_enter(vcpu);
@@ -2963,8 +3205,6 @@ static noinline void kvmppc_run_core(struct kvmppc_vcore *vc)
2963 spin_unlock(&core_info.vc[sub]->lock); 3205 spin_unlock(&core_info.vc[sub]->lock);
2964 3206
2965 if (kvm_is_radix(vc->kvm)) { 3207 if (kvm_is_radix(vc->kvm)) {
2966 int tmp = pcpu;
2967
2968 /* 3208 /*
2969 * Do we need to flush the process scoped TLB for the LPAR? 3209 * Do we need to flush the process scoped TLB for the LPAR?
2970 * 3210 *
@@ -2975,17 +3215,7 @@ static noinline void kvmppc_run_core(struct kvmppc_vcore *vc)
2975 * 3215 *
2976 * Hash must be flushed in realmode in order to use tlbiel. 3216 * Hash must be flushed in realmode in order to use tlbiel.
2977 */ 3217 */
2978 mtspr(SPRN_LPID, vc->kvm->arch.lpid); 3218 kvmppc_radix_check_need_tlb_flush(vc->kvm, pcpu, NULL);
2979 isync();
2980
2981 if (cpu_has_feature(CPU_FTR_ARCH_300))
2982 tmp &= ~0x3UL;
2983
2984 if (cpumask_test_cpu(tmp, &vc->kvm->arch.need_tlb_flush)) {
2985 radix__local_flush_tlb_lpid_guest(vc->kvm->arch.lpid);
2986 /* Clear the bit after the TLB flush */
2987 cpumask_clear_cpu(tmp, &vc->kvm->arch.need_tlb_flush);
2988 }
2989 } 3219 }
2990 3220
2991 /* 3221 /*
@@ -3080,6 +3310,300 @@ static noinline void kvmppc_run_core(struct kvmppc_vcore *vc)
3080} 3310}
3081 3311
3082/* 3312/*
3313 * Load up hypervisor-mode registers on P9.
3314 */
3315static int kvmhv_load_hv_regs_and_go(struct kvm_vcpu *vcpu, u64 time_limit,
3316 unsigned long lpcr)
3317{
3318 struct kvmppc_vcore *vc = vcpu->arch.vcore;
3319 s64 hdec;
3320 u64 tb, purr, spurr;
3321 int trap;
3322 unsigned long host_hfscr = mfspr(SPRN_HFSCR);
3323 unsigned long host_ciabr = mfspr(SPRN_CIABR);
3324 unsigned long host_dawr = mfspr(SPRN_DAWR);
3325 unsigned long host_dawrx = mfspr(SPRN_DAWRX);
3326 unsigned long host_psscr = mfspr(SPRN_PSSCR);
3327 unsigned long host_pidr = mfspr(SPRN_PID);
3328
3329 hdec = time_limit - mftb();
3330 if (hdec < 0)
3331 return BOOK3S_INTERRUPT_HV_DECREMENTER;
3332 mtspr(SPRN_HDEC, hdec);
3333
3334 if (vc->tb_offset) {
3335 u64 new_tb = mftb() + vc->tb_offset;
3336 mtspr(SPRN_TBU40, new_tb);
3337 tb = mftb();
3338 if ((tb & 0xffffff) < (new_tb & 0xffffff))
3339 mtspr(SPRN_TBU40, new_tb + 0x1000000);
3340 vc->tb_offset_applied = vc->tb_offset;
3341 }
3342
3343 if (vc->pcr)
3344 mtspr(SPRN_PCR, vc->pcr);
3345 mtspr(SPRN_DPDES, vc->dpdes);
3346 mtspr(SPRN_VTB, vc->vtb);
3347
3348 local_paca->kvm_hstate.host_purr = mfspr(SPRN_PURR);
3349 local_paca->kvm_hstate.host_spurr = mfspr(SPRN_SPURR);
3350 mtspr(SPRN_PURR, vcpu->arch.purr);
3351 mtspr(SPRN_SPURR, vcpu->arch.spurr);
3352
3353 if (cpu_has_feature(CPU_FTR_DAWR)) {
3354 mtspr(SPRN_DAWR, vcpu->arch.dawr);
3355 mtspr(SPRN_DAWRX, vcpu->arch.dawrx);
3356 }
3357 mtspr(SPRN_CIABR, vcpu->arch.ciabr);
3358 mtspr(SPRN_IC, vcpu->arch.ic);
3359 mtspr(SPRN_PID, vcpu->arch.pid);
3360
3361 mtspr(SPRN_PSSCR, vcpu->arch.psscr | PSSCR_EC |
3362 (local_paca->kvm_hstate.fake_suspend << PSSCR_FAKE_SUSPEND_LG));
3363
3364 mtspr(SPRN_HFSCR, vcpu->arch.hfscr);
3365
3366 mtspr(SPRN_SPRG0, vcpu->arch.shregs.sprg0);
3367 mtspr(SPRN_SPRG1, vcpu->arch.shregs.sprg1);
3368 mtspr(SPRN_SPRG2, vcpu->arch.shregs.sprg2);
3369 mtspr(SPRN_SPRG3, vcpu->arch.shregs.sprg3);
3370
3371 mtspr(SPRN_AMOR, ~0UL);
3372
3373 mtspr(SPRN_LPCR, lpcr);
3374 isync();
3375
3376 kvmppc_xive_push_vcpu(vcpu);
3377
3378 mtspr(SPRN_SRR0, vcpu->arch.shregs.srr0);
3379 mtspr(SPRN_SRR1, vcpu->arch.shregs.srr1);
3380
3381 trap = __kvmhv_vcpu_entry_p9(vcpu);
3382
3383 /* Advance host PURR/SPURR by the amount used by guest */
3384 purr = mfspr(SPRN_PURR);
3385 spurr = mfspr(SPRN_SPURR);
3386 mtspr(SPRN_PURR, local_paca->kvm_hstate.host_purr +
3387 purr - vcpu->arch.purr);
3388 mtspr(SPRN_SPURR, local_paca->kvm_hstate.host_spurr +
3389 spurr - vcpu->arch.spurr);
3390 vcpu->arch.purr = purr;
3391 vcpu->arch.spurr = spurr;
3392
3393 vcpu->arch.ic = mfspr(SPRN_IC);
3394 vcpu->arch.pid = mfspr(SPRN_PID);
3395 vcpu->arch.psscr = mfspr(SPRN_PSSCR) & PSSCR_GUEST_VIS;
3396
3397 vcpu->arch.shregs.sprg0 = mfspr(SPRN_SPRG0);
3398 vcpu->arch.shregs.sprg1 = mfspr(SPRN_SPRG1);
3399 vcpu->arch.shregs.sprg2 = mfspr(SPRN_SPRG2);
3400 vcpu->arch.shregs.sprg3 = mfspr(SPRN_SPRG3);
3401
3402 mtspr(SPRN_PSSCR, host_psscr);
3403 mtspr(SPRN_HFSCR, host_hfscr);
3404 mtspr(SPRN_CIABR, host_ciabr);
3405 mtspr(SPRN_DAWR, host_dawr);
3406 mtspr(SPRN_DAWRX, host_dawrx);
3407 mtspr(SPRN_PID, host_pidr);
3408
3409 /*
3410 * Since this is radix, do a eieio; tlbsync; ptesync sequence in
3411 * case we interrupted the guest between a tlbie and a ptesync.
3412 */
3413 asm volatile("eieio; tlbsync; ptesync");
3414
3415 mtspr(SPRN_LPID, vcpu->kvm->arch.host_lpid); /* restore host LPID */
3416 isync();
3417
3418 vc->dpdes = mfspr(SPRN_DPDES);
3419 vc->vtb = mfspr(SPRN_VTB);
3420 mtspr(SPRN_DPDES, 0);
3421 if (vc->pcr)
3422 mtspr(SPRN_PCR, 0);
3423
3424 if (vc->tb_offset_applied) {
3425 u64 new_tb = mftb() - vc->tb_offset_applied;
3426 mtspr(SPRN_TBU40, new_tb);
3427 tb = mftb();
3428 if ((tb & 0xffffff) < (new_tb & 0xffffff))
3429 mtspr(SPRN_TBU40, new_tb + 0x1000000);
3430 vc->tb_offset_applied = 0;
3431 }
3432
3433 mtspr(SPRN_HDEC, 0x7fffffff);
3434 mtspr(SPRN_LPCR, vcpu->kvm->arch.host_lpcr);
3435
3436 return trap;
3437}
3438
3439/*
3440 * Virtual-mode guest entry for POWER9 and later when the host and
3441 * guest are both using the radix MMU. The LPIDR has already been set.
3442 */
3443int kvmhv_p9_guest_entry(struct kvm_vcpu *vcpu, u64 time_limit,
3444 unsigned long lpcr)
3445{
3446 struct kvmppc_vcore *vc = vcpu->arch.vcore;
3447 unsigned long host_dscr = mfspr(SPRN_DSCR);
3448 unsigned long host_tidr = mfspr(SPRN_TIDR);
3449 unsigned long host_iamr = mfspr(SPRN_IAMR);
3450 s64 dec;
3451 u64 tb;
3452 int trap, save_pmu;
3453
3454 dec = mfspr(SPRN_DEC);
3455 tb = mftb();
3456 if (dec < 512)
3457 return BOOK3S_INTERRUPT_HV_DECREMENTER;
3458 local_paca->kvm_hstate.dec_expires = dec + tb;
3459 if (local_paca->kvm_hstate.dec_expires < time_limit)
3460 time_limit = local_paca->kvm_hstate.dec_expires;
3461
3462 vcpu->arch.ceded = 0;
3463
3464 kvmhv_save_host_pmu(); /* saves it to PACA kvm_hstate */
3465
3466 kvmppc_subcore_enter_guest();
3467
3468 vc->entry_exit_map = 1;
3469 vc->in_guest = 1;
3470
3471 if (vcpu->arch.vpa.pinned_addr) {
3472 struct lppaca *lp = vcpu->arch.vpa.pinned_addr;
3473 u32 yield_count = be32_to_cpu(lp->yield_count) + 1;
3474 lp->yield_count = cpu_to_be32(yield_count);
3475 vcpu->arch.vpa.dirty = 1;
3476 }
3477
3478 if (cpu_has_feature(CPU_FTR_TM) ||
3479 cpu_has_feature(CPU_FTR_P9_TM_HV_ASSIST))
3480 kvmppc_restore_tm_hv(vcpu, vcpu->arch.shregs.msr, true);
3481
3482 kvmhv_load_guest_pmu(vcpu);
3483
3484 msr_check_and_set(MSR_FP | MSR_VEC | MSR_VSX);
3485 load_fp_state(&vcpu->arch.fp);
3486#ifdef CONFIG_ALTIVEC
3487 load_vr_state(&vcpu->arch.vr);
3488#endif
3489
3490 mtspr(SPRN_DSCR, vcpu->arch.dscr);
3491 mtspr(SPRN_IAMR, vcpu->arch.iamr);
3492 mtspr(SPRN_PSPB, vcpu->arch.pspb);
3493 mtspr(SPRN_FSCR, vcpu->arch.fscr);
3494 mtspr(SPRN_TAR, vcpu->arch.tar);
3495 mtspr(SPRN_EBBHR, vcpu->arch.ebbhr);
3496 mtspr(SPRN_EBBRR, vcpu->arch.ebbrr);
3497 mtspr(SPRN_BESCR, vcpu->arch.bescr);
3498 mtspr(SPRN_WORT, vcpu->arch.wort);
3499 mtspr(SPRN_TIDR, vcpu->arch.tid);
3500 mtspr(SPRN_DAR, vcpu->arch.shregs.dar);
3501 mtspr(SPRN_DSISR, vcpu->arch.shregs.dsisr);
3502 mtspr(SPRN_AMR, vcpu->arch.amr);
3503 mtspr(SPRN_UAMOR, vcpu->arch.uamor);
3504
3505 if (!(vcpu->arch.ctrl & 1))
3506 mtspr(SPRN_CTRLT, mfspr(SPRN_CTRLF) & ~1);
3507
3508 mtspr(SPRN_DEC, vcpu->arch.dec_expires - mftb());
3509
3510 if (kvmhv_on_pseries()) {
3511 /* call our hypervisor to load up HV regs and go */
3512 struct hv_guest_state hvregs;
3513
3514 kvmhv_save_hv_regs(vcpu, &hvregs);
3515 hvregs.lpcr = lpcr;
3516 vcpu->arch.regs.msr = vcpu->arch.shregs.msr;
3517 hvregs.version = HV_GUEST_STATE_VERSION;
3518 if (vcpu->arch.nested) {
3519 hvregs.lpid = vcpu->arch.nested->shadow_lpid;
3520 hvregs.vcpu_token = vcpu->arch.nested_vcpu_id;
3521 } else {
3522 hvregs.lpid = vcpu->kvm->arch.lpid;
3523 hvregs.vcpu_token = vcpu->vcpu_id;
3524 }
3525 hvregs.hdec_expiry = time_limit;
3526 trap = plpar_hcall_norets(H_ENTER_NESTED, __pa(&hvregs),
3527 __pa(&vcpu->arch.regs));
3528 kvmhv_restore_hv_return_state(vcpu, &hvregs);
3529 vcpu->arch.shregs.msr = vcpu->arch.regs.msr;
3530 vcpu->arch.shregs.dar = mfspr(SPRN_DAR);
3531 vcpu->arch.shregs.dsisr = mfspr(SPRN_DSISR);
3532
3533 /* H_CEDE has to be handled now, not later */
3534 if (trap == BOOK3S_INTERRUPT_SYSCALL && !vcpu->arch.nested &&
3535 kvmppc_get_gpr(vcpu, 3) == H_CEDE) {
3536 kvmppc_nested_cede(vcpu);
3537 trap = 0;
3538 }
3539 } else {
3540 trap = kvmhv_load_hv_regs_and_go(vcpu, time_limit, lpcr);
3541 }
3542
3543 vcpu->arch.slb_max = 0;
3544 dec = mfspr(SPRN_DEC);
3545 tb = mftb();
3546 vcpu->arch.dec_expires = dec + tb;
3547 vcpu->cpu = -1;
3548 vcpu->arch.thread_cpu = -1;
3549 vcpu->arch.ctrl = mfspr(SPRN_CTRLF);
3550
3551 vcpu->arch.iamr = mfspr(SPRN_IAMR);
3552 vcpu->arch.pspb = mfspr(SPRN_PSPB);
3553 vcpu->arch.fscr = mfspr(SPRN_FSCR);
3554 vcpu->arch.tar = mfspr(SPRN_TAR);
3555 vcpu->arch.ebbhr = mfspr(SPRN_EBBHR);
3556 vcpu->arch.ebbrr = mfspr(SPRN_EBBRR);
3557 vcpu->arch.bescr = mfspr(SPRN_BESCR);
3558 vcpu->arch.wort = mfspr(SPRN_WORT);
3559 vcpu->arch.tid = mfspr(SPRN_TIDR);
3560 vcpu->arch.amr = mfspr(SPRN_AMR);
3561 vcpu->arch.uamor = mfspr(SPRN_UAMOR);
3562 vcpu->arch.dscr = mfspr(SPRN_DSCR);
3563
3564 mtspr(SPRN_PSPB, 0);
3565 mtspr(SPRN_WORT, 0);
3566 mtspr(SPRN_AMR, 0);
3567 mtspr(SPRN_UAMOR, 0);
3568 mtspr(SPRN_DSCR, host_dscr);
3569 mtspr(SPRN_TIDR, host_tidr);
3570 mtspr(SPRN_IAMR, host_iamr);
3571 mtspr(SPRN_PSPB, 0);
3572
3573 msr_check_and_set(MSR_FP | MSR_VEC | MSR_VSX);
3574 store_fp_state(&vcpu->arch.fp);
3575#ifdef CONFIG_ALTIVEC
3576 store_vr_state(&vcpu->arch.vr);
3577#endif
3578
3579 if (cpu_has_feature(CPU_FTR_TM) ||
3580 cpu_has_feature(CPU_FTR_P9_TM_HV_ASSIST))
3581 kvmppc_save_tm_hv(vcpu, vcpu->arch.shregs.msr, true);
3582
3583 save_pmu = 1;
3584 if (vcpu->arch.vpa.pinned_addr) {
3585 struct lppaca *lp = vcpu->arch.vpa.pinned_addr;
3586 u32 yield_count = be32_to_cpu(lp->yield_count) + 1;
3587 lp->yield_count = cpu_to_be32(yield_count);
3588 vcpu->arch.vpa.dirty = 1;
3589 save_pmu = lp->pmcregs_in_use;
3590 }
3591
3592 kvmhv_save_guest_pmu(vcpu, save_pmu);
3593
3594 vc->entry_exit_map = 0x101;
3595 vc->in_guest = 0;
3596
3597 mtspr(SPRN_DEC, local_paca->kvm_hstate.dec_expires - mftb());
3598
3599 kvmhv_load_host_pmu();
3600
3601 kvmppc_subcore_exit_guest();
3602
3603 return trap;
3604}
3605
3606/*
3083 * Wait for some other vcpu thread to execute us, and 3607 * Wait for some other vcpu thread to execute us, and
3084 * wake us up when we need to handle something in the host. 3608 * wake us up when we need to handle something in the host.
3085 */ 3609 */
@@ -3256,6 +3780,11 @@ out:
3256 trace_kvmppc_vcore_wakeup(do_sleep, block_ns); 3780 trace_kvmppc_vcore_wakeup(do_sleep, block_ns);
3257} 3781}
3258 3782
3783/*
3784 * This never fails for a radix guest, as none of the operations it does
3785 * for a radix guest can fail or have a way to report failure.
3786 * kvmhv_run_single_vcpu() relies on this fact.
3787 */
3259static int kvmhv_setup_mmu(struct kvm_vcpu *vcpu) 3788static int kvmhv_setup_mmu(struct kvm_vcpu *vcpu)
3260{ 3789{
3261 int r = 0; 3790 int r = 0;
@@ -3405,6 +3934,171 @@ static int kvmppc_run_vcpu(struct kvm_run *kvm_run, struct kvm_vcpu *vcpu)
3405 return vcpu->arch.ret; 3934 return vcpu->arch.ret;
3406} 3935}
3407 3936
3937int kvmhv_run_single_vcpu(struct kvm_run *kvm_run,
3938 struct kvm_vcpu *vcpu, u64 time_limit,
3939 unsigned long lpcr)
3940{
3941 int trap, r, pcpu;
3942 int srcu_idx;
3943 struct kvmppc_vcore *vc;
3944 struct kvm *kvm = vcpu->kvm;
3945 struct kvm_nested_guest *nested = vcpu->arch.nested;
3946
3947 trace_kvmppc_run_vcpu_enter(vcpu);
3948
3949 kvm_run->exit_reason = 0;
3950 vcpu->arch.ret = RESUME_GUEST;
3951 vcpu->arch.trap = 0;
3952
3953 vc = vcpu->arch.vcore;
3954 vcpu->arch.ceded = 0;
3955 vcpu->arch.run_task = current;
3956 vcpu->arch.kvm_run = kvm_run;
3957 vcpu->arch.stolen_logged = vcore_stolen_time(vc, mftb());
3958 vcpu->arch.state = KVMPPC_VCPU_RUNNABLE;
3959 vcpu->arch.busy_preempt = TB_NIL;
3960 vcpu->arch.last_inst = KVM_INST_FETCH_FAILED;
3961 vc->runnable_threads[0] = vcpu;
3962 vc->n_runnable = 1;
3963 vc->runner = vcpu;
3964
3965 /* See if the MMU is ready to go */
3966 if (!kvm->arch.mmu_ready)
3967 kvmhv_setup_mmu(vcpu);
3968
3969 if (need_resched())
3970 cond_resched();
3971
3972 kvmppc_update_vpas(vcpu);
3973
3974 init_vcore_to_run(vc);
3975 vc->preempt_tb = TB_NIL;
3976
3977 preempt_disable();
3978 pcpu = smp_processor_id();
3979 vc->pcpu = pcpu;
3980 kvmppc_prepare_radix_vcpu(vcpu, pcpu);
3981
3982 local_irq_disable();
3983 hard_irq_disable();
3984 if (signal_pending(current))
3985 goto sigpend;
3986 if (lazy_irq_pending() || need_resched() || !kvm->arch.mmu_ready)
3987 goto out;
3988
3989 if (!nested) {
3990 kvmppc_core_prepare_to_enter(vcpu);
3991 if (vcpu->arch.doorbell_request) {
3992 vc->dpdes = 1;
3993 smp_wmb();
3994 vcpu->arch.doorbell_request = 0;
3995 }
3996 if (test_bit(BOOK3S_IRQPRIO_EXTERNAL,
3997 &vcpu->arch.pending_exceptions))
3998 lpcr |= LPCR_MER;
3999 } else if (vcpu->arch.pending_exceptions ||
4000 vcpu->arch.doorbell_request ||
4001 xive_interrupt_pending(vcpu)) {
4002 vcpu->arch.ret = RESUME_HOST;
4003 goto out;
4004 }
4005
4006 kvmppc_clear_host_core(pcpu);
4007
4008 local_paca->kvm_hstate.tid = 0;
4009 local_paca->kvm_hstate.napping = 0;
4010 local_paca->kvm_hstate.kvm_split_mode = NULL;
4011 kvmppc_start_thread(vcpu, vc);
4012 kvmppc_create_dtl_entry(vcpu, vc);
4013 trace_kvm_guest_enter(vcpu);
4014
4015 vc->vcore_state = VCORE_RUNNING;
4016 trace_kvmppc_run_core(vc, 0);
4017
4018 if (cpu_has_feature(CPU_FTR_HVMODE))
4019 kvmppc_radix_check_need_tlb_flush(kvm, pcpu, nested);
4020
4021 trace_hardirqs_on();
4022 guest_enter_irqoff();
4023
4024 srcu_idx = srcu_read_lock(&kvm->srcu);
4025
4026 this_cpu_disable_ftrace();
4027
4028 trap = kvmhv_p9_guest_entry(vcpu, time_limit, lpcr);
4029 vcpu->arch.trap = trap;
4030
4031 this_cpu_enable_ftrace();
4032
4033 srcu_read_unlock(&kvm->srcu, srcu_idx);
4034
4035 if (cpu_has_feature(CPU_FTR_HVMODE)) {
4036 mtspr(SPRN_LPID, kvm->arch.host_lpid);
4037 isync();
4038 }
4039
4040 trace_hardirqs_off();
4041 set_irq_happened(trap);
4042
4043 kvmppc_set_host_core(pcpu);
4044
4045 local_irq_enable();
4046 guest_exit();
4047
4048 cpumask_clear_cpu(pcpu, &kvm->arch.cpu_in_guest);
4049
4050 preempt_enable();
4051
4052 /* cancel pending decrementer exception if DEC is now positive */
4053 if (get_tb() < vcpu->arch.dec_expires && kvmppc_core_pending_dec(vcpu))
4054 kvmppc_core_dequeue_dec(vcpu);
4055
4056 trace_kvm_guest_exit(vcpu);
4057 r = RESUME_GUEST;
4058 if (trap) {
4059 if (!nested)
4060 r = kvmppc_handle_exit_hv(kvm_run, vcpu, current);
4061 else
4062 r = kvmppc_handle_nested_exit(vcpu);
4063 }
4064 vcpu->arch.ret = r;
4065
4066 if (is_kvmppc_resume_guest(r) && vcpu->arch.ceded &&
4067 !kvmppc_vcpu_woken(vcpu)) {
4068 kvmppc_set_timer(vcpu);
4069 while (vcpu->arch.ceded && !kvmppc_vcpu_woken(vcpu)) {
4070 if (signal_pending(current)) {
4071 vcpu->stat.signal_exits++;
4072 kvm_run->exit_reason = KVM_EXIT_INTR;
4073 vcpu->arch.ret = -EINTR;
4074 break;
4075 }
4076 spin_lock(&vc->lock);
4077 kvmppc_vcore_blocked(vc);
4078 spin_unlock(&vc->lock);
4079 }
4080 }
4081 vcpu->arch.ceded = 0;
4082
4083 vc->vcore_state = VCORE_INACTIVE;
4084 trace_kvmppc_run_core(vc, 1);
4085
4086 done:
4087 kvmppc_remove_runnable(vc, vcpu);
4088 trace_kvmppc_run_vcpu_exit(vcpu, kvm_run);
4089
4090 return vcpu->arch.ret;
4091
4092 sigpend:
4093 vcpu->stat.signal_exits++;
4094 kvm_run->exit_reason = KVM_EXIT_INTR;
4095 vcpu->arch.ret = -EINTR;
4096 out:
4097 local_irq_enable();
4098 preempt_enable();
4099 goto done;
4100}
4101
3408static int kvmppc_vcpu_run_hv(struct kvm_run *run, struct kvm_vcpu *vcpu) 4102static int kvmppc_vcpu_run_hv(struct kvm_run *run, struct kvm_vcpu *vcpu)
3409{ 4103{
3410 int r; 4104 int r;
@@ -3480,7 +4174,20 @@ static int kvmppc_vcpu_run_hv(struct kvm_run *run, struct kvm_vcpu *vcpu)
3480 vcpu->arch.state = KVMPPC_VCPU_BUSY_IN_HOST; 4174 vcpu->arch.state = KVMPPC_VCPU_BUSY_IN_HOST;
3481 4175
3482 do { 4176 do {
3483 r = kvmppc_run_vcpu(run, vcpu); 4177 /*
4178 * The early POWER9 chips that can't mix radix and HPT threads
4179 * on the same core also need the workaround for the problem
4180 * where the TLB would prefetch entries in the guest exit path
4181 * for radix guests using the guest PIDR value and LPID 0.
4182 * The workaround is in the old path (kvmppc_run_vcpu())
4183 * but not the new path (kvmhv_run_single_vcpu()).
4184 */
4185 if (kvm->arch.threads_indep && kvm_is_radix(kvm) &&
4186 !no_mixing_hpt_and_radix)
4187 r = kvmhv_run_single_vcpu(run, vcpu, ~(u64)0,
4188 vcpu->arch.vcore->lpcr);
4189 else
4190 r = kvmppc_run_vcpu(run, vcpu);
3484 4191
3485 if (run->exit_reason == KVM_EXIT_PAPR_HCALL && 4192 if (run->exit_reason == KVM_EXIT_PAPR_HCALL &&
3486 !(vcpu->arch.shregs.msr & MSR_PR)) { 4193 !(vcpu->arch.shregs.msr & MSR_PR)) {
@@ -3559,6 +4266,10 @@ static int kvm_vm_ioctl_get_smmu_info_hv(struct kvm *kvm,
3559 kvmppc_add_seg_page_size(&sps, 16, SLB_VSID_L | SLB_VSID_LP_01); 4266 kvmppc_add_seg_page_size(&sps, 16, SLB_VSID_L | SLB_VSID_LP_01);
3560 kvmppc_add_seg_page_size(&sps, 24, SLB_VSID_L); 4267 kvmppc_add_seg_page_size(&sps, 24, SLB_VSID_L);
3561 4268
4269 /* If running as a nested hypervisor, we don't support HPT guests */
4270 if (kvmhv_on_pseries())
4271 info->flags |= KVM_PPC_NO_HASH;
4272
3562 return 0; 4273 return 0;
3563} 4274}
3564 4275
@@ -3723,8 +4434,7 @@ void kvmppc_setup_partition_table(struct kvm *kvm)
3723 __pa(kvm->arch.pgtable) | RADIX_PGD_INDEX_SIZE; 4434 __pa(kvm->arch.pgtable) | RADIX_PGD_INDEX_SIZE;
3724 dw1 = PATB_GR | kvm->arch.process_table; 4435 dw1 = PATB_GR | kvm->arch.process_table;
3725 } 4436 }
3726 4437 kvmhv_set_ptbl_entry(kvm->arch.lpid, dw0, dw1);
3727 mmu_partition_table_set_entry(kvm->arch.lpid, dw0, dw1);
3728} 4438}
3729 4439
3730/* 4440/*
@@ -3820,6 +4530,8 @@ static int kvmppc_hv_setup_htab_rma(struct kvm_vcpu *vcpu)
3820/* Must be called with kvm->lock held and mmu_ready = 0 and no vcpus running */ 4530/* Must be called with kvm->lock held and mmu_ready = 0 and no vcpus running */
3821int kvmppc_switch_mmu_to_hpt(struct kvm *kvm) 4531int kvmppc_switch_mmu_to_hpt(struct kvm *kvm)
3822{ 4532{
4533 if (nesting_enabled(kvm))
4534 kvmhv_release_all_nested(kvm);
3823 kvmppc_free_radix(kvm); 4535 kvmppc_free_radix(kvm);
3824 kvmppc_update_lpcr(kvm, LPCR_VPM1, 4536 kvmppc_update_lpcr(kvm, LPCR_VPM1,
3825 LPCR_VPM1 | LPCR_UPRT | LPCR_GTSE | LPCR_HR); 4537 LPCR_VPM1 | LPCR_UPRT | LPCR_GTSE | LPCR_HR);
@@ -3841,6 +4553,7 @@ int kvmppc_switch_mmu_to_radix(struct kvm *kvm)
3841 kvmppc_free_hpt(&kvm->arch.hpt); 4553 kvmppc_free_hpt(&kvm->arch.hpt);
3842 kvmppc_update_lpcr(kvm, LPCR_UPRT | LPCR_GTSE | LPCR_HR, 4554 kvmppc_update_lpcr(kvm, LPCR_UPRT | LPCR_GTSE | LPCR_HR,
3843 LPCR_VPM1 | LPCR_UPRT | LPCR_GTSE | LPCR_HR); 4555 LPCR_VPM1 | LPCR_UPRT | LPCR_GTSE | LPCR_HR);
4556 kvmppc_rmap_reset(kvm);
3844 kvm->arch.radix = 1; 4557 kvm->arch.radix = 1;
3845 return 0; 4558 return 0;
3846} 4559}
@@ -3940,6 +4653,8 @@ static int kvmppc_core_init_vm_hv(struct kvm *kvm)
3940 4653
3941 kvmppc_alloc_host_rm_ops(); 4654 kvmppc_alloc_host_rm_ops();
3942 4655
4656 kvmhv_vm_nested_init(kvm);
4657
3943 /* 4658 /*
3944 * Since we don't flush the TLB when tearing down a VM, 4659 * Since we don't flush the TLB when tearing down a VM,
3945 * and this lpid might have previously been used, 4660 * and this lpid might have previously been used,
@@ -3958,9 +4673,13 @@ static int kvmppc_core_init_vm_hv(struct kvm *kvm)
3958 kvm->arch.host_sdr1 = mfspr(SPRN_SDR1); 4673 kvm->arch.host_sdr1 = mfspr(SPRN_SDR1);
3959 4674
3960 /* Init LPCR for virtual RMA mode */ 4675 /* Init LPCR for virtual RMA mode */
3961 kvm->arch.host_lpid = mfspr(SPRN_LPID); 4676 if (cpu_has_feature(CPU_FTR_HVMODE)) {
3962 kvm->arch.host_lpcr = lpcr = mfspr(SPRN_LPCR); 4677 kvm->arch.host_lpid = mfspr(SPRN_LPID);
3963 lpcr &= LPCR_PECE | LPCR_LPES; 4678 kvm->arch.host_lpcr = lpcr = mfspr(SPRN_LPCR);
4679 lpcr &= LPCR_PECE | LPCR_LPES;
4680 } else {
4681 lpcr = 0;
4682 }
3964 lpcr |= (4UL << LPCR_DPFD_SH) | LPCR_HDICE | 4683 lpcr |= (4UL << LPCR_DPFD_SH) | LPCR_HDICE |
3965 LPCR_VPM0 | LPCR_VPM1; 4684 LPCR_VPM0 | LPCR_VPM1;
3966 kvm->arch.vrma_slb_v = SLB_VSID_B_1T | 4685 kvm->arch.vrma_slb_v = SLB_VSID_B_1T |
@@ -4027,8 +4746,14 @@ static int kvmppc_core_init_vm_hv(struct kvm *kvm)
4027 * On POWER9, we only need to do this if the "indep_threads_mode" 4746 * On POWER9, we only need to do this if the "indep_threads_mode"
4028 * module parameter has been set to N. 4747 * module parameter has been set to N.
4029 */ 4748 */
4030 if (cpu_has_feature(CPU_FTR_ARCH_300)) 4749 if (cpu_has_feature(CPU_FTR_ARCH_300)) {
4031 kvm->arch.threads_indep = indep_threads_mode; 4750 if (!indep_threads_mode && !cpu_has_feature(CPU_FTR_HVMODE)) {
4751 pr_warn("KVM: Ignoring indep_threads_mode=N in nested hypervisor\n");
4752 kvm->arch.threads_indep = true;
4753 } else {
4754 kvm->arch.threads_indep = indep_threads_mode;
4755 }
4756 }
4032 if (!kvm->arch.threads_indep) 4757 if (!kvm->arch.threads_indep)
4033 kvm_hv_vm_activated(); 4758 kvm_hv_vm_activated();
4034 4759
@@ -4051,6 +4776,8 @@ static int kvmppc_core_init_vm_hv(struct kvm *kvm)
4051 snprintf(buf, sizeof(buf), "vm%d", current->pid); 4776 snprintf(buf, sizeof(buf), "vm%d", current->pid);
4052 kvm->arch.debugfs_dir = debugfs_create_dir(buf, kvm_debugfs_dir); 4777 kvm->arch.debugfs_dir = debugfs_create_dir(buf, kvm_debugfs_dir);
4053 kvmppc_mmu_debugfs_init(kvm); 4778 kvmppc_mmu_debugfs_init(kvm);
4779 if (radix_enabled())
4780 kvmhv_radix_debugfs_init(kvm);
4054 4781
4055 return 0; 4782 return 0;
4056} 4783}
@@ -4073,13 +4800,21 @@ static void kvmppc_core_destroy_vm_hv(struct kvm *kvm)
4073 4800
4074 kvmppc_free_vcores(kvm); 4801 kvmppc_free_vcores(kvm);
4075 4802
4076 kvmppc_free_lpid(kvm->arch.lpid);
4077 4803
4078 if (kvm_is_radix(kvm)) 4804 if (kvm_is_radix(kvm))
4079 kvmppc_free_radix(kvm); 4805 kvmppc_free_radix(kvm);
4080 else 4806 else
4081 kvmppc_free_hpt(&kvm->arch.hpt); 4807 kvmppc_free_hpt(&kvm->arch.hpt);
4082 4808
4809 /* Perform global invalidation and return lpid to the pool */
4810 if (cpu_has_feature(CPU_FTR_ARCH_300)) {
4811 if (nesting_enabled(kvm))
4812 kvmhv_release_all_nested(kvm);
4813 kvm->arch.process_table = 0;
4814 kvmhv_set_ptbl_entry(kvm->arch.lpid, 0, 0);
4815 }
4816 kvmppc_free_lpid(kvm->arch.lpid);
4817
4083 kvmppc_free_pimap(kvm); 4818 kvmppc_free_pimap(kvm);
4084} 4819}
4085 4820
@@ -4104,11 +4839,15 @@ static int kvmppc_core_emulate_mfspr_hv(struct kvm_vcpu *vcpu, int sprn,
4104 4839
4105static int kvmppc_core_check_processor_compat_hv(void) 4840static int kvmppc_core_check_processor_compat_hv(void)
4106{ 4841{
4107 if (!cpu_has_feature(CPU_FTR_HVMODE) || 4842 if (cpu_has_feature(CPU_FTR_HVMODE) &&
4108 !cpu_has_feature(CPU_FTR_ARCH_206)) 4843 cpu_has_feature(CPU_FTR_ARCH_206))
4109 return -EIO; 4844 return 0;
4110 4845
4111 return 0; 4846 /* POWER9 in radix mode is capable of being a nested hypervisor. */
4847 if (cpu_has_feature(CPU_FTR_ARCH_300) && radix_enabled())
4848 return 0;
4849
4850 return -EIO;
4112} 4851}
4113 4852
4114#ifdef CONFIG_KVM_XICS 4853#ifdef CONFIG_KVM_XICS
@@ -4426,6 +5165,10 @@ static int kvmhv_configure_mmu(struct kvm *kvm, struct kvm_ppc_mmuv3_cfg *cfg)
4426 if (radix && !radix_enabled()) 5165 if (radix && !radix_enabled())
4427 return -EINVAL; 5166 return -EINVAL;
4428 5167
5168 /* If we're a nested hypervisor, we currently only support radix */
5169 if (kvmhv_on_pseries() && !radix)
5170 return -EINVAL;
5171
4429 mutex_lock(&kvm->lock); 5172 mutex_lock(&kvm->lock);
4430 if (radix != kvm_is_radix(kvm)) { 5173 if (radix != kvm_is_radix(kvm)) {
4431 if (kvm->arch.mmu_ready) { 5174 if (kvm->arch.mmu_ready) {
@@ -4458,6 +5201,19 @@ static int kvmhv_configure_mmu(struct kvm *kvm, struct kvm_ppc_mmuv3_cfg *cfg)
4458 return err; 5201 return err;
4459} 5202}
4460 5203
5204static int kvmhv_enable_nested(struct kvm *kvm)
5205{
5206 if (!nested)
5207 return -EPERM;
5208 if (!cpu_has_feature(CPU_FTR_ARCH_300) || no_mixing_hpt_and_radix)
5209 return -ENODEV;
5210
5211 /* kvm == NULL means the caller is testing if the capability exists */
5212 if (kvm)
5213 kvm->arch.nested_enable = true;
5214 return 0;
5215}
5216
4461static struct kvmppc_ops kvm_ops_hv = { 5217static struct kvmppc_ops kvm_ops_hv = {
4462 .get_sregs = kvm_arch_vcpu_ioctl_get_sregs_hv, 5218 .get_sregs = kvm_arch_vcpu_ioctl_get_sregs_hv,
4463 .set_sregs = kvm_arch_vcpu_ioctl_set_sregs_hv, 5219 .set_sregs = kvm_arch_vcpu_ioctl_set_sregs_hv,
@@ -4497,6 +5253,7 @@ static struct kvmppc_ops kvm_ops_hv = {
4497 .configure_mmu = kvmhv_configure_mmu, 5253 .configure_mmu = kvmhv_configure_mmu,
4498 .get_rmmu_info = kvmhv_get_rmmu_info, 5254 .get_rmmu_info = kvmhv_get_rmmu_info,
4499 .set_smt_mode = kvmhv_set_smt_mode, 5255 .set_smt_mode = kvmhv_set_smt_mode,
5256 .enable_nested = kvmhv_enable_nested,
4500}; 5257};
4501 5258
4502static int kvm_init_subcore_bitmap(void) 5259static int kvm_init_subcore_bitmap(void)
@@ -4547,6 +5304,10 @@ static int kvmppc_book3s_init_hv(void)
4547 if (r < 0) 5304 if (r < 0)
4548 return -ENODEV; 5305 return -ENODEV;
4549 5306
5307 r = kvmhv_nested_init();
5308 if (r)
5309 return r;
5310
4550 r = kvm_init_subcore_bitmap(); 5311 r = kvm_init_subcore_bitmap();
4551 if (r) 5312 if (r)
4552 return r; 5313 return r;
@@ -4557,7 +5318,8 @@ static int kvmppc_book3s_init_hv(void)
4557 * indirectly, via OPAL. 5318 * indirectly, via OPAL.
4558 */ 5319 */
4559#ifdef CONFIG_SMP 5320#ifdef CONFIG_SMP
4560 if (!xive_enabled() && !local_paca->kvm_hstate.xics_phys) { 5321 if (!xive_enabled() && !kvmhv_on_pseries() &&
5322 !local_paca->kvm_hstate.xics_phys) {
4561 struct device_node *np; 5323 struct device_node *np;
4562 5324
4563 np = of_find_compatible_node(NULL, NULL, "ibm,opal-intc"); 5325 np = of_find_compatible_node(NULL, NULL, "ibm,opal-intc");
@@ -4605,6 +5367,7 @@ static void kvmppc_book3s_exit_hv(void)
4605 if (kvmppc_radix_possible()) 5367 if (kvmppc_radix_possible())
4606 kvmppc_radix_exit(); 5368 kvmppc_radix_exit();
4607 kvmppc_hv_ops = NULL; 5369 kvmppc_hv_ops = NULL;
5370 kvmhv_nested_exit();
4608} 5371}
4609 5372
4610module_init(kvmppc_book3s_init_hv); 5373module_init(kvmppc_book3s_init_hv);
diff --git a/arch/powerpc/kvm/book3s_hv_builtin.c b/arch/powerpc/kvm/book3s_hv_builtin.c
index fc6bb9630a9c..a71e2fc00a4e 100644
--- a/arch/powerpc/kvm/book3s_hv_builtin.c
+++ b/arch/powerpc/kvm/book3s_hv_builtin.c
@@ -231,6 +231,15 @@ void kvmhv_rm_send_ipi(int cpu)
231 void __iomem *xics_phys; 231 void __iomem *xics_phys;
232 unsigned long msg = PPC_DBELL_TYPE(PPC_DBELL_SERVER); 232 unsigned long msg = PPC_DBELL_TYPE(PPC_DBELL_SERVER);
233 233
234 /* For a nested hypervisor, use the XICS via hcall */
235 if (kvmhv_on_pseries()) {
236 unsigned long retbuf[PLPAR_HCALL_BUFSIZE];
237
238 plpar_hcall_raw(H_IPI, retbuf, get_hard_smp_processor_id(cpu),
239 IPI_PRIORITY);
240 return;
241 }
242
234 /* On POWER9 we can use msgsnd for any destination cpu. */ 243 /* On POWER9 we can use msgsnd for any destination cpu. */
235 if (cpu_has_feature(CPU_FTR_ARCH_300)) { 244 if (cpu_has_feature(CPU_FTR_ARCH_300)) {
236 msg |= get_hard_smp_processor_id(cpu); 245 msg |= get_hard_smp_processor_id(cpu);
@@ -460,12 +469,19 @@ static long kvmppc_read_one_intr(bool *again)
460 return 1; 469 return 1;
461 470
462 /* Now read the interrupt from the ICP */ 471 /* Now read the interrupt from the ICP */
463 xics_phys = local_paca->kvm_hstate.xics_phys; 472 if (kvmhv_on_pseries()) {
464 rc = 0; 473 unsigned long retbuf[PLPAR_HCALL_BUFSIZE];
465 if (!xics_phys) 474
466 rc = opal_int_get_xirr(&xirr, false); 475 rc = plpar_hcall_raw(H_XIRR, retbuf, 0xFF);
467 else 476 xirr = cpu_to_be32(retbuf[0]);
468 xirr = __raw_rm_readl(xics_phys + XICS_XIRR); 477 } else {
478 xics_phys = local_paca->kvm_hstate.xics_phys;
479 rc = 0;
480 if (!xics_phys)
481 rc = opal_int_get_xirr(&xirr, false);
482 else
483 xirr = __raw_rm_readl(xics_phys + XICS_XIRR);
484 }
469 if (rc < 0) 485 if (rc < 0)
470 return 1; 486 return 1;
471 487
@@ -494,7 +510,13 @@ static long kvmppc_read_one_intr(bool *again)
494 */ 510 */
495 if (xisr == XICS_IPI) { 511 if (xisr == XICS_IPI) {
496 rc = 0; 512 rc = 0;
497 if (xics_phys) { 513 if (kvmhv_on_pseries()) {
514 unsigned long retbuf[PLPAR_HCALL_BUFSIZE];
515
516 plpar_hcall_raw(H_IPI, retbuf,
517 hard_smp_processor_id(), 0xff);
518 plpar_hcall_raw(H_EOI, retbuf, h_xirr);
519 } else if (xics_phys) {
498 __raw_rm_writeb(0xff, xics_phys + XICS_MFRR); 520 __raw_rm_writeb(0xff, xics_phys + XICS_MFRR);
499 __raw_rm_writel(xirr, xics_phys + XICS_XIRR); 521 __raw_rm_writel(xirr, xics_phys + XICS_XIRR);
500 } else { 522 } else {
@@ -520,7 +542,13 @@ static long kvmppc_read_one_intr(bool *again)
520 /* We raced with the host, 542 /* We raced with the host,
521 * we need to resend that IPI, bummer 543 * we need to resend that IPI, bummer
522 */ 544 */
523 if (xics_phys) 545 if (kvmhv_on_pseries()) {
546 unsigned long retbuf[PLPAR_HCALL_BUFSIZE];
547
548 plpar_hcall_raw(H_IPI, retbuf,
549 hard_smp_processor_id(),
550 IPI_PRIORITY);
551 } else if (xics_phys)
524 __raw_rm_writeb(IPI_PRIORITY, 552 __raw_rm_writeb(IPI_PRIORITY,
525 xics_phys + XICS_MFRR); 553 xics_phys + XICS_MFRR);
526 else 554 else
@@ -729,3 +757,51 @@ void kvmhv_p9_restore_lpcr(struct kvm_split_mode *sip)
729 smp_mb(); 757 smp_mb();
730 local_paca->kvm_hstate.kvm_split_mode = NULL; 758 local_paca->kvm_hstate.kvm_split_mode = NULL;
731} 759}
760
761/*
762 * Is there a PRIV_DOORBELL pending for the guest (on POWER9)?
763 * Can we inject a Decrementer or a External interrupt?
764 */
765void kvmppc_guest_entry_inject_int(struct kvm_vcpu *vcpu)
766{
767 int ext;
768 unsigned long vec = 0;
769 unsigned long lpcr;
770
771 /* Insert EXTERNAL bit into LPCR at the MER bit position */
772 ext = (vcpu->arch.pending_exceptions >> BOOK3S_IRQPRIO_EXTERNAL) & 1;
773 lpcr = mfspr(SPRN_LPCR);
774 lpcr |= ext << LPCR_MER_SH;
775 mtspr(SPRN_LPCR, lpcr);
776 isync();
777
778 if (vcpu->arch.shregs.msr & MSR_EE) {
779 if (ext) {
780 vec = BOOK3S_INTERRUPT_EXTERNAL;
781 } else {
782 long int dec = mfspr(SPRN_DEC);
783 if (!(lpcr & LPCR_LD))
784 dec = (int) dec;
785 if (dec < 0)
786 vec = BOOK3S_INTERRUPT_DECREMENTER;
787 }
788 }
789 if (vec) {
790 unsigned long msr, old_msr = vcpu->arch.shregs.msr;
791
792 kvmppc_set_srr0(vcpu, kvmppc_get_pc(vcpu));
793 kvmppc_set_srr1(vcpu, old_msr);
794 kvmppc_set_pc(vcpu, vec);
795 msr = vcpu->arch.intr_msr;
796 if (MSR_TM_ACTIVE(old_msr))
797 msr |= MSR_TS_S;
798 vcpu->arch.shregs.msr = msr;
799 }
800
801 if (vcpu->arch.doorbell_request) {
802 mtspr(SPRN_DPDES, 1);
803 vcpu->arch.vcore->dpdes = 1;
804 smp_wmb();
805 vcpu->arch.doorbell_request = 0;
806 }
807}
diff --git a/arch/powerpc/kvm/book3s_hv_interrupts.S b/arch/powerpc/kvm/book3s_hv_interrupts.S
index 666b91c79eb4..a6d10010d9e8 100644
--- a/arch/powerpc/kvm/book3s_hv_interrupts.S
+++ b/arch/powerpc/kvm/book3s_hv_interrupts.S
@@ -64,52 +64,7 @@ BEGIN_FTR_SECTION
64END_FTR_SECTION_IFCLR(CPU_FTR_ARCH_207S) 64END_FTR_SECTION_IFCLR(CPU_FTR_ARCH_207S)
65 65
66 /* Save host PMU registers */ 66 /* Save host PMU registers */
67BEGIN_FTR_SECTION 67 bl kvmhv_save_host_pmu
68 /* Work around P8 PMAE bug */
69 li r3, -1
70 clrrdi r3, r3, 10
71 mfspr r8, SPRN_MMCR2
72 mtspr SPRN_MMCR2, r3 /* freeze all counters using MMCR2 */
73 isync
74END_FTR_SECTION_IFSET(CPU_FTR_ARCH_207S)
75 li r3, 1
76 sldi r3, r3, 31 /* MMCR0_FC (freeze counters) bit */
77 mfspr r7, SPRN_MMCR0 /* save MMCR0 */
78 mtspr SPRN_MMCR0, r3 /* freeze all counters, disable interrupts */
79 mfspr r6, SPRN_MMCRA
80 /* Clear MMCRA in order to disable SDAR updates */
81 li r5, 0
82 mtspr SPRN_MMCRA, r5
83 isync
84 lbz r5, PACA_PMCINUSE(r13) /* is the host using the PMU? */
85 cmpwi r5, 0
86 beq 31f /* skip if not */
87 mfspr r5, SPRN_MMCR1
88 mfspr r9, SPRN_SIAR
89 mfspr r10, SPRN_SDAR
90 std r7, HSTATE_MMCR0(r13)
91 std r5, HSTATE_MMCR1(r13)
92 std r6, HSTATE_MMCRA(r13)
93 std r9, HSTATE_SIAR(r13)
94 std r10, HSTATE_SDAR(r13)
95BEGIN_FTR_SECTION
96 mfspr r9, SPRN_SIER
97 std r8, HSTATE_MMCR2(r13)
98 std r9, HSTATE_SIER(r13)
99END_FTR_SECTION_IFSET(CPU_FTR_ARCH_207S)
100 mfspr r3, SPRN_PMC1
101 mfspr r5, SPRN_PMC2
102 mfspr r6, SPRN_PMC3
103 mfspr r7, SPRN_PMC4
104 mfspr r8, SPRN_PMC5
105 mfspr r9, SPRN_PMC6
106 stw r3, HSTATE_PMC1(r13)
107 stw r5, HSTATE_PMC2(r13)
108 stw r6, HSTATE_PMC3(r13)
109 stw r7, HSTATE_PMC4(r13)
110 stw r8, HSTATE_PMC5(r13)
111 stw r9, HSTATE_PMC6(r13)
11231:
113 68
114 /* 69 /*
115 * Put whatever is in the decrementer into the 70 * Put whatever is in the decrementer into the
@@ -161,3 +116,51 @@ END_FTR_SECTION_IFSET(CPU_FTR_ARCH_300)
161 ld r0, PPC_LR_STKOFF(r1) 116 ld r0, PPC_LR_STKOFF(r1)
162 mtlr r0 117 mtlr r0
163 blr 118 blr
119
120_GLOBAL(kvmhv_save_host_pmu)
121BEGIN_FTR_SECTION
122 /* Work around P8 PMAE bug */
123 li r3, -1
124 clrrdi r3, r3, 10
125 mfspr r8, SPRN_MMCR2
126 mtspr SPRN_MMCR2, r3 /* freeze all counters using MMCR2 */
127 isync
128END_FTR_SECTION_IFSET(CPU_FTR_ARCH_207S)
129 li r3, 1
130 sldi r3, r3, 31 /* MMCR0_FC (freeze counters) bit */
131 mfspr r7, SPRN_MMCR0 /* save MMCR0 */
132 mtspr SPRN_MMCR0, r3 /* freeze all counters, disable interrupts */
133 mfspr r6, SPRN_MMCRA
134 /* Clear MMCRA in order to disable SDAR updates */
135 li r5, 0
136 mtspr SPRN_MMCRA, r5
137 isync
138 lbz r5, PACA_PMCINUSE(r13) /* is the host using the PMU? */
139 cmpwi r5, 0
140 beq 31f /* skip if not */
141 mfspr r5, SPRN_MMCR1
142 mfspr r9, SPRN_SIAR
143 mfspr r10, SPRN_SDAR
144 std r7, HSTATE_MMCR0(r13)
145 std r5, HSTATE_MMCR1(r13)
146 std r6, HSTATE_MMCRA(r13)
147 std r9, HSTATE_SIAR(r13)
148 std r10, HSTATE_SDAR(r13)
149BEGIN_FTR_SECTION
150 mfspr r9, SPRN_SIER
151 std r8, HSTATE_MMCR2(r13)
152 std r9, HSTATE_SIER(r13)
153END_FTR_SECTION_IFSET(CPU_FTR_ARCH_207S)
154 mfspr r3, SPRN_PMC1
155 mfspr r5, SPRN_PMC2
156 mfspr r6, SPRN_PMC3
157 mfspr r7, SPRN_PMC4
158 mfspr r8, SPRN_PMC5
159 mfspr r9, SPRN_PMC6
160 stw r3, HSTATE_PMC1(r13)
161 stw r5, HSTATE_PMC2(r13)
162 stw r6, HSTATE_PMC3(r13)
163 stw r7, HSTATE_PMC4(r13)
164 stw r8, HSTATE_PMC5(r13)
165 stw r9, HSTATE_PMC6(r13)
16631: blr
diff --git a/arch/powerpc/kvm/book3s_hv_nested.c b/arch/powerpc/kvm/book3s_hv_nested.c
new file mode 100644
index 000000000000..401d2ecbebc5
--- /dev/null
+++ b/arch/powerpc/kvm/book3s_hv_nested.c
@@ -0,0 +1,1291 @@
1// SPDX-License-Identifier: GPL-2.0
2/*
3 * Copyright IBM Corporation, 2018
4 * Authors Suraj Jitindar Singh <sjitindarsingh@gmail.com>
5 * Paul Mackerras <paulus@ozlabs.org>
6 *
7 * Description: KVM functions specific to running nested KVM-HV guests
8 * on Book3S processors (specifically POWER9 and later).
9 */
10
11#include <linux/kernel.h>
12#include <linux/kvm_host.h>
13#include <linux/llist.h>
14
15#include <asm/kvm_ppc.h>
16#include <asm/kvm_book3s.h>
17#include <asm/mmu.h>
18#include <asm/pgtable.h>
19#include <asm/pgalloc.h>
20#include <asm/pte-walk.h>
21#include <asm/reg.h>
22
23static struct patb_entry *pseries_partition_tb;
24
25static void kvmhv_update_ptbl_cache(struct kvm_nested_guest *gp);
26static void kvmhv_free_memslot_nest_rmap(struct kvm_memory_slot *free);
27
28void kvmhv_save_hv_regs(struct kvm_vcpu *vcpu, struct hv_guest_state *hr)
29{
30 struct kvmppc_vcore *vc = vcpu->arch.vcore;
31
32 hr->pcr = vc->pcr;
33 hr->dpdes = vc->dpdes;
34 hr->hfscr = vcpu->arch.hfscr;
35 hr->tb_offset = vc->tb_offset;
36 hr->dawr0 = vcpu->arch.dawr;
37 hr->dawrx0 = vcpu->arch.dawrx;
38 hr->ciabr = vcpu->arch.ciabr;
39 hr->purr = vcpu->arch.purr;
40 hr->spurr = vcpu->arch.spurr;
41 hr->ic = vcpu->arch.ic;
42 hr->vtb = vc->vtb;
43 hr->srr0 = vcpu->arch.shregs.srr0;
44 hr->srr1 = vcpu->arch.shregs.srr1;
45 hr->sprg[0] = vcpu->arch.shregs.sprg0;
46 hr->sprg[1] = vcpu->arch.shregs.sprg1;
47 hr->sprg[2] = vcpu->arch.shregs.sprg2;
48 hr->sprg[3] = vcpu->arch.shregs.sprg3;
49 hr->pidr = vcpu->arch.pid;
50 hr->cfar = vcpu->arch.cfar;
51 hr->ppr = vcpu->arch.ppr;
52}
53
54static void byteswap_pt_regs(struct pt_regs *regs)
55{
56 unsigned long *addr = (unsigned long *) regs;
57
58 for (; addr < ((unsigned long *) (regs + 1)); addr++)
59 *addr = swab64(*addr);
60}
61
62static void byteswap_hv_regs(struct hv_guest_state *hr)
63{
64 hr->version = swab64(hr->version);
65 hr->lpid = swab32(hr->lpid);
66 hr->vcpu_token = swab32(hr->vcpu_token);
67 hr->lpcr = swab64(hr->lpcr);
68 hr->pcr = swab64(hr->pcr);
69 hr->amor = swab64(hr->amor);
70 hr->dpdes = swab64(hr->dpdes);
71 hr->hfscr = swab64(hr->hfscr);
72 hr->tb_offset = swab64(hr->tb_offset);
73 hr->dawr0 = swab64(hr->dawr0);
74 hr->dawrx0 = swab64(hr->dawrx0);
75 hr->ciabr = swab64(hr->ciabr);
76 hr->hdec_expiry = swab64(hr->hdec_expiry);
77 hr->purr = swab64(hr->purr);
78 hr->spurr = swab64(hr->spurr);
79 hr->ic = swab64(hr->ic);
80 hr->vtb = swab64(hr->vtb);
81 hr->hdar = swab64(hr->hdar);
82 hr->hdsisr = swab64(hr->hdsisr);
83 hr->heir = swab64(hr->heir);
84 hr->asdr = swab64(hr->asdr);
85 hr->srr0 = swab64(hr->srr0);
86 hr->srr1 = swab64(hr->srr1);
87 hr->sprg[0] = swab64(hr->sprg[0]);
88 hr->sprg[1] = swab64(hr->sprg[1]);
89 hr->sprg[2] = swab64(hr->sprg[2]);
90 hr->sprg[3] = swab64(hr->sprg[3]);
91 hr->pidr = swab64(hr->pidr);
92 hr->cfar = swab64(hr->cfar);
93 hr->ppr = swab64(hr->ppr);
94}
95
96static void save_hv_return_state(struct kvm_vcpu *vcpu, int trap,
97 struct hv_guest_state *hr)
98{
99 struct kvmppc_vcore *vc = vcpu->arch.vcore;
100
101 hr->dpdes = vc->dpdes;
102 hr->hfscr = vcpu->arch.hfscr;
103 hr->purr = vcpu->arch.purr;
104 hr->spurr = vcpu->arch.spurr;
105 hr->ic = vcpu->arch.ic;
106 hr->vtb = vc->vtb;
107 hr->srr0 = vcpu->arch.shregs.srr0;
108 hr->srr1 = vcpu->arch.shregs.srr1;
109 hr->sprg[0] = vcpu->arch.shregs.sprg0;
110 hr->sprg[1] = vcpu->arch.shregs.sprg1;
111 hr->sprg[2] = vcpu->arch.shregs.sprg2;
112 hr->sprg[3] = vcpu->arch.shregs.sprg3;
113 hr->pidr = vcpu->arch.pid;
114 hr->cfar = vcpu->arch.cfar;
115 hr->ppr = vcpu->arch.ppr;
116 switch (trap) {
117 case BOOK3S_INTERRUPT_H_DATA_STORAGE:
118 hr->hdar = vcpu->arch.fault_dar;
119 hr->hdsisr = vcpu->arch.fault_dsisr;
120 hr->asdr = vcpu->arch.fault_gpa;
121 break;
122 case BOOK3S_INTERRUPT_H_INST_STORAGE:
123 hr->asdr = vcpu->arch.fault_gpa;
124 break;
125 case BOOK3S_INTERRUPT_H_EMUL_ASSIST:
126 hr->heir = vcpu->arch.emul_inst;
127 break;
128 }
129}
130
131static void sanitise_hv_regs(struct kvm_vcpu *vcpu, struct hv_guest_state *hr)
132{
133 /*
134 * Don't let L1 enable features for L2 which we've disabled for L1,
135 * but preserve the interrupt cause field.
136 */
137 hr->hfscr &= (HFSCR_INTR_CAUSE | vcpu->arch.hfscr);
138
139 /* Don't let data address watchpoint match in hypervisor state */
140 hr->dawrx0 &= ~DAWRX_HYP;
141
142 /* Don't let completed instruction address breakpt match in HV state */
143 if ((hr->ciabr & CIABR_PRIV) == CIABR_PRIV_HYPER)
144 hr->ciabr &= ~CIABR_PRIV;
145}
146
147static void restore_hv_regs(struct kvm_vcpu *vcpu, struct hv_guest_state *hr)
148{
149 struct kvmppc_vcore *vc = vcpu->arch.vcore;
150
151 vc->pcr = hr->pcr;
152 vc->dpdes = hr->dpdes;
153 vcpu->arch.hfscr = hr->hfscr;
154 vcpu->arch.dawr = hr->dawr0;
155 vcpu->arch.dawrx = hr->dawrx0;
156 vcpu->arch.ciabr = hr->ciabr;
157 vcpu->arch.purr = hr->purr;
158 vcpu->arch.spurr = hr->spurr;
159 vcpu->arch.ic = hr->ic;
160 vc->vtb = hr->vtb;
161 vcpu->arch.shregs.srr0 = hr->srr0;
162 vcpu->arch.shregs.srr1 = hr->srr1;
163 vcpu->arch.shregs.sprg0 = hr->sprg[0];
164 vcpu->arch.shregs.sprg1 = hr->sprg[1];
165 vcpu->arch.shregs.sprg2 = hr->sprg[2];
166 vcpu->arch.shregs.sprg3 = hr->sprg[3];
167 vcpu->arch.pid = hr->pidr;
168 vcpu->arch.cfar = hr->cfar;
169 vcpu->arch.ppr = hr->ppr;
170}
171
172void kvmhv_restore_hv_return_state(struct kvm_vcpu *vcpu,
173 struct hv_guest_state *hr)
174{
175 struct kvmppc_vcore *vc = vcpu->arch.vcore;
176
177 vc->dpdes = hr->dpdes;
178 vcpu->arch.hfscr = hr->hfscr;
179 vcpu->arch.purr = hr->purr;
180 vcpu->arch.spurr = hr->spurr;
181 vcpu->arch.ic = hr->ic;
182 vc->vtb = hr->vtb;
183 vcpu->arch.fault_dar = hr->hdar;
184 vcpu->arch.fault_dsisr = hr->hdsisr;
185 vcpu->arch.fault_gpa = hr->asdr;
186 vcpu->arch.emul_inst = hr->heir;
187 vcpu->arch.shregs.srr0 = hr->srr0;
188 vcpu->arch.shregs.srr1 = hr->srr1;
189 vcpu->arch.shregs.sprg0 = hr->sprg[0];
190 vcpu->arch.shregs.sprg1 = hr->sprg[1];
191 vcpu->arch.shregs.sprg2 = hr->sprg[2];
192 vcpu->arch.shregs.sprg3 = hr->sprg[3];
193 vcpu->arch.pid = hr->pidr;
194 vcpu->arch.cfar = hr->cfar;
195 vcpu->arch.ppr = hr->ppr;
196}
197
198long kvmhv_enter_nested_guest(struct kvm_vcpu *vcpu)
199{
200 long int err, r;
201 struct kvm_nested_guest *l2;
202 struct pt_regs l2_regs, saved_l1_regs;
203 struct hv_guest_state l2_hv, saved_l1_hv;
204 struct kvmppc_vcore *vc = vcpu->arch.vcore;
205 u64 hv_ptr, regs_ptr;
206 u64 hdec_exp;
207 s64 delta_purr, delta_spurr, delta_ic, delta_vtb;
208 u64 mask;
209 unsigned long lpcr;
210
211 if (vcpu->kvm->arch.l1_ptcr == 0)
212 return H_NOT_AVAILABLE;
213
214 /* copy parameters in */
215 hv_ptr = kvmppc_get_gpr(vcpu, 4);
216 err = kvm_vcpu_read_guest(vcpu, hv_ptr, &l2_hv,
217 sizeof(struct hv_guest_state));
218 if (err)
219 return H_PARAMETER;
220 if (kvmppc_need_byteswap(vcpu))
221 byteswap_hv_regs(&l2_hv);
222 if (l2_hv.version != HV_GUEST_STATE_VERSION)
223 return H_P2;
224
225 regs_ptr = kvmppc_get_gpr(vcpu, 5);
226 err = kvm_vcpu_read_guest(vcpu, regs_ptr, &l2_regs,
227 sizeof(struct pt_regs));
228 if (err)
229 return H_PARAMETER;
230 if (kvmppc_need_byteswap(vcpu))
231 byteswap_pt_regs(&l2_regs);
232 if (l2_hv.vcpu_token >= NR_CPUS)
233 return H_PARAMETER;
234
235 /* translate lpid */
236 l2 = kvmhv_get_nested(vcpu->kvm, l2_hv.lpid, true);
237 if (!l2)
238 return H_PARAMETER;
239 if (!l2->l1_gr_to_hr) {
240 mutex_lock(&l2->tlb_lock);
241 kvmhv_update_ptbl_cache(l2);
242 mutex_unlock(&l2->tlb_lock);
243 }
244
245 /* save l1 values of things */
246 vcpu->arch.regs.msr = vcpu->arch.shregs.msr;
247 saved_l1_regs = vcpu->arch.regs;
248 kvmhv_save_hv_regs(vcpu, &saved_l1_hv);
249
250 /* convert TB values/offsets to host (L0) values */
251 hdec_exp = l2_hv.hdec_expiry - vc->tb_offset;
252 vc->tb_offset += l2_hv.tb_offset;
253
254 /* set L1 state to L2 state */
255 vcpu->arch.nested = l2;
256 vcpu->arch.nested_vcpu_id = l2_hv.vcpu_token;
257 vcpu->arch.regs = l2_regs;
258 vcpu->arch.shregs.msr = vcpu->arch.regs.msr;
259 mask = LPCR_DPFD | LPCR_ILE | LPCR_TC | LPCR_AIL | LPCR_LD |
260 LPCR_LPES | LPCR_MER;
261 lpcr = (vc->lpcr & ~mask) | (l2_hv.lpcr & mask);
262 sanitise_hv_regs(vcpu, &l2_hv);
263 restore_hv_regs(vcpu, &l2_hv);
264
265 vcpu->arch.ret = RESUME_GUEST;
266 vcpu->arch.trap = 0;
267 do {
268 if (mftb() >= hdec_exp) {
269 vcpu->arch.trap = BOOK3S_INTERRUPT_HV_DECREMENTER;
270 r = RESUME_HOST;
271 break;
272 }
273 r = kvmhv_run_single_vcpu(vcpu->arch.kvm_run, vcpu, hdec_exp,
274 lpcr);
275 } while (is_kvmppc_resume_guest(r));
276
277 /* save L2 state for return */
278 l2_regs = vcpu->arch.regs;
279 l2_regs.msr = vcpu->arch.shregs.msr;
280 delta_purr = vcpu->arch.purr - l2_hv.purr;
281 delta_spurr = vcpu->arch.spurr - l2_hv.spurr;
282 delta_ic = vcpu->arch.ic - l2_hv.ic;
283 delta_vtb = vc->vtb - l2_hv.vtb;
284 save_hv_return_state(vcpu, vcpu->arch.trap, &l2_hv);
285
286 /* restore L1 state */
287 vcpu->arch.nested = NULL;
288 vcpu->arch.regs = saved_l1_regs;
289 vcpu->arch.shregs.msr = saved_l1_regs.msr & ~MSR_TS_MASK;
290 /* set L1 MSR TS field according to L2 transaction state */
291 if (l2_regs.msr & MSR_TS_MASK)
292 vcpu->arch.shregs.msr |= MSR_TS_S;
293 vc->tb_offset = saved_l1_hv.tb_offset;
294 restore_hv_regs(vcpu, &saved_l1_hv);
295 vcpu->arch.purr += delta_purr;
296 vcpu->arch.spurr += delta_spurr;
297 vcpu->arch.ic += delta_ic;
298 vc->vtb += delta_vtb;
299
300 kvmhv_put_nested(l2);
301
302 /* copy l2_hv_state and regs back to guest */
303 if (kvmppc_need_byteswap(vcpu)) {
304 byteswap_hv_regs(&l2_hv);
305 byteswap_pt_regs(&l2_regs);
306 }
307 err = kvm_vcpu_write_guest(vcpu, hv_ptr, &l2_hv,
308 sizeof(struct hv_guest_state));
309 if (err)
310 return H_AUTHORITY;
311 err = kvm_vcpu_write_guest(vcpu, regs_ptr, &l2_regs,
312 sizeof(struct pt_regs));
313 if (err)
314 return H_AUTHORITY;
315
316 if (r == -EINTR)
317 return H_INTERRUPT;
318
319 return vcpu->arch.trap;
320}
321
322long kvmhv_nested_init(void)
323{
324 long int ptb_order;
325 unsigned long ptcr;
326 long rc;
327
328 if (!kvmhv_on_pseries())
329 return 0;
330 if (!radix_enabled())
331 return -ENODEV;
332
333 /* find log base 2 of KVMPPC_NR_LPIDS, rounding up */
334 ptb_order = __ilog2(KVMPPC_NR_LPIDS - 1) + 1;
335 if (ptb_order < 8)
336 ptb_order = 8;
337 pseries_partition_tb = kmalloc(sizeof(struct patb_entry) << ptb_order,
338 GFP_KERNEL);
339 if (!pseries_partition_tb) {
340 pr_err("kvm-hv: failed to allocated nested partition table\n");
341 return -ENOMEM;
342 }
343
344 ptcr = __pa(pseries_partition_tb) | (ptb_order - 8);
345 rc = plpar_hcall_norets(H_SET_PARTITION_TABLE, ptcr);
346 if (rc != H_SUCCESS) {
347 pr_err("kvm-hv: Parent hypervisor does not support nesting (rc=%ld)\n",
348 rc);
349 kfree(pseries_partition_tb);
350 pseries_partition_tb = NULL;
351 return -ENODEV;
352 }
353
354 return 0;
355}
356
357void kvmhv_nested_exit(void)
358{
359 /*
360 * N.B. the kvmhv_on_pseries() test is there because it enables
361 * the compiler to remove the call to plpar_hcall_norets()
362 * when CONFIG_PPC_PSERIES=n.
363 */
364 if (kvmhv_on_pseries() && pseries_partition_tb) {
365 plpar_hcall_norets(H_SET_PARTITION_TABLE, 0);
366 kfree(pseries_partition_tb);
367 pseries_partition_tb = NULL;
368 }
369}
370
371static void kvmhv_flush_lpid(unsigned int lpid)
372{
373 long rc;
374
375 if (!kvmhv_on_pseries()) {
376 radix__flush_tlb_lpid(lpid);
377 return;
378 }
379
380 rc = plpar_hcall_norets(H_TLB_INVALIDATE, H_TLBIE_P1_ENC(2, 0, 1),
381 lpid, TLBIEL_INVAL_SET_LPID);
382 if (rc)
383 pr_err("KVM: TLB LPID invalidation hcall failed, rc=%ld\n", rc);
384}
385
386void kvmhv_set_ptbl_entry(unsigned int lpid, u64 dw0, u64 dw1)
387{
388 if (!kvmhv_on_pseries()) {
389 mmu_partition_table_set_entry(lpid, dw0, dw1);
390 return;
391 }
392
393 pseries_partition_tb[lpid].patb0 = cpu_to_be64(dw0);
394 pseries_partition_tb[lpid].patb1 = cpu_to_be64(dw1);
395 /* L0 will do the necessary barriers */
396 kvmhv_flush_lpid(lpid);
397}
398
399static void kvmhv_set_nested_ptbl(struct kvm_nested_guest *gp)
400{
401 unsigned long dw0;
402
403 dw0 = PATB_HR | radix__get_tree_size() |
404 __pa(gp->shadow_pgtable) | RADIX_PGD_INDEX_SIZE;
405 kvmhv_set_ptbl_entry(gp->shadow_lpid, dw0, gp->process_table);
406}
407
408void kvmhv_vm_nested_init(struct kvm *kvm)
409{
410 kvm->arch.max_nested_lpid = -1;
411}
412
413/*
414 * Handle the H_SET_PARTITION_TABLE hcall.
415 * r4 = guest real address of partition table + log_2(size) - 12
416 * (formatted as for the PTCR).
417 */
418long kvmhv_set_partition_table(struct kvm_vcpu *vcpu)
419{
420 struct kvm *kvm = vcpu->kvm;
421 unsigned long ptcr = kvmppc_get_gpr(vcpu, 4);
422 int srcu_idx;
423 long ret = H_SUCCESS;
424
425 srcu_idx = srcu_read_lock(&kvm->srcu);
426 /*
427 * Limit the partition table to 4096 entries (because that's what
428 * hardware supports), and check the base address.
429 */
430 if ((ptcr & PRTS_MASK) > 12 - 8 ||
431 !kvm_is_visible_gfn(vcpu->kvm, (ptcr & PRTB_MASK) >> PAGE_SHIFT))
432 ret = H_PARAMETER;
433 srcu_read_unlock(&kvm->srcu, srcu_idx);
434 if (ret == H_SUCCESS)
435 kvm->arch.l1_ptcr = ptcr;
436 return ret;
437}
438
439/*
440 * Reload the partition table entry for a guest.
441 * Caller must hold gp->tlb_lock.
442 */
443static void kvmhv_update_ptbl_cache(struct kvm_nested_guest *gp)
444{
445 int ret;
446 struct patb_entry ptbl_entry;
447 unsigned long ptbl_addr;
448 struct kvm *kvm = gp->l1_host;
449
450 ret = -EFAULT;
451 ptbl_addr = (kvm->arch.l1_ptcr & PRTB_MASK) + (gp->l1_lpid << 4);
452 if (gp->l1_lpid < (1ul << ((kvm->arch.l1_ptcr & PRTS_MASK) + 8)))
453 ret = kvm_read_guest(kvm, ptbl_addr,
454 &ptbl_entry, sizeof(ptbl_entry));
455 if (ret) {
456 gp->l1_gr_to_hr = 0;
457 gp->process_table = 0;
458 } else {
459 gp->l1_gr_to_hr = be64_to_cpu(ptbl_entry.patb0);
460 gp->process_table = be64_to_cpu(ptbl_entry.patb1);
461 }
462 kvmhv_set_nested_ptbl(gp);
463}
464
465struct kvm_nested_guest *kvmhv_alloc_nested(struct kvm *kvm, unsigned int lpid)
466{
467 struct kvm_nested_guest *gp;
468 long shadow_lpid;
469
470 gp = kzalloc(sizeof(*gp), GFP_KERNEL);
471 if (!gp)
472 return NULL;
473 gp->l1_host = kvm;
474 gp->l1_lpid = lpid;
475 mutex_init(&gp->tlb_lock);
476 gp->shadow_pgtable = pgd_alloc(kvm->mm);
477 if (!gp->shadow_pgtable)
478 goto out_free;
479 shadow_lpid = kvmppc_alloc_lpid();
480 if (shadow_lpid < 0)
481 goto out_free2;
482 gp->shadow_lpid = shadow_lpid;
483
484 memset(gp->prev_cpu, -1, sizeof(gp->prev_cpu));
485
486 return gp;
487
488 out_free2:
489 pgd_free(kvm->mm, gp->shadow_pgtable);
490 out_free:
491 kfree(gp);
492 return NULL;
493}
494
495/*
496 * Free up any resources allocated for a nested guest.
497 */
498static void kvmhv_release_nested(struct kvm_nested_guest *gp)
499{
500 struct kvm *kvm = gp->l1_host;
501
502 if (gp->shadow_pgtable) {
503 /*
504 * No vcpu is using this struct and no call to
505 * kvmhv_get_nested can find this struct,
506 * so we don't need to hold kvm->mmu_lock.
507 */
508 kvmppc_free_pgtable_radix(kvm, gp->shadow_pgtable,
509 gp->shadow_lpid);
510 pgd_free(kvm->mm, gp->shadow_pgtable);
511 }
512 kvmhv_set_ptbl_entry(gp->shadow_lpid, 0, 0);
513 kvmppc_free_lpid(gp->shadow_lpid);
514 kfree(gp);
515}
516
517static void kvmhv_remove_nested(struct kvm_nested_guest *gp)
518{
519 struct kvm *kvm = gp->l1_host;
520 int lpid = gp->l1_lpid;
521 long ref;
522
523 spin_lock(&kvm->mmu_lock);
524 if (gp == kvm->arch.nested_guests[lpid]) {
525 kvm->arch.nested_guests[lpid] = NULL;
526 if (lpid == kvm->arch.max_nested_lpid) {
527 while (--lpid >= 0 && !kvm->arch.nested_guests[lpid])
528 ;
529 kvm->arch.max_nested_lpid = lpid;
530 }
531 --gp->refcnt;
532 }
533 ref = gp->refcnt;
534 spin_unlock(&kvm->mmu_lock);
535 if (ref == 0)
536 kvmhv_release_nested(gp);
537}
538
539/*
540 * Free up all nested resources allocated for this guest.
541 * This is called with no vcpus of the guest running, when
542 * switching the guest to HPT mode or when destroying the
543 * guest.
544 */
545void kvmhv_release_all_nested(struct kvm *kvm)
546{
547 int i;
548 struct kvm_nested_guest *gp;
549 struct kvm_nested_guest *freelist = NULL;
550 struct kvm_memory_slot *memslot;
551 int srcu_idx;
552
553 spin_lock(&kvm->mmu_lock);
554 for (i = 0; i <= kvm->arch.max_nested_lpid; i++) {
555 gp = kvm->arch.nested_guests[i];
556 if (!gp)
557 continue;
558 kvm->arch.nested_guests[i] = NULL;
559 if (--gp->refcnt == 0) {
560 gp->next = freelist;
561 freelist = gp;
562 }
563 }
564 kvm->arch.max_nested_lpid = -1;
565 spin_unlock(&kvm->mmu_lock);
566 while ((gp = freelist) != NULL) {
567 freelist = gp->next;
568 kvmhv_release_nested(gp);
569 }
570
571 srcu_idx = srcu_read_lock(&kvm->srcu);
572 kvm_for_each_memslot(memslot, kvm_memslots(kvm))
573 kvmhv_free_memslot_nest_rmap(memslot);
574 srcu_read_unlock(&kvm->srcu, srcu_idx);
575}
576
577/* caller must hold gp->tlb_lock */
578static void kvmhv_flush_nested(struct kvm_nested_guest *gp)
579{
580 struct kvm *kvm = gp->l1_host;
581
582 spin_lock(&kvm->mmu_lock);
583 kvmppc_free_pgtable_radix(kvm, gp->shadow_pgtable, gp->shadow_lpid);
584 spin_unlock(&kvm->mmu_lock);
585 kvmhv_flush_lpid(gp->shadow_lpid);
586 kvmhv_update_ptbl_cache(gp);
587 if (gp->l1_gr_to_hr == 0)
588 kvmhv_remove_nested(gp);
589}
590
591struct kvm_nested_guest *kvmhv_get_nested(struct kvm *kvm, int l1_lpid,
592 bool create)
593{
594 struct kvm_nested_guest *gp, *newgp;
595
596 if (l1_lpid >= KVM_MAX_NESTED_GUESTS ||
597 l1_lpid >= (1ul << ((kvm->arch.l1_ptcr & PRTS_MASK) + 12 - 4)))
598 return NULL;
599
600 spin_lock(&kvm->mmu_lock);
601 gp = kvm->arch.nested_guests[l1_lpid];
602 if (gp)
603 ++gp->refcnt;
604 spin_unlock(&kvm->mmu_lock);
605
606 if (gp || !create)
607 return gp;
608
609 newgp = kvmhv_alloc_nested(kvm, l1_lpid);
610 if (!newgp)
611 return NULL;
612 spin_lock(&kvm->mmu_lock);
613 if (kvm->arch.nested_guests[l1_lpid]) {
614 /* someone else beat us to it */
615 gp = kvm->arch.nested_guests[l1_lpid];
616 } else {
617 kvm->arch.nested_guests[l1_lpid] = newgp;
618 ++newgp->refcnt;
619 gp = newgp;
620 newgp = NULL;
621 if (l1_lpid > kvm->arch.max_nested_lpid)
622 kvm->arch.max_nested_lpid = l1_lpid;
623 }
624 ++gp->refcnt;
625 spin_unlock(&kvm->mmu_lock);
626
627 if (newgp)
628 kvmhv_release_nested(newgp);
629
630 return gp;
631}
632
633void kvmhv_put_nested(struct kvm_nested_guest *gp)
634{
635 struct kvm *kvm = gp->l1_host;
636 long ref;
637
638 spin_lock(&kvm->mmu_lock);
639 ref = --gp->refcnt;
640 spin_unlock(&kvm->mmu_lock);
641 if (ref == 0)
642 kvmhv_release_nested(gp);
643}
644
645static struct kvm_nested_guest *kvmhv_find_nested(struct kvm *kvm, int lpid)
646{
647 if (lpid > kvm->arch.max_nested_lpid)
648 return NULL;
649 return kvm->arch.nested_guests[lpid];
650}
651
652static inline bool kvmhv_n_rmap_is_equal(u64 rmap_1, u64 rmap_2)
653{
654 return !((rmap_1 ^ rmap_2) & (RMAP_NESTED_LPID_MASK |
655 RMAP_NESTED_GPA_MASK));
656}
657
658void kvmhv_insert_nest_rmap(struct kvm *kvm, unsigned long *rmapp,
659 struct rmap_nested **n_rmap)
660{
661 struct llist_node *entry = ((struct llist_head *) rmapp)->first;
662 struct rmap_nested *cursor;
663 u64 rmap, new_rmap = (*n_rmap)->rmap;
664
665 /* Are there any existing entries? */
666 if (!(*rmapp)) {
667 /* No -> use the rmap as a single entry */
668 *rmapp = new_rmap | RMAP_NESTED_IS_SINGLE_ENTRY;
669 return;
670 }
671
672 /* Do any entries match what we're trying to insert? */
673 for_each_nest_rmap_safe(cursor, entry, &rmap) {
674 if (kvmhv_n_rmap_is_equal(rmap, new_rmap))
675 return;
676 }
677
678 /* Do we need to create a list or just add the new entry? */
679 rmap = *rmapp;
680 if (rmap & RMAP_NESTED_IS_SINGLE_ENTRY) /* Not previously a list */
681 *rmapp = 0UL;
682 llist_add(&((*n_rmap)->list), (struct llist_head *) rmapp);
683 if (rmap & RMAP_NESTED_IS_SINGLE_ENTRY) /* Not previously a list */
684 (*n_rmap)->list.next = (struct llist_node *) rmap;
685
686 /* Set NULL so not freed by caller */
687 *n_rmap = NULL;
688}
689
690static void kvmhv_remove_nest_rmap(struct kvm *kvm, u64 n_rmap,
691 unsigned long hpa, unsigned long mask)
692{
693 struct kvm_nested_guest *gp;
694 unsigned long gpa;
695 unsigned int shift, lpid;
696 pte_t *ptep;
697
698 gpa = n_rmap & RMAP_NESTED_GPA_MASK;
699 lpid = (n_rmap & RMAP_NESTED_LPID_MASK) >> RMAP_NESTED_LPID_SHIFT;
700 gp = kvmhv_find_nested(kvm, lpid);
701 if (!gp)
702 return;
703
704 /* Find and invalidate the pte */
705 ptep = __find_linux_pte(gp->shadow_pgtable, gpa, NULL, &shift);
706 /* Don't spuriously invalidate ptes if the pfn has changed */
707 if (ptep && pte_present(*ptep) && ((pte_val(*ptep) & mask) == hpa))
708 kvmppc_unmap_pte(kvm, ptep, gpa, shift, NULL, gp->shadow_lpid);
709}
710
711static void kvmhv_remove_nest_rmap_list(struct kvm *kvm, unsigned long *rmapp,
712 unsigned long hpa, unsigned long mask)
713{
714 struct llist_node *entry = llist_del_all((struct llist_head *) rmapp);
715 struct rmap_nested *cursor;
716 unsigned long rmap;
717
718 for_each_nest_rmap_safe(cursor, entry, &rmap) {
719 kvmhv_remove_nest_rmap(kvm, rmap, hpa, mask);
720 kfree(cursor);
721 }
722}
723
724/* called with kvm->mmu_lock held */
725void kvmhv_remove_nest_rmap_range(struct kvm *kvm,
726 struct kvm_memory_slot *memslot,
727 unsigned long gpa, unsigned long hpa,
728 unsigned long nbytes)
729{
730 unsigned long gfn, end_gfn;
731 unsigned long addr_mask;
732
733 if (!memslot)
734 return;
735 gfn = (gpa >> PAGE_SHIFT) - memslot->base_gfn;
736 end_gfn = gfn + (nbytes >> PAGE_SHIFT);
737
738 addr_mask = PTE_RPN_MASK & ~(nbytes - 1);
739 hpa &= addr_mask;
740
741 for (; gfn < end_gfn; gfn++) {
742 unsigned long *rmap = &memslot->arch.rmap[gfn];
743 kvmhv_remove_nest_rmap_list(kvm, rmap, hpa, addr_mask);
744 }
745}
746
747static void kvmhv_free_memslot_nest_rmap(struct kvm_memory_slot *free)
748{
749 unsigned long page;
750
751 for (page = 0; page < free->npages; page++) {
752 unsigned long rmap, *rmapp = &free->arch.rmap[page];
753 struct rmap_nested *cursor;
754 struct llist_node *entry;
755
756 entry = llist_del_all((struct llist_head *) rmapp);
757 for_each_nest_rmap_safe(cursor, entry, &rmap)
758 kfree(cursor);
759 }
760}
761
762static bool kvmhv_invalidate_shadow_pte(struct kvm_vcpu *vcpu,
763 struct kvm_nested_guest *gp,
764 long gpa, int *shift_ret)
765{
766 struct kvm *kvm = vcpu->kvm;
767 bool ret = false;
768 pte_t *ptep;
769 int shift;
770
771 spin_lock(&kvm->mmu_lock);
772 ptep = __find_linux_pte(gp->shadow_pgtable, gpa, NULL, &shift);
773 if (!shift)
774 shift = PAGE_SHIFT;
775 if (ptep && pte_present(*ptep)) {
776 kvmppc_unmap_pte(kvm, ptep, gpa, shift, NULL, gp->shadow_lpid);
777 ret = true;
778 }
779 spin_unlock(&kvm->mmu_lock);
780
781 if (shift_ret)
782 *shift_ret = shift;
783 return ret;
784}
785
786static inline int get_ric(unsigned int instr)
787{
788 return (instr >> 18) & 0x3;
789}
790
791static inline int get_prs(unsigned int instr)
792{
793 return (instr >> 17) & 0x1;
794}
795
796static inline int get_r(unsigned int instr)
797{
798 return (instr >> 16) & 0x1;
799}
800
801static inline int get_lpid(unsigned long r_val)
802{
803 return r_val & 0xffffffff;
804}
805
806static inline int get_is(unsigned long r_val)
807{
808 return (r_val >> 10) & 0x3;
809}
810
811static inline int get_ap(unsigned long r_val)
812{
813 return (r_val >> 5) & 0x7;
814}
815
816static inline long get_epn(unsigned long r_val)
817{
818 return r_val >> 12;
819}
820
821static int kvmhv_emulate_tlbie_tlb_addr(struct kvm_vcpu *vcpu, int lpid,
822 int ap, long epn)
823{
824 struct kvm *kvm = vcpu->kvm;
825 struct kvm_nested_guest *gp;
826 long npages;
827 int shift, shadow_shift;
828 unsigned long addr;
829
830 shift = ap_to_shift(ap);
831 addr = epn << 12;
832 if (shift < 0)
833 /* Invalid ap encoding */
834 return -EINVAL;
835
836 addr &= ~((1UL << shift) - 1);
837 npages = 1UL << (shift - PAGE_SHIFT);
838
839 gp = kvmhv_get_nested(kvm, lpid, false);
840 if (!gp) /* No such guest -> nothing to do */
841 return 0;
842 mutex_lock(&gp->tlb_lock);
843
844 /* There may be more than one host page backing this single guest pte */
845 do {
846 kvmhv_invalidate_shadow_pte(vcpu, gp, addr, &shadow_shift);
847
848 npages -= 1UL << (shadow_shift - PAGE_SHIFT);
849 addr += 1UL << shadow_shift;
850 } while (npages > 0);
851
852 mutex_unlock(&gp->tlb_lock);
853 kvmhv_put_nested(gp);
854 return 0;
855}
856
857static void kvmhv_emulate_tlbie_lpid(struct kvm_vcpu *vcpu,
858 struct kvm_nested_guest *gp, int ric)
859{
860 struct kvm *kvm = vcpu->kvm;
861
862 mutex_lock(&gp->tlb_lock);
863 switch (ric) {
864 case 0:
865 /* Invalidate TLB */
866 spin_lock(&kvm->mmu_lock);
867 kvmppc_free_pgtable_radix(kvm, gp->shadow_pgtable,
868 gp->shadow_lpid);
869 kvmhv_flush_lpid(gp->shadow_lpid);
870 spin_unlock(&kvm->mmu_lock);
871 break;
872 case 1:
873 /*
874 * Invalidate PWC
875 * We don't cache this -> nothing to do
876 */
877 break;
878 case 2:
879 /* Invalidate TLB, PWC and caching of partition table entries */
880 kvmhv_flush_nested(gp);
881 break;
882 default:
883 break;
884 }
885 mutex_unlock(&gp->tlb_lock);
886}
887
888static void kvmhv_emulate_tlbie_all_lpid(struct kvm_vcpu *vcpu, int ric)
889{
890 struct kvm *kvm = vcpu->kvm;
891 struct kvm_nested_guest *gp;
892 int i;
893
894 spin_lock(&kvm->mmu_lock);
895 for (i = 0; i <= kvm->arch.max_nested_lpid; i++) {
896 gp = kvm->arch.nested_guests[i];
897 if (gp) {
898 spin_unlock(&kvm->mmu_lock);
899 kvmhv_emulate_tlbie_lpid(vcpu, gp, ric);
900 spin_lock(&kvm->mmu_lock);
901 }
902 }
903 spin_unlock(&kvm->mmu_lock);
904}
905
906static int kvmhv_emulate_priv_tlbie(struct kvm_vcpu *vcpu, unsigned int instr,
907 unsigned long rsval, unsigned long rbval)
908{
909 struct kvm *kvm = vcpu->kvm;
910 struct kvm_nested_guest *gp;
911 int r, ric, prs, is, ap;
912 int lpid;
913 long epn;
914 int ret = 0;
915
916 ric = get_ric(instr);
917 prs = get_prs(instr);
918 r = get_r(instr);
919 lpid = get_lpid(rsval);
920 is = get_is(rbval);
921
922 /*
923 * These cases are invalid and are not handled:
924 * r != 1 -> Only radix supported
925 * prs == 1 -> Not HV privileged
926 * ric == 3 -> No cluster bombs for radix
927 * is == 1 -> Partition scoped translations not associated with pid
928 * (!is) && (ric == 1 || ric == 2) -> Not supported by ISA
929 */
930 if ((!r) || (prs) || (ric == 3) || (is == 1) ||
931 ((!is) && (ric == 1 || ric == 2)))
932 return -EINVAL;
933
934 switch (is) {
935 case 0:
936 /*
937 * We know ric == 0
938 * Invalidate TLB for a given target address
939 */
940 epn = get_epn(rbval);
941 ap = get_ap(rbval);
942 ret = kvmhv_emulate_tlbie_tlb_addr(vcpu, lpid, ap, epn);
943 break;
944 case 2:
945 /* Invalidate matching LPID */
946 gp = kvmhv_get_nested(kvm, lpid, false);
947 if (gp) {
948 kvmhv_emulate_tlbie_lpid(vcpu, gp, ric);
949 kvmhv_put_nested(gp);
950 }
951 break;
952 case 3:
953 /* Invalidate ALL LPIDs */
954 kvmhv_emulate_tlbie_all_lpid(vcpu, ric);
955 break;
956 default:
957 ret = -EINVAL;
958 break;
959 }
960
961 return ret;
962}
963
964/*
965 * This handles the H_TLB_INVALIDATE hcall.
966 * Parameters are (r4) tlbie instruction code, (r5) rS contents,
967 * (r6) rB contents.
968 */
969long kvmhv_do_nested_tlbie(struct kvm_vcpu *vcpu)
970{
971 int ret;
972
973 ret = kvmhv_emulate_priv_tlbie(vcpu, kvmppc_get_gpr(vcpu, 4),
974 kvmppc_get_gpr(vcpu, 5), kvmppc_get_gpr(vcpu, 6));
975 if (ret)
976 return H_PARAMETER;
977 return H_SUCCESS;
978}
979
980/* Used to convert a nested guest real address to a L1 guest real address */
981static int kvmhv_translate_addr_nested(struct kvm_vcpu *vcpu,
982 struct kvm_nested_guest *gp,
983 unsigned long n_gpa, unsigned long dsisr,
984 struct kvmppc_pte *gpte_p)
985{
986 u64 fault_addr, flags = dsisr & DSISR_ISSTORE;
987 int ret;
988
989 ret = kvmppc_mmu_walk_radix_tree(vcpu, n_gpa, gpte_p, gp->l1_gr_to_hr,
990 &fault_addr);
991
992 if (ret) {
993 /* We didn't find a pte */
994 if (ret == -EINVAL) {
995 /* Unsupported mmu config */
996 flags |= DSISR_UNSUPP_MMU;
997 } else if (ret == -ENOENT) {
998 /* No translation found */
999 flags |= DSISR_NOHPTE;
1000 } else if (ret == -EFAULT) {
1001 /* Couldn't access L1 real address */
1002 flags |= DSISR_PRTABLE_FAULT;
1003 vcpu->arch.fault_gpa = fault_addr;
1004 } else {
1005 /* Unknown error */
1006 return ret;
1007 }
1008 goto forward_to_l1;
1009 } else {
1010 /* We found a pte -> check permissions */
1011 if (dsisr & DSISR_ISSTORE) {
1012 /* Can we write? */
1013 if (!gpte_p->may_write) {
1014 flags |= DSISR_PROTFAULT;
1015 goto forward_to_l1;
1016 }
1017 } else if (vcpu->arch.trap == BOOK3S_INTERRUPT_H_INST_STORAGE) {
1018 /* Can we execute? */
1019 if (!gpte_p->may_execute) {
1020 flags |= SRR1_ISI_N_OR_G;
1021 goto forward_to_l1;
1022 }
1023 } else {
1024 /* Can we read? */
1025 if (!gpte_p->may_read && !gpte_p->may_write) {
1026 flags |= DSISR_PROTFAULT;
1027 goto forward_to_l1;
1028 }
1029 }
1030 }
1031
1032 return 0;
1033
1034forward_to_l1:
1035 vcpu->arch.fault_dsisr = flags;
1036 if (vcpu->arch.trap == BOOK3S_INTERRUPT_H_INST_STORAGE) {
1037 vcpu->arch.shregs.msr &= ~0x783f0000ul;
1038 vcpu->arch.shregs.msr |= flags;
1039 }
1040 return RESUME_HOST;
1041}
1042
1043static long kvmhv_handle_nested_set_rc(struct kvm_vcpu *vcpu,
1044 struct kvm_nested_guest *gp,
1045 unsigned long n_gpa,
1046 struct kvmppc_pte gpte,
1047 unsigned long dsisr)
1048{
1049 struct kvm *kvm = vcpu->kvm;
1050 bool writing = !!(dsisr & DSISR_ISSTORE);
1051 u64 pgflags;
1052 bool ret;
1053
1054 /* Are the rc bits set in the L1 partition scoped pte? */
1055 pgflags = _PAGE_ACCESSED;
1056 if (writing)
1057 pgflags |= _PAGE_DIRTY;
1058 if (pgflags & ~gpte.rc)
1059 return RESUME_HOST;
1060
1061 spin_lock(&kvm->mmu_lock);
1062 /* Set the rc bit in the pte of our (L0) pgtable for the L1 guest */
1063 ret = kvmppc_hv_handle_set_rc(kvm, kvm->arch.pgtable, writing,
1064 gpte.raddr, kvm->arch.lpid);
1065 spin_unlock(&kvm->mmu_lock);
1066 if (!ret)
1067 return -EINVAL;
1068
1069 /* Set the rc bit in the pte of the shadow_pgtable for the nest guest */
1070 ret = kvmppc_hv_handle_set_rc(kvm, gp->shadow_pgtable, writing, n_gpa,
1071 gp->shadow_lpid);
1072 if (!ret)
1073 return -EINVAL;
1074 return 0;
1075}
1076
1077static inline int kvmppc_radix_level_to_shift(int level)
1078{
1079 switch (level) {
1080 case 2:
1081 return PUD_SHIFT;
1082 case 1:
1083 return PMD_SHIFT;
1084 default:
1085 return PAGE_SHIFT;
1086 }
1087}
1088
1089static inline int kvmppc_radix_shift_to_level(int shift)
1090{
1091 if (shift == PUD_SHIFT)
1092 return 2;
1093 if (shift == PMD_SHIFT)
1094 return 1;
1095 if (shift == PAGE_SHIFT)
1096 return 0;
1097 WARN_ON_ONCE(1);
1098 return 0;
1099}
1100
1101/* called with gp->tlb_lock held */
1102static long int __kvmhv_nested_page_fault(struct kvm_vcpu *vcpu,
1103 struct kvm_nested_guest *gp)
1104{
1105 struct kvm *kvm = vcpu->kvm;
1106 struct kvm_memory_slot *memslot;
1107 struct rmap_nested *n_rmap;
1108 struct kvmppc_pte gpte;
1109 pte_t pte, *pte_p;
1110 unsigned long mmu_seq;
1111 unsigned long dsisr = vcpu->arch.fault_dsisr;
1112 unsigned long ea = vcpu->arch.fault_dar;
1113 unsigned long *rmapp;
1114 unsigned long n_gpa, gpa, gfn, perm = 0UL;
1115 unsigned int shift, l1_shift, level;
1116 bool writing = !!(dsisr & DSISR_ISSTORE);
1117 bool kvm_ro = false;
1118 long int ret;
1119
1120 if (!gp->l1_gr_to_hr) {
1121 kvmhv_update_ptbl_cache(gp);
1122 if (!gp->l1_gr_to_hr)
1123 return RESUME_HOST;
1124 }
1125
1126 /* Convert the nested guest real address into a L1 guest real address */
1127
1128 n_gpa = vcpu->arch.fault_gpa & ~0xF000000000000FFFULL;
1129 if (!(dsisr & DSISR_PRTABLE_FAULT))
1130 n_gpa |= ea & 0xFFF;
1131 ret = kvmhv_translate_addr_nested(vcpu, gp, n_gpa, dsisr, &gpte);
1132
1133 /*
1134 * If the hardware found a translation but we don't now have a usable
1135 * translation in the l1 partition-scoped tree, remove the shadow pte
1136 * and let the guest retry.
1137 */
1138 if (ret == RESUME_HOST &&
1139 (dsisr & (DSISR_PROTFAULT | DSISR_BADACCESS | DSISR_NOEXEC_OR_G |
1140 DSISR_BAD_COPYPASTE)))
1141 goto inval;
1142 if (ret)
1143 return ret;
1144
1145 /* Failed to set the reference/change bits */
1146 if (dsisr & DSISR_SET_RC) {
1147 ret = kvmhv_handle_nested_set_rc(vcpu, gp, n_gpa, gpte, dsisr);
1148 if (ret == RESUME_HOST)
1149 return ret;
1150 if (ret)
1151 goto inval;
1152 dsisr &= ~DSISR_SET_RC;
1153 if (!(dsisr & (DSISR_BAD_FAULT_64S | DSISR_NOHPTE |
1154 DSISR_PROTFAULT)))
1155 return RESUME_GUEST;
1156 }
1157
1158 /*
1159 * We took an HISI or HDSI while we were running a nested guest which
1160 * means we have no partition scoped translation for that. This means
1161 * we need to insert a pte for the mapping into our shadow_pgtable.
1162 */
1163
1164 l1_shift = gpte.page_shift;
1165 if (l1_shift < PAGE_SHIFT) {
1166 /* We don't support l1 using a page size smaller than our own */
1167 pr_err("KVM: L1 guest page shift (%d) less than our own (%d)\n",
1168 l1_shift, PAGE_SHIFT);
1169 return -EINVAL;
1170 }
1171 gpa = gpte.raddr;
1172 gfn = gpa >> PAGE_SHIFT;
1173
1174 /* 1. Get the corresponding host memslot */
1175
1176 memslot = gfn_to_memslot(kvm, gfn);
1177 if (!memslot || (memslot->flags & KVM_MEMSLOT_INVALID)) {
1178 if (dsisr & (DSISR_PRTABLE_FAULT | DSISR_BADACCESS)) {
1179 /* unusual error -> reflect to the guest as a DSI */
1180 kvmppc_core_queue_data_storage(vcpu, ea, dsisr);
1181 return RESUME_GUEST;
1182 }
1183 /* passthrough of emulated MMIO case... */
1184 pr_err("emulated MMIO passthrough?\n");
1185 return -EINVAL;
1186 }
1187 if (memslot->flags & KVM_MEM_READONLY) {
1188 if (writing) {
1189 /* Give the guest a DSI */
1190 kvmppc_core_queue_data_storage(vcpu, ea,
1191 DSISR_ISSTORE | DSISR_PROTFAULT);
1192 return RESUME_GUEST;
1193 }
1194 kvm_ro = true;
1195 }
1196
1197 /* 2. Find the host pte for this L1 guest real address */
1198
1199 /* Used to check for invalidations in progress */
1200 mmu_seq = kvm->mmu_notifier_seq;
1201 smp_rmb();
1202
1203 /* See if can find translation in our partition scoped tables for L1 */
1204 pte = __pte(0);
1205 spin_lock(&kvm->mmu_lock);
1206 pte_p = __find_linux_pte(kvm->arch.pgtable, gpa, NULL, &shift);
1207 if (!shift)
1208 shift = PAGE_SHIFT;
1209 if (pte_p)
1210 pte = *pte_p;
1211 spin_unlock(&kvm->mmu_lock);
1212
1213 if (!pte_present(pte) || (writing && !(pte_val(pte) & _PAGE_WRITE))) {
1214 /* No suitable pte found -> try to insert a mapping */
1215 ret = kvmppc_book3s_instantiate_page(vcpu, gpa, memslot,
1216 writing, kvm_ro, &pte, &level);
1217 if (ret == -EAGAIN)
1218 return RESUME_GUEST;
1219 else if (ret)
1220 return ret;
1221 shift = kvmppc_radix_level_to_shift(level);
1222 }
1223
1224 /* 3. Compute the pte we need to insert for nest_gpa -> host r_addr */
1225
1226 /* The permissions is the combination of the host and l1 guest ptes */
1227 perm |= gpte.may_read ? 0UL : _PAGE_READ;
1228 perm |= gpte.may_write ? 0UL : _PAGE_WRITE;
1229 perm |= gpte.may_execute ? 0UL : _PAGE_EXEC;
1230 pte = __pte(pte_val(pte) & ~perm);
1231
1232 /* What size pte can we insert? */
1233 if (shift > l1_shift) {
1234 u64 mask;
1235 unsigned int actual_shift = PAGE_SHIFT;
1236 if (PMD_SHIFT < l1_shift)
1237 actual_shift = PMD_SHIFT;
1238 mask = (1UL << shift) - (1UL << actual_shift);
1239 pte = __pte(pte_val(pte) | (gpa & mask));
1240 shift = actual_shift;
1241 }
1242 level = kvmppc_radix_shift_to_level(shift);
1243 n_gpa &= ~((1UL << shift) - 1);
1244
1245 /* 4. Insert the pte into our shadow_pgtable */
1246
1247 n_rmap = kzalloc(sizeof(*n_rmap), GFP_KERNEL);
1248 if (!n_rmap)
1249 return RESUME_GUEST; /* Let the guest try again */
1250 n_rmap->rmap = (n_gpa & RMAP_NESTED_GPA_MASK) |
1251 (((unsigned long) gp->l1_lpid) << RMAP_NESTED_LPID_SHIFT);
1252 rmapp = &memslot->arch.rmap[gfn - memslot->base_gfn];
1253 ret = kvmppc_create_pte(kvm, gp->shadow_pgtable, pte, n_gpa, level,
1254 mmu_seq, gp->shadow_lpid, rmapp, &n_rmap);
1255 if (n_rmap)
1256 kfree(n_rmap);
1257 if (ret == -EAGAIN)
1258 ret = RESUME_GUEST; /* Let the guest try again */
1259
1260 return ret;
1261
1262 inval:
1263 kvmhv_invalidate_shadow_pte(vcpu, gp, n_gpa, NULL);
1264 return RESUME_GUEST;
1265}
1266
1267long int kvmhv_nested_page_fault(struct kvm_vcpu *vcpu)
1268{
1269 struct kvm_nested_guest *gp = vcpu->arch.nested;
1270 long int ret;
1271
1272 mutex_lock(&gp->tlb_lock);
1273 ret = __kvmhv_nested_page_fault(vcpu, gp);
1274 mutex_unlock(&gp->tlb_lock);
1275 return ret;
1276}
1277
1278int kvmhv_nested_next_lpid(struct kvm *kvm, int lpid)
1279{
1280 int ret = -1;
1281
1282 spin_lock(&kvm->mmu_lock);
1283 while (++lpid <= kvm->arch.max_nested_lpid) {
1284 if (kvm->arch.nested_guests[lpid]) {
1285 ret = lpid;
1286 break;
1287 }
1288 }
1289 spin_unlock(&kvm->mmu_lock);
1290 return ret;
1291}
diff --git a/arch/powerpc/kvm/book3s_hv_ras.c b/arch/powerpc/kvm/book3s_hv_ras.c
index b11043b23c18..0787f12c1a1b 100644
--- a/arch/powerpc/kvm/book3s_hv_ras.c
+++ b/arch/powerpc/kvm/book3s_hv_ras.c
@@ -177,6 +177,7 @@ void kvmppc_subcore_enter_guest(void)
177 177
178 local_paca->sibling_subcore_state->in_guest[subcore_id] = 1; 178 local_paca->sibling_subcore_state->in_guest[subcore_id] = 1;
179} 179}
180EXPORT_SYMBOL_GPL(kvmppc_subcore_enter_guest);
180 181
181void kvmppc_subcore_exit_guest(void) 182void kvmppc_subcore_exit_guest(void)
182{ 183{
@@ -187,6 +188,7 @@ void kvmppc_subcore_exit_guest(void)
187 188
188 local_paca->sibling_subcore_state->in_guest[subcore_id] = 0; 189 local_paca->sibling_subcore_state->in_guest[subcore_id] = 0;
189} 190}
191EXPORT_SYMBOL_GPL(kvmppc_subcore_exit_guest);
190 192
191static bool kvmppc_tb_resync_required(void) 193static bool kvmppc_tb_resync_required(void)
192{ 194{
@@ -331,5 +333,13 @@ long kvmppc_realmode_hmi_handler(void)
331 } else { 333 } else {
332 wait_for_tb_resync(); 334 wait_for_tb_resync();
333 } 335 }
336
337 /*
338 * Reset tb_offset_applied so the guest exit code won't try
339 * to subtract the previous timebase offset from the timebase.
340 */
341 if (local_paca->kvm_hstate.kvm_vcore)
342 local_paca->kvm_hstate.kvm_vcore->tb_offset_applied = 0;
343
334 return 0; 344 return 0;
335} 345}
diff --git a/arch/powerpc/kvm/book3s_hv_rm_xics.c b/arch/powerpc/kvm/book3s_hv_rm_xics.c
index 758d1d23215e..b3f5786b20dc 100644
--- a/arch/powerpc/kvm/book3s_hv_rm_xics.c
+++ b/arch/powerpc/kvm/book3s_hv_rm_xics.c
@@ -136,7 +136,7 @@ static void icp_rm_set_vcpu_irq(struct kvm_vcpu *vcpu,
136 136
137 /* Mark the target VCPU as having an interrupt pending */ 137 /* Mark the target VCPU as having an interrupt pending */
138 vcpu->stat.queue_intr++; 138 vcpu->stat.queue_intr++;
139 set_bit(BOOK3S_IRQPRIO_EXTERNAL_LEVEL, &vcpu->arch.pending_exceptions); 139 set_bit(BOOK3S_IRQPRIO_EXTERNAL, &vcpu->arch.pending_exceptions);
140 140
141 /* Kick self ? Just set MER and return */ 141 /* Kick self ? Just set MER and return */
142 if (vcpu == this_vcpu) { 142 if (vcpu == this_vcpu) {
@@ -170,8 +170,7 @@ static void icp_rm_set_vcpu_irq(struct kvm_vcpu *vcpu,
170static void icp_rm_clr_vcpu_irq(struct kvm_vcpu *vcpu) 170static void icp_rm_clr_vcpu_irq(struct kvm_vcpu *vcpu)
171{ 171{
172 /* Note: Only called on self ! */ 172 /* Note: Only called on self ! */
173 clear_bit(BOOK3S_IRQPRIO_EXTERNAL_LEVEL, 173 clear_bit(BOOK3S_IRQPRIO_EXTERNAL, &vcpu->arch.pending_exceptions);
174 &vcpu->arch.pending_exceptions);
175 mtspr(SPRN_LPCR, mfspr(SPRN_LPCR) & ~LPCR_MER); 174 mtspr(SPRN_LPCR, mfspr(SPRN_LPCR) & ~LPCR_MER);
176} 175}
177 176
@@ -768,6 +767,14 @@ static void icp_eoi(struct irq_chip *c, u32 hwirq, __be32 xirr, bool *again)
768 void __iomem *xics_phys; 767 void __iomem *xics_phys;
769 int64_t rc; 768 int64_t rc;
770 769
770 if (kvmhv_on_pseries()) {
771 unsigned long retbuf[PLPAR_HCALL_BUFSIZE];
772
773 iosync();
774 plpar_hcall_raw(H_EOI, retbuf, hwirq);
775 return;
776 }
777
771 rc = pnv_opal_pci_msi_eoi(c, hwirq); 778 rc = pnv_opal_pci_msi_eoi(c, hwirq);
772 779
773 if (rc) 780 if (rc)
diff --git a/arch/powerpc/kvm/book3s_hv_rmhandlers.S b/arch/powerpc/kvm/book3s_hv_rmhandlers.S
index 1d14046124a0..9b8d50a7cbaf 100644
--- a/arch/powerpc/kvm/book3s_hv_rmhandlers.S
+++ b/arch/powerpc/kvm/book3s_hv_rmhandlers.S
@@ -28,6 +28,7 @@
28#include <asm/exception-64s.h> 28#include <asm/exception-64s.h>
29#include <asm/kvm_book3s_asm.h> 29#include <asm/kvm_book3s_asm.h>
30#include <asm/book3s/64/mmu-hash.h> 30#include <asm/book3s/64/mmu-hash.h>
31#include <asm/export.h>
31#include <asm/tm.h> 32#include <asm/tm.h>
32#include <asm/opal.h> 33#include <asm/opal.h>
33#include <asm/xive-regs.h> 34#include <asm/xive-regs.h>
@@ -46,8 +47,9 @@ END_FTR_SECTION_IFCLR(CPU_FTR_ARCH_300)
46#define NAPPING_NOVCPU 2 47#define NAPPING_NOVCPU 2
47 48
48/* Stack frame offsets for kvmppc_hv_entry */ 49/* Stack frame offsets for kvmppc_hv_entry */
49#define SFS 160 50#define SFS 208
50#define STACK_SLOT_TRAP (SFS-4) 51#define STACK_SLOT_TRAP (SFS-4)
52#define STACK_SLOT_SHORT_PATH (SFS-8)
51#define STACK_SLOT_TID (SFS-16) 53#define STACK_SLOT_TID (SFS-16)
52#define STACK_SLOT_PSSCR (SFS-24) 54#define STACK_SLOT_PSSCR (SFS-24)
53#define STACK_SLOT_PID (SFS-32) 55#define STACK_SLOT_PID (SFS-32)
@@ -56,6 +58,8 @@ END_FTR_SECTION_IFCLR(CPU_FTR_ARCH_300)
56#define STACK_SLOT_DAWR (SFS-56) 58#define STACK_SLOT_DAWR (SFS-56)
57#define STACK_SLOT_DAWRX (SFS-64) 59#define STACK_SLOT_DAWRX (SFS-64)
58#define STACK_SLOT_HFSCR (SFS-72) 60#define STACK_SLOT_HFSCR (SFS-72)
61/* the following is used by the P9 short path */
62#define STACK_SLOT_NVGPRS (SFS-152) /* 18 gprs */
59 63
60/* 64/*
61 * Call kvmppc_hv_entry in real mode. 65 * Call kvmppc_hv_entry in real mode.
@@ -113,45 +117,7 @@ END_FTR_SECTION_IFCLR(CPU_FTR_ARCH_207S)
113 mtspr SPRN_SPRG_VDSO_WRITE,r3 117 mtspr SPRN_SPRG_VDSO_WRITE,r3
114 118
115 /* Reload the host's PMU registers */ 119 /* Reload the host's PMU registers */
116 lbz r4, PACA_PMCINUSE(r13) /* is the host using the PMU? */ 120 bl kvmhv_load_host_pmu
117 cmpwi r4, 0
118 beq 23f /* skip if not */
119BEGIN_FTR_SECTION
120 ld r3, HSTATE_MMCR0(r13)
121 andi. r4, r3, MMCR0_PMAO_SYNC | MMCR0_PMAO
122 cmpwi r4, MMCR0_PMAO
123 beql kvmppc_fix_pmao
124END_FTR_SECTION_IFSET(CPU_FTR_PMAO_BUG)
125 lwz r3, HSTATE_PMC1(r13)
126 lwz r4, HSTATE_PMC2(r13)
127 lwz r5, HSTATE_PMC3(r13)
128 lwz r6, HSTATE_PMC4(r13)
129 lwz r8, HSTATE_PMC5(r13)
130 lwz r9, HSTATE_PMC6(r13)
131 mtspr SPRN_PMC1, r3
132 mtspr SPRN_PMC2, r4
133 mtspr SPRN_PMC3, r5
134 mtspr SPRN_PMC4, r6
135 mtspr SPRN_PMC5, r8
136 mtspr SPRN_PMC6, r9
137 ld r3, HSTATE_MMCR0(r13)
138 ld r4, HSTATE_MMCR1(r13)
139 ld r5, HSTATE_MMCRA(r13)
140 ld r6, HSTATE_SIAR(r13)
141 ld r7, HSTATE_SDAR(r13)
142 mtspr SPRN_MMCR1, r4
143 mtspr SPRN_MMCRA, r5
144 mtspr SPRN_SIAR, r6
145 mtspr SPRN_SDAR, r7
146BEGIN_FTR_SECTION
147 ld r8, HSTATE_MMCR2(r13)
148 ld r9, HSTATE_SIER(r13)
149 mtspr SPRN_MMCR2, r8
150 mtspr SPRN_SIER, r9
151END_FTR_SECTION_IFSET(CPU_FTR_ARCH_207S)
152 mtspr SPRN_MMCR0, r3
153 isync
15423:
155 121
156 /* 122 /*
157 * Reload DEC. HDEC interrupts were disabled when 123 * Reload DEC. HDEC interrupts were disabled when
@@ -796,66 +762,23 @@ BEGIN_FTR_SECTION
796 b 91f 762 b 91f
797END_FTR_SECTION(CPU_FTR_TM | CPU_FTR_P9_TM_HV_ASSIST, 0) 763END_FTR_SECTION(CPU_FTR_TM | CPU_FTR_P9_TM_HV_ASSIST, 0)
798 /* 764 /*
799 * NOTE THAT THIS TRASHES ALL NON-VOLATILE REGISTERS INCLUDING CR 765 * NOTE THAT THIS TRASHES ALL NON-VOLATILE REGISTERS (but not CR)
800 */ 766 */
801 mr r3, r4 767 mr r3, r4
802 ld r4, VCPU_MSR(r3) 768 ld r4, VCPU_MSR(r3)
769 li r5, 0 /* don't preserve non-vol regs */
803 bl kvmppc_restore_tm_hv 770 bl kvmppc_restore_tm_hv
771 nop
804 ld r4, HSTATE_KVM_VCPU(r13) 772 ld r4, HSTATE_KVM_VCPU(r13)
80591: 77391:
806#endif 774#endif
807 775
808 /* Load guest PMU registers */ 776 /* Load guest PMU registers; r4 = vcpu pointer here */
809 /* R4 is live here (vcpu pointer) */ 777 mr r3, r4
810 li r3, 1 778 bl kvmhv_load_guest_pmu
811 sldi r3, r3, 31 /* MMCR0_FC (freeze counters) bit */
812 mtspr SPRN_MMCR0, r3 /* freeze all counters, disable ints */
813 isync
814BEGIN_FTR_SECTION
815 ld r3, VCPU_MMCR(r4)
816 andi. r5, r3, MMCR0_PMAO_SYNC | MMCR0_PMAO
817 cmpwi r5, MMCR0_PMAO
818 beql kvmppc_fix_pmao
819END_FTR_SECTION_IFSET(CPU_FTR_PMAO_BUG)
820 lwz r3, VCPU_PMC(r4) /* always load up guest PMU registers */
821 lwz r5, VCPU_PMC + 4(r4) /* to prevent information leak */
822 lwz r6, VCPU_PMC + 8(r4)
823 lwz r7, VCPU_PMC + 12(r4)
824 lwz r8, VCPU_PMC + 16(r4)
825 lwz r9, VCPU_PMC + 20(r4)
826 mtspr SPRN_PMC1, r3
827 mtspr SPRN_PMC2, r5
828 mtspr SPRN_PMC3, r6
829 mtspr SPRN_PMC4, r7
830 mtspr SPRN_PMC5, r8
831 mtspr SPRN_PMC6, r9
832 ld r3, VCPU_MMCR(r4)
833 ld r5, VCPU_MMCR + 8(r4)
834 ld r6, VCPU_MMCR + 16(r4)
835 ld r7, VCPU_SIAR(r4)
836 ld r8, VCPU_SDAR(r4)
837 mtspr SPRN_MMCR1, r5
838 mtspr SPRN_MMCRA, r6
839 mtspr SPRN_SIAR, r7
840 mtspr SPRN_SDAR, r8
841BEGIN_FTR_SECTION
842 ld r5, VCPU_MMCR + 24(r4)
843 ld r6, VCPU_SIER(r4)
844 mtspr SPRN_MMCR2, r5
845 mtspr SPRN_SIER, r6
846BEGIN_FTR_SECTION_NESTED(96)
847 lwz r7, VCPU_PMC + 24(r4)
848 lwz r8, VCPU_PMC + 28(r4)
849 ld r9, VCPU_MMCR + 32(r4)
850 mtspr SPRN_SPMC1, r7
851 mtspr SPRN_SPMC2, r8
852 mtspr SPRN_MMCRS, r9
853END_FTR_SECTION_NESTED(CPU_FTR_ARCH_300, 0, 96)
854END_FTR_SECTION_IFSET(CPU_FTR_ARCH_207S)
855 mtspr SPRN_MMCR0, r3
856 isync
857 779
858 /* Load up FP, VMX and VSX registers */ 780 /* Load up FP, VMX and VSX registers */
781 ld r4, HSTATE_KVM_VCPU(r13)
859 bl kvmppc_load_fp 782 bl kvmppc_load_fp
860 783
861 ld r14, VCPU_GPR(R14)(r4) 784 ld r14, VCPU_GPR(R14)(r4)
@@ -1100,73 +1023,40 @@ ALT_FTR_SECTION_END_IFCLR(CPU_FTR_ARCH_300)
1100no_xive: 1023no_xive:
1101#endif /* CONFIG_KVM_XICS */ 1024#endif /* CONFIG_KVM_XICS */
1102 1025
1103deliver_guest_interrupt: 1026 li r0, 0
1104 ld r6, VCPU_CTR(r4) 1027 stw r0, STACK_SLOT_SHORT_PATH(r1)
1105 ld r7, VCPU_XER(r4)
1106
1107 mtctr r6
1108 mtxer r7
1109 1028
1110kvmppc_cede_reentry: /* r4 = vcpu, r13 = paca */ 1029deliver_guest_interrupt: /* r4 = vcpu, r13 = paca */
1111 ld r10, VCPU_PC(r4) 1030 /* Check if we can deliver an external or decrementer interrupt now */
1112 ld r11, VCPU_MSR(r4) 1031 ld r0, VCPU_PENDING_EXC(r4)
1032BEGIN_FTR_SECTION
1033 /* On POWER9, also check for emulated doorbell interrupt */
1034 lbz r3, VCPU_DBELL_REQ(r4)
1035 or r0, r0, r3
1036END_FTR_SECTION_IFSET(CPU_FTR_ARCH_300)
1037 cmpdi r0, 0
1038 beq 71f
1039 mr r3, r4
1040 bl kvmppc_guest_entry_inject_int
1041 ld r4, HSTATE_KVM_VCPU(r13)
104271:
1113 ld r6, VCPU_SRR0(r4) 1043 ld r6, VCPU_SRR0(r4)
1114 ld r7, VCPU_SRR1(r4) 1044 ld r7, VCPU_SRR1(r4)
1115 mtspr SPRN_SRR0, r6 1045 mtspr SPRN_SRR0, r6
1116 mtspr SPRN_SRR1, r7 1046 mtspr SPRN_SRR1, r7
1117 1047
1048fast_guest_entry_c:
1049 ld r10, VCPU_PC(r4)
1050 ld r11, VCPU_MSR(r4)
1118 /* r11 = vcpu->arch.msr & ~MSR_HV */ 1051 /* r11 = vcpu->arch.msr & ~MSR_HV */
1119 rldicl r11, r11, 63 - MSR_HV_LG, 1 1052 rldicl r11, r11, 63 - MSR_HV_LG, 1
1120 rotldi r11, r11, 1 + MSR_HV_LG 1053 rotldi r11, r11, 1 + MSR_HV_LG
1121 ori r11, r11, MSR_ME 1054 ori r11, r11, MSR_ME
1122 1055
1123 /* Check if we can deliver an external or decrementer interrupt now */ 1056 ld r6, VCPU_CTR(r4)
1124 ld r0, VCPU_PENDING_EXC(r4) 1057 ld r7, VCPU_XER(r4)
1125 rldicl r0, r0, 64 - BOOK3S_IRQPRIO_EXTERNAL_LEVEL, 63 1058 mtctr r6
1126 cmpdi cr1, r0, 0 1059 mtxer r7
1127 andi. r8, r11, MSR_EE
1128 mfspr r8, SPRN_LPCR
1129 /* Insert EXTERNAL_LEVEL bit into LPCR at the MER bit position */
1130 rldimi r8, r0, LPCR_MER_SH, 63 - LPCR_MER_SH
1131 mtspr SPRN_LPCR, r8
1132 isync
1133 beq 5f
1134 li r0, BOOK3S_INTERRUPT_EXTERNAL
1135 bne cr1, 12f
1136 mfspr r0, SPRN_DEC
1137BEGIN_FTR_SECTION
1138 /* On POWER9 check whether the guest has large decrementer enabled */
1139 andis. r8, r8, LPCR_LD@h
1140 bne 15f
1141END_FTR_SECTION_IFSET(CPU_FTR_ARCH_300)
1142 extsw r0, r0
114315: cmpdi r0, 0
1144 li r0, BOOK3S_INTERRUPT_DECREMENTER
1145 bge 5f
1146
114712: mtspr SPRN_SRR0, r10
1148 mr r10,r0
1149 mtspr SPRN_SRR1, r11
1150 mr r9, r4
1151 bl kvmppc_msr_interrupt
11525:
1153BEGIN_FTR_SECTION
1154 b fast_guest_return
1155END_FTR_SECTION_IFCLR(CPU_FTR_ARCH_300)
1156 /* On POWER9, check for pending doorbell requests */
1157 lbz r0, VCPU_DBELL_REQ(r4)
1158 cmpwi r0, 0
1159 beq fast_guest_return
1160 ld r5, HSTATE_KVM_VCORE(r13)
1161 /* Set DPDES register so the CPU will take a doorbell interrupt */
1162 li r0, 1
1163 mtspr SPRN_DPDES, r0
1164 std r0, VCORE_DPDES(r5)
1165 /* Make sure other cpus see vcore->dpdes set before dbell req clear */
1166 lwsync
1167 /* Clear the pending doorbell request */
1168 li r0, 0
1169 stb r0, VCPU_DBELL_REQ(r4)
1170 1060
1171/* 1061/*
1172 * Required state: 1062 * Required state:
@@ -1202,7 +1092,7 @@ BEGIN_FTR_SECTION
1202END_FTR_SECTION_IFSET(CPU_FTR_HAS_PPR) 1092END_FTR_SECTION_IFSET(CPU_FTR_HAS_PPR)
1203 1093
1204 ld r5, VCPU_LR(r4) 1094 ld r5, VCPU_LR(r4)
1205 lwz r6, VCPU_CR(r4) 1095 ld r6, VCPU_CR(r4)
1206 mtlr r5 1096 mtlr r5
1207 mtcr r6 1097 mtcr r6
1208 1098
@@ -1234,6 +1124,83 @@ END_FTR_SECTION_IFSET(CPU_FTR_ARCH_300)
1234 HRFI_TO_GUEST 1124 HRFI_TO_GUEST
1235 b . 1125 b .
1236 1126
1127/*
1128 * Enter the guest on a P9 or later system where we have exactly
1129 * one vcpu per vcore and we don't need to go to real mode
1130 * (which implies that host and guest are both using radix MMU mode).
1131 * r3 = vcpu pointer
1132 * Most SPRs and all the VSRs have been loaded already.
1133 */
1134_GLOBAL(__kvmhv_vcpu_entry_p9)
1135EXPORT_SYMBOL_GPL(__kvmhv_vcpu_entry_p9)
1136 mflr r0
1137 std r0, PPC_LR_STKOFF(r1)
1138 stdu r1, -SFS(r1)
1139
1140 li r0, 1
1141 stw r0, STACK_SLOT_SHORT_PATH(r1)
1142
1143 std r3, HSTATE_KVM_VCPU(r13)
1144 mfcr r4
1145 stw r4, SFS+8(r1)
1146
1147 std r1, HSTATE_HOST_R1(r13)
1148
1149 reg = 14
1150 .rept 18
1151 std reg, STACK_SLOT_NVGPRS + ((reg - 14) * 8)(r1)
1152 reg = reg + 1
1153 .endr
1154
1155 reg = 14
1156 .rept 18
1157 ld reg, __VCPU_GPR(reg)(r3)
1158 reg = reg + 1
1159 .endr
1160
1161 mfmsr r10
1162 std r10, HSTATE_HOST_MSR(r13)
1163
1164 mr r4, r3
1165 b fast_guest_entry_c
1166guest_exit_short_path:
1167
1168 li r0, KVM_GUEST_MODE_NONE
1169 stb r0, HSTATE_IN_GUEST(r13)
1170
1171 reg = 14
1172 .rept 18
1173 std reg, __VCPU_GPR(reg)(r9)
1174 reg = reg + 1
1175 .endr
1176
1177 reg = 14
1178 .rept 18
1179 ld reg, STACK_SLOT_NVGPRS + ((reg - 14) * 8)(r1)
1180 reg = reg + 1
1181 .endr
1182
1183 lwz r4, SFS+8(r1)
1184 mtcr r4
1185
1186 mr r3, r12 /* trap number */
1187
1188 addi r1, r1, SFS
1189 ld r0, PPC_LR_STKOFF(r1)
1190 mtlr r0
1191
1192 /* If we are in real mode, do a rfid to get back to the caller */
1193 mfmsr r4
1194 andi. r5, r4, MSR_IR
1195 bnelr
1196 rldicl r5, r4, 64 - MSR_TS_S_LG, 62 /* extract TS field */
1197 mtspr SPRN_SRR0, r0
1198 ld r10, HSTATE_HOST_MSR(r13)
1199 rldimi r10, r5, MSR_TS_S_LG, 63 - MSR_TS_T_LG
1200 mtspr SPRN_SRR1, r10
1201 RFI_TO_KERNEL
1202 b .
1203
1237secondary_too_late: 1204secondary_too_late:
1238 li r12, 0 1205 li r12, 0
1239 stw r12, STACK_SLOT_TRAP(r1) 1206 stw r12, STACK_SLOT_TRAP(r1)
@@ -1313,7 +1280,7 @@ kvmppc_interrupt_hv:
1313 std r3, VCPU_GPR(R12)(r9) 1280 std r3, VCPU_GPR(R12)(r9)
1314 /* CR is in the high half of r12 */ 1281 /* CR is in the high half of r12 */
1315 srdi r4, r12, 32 1282 srdi r4, r12, 32
1316 stw r4, VCPU_CR(r9) 1283 std r4, VCPU_CR(r9)
1317BEGIN_FTR_SECTION 1284BEGIN_FTR_SECTION
1318 ld r3, HSTATE_CFAR(r13) 1285 ld r3, HSTATE_CFAR(r13)
1319 std r3, VCPU_CFAR(r9) 1286 std r3, VCPU_CFAR(r9)
@@ -1387,18 +1354,26 @@ END_FTR_SECTION_IFSET(CPU_FTR_HAS_PPR)
1387 std r3, VCPU_CTR(r9) 1354 std r3, VCPU_CTR(r9)
1388 std r4, VCPU_XER(r9) 1355 std r4, VCPU_XER(r9)
1389 1356
1390#ifdef CONFIG_PPC_TRANSACTIONAL_MEM 1357 /* Save more register state */
1391 /* For softpatch interrupt, go off and do TM instruction emulation */ 1358 mfdar r3
1392 cmpwi r12, BOOK3S_INTERRUPT_HV_SOFTPATCH 1359 mfdsisr r4
1393 beq kvmppc_tm_emul 1360 std r3, VCPU_DAR(r9)
1394#endif 1361 stw r4, VCPU_DSISR(r9)
1395 1362
1396 /* If this is a page table miss then see if it's theirs or ours */ 1363 /* If this is a page table miss then see if it's theirs or ours */
1397 cmpwi r12, BOOK3S_INTERRUPT_H_DATA_STORAGE 1364 cmpwi r12, BOOK3S_INTERRUPT_H_DATA_STORAGE
1398 beq kvmppc_hdsi 1365 beq kvmppc_hdsi
1366 std r3, VCPU_FAULT_DAR(r9)
1367 stw r4, VCPU_FAULT_DSISR(r9)
1399 cmpwi r12, BOOK3S_INTERRUPT_H_INST_STORAGE 1368 cmpwi r12, BOOK3S_INTERRUPT_H_INST_STORAGE
1400 beq kvmppc_hisi 1369 beq kvmppc_hisi
1401 1370
1371#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
1372 /* For softpatch interrupt, go off and do TM instruction emulation */
1373 cmpwi r12, BOOK3S_INTERRUPT_HV_SOFTPATCH
1374 beq kvmppc_tm_emul
1375#endif
1376
1402 /* See if this is a leftover HDEC interrupt */ 1377 /* See if this is a leftover HDEC interrupt */
1403 cmpwi r12,BOOK3S_INTERRUPT_HV_DECREMENTER 1378 cmpwi r12,BOOK3S_INTERRUPT_HV_DECREMENTER
1404 bne 2f 1379 bne 2f
@@ -1418,10 +1393,14 @@ END_FTR_SECTION_IFSET(CPU_FTR_HAS_PPR)
1418BEGIN_FTR_SECTION 1393BEGIN_FTR_SECTION
1419 PPC_MSGSYNC 1394 PPC_MSGSYNC
1420 lwsync 1395 lwsync
1396 /* always exit if we're running a nested guest */
1397 ld r0, VCPU_NESTED(r9)
1398 cmpdi r0, 0
1399 bne guest_exit_cont
1421END_FTR_SECTION_IFSET(CPU_FTR_ARCH_300) 1400END_FTR_SECTION_IFSET(CPU_FTR_ARCH_300)
1422 lbz r0, HSTATE_HOST_IPI(r13) 1401 lbz r0, HSTATE_HOST_IPI(r13)
1423 cmpwi r0, 0 1402 cmpwi r0, 0
1424 beq 4f 1403 beq maybe_reenter_guest
1425 b guest_exit_cont 1404 b guest_exit_cont
14263: 14053:
1427 /* If it's a hypervisor facility unavailable interrupt, save HFSCR */ 1406 /* If it's a hypervisor facility unavailable interrupt, save HFSCR */
@@ -1433,82 +1412,16 @@ END_FTR_SECTION_IFSET(CPU_FTR_ARCH_300)
143314: 141214:
1434 /* External interrupt ? */ 1413 /* External interrupt ? */
1435 cmpwi r12, BOOK3S_INTERRUPT_EXTERNAL 1414 cmpwi r12, BOOK3S_INTERRUPT_EXTERNAL
1436 bne+ guest_exit_cont 1415 beq kvmppc_guest_external
1437
1438 /* External interrupt, first check for host_ipi. If this is
1439 * set, we know the host wants us out so let's do it now
1440 */
1441 bl kvmppc_read_intr
1442
1443 /*
1444 * Restore the active volatile registers after returning from
1445 * a C function.
1446 */
1447 ld r9, HSTATE_KVM_VCPU(r13)
1448 li r12, BOOK3S_INTERRUPT_EXTERNAL
1449
1450 /*
1451 * kvmppc_read_intr return codes:
1452 *
1453 * Exit to host (r3 > 0)
1454 * 1 An interrupt is pending that needs to be handled by the host
1455 * Exit guest and return to host by branching to guest_exit_cont
1456 *
1457 * 2 Passthrough that needs completion in the host
1458 * Exit guest and return to host by branching to guest_exit_cont
1459 * However, we also set r12 to BOOK3S_INTERRUPT_HV_RM_HARD
1460 * to indicate to the host to complete handling the interrupt
1461 *
1462 * Before returning to guest, we check if any CPU is heading out
1463 * to the host and if so, we head out also. If no CPUs are heading
1464 * check return values <= 0.
1465 *
1466 * Return to guest (r3 <= 0)
1467 * 0 No external interrupt is pending
1468 * -1 A guest wakeup IPI (which has now been cleared)
1469 * In either case, we return to guest to deliver any pending
1470 * guest interrupts.
1471 *
1472 * -2 A PCI passthrough external interrupt was handled
1473 * (interrupt was delivered directly to guest)
1474 * Return to guest to deliver any pending guest interrupts.
1475 */
1476
1477 cmpdi r3, 1
1478 ble 1f
1479
1480 /* Return code = 2 */
1481 li r12, BOOK3S_INTERRUPT_HV_RM_HARD
1482 stw r12, VCPU_TRAP(r9)
1483 b guest_exit_cont
1484
14851: /* Return code <= 1 */
1486 cmpdi r3, 0
1487 bgt guest_exit_cont
1488
1489 /* Return code <= 0 */
14904: ld r5, HSTATE_KVM_VCORE(r13)
1491 lwz r0, VCORE_ENTRY_EXIT(r5)
1492 cmpwi r0, 0x100
1493 mr r4, r9
1494 blt deliver_guest_interrupt
1495
1496guest_exit_cont: /* r9 = vcpu, r12 = trap, r13 = paca */
1497 /* Save more register state */
1498 mfdar r6
1499 mfdsisr r7
1500 std r6, VCPU_DAR(r9)
1501 stw r7, VCPU_DSISR(r9)
1502 /* don't overwrite fault_dar/fault_dsisr if HDSI */
1503 cmpwi r12,BOOK3S_INTERRUPT_H_DATA_STORAGE
1504 beq mc_cont
1505 std r6, VCPU_FAULT_DAR(r9)
1506 stw r7, VCPU_FAULT_DSISR(r9)
1507
1508 /* See if it is a machine check */ 1416 /* See if it is a machine check */
1509 cmpwi r12, BOOK3S_INTERRUPT_MACHINE_CHECK 1417 cmpwi r12, BOOK3S_INTERRUPT_MACHINE_CHECK
1510 beq machine_check_realmode 1418 beq machine_check_realmode
1511mc_cont: 1419 /* Or a hypervisor maintenance interrupt */
1420 cmpwi r12, BOOK3S_INTERRUPT_HMI
1421 beq hmi_realmode
1422
1423guest_exit_cont: /* r9 = vcpu, r12 = trap, r13 = paca */
1424
1512#ifdef CONFIG_KVM_BOOK3S_HV_EXIT_TIMING 1425#ifdef CONFIG_KVM_BOOK3S_HV_EXIT_TIMING
1513 addi r3, r9, VCPU_TB_RMEXIT 1426 addi r3, r9, VCPU_TB_RMEXIT
1514 mr r4, r9 1427 mr r4, r9
@@ -1552,6 +1465,11 @@ mc_cont:
15521: 14651:
1553#endif /* CONFIG_KVM_XICS */ 1466#endif /* CONFIG_KVM_XICS */
1554 1467
1468 /* If we came in through the P9 short path, go back out to C now */
1469 lwz r0, STACK_SLOT_SHORT_PATH(r1)
1470 cmpwi r0, 0
1471 bne guest_exit_short_path
1472
1555 /* For hash guest, read the guest SLB and save it away */ 1473 /* For hash guest, read the guest SLB and save it away */
1556 ld r5, VCPU_KVM(r9) 1474 ld r5, VCPU_KVM(r9)
1557 lbz r0, KVM_RADIX(r5) 1475 lbz r0, KVM_RADIX(r5)
@@ -1780,11 +1698,13 @@ BEGIN_FTR_SECTION
1780 b 91f 1698 b 91f
1781END_FTR_SECTION(CPU_FTR_TM | CPU_FTR_P9_TM_HV_ASSIST, 0) 1699END_FTR_SECTION(CPU_FTR_TM | CPU_FTR_P9_TM_HV_ASSIST, 0)
1782 /* 1700 /*
1783 * NOTE THAT THIS TRASHES ALL NON-VOLATILE REGISTERS INCLUDING CR 1701 * NOTE THAT THIS TRASHES ALL NON-VOLATILE REGISTERS (but not CR)
1784 */ 1702 */
1785 mr r3, r9 1703 mr r3, r9
1786 ld r4, VCPU_MSR(r3) 1704 ld r4, VCPU_MSR(r3)
1705 li r5, 0 /* don't preserve non-vol regs */
1787 bl kvmppc_save_tm_hv 1706 bl kvmppc_save_tm_hv
1707 nop
1788 ld r9, HSTATE_KVM_VCPU(r13) 1708 ld r9, HSTATE_KVM_VCPU(r13)
178991: 170991:
1790#endif 1710#endif
@@ -1802,83 +1722,12 @@ END_FTR_SECTION(CPU_FTR_TM | CPU_FTR_P9_TM_HV_ASSIST, 0)
180225: 172225:
1803 /* Save PMU registers if requested */ 1723 /* Save PMU registers if requested */
1804 /* r8 and cr0.eq are live here */ 1724 /* r8 and cr0.eq are live here */
1805BEGIN_FTR_SECTION 1725 mr r3, r9
1806 /* 1726 li r4, 1
1807 * POWER8 seems to have a hardware bug where setting
1808 * MMCR0[PMAE] along with MMCR0[PMC1CE] and/or MMCR0[PMCjCE]
1809 * when some counters are already negative doesn't seem
1810 * to cause a performance monitor alert (and hence interrupt).
1811 * The effect of this is that when saving the PMU state,
1812 * if there is no PMU alert pending when we read MMCR0
1813 * before freezing the counters, but one becomes pending
1814 * before we read the counters, we lose it.
1815 * To work around this, we need a way to freeze the counters
1816 * before reading MMCR0. Normally, freezing the counters
1817 * is done by writing MMCR0 (to set MMCR0[FC]) which
1818 * unavoidably writes MMCR0[PMA0] as well. On POWER8,
1819 * we can also freeze the counters using MMCR2, by writing
1820 * 1s to all the counter freeze condition bits (there are
1821 * 9 bits each for 6 counters).
1822 */
1823 li r3, -1 /* set all freeze bits */
1824 clrrdi r3, r3, 10
1825 mfspr r10, SPRN_MMCR2
1826 mtspr SPRN_MMCR2, r3
1827 isync
1828END_FTR_SECTION_IFSET(CPU_FTR_ARCH_207S)
1829 li r3, 1
1830 sldi r3, r3, 31 /* MMCR0_FC (freeze counters) bit */
1831 mfspr r4, SPRN_MMCR0 /* save MMCR0 */
1832 mtspr SPRN_MMCR0, r3 /* freeze all counters, disable ints */
1833 mfspr r6, SPRN_MMCRA
1834 /* Clear MMCRA in order to disable SDAR updates */
1835 li r7, 0
1836 mtspr SPRN_MMCRA, r7
1837 isync
1838 beq 21f /* if no VPA, save PMU stuff anyway */ 1727 beq 21f /* if no VPA, save PMU stuff anyway */
1839 lbz r7, LPPACA_PMCINUSE(r8) 1728 lbz r4, LPPACA_PMCINUSE(r8)
1840 cmpwi r7, 0 /* did they ask for PMU stuff to be saved? */ 172921: bl kvmhv_save_guest_pmu
1841 bne 21f 1730 ld r9, HSTATE_KVM_VCPU(r13)
1842 std r3, VCPU_MMCR(r9) /* if not, set saved MMCR0 to FC */
1843 b 22f
184421: mfspr r5, SPRN_MMCR1
1845 mfspr r7, SPRN_SIAR
1846 mfspr r8, SPRN_SDAR
1847 std r4, VCPU_MMCR(r9)
1848 std r5, VCPU_MMCR + 8(r9)
1849 std r6, VCPU_MMCR + 16(r9)
1850BEGIN_FTR_SECTION
1851 std r10, VCPU_MMCR + 24(r9)
1852END_FTR_SECTION_IFSET(CPU_FTR_ARCH_207S)
1853 std r7, VCPU_SIAR(r9)
1854 std r8, VCPU_SDAR(r9)
1855 mfspr r3, SPRN_PMC1
1856 mfspr r4, SPRN_PMC2
1857 mfspr r5, SPRN_PMC3
1858 mfspr r6, SPRN_PMC4
1859 mfspr r7, SPRN_PMC5
1860 mfspr r8, SPRN_PMC6
1861 stw r3, VCPU_PMC(r9)
1862 stw r4, VCPU_PMC + 4(r9)
1863 stw r5, VCPU_PMC + 8(r9)
1864 stw r6, VCPU_PMC + 12(r9)
1865 stw r7, VCPU_PMC + 16(r9)
1866 stw r8, VCPU_PMC + 20(r9)
1867BEGIN_FTR_SECTION
1868 mfspr r5, SPRN_SIER
1869 std r5, VCPU_SIER(r9)
1870BEGIN_FTR_SECTION_NESTED(96)
1871 mfspr r6, SPRN_SPMC1
1872 mfspr r7, SPRN_SPMC2
1873 mfspr r8, SPRN_MMCRS
1874 stw r6, VCPU_PMC + 24(r9)
1875 stw r7, VCPU_PMC + 28(r9)
1876 std r8, VCPU_MMCR + 32(r9)
1877 lis r4, 0x8000
1878 mtspr SPRN_MMCRS, r4
1879END_FTR_SECTION_NESTED(CPU_FTR_ARCH_300, 0, 96)
1880END_FTR_SECTION_IFSET(CPU_FTR_ARCH_207S)
188122:
1882 1731
1883 /* Restore host values of some registers */ 1732 /* Restore host values of some registers */
1884BEGIN_FTR_SECTION 1733BEGIN_FTR_SECTION
@@ -2010,24 +1859,6 @@ BEGIN_FTR_SECTION
2010 mtspr SPRN_DPDES, r8 1859 mtspr SPRN_DPDES, r8
2011END_FTR_SECTION_IFSET(CPU_FTR_ARCH_207S) 1860END_FTR_SECTION_IFSET(CPU_FTR_ARCH_207S)
2012 1861
2013 /* If HMI, call kvmppc_realmode_hmi_handler() */
2014 lwz r12, STACK_SLOT_TRAP(r1)
2015 cmpwi r12, BOOK3S_INTERRUPT_HMI
2016 bne 27f
2017 bl kvmppc_realmode_hmi_handler
2018 nop
2019 cmpdi r3, 0
2020 /*
2021 * At this point kvmppc_realmode_hmi_handler may have resync-ed
2022 * the TB, and if it has, we must not subtract the guest timebase
2023 * offset from the timebase. So, skip it.
2024 *
2025 * Also, do not call kvmppc_subcore_exit_guest() because it has
2026 * been invoked as part of kvmppc_realmode_hmi_handler().
2027 */
2028 beq 30f
2029
203027:
2031 /* Subtract timebase offset from timebase */ 1862 /* Subtract timebase offset from timebase */
2032 ld r8, VCORE_TB_OFFSET_APPL(r5) 1863 ld r8, VCORE_TB_OFFSET_APPL(r5)
2033 cmpdi r8,0 1864 cmpdi r8,0
@@ -2045,7 +1876,16 @@ END_FTR_SECTION_IFSET(CPU_FTR_ARCH_207S)
2045 addis r8,r8,0x100 /* if so, increment upper 40 bits */ 1876 addis r8,r8,0x100 /* if so, increment upper 40 bits */
2046 mtspr SPRN_TBU40,r8 1877 mtspr SPRN_TBU40,r8
2047 1878
204817: bl kvmppc_subcore_exit_guest 187917:
1880 /*
1881 * If this is an HMI, we called kvmppc_realmode_hmi_handler
1882 * above, which may or may not have already called
1883 * kvmppc_subcore_exit_guest. Fortunately, all that
1884 * kvmppc_subcore_exit_guest does is clear a flag, so calling
1885 * it again here is benign even if kvmppc_realmode_hmi_handler
1886 * has already called it.
1887 */
1888 bl kvmppc_subcore_exit_guest
2049 nop 1889 nop
205030: ld r5,HSTATE_KVM_VCORE(r13) 189030: ld r5,HSTATE_KVM_VCORE(r13)
2051 ld r4,VCORE_KVM(r5) /* pointer to struct kvm */ 1891 ld r4,VCORE_KVM(r5) /* pointer to struct kvm */
@@ -2099,6 +1939,67 @@ END_FTR_SECTION_IFSET(CPU_FTR_ARCH_300)
2099 mtlr r0 1939 mtlr r0
2100 blr 1940 blr
2101 1941
1942kvmppc_guest_external:
1943 /* External interrupt, first check for host_ipi. If this is
1944 * set, we know the host wants us out so let's do it now
1945 */
1946 bl kvmppc_read_intr
1947
1948 /*
1949 * Restore the active volatile registers after returning from
1950 * a C function.
1951 */
1952 ld r9, HSTATE_KVM_VCPU(r13)
1953 li r12, BOOK3S_INTERRUPT_EXTERNAL
1954
1955 /*
1956 * kvmppc_read_intr return codes:
1957 *
1958 * Exit to host (r3 > 0)
1959 * 1 An interrupt is pending that needs to be handled by the host
1960 * Exit guest and return to host by branching to guest_exit_cont
1961 *
1962 * 2 Passthrough that needs completion in the host
1963 * Exit guest and return to host by branching to guest_exit_cont
1964 * However, we also set r12 to BOOK3S_INTERRUPT_HV_RM_HARD
1965 * to indicate to the host to complete handling the interrupt
1966 *
1967 * Before returning to guest, we check if any CPU is heading out
1968 * to the host and if so, we head out also. If no CPUs are heading
1969 * check return values <= 0.
1970 *
1971 * Return to guest (r3 <= 0)
1972 * 0 No external interrupt is pending
1973 * -1 A guest wakeup IPI (which has now been cleared)
1974 * In either case, we return to guest to deliver any pending
1975 * guest interrupts.
1976 *
1977 * -2 A PCI passthrough external interrupt was handled
1978 * (interrupt was delivered directly to guest)
1979 * Return to guest to deliver any pending guest interrupts.
1980 */
1981
1982 cmpdi r3, 1
1983 ble 1f
1984
1985 /* Return code = 2 */
1986 li r12, BOOK3S_INTERRUPT_HV_RM_HARD
1987 stw r12, VCPU_TRAP(r9)
1988 b guest_exit_cont
1989
19901: /* Return code <= 1 */
1991 cmpdi r3, 0
1992 bgt guest_exit_cont
1993
1994 /* Return code <= 0 */
1995maybe_reenter_guest:
1996 ld r5, HSTATE_KVM_VCORE(r13)
1997 lwz r0, VCORE_ENTRY_EXIT(r5)
1998 cmpwi r0, 0x100
1999 mr r4, r9
2000 blt deliver_guest_interrupt
2001 b guest_exit_cont
2002
2102#ifdef CONFIG_PPC_TRANSACTIONAL_MEM 2003#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
2103/* 2004/*
2104 * Softpatch interrupt for transactional memory emulation cases 2005 * Softpatch interrupt for transactional memory emulation cases
@@ -2302,6 +2203,10 @@ hcall_try_real_mode:
2302 andi. r0,r11,MSR_PR 2203 andi. r0,r11,MSR_PR
2303 /* sc 1 from userspace - reflect to guest syscall */ 2204 /* sc 1 from userspace - reflect to guest syscall */
2304 bne sc_1_fast_return 2205 bne sc_1_fast_return
2206 /* sc 1 from nested guest - give it to L1 to handle */
2207 ld r0, VCPU_NESTED(r9)
2208 cmpdi r0, 0
2209 bne guest_exit_cont
2305 clrrdi r3,r3,2 2210 clrrdi r3,r3,2
2306 cmpldi r3,hcall_real_table_end - hcall_real_table 2211 cmpldi r3,hcall_real_table_end - hcall_real_table
2307 bge guest_exit_cont 2212 bge guest_exit_cont
@@ -2561,6 +2466,7 @@ hcall_real_table:
2561hcall_real_table_end: 2466hcall_real_table_end:
2562 2467
2563_GLOBAL(kvmppc_h_set_xdabr) 2468_GLOBAL(kvmppc_h_set_xdabr)
2469EXPORT_SYMBOL_GPL(kvmppc_h_set_xdabr)
2564 andi. r0, r5, DABRX_USER | DABRX_KERNEL 2470 andi. r0, r5, DABRX_USER | DABRX_KERNEL
2565 beq 6f 2471 beq 6f
2566 li r0, DABRX_USER | DABRX_KERNEL | DABRX_BTI 2472 li r0, DABRX_USER | DABRX_KERNEL | DABRX_BTI
@@ -2570,6 +2476,7 @@ _GLOBAL(kvmppc_h_set_xdabr)
2570 blr 2476 blr
2571 2477
2572_GLOBAL(kvmppc_h_set_dabr) 2478_GLOBAL(kvmppc_h_set_dabr)
2479EXPORT_SYMBOL_GPL(kvmppc_h_set_dabr)
2573 li r5, DABRX_USER | DABRX_KERNEL 2480 li r5, DABRX_USER | DABRX_KERNEL
25743: 24813:
2575BEGIN_FTR_SECTION 2482BEGIN_FTR_SECTION
@@ -2682,11 +2589,13 @@ BEGIN_FTR_SECTION
2682 b 91f 2589 b 91f
2683END_FTR_SECTION(CPU_FTR_TM | CPU_FTR_P9_TM_HV_ASSIST, 0) 2590END_FTR_SECTION(CPU_FTR_TM | CPU_FTR_P9_TM_HV_ASSIST, 0)
2684 /* 2591 /*
2685 * NOTE THAT THIS TRASHES ALL NON-VOLATILE REGISTERS INCLUDING CR 2592 * NOTE THAT THIS TRASHES ALL NON-VOLATILE REGISTERS (but not CR)
2686 */ 2593 */
2687 ld r3, HSTATE_KVM_VCPU(r13) 2594 ld r3, HSTATE_KVM_VCPU(r13)
2688 ld r4, VCPU_MSR(r3) 2595 ld r4, VCPU_MSR(r3)
2596 li r5, 0 /* don't preserve non-vol regs */
2689 bl kvmppc_save_tm_hv 2597 bl kvmppc_save_tm_hv
2598 nop
269091: 259991:
2691#endif 2600#endif
2692 2601
@@ -2802,11 +2711,13 @@ BEGIN_FTR_SECTION
2802 b 91f 2711 b 91f
2803END_FTR_SECTION(CPU_FTR_TM | CPU_FTR_P9_TM_HV_ASSIST, 0) 2712END_FTR_SECTION(CPU_FTR_TM | CPU_FTR_P9_TM_HV_ASSIST, 0)
2804 /* 2713 /*
2805 * NOTE THAT THIS TRASHES ALL NON-VOLATILE REGISTERS INCLUDING CR 2714 * NOTE THAT THIS TRASHES ALL NON-VOLATILE REGISTERS (but not CR)
2806 */ 2715 */
2807 mr r3, r4 2716 mr r3, r4
2808 ld r4, VCPU_MSR(r3) 2717 ld r4, VCPU_MSR(r3)
2718 li r5, 0 /* don't preserve non-vol regs */
2809 bl kvmppc_restore_tm_hv 2719 bl kvmppc_restore_tm_hv
2720 nop
2810 ld r4, HSTATE_KVM_VCPU(r13) 2721 ld r4, HSTATE_KVM_VCPU(r13)
281191: 272291:
2812#endif 2723#endif
@@ -2874,13 +2785,7 @@ END_FTR_SECTION(CPU_FTR_TM | CPU_FTR_P9_TM_HV_ASSIST, 0)
2874 mr r9, r4 2785 mr r9, r4
2875 cmpdi r3, 0 2786 cmpdi r3, 0
2876 bgt guest_exit_cont 2787 bgt guest_exit_cont
2877 2788 b maybe_reenter_guest
2878 /* see if any other thread is already exiting */
2879 lwz r0,VCORE_ENTRY_EXIT(r5)
2880 cmpwi r0,0x100
2881 bge guest_exit_cont
2882
2883 b kvmppc_cede_reentry /* if not go back to guest */
2884 2789
2885 /* cede when already previously prodded case */ 2790 /* cede when already previously prodded case */
2886kvm_cede_prodded: 2791kvm_cede_prodded:
@@ -2947,12 +2852,12 @@ machine_check_realmode:
2947 */ 2852 */
2948 ld r11, VCPU_MSR(r9) 2853 ld r11, VCPU_MSR(r9)
2949 rldicl. r0, r11, 64-MSR_HV_LG, 63 /* check if it happened in HV mode */ 2854 rldicl. r0, r11, 64-MSR_HV_LG, 63 /* check if it happened in HV mode */
2950 bne mc_cont /* if so, exit to host */ 2855 bne guest_exit_cont /* if so, exit to host */
2951 /* Check if guest is capable of handling NMI exit */ 2856 /* Check if guest is capable of handling NMI exit */
2952 ld r10, VCPU_KVM(r9) 2857 ld r10, VCPU_KVM(r9)
2953 lbz r10, KVM_FWNMI(r10) 2858 lbz r10, KVM_FWNMI(r10)
2954 cmpdi r10, 1 /* FWNMI capable? */ 2859 cmpdi r10, 1 /* FWNMI capable? */
2955 beq mc_cont /* if so, exit with KVM_EXIT_NMI. */ 2860 beq guest_exit_cont /* if so, exit with KVM_EXIT_NMI. */
2956 2861
2957 /* if not, fall through for backward compatibility. */ 2862 /* if not, fall through for backward compatibility. */
2958 andi. r10, r11, MSR_RI /* check for unrecoverable exception */ 2863 andi. r10, r11, MSR_RI /* check for unrecoverable exception */
@@ -2966,6 +2871,21 @@ machine_check_realmode:
29662: b fast_interrupt_c_return 28712: b fast_interrupt_c_return
2967 2872
2968/* 2873/*
2874 * Call C code to handle a HMI in real mode.
2875 * Only the primary thread does the call, secondary threads are handled
2876 * by calling hmi_exception_realmode() after kvmppc_hv_entry returns.
2877 * r9 points to the vcpu on entry
2878 */
2879hmi_realmode:
2880 lbz r0, HSTATE_PTID(r13)
2881 cmpwi r0, 0
2882 bne guest_exit_cont
2883 bl kvmppc_realmode_hmi_handler
2884 ld r9, HSTATE_KVM_VCPU(r13)
2885 li r12, BOOK3S_INTERRUPT_HMI
2886 b guest_exit_cont
2887
2888/*
2969 * Check the reason we woke from nap, and take appropriate action. 2889 * Check the reason we woke from nap, and take appropriate action.
2970 * Returns (in r3): 2890 * Returns (in r3):
2971 * 0 if nothing needs to be done 2891 * 0 if nothing needs to be done
@@ -3130,10 +3050,12 @@ END_FTR_SECTION_IFSET(CPU_FTR_ALTIVEC)
3130 * Save transactional state and TM-related registers. 3050 * Save transactional state and TM-related registers.
3131 * Called with r3 pointing to the vcpu struct and r4 containing 3051 * Called with r3 pointing to the vcpu struct and r4 containing
3132 * the guest MSR value. 3052 * the guest MSR value.
3133 * This can modify all checkpointed registers, but 3053 * r5 is non-zero iff non-volatile register state needs to be maintained.
3054 * If r5 == 0, this can modify all checkpointed registers, but
3134 * restores r1 and r2 before exit. 3055 * restores r1 and r2 before exit.
3135 */ 3056 */
3136kvmppc_save_tm_hv: 3057_GLOBAL_TOC(kvmppc_save_tm_hv)
3058EXPORT_SYMBOL_GPL(kvmppc_save_tm_hv)
3137 /* See if we need to handle fake suspend mode */ 3059 /* See if we need to handle fake suspend mode */
3138BEGIN_FTR_SECTION 3060BEGIN_FTR_SECTION
3139 b __kvmppc_save_tm 3061 b __kvmppc_save_tm
@@ -3161,12 +3083,6 @@ BEGIN_FTR_SECTION
3161END_FTR_SECTION_IFSET(CPU_FTR_P9_TM_XER_SO_BUG) 3083END_FTR_SECTION_IFSET(CPU_FTR_P9_TM_XER_SO_BUG)
3162 nop 3084 nop
3163 3085
3164 std r1, HSTATE_HOST_R1(r13)
3165
3166 /* Clear the MSR RI since r1, r13 may be foobar. */
3167 li r5, 0
3168 mtmsrd r5, 1
3169
3170 /* We have to treclaim here because that's the only way to do S->N */ 3086 /* We have to treclaim here because that's the only way to do S->N */
3171 li r3, TM_CAUSE_KVM_RESCHED 3087 li r3, TM_CAUSE_KVM_RESCHED
3172 TRECLAIM(R3) 3088 TRECLAIM(R3)
@@ -3175,22 +3091,13 @@ END_FTR_SECTION_IFSET(CPU_FTR_P9_TM_XER_SO_BUG)
3175 * We were in fake suspend, so we are not going to save the 3091 * We were in fake suspend, so we are not going to save the
3176 * register state as the guest checkpointed state (since 3092 * register state as the guest checkpointed state (since
3177 * we already have it), therefore we can now use any volatile GPR. 3093 * we already have it), therefore we can now use any volatile GPR.
3094 * In fact treclaim in fake suspend state doesn't modify
3095 * any registers.
3178 */ 3096 */
3179 /* Reload PACA pointer, stack pointer and TOC. */
3180 GET_PACA(r13)
3181 ld r1, HSTATE_HOST_R1(r13)
3182 ld r2, PACATOC(r13)
3183 3097
3184 /* Set MSR RI now we have r1 and r13 back. */ 3098BEGIN_FTR_SECTION
3185 li r5, MSR_RI
3186 mtmsrd r5, 1
3187
3188 HMT_MEDIUM
3189 ld r6, HSTATE_DSCR(r13)
3190 mtspr SPRN_DSCR, r6
3191BEGIN_FTR_SECTION_NESTED(96)
3192 bl pnv_power9_force_smt4_release 3099 bl pnv_power9_force_smt4_release
3193END_FTR_SECTION_NESTED(CPU_FTR_P9_TM_XER_SO_BUG, CPU_FTR_P9_TM_XER_SO_BUG, 96) 3100END_FTR_SECTION_IFSET(CPU_FTR_P9_TM_XER_SO_BUG)
3194 nop 3101 nop
3195 3102
31964: 31034:
@@ -3216,10 +3123,12 @@ END_FTR_SECTION_NESTED(CPU_FTR_P9_TM_XER_SO_BUG, CPU_FTR_P9_TM_XER_SO_BUG, 96)
3216 * Restore transactional state and TM-related registers. 3123 * Restore transactional state and TM-related registers.
3217 * Called with r3 pointing to the vcpu struct 3124 * Called with r3 pointing to the vcpu struct
3218 * and r4 containing the guest MSR value. 3125 * and r4 containing the guest MSR value.
3126 * r5 is non-zero iff non-volatile register state needs to be maintained.
3219 * This potentially modifies all checkpointed registers. 3127 * This potentially modifies all checkpointed registers.
3220 * It restores r1 and r2 from the PACA. 3128 * It restores r1 and r2 from the PACA.
3221 */ 3129 */
3222kvmppc_restore_tm_hv: 3130_GLOBAL_TOC(kvmppc_restore_tm_hv)
3131EXPORT_SYMBOL_GPL(kvmppc_restore_tm_hv)
3223 /* 3132 /*
3224 * If we are doing TM emulation for the guest on a POWER9 DD2, 3133 * If we are doing TM emulation for the guest on a POWER9 DD2,
3225 * then we don't actually do a trechkpt -- we either set up 3134 * then we don't actually do a trechkpt -- we either set up
@@ -3424,6 +3333,194 @@ kvmppc_msr_interrupt:
3424 blr 3333 blr
3425 3334
3426/* 3335/*
3336 * Load up guest PMU state. R3 points to the vcpu struct.
3337 */
3338_GLOBAL(kvmhv_load_guest_pmu)
3339EXPORT_SYMBOL_GPL(kvmhv_load_guest_pmu)
3340 mr r4, r3
3341 mflr r0
3342 li r3, 1
3343 sldi r3, r3, 31 /* MMCR0_FC (freeze counters) bit */
3344 mtspr SPRN_MMCR0, r3 /* freeze all counters, disable ints */
3345 isync
3346BEGIN_FTR_SECTION
3347 ld r3, VCPU_MMCR(r4)
3348 andi. r5, r3, MMCR0_PMAO_SYNC | MMCR0_PMAO
3349 cmpwi r5, MMCR0_PMAO
3350 beql kvmppc_fix_pmao
3351END_FTR_SECTION_IFSET(CPU_FTR_PMAO_BUG)
3352 lwz r3, VCPU_PMC(r4) /* always load up guest PMU registers */
3353 lwz r5, VCPU_PMC + 4(r4) /* to prevent information leak */
3354 lwz r6, VCPU_PMC + 8(r4)
3355 lwz r7, VCPU_PMC + 12(r4)
3356 lwz r8, VCPU_PMC + 16(r4)
3357 lwz r9, VCPU_PMC + 20(r4)
3358 mtspr SPRN_PMC1, r3
3359 mtspr SPRN_PMC2, r5
3360 mtspr SPRN_PMC3, r6
3361 mtspr SPRN_PMC4, r7
3362 mtspr SPRN_PMC5, r8
3363 mtspr SPRN_PMC6, r9
3364 ld r3, VCPU_MMCR(r4)
3365 ld r5, VCPU_MMCR + 8(r4)
3366 ld r6, VCPU_MMCR + 16(r4)
3367 ld r7, VCPU_SIAR(r4)
3368 ld r8, VCPU_SDAR(r4)
3369 mtspr SPRN_MMCR1, r5
3370 mtspr SPRN_MMCRA, r6
3371 mtspr SPRN_SIAR, r7
3372 mtspr SPRN_SDAR, r8
3373BEGIN_FTR_SECTION
3374 ld r5, VCPU_MMCR + 24(r4)
3375 ld r6, VCPU_SIER(r4)
3376 mtspr SPRN_MMCR2, r5
3377 mtspr SPRN_SIER, r6
3378BEGIN_FTR_SECTION_NESTED(96)
3379 lwz r7, VCPU_PMC + 24(r4)
3380 lwz r8, VCPU_PMC + 28(r4)
3381 ld r9, VCPU_MMCR + 32(r4)
3382 mtspr SPRN_SPMC1, r7
3383 mtspr SPRN_SPMC2, r8
3384 mtspr SPRN_MMCRS, r9
3385END_FTR_SECTION_NESTED(CPU_FTR_ARCH_300, 0, 96)
3386END_FTR_SECTION_IFSET(CPU_FTR_ARCH_207S)
3387 mtspr SPRN_MMCR0, r3
3388 isync
3389 mtlr r0
3390 blr
3391
3392/*
3393 * Reload host PMU state saved in the PACA by kvmhv_save_host_pmu.
3394 */
3395_GLOBAL(kvmhv_load_host_pmu)
3396EXPORT_SYMBOL_GPL(kvmhv_load_host_pmu)
3397 mflr r0
3398 lbz r4, PACA_PMCINUSE(r13) /* is the host using the PMU? */
3399 cmpwi r4, 0
3400 beq 23f /* skip if not */
3401BEGIN_FTR_SECTION
3402 ld r3, HSTATE_MMCR0(r13)
3403 andi. r4, r3, MMCR0_PMAO_SYNC | MMCR0_PMAO
3404 cmpwi r4, MMCR0_PMAO
3405 beql kvmppc_fix_pmao
3406END_FTR_SECTION_IFSET(CPU_FTR_PMAO_BUG)
3407 lwz r3, HSTATE_PMC1(r13)
3408 lwz r4, HSTATE_PMC2(r13)
3409 lwz r5, HSTATE_PMC3(r13)
3410 lwz r6, HSTATE_PMC4(r13)
3411 lwz r8, HSTATE_PMC5(r13)
3412 lwz r9, HSTATE_PMC6(r13)
3413 mtspr SPRN_PMC1, r3
3414 mtspr SPRN_PMC2, r4
3415 mtspr SPRN_PMC3, r5
3416 mtspr SPRN_PMC4, r6
3417 mtspr SPRN_PMC5, r8
3418 mtspr SPRN_PMC6, r9
3419 ld r3, HSTATE_MMCR0(r13)
3420 ld r4, HSTATE_MMCR1(r13)
3421 ld r5, HSTATE_MMCRA(r13)
3422 ld r6, HSTATE_SIAR(r13)
3423 ld r7, HSTATE_SDAR(r13)
3424 mtspr SPRN_MMCR1, r4
3425 mtspr SPRN_MMCRA, r5
3426 mtspr SPRN_SIAR, r6
3427 mtspr SPRN_SDAR, r7
3428BEGIN_FTR_SECTION
3429 ld r8, HSTATE_MMCR2(r13)
3430 ld r9, HSTATE_SIER(r13)
3431 mtspr SPRN_MMCR2, r8
3432 mtspr SPRN_SIER, r9
3433END_FTR_SECTION_IFSET(CPU_FTR_ARCH_207S)
3434 mtspr SPRN_MMCR0, r3
3435 isync
3436 mtlr r0
343723: blr
3438
3439/*
3440 * Save guest PMU state into the vcpu struct.
3441 * r3 = vcpu, r4 = full save flag (PMU in use flag set in VPA)
3442 */
3443_GLOBAL(kvmhv_save_guest_pmu)
3444EXPORT_SYMBOL_GPL(kvmhv_save_guest_pmu)
3445 mr r9, r3
3446 mr r8, r4
3447BEGIN_FTR_SECTION
3448 /*
3449 * POWER8 seems to have a hardware bug where setting
3450 * MMCR0[PMAE] along with MMCR0[PMC1CE] and/or MMCR0[PMCjCE]
3451 * when some counters are already negative doesn't seem
3452 * to cause a performance monitor alert (and hence interrupt).
3453 * The effect of this is that when saving the PMU state,
3454 * if there is no PMU alert pending when we read MMCR0
3455 * before freezing the counters, but one becomes pending
3456 * before we read the counters, we lose it.
3457 * To work around this, we need a way to freeze the counters
3458 * before reading MMCR0. Normally, freezing the counters
3459 * is done by writing MMCR0 (to set MMCR0[FC]) which
3460 * unavoidably writes MMCR0[PMA0] as well. On POWER8,
3461 * we can also freeze the counters using MMCR2, by writing
3462 * 1s to all the counter freeze condition bits (there are
3463 * 9 bits each for 6 counters).
3464 */
3465 li r3, -1 /* set all freeze bits */
3466 clrrdi r3, r3, 10
3467 mfspr r10, SPRN_MMCR2
3468 mtspr SPRN_MMCR2, r3
3469 isync
3470END_FTR_SECTION_IFSET(CPU_FTR_ARCH_207S)
3471 li r3, 1
3472 sldi r3, r3, 31 /* MMCR0_FC (freeze counters) bit */
3473 mfspr r4, SPRN_MMCR0 /* save MMCR0 */
3474 mtspr SPRN_MMCR0, r3 /* freeze all counters, disable ints */
3475 mfspr r6, SPRN_MMCRA
3476 /* Clear MMCRA in order to disable SDAR updates */
3477 li r7, 0
3478 mtspr SPRN_MMCRA, r7
3479 isync
3480 cmpwi r8, 0 /* did they ask for PMU stuff to be saved? */
3481 bne 21f
3482 std r3, VCPU_MMCR(r9) /* if not, set saved MMCR0 to FC */
3483 b 22f
348421: mfspr r5, SPRN_MMCR1
3485 mfspr r7, SPRN_SIAR
3486 mfspr r8, SPRN_SDAR
3487 std r4, VCPU_MMCR(r9)
3488 std r5, VCPU_MMCR + 8(r9)
3489 std r6, VCPU_MMCR + 16(r9)
3490BEGIN_FTR_SECTION
3491 std r10, VCPU_MMCR + 24(r9)
3492END_FTR_SECTION_IFSET(CPU_FTR_ARCH_207S)
3493 std r7, VCPU_SIAR(r9)
3494 std r8, VCPU_SDAR(r9)
3495 mfspr r3, SPRN_PMC1
3496 mfspr r4, SPRN_PMC2
3497 mfspr r5, SPRN_PMC3
3498 mfspr r6, SPRN_PMC4
3499 mfspr r7, SPRN_PMC5
3500 mfspr r8, SPRN_PMC6
3501 stw r3, VCPU_PMC(r9)
3502 stw r4, VCPU_PMC + 4(r9)
3503 stw r5, VCPU_PMC + 8(r9)
3504 stw r6, VCPU_PMC + 12(r9)
3505 stw r7, VCPU_PMC + 16(r9)
3506 stw r8, VCPU_PMC + 20(r9)
3507BEGIN_FTR_SECTION
3508 mfspr r5, SPRN_SIER
3509 std r5, VCPU_SIER(r9)
3510BEGIN_FTR_SECTION_NESTED(96)
3511 mfspr r6, SPRN_SPMC1
3512 mfspr r7, SPRN_SPMC2
3513 mfspr r8, SPRN_MMCRS
3514 stw r6, VCPU_PMC + 24(r9)
3515 stw r7, VCPU_PMC + 28(r9)
3516 std r8, VCPU_MMCR + 32(r9)
3517 lis r4, 0x8000
3518 mtspr SPRN_MMCRS, r4
3519END_FTR_SECTION_NESTED(CPU_FTR_ARCH_300, 0, 96)
3520END_FTR_SECTION_IFSET(CPU_FTR_ARCH_207S)
352122: blr
3522
3523/*
3427 * This works around a hardware bug on POWER8E processors, where 3524 * This works around a hardware bug on POWER8E processors, where
3428 * writing a 1 to the MMCR0[PMAO] bit doesn't generate a 3525 * writing a 1 to the MMCR0[PMAO] bit doesn't generate a
3429 * performance monitor interrupt. Instead, when we need to have 3526 * performance monitor interrupt. Instead, when we need to have
diff --git a/arch/powerpc/kvm/book3s_hv_tm.c b/arch/powerpc/kvm/book3s_hv_tm.c
index 008285058f9b..888e2609e3f1 100644
--- a/arch/powerpc/kvm/book3s_hv_tm.c
+++ b/arch/powerpc/kvm/book3s_hv_tm.c
@@ -130,7 +130,7 @@ int kvmhv_p9_tm_emulation(struct kvm_vcpu *vcpu)
130 return RESUME_GUEST; 130 return RESUME_GUEST;
131 } 131 }
132 /* Set CR0 to indicate previous transactional state */ 132 /* Set CR0 to indicate previous transactional state */
133 vcpu->arch.cr = (vcpu->arch.cr & 0x0fffffff) | 133 vcpu->arch.regs.ccr = (vcpu->arch.regs.ccr & 0x0fffffff) |
134 (((msr & MSR_TS_MASK) >> MSR_TS_S_LG) << 28); 134 (((msr & MSR_TS_MASK) >> MSR_TS_S_LG) << 28);
135 /* L=1 => tresume, L=0 => tsuspend */ 135 /* L=1 => tresume, L=0 => tsuspend */
136 if (instr & (1 << 21)) { 136 if (instr & (1 << 21)) {
@@ -174,7 +174,7 @@ int kvmhv_p9_tm_emulation(struct kvm_vcpu *vcpu)
174 copy_from_checkpoint(vcpu); 174 copy_from_checkpoint(vcpu);
175 175
176 /* Set CR0 to indicate previous transactional state */ 176 /* Set CR0 to indicate previous transactional state */
177 vcpu->arch.cr = (vcpu->arch.cr & 0x0fffffff) | 177 vcpu->arch.regs.ccr = (vcpu->arch.regs.ccr & 0x0fffffff) |
178 (((msr & MSR_TS_MASK) >> MSR_TS_S_LG) << 28); 178 (((msr & MSR_TS_MASK) >> MSR_TS_S_LG) << 28);
179 vcpu->arch.shregs.msr &= ~MSR_TS_MASK; 179 vcpu->arch.shregs.msr &= ~MSR_TS_MASK;
180 return RESUME_GUEST; 180 return RESUME_GUEST;
@@ -204,7 +204,7 @@ int kvmhv_p9_tm_emulation(struct kvm_vcpu *vcpu)
204 copy_to_checkpoint(vcpu); 204 copy_to_checkpoint(vcpu);
205 205
206 /* Set CR0 to indicate previous transactional state */ 206 /* Set CR0 to indicate previous transactional state */
207 vcpu->arch.cr = (vcpu->arch.cr & 0x0fffffff) | 207 vcpu->arch.regs.ccr = (vcpu->arch.regs.ccr & 0x0fffffff) |
208 (((msr & MSR_TS_MASK) >> MSR_TS_S_LG) << 28); 208 (((msr & MSR_TS_MASK) >> MSR_TS_S_LG) << 28);
209 vcpu->arch.shregs.msr = msr | MSR_TS_S; 209 vcpu->arch.shregs.msr = msr | MSR_TS_S;
210 return RESUME_GUEST; 210 return RESUME_GUEST;
diff --git a/arch/powerpc/kvm/book3s_hv_tm_builtin.c b/arch/powerpc/kvm/book3s_hv_tm_builtin.c
index b2c7c6fca4f9..3cf5863bc06e 100644
--- a/arch/powerpc/kvm/book3s_hv_tm_builtin.c
+++ b/arch/powerpc/kvm/book3s_hv_tm_builtin.c
@@ -89,7 +89,8 @@ int kvmhv_p9_tm_emulation_early(struct kvm_vcpu *vcpu)
89 if (instr & (1 << 21)) 89 if (instr & (1 << 21))
90 vcpu->arch.shregs.msr = (msr & ~MSR_TS_MASK) | MSR_TS_T; 90 vcpu->arch.shregs.msr = (msr & ~MSR_TS_MASK) | MSR_TS_T;
91 /* Set CR0 to 0b0010 */ 91 /* Set CR0 to 0b0010 */
92 vcpu->arch.cr = (vcpu->arch.cr & 0x0fffffff) | 0x20000000; 92 vcpu->arch.regs.ccr = (vcpu->arch.regs.ccr & 0x0fffffff) |
93 0x20000000;
93 return 1; 94 return 1;
94 } 95 }
95 96
@@ -105,5 +106,5 @@ void kvmhv_emulate_tm_rollback(struct kvm_vcpu *vcpu)
105 vcpu->arch.shregs.msr &= ~MSR_TS_MASK; /* go to N state */ 106 vcpu->arch.shregs.msr &= ~MSR_TS_MASK; /* go to N state */
106 vcpu->arch.regs.nip = vcpu->arch.tfhar; 107 vcpu->arch.regs.nip = vcpu->arch.tfhar;
107 copy_from_checkpoint(vcpu); 108 copy_from_checkpoint(vcpu);
108 vcpu->arch.cr = (vcpu->arch.cr & 0x0fffffff) | 0xa0000000; 109 vcpu->arch.regs.ccr = (vcpu->arch.regs.ccr & 0x0fffffff) | 0xa0000000;
109} 110}
diff --git a/arch/powerpc/kvm/book3s_pr.c b/arch/powerpc/kvm/book3s_pr.c
index 614ebb4261f7..4efd65d9e828 100644
--- a/arch/powerpc/kvm/book3s_pr.c
+++ b/arch/powerpc/kvm/book3s_pr.c
@@ -167,7 +167,7 @@ void kvmppc_copy_to_svcpu(struct kvm_vcpu *vcpu)
167 svcpu->gpr[11] = vcpu->arch.regs.gpr[11]; 167 svcpu->gpr[11] = vcpu->arch.regs.gpr[11];
168 svcpu->gpr[12] = vcpu->arch.regs.gpr[12]; 168 svcpu->gpr[12] = vcpu->arch.regs.gpr[12];
169 svcpu->gpr[13] = vcpu->arch.regs.gpr[13]; 169 svcpu->gpr[13] = vcpu->arch.regs.gpr[13];
170 svcpu->cr = vcpu->arch.cr; 170 svcpu->cr = vcpu->arch.regs.ccr;
171 svcpu->xer = vcpu->arch.regs.xer; 171 svcpu->xer = vcpu->arch.regs.xer;
172 svcpu->ctr = vcpu->arch.regs.ctr; 172 svcpu->ctr = vcpu->arch.regs.ctr;
173 svcpu->lr = vcpu->arch.regs.link; 173 svcpu->lr = vcpu->arch.regs.link;
@@ -249,7 +249,7 @@ void kvmppc_copy_from_svcpu(struct kvm_vcpu *vcpu)
249 vcpu->arch.regs.gpr[11] = svcpu->gpr[11]; 249 vcpu->arch.regs.gpr[11] = svcpu->gpr[11];
250 vcpu->arch.regs.gpr[12] = svcpu->gpr[12]; 250 vcpu->arch.regs.gpr[12] = svcpu->gpr[12];
251 vcpu->arch.regs.gpr[13] = svcpu->gpr[13]; 251 vcpu->arch.regs.gpr[13] = svcpu->gpr[13];
252 vcpu->arch.cr = svcpu->cr; 252 vcpu->arch.regs.ccr = svcpu->cr;
253 vcpu->arch.regs.xer = svcpu->xer; 253 vcpu->arch.regs.xer = svcpu->xer;
254 vcpu->arch.regs.ctr = svcpu->ctr; 254 vcpu->arch.regs.ctr = svcpu->ctr;
255 vcpu->arch.regs.link = svcpu->lr; 255 vcpu->arch.regs.link = svcpu->lr;
@@ -1246,7 +1246,6 @@ int kvmppc_handle_exit_pr(struct kvm_run *run, struct kvm_vcpu *vcpu,
1246 r = RESUME_GUEST; 1246 r = RESUME_GUEST;
1247 break; 1247 break;
1248 case BOOK3S_INTERRUPT_EXTERNAL: 1248 case BOOK3S_INTERRUPT_EXTERNAL:
1249 case BOOK3S_INTERRUPT_EXTERNAL_LEVEL:
1250 case BOOK3S_INTERRUPT_EXTERNAL_HV: 1249 case BOOK3S_INTERRUPT_EXTERNAL_HV:
1251 case BOOK3S_INTERRUPT_H_VIRT: 1250 case BOOK3S_INTERRUPT_H_VIRT:
1252 vcpu->stat.ext_intr_exits++; 1251 vcpu->stat.ext_intr_exits++;
diff --git a/arch/powerpc/kvm/book3s_xics.c b/arch/powerpc/kvm/book3s_xics.c
index b8356cdc0c04..b0b2bfc2ff51 100644
--- a/arch/powerpc/kvm/book3s_xics.c
+++ b/arch/powerpc/kvm/book3s_xics.c
@@ -310,7 +310,7 @@ static inline bool icp_try_update(struct kvmppc_icp *icp,
310 */ 310 */
311 if (new.out_ee) { 311 if (new.out_ee) {
312 kvmppc_book3s_queue_irqprio(icp->vcpu, 312 kvmppc_book3s_queue_irqprio(icp->vcpu,
313 BOOK3S_INTERRUPT_EXTERNAL_LEVEL); 313 BOOK3S_INTERRUPT_EXTERNAL);
314 if (!change_self) 314 if (!change_self)
315 kvmppc_fast_vcpu_kick(icp->vcpu); 315 kvmppc_fast_vcpu_kick(icp->vcpu);
316 } 316 }
@@ -593,8 +593,7 @@ static noinline unsigned long kvmppc_h_xirr(struct kvm_vcpu *vcpu)
593 u32 xirr; 593 u32 xirr;
594 594
595 /* First, remove EE from the processor */ 595 /* First, remove EE from the processor */
596 kvmppc_book3s_dequeue_irqprio(icp->vcpu, 596 kvmppc_book3s_dequeue_irqprio(icp->vcpu, BOOK3S_INTERRUPT_EXTERNAL);
597 BOOK3S_INTERRUPT_EXTERNAL_LEVEL);
598 597
599 /* 598 /*
600 * ICP State: Accept_Interrupt 599 * ICP State: Accept_Interrupt
@@ -754,8 +753,7 @@ static noinline void kvmppc_h_cppr(struct kvm_vcpu *vcpu, unsigned long cppr)
754 * We can remove EE from the current processor, the update 753 * We can remove EE from the current processor, the update
755 * transaction will set it again if needed 754 * transaction will set it again if needed
756 */ 755 */
757 kvmppc_book3s_dequeue_irqprio(icp->vcpu, 756 kvmppc_book3s_dequeue_irqprio(icp->vcpu, BOOK3S_INTERRUPT_EXTERNAL);
758 BOOK3S_INTERRUPT_EXTERNAL_LEVEL);
759 757
760 do { 758 do {
761 old_state = new_state = READ_ONCE(icp->state); 759 old_state = new_state = READ_ONCE(icp->state);
@@ -1167,8 +1165,7 @@ int kvmppc_xics_set_icp(struct kvm_vcpu *vcpu, u64 icpval)
1167 * Deassert the CPU interrupt request. 1165 * Deassert the CPU interrupt request.
1168 * icp_try_update will reassert it if necessary. 1166 * icp_try_update will reassert it if necessary.
1169 */ 1167 */
1170 kvmppc_book3s_dequeue_irqprio(icp->vcpu, 1168 kvmppc_book3s_dequeue_irqprio(icp->vcpu, BOOK3S_INTERRUPT_EXTERNAL);
1171 BOOK3S_INTERRUPT_EXTERNAL_LEVEL);
1172 1169
1173 /* 1170 /*
1174 * Note that if we displace an interrupt from old_state.xisr, 1171 * Note that if we displace an interrupt from old_state.xisr,
@@ -1393,7 +1390,8 @@ static int kvmppc_xics_create(struct kvm_device *dev, u32 type)
1393 } 1390 }
1394 1391
1395#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE 1392#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
1396 if (cpu_has_feature(CPU_FTR_ARCH_206)) { 1393 if (cpu_has_feature(CPU_FTR_ARCH_206) &&
1394 cpu_has_feature(CPU_FTR_HVMODE)) {
1397 /* Enable real mode support */ 1395 /* Enable real mode support */
1398 xics->real_mode = ENABLE_REALMODE; 1396 xics->real_mode = ENABLE_REALMODE;
1399 xics->real_mode_dbg = DEBUG_REALMODE; 1397 xics->real_mode_dbg = DEBUG_REALMODE;
diff --git a/arch/powerpc/kvm/book3s_xive.c b/arch/powerpc/kvm/book3s_xive.c
index 30c2eb766954..ad4a370703d3 100644
--- a/arch/powerpc/kvm/book3s_xive.c
+++ b/arch/powerpc/kvm/book3s_xive.c
@@ -62,6 +62,69 @@
62#define XIVE_Q_GAP 2 62#define XIVE_Q_GAP 2
63 63
64/* 64/*
65 * Push a vcpu's context to the XIVE on guest entry.
66 * This assumes we are in virtual mode (MMU on)
67 */
68void kvmppc_xive_push_vcpu(struct kvm_vcpu *vcpu)
69{
70 void __iomem *tima = local_paca->kvm_hstate.xive_tima_virt;
71 u64 pq;
72
73 if (!tima)
74 return;
75 eieio();
76 __raw_writeq(vcpu->arch.xive_saved_state.w01, tima + TM_QW1_OS);
77 __raw_writel(vcpu->arch.xive_cam_word, tima + TM_QW1_OS + TM_WORD2);
78 vcpu->arch.xive_pushed = 1;
79 eieio();
80
81 /*
82 * We clear the irq_pending flag. There is a small chance of a
83 * race vs. the escalation interrupt happening on another
84 * processor setting it again, but the only consequence is to
85 * cause a spurious wakeup on the next H_CEDE, which is not an
86 * issue.
87 */
88 vcpu->arch.irq_pending = 0;
89
90 /*
91 * In single escalation mode, if the escalation interrupt is
92 * on, we mask it.
93 */
94 if (vcpu->arch.xive_esc_on) {
95 pq = __raw_readq((void __iomem *)(vcpu->arch.xive_esc_vaddr +
96 XIVE_ESB_SET_PQ_01));
97 mb();
98
99 /*
100 * We have a possible subtle race here: The escalation
101 * interrupt might have fired and be on its way to the
102 * host queue while we mask it, and if we unmask it
103 * early enough (re-cede right away), there is a
104 * theorical possibility that it fires again, thus
105 * landing in the target queue more than once which is
106 * a big no-no.
107 *
108 * Fortunately, solving this is rather easy. If the
109 * above load setting PQ to 01 returns a previous
110 * value where P is set, then we know the escalation
111 * interrupt is somewhere on its way to the host. In
112 * that case we simply don't clear the xive_esc_on
113 * flag below. It will be eventually cleared by the
114 * handler for the escalation interrupt.
115 *
116 * Then, when doing a cede, we check that flag again
117 * before re-enabling the escalation interrupt, and if
118 * set, we abort the cede.
119 */
120 if (!(pq & XIVE_ESB_VAL_P))
121 /* Now P is 0, we can clear the flag */
122 vcpu->arch.xive_esc_on = 0;
123 }
124}
125EXPORT_SYMBOL_GPL(kvmppc_xive_push_vcpu);
126
127/*
65 * This is a simple trigger for a generic XIVE IRQ. This must 128 * This is a simple trigger for a generic XIVE IRQ. This must
66 * only be called for interrupts that support a trigger page 129 * only be called for interrupts that support a trigger page
67 */ 130 */
diff --git a/arch/powerpc/kvm/book3s_xive_template.c b/arch/powerpc/kvm/book3s_xive_template.c
index 4171ede8722b..033363d6e764 100644
--- a/arch/powerpc/kvm/book3s_xive_template.c
+++ b/arch/powerpc/kvm/book3s_xive_template.c
@@ -280,14 +280,6 @@ X_STATIC unsigned long GLUE(X_PFX,h_xirr)(struct kvm_vcpu *vcpu)
280 /* First collect pending bits from HW */ 280 /* First collect pending bits from HW */
281 GLUE(X_PFX,ack_pending)(xc); 281 GLUE(X_PFX,ack_pending)(xc);
282 282
283 /*
284 * Cleanup the old-style bits if needed (they may have been
285 * set by pull or an escalation interrupts).
286 */
287 if (test_bit(BOOK3S_IRQPRIO_EXTERNAL, &vcpu->arch.pending_exceptions))
288 clear_bit(BOOK3S_IRQPRIO_EXTERNAL_LEVEL,
289 &vcpu->arch.pending_exceptions);
290
291 pr_devel(" new pending=0x%02x hw_cppr=%d cppr=%d\n", 283 pr_devel(" new pending=0x%02x hw_cppr=%d cppr=%d\n",
292 xc->pending, xc->hw_cppr, xc->cppr); 284 xc->pending, xc->hw_cppr, xc->cppr);
293 285
diff --git a/arch/powerpc/kvm/bookehv_interrupts.S b/arch/powerpc/kvm/bookehv_interrupts.S
index 81bd8a07aa51..051af7d97327 100644
--- a/arch/powerpc/kvm/bookehv_interrupts.S
+++ b/arch/powerpc/kvm/bookehv_interrupts.S
@@ -182,7 +182,7 @@
182 */ 182 */
183 PPC_LL r4, PACACURRENT(r13) 183 PPC_LL r4, PACACURRENT(r13)
184 PPC_LL r4, (THREAD + THREAD_KVM_VCPU)(r4) 184 PPC_LL r4, (THREAD + THREAD_KVM_VCPU)(r4)
185 stw r10, VCPU_CR(r4) 185 PPC_STL r10, VCPU_CR(r4)
186 PPC_STL r11, VCPU_GPR(R4)(r4) 186 PPC_STL r11, VCPU_GPR(R4)(r4)
187 PPC_STL r5, VCPU_GPR(R5)(r4) 187 PPC_STL r5, VCPU_GPR(R5)(r4)
188 PPC_STL r6, VCPU_GPR(R6)(r4) 188 PPC_STL r6, VCPU_GPR(R6)(r4)
@@ -292,7 +292,7 @@ _GLOBAL(kvmppc_handler_\intno\()_\srr1)
292 PPC_STL r4, VCPU_GPR(R4)(r11) 292 PPC_STL r4, VCPU_GPR(R4)(r11)
293 PPC_LL r4, THREAD_NORMSAVE(0)(r10) 293 PPC_LL r4, THREAD_NORMSAVE(0)(r10)
294 PPC_STL r5, VCPU_GPR(R5)(r11) 294 PPC_STL r5, VCPU_GPR(R5)(r11)
295 stw r13, VCPU_CR(r11) 295 PPC_STL r13, VCPU_CR(r11)
296 mfspr r5, \srr0 296 mfspr r5, \srr0
297 PPC_STL r3, VCPU_GPR(R10)(r11) 297 PPC_STL r3, VCPU_GPR(R10)(r11)
298 PPC_LL r3, THREAD_NORMSAVE(2)(r10) 298 PPC_LL r3, THREAD_NORMSAVE(2)(r10)
@@ -319,7 +319,7 @@ _GLOBAL(kvmppc_handler_\intno\()_\srr1)
319 PPC_STL r4, VCPU_GPR(R4)(r11) 319 PPC_STL r4, VCPU_GPR(R4)(r11)
320 PPC_LL r4, GPR9(r8) 320 PPC_LL r4, GPR9(r8)
321 PPC_STL r5, VCPU_GPR(R5)(r11) 321 PPC_STL r5, VCPU_GPR(R5)(r11)
322 stw r9, VCPU_CR(r11) 322 PPC_STL r9, VCPU_CR(r11)
323 mfspr r5, \srr0 323 mfspr r5, \srr0
324 PPC_STL r3, VCPU_GPR(R8)(r11) 324 PPC_STL r3, VCPU_GPR(R8)(r11)
325 PPC_LL r3, GPR10(r8) 325 PPC_LL r3, GPR10(r8)
@@ -643,7 +643,7 @@ lightweight_exit:
643 PPC_LL r3, VCPU_LR(r4) 643 PPC_LL r3, VCPU_LR(r4)
644 PPC_LL r5, VCPU_XER(r4) 644 PPC_LL r5, VCPU_XER(r4)
645 PPC_LL r6, VCPU_CTR(r4) 645 PPC_LL r6, VCPU_CTR(r4)
646 lwz r7, VCPU_CR(r4) 646 PPC_LL r7, VCPU_CR(r4)
647 PPC_LL r8, VCPU_PC(r4) 647 PPC_LL r8, VCPU_PC(r4)
648 PPC_LD(r9, VCPU_SHARED_MSR, r11) 648 PPC_LD(r9, VCPU_SHARED_MSR, r11)
649 PPC_LL r0, VCPU_GPR(R0)(r4) 649 PPC_LL r0, VCPU_GPR(R0)(r4)
diff --git a/arch/powerpc/kvm/emulate_loadstore.c b/arch/powerpc/kvm/emulate_loadstore.c
index 75dce1ef3bc8..f91b1309a0a8 100644
--- a/arch/powerpc/kvm/emulate_loadstore.c
+++ b/arch/powerpc/kvm/emulate_loadstore.c
@@ -117,7 +117,6 @@ int kvmppc_emulate_loadstore(struct kvm_vcpu *vcpu)
117 117
118 emulated = EMULATE_FAIL; 118 emulated = EMULATE_FAIL;
119 vcpu->arch.regs.msr = vcpu->arch.shared->msr; 119 vcpu->arch.regs.msr = vcpu->arch.shared->msr;
120 vcpu->arch.regs.ccr = vcpu->arch.cr;
121 if (analyse_instr(&op, &vcpu->arch.regs, inst) == 0) { 120 if (analyse_instr(&op, &vcpu->arch.regs, inst) == 0) {
122 int type = op.type & INSTR_TYPE_MASK; 121 int type = op.type & INSTR_TYPE_MASK;
123 int size = GETSIZE(op.type); 122 int size = GETSIZE(op.type);
diff --git a/arch/powerpc/kvm/powerpc.c b/arch/powerpc/kvm/powerpc.c
index eba5756d5b41..2869a299c4ed 100644
--- a/arch/powerpc/kvm/powerpc.c
+++ b/arch/powerpc/kvm/powerpc.c
@@ -594,7 +594,12 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
594 r = !!(hv_enabled && radix_enabled()); 594 r = !!(hv_enabled && radix_enabled());
595 break; 595 break;
596 case KVM_CAP_PPC_MMU_HASH_V3: 596 case KVM_CAP_PPC_MMU_HASH_V3:
597 r = !!(hv_enabled && cpu_has_feature(CPU_FTR_ARCH_300)); 597 r = !!(hv_enabled && cpu_has_feature(CPU_FTR_ARCH_300) &&
598 cpu_has_feature(CPU_FTR_HVMODE));
599 break;
600 case KVM_CAP_PPC_NESTED_HV:
601 r = !!(hv_enabled && kvmppc_hv_ops->enable_nested &&
602 !kvmppc_hv_ops->enable_nested(NULL));
598 break; 603 break;
599#endif 604#endif
600 case KVM_CAP_SYNC_MMU: 605 case KVM_CAP_SYNC_MMU:
@@ -2114,6 +2119,14 @@ static int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
2114 r = kvm->arch.kvm_ops->set_smt_mode(kvm, mode, flags); 2119 r = kvm->arch.kvm_ops->set_smt_mode(kvm, mode, flags);
2115 break; 2120 break;
2116 } 2121 }
2122
2123 case KVM_CAP_PPC_NESTED_HV:
2124 r = -EINVAL;
2125 if (!is_kvmppc_hv_enabled(kvm) ||
2126 !kvm->arch.kvm_ops->enable_nested)
2127 break;
2128 r = kvm->arch.kvm_ops->enable_nested(kvm);
2129 break;
2117#endif 2130#endif
2118 default: 2131 default:
2119 r = -EINVAL; 2132 r = -EINVAL;
diff --git a/arch/powerpc/kvm/tm.S b/arch/powerpc/kvm/tm.S
index 90e330f21356..0531a1492fdf 100644
--- a/arch/powerpc/kvm/tm.S
+++ b/arch/powerpc/kvm/tm.S
@@ -28,17 +28,25 @@
28 * Save transactional state and TM-related registers. 28 * Save transactional state and TM-related registers.
29 * Called with: 29 * Called with:
30 * - r3 pointing to the vcpu struct 30 * - r3 pointing to the vcpu struct
31 * - r4 points to the MSR with current TS bits: 31 * - r4 containing the MSR with current TS bits:
32 * (For HV KVM, it is VCPU_MSR ; For PR KVM, it is host MSR). 32 * (For HV KVM, it is VCPU_MSR ; For PR KVM, it is host MSR).
33 * This can modify all checkpointed registers, but 33 * - r5 containing a flag indicating that non-volatile registers
34 * restores r1, r2 before exit. 34 * must be preserved.
35 * If r5 == 0, this can modify all checkpointed registers, but
36 * restores r1, r2 before exit. If r5 != 0, this restores the
37 * MSR TM/FP/VEC/VSX bits to their state on entry.
35 */ 38 */
36_GLOBAL(__kvmppc_save_tm) 39_GLOBAL(__kvmppc_save_tm)
37 mflr r0 40 mflr r0
38 std r0, PPC_LR_STKOFF(r1) 41 std r0, PPC_LR_STKOFF(r1)
42 stdu r1, -SWITCH_FRAME_SIZE(r1)
43
44 mr r9, r3
45 cmpdi cr7, r5, 0
39 46
40 /* Turn on TM. */ 47 /* Turn on TM. */
41 mfmsr r8 48 mfmsr r8
49 mr r10, r8
42 li r0, 1 50 li r0, 1
43 rldimi r8, r0, MSR_TM_LG, 63-MSR_TM_LG 51 rldimi r8, r0, MSR_TM_LG, 63-MSR_TM_LG
44 ori r8, r8, MSR_FP 52 ori r8, r8, MSR_FP
@@ -51,6 +59,27 @@ _GLOBAL(__kvmppc_save_tm)
51 std r1, HSTATE_SCRATCH2(r13) 59 std r1, HSTATE_SCRATCH2(r13)
52 std r3, HSTATE_SCRATCH1(r13) 60 std r3, HSTATE_SCRATCH1(r13)
53 61
62 /* Save CR on the stack - even if r5 == 0 we need to get cr7 back. */
63 mfcr r6
64 SAVE_GPR(6, r1)
65
66 /* Save DSCR so we can restore it to avoid running with user value */
67 mfspr r7, SPRN_DSCR
68 SAVE_GPR(7, r1)
69
70 /*
71 * We are going to do treclaim., which will modify all checkpointed
72 * registers. Save the non-volatile registers on the stack if
73 * preservation of non-volatile state has been requested.
74 */
75 beq cr7, 3f
76 SAVE_NVGPRS(r1)
77
78 /* MSR[TS] will be 0 (non-transactional) once we do treclaim. */
79 li r0, 0
80 rldimi r10, r0, MSR_TS_S_LG, 63 - MSR_TS_T_LG
81 SAVE_GPR(10, r1) /* final MSR value */
823:
54#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE 83#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
55BEGIN_FTR_SECTION 84BEGIN_FTR_SECTION
56 /* Emulation of the treclaim instruction needs TEXASR before treclaim */ 85 /* Emulation of the treclaim instruction needs TEXASR before treclaim */
@@ -74,22 +103,25 @@ END_FTR_SECTION_IFSET(CPU_FTR_P9_TM_HV_ASSIST)
74 std r9, PACATMSCRATCH(r13) 103 std r9, PACATMSCRATCH(r13)
75 ld r9, HSTATE_SCRATCH1(r13) 104 ld r9, HSTATE_SCRATCH1(r13)
76 105
77 /* Get a few more GPRs free. */ 106 /* Save away PPR soon so we don't run with user value. */
78 std r29, VCPU_GPRS_TM(29)(r9) 107 std r0, VCPU_GPRS_TM(0)(r9)
79 std r30, VCPU_GPRS_TM(30)(r9) 108 mfspr r0, SPRN_PPR
80 std r31, VCPU_GPRS_TM(31)(r9)
81
82 /* Save away PPR and DSCR soon so don't run with user values. */
83 mfspr r31, SPRN_PPR
84 HMT_MEDIUM 109 HMT_MEDIUM
85 mfspr r30, SPRN_DSCR
86#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
87 ld r29, HSTATE_DSCR(r13)
88 mtspr SPRN_DSCR, r29
89#endif
90 110
91 /* Save all but r9, r13 & r29-r31 */ 111 /* Reload stack pointer. */
92 reg = 0 112 std r1, VCPU_GPRS_TM(1)(r9)
113 ld r1, HSTATE_SCRATCH2(r13)
114
115 /* Set MSR RI now we have r1 and r13 back. */
116 std r2, VCPU_GPRS_TM(2)(r9)
117 li r2, MSR_RI
118 mtmsrd r2, 1
119
120 /* Reload TOC pointer. */
121 ld r2, PACATOC(r13)
122
123 /* Save all but r0-r2, r9 & r13 */
124 reg = 3
93 .rept 29 125 .rept 29
94 .if (reg != 9) && (reg != 13) 126 .if (reg != 9) && (reg != 13)
95 std reg, VCPU_GPRS_TM(reg)(r9) 127 std reg, VCPU_GPRS_TM(reg)(r9)
@@ -103,33 +135,29 @@ END_FTR_SECTION_IFSET(CPU_FTR_P9_TM_HV_ASSIST)
103 ld r4, PACATMSCRATCH(r13) 135 ld r4, PACATMSCRATCH(r13)
104 std r4, VCPU_GPRS_TM(9)(r9) 136 std r4, VCPU_GPRS_TM(9)(r9)
105 137
106 /* Reload stack pointer and TOC. */ 138 /* Restore host DSCR and CR values, after saving guest values */
107 ld r1, HSTATE_SCRATCH2(r13) 139 mfcr r6
108 ld r2, PACATOC(r13) 140 mfspr r7, SPRN_DSCR
109 141 stw r6, VCPU_CR_TM(r9)
110 /* Set MSR RI now we have r1 and r13 back. */ 142 std r7, VCPU_DSCR_TM(r9)
111 li r5, MSR_RI 143 REST_GPR(6, r1)
112 mtmsrd r5, 1 144 REST_GPR(7, r1)
145 mtcr r6
146 mtspr SPRN_DSCR, r7
113 147
114 /* Save away checkpinted SPRs. */ 148 /* Save away checkpointed SPRs. */
115 std r31, VCPU_PPR_TM(r9) 149 std r0, VCPU_PPR_TM(r9)
116 std r30, VCPU_DSCR_TM(r9)
117 mflr r5 150 mflr r5
118 mfcr r6
119 mfctr r7 151 mfctr r7
120 mfspr r8, SPRN_AMR 152 mfspr r8, SPRN_AMR
121 mfspr r10, SPRN_TAR 153 mfspr r10, SPRN_TAR
122 mfxer r11 154 mfxer r11
123 std r5, VCPU_LR_TM(r9) 155 std r5, VCPU_LR_TM(r9)
124 stw r6, VCPU_CR_TM(r9)
125 std r7, VCPU_CTR_TM(r9) 156 std r7, VCPU_CTR_TM(r9)
126 std r8, VCPU_AMR_TM(r9) 157 std r8, VCPU_AMR_TM(r9)
127 std r10, VCPU_TAR_TM(r9) 158 std r10, VCPU_TAR_TM(r9)
128 std r11, VCPU_XER_TM(r9) 159 std r11, VCPU_XER_TM(r9)
129 160
130 /* Restore r12 as trap number. */
131 lwz r12, VCPU_TRAP(r9)
132
133 /* Save FP/VSX. */ 161 /* Save FP/VSX. */
134 addi r3, r9, VCPU_FPRS_TM 162 addi r3, r9, VCPU_FPRS_TM
135 bl store_fp_state 163 bl store_fp_state
@@ -137,6 +165,11 @@ END_FTR_SECTION_IFSET(CPU_FTR_P9_TM_HV_ASSIST)
137 bl store_vr_state 165 bl store_vr_state
138 mfspr r6, SPRN_VRSAVE 166 mfspr r6, SPRN_VRSAVE
139 stw r6, VCPU_VRSAVE_TM(r9) 167 stw r6, VCPU_VRSAVE_TM(r9)
168
169 /* Restore non-volatile registers if requested to */
170 beq cr7, 1f
171 REST_NVGPRS(r1)
172 REST_GPR(10, r1)
1401: 1731:
141 /* 174 /*
142 * We need to save these SPRs after the treclaim so that the software 175 * We need to save these SPRs after the treclaim so that the software
@@ -146,12 +179,16 @@ END_FTR_SECTION_IFSET(CPU_FTR_P9_TM_HV_ASSIST)
146 */ 179 */
147 mfspr r7, SPRN_TEXASR 180 mfspr r7, SPRN_TEXASR
148 std r7, VCPU_TEXASR(r9) 181 std r7, VCPU_TEXASR(r9)
14911:
150 mfspr r5, SPRN_TFHAR 182 mfspr r5, SPRN_TFHAR
151 mfspr r6, SPRN_TFIAR 183 mfspr r6, SPRN_TFIAR
152 std r5, VCPU_TFHAR(r9) 184 std r5, VCPU_TFHAR(r9)
153 std r6, VCPU_TFIAR(r9) 185 std r6, VCPU_TFIAR(r9)
154 186
187 /* Restore MSR state if requested */
188 beq cr7, 2f
189 mtmsrd r10, 0
1902:
191 addi r1, r1, SWITCH_FRAME_SIZE
155 ld r0, PPC_LR_STKOFF(r1) 192 ld r0, PPC_LR_STKOFF(r1)
156 mtlr r0 193 mtlr r0
157 blr 194 blr
@@ -161,49 +198,22 @@ END_FTR_SECTION_IFSET(CPU_FTR_P9_TM_HV_ASSIST)
161 * be invoked from C function by PR KVM only. 198 * be invoked from C function by PR KVM only.
162 */ 199 */
163_GLOBAL(_kvmppc_save_tm_pr) 200_GLOBAL(_kvmppc_save_tm_pr)
164 mflr r5 201 mflr r0
165 std r5, PPC_LR_STKOFF(r1) 202 std r0, PPC_LR_STKOFF(r1)
166 stdu r1, -SWITCH_FRAME_SIZE(r1) 203 stdu r1, -PPC_MIN_STKFRM(r1)
167 SAVE_NVGPRS(r1)
168
169 /* save MSR since TM/math bits might be impacted
170 * by __kvmppc_save_tm().
171 */
172 mfmsr r5
173 SAVE_GPR(5, r1)
174
175 /* also save DSCR/CR/TAR so that it can be recovered later */
176 mfspr r6, SPRN_DSCR
177 SAVE_GPR(6, r1)
178
179 mfcr r7
180 stw r7, _CCR(r1)
181 204
182 mfspr r8, SPRN_TAR 205 mfspr r8, SPRN_TAR
183 SAVE_GPR(8, r1) 206 std r8, PPC_MIN_STKFRM-8(r1)
184 207
208 li r5, 1 /* preserve non-volatile registers */
185 bl __kvmppc_save_tm 209 bl __kvmppc_save_tm
186 210
187 REST_GPR(8, r1) 211 ld r8, PPC_MIN_STKFRM-8(r1)
188 mtspr SPRN_TAR, r8 212 mtspr SPRN_TAR, r8
189 213
190 ld r7, _CCR(r1) 214 addi r1, r1, PPC_MIN_STKFRM
191 mtcr r7 215 ld r0, PPC_LR_STKOFF(r1)
192 216 mtlr r0
193 REST_GPR(6, r1)
194 mtspr SPRN_DSCR, r6
195
196 /* need preserve current MSR's MSR_TS bits */
197 REST_GPR(5, r1)
198 mfmsr r6
199 rldicl r6, r6, 64 - MSR_TS_S_LG, 62
200 rldimi r5, r6, MSR_TS_S_LG, 63 - MSR_TS_T_LG
201 mtmsrd r5
202
203 REST_NVGPRS(r1)
204 addi r1, r1, SWITCH_FRAME_SIZE
205 ld r5, PPC_LR_STKOFF(r1)
206 mtlr r5
207 blr 217 blr
208 218
209EXPORT_SYMBOL_GPL(_kvmppc_save_tm_pr); 219EXPORT_SYMBOL_GPL(_kvmppc_save_tm_pr);
@@ -215,15 +225,21 @@ EXPORT_SYMBOL_GPL(_kvmppc_save_tm_pr);
215 * - r4 is the guest MSR with desired TS bits: 225 * - r4 is the guest MSR with desired TS bits:
216 * For HV KVM, it is VCPU_MSR 226 * For HV KVM, it is VCPU_MSR
217 * For PR KVM, it is provided by caller 227 * For PR KVM, it is provided by caller
218 * This potentially modifies all checkpointed registers. 228 * - r5 containing a flag indicating that non-volatile registers
219 * It restores r1, r2 from the PACA. 229 * must be preserved.
230 * If r5 == 0, this potentially modifies all checkpointed registers, but
231 * restores r1, r2 from the PACA before exit.
232 * If r5 != 0, this restores the MSR TM/FP/VEC/VSX bits to their state on entry.
220 */ 233 */
221_GLOBAL(__kvmppc_restore_tm) 234_GLOBAL(__kvmppc_restore_tm)
222 mflr r0 235 mflr r0
223 std r0, PPC_LR_STKOFF(r1) 236 std r0, PPC_LR_STKOFF(r1)
224 237
238 cmpdi cr7, r5, 0
239
225 /* Turn on TM/FP/VSX/VMX so we can restore them. */ 240 /* Turn on TM/FP/VSX/VMX so we can restore them. */
226 mfmsr r5 241 mfmsr r5
242 mr r10, r5
227 li r6, MSR_TM >> 32 243 li r6, MSR_TM >> 32
228 sldi r6, r6, 32 244 sldi r6, r6, 32
229 or r5, r5, r6 245 or r5, r5, r6
@@ -244,8 +260,7 @@ _GLOBAL(__kvmppc_restore_tm)
244 260
245 mr r5, r4 261 mr r5, r4
246 rldicl. r5, r5, 64 - MSR_TS_S_LG, 62 262 rldicl. r5, r5, 64 - MSR_TS_S_LG, 62
247 beqlr /* TM not active in guest */ 263 beq 9f /* TM not active in guest */
248 std r1, HSTATE_SCRATCH2(r13)
249 264
250 /* Make sure the failure summary is set, otherwise we'll program check 265 /* Make sure the failure summary is set, otherwise we'll program check
251 * when we trechkpt. It's possible that this might have been not set 266 * when we trechkpt. It's possible that this might have been not set
@@ -256,6 +271,26 @@ _GLOBAL(__kvmppc_restore_tm)
256 mtspr SPRN_TEXASR, r7 271 mtspr SPRN_TEXASR, r7
257 272
258 /* 273 /*
274 * Make a stack frame and save non-volatile registers if requested.
275 */
276 stdu r1, -SWITCH_FRAME_SIZE(r1)
277 std r1, HSTATE_SCRATCH2(r13)
278
279 mfcr r6
280 mfspr r7, SPRN_DSCR
281 SAVE_GPR(2, r1)
282 SAVE_GPR(6, r1)
283 SAVE_GPR(7, r1)
284
285 beq cr7, 4f
286 SAVE_NVGPRS(r1)
287
288 /* MSR[TS] will be 1 (suspended) once we do trechkpt */
289 li r0, 1
290 rldimi r10, r0, MSR_TS_S_LG, 63 - MSR_TS_T_LG
291 SAVE_GPR(10, r1) /* final MSR value */
2924:
293 /*
259 * We need to load up the checkpointed state for the guest. 294 * We need to load up the checkpointed state for the guest.
260 * We need to do this early as it will blow away any GPRs, VSRs and 295 * We need to do this early as it will blow away any GPRs, VSRs and
261 * some SPRs. 296 * some SPRs.
@@ -291,8 +326,6 @@ _GLOBAL(__kvmppc_restore_tm)
291 ld r29, VCPU_DSCR_TM(r3) 326 ld r29, VCPU_DSCR_TM(r3)
292 ld r30, VCPU_PPR_TM(r3) 327 ld r30, VCPU_PPR_TM(r3)
293 328
294 std r2, PACATMSCRATCH(r13) /* Save TOC */
295
296 /* Clear the MSR RI since r1, r13 are all going to be foobar. */ 329 /* Clear the MSR RI since r1, r13 are all going to be foobar. */
297 li r5, 0 330 li r5, 0
298 mtmsrd r5, 1 331 mtmsrd r5, 1
@@ -318,18 +351,31 @@ _GLOBAL(__kvmppc_restore_tm)
318 /* Now let's get back the state we need. */ 351 /* Now let's get back the state we need. */
319 HMT_MEDIUM 352 HMT_MEDIUM
320 GET_PACA(r13) 353 GET_PACA(r13)
321#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
322 ld r29, HSTATE_DSCR(r13)
323 mtspr SPRN_DSCR, r29
324#endif
325 ld r1, HSTATE_SCRATCH2(r13) 354 ld r1, HSTATE_SCRATCH2(r13)
326 ld r2, PACATMSCRATCH(r13) 355 REST_GPR(7, r1)
356 mtspr SPRN_DSCR, r7
327 357
328 /* Set the MSR RI since we have our registers back. */ 358 /* Set the MSR RI since we have our registers back. */
329 li r5, MSR_RI 359 li r5, MSR_RI
330 mtmsrd r5, 1 360 mtmsrd r5, 1
361
362 /* Restore TOC pointer and CR */
363 REST_GPR(2, r1)
364 REST_GPR(6, r1)
365 mtcr r6
366
367 /* Restore non-volatile registers if requested to. */
368 beq cr7, 5f
369 REST_GPR(10, r1)
370 REST_NVGPRS(r1)
371
3725: addi r1, r1, SWITCH_FRAME_SIZE
331 ld r0, PPC_LR_STKOFF(r1) 373 ld r0, PPC_LR_STKOFF(r1)
332 mtlr r0 374 mtlr r0
375
3769: /* Restore MSR bits if requested */
377 beqlr cr7
378 mtmsrd r10, 0
333 blr 379 blr
334 380
335/* 381/*
@@ -337,47 +383,23 @@ _GLOBAL(__kvmppc_restore_tm)
337 * can be invoked from C function by PR KVM only. 383 * can be invoked from C function by PR KVM only.
338 */ 384 */
339_GLOBAL(_kvmppc_restore_tm_pr) 385_GLOBAL(_kvmppc_restore_tm_pr)
340 mflr r5 386 mflr r0
341 std r5, PPC_LR_STKOFF(r1) 387 std r0, PPC_LR_STKOFF(r1)
342 stdu r1, -SWITCH_FRAME_SIZE(r1) 388 stdu r1, -PPC_MIN_STKFRM(r1)
343 SAVE_NVGPRS(r1)
344
345 /* save MSR to avoid TM/math bits change */
346 mfmsr r5
347 SAVE_GPR(5, r1)
348
349 /* also save DSCR/CR/TAR so that it can be recovered later */
350 mfspr r6, SPRN_DSCR
351 SAVE_GPR(6, r1)
352
353 mfcr r7
354 stw r7, _CCR(r1)
355 389
390 /* save TAR so that it can be recovered later */
356 mfspr r8, SPRN_TAR 391 mfspr r8, SPRN_TAR
357 SAVE_GPR(8, r1) 392 std r8, PPC_MIN_STKFRM-8(r1)
358 393
394 li r5, 1
359 bl __kvmppc_restore_tm 395 bl __kvmppc_restore_tm
360 396
361 REST_GPR(8, r1) 397 ld r8, PPC_MIN_STKFRM-8(r1)
362 mtspr SPRN_TAR, r8 398 mtspr SPRN_TAR, r8
363 399
364 ld r7, _CCR(r1) 400 addi r1, r1, PPC_MIN_STKFRM
365 mtcr r7 401 ld r0, PPC_LR_STKOFF(r1)
366 402 mtlr r0
367 REST_GPR(6, r1)
368 mtspr SPRN_DSCR, r6
369
370 /* need preserve current MSR's MSR_TS bits */
371 REST_GPR(5, r1)
372 mfmsr r6
373 rldicl r6, r6, 64 - MSR_TS_S_LG, 62
374 rldimi r5, r6, MSR_TS_S_LG, 63 - MSR_TS_T_LG
375 mtmsrd r5
376
377 REST_NVGPRS(r1)
378 addi r1, r1, SWITCH_FRAME_SIZE
379 ld r5, PPC_LR_STKOFF(r1)
380 mtlr r5
381 blr 403 blr
382 404
383EXPORT_SYMBOL_GPL(_kvmppc_restore_tm_pr); 405EXPORT_SYMBOL_GPL(_kvmppc_restore_tm_pr);
diff --git a/arch/powerpc/kvm/trace_book3s.h b/arch/powerpc/kvm/trace_book3s.h
index f3b23759e017..372a82fa2de3 100644
--- a/arch/powerpc/kvm/trace_book3s.h
+++ b/arch/powerpc/kvm/trace_book3s.h
@@ -14,7 +14,6 @@
14 {0x400, "INST_STORAGE"}, \ 14 {0x400, "INST_STORAGE"}, \
15 {0x480, "INST_SEGMENT"}, \ 15 {0x480, "INST_SEGMENT"}, \
16 {0x500, "EXTERNAL"}, \ 16 {0x500, "EXTERNAL"}, \
17 {0x501, "EXTERNAL_LEVEL"}, \
18 {0x502, "EXTERNAL_HV"}, \ 17 {0x502, "EXTERNAL_HV"}, \
19 {0x600, "ALIGNMENT"}, \ 18 {0x600, "ALIGNMENT"}, \
20 {0x700, "PROGRAM"}, \ 19 {0x700, "PROGRAM"}, \
diff --git a/arch/powerpc/mm/tlb-radix.c b/arch/powerpc/mm/tlb-radix.c
index fef3e1eb3a19..4c4dfc473800 100644
--- a/arch/powerpc/mm/tlb-radix.c
+++ b/arch/powerpc/mm/tlb-radix.c
@@ -833,6 +833,15 @@ EXPORT_SYMBOL_GPL(radix__flush_pwc_lpid);
833/* 833/*
834 * Flush partition scoped translations from LPID (=LPIDR) 834 * Flush partition scoped translations from LPID (=LPIDR)
835 */ 835 */
836void radix__flush_tlb_lpid(unsigned int lpid)
837{
838 _tlbie_lpid(lpid, RIC_FLUSH_ALL);
839}
840EXPORT_SYMBOL_GPL(radix__flush_tlb_lpid);
841
842/*
843 * Flush partition scoped translations from LPID (=LPIDR)
844 */
836void radix__local_flush_tlb_lpid(unsigned int lpid) 845void radix__local_flush_tlb_lpid(unsigned int lpid)
837{ 846{
838 _tlbiel_lpid(lpid, RIC_FLUSH_ALL); 847 _tlbiel_lpid(lpid, RIC_FLUSH_ALL);
diff --git a/arch/s390/Kconfig b/arch/s390/Kconfig
index 039a3417dfc4..8b25e1f45b27 100644
--- a/arch/s390/Kconfig
+++ b/arch/s390/Kconfig
@@ -783,6 +783,17 @@ config VFIO_CCW
783 To compile this driver as a module, choose M here: the 783 To compile this driver as a module, choose M here: the
784 module will be called vfio_ccw. 784 module will be called vfio_ccw.
785 785
786config VFIO_AP
787 def_tristate n
788 prompt "VFIO support for AP devices"
789 depends on S390_AP_IOMMU && VFIO_MDEV_DEVICE && KVM
790 help
791 This driver grants access to Adjunct Processor (AP) devices
792 via the VFIO mediated device interface.
793
794 To compile this driver as a module, choose M here: the module
795 will be called vfio_ap.
796
786endmenu 797endmenu
787 798
788menu "Dump support" 799menu "Dump support"
diff --git a/arch/s390/include/asm/kvm_host.h b/arch/s390/include/asm/kvm_host.h
index 29c940bf8506..d5d24889c3bc 100644
--- a/arch/s390/include/asm/kvm_host.h
+++ b/arch/s390/include/asm/kvm_host.h
@@ -44,6 +44,7 @@
44#define KVM_REQ_ICPT_OPEREXC KVM_ARCH_REQ(2) 44#define KVM_REQ_ICPT_OPEREXC KVM_ARCH_REQ(2)
45#define KVM_REQ_START_MIGRATION KVM_ARCH_REQ(3) 45#define KVM_REQ_START_MIGRATION KVM_ARCH_REQ(3)
46#define KVM_REQ_STOP_MIGRATION KVM_ARCH_REQ(4) 46#define KVM_REQ_STOP_MIGRATION KVM_ARCH_REQ(4)
47#define KVM_REQ_VSIE_RESTART KVM_ARCH_REQ(5)
47 48
48#define SIGP_CTRL_C 0x80 49#define SIGP_CTRL_C 0x80
49#define SIGP_CTRL_SCN_MASK 0x3f 50#define SIGP_CTRL_SCN_MASK 0x3f
@@ -186,6 +187,7 @@ struct kvm_s390_sie_block {
186#define ECA_AIV 0x00200000 187#define ECA_AIV 0x00200000
187#define ECA_VX 0x00020000 188#define ECA_VX 0x00020000
188#define ECA_PROTEXCI 0x00002000 189#define ECA_PROTEXCI 0x00002000
190#define ECA_APIE 0x00000008
189#define ECA_SII 0x00000001 191#define ECA_SII 0x00000001
190 __u32 eca; /* 0x004c */ 192 __u32 eca; /* 0x004c */
191#define ICPT_INST 0x04 193#define ICPT_INST 0x04
@@ -237,7 +239,11 @@ struct kvm_s390_sie_block {
237 psw_t gpsw; /* 0x0090 */ 239 psw_t gpsw; /* 0x0090 */
238 __u64 gg14; /* 0x00a0 */ 240 __u64 gg14; /* 0x00a0 */
239 __u64 gg15; /* 0x00a8 */ 241 __u64 gg15; /* 0x00a8 */
240 __u8 reservedb0[20]; /* 0x00b0 */ 242 __u8 reservedb0[8]; /* 0x00b0 */
243#define HPID_KVM 0x4
244#define HPID_VSIE 0x5
245 __u8 hpid; /* 0x00b8 */
246 __u8 reservedb9[11]; /* 0x00b9 */
241 __u16 extcpuaddr; /* 0x00c4 */ 247 __u16 extcpuaddr; /* 0x00c4 */
242 __u16 eic; /* 0x00c6 */ 248 __u16 eic; /* 0x00c6 */
243 __u32 reservedc8; /* 0x00c8 */ 249 __u32 reservedc8; /* 0x00c8 */
@@ -255,6 +261,8 @@ struct kvm_s390_sie_block {
255 __u8 reservede4[4]; /* 0x00e4 */ 261 __u8 reservede4[4]; /* 0x00e4 */
256 __u64 tecmc; /* 0x00e8 */ 262 __u64 tecmc; /* 0x00e8 */
257 __u8 reservedf0[12]; /* 0x00f0 */ 263 __u8 reservedf0[12]; /* 0x00f0 */
264#define CRYCB_FORMAT_MASK 0x00000003
265#define CRYCB_FORMAT0 0x00000000
258#define CRYCB_FORMAT1 0x00000001 266#define CRYCB_FORMAT1 0x00000001
259#define CRYCB_FORMAT2 0x00000003 267#define CRYCB_FORMAT2 0x00000003
260 __u32 crycbd; /* 0x00fc */ 268 __u32 crycbd; /* 0x00fc */
@@ -715,6 +723,7 @@ struct kvm_s390_crypto {
715 __u32 crycbd; 723 __u32 crycbd;
716 __u8 aes_kw; 724 __u8 aes_kw;
717 __u8 dea_kw; 725 __u8 dea_kw;
726 __u8 apie;
718}; 727};
719 728
720#define APCB0_MASK_SIZE 1 729#define APCB0_MASK_SIZE 1
@@ -855,6 +864,10 @@ void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
855void kvm_arch_async_page_present(struct kvm_vcpu *vcpu, 864void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
856 struct kvm_async_pf *work); 865 struct kvm_async_pf *work);
857 866
867void kvm_arch_crypto_clear_masks(struct kvm *kvm);
868void kvm_arch_crypto_set_masks(struct kvm *kvm, unsigned long *apm,
869 unsigned long *aqm, unsigned long *adm);
870
858extern int sie64a(struct kvm_s390_sie_block *, u64 *); 871extern int sie64a(struct kvm_s390_sie_block *, u64 *);
859extern char sie_exit; 872extern char sie_exit;
860 873
diff --git a/arch/s390/include/uapi/asm/kvm.h b/arch/s390/include/uapi/asm/kvm.h
index 9a50f02b9894..16511d97e8dc 100644
--- a/arch/s390/include/uapi/asm/kvm.h
+++ b/arch/s390/include/uapi/asm/kvm.h
@@ -160,6 +160,8 @@ struct kvm_s390_vm_cpu_subfunc {
160#define KVM_S390_VM_CRYPTO_ENABLE_DEA_KW 1 160#define KVM_S390_VM_CRYPTO_ENABLE_DEA_KW 1
161#define KVM_S390_VM_CRYPTO_DISABLE_AES_KW 2 161#define KVM_S390_VM_CRYPTO_DISABLE_AES_KW 2
162#define KVM_S390_VM_CRYPTO_DISABLE_DEA_KW 3 162#define KVM_S390_VM_CRYPTO_DISABLE_DEA_KW 3
163#define KVM_S390_VM_CRYPTO_ENABLE_APIE 4
164#define KVM_S390_VM_CRYPTO_DISABLE_APIE 5
163 165
164/* kvm attributes for migration mode */ 166/* kvm attributes for migration mode */
165#define KVM_S390_VM_MIGRATION_STOP 0 167#define KVM_S390_VM_MIGRATION_STOP 0
diff --git a/arch/s390/kvm/kvm-s390.c b/arch/s390/kvm/kvm-s390.c
index ac5da6b0b862..fe24150ff666 100644
--- a/arch/s390/kvm/kvm-s390.c
+++ b/arch/s390/kvm/kvm-s390.c
@@ -40,6 +40,7 @@
40#include <asm/sclp.h> 40#include <asm/sclp.h>
41#include <asm/cpacf.h> 41#include <asm/cpacf.h>
42#include <asm/timex.h> 42#include <asm/timex.h>
43#include <asm/ap.h>
43#include "kvm-s390.h" 44#include "kvm-s390.h"
44#include "gaccess.h" 45#include "gaccess.h"
45 46
@@ -844,20 +845,24 @@ void kvm_s390_vcpu_crypto_reset_all(struct kvm *kvm)
844 845
845 kvm_s390_vcpu_block_all(kvm); 846 kvm_s390_vcpu_block_all(kvm);
846 847
847 kvm_for_each_vcpu(i, vcpu, kvm) 848 kvm_for_each_vcpu(i, vcpu, kvm) {
848 kvm_s390_vcpu_crypto_setup(vcpu); 849 kvm_s390_vcpu_crypto_setup(vcpu);
850 /* recreate the shadow crycb by leaving the VSIE handler */
851 kvm_s390_sync_request(KVM_REQ_VSIE_RESTART, vcpu);
852 }
849 853
850 kvm_s390_vcpu_unblock_all(kvm); 854 kvm_s390_vcpu_unblock_all(kvm);
851} 855}
852 856
853static int kvm_s390_vm_set_crypto(struct kvm *kvm, struct kvm_device_attr *attr) 857static int kvm_s390_vm_set_crypto(struct kvm *kvm, struct kvm_device_attr *attr)
854{ 858{
855 if (!test_kvm_facility(kvm, 76))
856 return -EINVAL;
857
858 mutex_lock(&kvm->lock); 859 mutex_lock(&kvm->lock);
859 switch (attr->attr) { 860 switch (attr->attr) {
860 case KVM_S390_VM_CRYPTO_ENABLE_AES_KW: 861 case KVM_S390_VM_CRYPTO_ENABLE_AES_KW:
862 if (!test_kvm_facility(kvm, 76)) {
863 mutex_unlock(&kvm->lock);
864 return -EINVAL;
865 }
861 get_random_bytes( 866 get_random_bytes(
862 kvm->arch.crypto.crycb->aes_wrapping_key_mask, 867 kvm->arch.crypto.crycb->aes_wrapping_key_mask,
863 sizeof(kvm->arch.crypto.crycb->aes_wrapping_key_mask)); 868 sizeof(kvm->arch.crypto.crycb->aes_wrapping_key_mask));
@@ -865,6 +870,10 @@ static int kvm_s390_vm_set_crypto(struct kvm *kvm, struct kvm_device_attr *attr)
865 VM_EVENT(kvm, 3, "%s", "ENABLE: AES keywrapping support"); 870 VM_EVENT(kvm, 3, "%s", "ENABLE: AES keywrapping support");
866 break; 871 break;
867 case KVM_S390_VM_CRYPTO_ENABLE_DEA_KW: 872 case KVM_S390_VM_CRYPTO_ENABLE_DEA_KW:
873 if (!test_kvm_facility(kvm, 76)) {
874 mutex_unlock(&kvm->lock);
875 return -EINVAL;
876 }
868 get_random_bytes( 877 get_random_bytes(
869 kvm->arch.crypto.crycb->dea_wrapping_key_mask, 878 kvm->arch.crypto.crycb->dea_wrapping_key_mask,
870 sizeof(kvm->arch.crypto.crycb->dea_wrapping_key_mask)); 879 sizeof(kvm->arch.crypto.crycb->dea_wrapping_key_mask));
@@ -872,17 +881,39 @@ static int kvm_s390_vm_set_crypto(struct kvm *kvm, struct kvm_device_attr *attr)
872 VM_EVENT(kvm, 3, "%s", "ENABLE: DEA keywrapping support"); 881 VM_EVENT(kvm, 3, "%s", "ENABLE: DEA keywrapping support");
873 break; 882 break;
874 case KVM_S390_VM_CRYPTO_DISABLE_AES_KW: 883 case KVM_S390_VM_CRYPTO_DISABLE_AES_KW:
884 if (!test_kvm_facility(kvm, 76)) {
885 mutex_unlock(&kvm->lock);
886 return -EINVAL;
887 }
875 kvm->arch.crypto.aes_kw = 0; 888 kvm->arch.crypto.aes_kw = 0;
876 memset(kvm->arch.crypto.crycb->aes_wrapping_key_mask, 0, 889 memset(kvm->arch.crypto.crycb->aes_wrapping_key_mask, 0,
877 sizeof(kvm->arch.crypto.crycb->aes_wrapping_key_mask)); 890 sizeof(kvm->arch.crypto.crycb->aes_wrapping_key_mask));
878 VM_EVENT(kvm, 3, "%s", "DISABLE: AES keywrapping support"); 891 VM_EVENT(kvm, 3, "%s", "DISABLE: AES keywrapping support");
879 break; 892 break;
880 case KVM_S390_VM_CRYPTO_DISABLE_DEA_KW: 893 case KVM_S390_VM_CRYPTO_DISABLE_DEA_KW:
894 if (!test_kvm_facility(kvm, 76)) {
895 mutex_unlock(&kvm->lock);
896 return -EINVAL;
897 }
881 kvm->arch.crypto.dea_kw = 0; 898 kvm->arch.crypto.dea_kw = 0;
882 memset(kvm->arch.crypto.crycb->dea_wrapping_key_mask, 0, 899 memset(kvm->arch.crypto.crycb->dea_wrapping_key_mask, 0,
883 sizeof(kvm->arch.crypto.crycb->dea_wrapping_key_mask)); 900 sizeof(kvm->arch.crypto.crycb->dea_wrapping_key_mask));
884 VM_EVENT(kvm, 3, "%s", "DISABLE: DEA keywrapping support"); 901 VM_EVENT(kvm, 3, "%s", "DISABLE: DEA keywrapping support");
885 break; 902 break;
903 case KVM_S390_VM_CRYPTO_ENABLE_APIE:
904 if (!ap_instructions_available()) {
905 mutex_unlock(&kvm->lock);
906 return -EOPNOTSUPP;
907 }
908 kvm->arch.crypto.apie = 1;
909 break;
910 case KVM_S390_VM_CRYPTO_DISABLE_APIE:
911 if (!ap_instructions_available()) {
912 mutex_unlock(&kvm->lock);
913 return -EOPNOTSUPP;
914 }
915 kvm->arch.crypto.apie = 0;
916 break;
886 default: 917 default:
887 mutex_unlock(&kvm->lock); 918 mutex_unlock(&kvm->lock);
888 return -ENXIO; 919 return -ENXIO;
@@ -1491,6 +1522,10 @@ static int kvm_s390_vm_has_attr(struct kvm *kvm, struct kvm_device_attr *attr)
1491 case KVM_S390_VM_CRYPTO_DISABLE_DEA_KW: 1522 case KVM_S390_VM_CRYPTO_DISABLE_DEA_KW:
1492 ret = 0; 1523 ret = 0;
1493 break; 1524 break;
1525 case KVM_S390_VM_CRYPTO_ENABLE_APIE:
1526 case KVM_S390_VM_CRYPTO_DISABLE_APIE:
1527 ret = ap_instructions_available() ? 0 : -ENXIO;
1528 break;
1494 default: 1529 default:
1495 ret = -ENXIO; 1530 ret = -ENXIO;
1496 break; 1531 break;
@@ -1992,55 +2027,101 @@ long kvm_arch_vm_ioctl(struct file *filp,
1992 return r; 2027 return r;
1993} 2028}
1994 2029
1995static int kvm_s390_query_ap_config(u8 *config)
1996{
1997 u32 fcn_code = 0x04000000UL;
1998 u32 cc = 0;
1999
2000 memset(config, 0, 128);
2001 asm volatile(
2002 "lgr 0,%1\n"
2003 "lgr 2,%2\n"
2004 ".long 0xb2af0000\n" /* PQAP(QCI) */
2005 "0: ipm %0\n"
2006 "srl %0,28\n"
2007 "1:\n"
2008 EX_TABLE(0b, 1b)
2009 : "+r" (cc)
2010 : "r" (fcn_code), "r" (config)
2011 : "cc", "0", "2", "memory"
2012 );
2013
2014 return cc;
2015}
2016
2017static int kvm_s390_apxa_installed(void) 2030static int kvm_s390_apxa_installed(void)
2018{ 2031{
2019 u8 config[128]; 2032 struct ap_config_info info;
2020 int cc;
2021 2033
2022 if (test_facility(12)) { 2034 if (ap_instructions_available()) {
2023 cc = kvm_s390_query_ap_config(config); 2035 if (ap_qci(&info) == 0)
2024 2036 return info.apxa;
2025 if (cc)
2026 pr_err("PQAP(QCI) failed with cc=%d", cc);
2027 else
2028 return config[0] & 0x40;
2029 } 2037 }
2030 2038
2031 return 0; 2039 return 0;
2032} 2040}
2033 2041
2042/*
2043 * The format of the crypto control block (CRYCB) is specified in the 3 low
2044 * order bits of the CRYCB designation (CRYCBD) field as follows:
2045 * Format 0: Neither the message security assist extension 3 (MSAX3) nor the
2046 * AP extended addressing (APXA) facility are installed.
2047 * Format 1: The APXA facility is not installed but the MSAX3 facility is.
2048 * Format 2: Both the APXA and MSAX3 facilities are installed
2049 */
2034static void kvm_s390_set_crycb_format(struct kvm *kvm) 2050static void kvm_s390_set_crycb_format(struct kvm *kvm)
2035{ 2051{
2036 kvm->arch.crypto.crycbd = (__u32)(unsigned long) kvm->arch.crypto.crycb; 2052 kvm->arch.crypto.crycbd = (__u32)(unsigned long) kvm->arch.crypto.crycb;
2037 2053
2054 /* Clear the CRYCB format bits - i.e., set format 0 by default */
2055 kvm->arch.crypto.crycbd &= ~(CRYCB_FORMAT_MASK);
2056
2057 /* Check whether MSAX3 is installed */
2058 if (!test_kvm_facility(kvm, 76))
2059 return;
2060
2038 if (kvm_s390_apxa_installed()) 2061 if (kvm_s390_apxa_installed())
2039 kvm->arch.crypto.crycbd |= CRYCB_FORMAT2; 2062 kvm->arch.crypto.crycbd |= CRYCB_FORMAT2;
2040 else 2063 else
2041 kvm->arch.crypto.crycbd |= CRYCB_FORMAT1; 2064 kvm->arch.crypto.crycbd |= CRYCB_FORMAT1;
2042} 2065}
2043 2066
2067void kvm_arch_crypto_set_masks(struct kvm *kvm, unsigned long *apm,
2068 unsigned long *aqm, unsigned long *adm)
2069{
2070 struct kvm_s390_crypto_cb *crycb = kvm->arch.crypto.crycb;
2071
2072 mutex_lock(&kvm->lock);
2073 kvm_s390_vcpu_block_all(kvm);
2074
2075 switch (kvm->arch.crypto.crycbd & CRYCB_FORMAT_MASK) {
2076 case CRYCB_FORMAT2: /* APCB1 use 256 bits */
2077 memcpy(crycb->apcb1.apm, apm, 32);
2078 VM_EVENT(kvm, 3, "SET CRYCB: apm %016lx %016lx %016lx %016lx",
2079 apm[0], apm[1], apm[2], apm[3]);
2080 memcpy(crycb->apcb1.aqm, aqm, 32);
2081 VM_EVENT(kvm, 3, "SET CRYCB: aqm %016lx %016lx %016lx %016lx",
2082 aqm[0], aqm[1], aqm[2], aqm[3]);
2083 memcpy(crycb->apcb1.adm, adm, 32);
2084 VM_EVENT(kvm, 3, "SET CRYCB: adm %016lx %016lx %016lx %016lx",
2085 adm[0], adm[1], adm[2], adm[3]);
2086 break;
2087 case CRYCB_FORMAT1:
2088 case CRYCB_FORMAT0: /* Fall through both use APCB0 */
2089 memcpy(crycb->apcb0.apm, apm, 8);
2090 memcpy(crycb->apcb0.aqm, aqm, 2);
2091 memcpy(crycb->apcb0.adm, adm, 2);
2092 VM_EVENT(kvm, 3, "SET CRYCB: apm %016lx aqm %04x adm %04x",
2093 apm[0], *((unsigned short *)aqm),
2094 *((unsigned short *)adm));
2095 break;
2096 default: /* Can not happen */
2097 break;
2098 }
2099
2100 /* recreate the shadow crycb for each vcpu */
2101 kvm_s390_sync_request_broadcast(kvm, KVM_REQ_VSIE_RESTART);
2102 kvm_s390_vcpu_unblock_all(kvm);
2103 mutex_unlock(&kvm->lock);
2104}
2105EXPORT_SYMBOL_GPL(kvm_arch_crypto_set_masks);
2106
2107void kvm_arch_crypto_clear_masks(struct kvm *kvm)
2108{
2109 mutex_lock(&kvm->lock);
2110 kvm_s390_vcpu_block_all(kvm);
2111
2112 memset(&kvm->arch.crypto.crycb->apcb0, 0,
2113 sizeof(kvm->arch.crypto.crycb->apcb0));
2114 memset(&kvm->arch.crypto.crycb->apcb1, 0,
2115 sizeof(kvm->arch.crypto.crycb->apcb1));
2116
2117 VM_EVENT(kvm, 3, "%s", "CLR CRYCB:");
2118 /* recreate the shadow crycb for each vcpu */
2119 kvm_s390_sync_request_broadcast(kvm, KVM_REQ_VSIE_RESTART);
2120 kvm_s390_vcpu_unblock_all(kvm);
2121 mutex_unlock(&kvm->lock);
2122}
2123EXPORT_SYMBOL_GPL(kvm_arch_crypto_clear_masks);
2124
2044static u64 kvm_s390_get_initial_cpuid(void) 2125static u64 kvm_s390_get_initial_cpuid(void)
2045{ 2126{
2046 struct cpuid cpuid; 2127 struct cpuid cpuid;
@@ -2052,12 +2133,12 @@ static u64 kvm_s390_get_initial_cpuid(void)
2052 2133
2053static void kvm_s390_crypto_init(struct kvm *kvm) 2134static void kvm_s390_crypto_init(struct kvm *kvm)
2054{ 2135{
2055 if (!test_kvm_facility(kvm, 76))
2056 return;
2057
2058 kvm->arch.crypto.crycb = &kvm->arch.sie_page2->crycb; 2136 kvm->arch.crypto.crycb = &kvm->arch.sie_page2->crycb;
2059 kvm_s390_set_crycb_format(kvm); 2137 kvm_s390_set_crycb_format(kvm);
2060 2138
2139 if (!test_kvm_facility(kvm, 76))
2140 return;
2141
2061 /* Enable AES/DEA protected key functions by default */ 2142 /* Enable AES/DEA protected key functions by default */
2062 kvm->arch.crypto.aes_kw = 1; 2143 kvm->arch.crypto.aes_kw = 1;
2063 kvm->arch.crypto.dea_kw = 1; 2144 kvm->arch.crypto.dea_kw = 1;
@@ -2583,17 +2664,25 @@ void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
2583 2664
2584static void kvm_s390_vcpu_crypto_setup(struct kvm_vcpu *vcpu) 2665static void kvm_s390_vcpu_crypto_setup(struct kvm_vcpu *vcpu)
2585{ 2666{
2586 if (!test_kvm_facility(vcpu->kvm, 76)) 2667 /*
2668 * If the AP instructions are not being interpreted and the MSAX3
2669 * facility is not configured for the guest, there is nothing to set up.
2670 */
2671 if (!vcpu->kvm->arch.crypto.apie && !test_kvm_facility(vcpu->kvm, 76))
2587 return; 2672 return;
2588 2673
2674 vcpu->arch.sie_block->crycbd = vcpu->kvm->arch.crypto.crycbd;
2589 vcpu->arch.sie_block->ecb3 &= ~(ECB3_AES | ECB3_DEA); 2675 vcpu->arch.sie_block->ecb3 &= ~(ECB3_AES | ECB3_DEA);
2676 vcpu->arch.sie_block->eca &= ~ECA_APIE;
2677
2678 if (vcpu->kvm->arch.crypto.apie)
2679 vcpu->arch.sie_block->eca |= ECA_APIE;
2590 2680
2681 /* Set up protected key support */
2591 if (vcpu->kvm->arch.crypto.aes_kw) 2682 if (vcpu->kvm->arch.crypto.aes_kw)
2592 vcpu->arch.sie_block->ecb3 |= ECB3_AES; 2683 vcpu->arch.sie_block->ecb3 |= ECB3_AES;
2593 if (vcpu->kvm->arch.crypto.dea_kw) 2684 if (vcpu->kvm->arch.crypto.dea_kw)
2594 vcpu->arch.sie_block->ecb3 |= ECB3_DEA; 2685 vcpu->arch.sie_block->ecb3 |= ECB3_DEA;
2595
2596 vcpu->arch.sie_block->crycbd = vcpu->kvm->arch.crypto.crycbd;
2597} 2686}
2598 2687
2599void kvm_s390_vcpu_unsetup_cmma(struct kvm_vcpu *vcpu) 2688void kvm_s390_vcpu_unsetup_cmma(struct kvm_vcpu *vcpu)
@@ -2685,6 +2774,8 @@ int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
2685 hrtimer_init(&vcpu->arch.ckc_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); 2774 hrtimer_init(&vcpu->arch.ckc_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2686 vcpu->arch.ckc_timer.function = kvm_s390_idle_wakeup; 2775 vcpu->arch.ckc_timer.function = kvm_s390_idle_wakeup;
2687 2776
2777 vcpu->arch.sie_block->hpid = HPID_KVM;
2778
2688 kvm_s390_vcpu_crypto_setup(vcpu); 2779 kvm_s390_vcpu_crypto_setup(vcpu);
2689 2780
2690 return rc; 2781 return rc;
@@ -2768,18 +2859,25 @@ static void kvm_s390_vcpu_request(struct kvm_vcpu *vcpu)
2768 exit_sie(vcpu); 2859 exit_sie(vcpu);
2769} 2860}
2770 2861
2862bool kvm_s390_vcpu_sie_inhibited(struct kvm_vcpu *vcpu)
2863{
2864 return atomic_read(&vcpu->arch.sie_block->prog20) &
2865 (PROG_BLOCK_SIE | PROG_REQUEST);
2866}
2867
2771static void kvm_s390_vcpu_request_handled(struct kvm_vcpu *vcpu) 2868static void kvm_s390_vcpu_request_handled(struct kvm_vcpu *vcpu)
2772{ 2869{
2773 atomic_andnot(PROG_REQUEST, &vcpu->arch.sie_block->prog20); 2870 atomic_andnot(PROG_REQUEST, &vcpu->arch.sie_block->prog20);
2774} 2871}
2775 2872
2776/* 2873/*
2777 * Kick a guest cpu out of SIE and wait until SIE is not running. 2874 * Kick a guest cpu out of (v)SIE and wait until (v)SIE is not running.
2778 * If the CPU is not running (e.g. waiting as idle) the function will 2875 * If the CPU is not running (e.g. waiting as idle) the function will
2779 * return immediately. */ 2876 * return immediately. */
2780void exit_sie(struct kvm_vcpu *vcpu) 2877void exit_sie(struct kvm_vcpu *vcpu)
2781{ 2878{
2782 kvm_s390_set_cpuflags(vcpu, CPUSTAT_STOP_INT); 2879 kvm_s390_set_cpuflags(vcpu, CPUSTAT_STOP_INT);
2880 kvm_s390_vsie_kick(vcpu);
2783 while (vcpu->arch.sie_block->prog0c & PROG_IN_SIE) 2881 while (vcpu->arch.sie_block->prog0c & PROG_IN_SIE)
2784 cpu_relax(); 2882 cpu_relax();
2785} 2883}
@@ -3196,6 +3294,8 @@ retry:
3196 3294
3197 /* nothing to do, just clear the request */ 3295 /* nothing to do, just clear the request */
3198 kvm_clear_request(KVM_REQ_UNHALT, vcpu); 3296 kvm_clear_request(KVM_REQ_UNHALT, vcpu);
3297 /* we left the vsie handler, nothing to do, just clear the request */
3298 kvm_clear_request(KVM_REQ_VSIE_RESTART, vcpu);
3199 3299
3200 return 0; 3300 return 0;
3201} 3301}
diff --git a/arch/s390/kvm/kvm-s390.h b/arch/s390/kvm/kvm-s390.h
index 981e3ba97461..1f6e36cdce0d 100644
--- a/arch/s390/kvm/kvm-s390.h
+++ b/arch/s390/kvm/kvm-s390.h
@@ -290,6 +290,7 @@ void kvm_s390_vcpu_start(struct kvm_vcpu *vcpu);
290void kvm_s390_vcpu_stop(struct kvm_vcpu *vcpu); 290void kvm_s390_vcpu_stop(struct kvm_vcpu *vcpu);
291void kvm_s390_vcpu_block(struct kvm_vcpu *vcpu); 291void kvm_s390_vcpu_block(struct kvm_vcpu *vcpu);
292void kvm_s390_vcpu_unblock(struct kvm_vcpu *vcpu); 292void kvm_s390_vcpu_unblock(struct kvm_vcpu *vcpu);
293bool kvm_s390_vcpu_sie_inhibited(struct kvm_vcpu *vcpu);
293void exit_sie(struct kvm_vcpu *vcpu); 294void exit_sie(struct kvm_vcpu *vcpu);
294void kvm_s390_sync_request(int req, struct kvm_vcpu *vcpu); 295void kvm_s390_sync_request(int req, struct kvm_vcpu *vcpu);
295int kvm_s390_vcpu_setup_cmma(struct kvm_vcpu *vcpu); 296int kvm_s390_vcpu_setup_cmma(struct kvm_vcpu *vcpu);
diff --git a/arch/s390/kvm/vsie.c b/arch/s390/kvm/vsie.c
index a2b28cd1e3fe..a153257bf7d9 100644
--- a/arch/s390/kvm/vsie.c
+++ b/arch/s390/kvm/vsie.c
@@ -135,14 +135,148 @@ static int prepare_cpuflags(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page)
135 atomic_set(&scb_s->cpuflags, newflags); 135 atomic_set(&scb_s->cpuflags, newflags);
136 return 0; 136 return 0;
137} 137}
138/* Copy to APCB FORMAT1 from APCB FORMAT0 */
139static int setup_apcb10(struct kvm_vcpu *vcpu, struct kvm_s390_apcb1 *apcb_s,
140 unsigned long apcb_o, struct kvm_s390_apcb1 *apcb_h)
141{
142 struct kvm_s390_apcb0 tmp;
138 143
139/* 144 if (read_guest_real(vcpu, apcb_o, &tmp, sizeof(struct kvm_s390_apcb0)))
145 return -EFAULT;
146
147 apcb_s->apm[0] = apcb_h->apm[0] & tmp.apm[0];
148 apcb_s->aqm[0] = apcb_h->aqm[0] & tmp.aqm[0] & 0xffff000000000000UL;
149 apcb_s->adm[0] = apcb_h->adm[0] & tmp.adm[0] & 0xffff000000000000UL;
150
151 return 0;
152
153}
154
155/**
156 * setup_apcb00 - Copy to APCB FORMAT0 from APCB FORMAT0
157 * @vcpu: pointer to the virtual CPU
158 * @apcb_s: pointer to start of apcb in the shadow crycb
159 * @apcb_o: pointer to start of original apcb in the guest2
160 * @apcb_h: pointer to start of apcb in the guest1
161 *
162 * Returns 0 and -EFAULT on error reading guest apcb
163 */
164static int setup_apcb00(struct kvm_vcpu *vcpu, unsigned long *apcb_s,
165 unsigned long apcb_o, unsigned long *apcb_h)
166{
167 if (read_guest_real(vcpu, apcb_o, apcb_s,
168 sizeof(struct kvm_s390_apcb0)))
169 return -EFAULT;
170
171 bitmap_and(apcb_s, apcb_s, apcb_h, sizeof(struct kvm_s390_apcb0));
172
173 return 0;
174}
175
176/**
177 * setup_apcb11 - Copy the FORMAT1 APCB from the guest to the shadow CRYCB
178 * @vcpu: pointer to the virtual CPU
179 * @apcb_s: pointer to start of apcb in the shadow crycb
180 * @apcb_o: pointer to start of original guest apcb
181 * @apcb_h: pointer to start of apcb in the host
182 *
183 * Returns 0 and -EFAULT on error reading guest apcb
184 */
185static int setup_apcb11(struct kvm_vcpu *vcpu, unsigned long *apcb_s,
186 unsigned long apcb_o,
187 unsigned long *apcb_h)
188{
189 if (read_guest_real(vcpu, apcb_o, apcb_s,
190 sizeof(struct kvm_s390_apcb1)))
191 return -EFAULT;
192
193 bitmap_and(apcb_s, apcb_s, apcb_h, sizeof(struct kvm_s390_apcb1));
194
195 return 0;
196}
197
198/**
199 * setup_apcb - Create a shadow copy of the apcb.
200 * @vcpu: pointer to the virtual CPU
201 * @crycb_s: pointer to shadow crycb
202 * @crycb_o: pointer to original guest crycb
203 * @crycb_h: pointer to the host crycb
204 * @fmt_o: format of the original guest crycb.
205 * @fmt_h: format of the host crycb.
206 *
207 * Checks the compatibility between the guest and host crycb and calls the
208 * appropriate copy function.
209 *
210 * Return 0 or an error number if the guest and host crycb are incompatible.
211 */
212static int setup_apcb(struct kvm_vcpu *vcpu, struct kvm_s390_crypto_cb *crycb_s,
213 const u32 crycb_o,
214 struct kvm_s390_crypto_cb *crycb_h,
215 int fmt_o, int fmt_h)
216{
217 struct kvm_s390_crypto_cb *crycb;
218
219 crycb = (struct kvm_s390_crypto_cb *) (unsigned long)crycb_o;
220
221 switch (fmt_o) {
222 case CRYCB_FORMAT2:
223 if ((crycb_o & PAGE_MASK) != ((crycb_o + 256) & PAGE_MASK))
224 return -EACCES;
225 if (fmt_h != CRYCB_FORMAT2)
226 return -EINVAL;
227 return setup_apcb11(vcpu, (unsigned long *)&crycb_s->apcb1,
228 (unsigned long) &crycb->apcb1,
229 (unsigned long *)&crycb_h->apcb1);
230 case CRYCB_FORMAT1:
231 switch (fmt_h) {
232 case CRYCB_FORMAT2:
233 return setup_apcb10(vcpu, &crycb_s->apcb1,
234 (unsigned long) &crycb->apcb0,
235 &crycb_h->apcb1);
236 case CRYCB_FORMAT1:
237 return setup_apcb00(vcpu,
238 (unsigned long *) &crycb_s->apcb0,
239 (unsigned long) &crycb->apcb0,
240 (unsigned long *) &crycb_h->apcb0);
241 }
242 break;
243 case CRYCB_FORMAT0:
244 if ((crycb_o & PAGE_MASK) != ((crycb_o + 32) & PAGE_MASK))
245 return -EACCES;
246
247 switch (fmt_h) {
248 case CRYCB_FORMAT2:
249 return setup_apcb10(vcpu, &crycb_s->apcb1,
250 (unsigned long) &crycb->apcb0,
251 &crycb_h->apcb1);
252 case CRYCB_FORMAT1:
253 case CRYCB_FORMAT0:
254 return setup_apcb00(vcpu,
255 (unsigned long *) &crycb_s->apcb0,
256 (unsigned long) &crycb->apcb0,
257 (unsigned long *) &crycb_h->apcb0);
258 }
259 }
260 return -EINVAL;
261}
262
263/**
264 * shadow_crycb - Create a shadow copy of the crycb block
265 * @vcpu: a pointer to the virtual CPU
266 * @vsie_page: a pointer to internal date used for the vSIE
267 *
140 * Create a shadow copy of the crycb block and setup key wrapping, if 268 * Create a shadow copy of the crycb block and setup key wrapping, if
141 * requested for guest 3 and enabled for guest 2. 269 * requested for guest 3 and enabled for guest 2.
142 * 270 *
143 * We only accept format-1 (no AP in g2), but convert it into format-2 271 * We accept format-1 or format-2, but we convert format-1 into format-2
272 * in the shadow CRYCB.
273 * Using format-2 enables the firmware to choose the right format when
274 * scheduling the SIE.
144 * There is nothing to do for format-0. 275 * There is nothing to do for format-0.
145 * 276 *
277 * This function centralize the issuing of set_validity_icpt() for all
278 * the subfunctions working on the crycb.
279 *
146 * Returns: - 0 if shadowed or nothing to do 280 * Returns: - 0 if shadowed or nothing to do
147 * - > 0 if control has to be given to guest 2 281 * - > 0 if control has to be given to guest 2
148 */ 282 */
@@ -154,23 +288,40 @@ static int shadow_crycb(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page)
154 const u32 crycb_addr = crycbd_o & 0x7ffffff8U; 288 const u32 crycb_addr = crycbd_o & 0x7ffffff8U;
155 unsigned long *b1, *b2; 289 unsigned long *b1, *b2;
156 u8 ecb3_flags; 290 u8 ecb3_flags;
291 int apie_h;
292 int key_msk = test_kvm_facility(vcpu->kvm, 76);
293 int fmt_o = crycbd_o & CRYCB_FORMAT_MASK;
294 int fmt_h = vcpu->arch.sie_block->crycbd & CRYCB_FORMAT_MASK;
295 int ret = 0;
157 296
158 scb_s->crycbd = 0; 297 scb_s->crycbd = 0;
159 if (!(crycbd_o & vcpu->arch.sie_block->crycbd & CRYCB_FORMAT1)) 298
160 return 0; 299 apie_h = vcpu->arch.sie_block->eca & ECA_APIE;
161 /* format-1 is supported with message-security-assist extension 3 */ 300 if (!apie_h && !key_msk)
162 if (!test_kvm_facility(vcpu->kvm, 76))
163 return 0; 301 return 0;
302
303 if (!crycb_addr)
304 return set_validity_icpt(scb_s, 0x0039U);
305
306 if (fmt_o == CRYCB_FORMAT1)
307 if ((crycb_addr & PAGE_MASK) !=
308 ((crycb_addr + 128) & PAGE_MASK))
309 return set_validity_icpt(scb_s, 0x003CU);
310
311 if (apie_h && (scb_o->eca & ECA_APIE)) {
312 ret = setup_apcb(vcpu, &vsie_page->crycb, crycb_addr,
313 vcpu->kvm->arch.crypto.crycb,
314 fmt_o, fmt_h);
315 if (ret)
316 goto end;
317 scb_s->eca |= scb_o->eca & ECA_APIE;
318 }
319
164 /* we may only allow it if enabled for guest 2 */ 320 /* we may only allow it if enabled for guest 2 */
165 ecb3_flags = scb_o->ecb3 & vcpu->arch.sie_block->ecb3 & 321 ecb3_flags = scb_o->ecb3 & vcpu->arch.sie_block->ecb3 &
166 (ECB3_AES | ECB3_DEA); 322 (ECB3_AES | ECB3_DEA);
167 if (!ecb3_flags) 323 if (!ecb3_flags)
168 return 0; 324 goto end;
169
170 if ((crycb_addr & PAGE_MASK) != ((crycb_addr + 128) & PAGE_MASK))
171 return set_validity_icpt(scb_s, 0x003CU);
172 else if (!crycb_addr)
173 return set_validity_icpt(scb_s, 0x0039U);
174 325
175 /* copy only the wrapping keys */ 326 /* copy only the wrapping keys */
176 if (read_guest_real(vcpu, crycb_addr + 72, 327 if (read_guest_real(vcpu, crycb_addr + 72,
@@ -178,8 +329,6 @@ static int shadow_crycb(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page)
178 return set_validity_icpt(scb_s, 0x0035U); 329 return set_validity_icpt(scb_s, 0x0035U);
179 330
180 scb_s->ecb3 |= ecb3_flags; 331 scb_s->ecb3 |= ecb3_flags;
181 scb_s->crycbd = ((__u32)(__u64) &vsie_page->crycb) | CRYCB_FORMAT1 |
182 CRYCB_FORMAT2;
183 332
184 /* xor both blocks in one run */ 333 /* xor both blocks in one run */
185 b1 = (unsigned long *) vsie_page->crycb.dea_wrapping_key_mask; 334 b1 = (unsigned long *) vsie_page->crycb.dea_wrapping_key_mask;
@@ -187,6 +336,16 @@ static int shadow_crycb(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page)
187 vcpu->kvm->arch.crypto.crycb->dea_wrapping_key_mask; 336 vcpu->kvm->arch.crypto.crycb->dea_wrapping_key_mask;
188 /* as 56%8 == 0, bitmap_xor won't overwrite any data */ 337 /* as 56%8 == 0, bitmap_xor won't overwrite any data */
189 bitmap_xor(b1, b1, b2, BITS_PER_BYTE * 56); 338 bitmap_xor(b1, b1, b2, BITS_PER_BYTE * 56);
339end:
340 switch (ret) {
341 case -EINVAL:
342 return set_validity_icpt(scb_s, 0x0020U);
343 case -EFAULT:
344 return set_validity_icpt(scb_s, 0x0035U);
345 case -EACCES:
346 return set_validity_icpt(scb_s, 0x003CU);
347 }
348 scb_s->crycbd = ((__u32)(__u64) &vsie_page->crycb) | CRYCB_FORMAT2;
190 return 0; 349 return 0;
191} 350}
192 351
@@ -383,6 +542,8 @@ static int shadow_scb(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page)
383 if (test_kvm_facility(vcpu->kvm, 156)) 542 if (test_kvm_facility(vcpu->kvm, 156))
384 scb_s->ecd |= scb_o->ecd & ECD_ETOKENF; 543 scb_s->ecd |= scb_o->ecd & ECD_ETOKENF;
385 544
545 scb_s->hpid = HPID_VSIE;
546
386 prepare_ibc(vcpu, vsie_page); 547 prepare_ibc(vcpu, vsie_page);
387 rc = shadow_crycb(vcpu, vsie_page); 548 rc = shadow_crycb(vcpu, vsie_page);
388out: 549out:
@@ -830,7 +991,7 @@ static int do_vsie_run(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page)
830 struct kvm_s390_sie_block *scb_s = &vsie_page->scb_s; 991 struct kvm_s390_sie_block *scb_s = &vsie_page->scb_s;
831 struct kvm_s390_sie_block *scb_o = vsie_page->scb_o; 992 struct kvm_s390_sie_block *scb_o = vsie_page->scb_o;
832 int guest_bp_isolation; 993 int guest_bp_isolation;
833 int rc; 994 int rc = 0;
834 995
835 handle_last_fault(vcpu, vsie_page); 996 handle_last_fault(vcpu, vsie_page);
836 997
@@ -858,7 +1019,18 @@ static int do_vsie_run(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page)
858 guest_enter_irqoff(); 1019 guest_enter_irqoff();
859 local_irq_enable(); 1020 local_irq_enable();
860 1021
861 rc = sie64a(scb_s, vcpu->run->s.regs.gprs); 1022 /*
1023 * Simulate a SIE entry of the VCPU (see sie64a), so VCPU blocking
1024 * and VCPU requests also hinder the vSIE from running and lead
1025 * to an immediate exit. kvm_s390_vsie_kick() has to be used to
1026 * also kick the vSIE.
1027 */
1028 vcpu->arch.sie_block->prog0c |= PROG_IN_SIE;
1029 barrier();
1030 if (!kvm_s390_vcpu_sie_inhibited(vcpu))
1031 rc = sie64a(scb_s, vcpu->run->s.regs.gprs);
1032 barrier();
1033 vcpu->arch.sie_block->prog0c &= ~PROG_IN_SIE;
862 1034
863 local_irq_disable(); 1035 local_irq_disable();
864 guest_exit_irqoff(); 1036 guest_exit_irqoff();
@@ -1005,7 +1177,8 @@ static int vsie_run(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page)
1005 if (rc == -EAGAIN) 1177 if (rc == -EAGAIN)
1006 rc = 0; 1178 rc = 0;
1007 if (rc || scb_s->icptcode || signal_pending(current) || 1179 if (rc || scb_s->icptcode || signal_pending(current) ||
1008 kvm_s390_vcpu_has_irq(vcpu, 0)) 1180 kvm_s390_vcpu_has_irq(vcpu, 0) ||
1181 kvm_s390_vcpu_sie_inhibited(vcpu))
1009 break; 1182 break;
1010 } 1183 }
1011 1184
@@ -1122,7 +1295,8 @@ int kvm_s390_handle_vsie(struct kvm_vcpu *vcpu)
1122 if (unlikely(scb_addr & 0x1ffUL)) 1295 if (unlikely(scb_addr & 0x1ffUL))
1123 return kvm_s390_inject_program_int(vcpu, PGM_SPECIFICATION); 1296 return kvm_s390_inject_program_int(vcpu, PGM_SPECIFICATION);
1124 1297
1125 if (signal_pending(current) || kvm_s390_vcpu_has_irq(vcpu, 0)) 1298 if (signal_pending(current) || kvm_s390_vcpu_has_irq(vcpu, 0) ||
1299 kvm_s390_vcpu_sie_inhibited(vcpu))
1126 return 0; 1300 return 0;
1127 1301
1128 vsie_page = get_vsie_page(vcpu->kvm, scb_addr); 1302 vsie_page = get_vsie_page(vcpu->kvm, scb_addr);
diff --git a/arch/s390/mm/gmap.c b/arch/s390/mm/gmap.c
index 911c7ded35f1..1e668b95e0c6 100644
--- a/arch/s390/mm/gmap.c
+++ b/arch/s390/mm/gmap.c
@@ -907,10 +907,16 @@ static inline pmd_t *gmap_pmd_op_walk(struct gmap *gmap, unsigned long gaddr)
907 pmd_t *pmdp; 907 pmd_t *pmdp;
908 908
909 BUG_ON(gmap_is_shadow(gmap)); 909 BUG_ON(gmap_is_shadow(gmap));
910 spin_lock(&gmap->guest_table_lock);
911 pmdp = (pmd_t *) gmap_table_walk(gmap, gaddr, 1); 910 pmdp = (pmd_t *) gmap_table_walk(gmap, gaddr, 1);
911 if (!pmdp)
912 return NULL;
912 913
913 if (!pmdp || pmd_none(*pmdp)) { 914 /* without huge pages, there is no need to take the table lock */
915 if (!gmap->mm->context.allow_gmap_hpage_1m)
916 return pmd_none(*pmdp) ? NULL : pmdp;
917
918 spin_lock(&gmap->guest_table_lock);
919 if (pmd_none(*pmdp)) {
914 spin_unlock(&gmap->guest_table_lock); 920 spin_unlock(&gmap->guest_table_lock);
915 return NULL; 921 return NULL;
916 } 922 }
diff --git a/arch/s390/tools/gen_facilities.c b/arch/s390/tools/gen_facilities.c
index 0c85aedcf9b3..fd788e0f2e5b 100644
--- a/arch/s390/tools/gen_facilities.c
+++ b/arch/s390/tools/gen_facilities.c
@@ -106,6 +106,8 @@ static struct facility_def facility_defs[] = {
106 106
107 .name = "FACILITIES_KVM_CPUMODEL", 107 .name = "FACILITIES_KVM_CPUMODEL",
108 .bits = (int[]){ 108 .bits = (int[]){
109 12, /* AP Query Configuration Information */
110 15, /* AP Facilities Test */
109 156, /* etoken facility */ 111 156, /* etoken facility */
110 -1 /* END */ 112 -1 /* END */
111 } 113 }
diff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_host.h
index 09b2e3e2cf1b..55e51ff7e421 100644
--- a/arch/x86/include/asm/kvm_host.h
+++ b/arch/x86/include/asm/kvm_host.h
@@ -102,7 +102,15 @@
102#define UNMAPPED_GVA (~(gpa_t)0) 102#define UNMAPPED_GVA (~(gpa_t)0)
103 103
104/* KVM Hugepage definitions for x86 */ 104/* KVM Hugepage definitions for x86 */
105#define KVM_NR_PAGE_SIZES 3 105enum {
106 PT_PAGE_TABLE_LEVEL = 1,
107 PT_DIRECTORY_LEVEL = 2,
108 PT_PDPE_LEVEL = 3,
109 /* set max level to the biggest one */
110 PT_MAX_HUGEPAGE_LEVEL = PT_PDPE_LEVEL,
111};
112#define KVM_NR_PAGE_SIZES (PT_MAX_HUGEPAGE_LEVEL - \
113 PT_PAGE_TABLE_LEVEL + 1)
106#define KVM_HPAGE_GFN_SHIFT(x) (((x) - 1) * 9) 114#define KVM_HPAGE_GFN_SHIFT(x) (((x) - 1) * 9)
107#define KVM_HPAGE_SHIFT(x) (PAGE_SHIFT + KVM_HPAGE_GFN_SHIFT(x)) 115#define KVM_HPAGE_SHIFT(x) (PAGE_SHIFT + KVM_HPAGE_GFN_SHIFT(x))
108#define KVM_HPAGE_SIZE(x) (1UL << KVM_HPAGE_SHIFT(x)) 116#define KVM_HPAGE_SIZE(x) (1UL << KVM_HPAGE_SHIFT(x))
@@ -177,6 +185,7 @@ enum {
177 185
178#define DR6_BD (1 << 13) 186#define DR6_BD (1 << 13)
179#define DR6_BS (1 << 14) 187#define DR6_BS (1 << 14)
188#define DR6_BT (1 << 15)
180#define DR6_RTM (1 << 16) 189#define DR6_RTM (1 << 16)
181#define DR6_FIXED_1 0xfffe0ff0 190#define DR6_FIXED_1 0xfffe0ff0
182#define DR6_INIT 0xffff0ff0 191#define DR6_INIT 0xffff0ff0
@@ -247,7 +256,7 @@ struct kvm_mmu_memory_cache {
247 * @nxe, @cr0_wp, @smep_andnot_wp and @smap_andnot_wp. 256 * @nxe, @cr0_wp, @smep_andnot_wp and @smap_andnot_wp.
248 */ 257 */
249union kvm_mmu_page_role { 258union kvm_mmu_page_role {
250 unsigned word; 259 u32 word;
251 struct { 260 struct {
252 unsigned level:4; 261 unsigned level:4;
253 unsigned cr4_pae:1; 262 unsigned cr4_pae:1;
@@ -273,6 +282,34 @@ union kvm_mmu_page_role {
273 }; 282 };
274}; 283};
275 284
285union kvm_mmu_extended_role {
286/*
287 * This structure complements kvm_mmu_page_role caching everything needed for
288 * MMU configuration. If nothing in both these structures changed, MMU
289 * re-configuration can be skipped. @valid bit is set on first usage so we don't
290 * treat all-zero structure as valid data.
291 */
292 u32 word;
293 struct {
294 unsigned int valid:1;
295 unsigned int execonly:1;
296 unsigned int cr0_pg:1;
297 unsigned int cr4_pse:1;
298 unsigned int cr4_pke:1;
299 unsigned int cr4_smap:1;
300 unsigned int cr4_smep:1;
301 unsigned int cr4_la57:1;
302 };
303};
304
305union kvm_mmu_role {
306 u64 as_u64;
307 struct {
308 union kvm_mmu_page_role base;
309 union kvm_mmu_extended_role ext;
310 };
311};
312
276struct kvm_rmap_head { 313struct kvm_rmap_head {
277 unsigned long val; 314 unsigned long val;
278}; 315};
@@ -280,18 +317,18 @@ struct kvm_rmap_head {
280struct kvm_mmu_page { 317struct kvm_mmu_page {
281 struct list_head link; 318 struct list_head link;
282 struct hlist_node hash_link; 319 struct hlist_node hash_link;
320 bool unsync;
283 321
284 /* 322 /*
285 * The following two entries are used to key the shadow page in the 323 * The following two entries are used to key the shadow page in the
286 * hash table. 324 * hash table.
287 */ 325 */
288 gfn_t gfn;
289 union kvm_mmu_page_role role; 326 union kvm_mmu_page_role role;
327 gfn_t gfn;
290 328
291 u64 *spt; 329 u64 *spt;
292 /* hold the gfn of each spte inside spt */ 330 /* hold the gfn of each spte inside spt */
293 gfn_t *gfns; 331 gfn_t *gfns;
294 bool unsync;
295 int root_count; /* Currently serving as active root */ 332 int root_count; /* Currently serving as active root */
296 unsigned int unsync_children; 333 unsigned int unsync_children;
297 struct kvm_rmap_head parent_ptes; /* rmap pointers to parent sptes */ 334 struct kvm_rmap_head parent_ptes; /* rmap pointers to parent sptes */
@@ -360,7 +397,7 @@ struct kvm_mmu {
360 void (*update_pte)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, 397 void (*update_pte)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
361 u64 *spte, const void *pte); 398 u64 *spte, const void *pte);
362 hpa_t root_hpa; 399 hpa_t root_hpa;
363 union kvm_mmu_page_role base_role; 400 union kvm_mmu_role mmu_role;
364 u8 root_level; 401 u8 root_level;
365 u8 shadow_root_level; 402 u8 shadow_root_level;
366 u8 ept_ad; 403 u8 ept_ad;
@@ -490,7 +527,7 @@ struct kvm_vcpu_hv {
490 struct kvm_hyperv_exit exit; 527 struct kvm_hyperv_exit exit;
491 struct kvm_vcpu_hv_stimer stimer[HV_SYNIC_STIMER_COUNT]; 528 struct kvm_vcpu_hv_stimer stimer[HV_SYNIC_STIMER_COUNT];
492 DECLARE_BITMAP(stimer_pending_bitmap, HV_SYNIC_STIMER_COUNT); 529 DECLARE_BITMAP(stimer_pending_bitmap, HV_SYNIC_STIMER_COUNT);
493 cpumask_t tlb_lush; 530 cpumask_t tlb_flush;
494}; 531};
495 532
496struct kvm_vcpu_arch { 533struct kvm_vcpu_arch {
@@ -534,7 +571,13 @@ struct kvm_vcpu_arch {
534 * the paging mode of the l1 guest. This context is always used to 571 * the paging mode of the l1 guest. This context is always used to
535 * handle faults. 572 * handle faults.
536 */ 573 */
537 struct kvm_mmu mmu; 574 struct kvm_mmu *mmu;
575
576 /* Non-nested MMU for L1 */
577 struct kvm_mmu root_mmu;
578
579 /* L1 MMU when running nested */
580 struct kvm_mmu guest_mmu;
538 581
539 /* 582 /*
540 * Paging state of an L2 guest (used for nested npt) 583 * Paging state of an L2 guest (used for nested npt)
@@ -585,6 +628,8 @@ struct kvm_vcpu_arch {
585 bool has_error_code; 628 bool has_error_code;
586 u8 nr; 629 u8 nr;
587 u32 error_code; 630 u32 error_code;
631 unsigned long payload;
632 bool has_payload;
588 u8 nested_apf; 633 u8 nested_apf;
589 } exception; 634 } exception;
590 635
@@ -781,6 +826,9 @@ struct kvm_hv {
781 u64 hv_reenlightenment_control; 826 u64 hv_reenlightenment_control;
782 u64 hv_tsc_emulation_control; 827 u64 hv_tsc_emulation_control;
783 u64 hv_tsc_emulation_status; 828 u64 hv_tsc_emulation_status;
829
830 /* How many vCPUs have VP index != vCPU index */
831 atomic_t num_mismatched_vp_indexes;
784}; 832};
785 833
786enum kvm_irqchip_mode { 834enum kvm_irqchip_mode {
@@ -871,6 +919,7 @@ struct kvm_arch {
871 bool x2apic_broadcast_quirk_disabled; 919 bool x2apic_broadcast_quirk_disabled;
872 920
873 bool guest_can_read_msr_platform_info; 921 bool guest_can_read_msr_platform_info;
922 bool exception_payload_enabled;
874}; 923};
875 924
876struct kvm_vm_stat { 925struct kvm_vm_stat {
@@ -1133,6 +1182,9 @@ struct kvm_x86_ops {
1133 int (*mem_enc_unreg_region)(struct kvm *kvm, struct kvm_enc_region *argp); 1182 int (*mem_enc_unreg_region)(struct kvm *kvm, struct kvm_enc_region *argp);
1134 1183
1135 int (*get_msr_feature)(struct kvm_msr_entry *entry); 1184 int (*get_msr_feature)(struct kvm_msr_entry *entry);
1185
1186 int (*nested_enable_evmcs)(struct kvm_vcpu *vcpu,
1187 uint16_t *vmcs_version);
1136}; 1188};
1137 1189
1138struct kvm_arch_async_pf { 1190struct kvm_arch_async_pf {
@@ -1170,7 +1222,6 @@ void kvm_mmu_module_exit(void);
1170 1222
1171void kvm_mmu_destroy(struct kvm_vcpu *vcpu); 1223void kvm_mmu_destroy(struct kvm_vcpu *vcpu);
1172int kvm_mmu_create(struct kvm_vcpu *vcpu); 1224int kvm_mmu_create(struct kvm_vcpu *vcpu);
1173void kvm_mmu_setup(struct kvm_vcpu *vcpu);
1174void kvm_mmu_init_vm(struct kvm *kvm); 1225void kvm_mmu_init_vm(struct kvm *kvm);
1175void kvm_mmu_uninit_vm(struct kvm *kvm); 1226void kvm_mmu_uninit_vm(struct kvm *kvm);
1176void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask, 1227void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
@@ -1324,7 +1375,8 @@ void __kvm_mmu_free_some_pages(struct kvm_vcpu *vcpu);
1324int kvm_mmu_load(struct kvm_vcpu *vcpu); 1375int kvm_mmu_load(struct kvm_vcpu *vcpu);
1325void kvm_mmu_unload(struct kvm_vcpu *vcpu); 1376void kvm_mmu_unload(struct kvm_vcpu *vcpu);
1326void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu); 1377void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu);
1327void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, ulong roots_to_free); 1378void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
1379 ulong roots_to_free);
1328gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access, 1380gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
1329 struct x86_exception *exception); 1381 struct x86_exception *exception);
1330gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva, 1382gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
diff --git a/arch/x86/include/asm/virtext.h b/arch/x86/include/asm/virtext.h
index e05e0d309244..1fc7a0d1e877 100644
--- a/arch/x86/include/asm/virtext.h
+++ b/arch/x86/include/asm/virtext.h
@@ -40,7 +40,7 @@ static inline int cpu_has_vmx(void)
40 */ 40 */
41static inline void cpu_vmxoff(void) 41static inline void cpu_vmxoff(void)
42{ 42{
43 asm volatile (ASM_VMX_VMXOFF : : : "cc"); 43 asm volatile ("vmxoff");
44 cr4_clear_bits(X86_CR4_VMXE); 44 cr4_clear_bits(X86_CR4_VMXE);
45} 45}
46 46
diff --git a/arch/x86/include/asm/vmx.h b/arch/x86/include/asm/vmx.h
index 9527ba5d62da..ade0f153947d 100644
--- a/arch/x86/include/asm/vmx.h
+++ b/arch/x86/include/asm/vmx.h
@@ -503,19 +503,6 @@ enum vmcs_field {
503 503
504#define VMX_EPT_IDENTITY_PAGETABLE_ADDR 0xfffbc000ul 504#define VMX_EPT_IDENTITY_PAGETABLE_ADDR 0xfffbc000ul
505 505
506
507#define ASM_VMX_VMCLEAR_RAX ".byte 0x66, 0x0f, 0xc7, 0x30"
508#define ASM_VMX_VMLAUNCH ".byte 0x0f, 0x01, 0xc2"
509#define ASM_VMX_VMRESUME ".byte 0x0f, 0x01, 0xc3"
510#define ASM_VMX_VMPTRLD_RAX ".byte 0x0f, 0xc7, 0x30"
511#define ASM_VMX_VMREAD_RDX_RAX ".byte 0x0f, 0x78, 0xd0"
512#define ASM_VMX_VMWRITE_RAX_RDX ".byte 0x0f, 0x79, 0xd0"
513#define ASM_VMX_VMWRITE_RSP_RDX ".byte 0x0f, 0x79, 0xd4"
514#define ASM_VMX_VMXOFF ".byte 0x0f, 0x01, 0xc4"
515#define ASM_VMX_VMXON_RAX ".byte 0xf3, 0x0f, 0xc7, 0x30"
516#define ASM_VMX_INVEPT ".byte 0x66, 0x0f, 0x38, 0x80, 0x08"
517#define ASM_VMX_INVVPID ".byte 0x66, 0x0f, 0x38, 0x81, 0x08"
518
519struct vmx_msr_entry { 506struct vmx_msr_entry {
520 u32 index; 507 u32 index;
521 u32 reserved; 508 u32 reserved;
diff --git a/arch/x86/include/uapi/asm/kvm.h b/arch/x86/include/uapi/asm/kvm.h
index fd23d5778ea1..dabfcf7c3941 100644
--- a/arch/x86/include/uapi/asm/kvm.h
+++ b/arch/x86/include/uapi/asm/kvm.h
@@ -288,6 +288,7 @@ struct kvm_reinject_control {
288#define KVM_VCPUEVENT_VALID_SIPI_VECTOR 0x00000002 288#define KVM_VCPUEVENT_VALID_SIPI_VECTOR 0x00000002
289#define KVM_VCPUEVENT_VALID_SHADOW 0x00000004 289#define KVM_VCPUEVENT_VALID_SHADOW 0x00000004
290#define KVM_VCPUEVENT_VALID_SMM 0x00000008 290#define KVM_VCPUEVENT_VALID_SMM 0x00000008
291#define KVM_VCPUEVENT_VALID_PAYLOAD 0x00000010
291 292
292/* Interrupt shadow states */ 293/* Interrupt shadow states */
293#define KVM_X86_SHADOW_INT_MOV_SS 0x01 294#define KVM_X86_SHADOW_INT_MOV_SS 0x01
@@ -299,7 +300,7 @@ struct kvm_vcpu_events {
299 __u8 injected; 300 __u8 injected;
300 __u8 nr; 301 __u8 nr;
301 __u8 has_error_code; 302 __u8 has_error_code;
302 __u8 pad; 303 __u8 pending;
303 __u32 error_code; 304 __u32 error_code;
304 } exception; 305 } exception;
305 struct { 306 struct {
@@ -322,7 +323,9 @@ struct kvm_vcpu_events {
322 __u8 smm_inside_nmi; 323 __u8 smm_inside_nmi;
323 __u8 latched_init; 324 __u8 latched_init;
324 } smi; 325 } smi;
325 __u32 reserved[9]; 326 __u8 reserved[27];
327 __u8 exception_has_payload;
328 __u64 exception_payload;
326}; 329};
327 330
328/* for KVM_GET/SET_DEBUGREGS */ 331/* for KVM_GET/SET_DEBUGREGS */
@@ -381,6 +384,7 @@ struct kvm_sync_regs {
381 384
382#define KVM_STATE_NESTED_GUEST_MODE 0x00000001 385#define KVM_STATE_NESTED_GUEST_MODE 0x00000001
383#define KVM_STATE_NESTED_RUN_PENDING 0x00000002 386#define KVM_STATE_NESTED_RUN_PENDING 0x00000002
387#define KVM_STATE_NESTED_EVMCS 0x00000004
384 388
385#define KVM_STATE_NESTED_SMM_GUEST_MODE 0x00000001 389#define KVM_STATE_NESTED_SMM_GUEST_MODE 0x00000001
386#define KVM_STATE_NESTED_SMM_VMXON 0x00000002 390#define KVM_STATE_NESTED_SMM_VMXON 0x00000002
diff --git a/arch/x86/kvm/hyperv.c b/arch/x86/kvm/hyperv.c
index 01d209ab5481..4e80080f277a 100644
--- a/arch/x86/kvm/hyperv.c
+++ b/arch/x86/kvm/hyperv.c
@@ -36,6 +36,8 @@
36 36
37#include "trace.h" 37#include "trace.h"
38 38
39#define KVM_HV_MAX_SPARSE_VCPU_SET_BITS DIV_ROUND_UP(KVM_MAX_VCPUS, 64)
40
39static inline u64 synic_read_sint(struct kvm_vcpu_hv_synic *synic, int sint) 41static inline u64 synic_read_sint(struct kvm_vcpu_hv_synic *synic, int sint)
40{ 42{
41 return atomic64_read(&synic->sint[sint]); 43 return atomic64_read(&synic->sint[sint]);
@@ -132,8 +134,10 @@ static struct kvm_vcpu *get_vcpu_by_vpidx(struct kvm *kvm, u32 vpidx)
132 struct kvm_vcpu *vcpu = NULL; 134 struct kvm_vcpu *vcpu = NULL;
133 int i; 135 int i;
134 136
135 if (vpidx < KVM_MAX_VCPUS) 137 if (vpidx >= KVM_MAX_VCPUS)
136 vcpu = kvm_get_vcpu(kvm, vpidx); 138 return NULL;
139
140 vcpu = kvm_get_vcpu(kvm, vpidx);
137 if (vcpu && vcpu_to_hv_vcpu(vcpu)->vp_index == vpidx) 141 if (vcpu && vcpu_to_hv_vcpu(vcpu)->vp_index == vpidx)
138 return vcpu; 142 return vcpu;
139 kvm_for_each_vcpu(i, vcpu, kvm) 143 kvm_for_each_vcpu(i, vcpu, kvm)
@@ -689,6 +693,24 @@ void kvm_hv_vcpu_uninit(struct kvm_vcpu *vcpu)
689 stimer_cleanup(&hv_vcpu->stimer[i]); 693 stimer_cleanup(&hv_vcpu->stimer[i]);
690} 694}
691 695
696bool kvm_hv_assist_page_enabled(struct kvm_vcpu *vcpu)
697{
698 if (!(vcpu->arch.hyperv.hv_vapic & HV_X64_MSR_VP_ASSIST_PAGE_ENABLE))
699 return false;
700 return vcpu->arch.pv_eoi.msr_val & KVM_MSR_ENABLED;
701}
702EXPORT_SYMBOL_GPL(kvm_hv_assist_page_enabled);
703
704bool kvm_hv_get_assist_page(struct kvm_vcpu *vcpu,
705 struct hv_vp_assist_page *assist_page)
706{
707 if (!kvm_hv_assist_page_enabled(vcpu))
708 return false;
709 return !kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data,
710 assist_page, sizeof(*assist_page));
711}
712EXPORT_SYMBOL_GPL(kvm_hv_get_assist_page);
713
692static void stimer_prepare_msg(struct kvm_vcpu_hv_stimer *stimer) 714static void stimer_prepare_msg(struct kvm_vcpu_hv_stimer *stimer)
693{ 715{
694 struct hv_message *msg = &stimer->msg; 716 struct hv_message *msg = &stimer->msg;
@@ -1040,21 +1062,41 @@ static u64 current_task_runtime_100ns(void)
1040 1062
1041static int kvm_hv_set_msr(struct kvm_vcpu *vcpu, u32 msr, u64 data, bool host) 1063static int kvm_hv_set_msr(struct kvm_vcpu *vcpu, u32 msr, u64 data, bool host)
1042{ 1064{
1043 struct kvm_vcpu_hv *hv = &vcpu->arch.hyperv; 1065 struct kvm_vcpu_hv *hv_vcpu = &vcpu->arch.hyperv;
1044 1066
1045 switch (msr) { 1067 switch (msr) {
1046 case HV_X64_MSR_VP_INDEX: 1068 case HV_X64_MSR_VP_INDEX: {
1047 if (!host) 1069 struct kvm_hv *hv = &vcpu->kvm->arch.hyperv;
1070 int vcpu_idx = kvm_vcpu_get_idx(vcpu);
1071 u32 new_vp_index = (u32)data;
1072
1073 if (!host || new_vp_index >= KVM_MAX_VCPUS)
1048 return 1; 1074 return 1;
1049 hv->vp_index = (u32)data; 1075
1076 if (new_vp_index == hv_vcpu->vp_index)
1077 return 0;
1078
1079 /*
1080 * The VP index is initialized to vcpu_index by
1081 * kvm_hv_vcpu_postcreate so they initially match. Now the
1082 * VP index is changing, adjust num_mismatched_vp_indexes if
1083 * it now matches or no longer matches vcpu_idx.
1084 */
1085 if (hv_vcpu->vp_index == vcpu_idx)
1086 atomic_inc(&hv->num_mismatched_vp_indexes);
1087 else if (new_vp_index == vcpu_idx)
1088 atomic_dec(&hv->num_mismatched_vp_indexes);
1089
1090 hv_vcpu->vp_index = new_vp_index;
1050 break; 1091 break;
1092 }
1051 case HV_X64_MSR_VP_ASSIST_PAGE: { 1093 case HV_X64_MSR_VP_ASSIST_PAGE: {
1052 u64 gfn; 1094 u64 gfn;
1053 unsigned long addr; 1095 unsigned long addr;
1054 1096
1055 if (!(data & HV_X64_MSR_VP_ASSIST_PAGE_ENABLE)) { 1097 if (!(data & HV_X64_MSR_VP_ASSIST_PAGE_ENABLE)) {
1056 hv->hv_vapic = data; 1098 hv_vcpu->hv_vapic = data;
1057 if (kvm_lapic_enable_pv_eoi(vcpu, 0)) 1099 if (kvm_lapic_enable_pv_eoi(vcpu, 0, 0))
1058 return 1; 1100 return 1;
1059 break; 1101 break;
1060 } 1102 }
@@ -1062,12 +1104,19 @@ static int kvm_hv_set_msr(struct kvm_vcpu *vcpu, u32 msr, u64 data, bool host)
1062 addr = kvm_vcpu_gfn_to_hva(vcpu, gfn); 1104 addr = kvm_vcpu_gfn_to_hva(vcpu, gfn);
1063 if (kvm_is_error_hva(addr)) 1105 if (kvm_is_error_hva(addr))
1064 return 1; 1106 return 1;
1065 if (__clear_user((void __user *)addr, PAGE_SIZE)) 1107
1108 /*
1109 * Clear apic_assist portion of f(struct hv_vp_assist_page
1110 * only, there can be valuable data in the rest which needs
1111 * to be preserved e.g. on migration.
1112 */
1113 if (__clear_user((void __user *)addr, sizeof(u32)))
1066 return 1; 1114 return 1;
1067 hv->hv_vapic = data; 1115 hv_vcpu->hv_vapic = data;
1068 kvm_vcpu_mark_page_dirty(vcpu, gfn); 1116 kvm_vcpu_mark_page_dirty(vcpu, gfn);
1069 if (kvm_lapic_enable_pv_eoi(vcpu, 1117 if (kvm_lapic_enable_pv_eoi(vcpu,
1070 gfn_to_gpa(gfn) | KVM_MSR_ENABLED)) 1118 gfn_to_gpa(gfn) | KVM_MSR_ENABLED,
1119 sizeof(struct hv_vp_assist_page)))
1071 return 1; 1120 return 1;
1072 break; 1121 break;
1073 } 1122 }
@@ -1080,7 +1129,7 @@ static int kvm_hv_set_msr(struct kvm_vcpu *vcpu, u32 msr, u64 data, bool host)
1080 case HV_X64_MSR_VP_RUNTIME: 1129 case HV_X64_MSR_VP_RUNTIME:
1081 if (!host) 1130 if (!host)
1082 return 1; 1131 return 1;
1083 hv->runtime_offset = data - current_task_runtime_100ns(); 1132 hv_vcpu->runtime_offset = data - current_task_runtime_100ns();
1084 break; 1133 break;
1085 case HV_X64_MSR_SCONTROL: 1134 case HV_X64_MSR_SCONTROL:
1086 case HV_X64_MSR_SVERSION: 1135 case HV_X64_MSR_SVERSION:
@@ -1172,11 +1221,11 @@ static int kvm_hv_get_msr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata,
1172 bool host) 1221 bool host)
1173{ 1222{
1174 u64 data = 0; 1223 u64 data = 0;
1175 struct kvm_vcpu_hv *hv = &vcpu->arch.hyperv; 1224 struct kvm_vcpu_hv *hv_vcpu = &vcpu->arch.hyperv;
1176 1225
1177 switch (msr) { 1226 switch (msr) {
1178 case HV_X64_MSR_VP_INDEX: 1227 case HV_X64_MSR_VP_INDEX:
1179 data = hv->vp_index; 1228 data = hv_vcpu->vp_index;
1180 break; 1229 break;
1181 case HV_X64_MSR_EOI: 1230 case HV_X64_MSR_EOI:
1182 return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata); 1231 return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
@@ -1185,10 +1234,10 @@ static int kvm_hv_get_msr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata,
1185 case HV_X64_MSR_TPR: 1234 case HV_X64_MSR_TPR:
1186 return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata); 1235 return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
1187 case HV_X64_MSR_VP_ASSIST_PAGE: 1236 case HV_X64_MSR_VP_ASSIST_PAGE:
1188 data = hv->hv_vapic; 1237 data = hv_vcpu->hv_vapic;
1189 break; 1238 break;
1190 case HV_X64_MSR_VP_RUNTIME: 1239 case HV_X64_MSR_VP_RUNTIME:
1191 data = current_task_runtime_100ns() + hv->runtime_offset; 1240 data = current_task_runtime_100ns() + hv_vcpu->runtime_offset;
1192 break; 1241 break;
1193 case HV_X64_MSR_SCONTROL: 1242 case HV_X64_MSR_SCONTROL:
1194 case HV_X64_MSR_SVERSION: 1243 case HV_X64_MSR_SVERSION:
@@ -1255,32 +1304,47 @@ int kvm_hv_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
1255 return kvm_hv_get_msr(vcpu, msr, pdata, host); 1304 return kvm_hv_get_msr(vcpu, msr, pdata, host);
1256} 1305}
1257 1306
1258static __always_inline int get_sparse_bank_no(u64 valid_bank_mask, int bank_no) 1307static __always_inline unsigned long *sparse_set_to_vcpu_mask(
1308 struct kvm *kvm, u64 *sparse_banks, u64 valid_bank_mask,
1309 u64 *vp_bitmap, unsigned long *vcpu_bitmap)
1259{ 1310{
1260 int i = 0, j; 1311 struct kvm_hv *hv = &kvm->arch.hyperv;
1312 struct kvm_vcpu *vcpu;
1313 int i, bank, sbank = 0;
1261 1314
1262 if (!(valid_bank_mask & BIT_ULL(bank_no))) 1315 memset(vp_bitmap, 0,
1263 return -1; 1316 KVM_HV_MAX_SPARSE_VCPU_SET_BITS * sizeof(*vp_bitmap));
1317 for_each_set_bit(bank, (unsigned long *)&valid_bank_mask,
1318 KVM_HV_MAX_SPARSE_VCPU_SET_BITS)
1319 vp_bitmap[bank] = sparse_banks[sbank++];
1264 1320
1265 for (j = 0; j < bank_no; j++) 1321 if (likely(!atomic_read(&hv->num_mismatched_vp_indexes))) {
1266 if (valid_bank_mask & BIT_ULL(j)) 1322 /* for all vcpus vp_index == vcpu_idx */
1267 i++; 1323 return (unsigned long *)vp_bitmap;
1324 }
1268 1325
1269 return i; 1326 bitmap_zero(vcpu_bitmap, KVM_MAX_VCPUS);
1327 kvm_for_each_vcpu(i, vcpu, kvm) {
1328 if (test_bit(vcpu_to_hv_vcpu(vcpu)->vp_index,
1329 (unsigned long *)vp_bitmap))
1330 __set_bit(i, vcpu_bitmap);
1331 }
1332 return vcpu_bitmap;
1270} 1333}
1271 1334
1272static u64 kvm_hv_flush_tlb(struct kvm_vcpu *current_vcpu, u64 ingpa, 1335static u64 kvm_hv_flush_tlb(struct kvm_vcpu *current_vcpu, u64 ingpa,
1273 u16 rep_cnt, bool ex) 1336 u16 rep_cnt, bool ex)
1274{ 1337{
1275 struct kvm *kvm = current_vcpu->kvm; 1338 struct kvm *kvm = current_vcpu->kvm;
1276 struct kvm_vcpu_hv *hv_current = &current_vcpu->arch.hyperv; 1339 struct kvm_vcpu_hv *hv_vcpu = &current_vcpu->arch.hyperv;
1277 struct hv_tlb_flush_ex flush_ex; 1340 struct hv_tlb_flush_ex flush_ex;
1278 struct hv_tlb_flush flush; 1341 struct hv_tlb_flush flush;
1279 struct kvm_vcpu *vcpu; 1342 u64 vp_bitmap[KVM_HV_MAX_SPARSE_VCPU_SET_BITS];
1280 unsigned long vcpu_bitmap[BITS_TO_LONGS(KVM_MAX_VCPUS)] = {0}; 1343 DECLARE_BITMAP(vcpu_bitmap, KVM_MAX_VCPUS);
1281 unsigned long valid_bank_mask = 0; 1344 unsigned long *vcpu_mask;
1345 u64 valid_bank_mask;
1282 u64 sparse_banks[64]; 1346 u64 sparse_banks[64];
1283 int sparse_banks_len, i; 1347 int sparse_banks_len;
1284 bool all_cpus; 1348 bool all_cpus;
1285 1349
1286 if (!ex) { 1350 if (!ex) {
@@ -1290,6 +1354,7 @@ static u64 kvm_hv_flush_tlb(struct kvm_vcpu *current_vcpu, u64 ingpa,
1290 trace_kvm_hv_flush_tlb(flush.processor_mask, 1354 trace_kvm_hv_flush_tlb(flush.processor_mask,
1291 flush.address_space, flush.flags); 1355 flush.address_space, flush.flags);
1292 1356
1357 valid_bank_mask = BIT_ULL(0);
1293 sparse_banks[0] = flush.processor_mask; 1358 sparse_banks[0] = flush.processor_mask;
1294 all_cpus = flush.flags & HV_FLUSH_ALL_PROCESSORS; 1359 all_cpus = flush.flags & HV_FLUSH_ALL_PROCESSORS;
1295 } else { 1360 } else {
@@ -1306,7 +1371,8 @@ static u64 kvm_hv_flush_tlb(struct kvm_vcpu *current_vcpu, u64 ingpa,
1306 all_cpus = flush_ex.hv_vp_set.format != 1371 all_cpus = flush_ex.hv_vp_set.format !=
1307 HV_GENERIC_SET_SPARSE_4K; 1372 HV_GENERIC_SET_SPARSE_4K;
1308 1373
1309 sparse_banks_len = bitmap_weight(&valid_bank_mask, 64) * 1374 sparse_banks_len =
1375 bitmap_weight((unsigned long *)&valid_bank_mask, 64) *
1310 sizeof(sparse_banks[0]); 1376 sizeof(sparse_banks[0]);
1311 1377
1312 if (!sparse_banks_len && !all_cpus) 1378 if (!sparse_banks_len && !all_cpus)
@@ -1321,48 +1387,19 @@ static u64 kvm_hv_flush_tlb(struct kvm_vcpu *current_vcpu, u64 ingpa,
1321 return HV_STATUS_INVALID_HYPERCALL_INPUT; 1387 return HV_STATUS_INVALID_HYPERCALL_INPUT;
1322 } 1388 }
1323 1389
1324 cpumask_clear(&hv_current->tlb_lush); 1390 cpumask_clear(&hv_vcpu->tlb_flush);
1325
1326 kvm_for_each_vcpu(i, vcpu, kvm) {
1327 struct kvm_vcpu_hv *hv = &vcpu->arch.hyperv;
1328 int bank = hv->vp_index / 64, sbank = 0;
1329
1330 if (!all_cpus) {
1331 /* Banks >64 can't be represented */
1332 if (bank >= 64)
1333 continue;
1334
1335 /* Non-ex hypercalls can only address first 64 vCPUs */
1336 if (!ex && bank)
1337 continue;
1338
1339 if (ex) {
1340 /*
1341 * Check is the bank of this vCPU is in sparse
1342 * set and get the sparse bank number.
1343 */
1344 sbank = get_sparse_bank_no(valid_bank_mask,
1345 bank);
1346
1347 if (sbank < 0)
1348 continue;
1349 }
1350
1351 if (!(sparse_banks[sbank] & BIT_ULL(hv->vp_index % 64)))
1352 continue;
1353 }
1354 1391
1355 /* 1392 vcpu_mask = all_cpus ? NULL :
1356 * vcpu->arch.cr3 may not be up-to-date for running vCPUs so we 1393 sparse_set_to_vcpu_mask(kvm, sparse_banks, valid_bank_mask,
1357 * can't analyze it here, flush TLB regardless of the specified 1394 vp_bitmap, vcpu_bitmap);
1358 * address space.
1359 */
1360 __set_bit(i, vcpu_bitmap);
1361 }
1362 1395
1396 /*
1397 * vcpu->arch.cr3 may not be up-to-date for running vCPUs so we can't
1398 * analyze it here, flush TLB regardless of the specified address space.
1399 */
1363 kvm_make_vcpus_request_mask(kvm, 1400 kvm_make_vcpus_request_mask(kvm,
1364 KVM_REQ_TLB_FLUSH | KVM_REQUEST_NO_WAKEUP, 1401 KVM_REQ_TLB_FLUSH | KVM_REQUEST_NO_WAKEUP,
1365 vcpu_bitmap, &hv_current->tlb_lush); 1402 vcpu_mask, &hv_vcpu->tlb_flush);
1366 1403
1367ret_success: 1404ret_success:
1368 /* We always do full TLB flush, set rep_done = rep_cnt. */ 1405 /* We always do full TLB flush, set rep_done = rep_cnt. */
@@ -1370,6 +1407,99 @@ ret_success:
1370 ((u64)rep_cnt << HV_HYPERCALL_REP_COMP_OFFSET); 1407 ((u64)rep_cnt << HV_HYPERCALL_REP_COMP_OFFSET);
1371} 1408}
1372 1409
1410static void kvm_send_ipi_to_many(struct kvm *kvm, u32 vector,
1411 unsigned long *vcpu_bitmap)
1412{
1413 struct kvm_lapic_irq irq = {
1414 .delivery_mode = APIC_DM_FIXED,
1415 .vector = vector
1416 };
1417 struct kvm_vcpu *vcpu;
1418 int i;
1419
1420 kvm_for_each_vcpu(i, vcpu, kvm) {
1421 if (vcpu_bitmap && !test_bit(i, vcpu_bitmap))
1422 continue;
1423
1424 /* We fail only when APIC is disabled */
1425 kvm_apic_set_irq(vcpu, &irq, NULL);
1426 }
1427}
1428
1429static u64 kvm_hv_send_ipi(struct kvm_vcpu *current_vcpu, u64 ingpa, u64 outgpa,
1430 bool ex, bool fast)
1431{
1432 struct kvm *kvm = current_vcpu->kvm;
1433 struct hv_send_ipi_ex send_ipi_ex;
1434 struct hv_send_ipi send_ipi;
1435 u64 vp_bitmap[KVM_HV_MAX_SPARSE_VCPU_SET_BITS];
1436 DECLARE_BITMAP(vcpu_bitmap, KVM_MAX_VCPUS);
1437 unsigned long *vcpu_mask;
1438 unsigned long valid_bank_mask;
1439 u64 sparse_banks[64];
1440 int sparse_banks_len;
1441 u32 vector;
1442 bool all_cpus;
1443
1444 if (!ex) {
1445 if (!fast) {
1446 if (unlikely(kvm_read_guest(kvm, ingpa, &send_ipi,
1447 sizeof(send_ipi))))
1448 return HV_STATUS_INVALID_HYPERCALL_INPUT;
1449 sparse_banks[0] = send_ipi.cpu_mask;
1450 vector = send_ipi.vector;
1451 } else {
1452 /* 'reserved' part of hv_send_ipi should be 0 */
1453 if (unlikely(ingpa >> 32 != 0))
1454 return HV_STATUS_INVALID_HYPERCALL_INPUT;
1455 sparse_banks[0] = outgpa;
1456 vector = (u32)ingpa;
1457 }
1458 all_cpus = false;
1459 valid_bank_mask = BIT_ULL(0);
1460
1461 trace_kvm_hv_send_ipi(vector, sparse_banks[0]);
1462 } else {
1463 if (unlikely(kvm_read_guest(kvm, ingpa, &send_ipi_ex,
1464 sizeof(send_ipi_ex))))
1465 return HV_STATUS_INVALID_HYPERCALL_INPUT;
1466
1467 trace_kvm_hv_send_ipi_ex(send_ipi_ex.vector,
1468 send_ipi_ex.vp_set.format,
1469 send_ipi_ex.vp_set.valid_bank_mask);
1470
1471 vector = send_ipi_ex.vector;
1472 valid_bank_mask = send_ipi_ex.vp_set.valid_bank_mask;
1473 sparse_banks_len = bitmap_weight(&valid_bank_mask, 64) *
1474 sizeof(sparse_banks[0]);
1475
1476 all_cpus = send_ipi_ex.vp_set.format == HV_GENERIC_SET_ALL;
1477
1478 if (!sparse_banks_len)
1479 goto ret_success;
1480
1481 if (!all_cpus &&
1482 kvm_read_guest(kvm,
1483 ingpa + offsetof(struct hv_send_ipi_ex,
1484 vp_set.bank_contents),
1485 sparse_banks,
1486 sparse_banks_len))
1487 return HV_STATUS_INVALID_HYPERCALL_INPUT;
1488 }
1489
1490 if ((vector < HV_IPI_LOW_VECTOR) || (vector > HV_IPI_HIGH_VECTOR))
1491 return HV_STATUS_INVALID_HYPERCALL_INPUT;
1492
1493 vcpu_mask = all_cpus ? NULL :
1494 sparse_set_to_vcpu_mask(kvm, sparse_banks, valid_bank_mask,
1495 vp_bitmap, vcpu_bitmap);
1496
1497 kvm_send_ipi_to_many(kvm, vector, vcpu_mask);
1498
1499ret_success:
1500 return HV_STATUS_SUCCESS;
1501}
1502
1373bool kvm_hv_hypercall_enabled(struct kvm *kvm) 1503bool kvm_hv_hypercall_enabled(struct kvm *kvm)
1374{ 1504{
1375 return READ_ONCE(kvm->arch.hyperv.hv_hypercall) & HV_X64_MSR_HYPERCALL_ENABLE; 1505 return READ_ONCE(kvm->arch.hyperv.hv_hypercall) & HV_X64_MSR_HYPERCALL_ENABLE;
@@ -1539,6 +1669,20 @@ int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
1539 } 1669 }
1540 ret = kvm_hv_flush_tlb(vcpu, ingpa, rep_cnt, true); 1670 ret = kvm_hv_flush_tlb(vcpu, ingpa, rep_cnt, true);
1541 break; 1671 break;
1672 case HVCALL_SEND_IPI:
1673 if (unlikely(rep)) {
1674 ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
1675 break;
1676 }
1677 ret = kvm_hv_send_ipi(vcpu, ingpa, outgpa, false, fast);
1678 break;
1679 case HVCALL_SEND_IPI_EX:
1680 if (unlikely(fast || rep)) {
1681 ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
1682 break;
1683 }
1684 ret = kvm_hv_send_ipi(vcpu, ingpa, outgpa, true, false);
1685 break;
1542 default: 1686 default:
1543 ret = HV_STATUS_INVALID_HYPERCALL_CODE; 1687 ret = HV_STATUS_INVALID_HYPERCALL_CODE;
1544 break; 1688 break;
diff --git a/arch/x86/kvm/hyperv.h b/arch/x86/kvm/hyperv.h
index d6aa969e20f1..0e66c12ed2c3 100644
--- a/arch/x86/kvm/hyperv.h
+++ b/arch/x86/kvm/hyperv.h
@@ -62,6 +62,10 @@ void kvm_hv_vcpu_init(struct kvm_vcpu *vcpu);
62void kvm_hv_vcpu_postcreate(struct kvm_vcpu *vcpu); 62void kvm_hv_vcpu_postcreate(struct kvm_vcpu *vcpu);
63void kvm_hv_vcpu_uninit(struct kvm_vcpu *vcpu); 63void kvm_hv_vcpu_uninit(struct kvm_vcpu *vcpu);
64 64
65bool kvm_hv_assist_page_enabled(struct kvm_vcpu *vcpu);
66bool kvm_hv_get_assist_page(struct kvm_vcpu *vcpu,
67 struct hv_vp_assist_page *assist_page);
68
65static inline struct kvm_vcpu_hv_stimer *vcpu_to_stimer(struct kvm_vcpu *vcpu, 69static inline struct kvm_vcpu_hv_stimer *vcpu_to_stimer(struct kvm_vcpu *vcpu,
66 int timer_index) 70 int timer_index)
67{ 71{
diff --git a/arch/x86/kvm/lapic.c b/arch/x86/kvm/lapic.c
index fbb0e6df121b..3cd227ff807f 100644
--- a/arch/x86/kvm/lapic.c
+++ b/arch/x86/kvm/lapic.c
@@ -70,6 +70,11 @@
70#define APIC_BROADCAST 0xFF 70#define APIC_BROADCAST 0xFF
71#define X2APIC_BROADCAST 0xFFFFFFFFul 71#define X2APIC_BROADCAST 0xFFFFFFFFul
72 72
73static bool lapic_timer_advance_adjust_done = false;
74#define LAPIC_TIMER_ADVANCE_ADJUST_DONE 100
75/* step-by-step approximation to mitigate fluctuation */
76#define LAPIC_TIMER_ADVANCE_ADJUST_STEP 8
77
73static inline int apic_test_vector(int vec, void *bitmap) 78static inline int apic_test_vector(int vec, void *bitmap)
74{ 79{
75 return test_bit(VEC_POS(vec), (bitmap) + REG_POS(vec)); 80 return test_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
@@ -955,14 +960,14 @@ bool kvm_irq_delivery_to_apic_fast(struct kvm *kvm, struct kvm_lapic *src,
955 map = rcu_dereference(kvm->arch.apic_map); 960 map = rcu_dereference(kvm->arch.apic_map);
956 961
957 ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dst, &bitmap); 962 ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dst, &bitmap);
958 if (ret) 963 if (ret) {
964 *r = 0;
959 for_each_set_bit(i, &bitmap, 16) { 965 for_each_set_bit(i, &bitmap, 16) {
960 if (!dst[i]) 966 if (!dst[i])
961 continue; 967 continue;
962 if (*r < 0)
963 *r = 0;
964 *r += kvm_apic_set_irq(dst[i]->vcpu, irq, dest_map); 968 *r += kvm_apic_set_irq(dst[i]->vcpu, irq, dest_map);
965 } 969 }
970 }
966 971
967 rcu_read_unlock(); 972 rcu_read_unlock();
968 return ret; 973 return ret;
@@ -1472,7 +1477,7 @@ static bool lapic_timer_int_injected(struct kvm_vcpu *vcpu)
1472void wait_lapic_expire(struct kvm_vcpu *vcpu) 1477void wait_lapic_expire(struct kvm_vcpu *vcpu)
1473{ 1478{
1474 struct kvm_lapic *apic = vcpu->arch.apic; 1479 struct kvm_lapic *apic = vcpu->arch.apic;
1475 u64 guest_tsc, tsc_deadline; 1480 u64 guest_tsc, tsc_deadline, ns;
1476 1481
1477 if (!lapic_in_kernel(vcpu)) 1482 if (!lapic_in_kernel(vcpu))
1478 return; 1483 return;
@@ -1492,6 +1497,24 @@ void wait_lapic_expire(struct kvm_vcpu *vcpu)
1492 if (guest_tsc < tsc_deadline) 1497 if (guest_tsc < tsc_deadline)
1493 __delay(min(tsc_deadline - guest_tsc, 1498 __delay(min(tsc_deadline - guest_tsc,
1494 nsec_to_cycles(vcpu, lapic_timer_advance_ns))); 1499 nsec_to_cycles(vcpu, lapic_timer_advance_ns)));
1500
1501 if (!lapic_timer_advance_adjust_done) {
1502 /* too early */
1503 if (guest_tsc < tsc_deadline) {
1504 ns = (tsc_deadline - guest_tsc) * 1000000ULL;
1505 do_div(ns, vcpu->arch.virtual_tsc_khz);
1506 lapic_timer_advance_ns -= min((unsigned int)ns,
1507 lapic_timer_advance_ns / LAPIC_TIMER_ADVANCE_ADJUST_STEP);
1508 } else {
1509 /* too late */
1510 ns = (guest_tsc - tsc_deadline) * 1000000ULL;
1511 do_div(ns, vcpu->arch.virtual_tsc_khz);
1512 lapic_timer_advance_ns += min((unsigned int)ns,
1513 lapic_timer_advance_ns / LAPIC_TIMER_ADVANCE_ADJUST_STEP);
1514 }
1515 if (abs(guest_tsc - tsc_deadline) < LAPIC_TIMER_ADVANCE_ADJUST_DONE)
1516 lapic_timer_advance_adjust_done = true;
1517 }
1495} 1518}
1496 1519
1497static void start_sw_tscdeadline(struct kvm_lapic *apic) 1520static void start_sw_tscdeadline(struct kvm_lapic *apic)
@@ -2621,17 +2644,25 @@ int kvm_hv_vapic_msr_read(struct kvm_vcpu *vcpu, u32 reg, u64 *data)
2621 return 0; 2644 return 0;
2622} 2645}
2623 2646
2624int kvm_lapic_enable_pv_eoi(struct kvm_vcpu *vcpu, u64 data) 2647int kvm_lapic_enable_pv_eoi(struct kvm_vcpu *vcpu, u64 data, unsigned long len)
2625{ 2648{
2626 u64 addr = data & ~KVM_MSR_ENABLED; 2649 u64 addr = data & ~KVM_MSR_ENABLED;
2650 struct gfn_to_hva_cache *ghc = &vcpu->arch.pv_eoi.data;
2651 unsigned long new_len;
2652
2627 if (!IS_ALIGNED(addr, 4)) 2653 if (!IS_ALIGNED(addr, 4))
2628 return 1; 2654 return 1;
2629 2655
2630 vcpu->arch.pv_eoi.msr_val = data; 2656 vcpu->arch.pv_eoi.msr_val = data;
2631 if (!pv_eoi_enabled(vcpu)) 2657 if (!pv_eoi_enabled(vcpu))
2632 return 0; 2658 return 0;
2633 return kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.pv_eoi.data, 2659
2634 addr, sizeof(u8)); 2660 if (addr == ghc->gpa && len <= ghc->len)
2661 new_len = ghc->len;
2662 else
2663 new_len = len;
2664
2665 return kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, addr, new_len);
2635} 2666}
2636 2667
2637void kvm_apic_accept_events(struct kvm_vcpu *vcpu) 2668void kvm_apic_accept_events(struct kvm_vcpu *vcpu)
diff --git a/arch/x86/kvm/lapic.h b/arch/x86/kvm/lapic.h
index ed0ed39abd36..ff6ef9c3d760 100644
--- a/arch/x86/kvm/lapic.h
+++ b/arch/x86/kvm/lapic.h
@@ -120,7 +120,7 @@ static inline bool kvm_hv_vapic_assist_page_enabled(struct kvm_vcpu *vcpu)
120 return vcpu->arch.hyperv.hv_vapic & HV_X64_MSR_VP_ASSIST_PAGE_ENABLE; 120 return vcpu->arch.hyperv.hv_vapic & HV_X64_MSR_VP_ASSIST_PAGE_ENABLE;
121} 121}
122 122
123int kvm_lapic_enable_pv_eoi(struct kvm_vcpu *vcpu, u64 data); 123int kvm_lapic_enable_pv_eoi(struct kvm_vcpu *vcpu, u64 data, unsigned long len);
124void kvm_lapic_init(void); 124void kvm_lapic_init(void);
125void kvm_lapic_exit(void); 125void kvm_lapic_exit(void);
126 126
diff --git a/arch/x86/kvm/mmu.c b/arch/x86/kvm/mmu.c
index e843ec46609d..cf5f572f2305 100644
--- a/arch/x86/kvm/mmu.c
+++ b/arch/x86/kvm/mmu.c
@@ -932,7 +932,7 @@ static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
932 while (cache->nobjs < ARRAY_SIZE(cache->objects)) { 932 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
933 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL); 933 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL);
934 if (!obj) 934 if (!obj)
935 return -ENOMEM; 935 return cache->nobjs >= min ? 0 : -ENOMEM;
936 cache->objects[cache->nobjs++] = obj; 936 cache->objects[cache->nobjs++] = obj;
937 } 937 }
938 return 0; 938 return 0;
@@ -960,7 +960,7 @@ static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
960 while (cache->nobjs < ARRAY_SIZE(cache->objects)) { 960 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
961 page = (void *)__get_free_page(GFP_KERNEL_ACCOUNT); 961 page = (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
962 if (!page) 962 if (!page)
963 return -ENOMEM; 963 return cache->nobjs >= min ? 0 : -ENOMEM;
964 cache->objects[cache->nobjs++] = page; 964 cache->objects[cache->nobjs++] = page;
965 } 965 }
966 return 0; 966 return 0;
@@ -1265,24 +1265,24 @@ pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
1265 mmu_free_pte_list_desc(desc); 1265 mmu_free_pte_list_desc(desc);
1266} 1266}
1267 1267
1268static void pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head) 1268static void __pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1269{ 1269{
1270 struct pte_list_desc *desc; 1270 struct pte_list_desc *desc;
1271 struct pte_list_desc *prev_desc; 1271 struct pte_list_desc *prev_desc;
1272 int i; 1272 int i;
1273 1273
1274 if (!rmap_head->val) { 1274 if (!rmap_head->val) {
1275 printk(KERN_ERR "pte_list_remove: %p 0->BUG\n", spte); 1275 pr_err("%s: %p 0->BUG\n", __func__, spte);
1276 BUG(); 1276 BUG();
1277 } else if (!(rmap_head->val & 1)) { 1277 } else if (!(rmap_head->val & 1)) {
1278 rmap_printk("pte_list_remove: %p 1->0\n", spte); 1278 rmap_printk("%s: %p 1->0\n", __func__, spte);
1279 if ((u64 *)rmap_head->val != spte) { 1279 if ((u64 *)rmap_head->val != spte) {
1280 printk(KERN_ERR "pte_list_remove: %p 1->BUG\n", spte); 1280 pr_err("%s: %p 1->BUG\n", __func__, spte);
1281 BUG(); 1281 BUG();
1282 } 1282 }
1283 rmap_head->val = 0; 1283 rmap_head->val = 0;
1284 } else { 1284 } else {
1285 rmap_printk("pte_list_remove: %p many->many\n", spte); 1285 rmap_printk("%s: %p many->many\n", __func__, spte);
1286 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul); 1286 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1287 prev_desc = NULL; 1287 prev_desc = NULL;
1288 while (desc) { 1288 while (desc) {
@@ -1296,11 +1296,17 @@ static void pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1296 prev_desc = desc; 1296 prev_desc = desc;
1297 desc = desc->more; 1297 desc = desc->more;
1298 } 1298 }
1299 pr_err("pte_list_remove: %p many->many\n", spte); 1299 pr_err("%s: %p many->many\n", __func__, spte);
1300 BUG(); 1300 BUG();
1301 } 1301 }
1302} 1302}
1303 1303
1304static void pte_list_remove(struct kvm_rmap_head *rmap_head, u64 *sptep)
1305{
1306 mmu_spte_clear_track_bits(sptep);
1307 __pte_list_remove(sptep, rmap_head);
1308}
1309
1304static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level, 1310static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
1305 struct kvm_memory_slot *slot) 1311 struct kvm_memory_slot *slot)
1306{ 1312{
@@ -1349,7 +1355,7 @@ static void rmap_remove(struct kvm *kvm, u64 *spte)
1349 sp = page_header(__pa(spte)); 1355 sp = page_header(__pa(spte));
1350 gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt); 1356 gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1351 rmap_head = gfn_to_rmap(kvm, gfn, sp); 1357 rmap_head = gfn_to_rmap(kvm, gfn, sp);
1352 pte_list_remove(spte, rmap_head); 1358 __pte_list_remove(spte, rmap_head);
1353} 1359}
1354 1360
1355/* 1361/*
@@ -1685,7 +1691,7 @@ static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1685 while ((sptep = rmap_get_first(rmap_head, &iter))) { 1691 while ((sptep = rmap_get_first(rmap_head, &iter))) {
1686 rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep); 1692 rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
1687 1693
1688 drop_spte(kvm, sptep); 1694 pte_list_remove(rmap_head, sptep);
1689 flush = true; 1695 flush = true;
1690 } 1696 }
1691 1697
@@ -1721,7 +1727,7 @@ restart:
1721 need_flush = 1; 1727 need_flush = 1;
1722 1728
1723 if (pte_write(*ptep)) { 1729 if (pte_write(*ptep)) {
1724 drop_spte(kvm, sptep); 1730 pte_list_remove(rmap_head, sptep);
1725 goto restart; 1731 goto restart;
1726 } else { 1732 } else {
1727 new_spte = *sptep & ~PT64_BASE_ADDR_MASK; 1733 new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
@@ -1988,7 +1994,7 @@ static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
1988static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp, 1994static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
1989 u64 *parent_pte) 1995 u64 *parent_pte)
1990{ 1996{
1991 pte_list_remove(parent_pte, &sp->parent_ptes); 1997 __pte_list_remove(parent_pte, &sp->parent_ptes);
1992} 1998}
1993 1999
1994static void drop_parent_pte(struct kvm_mmu_page *sp, 2000static void drop_parent_pte(struct kvm_mmu_page *sp,
@@ -2181,7 +2187,7 @@ static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2181 struct list_head *invalid_list) 2187 struct list_head *invalid_list)
2182{ 2188{
2183 if (sp->role.cr4_pae != !!is_pae(vcpu) 2189 if (sp->role.cr4_pae != !!is_pae(vcpu)
2184 || vcpu->arch.mmu.sync_page(vcpu, sp) == 0) { 2190 || vcpu->arch.mmu->sync_page(vcpu, sp) == 0) {
2185 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list); 2191 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2186 return false; 2192 return false;
2187 } 2193 }
@@ -2375,14 +2381,14 @@ static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2375 int collisions = 0; 2381 int collisions = 0;
2376 LIST_HEAD(invalid_list); 2382 LIST_HEAD(invalid_list);
2377 2383
2378 role = vcpu->arch.mmu.base_role; 2384 role = vcpu->arch.mmu->mmu_role.base;
2379 role.level = level; 2385 role.level = level;
2380 role.direct = direct; 2386 role.direct = direct;
2381 if (role.direct) 2387 if (role.direct)
2382 role.cr4_pae = 0; 2388 role.cr4_pae = 0;
2383 role.access = access; 2389 role.access = access;
2384 if (!vcpu->arch.mmu.direct_map 2390 if (!vcpu->arch.mmu->direct_map
2385 && vcpu->arch.mmu.root_level <= PT32_ROOT_LEVEL) { 2391 && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
2386 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level)); 2392 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2387 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1; 2393 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2388 role.quadrant = quadrant; 2394 role.quadrant = quadrant;
@@ -2457,11 +2463,11 @@ static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterato
2457{ 2463{
2458 iterator->addr = addr; 2464 iterator->addr = addr;
2459 iterator->shadow_addr = root; 2465 iterator->shadow_addr = root;
2460 iterator->level = vcpu->arch.mmu.shadow_root_level; 2466 iterator->level = vcpu->arch.mmu->shadow_root_level;
2461 2467
2462 if (iterator->level == PT64_ROOT_4LEVEL && 2468 if (iterator->level == PT64_ROOT_4LEVEL &&
2463 vcpu->arch.mmu.root_level < PT64_ROOT_4LEVEL && 2469 vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2464 !vcpu->arch.mmu.direct_map) 2470 !vcpu->arch.mmu->direct_map)
2465 --iterator->level; 2471 --iterator->level;
2466 2472
2467 if (iterator->level == PT32E_ROOT_LEVEL) { 2473 if (iterator->level == PT32E_ROOT_LEVEL) {
@@ -2469,10 +2475,10 @@ static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterato
2469 * prev_root is currently only used for 64-bit hosts. So only 2475 * prev_root is currently only used for 64-bit hosts. So only
2470 * the active root_hpa is valid here. 2476 * the active root_hpa is valid here.
2471 */ 2477 */
2472 BUG_ON(root != vcpu->arch.mmu.root_hpa); 2478 BUG_ON(root != vcpu->arch.mmu->root_hpa);
2473 2479
2474 iterator->shadow_addr 2480 iterator->shadow_addr
2475 = vcpu->arch.mmu.pae_root[(addr >> 30) & 3]; 2481 = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2476 iterator->shadow_addr &= PT64_BASE_ADDR_MASK; 2482 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2477 --iterator->level; 2483 --iterator->level;
2478 if (!iterator->shadow_addr) 2484 if (!iterator->shadow_addr)
@@ -2483,7 +2489,7 @@ static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterato
2483static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator, 2489static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2484 struct kvm_vcpu *vcpu, u64 addr) 2490 struct kvm_vcpu *vcpu, u64 addr)
2485{ 2491{
2486 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu.root_hpa, 2492 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
2487 addr); 2493 addr);
2488} 2494}
2489 2495
@@ -3095,7 +3101,7 @@ static int __direct_map(struct kvm_vcpu *vcpu, int write, int map_writable,
3095 int emulate = 0; 3101 int emulate = 0;
3096 gfn_t pseudo_gfn; 3102 gfn_t pseudo_gfn;
3097 3103
3098 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa)) 3104 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3099 return 0; 3105 return 0;
3100 3106
3101 for_each_shadow_entry(vcpu, (u64)gfn << PAGE_SHIFT, iterator) { 3107 for_each_shadow_entry(vcpu, (u64)gfn << PAGE_SHIFT, iterator) {
@@ -3301,7 +3307,7 @@ static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level,
3301 u64 spte = 0ull; 3307 u64 spte = 0ull;
3302 uint retry_count = 0; 3308 uint retry_count = 0;
3303 3309
3304 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa)) 3310 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3305 return false; 3311 return false;
3306 3312
3307 if (!page_fault_can_be_fast(error_code)) 3313 if (!page_fault_can_be_fast(error_code))
@@ -3471,11 +3477,11 @@ static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3471} 3477}
3472 3478
3473/* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */ 3479/* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3474void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, ulong roots_to_free) 3480void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
3481 ulong roots_to_free)
3475{ 3482{
3476 int i; 3483 int i;
3477 LIST_HEAD(invalid_list); 3484 LIST_HEAD(invalid_list);
3478 struct kvm_mmu *mmu = &vcpu->arch.mmu;
3479 bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT; 3485 bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
3480 3486
3481 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG); 3487 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
@@ -3535,20 +3541,20 @@ static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3535 struct kvm_mmu_page *sp; 3541 struct kvm_mmu_page *sp;
3536 unsigned i; 3542 unsigned i;
3537 3543
3538 if (vcpu->arch.mmu.shadow_root_level >= PT64_ROOT_4LEVEL) { 3544 if (vcpu->arch.mmu->shadow_root_level >= PT64_ROOT_4LEVEL) {
3539 spin_lock(&vcpu->kvm->mmu_lock); 3545 spin_lock(&vcpu->kvm->mmu_lock);
3540 if(make_mmu_pages_available(vcpu) < 0) { 3546 if(make_mmu_pages_available(vcpu) < 0) {
3541 spin_unlock(&vcpu->kvm->mmu_lock); 3547 spin_unlock(&vcpu->kvm->mmu_lock);
3542 return -ENOSPC; 3548 return -ENOSPC;
3543 } 3549 }
3544 sp = kvm_mmu_get_page(vcpu, 0, 0, 3550 sp = kvm_mmu_get_page(vcpu, 0, 0,
3545 vcpu->arch.mmu.shadow_root_level, 1, ACC_ALL); 3551 vcpu->arch.mmu->shadow_root_level, 1, ACC_ALL);
3546 ++sp->root_count; 3552 ++sp->root_count;
3547 spin_unlock(&vcpu->kvm->mmu_lock); 3553 spin_unlock(&vcpu->kvm->mmu_lock);
3548 vcpu->arch.mmu.root_hpa = __pa(sp->spt); 3554 vcpu->arch.mmu->root_hpa = __pa(sp->spt);
3549 } else if (vcpu->arch.mmu.shadow_root_level == PT32E_ROOT_LEVEL) { 3555 } else if (vcpu->arch.mmu->shadow_root_level == PT32E_ROOT_LEVEL) {
3550 for (i = 0; i < 4; ++i) { 3556 for (i = 0; i < 4; ++i) {
3551 hpa_t root = vcpu->arch.mmu.pae_root[i]; 3557 hpa_t root = vcpu->arch.mmu->pae_root[i];
3552 3558
3553 MMU_WARN_ON(VALID_PAGE(root)); 3559 MMU_WARN_ON(VALID_PAGE(root));
3554 spin_lock(&vcpu->kvm->mmu_lock); 3560 spin_lock(&vcpu->kvm->mmu_lock);
@@ -3561,9 +3567,9 @@ static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3561 root = __pa(sp->spt); 3567 root = __pa(sp->spt);
3562 ++sp->root_count; 3568 ++sp->root_count;
3563 spin_unlock(&vcpu->kvm->mmu_lock); 3569 spin_unlock(&vcpu->kvm->mmu_lock);
3564 vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK; 3570 vcpu->arch.mmu->pae_root[i] = root | PT_PRESENT_MASK;
3565 } 3571 }
3566 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root); 3572 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3567 } else 3573 } else
3568 BUG(); 3574 BUG();
3569 3575
@@ -3577,7 +3583,7 @@ static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3577 gfn_t root_gfn; 3583 gfn_t root_gfn;
3578 int i; 3584 int i;
3579 3585
3580 root_gfn = vcpu->arch.mmu.get_cr3(vcpu) >> PAGE_SHIFT; 3586 root_gfn = vcpu->arch.mmu->get_cr3(vcpu) >> PAGE_SHIFT;
3581 3587
3582 if (mmu_check_root(vcpu, root_gfn)) 3588 if (mmu_check_root(vcpu, root_gfn))
3583 return 1; 3589 return 1;
@@ -3586,8 +3592,8 @@ static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3586 * Do we shadow a long mode page table? If so we need to 3592 * Do we shadow a long mode page table? If so we need to
3587 * write-protect the guests page table root. 3593 * write-protect the guests page table root.
3588 */ 3594 */
3589 if (vcpu->arch.mmu.root_level >= PT64_ROOT_4LEVEL) { 3595 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3590 hpa_t root = vcpu->arch.mmu.root_hpa; 3596 hpa_t root = vcpu->arch.mmu->root_hpa;
3591 3597
3592 MMU_WARN_ON(VALID_PAGE(root)); 3598 MMU_WARN_ON(VALID_PAGE(root));
3593 3599
@@ -3597,11 +3603,11 @@ static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3597 return -ENOSPC; 3603 return -ENOSPC;
3598 } 3604 }
3599 sp = kvm_mmu_get_page(vcpu, root_gfn, 0, 3605 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
3600 vcpu->arch.mmu.shadow_root_level, 0, ACC_ALL); 3606 vcpu->arch.mmu->shadow_root_level, 0, ACC_ALL);
3601 root = __pa(sp->spt); 3607 root = __pa(sp->spt);
3602 ++sp->root_count; 3608 ++sp->root_count;
3603 spin_unlock(&vcpu->kvm->mmu_lock); 3609 spin_unlock(&vcpu->kvm->mmu_lock);
3604 vcpu->arch.mmu.root_hpa = root; 3610 vcpu->arch.mmu->root_hpa = root;
3605 return 0; 3611 return 0;
3606 } 3612 }
3607 3613
@@ -3611,17 +3617,17 @@ static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3611 * the shadow page table may be a PAE or a long mode page table. 3617 * the shadow page table may be a PAE or a long mode page table.
3612 */ 3618 */
3613 pm_mask = PT_PRESENT_MASK; 3619 pm_mask = PT_PRESENT_MASK;
3614 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_4LEVEL) 3620 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL)
3615 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK; 3621 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3616 3622
3617 for (i = 0; i < 4; ++i) { 3623 for (i = 0; i < 4; ++i) {
3618 hpa_t root = vcpu->arch.mmu.pae_root[i]; 3624 hpa_t root = vcpu->arch.mmu->pae_root[i];
3619 3625
3620 MMU_WARN_ON(VALID_PAGE(root)); 3626 MMU_WARN_ON(VALID_PAGE(root));
3621 if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) { 3627 if (vcpu->arch.mmu->root_level == PT32E_ROOT_LEVEL) {
3622 pdptr = vcpu->arch.mmu.get_pdptr(vcpu, i); 3628 pdptr = vcpu->arch.mmu->get_pdptr(vcpu, i);
3623 if (!(pdptr & PT_PRESENT_MASK)) { 3629 if (!(pdptr & PT_PRESENT_MASK)) {
3624 vcpu->arch.mmu.pae_root[i] = 0; 3630 vcpu->arch.mmu->pae_root[i] = 0;
3625 continue; 3631 continue;
3626 } 3632 }
3627 root_gfn = pdptr >> PAGE_SHIFT; 3633 root_gfn = pdptr >> PAGE_SHIFT;
@@ -3639,16 +3645,16 @@ static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3639 ++sp->root_count; 3645 ++sp->root_count;
3640 spin_unlock(&vcpu->kvm->mmu_lock); 3646 spin_unlock(&vcpu->kvm->mmu_lock);
3641 3647
3642 vcpu->arch.mmu.pae_root[i] = root | pm_mask; 3648 vcpu->arch.mmu->pae_root[i] = root | pm_mask;
3643 } 3649 }
3644 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root); 3650 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3645 3651
3646 /* 3652 /*
3647 * If we shadow a 32 bit page table with a long mode page 3653 * If we shadow a 32 bit page table with a long mode page
3648 * table we enter this path. 3654 * table we enter this path.
3649 */ 3655 */
3650 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_4LEVEL) { 3656 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL) {
3651 if (vcpu->arch.mmu.lm_root == NULL) { 3657 if (vcpu->arch.mmu->lm_root == NULL) {
3652 /* 3658 /*
3653 * The additional page necessary for this is only 3659 * The additional page necessary for this is only
3654 * allocated on demand. 3660 * allocated on demand.
@@ -3660,12 +3666,12 @@ static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3660 if (lm_root == NULL) 3666 if (lm_root == NULL)
3661 return 1; 3667 return 1;
3662 3668
3663 lm_root[0] = __pa(vcpu->arch.mmu.pae_root) | pm_mask; 3669 lm_root[0] = __pa(vcpu->arch.mmu->pae_root) | pm_mask;
3664 3670
3665 vcpu->arch.mmu.lm_root = lm_root; 3671 vcpu->arch.mmu->lm_root = lm_root;
3666 } 3672 }
3667 3673
3668 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.lm_root); 3674 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->lm_root);
3669 } 3675 }
3670 3676
3671 return 0; 3677 return 0;
@@ -3673,7 +3679,7 @@ static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3673 3679
3674static int mmu_alloc_roots(struct kvm_vcpu *vcpu) 3680static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3675{ 3681{
3676 if (vcpu->arch.mmu.direct_map) 3682 if (vcpu->arch.mmu->direct_map)
3677 return mmu_alloc_direct_roots(vcpu); 3683 return mmu_alloc_direct_roots(vcpu);
3678 else 3684 else
3679 return mmu_alloc_shadow_roots(vcpu); 3685 return mmu_alloc_shadow_roots(vcpu);
@@ -3684,17 +3690,16 @@ void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3684 int i; 3690 int i;
3685 struct kvm_mmu_page *sp; 3691 struct kvm_mmu_page *sp;
3686 3692
3687 if (vcpu->arch.mmu.direct_map) 3693 if (vcpu->arch.mmu->direct_map)
3688 return; 3694 return;
3689 3695
3690 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa)) 3696 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3691 return; 3697 return;
3692 3698
3693 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY); 3699 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3694 3700
3695 if (vcpu->arch.mmu.root_level >= PT64_ROOT_4LEVEL) { 3701 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3696 hpa_t root = vcpu->arch.mmu.root_hpa; 3702 hpa_t root = vcpu->arch.mmu->root_hpa;
3697
3698 sp = page_header(root); 3703 sp = page_header(root);
3699 3704
3700 /* 3705 /*
@@ -3725,7 +3730,7 @@ void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3725 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC); 3730 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3726 3731
3727 for (i = 0; i < 4; ++i) { 3732 for (i = 0; i < 4; ++i) {
3728 hpa_t root = vcpu->arch.mmu.pae_root[i]; 3733 hpa_t root = vcpu->arch.mmu->pae_root[i];
3729 3734
3730 if (root && VALID_PAGE(root)) { 3735 if (root && VALID_PAGE(root)) {
3731 root &= PT64_BASE_ADDR_MASK; 3736 root &= PT64_BASE_ADDR_MASK;
@@ -3799,7 +3804,7 @@ walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3799 int root, leaf; 3804 int root, leaf;
3800 bool reserved = false; 3805 bool reserved = false;
3801 3806
3802 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa)) 3807 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3803 goto exit; 3808 goto exit;
3804 3809
3805 walk_shadow_page_lockless_begin(vcpu); 3810 walk_shadow_page_lockless_begin(vcpu);
@@ -3816,7 +3821,7 @@ walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3816 if (!is_shadow_present_pte(spte)) 3821 if (!is_shadow_present_pte(spte))
3817 break; 3822 break;
3818 3823
3819 reserved |= is_shadow_zero_bits_set(&vcpu->arch.mmu, spte, 3824 reserved |= is_shadow_zero_bits_set(vcpu->arch.mmu, spte,
3820 iterator.level); 3825 iterator.level);
3821 } 3826 }
3822 3827
@@ -3895,7 +3900,7 @@ static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
3895 struct kvm_shadow_walk_iterator iterator; 3900 struct kvm_shadow_walk_iterator iterator;
3896 u64 spte; 3901 u64 spte;
3897 3902
3898 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa)) 3903 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3899 return; 3904 return;
3900 3905
3901 walk_shadow_page_lockless_begin(vcpu); 3906 walk_shadow_page_lockless_begin(vcpu);
@@ -3922,7 +3927,7 @@ static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
3922 if (r) 3927 if (r)
3923 return r; 3928 return r;
3924 3929
3925 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa)); 3930 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
3926 3931
3927 3932
3928 return nonpaging_map(vcpu, gva & PAGE_MASK, 3933 return nonpaging_map(vcpu, gva & PAGE_MASK,
@@ -3935,8 +3940,8 @@ static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
3935 3940
3936 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id; 3941 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
3937 arch.gfn = gfn; 3942 arch.gfn = gfn;
3938 arch.direct_map = vcpu->arch.mmu.direct_map; 3943 arch.direct_map = vcpu->arch.mmu->direct_map;
3939 arch.cr3 = vcpu->arch.mmu.get_cr3(vcpu); 3944 arch.cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3940 3945
3941 return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch); 3946 return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
3942} 3947}
@@ -4042,7 +4047,7 @@ static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
4042 int write = error_code & PFERR_WRITE_MASK; 4047 int write = error_code & PFERR_WRITE_MASK;
4043 bool map_writable; 4048 bool map_writable;
4044 4049
4045 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa)); 4050 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
4046 4051
4047 if (page_fault_handle_page_track(vcpu, error_code, gfn)) 4052 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4048 return RET_PF_EMULATE; 4053 return RET_PF_EMULATE;
@@ -4118,7 +4123,7 @@ static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4118{ 4123{
4119 uint i; 4124 uint i;
4120 struct kvm_mmu_root_info root; 4125 struct kvm_mmu_root_info root;
4121 struct kvm_mmu *mmu = &vcpu->arch.mmu; 4126 struct kvm_mmu *mmu = vcpu->arch.mmu;
4122 4127
4123 root.cr3 = mmu->get_cr3(vcpu); 4128 root.cr3 = mmu->get_cr3(vcpu);
4124 root.hpa = mmu->root_hpa; 4129 root.hpa = mmu->root_hpa;
@@ -4141,7 +4146,7 @@ static bool fast_cr3_switch(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4141 union kvm_mmu_page_role new_role, 4146 union kvm_mmu_page_role new_role,
4142 bool skip_tlb_flush) 4147 bool skip_tlb_flush)
4143{ 4148{
4144 struct kvm_mmu *mmu = &vcpu->arch.mmu; 4149 struct kvm_mmu *mmu = vcpu->arch.mmu;
4145 4150
4146 /* 4151 /*
4147 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid 4152 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
@@ -4192,7 +4197,8 @@ static void __kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4192 bool skip_tlb_flush) 4197 bool skip_tlb_flush)
4193{ 4198{
4194 if (!fast_cr3_switch(vcpu, new_cr3, new_role, skip_tlb_flush)) 4199 if (!fast_cr3_switch(vcpu, new_cr3, new_role, skip_tlb_flush))
4195 kvm_mmu_free_roots(vcpu, KVM_MMU_ROOT_CURRENT); 4200 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu,
4201 KVM_MMU_ROOT_CURRENT);
4196} 4202}
4197 4203
4198void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3, bool skip_tlb_flush) 4204void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3, bool skip_tlb_flush)
@@ -4210,7 +4216,7 @@ static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4210static void inject_page_fault(struct kvm_vcpu *vcpu, 4216static void inject_page_fault(struct kvm_vcpu *vcpu,
4211 struct x86_exception *fault) 4217 struct x86_exception *fault)
4212{ 4218{
4213 vcpu->arch.mmu.inject_page_fault(vcpu, fault); 4219 vcpu->arch.mmu->inject_page_fault(vcpu, fault);
4214} 4220}
4215 4221
4216static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn, 4222static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
@@ -4414,7 +4420,8 @@ static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4414void 4420void
4415reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context) 4421reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4416{ 4422{
4417 bool uses_nx = context->nx || context->base_role.smep_andnot_wp; 4423 bool uses_nx = context->nx ||
4424 context->mmu_role.base.smep_andnot_wp;
4418 struct rsvd_bits_validate *shadow_zero_check; 4425 struct rsvd_bits_validate *shadow_zero_check;
4419 int i; 4426 int i;
4420 4427
@@ -4553,7 +4560,7 @@ static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4553 * SMAP:kernel-mode data accesses from user-mode 4560 * SMAP:kernel-mode data accesses from user-mode
4554 * mappings should fault. A fault is considered 4561 * mappings should fault. A fault is considered
4555 * as a SMAP violation if all of the following 4562 * as a SMAP violation if all of the following
4556 * conditions are ture: 4563 * conditions are true:
4557 * - X86_CR4_SMAP is set in CR4 4564 * - X86_CR4_SMAP is set in CR4
4558 * - A user page is accessed 4565 * - A user page is accessed
4559 * - The access is not a fetch 4566 * - The access is not a fetch
@@ -4714,27 +4721,65 @@ static void paging32E_init_context(struct kvm_vcpu *vcpu,
4714 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL); 4721 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4715} 4722}
4716 4723
4717static union kvm_mmu_page_role 4724static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu)
4718kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu) 4725{
4726 union kvm_mmu_extended_role ext = {0};
4727
4728 ext.cr0_pg = !!is_paging(vcpu);
4729 ext.cr4_smep = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4730 ext.cr4_smap = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4731 ext.cr4_pse = !!is_pse(vcpu);
4732 ext.cr4_pke = !!kvm_read_cr4_bits(vcpu, X86_CR4_PKE);
4733 ext.cr4_la57 = !!kvm_read_cr4_bits(vcpu, X86_CR4_LA57);
4734
4735 ext.valid = 1;
4736
4737 return ext;
4738}
4739
4740static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
4741 bool base_only)
4742{
4743 union kvm_mmu_role role = {0};
4744
4745 role.base.access = ACC_ALL;
4746 role.base.nxe = !!is_nx(vcpu);
4747 role.base.cr4_pae = !!is_pae(vcpu);
4748 role.base.cr0_wp = is_write_protection(vcpu);
4749 role.base.smm = is_smm(vcpu);
4750 role.base.guest_mode = is_guest_mode(vcpu);
4751
4752 if (base_only)
4753 return role;
4754
4755 role.ext = kvm_calc_mmu_role_ext(vcpu);
4756
4757 return role;
4758}
4759
4760static union kvm_mmu_role
4761kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4719{ 4762{
4720 union kvm_mmu_page_role role = {0}; 4763 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4721 4764
4722 role.guest_mode = is_guest_mode(vcpu); 4765 role.base.ad_disabled = (shadow_accessed_mask == 0);
4723 role.smm = is_smm(vcpu); 4766 role.base.level = kvm_x86_ops->get_tdp_level(vcpu);
4724 role.ad_disabled = (shadow_accessed_mask == 0); 4767 role.base.direct = true;
4725 role.level = kvm_x86_ops->get_tdp_level(vcpu);
4726 role.direct = true;
4727 role.access = ACC_ALL;
4728 4768
4729 return role; 4769 return role;
4730} 4770}
4731 4771
4732static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu) 4772static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4733{ 4773{
4734 struct kvm_mmu *context = &vcpu->arch.mmu; 4774 struct kvm_mmu *context = vcpu->arch.mmu;
4775 union kvm_mmu_role new_role =
4776 kvm_calc_tdp_mmu_root_page_role(vcpu, false);
4735 4777
4736 context->base_role.word = mmu_base_role_mask.word & 4778 new_role.base.word &= mmu_base_role_mask.word;
4737 kvm_calc_tdp_mmu_root_page_role(vcpu).word; 4779 if (new_role.as_u64 == context->mmu_role.as_u64)
4780 return;
4781
4782 context->mmu_role.as_u64 = new_role.as_u64;
4738 context->page_fault = tdp_page_fault; 4783 context->page_fault = tdp_page_fault;
4739 context->sync_page = nonpaging_sync_page; 4784 context->sync_page = nonpaging_sync_page;
4740 context->invlpg = nonpaging_invlpg; 4785 context->invlpg = nonpaging_invlpg;
@@ -4774,36 +4819,36 @@ static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4774 reset_tdp_shadow_zero_bits_mask(vcpu, context); 4819 reset_tdp_shadow_zero_bits_mask(vcpu, context);
4775} 4820}
4776 4821
4777static union kvm_mmu_page_role 4822static union kvm_mmu_role
4778kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu) 4823kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4779{ 4824{
4780 union kvm_mmu_page_role role = {0}; 4825 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4781 bool smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP); 4826
4782 bool smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP); 4827 role.base.smep_andnot_wp = role.ext.cr4_smep &&
4783 4828 !is_write_protection(vcpu);
4784 role.nxe = is_nx(vcpu); 4829 role.base.smap_andnot_wp = role.ext.cr4_smap &&
4785 role.cr4_pae = !!is_pae(vcpu); 4830 !is_write_protection(vcpu);
4786 role.cr0_wp = is_write_protection(vcpu); 4831 role.base.direct = !is_paging(vcpu);
4787 role.smep_andnot_wp = smep && !is_write_protection(vcpu);
4788 role.smap_andnot_wp = smap && !is_write_protection(vcpu);
4789 role.guest_mode = is_guest_mode(vcpu);
4790 role.smm = is_smm(vcpu);
4791 role.direct = !is_paging(vcpu);
4792 role.access = ACC_ALL;
4793 4832
4794 if (!is_long_mode(vcpu)) 4833 if (!is_long_mode(vcpu))
4795 role.level = PT32E_ROOT_LEVEL; 4834 role.base.level = PT32E_ROOT_LEVEL;
4796 else if (is_la57_mode(vcpu)) 4835 else if (is_la57_mode(vcpu))
4797 role.level = PT64_ROOT_5LEVEL; 4836 role.base.level = PT64_ROOT_5LEVEL;
4798 else 4837 else
4799 role.level = PT64_ROOT_4LEVEL; 4838 role.base.level = PT64_ROOT_4LEVEL;
4800 4839
4801 return role; 4840 return role;
4802} 4841}
4803 4842
4804void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu) 4843void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
4805{ 4844{
4806 struct kvm_mmu *context = &vcpu->arch.mmu; 4845 struct kvm_mmu *context = vcpu->arch.mmu;
4846 union kvm_mmu_role new_role =
4847 kvm_calc_shadow_mmu_root_page_role(vcpu, false);
4848
4849 new_role.base.word &= mmu_base_role_mask.word;
4850 if (new_role.as_u64 == context->mmu_role.as_u64)
4851 return;
4807 4852
4808 if (!is_paging(vcpu)) 4853 if (!is_paging(vcpu))
4809 nonpaging_init_context(vcpu, context); 4854 nonpaging_init_context(vcpu, context);
@@ -4814,22 +4859,28 @@ void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
4814 else 4859 else
4815 paging32_init_context(vcpu, context); 4860 paging32_init_context(vcpu, context);
4816 4861
4817 context->base_role.word = mmu_base_role_mask.word & 4862 context->mmu_role.as_u64 = new_role.as_u64;
4818 kvm_calc_shadow_mmu_root_page_role(vcpu).word;
4819 reset_shadow_zero_bits_mask(vcpu, context); 4863 reset_shadow_zero_bits_mask(vcpu, context);
4820} 4864}
4821EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu); 4865EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
4822 4866
4823static union kvm_mmu_page_role 4867static union kvm_mmu_role
4824kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty) 4868kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
4869 bool execonly)
4825{ 4870{
4826 union kvm_mmu_page_role role = vcpu->arch.mmu.base_role; 4871 union kvm_mmu_role role;
4872
4873 /* Base role is inherited from root_mmu */
4874 role.base.word = vcpu->arch.root_mmu.mmu_role.base.word;
4875 role.ext = kvm_calc_mmu_role_ext(vcpu);
4876
4877 role.base.level = PT64_ROOT_4LEVEL;
4878 role.base.direct = false;
4879 role.base.ad_disabled = !accessed_dirty;
4880 role.base.guest_mode = true;
4881 role.base.access = ACC_ALL;
4827 4882
4828 role.level = PT64_ROOT_4LEVEL; 4883 role.ext.execonly = execonly;
4829 role.direct = false;
4830 role.ad_disabled = !accessed_dirty;
4831 role.guest_mode = true;
4832 role.access = ACC_ALL;
4833 4884
4834 return role; 4885 return role;
4835} 4886}
@@ -4837,11 +4888,17 @@ kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty)
4837void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly, 4888void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
4838 bool accessed_dirty, gpa_t new_eptp) 4889 bool accessed_dirty, gpa_t new_eptp)
4839{ 4890{
4840 struct kvm_mmu *context = &vcpu->arch.mmu; 4891 struct kvm_mmu *context = vcpu->arch.mmu;
4841 union kvm_mmu_page_role root_page_role = 4892 union kvm_mmu_role new_role =
4842 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty); 4893 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
4894 execonly);
4895
4896 __kvm_mmu_new_cr3(vcpu, new_eptp, new_role.base, false);
4897
4898 new_role.base.word &= mmu_base_role_mask.word;
4899 if (new_role.as_u64 == context->mmu_role.as_u64)
4900 return;
4843 4901
4844 __kvm_mmu_new_cr3(vcpu, new_eptp, root_page_role, false);
4845 context->shadow_root_level = PT64_ROOT_4LEVEL; 4902 context->shadow_root_level = PT64_ROOT_4LEVEL;
4846 4903
4847 context->nx = true; 4904 context->nx = true;
@@ -4853,7 +4910,8 @@ void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
4853 context->update_pte = ept_update_pte; 4910 context->update_pte = ept_update_pte;
4854 context->root_level = PT64_ROOT_4LEVEL; 4911 context->root_level = PT64_ROOT_4LEVEL;
4855 context->direct_map = false; 4912 context->direct_map = false;
4856 context->base_role.word = root_page_role.word & mmu_base_role_mask.word; 4913 context->mmu_role.as_u64 = new_role.as_u64;
4914
4857 update_permission_bitmask(vcpu, context, true); 4915 update_permission_bitmask(vcpu, context, true);
4858 update_pkru_bitmask(vcpu, context, true); 4916 update_pkru_bitmask(vcpu, context, true);
4859 update_last_nonleaf_level(vcpu, context); 4917 update_last_nonleaf_level(vcpu, context);
@@ -4864,7 +4922,7 @@ EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
4864 4922
4865static void init_kvm_softmmu(struct kvm_vcpu *vcpu) 4923static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
4866{ 4924{
4867 struct kvm_mmu *context = &vcpu->arch.mmu; 4925 struct kvm_mmu *context = vcpu->arch.mmu;
4868 4926
4869 kvm_init_shadow_mmu(vcpu); 4927 kvm_init_shadow_mmu(vcpu);
4870 context->set_cr3 = kvm_x86_ops->set_cr3; 4928 context->set_cr3 = kvm_x86_ops->set_cr3;
@@ -4875,14 +4933,20 @@ static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
4875 4933
4876static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu) 4934static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
4877{ 4935{
4936 union kvm_mmu_role new_role = kvm_calc_mmu_role_common(vcpu, false);
4878 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu; 4937 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
4879 4938
4939 new_role.base.word &= mmu_base_role_mask.word;
4940 if (new_role.as_u64 == g_context->mmu_role.as_u64)
4941 return;
4942
4943 g_context->mmu_role.as_u64 = new_role.as_u64;
4880 g_context->get_cr3 = get_cr3; 4944 g_context->get_cr3 = get_cr3;
4881 g_context->get_pdptr = kvm_pdptr_read; 4945 g_context->get_pdptr = kvm_pdptr_read;
4882 g_context->inject_page_fault = kvm_inject_page_fault; 4946 g_context->inject_page_fault = kvm_inject_page_fault;
4883 4947
4884 /* 4948 /*
4885 * Note that arch.mmu.gva_to_gpa translates l2_gpa to l1_gpa using 4949 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
4886 * L1's nested page tables (e.g. EPT12). The nested translation 4950 * L1's nested page tables (e.g. EPT12). The nested translation
4887 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using 4951 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
4888 * L2's page tables as the first level of translation and L1's 4952 * L2's page tables as the first level of translation and L1's
@@ -4921,10 +4985,10 @@ void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
4921 if (reset_roots) { 4985 if (reset_roots) {
4922 uint i; 4986 uint i;
4923 4987
4924 vcpu->arch.mmu.root_hpa = INVALID_PAGE; 4988 vcpu->arch.mmu->root_hpa = INVALID_PAGE;
4925 4989
4926 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) 4990 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
4927 vcpu->arch.mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID; 4991 vcpu->arch.mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
4928 } 4992 }
4929 4993
4930 if (mmu_is_nested(vcpu)) 4994 if (mmu_is_nested(vcpu))
@@ -4939,10 +5003,14 @@ EXPORT_SYMBOL_GPL(kvm_init_mmu);
4939static union kvm_mmu_page_role 5003static union kvm_mmu_page_role
4940kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu) 5004kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
4941{ 5005{
5006 union kvm_mmu_role role;
5007
4942 if (tdp_enabled) 5008 if (tdp_enabled)
4943 return kvm_calc_tdp_mmu_root_page_role(vcpu); 5009 role = kvm_calc_tdp_mmu_root_page_role(vcpu, true);
4944 else 5010 else
4945 return kvm_calc_shadow_mmu_root_page_role(vcpu); 5011 role = kvm_calc_shadow_mmu_root_page_role(vcpu, true);
5012
5013 return role.base;
4946} 5014}
4947 5015
4948void kvm_mmu_reset_context(struct kvm_vcpu *vcpu) 5016void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
@@ -4972,8 +5040,10 @@ EXPORT_SYMBOL_GPL(kvm_mmu_load);
4972 5040
4973void kvm_mmu_unload(struct kvm_vcpu *vcpu) 5041void kvm_mmu_unload(struct kvm_vcpu *vcpu)
4974{ 5042{
4975 kvm_mmu_free_roots(vcpu, KVM_MMU_ROOTS_ALL); 5043 kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
4976 WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa)); 5044 WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
5045 kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5046 WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
4977} 5047}
4978EXPORT_SYMBOL_GPL(kvm_mmu_unload); 5048EXPORT_SYMBOL_GPL(kvm_mmu_unload);
4979 5049
@@ -4987,7 +5057,7 @@ static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
4987 } 5057 }
4988 5058
4989 ++vcpu->kvm->stat.mmu_pte_updated; 5059 ++vcpu->kvm->stat.mmu_pte_updated;
4990 vcpu->arch.mmu.update_pte(vcpu, sp, spte, new); 5060 vcpu->arch.mmu->update_pte(vcpu, sp, spte, new);
4991} 5061}
4992 5062
4993static bool need_remote_flush(u64 old, u64 new) 5063static bool need_remote_flush(u64 old, u64 new)
@@ -5164,10 +5234,12 @@ static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5164 5234
5165 local_flush = true; 5235 local_flush = true;
5166 while (npte--) { 5236 while (npte--) {
5237 u32 base_role = vcpu->arch.mmu->mmu_role.base.word;
5238
5167 entry = *spte; 5239 entry = *spte;
5168 mmu_page_zap_pte(vcpu->kvm, sp, spte); 5240 mmu_page_zap_pte(vcpu->kvm, sp, spte);
5169 if (gentry && 5241 if (gentry &&
5170 !((sp->role.word ^ vcpu->arch.mmu.base_role.word) 5242 !((sp->role.word ^ base_role)
5171 & mmu_base_role_mask.word) && rmap_can_add(vcpu)) 5243 & mmu_base_role_mask.word) && rmap_can_add(vcpu))
5172 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry); 5244 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5173 if (need_remote_flush(entry, *spte)) 5245 if (need_remote_flush(entry, *spte))
@@ -5185,7 +5257,7 @@ int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5185 gpa_t gpa; 5257 gpa_t gpa;
5186 int r; 5258 int r;
5187 5259
5188 if (vcpu->arch.mmu.direct_map) 5260 if (vcpu->arch.mmu->direct_map)
5189 return 0; 5261 return 0;
5190 5262
5191 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL); 5263 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
@@ -5221,10 +5293,10 @@ int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u64 error_code,
5221{ 5293{
5222 int r, emulation_type = 0; 5294 int r, emulation_type = 0;
5223 enum emulation_result er; 5295 enum emulation_result er;
5224 bool direct = vcpu->arch.mmu.direct_map; 5296 bool direct = vcpu->arch.mmu->direct_map;
5225 5297
5226 /* With shadow page tables, fault_address contains a GVA or nGPA. */ 5298 /* With shadow page tables, fault_address contains a GVA or nGPA. */
5227 if (vcpu->arch.mmu.direct_map) { 5299 if (vcpu->arch.mmu->direct_map) {
5228 vcpu->arch.gpa_available = true; 5300 vcpu->arch.gpa_available = true;
5229 vcpu->arch.gpa_val = cr2; 5301 vcpu->arch.gpa_val = cr2;
5230 } 5302 }
@@ -5237,8 +5309,9 @@ int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u64 error_code,
5237 } 5309 }
5238 5310
5239 if (r == RET_PF_INVALID) { 5311 if (r == RET_PF_INVALID) {
5240 r = vcpu->arch.mmu.page_fault(vcpu, cr2, lower_32_bits(error_code), 5312 r = vcpu->arch.mmu->page_fault(vcpu, cr2,
5241 false); 5313 lower_32_bits(error_code),
5314 false);
5242 WARN_ON(r == RET_PF_INVALID); 5315 WARN_ON(r == RET_PF_INVALID);
5243 } 5316 }
5244 5317
@@ -5254,7 +5327,7 @@ int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u64 error_code,
5254 * paging in both guests. If true, we simply unprotect the page 5327 * paging in both guests. If true, we simply unprotect the page
5255 * and resume the guest. 5328 * and resume the guest.
5256 */ 5329 */
5257 if (vcpu->arch.mmu.direct_map && 5330 if (vcpu->arch.mmu->direct_map &&
5258 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) { 5331 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5259 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2)); 5332 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2));
5260 return 1; 5333 return 1;
@@ -5302,7 +5375,7 @@ EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5302 5375
5303void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva) 5376void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5304{ 5377{
5305 struct kvm_mmu *mmu = &vcpu->arch.mmu; 5378 struct kvm_mmu *mmu = vcpu->arch.mmu;
5306 int i; 5379 int i;
5307 5380
5308 /* INVLPG on a * non-canonical address is a NOP according to the SDM. */ 5381 /* INVLPG on a * non-canonical address is a NOP according to the SDM. */
@@ -5333,7 +5406,7 @@ EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5333 5406
5334void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid) 5407void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5335{ 5408{
5336 struct kvm_mmu *mmu = &vcpu->arch.mmu; 5409 struct kvm_mmu *mmu = vcpu->arch.mmu;
5337 bool tlb_flush = false; 5410 bool tlb_flush = false;
5338 uint i; 5411 uint i;
5339 5412
@@ -5377,8 +5450,8 @@ EXPORT_SYMBOL_GPL(kvm_disable_tdp);
5377 5450
5378static void free_mmu_pages(struct kvm_vcpu *vcpu) 5451static void free_mmu_pages(struct kvm_vcpu *vcpu)
5379{ 5452{
5380 free_page((unsigned long)vcpu->arch.mmu.pae_root); 5453 free_page((unsigned long)vcpu->arch.mmu->pae_root);
5381 free_page((unsigned long)vcpu->arch.mmu.lm_root); 5454 free_page((unsigned long)vcpu->arch.mmu->lm_root);
5382} 5455}
5383 5456
5384static int alloc_mmu_pages(struct kvm_vcpu *vcpu) 5457static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
@@ -5398,9 +5471,9 @@ static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
5398 if (!page) 5471 if (!page)
5399 return -ENOMEM; 5472 return -ENOMEM;
5400 5473
5401 vcpu->arch.mmu.pae_root = page_address(page); 5474 vcpu->arch.mmu->pae_root = page_address(page);
5402 for (i = 0; i < 4; ++i) 5475 for (i = 0; i < 4; ++i)
5403 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE; 5476 vcpu->arch.mmu->pae_root[i] = INVALID_PAGE;
5404 5477
5405 return 0; 5478 return 0;
5406} 5479}
@@ -5409,27 +5482,21 @@ int kvm_mmu_create(struct kvm_vcpu *vcpu)
5409{ 5482{
5410 uint i; 5483 uint i;
5411 5484
5412 vcpu->arch.walk_mmu = &vcpu->arch.mmu; 5485 vcpu->arch.mmu = &vcpu->arch.root_mmu;
5413 vcpu->arch.mmu.root_hpa = INVALID_PAGE; 5486 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5414 vcpu->arch.mmu.translate_gpa = translate_gpa;
5415 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5416 5487
5488 vcpu->arch.root_mmu.root_hpa = INVALID_PAGE;
5489 vcpu->arch.root_mmu.translate_gpa = translate_gpa;
5417 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) 5490 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5418 vcpu->arch.mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID; 5491 vcpu->arch.root_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5419
5420 return alloc_mmu_pages(vcpu);
5421}
5422 5492
5423void kvm_mmu_setup(struct kvm_vcpu *vcpu) 5493 vcpu->arch.guest_mmu.root_hpa = INVALID_PAGE;
5424{ 5494 vcpu->arch.guest_mmu.translate_gpa = translate_gpa;
5425 MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa)); 5495 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5496 vcpu->arch.guest_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5426 5497
5427 /* 5498 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5428 * kvm_mmu_setup() is called only on vCPU initialization. 5499 return alloc_mmu_pages(vcpu);
5429 * Therefore, no need to reset mmu roots as they are not yet
5430 * initialized.
5431 */
5432 kvm_init_mmu(vcpu, false);
5433} 5500}
5434 5501
5435static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm, 5502static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
@@ -5612,7 +5679,7 @@ restart:
5612 if (sp->role.direct && 5679 if (sp->role.direct &&
5613 !kvm_is_reserved_pfn(pfn) && 5680 !kvm_is_reserved_pfn(pfn) &&
5614 PageTransCompoundMap(pfn_to_page(pfn))) { 5681 PageTransCompoundMap(pfn_to_page(pfn))) {
5615 drop_spte(kvm, sptep); 5682 pte_list_remove(rmap_head, sptep);
5616 need_tlb_flush = 1; 5683 need_tlb_flush = 1;
5617 goto restart; 5684 goto restart;
5618 } 5685 }
@@ -5869,6 +5936,16 @@ int kvm_mmu_module_init(void)
5869{ 5936{
5870 int ret = -ENOMEM; 5937 int ret = -ENOMEM;
5871 5938
5939 /*
5940 * MMU roles use union aliasing which is, generally speaking, an
5941 * undefined behavior. However, we supposedly know how compilers behave
5942 * and the current status quo is unlikely to change. Guardians below are
5943 * supposed to let us know if the assumption becomes false.
5944 */
5945 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
5946 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
5947 BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
5948
5872 kvm_mmu_reset_all_pte_masks(); 5949 kvm_mmu_reset_all_pte_masks();
5873 5950
5874 pte_list_desc_cache = kmem_cache_create("pte_list_desc", 5951 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
@@ -5898,7 +5975,7 @@ out:
5898} 5975}
5899 5976
5900/* 5977/*
5901 * Caculate mmu pages needed for kvm. 5978 * Calculate mmu pages needed for kvm.
5902 */ 5979 */
5903unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm) 5980unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
5904{ 5981{
diff --git a/arch/x86/kvm/mmu.h b/arch/x86/kvm/mmu.h
index 1fab69c0b2f3..c7b333147c4a 100644
--- a/arch/x86/kvm/mmu.h
+++ b/arch/x86/kvm/mmu.h
@@ -43,11 +43,6 @@
43#define PT32_ROOT_LEVEL 2 43#define PT32_ROOT_LEVEL 2
44#define PT32E_ROOT_LEVEL 3 44#define PT32E_ROOT_LEVEL 3
45 45
46#define PT_PDPE_LEVEL 3
47#define PT_DIRECTORY_LEVEL 2
48#define PT_PAGE_TABLE_LEVEL 1
49#define PT_MAX_HUGEPAGE_LEVEL (PT_PAGE_TABLE_LEVEL + KVM_NR_PAGE_SIZES - 1)
50
51static inline u64 rsvd_bits(int s, int e) 46static inline u64 rsvd_bits(int s, int e)
52{ 47{
53 if (e < s) 48 if (e < s)
@@ -80,7 +75,7 @@ static inline unsigned int kvm_mmu_available_pages(struct kvm *kvm)
80 75
81static inline int kvm_mmu_reload(struct kvm_vcpu *vcpu) 76static inline int kvm_mmu_reload(struct kvm_vcpu *vcpu)
82{ 77{
83 if (likely(vcpu->arch.mmu.root_hpa != INVALID_PAGE)) 78 if (likely(vcpu->arch.mmu->root_hpa != INVALID_PAGE))
84 return 0; 79 return 0;
85 80
86 return kvm_mmu_load(vcpu); 81 return kvm_mmu_load(vcpu);
@@ -102,9 +97,9 @@ static inline unsigned long kvm_get_active_pcid(struct kvm_vcpu *vcpu)
102 97
103static inline void kvm_mmu_load_cr3(struct kvm_vcpu *vcpu) 98static inline void kvm_mmu_load_cr3(struct kvm_vcpu *vcpu)
104{ 99{
105 if (VALID_PAGE(vcpu->arch.mmu.root_hpa)) 100 if (VALID_PAGE(vcpu->arch.mmu->root_hpa))
106 vcpu->arch.mmu.set_cr3(vcpu, vcpu->arch.mmu.root_hpa | 101 vcpu->arch.mmu->set_cr3(vcpu, vcpu->arch.mmu->root_hpa |
107 kvm_get_active_pcid(vcpu)); 102 kvm_get_active_pcid(vcpu));
108} 103}
109 104
110/* 105/*
diff --git a/arch/x86/kvm/mmu_audit.c b/arch/x86/kvm/mmu_audit.c
index 1272861e77b9..abac7e208853 100644
--- a/arch/x86/kvm/mmu_audit.c
+++ b/arch/x86/kvm/mmu_audit.c
@@ -59,19 +59,19 @@ static void mmu_spte_walk(struct kvm_vcpu *vcpu, inspect_spte_fn fn)
59 int i; 59 int i;
60 struct kvm_mmu_page *sp; 60 struct kvm_mmu_page *sp;
61 61
62 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa)) 62 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
63 return; 63 return;
64 64
65 if (vcpu->arch.mmu.root_level >= PT64_ROOT_4LEVEL) { 65 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
66 hpa_t root = vcpu->arch.mmu.root_hpa; 66 hpa_t root = vcpu->arch.mmu->root_hpa;
67 67
68 sp = page_header(root); 68 sp = page_header(root);
69 __mmu_spte_walk(vcpu, sp, fn, vcpu->arch.mmu.root_level); 69 __mmu_spte_walk(vcpu, sp, fn, vcpu->arch.mmu->root_level);
70 return; 70 return;
71 } 71 }
72 72
73 for (i = 0; i < 4; ++i) { 73 for (i = 0; i < 4; ++i) {
74 hpa_t root = vcpu->arch.mmu.pae_root[i]; 74 hpa_t root = vcpu->arch.mmu->pae_root[i];
75 75
76 if (root && VALID_PAGE(root)) { 76 if (root && VALID_PAGE(root)) {
77 root &= PT64_BASE_ADDR_MASK; 77 root &= PT64_BASE_ADDR_MASK;
@@ -122,7 +122,7 @@ static void audit_mappings(struct kvm_vcpu *vcpu, u64 *sptep, int level)
122 hpa = pfn << PAGE_SHIFT; 122 hpa = pfn << PAGE_SHIFT;
123 if ((*sptep & PT64_BASE_ADDR_MASK) != hpa) 123 if ((*sptep & PT64_BASE_ADDR_MASK) != hpa)
124 audit_printk(vcpu->kvm, "levels %d pfn %llx hpa %llx " 124 audit_printk(vcpu->kvm, "levels %d pfn %llx hpa %llx "
125 "ent %llxn", vcpu->arch.mmu.root_level, pfn, 125 "ent %llxn", vcpu->arch.mmu->root_level, pfn,
126 hpa, *sptep); 126 hpa, *sptep);
127} 127}
128 128
diff --git a/arch/x86/kvm/paging_tmpl.h b/arch/x86/kvm/paging_tmpl.h
index 14ffd973df54..7cf2185b7eb5 100644
--- a/arch/x86/kvm/paging_tmpl.h
+++ b/arch/x86/kvm/paging_tmpl.h
@@ -158,14 +158,15 @@ static bool FNAME(prefetch_invalid_gpte)(struct kvm_vcpu *vcpu,
158 struct kvm_mmu_page *sp, u64 *spte, 158 struct kvm_mmu_page *sp, u64 *spte,
159 u64 gpte) 159 u64 gpte)
160{ 160{
161 if (is_rsvd_bits_set(&vcpu->arch.mmu, gpte, PT_PAGE_TABLE_LEVEL)) 161 if (is_rsvd_bits_set(vcpu->arch.mmu, gpte, PT_PAGE_TABLE_LEVEL))
162 goto no_present; 162 goto no_present;
163 163
164 if (!FNAME(is_present_gpte)(gpte)) 164 if (!FNAME(is_present_gpte)(gpte))
165 goto no_present; 165 goto no_present;
166 166
167 /* if accessed bit is not supported prefetch non accessed gpte */ 167 /* if accessed bit is not supported prefetch non accessed gpte */
168 if (PT_HAVE_ACCESSED_DIRTY(&vcpu->arch.mmu) && !(gpte & PT_GUEST_ACCESSED_MASK)) 168 if (PT_HAVE_ACCESSED_DIRTY(vcpu->arch.mmu) &&
169 !(gpte & PT_GUEST_ACCESSED_MASK))
169 goto no_present; 170 goto no_present;
170 171
171 return false; 172 return false;
@@ -480,7 +481,7 @@ error:
480static int FNAME(walk_addr)(struct guest_walker *walker, 481static int FNAME(walk_addr)(struct guest_walker *walker,
481 struct kvm_vcpu *vcpu, gva_t addr, u32 access) 482 struct kvm_vcpu *vcpu, gva_t addr, u32 access)
482{ 483{
483 return FNAME(walk_addr_generic)(walker, vcpu, &vcpu->arch.mmu, addr, 484 return FNAME(walk_addr_generic)(walker, vcpu, vcpu->arch.mmu, addr,
484 access); 485 access);
485} 486}
486 487
@@ -509,7 +510,7 @@ FNAME(prefetch_gpte)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
509 510
510 gfn = gpte_to_gfn(gpte); 511 gfn = gpte_to_gfn(gpte);
511 pte_access = sp->role.access & FNAME(gpte_access)(gpte); 512 pte_access = sp->role.access & FNAME(gpte_access)(gpte);
512 FNAME(protect_clean_gpte)(&vcpu->arch.mmu, &pte_access, gpte); 513 FNAME(protect_clean_gpte)(vcpu->arch.mmu, &pte_access, gpte);
513 pfn = pte_prefetch_gfn_to_pfn(vcpu, gfn, 514 pfn = pte_prefetch_gfn_to_pfn(vcpu, gfn,
514 no_dirty_log && (pte_access & ACC_WRITE_MASK)); 515 no_dirty_log && (pte_access & ACC_WRITE_MASK));
515 if (is_error_pfn(pfn)) 516 if (is_error_pfn(pfn))
@@ -604,7 +605,7 @@ static int FNAME(fetch)(struct kvm_vcpu *vcpu, gva_t addr,
604 605
605 direct_access = gw->pte_access; 606 direct_access = gw->pte_access;
606 607
607 top_level = vcpu->arch.mmu.root_level; 608 top_level = vcpu->arch.mmu->root_level;
608 if (top_level == PT32E_ROOT_LEVEL) 609 if (top_level == PT32E_ROOT_LEVEL)
609 top_level = PT32_ROOT_LEVEL; 610 top_level = PT32_ROOT_LEVEL;
610 /* 611 /*
@@ -616,7 +617,7 @@ static int FNAME(fetch)(struct kvm_vcpu *vcpu, gva_t addr,
616 if (FNAME(gpte_changed)(vcpu, gw, top_level)) 617 if (FNAME(gpte_changed)(vcpu, gw, top_level))
617 goto out_gpte_changed; 618 goto out_gpte_changed;
618 619
619 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa)) 620 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
620 goto out_gpte_changed; 621 goto out_gpte_changed;
621 622
622 for (shadow_walk_init(&it, vcpu, addr); 623 for (shadow_walk_init(&it, vcpu, addr);
@@ -1004,7 +1005,7 @@ static int FNAME(sync_page)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1004 gfn = gpte_to_gfn(gpte); 1005 gfn = gpte_to_gfn(gpte);
1005 pte_access = sp->role.access; 1006 pte_access = sp->role.access;
1006 pte_access &= FNAME(gpte_access)(gpte); 1007 pte_access &= FNAME(gpte_access)(gpte);
1007 FNAME(protect_clean_gpte)(&vcpu->arch.mmu, &pte_access, gpte); 1008 FNAME(protect_clean_gpte)(vcpu->arch.mmu, &pte_access, gpte);
1008 1009
1009 if (sync_mmio_spte(vcpu, &sp->spt[i], gfn, pte_access, 1010 if (sync_mmio_spte(vcpu, &sp->spt[i], gfn, pte_access,
1010 &nr_present)) 1011 &nr_present))
diff --git a/arch/x86/kvm/svm.c b/arch/x86/kvm/svm.c
index 61ccfb13899e..0e21ccc46792 100644
--- a/arch/x86/kvm/svm.c
+++ b/arch/x86/kvm/svm.c
@@ -809,6 +809,8 @@ static void svm_queue_exception(struct kvm_vcpu *vcpu)
809 nested_svm_check_exception(svm, nr, has_error_code, error_code)) 809 nested_svm_check_exception(svm, nr, has_error_code, error_code))
810 return; 810 return;
811 811
812 kvm_deliver_exception_payload(&svm->vcpu);
813
812 if (nr == BP_VECTOR && !static_cpu_has(X86_FEATURE_NRIPS)) { 814 if (nr == BP_VECTOR && !static_cpu_has(X86_FEATURE_NRIPS)) {
813 unsigned long rip, old_rip = kvm_rip_read(&svm->vcpu); 815 unsigned long rip, old_rip = kvm_rip_read(&svm->vcpu);
814 816
@@ -2922,18 +2924,18 @@ static void nested_svm_init_mmu_context(struct kvm_vcpu *vcpu)
2922{ 2924{
2923 WARN_ON(mmu_is_nested(vcpu)); 2925 WARN_ON(mmu_is_nested(vcpu));
2924 kvm_init_shadow_mmu(vcpu); 2926 kvm_init_shadow_mmu(vcpu);
2925 vcpu->arch.mmu.set_cr3 = nested_svm_set_tdp_cr3; 2927 vcpu->arch.mmu->set_cr3 = nested_svm_set_tdp_cr3;
2926 vcpu->arch.mmu.get_cr3 = nested_svm_get_tdp_cr3; 2928 vcpu->arch.mmu->get_cr3 = nested_svm_get_tdp_cr3;
2927 vcpu->arch.mmu.get_pdptr = nested_svm_get_tdp_pdptr; 2929 vcpu->arch.mmu->get_pdptr = nested_svm_get_tdp_pdptr;
2928 vcpu->arch.mmu.inject_page_fault = nested_svm_inject_npf_exit; 2930 vcpu->arch.mmu->inject_page_fault = nested_svm_inject_npf_exit;
2929 vcpu->arch.mmu.shadow_root_level = get_npt_level(vcpu); 2931 vcpu->arch.mmu->shadow_root_level = get_npt_level(vcpu);
2930 reset_shadow_zero_bits_mask(vcpu, &vcpu->arch.mmu); 2932 reset_shadow_zero_bits_mask(vcpu, vcpu->arch.mmu);
2931 vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu; 2933 vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
2932} 2934}
2933 2935
2934static void nested_svm_uninit_mmu_context(struct kvm_vcpu *vcpu) 2936static void nested_svm_uninit_mmu_context(struct kvm_vcpu *vcpu)
2935{ 2937{
2936 vcpu->arch.walk_mmu = &vcpu->arch.mmu; 2938 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
2937} 2939}
2938 2940
2939static int nested_svm_check_permissions(struct vcpu_svm *svm) 2941static int nested_svm_check_permissions(struct vcpu_svm *svm)
@@ -2969,16 +2971,13 @@ static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
2969 svm->vmcb->control.exit_info_1 = error_code; 2971 svm->vmcb->control.exit_info_1 = error_code;
2970 2972
2971 /* 2973 /*
2972 * FIXME: we should not write CR2 when L1 intercepts an L2 #PF exception. 2974 * EXITINFO2 is undefined for all exception intercepts other
2973 * The fix is to add the ancillary datum (CR2 or DR6) to structs 2975 * than #PF.
2974 * kvm_queued_exception and kvm_vcpu_events, so that CR2 and DR6 can be
2975 * written only when inject_pending_event runs (DR6 would written here
2976 * too). This should be conditional on a new capability---if the
2977 * capability is disabled, kvm_multiple_exception would write the
2978 * ancillary information to CR2 or DR6, for backwards ABI-compatibility.
2979 */ 2976 */
2980 if (svm->vcpu.arch.exception.nested_apf) 2977 if (svm->vcpu.arch.exception.nested_apf)
2981 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.apf.nested_apf_token; 2978 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.apf.nested_apf_token;
2979 else if (svm->vcpu.arch.exception.has_payload)
2980 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.exception.payload;
2982 else 2981 else
2983 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.cr2; 2982 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.cr2;
2984 2983
@@ -5642,26 +5641,24 @@ static void svm_vcpu_run(struct kvm_vcpu *vcpu)
5642 "mov %%r13, %c[r13](%[svm]) \n\t" 5641 "mov %%r13, %c[r13](%[svm]) \n\t"
5643 "mov %%r14, %c[r14](%[svm]) \n\t" 5642 "mov %%r14, %c[r14](%[svm]) \n\t"
5644 "mov %%r15, %c[r15](%[svm]) \n\t" 5643 "mov %%r15, %c[r15](%[svm]) \n\t"
5645#endif
5646 /* 5644 /*
5647 * Clear host registers marked as clobbered to prevent 5645 * Clear host registers marked as clobbered to prevent
5648 * speculative use. 5646 * speculative use.
5649 */ 5647 */
5650 "xor %%" _ASM_BX ", %%" _ASM_BX " \n\t" 5648 "xor %%r8d, %%r8d \n\t"
5651 "xor %%" _ASM_CX ", %%" _ASM_CX " \n\t" 5649 "xor %%r9d, %%r9d \n\t"
5652 "xor %%" _ASM_DX ", %%" _ASM_DX " \n\t" 5650 "xor %%r10d, %%r10d \n\t"
5653 "xor %%" _ASM_SI ", %%" _ASM_SI " \n\t" 5651 "xor %%r11d, %%r11d \n\t"
5654 "xor %%" _ASM_DI ", %%" _ASM_DI " \n\t" 5652 "xor %%r12d, %%r12d \n\t"
5655#ifdef CONFIG_X86_64 5653 "xor %%r13d, %%r13d \n\t"
5656 "xor %%r8, %%r8 \n\t" 5654 "xor %%r14d, %%r14d \n\t"
5657 "xor %%r9, %%r9 \n\t" 5655 "xor %%r15d, %%r15d \n\t"
5658 "xor %%r10, %%r10 \n\t"
5659 "xor %%r11, %%r11 \n\t"
5660 "xor %%r12, %%r12 \n\t"
5661 "xor %%r13, %%r13 \n\t"
5662 "xor %%r14, %%r14 \n\t"
5663 "xor %%r15, %%r15 \n\t"
5664#endif 5656#endif
5657 "xor %%ebx, %%ebx \n\t"
5658 "xor %%ecx, %%ecx \n\t"
5659 "xor %%edx, %%edx \n\t"
5660 "xor %%esi, %%esi \n\t"
5661 "xor %%edi, %%edi \n\t"
5665 "pop %%" _ASM_BP 5662 "pop %%" _ASM_BP
5666 : 5663 :
5667 : [svm]"a"(svm), 5664 : [svm]"a"(svm),
@@ -7040,6 +7037,13 @@ failed:
7040 return ret; 7037 return ret;
7041} 7038}
7042 7039
7040static int nested_enable_evmcs(struct kvm_vcpu *vcpu,
7041 uint16_t *vmcs_version)
7042{
7043 /* Intel-only feature */
7044 return -ENODEV;
7045}
7046
7043static struct kvm_x86_ops svm_x86_ops __ro_after_init = { 7047static struct kvm_x86_ops svm_x86_ops __ro_after_init = {
7044 .cpu_has_kvm_support = has_svm, 7048 .cpu_has_kvm_support = has_svm,
7045 .disabled_by_bios = is_disabled, 7049 .disabled_by_bios = is_disabled,
@@ -7169,6 +7173,8 @@ static struct kvm_x86_ops svm_x86_ops __ro_after_init = {
7169 .mem_enc_op = svm_mem_enc_op, 7173 .mem_enc_op = svm_mem_enc_op,
7170 .mem_enc_reg_region = svm_register_enc_region, 7174 .mem_enc_reg_region = svm_register_enc_region,
7171 .mem_enc_unreg_region = svm_unregister_enc_region, 7175 .mem_enc_unreg_region = svm_unregister_enc_region,
7176
7177 .nested_enable_evmcs = nested_enable_evmcs,
7172}; 7178};
7173 7179
7174static int __init svm_init(void) 7180static int __init svm_init(void)
diff --git a/arch/x86/kvm/trace.h b/arch/x86/kvm/trace.h
index 0f997683404f..0659465a745c 100644
--- a/arch/x86/kvm/trace.h
+++ b/arch/x86/kvm/trace.h
@@ -1418,6 +1418,48 @@ TRACE_EVENT(kvm_hv_flush_tlb_ex,
1418 __entry->valid_bank_mask, __entry->format, 1418 __entry->valid_bank_mask, __entry->format,
1419 __entry->address_space, __entry->flags) 1419 __entry->address_space, __entry->flags)
1420); 1420);
1421
1422/*
1423 * Tracepoints for kvm_hv_send_ipi.
1424 */
1425TRACE_EVENT(kvm_hv_send_ipi,
1426 TP_PROTO(u32 vector, u64 processor_mask),
1427 TP_ARGS(vector, processor_mask),
1428
1429 TP_STRUCT__entry(
1430 __field(u32, vector)
1431 __field(u64, processor_mask)
1432 ),
1433
1434 TP_fast_assign(
1435 __entry->vector = vector;
1436 __entry->processor_mask = processor_mask;
1437 ),
1438
1439 TP_printk("vector %x processor_mask 0x%llx",
1440 __entry->vector, __entry->processor_mask)
1441);
1442
1443TRACE_EVENT(kvm_hv_send_ipi_ex,
1444 TP_PROTO(u32 vector, u64 format, u64 valid_bank_mask),
1445 TP_ARGS(vector, format, valid_bank_mask),
1446
1447 TP_STRUCT__entry(
1448 __field(u32, vector)
1449 __field(u64, format)
1450 __field(u64, valid_bank_mask)
1451 ),
1452
1453 TP_fast_assign(
1454 __entry->vector = vector;
1455 __entry->format = format;
1456 __entry->valid_bank_mask = valid_bank_mask;
1457 ),
1458
1459 TP_printk("vector %x format %llx valid_bank_mask 0x%llx",
1460 __entry->vector, __entry->format,
1461 __entry->valid_bank_mask)
1462);
1421#endif /* _TRACE_KVM_H */ 1463#endif /* _TRACE_KVM_H */
1422 1464
1423#undef TRACE_INCLUDE_PATH 1465#undef TRACE_INCLUDE_PATH
diff --git a/arch/x86/kvm/vmx.c b/arch/x86/kvm/vmx.c
index e665aa7167cf..4555077d69ce 100644
--- a/arch/x86/kvm/vmx.c
+++ b/arch/x86/kvm/vmx.c
@@ -20,6 +20,7 @@
20#include "mmu.h" 20#include "mmu.h"
21#include "cpuid.h" 21#include "cpuid.h"
22#include "lapic.h" 22#include "lapic.h"
23#include "hyperv.h"
23 24
24#include <linux/kvm_host.h> 25#include <linux/kvm_host.h>
25#include <linux/module.h> 26#include <linux/module.h>
@@ -61,7 +62,7 @@
61 62
62#define __ex(x) __kvm_handle_fault_on_reboot(x) 63#define __ex(x) __kvm_handle_fault_on_reboot(x)
63#define __ex_clear(x, reg) \ 64#define __ex_clear(x, reg) \
64 ____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg) 65 ____kvm_handle_fault_on_reboot(x, "xor " reg ", " reg)
65 66
66MODULE_AUTHOR("Qumranet"); 67MODULE_AUTHOR("Qumranet");
67MODULE_LICENSE("GPL"); 68MODULE_LICENSE("GPL");
@@ -107,9 +108,12 @@ module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
107 * VMX and be a hypervisor for its own guests. If nested=0, guests may not 108 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
108 * use VMX instructions. 109 * use VMX instructions.
109 */ 110 */
110static bool __read_mostly nested = 0; 111static bool __read_mostly nested = 1;
111module_param(nested, bool, S_IRUGO); 112module_param(nested, bool, S_IRUGO);
112 113
114static bool __read_mostly nested_early_check = 0;
115module_param(nested_early_check, bool, S_IRUGO);
116
113static u64 __read_mostly host_xss; 117static u64 __read_mostly host_xss;
114 118
115static bool __read_mostly enable_pml = 1; 119static bool __read_mostly enable_pml = 1;
@@ -131,7 +135,7 @@ static bool __read_mostly enable_preemption_timer = 1;
131module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO); 135module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
132#endif 136#endif
133 137
134#define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD) 138#define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
135#define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE 139#define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
136#define KVM_VM_CR0_ALWAYS_ON \ 140#define KVM_VM_CR0_ALWAYS_ON \
137 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | \ 141 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | \
@@ -187,6 +191,7 @@ static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
187module_param(ple_window_max, uint, 0444); 191module_param(ple_window_max, uint, 0444);
188 192
189extern const ulong vmx_return; 193extern const ulong vmx_return;
194extern const ulong vmx_early_consistency_check_return;
190 195
191static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush); 196static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
192static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond); 197static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
@@ -827,14 +832,28 @@ struct nested_vmx {
827 */ 832 */
828 struct vmcs12 *cached_shadow_vmcs12; 833 struct vmcs12 *cached_shadow_vmcs12;
829 /* 834 /*
830 * Indicates if the shadow vmcs must be updated with the 835 * Indicates if the shadow vmcs or enlightened vmcs must be updated
831 * data hold by vmcs12 836 * with the data held by struct vmcs12.
832 */ 837 */
833 bool sync_shadow_vmcs; 838 bool need_vmcs12_sync;
834 bool dirty_vmcs12; 839 bool dirty_vmcs12;
835 840
841 /*
842 * vmcs02 has been initialized, i.e. state that is constant for
843 * vmcs02 has been written to the backing VMCS. Initialization
844 * is delayed until L1 actually attempts to run a nested VM.
845 */
846 bool vmcs02_initialized;
847
836 bool change_vmcs01_virtual_apic_mode; 848 bool change_vmcs01_virtual_apic_mode;
837 849
850 /*
851 * Enlightened VMCS has been enabled. It does not mean that L1 has to
852 * use it. However, VMX features available to L1 will be limited based
853 * on what the enlightened VMCS supports.
854 */
855 bool enlightened_vmcs_enabled;
856
838 /* L2 must run next, and mustn't decide to exit to L1. */ 857 /* L2 must run next, and mustn't decide to exit to L1. */
839 bool nested_run_pending; 858 bool nested_run_pending;
840 859
@@ -870,6 +889,10 @@ struct nested_vmx {
870 /* in guest mode on SMM entry? */ 889 /* in guest mode on SMM entry? */
871 bool guest_mode; 890 bool guest_mode;
872 } smm; 891 } smm;
892
893 gpa_t hv_evmcs_vmptr;
894 struct page *hv_evmcs_page;
895 struct hv_enlightened_vmcs *hv_evmcs;
873}; 896};
874 897
875#define POSTED_INTR_ON 0 898#define POSTED_INTR_ON 0
@@ -1381,6 +1404,49 @@ DEFINE_STATIC_KEY_FALSE(enable_evmcs);
1381 1404
1382#define KVM_EVMCS_VERSION 1 1405#define KVM_EVMCS_VERSION 1
1383 1406
1407/*
1408 * Enlightened VMCSv1 doesn't support these:
1409 *
1410 * POSTED_INTR_NV = 0x00000002,
1411 * GUEST_INTR_STATUS = 0x00000810,
1412 * APIC_ACCESS_ADDR = 0x00002014,
1413 * POSTED_INTR_DESC_ADDR = 0x00002016,
1414 * EOI_EXIT_BITMAP0 = 0x0000201c,
1415 * EOI_EXIT_BITMAP1 = 0x0000201e,
1416 * EOI_EXIT_BITMAP2 = 0x00002020,
1417 * EOI_EXIT_BITMAP3 = 0x00002022,
1418 * GUEST_PML_INDEX = 0x00000812,
1419 * PML_ADDRESS = 0x0000200e,
1420 * VM_FUNCTION_CONTROL = 0x00002018,
1421 * EPTP_LIST_ADDRESS = 0x00002024,
1422 * VMREAD_BITMAP = 0x00002026,
1423 * VMWRITE_BITMAP = 0x00002028,
1424 *
1425 * TSC_MULTIPLIER = 0x00002032,
1426 * PLE_GAP = 0x00004020,
1427 * PLE_WINDOW = 0x00004022,
1428 * VMX_PREEMPTION_TIMER_VALUE = 0x0000482E,
1429 * GUEST_IA32_PERF_GLOBAL_CTRL = 0x00002808,
1430 * HOST_IA32_PERF_GLOBAL_CTRL = 0x00002c04,
1431 *
1432 * Currently unsupported in KVM:
1433 * GUEST_IA32_RTIT_CTL = 0x00002814,
1434 */
1435#define EVMCS1_UNSUPPORTED_PINCTRL (PIN_BASED_POSTED_INTR | \
1436 PIN_BASED_VMX_PREEMPTION_TIMER)
1437#define EVMCS1_UNSUPPORTED_2NDEXEC \
1438 (SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY | \
1439 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES | \
1440 SECONDARY_EXEC_APIC_REGISTER_VIRT | \
1441 SECONDARY_EXEC_ENABLE_PML | \
1442 SECONDARY_EXEC_ENABLE_VMFUNC | \
1443 SECONDARY_EXEC_SHADOW_VMCS | \
1444 SECONDARY_EXEC_TSC_SCALING | \
1445 SECONDARY_EXEC_PAUSE_LOOP_EXITING)
1446#define EVMCS1_UNSUPPORTED_VMEXIT_CTRL (VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
1447#define EVMCS1_UNSUPPORTED_VMENTRY_CTRL (VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
1448#define EVMCS1_UNSUPPORTED_VMFUNC (VMX_VMFUNC_EPTP_SWITCHING)
1449
1384#if IS_ENABLED(CONFIG_HYPERV) 1450#if IS_ENABLED(CONFIG_HYPERV)
1385static bool __read_mostly enlightened_vmcs = true; 1451static bool __read_mostly enlightened_vmcs = true;
1386module_param(enlightened_vmcs, bool, 0444); 1452module_param(enlightened_vmcs, bool, 0444);
@@ -1473,69 +1539,12 @@ static void evmcs_load(u64 phys_addr)
1473 1539
1474static void evmcs_sanitize_exec_ctrls(struct vmcs_config *vmcs_conf) 1540static void evmcs_sanitize_exec_ctrls(struct vmcs_config *vmcs_conf)
1475{ 1541{
1476 /* 1542 vmcs_conf->pin_based_exec_ctrl &= ~EVMCS1_UNSUPPORTED_PINCTRL;
1477 * Enlightened VMCSv1 doesn't support these: 1543 vmcs_conf->cpu_based_2nd_exec_ctrl &= ~EVMCS1_UNSUPPORTED_2NDEXEC;
1478 *
1479 * POSTED_INTR_NV = 0x00000002,
1480 * GUEST_INTR_STATUS = 0x00000810,
1481 * APIC_ACCESS_ADDR = 0x00002014,
1482 * POSTED_INTR_DESC_ADDR = 0x00002016,
1483 * EOI_EXIT_BITMAP0 = 0x0000201c,
1484 * EOI_EXIT_BITMAP1 = 0x0000201e,
1485 * EOI_EXIT_BITMAP2 = 0x00002020,
1486 * EOI_EXIT_BITMAP3 = 0x00002022,
1487 */
1488 vmcs_conf->pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
1489 vmcs_conf->cpu_based_2nd_exec_ctrl &=
1490 ~SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
1491 vmcs_conf->cpu_based_2nd_exec_ctrl &=
1492 ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1493 vmcs_conf->cpu_based_2nd_exec_ctrl &=
1494 ~SECONDARY_EXEC_APIC_REGISTER_VIRT;
1495
1496 /*
1497 * GUEST_PML_INDEX = 0x00000812,
1498 * PML_ADDRESS = 0x0000200e,
1499 */
1500 vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_ENABLE_PML;
1501
1502 /* VM_FUNCTION_CONTROL = 0x00002018, */
1503 vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_ENABLE_VMFUNC;
1504
1505 /*
1506 * EPTP_LIST_ADDRESS = 0x00002024,
1507 * VMREAD_BITMAP = 0x00002026,
1508 * VMWRITE_BITMAP = 0x00002028,
1509 */
1510 vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_SHADOW_VMCS;
1511
1512 /*
1513 * TSC_MULTIPLIER = 0x00002032,
1514 */
1515 vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_TSC_SCALING;
1516 1544
1517 /* 1545 vmcs_conf->vmexit_ctrl &= ~EVMCS1_UNSUPPORTED_VMEXIT_CTRL;
1518 * PLE_GAP = 0x00004020, 1546 vmcs_conf->vmentry_ctrl &= ~EVMCS1_UNSUPPORTED_VMENTRY_CTRL;
1519 * PLE_WINDOW = 0x00004022,
1520 */
1521 vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1522
1523 /*
1524 * VMX_PREEMPTION_TIMER_VALUE = 0x0000482E,
1525 */
1526 vmcs_conf->pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
1527
1528 /*
1529 * GUEST_IA32_PERF_GLOBAL_CTRL = 0x00002808,
1530 * HOST_IA32_PERF_GLOBAL_CTRL = 0x00002c04,
1531 */
1532 vmcs_conf->vmexit_ctrl &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
1533 vmcs_conf->vmentry_ctrl &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
1534 1547
1535 /*
1536 * Currently unsupported in KVM:
1537 * GUEST_IA32_RTIT_CTL = 0x00002814,
1538 */
1539} 1548}
1540 1549
1541/* check_ept_pointer() should be under protection of ept_pointer_lock. */ 1550/* check_ept_pointer() should be under protection of ept_pointer_lock. */
@@ -1560,26 +1569,27 @@ static void check_ept_pointer_match(struct kvm *kvm)
1560 1569
1561static int vmx_hv_remote_flush_tlb(struct kvm *kvm) 1570static int vmx_hv_remote_flush_tlb(struct kvm *kvm)
1562{ 1571{
1563 int ret; 1572 struct kvm_vcpu *vcpu;
1573 int ret = -ENOTSUPP, i;
1564 1574
1565 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock); 1575 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
1566 1576
1567 if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK) 1577 if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK)
1568 check_ept_pointer_match(kvm); 1578 check_ept_pointer_match(kvm);
1569 1579
1570 if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
1571 ret = -ENOTSUPP;
1572 goto out;
1573 }
1574
1575 /* 1580 /*
1576 * FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE hypercall needs the address of the 1581 * FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE hypercall needs the address of the
1577 * base of EPT PML4 table, strip off EPT configuration information. 1582 * base of EPT PML4 table, strip off EPT configuration information.
1578 */ 1583 */
1579 ret = hyperv_flush_guest_mapping( 1584 if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
1580 to_vmx(kvm_get_vcpu(kvm, 0))->ept_pointer & PAGE_MASK); 1585 kvm_for_each_vcpu(i, vcpu, kvm)
1586 ret |= hyperv_flush_guest_mapping(
1587 to_vmx(kvm_get_vcpu(kvm, i))->ept_pointer & PAGE_MASK);
1588 } else {
1589 ret = hyperv_flush_guest_mapping(
1590 to_vmx(kvm_get_vcpu(kvm, 0))->ept_pointer & PAGE_MASK);
1591 }
1581 1592
1582out:
1583 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock); 1593 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
1584 return ret; 1594 return ret;
1585} 1595}
@@ -1595,6 +1605,35 @@ static inline void evmcs_sanitize_exec_ctrls(struct vmcs_config *vmcs_conf) {}
1595static inline void evmcs_touch_msr_bitmap(void) {} 1605static inline void evmcs_touch_msr_bitmap(void) {}
1596#endif /* IS_ENABLED(CONFIG_HYPERV) */ 1606#endif /* IS_ENABLED(CONFIG_HYPERV) */
1597 1607
1608static int nested_enable_evmcs(struct kvm_vcpu *vcpu,
1609 uint16_t *vmcs_version)
1610{
1611 struct vcpu_vmx *vmx = to_vmx(vcpu);
1612
1613 /* We don't support disabling the feature for simplicity. */
1614 if (vmx->nested.enlightened_vmcs_enabled)
1615 return 0;
1616
1617 vmx->nested.enlightened_vmcs_enabled = true;
1618
1619 /*
1620 * vmcs_version represents the range of supported Enlightened VMCS
1621 * versions: lower 8 bits is the minimal version, higher 8 bits is the
1622 * maximum supported version. KVM supports versions from 1 to
1623 * KVM_EVMCS_VERSION.
1624 */
1625 if (vmcs_version)
1626 *vmcs_version = (KVM_EVMCS_VERSION << 8) | 1;
1627
1628 vmx->nested.msrs.pinbased_ctls_high &= ~EVMCS1_UNSUPPORTED_PINCTRL;
1629 vmx->nested.msrs.entry_ctls_high &= ~EVMCS1_UNSUPPORTED_VMENTRY_CTRL;
1630 vmx->nested.msrs.exit_ctls_high &= ~EVMCS1_UNSUPPORTED_VMEXIT_CTRL;
1631 vmx->nested.msrs.secondary_ctls_high &= ~EVMCS1_UNSUPPORTED_2NDEXEC;
1632 vmx->nested.msrs.vmfunc_controls &= ~EVMCS1_UNSUPPORTED_VMFUNC;
1633
1634 return 0;
1635}
1636
1598static inline bool is_exception_n(u32 intr_info, u8 vector) 1637static inline bool is_exception_n(u32 intr_info, u8 vector)
1599{ 1638{
1600 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK | 1639 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
@@ -1617,11 +1656,6 @@ static inline bool is_page_fault(u32 intr_info)
1617 return is_exception_n(intr_info, PF_VECTOR); 1656 return is_exception_n(intr_info, PF_VECTOR);
1618} 1657}
1619 1658
1620static inline bool is_no_device(u32 intr_info)
1621{
1622 return is_exception_n(intr_info, NM_VECTOR);
1623}
1624
1625static inline bool is_invalid_opcode(u32 intr_info) 1659static inline bool is_invalid_opcode(u32 intr_info)
1626{ 1660{
1627 return is_exception_n(intr_info, UD_VECTOR); 1661 return is_exception_n(intr_info, UD_VECTOR);
@@ -1632,12 +1666,6 @@ static inline bool is_gp_fault(u32 intr_info)
1632 return is_exception_n(intr_info, GP_VECTOR); 1666 return is_exception_n(intr_info, GP_VECTOR);
1633} 1667}
1634 1668
1635static inline bool is_external_interrupt(u32 intr_info)
1636{
1637 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1638 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
1639}
1640
1641static inline bool is_machine_check(u32 intr_info) 1669static inline bool is_machine_check(u32 intr_info)
1642{ 1670{
1643 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK | 1671 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
@@ -2063,9 +2091,6 @@ static inline bool is_nmi(u32 intr_info)
2063static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason, 2091static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
2064 u32 exit_intr_info, 2092 u32 exit_intr_info,
2065 unsigned long exit_qualification); 2093 unsigned long exit_qualification);
2066static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
2067 struct vmcs12 *vmcs12,
2068 u32 reason, unsigned long qualification);
2069 2094
2070static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr) 2095static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
2071{ 2096{
@@ -2077,7 +2102,7 @@ static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
2077 return -1; 2102 return -1;
2078} 2103}
2079 2104
2080static inline void __invvpid(int ext, u16 vpid, gva_t gva) 2105static inline void __invvpid(unsigned long ext, u16 vpid, gva_t gva)
2081{ 2106{
2082 struct { 2107 struct {
2083 u64 vpid : 16; 2108 u64 vpid : 16;
@@ -2086,22 +2111,20 @@ static inline void __invvpid(int ext, u16 vpid, gva_t gva)
2086 } operand = { vpid, 0, gva }; 2111 } operand = { vpid, 0, gva };
2087 bool error; 2112 bool error;
2088 2113
2089 asm volatile (__ex(ASM_VMX_INVVPID) CC_SET(na) 2114 asm volatile (__ex("invvpid %2, %1") CC_SET(na)
2090 : CC_OUT(na) (error) : "a"(&operand), "c"(ext) 2115 : CC_OUT(na) (error) : "r"(ext), "m"(operand));
2091 : "memory");
2092 BUG_ON(error); 2116 BUG_ON(error);
2093} 2117}
2094 2118
2095static inline void __invept(int ext, u64 eptp, gpa_t gpa) 2119static inline void __invept(unsigned long ext, u64 eptp, gpa_t gpa)
2096{ 2120{
2097 struct { 2121 struct {
2098 u64 eptp, gpa; 2122 u64 eptp, gpa;
2099 } operand = {eptp, gpa}; 2123 } operand = {eptp, gpa};
2100 bool error; 2124 bool error;
2101 2125
2102 asm volatile (__ex(ASM_VMX_INVEPT) CC_SET(na) 2126 asm volatile (__ex("invept %2, %1") CC_SET(na)
2103 : CC_OUT(na) (error) : "a" (&operand), "c" (ext) 2127 : CC_OUT(na) (error) : "r"(ext), "m"(operand));
2104 : "memory");
2105 BUG_ON(error); 2128 BUG_ON(error);
2106} 2129}
2107 2130
@@ -2120,9 +2143,8 @@ static void vmcs_clear(struct vmcs *vmcs)
2120 u64 phys_addr = __pa(vmcs); 2143 u64 phys_addr = __pa(vmcs);
2121 bool error; 2144 bool error;
2122 2145
2123 asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) CC_SET(na) 2146 asm volatile (__ex("vmclear %1") CC_SET(na)
2124 : CC_OUT(na) (error) : "a"(&phys_addr), "m"(phys_addr) 2147 : CC_OUT(na) (error) : "m"(phys_addr));
2125 : "memory");
2126 if (unlikely(error)) 2148 if (unlikely(error))
2127 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n", 2149 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
2128 vmcs, phys_addr); 2150 vmcs, phys_addr);
@@ -2145,9 +2167,8 @@ static void vmcs_load(struct vmcs *vmcs)
2145 if (static_branch_unlikely(&enable_evmcs)) 2167 if (static_branch_unlikely(&enable_evmcs))
2146 return evmcs_load(phys_addr); 2168 return evmcs_load(phys_addr);
2147 2169
2148 asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) CC_SET(na) 2170 asm volatile (__ex("vmptrld %1") CC_SET(na)
2149 : CC_OUT(na) (error) : "a"(&phys_addr), "m"(phys_addr) 2171 : CC_OUT(na) (error) : "m"(phys_addr));
2150 : "memory");
2151 if (unlikely(error)) 2172 if (unlikely(error))
2152 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n", 2173 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
2153 vmcs, phys_addr); 2174 vmcs, phys_addr);
@@ -2323,8 +2344,8 @@ static __always_inline unsigned long __vmcs_readl(unsigned long field)
2323{ 2344{
2324 unsigned long value; 2345 unsigned long value;
2325 2346
2326 asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0") 2347 asm volatile (__ex_clear("vmread %1, %0", "%k0")
2327 : "=a"(value) : "d"(field) : "cc"); 2348 : "=r"(value) : "r"(field));
2328 return value; 2349 return value;
2329} 2350}
2330 2351
@@ -2375,8 +2396,8 @@ static __always_inline void __vmcs_writel(unsigned long field, unsigned long val
2375{ 2396{
2376 bool error; 2397 bool error;
2377 2398
2378 asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) CC_SET(na) 2399 asm volatile (__ex("vmwrite %2, %1") CC_SET(na)
2379 : CC_OUT(na) (error) : "a"(value), "d"(field)); 2400 : CC_OUT(na) (error) : "r"(field), "rm"(value));
2380 if (unlikely(error)) 2401 if (unlikely(error))
2381 vmwrite_error(field, value); 2402 vmwrite_error(field, value);
2382} 2403}
@@ -2707,7 +2728,8 @@ static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2707 u64 guest_val, u64 host_val) 2728 u64 guest_val, u64 host_val)
2708{ 2729{
2709 vmcs_write64(guest_val_vmcs, guest_val); 2730 vmcs_write64(guest_val_vmcs, guest_val);
2710 vmcs_write64(host_val_vmcs, host_val); 2731 if (host_val_vmcs != HOST_IA32_EFER)
2732 vmcs_write64(host_val_vmcs, host_val);
2711 vm_entry_controls_setbit(vmx, entry); 2733 vm_entry_controls_setbit(vmx, entry);
2712 vm_exit_controls_setbit(vmx, exit); 2734 vm_exit_controls_setbit(vmx, exit);
2713} 2735}
@@ -2805,8 +2827,6 @@ static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
2805 ignore_bits &= ~(u64)EFER_SCE; 2827 ignore_bits &= ~(u64)EFER_SCE;
2806#endif 2828#endif
2807 2829
2808 clear_atomic_switch_msr(vmx, MSR_EFER);
2809
2810 /* 2830 /*
2811 * On EPT, we can't emulate NX, so we must switch EFER atomically. 2831 * On EPT, we can't emulate NX, so we must switch EFER atomically.
2812 * On CPUs that support "load IA32_EFER", always switch EFER 2832 * On CPUs that support "load IA32_EFER", always switch EFER
@@ -2819,8 +2839,12 @@ static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
2819 if (guest_efer != host_efer) 2839 if (guest_efer != host_efer)
2820 add_atomic_switch_msr(vmx, MSR_EFER, 2840 add_atomic_switch_msr(vmx, MSR_EFER,
2821 guest_efer, host_efer, false); 2841 guest_efer, host_efer, false);
2842 else
2843 clear_atomic_switch_msr(vmx, MSR_EFER);
2822 return false; 2844 return false;
2823 } else { 2845 } else {
2846 clear_atomic_switch_msr(vmx, MSR_EFER);
2847
2824 guest_efer &= ~ignore_bits; 2848 guest_efer &= ~ignore_bits;
2825 guest_efer |= host_efer & ignore_bits; 2849 guest_efer |= host_efer & ignore_bits;
2826 2850
@@ -3272,34 +3296,30 @@ static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned long *exit
3272{ 3296{
3273 struct vmcs12 *vmcs12 = get_vmcs12(vcpu); 3297 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3274 unsigned int nr = vcpu->arch.exception.nr; 3298 unsigned int nr = vcpu->arch.exception.nr;
3299 bool has_payload = vcpu->arch.exception.has_payload;
3300 unsigned long payload = vcpu->arch.exception.payload;
3275 3301
3276 if (nr == PF_VECTOR) { 3302 if (nr == PF_VECTOR) {
3277 if (vcpu->arch.exception.nested_apf) { 3303 if (vcpu->arch.exception.nested_apf) {
3278 *exit_qual = vcpu->arch.apf.nested_apf_token; 3304 *exit_qual = vcpu->arch.apf.nested_apf_token;
3279 return 1; 3305 return 1;
3280 } 3306 }
3281 /*
3282 * FIXME: we must not write CR2 when L1 intercepts an L2 #PF exception.
3283 * The fix is to add the ancillary datum (CR2 or DR6) to structs
3284 * kvm_queued_exception and kvm_vcpu_events, so that CR2 and DR6
3285 * can be written only when inject_pending_event runs. This should be
3286 * conditional on a new capability---if the capability is disabled,
3287 * kvm_multiple_exception would write the ancillary information to
3288 * CR2 or DR6, for backwards ABI-compatibility.
3289 */
3290 if (nested_vmx_is_page_fault_vmexit(vmcs12, 3307 if (nested_vmx_is_page_fault_vmexit(vmcs12,
3291 vcpu->arch.exception.error_code)) { 3308 vcpu->arch.exception.error_code)) {
3292 *exit_qual = vcpu->arch.cr2; 3309 *exit_qual = has_payload ? payload : vcpu->arch.cr2;
3293 return 1;
3294 }
3295 } else {
3296 if (vmcs12->exception_bitmap & (1u << nr)) {
3297 if (nr == DB_VECTOR)
3298 *exit_qual = vcpu->arch.dr6;
3299 else
3300 *exit_qual = 0;
3301 return 1; 3310 return 1;
3302 } 3311 }
3312 } else if (vmcs12->exception_bitmap & (1u << nr)) {
3313 if (nr == DB_VECTOR) {
3314 if (!has_payload) {
3315 payload = vcpu->arch.dr6;
3316 payload &= ~(DR6_FIXED_1 | DR6_BT);
3317 payload ^= DR6_RTM;
3318 }
3319 *exit_qual = payload;
3320 } else
3321 *exit_qual = 0;
3322 return 1;
3303 } 3323 }
3304 3324
3305 return 0; 3325 return 0;
@@ -3326,6 +3346,8 @@ static void vmx_queue_exception(struct kvm_vcpu *vcpu)
3326 u32 error_code = vcpu->arch.exception.error_code; 3346 u32 error_code = vcpu->arch.exception.error_code;
3327 u32 intr_info = nr | INTR_INFO_VALID_MASK; 3347 u32 intr_info = nr | INTR_INFO_VALID_MASK;
3328 3348
3349 kvm_deliver_exception_payload(vcpu);
3350
3329 if (has_error_code) { 3351 if (has_error_code) {
3330 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code); 3352 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
3331 intr_info |= INTR_INFO_DELIVER_CODE_MASK; 3353 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
@@ -4397,9 +4419,7 @@ static void kvm_cpu_vmxon(u64 addr)
4397 cr4_set_bits(X86_CR4_VMXE); 4419 cr4_set_bits(X86_CR4_VMXE);
4398 intel_pt_handle_vmx(1); 4420 intel_pt_handle_vmx(1);
4399 4421
4400 asm volatile (ASM_VMX_VMXON_RAX 4422 asm volatile ("vmxon %0" : : "m"(addr));
4401 : : "a"(&addr), "m"(addr)
4402 : "memory", "cc");
4403} 4423}
4404 4424
4405static int hardware_enable(void) 4425static int hardware_enable(void)
@@ -4468,7 +4488,7 @@ static void vmclear_local_loaded_vmcss(void)
4468 */ 4488 */
4469static void kvm_cpu_vmxoff(void) 4489static void kvm_cpu_vmxoff(void)
4470{ 4490{
4471 asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc"); 4491 asm volatile (__ex("vmxoff"));
4472 4492
4473 intel_pt_handle_vmx(0); 4493 intel_pt_handle_vmx(0);
4474 cr4_clear_bits(X86_CR4_VMXE); 4494 cr4_clear_bits(X86_CR4_VMXE);
@@ -5112,9 +5132,10 @@ static inline void __vmx_flush_tlb(struct kvm_vcpu *vcpu, int vpid,
5112 bool invalidate_gpa) 5132 bool invalidate_gpa)
5113{ 5133{
5114 if (enable_ept && (invalidate_gpa || !enable_vpid)) { 5134 if (enable_ept && (invalidate_gpa || !enable_vpid)) {
5115 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa)) 5135 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
5116 return; 5136 return;
5117 ept_sync_context(construct_eptp(vcpu, vcpu->arch.mmu.root_hpa)); 5137 ept_sync_context(construct_eptp(vcpu,
5138 vcpu->arch.mmu->root_hpa));
5118 } else { 5139 } else {
5119 vpid_sync_context(vpid); 5140 vpid_sync_context(vpid);
5120 } 5141 }
@@ -5264,7 +5285,7 @@ static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
5264 struct vcpu_vmx *vmx = to_vmx(vcpu); 5285 struct vcpu_vmx *vmx = to_vmx(vcpu);
5265 unsigned long hw_cr0; 5286 unsigned long hw_cr0;
5266 5287
5267 hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK); 5288 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
5268 if (enable_unrestricted_guest) 5289 if (enable_unrestricted_guest)
5269 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST; 5290 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
5270 else { 5291 else {
@@ -6339,6 +6360,9 @@ static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
6339 rdmsr(MSR_IA32_CR_PAT, low32, high32); 6360 rdmsr(MSR_IA32_CR_PAT, low32, high32);
6340 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32)); 6361 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
6341 } 6362 }
6363
6364 if (cpu_has_load_ia32_efer)
6365 vmcs_write64(HOST_IA32_EFER, host_efer);
6342} 6366}
6343 6367
6344static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx) 6368static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
@@ -6666,7 +6690,6 @@ static void vmx_vcpu_setup(struct vcpu_vmx *vmx)
6666 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP); 6690 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
6667 6691
6668 if (enable_pml) { 6692 if (enable_pml) {
6669 ASSERT(vmx->pml_pg);
6670 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg)); 6693 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
6671 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1); 6694 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
6672 } 6695 }
@@ -8067,35 +8090,39 @@ static int handle_monitor(struct kvm_vcpu *vcpu)
8067 8090
8068/* 8091/*
8069 * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(), 8092 * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
8070 * set the success or error code of an emulated VMX instruction, as specified 8093 * set the success or error code of an emulated VMX instruction (as specified
8071 * by Vol 2B, VMX Instruction Reference, "Conventions". 8094 * by Vol 2B, VMX Instruction Reference, "Conventions"), and skip the emulated
8095 * instruction.
8072 */ 8096 */
8073static void nested_vmx_succeed(struct kvm_vcpu *vcpu) 8097static int nested_vmx_succeed(struct kvm_vcpu *vcpu)
8074{ 8098{
8075 vmx_set_rflags(vcpu, vmx_get_rflags(vcpu) 8099 vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
8076 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF | 8100 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
8077 X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF)); 8101 X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
8102 return kvm_skip_emulated_instruction(vcpu);
8078} 8103}
8079 8104
8080static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu) 8105static int nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
8081{ 8106{
8082 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu) 8107 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
8083 & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF | 8108 & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
8084 X86_EFLAGS_SF | X86_EFLAGS_OF)) 8109 X86_EFLAGS_SF | X86_EFLAGS_OF))
8085 | X86_EFLAGS_CF); 8110 | X86_EFLAGS_CF);
8111 return kvm_skip_emulated_instruction(vcpu);
8086} 8112}
8087 8113
8088static void nested_vmx_failValid(struct kvm_vcpu *vcpu, 8114static int nested_vmx_failValid(struct kvm_vcpu *vcpu,
8089 u32 vm_instruction_error) 8115 u32 vm_instruction_error)
8090{ 8116{
8091 if (to_vmx(vcpu)->nested.current_vmptr == -1ull) { 8117 struct vcpu_vmx *vmx = to_vmx(vcpu);
8092 /* 8118
8093 * failValid writes the error number to the current VMCS, which 8119 /*
8094 * can't be done there isn't a current VMCS. 8120 * failValid writes the error number to the current VMCS, which
8095 */ 8121 * can't be done if there isn't a current VMCS.
8096 nested_vmx_failInvalid(vcpu); 8122 */
8097 return; 8123 if (vmx->nested.current_vmptr == -1ull && !vmx->nested.hv_evmcs)
8098 } 8124 return nested_vmx_failInvalid(vcpu);
8125
8099 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu) 8126 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
8100 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF | 8127 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
8101 X86_EFLAGS_SF | X86_EFLAGS_OF)) 8128 X86_EFLAGS_SF | X86_EFLAGS_OF))
@@ -8105,6 +8132,7 @@ static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
8105 * We don't need to force a shadow sync because 8132 * We don't need to force a shadow sync because
8106 * VM_INSTRUCTION_ERROR is not shadowed 8133 * VM_INSTRUCTION_ERROR is not shadowed
8107 */ 8134 */
8135 return kvm_skip_emulated_instruction(vcpu);
8108} 8136}
8109 8137
8110static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator) 8138static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
@@ -8292,6 +8320,7 @@ static int enter_vmx_operation(struct kvm_vcpu *vcpu)
8292 8320
8293 vmx->nested.vpid02 = allocate_vpid(); 8321 vmx->nested.vpid02 = allocate_vpid();
8294 8322
8323 vmx->nested.vmcs02_initialized = false;
8295 vmx->nested.vmxon = true; 8324 vmx->nested.vmxon = true;
8296 return 0; 8325 return 0;
8297 8326
@@ -8345,10 +8374,9 @@ static int handle_vmon(struct kvm_vcpu *vcpu)
8345 return 1; 8374 return 1;
8346 } 8375 }
8347 8376
8348 if (vmx->nested.vmxon) { 8377 if (vmx->nested.vmxon)
8349 nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION); 8378 return nested_vmx_failValid(vcpu,
8350 return kvm_skip_emulated_instruction(vcpu); 8379 VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
8351 }
8352 8380
8353 if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES) 8381 if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
8354 != VMXON_NEEDED_FEATURES) { 8382 != VMXON_NEEDED_FEATURES) {
@@ -8367,21 +8395,17 @@ static int handle_vmon(struct kvm_vcpu *vcpu)
8367 * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case; 8395 * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case;
8368 * which replaces physical address width with 32 8396 * which replaces physical address width with 32
8369 */ 8397 */
8370 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) { 8398 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu)))
8371 nested_vmx_failInvalid(vcpu); 8399 return nested_vmx_failInvalid(vcpu);
8372 return kvm_skip_emulated_instruction(vcpu);
8373 }
8374 8400
8375 page = kvm_vcpu_gpa_to_page(vcpu, vmptr); 8401 page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
8376 if (is_error_page(page)) { 8402 if (is_error_page(page))
8377 nested_vmx_failInvalid(vcpu); 8403 return nested_vmx_failInvalid(vcpu);
8378 return kvm_skip_emulated_instruction(vcpu); 8404
8379 }
8380 if (*(u32 *)kmap(page) != VMCS12_REVISION) { 8405 if (*(u32 *)kmap(page) != VMCS12_REVISION) {
8381 kunmap(page); 8406 kunmap(page);
8382 kvm_release_page_clean(page); 8407 kvm_release_page_clean(page);
8383 nested_vmx_failInvalid(vcpu); 8408 return nested_vmx_failInvalid(vcpu);
8384 return kvm_skip_emulated_instruction(vcpu);
8385 } 8409 }
8386 kunmap(page); 8410 kunmap(page);
8387 kvm_release_page_clean(page); 8411 kvm_release_page_clean(page);
@@ -8391,8 +8415,7 @@ static int handle_vmon(struct kvm_vcpu *vcpu)
8391 if (ret) 8415 if (ret)
8392 return ret; 8416 return ret;
8393 8417
8394 nested_vmx_succeed(vcpu); 8418 return nested_vmx_succeed(vcpu);
8395 return kvm_skip_emulated_instruction(vcpu);
8396} 8419}
8397 8420
8398/* 8421/*
@@ -8423,8 +8446,24 @@ static void vmx_disable_shadow_vmcs(struct vcpu_vmx *vmx)
8423 vmcs_write64(VMCS_LINK_POINTER, -1ull); 8446 vmcs_write64(VMCS_LINK_POINTER, -1ull);
8424} 8447}
8425 8448
8426static inline void nested_release_vmcs12(struct vcpu_vmx *vmx) 8449static inline void nested_release_evmcs(struct kvm_vcpu *vcpu)
8450{
8451 struct vcpu_vmx *vmx = to_vmx(vcpu);
8452
8453 if (!vmx->nested.hv_evmcs)
8454 return;
8455
8456 kunmap(vmx->nested.hv_evmcs_page);
8457 kvm_release_page_dirty(vmx->nested.hv_evmcs_page);
8458 vmx->nested.hv_evmcs_vmptr = -1ull;
8459 vmx->nested.hv_evmcs_page = NULL;
8460 vmx->nested.hv_evmcs = NULL;
8461}
8462
8463static inline void nested_release_vmcs12(struct kvm_vcpu *vcpu)
8427{ 8464{
8465 struct vcpu_vmx *vmx = to_vmx(vcpu);
8466
8428 if (vmx->nested.current_vmptr == -1ull) 8467 if (vmx->nested.current_vmptr == -1ull)
8429 return; 8468 return;
8430 8469
@@ -8432,16 +8471,18 @@ static inline void nested_release_vmcs12(struct vcpu_vmx *vmx)
8432 /* copy to memory all shadowed fields in case 8471 /* copy to memory all shadowed fields in case
8433 they were modified */ 8472 they were modified */
8434 copy_shadow_to_vmcs12(vmx); 8473 copy_shadow_to_vmcs12(vmx);
8435 vmx->nested.sync_shadow_vmcs = false; 8474 vmx->nested.need_vmcs12_sync = false;
8436 vmx_disable_shadow_vmcs(vmx); 8475 vmx_disable_shadow_vmcs(vmx);
8437 } 8476 }
8438 vmx->nested.posted_intr_nv = -1; 8477 vmx->nested.posted_intr_nv = -1;
8439 8478
8440 /* Flush VMCS12 to guest memory */ 8479 /* Flush VMCS12 to guest memory */
8441 kvm_vcpu_write_guest_page(&vmx->vcpu, 8480 kvm_vcpu_write_guest_page(vcpu,
8442 vmx->nested.current_vmptr >> PAGE_SHIFT, 8481 vmx->nested.current_vmptr >> PAGE_SHIFT,
8443 vmx->nested.cached_vmcs12, 0, VMCS12_SIZE); 8482 vmx->nested.cached_vmcs12, 0, VMCS12_SIZE);
8444 8483
8484 kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
8485
8445 vmx->nested.current_vmptr = -1ull; 8486 vmx->nested.current_vmptr = -1ull;
8446} 8487}
8447 8488
@@ -8449,8 +8490,10 @@ static inline void nested_release_vmcs12(struct vcpu_vmx *vmx)
8449 * Free whatever needs to be freed from vmx->nested when L1 goes down, or 8490 * Free whatever needs to be freed from vmx->nested when L1 goes down, or
8450 * just stops using VMX. 8491 * just stops using VMX.
8451 */ 8492 */
8452static void free_nested(struct vcpu_vmx *vmx) 8493static void free_nested(struct kvm_vcpu *vcpu)
8453{ 8494{
8495 struct vcpu_vmx *vmx = to_vmx(vcpu);
8496
8454 if (!vmx->nested.vmxon && !vmx->nested.smm.vmxon) 8497 if (!vmx->nested.vmxon && !vmx->nested.smm.vmxon)
8455 return; 8498 return;
8456 8499
@@ -8483,6 +8526,10 @@ static void free_nested(struct vcpu_vmx *vmx)
8483 vmx->nested.pi_desc = NULL; 8526 vmx->nested.pi_desc = NULL;
8484 } 8527 }
8485 8528
8529 kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
8530
8531 nested_release_evmcs(vcpu);
8532
8486 free_loaded_vmcs(&vmx->nested.vmcs02); 8533 free_loaded_vmcs(&vmx->nested.vmcs02);
8487} 8534}
8488 8535
@@ -8491,9 +8538,8 @@ static int handle_vmoff(struct kvm_vcpu *vcpu)
8491{ 8538{
8492 if (!nested_vmx_check_permission(vcpu)) 8539 if (!nested_vmx_check_permission(vcpu))
8493 return 1; 8540 return 1;
8494 free_nested(to_vmx(vcpu)); 8541 free_nested(vcpu);
8495 nested_vmx_succeed(vcpu); 8542 return nested_vmx_succeed(vcpu);
8496 return kvm_skip_emulated_instruction(vcpu);
8497} 8543}
8498 8544
8499/* Emulate the VMCLEAR instruction */ 8545/* Emulate the VMCLEAR instruction */
@@ -8509,25 +8555,28 @@ static int handle_vmclear(struct kvm_vcpu *vcpu)
8509 if (nested_vmx_get_vmptr(vcpu, &vmptr)) 8555 if (nested_vmx_get_vmptr(vcpu, &vmptr))
8510 return 1; 8556 return 1;
8511 8557
8512 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) { 8558 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu)))
8513 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_INVALID_ADDRESS); 8559 return nested_vmx_failValid(vcpu,
8514 return kvm_skip_emulated_instruction(vcpu); 8560 VMXERR_VMCLEAR_INVALID_ADDRESS);
8515 }
8516 8561
8517 if (vmptr == vmx->nested.vmxon_ptr) { 8562 if (vmptr == vmx->nested.vmxon_ptr)
8518 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_VMXON_POINTER); 8563 return nested_vmx_failValid(vcpu,
8519 return kvm_skip_emulated_instruction(vcpu); 8564 VMXERR_VMCLEAR_VMXON_POINTER);
8520 }
8521 8565
8522 if (vmptr == vmx->nested.current_vmptr) 8566 if (vmx->nested.hv_evmcs_page) {
8523 nested_release_vmcs12(vmx); 8567 if (vmptr == vmx->nested.hv_evmcs_vmptr)
8568 nested_release_evmcs(vcpu);
8569 } else {
8570 if (vmptr == vmx->nested.current_vmptr)
8571 nested_release_vmcs12(vcpu);
8524 8572
8525 kvm_vcpu_write_guest(vcpu, 8573 kvm_vcpu_write_guest(vcpu,
8526 vmptr + offsetof(struct vmcs12, launch_state), 8574 vmptr + offsetof(struct vmcs12,
8527 &zero, sizeof(zero)); 8575 launch_state),
8576 &zero, sizeof(zero));
8577 }
8528 8578
8529 nested_vmx_succeed(vcpu); 8579 return nested_vmx_succeed(vcpu);
8530 return kvm_skip_emulated_instruction(vcpu);
8531} 8580}
8532 8581
8533static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch); 8582static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
@@ -8610,6 +8659,395 @@ static inline int vmcs12_write_any(struct vmcs12 *vmcs12,
8610 8659
8611} 8660}
8612 8661
8662static int copy_enlightened_to_vmcs12(struct vcpu_vmx *vmx)
8663{
8664 struct vmcs12 *vmcs12 = vmx->nested.cached_vmcs12;
8665 struct hv_enlightened_vmcs *evmcs = vmx->nested.hv_evmcs;
8666
8667 vmcs12->hdr.revision_id = evmcs->revision_id;
8668
8669 /* HV_VMX_ENLIGHTENED_CLEAN_FIELD_NONE */
8670 vmcs12->tpr_threshold = evmcs->tpr_threshold;
8671 vmcs12->guest_rip = evmcs->guest_rip;
8672
8673 if (unlikely(!(evmcs->hv_clean_fields &
8674 HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_BASIC))) {
8675 vmcs12->guest_rsp = evmcs->guest_rsp;
8676 vmcs12->guest_rflags = evmcs->guest_rflags;
8677 vmcs12->guest_interruptibility_info =
8678 evmcs->guest_interruptibility_info;
8679 }
8680
8681 if (unlikely(!(evmcs->hv_clean_fields &
8682 HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_PROC))) {
8683 vmcs12->cpu_based_vm_exec_control =
8684 evmcs->cpu_based_vm_exec_control;
8685 }
8686
8687 if (unlikely(!(evmcs->hv_clean_fields &
8688 HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_PROC))) {
8689 vmcs12->exception_bitmap = evmcs->exception_bitmap;
8690 }
8691
8692 if (unlikely(!(evmcs->hv_clean_fields &
8693 HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_ENTRY))) {
8694 vmcs12->vm_entry_controls = evmcs->vm_entry_controls;
8695 }
8696
8697 if (unlikely(!(evmcs->hv_clean_fields &
8698 HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_EVENT))) {
8699 vmcs12->vm_entry_intr_info_field =
8700 evmcs->vm_entry_intr_info_field;
8701 vmcs12->vm_entry_exception_error_code =
8702 evmcs->vm_entry_exception_error_code;
8703 vmcs12->vm_entry_instruction_len =
8704 evmcs->vm_entry_instruction_len;
8705 }
8706
8707 if (unlikely(!(evmcs->hv_clean_fields &
8708 HV_VMX_ENLIGHTENED_CLEAN_FIELD_HOST_GRP1))) {
8709 vmcs12->host_ia32_pat = evmcs->host_ia32_pat;
8710 vmcs12->host_ia32_efer = evmcs->host_ia32_efer;
8711 vmcs12->host_cr0 = evmcs->host_cr0;
8712 vmcs12->host_cr3 = evmcs->host_cr3;
8713 vmcs12->host_cr4 = evmcs->host_cr4;
8714 vmcs12->host_ia32_sysenter_esp = evmcs->host_ia32_sysenter_esp;
8715 vmcs12->host_ia32_sysenter_eip = evmcs->host_ia32_sysenter_eip;
8716 vmcs12->host_rip = evmcs->host_rip;
8717 vmcs12->host_ia32_sysenter_cs = evmcs->host_ia32_sysenter_cs;
8718 vmcs12->host_es_selector = evmcs->host_es_selector;
8719 vmcs12->host_cs_selector = evmcs->host_cs_selector;
8720 vmcs12->host_ss_selector = evmcs->host_ss_selector;
8721 vmcs12->host_ds_selector = evmcs->host_ds_selector;
8722 vmcs12->host_fs_selector = evmcs->host_fs_selector;
8723 vmcs12->host_gs_selector = evmcs->host_gs_selector;
8724 vmcs12->host_tr_selector = evmcs->host_tr_selector;
8725 }
8726
8727 if (unlikely(!(evmcs->hv_clean_fields &
8728 HV_VMX_ENLIGHTENED_CLEAN_FIELD_HOST_GRP1))) {
8729 vmcs12->pin_based_vm_exec_control =
8730 evmcs->pin_based_vm_exec_control;
8731 vmcs12->vm_exit_controls = evmcs->vm_exit_controls;
8732 vmcs12->secondary_vm_exec_control =
8733 evmcs->secondary_vm_exec_control;
8734 }
8735
8736 if (unlikely(!(evmcs->hv_clean_fields &
8737 HV_VMX_ENLIGHTENED_CLEAN_FIELD_IO_BITMAP))) {
8738 vmcs12->io_bitmap_a = evmcs->io_bitmap_a;
8739 vmcs12->io_bitmap_b = evmcs->io_bitmap_b;
8740 }
8741
8742 if (unlikely(!(evmcs->hv_clean_fields &
8743 HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP))) {
8744 vmcs12->msr_bitmap = evmcs->msr_bitmap;
8745 }
8746
8747 if (unlikely(!(evmcs->hv_clean_fields &
8748 HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP2))) {
8749 vmcs12->guest_es_base = evmcs->guest_es_base;
8750 vmcs12->guest_cs_base = evmcs->guest_cs_base;
8751 vmcs12->guest_ss_base = evmcs->guest_ss_base;
8752 vmcs12->guest_ds_base = evmcs->guest_ds_base;
8753 vmcs12->guest_fs_base = evmcs->guest_fs_base;
8754 vmcs12->guest_gs_base = evmcs->guest_gs_base;
8755 vmcs12->guest_ldtr_base = evmcs->guest_ldtr_base;
8756 vmcs12->guest_tr_base = evmcs->guest_tr_base;
8757 vmcs12->guest_gdtr_base = evmcs->guest_gdtr_base;
8758 vmcs12->guest_idtr_base = evmcs->guest_idtr_base;
8759 vmcs12->guest_es_limit = evmcs->guest_es_limit;
8760 vmcs12->guest_cs_limit = evmcs->guest_cs_limit;
8761 vmcs12->guest_ss_limit = evmcs->guest_ss_limit;
8762 vmcs12->guest_ds_limit = evmcs->guest_ds_limit;
8763 vmcs12->guest_fs_limit = evmcs->guest_fs_limit;
8764 vmcs12->guest_gs_limit = evmcs->guest_gs_limit;
8765 vmcs12->guest_ldtr_limit = evmcs->guest_ldtr_limit;
8766 vmcs12->guest_tr_limit = evmcs->guest_tr_limit;
8767 vmcs12->guest_gdtr_limit = evmcs->guest_gdtr_limit;
8768 vmcs12->guest_idtr_limit = evmcs->guest_idtr_limit;
8769 vmcs12->guest_es_ar_bytes = evmcs->guest_es_ar_bytes;
8770 vmcs12->guest_cs_ar_bytes = evmcs->guest_cs_ar_bytes;
8771 vmcs12->guest_ss_ar_bytes = evmcs->guest_ss_ar_bytes;
8772 vmcs12->guest_ds_ar_bytes = evmcs->guest_ds_ar_bytes;
8773 vmcs12->guest_fs_ar_bytes = evmcs->guest_fs_ar_bytes;
8774 vmcs12->guest_gs_ar_bytes = evmcs->guest_gs_ar_bytes;
8775 vmcs12->guest_ldtr_ar_bytes = evmcs->guest_ldtr_ar_bytes;
8776 vmcs12->guest_tr_ar_bytes = evmcs->guest_tr_ar_bytes;
8777 vmcs12->guest_es_selector = evmcs->guest_es_selector;
8778 vmcs12->guest_cs_selector = evmcs->guest_cs_selector;
8779 vmcs12->guest_ss_selector = evmcs->guest_ss_selector;
8780 vmcs12->guest_ds_selector = evmcs->guest_ds_selector;
8781 vmcs12->guest_fs_selector = evmcs->guest_fs_selector;
8782 vmcs12->guest_gs_selector = evmcs->guest_gs_selector;
8783 vmcs12->guest_ldtr_selector = evmcs->guest_ldtr_selector;
8784 vmcs12->guest_tr_selector = evmcs->guest_tr_selector;
8785 }
8786
8787 if (unlikely(!(evmcs->hv_clean_fields &
8788 HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_GRP2))) {
8789 vmcs12->tsc_offset = evmcs->tsc_offset;
8790 vmcs12->virtual_apic_page_addr = evmcs->virtual_apic_page_addr;
8791 vmcs12->xss_exit_bitmap = evmcs->xss_exit_bitmap;
8792 }
8793
8794 if (unlikely(!(evmcs->hv_clean_fields &
8795 HV_VMX_ENLIGHTENED_CLEAN_FIELD_CRDR))) {
8796 vmcs12->cr0_guest_host_mask = evmcs->cr0_guest_host_mask;
8797 vmcs12->cr4_guest_host_mask = evmcs->cr4_guest_host_mask;
8798 vmcs12->cr0_read_shadow = evmcs->cr0_read_shadow;
8799 vmcs12->cr4_read_shadow = evmcs->cr4_read_shadow;
8800 vmcs12->guest_cr0 = evmcs->guest_cr0;
8801 vmcs12->guest_cr3 = evmcs->guest_cr3;
8802 vmcs12->guest_cr4 = evmcs->guest_cr4;
8803 vmcs12->guest_dr7 = evmcs->guest_dr7;
8804 }
8805
8806 if (unlikely(!(evmcs->hv_clean_fields &
8807 HV_VMX_ENLIGHTENED_CLEAN_FIELD_HOST_POINTER))) {
8808 vmcs12->host_fs_base = evmcs->host_fs_base;
8809 vmcs12->host_gs_base = evmcs->host_gs_base;
8810 vmcs12->host_tr_base = evmcs->host_tr_base;
8811 vmcs12->host_gdtr_base = evmcs->host_gdtr_base;
8812 vmcs12->host_idtr_base = evmcs->host_idtr_base;
8813 vmcs12->host_rsp = evmcs->host_rsp;
8814 }
8815
8816 if (unlikely(!(evmcs->hv_clean_fields &
8817 HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_XLAT))) {
8818 vmcs12->ept_pointer = evmcs->ept_pointer;
8819 vmcs12->virtual_processor_id = evmcs->virtual_processor_id;
8820 }
8821
8822 if (unlikely(!(evmcs->hv_clean_fields &
8823 HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP1))) {
8824 vmcs12->vmcs_link_pointer = evmcs->vmcs_link_pointer;
8825 vmcs12->guest_ia32_debugctl = evmcs->guest_ia32_debugctl;
8826 vmcs12->guest_ia32_pat = evmcs->guest_ia32_pat;
8827 vmcs12->guest_ia32_efer = evmcs->guest_ia32_efer;
8828 vmcs12->guest_pdptr0 = evmcs->guest_pdptr0;
8829 vmcs12->guest_pdptr1 = evmcs->guest_pdptr1;
8830 vmcs12->guest_pdptr2 = evmcs->guest_pdptr2;
8831 vmcs12->guest_pdptr3 = evmcs->guest_pdptr3;
8832 vmcs12->guest_pending_dbg_exceptions =
8833 evmcs->guest_pending_dbg_exceptions;
8834 vmcs12->guest_sysenter_esp = evmcs->guest_sysenter_esp;
8835 vmcs12->guest_sysenter_eip = evmcs->guest_sysenter_eip;
8836 vmcs12->guest_bndcfgs = evmcs->guest_bndcfgs;
8837 vmcs12->guest_activity_state = evmcs->guest_activity_state;
8838 vmcs12->guest_sysenter_cs = evmcs->guest_sysenter_cs;
8839 }
8840
8841 /*
8842 * Not used?
8843 * vmcs12->vm_exit_msr_store_addr = evmcs->vm_exit_msr_store_addr;
8844 * vmcs12->vm_exit_msr_load_addr = evmcs->vm_exit_msr_load_addr;
8845 * vmcs12->vm_entry_msr_load_addr = evmcs->vm_entry_msr_load_addr;
8846 * vmcs12->cr3_target_value0 = evmcs->cr3_target_value0;
8847 * vmcs12->cr3_target_value1 = evmcs->cr3_target_value1;
8848 * vmcs12->cr3_target_value2 = evmcs->cr3_target_value2;
8849 * vmcs12->cr3_target_value3 = evmcs->cr3_target_value3;
8850 * vmcs12->page_fault_error_code_mask =
8851 * evmcs->page_fault_error_code_mask;
8852 * vmcs12->page_fault_error_code_match =
8853 * evmcs->page_fault_error_code_match;
8854 * vmcs12->cr3_target_count = evmcs->cr3_target_count;
8855 * vmcs12->vm_exit_msr_store_count = evmcs->vm_exit_msr_store_count;
8856 * vmcs12->vm_exit_msr_load_count = evmcs->vm_exit_msr_load_count;
8857 * vmcs12->vm_entry_msr_load_count = evmcs->vm_entry_msr_load_count;
8858 */
8859
8860 /*
8861 * Read only fields:
8862 * vmcs12->guest_physical_address = evmcs->guest_physical_address;
8863 * vmcs12->vm_instruction_error = evmcs->vm_instruction_error;
8864 * vmcs12->vm_exit_reason = evmcs->vm_exit_reason;
8865 * vmcs12->vm_exit_intr_info = evmcs->vm_exit_intr_info;
8866 * vmcs12->vm_exit_intr_error_code = evmcs->vm_exit_intr_error_code;
8867 * vmcs12->idt_vectoring_info_field = evmcs->idt_vectoring_info_field;
8868 * vmcs12->idt_vectoring_error_code = evmcs->idt_vectoring_error_code;
8869 * vmcs12->vm_exit_instruction_len = evmcs->vm_exit_instruction_len;
8870 * vmcs12->vmx_instruction_info = evmcs->vmx_instruction_info;
8871 * vmcs12->exit_qualification = evmcs->exit_qualification;
8872 * vmcs12->guest_linear_address = evmcs->guest_linear_address;
8873 *
8874 * Not present in struct vmcs12:
8875 * vmcs12->exit_io_instruction_ecx = evmcs->exit_io_instruction_ecx;
8876 * vmcs12->exit_io_instruction_esi = evmcs->exit_io_instruction_esi;
8877 * vmcs12->exit_io_instruction_edi = evmcs->exit_io_instruction_edi;
8878 * vmcs12->exit_io_instruction_eip = evmcs->exit_io_instruction_eip;
8879 */
8880
8881 return 0;
8882}
8883
8884static int copy_vmcs12_to_enlightened(struct vcpu_vmx *vmx)
8885{
8886 struct vmcs12 *vmcs12 = vmx->nested.cached_vmcs12;
8887 struct hv_enlightened_vmcs *evmcs = vmx->nested.hv_evmcs;
8888
8889 /*
8890 * Should not be changed by KVM:
8891 *
8892 * evmcs->host_es_selector = vmcs12->host_es_selector;
8893 * evmcs->host_cs_selector = vmcs12->host_cs_selector;
8894 * evmcs->host_ss_selector = vmcs12->host_ss_selector;
8895 * evmcs->host_ds_selector = vmcs12->host_ds_selector;
8896 * evmcs->host_fs_selector = vmcs12->host_fs_selector;
8897 * evmcs->host_gs_selector = vmcs12->host_gs_selector;
8898 * evmcs->host_tr_selector = vmcs12->host_tr_selector;
8899 * evmcs->host_ia32_pat = vmcs12->host_ia32_pat;
8900 * evmcs->host_ia32_efer = vmcs12->host_ia32_efer;
8901 * evmcs->host_cr0 = vmcs12->host_cr0;
8902 * evmcs->host_cr3 = vmcs12->host_cr3;
8903 * evmcs->host_cr4 = vmcs12->host_cr4;
8904 * evmcs->host_ia32_sysenter_esp = vmcs12->host_ia32_sysenter_esp;
8905 * evmcs->host_ia32_sysenter_eip = vmcs12->host_ia32_sysenter_eip;
8906 * evmcs->host_rip = vmcs12->host_rip;
8907 * evmcs->host_ia32_sysenter_cs = vmcs12->host_ia32_sysenter_cs;
8908 * evmcs->host_fs_base = vmcs12->host_fs_base;
8909 * evmcs->host_gs_base = vmcs12->host_gs_base;
8910 * evmcs->host_tr_base = vmcs12->host_tr_base;
8911 * evmcs->host_gdtr_base = vmcs12->host_gdtr_base;
8912 * evmcs->host_idtr_base = vmcs12->host_idtr_base;
8913 * evmcs->host_rsp = vmcs12->host_rsp;
8914 * sync_vmcs12() doesn't read these:
8915 * evmcs->io_bitmap_a = vmcs12->io_bitmap_a;
8916 * evmcs->io_bitmap_b = vmcs12->io_bitmap_b;
8917 * evmcs->msr_bitmap = vmcs12->msr_bitmap;
8918 * evmcs->ept_pointer = vmcs12->ept_pointer;
8919 * evmcs->xss_exit_bitmap = vmcs12->xss_exit_bitmap;
8920 * evmcs->vm_exit_msr_store_addr = vmcs12->vm_exit_msr_store_addr;
8921 * evmcs->vm_exit_msr_load_addr = vmcs12->vm_exit_msr_load_addr;
8922 * evmcs->vm_entry_msr_load_addr = vmcs12->vm_entry_msr_load_addr;
8923 * evmcs->cr3_target_value0 = vmcs12->cr3_target_value0;
8924 * evmcs->cr3_target_value1 = vmcs12->cr3_target_value1;
8925 * evmcs->cr3_target_value2 = vmcs12->cr3_target_value2;
8926 * evmcs->cr3_target_value3 = vmcs12->cr3_target_value3;
8927 * evmcs->tpr_threshold = vmcs12->tpr_threshold;
8928 * evmcs->virtual_processor_id = vmcs12->virtual_processor_id;
8929 * evmcs->exception_bitmap = vmcs12->exception_bitmap;
8930 * evmcs->vmcs_link_pointer = vmcs12->vmcs_link_pointer;
8931 * evmcs->pin_based_vm_exec_control = vmcs12->pin_based_vm_exec_control;
8932 * evmcs->vm_exit_controls = vmcs12->vm_exit_controls;
8933 * evmcs->secondary_vm_exec_control = vmcs12->secondary_vm_exec_control;
8934 * evmcs->page_fault_error_code_mask =
8935 * vmcs12->page_fault_error_code_mask;
8936 * evmcs->page_fault_error_code_match =
8937 * vmcs12->page_fault_error_code_match;
8938 * evmcs->cr3_target_count = vmcs12->cr3_target_count;
8939 * evmcs->virtual_apic_page_addr = vmcs12->virtual_apic_page_addr;
8940 * evmcs->tsc_offset = vmcs12->tsc_offset;
8941 * evmcs->guest_ia32_debugctl = vmcs12->guest_ia32_debugctl;
8942 * evmcs->cr0_guest_host_mask = vmcs12->cr0_guest_host_mask;
8943 * evmcs->cr4_guest_host_mask = vmcs12->cr4_guest_host_mask;
8944 * evmcs->cr0_read_shadow = vmcs12->cr0_read_shadow;
8945 * evmcs->cr4_read_shadow = vmcs12->cr4_read_shadow;
8946 * evmcs->vm_exit_msr_store_count = vmcs12->vm_exit_msr_store_count;
8947 * evmcs->vm_exit_msr_load_count = vmcs12->vm_exit_msr_load_count;
8948 * evmcs->vm_entry_msr_load_count = vmcs12->vm_entry_msr_load_count;
8949 *
8950 * Not present in struct vmcs12:
8951 * evmcs->exit_io_instruction_ecx = vmcs12->exit_io_instruction_ecx;
8952 * evmcs->exit_io_instruction_esi = vmcs12->exit_io_instruction_esi;
8953 * evmcs->exit_io_instruction_edi = vmcs12->exit_io_instruction_edi;
8954 * evmcs->exit_io_instruction_eip = vmcs12->exit_io_instruction_eip;
8955 */
8956
8957 evmcs->guest_es_selector = vmcs12->guest_es_selector;
8958 evmcs->guest_cs_selector = vmcs12->guest_cs_selector;
8959 evmcs->guest_ss_selector = vmcs12->guest_ss_selector;
8960 evmcs->guest_ds_selector = vmcs12->guest_ds_selector;
8961 evmcs->guest_fs_selector = vmcs12->guest_fs_selector;
8962 evmcs->guest_gs_selector = vmcs12->guest_gs_selector;
8963 evmcs->guest_ldtr_selector = vmcs12->guest_ldtr_selector;
8964 evmcs->guest_tr_selector = vmcs12->guest_tr_selector;
8965
8966 evmcs->guest_es_limit = vmcs12->guest_es_limit;
8967 evmcs->guest_cs_limit = vmcs12->guest_cs_limit;
8968 evmcs->guest_ss_limit = vmcs12->guest_ss_limit;
8969 evmcs->guest_ds_limit = vmcs12->guest_ds_limit;
8970 evmcs->guest_fs_limit = vmcs12->guest_fs_limit;
8971 evmcs->guest_gs_limit = vmcs12->guest_gs_limit;
8972 evmcs->guest_ldtr_limit = vmcs12->guest_ldtr_limit;
8973 evmcs->guest_tr_limit = vmcs12->guest_tr_limit;
8974 evmcs->guest_gdtr_limit = vmcs12->guest_gdtr_limit;
8975 evmcs->guest_idtr_limit = vmcs12->guest_idtr_limit;
8976
8977 evmcs->guest_es_ar_bytes = vmcs12->guest_es_ar_bytes;
8978 evmcs->guest_cs_ar_bytes = vmcs12->guest_cs_ar_bytes;
8979 evmcs->guest_ss_ar_bytes = vmcs12->guest_ss_ar_bytes;
8980 evmcs->guest_ds_ar_bytes = vmcs12->guest_ds_ar_bytes;
8981 evmcs->guest_fs_ar_bytes = vmcs12->guest_fs_ar_bytes;
8982 evmcs->guest_gs_ar_bytes = vmcs12->guest_gs_ar_bytes;
8983 evmcs->guest_ldtr_ar_bytes = vmcs12->guest_ldtr_ar_bytes;
8984 evmcs->guest_tr_ar_bytes = vmcs12->guest_tr_ar_bytes;
8985
8986 evmcs->guest_es_base = vmcs12->guest_es_base;
8987 evmcs->guest_cs_base = vmcs12->guest_cs_base;
8988 evmcs->guest_ss_base = vmcs12->guest_ss_base;
8989 evmcs->guest_ds_base = vmcs12->guest_ds_base;
8990 evmcs->guest_fs_base = vmcs12->guest_fs_base;
8991 evmcs->guest_gs_base = vmcs12->guest_gs_base;
8992 evmcs->guest_ldtr_base = vmcs12->guest_ldtr_base;
8993 evmcs->guest_tr_base = vmcs12->guest_tr_base;
8994 evmcs->guest_gdtr_base = vmcs12->guest_gdtr_base;
8995 evmcs->guest_idtr_base = vmcs12->guest_idtr_base;
8996
8997 evmcs->guest_ia32_pat = vmcs12->guest_ia32_pat;
8998 evmcs->guest_ia32_efer = vmcs12->guest_ia32_efer;
8999
9000 evmcs->guest_pdptr0 = vmcs12->guest_pdptr0;
9001 evmcs->guest_pdptr1 = vmcs12->guest_pdptr1;
9002 evmcs->guest_pdptr2 = vmcs12->guest_pdptr2;
9003 evmcs->guest_pdptr3 = vmcs12->guest_pdptr3;
9004
9005 evmcs->guest_pending_dbg_exceptions =
9006 vmcs12->guest_pending_dbg_exceptions;
9007 evmcs->guest_sysenter_esp = vmcs12->guest_sysenter_esp;
9008 evmcs->guest_sysenter_eip = vmcs12->guest_sysenter_eip;
9009
9010 evmcs->guest_activity_state = vmcs12->guest_activity_state;
9011 evmcs->guest_sysenter_cs = vmcs12->guest_sysenter_cs;
9012
9013 evmcs->guest_cr0 = vmcs12->guest_cr0;
9014 evmcs->guest_cr3 = vmcs12->guest_cr3;
9015 evmcs->guest_cr4 = vmcs12->guest_cr4;
9016 evmcs->guest_dr7 = vmcs12->guest_dr7;
9017
9018 evmcs->guest_physical_address = vmcs12->guest_physical_address;
9019
9020 evmcs->vm_instruction_error = vmcs12->vm_instruction_error;
9021 evmcs->vm_exit_reason = vmcs12->vm_exit_reason;
9022 evmcs->vm_exit_intr_info = vmcs12->vm_exit_intr_info;
9023 evmcs->vm_exit_intr_error_code = vmcs12->vm_exit_intr_error_code;
9024 evmcs->idt_vectoring_info_field = vmcs12->idt_vectoring_info_field;
9025 evmcs->idt_vectoring_error_code = vmcs12->idt_vectoring_error_code;
9026 evmcs->vm_exit_instruction_len = vmcs12->vm_exit_instruction_len;
9027 evmcs->vmx_instruction_info = vmcs12->vmx_instruction_info;
9028
9029 evmcs->exit_qualification = vmcs12->exit_qualification;
9030
9031 evmcs->guest_linear_address = vmcs12->guest_linear_address;
9032 evmcs->guest_rsp = vmcs12->guest_rsp;
9033 evmcs->guest_rflags = vmcs12->guest_rflags;
9034
9035 evmcs->guest_interruptibility_info =
9036 vmcs12->guest_interruptibility_info;
9037 evmcs->cpu_based_vm_exec_control = vmcs12->cpu_based_vm_exec_control;
9038 evmcs->vm_entry_controls = vmcs12->vm_entry_controls;
9039 evmcs->vm_entry_intr_info_field = vmcs12->vm_entry_intr_info_field;
9040 evmcs->vm_entry_exception_error_code =
9041 vmcs12->vm_entry_exception_error_code;
9042 evmcs->vm_entry_instruction_len = vmcs12->vm_entry_instruction_len;
9043
9044 evmcs->guest_rip = vmcs12->guest_rip;
9045
9046 evmcs->guest_bndcfgs = vmcs12->guest_bndcfgs;
9047
9048 return 0;
9049}
9050
8613/* 9051/*
8614 * Copy the writable VMCS shadow fields back to the VMCS12, in case 9052 * Copy the writable VMCS shadow fields back to the VMCS12, in case
8615 * they have been modified by the L1 guest. Note that the "read-only" 9053 * they have been modified by the L1 guest. Note that the "read-only"
@@ -8683,20 +9121,6 @@ static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
8683 vmcs_load(vmx->loaded_vmcs->vmcs); 9121 vmcs_load(vmx->loaded_vmcs->vmcs);
8684} 9122}
8685 9123
8686/*
8687 * VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
8688 * used before) all generate the same failure when it is missing.
8689 */
8690static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
8691{
8692 struct vcpu_vmx *vmx = to_vmx(vcpu);
8693 if (vmx->nested.current_vmptr == -1ull) {
8694 nested_vmx_failInvalid(vcpu);
8695 return 0;
8696 }
8697 return 1;
8698}
8699
8700static int handle_vmread(struct kvm_vcpu *vcpu) 9124static int handle_vmread(struct kvm_vcpu *vcpu)
8701{ 9125{
8702 unsigned long field; 9126 unsigned long field;
@@ -8709,8 +9133,8 @@ static int handle_vmread(struct kvm_vcpu *vcpu)
8709 if (!nested_vmx_check_permission(vcpu)) 9133 if (!nested_vmx_check_permission(vcpu))
8710 return 1; 9134 return 1;
8711 9135
8712 if (!nested_vmx_check_vmcs12(vcpu)) 9136 if (to_vmx(vcpu)->nested.current_vmptr == -1ull)
8713 return kvm_skip_emulated_instruction(vcpu); 9137 return nested_vmx_failInvalid(vcpu);
8714 9138
8715 if (!is_guest_mode(vcpu)) 9139 if (!is_guest_mode(vcpu))
8716 vmcs12 = get_vmcs12(vcpu); 9140 vmcs12 = get_vmcs12(vcpu);
@@ -8719,20 +9143,18 @@ static int handle_vmread(struct kvm_vcpu *vcpu)
8719 * When vmcs->vmcs_link_pointer is -1ull, any VMREAD 9143 * When vmcs->vmcs_link_pointer is -1ull, any VMREAD
8720 * to shadowed-field sets the ALU flags for VMfailInvalid. 9144 * to shadowed-field sets the ALU flags for VMfailInvalid.
8721 */ 9145 */
8722 if (get_vmcs12(vcpu)->vmcs_link_pointer == -1ull) { 9146 if (get_vmcs12(vcpu)->vmcs_link_pointer == -1ull)
8723 nested_vmx_failInvalid(vcpu); 9147 return nested_vmx_failInvalid(vcpu);
8724 return kvm_skip_emulated_instruction(vcpu);
8725 }
8726 vmcs12 = get_shadow_vmcs12(vcpu); 9148 vmcs12 = get_shadow_vmcs12(vcpu);
8727 } 9149 }
8728 9150
8729 /* Decode instruction info and find the field to read */ 9151 /* Decode instruction info and find the field to read */
8730 field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf)); 9152 field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
8731 /* Read the field, zero-extended to a u64 field_value */ 9153 /* Read the field, zero-extended to a u64 field_value */
8732 if (vmcs12_read_any(vmcs12, field, &field_value) < 0) { 9154 if (vmcs12_read_any(vmcs12, field, &field_value) < 0)
8733 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT); 9155 return nested_vmx_failValid(vcpu,
8734 return kvm_skip_emulated_instruction(vcpu); 9156 VMXERR_UNSUPPORTED_VMCS_COMPONENT);
8735 } 9157
8736 /* 9158 /*
8737 * Now copy part of this value to register or memory, as requested. 9159 * Now copy part of this value to register or memory, as requested.
8738 * Note that the number of bits actually copied is 32 or 64 depending 9160 * Note that the number of bits actually copied is 32 or 64 depending
@@ -8750,8 +9172,7 @@ static int handle_vmread(struct kvm_vcpu *vcpu)
8750 (is_long_mode(vcpu) ? 8 : 4), NULL); 9172 (is_long_mode(vcpu) ? 8 : 4), NULL);
8751 } 9173 }
8752 9174
8753 nested_vmx_succeed(vcpu); 9175 return nested_vmx_succeed(vcpu);
8754 return kvm_skip_emulated_instruction(vcpu);
8755} 9176}
8756 9177
8757 9178
@@ -8776,8 +9197,8 @@ static int handle_vmwrite(struct kvm_vcpu *vcpu)
8776 if (!nested_vmx_check_permission(vcpu)) 9197 if (!nested_vmx_check_permission(vcpu))
8777 return 1; 9198 return 1;
8778 9199
8779 if (!nested_vmx_check_vmcs12(vcpu)) 9200 if (vmx->nested.current_vmptr == -1ull)
8780 return kvm_skip_emulated_instruction(vcpu); 9201 return nested_vmx_failInvalid(vcpu);
8781 9202
8782 if (vmx_instruction_info & (1u << 10)) 9203 if (vmx_instruction_info & (1u << 10))
8783 field_value = kvm_register_readl(vcpu, 9204 field_value = kvm_register_readl(vcpu,
@@ -8800,11 +9221,9 @@ static int handle_vmwrite(struct kvm_vcpu *vcpu)
8800 * VMCS," then the "read-only" fields are actually read/write. 9221 * VMCS," then the "read-only" fields are actually read/write.
8801 */ 9222 */
8802 if (vmcs_field_readonly(field) && 9223 if (vmcs_field_readonly(field) &&
8803 !nested_cpu_has_vmwrite_any_field(vcpu)) { 9224 !nested_cpu_has_vmwrite_any_field(vcpu))
8804 nested_vmx_failValid(vcpu, 9225 return nested_vmx_failValid(vcpu,
8805 VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT); 9226 VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
8806 return kvm_skip_emulated_instruction(vcpu);
8807 }
8808 9227
8809 if (!is_guest_mode(vcpu)) 9228 if (!is_guest_mode(vcpu))
8810 vmcs12 = get_vmcs12(vcpu); 9229 vmcs12 = get_vmcs12(vcpu);
@@ -8813,18 +9232,14 @@ static int handle_vmwrite(struct kvm_vcpu *vcpu)
8813 * When vmcs->vmcs_link_pointer is -1ull, any VMWRITE 9232 * When vmcs->vmcs_link_pointer is -1ull, any VMWRITE
8814 * to shadowed-field sets the ALU flags for VMfailInvalid. 9233 * to shadowed-field sets the ALU flags for VMfailInvalid.
8815 */ 9234 */
8816 if (get_vmcs12(vcpu)->vmcs_link_pointer == -1ull) { 9235 if (get_vmcs12(vcpu)->vmcs_link_pointer == -1ull)
8817 nested_vmx_failInvalid(vcpu); 9236 return nested_vmx_failInvalid(vcpu);
8818 return kvm_skip_emulated_instruction(vcpu);
8819 }
8820 vmcs12 = get_shadow_vmcs12(vcpu); 9237 vmcs12 = get_shadow_vmcs12(vcpu);
8821
8822 } 9238 }
8823 9239
8824 if (vmcs12_write_any(vmcs12, field, field_value) < 0) { 9240 if (vmcs12_write_any(vmcs12, field, field_value) < 0)
8825 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT); 9241 return nested_vmx_failValid(vcpu,
8826 return kvm_skip_emulated_instruction(vcpu); 9242 VMXERR_UNSUPPORTED_VMCS_COMPONENT);
8827 }
8828 9243
8829 /* 9244 /*
8830 * Do not track vmcs12 dirty-state if in guest-mode 9245 * Do not track vmcs12 dirty-state if in guest-mode
@@ -8846,8 +9261,7 @@ static int handle_vmwrite(struct kvm_vcpu *vcpu)
8846 } 9261 }
8847 } 9262 }
8848 9263
8849 nested_vmx_succeed(vcpu); 9264 return nested_vmx_succeed(vcpu);
8850 return kvm_skip_emulated_instruction(vcpu);
8851} 9265}
8852 9266
8853static void set_current_vmptr(struct vcpu_vmx *vmx, gpa_t vmptr) 9267static void set_current_vmptr(struct vcpu_vmx *vmx, gpa_t vmptr)
@@ -8858,7 +9272,7 @@ static void set_current_vmptr(struct vcpu_vmx *vmx, gpa_t vmptr)
8858 SECONDARY_EXEC_SHADOW_VMCS); 9272 SECONDARY_EXEC_SHADOW_VMCS);
8859 vmcs_write64(VMCS_LINK_POINTER, 9273 vmcs_write64(VMCS_LINK_POINTER,
8860 __pa(vmx->vmcs01.shadow_vmcs)); 9274 __pa(vmx->vmcs01.shadow_vmcs));
8861 vmx->nested.sync_shadow_vmcs = true; 9275 vmx->nested.need_vmcs12_sync = true;
8862 } 9276 }
8863 vmx->nested.dirty_vmcs12 = true; 9277 vmx->nested.dirty_vmcs12 = true;
8864} 9278}
@@ -8875,36 +9289,37 @@ static int handle_vmptrld(struct kvm_vcpu *vcpu)
8875 if (nested_vmx_get_vmptr(vcpu, &vmptr)) 9289 if (nested_vmx_get_vmptr(vcpu, &vmptr))
8876 return 1; 9290 return 1;
8877 9291
8878 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) { 9292 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu)))
8879 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_INVALID_ADDRESS); 9293 return nested_vmx_failValid(vcpu,
8880 return kvm_skip_emulated_instruction(vcpu); 9294 VMXERR_VMPTRLD_INVALID_ADDRESS);
8881 }
8882 9295
8883 if (vmptr == vmx->nested.vmxon_ptr) { 9296 if (vmptr == vmx->nested.vmxon_ptr)
8884 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_VMXON_POINTER); 9297 return nested_vmx_failValid(vcpu,
8885 return kvm_skip_emulated_instruction(vcpu); 9298 VMXERR_VMPTRLD_VMXON_POINTER);
8886 } 9299
9300 /* Forbid normal VMPTRLD if Enlightened version was used */
9301 if (vmx->nested.hv_evmcs)
9302 return 1;
8887 9303
8888 if (vmx->nested.current_vmptr != vmptr) { 9304 if (vmx->nested.current_vmptr != vmptr) {
8889 struct vmcs12 *new_vmcs12; 9305 struct vmcs12 *new_vmcs12;
8890 struct page *page; 9306 struct page *page;
8891 page = kvm_vcpu_gpa_to_page(vcpu, vmptr); 9307 page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
8892 if (is_error_page(page)) { 9308 if (is_error_page(page))
8893 nested_vmx_failInvalid(vcpu); 9309 return nested_vmx_failInvalid(vcpu);
8894 return kvm_skip_emulated_instruction(vcpu); 9310
8895 }
8896 new_vmcs12 = kmap(page); 9311 new_vmcs12 = kmap(page);
8897 if (new_vmcs12->hdr.revision_id != VMCS12_REVISION || 9312 if (new_vmcs12->hdr.revision_id != VMCS12_REVISION ||
8898 (new_vmcs12->hdr.shadow_vmcs && 9313 (new_vmcs12->hdr.shadow_vmcs &&
8899 !nested_cpu_has_vmx_shadow_vmcs(vcpu))) { 9314 !nested_cpu_has_vmx_shadow_vmcs(vcpu))) {
8900 kunmap(page); 9315 kunmap(page);
8901 kvm_release_page_clean(page); 9316 kvm_release_page_clean(page);
8902 nested_vmx_failValid(vcpu, 9317 return nested_vmx_failValid(vcpu,
8903 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID); 9318 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
8904 return kvm_skip_emulated_instruction(vcpu);
8905 } 9319 }
8906 9320
8907 nested_release_vmcs12(vmx); 9321 nested_release_vmcs12(vcpu);
9322
8908 /* 9323 /*
8909 * Load VMCS12 from guest memory since it is not already 9324 * Load VMCS12 from guest memory since it is not already
8910 * cached. 9325 * cached.
@@ -8916,8 +9331,71 @@ static int handle_vmptrld(struct kvm_vcpu *vcpu)
8916 set_current_vmptr(vmx, vmptr); 9331 set_current_vmptr(vmx, vmptr);
8917 } 9332 }
8918 9333
8919 nested_vmx_succeed(vcpu); 9334 return nested_vmx_succeed(vcpu);
8920 return kvm_skip_emulated_instruction(vcpu); 9335}
9336
9337/*
9338 * This is an equivalent of the nested hypervisor executing the vmptrld
9339 * instruction.
9340 */
9341static int nested_vmx_handle_enlightened_vmptrld(struct kvm_vcpu *vcpu,
9342 bool from_launch)
9343{
9344 struct vcpu_vmx *vmx = to_vmx(vcpu);
9345 struct hv_vp_assist_page assist_page;
9346
9347 if (likely(!vmx->nested.enlightened_vmcs_enabled))
9348 return 1;
9349
9350 if (unlikely(!kvm_hv_get_assist_page(vcpu, &assist_page)))
9351 return 1;
9352
9353 if (unlikely(!assist_page.enlighten_vmentry))
9354 return 1;
9355
9356 if (unlikely(assist_page.current_nested_vmcs !=
9357 vmx->nested.hv_evmcs_vmptr)) {
9358
9359 if (!vmx->nested.hv_evmcs)
9360 vmx->nested.current_vmptr = -1ull;
9361
9362 nested_release_evmcs(vcpu);
9363
9364 vmx->nested.hv_evmcs_page = kvm_vcpu_gpa_to_page(
9365 vcpu, assist_page.current_nested_vmcs);
9366
9367 if (unlikely(is_error_page(vmx->nested.hv_evmcs_page)))
9368 return 0;
9369
9370 vmx->nested.hv_evmcs = kmap(vmx->nested.hv_evmcs_page);
9371
9372 if (vmx->nested.hv_evmcs->revision_id != VMCS12_REVISION) {
9373 nested_release_evmcs(vcpu);
9374 return 0;
9375 }
9376
9377 vmx->nested.dirty_vmcs12 = true;
9378 /*
9379 * As we keep L2 state for one guest only 'hv_clean_fields' mask
9380 * can't be used when we switch between them. Reset it here for
9381 * simplicity.
9382 */
9383 vmx->nested.hv_evmcs->hv_clean_fields &=
9384 ~HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
9385 vmx->nested.hv_evmcs_vmptr = assist_page.current_nested_vmcs;
9386
9387 /*
9388 * Unlike normal vmcs12, enlightened vmcs12 is not fully
9389 * reloaded from guest's memory (read only fields, fields not
9390 * present in struct hv_enlightened_vmcs, ...). Make sure there
9391 * are no leftovers.
9392 */
9393 if (from_launch)
9394 memset(vmx->nested.cached_vmcs12, 0,
9395 sizeof(*vmx->nested.cached_vmcs12));
9396
9397 }
9398 return 1;
8921} 9399}
8922 9400
8923/* Emulate the VMPTRST instruction */ 9401/* Emulate the VMPTRST instruction */
@@ -8932,6 +9410,9 @@ static int handle_vmptrst(struct kvm_vcpu *vcpu)
8932 if (!nested_vmx_check_permission(vcpu)) 9410 if (!nested_vmx_check_permission(vcpu))
8933 return 1; 9411 return 1;
8934 9412
9413 if (unlikely(to_vmx(vcpu)->nested.hv_evmcs))
9414 return 1;
9415
8935 if (get_vmx_mem_address(vcpu, exit_qual, instr_info, true, &gva)) 9416 if (get_vmx_mem_address(vcpu, exit_qual, instr_info, true, &gva))
8936 return 1; 9417 return 1;
8937 /* *_system ok, nested_vmx_check_permission has verified cpl=0 */ 9418 /* *_system ok, nested_vmx_check_permission has verified cpl=0 */
@@ -8940,8 +9421,7 @@ static int handle_vmptrst(struct kvm_vcpu *vcpu)
8940 kvm_inject_page_fault(vcpu, &e); 9421 kvm_inject_page_fault(vcpu, &e);
8941 return 1; 9422 return 1;
8942 } 9423 }
8943 nested_vmx_succeed(vcpu); 9424 return nested_vmx_succeed(vcpu);
8944 return kvm_skip_emulated_instruction(vcpu);
8945} 9425}
8946 9426
8947/* Emulate the INVEPT instruction */ 9427/* Emulate the INVEPT instruction */
@@ -8971,11 +9451,9 @@ static int handle_invept(struct kvm_vcpu *vcpu)
8971 9451
8972 types = (vmx->nested.msrs.ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6; 9452 types = (vmx->nested.msrs.ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
8973 9453
8974 if (type >= 32 || !(types & (1 << type))) { 9454 if (type >= 32 || !(types & (1 << type)))
8975 nested_vmx_failValid(vcpu, 9455 return nested_vmx_failValid(vcpu,
8976 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID); 9456 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
8977 return kvm_skip_emulated_instruction(vcpu);
8978 }
8979 9457
8980 /* According to the Intel VMX instruction reference, the memory 9458 /* According to the Intel VMX instruction reference, the memory
8981 * operand is read even if it isn't needed (e.g., for type==global) 9459 * operand is read even if it isn't needed (e.g., for type==global)
@@ -8997,14 +9475,20 @@ static int handle_invept(struct kvm_vcpu *vcpu)
8997 case VMX_EPT_EXTENT_CONTEXT: 9475 case VMX_EPT_EXTENT_CONTEXT:
8998 kvm_mmu_sync_roots(vcpu); 9476 kvm_mmu_sync_roots(vcpu);
8999 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu); 9477 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
9000 nested_vmx_succeed(vcpu);
9001 break; 9478 break;
9002 default: 9479 default:
9003 BUG_ON(1); 9480 BUG_ON(1);
9004 break; 9481 break;
9005 } 9482 }
9006 9483
9007 return kvm_skip_emulated_instruction(vcpu); 9484 return nested_vmx_succeed(vcpu);
9485}
9486
9487static u16 nested_get_vpid02(struct kvm_vcpu *vcpu)
9488{
9489 struct vcpu_vmx *vmx = to_vmx(vcpu);
9490
9491 return vmx->nested.vpid02 ? vmx->nested.vpid02 : vmx->vpid;
9008} 9492}
9009 9493
9010static int handle_invvpid(struct kvm_vcpu *vcpu) 9494static int handle_invvpid(struct kvm_vcpu *vcpu)
@@ -9018,6 +9502,7 @@ static int handle_invvpid(struct kvm_vcpu *vcpu)
9018 u64 vpid; 9502 u64 vpid;
9019 u64 gla; 9503 u64 gla;
9020 } operand; 9504 } operand;
9505 u16 vpid02;
9021 9506
9022 if (!(vmx->nested.msrs.secondary_ctls_high & 9507 if (!(vmx->nested.msrs.secondary_ctls_high &
9023 SECONDARY_EXEC_ENABLE_VPID) || 9508 SECONDARY_EXEC_ENABLE_VPID) ||
@@ -9035,11 +9520,9 @@ static int handle_invvpid(struct kvm_vcpu *vcpu)
9035 types = (vmx->nested.msrs.vpid_caps & 9520 types = (vmx->nested.msrs.vpid_caps &
9036 VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8; 9521 VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
9037 9522
9038 if (type >= 32 || !(types & (1 << type))) { 9523 if (type >= 32 || !(types & (1 << type)))
9039 nested_vmx_failValid(vcpu, 9524 return nested_vmx_failValid(vcpu,
9040 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID); 9525 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9041 return kvm_skip_emulated_instruction(vcpu);
9042 }
9043 9526
9044 /* according to the intel vmx instruction reference, the memory 9527 /* according to the intel vmx instruction reference, the memory
9045 * operand is read even if it isn't needed (e.g., for type==global) 9528 * operand is read even if it isn't needed (e.g., for type==global)
@@ -9051,47 +9534,39 @@ static int handle_invvpid(struct kvm_vcpu *vcpu)
9051 kvm_inject_page_fault(vcpu, &e); 9534 kvm_inject_page_fault(vcpu, &e);
9052 return 1; 9535 return 1;
9053 } 9536 }
9054 if (operand.vpid >> 16) { 9537 if (operand.vpid >> 16)
9055 nested_vmx_failValid(vcpu, 9538 return nested_vmx_failValid(vcpu,
9056 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID); 9539 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9057 return kvm_skip_emulated_instruction(vcpu);
9058 }
9059 9540
9541 vpid02 = nested_get_vpid02(vcpu);
9060 switch (type) { 9542 switch (type) {
9061 case VMX_VPID_EXTENT_INDIVIDUAL_ADDR: 9543 case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
9062 if (!operand.vpid || 9544 if (!operand.vpid ||
9063 is_noncanonical_address(operand.gla, vcpu)) { 9545 is_noncanonical_address(operand.gla, vcpu))
9064 nested_vmx_failValid(vcpu, 9546 return nested_vmx_failValid(vcpu,
9065 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID); 9547 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9066 return kvm_skip_emulated_instruction(vcpu); 9548 if (cpu_has_vmx_invvpid_individual_addr()) {
9067 }
9068 if (cpu_has_vmx_invvpid_individual_addr() &&
9069 vmx->nested.vpid02) {
9070 __invvpid(VMX_VPID_EXTENT_INDIVIDUAL_ADDR, 9549 __invvpid(VMX_VPID_EXTENT_INDIVIDUAL_ADDR,
9071 vmx->nested.vpid02, operand.gla); 9550 vpid02, operand.gla);
9072 } else 9551 } else
9073 __vmx_flush_tlb(vcpu, vmx->nested.vpid02, true); 9552 __vmx_flush_tlb(vcpu, vpid02, false);
9074 break; 9553 break;
9075 case VMX_VPID_EXTENT_SINGLE_CONTEXT: 9554 case VMX_VPID_EXTENT_SINGLE_CONTEXT:
9076 case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL: 9555 case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
9077 if (!operand.vpid) { 9556 if (!operand.vpid)
9078 nested_vmx_failValid(vcpu, 9557 return nested_vmx_failValid(vcpu,
9079 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID); 9558 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9080 return kvm_skip_emulated_instruction(vcpu); 9559 __vmx_flush_tlb(vcpu, vpid02, false);
9081 }
9082 __vmx_flush_tlb(vcpu, vmx->nested.vpid02, true);
9083 break; 9560 break;
9084 case VMX_VPID_EXTENT_ALL_CONTEXT: 9561 case VMX_VPID_EXTENT_ALL_CONTEXT:
9085 __vmx_flush_tlb(vcpu, vmx->nested.vpid02, true); 9562 __vmx_flush_tlb(vcpu, vpid02, false);
9086 break; 9563 break;
9087 default: 9564 default:
9088 WARN_ON_ONCE(1); 9565 WARN_ON_ONCE(1);
9089 return kvm_skip_emulated_instruction(vcpu); 9566 return kvm_skip_emulated_instruction(vcpu);
9090 } 9567 }
9091 9568
9092 nested_vmx_succeed(vcpu); 9569 return nested_vmx_succeed(vcpu);
9093
9094 return kvm_skip_emulated_instruction(vcpu);
9095} 9570}
9096 9571
9097static int handle_invpcid(struct kvm_vcpu *vcpu) 9572static int handle_invpcid(struct kvm_vcpu *vcpu)
@@ -9162,11 +9637,11 @@ static int handle_invpcid(struct kvm_vcpu *vcpu)
9162 } 9637 }
9163 9638
9164 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) 9639 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
9165 if (kvm_get_pcid(vcpu, vcpu->arch.mmu.prev_roots[i].cr3) 9640 if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].cr3)
9166 == operand.pcid) 9641 == operand.pcid)
9167 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i); 9642 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
9168 9643
9169 kvm_mmu_free_roots(vcpu, roots_to_free); 9644 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
9170 /* 9645 /*
9171 * If neither the current cr3 nor any of the prev_roots use the 9646 * If neither the current cr3 nor any of the prev_roots use the
9172 * given PCID, then nothing needs to be done here because a 9647 * given PCID, then nothing needs to be done here because a
@@ -9293,7 +9768,7 @@ static int nested_vmx_eptp_switching(struct kvm_vcpu *vcpu,
9293 9768
9294 kvm_mmu_unload(vcpu); 9769 kvm_mmu_unload(vcpu);
9295 mmu->ept_ad = accessed_dirty; 9770 mmu->ept_ad = accessed_dirty;
9296 mmu->base_role.ad_disabled = !accessed_dirty; 9771 mmu->mmu_role.base.ad_disabled = !accessed_dirty;
9297 vmcs12->ept_pointer = address; 9772 vmcs12->ept_pointer = address;
9298 /* 9773 /*
9299 * TODO: Check what's the correct approach in case 9774 * TODO: Check what's the correct approach in case
@@ -9652,9 +10127,6 @@ static bool nested_vmx_exit_reflected(struct kvm_vcpu *vcpu, u32 exit_reason)
9652 return false; 10127 return false;
9653 else if (is_page_fault(intr_info)) 10128 else if (is_page_fault(intr_info))
9654 return !vmx->vcpu.arch.apf.host_apf_reason && enable_ept; 10129 return !vmx->vcpu.arch.apf.host_apf_reason && enable_ept;
9655 else if (is_no_device(intr_info) &&
9656 !(vmcs12->guest_cr0 & X86_CR0_TS))
9657 return false;
9658 else if (is_debug(intr_info) && 10130 else if (is_debug(intr_info) &&
9659 vcpu->guest_debug & 10131 vcpu->guest_debug &
9660 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) 10132 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
@@ -10676,9 +11148,25 @@ static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
10676 vmcs_write32(PLE_WINDOW, vmx->ple_window); 11148 vmcs_write32(PLE_WINDOW, vmx->ple_window);
10677 } 11149 }
10678 11150
10679 if (vmx->nested.sync_shadow_vmcs) { 11151 if (vmx->nested.need_vmcs12_sync) {
10680 copy_vmcs12_to_shadow(vmx); 11152 /*
10681 vmx->nested.sync_shadow_vmcs = false; 11153 * hv_evmcs may end up being not mapped after migration (when
11154 * L2 was running), map it here to make sure vmcs12 changes are
11155 * properly reflected.
11156 */
11157 if (vmx->nested.enlightened_vmcs_enabled &&
11158 !vmx->nested.hv_evmcs)
11159 nested_vmx_handle_enlightened_vmptrld(vcpu, false);
11160
11161 if (vmx->nested.hv_evmcs) {
11162 copy_vmcs12_to_enlightened(vmx);
11163 /* All fields are clean */
11164 vmx->nested.hv_evmcs->hv_clean_fields |=
11165 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
11166 } else {
11167 copy_vmcs12_to_shadow(vmx);
11168 }
11169 vmx->nested.need_vmcs12_sync = false;
10682 } 11170 }
10683 11171
10684 if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty)) 11172 if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
@@ -10745,7 +11233,7 @@ static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
10745 "mov %%" _ASM_SP ", (%%" _ASM_SI ") \n\t" 11233 "mov %%" _ASM_SP ", (%%" _ASM_SI ") \n\t"
10746 "jmp 1f \n\t" 11234 "jmp 1f \n\t"
10747 "2: \n\t" 11235 "2: \n\t"
10748 __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t" 11236 __ex("vmwrite %%" _ASM_SP ", %%" _ASM_DX) "\n\t"
10749 "1: \n\t" 11237 "1: \n\t"
10750 /* Reload cr2 if changed */ 11238 /* Reload cr2 if changed */
10751 "mov %c[cr2](%0), %%" _ASM_AX " \n\t" 11239 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
@@ -10777,9 +11265,9 @@ static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
10777 11265
10778 /* Enter guest mode */ 11266 /* Enter guest mode */
10779 "jne 1f \n\t" 11267 "jne 1f \n\t"
10780 __ex(ASM_VMX_VMLAUNCH) "\n\t" 11268 __ex("vmlaunch") "\n\t"
10781 "jmp 2f \n\t" 11269 "jmp 2f \n\t"
10782 "1: " __ex(ASM_VMX_VMRESUME) "\n\t" 11270 "1: " __ex("vmresume") "\n\t"
10783 "2: " 11271 "2: "
10784 /* Save guest registers, load host registers, keep flags */ 11272 /* Save guest registers, load host registers, keep flags */
10785 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t" 11273 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
@@ -10801,6 +11289,10 @@ static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
10801 "mov %%r13, %c[r13](%0) \n\t" 11289 "mov %%r13, %c[r13](%0) \n\t"
10802 "mov %%r14, %c[r14](%0) \n\t" 11290 "mov %%r14, %c[r14](%0) \n\t"
10803 "mov %%r15, %c[r15](%0) \n\t" 11291 "mov %%r15, %c[r15](%0) \n\t"
11292 /*
11293 * Clear host registers marked as clobbered to prevent
11294 * speculative use.
11295 */
10804 "xor %%r8d, %%r8d \n\t" 11296 "xor %%r8d, %%r8d \n\t"
10805 "xor %%r9d, %%r9d \n\t" 11297 "xor %%r9d, %%r9d \n\t"
10806 "xor %%r10d, %%r10d \n\t" 11298 "xor %%r10d, %%r10d \n\t"
@@ -10958,6 +11450,10 @@ static void vmx_switch_vmcs(struct kvm_vcpu *vcpu, struct loaded_vmcs *vmcs)
10958 vmx->loaded_vmcs = vmcs; 11450 vmx->loaded_vmcs = vmcs;
10959 vmx_vcpu_load(vcpu, cpu); 11451 vmx_vcpu_load(vcpu, cpu);
10960 put_cpu(); 11452 put_cpu();
11453
11454 vm_entry_controls_reset_shadow(vmx);
11455 vm_exit_controls_reset_shadow(vmx);
11456 vmx_segment_cache_clear(vmx);
10961} 11457}
10962 11458
10963/* 11459/*
@@ -10966,12 +11462,10 @@ static void vmx_switch_vmcs(struct kvm_vcpu *vcpu, struct loaded_vmcs *vmcs)
10966 */ 11462 */
10967static void vmx_free_vcpu_nested(struct kvm_vcpu *vcpu) 11463static void vmx_free_vcpu_nested(struct kvm_vcpu *vcpu)
10968{ 11464{
10969 struct vcpu_vmx *vmx = to_vmx(vcpu); 11465 vcpu_load(vcpu);
10970 11466 vmx_switch_vmcs(vcpu, &to_vmx(vcpu)->vmcs01);
10971 vcpu_load(vcpu); 11467 free_nested(vcpu);
10972 vmx_switch_vmcs(vcpu, &vmx->vmcs01); 11468 vcpu_put(vcpu);
10973 free_nested(vmx);
10974 vcpu_put(vcpu);
10975} 11469}
10976 11470
10977static void vmx_free_vcpu(struct kvm_vcpu *vcpu) 11471static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
@@ -11334,28 +11828,28 @@ static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
11334 return get_vmcs12(vcpu)->ept_pointer; 11828 return get_vmcs12(vcpu)->ept_pointer;
11335} 11829}
11336 11830
11337static int nested_ept_init_mmu_context(struct kvm_vcpu *vcpu) 11831static void nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
11338{ 11832{
11339 WARN_ON(mmu_is_nested(vcpu)); 11833 WARN_ON(mmu_is_nested(vcpu));
11340 if (!valid_ept_address(vcpu, nested_ept_get_cr3(vcpu)))
11341 return 1;
11342 11834
11835 vcpu->arch.mmu = &vcpu->arch.guest_mmu;
11343 kvm_init_shadow_ept_mmu(vcpu, 11836 kvm_init_shadow_ept_mmu(vcpu,
11344 to_vmx(vcpu)->nested.msrs.ept_caps & 11837 to_vmx(vcpu)->nested.msrs.ept_caps &
11345 VMX_EPT_EXECUTE_ONLY_BIT, 11838 VMX_EPT_EXECUTE_ONLY_BIT,
11346 nested_ept_ad_enabled(vcpu), 11839 nested_ept_ad_enabled(vcpu),
11347 nested_ept_get_cr3(vcpu)); 11840 nested_ept_get_cr3(vcpu));
11348 vcpu->arch.mmu.set_cr3 = vmx_set_cr3; 11841 vcpu->arch.mmu->set_cr3 = vmx_set_cr3;
11349 vcpu->arch.mmu.get_cr3 = nested_ept_get_cr3; 11842 vcpu->arch.mmu->get_cr3 = nested_ept_get_cr3;
11350 vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault; 11843 vcpu->arch.mmu->inject_page_fault = nested_ept_inject_page_fault;
11844 vcpu->arch.mmu->get_pdptr = kvm_pdptr_read;
11351 11845
11352 vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu; 11846 vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
11353 return 0;
11354} 11847}
11355 11848
11356static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu) 11849static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
11357{ 11850{
11358 vcpu->arch.walk_mmu = &vcpu->arch.mmu; 11851 vcpu->arch.mmu = &vcpu->arch.root_mmu;
11852 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
11359} 11853}
11360 11854
11361static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12, 11855static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
@@ -11716,7 +12210,7 @@ static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
11716 !nested_exit_intr_ack_set(vcpu) || 12210 !nested_exit_intr_ack_set(vcpu) ||
11717 (vmcs12->posted_intr_nv & 0xff00) || 12211 (vmcs12->posted_intr_nv & 0xff00) ||
11718 (vmcs12->posted_intr_desc_addr & 0x3f) || 12212 (vmcs12->posted_intr_desc_addr & 0x3f) ||
11719 (!page_address_valid(vcpu, vmcs12->posted_intr_desc_addr)))) 12213 (vmcs12->posted_intr_desc_addr >> cpuid_maxphyaddr(vcpu))))
11720 return -EINVAL; 12214 return -EINVAL;
11721 12215
11722 /* tpr shadow is needed by all apicv features. */ 12216 /* tpr shadow is needed by all apicv features. */
@@ -11772,15 +12266,12 @@ static int nested_vmx_check_msr_switch_controls(struct kvm_vcpu *vcpu,
11772static int nested_vmx_check_pml_controls(struct kvm_vcpu *vcpu, 12266static int nested_vmx_check_pml_controls(struct kvm_vcpu *vcpu,
11773 struct vmcs12 *vmcs12) 12267 struct vmcs12 *vmcs12)
11774{ 12268{
11775 u64 address = vmcs12->pml_address; 12269 if (!nested_cpu_has_pml(vmcs12))
11776 int maxphyaddr = cpuid_maxphyaddr(vcpu); 12270 return 0;
11777 12271
11778 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML)) { 12272 if (!nested_cpu_has_ept(vmcs12) ||
11779 if (!nested_cpu_has_ept(vmcs12) || 12273 !page_address_valid(vcpu, vmcs12->pml_address))
11780 !IS_ALIGNED(address, 4096) || 12274 return -EINVAL;
11781 address >> maxphyaddr)
11782 return -EINVAL;
11783 }
11784 12275
11785 return 0; 12276 return 0;
11786} 12277}
@@ -11960,112 +12451,87 @@ static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3, bool ne
11960 return 0; 12451 return 0;
11961} 12452}
11962 12453
11963static void prepare_vmcs02_full(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12) 12454/*
12455 * Returns if KVM is able to config CPU to tag TLB entries
12456 * populated by L2 differently than TLB entries populated
12457 * by L1.
12458 *
12459 * If L1 uses EPT, then TLB entries are tagged with different EPTP.
12460 *
12461 * If L1 uses VPID and we allocated a vpid02, TLB entries are tagged
12462 * with different VPID (L1 entries are tagged with vmx->vpid
12463 * while L2 entries are tagged with vmx->nested.vpid02).
12464 */
12465static bool nested_has_guest_tlb_tag(struct kvm_vcpu *vcpu)
11964{ 12466{
11965 struct vcpu_vmx *vmx = to_vmx(vcpu); 12467 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11966 12468
11967 vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector); 12469 return nested_cpu_has_ept(vmcs12) ||
11968 vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector); 12470 (nested_cpu_has_vpid(vmcs12) && to_vmx(vcpu)->nested.vpid02);
11969 vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector); 12471}
11970 vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
11971 vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
11972 vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
11973 vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
11974 vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
11975 vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
11976 vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
11977 vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
11978 vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
11979 vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
11980 vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
11981 vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
11982 vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
11983 vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
11984 vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
11985 vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
11986 vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
11987 vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
11988 vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
11989 vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
11990 vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
11991 vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
11992 vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
11993 vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
11994 vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
11995 vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
11996 vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
11997 vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
11998
11999 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
12000 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
12001 vmcs12->guest_pending_dbg_exceptions);
12002 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
12003 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
12004 12472
12005 if (nested_cpu_has_xsaves(vmcs12)) 12473static u64 nested_vmx_calc_efer(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
12006 vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap); 12474{
12007 vmcs_write64(VMCS_LINK_POINTER, -1ull); 12475 if (vmx->nested.nested_run_pending &&
12476 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
12477 return vmcs12->guest_ia32_efer;
12478 else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
12479 return vmx->vcpu.arch.efer | (EFER_LMA | EFER_LME);
12480 else
12481 return vmx->vcpu.arch.efer & ~(EFER_LMA | EFER_LME);
12482}
12008 12483
12009 if (cpu_has_vmx_posted_intr()) 12484static void prepare_vmcs02_constant_state(struct vcpu_vmx *vmx)
12010 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR); 12485{
12486 /*
12487 * If vmcs02 hasn't been initialized, set the constant vmcs02 state
12488 * according to L0's settings (vmcs12 is irrelevant here). Host
12489 * fields that come from L0 and are not constant, e.g. HOST_CR3,
12490 * will be set as needed prior to VMLAUNCH/VMRESUME.
12491 */
12492 if (vmx->nested.vmcs02_initialized)
12493 return;
12494 vmx->nested.vmcs02_initialized = true;
12011 12495
12012 /* 12496 /*
12013 * Whether page-faults are trapped is determined by a combination of 12497 * We don't care what the EPTP value is we just need to guarantee
12014 * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF. 12498 * it's valid so we don't get a false positive when doing early
12015 * If enable_ept, L0 doesn't care about page faults and we should 12499 * consistency checks.
12016 * set all of these to L1's desires. However, if !enable_ept, L0 does
12017 * care about (at least some) page faults, and because it is not easy
12018 * (if at all possible?) to merge L0 and L1's desires, we simply ask
12019 * to exit on each and every L2 page fault. This is done by setting
12020 * MASK=MATCH=0 and (see below) EB.PF=1.
12021 * Note that below we don't need special code to set EB.PF beyond the
12022 * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
12023 * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
12024 * !enable_ept, EB.PF is 1, so the "or" will always be 1.
12025 */ 12500 */
12026 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 12501 if (enable_ept && nested_early_check)
12027 enable_ept ? vmcs12->page_fault_error_code_mask : 0); 12502 vmcs_write64(EPT_POINTER, construct_eptp(&vmx->vcpu, 0));
12028 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
12029 enable_ept ? vmcs12->page_fault_error_code_match : 0);
12030 12503
12031 /* All VMFUNCs are currently emulated through L0 vmexits. */ 12504 /* All VMFUNCs are currently emulated through L0 vmexits. */
12032 if (cpu_has_vmx_vmfunc()) 12505 if (cpu_has_vmx_vmfunc())
12033 vmcs_write64(VM_FUNCTION_CONTROL, 0); 12506 vmcs_write64(VM_FUNCTION_CONTROL, 0);
12034 12507
12035 if (cpu_has_vmx_apicv()) { 12508 if (cpu_has_vmx_posted_intr())
12036 vmcs_write64(EOI_EXIT_BITMAP0, vmcs12->eoi_exit_bitmap0); 12509 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
12037 vmcs_write64(EOI_EXIT_BITMAP1, vmcs12->eoi_exit_bitmap1);
12038 vmcs_write64(EOI_EXIT_BITMAP2, vmcs12->eoi_exit_bitmap2);
12039 vmcs_write64(EOI_EXIT_BITMAP3, vmcs12->eoi_exit_bitmap3);
12040 }
12041 12510
12042 /* 12511 if (cpu_has_vmx_msr_bitmap())
12043 * Set host-state according to L0's settings (vmcs12 is irrelevant here) 12512 vmcs_write64(MSR_BITMAP, __pa(vmx->nested.vmcs02.msr_bitmap));
12044 * Some constant fields are set here by vmx_set_constant_host_state(). 12513
12045 * Other fields are different per CPU, and will be set later when 12514 if (enable_pml)
12046 * vmx_vcpu_load() is called, and when vmx_prepare_switch_to_guest() 12515 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
12047 * is called.
12048 */
12049 vmx_set_constant_host_state(vmx);
12050 12516
12051 /* 12517 /*
12052 * Set the MSR load/store lists to match L0's settings. 12518 * Set the MSR load/store lists to match L0's settings. Only the
12519 * addresses are constant (for vmcs02), the counts can change based
12520 * on L2's behavior, e.g. switching to/from long mode.
12053 */ 12521 */
12054 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0); 12522 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
12055 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
12056 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val)); 12523 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
12057 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
12058 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val)); 12524 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
12059 12525
12060 set_cr4_guest_host_mask(vmx); 12526 vmx_set_constant_host_state(vmx);
12527}
12061 12528
12062 if (kvm_mpx_supported()) { 12529static void prepare_vmcs02_early_full(struct vcpu_vmx *vmx,
12063 if (vmx->nested.nested_run_pending && 12530 struct vmcs12 *vmcs12)
12064 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS)) 12531{
12065 vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs); 12532 prepare_vmcs02_constant_state(vmx);
12066 else 12533
12067 vmcs_write64(GUEST_BNDCFGS, vmx->nested.vmcs01_guest_bndcfgs); 12534 vmcs_write64(VMCS_LINK_POINTER, -1ull);
12068 }
12069 12535
12070 if (enable_vpid) { 12536 if (enable_vpid) {
12071 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02) 12537 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02)
@@ -12073,78 +12539,30 @@ static void prepare_vmcs02_full(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12073 else 12539 else
12074 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid); 12540 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
12075 } 12541 }
12076
12077 /*
12078 * L1 may access the L2's PDPTR, so save them to construct vmcs12
12079 */
12080 if (enable_ept) {
12081 vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
12082 vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
12083 vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
12084 vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
12085 }
12086
12087 if (cpu_has_vmx_msr_bitmap())
12088 vmcs_write64(MSR_BITMAP, __pa(vmx->nested.vmcs02.msr_bitmap));
12089} 12542}
12090 12543
12091/* 12544static void prepare_vmcs02_early(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
12092 * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
12093 * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
12094 * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
12095 * guest in a way that will both be appropriate to L1's requests, and our
12096 * needs. In addition to modifying the active vmcs (which is vmcs02), this
12097 * function also has additional necessary side-effects, like setting various
12098 * vcpu->arch fields.
12099 * Returns 0 on success, 1 on failure. Invalid state exit qualification code
12100 * is assigned to entry_failure_code on failure.
12101 */
12102static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12103 u32 *entry_failure_code)
12104{ 12545{
12105 struct vcpu_vmx *vmx = to_vmx(vcpu);
12106 u32 exec_control, vmcs12_exec_ctrl; 12546 u32 exec_control, vmcs12_exec_ctrl;
12547 u64 guest_efer = nested_vmx_calc_efer(vmx, vmcs12);
12107 12548
12108 if (vmx->nested.dirty_vmcs12) { 12549 if (vmx->nested.dirty_vmcs12 || vmx->nested.hv_evmcs)
12109 prepare_vmcs02_full(vcpu, vmcs12); 12550 prepare_vmcs02_early_full(vmx, vmcs12);
12110 vmx->nested.dirty_vmcs12 = false;
12111 }
12112 12551
12113 /* 12552 /*
12114 * First, the fields that are shadowed. This must be kept in sync 12553 * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
12115 * with vmx_shadow_fields.h. 12554 * entry, but only if the current (host) sp changed from the value
12555 * we wrote last (vmx->host_rsp). This cache is no longer relevant
12556 * if we switch vmcs, and rather than hold a separate cache per vmcs,
12557 * here we just force the write to happen on entry. host_rsp will
12558 * also be written unconditionally by nested_vmx_check_vmentry_hw()
12559 * if we are doing early consistency checks via hardware.
12116 */ 12560 */
12561 vmx->host_rsp = 0;
12117 12562
12118 vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector); 12563 /*
12119 vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit); 12564 * PIN CONTROLS
12120 vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes); 12565 */
12121 vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
12122 vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
12123
12124 if (vmx->nested.nested_run_pending &&
12125 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
12126 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
12127 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
12128 } else {
12129 kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
12130 vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
12131 }
12132 if (vmx->nested.nested_run_pending) {
12133 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
12134 vmcs12->vm_entry_intr_info_field);
12135 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
12136 vmcs12->vm_entry_exception_error_code);
12137 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
12138 vmcs12->vm_entry_instruction_len);
12139 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
12140 vmcs12->guest_interruptibility_info);
12141 vmx->loaded_vmcs->nmi_known_unmasked =
12142 !(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
12143 } else {
12144 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
12145 }
12146 vmx_set_rflags(vcpu, vmcs12->guest_rflags);
12147
12148 exec_control = vmcs12->pin_based_vm_exec_control; 12566 exec_control = vmcs12->pin_based_vm_exec_control;
12149 12567
12150 /* Preemption timer setting is computed directly in vmx_vcpu_run. */ 12568 /* Preemption timer setting is computed directly in vmx_vcpu_run. */
@@ -12159,13 +12577,43 @@ static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12159 } else { 12577 } else {
12160 exec_control &= ~PIN_BASED_POSTED_INTR; 12578 exec_control &= ~PIN_BASED_POSTED_INTR;
12161 } 12579 }
12162
12163 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control); 12580 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
12164 12581
12165 vmx->nested.preemption_timer_expired = false; 12582 /*
12166 if (nested_cpu_has_preemption_timer(vmcs12)) 12583 * EXEC CONTROLS
12167 vmx_start_preemption_timer(vcpu); 12584 */
12585 exec_control = vmx_exec_control(vmx); /* L0's desires */
12586 exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
12587 exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
12588 exec_control &= ~CPU_BASED_TPR_SHADOW;
12589 exec_control |= vmcs12->cpu_based_vm_exec_control;
12168 12590
12591 /*
12592 * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR. Later, if
12593 * nested_get_vmcs12_pages can't fix it up, the illegal value
12594 * will result in a VM entry failure.
12595 */
12596 if (exec_control & CPU_BASED_TPR_SHADOW) {
12597 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull);
12598 vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
12599 } else {
12600#ifdef CONFIG_X86_64
12601 exec_control |= CPU_BASED_CR8_LOAD_EXITING |
12602 CPU_BASED_CR8_STORE_EXITING;
12603#endif
12604 }
12605
12606 /*
12607 * A vmexit (to either L1 hypervisor or L0 userspace) is always needed
12608 * for I/O port accesses.
12609 */
12610 exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
12611 exec_control |= CPU_BASED_UNCOND_IO_EXITING;
12612 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
12613
12614 /*
12615 * SECONDARY EXEC CONTROLS
12616 */
12169 if (cpu_has_secondary_exec_ctrls()) { 12617 if (cpu_has_secondary_exec_ctrls()) {
12170 exec_control = vmx->secondary_exec_control; 12618 exec_control = vmx->secondary_exec_control;
12171 12619
@@ -12206,43 +12654,214 @@ static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12206 } 12654 }
12207 12655
12208 /* 12656 /*
12209 * HOST_RSP is normally set correctly in vmx_vcpu_run() just before 12657 * ENTRY CONTROLS
12210 * entry, but only if the current (host) sp changed from the value 12658 *
12211 * we wrote last (vmx->host_rsp). This cache is no longer relevant 12659 * vmcs12's VM_{ENTRY,EXIT}_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE
12212 * if we switch vmcs, and rather than hold a separate cache per vmcs, 12660 * are emulated by vmx_set_efer() in prepare_vmcs02(), but speculate
12213 * here we just force the write to happen on entry. 12661 * on the related bits (if supported by the CPU) in the hope that
12662 * we can avoid VMWrites during vmx_set_efer().
12663 */
12664 exec_control = (vmcs12->vm_entry_controls | vmcs_config.vmentry_ctrl) &
12665 ~VM_ENTRY_IA32E_MODE & ~VM_ENTRY_LOAD_IA32_EFER;
12666 if (cpu_has_load_ia32_efer) {
12667 if (guest_efer & EFER_LMA)
12668 exec_control |= VM_ENTRY_IA32E_MODE;
12669 if (guest_efer != host_efer)
12670 exec_control |= VM_ENTRY_LOAD_IA32_EFER;
12671 }
12672 vm_entry_controls_init(vmx, exec_control);
12673
12674 /*
12675 * EXIT CONTROLS
12676 *
12677 * L2->L1 exit controls are emulated - the hardware exit is to L0 so
12678 * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
12679 * bits may be modified by vmx_set_efer() in prepare_vmcs02().
12214 */ 12680 */
12215 vmx->host_rsp = 0; 12681 exec_control = vmcs_config.vmexit_ctrl;
12682 if (cpu_has_load_ia32_efer && guest_efer != host_efer)
12683 exec_control |= VM_EXIT_LOAD_IA32_EFER;
12684 vm_exit_controls_init(vmx, exec_control);
12216 12685
12217 exec_control = vmx_exec_control(vmx); /* L0's desires */ 12686 /*
12218 exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING; 12687 * Conceptually we want to copy the PML address and index from
12219 exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING; 12688 * vmcs01 here, and then back to vmcs01 on nested vmexit. But,
12220 exec_control &= ~CPU_BASED_TPR_SHADOW; 12689 * since we always flush the log on each vmexit and never change
12221 exec_control |= vmcs12->cpu_based_vm_exec_control; 12690 * the PML address (once set), this happens to be equivalent to
12691 * simply resetting the index in vmcs02.
12692 */
12693 if (enable_pml)
12694 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
12222 12695
12223 /* 12696 /*
12224 * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR. Later, if 12697 * Interrupt/Exception Fields
12225 * nested_get_vmcs12_pages can't fix it up, the illegal value
12226 * will result in a VM entry failure.
12227 */ 12698 */
12228 if (exec_control & CPU_BASED_TPR_SHADOW) { 12699 if (vmx->nested.nested_run_pending) {
12229 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull); 12700 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
12230 vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold); 12701 vmcs12->vm_entry_intr_info_field);
12702 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
12703 vmcs12->vm_entry_exception_error_code);
12704 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
12705 vmcs12->vm_entry_instruction_len);
12706 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
12707 vmcs12->guest_interruptibility_info);
12708 vmx->loaded_vmcs->nmi_known_unmasked =
12709 !(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
12231 } else { 12710 } else {
12232#ifdef CONFIG_X86_64 12711 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
12233 exec_control |= CPU_BASED_CR8_LOAD_EXITING |
12234 CPU_BASED_CR8_STORE_EXITING;
12235#endif
12236 } 12712 }
12713}
12714
12715static void prepare_vmcs02_full(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
12716{
12717 struct hv_enlightened_vmcs *hv_evmcs = vmx->nested.hv_evmcs;
12718
12719 if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
12720 HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP2)) {
12721 vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
12722 vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
12723 vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
12724 vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
12725 vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
12726 vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
12727 vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
12728 vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
12729 vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
12730 vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
12731 vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
12732 vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
12733 vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
12734 vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
12735 vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
12736 vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
12737 vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
12738 vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
12739 vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
12740 vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
12741 vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
12742 vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
12743 vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
12744 vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
12745 vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
12746 vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
12747 vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
12748 vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
12749 vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
12750 vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
12751 vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
12752 vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
12753 vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
12754 vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
12755 }
12756
12757 if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
12758 HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP1)) {
12759 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
12760 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
12761 vmcs12->guest_pending_dbg_exceptions);
12762 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
12763 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
12764
12765 /*
12766 * L1 may access the L2's PDPTR, so save them to construct
12767 * vmcs12
12768 */
12769 if (enable_ept) {
12770 vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
12771 vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
12772 vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
12773 vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
12774 }
12775 }
12776
12777 if (nested_cpu_has_xsaves(vmcs12))
12778 vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
12237 12779
12238 /* 12780 /*
12239 * A vmexit (to either L1 hypervisor or L0 userspace) is always needed 12781 * Whether page-faults are trapped is determined by a combination of
12240 * for I/O port accesses. 12782 * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
12783 * If enable_ept, L0 doesn't care about page faults and we should
12784 * set all of these to L1's desires. However, if !enable_ept, L0 does
12785 * care about (at least some) page faults, and because it is not easy
12786 * (if at all possible?) to merge L0 and L1's desires, we simply ask
12787 * to exit on each and every L2 page fault. This is done by setting
12788 * MASK=MATCH=0 and (see below) EB.PF=1.
12789 * Note that below we don't need special code to set EB.PF beyond the
12790 * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
12791 * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
12792 * !enable_ept, EB.PF is 1, so the "or" will always be 1.
12241 */ 12793 */
12242 exec_control &= ~CPU_BASED_USE_IO_BITMAPS; 12794 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
12243 exec_control |= CPU_BASED_UNCOND_IO_EXITING; 12795 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
12796 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
12797 enable_ept ? vmcs12->page_fault_error_code_match : 0);
12244 12798
12245 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control); 12799 if (cpu_has_vmx_apicv()) {
12800 vmcs_write64(EOI_EXIT_BITMAP0, vmcs12->eoi_exit_bitmap0);
12801 vmcs_write64(EOI_EXIT_BITMAP1, vmcs12->eoi_exit_bitmap1);
12802 vmcs_write64(EOI_EXIT_BITMAP2, vmcs12->eoi_exit_bitmap2);
12803 vmcs_write64(EOI_EXIT_BITMAP3, vmcs12->eoi_exit_bitmap3);
12804 }
12805
12806 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
12807 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
12808
12809 set_cr4_guest_host_mask(vmx);
12810
12811 if (kvm_mpx_supported()) {
12812 if (vmx->nested.nested_run_pending &&
12813 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
12814 vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
12815 else
12816 vmcs_write64(GUEST_BNDCFGS, vmx->nested.vmcs01_guest_bndcfgs);
12817 }
12818}
12819
12820/*
12821 * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
12822 * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
12823 * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
12824 * guest in a way that will both be appropriate to L1's requests, and our
12825 * needs. In addition to modifying the active vmcs (which is vmcs02), this
12826 * function also has additional necessary side-effects, like setting various
12827 * vcpu->arch fields.
12828 * Returns 0 on success, 1 on failure. Invalid state exit qualification code
12829 * is assigned to entry_failure_code on failure.
12830 */
12831static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12832 u32 *entry_failure_code)
12833{
12834 struct vcpu_vmx *vmx = to_vmx(vcpu);
12835 struct hv_enlightened_vmcs *hv_evmcs = vmx->nested.hv_evmcs;
12836
12837 if (vmx->nested.dirty_vmcs12 || vmx->nested.hv_evmcs) {
12838 prepare_vmcs02_full(vmx, vmcs12);
12839 vmx->nested.dirty_vmcs12 = false;
12840 }
12841
12842 /*
12843 * First, the fields that are shadowed. This must be kept in sync
12844 * with vmx_shadow_fields.h.
12845 */
12846 if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
12847 HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP2)) {
12848 vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
12849 vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
12850 }
12851
12852 if (vmx->nested.nested_run_pending &&
12853 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
12854 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
12855 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
12856 } else {
12857 kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
12858 vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
12859 }
12860 vmx_set_rflags(vcpu, vmcs12->guest_rflags);
12861
12862 vmx->nested.preemption_timer_expired = false;
12863 if (nested_cpu_has_preemption_timer(vmcs12))
12864 vmx_start_preemption_timer(vcpu);
12246 12865
12247 /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the 12866 /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
12248 * bitwise-or of what L1 wants to trap for L2, and what we want to 12867 * bitwise-or of what L1 wants to trap for L2, and what we want to
@@ -12252,20 +12871,6 @@ static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12252 vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask; 12871 vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
12253 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits); 12872 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
12254 12873
12255 /* L2->L1 exit controls are emulated - the hardware exit is to L0 so
12256 * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
12257 * bits are further modified by vmx_set_efer() below.
12258 */
12259 vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
12260
12261 /* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
12262 * emulated by vmx_set_efer(), below.
12263 */
12264 vm_entry_controls_init(vmx,
12265 (vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
12266 ~VM_ENTRY_IA32E_MODE) |
12267 (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
12268
12269 if (vmx->nested.nested_run_pending && 12874 if (vmx->nested.nested_run_pending &&
12270 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) { 12875 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
12271 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat); 12876 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
@@ -12288,37 +12893,29 @@ static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12288 * influence global bitmap(for vpid01 and vpid02 allocation) 12893 * influence global bitmap(for vpid01 and vpid02 allocation)
12289 * even if spawn a lot of nested vCPUs. 12894 * even if spawn a lot of nested vCPUs.
12290 */ 12895 */
12291 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02) { 12896 if (nested_cpu_has_vpid(vmcs12) && nested_has_guest_tlb_tag(vcpu)) {
12292 if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) { 12897 if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
12293 vmx->nested.last_vpid = vmcs12->virtual_processor_id; 12898 vmx->nested.last_vpid = vmcs12->virtual_processor_id;
12294 __vmx_flush_tlb(vcpu, vmx->nested.vpid02, true); 12899 __vmx_flush_tlb(vcpu, nested_get_vpid02(vcpu), false);
12295 } 12900 }
12296 } else { 12901 } else {
12297 vmx_flush_tlb(vcpu, true); 12902 /*
12903 * If L1 use EPT, then L0 needs to execute INVEPT on
12904 * EPTP02 instead of EPTP01. Therefore, delay TLB
12905 * flush until vmcs02->eptp is fully updated by
12906 * KVM_REQ_LOAD_CR3. Note that this assumes
12907 * KVM_REQ_TLB_FLUSH is evaluated after
12908 * KVM_REQ_LOAD_CR3 in vcpu_enter_guest().
12909 */
12910 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
12298 } 12911 }
12299 } 12912 }
12300 12913
12301 if (enable_pml) { 12914 if (nested_cpu_has_ept(vmcs12))
12302 /* 12915 nested_ept_init_mmu_context(vcpu);
12303 * Conceptually we want to copy the PML address and index from 12916 else if (nested_cpu_has2(vmcs12,
12304 * vmcs01 here, and then back to vmcs01 on nested vmexit. But, 12917 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
12305 * since we always flush the log on each vmexit, this happens
12306 * to be equivalent to simply resetting the fields in vmcs02.
12307 */
12308 ASSERT(vmx->pml_pg);
12309 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
12310 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
12311 }
12312
12313 if (nested_cpu_has_ept(vmcs12)) {
12314 if (nested_ept_init_mmu_context(vcpu)) {
12315 *entry_failure_code = ENTRY_FAIL_DEFAULT;
12316 return 1;
12317 }
12318 } else if (nested_cpu_has2(vmcs12,
12319 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
12320 vmx_flush_tlb(vcpu, true); 12918 vmx_flush_tlb(vcpu, true);
12321 }
12322 12919
12323 /* 12920 /*
12324 * This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those 12921 * This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those
@@ -12334,14 +12931,8 @@ static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12334 vmx_set_cr4(vcpu, vmcs12->guest_cr4); 12931 vmx_set_cr4(vcpu, vmcs12->guest_cr4);
12335 vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12)); 12932 vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
12336 12933
12337 if (vmx->nested.nested_run_pending && 12934 vcpu->arch.efer = nested_vmx_calc_efer(vmx, vmcs12);
12338 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) 12935 /* Note: may modify VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
12339 vcpu->arch.efer = vmcs12->guest_ia32_efer;
12340 else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
12341 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
12342 else
12343 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
12344 /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
12345 vmx_set_efer(vcpu, vcpu->arch.efer); 12936 vmx_set_efer(vcpu, vcpu->arch.efer);
12346 12937
12347 /* 12938 /*
@@ -12383,6 +12974,7 @@ static int nested_vmx_check_nmi_controls(struct vmcs12 *vmcs12)
12383static int check_vmentry_prereqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12) 12974static int check_vmentry_prereqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12384{ 12975{
12385 struct vcpu_vmx *vmx = to_vmx(vcpu); 12976 struct vcpu_vmx *vmx = to_vmx(vcpu);
12977 bool ia32e;
12386 12978
12387 if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE && 12979 if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
12388 vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT) 12980 vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT)
@@ -12457,6 +13049,21 @@ static int check_vmentry_prereqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12457 return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD; 13049 return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
12458 13050
12459 /* 13051 /*
13052 * If the load IA32_EFER VM-exit control is 1, bits reserved in the
13053 * IA32_EFER MSR must be 0 in the field for that register. In addition,
13054 * the values of the LMA and LME bits in the field must each be that of
13055 * the host address-space size VM-exit control.
13056 */
13057 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
13058 ia32e = (vmcs12->vm_exit_controls &
13059 VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
13060 if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
13061 ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
13062 ia32e != !!(vmcs12->host_ia32_efer & EFER_LME))
13063 return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
13064 }
13065
13066 /*
12460 * From the Intel SDM, volume 3: 13067 * From the Intel SDM, volume 3:
12461 * Fields relevant to VM-entry event injection must be set properly. 13068 * Fields relevant to VM-entry event injection must be set properly.
12462 * These fields are the VM-entry interruption-information field, the 13069 * These fields are the VM-entry interruption-information field, the
@@ -12512,6 +13119,10 @@ static int check_vmentry_prereqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12512 } 13119 }
12513 } 13120 }
12514 13121
13122 if (nested_cpu_has_ept(vmcs12) &&
13123 !valid_ept_address(vcpu, vmcs12->ept_pointer))
13124 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13125
12515 return 0; 13126 return 0;
12516} 13127}
12517 13128
@@ -12577,21 +13188,6 @@ static int check_vmentry_postreqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12577 return 1; 13188 return 1;
12578 } 13189 }
12579 13190
12580 /*
12581 * If the load IA32_EFER VM-exit control is 1, bits reserved in the
12582 * IA32_EFER MSR must be 0 in the field for that register. In addition,
12583 * the values of the LMA and LME bits in the field must each be that of
12584 * the host address-space size VM-exit control.
12585 */
12586 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
12587 ia32e = (vmcs12->vm_exit_controls &
12588 VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
12589 if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
12590 ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
12591 ia32e != !!(vmcs12->host_ia32_efer & EFER_LME))
12592 return 1;
12593 }
12594
12595 if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS) && 13191 if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS) &&
12596 (is_noncanonical_address(vmcs12->guest_bndcfgs & PAGE_MASK, vcpu) || 13192 (is_noncanonical_address(vmcs12->guest_bndcfgs & PAGE_MASK, vcpu) ||
12597 (vmcs12->guest_bndcfgs & MSR_IA32_BNDCFGS_RSVD))) 13193 (vmcs12->guest_bndcfgs & MSR_IA32_BNDCFGS_RSVD)))
@@ -12600,26 +13196,139 @@ static int check_vmentry_postreqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12600 return 0; 13196 return 0;
12601} 13197}
12602 13198
13199static int __noclone nested_vmx_check_vmentry_hw(struct kvm_vcpu *vcpu)
13200{
13201 struct vcpu_vmx *vmx = to_vmx(vcpu);
13202 unsigned long cr3, cr4;
13203
13204 if (!nested_early_check)
13205 return 0;
13206
13207 if (vmx->msr_autoload.host.nr)
13208 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
13209 if (vmx->msr_autoload.guest.nr)
13210 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
13211
13212 preempt_disable();
13213
13214 vmx_prepare_switch_to_guest(vcpu);
13215
13216 /*
13217 * Induce a consistency check VMExit by clearing bit 1 in GUEST_RFLAGS,
13218 * which is reserved to '1' by hardware. GUEST_RFLAGS is guaranteed to
13219 * be written (by preparve_vmcs02()) before the "real" VMEnter, i.e.
13220 * there is no need to preserve other bits or save/restore the field.
13221 */
13222 vmcs_writel(GUEST_RFLAGS, 0);
13223
13224 vmcs_writel(HOST_RIP, vmx_early_consistency_check_return);
13225
13226 cr3 = __get_current_cr3_fast();
13227 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
13228 vmcs_writel(HOST_CR3, cr3);
13229 vmx->loaded_vmcs->host_state.cr3 = cr3;
13230 }
13231
13232 cr4 = cr4_read_shadow();
13233 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
13234 vmcs_writel(HOST_CR4, cr4);
13235 vmx->loaded_vmcs->host_state.cr4 = cr4;
13236 }
13237
13238 vmx->__launched = vmx->loaded_vmcs->launched;
13239
13240 asm(
13241 /* Set HOST_RSP */
13242 __ex("vmwrite %%" _ASM_SP ", %%" _ASM_DX) "\n\t"
13243 "mov %%" _ASM_SP ", %c[host_rsp](%0)\n\t"
13244
13245 /* Check if vmlaunch of vmresume is needed */
13246 "cmpl $0, %c[launched](%0)\n\t"
13247 "je 1f\n\t"
13248 __ex("vmresume") "\n\t"
13249 "jmp 2f\n\t"
13250 "1: " __ex("vmlaunch") "\n\t"
13251 "jmp 2f\n\t"
13252 "2: "
13253
13254 /* Set vmx->fail accordingly */
13255 "setbe %c[fail](%0)\n\t"
13256
13257 ".pushsection .rodata\n\t"
13258 ".global vmx_early_consistency_check_return\n\t"
13259 "vmx_early_consistency_check_return: " _ASM_PTR " 2b\n\t"
13260 ".popsection"
13261 :
13262 : "c"(vmx), "d"((unsigned long)HOST_RSP),
13263 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
13264 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
13265 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp))
13266 : "rax", "cc", "memory"
13267 );
13268
13269 vmcs_writel(HOST_RIP, vmx_return);
13270
13271 preempt_enable();
13272
13273 if (vmx->msr_autoload.host.nr)
13274 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
13275 if (vmx->msr_autoload.guest.nr)
13276 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
13277
13278 if (vmx->fail) {
13279 WARN_ON_ONCE(vmcs_read32(VM_INSTRUCTION_ERROR) !=
13280 VMXERR_ENTRY_INVALID_CONTROL_FIELD);
13281 vmx->fail = 0;
13282 return 1;
13283 }
13284
13285 /*
13286 * VMExit clears RFLAGS.IF and DR7, even on a consistency check.
13287 */
13288 local_irq_enable();
13289 if (hw_breakpoint_active())
13290 set_debugreg(__this_cpu_read(cpu_dr7), 7);
13291
13292 /*
13293 * A non-failing VMEntry means we somehow entered guest mode with
13294 * an illegal RIP, and that's just the tip of the iceberg. There
13295 * is no telling what memory has been modified or what state has
13296 * been exposed to unknown code. Hitting this all but guarantees
13297 * a (very critical) hardware issue.
13298 */
13299 WARN_ON(!(vmcs_read32(VM_EXIT_REASON) &
13300 VMX_EXIT_REASONS_FAILED_VMENTRY));
13301
13302 return 0;
13303}
13304STACK_FRAME_NON_STANDARD(nested_vmx_check_vmentry_hw);
13305
13306static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
13307 struct vmcs12 *vmcs12);
13308
12603/* 13309/*
12604 * If exit_qual is NULL, this is being called from state restore (either RSM 13310 * If from_vmentry is false, this is being called from state restore (either RSM
12605 * or KVM_SET_NESTED_STATE). Otherwise it's called from vmlaunch/vmresume. 13311 * or KVM_SET_NESTED_STATE). Otherwise it's called from vmlaunch/vmresume.
13312+ *
13313+ * Returns:
13314+ * 0 - success, i.e. proceed with actual VMEnter
13315+ * 1 - consistency check VMExit
13316+ * -1 - consistency check VMFail
12606 */ 13317 */
12607static int enter_vmx_non_root_mode(struct kvm_vcpu *vcpu, u32 *exit_qual) 13318static int nested_vmx_enter_non_root_mode(struct kvm_vcpu *vcpu,
13319 bool from_vmentry)
12608{ 13320{
12609 struct vcpu_vmx *vmx = to_vmx(vcpu); 13321 struct vcpu_vmx *vmx = to_vmx(vcpu);
12610 struct vmcs12 *vmcs12 = get_vmcs12(vcpu); 13322 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
12611 bool from_vmentry = !!exit_qual;
12612 u32 dummy_exit_qual;
12613 bool evaluate_pending_interrupts; 13323 bool evaluate_pending_interrupts;
12614 int r = 0; 13324 u32 exit_reason = EXIT_REASON_INVALID_STATE;
13325 u32 exit_qual;
12615 13326
12616 evaluate_pending_interrupts = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) & 13327 evaluate_pending_interrupts = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
12617 (CPU_BASED_VIRTUAL_INTR_PENDING | CPU_BASED_VIRTUAL_NMI_PENDING); 13328 (CPU_BASED_VIRTUAL_INTR_PENDING | CPU_BASED_VIRTUAL_NMI_PENDING);
12618 if (likely(!evaluate_pending_interrupts) && kvm_vcpu_apicv_active(vcpu)) 13329 if (likely(!evaluate_pending_interrupts) && kvm_vcpu_apicv_active(vcpu))
12619 evaluate_pending_interrupts |= vmx_has_apicv_interrupt(vcpu); 13330 evaluate_pending_interrupts |= vmx_has_apicv_interrupt(vcpu);
12620 13331
12621 enter_guest_mode(vcpu);
12622
12623 if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) 13332 if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
12624 vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL); 13333 vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
12625 if (kvm_mpx_supported() && 13334 if (kvm_mpx_supported() &&
@@ -12627,24 +13336,35 @@ static int enter_vmx_non_root_mode(struct kvm_vcpu *vcpu, u32 *exit_qual)
12627 vmx->nested.vmcs01_guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS); 13336 vmx->nested.vmcs01_guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
12628 13337
12629 vmx_switch_vmcs(vcpu, &vmx->nested.vmcs02); 13338 vmx_switch_vmcs(vcpu, &vmx->nested.vmcs02);
12630 vmx_segment_cache_clear(vmx);
12631 13339
13340 prepare_vmcs02_early(vmx, vmcs12);
13341
13342 if (from_vmentry) {
13343 nested_get_vmcs12_pages(vcpu);
13344
13345 if (nested_vmx_check_vmentry_hw(vcpu)) {
13346 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
13347 return -1;
13348 }
13349
13350 if (check_vmentry_postreqs(vcpu, vmcs12, &exit_qual))
13351 goto vmentry_fail_vmexit;
13352 }
13353
13354 enter_guest_mode(vcpu);
12632 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING) 13355 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
12633 vcpu->arch.tsc_offset += vmcs12->tsc_offset; 13356 vcpu->arch.tsc_offset += vmcs12->tsc_offset;
12634 13357
12635 r = EXIT_REASON_INVALID_STATE; 13358 if (prepare_vmcs02(vcpu, vmcs12, &exit_qual))
12636 if (prepare_vmcs02(vcpu, vmcs12, from_vmentry ? exit_qual : &dummy_exit_qual)) 13359 goto vmentry_fail_vmexit_guest_mode;
12637 goto fail;
12638 13360
12639 if (from_vmentry) { 13361 if (from_vmentry) {
12640 nested_get_vmcs12_pages(vcpu); 13362 exit_reason = EXIT_REASON_MSR_LOAD_FAIL;
12641 13363 exit_qual = nested_vmx_load_msr(vcpu,
12642 r = EXIT_REASON_MSR_LOAD_FAIL; 13364 vmcs12->vm_entry_msr_load_addr,
12643 *exit_qual = nested_vmx_load_msr(vcpu, 13365 vmcs12->vm_entry_msr_load_count);
12644 vmcs12->vm_entry_msr_load_addr, 13366 if (exit_qual)
12645 vmcs12->vm_entry_msr_load_count); 13367 goto vmentry_fail_vmexit_guest_mode;
12646 if (*exit_qual)
12647 goto fail;
12648 } else { 13368 } else {
12649 /* 13369 /*
12650 * The MMU is not initialized to point at the right entities yet and 13370 * The MMU is not initialized to point at the right entities yet and
@@ -12681,12 +13401,28 @@ static int enter_vmx_non_root_mode(struct kvm_vcpu *vcpu, u32 *exit_qual)
12681 */ 13401 */
12682 return 0; 13402 return 0;
12683 13403
12684fail: 13404 /*
13405 * A failed consistency check that leads to a VMExit during L1's
13406 * VMEnter to L2 is a variation of a normal VMexit, as explained in
13407 * 26.7 "VM-entry failures during or after loading guest state".
13408 */
13409vmentry_fail_vmexit_guest_mode:
12685 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING) 13410 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
12686 vcpu->arch.tsc_offset -= vmcs12->tsc_offset; 13411 vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
12687 leave_guest_mode(vcpu); 13412 leave_guest_mode(vcpu);
13413
13414vmentry_fail_vmexit:
12688 vmx_switch_vmcs(vcpu, &vmx->vmcs01); 13415 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
12689 return r; 13416
13417 if (!from_vmentry)
13418 return 1;
13419
13420 load_vmcs12_host_state(vcpu, vmcs12);
13421 vmcs12->vm_exit_reason = exit_reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
13422 vmcs12->exit_qualification = exit_qual;
13423 if (enable_shadow_vmcs || vmx->nested.hv_evmcs)
13424 vmx->nested.need_vmcs12_sync = true;
13425 return 1;
12690} 13426}
12691 13427
12692/* 13428/*
@@ -12698,14 +13434,16 @@ static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
12698 struct vmcs12 *vmcs12; 13434 struct vmcs12 *vmcs12;
12699 struct vcpu_vmx *vmx = to_vmx(vcpu); 13435 struct vcpu_vmx *vmx = to_vmx(vcpu);
12700 u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu); 13436 u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
12701 u32 exit_qual;
12702 int ret; 13437 int ret;
12703 13438
12704 if (!nested_vmx_check_permission(vcpu)) 13439 if (!nested_vmx_check_permission(vcpu))
12705 return 1; 13440 return 1;
12706 13441
12707 if (!nested_vmx_check_vmcs12(vcpu)) 13442 if (!nested_vmx_handle_enlightened_vmptrld(vcpu, true))
12708 goto out; 13443 return 1;
13444
13445 if (!vmx->nested.hv_evmcs && vmx->nested.current_vmptr == -1ull)
13446 return nested_vmx_failInvalid(vcpu);
12709 13447
12710 vmcs12 = get_vmcs12(vcpu); 13448 vmcs12 = get_vmcs12(vcpu);
12711 13449
@@ -12715,13 +13453,16 @@ static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
12715 * rather than RFLAGS.ZF, and no error number is stored to the 13453 * rather than RFLAGS.ZF, and no error number is stored to the
12716 * VM-instruction error field. 13454 * VM-instruction error field.
12717 */ 13455 */
12718 if (vmcs12->hdr.shadow_vmcs) { 13456 if (vmcs12->hdr.shadow_vmcs)
12719 nested_vmx_failInvalid(vcpu); 13457 return nested_vmx_failInvalid(vcpu);
12720 goto out;
12721 }
12722 13458
12723 if (enable_shadow_vmcs) 13459 if (vmx->nested.hv_evmcs) {
13460 copy_enlightened_to_vmcs12(vmx);
13461 /* Enlightened VMCS doesn't have launch state */
13462 vmcs12->launch_state = !launch;
13463 } else if (enable_shadow_vmcs) {
12724 copy_shadow_to_vmcs12(vmx); 13464 copy_shadow_to_vmcs12(vmx);
13465 }
12725 13466
12726 /* 13467 /*
12727 * The nested entry process starts with enforcing various prerequisites 13468 * The nested entry process starts with enforcing various prerequisites
@@ -12733,59 +13474,37 @@ static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
12733 * for misconfigurations which will anyway be caught by the processor 13474 * for misconfigurations which will anyway be caught by the processor
12734 * when using the merged vmcs02. 13475 * when using the merged vmcs02.
12735 */ 13476 */
12736 if (interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS) { 13477 if (interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS)
12737 nested_vmx_failValid(vcpu, 13478 return nested_vmx_failValid(vcpu,
12738 VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS); 13479 VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
12739 goto out;
12740 }
12741 13480
12742 if (vmcs12->launch_state == launch) { 13481 if (vmcs12->launch_state == launch)
12743 nested_vmx_failValid(vcpu, 13482 return nested_vmx_failValid(vcpu,
12744 launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS 13483 launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
12745 : VMXERR_VMRESUME_NONLAUNCHED_VMCS); 13484 : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
12746 goto out;
12747 }
12748 13485
12749 ret = check_vmentry_prereqs(vcpu, vmcs12); 13486 ret = check_vmentry_prereqs(vcpu, vmcs12);
12750 if (ret) { 13487 if (ret)
12751 nested_vmx_failValid(vcpu, ret); 13488 return nested_vmx_failValid(vcpu, ret);
12752 goto out;
12753 }
12754
12755 /*
12756 * After this point, the trap flag no longer triggers a singlestep trap
12757 * on the vm entry instructions; don't call kvm_skip_emulated_instruction.
12758 * This is not 100% correct; for performance reasons, we delegate most
12759 * of the checks on host state to the processor. If those fail,
12760 * the singlestep trap is missed.
12761 */
12762 skip_emulated_instruction(vcpu);
12763
12764 ret = check_vmentry_postreqs(vcpu, vmcs12, &exit_qual);
12765 if (ret) {
12766 nested_vmx_entry_failure(vcpu, vmcs12,
12767 EXIT_REASON_INVALID_STATE, exit_qual);
12768 return 1;
12769 }
12770 13489
12771 /* 13490 /*
12772 * We're finally done with prerequisite checking, and can start with 13491 * We're finally done with prerequisite checking, and can start with
12773 * the nested entry. 13492 * the nested entry.
12774 */ 13493 */
12775
12776 vmx->nested.nested_run_pending = 1; 13494 vmx->nested.nested_run_pending = 1;
12777 ret = enter_vmx_non_root_mode(vcpu, &exit_qual); 13495 ret = nested_vmx_enter_non_root_mode(vcpu, true);
12778 if (ret) { 13496 vmx->nested.nested_run_pending = !ret;
12779 nested_vmx_entry_failure(vcpu, vmcs12, ret, exit_qual); 13497 if (ret > 0)
12780 vmx->nested.nested_run_pending = 0;
12781 return 1; 13498 return 1;
12782 } 13499 else if (ret)
13500 return nested_vmx_failValid(vcpu,
13501 VMXERR_ENTRY_INVALID_CONTROL_FIELD);
12783 13502
12784 /* Hide L1D cache contents from the nested guest. */ 13503 /* Hide L1D cache contents from the nested guest. */
12785 vmx->vcpu.arch.l1tf_flush_l1d = true; 13504 vmx->vcpu.arch.l1tf_flush_l1d = true;
12786 13505
12787 /* 13506 /*
12788 * Must happen outside of enter_vmx_non_root_mode() as it will 13507 * Must happen outside of nested_vmx_enter_non_root_mode() as it will
12789 * also be used as part of restoring nVMX state for 13508 * also be used as part of restoring nVMX state for
12790 * snapshot restore (migration). 13509 * snapshot restore (migration).
12791 * 13510 *
@@ -12806,9 +13525,6 @@ static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
12806 return kvm_vcpu_halt(vcpu); 13525 return kvm_vcpu_halt(vcpu);
12807 } 13526 }
12808 return 1; 13527 return 1;
12809
12810out:
12811 return kvm_skip_emulated_instruction(vcpu);
12812} 13528}
12813 13529
12814/* 13530/*
@@ -13122,24 +13838,6 @@ static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
13122 kvm_clear_interrupt_queue(vcpu); 13838 kvm_clear_interrupt_queue(vcpu);
13123} 13839}
13124 13840
13125static void load_vmcs12_mmu_host_state(struct kvm_vcpu *vcpu,
13126 struct vmcs12 *vmcs12)
13127{
13128 u32 entry_failure_code;
13129
13130 nested_ept_uninit_mmu_context(vcpu);
13131
13132 /*
13133 * Only PDPTE load can fail as the value of cr3 was checked on entry and
13134 * couldn't have changed.
13135 */
13136 if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &entry_failure_code))
13137 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
13138
13139 if (!enable_ept)
13140 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
13141}
13142
13143/* 13841/*
13144 * A part of what we need to when the nested L2 guest exits and we want to 13842 * A part of what we need to when the nested L2 guest exits and we want to
13145 * run its L1 parent, is to reset L1's guest state to the host state specified 13843 * run its L1 parent, is to reset L1's guest state to the host state specified
@@ -13153,6 +13851,7 @@ static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
13153 struct vmcs12 *vmcs12) 13851 struct vmcs12 *vmcs12)
13154{ 13852{
13155 struct kvm_segment seg; 13853 struct kvm_segment seg;
13854 u32 entry_failure_code;
13156 13855
13157 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) 13856 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
13158 vcpu->arch.efer = vmcs12->host_ia32_efer; 13857 vcpu->arch.efer = vmcs12->host_ia32_efer;
@@ -13165,6 +13864,8 @@ static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
13165 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp); 13864 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
13166 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip); 13865 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
13167 vmx_set_rflags(vcpu, X86_EFLAGS_FIXED); 13866 vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
13867 vmx_set_interrupt_shadow(vcpu, 0);
13868
13168 /* 13869 /*
13169 * Note that calling vmx_set_cr0 is important, even if cr0 hasn't 13870 * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
13170 * actually changed, because vmx_set_cr0 refers to efer set above. 13871 * actually changed, because vmx_set_cr0 refers to efer set above.
@@ -13179,23 +13880,35 @@ static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
13179 vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK); 13880 vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
13180 vmx_set_cr4(vcpu, vmcs12->host_cr4); 13881 vmx_set_cr4(vcpu, vmcs12->host_cr4);
13181 13882
13182 load_vmcs12_mmu_host_state(vcpu, vmcs12); 13883 nested_ept_uninit_mmu_context(vcpu);
13183 13884
13184 /* 13885 /*
13185 * If vmcs01 don't use VPID, CPU flushes TLB on every 13886 * Only PDPTE load can fail as the value of cr3 was checked on entry and
13887 * couldn't have changed.
13888 */
13889 if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &entry_failure_code))
13890 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
13891
13892 if (!enable_ept)
13893 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
13894
13895 /*
13896 * If vmcs01 doesn't use VPID, CPU flushes TLB on every
13186 * VMEntry/VMExit. Thus, no need to flush TLB. 13897 * VMEntry/VMExit. Thus, no need to flush TLB.
13187 * 13898 *
13188 * If vmcs12 uses VPID, TLB entries populated by L2 are 13899 * If vmcs12 doesn't use VPID, L1 expects TLB to be
13189 * tagged with vmx->nested.vpid02 while L1 entries are tagged 13900 * flushed on every VMEntry/VMExit.
13190 * with vmx->vpid. Thus, no need to flush TLB. 13901 *
13902 * Otherwise, we can preserve TLB entries as long as we are
13903 * able to tag L1 TLB entries differently than L2 TLB entries.
13191 * 13904 *
13192 * Therefore, flush TLB only in case vmcs01 uses VPID and 13905 * If vmcs12 uses EPT, we need to execute this flush on EPTP01
13193 * vmcs12 don't use VPID as in this case L1 & L2 TLB entries 13906 * and therefore we request the TLB flush to happen only after VMCS EPTP
13194 * are both tagged with vmx->vpid. 13907 * has been set by KVM_REQ_LOAD_CR3.
13195 */ 13908 */
13196 if (enable_vpid && 13909 if (enable_vpid &&
13197 !(nested_cpu_has_vpid(vmcs12) && to_vmx(vcpu)->nested.vpid02)) { 13910 (!nested_cpu_has_vpid(vmcs12) || !nested_has_guest_tlb_tag(vcpu))) {
13198 vmx_flush_tlb(vcpu, true); 13911 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
13199 } 13912 }
13200 13913
13201 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs); 13914 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
@@ -13275,6 +13988,140 @@ static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
13275 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL); 13988 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
13276} 13989}
13277 13990
13991static inline u64 nested_vmx_get_vmcs01_guest_efer(struct vcpu_vmx *vmx)
13992{
13993 struct shared_msr_entry *efer_msr;
13994 unsigned int i;
13995
13996 if (vm_entry_controls_get(vmx) & VM_ENTRY_LOAD_IA32_EFER)
13997 return vmcs_read64(GUEST_IA32_EFER);
13998
13999 if (cpu_has_load_ia32_efer)
14000 return host_efer;
14001
14002 for (i = 0; i < vmx->msr_autoload.guest.nr; ++i) {
14003 if (vmx->msr_autoload.guest.val[i].index == MSR_EFER)
14004 return vmx->msr_autoload.guest.val[i].value;
14005 }
14006
14007 efer_msr = find_msr_entry(vmx, MSR_EFER);
14008 if (efer_msr)
14009 return efer_msr->data;
14010
14011 return host_efer;
14012}
14013
14014static void nested_vmx_restore_host_state(struct kvm_vcpu *vcpu)
14015{
14016 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
14017 struct vcpu_vmx *vmx = to_vmx(vcpu);
14018 struct vmx_msr_entry g, h;
14019 struct msr_data msr;
14020 gpa_t gpa;
14021 u32 i, j;
14022
14023 vcpu->arch.pat = vmcs_read64(GUEST_IA32_PAT);
14024
14025 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) {
14026 /*
14027 * L1's host DR7 is lost if KVM_GUESTDBG_USE_HW_BP is set
14028 * as vmcs01.GUEST_DR7 contains a userspace defined value
14029 * and vcpu->arch.dr7 is not squirreled away before the
14030 * nested VMENTER (not worth adding a variable in nested_vmx).
14031 */
14032 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
14033 kvm_set_dr(vcpu, 7, DR7_FIXED_1);
14034 else
14035 WARN_ON(kvm_set_dr(vcpu, 7, vmcs_readl(GUEST_DR7)));
14036 }
14037
14038 /*
14039 * Note that calling vmx_set_{efer,cr0,cr4} is important as they
14040 * handle a variety of side effects to KVM's software model.
14041 */
14042 vmx_set_efer(vcpu, nested_vmx_get_vmcs01_guest_efer(vmx));
14043
14044 vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
14045 vmx_set_cr0(vcpu, vmcs_readl(CR0_READ_SHADOW));
14046
14047 vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
14048 vmx_set_cr4(vcpu, vmcs_readl(CR4_READ_SHADOW));
14049
14050 nested_ept_uninit_mmu_context(vcpu);
14051 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
14052 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
14053
14054 /*
14055 * Use ept_save_pdptrs(vcpu) to load the MMU's cached PDPTRs
14056 * from vmcs01 (if necessary). The PDPTRs are not loaded on
14057 * VMFail, like everything else we just need to ensure our
14058 * software model is up-to-date.
14059 */
14060 ept_save_pdptrs(vcpu);
14061
14062 kvm_mmu_reset_context(vcpu);
14063
14064 if (cpu_has_vmx_msr_bitmap())
14065 vmx_update_msr_bitmap(vcpu);
14066
14067 /*
14068 * This nasty bit of open coding is a compromise between blindly
14069 * loading L1's MSRs using the exit load lists (incorrect emulation
14070 * of VMFail), leaving the nested VM's MSRs in the software model
14071 * (incorrect behavior) and snapshotting the modified MSRs (too
14072 * expensive since the lists are unbound by hardware). For each
14073 * MSR that was (prematurely) loaded from the nested VMEntry load
14074 * list, reload it from the exit load list if it exists and differs
14075 * from the guest value. The intent is to stuff host state as
14076 * silently as possible, not to fully process the exit load list.
14077 */
14078 msr.host_initiated = false;
14079 for (i = 0; i < vmcs12->vm_entry_msr_load_count; i++) {
14080 gpa = vmcs12->vm_entry_msr_load_addr + (i * sizeof(g));
14081 if (kvm_vcpu_read_guest(vcpu, gpa, &g, sizeof(g))) {
14082 pr_debug_ratelimited(
14083 "%s read MSR index failed (%u, 0x%08llx)\n",
14084 __func__, i, gpa);
14085 goto vmabort;
14086 }
14087
14088 for (j = 0; j < vmcs12->vm_exit_msr_load_count; j++) {
14089 gpa = vmcs12->vm_exit_msr_load_addr + (j * sizeof(h));
14090 if (kvm_vcpu_read_guest(vcpu, gpa, &h, sizeof(h))) {
14091 pr_debug_ratelimited(
14092 "%s read MSR failed (%u, 0x%08llx)\n",
14093 __func__, j, gpa);
14094 goto vmabort;
14095 }
14096 if (h.index != g.index)
14097 continue;
14098 if (h.value == g.value)
14099 break;
14100
14101 if (nested_vmx_load_msr_check(vcpu, &h)) {
14102 pr_debug_ratelimited(
14103 "%s check failed (%u, 0x%x, 0x%x)\n",
14104 __func__, j, h.index, h.reserved);
14105 goto vmabort;
14106 }
14107
14108 msr.index = h.index;
14109 msr.data = h.value;
14110 if (kvm_set_msr(vcpu, &msr)) {
14111 pr_debug_ratelimited(
14112 "%s WRMSR failed (%u, 0x%x, 0x%llx)\n",
14113 __func__, j, h.index, h.value);
14114 goto vmabort;
14115 }
14116 }
14117 }
14118
14119 return;
14120
14121vmabort:
14122 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
14123}
14124
13278/* 14125/*
13279 * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1 14126 * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
13280 * and modify vmcs12 to make it see what it would expect to see there if 14127 * and modify vmcs12 to make it see what it would expect to see there if
@@ -13290,14 +14137,6 @@ static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
13290 /* trying to cancel vmlaunch/vmresume is a bug */ 14137 /* trying to cancel vmlaunch/vmresume is a bug */
13291 WARN_ON_ONCE(vmx->nested.nested_run_pending); 14138 WARN_ON_ONCE(vmx->nested.nested_run_pending);
13292 14139
13293 /*
13294 * The only expected VM-instruction error is "VM entry with
13295 * invalid control field(s)." Anything else indicates a
13296 * problem with L0.
13297 */
13298 WARN_ON_ONCE(vmx->fail && (vmcs_read32(VM_INSTRUCTION_ERROR) !=
13299 VMXERR_ENTRY_INVALID_CONTROL_FIELD));
13300
13301 leave_guest_mode(vcpu); 14140 leave_guest_mode(vcpu);
13302 14141
13303 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING) 14142 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
@@ -13324,12 +14163,19 @@ static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
13324 if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr, 14163 if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr,
13325 vmcs12->vm_exit_msr_store_count)) 14164 vmcs12->vm_exit_msr_store_count))
13326 nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL); 14165 nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL);
14166 } else {
14167 /*
14168 * The only expected VM-instruction error is "VM entry with
14169 * invalid control field(s)." Anything else indicates a
14170 * problem with L0. And we should never get here with a
14171 * VMFail of any type if early consistency checks are enabled.
14172 */
14173 WARN_ON_ONCE(vmcs_read32(VM_INSTRUCTION_ERROR) !=
14174 VMXERR_ENTRY_INVALID_CONTROL_FIELD);
14175 WARN_ON_ONCE(nested_early_check);
13327 } 14176 }
13328 14177
13329 vmx_switch_vmcs(vcpu, &vmx->vmcs01); 14178 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
13330 vm_entry_controls_reset_shadow(vmx);
13331 vm_exit_controls_reset_shadow(vmx);
13332 vmx_segment_cache_clear(vmx);
13333 14179
13334 /* Update any VMCS fields that might have changed while L2 ran */ 14180 /* Update any VMCS fields that might have changed while L2 ran */
13335 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr); 14181 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
@@ -13373,8 +14219,8 @@ static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
13373 */ 14219 */
13374 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu); 14220 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
13375 14221
13376 if (enable_shadow_vmcs && exit_reason != -1) 14222 if ((exit_reason != -1) && (enable_shadow_vmcs || vmx->nested.hv_evmcs))
13377 vmx->nested.sync_shadow_vmcs = true; 14223 vmx->nested.need_vmcs12_sync = true;
13378 14224
13379 /* in case we halted in L2 */ 14225 /* in case we halted in L2 */
13380 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE; 14226 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
@@ -13409,24 +14255,24 @@ static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
13409 14255
13410 return; 14256 return;
13411 } 14257 }
13412 14258
13413 /* 14259 /*
13414 * After an early L2 VM-entry failure, we're now back 14260 * After an early L2 VM-entry failure, we're now back
13415 * in L1 which thinks it just finished a VMLAUNCH or 14261 * in L1 which thinks it just finished a VMLAUNCH or
13416 * VMRESUME instruction, so we need to set the failure 14262 * VMRESUME instruction, so we need to set the failure
13417 * flag and the VM-instruction error field of the VMCS 14263 * flag and the VM-instruction error field of the VMCS
13418 * accordingly. 14264 * accordingly, and skip the emulated instruction.
13419 */ 14265 */
13420 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD); 14266 (void)nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
13421
13422 load_vmcs12_mmu_host_state(vcpu, vmcs12);
13423 14267
13424 /* 14268 /*
13425 * The emulated instruction was already skipped in 14269 * Restore L1's host state to KVM's software model. We're here
13426 * nested_vmx_run, but the updated RIP was never 14270 * because a consistency check was caught by hardware, which
13427 * written back to the vmcs01. 14271 * means some amount of guest state has been propagated to KVM's
14272 * model and needs to be unwound to the host's state.
13428 */ 14273 */
13429 skip_emulated_instruction(vcpu); 14274 nested_vmx_restore_host_state(vcpu);
14275
13430 vmx->fail = 0; 14276 vmx->fail = 0;
13431} 14277}
13432 14278
@@ -13439,26 +14285,7 @@ static void vmx_leave_nested(struct kvm_vcpu *vcpu)
13439 to_vmx(vcpu)->nested.nested_run_pending = 0; 14285 to_vmx(vcpu)->nested.nested_run_pending = 0;
13440 nested_vmx_vmexit(vcpu, -1, 0, 0); 14286 nested_vmx_vmexit(vcpu, -1, 0, 0);
13441 } 14287 }
13442 free_nested(to_vmx(vcpu)); 14288 free_nested(vcpu);
13443}
13444
13445/*
13446 * L1's failure to enter L2 is a subset of a normal exit, as explained in
13447 * 23.7 "VM-entry failures during or after loading guest state" (this also
13448 * lists the acceptable exit-reason and exit-qualification parameters).
13449 * It should only be called before L2 actually succeeded to run, and when
13450 * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
13451 */
13452static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
13453 struct vmcs12 *vmcs12,
13454 u32 reason, unsigned long qualification)
13455{
13456 load_vmcs12_host_state(vcpu, vmcs12);
13457 vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
13458 vmcs12->exit_qualification = qualification;
13459 nested_vmx_succeed(vcpu);
13460 if (enable_shadow_vmcs)
13461 to_vmx(vcpu)->nested.sync_shadow_vmcs = true;
13462} 14289}
13463 14290
13464static int vmx_check_intercept(struct kvm_vcpu *vcpu, 14291static int vmx_check_intercept(struct kvm_vcpu *vcpu,
@@ -13884,7 +14711,7 @@ static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, u64 smbase)
13884 14711
13885 if (vmx->nested.smm.guest_mode) { 14712 if (vmx->nested.smm.guest_mode) {
13886 vcpu->arch.hflags &= ~HF_SMM_MASK; 14713 vcpu->arch.hflags &= ~HF_SMM_MASK;
13887 ret = enter_vmx_non_root_mode(vcpu, NULL); 14714 ret = nested_vmx_enter_non_root_mode(vcpu, false);
13888 vcpu->arch.hflags |= HF_SMM_MASK; 14715 vcpu->arch.hflags |= HF_SMM_MASK;
13889 if (ret) 14716 if (ret)
13890 return ret; 14717 return ret;
@@ -13899,6 +14726,20 @@ static int enable_smi_window(struct kvm_vcpu *vcpu)
13899 return 0; 14726 return 0;
13900} 14727}
13901 14728
14729static inline int vmx_has_valid_vmcs12(struct kvm_vcpu *vcpu)
14730{
14731 struct vcpu_vmx *vmx = to_vmx(vcpu);
14732
14733 /*
14734 * In case we do two consecutive get/set_nested_state()s while L2 was
14735 * running hv_evmcs may end up not being mapped (we map it from
14736 * nested_vmx_run()/vmx_vcpu_run()). Check is_guest_mode() as we always
14737 * have vmcs12 if it is true.
14738 */
14739 return is_guest_mode(vcpu) || vmx->nested.current_vmptr != -1ull ||
14740 vmx->nested.hv_evmcs;
14741}
14742
13902static int vmx_get_nested_state(struct kvm_vcpu *vcpu, 14743static int vmx_get_nested_state(struct kvm_vcpu *vcpu,
13903 struct kvm_nested_state __user *user_kvm_nested_state, 14744 struct kvm_nested_state __user *user_kvm_nested_state,
13904 u32 user_data_size) 14745 u32 user_data_size)
@@ -13918,12 +14759,16 @@ static int vmx_get_nested_state(struct kvm_vcpu *vcpu,
13918 14759
13919 vmx = to_vmx(vcpu); 14760 vmx = to_vmx(vcpu);
13920 vmcs12 = get_vmcs12(vcpu); 14761 vmcs12 = get_vmcs12(vcpu);
14762
14763 if (nested_vmx_allowed(vcpu) && vmx->nested.enlightened_vmcs_enabled)
14764 kvm_state.flags |= KVM_STATE_NESTED_EVMCS;
14765
13921 if (nested_vmx_allowed(vcpu) && 14766 if (nested_vmx_allowed(vcpu) &&
13922 (vmx->nested.vmxon || vmx->nested.smm.vmxon)) { 14767 (vmx->nested.vmxon || vmx->nested.smm.vmxon)) {
13923 kvm_state.vmx.vmxon_pa = vmx->nested.vmxon_ptr; 14768 kvm_state.vmx.vmxon_pa = vmx->nested.vmxon_ptr;
13924 kvm_state.vmx.vmcs_pa = vmx->nested.current_vmptr; 14769 kvm_state.vmx.vmcs_pa = vmx->nested.current_vmptr;
13925 14770
13926 if (vmx->nested.current_vmptr != -1ull) { 14771 if (vmx_has_valid_vmcs12(vcpu)) {
13927 kvm_state.size += VMCS12_SIZE; 14772 kvm_state.size += VMCS12_SIZE;
13928 14773
13929 if (is_guest_mode(vcpu) && 14774 if (is_guest_mode(vcpu) &&
@@ -13952,20 +14797,24 @@ static int vmx_get_nested_state(struct kvm_vcpu *vcpu,
13952 if (copy_to_user(user_kvm_nested_state, &kvm_state, sizeof(kvm_state))) 14797 if (copy_to_user(user_kvm_nested_state, &kvm_state, sizeof(kvm_state)))
13953 return -EFAULT; 14798 return -EFAULT;
13954 14799
13955 if (vmx->nested.current_vmptr == -1ull) 14800 if (!vmx_has_valid_vmcs12(vcpu))
13956 goto out; 14801 goto out;
13957 14802
13958 /* 14803 /*
13959 * When running L2, the authoritative vmcs12 state is in the 14804 * When running L2, the authoritative vmcs12 state is in the
13960 * vmcs02. When running L1, the authoritative vmcs12 state is 14805 * vmcs02. When running L1, the authoritative vmcs12 state is
13961 * in the shadow vmcs linked to vmcs01, unless 14806 * in the shadow or enlightened vmcs linked to vmcs01, unless
13962 * sync_shadow_vmcs is set, in which case, the authoritative 14807 * need_vmcs12_sync is set, in which case, the authoritative
13963 * vmcs12 state is in the vmcs12 already. 14808 * vmcs12 state is in the vmcs12 already.
13964 */ 14809 */
13965 if (is_guest_mode(vcpu)) 14810 if (is_guest_mode(vcpu)) {
13966 sync_vmcs12(vcpu, vmcs12); 14811 sync_vmcs12(vcpu, vmcs12);
13967 else if (enable_shadow_vmcs && !vmx->nested.sync_shadow_vmcs) 14812 } else if (!vmx->nested.need_vmcs12_sync) {
13968 copy_shadow_to_vmcs12(vmx); 14813 if (vmx->nested.hv_evmcs)
14814 copy_enlightened_to_vmcs12(vmx);
14815 else if (enable_shadow_vmcs)
14816 copy_shadow_to_vmcs12(vmx);
14817 }
13969 14818
13970 if (copy_to_user(user_kvm_nested_state->data, vmcs12, sizeof(*vmcs12))) 14819 if (copy_to_user(user_kvm_nested_state->data, vmcs12, sizeof(*vmcs12)))
13971 return -EFAULT; 14820 return -EFAULT;
@@ -13993,6 +14842,9 @@ static int vmx_set_nested_state(struct kvm_vcpu *vcpu,
13993 if (kvm_state->format != 0) 14842 if (kvm_state->format != 0)
13994 return -EINVAL; 14843 return -EINVAL;
13995 14844
14845 if (kvm_state->flags & KVM_STATE_NESTED_EVMCS)
14846 nested_enable_evmcs(vcpu, NULL);
14847
13996 if (!nested_vmx_allowed(vcpu)) 14848 if (!nested_vmx_allowed(vcpu))
13997 return kvm_state->vmx.vmxon_pa == -1ull ? 0 : -EINVAL; 14849 return kvm_state->vmx.vmxon_pa == -1ull ? 0 : -EINVAL;
13998 14850
@@ -14010,13 +14862,6 @@ static int vmx_set_nested_state(struct kvm_vcpu *vcpu,
14010 if (!page_address_valid(vcpu, kvm_state->vmx.vmxon_pa)) 14862 if (!page_address_valid(vcpu, kvm_state->vmx.vmxon_pa))
14011 return -EINVAL; 14863 return -EINVAL;
14012 14864
14013 if (kvm_state->size < sizeof(kvm_state) + sizeof(*vmcs12))
14014 return -EINVAL;
14015
14016 if (kvm_state->vmx.vmcs_pa == kvm_state->vmx.vmxon_pa ||
14017 !page_address_valid(vcpu, kvm_state->vmx.vmcs_pa))
14018 return -EINVAL;
14019
14020 if ((kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) && 14865 if ((kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
14021 (kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE)) 14866 (kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
14022 return -EINVAL; 14867 return -EINVAL;
@@ -14046,7 +14891,25 @@ static int vmx_set_nested_state(struct kvm_vcpu *vcpu,
14046 if (ret) 14891 if (ret)
14047 return ret; 14892 return ret;
14048 14893
14049 set_current_vmptr(vmx, kvm_state->vmx.vmcs_pa); 14894 /* Empty 'VMXON' state is permitted */
14895 if (kvm_state->size < sizeof(kvm_state) + sizeof(*vmcs12))
14896 return 0;
14897
14898 if (kvm_state->vmx.vmcs_pa != -1ull) {
14899 if (kvm_state->vmx.vmcs_pa == kvm_state->vmx.vmxon_pa ||
14900 !page_address_valid(vcpu, kvm_state->vmx.vmcs_pa))
14901 return -EINVAL;
14902
14903 set_current_vmptr(vmx, kvm_state->vmx.vmcs_pa);
14904 } else if (kvm_state->flags & KVM_STATE_NESTED_EVMCS) {
14905 /*
14906 * Sync eVMCS upon entry as we may not have
14907 * HV_X64_MSR_VP_ASSIST_PAGE set up yet.
14908 */
14909 vmx->nested.need_vmcs12_sync = true;
14910 } else {
14911 return -EINVAL;
14912 }
14050 14913
14051 if (kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON) { 14914 if (kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON) {
14052 vmx->nested.smm.vmxon = true; 14915 vmx->nested.smm.vmxon = true;
@@ -14090,7 +14953,7 @@ static int vmx_set_nested_state(struct kvm_vcpu *vcpu,
14090 return -EINVAL; 14953 return -EINVAL;
14091 14954
14092 vmx->nested.dirty_vmcs12 = true; 14955 vmx->nested.dirty_vmcs12 = true;
14093 ret = enter_vmx_non_root_mode(vcpu, NULL); 14956 ret = nested_vmx_enter_non_root_mode(vcpu, false);
14094 if (ret) 14957 if (ret)
14095 return -EINVAL; 14958 return -EINVAL;
14096 14959
@@ -14242,6 +15105,8 @@ static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
14242 .pre_enter_smm = vmx_pre_enter_smm, 15105 .pre_enter_smm = vmx_pre_enter_smm,
14243 .pre_leave_smm = vmx_pre_leave_smm, 15106 .pre_leave_smm = vmx_pre_leave_smm,
14244 .enable_smi_window = enable_smi_window, 15107 .enable_smi_window = enable_smi_window,
15108
15109 .nested_enable_evmcs = nested_enable_evmcs,
14245}; 15110};
14246 15111
14247static void vmx_cleanup_l1d_flush(void) 15112static void vmx_cleanup_l1d_flush(void)
diff --git a/arch/x86/kvm/vmx_shadow_fields.h b/arch/x86/kvm/vmx_shadow_fields.h
index cd0c75f6d037..132432f375c2 100644
--- a/arch/x86/kvm/vmx_shadow_fields.h
+++ b/arch/x86/kvm/vmx_shadow_fields.h
@@ -28,7 +28,6 @@
28 */ 28 */
29 29
30/* 16-bits */ 30/* 16-bits */
31SHADOW_FIELD_RW(GUEST_CS_SELECTOR)
32SHADOW_FIELD_RW(GUEST_INTR_STATUS) 31SHADOW_FIELD_RW(GUEST_INTR_STATUS)
33SHADOW_FIELD_RW(GUEST_PML_INDEX) 32SHADOW_FIELD_RW(GUEST_PML_INDEX)
34SHADOW_FIELD_RW(HOST_FS_SELECTOR) 33SHADOW_FIELD_RW(HOST_FS_SELECTOR)
@@ -47,8 +46,8 @@ SHADOW_FIELD_RW(VM_ENTRY_EXCEPTION_ERROR_CODE)
47SHADOW_FIELD_RW(VM_ENTRY_INTR_INFO_FIELD) 46SHADOW_FIELD_RW(VM_ENTRY_INTR_INFO_FIELD)
48SHADOW_FIELD_RW(VM_ENTRY_INSTRUCTION_LEN) 47SHADOW_FIELD_RW(VM_ENTRY_INSTRUCTION_LEN)
49SHADOW_FIELD_RW(TPR_THRESHOLD) 48SHADOW_FIELD_RW(TPR_THRESHOLD)
50SHADOW_FIELD_RW(GUEST_CS_LIMIT)
51SHADOW_FIELD_RW(GUEST_CS_AR_BYTES) 49SHADOW_FIELD_RW(GUEST_CS_AR_BYTES)
50SHADOW_FIELD_RW(GUEST_SS_AR_BYTES)
52SHADOW_FIELD_RW(GUEST_INTERRUPTIBILITY_INFO) 51SHADOW_FIELD_RW(GUEST_INTERRUPTIBILITY_INFO)
53SHADOW_FIELD_RW(VMX_PREEMPTION_TIMER_VALUE) 52SHADOW_FIELD_RW(VMX_PREEMPTION_TIMER_VALUE)
54 53
@@ -61,8 +60,6 @@ SHADOW_FIELD_RW(GUEST_CR0)
61SHADOW_FIELD_RW(GUEST_CR3) 60SHADOW_FIELD_RW(GUEST_CR3)
62SHADOW_FIELD_RW(GUEST_CR4) 61SHADOW_FIELD_RW(GUEST_CR4)
63SHADOW_FIELD_RW(GUEST_RFLAGS) 62SHADOW_FIELD_RW(GUEST_RFLAGS)
64SHADOW_FIELD_RW(GUEST_CS_BASE)
65SHADOW_FIELD_RW(GUEST_ES_BASE)
66SHADOW_FIELD_RW(CR0_GUEST_HOST_MASK) 63SHADOW_FIELD_RW(CR0_GUEST_HOST_MASK)
67SHADOW_FIELD_RW(CR0_READ_SHADOW) 64SHADOW_FIELD_RW(CR0_READ_SHADOW)
68SHADOW_FIELD_RW(CR4_READ_SHADOW) 65SHADOW_FIELD_RW(CR4_READ_SHADOW)
diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
index ca717737347e..66d66d77caee 100644
--- a/arch/x86/kvm/x86.c
+++ b/arch/x86/kvm/x86.c
@@ -136,7 +136,7 @@ static u32 __read_mostly tsc_tolerance_ppm = 250;
136module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR); 136module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
137 137
138/* lapic timer advance (tscdeadline mode only) in nanoseconds */ 138/* lapic timer advance (tscdeadline mode only) in nanoseconds */
139unsigned int __read_mostly lapic_timer_advance_ns = 0; 139unsigned int __read_mostly lapic_timer_advance_ns = 1000;
140module_param(lapic_timer_advance_ns, uint, S_IRUGO | S_IWUSR); 140module_param(lapic_timer_advance_ns, uint, S_IRUGO | S_IWUSR);
141EXPORT_SYMBOL_GPL(lapic_timer_advance_ns); 141EXPORT_SYMBOL_GPL(lapic_timer_advance_ns);
142 142
@@ -400,9 +400,51 @@ static int exception_type(int vector)
400 return EXCPT_FAULT; 400 return EXCPT_FAULT;
401} 401}
402 402
403void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu)
404{
405 unsigned nr = vcpu->arch.exception.nr;
406 bool has_payload = vcpu->arch.exception.has_payload;
407 unsigned long payload = vcpu->arch.exception.payload;
408
409 if (!has_payload)
410 return;
411
412 switch (nr) {
413 case DB_VECTOR:
414 /*
415 * "Certain debug exceptions may clear bit 0-3. The
416 * remaining contents of the DR6 register are never
417 * cleared by the processor".
418 */
419 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
420 /*
421 * DR6.RTM is set by all #DB exceptions that don't clear it.
422 */
423 vcpu->arch.dr6 |= DR6_RTM;
424 vcpu->arch.dr6 |= payload;
425 /*
426 * Bit 16 should be set in the payload whenever the #DB
427 * exception should clear DR6.RTM. This makes the payload
428 * compatible with the pending debug exceptions under VMX.
429 * Though not currently documented in the SDM, this also
430 * makes the payload compatible with the exit qualification
431 * for #DB exceptions under VMX.
432 */
433 vcpu->arch.dr6 ^= payload & DR6_RTM;
434 break;
435 case PF_VECTOR:
436 vcpu->arch.cr2 = payload;
437 break;
438 }
439
440 vcpu->arch.exception.has_payload = false;
441 vcpu->arch.exception.payload = 0;
442}
443EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
444
403static void kvm_multiple_exception(struct kvm_vcpu *vcpu, 445static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
404 unsigned nr, bool has_error, u32 error_code, 446 unsigned nr, bool has_error, u32 error_code,
405 bool reinject) 447 bool has_payload, unsigned long payload, bool reinject)
406{ 448{
407 u32 prev_nr; 449 u32 prev_nr;
408 int class1, class2; 450 int class1, class2;
@@ -424,6 +466,14 @@ static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
424 */ 466 */
425 WARN_ON_ONCE(vcpu->arch.exception.pending); 467 WARN_ON_ONCE(vcpu->arch.exception.pending);
426 vcpu->arch.exception.injected = true; 468 vcpu->arch.exception.injected = true;
469 if (WARN_ON_ONCE(has_payload)) {
470 /*
471 * A reinjected event has already
472 * delivered its payload.
473 */
474 has_payload = false;
475 payload = 0;
476 }
427 } else { 477 } else {
428 vcpu->arch.exception.pending = true; 478 vcpu->arch.exception.pending = true;
429 vcpu->arch.exception.injected = false; 479 vcpu->arch.exception.injected = false;
@@ -431,6 +481,22 @@ static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
431 vcpu->arch.exception.has_error_code = has_error; 481 vcpu->arch.exception.has_error_code = has_error;
432 vcpu->arch.exception.nr = nr; 482 vcpu->arch.exception.nr = nr;
433 vcpu->arch.exception.error_code = error_code; 483 vcpu->arch.exception.error_code = error_code;
484 vcpu->arch.exception.has_payload = has_payload;
485 vcpu->arch.exception.payload = payload;
486 /*
487 * In guest mode, payload delivery should be deferred,
488 * so that the L1 hypervisor can intercept #PF before
489 * CR2 is modified (or intercept #DB before DR6 is
490 * modified under nVMX). However, for ABI
491 * compatibility with KVM_GET_VCPU_EVENTS and
492 * KVM_SET_VCPU_EVENTS, we can't delay payload
493 * delivery unless userspace has enabled this
494 * functionality via the per-VM capability,
495 * KVM_CAP_EXCEPTION_PAYLOAD.
496 */
497 if (!vcpu->kvm->arch.exception_payload_enabled ||
498 !is_guest_mode(vcpu))
499 kvm_deliver_exception_payload(vcpu);
434 return; 500 return;
435 } 501 }
436 502
@@ -455,6 +521,8 @@ static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
455 vcpu->arch.exception.has_error_code = true; 521 vcpu->arch.exception.has_error_code = true;
456 vcpu->arch.exception.nr = DF_VECTOR; 522 vcpu->arch.exception.nr = DF_VECTOR;
457 vcpu->arch.exception.error_code = 0; 523 vcpu->arch.exception.error_code = 0;
524 vcpu->arch.exception.has_payload = false;
525 vcpu->arch.exception.payload = 0;
458 } else 526 } else
459 /* replace previous exception with a new one in a hope 527 /* replace previous exception with a new one in a hope
460 that instruction re-execution will regenerate lost 528 that instruction re-execution will regenerate lost
@@ -464,16 +532,29 @@ static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
464 532
465void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr) 533void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
466{ 534{
467 kvm_multiple_exception(vcpu, nr, false, 0, false); 535 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, false);
468} 536}
469EXPORT_SYMBOL_GPL(kvm_queue_exception); 537EXPORT_SYMBOL_GPL(kvm_queue_exception);
470 538
471void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr) 539void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
472{ 540{
473 kvm_multiple_exception(vcpu, nr, false, 0, true); 541 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, true);
474} 542}
475EXPORT_SYMBOL_GPL(kvm_requeue_exception); 543EXPORT_SYMBOL_GPL(kvm_requeue_exception);
476 544
545static void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
546 unsigned long payload)
547{
548 kvm_multiple_exception(vcpu, nr, false, 0, true, payload, false);
549}
550
551static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
552 u32 error_code, unsigned long payload)
553{
554 kvm_multiple_exception(vcpu, nr, true, error_code,
555 true, payload, false);
556}
557
477int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err) 558int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
478{ 559{
479 if (err) 560 if (err)
@@ -490,11 +571,13 @@ void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
490 ++vcpu->stat.pf_guest; 571 ++vcpu->stat.pf_guest;
491 vcpu->arch.exception.nested_apf = 572 vcpu->arch.exception.nested_apf =
492 is_guest_mode(vcpu) && fault->async_page_fault; 573 is_guest_mode(vcpu) && fault->async_page_fault;
493 if (vcpu->arch.exception.nested_apf) 574 if (vcpu->arch.exception.nested_apf) {
494 vcpu->arch.apf.nested_apf_token = fault->address; 575 vcpu->arch.apf.nested_apf_token = fault->address;
495 else 576 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
496 vcpu->arch.cr2 = fault->address; 577 } else {
497 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code); 578 kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
579 fault->address);
580 }
498} 581}
499EXPORT_SYMBOL_GPL(kvm_inject_page_fault); 582EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
500 583
@@ -503,7 +586,7 @@ static bool kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fau
503 if (mmu_is_nested(vcpu) && !fault->nested_page_fault) 586 if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
504 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault); 587 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
505 else 588 else
506 vcpu->arch.mmu.inject_page_fault(vcpu, fault); 589 vcpu->arch.mmu->inject_page_fault(vcpu, fault);
507 590
508 return fault->nested_page_fault; 591 return fault->nested_page_fault;
509} 592}
@@ -517,13 +600,13 @@ EXPORT_SYMBOL_GPL(kvm_inject_nmi);
517 600
518void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code) 601void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
519{ 602{
520 kvm_multiple_exception(vcpu, nr, true, error_code, false); 603 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, false);
521} 604}
522EXPORT_SYMBOL_GPL(kvm_queue_exception_e); 605EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
523 606
524void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code) 607void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
525{ 608{
526 kvm_multiple_exception(vcpu, nr, true, error_code, true); 609 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, true);
527} 610}
528EXPORT_SYMBOL_GPL(kvm_requeue_exception_e); 611EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
529 612
@@ -602,7 +685,7 @@ int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
602 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) { 685 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
603 if ((pdpte[i] & PT_PRESENT_MASK) && 686 if ((pdpte[i] & PT_PRESENT_MASK) &&
604 (pdpte[i] & 687 (pdpte[i] &
605 vcpu->arch.mmu.guest_rsvd_check.rsvd_bits_mask[0][2])) { 688 vcpu->arch.mmu->guest_rsvd_check.rsvd_bits_mask[0][2])) {
606 ret = 0; 689 ret = 0;
607 goto out; 690 goto out;
608 } 691 }
@@ -2477,7 +2560,7 @@ int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2477 2560
2478 break; 2561 break;
2479 case MSR_KVM_PV_EOI_EN: 2562 case MSR_KVM_PV_EOI_EN:
2480 if (kvm_lapic_enable_pv_eoi(vcpu, data)) 2563 if (kvm_lapic_enable_pv_eoi(vcpu, data, sizeof(u8)))
2481 return 1; 2564 return 1;
2482 break; 2565 break;
2483 2566
@@ -2912,6 +2995,8 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
2912 case KVM_CAP_HYPERV_VP_INDEX: 2995 case KVM_CAP_HYPERV_VP_INDEX:
2913 case KVM_CAP_HYPERV_EVENTFD: 2996 case KVM_CAP_HYPERV_EVENTFD:
2914 case KVM_CAP_HYPERV_TLBFLUSH: 2997 case KVM_CAP_HYPERV_TLBFLUSH:
2998 case KVM_CAP_HYPERV_SEND_IPI:
2999 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
2915 case KVM_CAP_PCI_SEGMENT: 3000 case KVM_CAP_PCI_SEGMENT:
2916 case KVM_CAP_DEBUGREGS: 3001 case KVM_CAP_DEBUGREGS:
2917 case KVM_CAP_X86_ROBUST_SINGLESTEP: 3002 case KVM_CAP_X86_ROBUST_SINGLESTEP:
@@ -2930,6 +3015,7 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
2930 case KVM_CAP_IMMEDIATE_EXIT: 3015 case KVM_CAP_IMMEDIATE_EXIT:
2931 case KVM_CAP_GET_MSR_FEATURES: 3016 case KVM_CAP_GET_MSR_FEATURES:
2932 case KVM_CAP_MSR_PLATFORM_INFO: 3017 case KVM_CAP_MSR_PLATFORM_INFO:
3018 case KVM_CAP_EXCEPTION_PAYLOAD:
2933 r = 1; 3019 r = 1;
2934 break; 3020 break;
2935 case KVM_CAP_SYNC_REGS: 3021 case KVM_CAP_SYNC_REGS:
@@ -3362,19 +3448,33 @@ static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3362 struct kvm_vcpu_events *events) 3448 struct kvm_vcpu_events *events)
3363{ 3449{
3364 process_nmi(vcpu); 3450 process_nmi(vcpu);
3451
3365 /* 3452 /*
3366 * FIXME: pass injected and pending separately. This is only 3453 * The API doesn't provide the instruction length for software
3367 * needed for nested virtualization, whose state cannot be 3454 * exceptions, so don't report them. As long as the guest RIP
3368 * migrated yet. For now we can combine them. 3455 * isn't advanced, we should expect to encounter the exception
3456 * again.
3369 */ 3457 */
3370 events->exception.injected = 3458 if (kvm_exception_is_soft(vcpu->arch.exception.nr)) {
3371 (vcpu->arch.exception.pending || 3459 events->exception.injected = 0;
3372 vcpu->arch.exception.injected) && 3460 events->exception.pending = 0;
3373 !kvm_exception_is_soft(vcpu->arch.exception.nr); 3461 } else {
3462 events->exception.injected = vcpu->arch.exception.injected;
3463 events->exception.pending = vcpu->arch.exception.pending;
3464 /*
3465 * For ABI compatibility, deliberately conflate
3466 * pending and injected exceptions when
3467 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
3468 */
3469 if (!vcpu->kvm->arch.exception_payload_enabled)
3470 events->exception.injected |=
3471 vcpu->arch.exception.pending;
3472 }
3374 events->exception.nr = vcpu->arch.exception.nr; 3473 events->exception.nr = vcpu->arch.exception.nr;
3375 events->exception.has_error_code = vcpu->arch.exception.has_error_code; 3474 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3376 events->exception.pad = 0;
3377 events->exception.error_code = vcpu->arch.exception.error_code; 3475 events->exception.error_code = vcpu->arch.exception.error_code;
3476 events->exception_has_payload = vcpu->arch.exception.has_payload;
3477 events->exception_payload = vcpu->arch.exception.payload;
3378 3478
3379 events->interrupt.injected = 3479 events->interrupt.injected =
3380 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft; 3480 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
@@ -3398,6 +3498,9 @@ static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3398 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING 3498 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3399 | KVM_VCPUEVENT_VALID_SHADOW 3499 | KVM_VCPUEVENT_VALID_SHADOW
3400 | KVM_VCPUEVENT_VALID_SMM); 3500 | KVM_VCPUEVENT_VALID_SMM);
3501 if (vcpu->kvm->arch.exception_payload_enabled)
3502 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
3503
3401 memset(&events->reserved, 0, sizeof(events->reserved)); 3504 memset(&events->reserved, 0, sizeof(events->reserved));
3402} 3505}
3403 3506
@@ -3409,12 +3512,24 @@ static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3409 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING 3512 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3410 | KVM_VCPUEVENT_VALID_SIPI_VECTOR 3513 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3411 | KVM_VCPUEVENT_VALID_SHADOW 3514 | KVM_VCPUEVENT_VALID_SHADOW
3412 | KVM_VCPUEVENT_VALID_SMM)) 3515 | KVM_VCPUEVENT_VALID_SMM
3516 | KVM_VCPUEVENT_VALID_PAYLOAD))
3413 return -EINVAL; 3517 return -EINVAL;
3414 3518
3415 if (events->exception.injected && 3519 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
3416 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR || 3520 if (!vcpu->kvm->arch.exception_payload_enabled)
3417 is_guest_mode(vcpu))) 3521 return -EINVAL;
3522 if (events->exception.pending)
3523 events->exception.injected = 0;
3524 else
3525 events->exception_has_payload = 0;
3526 } else {
3527 events->exception.pending = 0;
3528 events->exception_has_payload = 0;
3529 }
3530
3531 if ((events->exception.injected || events->exception.pending) &&
3532 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
3418 return -EINVAL; 3533 return -EINVAL;
3419 3534
3420 /* INITs are latched while in SMM */ 3535 /* INITs are latched while in SMM */
@@ -3424,11 +3539,13 @@ static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3424 return -EINVAL; 3539 return -EINVAL;
3425 3540
3426 process_nmi(vcpu); 3541 process_nmi(vcpu);
3427 vcpu->arch.exception.injected = false; 3542 vcpu->arch.exception.injected = events->exception.injected;
3428 vcpu->arch.exception.pending = events->exception.injected; 3543 vcpu->arch.exception.pending = events->exception.pending;
3429 vcpu->arch.exception.nr = events->exception.nr; 3544 vcpu->arch.exception.nr = events->exception.nr;
3430 vcpu->arch.exception.has_error_code = events->exception.has_error_code; 3545 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3431 vcpu->arch.exception.error_code = events->exception.error_code; 3546 vcpu->arch.exception.error_code = events->exception.error_code;
3547 vcpu->arch.exception.has_payload = events->exception_has_payload;
3548 vcpu->arch.exception.payload = events->exception_payload;
3432 3549
3433 vcpu->arch.interrupt.injected = events->interrupt.injected; 3550 vcpu->arch.interrupt.injected = events->interrupt.injected;
3434 vcpu->arch.interrupt.nr = events->interrupt.nr; 3551 vcpu->arch.interrupt.nr = events->interrupt.nr;
@@ -3694,6 +3811,10 @@ static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3694static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu, 3811static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
3695 struct kvm_enable_cap *cap) 3812 struct kvm_enable_cap *cap)
3696{ 3813{
3814 int r;
3815 uint16_t vmcs_version;
3816 void __user *user_ptr;
3817
3697 if (cap->flags) 3818 if (cap->flags)
3698 return -EINVAL; 3819 return -EINVAL;
3699 3820
@@ -3706,6 +3827,16 @@ static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
3706 return -EINVAL; 3827 return -EINVAL;
3707 return kvm_hv_activate_synic(vcpu, cap->cap == 3828 return kvm_hv_activate_synic(vcpu, cap->cap ==
3708 KVM_CAP_HYPERV_SYNIC2); 3829 KVM_CAP_HYPERV_SYNIC2);
3830 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
3831 r = kvm_x86_ops->nested_enable_evmcs(vcpu, &vmcs_version);
3832 if (!r) {
3833 user_ptr = (void __user *)(uintptr_t)cap->args[0];
3834 if (copy_to_user(user_ptr, &vmcs_version,
3835 sizeof(vmcs_version)))
3836 r = -EFAULT;
3837 }
3838 return r;
3839
3709 default: 3840 default:
3710 return -EINVAL; 3841 return -EINVAL;
3711 } 3842 }
@@ -4047,11 +4178,13 @@ long kvm_arch_vcpu_ioctl(struct file *filp,
4047 break; 4178 break;
4048 4179
4049 if (kvm_state.flags & 4180 if (kvm_state.flags &
4050 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE)) 4181 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
4182 | KVM_STATE_NESTED_EVMCS))
4051 break; 4183 break;
4052 4184
4053 /* nested_run_pending implies guest_mode. */ 4185 /* nested_run_pending implies guest_mode. */
4054 if (kvm_state.flags == KVM_STATE_NESTED_RUN_PENDING) 4186 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
4187 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
4055 break; 4188 break;
4056 4189
4057 r = kvm_x86_ops->set_nested_state(vcpu, user_kvm_nested_state, &kvm_state); 4190 r = kvm_x86_ops->set_nested_state(vcpu, user_kvm_nested_state, &kvm_state);
@@ -4363,6 +4496,10 @@ split_irqchip_unlock:
4363 kvm->arch.guest_can_read_msr_platform_info = cap->args[0]; 4496 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
4364 r = 0; 4497 r = 0;
4365 break; 4498 break;
4499 case KVM_CAP_EXCEPTION_PAYLOAD:
4500 kvm->arch.exception_payload_enabled = cap->args[0];
4501 r = 0;
4502 break;
4366 default: 4503 default:
4367 r = -EINVAL; 4504 r = -EINVAL;
4368 break; 4505 break;
@@ -4803,7 +4940,7 @@ gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
4803 4940
4804 /* NPT walks are always user-walks */ 4941 /* NPT walks are always user-walks */
4805 access |= PFERR_USER_MASK; 4942 access |= PFERR_USER_MASK;
4806 t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, exception); 4943 t_gpa = vcpu->arch.mmu->gva_to_gpa(vcpu, gpa, access, exception);
4807 4944
4808 return t_gpa; 4945 return t_gpa;
4809} 4946}
@@ -5889,7 +6026,7 @@ static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
5889 if (WARN_ON_ONCE(is_guest_mode(vcpu))) 6026 if (WARN_ON_ONCE(is_guest_mode(vcpu)))
5890 return false; 6027 return false;
5891 6028
5892 if (!vcpu->arch.mmu.direct_map) { 6029 if (!vcpu->arch.mmu->direct_map) {
5893 /* 6030 /*
5894 * Write permission should be allowed since only 6031 * Write permission should be allowed since only
5895 * write access need to be emulated. 6032 * write access need to be emulated.
@@ -5922,7 +6059,7 @@ static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
5922 kvm_release_pfn_clean(pfn); 6059 kvm_release_pfn_clean(pfn);
5923 6060
5924 /* The instructions are well-emulated on direct mmu. */ 6061 /* The instructions are well-emulated on direct mmu. */
5925 if (vcpu->arch.mmu.direct_map) { 6062 if (vcpu->arch.mmu->direct_map) {
5926 unsigned int indirect_shadow_pages; 6063 unsigned int indirect_shadow_pages;
5927 6064
5928 spin_lock(&vcpu->kvm->mmu_lock); 6065 spin_lock(&vcpu->kvm->mmu_lock);
@@ -5989,7 +6126,7 @@ static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
5989 vcpu->arch.last_retry_eip = ctxt->eip; 6126 vcpu->arch.last_retry_eip = ctxt->eip;
5990 vcpu->arch.last_retry_addr = cr2; 6127 vcpu->arch.last_retry_addr = cr2;
5991 6128
5992 if (!vcpu->arch.mmu.direct_map) 6129 if (!vcpu->arch.mmu->direct_map)
5993 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL); 6130 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5994 6131
5995 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa)); 6132 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
@@ -6049,14 +6186,7 @@ static void kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu, int *r)
6049 kvm_run->exit_reason = KVM_EXIT_DEBUG; 6186 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6050 *r = EMULATE_USER_EXIT; 6187 *r = EMULATE_USER_EXIT;
6051 } else { 6188 } else {
6052 /* 6189 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
6053 * "Certain debug exceptions may clear bit 0-3. The
6054 * remaining contents of the DR6 register are never
6055 * cleared by the processor".
6056 */
6057 vcpu->arch.dr6 &= ~15;
6058 vcpu->arch.dr6 |= DR6_BS | DR6_RTM;
6059 kvm_queue_exception(vcpu, DB_VECTOR);
6060 } 6190 }
6061} 6191}
6062 6192
@@ -6995,10 +7125,22 @@ static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
6995 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) | 7125 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
6996 X86_EFLAGS_RF); 7126 X86_EFLAGS_RF);
6997 7127
6998 if (vcpu->arch.exception.nr == DB_VECTOR && 7128 if (vcpu->arch.exception.nr == DB_VECTOR) {
6999 (vcpu->arch.dr7 & DR7_GD)) { 7129 /*
7000 vcpu->arch.dr7 &= ~DR7_GD; 7130 * This code assumes that nSVM doesn't use
7001 kvm_update_dr7(vcpu); 7131 * check_nested_events(). If it does, the
7132 * DR6/DR7 changes should happen before L1
7133 * gets a #VMEXIT for an intercepted #DB in
7134 * L2. (Under VMX, on the other hand, the
7135 * DR6/DR7 changes should not happen in the
7136 * event of a VM-exit to L1 for an intercepted
7137 * #DB in L2.)
7138 */
7139 kvm_deliver_exception_payload(vcpu);
7140 if (vcpu->arch.dr7 & DR7_GD) {
7141 vcpu->arch.dr7 &= ~DR7_GD;
7142 kvm_update_dr7(vcpu);
7143 }
7002 } 7144 }
7003 7145
7004 kvm_x86_ops->queue_exception(vcpu); 7146 kvm_x86_ops->queue_exception(vcpu);
@@ -8478,7 +8620,7 @@ int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
8478 kvm_vcpu_mtrr_init(vcpu); 8620 kvm_vcpu_mtrr_init(vcpu);
8479 vcpu_load(vcpu); 8621 vcpu_load(vcpu);
8480 kvm_vcpu_reset(vcpu, false); 8622 kvm_vcpu_reset(vcpu, false);
8481 kvm_mmu_setup(vcpu); 8623 kvm_init_mmu(vcpu, false);
8482 vcpu_put(vcpu); 8624 vcpu_put(vcpu);
8483 return 0; 8625 return 0;
8484} 8626}
@@ -9327,7 +9469,7 @@ void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
9327{ 9469{
9328 int r; 9470 int r;
9329 9471
9330 if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) || 9472 if ((vcpu->arch.mmu->direct_map != work->arch.direct_map) ||
9331 work->wakeup_all) 9473 work->wakeup_all)
9332 return; 9474 return;
9333 9475
@@ -9335,11 +9477,11 @@ void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
9335 if (unlikely(r)) 9477 if (unlikely(r))
9336 return; 9478 return;
9337 9479
9338 if (!vcpu->arch.mmu.direct_map && 9480 if (!vcpu->arch.mmu->direct_map &&
9339 work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu)) 9481 work->arch.cr3 != vcpu->arch.mmu->get_cr3(vcpu))
9340 return; 9482 return;
9341 9483
9342 vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true); 9484 vcpu->arch.mmu->page_fault(vcpu, work->gva, 0, true);
9343} 9485}
9344 9486
9345static inline u32 kvm_async_pf_hash_fn(gfn_t gfn) 9487static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
@@ -9463,6 +9605,8 @@ void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
9463 vcpu->arch.exception.nr = 0; 9605 vcpu->arch.exception.nr = 0;
9464 vcpu->arch.exception.has_error_code = false; 9606 vcpu->arch.exception.has_error_code = false;
9465 vcpu->arch.exception.error_code = 0; 9607 vcpu->arch.exception.error_code = 0;
9608 vcpu->arch.exception.has_payload = false;
9609 vcpu->arch.exception.payload = 0;
9466 } else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) { 9610 } else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
9467 fault.vector = PF_VECTOR; 9611 fault.vector = PF_VECTOR;
9468 fault.error_code_valid = true; 9612 fault.error_code_valid = true;
diff --git a/arch/x86/kvm/x86.h b/arch/x86/kvm/x86.h
index 67b9568613f3..224cd0a47568 100644
--- a/arch/x86/kvm/x86.h
+++ b/arch/x86/kvm/x86.h
@@ -266,6 +266,8 @@ int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu,
266 266
267int handle_ud(struct kvm_vcpu *vcpu); 267int handle_ud(struct kvm_vcpu *vcpu);
268 268
269void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu);
270
269void kvm_vcpu_mtrr_init(struct kvm_vcpu *vcpu); 271void kvm_vcpu_mtrr_init(struct kvm_vcpu *vcpu);
270u8 kvm_mtrr_get_guest_memory_type(struct kvm_vcpu *vcpu, gfn_t gfn); 272u8 kvm_mtrr_get_guest_memory_type(struct kvm_vcpu *vcpu, gfn_t gfn);
271bool kvm_mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data); 273bool kvm_mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data);
diff --git a/drivers/iommu/Kconfig b/drivers/iommu/Kconfig
index c60395b7470f..83e6d993fca5 100644
--- a/drivers/iommu/Kconfig
+++ b/drivers/iommu/Kconfig
@@ -372,6 +372,14 @@ config S390_CCW_IOMMU
372 Enables bits of IOMMU API required by VFIO. The iommu_ops 372 Enables bits of IOMMU API required by VFIO. The iommu_ops
373 is not implemented as it is not necessary for VFIO. 373 is not implemented as it is not necessary for VFIO.
374 374
375config S390_AP_IOMMU
376 bool "S390 AP IOMMU Support"
377 depends on S390 && ZCRYPT
378 select IOMMU_API
379 help
380 Enables bits of IOMMU API required by VFIO. The iommu_ops
381 is not implemented as it is not necessary for VFIO.
382
375config MTK_IOMMU 383config MTK_IOMMU
376 bool "MTK IOMMU Support" 384 bool "MTK IOMMU Support"
377 depends on ARM || ARM64 385 depends on ARM || ARM64
diff --git a/drivers/s390/crypto/Makefile b/drivers/s390/crypto/Makefile
index fd5e215c66b7..6ccd93d0b1cb 100644
--- a/drivers/s390/crypto/Makefile
+++ b/drivers/s390/crypto/Makefile
@@ -15,3 +15,7 @@ obj-$(CONFIG_ZCRYPT) += zcrypt_cex2c.o zcrypt_cex2a.o zcrypt_cex4.o
15# pkey kernel module 15# pkey kernel module
16pkey-objs := pkey_api.o 16pkey-objs := pkey_api.o
17obj-$(CONFIG_PKEY) += pkey.o 17obj-$(CONFIG_PKEY) += pkey.o
18
19# adjunct processor matrix
20vfio_ap-objs := vfio_ap_drv.o vfio_ap_ops.o
21obj-$(CONFIG_VFIO_AP) += vfio_ap.o
diff --git a/drivers/s390/crypto/vfio_ap_drv.c b/drivers/s390/crypto/vfio_ap_drv.c
new file mode 100644
index 000000000000..7667b38728f0
--- /dev/null
+++ b/drivers/s390/crypto/vfio_ap_drv.c
@@ -0,0 +1,157 @@
1// SPDX-License-Identifier: GPL-2.0+
2/*
3 * VFIO based AP device driver
4 *
5 * Copyright IBM Corp. 2018
6 *
7 * Author(s): Tony Krowiak <akrowiak@linux.ibm.com>
8 */
9
10#include <linux/module.h>
11#include <linux/mod_devicetable.h>
12#include <linux/slab.h>
13#include <linux/string.h>
14#include "vfio_ap_private.h"
15
16#define VFIO_AP_ROOT_NAME "vfio_ap"
17#define VFIO_AP_DEV_TYPE_NAME "ap_matrix"
18#define VFIO_AP_DEV_NAME "matrix"
19
20MODULE_AUTHOR("IBM Corporation");
21MODULE_DESCRIPTION("VFIO AP device driver, Copyright IBM Corp. 2018");
22MODULE_LICENSE("GPL v2");
23
24static struct ap_driver vfio_ap_drv;
25
26static struct device_type vfio_ap_dev_type = {
27 .name = VFIO_AP_DEV_TYPE_NAME,
28};
29
30struct ap_matrix_dev *matrix_dev;
31
32/* Only type 10 adapters (CEX4 and later) are supported
33 * by the AP matrix device driver
34 */
35static struct ap_device_id ap_queue_ids[] = {
36 { .dev_type = AP_DEVICE_TYPE_CEX4,
37 .match_flags = AP_DEVICE_ID_MATCH_QUEUE_TYPE },
38 { .dev_type = AP_DEVICE_TYPE_CEX5,
39 .match_flags = AP_DEVICE_ID_MATCH_QUEUE_TYPE },
40 { .dev_type = AP_DEVICE_TYPE_CEX6,
41 .match_flags = AP_DEVICE_ID_MATCH_QUEUE_TYPE },
42 { /* end of sibling */ },
43};
44
45MODULE_DEVICE_TABLE(vfio_ap, ap_queue_ids);
46
47static int vfio_ap_queue_dev_probe(struct ap_device *apdev)
48{
49 return 0;
50}
51
52static void vfio_ap_queue_dev_remove(struct ap_device *apdev)
53{
54 /* Nothing to do yet */
55}
56
57static void vfio_ap_matrix_dev_release(struct device *dev)
58{
59 struct ap_matrix_dev *matrix_dev = dev_get_drvdata(dev);
60
61 kfree(matrix_dev);
62}
63
64static int vfio_ap_matrix_dev_create(void)
65{
66 int ret;
67 struct device *root_device;
68
69 root_device = root_device_register(VFIO_AP_ROOT_NAME);
70 if (IS_ERR(root_device))
71 return PTR_ERR(root_device);
72
73 matrix_dev = kzalloc(sizeof(*matrix_dev), GFP_KERNEL);
74 if (!matrix_dev) {
75 ret = -ENOMEM;
76 goto matrix_alloc_err;
77 }
78
79 /* Fill in config info via PQAP(QCI), if available */
80 if (test_facility(12)) {
81 ret = ap_qci(&matrix_dev->info);
82 if (ret)
83 goto matrix_alloc_err;
84 }
85
86 mutex_init(&matrix_dev->lock);
87 INIT_LIST_HEAD(&matrix_dev->mdev_list);
88
89 matrix_dev->device.type = &vfio_ap_dev_type;
90 dev_set_name(&matrix_dev->device, "%s", VFIO_AP_DEV_NAME);
91 matrix_dev->device.parent = root_device;
92 matrix_dev->device.release = vfio_ap_matrix_dev_release;
93 matrix_dev->device.driver = &vfio_ap_drv.driver;
94
95 ret = device_register(&matrix_dev->device);
96 if (ret)
97 goto matrix_reg_err;
98
99 return 0;
100
101matrix_reg_err:
102 put_device(&matrix_dev->device);
103matrix_alloc_err:
104 root_device_unregister(root_device);
105
106 return ret;
107}
108
109static void vfio_ap_matrix_dev_destroy(void)
110{
111 device_unregister(&matrix_dev->device);
112 root_device_unregister(matrix_dev->device.parent);
113}
114
115static int __init vfio_ap_init(void)
116{
117 int ret;
118
119 /* If there are no AP instructions, there is nothing to pass through. */
120 if (!ap_instructions_available())
121 return -ENODEV;
122
123 ret = vfio_ap_matrix_dev_create();
124 if (ret)
125 return ret;
126
127 memset(&vfio_ap_drv, 0, sizeof(vfio_ap_drv));
128 vfio_ap_drv.probe = vfio_ap_queue_dev_probe;
129 vfio_ap_drv.remove = vfio_ap_queue_dev_remove;
130 vfio_ap_drv.ids = ap_queue_ids;
131
132 ret = ap_driver_register(&vfio_ap_drv, THIS_MODULE, VFIO_AP_DRV_NAME);
133 if (ret) {
134 vfio_ap_matrix_dev_destroy();
135 return ret;
136 }
137
138 ret = vfio_ap_mdev_register();
139 if (ret) {
140 ap_driver_unregister(&vfio_ap_drv);
141 vfio_ap_matrix_dev_destroy();
142
143 return ret;
144 }
145
146 return 0;
147}
148
149static void __exit vfio_ap_exit(void)
150{
151 vfio_ap_mdev_unregister();
152 ap_driver_unregister(&vfio_ap_drv);
153 vfio_ap_matrix_dev_destroy();
154}
155
156module_init(vfio_ap_init);
157module_exit(vfio_ap_exit);
diff --git a/drivers/s390/crypto/vfio_ap_ops.c b/drivers/s390/crypto/vfio_ap_ops.c
new file mode 100644
index 000000000000..272ef427dcc0
--- /dev/null
+++ b/drivers/s390/crypto/vfio_ap_ops.c
@@ -0,0 +1,939 @@
1// SPDX-License-Identifier: GPL-2.0+
2/*
3 * Adjunct processor matrix VFIO device driver callbacks.
4 *
5 * Copyright IBM Corp. 2018
6 *
7 * Author(s): Tony Krowiak <akrowiak@linux.ibm.com>
8 * Halil Pasic <pasic@linux.ibm.com>
9 * Pierre Morel <pmorel@linux.ibm.com>
10 */
11#include <linux/string.h>
12#include <linux/vfio.h>
13#include <linux/device.h>
14#include <linux/list.h>
15#include <linux/ctype.h>
16#include <linux/bitops.h>
17#include <linux/kvm_host.h>
18#include <linux/module.h>
19#include <asm/kvm.h>
20#include <asm/zcrypt.h>
21
22#include "vfio_ap_private.h"
23
24#define VFIO_AP_MDEV_TYPE_HWVIRT "passthrough"
25#define VFIO_AP_MDEV_NAME_HWVIRT "VFIO AP Passthrough Device"
26
27static void vfio_ap_matrix_init(struct ap_config_info *info,
28 struct ap_matrix *matrix)
29{
30 matrix->apm_max = info->apxa ? info->Na : 63;
31 matrix->aqm_max = info->apxa ? info->Nd : 15;
32 matrix->adm_max = info->apxa ? info->Nd : 15;
33}
34
35static int vfio_ap_mdev_create(struct kobject *kobj, struct mdev_device *mdev)
36{
37 struct ap_matrix_mdev *matrix_mdev;
38
39 if ((atomic_dec_if_positive(&matrix_dev->available_instances) < 0))
40 return -EPERM;
41
42 matrix_mdev = kzalloc(sizeof(*matrix_mdev), GFP_KERNEL);
43 if (!matrix_mdev) {
44 atomic_inc(&matrix_dev->available_instances);
45 return -ENOMEM;
46 }
47
48 vfio_ap_matrix_init(&matrix_dev->info, &matrix_mdev->matrix);
49 mdev_set_drvdata(mdev, matrix_mdev);
50 mutex_lock(&matrix_dev->lock);
51 list_add(&matrix_mdev->node, &matrix_dev->mdev_list);
52 mutex_unlock(&matrix_dev->lock);
53
54 return 0;
55}
56
57static int vfio_ap_mdev_remove(struct mdev_device *mdev)
58{
59 struct ap_matrix_mdev *matrix_mdev = mdev_get_drvdata(mdev);
60
61 if (matrix_mdev->kvm)
62 return -EBUSY;
63
64 mutex_lock(&matrix_dev->lock);
65 list_del(&matrix_mdev->node);
66 mutex_unlock(&matrix_dev->lock);
67
68 kfree(matrix_mdev);
69 mdev_set_drvdata(mdev, NULL);
70 atomic_inc(&matrix_dev->available_instances);
71
72 return 0;
73}
74
75static ssize_t name_show(struct kobject *kobj, struct device *dev, char *buf)
76{
77 return sprintf(buf, "%s\n", VFIO_AP_MDEV_NAME_HWVIRT);
78}
79
80static MDEV_TYPE_ATTR_RO(name);
81
82static ssize_t available_instances_show(struct kobject *kobj,
83 struct device *dev, char *buf)
84{
85 return sprintf(buf, "%d\n",
86 atomic_read(&matrix_dev->available_instances));
87}
88
89static MDEV_TYPE_ATTR_RO(available_instances);
90
91static ssize_t device_api_show(struct kobject *kobj, struct device *dev,
92 char *buf)
93{
94 return sprintf(buf, "%s\n", VFIO_DEVICE_API_AP_STRING);
95}
96
97static MDEV_TYPE_ATTR_RO(device_api);
98
99static struct attribute *vfio_ap_mdev_type_attrs[] = {
100 &mdev_type_attr_name.attr,
101 &mdev_type_attr_device_api.attr,
102 &mdev_type_attr_available_instances.attr,
103 NULL,
104};
105
106static struct attribute_group vfio_ap_mdev_hwvirt_type_group = {
107 .name = VFIO_AP_MDEV_TYPE_HWVIRT,
108 .attrs = vfio_ap_mdev_type_attrs,
109};
110
111static struct attribute_group *vfio_ap_mdev_type_groups[] = {
112 &vfio_ap_mdev_hwvirt_type_group,
113 NULL,
114};
115
116struct vfio_ap_queue_reserved {
117 unsigned long *apid;
118 unsigned long *apqi;
119 bool reserved;
120};
121
122/**
123 * vfio_ap_has_queue
124 *
125 * @dev: an AP queue device
126 * @data: a struct vfio_ap_queue_reserved reference
127 *
128 * Flags whether the AP queue device (@dev) has a queue ID containing the APQN,
129 * apid or apqi specified in @data:
130 *
131 * - If @data contains both an apid and apqi value, then @data will be flagged
132 * as reserved if the APID and APQI fields for the AP queue device matches
133 *
134 * - If @data contains only an apid value, @data will be flagged as
135 * reserved if the APID field in the AP queue device matches
136 *
137 * - If @data contains only an apqi value, @data will be flagged as
138 * reserved if the APQI field in the AP queue device matches
139 *
140 * Returns 0 to indicate the input to function succeeded. Returns -EINVAL if
141 * @data does not contain either an apid or apqi.
142 */
143static int vfio_ap_has_queue(struct device *dev, void *data)
144{
145 struct vfio_ap_queue_reserved *qres = data;
146 struct ap_queue *ap_queue = to_ap_queue(dev);
147 ap_qid_t qid;
148 unsigned long id;
149
150 if (qres->apid && qres->apqi) {
151 qid = AP_MKQID(*qres->apid, *qres->apqi);
152 if (qid == ap_queue->qid)
153 qres->reserved = true;
154 } else if (qres->apid && !qres->apqi) {
155 id = AP_QID_CARD(ap_queue->qid);
156 if (id == *qres->apid)
157 qres->reserved = true;
158 } else if (!qres->apid && qres->apqi) {
159 id = AP_QID_QUEUE(ap_queue->qid);
160 if (id == *qres->apqi)
161 qres->reserved = true;
162 } else {
163 return -EINVAL;
164 }
165
166 return 0;
167}
168
169/**
170 * vfio_ap_verify_queue_reserved
171 *
172 * @matrix_dev: a mediated matrix device
173 * @apid: an AP adapter ID
174 * @apqi: an AP queue index
175 *
176 * Verifies that the AP queue with @apid/@apqi is reserved by the VFIO AP device
177 * driver according to the following rules:
178 *
179 * - If both @apid and @apqi are not NULL, then there must be an AP queue
180 * device bound to the vfio_ap driver with the APQN identified by @apid and
181 * @apqi
182 *
183 * - If only @apid is not NULL, then there must be an AP queue device bound
184 * to the vfio_ap driver with an APQN containing @apid
185 *
186 * - If only @apqi is not NULL, then there must be an AP queue device bound
187 * to the vfio_ap driver with an APQN containing @apqi
188 *
189 * Returns 0 if the AP queue is reserved; otherwise, returns -EADDRNOTAVAIL.
190 */
191static int vfio_ap_verify_queue_reserved(unsigned long *apid,
192 unsigned long *apqi)
193{
194 int ret;
195 struct vfio_ap_queue_reserved qres;
196
197 qres.apid = apid;
198 qres.apqi = apqi;
199 qres.reserved = false;
200
201 ret = driver_for_each_device(matrix_dev->device.driver, NULL, &qres,
202 vfio_ap_has_queue);
203 if (ret)
204 return ret;
205
206 if (qres.reserved)
207 return 0;
208
209 return -EADDRNOTAVAIL;
210}
211
212static int
213vfio_ap_mdev_verify_queues_reserved_for_apid(struct ap_matrix_mdev *matrix_mdev,
214 unsigned long apid)
215{
216 int ret;
217 unsigned long apqi;
218 unsigned long nbits = matrix_mdev->matrix.aqm_max + 1;
219
220 if (find_first_bit_inv(matrix_mdev->matrix.aqm, nbits) >= nbits)
221 return vfio_ap_verify_queue_reserved(&apid, NULL);
222
223 for_each_set_bit_inv(apqi, matrix_mdev->matrix.aqm, nbits) {
224 ret = vfio_ap_verify_queue_reserved(&apid, &apqi);
225 if (ret)
226 return ret;
227 }
228
229 return 0;
230}
231
232/**
233 * vfio_ap_mdev_verify_no_sharing
234 *
235 * Verifies that the APQNs derived from the cross product of the AP adapter IDs
236 * and AP queue indexes comprising the AP matrix are not configured for another
237 * mediated device. AP queue sharing is not allowed.
238 *
239 * @matrix_mdev: the mediated matrix device
240 *
241 * Returns 0 if the APQNs are not shared, otherwise; returns -EADDRINUSE.
242 */
243static int vfio_ap_mdev_verify_no_sharing(struct ap_matrix_mdev *matrix_mdev)
244{
245 struct ap_matrix_mdev *lstdev;
246 DECLARE_BITMAP(apm, AP_DEVICES);
247 DECLARE_BITMAP(aqm, AP_DOMAINS);
248
249 list_for_each_entry(lstdev, &matrix_dev->mdev_list, node) {
250 if (matrix_mdev == lstdev)
251 continue;
252
253 memset(apm, 0, sizeof(apm));
254 memset(aqm, 0, sizeof(aqm));
255
256 /*
257 * We work on full longs, as we can only exclude the leftover
258 * bits in non-inverse order. The leftover is all zeros.
259 */
260 if (!bitmap_and(apm, matrix_mdev->matrix.apm,
261 lstdev->matrix.apm, AP_DEVICES))
262 continue;
263
264 if (!bitmap_and(aqm, matrix_mdev->matrix.aqm,
265 lstdev->matrix.aqm, AP_DOMAINS))
266 continue;
267
268 return -EADDRINUSE;
269 }
270
271 return 0;
272}
273
274/**
275 * assign_adapter_store
276 *
277 * @dev: the matrix device
278 * @attr: the mediated matrix device's assign_adapter attribute
279 * @buf: a buffer containing the AP adapter number (APID) to
280 * be assigned
281 * @count: the number of bytes in @buf
282 *
283 * Parses the APID from @buf and sets the corresponding bit in the mediated
284 * matrix device's APM.
285 *
286 * Returns the number of bytes processed if the APID is valid; otherwise,
287 * returns one of the following errors:
288 *
289 * 1. -EINVAL
290 * The APID is not a valid number
291 *
292 * 2. -ENODEV
293 * The APID exceeds the maximum value configured for the system
294 *
295 * 3. -EADDRNOTAVAIL
296 * An APQN derived from the cross product of the APID being assigned
297 * and the APQIs previously assigned is not bound to the vfio_ap device
298 * driver; or, if no APQIs have yet been assigned, the APID is not
299 * contained in an APQN bound to the vfio_ap device driver.
300 *
301 * 4. -EADDRINUSE
302 * An APQN derived from the cross product of the APID being assigned
303 * and the APQIs previously assigned is being used by another mediated
304 * matrix device
305 */
306static ssize_t assign_adapter_store(struct device *dev,
307 struct device_attribute *attr,
308 const char *buf, size_t count)
309{
310 int ret;
311 unsigned long apid;
312 struct mdev_device *mdev = mdev_from_dev(dev);
313 struct ap_matrix_mdev *matrix_mdev = mdev_get_drvdata(mdev);
314
315 /* If the guest is running, disallow assignment of adapter */
316 if (matrix_mdev->kvm)
317 return -EBUSY;
318
319 ret = kstrtoul(buf, 0, &apid);
320 if (ret)
321 return ret;
322
323 if (apid > matrix_mdev->matrix.apm_max)
324 return -ENODEV;
325
326 /*
327 * Set the bit in the AP mask (APM) corresponding to the AP adapter
328 * number (APID). The bits in the mask, from most significant to least
329 * significant bit, correspond to APIDs 0-255.
330 */
331 mutex_lock(&matrix_dev->lock);
332
333 ret = vfio_ap_mdev_verify_queues_reserved_for_apid(matrix_mdev, apid);
334 if (ret)
335 goto done;
336
337 set_bit_inv(apid, matrix_mdev->matrix.apm);
338
339 ret = vfio_ap_mdev_verify_no_sharing(matrix_mdev);
340 if (ret)
341 goto share_err;
342
343 ret = count;
344 goto done;
345
346share_err:
347 clear_bit_inv(apid, matrix_mdev->matrix.apm);
348done:
349 mutex_unlock(&matrix_dev->lock);
350
351 return ret;
352}
353static DEVICE_ATTR_WO(assign_adapter);
354
355/**
356 * unassign_adapter_store
357 *
358 * @dev: the matrix device
359 * @attr: the mediated matrix device's unassign_adapter attribute
360 * @buf: a buffer containing the adapter number (APID) to be unassigned
361 * @count: the number of bytes in @buf
362 *
363 * Parses the APID from @buf and clears the corresponding bit in the mediated
364 * matrix device's APM.
365 *
366 * Returns the number of bytes processed if the APID is valid; otherwise,
367 * returns one of the following errors:
368 * -EINVAL if the APID is not a number
369 * -ENODEV if the APID it exceeds the maximum value configured for the
370 * system
371 */
372static ssize_t unassign_adapter_store(struct device *dev,
373 struct device_attribute *attr,
374 const char *buf, size_t count)
375{
376 int ret;
377 unsigned long apid;
378 struct mdev_device *mdev = mdev_from_dev(dev);
379 struct ap_matrix_mdev *matrix_mdev = mdev_get_drvdata(mdev);
380
381 /* If the guest is running, disallow un-assignment of adapter */
382 if (matrix_mdev->kvm)
383 return -EBUSY;
384
385 ret = kstrtoul(buf, 0, &apid);
386 if (ret)
387 return ret;
388
389 if (apid > matrix_mdev->matrix.apm_max)
390 return -ENODEV;
391
392 mutex_lock(&matrix_dev->lock);
393 clear_bit_inv((unsigned long)apid, matrix_mdev->matrix.apm);
394 mutex_unlock(&matrix_dev->lock);
395
396 return count;
397}
398static DEVICE_ATTR_WO(unassign_adapter);
399
400static int
401vfio_ap_mdev_verify_queues_reserved_for_apqi(struct ap_matrix_mdev *matrix_mdev,
402 unsigned long apqi)
403{
404 int ret;
405 unsigned long apid;
406 unsigned long nbits = matrix_mdev->matrix.apm_max + 1;
407
408 if (find_first_bit_inv(matrix_mdev->matrix.apm, nbits) >= nbits)
409 return vfio_ap_verify_queue_reserved(NULL, &apqi);
410
411 for_each_set_bit_inv(apid, matrix_mdev->matrix.apm, nbits) {
412 ret = vfio_ap_verify_queue_reserved(&apid, &apqi);
413 if (ret)
414 return ret;
415 }
416
417 return 0;
418}
419
420/**
421 * assign_domain_store
422 *
423 * @dev: the matrix device
424 * @attr: the mediated matrix device's assign_domain attribute
425 * @buf: a buffer containing the AP queue index (APQI) of the domain to
426 * be assigned
427 * @count: the number of bytes in @buf
428 *
429 * Parses the APQI from @buf and sets the corresponding bit in the mediated
430 * matrix device's AQM.
431 *
432 * Returns the number of bytes processed if the APQI is valid; otherwise returns
433 * one of the following errors:
434 *
435 * 1. -EINVAL
436 * The APQI is not a valid number
437 *
438 * 2. -ENODEV
439 * The APQI exceeds the maximum value configured for the system
440 *
441 * 3. -EADDRNOTAVAIL
442 * An APQN derived from the cross product of the APQI being assigned
443 * and the APIDs previously assigned is not bound to the vfio_ap device
444 * driver; or, if no APIDs have yet been assigned, the APQI is not
445 * contained in an APQN bound to the vfio_ap device driver.
446 *
447 * 4. -EADDRINUSE
448 * An APQN derived from the cross product of the APQI being assigned
449 * and the APIDs previously assigned is being used by another mediated
450 * matrix device
451 */
452static ssize_t assign_domain_store(struct device *dev,
453 struct device_attribute *attr,
454 const char *buf, size_t count)
455{
456 int ret;
457 unsigned long apqi;
458 struct mdev_device *mdev = mdev_from_dev(dev);
459 struct ap_matrix_mdev *matrix_mdev = mdev_get_drvdata(mdev);
460 unsigned long max_apqi = matrix_mdev->matrix.aqm_max;
461
462 /* If the guest is running, disallow assignment of domain */
463 if (matrix_mdev->kvm)
464 return -EBUSY;
465
466 ret = kstrtoul(buf, 0, &apqi);
467 if (ret)
468 return ret;
469 if (apqi > max_apqi)
470 return -ENODEV;
471
472 mutex_lock(&matrix_dev->lock);
473
474 ret = vfio_ap_mdev_verify_queues_reserved_for_apqi(matrix_mdev, apqi);
475 if (ret)
476 goto done;
477
478 set_bit_inv(apqi, matrix_mdev->matrix.aqm);
479
480 ret = vfio_ap_mdev_verify_no_sharing(matrix_mdev);
481 if (ret)
482 goto share_err;
483
484 ret = count;
485 goto done;
486
487share_err:
488 clear_bit_inv(apqi, matrix_mdev->matrix.aqm);
489done:
490 mutex_unlock(&matrix_dev->lock);
491
492 return ret;
493}
494static DEVICE_ATTR_WO(assign_domain);
495
496
497/**
498 * unassign_domain_store
499 *
500 * @dev: the matrix device
501 * @attr: the mediated matrix device's unassign_domain attribute
502 * @buf: a buffer containing the AP queue index (APQI) of the domain to
503 * be unassigned
504 * @count: the number of bytes in @buf
505 *
506 * Parses the APQI from @buf and clears the corresponding bit in the
507 * mediated matrix device's AQM.
508 *
509 * Returns the number of bytes processed if the APQI is valid; otherwise,
510 * returns one of the following errors:
511 * -EINVAL if the APQI is not a number
512 * -ENODEV if the APQI exceeds the maximum value configured for the system
513 */
514static ssize_t unassign_domain_store(struct device *dev,
515 struct device_attribute *attr,
516 const char *buf, size_t count)
517{
518 int ret;
519 unsigned long apqi;
520 struct mdev_device *mdev = mdev_from_dev(dev);
521 struct ap_matrix_mdev *matrix_mdev = mdev_get_drvdata(mdev);
522
523 /* If the guest is running, disallow un-assignment of domain */
524 if (matrix_mdev->kvm)
525 return -EBUSY;
526
527 ret = kstrtoul(buf, 0, &apqi);
528 if (ret)
529 return ret;
530
531 if (apqi > matrix_mdev->matrix.aqm_max)
532 return -ENODEV;
533
534 mutex_lock(&matrix_dev->lock);
535 clear_bit_inv((unsigned long)apqi, matrix_mdev->matrix.aqm);
536 mutex_unlock(&matrix_dev->lock);
537
538 return count;
539}
540static DEVICE_ATTR_WO(unassign_domain);
541
542/**
543 * assign_control_domain_store
544 *
545 * @dev: the matrix device
546 * @attr: the mediated matrix device's assign_control_domain attribute
547 * @buf: a buffer containing the domain ID to be assigned
548 * @count: the number of bytes in @buf
549 *
550 * Parses the domain ID from @buf and sets the corresponding bit in the mediated
551 * matrix device's ADM.
552 *
553 * Returns the number of bytes processed if the domain ID is valid; otherwise,
554 * returns one of the following errors:
555 * -EINVAL if the ID is not a number
556 * -ENODEV if the ID exceeds the maximum value configured for the system
557 */
558static ssize_t assign_control_domain_store(struct device *dev,
559 struct device_attribute *attr,
560 const char *buf, size_t count)
561{
562 int ret;
563 unsigned long id;
564 struct mdev_device *mdev = mdev_from_dev(dev);
565 struct ap_matrix_mdev *matrix_mdev = mdev_get_drvdata(mdev);
566
567 /* If the guest is running, disallow assignment of control domain */
568 if (matrix_mdev->kvm)
569 return -EBUSY;
570
571 ret = kstrtoul(buf, 0, &id);
572 if (ret)
573 return ret;
574
575 if (id > matrix_mdev->matrix.adm_max)
576 return -ENODEV;
577
578 /* Set the bit in the ADM (bitmask) corresponding to the AP control
579 * domain number (id). The bits in the mask, from most significant to
580 * least significant, correspond to IDs 0 up to the one less than the
581 * number of control domains that can be assigned.
582 */
583 mutex_lock(&matrix_dev->lock);
584 set_bit_inv(id, matrix_mdev->matrix.adm);
585 mutex_unlock(&matrix_dev->lock);
586
587 return count;
588}
589static DEVICE_ATTR_WO(assign_control_domain);
590
591/**
592 * unassign_control_domain_store
593 *
594 * @dev: the matrix device
595 * @attr: the mediated matrix device's unassign_control_domain attribute
596 * @buf: a buffer containing the domain ID to be unassigned
597 * @count: the number of bytes in @buf
598 *
599 * Parses the domain ID from @buf and clears the corresponding bit in the
600 * mediated matrix device's ADM.
601 *
602 * Returns the number of bytes processed if the domain ID is valid; otherwise,
603 * returns one of the following errors:
604 * -EINVAL if the ID is not a number
605 * -ENODEV if the ID exceeds the maximum value configured for the system
606 */
607static ssize_t unassign_control_domain_store(struct device *dev,
608 struct device_attribute *attr,
609 const char *buf, size_t count)
610{
611 int ret;
612 unsigned long domid;
613 struct mdev_device *mdev = mdev_from_dev(dev);
614 struct ap_matrix_mdev *matrix_mdev = mdev_get_drvdata(mdev);
615 unsigned long max_domid = matrix_mdev->matrix.adm_max;
616
617 /* If the guest is running, disallow un-assignment of control domain */
618 if (matrix_mdev->kvm)
619 return -EBUSY;
620
621 ret = kstrtoul(buf, 0, &domid);
622 if (ret)
623 return ret;
624 if (domid > max_domid)
625 return -ENODEV;
626
627 mutex_lock(&matrix_dev->lock);
628 clear_bit_inv(domid, matrix_mdev->matrix.adm);
629 mutex_unlock(&matrix_dev->lock);
630
631 return count;
632}
633static DEVICE_ATTR_WO(unassign_control_domain);
634
635static ssize_t control_domains_show(struct device *dev,
636 struct device_attribute *dev_attr,
637 char *buf)
638{
639 unsigned long id;
640 int nchars = 0;
641 int n;
642 char *bufpos = buf;
643 struct mdev_device *mdev = mdev_from_dev(dev);
644 struct ap_matrix_mdev *matrix_mdev = mdev_get_drvdata(mdev);
645 unsigned long max_domid = matrix_mdev->matrix.adm_max;
646
647 mutex_lock(&matrix_dev->lock);
648 for_each_set_bit_inv(id, matrix_mdev->matrix.adm, max_domid + 1) {
649 n = sprintf(bufpos, "%04lx\n", id);
650 bufpos += n;
651 nchars += n;
652 }
653 mutex_unlock(&matrix_dev->lock);
654
655 return nchars;
656}
657static DEVICE_ATTR_RO(control_domains);
658
659static ssize_t matrix_show(struct device *dev, struct device_attribute *attr,
660 char *buf)
661{
662 struct mdev_device *mdev = mdev_from_dev(dev);
663 struct ap_matrix_mdev *matrix_mdev = mdev_get_drvdata(mdev);
664 char *bufpos = buf;
665 unsigned long apid;
666 unsigned long apqi;
667 unsigned long apid1;
668 unsigned long apqi1;
669 unsigned long napm_bits = matrix_mdev->matrix.apm_max + 1;
670 unsigned long naqm_bits = matrix_mdev->matrix.aqm_max + 1;
671 int nchars = 0;
672 int n;
673
674 apid1 = find_first_bit_inv(matrix_mdev->matrix.apm, napm_bits);
675 apqi1 = find_first_bit_inv(matrix_mdev->matrix.aqm, naqm_bits);
676
677 mutex_lock(&matrix_dev->lock);
678
679 if ((apid1 < napm_bits) && (apqi1 < naqm_bits)) {
680 for_each_set_bit_inv(apid, matrix_mdev->matrix.apm, napm_bits) {
681 for_each_set_bit_inv(apqi, matrix_mdev->matrix.aqm,
682 naqm_bits) {
683 n = sprintf(bufpos, "%02lx.%04lx\n", apid,
684 apqi);
685 bufpos += n;
686 nchars += n;
687 }
688 }
689 } else if (apid1 < napm_bits) {
690 for_each_set_bit_inv(apid, matrix_mdev->matrix.apm, napm_bits) {
691 n = sprintf(bufpos, "%02lx.\n", apid);
692 bufpos += n;
693 nchars += n;
694 }
695 } else if (apqi1 < naqm_bits) {
696 for_each_set_bit_inv(apqi, matrix_mdev->matrix.aqm, naqm_bits) {
697 n = sprintf(bufpos, ".%04lx\n", apqi);
698 bufpos += n;
699 nchars += n;
700 }
701 }
702
703 mutex_unlock(&matrix_dev->lock);
704
705 return nchars;
706}
707static DEVICE_ATTR_RO(matrix);
708
709static struct attribute *vfio_ap_mdev_attrs[] = {
710 &dev_attr_assign_adapter.attr,
711 &dev_attr_unassign_adapter.attr,
712 &dev_attr_assign_domain.attr,
713 &dev_attr_unassign_domain.attr,
714 &dev_attr_assign_control_domain.attr,
715 &dev_attr_unassign_control_domain.attr,
716 &dev_attr_control_domains.attr,
717 &dev_attr_matrix.attr,
718 NULL,
719};
720
721static struct attribute_group vfio_ap_mdev_attr_group = {
722 .attrs = vfio_ap_mdev_attrs
723};
724
725static const struct attribute_group *vfio_ap_mdev_attr_groups[] = {
726 &vfio_ap_mdev_attr_group,
727 NULL
728};
729
730/**
731 * vfio_ap_mdev_set_kvm
732 *
733 * @matrix_mdev: a mediated matrix device
734 * @kvm: reference to KVM instance
735 *
736 * Verifies no other mediated matrix device has @kvm and sets a reference to
737 * it in @matrix_mdev->kvm.
738 *
739 * Return 0 if no other mediated matrix device has a reference to @kvm;
740 * otherwise, returns an -EPERM.
741 */
742static int vfio_ap_mdev_set_kvm(struct ap_matrix_mdev *matrix_mdev,
743 struct kvm *kvm)
744{
745 struct ap_matrix_mdev *m;
746
747 mutex_lock(&matrix_dev->lock);
748
749 list_for_each_entry(m, &matrix_dev->mdev_list, node) {
750 if ((m != matrix_mdev) && (m->kvm == kvm)) {
751 mutex_unlock(&matrix_dev->lock);
752 return -EPERM;
753 }
754 }
755
756 matrix_mdev->kvm = kvm;
757 mutex_unlock(&matrix_dev->lock);
758
759 return 0;
760}
761
762static int vfio_ap_mdev_group_notifier(struct notifier_block *nb,
763 unsigned long action, void *data)
764{
765 int ret;
766 struct ap_matrix_mdev *matrix_mdev;
767
768 if (action != VFIO_GROUP_NOTIFY_SET_KVM)
769 return NOTIFY_OK;
770
771 matrix_mdev = container_of(nb, struct ap_matrix_mdev, group_notifier);
772
773 if (!data) {
774 matrix_mdev->kvm = NULL;
775 return NOTIFY_OK;
776 }
777
778 ret = vfio_ap_mdev_set_kvm(matrix_mdev, data);
779 if (ret)
780 return NOTIFY_DONE;
781
782 /* If there is no CRYCB pointer, then we can't copy the masks */
783 if (!matrix_mdev->kvm->arch.crypto.crycbd)
784 return NOTIFY_DONE;
785
786 kvm_arch_crypto_set_masks(matrix_mdev->kvm, matrix_mdev->matrix.apm,
787 matrix_mdev->matrix.aqm,
788 matrix_mdev->matrix.adm);
789
790 return NOTIFY_OK;
791}
792
793static int vfio_ap_mdev_reset_queue(unsigned int apid, unsigned int apqi,
794 unsigned int retry)
795{
796 struct ap_queue_status status;
797
798 do {
799 status = ap_zapq(AP_MKQID(apid, apqi));
800 switch (status.response_code) {
801 case AP_RESPONSE_NORMAL:
802 return 0;
803 case AP_RESPONSE_RESET_IN_PROGRESS:
804 case AP_RESPONSE_BUSY:
805 msleep(20);
806 break;
807 default:
808 /* things are really broken, give up */
809 return -EIO;
810 }
811 } while (retry--);
812
813 return -EBUSY;
814}
815
816static int vfio_ap_mdev_reset_queues(struct mdev_device *mdev)
817{
818 int ret;
819 int rc = 0;
820 unsigned long apid, apqi;
821 struct ap_matrix_mdev *matrix_mdev = mdev_get_drvdata(mdev);
822
823 for_each_set_bit_inv(apid, matrix_mdev->matrix.apm,
824 matrix_mdev->matrix.apm_max + 1) {
825 for_each_set_bit_inv(apqi, matrix_mdev->matrix.aqm,
826 matrix_mdev->matrix.aqm_max + 1) {
827 ret = vfio_ap_mdev_reset_queue(apid, apqi, 1);
828 /*
829 * Regardless whether a queue turns out to be busy, or
830 * is not operational, we need to continue resetting
831 * the remaining queues.
832 */
833 if (ret)
834 rc = ret;
835 }
836 }
837
838 return rc;
839}
840
841static int vfio_ap_mdev_open(struct mdev_device *mdev)
842{
843 struct ap_matrix_mdev *matrix_mdev = mdev_get_drvdata(mdev);
844 unsigned long events;
845 int ret;
846
847
848 if (!try_module_get(THIS_MODULE))
849 return -ENODEV;
850
851 matrix_mdev->group_notifier.notifier_call = vfio_ap_mdev_group_notifier;
852 events = VFIO_GROUP_NOTIFY_SET_KVM;
853
854 ret = vfio_register_notifier(mdev_dev(mdev), VFIO_GROUP_NOTIFY,
855 &events, &matrix_mdev->group_notifier);
856 if (ret) {
857 module_put(THIS_MODULE);
858 return ret;
859 }
860
861 return 0;
862}
863
864static void vfio_ap_mdev_release(struct mdev_device *mdev)
865{
866 struct ap_matrix_mdev *matrix_mdev = mdev_get_drvdata(mdev);
867
868 if (matrix_mdev->kvm)
869 kvm_arch_crypto_clear_masks(matrix_mdev->kvm);
870
871 vfio_ap_mdev_reset_queues(mdev);
872 vfio_unregister_notifier(mdev_dev(mdev), VFIO_GROUP_NOTIFY,
873 &matrix_mdev->group_notifier);
874 matrix_mdev->kvm = NULL;
875 module_put(THIS_MODULE);
876}
877
878static int vfio_ap_mdev_get_device_info(unsigned long arg)
879{
880 unsigned long minsz;
881 struct vfio_device_info info;
882
883 minsz = offsetofend(struct vfio_device_info, num_irqs);
884
885 if (copy_from_user(&info, (void __user *)arg, minsz))
886 return -EFAULT;
887
888 if (info.argsz < minsz)
889 return -EINVAL;
890
891 info.flags = VFIO_DEVICE_FLAGS_AP | VFIO_DEVICE_FLAGS_RESET;
892 info.num_regions = 0;
893 info.num_irqs = 0;
894
895 return copy_to_user((void __user *)arg, &info, minsz);
896}
897
898static ssize_t vfio_ap_mdev_ioctl(struct mdev_device *mdev,
899 unsigned int cmd, unsigned long arg)
900{
901 int ret;
902
903 switch (cmd) {
904 case VFIO_DEVICE_GET_INFO:
905 ret = vfio_ap_mdev_get_device_info(arg);
906 break;
907 case VFIO_DEVICE_RESET:
908 ret = vfio_ap_mdev_reset_queues(mdev);
909 break;
910 default:
911 ret = -EOPNOTSUPP;
912 break;
913 }
914
915 return ret;
916}
917
918static const struct mdev_parent_ops vfio_ap_matrix_ops = {
919 .owner = THIS_MODULE,
920 .supported_type_groups = vfio_ap_mdev_type_groups,
921 .mdev_attr_groups = vfio_ap_mdev_attr_groups,
922 .create = vfio_ap_mdev_create,
923 .remove = vfio_ap_mdev_remove,
924 .open = vfio_ap_mdev_open,
925 .release = vfio_ap_mdev_release,
926 .ioctl = vfio_ap_mdev_ioctl,
927};
928
929int vfio_ap_mdev_register(void)
930{
931 atomic_set(&matrix_dev->available_instances, MAX_ZDEV_ENTRIES_EXT);
932
933 return mdev_register_device(&matrix_dev->device, &vfio_ap_matrix_ops);
934}
935
936void vfio_ap_mdev_unregister(void)
937{
938 mdev_unregister_device(&matrix_dev->device);
939}
diff --git a/drivers/s390/crypto/vfio_ap_private.h b/drivers/s390/crypto/vfio_ap_private.h
new file mode 100644
index 000000000000..5675492233c7
--- /dev/null
+++ b/drivers/s390/crypto/vfio_ap_private.h
@@ -0,0 +1,88 @@
1/* SPDX-License-Identifier: GPL-2.0 */
2/*
3 * Private data and functions for adjunct processor VFIO matrix driver.
4 *
5 * Author(s): Tony Krowiak <akrowiak@linux.ibm.com>
6 * Halil Pasic <pasic@linux.ibm.com>
7 *
8 * Copyright IBM Corp. 2018
9 */
10
11#ifndef _VFIO_AP_PRIVATE_H_
12#define _VFIO_AP_PRIVATE_H_
13
14#include <linux/types.h>
15#include <linux/device.h>
16#include <linux/mdev.h>
17#include <linux/delay.h>
18#include <linux/mutex.h>
19
20#include "ap_bus.h"
21
22#define VFIO_AP_MODULE_NAME "vfio_ap"
23#define VFIO_AP_DRV_NAME "vfio_ap"
24
25/**
26 * ap_matrix_dev - the AP matrix device structure
27 * @device: generic device structure associated with the AP matrix device
28 * @available_instances: number of mediated matrix devices that can be created
29 * @info: the struct containing the output from the PQAP(QCI) instruction
30 * mdev_list: the list of mediated matrix devices created
31 * lock: mutex for locking the AP matrix device. This lock will be
32 * taken every time we fiddle with state managed by the vfio_ap
33 * driver, be it using @mdev_list or writing the state of a
34 * single ap_matrix_mdev device. It's quite coarse but we don't
35 * expect much contention.
36 */
37struct ap_matrix_dev {
38 struct device device;
39 atomic_t available_instances;
40 struct ap_config_info info;
41 struct list_head mdev_list;
42 struct mutex lock;
43};
44
45extern struct ap_matrix_dev *matrix_dev;
46
47/**
48 * The AP matrix is comprised of three bit masks identifying the adapters,
49 * queues (domains) and control domains that belong to an AP matrix. The bits i
50 * each mask, from least significant to most significant bit, correspond to IDs
51 * 0 to 255. When a bit is set, the corresponding ID belongs to the matrix.
52 *
53 * @apm_max: max adapter number in @apm
54 * @apm identifies the AP adapters in the matrix
55 * @aqm_max: max domain number in @aqm
56 * @aqm identifies the AP queues (domains) in the matrix
57 * @adm_max: max domain number in @adm
58 * @adm identifies the AP control domains in the matrix
59 */
60struct ap_matrix {
61 unsigned long apm_max;
62 DECLARE_BITMAP(apm, 256);
63 unsigned long aqm_max;
64 DECLARE_BITMAP(aqm, 256);
65 unsigned long adm_max;
66 DECLARE_BITMAP(adm, 256);
67};
68
69/**
70 * struct ap_matrix_mdev - the mediated matrix device structure
71 * @list: allows the ap_matrix_mdev struct to be added to a list
72 * @matrix: the adapters, usage domains and control domains assigned to the
73 * mediated matrix device.
74 * @group_notifier: notifier block used for specifying callback function for
75 * handling the VFIO_GROUP_NOTIFY_SET_KVM event
76 * @kvm: the struct holding guest's state
77 */
78struct ap_matrix_mdev {
79 struct list_head node;
80 struct ap_matrix matrix;
81 struct notifier_block group_notifier;
82 struct kvm *kvm;
83};
84
85extern int vfio_ap_mdev_register(void);
86extern void vfio_ap_mdev_unregister(void);
87
88#endif /* _VFIO_AP_PRIVATE_H_ */
diff --git a/drivers/vfio/vfio_iommu_spapr_tce.c b/drivers/vfio/vfio_iommu_spapr_tce.c
index 96721b154454..b30926e11d87 100644
--- a/drivers/vfio/vfio_iommu_spapr_tce.c
+++ b/drivers/vfio/vfio_iommu_spapr_tce.c
@@ -444,7 +444,7 @@ static void tce_iommu_unuse_page_v2(struct tce_container *container,
444 struct mm_iommu_table_group_mem_t *mem = NULL; 444 struct mm_iommu_table_group_mem_t *mem = NULL;
445 int ret; 445 int ret;
446 unsigned long hpa = 0; 446 unsigned long hpa = 0;
447 __be64 *pua = IOMMU_TABLE_USERSPACE_ENTRY(tbl, entry); 447 __be64 *pua = IOMMU_TABLE_USERSPACE_ENTRY_RO(tbl, entry);
448 448
449 if (!pua) 449 if (!pua)
450 return; 450 return;
@@ -467,8 +467,27 @@ static int tce_iommu_clear(struct tce_container *container,
467 unsigned long oldhpa; 467 unsigned long oldhpa;
468 long ret; 468 long ret;
469 enum dma_data_direction direction; 469 enum dma_data_direction direction;
470 unsigned long lastentry = entry + pages;
471
472 for ( ; entry < lastentry; ++entry) {
473 if (tbl->it_indirect_levels && tbl->it_userspace) {
474 /*
475 * For multilevel tables, we can take a shortcut here
476 * and skip some TCEs as we know that the userspace
477 * addresses cache is a mirror of the real TCE table
478 * and if it is missing some indirect levels, then
479 * the hardware table does not have them allocated
480 * either and therefore does not require updating.
481 */
482 __be64 *pua = IOMMU_TABLE_USERSPACE_ENTRY_RO(tbl,
483 entry);
484 if (!pua) {
485 /* align to level_size which is power of two */
486 entry |= tbl->it_level_size - 1;
487 continue;
488 }
489 }
470 490
471 for ( ; pages; --pages, ++entry) {
472 cond_resched(); 491 cond_resched();
473 492
474 direction = DMA_NONE; 493 direction = DMA_NONE;
diff --git a/include/linux/irqchip/arm-gic-v3.h b/include/linux/irqchip/arm-gic-v3.h
index c2a7b863fc2e..071b4cbdf010 100644
--- a/include/linux/irqchip/arm-gic-v3.h
+++ b/include/linux/irqchip/arm-gic-v3.h
@@ -357,6 +357,8 @@
357#define GITS_CBASER_RaWaWt GIC_BASER_CACHEABILITY(GITS_CBASER, INNER, RaWaWt) 357#define GITS_CBASER_RaWaWt GIC_BASER_CACHEABILITY(GITS_CBASER, INNER, RaWaWt)
358#define GITS_CBASER_RaWaWb GIC_BASER_CACHEABILITY(GITS_CBASER, INNER, RaWaWb) 358#define GITS_CBASER_RaWaWb GIC_BASER_CACHEABILITY(GITS_CBASER, INNER, RaWaWb)
359 359
360#define GITS_CBASER_ADDRESS(cbaser) ((cbaser) & GENMASK_ULL(51, 12))
361
360#define GITS_BASER_NR_REGS 8 362#define GITS_BASER_NR_REGS 8
361 363
362#define GITS_BASER_VALID (1ULL << 63) 364#define GITS_BASER_VALID (1ULL << 63)
@@ -388,6 +390,9 @@
388#define GITS_BASER_ENTRY_SIZE_MASK GENMASK_ULL(52, 48) 390#define GITS_BASER_ENTRY_SIZE_MASK GENMASK_ULL(52, 48)
389#define GITS_BASER_PHYS_52_to_48(phys) \ 391#define GITS_BASER_PHYS_52_to_48(phys) \
390 (((phys) & GENMASK_ULL(47, 16)) | (((phys) >> 48) & 0xf) << 12) 392 (((phys) & GENMASK_ULL(47, 16)) | (((phys) >> 48) & 0xf) << 12)
393#define GITS_BASER_ADDR_48_to_52(baser) \
394 (((baser) & GENMASK_ULL(47, 16)) | (((baser) >> 12) & 0xf) << 48)
395
391#define GITS_BASER_SHAREABILITY_SHIFT (10) 396#define GITS_BASER_SHAREABILITY_SHIFT (10)
392#define GITS_BASER_InnerShareable \ 397#define GITS_BASER_InnerShareable \
393 GIC_BASER_SHAREABILITY(GITS_BASER, InnerShareable) 398 GIC_BASER_SHAREABILITY(GITS_BASER, InnerShareable)
diff --git a/include/uapi/linux/kvm.h b/include/uapi/linux/kvm.h
index 251be353f950..2b7a652c9fa4 100644
--- a/include/uapi/linux/kvm.h
+++ b/include/uapi/linux/kvm.h
@@ -420,13 +420,19 @@ struct kvm_run {
420struct kvm_coalesced_mmio_zone { 420struct kvm_coalesced_mmio_zone {
421 __u64 addr; 421 __u64 addr;
422 __u32 size; 422 __u32 size;
423 __u32 pad; 423 union {
424 __u32 pad;
425 __u32 pio;
426 };
424}; 427};
425 428
426struct kvm_coalesced_mmio { 429struct kvm_coalesced_mmio {
427 __u64 phys_addr; 430 __u64 phys_addr;
428 __u32 len; 431 __u32 len;
429 __u32 pad; 432 union {
433 __u32 pad;
434 __u32 pio;
435 };
430 __u8 data[8]; 436 __u8 data[8];
431}; 437};
432 438
@@ -719,6 +725,7 @@ struct kvm_ppc_one_seg_page_size {
719 725
720#define KVM_PPC_PAGE_SIZES_REAL 0x00000001 726#define KVM_PPC_PAGE_SIZES_REAL 0x00000001
721#define KVM_PPC_1T_SEGMENTS 0x00000002 727#define KVM_PPC_1T_SEGMENTS 0x00000002
728#define KVM_PPC_NO_HASH 0x00000004
722 729
723struct kvm_ppc_smmu_info { 730struct kvm_ppc_smmu_info {
724 __u64 flags; 731 __u64 flags;
@@ -751,6 +758,15 @@ struct kvm_ppc_resize_hpt {
751#define KVM_S390_SIE_PAGE_OFFSET 1 758#define KVM_S390_SIE_PAGE_OFFSET 1
752 759
753/* 760/*
761 * On arm64, machine type can be used to request the physical
762 * address size for the VM. Bits[7-0] are reserved for the guest
763 * PA size shift (i.e, log2(PA_Size)). For backward compatibility,
764 * value 0 implies the default IPA size, 40bits.
765 */
766#define KVM_VM_TYPE_ARM_IPA_SIZE_MASK 0xffULL
767#define KVM_VM_TYPE_ARM_IPA_SIZE(x) \
768 ((x) & KVM_VM_TYPE_ARM_IPA_SIZE_MASK)
769/*
754 * ioctls for /dev/kvm fds: 770 * ioctls for /dev/kvm fds:
755 */ 771 */
756#define KVM_GET_API_VERSION _IO(KVMIO, 0x00) 772#define KVM_GET_API_VERSION _IO(KVMIO, 0x00)
@@ -953,6 +969,12 @@ struct kvm_ppc_resize_hpt {
953#define KVM_CAP_NESTED_STATE 157 969#define KVM_CAP_NESTED_STATE 157
954#define KVM_CAP_ARM_INJECT_SERROR_ESR 158 970#define KVM_CAP_ARM_INJECT_SERROR_ESR 158
955#define KVM_CAP_MSR_PLATFORM_INFO 159 971#define KVM_CAP_MSR_PLATFORM_INFO 159
972#define KVM_CAP_PPC_NESTED_HV 160
973#define KVM_CAP_HYPERV_SEND_IPI 161
974#define KVM_CAP_COALESCED_PIO 162
975#define KVM_CAP_HYPERV_ENLIGHTENED_VMCS 163
976#define KVM_CAP_EXCEPTION_PAYLOAD 164
977#define KVM_CAP_ARM_VM_IPA_SIZE 165
956 978
957#ifdef KVM_CAP_IRQ_ROUTING 979#ifdef KVM_CAP_IRQ_ROUTING
958 980
diff --git a/include/uapi/linux/vfio.h b/include/uapi/linux/vfio.h
index 1aa7b82e8169..f378b9802d8b 100644
--- a/include/uapi/linux/vfio.h
+++ b/include/uapi/linux/vfio.h
@@ -200,6 +200,7 @@ struct vfio_device_info {
200#define VFIO_DEVICE_FLAGS_PLATFORM (1 << 2) /* vfio-platform device */ 200#define VFIO_DEVICE_FLAGS_PLATFORM (1 << 2) /* vfio-platform device */
201#define VFIO_DEVICE_FLAGS_AMBA (1 << 3) /* vfio-amba device */ 201#define VFIO_DEVICE_FLAGS_AMBA (1 << 3) /* vfio-amba device */
202#define VFIO_DEVICE_FLAGS_CCW (1 << 4) /* vfio-ccw device */ 202#define VFIO_DEVICE_FLAGS_CCW (1 << 4) /* vfio-ccw device */
203#define VFIO_DEVICE_FLAGS_AP (1 << 5) /* vfio-ap device */
203 __u32 num_regions; /* Max region index + 1 */ 204 __u32 num_regions; /* Max region index + 1 */
204 __u32 num_irqs; /* Max IRQ index + 1 */ 205 __u32 num_irqs; /* Max IRQ index + 1 */
205}; 206};
@@ -215,6 +216,7 @@ struct vfio_device_info {
215#define VFIO_DEVICE_API_PLATFORM_STRING "vfio-platform" 216#define VFIO_DEVICE_API_PLATFORM_STRING "vfio-platform"
216#define VFIO_DEVICE_API_AMBA_STRING "vfio-amba" 217#define VFIO_DEVICE_API_AMBA_STRING "vfio-amba"
217#define VFIO_DEVICE_API_CCW_STRING "vfio-ccw" 218#define VFIO_DEVICE_API_CCW_STRING "vfio-ccw"
219#define VFIO_DEVICE_API_AP_STRING "vfio-ap"
218 220
219/** 221/**
220 * VFIO_DEVICE_GET_REGION_INFO - _IOWR(VFIO_TYPE, VFIO_BASE + 8, 222 * VFIO_DEVICE_GET_REGION_INFO - _IOWR(VFIO_TYPE, VFIO_BASE + 8,
diff --git a/tools/arch/x86/include/uapi/asm/kvm.h b/tools/arch/x86/include/uapi/asm/kvm.h
index fd23d5778ea1..8a6eff9c27f3 100644
--- a/tools/arch/x86/include/uapi/asm/kvm.h
+++ b/tools/arch/x86/include/uapi/asm/kvm.h
@@ -288,6 +288,7 @@ struct kvm_reinject_control {
288#define KVM_VCPUEVENT_VALID_SIPI_VECTOR 0x00000002 288#define KVM_VCPUEVENT_VALID_SIPI_VECTOR 0x00000002
289#define KVM_VCPUEVENT_VALID_SHADOW 0x00000004 289#define KVM_VCPUEVENT_VALID_SHADOW 0x00000004
290#define KVM_VCPUEVENT_VALID_SMM 0x00000008 290#define KVM_VCPUEVENT_VALID_SMM 0x00000008
291#define KVM_VCPUEVENT_VALID_PAYLOAD 0x00000010
291 292
292/* Interrupt shadow states */ 293/* Interrupt shadow states */
293#define KVM_X86_SHADOW_INT_MOV_SS 0x01 294#define KVM_X86_SHADOW_INT_MOV_SS 0x01
@@ -299,7 +300,10 @@ struct kvm_vcpu_events {
299 __u8 injected; 300 __u8 injected;
300 __u8 nr; 301 __u8 nr;
301 __u8 has_error_code; 302 __u8 has_error_code;
302 __u8 pad; 303 union {
304 __u8 pad;
305 __u8 pending;
306 };
303 __u32 error_code; 307 __u32 error_code;
304 } exception; 308 } exception;
305 struct { 309 struct {
@@ -322,7 +326,9 @@ struct kvm_vcpu_events {
322 __u8 smm_inside_nmi; 326 __u8 smm_inside_nmi;
323 __u8 latched_init; 327 __u8 latched_init;
324 } smi; 328 } smi;
325 __u32 reserved[9]; 329 __u8 reserved[27];
330 __u8 exception_has_payload;
331 __u64 exception_payload;
326}; 332};
327 333
328/* for KVM_GET/SET_DEBUGREGS */ 334/* for KVM_GET/SET_DEBUGREGS */
diff --git a/tools/include/uapi/linux/kvm.h b/tools/include/uapi/linux/kvm.h
index 251be353f950..2875ce85b322 100644
--- a/tools/include/uapi/linux/kvm.h
+++ b/tools/include/uapi/linux/kvm.h
@@ -719,6 +719,7 @@ struct kvm_ppc_one_seg_page_size {
719 719
720#define KVM_PPC_PAGE_SIZES_REAL 0x00000001 720#define KVM_PPC_PAGE_SIZES_REAL 0x00000001
721#define KVM_PPC_1T_SEGMENTS 0x00000002 721#define KVM_PPC_1T_SEGMENTS 0x00000002
722#define KVM_PPC_NO_HASH 0x00000004
722 723
723struct kvm_ppc_smmu_info { 724struct kvm_ppc_smmu_info {
724 __u64 flags; 725 __u64 flags;
@@ -953,6 +954,10 @@ struct kvm_ppc_resize_hpt {
953#define KVM_CAP_NESTED_STATE 157 954#define KVM_CAP_NESTED_STATE 157
954#define KVM_CAP_ARM_INJECT_SERROR_ESR 158 955#define KVM_CAP_ARM_INJECT_SERROR_ESR 158
955#define KVM_CAP_MSR_PLATFORM_INFO 159 956#define KVM_CAP_MSR_PLATFORM_INFO 159
957#define KVM_CAP_PPC_NESTED_HV 160
958#define KVM_CAP_HYPERV_SEND_IPI 161
959#define KVM_CAP_COALESCED_PIO 162
960#define KVM_CAP_HYPERV_ENLIGHTENED_VMCS 163
956 961
957#ifdef KVM_CAP_IRQ_ROUTING 962#ifdef KVM_CAP_IRQ_ROUTING
958 963
diff --git a/tools/perf/arch/powerpc/util/book3s_hv_exits.h b/tools/perf/arch/powerpc/util/book3s_hv_exits.h
index 853b95d1e139..2011376c7ab5 100644
--- a/tools/perf/arch/powerpc/util/book3s_hv_exits.h
+++ b/tools/perf/arch/powerpc/util/book3s_hv_exits.h
@@ -15,7 +15,6 @@
15 {0x400, "INST_STORAGE"}, \ 15 {0x400, "INST_STORAGE"}, \
16 {0x480, "INST_SEGMENT"}, \ 16 {0x480, "INST_SEGMENT"}, \
17 {0x500, "EXTERNAL"}, \ 17 {0x500, "EXTERNAL"}, \
18 {0x501, "EXTERNAL_LEVEL"}, \
19 {0x502, "EXTERNAL_HV"}, \ 18 {0x502, "EXTERNAL_HV"}, \
20 {0x600, "ALIGNMENT"}, \ 19 {0x600, "ALIGNMENT"}, \
21 {0x700, "PROGRAM"}, \ 20 {0x700, "PROGRAM"}, \
diff --git a/tools/testing/selftests/kvm/.gitignore b/tools/testing/selftests/kvm/.gitignore
index 5c34752e1cff..6210ba41c29e 100644
--- a/tools/testing/selftests/kvm/.gitignore
+++ b/tools/testing/selftests/kvm/.gitignore
@@ -1,6 +1,8 @@
1cr4_cpuid_sync_test 1/x86_64/cr4_cpuid_sync_test
2platform_info_test 2/x86_64/evmcs_test
3set_sregs_test 3/x86_64/platform_info_test
4sync_regs_test 4/x86_64/set_sregs_test
5vmx_tsc_adjust_test 5/x86_64/sync_regs_test
6state_test 6/x86_64/vmx_tsc_adjust_test
7/x86_64/state_test
8/dirty_log_test
diff --git a/tools/testing/selftests/kvm/Makefile b/tools/testing/selftests/kvm/Makefile
index ec32dad3c3f0..01a219229238 100644
--- a/tools/testing/selftests/kvm/Makefile
+++ b/tools/testing/selftests/kvm/Makefile
@@ -1,26 +1,30 @@
1all: 1all:
2 2
3top_srcdir = ../../../../ 3top_srcdir = ../../../..
4UNAME_M := $(shell uname -m) 4UNAME_M := $(shell uname -m)
5 5
6LIBKVM = lib/assert.c lib/elf.c lib/io.c lib/kvm_util.c lib/sparsebit.c 6LIBKVM = lib/assert.c lib/elf.c lib/io.c lib/kvm_util.c lib/ucall.c lib/sparsebit.c
7LIBKVM_x86_64 = lib/x86.c lib/vmx.c 7LIBKVM_x86_64 = lib/x86_64/processor.c lib/x86_64/vmx.c
8 8LIBKVM_aarch64 = lib/aarch64/processor.c
9TEST_GEN_PROGS_x86_64 = platform_info_test 9
10TEST_GEN_PROGS_x86_64 += set_sregs_test 10TEST_GEN_PROGS_x86_64 = x86_64/platform_info_test
11TEST_GEN_PROGS_x86_64 += sync_regs_test 11TEST_GEN_PROGS_x86_64 += x86_64/set_sregs_test
12TEST_GEN_PROGS_x86_64 += vmx_tsc_adjust_test 12TEST_GEN_PROGS_x86_64 += x86_64/sync_regs_test
13TEST_GEN_PROGS_x86_64 += cr4_cpuid_sync_test 13TEST_GEN_PROGS_x86_64 += x86_64/vmx_tsc_adjust_test
14TEST_GEN_PROGS_x86_64 += state_test 14TEST_GEN_PROGS_x86_64 += x86_64/cr4_cpuid_sync_test
15TEST_GEN_PROGS_x86_64 += x86_64/state_test
16TEST_GEN_PROGS_x86_64 += x86_64/evmcs_test
15TEST_GEN_PROGS_x86_64 += dirty_log_test 17TEST_GEN_PROGS_x86_64 += dirty_log_test
16 18
19TEST_GEN_PROGS_aarch64 += dirty_log_test
20
17TEST_GEN_PROGS += $(TEST_GEN_PROGS_$(UNAME_M)) 21TEST_GEN_PROGS += $(TEST_GEN_PROGS_$(UNAME_M))
18LIBKVM += $(LIBKVM_$(UNAME_M)) 22LIBKVM += $(LIBKVM_$(UNAME_M))
19 23
20INSTALL_HDR_PATH = $(top_srcdir)/usr 24INSTALL_HDR_PATH = $(top_srcdir)/usr
21LINUX_HDR_PATH = $(INSTALL_HDR_PATH)/include/ 25LINUX_HDR_PATH = $(INSTALL_HDR_PATH)/include/
22LINUX_TOOL_INCLUDE = $(top_srcdir)tools/include 26LINUX_TOOL_INCLUDE = $(top_srcdir)/tools/include
23CFLAGS += -O2 -g -std=gnu99 -I$(LINUX_TOOL_INCLUDE) -I$(LINUX_HDR_PATH) -Iinclude -I$(<D) -I.. 27CFLAGS += -O2 -g -std=gnu99 -I$(LINUX_TOOL_INCLUDE) -I$(LINUX_HDR_PATH) -Iinclude -I$(<D) -Iinclude/$(UNAME_M) -I..
24LDFLAGS += -pthread 28LDFLAGS += -pthread
25 29
26# After inclusion, $(OUTPUT) is defined and 30# After inclusion, $(OUTPUT) is defined and
@@ -29,7 +33,7 @@ include ../lib.mk
29 33
30STATIC_LIBS := $(OUTPUT)/libkvm.a 34STATIC_LIBS := $(OUTPUT)/libkvm.a
31LIBKVM_OBJ := $(patsubst %.c, $(OUTPUT)/%.o, $(LIBKVM)) 35LIBKVM_OBJ := $(patsubst %.c, $(OUTPUT)/%.o, $(LIBKVM))
32EXTRA_CLEAN += $(LIBKVM_OBJ) $(STATIC_LIBS) 36EXTRA_CLEAN += $(LIBKVM_OBJ) $(STATIC_LIBS) cscope.*
33 37
34x := $(shell mkdir -p $(sort $(dir $(LIBKVM_OBJ)))) 38x := $(shell mkdir -p $(sort $(dir $(LIBKVM_OBJ))))
35$(LIBKVM_OBJ): $(OUTPUT)/%.o: %.c 39$(LIBKVM_OBJ): $(OUTPUT)/%.o: %.c
@@ -41,3 +45,12 @@ $(OUTPUT)/libkvm.a: $(LIBKVM_OBJ)
41all: $(STATIC_LIBS) 45all: $(STATIC_LIBS)
42$(TEST_GEN_PROGS): $(STATIC_LIBS) 46$(TEST_GEN_PROGS): $(STATIC_LIBS)
43$(STATIC_LIBS):| khdr 47$(STATIC_LIBS):| khdr
48
49cscope: include_paths = $(LINUX_TOOL_INCLUDE) $(LINUX_HDR_PATH) include lib ..
50cscope:
51 $(RM) cscope.*
52 (find $(include_paths) -name '*.h' \
53 -exec realpath --relative-base=$(PWD) {} \;; \
54 find . -name '*.c' \
55 -exec realpath --relative-base=$(PWD) {} \;) | sort -u > cscope.files
56 cscope -b
diff --git a/tools/testing/selftests/kvm/dirty_log_test.c b/tools/testing/selftests/kvm/dirty_log_test.c
index 0c2cdc105f96..d59820cc2d39 100644
--- a/tools/testing/selftests/kvm/dirty_log_test.c
+++ b/tools/testing/selftests/kvm/dirty_log_test.c
@@ -5,6 +5,8 @@
5 * Copyright (C) 2018, Red Hat, Inc. 5 * Copyright (C) 2018, Red Hat, Inc.
6 */ 6 */
7 7
8#define _GNU_SOURCE /* for program_invocation_name */
9
8#include <stdio.h> 10#include <stdio.h>
9#include <stdlib.h> 11#include <stdlib.h>
10#include <unistd.h> 12#include <unistd.h>
@@ -15,76 +17,78 @@
15 17
16#include "test_util.h" 18#include "test_util.h"
17#include "kvm_util.h" 19#include "kvm_util.h"
20#include "processor.h"
21
22#define DEBUG printf
18 23
19#define DEBUG printf 24#define VCPU_ID 1
20 25
21#define VCPU_ID 1
22/* The memory slot index to track dirty pages */ 26/* The memory slot index to track dirty pages */
23#define TEST_MEM_SLOT_INDEX 1 27#define TEST_MEM_SLOT_INDEX 1
24/* 28
25 * GPA offset of the testing memory slot. Must be bigger than the 29/* Default guest test memory offset, 1G */
26 * default vm mem slot, which is DEFAULT_GUEST_PHY_PAGES. 30#define DEFAULT_GUEST_TEST_MEM 0x40000000
27 */ 31
28#define TEST_MEM_OFFSET (1ULL << 30) /* 1G */
29/* Size of the testing memory slot */
30#define TEST_MEM_PAGES (1ULL << 18) /* 1G for 4K pages */
31/* How many pages to dirty for each guest loop */ 32/* How many pages to dirty for each guest loop */
32#define TEST_PAGES_PER_LOOP 1024 33#define TEST_PAGES_PER_LOOP 1024
34
33/* How many host loops to run (one KVM_GET_DIRTY_LOG for each loop) */ 35/* How many host loops to run (one KVM_GET_DIRTY_LOG for each loop) */
34#define TEST_HOST_LOOP_N 32 36#define TEST_HOST_LOOP_N 32
37
35/* Interval for each host loop (ms) */ 38/* Interval for each host loop (ms) */
36#define TEST_HOST_LOOP_INTERVAL 10 39#define TEST_HOST_LOOP_INTERVAL 10
40
41/*
42 * Guest/Host shared variables. Ensure addr_gva2hva() and/or
43 * sync_global_to/from_guest() are used when accessing from
44 * the host. READ/WRITE_ONCE() should also be used with anything
45 * that may change.
46 */
47static uint64_t host_page_size;
48static uint64_t guest_page_size;
49static uint64_t guest_num_pages;
50static uint64_t random_array[TEST_PAGES_PER_LOOP];
51static uint64_t iteration;
37 52
38/* 53/*
39 * Guest variables. We use these variables to share data between host 54 * GPA offset of the testing memory slot. Must be bigger than
40 * and guest. There are two copies of the variables, one in host memory 55 * DEFAULT_GUEST_PHY_PAGES.
41 * (which is unused) and one in guest memory. When the host wants to
42 * access these variables, it needs to call addr_gva2hva() to access the
43 * guest copy.
44 */ 56 */
45uint64_t guest_random_array[TEST_PAGES_PER_LOOP]; 57static uint64_t guest_test_mem = DEFAULT_GUEST_TEST_MEM;
46uint64_t guest_iteration;
47uint64_t guest_page_size;
48 58
49/* 59/*
50 * Writes to the first byte of a random page within the testing memory 60 * Continuously write to the first 8 bytes of a random pages within
51 * region continuously. 61 * the testing memory region.
52 */ 62 */
53void guest_code(void) 63static void guest_code(void)
54{ 64{
55 int i = 0; 65 int i;
56 uint64_t volatile *array = guest_random_array;
57 uint64_t volatile *guest_addr;
58 66
59 while (true) { 67 while (true) {
60 for (i = 0; i < TEST_PAGES_PER_LOOP; i++) { 68 for (i = 0; i < TEST_PAGES_PER_LOOP; i++) {
61 /* 69 uint64_t addr = guest_test_mem;
62 * Write to the first 8 bytes of a random page 70 addr += (READ_ONCE(random_array[i]) % guest_num_pages)
63 * on the testing memory region. 71 * guest_page_size;
64 */ 72 addr &= ~(host_page_size - 1);
65 guest_addr = (uint64_t *) 73 *(uint64_t *)addr = READ_ONCE(iteration);
66 (TEST_MEM_OFFSET +
67 (array[i] % TEST_MEM_PAGES) * guest_page_size);
68 *guest_addr = guest_iteration;
69 } 74 }
75
70 /* Tell the host that we need more random numbers */ 76 /* Tell the host that we need more random numbers */
71 GUEST_SYNC(1); 77 GUEST_SYNC(1);
72 } 78 }
73} 79}
74 80
75/* 81/* Host variables */
76 * Host variables. These variables should only be used by the host 82static bool host_quit;
77 * rather than the guest.
78 */
79bool host_quit;
80 83
81/* Points to the test VM memory region on which we track dirty logs */ 84/* Points to the test VM memory region on which we track dirty logs */
82void *host_test_mem; 85static void *host_test_mem;
86static uint64_t host_num_pages;
83 87
84/* For statistics only */ 88/* For statistics only */
85uint64_t host_dirty_count; 89static uint64_t host_dirty_count;
86uint64_t host_clear_count; 90static uint64_t host_clear_count;
87uint64_t host_track_next_count; 91static uint64_t host_track_next_count;
88 92
89/* 93/*
90 * We use this bitmap to track some pages that should have its dirty 94 * We use this bitmap to track some pages that should have its dirty
@@ -93,40 +97,34 @@ uint64_t host_track_next_count;
93 * page bit is cleared in the latest bitmap, then the system must 97 * page bit is cleared in the latest bitmap, then the system must
94 * report that write in the next get dirty log call. 98 * report that write in the next get dirty log call.
95 */ 99 */
96unsigned long *host_bmap_track; 100static unsigned long *host_bmap_track;
97 101
98void generate_random_array(uint64_t *guest_array, uint64_t size) 102static void generate_random_array(uint64_t *guest_array, uint64_t size)
99{ 103{
100 uint64_t i; 104 uint64_t i;
101 105
102 for (i = 0; i < size; i++) { 106 for (i = 0; i < size; i++)
103 guest_array[i] = random(); 107 guest_array[i] = random();
104 }
105} 108}
106 109
107void *vcpu_worker(void *data) 110static void *vcpu_worker(void *data)
108{ 111{
109 int ret; 112 int ret;
110 uint64_t loops, *guest_array, pages_count = 0;
111 struct kvm_vm *vm = data; 113 struct kvm_vm *vm = data;
114 uint64_t *guest_array;
115 uint64_t pages_count = 0;
112 struct kvm_run *run; 116 struct kvm_run *run;
113 struct guest_args args; 117 struct ucall uc;
114 118
115 run = vcpu_state(vm, VCPU_ID); 119 run = vcpu_state(vm, VCPU_ID);
116 120
117 /* Retrieve the guest random array pointer and cache it */ 121 guest_array = addr_gva2hva(vm, (vm_vaddr_t)random_array);
118 guest_array = addr_gva2hva(vm, (vm_vaddr_t)guest_random_array);
119
120 DEBUG("VCPU starts\n");
121
122 generate_random_array(guest_array, TEST_PAGES_PER_LOOP); 122 generate_random_array(guest_array, TEST_PAGES_PER_LOOP);
123 123
124 while (!READ_ONCE(host_quit)) { 124 while (!READ_ONCE(host_quit)) {
125 /* Let the guest to dirty these random pages */ 125 /* Let the guest dirty the random pages */
126 ret = _vcpu_run(vm, VCPU_ID); 126 ret = _vcpu_run(vm, VCPU_ID);
127 guest_args_read(vm, VCPU_ID, &args); 127 if (get_ucall(vm, VCPU_ID, &uc) == UCALL_SYNC) {
128 if (run->exit_reason == KVM_EXIT_IO &&
129 args.port == GUEST_PORT_SYNC) {
130 pages_count += TEST_PAGES_PER_LOOP; 128 pages_count += TEST_PAGES_PER_LOOP;
131 generate_random_array(guest_array, TEST_PAGES_PER_LOOP); 129 generate_random_array(guest_array, TEST_PAGES_PER_LOOP);
132 } else { 130 } else {
@@ -137,18 +135,20 @@ void *vcpu_worker(void *data)
137 } 135 }
138 } 136 }
139 137
140 DEBUG("VCPU exits, dirtied %"PRIu64" pages\n", pages_count); 138 DEBUG("Dirtied %"PRIu64" pages\n", pages_count);
141 139
142 return NULL; 140 return NULL;
143} 141}
144 142
145void vm_dirty_log_verify(unsigned long *bmap, uint64_t iteration) 143static void vm_dirty_log_verify(unsigned long *bmap)
146{ 144{
147 uint64_t page; 145 uint64_t page;
148 uint64_t volatile *value_ptr; 146 uint64_t *value_ptr;
147 uint64_t step = host_page_size >= guest_page_size ? 1 :
148 guest_page_size / host_page_size;
149 149
150 for (page = 0; page < TEST_MEM_PAGES; page++) { 150 for (page = 0; page < host_num_pages; page += step) {
151 value_ptr = host_test_mem + page * getpagesize(); 151 value_ptr = host_test_mem + page * host_page_size;
152 152
153 /* If this is a special page that we were tracking... */ 153 /* If this is a special page that we were tracking... */
154 if (test_and_clear_bit(page, host_bmap_track)) { 154 if (test_and_clear_bit(page, host_bmap_track)) {
@@ -208,88 +208,117 @@ void vm_dirty_log_verify(unsigned long *bmap, uint64_t iteration)
208 } 208 }
209} 209}
210 210
211void help(char *name) 211static struct kvm_vm *create_vm(enum vm_guest_mode mode, uint32_t vcpuid,
212 uint64_t extra_mem_pages, void *guest_code)
212{ 213{
213 puts(""); 214 struct kvm_vm *vm;
214 printf("usage: %s [-i iterations] [-I interval] [-h]\n", name); 215 uint64_t extra_pg_pages = extra_mem_pages / 512 * 2;
215 puts(""); 216
216 printf(" -i: specify iteration counts (default: %"PRIu64")\n", 217 vm = vm_create(mode, DEFAULT_GUEST_PHY_PAGES + extra_pg_pages, O_RDWR);
217 TEST_HOST_LOOP_N); 218 kvm_vm_elf_load(vm, program_invocation_name, 0, 0);
218 printf(" -I: specify interval in ms (default: %"PRIu64" ms)\n", 219#ifdef __x86_64__
219 TEST_HOST_LOOP_INTERVAL); 220 vm_create_irqchip(vm);
220 puts(""); 221#endif
221 exit(0); 222 vm_vcpu_add_default(vm, vcpuid, guest_code);
223 return vm;
222} 224}
223 225
224int main(int argc, char *argv[]) 226static void run_test(enum vm_guest_mode mode, unsigned long iterations,
227 unsigned long interval, bool top_offset)
225{ 228{
229 unsigned int guest_pa_bits, guest_page_shift;
226 pthread_t vcpu_thread; 230 pthread_t vcpu_thread;
227 struct kvm_vm *vm; 231 struct kvm_vm *vm;
228 uint64_t volatile *psize, *iteration; 232 uint64_t max_gfn;
229 unsigned long *bmap, iterations = TEST_HOST_LOOP_N, 233 unsigned long *bmap;
230 interval = TEST_HOST_LOOP_INTERVAL; 234
231 int opt; 235 switch (mode) {
232 236 case VM_MODE_P52V48_4K:
233 while ((opt = getopt(argc, argv, "hi:I:")) != -1) { 237 guest_pa_bits = 52;
234 switch (opt) { 238 guest_page_shift = 12;
235 case 'i': 239 break;
236 iterations = strtol(optarg, NULL, 10); 240 case VM_MODE_P52V48_64K:
237 break; 241 guest_pa_bits = 52;
238 case 'I': 242 guest_page_shift = 16;
239 interval = strtol(optarg, NULL, 10); 243 break;
240 break; 244 case VM_MODE_P40V48_4K:
241 case 'h': 245 guest_pa_bits = 40;
242 default: 246 guest_page_shift = 12;
243 help(argv[0]); 247 break;
244 break; 248 case VM_MODE_P40V48_64K:
245 } 249 guest_pa_bits = 40;
250 guest_page_shift = 16;
251 break;
252 default:
253 TEST_ASSERT(false, "Unknown guest mode, mode: 0x%x", mode);
246 } 254 }
247 255
248 TEST_ASSERT(iterations > 2, "Iteration must be bigger than zero\n"); 256 DEBUG("Testing guest mode: %s\n", vm_guest_mode_string(mode));
249 TEST_ASSERT(interval > 0, "Interval must be bigger than zero");
250 257
251 DEBUG("Test iterations: %"PRIu64", interval: %"PRIu64" (ms)\n", 258 max_gfn = (1ul << (guest_pa_bits - guest_page_shift)) - 1;
252 iterations, interval); 259 guest_page_size = (1ul << guest_page_shift);
260 /* 1G of guest page sized pages */
261 guest_num_pages = (1ul << (30 - guest_page_shift));
262 host_page_size = getpagesize();
263 host_num_pages = (guest_num_pages * guest_page_size) / host_page_size +
264 !!((guest_num_pages * guest_page_size) % host_page_size);
253 265
254 srandom(time(0)); 266 if (top_offset) {
267 guest_test_mem = (max_gfn - guest_num_pages) * guest_page_size;
268 guest_test_mem &= ~(host_page_size - 1);
269 }
255 270
256 bmap = bitmap_alloc(TEST_MEM_PAGES); 271 DEBUG("guest test mem offset: 0x%lx\n", guest_test_mem);
257 host_bmap_track = bitmap_alloc(TEST_MEM_PAGES);
258 272
259 vm = vm_create_default(VCPU_ID, TEST_MEM_PAGES, guest_code); 273 bmap = bitmap_alloc(host_num_pages);
274 host_bmap_track = bitmap_alloc(host_num_pages);
275
276 vm = create_vm(mode, VCPU_ID, guest_num_pages, guest_code);
260 277
261 /* Add an extra memory slot for testing dirty logging */ 278 /* Add an extra memory slot for testing dirty logging */
262 vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS, 279 vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
263 TEST_MEM_OFFSET, 280 guest_test_mem,
264 TEST_MEM_SLOT_INDEX, 281 TEST_MEM_SLOT_INDEX,
265 TEST_MEM_PAGES, 282 guest_num_pages,
266 KVM_MEM_LOG_DIRTY_PAGES); 283 KVM_MEM_LOG_DIRTY_PAGES);
267 /* Cache the HVA pointer of the region */
268 host_test_mem = addr_gpa2hva(vm, (vm_paddr_t)TEST_MEM_OFFSET);
269 284
270 /* Do 1:1 mapping for the dirty track memory slot */ 285 /* Do 1:1 mapping for the dirty track memory slot */
271 virt_map(vm, TEST_MEM_OFFSET, TEST_MEM_OFFSET, 286 virt_map(vm, guest_test_mem, guest_test_mem,
272 TEST_MEM_PAGES * getpagesize(), 0); 287 guest_num_pages * guest_page_size, 0);
288
289 /* Cache the HVA pointer of the region */
290 host_test_mem = addr_gpa2hva(vm, (vm_paddr_t)guest_test_mem);
273 291
292#ifdef __x86_64__
274 vcpu_set_cpuid(vm, VCPU_ID, kvm_get_supported_cpuid()); 293 vcpu_set_cpuid(vm, VCPU_ID, kvm_get_supported_cpuid());
294#endif
295#ifdef __aarch64__
296 ucall_init(vm, UCALL_MMIO, NULL);
297#endif
275 298
276 /* Tell the guest about the page size on the system */ 299 /* Export the shared variables to the guest */
277 psize = addr_gva2hva(vm, (vm_vaddr_t)&guest_page_size); 300 sync_global_to_guest(vm, host_page_size);
278 *psize = getpagesize(); 301 sync_global_to_guest(vm, guest_page_size);
302 sync_global_to_guest(vm, guest_test_mem);
303 sync_global_to_guest(vm, guest_num_pages);
279 304
280 /* Start the iterations */ 305 /* Start the iterations */
281 iteration = addr_gva2hva(vm, (vm_vaddr_t)&guest_iteration); 306 iteration = 1;
282 *iteration = 1; 307 sync_global_to_guest(vm, iteration);
308 host_quit = false;
309 host_dirty_count = 0;
310 host_clear_count = 0;
311 host_track_next_count = 0;
283 312
284 /* Start dirtying pages */
285 pthread_create(&vcpu_thread, NULL, vcpu_worker, vm); 313 pthread_create(&vcpu_thread, NULL, vcpu_worker, vm);
286 314
287 while (*iteration < iterations) { 315 while (iteration < iterations) {
288 /* Give the vcpu thread some time to dirty some pages */ 316 /* Give the vcpu thread some time to dirty some pages */
289 usleep(interval * 1000); 317 usleep(interval * 1000);
290 kvm_vm_get_dirty_log(vm, TEST_MEM_SLOT_INDEX, bmap); 318 kvm_vm_get_dirty_log(vm, TEST_MEM_SLOT_INDEX, bmap);
291 vm_dirty_log_verify(bmap, *iteration); 319 vm_dirty_log_verify(bmap);
292 (*iteration)++; 320 iteration++;
321 sync_global_to_guest(vm, iteration);
293 } 322 }
294 323
295 /* Tell the vcpu thread to quit */ 324 /* Tell the vcpu thread to quit */
@@ -302,7 +331,118 @@ int main(int argc, char *argv[])
302 331
303 free(bmap); 332 free(bmap);
304 free(host_bmap_track); 333 free(host_bmap_track);
334 ucall_uninit(vm);
305 kvm_vm_free(vm); 335 kvm_vm_free(vm);
336}
337
338static struct vm_guest_modes {
339 enum vm_guest_mode mode;
340 bool supported;
341 bool enabled;
342} vm_guest_modes[NUM_VM_MODES] = {
343#if defined(__x86_64__)
344 { VM_MODE_P52V48_4K, 1, 1, },
345 { VM_MODE_P52V48_64K, 0, 0, },
346 { VM_MODE_P40V48_4K, 0, 0, },
347 { VM_MODE_P40V48_64K, 0, 0, },
348#elif defined(__aarch64__)
349 { VM_MODE_P52V48_4K, 0, 0, },
350 { VM_MODE_P52V48_64K, 0, 0, },
351 { VM_MODE_P40V48_4K, 1, 1, },
352 { VM_MODE_P40V48_64K, 1, 1, },
353#endif
354};
355
356static void help(char *name)
357{
358 int i;
359
360 puts("");
361 printf("usage: %s [-h] [-i iterations] [-I interval] "
362 "[-o offset] [-t] [-m mode]\n", name);
363 puts("");
364 printf(" -i: specify iteration counts (default: %"PRIu64")\n",
365 TEST_HOST_LOOP_N);
366 printf(" -I: specify interval in ms (default: %"PRIu64" ms)\n",
367 TEST_HOST_LOOP_INTERVAL);
368 printf(" -o: guest test memory offset (default: 0x%lx)\n",
369 DEFAULT_GUEST_TEST_MEM);
370 printf(" -t: map guest test memory at the top of the allowed "
371 "physical address range\n");
372 printf(" -m: specify the guest mode ID to test "
373 "(default: test all supported modes)\n"
374 " This option may be used multiple times.\n"
375 " Guest mode IDs:\n");
376 for (i = 0; i < NUM_VM_MODES; ++i) {
377 printf(" %d: %s%s\n",
378 vm_guest_modes[i].mode,
379 vm_guest_mode_string(vm_guest_modes[i].mode),
380 vm_guest_modes[i].supported ? " (supported)" : "");
381 }
382 puts("");
383 exit(0);
384}
385
386int main(int argc, char *argv[])
387{
388 unsigned long iterations = TEST_HOST_LOOP_N;
389 unsigned long interval = TEST_HOST_LOOP_INTERVAL;
390 bool mode_selected = false;
391 bool top_offset = false;
392 unsigned int mode;
393 int opt, i;
394
395 while ((opt = getopt(argc, argv, "hi:I:o:tm:")) != -1) {
396 switch (opt) {
397 case 'i':
398 iterations = strtol(optarg, NULL, 10);
399 break;
400 case 'I':
401 interval = strtol(optarg, NULL, 10);
402 break;
403 case 'o':
404 guest_test_mem = strtoull(optarg, NULL, 0);
405 break;
406 case 't':
407 top_offset = true;
408 break;
409 case 'm':
410 if (!mode_selected) {
411 for (i = 0; i < NUM_VM_MODES; ++i)
412 vm_guest_modes[i].enabled = 0;
413 mode_selected = true;
414 }
415 mode = strtoul(optarg, NULL, 10);
416 TEST_ASSERT(mode < NUM_VM_MODES,
417 "Guest mode ID %d too big", mode);
418 vm_guest_modes[mode].enabled = 1;
419 break;
420 case 'h':
421 default:
422 help(argv[0]);
423 break;
424 }
425 }
426
427 TEST_ASSERT(iterations > 2, "Iterations must be greater than two");
428 TEST_ASSERT(interval > 0, "Interval must be greater than zero");
429 TEST_ASSERT(!top_offset || guest_test_mem == DEFAULT_GUEST_TEST_MEM,
430 "Cannot use both -o [offset] and -t at the same time");
431
432 DEBUG("Test iterations: %"PRIu64", interval: %"PRIu64" (ms)\n",
433 iterations, interval);
434
435 srandom(time(0));
436
437 for (i = 0; i < NUM_VM_MODES; ++i) {
438 if (!vm_guest_modes[i].enabled)
439 continue;
440 TEST_ASSERT(vm_guest_modes[i].supported,
441 "Guest mode ID %d (%s) not supported.",
442 vm_guest_modes[i].mode,
443 vm_guest_mode_string(vm_guest_modes[i].mode));
444 run_test(vm_guest_modes[i].mode, iterations, interval, top_offset);
445 }
306 446
307 return 0; 447 return 0;
308} 448}
diff --git a/tools/testing/selftests/kvm/include/aarch64/processor.h b/tools/testing/selftests/kvm/include/aarch64/processor.h
new file mode 100644
index 000000000000..9ef2ab1a0c08
--- /dev/null
+++ b/tools/testing/selftests/kvm/include/aarch64/processor.h
@@ -0,0 +1,55 @@
1/* SPDX-License-Identifier: GPL-2.0 */
2/*
3 * AArch64 processor specific defines
4 *
5 * Copyright (C) 2018, Red Hat, Inc.
6 */
7#ifndef SELFTEST_KVM_PROCESSOR_H
8#define SELFTEST_KVM_PROCESSOR_H
9
10#include "kvm_util.h"
11
12
13#define ARM64_CORE_REG(x) (KVM_REG_ARM64 | KVM_REG_SIZE_U64 | \
14 KVM_REG_ARM_CORE | KVM_REG_ARM_CORE_REG(x))
15
16#define CPACR_EL1 3, 0, 1, 0, 2
17#define TCR_EL1 3, 0, 2, 0, 2
18#define MAIR_EL1 3, 0, 10, 2, 0
19#define TTBR0_EL1 3, 0, 2, 0, 0
20#define SCTLR_EL1 3, 0, 1, 0, 0
21
22/*
23 * Default MAIR
24 * index attribute
25 * DEVICE_nGnRnE 0 0000:0000
26 * DEVICE_nGnRE 1 0000:0100
27 * DEVICE_GRE 2 0000:1100
28 * NORMAL_NC 3 0100:0100
29 * NORMAL 4 1111:1111
30 * NORMAL_WT 5 1011:1011
31 */
32#define DEFAULT_MAIR_EL1 ((0x00ul << (0 * 8)) | \
33 (0x04ul << (1 * 8)) | \
34 (0x0cul << (2 * 8)) | \
35 (0x44ul << (3 * 8)) | \
36 (0xfful << (4 * 8)) | \
37 (0xbbul << (5 * 8)))
38
39static inline void get_reg(struct kvm_vm *vm, uint32_t vcpuid, uint64_t id, uint64_t *addr)
40{
41 struct kvm_one_reg reg;
42 reg.id = id;
43 reg.addr = (uint64_t)addr;
44 vcpu_ioctl(vm, vcpuid, KVM_GET_ONE_REG, &reg);
45}
46
47static inline void set_reg(struct kvm_vm *vm, uint32_t vcpuid, uint64_t id, uint64_t val)
48{
49 struct kvm_one_reg reg;
50 reg.id = id;
51 reg.addr = (uint64_t)&val;
52 vcpu_ioctl(vm, vcpuid, KVM_SET_ONE_REG, &reg);
53}
54
55#endif /* SELFTEST_KVM_PROCESSOR_H */
diff --git a/tools/testing/selftests/kvm/include/evmcs.h b/tools/testing/selftests/kvm/include/evmcs.h
new file mode 100644
index 000000000000..4059014d93ea
--- /dev/null
+++ b/tools/testing/selftests/kvm/include/evmcs.h
@@ -0,0 +1,1098 @@
1/* SPDX-License-Identifier: GPL-2.0 */
2/*
3 * tools/testing/selftests/kvm/include/vmx.h
4 *
5 * Copyright (C) 2018, Red Hat, Inc.
6 *
7 */
8
9#ifndef SELFTEST_KVM_EVMCS_H
10#define SELFTEST_KVM_EVMCS_H
11
12#include <stdint.h>
13#include "vmx.h"
14
15#define u16 uint16_t
16#define u32 uint32_t
17#define u64 uint64_t
18
19extern bool enable_evmcs;
20
21struct hv_vp_assist_page {
22 __u32 apic_assist;
23 __u32 reserved;
24 __u64 vtl_control[2];
25 __u64 nested_enlightenments_control[2];
26 __u32 enlighten_vmentry;
27 __u64 current_nested_vmcs;
28};
29
30struct hv_enlightened_vmcs {
31 u32 revision_id;
32 u32 abort;
33
34 u16 host_es_selector;
35 u16 host_cs_selector;
36 u16 host_ss_selector;
37 u16 host_ds_selector;
38 u16 host_fs_selector;
39 u16 host_gs_selector;
40 u16 host_tr_selector;
41
42 u64 host_ia32_pat;
43 u64 host_ia32_efer;
44
45 u64 host_cr0;
46 u64 host_cr3;
47 u64 host_cr4;
48
49 u64 host_ia32_sysenter_esp;
50 u64 host_ia32_sysenter_eip;
51 u64 host_rip;
52 u32 host_ia32_sysenter_cs;
53
54 u32 pin_based_vm_exec_control;
55 u32 vm_exit_controls;
56 u32 secondary_vm_exec_control;
57
58 u64 io_bitmap_a;
59 u64 io_bitmap_b;
60 u64 msr_bitmap;
61
62 u16 guest_es_selector;
63 u16 guest_cs_selector;
64 u16 guest_ss_selector;
65 u16 guest_ds_selector;
66 u16 guest_fs_selector;
67 u16 guest_gs_selector;
68 u16 guest_ldtr_selector;
69 u16 guest_tr_selector;
70
71 u32 guest_es_limit;
72 u32 guest_cs_limit;
73 u32 guest_ss_limit;
74 u32 guest_ds_limit;
75 u32 guest_fs_limit;
76 u32 guest_gs_limit;
77 u32 guest_ldtr_limit;
78 u32 guest_tr_limit;
79 u32 guest_gdtr_limit;
80 u32 guest_idtr_limit;
81
82 u32 guest_es_ar_bytes;
83 u32 guest_cs_ar_bytes;
84 u32 guest_ss_ar_bytes;
85 u32 guest_ds_ar_bytes;
86 u32 guest_fs_ar_bytes;
87 u32 guest_gs_ar_bytes;
88 u32 guest_ldtr_ar_bytes;
89 u32 guest_tr_ar_bytes;
90
91 u64 guest_es_base;
92 u64 guest_cs_base;
93 u64 guest_ss_base;
94 u64 guest_ds_base;
95 u64 guest_fs_base;
96 u64 guest_gs_base;
97 u64 guest_ldtr_base;
98 u64 guest_tr_base;
99 u64 guest_gdtr_base;
100 u64 guest_idtr_base;
101
102 u64 padding64_1[3];
103
104 u64 vm_exit_msr_store_addr;
105 u64 vm_exit_msr_load_addr;
106 u64 vm_entry_msr_load_addr;
107
108 u64 cr3_target_value0;
109 u64 cr3_target_value1;
110 u64 cr3_target_value2;
111 u64 cr3_target_value3;
112
113 u32 page_fault_error_code_mask;
114 u32 page_fault_error_code_match;
115
116 u32 cr3_target_count;
117 u32 vm_exit_msr_store_count;
118 u32 vm_exit_msr_load_count;
119 u32 vm_entry_msr_load_count;
120
121 u64 tsc_offset;
122 u64 virtual_apic_page_addr;
123 u64 vmcs_link_pointer;
124
125 u64 guest_ia32_debugctl;
126 u64 guest_ia32_pat;
127 u64 guest_ia32_efer;
128
129 u64 guest_pdptr0;
130 u64 guest_pdptr1;
131 u64 guest_pdptr2;
132 u64 guest_pdptr3;
133
134 u64 guest_pending_dbg_exceptions;
135 u64 guest_sysenter_esp;
136 u64 guest_sysenter_eip;
137
138 u32 guest_activity_state;
139 u32 guest_sysenter_cs;
140
141 u64 cr0_guest_host_mask;
142 u64 cr4_guest_host_mask;
143 u64 cr0_read_shadow;
144 u64 cr4_read_shadow;
145 u64 guest_cr0;
146 u64 guest_cr3;
147 u64 guest_cr4;
148 u64 guest_dr7;
149
150 u64 host_fs_base;
151 u64 host_gs_base;
152 u64 host_tr_base;
153 u64 host_gdtr_base;
154 u64 host_idtr_base;
155 u64 host_rsp;
156
157 u64 ept_pointer;
158
159 u16 virtual_processor_id;
160 u16 padding16[3];
161
162 u64 padding64_2[5];
163 u64 guest_physical_address;
164
165 u32 vm_instruction_error;
166 u32 vm_exit_reason;
167 u32 vm_exit_intr_info;
168 u32 vm_exit_intr_error_code;
169 u32 idt_vectoring_info_field;
170 u32 idt_vectoring_error_code;
171 u32 vm_exit_instruction_len;
172 u32 vmx_instruction_info;
173
174 u64 exit_qualification;
175 u64 exit_io_instruction_ecx;
176 u64 exit_io_instruction_esi;
177 u64 exit_io_instruction_edi;
178 u64 exit_io_instruction_eip;
179
180 u64 guest_linear_address;
181 u64 guest_rsp;
182 u64 guest_rflags;
183
184 u32 guest_interruptibility_info;
185 u32 cpu_based_vm_exec_control;
186 u32 exception_bitmap;
187 u32 vm_entry_controls;
188 u32 vm_entry_intr_info_field;
189 u32 vm_entry_exception_error_code;
190 u32 vm_entry_instruction_len;
191 u32 tpr_threshold;
192
193 u64 guest_rip;
194
195 u32 hv_clean_fields;
196 u32 hv_padding_32;
197 u32 hv_synthetic_controls;
198 struct {
199 u32 nested_flush_hypercall:1;
200 u32 msr_bitmap:1;
201 u32 reserved:30;
202 } hv_enlightenments_control;
203 u32 hv_vp_id;
204
205 u64 hv_vm_id;
206 u64 partition_assist_page;
207 u64 padding64_4[4];
208 u64 guest_bndcfgs;
209 u64 padding64_5[7];
210 u64 xss_exit_bitmap;
211 u64 padding64_6[7];
212};
213
214#define HV_X64_MSR_VP_ASSIST_PAGE 0x40000073
215#define HV_X64_MSR_VP_ASSIST_PAGE_ENABLE 0x00000001
216#define HV_X64_MSR_VP_ASSIST_PAGE_ADDRESS_SHIFT 12
217#define HV_X64_MSR_VP_ASSIST_PAGE_ADDRESS_MASK \
218 (~((1ull << HV_X64_MSR_VP_ASSIST_PAGE_ADDRESS_SHIFT) - 1))
219
220struct hv_enlightened_vmcs *current_evmcs;
221struct hv_vp_assist_page *current_vp_assist;
222
223static inline int enable_vp_assist(uint64_t vp_assist_pa, void *vp_assist)
224{
225 u64 val = (vp_assist_pa & HV_X64_MSR_VP_ASSIST_PAGE_ADDRESS_MASK) |
226 HV_X64_MSR_VP_ASSIST_PAGE_ENABLE;
227
228 wrmsr(HV_X64_MSR_VP_ASSIST_PAGE, val);
229
230 current_vp_assist = vp_assist;
231
232 enable_evmcs = true;
233
234 return 0;
235}
236
237static inline int evmcs_vmptrld(uint64_t vmcs_pa, void *vmcs)
238{
239 current_vp_assist->current_nested_vmcs = vmcs_pa;
240 current_vp_assist->enlighten_vmentry = 1;
241
242 current_evmcs = vmcs;
243
244 return 0;
245}
246
247static inline int evmcs_vmptrst(uint64_t *value)
248{
249 *value = current_vp_assist->current_nested_vmcs &
250 ~HV_X64_MSR_VP_ASSIST_PAGE_ENABLE;
251
252 return 0;
253}
254
255static inline int evmcs_vmread(uint64_t encoding, uint64_t *value)
256{
257 switch (encoding) {
258 case GUEST_RIP:
259 *value = current_evmcs->guest_rip;
260 break;
261 case GUEST_RSP:
262 *value = current_evmcs->guest_rsp;
263 break;
264 case GUEST_RFLAGS:
265 *value = current_evmcs->guest_rflags;
266 break;
267 case HOST_IA32_PAT:
268 *value = current_evmcs->host_ia32_pat;
269 break;
270 case HOST_IA32_EFER:
271 *value = current_evmcs->host_ia32_efer;
272 break;
273 case HOST_CR0:
274 *value = current_evmcs->host_cr0;
275 break;
276 case HOST_CR3:
277 *value = current_evmcs->host_cr3;
278 break;
279 case HOST_CR4:
280 *value = current_evmcs->host_cr4;
281 break;
282 case HOST_IA32_SYSENTER_ESP:
283 *value = current_evmcs->host_ia32_sysenter_esp;
284 break;
285 case HOST_IA32_SYSENTER_EIP:
286 *value = current_evmcs->host_ia32_sysenter_eip;
287 break;
288 case HOST_RIP:
289 *value = current_evmcs->host_rip;
290 break;
291 case IO_BITMAP_A:
292 *value = current_evmcs->io_bitmap_a;
293 break;
294 case IO_BITMAP_B:
295 *value = current_evmcs->io_bitmap_b;
296 break;
297 case MSR_BITMAP:
298 *value = current_evmcs->msr_bitmap;
299 break;
300 case GUEST_ES_BASE:
301 *value = current_evmcs->guest_es_base;
302 break;
303 case GUEST_CS_BASE:
304 *value = current_evmcs->guest_cs_base;
305 break;
306 case GUEST_SS_BASE:
307 *value = current_evmcs->guest_ss_base;
308 break;
309 case GUEST_DS_BASE:
310 *value = current_evmcs->guest_ds_base;
311 break;
312 case GUEST_FS_BASE:
313 *value = current_evmcs->guest_fs_base;
314 break;
315 case GUEST_GS_BASE:
316 *value = current_evmcs->guest_gs_base;
317 break;
318 case GUEST_LDTR_BASE:
319 *value = current_evmcs->guest_ldtr_base;
320 break;
321 case GUEST_TR_BASE:
322 *value = current_evmcs->guest_tr_base;
323 break;
324 case GUEST_GDTR_BASE:
325 *value = current_evmcs->guest_gdtr_base;
326 break;
327 case GUEST_IDTR_BASE:
328 *value = current_evmcs->guest_idtr_base;
329 break;
330 case TSC_OFFSET:
331 *value = current_evmcs->tsc_offset;
332 break;
333 case VIRTUAL_APIC_PAGE_ADDR:
334 *value = current_evmcs->virtual_apic_page_addr;
335 break;
336 case VMCS_LINK_POINTER:
337 *value = current_evmcs->vmcs_link_pointer;
338 break;
339 case GUEST_IA32_DEBUGCTL:
340 *value = current_evmcs->guest_ia32_debugctl;
341 break;
342 case GUEST_IA32_PAT:
343 *value = current_evmcs->guest_ia32_pat;
344 break;
345 case GUEST_IA32_EFER:
346 *value = current_evmcs->guest_ia32_efer;
347 break;
348 case GUEST_PDPTR0:
349 *value = current_evmcs->guest_pdptr0;
350 break;
351 case GUEST_PDPTR1:
352 *value = current_evmcs->guest_pdptr1;
353 break;
354 case GUEST_PDPTR2:
355 *value = current_evmcs->guest_pdptr2;
356 break;
357 case GUEST_PDPTR3:
358 *value = current_evmcs->guest_pdptr3;
359 break;
360 case GUEST_PENDING_DBG_EXCEPTIONS:
361 *value = current_evmcs->guest_pending_dbg_exceptions;
362 break;
363 case GUEST_SYSENTER_ESP:
364 *value = current_evmcs->guest_sysenter_esp;
365 break;
366 case GUEST_SYSENTER_EIP:
367 *value = current_evmcs->guest_sysenter_eip;
368 break;
369 case CR0_GUEST_HOST_MASK:
370 *value = current_evmcs->cr0_guest_host_mask;
371 break;
372 case CR4_GUEST_HOST_MASK:
373 *value = current_evmcs->cr4_guest_host_mask;
374 break;
375 case CR0_READ_SHADOW:
376 *value = current_evmcs->cr0_read_shadow;
377 break;
378 case CR4_READ_SHADOW:
379 *value = current_evmcs->cr4_read_shadow;
380 break;
381 case GUEST_CR0:
382 *value = current_evmcs->guest_cr0;
383 break;
384 case GUEST_CR3:
385 *value = current_evmcs->guest_cr3;
386 break;
387 case GUEST_CR4:
388 *value = current_evmcs->guest_cr4;
389 break;
390 case GUEST_DR7:
391 *value = current_evmcs->guest_dr7;
392 break;
393 case HOST_FS_BASE:
394 *value = current_evmcs->host_fs_base;
395 break;
396 case HOST_GS_BASE:
397 *value = current_evmcs->host_gs_base;
398 break;
399 case HOST_TR_BASE:
400 *value = current_evmcs->host_tr_base;
401 break;
402 case HOST_GDTR_BASE:
403 *value = current_evmcs->host_gdtr_base;
404 break;
405 case HOST_IDTR_BASE:
406 *value = current_evmcs->host_idtr_base;
407 break;
408 case HOST_RSP:
409 *value = current_evmcs->host_rsp;
410 break;
411 case EPT_POINTER:
412 *value = current_evmcs->ept_pointer;
413 break;
414 case GUEST_BNDCFGS:
415 *value = current_evmcs->guest_bndcfgs;
416 break;
417 case XSS_EXIT_BITMAP:
418 *value = current_evmcs->xss_exit_bitmap;
419 break;
420 case GUEST_PHYSICAL_ADDRESS:
421 *value = current_evmcs->guest_physical_address;
422 break;
423 case EXIT_QUALIFICATION:
424 *value = current_evmcs->exit_qualification;
425 break;
426 case GUEST_LINEAR_ADDRESS:
427 *value = current_evmcs->guest_linear_address;
428 break;
429 case VM_EXIT_MSR_STORE_ADDR:
430 *value = current_evmcs->vm_exit_msr_store_addr;
431 break;
432 case VM_EXIT_MSR_LOAD_ADDR:
433 *value = current_evmcs->vm_exit_msr_load_addr;
434 break;
435 case VM_ENTRY_MSR_LOAD_ADDR:
436 *value = current_evmcs->vm_entry_msr_load_addr;
437 break;
438 case CR3_TARGET_VALUE0:
439 *value = current_evmcs->cr3_target_value0;
440 break;
441 case CR3_TARGET_VALUE1:
442 *value = current_evmcs->cr3_target_value1;
443 break;
444 case CR3_TARGET_VALUE2:
445 *value = current_evmcs->cr3_target_value2;
446 break;
447 case CR3_TARGET_VALUE3:
448 *value = current_evmcs->cr3_target_value3;
449 break;
450 case TPR_THRESHOLD:
451 *value = current_evmcs->tpr_threshold;
452 break;
453 case GUEST_INTERRUPTIBILITY_INFO:
454 *value = current_evmcs->guest_interruptibility_info;
455 break;
456 case CPU_BASED_VM_EXEC_CONTROL:
457 *value = current_evmcs->cpu_based_vm_exec_control;
458 break;
459 case EXCEPTION_BITMAP:
460 *value = current_evmcs->exception_bitmap;
461 break;
462 case VM_ENTRY_CONTROLS:
463 *value = current_evmcs->vm_entry_controls;
464 break;
465 case VM_ENTRY_INTR_INFO_FIELD:
466 *value = current_evmcs->vm_entry_intr_info_field;
467 break;
468 case VM_ENTRY_EXCEPTION_ERROR_CODE:
469 *value = current_evmcs->vm_entry_exception_error_code;
470 break;
471 case VM_ENTRY_INSTRUCTION_LEN:
472 *value = current_evmcs->vm_entry_instruction_len;
473 break;
474 case HOST_IA32_SYSENTER_CS:
475 *value = current_evmcs->host_ia32_sysenter_cs;
476 break;
477 case PIN_BASED_VM_EXEC_CONTROL:
478 *value = current_evmcs->pin_based_vm_exec_control;
479 break;
480 case VM_EXIT_CONTROLS:
481 *value = current_evmcs->vm_exit_controls;
482 break;
483 case SECONDARY_VM_EXEC_CONTROL:
484 *value = current_evmcs->secondary_vm_exec_control;
485 break;
486 case GUEST_ES_LIMIT:
487 *value = current_evmcs->guest_es_limit;
488 break;
489 case GUEST_CS_LIMIT:
490 *value = current_evmcs->guest_cs_limit;
491 break;
492 case GUEST_SS_LIMIT:
493 *value = current_evmcs->guest_ss_limit;
494 break;
495 case GUEST_DS_LIMIT:
496 *value = current_evmcs->guest_ds_limit;
497 break;
498 case GUEST_FS_LIMIT:
499 *value = current_evmcs->guest_fs_limit;
500 break;
501 case GUEST_GS_LIMIT:
502 *value = current_evmcs->guest_gs_limit;
503 break;
504 case GUEST_LDTR_LIMIT:
505 *value = current_evmcs->guest_ldtr_limit;
506 break;
507 case GUEST_TR_LIMIT:
508 *value = current_evmcs->guest_tr_limit;
509 break;
510 case GUEST_GDTR_LIMIT:
511 *value = current_evmcs->guest_gdtr_limit;
512 break;
513 case GUEST_IDTR_LIMIT:
514 *value = current_evmcs->guest_idtr_limit;
515 break;
516 case GUEST_ES_AR_BYTES:
517 *value = current_evmcs->guest_es_ar_bytes;
518 break;
519 case GUEST_CS_AR_BYTES:
520 *value = current_evmcs->guest_cs_ar_bytes;
521 break;
522 case GUEST_SS_AR_BYTES:
523 *value = current_evmcs->guest_ss_ar_bytes;
524 break;
525 case GUEST_DS_AR_BYTES:
526 *value = current_evmcs->guest_ds_ar_bytes;
527 break;
528 case GUEST_FS_AR_BYTES:
529 *value = current_evmcs->guest_fs_ar_bytes;
530 break;
531 case GUEST_GS_AR_BYTES:
532 *value = current_evmcs->guest_gs_ar_bytes;
533 break;
534 case GUEST_LDTR_AR_BYTES:
535 *value = current_evmcs->guest_ldtr_ar_bytes;
536 break;
537 case GUEST_TR_AR_BYTES:
538 *value = current_evmcs->guest_tr_ar_bytes;
539 break;
540 case GUEST_ACTIVITY_STATE:
541 *value = current_evmcs->guest_activity_state;
542 break;
543 case GUEST_SYSENTER_CS:
544 *value = current_evmcs->guest_sysenter_cs;
545 break;
546 case VM_INSTRUCTION_ERROR:
547 *value = current_evmcs->vm_instruction_error;
548 break;
549 case VM_EXIT_REASON:
550 *value = current_evmcs->vm_exit_reason;
551 break;
552 case VM_EXIT_INTR_INFO:
553 *value = current_evmcs->vm_exit_intr_info;
554 break;
555 case VM_EXIT_INTR_ERROR_CODE:
556 *value = current_evmcs->vm_exit_intr_error_code;
557 break;
558 case IDT_VECTORING_INFO_FIELD:
559 *value = current_evmcs->idt_vectoring_info_field;
560 break;
561 case IDT_VECTORING_ERROR_CODE:
562 *value = current_evmcs->idt_vectoring_error_code;
563 break;
564 case VM_EXIT_INSTRUCTION_LEN:
565 *value = current_evmcs->vm_exit_instruction_len;
566 break;
567 case VMX_INSTRUCTION_INFO:
568 *value = current_evmcs->vmx_instruction_info;
569 break;
570 case PAGE_FAULT_ERROR_CODE_MASK:
571 *value = current_evmcs->page_fault_error_code_mask;
572 break;
573 case PAGE_FAULT_ERROR_CODE_MATCH:
574 *value = current_evmcs->page_fault_error_code_match;
575 break;
576 case CR3_TARGET_COUNT:
577 *value = current_evmcs->cr3_target_count;
578 break;
579 case VM_EXIT_MSR_STORE_COUNT:
580 *value = current_evmcs->vm_exit_msr_store_count;
581 break;
582 case VM_EXIT_MSR_LOAD_COUNT:
583 *value = current_evmcs->vm_exit_msr_load_count;
584 break;
585 case VM_ENTRY_MSR_LOAD_COUNT:
586 *value = current_evmcs->vm_entry_msr_load_count;
587 break;
588 case HOST_ES_SELECTOR:
589 *value = current_evmcs->host_es_selector;
590 break;
591 case HOST_CS_SELECTOR:
592 *value = current_evmcs->host_cs_selector;
593 break;
594 case HOST_SS_SELECTOR:
595 *value = current_evmcs->host_ss_selector;
596 break;
597 case HOST_DS_SELECTOR:
598 *value = current_evmcs->host_ds_selector;
599 break;
600 case HOST_FS_SELECTOR:
601 *value = current_evmcs->host_fs_selector;
602 break;
603 case HOST_GS_SELECTOR:
604 *value = current_evmcs->host_gs_selector;
605 break;
606 case HOST_TR_SELECTOR:
607 *value = current_evmcs->host_tr_selector;
608 break;
609 case GUEST_ES_SELECTOR:
610 *value = current_evmcs->guest_es_selector;
611 break;
612 case GUEST_CS_SELECTOR:
613 *value = current_evmcs->guest_cs_selector;
614 break;
615 case GUEST_SS_SELECTOR:
616 *value = current_evmcs->guest_ss_selector;
617 break;
618 case GUEST_DS_SELECTOR:
619 *value = current_evmcs->guest_ds_selector;
620 break;
621 case GUEST_FS_SELECTOR:
622 *value = current_evmcs->guest_fs_selector;
623 break;
624 case GUEST_GS_SELECTOR:
625 *value = current_evmcs->guest_gs_selector;
626 break;
627 case GUEST_LDTR_SELECTOR:
628 *value = current_evmcs->guest_ldtr_selector;
629 break;
630 case GUEST_TR_SELECTOR:
631 *value = current_evmcs->guest_tr_selector;
632 break;
633 case VIRTUAL_PROCESSOR_ID:
634 *value = current_evmcs->virtual_processor_id;
635 break;
636 default: return 1;
637 }
638
639 return 0;
640}
641
642static inline int evmcs_vmwrite(uint64_t encoding, uint64_t value)
643{
644 switch (encoding) {
645 case GUEST_RIP:
646 current_evmcs->guest_rip = value;
647 break;
648 case GUEST_RSP:
649 current_evmcs->guest_rsp = value;
650 break;
651 case GUEST_RFLAGS:
652 current_evmcs->guest_rflags = value;
653 break;
654 case HOST_IA32_PAT:
655 current_evmcs->host_ia32_pat = value;
656 break;
657 case HOST_IA32_EFER:
658 current_evmcs->host_ia32_efer = value;
659 break;
660 case HOST_CR0:
661 current_evmcs->host_cr0 = value;
662 break;
663 case HOST_CR3:
664 current_evmcs->host_cr3 = value;
665 break;
666 case HOST_CR4:
667 current_evmcs->host_cr4 = value;
668 break;
669 case HOST_IA32_SYSENTER_ESP:
670 current_evmcs->host_ia32_sysenter_esp = value;
671 break;
672 case HOST_IA32_SYSENTER_EIP:
673 current_evmcs->host_ia32_sysenter_eip = value;
674 break;
675 case HOST_RIP:
676 current_evmcs->host_rip = value;
677 break;
678 case IO_BITMAP_A:
679 current_evmcs->io_bitmap_a = value;
680 break;
681 case IO_BITMAP_B:
682 current_evmcs->io_bitmap_b = value;
683 break;
684 case MSR_BITMAP:
685 current_evmcs->msr_bitmap = value;
686 break;
687 case GUEST_ES_BASE:
688 current_evmcs->guest_es_base = value;
689 break;
690 case GUEST_CS_BASE:
691 current_evmcs->guest_cs_base = value;
692 break;
693 case GUEST_SS_BASE:
694 current_evmcs->guest_ss_base = value;
695 break;
696 case GUEST_DS_BASE:
697 current_evmcs->guest_ds_base = value;
698 break;
699 case GUEST_FS_BASE:
700 current_evmcs->guest_fs_base = value;
701 break;
702 case GUEST_GS_BASE:
703 current_evmcs->guest_gs_base = value;
704 break;
705 case GUEST_LDTR_BASE:
706 current_evmcs->guest_ldtr_base = value;
707 break;
708 case GUEST_TR_BASE:
709 current_evmcs->guest_tr_base = value;
710 break;
711 case GUEST_GDTR_BASE:
712 current_evmcs->guest_gdtr_base = value;
713 break;
714 case GUEST_IDTR_BASE:
715 current_evmcs->guest_idtr_base = value;
716 break;
717 case TSC_OFFSET:
718 current_evmcs->tsc_offset = value;
719 break;
720 case VIRTUAL_APIC_PAGE_ADDR:
721 current_evmcs->virtual_apic_page_addr = value;
722 break;
723 case VMCS_LINK_POINTER:
724 current_evmcs->vmcs_link_pointer = value;
725 break;
726 case GUEST_IA32_DEBUGCTL:
727 current_evmcs->guest_ia32_debugctl = value;
728 break;
729 case GUEST_IA32_PAT:
730 current_evmcs->guest_ia32_pat = value;
731 break;
732 case GUEST_IA32_EFER:
733 current_evmcs->guest_ia32_efer = value;
734 break;
735 case GUEST_PDPTR0:
736 current_evmcs->guest_pdptr0 = value;
737 break;
738 case GUEST_PDPTR1:
739 current_evmcs->guest_pdptr1 = value;
740 break;
741 case GUEST_PDPTR2:
742 current_evmcs->guest_pdptr2 = value;
743 break;
744 case GUEST_PDPTR3:
745 current_evmcs->guest_pdptr3 = value;
746 break;
747 case GUEST_PENDING_DBG_EXCEPTIONS:
748 current_evmcs->guest_pending_dbg_exceptions = value;
749 break;
750 case GUEST_SYSENTER_ESP:
751 current_evmcs->guest_sysenter_esp = value;
752 break;
753 case GUEST_SYSENTER_EIP:
754 current_evmcs->guest_sysenter_eip = value;
755 break;
756 case CR0_GUEST_HOST_MASK:
757 current_evmcs->cr0_guest_host_mask = value;
758 break;
759 case CR4_GUEST_HOST_MASK:
760 current_evmcs->cr4_guest_host_mask = value;
761 break;
762 case CR0_READ_SHADOW:
763 current_evmcs->cr0_read_shadow = value;
764 break;
765 case CR4_READ_SHADOW:
766 current_evmcs->cr4_read_shadow = value;
767 break;
768 case GUEST_CR0:
769 current_evmcs->guest_cr0 = value;
770 break;
771 case GUEST_CR3:
772 current_evmcs->guest_cr3 = value;
773 break;
774 case GUEST_CR4:
775 current_evmcs->guest_cr4 = value;
776 break;
777 case GUEST_DR7:
778 current_evmcs->guest_dr7 = value;
779 break;
780 case HOST_FS_BASE:
781 current_evmcs->host_fs_base = value;
782 break;
783 case HOST_GS_BASE:
784 current_evmcs->host_gs_base = value;
785 break;
786 case HOST_TR_BASE:
787 current_evmcs->host_tr_base = value;
788 break;
789 case HOST_GDTR_BASE:
790 current_evmcs->host_gdtr_base = value;
791 break;
792 case HOST_IDTR_BASE:
793 current_evmcs->host_idtr_base = value;
794 break;
795 case HOST_RSP:
796 current_evmcs->host_rsp = value;
797 break;
798 case EPT_POINTER:
799 current_evmcs->ept_pointer = value;
800 break;
801 case GUEST_BNDCFGS:
802 current_evmcs->guest_bndcfgs = value;
803 break;
804 case XSS_EXIT_BITMAP:
805 current_evmcs->xss_exit_bitmap = value;
806 break;
807 case GUEST_PHYSICAL_ADDRESS:
808 current_evmcs->guest_physical_address = value;
809 break;
810 case EXIT_QUALIFICATION:
811 current_evmcs->exit_qualification = value;
812 break;
813 case GUEST_LINEAR_ADDRESS:
814 current_evmcs->guest_linear_address = value;
815 break;
816 case VM_EXIT_MSR_STORE_ADDR:
817 current_evmcs->vm_exit_msr_store_addr = value;
818 break;
819 case VM_EXIT_MSR_LOAD_ADDR:
820 current_evmcs->vm_exit_msr_load_addr = value;
821 break;
822 case VM_ENTRY_MSR_LOAD_ADDR:
823 current_evmcs->vm_entry_msr_load_addr = value;
824 break;
825 case CR3_TARGET_VALUE0:
826 current_evmcs->cr3_target_value0 = value;
827 break;
828 case CR3_TARGET_VALUE1:
829 current_evmcs->cr3_target_value1 = value;
830 break;
831 case CR3_TARGET_VALUE2:
832 current_evmcs->cr3_target_value2 = value;
833 break;
834 case CR3_TARGET_VALUE3:
835 current_evmcs->cr3_target_value3 = value;
836 break;
837 case TPR_THRESHOLD:
838 current_evmcs->tpr_threshold = value;
839 break;
840 case GUEST_INTERRUPTIBILITY_INFO:
841 current_evmcs->guest_interruptibility_info = value;
842 break;
843 case CPU_BASED_VM_EXEC_CONTROL:
844 current_evmcs->cpu_based_vm_exec_control = value;
845 break;
846 case EXCEPTION_BITMAP:
847 current_evmcs->exception_bitmap = value;
848 break;
849 case VM_ENTRY_CONTROLS:
850 current_evmcs->vm_entry_controls = value;
851 break;
852 case VM_ENTRY_INTR_INFO_FIELD:
853 current_evmcs->vm_entry_intr_info_field = value;
854 break;
855 case VM_ENTRY_EXCEPTION_ERROR_CODE:
856 current_evmcs->vm_entry_exception_error_code = value;
857 break;
858 case VM_ENTRY_INSTRUCTION_LEN:
859 current_evmcs->vm_entry_instruction_len = value;
860 break;
861 case HOST_IA32_SYSENTER_CS:
862 current_evmcs->host_ia32_sysenter_cs = value;
863 break;
864 case PIN_BASED_VM_EXEC_CONTROL:
865 current_evmcs->pin_based_vm_exec_control = value;
866 break;
867 case VM_EXIT_CONTROLS:
868 current_evmcs->vm_exit_controls = value;
869 break;
870 case SECONDARY_VM_EXEC_CONTROL:
871 current_evmcs->secondary_vm_exec_control = value;
872 break;
873 case GUEST_ES_LIMIT:
874 current_evmcs->guest_es_limit = value;
875 break;
876 case GUEST_CS_LIMIT:
877 current_evmcs->guest_cs_limit = value;
878 break;
879 case GUEST_SS_LIMIT:
880 current_evmcs->guest_ss_limit = value;
881 break;
882 case GUEST_DS_LIMIT:
883 current_evmcs->guest_ds_limit = value;
884 break;
885 case GUEST_FS_LIMIT:
886 current_evmcs->guest_fs_limit = value;
887 break;
888 case GUEST_GS_LIMIT:
889 current_evmcs->guest_gs_limit = value;
890 break;
891 case GUEST_LDTR_LIMIT:
892 current_evmcs->guest_ldtr_limit = value;
893 break;
894 case GUEST_TR_LIMIT:
895 current_evmcs->guest_tr_limit = value;
896 break;
897 case GUEST_GDTR_LIMIT:
898 current_evmcs->guest_gdtr_limit = value;
899 break;
900 case GUEST_IDTR_LIMIT:
901 current_evmcs->guest_idtr_limit = value;
902 break;
903 case GUEST_ES_AR_BYTES:
904 current_evmcs->guest_es_ar_bytes = value;
905 break;
906 case GUEST_CS_AR_BYTES:
907 current_evmcs->guest_cs_ar_bytes = value;
908 break;
909 case GUEST_SS_AR_BYTES:
910 current_evmcs->guest_ss_ar_bytes = value;
911 break;
912 case GUEST_DS_AR_BYTES:
913 current_evmcs->guest_ds_ar_bytes = value;
914 break;
915 case GUEST_FS_AR_BYTES:
916 current_evmcs->guest_fs_ar_bytes = value;
917 break;
918 case GUEST_GS_AR_BYTES:
919 current_evmcs->guest_gs_ar_bytes = value;
920 break;
921 case GUEST_LDTR_AR_BYTES:
922 current_evmcs->guest_ldtr_ar_bytes = value;
923 break;
924 case GUEST_TR_AR_BYTES:
925 current_evmcs->guest_tr_ar_bytes = value;
926 break;
927 case GUEST_ACTIVITY_STATE:
928 current_evmcs->guest_activity_state = value;
929 break;
930 case GUEST_SYSENTER_CS:
931 current_evmcs->guest_sysenter_cs = value;
932 break;
933 case VM_INSTRUCTION_ERROR:
934 current_evmcs->vm_instruction_error = value;
935 break;
936 case VM_EXIT_REASON:
937 current_evmcs->vm_exit_reason = value;
938 break;
939 case VM_EXIT_INTR_INFO:
940 current_evmcs->vm_exit_intr_info = value;
941 break;
942 case VM_EXIT_INTR_ERROR_CODE:
943 current_evmcs->vm_exit_intr_error_code = value;
944 break;
945 case IDT_VECTORING_INFO_FIELD:
946 current_evmcs->idt_vectoring_info_field = value;
947 break;
948 case IDT_VECTORING_ERROR_CODE:
949 current_evmcs->idt_vectoring_error_code = value;
950 break;
951 case VM_EXIT_INSTRUCTION_LEN:
952 current_evmcs->vm_exit_instruction_len = value;
953 break;
954 case VMX_INSTRUCTION_INFO:
955 current_evmcs->vmx_instruction_info = value;
956 break;
957 case PAGE_FAULT_ERROR_CODE_MASK:
958 current_evmcs->page_fault_error_code_mask = value;
959 break;
960 case PAGE_FAULT_ERROR_CODE_MATCH:
961 current_evmcs->page_fault_error_code_match = value;
962 break;
963 case CR3_TARGET_COUNT:
964 current_evmcs->cr3_target_count = value;
965 break;
966 case VM_EXIT_MSR_STORE_COUNT:
967 current_evmcs->vm_exit_msr_store_count = value;
968 break;
969 case VM_EXIT_MSR_LOAD_COUNT:
970 current_evmcs->vm_exit_msr_load_count = value;
971 break;
972 case VM_ENTRY_MSR_LOAD_COUNT:
973 current_evmcs->vm_entry_msr_load_count = value;
974 break;
975 case HOST_ES_SELECTOR:
976 current_evmcs->host_es_selector = value;
977 break;
978 case HOST_CS_SELECTOR:
979 current_evmcs->host_cs_selector = value;
980 break;
981 case HOST_SS_SELECTOR:
982 current_evmcs->host_ss_selector = value;
983 break;
984 case HOST_DS_SELECTOR:
985 current_evmcs->host_ds_selector = value;
986 break;
987 case HOST_FS_SELECTOR:
988 current_evmcs->host_fs_selector = value;
989 break;
990 case HOST_GS_SELECTOR:
991 current_evmcs->host_gs_selector = value;
992 break;
993 case HOST_TR_SELECTOR:
994 current_evmcs->host_tr_selector = value;
995 break;
996 case GUEST_ES_SELECTOR:
997 current_evmcs->guest_es_selector = value;
998 break;
999 case GUEST_CS_SELECTOR:
1000 current_evmcs->guest_cs_selector = value;
1001 break;
1002 case GUEST_SS_SELECTOR:
1003 current_evmcs->guest_ss_selector = value;
1004 break;
1005 case GUEST_DS_SELECTOR:
1006 current_evmcs->guest_ds_selector = value;
1007 break;
1008 case GUEST_FS_SELECTOR:
1009 current_evmcs->guest_fs_selector = value;
1010 break;
1011 case GUEST_GS_SELECTOR:
1012 current_evmcs->guest_gs_selector = value;
1013 break;
1014 case GUEST_LDTR_SELECTOR:
1015 current_evmcs->guest_ldtr_selector = value;
1016 break;
1017 case GUEST_TR_SELECTOR:
1018 current_evmcs->guest_tr_selector = value;
1019 break;
1020 case VIRTUAL_PROCESSOR_ID:
1021 current_evmcs->virtual_processor_id = value;
1022 break;
1023 default: return 1;
1024 }
1025
1026 return 0;
1027}
1028
1029static inline int evmcs_vmlaunch(void)
1030{
1031 int ret;
1032
1033 current_evmcs->hv_clean_fields = 0;
1034
1035 __asm__ __volatile__("push %%rbp;"
1036 "push %%rcx;"
1037 "push %%rdx;"
1038 "push %%rsi;"
1039 "push %%rdi;"
1040 "push $0;"
1041 "mov %%rsp, (%[host_rsp]);"
1042 "lea 1f(%%rip), %%rax;"
1043 "mov %%rax, (%[host_rip]);"
1044 "vmlaunch;"
1045 "incq (%%rsp);"
1046 "1: pop %%rax;"
1047 "pop %%rdi;"
1048 "pop %%rsi;"
1049 "pop %%rdx;"
1050 "pop %%rcx;"
1051 "pop %%rbp;"
1052 : [ret]"=&a"(ret)
1053 : [host_rsp]"r"
1054 ((uint64_t)&current_evmcs->host_rsp),
1055 [host_rip]"r"
1056 ((uint64_t)&current_evmcs->host_rip)
1057 : "memory", "cc", "rbx", "r8", "r9", "r10",
1058 "r11", "r12", "r13", "r14", "r15");
1059 return ret;
1060}
1061
1062/*
1063 * No guest state (e.g. GPRs) is established by this vmresume.
1064 */
1065static inline int evmcs_vmresume(void)
1066{
1067 int ret;
1068
1069 current_evmcs->hv_clean_fields = 0;
1070
1071 __asm__ __volatile__("push %%rbp;"
1072 "push %%rcx;"
1073 "push %%rdx;"
1074 "push %%rsi;"
1075 "push %%rdi;"
1076 "push $0;"
1077 "mov %%rsp, (%[host_rsp]);"
1078 "lea 1f(%%rip), %%rax;"
1079 "mov %%rax, (%[host_rip]);"
1080 "vmresume;"
1081 "incq (%%rsp);"
1082 "1: pop %%rax;"
1083 "pop %%rdi;"
1084 "pop %%rsi;"
1085 "pop %%rdx;"
1086 "pop %%rcx;"
1087 "pop %%rbp;"
1088 : [ret]"=&a"(ret)
1089 : [host_rsp]"r"
1090 ((uint64_t)&current_evmcs->host_rsp),
1091 [host_rip]"r"
1092 ((uint64_t)&current_evmcs->host_rip)
1093 : "memory", "cc", "rbx", "r8", "r9", "r10",
1094 "r11", "r12", "r13", "r14", "r15");
1095 return ret;
1096}
1097
1098#endif /* !SELFTEST_KVM_EVMCS_H */
diff --git a/tools/testing/selftests/kvm/include/kvm_util.h b/tools/testing/selftests/kvm/include/kvm_util.h
index 3acf9a91704c..a4e59e3b4826 100644
--- a/tools/testing/selftests/kvm/include/kvm_util.h
+++ b/tools/testing/selftests/kvm/include/kvm_util.h
@@ -7,7 +7,7 @@
7 * 7 *
8 */ 8 */
9#ifndef SELFTEST_KVM_UTIL_H 9#ifndef SELFTEST_KVM_UTIL_H
10#define SELFTEST_KVM_UTIL_H 1 10#define SELFTEST_KVM_UTIL_H
11 11
12#include "test_util.h" 12#include "test_util.h"
13 13
@@ -17,12 +17,6 @@
17 17
18#include "sparsebit.h" 18#include "sparsebit.h"
19 19
20/*
21 * Memslots can't cover the gfn starting at this gpa otherwise vCPUs can't be
22 * created. Only applies to VMs using EPT.
23 */
24#define KVM_DEFAULT_IDENTITY_MAP_ADDRESS 0xfffbc000ul
25
26 20
27/* Callers of kvm_util only have an incomplete/opaque description of the 21/* Callers of kvm_util only have an incomplete/opaque description of the
28 * structure kvm_util is using to maintain the state of a VM. 22 * structure kvm_util is using to maintain the state of a VM.
@@ -33,16 +27,23 @@ typedef uint64_t vm_paddr_t; /* Virtual Machine (Guest) physical address */
33typedef uint64_t vm_vaddr_t; /* Virtual Machine (Guest) virtual address */ 27typedef uint64_t vm_vaddr_t; /* Virtual Machine (Guest) virtual address */
34 28
35/* Minimum allocated guest virtual and physical addresses */ 29/* Minimum allocated guest virtual and physical addresses */
36#define KVM_UTIL_MIN_VADDR 0x2000 30#define KVM_UTIL_MIN_VADDR 0x2000
37 31
38#define DEFAULT_GUEST_PHY_PAGES 512 32#define DEFAULT_GUEST_PHY_PAGES 512
39#define DEFAULT_GUEST_STACK_VADDR_MIN 0xab6000 33#define DEFAULT_GUEST_STACK_VADDR_MIN 0xab6000
40#define DEFAULT_STACK_PGS 5 34#define DEFAULT_STACK_PGS 5
41 35
42enum vm_guest_mode { 36enum vm_guest_mode {
43 VM_MODE_FLAT48PG, 37 VM_MODE_P52V48_4K,
38 VM_MODE_P52V48_64K,
39 VM_MODE_P40V48_4K,
40 VM_MODE_P40V48_64K,
41 NUM_VM_MODES,
44}; 42};
45 43
44#define vm_guest_mode_string(m) vm_guest_mode_string[m]
45extern const char * const vm_guest_mode_string[];
46
46enum vm_mem_backing_src_type { 47enum vm_mem_backing_src_type {
47 VM_MEM_SRC_ANONYMOUS, 48 VM_MEM_SRC_ANONYMOUS,
48 VM_MEM_SRC_ANONYMOUS_THP, 49 VM_MEM_SRC_ANONYMOUS_THP,
@@ -58,15 +59,15 @@ void kvm_vm_restart(struct kvm_vm *vmp, int perm);
58void kvm_vm_release(struct kvm_vm *vmp); 59void kvm_vm_release(struct kvm_vm *vmp);
59void kvm_vm_get_dirty_log(struct kvm_vm *vm, int slot, void *log); 60void kvm_vm_get_dirty_log(struct kvm_vm *vm, int slot, void *log);
60 61
61int kvm_memcmp_hva_gva(void *hva, 62int kvm_memcmp_hva_gva(void *hva, struct kvm_vm *vm, const vm_vaddr_t gva,
62 struct kvm_vm *vm, const vm_vaddr_t gva, size_t len); 63 size_t len);
63 64
64void kvm_vm_elf_load(struct kvm_vm *vm, const char *filename, 65void kvm_vm_elf_load(struct kvm_vm *vm, const char *filename,
65 uint32_t data_memslot, uint32_t pgd_memslot); 66 uint32_t data_memslot, uint32_t pgd_memslot);
66 67
67void vm_dump(FILE *stream, struct kvm_vm *vm, uint8_t indent); 68void vm_dump(FILE *stream, struct kvm_vm *vm, uint8_t indent);
68void vcpu_dump(FILE *stream, struct kvm_vm *vm, 69void vcpu_dump(FILE *stream, struct kvm_vm *vm, uint32_t vcpuid,
69 uint32_t vcpuid, uint8_t indent); 70 uint8_t indent);
70 71
71void vm_create_irqchip(struct kvm_vm *vm); 72void vm_create_irqchip(struct kvm_vm *vm);
72 73
@@ -75,13 +76,14 @@ void vm_userspace_mem_region_add(struct kvm_vm *vm,
75 uint64_t guest_paddr, uint32_t slot, uint64_t npages, 76 uint64_t guest_paddr, uint32_t slot, uint64_t npages,
76 uint32_t flags); 77 uint32_t flags);
77 78
78void vcpu_ioctl(struct kvm_vm *vm, 79void vcpu_ioctl(struct kvm_vm *vm, uint32_t vcpuid, unsigned long ioctl,
79 uint32_t vcpuid, unsigned long ioctl, void *arg); 80 void *arg);
80void vm_ioctl(struct kvm_vm *vm, unsigned long ioctl, void *arg); 81void vm_ioctl(struct kvm_vm *vm, unsigned long ioctl, void *arg);
81void vm_mem_region_set_flags(struct kvm_vm *vm, uint32_t slot, uint32_t flags); 82void vm_mem_region_set_flags(struct kvm_vm *vm, uint32_t slot, uint32_t flags);
82void vm_vcpu_add(struct kvm_vm *vm, uint32_t vcpuid, int pgd_memslot, int gdt_memslot); 83void vm_vcpu_add(struct kvm_vm *vm, uint32_t vcpuid, int pgd_memslot,
84 int gdt_memslot);
83vm_vaddr_t vm_vaddr_alloc(struct kvm_vm *vm, size_t sz, vm_vaddr_t vaddr_min, 85vm_vaddr_t vm_vaddr_alloc(struct kvm_vm *vm, size_t sz, vm_vaddr_t vaddr_min,
84 uint32_t data_memslot, uint32_t pgd_memslot); 86 uint32_t data_memslot, uint32_t pgd_memslot);
85void virt_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr, 87void virt_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr,
86 size_t size, uint32_t pgd_memslot); 88 size_t size, uint32_t pgd_memslot);
87void *addr_gpa2hva(struct kvm_vm *vm, vm_paddr_t gpa); 89void *addr_gpa2hva(struct kvm_vm *vm, vm_paddr_t gpa);
@@ -93,56 +95,35 @@ struct kvm_run *vcpu_state(struct kvm_vm *vm, uint32_t vcpuid);
93void vcpu_run(struct kvm_vm *vm, uint32_t vcpuid); 95void vcpu_run(struct kvm_vm *vm, uint32_t vcpuid);
94int _vcpu_run(struct kvm_vm *vm, uint32_t vcpuid); 96int _vcpu_run(struct kvm_vm *vm, uint32_t vcpuid);
95void vcpu_set_mp_state(struct kvm_vm *vm, uint32_t vcpuid, 97void vcpu_set_mp_state(struct kvm_vm *vm, uint32_t vcpuid,
96 struct kvm_mp_state *mp_state); 98 struct kvm_mp_state *mp_state);
97void vcpu_regs_get(struct kvm_vm *vm, 99void vcpu_regs_get(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_regs *regs);
98 uint32_t vcpuid, struct kvm_regs *regs); 100void vcpu_regs_set(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_regs *regs);
99void vcpu_regs_set(struct kvm_vm *vm,
100 uint32_t vcpuid, struct kvm_regs *regs);
101void vcpu_args_set(struct kvm_vm *vm, uint32_t vcpuid, unsigned int num, ...); 101void vcpu_args_set(struct kvm_vm *vm, uint32_t vcpuid, unsigned int num, ...);
102void vcpu_sregs_get(struct kvm_vm *vm, 102void vcpu_sregs_get(struct kvm_vm *vm, uint32_t vcpuid,
103 uint32_t vcpuid, struct kvm_sregs *sregs); 103 struct kvm_sregs *sregs);
104void vcpu_sregs_set(struct kvm_vm *vm, 104void vcpu_sregs_set(struct kvm_vm *vm, uint32_t vcpuid,
105 uint32_t vcpuid, struct kvm_sregs *sregs); 105 struct kvm_sregs *sregs);
106int _vcpu_sregs_set(struct kvm_vm *vm, 106int _vcpu_sregs_set(struct kvm_vm *vm, uint32_t vcpuid,
107 uint32_t vcpuid, struct kvm_sregs *sregs); 107 struct kvm_sregs *sregs);
108void vcpu_events_get(struct kvm_vm *vm, uint32_t vcpuid, 108void vcpu_events_get(struct kvm_vm *vm, uint32_t vcpuid,
109 struct kvm_vcpu_events *events); 109 struct kvm_vcpu_events *events);
110void vcpu_events_set(struct kvm_vm *vm, uint32_t vcpuid, 110void vcpu_events_set(struct kvm_vm *vm, uint32_t vcpuid,
111 struct kvm_vcpu_events *events); 111 struct kvm_vcpu_events *events);
112uint64_t vcpu_get_msr(struct kvm_vm *vm, uint32_t vcpuid, uint64_t msr_index);
113void vcpu_set_msr(struct kvm_vm *vm, uint32_t vcpuid, uint64_t msr_index,
114 uint64_t msr_value);
115 112
116const char *exit_reason_str(unsigned int exit_reason); 113const char *exit_reason_str(unsigned int exit_reason);
117 114
118void virt_pgd_alloc(struct kvm_vm *vm, uint32_t pgd_memslot); 115void virt_pgd_alloc(struct kvm_vm *vm, uint32_t pgd_memslot);
119void virt_pg_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr, 116void virt_pg_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr,
120 uint32_t pgd_memslot); 117 uint32_t pgd_memslot);
121vm_paddr_t vm_phy_page_alloc(struct kvm_vm *vm, 118vm_paddr_t vm_phy_page_alloc(struct kvm_vm *vm, vm_paddr_t paddr_min,
122 vm_paddr_t paddr_min, uint32_t memslot); 119 uint32_t memslot);
123 120vm_paddr_t vm_phy_pages_alloc(struct kvm_vm *vm, size_t num,
124struct kvm_cpuid2 *kvm_get_supported_cpuid(void); 121 vm_paddr_t paddr_min, uint32_t memslot);
125void vcpu_set_cpuid(
126 struct kvm_vm *vm, uint32_t vcpuid, struct kvm_cpuid2 *cpuid);
127
128struct kvm_cpuid_entry2 *
129kvm_get_supported_cpuid_index(uint32_t function, uint32_t index);
130
131static inline struct kvm_cpuid_entry2 *
132kvm_get_supported_cpuid_entry(uint32_t function)
133{
134 return kvm_get_supported_cpuid_index(function, 0);
135}
136 122
137struct kvm_vm *vm_create_default(uint32_t vcpuid, uint64_t extra_mem_size, 123struct kvm_vm *vm_create_default(uint32_t vcpuid, uint64_t extra_mem_size,
138 void *guest_code); 124 void *guest_code);
139void vm_vcpu_add_default(struct kvm_vm *vm, uint32_t vcpuid, void *guest_code); 125void vm_vcpu_add_default(struct kvm_vm *vm, uint32_t vcpuid, void *guest_code);
140 126
141typedef void (*vmx_guest_code_t)(vm_vaddr_t vmxon_vaddr,
142 vm_paddr_t vmxon_paddr,
143 vm_vaddr_t vmcs_vaddr,
144 vm_paddr_t vmcs_paddr);
145
146struct kvm_userspace_memory_region * 127struct kvm_userspace_memory_region *
147kvm_userspace_memory_region_find(struct kvm_vm *vm, uint64_t start, 128kvm_userspace_memory_region_find(struct kvm_vm *vm, uint64_t start,
148 uint64_t end); 129 uint64_t end);
@@ -152,43 +133,49 @@ allocate_kvm_dirty_log(struct kvm_userspace_memory_region *region);
152 133
153int vm_create_device(struct kvm_vm *vm, struct kvm_create_device *cd); 134int vm_create_device(struct kvm_vm *vm, struct kvm_create_device *cd);
154 135
155#define GUEST_PORT_SYNC 0x1000 136#define sync_global_to_guest(vm, g) ({ \
156#define GUEST_PORT_ABORT 0x1001 137 typeof(g) *_p = addr_gva2hva(vm, (vm_vaddr_t)&(g)); \
157#define GUEST_PORT_DONE 0x1002 138 memcpy(_p, &(g), sizeof(g)); \
158 139})
159static inline void __exit_to_l0(uint16_t port, uint64_t arg0, uint64_t arg1) 140
160{ 141#define sync_global_from_guest(vm, g) ({ \
161 __asm__ __volatile__("in %[port], %%al" 142 typeof(g) *_p = addr_gva2hva(vm, (vm_vaddr_t)&(g)); \
162 : 143 memcpy(&(g), _p, sizeof(g)); \
163 : [port]"d"(port), "D"(arg0), "S"(arg1) 144})
164 : "rax"); 145
165} 146/* ucall implementation types */
166 147typedef enum {
167/* 148 UCALL_PIO,
168 * Allows to pass three arguments to the host: port is 16bit wide, 149 UCALL_MMIO,
169 * arg0 & arg1 are 64bit wide 150} ucall_type_t;
170 */ 151
171#define GUEST_SYNC_ARGS(_port, _arg0, _arg1) \ 152/* Common ucalls */
172 __exit_to_l0(_port, (uint64_t) (_arg0), (uint64_t) (_arg1)) 153enum {
173 154 UCALL_NONE,
174#define GUEST_ASSERT(_condition) do { \ 155 UCALL_SYNC,
175 if (!(_condition)) \ 156 UCALL_ABORT,
176 GUEST_SYNC_ARGS(GUEST_PORT_ABORT, \ 157 UCALL_DONE,
177 "Failed guest assert: " \ 158};
178 #_condition, __LINE__); \
179 } while (0)
180
181#define GUEST_SYNC(stage) GUEST_SYNC_ARGS(GUEST_PORT_SYNC, "hello", stage)
182 159
183#define GUEST_DONE() GUEST_SYNC_ARGS(GUEST_PORT_DONE, 0, 0) 160#define UCALL_MAX_ARGS 6
184 161
185struct guest_args { 162struct ucall {
186 uint64_t arg0; 163 uint64_t cmd;
187 uint64_t arg1; 164 uint64_t args[UCALL_MAX_ARGS];
188 uint16_t port; 165};
189} __attribute__ ((packed));
190 166
191void guest_args_read(struct kvm_vm *vm, uint32_t vcpu_id, 167void ucall_init(struct kvm_vm *vm, ucall_type_t type, void *arg);
192 struct guest_args *args); 168void ucall_uninit(struct kvm_vm *vm);
169void ucall(uint64_t cmd, int nargs, ...);
170uint64_t get_ucall(struct kvm_vm *vm, uint32_t vcpu_id, struct ucall *uc);
171
172#define GUEST_SYNC(stage) ucall(UCALL_SYNC, 2, "hello", stage)
173#define GUEST_DONE() ucall(UCALL_DONE, 0)
174#define GUEST_ASSERT(_condition) do { \
175 if (!(_condition)) \
176 ucall(UCALL_ABORT, 2, \
177 "Failed guest assert: " \
178 #_condition, __LINE__); \
179} while (0)
193 180
194#endif /* SELFTEST_KVM_UTIL_H */ 181#endif /* SELFTEST_KVM_UTIL_H */
diff --git a/tools/testing/selftests/kvm/include/sparsebit.h b/tools/testing/selftests/kvm/include/sparsebit.h
index 54cfeb6568d3..31e030915c1f 100644
--- a/tools/testing/selftests/kvm/include/sparsebit.h
+++ b/tools/testing/selftests/kvm/include/sparsebit.h
@@ -15,8 +15,8 @@
15 * even in the case where most bits are set. 15 * even in the case where most bits are set.
16 */ 16 */
17 17
18#ifndef _TEST_SPARSEBIT_H_ 18#ifndef SELFTEST_KVM_SPARSEBIT_H
19#define _TEST_SPARSEBIT_H_ 19#define SELFTEST_KVM_SPARSEBIT_H
20 20
21#include <stdbool.h> 21#include <stdbool.h>
22#include <stdint.h> 22#include <stdint.h>
@@ -72,4 +72,4 @@ void sparsebit_validate_internal(struct sparsebit *sbit);
72} 72}
73#endif 73#endif
74 74
75#endif /* _TEST_SPARSEBIT_H_ */ 75#endif /* SELFTEST_KVM_SPARSEBIT_H */
diff --git a/tools/testing/selftests/kvm/include/test_util.h b/tools/testing/selftests/kvm/include/test_util.h
index 73c3933436ec..c7dafe8bd02c 100644
--- a/tools/testing/selftests/kvm/include/test_util.h
+++ b/tools/testing/selftests/kvm/include/test_util.h
@@ -7,8 +7,8 @@
7 * 7 *
8 */ 8 */
9 9
10#ifndef TEST_UTIL_H 10#ifndef SELFTEST_KVM_TEST_UTIL_H
11#define TEST_UTIL_H 1 11#define SELFTEST_KVM_TEST_UTIL_H
12 12
13#include <stdlib.h> 13#include <stdlib.h>
14#include <stdarg.h> 14#include <stdarg.h>
@@ -41,4 +41,4 @@ void test_assert(bool exp, const char *exp_str,
41 #a, #b, #a, (unsigned long) __a, #b, (unsigned long) __b); \ 41 #a, #b, #a, (unsigned long) __a, #b, (unsigned long) __b); \
42} while (0) 42} while (0)
43 43
44#endif /* TEST_UTIL_H */ 44#endif /* SELFTEST_KVM_TEST_UTIL_H */
diff --git a/tools/testing/selftests/kvm/include/x86.h b/tools/testing/selftests/kvm/include/x86_64/processor.h
index 42c3596815b8..e2884c2b81ff 100644
--- a/tools/testing/selftests/kvm/include/x86.h
+++ b/tools/testing/selftests/kvm/include/x86_64/processor.h
@@ -1,5 +1,5 @@
1/* 1/*
2 * tools/testing/selftests/kvm/include/x86.h 2 * tools/testing/selftests/kvm/include/x86_64/processor.h
3 * 3 *
4 * Copyright (C) 2018, Google LLC. 4 * Copyright (C) 2018, Google LLC.
5 * 5 *
@@ -7,8 +7,8 @@
7 * 7 *
8 */ 8 */
9 9
10#ifndef SELFTEST_KVM_X86_H 10#ifndef SELFTEST_KVM_PROCESSOR_H
11#define SELFTEST_KVM_X86_H 11#define SELFTEST_KVM_PROCESSOR_H
12 12
13#include <assert.h> 13#include <assert.h>
14#include <stdint.h> 14#include <stdint.h>
@@ -305,7 +305,25 @@ static inline unsigned long get_xmm(int n)
305 305
306struct kvm_x86_state; 306struct kvm_x86_state;
307struct kvm_x86_state *vcpu_save_state(struct kvm_vm *vm, uint32_t vcpuid); 307struct kvm_x86_state *vcpu_save_state(struct kvm_vm *vm, uint32_t vcpuid);
308void vcpu_load_state(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_x86_state *state); 308void vcpu_load_state(struct kvm_vm *vm, uint32_t vcpuid,
309 struct kvm_x86_state *state);
310
311struct kvm_cpuid2 *kvm_get_supported_cpuid(void);
312void vcpu_set_cpuid(struct kvm_vm *vm, uint32_t vcpuid,
313 struct kvm_cpuid2 *cpuid);
314
315struct kvm_cpuid_entry2 *
316kvm_get_supported_cpuid_index(uint32_t function, uint32_t index);
317
318static inline struct kvm_cpuid_entry2 *
319kvm_get_supported_cpuid_entry(uint32_t function)
320{
321 return kvm_get_supported_cpuid_index(function, 0);
322}
323
324uint64_t vcpu_get_msr(struct kvm_vm *vm, uint32_t vcpuid, uint64_t msr_index);
325void vcpu_set_msr(struct kvm_vm *vm, uint32_t vcpuid, uint64_t msr_index,
326 uint64_t msr_value);
309 327
310/* 328/*
311 * Basic CPU control in CR0 329 * Basic CPU control in CR0
@@ -1044,4 +1062,4 @@ void vcpu_load_state(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_x86_state *s
1044#define MSR_VM_IGNNE 0xc0010115 1062#define MSR_VM_IGNNE 0xc0010115
1045#define MSR_VM_HSAVE_PA 0xc0010117 1063#define MSR_VM_HSAVE_PA 0xc0010117
1046 1064
1047#endif /* !SELFTEST_KVM_X86_H */ 1065#endif /* SELFTEST_KVM_PROCESSOR_H */
diff --git a/tools/testing/selftests/kvm/include/vmx.h b/tools/testing/selftests/kvm/include/x86_64/vmx.h
index b9ffe1024d3a..c9bd935b939c 100644
--- a/tools/testing/selftests/kvm/include/vmx.h
+++ b/tools/testing/selftests/kvm/include/x86_64/vmx.h
@@ -1,5 +1,5 @@
1/* 1/*
2 * tools/testing/selftests/kvm/include/vmx.h 2 * tools/testing/selftests/kvm/include/x86_64/vmx.h
3 * 3 *
4 * Copyright (C) 2018, Google LLC. 4 * Copyright (C) 2018, Google LLC.
5 * 5 *
@@ -11,7 +11,7 @@
11#define SELFTEST_KVM_VMX_H 11#define SELFTEST_KVM_VMX_H
12 12
13#include <stdint.h> 13#include <stdint.h>
14#include "x86.h" 14#include "processor.h"
15 15
16#define CPUID_VMX_BIT 5 16#define CPUID_VMX_BIT 5
17 17
@@ -339,6 +339,8 @@ struct vmx_msr_entry {
339 uint64_t value; 339 uint64_t value;
340} __attribute__ ((aligned(16))); 340} __attribute__ ((aligned(16)));
341 341
342#include "evmcs.h"
343
342static inline int vmxon(uint64_t phys) 344static inline int vmxon(uint64_t phys)
343{ 345{
344 uint8_t ret; 346 uint8_t ret;
@@ -372,6 +374,9 @@ static inline int vmptrld(uint64_t vmcs_pa)
372{ 374{
373 uint8_t ret; 375 uint8_t ret;
374 376
377 if (enable_evmcs)
378 return -1;
379
375 __asm__ __volatile__ ("vmptrld %[pa]; setna %[ret]" 380 __asm__ __volatile__ ("vmptrld %[pa]; setna %[ret]"
376 : [ret]"=rm"(ret) 381 : [ret]"=rm"(ret)
377 : [pa]"m"(vmcs_pa) 382 : [pa]"m"(vmcs_pa)
@@ -385,6 +390,9 @@ static inline int vmptrst(uint64_t *value)
385 uint64_t tmp; 390 uint64_t tmp;
386 uint8_t ret; 391 uint8_t ret;
387 392
393 if (enable_evmcs)
394 return evmcs_vmptrst(value);
395
388 __asm__ __volatile__("vmptrst %[value]; setna %[ret]" 396 __asm__ __volatile__("vmptrst %[value]; setna %[ret]"
389 : [value]"=m"(tmp), [ret]"=rm"(ret) 397 : [value]"=m"(tmp), [ret]"=rm"(ret)
390 : : "cc", "memory"); 398 : : "cc", "memory");
@@ -411,6 +419,9 @@ static inline int vmlaunch(void)
411{ 419{
412 int ret; 420 int ret;
413 421
422 if (enable_evmcs)
423 return evmcs_vmlaunch();
424
414 __asm__ __volatile__("push %%rbp;" 425 __asm__ __volatile__("push %%rbp;"
415 "push %%rcx;" 426 "push %%rcx;"
416 "push %%rdx;" 427 "push %%rdx;"
@@ -443,6 +454,9 @@ static inline int vmresume(void)
443{ 454{
444 int ret; 455 int ret;
445 456
457 if (enable_evmcs)
458 return evmcs_vmresume();
459
446 __asm__ __volatile__("push %%rbp;" 460 __asm__ __volatile__("push %%rbp;"
447 "push %%rcx;" 461 "push %%rcx;"
448 "push %%rdx;" 462 "push %%rdx;"
@@ -482,6 +496,9 @@ static inline int vmread(uint64_t encoding, uint64_t *value)
482 uint64_t tmp; 496 uint64_t tmp;
483 uint8_t ret; 497 uint8_t ret;
484 498
499 if (enable_evmcs)
500 return evmcs_vmread(encoding, value);
501
485 __asm__ __volatile__("vmread %[encoding], %[value]; setna %[ret]" 502 __asm__ __volatile__("vmread %[encoding], %[value]; setna %[ret]"
486 : [value]"=rm"(tmp), [ret]"=rm"(ret) 503 : [value]"=rm"(tmp), [ret]"=rm"(ret)
487 : [encoding]"r"(encoding) 504 : [encoding]"r"(encoding)
@@ -506,6 +523,9 @@ static inline int vmwrite(uint64_t encoding, uint64_t value)
506{ 523{
507 uint8_t ret; 524 uint8_t ret;
508 525
526 if (enable_evmcs)
527 return evmcs_vmwrite(encoding, value);
528
509 __asm__ __volatile__ ("vmwrite %[value], %[encoding]; setna %[ret]" 529 __asm__ __volatile__ ("vmwrite %[value], %[encoding]; setna %[ret]"
510 : [ret]"=rm"(ret) 530 : [ret]"=rm"(ret)
511 : [value]"rm"(value), [encoding]"r"(encoding) 531 : [value]"rm"(value), [encoding]"r"(encoding)
@@ -543,10 +563,19 @@ struct vmx_pages {
543 void *vmwrite_hva; 563 void *vmwrite_hva;
544 uint64_t vmwrite_gpa; 564 uint64_t vmwrite_gpa;
545 void *vmwrite; 565 void *vmwrite;
566
567 void *vp_assist_hva;
568 uint64_t vp_assist_gpa;
569 void *vp_assist;
570
571 void *enlightened_vmcs_hva;
572 uint64_t enlightened_vmcs_gpa;
573 void *enlightened_vmcs;
546}; 574};
547 575
548struct vmx_pages *vcpu_alloc_vmx(struct kvm_vm *vm, vm_vaddr_t *p_vmx_gva); 576struct vmx_pages *vcpu_alloc_vmx(struct kvm_vm *vm, vm_vaddr_t *p_vmx_gva);
549bool prepare_for_vmx_operation(struct vmx_pages *vmx); 577bool prepare_for_vmx_operation(struct vmx_pages *vmx);
550void prepare_vmcs(struct vmx_pages *vmx, void *guest_rip, void *guest_rsp); 578void prepare_vmcs(struct vmx_pages *vmx, void *guest_rip, void *guest_rsp);
579bool load_vmcs(struct vmx_pages *vmx);
551 580
552#endif /* !SELFTEST_KVM_VMX_H */ 581#endif /* SELFTEST_KVM_VMX_H */
diff --git a/tools/testing/selftests/kvm/lib/aarch64/processor.c b/tools/testing/selftests/kvm/lib/aarch64/processor.c
new file mode 100644
index 000000000000..b6022e2f116e
--- /dev/null
+++ b/tools/testing/selftests/kvm/lib/aarch64/processor.c
@@ -0,0 +1,311 @@
1// SPDX-License-Identifier: GPL-2.0
2/*
3 * AArch64 code
4 *
5 * Copyright (C) 2018, Red Hat, Inc.
6 */
7
8#define _GNU_SOURCE /* for program_invocation_name */
9
10#include "kvm_util.h"
11#include "../kvm_util_internal.h"
12#include "processor.h"
13
14#define KVM_GUEST_PAGE_TABLE_MIN_PADDR 0x180000
15#define DEFAULT_ARM64_GUEST_STACK_VADDR_MIN 0xac0000
16
17static uint64_t page_align(struct kvm_vm *vm, uint64_t v)
18{
19 return (v + vm->page_size) & ~(vm->page_size - 1);
20}
21
22static uint64_t pgd_index(struct kvm_vm *vm, vm_vaddr_t gva)
23{
24 unsigned int shift = (vm->pgtable_levels - 1) * (vm->page_shift - 3) + vm->page_shift;
25 uint64_t mask = (1UL << (vm->va_bits - shift)) - 1;
26
27 return (gva >> shift) & mask;
28}
29
30static uint64_t pud_index(struct kvm_vm *vm, vm_vaddr_t gva)
31{
32 unsigned int shift = 2 * (vm->page_shift - 3) + vm->page_shift;
33 uint64_t mask = (1UL << (vm->page_shift - 3)) - 1;
34
35 TEST_ASSERT(vm->pgtable_levels == 4,
36 "Mode %d does not have 4 page table levels", vm->mode);
37
38 return (gva >> shift) & mask;
39}
40
41static uint64_t pmd_index(struct kvm_vm *vm, vm_vaddr_t gva)
42{
43 unsigned int shift = (vm->page_shift - 3) + vm->page_shift;
44 uint64_t mask = (1UL << (vm->page_shift - 3)) - 1;
45
46 TEST_ASSERT(vm->pgtable_levels >= 3,
47 "Mode %d does not have >= 3 page table levels", vm->mode);
48
49 return (gva >> shift) & mask;
50}
51
52static uint64_t pte_index(struct kvm_vm *vm, vm_vaddr_t gva)
53{
54 uint64_t mask = (1UL << (vm->page_shift - 3)) - 1;
55 return (gva >> vm->page_shift) & mask;
56}
57
58static uint64_t pte_addr(struct kvm_vm *vm, uint64_t entry)
59{
60 uint64_t mask = ((1UL << (vm->va_bits - vm->page_shift)) - 1) << vm->page_shift;
61 return entry & mask;
62}
63
64static uint64_t ptrs_per_pgd(struct kvm_vm *vm)
65{
66 unsigned int shift = (vm->pgtable_levels - 1) * (vm->page_shift - 3) + vm->page_shift;
67 return 1 << (vm->va_bits - shift);
68}
69
70static uint64_t ptrs_per_pte(struct kvm_vm *vm)
71{
72 return 1 << (vm->page_shift - 3);
73}
74
75void virt_pgd_alloc(struct kvm_vm *vm, uint32_t pgd_memslot)
76{
77 int rc;
78
79 if (!vm->pgd_created) {
80 vm_paddr_t paddr = vm_phy_pages_alloc(vm,
81 page_align(vm, ptrs_per_pgd(vm) * 8) / vm->page_size,
82 KVM_GUEST_PAGE_TABLE_MIN_PADDR, pgd_memslot);
83 vm->pgd = paddr;
84 vm->pgd_created = true;
85 }
86}
87
88void _virt_pg_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr,
89 uint32_t pgd_memslot, uint64_t flags)
90{
91 uint8_t attr_idx = flags & 7;
92 uint64_t *ptep;
93
94 TEST_ASSERT((vaddr % vm->page_size) == 0,
95 "Virtual address not on page boundary,\n"
96 " vaddr: 0x%lx vm->page_size: 0x%x", vaddr, vm->page_size);
97 TEST_ASSERT(sparsebit_is_set(vm->vpages_valid,
98 (vaddr >> vm->page_shift)),
99 "Invalid virtual address, vaddr: 0x%lx", vaddr);
100 TEST_ASSERT((paddr % vm->page_size) == 0,
101 "Physical address not on page boundary,\n"
102 " paddr: 0x%lx vm->page_size: 0x%x", paddr, vm->page_size);
103 TEST_ASSERT((paddr >> vm->page_shift) <= vm->max_gfn,
104 "Physical address beyond beyond maximum supported,\n"
105 " paddr: 0x%lx vm->max_gfn: 0x%lx vm->page_size: 0x%x",
106 paddr, vm->max_gfn, vm->page_size);
107
108 ptep = addr_gpa2hva(vm, vm->pgd) + pgd_index(vm, vaddr) * 8;
109 if (!*ptep) {
110 *ptep = vm_phy_page_alloc(vm, KVM_GUEST_PAGE_TABLE_MIN_PADDR, pgd_memslot);
111 *ptep |= 3;
112 }
113
114 switch (vm->pgtable_levels) {
115 case 4:
116 ptep = addr_gpa2hva(vm, pte_addr(vm, *ptep)) + pud_index(vm, vaddr) * 8;
117 if (!*ptep) {
118 *ptep = vm_phy_page_alloc(vm, KVM_GUEST_PAGE_TABLE_MIN_PADDR, pgd_memslot);
119 *ptep |= 3;
120 }
121 /* fall through */
122 case 3:
123 ptep = addr_gpa2hva(vm, pte_addr(vm, *ptep)) + pmd_index(vm, vaddr) * 8;
124 if (!*ptep) {
125 *ptep = vm_phy_page_alloc(vm, KVM_GUEST_PAGE_TABLE_MIN_PADDR, pgd_memslot);
126 *ptep |= 3;
127 }
128 /* fall through */
129 case 2:
130 ptep = addr_gpa2hva(vm, pte_addr(vm, *ptep)) + pte_index(vm, vaddr) * 8;
131 break;
132 default:
133 TEST_ASSERT(false, "Page table levels must be 2, 3, or 4");
134 }
135
136 *ptep = paddr | 3;
137 *ptep |= (attr_idx << 2) | (1 << 10) /* Access Flag */;
138}
139
140void virt_pg_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr,
141 uint32_t pgd_memslot)
142{
143 uint64_t attr_idx = 4; /* NORMAL (See DEFAULT_MAIR_EL1) */
144
145 _virt_pg_map(vm, vaddr, paddr, pgd_memslot, attr_idx);
146}
147
148vm_paddr_t addr_gva2gpa(struct kvm_vm *vm, vm_vaddr_t gva)
149{
150 uint64_t *ptep;
151
152 if (!vm->pgd_created)
153 goto unmapped_gva;
154
155 ptep = addr_gpa2hva(vm, vm->pgd) + pgd_index(vm, gva) * 8;
156 if (!ptep)
157 goto unmapped_gva;
158
159 switch (vm->pgtable_levels) {
160 case 4:
161 ptep = addr_gpa2hva(vm, pte_addr(vm, *ptep)) + pud_index(vm, gva) * 8;
162 if (!ptep)
163 goto unmapped_gva;
164 /* fall through */
165 case 3:
166 ptep = addr_gpa2hva(vm, pte_addr(vm, *ptep)) + pmd_index(vm, gva) * 8;
167 if (!ptep)
168 goto unmapped_gva;
169 /* fall through */
170 case 2:
171 ptep = addr_gpa2hva(vm, pte_addr(vm, *ptep)) + pte_index(vm, gva) * 8;
172 if (!ptep)
173 goto unmapped_gva;
174 break;
175 default:
176 TEST_ASSERT(false, "Page table levels must be 2, 3, or 4");
177 }
178
179 return pte_addr(vm, *ptep) + (gva & (vm->page_size - 1));
180
181unmapped_gva:
182 TEST_ASSERT(false, "No mapping for vm virtual address, "
183 "gva: 0x%lx", gva);
184}
185
186static void pte_dump(FILE *stream, struct kvm_vm *vm, uint8_t indent, uint64_t page, int level)
187{
188#ifdef DEBUG_VM
189 static const char * const type[] = { "", "pud", "pmd", "pte" };
190 uint64_t pte, *ptep;
191
192 if (level == 4)
193 return;
194
195 for (pte = page; pte < page + ptrs_per_pte(vm) * 8; pte += 8) {
196 ptep = addr_gpa2hva(vm, pte);
197 if (!*ptep)
198 continue;
199 printf("%*s%s: %lx: %lx at %p\n", indent, "", type[level], pte, *ptep, ptep);
200 pte_dump(stream, vm, indent + 1, pte_addr(vm, *ptep), level + 1);
201 }
202#endif
203}
204
205void virt_dump(FILE *stream, struct kvm_vm *vm, uint8_t indent)
206{
207 int level = 4 - (vm->pgtable_levels - 1);
208 uint64_t pgd, *ptep;
209
210 if (!vm->pgd_created)
211 return;
212
213 for (pgd = vm->pgd; pgd < vm->pgd + ptrs_per_pgd(vm) * 8; pgd += 8) {
214 ptep = addr_gpa2hva(vm, pgd);
215 if (!*ptep)
216 continue;
217 printf("%*spgd: %lx: %lx at %p\n", indent, "", pgd, *ptep, ptep);
218 pte_dump(stream, vm, indent + 1, pte_addr(vm, *ptep), level);
219 }
220}
221
222struct kvm_vm *vm_create_default(uint32_t vcpuid, uint64_t extra_mem_pages,
223 void *guest_code)
224{
225 uint64_t ptrs_per_4k_pte = 512;
226 uint64_t extra_pg_pages = (extra_mem_pages / ptrs_per_4k_pte) * 2;
227 struct kvm_vm *vm;
228
229 vm = vm_create(VM_MODE_P52V48_4K, DEFAULT_GUEST_PHY_PAGES + extra_pg_pages, O_RDWR);
230
231 kvm_vm_elf_load(vm, program_invocation_name, 0, 0);
232 vm_vcpu_add_default(vm, vcpuid, guest_code);
233
234 return vm;
235}
236
237void vm_vcpu_add_default(struct kvm_vm *vm, uint32_t vcpuid, void *guest_code)
238{
239 size_t stack_size = vm->page_size == 4096 ?
240 DEFAULT_STACK_PGS * vm->page_size :
241 vm->page_size;
242 uint64_t stack_vaddr = vm_vaddr_alloc(vm, stack_size,
243 DEFAULT_ARM64_GUEST_STACK_VADDR_MIN, 0, 0);
244
245 vm_vcpu_add(vm, vcpuid, 0, 0);
246
247 set_reg(vm, vcpuid, ARM64_CORE_REG(sp_el1), stack_vaddr + stack_size);
248 set_reg(vm, vcpuid, ARM64_CORE_REG(regs.pc), (uint64_t)guest_code);
249}
250
251void vcpu_setup(struct kvm_vm *vm, int vcpuid, int pgd_memslot, int gdt_memslot)
252{
253 struct kvm_vcpu_init init;
254 uint64_t sctlr_el1, tcr_el1;
255
256 memset(&init, 0, sizeof(init));
257 init.target = KVM_ARM_TARGET_GENERIC_V8;
258 vcpu_ioctl(vm, vcpuid, KVM_ARM_VCPU_INIT, &init);
259
260 /*
261 * Enable FP/ASIMD to avoid trapping when accessing Q0-Q15
262 * registers, which the variable argument list macros do.
263 */
264 set_reg(vm, vcpuid, ARM64_SYS_REG(CPACR_EL1), 3 << 20);
265
266 get_reg(vm, vcpuid, ARM64_SYS_REG(SCTLR_EL1), &sctlr_el1);
267 get_reg(vm, vcpuid, ARM64_SYS_REG(TCR_EL1), &tcr_el1);
268
269 switch (vm->mode) {
270 case VM_MODE_P52V48_4K:
271 tcr_el1 |= 0ul << 14; /* TG0 = 4KB */
272 tcr_el1 |= 6ul << 32; /* IPS = 52 bits */
273 break;
274 case VM_MODE_P52V48_64K:
275 tcr_el1 |= 1ul << 14; /* TG0 = 64KB */
276 tcr_el1 |= 6ul << 32; /* IPS = 52 bits */
277 break;
278 case VM_MODE_P40V48_4K:
279 tcr_el1 |= 0ul << 14; /* TG0 = 4KB */
280 tcr_el1 |= 2ul << 32; /* IPS = 40 bits */
281 break;
282 case VM_MODE_P40V48_64K:
283 tcr_el1 |= 1ul << 14; /* TG0 = 64KB */
284 tcr_el1 |= 2ul << 32; /* IPS = 40 bits */
285 break;
286 default:
287 TEST_ASSERT(false, "Unknown guest mode, mode: 0x%x", vm->mode);
288 }
289
290 sctlr_el1 |= (1 << 0) | (1 << 2) | (1 << 12) /* M | C | I */;
291 /* TCR_EL1 |= IRGN0:WBWA | ORGN0:WBWA | SH0:Inner-Shareable */;
292 tcr_el1 |= (1 << 8) | (1 << 10) | (3 << 12);
293 tcr_el1 |= (64 - vm->va_bits) /* T0SZ */;
294
295 set_reg(vm, vcpuid, ARM64_SYS_REG(SCTLR_EL1), sctlr_el1);
296 set_reg(vm, vcpuid, ARM64_SYS_REG(TCR_EL1), tcr_el1);
297 set_reg(vm, vcpuid, ARM64_SYS_REG(MAIR_EL1), DEFAULT_MAIR_EL1);
298 set_reg(vm, vcpuid, ARM64_SYS_REG(TTBR0_EL1), vm->pgd);
299}
300
301void vcpu_dump(FILE *stream, struct kvm_vm *vm, uint32_t vcpuid, uint8_t indent)
302{
303 uint64_t pstate, pc;
304
305 get_reg(vm, vcpuid, ARM64_CORE_REG(regs.pstate), &pstate);
306 get_reg(vm, vcpuid, ARM64_CORE_REG(regs.pc), &pc);
307
308 fprintf(stream, "%*spstate: 0x%.16llx pc: 0x%.16llx\n",
309 indent, "", pstate, pc);
310
311}
diff --git a/tools/testing/selftests/kvm/lib/assert.c b/tools/testing/selftests/kvm/lib/assert.c
index cd01144d27c8..6398efe67885 100644
--- a/tools/testing/selftests/kvm/lib/assert.c
+++ b/tools/testing/selftests/kvm/lib/assert.c
@@ -13,7 +13,7 @@
13#include <execinfo.h> 13#include <execinfo.h>
14#include <sys/syscall.h> 14#include <sys/syscall.h>
15 15
16#include "../../kselftest.h" 16#include "kselftest.h"
17 17
18/* Dumps the current stack trace to stderr. */ 18/* Dumps the current stack trace to stderr. */
19static void __attribute__((noinline)) test_dump_stack(void); 19static void __attribute__((noinline)) test_dump_stack(void);
diff --git a/tools/testing/selftests/kvm/lib/kvm_util.c b/tools/testing/selftests/kvm/lib/kvm_util.c
index 6fd8c089cafc..8c06da4f03db 100644
--- a/tools/testing/selftests/kvm/lib/kvm_util.c
+++ b/tools/testing/selftests/kvm/lib/kvm_util.c
@@ -16,10 +16,8 @@
16#include <sys/stat.h> 16#include <sys/stat.h>
17#include <linux/kernel.h> 17#include <linux/kernel.h>
18 18
19#define KVM_DEV_PATH "/dev/kvm"
20
21#define KVM_UTIL_PGS_PER_HUGEPG 512 19#define KVM_UTIL_PGS_PER_HUGEPG 512
22#define KVM_UTIL_MIN_PADDR 0x2000 20#define KVM_UTIL_MIN_PFN 2
23 21
24/* Aligns x up to the next multiple of size. Size must be a power of 2. */ 22/* Aligns x up to the next multiple of size. Size must be a power of 2. */
25static void *align(void *x, size_t size) 23static void *align(void *x, size_t size)
@@ -30,7 +28,8 @@ static void *align(void *x, size_t size)
30 return (void *) (((size_t) x + mask) & ~mask); 28 return (void *) (((size_t) x + mask) & ~mask);
31} 29}
32 30
33/* Capability 31/*
32 * Capability
34 * 33 *
35 * Input Args: 34 * Input Args:
36 * cap - Capability 35 * cap - Capability
@@ -92,16 +91,23 @@ static void vm_open(struct kvm_vm *vm, int perm)
92 if (vm->kvm_fd < 0) 91 if (vm->kvm_fd < 0)
93 exit(KSFT_SKIP); 92 exit(KSFT_SKIP);
94 93
95 /* Create VM. */
96 vm->fd = ioctl(vm->kvm_fd, KVM_CREATE_VM, NULL); 94 vm->fd = ioctl(vm->kvm_fd, KVM_CREATE_VM, NULL);
97 TEST_ASSERT(vm->fd >= 0, "KVM_CREATE_VM ioctl failed, " 95 TEST_ASSERT(vm->fd >= 0, "KVM_CREATE_VM ioctl failed, "
98 "rc: %i errno: %i", vm->fd, errno); 96 "rc: %i errno: %i", vm->fd, errno);
99} 97}
100 98
101/* VM Create 99const char * const vm_guest_mode_string[] = {
100 "PA-bits:52, VA-bits:48, 4K pages",
101 "PA-bits:52, VA-bits:48, 64K pages",
102 "PA-bits:40, VA-bits:48, 4K pages",
103 "PA-bits:40, VA-bits:48, 64K pages",
104};
105
106/*
107 * VM Create
102 * 108 *
103 * Input Args: 109 * Input Args:
104 * mode - VM Mode (e.g. VM_MODE_FLAT48PG) 110 * mode - VM Mode (e.g. VM_MODE_P52V48_4K)
105 * phy_pages - Physical memory pages 111 * phy_pages - Physical memory pages
106 * perm - permission 112 * perm - permission
107 * 113 *
@@ -110,7 +116,7 @@ static void vm_open(struct kvm_vm *vm, int perm)
110 * Return: 116 * Return:
111 * Pointer to opaque structure that describes the created VM. 117 * Pointer to opaque structure that describes the created VM.
112 * 118 *
113 * Creates a VM with the mode specified by mode (e.g. VM_MODE_FLAT48PG). 119 * Creates a VM with the mode specified by mode (e.g. VM_MODE_P52V48_4K).
114 * When phy_pages is non-zero, a memory region of phy_pages physical pages 120 * When phy_pages is non-zero, a memory region of phy_pages physical pages
115 * is created and mapped starting at guest physical address 0. The file 121 * is created and mapped starting at guest physical address 0. The file
116 * descriptor to control the created VM is created with the permissions 122 * descriptor to control the created VM is created with the permissions
@@ -121,7 +127,6 @@ struct kvm_vm *vm_create(enum vm_guest_mode mode, uint64_t phy_pages, int perm)
121 struct kvm_vm *vm; 127 struct kvm_vm *vm;
122 int kvm_fd; 128 int kvm_fd;
123 129
124 /* Allocate memory. */
125 vm = calloc(1, sizeof(*vm)); 130 vm = calloc(1, sizeof(*vm));
126 TEST_ASSERT(vm != NULL, "Insufficent Memory"); 131 TEST_ASSERT(vm != NULL, "Insufficent Memory");
127 132
@@ -130,26 +135,48 @@ struct kvm_vm *vm_create(enum vm_guest_mode mode, uint64_t phy_pages, int perm)
130 135
131 /* Setup mode specific traits. */ 136 /* Setup mode specific traits. */
132 switch (vm->mode) { 137 switch (vm->mode) {
133 case VM_MODE_FLAT48PG: 138 case VM_MODE_P52V48_4K:
139 vm->pgtable_levels = 4;
134 vm->page_size = 0x1000; 140 vm->page_size = 0x1000;
135 vm->page_shift = 12; 141 vm->page_shift = 12;
136 142 vm->va_bits = 48;
137 /* Limit to 48-bit canonical virtual addresses. */ 143 break;
138 vm->vpages_valid = sparsebit_alloc(); 144 case VM_MODE_P52V48_64K:
139 sparsebit_set_num(vm->vpages_valid, 145 vm->pgtable_levels = 3;
140 0, (1ULL << (48 - 1)) >> vm->page_shift); 146 vm->pa_bits = 52;
141 sparsebit_set_num(vm->vpages_valid, 147 vm->page_size = 0x10000;
142 (~((1ULL << (48 - 1)) - 1)) >> vm->page_shift, 148 vm->page_shift = 16;
143 (1ULL << (48 - 1)) >> vm->page_shift); 149 vm->va_bits = 48;
144 150 break;
145 /* Limit physical addresses to 52-bits. */ 151 case VM_MODE_P40V48_4K:
146 vm->max_gfn = ((1ULL << 52) >> vm->page_shift) - 1; 152 vm->pgtable_levels = 4;
153 vm->pa_bits = 40;
154 vm->va_bits = 48;
155 vm->page_size = 0x1000;
156 vm->page_shift = 12;
157 break;
158 case VM_MODE_P40V48_64K:
159 vm->pgtable_levels = 3;
160 vm->pa_bits = 40;
161 vm->va_bits = 48;
162 vm->page_size = 0x10000;
163 vm->page_shift = 16;
147 break; 164 break;
148
149 default: 165 default:
150 TEST_ASSERT(false, "Unknown guest mode, mode: 0x%x", mode); 166 TEST_ASSERT(false, "Unknown guest mode, mode: 0x%x", mode);
151 } 167 }
152 168
169 /* Limit to VA-bit canonical virtual addresses. */
170 vm->vpages_valid = sparsebit_alloc();
171 sparsebit_set_num(vm->vpages_valid,
172 0, (1ULL << (vm->va_bits - 1)) >> vm->page_shift);
173 sparsebit_set_num(vm->vpages_valid,
174 (~((1ULL << (vm->va_bits - 1)) - 1)) >> vm->page_shift,
175 (1ULL << (vm->va_bits - 1)) >> vm->page_shift);
176
177 /* Limit physical addresses to PA-bits. */
178 vm->max_gfn = ((1ULL << vm->pa_bits) >> vm->page_shift) - 1;
179
153 /* Allocate and setup memory for guest. */ 180 /* Allocate and setup memory for guest. */
154 vm->vpages_mapped = sparsebit_alloc(); 181 vm->vpages_mapped = sparsebit_alloc();
155 if (phy_pages != 0) 182 if (phy_pages != 0)
@@ -159,7 +186,8 @@ struct kvm_vm *vm_create(enum vm_guest_mode mode, uint64_t phy_pages, int perm)
159 return vm; 186 return vm;
160} 187}
161 188
162/* VM Restart 189/*
190 * VM Restart
163 * 191 *
164 * Input Args: 192 * Input Args:
165 * vm - VM that has been released before 193 * vm - VM that has been released before
@@ -186,7 +214,8 @@ void kvm_vm_restart(struct kvm_vm *vmp, int perm)
186 " rc: %i errno: %i\n" 214 " rc: %i errno: %i\n"
187 " slot: %u flags: 0x%x\n" 215 " slot: %u flags: 0x%x\n"
188 " guest_phys_addr: 0x%lx size: 0x%lx", 216 " guest_phys_addr: 0x%lx size: 0x%lx",
189 ret, errno, region->region.slot, region->region.flags, 217 ret, errno, region->region.slot,
218 region->region.flags,
190 region->region.guest_phys_addr, 219 region->region.guest_phys_addr,
191 region->region.memory_size); 220 region->region.memory_size);
192 } 221 }
@@ -202,7 +231,8 @@ void kvm_vm_get_dirty_log(struct kvm_vm *vm, int slot, void *log)
202 strerror(-ret)); 231 strerror(-ret));
203} 232}
204 233
205/* Userspace Memory Region Find 234/*
235 * Userspace Memory Region Find
206 * 236 *
207 * Input Args: 237 * Input Args:
208 * vm - Virtual Machine 238 * vm - Virtual Machine
@@ -220,8 +250,8 @@ void kvm_vm_get_dirty_log(struct kvm_vm *vm, int slot, void *log)
220 * of the regions is returned. Null is returned only when no overlapping 250 * of the regions is returned. Null is returned only when no overlapping
221 * region exists. 251 * region exists.
222 */ 252 */
223static struct userspace_mem_region *userspace_mem_region_find( 253static struct userspace_mem_region *
224 struct kvm_vm *vm, uint64_t start, uint64_t end) 254userspace_mem_region_find(struct kvm_vm *vm, uint64_t start, uint64_t end)
225{ 255{
226 struct userspace_mem_region *region; 256 struct userspace_mem_region *region;
227 257
@@ -237,7 +267,8 @@ static struct userspace_mem_region *userspace_mem_region_find(
237 return NULL; 267 return NULL;
238} 268}
239 269
240/* KVM Userspace Memory Region Find 270/*
271 * KVM Userspace Memory Region Find
241 * 272 *
242 * Input Args: 273 * Input Args:
243 * vm - Virtual Machine 274 * vm - Virtual Machine
@@ -265,7 +296,8 @@ kvm_userspace_memory_region_find(struct kvm_vm *vm, uint64_t start,
265 return &region->region; 296 return &region->region;
266} 297}
267 298
268/* VCPU Find 299/*
300 * VCPU Find
269 * 301 *
270 * Input Args: 302 * Input Args:
271 * vm - Virtual Machine 303 * vm - Virtual Machine
@@ -280,8 +312,7 @@ kvm_userspace_memory_region_find(struct kvm_vm *vm, uint64_t start,
280 * returns a pointer to it. Returns NULL if the VM doesn't contain a VCPU 312 * returns a pointer to it. Returns NULL if the VM doesn't contain a VCPU
281 * for the specified vcpuid. 313 * for the specified vcpuid.
282 */ 314 */
283struct vcpu *vcpu_find(struct kvm_vm *vm, 315struct vcpu *vcpu_find(struct kvm_vm *vm, uint32_t vcpuid)
284 uint32_t vcpuid)
285{ 316{
286 struct vcpu *vcpup; 317 struct vcpu *vcpup;
287 318
@@ -293,7 +324,8 @@ struct vcpu *vcpu_find(struct kvm_vm *vm,
293 return NULL; 324 return NULL;
294} 325}
295 326
296/* VM VCPU Remove 327/*
328 * VM VCPU Remove
297 * 329 *
298 * Input Args: 330 * Input Args:
299 * vm - Virtual Machine 331 * vm - Virtual Machine
@@ -330,11 +362,9 @@ void kvm_vm_release(struct kvm_vm *vmp)
330{ 362{
331 int ret; 363 int ret;
332 364
333 /* Free VCPUs. */
334 while (vmp->vcpu_head) 365 while (vmp->vcpu_head)
335 vm_vcpu_rm(vmp, vmp->vcpu_head->id); 366 vm_vcpu_rm(vmp, vmp->vcpu_head->id);
336 367
337 /* Close file descriptor for the VM. */
338 ret = close(vmp->fd); 368 ret = close(vmp->fd);
339 TEST_ASSERT(ret == 0, "Close of vm fd failed,\n" 369 TEST_ASSERT(ret == 0, "Close of vm fd failed,\n"
340 " vmp->fd: %i rc: %i errno: %i", vmp->fd, ret, errno); 370 " vmp->fd: %i rc: %i errno: %i", vmp->fd, ret, errno);
@@ -344,7 +374,8 @@ void kvm_vm_release(struct kvm_vm *vmp)
344 " vmp->kvm_fd: %i rc: %i errno: %i", vmp->kvm_fd, ret, errno); 374 " vmp->kvm_fd: %i rc: %i errno: %i", vmp->kvm_fd, ret, errno);
345} 375}
346 376
347/* Destroys and frees the VM pointed to by vmp. 377/*
378 * Destroys and frees the VM pointed to by vmp.
348 */ 379 */
349void kvm_vm_free(struct kvm_vm *vmp) 380void kvm_vm_free(struct kvm_vm *vmp)
350{ 381{
@@ -383,7 +414,8 @@ void kvm_vm_free(struct kvm_vm *vmp)
383 free(vmp); 414 free(vmp);
384} 415}
385 416
386/* Memory Compare, host virtual to guest virtual 417/*
418 * Memory Compare, host virtual to guest virtual
387 * 419 *
388 * Input Args: 420 * Input Args:
389 * hva - Starting host virtual address 421 * hva - Starting host virtual address
@@ -405,23 +437,25 @@ void kvm_vm_free(struct kvm_vm *vmp)
405 * a length of len, to the guest bytes starting at the guest virtual 437 * a length of len, to the guest bytes starting at the guest virtual
406 * address given by gva. 438 * address given by gva.
407 */ 439 */
408int kvm_memcmp_hva_gva(void *hva, 440int kvm_memcmp_hva_gva(void *hva, struct kvm_vm *vm, vm_vaddr_t gva, size_t len)
409 struct kvm_vm *vm, vm_vaddr_t gva, size_t len)
410{ 441{
411 size_t amt; 442 size_t amt;
412 443
413 /* Compare a batch of bytes until either a match is found 444 /*
445 * Compare a batch of bytes until either a match is found
414 * or all the bytes have been compared. 446 * or all the bytes have been compared.
415 */ 447 */
416 for (uintptr_t offset = 0; offset < len; offset += amt) { 448 for (uintptr_t offset = 0; offset < len; offset += amt) {
417 uintptr_t ptr1 = (uintptr_t)hva + offset; 449 uintptr_t ptr1 = (uintptr_t)hva + offset;
418 450
419 /* Determine host address for guest virtual address 451 /*
452 * Determine host address for guest virtual address
420 * at offset. 453 * at offset.
421 */ 454 */
422 uintptr_t ptr2 = (uintptr_t)addr_gva2hva(vm, gva + offset); 455 uintptr_t ptr2 = (uintptr_t)addr_gva2hva(vm, gva + offset);
423 456
424 /* Determine amount to compare on this pass. 457 /*
458 * Determine amount to compare on this pass.
425 * Don't allow the comparsion to cross a page boundary. 459 * Don't allow the comparsion to cross a page boundary.
426 */ 460 */
427 amt = len - offset; 461 amt = len - offset;
@@ -433,7 +467,8 @@ int kvm_memcmp_hva_gva(void *hva,
433 assert((ptr1 >> vm->page_shift) == ((ptr1 + amt - 1) >> vm->page_shift)); 467 assert((ptr1 >> vm->page_shift) == ((ptr1 + amt - 1) >> vm->page_shift));
434 assert((ptr2 >> vm->page_shift) == ((ptr2 + amt - 1) >> vm->page_shift)); 468 assert((ptr2 >> vm->page_shift) == ((ptr2 + amt - 1) >> vm->page_shift));
435 469
436 /* Perform the comparison. If there is a difference 470 /*
471 * Perform the comparison. If there is a difference
437 * return that result to the caller, otherwise need 472 * return that result to the caller, otherwise need
438 * to continue on looking for a mismatch. 473 * to continue on looking for a mismatch.
439 */ 474 */
@@ -442,109 +477,15 @@ int kvm_memcmp_hva_gva(void *hva,
442 return ret; 477 return ret;
443 } 478 }
444 479
445 /* No mismatch found. Let the caller know the two memory 480 /*
481 * No mismatch found. Let the caller know the two memory
446 * areas are equal. 482 * areas are equal.
447 */ 483 */
448 return 0; 484 return 0;
449} 485}
450 486
451/* Allocate an instance of struct kvm_cpuid2 487/*
452 * 488 * VM Userspace Memory Region Add
453 * Input Args: None
454 *
455 * Output Args: None
456 *
457 * Return: A pointer to the allocated struct. The caller is responsible
458 * for freeing this struct.
459 *
460 * Since kvm_cpuid2 uses a 0-length array to allow a the size of the
461 * array to be decided at allocation time, allocation is slightly
462 * complicated. This function uses a reasonable default length for
463 * the array and performs the appropriate allocation.
464 */
465static struct kvm_cpuid2 *allocate_kvm_cpuid2(void)
466{
467 struct kvm_cpuid2 *cpuid;
468 int nent = 100;
469 size_t size;
470
471 size = sizeof(*cpuid);
472 size += nent * sizeof(struct kvm_cpuid_entry2);
473 cpuid = malloc(size);
474 if (!cpuid) {
475 perror("malloc");
476 abort();
477 }
478
479 cpuid->nent = nent;
480
481 return cpuid;
482}
483
484/* KVM Supported CPUID Get
485 *
486 * Input Args: None
487 *
488 * Output Args:
489 *
490 * Return: The supported KVM CPUID
491 *
492 * Get the guest CPUID supported by KVM.
493 */
494struct kvm_cpuid2 *kvm_get_supported_cpuid(void)
495{
496 static struct kvm_cpuid2 *cpuid;
497 int ret;
498 int kvm_fd;
499
500 if (cpuid)
501 return cpuid;
502
503 cpuid = allocate_kvm_cpuid2();
504 kvm_fd = open(KVM_DEV_PATH, O_RDONLY);
505 if (kvm_fd < 0)
506 exit(KSFT_SKIP);
507
508 ret = ioctl(kvm_fd, KVM_GET_SUPPORTED_CPUID, cpuid);
509 TEST_ASSERT(ret == 0, "KVM_GET_SUPPORTED_CPUID failed %d %d\n",
510 ret, errno);
511
512 close(kvm_fd);
513 return cpuid;
514}
515
516/* Locate a cpuid entry.
517 *
518 * Input Args:
519 * cpuid: The cpuid.
520 * function: The function of the cpuid entry to find.
521 *
522 * Output Args: None
523 *
524 * Return: A pointer to the cpuid entry. Never returns NULL.
525 */
526struct kvm_cpuid_entry2 *
527kvm_get_supported_cpuid_index(uint32_t function, uint32_t index)
528{
529 struct kvm_cpuid2 *cpuid;
530 struct kvm_cpuid_entry2 *entry = NULL;
531 int i;
532
533 cpuid = kvm_get_supported_cpuid();
534 for (i = 0; i < cpuid->nent; i++) {
535 if (cpuid->entries[i].function == function &&
536 cpuid->entries[i].index == index) {
537 entry = &cpuid->entries[i];
538 break;
539 }
540 }
541
542 TEST_ASSERT(entry, "Guest CPUID entry not found: (EAX=%x, ECX=%x).",
543 function, index);
544 return entry;
545}
546
547/* VM Userspace Memory Region Add
548 * 489 *
549 * Input Args: 490 * Input Args:
550 * vm - Virtual Machine 491 * vm - Virtual Machine
@@ -586,7 +527,8 @@ void vm_userspace_mem_region_add(struct kvm_vm *vm,
586 " vm->max_gfn: 0x%lx vm->page_size: 0x%x", 527 " vm->max_gfn: 0x%lx vm->page_size: 0x%x",
587 guest_paddr, npages, vm->max_gfn, vm->page_size); 528 guest_paddr, npages, vm->max_gfn, vm->page_size);
588 529
589 /* Confirm a mem region with an overlapping address doesn't 530 /*
531 * Confirm a mem region with an overlapping address doesn't
590 * already exist. 532 * already exist.
591 */ 533 */
592 region = (struct userspace_mem_region *) userspace_mem_region_find( 534 region = (struct userspace_mem_region *) userspace_mem_region_find(
@@ -677,7 +619,8 @@ void vm_userspace_mem_region_add(struct kvm_vm *vm,
677 vm->userspace_mem_region_head = region; 619 vm->userspace_mem_region_head = region;
678} 620}
679 621
680/* Memslot to region 622/*
623 * Memslot to region
681 * 624 *
682 * Input Args: 625 * Input Args:
683 * vm - Virtual Machine 626 * vm - Virtual Machine
@@ -691,8 +634,8 @@ void vm_userspace_mem_region_add(struct kvm_vm *vm,
691 * on error (e.g. currently no memory region using memslot as a KVM 634 * on error (e.g. currently no memory region using memslot as a KVM
692 * memory slot ID). 635 * memory slot ID).
693 */ 636 */
694static struct userspace_mem_region *memslot2region(struct kvm_vm *vm, 637static struct userspace_mem_region *
695 uint32_t memslot) 638memslot2region(struct kvm_vm *vm, uint32_t memslot)
696{ 639{
697 struct userspace_mem_region *region; 640 struct userspace_mem_region *region;
698 641
@@ -712,7 +655,8 @@ static struct userspace_mem_region *memslot2region(struct kvm_vm *vm,
712 return region; 655 return region;
713} 656}
714 657
715/* VM Memory Region Flags Set 658/*
659 * VM Memory Region Flags Set
716 * 660 *
717 * Input Args: 661 * Input Args:
718 * vm - Virtual Machine 662 * vm - Virtual Machine
@@ -730,7 +674,6 @@ void vm_mem_region_set_flags(struct kvm_vm *vm, uint32_t slot, uint32_t flags)
730 int ret; 674 int ret;
731 struct userspace_mem_region *region; 675 struct userspace_mem_region *region;
732 676
733 /* Locate memory region. */
734 region = memslot2region(vm, slot); 677 region = memslot2region(vm, slot);
735 678
736 region->region.flags = flags; 679 region->region.flags = flags;
@@ -742,7 +685,8 @@ void vm_mem_region_set_flags(struct kvm_vm *vm, uint32_t slot, uint32_t flags)
742 ret, errno, slot, flags); 685 ret, errno, slot, flags);
743} 686}
744 687
745/* VCPU mmap Size 688/*
689 * VCPU mmap Size
746 * 690 *
747 * Input Args: None 691 * Input Args: None
748 * 692 *
@@ -772,7 +716,8 @@ static int vcpu_mmap_sz(void)
772 return ret; 716 return ret;
773} 717}
774 718
775/* VM VCPU Add 719/*
720 * VM VCPU Add
776 * 721 *
777 * Input Args: 722 * Input Args:
778 * vm - Virtual Machine 723 * vm - Virtual Machine
@@ -785,7 +730,8 @@ static int vcpu_mmap_sz(void)
785 * Creates and adds to the VM specified by vm and virtual CPU with 730 * Creates and adds to the VM specified by vm and virtual CPU with
786 * the ID given by vcpuid. 731 * the ID given by vcpuid.
787 */ 732 */
788void vm_vcpu_add(struct kvm_vm *vm, uint32_t vcpuid, int pgd_memslot, int gdt_memslot) 733void vm_vcpu_add(struct kvm_vm *vm, uint32_t vcpuid, int pgd_memslot,
734 int gdt_memslot)
789{ 735{
790 struct vcpu *vcpu; 736 struct vcpu *vcpu;
791 737
@@ -823,7 +769,8 @@ void vm_vcpu_add(struct kvm_vm *vm, uint32_t vcpuid, int pgd_memslot, int gdt_me
823 vcpu_setup(vm, vcpuid, pgd_memslot, gdt_memslot); 769 vcpu_setup(vm, vcpuid, pgd_memslot, gdt_memslot);
824} 770}
825 771
826/* VM Virtual Address Unused Gap 772/*
773 * VM Virtual Address Unused Gap
827 * 774 *
828 * Input Args: 775 * Input Args:
829 * vm - Virtual Machine 776 * vm - Virtual Machine
@@ -843,14 +790,14 @@ void vm_vcpu_add(struct kvm_vm *vm, uint32_t vcpuid, int pgd_memslot, int gdt_me
843 * sz unallocated bytes >= vaddr_min is available. 790 * sz unallocated bytes >= vaddr_min is available.
844 */ 791 */
845static vm_vaddr_t vm_vaddr_unused_gap(struct kvm_vm *vm, size_t sz, 792static vm_vaddr_t vm_vaddr_unused_gap(struct kvm_vm *vm, size_t sz,
846 vm_vaddr_t vaddr_min) 793 vm_vaddr_t vaddr_min)
847{ 794{
848 uint64_t pages = (sz + vm->page_size - 1) >> vm->page_shift; 795 uint64_t pages = (sz + vm->page_size - 1) >> vm->page_shift;
849 796
850 /* Determine lowest permitted virtual page index. */ 797 /* Determine lowest permitted virtual page index. */
851 uint64_t pgidx_start = (vaddr_min + vm->page_size - 1) >> vm->page_shift; 798 uint64_t pgidx_start = (vaddr_min + vm->page_size - 1) >> vm->page_shift;
852 if ((pgidx_start * vm->page_size) < vaddr_min) 799 if ((pgidx_start * vm->page_size) < vaddr_min)
853 goto no_va_found; 800 goto no_va_found;
854 801
855 /* Loop over section with enough valid virtual page indexes. */ 802 /* Loop over section with enough valid virtual page indexes. */
856 if (!sparsebit_is_set_num(vm->vpages_valid, 803 if (!sparsebit_is_set_num(vm->vpages_valid,
@@ -909,7 +856,8 @@ va_found:
909 return pgidx_start * vm->page_size; 856 return pgidx_start * vm->page_size;
910} 857}
911 858
912/* VM Virtual Address Allocate 859/*
860 * VM Virtual Address Allocate
913 * 861 *
914 * Input Args: 862 * Input Args:
915 * vm - Virtual Machine 863 * vm - Virtual Machine
@@ -930,13 +878,14 @@ va_found:
930 * a page. 878 * a page.
931 */ 879 */
932vm_vaddr_t vm_vaddr_alloc(struct kvm_vm *vm, size_t sz, vm_vaddr_t vaddr_min, 880vm_vaddr_t vm_vaddr_alloc(struct kvm_vm *vm, size_t sz, vm_vaddr_t vaddr_min,
933 uint32_t data_memslot, uint32_t pgd_memslot) 881 uint32_t data_memslot, uint32_t pgd_memslot)
934{ 882{
935 uint64_t pages = (sz >> vm->page_shift) + ((sz % vm->page_size) != 0); 883 uint64_t pages = (sz >> vm->page_shift) + ((sz % vm->page_size) != 0);
936 884
937 virt_pgd_alloc(vm, pgd_memslot); 885 virt_pgd_alloc(vm, pgd_memslot);
938 886
939 /* Find an unused range of virtual page addresses of at least 887 /*
888 * Find an unused range of virtual page addresses of at least
940 * pages in length. 889 * pages in length.
941 */ 890 */
942 vm_vaddr_t vaddr_start = vm_vaddr_unused_gap(vm, sz, vaddr_min); 891 vm_vaddr_t vaddr_start = vm_vaddr_unused_gap(vm, sz, vaddr_min);
@@ -946,7 +895,8 @@ vm_vaddr_t vm_vaddr_alloc(struct kvm_vm *vm, size_t sz, vm_vaddr_t vaddr_min,
946 pages--, vaddr += vm->page_size) { 895 pages--, vaddr += vm->page_size) {
947 vm_paddr_t paddr; 896 vm_paddr_t paddr;
948 897
949 paddr = vm_phy_page_alloc(vm, KVM_UTIL_MIN_PADDR, data_memslot); 898 paddr = vm_phy_page_alloc(vm,
899 KVM_UTIL_MIN_PFN * vm->page_size, data_memslot);
950 900
951 virt_pg_map(vm, vaddr, paddr, pgd_memslot); 901 virt_pg_map(vm, vaddr, paddr, pgd_memslot);
952 902
@@ -990,7 +940,8 @@ void virt_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr,
990 } 940 }
991} 941}
992 942
993/* Address VM Physical to Host Virtual 943/*
944 * Address VM Physical to Host Virtual
994 * 945 *
995 * Input Args: 946 * Input Args:
996 * vm - Virtual Machine 947 * vm - Virtual Machine
@@ -1022,7 +973,8 @@ void *addr_gpa2hva(struct kvm_vm *vm, vm_paddr_t gpa)
1022 return NULL; 973 return NULL;
1023} 974}
1024 975
1025/* Address Host Virtual to VM Physical 976/*
977 * Address Host Virtual to VM Physical
1026 * 978 *
1027 * Input Args: 979 * Input Args:
1028 * vm - Virtual Machine 980 * vm - Virtual Machine
@@ -1056,7 +1008,8 @@ vm_paddr_t addr_hva2gpa(struct kvm_vm *vm, void *hva)
1056 return -1; 1008 return -1;
1057} 1009}
1058 1010
1059/* VM Create IRQ Chip 1011/*
1012 * VM Create IRQ Chip
1060 * 1013 *
1061 * Input Args: 1014 * Input Args:
1062 * vm - Virtual Machine 1015 * vm - Virtual Machine
@@ -1078,7 +1031,8 @@ void vm_create_irqchip(struct kvm_vm *vm)
1078 vm->has_irqchip = true; 1031 vm->has_irqchip = true;
1079} 1032}
1080 1033
1081/* VM VCPU State 1034/*
1035 * VM VCPU State
1082 * 1036 *
1083 * Input Args: 1037 * Input Args:
1084 * vm - Virtual Machine 1038 * vm - Virtual Machine
@@ -1100,7 +1054,8 @@ struct kvm_run *vcpu_state(struct kvm_vm *vm, uint32_t vcpuid)
1100 return vcpu->state; 1054 return vcpu->state;
1101} 1055}
1102 1056
1103/* VM VCPU Run 1057/*
1058 * VM VCPU Run
1104 * 1059 *
1105 * Input Args: 1060 * Input Args:
1106 * vm - Virtual Machine 1061 * vm - Virtual Machine
@@ -1126,13 +1081,14 @@ int _vcpu_run(struct kvm_vm *vm, uint32_t vcpuid)
1126 int rc; 1081 int rc;
1127 1082
1128 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid); 1083 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1129 do { 1084 do {
1130 rc = ioctl(vcpu->fd, KVM_RUN, NULL); 1085 rc = ioctl(vcpu->fd, KVM_RUN, NULL);
1131 } while (rc == -1 && errno == EINTR); 1086 } while (rc == -1 && errno == EINTR);
1132 return rc; 1087 return rc;
1133} 1088}
1134 1089
1135/* VM VCPU Set MP State 1090/*
1091 * VM VCPU Set MP State
1136 * 1092 *
1137 * Input Args: 1093 * Input Args:
1138 * vm - Virtual Machine 1094 * vm - Virtual Machine
@@ -1147,7 +1103,7 @@ int _vcpu_run(struct kvm_vm *vm, uint32_t vcpuid)
1147 * by mp_state. 1103 * by mp_state.
1148 */ 1104 */
1149void vcpu_set_mp_state(struct kvm_vm *vm, uint32_t vcpuid, 1105void vcpu_set_mp_state(struct kvm_vm *vm, uint32_t vcpuid,
1150 struct kvm_mp_state *mp_state) 1106 struct kvm_mp_state *mp_state)
1151{ 1107{
1152 struct vcpu *vcpu = vcpu_find(vm, vcpuid); 1108 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1153 int ret; 1109 int ret;
@@ -1159,7 +1115,8 @@ void vcpu_set_mp_state(struct kvm_vm *vm, uint32_t vcpuid,
1159 "rc: %i errno: %i", ret, errno); 1115 "rc: %i errno: %i", ret, errno);
1160} 1116}
1161 1117
1162/* VM VCPU Regs Get 1118/*
1119 * VM VCPU Regs Get
1163 * 1120 *
1164 * Input Args: 1121 * Input Args:
1165 * vm - Virtual Machine 1122 * vm - Virtual Machine
@@ -1173,21 +1130,20 @@ void vcpu_set_mp_state(struct kvm_vm *vm, uint32_t vcpuid,
1173 * Obtains the current register state for the VCPU specified by vcpuid 1130 * Obtains the current register state for the VCPU specified by vcpuid
1174 * and stores it at the location given by regs. 1131 * and stores it at the location given by regs.
1175 */ 1132 */
1176void vcpu_regs_get(struct kvm_vm *vm, 1133void vcpu_regs_get(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_regs *regs)
1177 uint32_t vcpuid, struct kvm_regs *regs)
1178{ 1134{
1179 struct vcpu *vcpu = vcpu_find(vm, vcpuid); 1135 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1180 int ret; 1136 int ret;
1181 1137
1182 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid); 1138 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1183 1139
1184 /* Get the regs. */
1185 ret = ioctl(vcpu->fd, KVM_GET_REGS, regs); 1140 ret = ioctl(vcpu->fd, KVM_GET_REGS, regs);
1186 TEST_ASSERT(ret == 0, "KVM_GET_REGS failed, rc: %i errno: %i", 1141 TEST_ASSERT(ret == 0, "KVM_GET_REGS failed, rc: %i errno: %i",
1187 ret, errno); 1142 ret, errno);
1188} 1143}
1189 1144
1190/* VM VCPU Regs Set 1145/*
1146 * VM VCPU Regs Set
1191 * 1147 *
1192 * Input Args: 1148 * Input Args:
1193 * vm - Virtual Machine 1149 * vm - Virtual Machine
@@ -1201,165 +1157,46 @@ void vcpu_regs_get(struct kvm_vm *vm,
1201 * Sets the regs of the VCPU specified by vcpuid to the values 1157 * Sets the regs of the VCPU specified by vcpuid to the values
1202 * given by regs. 1158 * given by regs.
1203 */ 1159 */
1204void vcpu_regs_set(struct kvm_vm *vm, 1160void vcpu_regs_set(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_regs *regs)
1205 uint32_t vcpuid, struct kvm_regs *regs)
1206{ 1161{
1207 struct vcpu *vcpu = vcpu_find(vm, vcpuid); 1162 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1208 int ret; 1163 int ret;
1209 1164
1210 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid); 1165 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1211 1166
1212 /* Set the regs. */
1213 ret = ioctl(vcpu->fd, KVM_SET_REGS, regs); 1167 ret = ioctl(vcpu->fd, KVM_SET_REGS, regs);
1214 TEST_ASSERT(ret == 0, "KVM_SET_REGS failed, rc: %i errno: %i", 1168 TEST_ASSERT(ret == 0, "KVM_SET_REGS failed, rc: %i errno: %i",
1215 ret, errno); 1169 ret, errno);
1216} 1170}
1217 1171
1218void vcpu_events_get(struct kvm_vm *vm, uint32_t vcpuid, 1172void vcpu_events_get(struct kvm_vm *vm, uint32_t vcpuid,
1219 struct kvm_vcpu_events *events) 1173 struct kvm_vcpu_events *events)
1220{ 1174{
1221 struct vcpu *vcpu = vcpu_find(vm, vcpuid); 1175 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1222 int ret; 1176 int ret;
1223 1177
1224 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid); 1178 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1225 1179
1226 /* Get the regs. */
1227 ret = ioctl(vcpu->fd, KVM_GET_VCPU_EVENTS, events); 1180 ret = ioctl(vcpu->fd, KVM_GET_VCPU_EVENTS, events);
1228 TEST_ASSERT(ret == 0, "KVM_GET_VCPU_EVENTS, failed, rc: %i errno: %i", 1181 TEST_ASSERT(ret == 0, "KVM_GET_VCPU_EVENTS, failed, rc: %i errno: %i",
1229 ret, errno); 1182 ret, errno);
1230} 1183}
1231 1184
1232void vcpu_events_set(struct kvm_vm *vm, uint32_t vcpuid, 1185void vcpu_events_set(struct kvm_vm *vm, uint32_t vcpuid,
1233 struct kvm_vcpu_events *events) 1186 struct kvm_vcpu_events *events)
1234{ 1187{
1235 struct vcpu *vcpu = vcpu_find(vm, vcpuid); 1188 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1236 int ret; 1189 int ret;
1237 1190
1238 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid); 1191 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1239 1192
1240 /* Set the regs. */
1241 ret = ioctl(vcpu->fd, KVM_SET_VCPU_EVENTS, events); 1193 ret = ioctl(vcpu->fd, KVM_SET_VCPU_EVENTS, events);
1242 TEST_ASSERT(ret == 0, "KVM_SET_VCPU_EVENTS, failed, rc: %i errno: %i", 1194 TEST_ASSERT(ret == 0, "KVM_SET_VCPU_EVENTS, failed, rc: %i errno: %i",
1243 ret, errno); 1195 ret, errno);
1244} 1196}
1245 1197
1246/* VCPU Get MSR 1198/*
1247 * 1199 * VM VCPU System Regs Get
1248 * Input Args:
1249 * vm - Virtual Machine
1250 * vcpuid - VCPU ID
1251 * msr_index - Index of MSR
1252 *
1253 * Output Args: None
1254 *
1255 * Return: On success, value of the MSR. On failure a TEST_ASSERT is produced.
1256 *
1257 * Get value of MSR for VCPU.
1258 */
1259uint64_t vcpu_get_msr(struct kvm_vm *vm, uint32_t vcpuid, uint64_t msr_index)
1260{
1261 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1262 struct {
1263 struct kvm_msrs header;
1264 struct kvm_msr_entry entry;
1265 } buffer = {};
1266 int r;
1267
1268 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1269 buffer.header.nmsrs = 1;
1270 buffer.entry.index = msr_index;
1271 r = ioctl(vcpu->fd, KVM_GET_MSRS, &buffer.header);
1272 TEST_ASSERT(r == 1, "KVM_GET_MSRS IOCTL failed,\n"
1273 " rc: %i errno: %i", r, errno);
1274
1275 return buffer.entry.data;
1276}
1277
1278/* VCPU Set MSR
1279 *
1280 * Input Args:
1281 * vm - Virtual Machine
1282 * vcpuid - VCPU ID
1283 * msr_index - Index of MSR
1284 * msr_value - New value of MSR
1285 *
1286 * Output Args: None
1287 *
1288 * Return: On success, nothing. On failure a TEST_ASSERT is produced.
1289 *
1290 * Set value of MSR for VCPU.
1291 */
1292void vcpu_set_msr(struct kvm_vm *vm, uint32_t vcpuid, uint64_t msr_index,
1293 uint64_t msr_value)
1294{
1295 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1296 struct {
1297 struct kvm_msrs header;
1298 struct kvm_msr_entry entry;
1299 } buffer = {};
1300 int r;
1301
1302 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1303 memset(&buffer, 0, sizeof(buffer));
1304 buffer.header.nmsrs = 1;
1305 buffer.entry.index = msr_index;
1306 buffer.entry.data = msr_value;
1307 r = ioctl(vcpu->fd, KVM_SET_MSRS, &buffer.header);
1308 TEST_ASSERT(r == 1, "KVM_SET_MSRS IOCTL failed,\n"
1309 " rc: %i errno: %i", r, errno);
1310}
1311
1312/* VM VCPU Args Set
1313 *
1314 * Input Args:
1315 * vm - Virtual Machine
1316 * vcpuid - VCPU ID
1317 * num - number of arguments
1318 * ... - arguments, each of type uint64_t
1319 *
1320 * Output Args: None
1321 *
1322 * Return: None
1323 *
1324 * Sets the first num function input arguments to the values
1325 * given as variable args. Each of the variable args is expected to
1326 * be of type uint64_t.
1327 */
1328void vcpu_args_set(struct kvm_vm *vm, uint32_t vcpuid, unsigned int num, ...)
1329{
1330 va_list ap;
1331 struct kvm_regs regs;
1332
1333 TEST_ASSERT(num >= 1 && num <= 6, "Unsupported number of args,\n"
1334 " num: %u\n",
1335 num);
1336
1337 va_start(ap, num);
1338 vcpu_regs_get(vm, vcpuid, &regs);
1339
1340 if (num >= 1)
1341 regs.rdi = va_arg(ap, uint64_t);
1342
1343 if (num >= 2)
1344 regs.rsi = va_arg(ap, uint64_t);
1345
1346 if (num >= 3)
1347 regs.rdx = va_arg(ap, uint64_t);
1348
1349 if (num >= 4)
1350 regs.rcx = va_arg(ap, uint64_t);
1351
1352 if (num >= 5)
1353 regs.r8 = va_arg(ap, uint64_t);
1354
1355 if (num >= 6)
1356 regs.r9 = va_arg(ap, uint64_t);
1357
1358 vcpu_regs_set(vm, vcpuid, &regs);
1359 va_end(ap);
1360}
1361
1362/* VM VCPU System Regs Get
1363 * 1200 *
1364 * Input Args: 1201 * Input Args:
1365 * vm - Virtual Machine 1202 * vm - Virtual Machine
@@ -1373,22 +1210,20 @@ void vcpu_args_set(struct kvm_vm *vm, uint32_t vcpuid, unsigned int num, ...)
1373 * Obtains the current system register state for the VCPU specified by 1210 * Obtains the current system register state for the VCPU specified by
1374 * vcpuid and stores it at the location given by sregs. 1211 * vcpuid and stores it at the location given by sregs.
1375 */ 1212 */
1376void vcpu_sregs_get(struct kvm_vm *vm, 1213void vcpu_sregs_get(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_sregs *sregs)
1377 uint32_t vcpuid, struct kvm_sregs *sregs)
1378{ 1214{
1379 struct vcpu *vcpu = vcpu_find(vm, vcpuid); 1215 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1380 int ret; 1216 int ret;
1381 1217
1382 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid); 1218 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1383 1219
1384 /* Get the regs. */
1385 /* Get the regs. */
1386 ret = ioctl(vcpu->fd, KVM_GET_SREGS, sregs); 1220 ret = ioctl(vcpu->fd, KVM_GET_SREGS, sregs);
1387 TEST_ASSERT(ret == 0, "KVM_GET_SREGS failed, rc: %i errno: %i", 1221 TEST_ASSERT(ret == 0, "KVM_GET_SREGS failed, rc: %i errno: %i",
1388 ret, errno); 1222 ret, errno);
1389} 1223}
1390 1224
1391/* VM VCPU System Regs Set 1225/*
1226 * VM VCPU System Regs Set
1392 * 1227 *
1393 * Input Args: 1228 * Input Args:
1394 * vm - Virtual Machine 1229 * vm - Virtual Machine
@@ -1402,27 +1237,25 @@ void vcpu_sregs_get(struct kvm_vm *vm,
1402 * Sets the system regs of the VCPU specified by vcpuid to the values 1237 * Sets the system regs of the VCPU specified by vcpuid to the values
1403 * given by sregs. 1238 * given by sregs.
1404 */ 1239 */
1405void vcpu_sregs_set(struct kvm_vm *vm, 1240void vcpu_sregs_set(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_sregs *sregs)
1406 uint32_t vcpuid, struct kvm_sregs *sregs)
1407{ 1241{
1408 int ret = _vcpu_sregs_set(vm, vcpuid, sregs); 1242 int ret = _vcpu_sregs_set(vm, vcpuid, sregs);
1409 TEST_ASSERT(ret == 0, "KVM_RUN IOCTL failed, " 1243 TEST_ASSERT(ret == 0, "KVM_RUN IOCTL failed, "
1410 "rc: %i errno: %i", ret, errno); 1244 "rc: %i errno: %i", ret, errno);
1411} 1245}
1412 1246
1413int _vcpu_sregs_set(struct kvm_vm *vm, 1247int _vcpu_sregs_set(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_sregs *sregs)
1414 uint32_t vcpuid, struct kvm_sregs *sregs)
1415{ 1248{
1416 struct vcpu *vcpu = vcpu_find(vm, vcpuid); 1249 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1417 int ret; 1250 int ret;
1418 1251
1419 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid); 1252 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1420 1253
1421 /* Get the regs. */
1422 return ioctl(vcpu->fd, KVM_SET_SREGS, sregs); 1254 return ioctl(vcpu->fd, KVM_SET_SREGS, sregs);
1423} 1255}
1424 1256
1425/* VCPU Ioctl 1257/*
1258 * VCPU Ioctl
1426 * 1259 *
1427 * Input Args: 1260 * Input Args:
1428 * vm - Virtual Machine 1261 * vm - Virtual Machine
@@ -1434,8 +1267,8 @@ int _vcpu_sregs_set(struct kvm_vm *vm,
1434 * 1267 *
1435 * Issues an arbitrary ioctl on a VCPU fd. 1268 * Issues an arbitrary ioctl on a VCPU fd.
1436 */ 1269 */
1437void vcpu_ioctl(struct kvm_vm *vm, 1270void vcpu_ioctl(struct kvm_vm *vm, uint32_t vcpuid,
1438 uint32_t vcpuid, unsigned long cmd, void *arg) 1271 unsigned long cmd, void *arg)
1439{ 1272{
1440 struct vcpu *vcpu = vcpu_find(vm, vcpuid); 1273 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1441 int ret; 1274 int ret;
@@ -1447,7 +1280,8 @@ void vcpu_ioctl(struct kvm_vm *vm,
1447 cmd, ret, errno, strerror(errno)); 1280 cmd, ret, errno, strerror(errno));
1448} 1281}
1449 1282
1450/* VM Ioctl 1283/*
1284 * VM Ioctl
1451 * 1285 *
1452 * Input Args: 1286 * Input Args:
1453 * vm - Virtual Machine 1287 * vm - Virtual Machine
@@ -1467,7 +1301,8 @@ void vm_ioctl(struct kvm_vm *vm, unsigned long cmd, void *arg)
1467 cmd, ret, errno, strerror(errno)); 1301 cmd, ret, errno, strerror(errno));
1468} 1302}
1469 1303
1470/* VM Dump 1304/*
1305 * VM Dump
1471 * 1306 *
1472 * Input Args: 1307 * Input Args:
1473 * vm - Virtual Machine 1308 * vm - Virtual Machine
@@ -1514,38 +1349,6 @@ void vm_dump(FILE *stream, struct kvm_vm *vm, uint8_t indent)
1514 vcpu_dump(stream, vm, vcpu->id, indent + 2); 1349 vcpu_dump(stream, vm, vcpu->id, indent + 2);
1515} 1350}
1516 1351
1517/* VM VCPU Dump
1518 *
1519 * Input Args:
1520 * vm - Virtual Machine
1521 * vcpuid - VCPU ID
1522 * indent - Left margin indent amount
1523 *
1524 * Output Args:
1525 * stream - Output FILE stream
1526 *
1527 * Return: None
1528 *
1529 * Dumps the current state of the VCPU specified by vcpuid, within the VM
1530 * given by vm, to the FILE stream given by stream.
1531 */
1532void vcpu_dump(FILE *stream, struct kvm_vm *vm,
1533 uint32_t vcpuid, uint8_t indent)
1534{
1535 struct kvm_regs regs;
1536 struct kvm_sregs sregs;
1537
1538 fprintf(stream, "%*scpuid: %u\n", indent, "", vcpuid);
1539
1540 fprintf(stream, "%*sregs:\n", indent + 2, "");
1541 vcpu_regs_get(vm, vcpuid, &regs);
1542 regs_dump(stream, &regs, indent + 4);
1543
1544 fprintf(stream, "%*ssregs:\n", indent + 2, "");
1545 vcpu_sregs_get(vm, vcpuid, &sregs);
1546 sregs_dump(stream, &sregs, indent + 4);
1547}
1548
1549/* Known KVM exit reasons */ 1352/* Known KVM exit reasons */
1550static struct exit_reason { 1353static struct exit_reason {
1551 unsigned int reason; 1354 unsigned int reason;
@@ -1576,7 +1379,8 @@ static struct exit_reason {
1576#endif 1379#endif
1577}; 1380};
1578 1381
1579/* Exit Reason String 1382/*
1383 * Exit Reason String
1580 * 1384 *
1581 * Input Args: 1385 * Input Args:
1582 * exit_reason - Exit reason 1386 * exit_reason - Exit reason
@@ -1602,10 +1406,12 @@ const char *exit_reason_str(unsigned int exit_reason)
1602 return "Unknown"; 1406 return "Unknown";
1603} 1407}
1604 1408
1605/* Physical Page Allocate 1409/*
1410 * Physical Contiguous Page Allocator
1606 * 1411 *
1607 * Input Args: 1412 * Input Args:
1608 * vm - Virtual Machine 1413 * vm - Virtual Machine
1414 * num - number of pages
1609 * paddr_min - Physical address minimum 1415 * paddr_min - Physical address minimum
1610 * memslot - Memory region to allocate page from 1416 * memslot - Memory region to allocate page from
1611 * 1417 *
@@ -1614,47 +1420,59 @@ const char *exit_reason_str(unsigned int exit_reason)
1614 * Return: 1420 * Return:
1615 * Starting physical address 1421 * Starting physical address
1616 * 1422 *
1617 * Within the VM specified by vm, locates an available physical page 1423 * Within the VM specified by vm, locates a range of available physical
1618 * at or above paddr_min. If found, the page is marked as in use 1424 * pages at or above paddr_min. If found, the pages are marked as in use
1619 * and its address is returned. A TEST_ASSERT failure occurs if no 1425 * and thier base address is returned. A TEST_ASSERT failure occurs if
1620 * page is available at or above paddr_min. 1426 * not enough pages are available at or above paddr_min.
1621 */ 1427 */
1622vm_paddr_t vm_phy_page_alloc(struct kvm_vm *vm, 1428vm_paddr_t vm_phy_pages_alloc(struct kvm_vm *vm, size_t num,
1623 vm_paddr_t paddr_min, uint32_t memslot) 1429 vm_paddr_t paddr_min, uint32_t memslot)
1624{ 1430{
1625 struct userspace_mem_region *region; 1431 struct userspace_mem_region *region;
1626 sparsebit_idx_t pg; 1432 sparsebit_idx_t pg, base;
1433
1434 TEST_ASSERT(num > 0, "Must allocate at least one page");
1627 1435
1628 TEST_ASSERT((paddr_min % vm->page_size) == 0, "Min physical address " 1436 TEST_ASSERT((paddr_min % vm->page_size) == 0, "Min physical address "
1629 "not divisible by page size.\n" 1437 "not divisible by page size.\n"
1630 " paddr_min: 0x%lx page_size: 0x%x", 1438 " paddr_min: 0x%lx page_size: 0x%x",
1631 paddr_min, vm->page_size); 1439 paddr_min, vm->page_size);
1632 1440
1633 /* Locate memory region. */
1634 region = memslot2region(vm, memslot); 1441 region = memslot2region(vm, memslot);
1442 base = pg = paddr_min >> vm->page_shift;
1635 1443
1636 /* Locate next available physical page at or above paddr_min. */ 1444 do {
1637 pg = paddr_min >> vm->page_shift; 1445 for (; pg < base + num; ++pg) {
1638 1446 if (!sparsebit_is_set(region->unused_phy_pages, pg)) {
1639 if (!sparsebit_is_set(region->unused_phy_pages, pg)) { 1447 base = pg = sparsebit_next_set(region->unused_phy_pages, pg);
1640 pg = sparsebit_next_set(region->unused_phy_pages, pg); 1448 break;
1641 if (pg == 0) { 1449 }
1642 fprintf(stderr, "No guest physical page available, "
1643 "paddr_min: 0x%lx page_size: 0x%x memslot: %u",
1644 paddr_min, vm->page_size, memslot);
1645 fputs("---- vm dump ----\n", stderr);
1646 vm_dump(stderr, vm, 2);
1647 abort();
1648 } 1450 }
1451 } while (pg && pg != base + num);
1452
1453 if (pg == 0) {
1454 fprintf(stderr, "No guest physical page available, "
1455 "paddr_min: 0x%lx page_size: 0x%x memslot: %u\n",
1456 paddr_min, vm->page_size, memslot);
1457 fputs("---- vm dump ----\n", stderr);
1458 vm_dump(stderr, vm, 2);
1459 abort();
1649 } 1460 }
1650 1461
1651 /* Specify page as in use and return its address. */ 1462 for (pg = base; pg < base + num; ++pg)
1652 sparsebit_clear(region->unused_phy_pages, pg); 1463 sparsebit_clear(region->unused_phy_pages, pg);
1464
1465 return base * vm->page_size;
1466}
1653 1467
1654 return pg * vm->page_size; 1468vm_paddr_t vm_phy_page_alloc(struct kvm_vm *vm, vm_paddr_t paddr_min,
1469 uint32_t memslot)
1470{
1471 return vm_phy_pages_alloc(vm, 1, paddr_min, memslot);
1655} 1472}
1656 1473
1657/* Address Guest Virtual to Host Virtual 1474/*
1475 * Address Guest Virtual to Host Virtual
1658 * 1476 *
1659 * Input Args: 1477 * Input Args:
1660 * vm - Virtual Machine 1478 * vm - Virtual Machine
@@ -1669,17 +1487,3 @@ void *addr_gva2hva(struct kvm_vm *vm, vm_vaddr_t gva)
1669{ 1487{
1670 return addr_gpa2hva(vm, addr_gva2gpa(vm, gva)); 1488 return addr_gpa2hva(vm, addr_gva2gpa(vm, gva));
1671} 1489}
1672
1673void guest_args_read(struct kvm_vm *vm, uint32_t vcpu_id,
1674 struct guest_args *args)
1675{
1676 struct kvm_run *run = vcpu_state(vm, vcpu_id);
1677 struct kvm_regs regs;
1678
1679 memset(&regs, 0, sizeof(regs));
1680 vcpu_regs_get(vm, vcpu_id, &regs);
1681
1682 args->port = run->io.port;
1683 args->arg0 = regs.rdi;
1684 args->arg1 = regs.rsi;
1685}
diff --git a/tools/testing/selftests/kvm/lib/kvm_util_internal.h b/tools/testing/selftests/kvm/lib/kvm_util_internal.h
index 542ed606b338..52701db0f253 100644
--- a/tools/testing/selftests/kvm/lib/kvm_util_internal.h
+++ b/tools/testing/selftests/kvm/lib/kvm_util_internal.h
@@ -1,28 +1,29 @@
1/* 1/*
2 * tools/testing/selftests/kvm/lib/kvm_util.c 2 * tools/testing/selftests/kvm/lib/kvm_util_internal.h
3 * 3 *
4 * Copyright (C) 2018, Google LLC. 4 * Copyright (C) 2018, Google LLC.
5 * 5 *
6 * This work is licensed under the terms of the GNU GPL, version 2. 6 * This work is licensed under the terms of the GNU GPL, version 2.
7 */ 7 */
8 8
9#ifndef KVM_UTIL_INTERNAL_H 9#ifndef SELFTEST_KVM_UTIL_INTERNAL_H
10#define KVM_UTIL_INTERNAL_H 1 10#define SELFTEST_KVM_UTIL_INTERNAL_H
11 11
12#include "sparsebit.h" 12#include "sparsebit.h"
13 13
14#define KVM_DEV_PATH "/dev/kvm"
15
14#ifndef BITS_PER_BYTE 16#ifndef BITS_PER_BYTE
15#define BITS_PER_BYTE 8 17#define BITS_PER_BYTE 8
16#endif 18#endif
17 19
18#ifndef BITS_PER_LONG 20#ifndef BITS_PER_LONG
19#define BITS_PER_LONG (BITS_PER_BYTE * sizeof(long)) 21#define BITS_PER_LONG (BITS_PER_BYTE * sizeof(long))
20#endif 22#endif
21 23
22#define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d)) 24#define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
23#define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, BITS_PER_LONG) 25#define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, BITS_PER_LONG)
24 26
25/* Concrete definition of struct kvm_vm. */
26struct userspace_mem_region { 27struct userspace_mem_region {
27 struct userspace_mem_region *next, *prev; 28 struct userspace_mem_region *next, *prev;
28 struct kvm_userspace_memory_region region; 29 struct kvm_userspace_memory_region region;
@@ -45,14 +46,16 @@ struct kvm_vm {
45 int mode; 46 int mode;
46 int kvm_fd; 47 int kvm_fd;
47 int fd; 48 int fd;
49 unsigned int pgtable_levels;
48 unsigned int page_size; 50 unsigned int page_size;
49 unsigned int page_shift; 51 unsigned int page_shift;
52 unsigned int pa_bits;
53 unsigned int va_bits;
50 uint64_t max_gfn; 54 uint64_t max_gfn;
51 struct vcpu *vcpu_head; 55 struct vcpu *vcpu_head;
52 struct userspace_mem_region *userspace_mem_region_head; 56 struct userspace_mem_region *userspace_mem_region_head;
53 struct sparsebit *vpages_valid; 57 struct sparsebit *vpages_valid;
54 struct sparsebit *vpages_mapped; 58 struct sparsebit *vpages_mapped;
55
56 bool has_irqchip; 59 bool has_irqchip;
57 bool pgd_created; 60 bool pgd_created;
58 vm_paddr_t pgd; 61 vm_paddr_t pgd;
@@ -60,13 +63,11 @@ struct kvm_vm {
60 vm_vaddr_t tss; 63 vm_vaddr_t tss;
61}; 64};
62 65
63struct vcpu *vcpu_find(struct kvm_vm *vm, 66struct vcpu *vcpu_find(struct kvm_vm *vm, uint32_t vcpuid);
64 uint32_t vcpuid); 67void vcpu_setup(struct kvm_vm *vm, int vcpuid, int pgd_memslot,
65void vcpu_setup(struct kvm_vm *vm, int vcpuid, int pgd_memslot, int gdt_memslot); 68 int gdt_memslot);
66void virt_dump(FILE *stream, struct kvm_vm *vm, uint8_t indent); 69void virt_dump(FILE *stream, struct kvm_vm *vm, uint8_t indent);
67void regs_dump(FILE *stream, struct kvm_regs *regs, 70void regs_dump(FILE *stream, struct kvm_regs *regs, uint8_t indent);
68 uint8_t indent); 71void sregs_dump(FILE *stream, struct kvm_sregs *sregs, uint8_t indent);
69void sregs_dump(FILE *stream, struct kvm_sregs *sregs,
70 uint8_t indent);
71 72
72#endif 73#endif /* SELFTEST_KVM_UTIL_INTERNAL_H */
diff --git a/tools/testing/selftests/kvm/lib/ucall.c b/tools/testing/selftests/kvm/lib/ucall.c
new file mode 100644
index 000000000000..4777f9bb5194
--- /dev/null
+++ b/tools/testing/selftests/kvm/lib/ucall.c
@@ -0,0 +1,144 @@
1// SPDX-License-Identifier: GPL-2.0
2/*
3 * ucall support. A ucall is a "hypercall to userspace".
4 *
5 * Copyright (C) 2018, Red Hat, Inc.
6 */
7#include "kvm_util.h"
8#include "kvm_util_internal.h"
9
10#define UCALL_PIO_PORT ((uint16_t)0x1000)
11
12static ucall_type_t ucall_type;
13static vm_vaddr_t *ucall_exit_mmio_addr;
14
15static bool ucall_mmio_init(struct kvm_vm *vm, vm_paddr_t gpa)
16{
17 if (kvm_userspace_memory_region_find(vm, gpa, gpa + 1))
18 return false;
19
20 virt_pg_map(vm, gpa, gpa, 0);
21
22 ucall_exit_mmio_addr = (vm_vaddr_t *)gpa;
23 sync_global_to_guest(vm, ucall_exit_mmio_addr);
24
25 return true;
26}
27
28void ucall_init(struct kvm_vm *vm, ucall_type_t type, void *arg)
29{
30 ucall_type = type;
31 sync_global_to_guest(vm, ucall_type);
32
33 if (type == UCALL_PIO)
34 return;
35
36 if (type == UCALL_MMIO) {
37 vm_paddr_t gpa, start, end, step;
38 bool ret;
39
40 if (arg) {
41 gpa = (vm_paddr_t)arg;
42 ret = ucall_mmio_init(vm, gpa);
43 TEST_ASSERT(ret, "Can't set ucall mmio address to %lx", gpa);
44 return;
45 }
46
47 /*
48 * Find an address within the allowed virtual address space,
49 * that does _not_ have a KVM memory region associated with it.
50 * Identity mapping an address like this allows the guest to
51 * access it, but as KVM doesn't know what to do with it, it
52 * will assume it's something userspace handles and exit with
53 * KVM_EXIT_MMIO. Well, at least that's how it works for AArch64.
54 * Here we start with a guess that the addresses around two
55 * thirds of the VA space are unmapped and then work both down
56 * and up from there in 1/6 VA space sized steps.
57 */
58 start = 1ul << (vm->va_bits * 2 / 3);
59 end = 1ul << vm->va_bits;
60 step = 1ul << (vm->va_bits / 6);
61 for (gpa = start; gpa >= 0; gpa -= step) {
62 if (ucall_mmio_init(vm, gpa & ~(vm->page_size - 1)))
63 return;
64 }
65 for (gpa = start + step; gpa < end; gpa += step) {
66 if (ucall_mmio_init(vm, gpa & ~(vm->page_size - 1)))
67 return;
68 }
69 TEST_ASSERT(false, "Can't find a ucall mmio address");
70 }
71}
72
73void ucall_uninit(struct kvm_vm *vm)
74{
75 ucall_type = 0;
76 sync_global_to_guest(vm, ucall_type);
77 ucall_exit_mmio_addr = 0;
78 sync_global_to_guest(vm, ucall_exit_mmio_addr);
79}
80
81static void ucall_pio_exit(struct ucall *uc)
82{
83#ifdef __x86_64__
84 asm volatile("in %[port], %%al"
85 : : [port] "d" (UCALL_PIO_PORT), "D" (uc) : "rax");
86#endif
87}
88
89static void ucall_mmio_exit(struct ucall *uc)
90{
91 *ucall_exit_mmio_addr = (vm_vaddr_t)uc;
92}
93
94void ucall(uint64_t cmd, int nargs, ...)
95{
96 struct ucall uc = {
97 .cmd = cmd,
98 };
99 va_list va;
100 int i;
101
102 nargs = nargs <= UCALL_MAX_ARGS ? nargs : UCALL_MAX_ARGS;
103
104 va_start(va, nargs);
105 for (i = 0; i < nargs; ++i)
106 uc.args[i] = va_arg(va, uint64_t);
107 va_end(va);
108
109 switch (ucall_type) {
110 case UCALL_PIO:
111 ucall_pio_exit(&uc);
112 break;
113 case UCALL_MMIO:
114 ucall_mmio_exit(&uc);
115 break;
116 };
117}
118
119uint64_t get_ucall(struct kvm_vm *vm, uint32_t vcpu_id, struct ucall *uc)
120{
121 struct kvm_run *run = vcpu_state(vm, vcpu_id);
122
123 memset(uc, 0, sizeof(*uc));
124
125#ifdef __x86_64__
126 if (ucall_type == UCALL_PIO && run->exit_reason == KVM_EXIT_IO &&
127 run->io.port == UCALL_PIO_PORT) {
128 struct kvm_regs regs;
129 vcpu_regs_get(vm, vcpu_id, &regs);
130 memcpy(uc, addr_gva2hva(vm, (vm_vaddr_t)regs.rdi), sizeof(*uc));
131 return uc->cmd;
132 }
133#endif
134 if (ucall_type == UCALL_MMIO && run->exit_reason == KVM_EXIT_MMIO &&
135 run->mmio.phys_addr == (uint64_t)ucall_exit_mmio_addr) {
136 vm_vaddr_t gva;
137 TEST_ASSERT(run->mmio.is_write && run->mmio.len == 8,
138 "Unexpected ucall exit mmio address access");
139 gva = *(vm_vaddr_t *)run->mmio.data;
140 memcpy(uc, addr_gva2hva(vm, gva), sizeof(*uc));
141 }
142
143 return uc->cmd;
144}
diff --git a/tools/testing/selftests/kvm/lib/x86.c b/tools/testing/selftests/kvm/lib/x86_64/processor.c
index a3122f1949a8..f28127f4a3af 100644
--- a/tools/testing/selftests/kvm/lib/x86.c
+++ b/tools/testing/selftests/kvm/lib/x86_64/processor.c
@@ -1,5 +1,5 @@
1/* 1/*
2 * tools/testing/selftests/kvm/lib/x86.c 2 * tools/testing/selftests/kvm/lib/x86_64/processor.c
3 * 3 *
4 * Copyright (C) 2018, Google LLC. 4 * Copyright (C) 2018, Google LLC.
5 * 5 *
@@ -10,8 +10,8 @@
10 10
11#include "test_util.h" 11#include "test_util.h"
12#include "kvm_util.h" 12#include "kvm_util.h"
13#include "kvm_util_internal.h" 13#include "../kvm_util_internal.h"
14#include "x86.h" 14#include "processor.h"
15 15
16/* Minimum physical address used for virtual translation tables. */ 16/* Minimum physical address used for virtual translation tables. */
17#define KVM_GUEST_PAGE_TABLE_MIN_PADDR 0x180000 17#define KVM_GUEST_PAGE_TABLE_MIN_PADDR 0x180000
@@ -231,7 +231,7 @@ void virt_pgd_alloc(struct kvm_vm *vm, uint32_t pgd_memslot)
231{ 231{
232 int rc; 232 int rc;
233 233
234 TEST_ASSERT(vm->mode == VM_MODE_FLAT48PG, "Attempt to use " 234 TEST_ASSERT(vm->mode == VM_MODE_P52V48_4K, "Attempt to use "
235 "unknown or unsupported guest mode, mode: 0x%x", vm->mode); 235 "unknown or unsupported guest mode, mode: 0x%x", vm->mode);
236 236
237 /* If needed, create page map l4 table. */ 237 /* If needed, create page map l4 table. */
@@ -264,7 +264,7 @@ void virt_pg_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr,
264 uint16_t index[4]; 264 uint16_t index[4];
265 struct pageMapL4Entry *pml4e; 265 struct pageMapL4Entry *pml4e;
266 266
267 TEST_ASSERT(vm->mode == VM_MODE_FLAT48PG, "Attempt to use " 267 TEST_ASSERT(vm->mode == VM_MODE_P52V48_4K, "Attempt to use "
268 "unknown or unsupported guest mode, mode: 0x%x", vm->mode); 268 "unknown or unsupported guest mode, mode: 0x%x", vm->mode);
269 269
270 TEST_ASSERT((vaddr % vm->page_size) == 0, 270 TEST_ASSERT((vaddr % vm->page_size) == 0,
@@ -551,7 +551,7 @@ vm_paddr_t addr_gva2gpa(struct kvm_vm *vm, vm_vaddr_t gva)
551 struct pageTableEntry *pte; 551 struct pageTableEntry *pte;
552 void *hva; 552 void *hva;
553 553
554 TEST_ASSERT(vm->mode == VM_MODE_FLAT48PG, "Attempt to use " 554 TEST_ASSERT(vm->mode == VM_MODE_P52V48_4K, "Attempt to use "
555 "unknown or unsupported guest mode, mode: 0x%x", vm->mode); 555 "unknown or unsupported guest mode, mode: 0x%x", vm->mode);
556 556
557 index[0] = (gva >> 12) & 0x1ffu; 557 index[0] = (gva >> 12) & 0x1ffu;
@@ -624,9 +624,9 @@ void vcpu_setup(struct kvm_vm *vm, int vcpuid, int pgd_memslot, int gdt_memslot)
624 kvm_setup_gdt(vm, &sregs.gdt, gdt_memslot, pgd_memslot); 624 kvm_setup_gdt(vm, &sregs.gdt, gdt_memslot, pgd_memslot);
625 625
626 switch (vm->mode) { 626 switch (vm->mode) {
627 case VM_MODE_FLAT48PG: 627 case VM_MODE_P52V48_4K:
628 sregs.cr0 = X86_CR0_PE | X86_CR0_NE | X86_CR0_PG; 628 sregs.cr0 = X86_CR0_PE | X86_CR0_NE | X86_CR0_PG;
629 sregs.cr4 |= X86_CR4_PAE; 629 sregs.cr4 |= X86_CR4_PAE | X86_CR4_OSFXSR;
630 sregs.efer |= (EFER_LME | EFER_LMA | EFER_NX); 630 sregs.efer |= (EFER_LME | EFER_LMA | EFER_NX);
631 631
632 kvm_seg_set_unusable(&sregs.ldt); 632 kvm_seg_set_unusable(&sregs.ldt);
@@ -672,6 +672,102 @@ void vm_vcpu_add_default(struct kvm_vm *vm, uint32_t vcpuid, void *guest_code)
672 vcpu_set_mp_state(vm, vcpuid, &mp_state); 672 vcpu_set_mp_state(vm, vcpuid, &mp_state);
673} 673}
674 674
675/* Allocate an instance of struct kvm_cpuid2
676 *
677 * Input Args: None
678 *
679 * Output Args: None
680 *
681 * Return: A pointer to the allocated struct. The caller is responsible
682 * for freeing this struct.
683 *
684 * Since kvm_cpuid2 uses a 0-length array to allow a the size of the
685 * array to be decided at allocation time, allocation is slightly
686 * complicated. This function uses a reasonable default length for
687 * the array and performs the appropriate allocation.
688 */
689static struct kvm_cpuid2 *allocate_kvm_cpuid2(void)
690{
691 struct kvm_cpuid2 *cpuid;
692 int nent = 100;
693 size_t size;
694
695 size = sizeof(*cpuid);
696 size += nent * sizeof(struct kvm_cpuid_entry2);
697 cpuid = malloc(size);
698 if (!cpuid) {
699 perror("malloc");
700 abort();
701 }
702
703 cpuid->nent = nent;
704
705 return cpuid;
706}
707
708/* KVM Supported CPUID Get
709 *
710 * Input Args: None
711 *
712 * Output Args:
713 *
714 * Return: The supported KVM CPUID
715 *
716 * Get the guest CPUID supported by KVM.
717 */
718struct kvm_cpuid2 *kvm_get_supported_cpuid(void)
719{
720 static struct kvm_cpuid2 *cpuid;
721 int ret;
722 int kvm_fd;
723
724 if (cpuid)
725 return cpuid;
726
727 cpuid = allocate_kvm_cpuid2();
728 kvm_fd = open(KVM_DEV_PATH, O_RDONLY);
729 if (kvm_fd < 0)
730 exit(KSFT_SKIP);
731
732 ret = ioctl(kvm_fd, KVM_GET_SUPPORTED_CPUID, cpuid);
733 TEST_ASSERT(ret == 0, "KVM_GET_SUPPORTED_CPUID failed %d %d\n",
734 ret, errno);
735
736 close(kvm_fd);
737 return cpuid;
738}
739
740/* Locate a cpuid entry.
741 *
742 * Input Args:
743 * cpuid: The cpuid.
744 * function: The function of the cpuid entry to find.
745 *
746 * Output Args: None
747 *
748 * Return: A pointer to the cpuid entry. Never returns NULL.
749 */
750struct kvm_cpuid_entry2 *
751kvm_get_supported_cpuid_index(uint32_t function, uint32_t index)
752{
753 struct kvm_cpuid2 *cpuid;
754 struct kvm_cpuid_entry2 *entry = NULL;
755 int i;
756
757 cpuid = kvm_get_supported_cpuid();
758 for (i = 0; i < cpuid->nent; i++) {
759 if (cpuid->entries[i].function == function &&
760 cpuid->entries[i].index == index) {
761 entry = &cpuid->entries[i];
762 break;
763 }
764 }
765
766 TEST_ASSERT(entry, "Guest CPUID entry not found: (EAX=%x, ECX=%x).",
767 function, index);
768 return entry;
769}
770
675/* VM VCPU CPUID Set 771/* VM VCPU CPUID Set
676 * 772 *
677 * Input Args: 773 * Input Args:
@@ -698,6 +794,7 @@ void vcpu_set_cpuid(struct kvm_vm *vm,
698 rc, errno); 794 rc, errno);
699 795
700} 796}
797
701/* Create a VM with reasonable defaults 798/* Create a VM with reasonable defaults
702 * 799 *
703 * Input Args: 800 * Input Args:
@@ -726,7 +823,7 @@ struct kvm_vm *vm_create_default(uint32_t vcpuid, uint64_t extra_mem_pages,
726 uint64_t extra_pg_pages = extra_mem_pages / 512 * 2; 823 uint64_t extra_pg_pages = extra_mem_pages / 512 * 2;
727 824
728 /* Create VM */ 825 /* Create VM */
729 vm = vm_create(VM_MODE_FLAT48PG, 826 vm = vm_create(VM_MODE_P52V48_4K,
730 DEFAULT_GUEST_PHY_PAGES + extra_pg_pages, 827 DEFAULT_GUEST_PHY_PAGES + extra_pg_pages,
731 O_RDWR); 828 O_RDWR);
732 829
@@ -742,6 +839,154 @@ struct kvm_vm *vm_create_default(uint32_t vcpuid, uint64_t extra_mem_pages,
742 return vm; 839 return vm;
743} 840}
744 841
842/* VCPU Get MSR
843 *
844 * Input Args:
845 * vm - Virtual Machine
846 * vcpuid - VCPU ID
847 * msr_index - Index of MSR
848 *
849 * Output Args: None
850 *
851 * Return: On success, value of the MSR. On failure a TEST_ASSERT is produced.
852 *
853 * Get value of MSR for VCPU.
854 */
855uint64_t vcpu_get_msr(struct kvm_vm *vm, uint32_t vcpuid, uint64_t msr_index)
856{
857 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
858 struct {
859 struct kvm_msrs header;
860 struct kvm_msr_entry entry;
861 } buffer = {};
862 int r;
863
864 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
865 buffer.header.nmsrs = 1;
866 buffer.entry.index = msr_index;
867 r = ioctl(vcpu->fd, KVM_GET_MSRS, &buffer.header);
868 TEST_ASSERT(r == 1, "KVM_GET_MSRS IOCTL failed,\n"
869 " rc: %i errno: %i", r, errno);
870
871 return buffer.entry.data;
872}
873
874/* VCPU Set MSR
875 *
876 * Input Args:
877 * vm - Virtual Machine
878 * vcpuid - VCPU ID
879 * msr_index - Index of MSR
880 * msr_value - New value of MSR
881 *
882 * Output Args: None
883 *
884 * Return: On success, nothing. On failure a TEST_ASSERT is produced.
885 *
886 * Set value of MSR for VCPU.
887 */
888void vcpu_set_msr(struct kvm_vm *vm, uint32_t vcpuid, uint64_t msr_index,
889 uint64_t msr_value)
890{
891 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
892 struct {
893 struct kvm_msrs header;
894 struct kvm_msr_entry entry;
895 } buffer = {};
896 int r;
897
898 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
899 memset(&buffer, 0, sizeof(buffer));
900 buffer.header.nmsrs = 1;
901 buffer.entry.index = msr_index;
902 buffer.entry.data = msr_value;
903 r = ioctl(vcpu->fd, KVM_SET_MSRS, &buffer.header);
904 TEST_ASSERT(r == 1, "KVM_SET_MSRS IOCTL failed,\n"
905 " rc: %i errno: %i", r, errno);
906}
907
908/* VM VCPU Args Set
909 *
910 * Input Args:
911 * vm - Virtual Machine
912 * vcpuid - VCPU ID
913 * num - number of arguments
914 * ... - arguments, each of type uint64_t
915 *
916 * Output Args: None
917 *
918 * Return: None
919 *
920 * Sets the first num function input arguments to the values
921 * given as variable args. Each of the variable args is expected to
922 * be of type uint64_t.
923 */
924void vcpu_args_set(struct kvm_vm *vm, uint32_t vcpuid, unsigned int num, ...)
925{
926 va_list ap;
927 struct kvm_regs regs;
928
929 TEST_ASSERT(num >= 1 && num <= 6, "Unsupported number of args,\n"
930 " num: %u\n",
931 num);
932
933 va_start(ap, num);
934 vcpu_regs_get(vm, vcpuid, &regs);
935
936 if (num >= 1)
937 regs.rdi = va_arg(ap, uint64_t);
938
939 if (num >= 2)
940 regs.rsi = va_arg(ap, uint64_t);
941
942 if (num >= 3)
943 regs.rdx = va_arg(ap, uint64_t);
944
945 if (num >= 4)
946 regs.rcx = va_arg(ap, uint64_t);
947
948 if (num >= 5)
949 regs.r8 = va_arg(ap, uint64_t);
950
951 if (num >= 6)
952 regs.r9 = va_arg(ap, uint64_t);
953
954 vcpu_regs_set(vm, vcpuid, &regs);
955 va_end(ap);
956}
957
958/*
959 * VM VCPU Dump
960 *
961 * Input Args:
962 * vm - Virtual Machine
963 * vcpuid - VCPU ID
964 * indent - Left margin indent amount
965 *
966 * Output Args:
967 * stream - Output FILE stream
968 *
969 * Return: None
970 *
971 * Dumps the current state of the VCPU specified by vcpuid, within the VM
972 * given by vm, to the FILE stream given by stream.
973 */
974void vcpu_dump(FILE *stream, struct kvm_vm *vm, uint32_t vcpuid, uint8_t indent)
975{
976 struct kvm_regs regs;
977 struct kvm_sregs sregs;
978
979 fprintf(stream, "%*scpuid: %u\n", indent, "", vcpuid);
980
981 fprintf(stream, "%*sregs:\n", indent + 2, "");
982 vcpu_regs_get(vm, vcpuid, &regs);
983 regs_dump(stream, &regs, indent + 4);
984
985 fprintf(stream, "%*ssregs:\n", indent + 2, "");
986 vcpu_sregs_get(vm, vcpuid, &sregs);
987 sregs_dump(stream, &sregs, indent + 4);
988}
989
745struct kvm_x86_state { 990struct kvm_x86_state {
746 struct kvm_vcpu_events events; 991 struct kvm_vcpu_events events;
747 struct kvm_mp_state mp_state; 992 struct kvm_mp_state mp_state;
diff --git a/tools/testing/selftests/kvm/lib/vmx.c b/tools/testing/selftests/kvm/lib/x86_64/vmx.c
index b987c3c970eb..771ba6bf751c 100644
--- a/tools/testing/selftests/kvm/lib/vmx.c
+++ b/tools/testing/selftests/kvm/lib/x86_64/vmx.c
@@ -1,5 +1,5 @@
1/* 1/*
2 * tools/testing/selftests/kvm/lib/x86.c 2 * tools/testing/selftests/kvm/lib/x86_64/vmx.c
3 * 3 *
4 * Copyright (C) 2018, Google LLC. 4 * Copyright (C) 2018, Google LLC.
5 * 5 *
@@ -10,9 +10,11 @@
10 10
11#include "test_util.h" 11#include "test_util.h"
12#include "kvm_util.h" 12#include "kvm_util.h"
13#include "x86.h" 13#include "processor.h"
14#include "vmx.h" 14#include "vmx.h"
15 15
16bool enable_evmcs;
17
16/* Allocate memory regions for nested VMX tests. 18/* Allocate memory regions for nested VMX tests.
17 * 19 *
18 * Input Args: 20 * Input Args:
@@ -62,6 +64,20 @@ vcpu_alloc_vmx(struct kvm_vm *vm, vm_vaddr_t *p_vmx_gva)
62 vmx->vmwrite_gpa = addr_gva2gpa(vm, (uintptr_t)vmx->vmwrite); 64 vmx->vmwrite_gpa = addr_gva2gpa(vm, (uintptr_t)vmx->vmwrite);
63 memset(vmx->vmwrite_hva, 0, getpagesize()); 65 memset(vmx->vmwrite_hva, 0, getpagesize());
64 66
67 /* Setup of a region of guest memory for the VP Assist page. */
68 vmx->vp_assist = (void *)vm_vaddr_alloc(vm, getpagesize(),
69 0x10000, 0, 0);
70 vmx->vp_assist_hva = addr_gva2hva(vm, (uintptr_t)vmx->vp_assist);
71 vmx->vp_assist_gpa = addr_gva2gpa(vm, (uintptr_t)vmx->vp_assist);
72
73 /* Setup of a region of guest memory for the enlightened VMCS. */
74 vmx->enlightened_vmcs = (void *)vm_vaddr_alloc(vm, getpagesize(),
75 0x10000, 0, 0);
76 vmx->enlightened_vmcs_hva =
77 addr_gva2hva(vm, (uintptr_t)vmx->enlightened_vmcs);
78 vmx->enlightened_vmcs_gpa =
79 addr_gva2gpa(vm, (uintptr_t)vmx->enlightened_vmcs);
80
65 *p_vmx_gva = vmx_gva; 81 *p_vmx_gva = vmx_gva;
66 return vmx; 82 return vmx;
67} 83}
@@ -107,18 +123,31 @@ bool prepare_for_vmx_operation(struct vmx_pages *vmx)
107 if (vmxon(vmx->vmxon_gpa)) 123 if (vmxon(vmx->vmxon_gpa))
108 return false; 124 return false;
109 125
110 /* Load a VMCS. */ 126 return true;
111 *(uint32_t *)(vmx->vmcs) = vmcs_revision(); 127}
112 if (vmclear(vmx->vmcs_gpa))
113 return false;
114
115 if (vmptrld(vmx->vmcs_gpa))
116 return false;
117 128
118 /* Setup shadow VMCS, do not load it yet. */ 129bool load_vmcs(struct vmx_pages *vmx)
119 *(uint32_t *)(vmx->shadow_vmcs) = vmcs_revision() | 0x80000000ul; 130{
120 if (vmclear(vmx->shadow_vmcs_gpa)) 131 if (!enable_evmcs) {
121 return false; 132 /* Load a VMCS. */
133 *(uint32_t *)(vmx->vmcs) = vmcs_revision();
134 if (vmclear(vmx->vmcs_gpa))
135 return false;
136
137 if (vmptrld(vmx->vmcs_gpa))
138 return false;
139
140 /* Setup shadow VMCS, do not load it yet. */
141 *(uint32_t *)(vmx->shadow_vmcs) =
142 vmcs_revision() | 0x80000000ul;
143 if (vmclear(vmx->shadow_vmcs_gpa))
144 return false;
145 } else {
146 if (evmcs_vmptrld(vmx->enlightened_vmcs_gpa,
147 vmx->enlightened_vmcs))
148 return false;
149 current_evmcs->revision_id = vmcs_revision();
150 }
122 151
123 return true; 152 return true;
124} 153}
diff --git a/tools/testing/selftests/kvm/cr4_cpuid_sync_test.c b/tools/testing/selftests/kvm/x86_64/cr4_cpuid_sync_test.c
index 11ec358bf969..d503a51fad30 100644
--- a/tools/testing/selftests/kvm/cr4_cpuid_sync_test.c
+++ b/tools/testing/selftests/kvm/x86_64/cr4_cpuid_sync_test.c
@@ -17,7 +17,7 @@
17#include "test_util.h" 17#include "test_util.h"
18 18
19#include "kvm_util.h" 19#include "kvm_util.h"
20#include "x86.h" 20#include "processor.h"
21 21
22#define X86_FEATURE_XSAVE (1<<26) 22#define X86_FEATURE_XSAVE (1<<26)
23#define X86_FEATURE_OSXSAVE (1<<27) 23#define X86_FEATURE_OSXSAVE (1<<27)
@@ -67,6 +67,7 @@ int main(int argc, char *argv[])
67 struct kvm_vm *vm; 67 struct kvm_vm *vm;
68 struct kvm_sregs sregs; 68 struct kvm_sregs sregs;
69 struct kvm_cpuid_entry2 *entry; 69 struct kvm_cpuid_entry2 *entry;
70 struct ucall uc;
70 int rc; 71 int rc;
71 72
72 entry = kvm_get_supported_cpuid_entry(1); 73 entry = kvm_get_supported_cpuid_entry(1);
@@ -87,21 +88,20 @@ int main(int argc, char *argv[])
87 rc = _vcpu_run(vm, VCPU_ID); 88 rc = _vcpu_run(vm, VCPU_ID);
88 89
89 if (run->exit_reason == KVM_EXIT_IO) { 90 if (run->exit_reason == KVM_EXIT_IO) {
90 switch (run->io.port) { 91 switch (get_ucall(vm, VCPU_ID, &uc)) {
91 case GUEST_PORT_SYNC: 92 case UCALL_SYNC:
92 /* emulate hypervisor clearing CR4.OSXSAVE */ 93 /* emulate hypervisor clearing CR4.OSXSAVE */
93 vcpu_sregs_get(vm, VCPU_ID, &sregs); 94 vcpu_sregs_get(vm, VCPU_ID, &sregs);
94 sregs.cr4 &= ~X86_CR4_OSXSAVE; 95 sregs.cr4 &= ~X86_CR4_OSXSAVE;
95 vcpu_sregs_set(vm, VCPU_ID, &sregs); 96 vcpu_sregs_set(vm, VCPU_ID, &sregs);
96 break; 97 break;
97 case GUEST_PORT_ABORT: 98 case UCALL_ABORT:
98 TEST_ASSERT(false, "Guest CR4 bit (OSXSAVE) unsynchronized with CPUID bit."); 99 TEST_ASSERT(false, "Guest CR4 bit (OSXSAVE) unsynchronized with CPUID bit.");
99 break; 100 break;
100 case GUEST_PORT_DONE: 101 case UCALL_DONE:
101 goto done; 102 goto done;
102 default: 103 default:
103 TEST_ASSERT(false, "Unknown port 0x%x.", 104 TEST_ASSERT(false, "Unknown ucall 0x%x.", uc.cmd);
104 run->io.port);
105 } 105 }
106 } 106 }
107 } 107 }
diff --git a/tools/testing/selftests/kvm/x86_64/evmcs_test.c b/tools/testing/selftests/kvm/x86_64/evmcs_test.c
new file mode 100644
index 000000000000..92c2cfd1b182
--- /dev/null
+++ b/tools/testing/selftests/kvm/x86_64/evmcs_test.c
@@ -0,0 +1,160 @@
1// SPDX-License-Identifier: GPL-2.0
2/*
3 * Copyright (C) 2018, Red Hat, Inc.
4 *
5 * Tests for Enlightened VMCS, including nested guest state.
6 */
7#define _GNU_SOURCE /* for program_invocation_short_name */
8#include <fcntl.h>
9#include <stdio.h>
10#include <stdlib.h>
11#include <string.h>
12#include <sys/ioctl.h>
13
14#include "test_util.h"
15
16#include "kvm_util.h"
17
18#include "vmx.h"
19
20#define VCPU_ID 5
21
22static bool have_nested_state;
23
24void l2_guest_code(void)
25{
26 GUEST_SYNC(6);
27
28 GUEST_SYNC(7);
29
30 /* Done, exit to L1 and never come back. */
31 vmcall();
32}
33
34void l1_guest_code(struct vmx_pages *vmx_pages)
35{
36#define L2_GUEST_STACK_SIZE 64
37 unsigned long l2_guest_stack[L2_GUEST_STACK_SIZE];
38
39 enable_vp_assist(vmx_pages->vp_assist_gpa, vmx_pages->vp_assist);
40
41 GUEST_ASSERT(vmx_pages->vmcs_gpa);
42 GUEST_ASSERT(prepare_for_vmx_operation(vmx_pages));
43 GUEST_SYNC(3);
44 GUEST_ASSERT(load_vmcs(vmx_pages));
45 GUEST_ASSERT(vmptrstz() == vmx_pages->enlightened_vmcs_gpa);
46
47 GUEST_SYNC(4);
48 GUEST_ASSERT(vmptrstz() == vmx_pages->enlightened_vmcs_gpa);
49
50 prepare_vmcs(vmx_pages, l2_guest_code,
51 &l2_guest_stack[L2_GUEST_STACK_SIZE]);
52
53 GUEST_SYNC(5);
54 GUEST_ASSERT(vmptrstz() == vmx_pages->enlightened_vmcs_gpa);
55 GUEST_ASSERT(!vmlaunch());
56 GUEST_ASSERT(vmptrstz() == vmx_pages->enlightened_vmcs_gpa);
57 GUEST_SYNC(8);
58 GUEST_ASSERT(!vmresume());
59 GUEST_ASSERT(vmreadz(VM_EXIT_REASON) == EXIT_REASON_VMCALL);
60 GUEST_SYNC(9);
61}
62
63void guest_code(struct vmx_pages *vmx_pages)
64{
65 GUEST_SYNC(1);
66 GUEST_SYNC(2);
67
68 if (vmx_pages)
69 l1_guest_code(vmx_pages);
70
71 GUEST_DONE();
72}
73
74int main(int argc, char *argv[])
75{
76 struct vmx_pages *vmx_pages = NULL;
77 vm_vaddr_t vmx_pages_gva = 0;
78
79 struct kvm_regs regs1, regs2;
80 struct kvm_vm *vm;
81 struct kvm_run *run;
82 struct kvm_x86_state *state;
83 struct ucall uc;
84 int stage;
85 uint16_t evmcs_ver;
86 struct kvm_enable_cap enable_evmcs_cap = {
87 .cap = KVM_CAP_HYPERV_ENLIGHTENED_VMCS,
88 .args[0] = (unsigned long)&evmcs_ver
89 };
90
91 struct kvm_cpuid_entry2 *entry = kvm_get_supported_cpuid_entry(1);
92
93 /* Create VM */
94 vm = vm_create_default(VCPU_ID, 0, guest_code);
95
96 vcpu_set_cpuid(vm, VCPU_ID, kvm_get_supported_cpuid());
97
98 if (!kvm_check_cap(KVM_CAP_NESTED_STATE) ||
99 !kvm_check_cap(KVM_CAP_HYPERV_ENLIGHTENED_VMCS)) {
100 printf("capabilities not available, skipping test\n");
101 exit(KSFT_SKIP);
102 }
103
104 vcpu_ioctl(vm, VCPU_ID, KVM_ENABLE_CAP, &enable_evmcs_cap);
105
106 run = vcpu_state(vm, VCPU_ID);
107
108 vcpu_regs_get(vm, VCPU_ID, &regs1);
109
110 vmx_pages = vcpu_alloc_vmx(vm, &vmx_pages_gva);
111 vcpu_args_set(vm, VCPU_ID, 1, vmx_pages_gva);
112
113 for (stage = 1;; stage++) {
114 _vcpu_run(vm, VCPU_ID);
115 TEST_ASSERT(run->exit_reason == KVM_EXIT_IO,
116 "Unexpected exit reason: %u (%s),\n",
117 run->exit_reason,
118 exit_reason_str(run->exit_reason));
119
120 memset(&regs1, 0, sizeof(regs1));
121 vcpu_regs_get(vm, VCPU_ID, &regs1);
122 switch (get_ucall(vm, VCPU_ID, &uc)) {
123 case UCALL_ABORT:
124 TEST_ASSERT(false, "%s at %s:%d", (const char *)uc.args[0],
125 __FILE__, uc.args[1]);
126 /* NOT REACHED */
127 case UCALL_SYNC:
128 break;
129 case UCALL_DONE:
130 goto done;
131 default:
132 TEST_ASSERT(false, "Unknown ucall 0x%x.", uc.cmd);
133 }
134
135 /* UCALL_SYNC is handled here. */
136 TEST_ASSERT(!strcmp((const char *)uc.args[0], "hello") &&
137 uc.args[1] == stage, "Unexpected register values vmexit #%lx, got %lx",
138 stage, (ulong)uc.args[1]);
139
140 state = vcpu_save_state(vm, VCPU_ID);
141 kvm_vm_release(vm);
142
143 /* Restore state in a new VM. */
144 kvm_vm_restart(vm, O_RDWR);
145 vm_vcpu_add(vm, VCPU_ID, 0, 0);
146 vcpu_set_cpuid(vm, VCPU_ID, kvm_get_supported_cpuid());
147 vcpu_load_state(vm, VCPU_ID, state);
148 run = vcpu_state(vm, VCPU_ID);
149 free(state);
150
151 memset(&regs2, 0, sizeof(regs2));
152 vcpu_regs_get(vm, VCPU_ID, &regs2);
153 TEST_ASSERT(!memcmp(&regs1, &regs2, sizeof(regs2)),
154 "Unexpected register values after vcpu_load_state; rdi: %lx rsi: %lx",
155 (ulong) regs2.rdi, (ulong) regs2.rsi);
156 }
157
158done:
159 kvm_vm_free(vm);
160}
diff --git a/tools/testing/selftests/kvm/platform_info_test.c b/tools/testing/selftests/kvm/x86_64/platform_info_test.c
index 3764e7121265..eb3e7a838cb4 100644
--- a/tools/testing/selftests/kvm/platform_info_test.c
+++ b/tools/testing/selftests/kvm/x86_64/platform_info_test.c
@@ -19,7 +19,7 @@
19 19
20#include "test_util.h" 20#include "test_util.h"
21#include "kvm_util.h" 21#include "kvm_util.h"
22#include "x86.h" 22#include "processor.h"
23 23
24#define VCPU_ID 0 24#define VCPU_ID 0
25#define MSR_PLATFORM_INFO_MAX_TURBO_RATIO 0xff00 25#define MSR_PLATFORM_INFO_MAX_TURBO_RATIO 0xff00
@@ -48,7 +48,7 @@ static void set_msr_platform_info_enabled(struct kvm_vm *vm, bool enable)
48static void test_msr_platform_info_enabled(struct kvm_vm *vm) 48static void test_msr_platform_info_enabled(struct kvm_vm *vm)
49{ 49{
50 struct kvm_run *run = vcpu_state(vm, VCPU_ID); 50 struct kvm_run *run = vcpu_state(vm, VCPU_ID);
51 struct guest_args args; 51 struct ucall uc;
52 52
53 set_msr_platform_info_enabled(vm, true); 53 set_msr_platform_info_enabled(vm, true);
54 vcpu_run(vm, VCPU_ID); 54 vcpu_run(vm, VCPU_ID);
@@ -56,11 +56,11 @@ static void test_msr_platform_info_enabled(struct kvm_vm *vm)
56 "Exit_reason other than KVM_EXIT_IO: %u (%s),\n", 56 "Exit_reason other than KVM_EXIT_IO: %u (%s),\n",
57 run->exit_reason, 57 run->exit_reason,
58 exit_reason_str(run->exit_reason)); 58 exit_reason_str(run->exit_reason));
59 guest_args_read(vm, VCPU_ID, &args); 59 get_ucall(vm, VCPU_ID, &uc);
60 TEST_ASSERT(args.port == GUEST_PORT_SYNC, 60 TEST_ASSERT(uc.cmd == UCALL_SYNC,
61 "Received IO from port other than PORT_HOST_SYNC: %u\n", 61 "Received ucall other than UCALL_SYNC: %u\n",
62 run->io.port); 62 ucall);
63 TEST_ASSERT((args.arg1 & MSR_PLATFORM_INFO_MAX_TURBO_RATIO) == 63 TEST_ASSERT((uc.args[1] & MSR_PLATFORM_INFO_MAX_TURBO_RATIO) ==
64 MSR_PLATFORM_INFO_MAX_TURBO_RATIO, 64 MSR_PLATFORM_INFO_MAX_TURBO_RATIO,
65 "Expected MSR_PLATFORM_INFO to have max turbo ratio mask: %i.", 65 "Expected MSR_PLATFORM_INFO to have max turbo ratio mask: %i.",
66 MSR_PLATFORM_INFO_MAX_TURBO_RATIO); 66 MSR_PLATFORM_INFO_MAX_TURBO_RATIO);
diff --git a/tools/testing/selftests/kvm/set_sregs_test.c b/tools/testing/selftests/kvm/x86_64/set_sregs_test.c
index 881419d5746e..35640e8e95bc 100644
--- a/tools/testing/selftests/kvm/set_sregs_test.c
+++ b/tools/testing/selftests/kvm/x86_64/set_sregs_test.c
@@ -22,7 +22,7 @@
22#include "test_util.h" 22#include "test_util.h"
23 23
24#include "kvm_util.h" 24#include "kvm_util.h"
25#include "x86.h" 25#include "processor.h"
26 26
27#define VCPU_ID 5 27#define VCPU_ID 5
28 28
diff --git a/tools/testing/selftests/kvm/state_test.c b/tools/testing/selftests/kvm/x86_64/state_test.c
index 900e3e9dfb9f..03da41f0f736 100644
--- a/tools/testing/selftests/kvm/state_test.c
+++ b/tools/testing/selftests/kvm/x86_64/state_test.c
@@ -17,7 +17,7 @@
17#include "test_util.h" 17#include "test_util.h"
18 18
19#include "kvm_util.h" 19#include "kvm_util.h"
20#include "x86.h" 20#include "processor.h"
21#include "vmx.h" 21#include "vmx.h"
22 22
23#define VCPU_ID 5 23#define VCPU_ID 5
@@ -26,20 +26,20 @@ static bool have_nested_state;
26 26
27void l2_guest_code(void) 27void l2_guest_code(void)
28{ 28{
29 GUEST_SYNC(5); 29 GUEST_SYNC(6);
30 30
31 /* Exit to L1 */ 31 /* Exit to L1 */
32 vmcall(); 32 vmcall();
33 33
34 /* L1 has now set up a shadow VMCS for us. */ 34 /* L1 has now set up a shadow VMCS for us. */
35 GUEST_ASSERT(vmreadz(GUEST_RIP) == 0xc0ffee); 35 GUEST_ASSERT(vmreadz(GUEST_RIP) == 0xc0ffee);
36 GUEST_SYNC(9); 36 GUEST_SYNC(10);
37 GUEST_ASSERT(vmreadz(GUEST_RIP) == 0xc0ffee); 37 GUEST_ASSERT(vmreadz(GUEST_RIP) == 0xc0ffee);
38 GUEST_ASSERT(!vmwrite(GUEST_RIP, 0xc0fffee)); 38 GUEST_ASSERT(!vmwrite(GUEST_RIP, 0xc0fffee));
39 GUEST_SYNC(10); 39 GUEST_SYNC(11);
40 GUEST_ASSERT(vmreadz(GUEST_RIP) == 0xc0fffee); 40 GUEST_ASSERT(vmreadz(GUEST_RIP) == 0xc0fffee);
41 GUEST_ASSERT(!vmwrite(GUEST_RIP, 0xc0ffffee)); 41 GUEST_ASSERT(!vmwrite(GUEST_RIP, 0xc0ffffee));
42 GUEST_SYNC(11); 42 GUEST_SYNC(12);
43 43
44 /* Done, exit to L1 and never come back. */ 44 /* Done, exit to L1 and never come back. */
45 vmcall(); 45 vmcall();
@@ -52,15 +52,17 @@ void l1_guest_code(struct vmx_pages *vmx_pages)
52 52
53 GUEST_ASSERT(vmx_pages->vmcs_gpa); 53 GUEST_ASSERT(vmx_pages->vmcs_gpa);
54 GUEST_ASSERT(prepare_for_vmx_operation(vmx_pages)); 54 GUEST_ASSERT(prepare_for_vmx_operation(vmx_pages));
55 GUEST_SYNC(3);
56 GUEST_ASSERT(load_vmcs(vmx_pages));
55 GUEST_ASSERT(vmptrstz() == vmx_pages->vmcs_gpa); 57 GUEST_ASSERT(vmptrstz() == vmx_pages->vmcs_gpa);
56 58
57 GUEST_SYNC(3); 59 GUEST_SYNC(4);
58 GUEST_ASSERT(vmptrstz() == vmx_pages->vmcs_gpa); 60 GUEST_ASSERT(vmptrstz() == vmx_pages->vmcs_gpa);
59 61
60 prepare_vmcs(vmx_pages, l2_guest_code, 62 prepare_vmcs(vmx_pages, l2_guest_code,
61 &l2_guest_stack[L2_GUEST_STACK_SIZE]); 63 &l2_guest_stack[L2_GUEST_STACK_SIZE]);
62 64
63 GUEST_SYNC(4); 65 GUEST_SYNC(5);
64 GUEST_ASSERT(vmptrstz() == vmx_pages->vmcs_gpa); 66 GUEST_ASSERT(vmptrstz() == vmx_pages->vmcs_gpa);
65 GUEST_ASSERT(!vmlaunch()); 67 GUEST_ASSERT(!vmlaunch());
66 GUEST_ASSERT(vmptrstz() == vmx_pages->vmcs_gpa); 68 GUEST_ASSERT(vmptrstz() == vmx_pages->vmcs_gpa);
@@ -72,7 +74,7 @@ void l1_guest_code(struct vmx_pages *vmx_pages)
72 GUEST_ASSERT(!vmresume()); 74 GUEST_ASSERT(!vmresume());
73 GUEST_ASSERT(vmreadz(VM_EXIT_REASON) == EXIT_REASON_VMCALL); 75 GUEST_ASSERT(vmreadz(VM_EXIT_REASON) == EXIT_REASON_VMCALL);
74 76
75 GUEST_SYNC(6); 77 GUEST_SYNC(7);
76 GUEST_ASSERT(vmreadz(VM_EXIT_REASON) == EXIT_REASON_VMCALL); 78 GUEST_ASSERT(vmreadz(VM_EXIT_REASON) == EXIT_REASON_VMCALL);
77 79
78 GUEST_ASSERT(!vmresume()); 80 GUEST_ASSERT(!vmresume());
@@ -85,12 +87,12 @@ void l1_guest_code(struct vmx_pages *vmx_pages)
85 87
86 GUEST_ASSERT(!vmptrld(vmx_pages->shadow_vmcs_gpa)); 88 GUEST_ASSERT(!vmptrld(vmx_pages->shadow_vmcs_gpa));
87 GUEST_ASSERT(vmlaunch()); 89 GUEST_ASSERT(vmlaunch());
88 GUEST_SYNC(7); 90 GUEST_SYNC(8);
89 GUEST_ASSERT(vmlaunch()); 91 GUEST_ASSERT(vmlaunch());
90 GUEST_ASSERT(vmresume()); 92 GUEST_ASSERT(vmresume());
91 93
92 vmwrite(GUEST_RIP, 0xc0ffee); 94 vmwrite(GUEST_RIP, 0xc0ffee);
93 GUEST_SYNC(8); 95 GUEST_SYNC(9);
94 GUEST_ASSERT(vmreadz(GUEST_RIP) == 0xc0ffee); 96 GUEST_ASSERT(vmreadz(GUEST_RIP) == 0xc0ffee);
95 97
96 GUEST_ASSERT(!vmptrld(vmx_pages->vmcs_gpa)); 98 GUEST_ASSERT(!vmptrld(vmx_pages->vmcs_gpa));
@@ -101,7 +103,7 @@ void l1_guest_code(struct vmx_pages *vmx_pages)
101 GUEST_ASSERT(vmreadz(GUEST_RIP) == 0xc0ffffee); 103 GUEST_ASSERT(vmreadz(GUEST_RIP) == 0xc0ffffee);
102 GUEST_ASSERT(vmlaunch()); 104 GUEST_ASSERT(vmlaunch());
103 GUEST_ASSERT(vmresume()); 105 GUEST_ASSERT(vmresume());
104 GUEST_SYNC(12); 106 GUEST_SYNC(13);
105 GUEST_ASSERT(vmreadz(GUEST_RIP) == 0xc0ffffee); 107 GUEST_ASSERT(vmreadz(GUEST_RIP) == 0xc0ffffee);
106 GUEST_ASSERT(vmlaunch()); 108 GUEST_ASSERT(vmlaunch());
107 GUEST_ASSERT(vmresume()); 109 GUEST_ASSERT(vmresume());
@@ -127,6 +129,7 @@ int main(int argc, char *argv[])
127 struct kvm_vm *vm; 129 struct kvm_vm *vm;
128 struct kvm_run *run; 130 struct kvm_run *run;
129 struct kvm_x86_state *state; 131 struct kvm_x86_state *state;
132 struct ucall uc;
130 int stage; 133 int stage;
131 134
132 struct kvm_cpuid_entry2 *entry = kvm_get_supported_cpuid_entry(1); 135 struct kvm_cpuid_entry2 *entry = kvm_get_supported_cpuid_entry(1);
@@ -155,23 +158,23 @@ int main(int argc, char *argv[])
155 158
156 memset(&regs1, 0, sizeof(regs1)); 159 memset(&regs1, 0, sizeof(regs1));
157 vcpu_regs_get(vm, VCPU_ID, &regs1); 160 vcpu_regs_get(vm, VCPU_ID, &regs1);
158 switch (run->io.port) { 161 switch (get_ucall(vm, VCPU_ID, &uc)) {
159 case GUEST_PORT_ABORT: 162 case UCALL_ABORT:
160 TEST_ASSERT(false, "%s at %s:%d", (const char *) regs1.rdi, 163 TEST_ASSERT(false, "%s at %s:%d", (const char *)uc.args[0],
161 __FILE__, regs1.rsi); 164 __FILE__, uc.args[1]);
162 /* NOT REACHED */ 165 /* NOT REACHED */
163 case GUEST_PORT_SYNC: 166 case UCALL_SYNC:
164 break; 167 break;
165 case GUEST_PORT_DONE: 168 case UCALL_DONE:
166 goto done; 169 goto done;
167 default: 170 default:
168 TEST_ASSERT(false, "Unknown port 0x%x.", run->io.port); 171 TEST_ASSERT(false, "Unknown ucall 0x%x.", uc.cmd);
169 } 172 }
170 173
171 /* PORT_SYNC is handled here. */ 174 /* UCALL_SYNC is handled here. */
172 TEST_ASSERT(!strcmp((const char *)regs1.rdi, "hello") && 175 TEST_ASSERT(!strcmp((const char *)uc.args[0], "hello") &&
173 regs1.rsi == stage, "Unexpected register values vmexit #%lx, got %lx", 176 uc.args[1] == stage, "Unexpected register values vmexit #%lx, got %lx",
174 stage, (ulong) regs1.rsi); 177 stage, (ulong)uc.args[1]);
175 178
176 state = vcpu_save_state(vm, VCPU_ID); 179 state = vcpu_save_state(vm, VCPU_ID);
177 kvm_vm_release(vm); 180 kvm_vm_release(vm);
diff --git a/tools/testing/selftests/kvm/sync_regs_test.c b/tools/testing/selftests/kvm/x86_64/sync_regs_test.c
index 213343e5dff9..c8478ce9ea77 100644
--- a/tools/testing/selftests/kvm/sync_regs_test.c
+++ b/tools/testing/selftests/kvm/x86_64/sync_regs_test.c
@@ -19,7 +19,7 @@
19 19
20#include "test_util.h" 20#include "test_util.h"
21#include "kvm_util.h" 21#include "kvm_util.h"
22#include "x86.h" 22#include "processor.h"
23 23
24#define VCPU_ID 5 24#define VCPU_ID 5
25 25
diff --git a/tools/testing/selftests/kvm/vmx_tsc_adjust_test.c b/tools/testing/selftests/kvm/x86_64/vmx_tsc_adjust_test.c
index 49bcc68b0235..18fa64db0d7a 100644
--- a/tools/testing/selftests/kvm/vmx_tsc_adjust_test.c
+++ b/tools/testing/selftests/kvm/x86_64/vmx_tsc_adjust_test.c
@@ -1,5 +1,5 @@
1/* 1/*
2 * gtests/tests/vmx_tsc_adjust_test.c 2 * vmx_tsc_adjust_test
3 * 3 *
4 * Copyright (C) 2018, Google LLC. 4 * Copyright (C) 2018, Google LLC.
5 * 5 *
@@ -22,13 +22,13 @@
22 22
23#include "test_util.h" 23#include "test_util.h"
24#include "kvm_util.h" 24#include "kvm_util.h"
25#include "x86.h" 25#include "processor.h"
26#include "vmx.h" 26#include "vmx.h"
27 27
28#include <string.h> 28#include <string.h>
29#include <sys/ioctl.h> 29#include <sys/ioctl.h>
30 30
31#include "../kselftest.h" 31#include "kselftest.h"
32 32
33#ifndef MSR_IA32_TSC_ADJUST 33#ifndef MSR_IA32_TSC_ADJUST
34#define MSR_IA32_TSC_ADJUST 0x3b 34#define MSR_IA32_TSC_ADJUST 0x3b
@@ -94,6 +94,7 @@ static void l1_guest_code(struct vmx_pages *vmx_pages)
94 check_ia32_tsc_adjust(-1 * TSC_ADJUST_VALUE); 94 check_ia32_tsc_adjust(-1 * TSC_ADJUST_VALUE);
95 95
96 GUEST_ASSERT(prepare_for_vmx_operation(vmx_pages)); 96 GUEST_ASSERT(prepare_for_vmx_operation(vmx_pages));
97 GUEST_ASSERT(load_vmcs(vmx_pages));
97 98
98 /* Prepare the VMCS for L2 execution. */ 99 /* Prepare the VMCS for L2 execution. */
99 prepare_vmcs(vmx_pages, l2_guest_code, 100 prepare_vmcs(vmx_pages, l2_guest_code,
@@ -146,26 +147,25 @@ int main(int argc, char *argv[])
146 147
147 for (;;) { 148 for (;;) {
148 volatile struct kvm_run *run = vcpu_state(vm, VCPU_ID); 149 volatile struct kvm_run *run = vcpu_state(vm, VCPU_ID);
149 struct guest_args args; 150 struct ucall uc;
150 151
151 vcpu_run(vm, VCPU_ID); 152 vcpu_run(vm, VCPU_ID);
152 guest_args_read(vm, VCPU_ID, &args);
153 TEST_ASSERT(run->exit_reason == KVM_EXIT_IO, 153 TEST_ASSERT(run->exit_reason == KVM_EXIT_IO,
154 "Got exit_reason other than KVM_EXIT_IO: %u (%s)\n", 154 "Got exit_reason other than KVM_EXIT_IO: %u (%s)\n",
155 run->exit_reason, 155 run->exit_reason,
156 exit_reason_str(run->exit_reason)); 156 exit_reason_str(run->exit_reason));
157 157
158 switch (args.port) { 158 switch (get_ucall(vm, VCPU_ID, &uc)) {
159 case GUEST_PORT_ABORT: 159 case UCALL_ABORT:
160 TEST_ASSERT(false, "%s", (const char *) args.arg0); 160 TEST_ASSERT(false, "%s", (const char *)uc.args[0]);
161 /* NOT REACHED */ 161 /* NOT REACHED */
162 case GUEST_PORT_SYNC: 162 case UCALL_SYNC:
163 report(args.arg1); 163 report(uc.args[1]);
164 break; 164 break;
165 case GUEST_PORT_DONE: 165 case UCALL_DONE:
166 goto done; 166 goto done;
167 default: 167 default:
168 TEST_ASSERT(false, "Unknown port 0x%x.", args.port); 168 TEST_ASSERT(false, "Unknown ucall 0x%x.", uc.cmd);
169 } 169 }
170 } 170 }
171 171
diff --git a/virt/kvm/arm/arm.c b/virt/kvm/arm/arm.c
index 150c8a69cdaf..23774970c9df 100644
--- a/virt/kvm/arm/arm.c
+++ b/virt/kvm/arm/arm.c
@@ -120,8 +120,9 @@ int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
120{ 120{
121 int ret, cpu; 121 int ret, cpu;
122 122
123 if (type) 123 ret = kvm_arm_setup_stage2(kvm, type);
124 return -EINVAL; 124 if (ret)
125 return ret;
125 126
126 kvm->arch.last_vcpu_ran = alloc_percpu(typeof(*kvm->arch.last_vcpu_ran)); 127 kvm->arch.last_vcpu_ran = alloc_percpu(typeof(*kvm->arch.last_vcpu_ran));
127 if (!kvm->arch.last_vcpu_ran) 128 if (!kvm->arch.last_vcpu_ran)
@@ -212,6 +213,7 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
212 case KVM_CAP_READONLY_MEM: 213 case KVM_CAP_READONLY_MEM:
213 case KVM_CAP_MP_STATE: 214 case KVM_CAP_MP_STATE:
214 case KVM_CAP_IMMEDIATE_EXIT: 215 case KVM_CAP_IMMEDIATE_EXIT:
216 case KVM_CAP_VCPU_EVENTS:
215 r = 1; 217 r = 1;
216 break; 218 break;
217 case KVM_CAP_ARM_SET_DEVICE_ADDR: 219 case KVM_CAP_ARM_SET_DEVICE_ADDR:
@@ -240,7 +242,7 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
240 r = 1; 242 r = 1;
241 break; 243 break;
242 default: 244 default:
243 r = kvm_arch_dev_ioctl_check_extension(kvm, ext); 245 r = kvm_arch_vm_ioctl_check_extension(kvm, ext);
244 break; 246 break;
245 } 247 }
246 return r; 248 return r;
@@ -544,7 +546,7 @@ static void update_vttbr(struct kvm *kvm)
544 546
545 /* update vttbr to be used with the new vmid */ 547 /* update vttbr to be used with the new vmid */
546 pgd_phys = virt_to_phys(kvm->arch.pgd); 548 pgd_phys = virt_to_phys(kvm->arch.pgd);
547 BUG_ON(pgd_phys & ~VTTBR_BADDR_MASK); 549 BUG_ON(pgd_phys & ~kvm_vttbr_baddr_mask(kvm));
548 vmid = ((u64)(kvm->arch.vmid) << VTTBR_VMID_SHIFT) & VTTBR_VMID_MASK(kvm_vmid_bits); 550 vmid = ((u64)(kvm->arch.vmid) << VTTBR_VMID_SHIFT) & VTTBR_VMID_MASK(kvm_vmid_bits);
549 kvm->arch.vttbr = kvm_phys_to_vttbr(pgd_phys) | vmid | cnp; 551 kvm->arch.vttbr = kvm_phys_to_vttbr(pgd_phys) | vmid | cnp;
550 552
@@ -1295,8 +1297,6 @@ static void cpu_init_hyp_mode(void *dummy)
1295 1297
1296 __cpu_init_hyp_mode(pgd_ptr, hyp_stack_ptr, vector_ptr); 1298 __cpu_init_hyp_mode(pgd_ptr, hyp_stack_ptr, vector_ptr);
1297 __cpu_init_stage2(); 1299 __cpu_init_stage2();
1298
1299 kvm_arm_init_debug();
1300} 1300}
1301 1301
1302static void cpu_hyp_reset(void) 1302static void cpu_hyp_reset(void)
@@ -1309,16 +1309,12 @@ static void cpu_hyp_reinit(void)
1309{ 1309{
1310 cpu_hyp_reset(); 1310 cpu_hyp_reset();
1311 1311
1312 if (is_kernel_in_hyp_mode()) { 1312 if (is_kernel_in_hyp_mode())
1313 /*
1314 * __cpu_init_stage2() is safe to call even if the PM
1315 * event was cancelled before the CPU was reset.
1316 */
1317 __cpu_init_stage2();
1318 kvm_timer_init_vhe(); 1313 kvm_timer_init_vhe();
1319 } else { 1314 else
1320 cpu_init_hyp_mode(NULL); 1315 cpu_init_hyp_mode(NULL);
1321 } 1316
1317 kvm_arm_init_debug();
1322 1318
1323 if (vgic_present) 1319 if (vgic_present)
1324 kvm_vgic_init_cpu_hardware(); 1320 kvm_vgic_init_cpu_hardware();
@@ -1412,6 +1408,8 @@ static int init_common_resources(void)
1412 kvm_vmid_bits = kvm_get_vmid_bits(); 1408 kvm_vmid_bits = kvm_get_vmid_bits();
1413 kvm_info("%d-bit VMID\n", kvm_vmid_bits); 1409 kvm_info("%d-bit VMID\n", kvm_vmid_bits);
1414 1410
1411 kvm_set_ipa_limit();
1412
1415 return 0; 1413 return 0;
1416} 1414}
1417 1415
diff --git a/virt/kvm/arm/mmu.c b/virt/kvm/arm/mmu.c
index 1a2c3a1c56ce..5eca48bdb1a6 100644
--- a/virt/kvm/arm/mmu.c
+++ b/virt/kvm/arm/mmu.c
@@ -45,7 +45,6 @@ static phys_addr_t hyp_idmap_vector;
45 45
46static unsigned long io_map_base; 46static unsigned long io_map_base;
47 47
48#define S2_PGD_SIZE (PTRS_PER_S2_PGD * sizeof(pgd_t))
49#define hyp_pgd_order get_order(PTRS_PER_PGD * sizeof(pgd_t)) 48#define hyp_pgd_order get_order(PTRS_PER_PGD * sizeof(pgd_t))
50 49
51#define KVM_S2PTE_FLAG_IS_IOMAP (1UL << 0) 50#define KVM_S2PTE_FLAG_IS_IOMAP (1UL << 0)
@@ -150,20 +149,20 @@ static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
150 149
151static void clear_stage2_pgd_entry(struct kvm *kvm, pgd_t *pgd, phys_addr_t addr) 150static void clear_stage2_pgd_entry(struct kvm *kvm, pgd_t *pgd, phys_addr_t addr)
152{ 151{
153 pud_t *pud_table __maybe_unused = stage2_pud_offset(pgd, 0UL); 152 pud_t *pud_table __maybe_unused = stage2_pud_offset(kvm, pgd, 0UL);
154 stage2_pgd_clear(pgd); 153 stage2_pgd_clear(kvm, pgd);
155 kvm_tlb_flush_vmid_ipa(kvm, addr); 154 kvm_tlb_flush_vmid_ipa(kvm, addr);
156 stage2_pud_free(pud_table); 155 stage2_pud_free(kvm, pud_table);
157 put_page(virt_to_page(pgd)); 156 put_page(virt_to_page(pgd));
158} 157}
159 158
160static void clear_stage2_pud_entry(struct kvm *kvm, pud_t *pud, phys_addr_t addr) 159static void clear_stage2_pud_entry(struct kvm *kvm, pud_t *pud, phys_addr_t addr)
161{ 160{
162 pmd_t *pmd_table __maybe_unused = stage2_pmd_offset(pud, 0); 161 pmd_t *pmd_table __maybe_unused = stage2_pmd_offset(kvm, pud, 0);
163 VM_BUG_ON(stage2_pud_huge(*pud)); 162 VM_BUG_ON(stage2_pud_huge(kvm, *pud));
164 stage2_pud_clear(pud); 163 stage2_pud_clear(kvm, pud);
165 kvm_tlb_flush_vmid_ipa(kvm, addr); 164 kvm_tlb_flush_vmid_ipa(kvm, addr);
166 stage2_pmd_free(pmd_table); 165 stage2_pmd_free(kvm, pmd_table);
167 put_page(virt_to_page(pud)); 166 put_page(virt_to_page(pud));
168} 167}
169 168
@@ -252,7 +251,7 @@ static void unmap_stage2_ptes(struct kvm *kvm, pmd_t *pmd,
252 } 251 }
253 } while (pte++, addr += PAGE_SIZE, addr != end); 252 } while (pte++, addr += PAGE_SIZE, addr != end);
254 253
255 if (stage2_pte_table_empty(start_pte)) 254 if (stage2_pte_table_empty(kvm, start_pte))
256 clear_stage2_pmd_entry(kvm, pmd, start_addr); 255 clear_stage2_pmd_entry(kvm, pmd, start_addr);
257} 256}
258 257
@@ -262,9 +261,9 @@ static void unmap_stage2_pmds(struct kvm *kvm, pud_t *pud,
262 phys_addr_t next, start_addr = addr; 261 phys_addr_t next, start_addr = addr;
263 pmd_t *pmd, *start_pmd; 262 pmd_t *pmd, *start_pmd;
264 263
265 start_pmd = pmd = stage2_pmd_offset(pud, addr); 264 start_pmd = pmd = stage2_pmd_offset(kvm, pud, addr);
266 do { 265 do {
267 next = stage2_pmd_addr_end(addr, end); 266 next = stage2_pmd_addr_end(kvm, addr, end);
268 if (!pmd_none(*pmd)) { 267 if (!pmd_none(*pmd)) {
269 if (pmd_thp_or_huge(*pmd)) { 268 if (pmd_thp_or_huge(*pmd)) {
270 pmd_t old_pmd = *pmd; 269 pmd_t old_pmd = *pmd;
@@ -281,7 +280,7 @@ static void unmap_stage2_pmds(struct kvm *kvm, pud_t *pud,
281 } 280 }
282 } while (pmd++, addr = next, addr != end); 281 } while (pmd++, addr = next, addr != end);
283 282
284 if (stage2_pmd_table_empty(start_pmd)) 283 if (stage2_pmd_table_empty(kvm, start_pmd))
285 clear_stage2_pud_entry(kvm, pud, start_addr); 284 clear_stage2_pud_entry(kvm, pud, start_addr);
286} 285}
287 286
@@ -291,14 +290,14 @@ static void unmap_stage2_puds(struct kvm *kvm, pgd_t *pgd,
291 phys_addr_t next, start_addr = addr; 290 phys_addr_t next, start_addr = addr;
292 pud_t *pud, *start_pud; 291 pud_t *pud, *start_pud;
293 292
294 start_pud = pud = stage2_pud_offset(pgd, addr); 293 start_pud = pud = stage2_pud_offset(kvm, pgd, addr);
295 do { 294 do {
296 next = stage2_pud_addr_end(addr, end); 295 next = stage2_pud_addr_end(kvm, addr, end);
297 if (!stage2_pud_none(*pud)) { 296 if (!stage2_pud_none(kvm, *pud)) {
298 if (stage2_pud_huge(*pud)) { 297 if (stage2_pud_huge(kvm, *pud)) {
299 pud_t old_pud = *pud; 298 pud_t old_pud = *pud;
300 299
301 stage2_pud_clear(pud); 300 stage2_pud_clear(kvm, pud);
302 kvm_tlb_flush_vmid_ipa(kvm, addr); 301 kvm_tlb_flush_vmid_ipa(kvm, addr);
303 kvm_flush_dcache_pud(old_pud); 302 kvm_flush_dcache_pud(old_pud);
304 put_page(virt_to_page(pud)); 303 put_page(virt_to_page(pud));
@@ -308,7 +307,7 @@ static void unmap_stage2_puds(struct kvm *kvm, pgd_t *pgd,
308 } 307 }
309 } while (pud++, addr = next, addr != end); 308 } while (pud++, addr = next, addr != end);
310 309
311 if (stage2_pud_table_empty(start_pud)) 310 if (stage2_pud_table_empty(kvm, start_pud))
312 clear_stage2_pgd_entry(kvm, pgd, start_addr); 311 clear_stage2_pgd_entry(kvm, pgd, start_addr);
313} 312}
314 313
@@ -332,7 +331,7 @@ static void unmap_stage2_range(struct kvm *kvm, phys_addr_t start, u64 size)
332 assert_spin_locked(&kvm->mmu_lock); 331 assert_spin_locked(&kvm->mmu_lock);
333 WARN_ON(size & ~PAGE_MASK); 332 WARN_ON(size & ~PAGE_MASK);
334 333
335 pgd = kvm->arch.pgd + stage2_pgd_index(addr); 334 pgd = kvm->arch.pgd + stage2_pgd_index(kvm, addr);
336 do { 335 do {
337 /* 336 /*
338 * Make sure the page table is still active, as another thread 337 * Make sure the page table is still active, as another thread
@@ -341,8 +340,8 @@ static void unmap_stage2_range(struct kvm *kvm, phys_addr_t start, u64 size)
341 */ 340 */
342 if (!READ_ONCE(kvm->arch.pgd)) 341 if (!READ_ONCE(kvm->arch.pgd))
343 break; 342 break;
344 next = stage2_pgd_addr_end(addr, end); 343 next = stage2_pgd_addr_end(kvm, addr, end);
345 if (!stage2_pgd_none(*pgd)) 344 if (!stage2_pgd_none(kvm, *pgd))
346 unmap_stage2_puds(kvm, pgd, addr, next); 345 unmap_stage2_puds(kvm, pgd, addr, next);
347 /* 346 /*
348 * If the range is too large, release the kvm->mmu_lock 347 * If the range is too large, release the kvm->mmu_lock
@@ -371,9 +370,9 @@ static void stage2_flush_pmds(struct kvm *kvm, pud_t *pud,
371 pmd_t *pmd; 370 pmd_t *pmd;
372 phys_addr_t next; 371 phys_addr_t next;
373 372
374 pmd = stage2_pmd_offset(pud, addr); 373 pmd = stage2_pmd_offset(kvm, pud, addr);
375 do { 374 do {
376 next = stage2_pmd_addr_end(addr, end); 375 next = stage2_pmd_addr_end(kvm, addr, end);
377 if (!pmd_none(*pmd)) { 376 if (!pmd_none(*pmd)) {
378 if (pmd_thp_or_huge(*pmd)) 377 if (pmd_thp_or_huge(*pmd))
379 kvm_flush_dcache_pmd(*pmd); 378 kvm_flush_dcache_pmd(*pmd);
@@ -389,11 +388,11 @@ static void stage2_flush_puds(struct kvm *kvm, pgd_t *pgd,
389 pud_t *pud; 388 pud_t *pud;
390 phys_addr_t next; 389 phys_addr_t next;
391 390
392 pud = stage2_pud_offset(pgd, addr); 391 pud = stage2_pud_offset(kvm, pgd, addr);
393 do { 392 do {
394 next = stage2_pud_addr_end(addr, end); 393 next = stage2_pud_addr_end(kvm, addr, end);
395 if (!stage2_pud_none(*pud)) { 394 if (!stage2_pud_none(kvm, *pud)) {
396 if (stage2_pud_huge(*pud)) 395 if (stage2_pud_huge(kvm, *pud))
397 kvm_flush_dcache_pud(*pud); 396 kvm_flush_dcache_pud(*pud);
398 else 397 else
399 stage2_flush_pmds(kvm, pud, addr, next); 398 stage2_flush_pmds(kvm, pud, addr, next);
@@ -409,10 +408,11 @@ static void stage2_flush_memslot(struct kvm *kvm,
409 phys_addr_t next; 408 phys_addr_t next;
410 pgd_t *pgd; 409 pgd_t *pgd;
411 410
412 pgd = kvm->arch.pgd + stage2_pgd_index(addr); 411 pgd = kvm->arch.pgd + stage2_pgd_index(kvm, addr);
413 do { 412 do {
414 next = stage2_pgd_addr_end(addr, end); 413 next = stage2_pgd_addr_end(kvm, addr, end);
415 stage2_flush_puds(kvm, pgd, addr, next); 414 if (!stage2_pgd_none(kvm, *pgd))
415 stage2_flush_puds(kvm, pgd, addr, next);
416 } while (pgd++, addr = next, addr != end); 416 } while (pgd++, addr = next, addr != end);
417} 417}
418 418
@@ -897,7 +897,7 @@ int kvm_alloc_stage2_pgd(struct kvm *kvm)
897 } 897 }
898 898
899 /* Allocate the HW PGD, making sure that each page gets its own refcount */ 899 /* Allocate the HW PGD, making sure that each page gets its own refcount */
900 pgd = alloc_pages_exact(S2_PGD_SIZE, GFP_KERNEL | __GFP_ZERO); 900 pgd = alloc_pages_exact(stage2_pgd_size(kvm), GFP_KERNEL | __GFP_ZERO);
901 if (!pgd) 901 if (!pgd)
902 return -ENOMEM; 902 return -ENOMEM;
903 903
@@ -986,7 +986,7 @@ void kvm_free_stage2_pgd(struct kvm *kvm)
986 986
987 spin_lock(&kvm->mmu_lock); 987 spin_lock(&kvm->mmu_lock);
988 if (kvm->arch.pgd) { 988 if (kvm->arch.pgd) {
989 unmap_stage2_range(kvm, 0, KVM_PHYS_SIZE); 989 unmap_stage2_range(kvm, 0, kvm_phys_size(kvm));
990 pgd = READ_ONCE(kvm->arch.pgd); 990 pgd = READ_ONCE(kvm->arch.pgd);
991 kvm->arch.pgd = NULL; 991 kvm->arch.pgd = NULL;
992 } 992 }
@@ -994,7 +994,7 @@ void kvm_free_stage2_pgd(struct kvm *kvm)
994 994
995 /* Free the HW pgd, one page at a time */ 995 /* Free the HW pgd, one page at a time */
996 if (pgd) 996 if (pgd)
997 free_pages_exact(pgd, S2_PGD_SIZE); 997 free_pages_exact(pgd, stage2_pgd_size(kvm));
998} 998}
999 999
1000static pud_t *stage2_get_pud(struct kvm *kvm, struct kvm_mmu_memory_cache *cache, 1000static pud_t *stage2_get_pud(struct kvm *kvm, struct kvm_mmu_memory_cache *cache,
@@ -1003,16 +1003,16 @@ static pud_t *stage2_get_pud(struct kvm *kvm, struct kvm_mmu_memory_cache *cache
1003 pgd_t *pgd; 1003 pgd_t *pgd;
1004 pud_t *pud; 1004 pud_t *pud;
1005 1005
1006 pgd = kvm->arch.pgd + stage2_pgd_index(addr); 1006 pgd = kvm->arch.pgd + stage2_pgd_index(kvm, addr);
1007 if (WARN_ON(stage2_pgd_none(*pgd))) { 1007 if (stage2_pgd_none(kvm, *pgd)) {
1008 if (!cache) 1008 if (!cache)
1009 return NULL; 1009 return NULL;
1010 pud = mmu_memory_cache_alloc(cache); 1010 pud = mmu_memory_cache_alloc(cache);
1011 stage2_pgd_populate(pgd, pud); 1011 stage2_pgd_populate(kvm, pgd, pud);
1012 get_page(virt_to_page(pgd)); 1012 get_page(virt_to_page(pgd));
1013 } 1013 }
1014 1014
1015 return stage2_pud_offset(pgd, addr); 1015 return stage2_pud_offset(kvm, pgd, addr);
1016} 1016}
1017 1017
1018static pmd_t *stage2_get_pmd(struct kvm *kvm, struct kvm_mmu_memory_cache *cache, 1018static pmd_t *stage2_get_pmd(struct kvm *kvm, struct kvm_mmu_memory_cache *cache,
@@ -1025,15 +1025,15 @@ static pmd_t *stage2_get_pmd(struct kvm *kvm, struct kvm_mmu_memory_cache *cache
1025 if (!pud) 1025 if (!pud)
1026 return NULL; 1026 return NULL;
1027 1027
1028 if (stage2_pud_none(*pud)) { 1028 if (stage2_pud_none(kvm, *pud)) {
1029 if (!cache) 1029 if (!cache)
1030 return NULL; 1030 return NULL;
1031 pmd = mmu_memory_cache_alloc(cache); 1031 pmd = mmu_memory_cache_alloc(cache);
1032 stage2_pud_populate(pud, pmd); 1032 stage2_pud_populate(kvm, pud, pmd);
1033 get_page(virt_to_page(pud)); 1033 get_page(virt_to_page(pud));
1034 } 1034 }
1035 1035
1036 return stage2_pmd_offset(pud, addr); 1036 return stage2_pmd_offset(kvm, pud, addr);
1037} 1037}
1038 1038
1039static int stage2_set_pmd_huge(struct kvm *kvm, struct kvm_mmu_memory_cache 1039static int stage2_set_pmd_huge(struct kvm *kvm, struct kvm_mmu_memory_cache
@@ -1207,8 +1207,9 @@ int kvm_phys_addr_ioremap(struct kvm *kvm, phys_addr_t guest_ipa,
1207 if (writable) 1207 if (writable)
1208 pte = kvm_s2pte_mkwrite(pte); 1208 pte = kvm_s2pte_mkwrite(pte);
1209 1209
1210 ret = mmu_topup_memory_cache(&cache, KVM_MMU_CACHE_MIN_PAGES, 1210 ret = mmu_topup_memory_cache(&cache,
1211 KVM_NR_MEM_OBJS); 1211 kvm_mmu_cache_min_pages(kvm),
1212 KVM_NR_MEM_OBJS);
1212 if (ret) 1213 if (ret)
1213 goto out; 1214 goto out;
1214 spin_lock(&kvm->mmu_lock); 1215 spin_lock(&kvm->mmu_lock);
@@ -1230,8 +1231,14 @@ static bool transparent_hugepage_adjust(kvm_pfn_t *pfnp, phys_addr_t *ipap)
1230{ 1231{
1231 kvm_pfn_t pfn = *pfnp; 1232 kvm_pfn_t pfn = *pfnp;
1232 gfn_t gfn = *ipap >> PAGE_SHIFT; 1233 gfn_t gfn = *ipap >> PAGE_SHIFT;
1234 struct page *page = pfn_to_page(pfn);
1233 1235
1234 if (PageTransCompoundMap(pfn_to_page(pfn))) { 1236 /*
1237 * PageTransCompoungMap() returns true for THP and
1238 * hugetlbfs. Make sure the adjustment is done only for THP
1239 * pages.
1240 */
1241 if (!PageHuge(page) && PageTransCompoundMap(page)) {
1235 unsigned long mask; 1242 unsigned long mask;
1236 /* 1243 /*
1237 * The address we faulted on is backed by a transparent huge 1244 * The address we faulted on is backed by a transparent huge
@@ -1296,19 +1303,21 @@ static void stage2_wp_ptes(pmd_t *pmd, phys_addr_t addr, phys_addr_t end)
1296 1303
1297/** 1304/**
1298 * stage2_wp_pmds - write protect PUD range 1305 * stage2_wp_pmds - write protect PUD range
1306 * kvm: kvm instance for the VM
1299 * @pud: pointer to pud entry 1307 * @pud: pointer to pud entry
1300 * @addr: range start address 1308 * @addr: range start address
1301 * @end: range end address 1309 * @end: range end address
1302 */ 1310 */
1303static void stage2_wp_pmds(pud_t *pud, phys_addr_t addr, phys_addr_t end) 1311static void stage2_wp_pmds(struct kvm *kvm, pud_t *pud,
1312 phys_addr_t addr, phys_addr_t end)
1304{ 1313{
1305 pmd_t *pmd; 1314 pmd_t *pmd;
1306 phys_addr_t next; 1315 phys_addr_t next;
1307 1316
1308 pmd = stage2_pmd_offset(pud, addr); 1317 pmd = stage2_pmd_offset(kvm, pud, addr);
1309 1318
1310 do { 1319 do {
1311 next = stage2_pmd_addr_end(addr, end); 1320 next = stage2_pmd_addr_end(kvm, addr, end);
1312 if (!pmd_none(*pmd)) { 1321 if (!pmd_none(*pmd)) {
1313 if (pmd_thp_or_huge(*pmd)) { 1322 if (pmd_thp_or_huge(*pmd)) {
1314 if (!kvm_s2pmd_readonly(pmd)) 1323 if (!kvm_s2pmd_readonly(pmd))
@@ -1328,18 +1337,19 @@ static void stage2_wp_pmds(pud_t *pud, phys_addr_t addr, phys_addr_t end)
1328 * 1337 *
1329 * Process PUD entries, for a huge PUD we cause a panic. 1338 * Process PUD entries, for a huge PUD we cause a panic.
1330 */ 1339 */
1331static void stage2_wp_puds(pgd_t *pgd, phys_addr_t addr, phys_addr_t end) 1340static void stage2_wp_puds(struct kvm *kvm, pgd_t *pgd,
1341 phys_addr_t addr, phys_addr_t end)
1332{ 1342{
1333 pud_t *pud; 1343 pud_t *pud;
1334 phys_addr_t next; 1344 phys_addr_t next;
1335 1345
1336 pud = stage2_pud_offset(pgd, addr); 1346 pud = stage2_pud_offset(kvm, pgd, addr);
1337 do { 1347 do {
1338 next = stage2_pud_addr_end(addr, end); 1348 next = stage2_pud_addr_end(kvm, addr, end);
1339 if (!stage2_pud_none(*pud)) { 1349 if (!stage2_pud_none(kvm, *pud)) {
1340 /* TODO:PUD not supported, revisit later if supported */ 1350 /* TODO:PUD not supported, revisit later if supported */
1341 BUG_ON(stage2_pud_huge(*pud)); 1351 BUG_ON(stage2_pud_huge(kvm, *pud));
1342 stage2_wp_pmds(pud, addr, next); 1352 stage2_wp_pmds(kvm, pud, addr, next);
1343 } 1353 }
1344 } while (pud++, addr = next, addr != end); 1354 } while (pud++, addr = next, addr != end);
1345} 1355}
@@ -1355,7 +1365,7 @@ static void stage2_wp_range(struct kvm *kvm, phys_addr_t addr, phys_addr_t end)
1355 pgd_t *pgd; 1365 pgd_t *pgd;
1356 phys_addr_t next; 1366 phys_addr_t next;
1357 1367
1358 pgd = kvm->arch.pgd + stage2_pgd_index(addr); 1368 pgd = kvm->arch.pgd + stage2_pgd_index(kvm, addr);
1359 do { 1369 do {
1360 /* 1370 /*
1361 * Release kvm_mmu_lock periodically if the memory region is 1371 * Release kvm_mmu_lock periodically if the memory region is
@@ -1369,9 +1379,9 @@ static void stage2_wp_range(struct kvm *kvm, phys_addr_t addr, phys_addr_t end)
1369 cond_resched_lock(&kvm->mmu_lock); 1379 cond_resched_lock(&kvm->mmu_lock);
1370 if (!READ_ONCE(kvm->arch.pgd)) 1380 if (!READ_ONCE(kvm->arch.pgd))
1371 break; 1381 break;
1372 next = stage2_pgd_addr_end(addr, end); 1382 next = stage2_pgd_addr_end(kvm, addr, end);
1373 if (stage2_pgd_present(*pgd)) 1383 if (stage2_pgd_present(kvm, *pgd))
1374 stage2_wp_puds(pgd, addr, next); 1384 stage2_wp_puds(kvm, pgd, addr, next);
1375 } while (pgd++, addr = next, addr != end); 1385 } while (pgd++, addr = next, addr != end);
1376} 1386}
1377 1387
@@ -1514,7 +1524,7 @@ static int user_mem_abort(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa,
1514 up_read(&current->mm->mmap_sem); 1524 up_read(&current->mm->mmap_sem);
1515 1525
1516 /* We need minimum second+third level pages */ 1526 /* We need minimum second+third level pages */
1517 ret = mmu_topup_memory_cache(memcache, KVM_MMU_CACHE_MIN_PAGES, 1527 ret = mmu_topup_memory_cache(memcache, kvm_mmu_cache_min_pages(kvm),
1518 KVM_NR_MEM_OBJS); 1528 KVM_NR_MEM_OBJS);
1519 if (ret) 1529 if (ret)
1520 return ret; 1530 return ret;
@@ -1757,7 +1767,7 @@ int kvm_handle_guest_abort(struct kvm_vcpu *vcpu, struct kvm_run *run)
1757 } 1767 }
1758 1768
1759 /* Userspace should not be able to register out-of-bounds IPAs */ 1769 /* Userspace should not be able to register out-of-bounds IPAs */
1760 VM_BUG_ON(fault_ipa >= KVM_PHYS_SIZE); 1770 VM_BUG_ON(fault_ipa >= kvm_phys_size(vcpu->kvm));
1761 1771
1762 if (fault_status == FSC_ACCESS) { 1772 if (fault_status == FSC_ACCESS) {
1763 handle_access_fault(vcpu, fault_ipa); 1773 handle_access_fault(vcpu, fault_ipa);
@@ -2056,7 +2066,7 @@ int kvm_arch_prepare_memory_region(struct kvm *kvm,
2056 * space addressable by the KVM guest IPA space. 2066 * space addressable by the KVM guest IPA space.
2057 */ 2067 */
2058 if (memslot->base_gfn + memslot->npages >= 2068 if (memslot->base_gfn + memslot->npages >=
2059 (KVM_PHYS_SIZE >> PAGE_SHIFT)) 2069 (kvm_phys_size(kvm) >> PAGE_SHIFT))
2060 return -EFAULT; 2070 return -EFAULT;
2061 2071
2062 down_read(&current->mm->mmap_sem); 2072 down_read(&current->mm->mmap_sem);
diff --git a/virt/kvm/arm/vgic/vgic-its.c b/virt/kvm/arm/vgic/vgic-its.c
index 12502251727e..eb2a390a6c86 100644
--- a/virt/kvm/arm/vgic/vgic-its.c
+++ b/virt/kvm/arm/vgic/vgic-its.c
@@ -241,13 +241,6 @@ static struct its_ite *find_ite(struct vgic_its *its, u32 device_id,
241 list_for_each_entry(dev, &(its)->device_list, dev_list) \ 241 list_for_each_entry(dev, &(its)->device_list, dev_list) \
242 list_for_each_entry(ite, &(dev)->itt_head, ite_list) 242 list_for_each_entry(ite, &(dev)->itt_head, ite_list)
243 243
244/*
245 * We only implement 48 bits of PA at the moment, although the ITS
246 * supports more. Let's be restrictive here.
247 */
248#define BASER_ADDRESS(x) ((x) & GENMASK_ULL(47, 16))
249#define CBASER_ADDRESS(x) ((x) & GENMASK_ULL(47, 12))
250
251#define GIC_LPI_OFFSET 8192 244#define GIC_LPI_OFFSET 8192
252 245
253#define VITS_TYPER_IDBITS 16 246#define VITS_TYPER_IDBITS 16
@@ -759,6 +752,7 @@ static bool vgic_its_check_id(struct vgic_its *its, u64 baser, u32 id,
759{ 752{
760 int l1_tbl_size = GITS_BASER_NR_PAGES(baser) * SZ_64K; 753 int l1_tbl_size = GITS_BASER_NR_PAGES(baser) * SZ_64K;
761 u64 indirect_ptr, type = GITS_BASER_TYPE(baser); 754 u64 indirect_ptr, type = GITS_BASER_TYPE(baser);
755 phys_addr_t base = GITS_BASER_ADDR_48_to_52(baser);
762 int esz = GITS_BASER_ENTRY_SIZE(baser); 756 int esz = GITS_BASER_ENTRY_SIZE(baser);
763 int index; 757 int index;
764 gfn_t gfn; 758 gfn_t gfn;
@@ -783,7 +777,7 @@ static bool vgic_its_check_id(struct vgic_its *its, u64 baser, u32 id,
783 if (id >= (l1_tbl_size / esz)) 777 if (id >= (l1_tbl_size / esz))
784 return false; 778 return false;
785 779
786 addr = BASER_ADDRESS(baser) + id * esz; 780 addr = base + id * esz;
787 gfn = addr >> PAGE_SHIFT; 781 gfn = addr >> PAGE_SHIFT;
788 782
789 if (eaddr) 783 if (eaddr)
@@ -798,7 +792,7 @@ static bool vgic_its_check_id(struct vgic_its *its, u64 baser, u32 id,
798 792
799 /* Each 1st level entry is represented by a 64-bit value. */ 793 /* Each 1st level entry is represented by a 64-bit value. */
800 if (kvm_read_guest_lock(its->dev->kvm, 794 if (kvm_read_guest_lock(its->dev->kvm,
801 BASER_ADDRESS(baser) + index * sizeof(indirect_ptr), 795 base + index * sizeof(indirect_ptr),
802 &indirect_ptr, sizeof(indirect_ptr))) 796 &indirect_ptr, sizeof(indirect_ptr)))
803 return false; 797 return false;
804 798
@@ -808,11 +802,7 @@ static bool vgic_its_check_id(struct vgic_its *its, u64 baser, u32 id,
808 if (!(indirect_ptr & BIT_ULL(63))) 802 if (!(indirect_ptr & BIT_ULL(63)))
809 return false; 803 return false;
810 804
811 /* 805 /* Mask the guest physical address and calculate the frame number. */
812 * Mask the guest physical address and calculate the frame number.
813 * Any address beyond our supported 48 bits of PA will be caught
814 * by the actual check in the final step.
815 */
816 indirect_ptr &= GENMASK_ULL(51, 16); 806 indirect_ptr &= GENMASK_ULL(51, 16);
817 807
818 /* Find the address of the actual entry */ 808 /* Find the address of the actual entry */
@@ -1304,9 +1294,6 @@ static u64 vgic_sanitise_its_baser(u64 reg)
1304 GITS_BASER_OUTER_CACHEABILITY_SHIFT, 1294 GITS_BASER_OUTER_CACHEABILITY_SHIFT,
1305 vgic_sanitise_outer_cacheability); 1295 vgic_sanitise_outer_cacheability);
1306 1296
1307 /* Bits 15:12 contain bits 51:48 of the PA, which we don't support. */
1308 reg &= ~GENMASK_ULL(15, 12);
1309
1310 /* We support only one (ITS) page size: 64K */ 1297 /* We support only one (ITS) page size: 64K */
1311 reg = (reg & ~GITS_BASER_PAGE_SIZE_MASK) | GITS_BASER_PAGE_SIZE_64K; 1298 reg = (reg & ~GITS_BASER_PAGE_SIZE_MASK) | GITS_BASER_PAGE_SIZE_64K;
1312 1299
@@ -1325,11 +1312,8 @@ static u64 vgic_sanitise_its_cbaser(u64 reg)
1325 GITS_CBASER_OUTER_CACHEABILITY_SHIFT, 1312 GITS_CBASER_OUTER_CACHEABILITY_SHIFT,
1326 vgic_sanitise_outer_cacheability); 1313 vgic_sanitise_outer_cacheability);
1327 1314
1328 /* 1315 /* Sanitise the physical address to be 64k aligned. */
1329 * Sanitise the physical address to be 64k aligned. 1316 reg &= ~GENMASK_ULL(15, 12);
1330 * Also limit the physical addresses to 48 bits.
1331 */
1332 reg &= ~(GENMASK_ULL(51, 48) | GENMASK_ULL(15, 12));
1333 1317
1334 return reg; 1318 return reg;
1335} 1319}
@@ -1375,7 +1359,7 @@ static void vgic_its_process_commands(struct kvm *kvm, struct vgic_its *its)
1375 if (!its->enabled) 1359 if (!its->enabled)
1376 return; 1360 return;
1377 1361
1378 cbaser = CBASER_ADDRESS(its->cbaser); 1362 cbaser = GITS_CBASER_ADDRESS(its->cbaser);
1379 1363
1380 while (its->cwriter != its->creadr) { 1364 while (its->cwriter != its->creadr) {
1381 int ret = kvm_read_guest_lock(kvm, cbaser + its->creadr, 1365 int ret = kvm_read_guest_lock(kvm, cbaser + its->creadr,
@@ -2233,7 +2217,7 @@ static int vgic_its_restore_device_tables(struct vgic_its *its)
2233 if (!(baser & GITS_BASER_VALID)) 2217 if (!(baser & GITS_BASER_VALID))
2234 return 0; 2218 return 0;
2235 2219
2236 l1_gpa = BASER_ADDRESS(baser); 2220 l1_gpa = GITS_BASER_ADDR_48_to_52(baser);
2237 2221
2238 if (baser & GITS_BASER_INDIRECT) { 2222 if (baser & GITS_BASER_INDIRECT) {
2239 l1_esz = GITS_LVL1_ENTRY_SIZE; 2223 l1_esz = GITS_LVL1_ENTRY_SIZE;
@@ -2305,7 +2289,7 @@ static int vgic_its_save_collection_table(struct vgic_its *its)
2305{ 2289{
2306 const struct vgic_its_abi *abi = vgic_its_get_abi(its); 2290 const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2307 u64 baser = its->baser_coll_table; 2291 u64 baser = its->baser_coll_table;
2308 gpa_t gpa = BASER_ADDRESS(baser); 2292 gpa_t gpa = GITS_BASER_ADDR_48_to_52(baser);
2309 struct its_collection *collection; 2293 struct its_collection *collection;
2310 u64 val; 2294 u64 val;
2311 size_t max_size, filled = 0; 2295 size_t max_size, filled = 0;
@@ -2354,7 +2338,7 @@ static int vgic_its_restore_collection_table(struct vgic_its *its)
2354 if (!(baser & GITS_BASER_VALID)) 2338 if (!(baser & GITS_BASER_VALID))
2355 return 0; 2339 return 0;
2356 2340
2357 gpa = BASER_ADDRESS(baser); 2341 gpa = GITS_BASER_ADDR_48_to_52(baser);
2358 2342
2359 max_size = GITS_BASER_NR_PAGES(baser) * SZ_64K; 2343 max_size = GITS_BASER_NR_PAGES(baser) * SZ_64K;
2360 2344
diff --git a/virt/kvm/arm/vgic/vgic-kvm-device.c b/virt/kvm/arm/vgic/vgic-kvm-device.c
index 6ada2432e37c..114dce9f4bf5 100644
--- a/virt/kvm/arm/vgic/vgic-kvm-device.c
+++ b/virt/kvm/arm/vgic/vgic-kvm-device.c
@@ -25,7 +25,7 @@
25int vgic_check_ioaddr(struct kvm *kvm, phys_addr_t *ioaddr, 25int vgic_check_ioaddr(struct kvm *kvm, phys_addr_t *ioaddr,
26 phys_addr_t addr, phys_addr_t alignment) 26 phys_addr_t addr, phys_addr_t alignment)
27{ 27{
28 if (addr & ~KVM_PHYS_MASK) 28 if (addr & ~kvm_phys_mask(kvm))
29 return -E2BIG; 29 return -E2BIG;
30 30
31 if (!IS_ALIGNED(addr, alignment)) 31 if (!IS_ALIGNED(addr, alignment))
diff --git a/virt/kvm/arm/vgic/vgic-mmio-v3.c b/virt/kvm/arm/vgic/vgic-mmio-v3.c
index a2a175b08b17..b3d1f0985117 100644
--- a/virt/kvm/arm/vgic/vgic-mmio-v3.c
+++ b/virt/kvm/arm/vgic/vgic-mmio-v3.c
@@ -364,7 +364,6 @@ static u64 vgic_sanitise_pendbaser(u64 reg)
364 vgic_sanitise_outer_cacheability); 364 vgic_sanitise_outer_cacheability);
365 365
366 reg &= ~PENDBASER_RES0_MASK; 366 reg &= ~PENDBASER_RES0_MASK;
367 reg &= ~GENMASK_ULL(51, 48);
368 367
369 return reg; 368 return reg;
370} 369}
@@ -382,7 +381,6 @@ static u64 vgic_sanitise_propbaser(u64 reg)
382 vgic_sanitise_outer_cacheability); 381 vgic_sanitise_outer_cacheability);
383 382
384 reg &= ~PROPBASER_RES0_MASK; 383 reg &= ~PROPBASER_RES0_MASK;
385 reg &= ~GENMASK_ULL(51, 48);
386 return reg; 384 return reg;
387} 385}
388 386
diff --git a/virt/kvm/coalesced_mmio.c b/virt/kvm/coalesced_mmio.c
index 9e65feb6fa58..3710342cf6ad 100644
--- a/virt/kvm/coalesced_mmio.c
+++ b/virt/kvm/coalesced_mmio.c
@@ -83,6 +83,7 @@ static int coalesced_mmio_write(struct kvm_vcpu *vcpu,
83 ring->coalesced_mmio[ring->last].phys_addr = addr; 83 ring->coalesced_mmio[ring->last].phys_addr = addr;
84 ring->coalesced_mmio[ring->last].len = len; 84 ring->coalesced_mmio[ring->last].len = len;
85 memcpy(ring->coalesced_mmio[ring->last].data, val, len); 85 memcpy(ring->coalesced_mmio[ring->last].data, val, len);
86 ring->coalesced_mmio[ring->last].pio = dev->zone.pio;
86 smp_wmb(); 87 smp_wmb();
87 ring->last = (ring->last + 1) % KVM_COALESCED_MMIO_MAX; 88 ring->last = (ring->last + 1) % KVM_COALESCED_MMIO_MAX;
88 spin_unlock(&dev->kvm->ring_lock); 89 spin_unlock(&dev->kvm->ring_lock);
@@ -140,6 +141,9 @@ int kvm_vm_ioctl_register_coalesced_mmio(struct kvm *kvm,
140 int ret; 141 int ret;
141 struct kvm_coalesced_mmio_dev *dev; 142 struct kvm_coalesced_mmio_dev *dev;
142 143
144 if (zone->pio != 1 && zone->pio != 0)
145 return -EINVAL;
146
143 dev = kzalloc(sizeof(struct kvm_coalesced_mmio_dev), GFP_KERNEL); 147 dev = kzalloc(sizeof(struct kvm_coalesced_mmio_dev), GFP_KERNEL);
144 if (!dev) 148 if (!dev)
145 return -ENOMEM; 149 return -ENOMEM;
@@ -149,8 +153,9 @@ int kvm_vm_ioctl_register_coalesced_mmio(struct kvm *kvm,
149 dev->zone = *zone; 153 dev->zone = *zone;
150 154
151 mutex_lock(&kvm->slots_lock); 155 mutex_lock(&kvm->slots_lock);
152 ret = kvm_io_bus_register_dev(kvm, KVM_MMIO_BUS, zone->addr, 156 ret = kvm_io_bus_register_dev(kvm,
153 zone->size, &dev->dev); 157 zone->pio ? KVM_PIO_BUS : KVM_MMIO_BUS,
158 zone->addr, zone->size, &dev->dev);
154 if (ret < 0) 159 if (ret < 0)
155 goto out_free_dev; 160 goto out_free_dev;
156 list_add_tail(&dev->list, &kvm->coalesced_zones); 161 list_add_tail(&dev->list, &kvm->coalesced_zones);
@@ -174,7 +179,8 @@ int kvm_vm_ioctl_unregister_coalesced_mmio(struct kvm *kvm,
174 179
175 list_for_each_entry_safe(dev, tmp, &kvm->coalesced_zones, list) 180 list_for_each_entry_safe(dev, tmp, &kvm->coalesced_zones, list)
176 if (coalesced_mmio_in_range(dev, zone->addr, zone->size)) { 181 if (coalesced_mmio_in_range(dev, zone->addr, zone->size)) {
177 kvm_io_bus_unregister_dev(kvm, KVM_MMIO_BUS, &dev->dev); 182 kvm_io_bus_unregister_dev(kvm,
183 zone->pio ? KVM_PIO_BUS : KVM_MMIO_BUS, &dev->dev);
178 kvm_iodevice_destructor(&dev->dev); 184 kvm_iodevice_destructor(&dev->dev);
179 } 185 }
180 186
diff --git a/virt/kvm/kvm_main.c b/virt/kvm/kvm_main.c
index f986e31fa68c..786ade1843a2 100644
--- a/virt/kvm/kvm_main.c
+++ b/virt/kvm/kvm_main.c
@@ -219,7 +219,7 @@ bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
219 me = get_cpu(); 219 me = get_cpu();
220 220
221 kvm_for_each_vcpu(i, vcpu, kvm) { 221 kvm_for_each_vcpu(i, vcpu, kvm) {
222 if (!test_bit(i, vcpu_bitmap)) 222 if (vcpu_bitmap && !test_bit(i, vcpu_bitmap))
223 continue; 223 continue;
224 224
225 kvm_make_request(req, vcpu); 225 kvm_make_request(req, vcpu);
@@ -243,12 +243,10 @@ bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
243{ 243{
244 cpumask_var_t cpus; 244 cpumask_var_t cpus;
245 bool called; 245 bool called;
246 static unsigned long vcpu_bitmap[BITS_TO_LONGS(KVM_MAX_VCPUS)]
247 = {[0 ... BITS_TO_LONGS(KVM_MAX_VCPUS)-1] = ULONG_MAX};
248 246
249 zalloc_cpumask_var(&cpus, GFP_ATOMIC); 247 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
250 248
251 called = kvm_make_vcpus_request_mask(kvm, req, vcpu_bitmap, cpus); 249 called = kvm_make_vcpus_request_mask(kvm, req, NULL, cpus);
252 250
253 free_cpumask_var(cpus); 251 free_cpumask_var(cpus);
254 return called; 252 return called;
@@ -807,20 +805,25 @@ static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot)
807 * sorted array and known changed memslot position. 805 * sorted array and known changed memslot position.
808 */ 806 */
809static void update_memslots(struct kvm_memslots *slots, 807static void update_memslots(struct kvm_memslots *slots,
810 struct kvm_memory_slot *new) 808 struct kvm_memory_slot *new,
809 enum kvm_mr_change change)
811{ 810{
812 int id = new->id; 811 int id = new->id;
813 int i = slots->id_to_index[id]; 812 int i = slots->id_to_index[id];
814 struct kvm_memory_slot *mslots = slots->memslots; 813 struct kvm_memory_slot *mslots = slots->memslots;
815 814
816 WARN_ON(mslots[i].id != id); 815 WARN_ON(mslots[i].id != id);
817 if (!new->npages) { 816 switch (change) {
818 WARN_ON(!mslots[i].npages); 817 case KVM_MR_CREATE:
819 if (mslots[i].npages) 818 slots->used_slots++;
820 slots->used_slots--; 819 WARN_ON(mslots[i].npages || !new->npages);
821 } else { 820 break;
822 if (!mslots[i].npages) 821 case KVM_MR_DELETE:
823 slots->used_slots++; 822 slots->used_slots--;
823 WARN_ON(new->npages || !mslots[i].npages);
824 break;
825 default:
826 break;
824 } 827 }
825 828
826 while (i < KVM_MEM_SLOTS_NUM - 1 && 829 while (i < KVM_MEM_SLOTS_NUM - 1 &&
@@ -1056,7 +1059,7 @@ int __kvm_set_memory_region(struct kvm *kvm,
1056 memset(&new.arch, 0, sizeof(new.arch)); 1059 memset(&new.arch, 0, sizeof(new.arch));
1057 } 1060 }
1058 1061
1059 update_memslots(slots, &new); 1062 update_memslots(slots, &new, change);
1060 old_memslots = install_new_memslots(kvm, as_id, slots); 1063 old_memslots = install_new_memslots(kvm, as_id, slots);
1061 1064
1062 kvm_arch_commit_memory_region(kvm, mem, &old, &new, change); 1065 kvm_arch_commit_memory_region(kvm, mem, &old, &new, change);
@@ -1311,8 +1314,12 @@ unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
1311EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva); 1314EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
1312 1315
1313/* 1316/*
1314 * If writable is set to false, the hva returned by this function is only 1317 * Return the hva of a @gfn and the R/W attribute if possible.
1315 * allowed to be read. 1318 *
1319 * @slot: the kvm_memory_slot which contains @gfn
1320 * @gfn: the gfn to be translated
1321 * @writable: used to return the read/write attribute of the @slot if the hva
1322 * is valid and @writable is not NULL
1316 */ 1323 */
1317unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot, 1324unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
1318 gfn_t gfn, bool *writable) 1325 gfn_t gfn, bool *writable)
@@ -2946,6 +2953,8 @@ static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
2946#ifdef CONFIG_KVM_MMIO 2953#ifdef CONFIG_KVM_MMIO
2947 case KVM_CAP_COALESCED_MMIO: 2954 case KVM_CAP_COALESCED_MMIO:
2948 return KVM_COALESCED_MMIO_PAGE_OFFSET; 2955 return KVM_COALESCED_MMIO_PAGE_OFFSET;
2956 case KVM_CAP_COALESCED_PIO:
2957 return 1;
2949#endif 2958#endif
2950#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING 2959#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
2951 case KVM_CAP_IRQ_ROUTING: 2960 case KVM_CAP_IRQ_ROUTING: