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