xref: /linux/arch/arm64/include/asm/kvm_host.h (revision 6e7fd890f1d6ac83805409e9c346240de2705584)
1 /* SPDX-License-Identifier: GPL-2.0-only */
2 /*
3  * Copyright (C) 2012,2013 - ARM Ltd
4  * Author: Marc Zyngier <marc.zyngier@arm.com>
5  *
6  * Derived from arch/arm/include/asm/kvm_host.h:
7  * Copyright (C) 2012 - Virtual Open Systems and Columbia University
8  * Author: Christoffer Dall <c.dall@virtualopensystems.com>
9  */
10 
11 #ifndef __ARM64_KVM_HOST_H__
12 #define __ARM64_KVM_HOST_H__
13 
14 #include <linux/arm-smccc.h>
15 #include <linux/bitmap.h>
16 #include <linux/types.h>
17 #include <linux/jump_label.h>
18 #include <linux/kvm_types.h>
19 #include <linux/maple_tree.h>
20 #include <linux/percpu.h>
21 #include <linux/psci.h>
22 #include <asm/arch_gicv3.h>
23 #include <asm/barrier.h>
24 #include <asm/cpufeature.h>
25 #include <asm/cputype.h>
26 #include <asm/daifflags.h>
27 #include <asm/fpsimd.h>
28 #include <asm/kvm.h>
29 #include <asm/kvm_asm.h>
30 #include <asm/vncr_mapping.h>
31 
32 #define __KVM_HAVE_ARCH_INTC_INITIALIZED
33 
34 #define KVM_HALT_POLL_NS_DEFAULT 500000
35 
36 #include <kvm/arm_vgic.h>
37 #include <kvm/arm_arch_timer.h>
38 #include <kvm/arm_pmu.h>
39 
40 #define KVM_MAX_VCPUS VGIC_V3_MAX_CPUS
41 
42 #define KVM_VCPU_MAX_FEATURES 7
43 #define KVM_VCPU_VALID_FEATURES	(BIT(KVM_VCPU_MAX_FEATURES) - 1)
44 
45 #define KVM_REQ_SLEEP \
46 	KVM_ARCH_REQ_FLAGS(0, KVM_REQUEST_WAIT | KVM_REQUEST_NO_WAKEUP)
47 #define KVM_REQ_IRQ_PENDING	KVM_ARCH_REQ(1)
48 #define KVM_REQ_VCPU_RESET	KVM_ARCH_REQ(2)
49 #define KVM_REQ_RECORD_STEAL	KVM_ARCH_REQ(3)
50 #define KVM_REQ_RELOAD_GICv4	KVM_ARCH_REQ(4)
51 #define KVM_REQ_RELOAD_PMU	KVM_ARCH_REQ(5)
52 #define KVM_REQ_SUSPEND		KVM_ARCH_REQ(6)
53 #define KVM_REQ_RESYNC_PMU_EL0	KVM_ARCH_REQ(7)
54 
55 #define KVM_DIRTY_LOG_MANUAL_CAPS   (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE | \
56 				     KVM_DIRTY_LOG_INITIALLY_SET)
57 
58 #define KVM_HAVE_MMU_RWLOCK
59 
60 /*
61  * Mode of operation configurable with kvm-arm.mode early param.
62  * See Documentation/admin-guide/kernel-parameters.txt for more information.
63  */
64 enum kvm_mode {
65 	KVM_MODE_DEFAULT,
66 	KVM_MODE_PROTECTED,
67 	KVM_MODE_NV,
68 	KVM_MODE_NONE,
69 };
70 #ifdef CONFIG_KVM
71 enum kvm_mode kvm_get_mode(void);
72 #else
73 static inline enum kvm_mode kvm_get_mode(void) { return KVM_MODE_NONE; };
74 #endif
75 
76 DECLARE_STATIC_KEY_FALSE(userspace_irqchip_in_use);
77 
78 extern unsigned int __ro_after_init kvm_sve_max_vl;
79 extern unsigned int __ro_after_init kvm_host_sve_max_vl;
80 int __init kvm_arm_init_sve(void);
81 
82 u32 __attribute_const__ kvm_target_cpu(void);
83 void kvm_reset_vcpu(struct kvm_vcpu *vcpu);
84 void kvm_arm_vcpu_destroy(struct kvm_vcpu *vcpu);
85 
86 struct kvm_hyp_memcache {
87 	phys_addr_t head;
88 	unsigned long nr_pages;
89 };
90 
91 static inline void push_hyp_memcache(struct kvm_hyp_memcache *mc,
92 				     phys_addr_t *p,
93 				     phys_addr_t (*to_pa)(void *virt))
94 {
95 	*p = mc->head;
96 	mc->head = to_pa(p);
97 	mc->nr_pages++;
98 }
99 
100 static inline void *pop_hyp_memcache(struct kvm_hyp_memcache *mc,
101 				     void *(*to_va)(phys_addr_t phys))
102 {
103 	phys_addr_t *p = to_va(mc->head);
104 
105 	if (!mc->nr_pages)
106 		return NULL;
107 
108 	mc->head = *p;
109 	mc->nr_pages--;
110 
111 	return p;
112 }
113 
114 static inline int __topup_hyp_memcache(struct kvm_hyp_memcache *mc,
115 				       unsigned long min_pages,
116 				       void *(*alloc_fn)(void *arg),
117 				       phys_addr_t (*to_pa)(void *virt),
118 				       void *arg)
119 {
120 	while (mc->nr_pages < min_pages) {
121 		phys_addr_t *p = alloc_fn(arg);
122 
123 		if (!p)
124 			return -ENOMEM;
125 		push_hyp_memcache(mc, p, to_pa);
126 	}
127 
128 	return 0;
129 }
130 
131 static inline void __free_hyp_memcache(struct kvm_hyp_memcache *mc,
132 				       void (*free_fn)(void *virt, void *arg),
133 				       void *(*to_va)(phys_addr_t phys),
134 				       void *arg)
135 {
136 	while (mc->nr_pages)
137 		free_fn(pop_hyp_memcache(mc, to_va), arg);
138 }
139 
140 void free_hyp_memcache(struct kvm_hyp_memcache *mc);
141 int topup_hyp_memcache(struct kvm_hyp_memcache *mc, unsigned long min_pages);
142 
143 struct kvm_vmid {
144 	atomic64_t id;
145 };
146 
147 struct kvm_s2_mmu {
148 	struct kvm_vmid vmid;
149 
150 	/*
151 	 * stage2 entry level table
152 	 *
153 	 * Two kvm_s2_mmu structures in the same VM can point to the same
154 	 * pgd here.  This happens when running a guest using a
155 	 * translation regime that isn't affected by its own stage-2
156 	 * translation, such as a non-VHE hypervisor running at vEL2, or
157 	 * for vEL1/EL0 with vHCR_EL2.VM == 0.  In that case, we use the
158 	 * canonical stage-2 page tables.
159 	 */
160 	phys_addr_t	pgd_phys;
161 	struct kvm_pgtable *pgt;
162 
163 	/*
164 	 * VTCR value used on the host. For a non-NV guest (or a NV
165 	 * guest that runs in a context where its own S2 doesn't
166 	 * apply), its T0SZ value reflects that of the IPA size.
167 	 *
168 	 * For a shadow S2 MMU, T0SZ reflects the PARange exposed to
169 	 * the guest.
170 	 */
171 	u64	vtcr;
172 
173 	/* The last vcpu id that ran on each physical CPU */
174 	int __percpu *last_vcpu_ran;
175 
176 #define KVM_ARM_EAGER_SPLIT_CHUNK_SIZE_DEFAULT 0
177 	/*
178 	 * Memory cache used to split
179 	 * KVM_CAP_ARM_EAGER_SPLIT_CHUNK_SIZE worth of huge pages. It
180 	 * is used to allocate stage2 page tables while splitting huge
181 	 * pages. The choice of KVM_CAP_ARM_EAGER_SPLIT_CHUNK_SIZE
182 	 * influences both the capacity of the split page cache, and
183 	 * how often KVM reschedules. Be wary of raising CHUNK_SIZE
184 	 * too high.
185 	 *
186 	 * Protected by kvm->slots_lock.
187 	 */
188 	struct kvm_mmu_memory_cache split_page_cache;
189 	uint64_t split_page_chunk_size;
190 
191 	struct kvm_arch *arch;
192 
193 	/*
194 	 * For a shadow stage-2 MMU, the virtual vttbr used by the
195 	 * host to parse the guest S2.
196 	 * This either contains:
197 	 * - the virtual VTTBR programmed by the guest hypervisor with
198          *   CnP cleared
199 	 * - The value 1 (VMID=0, BADDR=0, CnP=1) if invalid
200 	 *
201 	 * We also cache the full VTCR which gets used for TLB invalidation,
202 	 * taking the ARM ARM's "Any of the bits in VTCR_EL2 are permitted
203 	 * to be cached in a TLB" to the letter.
204 	 */
205 	u64	tlb_vttbr;
206 	u64	tlb_vtcr;
207 
208 	/*
209 	 * true when this represents a nested context where virtual
210 	 * HCR_EL2.VM == 1
211 	 */
212 	bool	nested_stage2_enabled;
213 
214 	/*
215 	 *  0: Nobody is currently using this, check vttbr for validity
216 	 * >0: Somebody is actively using this.
217 	 */
218 	atomic_t refcnt;
219 };
220 
221 struct kvm_arch_memory_slot {
222 };
223 
224 /**
225  * struct kvm_smccc_features: Descriptor of the hypercall services exposed to the guests
226  *
227  * @std_bmap: Bitmap of standard secure service calls
228  * @std_hyp_bmap: Bitmap of standard hypervisor service calls
229  * @vendor_hyp_bmap: Bitmap of vendor specific hypervisor service calls
230  */
231 struct kvm_smccc_features {
232 	unsigned long std_bmap;
233 	unsigned long std_hyp_bmap;
234 	unsigned long vendor_hyp_bmap;
235 };
236 
237 typedef unsigned int pkvm_handle_t;
238 
239 struct kvm_protected_vm {
240 	pkvm_handle_t handle;
241 	struct kvm_hyp_memcache teardown_mc;
242 	bool enabled;
243 };
244 
245 struct kvm_mpidr_data {
246 	u64			mpidr_mask;
247 	DECLARE_FLEX_ARRAY(u16, cmpidr_to_idx);
248 };
249 
250 static inline u16 kvm_mpidr_index(struct kvm_mpidr_data *data, u64 mpidr)
251 {
252 	unsigned long index = 0, mask = data->mpidr_mask;
253 	unsigned long aff = mpidr & MPIDR_HWID_BITMASK;
254 
255 	bitmap_gather(&index, &aff, &mask, fls(mask));
256 
257 	return index;
258 }
259 
260 struct kvm_sysreg_masks;
261 
262 enum fgt_group_id {
263 	__NO_FGT_GROUP__,
264 	HFGxTR_GROUP,
265 	HDFGRTR_GROUP,
266 	HDFGWTR_GROUP = HDFGRTR_GROUP,
267 	HFGITR_GROUP,
268 	HAFGRTR_GROUP,
269 
270 	/* Must be last */
271 	__NR_FGT_GROUP_IDS__
272 };
273 
274 struct kvm_arch {
275 	struct kvm_s2_mmu mmu;
276 
277 	/*
278 	 * Fine-Grained UNDEF, mimicking the FGT layout defined by the
279 	 * architecture. We track them globally, as we present the
280 	 * same feature-set to all vcpus.
281 	 *
282 	 * Index 0 is currently spare.
283 	 */
284 	u64 fgu[__NR_FGT_GROUP_IDS__];
285 
286 	/*
287 	 * Stage 2 paging state for VMs with nested S2 using a virtual
288 	 * VMID.
289 	 */
290 	struct kvm_s2_mmu *nested_mmus;
291 	size_t nested_mmus_size;
292 	int nested_mmus_next;
293 
294 	/* Interrupt controller */
295 	struct vgic_dist	vgic;
296 
297 	/* Timers */
298 	struct arch_timer_vm_data timer_data;
299 
300 	/* Mandated version of PSCI */
301 	u32 psci_version;
302 
303 	/* Protects VM-scoped configuration data */
304 	struct mutex config_lock;
305 
306 	/*
307 	 * If we encounter a data abort without valid instruction syndrome
308 	 * information, report this to user space.  User space can (and
309 	 * should) opt in to this feature if KVM_CAP_ARM_NISV_TO_USER is
310 	 * supported.
311 	 */
312 #define KVM_ARCH_FLAG_RETURN_NISV_IO_ABORT_TO_USER	0
313 	/* Memory Tagging Extension enabled for the guest */
314 #define KVM_ARCH_FLAG_MTE_ENABLED			1
315 	/* At least one vCPU has ran in the VM */
316 #define KVM_ARCH_FLAG_HAS_RAN_ONCE			2
317 	/* The vCPU feature set for the VM is configured */
318 #define KVM_ARCH_FLAG_VCPU_FEATURES_CONFIGURED		3
319 	/* PSCI SYSTEM_SUSPEND enabled for the guest */
320 #define KVM_ARCH_FLAG_SYSTEM_SUSPEND_ENABLED		4
321 	/* VM counter offset */
322 #define KVM_ARCH_FLAG_VM_COUNTER_OFFSET			5
323 	/* Timer PPIs made immutable */
324 #define KVM_ARCH_FLAG_TIMER_PPIS_IMMUTABLE		6
325 	/* Initial ID reg values loaded */
326 #define KVM_ARCH_FLAG_ID_REGS_INITIALIZED		7
327 	/* Fine-Grained UNDEF initialised */
328 #define KVM_ARCH_FLAG_FGU_INITIALIZED			8
329 	unsigned long flags;
330 
331 	/* VM-wide vCPU feature set */
332 	DECLARE_BITMAP(vcpu_features, KVM_VCPU_MAX_FEATURES);
333 
334 	/* MPIDR to vcpu index mapping, optional */
335 	struct kvm_mpidr_data *mpidr_data;
336 
337 	/*
338 	 * VM-wide PMU filter, implemented as a bitmap and big enough for
339 	 * up to 2^10 events (ARMv8.0) or 2^16 events (ARMv8.1+).
340 	 */
341 	unsigned long *pmu_filter;
342 	struct arm_pmu *arm_pmu;
343 
344 	cpumask_var_t supported_cpus;
345 
346 	/* PMCR_EL0.N value for the guest */
347 	u8 pmcr_n;
348 
349 	/* Iterator for idreg debugfs */
350 	u8	idreg_debugfs_iter;
351 
352 	/* Hypercall features firmware registers' descriptor */
353 	struct kvm_smccc_features smccc_feat;
354 	struct maple_tree smccc_filter;
355 
356 	/*
357 	 * Emulated CPU ID registers per VM
358 	 * (Op0, Op1, CRn, CRm, Op2) of the ID registers to be saved in it
359 	 * is (3, 0, 0, crm, op2), where 1<=crm<8, 0<=op2<8.
360 	 *
361 	 * These emulated idregs are VM-wide, but accessed from the context of a vCPU.
362 	 * Atomic access to multiple idregs are guarded by kvm_arch.config_lock.
363 	 */
364 #define IDREG_IDX(id)		(((sys_reg_CRm(id) - 1) << 3) | sys_reg_Op2(id))
365 #define KVM_ARM_ID_REG_NUM	(IDREG_IDX(sys_reg(3, 0, 0, 7, 7)) + 1)
366 	u64 id_regs[KVM_ARM_ID_REG_NUM];
367 
368 	u64 ctr_el0;
369 
370 	/* Masks for VNCR-baked sysregs */
371 	struct kvm_sysreg_masks	*sysreg_masks;
372 
373 	/*
374 	 * For an untrusted host VM, 'pkvm.handle' is used to lookup
375 	 * the associated pKVM instance in the hypervisor.
376 	 */
377 	struct kvm_protected_vm pkvm;
378 };
379 
380 struct kvm_vcpu_fault_info {
381 	u64 esr_el2;		/* Hyp Syndrom Register */
382 	u64 far_el2;		/* Hyp Fault Address Register */
383 	u64 hpfar_el2;		/* Hyp IPA Fault Address Register */
384 	u64 disr_el1;		/* Deferred [SError] Status Register */
385 };
386 
387 /*
388  * VNCR() just places the VNCR_capable registers in the enum after
389  * __VNCR_START__, and the value (after correction) to be an 8-byte offset
390  * from the VNCR base. As we don't require the enum to be otherwise ordered,
391  * we need the terrible hack below to ensure that we correctly size the
392  * sys_regs array, no matter what.
393  *
394  * The __MAX__ macro has been lifted from Sean Eron Anderson's wonderful
395  * treasure trove of bit hacks:
396  * https://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
397  */
398 #define __MAX__(x,y)	((x) ^ (((x) ^ (y)) & -((x) < (y))))
399 #define VNCR(r)						\
400 	__before_##r,					\
401 	r = __VNCR_START__ + ((VNCR_ ## r) / 8),	\
402 	__after_##r = __MAX__(__before_##r - 1, r)
403 
404 enum vcpu_sysreg {
405 	__INVALID_SYSREG__,   /* 0 is reserved as an invalid value */
406 	MPIDR_EL1,	/* MultiProcessor Affinity Register */
407 	CLIDR_EL1,	/* Cache Level ID Register */
408 	CSSELR_EL1,	/* Cache Size Selection Register */
409 	TPIDR_EL0,	/* Thread ID, User R/W */
410 	TPIDRRO_EL0,	/* Thread ID, User R/O */
411 	TPIDR_EL1,	/* Thread ID, Privileged */
412 	CNTKCTL_EL1,	/* Timer Control Register (EL1) */
413 	PAR_EL1,	/* Physical Address Register */
414 	MDCCINT_EL1,	/* Monitor Debug Comms Channel Interrupt Enable Reg */
415 	OSLSR_EL1,	/* OS Lock Status Register */
416 	DISR_EL1,	/* Deferred Interrupt Status Register */
417 
418 	/* Performance Monitors Registers */
419 	PMCR_EL0,	/* Control Register */
420 	PMSELR_EL0,	/* Event Counter Selection Register */
421 	PMEVCNTR0_EL0,	/* Event Counter Register (0-30) */
422 	PMEVCNTR30_EL0 = PMEVCNTR0_EL0 + 30,
423 	PMCCNTR_EL0,	/* Cycle Counter Register */
424 	PMEVTYPER0_EL0,	/* Event Type Register (0-30) */
425 	PMEVTYPER30_EL0 = PMEVTYPER0_EL0 + 30,
426 	PMCCFILTR_EL0,	/* Cycle Count Filter Register */
427 	PMCNTENSET_EL0,	/* Count Enable Set Register */
428 	PMINTENSET_EL1,	/* Interrupt Enable Set Register */
429 	PMOVSSET_EL0,	/* Overflow Flag Status Set Register */
430 	PMUSERENR_EL0,	/* User Enable Register */
431 
432 	/* Pointer Authentication Registers in a strict increasing order. */
433 	APIAKEYLO_EL1,
434 	APIAKEYHI_EL1,
435 	APIBKEYLO_EL1,
436 	APIBKEYHI_EL1,
437 	APDAKEYLO_EL1,
438 	APDAKEYHI_EL1,
439 	APDBKEYLO_EL1,
440 	APDBKEYHI_EL1,
441 	APGAKEYLO_EL1,
442 	APGAKEYHI_EL1,
443 
444 	/* Memory Tagging Extension registers */
445 	RGSR_EL1,	/* Random Allocation Tag Seed Register */
446 	GCR_EL1,	/* Tag Control Register */
447 	TFSRE0_EL1,	/* Tag Fault Status Register (EL0) */
448 
449 	/* 32bit specific registers. */
450 	DACR32_EL2,	/* Domain Access Control Register */
451 	IFSR32_EL2,	/* Instruction Fault Status Register */
452 	FPEXC32_EL2,	/* Floating-Point Exception Control Register */
453 	DBGVCR32_EL2,	/* Debug Vector Catch Register */
454 
455 	/* EL2 registers */
456 	SCTLR_EL2,	/* System Control Register (EL2) */
457 	ACTLR_EL2,	/* Auxiliary Control Register (EL2) */
458 	MDCR_EL2,	/* Monitor Debug Configuration Register (EL2) */
459 	CPTR_EL2,	/* Architectural Feature Trap Register (EL2) */
460 	HACR_EL2,	/* Hypervisor Auxiliary Control Register */
461 	ZCR_EL2,	/* SVE Control Register (EL2) */
462 	TTBR0_EL2,	/* Translation Table Base Register 0 (EL2) */
463 	TTBR1_EL2,	/* Translation Table Base Register 1 (EL2) */
464 	TCR_EL2,	/* Translation Control Register (EL2) */
465 	SPSR_EL2,	/* EL2 saved program status register */
466 	ELR_EL2,	/* EL2 exception link register */
467 	AFSR0_EL2,	/* Auxiliary Fault Status Register 0 (EL2) */
468 	AFSR1_EL2,	/* Auxiliary Fault Status Register 1 (EL2) */
469 	ESR_EL2,	/* Exception Syndrome Register (EL2) */
470 	FAR_EL2,	/* Fault Address Register (EL2) */
471 	HPFAR_EL2,	/* Hypervisor IPA Fault Address Register */
472 	MAIR_EL2,	/* Memory Attribute Indirection Register (EL2) */
473 	AMAIR_EL2,	/* Auxiliary Memory Attribute Indirection Register (EL2) */
474 	VBAR_EL2,	/* Vector Base Address Register (EL2) */
475 	RVBAR_EL2,	/* Reset Vector Base Address Register */
476 	CONTEXTIDR_EL2,	/* Context ID Register (EL2) */
477 	CNTHCTL_EL2,	/* Counter-timer Hypervisor Control register */
478 	SP_EL2,		/* EL2 Stack Pointer */
479 	CNTHP_CTL_EL2,
480 	CNTHP_CVAL_EL2,
481 	CNTHV_CTL_EL2,
482 	CNTHV_CVAL_EL2,
483 
484 	__VNCR_START__,	/* Any VNCR-capable reg goes after this point */
485 
486 	VNCR(SCTLR_EL1),/* System Control Register */
487 	VNCR(ACTLR_EL1),/* Auxiliary Control Register */
488 	VNCR(CPACR_EL1),/* Coprocessor Access Control */
489 	VNCR(ZCR_EL1),	/* SVE Control */
490 	VNCR(TTBR0_EL1),/* Translation Table Base Register 0 */
491 	VNCR(TTBR1_EL1),/* Translation Table Base Register 1 */
492 	VNCR(TCR_EL1),	/* Translation Control Register */
493 	VNCR(TCR2_EL1),	/* Extended Translation Control Register */
494 	VNCR(ESR_EL1),	/* Exception Syndrome Register */
495 	VNCR(AFSR0_EL1),/* Auxiliary Fault Status Register 0 */
496 	VNCR(AFSR1_EL1),/* Auxiliary Fault Status Register 1 */
497 	VNCR(FAR_EL1),	/* Fault Address Register */
498 	VNCR(MAIR_EL1),	/* Memory Attribute Indirection Register */
499 	VNCR(VBAR_EL1),	/* Vector Base Address Register */
500 	VNCR(CONTEXTIDR_EL1),	/* Context ID Register */
501 	VNCR(AMAIR_EL1),/* Aux Memory Attribute Indirection Register */
502 	VNCR(MDSCR_EL1),/* Monitor Debug System Control Register */
503 	VNCR(ELR_EL1),
504 	VNCR(SP_EL1),
505 	VNCR(SPSR_EL1),
506 	VNCR(TFSR_EL1),	/* Tag Fault Status Register (EL1) */
507 	VNCR(VPIDR_EL2),/* Virtualization Processor ID Register */
508 	VNCR(VMPIDR_EL2),/* Virtualization Multiprocessor ID Register */
509 	VNCR(HCR_EL2),	/* Hypervisor Configuration Register */
510 	VNCR(HSTR_EL2),	/* Hypervisor System Trap Register */
511 	VNCR(VTTBR_EL2),/* Virtualization Translation Table Base Register */
512 	VNCR(VTCR_EL2),	/* Virtualization Translation Control Register */
513 	VNCR(TPIDR_EL2),/* EL2 Software Thread ID Register */
514 	VNCR(HCRX_EL2),	/* Extended Hypervisor Configuration Register */
515 
516 	/* Permission Indirection Extension registers */
517 	VNCR(PIR_EL1),	 /* Permission Indirection Register 1 (EL1) */
518 	VNCR(PIRE0_EL1), /*  Permission Indirection Register 0 (EL1) */
519 
520 	VNCR(HFGRTR_EL2),
521 	VNCR(HFGWTR_EL2),
522 	VNCR(HFGITR_EL2),
523 	VNCR(HDFGRTR_EL2),
524 	VNCR(HDFGWTR_EL2),
525 	VNCR(HAFGRTR_EL2),
526 
527 	VNCR(CNTVOFF_EL2),
528 	VNCR(CNTV_CVAL_EL0),
529 	VNCR(CNTV_CTL_EL0),
530 	VNCR(CNTP_CVAL_EL0),
531 	VNCR(CNTP_CTL_EL0),
532 
533 	NR_SYS_REGS	/* Nothing after this line! */
534 };
535 
536 struct kvm_sysreg_masks {
537 	struct {
538 		u64	res0;
539 		u64	res1;
540 	} mask[NR_SYS_REGS - __VNCR_START__];
541 };
542 
543 struct kvm_cpu_context {
544 	struct user_pt_regs regs;	/* sp = sp_el0 */
545 
546 	u64	spsr_abt;
547 	u64	spsr_und;
548 	u64	spsr_irq;
549 	u64	spsr_fiq;
550 
551 	struct user_fpsimd_state fp_regs;
552 
553 	u64 sys_regs[NR_SYS_REGS];
554 
555 	struct kvm_vcpu *__hyp_running_vcpu;
556 
557 	/* This pointer has to be 4kB aligned. */
558 	u64 *vncr_array;
559 };
560 
561 struct cpu_sve_state {
562 	__u64 zcr_el1;
563 
564 	/*
565 	 * Ordering is important since __sve_save_state/__sve_restore_state
566 	 * relies on it.
567 	 */
568 	__u32 fpsr;
569 	__u32 fpcr;
570 
571 	/* Must be SVE_VQ_BYTES (128 bit) aligned. */
572 	__u8 sve_regs[];
573 };
574 
575 /*
576  * This structure is instantiated on a per-CPU basis, and contains
577  * data that is:
578  *
579  * - tied to a single physical CPU, and
580  * - either have a lifetime that does not extend past vcpu_put()
581  * - or is an invariant for the lifetime of the system
582  *
583  * Use host_data_ptr(field) as a way to access a pointer to such a
584  * field.
585  */
586 struct kvm_host_data {
587 	struct kvm_cpu_context host_ctxt;
588 
589 	/*
590 	 * All pointers in this union are hyp VA.
591 	 * sve_state is only used in pKVM and if system_supports_sve().
592 	 */
593 	union {
594 		struct user_fpsimd_state *fpsimd_state;
595 		struct cpu_sve_state *sve_state;
596 	};
597 
598 	/* Ownership of the FP regs */
599 	enum {
600 		FP_STATE_FREE,
601 		FP_STATE_HOST_OWNED,
602 		FP_STATE_GUEST_OWNED,
603 	} fp_owner;
604 
605 	/*
606 	 * host_debug_state contains the host registers which are
607 	 * saved and restored during world switches.
608 	 */
609 	 struct {
610 		/* {Break,watch}point registers */
611 		struct kvm_guest_debug_arch regs;
612 		/* Statistical profiling extension */
613 		u64 pmscr_el1;
614 		/* Self-hosted trace */
615 		u64 trfcr_el1;
616 		/* Values of trap registers for the host before guest entry. */
617 		u64 mdcr_el2;
618 	} host_debug_state;
619 };
620 
621 struct kvm_host_psci_config {
622 	/* PSCI version used by host. */
623 	u32 version;
624 	u32 smccc_version;
625 
626 	/* Function IDs used by host if version is v0.1. */
627 	struct psci_0_1_function_ids function_ids_0_1;
628 
629 	bool psci_0_1_cpu_suspend_implemented;
630 	bool psci_0_1_cpu_on_implemented;
631 	bool psci_0_1_cpu_off_implemented;
632 	bool psci_0_1_migrate_implemented;
633 };
634 
635 extern struct kvm_host_psci_config kvm_nvhe_sym(kvm_host_psci_config);
636 #define kvm_host_psci_config CHOOSE_NVHE_SYM(kvm_host_psci_config)
637 
638 extern s64 kvm_nvhe_sym(hyp_physvirt_offset);
639 #define hyp_physvirt_offset CHOOSE_NVHE_SYM(hyp_physvirt_offset)
640 
641 extern u64 kvm_nvhe_sym(hyp_cpu_logical_map)[NR_CPUS];
642 #define hyp_cpu_logical_map CHOOSE_NVHE_SYM(hyp_cpu_logical_map)
643 
644 struct vcpu_reset_state {
645 	unsigned long	pc;
646 	unsigned long	r0;
647 	bool		be;
648 	bool		reset;
649 };
650 
651 struct kvm_vcpu_arch {
652 	struct kvm_cpu_context ctxt;
653 
654 	/*
655 	 * Guest floating point state
656 	 *
657 	 * The architecture has two main floating point extensions,
658 	 * the original FPSIMD and SVE.  These have overlapping
659 	 * register views, with the FPSIMD V registers occupying the
660 	 * low 128 bits of the SVE Z registers.  When the core
661 	 * floating point code saves the register state of a task it
662 	 * records which view it saved in fp_type.
663 	 */
664 	void *sve_state;
665 	enum fp_type fp_type;
666 	unsigned int sve_max_vl;
667 	u64 svcr;
668 	u64 fpmr;
669 
670 	/* Stage 2 paging state used by the hardware on next switch */
671 	struct kvm_s2_mmu *hw_mmu;
672 
673 	/* Values of trap registers for the guest. */
674 	u64 hcr_el2;
675 	u64 hcrx_el2;
676 	u64 mdcr_el2;
677 	u64 cptr_el2;
678 
679 	/* Exception Information */
680 	struct kvm_vcpu_fault_info fault;
681 
682 	/* Configuration flags, set once and for all before the vcpu can run */
683 	u8 cflags;
684 
685 	/* Input flags to the hypervisor code, potentially cleared after use */
686 	u8 iflags;
687 
688 	/* State flags for kernel bookkeeping, unused by the hypervisor code */
689 	u8 sflags;
690 
691 	/*
692 	 * Don't run the guest (internal implementation need).
693 	 *
694 	 * Contrary to the flags above, this is set/cleared outside of
695 	 * a vcpu context, and thus cannot be mixed with the flags
696 	 * themselves (or the flag accesses need to be made atomic).
697 	 */
698 	bool pause;
699 
700 	/*
701 	 * We maintain more than a single set of debug registers to support
702 	 * debugging the guest from the host and to maintain separate host and
703 	 * guest state during world switches. vcpu_debug_state are the debug
704 	 * registers of the vcpu as the guest sees them.
705 	 *
706 	 * external_debug_state contains the debug values we want to debug the
707 	 * guest. This is set via the KVM_SET_GUEST_DEBUG ioctl.
708 	 *
709 	 * debug_ptr points to the set of debug registers that should be loaded
710 	 * onto the hardware when running the guest.
711 	 */
712 	struct kvm_guest_debug_arch *debug_ptr;
713 	struct kvm_guest_debug_arch vcpu_debug_state;
714 	struct kvm_guest_debug_arch external_debug_state;
715 
716 	/* VGIC state */
717 	struct vgic_cpu vgic_cpu;
718 	struct arch_timer_cpu timer_cpu;
719 	struct kvm_pmu pmu;
720 
721 	/*
722 	 * Guest registers we preserve during guest debugging.
723 	 *
724 	 * These shadow registers are updated by the kvm_handle_sys_reg
725 	 * trap handler if the guest accesses or updates them while we
726 	 * are using guest debug.
727 	 */
728 	struct {
729 		u32	mdscr_el1;
730 		bool	pstate_ss;
731 	} guest_debug_preserved;
732 
733 	/* vcpu power state */
734 	struct kvm_mp_state mp_state;
735 	spinlock_t mp_state_lock;
736 
737 	/* Cache some mmu pages needed inside spinlock regions */
738 	struct kvm_mmu_memory_cache mmu_page_cache;
739 
740 	/* Virtual SError ESR to restore when HCR_EL2.VSE is set */
741 	u64 vsesr_el2;
742 
743 	/* Additional reset state */
744 	struct vcpu_reset_state	reset_state;
745 
746 	/* Guest PV state */
747 	struct {
748 		u64 last_steal;
749 		gpa_t base;
750 	} steal;
751 
752 	/* Per-vcpu CCSIDR override or NULL */
753 	u32 *ccsidr;
754 };
755 
756 /*
757  * Each 'flag' is composed of a comma-separated triplet:
758  *
759  * - the flag-set it belongs to in the vcpu->arch structure
760  * - the value for that flag
761  * - the mask for that flag
762  *
763  *  __vcpu_single_flag() builds such a triplet for a single-bit flag.
764  * unpack_vcpu_flag() extract the flag value from the triplet for
765  * direct use outside of the flag accessors.
766  */
767 #define __vcpu_single_flag(_set, _f)	_set, (_f), (_f)
768 
769 #define __unpack_flag(_set, _f, _m)	_f
770 #define unpack_vcpu_flag(...)		__unpack_flag(__VA_ARGS__)
771 
772 #define __build_check_flag(v, flagset, f, m)			\
773 	do {							\
774 		typeof(v->arch.flagset) *_fset;			\
775 								\
776 		/* Check that the flags fit in the mask */	\
777 		BUILD_BUG_ON(HWEIGHT(m) != HWEIGHT((f) | (m)));	\
778 		/* Check that the flags fit in the type */	\
779 		BUILD_BUG_ON((sizeof(*_fset) * 8) <= __fls(m));	\
780 	} while (0)
781 
782 #define __vcpu_get_flag(v, flagset, f, m)			\
783 	({							\
784 		__build_check_flag(v, flagset, f, m);		\
785 								\
786 		READ_ONCE(v->arch.flagset) & (m);		\
787 	})
788 
789 /*
790  * Note that the set/clear accessors must be preempt-safe in order to
791  * avoid nesting them with load/put which also manipulate flags...
792  */
793 #ifdef __KVM_NVHE_HYPERVISOR__
794 /* the nVHE hypervisor is always non-preemptible */
795 #define __vcpu_flags_preempt_disable()
796 #define __vcpu_flags_preempt_enable()
797 #else
798 #define __vcpu_flags_preempt_disable()	preempt_disable()
799 #define __vcpu_flags_preempt_enable()	preempt_enable()
800 #endif
801 
802 #define __vcpu_set_flag(v, flagset, f, m)			\
803 	do {							\
804 		typeof(v->arch.flagset) *fset;			\
805 								\
806 		__build_check_flag(v, flagset, f, m);		\
807 								\
808 		fset = &v->arch.flagset;			\
809 		__vcpu_flags_preempt_disable();			\
810 		if (HWEIGHT(m) > 1)				\
811 			*fset &= ~(m);				\
812 		*fset |= (f);					\
813 		__vcpu_flags_preempt_enable();			\
814 	} while (0)
815 
816 #define __vcpu_clear_flag(v, flagset, f, m)			\
817 	do {							\
818 		typeof(v->arch.flagset) *fset;			\
819 								\
820 		__build_check_flag(v, flagset, f, m);		\
821 								\
822 		fset = &v->arch.flagset;			\
823 		__vcpu_flags_preempt_disable();			\
824 		*fset &= ~(m);					\
825 		__vcpu_flags_preempt_enable();			\
826 	} while (0)
827 
828 #define vcpu_get_flag(v, ...)	__vcpu_get_flag((v), __VA_ARGS__)
829 #define vcpu_set_flag(v, ...)	__vcpu_set_flag((v), __VA_ARGS__)
830 #define vcpu_clear_flag(v, ...)	__vcpu_clear_flag((v), __VA_ARGS__)
831 
832 /* SVE exposed to guest */
833 #define GUEST_HAS_SVE		__vcpu_single_flag(cflags, BIT(0))
834 /* SVE config completed */
835 #define VCPU_SVE_FINALIZED	__vcpu_single_flag(cflags, BIT(1))
836 /* PTRAUTH exposed to guest */
837 #define GUEST_HAS_PTRAUTH	__vcpu_single_flag(cflags, BIT(2))
838 /* KVM_ARM_VCPU_INIT completed */
839 #define VCPU_INITIALIZED	__vcpu_single_flag(cflags, BIT(3))
840 
841 /* Exception pending */
842 #define PENDING_EXCEPTION	__vcpu_single_flag(iflags, BIT(0))
843 /*
844  * PC increment. Overlaps with EXCEPT_MASK on purpose so that it can't
845  * be set together with an exception...
846  */
847 #define INCREMENT_PC		__vcpu_single_flag(iflags, BIT(1))
848 /* Target EL/MODE (not a single flag, but let's abuse the macro) */
849 #define EXCEPT_MASK		__vcpu_single_flag(iflags, GENMASK(3, 1))
850 
851 /* Helpers to encode exceptions with minimum fuss */
852 #define __EXCEPT_MASK_VAL	unpack_vcpu_flag(EXCEPT_MASK)
853 #define __EXCEPT_SHIFT		__builtin_ctzl(__EXCEPT_MASK_VAL)
854 #define __vcpu_except_flags(_f)	iflags, (_f << __EXCEPT_SHIFT), __EXCEPT_MASK_VAL
855 
856 /*
857  * When PENDING_EXCEPTION is set, EXCEPT_MASK can take the following
858  * values:
859  *
860  * For AArch32 EL1:
861  */
862 #define EXCEPT_AA32_UND		__vcpu_except_flags(0)
863 #define EXCEPT_AA32_IABT	__vcpu_except_flags(1)
864 #define EXCEPT_AA32_DABT	__vcpu_except_flags(2)
865 /* For AArch64: */
866 #define EXCEPT_AA64_EL1_SYNC	__vcpu_except_flags(0)
867 #define EXCEPT_AA64_EL1_IRQ	__vcpu_except_flags(1)
868 #define EXCEPT_AA64_EL1_FIQ	__vcpu_except_flags(2)
869 #define EXCEPT_AA64_EL1_SERR	__vcpu_except_flags(3)
870 /* For AArch64 with NV: */
871 #define EXCEPT_AA64_EL2_SYNC	__vcpu_except_flags(4)
872 #define EXCEPT_AA64_EL2_IRQ	__vcpu_except_flags(5)
873 #define EXCEPT_AA64_EL2_FIQ	__vcpu_except_flags(6)
874 #define EXCEPT_AA64_EL2_SERR	__vcpu_except_flags(7)
875 /* Guest debug is live */
876 #define DEBUG_DIRTY		__vcpu_single_flag(iflags, BIT(4))
877 /* Save SPE context if active  */
878 #define DEBUG_STATE_SAVE_SPE	__vcpu_single_flag(iflags, BIT(5))
879 /* Save TRBE context if active  */
880 #define DEBUG_STATE_SAVE_TRBE	__vcpu_single_flag(iflags, BIT(6))
881 
882 /* SVE enabled for host EL0 */
883 #define HOST_SVE_ENABLED	__vcpu_single_flag(sflags, BIT(0))
884 /* SME enabled for EL0 */
885 #define HOST_SME_ENABLED	__vcpu_single_flag(sflags, BIT(1))
886 /* Physical CPU not in supported_cpus */
887 #define ON_UNSUPPORTED_CPU	__vcpu_single_flag(sflags, BIT(2))
888 /* WFIT instruction trapped */
889 #define IN_WFIT			__vcpu_single_flag(sflags, BIT(3))
890 /* vcpu system registers loaded on physical CPU */
891 #define SYSREGS_ON_CPU		__vcpu_single_flag(sflags, BIT(4))
892 /* Software step state is Active-pending */
893 #define DBG_SS_ACTIVE_PENDING	__vcpu_single_flag(sflags, BIT(5))
894 /* PMUSERENR for the guest EL0 is on physical CPU */
895 #define PMUSERENR_ON_CPU	__vcpu_single_flag(sflags, BIT(6))
896 /* WFI instruction trapped */
897 #define IN_WFI			__vcpu_single_flag(sflags, BIT(7))
898 
899 
900 /* Pointer to the vcpu's SVE FFR for sve_{save,load}_state() */
901 #define vcpu_sve_pffr(vcpu) (kern_hyp_va((vcpu)->arch.sve_state) +	\
902 			     sve_ffr_offset((vcpu)->arch.sve_max_vl))
903 
904 #define vcpu_sve_max_vq(vcpu)	sve_vq_from_vl((vcpu)->arch.sve_max_vl)
905 
906 #define vcpu_sve_zcr_elx(vcpu)						\
907 	(unlikely(is_hyp_ctxt(vcpu)) ? ZCR_EL2 : ZCR_EL1)
908 
909 #define vcpu_sve_state_size(vcpu) ({					\
910 	size_t __size_ret;						\
911 	unsigned int __vcpu_vq;						\
912 									\
913 	if (WARN_ON(!sve_vl_valid((vcpu)->arch.sve_max_vl))) {		\
914 		__size_ret = 0;						\
915 	} else {							\
916 		__vcpu_vq = vcpu_sve_max_vq(vcpu);			\
917 		__size_ret = SVE_SIG_REGS_SIZE(__vcpu_vq);		\
918 	}								\
919 									\
920 	__size_ret;							\
921 })
922 
923 #define KVM_GUESTDBG_VALID_MASK (KVM_GUESTDBG_ENABLE | \
924 				 KVM_GUESTDBG_USE_SW_BP | \
925 				 KVM_GUESTDBG_USE_HW | \
926 				 KVM_GUESTDBG_SINGLESTEP)
927 
928 #define vcpu_has_sve(vcpu) (system_supports_sve() &&			\
929 			    vcpu_get_flag(vcpu, GUEST_HAS_SVE))
930 
931 #ifdef CONFIG_ARM64_PTR_AUTH
932 #define vcpu_has_ptrauth(vcpu)						\
933 	((cpus_have_final_cap(ARM64_HAS_ADDRESS_AUTH) ||		\
934 	  cpus_have_final_cap(ARM64_HAS_GENERIC_AUTH)) &&		\
935 	  vcpu_get_flag(vcpu, GUEST_HAS_PTRAUTH))
936 #else
937 #define vcpu_has_ptrauth(vcpu)		false
938 #endif
939 
940 #define vcpu_on_unsupported_cpu(vcpu)					\
941 	vcpu_get_flag(vcpu, ON_UNSUPPORTED_CPU)
942 
943 #define vcpu_set_on_unsupported_cpu(vcpu)				\
944 	vcpu_set_flag(vcpu, ON_UNSUPPORTED_CPU)
945 
946 #define vcpu_clear_on_unsupported_cpu(vcpu)				\
947 	vcpu_clear_flag(vcpu, ON_UNSUPPORTED_CPU)
948 
949 #define vcpu_gp_regs(v)		(&(v)->arch.ctxt.regs)
950 
951 /*
952  * Only use __vcpu_sys_reg/ctxt_sys_reg if you know you want the
953  * memory backed version of a register, and not the one most recently
954  * accessed by a running VCPU.  For example, for userspace access or
955  * for system registers that are never context switched, but only
956  * emulated.
957  *
958  * Don't bother with VNCR-based accesses in the nVHE code, it has no
959  * business dealing with NV.
960  */
961 static inline u64 *___ctxt_sys_reg(const struct kvm_cpu_context *ctxt, int r)
962 {
963 #if !defined (__KVM_NVHE_HYPERVISOR__)
964 	if (unlikely(cpus_have_final_cap(ARM64_HAS_NESTED_VIRT) &&
965 		     r >= __VNCR_START__ && ctxt->vncr_array))
966 		return &ctxt->vncr_array[r - __VNCR_START__];
967 #endif
968 	return (u64 *)&ctxt->sys_regs[r];
969 }
970 
971 #define __ctxt_sys_reg(c,r)						\
972 	({								\
973 		BUILD_BUG_ON(__builtin_constant_p(r) &&			\
974 			     (r) >= NR_SYS_REGS);			\
975 		___ctxt_sys_reg(c, r);					\
976 	})
977 
978 #define ctxt_sys_reg(c,r)	(*__ctxt_sys_reg(c,r))
979 
980 u64 kvm_vcpu_sanitise_vncr_reg(const struct kvm_vcpu *, enum vcpu_sysreg);
981 #define __vcpu_sys_reg(v,r)						\
982 	(*({								\
983 		const struct kvm_cpu_context *ctxt = &(v)->arch.ctxt;	\
984 		u64 *__r = __ctxt_sys_reg(ctxt, (r));			\
985 		if (vcpu_has_nv((v)) && (r) >= __VNCR_START__)		\
986 			*__r = kvm_vcpu_sanitise_vncr_reg((v), (r));	\
987 		__r;							\
988 	}))
989 
990 u64 vcpu_read_sys_reg(const struct kvm_vcpu *vcpu, int reg);
991 void vcpu_write_sys_reg(struct kvm_vcpu *vcpu, u64 val, int reg);
992 
993 static inline bool __vcpu_read_sys_reg_from_cpu(int reg, u64 *val)
994 {
995 	/*
996 	 * *** VHE ONLY ***
997 	 *
998 	 * System registers listed in the switch are not saved on every
999 	 * exit from the guest but are only saved on vcpu_put.
1000 	 *
1001 	 * Note that MPIDR_EL1 for the guest is set by KVM via VMPIDR_EL2 but
1002 	 * should never be listed below, because the guest cannot modify its
1003 	 * own MPIDR_EL1 and MPIDR_EL1 is accessed for VCPU A from VCPU B's
1004 	 * thread when emulating cross-VCPU communication.
1005 	 */
1006 	if (!has_vhe())
1007 		return false;
1008 
1009 	switch (reg) {
1010 	case SCTLR_EL1:		*val = read_sysreg_s(SYS_SCTLR_EL12);	break;
1011 	case CPACR_EL1:		*val = read_sysreg_s(SYS_CPACR_EL12);	break;
1012 	case TTBR0_EL1:		*val = read_sysreg_s(SYS_TTBR0_EL12);	break;
1013 	case TTBR1_EL1:		*val = read_sysreg_s(SYS_TTBR1_EL12);	break;
1014 	case TCR_EL1:		*val = read_sysreg_s(SYS_TCR_EL12);	break;
1015 	case ESR_EL1:		*val = read_sysreg_s(SYS_ESR_EL12);	break;
1016 	case AFSR0_EL1:		*val = read_sysreg_s(SYS_AFSR0_EL12);	break;
1017 	case AFSR1_EL1:		*val = read_sysreg_s(SYS_AFSR1_EL12);	break;
1018 	case FAR_EL1:		*val = read_sysreg_s(SYS_FAR_EL12);	break;
1019 	case MAIR_EL1:		*val = read_sysreg_s(SYS_MAIR_EL12);	break;
1020 	case VBAR_EL1:		*val = read_sysreg_s(SYS_VBAR_EL12);	break;
1021 	case CONTEXTIDR_EL1:	*val = read_sysreg_s(SYS_CONTEXTIDR_EL12);break;
1022 	case TPIDR_EL0:		*val = read_sysreg_s(SYS_TPIDR_EL0);	break;
1023 	case TPIDRRO_EL0:	*val = read_sysreg_s(SYS_TPIDRRO_EL0);	break;
1024 	case TPIDR_EL1:		*val = read_sysreg_s(SYS_TPIDR_EL1);	break;
1025 	case AMAIR_EL1:		*val = read_sysreg_s(SYS_AMAIR_EL12);	break;
1026 	case CNTKCTL_EL1:	*val = read_sysreg_s(SYS_CNTKCTL_EL12);	break;
1027 	case ELR_EL1:		*val = read_sysreg_s(SYS_ELR_EL12);	break;
1028 	case SPSR_EL1:		*val = read_sysreg_s(SYS_SPSR_EL12);	break;
1029 	case PAR_EL1:		*val = read_sysreg_par();		break;
1030 	case DACR32_EL2:	*val = read_sysreg_s(SYS_DACR32_EL2);	break;
1031 	case IFSR32_EL2:	*val = read_sysreg_s(SYS_IFSR32_EL2);	break;
1032 	case DBGVCR32_EL2:	*val = read_sysreg_s(SYS_DBGVCR32_EL2);	break;
1033 	case ZCR_EL1:		*val = read_sysreg_s(SYS_ZCR_EL12);	break;
1034 	default:		return false;
1035 	}
1036 
1037 	return true;
1038 }
1039 
1040 static inline bool __vcpu_write_sys_reg_to_cpu(u64 val, int reg)
1041 {
1042 	/*
1043 	 * *** VHE ONLY ***
1044 	 *
1045 	 * System registers listed in the switch are not restored on every
1046 	 * entry to the guest but are only restored on vcpu_load.
1047 	 *
1048 	 * Note that MPIDR_EL1 for the guest is set by KVM via VMPIDR_EL2 but
1049 	 * should never be listed below, because the MPIDR should only be set
1050 	 * once, before running the VCPU, and never changed later.
1051 	 */
1052 	if (!has_vhe())
1053 		return false;
1054 
1055 	switch (reg) {
1056 	case SCTLR_EL1:		write_sysreg_s(val, SYS_SCTLR_EL12);	break;
1057 	case CPACR_EL1:		write_sysreg_s(val, SYS_CPACR_EL12);	break;
1058 	case TTBR0_EL1:		write_sysreg_s(val, SYS_TTBR0_EL12);	break;
1059 	case TTBR1_EL1:		write_sysreg_s(val, SYS_TTBR1_EL12);	break;
1060 	case TCR_EL1:		write_sysreg_s(val, SYS_TCR_EL12);	break;
1061 	case ESR_EL1:		write_sysreg_s(val, SYS_ESR_EL12);	break;
1062 	case AFSR0_EL1:		write_sysreg_s(val, SYS_AFSR0_EL12);	break;
1063 	case AFSR1_EL1:		write_sysreg_s(val, SYS_AFSR1_EL12);	break;
1064 	case FAR_EL1:		write_sysreg_s(val, SYS_FAR_EL12);	break;
1065 	case MAIR_EL1:		write_sysreg_s(val, SYS_MAIR_EL12);	break;
1066 	case VBAR_EL1:		write_sysreg_s(val, SYS_VBAR_EL12);	break;
1067 	case CONTEXTIDR_EL1:	write_sysreg_s(val, SYS_CONTEXTIDR_EL12);break;
1068 	case TPIDR_EL0:		write_sysreg_s(val, SYS_TPIDR_EL0);	break;
1069 	case TPIDRRO_EL0:	write_sysreg_s(val, SYS_TPIDRRO_EL0);	break;
1070 	case TPIDR_EL1:		write_sysreg_s(val, SYS_TPIDR_EL1);	break;
1071 	case AMAIR_EL1:		write_sysreg_s(val, SYS_AMAIR_EL12);	break;
1072 	case CNTKCTL_EL1:	write_sysreg_s(val, SYS_CNTKCTL_EL12);	break;
1073 	case ELR_EL1:		write_sysreg_s(val, SYS_ELR_EL12);	break;
1074 	case SPSR_EL1:		write_sysreg_s(val, SYS_SPSR_EL12);	break;
1075 	case PAR_EL1:		write_sysreg_s(val, SYS_PAR_EL1);	break;
1076 	case DACR32_EL2:	write_sysreg_s(val, SYS_DACR32_EL2);	break;
1077 	case IFSR32_EL2:	write_sysreg_s(val, SYS_IFSR32_EL2);	break;
1078 	case DBGVCR32_EL2:	write_sysreg_s(val, SYS_DBGVCR32_EL2);	break;
1079 	case ZCR_EL1:		write_sysreg_s(val, SYS_ZCR_EL12);	break;
1080 	default:		return false;
1081 	}
1082 
1083 	return true;
1084 }
1085 
1086 struct kvm_vm_stat {
1087 	struct kvm_vm_stat_generic generic;
1088 };
1089 
1090 struct kvm_vcpu_stat {
1091 	struct kvm_vcpu_stat_generic generic;
1092 	u64 hvc_exit_stat;
1093 	u64 wfe_exit_stat;
1094 	u64 wfi_exit_stat;
1095 	u64 mmio_exit_user;
1096 	u64 mmio_exit_kernel;
1097 	u64 signal_exits;
1098 	u64 exits;
1099 };
1100 
1101 unsigned long kvm_arm_num_regs(struct kvm_vcpu *vcpu);
1102 int kvm_arm_copy_reg_indices(struct kvm_vcpu *vcpu, u64 __user *indices);
1103 int kvm_arm_get_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg);
1104 int kvm_arm_set_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg);
1105 
1106 unsigned long kvm_arm_num_sys_reg_descs(struct kvm_vcpu *vcpu);
1107 int kvm_arm_copy_sys_reg_indices(struct kvm_vcpu *vcpu, u64 __user *uindices);
1108 
1109 int __kvm_arm_vcpu_get_events(struct kvm_vcpu *vcpu,
1110 			      struct kvm_vcpu_events *events);
1111 
1112 int __kvm_arm_vcpu_set_events(struct kvm_vcpu *vcpu,
1113 			      struct kvm_vcpu_events *events);
1114 
1115 void kvm_arm_halt_guest(struct kvm *kvm);
1116 void kvm_arm_resume_guest(struct kvm *kvm);
1117 
1118 #define vcpu_has_run_once(vcpu)	!!rcu_access_pointer((vcpu)->pid)
1119 
1120 #ifndef __KVM_NVHE_HYPERVISOR__
1121 #define kvm_call_hyp_nvhe(f, ...)						\
1122 	({								\
1123 		struct arm_smccc_res res;				\
1124 									\
1125 		arm_smccc_1_1_hvc(KVM_HOST_SMCCC_FUNC(f),		\
1126 				  ##__VA_ARGS__, &res);			\
1127 		WARN_ON(res.a0 != SMCCC_RET_SUCCESS);			\
1128 									\
1129 		res.a1;							\
1130 	})
1131 
1132 /*
1133  * The couple of isb() below are there to guarantee the same behaviour
1134  * on VHE as on !VHE, where the eret to EL1 acts as a context
1135  * synchronization event.
1136  */
1137 #define kvm_call_hyp(f, ...)						\
1138 	do {								\
1139 		if (has_vhe()) {					\
1140 			f(__VA_ARGS__);					\
1141 			isb();						\
1142 		} else {						\
1143 			kvm_call_hyp_nvhe(f, ##__VA_ARGS__);		\
1144 		}							\
1145 	} while(0)
1146 
1147 #define kvm_call_hyp_ret(f, ...)					\
1148 	({								\
1149 		typeof(f(__VA_ARGS__)) ret;				\
1150 									\
1151 		if (has_vhe()) {					\
1152 			ret = f(__VA_ARGS__);				\
1153 			isb();						\
1154 		} else {						\
1155 			ret = kvm_call_hyp_nvhe(f, ##__VA_ARGS__);	\
1156 		}							\
1157 									\
1158 		ret;							\
1159 	})
1160 #else /* __KVM_NVHE_HYPERVISOR__ */
1161 #define kvm_call_hyp(f, ...) f(__VA_ARGS__)
1162 #define kvm_call_hyp_ret(f, ...) f(__VA_ARGS__)
1163 #define kvm_call_hyp_nvhe(f, ...) f(__VA_ARGS__)
1164 #endif /* __KVM_NVHE_HYPERVISOR__ */
1165 
1166 int handle_exit(struct kvm_vcpu *vcpu, int exception_index);
1167 void handle_exit_early(struct kvm_vcpu *vcpu, int exception_index);
1168 
1169 int kvm_handle_cp14_load_store(struct kvm_vcpu *vcpu);
1170 int kvm_handle_cp14_32(struct kvm_vcpu *vcpu);
1171 int kvm_handle_cp14_64(struct kvm_vcpu *vcpu);
1172 int kvm_handle_cp15_32(struct kvm_vcpu *vcpu);
1173 int kvm_handle_cp15_64(struct kvm_vcpu *vcpu);
1174 int kvm_handle_sys_reg(struct kvm_vcpu *vcpu);
1175 int kvm_handle_cp10_id(struct kvm_vcpu *vcpu);
1176 
1177 void kvm_sys_regs_create_debugfs(struct kvm *kvm);
1178 void kvm_reset_sys_regs(struct kvm_vcpu *vcpu);
1179 
1180 int __init kvm_sys_reg_table_init(void);
1181 struct sys_reg_desc;
1182 int __init populate_sysreg_config(const struct sys_reg_desc *sr,
1183 				  unsigned int idx);
1184 int __init populate_nv_trap_config(void);
1185 
1186 bool lock_all_vcpus(struct kvm *kvm);
1187 void unlock_all_vcpus(struct kvm *kvm);
1188 
1189 void kvm_calculate_traps(struct kvm_vcpu *vcpu);
1190 
1191 /* MMIO helpers */
1192 void kvm_mmio_write_buf(void *buf, unsigned int len, unsigned long data);
1193 unsigned long kvm_mmio_read_buf(const void *buf, unsigned int len);
1194 
1195 int kvm_handle_mmio_return(struct kvm_vcpu *vcpu);
1196 int io_mem_abort(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa);
1197 
1198 /*
1199  * Returns true if a Performance Monitoring Interrupt (PMI), a.k.a. perf event,
1200  * arrived in guest context.  For arm64, any event that arrives while a vCPU is
1201  * loaded is considered to be "in guest".
1202  */
1203 static inline bool kvm_arch_pmi_in_guest(struct kvm_vcpu *vcpu)
1204 {
1205 	return IS_ENABLED(CONFIG_GUEST_PERF_EVENTS) && !!vcpu;
1206 }
1207 
1208 long kvm_hypercall_pv_features(struct kvm_vcpu *vcpu);
1209 gpa_t kvm_init_stolen_time(struct kvm_vcpu *vcpu);
1210 void kvm_update_stolen_time(struct kvm_vcpu *vcpu);
1211 
1212 bool kvm_arm_pvtime_supported(void);
1213 int kvm_arm_pvtime_set_attr(struct kvm_vcpu *vcpu,
1214 			    struct kvm_device_attr *attr);
1215 int kvm_arm_pvtime_get_attr(struct kvm_vcpu *vcpu,
1216 			    struct kvm_device_attr *attr);
1217 int kvm_arm_pvtime_has_attr(struct kvm_vcpu *vcpu,
1218 			    struct kvm_device_attr *attr);
1219 
1220 extern unsigned int __ro_after_init kvm_arm_vmid_bits;
1221 int __init kvm_arm_vmid_alloc_init(void);
1222 void __init kvm_arm_vmid_alloc_free(void);
1223 bool kvm_arm_vmid_update(struct kvm_vmid *kvm_vmid);
1224 void kvm_arm_vmid_clear_active(void);
1225 
1226 static inline void kvm_arm_pvtime_vcpu_init(struct kvm_vcpu_arch *vcpu_arch)
1227 {
1228 	vcpu_arch->steal.base = INVALID_GPA;
1229 }
1230 
1231 static inline bool kvm_arm_is_pvtime_enabled(struct kvm_vcpu_arch *vcpu_arch)
1232 {
1233 	return (vcpu_arch->steal.base != INVALID_GPA);
1234 }
1235 
1236 void kvm_set_sei_esr(struct kvm_vcpu *vcpu, u64 syndrome);
1237 
1238 struct kvm_vcpu *kvm_mpidr_to_vcpu(struct kvm *kvm, unsigned long mpidr);
1239 
1240 DECLARE_KVM_HYP_PER_CPU(struct kvm_host_data, kvm_host_data);
1241 
1242 /*
1243  * How we access per-CPU host data depends on the where we access it from,
1244  * and the mode we're in:
1245  *
1246  * - VHE and nVHE hypervisor bits use their locally defined instance
1247  *
1248  * - the rest of the kernel use either the VHE or nVHE one, depending on
1249  *   the mode we're running in.
1250  *
1251  *   Unless we're in protected mode, fully deprivileged, and the nVHE
1252  *   per-CPU stuff is exclusively accessible to the protected EL2 code.
1253  *   In this case, the EL1 code uses the *VHE* data as its private state
1254  *   (which makes sense in a way as there shouldn't be any shared state
1255  *   between the host and the hypervisor).
1256  *
1257  * Yes, this is all totally trivial. Shoot me now.
1258  */
1259 #if defined(__KVM_NVHE_HYPERVISOR__) || defined(__KVM_VHE_HYPERVISOR__)
1260 #define host_data_ptr(f)	(&this_cpu_ptr(&kvm_host_data)->f)
1261 #else
1262 #define host_data_ptr(f)						\
1263 	(static_branch_unlikely(&kvm_protected_mode_initialized) ?	\
1264 	 &this_cpu_ptr(&kvm_host_data)->f :				\
1265 	 &this_cpu_ptr_hyp_sym(kvm_host_data)->f)
1266 #endif
1267 
1268 /* Check whether the FP regs are owned by the guest */
1269 static inline bool guest_owns_fp_regs(void)
1270 {
1271 	return *host_data_ptr(fp_owner) == FP_STATE_GUEST_OWNED;
1272 }
1273 
1274 /* Check whether the FP regs are owned by the host */
1275 static inline bool host_owns_fp_regs(void)
1276 {
1277 	return *host_data_ptr(fp_owner) == FP_STATE_HOST_OWNED;
1278 }
1279 
1280 static inline void kvm_init_host_cpu_context(struct kvm_cpu_context *cpu_ctxt)
1281 {
1282 	/* The host's MPIDR is immutable, so let's set it up at boot time */
1283 	ctxt_sys_reg(cpu_ctxt, MPIDR_EL1) = read_cpuid_mpidr();
1284 }
1285 
1286 static inline bool kvm_system_needs_idmapped_vectors(void)
1287 {
1288 	return cpus_have_final_cap(ARM64_SPECTRE_V3A);
1289 }
1290 
1291 static inline void kvm_arch_sync_events(struct kvm *kvm) {}
1292 
1293 void kvm_arm_init_debug(void);
1294 void kvm_arm_vcpu_init_debug(struct kvm_vcpu *vcpu);
1295 void kvm_arm_setup_debug(struct kvm_vcpu *vcpu);
1296 void kvm_arm_clear_debug(struct kvm_vcpu *vcpu);
1297 void kvm_arm_reset_debug_ptr(struct kvm_vcpu *vcpu);
1298 
1299 #define kvm_vcpu_os_lock_enabled(vcpu)		\
1300 	(!!(__vcpu_sys_reg(vcpu, OSLSR_EL1) & OSLSR_EL1_OSLK))
1301 
1302 int kvm_arm_vcpu_arch_set_attr(struct kvm_vcpu *vcpu,
1303 			       struct kvm_device_attr *attr);
1304 int kvm_arm_vcpu_arch_get_attr(struct kvm_vcpu *vcpu,
1305 			       struct kvm_device_attr *attr);
1306 int kvm_arm_vcpu_arch_has_attr(struct kvm_vcpu *vcpu,
1307 			       struct kvm_device_attr *attr);
1308 
1309 int kvm_vm_ioctl_mte_copy_tags(struct kvm *kvm,
1310 			       struct kvm_arm_copy_mte_tags *copy_tags);
1311 int kvm_vm_ioctl_set_counter_offset(struct kvm *kvm,
1312 				    struct kvm_arm_counter_offset *offset);
1313 int kvm_vm_ioctl_get_reg_writable_masks(struct kvm *kvm,
1314 					struct reg_mask_range *range);
1315 
1316 /* Guest/host FPSIMD coordination helpers */
1317 int kvm_arch_vcpu_run_map_fp(struct kvm_vcpu *vcpu);
1318 void kvm_arch_vcpu_load_fp(struct kvm_vcpu *vcpu);
1319 void kvm_arch_vcpu_ctxflush_fp(struct kvm_vcpu *vcpu);
1320 void kvm_arch_vcpu_ctxsync_fp(struct kvm_vcpu *vcpu);
1321 void kvm_arch_vcpu_put_fp(struct kvm_vcpu *vcpu);
1322 
1323 static inline bool kvm_pmu_counter_deferred(struct perf_event_attr *attr)
1324 {
1325 	return (!has_vhe() && attr->exclude_host);
1326 }
1327 
1328 /* Flags for host debug state */
1329 void kvm_arch_vcpu_load_debug_state_flags(struct kvm_vcpu *vcpu);
1330 void kvm_arch_vcpu_put_debug_state_flags(struct kvm_vcpu *vcpu);
1331 
1332 #ifdef CONFIG_KVM
1333 void kvm_set_pmu_events(u32 set, struct perf_event_attr *attr);
1334 void kvm_clr_pmu_events(u32 clr);
1335 bool kvm_set_pmuserenr(u64 val);
1336 #else
1337 static inline void kvm_set_pmu_events(u32 set, struct perf_event_attr *attr) {}
1338 static inline void kvm_clr_pmu_events(u32 clr) {}
1339 static inline bool kvm_set_pmuserenr(u64 val)
1340 {
1341 	return false;
1342 }
1343 #endif
1344 
1345 void kvm_vcpu_load_vhe(struct kvm_vcpu *vcpu);
1346 void kvm_vcpu_put_vhe(struct kvm_vcpu *vcpu);
1347 
1348 int __init kvm_set_ipa_limit(void);
1349 u32 kvm_get_pa_bits(struct kvm *kvm);
1350 
1351 #define __KVM_HAVE_ARCH_VM_ALLOC
1352 struct kvm *kvm_arch_alloc_vm(void);
1353 
1354 #define __KVM_HAVE_ARCH_FLUSH_REMOTE_TLBS
1355 
1356 #define __KVM_HAVE_ARCH_FLUSH_REMOTE_TLBS_RANGE
1357 
1358 #define kvm_vm_is_protected(kvm)	(is_protected_kvm_enabled() && (kvm)->arch.pkvm.enabled)
1359 
1360 #define vcpu_is_protected(vcpu)		kvm_vm_is_protected((vcpu)->kvm)
1361 
1362 int kvm_arm_vcpu_finalize(struct kvm_vcpu *vcpu, int feature);
1363 bool kvm_arm_vcpu_is_finalized(struct kvm_vcpu *vcpu);
1364 
1365 #define kvm_arm_vcpu_sve_finalized(vcpu) vcpu_get_flag(vcpu, VCPU_SVE_FINALIZED)
1366 
1367 #define kvm_has_mte(kvm)					\
1368 	(system_supports_mte() &&				\
1369 	 test_bit(KVM_ARCH_FLAG_MTE_ENABLED, &(kvm)->arch.flags))
1370 
1371 #define kvm_supports_32bit_el0()				\
1372 	(system_supports_32bit_el0() &&				\
1373 	 !static_branch_unlikely(&arm64_mismatched_32bit_el0))
1374 
1375 #define kvm_vm_has_ran_once(kvm)					\
1376 	(test_bit(KVM_ARCH_FLAG_HAS_RAN_ONCE, &(kvm)->arch.flags))
1377 
1378 static inline bool __vcpu_has_feature(const struct kvm_arch *ka, int feature)
1379 {
1380 	return test_bit(feature, ka->vcpu_features);
1381 }
1382 
1383 #define vcpu_has_feature(v, f)	__vcpu_has_feature(&(v)->kvm->arch, (f))
1384 
1385 #define kvm_vcpu_initialized(v) vcpu_get_flag(vcpu, VCPU_INITIALIZED)
1386 
1387 int kvm_trng_call(struct kvm_vcpu *vcpu);
1388 #ifdef CONFIG_KVM
1389 extern phys_addr_t hyp_mem_base;
1390 extern phys_addr_t hyp_mem_size;
1391 void __init kvm_hyp_reserve(void);
1392 #else
1393 static inline void kvm_hyp_reserve(void) { }
1394 #endif
1395 
1396 void kvm_arm_vcpu_power_off(struct kvm_vcpu *vcpu);
1397 bool kvm_arm_vcpu_stopped(struct kvm_vcpu *vcpu);
1398 
1399 static inline u64 *__vm_id_reg(struct kvm_arch *ka, u32 reg)
1400 {
1401 	switch (reg) {
1402 	case sys_reg(3, 0, 0, 1, 0) ... sys_reg(3, 0, 0, 7, 7):
1403 		return &ka->id_regs[IDREG_IDX(reg)];
1404 	case SYS_CTR_EL0:
1405 		return &ka->ctr_el0;
1406 	default:
1407 		WARN_ON_ONCE(1);
1408 		return NULL;
1409 	}
1410 }
1411 
1412 #define kvm_read_vm_id_reg(kvm, reg)					\
1413 	({ u64 __val = *__vm_id_reg(&(kvm)->arch, reg); __val; })
1414 
1415 void kvm_set_vm_id_reg(struct kvm *kvm, u32 reg, u64 val);
1416 
1417 #define __expand_field_sign_unsigned(id, fld, val)			\
1418 	((u64)SYS_FIELD_VALUE(id, fld, val))
1419 
1420 #define __expand_field_sign_signed(id, fld, val)			\
1421 	({								\
1422 		u64 __val = SYS_FIELD_VALUE(id, fld, val);		\
1423 		sign_extend64(__val, id##_##fld##_WIDTH - 1);		\
1424 	})
1425 
1426 #define expand_field_sign(id, fld, val)					\
1427 	(id##_##fld##_SIGNED ?						\
1428 	 __expand_field_sign_signed(id, fld, val) :			\
1429 	 __expand_field_sign_unsigned(id, fld, val))
1430 
1431 #define get_idreg_field_unsigned(kvm, id, fld)				\
1432 	({								\
1433 		u64 __val = kvm_read_vm_id_reg((kvm), SYS_##id);	\
1434 		FIELD_GET(id##_##fld##_MASK, __val);			\
1435 	})
1436 
1437 #define get_idreg_field_signed(kvm, id, fld)				\
1438 	({								\
1439 		u64 __val = get_idreg_field_unsigned(kvm, id, fld);	\
1440 		sign_extend64(__val, id##_##fld##_WIDTH - 1);		\
1441 	})
1442 
1443 #define get_idreg_field_enum(kvm, id, fld)				\
1444 	get_idreg_field_unsigned(kvm, id, fld)
1445 
1446 #define get_idreg_field(kvm, id, fld)					\
1447 	(id##_##fld##_SIGNED ?						\
1448 	 get_idreg_field_signed(kvm, id, fld) :				\
1449 	 get_idreg_field_unsigned(kvm, id, fld))
1450 
1451 #define kvm_has_feat(kvm, id, fld, limit)				\
1452 	(get_idreg_field((kvm), id, fld) >= expand_field_sign(id, fld, limit))
1453 
1454 #define kvm_has_feat_enum(kvm, id, fld, val)				\
1455 	(get_idreg_field_unsigned((kvm), id, fld) == __expand_field_sign_unsigned(id, fld, val))
1456 
1457 #define kvm_has_feat_range(kvm, id, fld, min, max)			\
1458 	(get_idreg_field((kvm), id, fld) >= expand_field_sign(id, fld, min) && \
1459 	 get_idreg_field((kvm), id, fld) <= expand_field_sign(id, fld, max))
1460 
1461 /* Check for a given level of PAuth support */
1462 #define kvm_has_pauth(k, l)						\
1463 	({								\
1464 		bool pa, pi, pa3;					\
1465 									\
1466 		pa  = kvm_has_feat((k), ID_AA64ISAR1_EL1, APA, l);	\
1467 		pa &= kvm_has_feat((k), ID_AA64ISAR1_EL1, GPA, IMP);	\
1468 		pi  = kvm_has_feat((k), ID_AA64ISAR1_EL1, API, l);	\
1469 		pi &= kvm_has_feat((k), ID_AA64ISAR1_EL1, GPI, IMP);	\
1470 		pa3  = kvm_has_feat((k), ID_AA64ISAR2_EL1, APA3, l);	\
1471 		pa3 &= kvm_has_feat((k), ID_AA64ISAR2_EL1, GPA3, IMP);	\
1472 									\
1473 		(pa + pi + pa3) == 1;					\
1474 	})
1475 
1476 #endif /* __ARM64_KVM_HOST_H__ */
1477