1 /*
2  * Copyright (C) 2012 - Virtual Open Systems and Columbia University
3  * Author: Christoffer Dall <c.dall@virtualopensystems.com>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License, version 2, as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17  */
18 
19 #include <linux/bug.h>
20 #include <linux/cpu_pm.h>
21 #include <linux/errno.h>
22 #include <linux/err.h>
23 #include <linux/kvm_host.h>
24 #include <linux/list.h>
25 #include <linux/module.h>
26 #include <linux/vmalloc.h>
27 #include <linux/fs.h>
28 #include <linux/mman.h>
29 #include <linux/sched.h>
30 #include <linux/kvm.h>
31 #include <linux/kvm_irqfd.h>
32 #include <linux/irqbypass.h>
33 #include <linux/sched/stat.h>
34 #include <trace/events/kvm.h>
35 #include <kvm/arm_pmu.h>
36 #include <kvm/arm_psci.h>
37 
38 #define CREATE_TRACE_POINTS
39 #include "trace.h"
40 
41 #include <linux/uaccess.h>
42 #include <asm/ptrace.h>
43 #include <asm/mman.h>
44 #include <asm/tlbflush.h>
45 #include <asm/cacheflush.h>
46 #include <asm/cpufeature.h>
47 #include <asm/virt.h>
48 #include <asm/kvm_arm.h>
49 #include <asm/kvm_asm.h>
50 #include <asm/kvm_mmu.h>
51 #include <asm/kvm_emulate.h>
52 #include <asm/kvm_coproc.h>
53 #include <asm/sections.h>
54 
55 #ifdef REQUIRES_VIRT
56 __asm__(".arch_extension	virt");
57 #endif
58 
59 DEFINE_PER_CPU(kvm_cpu_context_t, kvm_host_cpu_state);
60 static DEFINE_PER_CPU(unsigned long, kvm_arm_hyp_stack_page);
61 
62 /* Per-CPU variable containing the currently running vcpu. */
63 static DEFINE_PER_CPU(struct kvm_vcpu *, kvm_arm_running_vcpu);
64 
65 /* The VMID used in the VTTBR */
66 static atomic64_t kvm_vmid_gen = ATOMIC64_INIT(1);
67 static u32 kvm_next_vmid;
68 static unsigned int kvm_vmid_bits __read_mostly;
69 static DEFINE_SPINLOCK(kvm_vmid_lock);
70 
71 static bool vgic_present;
72 
73 static DEFINE_PER_CPU(unsigned char, kvm_arm_hardware_enabled);
74 
kvm_arm_set_running_vcpu(struct kvm_vcpu * vcpu)75 static void kvm_arm_set_running_vcpu(struct kvm_vcpu *vcpu)
76 {
77 	__this_cpu_write(kvm_arm_running_vcpu, vcpu);
78 }
79 
80 DEFINE_STATIC_KEY_FALSE(userspace_irqchip_in_use);
81 
82 /**
83  * kvm_arm_get_running_vcpu - get the vcpu running on the current CPU.
84  * Must be called from non-preemptible context
85  */
kvm_arm_get_running_vcpu(void)86 struct kvm_vcpu *kvm_arm_get_running_vcpu(void)
87 {
88 	return __this_cpu_read(kvm_arm_running_vcpu);
89 }
90 
91 /**
92  * kvm_arm_get_running_vcpus - get the per-CPU array of currently running vcpus.
93  */
kvm_get_running_vcpus(void)94 struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
95 {
96 	return &kvm_arm_running_vcpu;
97 }
98 
kvm_arch_vcpu_should_kick(struct kvm_vcpu * vcpu)99 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
100 {
101 	return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
102 }
103 
kvm_arch_hardware_setup(void)104 int kvm_arch_hardware_setup(void)
105 {
106 	return 0;
107 }
108 
kvm_arch_check_processor_compat(void * rtn)109 void kvm_arch_check_processor_compat(void *rtn)
110 {
111 	*(int *)rtn = 0;
112 }
113 
114 
115 /**
116  * kvm_arch_init_vm - initializes a VM data structure
117  * @kvm:	pointer to the KVM struct
118  */
kvm_arch_init_vm(struct kvm * kvm,unsigned long type)119 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
120 {
121 	int ret, cpu;
122 
123 	if (type)
124 		return -EINVAL;
125 
126 	kvm->arch.last_vcpu_ran = alloc_percpu(typeof(*kvm->arch.last_vcpu_ran));
127 	if (!kvm->arch.last_vcpu_ran)
128 		return -ENOMEM;
129 
130 	for_each_possible_cpu(cpu)
131 		*per_cpu_ptr(kvm->arch.last_vcpu_ran, cpu) = -1;
132 
133 	ret = kvm_alloc_stage2_pgd(kvm);
134 	if (ret)
135 		goto out_fail_alloc;
136 
137 	ret = create_hyp_mappings(kvm, kvm + 1, PAGE_HYP);
138 	if (ret)
139 		goto out_free_stage2_pgd;
140 
141 	kvm_vgic_early_init(kvm);
142 
143 	/* Mark the initial VMID generation invalid */
144 	kvm->arch.vmid_gen = 0;
145 
146 	/* The maximum number of VCPUs is limited by the host's GIC model */
147 	kvm->arch.max_vcpus = vgic_present ?
148 				kvm_vgic_get_max_vcpus() : KVM_MAX_VCPUS;
149 
150 	return ret;
151 out_free_stage2_pgd:
152 	kvm_free_stage2_pgd(kvm);
153 out_fail_alloc:
154 	free_percpu(kvm->arch.last_vcpu_ran);
155 	kvm->arch.last_vcpu_ran = NULL;
156 	return ret;
157 }
158 
kvm_arch_has_vcpu_debugfs(void)159 bool kvm_arch_has_vcpu_debugfs(void)
160 {
161 	return false;
162 }
163 
kvm_arch_create_vcpu_debugfs(struct kvm_vcpu * vcpu)164 int kvm_arch_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
165 {
166 	return 0;
167 }
168 
kvm_arch_vcpu_fault(struct kvm_vcpu * vcpu,struct vm_fault * vmf)169 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
170 {
171 	return VM_FAULT_SIGBUS;
172 }
173 
174 
175 /**
176  * kvm_arch_destroy_vm - destroy the VM data structure
177  * @kvm:	pointer to the KVM struct
178  */
kvm_arch_destroy_vm(struct kvm * kvm)179 void kvm_arch_destroy_vm(struct kvm *kvm)
180 {
181 	int i;
182 
183 	kvm_vgic_destroy(kvm);
184 
185 	free_percpu(kvm->arch.last_vcpu_ran);
186 	kvm->arch.last_vcpu_ran = NULL;
187 
188 	for (i = 0; i < KVM_MAX_VCPUS; ++i) {
189 		if (kvm->vcpus[i]) {
190 			kvm_arch_vcpu_free(kvm->vcpus[i]);
191 			kvm->vcpus[i] = NULL;
192 		}
193 	}
194 	atomic_set(&kvm->online_vcpus, 0);
195 }
196 
kvm_vm_ioctl_check_extension(struct kvm * kvm,long ext)197 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
198 {
199 	int r;
200 	switch (ext) {
201 	case KVM_CAP_IRQCHIP:
202 		r = vgic_present;
203 		break;
204 	case KVM_CAP_IOEVENTFD:
205 	case KVM_CAP_DEVICE_CTRL:
206 	case KVM_CAP_USER_MEMORY:
207 	case KVM_CAP_SYNC_MMU:
208 	case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
209 	case KVM_CAP_ONE_REG:
210 	case KVM_CAP_ARM_PSCI:
211 	case KVM_CAP_ARM_PSCI_0_2:
212 	case KVM_CAP_READONLY_MEM:
213 	case KVM_CAP_MP_STATE:
214 	case KVM_CAP_IMMEDIATE_EXIT:
215 		r = 1;
216 		break;
217 	case KVM_CAP_ARM_SET_DEVICE_ADDR:
218 		r = 1;
219 		break;
220 	case KVM_CAP_NR_VCPUS:
221 		r = num_online_cpus();
222 		break;
223 	case KVM_CAP_MAX_VCPUS:
224 		r = KVM_MAX_VCPUS;
225 		break;
226 	case KVM_CAP_MAX_VCPU_ID:
227 		r = KVM_MAX_VCPU_ID;
228 		break;
229 	case KVM_CAP_NR_MEMSLOTS:
230 		r = KVM_USER_MEM_SLOTS;
231 		break;
232 	case KVM_CAP_MSI_DEVID:
233 		if (!kvm)
234 			r = -EINVAL;
235 		else
236 			r = kvm->arch.vgic.msis_require_devid;
237 		break;
238 	case KVM_CAP_ARM_USER_IRQ:
239 		/*
240 		 * 1: EL1_VTIMER, EL1_PTIMER, and PMU.
241 		 * (bump this number if adding more devices)
242 		 */
243 		r = 1;
244 		break;
245 	default:
246 		r = kvm_arch_dev_ioctl_check_extension(kvm, ext);
247 		break;
248 	}
249 	return r;
250 }
251 
kvm_arch_dev_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)252 long kvm_arch_dev_ioctl(struct file *filp,
253 			unsigned int ioctl, unsigned long arg)
254 {
255 	return -EINVAL;
256 }
257 
kvm_arch_alloc_vm(void)258 struct kvm *kvm_arch_alloc_vm(void)
259 {
260 	if (!has_vhe())
261 		return kzalloc(sizeof(struct kvm), GFP_KERNEL);
262 
263 	return vzalloc(sizeof(struct kvm));
264 }
265 
kvm_arch_free_vm(struct kvm * kvm)266 void kvm_arch_free_vm(struct kvm *kvm)
267 {
268 	if (!has_vhe())
269 		kfree(kvm);
270 	else
271 		vfree(kvm);
272 }
273 
kvm_arch_vcpu_create(struct kvm * kvm,unsigned int id)274 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm, unsigned int id)
275 {
276 	int err;
277 	struct kvm_vcpu *vcpu;
278 
279 	if (irqchip_in_kernel(kvm) && vgic_initialized(kvm)) {
280 		err = -EBUSY;
281 		goto out;
282 	}
283 
284 	if (id >= kvm->arch.max_vcpus) {
285 		err = -EINVAL;
286 		goto out;
287 	}
288 
289 	vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
290 	if (!vcpu) {
291 		err = -ENOMEM;
292 		goto out;
293 	}
294 
295 	err = kvm_vcpu_init(vcpu, kvm, id);
296 	if (err)
297 		goto free_vcpu;
298 
299 	err = create_hyp_mappings(vcpu, vcpu + 1, PAGE_HYP);
300 	if (err)
301 		goto vcpu_uninit;
302 
303 	return vcpu;
304 vcpu_uninit:
305 	kvm_vcpu_uninit(vcpu);
306 free_vcpu:
307 	kmem_cache_free(kvm_vcpu_cache, vcpu);
308 out:
309 	return ERR_PTR(err);
310 }
311 
kvm_arch_vcpu_postcreate(struct kvm_vcpu * vcpu)312 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
313 {
314 }
315 
kvm_arch_vcpu_free(struct kvm_vcpu * vcpu)316 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
317 {
318 	if (vcpu->arch.has_run_once && unlikely(!irqchip_in_kernel(vcpu->kvm)))
319 		static_branch_dec(&userspace_irqchip_in_use);
320 
321 	kvm_mmu_free_memory_caches(vcpu);
322 	kvm_timer_vcpu_terminate(vcpu);
323 	kvm_pmu_vcpu_destroy(vcpu);
324 	kvm_vcpu_uninit(vcpu);
325 	kmem_cache_free(kvm_vcpu_cache, vcpu);
326 }
327 
kvm_arch_vcpu_destroy(struct kvm_vcpu * vcpu)328 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
329 {
330 	kvm_arch_vcpu_free(vcpu);
331 }
332 
kvm_cpu_has_pending_timer(struct kvm_vcpu * vcpu)333 int kvm_cpu_has_pending_timer(struct kvm_vcpu *vcpu)
334 {
335 	return kvm_timer_is_pending(vcpu);
336 }
337 
kvm_arch_vcpu_blocking(struct kvm_vcpu * vcpu)338 void kvm_arch_vcpu_blocking(struct kvm_vcpu *vcpu)
339 {
340 	kvm_timer_schedule(vcpu);
341 	/*
342 	 * If we're about to block (most likely because we've just hit a
343 	 * WFI), we need to sync back the state of the GIC CPU interface
344 	 * so that we have the lastest PMR and group enables. This ensures
345 	 * that kvm_arch_vcpu_runnable has up-to-date data to decide
346 	 * whether we have pending interrupts.
347 	 */
348 	preempt_disable();
349 	kvm_vgic_vmcr_sync(vcpu);
350 	preempt_enable();
351 
352 	kvm_vgic_v4_enable_doorbell(vcpu);
353 }
354 
kvm_arch_vcpu_unblocking(struct kvm_vcpu * vcpu)355 void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu)
356 {
357 	kvm_timer_unschedule(vcpu);
358 	kvm_vgic_v4_disable_doorbell(vcpu);
359 }
360 
kvm_arch_vcpu_init(struct kvm_vcpu * vcpu)361 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
362 {
363 	/* Force users to call KVM_ARM_VCPU_INIT */
364 	vcpu->arch.target = -1;
365 	bitmap_zero(vcpu->arch.features, KVM_VCPU_MAX_FEATURES);
366 
367 	/* Set up the timer */
368 	kvm_timer_vcpu_init(vcpu);
369 
370 	kvm_arm_reset_debug_ptr(vcpu);
371 
372 	return kvm_vgic_vcpu_init(vcpu);
373 }
374 
kvm_arch_vcpu_load(struct kvm_vcpu * vcpu,int cpu)375 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
376 {
377 	int *last_ran;
378 
379 	last_ran = this_cpu_ptr(vcpu->kvm->arch.last_vcpu_ran);
380 
381 	/*
382 	 * We might get preempted before the vCPU actually runs, but
383 	 * over-invalidation doesn't affect correctness.
384 	 */
385 	if (*last_ran != vcpu->vcpu_id) {
386 		kvm_call_hyp(__kvm_tlb_flush_local_vmid, vcpu);
387 		*last_ran = vcpu->vcpu_id;
388 	}
389 
390 	vcpu->cpu = cpu;
391 	vcpu->arch.host_cpu_context = this_cpu_ptr(&kvm_host_cpu_state);
392 
393 	kvm_arm_set_running_vcpu(vcpu);
394 	kvm_vgic_load(vcpu);
395 	kvm_timer_vcpu_load(vcpu);
396 	kvm_vcpu_load_sysregs(vcpu);
397 	kvm_arch_vcpu_load_fp(vcpu);
398 
399 	if (single_task_running())
400 		vcpu_clear_wfe_traps(vcpu);
401 	else
402 		vcpu_set_wfe_traps(vcpu);
403 }
404 
kvm_arch_vcpu_put(struct kvm_vcpu * vcpu)405 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
406 {
407 	kvm_arch_vcpu_put_fp(vcpu);
408 	kvm_vcpu_put_sysregs(vcpu);
409 	kvm_timer_vcpu_put(vcpu);
410 	kvm_vgic_put(vcpu);
411 
412 	vcpu->cpu = -1;
413 
414 	kvm_arm_set_running_vcpu(NULL);
415 }
416 
vcpu_power_off(struct kvm_vcpu * vcpu)417 static void vcpu_power_off(struct kvm_vcpu *vcpu)
418 {
419 	vcpu->arch.power_off = true;
420 	kvm_make_request(KVM_REQ_SLEEP, vcpu);
421 	kvm_vcpu_kick(vcpu);
422 }
423 
kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)424 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
425 				    struct kvm_mp_state *mp_state)
426 {
427 	if (vcpu->arch.power_off)
428 		mp_state->mp_state = KVM_MP_STATE_STOPPED;
429 	else
430 		mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
431 
432 	return 0;
433 }
434 
kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)435 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
436 				    struct kvm_mp_state *mp_state)
437 {
438 	int ret = 0;
439 
440 	switch (mp_state->mp_state) {
441 	case KVM_MP_STATE_RUNNABLE:
442 		vcpu->arch.power_off = false;
443 		break;
444 	case KVM_MP_STATE_STOPPED:
445 		vcpu_power_off(vcpu);
446 		break;
447 	default:
448 		ret = -EINVAL;
449 	}
450 
451 	return ret;
452 }
453 
454 /**
455  * kvm_arch_vcpu_runnable - determine if the vcpu can be scheduled
456  * @v:		The VCPU pointer
457  *
458  * If the guest CPU is not waiting for interrupts or an interrupt line is
459  * asserted, the CPU is by definition runnable.
460  */
kvm_arch_vcpu_runnable(struct kvm_vcpu * v)461 int kvm_arch_vcpu_runnable(struct kvm_vcpu *v)
462 {
463 	bool irq_lines = *vcpu_hcr(v) & (HCR_VI | HCR_VF);
464 	return ((irq_lines || kvm_vgic_vcpu_pending_irq(v))
465 		&& !v->arch.power_off && !v->arch.pause);
466 }
467 
kvm_arch_vcpu_in_kernel(struct kvm_vcpu * vcpu)468 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
469 {
470 	return vcpu_mode_priv(vcpu);
471 }
472 
473 /* Just ensure a guest exit from a particular CPU */
exit_vm_noop(void * info)474 static void exit_vm_noop(void *info)
475 {
476 }
477 
force_vm_exit(const cpumask_t * mask)478 void force_vm_exit(const cpumask_t *mask)
479 {
480 	preempt_disable();
481 	smp_call_function_many(mask, exit_vm_noop, NULL, true);
482 	preempt_enable();
483 }
484 
485 /**
486  * need_new_vmid_gen - check that the VMID is still valid
487  * @kvm: The VM's VMID to check
488  *
489  * return true if there is a new generation of VMIDs being used
490  *
491  * The hardware supports only 256 values with the value zero reserved for the
492  * host, so we check if an assigned value belongs to a previous generation,
493  * which which requires us to assign a new value. If we're the first to use a
494  * VMID for the new generation, we must flush necessary caches and TLBs on all
495  * CPUs.
496  */
need_new_vmid_gen(struct kvm * kvm)497 static bool need_new_vmid_gen(struct kvm *kvm)
498 {
499 	u64 current_vmid_gen = atomic64_read(&kvm_vmid_gen);
500 	smp_rmb(); /* Orders read of kvm_vmid_gen and kvm->arch.vmid */
501 	return unlikely(READ_ONCE(kvm->arch.vmid_gen) != current_vmid_gen);
502 }
503 
504 /**
505  * update_vttbr - Update the VTTBR with a valid VMID before the guest runs
506  * @kvm	The guest that we are about to run
507  *
508  * Called from kvm_arch_vcpu_ioctl_run before entering the guest to ensure the
509  * VM has a valid VMID, otherwise assigns a new one and flushes corresponding
510  * caches and TLBs.
511  */
update_vttbr(struct kvm * kvm)512 static void update_vttbr(struct kvm *kvm)
513 {
514 	phys_addr_t pgd_phys;
515 	u64 vmid;
516 
517 	if (!need_new_vmid_gen(kvm))
518 		return;
519 
520 	spin_lock(&kvm_vmid_lock);
521 
522 	/*
523 	 * We need to re-check the vmid_gen here to ensure that if another vcpu
524 	 * already allocated a valid vmid for this vm, then this vcpu should
525 	 * use the same vmid.
526 	 */
527 	if (!need_new_vmid_gen(kvm)) {
528 		spin_unlock(&kvm_vmid_lock);
529 		return;
530 	}
531 
532 	/* First user of a new VMID generation? */
533 	if (unlikely(kvm_next_vmid == 0)) {
534 		atomic64_inc(&kvm_vmid_gen);
535 		kvm_next_vmid = 1;
536 
537 		/*
538 		 * On SMP we know no other CPUs can use this CPU's or each
539 		 * other's VMID after force_vm_exit returns since the
540 		 * kvm_vmid_lock blocks them from reentry to the guest.
541 		 */
542 		force_vm_exit(cpu_all_mask);
543 		/*
544 		 * Now broadcast TLB + ICACHE invalidation over the inner
545 		 * shareable domain to make sure all data structures are
546 		 * clean.
547 		 */
548 		kvm_call_hyp(__kvm_flush_vm_context);
549 	}
550 
551 	kvm->arch.vmid = kvm_next_vmid;
552 	kvm_next_vmid++;
553 	kvm_next_vmid &= (1 << kvm_vmid_bits) - 1;
554 
555 	/* update vttbr to be used with the new vmid */
556 	pgd_phys = virt_to_phys(kvm->arch.pgd);
557 	BUG_ON(pgd_phys & ~VTTBR_BADDR_MASK);
558 	vmid = ((u64)(kvm->arch.vmid) << VTTBR_VMID_SHIFT) & VTTBR_VMID_MASK(kvm_vmid_bits);
559 	kvm->arch.vttbr = kvm_phys_to_vttbr(pgd_phys) | vmid;
560 
561 	smp_wmb();
562 	WRITE_ONCE(kvm->arch.vmid_gen, atomic64_read(&kvm_vmid_gen));
563 
564 	spin_unlock(&kvm_vmid_lock);
565 }
566 
kvm_vcpu_first_run_init(struct kvm_vcpu * vcpu)567 static int kvm_vcpu_first_run_init(struct kvm_vcpu *vcpu)
568 {
569 	struct kvm *kvm = vcpu->kvm;
570 	int ret = 0;
571 
572 	if (likely(vcpu->arch.has_run_once))
573 		return 0;
574 
575 	vcpu->arch.has_run_once = true;
576 
577 	kvm_arm_vcpu_init_debug(vcpu);
578 
579 	if (likely(irqchip_in_kernel(kvm))) {
580 		/*
581 		 * Map the VGIC hardware resources before running a vcpu the
582 		 * first time on this VM.
583 		 */
584 		if (unlikely(!vgic_ready(kvm))) {
585 			ret = kvm_vgic_map_resources(kvm);
586 			if (ret)
587 				return ret;
588 		}
589 	} else {
590 		/*
591 		 * Tell the rest of the code that there are userspace irqchip
592 		 * VMs in the wild.
593 		 */
594 		static_branch_inc(&userspace_irqchip_in_use);
595 	}
596 
597 	ret = kvm_timer_enable(vcpu);
598 	if (ret)
599 		return ret;
600 
601 	ret = kvm_arm_pmu_v3_enable(vcpu);
602 
603 	return ret;
604 }
605 
kvm_arch_intc_initialized(struct kvm * kvm)606 bool kvm_arch_intc_initialized(struct kvm *kvm)
607 {
608 	return vgic_initialized(kvm);
609 }
610 
kvm_arm_halt_guest(struct kvm * kvm)611 void kvm_arm_halt_guest(struct kvm *kvm)
612 {
613 	int i;
614 	struct kvm_vcpu *vcpu;
615 
616 	kvm_for_each_vcpu(i, vcpu, kvm)
617 		vcpu->arch.pause = true;
618 	kvm_make_all_cpus_request(kvm, KVM_REQ_SLEEP);
619 }
620 
kvm_arm_resume_guest(struct kvm * kvm)621 void kvm_arm_resume_guest(struct kvm *kvm)
622 {
623 	int i;
624 	struct kvm_vcpu *vcpu;
625 
626 	kvm_for_each_vcpu(i, vcpu, kvm) {
627 		vcpu->arch.pause = false;
628 		swake_up_one(kvm_arch_vcpu_wq(vcpu));
629 	}
630 }
631 
vcpu_req_sleep(struct kvm_vcpu * vcpu)632 static void vcpu_req_sleep(struct kvm_vcpu *vcpu)
633 {
634 	struct swait_queue_head *wq = kvm_arch_vcpu_wq(vcpu);
635 
636 	swait_event_interruptible_exclusive(*wq, ((!vcpu->arch.power_off) &&
637 				       (!vcpu->arch.pause)));
638 
639 	if (vcpu->arch.power_off || vcpu->arch.pause) {
640 		/* Awaken to handle a signal, request we sleep again later. */
641 		kvm_make_request(KVM_REQ_SLEEP, vcpu);
642 	}
643 
644 	/*
645 	 * Make sure we will observe a potential reset request if we've
646 	 * observed a change to the power state. Pairs with the smp_wmb() in
647 	 * kvm_psci_vcpu_on().
648 	 */
649 	smp_rmb();
650 }
651 
kvm_vcpu_initialized(struct kvm_vcpu * vcpu)652 static int kvm_vcpu_initialized(struct kvm_vcpu *vcpu)
653 {
654 	return vcpu->arch.target >= 0;
655 }
656 
check_vcpu_requests(struct kvm_vcpu * vcpu)657 static void check_vcpu_requests(struct kvm_vcpu *vcpu)
658 {
659 	if (kvm_request_pending(vcpu)) {
660 		if (kvm_check_request(KVM_REQ_SLEEP, vcpu))
661 			vcpu_req_sleep(vcpu);
662 
663 		if (kvm_check_request(KVM_REQ_VCPU_RESET, vcpu))
664 			kvm_reset_vcpu(vcpu);
665 
666 		/*
667 		 * Clear IRQ_PENDING requests that were made to guarantee
668 		 * that a VCPU sees new virtual interrupts.
669 		 */
670 		kvm_check_request(KVM_REQ_IRQ_PENDING, vcpu);
671 	}
672 }
673 
674 /**
675  * kvm_arch_vcpu_ioctl_run - the main VCPU run function to execute guest code
676  * @vcpu:	The VCPU pointer
677  * @run:	The kvm_run structure pointer used for userspace state exchange
678  *
679  * This function is called through the VCPU_RUN ioctl called from user space. It
680  * will execute VM code in a loop until the time slice for the process is used
681  * or some emulation is needed from user space in which case the function will
682  * return with return value 0 and with the kvm_run structure filled in with the
683  * required data for the requested emulation.
684  */
kvm_arch_vcpu_ioctl_run(struct kvm_vcpu * vcpu,struct kvm_run * run)685 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *run)
686 {
687 	int ret;
688 
689 	if (unlikely(!kvm_vcpu_initialized(vcpu)))
690 		return -ENOEXEC;
691 
692 	ret = kvm_vcpu_first_run_init(vcpu);
693 	if (ret)
694 		return ret;
695 
696 	if (run->exit_reason == KVM_EXIT_MMIO) {
697 		ret = kvm_handle_mmio_return(vcpu, vcpu->run);
698 		if (ret)
699 			return ret;
700 		if (kvm_arm_handle_step_debug(vcpu, vcpu->run))
701 			return 0;
702 	}
703 
704 	if (run->immediate_exit)
705 		return -EINTR;
706 
707 	vcpu_load(vcpu);
708 
709 	kvm_sigset_activate(vcpu);
710 
711 	ret = 1;
712 	run->exit_reason = KVM_EXIT_UNKNOWN;
713 	while (ret > 0) {
714 		/*
715 		 * Check conditions before entering the guest
716 		 */
717 		cond_resched();
718 
719 		update_vttbr(vcpu->kvm);
720 
721 		check_vcpu_requests(vcpu);
722 
723 		/*
724 		 * Preparing the interrupts to be injected also
725 		 * involves poking the GIC, which must be done in a
726 		 * non-preemptible context.
727 		 */
728 		preempt_disable();
729 
730 		kvm_pmu_flush_hwstate(vcpu);
731 
732 		local_irq_disable();
733 
734 		kvm_vgic_flush_hwstate(vcpu);
735 
736 		/*
737 		 * Exit if we have a signal pending so that we can deliver the
738 		 * signal to user space.
739 		 */
740 		if (signal_pending(current)) {
741 			ret = -EINTR;
742 			run->exit_reason = KVM_EXIT_INTR;
743 		}
744 
745 		/*
746 		 * If we're using a userspace irqchip, then check if we need
747 		 * to tell a userspace irqchip about timer or PMU level
748 		 * changes and if so, exit to userspace (the actual level
749 		 * state gets updated in kvm_timer_update_run and
750 		 * kvm_pmu_update_run below).
751 		 */
752 		if (static_branch_unlikely(&userspace_irqchip_in_use)) {
753 			if (kvm_timer_should_notify_user(vcpu) ||
754 			    kvm_pmu_should_notify_user(vcpu)) {
755 				ret = -EINTR;
756 				run->exit_reason = KVM_EXIT_INTR;
757 			}
758 		}
759 
760 		/*
761 		 * Ensure we set mode to IN_GUEST_MODE after we disable
762 		 * interrupts and before the final VCPU requests check.
763 		 * See the comment in kvm_vcpu_exiting_guest_mode() and
764 		 * Documentation/virtual/kvm/vcpu-requests.rst
765 		 */
766 		smp_store_mb(vcpu->mode, IN_GUEST_MODE);
767 
768 		if (ret <= 0 || need_new_vmid_gen(vcpu->kvm) ||
769 		    kvm_request_pending(vcpu)) {
770 			vcpu->mode = OUTSIDE_GUEST_MODE;
771 			isb(); /* Ensure work in x_flush_hwstate is committed */
772 			kvm_pmu_sync_hwstate(vcpu);
773 			if (static_branch_unlikely(&userspace_irqchip_in_use))
774 				kvm_timer_sync_hwstate(vcpu);
775 			kvm_vgic_sync_hwstate(vcpu);
776 			local_irq_enable();
777 			preempt_enable();
778 			continue;
779 		}
780 
781 		kvm_arm_setup_debug(vcpu);
782 
783 		/**************************************************************
784 		 * Enter the guest
785 		 */
786 		trace_kvm_entry(*vcpu_pc(vcpu));
787 		guest_enter_irqoff();
788 
789 		if (has_vhe()) {
790 			kvm_arm_vhe_guest_enter();
791 			ret = kvm_vcpu_run_vhe(vcpu);
792 			kvm_arm_vhe_guest_exit();
793 		} else {
794 			ret = kvm_call_hyp(__kvm_vcpu_run_nvhe, vcpu);
795 		}
796 
797 		vcpu->mode = OUTSIDE_GUEST_MODE;
798 		vcpu->stat.exits++;
799 		/*
800 		 * Back from guest
801 		 *************************************************************/
802 
803 		kvm_arm_clear_debug(vcpu);
804 
805 		/*
806 		 * We must sync the PMU state before the vgic state so
807 		 * that the vgic can properly sample the updated state of the
808 		 * interrupt line.
809 		 */
810 		kvm_pmu_sync_hwstate(vcpu);
811 
812 		/*
813 		 * Sync the vgic state before syncing the timer state because
814 		 * the timer code needs to know if the virtual timer
815 		 * interrupts are active.
816 		 */
817 		kvm_vgic_sync_hwstate(vcpu);
818 
819 		/*
820 		 * Sync the timer hardware state before enabling interrupts as
821 		 * we don't want vtimer interrupts to race with syncing the
822 		 * timer virtual interrupt state.
823 		 */
824 		if (static_branch_unlikely(&userspace_irqchip_in_use))
825 			kvm_timer_sync_hwstate(vcpu);
826 
827 		kvm_arch_vcpu_ctxsync_fp(vcpu);
828 
829 		/*
830 		 * We may have taken a host interrupt in HYP mode (ie
831 		 * while executing the guest). This interrupt is still
832 		 * pending, as we haven't serviced it yet!
833 		 *
834 		 * We're now back in SVC mode, with interrupts
835 		 * disabled.  Enabling the interrupts now will have
836 		 * the effect of taking the interrupt again, in SVC
837 		 * mode this time.
838 		 */
839 		local_irq_enable();
840 
841 		/*
842 		 * We do local_irq_enable() before calling guest_exit() so
843 		 * that if a timer interrupt hits while running the guest we
844 		 * account that tick as being spent in the guest.  We enable
845 		 * preemption after calling guest_exit() so that if we get
846 		 * preempted we make sure ticks after that is not counted as
847 		 * guest time.
848 		 */
849 		guest_exit();
850 		trace_kvm_exit(ret, kvm_vcpu_trap_get_class(vcpu), *vcpu_pc(vcpu));
851 
852 		/* Exit types that need handling before we can be preempted */
853 		handle_exit_early(vcpu, run, ret);
854 
855 		preempt_enable();
856 
857 		ret = handle_exit(vcpu, run, ret);
858 	}
859 
860 	/* Tell userspace about in-kernel device output levels */
861 	if (unlikely(!irqchip_in_kernel(vcpu->kvm))) {
862 		kvm_timer_update_run(vcpu);
863 		kvm_pmu_update_run(vcpu);
864 	}
865 
866 	kvm_sigset_deactivate(vcpu);
867 
868 	vcpu_put(vcpu);
869 	return ret;
870 }
871 
vcpu_interrupt_line(struct kvm_vcpu * vcpu,int number,bool level)872 static int vcpu_interrupt_line(struct kvm_vcpu *vcpu, int number, bool level)
873 {
874 	int bit_index;
875 	bool set;
876 	unsigned long *hcr;
877 
878 	if (number == KVM_ARM_IRQ_CPU_IRQ)
879 		bit_index = __ffs(HCR_VI);
880 	else /* KVM_ARM_IRQ_CPU_FIQ */
881 		bit_index = __ffs(HCR_VF);
882 
883 	hcr = vcpu_hcr(vcpu);
884 	if (level)
885 		set = test_and_set_bit(bit_index, hcr);
886 	else
887 		set = test_and_clear_bit(bit_index, hcr);
888 
889 	/*
890 	 * If we didn't change anything, no need to wake up or kick other CPUs
891 	 */
892 	if (set == level)
893 		return 0;
894 
895 	/*
896 	 * The vcpu irq_lines field was updated, wake up sleeping VCPUs and
897 	 * trigger a world-switch round on the running physical CPU to set the
898 	 * virtual IRQ/FIQ fields in the HCR appropriately.
899 	 */
900 	kvm_make_request(KVM_REQ_IRQ_PENDING, vcpu);
901 	kvm_vcpu_kick(vcpu);
902 
903 	return 0;
904 }
905 
kvm_vm_ioctl_irq_line(struct kvm * kvm,struct kvm_irq_level * irq_level,bool line_status)906 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_level,
907 			  bool line_status)
908 {
909 	u32 irq = irq_level->irq;
910 	unsigned int irq_type, vcpu_idx, irq_num;
911 	int nrcpus = atomic_read(&kvm->online_vcpus);
912 	struct kvm_vcpu *vcpu = NULL;
913 	bool level = irq_level->level;
914 
915 	irq_type = (irq >> KVM_ARM_IRQ_TYPE_SHIFT) & KVM_ARM_IRQ_TYPE_MASK;
916 	vcpu_idx = (irq >> KVM_ARM_IRQ_VCPU_SHIFT) & KVM_ARM_IRQ_VCPU_MASK;
917 	irq_num = (irq >> KVM_ARM_IRQ_NUM_SHIFT) & KVM_ARM_IRQ_NUM_MASK;
918 
919 	trace_kvm_irq_line(irq_type, vcpu_idx, irq_num, irq_level->level);
920 
921 	switch (irq_type) {
922 	case KVM_ARM_IRQ_TYPE_CPU:
923 		if (irqchip_in_kernel(kvm))
924 			return -ENXIO;
925 
926 		if (vcpu_idx >= nrcpus)
927 			return -EINVAL;
928 
929 		vcpu = kvm_get_vcpu(kvm, vcpu_idx);
930 		if (!vcpu)
931 			return -EINVAL;
932 
933 		if (irq_num > KVM_ARM_IRQ_CPU_FIQ)
934 			return -EINVAL;
935 
936 		return vcpu_interrupt_line(vcpu, irq_num, level);
937 	case KVM_ARM_IRQ_TYPE_PPI:
938 		if (!irqchip_in_kernel(kvm))
939 			return -ENXIO;
940 
941 		if (vcpu_idx >= nrcpus)
942 			return -EINVAL;
943 
944 		vcpu = kvm_get_vcpu(kvm, vcpu_idx);
945 		if (!vcpu)
946 			return -EINVAL;
947 
948 		if (irq_num < VGIC_NR_SGIS || irq_num >= VGIC_NR_PRIVATE_IRQS)
949 			return -EINVAL;
950 
951 		return kvm_vgic_inject_irq(kvm, vcpu->vcpu_id, irq_num, level, NULL);
952 	case KVM_ARM_IRQ_TYPE_SPI:
953 		if (!irqchip_in_kernel(kvm))
954 			return -ENXIO;
955 
956 		if (irq_num < VGIC_NR_PRIVATE_IRQS)
957 			return -EINVAL;
958 
959 		return kvm_vgic_inject_irq(kvm, 0, irq_num, level, NULL);
960 	}
961 
962 	return -EINVAL;
963 }
964 
kvm_vcpu_set_target(struct kvm_vcpu * vcpu,const struct kvm_vcpu_init * init)965 static int kvm_vcpu_set_target(struct kvm_vcpu *vcpu,
966 			       const struct kvm_vcpu_init *init)
967 {
968 	unsigned int i, ret;
969 	int phys_target = kvm_target_cpu();
970 
971 	if (init->target != phys_target)
972 		return -EINVAL;
973 
974 	/*
975 	 * Secondary and subsequent calls to KVM_ARM_VCPU_INIT must
976 	 * use the same target.
977 	 */
978 	if (vcpu->arch.target != -1 && vcpu->arch.target != init->target)
979 		return -EINVAL;
980 
981 	/* -ENOENT for unknown features, -EINVAL for invalid combinations. */
982 	for (i = 0; i < sizeof(init->features) * 8; i++) {
983 		bool set = (init->features[i / 32] & (1 << (i % 32)));
984 
985 		if (set && i >= KVM_VCPU_MAX_FEATURES)
986 			return -ENOENT;
987 
988 		/*
989 		 * Secondary and subsequent calls to KVM_ARM_VCPU_INIT must
990 		 * use the same feature set.
991 		 */
992 		if (vcpu->arch.target != -1 && i < KVM_VCPU_MAX_FEATURES &&
993 		    test_bit(i, vcpu->arch.features) != set)
994 			return -EINVAL;
995 
996 		if (set)
997 			set_bit(i, vcpu->arch.features);
998 	}
999 
1000 	vcpu->arch.target = phys_target;
1001 
1002 	/* Now we know what it is, we can reset it. */
1003 	ret = kvm_reset_vcpu(vcpu);
1004 	if (ret) {
1005 		vcpu->arch.target = -1;
1006 		bitmap_zero(vcpu->arch.features, KVM_VCPU_MAX_FEATURES);
1007 	}
1008 
1009 	return ret;
1010 }
1011 
kvm_arch_vcpu_ioctl_vcpu_init(struct kvm_vcpu * vcpu,struct kvm_vcpu_init * init)1012 static int kvm_arch_vcpu_ioctl_vcpu_init(struct kvm_vcpu *vcpu,
1013 					 struct kvm_vcpu_init *init)
1014 {
1015 	int ret;
1016 
1017 	ret = kvm_vcpu_set_target(vcpu, init);
1018 	if (ret)
1019 		return ret;
1020 
1021 	/*
1022 	 * Ensure a rebooted VM will fault in RAM pages and detect if the
1023 	 * guest MMU is turned off and flush the caches as needed.
1024 	 */
1025 	if (vcpu->arch.has_run_once)
1026 		stage2_unmap_vm(vcpu->kvm);
1027 
1028 	vcpu_reset_hcr(vcpu);
1029 
1030 	/*
1031 	 * Handle the "start in power-off" case.
1032 	 */
1033 	if (test_bit(KVM_ARM_VCPU_POWER_OFF, vcpu->arch.features))
1034 		vcpu_power_off(vcpu);
1035 	else
1036 		vcpu->arch.power_off = false;
1037 
1038 	return 0;
1039 }
1040 
kvm_arm_vcpu_set_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)1041 static int kvm_arm_vcpu_set_attr(struct kvm_vcpu *vcpu,
1042 				 struct kvm_device_attr *attr)
1043 {
1044 	int ret = -ENXIO;
1045 
1046 	switch (attr->group) {
1047 	default:
1048 		ret = kvm_arm_vcpu_arch_set_attr(vcpu, attr);
1049 		break;
1050 	}
1051 
1052 	return ret;
1053 }
1054 
kvm_arm_vcpu_get_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)1055 static int kvm_arm_vcpu_get_attr(struct kvm_vcpu *vcpu,
1056 				 struct kvm_device_attr *attr)
1057 {
1058 	int ret = -ENXIO;
1059 
1060 	switch (attr->group) {
1061 	default:
1062 		ret = kvm_arm_vcpu_arch_get_attr(vcpu, attr);
1063 		break;
1064 	}
1065 
1066 	return ret;
1067 }
1068 
kvm_arm_vcpu_has_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)1069 static int kvm_arm_vcpu_has_attr(struct kvm_vcpu *vcpu,
1070 				 struct kvm_device_attr *attr)
1071 {
1072 	int ret = -ENXIO;
1073 
1074 	switch (attr->group) {
1075 	default:
1076 		ret = kvm_arm_vcpu_arch_has_attr(vcpu, attr);
1077 		break;
1078 	}
1079 
1080 	return ret;
1081 }
1082 
kvm_arm_vcpu_get_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)1083 static int kvm_arm_vcpu_get_events(struct kvm_vcpu *vcpu,
1084 				   struct kvm_vcpu_events *events)
1085 {
1086 	memset(events, 0, sizeof(*events));
1087 
1088 	return __kvm_arm_vcpu_get_events(vcpu, events);
1089 }
1090 
kvm_arm_vcpu_set_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)1091 static int kvm_arm_vcpu_set_events(struct kvm_vcpu *vcpu,
1092 				   struct kvm_vcpu_events *events)
1093 {
1094 	int i;
1095 
1096 	/* check whether the reserved field is zero */
1097 	for (i = 0; i < ARRAY_SIZE(events->reserved); i++)
1098 		if (events->reserved[i])
1099 			return -EINVAL;
1100 
1101 	/* check whether the pad field is zero */
1102 	for (i = 0; i < ARRAY_SIZE(events->exception.pad); i++)
1103 		if (events->exception.pad[i])
1104 			return -EINVAL;
1105 
1106 	return __kvm_arm_vcpu_set_events(vcpu, events);
1107 }
1108 
kvm_arch_vcpu_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)1109 long kvm_arch_vcpu_ioctl(struct file *filp,
1110 			 unsigned int ioctl, unsigned long arg)
1111 {
1112 	struct kvm_vcpu *vcpu = filp->private_data;
1113 	void __user *argp = (void __user *)arg;
1114 	struct kvm_device_attr attr;
1115 	long r;
1116 
1117 	switch (ioctl) {
1118 	case KVM_ARM_VCPU_INIT: {
1119 		struct kvm_vcpu_init init;
1120 
1121 		r = -EFAULT;
1122 		if (copy_from_user(&init, argp, sizeof(init)))
1123 			break;
1124 
1125 		r = kvm_arch_vcpu_ioctl_vcpu_init(vcpu, &init);
1126 		break;
1127 	}
1128 	case KVM_SET_ONE_REG:
1129 	case KVM_GET_ONE_REG: {
1130 		struct kvm_one_reg reg;
1131 
1132 		r = -ENOEXEC;
1133 		if (unlikely(!kvm_vcpu_initialized(vcpu)))
1134 			break;
1135 
1136 		r = -EFAULT;
1137 		if (copy_from_user(&reg, argp, sizeof(reg)))
1138 			break;
1139 
1140 		/*
1141 		 * We could owe a reset due to PSCI. Handle the pending reset
1142 		 * here to ensure userspace register accesses are ordered after
1143 		 * the reset.
1144 		 */
1145 		if (kvm_check_request(KVM_REQ_VCPU_RESET, vcpu))
1146 			kvm_reset_vcpu(vcpu);
1147 
1148 		if (ioctl == KVM_SET_ONE_REG)
1149 			r = kvm_arm_set_reg(vcpu, &reg);
1150 		else
1151 			r = kvm_arm_get_reg(vcpu, &reg);
1152 		break;
1153 	}
1154 	case KVM_GET_REG_LIST: {
1155 		struct kvm_reg_list __user *user_list = argp;
1156 		struct kvm_reg_list reg_list;
1157 		unsigned n;
1158 
1159 		r = -ENOEXEC;
1160 		if (unlikely(!kvm_vcpu_initialized(vcpu)))
1161 			break;
1162 
1163 		r = -EFAULT;
1164 		if (copy_from_user(&reg_list, user_list, sizeof(reg_list)))
1165 			break;
1166 		n = reg_list.n;
1167 		reg_list.n = kvm_arm_num_regs(vcpu);
1168 		if (copy_to_user(user_list, &reg_list, sizeof(reg_list)))
1169 			break;
1170 		r = -E2BIG;
1171 		if (n < reg_list.n)
1172 			break;
1173 		r = kvm_arm_copy_reg_indices(vcpu, user_list->reg);
1174 		break;
1175 	}
1176 	case KVM_SET_DEVICE_ATTR: {
1177 		r = -EFAULT;
1178 		if (copy_from_user(&attr, argp, sizeof(attr)))
1179 			break;
1180 		r = kvm_arm_vcpu_set_attr(vcpu, &attr);
1181 		break;
1182 	}
1183 	case KVM_GET_DEVICE_ATTR: {
1184 		r = -EFAULT;
1185 		if (copy_from_user(&attr, argp, sizeof(attr)))
1186 			break;
1187 		r = kvm_arm_vcpu_get_attr(vcpu, &attr);
1188 		break;
1189 	}
1190 	case KVM_HAS_DEVICE_ATTR: {
1191 		r = -EFAULT;
1192 		if (copy_from_user(&attr, argp, sizeof(attr)))
1193 			break;
1194 		r = kvm_arm_vcpu_has_attr(vcpu, &attr);
1195 		break;
1196 	}
1197 	case KVM_GET_VCPU_EVENTS: {
1198 		struct kvm_vcpu_events events;
1199 
1200 		if (kvm_arm_vcpu_get_events(vcpu, &events))
1201 			return -EINVAL;
1202 
1203 		if (copy_to_user(argp, &events, sizeof(events)))
1204 			return -EFAULT;
1205 
1206 		return 0;
1207 	}
1208 	case KVM_SET_VCPU_EVENTS: {
1209 		struct kvm_vcpu_events events;
1210 
1211 		if (copy_from_user(&events, argp, sizeof(events)))
1212 			return -EFAULT;
1213 
1214 		return kvm_arm_vcpu_set_events(vcpu, &events);
1215 	}
1216 	default:
1217 		r = -EINVAL;
1218 	}
1219 
1220 	return r;
1221 }
1222 
1223 /**
1224  * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
1225  * @kvm: kvm instance
1226  * @log: slot id and address to which we copy the log
1227  *
1228  * Steps 1-4 below provide general overview of dirty page logging. See
1229  * kvm_get_dirty_log_protect() function description for additional details.
1230  *
1231  * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
1232  * always flush the TLB (step 4) even if previous step failed  and the dirty
1233  * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
1234  * does not preclude user space subsequent dirty log read. Flushing TLB ensures
1235  * writes will be marked dirty for next log read.
1236  *
1237  *   1. Take a snapshot of the bit and clear it if needed.
1238  *   2. Write protect the corresponding page.
1239  *   3. Copy the snapshot to the userspace.
1240  *   4. Flush TLB's if needed.
1241  */
kvm_vm_ioctl_get_dirty_log(struct kvm * kvm,struct kvm_dirty_log * log)1242 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
1243 {
1244 	bool is_dirty = false;
1245 	int r;
1246 
1247 	mutex_lock(&kvm->slots_lock);
1248 
1249 	r = kvm_get_dirty_log_protect(kvm, log, &is_dirty);
1250 
1251 	if (is_dirty)
1252 		kvm_flush_remote_tlbs(kvm);
1253 
1254 	mutex_unlock(&kvm->slots_lock);
1255 	return r;
1256 }
1257 
kvm_vm_ioctl_set_device_addr(struct kvm * kvm,struct kvm_arm_device_addr * dev_addr)1258 static int kvm_vm_ioctl_set_device_addr(struct kvm *kvm,
1259 					struct kvm_arm_device_addr *dev_addr)
1260 {
1261 	unsigned long dev_id, type;
1262 
1263 	dev_id = (dev_addr->id & KVM_ARM_DEVICE_ID_MASK) >>
1264 		KVM_ARM_DEVICE_ID_SHIFT;
1265 	type = (dev_addr->id & KVM_ARM_DEVICE_TYPE_MASK) >>
1266 		KVM_ARM_DEVICE_TYPE_SHIFT;
1267 
1268 	switch (dev_id) {
1269 	case KVM_ARM_DEVICE_VGIC_V2:
1270 		if (!vgic_present)
1271 			return -ENXIO;
1272 		return kvm_vgic_addr(kvm, type, &dev_addr->addr, true);
1273 	default:
1274 		return -ENODEV;
1275 	}
1276 }
1277 
kvm_arch_vm_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)1278 long kvm_arch_vm_ioctl(struct file *filp,
1279 		       unsigned int ioctl, unsigned long arg)
1280 {
1281 	struct kvm *kvm = filp->private_data;
1282 	void __user *argp = (void __user *)arg;
1283 
1284 	switch (ioctl) {
1285 	case KVM_CREATE_IRQCHIP: {
1286 		int ret;
1287 		if (!vgic_present)
1288 			return -ENXIO;
1289 		mutex_lock(&kvm->lock);
1290 		ret = kvm_vgic_create(kvm, KVM_DEV_TYPE_ARM_VGIC_V2);
1291 		mutex_unlock(&kvm->lock);
1292 		return ret;
1293 	}
1294 	case KVM_ARM_SET_DEVICE_ADDR: {
1295 		struct kvm_arm_device_addr dev_addr;
1296 
1297 		if (copy_from_user(&dev_addr, argp, sizeof(dev_addr)))
1298 			return -EFAULT;
1299 		return kvm_vm_ioctl_set_device_addr(kvm, &dev_addr);
1300 	}
1301 	case KVM_ARM_PREFERRED_TARGET: {
1302 		int err;
1303 		struct kvm_vcpu_init init;
1304 
1305 		err = kvm_vcpu_preferred_target(&init);
1306 		if (err)
1307 			return err;
1308 
1309 		if (copy_to_user(argp, &init, sizeof(init)))
1310 			return -EFAULT;
1311 
1312 		return 0;
1313 	}
1314 	default:
1315 		return -EINVAL;
1316 	}
1317 }
1318 
cpu_init_hyp_mode(void * dummy)1319 static void cpu_init_hyp_mode(void *dummy)
1320 {
1321 	phys_addr_t pgd_ptr;
1322 	unsigned long hyp_stack_ptr;
1323 	unsigned long stack_page;
1324 	unsigned long vector_ptr;
1325 
1326 	/* Switch from the HYP stub to our own HYP init vector */
1327 	__hyp_set_vectors(kvm_get_idmap_vector());
1328 
1329 	pgd_ptr = kvm_mmu_get_httbr();
1330 	stack_page = __this_cpu_read(kvm_arm_hyp_stack_page);
1331 	hyp_stack_ptr = stack_page + PAGE_SIZE;
1332 	vector_ptr = (unsigned long)kvm_get_hyp_vector();
1333 
1334 	__cpu_init_hyp_mode(pgd_ptr, hyp_stack_ptr, vector_ptr);
1335 	__cpu_init_stage2();
1336 }
1337 
cpu_hyp_reset(void)1338 static void cpu_hyp_reset(void)
1339 {
1340 	if (!is_kernel_in_hyp_mode())
1341 		__hyp_reset_vectors();
1342 }
1343 
cpu_hyp_reinit(void)1344 static void cpu_hyp_reinit(void)
1345 {
1346 	cpu_hyp_reset();
1347 
1348 	if (is_kernel_in_hyp_mode()) {
1349 		/*
1350 		 * __cpu_init_stage2() is safe to call even if the PM
1351 		 * event was cancelled before the CPU was reset.
1352 		 */
1353 		__cpu_init_stage2();
1354 		kvm_timer_init_vhe();
1355 	} else {
1356 		cpu_init_hyp_mode(NULL);
1357 	}
1358 
1359 	kvm_arm_init_debug();
1360 
1361 	if (vgic_present)
1362 		kvm_vgic_init_cpu_hardware();
1363 }
1364 
_kvm_arch_hardware_enable(void * discard)1365 static void _kvm_arch_hardware_enable(void *discard)
1366 {
1367 	if (!__this_cpu_read(kvm_arm_hardware_enabled)) {
1368 		cpu_hyp_reinit();
1369 		__this_cpu_write(kvm_arm_hardware_enabled, 1);
1370 	}
1371 }
1372 
kvm_arch_hardware_enable(void)1373 int kvm_arch_hardware_enable(void)
1374 {
1375 	_kvm_arch_hardware_enable(NULL);
1376 	return 0;
1377 }
1378 
_kvm_arch_hardware_disable(void * discard)1379 static void _kvm_arch_hardware_disable(void *discard)
1380 {
1381 	if (__this_cpu_read(kvm_arm_hardware_enabled)) {
1382 		cpu_hyp_reset();
1383 		__this_cpu_write(kvm_arm_hardware_enabled, 0);
1384 	}
1385 }
1386 
kvm_arch_hardware_disable(void)1387 void kvm_arch_hardware_disable(void)
1388 {
1389 	_kvm_arch_hardware_disable(NULL);
1390 }
1391 
1392 #ifdef CONFIG_CPU_PM
hyp_init_cpu_pm_notifier(struct notifier_block * self,unsigned long cmd,void * v)1393 static int hyp_init_cpu_pm_notifier(struct notifier_block *self,
1394 				    unsigned long cmd,
1395 				    void *v)
1396 {
1397 	/*
1398 	 * kvm_arm_hardware_enabled is left with its old value over
1399 	 * PM_ENTER->PM_EXIT. It is used to indicate PM_EXIT should
1400 	 * re-enable hyp.
1401 	 */
1402 	switch (cmd) {
1403 	case CPU_PM_ENTER:
1404 		if (__this_cpu_read(kvm_arm_hardware_enabled))
1405 			/*
1406 			 * don't update kvm_arm_hardware_enabled here
1407 			 * so that the hardware will be re-enabled
1408 			 * when we resume. See below.
1409 			 */
1410 			cpu_hyp_reset();
1411 
1412 		return NOTIFY_OK;
1413 	case CPU_PM_ENTER_FAILED:
1414 	case CPU_PM_EXIT:
1415 		if (__this_cpu_read(kvm_arm_hardware_enabled))
1416 			/* The hardware was enabled before suspend. */
1417 			cpu_hyp_reinit();
1418 
1419 		return NOTIFY_OK;
1420 
1421 	default:
1422 		return NOTIFY_DONE;
1423 	}
1424 }
1425 
1426 static struct notifier_block hyp_init_cpu_pm_nb = {
1427 	.notifier_call = hyp_init_cpu_pm_notifier,
1428 };
1429 
hyp_cpu_pm_init(void)1430 static void __init hyp_cpu_pm_init(void)
1431 {
1432 	cpu_pm_register_notifier(&hyp_init_cpu_pm_nb);
1433 }
hyp_cpu_pm_exit(void)1434 static void __init hyp_cpu_pm_exit(void)
1435 {
1436 	cpu_pm_unregister_notifier(&hyp_init_cpu_pm_nb);
1437 }
1438 #else
hyp_cpu_pm_init(void)1439 static inline void hyp_cpu_pm_init(void)
1440 {
1441 }
hyp_cpu_pm_exit(void)1442 static inline void hyp_cpu_pm_exit(void)
1443 {
1444 }
1445 #endif
1446 
init_common_resources(void)1447 static int init_common_resources(void)
1448 {
1449 	/* set size of VMID supported by CPU */
1450 	kvm_vmid_bits = kvm_get_vmid_bits();
1451 	kvm_info("%d-bit VMID\n", kvm_vmid_bits);
1452 
1453 	return 0;
1454 }
1455 
init_subsystems(void)1456 static int init_subsystems(void)
1457 {
1458 	int err = 0;
1459 
1460 	/*
1461 	 * Enable hardware so that subsystem initialisation can access EL2.
1462 	 */
1463 	on_each_cpu(_kvm_arch_hardware_enable, NULL, 1);
1464 
1465 	/*
1466 	 * Register CPU lower-power notifier
1467 	 */
1468 	hyp_cpu_pm_init();
1469 
1470 	/*
1471 	 * Init HYP view of VGIC
1472 	 */
1473 	err = kvm_vgic_hyp_init();
1474 	switch (err) {
1475 	case 0:
1476 		vgic_present = true;
1477 		break;
1478 	case -ENODEV:
1479 	case -ENXIO:
1480 		vgic_present = false;
1481 		err = 0;
1482 		break;
1483 	default:
1484 		goto out;
1485 	}
1486 
1487 	/*
1488 	 * Init HYP architected timer support
1489 	 */
1490 	err = kvm_timer_hyp_init(vgic_present);
1491 	if (err)
1492 		goto out;
1493 
1494 	kvm_perf_init();
1495 	kvm_coproc_table_init();
1496 
1497 out:
1498 	on_each_cpu(_kvm_arch_hardware_disable, NULL, 1);
1499 
1500 	return err;
1501 }
1502 
teardown_hyp_mode(void)1503 static void teardown_hyp_mode(void)
1504 {
1505 	int cpu;
1506 
1507 	free_hyp_pgds();
1508 	for_each_possible_cpu(cpu)
1509 		free_page(per_cpu(kvm_arm_hyp_stack_page, cpu));
1510 	hyp_cpu_pm_exit();
1511 }
1512 
1513 /**
1514  * Inits Hyp-mode on all online CPUs
1515  */
init_hyp_mode(void)1516 static int init_hyp_mode(void)
1517 {
1518 	int cpu;
1519 	int err = 0;
1520 
1521 	/*
1522 	 * Allocate Hyp PGD and setup Hyp identity mapping
1523 	 */
1524 	err = kvm_mmu_init();
1525 	if (err)
1526 		goto out_err;
1527 
1528 	/*
1529 	 * Allocate stack pages for Hypervisor-mode
1530 	 */
1531 	for_each_possible_cpu(cpu) {
1532 		unsigned long stack_page;
1533 
1534 		stack_page = __get_free_page(GFP_KERNEL);
1535 		if (!stack_page) {
1536 			err = -ENOMEM;
1537 			goto out_err;
1538 		}
1539 
1540 		per_cpu(kvm_arm_hyp_stack_page, cpu) = stack_page;
1541 	}
1542 
1543 	/*
1544 	 * Map the Hyp-code called directly from the host
1545 	 */
1546 	err = create_hyp_mappings(kvm_ksym_ref(__hyp_text_start),
1547 				  kvm_ksym_ref(__hyp_text_end), PAGE_HYP_EXEC);
1548 	if (err) {
1549 		kvm_err("Cannot map world-switch code\n");
1550 		goto out_err;
1551 	}
1552 
1553 	err = create_hyp_mappings(kvm_ksym_ref(__start_rodata),
1554 				  kvm_ksym_ref(__end_rodata), PAGE_HYP_RO);
1555 	if (err) {
1556 		kvm_err("Cannot map rodata section\n");
1557 		goto out_err;
1558 	}
1559 
1560 	err = create_hyp_mappings(kvm_ksym_ref(__bss_start),
1561 				  kvm_ksym_ref(__bss_stop), PAGE_HYP_RO);
1562 	if (err) {
1563 		kvm_err("Cannot map bss section\n");
1564 		goto out_err;
1565 	}
1566 
1567 	err = kvm_map_vectors();
1568 	if (err) {
1569 		kvm_err("Cannot map vectors\n");
1570 		goto out_err;
1571 	}
1572 
1573 	/*
1574 	 * Map the Hyp stack pages
1575 	 */
1576 	for_each_possible_cpu(cpu) {
1577 		char *stack_page = (char *)per_cpu(kvm_arm_hyp_stack_page, cpu);
1578 		err = create_hyp_mappings(stack_page, stack_page + PAGE_SIZE,
1579 					  PAGE_HYP);
1580 
1581 		if (err) {
1582 			kvm_err("Cannot map hyp stack\n");
1583 			goto out_err;
1584 		}
1585 	}
1586 
1587 	for_each_possible_cpu(cpu) {
1588 		kvm_cpu_context_t *cpu_ctxt;
1589 
1590 		cpu_ctxt = per_cpu_ptr(&kvm_host_cpu_state, cpu);
1591 		err = create_hyp_mappings(cpu_ctxt, cpu_ctxt + 1, PAGE_HYP);
1592 
1593 		if (err) {
1594 			kvm_err("Cannot map host CPU state: %d\n", err);
1595 			goto out_err;
1596 		}
1597 	}
1598 
1599 	err = hyp_map_aux_data();
1600 	if (err)
1601 		kvm_err("Cannot map host auxilary data: %d\n", err);
1602 
1603 	return 0;
1604 
1605 out_err:
1606 	teardown_hyp_mode();
1607 	kvm_err("error initializing Hyp mode: %d\n", err);
1608 	return err;
1609 }
1610 
check_kvm_target_cpu(void * ret)1611 static void check_kvm_target_cpu(void *ret)
1612 {
1613 	*(int *)ret = kvm_target_cpu();
1614 }
1615 
kvm_mpidr_to_vcpu(struct kvm * kvm,unsigned long mpidr)1616 struct kvm_vcpu *kvm_mpidr_to_vcpu(struct kvm *kvm, unsigned long mpidr)
1617 {
1618 	struct kvm_vcpu *vcpu;
1619 	int i;
1620 
1621 	mpidr &= MPIDR_HWID_BITMASK;
1622 	kvm_for_each_vcpu(i, vcpu, kvm) {
1623 		if (mpidr == kvm_vcpu_get_mpidr_aff(vcpu))
1624 			return vcpu;
1625 	}
1626 	return NULL;
1627 }
1628 
kvm_arch_has_irq_bypass(void)1629 bool kvm_arch_has_irq_bypass(void)
1630 {
1631 	return true;
1632 }
1633 
kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer * cons,struct irq_bypass_producer * prod)1634 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
1635 				      struct irq_bypass_producer *prod)
1636 {
1637 	struct kvm_kernel_irqfd *irqfd =
1638 		container_of(cons, struct kvm_kernel_irqfd, consumer);
1639 
1640 	return kvm_vgic_v4_set_forwarding(irqfd->kvm, prod->irq,
1641 					  &irqfd->irq_entry);
1642 }
kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer * cons,struct irq_bypass_producer * prod)1643 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
1644 				      struct irq_bypass_producer *prod)
1645 {
1646 	struct kvm_kernel_irqfd *irqfd =
1647 		container_of(cons, struct kvm_kernel_irqfd, consumer);
1648 
1649 	kvm_vgic_v4_unset_forwarding(irqfd->kvm, prod->irq,
1650 				     &irqfd->irq_entry);
1651 }
1652 
kvm_arch_irq_bypass_stop(struct irq_bypass_consumer * cons)1653 void kvm_arch_irq_bypass_stop(struct irq_bypass_consumer *cons)
1654 {
1655 	struct kvm_kernel_irqfd *irqfd =
1656 		container_of(cons, struct kvm_kernel_irqfd, consumer);
1657 
1658 	kvm_arm_halt_guest(irqfd->kvm);
1659 }
1660 
kvm_arch_irq_bypass_start(struct irq_bypass_consumer * cons)1661 void kvm_arch_irq_bypass_start(struct irq_bypass_consumer *cons)
1662 {
1663 	struct kvm_kernel_irqfd *irqfd =
1664 		container_of(cons, struct kvm_kernel_irqfd, consumer);
1665 
1666 	kvm_arm_resume_guest(irqfd->kvm);
1667 }
1668 
1669 /**
1670  * Initialize Hyp-mode and memory mappings on all CPUs.
1671  */
kvm_arch_init(void * opaque)1672 int kvm_arch_init(void *opaque)
1673 {
1674 	int err;
1675 	int ret, cpu;
1676 	bool in_hyp_mode;
1677 
1678 	if (!is_hyp_mode_available()) {
1679 		kvm_info("HYP mode not available\n");
1680 		return -ENODEV;
1681 	}
1682 
1683 	if (!kvm_arch_check_sve_has_vhe()) {
1684 		kvm_pr_unimpl("SVE system without VHE unsupported.  Broken cpu?");
1685 		return -ENODEV;
1686 	}
1687 
1688 	for_each_online_cpu(cpu) {
1689 		smp_call_function_single(cpu, check_kvm_target_cpu, &ret, 1);
1690 		if (ret < 0) {
1691 			kvm_err("Error, CPU %d not supported!\n", cpu);
1692 			return -ENODEV;
1693 		}
1694 	}
1695 
1696 	err = init_common_resources();
1697 	if (err)
1698 		return err;
1699 
1700 	in_hyp_mode = is_kernel_in_hyp_mode();
1701 
1702 	if (!in_hyp_mode) {
1703 		err = init_hyp_mode();
1704 		if (err)
1705 			goto out_err;
1706 	}
1707 
1708 	err = init_subsystems();
1709 	if (err)
1710 		goto out_hyp;
1711 
1712 	if (in_hyp_mode)
1713 		kvm_info("VHE mode initialized successfully\n");
1714 	else
1715 		kvm_info("Hyp mode initialized successfully\n");
1716 
1717 	return 0;
1718 
1719 out_hyp:
1720 	if (!in_hyp_mode)
1721 		teardown_hyp_mode();
1722 out_err:
1723 	return err;
1724 }
1725 
1726 /* NOP: Compiling as a module not supported */
kvm_arch_exit(void)1727 void kvm_arch_exit(void)
1728 {
1729 	kvm_perf_teardown();
1730 }
1731 
arm_init(void)1732 static int arm_init(void)
1733 {
1734 	int rc = kvm_init(NULL, sizeof(struct kvm_vcpu), 0, THIS_MODULE);
1735 	return rc;
1736 }
1737 
1738 module_init(arm_init);
1739