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