Merge branch 'libnvdimm-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/nvdim...
[sfrench/cifs-2.6.git] / arch / powerpc / kvm / book3s_hv.c
1 /*
2  * Copyright 2011 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
3  * Copyright (C) 2009. SUSE Linux Products GmbH. All rights reserved.
4  *
5  * Authors:
6  *    Paul Mackerras <paulus@au1.ibm.com>
7  *    Alexander Graf <agraf@suse.de>
8  *    Kevin Wolf <mail@kevin-wolf.de>
9  *
10  * Description: KVM functions specific to running on Book 3S
11  * processors in hypervisor mode (specifically POWER7 and later).
12  *
13  * This file is derived from arch/powerpc/kvm/book3s.c,
14  * by Alexander Graf <agraf@suse.de>.
15  *
16  * This program is free software; you can redistribute it and/or modify
17  * it under the terms of the GNU General Public License, version 2, as
18  * published by the Free Software Foundation.
19  */
20
21 #include <linux/kvm_host.h>
22 #include <linux/err.h>
23 #include <linux/slab.h>
24 #include <linux/preempt.h>
25 #include <linux/sched/signal.h>
26 #include <linux/sched/stat.h>
27 #include <linux/delay.h>
28 #include <linux/export.h>
29 #include <linux/fs.h>
30 #include <linux/anon_inodes.h>
31 #include <linux/cpu.h>
32 #include <linux/cpumask.h>
33 #include <linux/spinlock.h>
34 #include <linux/page-flags.h>
35 #include <linux/srcu.h>
36 #include <linux/miscdevice.h>
37 #include <linux/debugfs.h>
38 #include <linux/gfp.h>
39 #include <linux/vmalloc.h>
40 #include <linux/highmem.h>
41 #include <linux/hugetlb.h>
42 #include <linux/kvm_irqfd.h>
43 #include <linux/irqbypass.h>
44 #include <linux/module.h>
45 #include <linux/compiler.h>
46 #include <linux/of.h>
47
48 #include <asm/reg.h>
49 #include <asm/cputable.h>
50 #include <asm/cacheflush.h>
51 #include <asm/tlbflush.h>
52 #include <linux/uaccess.h>
53 #include <asm/io.h>
54 #include <asm/kvm_ppc.h>
55 #include <asm/kvm_book3s.h>
56 #include <asm/mmu_context.h>
57 #include <asm/lppaca.h>
58 #include <asm/processor.h>
59 #include <asm/cputhreads.h>
60 #include <asm/page.h>
61 #include <asm/hvcall.h>
62 #include <asm/switch_to.h>
63 #include <asm/smp.h>
64 #include <asm/dbell.h>
65 #include <asm/hmi.h>
66 #include <asm/pnv-pci.h>
67 #include <asm/mmu.h>
68 #include <asm/opal.h>
69 #include <asm/xics.h>
70 #include <asm/xive.h>
71
72 #include "book3s.h"
73
74 #define CREATE_TRACE_POINTS
75 #include "trace_hv.h"
76
77 /* #define EXIT_DEBUG */
78 /* #define EXIT_DEBUG_SIMPLE */
79 /* #define EXIT_DEBUG_INT */
80
81 /* Used to indicate that a guest page fault needs to be handled */
82 #define RESUME_PAGE_FAULT       (RESUME_GUEST | RESUME_FLAG_ARCH1)
83 /* Used to indicate that a guest passthrough interrupt needs to be handled */
84 #define RESUME_PASSTHROUGH      (RESUME_GUEST | RESUME_FLAG_ARCH2)
85
86 /* Used as a "null" value for timebase values */
87 #define TB_NIL  (~(u64)0)
88
89 static DECLARE_BITMAP(default_enabled_hcalls, MAX_HCALL_OPCODE/4 + 1);
90
91 static int dynamic_mt_modes = 6;
92 module_param(dynamic_mt_modes, int, S_IRUGO | S_IWUSR);
93 MODULE_PARM_DESC(dynamic_mt_modes, "Set of allowed dynamic micro-threading modes: 0 (= none), 2, 4, or 6 (= 2 or 4)");
94 static int target_smt_mode;
95 module_param(target_smt_mode, int, S_IRUGO | S_IWUSR);
96 MODULE_PARM_DESC(target_smt_mode, "Target threads per core (0 = max)");
97
98 #ifdef CONFIG_KVM_XICS
99 static struct kernel_param_ops module_param_ops = {
100         .set = param_set_int,
101         .get = param_get_int,
102 };
103
104 module_param_cb(kvm_irq_bypass, &module_param_ops, &kvm_irq_bypass,
105                                                         S_IRUGO | S_IWUSR);
106 MODULE_PARM_DESC(kvm_irq_bypass, "Bypass passthrough interrupt optimization");
107
108 module_param_cb(h_ipi_redirect, &module_param_ops, &h_ipi_redirect,
109                                                         S_IRUGO | S_IWUSR);
110 MODULE_PARM_DESC(h_ipi_redirect, "Redirect H_IPI wakeup to a free host core");
111 #endif
112
113 static void kvmppc_end_cede(struct kvm_vcpu *vcpu);
114 static int kvmppc_hv_setup_htab_rma(struct kvm_vcpu *vcpu);
115
116 static inline struct kvm_vcpu *next_runnable_thread(struct kvmppc_vcore *vc,
117                 int *ip)
118 {
119         int i = *ip;
120         struct kvm_vcpu *vcpu;
121
122         while (++i < MAX_SMT_THREADS) {
123                 vcpu = READ_ONCE(vc->runnable_threads[i]);
124                 if (vcpu) {
125                         *ip = i;
126                         return vcpu;
127                 }
128         }
129         return NULL;
130 }
131
132 /* Used to traverse the list of runnable threads for a given vcore */
133 #define for_each_runnable_thread(i, vcpu, vc) \
134         for (i = -1; (vcpu = next_runnable_thread(vc, &i)); )
135
136 static bool kvmppc_ipi_thread(int cpu)
137 {
138         unsigned long msg = PPC_DBELL_TYPE(PPC_DBELL_SERVER);
139
140         /* On POWER9 we can use msgsnd to IPI any cpu */
141         if (cpu_has_feature(CPU_FTR_ARCH_300)) {
142                 msg |= get_hard_smp_processor_id(cpu);
143                 smp_mb();
144                 __asm__ __volatile__ (PPC_MSGSND(%0) : : "r" (msg));
145                 return true;
146         }
147
148         /* On POWER8 for IPIs to threads in the same core, use msgsnd */
149         if (cpu_has_feature(CPU_FTR_ARCH_207S)) {
150                 preempt_disable();
151                 if (cpu_first_thread_sibling(cpu) ==
152                     cpu_first_thread_sibling(smp_processor_id())) {
153                         msg |= cpu_thread_in_core(cpu);
154                         smp_mb();
155                         __asm__ __volatile__ (PPC_MSGSND(%0) : : "r" (msg));
156                         preempt_enable();
157                         return true;
158                 }
159                 preempt_enable();
160         }
161
162 #if defined(CONFIG_PPC_ICP_NATIVE) && defined(CONFIG_SMP)
163         if (cpu >= 0 && cpu < nr_cpu_ids) {
164                 if (paca[cpu].kvm_hstate.xics_phys) {
165                         xics_wake_cpu(cpu);
166                         return true;
167                 }
168                 opal_int_set_mfrr(get_hard_smp_processor_id(cpu), IPI_PRIORITY);
169                 return true;
170         }
171 #endif
172
173         return false;
174 }
175
176 static void kvmppc_fast_vcpu_kick_hv(struct kvm_vcpu *vcpu)
177 {
178         int cpu;
179         struct swait_queue_head *wqp;
180
181         wqp = kvm_arch_vcpu_wq(vcpu);
182         if (swait_active(wqp)) {
183                 swake_up(wqp);
184                 ++vcpu->stat.halt_wakeup;
185         }
186
187         cpu = READ_ONCE(vcpu->arch.thread_cpu);
188         if (cpu >= 0 && kvmppc_ipi_thread(cpu))
189                 return;
190
191         /* CPU points to the first thread of the core */
192         cpu = vcpu->cpu;
193         if (cpu >= 0 && cpu < nr_cpu_ids && cpu_online(cpu))
194                 smp_send_reschedule(cpu);
195 }
196
197 /*
198  * We use the vcpu_load/put functions to measure stolen time.
199  * Stolen time is counted as time when either the vcpu is able to
200  * run as part of a virtual core, but the task running the vcore
201  * is preempted or sleeping, or when the vcpu needs something done
202  * in the kernel by the task running the vcpu, but that task is
203  * preempted or sleeping.  Those two things have to be counted
204  * separately, since one of the vcpu tasks will take on the job
205  * of running the core, and the other vcpu tasks in the vcore will
206  * sleep waiting for it to do that, but that sleep shouldn't count
207  * as stolen time.
208  *
209  * Hence we accumulate stolen time when the vcpu can run as part of
210  * a vcore using vc->stolen_tb, and the stolen time when the vcpu
211  * needs its task to do other things in the kernel (for example,
212  * service a page fault) in busy_stolen.  We don't accumulate
213  * stolen time for a vcore when it is inactive, or for a vcpu
214  * when it is in state RUNNING or NOTREADY.  NOTREADY is a bit of
215  * a misnomer; it means that the vcpu task is not executing in
216  * the KVM_VCPU_RUN ioctl, i.e. it is in userspace or elsewhere in
217  * the kernel.  We don't have any way of dividing up that time
218  * between time that the vcpu is genuinely stopped, time that
219  * the task is actively working on behalf of the vcpu, and time
220  * that the task is preempted, so we don't count any of it as
221  * stolen.
222  *
223  * Updates to busy_stolen are protected by arch.tbacct_lock;
224  * updates to vc->stolen_tb are protected by the vcore->stoltb_lock
225  * lock.  The stolen times are measured in units of timebase ticks.
226  * (Note that the != TB_NIL checks below are purely defensive;
227  * they should never fail.)
228  */
229
230 static void kvmppc_core_start_stolen(struct kvmppc_vcore *vc)
231 {
232         unsigned long flags;
233
234         spin_lock_irqsave(&vc->stoltb_lock, flags);
235         vc->preempt_tb = mftb();
236         spin_unlock_irqrestore(&vc->stoltb_lock, flags);
237 }
238
239 static void kvmppc_core_end_stolen(struct kvmppc_vcore *vc)
240 {
241         unsigned long flags;
242
243         spin_lock_irqsave(&vc->stoltb_lock, flags);
244         if (vc->preempt_tb != TB_NIL) {
245                 vc->stolen_tb += mftb() - vc->preempt_tb;
246                 vc->preempt_tb = TB_NIL;
247         }
248         spin_unlock_irqrestore(&vc->stoltb_lock, flags);
249 }
250
251 static void kvmppc_core_vcpu_load_hv(struct kvm_vcpu *vcpu, int cpu)
252 {
253         struct kvmppc_vcore *vc = vcpu->arch.vcore;
254         unsigned long flags;
255
256         /*
257          * We can test vc->runner without taking the vcore lock,
258          * because only this task ever sets vc->runner to this
259          * vcpu, and once it is set to this vcpu, only this task
260          * ever sets it to NULL.
261          */
262         if (vc->runner == vcpu && vc->vcore_state >= VCORE_SLEEPING)
263                 kvmppc_core_end_stolen(vc);
264
265         spin_lock_irqsave(&vcpu->arch.tbacct_lock, flags);
266         if (vcpu->arch.state == KVMPPC_VCPU_BUSY_IN_HOST &&
267             vcpu->arch.busy_preempt != TB_NIL) {
268                 vcpu->arch.busy_stolen += mftb() - vcpu->arch.busy_preempt;
269                 vcpu->arch.busy_preempt = TB_NIL;
270         }
271         spin_unlock_irqrestore(&vcpu->arch.tbacct_lock, flags);
272 }
273
274 static void kvmppc_core_vcpu_put_hv(struct kvm_vcpu *vcpu)
275 {
276         struct kvmppc_vcore *vc = vcpu->arch.vcore;
277         unsigned long flags;
278
279         if (vc->runner == vcpu && vc->vcore_state >= VCORE_SLEEPING)
280                 kvmppc_core_start_stolen(vc);
281
282         spin_lock_irqsave(&vcpu->arch.tbacct_lock, flags);
283         if (vcpu->arch.state == KVMPPC_VCPU_BUSY_IN_HOST)
284                 vcpu->arch.busy_preempt = mftb();
285         spin_unlock_irqrestore(&vcpu->arch.tbacct_lock, flags);
286 }
287
288 static void kvmppc_set_msr_hv(struct kvm_vcpu *vcpu, u64 msr)
289 {
290         /*
291          * Check for illegal transactional state bit combination
292          * and if we find it, force the TS field to a safe state.
293          */
294         if ((msr & MSR_TS_MASK) == MSR_TS_MASK)
295                 msr &= ~MSR_TS_MASK;
296         vcpu->arch.shregs.msr = msr;
297         kvmppc_end_cede(vcpu);
298 }
299
300 static void kvmppc_set_pvr_hv(struct kvm_vcpu *vcpu, u32 pvr)
301 {
302         vcpu->arch.pvr = pvr;
303 }
304
305 /* Dummy value used in computing PCR value below */
306 #define PCR_ARCH_300    (PCR_ARCH_207 << 1)
307
308 static int kvmppc_set_arch_compat(struct kvm_vcpu *vcpu, u32 arch_compat)
309 {
310         unsigned long host_pcr_bit = 0, guest_pcr_bit = 0;
311         struct kvmppc_vcore *vc = vcpu->arch.vcore;
312
313         /* We can (emulate) our own architecture version and anything older */
314         if (cpu_has_feature(CPU_FTR_ARCH_300))
315                 host_pcr_bit = PCR_ARCH_300;
316         else if (cpu_has_feature(CPU_FTR_ARCH_207S))
317                 host_pcr_bit = PCR_ARCH_207;
318         else if (cpu_has_feature(CPU_FTR_ARCH_206))
319                 host_pcr_bit = PCR_ARCH_206;
320         else
321                 host_pcr_bit = PCR_ARCH_205;
322
323         /* Determine lowest PCR bit needed to run guest in given PVR level */
324         guest_pcr_bit = host_pcr_bit;
325         if (arch_compat) {
326                 switch (arch_compat) {
327                 case PVR_ARCH_205:
328                         guest_pcr_bit = PCR_ARCH_205;
329                         break;
330                 case PVR_ARCH_206:
331                 case PVR_ARCH_206p:
332                         guest_pcr_bit = PCR_ARCH_206;
333                         break;
334                 case PVR_ARCH_207:
335                         guest_pcr_bit = PCR_ARCH_207;
336                         break;
337                 case PVR_ARCH_300:
338                         guest_pcr_bit = PCR_ARCH_300;
339                         break;
340                 default:
341                         return -EINVAL;
342                 }
343         }
344
345         /* Check requested PCR bits don't exceed our capabilities */
346         if (guest_pcr_bit > host_pcr_bit)
347                 return -EINVAL;
348
349         spin_lock(&vc->lock);
350         vc->arch_compat = arch_compat;
351         /* Set all PCR bits for which guest_pcr_bit <= bit < host_pcr_bit */
352         vc->pcr = host_pcr_bit - guest_pcr_bit;
353         spin_unlock(&vc->lock);
354
355         return 0;
356 }
357
358 static void kvmppc_dump_regs(struct kvm_vcpu *vcpu)
359 {
360         int r;
361
362         pr_err("vcpu %p (%d):\n", vcpu, vcpu->vcpu_id);
363         pr_err("pc  = %.16lx  msr = %.16llx  trap = %x\n",
364                vcpu->arch.pc, vcpu->arch.shregs.msr, vcpu->arch.trap);
365         for (r = 0; r < 16; ++r)
366                 pr_err("r%2d = %.16lx  r%d = %.16lx\n",
367                        r, kvmppc_get_gpr(vcpu, r),
368                        r+16, kvmppc_get_gpr(vcpu, r+16));
369         pr_err("ctr = %.16lx  lr  = %.16lx\n",
370                vcpu->arch.ctr, vcpu->arch.lr);
371         pr_err("srr0 = %.16llx srr1 = %.16llx\n",
372                vcpu->arch.shregs.srr0, vcpu->arch.shregs.srr1);
373         pr_err("sprg0 = %.16llx sprg1 = %.16llx\n",
374                vcpu->arch.shregs.sprg0, vcpu->arch.shregs.sprg1);
375         pr_err("sprg2 = %.16llx sprg3 = %.16llx\n",
376                vcpu->arch.shregs.sprg2, vcpu->arch.shregs.sprg3);
377         pr_err("cr = %.8x  xer = %.16lx  dsisr = %.8x\n",
378                vcpu->arch.cr, vcpu->arch.xer, vcpu->arch.shregs.dsisr);
379         pr_err("dar = %.16llx\n", vcpu->arch.shregs.dar);
380         pr_err("fault dar = %.16lx dsisr = %.8x\n",
381                vcpu->arch.fault_dar, vcpu->arch.fault_dsisr);
382         pr_err("SLB (%d entries):\n", vcpu->arch.slb_max);
383         for (r = 0; r < vcpu->arch.slb_max; ++r)
384                 pr_err("  ESID = %.16llx VSID = %.16llx\n",
385                        vcpu->arch.slb[r].orige, vcpu->arch.slb[r].origv);
386         pr_err("lpcr = %.16lx sdr1 = %.16lx last_inst = %.8x\n",
387                vcpu->arch.vcore->lpcr, vcpu->kvm->arch.sdr1,
388                vcpu->arch.last_inst);
389 }
390
391 static struct kvm_vcpu *kvmppc_find_vcpu(struct kvm *kvm, int id)
392 {
393         struct kvm_vcpu *ret;
394
395         mutex_lock(&kvm->lock);
396         ret = kvm_get_vcpu_by_id(kvm, id);
397         mutex_unlock(&kvm->lock);
398         return ret;
399 }
400
401 static void init_vpa(struct kvm_vcpu *vcpu, struct lppaca *vpa)
402 {
403         vpa->__old_status |= LPPACA_OLD_SHARED_PROC;
404         vpa->yield_count = cpu_to_be32(1);
405 }
406
407 static int set_vpa(struct kvm_vcpu *vcpu, struct kvmppc_vpa *v,
408                    unsigned long addr, unsigned long len)
409 {
410         /* check address is cacheline aligned */
411         if (addr & (L1_CACHE_BYTES - 1))
412                 return -EINVAL;
413         spin_lock(&vcpu->arch.vpa_update_lock);
414         if (v->next_gpa != addr || v->len != len) {
415                 v->next_gpa = addr;
416                 v->len = addr ? len : 0;
417                 v->update_pending = 1;
418         }
419         spin_unlock(&vcpu->arch.vpa_update_lock);
420         return 0;
421 }
422
423 /* Length for a per-processor buffer is passed in at offset 4 in the buffer */
424 struct reg_vpa {
425         u32 dummy;
426         union {
427                 __be16 hword;
428                 __be32 word;
429         } length;
430 };
431
432 static int vpa_is_registered(struct kvmppc_vpa *vpap)
433 {
434         if (vpap->update_pending)
435                 return vpap->next_gpa != 0;
436         return vpap->pinned_addr != NULL;
437 }
438
439 static unsigned long do_h_register_vpa(struct kvm_vcpu *vcpu,
440                                        unsigned long flags,
441                                        unsigned long vcpuid, unsigned long vpa)
442 {
443         struct kvm *kvm = vcpu->kvm;
444         unsigned long len, nb;
445         void *va;
446         struct kvm_vcpu *tvcpu;
447         int err;
448         int subfunc;
449         struct kvmppc_vpa *vpap;
450
451         tvcpu = kvmppc_find_vcpu(kvm, vcpuid);
452         if (!tvcpu)
453                 return H_PARAMETER;
454
455         subfunc = (flags >> H_VPA_FUNC_SHIFT) & H_VPA_FUNC_MASK;
456         if (subfunc == H_VPA_REG_VPA || subfunc == H_VPA_REG_DTL ||
457             subfunc == H_VPA_REG_SLB) {
458                 /* Registering new area - address must be cache-line aligned */
459                 if ((vpa & (L1_CACHE_BYTES - 1)) || !vpa)
460                         return H_PARAMETER;
461
462                 /* convert logical addr to kernel addr and read length */
463                 va = kvmppc_pin_guest_page(kvm, vpa, &nb);
464                 if (va == NULL)
465                         return H_PARAMETER;
466                 if (subfunc == H_VPA_REG_VPA)
467                         len = be16_to_cpu(((struct reg_vpa *)va)->length.hword);
468                 else
469                         len = be32_to_cpu(((struct reg_vpa *)va)->length.word);
470                 kvmppc_unpin_guest_page(kvm, va, vpa, false);
471
472                 /* Check length */
473                 if (len > nb || len < sizeof(struct reg_vpa))
474                         return H_PARAMETER;
475         } else {
476                 vpa = 0;
477                 len = 0;
478         }
479
480         err = H_PARAMETER;
481         vpap = NULL;
482         spin_lock(&tvcpu->arch.vpa_update_lock);
483
484         switch (subfunc) {
485         case H_VPA_REG_VPA:             /* register VPA */
486                 if (len < sizeof(struct lppaca))
487                         break;
488                 vpap = &tvcpu->arch.vpa;
489                 err = 0;
490                 break;
491
492         case H_VPA_REG_DTL:             /* register DTL */
493                 if (len < sizeof(struct dtl_entry))
494                         break;
495                 len -= len % sizeof(struct dtl_entry);
496
497                 /* Check that they have previously registered a VPA */
498                 err = H_RESOURCE;
499                 if (!vpa_is_registered(&tvcpu->arch.vpa))
500                         break;
501
502                 vpap = &tvcpu->arch.dtl;
503                 err = 0;
504                 break;
505
506         case H_VPA_REG_SLB:             /* register SLB shadow buffer */
507                 /* Check that they have previously registered a VPA */
508                 err = H_RESOURCE;
509                 if (!vpa_is_registered(&tvcpu->arch.vpa))
510                         break;
511
512                 vpap = &tvcpu->arch.slb_shadow;
513                 err = 0;
514                 break;
515
516         case H_VPA_DEREG_VPA:           /* deregister VPA */
517                 /* Check they don't still have a DTL or SLB buf registered */
518                 err = H_RESOURCE;
519                 if (vpa_is_registered(&tvcpu->arch.dtl) ||
520                     vpa_is_registered(&tvcpu->arch.slb_shadow))
521                         break;
522
523                 vpap = &tvcpu->arch.vpa;
524                 err = 0;
525                 break;
526
527         case H_VPA_DEREG_DTL:           /* deregister DTL */
528                 vpap = &tvcpu->arch.dtl;
529                 err = 0;
530                 break;
531
532         case H_VPA_DEREG_SLB:           /* deregister SLB shadow buffer */
533                 vpap = &tvcpu->arch.slb_shadow;
534                 err = 0;
535                 break;
536         }
537
538         if (vpap) {
539                 vpap->next_gpa = vpa;
540                 vpap->len = len;
541                 vpap->update_pending = 1;
542         }
543
544         spin_unlock(&tvcpu->arch.vpa_update_lock);
545
546         return err;
547 }
548
549 static void kvmppc_update_vpa(struct kvm_vcpu *vcpu, struct kvmppc_vpa *vpap)
550 {
551         struct kvm *kvm = vcpu->kvm;
552         void *va;
553         unsigned long nb;
554         unsigned long gpa;
555
556         /*
557          * We need to pin the page pointed to by vpap->next_gpa,
558          * but we can't call kvmppc_pin_guest_page under the lock
559          * as it does get_user_pages() and down_read().  So we
560          * have to drop the lock, pin the page, then get the lock
561          * again and check that a new area didn't get registered
562          * in the meantime.
563          */
564         for (;;) {
565                 gpa = vpap->next_gpa;
566                 spin_unlock(&vcpu->arch.vpa_update_lock);
567                 va = NULL;
568                 nb = 0;
569                 if (gpa)
570                         va = kvmppc_pin_guest_page(kvm, gpa, &nb);
571                 spin_lock(&vcpu->arch.vpa_update_lock);
572                 if (gpa == vpap->next_gpa)
573                         break;
574                 /* sigh... unpin that one and try again */
575                 if (va)
576                         kvmppc_unpin_guest_page(kvm, va, gpa, false);
577         }
578
579         vpap->update_pending = 0;
580         if (va && nb < vpap->len) {
581                 /*
582                  * If it's now too short, it must be that userspace
583                  * has changed the mappings underlying guest memory,
584                  * so unregister the region.
585                  */
586                 kvmppc_unpin_guest_page(kvm, va, gpa, false);
587                 va = NULL;
588         }
589         if (vpap->pinned_addr)
590                 kvmppc_unpin_guest_page(kvm, vpap->pinned_addr, vpap->gpa,
591                                         vpap->dirty);
592         vpap->gpa = gpa;
593         vpap->pinned_addr = va;
594         vpap->dirty = false;
595         if (va)
596                 vpap->pinned_end = va + vpap->len;
597 }
598
599 static void kvmppc_update_vpas(struct kvm_vcpu *vcpu)
600 {
601         if (!(vcpu->arch.vpa.update_pending ||
602               vcpu->arch.slb_shadow.update_pending ||
603               vcpu->arch.dtl.update_pending))
604                 return;
605
606         spin_lock(&vcpu->arch.vpa_update_lock);
607         if (vcpu->arch.vpa.update_pending) {
608                 kvmppc_update_vpa(vcpu, &vcpu->arch.vpa);
609                 if (vcpu->arch.vpa.pinned_addr)
610                         init_vpa(vcpu, vcpu->arch.vpa.pinned_addr);
611         }
612         if (vcpu->arch.dtl.update_pending) {
613                 kvmppc_update_vpa(vcpu, &vcpu->arch.dtl);
614                 vcpu->arch.dtl_ptr = vcpu->arch.dtl.pinned_addr;
615                 vcpu->arch.dtl_index = 0;
616         }
617         if (vcpu->arch.slb_shadow.update_pending)
618                 kvmppc_update_vpa(vcpu, &vcpu->arch.slb_shadow);
619         spin_unlock(&vcpu->arch.vpa_update_lock);
620 }
621
622 /*
623  * Return the accumulated stolen time for the vcore up until `now'.
624  * The caller should hold the vcore lock.
625  */
626 static u64 vcore_stolen_time(struct kvmppc_vcore *vc, u64 now)
627 {
628         u64 p;
629         unsigned long flags;
630
631         spin_lock_irqsave(&vc->stoltb_lock, flags);
632         p = vc->stolen_tb;
633         if (vc->vcore_state != VCORE_INACTIVE &&
634             vc->preempt_tb != TB_NIL)
635                 p += now - vc->preempt_tb;
636         spin_unlock_irqrestore(&vc->stoltb_lock, flags);
637         return p;
638 }
639
640 static void kvmppc_create_dtl_entry(struct kvm_vcpu *vcpu,
641                                     struct kvmppc_vcore *vc)
642 {
643         struct dtl_entry *dt;
644         struct lppaca *vpa;
645         unsigned long stolen;
646         unsigned long core_stolen;
647         u64 now;
648
649         dt = vcpu->arch.dtl_ptr;
650         vpa = vcpu->arch.vpa.pinned_addr;
651         now = mftb();
652         core_stolen = vcore_stolen_time(vc, now);
653         stolen = core_stolen - vcpu->arch.stolen_logged;
654         vcpu->arch.stolen_logged = core_stolen;
655         spin_lock_irq(&vcpu->arch.tbacct_lock);
656         stolen += vcpu->arch.busy_stolen;
657         vcpu->arch.busy_stolen = 0;
658         spin_unlock_irq(&vcpu->arch.tbacct_lock);
659         if (!dt || !vpa)
660                 return;
661         memset(dt, 0, sizeof(struct dtl_entry));
662         dt->dispatch_reason = 7;
663         dt->processor_id = cpu_to_be16(vc->pcpu + vcpu->arch.ptid);
664         dt->timebase = cpu_to_be64(now + vc->tb_offset);
665         dt->enqueue_to_dispatch_time = cpu_to_be32(stolen);
666         dt->srr0 = cpu_to_be64(kvmppc_get_pc(vcpu));
667         dt->srr1 = cpu_to_be64(vcpu->arch.shregs.msr);
668         ++dt;
669         if (dt == vcpu->arch.dtl.pinned_end)
670                 dt = vcpu->arch.dtl.pinned_addr;
671         vcpu->arch.dtl_ptr = dt;
672         /* order writing *dt vs. writing vpa->dtl_idx */
673         smp_wmb();
674         vpa->dtl_idx = cpu_to_be64(++vcpu->arch.dtl_index);
675         vcpu->arch.dtl.dirty = true;
676 }
677
678 static bool kvmppc_power8_compatible(struct kvm_vcpu *vcpu)
679 {
680         if (vcpu->arch.vcore->arch_compat >= PVR_ARCH_207)
681                 return true;
682         if ((!vcpu->arch.vcore->arch_compat) &&
683             cpu_has_feature(CPU_FTR_ARCH_207S))
684                 return true;
685         return false;
686 }
687
688 static int kvmppc_h_set_mode(struct kvm_vcpu *vcpu, unsigned long mflags,
689                              unsigned long resource, unsigned long value1,
690                              unsigned long value2)
691 {
692         switch (resource) {
693         case H_SET_MODE_RESOURCE_SET_CIABR:
694                 if (!kvmppc_power8_compatible(vcpu))
695                         return H_P2;
696                 if (value2)
697                         return H_P4;
698                 if (mflags)
699                         return H_UNSUPPORTED_FLAG_START;
700                 /* Guests can't breakpoint the hypervisor */
701                 if ((value1 & CIABR_PRIV) == CIABR_PRIV_HYPER)
702                         return H_P3;
703                 vcpu->arch.ciabr  = value1;
704                 return H_SUCCESS;
705         case H_SET_MODE_RESOURCE_SET_DAWR:
706                 if (!kvmppc_power8_compatible(vcpu))
707                         return H_P2;
708                 if (mflags)
709                         return H_UNSUPPORTED_FLAG_START;
710                 if (value2 & DABRX_HYP)
711                         return H_P4;
712                 vcpu->arch.dawr  = value1;
713                 vcpu->arch.dawrx = value2;
714                 return H_SUCCESS;
715         default:
716                 return H_TOO_HARD;
717         }
718 }
719
720 static int kvm_arch_vcpu_yield_to(struct kvm_vcpu *target)
721 {
722         struct kvmppc_vcore *vcore = target->arch.vcore;
723
724         /*
725          * We expect to have been called by the real mode handler
726          * (kvmppc_rm_h_confer()) which would have directly returned
727          * H_SUCCESS if the source vcore wasn't idle (e.g. if it may
728          * have useful work to do and should not confer) so we don't
729          * recheck that here.
730          */
731
732         spin_lock(&vcore->lock);
733         if (target->arch.state == KVMPPC_VCPU_RUNNABLE &&
734             vcore->vcore_state != VCORE_INACTIVE &&
735             vcore->runner)
736                 target = vcore->runner;
737         spin_unlock(&vcore->lock);
738
739         return kvm_vcpu_yield_to(target);
740 }
741
742 static int kvmppc_get_yield_count(struct kvm_vcpu *vcpu)
743 {
744         int yield_count = 0;
745         struct lppaca *lppaca;
746
747         spin_lock(&vcpu->arch.vpa_update_lock);
748         lppaca = (struct lppaca *)vcpu->arch.vpa.pinned_addr;
749         if (lppaca)
750                 yield_count = be32_to_cpu(lppaca->yield_count);
751         spin_unlock(&vcpu->arch.vpa_update_lock);
752         return yield_count;
753 }
754
755 int kvmppc_pseries_do_hcall(struct kvm_vcpu *vcpu)
756 {
757         unsigned long req = kvmppc_get_gpr(vcpu, 3);
758         unsigned long target, ret = H_SUCCESS;
759         int yield_count;
760         struct kvm_vcpu *tvcpu;
761         int idx, rc;
762
763         if (req <= MAX_HCALL_OPCODE &&
764             !test_bit(req/4, vcpu->kvm->arch.enabled_hcalls))
765                 return RESUME_HOST;
766
767         switch (req) {
768         case H_CEDE:
769                 break;
770         case H_PROD:
771                 target = kvmppc_get_gpr(vcpu, 4);
772                 tvcpu = kvmppc_find_vcpu(vcpu->kvm, target);
773                 if (!tvcpu) {
774                         ret = H_PARAMETER;
775                         break;
776                 }
777                 tvcpu->arch.prodded = 1;
778                 smp_mb();
779                 if (tvcpu->arch.ceded)
780                         kvmppc_fast_vcpu_kick_hv(tvcpu);
781                 break;
782         case H_CONFER:
783                 target = kvmppc_get_gpr(vcpu, 4);
784                 if (target == -1)
785                         break;
786                 tvcpu = kvmppc_find_vcpu(vcpu->kvm, target);
787                 if (!tvcpu) {
788                         ret = H_PARAMETER;
789                         break;
790                 }
791                 yield_count = kvmppc_get_gpr(vcpu, 5);
792                 if (kvmppc_get_yield_count(tvcpu) != yield_count)
793                         break;
794                 kvm_arch_vcpu_yield_to(tvcpu);
795                 break;
796         case H_REGISTER_VPA:
797                 ret = do_h_register_vpa(vcpu, kvmppc_get_gpr(vcpu, 4),
798                                         kvmppc_get_gpr(vcpu, 5),
799                                         kvmppc_get_gpr(vcpu, 6));
800                 break;
801         case H_RTAS:
802                 if (list_empty(&vcpu->kvm->arch.rtas_tokens))
803                         return RESUME_HOST;
804
805                 idx = srcu_read_lock(&vcpu->kvm->srcu);
806                 rc = kvmppc_rtas_hcall(vcpu);
807                 srcu_read_unlock(&vcpu->kvm->srcu, idx);
808
809                 if (rc == -ENOENT)
810                         return RESUME_HOST;
811                 else if (rc == 0)
812                         break;
813
814                 /* Send the error out to userspace via KVM_RUN */
815                 return rc;
816         case H_LOGICAL_CI_LOAD:
817                 ret = kvmppc_h_logical_ci_load(vcpu);
818                 if (ret == H_TOO_HARD)
819                         return RESUME_HOST;
820                 break;
821         case H_LOGICAL_CI_STORE:
822                 ret = kvmppc_h_logical_ci_store(vcpu);
823                 if (ret == H_TOO_HARD)
824                         return RESUME_HOST;
825                 break;
826         case H_SET_MODE:
827                 ret = kvmppc_h_set_mode(vcpu, kvmppc_get_gpr(vcpu, 4),
828                                         kvmppc_get_gpr(vcpu, 5),
829                                         kvmppc_get_gpr(vcpu, 6),
830                                         kvmppc_get_gpr(vcpu, 7));
831                 if (ret == H_TOO_HARD)
832                         return RESUME_HOST;
833                 break;
834         case H_XIRR:
835         case H_CPPR:
836         case H_EOI:
837         case H_IPI:
838         case H_IPOLL:
839         case H_XIRR_X:
840                 if (kvmppc_xics_enabled(vcpu)) {
841                         if (xive_enabled()) {
842                                 ret = H_NOT_AVAILABLE;
843                                 return RESUME_GUEST;
844                         }
845                         ret = kvmppc_xics_hcall(vcpu, req);
846                         break;
847                 }
848                 return RESUME_HOST;
849         case H_PUT_TCE:
850                 ret = kvmppc_h_put_tce(vcpu, kvmppc_get_gpr(vcpu, 4),
851                                                 kvmppc_get_gpr(vcpu, 5),
852                                                 kvmppc_get_gpr(vcpu, 6));
853                 if (ret == H_TOO_HARD)
854                         return RESUME_HOST;
855                 break;
856         case H_PUT_TCE_INDIRECT:
857                 ret = kvmppc_h_put_tce_indirect(vcpu, kvmppc_get_gpr(vcpu, 4),
858                                                 kvmppc_get_gpr(vcpu, 5),
859                                                 kvmppc_get_gpr(vcpu, 6),
860                                                 kvmppc_get_gpr(vcpu, 7));
861                 if (ret == H_TOO_HARD)
862                         return RESUME_HOST;
863                 break;
864         case H_STUFF_TCE:
865                 ret = kvmppc_h_stuff_tce(vcpu, kvmppc_get_gpr(vcpu, 4),
866                                                 kvmppc_get_gpr(vcpu, 5),
867                                                 kvmppc_get_gpr(vcpu, 6),
868                                                 kvmppc_get_gpr(vcpu, 7));
869                 if (ret == H_TOO_HARD)
870                         return RESUME_HOST;
871                 break;
872         default:
873                 return RESUME_HOST;
874         }
875         kvmppc_set_gpr(vcpu, 3, ret);
876         vcpu->arch.hcall_needed = 0;
877         return RESUME_GUEST;
878 }
879
880 static int kvmppc_hcall_impl_hv(unsigned long cmd)
881 {
882         switch (cmd) {
883         case H_CEDE:
884         case H_PROD:
885         case H_CONFER:
886         case H_REGISTER_VPA:
887         case H_SET_MODE:
888         case H_LOGICAL_CI_LOAD:
889         case H_LOGICAL_CI_STORE:
890 #ifdef CONFIG_KVM_XICS
891         case H_XIRR:
892         case H_CPPR:
893         case H_EOI:
894         case H_IPI:
895         case H_IPOLL:
896         case H_XIRR_X:
897 #endif
898                 return 1;
899         }
900
901         /* See if it's in the real-mode table */
902         return kvmppc_hcall_impl_hv_realmode(cmd);
903 }
904
905 static int kvmppc_emulate_debug_inst(struct kvm_run *run,
906                                         struct kvm_vcpu *vcpu)
907 {
908         u32 last_inst;
909
910         if (kvmppc_get_last_inst(vcpu, INST_GENERIC, &last_inst) !=
911                                         EMULATE_DONE) {
912                 /*
913                  * Fetch failed, so return to guest and
914                  * try executing it again.
915                  */
916                 return RESUME_GUEST;
917         }
918
919         if (last_inst == KVMPPC_INST_SW_BREAKPOINT) {
920                 run->exit_reason = KVM_EXIT_DEBUG;
921                 run->debug.arch.address = kvmppc_get_pc(vcpu);
922                 return RESUME_HOST;
923         } else {
924                 kvmppc_core_queue_program(vcpu, SRR1_PROGILL);
925                 return RESUME_GUEST;
926         }
927 }
928
929 static int kvmppc_handle_exit_hv(struct kvm_run *run, struct kvm_vcpu *vcpu,
930                                  struct task_struct *tsk)
931 {
932         int r = RESUME_HOST;
933
934         vcpu->stat.sum_exits++;
935
936         /*
937          * This can happen if an interrupt occurs in the last stages
938          * of guest entry or the first stages of guest exit (i.e. after
939          * setting paca->kvm_hstate.in_guest to KVM_GUEST_MODE_GUEST_HV
940          * and before setting it to KVM_GUEST_MODE_HOST_HV).
941          * That can happen due to a bug, or due to a machine check
942          * occurring at just the wrong time.
943          */
944         if (vcpu->arch.shregs.msr & MSR_HV) {
945                 printk(KERN_EMERG "KVM trap in HV mode!\n");
946                 printk(KERN_EMERG "trap=0x%x | pc=0x%lx | msr=0x%llx\n",
947                         vcpu->arch.trap, kvmppc_get_pc(vcpu),
948                         vcpu->arch.shregs.msr);
949                 kvmppc_dump_regs(vcpu);
950                 run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
951                 run->hw.hardware_exit_reason = vcpu->arch.trap;
952                 return RESUME_HOST;
953         }
954         run->exit_reason = KVM_EXIT_UNKNOWN;
955         run->ready_for_interrupt_injection = 1;
956         switch (vcpu->arch.trap) {
957         /* We're good on these - the host merely wanted to get our attention */
958         case BOOK3S_INTERRUPT_HV_DECREMENTER:
959                 vcpu->stat.dec_exits++;
960                 r = RESUME_GUEST;
961                 break;
962         case BOOK3S_INTERRUPT_EXTERNAL:
963         case BOOK3S_INTERRUPT_H_DOORBELL:
964         case BOOK3S_INTERRUPT_H_VIRT:
965                 vcpu->stat.ext_intr_exits++;
966                 r = RESUME_GUEST;
967                 break;
968         /* HMI is hypervisor interrupt and host has handled it. Resume guest.*/
969         case BOOK3S_INTERRUPT_HMI:
970         case BOOK3S_INTERRUPT_PERFMON:
971                 r = RESUME_GUEST;
972                 break;
973         case BOOK3S_INTERRUPT_MACHINE_CHECK:
974                 /*
975                  * Deliver a machine check interrupt to the guest.
976                  * We have to do this, even if the host has handled the
977                  * machine check, because machine checks use SRR0/1 and
978                  * the interrupt might have trashed guest state in them.
979                  */
980                 kvmppc_book3s_queue_irqprio(vcpu,
981                                             BOOK3S_INTERRUPT_MACHINE_CHECK);
982                 r = RESUME_GUEST;
983                 break;
984         case BOOK3S_INTERRUPT_PROGRAM:
985         {
986                 ulong flags;
987                 /*
988                  * Normally program interrupts are delivered directly
989                  * to the guest by the hardware, but we can get here
990                  * as a result of a hypervisor emulation interrupt
991                  * (e40) getting turned into a 700 by BML RTAS.
992                  */
993                 flags = vcpu->arch.shregs.msr & 0x1f0000ull;
994                 kvmppc_core_queue_program(vcpu, flags);
995                 r = RESUME_GUEST;
996                 break;
997         }
998         case BOOK3S_INTERRUPT_SYSCALL:
999         {
1000                 /* hcall - punt to userspace */
1001                 int i;
1002
1003                 /* hypercall with MSR_PR has already been handled in rmode,
1004                  * and never reaches here.
1005                  */
1006
1007                 run->papr_hcall.nr = kvmppc_get_gpr(vcpu, 3);
1008                 for (i = 0; i < 9; ++i)
1009                         run->papr_hcall.args[i] = kvmppc_get_gpr(vcpu, 4 + i);
1010                 run->exit_reason = KVM_EXIT_PAPR_HCALL;
1011                 vcpu->arch.hcall_needed = 1;
1012                 r = RESUME_HOST;
1013                 break;
1014         }
1015         /*
1016          * We get these next two if the guest accesses a page which it thinks
1017          * it has mapped but which is not actually present, either because
1018          * it is for an emulated I/O device or because the corresonding
1019          * host page has been paged out.  Any other HDSI/HISI interrupts
1020          * have been handled already.
1021          */
1022         case BOOK3S_INTERRUPT_H_DATA_STORAGE:
1023                 r = RESUME_PAGE_FAULT;
1024                 break;
1025         case BOOK3S_INTERRUPT_H_INST_STORAGE:
1026                 vcpu->arch.fault_dar = kvmppc_get_pc(vcpu);
1027                 vcpu->arch.fault_dsisr = 0;
1028                 r = RESUME_PAGE_FAULT;
1029                 break;
1030         /*
1031          * This occurs if the guest executes an illegal instruction.
1032          * If the guest debug is disabled, generate a program interrupt
1033          * to the guest. If guest debug is enabled, we need to check
1034          * whether the instruction is a software breakpoint instruction.
1035          * Accordingly return to Guest or Host.
1036          */
1037         case BOOK3S_INTERRUPT_H_EMUL_ASSIST:
1038                 if (vcpu->arch.emul_inst != KVM_INST_FETCH_FAILED)
1039                         vcpu->arch.last_inst = kvmppc_need_byteswap(vcpu) ?
1040                                 swab32(vcpu->arch.emul_inst) :
1041                                 vcpu->arch.emul_inst;
1042                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP) {
1043                         r = kvmppc_emulate_debug_inst(run, vcpu);
1044                 } else {
1045                         kvmppc_core_queue_program(vcpu, SRR1_PROGILL);
1046                         r = RESUME_GUEST;
1047                 }
1048                 break;
1049         /*
1050          * This occurs if the guest (kernel or userspace), does something that
1051          * is prohibited by HFSCR.  We just generate a program interrupt to
1052          * the guest.
1053          */
1054         case BOOK3S_INTERRUPT_H_FAC_UNAVAIL:
1055                 kvmppc_core_queue_program(vcpu, SRR1_PROGILL);
1056                 r = RESUME_GUEST;
1057                 break;
1058         case BOOK3S_INTERRUPT_HV_RM_HARD:
1059                 r = RESUME_PASSTHROUGH;
1060                 break;
1061         default:
1062                 kvmppc_dump_regs(vcpu);
1063                 printk(KERN_EMERG "trap=0x%x | pc=0x%lx | msr=0x%llx\n",
1064                         vcpu->arch.trap, kvmppc_get_pc(vcpu),
1065                         vcpu->arch.shregs.msr);
1066                 run->hw.hardware_exit_reason = vcpu->arch.trap;
1067                 r = RESUME_HOST;
1068                 break;
1069         }
1070
1071         return r;
1072 }
1073
1074 static int kvm_arch_vcpu_ioctl_get_sregs_hv(struct kvm_vcpu *vcpu,
1075                                             struct kvm_sregs *sregs)
1076 {
1077         int i;
1078
1079         memset(sregs, 0, sizeof(struct kvm_sregs));
1080         sregs->pvr = vcpu->arch.pvr;
1081         for (i = 0; i < vcpu->arch.slb_max; i++) {
1082                 sregs->u.s.ppc64.slb[i].slbe = vcpu->arch.slb[i].orige;
1083                 sregs->u.s.ppc64.slb[i].slbv = vcpu->arch.slb[i].origv;
1084         }
1085
1086         return 0;
1087 }
1088
1089 static int kvm_arch_vcpu_ioctl_set_sregs_hv(struct kvm_vcpu *vcpu,
1090                                             struct kvm_sregs *sregs)
1091 {
1092         int i, j;
1093
1094         /* Only accept the same PVR as the host's, since we can't spoof it */
1095         if (sregs->pvr != vcpu->arch.pvr)
1096                 return -EINVAL;
1097
1098         j = 0;
1099         for (i = 0; i < vcpu->arch.slb_nr; i++) {
1100                 if (sregs->u.s.ppc64.slb[i].slbe & SLB_ESID_V) {
1101                         vcpu->arch.slb[j].orige = sregs->u.s.ppc64.slb[i].slbe;
1102                         vcpu->arch.slb[j].origv = sregs->u.s.ppc64.slb[i].slbv;
1103                         ++j;
1104                 }
1105         }
1106         vcpu->arch.slb_max = j;
1107
1108         return 0;
1109 }
1110
1111 static void kvmppc_set_lpcr(struct kvm_vcpu *vcpu, u64 new_lpcr,
1112                 bool preserve_top32)
1113 {
1114         struct kvm *kvm = vcpu->kvm;
1115         struct kvmppc_vcore *vc = vcpu->arch.vcore;
1116         u64 mask;
1117
1118         mutex_lock(&kvm->lock);
1119         spin_lock(&vc->lock);
1120         /*
1121          * If ILE (interrupt little-endian) has changed, update the
1122          * MSR_LE bit in the intr_msr for each vcpu in this vcore.
1123          */
1124         if ((new_lpcr & LPCR_ILE) != (vc->lpcr & LPCR_ILE)) {
1125                 struct kvm_vcpu *vcpu;
1126                 int i;
1127
1128                 kvm_for_each_vcpu(i, vcpu, kvm) {
1129                         if (vcpu->arch.vcore != vc)
1130                                 continue;
1131                         if (new_lpcr & LPCR_ILE)
1132                                 vcpu->arch.intr_msr |= MSR_LE;
1133                         else
1134                                 vcpu->arch.intr_msr &= ~MSR_LE;
1135                 }
1136         }
1137
1138         /*
1139          * Userspace can only modify DPFD (default prefetch depth),
1140          * ILE (interrupt little-endian) and TC (translation control).
1141          * On POWER8 and POWER9 userspace can also modify AIL (alt. interrupt loc.).
1142          */
1143         mask = LPCR_DPFD | LPCR_ILE | LPCR_TC;
1144         if (cpu_has_feature(CPU_FTR_ARCH_207S))
1145                 mask |= LPCR_AIL;
1146
1147         /* Broken 32-bit version of LPCR must not clear top bits */
1148         if (preserve_top32)
1149                 mask &= 0xFFFFFFFF;
1150         vc->lpcr = (vc->lpcr & ~mask) | (new_lpcr & mask);
1151         spin_unlock(&vc->lock);
1152         mutex_unlock(&kvm->lock);
1153 }
1154
1155 static int kvmppc_get_one_reg_hv(struct kvm_vcpu *vcpu, u64 id,
1156                                  union kvmppc_one_reg *val)
1157 {
1158         int r = 0;
1159         long int i;
1160
1161         switch (id) {
1162         case KVM_REG_PPC_DEBUG_INST:
1163                 *val = get_reg_val(id, KVMPPC_INST_SW_BREAKPOINT);
1164                 break;
1165         case KVM_REG_PPC_HIOR:
1166                 *val = get_reg_val(id, 0);
1167                 break;
1168         case KVM_REG_PPC_DABR:
1169                 *val = get_reg_val(id, vcpu->arch.dabr);
1170                 break;
1171         case KVM_REG_PPC_DABRX:
1172                 *val = get_reg_val(id, vcpu->arch.dabrx);
1173                 break;
1174         case KVM_REG_PPC_DSCR:
1175                 *val = get_reg_val(id, vcpu->arch.dscr);
1176                 break;
1177         case KVM_REG_PPC_PURR:
1178                 *val = get_reg_val(id, vcpu->arch.purr);
1179                 break;
1180         case KVM_REG_PPC_SPURR:
1181                 *val = get_reg_val(id, vcpu->arch.spurr);
1182                 break;
1183         case KVM_REG_PPC_AMR:
1184                 *val = get_reg_val(id, vcpu->arch.amr);
1185                 break;
1186         case KVM_REG_PPC_UAMOR:
1187                 *val = get_reg_val(id, vcpu->arch.uamor);
1188                 break;
1189         case KVM_REG_PPC_MMCR0 ... KVM_REG_PPC_MMCRS:
1190                 i = id - KVM_REG_PPC_MMCR0;
1191                 *val = get_reg_val(id, vcpu->arch.mmcr[i]);
1192                 break;
1193         case KVM_REG_PPC_PMC1 ... KVM_REG_PPC_PMC8:
1194                 i = id - KVM_REG_PPC_PMC1;
1195                 *val = get_reg_val(id, vcpu->arch.pmc[i]);
1196                 break;
1197         case KVM_REG_PPC_SPMC1 ... KVM_REG_PPC_SPMC2:
1198                 i = id - KVM_REG_PPC_SPMC1;
1199                 *val = get_reg_val(id, vcpu->arch.spmc[i]);
1200                 break;
1201         case KVM_REG_PPC_SIAR:
1202                 *val = get_reg_val(id, vcpu->arch.siar);
1203                 break;
1204         case KVM_REG_PPC_SDAR:
1205                 *val = get_reg_val(id, vcpu->arch.sdar);
1206                 break;
1207         case KVM_REG_PPC_SIER:
1208                 *val = get_reg_val(id, vcpu->arch.sier);
1209                 break;
1210         case KVM_REG_PPC_IAMR:
1211                 *val = get_reg_val(id, vcpu->arch.iamr);
1212                 break;
1213         case KVM_REG_PPC_PSPB:
1214                 *val = get_reg_val(id, vcpu->arch.pspb);
1215                 break;
1216         case KVM_REG_PPC_DPDES:
1217                 *val = get_reg_val(id, vcpu->arch.vcore->dpdes);
1218                 break;
1219         case KVM_REG_PPC_VTB:
1220                 *val = get_reg_val(id, vcpu->arch.vcore->vtb);
1221                 break;
1222         case KVM_REG_PPC_DAWR:
1223                 *val = get_reg_val(id, vcpu->arch.dawr);
1224                 break;
1225         case KVM_REG_PPC_DAWRX:
1226                 *val = get_reg_val(id, vcpu->arch.dawrx);
1227                 break;
1228         case KVM_REG_PPC_CIABR:
1229                 *val = get_reg_val(id, vcpu->arch.ciabr);
1230                 break;
1231         case KVM_REG_PPC_CSIGR:
1232                 *val = get_reg_val(id, vcpu->arch.csigr);
1233                 break;
1234         case KVM_REG_PPC_TACR:
1235                 *val = get_reg_val(id, vcpu->arch.tacr);
1236                 break;
1237         case KVM_REG_PPC_TCSCR:
1238                 *val = get_reg_val(id, vcpu->arch.tcscr);
1239                 break;
1240         case KVM_REG_PPC_PID:
1241                 *val = get_reg_val(id, vcpu->arch.pid);
1242                 break;
1243         case KVM_REG_PPC_ACOP:
1244                 *val = get_reg_val(id, vcpu->arch.acop);
1245                 break;
1246         case KVM_REG_PPC_WORT:
1247                 *val = get_reg_val(id, vcpu->arch.wort);
1248                 break;
1249         case KVM_REG_PPC_TIDR:
1250                 *val = get_reg_val(id, vcpu->arch.tid);
1251                 break;
1252         case KVM_REG_PPC_PSSCR:
1253                 *val = get_reg_val(id, vcpu->arch.psscr);
1254                 break;
1255         case KVM_REG_PPC_VPA_ADDR:
1256                 spin_lock(&vcpu->arch.vpa_update_lock);
1257                 *val = get_reg_val(id, vcpu->arch.vpa.next_gpa);
1258                 spin_unlock(&vcpu->arch.vpa_update_lock);
1259                 break;
1260         case KVM_REG_PPC_VPA_SLB:
1261                 spin_lock(&vcpu->arch.vpa_update_lock);
1262                 val->vpaval.addr = vcpu->arch.slb_shadow.next_gpa;
1263                 val->vpaval.length = vcpu->arch.slb_shadow.len;
1264                 spin_unlock(&vcpu->arch.vpa_update_lock);
1265                 break;
1266         case KVM_REG_PPC_VPA_DTL:
1267                 spin_lock(&vcpu->arch.vpa_update_lock);
1268                 val->vpaval.addr = vcpu->arch.dtl.next_gpa;
1269                 val->vpaval.length = vcpu->arch.dtl.len;
1270                 spin_unlock(&vcpu->arch.vpa_update_lock);
1271                 break;
1272         case KVM_REG_PPC_TB_OFFSET:
1273                 *val = get_reg_val(id, vcpu->arch.vcore->tb_offset);
1274                 break;
1275         case KVM_REG_PPC_LPCR:
1276         case KVM_REG_PPC_LPCR_64:
1277                 *val = get_reg_val(id, vcpu->arch.vcore->lpcr);
1278                 break;
1279         case KVM_REG_PPC_PPR:
1280                 *val = get_reg_val(id, vcpu->arch.ppr);
1281                 break;
1282 #ifdef CONFIG_PPC_TRANSACTIONAL_MEM
1283         case KVM_REG_PPC_TFHAR:
1284                 *val = get_reg_val(id, vcpu->arch.tfhar);
1285                 break;
1286         case KVM_REG_PPC_TFIAR:
1287                 *val = get_reg_val(id, vcpu->arch.tfiar);
1288                 break;
1289         case KVM_REG_PPC_TEXASR:
1290                 *val = get_reg_val(id, vcpu->arch.texasr);
1291                 break;
1292         case KVM_REG_PPC_TM_GPR0 ... KVM_REG_PPC_TM_GPR31:
1293                 i = id - KVM_REG_PPC_TM_GPR0;
1294                 *val = get_reg_val(id, vcpu->arch.gpr_tm[i]);
1295                 break;
1296         case KVM_REG_PPC_TM_VSR0 ... KVM_REG_PPC_TM_VSR63:
1297         {
1298                 int j;
1299                 i = id - KVM_REG_PPC_TM_VSR0;
1300                 if (i < 32)
1301                         for (j = 0; j < TS_FPRWIDTH; j++)
1302                                 val->vsxval[j] = vcpu->arch.fp_tm.fpr[i][j];
1303                 else {
1304                         if (cpu_has_feature(CPU_FTR_ALTIVEC))
1305                                 val->vval = vcpu->arch.vr_tm.vr[i-32];
1306                         else
1307                                 r = -ENXIO;
1308                 }
1309                 break;
1310         }
1311         case KVM_REG_PPC_TM_CR:
1312                 *val = get_reg_val(id, vcpu->arch.cr_tm);
1313                 break;
1314         case KVM_REG_PPC_TM_XER:
1315                 *val = get_reg_val(id, vcpu->arch.xer_tm);
1316                 break;
1317         case KVM_REG_PPC_TM_LR:
1318                 *val = get_reg_val(id, vcpu->arch.lr_tm);
1319                 break;
1320         case KVM_REG_PPC_TM_CTR:
1321                 *val = get_reg_val(id, vcpu->arch.ctr_tm);
1322                 break;
1323         case KVM_REG_PPC_TM_FPSCR:
1324                 *val = get_reg_val(id, vcpu->arch.fp_tm.fpscr);
1325                 break;
1326         case KVM_REG_PPC_TM_AMR:
1327                 *val = get_reg_val(id, vcpu->arch.amr_tm);
1328                 break;
1329         case KVM_REG_PPC_TM_PPR:
1330                 *val = get_reg_val(id, vcpu->arch.ppr_tm);
1331                 break;
1332         case KVM_REG_PPC_TM_VRSAVE:
1333                 *val = get_reg_val(id, vcpu->arch.vrsave_tm);
1334                 break;
1335         case KVM_REG_PPC_TM_VSCR:
1336                 if (cpu_has_feature(CPU_FTR_ALTIVEC))
1337                         *val = get_reg_val(id, vcpu->arch.vr_tm.vscr.u[3]);
1338                 else
1339                         r = -ENXIO;
1340                 break;
1341         case KVM_REG_PPC_TM_DSCR:
1342                 *val = get_reg_val(id, vcpu->arch.dscr_tm);
1343                 break;
1344         case KVM_REG_PPC_TM_TAR:
1345                 *val = get_reg_val(id, vcpu->arch.tar_tm);
1346                 break;
1347 #endif
1348         case KVM_REG_PPC_ARCH_COMPAT:
1349                 *val = get_reg_val(id, vcpu->arch.vcore->arch_compat);
1350                 break;
1351         default:
1352                 r = -EINVAL;
1353                 break;
1354         }
1355
1356         return r;
1357 }
1358
1359 static int kvmppc_set_one_reg_hv(struct kvm_vcpu *vcpu, u64 id,
1360                                  union kvmppc_one_reg *val)
1361 {
1362         int r = 0;
1363         long int i;
1364         unsigned long addr, len;
1365
1366         switch (id) {
1367         case KVM_REG_PPC_HIOR:
1368                 /* Only allow this to be set to zero */
1369                 if (set_reg_val(id, *val))
1370                         r = -EINVAL;
1371                 break;
1372         case KVM_REG_PPC_DABR:
1373                 vcpu->arch.dabr = set_reg_val(id, *val);
1374                 break;
1375         case KVM_REG_PPC_DABRX:
1376                 vcpu->arch.dabrx = set_reg_val(id, *val) & ~DABRX_HYP;
1377                 break;
1378         case KVM_REG_PPC_DSCR:
1379                 vcpu->arch.dscr = set_reg_val(id, *val);
1380                 break;
1381         case KVM_REG_PPC_PURR:
1382                 vcpu->arch.purr = set_reg_val(id, *val);
1383                 break;
1384         case KVM_REG_PPC_SPURR:
1385                 vcpu->arch.spurr = set_reg_val(id, *val);
1386                 break;
1387         case KVM_REG_PPC_AMR:
1388                 vcpu->arch.amr = set_reg_val(id, *val);
1389                 break;
1390         case KVM_REG_PPC_UAMOR:
1391                 vcpu->arch.uamor = set_reg_val(id, *val);
1392                 break;
1393         case KVM_REG_PPC_MMCR0 ... KVM_REG_PPC_MMCRS:
1394                 i = id - KVM_REG_PPC_MMCR0;
1395                 vcpu->arch.mmcr[i] = set_reg_val(id, *val);
1396                 break;
1397         case KVM_REG_PPC_PMC1 ... KVM_REG_PPC_PMC8:
1398                 i = id - KVM_REG_PPC_PMC1;
1399                 vcpu->arch.pmc[i] = set_reg_val(id, *val);
1400                 break;
1401         case KVM_REG_PPC_SPMC1 ... KVM_REG_PPC_SPMC2:
1402                 i = id - KVM_REG_PPC_SPMC1;
1403                 vcpu->arch.spmc[i] = set_reg_val(id, *val);
1404                 break;
1405         case KVM_REG_PPC_SIAR:
1406                 vcpu->arch.siar = set_reg_val(id, *val);
1407                 break;
1408         case KVM_REG_PPC_SDAR:
1409                 vcpu->arch.sdar = set_reg_val(id, *val);
1410                 break;
1411         case KVM_REG_PPC_SIER:
1412                 vcpu->arch.sier = set_reg_val(id, *val);
1413                 break;
1414         case KVM_REG_PPC_IAMR:
1415                 vcpu->arch.iamr = set_reg_val(id, *val);
1416                 break;
1417         case KVM_REG_PPC_PSPB:
1418                 vcpu->arch.pspb = set_reg_val(id, *val);
1419                 break;
1420         case KVM_REG_PPC_DPDES:
1421                 vcpu->arch.vcore->dpdes = set_reg_val(id, *val);
1422                 break;
1423         case KVM_REG_PPC_VTB:
1424                 vcpu->arch.vcore->vtb = set_reg_val(id, *val);
1425                 break;
1426         case KVM_REG_PPC_DAWR:
1427                 vcpu->arch.dawr = set_reg_val(id, *val);
1428                 break;
1429         case KVM_REG_PPC_DAWRX:
1430                 vcpu->arch.dawrx = set_reg_val(id, *val) & ~DAWRX_HYP;
1431                 break;
1432         case KVM_REG_PPC_CIABR:
1433                 vcpu->arch.ciabr = set_reg_val(id, *val);
1434                 /* Don't allow setting breakpoints in hypervisor code */
1435                 if ((vcpu->arch.ciabr & CIABR_PRIV) == CIABR_PRIV_HYPER)
1436                         vcpu->arch.ciabr &= ~CIABR_PRIV;        /* disable */
1437                 break;
1438         case KVM_REG_PPC_CSIGR:
1439                 vcpu->arch.csigr = set_reg_val(id, *val);
1440                 break;
1441         case KVM_REG_PPC_TACR:
1442                 vcpu->arch.tacr = set_reg_val(id, *val);
1443                 break;
1444         case KVM_REG_PPC_TCSCR:
1445                 vcpu->arch.tcscr = set_reg_val(id, *val);
1446                 break;
1447         case KVM_REG_PPC_PID:
1448                 vcpu->arch.pid = set_reg_val(id, *val);
1449                 break;
1450         case KVM_REG_PPC_ACOP:
1451                 vcpu->arch.acop = set_reg_val(id, *val);
1452                 break;
1453         case KVM_REG_PPC_WORT:
1454                 vcpu->arch.wort = set_reg_val(id, *val);
1455                 break;
1456         case KVM_REG_PPC_TIDR:
1457                 vcpu->arch.tid = set_reg_val(id, *val);
1458                 break;
1459         case KVM_REG_PPC_PSSCR:
1460                 vcpu->arch.psscr = set_reg_val(id, *val) & PSSCR_GUEST_VIS;
1461                 break;
1462         case KVM_REG_PPC_VPA_ADDR:
1463                 addr = set_reg_val(id, *val);
1464                 r = -EINVAL;
1465                 if (!addr && (vcpu->arch.slb_shadow.next_gpa ||
1466                               vcpu->arch.dtl.next_gpa))
1467                         break;
1468                 r = set_vpa(vcpu, &vcpu->arch.vpa, addr, sizeof(struct lppaca));
1469                 break;
1470         case KVM_REG_PPC_VPA_SLB:
1471                 addr = val->vpaval.addr;
1472                 len = val->vpaval.length;
1473                 r = -EINVAL;
1474                 if (addr && !vcpu->arch.vpa.next_gpa)
1475                         break;
1476                 r = set_vpa(vcpu, &vcpu->arch.slb_shadow, addr, len);
1477                 break;
1478         case KVM_REG_PPC_VPA_DTL:
1479                 addr = val->vpaval.addr;
1480                 len = val->vpaval.length;
1481                 r = -EINVAL;
1482                 if (addr && (len < sizeof(struct dtl_entry) ||
1483                              !vcpu->arch.vpa.next_gpa))
1484                         break;
1485                 len -= len % sizeof(struct dtl_entry);
1486                 r = set_vpa(vcpu, &vcpu->arch.dtl, addr, len);
1487                 break;
1488         case KVM_REG_PPC_TB_OFFSET:
1489                 /* round up to multiple of 2^24 */
1490                 vcpu->arch.vcore->tb_offset =
1491                         ALIGN(set_reg_val(id, *val), 1UL << 24);
1492                 break;
1493         case KVM_REG_PPC_LPCR:
1494                 kvmppc_set_lpcr(vcpu, set_reg_val(id, *val), true);
1495                 break;
1496         case KVM_REG_PPC_LPCR_64:
1497                 kvmppc_set_lpcr(vcpu, set_reg_val(id, *val), false);
1498                 break;
1499         case KVM_REG_PPC_PPR:
1500                 vcpu->arch.ppr = set_reg_val(id, *val);
1501                 break;
1502 #ifdef CONFIG_PPC_TRANSACTIONAL_MEM
1503         case KVM_REG_PPC_TFHAR:
1504                 vcpu->arch.tfhar = set_reg_val(id, *val);
1505                 break;
1506         case KVM_REG_PPC_TFIAR:
1507                 vcpu->arch.tfiar = set_reg_val(id, *val);
1508                 break;
1509         case KVM_REG_PPC_TEXASR:
1510                 vcpu->arch.texasr = set_reg_val(id, *val);
1511                 break;
1512         case KVM_REG_PPC_TM_GPR0 ... KVM_REG_PPC_TM_GPR31:
1513                 i = id - KVM_REG_PPC_TM_GPR0;
1514                 vcpu->arch.gpr_tm[i] = set_reg_val(id, *val);
1515                 break;
1516         case KVM_REG_PPC_TM_VSR0 ... KVM_REG_PPC_TM_VSR63:
1517         {
1518                 int j;
1519                 i = id - KVM_REG_PPC_TM_VSR0;
1520                 if (i < 32)
1521                         for (j = 0; j < TS_FPRWIDTH; j++)
1522                                 vcpu->arch.fp_tm.fpr[i][j] = val->vsxval[j];
1523                 else
1524                         if (cpu_has_feature(CPU_FTR_ALTIVEC))
1525                                 vcpu->arch.vr_tm.vr[i-32] = val->vval;
1526                         else
1527                                 r = -ENXIO;
1528                 break;
1529         }
1530         case KVM_REG_PPC_TM_CR:
1531                 vcpu->arch.cr_tm = set_reg_val(id, *val);
1532                 break;
1533         case KVM_REG_PPC_TM_XER:
1534                 vcpu->arch.xer_tm = set_reg_val(id, *val);
1535                 break;
1536         case KVM_REG_PPC_TM_LR:
1537                 vcpu->arch.lr_tm = set_reg_val(id, *val);
1538                 break;
1539         case KVM_REG_PPC_TM_CTR:
1540                 vcpu->arch.ctr_tm = set_reg_val(id, *val);
1541                 break;
1542         case KVM_REG_PPC_TM_FPSCR:
1543                 vcpu->arch.fp_tm.fpscr = set_reg_val(id, *val);
1544                 break;
1545         case KVM_REG_PPC_TM_AMR:
1546                 vcpu->arch.amr_tm = set_reg_val(id, *val);
1547                 break;
1548         case KVM_REG_PPC_TM_PPR:
1549                 vcpu->arch.ppr_tm = set_reg_val(id, *val);
1550                 break;
1551         case KVM_REG_PPC_TM_VRSAVE:
1552                 vcpu->arch.vrsave_tm = set_reg_val(id, *val);
1553                 break;
1554         case KVM_REG_PPC_TM_VSCR:
1555                 if (cpu_has_feature(CPU_FTR_ALTIVEC))
1556                         vcpu->arch.vr.vscr.u[3] = set_reg_val(id, *val);
1557                 else
1558                         r = - ENXIO;
1559                 break;
1560         case KVM_REG_PPC_TM_DSCR:
1561                 vcpu->arch.dscr_tm = set_reg_val(id, *val);
1562                 break;
1563         case KVM_REG_PPC_TM_TAR:
1564                 vcpu->arch.tar_tm = set_reg_val(id, *val);
1565                 break;
1566 #endif
1567         case KVM_REG_PPC_ARCH_COMPAT:
1568                 r = kvmppc_set_arch_compat(vcpu, set_reg_val(id, *val));
1569                 break;
1570         default:
1571                 r = -EINVAL;
1572                 break;
1573         }
1574
1575         return r;
1576 }
1577
1578 /*
1579  * On POWER9, threads are independent and can be in different partitions.
1580  * Therefore we consider each thread to be a subcore.
1581  * There is a restriction that all threads have to be in the same
1582  * MMU mode (radix or HPT), unfortunately, but since we only support
1583  * HPT guests on a HPT host so far, that isn't an impediment yet.
1584  */
1585 static int threads_per_vcore(void)
1586 {
1587         if (cpu_has_feature(CPU_FTR_ARCH_300))
1588                 return 1;
1589         return threads_per_subcore;
1590 }
1591
1592 static struct kvmppc_vcore *kvmppc_vcore_create(struct kvm *kvm, int core)
1593 {
1594         struct kvmppc_vcore *vcore;
1595
1596         vcore = kzalloc(sizeof(struct kvmppc_vcore), GFP_KERNEL);
1597
1598         if (vcore == NULL)
1599                 return NULL;
1600
1601         spin_lock_init(&vcore->lock);
1602         spin_lock_init(&vcore->stoltb_lock);
1603         init_swait_queue_head(&vcore->wq);
1604         vcore->preempt_tb = TB_NIL;
1605         vcore->lpcr = kvm->arch.lpcr;
1606         vcore->first_vcpuid = core * threads_per_vcore();
1607         vcore->kvm = kvm;
1608         INIT_LIST_HEAD(&vcore->preempt_list);
1609
1610         return vcore;
1611 }
1612
1613 #ifdef CONFIG_KVM_BOOK3S_HV_EXIT_TIMING
1614 static struct debugfs_timings_element {
1615         const char *name;
1616         size_t offset;
1617 } timings[] = {
1618         {"rm_entry",    offsetof(struct kvm_vcpu, arch.rm_entry)},
1619         {"rm_intr",     offsetof(struct kvm_vcpu, arch.rm_intr)},
1620         {"rm_exit",     offsetof(struct kvm_vcpu, arch.rm_exit)},
1621         {"guest",       offsetof(struct kvm_vcpu, arch.guest_time)},
1622         {"cede",        offsetof(struct kvm_vcpu, arch.cede_time)},
1623 };
1624
1625 #define N_TIMINGS       (sizeof(timings) / sizeof(timings[0]))
1626
1627 struct debugfs_timings_state {
1628         struct kvm_vcpu *vcpu;
1629         unsigned int    buflen;
1630         char            buf[N_TIMINGS * 100];
1631 };
1632
1633 static int debugfs_timings_open(struct inode *inode, struct file *file)
1634 {
1635         struct kvm_vcpu *vcpu = inode->i_private;
1636         struct debugfs_timings_state *p;
1637
1638         p = kzalloc(sizeof(*p), GFP_KERNEL);
1639         if (!p)
1640                 return -ENOMEM;
1641
1642         kvm_get_kvm(vcpu->kvm);
1643         p->vcpu = vcpu;
1644         file->private_data = p;
1645
1646         return nonseekable_open(inode, file);
1647 }
1648
1649 static int debugfs_timings_release(struct inode *inode, struct file *file)
1650 {
1651         struct debugfs_timings_state *p = file->private_data;
1652
1653         kvm_put_kvm(p->vcpu->kvm);
1654         kfree(p);
1655         return 0;
1656 }
1657
1658 static ssize_t debugfs_timings_read(struct file *file, char __user *buf,
1659                                     size_t len, loff_t *ppos)
1660 {
1661         struct debugfs_timings_state *p = file->private_data;
1662         struct kvm_vcpu *vcpu = p->vcpu;
1663         char *s, *buf_end;
1664         struct kvmhv_tb_accumulator tb;
1665         u64 count;
1666         loff_t pos;
1667         ssize_t n;
1668         int i, loops;
1669         bool ok;
1670
1671         if (!p->buflen) {
1672                 s = p->buf;
1673                 buf_end = s + sizeof(p->buf);
1674                 for (i = 0; i < N_TIMINGS; ++i) {
1675                         struct kvmhv_tb_accumulator *acc;
1676
1677                         acc = (struct kvmhv_tb_accumulator *)
1678                                 ((unsigned long)vcpu + timings[i].offset);
1679                         ok = false;
1680                         for (loops = 0; loops < 1000; ++loops) {
1681                                 count = acc->seqcount;
1682                                 if (!(count & 1)) {
1683                                         smp_rmb();
1684                                         tb = *acc;
1685                                         smp_rmb();
1686                                         if (count == acc->seqcount) {
1687                                                 ok = true;
1688                                                 break;
1689                                         }
1690                                 }
1691                                 udelay(1);
1692                         }
1693                         if (!ok)
1694                                 snprintf(s, buf_end - s, "%s: stuck\n",
1695                                         timings[i].name);
1696                         else
1697                                 snprintf(s, buf_end - s,
1698                                         "%s: %llu %llu %llu %llu\n",
1699                                         timings[i].name, count / 2,
1700                                         tb_to_ns(tb.tb_total),
1701                                         tb_to_ns(tb.tb_min),
1702                                         tb_to_ns(tb.tb_max));
1703                         s += strlen(s);
1704                 }
1705                 p->buflen = s - p->buf;
1706         }
1707
1708         pos = *ppos;
1709         if (pos >= p->buflen)
1710                 return 0;
1711         if (len > p->buflen - pos)
1712                 len = p->buflen - pos;
1713         n = copy_to_user(buf, p->buf + pos, len);
1714         if (n) {
1715                 if (n == len)
1716                         return -EFAULT;
1717                 len -= n;
1718         }
1719         *ppos = pos + len;
1720         return len;
1721 }
1722
1723 static ssize_t debugfs_timings_write(struct file *file, const char __user *buf,
1724                                      size_t len, loff_t *ppos)
1725 {
1726         return -EACCES;
1727 }
1728
1729 static const struct file_operations debugfs_timings_ops = {
1730         .owner   = THIS_MODULE,
1731         .open    = debugfs_timings_open,
1732         .release = debugfs_timings_release,
1733         .read    = debugfs_timings_read,
1734         .write   = debugfs_timings_write,
1735         .llseek  = generic_file_llseek,
1736 };
1737
1738 /* Create a debugfs directory for the vcpu */
1739 static void debugfs_vcpu_init(struct kvm_vcpu *vcpu, unsigned int id)
1740 {
1741         char buf[16];
1742         struct kvm *kvm = vcpu->kvm;
1743
1744         snprintf(buf, sizeof(buf), "vcpu%u", id);
1745         if (IS_ERR_OR_NULL(kvm->arch.debugfs_dir))
1746                 return;
1747         vcpu->arch.debugfs_dir = debugfs_create_dir(buf, kvm->arch.debugfs_dir);
1748         if (IS_ERR_OR_NULL(vcpu->arch.debugfs_dir))
1749                 return;
1750         vcpu->arch.debugfs_timings =
1751                 debugfs_create_file("timings", 0444, vcpu->arch.debugfs_dir,
1752                                     vcpu, &debugfs_timings_ops);
1753 }
1754
1755 #else /* CONFIG_KVM_BOOK3S_HV_EXIT_TIMING */
1756 static void debugfs_vcpu_init(struct kvm_vcpu *vcpu, unsigned int id)
1757 {
1758 }
1759 #endif /* CONFIG_KVM_BOOK3S_HV_EXIT_TIMING */
1760
1761 static struct kvm_vcpu *kvmppc_core_vcpu_create_hv(struct kvm *kvm,
1762                                                    unsigned int id)
1763 {
1764         struct kvm_vcpu *vcpu;
1765         int err = -EINVAL;
1766         int core;
1767         struct kvmppc_vcore *vcore;
1768
1769         core = id / threads_per_vcore();
1770         if (core >= KVM_MAX_VCORES)
1771                 goto out;
1772
1773         err = -ENOMEM;
1774         vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
1775         if (!vcpu)
1776                 goto out;
1777
1778         err = kvm_vcpu_init(vcpu, kvm, id);
1779         if (err)
1780                 goto free_vcpu;
1781
1782         vcpu->arch.shared = &vcpu->arch.shregs;
1783 #ifdef CONFIG_KVM_BOOK3S_PR_POSSIBLE
1784         /*
1785          * The shared struct is never shared on HV,
1786          * so we can always use host endianness
1787          */
1788 #ifdef __BIG_ENDIAN__
1789         vcpu->arch.shared_big_endian = true;
1790 #else
1791         vcpu->arch.shared_big_endian = false;
1792 #endif
1793 #endif
1794         vcpu->arch.mmcr[0] = MMCR0_FC;
1795         vcpu->arch.ctrl = CTRL_RUNLATCH;
1796         /* default to host PVR, since we can't spoof it */
1797         kvmppc_set_pvr_hv(vcpu, mfspr(SPRN_PVR));
1798         spin_lock_init(&vcpu->arch.vpa_update_lock);
1799         spin_lock_init(&vcpu->arch.tbacct_lock);
1800         vcpu->arch.busy_preempt = TB_NIL;
1801         vcpu->arch.intr_msr = MSR_SF | MSR_ME;
1802
1803         kvmppc_mmu_book3s_hv_init(vcpu);
1804
1805         vcpu->arch.state = KVMPPC_VCPU_NOTREADY;
1806
1807         init_waitqueue_head(&vcpu->arch.cpu_run);
1808
1809         mutex_lock(&kvm->lock);
1810         vcore = kvm->arch.vcores[core];
1811         if (!vcore) {
1812                 vcore = kvmppc_vcore_create(kvm, core);
1813                 kvm->arch.vcores[core] = vcore;
1814                 kvm->arch.online_vcores++;
1815         }
1816         mutex_unlock(&kvm->lock);
1817
1818         if (!vcore)
1819                 goto free_vcpu;
1820
1821         spin_lock(&vcore->lock);
1822         ++vcore->num_threads;
1823         spin_unlock(&vcore->lock);
1824         vcpu->arch.vcore = vcore;
1825         vcpu->arch.ptid = vcpu->vcpu_id - vcore->first_vcpuid;
1826         vcpu->arch.thread_cpu = -1;
1827         vcpu->arch.prev_cpu = -1;
1828
1829         vcpu->arch.cpu_type = KVM_CPU_3S_64;
1830         kvmppc_sanity_check(vcpu);
1831
1832         debugfs_vcpu_init(vcpu, id);
1833
1834         return vcpu;
1835
1836 free_vcpu:
1837         kmem_cache_free(kvm_vcpu_cache, vcpu);
1838 out:
1839         return ERR_PTR(err);
1840 }
1841
1842 static void unpin_vpa(struct kvm *kvm, struct kvmppc_vpa *vpa)
1843 {
1844         if (vpa->pinned_addr)
1845                 kvmppc_unpin_guest_page(kvm, vpa->pinned_addr, vpa->gpa,
1846                                         vpa->dirty);
1847 }
1848
1849 static void kvmppc_core_vcpu_free_hv(struct kvm_vcpu *vcpu)
1850 {
1851         spin_lock(&vcpu->arch.vpa_update_lock);
1852         unpin_vpa(vcpu->kvm, &vcpu->arch.dtl);
1853         unpin_vpa(vcpu->kvm, &vcpu->arch.slb_shadow);
1854         unpin_vpa(vcpu->kvm, &vcpu->arch.vpa);
1855         spin_unlock(&vcpu->arch.vpa_update_lock);
1856         kvm_vcpu_uninit(vcpu);
1857         kmem_cache_free(kvm_vcpu_cache, vcpu);
1858 }
1859
1860 static int kvmppc_core_check_requests_hv(struct kvm_vcpu *vcpu)
1861 {
1862         /* Indicate we want to get back into the guest */
1863         return 1;
1864 }
1865
1866 static void kvmppc_set_timer(struct kvm_vcpu *vcpu)
1867 {
1868         unsigned long dec_nsec, now;
1869
1870         now = get_tb();
1871         if (now > vcpu->arch.dec_expires) {
1872                 /* decrementer has already gone negative */
1873                 kvmppc_core_queue_dec(vcpu);
1874                 kvmppc_core_prepare_to_enter(vcpu);
1875                 return;
1876         }
1877         dec_nsec = (vcpu->arch.dec_expires - now) * NSEC_PER_SEC
1878                    / tb_ticks_per_sec;
1879         hrtimer_start(&vcpu->arch.dec_timer, dec_nsec, HRTIMER_MODE_REL);
1880         vcpu->arch.timer_running = 1;
1881 }
1882
1883 static void kvmppc_end_cede(struct kvm_vcpu *vcpu)
1884 {
1885         vcpu->arch.ceded = 0;
1886         if (vcpu->arch.timer_running) {
1887                 hrtimer_try_to_cancel(&vcpu->arch.dec_timer);
1888                 vcpu->arch.timer_running = 0;
1889         }
1890 }
1891
1892 extern void __kvmppc_vcore_entry(void);
1893
1894 static void kvmppc_remove_runnable(struct kvmppc_vcore *vc,
1895                                    struct kvm_vcpu *vcpu)
1896 {
1897         u64 now;
1898
1899         if (vcpu->arch.state != KVMPPC_VCPU_RUNNABLE)
1900                 return;
1901         spin_lock_irq(&vcpu->arch.tbacct_lock);
1902         now = mftb();
1903         vcpu->arch.busy_stolen += vcore_stolen_time(vc, now) -
1904                 vcpu->arch.stolen_logged;
1905         vcpu->arch.busy_preempt = now;
1906         vcpu->arch.state = KVMPPC_VCPU_BUSY_IN_HOST;
1907         spin_unlock_irq(&vcpu->arch.tbacct_lock);
1908         --vc->n_runnable;
1909         WRITE_ONCE(vc->runnable_threads[vcpu->arch.ptid], NULL);
1910 }
1911
1912 static int kvmppc_grab_hwthread(int cpu)
1913 {
1914         struct paca_struct *tpaca;
1915         long timeout = 10000;
1916
1917         tpaca = &paca[cpu];
1918
1919         /* Ensure the thread won't go into the kernel if it wakes */
1920         tpaca->kvm_hstate.kvm_vcpu = NULL;
1921         tpaca->kvm_hstate.kvm_vcore = NULL;
1922         tpaca->kvm_hstate.napping = 0;
1923         smp_wmb();
1924         tpaca->kvm_hstate.hwthread_req = 1;
1925
1926         /*
1927          * If the thread is already executing in the kernel (e.g. handling
1928          * a stray interrupt), wait for it to get back to nap mode.
1929          * The smp_mb() is to ensure that our setting of hwthread_req
1930          * is visible before we look at hwthread_state, so if this
1931          * races with the code at system_reset_pSeries and the thread
1932          * misses our setting of hwthread_req, we are sure to see its
1933          * setting of hwthread_state, and vice versa.
1934          */
1935         smp_mb();
1936         while (tpaca->kvm_hstate.hwthread_state == KVM_HWTHREAD_IN_KERNEL) {
1937                 if (--timeout <= 0) {
1938                         pr_err("KVM: couldn't grab cpu %d\n", cpu);
1939                         return -EBUSY;
1940                 }
1941                 udelay(1);
1942         }
1943         return 0;
1944 }
1945
1946 static void kvmppc_release_hwthread(int cpu)
1947 {
1948         struct paca_struct *tpaca;
1949
1950         tpaca = &paca[cpu];
1951         tpaca->kvm_hstate.hwthread_req = 0;
1952         tpaca->kvm_hstate.kvm_vcpu = NULL;
1953         tpaca->kvm_hstate.kvm_vcore = NULL;
1954         tpaca->kvm_hstate.kvm_split_mode = NULL;
1955 }
1956
1957 static void do_nothing(void *x)
1958 {
1959 }
1960
1961 static void radix_flush_cpu(struct kvm *kvm, int cpu, struct kvm_vcpu *vcpu)
1962 {
1963         int i;
1964
1965         cpu = cpu_first_thread_sibling(cpu);
1966         cpumask_set_cpu(cpu, &kvm->arch.need_tlb_flush);
1967         /*
1968          * Make sure setting of bit in need_tlb_flush precedes
1969          * testing of cpu_in_guest bits.  The matching barrier on
1970          * the other side is the first smp_mb() in kvmppc_run_core().
1971          */
1972         smp_mb();
1973         for (i = 0; i < threads_per_core; ++i)
1974                 if (cpumask_test_cpu(cpu + i, &kvm->arch.cpu_in_guest))
1975                         smp_call_function_single(cpu + i, do_nothing, NULL, 1);
1976 }
1977
1978 static void kvmppc_start_thread(struct kvm_vcpu *vcpu, struct kvmppc_vcore *vc)
1979 {
1980         int cpu;
1981         struct paca_struct *tpaca;
1982         struct kvmppc_vcore *mvc = vc->master_vcore;
1983         struct kvm *kvm = vc->kvm;
1984
1985         cpu = vc->pcpu;
1986         if (vcpu) {
1987                 if (vcpu->arch.timer_running) {
1988                         hrtimer_try_to_cancel(&vcpu->arch.dec_timer);
1989                         vcpu->arch.timer_running = 0;
1990                 }
1991                 cpu += vcpu->arch.ptid;
1992                 vcpu->cpu = mvc->pcpu;
1993                 vcpu->arch.thread_cpu = cpu;
1994
1995                 /*
1996                  * With radix, the guest can do TLB invalidations itself,
1997                  * and it could choose to use the local form (tlbiel) if
1998                  * it is invalidating a translation that has only ever been
1999                  * used on one vcpu.  However, that doesn't mean it has
2000                  * only ever been used on one physical cpu, since vcpus
2001                  * can move around between pcpus.  To cope with this, when
2002                  * a vcpu moves from one pcpu to another, we need to tell
2003                  * any vcpus running on the same core as this vcpu previously
2004                  * ran to flush the TLB.  The TLB is shared between threads,
2005                  * so we use a single bit in .need_tlb_flush for all 4 threads.
2006                  */
2007                 if (kvm_is_radix(kvm) && vcpu->arch.prev_cpu != cpu) {
2008                         if (vcpu->arch.prev_cpu >= 0 &&
2009                             cpu_first_thread_sibling(vcpu->arch.prev_cpu) !=
2010                             cpu_first_thread_sibling(cpu))
2011                                 radix_flush_cpu(kvm, vcpu->arch.prev_cpu, vcpu);
2012                         vcpu->arch.prev_cpu = cpu;
2013                 }
2014                 cpumask_set_cpu(cpu, &kvm->arch.cpu_in_guest);
2015         }
2016         tpaca = &paca[cpu];
2017         tpaca->kvm_hstate.kvm_vcpu = vcpu;
2018         tpaca->kvm_hstate.ptid = cpu - mvc->pcpu;
2019         /* Order stores to hstate.kvm_vcpu etc. before store to kvm_vcore */
2020         smp_wmb();
2021         tpaca->kvm_hstate.kvm_vcore = mvc;
2022         if (cpu != smp_processor_id())
2023                 kvmppc_ipi_thread(cpu);
2024 }
2025
2026 static void kvmppc_wait_for_nap(void)
2027 {
2028         int cpu = smp_processor_id();
2029         int i, loops;
2030         int n_threads = threads_per_vcore();
2031
2032         if (n_threads <= 1)
2033                 return;
2034         for (loops = 0; loops < 1000000; ++loops) {
2035                 /*
2036                  * Check if all threads are finished.
2037                  * We set the vcore pointer when starting a thread
2038                  * and the thread clears it when finished, so we look
2039                  * for any threads that still have a non-NULL vcore ptr.
2040                  */
2041                 for (i = 1; i < n_threads; ++i)
2042                         if (paca[cpu + i].kvm_hstate.kvm_vcore)
2043                                 break;
2044                 if (i == n_threads) {
2045                         HMT_medium();
2046                         return;
2047                 }
2048                 HMT_low();
2049         }
2050         HMT_medium();
2051         for (i = 1; i < n_threads; ++i)
2052                 if (paca[cpu + i].kvm_hstate.kvm_vcore)
2053                         pr_err("KVM: CPU %d seems to be stuck\n", cpu + i);
2054 }
2055
2056 /*
2057  * Check that we are on thread 0 and that any other threads in
2058  * this core are off-line.  Then grab the threads so they can't
2059  * enter the kernel.
2060  */
2061 static int on_primary_thread(void)
2062 {
2063         int cpu = smp_processor_id();
2064         int thr;
2065
2066         /* Are we on a primary subcore? */
2067         if (cpu_thread_in_subcore(cpu))
2068                 return 0;
2069
2070         thr = 0;
2071         while (++thr < threads_per_subcore)
2072                 if (cpu_online(cpu + thr))
2073                         return 0;
2074
2075         /* Grab all hw threads so they can't go into the kernel */
2076         for (thr = 1; thr < threads_per_subcore; ++thr) {
2077                 if (kvmppc_grab_hwthread(cpu + thr)) {
2078                         /* Couldn't grab one; let the others go */
2079                         do {
2080                                 kvmppc_release_hwthread(cpu + thr);
2081                         } while (--thr > 0);
2082                         return 0;
2083                 }
2084         }
2085         return 1;
2086 }
2087
2088 /*
2089  * A list of virtual cores for each physical CPU.
2090  * These are vcores that could run but their runner VCPU tasks are
2091  * (or may be) preempted.
2092  */
2093 struct preempted_vcore_list {
2094         struct list_head        list;
2095         spinlock_t              lock;
2096 };
2097
2098 static DEFINE_PER_CPU(struct preempted_vcore_list, preempted_vcores);
2099
2100 static void init_vcore_lists(void)
2101 {
2102         int cpu;
2103
2104         for_each_possible_cpu(cpu) {
2105                 struct preempted_vcore_list *lp = &per_cpu(preempted_vcores, cpu);
2106                 spin_lock_init(&lp->lock);
2107                 INIT_LIST_HEAD(&lp->list);
2108         }
2109 }
2110
2111 static void kvmppc_vcore_preempt(struct kvmppc_vcore *vc)
2112 {
2113         struct preempted_vcore_list *lp = this_cpu_ptr(&preempted_vcores);
2114
2115         vc->vcore_state = VCORE_PREEMPT;
2116         vc->pcpu = smp_processor_id();
2117         if (vc->num_threads < threads_per_vcore()) {
2118                 spin_lock(&lp->lock);
2119                 list_add_tail(&vc->preempt_list, &lp->list);
2120                 spin_unlock(&lp->lock);
2121         }
2122
2123         /* Start accumulating stolen time */
2124         kvmppc_core_start_stolen(vc);
2125 }
2126
2127 static void kvmppc_vcore_end_preempt(struct kvmppc_vcore *vc)
2128 {
2129         struct preempted_vcore_list *lp;
2130
2131         kvmppc_core_end_stolen(vc);
2132         if (!list_empty(&vc->preempt_list)) {
2133                 lp = &per_cpu(preempted_vcores, vc->pcpu);
2134                 spin_lock(&lp->lock);
2135                 list_del_init(&vc->preempt_list);
2136                 spin_unlock(&lp->lock);
2137         }
2138         vc->vcore_state = VCORE_INACTIVE;
2139 }
2140
2141 /*
2142  * This stores information about the virtual cores currently
2143  * assigned to a physical core.
2144  */
2145 struct core_info {
2146         int             n_subcores;
2147         int             max_subcore_threads;
2148         int             total_threads;
2149         int             subcore_threads[MAX_SUBCORES];
2150         struct kvm      *subcore_vm[MAX_SUBCORES];
2151         struct list_head vcs[MAX_SUBCORES];
2152 };
2153
2154 /*
2155  * This mapping means subcores 0 and 1 can use threads 0-3 and 4-7
2156  * respectively in 2-way micro-threading (split-core) mode.
2157  */
2158 static int subcore_thread_map[MAX_SUBCORES] = { 0, 4, 2, 6 };
2159
2160 static void init_core_info(struct core_info *cip, struct kvmppc_vcore *vc)
2161 {
2162         int sub;
2163
2164         memset(cip, 0, sizeof(*cip));
2165         cip->n_subcores = 1;
2166         cip->max_subcore_threads = vc->num_threads;
2167         cip->total_threads = vc->num_threads;
2168         cip->subcore_threads[0] = vc->num_threads;
2169         cip->subcore_vm[0] = vc->kvm;
2170         for (sub = 0; sub < MAX_SUBCORES; ++sub)
2171                 INIT_LIST_HEAD(&cip->vcs[sub]);
2172         list_add_tail(&vc->preempt_list, &cip->vcs[0]);
2173 }
2174
2175 static bool subcore_config_ok(int n_subcores, int n_threads)
2176 {
2177         /* Can only dynamically split if unsplit to begin with */
2178         if (n_subcores > 1 && threads_per_subcore < MAX_SMT_THREADS)
2179                 return false;
2180         if (n_subcores > MAX_SUBCORES)
2181                 return false;
2182         if (n_subcores > 1) {
2183                 if (!(dynamic_mt_modes & 2))
2184                         n_subcores = 4;
2185                 if (n_subcores > 2 && !(dynamic_mt_modes & 4))
2186                         return false;
2187         }
2188
2189         return n_subcores * roundup_pow_of_two(n_threads) <= MAX_SMT_THREADS;
2190 }
2191
2192 static void init_master_vcore(struct kvmppc_vcore *vc)
2193 {
2194         vc->master_vcore = vc;
2195         vc->entry_exit_map = 0;
2196         vc->in_guest = 0;
2197         vc->napping_threads = 0;
2198         vc->conferring_threads = 0;
2199 }
2200
2201 static bool can_dynamic_split(struct kvmppc_vcore *vc, struct core_info *cip)
2202 {
2203         int n_threads = vc->num_threads;
2204         int sub;
2205
2206         if (!cpu_has_feature(CPU_FTR_ARCH_207S))
2207                 return false;
2208
2209         if (n_threads < cip->max_subcore_threads)
2210                 n_threads = cip->max_subcore_threads;
2211         if (!subcore_config_ok(cip->n_subcores + 1, n_threads))
2212                 return false;
2213         cip->max_subcore_threads = n_threads;
2214
2215         sub = cip->n_subcores;
2216         ++cip->n_subcores;
2217         cip->total_threads += vc->num_threads;
2218         cip->subcore_threads[sub] = vc->num_threads;
2219         cip->subcore_vm[sub] = vc->kvm;
2220         init_master_vcore(vc);
2221         list_move_tail(&vc->preempt_list, &cip->vcs[sub]);
2222
2223         return true;
2224 }
2225
2226 /*
2227  * Work out whether it is possible to piggyback the execution of
2228  * vcore *pvc onto the execution of the other vcores described in *cip.
2229  */
2230 static bool can_piggyback(struct kvmppc_vcore *pvc, struct core_info *cip,
2231                           int target_threads)
2232 {
2233         if (cip->total_threads + pvc->num_threads > target_threads)
2234                 return false;
2235
2236         return can_dynamic_split(pvc, cip);
2237 }
2238
2239 static void prepare_threads(struct kvmppc_vcore *vc)
2240 {
2241         int i;
2242         struct kvm_vcpu *vcpu;
2243
2244         for_each_runnable_thread(i, vcpu, vc) {
2245                 if (signal_pending(vcpu->arch.run_task))
2246                         vcpu->arch.ret = -EINTR;
2247                 else if (vcpu->arch.vpa.update_pending ||
2248                          vcpu->arch.slb_shadow.update_pending ||
2249                          vcpu->arch.dtl.update_pending)
2250                         vcpu->arch.ret = RESUME_GUEST;
2251                 else
2252                         continue;
2253                 kvmppc_remove_runnable(vc, vcpu);
2254                 wake_up(&vcpu->arch.cpu_run);
2255         }
2256 }
2257
2258 static void collect_piggybacks(struct core_info *cip, int target_threads)
2259 {
2260         struct preempted_vcore_list *lp = this_cpu_ptr(&preempted_vcores);
2261         struct kvmppc_vcore *pvc, *vcnext;
2262
2263         spin_lock(&lp->lock);
2264         list_for_each_entry_safe(pvc, vcnext, &lp->list, preempt_list) {
2265                 if (!spin_trylock(&pvc->lock))
2266                         continue;
2267                 prepare_threads(pvc);
2268                 if (!pvc->n_runnable) {
2269                         list_del_init(&pvc->preempt_list);
2270                         if (pvc->runner == NULL) {
2271                                 pvc->vcore_state = VCORE_INACTIVE;
2272                                 kvmppc_core_end_stolen(pvc);
2273                         }
2274                         spin_unlock(&pvc->lock);
2275                         continue;
2276                 }
2277                 if (!can_piggyback(pvc, cip, target_threads)) {
2278                         spin_unlock(&pvc->lock);
2279                         continue;
2280                 }
2281                 kvmppc_core_end_stolen(pvc);
2282                 pvc->vcore_state = VCORE_PIGGYBACK;
2283                 if (cip->total_threads >= target_threads)
2284                         break;
2285         }
2286         spin_unlock(&lp->lock);
2287 }
2288
2289 static void post_guest_process(struct kvmppc_vcore *vc, bool is_master)
2290 {
2291         int still_running = 0, i;
2292         u64 now;
2293         long ret;
2294         struct kvm_vcpu *vcpu;
2295
2296         spin_lock(&vc->lock);
2297         now = get_tb();
2298         for_each_runnable_thread(i, vcpu, vc) {
2299                 /* cancel pending dec exception if dec is positive */
2300                 if (now < vcpu->arch.dec_expires &&
2301                     kvmppc_core_pending_dec(vcpu))
2302                         kvmppc_core_dequeue_dec(vcpu);
2303
2304                 trace_kvm_guest_exit(vcpu);
2305
2306                 ret = RESUME_GUEST;
2307                 if (vcpu->arch.trap)
2308                         ret = kvmppc_handle_exit_hv(vcpu->arch.kvm_run, vcpu,
2309                                                     vcpu->arch.run_task);
2310
2311                 vcpu->arch.ret = ret;
2312                 vcpu->arch.trap = 0;
2313
2314                 if (is_kvmppc_resume_guest(vcpu->arch.ret)) {
2315                         if (vcpu->arch.pending_exceptions)
2316                                 kvmppc_core_prepare_to_enter(vcpu);
2317                         if (vcpu->arch.ceded)
2318                                 kvmppc_set_timer(vcpu);
2319                         else
2320                                 ++still_running;
2321                 } else {
2322                         kvmppc_remove_runnable(vc, vcpu);
2323                         wake_up(&vcpu->arch.cpu_run);
2324                 }
2325         }
2326         list_del_init(&vc->preempt_list);
2327         if (!is_master) {
2328                 if (still_running > 0) {
2329                         kvmppc_vcore_preempt(vc);
2330                 } else if (vc->runner) {
2331                         vc->vcore_state = VCORE_PREEMPT;
2332                         kvmppc_core_start_stolen(vc);
2333                 } else {
2334                         vc->vcore_state = VCORE_INACTIVE;
2335                 }
2336                 if (vc->n_runnable > 0 && vc->runner == NULL) {
2337                         /* make sure there's a candidate runner awake */
2338                         i = -1;
2339                         vcpu = next_runnable_thread(vc, &i);
2340                         wake_up(&vcpu->arch.cpu_run);
2341                 }
2342         }
2343         spin_unlock(&vc->lock);
2344 }
2345
2346 /*
2347  * Clear core from the list of active host cores as we are about to
2348  * enter the guest. Only do this if it is the primary thread of the
2349  * core (not if a subcore) that is entering the guest.
2350  */
2351 static inline int kvmppc_clear_host_core(unsigned int cpu)
2352 {
2353         int core;
2354
2355         if (!kvmppc_host_rm_ops_hv || cpu_thread_in_core(cpu))
2356                 return 0;
2357         /*
2358          * Memory barrier can be omitted here as we will do a smp_wmb()
2359          * later in kvmppc_start_thread and we need ensure that state is
2360          * visible to other CPUs only after we enter guest.
2361          */
2362         core = cpu >> threads_shift;
2363         kvmppc_host_rm_ops_hv->rm_core[core].rm_state.in_host = 0;
2364         return 0;
2365 }
2366
2367 /*
2368  * Advertise this core as an active host core since we exited the guest
2369  * Only need to do this if it is the primary thread of the core that is
2370  * exiting.
2371  */
2372 static inline int kvmppc_set_host_core(unsigned int cpu)
2373 {
2374         int core;
2375
2376         if (!kvmppc_host_rm_ops_hv || cpu_thread_in_core(cpu))
2377                 return 0;
2378
2379         /*
2380          * Memory barrier can be omitted here because we do a spin_unlock
2381          * immediately after this which provides the memory barrier.
2382          */
2383         core = cpu >> threads_shift;
2384         kvmppc_host_rm_ops_hv->rm_core[core].rm_state.in_host = 1;
2385         return 0;
2386 }
2387
2388 /*
2389  * Run a set of guest threads on a physical core.
2390  * Called with vc->lock held.
2391  */
2392 static noinline void kvmppc_run_core(struct kvmppc_vcore *vc)
2393 {
2394         struct kvm_vcpu *vcpu;
2395         int i;
2396         int srcu_idx;
2397         struct core_info core_info;
2398         struct kvmppc_vcore *pvc, *vcnext;
2399         struct kvm_split_mode split_info, *sip;
2400         int split, subcore_size, active;
2401         int sub;
2402         bool thr0_done;
2403         unsigned long cmd_bit, stat_bit;
2404         int pcpu, thr;
2405         int target_threads;
2406         int controlled_threads;
2407
2408         /*
2409          * Remove from the list any threads that have a signal pending
2410          * or need a VPA update done
2411          */
2412         prepare_threads(vc);
2413
2414         /* if the runner is no longer runnable, let the caller pick a new one */
2415         if (vc->runner->arch.state != KVMPPC_VCPU_RUNNABLE)
2416                 return;
2417
2418         /*
2419          * Initialize *vc.
2420          */
2421         init_master_vcore(vc);
2422         vc->preempt_tb = TB_NIL;
2423
2424         /*
2425          * Number of threads that we will be controlling: the same as
2426          * the number of threads per subcore, except on POWER9,
2427          * where it's 1 because the threads are (mostly) independent.
2428          */
2429         controlled_threads = threads_per_vcore();
2430
2431         /*
2432          * Make sure we are running on primary threads, and that secondary
2433          * threads are offline.  Also check if the number of threads in this
2434          * guest are greater than the current system threads per guest.
2435          */
2436         if ((controlled_threads > 1) &&
2437             ((vc->num_threads > threads_per_subcore) || !on_primary_thread())) {
2438                 for_each_runnable_thread(i, vcpu, vc) {
2439                         vcpu->arch.ret = -EBUSY;
2440                         kvmppc_remove_runnable(vc, vcpu);
2441                         wake_up(&vcpu->arch.cpu_run);
2442                 }
2443                 goto out;
2444         }
2445
2446         /*
2447          * See if we could run any other vcores on the physical core
2448          * along with this one.
2449          */
2450         init_core_info(&core_info, vc);
2451         pcpu = smp_processor_id();
2452         target_threads = controlled_threads;
2453         if (target_smt_mode && target_smt_mode < target_threads)
2454                 target_threads = target_smt_mode;
2455         if (vc->num_threads < target_threads)
2456                 collect_piggybacks(&core_info, target_threads);
2457
2458         /* Decide on micro-threading (split-core) mode */
2459         subcore_size = threads_per_subcore;
2460         cmd_bit = stat_bit = 0;
2461         split = core_info.n_subcores;
2462         sip = NULL;
2463         if (split > 1) {
2464                 /* threads_per_subcore must be MAX_SMT_THREADS (8) here */
2465                 if (split == 2 && (dynamic_mt_modes & 2)) {
2466                         cmd_bit = HID0_POWER8_1TO2LPAR;
2467                         stat_bit = HID0_POWER8_2LPARMODE;
2468                 } else {
2469                         split = 4;
2470                         cmd_bit = HID0_POWER8_1TO4LPAR;
2471                         stat_bit = HID0_POWER8_4LPARMODE;
2472                 }
2473                 subcore_size = MAX_SMT_THREADS / split;
2474                 sip = &split_info;
2475                 memset(&split_info, 0, sizeof(split_info));
2476                 split_info.rpr = mfspr(SPRN_RPR);
2477                 split_info.pmmar = mfspr(SPRN_PMMAR);
2478                 split_info.ldbar = mfspr(SPRN_LDBAR);
2479                 split_info.subcore_size = subcore_size;
2480                 for (sub = 0; sub < core_info.n_subcores; ++sub)
2481                         split_info.master_vcs[sub] =
2482                                 list_first_entry(&core_info.vcs[sub],
2483                                         struct kvmppc_vcore, preempt_list);
2484                 /* order writes to split_info before kvm_split_mode pointer */
2485                 smp_wmb();
2486         }
2487         pcpu = smp_processor_id();
2488         for (thr = 0; thr < controlled_threads; ++thr)
2489                 paca[pcpu + thr].kvm_hstate.kvm_split_mode = sip;
2490
2491         /* Initiate micro-threading (split-core) if required */
2492         if (cmd_bit) {
2493                 unsigned long hid0 = mfspr(SPRN_HID0);
2494
2495                 hid0 |= cmd_bit | HID0_POWER8_DYNLPARDIS;
2496                 mb();
2497                 mtspr(SPRN_HID0, hid0);
2498                 isync();
2499                 for (;;) {
2500                         hid0 = mfspr(SPRN_HID0);
2501                         if (hid0 & stat_bit)
2502                                 break;
2503                         cpu_relax();
2504                 }
2505         }
2506
2507         kvmppc_clear_host_core(pcpu);
2508
2509         /* Start all the threads */
2510         active = 0;
2511         for (sub = 0; sub < core_info.n_subcores; ++sub) {
2512                 thr = subcore_thread_map[sub];
2513                 thr0_done = false;
2514                 active |= 1 << thr;
2515                 list_for_each_entry(pvc, &core_info.vcs[sub], preempt_list) {
2516                         pvc->pcpu = pcpu + thr;
2517                         for_each_runnable_thread(i, vcpu, pvc) {
2518                                 kvmppc_start_thread(vcpu, pvc);
2519                                 kvmppc_create_dtl_entry(vcpu, pvc);
2520                                 trace_kvm_guest_enter(vcpu);
2521                                 if (!vcpu->arch.ptid)
2522                                         thr0_done = true;
2523                                 active |= 1 << (thr + vcpu->arch.ptid);
2524                         }
2525                         /*
2526                          * We need to start the first thread of each subcore
2527                          * even if it doesn't have a vcpu.
2528                          */
2529                         if (pvc->master_vcore == pvc && !thr0_done)
2530                                 kvmppc_start_thread(NULL, pvc);
2531                         thr += pvc->num_threads;
2532                 }
2533         }
2534
2535         /*
2536          * Ensure that split_info.do_nap is set after setting
2537          * the vcore pointer in the PACA of the secondaries.
2538          */
2539         smp_mb();
2540         if (cmd_bit)
2541                 split_info.do_nap = 1;  /* ask secondaries to nap when done */
2542
2543         /*
2544          * When doing micro-threading, poke the inactive threads as well.
2545          * This gets them to the nap instruction after kvm_do_nap,
2546          * which reduces the time taken to unsplit later.
2547          */
2548         if (split > 1)
2549                 for (thr = 1; thr < threads_per_subcore; ++thr)
2550                         if (!(active & (1 << thr)))
2551                                 kvmppc_ipi_thread(pcpu + thr);
2552
2553         vc->vcore_state = VCORE_RUNNING;
2554         preempt_disable();
2555
2556         trace_kvmppc_run_core(vc, 0);
2557
2558         for (sub = 0; sub < core_info.n_subcores; ++sub)
2559                 list_for_each_entry(pvc, &core_info.vcs[sub], preempt_list)
2560                         spin_unlock(&pvc->lock);
2561
2562         guest_enter();
2563
2564         srcu_idx = srcu_read_lock(&vc->kvm->srcu);
2565
2566         __kvmppc_vcore_entry();
2567
2568         srcu_read_unlock(&vc->kvm->srcu, srcu_idx);
2569
2570         spin_lock(&vc->lock);
2571         /* prevent other vcpu threads from doing kvmppc_start_thread() now */
2572         vc->vcore_state = VCORE_EXITING;
2573
2574         /* wait for secondary threads to finish writing their state to memory */
2575         kvmppc_wait_for_nap();
2576
2577         /* Return to whole-core mode if we split the core earlier */
2578         if (split > 1) {
2579                 unsigned long hid0 = mfspr(SPRN_HID0);
2580                 unsigned long loops = 0;
2581
2582                 hid0 &= ~HID0_POWER8_DYNLPARDIS;
2583                 stat_bit = HID0_POWER8_2LPARMODE | HID0_POWER8_4LPARMODE;
2584                 mb();
2585                 mtspr(SPRN_HID0, hid0);
2586                 isync();
2587                 for (;;) {
2588                         hid0 = mfspr(SPRN_HID0);
2589                         if (!(hid0 & stat_bit))
2590                                 break;
2591                         cpu_relax();
2592                         ++loops;
2593                 }
2594                 split_info.do_nap = 0;
2595         }
2596
2597         /* Let secondaries go back to the offline loop */
2598         for (i = 0; i < controlled_threads; ++i) {
2599                 kvmppc_release_hwthread(pcpu + i);
2600                 if (sip && sip->napped[i])
2601                         kvmppc_ipi_thread(pcpu + i);
2602                 cpumask_clear_cpu(pcpu + i, &vc->kvm->arch.cpu_in_guest);
2603         }
2604
2605         kvmppc_set_host_core(pcpu);
2606
2607         spin_unlock(&vc->lock);
2608
2609         /* make sure updates to secondary vcpu structs are visible now */
2610         smp_mb();
2611         guest_exit();
2612
2613         for (sub = 0; sub < core_info.n_subcores; ++sub)
2614                 list_for_each_entry_safe(pvc, vcnext, &core_info.vcs[sub],
2615                                          preempt_list)
2616                         post_guest_process(pvc, pvc == vc);
2617
2618         spin_lock(&vc->lock);
2619         preempt_enable();
2620
2621  out:
2622         vc->vcore_state = VCORE_INACTIVE;
2623         trace_kvmppc_run_core(vc, 1);
2624 }
2625
2626 /*
2627  * Wait for some other vcpu thread to execute us, and
2628  * wake us up when we need to handle something in the host.
2629  */
2630 static void kvmppc_wait_for_exec(struct kvmppc_vcore *vc,
2631                                  struct kvm_vcpu *vcpu, int wait_state)
2632 {
2633         DEFINE_WAIT(wait);
2634
2635         prepare_to_wait(&vcpu->arch.cpu_run, &wait, wait_state);
2636         if (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE) {
2637                 spin_unlock(&vc->lock);
2638                 schedule();
2639                 spin_lock(&vc->lock);
2640         }
2641         finish_wait(&vcpu->arch.cpu_run, &wait);
2642 }
2643
2644 static void grow_halt_poll_ns(struct kvmppc_vcore *vc)
2645 {
2646         /* 10us base */
2647         if (vc->halt_poll_ns == 0 && halt_poll_ns_grow)
2648                 vc->halt_poll_ns = 10000;
2649         else
2650                 vc->halt_poll_ns *= halt_poll_ns_grow;
2651 }
2652
2653 static void shrink_halt_poll_ns(struct kvmppc_vcore *vc)
2654 {
2655         if (halt_poll_ns_shrink == 0)
2656                 vc->halt_poll_ns = 0;
2657         else
2658                 vc->halt_poll_ns /= halt_poll_ns_shrink;
2659 }
2660
2661 /*
2662  * Check to see if any of the runnable vcpus on the vcore have pending
2663  * exceptions or are no longer ceded
2664  */
2665 static int kvmppc_vcore_check_block(struct kvmppc_vcore *vc)
2666 {
2667         struct kvm_vcpu *vcpu;
2668         int i;
2669
2670         for_each_runnable_thread(i, vcpu, vc) {
2671                 if (vcpu->arch.pending_exceptions || !vcpu->arch.ceded ||
2672                     vcpu->arch.prodded)
2673                         return 1;
2674         }
2675
2676         return 0;
2677 }
2678
2679 /*
2680  * All the vcpus in this vcore are idle, so wait for a decrementer
2681  * or external interrupt to one of the vcpus.  vc->lock is held.
2682  */
2683 static void kvmppc_vcore_blocked(struct kvmppc_vcore *vc)
2684 {
2685         ktime_t cur, start_poll, start_wait;
2686         int do_sleep = 1;
2687         u64 block_ns;
2688         DECLARE_SWAITQUEUE(wait);
2689
2690         /* Poll for pending exceptions and ceded state */
2691         cur = start_poll = ktime_get();
2692         if (vc->halt_poll_ns) {
2693                 ktime_t stop = ktime_add_ns(start_poll, vc->halt_poll_ns);
2694                 ++vc->runner->stat.halt_attempted_poll;
2695
2696                 vc->vcore_state = VCORE_POLLING;
2697                 spin_unlock(&vc->lock);
2698
2699                 do {
2700                         if (kvmppc_vcore_check_block(vc)) {
2701                                 do_sleep = 0;
2702                                 break;
2703                         }
2704                         cur = ktime_get();
2705                 } while (single_task_running() && ktime_before(cur, stop));
2706
2707                 spin_lock(&vc->lock);
2708                 vc->vcore_state = VCORE_INACTIVE;
2709
2710                 if (!do_sleep) {
2711                         ++vc->runner->stat.halt_successful_poll;
2712                         goto out;
2713                 }
2714         }
2715
2716         prepare_to_swait(&vc->wq, &wait, TASK_INTERRUPTIBLE);
2717
2718         if (kvmppc_vcore_check_block(vc)) {
2719                 finish_swait(&vc->wq, &wait);
2720                 do_sleep = 0;
2721                 /* If we polled, count this as a successful poll */
2722                 if (vc->halt_poll_ns)
2723                         ++vc->runner->stat.halt_successful_poll;
2724                 goto out;
2725         }
2726
2727         start_wait = ktime_get();
2728
2729         vc->vcore_state = VCORE_SLEEPING;
2730         trace_kvmppc_vcore_blocked(vc, 0);
2731         spin_unlock(&vc->lock);
2732         schedule();
2733         finish_swait(&vc->wq, &wait);
2734         spin_lock(&vc->lock);
2735         vc->vcore_state = VCORE_INACTIVE;
2736         trace_kvmppc_vcore_blocked(vc, 1);
2737         ++vc->runner->stat.halt_successful_wait;
2738
2739         cur = ktime_get();
2740
2741 out:
2742         block_ns = ktime_to_ns(cur) - ktime_to_ns(start_poll);
2743
2744         /* Attribute wait time */
2745         if (do_sleep) {
2746                 vc->runner->stat.halt_wait_ns +=
2747                         ktime_to_ns(cur) - ktime_to_ns(start_wait);
2748                 /* Attribute failed poll time */
2749                 if (vc->halt_poll_ns)
2750                         vc->runner->stat.halt_poll_fail_ns +=
2751                                 ktime_to_ns(start_wait) -
2752                                 ktime_to_ns(start_poll);
2753         } else {
2754                 /* Attribute successful poll time */
2755                 if (vc->halt_poll_ns)
2756                         vc->runner->stat.halt_poll_success_ns +=
2757                                 ktime_to_ns(cur) -
2758                                 ktime_to_ns(start_poll);
2759         }
2760
2761         /* Adjust poll time */
2762         if (halt_poll_ns) {
2763                 if (block_ns <= vc->halt_poll_ns)
2764                         ;
2765                 /* We slept and blocked for longer than the max halt time */
2766                 else if (vc->halt_poll_ns && block_ns > halt_poll_ns)
2767                         shrink_halt_poll_ns(vc);
2768                 /* We slept and our poll time is too small */
2769                 else if (vc->halt_poll_ns < halt_poll_ns &&
2770                                 block_ns < halt_poll_ns)
2771                         grow_halt_poll_ns(vc);
2772                 if (vc->halt_poll_ns > halt_poll_ns)
2773                         vc->halt_poll_ns = halt_poll_ns;
2774         } else
2775                 vc->halt_poll_ns = 0;
2776
2777         trace_kvmppc_vcore_wakeup(do_sleep, block_ns);
2778 }
2779
2780 static int kvmppc_run_vcpu(struct kvm_run *kvm_run, struct kvm_vcpu *vcpu)
2781 {
2782         int n_ceded, i;
2783         struct kvmppc_vcore *vc;
2784         struct kvm_vcpu *v;
2785
2786         trace_kvmppc_run_vcpu_enter(vcpu);
2787
2788         kvm_run->exit_reason = 0;
2789         vcpu->arch.ret = RESUME_GUEST;
2790         vcpu->arch.trap = 0;
2791         kvmppc_update_vpas(vcpu);
2792
2793         /*
2794          * Synchronize with other threads in this virtual core
2795          */
2796         vc = vcpu->arch.vcore;
2797         spin_lock(&vc->lock);
2798         vcpu->arch.ceded = 0;
2799         vcpu->arch.run_task = current;
2800         vcpu->arch.kvm_run = kvm_run;
2801         vcpu->arch.stolen_logged = vcore_stolen_time(vc, mftb());
2802         vcpu->arch.state = KVMPPC_VCPU_RUNNABLE;
2803         vcpu->arch.busy_preempt = TB_NIL;
2804         WRITE_ONCE(vc->runnable_threads[vcpu->arch.ptid], vcpu);
2805         ++vc->n_runnable;
2806
2807         /*
2808          * This happens the first time this is called for a vcpu.
2809          * If the vcore is already running, we may be able to start
2810          * this thread straight away and have it join in.
2811          */
2812         if (!signal_pending(current)) {
2813                 if (vc->vcore_state == VCORE_PIGGYBACK) {
2814                         struct kvmppc_vcore *mvc = vc->master_vcore;
2815                         if (spin_trylock(&mvc->lock)) {
2816                                 if (mvc->vcore_state == VCORE_RUNNING &&
2817                                     !VCORE_IS_EXITING(mvc)) {
2818                                         kvmppc_create_dtl_entry(vcpu, vc);
2819                                         kvmppc_start_thread(vcpu, vc);
2820                                         trace_kvm_guest_enter(vcpu);
2821                                 }
2822                                 spin_unlock(&mvc->lock);
2823                         }
2824                 } else if (vc->vcore_state == VCORE_RUNNING &&
2825                            !VCORE_IS_EXITING(vc)) {
2826                         kvmppc_create_dtl_entry(vcpu, vc);
2827                         kvmppc_start_thread(vcpu, vc);
2828                         trace_kvm_guest_enter(vcpu);
2829                 } else if (vc->vcore_state == VCORE_SLEEPING) {
2830                         swake_up(&vc->wq);
2831                 }
2832
2833         }
2834
2835         while (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE &&
2836                !signal_pending(current)) {
2837                 if (vc->vcore_state == VCORE_PREEMPT && vc->runner == NULL)
2838                         kvmppc_vcore_end_preempt(vc);
2839
2840                 if (vc->vcore_state != VCORE_INACTIVE) {
2841                         kvmppc_wait_for_exec(vc, vcpu, TASK_INTERRUPTIBLE);
2842                         continue;
2843                 }
2844                 for_each_runnable_thread(i, v, vc) {
2845                         kvmppc_core_prepare_to_enter(v);
2846                         if (signal_pending(v->arch.run_task)) {
2847                                 kvmppc_remove_runnable(vc, v);
2848                                 v->stat.signal_exits++;
2849                                 v->arch.kvm_run->exit_reason = KVM_EXIT_INTR;
2850                                 v->arch.ret = -EINTR;
2851                                 wake_up(&v->arch.cpu_run);
2852                         }
2853                 }
2854                 if (!vc->n_runnable || vcpu->arch.state != KVMPPC_VCPU_RUNNABLE)
2855                         break;
2856                 n_ceded = 0;
2857                 for_each_runnable_thread(i, v, vc) {
2858                         if (!v->arch.pending_exceptions && !v->arch.prodded)
2859                                 n_ceded += v->arch.ceded;
2860                         else
2861                                 v->arch.ceded = 0;
2862                 }
2863                 vc->runner = vcpu;
2864                 if (n_ceded == vc->n_runnable) {
2865                         kvmppc_vcore_blocked(vc);
2866                 } else if (need_resched()) {
2867                         kvmppc_vcore_preempt(vc);
2868                         /* Let something else run */
2869                         cond_resched_lock(&vc->lock);
2870                         if (vc->vcore_state == VCORE_PREEMPT)
2871                                 kvmppc_vcore_end_preempt(vc);
2872                 } else {
2873                         kvmppc_run_core(vc);
2874                 }
2875                 vc->runner = NULL;
2876         }
2877
2878         while (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE &&
2879                (vc->vcore_state == VCORE_RUNNING ||
2880                 vc->vcore_state == VCORE_EXITING ||
2881                 vc->vcore_state == VCORE_PIGGYBACK))
2882                 kvmppc_wait_for_exec(vc, vcpu, TASK_UNINTERRUPTIBLE);
2883
2884         if (vc->vcore_state == VCORE_PREEMPT && vc->runner == NULL)
2885                 kvmppc_vcore_end_preempt(vc);
2886
2887         if (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE) {
2888                 kvmppc_remove_runnable(vc, vcpu);
2889                 vcpu->stat.signal_exits++;
2890                 kvm_run->exit_reason = KVM_EXIT_INTR;
2891                 vcpu->arch.ret = -EINTR;
2892         }
2893
2894         if (vc->n_runnable && vc->vcore_state == VCORE_INACTIVE) {
2895                 /* Wake up some vcpu to run the core */
2896                 i = -1;
2897                 v = next_runnable_thread(vc, &i);
2898                 wake_up(&v->arch.cpu_run);
2899         }
2900
2901         trace_kvmppc_run_vcpu_exit(vcpu, kvm_run);
2902         spin_unlock(&vc->lock);
2903         return vcpu->arch.ret;
2904 }
2905
2906 static int kvmppc_vcpu_run_hv(struct kvm_run *run, struct kvm_vcpu *vcpu)
2907 {
2908         int r;
2909         int srcu_idx;
2910
2911         if (!vcpu->arch.sane) {
2912                 run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
2913                 return -EINVAL;
2914         }
2915
2916         kvmppc_core_prepare_to_enter(vcpu);
2917
2918         /* No need to go into the guest when all we'll do is come back out */
2919         if (signal_pending(current)) {
2920                 run->exit_reason = KVM_EXIT_INTR;
2921                 return -EINTR;
2922         }
2923
2924         atomic_inc(&vcpu->kvm->arch.vcpus_running);
2925         /* Order vcpus_running vs. hpte_setup_done, see kvmppc_alloc_reset_hpt */
2926         smp_mb();
2927
2928         /* On the first time here, set up HTAB and VRMA */
2929         if (!kvm_is_radix(vcpu->kvm) && !vcpu->kvm->arch.hpte_setup_done) {
2930                 r = kvmppc_hv_setup_htab_rma(vcpu);
2931                 if (r)
2932                         goto out;
2933         }
2934
2935         flush_all_to_thread(current);
2936
2937         vcpu->arch.wqp = &vcpu->arch.vcore->wq;
2938         vcpu->arch.pgdir = current->mm->pgd;
2939         vcpu->arch.state = KVMPPC_VCPU_BUSY_IN_HOST;
2940
2941         do {
2942                 r = kvmppc_run_vcpu(run, vcpu);
2943
2944                 if (run->exit_reason == KVM_EXIT_PAPR_HCALL &&
2945                     !(vcpu->arch.shregs.msr & MSR_PR)) {
2946                         trace_kvm_hcall_enter(vcpu);
2947                         r = kvmppc_pseries_do_hcall(vcpu);
2948                         trace_kvm_hcall_exit(vcpu, r);
2949                         kvmppc_core_prepare_to_enter(vcpu);
2950                 } else if (r == RESUME_PAGE_FAULT) {
2951                         srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
2952                         r = kvmppc_book3s_hv_page_fault(run, vcpu,
2953                                 vcpu->arch.fault_dar, vcpu->arch.fault_dsisr);
2954                         srcu_read_unlock(&vcpu->kvm->srcu, srcu_idx);
2955                 } else if (r == RESUME_PASSTHROUGH) {
2956                         if (WARN_ON(xive_enabled()))
2957                                 r = H_SUCCESS;
2958                         else
2959                                 r = kvmppc_xics_rm_complete(vcpu, 0);
2960                 }
2961         } while (is_kvmppc_resume_guest(r));
2962
2963  out:
2964         vcpu->arch.state = KVMPPC_VCPU_NOTREADY;
2965         atomic_dec(&vcpu->kvm->arch.vcpus_running);
2966         return r;
2967 }
2968
2969 static void kvmppc_add_seg_page_size(struct kvm_ppc_one_seg_page_size **sps,
2970                                      int linux_psize)
2971 {
2972         struct mmu_psize_def *def = &mmu_psize_defs[linux_psize];
2973
2974         if (!def->shift)
2975                 return;
2976         (*sps)->page_shift = def->shift;
2977         (*sps)->slb_enc = def->sllp;
2978         (*sps)->enc[0].page_shift = def->shift;
2979         (*sps)->enc[0].pte_enc = def->penc[linux_psize];
2980         /*
2981          * Add 16MB MPSS support if host supports it
2982          */
2983         if (linux_psize != MMU_PAGE_16M && def->penc[MMU_PAGE_16M] != -1) {
2984                 (*sps)->enc[1].page_shift = 24;
2985                 (*sps)->enc[1].pte_enc = def->penc[MMU_PAGE_16M];
2986         }
2987         (*sps)++;
2988 }
2989
2990 static int kvm_vm_ioctl_get_smmu_info_hv(struct kvm *kvm,
2991                                          struct kvm_ppc_smmu_info *info)
2992 {
2993         struct kvm_ppc_one_seg_page_size *sps;
2994
2995         /*
2996          * Since we don't yet support HPT guests on a radix host,
2997          * return an error if the host uses radix.
2998          */
2999         if (radix_enabled())
3000                 return -EINVAL;
3001
3002         info->flags = KVM_PPC_PAGE_SIZES_REAL;
3003         if (mmu_has_feature(MMU_FTR_1T_SEGMENT))
3004                 info->flags |= KVM_PPC_1T_SEGMENTS;
3005         info->slb_size = mmu_slb_size;
3006
3007         /* We only support these sizes for now, and no muti-size segments */
3008         sps = &info->sps[0];
3009         kvmppc_add_seg_page_size(&sps, MMU_PAGE_4K);
3010         kvmppc_add_seg_page_size(&sps, MMU_PAGE_64K);
3011         kvmppc_add_seg_page_size(&sps, MMU_PAGE_16M);
3012
3013         return 0;
3014 }
3015
3016 /*
3017  * Get (and clear) the dirty memory log for a memory slot.
3018  */
3019 static int kvm_vm_ioctl_get_dirty_log_hv(struct kvm *kvm,
3020                                          struct kvm_dirty_log *log)
3021 {
3022         struct kvm_memslots *slots;
3023         struct kvm_memory_slot *memslot;
3024         int i, r;
3025         unsigned long n;
3026         unsigned long *buf;
3027         struct kvm_vcpu *vcpu;
3028
3029         mutex_lock(&kvm->slots_lock);
3030
3031         r = -EINVAL;
3032         if (log->slot >= KVM_USER_MEM_SLOTS)
3033                 goto out;
3034
3035         slots = kvm_memslots(kvm);
3036         memslot = id_to_memslot(slots, log->slot);
3037         r = -ENOENT;
3038         if (!memslot->dirty_bitmap)
3039                 goto out;
3040
3041         /*
3042          * Use second half of bitmap area because radix accumulates
3043          * bits in the first half.
3044          */
3045         n = kvm_dirty_bitmap_bytes(memslot);
3046         buf = memslot->dirty_bitmap + n / sizeof(long);
3047         memset(buf, 0, n);
3048
3049         if (kvm_is_radix(kvm))
3050                 r = kvmppc_hv_get_dirty_log_radix(kvm, memslot, buf);
3051         else
3052                 r = kvmppc_hv_get_dirty_log_hpt(kvm, memslot, buf);
3053         if (r)
3054                 goto out;
3055
3056         /* Harvest dirty bits from VPA and DTL updates */
3057         /* Note: we never modify the SLB shadow buffer areas */
3058         kvm_for_each_vcpu(i, vcpu, kvm) {
3059                 spin_lock(&vcpu->arch.vpa_update_lock);
3060                 kvmppc_harvest_vpa_dirty(&vcpu->arch.vpa, memslot, buf);
3061                 kvmppc_harvest_vpa_dirty(&vcpu->arch.dtl, memslot, buf);
3062                 spin_unlock(&vcpu->arch.vpa_update_lock);
3063         }
3064
3065         r = -EFAULT;
3066         if (copy_to_user(log->dirty_bitmap, buf, n))
3067                 goto out;
3068
3069         r = 0;
3070 out:
3071         mutex_unlock(&kvm->slots_lock);
3072         return r;
3073 }
3074
3075 static void kvmppc_core_free_memslot_hv(struct kvm_memory_slot *free,
3076                                         struct kvm_memory_slot *dont)
3077 {
3078         if (!dont || free->arch.rmap != dont->arch.rmap) {
3079                 vfree(free->arch.rmap);
3080                 free->arch.rmap = NULL;
3081         }
3082 }
3083
3084 static int kvmppc_core_create_memslot_hv(struct kvm_memory_slot *slot,
3085                                          unsigned long npages)
3086 {
3087         /*
3088          * For now, if radix_enabled() then we only support radix guests,
3089          * and in that case we don't need the rmap array.
3090          */
3091         if (radix_enabled()) {
3092                 slot->arch.rmap = NULL;
3093                 return 0;
3094         }
3095
3096         slot->arch.rmap = vzalloc(npages * sizeof(*slot->arch.rmap));
3097         if (!slot->arch.rmap)
3098                 return -ENOMEM;
3099
3100         return 0;
3101 }
3102
3103 static int kvmppc_core_prepare_memory_region_hv(struct kvm *kvm,
3104                                         struct kvm_memory_slot *memslot,
3105                                         const struct kvm_userspace_memory_region *mem)
3106 {
3107         return 0;
3108 }
3109
3110 static void kvmppc_core_commit_memory_region_hv(struct kvm *kvm,
3111                                 const struct kvm_userspace_memory_region *mem,
3112                                 const struct kvm_memory_slot *old,
3113                                 const struct kvm_memory_slot *new)
3114 {
3115         unsigned long npages = mem->memory_size >> PAGE_SHIFT;
3116         struct kvm_memslots *slots;
3117         struct kvm_memory_slot *memslot;
3118
3119         /*
3120          * If we are making a new memslot, it might make
3121          * some address that was previously cached as emulated
3122          * MMIO be no longer emulated MMIO, so invalidate
3123          * all the caches of emulated MMIO translations.
3124          */
3125         if (npages)
3126                 atomic64_inc(&kvm->arch.mmio_update);
3127
3128         if (npages && old->npages && !kvm_is_radix(kvm)) {
3129                 /*
3130                  * If modifying a memslot, reset all the rmap dirty bits.
3131                  * If this is a new memslot, we don't need to do anything
3132                  * since the rmap array starts out as all zeroes,
3133                  * i.e. no pages are dirty.
3134                  */
3135                 slots = kvm_memslots(kvm);
3136                 memslot = id_to_memslot(slots, mem->slot);
3137                 kvmppc_hv_get_dirty_log_hpt(kvm, memslot, NULL);
3138         }
3139 }
3140
3141 /*
3142  * Update LPCR values in kvm->arch and in vcores.
3143  * Caller must hold kvm->lock.
3144  */
3145 void kvmppc_update_lpcr(struct kvm *kvm, unsigned long lpcr, unsigned long mask)
3146 {
3147         long int i;
3148         u32 cores_done = 0;
3149
3150         if ((kvm->arch.lpcr & mask) == lpcr)
3151                 return;
3152
3153         kvm->arch.lpcr = (kvm->arch.lpcr & ~mask) | lpcr;
3154
3155         for (i = 0; i < KVM_MAX_VCORES; ++i) {
3156                 struct kvmppc_vcore *vc = kvm->arch.vcores[i];
3157                 if (!vc)
3158                         continue;
3159                 spin_lock(&vc->lock);
3160                 vc->lpcr = (vc->lpcr & ~mask) | lpcr;
3161                 spin_unlock(&vc->lock);
3162                 if (++cores_done >= kvm->arch.online_vcores)
3163                         break;
3164         }
3165 }
3166
3167 static void kvmppc_mmu_destroy_hv(struct kvm_vcpu *vcpu)
3168 {
3169         return;
3170 }
3171
3172 static void kvmppc_setup_partition_table(struct kvm *kvm)
3173 {
3174         unsigned long dw0, dw1;
3175
3176         if (!kvm_is_radix(kvm)) {
3177                 /* PS field - page size for VRMA */
3178                 dw0 = ((kvm->arch.vrma_slb_v & SLB_VSID_L) >> 1) |
3179                         ((kvm->arch.vrma_slb_v & SLB_VSID_LP) << 1);
3180                 /* HTABSIZE and HTABORG fields */
3181                 dw0 |= kvm->arch.sdr1;
3182
3183                 /* Second dword as set by userspace */
3184                 dw1 = kvm->arch.process_table;
3185         } else {
3186                 dw0 = PATB_HR | radix__get_tree_size() |
3187                         __pa(kvm->arch.pgtable) | RADIX_PGD_INDEX_SIZE;
3188                 dw1 = PATB_GR | kvm->arch.process_table;
3189         }
3190
3191         mmu_partition_table_set_entry(kvm->arch.lpid, dw0, dw1);
3192 }
3193
3194 static int kvmppc_hv_setup_htab_rma(struct kvm_vcpu *vcpu)
3195 {
3196         int err = 0;
3197         struct kvm *kvm = vcpu->kvm;
3198         unsigned long hva;
3199         struct kvm_memory_slot *memslot;
3200         struct vm_area_struct *vma;
3201         unsigned long lpcr = 0, senc;
3202         unsigned long psize, porder;
3203         int srcu_idx;
3204
3205         mutex_lock(&kvm->lock);
3206         if (kvm->arch.hpte_setup_done)
3207                 goto out;       /* another vcpu beat us to it */
3208
3209         /* Allocate hashed page table (if not done already) and reset it */
3210         if (!kvm->arch.hpt.virt) {
3211                 int order = KVM_DEFAULT_HPT_ORDER;
3212                 struct kvm_hpt_info info;
3213
3214                 err = kvmppc_allocate_hpt(&info, order);
3215                 /* If we get here, it means userspace didn't specify a
3216                  * size explicitly.  So, try successively smaller
3217                  * sizes if the default failed. */
3218                 while ((err == -ENOMEM) && --order >= PPC_MIN_HPT_ORDER)
3219                         err  = kvmppc_allocate_hpt(&info, order);
3220
3221                 if (err < 0) {
3222                         pr_err("KVM: Couldn't alloc HPT\n");
3223                         goto out;
3224                 }
3225
3226                 kvmppc_set_hpt(kvm, &info);
3227         }
3228
3229         /* Look up the memslot for guest physical address 0 */
3230         srcu_idx = srcu_read_lock(&kvm->srcu);
3231         memslot = gfn_to_memslot(kvm, 0);
3232
3233         /* We must have some memory at 0 by now */
3234         err = -EINVAL;
3235         if (!memslot || (memslot->flags & KVM_MEMSLOT_INVALID))
3236                 goto out_srcu;
3237
3238         /* Look up the VMA for the start of this memory slot */
3239         hva = memslot->userspace_addr;
3240         down_read(&current->mm->mmap_sem);
3241         vma = find_vma(current->mm, hva);
3242         if (!vma || vma->vm_start > hva || (vma->vm_flags & VM_IO))
3243                 goto up_out;
3244
3245         psize = vma_kernel_pagesize(vma);
3246         porder = __ilog2(psize);
3247
3248         up_read(&current->mm->mmap_sem);
3249
3250         /* We can handle 4k, 64k or 16M pages in the VRMA */
3251         err = -EINVAL;
3252         if (!(psize == 0x1000 || psize == 0x10000 ||
3253               psize == 0x1000000))
3254                 goto out_srcu;
3255
3256         senc = slb_pgsize_encoding(psize);
3257         kvm->arch.vrma_slb_v = senc | SLB_VSID_B_1T |
3258                 (VRMA_VSID << SLB_VSID_SHIFT_1T);
3259         /* Create HPTEs in the hash page table for the VRMA */
3260         kvmppc_map_vrma(vcpu, memslot, porder);
3261
3262         /* Update VRMASD field in the LPCR */
3263         if (!cpu_has_feature(CPU_FTR_ARCH_300)) {
3264                 /* the -4 is to account for senc values starting at 0x10 */
3265                 lpcr = senc << (LPCR_VRMASD_SH - 4);
3266                 kvmppc_update_lpcr(kvm, lpcr, LPCR_VRMASD);
3267         } else {
3268                 kvmppc_setup_partition_table(kvm);
3269         }
3270
3271         /* Order updates to kvm->arch.lpcr etc. vs. hpte_setup_done */
3272         smp_wmb();
3273         kvm->arch.hpte_setup_done = 1;
3274         err = 0;
3275  out_srcu:
3276         srcu_read_unlock(&kvm->srcu, srcu_idx);
3277  out:
3278         mutex_unlock(&kvm->lock);
3279         return err;
3280
3281  up_out:
3282         up_read(&current->mm->mmap_sem);
3283         goto out_srcu;
3284 }
3285
3286 #ifdef CONFIG_KVM_XICS
3287 /*
3288  * Allocate a per-core structure for managing state about which cores are
3289  * running in the host versus the guest and for exchanging data between
3290  * real mode KVM and CPU running in the host.
3291  * This is only done for the first VM.
3292  * The allocated structure stays even if all VMs have stopped.
3293  * It is only freed when the kvm-hv module is unloaded.
3294  * It's OK for this routine to fail, we just don't support host
3295  * core operations like redirecting H_IPI wakeups.
3296  */
3297 void kvmppc_alloc_host_rm_ops(void)
3298 {
3299         struct kvmppc_host_rm_ops *ops;
3300         unsigned long l_ops;
3301         int cpu, core;
3302         int size;
3303
3304         /* Not the first time here ? */
3305         if (kvmppc_host_rm_ops_hv != NULL)
3306                 return;
3307
3308         ops = kzalloc(sizeof(struct kvmppc_host_rm_ops), GFP_KERNEL);
3309         if (!ops)
3310                 return;
3311
3312         size = cpu_nr_cores() * sizeof(struct kvmppc_host_rm_core);
3313         ops->rm_core = kzalloc(size, GFP_KERNEL);
3314
3315         if (!ops->rm_core) {
3316                 kfree(ops);
3317                 return;
3318         }
3319
3320         get_online_cpus();
3321
3322         for (cpu = 0; cpu < nr_cpu_ids; cpu += threads_per_core) {
3323                 if (!cpu_online(cpu))
3324                         continue;
3325
3326                 core = cpu >> threads_shift;
3327                 ops->rm_core[core].rm_state.in_host = 1;
3328         }
3329
3330         ops->vcpu_kick = kvmppc_fast_vcpu_kick_hv;
3331
3332         /*
3333          * Make the contents of the kvmppc_host_rm_ops structure visible
3334          * to other CPUs before we assign it to the global variable.
3335          * Do an atomic assignment (no locks used here), but if someone
3336          * beats us to it, just free our copy and return.
3337          */
3338         smp_wmb();
3339         l_ops = (unsigned long) ops;
3340
3341         if (cmpxchg64((unsigned long *)&kvmppc_host_rm_ops_hv, 0, l_ops)) {
3342                 put_online_cpus();
3343                 kfree(ops->rm_core);
3344                 kfree(ops);
3345                 return;
3346         }
3347
3348         cpuhp_setup_state_nocalls(CPUHP_KVM_PPC_BOOK3S_PREPARE,
3349                                   "ppc/kvm_book3s:prepare",
3350                                   kvmppc_set_host_core,
3351                                   kvmppc_clear_host_core);
3352         put_online_cpus();
3353 }
3354
3355 void kvmppc_free_host_rm_ops(void)
3356 {
3357         if (kvmppc_host_rm_ops_hv) {
3358                 cpuhp_remove_state_nocalls(CPUHP_KVM_PPC_BOOK3S_PREPARE);
3359                 kfree(kvmppc_host_rm_ops_hv->rm_core);
3360                 kfree(kvmppc_host_rm_ops_hv);
3361                 kvmppc_host_rm_ops_hv = NULL;
3362         }
3363 }
3364 #endif
3365
3366 static int kvmppc_core_init_vm_hv(struct kvm *kvm)
3367 {
3368         unsigned long lpcr, lpid;
3369         char buf[32];
3370         int ret;
3371
3372         /* Allocate the guest's logical partition ID */
3373
3374         lpid = kvmppc_alloc_lpid();
3375         if ((long)lpid < 0)
3376                 return -ENOMEM;
3377         kvm->arch.lpid = lpid;
3378
3379         kvmppc_alloc_host_rm_ops();
3380
3381         /*
3382          * Since we don't flush the TLB when tearing down a VM,
3383          * and this lpid might have previously been used,
3384          * make sure we flush on each core before running the new VM.
3385          * On POWER9, the tlbie in mmu_partition_table_set_entry()
3386          * does this flush for us.
3387          */
3388         if (!cpu_has_feature(CPU_FTR_ARCH_300))
3389                 cpumask_setall(&kvm->arch.need_tlb_flush);
3390
3391         /* Start out with the default set of hcalls enabled */
3392         memcpy(kvm->arch.enabled_hcalls, default_enabled_hcalls,
3393                sizeof(kvm->arch.enabled_hcalls));
3394
3395         if (!cpu_has_feature(CPU_FTR_ARCH_300))
3396                 kvm->arch.host_sdr1 = mfspr(SPRN_SDR1);
3397
3398         /* Init LPCR for virtual RMA mode */
3399         kvm->arch.host_lpid = mfspr(SPRN_LPID);
3400         kvm->arch.host_lpcr = lpcr = mfspr(SPRN_LPCR);
3401         lpcr &= LPCR_PECE | LPCR_LPES;
3402         lpcr |= (4UL << LPCR_DPFD_SH) | LPCR_HDICE |
3403                 LPCR_VPM0 | LPCR_VPM1;
3404         kvm->arch.vrma_slb_v = SLB_VSID_B_1T |
3405                 (VRMA_VSID << SLB_VSID_SHIFT_1T);
3406         /* On POWER8 turn on online bit to enable PURR/SPURR */
3407         if (cpu_has_feature(CPU_FTR_ARCH_207S))
3408                 lpcr |= LPCR_ONL;
3409         /*
3410          * On POWER9, VPM0 bit is reserved (VPM0=1 behaviour is assumed)
3411          * Set HVICE bit to enable hypervisor virtualization interrupts.
3412          * Set HEIC to prevent OS interrupts to go to hypervisor (should
3413          * be unnecessary but better safe than sorry in case we re-enable
3414          * EE in HV mode with this LPCR still set)
3415          */
3416         if (cpu_has_feature(CPU_FTR_ARCH_300)) {
3417                 lpcr &= ~LPCR_VPM0;
3418                 lpcr |= LPCR_HVICE | LPCR_HEIC;
3419
3420                 /*
3421                  * If xive is enabled, we route 0x500 interrupts directly
3422                  * to the guest.
3423                  */
3424                 if (xive_enabled())
3425                         lpcr |= LPCR_LPES;
3426         }
3427
3428         /*
3429          * For now, if the host uses radix, the guest must be radix.
3430          */
3431         if (radix_enabled()) {
3432                 kvm->arch.radix = 1;
3433                 lpcr &= ~LPCR_VPM1;
3434                 lpcr |= LPCR_UPRT | LPCR_GTSE | LPCR_HR;
3435                 ret = kvmppc_init_vm_radix(kvm);
3436                 if (ret) {
3437                         kvmppc_free_lpid(kvm->arch.lpid);
3438                         return ret;
3439                 }
3440                 kvmppc_setup_partition_table(kvm);
3441         }
3442
3443         kvm->arch.lpcr = lpcr;
3444
3445         /* Initialization for future HPT resizes */
3446         kvm->arch.resize_hpt = NULL;
3447
3448         /*
3449          * Work out how many sets the TLB has, for the use of
3450          * the TLB invalidation loop in book3s_hv_rmhandlers.S.
3451          */
3452         if (kvm_is_radix(kvm))
3453                 kvm->arch.tlb_sets = POWER9_TLB_SETS_RADIX;     /* 128 */
3454         else if (cpu_has_feature(CPU_FTR_ARCH_300))
3455                 kvm->arch.tlb_sets = POWER9_TLB_SETS_HASH;      /* 256 */
3456         else if (cpu_has_feature(CPU_FTR_ARCH_207S))
3457                 kvm->arch.tlb_sets = POWER8_TLB_SETS;           /* 512 */
3458         else
3459                 kvm->arch.tlb_sets = POWER7_TLB_SETS;           /* 128 */
3460
3461         /*
3462          * Track that we now have a HV mode VM active. This blocks secondary
3463          * CPU threads from coming online.
3464          * On POWER9, we only need to do this for HPT guests on a radix
3465          * host, which is not yet supported.
3466          */
3467         if (!cpu_has_feature(CPU_FTR_ARCH_300))
3468                 kvm_hv_vm_activated();
3469
3470         /*
3471          * Create a debugfs directory for the VM
3472          */
3473         snprintf(buf, sizeof(buf), "vm%d", current->pid);
3474         kvm->arch.debugfs_dir = debugfs_create_dir(buf, kvm_debugfs_dir);
3475         if (!IS_ERR_OR_NULL(kvm->arch.debugfs_dir))
3476                 kvmppc_mmu_debugfs_init(kvm);
3477
3478         return 0;
3479 }
3480
3481 static void kvmppc_free_vcores(struct kvm *kvm)
3482 {
3483         long int i;
3484
3485         for (i = 0; i < KVM_MAX_VCORES; ++i)
3486                 kfree(kvm->arch.vcores[i]);
3487         kvm->arch.online_vcores = 0;
3488 }
3489
3490 static void kvmppc_core_destroy_vm_hv(struct kvm *kvm)
3491 {
3492         debugfs_remove_recursive(kvm->arch.debugfs_dir);
3493
3494         if (!cpu_has_feature(CPU_FTR_ARCH_300))
3495                 kvm_hv_vm_deactivated();
3496
3497         kvmppc_free_vcores(kvm);
3498
3499         kvmppc_free_lpid(kvm->arch.lpid);
3500
3501         if (kvm_is_radix(kvm))
3502                 kvmppc_free_radix(kvm);
3503         else
3504                 kvmppc_free_hpt(&kvm->arch.hpt);
3505
3506         kvmppc_free_pimap(kvm);
3507 }
3508
3509 /* We don't need to emulate any privileged instructions or dcbz */
3510 static int kvmppc_core_emulate_op_hv(struct kvm_run *run, struct kvm_vcpu *vcpu,
3511                                      unsigned int inst, int *advance)
3512 {
3513         return EMULATE_FAIL;
3514 }
3515
3516 static int kvmppc_core_emulate_mtspr_hv(struct kvm_vcpu *vcpu, int sprn,
3517                                         ulong spr_val)
3518 {
3519         return EMULATE_FAIL;
3520 }
3521
3522 static int kvmppc_core_emulate_mfspr_hv(struct kvm_vcpu *vcpu, int sprn,
3523                                         ulong *spr_val)
3524 {
3525         return EMULATE_FAIL;
3526 }
3527
3528 static int kvmppc_core_check_processor_compat_hv(void)
3529 {
3530         if (!cpu_has_feature(CPU_FTR_HVMODE) ||
3531             !cpu_has_feature(CPU_FTR_ARCH_206))
3532                 return -EIO;
3533
3534         return 0;
3535 }
3536
3537 #ifdef CONFIG_KVM_XICS
3538
3539 void kvmppc_free_pimap(struct kvm *kvm)
3540 {
3541         kfree(kvm->arch.pimap);
3542 }
3543
3544 static struct kvmppc_passthru_irqmap *kvmppc_alloc_pimap(void)
3545 {
3546         return kzalloc(sizeof(struct kvmppc_passthru_irqmap), GFP_KERNEL);
3547 }
3548
3549 static int kvmppc_set_passthru_irq(struct kvm *kvm, int host_irq, int guest_gsi)
3550 {
3551         struct irq_desc *desc;
3552         struct kvmppc_irq_map *irq_map;
3553         struct kvmppc_passthru_irqmap *pimap;
3554         struct irq_chip *chip;
3555         int i, rc = 0;
3556
3557         if (!kvm_irq_bypass)
3558                 return 1;
3559
3560         desc = irq_to_desc(host_irq);
3561         if (!desc)
3562                 return -EIO;
3563
3564         mutex_lock(&kvm->lock);
3565
3566         pimap = kvm->arch.pimap;
3567         if (pimap == NULL) {
3568                 /* First call, allocate structure to hold IRQ map */
3569                 pimap = kvmppc_alloc_pimap();
3570                 if (pimap == NULL) {
3571                         mutex_unlock(&kvm->lock);
3572                         return -ENOMEM;
3573                 }
3574                 kvm->arch.pimap = pimap;
3575         }
3576
3577         /*
3578          * For now, we only support interrupts for which the EOI operation
3579          * is an OPAL call followed by a write to XIRR, since that's
3580          * what our real-mode EOI code does, or a XIVE interrupt
3581          */
3582         chip = irq_data_get_irq_chip(&desc->irq_data);
3583         if (!chip || !(is_pnv_opal_msi(chip) || is_xive_irq(chip))) {
3584                 pr_warn("kvmppc_set_passthru_irq_hv: Could not assign IRQ map for (%d,%d)\n",
3585                         host_irq, guest_gsi);
3586                 mutex_unlock(&kvm->lock);
3587                 return -ENOENT;
3588         }
3589
3590         /*
3591          * See if we already have an entry for this guest IRQ number.
3592          * If it's mapped to a hardware IRQ number, that's an error,
3593          * otherwise re-use this entry.
3594          */
3595         for (i = 0; i < pimap->n_mapped; i++) {
3596                 if (guest_gsi == pimap->mapped[i].v_hwirq) {
3597                         if (pimap->mapped[i].r_hwirq) {
3598                                 mutex_unlock(&kvm->lock);
3599                                 return -EINVAL;
3600                         }
3601                         break;
3602                 }
3603         }
3604
3605         if (i == KVMPPC_PIRQ_MAPPED) {
3606                 mutex_unlock(&kvm->lock);
3607                 return -EAGAIN;         /* table is full */
3608         }
3609
3610         irq_map = &pimap->mapped[i];
3611
3612         irq_map->v_hwirq = guest_gsi;
3613         irq_map->desc = desc;
3614
3615         /*
3616          * Order the above two stores before the next to serialize with
3617          * the KVM real mode handler.
3618          */
3619         smp_wmb();
3620         irq_map->r_hwirq = desc->irq_data.hwirq;
3621
3622         if (i == pimap->n_mapped)
3623                 pimap->n_mapped++;
3624
3625         if (xive_enabled())
3626                 rc = kvmppc_xive_set_mapped(kvm, guest_gsi, desc);
3627         else
3628                 kvmppc_xics_set_mapped(kvm, guest_gsi, desc->irq_data.hwirq);
3629         if (rc)
3630                 irq_map->r_hwirq = 0;
3631
3632         mutex_unlock(&kvm->lock);
3633
3634         return 0;
3635 }
3636
3637 static int kvmppc_clr_passthru_irq(struct kvm *kvm, int host_irq, int guest_gsi)
3638 {
3639         struct irq_desc *desc;
3640         struct kvmppc_passthru_irqmap *pimap;
3641         int i, rc = 0;
3642
3643         if (!kvm_irq_bypass)
3644                 return 0;
3645
3646         desc = irq_to_desc(host_irq);
3647         if (!desc)
3648                 return -EIO;
3649
3650         mutex_lock(&kvm->lock);
3651         if (!kvm->arch.pimap)
3652                 goto unlock;
3653
3654         pimap = kvm->arch.pimap;
3655
3656         for (i = 0; i < pimap->n_mapped; i++) {
3657                 if (guest_gsi == pimap->mapped[i].v_hwirq)
3658                         break;
3659         }
3660
3661         if (i == pimap->n_mapped) {
3662                 mutex_unlock(&kvm->lock);
3663                 return -ENODEV;
3664         }
3665
3666         if (xive_enabled())
3667                 rc = kvmppc_xive_clr_mapped(kvm, guest_gsi, pimap->mapped[i].desc);
3668         else
3669                 kvmppc_xics_clr_mapped(kvm, guest_gsi, pimap->mapped[i].r_hwirq);
3670
3671         /* invalidate the entry (what do do on error from the above ?) */
3672         pimap->mapped[i].r_hwirq = 0;
3673
3674         /*
3675          * We don't free this structure even when the count goes to
3676          * zero. The structure is freed when we destroy the VM.
3677          */
3678  unlock:
3679         mutex_unlock(&kvm->lock);
3680         return rc;
3681 }
3682
3683 static int kvmppc_irq_bypass_add_producer_hv(struct irq_bypass_consumer *cons,
3684                                              struct irq_bypass_producer *prod)
3685 {
3686         int ret = 0;
3687         struct kvm_kernel_irqfd *irqfd =
3688                 container_of(cons, struct kvm_kernel_irqfd, consumer);
3689
3690         irqfd->producer = prod;
3691
3692         ret = kvmppc_set_passthru_irq(irqfd->kvm, prod->irq, irqfd->gsi);
3693         if (ret)
3694                 pr_info("kvmppc_set_passthru_irq (irq %d, gsi %d) fails: %d\n",
3695                         prod->irq, irqfd->gsi, ret);
3696
3697         return ret;
3698 }
3699
3700 static void kvmppc_irq_bypass_del_producer_hv(struct irq_bypass_consumer *cons,
3701                                               struct irq_bypass_producer *prod)
3702 {
3703         int ret;
3704         struct kvm_kernel_irqfd *irqfd =
3705                 container_of(cons, struct kvm_kernel_irqfd, consumer);
3706
3707         irqfd->producer = NULL;
3708
3709         /*
3710          * When producer of consumer is unregistered, we change back to
3711          * default external interrupt handling mode - KVM real mode
3712          * will switch back to host.
3713          */
3714         ret = kvmppc_clr_passthru_irq(irqfd->kvm, prod->irq, irqfd->gsi);
3715         if (ret)
3716                 pr_warn("kvmppc_clr_passthru_irq (irq %d, gsi %d) fails: %d\n",
3717                         prod->irq, irqfd->gsi, ret);
3718 }
3719 #endif
3720
3721 static long kvm_arch_vm_ioctl_hv(struct file *filp,
3722                                  unsigned int ioctl, unsigned long arg)
3723 {
3724         struct kvm *kvm __maybe_unused = filp->private_data;
3725         void __user *argp = (void __user *)arg;
3726         long r;
3727
3728         switch (ioctl) {
3729
3730         case KVM_PPC_ALLOCATE_HTAB: {
3731                 u32 htab_order;
3732
3733                 r = -EFAULT;
3734                 if (get_user(htab_order, (u32 __user *)argp))
3735                         break;
3736                 r = kvmppc_alloc_reset_hpt(kvm, htab_order);
3737                 if (r)
3738                         break;
3739                 r = 0;
3740                 break;
3741         }
3742
3743         case KVM_PPC_GET_HTAB_FD: {
3744                 struct kvm_get_htab_fd ghf;
3745
3746                 r = -EFAULT;
3747                 if (copy_from_user(&ghf, argp, sizeof(ghf)))
3748                         break;
3749                 r = kvm_vm_ioctl_get_htab_fd(kvm, &ghf);
3750                 break;
3751         }
3752
3753         case KVM_PPC_RESIZE_HPT_PREPARE: {
3754                 struct kvm_ppc_resize_hpt rhpt;
3755
3756                 r = -EFAULT;
3757                 if (copy_from_user(&rhpt, argp, sizeof(rhpt)))
3758                         break;
3759
3760                 r = kvm_vm_ioctl_resize_hpt_prepare(kvm, &rhpt);
3761                 break;
3762         }
3763
3764         case KVM_PPC_RESIZE_HPT_COMMIT: {
3765                 struct kvm_ppc_resize_hpt rhpt;
3766
3767                 r = -EFAULT;
3768                 if (copy_from_user(&rhpt, argp, sizeof(rhpt)))
3769                         break;
3770
3771                 r = kvm_vm_ioctl_resize_hpt_commit(kvm, &rhpt);
3772                 break;
3773         }
3774
3775         default:
3776                 r = -ENOTTY;
3777         }
3778
3779         return r;
3780 }
3781
3782 /*
3783  * List of hcall numbers to enable by default.
3784  * For compatibility with old userspace, we enable by default
3785  * all hcalls that were implemented before the hcall-enabling
3786  * facility was added.  Note this list should not include H_RTAS.
3787  */
3788 static unsigned int default_hcall_list[] = {
3789         H_REMOVE,
3790         H_ENTER,
3791         H_READ,
3792         H_PROTECT,
3793         H_BULK_REMOVE,
3794         H_GET_TCE,
3795         H_PUT_TCE,
3796         H_SET_DABR,
3797         H_SET_XDABR,
3798         H_CEDE,
3799         H_PROD,
3800         H_CONFER,
3801         H_REGISTER_VPA,
3802 #ifdef CONFIG_KVM_XICS
3803         H_EOI,
3804         H_CPPR,
3805         H_IPI,
3806         H_IPOLL,
3807         H_XIRR,
3808         H_XIRR_X,
3809 #endif
3810         0
3811 };
3812
3813 static void init_default_hcalls(void)
3814 {
3815         int i;
3816         unsigned int hcall;
3817
3818         for (i = 0; default_hcall_list[i]; ++i) {
3819                 hcall = default_hcall_list[i];
3820                 WARN_ON(!kvmppc_hcall_impl_hv(hcall));
3821                 __set_bit(hcall / 4, default_enabled_hcalls);
3822         }
3823 }
3824
3825 static int kvmhv_configure_mmu(struct kvm *kvm, struct kvm_ppc_mmuv3_cfg *cfg)
3826 {
3827         unsigned long lpcr;
3828         int radix;
3829
3830         /* If not on a POWER9, reject it */
3831         if (!cpu_has_feature(CPU_FTR_ARCH_300))
3832                 return -ENODEV;
3833
3834         /* If any unknown flags set, reject it */
3835         if (cfg->flags & ~(KVM_PPC_MMUV3_RADIX | KVM_PPC_MMUV3_GTSE))
3836                 return -EINVAL;
3837
3838         /* We can't change a guest to/from radix yet */
3839         radix = !!(cfg->flags & KVM_PPC_MMUV3_RADIX);
3840         if (radix != kvm_is_radix(kvm))
3841                 return -EINVAL;
3842
3843         /* GR (guest radix) bit in process_table field must match */
3844         if (!!(cfg->process_table & PATB_GR) != radix)
3845                 return -EINVAL;
3846
3847         /* Process table size field must be reasonable, i.e. <= 24 */
3848         if ((cfg->process_table & PRTS_MASK) > 24)
3849                 return -EINVAL;
3850
3851         kvm->arch.process_table = cfg->process_table;
3852         kvmppc_setup_partition_table(kvm);
3853
3854         lpcr = (cfg->flags & KVM_PPC_MMUV3_GTSE) ? LPCR_GTSE : 0;
3855         kvmppc_update_lpcr(kvm, lpcr, LPCR_GTSE);
3856
3857         return 0;
3858 }
3859
3860 static struct kvmppc_ops kvm_ops_hv = {
3861         .get_sregs = kvm_arch_vcpu_ioctl_get_sregs_hv,
3862         .set_sregs = kvm_arch_vcpu_ioctl_set_sregs_hv,
3863         .get_one_reg = kvmppc_get_one_reg_hv,
3864         .set_one_reg = kvmppc_set_one_reg_hv,
3865         .vcpu_load   = kvmppc_core_vcpu_load_hv,
3866         .vcpu_put    = kvmppc_core_vcpu_put_hv,
3867         .set_msr     = kvmppc_set_msr_hv,
3868         .vcpu_run    = kvmppc_vcpu_run_hv,
3869         .vcpu_create = kvmppc_core_vcpu_create_hv,
3870         .vcpu_free   = kvmppc_core_vcpu_free_hv,
3871         .check_requests = kvmppc_core_check_requests_hv,
3872         .get_dirty_log  = kvm_vm_ioctl_get_dirty_log_hv,
3873         .flush_memslot  = kvmppc_core_flush_memslot_hv,
3874         .prepare_memory_region = kvmppc_core_prepare_memory_region_hv,
3875         .commit_memory_region  = kvmppc_core_commit_memory_region_hv,
3876         .unmap_hva = kvm_unmap_hva_hv,
3877         .unmap_hva_range = kvm_unmap_hva_range_hv,
3878         .age_hva  = kvm_age_hva_hv,
3879         .test_age_hva = kvm_test_age_hva_hv,
3880         .set_spte_hva = kvm_set_spte_hva_hv,
3881         .mmu_destroy  = kvmppc_mmu_destroy_hv,
3882         .free_memslot = kvmppc_core_free_memslot_hv,
3883         .create_memslot = kvmppc_core_create_memslot_hv,
3884         .init_vm =  kvmppc_core_init_vm_hv,
3885         .destroy_vm = kvmppc_core_destroy_vm_hv,
3886         .get_smmu_info = kvm_vm_ioctl_get_smmu_info_hv,
3887         .emulate_op = kvmppc_core_emulate_op_hv,
3888         .emulate_mtspr = kvmppc_core_emulate_mtspr_hv,
3889         .emulate_mfspr = kvmppc_core_emulate_mfspr_hv,
3890         .fast_vcpu_kick = kvmppc_fast_vcpu_kick_hv,
3891         .arch_vm_ioctl  = kvm_arch_vm_ioctl_hv,
3892         .hcall_implemented = kvmppc_hcall_impl_hv,
3893 #ifdef CONFIG_KVM_XICS
3894         .irq_bypass_add_producer = kvmppc_irq_bypass_add_producer_hv,
3895         .irq_bypass_del_producer = kvmppc_irq_bypass_del_producer_hv,
3896 #endif
3897         .configure_mmu = kvmhv_configure_mmu,
3898         .get_rmmu_info = kvmhv_get_rmmu_info,
3899 };
3900
3901 static int kvm_init_subcore_bitmap(void)
3902 {
3903         int i, j;
3904         int nr_cores = cpu_nr_cores();
3905         struct sibling_subcore_state *sibling_subcore_state;
3906
3907         for (i = 0; i < nr_cores; i++) {
3908                 int first_cpu = i * threads_per_core;
3909                 int node = cpu_to_node(first_cpu);
3910
3911                 /* Ignore if it is already allocated. */
3912                 if (paca[first_cpu].sibling_subcore_state)
3913                         continue;
3914
3915                 sibling_subcore_state =
3916                         kmalloc_node(sizeof(struct sibling_subcore_state),
3917                                                         GFP_KERNEL, node);
3918                 if (!sibling_subcore_state)
3919                         return -ENOMEM;
3920
3921                 memset(sibling_subcore_state, 0,
3922                                 sizeof(struct sibling_subcore_state));
3923
3924                 for (j = 0; j < threads_per_core; j++) {
3925                         int cpu = first_cpu + j;
3926
3927                         paca[cpu].sibling_subcore_state = sibling_subcore_state;
3928                 }
3929         }
3930         return 0;
3931 }
3932
3933 static int kvmppc_radix_possible(void)
3934 {
3935         return cpu_has_feature(CPU_FTR_ARCH_300) && radix_enabled();
3936 }
3937
3938 static int kvmppc_book3s_init_hv(void)
3939 {
3940         int r;
3941         /*
3942          * FIXME!! Do we need to check on all cpus ?
3943          */
3944         r = kvmppc_core_check_processor_compat_hv();
3945         if (r < 0)
3946                 return -ENODEV;
3947
3948         r = kvm_init_subcore_bitmap();
3949         if (r)
3950                 return r;
3951
3952         /*
3953          * We need a way of accessing the XICS interrupt controller,
3954          * either directly, via paca[cpu].kvm_hstate.xics_phys, or
3955          * indirectly, via OPAL.
3956          */
3957 #ifdef CONFIG_SMP
3958         if (!xive_enabled() && !local_paca->kvm_hstate.xics_phys) {
3959                 struct device_node *np;
3960
3961                 np = of_find_compatible_node(NULL, NULL, "ibm,opal-intc");
3962                 if (!np) {
3963                         pr_err("KVM-HV: Cannot determine method for accessing XICS\n");
3964                         return -ENODEV;
3965                 }
3966         }
3967 #endif
3968
3969         kvm_ops_hv.owner = THIS_MODULE;
3970         kvmppc_hv_ops = &kvm_ops_hv;
3971
3972         init_default_hcalls();
3973
3974         init_vcore_lists();
3975
3976         r = kvmppc_mmu_hv_init();
3977         if (r)
3978                 return r;
3979
3980         if (kvmppc_radix_possible())
3981                 r = kvmppc_radix_init();
3982         return r;
3983 }
3984
3985 static void kvmppc_book3s_exit_hv(void)
3986 {
3987         kvmppc_free_host_rm_ops();
3988         if (kvmppc_radix_possible())
3989                 kvmppc_radix_exit();
3990         kvmppc_hv_ops = NULL;
3991 }
3992
3993 module_init(kvmppc_book3s_init_hv);
3994 module_exit(kvmppc_book3s_exit_hv);
3995 MODULE_LICENSE("GPL");
3996 MODULE_ALIAS_MISCDEV(KVM_MINOR);
3997 MODULE_ALIAS("devname:kvm");
3998