xref: /linux/arch/riscv/kvm/vcpu.c (revision fc9c7ca5fcbf7fe3bcba87d1ff72f0009071ba86)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2019 Western Digital Corporation or its affiliates.
4  *
5  * Authors:
6  *     Anup Patel <anup.patel@wdc.com>
7  */
8 
9 #include <linux/bitops.h>
10 #include <linux/errno.h>
11 #include <linux/err.h>
12 #include <linux/kdebug.h>
13 #include <linux/module.h>
14 #include <linux/percpu.h>
15 #include <linux/vmalloc.h>
16 #include <linux/sched/signal.h>
17 #include <linux/fs.h>
18 #include <linux/kvm_host.h>
19 #include <asm/cacheflush.h>
20 #include <asm/kvm_mmu.h>
21 #include <asm/kvm_nacl.h>
22 #include <asm/kvm_vcpu_vector.h>
23 
24 #define CREATE_TRACE_POINTS
25 #include "trace.h"
26 
27 static DEFINE_PER_CPU(struct kvm_vcpu *, kvm_former_vcpu);
28 
29 const struct kvm_stats_desc kvm_vcpu_stats_desc[] = {
30 	KVM_GENERIC_VCPU_STATS(),
31 	STATS_DESC_COUNTER(VCPU, ecall_exit_stat),
32 	STATS_DESC_COUNTER(VCPU, wfi_exit_stat),
33 	STATS_DESC_COUNTER(VCPU, wrs_exit_stat),
34 	STATS_DESC_COUNTER(VCPU, mmio_exit_user),
35 	STATS_DESC_COUNTER(VCPU, mmio_exit_kernel),
36 	STATS_DESC_COUNTER(VCPU, csr_exit_user),
37 	STATS_DESC_COUNTER(VCPU, csr_exit_kernel),
38 	STATS_DESC_COUNTER(VCPU, signal_exits),
39 	STATS_DESC_COUNTER(VCPU, exits),
40 	STATS_DESC_COUNTER(VCPU, instr_illegal_exits),
41 	STATS_DESC_COUNTER(VCPU, load_misaligned_exits),
42 	STATS_DESC_COUNTER(VCPU, store_misaligned_exits),
43 	STATS_DESC_COUNTER(VCPU, load_access_exits),
44 	STATS_DESC_COUNTER(VCPU, store_access_exits),
45 };
46 
47 const struct kvm_stats_header kvm_vcpu_stats_header = {
48 	.name_size = KVM_STATS_NAME_SIZE,
49 	.num_desc = ARRAY_SIZE(kvm_vcpu_stats_desc),
50 	.id_offset = sizeof(struct kvm_stats_header),
51 	.desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
52 	.data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
53 		       sizeof(kvm_vcpu_stats_desc),
54 };
55 
56 static void kvm_riscv_vcpu_context_reset(struct kvm_vcpu *vcpu,
57 					 bool kvm_sbi_reset)
58 {
59 	struct kvm_vcpu_csr *csr = &vcpu->arch.guest_csr;
60 	struct kvm_cpu_context *cntx = &vcpu->arch.guest_context;
61 	void *vector_datap = cntx->vector.datap;
62 
63 	memset(cntx, 0, sizeof(*cntx));
64 	memset(csr, 0, sizeof(*csr));
65 	memset(&vcpu->arch.smstateen_csr, 0, sizeof(vcpu->arch.smstateen_csr));
66 
67 	/* Restore datap as it's not a part of the guest context. */
68 	cntx->vector.datap = vector_datap;
69 
70 	if (kvm_sbi_reset)
71 		kvm_riscv_vcpu_sbi_load_reset_state(vcpu);
72 
73 	/* Setup reset state of shadow SSTATUS and HSTATUS CSRs */
74 	cntx->sstatus = SR_SPP | SR_SPIE;
75 
76 	cntx->hstatus |= HSTATUS_VTW;
77 	cntx->hstatus |= HSTATUS_SPVP;
78 	cntx->hstatus |= HSTATUS_SPV;
79 }
80 
81 static void kvm_riscv_reset_vcpu(struct kvm_vcpu *vcpu, bool kvm_sbi_reset)
82 {
83 	unsigned long flags;
84 	bool loaded;
85 
86 	/**
87 	 * The preemption should be disabled here because it races with
88 	 * kvm_sched_out/kvm_sched_in(called from preempt notifiers) which
89 	 * also calls vcpu_load/put.
90 	 */
91 	get_cpu();
92 	loaded = (vcpu->cpu != -1);
93 	if (loaded)
94 		kvm_arch_vcpu_put(vcpu);
95 
96 	vcpu->arch.last_exit_cpu = -1;
97 
98 	kvm_riscv_vcpu_context_reset(vcpu, kvm_sbi_reset);
99 
100 	kvm_riscv_vcpu_fp_reset(vcpu);
101 
102 	kvm_riscv_vcpu_vector_reset(vcpu);
103 
104 	kvm_riscv_vcpu_timer_reset(vcpu);
105 
106 	kvm_riscv_vcpu_aia_reset(vcpu);
107 
108 	raw_spin_lock_irqsave(&vcpu->arch.irqs_pending_lock, flags);
109 	bitmap_zero(vcpu->arch.irqs_pending, KVM_RISCV_VCPU_NR_IRQS);
110 	bitmap_zero(vcpu->arch.irqs_pending_mask, KVM_RISCV_VCPU_NR_IRQS);
111 	raw_spin_unlock_irqrestore(&vcpu->arch.irqs_pending_lock, flags);
112 
113 	kvm_riscv_vcpu_pmu_reset(vcpu);
114 
115 	vcpu->arch.hfence_head = 0;
116 	vcpu->arch.hfence_tail = 0;
117 	memset(vcpu->arch.hfence_queue, 0, sizeof(vcpu->arch.hfence_queue));
118 
119 	kvm_riscv_vcpu_sbi_reset(vcpu);
120 
121 	/* Reset the guest CSRs for hotplug usecase */
122 	if (loaded)
123 		kvm_arch_vcpu_load(vcpu, smp_processor_id());
124 	put_cpu();
125 }
126 
127 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
128 {
129 	return 0;
130 }
131 
132 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
133 {
134 	int rc;
135 
136 	spin_lock_init(&vcpu->arch.mp_state_lock);
137 
138 	/* Mark this VCPU never ran */
139 	vcpu->arch.ran_atleast_once = false;
140 
141 	vcpu->arch.mmu_page_cache.gfp_zero = __GFP_ZERO;
142 	bitmap_zero(vcpu->arch.isa, RISCV_ISA_EXT_MAX);
143 
144 	/* Setup VCPU config */
145 	kvm_riscv_vcpu_config_init(vcpu);
146 
147 	/* Setup ISA features available to VCPU */
148 	kvm_riscv_vcpu_setup_isa(vcpu);
149 
150 	/* Setup vendor, arch, and implementation details */
151 	vcpu->arch.mvendorid = sbi_get_mvendorid();
152 	vcpu->arch.marchid = sbi_get_marchid();
153 	vcpu->arch.mimpid = sbi_get_mimpid();
154 
155 	/* Setup VCPU hfence queue */
156 	spin_lock_init(&vcpu->arch.hfence_lock);
157 	raw_spin_lock_init(&vcpu->arch.irqs_pending_lock);
158 
159 	spin_lock_init(&vcpu->arch.reset_state.lock);
160 
161 	rc = kvm_riscv_vcpu_alloc_vector_context(vcpu);
162 	if (rc)
163 		return rc;
164 
165 	/* Setup VCPU timer */
166 	kvm_riscv_vcpu_timer_init(vcpu);
167 
168 	/* setup performance monitoring */
169 	kvm_riscv_vcpu_pmu_init(vcpu);
170 
171 	/* Setup VCPU AIA */
172 	kvm_riscv_vcpu_aia_init(vcpu);
173 
174 	/*
175 	 * Setup SBI extensions
176 	 * NOTE: This must be the last thing to be initialized.
177 	 */
178 	kvm_riscv_vcpu_sbi_init(vcpu);
179 
180 	/* Reset VCPU */
181 	kvm_riscv_reset_vcpu(vcpu, false);
182 
183 	return 0;
184 }
185 
186 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
187 {
188 	/**
189 	 * vcpu with id 0 is the designated boot cpu.
190 	 * Keep all vcpus with non-zero id in power-off state so that
191 	 * they can be brought up using SBI HSM extension.
192 	 */
193 	if (vcpu->vcpu_idx != 0)
194 		kvm_riscv_vcpu_power_off(vcpu);
195 }
196 
197 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
198 {
199 	kvm_riscv_vcpu_sbi_deinit(vcpu);
200 
201 	/* Cleanup VCPU AIA context */
202 	kvm_riscv_vcpu_aia_deinit(vcpu);
203 
204 	/* Cleanup VCPU timer */
205 	kvm_riscv_vcpu_timer_deinit(vcpu);
206 
207 	kvm_riscv_vcpu_pmu_deinit(vcpu);
208 
209 	/* Free unused pages pre-allocated for G-stage page table mappings */
210 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_cache);
211 
212 	/* Free vector context space for host and guest kernel */
213 	kvm_riscv_vcpu_free_vector_context(vcpu);
214 }
215 
216 int kvm_cpu_has_pending_timer(struct kvm_vcpu *vcpu)
217 {
218 	return kvm_riscv_vcpu_timer_pending(vcpu);
219 }
220 
221 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
222 {
223 	return (kvm_riscv_vcpu_has_interrupts(vcpu, -1ULL) &&
224 		!kvm_riscv_vcpu_stopped(vcpu) && !vcpu->arch.pause);
225 }
226 
227 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
228 {
229 	return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
230 }
231 
232 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
233 {
234 	return (vcpu->arch.guest_context.sstatus & SR_SPP) ? true : false;
235 }
236 
237 #ifdef CONFIG_GUEST_PERF_EVENTS
238 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
239 {
240 	return vcpu->arch.guest_context.sepc;
241 }
242 #endif
243 
244 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
245 {
246 	return VM_FAULT_SIGBUS;
247 }
248 
249 long kvm_arch_vcpu_unlocked_ioctl(struct file *filp, unsigned int ioctl,
250 				  unsigned long arg)
251 {
252 	struct kvm_vcpu *vcpu = filp->private_data;
253 	void __user *argp = (void __user *)arg;
254 
255 	if (ioctl == KVM_INTERRUPT) {
256 		struct kvm_interrupt irq;
257 
258 		if (copy_from_user(&irq, argp, sizeof(irq)))
259 			return -EFAULT;
260 
261 		if (irq.irq == KVM_INTERRUPT_SET)
262 			return kvm_riscv_vcpu_set_interrupt(vcpu, IRQ_VS_EXT);
263 		else
264 			return kvm_riscv_vcpu_unset_interrupt(vcpu, IRQ_VS_EXT);
265 	}
266 
267 	return -ENOIOCTLCMD;
268 }
269 
270 long kvm_arch_vcpu_ioctl(struct file *filp,
271 			 unsigned int ioctl, unsigned long arg)
272 {
273 	struct kvm_vcpu *vcpu = filp->private_data;
274 	void __user *argp = (void __user *)arg;
275 	long r = -EINVAL;
276 
277 	switch (ioctl) {
278 	case KVM_SET_ONE_REG:
279 	case KVM_GET_ONE_REG: {
280 		struct kvm_one_reg reg;
281 
282 		r = -EFAULT;
283 		if (copy_from_user(&reg, argp, sizeof(reg)))
284 			break;
285 
286 		if (ioctl == KVM_SET_ONE_REG)
287 			r = kvm_riscv_vcpu_set_reg(vcpu, &reg);
288 		else
289 			r = kvm_riscv_vcpu_get_reg(vcpu, &reg);
290 		break;
291 	}
292 	case KVM_GET_REG_LIST: {
293 		struct kvm_reg_list __user *user_list = argp;
294 		struct kvm_reg_list reg_list;
295 		unsigned int n;
296 
297 		r = -EFAULT;
298 		if (copy_from_user(&reg_list, user_list, sizeof(reg_list)))
299 			break;
300 		n = reg_list.n;
301 		reg_list.n = kvm_riscv_vcpu_num_regs(vcpu);
302 		if (copy_to_user(user_list, &reg_list, sizeof(reg_list)))
303 			break;
304 		r = -E2BIG;
305 		if (n < reg_list.n)
306 			break;
307 		r = kvm_riscv_vcpu_copy_reg_indices(vcpu, user_list->reg);
308 		break;
309 	}
310 	default:
311 		break;
312 	}
313 
314 	return r;
315 }
316 
317 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
318 				  struct kvm_sregs *sregs)
319 {
320 	return -EINVAL;
321 }
322 
323 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
324 				  struct kvm_sregs *sregs)
325 {
326 	return -EINVAL;
327 }
328 
329 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
330 {
331 	return -EINVAL;
332 }
333 
334 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
335 {
336 	return -EINVAL;
337 }
338 
339 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
340 				  struct kvm_translation *tr)
341 {
342 	return -EINVAL;
343 }
344 
345 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
346 {
347 	return -EINVAL;
348 }
349 
350 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
351 {
352 	return -EINVAL;
353 }
354 
355 void kvm_riscv_vcpu_flush_interrupts(struct kvm_vcpu *vcpu)
356 {
357 	struct kvm_vcpu_csr *csr = &vcpu->arch.guest_csr;
358 	unsigned long mask, val;
359 	unsigned long flags;
360 
361 	raw_spin_lock_irqsave(&vcpu->arch.irqs_pending_lock, flags);
362 
363 	mask = vcpu->arch.irqs_pending_mask[0];
364 	if (mask) {
365 		vcpu->arch.irqs_pending_mask[0] = 0;
366 		val = vcpu->arch.irqs_pending[0] & mask;
367 
368 		csr->hvip &= ~mask;
369 		csr->hvip |= val;
370 	}
371 
372 	/* Flush AIA high interrupts */
373 	kvm_riscv_vcpu_aia_flush_interrupts(vcpu);
374 
375 	raw_spin_unlock_irqrestore(&vcpu->arch.irqs_pending_lock, flags);
376 }
377 
378 void kvm_riscv_vcpu_sync_interrupts(struct kvm_vcpu *vcpu)
379 {
380 	unsigned long hvip;
381 	unsigned long flags;
382 	struct kvm_vcpu_arch *v = &vcpu->arch;
383 	struct kvm_vcpu_csr *csr = &vcpu->arch.guest_csr;
384 
385 	/* Read current HVIP and VSIE CSRs */
386 	csr->vsie = ncsr_read(CSR_VSIE);
387 
388 	/* Sync-up HVIP.VSSIP bit changes does by Guest */
389 	hvip = ncsr_read(CSR_HVIP);
390 
391 	raw_spin_lock_irqsave(&v->irqs_pending_lock, flags);
392 
393 	if ((csr->hvip ^ hvip) & (1UL << IRQ_VS_SOFT)) {
394 		if (hvip & (1UL << IRQ_VS_SOFT)) {
395 			if (!__test_and_set_bit(IRQ_VS_SOFT,
396 						v->irqs_pending_mask))
397 				__set_bit(IRQ_VS_SOFT, v->irqs_pending);
398 		} else {
399 			if (!__test_and_set_bit(IRQ_VS_SOFT,
400 						v->irqs_pending_mask))
401 				__clear_bit(IRQ_VS_SOFT, v->irqs_pending);
402 		}
403 	}
404 
405 	/* Sync up the HVIP.LCOFIP bit changes (only clear) by the guest */
406 	if ((csr->hvip ^ hvip) & (1UL << IRQ_PMU_OVF)) {
407 		if (!(hvip & (1UL << IRQ_PMU_OVF)) &&
408 		    !__test_and_set_bit(IRQ_PMU_OVF, v->irqs_pending_mask))
409 			__clear_bit(IRQ_PMU_OVF, v->irqs_pending);
410 	}
411 
412 	/* Sync-up AIA high interrupts */
413 	kvm_riscv_vcpu_aia_sync_interrupts(vcpu);
414 
415 	raw_spin_unlock_irqrestore(&v->irqs_pending_lock, flags);
416 
417 	/* Sync-up timer CSRs */
418 	kvm_riscv_vcpu_timer_sync(vcpu);
419 }
420 
421 int kvm_riscv_vcpu_set_interrupt(struct kvm_vcpu *vcpu, unsigned int irq)
422 {
423 	unsigned long flags;
424 
425 	/*
426 	 * We only allow VS-mode software, timer, and external
427 	 * interrupts when irq is one of the local interrupts
428 	 * defined by RISC-V privilege specification.
429 	 */
430 	if (irq < IRQ_LOCAL_MAX &&
431 	    irq != IRQ_VS_SOFT &&
432 	    irq != IRQ_VS_TIMER &&
433 	    irq != IRQ_VS_EXT &&
434 	    irq != IRQ_PMU_OVF)
435 		return -EINVAL;
436 
437 	raw_spin_lock_irqsave(&vcpu->arch.irqs_pending_lock, flags);
438 	__set_bit(irq, vcpu->arch.irqs_pending);
439 	__set_bit(irq, vcpu->arch.irqs_pending_mask);
440 	raw_spin_unlock_irqrestore(&vcpu->arch.irqs_pending_lock, flags);
441 
442 	kvm_vcpu_kick(vcpu);
443 
444 	return 0;
445 }
446 
447 int kvm_riscv_vcpu_unset_interrupt(struct kvm_vcpu *vcpu, unsigned int irq)
448 {
449 	unsigned long flags;
450 
451 	/*
452 	 * We only allow VS-mode software, timer, counter overflow and external
453 	 * interrupts when irq is one of the local interrupts
454 	 * defined by RISC-V privilege specification.
455 	 */
456 	if (irq < IRQ_LOCAL_MAX &&
457 	    irq != IRQ_VS_SOFT &&
458 	    irq != IRQ_VS_TIMER &&
459 	    irq != IRQ_VS_EXT &&
460 	    irq != IRQ_PMU_OVF)
461 		return -EINVAL;
462 
463 	raw_spin_lock_irqsave(&vcpu->arch.irqs_pending_lock, flags);
464 	__clear_bit(irq, vcpu->arch.irqs_pending);
465 	__set_bit(irq, vcpu->arch.irqs_pending_mask);
466 	raw_spin_unlock_irqrestore(&vcpu->arch.irqs_pending_lock, flags);
467 
468 	return 0;
469 }
470 
471 bool kvm_riscv_vcpu_has_interrupts(struct kvm_vcpu *vcpu, u64 mask)
472 {
473 	unsigned long flags;
474 	unsigned long ie;
475 	bool ret;
476 
477 	raw_spin_lock_irqsave(&vcpu->arch.irqs_pending_lock, flags);
478 	ie = ((vcpu->arch.guest_csr.vsie & VSIP_VALID_MASK)
479 		<< VSIP_TO_HVIP_SHIFT) & (unsigned long)mask;
480 	ie |= vcpu->arch.guest_csr.vsie & ~IRQ_LOCAL_MASK &
481 		(unsigned long)mask;
482 	ret = vcpu->arch.irqs_pending[0] & ie;
483 	raw_spin_unlock_irqrestore(&vcpu->arch.irqs_pending_lock, flags);
484 
485 	/* Check AIA high interrupts */
486 	if (!ret)
487 		ret = kvm_riscv_vcpu_aia_has_interrupts(vcpu, mask);
488 
489 	return ret;
490 }
491 
492 void __kvm_riscv_vcpu_power_off(struct kvm_vcpu *vcpu)
493 {
494 	WRITE_ONCE(vcpu->arch.mp_state.mp_state, KVM_MP_STATE_STOPPED);
495 	kvm_make_request(KVM_REQ_SLEEP, vcpu);
496 	kvm_vcpu_kick(vcpu);
497 }
498 
499 void kvm_riscv_vcpu_power_off(struct kvm_vcpu *vcpu)
500 {
501 	spin_lock(&vcpu->arch.mp_state_lock);
502 	__kvm_riscv_vcpu_power_off(vcpu);
503 	spin_unlock(&vcpu->arch.mp_state_lock);
504 }
505 
506 void __kvm_riscv_vcpu_power_on(struct kvm_vcpu *vcpu)
507 {
508 	WRITE_ONCE(vcpu->arch.mp_state.mp_state, KVM_MP_STATE_RUNNABLE);
509 	kvm_vcpu_wake_up(vcpu);
510 }
511 
512 void kvm_riscv_vcpu_power_on(struct kvm_vcpu *vcpu)
513 {
514 	spin_lock(&vcpu->arch.mp_state_lock);
515 	__kvm_riscv_vcpu_power_on(vcpu);
516 	spin_unlock(&vcpu->arch.mp_state_lock);
517 }
518 
519 bool kvm_riscv_vcpu_stopped(struct kvm_vcpu *vcpu)
520 {
521 	return READ_ONCE(vcpu->arch.mp_state.mp_state) == KVM_MP_STATE_STOPPED;
522 }
523 
524 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
525 				    struct kvm_mp_state *mp_state)
526 {
527 	*mp_state = READ_ONCE(vcpu->arch.mp_state);
528 
529 	return 0;
530 }
531 
532 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
533 				    struct kvm_mp_state *mp_state)
534 {
535 	int ret = 0;
536 
537 	spin_lock(&vcpu->arch.mp_state_lock);
538 
539 	switch (mp_state->mp_state) {
540 	case KVM_MP_STATE_RUNNABLE:
541 		WRITE_ONCE(vcpu->arch.mp_state, *mp_state);
542 		break;
543 	case KVM_MP_STATE_STOPPED:
544 		__kvm_riscv_vcpu_power_off(vcpu);
545 		break;
546 	case KVM_MP_STATE_INIT_RECEIVED:
547 		if (vcpu->kvm->arch.mp_state_reset)
548 			kvm_riscv_reset_vcpu(vcpu, false);
549 		else
550 			ret = -EINVAL;
551 		break;
552 	default:
553 		ret = -EINVAL;
554 	}
555 
556 	spin_unlock(&vcpu->arch.mp_state_lock);
557 
558 	return ret;
559 }
560 
561 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
562 					struct kvm_guest_debug *dbg)
563 {
564 	if (dbg->control & KVM_GUESTDBG_ENABLE)
565 		vcpu->guest_debug = dbg->control;
566 	else
567 		vcpu->guest_debug = 0;
568 
569 	kvm_riscv_vcpu_config_guest_debug(vcpu);
570 	return 0;
571 }
572 
573 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
574 {
575 	void *nsh;
576 	struct kvm_vcpu_csr *csr = &vcpu->arch.guest_csr;
577 
578 	/*
579 	 * If VCPU is being reloaded on the same physical CPU and no
580 	 * other KVM VCPU has run on this CPU since it was last put,
581 	 * we can skip the expensive CSR and HGATP writes.
582 	 *
583 	 * Note: If a new CSR is added to this fast-path skip block,
584 	 * make sure that 'csr_dirty' is set to true in any
585 	 * ioctl (e.g., KVM_SET_ONE_REG) that modifies it.
586 	 */
587 	if (vcpu != __this_cpu_read(kvm_former_vcpu))
588 		__this_cpu_write(kvm_former_vcpu, vcpu);
589 	else if (vcpu->arch.last_exit_cpu == cpu && !vcpu->arch.csr_dirty)
590 		goto csr_restore_done;
591 
592 	vcpu->arch.csr_dirty = false;
593 
594 	/*
595 	 * Load VCPU config CSRs before other CSRs because
596 	 * the read/write behaviour of certain CSRs change
597 	 * based on VCPU config CSRs.
598 	 */
599 	kvm_riscv_vcpu_config_load(vcpu);
600 
601 	if (kvm_riscv_nacl_sync_csr_available()) {
602 		nsh = nacl_shmem();
603 		nacl_csr_write(nsh, CSR_VSSTATUS, csr->vsstatus);
604 		nacl_csr_write(nsh, CSR_VSIE, csr->vsie);
605 		nacl_csr_write(nsh, CSR_VSTVEC, csr->vstvec);
606 		nacl_csr_write(nsh, CSR_VSSCRATCH, csr->vsscratch);
607 		nacl_csr_write(nsh, CSR_VSEPC, csr->vsepc);
608 		nacl_csr_write(nsh, CSR_VSCAUSE, csr->vscause);
609 		nacl_csr_write(nsh, CSR_VSTVAL, csr->vstval);
610 		nacl_csr_write(nsh, CSR_HVIP, csr->hvip);
611 		nacl_csr_write(nsh, CSR_VSATP, csr->vsatp);
612 	} else {
613 		csr_write(CSR_VSSTATUS, csr->vsstatus);
614 		csr_write(CSR_VSIE, csr->vsie);
615 		csr_write(CSR_VSTVEC, csr->vstvec);
616 		csr_write(CSR_VSSCRATCH, csr->vsscratch);
617 		csr_write(CSR_VSEPC, csr->vsepc);
618 		csr_write(CSR_VSCAUSE, csr->vscause);
619 		csr_write(CSR_VSTVAL, csr->vstval);
620 		csr_write(CSR_HVIP, csr->hvip);
621 		csr_write(CSR_VSATP, csr->vsatp);
622 	}
623 
624 	kvm_riscv_mmu_update_hgatp(vcpu);
625 
626 	kvm_riscv_vcpu_aia_load(vcpu, cpu);
627 
628 csr_restore_done:
629 	kvm_riscv_vcpu_timer_restore(vcpu);
630 
631 	kvm_riscv_vcpu_host_fp_save(&vcpu->arch.host_context);
632 	kvm_riscv_vcpu_guest_fp_restore(&vcpu->arch.guest_context,
633 					vcpu->arch.isa);
634 	kvm_riscv_vcpu_host_vector_save(&vcpu->arch.host_context);
635 	kvm_riscv_vcpu_guest_vector_restore(&vcpu->arch.guest_context,
636 					    vcpu->arch.isa);
637 
638 	kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
639 
640 	vcpu->cpu = cpu;
641 }
642 
643 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
644 {
645 	void *nsh;
646 	struct kvm_vcpu_csr *csr = &vcpu->arch.guest_csr;
647 
648 	vcpu->cpu = -1;
649 
650 	kvm_riscv_vcpu_aia_put(vcpu);
651 
652 	kvm_riscv_vcpu_guest_fp_save(&vcpu->arch.guest_context,
653 				     vcpu->arch.isa);
654 	kvm_riscv_vcpu_host_fp_restore(&vcpu->arch.host_context);
655 
656 	kvm_riscv_vcpu_timer_save(vcpu);
657 	kvm_riscv_vcpu_guest_vector_save(&vcpu->arch.guest_context,
658 					 vcpu->arch.isa);
659 	kvm_riscv_vcpu_host_vector_restore(&vcpu->arch.host_context);
660 
661 	if (kvm_riscv_nacl_available()) {
662 		nsh = nacl_shmem();
663 		csr->vsstatus = nacl_csr_read(nsh, CSR_VSSTATUS);
664 		csr->vsie = nacl_csr_read(nsh, CSR_VSIE);
665 		csr->vstvec = nacl_csr_read(nsh, CSR_VSTVEC);
666 		csr->vsscratch = nacl_csr_read(nsh, CSR_VSSCRATCH);
667 		csr->vsepc = nacl_csr_read(nsh, CSR_VSEPC);
668 		csr->vscause = nacl_csr_read(nsh, CSR_VSCAUSE);
669 		csr->vstval = nacl_csr_read(nsh, CSR_VSTVAL);
670 		csr->hvip = nacl_csr_read(nsh, CSR_HVIP);
671 		csr->vsatp = nacl_csr_read(nsh, CSR_VSATP);
672 	} else {
673 		csr->vsstatus = csr_read(CSR_VSSTATUS);
674 		csr->vsie = csr_read(CSR_VSIE);
675 		csr->vstvec = csr_read(CSR_VSTVEC);
676 		csr->vsscratch = csr_read(CSR_VSSCRATCH);
677 		csr->vsepc = csr_read(CSR_VSEPC);
678 		csr->vscause = csr_read(CSR_VSCAUSE);
679 		csr->vstval = csr_read(CSR_VSTVAL);
680 		csr->hvip = csr_read(CSR_HVIP);
681 		csr->vsatp = csr_read(CSR_VSATP);
682 	}
683 }
684 
685 /**
686  * kvm_riscv_check_vcpu_requests - check and handle pending vCPU requests
687  * @vcpu:	the VCPU pointer
688  *
689  * Return: 1 if we should enter the guest
690  *	    0 if we should exit to userspace
691  */
692 static int kvm_riscv_check_vcpu_requests(struct kvm_vcpu *vcpu)
693 {
694 	struct rcuwait *wait = kvm_arch_vcpu_get_wait(vcpu);
695 
696 	if (kvm_request_pending(vcpu)) {
697 		if (kvm_check_request(KVM_REQ_SLEEP, vcpu)) {
698 			kvm_vcpu_srcu_read_unlock(vcpu);
699 			rcuwait_wait_event(wait,
700 				(!kvm_riscv_vcpu_stopped(vcpu)) && (!vcpu->arch.pause),
701 				TASK_INTERRUPTIBLE);
702 			kvm_vcpu_srcu_read_lock(vcpu);
703 
704 			if (kvm_riscv_vcpu_stopped(vcpu) || vcpu->arch.pause) {
705 				/*
706 				 * Awaken to handle a signal, request to
707 				 * sleep again later.
708 				 */
709 				kvm_make_request(KVM_REQ_SLEEP, vcpu);
710 			}
711 		}
712 
713 		if (kvm_check_request(KVM_REQ_VCPU_RESET, vcpu))
714 			kvm_riscv_reset_vcpu(vcpu, true);
715 
716 		if (kvm_check_request(KVM_REQ_UPDATE_HGATP, vcpu))
717 			kvm_riscv_mmu_update_hgatp(vcpu);
718 
719 		if (kvm_check_request(KVM_REQ_FENCE_I, vcpu))
720 			kvm_riscv_fence_i_process(vcpu);
721 
722 		if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
723 			kvm_riscv_tlb_flush_process(vcpu);
724 
725 		if (kvm_check_request(KVM_REQ_HFENCE_VVMA_ALL, vcpu))
726 			kvm_riscv_hfence_vvma_all_process(vcpu);
727 
728 		if (kvm_check_request(KVM_REQ_HFENCE, vcpu))
729 			kvm_riscv_hfence_process(vcpu);
730 
731 		if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
732 			kvm_riscv_vcpu_record_steal_time(vcpu);
733 
734 		if (kvm_dirty_ring_check_request(vcpu))
735 			return 0;
736 	}
737 
738 	return 1;
739 }
740 
741 static void kvm_riscv_update_hvip(struct kvm_vcpu *vcpu)
742 {
743 	struct kvm_vcpu_csr *csr = &vcpu->arch.guest_csr;
744 
745 	ncsr_write(CSR_HVIP, csr->hvip);
746 	kvm_riscv_vcpu_aia_update_hvip(vcpu);
747 }
748 
749 static __always_inline void kvm_riscv_vcpu_swap_in_guest_state(struct kvm_vcpu *vcpu)
750 {
751 	struct kvm_vcpu_smstateen_csr *smcsr = &vcpu->arch.smstateen_csr;
752 	struct kvm_vcpu_csr *csr = &vcpu->arch.guest_csr;
753 
754 	vcpu->arch.host_scounteren = csr_swap(CSR_SCOUNTEREN, csr->scounteren);
755 	vcpu->arch.host_senvcfg = csr_swap(CSR_SENVCFG, csr->senvcfg);
756 	if (riscv_has_extension_unlikely(RISCV_ISA_EXT_SMSTATEEN))
757 		vcpu->arch.host_sstateen0 = csr_swap(CSR_SSTATEEN0, smcsr->sstateen0);
758 }
759 
760 static __always_inline void kvm_riscv_vcpu_swap_in_host_state(struct kvm_vcpu *vcpu)
761 {
762 	struct kvm_vcpu_smstateen_csr *smcsr = &vcpu->arch.smstateen_csr;
763 	struct kvm_vcpu_csr *csr = &vcpu->arch.guest_csr;
764 
765 	csr->scounteren = csr_swap(CSR_SCOUNTEREN, vcpu->arch.host_scounteren);
766 	csr->senvcfg = csr_swap(CSR_SENVCFG, vcpu->arch.host_senvcfg);
767 	if (riscv_has_extension_unlikely(RISCV_ISA_EXT_SMSTATEEN))
768 		smcsr->sstateen0 = csr_swap(CSR_SSTATEEN0, vcpu->arch.host_sstateen0);
769 }
770 
771 /*
772  * Actually run the vCPU, entering an RCU extended quiescent state (EQS) while
773  * the vCPU is running.
774  *
775  * This must be noinstr as instrumentation may make use of RCU, and this is not
776  * safe during the EQS.
777  */
778 static void noinstr kvm_riscv_vcpu_enter_exit(struct kvm_vcpu *vcpu,
779 					      struct kvm_cpu_trap *trap)
780 {
781 	void *nsh;
782 	struct kvm_cpu_context *gcntx = &vcpu->arch.guest_context;
783 	struct kvm_cpu_context *hcntx = &vcpu->arch.host_context;
784 
785 	/*
786 	 * We save trap CSRs (such as SEPC, SCAUSE, STVAL, HTVAL, and
787 	 * HTINST) here because we do local_irq_enable() after this
788 	 * function in kvm_arch_vcpu_ioctl_run() which can result in
789 	 * an interrupt immediately after local_irq_enable() and can
790 	 * potentially change trap CSRs.
791 	 */
792 
793 	kvm_riscv_vcpu_swap_in_guest_state(vcpu);
794 	guest_state_enter_irqoff();
795 
796 	if (kvm_riscv_nacl_sync_sret_available()) {
797 		nsh = nacl_shmem();
798 
799 		if (kvm_riscv_nacl_autoswap_csr_available()) {
800 			hcntx->hstatus =
801 				nacl_csr_read(nsh, CSR_HSTATUS);
802 			nacl_scratch_write_long(nsh,
803 						SBI_NACL_SHMEM_AUTOSWAP_OFFSET +
804 						SBI_NACL_SHMEM_AUTOSWAP_HSTATUS,
805 						gcntx->hstatus);
806 			nacl_scratch_write_long(nsh,
807 						SBI_NACL_SHMEM_AUTOSWAP_OFFSET,
808 						SBI_NACL_SHMEM_AUTOSWAP_FLAG_HSTATUS);
809 		} else if (kvm_riscv_nacl_sync_csr_available()) {
810 			hcntx->hstatus = nacl_csr_swap(nsh,
811 						       CSR_HSTATUS, gcntx->hstatus);
812 		} else {
813 			hcntx->hstatus = csr_swap(CSR_HSTATUS, gcntx->hstatus);
814 		}
815 
816 		nacl_scratch_write_longs(nsh,
817 					 SBI_NACL_SHMEM_SRET_OFFSET +
818 					 SBI_NACL_SHMEM_SRET_X(1),
819 					 &gcntx->ra,
820 					 SBI_NACL_SHMEM_SRET_X_LAST);
821 
822 		__kvm_riscv_nacl_switch_to(&vcpu->arch, SBI_EXT_NACL,
823 					   SBI_EXT_NACL_SYNC_SRET);
824 
825 		if (kvm_riscv_nacl_autoswap_csr_available()) {
826 			nacl_scratch_write_long(nsh,
827 						SBI_NACL_SHMEM_AUTOSWAP_OFFSET,
828 						0);
829 			gcntx->hstatus = nacl_scratch_read_long(nsh,
830 								SBI_NACL_SHMEM_AUTOSWAP_OFFSET +
831 								SBI_NACL_SHMEM_AUTOSWAP_HSTATUS);
832 		} else {
833 			gcntx->hstatus = csr_swap(CSR_HSTATUS, hcntx->hstatus);
834 		}
835 
836 		trap->htval = nacl_csr_read(nsh, CSR_HTVAL);
837 		trap->htinst = nacl_csr_read(nsh, CSR_HTINST);
838 	} else {
839 		hcntx->hstatus = csr_swap(CSR_HSTATUS, gcntx->hstatus);
840 
841 		__kvm_riscv_switch_to(&vcpu->arch);
842 
843 		gcntx->hstatus = csr_swap(CSR_HSTATUS, hcntx->hstatus);
844 
845 		trap->htval = csr_read(CSR_HTVAL);
846 		trap->htinst = csr_read(CSR_HTINST);
847 	}
848 
849 	trap->sepc = gcntx->sepc;
850 	trap->scause = csr_read(CSR_SCAUSE);
851 	trap->stval = csr_read(CSR_STVAL);
852 
853 	vcpu->arch.last_exit_cpu = vcpu->cpu;
854 	guest_state_exit_irqoff();
855 	kvm_riscv_vcpu_swap_in_host_state(vcpu);
856 }
857 
858 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
859 {
860 	int ret;
861 	struct kvm_cpu_trap trap;
862 	struct kvm_run *run = vcpu->run;
863 
864 	if (!vcpu->arch.ran_atleast_once)
865 		kvm_riscv_vcpu_config_ran_once(vcpu);
866 
867 	/* Mark this VCPU ran at least once */
868 	vcpu->arch.ran_atleast_once = true;
869 
870 	kvm_vcpu_srcu_read_lock(vcpu);
871 
872 	switch (run->exit_reason) {
873 	case KVM_EXIT_MMIO:
874 		/* Process MMIO value returned from user-space */
875 		ret = kvm_riscv_vcpu_mmio_return(vcpu, vcpu->run);
876 		break;
877 	case KVM_EXIT_RISCV_SBI:
878 		/* Process SBI value returned from user-space */
879 		ret = kvm_riscv_vcpu_sbi_return(vcpu, vcpu->run);
880 		break;
881 	case KVM_EXIT_RISCV_CSR:
882 		/* Process CSR value returned from user-space */
883 		ret = kvm_riscv_vcpu_csr_return(vcpu, vcpu->run);
884 		break;
885 	default:
886 		ret = 0;
887 		break;
888 	}
889 	if (ret) {
890 		kvm_vcpu_srcu_read_unlock(vcpu);
891 		return ret;
892 	}
893 
894 	if (!vcpu->wants_to_run) {
895 		kvm_vcpu_srcu_read_unlock(vcpu);
896 		return -EINTR;
897 	}
898 
899 	vcpu_load(vcpu);
900 
901 	kvm_sigset_activate(vcpu);
902 
903 	ret = 1;
904 	run->exit_reason = KVM_EXIT_UNKNOWN;
905 	while (ret > 0) {
906 		/* Check conditions before entering the guest */
907 		ret = kvm_xfer_to_guest_mode_handle_work(vcpu);
908 		if (ret)
909 			continue;
910 		ret = 1;
911 
912 		kvm_riscv_gstage_vmid_update(vcpu);
913 
914 		ret = kvm_riscv_check_vcpu_requests(vcpu);
915 		if (ret <= 0)
916 			continue;
917 
918 		preempt_disable();
919 
920 		/* Update AIA HW state before entering guest */
921 		ret = kvm_riscv_vcpu_aia_update(vcpu);
922 		if (ret <= 0) {
923 			preempt_enable();
924 			continue;
925 		}
926 
927 		local_irq_disable();
928 
929 		/*
930 		 * Ensure we set mode to IN_GUEST_MODE after we disable
931 		 * interrupts and before the final VCPU requests check.
932 		 * See the comment in kvm_vcpu_exiting_guest_mode() and
933 		 * Documentation/virt/kvm/vcpu-requests.rst
934 		 */
935 		vcpu->mode = IN_GUEST_MODE;
936 
937 		kvm_vcpu_srcu_read_unlock(vcpu);
938 		smp_mb__after_srcu_read_unlock();
939 
940 		/*
941 		 * We might have got VCPU interrupts updated asynchronously
942 		 * so update it in HW.
943 		 */
944 		kvm_riscv_vcpu_flush_interrupts(vcpu);
945 
946 		/* Update HVIP CSR for current CPU */
947 		kvm_riscv_update_hvip(vcpu);
948 
949 		if (kvm_riscv_gstage_vmid_ver_changed(&vcpu->kvm->arch.vmid) ||
950 		    kvm_request_pending(vcpu) ||
951 		    xfer_to_guest_mode_work_pending()) {
952 			vcpu->mode = OUTSIDE_GUEST_MODE;
953 			local_irq_enable();
954 			preempt_enable();
955 			kvm_vcpu_srcu_read_lock(vcpu);
956 			continue;
957 		}
958 
959 		/*
960 		 * Sanitize VMID mappings cached (TLB) on current CPU
961 		 *
962 		 * Note: This should be done after G-stage VMID has been
963 		 * updated using kvm_riscv_gstage_vmid_ver_changed()
964 		 */
965 		kvm_riscv_local_tlb_sanitize(vcpu);
966 
967 		trace_kvm_entry(vcpu);
968 
969 		guest_timing_enter_irqoff();
970 
971 		kvm_riscv_vcpu_enter_exit(vcpu, &trap);
972 
973 		vcpu->mode = OUTSIDE_GUEST_MODE;
974 		vcpu->stat.exits++;
975 
976 		/* Syncup interrupts state with HW */
977 		kvm_riscv_vcpu_sync_interrupts(vcpu);
978 
979 		/*
980 		 * We must ensure that any pending interrupts are taken before
981 		 * we exit guest timing so that timer ticks are accounted as
982 		 * guest time. Transiently unmask interrupts so that any
983 		 * pending interrupts are taken.
984 		 *
985 		 * There's no barrier which ensures that pending interrupts are
986 		 * recognised, so we just hope that the CPU takes any pending
987 		 * interrupts between the enable and disable.
988 		 */
989 		local_irq_enable();
990 		local_irq_disable();
991 
992 		guest_timing_exit_irqoff();
993 
994 		local_irq_enable();
995 
996 		trace_kvm_exit(&trap);
997 
998 		preempt_enable();
999 
1000 		kvm_vcpu_srcu_read_lock(vcpu);
1001 
1002 		ret = kvm_riscv_vcpu_exit(vcpu, run, &trap);
1003 	}
1004 
1005 	kvm_sigset_deactivate(vcpu);
1006 
1007 	vcpu_put(vcpu);
1008 
1009 	kvm_vcpu_srcu_read_unlock(vcpu);
1010 
1011 	return ret;
1012 }
1013